content_type
stringclasses 8
values | main_lang
stringclasses 7
values | message
stringlengths 1
50
| sha
stringlengths 40
40
| patch
stringlengths 52
962k
| file_count
int64 1
300
|
---|---|---|---|---|---|
Text | Text | add missing subtitle | f5e7fefa875887d94827dffea4b47f4cf4f3ed9a | <ide><path>guide/spanish/c/functions/index.md
<ide> Es posible que haya observado un problema similar con cosas como las declaracion
<ide>
<ide> Idealmente, siempre pasará a sus funciones como parámetros, pero es posible que no siempre pueda hacerlo. Escoger la mejor solución es tu trabajo como programador.
<ide>
<del>Recursion en c Cuando se llama a la función dentro de la misma función, se conoce como recursión en C. La función que llama a la misma función, se conoce como función recursiva.
<add>## Recursion en C
<add>Cuando se llama a la función dentro de la misma función, se conoce como recursión en C. La función que llama a la misma función, se conoce como función recursiva.
<ide> ```
<ide> int factorial (int n)
<ide> {
<ide> int factorial (int n)
<ide> * Las funciones toman parámetros con los que trabajar, si no toman nada, use `void` .
<ide> * `return` finaliza la función y devuelve un valor. Puedes tener varias en una función, pero tan pronto como presionas una, la función termina allí.
<ide> * Cuando pasa una variable a una función, tiene su propia copia para usar: cambiar algo en una función no lo hace fuera de la función.
<del>* Las variables declaradas dentro de una función solo son visibles dentro de esa función, a menos que se declaren estáticas.
<ide>\ No newline at end of file
<add>* Las variables declaradas dentro de una función solo son visibles dentro de esa función, a menos que se declaren estáticas. | 1 |
Javascript | Javascript | add crypto check to http2 tests | 1b719fe3d78e35a494151229b014ebed6a8383bf | <ide><path>test/parallel/test-http2-binding.js
<ide> // Flags: --expose-http2
<ide> 'use strict';
<ide>
<del>require('../common');
<add>const common = require('../common');
<add>if (!common.hasCrypto)
<add> common.skip('missing crypto');
<ide> const assert = require('assert');
<ide>
<ide> assert.doesNotThrow(() => process.binding('http2'));
<ide><path>test/parallel/test-http2-client-data-end.js
<ide> 'use strict';
<ide>
<ide> const common = require('../common');
<add>if (!common.hasCrypto)
<add> common.skip('missing crypto');
<ide> const assert = require('assert');
<ide> const http2 = require('http2');
<ide>
<ide><path>test/parallel/test-http2-client-destroy-before-connect.js
<ide> 'use strict';
<ide>
<ide> const common = require('../common');
<add>if (!common.hasCrypto)
<add> common.skip('missing crypto');
<ide> const h2 = require('http2');
<ide>
<ide> const server = h2.createServer();
<ide><path>test/parallel/test-http2-client-destroy-before-request.js
<ide> 'use strict';
<ide>
<ide> const common = require('../common');
<add>if (!common.hasCrypto)
<add> common.skip('missing crypto');
<ide> const assert = require('assert');
<ide> const h2 = require('http2');
<ide>
<ide><path>test/parallel/test-http2-client-destroy.js
<ide> 'use strict';
<ide>
<ide> const common = require('../common');
<add>if (!common.hasCrypto)
<add> common.skip('missing crypto');
<ide> const assert = require('assert');
<ide> const h2 = require('http2');
<ide>
<ide><path>test/parallel/test-http2-client-priority-before-connect.js
<ide> 'use strict';
<ide>
<ide> const common = require('../common');
<add>if (!common.hasCrypto)
<add> common.skip('missing crypto');
<ide> const h2 = require('http2');
<ide>
<ide> const server = h2.createServer();
<ide><path>test/parallel/test-http2-client-rststream-before-connect.js
<ide> 'use strict';
<ide>
<ide> const common = require('../common');
<add>if (!common.hasCrypto)
<add> common.skip('missing crypto');
<ide> const assert = require('assert');
<ide> const h2 = require('http2');
<ide>
<ide><path>test/parallel/test-http2-client-set-priority.js
<ide> 'use strict';
<ide>
<ide> const common = require('../common');
<add>if (!common.hasCrypto)
<add> common.skip('missing crypto');
<ide> const assert = require('assert');
<ide> const http2 = require('http2');
<ide>
<ide><path>test/parallel/test-http2-client-settings-before-connect.js
<ide> 'use strict';
<ide>
<ide> const common = require('../common');
<add>if (!common.hasCrypto)
<add> common.skip('missing crypto');
<ide> const assert = require('assert');
<ide> const h2 = require('http2');
<ide>
<ide><path>test/parallel/test-http2-client-shutdown-before-connect.js
<ide> 'use strict';
<ide>
<ide> const common = require('../common');
<add>if (!common.hasCrypto)
<add> common.skip('missing crypto');
<ide> const h2 = require('http2');
<ide>
<ide> const server = h2.createServer();
<ide><path>test/parallel/test-http2-client-socket-destroy.js
<ide> 'use strict';
<ide>
<ide> const common = require('../common');
<add>if (!common.hasCrypto)
<add> common.skip('missing crypto');
<ide> const h2 = require('http2');
<ide> const body =
<ide> '<html><head></head><body><h1>this is some data</h2></body></html>';
<ide><path>test/parallel/test-http2-client-stream-destroy-before-connect.js
<ide> 'use strict';
<ide>
<ide> const common = require('../common');
<add>if (!common.hasCrypto)
<add> common.skip('missing crypto');
<ide> const assert = require('assert');
<ide> const h2 = require('http2');
<ide> const NGHTTP2_INTERNAL_ERROR = h2.constants.NGHTTP2_INTERNAL_ERROR;
<ide><path>test/parallel/test-http2-client-unescaped-path.js
<ide> 'use strict';
<ide>
<ide> const common = require('../common');
<add>if (!common.hasCrypto)
<add> common.skip('missing crypto');
<ide> const http2 = require('http2');
<ide>
<ide> const server = http2.createServer();
<ide><path>test/parallel/test-http2-client-upload.js
<ide> // Verifies that uploading data from a client works
<ide>
<ide> const common = require('../common');
<add>if (!common.hasCrypto)
<add> common.skip('missing crypto');
<ide> const assert = require('assert');
<ide> const http2 = require('http2');
<ide> const fs = require('fs');
<ide><path>test/parallel/test-http2-client-write-before-connect.js
<ide> 'use strict';
<ide>
<ide> const common = require('../common');
<add>if (!common.hasCrypto)
<add> common.skip('missing crypto');
<ide> const assert = require('assert');
<ide> const h2 = require('http2');
<ide>
<ide><path>test/parallel/test-http2-compat-serverrequest-headers.js
<ide> 'use strict';
<ide>
<ide> const common = require('../common');
<add>if (!common.hasCrypto)
<add> common.skip('missing crypto');
<ide> const assert = require('assert');
<ide> const h2 = require('http2');
<ide>
<ide><path>test/parallel/test-http2-compat-serverrequest.js
<ide> 'use strict';
<ide>
<ide> const common = require('../common');
<add>if (!common.hasCrypto)
<add> common.skip('missing crypto');
<ide> const assert = require('assert');
<ide> const h2 = require('http2');
<ide> const net = require('net');
<ide><path>test/parallel/test-http2-compat-serverresponse-createpushresponse.js
<ide> 'use strict';
<ide>
<ide> const common = require('../common');
<add>if (!common.hasCrypto)
<add> common.skip('missing crypto');
<ide> const assert = require('assert');
<ide> const h2 = require('http2');
<ide>
<ide><path>test/parallel/test-http2-compat-serverresponse-end.js
<ide> // Flags: --expose-http2
<ide> 'use strict';
<ide>
<del>const { mustCall, mustNotCall } = require('../common');
<add>const { mustCall, mustNotCall, hasCrypto, skip } = require('../common');
<add>if (!hasCrypto)
<add> skip('missing crypto');
<ide> const { strictEqual } = require('assert');
<ide> const {
<ide> createServer,
<ide><path>test/parallel/test-http2-compat-serverresponse-finished.js
<ide> 'use strict';
<ide>
<ide> const common = require('../common');
<add>if (!common.hasCrypto)
<add> common.skip('missing crypto');
<ide> const assert = require('assert');
<ide> const h2 = require('http2');
<ide>
<ide><path>test/parallel/test-http2-compat-serverresponse-flushheaders.js
<ide> 'use strict';
<ide>
<ide> const common = require('../common');
<add>if (!common.hasCrypto)
<add> common.skip('missing crypto');
<ide> const assert = require('assert');
<ide> const h2 = require('http2');
<ide>
<ide><path>test/parallel/test-http2-compat-serverresponse-headers.js
<ide> 'use strict';
<ide>
<ide> const common = require('../common');
<add>if (!common.hasCrypto)
<add> common.skip('missing crypto');
<ide> const assert = require('assert');
<ide> const h2 = require('http2');
<ide>
<ide><path>test/parallel/test-http2-compat-serverresponse-statuscode.js
<ide> 'use strict';
<ide>
<ide> const common = require('../common');
<add>if (!common.hasCrypto)
<add> common.skip('missing crypto');
<ide> const assert = require('assert');
<ide> const h2 = require('http2');
<ide>
<ide><path>test/parallel/test-http2-compat-serverresponse-statusmessage-property.js
<ide> 'use strict';
<ide>
<ide> const common = require('../common');
<add>if (!common.hasCrypto)
<add> common.skip('missing crypto');
<ide> const assert = require('assert');
<ide> const h2 = require('http2');
<ide>
<ide><path>test/parallel/test-http2-compat-serverresponse-statusmessage.js
<ide> 'use strict';
<ide>
<ide> const common = require('../common');
<add>if (!common.hasCrypto)
<add> common.skip('missing crypto');
<ide> const assert = require('assert');
<ide> const h2 = require('http2');
<ide>
<ide><path>test/parallel/test-http2-compat-serverresponse-trailers.js
<ide> 'use strict';
<ide>
<ide> const common = require('../common');
<add>if (!common.hasCrypto)
<add> common.skip('missing crypto');
<ide> const assert = require('assert');
<ide> const http2 = require('http2');
<ide>
<ide><path>test/parallel/test-http2-compat-serverresponse-write-no-cb.js
<ide> // Flags: --expose-http2
<ide> 'use strict';
<ide>
<del>const { mustCall, mustNotCall, expectsError } = require('../common');
<add>const { mustCall,
<add> mustNotCall,
<add> expectsError,
<add> hasCrypto, skip } = require('../common');
<add>if (!hasCrypto)
<add> skip('missing crypto');
<ide> const { throws } = require('assert');
<ide> const { createServer, connect } = require('http2');
<ide>
<ide><path>test/parallel/test-http2-compat-serverresponse-writehead.js
<ide> 'use strict';
<ide>
<ide> const common = require('../common');
<add>if (!common.hasCrypto)
<add> common.skip('missing crypto');
<ide> const assert = require('assert');
<ide> const h2 = require('http2');
<ide>
<ide><path>test/parallel/test-http2-connect-method.js
<ide> 'use strict';
<ide>
<ide> const common = require('../common');
<add>if (!common.hasCrypto)
<add> common.skip('missing crypto');
<ide> const assert = require('assert');
<ide> const net = require('net');
<ide> const http2 = require('http2');
<ide><path>test/parallel/test-http2-connect.js
<ide> // Flags: --expose-http2
<ide> 'use strict';
<ide>
<del>const { mustCall } = require('../common');
<add>const { mustCall, hasCrypto, skip } = require('../common');
<add>if (!hasCrypto)
<add> skip('missing crypto');
<ide> const { doesNotThrow } = require('assert');
<ide> const { createServer, connect } = require('http2');
<ide>
<ide><path>test/parallel/test-http2-cookies.js
<ide> 'use strict';
<ide>
<ide> const common = require('../common');
<add>if (!common.hasCrypto)
<add> common.skip('missing crypto');
<ide> const assert = require('assert');
<ide> const h2 = require('http2');
<ide>
<ide><path>test/parallel/test-http2-create-client-connect.js
<ide> // Tests http2.connect()
<ide>
<ide> const common = require('../common');
<add>if (!common.hasCrypto)
<add> common.skip('missing crypto');
<ide> const fs = require('fs');
<ide> const h2 = require('http2');
<ide> const path = require('path');
<ide><path>test/parallel/test-http2-create-client-session.js
<ide> 'use strict';
<ide>
<ide> const common = require('../common');
<add>if (!common.hasCrypto)
<add> common.skip('missing crypto');
<ide> const assert = require('assert');
<ide> const h2 = require('http2');
<ide> const body =
<ide><path>test/parallel/test-http2-date-header.js
<ide> 'use strict';
<ide>
<ide> const common = require('../common');
<add>if (!common.hasCrypto)
<add> common.skip('missing crypto');
<ide> const assert = require('assert');
<ide> const http2 = require('http2');
<ide>
<ide><path>test/parallel/test-http2-dont-override.js
<ide> 'use strict';
<ide>
<ide> const common = require('../common');
<add>if (!common.hasCrypto)
<add> common.skip('missing crypto');
<ide> const assert = require('assert');
<ide> const http2 = require('http2');
<ide>
<ide><path>test/parallel/test-http2-getpackedsettings.js
<ide> 'use strict';
<ide>
<ide> const common = require('../common');
<add>if (!common.hasCrypto)
<add> common.skip('missing crypto');
<ide> const assert = require('assert');
<ide> const http2 = require('http2');
<ide>
<ide><path>test/parallel/test-http2-goaway-opaquedata.js
<ide> 'use strict';
<ide>
<ide> const common = require('../common');
<add>if (!common.hasCrypto)
<add> common.skip('missing crypto');
<ide> const assert = require('assert');
<ide> const http2 = require('http2');
<ide>
<ide><path>test/parallel/test-http2-head-request.js
<ide> 'use strict';
<ide>
<ide> const common = require('../common');
<add>if (!common.hasCrypto)
<add> common.skip('missing crypto');
<ide> const assert = require('assert');
<ide> const http2 = require('http2');
<ide>
<ide><path>test/parallel/test-http2-info-headers.js
<ide> 'use strict';
<ide>
<ide> const common = require('../common');
<add>if (!common.hasCrypto)
<add> common.skip('missing crypto');
<ide> const assert = require('assert');
<ide> const h2 = require('http2');
<ide>
<ide><path>test/parallel/test-http2-max-concurrent-streams.js
<ide> 'use strict';
<ide>
<ide> const common = require('../common');
<add>if (!common.hasCrypto)
<add> common.skip('missing crypto');
<ide> const assert = require('assert');
<ide> const h2 = require('http2');
<ide>
<ide><path>test/parallel/test-http2-methods.js
<ide> 'use strict';
<ide>
<ide> const common = require('../common');
<add>if (!common.hasCrypto)
<add> common.skip('missing crypto');
<ide> const assert = require('assert');
<ide> const h2 = require('http2');
<ide>
<ide><path>test/parallel/test-http2-misused-pseudoheaders.js
<ide> 'use strict';
<ide>
<ide> const common = require('../common');
<add>if (!common.hasCrypto)
<add> common.skip('missing crypto');
<ide> const assert = require('assert');
<ide> const h2 = require('http2');
<ide>
<ide><path>test/parallel/test-http2-multi-content-length.js
<ide> 'use strict';
<ide>
<ide> const common = require('../common');
<add>if (!common.hasCrypto)
<add> common.skip('missing crypto');
<ide> const http2 = require('http2');
<ide>
<ide> const server = http2.createServer();
<ide><path>test/parallel/test-http2-multiheaders.js
<ide> 'use strict';
<ide>
<ide> const common = require('../common');
<add>if (!common.hasCrypto)
<add> common.skip('missing crypto');
<ide> const assert = require('assert');
<ide> const http2 = require('http2');
<ide>
<ide><path>test/parallel/test-http2-multiplex.js
<ide> // connection and makes sure that the data for each is appropriately echoed.
<ide>
<ide> const common = require('../common');
<add>if (!common.hasCrypto)
<add> common.skip('missing crypto');
<ide> const assert = require('assert');
<ide> const http2 = require('http2');
<ide>
<ide><path>test/parallel/test-http2-options-max-headers-block-length.js
<ide> 'use strict';
<ide>
<ide> const common = require('../common');
<add>if (!common.hasCrypto)
<add> common.skip('missing crypto');
<ide> const assert = require('assert');
<ide> const h2 = require('http2');
<ide>
<ide><path>test/parallel/test-http2-options-max-reserved-streams.js
<ide> 'use strict';
<ide>
<ide> const common = require('../common');
<add>if (!common.hasCrypto)
<add> common.skip('missing crypto');
<ide> const h2 = require('http2');
<ide>
<ide> const server = h2.createServer();
<ide><path>test/parallel/test-http2-padding-callback.js
<ide> 'use strict';
<ide>
<ide> const common = require('../common');
<add>if (!common.hasCrypto)
<add> common.skip('missing crypto');
<ide> const assert = require('assert');
<ide> const h2 = require('http2');
<ide> const { PADDING_STRATEGY_CALLBACK } = h2.constants;
<ide><path>test/parallel/test-http2-priority-event.js
<ide> 'use strict';
<ide>
<ide> const common = require('../common');
<add>if (!common.hasCrypto)
<add> common.skip('missing crypto');
<ide> const assert = require('assert');
<ide> const h2 = require('http2');
<ide>
<ide><path>test/parallel/test-http2-respond-file-204.js
<ide> 'use strict';
<ide>
<ide> const common = require('../common');
<add>if (!common.hasCrypto)
<add> common.skip('missing crypto');
<ide> const http2 = require('http2');
<ide> const assert = require('assert');
<ide> const path = require('path');
<ide><path>test/parallel/test-http2-respond-file-304.js
<ide> 'use strict';
<ide>
<ide> const common = require('../common');
<add>if (!common.hasCrypto)
<add> common.skip('missing crypto');
<ide> const http2 = require('http2');
<ide> const assert = require('assert');
<ide> const path = require('path');
<ide><path>test/parallel/test-http2-respond-file-compat.js
<ide> 'use strict';
<ide>
<ide> const common = require('../common');
<add>if (!common.hasCrypto)
<add> common.skip('missing crypto');
<ide> const http2 = require('http2');
<ide> const path = require('path');
<ide>
<ide><path>test/parallel/test-http2-respond-file-fd-invalid.js
<ide> 'use strict';
<ide>
<ide> const common = require('../common');
<add>if (!common.hasCrypto)
<add> common.skip('missing crypto');
<ide> const http2 = require('http2');
<ide> const assert = require('assert');
<ide>
<ide><path>test/parallel/test-http2-respond-file-fd-range.js
<ide> // Tests the ability to minimally request a byte range with respondWithFD
<ide>
<ide> const common = require('../common');
<add>if (!common.hasCrypto)
<add> common.skip('missing crypto');
<ide> const http2 = require('http2');
<ide> const assert = require('assert');
<ide> const path = require('path');
<ide><path>test/parallel/test-http2-respond-file-fd.js
<ide> 'use strict';
<ide>
<ide> const common = require('../common');
<add>if (!common.hasCrypto)
<add> common.skip('missing crypto');
<ide> const http2 = require('http2');
<ide> const assert = require('assert');
<ide> const path = require('path');
<ide><path>test/parallel/test-http2-respond-file-push.js
<ide> 'use strict';
<ide>
<ide> const common = require('../common');
<add>if (!common.hasCrypto)
<add> common.skip('missing crypto');
<ide> const http2 = require('http2');
<ide> const assert = require('assert');
<ide> const path = require('path');
<ide><path>test/parallel/test-http2-respond-file-range.js
<ide> 'use strict';
<ide>
<ide> const common = require('../common');
<add>if (!common.hasCrypto)
<add> common.skip('missing crypto');
<ide> const http2 = require('http2');
<ide> const assert = require('assert');
<ide> const path = require('path');
<ide><path>test/parallel/test-http2-respond-file.js
<ide> 'use strict';
<ide>
<ide> const common = require('../common');
<add>if (!common.hasCrypto)
<add> common.skip('missing crypto');
<ide> const http2 = require('http2');
<ide> const assert = require('assert');
<ide> const path = require('path');
<ide><path>test/parallel/test-http2-response-splitting.js
<ide> // contain invalid characters.
<ide>
<ide> const common = require('../common');
<add>if (!common.hasCrypto)
<add> common.skip('missing crypto');
<ide> const assert = require('assert');
<ide> const http2 = require('http2');
<ide> const { URL } = require('url');
<ide><path>test/parallel/test-http2-server-destroy-before-additional.js
<ide> 'use strict';
<ide>
<ide> const common = require('../common');
<add>if (!common.hasCrypto)
<add> common.skip('missing crypto');
<ide> const assert = require('assert');
<ide> const h2 = require('http2');
<ide>
<ide><path>test/parallel/test-http2-server-destroy-before-push.js
<ide> 'use strict';
<ide>
<ide> const common = require('../common');
<add>if (!common.hasCrypto)
<add> common.skip('missing crypto');
<ide> const assert = require('assert');
<ide> const h2 = require('http2');
<ide>
<ide><path>test/parallel/test-http2-server-destroy-before-respond.js
<ide> 'use strict';
<ide>
<ide> const common = require('../common');
<add>if (!common.hasCrypto)
<add> common.skip('missing crypto');
<ide> const assert = require('assert');
<ide> const h2 = require('http2');
<ide>
<ide><path>test/parallel/test-http2-server-destroy-before-write.js
<ide> 'use strict';
<ide>
<ide> const common = require('../common');
<add>if (!common.hasCrypto)
<add> common.skip('missing crypto');
<ide> const assert = require('assert');
<ide> const h2 = require('http2');
<ide>
<ide><path>test/parallel/test-http2-server-push-disabled.js
<ide> 'use strict';
<ide>
<ide> const common = require('../common');
<add>if (!common.hasCrypto)
<add> common.skip('missing crypto');
<ide> const assert = require('assert');
<ide> const http2 = require('http2');
<ide>
<ide><path>test/parallel/test-http2-server-push-stream.js
<ide> 'use strict';
<ide>
<ide> const common = require('../common');
<add>if (!common.hasCrypto)
<add> common.skip('missing crypto');
<ide> const assert = require('assert');
<ide> const http2 = require('http2');
<ide>
<ide><path>test/parallel/test-http2-server-rst-before-respond.js
<ide> 'use strict';
<ide>
<ide> const common = require('../common');
<add>if (!common.hasCrypto)
<add> common.skip('missing crypto');
<ide> const assert = require('assert');
<ide> const h2 = require('http2');
<ide>
<ide><path>test/parallel/test-http2-server-rst-stream.js
<ide> 'use strict';
<ide>
<ide> const common = require('../common');
<add>if (!common.hasCrypto)
<add> common.skip('missing crypto');
<ide> const assert = require('assert');
<ide> const http2 = require('http2');
<ide>
<ide><path>test/parallel/test-http2-server-set-header.js
<ide> 'use strict';
<ide>
<ide> const common = require('../common');
<add>if (!common.hasCrypto)
<add> common.skip('missing crypto');
<ide> const assert = require('assert');
<ide> const http2 = require('http2');
<ide> const body =
<ide><path>test/parallel/test-http2-server-shutdown-before-respond.js
<ide> 'use strict';
<ide>
<ide> const common = require('../common');
<add>if (!common.hasCrypto)
<add> common.skip('missing crypto');
<ide> const h2 = require('http2');
<ide>
<ide> const server = h2.createServer();
<ide><path>test/parallel/test-http2-server-socket-destroy.js
<ide> 'use strict';
<ide>
<ide> const common = require('../common');
<add>if (!common.hasCrypto)
<add> common.skip('missing crypto');
<ide> const h2 = require('http2');
<ide> const assert = require('assert');
<ide>
<ide><path>test/parallel/test-http2-server-socketerror.js
<ide> 'use strict';
<ide>
<ide> const common = require('../common');
<add>if (!common.hasCrypto)
<add> common.skip('missing crypto');
<ide> const assert = require('assert');
<ide> const http2 = require('http2');
<ide>
<ide><path>test/parallel/test-http2-server-timeout.js
<ide> 'use strict';
<ide>
<ide> const common = require('../common');
<add>if (!common.hasCrypto)
<add> common.skip('missing crypto');
<ide> const http2 = require('http2');
<ide>
<ide> const server = http2.createServer();
<ide><path>test/parallel/test-http2-session-settings.js
<ide> 'use strict';
<ide>
<ide> const common = require('../common');
<add>if (!common.hasCrypto)
<add> common.skip('missing crypto');
<ide> const assert = require('assert');
<ide> const h2 = require('http2');
<ide>
<ide><path>test/parallel/test-http2-session-stream-state.js
<ide> 'use strict';
<ide>
<ide> const common = require('../common');
<add>if (!common.hasCrypto)
<add> common.skip('missing crypto');
<ide> const assert = require('assert');
<ide> const h2 = require('http2');
<ide>
<ide><path>test/parallel/test-http2-single-headers.js
<ide> 'use strict';
<ide>
<ide> const common = require('../common');
<add>if (!common.hasCrypto)
<add> common.skip('missing crypto');
<ide> const http2 = require('http2');
<ide>
<ide> const server = http2.createServer();
<ide><path>test/parallel/test-http2-status-code-invalid.js
<ide> 'use strict';
<ide>
<ide> const common = require('../common');
<add>if (!common.hasCrypto)
<add> common.skip('missing crypto');
<ide> const assert = require('assert');
<ide> const http2 = require('http2');
<ide>
<ide><path>test/parallel/test-http2-status-code.js
<ide> 'use strict';
<ide>
<ide> const common = require('../common');
<add>if (!common.hasCrypto)
<add> common.skip('missing crypto');
<ide> const assert = require('assert');
<ide> const http2 = require('http2');
<ide>
<ide><path>test/parallel/test-http2-timeouts.js
<ide> 'use strict';
<ide>
<ide> const common = require('../common');
<add>if (!common.hasCrypto)
<add> common.skip('missing crypto');
<ide> const h2 = require('http2');
<ide>
<ide> const server = h2.createServer();
<ide><path>test/parallel/test-http2-too-many-settings.js
<ide> // settings frames will result in a throw.
<ide>
<ide> const common = require('../common');
<add>if (!common.hasCrypto)
<add> common.skip('missing crypto');
<ide> const assert = require('assert');
<ide> const h2 = require('http2');
<ide>
<ide><path>test/parallel/test-http2-trailers.js
<ide> 'use strict';
<ide>
<ide> const common = require('../common');
<add>if (!common.hasCrypto)
<add> common.skip('missing crypto');
<ide> const assert = require('assert');
<ide> const h2 = require('http2');
<ide> const body =
<ide><path>test/parallel/test-http2-window-size.js
<ide> // on smaller / IoT platforms in case this poses problems for these targets.
<ide>
<ide> const common = require('../common');
<add>if (!common.hasCrypto)
<add> common.skip('missing crypto');
<ide> const assert = require('assert');
<ide> const h2 = require('http2');
<ide>
<ide><path>test/parallel/test-http2-withflag.js
<ide> // Flags: --expose-http2
<ide> 'use strict';
<ide>
<del>require('../common');
<add>const common = require('../common');
<add>if (!common.hasCrypto)
<add> common.skip('missing crypto');
<ide> const assert = require('assert');
<ide>
<ide> assert.doesNotThrow(() => require('http2'));
<ide><path>test/parallel/test-http2-write-callbacks.js
<ide> // Verifies that write callbacks are called
<ide>
<ide> const common = require('../common');
<add>if (!common.hasCrypto)
<add> common.skip('missing crypto');
<ide> const assert = require('assert');
<ide> const http2 = require('http2');
<ide>
<ide><path>test/parallel/test-http2-write-empty-string.js
<ide> 'use strict';
<ide>
<ide> const common = require('../common');
<add>if (!common.hasCrypto)
<add> common.skip('missing crypto');
<ide> const assert = require('assert');
<ide> const http2 = require('http2');
<ide>
<ide><path>test/parallel/test-http2-zero-length-write.js
<ide> 'use strict';
<ide>
<ide> const common = require('../common');
<add>if (!common.hasCrypto)
<add> common.skip('missing crypto');
<ide> const assert = require('assert');
<ide> const http2 = require('http2');
<ide> | 85 |
Ruby | Ruby | add new intel names | 6d46a4eed744229933e490b8709d11f7ec12d8da | <ide><path>Library/Homebrew/extend/os/linux/hardware/cpu.rb
<ide> def family
<ide> :merom
<ide> when 0x0d
<ide> :dothan
<del> when 0x36, 0x26, 0x1c
<add> when 0x1c, 0x26, 0x27, 0x35, 0x36
<ide> :atom
<del> when 0x3c, 0x3f, 0x46
<add> when 0x3c, 0x3f, 0x45, 0x46
<ide> :haswell
<ide> when 0x3d, 0x47, 0x4f, 0x56
<ide> :broadwell
<ide> when 0x4e, 0x55, 0x5e, 0x8e, 0x9e
<ide> :skylake
<add> when 0x66
<add> :cannonlake
<add> when 0x6a, 0x6c, 0x7d, 0x7e
<add> :icelake
<ide> else
<ide> unknown
<ide> end | 1 |
PHP | PHP | change mysql schema grammar to remove default 0 | 6b8f3f96a40ad22f6ac1436eca12f13d4caa0bef | <ide><path>src/Illuminate/Database/Schema/Grammars/MySqlGrammar.php
<ide> protected function typeTimestampTz(Fluent $column)
<ide> return 'timestamp default CURRENT_TIMESTAMP';
<ide> }
<ide>
<del> if (! $column->nullable && $column->default === null) {
<del> return 'timestamp default 0';
<del> }
<del>
<ide> return 'timestamp';
<ide> }
<ide>
<ide><path>tests/Database/DatabaseMySqlSchemaGrammarTest.php
<ide> public function testAddingTimeStampTz()
<ide> $statements = $blueprint->toSql($this->getConnection(), $this->getGrammar());
<ide>
<ide> $this->assertEquals(1, count($statements));
<del> $this->assertEquals('alter table `users` add `foo` timestamp default 0 not null', $statements[0]);
<add> $this->assertEquals('alter table `users` add `foo` timestamp not null', $statements[0]);
<ide> }
<ide>
<ide> public function testAddingTimeStampTzWithDefault()
<ide> public function testAddingTimeStampsTz()
<ide> $statements = $blueprint->toSql($this->getConnection(), $this->getGrammar());
<ide>
<ide> $this->assertEquals(1, count($statements));
<del> $this->assertEquals('alter table `users` add `created_at` timestamp default 0 not null, add `updated_at` timestamp default 0 not null', $statements[0]);
<add> $this->assertEquals('alter table `users` add `created_at` timestamp not null, add `updated_at` timestamp not null', $statements[0]);
<ide> }
<ide>
<ide> public function testAddingRememberToken() | 2 |
PHP | PHP | convert switch to array lookup | d926028341429f7208b1ee419c3117f044b78d2b | <ide><path>lib/Cake/Error/BaseErrorHandler.php
<ide> protected function _getMessage($exception) {
<ide> * @return array Array of error word, and log location.
<ide> */
<ide> public static function mapErrorCode($code) {
<del> $error = $log = null;
<del> switch ($code) {
<del> case E_PARSE:
<del> case E_ERROR:
<del> case E_CORE_ERROR:
<del> case E_COMPILE_ERROR:
<del> case E_USER_ERROR:
<del> $error = 'Fatal Error';
<del> $log = LOG_ERR;
<del> break;
<del> case E_WARNING:
<del> case E_USER_WARNING:
<del> case E_COMPILE_WARNING:
<del> case E_RECOVERABLE_ERROR:
<del> $error = 'Warning';
<del> $log = LOG_WARNING;
<del> break;
<del> case E_NOTICE:
<del> case E_USER_NOTICE:
<del> $error = 'Notice';
<del> $log = LOG_NOTICE;
<del> break;
<del> case E_STRICT:
<del> $error = 'Strict';
<del> $log = LOG_NOTICE;
<del> break;
<del> case E_DEPRECATED:
<del> case E_USER_DEPRECATED:
<del> $error = 'Deprecated';
<del> $log = LOG_NOTICE;
<del> break;
<del> }
<del> return array($error, $log);
<add> $levelMap = [
<add> E_PARSE => 'error',
<add> E_ERROR => 'error',
<add> E_CORE_ERROR => 'error',
<add> E_COMPILE_ERROR => 'error',
<add> E_USER_ERROR => 'error',
<add> E_WARNING => 'warning',
<add> E_USER_WARNING => 'warning',
<add> E_COMPILE_WARNING => 'warning',
<add> E_RECOVERABLE_ERROR => 'warning',
<add> E_NOTICE => 'notice',
<add> E_USER_NOTICE => 'notice',
<add> E_STRICT => 'strict',
<add> E_DEPRECATED => 'deprecated',
<add> E_USER_DEPRECATED => 'deprecated',
<add> ];
<add> $logMap = [
<add> 'error' => LOG_ERR,
<add> 'warning' => LOG_WARNING,
<add> 'notice' => LOG_NOTICE,
<add> 'strict' => LOG_NOTICE,
<add> 'deprecated' => LOG_NOTICE,
<add> ];
<add>
<add> $error = $levelMap[$code];
<add> $log = $logMap[$error];
<add> return [ucfirst($error), $log];
<ide> }
<ide>
<ide> } | 1 |
Javascript | Javascript | increase test timeout | e92f9d88d7d9f0224e6782c5454f20758d85a740 | <ide><path>test/ConfigTestCases.template.js
<ide> const describeCases = config => {
<ide> })
<ide> .catch(done);
<ide> });
<del> });
<add> }, 30000);
<ide>
<ide> const {
<ide> it: _it, | 1 |
PHP | PHP | check path in method hasfile | 077a9ef83057e8df5993ef16f1d607640cbb1dc8 | <ide><path>src/Illuminate/Http/Request.php
<ide> public function hasFile($key)
<ide> {
<ide> if (is_array($file = $this->file($key))) $file = head($file);
<ide>
<del> return $file instanceof \SplFileInfo;
<add> return $file instanceof \SplFileInfo && $file->getPath() != '';
<ide> }
<ide>
<ide> /** | 1 |
Javascript | Javascript | enforce blank line between functions | 68abaab8baac203833889c9106abf6fe82a5900f | <ide><path>.eslintrc.js
<ide> module.exports = {
<ide> 'one-var': ['error', { initialized: 'never' }],
<ide> 'one-var-declaration-per-line': 'error',
<ide> 'operator-linebreak': ['error', 'after'],
<add> 'padding-line-between-statements': [
<add> 'error',
<add> { blankLine: 'always', prev: 'function', next: 'function' },
<add> ],
<ide> 'prefer-const': ['error', { ignoreReadBeforeAssign: true }],
<ide> 'quotes': ['error', 'single', { avoidEscape: true }],
<ide> 'quote-props': ['error', 'consistent'], | 1 |
Python | Python | move `panopticdeeplabfusion` into project dir | 75f304ddd90e7b6adaecad20ad16817edbd32cc9 | <ide><path>official/vision/beta/projects/panoptic_maskrcnn/modeling/heads/panoptic_deeplab_heads.py
<ide> import tensorflow as tf
<ide>
<ide> from official.modeling import tf_utils
<del>from official.vision.beta.modeling.layers import nn_layers
<add>from official.vision.beta.projects.panoptic_maskrcnn.modeling.layers import fusion_layers
<ide> from official.vision.beta.ops import spatial_transform_ops
<ide>
<ide>
<ide> def build(self, input_shape: Union[tf.TensorShape, List[tf.TensorShape]]):
<ide> 'epsilon': self._config_dict['norm_epsilon'],
<ide> }
<ide>
<del> self._panoptic_deeplab_fusion = nn_layers.PanopticDeepLabFusion(
<add> self._panoptic_deeplab_fusion = fusion_layers.PanopticDeepLabFusion(
<ide> level=self._config_dict['level'],
<ide> low_level=self._config_dict['low_level'],
<ide> num_projection_filters=self._config_dict['low_level_num_filters'],
<ide><path>official/vision/beta/projects/panoptic_maskrcnn/modeling/layers/fusion_layers.py
<add># Copyright 2022 The TensorFlow Authors. All Rights Reserved.
<add>#
<add># Licensed under the Apache License, Version 2.0 (the "License");
<add># you may not use this file except in compliance with the License.
<add># You may obtain a copy of the License at
<add>#
<add># http://www.apache.org/licenses/LICENSE-2.0
<add>#
<add># Unless required by applicable law or agreed to in writing, software
<add># distributed under the License is distributed on an "AS IS" BASIS,
<add># WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
<add># See the License for the specific language governing permissions and
<add># limitations under the License.
<add>
<add>"""Contains common building blocks for neural networks."""
<add>from typing import Any, Callable, Dict, List, Mapping, Optional, Union
<add>
<add>import tensorflow as tf
<add>
<add>from official.modeling import tf_utils
<add>
<add>
<add># Type annotations.
<add>States = Dict[str, tf.Tensor]
<add>Activation = Union[str, Callable]
<add>
<add>
<add>class PanopticDeepLabFusion(tf.keras.layers.Layer):
<add> """Creates a Panoptic DeepLab feature Fusion layer.
<add>
<add> This implements the feature fusion introduced in the paper:
<add> Cheng et al. Panoptic-DeepLab
<add> (https://arxiv.org/pdf/1911.10194.pdf)
<add> """
<add>
<add> def __init__(
<add> self,
<add> level: int,
<add> low_level: List[int] = [3, 2],
<add> num_projection_filters: List[int] = [64, 32],
<add> num_output_filters: int = 256,
<add> activation: str = 'relu',
<add> use_sync_bn: bool = False,
<add> norm_momentum: float = 0.99,
<add> norm_epsilon: float = 0.001,
<add> kernel_regularizer: Optional[tf.keras.regularizers.Regularizer] = None,
<add> bias_regularizer: Optional[tf.keras.regularizers.Regularizer] = None,
<add> interpolation: str = 'bilinear',
<add> **kwargs):
<add> """Initializes panoptic FPN feature fusion layer.
<add>
<add> Args:
<add> level: An `int` level at which the decoder was appled at.
<add> low_level: A list of `int` of minimum level to use in feature fusion.
<add> num_filters: An `int` number of filters in conv2d layers.
<add> activation: A `str` name of the activation function.
<add> use_sync_bn: A `bool` that indicates whether to use synchronized batch
<add> normalization across different replicas.
<add> norm_momentum: A `float` of normalization momentum for the moving average.
<add> norm_epsilon: A `float` added to variance to avoid dividing by zero.
<add> kernel_regularizer: A `tf.keras.regularizers.Regularizer` object for
<add> Conv2D. Default is None.
<add> bias_regularizer: A `tf.keras.regularizers.Regularizer` object for Conv2D.
<add> interpolation: A `str` interpolation method for upsampling. Defaults to
<add> `bilinear`.
<add> **kwargs: Additional keyword arguments to be passed.
<add> Returns:
<add> A `float` `tf.Tensor` of shape [batch_size, feature_height, feature_width,
<add> feature_channel].
<add> """
<add> super(PanopticDeepLabFusion, self).__init__(**kwargs)
<add>
<add> self._config_dict = {
<add> 'level': level,
<add> 'low_level': low_level,
<add> 'num_projection_filters': num_projection_filters,
<add> 'num_output_filters': num_output_filters,
<add> 'activation': activation,
<add> 'use_sync_bn': use_sync_bn,
<add> 'norm_momentum': norm_momentum,
<add> 'norm_epsilon': norm_epsilon,
<add> 'kernel_regularizer': kernel_regularizer,
<add> 'bias_regularizer': bias_regularizer,
<add> 'interpolation': interpolation
<add> }
<add> if tf.keras.backend.image_data_format() == 'channels_last':
<add> self._channel_axis = -1
<add> else:
<add> self._channel_axis = 1
<add> self._activation = tf_utils.get_activation(activation)
<add>
<add> def build(self, input_shape: List[tf.TensorShape]):
<add> conv_op = tf.keras.layers.Conv2D
<add> conv_kwargs = {
<add> 'padding': 'same',
<add> 'use_bias': False,
<add> 'kernel_initializer': tf.initializers.VarianceScaling(),
<add> 'kernel_regularizer': self._config_dict['kernel_regularizer'],
<add> }
<add> bn_op = (tf.keras.layers.experimental.SyncBatchNormalization
<add> if self._config_dict['use_sync_bn']
<add> else tf.keras.layers.BatchNormalization)
<add> bn_kwargs = {
<add> 'axis': self._channel_axis,
<add> 'momentum': self._config_dict['norm_momentum'],
<add> 'epsilon': self._config_dict['norm_epsilon'],
<add> }
<add>
<add> self._projection_convs = []
<add> self._projection_norms = []
<add> self._fusion_convs = []
<add> self._fusion_norms = []
<add> for i in range(len(self._config_dict['low_level'])):
<add> self._projection_convs.append(
<add> conv_op(
<add> filters=self._config_dict['num_projection_filters'][i],
<add> kernel_size=1,
<add> **conv_kwargs))
<add> self._fusion_convs.append(
<add> conv_op(
<add> filters=self._config_dict['num_output_filters'],
<add> kernel_size=5,
<add> **conv_kwargs))
<add> self._projection_norms.append(bn_op(**bn_kwargs))
<add> self._fusion_norms.append(bn_op(**bn_kwargs))
<add>
<add> def call(self, inputs, training=None):
<add> if training is None:
<add> training = tf.keras.backend.learning_phase()
<add>
<add> backbone_output = inputs[0]
<add> decoder_output = inputs[1][str(self._config_dict['level'])]
<add>
<add> x = decoder_output
<add> for i in range(len(self._config_dict['low_level'])):
<add> feature = backbone_output[str(self._config_dict['low_level'][i])]
<add> feature = self._projection_convs[i](feature)
<add> feature = self._projection_norms[i](feature, training=training)
<add> feature = self._activation(feature)
<add>
<add> shape = tf.shape(feature)
<add> x = tf.image.resize(
<add> x, size=[shape[1], shape[2]],
<add> method=self._config_dict['interpolation'])
<add> x = tf.concat([x, feature], axis=self._channel_axis)
<add>
<add> x = self._fusion_convs[i](x)
<add> x = self._fusion_norms[i](x, training=training)
<add> x = self._activation(x)
<add> return x
<add>
<add> def get_config(self) -> Mapping[str, Any]:
<add> return self._config_dict
<add>
<add> @classmethod
<add> def from_config(cls, config, custom_objects=None):
<add> return cls(**config) | 2 |
PHP | PHP | fix views overwrite warning text | 6f4c3b2765fbfbff0ef80291f2f31b3ba9b29dfc | <ide><path>lib/Cake/Console/Command/Task/ViewTask.php
<ide> protected function _interactive() {
<ide> $this->Controller->connection = $this->connection;
<ide> $this->controllerName = $this->Controller->getName();
<ide>
<del> $prompt = __d('cake_console', "Would you like bake to build your views interactively?\nWarning: Choosing no will overwrite %s views if it exist.", $this->controllerName);
<add> $prompt = __d('cake_console', "Would you like bake to build your views interactively?\nWarning: Choosing no will overwrite %s views if they exist.", $this->controllerName);
<ide> $interactive = $this->in($prompt, array('y', 'n'), 'n');
<ide>
<ide> if (strtolower($interactive) === 'n') { | 1 |
Javascript | Javascript | bring box example up-to-date | c8c6292b2663d8a5afb315a8616eb5a9f0d9dac9 | <ide><path>examples/box/box.js
<del>var w = 120,
<del> h = 500,
<del> m = [10, 50, 20, 50], // top right bottom left
<add>var innerWidth = 120,
<add> innerHeight = 500,
<add> margin = {top: 10, right: 50, bottom: 20, left: 50},
<ide> min = Infinity,
<ide> max = -Infinity;
<ide>
<ide> var chart = boxChart()
<ide> .whiskers(iqr(1.5))
<del> .width(w - m[1] - m[3])
<del> .height(h - m[0] - m[2]);
<add> .width(innerWidth - margin[1] - margin[3])
<add> .height(innerHeight - margin.top - margin[2]);
<ide>
<ide> d3.csv("../data/morley.csv", function(csv) {
<ide> var data = [];
<ide> d3.csv("../data/morley.csv", function(csv) {
<ide> .data(data)
<ide> .enter().append("svg")
<ide> .attr("class", "box")
<del> .attr("width", w)
<del> .attr("height", h)
<add> .attr("width", innerWidth)
<add> .attr("height", innerHeight)
<ide> .append("g")
<del> .attr("transform", "translate(" + m[3] + "," + m[0] + ")")
<add> .attr("transform", "translate(" + margin[3] + "," + margin.top + ")")
<ide> .call(chart);
<ide>
<ide> chart.duration(1000); | 1 |
Text | Text | fix typo and add label to breaking change | f724d676db99c744b0548f9f9ac0d290aad0f7f2 | <ide><path>CHANGELOG.md
<ide> - Added `SESSION_CONNECTION` and `SESSION_STORE` env. variable ([#4735](https://github.com/laravel/laravel/pull/4735))
<ide>
<ide> ### Changed
<del>- Changed `QUEUE_DRIVER` env variable name to `QUEUE_CONNECTION` ([c30adc8](https://github.com/laravel/laravel/commit/c30adc88c1cf3f30618145c8b698734cbe03b19c))
<del>- Use seperate cache database for Redis ([#4665](https://github.com/laravel/laravel/pull/4665))
<add>- BREAKING CHANGE! Changed `QUEUE_DRIVER` env variable name to `QUEUE_CONNECTION` ([c30adc8](https://github.com/laravel/laravel/commit/c30adc88c1cf3f30618145c8b698734cbe03b19c))
<add>- Use separate cache database for Redis ([#4665](https://github.com/laravel/laravel/pull/4665))
<ide> - Upgrade Lodash to `^4.17.5` ([#4730](https://github.com/laravel/laravel/pull/4730))
<ide> - Changed font to Nuntio from Raleway ([#4727](https://github.com/laravel/laravel/pull/4727))
<ide> - Defined `mix` as `const` in `webpack.mix.js` ([#4741](https://github.com/laravel/laravel/pull/4741)) | 1 |
Text | Text | use consistent markdown in readme | cc3a9e79479b9486ba1726889767d44d26bcad81 | <ide><path>README.md
<del>Node.js
<del>=======
<add># Node.js
<ide>
<ide> [](https://gitter.im/nodejs/node?utm_source=badge&utm_medium=badge&utm_campaign=pr-badge&utm_content=badge) [](https://bestpractices.coreinfrastructure.org/projects/29)
<ide>
<ide> If you need help using or installing Node.js, please use the
<ide> ### Unofficial Resources
<ide>
<ide> * IRC (general questions): [#node.js on chat.freenode.net][]. Please see
<del>http://nodeirc.info/ for more information regarding the `#node.js` IRC channel.
<add><http://nodeirc.info/> for more information regarding the `#node.js` IRC
<add>channel.
<ide>
<del>*Please note that unofficial resources are neither managed by (nor necessarily
<add>_Please note that unofficial resources are neither managed by (nor necessarily
<ide> endorsed by) the Node.js TSC/CTC. Specifically, such resources are not
<ide> currently covered by the [Node.js Moderation Policy][] and the selection and
<del>actions of resource operators/moderators are not subject to TSC/CTC oversight.*
<add>actions of resource operators/moderators are not subject to TSC/CTC oversight._
<ide>
<ide> ## Release Types
<ide>
<ide> documentation of the latest stable version.
<ide>
<ide> ### Verifying Binaries
<ide>
<del>Current, LTS and Nightly download directories all contain a *SHASUM256.txt*
<add>Current, LTS and Nightly download directories all contain a _SHASUM256.txt_
<ide> file that lists the SHA checksums for each file available for
<ide> download.
<ide>
<del>The *SHASUM256.txt* can be downloaded using curl.
<add>The _SHASUM256.txt_ can be downloaded using curl.
<ide>
<del>```
<add>```console
<ide> $ curl -O https://nodejs.org/dist/vx.y.z/SHASUMS256.txt
<ide> ```
<ide>
<ide> To check that a downloaded file matches the checksum, run
<ide> it through `sha256sum` with a command such as:
<ide>
<del>```
<add>```console
<ide> $ grep node-vx.y.z.tar.gz SHASUMS256.txt | sha256sum -c -
<ide> ```
<ide>
<ide> the GPG keys of individuals authorized to create releases. They are
<ide> listed at the bottom of this README under [Release Team](#release-team).
<ide> Use a command such as this to import the keys:
<ide>
<del>```
<del>$ gpg --keyserver pool.sks-keyservers.net \
<del> --recv-keys DD8F2338BAE7501E3DD5AC78C273792F7D83545D
<add>```console
<add>$ gpg --keyserver pool.sks-keyservers.net --recv-keys DD8F2338BAE7501E3DD5AC78C273792F7D83545D
<ide> ```
<ide>
<ide> _(See the bottom of this README for a full script to import active
<ide> handling your report.
<ide> ## Current Project Team Members
<ide>
<ide> The Node.js project team comprises a group of core collaborators and a sub-group
<del>that forms the _Core Technical Committee_ (CTC) which governs the project. For more
<del>information about the governance of the Node.js project, see
<add>that forms the _Core Technical Committee_ (CTC) which governs the project. For
<add>more information about the governance of the Node.js project, see
<ide> [GOVERNANCE.md](./GOVERNANCE.md).
<ide>
<ide> ### CTC (Core Technical Committee)
<ide>
<del>* [addaleax](https://github.com/addaleax) - **Anna Henningsen** <[email protected]>
<del>* [bnoordhuis](https://github.com/bnoordhuis) - **Ben Noordhuis** <[email protected]>
<del>* [ChALkeR](https://github.com/ChALkeR) - **Сковорода Никита Андреевич** <[email protected]>
<del>* [chrisdickinson](https://github.com/chrisdickinson) - **Chris Dickinson** <[email protected]>
<del>* [cjihrig](https://github.com/cjihrig) - **Colin Ihrig** <[email protected]>
<del>* [evanlucas](https://github.com/evanlucas) - **Evan Lucas** <[email protected]>
<del>* [fishrock123](https://github.com/fishrock123) - **Jeremiah Senkpiel** <[email protected]>
<del>* [indutny](https://github.com/indutny) - **Fedor Indutny** <[email protected]>
<del>* [jasnell](https://github.com/jasnell) - **James M Snell** <[email protected]>
<del>* [mhdawson](https://github.com/mhdawson) - **Michael Dawson** <[email protected]>
<del>* [misterdjules](https://github.com/misterdjules) - **Julien Gilli** <[email protected]>
<del>* [mscdex](https://github.com/mscdex) - **Brian White** <[email protected]>
<del>* [ofrobots](https://github.com/ofrobots) - **Ali Ijaz Sheikh** <[email protected]>
<del>* [orangemocha](https://github.com/orangemocha) - **Alexis Campailla** <[email protected]>
<del>* [rvagg](https://github.com/rvagg) - **Rod Vagg** <[email protected]>
<del>* [shigeki](https://github.com/shigeki) - **Shigeki Ohtsu** <[email protected]>
<del>* [trevnorris](https://github.com/trevnorris) - **Trevor Norris** <[email protected]>
<del>* [Trott](https://github.com/Trott) - **Rich Trott** <[email protected]>
<add>* [addaleax](https://github.com/addaleax) -
<add>**Anna Henningsen** <[email protected]>
<add>* [bnoordhuis](https://github.com/bnoordhuis) -
<add>**Ben Noordhuis** <[email protected]>
<add>* [ChALkeR](https://github.com/ChALkeR) -
<add>**Сковорода Никита Андреевич** <[email protected]>
<add>* [chrisdickinson](https://github.com/chrisdickinson) -
<add>**Chris Dickinson** <[email protected]>
<add>* [cjihrig](https://github.com/cjihrig) -
<add>**Colin Ihrig** <[email protected]>
<add>* [evanlucas](https://github.com/evanlucas) -
<add>**Evan Lucas** <[email protected]>
<add>* [fishrock123](https://github.com/fishrock123) -
<add>**Jeremiah Senkpiel** <[email protected]>
<add>* [indutny](https://github.com/indutny) -
<add>**Fedor Indutny** <[email protected]>
<add>* [jasnell](https://github.com/jasnell) -
<add>**James M Snell** <[email protected]>
<add>* [mhdawson](https://github.com/mhdawson) -
<add>**Michael Dawson** <[email protected]>
<add>* [misterdjules](https://github.com/misterdjules) -
<add>**Julien Gilli** <[email protected]>
<add>* [mscdex](https://github.com/mscdex) -
<add>**Brian White** <[email protected]>
<add>* [ofrobots](https://github.com/ofrobots) -
<add>**Ali Ijaz Sheikh** <[email protected]>
<add>* [orangemocha](https://github.com/orangemocha) -
<add>**Alexis Campailla** <[email protected]>
<add>* [rvagg](https://github.com/rvagg) -
<add>**Rod Vagg** <[email protected]>
<add>* [shigeki](https://github.com/shigeki) -
<add>**Shigeki Ohtsu** <[email protected]>
<add>* [trevnorris](https://github.com/trevnorris) -
<add>**Trevor Norris** <[email protected]>
<add>* [Trott](https://github.com/Trott) -
<add>**Rich Trott** <[email protected]>
<ide>
<ide> ### Collaborators
<ide>
<del>* [andrasq](https://github.com/andrasq) - **Andras** <[email protected]>
<del>* [AndreasMadsen](https://github.com/AndreasMadsen) - **Andreas Madsen** <[email protected]>
<del>* [bengl](https://github.com/bengl) - **Bryan English** <[email protected]>
<del>* [benjamingr](https://github.com/benjamingr) - **Benjamin Gruenbaum** <[email protected]>
<del>* [bmeck](https://github.com/bmeck) - **Bradley Farias** <[email protected]>
<del>* [brendanashworth](https://github.com/brendanashworth) - **Brendan Ashworth** <[email protected]>
<del>* [bzoz](https://github.com/bzoz) - **Bartosz Sosnowski** <[email protected]>
<del>* [calvinmetcalf](https://github.com/calvinmetcalf) - **Calvin Metcalf** <[email protected]>
<del>* [claudiorodriguez](https://github.com/claudiorodriguez) - **Claudio Rodriguez** <[email protected]>
<del>* [domenic](https://github.com/domenic) - **Domenic Denicola** <[email protected]>
<del>* [eljefedelrodeodeljefe](https://github.com/eljefedelrodeodeljefe) - **Robert Jefe Lindstaedt** <[email protected]>
<del>* [estliberitas](https://github.com/estliberitas) - **Alexander Makarenko** <[email protected]>
<del>* [firedfox](https://github.com/firedfox) - **Daniel Wang** <[email protected]>
<del>* [geek](https://github.com/geek) - **Wyatt Preul** <[email protected]>
<del>* [iarna](https://github.com/iarna) - **Rebecca Turner** <[email protected]>
<del>* [isaacs](https://github.com/isaacs) - **Isaac Z. Schlueter** <[email protected]>
<del>* [iWuzHere](https://github.com/iWuzHere) - **Imran Iqbal** <[email protected]>
<del>* [JacksonTian](https://github.com/JacksonTian) - **Jackson Tian** <[email protected]>
<del>* [jbergstroem](https://github.com/jbergstroem) - **Johan Bergström** <[email protected]>
<del>* [jhamhader](https://github.com/jhamhader) - **Yuval Brik** <[email protected]>
<del>* [joaocgreis](https://github.com/joaocgreis) - **João Reis** <[email protected]>
<del>* [julianduque](https://github.com/julianduque) - **Julian Duque** <[email protected]>
<del>* [JungMinu](https://github.com/JungMinu) - **Minwoo Jung** <[email protected]>
<del>* [lance](https://github.com/lance) - **Lance Ball** <[email protected]>
<del>* [lxe](https://github.com/lxe) - **Aleksey Smolenchuk** <[email protected]>
<del>* [matthewloring](https://github.com/matthewloring) - **Matthew Loring** <[email protected]>
<del>* [mcollina](https://github.com/mcollina) - **Matteo Collina** <[email protected]>
<del>* [micnic](https://github.com/micnic) - **Nicu Micleușanu** <[email protected]>
<del>* [mikeal](https://github.com/mikeal) - **Mikeal Rogers** <[email protected]>
<del>* [monsanto](https://github.com/monsanto) - **Christopher Monsanto** <[email protected]>
<del>* [Olegas](https://github.com/Olegas) - **Oleg Elifantiev** <[email protected]>
<del>* [othiym23](https://github.com/othiym23) - **Forrest L Norvell** <[email protected]>
<del>* [petkaantonov](https://github.com/petkaantonov) - **Petka Antonov** <[email protected]>
<del>* [phillipj](https://github.com/phillipj) - **Phillip Johnsen** <[email protected]>
<del>* [piscisaureus](https://github.com/piscisaureus) - **Bert Belder** <[email protected]>
<del>* [pmq20](https://github.com/pmq20) - **Minqi Pan** <[email protected]>
<del>* [princejwesley](https://github.com/princejwesley) - **Prince John Wesley** <[email protected]>
<del>* [qard](https://github.com/qard) - **Stephen Belanger** <[email protected]>
<del>* [rlidwka](https://github.com/rlidwka) - **Alex Kocharin** <[email protected]>
<del>* [rmg](https://github.com/rmg) - **Ryan Graham** <[email protected]>
<del>* [robertkowalski](https://github.com/robertkowalski) - **Robert Kowalski** <[email protected]>
<del>* [romankl](https://github.com/romankl) - **Roman Klauke** <[email protected]>
<del>* [ronkorving](https://github.com/ronkorving) - **Ron Korving** <[email protected]>
<del>* [RReverser](https://github.com/RReverser) - **Ingvar Stepanyan** <[email protected]>
<del>* [saghul](https://github.com/saghul) - **Saúl Ibarra Corretgé** <[email protected]>
<del>* [sam-github](https://github.com/sam-github) - **Sam Roberts** <[email protected]>
<del>* [santigimeno](https://github.com/santigimeno) - **Santiago Gimeno** <[email protected]>
<del>* [seishun](https://github.com/seishun) - **Nikolai Vavilov** <[email protected]>
<del>* [silverwind](https://github.com/silverwind) - **Roman Reiss** <[email protected]>
<del>* [srl295](https://github.com/srl295) - **Steven R Loomis** <[email protected]>
<del>* [stefanmb](https://github.com/stefanmb) - **Stefan Budeanu** <[email protected]>
<del>* [targos](https://github.com/targos) - **Michaël Zasso** <[email protected]>
<del>* [tellnes](https://github.com/tellnes) - **Christian Tellnes** <[email protected]>
<del>* [thealphanerd](https://github.com/thealphanerd) - **Myles Borins** <[email protected]>
<del>* [thefourtheye](https://github.com/thefourtheye) - **Sakthipriyan Vairamani** <[email protected]>
<del>* [thekemkid](https://github.com/thekemkid) - **Glen Keane** <[email protected]>
<del>* [thlorenz](https://github.com/thlorenz) - **Thorsten Lorenz** <[email protected]>
<del>* [tunniclm](https://github.com/tunniclm) - **Mike Tunnicliffe** <[email protected]>
<del>* [vkurchatkin](https://github.com/vkurchatkin) - **Vladimir Kurchatkin** <[email protected]>
<del>* [whitlockjc](https://github.com/whitlockjc) - **Jeremy Whitlock** <[email protected]>
<del>* [yorkie](https://github.com/yorkie) - **Yorkie Liu** <[email protected]>
<del>* [yosuke-furukawa](https://github.com/yosuke-furukawa) - **Yosuke Furukawa** <[email protected]>
<del>* [zkat](https://github.com/zkat) - **Kat Marchán** <[email protected]>
<add>* [andrasq](https://github.com/andrasq) -
<add>**Andras** <[email protected]>
<add>* [AndreasMadsen](https://github.com/AndreasMadsen) -
<add>**Andreas Madsen** <[email protected]>
<add>* [bengl](https://github.com/bengl) -
<add>**Bryan English** <[email protected]>
<add>* [benjamingr](https://github.com/benjamingr) -
<add>**Benjamin Gruenbaum** <[email protected]>
<add>* [bmeck](https://github.com/bmeck) -
<add>**Bradley Farias** <[email protected]>
<add>* [brendanashworth](https://github.com/brendanashworth) -
<add>**Brendan Ashworth** <[email protected]>
<add>* [bzoz](https://github.com/bzoz) -
<add>**Bartosz Sosnowski** <[email protected]>
<add>* [calvinmetcalf](https://github.com/calvinmetcalf) -
<add>**Calvin Metcalf** <[email protected]>
<add>* [claudiorodriguez](https://github.com/claudiorodriguez) -
<add>**Claudio Rodriguez** <[email protected]>
<add>* [domenic](https://github.com/domenic) -
<add>**Domenic Denicola** <[email protected]>
<add>* [eljefedelrodeodeljefe](https://github.com/eljefedelrodeodeljefe) -
<add>**Robert Jefe Lindstaedt** <[email protected]>
<add>* [estliberitas](https://github.com/estliberitas) -
<add>**Alexander Makarenko** <[email protected]>
<add>* [firedfox](https://github.com/firedfox) -
<add>**Daniel Wang** <[email protected]>
<add>* [geek](https://github.com/geek) -
<add>**Wyatt Preul** <[email protected]>
<add>* [iarna](https://github.com/iarna) -
<add>**Rebecca Turner** <[email protected]>
<add>* [isaacs](https://github.com/isaacs) -
<add>**Isaac Z. Schlueter** <[email protected]>
<add>* [iWuzHere](https://github.com/iWuzHere) -
<add>**Imran Iqbal** <[email protected]>
<add>* [JacksonTian](https://github.com/JacksonTian) -
<add>**Jackson Tian** <[email protected]>
<add>* [jbergstroem](https://github.com/jbergstroem) -
<add>**Johan Bergström** <[email protected]>
<add>* [jhamhader](https://github.com/jhamhader) -
<add>**Yuval Brik** <[email protected]>
<add>* [joaocgreis](https://github.com/joaocgreis) -
<add>**João Reis** <[email protected]>
<add>* [julianduque](https://github.com/julianduque) -
<add>**Julian Duque** <[email protected]>
<add>* [JungMinu](https://github.com/JungMinu) -
<add>**Minwoo Jung** <[email protected]>
<add>* [lance](https://github.com/lance) -
<add>**Lance Ball** <[email protected]>
<add>* [lxe](https://github.com/lxe) -
<add>**Aleksey Smolenchuk** <[email protected]>
<add>* [matthewloring](https://github.com/matthewloring) -
<add>**Matthew Loring** <[email protected]>
<add>* [mcollina](https://github.com/mcollina) -
<add>**Matteo Collina** <[email protected]>
<add>* [micnic](https://github.com/micnic) -
<add>**Nicu Micleușanu** <[email protected]>
<add>* [mikeal](https://github.com/mikeal) -
<add>**Mikeal Rogers** <[email protected]>
<add>* [monsanto](https://github.com/monsanto) -
<add>**Christopher Monsanto** <[email protected]>
<add>* [Olegas](https://github.com/Olegas) -
<add>**Oleg Elifantiev** <[email protected]>
<add>* [othiym23](https://github.com/othiym23) -
<add>**Forrest L Norvell** <[email protected]>
<add>* [petkaantonov](https://github.com/petkaantonov) -
<add>**Petka Antonov** <[email protected]>
<add>* [phillipj](https://github.com/phillipj) -
<add>**Phillip Johnsen** <[email protected]>
<add>* [piscisaureus](https://github.com/piscisaureus) -
<add>**Bert Belder** <[email protected]>
<add>* [pmq20](https://github.com/pmq20) -
<add>**Minqi Pan** <[email protected]>
<add>* [princejwesley](https://github.com/princejwesley) -
<add>**Prince John Wesley** <[email protected]>
<add>* [qard](https://github.com/qard) -
<add>**Stephen Belanger** <[email protected]>
<add>* [rlidwka](https://github.com/rlidwka) -
<add>**Alex Kocharin** <[email protected]>
<add>* [rmg](https://github.com/rmg) -
<add>**Ryan Graham** <[email protected]>
<add>* [robertkowalski](https://github.com/robertkowalski) -
<add>**Robert Kowalski** <[email protected]>
<add>* [romankl](https://github.com/romankl) -
<add>**Roman Klauke** <[email protected]>
<add>* [ronkorving](https://github.com/ronkorving) -
<add>**Ron Korving** <[email protected]>
<add>* [RReverser](https://github.com/RReverser) -
<add>**Ingvar Stepanyan** <[email protected]>
<add>* [saghul](https://github.com/saghul) -
<add>**Saúl Ibarra Corretgé** <[email protected]>
<add>* [sam-github](https://github.com/sam-github) -
<add>**Sam Roberts** <[email protected]>
<add>* [santigimeno](https://github.com/santigimeno) -
<add>**Santiago Gimeno** <[email protected]>
<add>* [seishun](https://github.com/seishun) -
<add>**Nikolai Vavilov** <[email protected]>
<add>* [silverwind](https://github.com/silverwind) -
<add>**Roman Reiss** <[email protected]>
<add>* [srl295](https://github.com/srl295) -
<add>**Steven R Loomis** <[email protected]>
<add>* [stefanmb](https://github.com/stefanmb) -
<add>**Stefan Budeanu** <[email protected]>
<add>* [targos](https://github.com/targos) -
<add>**Michaël Zasso** <[email protected]>
<add>* [tellnes](https://github.com/tellnes) -
<add>**Christian Tellnes** <[email protected]>
<add>* [thealphanerd](https://github.com/thealphanerd) -
<add>**Myles Borins** <[email protected]>
<add>* [thefourtheye](https://github.com/thefourtheye) -
<add>**Sakthipriyan Vairamani** <[email protected]>
<add>* [thekemkid](https://github.com/thekemkid) -
<add>**Glen Keane** <[email protected]>
<add>* [thlorenz](https://github.com/thlorenz) -
<add>**Thorsten Lorenz** <[email protected]>
<add>* [tunniclm](https://github.com/tunniclm) -
<add>**Mike Tunnicliffe** <[email protected]>
<add>* [vkurchatkin](https://github.com/vkurchatkin) -
<add>**Vladimir Kurchatkin** <[email protected]>
<add>* [whitlockjc](https://github.com/whitlockjc) -
<add>**Jeremy Whitlock** <[email protected]>
<add>* [yorkie](https://github.com/yorkie) -
<add>**Yorkie Liu** <[email protected]>
<add>* [yosuke-furukawa](https://github.com/yosuke-furukawa) -
<add>**Yosuke Furukawa** <[email protected]>
<add>* [zkat](https://github.com/zkat) -
<add>**Kat Marchán** <[email protected]>
<ide>
<ide> Collaborators & CTC members follow the [COLLABORATOR_GUIDE.md](./COLLABORATOR_GUIDE.md) in
<ide> maintaining the Node.js project.
<ide> maintaining the Node.js project.
<ide>
<ide> Releases of Node.js and io.js will be signed with one of the following GPG keys:
<ide>
<del>* **Chris Dickinson** <[email protected]> `9554F04D7259F04124DE6B476D5A82AC7E37093B`
<del>* **Colin Ihrig** <[email protected]> `94AE36675C464D64BAFA68DD7434390BDBE9B9C5`
<del>* **Evan Lucas** <[email protected]> `B9AE9905FFD7803F25714661B63B535A4C206CA9`
<del>* **James M Snell** <[email protected]> `71DCFD284A79C3B38668286BC97EC7A07EDE3FC1`
<del>* **Jeremiah Senkpiel** <[email protected]> `FD3A5288F042B6850C66B31F09FE44734EB7990E`
<del>* **Myles Borins** <[email protected]> `C4F0DFFF4E8C1A8236409D08E73BC641CC11F4C8`
<del>* **Rod Vagg** <[email protected]> `DD8F2338BAE7501E3DD5AC78C273792F7D83545D`
<del>* **Sam Roberts** <[email protected]> `0034A06D9D9B0064CE8ADF6BF1747F4AD2306D93`
<add>* **Chris Dickinson** <[email protected]>
<add>`9554F04D7259F04124DE6B476D5A82AC7E37093B`
<add>* **Colin Ihrig** <[email protected]>
<add>`94AE36675C464D64BAFA68DD7434390BDBE9B9C5`
<add>* **Evan Lucas** <[email protected]>
<add>`B9AE9905FFD7803F25714661B63B535A4C206CA9`
<add>* **James M Snell** <[email protected]>
<add>`71DCFD284A79C3B38668286BC97EC7A07EDE3FC1`
<add>* **Jeremiah Senkpiel** <[email protected]>
<add>`FD3A5288F042B6850C66B31F09FE44734EB7990E`
<add>* **Myles Borins** <[email protected]>
<add>`C4F0DFFF4E8C1A8236409D08E73BC641CC11F4C8`
<add>* **Rod Vagg** <[email protected]>
<add>`DD8F2338BAE7501E3DD5AC78C273792F7D83545D`
<add>* **Sam Roberts** <[email protected]>
<add>`0034A06D9D9B0064CE8ADF6BF1747F4AD2306D93`
<ide>
<ide> The full set of trusted release keys can be imported by running:
<ide>
<del>```
<add>```shell
<ide> gpg --keyserver pool.sks-keyservers.net --recv-keys 9554F04D7259F04124DE6B476D5A82AC7E37093B
<ide> gpg --keyserver pool.sks-keyservers.net --recv-keys 94AE36675C464D64BAFA68DD7434390BDBE9B9C5
<ide> gpg --keyserver pool.sks-keyservers.net --recv-keys 0034A06D9D9B0064CE8ADF6BF1747F4AD2306D93
<ide> gpg --keyserver pool.sks-keyservers.net --recv-keys C4F0DFFF4E8C1A8236409D08E73B
<ide> gpg --keyserver pool.sks-keyservers.net --recv-keys B9AE9905FFD7803F25714661B63B535A4C206CA9
<ide> ```
<ide>
<del>See the section above on [Verifying Binaries](#verifying-binaries) for
<del>details on what to do with these keys to verify that a downloaded file is official.
<add>See the section above on [Verifying Binaries](#verifying-binaries) for details
<add>on what to do with these keys to verify that a downloaded file is official.
<ide>
<ide> Previous releases of Node.js have been signed with one of the following GPG
<ide> keys:
<ide>
<del>* **Isaac Z. Schlueter** <[email protected]> `93C7E9E91B49E432C2F75674B0A78B0A6C481CF6`
<del>* **Julien Gilli** <[email protected]> `114F43EE0176B71C7BC219DD50A3051F888C628D`
<del>* **Timothy J Fontaine** <[email protected]> `7937DFD2AB06298B2293C3187D33FF9D0246406D`
<add>* **Isaac Z. Schlueter** <[email protected]>
<add>`93C7E9E91B49E432C2F75674B0A78B0A6C481CF6`
<add>* **Julien Gilli** <[email protected]>
<add>`114F43EE0176B71C7BC219DD50A3051F888C628D`
<add>* **Timothy J Fontaine** <[email protected]>
<add>`7937DFD2AB06298B2293C3187D33FF9D0246406D`
<ide>
<ide> [Website]: https://nodejs.org/en/
<ide> [Contributing to the project]: CONTRIBUTING.md | 1 |
Python | Python | fix python3 compatibility | 10f49132889113c44be1e35e8fb7a768dd08a656 | <ide><path>libcloud/compute/drivers/libvirt_driver.py
<ide> def __init__(self, host, user='root', ssh_key=None,
<ide> # if ssh key is string create temp file
<ide> if not os.path.isfile(ssh_key):
<ide> key_temp_file = NamedTemporaryFile(delete=False)
<del> key_temp_file.write(ssh_key)
<add> key_temp_file.write(ssh_key.encode())
<ide> key_temp_file.close()
<ide> self.secret = key_temp_file.name
<ide> self.temp_key = self.secret
<ide> def _run_command(self, cmd, su=False):
<ide> except Exception as exc:
<ide> log.warn('Failed to run "%s" at %s: %r', cmd, self.host, exc)
<ide>
<del> return {'output': output, 'error': error}
<add> return {'output': output.decode(), 'error': error.decode()}
<ide>
<ide> def disconnect(self):
<ide> # Close the libvirt connection to the hypevisor. | 1 |
Python | Python | change the way sentinel tokens can retrived | 03ae1f060bbb8cfd8ba691385b35a7ae09adcf33 | <ide><path>src/transformers/models/t5/tokenization_t5.py
<ide> class T5Tokenizer(PreTrainedTokenizer):
<ide> pad_token (`str`, *optional*, defaults to `"<pad>"`):
<ide> The token used for padding, for example when batching sequences of different lengths.
<ide> extra_ids (`int`, *optional*, defaults to 100):
<del> Add a number of extra ids added to the end of the vocabulary for use as sentinels. These tokens are
<del> accessible as "<extra_id_{%d}>" where "{%d}" is a number between 0 and extra_ids-1. Extra tokens are
<del> indexed from the end of the vocabulary up to beginning ("<extra_id_0>" is the last token in the vocabulary
<del> like in T5 preprocessing see
<del> [here](https://github.com/google-research/text-to-text-transfer-transformer/blob/9fd7b14a769417be33bc6c850f9598764913c833/t5/data/preprocessors.py#L2117)).
<del> additional_special_tokens (`List[str]`, *optional*):
<add> Add a number of extra ids added to the vocabulary for use as sentinels. These tokens are
<add> accessible as "<extra_id_{%d}>" where "{%d}" is a number between 0 and extra_ids-1. These tokens can be
<add> retrieved by calling get_sentinel_tokens method and token ids can be by calling get_sentinel_token_ids
<add> method
<add> additional_special_tokens (`List[str]`, *optional*):
<ide> Additional special tokens used by the tokenizer.
<ide> sp_model_kwargs (`dict`, *optional*):
<ide> Will be passed to the `SentencePieceProcessor.__init__()` method. The [Python wrapper for
<ide> def get_special_tokens_mask(
<ide> return ([0] * len(token_ids_0)) + [1]
<ide> return ([0] * len(token_ids_0)) + [1] + ([0] * len(token_ids_1)) + [1]
<ide>
<add> def get_sentinel_tokens(self):
<add> return list(
<add> set(filter(lambda x: bool(re.search("<extra_id_\d+>", x)) is not None, self.additional_special_tokens))
<add> )
<add>
<add> def get_sentinel_token_ids(self):
<add> return [self._convert_token_to_id(token) for token in self.get_sentinel_tokens()]
<add>
<ide> def _add_eos_if_not_present(self, token_ids: List[int]) -> List[int]:
<ide> """Do not add eos again if user already added it."""
<ide> if len(token_ids) > 0 and token_ids[-1] == self.eos_token_id:
<ide><path>src/transformers/models/t5/tokenization_t5_fast.py
<ide>
<ide>
<ide> import os
<add>import re
<ide> import warnings
<ide> from shutil import copyfile
<ide> from typing import List, Optional, Tuple
<ide> class T5TokenizerFast(PreTrainedTokenizerFast):
<ide> pad_token (`str`, *optional*, defaults to `"<pad>"`):
<ide> The token used for padding, for example when batching sequences of different lengths.
<ide> extra_ids (`int`, *optional*, defaults to 100):
<del> Add a number of extra ids added to the end of the vocabulary for use as sentinels. These tokens are
<del> accessible as "<extra_id_{%d}>" where "{%d}" is a number between 0 and extra_ids-1. Extra tokens are
<del> indexed from the end of the vocabulary up to beginning ("<extra_id_0>" is the last token in the vocabulary
<del> like in T5 preprocessing see
<del> [here](https://github.com/google-research/text-to-text-transfer-transformer/blob/9fd7b14a769417be33bc6c850f9598764913c833/t5/data/preprocessors.py#L2117)).
<add> Add a number of extra ids added to the vocabulary for use as sentinels. These tokens are accessible as
<add> "<extra_id_{%d}>" where "{%d}" is a number between 0 and extra_ids-1. These tokens can be retrieved by
<add> calling get_sentinel_tokens method and token ids can be by calling get_sentinel_token_ids method
<ide> additional_special_tokens (`List[str]`, *optional*):
<ide> Additional special tokens used by the tokenizer.
<ide> """
<ide> def create_token_type_ids_from_sequences(
<ide> if token_ids_1 is None:
<ide> return len(token_ids_0 + eos) * [0]
<ide> return len(token_ids_0 + eos + token_ids_1 + eos) * [0]
<add>
<add> def get_sentinel_tokens(self):
<add> return list(
<add> set(filter(lambda x: bool(re.search("<extra_id_\d+>", x)) is not None, self.additional_special_tokens))
<add> )
<add>
<add> def get_sentinel_token_ids(self):
<add> return [self.convert_tokens_to_ids(token) for token in self.get_sentinel_tokens()]
<ide><path>tests/models/t5/test_tokenization_t5.py
<ide> # limitations under the License.
<ide> import json
<ide> import os
<add>import re
<ide> import tempfile
<ide> import unittest
<ide>
<ide> def test_tokenizer_integration(self):
<ide> model_name="t5-base",
<ide> revision="5a7ff2d8f5117c194c7e32ec1ccbf04642cca99b",
<ide> )
<add>
<add> def test_get_sentinel_tokens(self):
<add> tokenizer = T5Tokenizer(SAMPLE_VOCAB, extra_ids=10)
<add> sentinel_tokens = tokenizer.get_sentinel_tokens()
<add> self.assertEquals(len(sentinel_tokens), 10)
<add> self.assertListEqual(sorted(sentinel_tokens), sorted([f"<extra_id_{str(i)}>" for i in range(0, 10)]))
<add> self.assertTrue([re.search("<extra_id_\d+>", token) is not None for token in sentinel_tokens])
<add>
<add> def test_get_sentinel_token_ids(self):
<add> tokenizer = T5Tokenizer(SAMPLE_VOCAB, extra_ids=10)
<add> self.assertListEqual(sorted(tokenizer.get_sentinel_token_ids()), sorted([i for i in range(1000, 1010)]))
<add>
<add> def test_get_sentinel_tokens_for_fasttokenizer(self):
<add> tokenizer = T5TokenizerFast(SAMPLE_VOCAB, extra_ids=10)
<add> sentinel_tokens = tokenizer.get_sentinel_tokens()
<add> self.assertEquals(len(sentinel_tokens), 10)
<add> self.assertListEqual(sorted(sentinel_tokens), sorted([f"<extra_id_{str(i)}>" for i in range(0, 10)]))
<add> self.assertTrue([re.search("<extra_id_\d+>", token) is not None for token in sentinel_tokens])
<add>
<add> def test_get_sentinel_token_ids_for_fasttokenizer(self):
<add> tokenizer = T5TokenizerFast(SAMPLE_VOCAB, extra_ids=10)
<add> self.assertListEqual(sorted(tokenizer.get_sentinel_token_ids()), sorted([i for i in range(1000, 1010)])) | 3 |
Text | Text | remove readme link to non-existent upgrade guide | 6d367b9e2c9be19ab4c4afce7981ff47c4b33eca | <ide><path>README.md
<ide> You can use Gitpod, an online IDE(which is free for Open Source) for contributin
<ide> ## Resources
<ide>
<ide> * [Changelog](https://github.com/axios/axios/blob/v1.x/CHANGELOG.md)
<del>* [Upgrade Guide](https://github.com/axios/axios/blob/v1.x/UPGRADE_GUIDE.md)
<ide> * [Ecosystem](https://github.com/axios/axios/blob/v1.x/ECOSYSTEM.md)
<ide> * [Contributing Guide](https://github.com/axios/axios/blob/v1.x/CONTRIBUTING.md)
<ide> * [Code of Conduct](https://github.com/axios/axios/blob/v1.x/CODE_OF_CONDUCT.md) | 1 |
Javascript | Javascript | call gc() explicitly to avoid oom | 4ce744a24b52659dc3b365a32fddcc1b92fd67c0 | <ide><path>test/addons/stringbytes-external-exceed-max/test-stringbytes-external-exceed-max-by-1-binary.js
<add>// Flags: --expose-gc
<ide> 'use strict';
<ide>
<ide> const common = require('../../common');
<ide> common.expectsError(function() {
<ide> type: Error
<ide> });
<ide>
<add>// FIXME: Free the memory early to avoid OOM.
<add>// REF: https://github.com/nodejs/reliability/issues/12#issuecomment-412619655
<add>global.gc();
<ide> let maxString = buf.toString('latin1', 1);
<ide> assert.strictEqual(maxString.length, kStringMaxLength);
<del>// Free the memory early instead of at the end of the next assignment
<ide> maxString = undefined;
<add>global.gc();
<ide>
<ide> maxString = buf.toString('latin1', 0, kStringMaxLength);
<ide> assert.strictEqual(maxString.length, kStringMaxLength); | 1 |
Javascript | Javascript | remove `chrome` from `testem.travis-browsers.json` | 92b459ca954fe395247a029375b4bd31572a4b83 | <ide><path>bin/run-travis-browser-tests.js
<ide> function run(command, _args) {
<ide> }
<ide>
<ide>
<del>function setupChrome() {
<del> return RSVP.resolve()
<del> .then(function() {
<del> return run('sudo', ['apt-get', 'install', '-y', 'google-chrome-stable']);
<del> })
<del> .then(function() {
<del> return run('/usr/bin/google-chrome', ['--version']);
<del> });
<del>}
<del>
<ide> RSVP.resolve()
<del> .then(function() {
<del> return run('sudo', ['apt-get', 'update']);
<del> })
<del> .then(function() {
<del> return setupChrome();
<del> })
<ide> .then(function() {
<ide> return run('./node_modules/.bin/testem', ['launchers']);
<ide> })
<ide><path>testem.travis-browsers.js
<ide> module.exports = {
<ide> disable_watching: true,
<ide> launch_in_dev: [
<ide> 'Firefox',
<del> 'Chrome'
<ide> ],
<ide> launch_in_ci: [
<ide> 'Firefox',
<del> 'Chrome'
<ide> ],
<ide> reporter: new FailureOnlyReporter()
<ide> }; | 2 |
Python | Python | remove obsolete apps | 03339501ab53794b363df9838978d15631821afe | <ide><path>tests/test_apps/config_module_app.py
<del>import os
<del>import flask
<del>here = os.path.abspath(os.path.dirname(__file__))
<del>app = flask.Flask(__name__)
<ide><path>tests/test_apps/config_package_app/__init__.py
<del>import os
<del>import flask
<del>here = os.path.abspath(os.path.dirname(__file__))
<del>app = flask.Flask(__name__)
<ide><path>tests/test_apps/lib/python2.5/site-packages/site_app.py
<del>import flask
<del>
<del>app = flask.Flask(__name__)
<ide><path>tests/test_apps/lib/python2.5/site-packages/site_package/__init__.py
<del>import flask
<del>
<del>app = flask.Flask(__name__)
<ide><path>tests/test_apps/main_app.py
<del>import flask
<del>
<del># Test Flask initialization with main module.
<del>app = flask.Flask('__main__')
<ide><path>tests/test_apps/path/installed_package/__init__.py
<del>import flask
<del>
<del>app = flask.Flask(__name__) | 6 |
PHP | PHP | correct phpdoc code style | cd9a86b4c0dfea64b59b56effacaca49769c5ed6 | <ide><path>src/Illuminate/Foundation/Testing/TestResponse.php
<ide> public function assertJsonCount(int $count, $key = null)
<ide> /**
<ide> * Assert that the response has the given JSON validation errors for the given keys.
<ide> *
<del> * @param string|array $keys
<del> * @param string $responseKey
<add> * @param string|array $keys
<add> * @param string $responseKey
<ide> * @return $this
<ide> */
<ide> public function assertJsonValidationErrors($keys, string $responseKey = 'errors')
<ide> public function assertJsonValidationErrors($keys, string $responseKey = 'errors'
<ide> /**
<ide> * Assert that the response has no JSON validation errors for the given keys.
<ide> *
<del> * @param string|array $keys
<del> * @param string $responseKey
<add> * @param string|array $keys
<add> * @param string $responseKey
<ide> * @return $this
<ide> */
<ide> public function assertJsonMissingValidationErrors($keys = null, string $responseKey = 'errors') | 1 |
PHP | PHP | fix header manipulation | 210fd896613ff4d550cd51d8963f13f42b1eaf4b | <ide><path>src/TestSuite/IntegrationTestCase.php
<ide> protected function _buildRequest($url, $method, $data) {
<ide> 'session' => $session,
<ide> ];
<ide> if (isset($this->_request['headers'])) {
<del> $props['environment'] = $this->_request['headers'];
<add> $env = [];
<add> foreach ($this->_request['headers'] as $k => $v) {
<add> $env['HTTP_' . str_replace('-', '_', strtoupper($k))] = $v;
<add> }
<add> $props['environment'] = $env;
<ide> unset($this->_request['headers']);
<ide> }
<ide> $props += $this->_request;
<ide><path>tests/TestCase/TestSuite/IntegrationTestCaseTest.php
<ide> public function testRequestBuilding() {
<ide> $this->session(['User' => ['id' => 1, 'username' => 'mark']]);
<ide> $request = $this->_buildRequest('/tasks/add', 'POST', ['title' => 'First post']);
<ide>
<add> $this->assertEquals('abc123', $request->header('X-CSRF-Token'));
<ide> $this->assertEquals('tasks/add', $request->url);
<ide> $this->assertEquals(['split_token' => 'def345'], $request->cookies);
<ide> $this->assertEquals(['id' => '1', 'username' => 'mark'], $request->session()->read('User'));
<ide> public function testSendingGet() {
<ide> $this->get('/request_action/test_request_action');
<ide> $this->assertNotEmpty($this->_response);
<ide> $this->assertInstanceOf('Cake\Network\Response', $this->_response);
<add> $this->assertEquals('This is a test', $this->_response->body());
<ide> }
<ide>
<ide> } | 2 |
Javascript | Javascript | remove a couple calls to helpers.each | 4d7fefcdb6bd48a078af6378fba33dbcb63cf747 | <ide><path>src/core/core.controller.js
<ide> helpers.extend(Chart.prototype, /** @lends Chart */ {
<ide> buildOrUpdateControllers: function() {
<ide> var me = this;
<ide> var newControllers = [];
<add> var datasets = me.data.datasets;
<add> var i, ilen;
<ide>
<del> helpers.each(me.data.datasets, function(dataset, datasetIndex) {
<del> var meta = me.getDatasetMeta(datasetIndex);
<add> for (i = 0, ilen = datasets.length; i < ilen; i++) {
<add> var dataset = datasets[i];
<add> var meta = me.getDatasetMeta(i);
<ide> var type = dataset.type || me.config.type;
<ide>
<ide> if (meta.type && meta.type !== type) {
<del> me.destroyDatasetMeta(datasetIndex);
<del> meta = me.getDatasetMeta(datasetIndex);
<add> me.destroyDatasetMeta(i);
<add> meta = me.getDatasetMeta(i);
<ide> }
<ide> meta.type = type;
<ide> meta.order = dataset.order || 0;
<del> meta.index = datasetIndex;
<add> meta.index = i;
<ide>
<ide> if (meta.controller) {
<del> meta.controller.updateIndex(datasetIndex);
<add> meta.controller.updateIndex(i);
<ide> meta.controller.linkScales();
<ide> } else {
<ide> var ControllerClass = controllers[meta.type];
<ide> if (ControllerClass === undefined) {
<ide> throw new Error('"' + meta.type + '" is not a chart type.');
<ide> }
<ide>
<del> meta.controller = new ControllerClass(me, datasetIndex);
<add> meta.controller = new ControllerClass(me, i);
<ide> newControllers.push(meta.controller);
<ide> }
<del> }, me);
<add> }
<ide>
<ide> return newControllers;
<ide> },
<ide> helpers.extend(Chart.prototype, /** @lends Chart */ {
<ide>
<ide> update: function(config) {
<ide> var me = this;
<add> var i, ilen;
<ide>
<ide> if (!config || typeof config !== 'object') {
<ide> // backwards compatibility
<ide> helpers.extend(Chart.prototype, /** @lends Chart */ {
<ide> var newControllers = me.buildOrUpdateControllers();
<ide>
<ide> // Make sure all dataset controllers have correct meta data counts
<del> helpers.each(me.data.datasets, function(dataset, datasetIndex) {
<del> me.getDatasetMeta(datasetIndex).controller.buildOrUpdateElements();
<del> }, me);
<add> for (i = 0, ilen = me.data.datasets.length; i < ilen; i++) {
<add> me.getDatasetMeta(i).controller.buildOrUpdateElements();
<add> }
<ide>
<ide> me.updateLayout();
<ide> | 1 |
Javascript | Javascript | fix some warnings | 7eab70532ef299fff7de79a7351f6b0ed013c38c | <ide><path>utils/fonts_utils.js
<ide> function readFontIndexData(aStream, aIsByte) {
<ide> return aStream.getByte() << 24 | aStream.getByte() << 16 |
<ide> aStream.getByte() << 8 | aStream.getByte();
<ide> }
<add> error(offsize + " is not a valid offset size");
<add> return null;
<ide> };
<ide>
<ide> var offsets = [];
<ide> var Type2Parser = function(aFilePath) {
<ide> dump(subrs);
<ide>
<ide> // Reading Private Dict
<del> var private = font.get("Private");
<del> log("Reading Private Dict (offset: " + private.offset + " size: " + private.size + ")");
<del> aStream.pos = private.offset;
<add> var priv = font.get("Private");
<add> log("Reading Private Dict (offset: " + priv.offset + " size: " + priv.size + ")");
<add> aStream.pos = priv.offset;
<ide>
<ide> var privateDict = [];
<del> for (var i = 0; i < private.size; i++)
<add> for (var i = 0; i < priv.size; i++)
<ide> privateDict.push(aStream.getByte());
<ide> dump("private:" + privateDict);
<ide> parseAsToken(privateDict, CFFDictPrivateDataMap);
<ide> function writeToFile(aBytes, aFilePath) {
<ide>
<ide> var stream = Cc["@mozilla.org/network/file-output-stream;1"]
<ide> .createInstance(Ci.nsIFileOutputStream);
<del> stream.init(file, 0x04 | 0x08 | 0x20, 0600, 0);
<add> stream.init(file, 0x04 | 0x08 | 0x20, 600, 0);
<ide>
<ide> var bos = Cc["@mozilla.org/binaryoutputstream;1"]
<ide> .createInstance(Ci.nsIBinaryOutputStream); | 1 |
Javascript | Javascript | add test case | 85ffe1e8cedb8d574810051e1aba72effa2c36f1 | <ide><path>test/configCases/source-map/module-names/index.js
<add>function getSourceMap(filename) {
<add> var fs = require("fs");
<add> var source = fs.readFileSync(__dirname + "/" + filename + ".map", "utf-8");
<add> var map = JSON.parse(source);
<add> return map;
<add>}
<add>
<add>it("should include test.js in SourceMap", function() {
<add> var map = getSourceMap("bundle0.js");
<add> map.sources.should.containEql("module");
<add> map.sources.should.containEql("fallback");
<add> map.sources.should.containEql("fallback**");
<add> map = getSourceMap("chunk-a.js");
<add> map.sources.should.containEql("fallback*");
<add> map = getSourceMap("chunk-b.js");
<add> map.sources.should.containEql("fallback*");
<add> map.sources.should.containEql("fallback***");
<add>});
<add>
<add>require.ensure(["./test.js"], function(require) {}, "chunk-a");
<add>require.ensure(["./test.js", "./test.js?1"], function(require) {}, "chunk-b");
<ide><path>test/configCases/source-map/module-names/test.js
<add>var foo = {};
<add>
<add>module.exports = foo;
<ide>\ No newline at end of file
<ide><path>test/configCases/source-map/module-names/webpack.config.js
<add>module.exports = {
<add> output: {
<add> chunkFilename: "[name].js",
<add> devtoolModuleFilenameTemplate: "module",
<add> devtoolFallbackModuleFilenameTemplate: "fallback"
<add> },
<add> node: {
<add> __dirname: false,
<add> __filename: false
<add> },
<add> devtool: "source-map"
<add>}; | 3 |
Javascript | Javascript | fix accidental typo | a4a368739c80e799d273b14abf86b49b674df41f | <ide><path>examples/todos-with-undo/components/AddTodo.js
<ide> export default class AddTodo extends Component {
<ide> <form onSubmit={(e) => this.handleSubmit(e)}>
<ide> <input type="text" ref="input" />
<ide> <button>
<del> Addx
<add> Add
<ide> </button>
<ide> </form>
<ide> </div> | 1 |
Ruby | Ruby | expand path of user provided file in runner | 777e5ef3e262b9a5ee79139b7b1befe48faf4307 | <ide><path>railties/lib/rails/commands/runner/runner_command.rb
<ide> def perform(code_or_file = nil, *command_argv)
<ide> if code_or_file == "-"
<ide> eval($stdin.read, TOPLEVEL_BINDING, "stdin")
<ide> elsif File.exist?(code_or_file)
<del> $0 = code_or_file
<del> Kernel.load code_or_file
<add> expanded_file_path = File.expand_path code_or_file
<add> $0 = expanded_file_path
<add> Kernel.load expanded_file_path
<ide> else
<ide> begin
<ide> eval(code_or_file, TOPLEVEL_BINDING, __FILE__, __LINE__) | 1 |
Text | Text | fix incorrect code in java strings | 164f165fcaea7fe21429fb6fe4fe3d2b3b8f6b65 | <ide><path>guide/english/java/strings/index.md
<ide> title: Strings
<ide> ---
<ide> # Strings
<ide>
<del>Strings are sequences of characters. In Java, a `String` is an `Object`. Strings should not be confused with `char` as characters are literally 1 value rather than a sequence of characters. You can still use 1 value within a String, however it is preferred to use `char` when you are checking for 1 character.
<add>Strings are sequences of characters. In Java, a `String` is an `Object`. Strings should not be confused with `char` as characters are literally a single value rather than a sequence of characters. You can still use a single value within a String, however, it is preferred to use `char` when you are checking for a single character.
<ide>
<ide> ```java
<ide> String course = "FCC";
<ide> String str2 = "This is a string";
<ide> String str3 = new String("This is a string");
<ide> ```
<ide>
<del>The answer is: 2 String objects are created. `str` and `str2` both refer to the same object. `str3` has the same content but using `new` forced
<add>The answer is: **2** String objects are created. `str` and `str2` both refer to the same object. `str3` has the same content but using `new` forced
<ide> the creation of a new, distinct, object.
<ide>
<ide> When you create a String literal, the JVM internally checks, what is known as the `String pool`, to see if it can find a similar (content wise)
<ide> public class StringExample{
<ide> char ch[] = {'s','t','r','i','n','g','s'};
<ide> String s2 = new String(ch); // converting char array to string
<ide> String s3 = new String("example"); // creating Java string by new keyword
<del> System.out.println(s1);
<del> System.out.println(s2);
<del> System.out.println(s3);
<add> System.out.println(s1); // prints "java"
<add> System.out.println(s2); // prints "strings"
<add> System.out.println(s3); // prints "example"
<ide> }
<ide> }
<ide> ```
<ide>
<ide> #### Comparing Strings
<del>If you want to compare the value of two String variables, you can't use ==. This is due to the fact that this will compare the references of the variables
<del>and not the values that are linked to them. To compare the stored values of the Strings you use the method equals.
<add>If you want to compare the value of two String variables, you can't use `==`. This is due to the fact that this will compare the references of the variables
<add>and not the values that are linked to them. To compare the stored values of the Strings you use the `.equals()` method.
<ide>
<ide> ```java
<ide> boolean equals(Object obj)
<ide> It returns true if two objects are equal and false otherwise.
<ide> String str = "Hello world";
<ide> String str2 = "Hello world";
<ide>
<del>System.out.println(str == str2); // This prints false
<del>System.out.println(str.equals(str2); // This prints true
<add>System.out.println(str == str2); // This prints true
<add>System.out.println(str.equals(str2)); // This prints true
<ide> ```
<del>The first comparison is false because "==" looks at the references and they aren't the same.
<add>The first comparison is true because "==" looks at the references and they are the same, because the JVM simply returns a reference
<add>to the same `"Hello world"` object created in the String Pool the first time.
<ide>
<del>The second comparison is true because the variables store the same values. In this case "Hello world".
<add>The second comparison is true because the variables store the same values. In this case - `"Hello world"`.
<ide>
<ide> We have several inbuilt methods in String. The following is an example of the String Length() method .
<ide> | 1 |
Javascript | Javascript | show correct version number in api index | 433c8714f3d065a9a842502579b65d0388dd47ec | <ide><path>docs/app/src/docs.js
<ide> angular.module('DocsController', [])
<ide> function($scope, $rootScope, $location, $window, $cookies,
<ide> NG_PAGES, NG_NAVIGATION, NG_VERSION) {
<ide>
<del> $scope.docsVersion = NG_VERSION.isSnapshot ? 'snapshot' : NG_VERSION.version;
<del>
<ide> $scope.navClass = function(navItem) {
<ide> return {
<ide> active: navItem.href && this.currentPage && this.currentPage.path,
<ide> angular.module('DocsController', [])
<ide> Initialize
<ide> ***********************************/
<ide>
<del> $scope.versionNumber = angular.version.full;
<del> $scope.version = angular.version.full + ' ' + angular.version.codeName;
<add> $scope.versionNumber = NG_VERSION.full;
<add> $scope.version = NG_VERSION.full + ' ' + NG_VERSION.codeName;
<ide> $scope.loading = 0;
<ide>
<ide> | 1 |
Python | Python | remove outdated integration test | 72b55d20899fae554b453a9e67682bb26c2e60d2 | <ide><path>tests/integration_tests/applications_test.py
<ide> def _test_application_notop(app, last_dim):
<ide> assert output_shape[-1] == last_dim
<ide>
<ide>
<del>def test_mobilenet_v2_legacy_import():
<del> from keras.applications import mobilenetv2
<del> assert hasattr(mobilenetv2, 'MobileNetV2')
<del> from keras.applications import mobilenet_v2
<del> assert hasattr(mobilenet_v2, 'MobileNetV2')
<del>
<del>
<ide> def test_applications():
<ide> for _ in range(3):
<ide> app, last_dim = random.choice(MODEL_LIST) | 1 |
Javascript | Javascript | note input type restrictions | c434bde109b8e131f569808f8b7451013d5b3698 | <ide><path>src/ng/directive/attrs.js
<ide> *
<ide> * @description
<ide> *
<del> * Sets the `readOnly` attribute on the element, if the expression inside `ngReadonly` is truthy.
<add> * Sets the `readonly` attribute on the element, if the expression inside `ngReadonly` is truthy.
<add> * Note that `readonly` applies only to `input` elements with specific types. [See the input docs on
<add> * MDN](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/input#attr-readonly) for more information.
<ide> *
<del> * A special directive is necessary because we cannot use interpolation inside the `readOnly`
<add> * A special directive is necessary because we cannot use interpolation inside the `readonly`
<ide> * attribute. See the {@link guide/interpolation interpolation guide} for more info.
<ide> *
<ide> * @example | 1 |
Mixed | Text | linkify missing types | fd3a0cfb7c467c8016ad739a473be864425e645d | <ide><path>doc/api/async_hooks.md
<ide> added: v8.1.0
<ide> * `before` {Function} The [`before` callback][].
<ide> * `after` {Function} The [`after` callback][].
<ide> * `destroy` {Function} The [`destroy` callback][].
<del>* Returns: `{AsyncHook}` Instance used for disabling and enabling hooks
<add>* Returns: {AsyncHook} Instance used for disabling and enabling hooks
<ide>
<ide> Registers functions to be called for different lifetime events of each async
<ide> operation.
<ide><path>doc/api/cluster.md
<ide> changes:
<ide> description: This method now returns a reference to `worker`.
<ide> -->
<ide>
<del>* Returns: {Worker} A reference to `worker`.
<add>* Returns: {cluster.Worker} A reference to `worker`.
<ide>
<ide> In a worker, this function will close all servers, wait for the `'close'` event on
<ide> those servers, and then disconnect the IPC channel.
<ide><path>doc/api/console.md
<ide> const { Console } = console;
<ide> ```
<ide>
<ide> ### new Console(stdout[, stderr])
<del>* `stdout` {Writable}
<del>* `stderr` {Writable}
<add>* `stdout` {stream.Writable}
<add>* `stderr` {stream.Writable}
<ide>
<ide> Creates a new `Console` with one or two writable stream instances. `stdout` is a
<ide> writable stream to print log or info output. `stderr` is used for warning or
<ide><path>doc/api/fs.md
<ide> changes:
<ide>
<ide> * `path` {string|Buffer|URL}
<ide> * `mode` {integer} **Default:** `fs.constants.F_OK`
<del>* Returns: `undefined`
<add>* Returns: {undefined}
<ide>
<ide> Synchronously tests a user's permissions for the file or directory specified by
<ide> `path`. The `mode` argument is an optional integer that specifies the
<ide><path>doc/api/http2.md
<ide> they respectively default to:
<ide> added: v8.4.0
<ide> -->
<ide>
<del>* Extends: {Duplex}
<add>* Extends: {stream.Duplex}
<ide>
<ide> Each instance of the `Http2Stream` class represents a bidirectional HTTP/2
<ide> communications stream over an `Http2Session` instance. Any single `Http2Session`
<ide><path>doc/api/process.md
<ide> changes:
<ide>
<ide> * `module` {Object}
<ide> * `filename` {string}
<del>* `flags` {os.constants.dlopen}. Defaults to `os.constants.dlopen.RTLD_LAZY`.
<add>* `flags` {os.constants.dlopen} Defaults to `os.constants.dlopen.RTLD_LAZY`.
<ide>
<ide> The `process.dlopen()` method allows to dynamically load shared
<ide> objects. It is primarily used by `require()` to load
<ide><path>doc/api/readline.md
<ide> Interface's `input` *as if it were provided by the user*.
<ide> added: v0.7.7
<ide> -->
<ide>
<del>* `stream` {Writable}
<add>* `stream` {stream.Writable}
<ide> * `dir` {number}
<ide> * `-1` - to the left from cursor
<ide> * `1` - to the right from cursor
<ide> in a specified direction identified by `dir`.
<ide> added: v0.7.7
<ide> -->
<ide>
<del>* `stream` {Writable}
<add>* `stream` {stream.Writable}
<ide>
<ide> The `readline.clearScreenDown()` method clears the given [TTY][] stream from
<ide> the current position of the cursor down.
<ide> changes:
<ide> -->
<ide>
<ide> * `options` {Object}
<del> * `input` {Readable} The [Readable][] stream to listen to. This option is
<add> * `input` {stream.Readable} The [Readable][] stream to listen to. This option is
<ide> *required*.
<del> * `output` {Writable} The [Writable][] stream to write readline data to.
<add> * `output` {stream.Writable} The [Writable][] stream to write readline data to.
<ide> * `completer` {Function} An optional function used for Tab autocompletion.
<ide> * `terminal` {boolean} `true` if the `input` and `output` streams should be
<ide> treated like a TTY, and have ANSI/VT100 escape codes written to it.
<ide> function completer(linePartial, callback) {
<ide> added: v0.7.7
<ide> -->
<ide>
<del>* `stream` {Writable}
<add>* `stream` {stream.Writable}
<ide> * `x` {number}
<ide> * `y` {number}
<ide>
<ide> given [TTY][] `stream`.
<ide> added: v0.7.7
<ide> -->
<ide>
<del>* `stream` {Readable}
<add>* `stream` {stream.Readable}
<ide> * `interface` {readline.Interface}
<ide>
<ide> The `readline.emitKeypressEvents()` method causes the given [Readable][]
<ide> if (process.stdin.isTTY)
<ide> added: v0.7.7
<ide> -->
<ide>
<del>* `stream` {Writable}
<add>* `stream` {stream.Writable}
<ide> * `dx` {number}
<ide> * `dy` {number}
<ide>
<ide><path>doc/api/repl.md
<ide> changes:
<ide> * `options` {Object|string}
<ide> * `prompt` {string} The input prompt to display. Defaults to `> `
<ide> (with a trailing space).
<del> * `input` {Readable} The Readable stream from which REPL input will be read.
<add> * `input` {stream.Readable} The Readable stream from which REPL input will be read.
<ide> Defaults to `process.stdin`.
<del> * `output` {Writable} The Writable stream to which REPL output will be
<add> * `output` {stream.Writable} The Writable stream to which REPL output will be
<ide> written. Defaults to `process.stdout`.
<ide> * `terminal` {boolean} If `true`, specifies that the `output` should be
<ide> treated as a TTY terminal, and have ANSI/VT100 escape codes written to it.
<ide><path>doc/api/stream.md
<ide> changes:
<ide> -->
<ide>
<ide> * `encoding` {string} The new default encoding
<del>* Returns: `this`
<add>* Returns: {this}
<ide>
<ide> The `writable.setDefaultEncoding()` method sets the default `encoding` for a
<ide> [Writable][] stream.
<ide> A Writable stream in object mode will always ignore the `encoding` argument.
<ide> added: v8.0.0
<ide> -->
<ide>
<del>* Returns: `this`
<add>* Returns: {this}
<ide>
<ide> Destroy the stream, and emit the passed error. After this call, the
<ide> writable stream has ended. Implementors should not override this method,
<ide> readable.isPaused(); // === false
<ide> added: v0.9.4
<ide> -->
<ide>
<del>* Returns: `this`
<add>* Returns: {this}
<ide>
<ide> The `readable.pause()` method will cause a stream in flowing mode to stop
<ide> emitting [`'data'`][] events, switching out of flowing mode. Any data that
<ide> the status of the `highWaterMark`.
<ide> added: v0.9.4
<ide> -->
<ide>
<del>* Returns: `this`
<add>* Returns: {this}
<ide>
<ide> The `readable.resume()` method causes an explicitly paused Readable stream to
<ide> resume emitting [`'data'`][] events, switching the stream into flowing mode.
<ide> added: v0.9.4
<ide> -->
<ide>
<ide> * `encoding` {string} The encoding to use.
<del>* Returns: `this`
<add>* Returns: {this}
<ide>
<ide> The `readable.setEncoding()` method sets the character encoding for
<ide> data read from the Readable stream.
<ide><path>doc/api/tty.md
<ide> is updated whenever the `'resize'` event is emitted.
<ide> added: REPLACEME
<ide> -->
<ide>
<del>* `env` {object} A object containing the environment variables to check.
<add>* `env` {Object} A object containing the environment variables to check.
<ide> Defaults to `process.env`.
<ide> * Returns: {number}
<ide>
<ide><path>tools/doc/type-parser.js
<ide> const jsPrimitives = {
<ide> 'undefined': 'Undefined'
<ide> };
<ide> const jsGlobalTypes = [
<del> 'Error', 'Object', 'Function', 'Array', 'TypedArray', 'Uint8Array',
<del> 'Uint16Array', 'Uint32Array', 'Int8Array', 'Int16Array', 'Int32Array',
<del> 'Uint8ClampedArray', 'Float32Array', 'Float64Array', 'Date', 'RegExp',
<del> 'ArrayBuffer', 'DataView', 'Promise', 'EvalError', 'RangeError',
<del> 'ReferenceError', 'SyntaxError', 'TypeError', 'URIError', 'Proxy', 'Map',
<del> 'Set', 'WeakMap', 'WeakSet', 'Generator', 'GeneratorFunction',
<del> 'AsyncFunction', 'SharedArrayBuffer'
<add> 'Array', 'ArrayBuffer', 'AsyncFunction', 'DataView', 'Date', 'Error',
<add> 'EvalError', 'Float32Array', 'Float64Array', 'Function', 'Generator',
<add> 'GeneratorFunction', 'Int16Array', 'Int32Array', 'Int8Array', 'Map', 'Object',
<add> 'Promise', 'Proxy', 'RangeError', 'ReferenceError', 'RegExp', 'Set',
<add> 'SharedArrayBuffer', 'SyntaxError', 'TypeError', 'TypedArray', 'URIError',
<add> 'Uint16Array', 'Uint32Array', 'Uint8Array', 'Uint8ClampedArray', 'WeakMap',
<add> 'WeakSet'
<ide> ];
<ide> const typeMap = {
<ide> 'Iterable':
<ide> `${jsDocPrefix}Reference/Iteration_protocols#The_iterable_protocol`,
<ide> 'Iterator':
<ide> `${jsDocPrefix}Reference/Iteration_protocols#The_iterator_protocol`,
<ide>
<add> 'this': `${jsDocPrefix}Reference/Operators/this`,
<add>
<add> 'AsyncHook': 'async_hooks.html#async_hooks_async_hooks_createhook_callbacks',
<add>
<ide> 'Buffer': 'buffer.html#buffer_class_buffer',
<ide>
<ide> 'ChildProcess': 'child_process.html#child_process_class_childprocess',
<ide>
<ide> 'cluster.Worker': 'cluster.html#cluster_class_worker',
<ide>
<add> 'crypto.constants': 'crypto.html#crypto_crypto_constants_1',
<add>
<ide> 'dgram.Socket': 'dgram.html#dgram_class_dgram_socket',
<ide>
<add> 'Domain': 'domain.html#domain_class_domain',
<add>
<ide> 'EventEmitter': 'events.html#events_class_eventemitter',
<ide>
<add> 'fs.Stats': 'fs.html#fs_class_fs_stats',
<add>
<ide> 'http.Agent': 'http.html#http_class_http_agent',
<ide> 'http.ClientRequest': 'http.html#http_class_http_clientrequest',
<ide> 'http.IncomingMessage': 'http.html#http_class_http_incomingmessage',
<ide> 'http.Server': 'http.html#http_class_http_server',
<ide> 'http.ServerResponse': 'http.html#http_class_http_serverresponse',
<ide>
<add> 'ClientHttp2Stream': 'http2.html#http2_class_clienthttp2stream',
<ide> 'HTTP2 Headers Object': 'http2.html#http2_headers_object',
<ide> 'HTTP2 Settings Object': 'http2.html#http2_settings_object',
<add> 'http2.Http2ServerRequest': 'http2.html#http2_class_http2_http2serverrequest',
<add> 'http2.Http2ServerResponse':
<add> 'http2.html#http2_class_http2_http2serverresponse',
<add> 'Http2Server': 'http2.html#http2_class_http2server',
<add> 'Http2Session': 'http2.html#http2_class_http2session',
<add> 'Http2Stream': 'http2.html#http2_class_http2stream',
<add> 'ServerHttp2Stream': 'http2.html#http2_class_serverhttp2stream',
<ide>
<ide> 'Handle': 'net.html#net_server_listen_handle_backlog_callback',
<add> 'net.Server': 'net.html#net_class_net_server',
<ide> 'net.Socket': 'net.html#net_class_net_socket',
<ide>
<del> 'ServerHttp2Stream': 'http2.html#http2_class_serverhttp2stream',
<add> 'os.constants.dlopen': 'os.html#os_dlopen_constants',
<add>
<add> 'PerformanceObserver':
<add> 'perf_hooks.html#perf_hooks_class_performanceobserver_callback',
<add> 'PerformanceObserverEntryList':
<add> 'perf_hooks.html#perf_hooks_class_performanceobserverentrylist',
<add>
<add> 'readline.Interface': 'readline.html#readline_class_interface',
<ide>
<ide> 'Stream': 'stream.html#stream_stream',
<add> 'stream.Duplex': 'stream.html#stream_class_stream_duplex',
<ide> 'stream.Readable': 'stream.html#stream_class_stream_readable',
<ide> 'stream.Writable': 'stream.html#stream_class_stream_writable',
<del> 'stream.Duplex': 'stream.html#stream_class_stream_duplex',
<del>
<del> 'tls.TLSSocket': 'tls.html#tls_class_tls_tlssocket',
<ide>
<add> 'Immediate': 'timers.html#timers_class_immediate',
<add> 'Timeout': 'timers.html#timers_class_timeout',
<ide> 'Timer': 'timers.html#timers_timers',
<ide>
<add> 'tls.Server': 'tls.html#tls_class_tls_server',
<add> 'tls.TLSSocket': 'tls.html#tls_class_tls_tlssocket',
<add>
<ide> 'URL': 'url.html#url_the_whatwg_url_api',
<ide> 'URLSearchParams': 'url.html#url_class_urlsearchparams'
<ide> }; | 11 |
Text | Text | update rails on rack guide [ci skip] | aa5e551eb8b8988f5e6430463f01d483b1bd9346 | <ide><path>guides/source/rails_on_rack.md
<ide> use ActionDispatch::Flash
<ide> use Rack::Head
<ide> use Rack::ConditionalGet
<ide> use Rack::ETag
<del>run MyApp.application.routes
<add>run MyApp::Application.routes
<ide> ```
<ide>
<ide> The default middlewares shown here (and some others) are each summarized in the [Internal Middlewares](#internal-middleware-stack) section, below. | 1 |
Javascript | Javascript | add specs for accessibilityinfo | 67c3ed34ba75500098a16eced5f43b33039b0b14 | <ide><path>Libraries/Components/AccessibilityInfo/AccessibilityInfo.android.js
<ide>
<ide> 'use strict';
<ide>
<del>const NativeModules = require('../../BatchedBridge/NativeModules');
<add>import NativeAccessibilityInfo from './NativeAccessibilityInfo';
<add>
<ide> const RCTDeviceEventEmitter = require('../../EventEmitter/RCTDeviceEventEmitter');
<ide> const UIManager = require('../../ReactNative/UIManager');
<ide>
<del>const RCTAccessibilityInfo = NativeModules.AccessibilityInfo;
<del>
<ide> const REDUCE_MOTION_EVENT = 'reduceMotionDidChange';
<ide> const TOUCH_EXPLORATION_EVENT = 'touchExplorationDidChange';
<ide>
<ide> const AccessibilityInfo = {
<ide>
<ide> isReduceMotionEnabled: function(): Promise<boolean> {
<ide> return new Promise((resolve, reject) => {
<del> RCTAccessibilityInfo.isReduceMotionEnabled(resolve);
<add> if (NativeAccessibilityInfo) {
<add> NativeAccessibilityInfo.isReduceMotionEnabled(resolve);
<add> } else {
<add> reject(false);
<add> }
<ide> });
<ide> },
<ide>
<ide> const AccessibilityInfo = {
<ide>
<ide> isScreenReaderEnabled: function(): Promise<boolean> {
<ide> return new Promise((resolve, reject) => {
<del> RCTAccessibilityInfo.isTouchExplorationEnabled(resolve);
<add> if (NativeAccessibilityInfo) {
<add> NativeAccessibilityInfo.isTouchExplorationEnabled(resolve);
<add> } else {
<add> reject(false);
<add> }
<ide> });
<ide> },
<ide>
<ide> const AccessibilityInfo = {
<ide> * See http://facebook.github.io/react-native/docs/accessibilityinfo.html#announceforaccessibility
<ide> */
<ide> announceForAccessibility: function(announcement: string): void {
<del> RCTAccessibilityInfo.announceForAccessibility(announcement);
<add> if (NativeAccessibilityInfo) {
<add> NativeAccessibilityInfo.announceForAccessibility(announcement);
<add> }
<ide> },
<ide> };
<ide>
<ide><path>Libraries/Components/AccessibilityInfo/NativeAccessibilityInfo.js
<add>/**
<add> * Copyright (c) Facebook, Inc. and its affiliates.
<add> *
<add> * This source code is licensed under the MIT license found in the
<add> * LICENSE file in the root directory of this source tree.
<add> *
<add> * @flow
<add> * @format
<add> */
<add>
<add>'use strict';
<add>
<add>import type {TurboModule} from 'RCTExport';
<add>import * as TurboModuleRegistry from 'TurboModuleRegistry';
<add>
<add>export interface Spec extends TurboModule {
<add> +isReduceMotionEnabled: (
<add> onSuccess: (isReduceMotionEnabled: boolean) => void,
<add> ) => void;
<add> +isTouchExplorationEnabled: (
<add> onSuccess: (isScreenReaderEnabled: boolean) => void,
<add> ) => void;
<add> +setAccessibilityFocus: (reactTag: number) => void;
<add> +announceForAccessibility: (announcement: string) => void;
<add>}
<add>
<add>export default TurboModuleRegistry.get<Spec>('AccessibilityInfo'); | 2 |
Javascript | Javascript | add runtime logging | 09103af6c471ca8522499aea638622bfdd7fc052 | <ide><path>lib/Compiler.js
<ide> const RequestShortener = require("./RequestShortener");
<ide> const { makePathsRelative } = require("./util/identifier");
<ide> const ConcurrentCompilationError = require("./ConcurrentCompilationError");
<ide> const { Logger, LogType } = require("./logging/Logger");
<add>const logToConsole = require("./logging/logToConsole");
<ide>
<ide> /** @typedef {import("../declarations/WebpackOptions").Entry} Entry */
<ide> /** @typedef {import("../declarations/WebpackOptions").WebpackOptions} WebpackOptions */
<ide> class Compiler extends Tapable {
<ide> }
<ide> }
<ide> if (this.hooks.log.call(name, type, args) === undefined) {
<del> const labeledArgs = (prefix = "") => {
<del> if (Array.isArray(args)) {
<del> if (args.length > 0 && typeof args[0] === "string") {
<del> return [`${prefix}[${name}] ${args[0]}`, ...args.slice(1)];
<del> } else {
<del> return [`${prefix}[${name}]`, ...args];
<del> }
<del> } else {
<del> return [];
<del> }
<del> };
<del> switch (type) {
<del> case LogType.debug:
<del> // ignore
<del> break;
<del> case LogType.log:
<del> console.log(...labeledArgs());
<del> break;
<del> case LogType.info:
<del> console.info(...labeledArgs("<i> "));
<del> break;
<del> case LogType.warn:
<del> console.warn(...labeledArgs("<w> "));
<del> break;
<del> case LogType.error:
<del> console.error(...labeledArgs("<e> "));
<del> break;
<del> case LogType.trace:
<del> console.trace();
<del> break;
<del> case LogType.group:
<del> // eslint-disable-next-line node/no-unsupported-features/node-builtins
<del> if (typeof console.group === "function") {
<del> // eslint-disable-next-line node/no-unsupported-features/node-builtins
<del> console.group(...labeledArgs());
<del> } else {
<del> console.log(...labeledArgs());
<del> }
<del> break;
<del> case LogType.groupCollapsed:
<del> // eslint-disable-next-line node/no-unsupported-features/node-builtins
<del> if (typeof console.groupCollapsed === "function") {
<del> // eslint-disable-next-line node/no-unsupported-features/node-builtins
<del> console.groupCollapsed(...labeledArgs());
<del> } else {
<del> console.log(...labeledArgs("<g> "));
<del> }
<del> break;
<del> case LogType.groupEnd:
<del> // eslint-disable-next-line node/no-unsupported-features/node-builtins
<del> if (typeof console.groupEnd === "function") {
<del> // eslint-disable-next-line node/no-unsupported-features/node-builtins
<del> console.groupEnd();
<del> } else {
<del> console.log(...labeledArgs("</g> "));
<del> }
<del> break;
<del> case LogType.time:
<del> console.log(
<del> `[${name}] ${args[0]}: ${args[1] * 1000 + args[2] / 1000000}ms`
<del> );
<del> break;
<del> case LogType.profile:
<del> // eslint-disable-next-line node/no-unsupported-features/node-builtins
<del> if (typeof console.profile === "function") {
<del> // eslint-disable-next-line node/no-unsupported-features/node-builtins
<del> console.profile(...labeledArgs());
<del> }
<del> break;
<del> case LogType.profileEnd:
<del> // eslint-disable-next-line node/no-unsupported-features/node-builtins
<del> if (typeof console.profileEnd === "function") {
<del> // eslint-disable-next-line node/no-unsupported-features/node-builtins
<del> console.profileEnd(...labeledArgs());
<del> }
<del> break;
<del> case LogType.clear:
<del> // eslint-disable-next-line node/no-unsupported-features/node-builtins
<del> if (typeof console.clear === "function") {
<del> // eslint-disable-next-line node/no-unsupported-features/node-builtins
<del> console.clear();
<del> }
<del> break;
<del> default:
<del> throw new Error(`Unexpected LogType ${type}`);
<del> }
<add> // ignore debug logging by default
<add> if (type === LogType.debug) return;
<add> logToConsole(name, type, args);
<ide> }
<ide> });
<ide> }
<ide><path>lib/logging/Logger.js
<ide> const LogType = Object.freeze({
<ide>
<ide> exports.LogType = LogType;
<ide>
<add>/** @typedef {LogType} LogTypeEnum */
<add>
<ide> const LOG_SYMBOL = Symbol("webpack logger raw log method");
<ide> const TIMERS_SYMBOL = Symbol("webpack logger times");
<ide>
<ide><path>lib/logging/logToConsole.js
<add>/*
<add> MIT License http://www.opensource.org/licenses/mit-license.php
<add> Author Tobias Koppers @sokra
<add>*/
<add>
<add>"use strict";
<add>
<add>const { LogType } = require("./Logger");
<add>
<add>/** @typedef {import("./Logger").LogTypeEnum} LogTypeEnum */
<add>
<add>/**
<add> * @param {string} name name of the logger
<add> * @param {LogTypeEnum} type type of the log entry
<add> * @param {any[]} args arguments of the log entry
<add> */
<add>module.exports = (name, type, args) => {
<add> const labeledArgs = (prefix = "") => {
<add> if (Array.isArray(args)) {
<add> if (args.length > 0 && typeof args[0] === "string") {
<add> return [`${prefix}[${name}] ${args[0]}`, ...args.slice(1)];
<add> } else {
<add> return [`${prefix}[${name}]`, ...args];
<add> }
<add> } else {
<add> return [];
<add> }
<add> };
<add> switch (type) {
<add> case LogType.debug:
<add> // eslint-disable-next-line node/no-unsupported-features/node-builtins
<add> if (typeof console.debug === "function") {
<add> // eslint-disable-next-line node/no-unsupported-features/node-builtins
<add> console.debug(...labeledArgs());
<add> } else {
<add> console.log(...labeledArgs());
<add> }
<add> break;
<add> case LogType.log:
<add> console.log(...labeledArgs());
<add> break;
<add> case LogType.info:
<add> console.info(...labeledArgs("<i> "));
<add> break;
<add> case LogType.warn:
<add> console.warn(...labeledArgs("<w> "));
<add> break;
<add> case LogType.error:
<add> console.error(...labeledArgs("<e> "));
<add> break;
<add> case LogType.trace:
<add> console.trace();
<add> break;
<add> case LogType.group:
<add> // eslint-disable-next-line node/no-unsupported-features/node-builtins
<add> if (typeof console.group === "function") {
<add> // eslint-disable-next-line node/no-unsupported-features/node-builtins
<add> console.group(...labeledArgs());
<add> } else {
<add> console.log(...labeledArgs());
<add> }
<add> break;
<add> case LogType.groupCollapsed:
<add> // eslint-disable-next-line node/no-unsupported-features/node-builtins
<add> if (typeof console.groupCollapsed === "function") {
<add> // eslint-disable-next-line node/no-unsupported-features/node-builtins
<add> console.groupCollapsed(...labeledArgs());
<add> } else {
<add> console.log(...labeledArgs("<g> "));
<add> }
<add> break;
<add> case LogType.groupEnd:
<add> // eslint-disable-next-line node/no-unsupported-features/node-builtins
<add> if (typeof console.groupEnd === "function") {
<add> // eslint-disable-next-line node/no-unsupported-features/node-builtins
<add> console.groupEnd();
<add> } else {
<add> console.log(...labeledArgs("</g> "));
<add> }
<add> break;
<add> case LogType.time:
<add> console.log(
<add> `[${name}] ${args[0]}: ${args[1] * 1000 + args[2] / 1000000}ms`
<add> );
<add> break;
<add> case LogType.profile:
<add> // eslint-disable-next-line node/no-unsupported-features/node-builtins
<add> if (typeof console.profile === "function") {
<add> // eslint-disable-next-line node/no-unsupported-features/node-builtins
<add> console.profile(...labeledArgs());
<add> }
<add> break;
<add> case LogType.profileEnd:
<add> // eslint-disable-next-line node/no-unsupported-features/node-builtins
<add> if (typeof console.profileEnd === "function") {
<add> // eslint-disable-next-line node/no-unsupported-features/node-builtins
<add> console.profileEnd(...labeledArgs());
<add> }
<add> break;
<add> case LogType.clear:
<add> // eslint-disable-next-line node/no-unsupported-features/node-builtins
<add> if (typeof console.clear === "function") {
<add> // eslint-disable-next-line node/no-unsupported-features/node-builtins
<add> console.clear();
<add> }
<add> break;
<add> default:
<add> throw new Error(`Unexpected LogType ${type}`);
<add> }
<add>};
<ide><path>lib/logging/runtime.js
<add>const SyncBailHook = require("tapable/lib/SyncBailHook");
<add>const { Logger } = require("./Logger");
<add>const logToConsole = require("./logToConsole");
<add>
<add>exports.getLogger = name => {
<add> return new Logger((type, args) => {
<add> if (exports.hooks.log.call(name, type, args) === undefined) {
<add> logToConsole(name, type, args);
<add> }
<add> });
<add>};
<add>
<add>exports.hooks = {
<add> log: new SyncBailHook(["origin", "type", "args"])
<add>}; | 4 |
Python | Python | add support for keras masking and causal masking | c0293ded9abe8ac7719cceb0095fa9dff807d2fe | <ide><path>keras/layers/attention/multi_head_attention.py
<ide> class MultiHeadAttention(Layer):
<ide> activity_regularizer: Regularizer for dense layer activity.
<ide> kernel_constraint: Constraint for dense layer kernels.
<ide> bias_constraint: Constraint for dense layer kernels.
<add> causal: Boolean, whether to apply a causal mask to prevent tokens from
<add> attending to future tokens (e.g., used in a decoder Transformer).
<ide>
<ide> Call arguments:
<ide> query: Query `Tensor` of shape `(B, T, dim)`.
<ide> def __init__(
<ide> activity_regularizer=None,
<ide> kernel_constraint=None,
<ide> bias_constraint=None,
<add> causal=False,
<ide> **kwargs
<ide> ):
<ide> super().__init__(**kwargs)
<add> self.supports_masking = True
<ide> self._num_heads = num_heads
<ide> self._key_dim = key_dim
<ide> self._value_dim = value_dim if value_dim else key_dim
<ide> def __init__(
<ide> self._activity_regularizer = regularizers.get(activity_regularizer)
<ide> self._kernel_constraint = constraints.get(kernel_constraint)
<ide> self._bias_constraint = constraints.get(bias_constraint)
<add> self._causal = causal
<ide> if attention_axes is not None and not isinstance(
<ide> attention_axes, collections.abc.Sized
<ide> ):
<ide> def get_config(self):
<ide> ),
<ide> "kernel_constraint": constraints.serialize(self._kernel_constraint),
<ide> "bias_constraint": constraints.serialize(self._bias_constraint),
<add> "causal": self._causal,
<ide> "query_shape": self._query_shape,
<ide> "key_shape": self._key_shape,
<ide> "value_shape": self._value_shape,
<ide> def _build_attention(self, rank):
<ide> """Builds multi-head dot-product attention computations.
<ide>
<ide> This function builds attributes necessary for `_compute_attention` to
<del> costomize attention computation to replace the default dot-product
<add> customize attention computation to replace the default dot-product
<ide> attention.
<ide>
<ide> Args:
<ide> def _compute_attention(
<ide> key: Projected key `Tensor` of shape `(B, T, N, key_dim)`.
<ide> value: Projected value `Tensor` of shape `(B, T, N, value_dim)`.
<ide> attention_mask: a boolean mask of shape `(B, T, S)`, that prevents
<del> attention to certain positions.
<add> attention to certain positions. It is generally not needed if the
<add> `query` and `value` (and/or `key`) are masked.
<ide> training: Python boolean indicating whether the layer should behave in
<ide> training mode (adding dropout) or in inference mode (doing nothing).
<ide>
<ide> def call(
<ide> return_attention_scores=False,
<ide> training=None,
<ide> ):
<add> attention_mask = self._compute_attention_mask(
<add> query, value, key, attention_mask
<add> )
<add>
<ide> if not self._built_from_signature:
<ide> self._build_from_signature(query=query, value=value, key=key)
<ide> if key is None:
<ide> def call(
<ide> if return_attention_scores:
<ide> return attention_output, attention_scores
<ide> return attention_output
<add>
<add> def _compute_attention_mask(
<add> self, query, value, key=None, attention_mask=None
<add> ):
<add> """Computes the attention mask, using the Keras masks of the inputs.
<add>
<add> * The `query`'s mask is reshaped from [B, T] to [B, T, 1].
<add> * The `value`'s mask is reshaped from [B, S] to [B, 1, S].
<add> * The `key`'s mask is reshaped from [B, S] to [B, 1, S]. The `key`'s
<add> mask is ignored if `key` is `None` or if `key is value`.
<add> * If the layer was created with `causal=True`, then the causal mask is
<add> computed. Its shape is [1, T, S].
<add>
<add> All defined masks are merged using a logical AND operation (`&`).
<add>
<add> In general, if the `query` and `value` are masked, then there is no need
<add> to define the `attention_mask`.
<add>
<add> Args:
<add> query: Projected query `Tensor` of shape `(B, T, N, key_dim)`.
<add> key: Projected key `Tensor` of shape `(B, T, N, key_dim)`.
<add> value: Projected value `Tensor` of shape `(B, T, N, value_dim)`.
<add> attention_mask: a boolean mask of shape `(B, T, S)`, that prevents
<add> attention to certain positions.
<add> Returns:
<add> attention_mask: a boolean mask of shape `(B, T, S)`, that prevents
<add> attention to certain positions, based on the Keras masks of the
<add> `query`, `key`, `value`, and `attention_mask` tensors, and the
<add> causal mask if the layer was created with `causal=True`.
<add> """
<add> query_mask = getattr(query, "_keras_mask", None)
<add> value_mask = getattr(value, "_keras_mask", None)
<add> key_mask = getattr(key, "_keras_mask", None)
<add> auto_mask = None
<add> if query_mask is not None:
<add> # B = batch size, T = max query length
<add> auto_mask = query_mask[:, :, tf.newaxis] # shape is [B, T, 1]
<add> if value_mask is not None:
<add> # B = batch size, S == max value length
<add> mask = value_mask[:, tf.newaxis, :] # shape is [B, 1, S]
<add> auto_mask = mask if auto_mask is None else auto_mask & mask
<add> if key_mask is not None:
<add> # B == batch size, S == max key length == max value length
<add> mask = key_mask[:, tf.newaxis, :] # shape is [B, 1, S]
<add> auto_mask = mask if auto_mask is None else auto_mask & mask
<add> if self._causal:
<add> # the shape of the causal mask is [1, T, S]
<add> mask = self._compute_causal_mask(query, value)
<add> auto_mask = mask if auto_mask is None else auto_mask & mask
<add> if auto_mask is not None:
<add> # merge attention_mask & automatic mask, to shape [B, T, S]
<add> attention_mask = (
<add> auto_mask
<add> if attention_mask is None
<add> else attention_mask & auto_mask
<add> )
<add> return attention_mask
<add>
<add> def _compute_causal_mask(self, query, value=None):
<add> """Computes a causal mask (e.g., for masked self-attention layers).
<add>
<add> For example, if query and value both contain sequences of length 4,
<add> this function returns:
<add> [[True, False, False, False],
<add> [True, True, False, False],
<add> [True, True, True, False],
<add> [True, True, True, True]]
<add>
<add> Args:
<add> query: query `Tensor` of shape `(B, T, ...)`.
<add> value: value `Tensor` of shape `(B, S, ...)` (optional, defaults to
<add> query).
<add> Returns:
<add> mask: an array of shape [1, T, S] containing a lower triangular matrix
<add> of shape [T, S].
<add> """
<add> q_seq_length = tf.shape(query)[1]
<add> v_seq_length = q_seq_length if value is None else tf.shape(value)[1]
<add> return tf.linalg.band_part( # creates a lower triangular matrix
<add> tf.ones((1, q_seq_length, v_seq_length), tf.bool), -1, 0
<add> )
<ide><path>keras/layers/attention/multi_head_attention_test.py
<ide> def test_ragged_tensor(self, ragged_query, ragged_value, ragged_key):
<ide> results = test_layer(query, value, key)
<ide> self.assertAllEqual(results.shape.as_list(), query.shape.as_list())
<ide>
<add> def test_query_mask_progagation(self):
<add> """Test automatic propagation of the query's mask."""
<add> test_layer = keras.layers.MultiHeadAttention(num_heads=2, key_dim=2)
<add> self.assertTrue(test_layer.supports_masking)
<add> query = np.array([[1, 2, 3, 0, 0], [3, 3, 1, 1, 2], [1, 0, 0, 0, 0]])
<add> masked_query = keras.layers.Embedding(4, 8, mask_zero=True)(query)
<add> value = np.random.random((3, 3, 8))
<add> output = test_layer(query=masked_query, value=value)
<add> self.assertTrue(hasattr(output, "_keras_mask"))
<add> self.assertAllEqual(masked_query._keras_mask, output._keras_mask)
<add>
<add> @parameterized.named_parameters(("causal", True), ("not_causal", False))
<add> def test_value_mask(self, causal):
<add> """Test that the value and causal masks are taken into account."""
<add> test_layer = keras.layers.MultiHeadAttention(
<add> num_heads=2, key_dim=2, causal=causal
<add> )
<add> query = np.array([[1, 2, 3, 0, 0], [3, 3, 1, 1, 2], [1, 0, 0, 0, 0]])
<add> masked_query = keras.layers.Embedding(4, 8, mask_zero=True)(query)
<add> value = np.array([[5, 4, 0], [3, 0, 0], [2, 1, 1]])
<add> masked_value = keras.layers.Embedding(6, 8, mask_zero=True)(value)
<add> output = test_layer(query=masked_query, value=masked_value)
<add> mask = np.array(
<add> [[[True, True, False]] * 3 + [[False, False, False]] * 2]
<add> + [[[True, False, False]] * 5]
<add> + [[[True, True, True]] + [[False, False, False]] * 4]
<add> )
<add> if causal:
<add> mask = mask & np.array(
<add> [
<add> [[True, False, False], [True, True, False]]
<add> + [[True, True, True]] * 3
<add> ]
<add> )
<add> del masked_query._keras_mask
<add> del masked_value._keras_mask
<add> output_with_manual_mask = test_layer(
<add> query=masked_query, value=masked_value, attention_mask=mask
<add> )
<add> self.assertAllClose(output, output_with_manual_mask)
<add>
<ide>
<ide> class SubclassAttention(keras.layers.MultiHeadAttention):
<ide> def _build_attention(self, qkv_rank): | 2 |
Javascript | Javascript | remove inlined css in htmljs | 5869ea4b331b61e9b7fc90bd689fbe994e6a761f | <ide><path>packages/learn/src/head/index.js
<ide> import favicons from './favicons';
<ide> import meta from './meta';
<del>import styleSheets from './styleSheets';
<ide> import mathjax from './mathjax';
<ide> import sassjs from './sassjs';
<ide>
<ide> const metaAndStyleSheets = meta
<del> .concat(favicons, styleSheets, mathjax, sassjs)
<add> .concat(favicons, mathjax, sassjs)
<ide> .map((element, i) => ({ ...element, key: `meta-stylesheet-${i}` }));
<ide>
<ide> export default metaAndStyleSheets;
<ide><path>packages/learn/src/head/preloads.js
<ide> import React from 'react';
<ide> import styleSheets from './styleSheets';
<ide>
<ide> const preloads = styleSheets.map((styleSheet, i) => (
<del> <link
<del> as='style'
<del> href={styleSheet.props.href}
<del> key={`preload-${i}`}
<del> rel='preload'
<del> />
<add> <React.Fragment>
<add> <link
<add> as='style'
<add> href={styleSheet.props.href}
<add> key={`preload-${i}`}
<add> rel='preload'
<add> />
<add> {styleSheet}
<add> </React.Fragment>
<ide> ));
<ide>
<ide> export default preloads;
<ide><path>packages/learn/src/html.js
<ide> import PropTypes from 'prop-types';
<ide>
<ide> import preloads from './head/preloads';
<ide>
<del>let stylesStr;
<del>if (process.env.NODE_ENV === 'production') {
<del> try {
<del> stylesStr = require('!raw-loader!../public/styles.css');
<del> } catch (e) {
<del> console.log(e);
<del> }
<del>}
<del>
<ide> // These props are coming from Gatsby, we shouldn't have to worry about them
<ide> const propTypes = {
<ide> body: PropTypes.any,
<ide> function HTML(props) {
<ide> preBodyComponents,
<ide> postBodyComponents
<ide> } = props;
<del> let css;
<del> if (process.env.NODE_ENV === 'production') {
<del> css = (
<del> <style
<del> dangerouslySetInnerHTML={{ __html: stylesStr }}
<del> id='gatsby-inlined-css'
<del> />
<del> );
<del> }
<ide> return (
<ide> <html {...htmlAttributes}>
<ide> <head>
<ide> {preloads}
<ide> {headComponents}
<del> {css}
<ide> </head>
<ide> <body {...bodyAttributes}>
<ide> {preBodyComponents} | 3 |
Javascript | Javascript | add test case | 11bc877b42954b9912f0573e53416373e954cbd9 | <ide><path>test/ProfilingPlugin.test.js
<ide> describe("Profiling Plugin", function () {
<ide> new webpack.debug.ProfilingPlugin({
<ide> outputPath: finalPath
<ide> })
<del> ]
<add> ],
<add> experiments: {
<add> backCompat: false
<add> }
<ide> });
<ide> compiler.run(err => {
<ide> if (err) return done(err); | 1 |
Ruby | Ruby | tell users to fix head issues with inreplace | 03a489bf78709f9361109d65817ae8821eeef864 | <ide><path>Library/Homebrew/formula.rb
<ide> class Formula
<ide> extend Cachable
<ide> extend Predicable
<ide>
<del> # @!method inreplace(paths, before = nil, after = nil)
<del> # @see Utils::Inreplace.inreplace
<del>
<ide> # The name of this {Formula}.
<ide> # e.g. `this-formula`
<ide> attr_reader :name
<ide> def test_fixtures(file)
<ide> # end</pre>
<ide> def install; end
<ide>
<add> def inreplace(paths, before = nil, after = nil, audit_result = true) # rubocop:disable Style/OptionalBooleanParameter
<add> super(paths, before, after, audit_result)
<add> rescue Utils::Inreplace::Error
<add> raise BuildError.new(self, "inreplace", paths, nil)
<add> end
<add>
<ide> protected
<ide>
<ide> def setup_home(home)
<ide><path>Library/Homebrew/test/formula_spec.rb
<ide> end
<ide> end
<ide>
<add> describe "::inreplace" do
<add> specify "raises build error on failure" do
<add> f = formula do
<add> url "https://brew.sh/test-1.0.tbz"
<add> end
<add>
<add> expect { f.inreplace([]) }.to raise_error(BuildError)
<add> end
<add> end
<add>
<ide> describe "::installed_with_alias_path" do
<ide> specify "with alias path with nil" do
<ide> expect(described_class.installed_with_alias_path(nil)).to be_empty
<ide><path>Library/Homebrew/utils/inreplace.rb
<ide> module Utils
<ide> module Inreplace
<ide> extend T::Sig
<ide>
<del> # Error during replacement.
<add> # Error during text replacement.
<ide> class Error < RuntimeError
<ide> def initialize(errors)
<ide> formatted_errors = errors.reduce(+"inreplace failed\n") do |s, (path, errs)|
<ide> def inreplace(paths, before = nil, after = nil, audit_result = true) # rubocop:d
<ide> Pathname(path).atomic_write(s.inreplace_string)
<ide> end
<ide>
<del> raise Error, errors unless errors.empty?
<add> raise Utils::Inreplace::Error, errors unless errors.empty?
<ide> end
<ide>
<ide> # @api private
<ide> def inreplace_pairs(path, replacement_pairs, read_only_run: false, silent: false
<ide>
<ide> contents.gsub!(old, new)
<ide> end
<del> raise Error, path => contents.errors unless contents.errors.empty?
<add> raise Utils::Inreplace::Error, [path => contents.errors] unless contents.errors.empty?
<ide>
<ide> Pathname(path).atomic_write(contents.inreplace_string) unless read_only_run
<ide> contents.inreplace_string | 3 |
Javascript | Javascript | apply linting fixes | e417f3f0d41c9d99bd6eccb71abeb0c8efa86415 | <ide><path>config/env.js
<ide> const {
<ide> FORUM_LOCATION: forum,
<ide> NEWS_LOCATION: news,
<ide> LOCALE: locale,
<del> STRIPE_PUBLIC: stripePublicKey,
<add> STRIPE_PUBLIC: stripePublicKey
<ide> } = process.env;
<ide>
<ide> const locations = { | 1 |
Ruby | Ruby | fix filtering of aliases in results | 79ea14b73867f52a6016c97ca8e38f5c7f7672e9 | <ide><path>Library/Homebrew/cmd/search.rb
<ide> def search_formulae(rx)
<ide> aliases = Formula.aliases
<ide> results = (Formula.full_names+aliases).grep(rx).sort
<ide>
<del> results.each_with_index do |name, i|
<add> results.map do |name|
<ide> canonical_name = Formulary.canonical_name(name)
<del> # Remove aliases from results when the full name was also found
<add> # Ignore aliases from results when the full name was also found
<ide> if aliases.include?(name) && results.include?(canonical_name)
<del> results.delete_at(i)
<del> # Notify the user if the formula is installed
<add> next
<ide> elsif (HOMEBREW_CELLAR/canonical_name).directory?
<del> results[i] = "#{name} (installed)"
<add> "#{name} (installed)"
<add> else
<add> name
<ide> end
<del> end
<add> end.compact
<ide> end
<ide> end | 1 |
Javascript | Javascript | render overlay decorations | b6f71bc64859bec75ec97ce5c0f9705d5cd9f793 | <ide><path>spec/text-editor-component-spec.js
<ide> describe('TextEditorComponent', () => {
<ide> })
<ide> })
<ide>
<add> describe('overlay decorations', () => {
<add> it('renders overlay elements at the specified screen position unless it would overflow the window', async () => {
<add> const {component, element, editor} = buildComponent({width: 200, height: 100, attach: false})
<add> const fakeWindow = document.createElement('div')
<add> fakeWindow.style.position = 'absolute'
<add> fakeWindow.style.padding = 20 + 'px'
<add> fakeWindow.style.backgroundColor = 'blue'
<add> fakeWindow.appendChild(element)
<add> jasmine.attachToDOM(fakeWindow)
<add>
<add> component.getWindowInnerWidth = () => fakeWindow.getBoundingClientRect().width
<add> component.getWindowInnerHeight = () => fakeWindow.getBoundingClientRect().height
<add> // spyOn(component, 'getWindowInnerWidth').andCallFake(() => fakeWindow.getBoundingClientRect().width)
<add> // spyOn(component, 'getWindowInnerHeight').andCallFake(() => fakeWindow.getBoundingClientRect().height)
<add> await setScrollTop(component, 50)
<add> await setScrollLeft(component, 100)
<add>
<add> const marker = editor.markScreenPosition([4, 25])
<add>
<add> const overlayElement = document.createElement('div')
<add> overlayElement.style.width = '50px'
<add> overlayElement.style.height = '50px'
<add> overlayElement.style.margin = '3px'
<add> overlayElement.style.backgroundColor = 'red'
<add>
<add> editor.decorateMarker(marker, {type: 'overlay', item: overlayElement})
<add> await component.getNextUpdatePromise()
<add>
<add> const overlayWrapper = overlayElement.parentElement
<add> expect(overlayWrapper.getBoundingClientRect().top).toBe(clientTopForLine(component, 5))
<add> expect(overlayWrapper.getBoundingClientRect().left).toBe(clientLeftForCharacter(component, 4, 25))
<add>
<add> // Updates the horizontal position on scroll
<add> await setScrollLeft(component, 150)
<add> expect(overlayWrapper.getBoundingClientRect().left).toBe(clientLeftForCharacter(component, 4, 25))
<add>
<add> // Shifts the overlay horizontally to ensure the overlay element does not
<add> // overflow the window
<add> await setScrollLeft(component, 30)
<add> expect(overlayElement.getBoundingClientRect().right).toBe(fakeWindow.getBoundingClientRect().right)
<add> await setScrollLeft(component, 280)
<add> expect(overlayElement.getBoundingClientRect().left).toBe(fakeWindow.getBoundingClientRect().left)
<add>
<add> // Updates the vertical position on scroll
<add> await setScrollTop(component, 60)
<add> expect(overlayWrapper.getBoundingClientRect().top).toBe(clientTopForLine(component, 5))
<add>
<add> // Flips the overlay vertically to ensure the overlay element does not
<add> // overflow the bottom of the window
<add> setScrollLeft(component, 100)
<add> await setScrollTop(component, 0)
<add> expect(overlayWrapper.getBoundingClientRect().bottom).toBe(clientTopForLine(component, 4))
<add>
<add> // Flips the overlay vertically on overlay resize if necessary
<add> await setScrollTop(component, 20)
<add> expect(overlayWrapper.getBoundingClientRect().top).toBe(clientTopForLine(component, 5))
<add> overlayElement.style.height = 60 + 'px'
<add> await component.getNextUpdatePromise()
<add> expect(overlayWrapper.getBoundingClientRect().bottom).toBe(clientTopForLine(component, 4))
<add>
<add> // Does not flip the overlay vertically if it would overflow the top of the window
<add> overlayElement.style.height = 80 + 'px'
<add> await component.getNextUpdatePromise()
<add> expect(overlayWrapper.getBoundingClientRect().top).toBe(clientTopForLine(component, 5))
<add> })
<add> })
<add>
<ide> describe('mouse input', () => {
<ide> describe('on the lines', () => {
<ide> it('positions the cursor on single-click', async () => {
<ide><path>src/text-editor-component.js
<ide> const etch = require('etch')
<ide> const {CompositeDisposable} = require('event-kit')
<ide> const {Point, Range} = require('text-buffer')
<del>const resizeDetector = require('element-resize-detector')({strategy: 'scroll'})
<add>const ResizeDetector = require('element-resize-detector')
<ide> const TextEditor = require('./text-editor')
<ide> const {isPairedCharacter} = require('./text-utils')
<ide> const $ = etch.dom
<ide> class TextEditorComponent {
<ide> this.virtualNode.domNode = this.element
<ide> this.refs = {}
<ide>
<add> this.updateSync = this.updateSync.bind(this)
<add> this.didScrollDummyScrollbar = this.didScrollDummyScrollbar.bind(this)
<add> this.didMouseDownOnContent = this.didMouseDownOnContent.bind(this)
<ide> this.disposables = new CompositeDisposable()
<ide> this.updateScheduled = false
<ide> this.measurements = null
<ide> class TextEditorComponent {
<ide> this.horizontalPixelPositionsByScreenLineId = new Map() // Values are maps from column to horiontal pixel positions
<ide> this.lineNodesByScreenLineId = new Map()
<ide> this.textNodesByScreenLineId = new Map()
<del> this.didScrollDummyScrollbar = this.didScrollDummyScrollbar.bind(this)
<del> this.didMouseDownOnContent = this.didMouseDownOnContent.bind(this)
<ide> this.scrollbarsVisible = true
<ide> this.refreshScrollbarStyling = false
<ide> this.pendingAutoscroll = null
<ide> class TextEditorComponent {
<ide> lineNumbers: new Map(),
<ide> lines: new Map(),
<ide> highlights: new Map(),
<del> cursors: []
<add> cursors: [],
<add> overlays: []
<ide> }
<ide> this.decorationsToMeasure = {
<ide> highlights: new Map(),
<ide> cursors: []
<ide> }
<ide>
<ide> this.observeModel()
<del> resizeDetector.listenTo(this.element, this.didResize.bind(this))
<add> getElementResizeDetector().listenTo(this.element, this.didResize.bind(this))
<ide>
<ide> etch.updateSync(this)
<ide> }
<ide> class TextEditorComponent {
<ide> const style = {}
<ide>
<ide> if (!model.getAutoHeight() && !model.getAutoWidth()) {
<del> style.contain = 'strict'
<add> style.contain = 'size'
<ide> }
<ide>
<ide> if (this.measurements) {
<ide> class TextEditorComponent {
<ide> },
<ide> this.renderGutterContainer(),
<ide> this.renderScrollContainer()
<del> )
<add> ),
<add> this.renderOverlayDecorations()
<ide> )
<ide> }
<ide>
<ide> class TextEditorComponent {
<ide> }
<ide> }
<ide>
<add> renderOverlayDecorations () {
<add> return this.decorationsToRender.overlays.map((overlayProps) =>
<add> $(OverlayComponent, Object.assign({didResize: this.updateSync}, overlayProps))
<add> )
<add> }
<add>
<ide> // This is easier to mock
<ide> getPlatform () {
<ide> return process.platform
<ide> class TextEditorComponent {
<ide> queryDecorationsToRender () {
<ide> this.decorationsToRender.lineNumbers.clear()
<ide> this.decorationsToRender.lines.clear()
<add> this.decorationsToRender.overlays.length = 0
<ide> this.decorationsToMeasure.highlights.clear()
<ide> this.decorationsToMeasure.cursors.length = 0
<ide>
<ide> class TextEditorComponent {
<ide> case 'cursor':
<ide> this.addCursorDecorationToMeasure(marker, screenRange, reversed)
<ide> break
<add> case 'overlay':
<add> this.addOverlayDecorationToRender(decoration, marker)
<add> break
<ide> }
<ide> }
<ide> }
<ide> class TextEditorComponent {
<ide> this.decorationsToMeasure.cursors.push({screenPosition, columnWidth, isLastCursor})
<ide> }
<ide>
<add> addOverlayDecorationToRender (decoration, marker) {
<add> const {class: className, item, position} = decoration
<add> const element = atom.views.getView(item)
<add> const screenPosition = (position === 'tail')
<add> ? marker.getTailScreenPosition()
<add> : marker.getHeadScreenPosition()
<add>
<add> this.requestHorizontalMeasurement(screenPosition.row, screenPosition.column)
<add> this.decorationsToRender.overlays.push({
<add> key: element,
<add> className, element, screenPosition
<add> })
<add> }
<add>
<ide> updateAbsolutePositionedDecorations () {
<ide> this.updateHighlightsToRender()
<ide> this.updateCursorsToRender()
<add> this.updateOverlaysToRender()
<ide> }
<ide>
<ide> updateHighlightsToRender () {
<ide> class TextEditorComponent {
<ide> }
<ide> }
<ide>
<add> updateOverlaysToRender () {
<add> const overlayCount = this.decorationsToRender.overlays.length
<add> if (overlayCount === 0) return null
<add>
<add> const windowInnerHeight = this.getWindowInnerHeight()
<add> const windowInnerWidth = this.getWindowInnerWidth()
<add> const contentClientRect = this.refs.content.getBoundingClientRect()
<add> for (let i = 0; i < overlayCount; i++) {
<add> const decoration = this.decorationsToRender.overlays[i]
<add> const {element, screenPosition} = decoration
<add> const {row, column} = screenPosition
<add> const computedStyle = window.getComputedStyle(element)
<add>
<add> let wrapperTop = contentClientRect.top + this.pixelTopForRow(row) + this.getLineHeight()
<add> const elementHeight = element.offsetHeight
<add> const elementTop = wrapperTop + parseInt(computedStyle.marginTop)
<add> const elementBottom = elementTop + elementHeight
<add> const flippedElementTop = wrapperTop - this.getLineHeight() - elementHeight - parseInt(computedStyle.marginBottom)
<add>
<add> if (elementBottom > windowInnerHeight && flippedElementTop >= 0) {
<add> wrapperTop -= (elementTop - flippedElementTop)
<add> }
<add>
<add> let wrapperLeft = contentClientRect.left + this.pixelLeftForRowAndColumn(row, column)
<add> const elementLeft = wrapperLeft + parseInt(computedStyle.marginLeft)
<add> const elementRight = elementLeft + element.offsetWidth
<add> if (elementLeft < 0) {
<add> wrapperLeft -= elementLeft
<add> } else if (elementRight > windowInnerWidth) {
<add> wrapperLeft -= (elementRight - windowInnerWidth)
<add> }
<add>
<add> decoration.pixelTop = wrapperTop
<add> decoration.pixelLeft = wrapperLeft
<add> }
<add> }
<add>
<ide> didAttach () {
<ide> if (!this.attached) {
<ide> this.attached = true
<ide> class TextEditorComponent {
<ide> return this.element.offsetWidth > 0 || this.element.offsetHeight > 0
<ide> }
<ide>
<add> getWindowInnerHeight () {
<add> return window.innerHeight
<add> }
<add>
<add> getWindowInnerWidth () {
<add> return window.innerWidth
<add> }
<add>
<ide> getLineHeight () {
<ide> return this.measurements.lineHeight
<ide> }
<ide> class HighlightComponent {
<ide> }
<ide> }
<ide>
<add>class OverlayComponent {
<add> constructor (props) {
<add> this.props = props
<add> this.element = document.createElement('atom-overlay')
<add> this.element.appendChild(this.props.element)
<add> this.element.style.position = 'fixed'
<add> this.element.style.zIndex = 4
<add> this.element.style.top = (this.props.pixelTop || 0) + 'px'
<add> this.element.style.left = (this.props.pixelLeft || 0) + 'px'
<add> getElementResizeDetector().listenTo(this.element, this.props.didResize)
<add> }
<add>
<add> update (props) {
<add> this.props = props
<add> if (this.props.pixelTop != null) this.element.style.top = this.props.pixelTop + 'px'
<add> if (this.props.pixelLeft != null) this.element.style.left = this.props.pixelLeft + 'px'
<add> }
<add>}
<add>
<ide> const classNamesByScopeName = new Map()
<ide> function classNameForScopeName (scopeName) {
<ide> let classString = classNamesByScopeName.get(scopeName)
<ide> function clientRectForRange (textNode, startIndex, endIndex) {
<ide> return rangeForMeasurement.getBoundingClientRect()
<ide> }
<ide>
<add>let resizeDetector
<add>function getElementResizeDetector () {
<add> if (resizeDetector == null) resizeDetector = ResizeDetector({strategy: 'scroll'})
<add> return resizeDetector
<add>}
<add>
<ide> function arraysEqual(a, b) {
<ide> if (a.length !== b.length) return false
<ide> for (let i = 0, length = a.length; i < length; i++) { | 2 |
Text | Text | improve quiet documentation | 4fd2ca25989bdc48110655aa66e9b474ea229032 | <ide><path>README.md
<ide> The `next` API is as follows:
<ide> Supported options:
<ide> - `dev` (`bool`) whether to launch Next.js in dev mode - default `false`
<ide> - `dir` (`string`) where the Next project is located - default `'.'`
<del>- `quiet` (`bool`) Display error messages with server information - default `false`
<add>- `quiet` (`bool`) Hide error messages containing server information - default `false`
<ide>
<ide> ### Custom `<Document>`
<ide> | 1 |
Text | Text | add text that elaborates on 'is' with '=' | 38862b6f9cc7884ac2217e58d78d43af3d7d59cf | <ide><path>guide/english/python/difference-between-is-and-equal-equal-operators/index.md
<ide> ---
<ide> title: Difference between Python 'is' and '==' operators
<ide> ---
<del>`is` is a check for object identity - ie, checking if two or more variables are referring to the same object. You can't overload `is`.
<add>`is` is a check for object identity - ie, checking if two or more variables are referring to the same object. You can't overload `is`. That object identity is established and assigned with `=`.
<ide>
<ide> `==` evaluates to true if object referred to by the variables are equal. You can overload `==` via the `__eq__` operator.
<ide> | 1 |
Go | Go | adjust api version to match correct release | a061b1e2d8f6117b0524e44de7b6bc391245864e | <ide><path>integration/build/build_test.go
<ide> func TestBuildMultiStageParentConfig(t *testing.T) {
<ide>
<ide> // Test cases in #36996
<ide> func TestBuildLabelWithTargets(t *testing.T) {
<del> skip.If(t, versions.LessThan(testEnv.DaemonAPIVersion(), "1.37"), "test added after 1.37")
<add> skip.If(t, versions.LessThan(testEnv.DaemonAPIVersion(), "1.38"), "test added after 1.38")
<ide> bldName := "build-a"
<ide> testLabels := map[string]string{
<ide> "foo": "bar", | 1 |
Ruby | Ruby | add missing magic comment (linting) | 61bbcb71d502f6bba26cc6334f887975f159c6cb | <ide><path>actioncable/lib/action_cable/zeitwerk.rb
<add># frozen_string_literal: true
<add>
<ide> require "zeitwerk"
<ide>
<ide> lib = File.expand_path("..", __dir__) | 1 |
PHP | PHP | show better exception messages with blade views | bccc3fbaf48bf05800269251fecc6b6f27e3731c | <ide><path>src/Illuminate/View/Engines/CompilerEngine.php
<ide> class CompilerEngine extends PhpEngine {
<ide> */
<ide> protected $compiler;
<ide>
<add> /**
<add> * A stack of the last compiled templates.
<add> *
<add> * @var array
<add> */
<add> protected $lastCompiled = array();
<add>
<ide> /**
<ide> * Create a new Blade view engine instance.
<ide> *
<ide> public function __construct(CompilerInterface $compiler)
<ide> */
<ide> public function get($path, array $data = array())
<ide> {
<add> $this->lastCompiled[] = $path;
<add>
<ide> // If this given view has expired, which means it has simply been edited since
<ide> // it was last compiled, we will re-compile the views so we can evaluate a
<ide> // fresh copy of the view. We'll pass the compiler the path of the view.
<ide> public function get($path, array $data = array())
<ide>
<ide> $compiled = $this->compiler->getCompiledPath($path);
<ide>
<del> return $this->evaluatePath($compiled, $data);
<add> // Once we have the path to the compiled file, we will evaluate the paths with
<add> // typical PHP just like any other templates. We also keep a stack of views
<add> // which have been rendered for right exception messages to be generated.
<add> $results = $this->evaluatePath($compiled, $data);
<add>
<add> array_pop($this->lastCompiled);
<add>
<add> return $results;
<add> }
<add>
<add> /**
<add> * Handle a view exception.
<add> *
<add> * @param Exception $e
<add> * @return void
<add> *
<add> * @throws $e
<add> */
<add> protected function handleViewException($e)
<add> {
<add> $e = new \ErrorException($this->getMessage($e), 0, 1, $e->getFile(), $e->getLine(), $e);
<add>
<add> ob_get_clean(); throw $e;
<add> }
<add>
<add> /**
<add> * Get the exception message for an exception.
<add> *
<add> * @param \Exception $e
<add> * @return string
<add> */
<add> protected function getMessage($e)
<add> {
<add> return $e->getMessage().' (View: '.realpath(last($this->lastCompiled)).')';
<ide> }
<ide>
<ide> /** | 1 |
Javascript | Javascript | simplify constant decls | 08809f28ad797b914bad2dcd21eefba898eaaa4d | <ide><path>lib/internal/fs.js
<ide> const Buffer = require('buffer').Buffer;
<ide> const Writable = require('stream').Writable;
<ide> const fs = require('fs');
<ide> const util = require('util');
<del>const constants = process.binding('constants').fs;
<del>
<del>const O_APPEND = constants.O_APPEND | 0;
<del>const O_CREAT = constants.O_CREAT | 0;
<del>const O_EXCL = constants.O_EXCL | 0;
<del>const O_RDONLY = constants.O_RDONLY | 0;
<del>const O_RDWR = constants.O_RDWR | 0;
<del>const O_SYNC = constants.O_SYNC | 0;
<del>const O_TRUNC = constants.O_TRUNC | 0;
<del>const O_WRONLY = constants.O_WRONLY | 0;
<add>
<add>const {
<add> O_APPEND,
<add> O_CREAT,
<add> O_EXCL,
<add> O_RDONLY,
<add> O_RDWR,
<add> O_SYNC,
<add> O_TRUNC,
<add> O_WRONLY
<add>} = process.binding('constants').fs;
<ide>
<ide> function assertEncoding(encoding) {
<ide> if (encoding && !Buffer.isEncoding(encoding)) { | 1 |
Mixed | Python | fix icu shrinker and docs | a4ffa0cb948d813ad77998c1d5c60a8e5dc52959 | <ide><path>tools/icu/README.md
<ide> make clean
<ide> tools/license-builder.sh
<ide> ```
<ide>
<del>- Now, fix the default URL for the `full-icu` build in `/configure`, in
<add>- Now, fix the default URL for the `full-icu` build in `/configure.py`, in
<ide> the `configure_intl()` function. It should match the ICU URL used in the
<ide> first step. When this is done, the following should build with full ICU.
<ide>
<ide> make
<ide> make test-ci
<ide> ```
<ide>
<del>- commit the change to `configure` along with the updated `LICENSE` file.
<add>- commit the change to `configure.py` along with the updated `LICENSE` file.
<ide>
<ide> - Note: To simplify review, I often will “pre-land” this patch, meaning that
<ide> I run the patch through `curl -L https://github.com/nodejs/node/pull/xxx.patch
<ide><path>tools/icu/shrink-icu-src.py
<ide> parser.add_option('--icutmp',
<ide> action='store',
<ide> dest='icutmp',
<del> default='out/Release/gen/icutmp',
<add> default='out/Release/obj/gen/icutmp',
<ide> help='path to icutmp dir.')
<ide>
<ide> | 2 |
Python | Python | add example for ctrl text generation in docs | 87c8fca9bc39435f518e0b60e44aafc374333886 | <ide><path>src/transformers/modeling_utils.py
<ide> def generate(
<ide> input_ids = torch.tensor(tokenizer.encode(input_context)).unsqueeze(0) # encode input context
<ide> outputs = model.generate(input_ids=input_ids, max_length=40, do_sample=True, temperature=0.7, bos_token_id=tokenizer.bos_token_id, eos_token_ids=tokenizer.eos_token_id, num_beams=3) # generate sequences using beam search decoding (3 beams)
<ide> print('Generated: {}'.format(tokenizer.decode(outputs[0], skip_special_tokens=True)))
<add>
<add> tokenizer = AutoTokenizer.from_pretrained('ctrl') # Initialize tokenizer
<add> model = AutoModelWithLMHead.from_pretrained('ctrl') # Download model and configuration from S3 and cache.
<add> input_context = 'Legal My neighbor is' # "Legal" is one of the control codes for ctrl
<add> input_ids = torch.tensor(tokenizer.encode(input_context)).unsqueeze(0) # encode input context
<add> outputs = model.generate(input_ids=input_ids, max_length=50, temperature=0.7, repetition_penalty=1.2) # generate sequences using using greedy search
<add> print('Generated: {}'.format(tokenizer.decode(outputs[0], skip_special_tokens=True)))
<add>
<ide> """
<ide>
<ide> # We cannot generate if the model does not have a LM head | 1 |
PHP | PHP | add more tests for brace style routes | 7968bbeef315211f2af07b19440b64b37a891aff | <ide><path>src/Routing/Route/Route.php
<ide> protected function _writeRoute()
<ide> $parsed = preg_quote($this->template, '#');
<ide>
<ide> if (strpos($route, '{') !== false && strpos($route, '}') !== false) {
<del> preg_match_all('/\{([a-z0-9-_]+)\}/i', $route, $namedElements);
<add> preg_match_all('/\{([a-z][a-z0-9-_]*)\}/i', $route, $namedElements);
<ide> $this->braceKeys = true;
<ide> } else {
<ide> preg_match_all('/:([a-z0-9-_]+(?<![-_]))/i', $route, $namedElements);
<ide><path>tests/TestCase/Routing/Route/RouteTest.php
<ide> public function testRouteCompileBraces()
<ide> ['controller' => 'Fighters', 'action' => 'move'],
<ide> ['id' => '\d+', 'x' => '\d+', 'y' => '\d+', 'pass' => ['id', 'x', 'y']]
<ide> );
<del> $pattern = $route->compile();
<del> $this->assertRegExp($pattern, '/fighters/123/move/8/42');
<add> $this->assertRegExp($route->compile(), '/fighters/123/move/8/42');
<ide>
<ide> $result = $route->match([
<ide> 'controller' => 'Fighters',
<ide> public function testRouteCompileBraces()
<ide> '/images/{id}/{x}x{y}',
<ide> ['controller' => 'Images', 'action' => 'view']
<ide> );
<del> $pattern = $route->compile();
<del> $this->assertRegExp($pattern, '/images/123/640x480');
<add> $this->assertRegExp($route->compile(), '/images/123/640x480');
<ide>
<ide> $result = $route->match([
<ide> 'controller' => 'Images',
<ide> public function testRouteCompileBraces()
<ide> $this->assertEquals('/images/123/8x42', $result);
<ide> }
<ide>
<add> /**
<add> * Test route compile with brace format.
<add> *
<add> * @return void
<add> */
<add> public function testRouteCompileBracesVariableName()
<add> {
<add> $route = new Route(
<add> '/fighters/{0id}',
<add> ['controller' => 'Fighters', 'action' => 'move']
<add> );
<add> $pattern = $route->compile();
<add> $this->assertNotRegExp($route->compile(), '/fighters/123', 'Placeholders must start with letter');
<add>
<add> $route = new Route('/fighters/{Id}', ['controller' => 'Fighters', 'action' => 'move']);
<add> $this->assertRegExp($route->compile(), '/fighters/123');
<add>
<add> $route = new Route('/fighters/{i_d}', ['controller' => 'Fighters', 'action' => 'move']);
<add> $this->assertRegExp($route->compile(), '/fighters/123');
<add>
<add> $route = new Route('/fighters/{id99}', ['controller' => 'Fighters', 'action' => 'move']);
<add> $this->assertRegExp($route->compile(), '/fighters/123');
<add> }
<add>
<add> /**
<add> * Test route compile with brace format.
<add> *
<add> * @return void
<add> */
<add> public function testRouteCompileBracesInvalid()
<add> {
<add> $route = new Route(
<add> '/fighters/{ id }',
<add> ['controller' => 'Fighters', 'action' => 'move']
<add> );
<add> $this->assertNotRegExp($route->compile(), '/fighters/123', 'no spaces in placeholder');
<add>
<add> $route = new Route(
<add> '/fighters/{i d}',
<add> ['controller' => 'Fighters', 'action' => 'move']
<add> );
<add> $this->assertNotRegExp($route->compile(), '/fighters/123', 'no spaces in placeholder');
<add> }
<add>
<ide> /**
<ide> * Test route compile with mixed placeholder types brace format.
<ide> * | 2 |
Ruby | Ruby | use sprockets-rails from github repo | 757dd93c7fb59965fcb19581281f2f4eec7a7222 | <ide><path>railties/lib/rails/generators/app_base.rb
<ide> def rails_gemfile_entry
<ide> if options.dev?
<ide> [
<ide> GemfileEntry.path('rails', Rails::Generators::RAILS_DEV_PATH),
<add> GemfileEntry.github('sprockets-rails', 'rails/sprockets-rails'),
<ide> GemfileEntry.github('arel', 'rails/arel')
<ide> ]
<ide> elsif options.edge?
<ide> [
<ide> GemfileEntry.github('rails', 'rails/rails'),
<add> GemfileEntry.github('sprockets-rails', 'rails/sprockets-rails'),
<ide> GemfileEntry.github('arel', 'rails/arel')
<ide> ]
<ide> else | 1 |
Java | Java | avoid possible memory leak in resolvabletype | 29d021ae3ce11dacd0793f08524651a23468a06d | <ide><path>spring-core/src/main/java/org/springframework/core/ResolvableType.java
<ide> VariableResolver asVariableResolver() {
<ide> if (this == NONE) {
<ide> return null;
<ide> }
<del> return new DefaultVariableResolver();
<add> return new DefaultVariableResolver(this);
<ide> }
<ide>
<ide> /**
<ide> interface VariableResolver extends Serializable {
<ide>
<ide>
<ide> @SuppressWarnings("serial")
<del> private class DefaultVariableResolver implements VariableResolver {
<add> private static class DefaultVariableResolver implements VariableResolver {
<add>
<add> private final ResolvableType source;
<add>
<add> DefaultVariableResolver(ResolvableType resolvableType) {
<add> this.source = resolvableType;
<add> }
<ide>
<ide> @Override
<ide> @Nullable
<ide> public ResolvableType resolveVariable(TypeVariable<?> variable) {
<del> return ResolvableType.this.resolveVariable(variable);
<add> return this.source.resolveVariable(variable);
<ide> }
<ide>
<ide> @Override
<ide> public Object getSource() {
<del> return ResolvableType.this;
<add> return this.source;
<ide> }
<ide> }
<ide> | 1 |
Go | Go | use gocheck asserts instead of fatal | 22d0be5797fd5561c999e08701e64258ff9d9536 | <ide><path>integration-cli/docker_cli_rename_test.go
<ide> package main
<ide> import (
<ide> "strings"
<ide>
<add> "github.com/docker/docker/pkg/integration/checker"
<ide> "github.com/docker/docker/pkg/stringid"
<ide> "github.com/go-check/check"
<ide> )
<ide> func (s *DockerSuite) TestRenameStoppedContainer(c *check.C) {
<ide> dockerCmd(c, "rename", "first_name", newName)
<ide>
<ide> name, err = inspectField(cleanedContainerID, "Name")
<del> if err != nil {
<del> c.Fatal(err)
<del> }
<del> if name != "/"+newName {
<del> c.Fatal("Failed to rename container ", name)
<del> }
<add> c.Assert(err, checker.IsNil, check.Commentf("Failed to rename container %s", name))
<add> c.Assert(name, checker.Equals, "/"+newName, check.Commentf("Failed to rename container %s", name))
<ide>
<ide> }
<ide>
<ide> func (s *DockerSuite) TestRenameRunningContainer(c *check.C) {
<ide> dockerCmd(c, "rename", "first_name", newName)
<ide>
<ide> name, err := inspectField(cleanedContainerID, "Name")
<del> if err != nil {
<del> c.Fatal(err)
<del> }
<del> if name != "/"+newName {
<del> c.Fatal("Failed to rename container ")
<del> }
<add> c.Assert(err, checker.IsNil, check.Commentf("Failed to rename container %s", name))
<add> c.Assert(name, checker.Equals, "/"+newName, check.Commentf("Failed to rename container %s", name))
<ide> }
<ide>
<ide> func (s *DockerSuite) TestRenameCheckNames(c *check.C) {
<ide> func (s *DockerSuite) TestRenameCheckNames(c *check.C) {
<ide> dockerCmd(c, "rename", "first_name", newName)
<ide>
<ide> name, err := inspectField(newName, "Name")
<del> if err != nil {
<del> c.Fatal(err)
<del> }
<del> if name != "/"+newName {
<del> c.Fatal("Failed to rename container ")
<del> }
<add> c.Assert(err, checker.IsNil, check.Commentf("Failed to rename container %s", name))
<add> c.Assert(name, checker.Equals, "/"+newName, check.Commentf("Failed to rename container %s", name))
<ide>
<ide> name, err = inspectField("first_name", "Name")
<del> if err == nil && !strings.Contains(err.Error(), "No such image or container: first_name") {
<del> c.Fatal(err)
<del> }
<add> c.Assert(err, checker.NotNil, check.Commentf(name))
<add> c.Assert(err.Error(), checker.Contains, "No such image or container: first_name")
<ide> }
<ide>
<ide> func (s *DockerSuite) TestRenameInvalidName(c *check.C) {
<ide> testRequires(c, DaemonIsLinux)
<ide> dockerCmd(c, "run", "--name", "myname", "-d", "busybox", "top")
<ide>
<del> if out, _, err := dockerCmdWithError("rename", "myname", "new:invalid"); err == nil || !strings.Contains(out, "Invalid container name") {
<del> c.Fatalf("Renaming container to invalid name should have failed: %s\n%v", out, err)
<del> }
<add> out, _, err := dockerCmdWithError("rename", "myname", "new:invalid")
<add> c.Assert(err, checker.NotNil, check.Commentf("Renaming container to invalid name should have failed: %s", out))
<add> c.Assert(out, checker.Contains, "Invalid container name", check.Commentf("%v", err))
<ide>
<del> if out, _, err := dockerCmdWithError("rename", "myname", ""); err == nil || !strings.Contains(out, "may be empty") {
<del> c.Fatalf("Renaming container to empty name should have failed: %s\n%v", out, err)
<del> }
<add> out, _, err = dockerCmdWithError("rename", "myname", "")
<add> c.Assert(err, checker.NotNil, check.Commentf("Renaming container to invalid name should have failed: %s", out))
<add> c.Assert(out, checker.Contains, "may be empty", check.Commentf("%v", err))
<ide>
<del> if out, _, err := dockerCmdWithError("rename", "", "newname"); err == nil || !strings.Contains(out, "may be empty") {
<del> c.Fatalf("Renaming container to empty name should have failed: %s\n%v", out, err)
<del> }
<add> out, _, err = dockerCmdWithError("rename", "", "newname")
<add> c.Assert(err, checker.NotNil, check.Commentf("Renaming container with empty name should have failed: %s", out))
<add> c.Assert(out, checker.Contains, "may be empty", check.Commentf("%v", err))
<ide>
<del> if out, _, err := dockerCmdWithError("ps", "-a"); err != nil || !strings.Contains(out, "myname") {
<del> c.Fatalf("Output of docker ps should have included 'myname': %s\n%v", out, err)
<del> }
<add> out, _ = dockerCmd(c, "ps", "-a")
<add> c.Assert(out, checker.Contains, "myname", check.Commentf("Output of docker ps should have included 'myname': %s", out))
<ide> } | 1 |
Ruby | Ruby | add support for invalid foreign keys in postgres | 8203482a9ef9bd60d5014745fd7af868d9954b1d | <ide><path>activerecord/lib/active_record/connection_adapters/abstract/schema_definitions.rb
<ide> def custom_primary_key?
<ide> options[:primary_key] != default_primary_key
<ide> end
<ide>
<add> def validate?
<add> options.fetch(:validate, true)
<add> end
<add> alias validated? validate?
<add>
<ide> def defined_for?(to_table_ord = nil, to_table: nil, **options)
<ide> if to_table_ord
<ide> self.to_table == to_table_ord.to_s
<ide><path>activerecord/lib/active_record/connection_adapters/abstract/schema_statements.rb
<ide> def foreign_keys(table_name)
<ide> # Action that happens <tt>ON DELETE</tt>. Valid values are +:nullify+, +:cascade+ and +:restrict+
<ide> # [<tt>:on_update</tt>]
<ide> # Action that happens <tt>ON UPDATE</tt>. Valid values are +:nullify+, +:cascade+ and +:restrict+
<add> # [<tt>:validate</tt>]
<add> # (Postgres only) Specify whether or not the constraint should be validated. Defaults to +true+.
<ide> def add_foreign_key(from_table, to_table, options = {})
<ide> return unless supports_foreign_keys?
<ide>
<ide><path>activerecord/lib/active_record/connection_adapters/abstract_adapter.rb
<ide> def supports_foreign_keys?
<ide> false
<ide> end
<ide>
<add> # Does this adapter support creating invalid constraints?
<add> def supports_validate_constraints?
<add> false
<add> end
<add>
<ide> # Does this adapter support creating foreign key constraints
<ide> # in the same statement as creating the table?
<ide> def supports_foreign_keys_in_create?
<ide><path>activerecord/lib/active_record/connection_adapters/postgresql/schema_creation.rb
<ide> module ConnectionAdapters
<ide> module PostgreSQL
<ide> class SchemaCreation < AbstractAdapter::SchemaCreation # :nodoc:
<ide> private
<add> def visit_AlterTable(o)
<add> super << o.constraint_validations.map { |fk| visit_ValidateConstraint fk }.join(" ")
<add> end
<add>
<add> def visit_AddForeignKey(o)
<add> super.dup.tap { |sql| sql << " NOT VALID" unless o.validate? }
<add> end
<add>
<add> def visit_ValidateConstraint(name)
<add> "VALIDATE CONSTRAINT #{quote_column_name(name)}"
<add> end
<add>
<ide> def add_column_options!(sql, options)
<ide> if options[:collation]
<ide> sql << " COLLATE \"#{options[:collation]}\""
<ide><path>activerecord/lib/active_record/connection_adapters/postgresql/schema_definitions.rb
<ide> def integer_like_primary_key_type(type, options)
<ide> class Table < ActiveRecord::ConnectionAdapters::Table
<ide> include ColumnMethods
<ide> end
<add>
<add> class AlterTable < ActiveRecord::ConnectionAdapters::AlterTable
<add> attr_reader :constraint_validations
<add>
<add> def initialize(td)
<add> super
<add> @constraint_validations = []
<add> end
<add>
<add> def validate_constraint(name)
<add> @constraint_validations << name
<add> end
<add> end
<ide> end
<ide> end
<ide> end
<ide><path>activerecord/lib/active_record/connection_adapters/postgresql/schema_statements.rb
<ide> def rename_index(table_name, old_name, new_name)
<ide> def foreign_keys(table_name)
<ide> scope = quoted_scope(table_name)
<ide> fk_info = exec_query(<<-SQL.strip_heredoc, "SCHEMA")
<del> SELECT t2.oid::regclass::text AS to_table, a1.attname AS column, a2.attname AS primary_key, c.conname AS name, c.confupdtype AS on_update, c.confdeltype AS on_delete
<add> SELECT t2.oid::regclass::text AS to_table, a1.attname AS column, a2.attname AS primary_key, c.conname AS name, c.confupdtype AS on_update, c.confdeltype AS on_delete, c.convalidated AS valid
<ide> FROM pg_constraint c
<ide> JOIN pg_class t1 ON c.conrelid = t1.oid
<ide> JOIN pg_class t2 ON c.confrelid = t2.oid
<ide> def foreign_keys(table_name)
<ide>
<ide> options[:on_delete] = extract_foreign_key_action(row["on_delete"])
<ide> options[:on_update] = extract_foreign_key_action(row["on_update"])
<add> options[:validate] = row["valid"]
<ide>
<ide> ForeignKeyDefinition.new(table_name, row["to_table"], options)
<ide> end
<ide> def create_schema_dumper(options) # :nodoc:
<ide> PostgreSQL::SchemaDumper.create(self, options)
<ide> end
<ide>
<add> # Validates the given constraint.
<add> #
<add> # Validates the constraint named +constraint_name+ on +accounts+.
<add> #
<add> # validate_foreign_key :accounts, :constraint_name
<add> def validate_constraint(table_name, constraint_name)
<add> return unless supports_validate_constraints?
<add>
<add> at = create_alter_table table_name
<add> at.validate_constraint constraint_name
<add>
<add> execute schema_creation.accept(at)
<add> end
<add>
<add> # Validates the given foreign key.
<add> #
<add> # Validates the foreign key on +accounts.branch_id+.
<add> #
<add> # validate_foreign_key :accounts, :branches
<add> #
<add> # Validates the foreign key on +accounts.owner_id+.
<add> #
<add> # validate_foreign_key :accounts, column: :owner_id
<add> #
<add> # Validates the foreign key named +special_fk_name+ on the +accounts+ table.
<add> #
<add> # validate_foreign_key :accounts, name: :special_fk_name
<add> #
<add> # The +options+ hash accepts the same keys as SchemaStatements#add_foreign_key.
<add> def validate_foreign_key(from_table, options_or_to_table = {})
<add> return unless supports_validate_constraints?
<add>
<add> fk_name_to_validate = foreign_key_for!(from_table, options_or_to_table).name
<add>
<add> validate_constraint from_table, fk_name_to_validate
<add> end
<add>
<ide> private
<ide> def schema_creation
<ide> PostgreSQL::SchemaCreation.new(self)
<ide> def create_table_definition(*args)
<ide> PostgreSQL::TableDefinition.new(*args)
<ide> end
<ide>
<add> def create_alter_table(name)
<add> PostgreSQL::AlterTable.new create_table_definition(name)
<add> end
<add>
<ide> def new_column_from_field(table_name, field)
<ide> column_name, type, default, notnull, oid, fmod, collation, comment = field
<ide> type_metadata = fetch_type_metadata(column_name, type, oid.to_i, fmod.to_i)
<ide><path>activerecord/lib/active_record/connection_adapters/postgresql_adapter.rb
<ide> def supports_foreign_keys?
<ide> true
<ide> end
<ide>
<add> def supports_validate_constraints?
<add> true
<add> end
<add>
<ide> def supports_views?
<ide> true
<ide> end
<ide><path>activerecord/test/cases/migration/foreign_key_test.rb
<ide> def test_remove_foreign_non_existing_foreign_key_raises
<ide> end
<ide> end
<ide>
<add> if ActiveRecord::Base.connection.supports_validate_constraints?
<add> def test_add_invalid_foreign_key
<add> @connection.add_foreign_key :astronauts, :rockets, column: "rocket_id", validate: false
<add>
<add> foreign_keys = @connection.foreign_keys("astronauts")
<add> assert_equal 1, foreign_keys.size
<add>
<add> fk = foreign_keys.first
<add> refute fk.validated?
<add> end
<add>
<add> def test_validate_foreign_key_infers_column
<add> @connection.add_foreign_key :astronauts, :rockets, validate: false
<add> refute @connection.foreign_keys("astronauts").first.validated?
<add>
<add> @connection.validate_foreign_key :astronauts, :rockets
<add> assert @connection.foreign_keys("astronauts").first.validated?
<add> end
<add>
<add> def test_validate_foreign_key_by_column
<add> @connection.add_foreign_key :astronauts, :rockets, column: "rocket_id", validate: false
<add> refute @connection.foreign_keys("astronauts").first.validated?
<add>
<add> @connection.validate_foreign_key :astronauts, column: "rocket_id"
<add> assert @connection.foreign_keys("astronauts").first.validated?
<add> end
<add>
<add> def test_validate_foreign_key_by_symbol_column
<add> @connection.add_foreign_key :astronauts, :rockets, column: :rocket_id, validate: false
<add> refute @connection.foreign_keys("astronauts").first.validated?
<add>
<add> @connection.validate_foreign_key :astronauts, column: :rocket_id
<add> assert @connection.foreign_keys("astronauts").first.validated?
<add> end
<add>
<add> def test_validate_foreign_key_by_name
<add> @connection.add_foreign_key :astronauts, :rockets, column: "rocket_id", name: "fancy_named_fk", validate: false
<add> refute @connection.foreign_keys("astronauts").first.validated?
<add>
<add> @connection.validate_foreign_key :astronauts, name: "fancy_named_fk"
<add> assert @connection.foreign_keys("astronauts").first.validated?
<add> end
<add>
<add> def test_validate_foreign_non_existing_foreign_key_raises
<add> assert_raises ArgumentError do
<add> @connection.validate_foreign_key :astronauts, :rockets
<add> end
<add> end
<add>
<add> def test_validate_constraint_by_name
<add> @connection.add_foreign_key :astronauts, :rockets, column: "rocket_id", name: "fancy_named_fk", validate: false
<add>
<add> @connection.validate_constraint :astronauts, "fancy_named_fk"
<add> assert @connection.foreign_keys("astronauts").first.validated?
<add> end
<add> else
<add> # Foreign key should still be created, but should not be invalid
<add> def test_add_invalid_foreign_key
<add> @connection.add_foreign_key :astronauts, :rockets, column: "rocket_id", validate: false
<add>
<add> foreign_keys = @connection.foreign_keys("astronauts")
<add> assert_equal 1, foreign_keys.size
<add>
<add> fk = foreign_keys.first
<add> assert fk.validated?
<add> end
<add> end
<add>
<ide> def test_schema_dumping
<ide> @connection.add_foreign_key :astronauts, :rockets
<ide> output = dump_table_schema "astronauts" | 8 |
Python | Python | enable sphinx.ext.viewcode extenstion | e06179862d25754691b1ef4b5481e3f94cc748ce | <ide><path>docs/conf.py
<ide>
<ide> # Add any Sphinx extension module names here, as strings. They can be extensions
<ide> # coming with Sphinx (named 'sphinx.ext.*') or your custom ones.
<del>extensions = ['sphinx.ext.autodoc', 'sphinx.ext.intersphinx']
<add>extensions = ['sphinx.ext.autodoc', 'sphinx.ext.intersphinx',
<add> 'sphinx.ext.viewcode']
<ide>
<ide> # Add any paths that contain templates here, relative to this directory.
<ide> templates_path = ['_templates'] | 1 |
PHP | PHP | add `orm_cache clear` command | 038f1fb3b05d18e47cdcc48db079bcd955ba7cb7 | <ide><path>src/Console/Command/OrmCacheShell.php
<ide> */
<ide> namespace Cake\Console\Command;
<ide>
<add>use Cake\Cache\Cache;
<ide> use Cake\Console\Shell;
<ide> use Cake\Datasource\ConnectionManager;
<ide>
<ide> public function build($name = null) {
<ide> $this->_io->verbose('Building metadata cache for ' . $table);
<ide> $schema->describe($table);
<ide> }
<add> $this->out('<success>Cache build complete</success>');
<ide> }
<ide>
<ide> /**
<ide> public function build($name = null) {
<ide> */
<ide> public function clear($name = null) {
<ide> $source = ConnectionManager::get($this->params['connection']);
<add> $schema = $source->schemaCollection();
<add> $tables = [$name];
<add> if (empty($name)) {
<add> $tables = $schema->listTables();
<add> }
<add> if (!$schema->cacheMetadata()) {
<add> $this->_io->verbose('Metadata cache was disabled in config. Enabling to clear cache.');
<add> $schema->cacheMetadata(true);
<add> }
<add> $configName = $schema->cacheMetadata();
<add>
<add> foreach ($tables as $table) {
<add> $this->_io->verbose(sprintf(
<add> 'Clearing metadata cache from "%s" for %s',
<add> $configName,
<add> $table
<add> ));
<add> $key = $schema->cacheKey($table);
<add> Cache::delete($key, $configName);
<add> }
<add> $this->out('<success>Cache clear complete</success>');
<ide> }
<ide>
<ide> /**
<ide><path>src/Database/Schema/Collection.php
<ide> public function listTables() {
<ide> public function describe($name) {
<ide> $cacheConfig = $this->cacheMetadata();
<ide> if ($cacheConfig) {
<del> $cacheKey = $this->_connection->configName() . '_' . $name;
<add> $cacheKey = $this->cacheKey($name);
<ide> $cached = Cache::read($cacheKey, $cacheConfig);
<ide> if ($cached !== false) {
<ide> return $cached;
<ide> public function describe($name) {
<ide> return $table;
<ide> }
<ide>
<add>/**
<add> * Get the cache key for a given name.
<add> *
<add> * @param string $name The name to get a cache key for.
<add> * @return string The cache key.
<add> */
<add> public function cacheKey($name) {
<add> return $this->_connection->configName() . '_' . $name;
<add> }
<add>
<ide> /**
<ide> * Sets the cache config name to use for caching table metadata, or
<ide> * disabels it if false is passed. | 2 |
Go | Go | add useful comments | ad968ef3ef54f3161e8e1012f0ef20b8757ac0aa | <ide><path>devmapper/deviceset_devmapper.go
<ide> func (devices *DeviceSetDM) hasImage(name string) bool {
<ide> return err == nil
<ide> }
<ide>
<add>// ensureImage creates a sparse file of <size> bytes at the path
<add>// <root>/devicemapper/<name>.
<add>// If the file already exists, it does nothing.
<add>// Either way it returns the full path.
<ide> func (devices *DeviceSetDM) ensureImage(name string, size int64) (string, error) {
<ide> dirname := devices.loopbackDir()
<ide> filename := path.Join(dirname, name)
<ide><path>devmapper/devmapper.go
<ide> package devmapper
<ide> #define LOOP_CTL_GET_FREE 0x4C82
<ide> #endif
<ide>
<add>// FIXME: this could easily be rewritten in go
<ide> char* attach_loop_device(const char *filename, int *loop_fd_out)
<ide> {
<ide> struct loop_info64 loopinfo = {0};
<ide> func free(p *C.char) {
<ide> C.free(unsafe.Pointer(p))
<ide> }
<ide>
<add>// This is the programmatic example of "dmsetup create"
<ide> func createPool(poolName string, dataFile *os.File, metadataFile *os.File) error {
<ide> task, err := createTask(DeviceCreate, poolName)
<ide> if task == nil { | 2 |
Python | Python | fix italian tag map | f7485a09c89a071b20189698984af51932c229af | <ide><path>spacy/lang/it/tag_map.py
<ide>
<ide>
<ide> TAG_MAP = {
<del> "AP__Gender=Fem|Number=Plur|Poss=Yes|PronType=Prs": {"pos": "AP"},
<del> "AP__Gender=Fem|Number=Sing|Poss=Yes|PronType=Prs": {"pos": "AP"},
<del> "AP__Gender=Masc|Number=Plur|Poss=Yes|PronType=Prs": {"pos": "AP"},
<del> "AP__Gender=Masc|Number=Sing|Poss=Yes|PronType=Prs": {"pos": "AP"},
<del> "AP__Gender=Masc|Poss=Yes|PronType=Prs": {"pos": "AP"},
<del> "AP__Number=Sing|Poss=Yes|PronType=Prs": {"pos": "AP"},
<del> "AP__Poss=Yes|PronType=Prs": {"pos": "AP"},
<del> "A__Degree=Abs|Gender=Fem|Number=Plur": {"pos": "A"},
<del> "A__Degree=Abs|Gender=Fem|Number=Sing": {"pos": "A"},
<del> "A__Degree=Abs|Gender=Masc|Number=Plur": {"pos": "A"},
<del> "A__Degree=Abs|Gender=Masc|Number=Sing": {"pos": "A"},
<del> "A__Degree=Cmp": {"pos": "A"},
<del> "A__Degree=Cmp|Number=Plur": {"pos": "A"},
<del> "A__Degree=Cmp|Number=Sing": {"pos": "A"},
<del> "A__Gender=Fem|Number=Plur": {"pos": "A"},
<del> "A__Gender=Fem|Number=Sing": {"pos": "A"},
<del> "A__Gender=Fem|Number=Sing|Poss=Yes|PronType=Prs": {"pos": "A"},
<del> "A__Gender=Masc": {"pos": "A"},
<del> "A__Gender=Masc|Number=Plur": {"pos": "A"},
<del> "A__Gender=Masc|Number=Sing": {"pos": "A"},
<del> "A__Number=Plur": {"pos": "A"},
<del> "A__Number=Sing": {"pos": "A"},
<del> "A___": {"pos": "A"},
<del> "BN__PronType=Neg": {"pos": "BN"},
<del> "B__Degree=Abs": {"pos": "B"},
<del> "B__Degree=Abs|Gender=Masc|Number=Sing": {"pos": "B"},
<del> "B___": {"pos": "B"},
<del> "CC___": {"pos": "CC"},
<del> "CS___": {"pos": "CS"},
<del> "DD__Gender=Fem|Number=Plur|PronType=Dem": {"pos": "DD"},
<del> "DD__Gender=Fem|Number=Sing|PronType=Dem": {"pos": "DD"},
<del> "DD__Gender=Masc|Number=Plur|PronType=Dem": {"pos": "DD"},
<del> "DD__Gender=Masc|Number=Sing|PronType=Dem": {"pos": "DD"},
<del> "DD__Gender=Masc|PronType=Dem": {"pos": "DD"},
<del> "DD__Number=Plur|PronType=Dem": {"pos": "DD"},
<del> "DD__Number=Sing|PronType=Dem": {"pos": "DD"},
<del> "DE__PronType=Exc": {"pos": "DE"},
<del> "DI__Definite=Def|Gender=Fem|Number=Plur|PronType=Art": {"pos": "DI"},
<del> "DI__Gender=Fem|Number=Plur": {"pos": "DI"},
<del> "DI__Gender=Fem|Number=Plur|PronType=Ind": {"pos": "DI"},
<del> "DI__Gender=Fem|Number=Sing|PronType=Ind": {"pos": "DI"},
<del> "DI__Gender=Masc|Number=Plur": {"pos": "DI"},
<del> "DI__Gender=Masc|Number=Plur|PronType=Ind": {"pos": "DI"},
<del> "DI__Gender=Masc|Number=Sing|PronType=Ind": {"pos": "DI"},
<del> "DI__Number=Sing|PronType=Art": {"pos": "DI"},
<del> "DI__Number=Sing|PronType=Ind": {"pos": "DI"},
<del> "DI__PronType=Ind": {"pos": "DI"},
<del> "DQ__Gender=Fem|Number=Plur|PronType=Int": {"pos": "DQ"},
<del> "DQ__Gender=Fem|Number=Sing|PronType=Int": {"pos": "DQ"},
<del> "DQ__Gender=Masc|Number=Plur|PronType=Int": {"pos": "DQ"},
<del> "DQ__Gender=Masc|Number=Sing|PronType=Int": {"pos": "DQ"},
<del> "DQ__Number=Plur|PronType=Int": {"pos": "DQ"},
<del> "DQ__Number=Sing|PronType=Int": {"pos": "DQ"},
<del> "DQ__PronType=Int": {"pos": "DQ"},
<del> "DQ___": {"pos": "DQ"},
<del> "DR__Number=Plur|PronType=Rel": {"pos": "DR"},
<del> "DR__PronType=Rel": {"pos": "DR"},
<del> "E__Gender=Masc|Number=Sing": {"pos": "E"},
<del> "E___": {"pos": "E"},
<del> "FB___": {"pos": "FB"},
<del> "FC___": {"pos": "FC"},
<del> "FF___": {"pos": "FF"},
<del> "FS___": {"pos": "FS"},
<del> "I__Polarity=Neg": {"pos": "I"},
<del> "I__Polarity=Pos": {"pos": "I"},
<del> "I___": {"pos": "I"},
<del> "NO__Gender=Fem|Number=Plur|NumType=Ord": {"pos": "NO"},
<del> "NO__Gender=Fem|Number=Sing|NumType=Ord": {"pos": "NO"},
<del> "NO__Gender=Masc|Number=Plur": {"pos": "NO"},
<del> "NO__Gender=Masc|Number=Plur|NumType=Ord": {"pos": "NO"},
<del> "NO__Gender=Masc|Number=Sing|NumType=Ord": {"pos": "NO"},
<del> "NO__NumType=Ord": {"pos": "NO"},
<del> "NO__Number=Sing|NumType=Ord": {"pos": "NO"},
<del> "NO___": {"pos": "NO"},
<del> "N__Gender=Masc|Number=Sing": {"pos": "N"},
<del> "N__NumType=Card": {"pos": "N"},
<del> "N__NumType=Range": {"pos": "N"},
<del> "N___": {"pos": "N"},
<add> "AP__Gender=Fem|Number=Plur|Poss=Yes|PronType=Prs": {"pos": "DET"},
<add> "AP__Gender=Fem|Number=Sing|Poss=Yes|PronType=Prs": {"pos": "DET"},
<add> "AP__Gender=Masc|Number=Plur|Poss=Yes|PronType=Prs": {"pos": "DET"},
<add> "AP__Gender=Masc|Number=Sing|Poss=Yes|PronType=Prs": {"pos": "DET"},
<add> "AP__Gender=Masc|Poss=Yes|PronType=Prs": {"pos": "DET"},
<add> "AP__Number=Sing|Poss=Yes|PronType=Prs": {"pos": "DET"},
<add> "AP__Poss=Yes|PronType=Prs": {"pos": "DET"},
<add> "A__Degree=Abs|Gender=Fem|Number=Plur": {"pos": "ADJ"},
<add> "A__Degree=Abs|Gender=Fem|Number=Sing": {"pos": "ADJ"},
<add> "A__Degree=Abs|Gender=Masc|Number=Plur": {"pos": "ADJ"},
<add> "A__Degree=Abs|Gender=Masc|Number=Sing": {"pos": "ADJ"},
<add> "A__Degree=Cmp": {"pos": "ADJ"},
<add> "A__Degree=Cmp|Number=Plur": {"pos": "ADJ"},
<add> "A__Degree=Cmp|Number=Sing": {"pos": "ADJ"},
<add> "A__Gender=Fem|Number=Plur": {"pos": "ADJ"},
<add> "A__Gender=Fem|Number=Sing": {"pos": "ADJ"},
<add> "A__Gender=Fem|Number=Sing|Poss=Yes|PronType=Prs": {"pos": "ADJ"},
<add> "A__Gender=Masc": {"pos": "ADJ"},
<add> "A__Gender=Masc|Number=Plur": {"pos": "ADJ"},
<add> "A__Gender=Masc|Number=Sing": {"pos": "ADJ"},
<add> "A__Number=Plur": {"pos": "ADJ"},
<add> "A__Number=Sing": {"pos": "ADJ"},
<add> "A___": {"pos": "ADJ"},
<add> "BN__PronType=Neg": {"pos": "ADV"},
<add> "B__Degree=Abs": {"pos": "ADV"},
<add> "B__Degree=Abs|Gender=Masc|Number=Sing": {"pos": "ADV"},
<add> "B___": {"pos": "ADV"},
<add> "CC___": {"pos": "CONJ"},
<add> "CS___": {"pos": "SCONJ"},
<add> "DD__Gender=Fem|Number=Plur|PronType=Dem": {"pos": "DET"},
<add> "DD__Gender=Fem|Number=Sing|PronType=Dem": {"pos": "DET"},
<add> "DD__Gender=Masc|Number=Plur|PronType=Dem": {"pos": "DET"},
<add> "DD__Gender=Masc|Number=Sing|PronType=Dem": {"pos": "DET"},
<add> "DD__Gender=Masc|PronType=Dem": {"pos": "DET"},
<add> "DD__Number=Plur|PronType=Dem": {"pos": "DET"},
<add> "DD__Number=Sing|PronType=Dem": {"pos": "DET"},
<add> "DE__PronType=Exc": {"pos": "DET"},
<add> "DI__Definite=Def|Gender=Fem|Number=Plur|PronType=Art": {"pos": "DET"},
<add> "DI__Gender=Fem|Number=Plur": {"pos": "DET"},
<add> "DI__Gender=Fem|Number=Plur|PronType=Ind": {"pos": "DET"},
<add> "DI__Gender=Fem|Number=Sing|PronType=Ind": {"pos": "DET"},
<add> "DI__Gender=Masc|Number=Plur": {"pos": "DET"},
<add> "DI__Gender=Masc|Number=Plur|PronType=Ind": {"pos": "DET"},
<add> "DI__Gender=Masc|Number=Sing|PronType=Ind": {"pos": "DET"},
<add> "DI__Number=Sing|PronType=Art": {"pos": "DET"},
<add> "DI__Number=Sing|PronType=Ind": {"pos": "DET"},
<add> "DI__PronType=Ind": {"pos": "DET"},
<add> "DQ__Gender=Fem|Number=Plur|PronType=Int": {"pos": "DET"},
<add> "DQ__Gender=Fem|Number=Sing|PronType=Int": {"pos": "DET"},
<add> "DQ__Gender=Masc|Number=Plur|PronType=Int": {"pos": "DET"},
<add> "DQ__Gender=Masc|Number=Sing|PronType=Int": {"pos": "DET"},
<add> "DQ__Number=Plur|PronType=Int": {"pos": "DET"},
<add> "DQ__Number=Sing|PronType=Int": {"pos": "DET"},
<add> "DQ__PronType=Int": {"pos": "DET"},
<add> "DQ___": {"pos": "DET"},
<add> "DR__Number=Plur|PronType=Rel": {"pos": "DET"},
<add> "DR__PronType=Rel": {"pos": "DET"},
<add> "E__Gender=Masc|Number=Sing": {"pos": "ADP"},
<add> "E___": {"pos": "ADP"},
<add> "FB___": {"pos": "PUNCT"},
<add> "FC___": {"pos": "PUNCT"},
<add> "FF___": {"pos": "PUNCT"},
<add> "FS___": {"pos": "PUNCT"},
<add> "I__Polarity=Neg": {"pos": "INTJ"},
<add> "I__Polarity=Pos": {"pos": "INTJ"},
<add> "I___": {"pos": "INTJ"},
<add> "NO__Gender=Fem|Number=Plur|NumType=Ord": {"pos": "ADJ"},
<add> "NO__Gender=Fem|Number=Sing|NumType=Ord": {"pos": "ADJ"},
<add> "NO__Gender=Masc|Number=Plur": {"pos": "ADJ"},
<add> "NO__Gender=Masc|Number=Plur|NumType=Ord": {"pos": "ADJ"},
<add> "NO__Gender=Masc|Number=Sing|NumType=Ord": {"pos": "ADJ"},
<add> "NO__NumType=Ord": {"pos": "ADJ"},
<add> "NO__Number=Sing|NumType=Ord": {"pos": "ADJ"},
<add> "NO___": {"pos": "ADJ"},
<add> "N__Gender=Masc|Number=Sing": {"pos": "NUM"},
<add> "N__NumType=Card": {"pos": "NUM"},
<add> "N__NumType=Range": {"pos": "NUM"},
<add> "N___": {"pos": "NUM"},
<ide> "PART___": {"pos": "PART"},
<del> "PC__Clitic=Yes|Definite=Def|Gender=Fem|Number=Plur|PronType=Art": {"pos": "PC"},
<del> "PC__Clitic=Yes|Gender=Fem|Number=Plur|Person=3|PronType=Prs": {"pos": "PC"},
<del> "PC__Clitic=Yes|Gender=Fem|Number=Plur|PronType=Prs": {"pos": "PC"},
<del> "PC__Clitic=Yes|Gender=Fem|Number=Sing|Person=3|PronType=Prs": {"pos": "PC"},
<del> "PC__Clitic=Yes|Gender=Fem|Person=3|PronType=Prs": {"pos": "PC"},
<del> "PC__Clitic=Yes|Gender=Masc|Number=Plur|Person=3|PronType=Prs": {"pos": "PC"},
<del> "PC__Clitic=Yes|Gender=Masc|Number=Sing|Person=3|PronType=Prs": {"pos": "PC"},
<del> "PC__Clitic=Yes|Gender=Masc|Number=Sing|PronType=Prs": {"pos": "PC"},
<del> "PC__Clitic=Yes|Number=Plur|Person=1|PronType=Prs": {"pos": "PC"},
<del> "PC__Clitic=Yes|Number=Plur|Person=2|PronType=Prs": {"pos": "PC"},
<del> "PC__Clitic=Yes|Number=Plur|Person=3|PronType=Prs": {"pos": "PC"},
<del> "PC__Clitic=Yes|Number=Plur|PronType=Prs": {"pos": "PC"},
<del> "PC__Clitic=Yes|Number=Sing|Person=1|PronType=Prs": {"pos": "PC"},
<del> "PC__Clitic=Yes|Number=Sing|Person=2|PronType=Prs": {"pos": "PC"},
<del> "PC__Clitic=Yes|Number=Sing|Person=3|PronType=Prs": {"pos": "PC"},
<del> "PC__Clitic=Yes|Person=3|PronType=Prs": {"pos": "PC"},
<del> "PC__Clitic=Yes|PronType=Prs": {"pos": "PC"},
<del> "PD__Gender=Fem|Number=Plur|PronType=Dem": {"pos": "PD"},
<del> "PD__Gender=Fem|Number=Sing|PronType=Dem": {"pos": "PD"},
<del> "PD__Gender=Masc|Number=Plur|PronType=Dem": {"pos": "PD"},
<del> "PD__Gender=Masc|Number=Sing|PronType=Dem": {"pos": "PD"},
<del> "PD__Number=Plur|PronType=Dem": {"pos": "PD"},
<del> "PD__Number=Sing|PronType=Dem": {"pos": "PD"},
<del> "PD__PronType=Dem": {"pos": "PD"},
<del> "PE__Gender=Fem|Number=Plur|Person=3|PronType=Prs": {"pos": "PE"},
<del> "PE__Gender=Fem|Number=Sing|Person=3|PronType=Prs": {"pos": "PE"},
<del> "PE__Gender=Masc|Number=Plur|Person=3|PronType=Prs": {"pos": "PE"},
<del> "PE__Gender=Masc|Number=Sing|Person=3|PronType=Prs": {"pos": "PE"},
<del> "PE__Number=Plur|Person=1|PronType=Prs": {"pos": "PE"},
<del> "PE__Number=Plur|Person=2|PronType=Prs": {"pos": "PE"},
<del> "PE__Number=Plur|Person=3|PronType=Prs": {"pos": "PE"},
<del> "PE__Number=Sing|Person=1|PronType=Prs": {"pos": "PE"},
<del> "PE__Number=Sing|Person=2|PronType=Prs": {"pos": "PE"},
<del> "PE__Number=Sing|Person=3|PronType=Prs": {"pos": "PE"},
<del> "PE__Person=3|PronType=Prs": {"pos": "PE"},
<del> "PE__PronType=Prs": {"pos": "PE"},
<del> "PI__Gender=Fem|Number=Plur|PronType=Ind": {"pos": "PI"},
<del> "PI__Gender=Fem|Number=Sing|PronType=Ind": {"pos": "PI"},
<del> "PI__Gender=Masc|Number=Plur|PronType=Ind": {"pos": "PI"},
<del> "PI__Gender=Masc|Number=Sing": {"pos": "PI"},
<del> "PI__Gender=Masc|Number=Sing|PronType=Ind": {"pos": "PI"},
<del> "PI__Number=Plur|PronType=Ind": {"pos": "PI"},
<del> "PI__Number=Sing|PronType=Ind": {"pos": "PI"},
<del> "PI__PronType=Ind": {"pos": "PI"},
<del> "PP__Gender=Fem|Number=Sing|Poss=Yes|PronType=Prs": {"pos": "PP"},
<del> "PP__Gender=Masc|Number=Plur|Poss=Yes|PronType=Prs": {"pos": "PP"},
<del> "PP__Gender=Masc|Number=Sing|Poss=Yes|PronType=Prs": {"pos": "PP"},
<del> "PP__Number=Plur|Poss=Yes|PronType=Prs": {"pos": "PP"},
<del> "PP__Number=Sing|Poss=Yes|PronType=Prs": {"pos": "PP"},
<del> "PQ__Gender=Fem|Number=Plur|PronType=Int": {"pos": "PQ"},
<del> "PQ__Gender=Fem|Number=Sing|PronType=Int": {"pos": "PQ"},
<del> "PQ__Gender=Masc|Number=Plur|PronType=Int": {"pos": "PQ"},
<del> "PQ__Gender=Masc|Number=Sing|PronType=Int": {"pos": "PQ"},
<del> "PQ__Number=Plur|PronType=Int": {"pos": "PQ"},
<del> "PQ__Number=Sing|PronType=Int": {"pos": "PQ"},
<del> "PQ__PronType=Int": {"pos": "PQ"},
<del> "PR__Gender=Masc|Number=Plur|PronType=Rel": {"pos": "PR"},
<del> "PR__Gender=Masc|Number=Sing|PronType=Rel": {"pos": "PR"},
<del> "PR__Gender=Masc|PronType=Rel": {"pos": "PR"},
<del> "PR__Number=Plur|PronType=Rel": {"pos": "PR"},
<del> "PR__Number=Sing|PronType=Rel": {"pos": "PR"},
<del> "PR__Person=3|PronType=Rel": {"pos": "PR"},
<del> "PR__PronType=Rel": {"pos": "PR"},
<del> "RD__Definite=Def": {"pos": "RD"},
<del> "RD__Definite=Def|Gender=Fem": {"pos": "RD"},
<del> "RD__Definite=Def|Gender=Fem|Number=Plur|PronType=Art": {"pos": "RD"},
<del> "RD__Definite=Def|Gender=Fem|Number=Sing|PronType=Art": {"pos": "RD"},
<del> "RD__Definite=Def|Gender=Masc|Number=Plur|PronType=Art": {"pos": "RD"},
<del> "RD__Definite=Def|Gender=Masc|Number=Sing|PronType=Art": {"pos": "RD"},
<del> "RD__Definite=Def|Number=Plur|PronType=Art": {"pos": "RD"},
<del> "RD__Definite=Def|Number=Sing|PronType=Art": {"pos": "RD"},
<del> "RD__Definite=Def|PronType=Art": {"pos": "RD"},
<del> "RD__Gender=Fem|Number=Sing": {"pos": "RD"},
<del> "RD__Gender=Masc|Number=Sing": {"pos": "RD"},
<del> "RD__Number=Sing": {"pos": "RD"},
<del> "RD__Number=Sing|PronType=Art": {"pos": "RD"},
<del> "RI__Definite=Ind|Gender=Fem|Number=Plur|PronType=Art": {"pos": "RI"},
<del> "RI__Definite=Ind|Gender=Fem|Number=Sing|PronType=Art": {"pos": "RI"},
<del> "RI__Definite=Ind|Gender=Masc|Number=Plur|PronType=Art": {"pos": "RI"},
<del> "RI__Definite=Ind|Gender=Masc|Number=Sing|PronType=Art": {"pos": "RI"},
<del> "RI__Definite=Ind|Number=Sing|PronType=Art": {"pos": "RI"},
<del> "RI__Definite=Ind|PronType=Art": {"pos": "RI"},
<del> "SP__Gender=Fem|Number=Plur": {"pos": "SP"},
<del> "SP__NumType=Card": {"pos": "SP"},
<del> "SP___": {"pos": "SP"},
<del> "SW__Foreign=Yes": {"pos": "SW"},
<del> "SW__Foreign=Yes|Gender=Masc": {"pos": "SW"},
<del> "SW__Foreign=Yes|Number=Sing": {"pos": "SW"},
<add> "PC__Clitic=Yes|Definite=Def|Gender=Fem|Number=Plur|PronType=Art": {"pos": "PRON"},
<add> "PC__Clitic=Yes|Gender=Fem|Number=Plur|Person=3|PronType=Prs": {"pos": "PRON"},
<add> "PC__Clitic=Yes|Gender=Fem|Number=Plur|PronType=Prs": {"pos": "PRON"},
<add> "PC__Clitic=Yes|Gender=Fem|Number=Sing|Person=3|PronType=Prs": {"pos": "PRON"},
<add> "PC__Clitic=Yes|Gender=Fem|Person=3|PronType=Prs": {"pos": "PRON"},
<add> "PC__Clitic=Yes|Gender=Masc|Number=Plur|Person=3|PronType=Prs": {"pos": "PRON"},
<add> "PC__Clitic=Yes|Gender=Masc|Number=Sing|Person=3|PronType=Prs": {"pos": "PRON"},
<add> "PC__Clitic=Yes|Gender=Masc|Number=Sing|PronType=Prs": {"pos": "PRON"},
<add> "PC__Clitic=Yes|Number=Plur|Person=1|PronType=Prs": {"pos": "PRON"},
<add> "PC__Clitic=Yes|Number=Plur|Person=2|PronType=Prs": {"pos": "PRON"},
<add> "PC__Clitic=Yes|Number=Plur|Person=3|PronType=Prs": {"pos": "PRON"},
<add> "PC__Clitic=Yes|Number=Plur|PronType=Prs": {"pos": "PRON"},
<add> "PC__Clitic=Yes|Number=Sing|Person=1|PronType=Prs": {"pos": "PRON"},
<add> "PC__Clitic=Yes|Number=Sing|Person=2|PronType=Prs": {"pos": "PRON"},
<add> "PC__Clitic=Yes|Number=Sing|Person=3|PronType=Prs": {"pos": "PRON"},
<add> "PC__Clitic=Yes|Person=3|PronType=Prs": {"pos": "PRON"},
<add> "PC__Clitic=Yes|PronType=Prs": {"pos": "PRON"},
<add> "PD__Gender=Fem|Number=Plur|PronType=Dem": {"pos": "PRON"},
<add> "PD__Gender=Fem|Number=Sing|PronType=Dem": {"pos": "PRON"},
<add> "PD__Gender=Masc|Number=Plur|PronType=Dem": {"pos": "PRON"},
<add> "PD__Gender=Masc|Number=Sing|PronType=Dem": {"pos": "PRON"},
<add> "PD__Number=Plur|PronType=Dem": {"pos": "PRON"},
<add> "PD__Number=Sing|PronType=Dem": {"pos": "PRON"},
<add> "PD__PronType=Dem": {"pos": "PRON"},
<add> "PE__Gender=Fem|Number=Plur|Person=3|PronType=Prs": {"pos": "PRON"},
<add> "PE__Gender=Fem|Number=Sing|Person=3|PronType=Prs": {"pos": "PRON"},
<add> "PE__Gender=Masc|Number=Plur|Person=3|PronType=Prs": {"pos": "PRON"},
<add> "PE__Gender=Masc|Number=Sing|Person=3|PronType=Prs": {"pos": "PRON"},
<add> "PE__Number=Plur|Person=1|PronType=Prs": {"pos": "PRON"},
<add> "PE__Number=Plur|Person=2|PronType=Prs": {"pos": "PRON"},
<add> "PE__Number=Plur|Person=3|PronType=Prs": {"pos": "PRON"},
<add> "PE__Number=Sing|Person=1|PronType=Prs": {"pos": "PRON"},
<add> "PE__Number=Sing|Person=2|PronType=Prs": {"pos": "PRON"},
<add> "PE__Number=Sing|Person=3|PronType=Prs": {"pos": "PRON"},
<add> "PE__Person=3|PronType=Prs": {"pos": "PRON"},
<add> "PE__PronType=Prs": {"pos": "PRON"},
<add> "PI__Gender=Fem|Number=Plur|PronType=Ind": {"pos": "PRON"},
<add> "PI__Gender=Fem|Number=Sing|PronType=Ind": {"pos": "PRON"},
<add> "PI__Gender=Masc|Number=Plur|PronType=Ind": {"pos": "PRON"},
<add> "PI__Gender=Masc|Number=Sing": {"pos": "PRON"},
<add> "PI__Gender=Masc|Number=Sing|PronType=Ind": {"pos": "PRON"},
<add> "PI__Number=Plur|PronType=Ind": {"pos": "PRON"},
<add> "PI__Number=Sing|PronType=Ind": {"pos": "PRON"},
<add> "PI__PronType=Ind": {"pos": "PRON"},
<add> "PP__Gender=Fem|Number=Sing|Poss=Yes|PronType=Prs": {"pos": "PRON"},
<add> "PP__Gender=Masc|Number=Plur|Poss=Yes|PronType=Prs": {"pos": "PRON"},
<add> "PP__Gender=Masc|Number=Sing|Poss=Yes|PronType=Prs": {"pos": "PRON"},
<add> "PP__Number=Plur|Poss=Yes|PronType=Prs": {"pos": "PRON"},
<add> "PP__Number=Sing|Poss=Yes|PronType=Prs": {"pos": "PRON"},
<add> "PQ__Gender=Fem|Number=Plur|PronType=Int": {"pos": "PRON"},
<add> "PQ__Gender=Fem|Number=Sing|PronType=Int": {"pos": "PRON"},
<add> "PQ__Gender=Masc|Number=Plur|PronType=Int": {"pos": "PRON"},
<add> "PQ__Gender=Masc|Number=Sing|PronType=Int": {"pos": "PRON"},
<add> "PQ__Number=Plur|PronType=Int": {"pos": "PRON"},
<add> "PQ__Number=Sing|PronType=Int": {"pos": "PRON"},
<add> "PQ__PronType=Int": {"pos": "PRON"},
<add> "PR__Gender=Masc|Number=Plur|PronType=Rel": {"pos": "PRON"},
<add> "PR__Gender=Masc|Number=Sing|PronType=Rel": {"pos": "PRON"},
<add> "PR__Gender=Masc|PronType=Rel": {"pos": "PRON"},
<add> "PR__Number=Plur|PronType=Rel": {"pos": "PRON"},
<add> "PR__Number=Sing|PronType=Rel": {"pos": "PRON"},
<add> "PR__Person=3|PronType=Rel": {"pos": "PRON"},
<add> "PR__PronType=Rel": {"pos": "PRON"},
<add> "RD__Definite=Def": {"pos": "DET"},
<add> "RD__Definite=Def|Gender=Fem": {"pos": "DET"},
<add> "RD__Definite=Def|Gender=Fem|Number=Plur|PronType=Art": {"pos": "DET"},
<add> "RD__Definite=Def|Gender=Fem|Number=Sing|PronType=Art": {"pos": "DET"},
<add> "RD__Definite=Def|Gender=Masc|Number=Plur|PronType=Art": {"pos": "DET"},
<add> "RD__Definite=Def|Gender=Masc|Number=Sing|PronType=Art": {"pos": "DET"},
<add> "RD__Definite=Def|Number=Plur|PronType=Art": {"pos": "DET"},
<add> "RD__Definite=Def|Number=Sing|PronType=Art": {"pos": "DET"},
<add> "RD__Definite=Def|PronType=Art": {"pos": "DET"},
<add> "RD__Gender=Fem|Number=Sing": {"pos": "DET"},
<add> "RD__Gender=Masc|Number=Sing": {"pos": "DET"},
<add> "RD__Number=Sing": {"pos": "DET"},
<add> "RD__Number=Sing|PronType=Art": {"pos": "DET"},
<add> "RI__Definite=Ind|Gender=Fem|Number=Plur|PronType=Art": {"pos": "DET"},
<add> "RI__Definite=Ind|Gender=Fem|Number=Sing|PronType=Art": {"pos": "DET"},
<add> "RI__Definite=Ind|Gender=Masc|Number=Plur|PronType=Art": {"pos": "DET"},
<add> "RI__Definite=Ind|Gender=Masc|Number=Sing|PronType=Art": {"pos": "DET"},
<add> "RI__Definite=Ind|Number=Sing|PronType=Art": {"pos": "DET"},
<add> "RI__Definite=Ind|PronType=Art": {"pos": "DET"},
<add> "SP__Gender=Fem|Number=Plur": {"pos": "PROPN"},
<add> "SP__NumType=Card": {"pos": "PROPN"},
<add> "SP___": {"pos": "PROPN"},
<add> "SW__Foreign=Yes": {"pos": "X"},
<add> "SW__Foreign=Yes|Gender=Masc": {"pos": "X"},
<add> "SW__Foreign=Yes|Number=Sing": {"pos": "X"},
<ide> "SYM___": {"pos": "SYM"},
<del> "S__Gender=Fem": {"pos": "S"},
<del> "S__Gender=Fem|Number=Plur": {"pos": "S"},
<del> "S__Gender=Fem|Number=Sing": {"pos": "S"},
<del> "S__Gender=Masc": {"pos": "S"},
<del> "S__Gender=Masc|Number=Plur": {"pos": "S"},
<del> "S__Gender=Masc|Number=Sing": {"pos": "S"},
<del> "S__Gender=Masc|Number=Sing|Tense=Past|VerbForm=Part": {"pos": "S"},
<del> "S__Number=Plur": {"pos": "S"},
<del> "S__Number=Sing": {"pos": "S"},
<del> "S___": {"pos": "S"},
<del> "Sw___": {"pos": "Sw"},
<del> "T__Gender=Fem|Number=Plur|PronType=Tot": {"pos": "T"},
<del> "T__Gender=Fem|Number=Sing": {"pos": "T"},
<del> "T__Gender=Fem|Number=Sing|PronType=Tot": {"pos": "T"},
<del> "T__Gender=Masc|Number=Plur|PronType=Tot": {"pos": "T"},
<del> "T__Gender=Masc|Number=Sing|PronType=Tot": {"pos": "T"},
<del> "T__Number=Plur|PronType=Tot": {"pos": "T"},
<del> "T__PronType=Tot": {"pos": "T"},
<del> "VA__Gender=Fem|Number=Plur|Tense=Past|VerbForm=Part": {"pos": "VA"},
<del> "VA__Gender=Fem|Number=Sing|Tense=Past|VerbForm=Part": {"pos": "VA"},
<del> "VA__Gender=Masc|Number=Plur|Tense=Past|VerbForm=Part": {"pos": "VA"},
<del> "VA__Gender=Masc|Number=Sing|Tense=Past|VerbForm=Part": {"pos": "VA"},
<del> "VA__Mood=Cnd|Number=Plur|Person=1|Tense=Pres|VerbForm=Fin": {"pos": "VA"},
<del> "VA__Mood=Cnd|Number=Plur|Person=3|Tense=Pres|VerbForm=Fin": {"pos": "VA"},
<del> "VA__Mood=Cnd|Number=Sing|Person=1|Tense=Pres|VerbForm=Fin": {"pos": "VA"},
<del> "VA__Mood=Cnd|Number=Sing|Person=3|Tense=Pres|VerbForm=Fin": {"pos": "VA"},
<del> "VA__Mood=Ind|Number=Plur|Person=1|Tense=Fut|VerbForm=Fin": {"pos": "VA"},
<del> "VA__Mood=Ind|Number=Plur|Person=1|Tense=Imp|VerbForm=Fin": {"pos": "VA"},
<del> "VA__Mood=Ind|Number=Plur|Person=1|Tense=Pres|VerbForm=Fin": {"pos": "VA"},
<del> "VA__Mood=Ind|Number=Plur|Person=2|Tense=Fut|VerbForm=Fin": {"pos": "VA"},
<del> "VA__Mood=Ind|Number=Plur|Person=2|Tense=Imp|VerbForm=Fin": {"pos": "VA"},
<del> "VA__Mood=Ind|Number=Plur|Person=2|Tense=Pres|VerbForm=Fin": {"pos": "VA"},
<del> "VA__Mood=Ind|Number=Plur|Person=3|Tense=Fut|VerbForm=Fin": {"pos": "VA"},
<del> "VA__Mood=Ind|Number=Plur|Person=3|Tense=Imp|VerbForm=Fin": {"pos": "VA"},
<del> "VA__Mood=Ind|Number=Plur|Person=3|Tense=Past|VerbForm=Fin": {"pos": "VA"},
<del> "VA__Mood=Ind|Number=Plur|Person=3|Tense=Pres|VerbForm=Fin": {"pos": "VA"},
<del> "VA__Mood=Ind|Number=Sing|Person=1|Tense=Fut|VerbForm=Fin": {"pos": "VA"},
<del> "VA__Mood=Ind|Number=Sing|Person=1|Tense=Imp|VerbForm=Fin": {"pos": "VA"},
<del> "VA__Mood=Ind|Number=Sing|Person=1|Tense=Past|VerbForm=Fin": {"pos": "VA"},
<del> "VA__Mood=Ind|Number=Sing|Person=1|Tense=Pres|VerbForm=Fin": {"pos": "VA"},
<del> "VA__Mood=Ind|Number=Sing|Person=2|Tense=Fut|VerbForm=Fin": {"pos": "VA"},
<del> "VA__Mood=Ind|Number=Sing|Person=2|Tense=Pres|VerbForm=Fin": {"pos": "VA"},
<del> "VA__Mood=Ind|Number=Sing|Person=3|Tense=Fut|VerbForm=Fin": {"pos": "VA"},
<del> "VA__Mood=Ind|Number=Sing|Person=3|Tense=Imp|VerbForm=Fin": {"pos": "VA"},
<del> "VA__Mood=Ind|Number=Sing|Person=3|Tense=Past|VerbForm=Fin": {"pos": "VA"},
<del> "VA__Mood=Ind|Number=Sing|Person=3|Tense=Pres|VerbForm=Fin": {"pos": "VA"},
<del> "VA__Mood=Sub|Number=Plur|Person=2|Tense=Pres|VerbForm=Fin": {"pos": "VA"},
<del> "VA__Mood=Sub|Number=Plur|Person=3|Tense=Imp|VerbForm=Fin": {"pos": "VA"},
<del> "VA__Mood=Sub|Number=Plur|Person=3|Tense=Pres|VerbForm=Fin": {"pos": "VA"},
<del> "VA__Mood=Sub|Number=Sing|Person=1|Tense=Imp|VerbForm=Fin": {"pos": "VA"},
<del> "VA__Mood=Sub|Number=Sing|Person=3|Tense=Imp|VerbForm=Fin": {"pos": "VA"},
<del> "VA__Mood=Sub|Number=Sing|Person=3|Tense=Pres|VerbForm=Fin": {"pos": "VA"},
<del> "VA__VerbForm=Ger": {"pos": "VA"},
<del> "VA__VerbForm=Inf": {"pos": "VA"},
<del> "VM__Gender=Fem|Number=Sing|Tense=Past|VerbForm=Part": {"pos": "VM"},
<del> "VM__Gender=Masc|Number=Sing|Tense=Past|VerbForm=Part": {"pos": "VM"},
<del> "VM__Mood=Cnd|Number=Plur|Person=1|Tense=Pres|VerbForm=Fin": {"pos": "VM"},
<del> "VM__Mood=Cnd|Number=Plur|Person=2|Tense=Pres|VerbForm=Fin": {"pos": "VM"},
<del> "VM__Mood=Cnd|Number=Plur|Person=3|Tense=Pres|VerbForm=Fin": {"pos": "VM"},
<del> "VM__Mood=Cnd|Number=Sing|Person=1|Tense=Pres|VerbForm=Fin": {"pos": "VM"},
<del> "VM__Mood=Cnd|Number=Sing|Person=2|Tense=Pres|VerbForm=Fin": {"pos": "VM"},
<del> "VM__Mood=Cnd|Number=Sing|Person=3|Tense=Pres|VerbForm=Fin": {"pos": "VM"},
<del> "VM__Mood=Imp|Number=Plur|Person=2|Tense=Pres|VerbForm=Fin": {"pos": "VM"},
<del> "VM__Mood=Imp|Number=Sing|Person=2|Tense=Pres|VerbForm=Fin": {"pos": "VM"},
<del> "VM__Mood=Ind|Number=Plur|Person=1|Tense=Fut|VerbForm=Fin": {"pos": "VM"},
<del> "VM__Mood=Ind|Number=Plur|Person=1|Tense=Imp|VerbForm=Fin": {"pos": "VM"},
<del> "VM__Mood=Ind|Number=Plur|Person=1|Tense=Pres|VerbForm=Fin": {"pos": "VM"},
<del> "VM__Mood=Ind|Number=Plur|Person=2|Tense=Fut|VerbForm=Fin": {"pos": "VM"},
<del> "VM__Mood=Ind|Number=Plur|Person=2|Tense=Pres|VerbForm=Fin": {"pos": "VM"},
<del> "VM__Mood=Ind|Number=Plur|Person=3|Tense=Fut|VerbForm=Fin": {"pos": "VM"},
<del> "VM__Mood=Ind|Number=Plur|Person=3|Tense=Imp|VerbForm=Fin": {"pos": "VM"},
<del> "VM__Mood=Ind|Number=Plur|Person=3|Tense=Past|VerbForm=Fin": {"pos": "VM"},
<del> "VM__Mood=Ind|Number=Plur|Person=3|Tense=Pres|VerbForm=Fin": {"pos": "VM"},
<del> "VM__Mood=Ind|Number=Sing|Person=1|Tense=Imp|VerbForm=Fin": {"pos": "VM"},
<del> "VM__Mood=Ind|Number=Sing|Person=1|Tense=Pres|VerbForm=Fin": {"pos": "VM"},
<del> "VM__Mood=Ind|Number=Sing|Person=2|Tense=Fut|VerbForm=Fin": {"pos": "VM"},
<del> "VM__Mood=Ind|Number=Sing|Person=2|Tense=Imp|VerbForm=Fin": {"pos": "VM"},
<del> "VM__Mood=Ind|Number=Sing|Person=2|Tense=Pres|VerbForm=Fin": {"pos": "VM"},
<del> "VM__Mood=Ind|Number=Sing|Person=3|Tense=Fut|VerbForm=Fin": {"pos": "VM"},
<del> "VM__Mood=Ind|Number=Sing|Person=3|Tense=Imp|VerbForm=Fin": {"pos": "VM"},
<del> "VM__Mood=Ind|Number=Sing|Person=3|Tense=Past|VerbForm=Fin": {"pos": "VM"},
<del> "VM__Mood=Ind|Number=Sing|Person=3|Tense=Pres|VerbForm=Fin": {"pos": "VM"},
<del> "VM__Mood=Sub|Number=Plur|Person=1|Tense=Imp|VerbForm=Fin": {"pos": "VM"},
<del> "VM__Mood=Sub|Number=Plur|Person=1|Tense=Pres|VerbForm=Fin": {"pos": "VM"},
<del> "VM__Mood=Sub|Number=Plur|Person=3|Tense=Imp|VerbForm=Fin": {"pos": "VM"},
<del> "VM__Mood=Sub|Number=Plur|Person=3|Tense=Pres|VerbForm=Fin": {"pos": "VM"},
<del> "VM__Mood=Sub|Number=Sing|Person=3|Tense=Imp|VerbForm=Fin": {"pos": "VM"},
<del> "VM__Mood=Sub|Number=Sing|Person=3|Tense=Pres|VerbForm=Fin": {"pos": "VM"},
<del> "VM__VerbForm=Ger": {"pos": "VM"},
<del> "VM__VerbForm=Inf": {"pos": "VM"},
<del> "V__Gender=Fem|Number=Plur|Tense=Past|VerbForm=Part": {"pos": "V"},
<del> "V__Gender=Fem|Number=Sing|Tense=Past|VerbForm=Part": {"pos": "V"},
<del> "V__Gender=Masc|Number=Plur|Tense=Past|VerbForm=Fin": {"pos": "V"},
<del> "V__Gender=Masc|Number=Plur|Tense=Past|VerbForm=Part": {"pos": "V"},
<del> "V__Gender=Masc|Number=Sing|Tense=Past|VerbForm=Part": {"pos": "V"},
<del> "V__Mood=Cnd|Number=Plur|Person=1|Tense=Pres|VerbForm=Fin": {"pos": "V"},
<del> "V__Mood=Cnd|Number=Plur|Person=2|Tense=Pres|VerbForm=Fin": {"pos": "V"},
<del> "V__Mood=Cnd|Number=Plur|Person=3|Tense=Pres|VerbForm=Fin": {"pos": "V"},
<del> "V__Mood=Cnd|Number=Sing|Person=1|Tense=Pres|VerbForm=Fin": {"pos": "V"},
<del> "V__Mood=Cnd|Number=Sing|Person=2|Tense=Pres|VerbForm=Fin": {"pos": "V"},
<del> "V__Mood=Cnd|Number=Sing|Person=3|Tense=Pres|VerbForm=Fin": {"pos": "V"},
<del> "V__Mood=Imp|Number=Plur|Person=1|Tense=Pres|VerbForm=Fin": {"pos": "V"},
<del> "V__Mood=Imp|Number=Plur|Person=2|Tense=Pres|VerbForm=Fin": {"pos": "V"},
<del> "V__Mood=Imp|Number=Sing|Person=2|Tense=Pres|VerbForm=Fin": {"pos": "V"},
<del> "V__Mood=Imp|Number=Sing|Person=3|Tense=Pres|VerbForm=Fin": {"pos": "V"},
<del> "V__Mood=Ind|Number=Plur|Person=1|Tense=Fut|VerbForm=Fin": {"pos": "V"},
<del> "V__Mood=Ind|Number=Plur|Person=1|Tense=Imp|VerbForm=Fin": {"pos": "V"},
<del> "V__Mood=Ind|Number=Plur|Person=1|Tense=Past|VerbForm=Fin": {"pos": "V"},
<del> "V__Mood=Ind|Number=Plur|Person=1|Tense=Pres|VerbForm=Fin": {"pos": "V"},
<del> "V__Mood=Ind|Number=Plur|Person=2|Tense=Fut|VerbForm=Fin": {"pos": "V"},
<del> "V__Mood=Ind|Number=Plur|Person=2|Tense=Pres|VerbForm=Fin": {"pos": "V"},
<del> "V__Mood=Ind|Number=Plur|Person=3|Tense=Fut|VerbForm=Fin": {"pos": "V"},
<del> "V__Mood=Ind|Number=Plur|Person=3|Tense=Imp|VerbForm=Fin": {"pos": "V"},
<del> "V__Mood=Ind|Number=Plur|Person=3|Tense=Past|VerbForm=Fin": {"pos": "V"},
<del> "V__Mood=Ind|Number=Plur|Person=3|Tense=Pres|VerbForm=Fin": {"pos": "V"},
<del> "V__Mood=Ind|Number=Sing|Person=1|Tense=Fut|VerbForm=Fin": {"pos": "V"},
<del> "V__Mood=Ind|Number=Sing|Person=1|Tense=Imp|VerbForm=Fin": {"pos": "V"},
<del> "V__Mood=Ind|Number=Sing|Person=1|Tense=Past|VerbForm=Fin": {"pos": "V"},
<del> "V__Mood=Ind|Number=Sing|Person=1|Tense=Pres|VerbForm=Fin": {"pos": "V"},
<del> "V__Mood=Ind|Number=Sing|Person=2|Tense=Fut|VerbForm=Fin": {"pos": "V"},
<del> "V__Mood=Ind|Number=Sing|Person=2|Tense=Pres|VerbForm=Fin": {"pos": "V"},
<del> "V__Mood=Ind|Number=Sing|Person=3|Tense=Fut|VerbForm=Fin": {"pos": "V"},
<del> "V__Mood=Ind|Number=Sing|Person=3|Tense=Imp|VerbForm=Fin": {"pos": "V"},
<del> "V__Mood=Ind|Number=Sing|Person=3|Tense=Past|VerbForm=Fin": {"pos": "V"},
<del> "V__Mood=Ind|Number=Sing|Person=3|Tense=Pres|VerbForm=Fin": {"pos": "V"},
<del> "V__Mood=Ind|Person=3|Tense=Pres|VerbForm=Fin": {"pos": "V"},
<del> "V__Mood=Ind|Tense=Pres|VerbForm=Fin": {"pos": "V"},
<del> "V__Mood=Sub|Number=Plur|Person=1|Tense=Imp|VerbForm=Fin": {"pos": "V"},
<del> "V__Mood=Sub|Number=Plur|Person=1|Tense=Pres|VerbForm=Fin": {"pos": "V"},
<del> "V__Mood=Sub|Number=Plur|Person=2|Tense=Imp|VerbForm=Fin": {"pos": "V"},
<del> "V__Mood=Sub|Number=Plur|Person=2|Tense=Pres|VerbForm=Fin": {"pos": "V"},
<del> "V__Mood=Sub|Number=Plur|Person=3|Tense=Imp|VerbForm=Fin": {"pos": "V"},
<del> "V__Mood=Sub|Number=Plur|Person=3|Tense=Pres|VerbForm=Fin": {"pos": "V"},
<del> "V__Mood=Sub|Number=Sing|Person=1|Tense=Imp|VerbForm=Fin": {"pos": "V"},
<del> "V__Mood=Sub|Number=Sing|Person=1|Tense=Pres|VerbForm=Fin": {"pos": "V"},
<del> "V__Mood=Sub|Number=Sing|Person=2|Tense=Pres|VerbForm=Fin": {"pos": "V"},
<del> "V__Mood=Sub|Number=Sing|Person=3|Tense=Imp|VerbForm=Fin": {"pos": "V"},
<del> "V__Mood=Sub|Number=Sing|Person=3|Tense=Pres|VerbForm=Fin": {"pos": "V"},
<del> "V__Mood=Sub|Number=Sing|Person=3|VerbForm=Fin": {"pos": "V"},
<del> "V__Number=Plur|Tense=Pres|VerbForm=Part": {"pos": "V"},
<del> "V__Number=Sing|Tense=Pres|VerbForm=Part": {"pos": "V"},
<del> "V__Tense=Past|VerbForm=Part": {"pos": "V"},
<del> "V__VerbForm=Ger": {"pos": "V"},
<del> "V__VerbForm=Inf": {"pos": "V"},
<add> "S__Gender=Fem": {"pos": "NOUN"},
<add> "S__Gender=Fem|Number=Plur": {"pos": "NOUN"},
<add> "S__Gender=Fem|Number=Sing": {"pos": "NOUN"},
<add> "S__Gender=Masc": {"pos": "NOUN"},
<add> "S__Gender=Masc|Number=Plur": {"pos": "NOUN"},
<add> "S__Gender=Masc|Number=Sing": {"pos": "NOUN"},
<add> "S__Gender=Masc|Number=Sing|Tense=Past|VerbForm=Part": {"pos": "NOUN"},
<add> "S__Number=Plur": {"pos": "NOUN"},
<add> "S__Number=Sing": {"pos": "NOUN"},
<add> "S___": {"pos": "NOUN"},
<add> "Sw___": {"pos": "X"},
<add> "T__Gender=Fem|Number=Plur|PronType=Tot": {"pos": "DET"},
<add> "T__Gender=Fem|Number=Sing": {"pos": "DET"},
<add> "T__Gender=Fem|Number=Sing|PronType=Tot": {"pos": "DET"},
<add> "T__Gender=Masc|Number=Plur|PronType=Tot": {"pos": "DET"},
<add> "T__Gender=Masc|Number=Sing|PronType=Tot": {"pos": "DET"},
<add> "T__Number=Plur|PronType=Tot": {"pos": "DET"},
<add> "T__PronType=Tot": {"pos": "DET"},
<add> "VA__Gender=Fem|Number=Plur|Tense=Past|VerbForm=Part": {"pos": "AUX"},
<add> "VA__Gender=Fem|Number=Sing|Tense=Past|VerbForm=Part": {"pos": "AUX"},
<add> "VA__Gender=Masc|Number=Plur|Tense=Past|VerbForm=Part": {"pos": "AUX"},
<add> "VA__Gender=Masc|Number=Sing|Tense=Past|VerbForm=Part": {"pos": "AUX"},
<add> "VA__Mood=Cnd|Number=Plur|Person=1|Tense=Pres|VerbForm=Fin": {"pos": "AUX"},
<add> "VA__Mood=Cnd|Number=Plur|Person=3|Tense=Pres|VerbForm=Fin": {"pos": "AUX"},
<add> "VA__Mood=Cnd|Number=Sing|Person=1|Tense=Pres|VerbForm=Fin": {"pos": "AUX"},
<add> "VA__Mood=Cnd|Number=Sing|Person=3|Tense=Pres|VerbForm=Fin": {"pos": "AUX"},
<add> "VA__Mood=Ind|Number=Plur|Person=1|Tense=Fut|VerbForm=Fin": {"pos": "AUX"},
<add> "VA__Mood=Ind|Number=Plur|Person=1|Tense=Imp|VerbForm=Fin": {"pos": "AUX"},
<add> "VA__Mood=Ind|Number=Plur|Person=1|Tense=Pres|VerbForm=Fin": {"pos": "AUX"},
<add> "VA__Mood=Ind|Number=Plur|Person=2|Tense=Fut|VerbForm=Fin": {"pos": "AUX"},
<add> "VA__Mood=Ind|Number=Plur|Person=2|Tense=Imp|VerbForm=Fin": {"pos": "AUX"},
<add> "VA__Mood=Ind|Number=Plur|Person=2|Tense=Pres|VerbForm=Fin": {"pos": "AUX"},
<add> "VA__Mood=Ind|Number=Plur|Person=3|Tense=Fut|VerbForm=Fin": {"pos": "AUX"},
<add> "VA__Mood=Ind|Number=Plur|Person=3|Tense=Imp|VerbForm=Fin": {"pos": "AUX"},
<add> "VA__Mood=Ind|Number=Plur|Person=3|Tense=Past|VerbForm=Fin": {"pos": "AUX"},
<add> "VA__Mood=Ind|Number=Plur|Person=3|Tense=Pres|VerbForm=Fin": {"pos": "AUX"},
<add> "VA__Mood=Ind|Number=Sing|Person=1|Tense=Fut|VerbForm=Fin": {"pos": "AUX"},
<add> "VA__Mood=Ind|Number=Sing|Person=1|Tense=Imp|VerbForm=Fin": {"pos": "AUX"},
<add> "VA__Mood=Ind|Number=Sing|Person=1|Tense=Past|VerbForm=Fin": {"pos": "AUX"},
<add> "VA__Mood=Ind|Number=Sing|Person=1|Tense=Pres|VerbForm=Fin": {"pos": "AUX"},
<add> "VA__Mood=Ind|Number=Sing|Person=2|Tense=Fut|VerbForm=Fin": {"pos": "AUX"},
<add> "VA__Mood=Ind|Number=Sing|Person=2|Tense=Pres|VerbForm=Fin": {"pos": "AUX"},
<add> "VA__Mood=Ind|Number=Sing|Person=3|Tense=Fut|VerbForm=Fin": {"pos": "AUX"},
<add> "VA__Mood=Ind|Number=Sing|Person=3|Tense=Imp|VerbForm=Fin": {"pos": "AUX"},
<add> "VA__Mood=Ind|Number=Sing|Person=3|Tense=Past|VerbForm=Fin": {"pos": "AUX"},
<add> "VA__Mood=Ind|Number=Sing|Person=3|Tense=Pres|VerbForm=Fin": {"pos": "AUX"},
<add> "VA__Mood=Sub|Number=Plur|Person=2|Tense=Pres|VerbForm=Fin": {"pos": "AUX"},
<add> "VA__Mood=Sub|Number=Plur|Person=3|Tense=Imp|VerbForm=Fin": {"pos": "AUX"},
<add> "VA__Mood=Sub|Number=Plur|Person=3|Tense=Pres|VerbForm=Fin": {"pos": "AUX"},
<add> "VA__Mood=Sub|Number=Sing|Person=1|Tense=Imp|VerbForm=Fin": {"pos": "AUX"},
<add> "VA__Mood=Sub|Number=Sing|Person=3|Tense=Imp|VerbForm=Fin": {"pos": "AUX"},
<add> "VA__Mood=Sub|Number=Sing|Person=3|Tense=Pres|VerbForm=Fin": {"pos": "AUX"},
<add> "VA__VerbForm=Ger": {"pos": "AUX"},
<add> "VA__VerbForm=Inf": {"pos": "AUX"},
<add> "VM__Gender=Fem|Number=Sing|Tense=Past|VerbForm=Part": {"pos": "AUX"},
<add> "VM__Gender=Masc|Number=Sing|Tense=Past|VerbForm=Part": {"pos": "AUX"},
<add> "VM__Mood=Cnd|Number=Plur|Person=1|Tense=Pres|VerbForm=Fin": {"pos": "AUX"},
<add> "VM__Mood=Cnd|Number=Plur|Person=2|Tense=Pres|VerbForm=Fin": {"pos": "AUX"},
<add> "VM__Mood=Cnd|Number=Plur|Person=3|Tense=Pres|VerbForm=Fin": {"pos": "AUX"},
<add> "VM__Mood=Cnd|Number=Sing|Person=1|Tense=Pres|VerbForm=Fin": {"pos": "AUX"},
<add> "VM__Mood=Cnd|Number=Sing|Person=2|Tense=Pres|VerbForm=Fin": {"pos": "AUX"},
<add> "VM__Mood=Cnd|Number=Sing|Person=3|Tense=Pres|VerbForm=Fin": {"pos": "AUX"},
<add> "VM__Mood=Imp|Number=Plur|Person=2|Tense=Pres|VerbForm=Fin": {"pos": "AUX"},
<add> "VM__Mood=Imp|Number=Sing|Person=2|Tense=Pres|VerbForm=Fin": {"pos": "AUX"},
<add> "VM__Mood=Ind|Number=Plur|Person=1|Tense=Fut|VerbForm=Fin": {"pos": "AUX"},
<add> "VM__Mood=Ind|Number=Plur|Person=1|Tense=Imp|VerbForm=Fin": {"pos": "AUX"},
<add> "VM__Mood=Ind|Number=Plur|Person=1|Tense=Pres|VerbForm=Fin": {"pos": "AUX"},
<add> "VM__Mood=Ind|Number=Plur|Person=2|Tense=Fut|VerbForm=Fin": {"pos": "AUX"},
<add> "VM__Mood=Ind|Number=Plur|Person=2|Tense=Pres|VerbForm=Fin": {"pos": "AUX"},
<add> "VM__Mood=Ind|Number=Plur|Person=3|Tense=Fut|VerbForm=Fin": {"pos": "AUX"},
<add> "VM__Mood=Ind|Number=Plur|Person=3|Tense=Imp|VerbForm=Fin": {"pos": "AUX"},
<add> "VM__Mood=Ind|Number=Plur|Person=3|Tense=Past|VerbForm=Fin": {"pos": "AUX"},
<add> "VM__Mood=Ind|Number=Plur|Person=3|Tense=Pres|VerbForm=Fin": {"pos": "AUX"},
<add> "VM__Mood=Ind|Number=Sing|Person=1|Tense=Imp|VerbForm=Fin": {"pos": "AUX"},
<add> "VM__Mood=Ind|Number=Sing|Person=1|Tense=Pres|VerbForm=Fin": {"pos": "AUX"},
<add> "VM__Mood=Ind|Number=Sing|Person=2|Tense=Fut|VerbForm=Fin": {"pos": "AUX"},
<add> "VM__Mood=Ind|Number=Sing|Person=2|Tense=Imp|VerbForm=Fin": {"pos": "AUX"},
<add> "VM__Mood=Ind|Number=Sing|Person=2|Tense=Pres|VerbForm=Fin": {"pos": "AUX"},
<add> "VM__Mood=Ind|Number=Sing|Person=3|Tense=Fut|VerbForm=Fin": {"pos": "AUX"},
<add> "VM__Mood=Ind|Number=Sing|Person=3|Tense=Imp|VerbForm=Fin": {"pos": "AUX"},
<add> "VM__Mood=Ind|Number=Sing|Person=3|Tense=Past|VerbForm=Fin": {"pos": "AUX"},
<add> "VM__Mood=Ind|Number=Sing|Person=3|Tense=Pres|VerbForm=Fin": {"pos": "AUX"},
<add> "VM__Mood=Sub|Number=Plur|Person=1|Tense=Imp|VerbForm=Fin": {"pos": "AUX"},
<add> "VM__Mood=Sub|Number=Plur|Person=1|Tense=Pres|VerbForm=Fin": {"pos": "AUX"},
<add> "VM__Mood=Sub|Number=Plur|Person=3|Tense=Imp|VerbForm=Fin": {"pos": "AUX"},
<add> "VM__Mood=Sub|Number=Plur|Person=3|Tense=Pres|VerbForm=Fin": {"pos": "AUX"},
<add> "VM__Mood=Sub|Number=Sing|Person=3|Tense=Imp|VerbForm=Fin": {"pos": "AUX"},
<add> "VM__Mood=Sub|Number=Sing|Person=3|Tense=Pres|VerbForm=Fin": {"pos": "AUX"},
<add> "VM__VerbForm=Ger": {"pos": "AUX"},
<add> "VM__VerbForm=Inf": {"pos": "AUX"},
<add> "V__Gender=Fem|Number=Plur|Tense=Past|VerbForm=Part": {"pos": "VERB"},
<add> "V__Gender=Fem|Number=Sing|Tense=Past|VerbForm=Part": {"pos": "VERB"},
<add> "V__Gender=Masc|Number=Plur|Tense=Past|VerbForm=Fin": {"pos": "VERB"},
<add> "V__Gender=Masc|Number=Plur|Tense=Past|VerbForm=Part": {"pos": "VERB"},
<add> "V__Gender=Masc|Number=Sing|Tense=Past|VerbForm=Part": {"pos": "VERB"},
<add> "V__Mood=Cnd|Number=Plur|Person=1|Tense=Pres|VerbForm=Fin": {"pos": "VERB"},
<add> "V__Mood=Cnd|Number=Plur|Person=2|Tense=Pres|VerbForm=Fin": {"pos": "VERB"},
<add> "V__Mood=Cnd|Number=Plur|Person=3|Tense=Pres|VerbForm=Fin": {"pos": "VERB"},
<add> "V__Mood=Cnd|Number=Sing|Person=1|Tense=Pres|VerbForm=Fin": {"pos": "VERB"},
<add> "V__Mood=Cnd|Number=Sing|Person=2|Tense=Pres|VerbForm=Fin": {"pos": "VERB"},
<add> "V__Mood=Cnd|Number=Sing|Person=3|Tense=Pres|VerbForm=Fin": {"pos": "VERB"},
<add> "V__Mood=Imp|Number=Plur|Person=1|Tense=Pres|VerbForm=Fin": {"pos": "VERB"},
<add> "V__Mood=Imp|Number=Plur|Person=2|Tense=Pres|VerbForm=Fin": {"pos": "VERB"},
<add> "V__Mood=Imp|Number=Sing|Person=2|Tense=Pres|VerbForm=Fin": {"pos": "VERB"},
<add> "V__Mood=Imp|Number=Sing|Person=3|Tense=Pres|VerbForm=Fin": {"pos": "VERB"},
<add> "V__Mood=Ind|Number=Plur|Person=1|Tense=Fut|VerbForm=Fin": {"pos": "VERB"},
<add> "V__Mood=Ind|Number=Plur|Person=1|Tense=Imp|VerbForm=Fin": {"pos": "VERB"},
<add> "V__Mood=Ind|Number=Plur|Person=1|Tense=Past|VerbForm=Fin": {"pos": "VERB"},
<add> "V__Mood=Ind|Number=Plur|Person=1|Tense=Pres|VerbForm=Fin": {"pos": "VERB"},
<add> "V__Mood=Ind|Number=Plur|Person=2|Tense=Fut|VerbForm=Fin": {"pos": "VERB"},
<add> "V__Mood=Ind|Number=Plur|Person=2|Tense=Pres|VerbForm=Fin": {"pos": "VERB"},
<add> "V__Mood=Ind|Number=Plur|Person=3|Tense=Fut|VerbForm=Fin": {"pos": "VERB"},
<add> "V__Mood=Ind|Number=Plur|Person=3|Tense=Imp|VerbForm=Fin": {"pos": "VERB"},
<add> "V__Mood=Ind|Number=Plur|Person=3|Tense=Past|VerbForm=Fin": {"pos": "VERB"},
<add> "V__Mood=Ind|Number=Plur|Person=3|Tense=Pres|VerbForm=Fin": {"pos": "VERB"},
<add> "V__Mood=Ind|Number=Sing|Person=1|Tense=Fut|VerbForm=Fin": {"pos": "VERB"},
<add> "V__Mood=Ind|Number=Sing|Person=1|Tense=Imp|VerbForm=Fin": {"pos": "VERB"},
<add> "V__Mood=Ind|Number=Sing|Person=1|Tense=Past|VerbForm=Fin": {"pos": "VERB"},
<add> "V__Mood=Ind|Number=Sing|Person=1|Tense=Pres|VerbForm=Fin": {"pos": "VERB"},
<add> "V__Mood=Ind|Number=Sing|Person=2|Tense=Fut|VerbForm=Fin": {"pos": "VERB"},
<add> "V__Mood=Ind|Number=Sing|Person=2|Tense=Pres|VerbForm=Fin": {"pos": "VERB"},
<add> "V__Mood=Ind|Number=Sing|Person=3|Tense=Fut|VerbForm=Fin": {"pos": "VERB"},
<add> "V__Mood=Ind|Number=Sing|Person=3|Tense=Imp|VerbForm=Fin": {"pos": "VERB"},
<add> "V__Mood=Ind|Number=Sing|Person=3|Tense=Past|VerbForm=Fin": {"pos": "VERB"},
<add> "V__Mood=Ind|Number=Sing|Person=3|Tense=Pres|VerbForm=Fin": {"pos": "VERB"},
<add> "V__Mood=Ind|Person=3|Tense=Pres|VerbForm=Fin": {"pos": "VERB"},
<add> "V__Mood=Ind|Tense=Pres|VerbForm=Fin": {"pos": "VERB"},
<add> "V__Mood=Sub|Number=Plur|Person=1|Tense=Imp|VerbForm=Fin": {"pos": "VERB"},
<add> "V__Mood=Sub|Number=Plur|Person=1|Tense=Pres|VerbForm=Fin": {"pos": "VERB"},
<add> "V__Mood=Sub|Number=Plur|Person=2|Tense=Imp|VerbForm=Fin": {"pos": "VERB"},
<add> "V__Mood=Sub|Number=Plur|Person=2|Tense=Pres|VerbForm=Fin": {"pos": "VERB"},
<add> "V__Mood=Sub|Number=Plur|Person=3|Tense=Imp|VerbForm=Fin": {"pos": "VERB"},
<add> "V__Mood=Sub|Number=Plur|Person=3|Tense=Pres|VerbForm=Fin": {"pos": "VERB"},
<add> "V__Mood=Sub|Number=Sing|Person=1|Tense=Imp|VerbForm=Fin": {"pos": "VERB"},
<add> "V__Mood=Sub|Number=Sing|Person=1|Tense=Pres|VerbForm=Fin": {"pos": "VERB"},
<add> "V__Mood=Sub|Number=Sing|Person=2|Tense=Pres|VerbForm=Fin": {"pos": "VERB"},
<add> "V__Mood=Sub|Number=Sing|Person=3|Tense=Imp|VerbForm=Fin": {"pos": "VERB"},
<add> "V__Mood=Sub|Number=Sing|Person=3|Tense=Pres|VerbForm=Fin": {"pos": "VERB"},
<add> "V__Mood=Sub|Number=Sing|Person=3|VerbForm=Fin": {"pos": "VERB"},
<add> "V__Number=Plur|Tense=Pres|VerbForm=Part": {"pos": "VERB"},
<add> "V__Number=Sing|Tense=Pres|VerbForm=Part": {"pos": "VERB"},
<add> "V__Tense=Past|VerbForm=Part": {"pos": "VERB"},
<add> "V__VerbForm=Ger": {"pos": "VERB"},
<add> "V__VerbForm=Inf": {"pos": "VERB"},
<ide> "X___": {"pos": "X"},
<ide> "_SP": {"pos": "_SP"}
<ide> } | 1 |
Javascript | Javascript | add missing param to fetchfrompage() | d2f08dd40d87376d7d2200ab5463cb79e67f343d | <ide><path>packages/react-devtools-extensions/src/main.js
<ide> function createPanelIfReactLoaded() {
<ide> }
<ide>
<ide> // Edge case where getContent() returned null; fall back to fetch.
<del> fetchFromPage(url, resolve);
<add> fetchFromPage(url, resolve, reject);
<ide> }
<ide> });
<ide>
<ide> function createPanelIfReactLoaded() {
<ide> }
<ide>
<ide> // No matching URL found; fall back to fetch.
<del> fetchFromPage(url, resolve);
<add> fetchFromPage(url, resolve, reject);
<ide> });
<ide> };
<ide> | 1 |
Javascript | Javascript | remove function redeclaration | 8b3772d47fc94fe3c3175602bba5eef6605fad86 | <ide><path>lib/EntryOptionPlugin.js
<ide> const SingleEntryPlugin = require("./SingleEntryPlugin");
<ide> const MultiEntryPlugin = require("./MultiEntryPlugin");
<ide> const DynamicEntryPlugin = require("./DynamicEntryPlugin");
<ide>
<add>function itemToPlugin(context, item, name) {
<add> if(Array.isArray(item)) {
<add> return new MultiEntryPlugin(context, item, name);
<add> } else {
<add> return new SingleEntryPlugin(context, item, name);
<add> }
<add>}
<add>
<ide> module.exports = class EntryOptionPlugin {
<ide> apply(compiler) {
<ide> compiler.plugin("entry-option", (context, entry) => {
<del> function itemToPlugin(item, name) {
<del> if(Array.isArray(item)) {
<del> return new MultiEntryPlugin(context, item, name);
<del> } else {
<del> return new SingleEntryPlugin(context, item, name);
<del> }
<del> }
<ide> if(typeof entry === "string" || Array.isArray(entry)) {
<del> compiler.apply(itemToPlugin(entry, "main"));
<add> compiler.apply(itemToPlugin(context, entry, "main"));
<ide> } else if(typeof entry === "object") {
<del> Object.keys(entry).forEach(name => compiler.apply(itemToPlugin(entry[name], name)));
<add> Object.keys(entry).forEach(name => compiler.apply(itemToPlugin(context, entry[name], name)));
<ide> } else if(typeof entry === "function") {
<ide> compiler.apply(new DynamicEntryPlugin(context, entry));
<ide> } | 1 |
Javascript | Javascript | improve ability to detect the format of a stl file | bb64625533a4d74fd0e4fc8bb8ed36abf2a8a2fe | <ide><path>examples/js/loaders/STLLoader.js
<ide> THREE.STLLoader.prototype = {
<ide> face_size = (32 / 8 * 3) + ((32 / 8 * 3) * 3) + (16 / 8);
<ide> n_faces = reader.getUint32(80,true);
<ide> expect = 80 + (32 / 8) + (n_faces * face_size);
<del> return expect === reader.byteLength;
<add>
<add> if ( expect === reader.byteLength ) {
<add>
<add> return true;
<add>
<add> }
<add>
<add> var fileLength = reader.byteLength;
<add>
<add> for ( var index = 0; index < fileLength; index ++ ) {
<add>
<add> if ( reader.getUint8(index, false) > 127 ) {
<add>
<add> return true;
<add>
<add> }
<add>
<add> }
<add>
<add> return false;
<ide>
<ide> };
<ide> | 1 |
Python | Python | use sum instead of mean in cosine_proximity | 2dfba02e0a507eddaf3db3d7f3660d75ce740639 | <ide><path>keras/losses.py
<ide> def poisson(y_true, y_pred):
<ide> def cosine_proximity(y_true, y_pred):
<ide> y_true = K.l2_normalize(y_true, axis=-1)
<ide> y_pred = K.l2_normalize(y_pred, axis=-1)
<del> return -K.mean(y_true * y_pred, axis=-1)
<add> return -K.sum(y_true * y_pred, axis=-1)
<ide>
<ide>
<ide> # Aliases. | 1 |
Python | Python | fix function that defines masks in xlm | c5a94a6100afdd550fb3ea445d8bddc6b9769fcc | <ide><path>transformers/modeling_xlm.py
<ide> def get_masks(slen, lengths, causal, padding_mask=None):
<ide> """
<ide> Generate hidden states mask, and optionally an attention mask.
<ide> """
<del> bs = lengths.size(0)
<add> alen = torch.arange(slen, dtype=torch.long, device=lengths.device)
<ide> if padding_mask is not None:
<ide> mask = padding_mask
<ide> else:
<ide> assert lengths.max().item() <= slen
<del> alen = torch.arange(slen, dtype=torch.long, device=lengths.device)
<ide> mask = alen < lengths[:, None]
<ide>
<ide> # attention mask is the same as mask, or triangular inferior attention (causal)
<ide> if causal:
<add> bs = lengths.size(0)
<ide> attn_mask = alen[None, None, :].repeat(bs, slen, 1) <= alen[None, :, None]
<ide> else:
<ide> attn_mask = mask | 1 |
Ruby | Ruby | use dup to preserve previous behavior | fb3ea8b8cb324d174e801d27dc15315b9358486f | <ide><path>activesupport/lib/active_support/hash_with_indifferent_access.rb
<ide> def extractable_options?
<ide> end
<ide>
<ide> def with_indifferent_access
<del> self
<add> dup
<ide> end
<ide>
<ide> def initialize(constructor = {})
<ide><path>activesupport/test/core_ext/hash_ext_test.rb
<ide> def test_should_nil_if_no_default_value_is_supplied
<ide> assert_nil hash_wia.default
<ide> end
<ide>
<del> def test_should_return_self_for_with_indifferent_access
<add> def test_should_return_dup_for_with_indifferent_access
<ide> hash_wia = HashWithIndifferentAccess.new
<ide> assert_equal hash_wia, hash_wia.with_indifferent_access
<ide> end | 2 |
Java | Java | add logutils and httplogging | 4d6f2df3cbdf956ec22e5dbefe18e79a290b4ea8 | <add><path>spring-core/src/main/java/org/springframework/util/log/CompositeLog.java
<del><path>spring-web/src/main/java/org/springframework/http/HttpLog.java
<ide> * See the License for the specific language governing permissions and
<ide> * limitations under the License.
<ide> */
<del>package org.springframework.http;
<add>package org.springframework.util.log;
<ide>
<del>import java.util.ArrayList;
<del>import java.util.Collections;
<ide> import java.util.List;
<ide> import java.util.function.Predicate;
<ide>
<ide> import org.apache.commons.logging.Log;
<del>import org.apache.commons.logging.LogFactory;
<ide> import org.apache.commons.logging.impl.NoOpLog;
<ide>
<del>import org.springframework.util.ObjectUtils;
<del>
<ide> /**
<del> * Composite {@link Log} configured with a primary logger and a list of secondary
<del> * ones to fall back on if the main one is not enabled.
<del> *
<del> * <p>This class also declares {@link #webLogger} for use as fallback when
<del> * logging in the "org.springframework.http" package.
<add> * Implementation of {@link Log} that wraps a list of loggers and delegates to
<add> * the first one for which logging is enabled at the given level.
<ide> *
<ide> * @author Rossen Stoyanchev
<ide> * @since 5.1
<add> * @see LogUtils#getCompositeLog
<ide> */
<del>public final class HttpLog implements Log {
<del>
<del> /**
<del> * Logger with category "org.springframework.web.HTTP" to use as fallback
<del> * if "org.springframework.web" is on.
<del> */
<del> public static final Log webLogger = LogFactory.getLog("org.springframework.web.HTTP");
<add>class CompositeLog implements Log {
<ide>
<ide> private static final Log noOpLog = new NoOpLog();
<ide>
<ide> public final class HttpLog implements Log {
<ide> private final Log traceLogger;
<ide>
<ide>
<del> private HttpLog(List<Log> loggers) {
<add> /**
<add> * Constructor with list of loggers. For optimal performance, the constructor
<add> * checks and remembers which logger is on for each log category.
<add> * @param loggers the loggers to use
<add> */
<add> public CompositeLog(List<Log> loggers) {
<ide> this.fatalLogger = initLogger(loggers, Log::isFatalEnabled);
<ide> this.errorLogger = initLogger(loggers, Log::isErrorEnabled);
<ide> this.warnLogger = initLogger(loggers, Log::isWarnEnabled);
<ide> public void trace(Object message) {
<ide> public void trace(Object message, Throwable ex) {
<ide> this.traceLogger.trace(message, ex);
<ide> }
<del>
<del>
<del> /**
<del> * Create a composite logger that uses the given primary logger, if enabled,
<del> * or falls back on {@link #webLogger}.
<del> * @param primaryLogger the primary logger
<del> * @return a composite logger
<del> */
<del> public static Log create(Log primaryLogger) {
<del> return createWith(primaryLogger, webLogger);
<del> }
<del>
<del> /**
<del> * Create a composite logger that uses the given primary logger, if enabled,
<del> * or falls back on one of the given secondary loggers..
<del> * @param primaryLogger the primary logger
<del> * @param secondaryLoggers fallback loggers
<del> * @return a composite logger
<del> */
<del> public static Log createWith(Log primaryLogger, Log... secondaryLoggers) {
<del> if (ObjectUtils.isEmpty(secondaryLoggers)) {
<del> return primaryLogger;
<del> }
<del> List<Log> loggers = new ArrayList<>(1 + secondaryLoggers.length);
<del> loggers.add(primaryLogger);
<del> Collections.addAll(loggers, secondaryLoggers);
<del> return new HttpLog(loggers);
<del> }
<del>
<ide> }
<ide><path>spring-core/src/main/java/org/springframework/util/log/LogUtils.java
<add>/*
<add> * Copyright 2002-2018 the original author or authors.
<add> *
<add> * Licensed under the Apache License, Version 2.0 (the "License");
<add> * you may not use this file except in compliance with the License.
<add> * You may obtain a copy of the License at
<add> *
<add> * http://www.apache.org/licenses/LICENSE-2.0
<add> *
<add> * Unless required by applicable law or agreed to in writing, software
<add> * distributed under the License is distributed on an "AS IS" BASIS,
<add> * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
<add> * See the License for the specific language governing permissions and
<add> * limitations under the License.
<add> */
<add>package org.springframework.util.log;
<add>
<add>import java.util.ArrayList;
<add>import java.util.Collections;
<add>import java.util.List;
<add>
<add>import org.apache.commons.logging.Log;
<add>import org.apache.commons.logging.LogFactory;
<add>
<add>/**
<add> * Utilities to assist with logging. Mainly for internal use within the framework
<add> * with Appache Commons Logging.
<add> *
<add> * @author Rossen Stoyanchev
<add> * @since 5.1
<add> */
<add>public abstract class LogUtils {
<add>
<add> /**
<add> * Create a composite logger that delegates to a primary or falls back on a
<add> * secondary logger if logging for the primary logger is not enabled.
<add> * <p>This may be used for fallback logging from lower level packages that
<add> * logically should log together with some higher level package but the two
<add> * don't happen to share a suitable parent package (e.g. logging for the web
<add> * and lower level http and codec packages). For such cases the primary,
<add> * class-based logger can be wrapped with a shared fallback logger.
<add> * @param primaryLogger primary logger to try first
<add> * @param secondaryLogger secondary logger
<add> * @param tertiaryLoggers optionally, more fallback loggers
<add> * @return the resulting logger to use
<add> */
<add> public static Log getCompositeLog(Log primaryLogger, Log secondaryLogger, Log... tertiaryLoggers) {
<add> List<Log> loggers = new ArrayList<>(2 + tertiaryLoggers.length);
<add> loggers.add(primaryLogger);
<add> loggers.add(secondaryLogger);
<add> Collections.addAll(loggers, tertiaryLoggers);
<add> return new CompositeLog(loggers);
<add> }
<add>
<add> /**
<add> * Create a "hidden" logger whose name is intentionally prefixed with "_"
<add> * because its output is either too verbose or otherwise deemed as optional
<add> * or unnecessary to see at any log level by default under the normal package
<add> * based log hierarchy.
<add> * @param clazz the class for which to create a logger
<add> * @return the created logger
<add> */
<add> public static Log getHiddenLog(Class<?> clazz) {
<add> return LogFactory.getLog("_" + clazz.getName());
<add> }
<add>
<add>}
<ide><path>spring-core/src/main/java/org/springframework/util/log/package-info.java
<add>/**
<add> * Useful helper classes for logging.
<add> */
<add>@NonNullApi
<add>@NonNullFields
<add>package org.springframework.util.log;
<add>
<add>import org.springframework.lang.NonNullApi;
<add>import org.springframework.lang.NonNullFields;
<ide><path>spring-web/src/main/java/org/springframework/http/HttpLogging.java
<add>/*
<add> * Copyright 2002-2018 the original author or authors.
<add> *
<add> * Licensed under the Apache License, Version 2.0 (the "License");
<add> * you may not use this file except in compliance with the License.
<add> * You may obtain a copy of the License at
<add> *
<add> * http://www.apache.org/licenses/LICENSE-2.0
<add> *
<add> * Unless required by applicable law or agreed to in writing, software
<add> * distributed under the License is distributed on an "AS IS" BASIS,
<add> * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
<add> * See the License for the specific language governing permissions and
<add> * limitations under the License.
<add> */
<add>package org.springframework.http;
<add>
<add>import org.apache.commons.logging.Log;
<add>import org.apache.commons.logging.LogFactory;
<add>
<add>import org.springframework.util.log.LogUtils;
<add>
<add>/**
<add> * Holds the shared logger named "org.springframework.web.HttpLogging" for HTTP
<add> * related logging when "org.springframework.http" is not enabled but
<add> * "org.springframework.web" is.
<add> *
<add> * <p>That means "org.springframework.web" enables all web logging including
<add> * from lower level packages such as "org.springframework.http" and modules
<add> * such as codecs from {@literal "spring-core"} when those are wrapped with
<add> * {@link org.springframework.http.codec.EncoderHttpMessageWriter EncoderHttpMessageWriter} or
<add> * {@link org.springframework.http.codec.DecoderHttpMessageReader DecoderHttpMessageReader}.
<add> *
<add> * <p>To see logging from the primary class loggers simply enable logging for
<add> * "org.springframework.http" and "org.springframework.codec".
<add> *
<add> * @author Rossen Stoyanchev
<add> * @since 5.1
<add> */
<add>public abstract class HttpLogging {
<add>
<add> private static final Log fallbackLogger =
<add> LogFactory.getLog("org.springframework.web." + HttpLogging.class.getSimpleName());
<add>
<add>
<add> /**
<add> * Create a primary logger for the given class and wrap it with a composite
<add> * that delegates to it or to the fallback logger
<add> * "org.springframework.web.HttpLogging", if the primary is not enabled.
<add> * @param primaryLoggerClass the class for the name of the primary logger
<add> * @return the resulting composite logger
<add> */
<add> public static Log forLogName(Class<?> primaryLoggerClass) {
<add> Log primaryLogger = LogFactory.getLog(primaryLoggerClass);
<add> return forLog(primaryLogger);
<add> }
<add>
<add> /**
<add> * Wrap the given primary logger with a composite logger that delegates to
<add> * it or to the fallback logger "org.springframework.web.HttpLogging", if
<add> * the primary is not enabled.
<add> * @param primaryLogger the primary logger to use
<add> * @return the resulting composite logger
<add> */
<add> public static Log forLog(Log primaryLogger) {
<add> return LogUtils.getCompositeLog(primaryLogger, fallbackLogger);
<add> }
<add>
<add>}
<ide><path>spring-web/src/main/java/org/springframework/http/client/support/AsyncHttpAccessor.java
<ide> import java.net.URI;
<ide>
<ide> import org.apache.commons.logging.Log;
<del>import org.apache.commons.logging.LogFactory;
<ide>
<add>import org.springframework.http.HttpLogging;
<ide> import org.springframework.http.HttpMethod;
<ide> import org.springframework.lang.Nullable;
<ide> import org.springframework.util.Assert;
<ide> public class AsyncHttpAccessor {
<ide>
<ide> /** Logger available to subclasses. */
<del> protected final Log logger = LogFactory.getLog(getClass());
<add> protected final Log logger = HttpLogging.forLogName(getClass());
<ide>
<ide> @Nullable
<ide> private org.springframework.http.client.AsyncClientHttpRequestFactory asyncRequestFactory;
<ide><path>spring-web/src/main/java/org/springframework/http/client/support/HttpAccessor.java
<ide> import java.net.URI;
<ide>
<ide> import org.apache.commons.logging.Log;
<del>import org.apache.commons.logging.LogFactory;
<ide>
<add>import org.springframework.http.HttpLogging;
<ide> import org.springframework.http.HttpMethod;
<ide> import org.springframework.http.client.ClientHttpRequest;
<ide> import org.springframework.http.client.ClientHttpRequestFactory;
<ide> public abstract class HttpAccessor {
<ide>
<ide> /** Logger available to subclasses. */
<del> protected final Log logger = LogFactory.getLog(getClass());
<add> protected final Log logger = HttpLogging.forLogName(getClass());
<ide>
<ide> private ClientHttpRequestFactory requestFactory = new SimpleClientHttpRequestFactory();
<ide>
<ide><path>spring-web/src/main/java/org/springframework/http/codec/DecoderHttpMessageReader.java
<ide> import org.springframework.core.codec.AbstractDecoder;
<ide> import org.springframework.core.codec.Decoder;
<ide> import org.springframework.core.codec.Hints;
<del>import org.springframework.http.HttpLog;
<add>import org.springframework.http.HttpLogging;
<ide> import org.springframework.http.HttpMessage;
<ide> import org.springframework.http.MediaType;
<ide> import org.springframework.http.ReactiveHttpInputMessage;
<ide> private void initLogger(Decoder<T> decoder) {
<ide> if (decoder instanceof AbstractDecoder &&
<ide> decoder.getClass().getPackage().getName().startsWith("org.springframework.core.codec")) {
<ide>
<del> Log logger = HttpLog.create(((AbstractDecoder) decoder).getLogger());
<add> Log logger = HttpLogging.forLog(((AbstractDecoder) decoder).getLogger());
<ide> ((AbstractDecoder) decoder).setLogger(logger);
<ide> }
<ide> }
<ide><path>spring-web/src/main/java/org/springframework/http/codec/EncoderHttpMessageWriter.java
<ide> import org.springframework.core.codec.Hints;
<ide> import org.springframework.core.io.buffer.DataBuffer;
<ide> import org.springframework.http.HttpHeaders;
<del>import org.springframework.http.HttpLog;
<add>import org.springframework.http.HttpLogging;
<ide> import org.springframework.http.MediaType;
<ide> import org.springframework.http.ReactiveHttpOutputMessage;
<ide> import org.springframework.http.server.reactive.ServerHttpRequest;
<ide> private void initLogger(Encoder<T> encoder) {
<ide> if (encoder instanceof AbstractEncoder &&
<ide> encoder.getClass().getPackage().getName().startsWith("org.springframework.core.codec")) {
<ide>
<del> Log logger = HttpLog.create(((AbstractEncoder) encoder).getLogger());
<add> Log logger = HttpLogging.forLog(((AbstractEncoder) encoder).getLogger());
<ide> ((AbstractEncoder) encoder).setLogger(logger);
<ide> }
<ide> }
<ide><path>spring-web/src/main/java/org/springframework/http/codec/LoggingCodecSupport.java
<ide> package org.springframework.http.codec;
<ide>
<ide> import org.apache.commons.logging.Log;
<del>import org.apache.commons.logging.LogFactory;
<ide>
<del>import org.springframework.http.HttpLog;
<add>import org.springframework.http.HttpLogging;
<ide>
<ide> /**
<ide> * Base class for {@link org.springframework.core.codec.Encoder},
<ide> */
<ide> public class LoggingCodecSupport {
<ide>
<del> protected final Log logger = HttpLog.create(LogFactory.getLog(getClass()));
<add> protected final Log logger = HttpLogging.forLogName(getClass());
<ide>
<ide> /** Whether to log potentially sensitive info (form data at DEBUG and headers at TRACE). */
<ide> private boolean enableLoggingRequestDetails = false;
<ide><path>spring-web/src/main/java/org/springframework/http/codec/ResourceHttpMessageWriter.java
<ide> import java.util.Optional;
<ide>
<ide> import org.apache.commons.logging.Log;
<del>import org.apache.commons.logging.LogFactory;
<ide> import org.reactivestreams.Publisher;
<ide> import reactor.core.publisher.Flux;
<ide> import reactor.core.publisher.Mono;
<ide> import org.springframework.core.io.buffer.DataBufferFactory;
<ide> import org.springframework.core.io.support.ResourceRegion;
<ide> import org.springframework.http.HttpHeaders;
<del>import org.springframework.http.HttpLog;
<add>import org.springframework.http.HttpLogging;
<ide> import org.springframework.http.HttpRange;
<ide> import org.springframework.http.HttpStatus;
<ide> import org.springframework.http.MediaType;
<ide> public class ResourceHttpMessageWriter implements HttpMessageWriter<Resource> {
<ide>
<ide> private static final ResolvableType REGION_TYPE = ResolvableType.forClass(ResourceRegion.class);
<ide>
<del> private static final Log logger = HttpLog.create(LogFactory.getLog(ResourceHttpMessageWriter.class));
<add> private static final Log logger = HttpLogging.forLogName(ResourceHttpMessageWriter.class);
<ide>
<ide>
<ide> private final ResourceEncoder encoder;
<ide><path>spring-web/src/main/java/org/springframework/http/codec/json/Jackson2CodecSupport.java
<ide> import com.fasterxml.jackson.databind.ObjectMapper;
<ide> import com.fasterxml.jackson.databind.type.TypeFactory;
<ide> import org.apache.commons.logging.Log;
<del>import org.apache.commons.logging.LogFactory;
<ide>
<ide> import org.springframework.core.GenericTypeResolver;
<ide> import org.springframework.core.MethodParameter;
<ide> import org.springframework.core.ResolvableType;
<ide> import org.springframework.core.codec.Hints;
<del>import org.springframework.http.HttpLog;
<add>import org.springframework.http.HttpLogging;
<ide> import org.springframework.lang.Nullable;
<ide> import org.springframework.util.Assert;
<ide> import org.springframework.util.MimeType;
<ide> public abstract class Jackson2CodecSupport {
<ide> new MimeType("application", "*+json", StandardCharsets.UTF_8)));
<ide>
<ide>
<del> protected final Log logger = HttpLog.create(LogFactory.getLog(getClass()));
<add> protected final Log logger = HttpLogging.forLogName(getClass());
<ide>
<ide> private final ObjectMapper objectMapper;
<ide>
<ide><path>spring-web/src/main/java/org/springframework/http/converter/AbstractHttpMessageConverter.java
<ide> import java.util.List;
<ide>
<ide> import org.apache.commons.logging.Log;
<del>import org.apache.commons.logging.LogFactory;
<ide>
<ide> import org.springframework.http.HttpHeaders;
<ide> import org.springframework.http.HttpInputMessage;
<del>import org.springframework.http.HttpLog;
<add>import org.springframework.http.HttpLogging;
<ide> import org.springframework.http.HttpOutputMessage;
<ide> import org.springframework.http.MediaType;
<ide> import org.springframework.http.StreamingHttpOutputMessage;
<ide> public abstract class AbstractHttpMessageConverter<T> implements HttpMessageConverter<T> {
<ide>
<ide> /** Logger available to subclasses. */
<del> protected final Log logger = HttpLog.create(LogFactory.getLog(getClass()));
<add> protected final Log logger = HttpLogging.forLogName(getClass());
<ide>
<ide> private List<MediaType> supportedMediaTypes = Collections.emptyList();
<ide>
<ide><path>spring-web/src/main/java/org/springframework/http/converter/json/Jackson2ObjectMapperBuilder.java
<ide> import com.fasterxml.jackson.dataformat.xml.XmlFactory;
<ide> import com.fasterxml.jackson.dataformat.xml.XmlMapper;
<ide> import org.apache.commons.logging.Log;
<del>import org.apache.commons.logging.LogFactory;
<ide>
<ide> import org.springframework.beans.BeanUtils;
<ide> import org.springframework.beans.FatalBeanException;
<ide> import org.springframework.context.ApplicationContext;
<ide> import org.springframework.core.KotlinDetector;
<del>import org.springframework.http.HttpLog;
<add>import org.springframework.http.HttpLogging;
<ide> import org.springframework.lang.Nullable;
<ide> import org.springframework.util.Assert;
<ide> import org.springframework.util.ClassUtils;
<ide> public class Jackson2ObjectMapperBuilder {
<ide>
<ide> private static volatile boolean kotlinWarningLogged = false;
<ide>
<del> private final Log logger = HttpLog.create(LogFactory.getLog(getClass()));
<add> private final Log logger = HttpLogging.forLogName(getClass());
<ide>
<ide> private final Map<Class<?>, Class<?>> mixIns = new HashMap<>();
<ide>
<ide><path>spring-web/src/main/java/org/springframework/http/server/reactive/AbstractListenerReadPublisher.java
<ide> import java.util.concurrent.atomic.AtomicReference;
<ide>
<ide> import org.apache.commons.logging.Log;
<del>import org.apache.commons.logging.LogFactory;
<ide> import org.reactivestreams.Publisher;
<ide> import org.reactivestreams.Subscriber;
<ide> import org.reactivestreams.Subscription;
<ide> import reactor.core.publisher.Operators;
<ide>
<ide> import org.springframework.lang.Nullable;
<ide> import org.springframework.util.Assert;
<add>import org.springframework.util.log.LogUtils;
<ide>
<ide> /**
<ide> * Abstract base class for {@code Publisher} implementations that bridge between
<ide> public abstract class AbstractListenerReadPublisher<T> implements Publisher<T> {
<ide>
<ide> /**
<del> * Special logger for tracing Reactive Streams signals.
<del> * <p>This logger is not exposed under "org.springframework" because it is
<del> * verbose. To enable this, and other related Reactive Streams loggers in
<del> * this package, set "spring-web.reactivestreams" to TRACE.
<add> * Special logger for debugging Reactive Streams signals.
<add> * @see LogUtils#getHiddenLog(Class)
<add> * @see AbstractListenerWriteProcessor#rsWriteLogger
<add> * @see AbstractListenerWriteFlushProcessor#rsWriteFlushLogger
<add> * @see WriteResultPublisher#rsWriteResultLogger
<ide> */
<del> protected static Log rsReadLogger = LogFactory.getLog("spring-web.reactivestreams.ReadPublisher");
<add> protected static Log rsReadLogger = LogUtils.getHiddenLog(AbstractListenerReadPublisher.class);
<ide>
<ide>
<ide> private final AtomicReference<State> state = new AtomicReference<>(State.UNSUBSCRIBED);
<ide><path>spring-web/src/main/java/org/springframework/http/server/reactive/AbstractListenerWriteFlushProcessor.java
<ide> import java.util.concurrent.atomic.AtomicReference;
<ide>
<ide> import org.apache.commons.logging.Log;
<del>import org.apache.commons.logging.LogFactory;
<ide> import org.reactivestreams.Processor;
<ide> import org.reactivestreams.Publisher;
<ide> import org.reactivestreams.Subscriber;
<ide> import org.reactivestreams.Subscription;
<ide>
<ide> import org.springframework.lang.Nullable;
<ide> import org.springframework.util.Assert;
<add>import org.springframework.util.log.LogUtils;
<ide>
<ide> /**
<ide> * An alternative to {@link AbstractListenerWriteProcessor} but instead writing
<ide> public abstract class AbstractListenerWriteFlushProcessor<T> implements Processor<Publisher<? extends T>, Void> {
<ide>
<ide> /**
<del> * Special logger for tracing Reactive Streams signals.
<del> * <p>This logger is not exposed under "org.springframework" because it is
<del> * verbose. To enable this, and other related Reactive Streams loggers in
<del> * this package, set "spring-web.reactivestreams" to TRACE.
<add> * Special logger for debugging Reactive Streams signals.
<add> * @see LogUtils#getHiddenLog(Class)
<add> * @see AbstractListenerReadPublisher#rsReadLogger
<add> * @see AbstractListenerWriteProcessor#rsWriteLogger
<add> * @see WriteResultPublisher#rsWriteResultLogger
<ide> */
<del> protected static final Log rsWriteFlushLogger =
<del> LogFactory.getLog("spring-web.reactivestreams.WriteFlushProcessor");
<add> protected static final Log rsWriteFlushLogger = LogUtils.getHiddenLog(AbstractListenerWriteFlushProcessor.class);
<ide>
<ide>
<ide> private final AtomicReference<State> state = new AtomicReference<>(State.UNSUBSCRIBED);
<ide><path>spring-web/src/main/java/org/springframework/http/server/reactive/AbstractListenerWriteProcessor.java
<ide> import java.util.concurrent.atomic.AtomicReference;
<ide>
<ide> import org.apache.commons.logging.Log;
<del>import org.apache.commons.logging.LogFactory;
<ide> import org.reactivestreams.Processor;
<ide> import org.reactivestreams.Subscriber;
<ide> import org.reactivestreams.Subscription;
<ide>
<ide> import org.springframework.lang.Nullable;
<ide> import org.springframework.util.Assert;
<add>import org.springframework.util.log.LogUtils;
<ide>
<ide> /**
<ide> * Abstract base class for {@code Processor} implementations that bridge between
<ide> public abstract class AbstractListenerWriteProcessor<T> implements Processor<T, Void> {
<ide>
<ide> /**
<del> * Special logger for tracing Reactive Streams signals.
<del> * <p>This logger is not exposed under "org.springframework" because it is
<del> * verbose. To enable this, and other related Reactive Streams loggers in
<del> * this package, set "spring-web.reactivestreams" to TRACE.
<add> * Special logger for debugging Reactive Streams signals.
<add> * @see LogUtils#getHiddenLog(Class)
<add> * @see AbstractListenerReadPublisher#rsReadLogger
<add> * @see AbstractListenerWriteFlushProcessor#rsWriteFlushLogger
<add> * @see WriteResultPublisher#rsWriteResultLogger
<ide> */
<del> protected static final Log rsWriteLogger = LogFactory.getLog("spring-web.reactivestreams.WriteProcessor");
<add> protected static final Log rsWriteLogger = LogUtils.getHiddenLog(AbstractListenerWriteProcessor.class);
<ide>
<ide>
<ide> private final AtomicReference<State> state = new AtomicReference<>(State.UNSUBSCRIBED);
<ide><path>spring-web/src/main/java/org/springframework/http/server/reactive/AbstractServerHttpRequest.java
<ide> import java.util.regex.Pattern;
<ide>
<ide> import org.apache.commons.logging.Log;
<del>import org.apache.commons.logging.LogFactory;
<ide>
<ide> import org.springframework.http.HttpCookie;
<ide> import org.springframework.http.HttpHeaders;
<del>import org.springframework.http.HttpLog;
<add>import org.springframework.http.HttpLogging;
<ide> import org.springframework.http.server.RequestPath;
<ide> import org.springframework.lang.Nullable;
<ide> import org.springframework.util.CollectionUtils;
<ide> */
<ide> public abstract class AbstractServerHttpRequest implements ServerHttpRequest {
<ide>
<del> protected final Log logger = HttpLog.create(LogFactory.getLog(getClass()));
<add> protected final Log logger = HttpLogging.forLogName(getClass());
<ide>
<ide> private static final Pattern QUERY_PATTERN = Pattern.compile("([^&=]+)(=?)([^&]+)?");
<ide>
<ide><path>spring-web/src/main/java/org/springframework/http/server/reactive/AbstractServerHttpResponse.java
<ide> import java.util.stream.Collectors;
<ide>
<ide> import org.apache.commons.logging.Log;
<del>import org.apache.commons.logging.LogFactory;
<ide> import org.reactivestreams.Publisher;
<ide> import reactor.core.publisher.Flux;
<ide> import reactor.core.publisher.Mono;
<ide>
<ide> import org.springframework.core.io.buffer.DataBuffer;
<ide> import org.springframework.core.io.buffer.DataBufferFactory;
<ide> import org.springframework.http.HttpHeaders;
<del>import org.springframework.http.HttpLog;
<add>import org.springframework.http.HttpLogging;
<ide> import org.springframework.http.HttpStatus;
<ide> import org.springframework.http.ResponseCookie;
<ide> import org.springframework.lang.Nullable;
<ide> public abstract class AbstractServerHttpResponse implements ServerHttpResponse {
<ide> */
<ide> private enum State {NEW, COMMITTING, COMMITTED}
<ide>
<del> protected final Log logger = HttpLog.create(LogFactory.getLog(getClass()));
<add> protected final Log logger = HttpLogging.forLogName(getClass());
<ide>
<ide>
<ide> private final DataBufferFactory dataBufferFactory;
<ide><path>spring-web/src/main/java/org/springframework/http/server/reactive/ReactorHttpHandlerAdapter.java
<ide>
<ide> import io.netty.handler.codec.http.HttpResponseStatus;
<ide> import org.apache.commons.logging.Log;
<del>import org.apache.commons.logging.LogFactory;
<ide> import reactor.core.publisher.Mono;
<ide> import reactor.netty.http.server.HttpServerRequest;
<ide> import reactor.netty.http.server.HttpServerResponse;
<ide>
<ide> import org.springframework.core.io.buffer.NettyDataBufferFactory;
<del>import org.springframework.http.HttpLog;
<add>import org.springframework.http.HttpLogging;
<ide> import org.springframework.http.HttpMethod;
<ide> import org.springframework.util.Assert;
<ide>
<ide> */
<ide> public class ReactorHttpHandlerAdapter implements BiFunction<HttpServerRequest, HttpServerResponse, Mono<Void>> {
<ide>
<del> private static final Log logger = HttpLog.create(LogFactory.getLog(ReactorHttpHandlerAdapter.class));
<add> private static final Log logger = HttpLogging.forLogName(ReactorHttpHandlerAdapter.class);
<ide>
<ide>
<ide> private final HttpHandler httpHandler;
<ide><path>spring-web/src/main/java/org/springframework/http/server/reactive/ServletHttpHandlerAdapter.java
<ide> import javax.servlet.http.HttpServletResponse;
<ide>
<ide> import org.apache.commons.logging.Log;
<del>import org.apache.commons.logging.LogFactory;
<ide> import org.reactivestreams.Subscriber;
<ide> import org.reactivestreams.Subscription;
<ide>
<ide> import org.springframework.core.io.buffer.DataBufferFactory;
<ide> import org.springframework.core.io.buffer.DefaultDataBufferFactory;
<del>import org.springframework.http.HttpLog;
<add>import org.springframework.http.HttpLogging;
<ide> import org.springframework.http.HttpMethod;
<ide> import org.springframework.lang.Nullable;
<ide> import org.springframework.util.Assert;
<ide> @SuppressWarnings("serial")
<ide> public class ServletHttpHandlerAdapter implements Servlet {
<ide>
<del> private static final Log logger = HttpLog.create(LogFactory.getLog(ServletHttpHandlerAdapter.class));
<add> private static final Log logger = HttpLogging.forLogName(ServletHttpHandlerAdapter.class);
<ide>
<ide> private static final int DEFAULT_BUFFER_SIZE = 8192;
<ide>
<ide><path>spring-web/src/main/java/org/springframework/http/server/reactive/UndertowHttpHandlerAdapter.java
<ide>
<ide> import io.undertow.server.HttpServerExchange;
<ide> import org.apache.commons.logging.Log;
<del>import org.apache.commons.logging.LogFactory;
<ide> import org.reactivestreams.Subscriber;
<ide> import org.reactivestreams.Subscription;
<ide>
<ide> import org.springframework.core.io.buffer.DataBufferFactory;
<ide> import org.springframework.core.io.buffer.DefaultDataBufferFactory;
<del>import org.springframework.http.HttpLog;
<add>import org.springframework.http.HttpLogging;
<ide> import org.springframework.http.HttpMethod;
<ide> import org.springframework.util.Assert;
<ide>
<ide> */
<ide> public class UndertowHttpHandlerAdapter implements io.undertow.server.HttpHandler {
<ide>
<del> private static final Log logger = HttpLog.create(LogFactory.getLog(UndertowHttpHandlerAdapter.class));
<add> private static final Log logger = HttpLogging.forLogName(UndertowHttpHandlerAdapter.class);
<ide>
<ide>
<ide> private final HttpHandler httpHandler;
<ide><path>spring-web/src/main/java/org/springframework/http/server/reactive/WriteResultPublisher.java
<ide> import java.util.concurrent.atomic.AtomicReference;
<ide>
<ide> import org.apache.commons.logging.Log;
<del>import org.apache.commons.logging.LogFactory;
<ide> import org.reactivestreams.Publisher;
<ide> import org.reactivestreams.Subscriber;
<ide> import org.reactivestreams.Subscription;
<ide> import reactor.core.publisher.Operators;
<ide>
<ide> import org.springframework.lang.Nullable;
<ide> import org.springframework.util.Assert;
<add>import org.springframework.util.log.LogUtils;
<ide>
<ide> /**
<ide> * Publisher returned from {@link ServerHttpResponse#writeWith(Publisher)}.
<ide> class WriteResultPublisher implements Publisher<Void> {
<ide>
<ide> /**
<del> * Special logger for tracing Reactive Streams signals.
<del> * <p>This logger is not exposed under "org.springframework" because it is
<del> * verbose. To enable this, and other related Reactive Streams loggers in
<del> * this package, set "spring-web.reactivestreams" to TRACE.
<add> * Special logger for debugging Reactive Streams signals.
<add> * @see LogUtils#getHiddenLog(Class)
<add> * @see AbstractListenerReadPublisher#rsReadLogger
<add> * @see AbstractListenerWriteProcessor#rsWriteLogger
<add> * @see AbstractListenerWriteFlushProcessor#rsWriteFlushLogger
<ide> */
<del> private static final Log rsWriteResultLogger =
<del> LogFactory.getLog("spring-web.reactivestreams.WriteResultPublisher");
<add> private static final Log rsWriteResultLogger = LogUtils.getHiddenLog(WriteResultPublisher.class);
<ide>
<ide>
<ide> private final AtomicReference<State> state = new AtomicReference<>(State.UNSUBSCRIBED); | 22 |
Go | Go | fix time setting for old kernels | 55e1782d6623b59af3f1aea1eb9646a36bbb5579 | <ide><path>image.go
<ide> func (image *Image) TarLayer(compression Compression) (Archive, error) {
<ide> type TimeUpdate struct {
<ide> path string
<ide> time []syscall.Timeval
<add> mode uint32
<ide> }
<ide>
<ide> func (image *Image) applyLayer(layer, target string) error {
<ide> func (image *Image) applyLayer(layer, target string) error {
<ide> u := TimeUpdate{
<ide> path: targetPath,
<ide> time: ts,
<add> mode: srcStat.Mode,
<ide> }
<ide>
<ide> // Delay time updates until all other changes done, or it is
<ide> func (image *Image) applyLayer(layer, target string) error {
<ide> update := updateTimes[i]
<ide>
<ide> O_PATH := 010000000 // Not in syscall yet
<del> fd, err := syscall.Open(update.path, syscall.O_RDWR|O_PATH|syscall.O_NOFOLLOW, 0600)
<del> if err == syscall.EISDIR || err == syscall.ELOOP {
<del> // O_PATH not supported, use Utimes except on symlinks where Utimes doesn't work
<del> if err != syscall.ELOOP {
<del> err = syscall.Utimes(update.path, update.time)
<del> if err != nil {
<del> return err
<del> }
<add> var err error = nil
<add> if update.mode&syscall.S_IFLNK == syscall.S_IFLNK {
<add> // Update time on the symlink via O_PATH + futimes(), if supported by the kernel
<add>
<add> fd, err := syscall.Open(update.path, syscall.O_RDWR|O_PATH|syscall.O_NOFOLLOW, 0600)
<add> if err == syscall.EISDIR || err == syscall.ELOOP {
<add> // O_PATH not supported by kernel, nothing to do, ignore
<add> } else if err != nil {
<add> return err
<add> } else {
<add> syscall.Futimes(fd, update.time)
<add> _ = syscall.Close(fd)
<ide> }
<ide> } else {
<add> err = syscall.Utimes(update.path, update.time)
<ide> if err != nil {
<ide> return err
<ide> }
<del> syscall.Futimes(fd, update.time)
<del> _ = syscall.Close(fd)
<ide> }
<ide> }
<ide> | 1 |
PHP | PHP | add filename option | 2c463284582f9ec43083ccae459838380c87df1d | <ide><path>src/Illuminate/Foundation/Console/EnvironmentDecryptCommand.php
<ide> class EnvironmentDecryptCommand extends Command
<ide> {--key= : The encryption key}
<ide> {--cipher= : The encryption cipher}
<ide> {--env= : The environment to be decrypted}
<del> {--force : Overwrite existing environment file}';
<add> {--force : Overwrite existing environment file}
<add> {--filename : Filename to which to write the decrypted contents}';
<ide>
<ide> /**
<ide> * The name of the console command.
<ide> public function handle()
<ide> ? base_path('.env').'.'.$this->option('env')
<ide> : $this->laravel->environmentFilePath();
<ide> $encryptedFile = $environmentFile.'.encrypted';
<add> $filename = $this->option('filename') ? base_path($this->option('filename')) : $environmentFile;
<ide>
<ide> if (! $this->files->exists($encryptedFile)) {
<ide> $this->components->error('Encrypted environment file not found.');
<ide> public function handle()
<ide> $encrypter = new Encrypter($key, $cipher);
<ide>
<ide> $this->files->put(
<del> $environmentFile,
<add> $filename,
<ide> $encrypter->decrypt($this->files->get($encryptedFile))
<ide> );
<ide> } catch (Exception $e) {
<ide><path>tests/Integration/Console/EnvironmentDecryptCommandTest.php
<ide> public function testItDecryptsMultiLineEnvironmentCorrectly()
<ide> $this->filesystem->shouldHaveReceived('put')
<ide> ->with(base_path('.env'), $contents);
<ide> }
<add>
<add> public function testItWritesTheEnvironmentFileCustomFilename()
<add> {
<add> $this->filesystem->shouldReceive('exists')
<add> ->once()
<add> ->andReturn(true)
<add> ->shouldReceive('exists')
<add> ->once()
<add> ->andReturn(false)
<add> ->shouldReceive('get')
<add> ->once()
<add> ->andReturn(
<add> (new Encrypter('abcdefghijklmnop'))
<add> ->encrypt('APP_NAME="Laravel Two"')
<add> );
<add>
<add> $this->artisan('env:decrypt', ['--env' => 'production', '--key' => 'abcdefghijklmnop', '--filename' => '.env'])
<add> ->expectsOutputToContain('Environment successfully decrypted.')
<add> ->assertExitCode(0);
<add>
<add> $this->filesystem->shouldHaveReceived('put')
<add> ->with(base_path('.env'), 'APP_NAME="Laravel Two"');
<add> }
<ide> } | 2 |
Javascript | Javascript | add semicolon to make jshint happy | ce072ac3e884f51d3fcbfb78a7beb3c493cbad63 | <ide><path>src/test/moment/format.js
<ide> test('full expanded format is returned from abbreviated formats', function(asser
<ide> assert.equal(false, !!~format.indexOf(token), 'locale ' + locale + ' contains ' + token + ' in ' + i);
<ide> });
<ide> });
<del> })
<add> });
<ide>
<ide> }); | 1 |
Ruby | Ruby | handle nil qs | 0c92a51dadc48fc64c7c35606c5616d2f40be107 | <ide><path>actionpack/lib/action_dispatch/rack/parse_query.rb
<ide> module Utils
<ide> module_function :parse_query_without_ajax_body_cleanup
<ide>
<ide> def parse_query(qs, d = '&;')
<del> qs = qs.dup
<add> qs = qs.to_s.dup
<ide> qs.chop! if qs[-1] == 0
<ide> qs.gsub!(/&_=$/, '')
<ide> parse_query_without_ajax_body_cleanup(qs, d) | 1 |
Javascript | Javascript | ignore jqlite#append for doc fragment | a2c42711281d6ec61b73190b47743f79143c5bb1 | <ide><path>src/jqLite.js
<ide> forEach({
<ide>
<ide> append: function(element, node) {
<ide> forEach(new JQLite(node), function(child){
<del> element.appendChild(child);
<add> if (element.nodeType === 1)
<add> element.appendChild(child);
<ide> });
<ide> },
<ide>
<ide><path>test/jqLiteSpec.js
<ide> describe('jqLite', function(){
<ide> expect(root.append('text')).toEqual(root);
<ide> expect(root.html()).toEqual('text');
<ide> });
<add> it('should not append anything if parent node is not of type element', function() {
<add> var root = jqLite(document.createDocumentFragment());
<add> expect(root.append('<p>foo</p>')).toBe(root);
<add> expect(root.children().length).toBe(0);
<add> });
<ide> });
<ide> describe('remove', function(){
<ide> it('should remove', function(){ | 2 |
Mixed | Javascript | use bytelength to handle arraybuffer views | 6bbe28552ced571bec3a21861cf16987927fa056 | <ide><path>doc/api/fs.md
<ide> added: v10.0.0
<ide> added: v10.0.0
<ide> -->
<ide>
<del>* `buffer` {Buffer|Uint8Array} A buffer that will be filled with the file
<del> data read.
<add>* `buffer` {Buffer|TypedArray|DataView} A buffer that will be filled with the
<add> file data read.
<ide> * `offset` {integer} The location in the buffer at which to start filling.
<ide> **Default:** `0`
<del>* `length` {integer} The number of bytes to read. **Default:** `buffer.length`
<add>* `length` {integer} The number of bytes to read. **Default:**
<add> `buffer.byteLength`
<ide> * `position` {integer} The location where to begin reading data from the
<ide> file. If `null`, data will be read from the current file position, and
<ide> the position will be updated. If `position` is an integer, the current
<ide> file position will remain unchanged.
<ide> * Returns: {Promise} Fulfills upon success with an object with two properties:
<ide> * `bytesRead` {integer} The number of bytes read
<del> * `buffer` {Buffer|Uint8Array} A reference to the passed in `buffer` argument.
<add> * `buffer` {Buffer|TypedArray|DataView} A reference to the passed in `buffer`
<add> argument.
<ide>
<ide> Reads data from the file and stores that in the given buffer.
<ide>
<ide> added:
<ide> - v12.17.0
<ide> -->
<ide> * `options` {Object}
<del> * `buffer` {Buffer|Uint8Array} A buffer that will be filled with the file
<del> data read. **Default:** `Buffer.alloc(16384)`
<add> * `buffer` {Buffer|TypedArray|DataView} A buffer that will be filled with the
<add> file data read. **Default:** `Buffer.alloc(16384)`
<ide> * `offset` {integer} The location in the buffer at which to start filling.
<ide> **Default:** `0`
<del> * `length` {integer} The number of bytes to read. **Default:** `buffer.length`
<add> * `length` {integer} The number of bytes to read. **Default:**
<add> `buffer.byteLength`
<ide> * `position` {integer} The location where to begin reading data from the
<ide> file. If `null`, data will be read from the current file position, and
<ide> the position will be updated. If `position` is an integer, the current
<ide> file position will remain unchanged. **Default:**: `null`
<ide> * Returns: {Promise} Fulfills upon success with an object with two properties:
<ide> * `bytesRead` {integer} The number of bytes read
<del> * `buffer` {Buffer|Uint8Array} A reference to the passed in `buffer`
<del> argument.
<add> * `buffer` {Buffer|TypedArray|DataView} A reference to the passed in `buffer`
<add> argument.
<ide>
<ide> Reads data from the file and stores that in the given buffer.
<ide>
<ide> changes:
<ide> buffers anymore.
<ide> -->
<ide>
<del>* `buffer` {Buffer|Uint8Array|string|Object}
<add>* `buffer` {Buffer|TypedArray|DataView|string|Object}
<ide> * `offset` {integer} The start position from within `buffer` where the data
<del> to write begins.
<del>* `length` {integer} The number of bytes from `buffer` to write.
<add> to write begins. **Default:** `0`
<add>* `length` {integer} The number of bytes from `buffer` to write. **Default:**
<add> `buffer.byteLength`
<ide> * `position` {integer} The offset from the beginning of the file where the
<ide> data from `buffer` should be written. If `position` is not a `number`,
<ide> the data will be written at the current position. See the POSIX pwrite(2)
<ide> Write `buffer` to the file.
<ide> The promise is resolved with an object containing two properties:
<ide>
<ide> * `bytesWritten` {integer} the number of bytes written
<del>* `buffer` {Buffer|Uint8Array|string|Object} a reference to the `buffer`
<del> written.
<add>* `buffer` {Buffer|TypedArray|DataView|string|Object} a reference to the
<add> `buffer` written.
<ide>
<ide> It is unsafe to use `filehandle.write()` multiple times on the same file
<ide> without waiting for the promise to be resolved (or rejected). For this
<ide> changes:
<ide> strings anymore.
<ide> -->
<ide>
<del>* `data` {string|Buffer|Uint8Array|Object}
<add>* `data` {string|Buffer|TypedArray|DataView|Object}
<ide> * `options` {Object|string}
<ide> * `encoding` {string|null} The expected character encoding when `data` is a
<ide> string. **Default:** `'utf8'`
<ide> changes:
<ide> -->
<ide>
<ide> * `file` {string|Buffer|URL|FileHandle} filename or `FileHandle`
<del>* `data` {string|Buffer|Uint8Array|Object|AsyncIterable|Iterable
<add>* `data` {string|Buffer|TypedArray|DataView|Object|AsyncIterable|Iterable
<ide> |Stream}
<ide> * `options` {Object|string}
<ide> * `encoding` {string|null} **Default:** `'utf8'`
<ide> changes:
<ide>
<ide> * `fd` {integer}
<ide> * `buffer` {Buffer|TypedArray|DataView} The buffer that the data will be
<del> written to.
<del>* `offset` {integer} The position in `buffer` to write the data to.
<del>* `length` {integer} The number of bytes to read.
<add> written to. **Default:** `Buffer.alloc(16384)`
<add>* `offset` {integer} The position in `buffer` to write the data to. **Default:**
<add> `0`
<add>* `length` {integer} The number of bytes to read. **Default:**
<add> `buffer.byteLength`
<ide> * `position` {integer|bigint} Specifies where to begin reading from in the
<ide> file. If `position` is `null` or `-1 `, data will be read from the current
<ide> file position, and the file position will be updated. If `position` is an
<ide> changes:
<ide> * `options` {Object}
<ide> * `buffer` {Buffer|TypedArray|DataView} **Default:** `Buffer.alloc(16384)`
<ide> * `offset` {integer} **Default:** `0`
<del> * `length` {integer} **Default:** `buffer.length`
<add> * `length` {integer} **Default:** `buffer.byteLength`
<ide> * `position` {integer|bigint} **Default:** `null`
<ide> * `callback` {Function}
<ide> * `err` {Error}
<ide> changes:
<ide> * `buffer` {Buffer|TypedArray|DataView}
<ide> * `options` {Object}
<ide> * `offset` {integer} **Default:** `0`
<del> * `length` {integer} **Default:** `buffer.length`
<add> * `length` {integer} **Default:** `buffer.byteLength`
<ide> * `position` {integer|bigint} **Default:** `null`
<ide> * Returns: {number}
<ide>
<ide><path>lib/fs.js
<ide> function read(fd, buffer, offset, length, position, callback) {
<ide> ({
<ide> buffer = Buffer.alloc(16384),
<ide> offset = 0,
<del> length = buffer.length,
<add> length = buffer.byteLength,
<ide> position
<ide> } = options);
<ide> }
<ide> ObjectDefineProperty(read, internalUtil.customPromisifyArgs,
<ide> function readSync(fd, buffer, offset, length, position) {
<ide> fd = getValidatedFd(fd);
<ide>
<add> validateBuffer(buffer);
<add>
<ide> if (arguments.length <= 3) {
<ide> // Assume fs.read(fd, buffer, options)
<ide> const options = offset || {};
<ide>
<del> ({ offset = 0, length = buffer.length, position } = options);
<add> ({ offset = 0, length = buffer.byteLength, position } = options);
<ide> }
<ide>
<del> validateBuffer(buffer);
<del>
<ide> if (offset == null) {
<ide> offset = 0;
<ide> } else {
<ide> function write(fd, buffer, offset, length, position, callback) {
<ide> validateInteger(offset, 'offset');
<ide> }
<ide> if (typeof length !== 'number')
<del> length = buffer.length - offset;
<add> length = buffer.byteLength - offset;
<ide> if (typeof position !== 'number')
<ide> position = null;
<ide> validateOffsetLengthWrite(offset, length, buffer.byteLength);
<ide><path>lib/internal/fs/promises.js
<ide> async function writeFileHandle(filehandle, data, signal, encoding) {
<ide> checkAborted(signal);
<ide> await write(
<ide> filehandle, buf, undefined,
<del> isArrayBufferView(buf) ? buf.length : encoding);
<add> isArrayBufferView(buf) ? buf.byteLength : encoding);
<ide> checkAborted(signal);
<ide> }
<ide> return;
<ide> }
<ide> data = new Uint8Array(data.buffer, data.byteOffset, data.byteLength);
<del> let remaining = data.length;
<add> let remaining = data.byteLength;
<ide> if (remaining === 0) return;
<ide> do {
<ide> checkAborted(signal);
<ide> const { bytesWritten } =
<ide> await write(filehandle, data, 0,
<del> MathMin(kWriteFileMaxChunkSize, data.length));
<add> MathMin(kWriteFileMaxChunkSize, data.byteLength));
<ide> remaining -= bytesWritten;
<ide> data = new Uint8Array(
<ide> data.buffer,
<ide> async function read(handle, bufferOrOptions, offset, length, position) {
<ide> buffer = Buffer.alloc(16384);
<ide> }
<ide> offset = bufferOrOptions.offset || 0;
<del> length = buffer.length;
<add> length = buffer.byteLength;
<ide> position = bufferOrOptions.position || null;
<ide> }
<ide>
<ide> async function read(handle, bufferOrOptions, offset, length, position) {
<ide> if (length === 0)
<ide> return { bytesRead: length, buffer };
<ide>
<del> if (buffer.length === 0) {
<add> if (buffer.byteLength === 0) {
<ide> throw new ERR_INVALID_ARG_VALUE('buffer', buffer,
<ide> 'is empty and cannot be written');
<ide> }
<ide>
<del> validateOffsetLengthRead(offset, length, buffer.length);
<add> validateOffsetLengthRead(offset, length, buffer.byteLength);
<ide>
<ide> if (!NumberIsSafeInteger(position))
<ide> position = -1;
<ide> async function readv(handle, buffers, position) {
<ide> }
<ide>
<ide> async function write(handle, buffer, offset, length, position) {
<del> if (buffer?.length === 0)
<add> if (buffer?.byteLength === 0)
<ide> return { bytesWritten: 0, buffer };
<ide>
<ide> if (isArrayBufferView(buffer)) {
<ide> async function write(handle, buffer, offset, length, position) {
<ide> validateInteger(offset, 'offset');
<ide> }
<ide> if (typeof length !== 'number')
<del> length = buffer.length - offset;
<add> length = buffer.byteLength - offset;
<ide> if (typeof position !== 'number')
<ide> position = null;
<ide> validateOffsetLengthWrite(offset, length, buffer.byteLength);
<ide><path>test/parallel/test-fs-write-buffer.js
<ide> tmpdir.refresh();
<ide> fs.closeSync(fd);
<ide> }));
<ide> }
<add>
<add>// fs.write with a DataView, without the offset and length parameters:
<add>{
<add> const filename = path.join(tmpdir.path, 'write8.txt');
<add> fs.open(filename, 'w', 0o644, common.mustSucceed((fd) => {
<add> const cb = common.mustSucceed((written) => {
<add> assert.strictEqual(written, expected.length);
<add> fs.closeSync(fd);
<add>
<add> const found = fs.readFileSync(filename, 'utf8');
<add> assert.strictEqual(found, expected.toString());
<add> });
<add>
<add> const uint8 = Uint8Array.from(expected);
<add> fs.write(fd, new DataView(uint8.buffer), cb);
<add> }));
<add>} | 4 |
Text | Text | fix inconsistency for | 6d50737355f748cbb49d304d0b2dbfe5a17dfd16 | <ide><path>docs/reference/commandline/service.md
<ide> Commands:
<ide> inspect Display detailed information on one or more services
<ide> logs Fetch the logs of a service
<ide> ls List services
<del> ps List the tasks of a service
<add> ps List the tasks of one or more services
<ide> rm Remove one or more services
<ide> scale Scale one or multiple replicated services
<ide> update Update a service
<ide><path>docs/reference/commandline/service_ps.md
<ide> aliases: ["/engine/reference/commandline/service_tasks/"]
<ide> # service ps
<ide>
<ide> ```Markdown
<del>Usage: docker service ps [OPTIONS] SERVICE
<add>Usage: docker service ps [OPTIONS] SERVICE [SERVICE...]
<ide>
<ide> List the tasks of one or more services
<ide>
<ide> ID NAME IMAGE NODE DESIRED STATE CURRENT STATE
<ide> 8eaxrb2fqpbn redis.10 redis:3.0.6 manager1 Running Running 8 seconds
<ide> ```
<ide>
<del>
<ide> #### desired-state
<ide>
<ide> The `desired-state` filter can take the values `running`, `shutdown`, and `accepted`.
<ide>
<del>
<ide> ### Formatting
<ide>
<ide> The formatting options (`--format`) pretty-prints tasks output
<ide> output the data exactly as the template declares or, when using the
<ide> `table` directive, includes column headers as well.
<ide>
<ide> The following example uses a template without headers and outputs the
<del>`ID` and `Driver` entries separated by a colon for all tasks:
<add>`Name` and `Image` entries separated by a colon for all tasks:
<ide>
<ide> ```bash
<ide> $ docker service ps --format "{{.Name}}: {{.Image}}" top | 2 |
Python | Python | add set_learning_phase in tf backend | 2cc9ebf28bef640043fc9abc2c61a421ffded792 | <ide><path>keras/backend/tensorflow_backend.py
<ide> def learning_phase():
<ide> return _LEARNING_PHASE
<ide>
<ide>
<add>def set_learning_phase(value):
<add> global _LEARNING_PHASE
<add> _LEARNING_PHASE = tf.constant(value, name='keras_learning_phase')
<add>
<add>
<ide> def get_session():
<ide> '''Returns the TF session in use by the backend.
<ide> ''' | 1 |
Ruby | Ruby | remove download_strategy from softwarespec | 9d3b9edb4dc0303a884d5bd826ad62788ced9c89 | <ide><path>Library/Homebrew/software_spec.rb
<ide> class SoftwareSpec
<ide> attr_reader :build, :resources, :owner
<ide> attr_reader :dependency_collector
<ide>
<del> def_delegators :@resource, :stage, :fetch
<del> def_delegators :@resource, :download_strategy, :verify_download_integrity
<add> def_delegators :@resource, :stage, :fetch, :verify_download_integrity
<ide> def_delegators :@resource, :cached_download, :clear_cache
<ide> def_delegators :@resource, :checksum, :mirrors, :specs, :using, :downloader
<ide> def_delegators :@resource, :version, :mirror, *Checksum::TYPES | 1 |
Javascript | Javascript | use the frustum diagonal | d527e1b7e4b420c0aef99e161934795f6ac4d50f | <ide><path>examples/jsm/csm/CSM.js
<ide> export default class CSM {
<ide> _bbox.getCenter( _center );
<ide> _center.z = _bbox.max.z + this.lightMargin;
<ide>
<del> let squaredBBWidth = _lightSpaceFrustum.vertices.far[ 0 ].distanceTo( _lightSpaceFrustum.vertices.far[ 2 ] );
<add> let squaredBBWidth = _lightSpaceFrustum.vertices.far[ 0 ].distanceTo( _lightSpaceFrustum.vertices.near[ 2 ] );
<ide> if ( this.fade ) {
<ide>
<ide> // expand the shadow extents by the fade margin if fade is enabled.
<ide> export default class CSM {
<ide> const texelSize = squaredBBWidth / this.shadowMapSize;
<ide> _center.x = Math.floor( _center.x / texelSize ) * texelSize;
<ide> _center.y = Math.floor( _center.y / texelSize ) * texelSize;
<del> _center.z = Math.floor( _center.z / texelSize ) * texelSize;
<ide> _center.applyMatrix4( light.shadow.camera.matrixWorld );
<ide>
<ide> light.shadow.camera.left = - squaredBBWidth / 2; | 1 |
Python | Python | forbid resnet v1 from running with fp16 | 4b8fe70416fe4826a3bad622e56780a7c2eb330c | <ide><path>official/resnet/cifar10_test.py
<ide> def test_cifar10_end_to_end_synthetic_v2(self):
<ide> extra_flags=['-resnet_version', '2']
<ide> )
<ide>
<add> def test_flag_restriction(self):
<add> with self.assertRaises(SystemExit):
<add> integration.run_synthetic(
<add> main=cifar10_main.run_cifar, tmp_root=self.get_temp_dir(),
<add> extra_flags=['-resnet_version', '1', "-dtype", "fp16"]
<add> )
<add>
<ide>
<ide> if __name__ == '__main__':
<ide> tf.test.main()
<ide><path>official/resnet/imagenet_test.py
<ide> def test_imagenet_end_to_end_synthetic_v2_huge(self):
<ide> extra_flags=['-resnet_version', '2', '-resnet_size', '200']
<ide> )
<ide>
<add> def test_flag_restriction(self):
<add> with self.assertRaises(SystemExit):
<add> integration.run_synthetic(
<add> main=imagenet_main.run_imagenet, tmp_root=self.get_temp_dir(),
<add> extra_flags=['-resnet_version', '1', '-dtype', 'fp16']
<add> )
<add>
<ide>
<ide> if __name__ == '__main__':
<ide> tf.test.main()
<ide><path>official/resnet/resnet_run_loop.py
<ide>
<ide> import os
<ide>
<add># pylint: disable=g-bad-import-order
<ide> from absl import flags
<del>import tensorflow as tf # pylint: disable=g-bad-import-order
<add>import tensorflow as tf
<ide>
<ide> from official.resnet import resnet_model
<ide> from official.utils.flags import core as flags_core
<ide> from official.utils.export import export
<ide> from official.utils.logs import hooks_helper
<ide> from official.utils.logs import logger
<ide> from official.utils.misc import model_helpers
<add># pylint: enable=g-bad-import-order
<ide>
<ide>
<ide> ################################################################################
<ide> def define_resnet_flags(resnet_size_choices=None):
<ide> help=flags_core.help_wrap(
<ide> 'Version of ResNet. (1 or 2) See README.md for details.'))
<ide>
<del>
<ide> choice_kwargs = dict(
<ide> name='resnet_size', short_name='rs', default='50',
<ide> help=flags_core.help_wrap('The size of the ResNet model to use.'))
<ide> def define_resnet_flags(resnet_size_choices=None):
<ide> flags.DEFINE_string(**choice_kwargs)
<ide> else:
<ide> flags.DEFINE_enum(enum_values=resnet_size_choices, **choice_kwargs)
<add>
<add> # The current implementation of ResNet v1 is numerically unstable when run
<add> # with fp16 and will produce NaN errors soon after training begins.
<add> msg = ('ResNet version 1 is not currently supported with fp16. '
<add> 'Please use version 2 instead.')
<add> @flags.multi_flags_validator(['dtype', 'resnet_version'], message=msg)
<add> def _forbid_v1_fp16(flag_values): # pylint: disable=unused-variable
<add> return (flags_core.DTYPE_MAP[flag_values['dtype']][0] != tf.float16 or
<add> flag_values['resnet_version'] != '1')
<ide><path>official/utils/flags/core.py
<ide> def core_fn(*args, **kwargs):
<ide> get_num_gpus = _base.get_num_gpus
<ide> get_tf_dtype = _performance.get_tf_dtype
<ide> get_loss_scale = _performance.get_loss_scale
<add>DTYPE_MAP = _performance.DTYPE_MAP | 4 |
Javascript | Javascript | remove self.isiinitialized check | 3f87bb809dedba617489e85482615ba79cdcc3c2 | <ide><path>packages/ember-application/lib/system/application.js
<ide> var Application = Ember.Application = Ember.Namespace.extend({
<ide> @method scheduleInitialize
<ide> */
<ide> scheduleInitialize: function() {
<add> var self = this;
<add>
<add> function initialize(){
<add> if (self.isDestroyed) { return; }
<add> Ember.run.schedule('actions', self, 'initialize');
<add> }
<add>
<ide> if (!this.$ || this.$.isReady) {
<del> Ember.run.schedule('actions', this, 'initialize');
<add> initialize();
<ide> } else {
<del> var self = this;
<del> this.$().ready(function() {
<del> if (self.isDestroyed || self.isInitialized) { return; }
<del> Ember.run(self, 'initialize');
<del> });
<add> this.$().ready(initialize);
<ide> }
<ide> },
<ide>
<ide> var Application = Ember.Application = Ember.Namespace.extend({
<ide>
<ide> this.isInitialized = false;
<ide>
<del> Em.run.schedule('actions', this, function(){
<add> Ember.run.schedule('actions', this, function(){
<ide> this.initialize();
<ide> this.startRouting();
<ide> });
<ide><path>packages/ember-application/tests/system/readiness_test.js
<ide> test("Ember.Application's ready event is called after the document becomes ready
<ide> test("Ember.Application's ready event can be deferred by other components", function() {
<ide> Ember.run(function() {
<ide> application = Application.create({ router: false });
<del> });
<del>
<del> application.deferReadiness();
<del>
<del> Ember.run(function() {
<del> application.initialize();
<add> application.deferReadiness();
<ide> });
<ide>
<ide> equal(readyWasCalled, 0, "ready wasn't called yet");
<ide> test("Ember.Application's ready event can be deferred by other components", func
<ide>
<ide> Ember.run(function() {
<ide> application = Application.create({ router: false });
<add> application.deferReadiness();
<ide> });
<ide>
<del> application.deferReadiness();
<del>
<ide> Ember.run(function() {
<ide> domReady();
<ide> }); | 2 |
PHP | PHP | add pipeline test | d51029a0870e874eff69ad91a5e36dc4d4595a44 | <ide><path>tests/Pipeline/PipelineTest.php
<ide> public function testPipelineUsageWithParameters()
<ide>
<ide> unset($_SERVER['__test.pipe.parameters']);
<ide> }
<add>
<add> public function testPipelineViaChangesTheMethodBeingCalledOnThePipes()
<add> {
<add> $pipelineInstance = new Pipeline(new Illuminate\Container\Container);
<add> $result = $pipelineInstance->send('data')
<add> ->through('PipelineTestPipeOne')
<add> ->via('differentMethod')
<add> ->then(function ($piped) {
<add> return $piped;
<add> });
<add> $this->assertEquals('data', $result);
<add> }
<ide> }
<ide>
<ide> class PipelineTestPipeOne
<ide> public function handle($piped, $next)
<ide>
<ide> return $next($piped);
<ide> }
<add>
<add> public function differentMethod($piped, $next)
<add> {
<add> return $next($piped);
<add> }
<ide> }
<ide>
<ide> class PipelineTestParameterPipe | 1 |
Go | Go | add test coverage to pkg/parsers | b81472a6d861b335d968a1e970d9aebc314530f2 | <ide><path>pkg/parsers/filters/parse_test.go
<ide> func TestParseArgs(t *testing.T) {
<ide> }
<ide> }
<ide>
<del>func TestParam(t *testing.T) {
<add>func TestParseArgsEdgeCase(t *testing.T) {
<add> var filters Args
<add> args, err := ParseFlag("", filters)
<add> if err != nil {
<add> t.Fatal(err)
<add> }
<add> if args == nil || len(args) != 0 {
<add> t.Fatalf("Expected an empty Args (map), got %v", args)
<add> }
<add> if args, err = ParseFlag("anything", args); err == nil || err != ErrorBadFormat {
<add> t.Fatalf("Expected ErrorBadFormat, got %v", err)
<add> }
<add>}
<add>
<add>func TestToParam(t *testing.T) {
<ide> a := Args{
<ide> "created": []string{"today"},
<ide> "image.name": []string{"ubuntu*", "*untu"},
<ide> }
<ide>
<del> v, err := ToParam(a)
<add> _, err := ToParam(a)
<ide> if err != nil {
<ide> t.Errorf("failed to marshal the filters: %s", err)
<ide> }
<del> v1, err := FromParam(v)
<del> if err != nil {
<del> t.Errorf("%s", err)
<add>}
<add>
<add>func TestFromParam(t *testing.T) {
<add> invalids := []string{
<add> "anything",
<add> "['a','list']",
<add> "{'key': 'value'}",
<add> `{"key": "value"}`,
<ide> }
<del> for key, vals := range v1 {
<del> if _, ok := a[key]; !ok {
<del> t.Errorf("could not find key %s in original set", key)
<add> valids := map[string]Args{
<add> `{"key": ["value"]}`: {
<add> "key": {"value"},
<add> },
<add> `{"key": ["value1", "value2"]}`: {
<add> "key": {"value1", "value2"},
<add> },
<add> `{"key1": ["value1"], "key2": ["value2"]}`: {
<add> "key1": {"value1"},
<add> "key2": {"value2"},
<add> },
<add> }
<add> for _, invalid := range invalids {
<add> if _, err := FromParam(invalid); err == nil {
<add> t.Fatalf("Expected an error with %v, got nothing", invalid)
<ide> }
<del> sort.Strings(vals)
<del> sort.Strings(a[key])
<del> if len(vals) != len(a[key]) {
<del> t.Errorf("value lengths ought to match")
<del> continue
<add> }
<add> for json, expectedArgs := range valids {
<add> args, err := FromParam(json)
<add> if err != nil {
<add> t.Fatal(err)
<add> }
<add> if len(args) != len(expectedArgs) {
<add> t.Fatalf("Expected %v, go %v", expectedArgs, args)
<ide> }
<del> for i := range vals {
<del> if vals[i] != a[key][i] {
<del> t.Errorf("expected %s, but got %s", a[key][i], vals[i])
<add> for key, expectedValues := range expectedArgs {
<add> values := args[key]
<add> sort.Strings(values)
<add> sort.Strings(expectedValues)
<add> if len(values) != len(expectedValues) {
<add> t.Fatalf("Expected %v, go %v", expectedArgs, args)
<add> }
<add> for index, expectedValue := range expectedValues {
<add> if values[index] != expectedValue {
<add> t.Fatalf("Expected %v, go %v", expectedArgs, args)
<add> }
<ide> }
<ide> }
<ide> }
<ide> func TestEmpty(t *testing.T) {
<ide> t.Errorf("these should both be empty sets")
<ide> }
<ide> }
<add>
<add>func TestArgsMatchKVList(t *testing.T) {
<add> // empty sources
<add> args := Args{
<add> "created": []string{"today"},
<add> }
<add> if args.MatchKVList("created", map[string]string{}) {
<add> t.Fatalf("Expected false for (%v,created), got true", args)
<add> }
<add> // Not empty sources
<add> sources := map[string]string{
<add> "key1": "value1",
<add> "key2": "value2",
<add> "key3": "value3",
<add> }
<add> matches := map[*Args]string{
<add> &Args{}: "field",
<add> &Args{
<add> "created": []string{"today"},
<add> "labels": []string{"key1"},
<add> }: "labels",
<add> &Args{
<add> "created": []string{"today"},
<add> "labels": []string{"key1=value1"},
<add> }: "labels",
<add> }
<add> differs := map[*Args]string{
<add> &Args{
<add> "created": []string{"today"},
<add> }: "created",
<add> &Args{
<add> "created": []string{"today"},
<add> "labels": []string{"key4"},
<add> }: "labels",
<add> &Args{
<add> "created": []string{"today"},
<add> "labels": []string{"key1=value3"},
<add> }: "labels",
<add> }
<add> for args, field := range matches {
<add> if args.MatchKVList(field, sources) != true {
<add> t.Fatalf("Expected true for %v on %v, got false", sources, args)
<add> }
<add> }
<add> for args, field := range differs {
<add> if args.MatchKVList(field, sources) != false {
<add> t.Fatalf("Expected false for %v on %v, got true", sources, args)
<add> }
<add> }
<add>}
<add>
<add>func TestArgsMatch(t *testing.T) {
<add> source := "today"
<add> matches := map[*Args]string{
<add> &Args{}: "field",
<add> &Args{
<add> "created": []string{"today"},
<add> "labels": []string{"key1"},
<add> }: "today",
<add> &Args{
<add> "created": []string{"to*"},
<add> }: "created",
<add> &Args{
<add> "created": []string{"to(.*)"},
<add> }: "created",
<add> &Args{
<add> "created": []string{"tod"},
<add> }: "created",
<add> &Args{
<add> "created": []string{"anything", "to*"},
<add> }: "created",
<add> }
<add> differs := map[*Args]string{
<add> &Args{
<add> "created": []string{"tomorrow"},
<add> }: "created",
<add> &Args{
<add> "created": []string{"to(day"},
<add> }: "created",
<add> &Args{
<add> "created": []string{"tom(.*)"},
<add> }: "created",
<add> &Args{
<add> "created": []string{"today1"},
<add> "labels": []string{"today"},
<add> }: "created",
<add> }
<add> for args, field := range matches {
<add> if args.Match(field, source) != true {
<add> t.Fatalf("Expected true for %v on %v, got false", source, args)
<add> }
<add> }
<add> for args, field := range differs {
<add> if args.Match(field, source) != false {
<add> t.Fatalf("Expected false for %v on %v, got true", source, args)
<add> }
<add> }
<add>}
<ide><path>pkg/parsers/kernel/kernel_test.go
<ide> package kernel
<ide>
<ide> import (
<add> "fmt"
<ide> "testing"
<ide> )
<ide>
<ide> func assertParseRelease(t *testing.T, release string, b *KernelVersionInfo, resu
<ide> a, _ = ParseRelease(release)
<ide>
<ide> if r := CompareKernelVersion(a, b); r != result {
<del> t.Fatalf("Unexpected kernel version comparison result. Found %d, expected %d", r, result)
<add> t.Fatalf("Unexpected kernel version comparison result for (%v,%v). Found %d, expected %d", release, b, r, result)
<ide> }
<ide> if a.Flavor != b.Flavor {
<ide> t.Fatalf("Unexpected parsed kernel flavor. Found %s, expected %s", a.Flavor, b.Flavor)
<ide> func TestParseRelease(t *testing.T) {
<ide> assertParseRelease(t, "3.8.0-19-generic", &KernelVersionInfo{Kernel: 3, Major: 8, Minor: 0, Flavor: "-19-generic"}, 0)
<ide> assertParseRelease(t, "3.12.8tag", &KernelVersionInfo{Kernel: 3, Major: 12, Minor: 8, Flavor: "tag"}, 0)
<ide> assertParseRelease(t, "3.12-1-amd64", &KernelVersionInfo{Kernel: 3, Major: 12, Minor: 0, Flavor: "-1-amd64"}, 0)
<add> assertParseRelease(t, "3.8.0", &KernelVersionInfo{Kernel: 4, Major: 8, Minor: 0}, -1)
<add> // Errors
<add> invalids := []string{
<add> "3",
<add> "a",
<add> "a.a",
<add> "a.a.a-a",
<add> }
<add> for _, invalid := range invalids {
<add> expectedMessage := fmt.Sprintf("Can't parse kernel version %v", invalid)
<add> if _, err := ParseRelease(invalid); err == nil || err.Error() != expectedMessage {
<add>
<add> }
<add> }
<ide> }
<ide>
<ide> func assertKernelVersion(t *testing.T, a, b *KernelVersionInfo, result int) {
<ide> func TestCompareKernelVersion(t *testing.T) {
<ide> &KernelVersionInfo{Kernel: 3, Major: 0, Minor: 20},
<ide> &KernelVersionInfo{Kernel: 3, Major: 8, Minor: 0},
<ide> -1)
<add> assertKernelVersion(t,
<add> &KernelVersionInfo{Kernel: 3, Major: 7, Minor: 20},
<add> &KernelVersionInfo{Kernel: 3, Major: 8, Minor: 0},
<add> -1)
<add> assertKernelVersion(t,
<add> &KernelVersionInfo{Kernel: 3, Major: 8, Minor: 20},
<add> &KernelVersionInfo{Kernel: 3, Major: 7, Minor: 0},
<add> 1)
<add> assertKernelVersion(t,
<add> &KernelVersionInfo{Kernel: 3, Major: 8, Minor: 20},
<add> &KernelVersionInfo{Kernel: 3, Major: 8, Minor: 0},
<add> 1)
<add> assertKernelVersion(t,
<add> &KernelVersionInfo{Kernel: 3, Major: 8, Minor: 0},
<add> &KernelVersionInfo{Kernel: 3, Major: 8, Minor: 20},
<add> -1)
<ide> }
<ide><path>pkg/parsers/parsers_test.go
<ide> func TestParseHost(t *testing.T) {
<ide> defaultHttpHost = "127.0.0.1"
<ide> defaultUnix = "/var/run/docker.sock"
<ide> )
<del> if addr, err := ParseHost(defaultHttpHost, defaultUnix, "0.0.0.0"); err == nil {
<del> t.Errorf("tcp 0.0.0.0 address expected error return, but err == nil, got %s", addr)
<add> invalids := map[string]string{
<add> "0.0.0.0": "Invalid bind address format: 0.0.0.0",
<add> "tcp://": "Invalid proto, expected tcp: ",
<add> "tcp:a.b.c.d": "Invalid bind address format: tcp:a.b.c.d",
<add> "udp://127.0.0.1": "Invalid bind address format: udp://127.0.0.1",
<add> "udp://127.0.0.1:2375": "Invalid bind address format: udp://127.0.0.1:2375",
<add> }
<add> valids := map[string]string{
<add> "0.0.0.1:5555": "tcp://0.0.0.1:5555",
<add> ":6666": "tcp://127.0.0.1:6666",
<add> "tcp://:7777": "tcp://127.0.0.1:7777",
<add> "": "unix:///var/run/docker.sock",
<add> "unix:///run/docker.sock": "unix:///run/docker.sock",
<add> "unix://": "unix:///var/run/docker.sock",
<add> "fd://": "fd://",
<add> "fd://something": "fd://something",
<add> }
<add> for invalidAddr, expectedError := range invalids {
<add> if addr, err := ParseHost(defaultHttpHost, defaultUnix, invalidAddr); err == nil || err.Error() != expectedError {
<add> t.Errorf("tcp %v address expected error %v return, got %s and addr %v", invalidAddr, expectedError, err, addr)
<add> }
<add> }
<add> for validAddr, expectedAddr := range valids {
<add> if addr, err := ParseHost(defaultHttpHost, defaultUnix, validAddr); err != nil || addr != expectedAddr {
<add> t.Errorf("%v -> expected %v, got %v", validAddr, expectedAddr, addr)
<add> }
<ide> }
<del> if addr, err := ParseHost(defaultHttpHost, defaultUnix, "tcp://"); err == nil {
<del> t.Errorf("default tcp:// address expected error return, but err == nil, got %s", addr)
<del> }
<del> if addr, err := ParseHost(defaultHttpHost, defaultUnix, "0.0.0.1:5555"); err != nil || addr != "tcp://0.0.0.1:5555" {
<del> t.Errorf("0.0.0.1:5555 -> expected tcp://0.0.0.1:5555, got %s", addr)
<del> }
<del> if addr, err := ParseHost(defaultHttpHost, defaultUnix, ":6666"); err != nil || addr != "tcp://127.0.0.1:6666" {
<del> t.Errorf(":6666 -> expected tcp://127.0.0.1:6666, got %s", addr)
<del> }
<del> if addr, err := ParseHost(defaultHttpHost, defaultUnix, "tcp://:7777"); err != nil || addr != "tcp://127.0.0.1:7777" {
<del> t.Errorf("tcp://:7777 -> expected tcp://127.0.0.1:7777, got %s", addr)
<del> }
<del> if addr, err := ParseHost(defaultHttpHost, defaultUnix, ""); err != nil || addr != "unix:///var/run/docker.sock" {
<del> t.Errorf("empty argument -> expected unix:///var/run/docker.sock, got %s", addr)
<del> }
<del> if addr, err := ParseHost(defaultHttpHost, defaultUnix, "unix:///var/run/docker.sock"); err != nil || addr != "unix:///var/run/docker.sock" {
<del> t.Errorf("unix:///var/run/docker.sock -> expected unix:///var/run/docker.sock, got %s", addr)
<del> }
<del> if addr, err := ParseHost(defaultHttpHost, defaultUnix, "unix://"); err != nil || addr != "unix:///var/run/docker.sock" {
<del> t.Errorf("unix:///var/run/docker.sock -> expected unix:///var/run/docker.sock, got %s", addr)
<del> }
<del> if addr, err := ParseHost(defaultHttpHost, defaultUnix, "udp://127.0.0.1"); err == nil {
<del> t.Errorf("udp protocol address expected error return, but err == nil. Got %s", addr)
<del> }
<del> if addr, err := ParseHost(defaultHttpHost, defaultUnix, "udp://127.0.0.1:2375"); err == nil {
<del> t.Errorf("udp protocol address expected error return, but err == nil. Got %s", addr)
<add>}
<add>
<add>func TestParseInvalidUnixAddrInvalid(t *testing.T) {
<add> if _, err := ParseUnixAddr("unix://tcp://127.0.0.1", "unix:///var/run/docker.sock"); err == nil || err.Error() != "Invalid proto, expected unix: tcp://127.0.0.1" {
<add> t.Fatalf("Expected an error, got %v", err)
<ide> }
<ide> }
<ide>
<ide> func TestParseRepositoryTag(t *testing.T) {
<ide> }
<ide>
<ide> func TestParsePortMapping(t *testing.T) {
<add> if _, err := PartParser("ip:public:private", "192.168.1.1:80"); err == nil {
<add> t.Fatalf("Expected an error, got %v", err)
<add> }
<ide> data, err := PartParser("ip:public:private", "192.168.1.1:80:8080")
<ide> if err != nil {
<ide> t.Fatal(err)
<ide> func TestParsePortMapping(t *testing.T) {
<ide> }
<ide> }
<ide>
<add>func TestParseKeyValueOpt(t *testing.T) {
<add> invalids := map[string]string{
<add> "": "Unable to parse key/value option: ",
<add> "key": "Unable to parse key/value option: key",
<add> }
<add> for invalid, expectedError := range invalids {
<add> if _, _, err := ParseKeyValueOpt(invalid); err == nil || err.Error() != expectedError {
<add> t.Fatalf("Expected error %v for %v, got %v", expectedError, invalid, err)
<add> }
<add> }
<add> valids := map[string][]string{
<add> "key=value": {"key", "value"},
<add> " key = value ": {"key", "value"},
<add> "key=value1=value2": {"key", "value1=value2"},
<add> " key = value1 = value2 ": {"key", "value1 = value2"},
<add> }
<add> for valid, expectedKeyValue := range valids {
<add> key, value, err := ParseKeyValueOpt(valid)
<add> if err != nil {
<add> t.Fatal(err)
<add> }
<add> if key != expectedKeyValue[0] || value != expectedKeyValue[1] {
<add> t.Fatalf("Expected {%v: %v} got {%v: %v}", expectedKeyValue[0], expectedKeyValue[1], key, value)
<add> }
<add> }
<add>}
<add>
<ide> func TestParsePortRange(t *testing.T) {
<ide> if start, end, err := ParsePortRange("8000-8080"); err != nil || start != 8000 || end != 8080 {
<ide> t.Fatalf("Error: %s or Expecting {start,end} values {8000,8080} but found {%d,%d}.", err, start, end)
<ide> }
<ide> }
<ide>
<add>func TestParsePortRangeEmpty(t *testing.T) {
<add> if _, _, err := ParsePortRange(""); err == nil || err.Error() != "Empty string specified for ports." {
<add> t.Fatalf("Expected error 'Empty string specified for ports.', got %v", err)
<add> }
<add>}
<add>
<add>func TestParsePortRangeWithNoRange(t *testing.T) {
<add> start, end, err := ParsePortRange("8080")
<add> if err != nil {
<add> t.Fatal(err)
<add> }
<add> if start != 8080 || end != 8080 {
<add> t.Fatalf("Expected start and end to be the same and equal to 8080, but were %v and %v", start, end)
<add> }
<add>}
<add>
<ide> func TestParsePortRangeIncorrectRange(t *testing.T) {
<ide> if _, _, err := ParsePortRange("9000-8080"); err == nil || !strings.Contains(err.Error(), "Invalid range specified for the Port") {
<ide> t.Fatalf("Expecting error 'Invalid range specified for the Port' but received %s.", err) | 3 |
Javascript | Javascript | add hide threshold to subs-caps button | 88ee6af4310c93e73950a2b0fd8c105678bda338 | <ide><path>src/js/control-bar/text-track-controls/subs-caps-button.js
<ide> class SubsCapsButton extends TextTrackButton {
<ide> return `vjs-subs-caps-button ${super.buildWrapperCSSClass()}`;
<ide> }
<ide>
<del> /**
<del> * Update caption menu items
<del> *
<del> * @param {EventTarget~Event} [event]
<del> * The `addtrack` or `removetrack` event that caused this function to be
<del> * called.
<del> *
<del> * @listens TextTrackList#addtrack
<del> * @listens TextTrackList#removetrack
<del> */
<del> update(event) {
<del> let threshold = 2;
<del>
<del> super.update();
<del>
<del> // if native, then threshold is 1 because no settings button
<del> if (this.player().tech_ && this.player().tech_.featuresNativeTextTracks) {
<del> threshold = 1;
<del> }
<del>
<del> if (this.items && this.items.length > threshold) {
<del> this.show();
<del> } else {
<del> this.hide();
<del> }
<del> }
<del>
<ide> /**
<ide> * Create caption/subtitles menu items
<ide> *
<ide> class SubsCapsButton extends TextTrackButton {
<ide>
<ide> if (!(this.player().tech_ && this.player().tech_.featuresNativeTextTracks)) {
<ide> items.push(new CaptionSettingsMenuItem(this.player_, {kind: this.label_}));
<add>
<add> this.hideThreshold_ += 1;
<ide> }
<ide>
<ide> items = super.createItems(items, SubsCapsMenuItem); | 1 |
Text | Text | remove guide specific checklist points | dfe2d9136098177dbeded4ea51f46e5a4c3cdd1e | <ide><path>.github/PULL_REQUEST_TEMPLATE.md
<add>Checklist:
<add>
<ide> <!-- Please follow this checklist and put an x in each of the boxes, like this: [x]. It will ensure that our team takes your pull request seriously. -->
<ide>
<ide> - [ ] I have read [freeCodeCamp's contribution guidelines](https://github.com/freeCodeCamp/freeCodeCamp/blob/master/CONTRIBUTING.md).
<ide> - [ ] My pull request has a descriptive title (not a vague title like `Update index.md`)
<ide> - [ ] My pull request targets the `master` branch of freeCodeCamp.
<del>- [ ] None of my changes are plagiarized from another source without proper attribution.
<del>- [ ] All the files I changed are in the same world language (for example: only English changes, or only Chinese changes, etc.)
<del>- [ ] My changes do not use shortened URLs or affiliate links.
<add>- [ ] All the files I changed are in the same world language, for example: only English changes, or only Chinese changes, etc.
<ide>
<ide> <!--If your pull request closes a GitHub issue, replace the XXXXX below with the issue number.-->
<ide>
<ide> Closes #XXXXX
<add>
<add><!-- Feel free to add any addtional description of changes below this line --> | 1 |
Mixed | Python | add words to portuguese language _num_words | fe515085f332d100b6c2c2c8a08bb7fe14e856f4 | <ide><path>.github/contributors/filipecaixeta.md
<add># spaCy contributor agreement
<add>
<add>This spaCy Contributor Agreement (**"SCA"**) is based on the
<add>[Oracle Contributor Agreement](http://www.oracle.com/technetwork/oca-405177.pdf).
<add>The SCA applies to any contribution that you make to any product or project
<add>managed by us (the **"project"**), and sets out the intellectual property rights
<add>you grant to us in the contributed materials. The term **"us"** shall mean
<add>[ExplosionAI UG (haftungsbeschränkt)](https://explosion.ai/legal). The term
<add>**"you"** shall mean the person or entity identified below.
<add>
<add>If you agree to be bound by these terms, fill in the information requested
<add>below and include the filled-in version with your first pull request, under the
<add>folder [`.github/contributors/`](/.github/contributors/). The name of the file
<add>should be your GitHub username, with the extension `.md`. For example, the user
<add>example_user would create the file `.github/contributors/example_user.md`.
<add>
<add>Read this agreement carefully before signing. These terms and conditions
<add>constitute a binding legal agreement.
<add>
<add>## Contributor Agreement
<add>
<add>1. The term "contribution" or "contributed materials" means any source code,
<add>object code, patch, tool, sample, graphic, specification, manual,
<add>documentation, or any other material posted or submitted by you to the project.
<add>
<add>2. With respect to any worldwide copyrights, or copyright applications and
<add>registrations, in your contribution:
<add>
<add> * you hereby assign to us joint ownership, and to the extent that such
<add> assignment is or becomes invalid, ineffective or unenforceable, you hereby
<add> grant to us a perpetual, irrevocable, non-exclusive, worldwide, no-charge,
<add> royalty-free, unrestricted license to exercise all rights under those
<add> copyrights. This includes, at our option, the right to sublicense these same
<add> rights to third parties through multiple levels of sublicensees or other
<add> licensing arrangements;
<add>
<add> * you agree that each of us can do all things in relation to your
<add> contribution as if each of us were the sole owners, and if one of us makes
<add> a derivative work of your contribution, the one who makes the derivative
<add> work (or has it made will be the sole owner of that derivative work;
<add>
<add> * you agree that you will not assert any moral rights in your contribution
<add> against us, our licensees or transferees;
<add>
<add> * you agree that we may register a copyright in your contribution and
<add> exercise all ownership rights associated with it; and
<add>
<add> * you agree that neither of us has any duty to consult with, obtain the
<add> consent of, pay or render an accounting to the other for any use or
<add> distribution of your contribution.
<add>
<add>3. With respect to any patents you own, or that you can license without payment
<add>to any third party, you hereby grant to us a perpetual, irrevocable,
<add>non-exclusive, worldwide, no-charge, royalty-free license to:
<add>
<add> * make, have made, use, sell, offer to sell, import, and otherwise transfer
<add> your contribution in whole or in part, alone or in combination with or
<add> included in any product, work or materials arising out of the project to
<add> which your contribution was submitted, and
<add>
<add> * at our option, to sublicense these same rights to third parties through
<add> multiple levels of sublicensees or other licensing arrangements.
<add>
<add>4. Except as set out above, you keep all right, title, and interest in your
<add>contribution. The rights that you grant to us under these terms are effective
<add>on the date you first submitted a contribution to us, even if your submission
<add>took place before the date you sign these terms.
<add>
<add>5. You covenant, represent, warrant and agree that:
<add>
<add> * Each contribution that you submit is and shall be an original work of
<add> authorship and you can legally grant the rights set out in this SCA;
<add>
<add> * to the best of your knowledge, each contribution will not violate any
<add> third party's copyrights, trademarks, patents, or other intellectual
<add> property rights; and
<add>
<add> * each contribution shall be in compliance with U.S. export control laws and
<add> other applicable export and import laws. You agree to notify us if you
<add> become aware of any circumstance which would make any of the foregoing
<add> representations inaccurate in any respect. We may publicly disclose your
<add> participation in the project, including the fact that you have signed the SCA.
<add>
<add>6. This SCA is governed by the laws of the State of California and applicable
<add>U.S. Federal law. Any choice of law rules will not apply.
<add>
<add>7. Please place an “x” on one of the applicable statement below. Please do NOT
<add>mark both statements:
<add>
<add> * [x] I am signing on behalf of myself as an individual and no other person
<add> or entity, including my employer, has or will have rights with respect to my
<add> contributions.
<add>
<add> * [ ] I am signing on behalf of my employer or a legal entity and I have the
<add> actual authority to contractually bind that entity.
<add>
<add>## Contributor Details
<add>
<add>| Field | Entry |
<add>|------------------------------- | -------------------- |
<add>| Name | Filipe Caixeta |
<add>| Company name (if applicable) | |
<add>| Title or role (if applicable) | |
<add>| Date | 09.12.2018 |
<add>| GitHub username | filipecaixeta |
<add>| Website (optional) | filipecaixeta.com.br |
<ide><path>spacy/lang/pt/lex_attrs.py
<ide> from ...attrs import LIKE_NUM
<ide>
<ide>
<del>_num_words = ['zero', 'um', 'dois', 'três', 'quatro', 'cinco', 'seis', 'sete',
<del> 'oito', 'nove', 'dez', 'onze', 'doze', 'treze', 'catorze',
<del> 'quinze', 'dezesseis', 'dezasseis', 'dezessete', 'dezassete', 'dezoito', 'dezenove', 'dezanove', 'vinte',
<del> 'trinta', 'quarenta', 'cinquenta', 'sessenta', 'setenta',
<del> 'oitenta', 'noventa', 'cem', 'mil', 'milhão', 'bilhão', 'bilião', 'trilhão', 'trilião',
<del> 'quatrilhão']
<add>_num_words = ['zero', 'um', 'dois', 'três', 'tres', 'quatro', 'cinco', 'seis', 'sete', 'oito', 'nove', 'dez',
<add> 'onze', 'doze', 'dúzia', 'dúzias', 'duzia', 'duzias', 'treze', 'catorze', 'quinze', 'dezasseis',
<add> 'dezassete', 'dezoito', 'dezanove', 'vinte', 'trinta', 'quarenta', 'cinquenta', 'sessenta',
<add> 'setenta', 'oitenta', 'noventa', 'cem', 'cento', 'duzentos', 'trezentos', 'quatrocentos',
<add> 'quinhentos', 'seicentos', 'setecentos', 'oitocentos', 'novecentos', 'mil', 'milhão', 'milhao',
<add> 'milhões', 'milhoes', 'bilhão', 'bilhao', 'bilhões', 'bilhoes', 'trilhão', 'trilhao', 'trilhões',
<add> 'trilhoes', 'quadrilhão', 'quadrilhao', 'quadrilhões', 'quadrilhoes']
<add>
<ide>
<ide> _ordinal_words = ['primeiro', 'segundo', 'terceiro', 'quarto', 'quinto', 'sexto',
<ide> 'sétimo', 'oitavo', 'nono', 'décimo', 'vigésimo', 'trigésimo', | 2 |
Text | Text | convert celsius to fahrenheit - portuguese | 46df633b74a7c89782e6e894bdd1432b43c9d15a | <ide><path>curriculum/challenges/portuguese/02-javascript-algorithms-and-data-structures/basic-algorithm-scripting/convert-celsius-to-fahrenheit.portuguese.md
<ide> convertToF(30);
<ide> <section id='solution'>
<ide>
<ide> ```js
<del>// solution required
<add>function convertToF(celsius) {
<add> return (celsius * (9 / 5)) + 32;
<add>}
<add>
<add>convertToF(30);
<ide> ```
<ide> </section> | 1 |
PHP | PHP | fix whitespace errors | 6672eafe539ef36c9ff33147ad37ca616a23e6a1 | <ide><path>lib/Cake/Console/Shell.php
<ide> public function createFile($path, $contents) {
<ide> $this->out(__d('cake_console', '<success>Wrote</success> `%s`', $path));
<ide> return true;
<ide> }
<del>
<add>
<ide> $this->err(__d('cake_console', '<error>Could not write to `%s`</error>.', $path), 2);
<ide> return false;
<ide> }
<ide><path>lib/Cake/Console/ShellDispatcher.php
<ide> class ShellDispatcher {
<ide> public function __construct($args = array(), $bootstrap = true) {
<ide> set_time_limit(0);
<ide> $this->parseParams($args);
<del>
<add>
<ide> if ($bootstrap) {
<ide> $this->_initConstants();
<ide> $this->_initEnvironment(); | 2 |
Javascript | Javascript | relocate needspinner calls | 5b636feaa8550ca39229e7d8805c73c72f7995dc | <ide><path>src/node.js
<ide> } else {
<ide> nextTickQueue.splice(0, infoBox[index]);
<ide> infoBox[length] = nextTickQueue.length;
<del> if (needSpinner) {
<del> _needTickCallback();
<del> needSpinner = false;
<del> }
<ide> }
<ide> }
<add> if (needSpinner) {
<add> _needTickCallback();
<add> needSpinner = false;
<add> }
<ide> inTick = false;
<ide> infoBox[index] = 0;
<ide> infoBox[depth] = tickDepth_;
<ide>
<ide> nextTickQueue.push(obj);
<ide> infoBox[length]++;
<del>
<del> if (needSpinner) {
<del> _needTickCallback();
<del> needSpinner = false;
<del> }
<ide> }
<ide>
<ide> function _nextDomainTick(callback) {
<ide>
<ide> nextTickQueue.push(obj);
<ide> infoBox[length]++;
<del>
<del> if (needSpinner) {
<del> _needTickCallback();
<del> needSpinner = false;
<del> }
<ide> }
<ide> };
<ide> | 1 |
Ruby | Ruby | add tests and fix type signature | e13dc902df8fdabfde7f50c1a2a3d772e77d6c5e | <ide><path>Library/Homebrew/dev-cmd/release-notes.rb
<ide> def release_notes_args
<ide> def release_notes
<ide> args = release_notes_args.parse
<ide>
<add> # TODO: (2.8) Deprecate this command now that the `brew release` command exists.
<add> # odeprecated "`brew release-notes`"
<add>
<ide> previous_tag = args.named.first
<ide>
<ide> if previous_tag.present?
<ide> def release_notes
<ide> odie "Ref #{ref} does not exist!"
<ide> end
<ide>
<del> release_notes = ReleaseNotes.generate_release_notes previous_tag, end_ref, markdown: T.must(args.markdown?)
<add> release_notes = ReleaseNotes.generate_release_notes previous_tag, end_ref, markdown: args.markdown?
<ide>
<ide> $stderr.puts "Release notes between #{previous_tag} and #{end_ref}:"
<ide> puts release_notes
<ide><path>Library/Homebrew/release_notes.rb
<ide> module ReleaseNotes
<ide> module_function
<ide>
<ide> sig {
<del> params(start_ref: T.any(String, Version), end_ref: T.any(String, Version), markdown: T::Boolean)
<add> params(start_ref: T.any(String, Version), end_ref: T.any(String, Version), markdown: T.nilable(T::Boolean))
<ide> .returns(String)
<ide> }
<ide> def generate_release_notes(start_ref, end_ref, markdown: false)
<ide><path>Library/Homebrew/test/dev-cmd/release_spec.rb
<add># typed: false
<add># frozen_string_literal: true
<add>
<add>require "cmd/shared_examples/args_parse"
<add>
<add>describe "Homebrew.release_args" do
<add> it_behaves_like "parseable arguments"
<add>end
<ide><path>Library/Homebrew/test/release_notes_spec.rb
<add># typed: false
<add># frozen_string_literal: true
<add>
<add>require "release_notes"
<add>
<add>describe ReleaseNotes do
<add> before do
<add> HOMEBREW_REPOSITORY.cd do
<add> system "git", "init"
<add> system "git", "commit", "--allow-empty", "-m", "Initial commit"
<add> system "git", "tag", "release-notes-testing"
<add> system "git", "commit", "--allow-empty", "-m", "Merge pull request #1 from Homebrew/fix", "-m", "Do something"
<add> system "git", "commit", "--allow-empty", "-m", "make a change"
<add> system "git", "commit", "--allow-empty", "-m", "Merge pull request #2 from User/fix", "-m", "Do something else"
<add> end
<add> end
<add>
<add> describe ".generate_release_notes" do
<add> it "generates release notes" do
<add> expect(described_class.generate_release_notes("release-notes-testing", "HEAD")).to eq <<~NOTES
<add> https://github.com/Homebrew/brew/pull/2 (@User) - Do something else
<add> https://github.com/Homebrew/brew/pull/1 (@Homebrew) - Do something
<add> NOTES
<add> end
<add>
<add> it "generates markdown release notes" do
<add> expect(described_class.generate_release_notes("release-notes-testing", "HEAD", markdown: true)).to eq <<~NOTES
<add> - [Do something else](https://github.com/Homebrew/brew/pull/2) (@User)
<add> - [Do something](https://github.com/Homebrew/brew/pull/1) (@Homebrew)
<add> NOTES
<add> end
<add> end
<add>end | 4 |
PHP | PHP | add ftp adapter to filesystem config | 9534ded88310ed9335fd088d639e69b517a7b5be | <ide><path>config/filesystems.php
<ide> | by the framework. A "local" driver, as well as a variety of cloud
<ide> | based drivers are available for your choosing. Just store away!
<ide> |
<del> | Supported: "local", "s3", "rackspace"
<add> | Supported: "local", "ftp", "s3", "rackspace"
<ide> |
<ide> */
<ide>
<ide> 'root' => storage_path().'/app',
<ide> ],
<ide>
<add> 'ftp' => [
<add> 'driver' => 'ftp',
<add> 'host' => 'ftp.example.com',
<add> 'username' => 'your-username',
<add> 'password' => 'your-password',
<add>
<add> // Optional config settings
<add> // 'port' => 21,
<add> // 'root' => '',
<add> // 'passive' => true,
<add> // 'ssl' => true,
<add> // 'timeout' => 30,
<add> ],
<add>
<ide> 's3' => [
<ide> 'driver' => 's3',
<ide> 'key' => 'your-key', | 1 |
Python | Python | use python -m virtualenv in fabfile | ed27ca7e217a23fe48ff1a8f4a61fd380ee3174a | <ide><path>fabfile.py
<ide> def env(lang='python2.7'):
<ide> if path.exists(VENV_DIR):
<ide> local('rm -rf {env}'.format(env=VENV_DIR))
<del> local('virtualenv -p {lang} {env}'.format(lang=lang, env=VENV_DIR))
<add> local('python -m virtualenv -p {lang} {env}'.format(lang=lang, env=VENV_DIR))
<ide>
<ide>
<ide> def install(): | 1 |
Javascript | Javascript | name anonymous functions in http | accf410eb0992628b4aab3c139242a409874a4fb | <ide><path>lib/http.js
<ide> exports.STATUS_CODES = server.STATUS_CODES;
<ide> exports._connectionListener = server._connectionListener;
<ide> const Server = exports.Server = server.Server;
<ide>
<del>exports.createServer = function(requestListener) {
<add>exports.createServer = function createServer(requestListener) {
<ide> return new Server(requestListener);
<ide> };
<ide>
<ide> const client = require('_http_client');
<ide> const ClientRequest = exports.ClientRequest = client.ClientRequest;
<ide>
<del>exports.request = function(options, cb) {
<add>exports.request = function request(options, cb) {
<ide> return new ClientRequest(options, cb);
<ide> };
<ide>
<del>exports.get = function(options, cb) {
<add>exports.get = function get(options, cb) {
<ide> var req = exports.request(options, cb);
<ide> req.end();
<ide> return req; | 1 |
Text | Text | use lowercase for 'article' tag | 8cb540fe85f9a02067e8e6d81a656ebefa109ab0 | <ide><path>curriculum/challenges/english/01-responsive-web-design/applied-accessibility/wrap-content-in-the-article-element.english.md
<ide> videoUrl: 'https://scrimba.com/c/cPp79S3'
<ide>
<ide> ## Description
<ide> <section id='description'>
<del><code>article</code> is another one of the new HTML5 elements that adds semantic meaning to your markup. <code>Article</code> is a sectioning element, and is used to wrap independent, self-contained content. The tag works well with blog entries, forum posts, or news articles.
<add><code>article</code> is another one of the new HTML5 elements that adds semantic meaning to your markup. <code>article</code> is a sectioning element, and is used to wrap independent, self-contained content. The tag works well with blog entries, forum posts, or news articles.
<ide> Determining whether content can stand alone is usually a judgement call, but there are a couple simple tests you can use. Ask yourself if you removed all surrounding context, would that content still make sense? Similarly for text, would the content hold up if it were in an RSS feed?
<ide> Remember that folks using assistive technologies rely on organized, semantically meaningful markup to better understand your work.
<ide> <strong>Note about <code>section</code> and <code>div</code></strong><br>The <code>section</code> element is also new with HTML5, and has a slightly different semantic meaning than <code>article</code>. An <code>article</code> is for standalone content, and a <code>section</code> is for grouping thematically related content. They can be used within each other, as needed. For example, if a book is the <code>article</code>, then each chapter is a <code>section</code>. When there's no relationship between groups of content, then use a <code>div</code>. | 1 |
Text | Text | update chinese translation of react | 6021a32de99616d38e0ab347ead803b73ef85b91 | <ide><path>curriculum/challenges/chinese/03-front-end-libraries/react/access-props-using-this.props.chinese.md
<ide> id: 5a24c314108439a4d403616e
<ide> title: Access Props Using this.props
<ide> challengeType: 6
<ide> isRequired: false
<del>videoUrl: ''
<del>localeTitle: 使用this.props访问道具
<add>forumTopicId: 301375
<add>localeTitle: 使用 this.props 访问 Props
<ide> ---
<ide>
<ide> ## Description
<del><section id="description">最后几个挑战涵盖了将道具传递给子组件的基本方法。但是,如果你传递道具的子组件是ES6类组件,而不是无状态功能组件呢? ES6类组件使用稍微不同的约定来访问props。无论何时在您自己引用类组件时,都使用<code>this</code>关键字。一类组件中访问的道具,你前言您使用与访问它的代码<code>this</code> 。例如,如果ES6类组件具有名为<code>data</code>的prop,则在JSX中编写<code>{this.props.data}</code> 。 </section>
<add><section id='description'>
<add>前几项挑战涵盖了将 props 传递给子组件的基本方法。但是,倘若接收 prop 的子组件不是无状态函数组件,而是一个 ES6 类组件又当如何呢?ES6 类组件访问 props 的方法略有不同。
<add>任何时候,只要引用类组件本身,就要使用<code>this</code>关键字。要访问类组件中的 props,你需要在在访问它的代码前面添加<code>this</code>。例如,如果 ES6 类组件有一个名为<code>data</code>的 prop,你可以在 JSX 中这样写:<code>{this.props.data}</code>。
<add></section>
<ide>
<ide> ## Instructions
<del><section id="instructions">在父组件<code>ResetPassword</code>呈现<code>ReturnTempPassword</code>组件的实例。在这里,给<code>ReturnTempPassword</code>一个<code>tempPassword</code>的prop,并为它<code>tempPassword</code>一个至少8个字符长的字符串的值。在子项<code>ReturnTempPassword</code> ,访问<code>strong</code>标记内的<code>tempPassword</code> prop,以确保用户看到临时密码。 </section>
<add><section id='instructions'>
<add>在父组件<code>ResetPassword</code>中渲染<code>ReturnTempPassword</code>组件的一个实例。在这里,为<code>ReturnTempPassword</code>提供一个<code>tempPassword</code>prop,并赋值给 prop 一个长度至少为 8 个字符的字符串。在子组件<code>ReturnTempPassword</code>中,访问<code>strong</code>标签中的<code>tempPassword</code>prop,以确保用户看到临时密码。
<add></section>
<ide>
<ide> ## Tests
<ide> <section id='tests'>
<ide>
<ide> ```yml
<ide> tests:
<del> - text: <code>ResetPassword</code>组件应返回单个<code>div</code>元素。
<add> - text: <code>ResetPassword</code>组件应该返回单个<code>div</code>元素。
<ide> testString: assert((function() { const mockedComponent = Enzyme.mount(React.createElement(ResetPassword)); return mockedComponent.children().type() === 'div'; })());
<del> - text: <code>ResetPassword</code>的第四个子<code>ResetPassword</code>应该是<code>ReturnTempPassword</code>组件。
<add> - text: <code>ResetPassword</code>的第四个子组件应该是<code>ReturnTempPassword</code>组件。
<ide> testString: assert((function() { const mockedComponent = Enzyme.mount(React.createElement(ResetPassword)); return mockedComponent.children().childAt(3).name() === 'ReturnTempPassword'; })());
<del> - text: <code>ReturnTempPassword</code>组件应该有一个名为<code>tempPassword</code>的prop。
<add> - text: <code>ReturnTempPassword</code>组件应该有一个名为<code>tempPassword</code>的属性。
<ide> testString: assert((function() { const mockedComponent = Enzyme.mount(React.createElement(ResetPassword)); return mockedComponent.find('ReturnTempPassword').props().tempPassword; })());
<del> - text: <code>ReturnTempPassword</code>的<code>tempPassword</code>道具应该等于至少<code>8</code>字符的字符串。
<add> - text: <code>ReturnTempPassword</code>组件的<code>tempPassword</code>prop 值应该是一个字符串,其长度至少为<code>8</code>。
<ide> testString: assert((function() { const mockedComponent = Enzyme.mount(React.createElement(ResetPassword)); const temp = mockedComponent.find('ReturnTempPassword').props().tempPassword; return typeof temp === 'string' && temp.length >= 8; })());
<del> - text: <code>ReturnTempPassword</code>组件应显示您在<code>strong</code>标记内作为<code>tempPassword</code>支柱创建的密码。
<add> - text: <code>ReturnTempPassword</code>组件应该显示你作为<code>tempPassword</code>prop 创建的密码,并且密码显示在<code>strong</code>标签中。
<ide> testString: assert((function() { const mockedComponent = Enzyme.mount(React.createElement(ResetPassword)); return mockedComponent.find('strong').text() === mockedComponent.find('ReturnTempPassword').props().tempPassword; })());
<ide>
<ide> ```
<ide> class ResetPassword extends React.Component {
<ide> );
<ide> }
<ide> };
<del>
<ide> ```
<ide>
<ide> </div>
<ide> class ResetPassword extends React.Component {
<ide> <div id='jsx-teardown'>
<ide>
<ide> ```js
<del>console.info('after the test');
<add>ReactDOM.render(<ResetPassword />, document.getElementById('root'))
<ide> ```
<ide>
<ide> </div>
<ide> console.info('after the test');
<ide> ## Solution
<ide> <section id='solution'>
<ide>
<add>
<ide> ```js
<del>// solution required
<add>class ReturnTempPassword extends React.Component {
<add> constructor(props) {
<add> super(props);
<add>
<add> }
<add> render() {
<add> return (
<add> <div>
<add> <p>Your temporary password is: <strong>{this.props.tempPassword}</strong></p>
<add> </div>
<add> );
<add> }
<add>};
<add>
<add>class ResetPassword extends React.Component {
<add> constructor(props) {
<add> super(props);
<add>
<add> }
<add> render() {
<add> return (
<add> <div>
<add> <h2>Reset Password</h2>
<add> <h3>We've generated a new temporary password for you.</h3>
<add> <h3>Please reset this password from your account settings ASAP.</h3>
<add> { /* change code below this line */ }
<add> <ReturnTempPassword tempPassword="serrPbqrPnzc" />
<add> { /* change code above this line */ }
<add> </div>
<add> );
<add> }
<add>};
<ide> ```
<ide>
<del>/section>
<add></section>
<ide><path>curriculum/challenges/chinese/03-front-end-libraries/react/add-comments-in-jsx.chinese.md
<ide> id: 5a24bbe0dba28a8d3cbd4c5e
<ide> title: Add Comments in JSX
<ide> challengeType: 6
<ide> isRequired: false
<del>videoUrl: ''
<del>localeTitle: 在JSX中添加注释
<add>forumTopicId: 301376
<add>localeTitle: 在 JSX 中添加注释
<ide> ---
<ide>
<ide> ## Description
<del><section id="description"> JSX是一种可以编译成有效JavaScript的语法。有时,为了便于阅读,您可能需要在代码中添加注释。像大多数编程语言一样,JSX有自己的方法来做到这一点。要将注释放在JSX中,可以使用语法<code>{/* */}</code>来包含注释文本。 </section>
<add><section id='description'>
<add>JSX 是一种可以编译成有效 JavaScript 的语法。有时,为了便于阅读,你可能需要在代码中添加注释。像大多数编程语言一样,JSX 也有自己的方法来实现这一点。
<add>要将注释放在 JSX 中,可以使用<code>{/* */}</code>语法来包裹注释文本。
<add></section>
<ide>
<ide> ## Instructions
<del><section id="instructions">代码编辑器的JSX元素与您在上一个挑战中创建的元素类似。在提供的<code>div</code>元素中的某处添加注释,而不修改现有的<code>h1</code>或<code>p</code>元素。 </section>
<add><section id='instructions'>
<add>代码编辑器中的 JSX 元素与你在上一个挑战中创建的元素类似。在提供的<code>div</code>元素中的某处添加注释,而不修改现有的<code>h1</code>或<code>p</code>元素。
<add></section>
<ide>
<ide> ## Tests
<ide> <section id='tests'>
<ide>
<ide> ```yml
<ide> tests:
<ide> - text: 常量<code>JSX</code>应该返回一个<code>div</code>元素。
<del> testString: 'assert(JSX.type === "div", "The constant <code>JSX</code> should return a <code>div</code> element.");'
<del> - text: <code>div</code>应包含一个<code>h1</code>标记作为第一个元素。
<del> testString: 'assert(JSX.props.children[0].type === "h1", "The <code>div</code> should contain an <code>h1</code> tag as the first element.");'
<add> testString: assert(JSX.type === 'div');
<add> - text: <code>div</code>应该包含一个<code>h1</code>标签作为第一个元素。
<add> testString: assert(JSX.props.children[0].type === 'h1');
<ide> - text: <code>div</code>应该包含一个<code>p</code>标签作为第二个元素。
<del> testString: 'assert(JSX.props.children[1].type === "p", "The <code>div</code> should contain a <code>p</code> tag as the second element.");'
<del> - text: <code>JSX</code>应该包含一条评论。
<del> testString: 'getUserInput => assert(getUserInput("index").includes("/*") && getUserInput("index").includes("*/"), "The <code>JSX</code> should include a comment.");'
<del>
<add> testString: assert(JSX.props.children[1].type === 'p');
<add> - text: 当前的 <code>h1</code> 和 <code>p</code> 元素不能被修改。
<add> testString: assert(JSX.props.children[0].props.children === 'This is a block of JSX' && JSX.props.children[1].props.children === 'Here\'s a subtitle');
<add> - text: <code>JSX</code>应该包含一个注释。
<add> testString: assert(/<div>[\s\S]*{\s*\/\*[\s\S]*\*\/\s*}[\s\S]*<\/div>/.test(code));
<ide> ```
<ide>
<ide> </section>
<ide> const JSX = (
<ide> <p>Here's a subtitle</p>
<ide> </div>
<ide> );
<del>
<ide> ```
<ide>
<ide> </div>
<ide> const JSX = (
<ide> <div id='jsx-teardown'>
<ide>
<ide> ```js
<del>console.info('after the test');
<add>ReactDOM.render(JSX, document.getElementById('root'))
<ide> ```
<ide>
<ide> </div>
<ide> console.info('after the test');
<ide> ## Solution
<ide> <section id='solution'>
<ide>
<add>
<ide> ```js
<del>// solution required
<add>const JSX = (
<add><div>
<add> <h1>This is a block of JSX</h1>
<add> { /* this is a JSX comment */ }
<add> <p>Here's a subtitle</p>
<add></div>);
<ide> ```
<ide>
<del>/section>
<add></section>
<ide><path>curriculum/challenges/chinese/03-front-end-libraries/react/add-event-listeners.chinese.md
<ide> id: 5a24c314108439a4d403617e
<ide> title: Add Event Listeners
<ide> challengeType: 6
<ide> isRequired: false
<del>videoUrl: ''
<del>localeTitle: 添加事件监听器
<add>forumTopicId: 301377
<add>localeTitle: 添加事件侦听器
<ide> ---
<ide>
<ide> ## Description
<del><section id="description"> <code>componentDidMount()</code>方法也是附加您需要为特定功能添加的任何事件侦听器的最佳位置。 React提供了一个合成事件系统,它包装了浏览器中的本机事件系统。这意味着无论用户的浏览器如何,合成事件系统的行为都完全相同 - 即使本机事件在不同浏览器之间的行为可能不同。您已经使用了一些合成事件处理程序,如<code>onClick()</code> 。 React的合成事件系统非常适合用于您在DOM元素上管理的大多数交互。但是,如果要将事件处理程序附加到文档或窗口对象,则必须直接执行此操作。 </section>
<add><section id='description'>
<add><code>componentDidMount()</code>方法也是添加特定功能所需的任何事件监听器的最佳位置。React 提供了一个合成事件系统,它将本地事件系统封装在浏览器中。这意味着,不管用户的浏览器如何,合成事件系统的行为都完全相同--即使不同浏览器之间的本地事件的行为可能不同。
<add>你已经使用了一些合成事件处理程序,如<code>onClick()</code>。React 的合成事件系统非常适合用于你在 DOM 元素上管理的大多数交互。但是,如果要将事件处理程序附加到 document 或 window 对象,则必须直接执行此操作。
<add></section>
<ide>
<ide> ## Instructions
<del><section id="instructions">在<code>componentDidMount()</code>方法中为<code>keydown</code>事件附加事件侦听器,并让这些事件触发回调<code>handleKeyPress()</code> 。您可以使用<code>document.addEventListener()</code> ,它将事件(在引号中)作为第一个参数,将回调作为第二个参数。然后,在<code>componentWillUnmount()</code> ,删除此相同的事件侦听器。您可以将相同的参数传递给<code>document.removeEventListener()</code> 。在卸载和销毁之前,使用此生命周期方法对React组件进行任何清理是一种很好的做法。删除事件侦听器就是一个这样的清理操作的示例。 </section>
<add><section id='instructions'>
<add>在<code>componentDidMount()</code>方法中为<code>keydown</code>事件添加事件监听器,并让这些事件触发回调<code>handleKeyPress()</code>。你可以使用<code>document.addEventListener()</code>,它将事件(用引号括起来)作为第一个参数,将回调作为第二个参数。
<add>然后,在<code>componentWillUnmount()</code>中移除相同的事件监听器。你可以把相同的参数传递给<code>document.removeEventListener()</code>。在卸载和销毁 React 组件之前,最好使用这种生命周期方法对它们进行清理。移除事件监听器就是这样一个清理操作的例子。
<add></section>
<ide>
<ide> ## Tests
<ide> <section id='tests'>
<ide>
<ide> ```yml
<ide> tests:
<del> - text: <code>MyComponent</code>应该呈现一个包含<code>h1</code>标记的<code>div</code>元素。
<add> - text: <code>MyComponent</code>应该渲染一个包含<code>h1</code>标签的<code>div</code>元素。
<ide> testString: assert((() => { const mockedComponent = Enzyme.mount(React.createElement(MyComponent)); return mockedComponent.find('div').children().find('h1').length === 1; })());
<del> - text: keydown侦听器应附加到<code>componentDidMount</code>的文档。
<add> - text: 应该在<code>componentDidMount</code>中将 keydown 事件监听添加到到 document 上。
<ide> testString: assert((() => { const mockedComponent = Enzyme.mount(React.createElement(MyComponent)); const didMountString = mockedComponent.instance().componentDidMount.toString(); return new RegExp('document\.addEventListener(.|\n|\r)+keydown(.|\n|\r)+this\.handleKeyPress').test(didMountString); })());
<del> - text: 应该从<code>componentWillUnmount</code>的文档中删除keydown侦听器。
<add> - text: 应该在<code>componentWillUnmount</code>中将 document 上的 keydown 事件监听移除。
<ide> testString: assert((() => { const mockedComponent = Enzyme.mount(React.createElement(MyComponent)); const willUnmountString = mockedComponent.instance().componentWillUnmount.toString(); return new RegExp('document\.removeEventListener(.|\n|\r)+keydown(.|\n|\r)+this\.handleKeyPress').test(willUnmountString); })());
<del> - text: 组件安装完成后,按<code>enter</code>应更新其状态和渲染的<code>h1</code>标签。
<add> - text: 一旦组件装载完毕,按<code>enter</code>应该会更新其 state 并渲染到<code>h1</code>标签。
<ide> testString: 'async () => { const waitForIt = (fn) => new Promise((resolve, reject) => setTimeout(() => resolve(fn()), 250)); const mockedComponent = Enzyme.mount(React.createElement(MyComponent)); const beforeState = mockedComponent.state(''message''); const beforeText = mockedComponent.find(''h1'').text(); const pressEnterKey = () => { mockedComponent.instance().handleKeyPress({ keyCode: 13 }); return waitForIt(() => { mockedComponent.update(); return { state: mockedComponent.state(''message''), text: mockedComponent.find(''h1'').text()}; });}; const afterKeyPress = await pressEnterKey(); assert(beforeState !== afterKeyPress.state && beforeText !== afterKeyPress.text); }; '
<ide>
<ide> ```
<ide> class MyComponent extends React.Component {
<ide> constructor(props) {
<ide> super(props);
<ide> this.state = {
<del> message: "
<add> message: ''
<ide> };
<ide> this.handleEnter = this.handleEnter.bind(this);
<ide> this.handleKeyPress = this.handleKeyPress.bind(this);
<ide> class MyComponent extends React.Component {
<ide> );
<ide> }
<ide> };
<del>
<ide> ```
<ide>
<ide> </div>
<ide> class MyComponent extends React.Component {
<ide> <div id='jsx-teardown'>
<ide>
<ide> ```js
<del>console.info('after the test');
<add>ReactDOM.render(<MyComponent />, document.getElementById('root'))
<ide> ```
<ide>
<ide> </div>
<ide> console.info('after the test');
<ide> ## Solution
<ide> <section id='solution'>
<ide>
<add>
<ide> ```js
<del>// solution required
<add>class MyComponent extends React.Component {
<add> constructor(props) {
<add> super(props);
<add> this.state = {
<add> message: ''
<add> };
<add> this.handleKeyPress = this.handleKeyPress.bind(this);
<add> this.handleEnter = this.handleEnter.bind(this); }
<add> componentDidMount() {
<add> // change code below this line
<add> document.addEventListener('keydown', this.handleKeyPress);
<add> // change code above this line
<add> }
<add> componentWillUnmount() {
<add> // change code below this line
<add> document.removeEventListener('keydown', this.handleKeyPress);
<add> // change code above this line
<add> }
<add> handleEnter() {
<add> this.setState({
<add> message: this.state.message + 'You pressed the enter key! '
<add> });
<add> }
<add> handleKeyPress(event) {
<add> if (event.keyCode === 13) {
<add> this.handleEnter();
<add> }
<add> }
<add> render() {
<add> return (
<add> <div>
<add> <h1>{this.state.message}</h1>
<add> </div>
<add> );
<add> }
<add>};
<ide> ```
<ide>
<del>/section>
<add></section>
<ide><path>curriculum/challenges/chinese/03-front-end-libraries/react/add-inline-styles-in-react.chinese.md
<ide> id: 5a24c314108439a4d4036182
<ide> title: Add Inline Styles in React
<ide> challengeType: 6
<ide> isRequired: false
<del>videoUrl: ''
<del>localeTitle: 在React中添加内联样式
<add>forumTopicId: 301378
<add>localeTitle: 在 React 中添加内联样式
<ide> ---
<ide>
<ide> ## Description
<del><section id="description">您可能已经注意到,在上一个挑战中,除了设置为JavaScript对象的<code>style</code>属性之外,还有HTML内联样式的其他几种语法差异。首先,某些CSS样式属性的名称使用驼峰大小写。例如,最后一个挑战使用<code>fontSize</code>而不是<code>font-size</code>设置<code>font-size</code> 。像<code>font-size</code>这样的连字符是JavaScript对象属性的无效语法,因此React使用驼峰大小写。通常,任何带连字符的样式属性都是使用JSX中的camel case编写的。除非另有说明,否则假定所有属性值长度单位(如<code>height</code> , <code>width</code>和<code>fontSize</code> )均为<code>px</code> 。例如,如果要使用<code>em</code> ,则将值和单位用引号括起来,如<code>{fontSize: "4em"}</code> 。除了默认为<code>px</code>的长度值之外,所有其他属性值都应该用引号括起来。 </section>
<add><section id='description'>
<add>在上一次挑战中,你可能已经注意到,除了设置为 JavaScript 对象的<code>style</code>属性之外,与 HTML 内联样式相比,React 的内联样式还有其他几个语法差异。首先,某些 CSS 样式属性的名称使用驼峰式命名。例如,最后一个挑战用<code>fontSize</code>而不是<code>font-size</code>来设置字体的大小。对于 JavaScript 对象属性来说,像<code>font-size</code>这样的连字符命名是无效的语法,所以 React 使用驼峰式命名。通常,任何连字符的 style 属性在 JSX 中都是使用驼峰式命名的。
<add>除非另有规定,否则所有属性值是长度的(如<code>height</code>、<code>width</code>和<code>fontSize</code>)其单位都假定为<code>px</code>。例如,如果要使用<code>em</code>,可以用引号将值和单位括起来,例如<code>{fontSize: "4em"}</code>。除了默认为<code>px</code>的长度值之外,所有其他属性值都应该用引号括起来。
<add></section>
<ide>
<ide> ## Instructions
<del><section id="instructions">如果您有大量样式,则可以将样式<code>object</code>分配给常量以保持代码的有序性。取消注释<code>styles</code>常量并声明具有三个样式属性及其值的<code>object</code> 。给<code>div</code>一个颜色为<code>"purple"</code> ,字体大小为<code>40</code> ,边框为<code>"2px solid purple"</code> 。然后将<code>style</code>属性设置为等于<code>styles</code>常量。 </section>
<add><section id='instructions'>
<add>如果你有大量样式,你可以将 style<code>对象</code>分配给一个常量,以保持代码的组织有序。取消对<code>styles</code>常量的注释,并声明具有三个样式属性及对应值的<code>对象</code>。使<code>div</code>的文字颜色为<code>"purple"</code>、字号为<code>40</code>、边框为<code>"2px solid purple"</code>。然后设置<code>style</code>属性,使其等于<code>styles</code>常量。
<add></section>
<ide>
<ide> ## Tests
<ide> <section id='tests'>
<ide>
<ide> ```yml
<ide> tests:
<del> - text: <code>styles</code>变量应该是具有三个属性的<code>object</code> 。
<add> - text: <code>styles</code>变量应该是具有三个属性的<code>对象</code>。
<ide> testString: assert(Object.keys(styles).length === 3);
<del> - text: <code>styles</code>变量的<code>color</code>属性应设置为<code>purple</code>的值。
<add> - text: <code>styles</code>变量的<code>color</code>属性应该设置为<code>purple</code>。
<ide> testString: assert(styles.color === 'purple');
<del> - text: <code>styles</code>变量应该将<code>fontSize</code>属性设置为值<code>40</code> 。
<add> - text: <code>styles</code>变量应该将<code>fontSize</code>属性设置为<code>40</code>。
<ide> testString: assert(styles.fontSize === 40);
<del> - text: <code>styles</code>变量应该将<code>border</code>属性设置为<code>2px solid purple</code>的值。
<add> - text: <code>styles</code>变量的<code>border</code>属性应该设置为<code>2px solid purple</code>。
<ide> testString: assert(styles.border === "2px solid purple");
<del> - text: 该组件应呈现<code>div</code>元素。
<add> - text: 组件应该渲染一个<code>div</code>元素。
<ide> testString: assert((function() { const mockedComponent = Enzyme.shallow(React.createElement(Colorful)); return mockedComponent.type() === 'div'; })());
<ide> - text: <code>div</code>元素的样式应该由<code>styles</code>对象定义。
<ide> testString: assert((function() { const mockedComponent = Enzyme.shallow(React.createElement(Colorful)); return (mockedComponent.props().style.color === "purple" && mockedComponent.props().style.fontSize === 40 && mockedComponent.props().style.border === "2px solid purple"); })());
<ide> tests:
<ide> <div id='jsx-seed'>
<ide>
<ide> ```jsx
<add>
<ide> // const styles =
<ide> // change code above this line
<ide> class Colorful extends React.Component {
<ide> class Colorful extends React.Component {
<ide> <div id='jsx-teardown'>
<ide>
<ide> ```js
<del>console.info('after the test');
<add>ReactDOM.render(<Colorful />, document.getElementById('root'))
<ide> ```
<ide>
<ide> </div>
<ide> console.info('after the test');
<ide> ## Solution
<ide> <section id='solution'>
<ide>
<add>
<ide> ```js
<del>// solution required
<add>const styles = {
<add> color: "purple",
<add> fontSize: 40,
<add> border: "2px solid purple"
<add>};
<add>// change code above this line
<add>class Colorful extends React.Component {
<add> render() {
<add> // change code below this line
<add> return (
<add> <div style={styles}>Style Me!</div>
<add> // change code above this line
<add> );
<add> }
<add>};
<add>
<ide> ```
<ide>
<del>/section>
<add></section>
<ide><path>curriculum/challenges/chinese/03-front-end-libraries/react/bind-this-to-a-class-method.chinese.md
<ide> id: 5a24c314108439a4d4036174
<ide> title: Bind 'this' to a Class Method
<ide> challengeType: 6
<ide> isRequired: false
<del>videoUrl: ''
<del>localeTitle: 将'this'绑定到类方法
<add>forumTopicId: 301379
<add>localeTitle: 将 this 绑定到 Class 方法
<ide> ---
<ide>
<ide> ## Description
<del><section id="description">除了设置和更新<code>state</code> ,您还可以为组件类定义方法。类方法通常需要使用<code>this</code>关键字,以便它可以访问方法范围内的类(例如<code>state</code>和<code>props</code> )上的属性。有几种方法可以让您的类方法访问<code>this</code> 。一个常用的方法是显式绑定<code>this</code>所以在构造<code>this</code>组件已初始化变为绑定到类方法。您可能已经注意到最后一个挑战使用<code>this.handleClick = this.handleClick.bind(this)</code>作为构造函数中的<code>handleClick</code>方法。然后,当您在类方法中调用类似<code>this.setState()</code>的函数时, <code>this</code>引用该类,并且不会被<code>undefined</code> 。 <strong>注意:</strong> <code>this</code>关键字是JavaScript中最令人困惑的方面之一,但它在React中起着重要作用。虽然这里的行为是完全正常的,但这些课程并不是<code>this</code>进行深入审查的地方,所以如果上述内容令人困惑,请参考其他课程! </section>
<add><section id='description'>
<add>除了设置和更新<code>state</code>之外,你还可以为组件类定义方法。类方法通常需要使用<code>this</code>关键字,以便它可以访问方法中类的属性(例如<code>state</code>和<code>props </code>)。有几种方法可以让你的类方法访问<code>this</code>。
<add>一种常见的方法是在构造函数中显式地绑定<code>this</code>,这样当组件初始化时,<code>this</code>就会绑定到类方法。你可能已经注意到上一个挑战使用了<code>this.handleClick = this.handleClick.bind(this)</code>用于其在构造函数中的<code>handleClick</code>方法。然后,当你在类方法中调用像<code>this.setState()</code>这样的函数时,<code>this</code>指的是这个类,而不是<code>undefined</code>。
<add><strong>注意:</strong> <code>this</code>关键字是 JavaScript 中最令人困惑的方面之一,但它在 React 中扮演着重要的角色。虽然它的行为在这里是完全正常的,但是这些课程并不深入研究<code>this</code>,所以如果以上内容令你感到困惑,请参考其他课程!
<add></section>
<ide>
<ide> ## Instructions
<del><section id="instructions">代码编辑器具有与组件<code>state</code>保持跟踪的项目计数。它还有一个方法,允许您增加此项目计数。但是,该方法不起作用,因为它使用未定义的<code>this</code>关键字。通过明确地结合修复它<code>this</code>到<code>addItem()</code>在组件的构造方法。接下来,将单击处理程序添加到render方法中的<code>button</code>元素。当按钮收到click事件时,它应该触发<code>addItem()</code>方法。请记住,传递给<code>onClick</code>处理程序的方法需要花括号,因为它应该直接解释为JavaScript。完成上述步骤后,您应该可以单击按钮并查看HTML中的项目计数增量。 </section>
<add><section id='instructions'>
<add>代码编辑器有一个带有<code>state</code>的组件,用于跟踪项目计数。它还有一个方法,允许你增加此项目计数。但是,该方法不起作用,因为它使用了未定义的<code>this</code>关键字。可以通过将<code>this</code>显式绑定到组件构造函数中的<code>addItem()</code>方法来修复它。
<add>接下来,向 render 方法中的<code>button</code>元素添加一个单击处理程序。当按钮接收到单击事件时,它应该触发<code>addItem()</code>方法。记住,传递给<code>onClick</code>处理程序的方法需要使用花括号,因为它应该直接被解释为 JavaScript。
<add>完成上述步骤后,你应该可以单击按钮并查看 HTML 中的项目计数增量。
<add></section>
<ide>
<ide> ## Tests
<ide> <section id='tests'>
<ide>
<ide> ```yml
<ide> tests:
<del> - text: <code>MyComponent</code>应该返回一个<code>div</code>元素,它按顺序包装两个元素,一个按钮和一个<code>h1</code>元素。
<add> - text: <code>MyComponent</code>应返回<code>div</code>元素,该元素按顺序包含两个元素,一个按钮和一个<code>h1</code>元素。
<ide> testString: assert(Enzyme.mount(React.createElement(MyComponent)).find('div').length === 1 && Enzyme.mount(React.createElement(MyComponent)).find('div').childAt(0).type() === 'button' && Enzyme.mount(React.createElement(MyComponent)).find('div').childAt(1).type() === 'h1');
<del> - text: '<code>MyComponent</code>的状态应使用键值对<code>{ itemCount: 0 }</code>初始化。'
<add> - text: '<code>MyComponent</code>的 state 应该使用键值对<code>{ itemCount: 0 }</code>进行初始化。'
<ide> testString: 'assert(Enzyme.mount(React.createElement(MyComponent)).state(''text'') === ''Hello'');'
<del> - text: 单击<code>button</code>元素应该运行<code>addItem</code>方法并将状态<code>itemCount</code>递增<code>1</code> 。
<add> - text: 单击<code>button</code>元素应该运行<code>addItem</code>方法,并使 state<code>itemCount</code>的计数增加<code>1</code>。
<ide> testString: 'async () => { const waitForIt = (fn) => new Promise((resolve, reject) => setTimeout(() => resolve(fn()), 250)); const mockedComponent = Enzyme.mount(React.createElement(MyComponent)); const first = () => { mockedComponent.setState({ text: ''Hello'' }); return waitForIt(() => mockedComponent.state(''text'')); }; const second = () => { mockedComponent.find(''button'').simulate(''click''); return waitForIt(() => mockedComponent.state(''text'')); }; const firstValue = await first(); const secondValue = await second(); assert(firstValue === ''Hello'' && secondValue === ''You clicked!''); };'
<ide>
<ide> ```
<ide> class MyComponent extends React.Component {
<ide> constructor(props) {
<ide> super(props);
<ide> this.state = {
<del> itemCount: 0
<add> text: "Hello"
<ide> };
<ide> // change code below this line
<ide>
<ide> // change code above this line
<ide> }
<del> addItem() {
<add> handleClick() {
<ide> this.setState({
<del> itemCount: this.state.itemCount + 1
<add> text: "You clicked!"
<ide> });
<ide> }
<ide> render() {
<ide> class MyComponent extends React.Component {
<ide> { /* change code below this line */ }
<ide> <button>Click Me</button>
<ide> { /* change code above this line */ }
<del> <h1>Current Item Count: {this.state.itemCount}</h1>
<add> <h1>{this.state.text}</h1>
<ide> </div>
<ide> );
<ide> }
<ide> };
<del>
<ide> ```
<ide>
<ide> </div>
<ide> class MyComponent extends React.Component {
<ide> <div id='jsx-teardown'>
<ide>
<ide> ```js
<del>console.info('after the test');
<add>ReactDOM.render(<MyComponent />, document.getElementById('root'))
<ide> ```
<ide>
<ide> </div>
<ide> console.info('after the test');
<ide> ## Solution
<ide> <section id='solution'>
<ide>
<add>
<ide> ```js
<del>// solution required
<add>class MyComponent extends React.Component {
<add> constructor(props) {
<add> super(props);
<add> this.state = {
<add> text: "Hello"
<add> };
<add> this.handleClick = this.handleClick.bind(this);
<add> }
<add> handleClick() {
<add> this.setState({
<add> text: "You clicked!"
<add> });
<add> }
<add> render() {
<add> return (
<add> <div>
<add> <button onClick = {this.handleClick}>Click Me</button>
<add> <h1>{this.state.text}</h1>
<add> </div>
<add> );
<add> }
<add>};
<ide> ```
<ide>
<del>/section>
<add></section>
<ide><path>curriculum/challenges/chinese/03-front-end-libraries/react/change-inline-css-conditionally-based-on-component-state.chinese.md
<ide> id: 5a24c314108439a4d4036189
<ide> title: Change Inline CSS Conditionally Based on Component State
<ide> challengeType: 6
<ide> isRequired: false
<del>videoUrl: ''
<del>localeTitle: 有条件地改变内联CSS基于组件状态
<add>forumTopicId: 301380
<add>localeTitle: 根据组件状态有条件地更改内联 CSS
<ide> ---
<ide>
<ide> ## Description
<del><section id="description">此时,您已经看到了条件渲染的几个应用程序以及内联样式的使用。这是另外一个结合了这两个主题的例子。您还可以根据React组件的状态有条件地呈现CSS。要执行此操作,请检查条件,如果满足该条件,则修改在render方法中分配给JSX元素的样式对象。这个范例很重要,因为它是通过直接修改DOM元素来应用样式的更传统方法的一种戏剧性转变(例如,jQuery非常常见)。在该方法中,您必须跟踪元素何时更改并直接处理实际操作。跟踪更改可能变得很困难,可能会使您的UI无法预测。根据条件设置样式对象时,您将描述UI应如何看作应用程序状态的函数。有明确的信息流只能向一个方向移动。使用React编写应用程序时,这是首选方法。 </section>
<add><section id='description'>
<add>此时,你已经看到了一些条件渲染的应用程序和内联样式的使用。这里还有一个将这两个主题结合在一起的例子。你也可以根据 React 组件的 state 有条件地渲染 CSS。要执行此操作,请检查条件,如果满足该条件,则修改在 render 方法中分配给 JSX 元素的样式对象。
<add>这个范例对于更加容易理解,因为相比传统的通过直接修改 DOM 元素来应用样式的方法(这在 jQuery 中非常常见),这种方法是一个戏剧性的转变。在传统方法中,你必须跟踪元素何时发生变化,并直接处理实际操作,这使得跟踪变化变得很困难,也可能会让你的用户界面变得不可预测。当你根据一个条件设置一个样式对象时,你描述了 UI 作为应用程序的状态函数应当如何展现。如此便有一个清晰的单向流动的信息流。这是使用 React 编写应用程序时的首选方法。
<add></section>
<ide>
<ide> ## Instructions
<del><section id="instructions">代码编辑器有一个简单的受控输入组件,带有样式边框。如果用户在输入框中键入超过15个字符的文本,则希望将此边框设置为红色。添加条件以检查此情况,如果条件有效,则将输入边框样式设置为<code>3px solid red</code> 。您可以通过在输入中输入文本来尝试。 </section>
<add><section id='instructions'>
<add>代码编辑器有一个简单的带有边框样式的受控 input 组件。如果用户在输入框中键入超过 15 个字符的文本,你希望将此边框变成红色。添加一个条件来检查这一点,如果条件有效,则将 input 的边框样式设置为<code>3px solid red</code>。你可以通过在 input 中输入文本来尝试。
<add></section>
<ide>
<ide> ## Tests
<ide> <section id='tests'>
<ide>
<ide> ```yml
<ide> tests:
<del> - text: <code>GateKeeper</code>组件应该呈现<code>div</code>元素。
<add> - text: <code>GateKeeper</code>组件应该渲染一个de>div</code>元素。
<ide> testString: assert((function() { const mockedComponent = Enzyme.mount(React.createElement(GateKeeper)); return mockedComponent.find('div').length === 1; })());
<del> - text: 应使用设置为空字符串的状态键<code>input</code>初始化<code>GateKeeper</code>组件。
<add> - text: <code>GateKeeper</code>组件应使用设置为空字符串的 state <code>input</code>进行初始化。
<ide> testString: assert((function() { const mockedComponent = Enzyme.mount(React.createElement(GateKeeper)); return mockedComponent.state().input === ''; })());
<del> - text: <code>GateKeeper</code>组件应呈现<code>h3</code>标记和<code>input</code>标记。
<add> - text: <code>GateKeeper</code>组件应该渲染一个<code>h3</code>标签和一个<code>input</code>标签。
<ide> testString: assert((function() { const mockedComponent = Enzyme.mount(React.createElement(GateKeeper)); return mockedComponent.find('h3').length === 1 && mockedComponent.find('input').length === 1; })());
<del> - text: <code>input</code>标记最初应为<code>border</code>属性的<code>1px solid black</code>样式。
<add> - text: <code>input</code>标签<code>border</code>属性的样式应该初始化为<code>1px solid black</code>。
<ide> testString: assert((function() { const mockedComponent = Enzyme.mount(React.createElement(GateKeeper)); return mockedComponent.find('input').props().style.border === '1px solid black'; })());
<del> - text: 如果状态中的输入值超过15个字符,则<code>input</code>标记应使用<code>3px solid red</code>边框进行样式设置。
<add> - text: 如果 state 中 input 的值超过 15 个字符,则 <code>input</code> 标签的 border 样式应为<code>3px solid red</code>。
<ide> testString: 'async () => { const waitForIt = (fn) => new Promise((resolve, reject) => setTimeout(() => resolve(fn()), 100)); const mockedComponent = Enzyme.mount(React.createElement(GateKeeper)); const simulateChange = (el, value) => el.simulate(''change'', {target: {value}}); let initialStyle = mockedComponent.find(''input'').props().style.border; const state_1 = () => { mockedComponent.setState({input: ''this is 15 char'' }); return waitForIt(() => mockedComponent.find(''input'').props().style.border )}; const state_2 = () => { mockedComponent.setState({input: ''A very long string longer than 15 characters.'' }); return waitForIt(() => mockedComponent.find(''input'').props().style.border )}; const style_1 = await state_1(); const style_2 = await state_2(); assert(initialStyle === ''1px solid black'' && style_1 === ''1px solid black'' && style_2 === ''3px solid red''); }; '
<ide>
<ide> ```
<ide> tests:
<ide> <div id='jsx-seed'>
<ide>
<ide> ```jsx
<add>
<ide> class GateKeeper extends React.Component {
<ide> constructor(props) {
<ide> super(props);
<ide> this.state = {
<del> input: "
<add> input: ''
<ide> };
<ide> this.handleChange = this.handleChange.bind(this);
<ide> }
<ide> class GateKeeper extends React.Component {
<ide> );
<ide> }
<ide> };
<del>
<ide> ```
<ide>
<ide> </div>
<ide> class GateKeeper extends React.Component {
<ide> <div id='jsx-teardown'>
<ide>
<ide> ```js
<del>console.info('after the test');
<add>ReactDOM.render(<GateKeeper />, document.getElementById('root'))
<ide> ```
<ide>
<ide> </div>
<ide> console.info('after the test');
<ide> ## Solution
<ide> <section id='solution'>
<ide>
<add>
<ide> ```js
<del>// solution required
<add>class GateKeeper extends React.Component {
<add> constructor(props) {
<add> super(props);
<add> this.state = {
<add> input: ''
<add> };
<add> this.handleChange = this.handleChange.bind(this);
<add> }
<add> handleChange(event) {
<add> this.setState({ input: event.target.value })
<add> }
<add> render() {
<add> let inputStyle = {
<add> border: '1px solid black'
<add> };
<add> if (this.state.input.length > 15) {
<add> inputStyle.border = '3px solid red';
<add> };
<add> return (
<add> <div>
<add> <h3>Don't Type Too Much:</h3>
<add> <input
<add> type="text"
<add> style={inputStyle}
<add> value={this.state.input}
<add> onChange={this.handleChange} />
<add> </div>
<add> );
<add> }
<add>};
<ide> ```
<ide>
<del>/section>
<add></section>
<ide><path>curriculum/challenges/chinese/03-front-end-libraries/react/compose-react-components.chinese.md
<ide> id: 5a24c314108439a4d4036166
<ide> title: Compose React Components
<ide> challengeType: 6
<ide> isRequired: false
<del>videoUrl: ''
<del>localeTitle: 撰写反应组件
<add>forumTopicId: 301381
<add>localeTitle: 组合 React 组件
<ide> ---
<ide>
<ide> ## Description
<del><section id="description">随着挑战继续使用更复杂的组合与React组件和JSX,有一点需要注意。在其他组件中渲染ES6样式类组件与渲染您在最后几个挑战中使用的简单组件没有什么不同。您可以在其他组件中呈现JSX元素,无状态功能组件和ES6类组件。 </section>
<add><section id='description'>
<add>随着挑战继续,我们将组合使用更复杂的 React 组件和 JSX,有一点需要注意。在其他组件中渲染 ES6 风格的类组件和渲染你在过去几个挑战中使用的简单组件没有什么不同。你可以在其他组件中渲染 JSX 元素、无状态功能组件和 ES6 类组件。
<add></section>
<ide>
<ide> ## Instructions
<del><section id="instructions">在代码编辑器中, <code>TypesOfFood</code>组件已经在呈现一个名为<code>Vegetables</code>的组件。此外,还有最后一项挑战中的<code>Fruits</code>成分。将两种成分<code>NonCitrus</code> <code>Fruits</code> - 首先是<code>NonCitrus</code> ,然后是<code>Citrus</code> 。这两个组件都是在后台为您提供的。接下来,将<code>Fruits</code>类组件嵌入到<code>TypesOfFood</code>组件中,位于<code>h1</code>标题下方和<code>Vegetables</code>上方。结果应该是一系列嵌套组件,它们使用两种不同的组件类型。 </section>
<add><section id='instructions'>
<add>在代码编辑器中,<code>TypesOfFood</code>组件已经渲染了一个名为<code>Vegetables</code>的组件。此外,还有上次挑战中的<code>Fruits</code>组件。
<add>在<code>Fruits</code>中嵌套两个组件,首先<code>NonCitrus</code>,然后是<code>Citrus</code>,这两个组件都是在后台为你提供的。接下来,将<code>Fruits</code>类组件嵌到<code>TypesOfFood</code>组件中,位于<code>h1</code>标题下方和<code>Vegetables</code>上方。结果应该是一系列嵌套的组件,它们使用两种不同的组件类型。
<add></section>
<ide>
<ide> ## Tests
<ide> <section id='tests'>
<ide>
<ide> ```yml
<ide> tests:
<del> - text: <code>TypesOfFood</code>组件应返回单个<code>div</code>元素。
<add> - text: <code>TypesOfFood</code>组件应该返回单个<code>div</code>元素。
<ide> testString: assert((function() { const mockedComponent = Enzyme.mount(React.createElement(TypesOfFood)); return mockedComponent.children().type() === 'div'; })());
<del> - text: <code>TypesOfFood</code>组件应返回<code>Fruits</code>组件。
<add> - text: <code>TypesOfFood</code>组件应该返回<code>Fruits</code>组件。
<ide> testString: assert((function() { const mockedComponent = Enzyme.mount(React.createElement(TypesOfFood)); return mockedComponent.children().childAt(1).name() === 'Fruits'; })());
<del> - text: <code>Fruits</code>组件应返回<code>NonCitrus</code>组件和<code>Citrus</code>组件。
<add> - text: <code>Fruits</code>组件应该返回<code>NonCitrus</code>组件和<code>Citrus</code>组件。
<ide> testString: assert((function() { const mockedComponent = Enzyme.mount(React.createElement(TypesOfFood)); return (mockedComponent.find('Fruits').children().find('NonCitrus').length === 1 && mockedComponent.find('Fruits').children().find('Citrus').length === 1); })());
<del> - text: <code>TypesOfFood</code>组件应返回<code>Fruits</code>组件下面的<code>Vegetables</code>组件。
<add> - text: <code>TypesOfFood</code>组件应该返回<code>Vegetables</code>组件,且其位于<code>Fruits</code>组件之下。
<ide> testString: assert((function() { const mockedComponent = Enzyme.mount(React.createElement(TypesOfFood)); return mockedComponent.children().childAt(2).name() === 'Vegetables'; })());
<ide>
<ide> ```
<ide> class TypesOfFood extends React.Component {
<ide> );
<ide> }
<ide> };
<del>
<ide> ```
<ide>
<ide> </div>
<ide> class Vegetables extends React.Component {
<ide> );
<ide> }
<ide> };
<del>
<ide> ```
<ide>
<ide> </div>
<ide> class Vegetables extends React.Component {
<ide> <div id='jsx-teardown'>
<ide>
<ide> ```js
<del>console.info('after the test');
<add>ReactDOM.render(<TypesOfFood />, document.getElementById('root'))
<ide> ```
<ide>
<ide> </div>
<ide> console.info('after the test');
<ide> ## Solution
<ide> <section id='solution'>
<ide>
<add>
<ide> ```js
<del>// solution required
<add>class Fruits extends React.Component {
<add> constructor(props) {
<add> super(props);
<add> }
<add> render() {
<add> return (
<add> <div>
<add> <h2>Fruits:</h2>
<add> { /* change code below this line */ }
<add> <NonCitrus />
<add> <Citrus />
<add> { /* change code above this line */ }
<add> </div>
<add> )
<add> }
<add>}
<add>
<add>class TypesOfFood extends React.Component {
<add> constructor(props) {
<add> super(props);
<add> }
<add> render() {
<add> return (
<add> <div>
<add> <h1>Types of Food:</h1>
<add> { /* change code below this line */ }
<add> <Fruits />
<add> { /* change code above this line */ }
<add> <Vegetables />
<add> </div>
<add> );
<add> }
<add>};
<ide> ```
<ide>
<del>/section>
<add></section>
<ide><path>curriculum/challenges/chinese/03-front-end-libraries/react/create-a-complex-jsx-element.chinese.md
<ide> id: 5a24bbe0dba28a8d3cbd4c5d
<ide> title: Create a Complex JSX Element
<ide> challengeType: 6
<ide> isRequired: false
<del>videoUrl: ''
<del>localeTitle: 创建一个复杂的JSX元素
<add>forumTopicId: 301382
<add>localeTitle: 创建一个复杂的 JSX 元素
<ide> ---
<ide>
<ide> ## Description
<del><section id="description">最后一个挑战是JSX的一个简单示例,但JSX也可以代表更复杂的HTML。关于嵌套JSX的一个重要事项是它必须返回一个元素。这个父元素将包装所有其他级别的嵌套元素。例如,编写为没有父包装元素的兄弟姐妹的几个JSX元素将不会转换。这是一个例子: <b>有效的JSX:</b> <blockquote> <DIV> <br> <p>第一段</ p> <br> <p>第二段</ p> <br> <p>第3段</ p> <br> </ DIV> </blockquote> <b>JSX无效:</b> <blockquote> <p>第一段</ p> <br> <p>第二段</ p> <br> <p>第3段</ p> <br></blockquote></section>
<add><section id='description'>
<add>上一个挑战是 JSX 的一个简单示例,但 JSX 也可以表示更复杂的 HTML。
<add>关于嵌套的 JSX,你需要知道的一件重要的事情,那就是它必须返回单个元素。
<add>这个父元素将包裹所有其他级别的嵌套元素。
<add>例如,几个作为兄弟元素而编写的JSX元素没有父元素包裹将不会被转换。
<add>这里是一个示例:
<add><b>有效的 JSX:</b>
<add>
<add>```jsx
<add><div>
<add> <p>Paragraph One</p>
<add> <p>Paragraph Two</p>
<add> <p>Paragraph Three</p>
<add></div>
<add>```
<add>
<add><b>无效的 JSX:</b>
<add>
<add>```jsx
<add><p>Paragraph One</p>
<add><p>Paragraph Two</p>
<add><p>Paragraph Three</p>
<add>```
<add>
<add></section>
<ide>
<ide> ## Instructions
<del><section id="instructions">定义一个新的常量<code>JSX</code> ,它呈现一个按顺序包含以下元素的<code>div</code> :一个<code>h1</code> ,一个<code>p</code>和一个包含三个<code>li</code>项的无序列表。您可以在每个元素中包含所需的任何文本。 <strong>注意:</strong>渲染多个这样的元素时,可以将它们全部括在括号中,但并不是严格要求的。另请注意,此挑战使用<code>div</code>标记将所有子元素包装在单个父元素中。如果删除<code>div</code> ,JSX将不再转换。请记住这一点,因为当您在React组件中返回JSX元素时它也将适用。 </section>
<add><section id='instructions'>
<add>定义一个新的常量<code>JSX</code>,渲染一个<code>div</code>,其中依次包含以下元素:
<add>一个<code>h1</code>,一个<code>p</code>,一个包含三个<code>li</code>项的无序列表。你可以在每个元素中包含任何你想要的文本。
<add><strong>注意:</strong> 当像这样渲染多个元素时,你可以把它们都用圆括号括起来,但是这并不是必须的。还请注意,此挑战使用<code>div</code>标签把所有子元素包裹在里面。如果删除<code>div</code>,JSX 将不会编译这些元素。请记住这一点,因为当你在 React 组件中返回 JSX 元素时它也适用。
<add></section>
<ide>
<ide> ## Tests
<ide> <section id='tests'>
<ide> tests:
<ide> testString: assert(JSX.type === 'div');
<ide> - text: <code>div</code>应该包含一个<code>p</code>标签作为第二个元素。
<ide> testString: assert(JSX.props.children[0].type === 'h1');
<del> - text: <code>div</code>应包含<code>ul</code>标记作为第三个元素。
<add> - text: <code>div</code>应该包含一个<code>ul</code>标签作为第三个元素。
<ide> testString: assert(JSX.props.children[1].type === 'p');
<del> - text: <code>div</code>应包含一个<code>h1</code>标记作为第一个元素。
<add> - text: <code>div</code>应该包含一个<code>h1</code>标签作为第一个元素。
<ide> testString: assert(JSX.props.children[2].type === 'ul');
<ide> - text: <code>ul</code>应该包含三个<code>li</code>元素。
<ide> testString: assert(JSX.props.children.filter(ele => ele.type === 'ul')[0].props.children.filter(ele => ele.type === 'li').length === 3);
<ide> tests:
<ide> <div id='jsx-teardown'>
<ide>
<ide> ```js
<del>console.info('after the test');
<add>ReactDOM.render(JSX, document.getElementById('root'))
<ide> ```
<ide>
<ide> </div>
<ide> console.info('after the test');
<ide> ## Solution
<ide> <section id='solution'>
<ide>
<add>
<ide> ```js
<del>// solution required
<add>const JSX = (
<add><div>
<add> <h1>Hello JSX!</h1>
<add> <p>Some info</p>
<add> <ul>
<add> <li>An item</li>
<add> <li>Another item</li>
<add> <li>A third item</li>
<add> </ul>
<add></div>);
<ide> ```
<ide>
<del>/section>
<add></section>
<ide><path>curriculum/challenges/chinese/03-front-end-libraries/react/create-a-component-with-composition.chinese.md
<ide> id: 5a24c314108439a4d4036164
<ide> title: Create a Component with Composition
<ide> challengeType: 6
<ide> isRequired: false
<del>videoUrl: ''
<del>localeTitle: 使用Composition创建一个Component
<add>forumTopicId: 301383
<add>localeTitle: 用组合的方式创建一个 React 组件
<ide> ---
<ide>
<ide> ## Description
<del><section id="description">现在我们来看看如何组合多个React组件。想象一下,您正在构建一个应用程序并创建了三个组件,一个<code>Navbar</code> , <code>Dashboard</code>和<code>Footer</code> 。要将这些组件组合在一起,您可以创建一个<code>App</code> <i>父</i>组件,它将这三个组件中的每一个都呈现为<i>子</i>组件。要在React组件中将组件呈现为子组件,请在JSX中包含作为自定义HTML标记编写的组件名称。例如,在<code>render</code>方法中,您可以编写: <blockquote>回来( <br> <应用> <br> <Navbar /> <br> <仪表板/> <br> <页脚/> <br> </应用> <br> ) </blockquote>当React遇到引用另一个组件的自定义HTML标记(在此示例中包含在<code>< /></code>的组件名称)时,它会在标记的位置呈现该组件的标记。这应该说明<code>App</code>组件与<code>Navbar</code> , <code>Dashboard</code>和<code>Footer</code>之间的父/子关系。 </section>
<add><section id='description'>
<add>现在我们来看看如何组合多个 React 组件。想象一下,你正在构建一个应用程序,并创建了三个组件:<code>Navbar</code>、<code>Dashboard</code>和<code>Footer</code>。
<add>要将这些组件组合在一起,你可以创建一个<code>App</code><i>父组件</i>,将这三个组件分别渲染成为<i>子组件</i>。要在 React 组件中渲染一个子组件,你需要在 JSX 中包含作为自定义 HTML 标签编写的组件名称。例如,在<code>render</code>方法中,你可以这样编写:
<add>
<add>```jsx
<add>return (
<add> <App>
<add> <Navbar />
<add> <Dashboard />
<add> <Footer />
<add> </App>
<add>)
<add>```
<add>
<add>当 React 遇到引用另一个组件的自定义 HTML 标签时(如本例所示,组件名称包含在<code>< /></code>中),它在标签的位置渲染该组件的标签。这可以说明<code>App</code>组件和<code>Navbar</code>、<code>Dashboard</code>以及<code>Footer</code>之间的父子关系。
<add></section>
<ide>
<ide> ## Instructions
<del><section id="instructions">在代码编辑器中,有一个名为<code>ChildComponent</code>的简单功能组件和一个名为<code>ParentComponent</code>的React组件。通过在<code>ParentComponent</code>呈现<code>ChildComponent</code>将两者组合在一起。确保使用正斜杠关闭<code>ChildComponent</code>标记。 <strong>注意:</strong> <code>ChildComponent</code>是使用ES6箭头函数定义的,因为这是使用React时非常常见的做法。但是,要知道这只是一个功能。如果您不熟悉箭头函数语法,请参阅JavaScript部分。 </section>
<add><section id='instructions'>
<add>在代码编辑器中,有一个名为<code>ChildComponent</code>的简单功能组件和一个名为<code>ParentComponent</code>的 React 组件。通过在<code>ParentComponent</code>中渲染<code>ChildComponent</code>来将两者组合在一起。确保使用正斜杠关闭<code>ChildComponent</code>标签。
<add><strong>注意:</strong> <code>ChildComponent</code>是使用 ES6 的箭头函数定义的,因为这是使用 React 时非常常见的做法。但是,要知道这只是一个函数。如果你不熟悉箭头函数语法,请参阅 JavaScript 部分。
<add></section>
<ide>
<ide> ## Tests
<ide> <section id='tests'>
<ide>
<ide> ```yml
<ide> tests:
<del> - text: React组件应返回单个<code>div</code>元素。
<add> - text: React 组件应该返回单个<code>div</code>元素。
<ide> testString: assert((function() { var shallowRender = Enzyme.shallow(React.createElement(ParentComponent)); return shallowRender.type() === 'div'; })());
<del> - text: 该组件应返回两个嵌套元素。
<add> - text: 组件应该返回两个嵌套的元素。
<ide> testString: assert((function() { var shallowRender = Enzyme.shallow(React.createElement(ParentComponent)); return shallowRender.children().length === 2; })());
<del> - text: 该组件应将ChildComponent作为其第二个子项返回。
<add> - text: 组件的第二个子元素应该是 ChildComponent。
<ide> testString: assert((function() { const mockedComponent = Enzyme.mount(React.createElement(ParentComponent)); return mockedComponent.find('ParentComponent').find('ChildComponent').length === 1; })());
<ide>
<ide> ```
<ide> class ParentComponent extends React.Component {
<ide> );
<ide> }
<ide> };
<del>
<ide> ```
<ide>
<ide> </div>
<ide> class ParentComponent extends React.Component {
<ide> <div id='jsx-teardown'>
<ide>
<ide> ```js
<del>console.info('after the test');
<add>ReactDOM.render(<ParentComponent />, document.getElementById('root'))
<ide> ```
<ide>
<ide> </div>
<ide> console.info('after the test');
<ide> ## Solution
<ide> <section id='solution'>
<ide>
<add>
<ide> ```js
<del>// solution required
<add>const ChildComponent = () => {
<add> return (
<add> <div>
<add> <p>I am the child</p>
<add> </div>
<add> );
<add>};
<add>
<add>class ParentComponent extends React.Component {
<add> constructor(props) {
<add> super(props);
<add> }
<add> render() {
<add> return (
<add> <div>
<add> <h1>I am the parent</h1>
<add> { /* change code below this line */ }
<add> <ChildComponent />
<add> { /* change code above this line */ }
<add> </div>
<add> );
<add> }
<add>};
<ide> ```
<ide>
<del>/section>
<add></section>
<ide><path>curriculum/challenges/chinese/03-front-end-libraries/react/create-a-controlled-form.chinese.md
<ide> id: 5a24c314108439a4d4036179
<ide> title: Create a Controlled Form
<ide> challengeType: 6
<ide> isRequired: false
<del>videoUrl: ''
<del>localeTitle: 创建受控表格
<add>forumTopicId: 301384
<add>localeTitle: 创建一个可以控制的表单
<ide> ---
<ide>
<ide> ## Description
<del><section id="description">最后一个挑战表明,React可以控制<code>input</code>和<code>textarea</code>等某些元素的内部状态,这使得它们成为受控组件。这也适用于其他表单元素,包括常规HTML <code>form</code>元素。 </section>
<add><section id='description'>
<add>上一个挑战展示了 React 能控制某些元素的内部 state,比如<code>input</code>和<code>textarea</code>,这使得这些元素成为受控组件。这也适用于其他表单元素,包括常规的 HTML 表单<code>form</code>元素。
<add></section>
<ide>
<ide> ## Instructions
<del><section id="instructions"> <code>MyForm</code>组件设置为带有提交处理程序的空<code>form</code> 。提交表单时将调用提交处理程序。我们添加了一个提交表单的按钮。您可以看到它的<code>type</code>设置为<code>submit</code>表明它是控制表单的按钮。在<code>form</code>添加<code>input</code>元素并设置其<code>value</code>和<code>onChange()</code>属性, <code>onChange()</code>一个挑战。然后,您应该完成<code>handleSubmit</code>方法,以便将组件状态属性<code>submit</code>设置为本地<code>state</code>的当前输入值。 <strong>注意:</strong>您还必须在提交处理程序中调用<code>event.preventDefault()</code> ,以防止将刷新网页的默认表单提交行为。最后,在<code>form</code>之后创建一个<code>h1</code>标记,该<code>form</code>从组件的<code>state</code>呈现<code>submit</code>值。然后,您可以键入表单并单击按钮(或按Enter键),您应该看到您的输入呈现给页面。 </section>
<add><section id='instructions'>
<add><code>MyForm</code>组件中是一个带有提交处理程序的空<code>form</code>元素,提交处理程序将在提交表单时被调用。
<add>我们增加了一个提交表单的按钮。你可以看到它的<code>type</code>被设置为<code>submit</code>,表明它是控制表单的按钮。在表单中添加<code>input</code>元素,并像上次挑战一样设置其<code>value</code>和<code>onChange()</code>属性。然后,你应该完成<code>handleSubmit</code>方法,以便将组件 state 属性<code>submit</code>设置为本地<code>state</code>下的当前输入值。
<add><strong>注意:</strong> 你还必须在提交处理程序中调用<code>event.preventDefault()</code>,以防止默认的表单提交行为刷新网页。
<add>最后,在<code>form</code>元素之后创建一个<code>h1</code>标签,该标签从组件的<code>state</code>渲染<code>submit</code>的值。然后,你可以在表单中键入任何内容,然后单击按钮(或按 enter 键),你的输入会渲染到页面上。
<add></section>
<ide>
<ide> ## Tests
<ide> <section id='tests'>
<ide>
<ide> ```yml
<ide> tests:
<del> - text: <code>MyForm</code>应该返回一个包含<code>form</code>和<code>h1</code>标记的<code>div</code>元素。表单应包含<code>input</code>和<code>button</code> 。
<add> - text: <code>MyForm</code>应该返回一个包含<code>form</code>和<code>h1</code>标签的<code>div</code>元素,其中,表单中应该包括一个<code>input</code>和一个<code>button</code>。
<ide> testString: assert((() => { const mockedComponent = Enzyme.mount(React.createElement(MyForm)); return (mockedComponent.find('div').children().find('form').length === 1 && mockedComponent.find('div').children().find('h1').length === 1 && mockedComponent.find('form').children().find('input').length === 1 && mockedComponent.find('form').children().find('button').length === 1) })());
<del> - text: <code>MyForm</code>的状态应该使用<code>input</code>和<code>submit</code>属性初始化,两者都设置为空字符串。
<add> - text: <code>MyForm</code>的 state 应该用<code>input</code>和<code>submit</code>属性初始化,且两者都为空字符串。
<ide> testString: assert(Enzyme.mount(React.createElement(MyForm)).state('input') === '' && Enzyme.mount(React.createElement(MyForm)).state('submit') === '');
<del> - text: 输入<code>input</code>元素应该更新组件状态的<code>input</code>属性。
<add> - text: <code>input</code>元素中的输入应该会更新组件中 state 的<code>input</code>属性。
<ide> testString: 'async () => { const waitForIt = (fn) => new Promise((resolve, reject) => setTimeout(() => resolve(fn()), 250)); const mockedComponent = Enzyme.mount(React.createElement(MyForm)); const _1 = () => { mockedComponent.setState({ input: '''' }); return waitForIt(() => mockedComponent.state(''input''))}; const _2 = () => { mockedComponent.find(''input'').simulate(''change'', { target: { value: ''TestInput'' }}); return waitForIt(() => ({ state: mockedComponent.state(''input''), inputVal: mockedComponent.find(''input'').props().value }))}; const before = await _1(); const after = await _2(); assert(before === '''' && after.state === ''TestInput'' && after.inputVal === ''TestInput''); }; '
<del> - text: 提交表单应该运行<code>handleSubmit</code> ,它应该将<code>submit</code>属性设置为等于当前输入的状态。
<add> - text: 提交表单应该运行<code>handleSubmit</code>,它应该将 state 中的<code>submit</code>属性设置为当前输入。
<ide> testString: 'async () => { const waitForIt = (fn) => new Promise((resolve, reject) => setTimeout(() => resolve(fn()), 250)); const mockedComponent = Enzyme.mount(React.createElement(MyForm)); const _1 = () => { mockedComponent.setState({ input: '''' }); mockedComponent.setState({submit: ''''}); mockedComponent.find(''input'').simulate(''change'', {target: {value: ''SubmitInput''}}); return waitForIt(() => mockedComponent.state(''submit''))}; const _2 = () => { mockedComponent.find(''form'').simulate(''submit''); return waitForIt(() => mockedComponent.state(''submit''))}; const before = await _1(); const after = await _2(); assert(before === '''' && after === ''SubmitInput''); };'
<del> - text: <code>h1</code>标头应该从组件的状态呈现<code>submit</code>字段的值。
<add> - text: <code>h1</code>标题应该从组件的 state 渲染<code>submit</code>字段的值。
<ide> testString: 'async () => { const waitForIt = (fn) => new Promise((resolve, reject) => setTimeout(() => resolve(fn()), 250)); const mockedComponent = Enzyme.mount(React.createElement(MyForm)); const _1 = () => { mockedComponent.setState({ input: '''' }); mockedComponent.setState({submit: ''''}); mockedComponent.find(''input'').simulate(''change'', {target: {value: ''TestInput''}}); return waitForIt(() => mockedComponent.find(''h1'').text())}; const _2 = () => { mockedComponent.find(''form'').simulate(''submit''); return waitForIt(() => mockedComponent.find(''h1'').text())}; const before = await _1(); const after = await _2(); assert(before === '''' && after === ''TestInput''); }; '
<ide>
<ide> ```
<ide> class MyForm extends React.Component {
<ide> constructor(props) {
<ide> super(props);
<ide> this.state = {
<del> input: ",
<del> submit: "
<add> input: '',
<add> submit: ''
<ide> };
<ide> this.handleChange = this.handleChange.bind(this);
<ide> this.handleSubmit = this.handleSubmit.bind(this);
<ide> class MyForm extends React.Component {
<ide> );
<ide> }
<ide> };
<del>
<ide> ```
<ide>
<ide> </div>
<ide> class MyForm extends React.Component {
<ide> <div id='jsx-teardown'>
<ide>
<ide> ```js
<del>console.info('after the test');
<add>ReactDOM.render(<MyForm />, document.getElementById('root'))
<ide> ```
<ide>
<ide> </div>
<ide> console.info('after the test');
<ide> ## Solution
<ide> <section id='solution'>
<ide>
<add>
<ide> ```js
<del>// solution required
<add>class MyForm extends React.Component {
<add> constructor(props) {
<add> super(props);
<add> this.state = {
<add> input: '',
<add> submit: ''
<add> };
<add> this.handleChange = this.handleChange.bind(this);
<add> this.handleSubmit = this.handleSubmit.bind(this);
<add> }
<add> handleChange(event) {
<add> this.setState({
<add> input: event.target.value
<add> });
<add> }
<add> handleSubmit(event) {
<add> event.preventDefault()
<add> this.setState({
<add> submit: this.state.input
<add> });
<add> }
<add> render() {
<add> return (
<add> <div>
<add> <form onSubmit={this.handleSubmit}>
<add> <input
<add> value={this.state.input}
<add> onChange={this.handleChange} />
<add> <button type='submit'>Submit!</button>
<add> </form>
<add> <h1>{this.state.submit}</h1>
<add> </div>
<add> );
<add> }
<add>};
<ide> ```
<ide>
<del>/section>
<add></section>
<ide><path>curriculum/challenges/chinese/03-front-end-libraries/react/create-a-controlled-input.chinese.md
<ide> id: 5a24c314108439a4d4036178
<ide> title: Create a Controlled Input
<ide> challengeType: 6
<ide> isRequired: false
<del>videoUrl: ''
<del>localeTitle: 创建受控输入
<add>forumTopicId: 301385
<add>localeTitle: 创建一个可以控制的输入框
<ide> ---
<ide>
<ide> ## Description
<del><section id="description">您的应用程序可能在<code>state</code>和呈现的UI之间进行更复杂的交互。例如,用于文本输入的表单控件元素(例如<code>input</code>和<code>textarea</code>在用户键入时在DOM中维护它们自己的状态。使用React,您可以将此可变状态移动到React组件的<code>state</code> 。用户的输入成为应用程序<code>state</code>一部分,因此React控制该输入字段的值。通常,如果React组件具有用户可以键入的输入字段,则它将是受控输入表单。 </section>
<add><section id='description'>
<add>你的应用程序可能在<code>state</code>和渲染的 UI 之间有更复杂的交互。例如,用于文本输入的表单控件元素(如<code>input</code>和<code>textarea</code>)在用户键入时在 DOM 中维护自己的 state。通过 React,你可以将这种可变 state 转移到 React 组件的<code>state</code>中。用户的输入变成了应用程序<code>state</code>的一部分,因此 React 控制该输入字段的值。通常,如果你的 React 组件具有用户可以键入的输入字段,那么它将是一个受控的输入表单。
<add></section>
<ide>
<ide> ## Instructions
<del><section id="instructions">代码编辑器具有名为<code>ControlledInput</code>的组件的骨架,以创建受控<code>input</code>元素。组件的<code>state</code>已经使用包含空字符串的<code>input</code>属性进行初始化。此值表示用户在<code>input</code>字段中键入的文本。首先,创建一个名为<code>handleChange()</code>的方法,该方法具有一个名为<code>event</code>的参数。调用该方法时,它会接收一个<code>event</code>对象,该对象包含<code>input</code>元素中的一串文本。您可以使用方法内的<code>event.target.value</code>访问此字符串。使用此新字符串更新组件<code>state</code>的<code>input</code>属性。在render方法中,在<code>h4</code>标记上方创建<code>input</code>元素。添加一个<code>value</code>属性,该属性等于组件<code>state</code>的<code>input</code>属性。然后将<code>onChange()</code>事件处理程序集添加到<code>handleChange()</code>方法。当您在输入框中键入时,该文本由<code>handleChange()</code>方法处理,设置为本地<code>state</code>的<code>input</code>属性,并在页面的<code>input</code>框中呈现为值。组件<code>state</code>是关于输入数据的单一事实来源。最后但并非最不重要的是,不要忘记在构造函数中添加必要的绑定。 </section>
<add><section id='instructions'>
<add>代码编辑器具有一个名为<code>ControlledInput</code>的组件框架,用于创建受控的<code>input</code>元素。组件的<code>state</code>已经被包含空字符串的<code>input</code>属性初始化。此值表示用户在<code>input</code>字段中键入的文本。
<add>首先,创建一个名为<code>handleChange()</code>的方法,该方法具有一个名为<code>event</code>的参数。方法被调用时,它接收一个<code>event</code>对象,该对象包含一个来自<code>input</code>元素的字符串文本。你可以使用方法内的<code>event.target.value</code>来访问这个字符串。用这个新字符串更新组件的<code>state</code>的<code>input</code>属性。
<add>在 render 方法中,在<code>h4</code>标签之上创建<code>input</code>元素。添加一个<code>value</code>属性,它等于组件的<code>state</code>的<code>input</code>属性。然后将<code>onChange()</code>事件处理程序设置到<code>handleChange()</code>方法。
<add>在输入框中键入时,该文本由<code>handleChange()</code>方法处理,该文本被设置为本地<code>state</code>中的<code>input</code>属性,并渲染在页面上的<code>input</code>框中。组件<code>state</code>是输入数据的唯一真实来源。
<add>最后也是最重要的,不要忘记在构造函数中添加必要的绑定。
<add></section>
<ide>
<ide> ## Tests
<ide> <section id='tests'>
<ide>
<ide> ```yml
<ide> tests:
<del> - text: <code>ControlledInput</code>应返回包含<code>input</code>和<code>p</code>标记的<code>div</code>元素。
<add> - text: <code>ControlledInput</code>应该返回包含一个<code>input</code>标签和<code>p</code>标签的<code>div</code>元素。
<ide> testString: assert(Enzyme.mount(React.createElement(ControlledInput)).find('div').children().find('input').length === 1 && Enzyme.mount(React.createElement(ControlledInput)).find('div').children().find('p').length === 1);
<del> - text: <code>ControlledInput</code>的状态应该初始化, <code>input</code>属性设置为空字符串。
<add> - text: <code>ControlledInput</code>的 state 应该使用设置为空字符串的<code>input</code>属性初始化。
<ide> testString: assert.strictEqual(Enzyme.mount(React.createElement(ControlledInput)).state('input'), '');
<del> - text: 输入input元素应更新输入的状态和值, <code>p</code>元素应在键入时呈现此状态。
<add> - text: input 元素中的键入值应该更新 input 的 state 和值,并且<code>p</code>元素应该在输入时呈现 state。
<ide> testString: 'async () => { const waitForIt = (fn) => new Promise((resolve, reject) => setTimeout(() => resolve(fn()), 250)); const mockedComponent = Enzyme.mount(React.createElement(ControlledInput)); const _1 = () => { mockedComponent.setState({ input: '''' }); return waitForIt(() => mockedComponent.state(''input''))}; const _2 = () => { mockedComponent.find(''input'').simulate(''change'', { target: { value: ''TestInput'' }}); return waitForIt(() => ({ state: mockedComponent.state(''input''), text: mockedComponent.find(''p'').text(), inputVal: mockedComponent.find(''input'').props().value }))}; const before = await _1(); const after = await _2(); assert(before === '''' && after.state === ''TestInput'' && after.text === ''TestInput'' && after.inputVal === ''TestInput''); }; '
<ide>
<ide> ```
<ide> class ControlledInput extends React.Component {
<ide> constructor(props) {
<ide> super(props);
<ide> this.state = {
<del> input: "
<add> input: ''
<ide> };
<ide> // change code below this line
<ide>
<ide> class ControlledInput extends React.Component {
<ide> );
<ide> }
<ide> };
<del>
<ide> ```
<ide>
<ide> </div>
<ide> class ControlledInput extends React.Component {
<ide> <div id='jsx-teardown'>
<ide>
<ide> ```js
<del>console.info('after the test');
<add>ReactDOM.render(<ControlledInput />, document.getElementById('root'))
<ide> ```
<ide>
<ide> </div>
<ide> console.info('after the test');
<ide> ## Solution
<ide> <section id='solution'>
<ide>
<add>
<ide> ```js
<del>// solution required
<add>class ControlledInput extends React.Component {
<add> constructor(props) {
<add> super(props);
<add> this.state = {
<add> input: ''
<add> };
<add> this.handleChange = this.handleChange.bind(this);
<add> }
<add> handleChange(event) {
<add> this.setState({
<add> input: event.target.value
<add> });
<add> }
<add> render() {
<add> return (
<add> <div>
<add> <input
<add> value={this.state.input}
<add> onChange={this.handleChange} />
<add> <h4>Controlled Input:</h4>
<add>
<add> <p>{this.state.input}</p>
<add> </div>
<add> );
<add> }
<add>};
<ide> ```
<ide>
<del>/section>
<add></section>
<ide><path>curriculum/challenges/chinese/03-front-end-libraries/react/create-a-react-component.chinese.md
<ide> id: 5a24c314108439a4d4036163
<ide> title: Create a React Component
<ide> challengeType: 6
<ide> isRequired: false
<del>videoUrl: ''
<del>localeTitle: 创建一个React组件
<add>forumTopicId: 301386
<add>localeTitle: 创建一个 React 组件
<ide> ---
<ide>
<ide> ## Description
<del><section id="description">定义React组件的另一种方法是使用ES6 <code>class</code>语法。在以下示例中, <code>Kitten</code>扩展了<code>React.Component</code> : <blockquote> class Kitten扩展了React.Component { <br>构造函数(道具){ <br>超级(道具); <br> } <br><br> render(){ <br>回来( <br> <H1>,您好</ H1> <br> ); <br> } <br> } </blockquote>这将创建一个扩展<code>React.Component</code>类的ES6类<code>Kitten</code> 。因此, <code>Kitten</code>类现在可以访问许多有用的React功能,例如本地状态和生命周期钩子。如果您还不熟悉这些术语,请不要担心,在以后的挑战中将更详细地介绍它们。另请注意, <code>Kitten</code>类在其中定义了一个调用<code>super()</code>的<code>constructor</code>函数。它使用<code>super()</code>来调用父类的构造函数,在本例中为<code>React.Component</code> 。构造函数是在使用<code>class</code>关键字创建的对象初始化期间使用的特殊方法。最好用<code>super</code>调用组件的<code>constructor</code> ,并将<code>props</code>传递给它们。这可确保组件正确初始化。现在,请知道包含此代码是标准的。很快你会看到构造函数和<code>props</code>其他用途。 </section>
<add><section id='description'>
<add>定义 React 组件的另一种方法是使用 ES6 的<code>class</code>语法。在以下示例中,<code>Kitten</code>扩展了<code>React.Component</code>:
<add>
<add>```jsx
<add>class Kitten extends React.Component {
<add> constructor(props) {
<add> super(props);
<add> }
<add>
<add> render() {
<add> return (
<add> <h1>Hi</h1>
<add> );
<add> }
<add>}
<add>```
<add>
<add>这将创建一个 ES6 类<code>Kitten</code>,它扩展了<code>React.Component</code>类。因此,<code>Kitten</code>类现在可以访问许多有用的 React 功能,例如本地状态和生命周期钩子。如果你还不熟悉这些术语,请不要担心,在以后的挑战中我们将更详细地介绍它们。
<add>另请注意,<code>Kitten</code>类中定义了一个调用<code>super()</code>方法的<code>constructor</code>。它使用<code>super()</code>调用父类的构造函数,即本例中的<code>React.Component</code>。构造函数是使用<code>class</code>关键字创建的特殊方法,它用在实例初始化之前。最佳做法是在组件的<code>constructor</code>里调用<code>super</code>,并将<code>props</code>传递给它们,这样可以保证组件能够正确地初始化。现在,你只需要知道这是标准的做法。很快你会看到构造函数的其他用途以及<code>props</code>。
<add></section>
<ide>
<ide> ## Instructions
<del><section id="instructions"> <code>MyComponent</code>是使用类语法在代码编辑器中定义的。完成编写<code>render</code>方法,以便返回包含带有文本<code>Hello React!</code>的<code>h1</code>的<code>div</code>元素<code>Hello React!</code> 。 </section>
<add><section id='instructions'>
<add><code>MyComponent</code>是使用类语法在代码编辑器中定义的。完成<code>render</code>方法的编写,使其返回<code>div</code>元素,其中包含文本内容为<code>Hello React!</code>的<code>h1</code>元素。
<add></section>
<ide>
<ide> ## Tests
<ide> <section id='tests'>
<ide>
<ide> ```yml
<ide> tests:
<del> - text: React组件应返回<code>div</code>元素。
<add> - text: 该 React 组件应该返回一个<code>div</code>元素。
<ide> testString: assert(Enzyme.shallow(React.createElement(MyComponent)).type() === 'div');
<del> - text: 返回的<code>div</code>应该在其中呈现一个<code>h1</code>头。
<add> - text: 返回的<code>div</code>中应该渲染一个<code>h1</code>标题。
<ide> testString: assert(/<div><h1>.*<\/h1><\/div>/.test(Enzyme.shallow(React.createElement(MyComponent)).html()));
<del> - text: <code>h1</code>标头应该包含字符串<code>Hello React!</code> 。
<add> - text: <code>h1</code>标题中应该包含字符串<code>Hello React!</code>。
<ide> testString: assert(Enzyme.shallow(React.createElement(MyComponent)).html() === '<div><h1>Hello React!</h1></div>');
<ide>
<ide> ```
<ide> tests:
<ide> <div id='jsx-seed'>
<ide>
<ide> ```jsx
<add>
<ide> class MyComponent extends React.Component {
<ide> constructor(props) {
<ide> super(props);
<ide> class MyComponent extends React.Component {
<ide> // change code above this line
<ide> }
<ide> };
<del>
<ide> ```
<ide>
<ide> </div>
<ide> class MyComponent extends React.Component {
<ide> <div id='jsx-teardown'>
<ide>
<ide> ```js
<del>console.info('after the test');
<add>ReactDOM.render(<MyComponent />, document.getElementById('root'))
<ide> ```
<ide>
<ide> </div>
<ide> console.info('after the test');
<ide> ## Solution
<ide> <section id='solution'>
<ide>
<add>
<ide> ```js
<del>// solution required
<add>class MyComponent extends React.Component {
<add> constructor(props) {
<add> super(props);
<add> }
<add> render() {
<add> // change code below this line
<add> return (
<add> <div>
<add> <h1>Hello React!</h1>
<add> </div>
<add> );
<add> // change code above this line
<add> }
<add>};
<ide> ```
<ide>
<del>/section>
<add></section>
<ide><path>curriculum/challenges/chinese/03-front-end-libraries/react/create-a-simple-jsx-element.chinese.md
<ide> id: 587d7dbc367417b2b2512bb1
<ide> title: Create a Simple JSX Element
<ide> challengeType: 6
<ide> isRequired: false
<del>videoUrl: ''
<del>localeTitle: 创建一个简单的JSX元素
<add>forumTopicId: 301390
<add>localeTitle: 创建一个简单的 JSX 元素
<ide> ---
<ide>
<ide> ## Description
<del><section id="description"> <strong>简介:</strong> React是由Facebook创建和维护的开源视图库。它是渲染现代Web应用程序的用户界面(UI)的绝佳工具。 React使用名为JSX的JavaScript语法扩展,允许您直接在JavaScript中编写HTML。这有几个好处。它允许您在HTML中使用JavaScript的完整程序功能,并有助于保持代码的可读性。在大多数情况下,JSX类似于您已经学过的HTML,但是在这些挑战中将会涉及一些关键差异。例如,因为JSX是JavaScript的语法扩展,所以您实际上可以直接在JSX中编写JavaScript。要做到这一点,您只需在花括号中包含您希望被视为<code>{ 'this is treated as JavaScript code' }</code> : <code>{ 'this is treated as JavaScript code' }</code> 。记住这一点,因为它用于未来的几个挑战。但是,由于JSX不是有效的JavaScript,因此必须将JSX代码编译为JavaScript。转换器Babel是这个过程的流行工具。为了您的方便,它已经在幕后为这些挑战添加。如果您碰巧编写语法无效的JSX,您将看到这些挑战中的第一个测试失败。值得注意的是,在引擎盖下,挑战是调用<code>ReactDOM.render(JSX, document.getElementById('root'))</code> 。这个函数调用是将JSX置于React自己的DOM轻量级表示中的原因。然后,React使用自己的DOM快照来优化仅更新实际DOM的特定部分。 </section>
<add><section id='description'>
<add><strong>简介:</strong>React 是由 Facebook 创建和维护的开源视图库。它是渲染当代 Web 应用程序用户界面(UI)的绝佳工具。
<add>React 使用名为 JSX 的 JavaScript 语法扩展,允许你直接在 JavaScript 中编写 HTML。这有几个好处。它允许你在 HTML 中使用 JavaScript 的完整程序功能,并有助于保持代码的可读性。在大多数情况下,JSX 类似于你已经学过的 HTML,但是在这些挑战中将会涉及一些关键差异。
<add>例如,因为 JSX 是 JavaScript 的语法扩展,所以你实际上可以直接在 JSX 中编写 JavaScript。要做到这一点,你只需在花括号中包含你希望被视为 JavaScript 的代码:<code>{“这被视为 JavaScript 代码”}</code>。请牢记这个写法,你将会在接下来的挑战中使用。
<add>但是,由于浏览器不能解析 JSX,因此必须将 JSX 代码编译为 JavaScript。在这个过程中,转换器 Babel 是一个很受欢迎的工具。后续挑战已经在后台引入了 Babel,你可以直接写 JSX 代码。如果你的代码不符合 JSX 语法,那么挑战中的第一个测试就不会通过。
<add>值得注意的是,这些挑战在底层调用<code>ReactDOM.render(JSX, document.getElementById('root'))</code>。这个函数调用是将你的 JSX 置于 React 自己的轻量级 DOM 中。然后,React 使用自己的 DOM 快照来优化更新实际 DOM 的特定部分。
<add></section>
<ide>
<ide> ## Instructions
<del><section id="instructions"> <strong>说明:</strong>当前代码使用JSX将<code>div</code>元素分配给常量<code>JSX</code> 。用<code>h1</code>元素替换<code>div</code>并添加文本<code>Hello JSX!</code>在里面。 </section>
<add><section id='instructions'>
<add><strong>说明:</strong>当前代码使用 JSX 将<code>div</code>元素赋值给常量<code>JSX</code>。将<code>div</code>替换为<code>h1</code>元素,并在其中添加文本<code>Hello JSX!</code>。
<add></section>
<ide>
<ide> ## Tests
<ide> <section id='tests'>
<ide> localeTitle: 创建一个简单的JSX元素
<ide> tests:
<ide> - text: 常量<code>JSX</code>应该返回一个<code>h1</code>元素。
<ide> testString: assert(JSX.type === 'h1');
<del> - text: <code>h1</code>标签应该包含文本<code>Hello JSX!</code>
<add> - text: <code>h1</code>标签应该包含文本<code>Hello JSX!</code>。
<ide> testString: assert(Enzyme.shallow(JSX).contains('Hello JSX!'));
<ide>
<ide> ```
<ide> tests:
<ide> <div id='jsx-seed'>
<ide>
<ide> ```jsx
<add>
<ide> const JSX = <div></div>;
<ide>
<ide> ```
<ide> const JSX = <div></div>;
<ide> <div id='jsx-teardown'>
<ide>
<ide> ```js
<del>console.info('after the test');
<add>ReactDOM.render(JSX, document.getElementById('root'))
<ide> ```
<ide>
<ide> </div>
<ide> console.info('after the test');
<ide> ## Solution
<ide> <section id='solution'>
<ide>
<add>
<ide> ```js
<del>// solution required
<add>const JSX = <h1>Hello JSX!</h1>;
<ide> ```
<ide>
<del>/section>
<add></section>
<ide><path>curriculum/challenges/chinese/03-front-end-libraries/react/create-a-stateful-component.chinese.md
<ide> id: 5a24c314108439a4d4036170
<ide> title: Create a Stateful Component
<ide> challengeType: 6
<ide> isRequired: false
<del>videoUrl: ''
<del>localeTitle: 创建一个有状态组件
<add>forumTopicId: 301391
<add>localeTitle: 创建一个有状态的组件
<ide> ---
<ide>
<ide> ## Description
<del><section id="description"> React最重要的主题之一是<code>state</code> 。 State包含应用程序需要了解的任何数据,这些数据可能会随时间而变化。您希望应用程序响应状态更改并在必要时显示更新的UI。 React为现代Web应用程序的状态管理提供了一个很好的解决方案。您可以通过在<code>constructor</code>声明组件类的<code>state</code>属性来在React组件中创建状态。这与初始化该组件<code>state</code>被创建时。 <code>state</code>属性必须设置为JavaScript <code>object</code> 。声明它看起来像这样: <blockquote> this.state = { <br> //在这里描述你的州<br>您可以在组件的整个生命周期内访问<code>state</code>对象。您可以更新它,在UI中呈现它,并将其作为道具传递给子组件。 <code>state</code>对象可以像您需要的那样复杂或简单。请注意,您必须通过扩展<code>React.Component</code>来创建类组件,以便创建这样的<code>state</code> 。 </blockquote></section>
<add><section id='description'>
<add>React中最重要的主题之一是<code>state</code>。 state 包含应用程序需要了解的任何数据,这些数据可能会随时间而变化。你希望应用程序能够响应 state 的变更,并在必要时显示更新后的 UI。React 为现代 Web 应用程序的状态管理提供了一个很好的解决方案。
<add>你可以通过在<code>constructor</code>中的组件类上声明<code>state</code>属性来在 React 组件中创建 state,它在创建时使用<code>state</code>初始化组件。<code>state</code>属性必须设置为 JavaScript<code>对象</code>。声明如下:
<add>
<add>```jsx
<add>this.state = {
<add> // describe your state here
<add>}
<add>```
<add>
<add>你可以在组件的整个生命周期内访问<code>state</code>对象,你可以更新它、在 UI 中渲染它,也可以将其作为 props 传递给子组件。<code>state</code>对象的使用可以很简单,亦可以很复杂,就看你怎么用了。请注意,你必须通过扩展<code>React.Component</code>来创建类组件,以便像这样创建<code>state</code>。
<add></section>
<ide>
<ide> ## Instructions
<del><section id="instructions">代码编辑器中有一个组件试图从其<code>state</code>呈现<code>name</code>属性。但是,没有定义<code>state</code> 。初始化与组件<code>state</code>的<code>constructor</code> ,并指定你的名字的属性<code>name</code> 。 </section>
<add><section id='instructions'>
<add>代码编辑器中有一个组件试图从其<code>state</code>中渲染一个<code>name</code>属性,但是<code>state</code>还没有定义。在<code>constructor</code>中使用<code>state</code>初始化组件,并将你的名字赋给<code>name</code>属性。
<add></section>
<ide>
<ide> ## Tests
<ide> <section id='tests'>
<ide>
<ide> ```yml
<ide> tests:
<del> - text: <code>StatefulComponent</code>应该存在并呈现。
<add> - text: <code>StatefulComponent</code>应该存在并被渲染。
<ide> testString: assert((function() { const mockedComponent = Enzyme.mount(React.createElement(StatefulComponent)); return mockedComponent.find('StatefulComponent').length === 1; })());
<del> - text: <code>StatefulComponent</code>应该呈现<code>div</code>和<code>h1</code>元素。
<add> - text: <code>StatefulComponent</code>应该渲染一个<code>div</code>元素和一个<code>h1</code>元素。
<ide> testString: assert((function() { const mockedComponent = Enzyme.mount(React.createElement(StatefulComponent)); return mockedComponent.find('div').length === 1 && mockedComponent.find('h1').length === 1; })());
<del> - text: 应使用设置为字符串的属性<code>name</code>初始化<code>StatefulComponent</code> 。
<add> - text: 应使用被设置为字符串的<code>name</code>属性来初始化<code>StatefulComponent</code>的 state。
<ide> testString: assert((function() { const mockedComponent = Enzyme.mount(React.createElement(StatefulComponent)); const initialState = mockedComponent.state(); return ( typeof initialState === 'object' && typeof initialState.name === 'string'); })());
<del> - text: <code>StatefulComponent</code>的属性<code>name</code>应在<code>h1</code>元素中呈现。
<add> - text: <code>StatefulComponent</code>中 state 的<code>name</code>属性应该渲染在<code>h1</code>元素里。
<ide> testString: assert((function() { const mockedComponent = Enzyme.mount(React.createElement(StatefulComponent)); const initialState = mockedComponent.state(); return mockedComponent.find('h1').text() === initialState.name; })());
<ide>
<ide> ```
<ide> tests:
<ide> <div id='jsx-seed'>
<ide>
<ide> ```jsx
<add>
<ide> class StatefulComponent extends React.Component {
<ide> constructor(props) {
<ide> super(props);
<ide> class StatefulComponent extends React.Component {
<ide> );
<ide> }
<ide> };
<del>
<ide> ```
<ide>
<ide> </div>
<ide> class StatefulComponent extends React.Component {
<ide> <div id='jsx-teardown'>
<ide>
<ide> ```js
<del>console.info('after the test');
<add>ReactDOM.render(<StatefulComponent />, document.getElementById('root'))
<ide> ```
<ide>
<ide> </div>
<ide> console.info('after the test');
<ide> ## Solution
<ide> <section id='solution'>
<ide>
<add>
<ide> ```js
<del>// solution required
<add>class StatefulComponent extends React.Component {
<add> constructor(props) {
<add> super(props);
<add> this.state = {
<add> name: 'freeCodeCamp!'
<add> }
<add> }
<add> render() {
<add> return (
<add> <div>
<add> <h1>{this.state.name}</h1>
<add> </div>
<add> );
<add> }
<add>};
<ide> ```
<ide>
<del>/section>
<add></section>
<ide><path>curriculum/challenges/chinese/03-front-end-libraries/react/create-a-stateless-functional-component.chinese.md
<ide> id: 5a24c314108439a4d4036162
<ide> title: Create a Stateless Functional Component
<ide> challengeType: 6
<ide> isRequired: false
<del>videoUrl: ''
<del>localeTitle: 创建无状态功能组件
<add>forumTopicId: 301392
<add>localeTitle: 创建一个无状态的函数组件
<ide> ---
<ide>
<ide> ## Description
<del><section id="description">组件是React的核心。 React中的所有内容都是一个组件,在这里您将学习如何创建一个组件。有两种方法可以创建React组件。第一种方法是使用JavaScript函数。以这种方式定义组件会创建<em>无状态功能组件</em> 。应用程序中的状态概念将在以后的挑战中介绍。现在,将无状态组件视为可以接收数据并对其进行渲染的组件,但不管理或跟踪对该数据的更改。 (我们将介绍在下一个挑战中创建React组件的第二种方法。)要创建一个带有函数的组件,您只需编写一个返回JSX或<code>null</code>的JavaScript函数。需要注意的一件重要事情是,React要求您的函数名称以大写字母开头。这是一个在JSX中分配HTML类的无状态功能组件的示例: <blockquote> //被转换后,<div>将有一个CSS类'customClass' <br> const DemoComponent = function(){ <br>回来( <br> <div className ='customClass'/> <br> ); <br> }; </blockquote>因为JSX组件代表HTML,所以您可以将几个组件放在一起以创建更复杂的HTML页面。这是React提供的组件架构的关键优势之一。它允许您从许多独立的,独立的组件中组合UI。这使得构建和维护复杂的用户界面变得更加容易。 </section>
<add><section id='description'>
<add>组件是 React 的核心。React 中的所有内容都是一个组件,在这里你将学习如何创建一个组件。
<add>有两种方法可以创建 React 组件。第一种方法是使用 JavaScript 函数。以这种方式定义组件会创建<em>无状态功能组件</em>。应用程序中的状态概念将在以后的挑战中介绍。目前,可以将无状态组件视为可以接收数据并对其进行渲染的组件,但是它不管理或跟踪对数据的更改,我们将在下一次挑战中介绍创建 React 组件的第二种方法。
<add>要用函数创建组件,只需编写一个返回 JSX 或<code>null</code>的 JavaScript 函数。需要注意的一点是,React 要求你的函数名以大写字母开头。下面是一个无状态功能组件的示例,该组件在 JSX 中分配一个 HTML 的 class:
<add>
<add>```jsx
<add>// After being transpiled, the <div> will have a CSS class of 'customClass'
<add>const DemoComponent = function() {
<add> return (
<add> <div className='customClass' />
<add> );
<add>};
<add>```
<add>
<add>因为 JSX 组件代表 HTML,所以你可以将几个组件放在一起以创建更复杂的 HTML 页面,这是 React 提供的组件架构的关键优势之一,它允许你用许多独立的组件组成 UI。这使得构建和维护复杂的用户界面变得更加容易。
<add></section>
<ide>
<ide> ## Instructions
<del><section id="instructions">代码编辑器有一个名为<code>MyComponent</code>的函数。完成此函数,以便返回包含一些文本字符串的单个<code>div</code>元素。 <strong>注意:</strong>该文本被视为<code>div</code>元素的子元素,因此您将无法使用自闭合标记。 </section>
<add><section id='instructions'>
<add>代码编辑器中有一个名为<code>MyComponent</code>的函数。完成此函数,使其返回包含一些文本字符串的单个<code>div</code>元素。
<add><strong>注意:</strong> 文本被视为是<code>div</code>的子元素,因此你将不能使用自闭合标签。
<add></section>
<ide>
<ide> ## Tests
<ide> <section id='tests'>
<ide>
<ide> ```yml
<ide> tests:
<del> - text: <code>MyComponent</code>应该返回JSX。
<add> - text: <code>MyComponent</code>应该返回 JSX。
<ide> testString: assert((function() { const mockedComponent = Enzyme.mount(React.createElement(MyComponent)); return mockedComponent.length === 1; })());
<ide> - text: <code>MyComponent</code>应该返回一个<code>div</code>元素。
<ide> testString: assert((function() { const mockedComponent = Enzyme.mount(React.createElement(MyComponent)); return mockedComponent.children().type() === 'div' })());
<del> - text: <code>div</code>元素应包含一串文本。
<add> - text: <code>div</code>元素应该包含一个文本字符串。
<ide> testString: assert((function() { const mockedComponent = Enzyme.mount(React.createElement(MyComponent)); return mockedComponent.find('div').text() !== ''; })());
<ide>
<ide> ```
<ide> const MyComponent = function() {
<ide>
<ide> // change code above this line
<ide> }
<del>
<ide> ```
<ide>
<ide> </div>
<ide> const MyComponent = function() {
<ide> <div id='jsx-teardown'>
<ide>
<ide> ```js
<del>console.info('after the test');
<add>ReactDOM.render(<MyComponent />, document.getElementById('root'))
<ide> ```
<ide>
<ide> </div>
<ide> console.info('after the test');
<ide> ## Solution
<ide> <section id='solution'>
<ide>
<add>
<ide> ```js
<del>// solution required
<add>const MyComponent = function() {
<add> // change code below this line
<add> return (
<add> <div>
<add> Demo Solution
<add> </div>
<add> );
<add> // change code above this line
<add>}
<ide> ```
<ide>
<del>/section>
<add></section>
<ide><path>curriculum/challenges/chinese/03-front-end-libraries/react/define-an-html-class-in-jsx.chinese.md
<ide> id: 5a24c314108439a4d4036160
<ide> title: Define an HTML Class in JSX
<ide> challengeType: 6
<ide> isRequired: false
<del>videoUrl: ''
<del>localeTitle: 在JSX中定义HTML类
<add>forumTopicId: 301393
<add>localeTitle: 在 JSX 中定义一个 HTML Class
<ide> ---
<ide>
<ide> ## Description
<del><section id="description">现在您已经开始编写JSX了,您可能想知道它与HTML的区别。到目前为止,似乎HTML和JSX完全相同。 JSX的一个关键区别是你不能再使用单词<code>class</code>来定义HTML类。这是因为<code>class</code>是JavaScript中的保留字。相反,JSX使用<code>className</code> 。事实上,JSX中所有HTML属性和事件引用的命名约定都变成了camelCase。例如,JSX中的单击事件是<code>onClick</code> ,而不是<code>onclick</code> 。同样, <code>onchange</code>变为<code>onChange</code> 。虽然这是一个微妙的差异,但重要的是要记住前进。 </section>
<add><section id='description'>
<add>现在你已经习惯了编写 JSX,你可能想知道它与 HTML 有什么不同。
<add>到目前为止,HTML 和 JSX 似乎完全相同。
<add>JSX 的一个关键区别是你不能再使用<code>class</code>这个单词来定义 HTML 的 class 名。这是因为<code>class</code>是 JavaScript 中的关键字。JSX 使用<code>className</code>代替。
<add>事实上,JSX 中所有 HTML 属性和事件引用的命名约定都变成了驼峰式。例如,JSX 中的单击事件是 <code>onClick</code>,而不是 <code>onclick</code>。同样,<code>onchange</code>变成了<code>onChange</code>。虽然这是一个微妙的差异,但请你一定要记住。
<add></section>
<ide>
<ide> ## Instructions
<del><section id="instructions">将一个<code>myDiv</code>类<code>myDiv</code> JSX代码中提供的<code>div</code> 。 </section>
<add><section id='instructions'>
<add>将 class<code>myDiv</code> 应用于 JSX 提供的<code>div</code>上。
<add></section>
<ide>
<ide> ## Tests
<ide> <section id='tests'>
<ide> localeTitle: 在JSX中定义HTML类
<ide> tests:
<ide> - text: 常量<code>JSX</code>应该返回一个<code>div</code>元素。
<ide> testString: assert.strictEqual(JSX.type, 'div');
<del> - text: <code>div</code>有一类<code>myDiv</code> 。
<add> - text: <code>div</code>有一个<code>myDiv</code>class。
<ide> testString: assert.strictEqual(JSX.props.className, 'myDiv');
<ide>
<ide> ```
<ide> const JSX = (
<ide> <h1>Add a class to this div</h1>
<ide> </div>
<ide> );
<del>
<ide> ```
<ide>
<ide> </div>
<ide> const JSX = (
<ide> <div id='jsx-teardown'>
<ide>
<ide> ```js
<del>console.info('after the test');
<add>ReactDOM.render(JSX, document.getElementById('root'))
<ide> ```
<ide>
<ide> </div>
<ide> console.info('after the test');
<ide> ## Solution
<ide> <section id='solution'>
<ide>
<add>
<ide> ```js
<del>// solution required
<add>const JSX = (
<add><div className = 'myDiv'>
<add> <h1>Add a class to this div</h1>
<add></div>);
<ide> ```
<ide>
<del>/section>
<add></section>
<ide><path>curriculum/challenges/chinese/03-front-end-libraries/react/give-sibling-elements-a-unique-key-attribute.chinese.md
<ide> id: 5a24c314108439a4d403618b
<ide> title: Give Sibling Elements a Unique Key Attribute
<ide> challengeType: 6
<ide> isRequired: false
<del>videoUrl: ''
<del>localeTitle: 为兄弟元素提供唯一的键属性
<add>forumTopicId: 301394
<add>localeTitle: 给同级元素一个唯一的键属性
<ide> ---
<ide>
<ide> ## Description
<del><section id="description">最后一项挑战展示了如何使用<code>map</code>方法根据用户输入动态呈现多个元素。但是,这个例子中缺少一个重要的部分。创建元素数组时,每个元素都需要将<code>key</code>属性设置为唯一值。 React使用这些键来跟踪添加,更改或删除的项目。当以任何方式修改列表时,这有助于使重新呈现过程更有效。请注意,键只需要在兄弟元素之间是唯一的,它们在您的应用程序中不需要是全局唯一的。 </section>
<add><section id='description'>
<add>上一个挑战展示了如何使用<code>map</code>方法根据用户输入动态渲染多个元素。然而,这个例子中缺少一个重要的部分。创建元素数组时,每个元素都需要一个设置为唯一值的<code>key</code>属性。React 使用这些键来跟踪哪些项目被添加、更改或删除。这有助于在以任何方式修改列表时提高重新渲染过程的效率。请注意,键只需要在同级元素之间是唯一的,它们不需要在应用程序中是全局唯一的。
<add></section>
<ide>
<ide> ## Instructions
<del><section id="instructions">代码编辑器有一个包含一些前端框架的数组和一个名为<code>Frameworks()</code>的无状态功能组件。 <code>Frameworks()</code>需要将数组映射到无序列表,就像上一次挑战一样。完成编写<code>map</code>回调以返回<code>frontEndFrameworks</code>数组中每个框架的<code>li</code>元素。这一次,请确保为每个<code>li</code>一个<code>key</code>属性,设置为唯一值。通常,您希望使键成为唯一标识要呈现的元素的键。作为最后的手段,可以使用数组索引,但通常您应该尝试使用唯一标识。 </section>
<add><section id='instructions'>
<add>代码编辑器有一个数组,它包含一些前端框架和一个名为<code>Frameworks()</code>的无状态函数组件。<code>Frameworks()</code>需要将数组映射到无序列表,就像上一个挑战一样。完成<code>map</code>回调,为<code>frontEndFrameworks</code>数组中的每个框架返回一个<code>li</code>元素。这次,确保给每个<code>li</code>的<code>key</code>属性设置一个唯一的值。
<add>通常,你希望使 key 能唯一标识要渲染的元素。作为最后的手段,可以使用数组索引,但通常你应该尝试使用唯一标识。
<add></section>
<ide>
<ide> ## Tests
<ide> <section id='tests'>
<ide>
<ide> ```yml
<ide> tests:
<del> - text: <code>Frameworks</code>组件应该存在并呈现给页面。
<del> testString: 'assert(Enzyme.mount(React.createElement(Frameworks)).find("Frameworks").length === 1, "The <code>Frameworks</code> component should exist and render to the page.");'
<del> - text: <code>Frameworks</code>应该呈现<code>h1</code>元素。
<del> testString: 'assert(Enzyme.mount(React.createElement(Frameworks)).find("h1").length === 1, "<code>Frameworks</code> should render an <code>h1</code> element.");'
<del> - text: <code>Frameworks</code>应该呈现<code>ul</code>元素。
<del> testString: 'assert(Enzyme.mount(React.createElement(Frameworks)).find("ul").length === 1, "<code>Frameworks</code> should render a <code>ul</code> element.");'
<del> - text: <code>ul</code>标记应呈现6个子<code>li</code>元素。
<del> testString: 'assert(Enzyme.mount(React.createElement(Frameworks)).find("ul").children().length === 6 && Enzyme.mount(React.createElement(Frameworks)).find("ul").childAt(0).name() === "li" && Enzyme.mount(React.createElement(Frameworks)).find("li").length === 6, "The <code>ul</code> tag should render 6 child <code>li</code> elements.");'
<del> - text: 每个列表项元素都应具有唯一的<code>key</code>属性。
<del> testString: 'assert((() => { const ul = Enzyme.mount(React.createElement(Frameworks)).find("ul"); const keys = new Set([ ul.childAt(0).key(), ul.childAt(1).key(), ul.childAt(2).key(), ul.childAt(3).key(), ul.childAt(4).key(), ul.childAt(5).key(), ]); return keys.size === 6; })(), "Each list item element should have a unique <code>key</code> attribute.");'
<add> - text: <code>Frameworks</code> 组件应该存在并渲染到页面。
<add> testString: assert(Enzyme.mount(React.createElement(Frameworks)).find('Frameworks').length === 1);
<add> - text: <code>Frameworks</code>应该渲染一个<code>h1</code>元素。
<add> testString: assert(Enzyme.mount(React.createElement(Frameworks)).find('h1').length === 1);
<add> - text: <code>Frameworks</code>应该渲染一个<code>ul</code>元素。
<add> testString: assert(Enzyme.mount(React.createElement(Frameworks)).find('ul').length === 1);
<add> - text: <code>ul</code>标签应该渲染 6 个<code>li</code>子元素。
<add> testString: assert(Enzyme.mount(React.createElement(Frameworks)).find('ul').children().length === 6 && Enzyme.mount(React.createElement(Frameworks)).find('ul').childAt(0).name() === 'li' && Enzyme.mount(React.createElement(Frameworks)).find('li').length === 6);
<add> - text: 每个列表项元素都应该有一个唯一的<code>key</code>属性。
<add> testString: assert((() => { const ul = Enzyme.mount(React.createElement(Frameworks)).find('ul'); const keys = new Set([ ul.childAt(0).key(), ul.childAt(1).key(), ul.childAt(2).key(), ul.childAt(3).key(), ul.childAt(4).key(), ul.childAt(5).key(), ]); return keys.size === 6; })());
<add> - text: 每个列表元素都应该包含 <code>frontEndFrameworks</code> 里的文本。
<add> testString: assert((() => {const li = Enzyme.mount(React.createElement(Frameworks)).find('ul').children(); return [...Array(5)].every((_, i) => frontEndFrameworks.includes(li.at(i).text()))})());
<ide>
<ide> ```
<ide>
<ide> tests:
<ide> <div id='jsx-seed'>
<ide>
<ide> ```jsx
<add>
<ide> const frontEndFrameworks = [
<ide> 'React',
<ide> 'Angular',
<ide> function Frameworks() {
<ide> </div>
<ide> );
<ide> };
<del>
<ide> ```
<ide>
<ide> </div>
<ide> function Frameworks() {
<ide> <div id='jsx-teardown'>
<ide>
<ide> ```js
<del>console.info('after the test');
<add>ReactDOM.render(<Frameworks />, document.getElementById('root'))
<ide> ```
<ide>
<ide> </div>
<ide> console.info('after the test');
<ide> ## Solution
<ide> <section id='solution'>
<ide>
<add>
<ide> ```js
<del>// solution required
<add>const frontEndFrameworks = [
<add> 'React',
<add> 'Angular',
<add> 'Ember',
<add> 'Knockout',
<add> 'Backbone',
<add> 'Vue'
<add>];
<add>
<add>function Frameworks() {
<add> const renderFrameworks = frontEndFrameworks.map((fw, i) => <li key={i}>{fw}</li>);
<add> return (
<add> <div>
<add> <h1>Popular Front End JavaScript Frameworks</h1>
<add> <ul>
<add> {renderFrameworks}
<add> </ul>
<add> </div>
<add> );
<add>};
<ide> ```
<ide>
<del>/section>
<add></section>
<ide><path>curriculum/challenges/chinese/03-front-end-libraries/react/introducing-inline-styles.chinese.md
<ide> id: 5a24c314108439a4d4036181
<ide> title: Introducing Inline Styles
<ide> challengeType: 6
<ide> isRequired: false
<del>videoUrl: ''
<add>forumTopicId: 301395
<ide> localeTitle: 介绍内联样式
<ide> ---
<ide>
<ide> ## Description
<del><section id="description">还有其他复杂的概念可以为您的React代码添加强大的功能。但是你可能想知道如何设置你在React中创建的那些JSX元素的更简单的问题。您可能知道它与使用HTML完全不同,因为<a target="_blank" href="/learn/front-end-libraries/react/define-an-html-class-in-jsx">您将类应用于JSX元素的方式</a> 。如果从样式表导入样式,它就没有太大的不同。使用<code>className</code>属性将类应用于JSX元素,并将样式应用于样式表中的类。另一种选择是应用<strong><em>内联</em></strong>样式,这在ReactJS开发中非常常见。您将内联样式应用于JSX元素,类似于您在HTML中的操作方式,但有一些JSX差异。以下是HTML中内联样式的示例: <code><div style="color: yellow; font-size: 16px">Mellow Yellow</div></code> JSX元素使用<code>style</code>属性,但由于JSX的转换方式,您可以不要将值设置为<code>string</code> 。相反,您将其设置为等于JavaScript <code>object</code> 。这是一个例子: <code><div style={{color: "yellow", fontSize: 16}}>Mellow Yellow</div></code>注意我们如何使用“fontSize”属性?这是因为React不接受样式对象中的kebab-case键。 React将在HTML中为我们应用正确的属性名称。 </section>
<add><section id='description'>
<add>还有其他复杂的概念可以为你的 React 代码增加强大的功能。但是,你可能会想知道更简单的问题,比如:如何对在 React 中创建的 JSX 元素进行风格化。你可能知道,由于<a target="_blank" href="define-an-html-class-in-jsx">将 class 应用于 JSX 元素的方式</a>与 HTML 中的使用并不完全相同。
<add>如果从样式表导入样式,它就没有太大的不同。使用<code>className</code>属性将 class 应用于 JSX 元素,并将样式应用于样式表中的 class。另一种选择是使用<strong><em>内联</em></strong>样式,这在 ReactJS 开发中非常常见。
<add>你将内联样式应用于 JSX 元素,类似于你在 HTML 中的操作方式,但有一些 JSX 差异。以下是 HTML 中内联样式的示例:
<add><code><div style="color: yellow; font-size: 16px">Mellow Yellow</div></code>
<add>JSX 元素使用<code>style</code>属性,但是由于 JSX 的传输方式,你不能将值设置为<code>字符串</code>。相反,你应将其设置为 JavaScript<code>对象</code>。这里有一个例子:
<add><code><div style={{color: "yellow", fontSize: 16}}>Mellow Yellow</div></code>
<add>注意我们使用驼峰式命名的 "fontSize" 属性,这是因为 React 不会接受样式对象中的连字符。React 将在 HTML 中为我们应用正确的属性名称。
<add></section>
<ide>
<ide> ## Instructions
<del><section id="instructions">在代码编辑器中为<code>div</code>添加<code>style</code>属性,为文本提供红色和字体大小为72px的颜色。请注意,您可以选择将字体大小设置为数字,省略单位“px”,或将其写为“72px”。 </section>
<add><section id='instructions'>
<add>在代码编辑器的<code>div</code>中添加一个<code>style</code>属性,使文本颜色为红色,字体大小为 72px。
<add>请注意,你可以选择将字体大小设置为数字,省略单位 "px",或者将其写为 "72px"。
<add></section>
<ide>
<ide> ## Tests
<ide> <section id='tests'>
<ide>
<ide> ```yml
<ide> tests:
<del> - text: 该组件应呈现<code>div</code>元素。
<add> - text: 组件应该渲染一个<code>div</code>元素。
<ide> testString: assert((function() { const mockedComponent = Enzyme.mount(React.createElement(Colorful)); return mockedComponent.children().type() === 'div'; })());
<del> - text: <code>div</code>元素应该是<code>red</code> 。
<add> - text: <code>div</code>元素应该是<code>红色</code>的。
<ide> testString: assert((function() { const mockedComponent = Enzyme.mount(React.createElement(Colorful)); return mockedComponent.children().props().style.color === 'red'; })());
<ide> - text: <code>div</code>元素的字体大小应为<code>72px</code>。
<ide> testString: assert((function() { const mockedComponent = Enzyme.mount(React.createElement(Colorful)); return (mockedComponent.children().props().style.fontSize === 72 || mockedComponent.children().props().style.fontSize === '72' || mockedComponent.children().props().style.fontSize === '72px'); })());
<ide> tests:
<ide> <div id='jsx-seed'>
<ide>
<ide> ```jsx
<add>
<ide> class Colorful extends React.Component {
<ide> render() {
<ide> return (
<ide> class Colorful extends React.Component {
<ide> <div id='jsx-teardown'>
<ide>
<ide> ```js
<del>console.info('after the test');
<add>ReactDOM.render(<Colorful />, document.getElementById('root'))
<ide> ```
<ide>
<ide> </div>
<ide> console.info('after the test');
<ide> ## Solution
<ide> <section id='solution'>
<ide>
<add>
<ide> ```js
<del>// solution required
<add>class Colorful extends React.Component {
<add> render() {
<add> return (
<add> <div style={{color: "red", fontSize: 72}}>Big Red</div>
<add> );
<add> }
<add>};
<add>
<ide> ```
<ide>
<del>/section>
<add></section>
<ide><path>curriculum/challenges/chinese/03-front-end-libraries/react/learn-about-self-closing-jsx-tags.chinese.md
<ide> id: 5a24c314108439a4d4036161
<ide> title: Learn About Self-Closing JSX Tags
<ide> challengeType: 6
<ide> isRequired: false
<del>videoUrl: ''
<del>localeTitle: 了解自我关闭JSX标签
<add>forumTopicId: 301396
<add>localeTitle: 了解自动闭合的 JSX 标记
<ide> ---
<ide>
<ide> ## Description
<del><section id="description">到目前为止,您已经看到JSX与HTML的不同之处在于使用<code>className</code>与<code>class</code>来定义HTML类。 JSX与HTML的另一个重要方式是自闭标签。在HTML中,几乎所有标签都有开始和结束标签: <code><div></div></code> ;结束标记在您要关闭的标记名称之前始终具有正斜杠。但是,HTML中有一些称为“自闭标签”的特殊实例,或者在另一个标签可以启动之前不需要开始和结束标签的标签。例如,换行标记可以写成<code><br></code>或<code><br /></code> ,但不应该写为<code><br></br></code> ,因为它不包含任何内容。在JSX中,规则略有不同。任何JSX元素都可以使用自闭合标记编写,并且必须关闭每个元素。例如,换行标记必须始终写为<code><br /></code>才能成为可以转换的有效JSX。另一方面, <code><div></code>可以写为<code><div /></code>或<code><div></div></code> 。不同之处在于,在第一个语法版本中,无法在<code><div /></code>包含任何内容。您将在以后的挑战中看到,在呈现React组件时,此语法非常有用。 </section>
<add><section id='description'>
<add>到目前为止,你已经看到 JSX 与 HTML 的不同之处在于使用<code>className</code>和使用<code>class</code>来定义 HTML 的 class。
<add>JSX 不同于 HTML 的另一个重要方面是自闭合标签。
<add>在HTML中,几乎所有的标签都有一个开始和结束标签:<code><div></div></code>,结束标签在你要关闭的标签名之前始终具有正斜杠。但是,HTML 中有一些称为“自闭合标签”的特殊实例,它们在另一个标签开始之前,不需要开始和结束标签都存在。
<add>例如,换行标签可以写成<code><br></code>或者<code><br /></code>,但是不应该写成<code><br></br></code>,因为它不包含任何内容。
<add>在 JSX 中,规则略有不同。任何 JSX 元素都可以使用自闭合标签编写,并且每个元素都必须关闭。例如,换行标签必须始终编写为<code><br /></code>。另一方面<code><div></code>可以写成<code><div /></code>或者<code><div></div></code>。不同之处在于,在第一个语法版本中,无法在<code><div /></code>中包含任何内容。在后面的挑战中你会发现,这种语法在渲染 React 组件时非常有用。
<add></section>
<ide>
<ide> ## Instructions
<del><section id="instructions">修复代码编辑器中的错误,使其成为有效的JSX并成功转换。确保您不更改任何内容 - 您只需要在需要的地方关闭标签。 </section>
<add><section id='instructions'>
<add>修复代码编辑器中的错误,使其成为有效的 JSX 并成功转换。确保你不更改任何内容--你只需要在需要的地方关闭标签。
<add></section>
<ide>
<ide> ## Tests
<ide> <section id='tests'>
<ide> tests:
<ide> testString: assert.strictEqual(JSX.type, 'div');
<ide> - text: <code>div</code>应该包含一个<code>br</code>标签。
<ide> testString: assert(Enzyme.shallow(JSX).find('br').length === 1);
<del> - text: <code>div</code>应包含<code>hr</code>标记。
<add> - text: <code>div</code>应该包含一个<code>hr</code>标签。
<ide> testString: assert(Enzyme.shallow(JSX).find('hr').length === 1);
<ide>
<ide> ```
<ide> const JSX = (
<ide> <div id='jsx-teardown'>
<ide>
<ide> ```js
<del>console.info('after the test');
<add>ReactDOM.render(JSX, document.getElementById('root'))
<ide> ```
<ide>
<ide> </div>
<ide> console.info('after the test');
<ide> ## Solution
<ide> <section id='solution'>
<ide>
<add>
<ide> ```js
<del>// solution required
<add>const JSX = (
<add><div>
<add> {/* change code below this line */}
<add> <h2>Welcome to React!</h2> <br />
<add> <p>Be sure to close all tags!</p>
<add> <hr />
<add> {/* change code above this line */}
<add></div>
<add>);
<ide> ```
<ide>
<del>/section>
<add></section>
<ide><path>curriculum/challenges/chinese/03-front-end-libraries/react/optimize-re-renders-with-shouldcomponentupdate.chinese.md
<ide> id: 5a24c314108439a4d4036180
<ide> title: Optimize Re-Renders with shouldComponentUpdate
<ide> challengeType: 6
<ide> isRequired: false
<del>videoUrl: ''
<del>localeTitle: 使用shouldComponentUpdate优化重新渲染
<add>forumTopicId: 301398
<add>localeTitle: 使用 shouldComponentUpdate 优化重新渲染
<ide> ---
<ide>
<ide> ## Description
<del><section id="description">到目前为止,如果任何组件接收到新的<code>state</code>或新的<code>props</code> ,它会重新呈现自己及其所有子项。这通常没问题。但是React提供了一个生命周期方法,您可以在子组件接收新<code>state</code>或<code>props</code>时调用它,并特别声明组件是否应该更新。方法是<code>shouldComponentUpdate()</code> ,它将<code>nextProps</code>和<code>nextState</code>作为参数。此方法是优化性能的有用方法。例如,默认行为是您的组件在收到新<code>props</code>时重新渲染,即使<code>props</code>未更改。您可以使用<code>shouldComponentUpdate()</code>通过比较<code>props</code>来防止这种情况。该方法必须返回一个<code>boolean</code>值,告诉React是否更新组件。您可以将当前道具( <code>this.props</code> )与下一个道具( <code>nextProps</code> )进行比较,以确定是否需要更新,并相应地返回<code>true</code>或<code>false</code> 。 </section>
<add><section id='description'>
<add>到目前为止,如果任何组件接收到新的<code>state</code>或新的<code>props</code>,它会重新渲染自己及其所有子组件。这通常是好的。但是 React 提供了一种生命周期方法,当子组件接收到新的<code>state</code>或<code>props</code>时,你可以调用该方法,并特别声明组件是否应该更新。方法是<code>shouldComponentUpdate()</code>,它将<code>nextProps</code>和<code>nextState</code>作为参数。
<add>这种方法是优化性能的有效方法。例如,默认行为是,当组件接收到新的<code>props</code>时,即使<code>props</code>没有改变,它也会重新渲染。你可以通过使用<code>shouldComponentUpdate()</code>比较<code>props</code>来防止这种情况。该方法必须返回一个布尔值,该值告诉 React 是否更新组件。你可以比较当前的 props(<code>this.props</code>)和下一个 props(<code>nextProps</code>),以确定你是否需要更新,并相应地返回<code>true</code>或<code>false</code>。
<add></section>
<ide>
<ide> ## Instructions
<del><section id="instructions"> <code>shouldComponentUpdate()</code>方法添加到名为<code>OnlyEvens</code>的组件中。目前,此方法返回<code>true</code>因此每次收到新<code>props</code>时, <code>OnlyEvens</code>重新渲染。修改方法,以便<code>OnlyEvens</code>更新仅当<code>value</code>的新道具的是偶数。单击“ <code>Add</code>按钮,在触发其他生命周期挂钩时,在浏览器控制台中查看事件的顺序。 </section>
<add><section id='instructions'>
<add><code>shouldComponentUpdate()</code>方法添加到名为<code>OnlyEvens</code>的组件中。目前,该方法返回<code>true</code>,因此每次收到新的<code>props</code>时,<code>OnlyEvens</code>都会重新渲染。修改该方法,以便<code>OnlyEvens</code>仅在其新 props 的<code>value</code>为偶数时更新。单击<code>Add</code>按钮,在触发其他生命周期钩子时,在浏览器控制台中查看事件的顺序。
<add></section>
<ide>
<ide> ## Tests
<ide> <section id='tests'>
<ide>
<ide> ```yml
<ide> tests:
<del> - text: <code>Controller</code>组件应将<code>OnlyEvens</code>组件呈现为<code>OnlyEvens</code>组件。
<add> - text: <code>Controller</code>组件应该将<code>OnlyEvens</code>组件渲染为子组件。
<ide> testString: assert((() => { const mockedComponent = Enzyme.mount(React.createElement(Controller)); return mockedComponent.find('Controller').length === 1 && mockedComponent.find('OnlyEvens').length === 1; })());
<ide> - text: 应该在<code>OnlyEvens</code>组件上定义<code>shouldComponentUpdate</code>方法。
<ide> testString: assert((() => { const child = React.createElement(OnlyEvens).type.prototype.shouldComponentUpdate.toString().replace(/s/g,''); return child !== 'undefined'; })());
<del> - text: <code>OnlyEvens</code>组件应返回一个<code>h1</code>标记,该标记呈现<code>this.props.value</code>的值。
<add> - text: <code>OnlyEvens</code>组件应该返回一个<code>h1</code>标签,该标签渲染<code>this.props.value</code>的值。
<ide> testString: 'async () => { const waitForIt = (fn) => new Promise((resolve, reject) => setTimeout(() => resolve(fn()), 250)); const mockedComponent = Enzyme.mount(React.createElement(Controller)); const first = () => { mockedComponent.setState({ value: 1000 }); return waitForIt(() => mockedComponent.find(''h1'').html()); }; const second = () => { mockedComponent.setState({ value: 10 }); return waitForIt(() => mockedComponent.find(''h1'').html()); }; const firstValue = await first(); const secondValue = await second(); assert(firstValue === ''<h1>1000</h1>'' && secondValue === ''<h1>10</h1>''); }; '
<del> - text: <code>OnlyEvens</code>只有在<code>nextProps.value</code>为偶数<code>OnlyEvens</code>应该重新渲染。
<add> - text: 只有在<code>nextProps.value</code>为偶数时,<code>OnlyEvens</code>才会重新渲染。
<ide> testString: 'async () => { const waitForIt = (fn) => new Promise((resolve, reject) => setTimeout(() => resolve(fn()), 250)); const mockedComponent = Enzyme.mount(React.createElement(Controller)); const first = () => { mockedComponent.setState({ value: 8 }); return waitForIt(() => mockedComponent.find(''h1'').text()); }; const second = () => { mockedComponent.setState({ value: 7 }); return waitForIt(() => mockedComponent.find(''h1'').text()); }; const third = () => { mockedComponent.setState({ value: 42 }); return waitForIt(() => mockedComponent.find(''h1'').text()); }; const firstValue = await first(); const secondValue = await second(); const thirdValue = await third(); assert(firstValue === ''8'' && secondValue === ''8'' && thirdValue === ''42''); }; '
<ide>
<ide> ```
<ide> class OnlyEvens extends React.Component {
<ide> return true;
<ide> // change code above this line
<ide> }
<del> componentWillReceiveProps(nextProps) {
<del> console.log('Receiving new props...');
<del> }
<ide> componentDidUpdate() {
<ide> console.log('Component re-rendered.');
<ide> }
<ide> class Controller extends React.Component {
<ide> );
<ide> }
<ide> };
<del>
<ide> ```
<ide>
<ide> </div>
<ide> class Controller extends React.Component {
<ide> <div id='jsx-teardown'>
<ide>
<ide> ```js
<del>console.info('after the test');
<add>ReactDOM.render(<Controller />, document.getElementById('root'))
<ide> ```
<ide>
<ide> </div>
<ide> console.info('after the test');
<ide> ## Solution
<ide> <section id='solution'>
<ide>
<add>
<ide> ```js
<del>// solution required
<add>class OnlyEvens extends React.Component {
<add> constructor(props) {
<add> super(props);
<add> }
<add> shouldComponentUpdate(nextProps, nextState) {
<add> console.log('Should I update?');
<add> // change code below this line
<add> return nextProps.value % 2 === 0;
<add> // change code above this line
<add> }
<add> componentDidUpdate() {
<add> console.log('Component re-rendered.');
<add> }
<add> render() {
<add> return <h1>{this.props.value}</h1>
<add> }
<add>};
<add>
<add>class Controller extends React.Component {
<add> constructor(props) {
<add> super(props);
<add> this.state = {
<add> value: 0
<add> };
<add> this.addValue = this.addValue.bind(this);
<add> }
<add> addValue() {
<add> this.setState({
<add> value: this.state.value + 1
<add> });
<add> }
<add> render() {
<add> return (
<add> <div>
<add> <button onClick={this.addValue}>Add</button>
<add> <OnlyEvens value={this.state.value}/>
<add> </div>
<add> );
<add> }
<add>};
<ide> ```
<ide>
<del>/section>
<add></section>
<ide><path>curriculum/challenges/chinese/03-front-end-libraries/react/override-default-props.chinese.md
<ide> id: 5a24c314108439a4d403616c
<ide> title: Override Default Props
<ide> challengeType: 6
<ide> isRequired: false
<del>videoUrl: ''
<del>localeTitle: 覆盖默认道具
<add>forumTopicId: 301399
<add>localeTitle: 覆盖默认的 Props
<ide> ---
<ide>
<ide> ## Description
<del><section id="description">设置默认道具的能力是React中的一个有用功能。覆盖默认道具的方法是显式设置组件的prop值。 </section>
<add><section id='description'>
<add>在 React 中,设置默认的 props 是一个很有用的特性,显式设置组件的 prop 值即可覆盖默认 props。
<add></section>
<ide>
<ide> ## Instructions
<del><section id="instructions"> <code>ShoppingCart</code>组件现在呈现子组件<code>Items</code> 。此<code>Items</code>组件的默认prop <code>quantity</code>设置为整数<code>0</code> 。通过为<code>quantity</code>传递值<code>10</code>来覆盖默认支柱。 <strong>注意:</strong>请记住,向组件添加prop的语法与添加HTML属性的方式类似。但是,由于<code>quantity</code>的值是一个整数,因此它不会引用引号,但应该用大括号括起来。例如, <code>{100}</code> 。此语法告诉JSX将大括号内的值直接解释为JavaScript。 </section>
<add><section id='instructions'>
<add><code>ShoppingCart</code>组件现在渲染了一个子组件<code>Items</code>。该<code>Items</code>组件有一个默认<code>quantity</code>prop,其值被设置为整数<code>0</code>。通过传入数值<code>10</code>来覆盖<code>quantity</code>的默认 prop。
<add><strong>注意:</strong> 请记住,向组件添加 prop 的语法与添加 HTML 属性类似。但是,由于<code>quantity</code>的值是整数,所以它不会加引号,但应该用花括号括起来,例如<code>{100}</code>。这个语法告诉 JSX 直接将花括号中的值解释为 JavaScript。
<add></section>
<ide>
<ide> ## Tests
<ide> <section id='tests'>
<ide>
<ide> ```yml
<ide> tests:
<del> - text: <code>ShoppingCart</code>应该呈现组件。
<add> - text: 应该渲染<code>ShoppingCart</code>组件。
<ide> testString: assert((function() { const mockedComponent = Enzyme.mount(React.createElement(ShoppingCart)); return mockedComponent.find('ShoppingCart').length === 1; })());
<del> - text: 该组件<code>Items</code>应该呈现。
<add> - text: 应该渲染<code>Items</code>组件。
<ide> testString: assert((function() { const mockedComponent = Enzyme.mount(React.createElement(ShoppingCart)); return mockedComponent.find('Items').length === 1; })());
<del> - text: '<code>Items</code>组件应具有从<code>ShoppingCart</code>组件传递的<code>{ quantity: 10 }</code>的prop。'
<add> - text: '<code>Items</code>组件应该有一个<code>{ quantity: 10 }</code>的prop,该 prop 是从<code>ShoppingCart</code>组件传递过去的。'
<ide> testString: "getUserInput => assert((function() { const mockedComponent = Enzyme.mount(React.createElement(ShoppingCart)); return mockedComponent.find('Items').props().quantity == 10 && getUserInput('index').replace(/ /g,'').includes('<Itemsquantity={10}/>'); })());"
<ide>
<ide> ```
<ide> class ShoppingCart extends React.Component {
<ide> { /* change code above this line */ }
<ide> }
<ide> };
<del>
<ide> ```
<ide>
<ide> </div>
<ide> class ShoppingCart extends React.Component {
<ide> <div id='jsx-teardown'>
<ide>
<ide> ```js
<del>console.info('after the test');
<add>ReactDOM.render(<ShoppingCart />, document.getElementById('root'))
<ide> ```
<ide>
<ide> </div>
<ide> console.info('after the test');
<ide> ## Solution
<ide> <section id='solution'>
<ide>
<add>
<ide> ```js
<del>// solution required
<add>const Items = (props) => {
<add> return <h1>Current Quantity of Items in Cart: {props.quantity}</h1>
<add>}
<add>
<add>Items.defaultProps = {
<add> quantity: 0
<add>}
<add>
<add>class ShoppingCart extends React.Component {
<add> constructor(props) {
<add> super(props);
<add> }
<add> render() {
<add> { /* change code below this line */ }
<add> return <Items quantity = {10} />
<add> { /* change code above this line */ }
<add> }
<add>};
<ide> ```
<ide>
<del>/section>
<add></section>
<ide><path>curriculum/challenges/chinese/03-front-end-libraries/react/pass-a-callback-as-props.chinese.md
<ide> id: 5a24c314108439a4d403617b
<ide> title: Pass a Callback as Props
<ide> challengeType: 6
<ide> isRequired: false
<del>videoUrl: ''
<del>localeTitle: 将回调作为道具传递
<add>forumTopicId: 301400
<add>localeTitle: 传递回调作为 Props
<ide> ---
<ide>
<ide> ## Description
<del><section id="description">您可以将<code>state</code>作为道具传递给子组件,但您不仅限于传递数据。您还可以将处理函数或在React组件上定义的任何方法传递给子组件。这是允许子组件与其父组件交互的方式。您可以将方法传递给孩子,就像常规道具一样。它被分配了一个名称,您可以在子组件中的<code>this.props</code>下访问该方法名称。 </section>
<add><section id='description'>
<add>你可以将<code>state</code>作为 props 传递给子组件,但不仅限于传递数据。你也可以将处理函数或在 React 组件中定义的任何方法传递给子组件。这就是允许子组件与父组件交互的方式。你可以把方法像普通 prop 一样传递给子组件,它会被分配一个名字,你可以在子组件中的<code>this.props</code>下访问该方法的名字。
<add></section>
<ide>
<ide> ## Instructions
<del><section id="instructions">代码编辑器中列出了三个组件。 <code>MyApp</code>组件是将呈现<code>GetInput</code>和<code>RenderInput</code>子组件的父组件。将<code>GetInput</code>组件添加到<code>MyApp</code>的render方法,然后从<code>MyApp</code>的<code>state</code>向它传递一个名为<code>input</code>的prop,该<code>input</code>分配给<code>inputValue</code> 。还要创建一个名为<code>handleChange</code>的prop,并将输入处理程序<code>handleChange</code>给它。接下来,将<code>RenderInput</code>添加到<code>MyApp</code>的render方法,然后创建一个名为<code>input</code>的prop,并将<code>inputValue</code>从<code>state</code>传递给它。完成后,您将能够在<code>GetInput</code>组件中<code>input</code>字段,然后通过props调用其父级中的处理程序方法。这将更新父级<code>state</code>的输入,该输入作为props传递给两个子级。观察数据如何在组件之间流动以及单个事实源如何保持父组件的<code>state</code> 。不可否认,这个例子有点人为,但应该用来说明如何在React组件之间传递数据和回调。 </section>
<add><section id='instructions'>
<add>代码编辑器中列出了三个组件。<code>MyApp</code>是父组件,<code>GetInput</code>和<code>RenderInput</code>是它的子组件。将<code>GetInput</code>组件添加到<code>MyApp</code>的 render 方法,然后将<code>MyApp</code>的<code>state</code>中的<code>inputValue</code>传入名为<code>input</code>的 prop。还要创建一个名为<code>handleChange</code>的 prop,并将输入处理程序<code>handleChange</code>传递给它。
<add>接下来,将<code>RenderInput</code>添加到<code>MyApp</code>中的 render 方法中,然后创建一个名为<code>input</code>的 prop,并将<code>state</code>中的<code>inputValue</code>传递给它。完成后,你将能够在<code>GetInput</code>组件中的<code>input</code>字段中键入内容,然后该组件通过 props 调用其父组件中的处理函数方法。这将更新处于父组件<code>state</code>中的 input,该 input 将作为 props 传递给两个子组件。观察数据如何在组件之间流动,以及单一数据源如何保持父组件<code>state</code>。诚然,这个示例有点做作,但是应该能用来说明数据和回调是如何在 React 组件之间传递的。
<add></section>
<ide>
<ide> ## Tests
<ide> <section id='tests'>
<ide>
<ide> ```yml
<ide> tests:
<del> - text: <code>MyApp</code>组件应该呈现。
<add> - text: 应该渲染<code>MyApp</code>组件。
<ide> testString: assert((function() { const mockedComponent = Enzyme.mount(React.createElement(MyApp)); return mockedComponent.find('MyApp').length === 1; })());
<del> - text: <code>GetInput</code>组件应该呈现。
<add> - text: 应该渲染<code>GetInput</code>组件。
<ide> testString: assert((function() { const mockedComponent = Enzyme.mount(React.createElement(MyApp)); return mockedComponent.find('GetInput').length === 1; })());
<del> - text: <code>RenderInput</code>组件应该呈现。
<add> - text: 应该渲染<code>RenderInput</code>组件。
<ide> testString: assert((function() { const mockedComponent = Enzyme.mount(React.createElement(MyApp)); return mockedComponent.find('RenderInput').length === 1; })());
<del> - text: <code>GetInput</code>组件应该将<code>MyApp</code>状态属性<code>inputValue</code>作为props接收,并包含一个修改<code>MyApp</code>状态的<code>input</code>元素。
<add> - text: <code>GetInput</code>组件应该接收<code>MyApp</code>的 state 属性<code>inputValue</code>作为 props,并包含一个修改<code>MyApp</code>state 的<code>input</code>元素。
<ide> testString: 'async () => { const waitForIt = (fn) => new Promise((resolve, reject) => setTimeout(() => resolve(fn()), 250)); const mockedComponent = Enzyme.mount(React.createElement(MyApp)); const state_1 = () => { mockedComponent.setState({inputValue: ''''}); return waitForIt(() => mockedComponent.state() )}; const state_2 = () => { mockedComponent.find(''input'').simulate(''change'', {target: {value: ''TestInput''}}); return waitForIt(() => mockedComponent.state() )}; const updated_1 = await state_1(); const updated_2 = await state_2(); assert(updated_1.inputValue === '''' && updated_2.inputValue === ''TestInput''); }; '
<del> - text: <code>RenderInput</code>组件应该将<code>MyApp</code>状态属性<code>inputValue</code>作为props接收。
<add> - text: <code>RenderInput</code>组件应该接收<code>MyApp</code>state 属性<code>inputValue</code>作为 props。
<ide> testString: 'async () => { const waitForIt = (fn) => new Promise((resolve, reject) => setTimeout(() => resolve(fn()), 250)); const mockedComponent = Enzyme.mount(React.createElement(MyApp)); const state_1 = () => { mockedComponent.setState({inputValue: ''TestName''}); return waitForIt(() => mockedComponent )}; const updated_1 = await state_1(); assert(updated_1.find(''p'').text().includes(''TestName'')); }; '
<ide>
<ide> ```
<ide> class MyApp extends React.Component {
<ide> constructor(props) {
<ide> super(props);
<ide> this.state = {
<del> inputValue: "
<add> inputValue: ''
<ide> }
<ide> this.handleChange = this.handleChange.bind(this);
<ide> }
<ide> class RenderInput extends React.Component {
<ide> );
<ide> }
<ide> };
<del>
<ide> ```
<ide>
<ide> </div>
<ide> class RenderInput extends React.Component {
<ide> <div id='jsx-teardown'>
<ide>
<ide> ```js
<del>console.info('after the test');
<add>ReactDOM.render(<MyApp />, document.getElementById('root'))
<ide> ```
<ide>
<ide> </div>
<ide> console.info('after the test');
<ide> ## Solution
<ide> <section id='solution'>
<ide>
<add>
<ide> ```js
<del>// solution required
<add>class MyApp extends React.Component {
<add> constructor(props) {
<add> super(props);
<add> this.state = {
<add> inputValue: ''
<add> }
<add> this.handleChange = this.handleChange.bind(this);
<add> }
<add> handleChange(event) {
<add> this.setState({
<add> inputValue: event.target.value
<add> });
<add> }
<add> render() {
<add> return (
<add> <div>
<add> <GetInput
<add> input={this.state.inputValue}
<add> handleChange={this.handleChange}/>
<add> <RenderInput
<add> input={this.state.inputValue}/>
<add> </div>
<add> );
<add> }
<add>};
<add>
<add>class GetInput extends React.Component {
<add> constructor(props) {
<add> super(props);
<add> }
<add> render() {
<add> return (
<add> <div>
<add> <h3>Get Input:</h3>
<add> <input
<add> value={this.props.input}
<add> onChange={this.props.handleChange}/>
<add> </div>
<add> );
<add> }
<add>};
<add>
<add>class RenderInput extends React.Component {
<add> constructor(props) {
<add> super(props);
<add> }
<add> render() {
<add> return (
<add> <div>
<add> <h3>Input Render:</h3>
<add> <p>{this.props.input}</p>
<add> </div>
<add> );
<add> }
<add>};
<ide> ```
<ide>
<del>/section>
<add></section>
<ide><path>curriculum/challenges/chinese/03-front-end-libraries/react/pass-an-array-as-props.chinese.md
<ide> id: 5a24c314108439a4d403616a
<ide> title: Pass an Array as Props
<ide> challengeType: 6
<ide> isRequired: false
<del>videoUrl: ''
<del>localeTitle: 将数组作为道具传递
<add>forumTopicId: 301401
<add>localeTitle: 传递一个数组作为 Props
<ide> ---
<ide>
<ide> ## Description
<del><section id="description">最后一项挑战演示了如何将信息从父组件传递到子组件作为<code>props</code>或属性。这个挑战着眼于如何将数组作为<code>props</code>传递。要将数组传递给JSX元素,必须将其视为JavaScript并用大括号括起来。 <blockquote> <为父级> <br> <ChildComponent colors = {[“green”,“blue”,“red”]} /> <br> </为父级> </blockquote>然后子组件可以访问数组属性<code>colors</code> 。访问属性时可以使用诸如<code>join()</code>类的数组方法。 <code>const ChildComponent = (props) => <p>{props.colors.join(', ')}</p></code>这会将所有<code>colors</code>数组项连接成逗号分隔的字符串并生成: <code><p>green, blue, red</p></code>稍后,我们将了解在React中呈现数据数组的其他常用方法。 </section>
<add><section id='description'>
<add>上一个挑战演示了如何将来自父组件的信息作为<code>props</code>传递给子组件。这个挑战着眼于如何将数组作为<code>props</code>传递。要将数组传递给 JSX 元素,必须将其视为 JavaScript 并用花括号括起来。
<add>
<add>```jsx
<add><ParentComponent>
<add> <ChildComponent colors={["green", "blue", "red"]} />
<add></ParentComponent>
<add>```
<add>
<add>这样,子组件就可以访问数组属性<code>colors</code>。访问属性时可以使用<code>join()</code>等数组方法。
<add><code>const ChildComponent = (props) => <p>{props.colors.join(', ')}</p></code>
<add>这将把所有<code>colors</code>数组项连接成一个逗号分隔的字符串并生成:
<add> <code> <p>green, blue, red</p></code>
<add>稍后,我们将了解在 React 中渲染数组数据的其他常用方法。
<add></section>
<ide>
<ide> ## Instructions
<del><section id="instructions">代码编辑器中有<code>List</code>和<code>ToDo</code>组件。从<code>ToDo</code>组件渲染每个<code>List</code> ,传入分配给待办任务数组的<code>tasks</code>属性,例如<code>["walk dog", "workout"]</code> 。然后在<code>List</code>组件中访问此<code>tasks</code>数组,在<code>p</code>元素中显示其值。使用<code>join(", ")</code>以逗号分隔列表的形式显示<code>p</code>元素中的<code>props.tasks</code>数组。今天的列表应该至少有2个任务,明天应该至少有3个任务。 </section>
<add><section id='instructions'>
<add>代码编辑器中有<code>List</code>和<code>ToDo</code>组件。在<code>ToDo</code>组件中渲染每个<code>List</code>时,传入<code>tasks</code>属性并将其分配给待办任务数组,例如<code>["walk dog", "workout"]</code>。然后访问<code>List</code>组件中的<code>tasks</code>数组,在<code>p</code>元素中显示其值。使用<code>join(", ")</code>把<code>props.tasks</code>数组作为逗号分隔列表显示在<code>p</code>元素中。今天的列表应该至少有 2 个任务,明天应该至少有 3 个任务。
<add></section>
<ide>
<ide> ## Tests
<ide> <section id='tests'>
<ide>
<ide> ```yml
<ide> tests:
<del> - text: <code>ToDo</code>组件应返回单个外部<code>div</code> 。
<add> - text: <code>ToDo</code>组件应该返回单个外部<code>div</code>。
<ide> testString: assert((function() { const mockedComponent = Enzyme.mount(React.createElement(ToDo)); return mockedComponent.children().first().type() === 'div'; })());
<del> - text: <code>ToDo</code>组件的第三个子<code>ToDo</code>应该是<code>List</code>组件的实例。
<add> - text: <code>ToDo</code>组件的第三个子元素应该是<code>List</code>组件的一个实例。
<ide> testString: assert((function() { const mockedComponent = Enzyme.mount(React.createElement(ToDo)); return mockedComponent.children().first().childAt(2).name() === 'List'; })());
<del> - text: <code>ToDo</code>组件的第五个子<code>ToDo</code>应该是<code>List</code>组件的一个实例。
<add> - text: <code>ToDo</code>组件的第五个子元素应该是<code>List</code>组件的一个实例。
<ide> testString: assert((function() { const mockedComponent = Enzyme.mount(React.createElement(ToDo)); return mockedComponent.children().first().childAt(4).name() === 'List'; })());
<del> - text: <code>List</code>组件的两个实例都应该有一个名为<code>tasks</code>的属性,而<code>tasks</code>应该是array类型。
<add> - text: <code>List</code>组件的两个实例都应该具有一个名为<code>tasks</code>的属性,并且<code>tasks</code>的类型应该是数组。
<ide> testString: assert((function() { const mockedComponent = Enzyme.mount(React.createElement(ToDo)); return Array.isArray(mockedComponent.find('List').get(0).props.tasks) && Array.isArray(mockedComponent.find('List').get(1).props.tasks); })());
<del> - text: 表示今天任务的第一个<code>List</code>组件应该有2个或更多项。
<add> - text: 表示今天任务的第一个<code>List</code>组件应该有 2 个或更多项。
<ide> testString: assert((function() { const mockedComponent = Enzyme.mount(React.createElement(ToDo)); return mockedComponent.find('List').get(0).props.tasks.length >= 2; })());
<del> - text: 表示明天任务的第二个<code>List</code>组件应该有3个或更多项。
<add> - text: 表示明天任务的第二个<code>List</code>组件应该有 3 个或更多项。
<ide> testString: assert((function() { const mockedComponent = Enzyme.mount(React.createElement(ToDo)); return mockedComponent.find('List').get(1).props.tasks.length >= 3; })());
<del> - text: '<code>List</code>组件应该将<code>p</code>标记中的<code>tasks</code> prop的值呈现为以逗号分隔的列表,例如<code>walk dog, workout</code> 。'
<add> - text: <code>List</code>组件应在<code>p</code>标签中渲染<code>tasks</code>属性的值。
<ide> testString: assert((function() { const mockedComponent = Enzyme.mount(React.createElement(ToDo)); return mockedComponent.find('p').get(0).props.children === mockedComponent.find('List').get(0).props.tasks.join(', ') && mockedComponent.find('p').get(1).props.children === mockedComponent.find('List').get(1).props.tasks.join(', '); })());
<ide>
<ide> ```
<ide> tests:
<ide> <div id='jsx-seed'>
<ide>
<ide> ```jsx
<del>const List= (props) => {
<add>const List = (props) => {
<ide> { /* change code below this line */ }
<ide> return <p>{}</p>
<ide> { /* change code above this line */ }
<ide> class ToDo extends React.Component {
<ide> );
<ide> }
<ide> };
<del>
<ide> ```
<ide>
<ide> </div>
<ide> class ToDo extends React.Component {
<ide> <div id='jsx-teardown'>
<ide>
<ide> ```js
<del>console.info('after the test');
<add>ReactDOM.render(<ToDo />, document.getElementById('root'))
<ide> ```
<ide>
<ide> </div>
<ide> console.info('after the test');
<ide> ## Solution
<ide> <section id='solution'>
<ide>
<add>
<ide> ```js
<del>// solution required
<add>const List= (props) => {
<add> return <p>{props.tasks.join(', ')}</p>
<add>};
<add>
<add>class ToDo extends React.Component {
<add> constructor(props) {
<add> super(props);
<add> }
<add> render() {
<add> return (
<add> <div>
<add> <h1>To Do Lists</h1>
<add> <h2>Today</h2>
<add> <List tasks={['study', 'exercise']} />
<add> <h2>Tomorrow</h2>
<add> <List tasks={['call Sam', 'grocery shopping', 'order tickets']} />
<add> </div>
<add> );
<add> }
<add>};
<ide> ```
<ide>
<del>/section>
<add></section>
<ide><path>curriculum/challenges/chinese/03-front-end-libraries/react/pass-props-to-a-stateless-functional-component.chinese.md
<ide> id: 5a24c314108439a4d4036169
<ide> title: Pass Props to a Stateless Functional Component
<ide> challengeType: 6
<ide> isRequired: false
<del>videoUrl: ''
<del>localeTitle: 将道具传递给无状态功能组件
<add>forumTopicId: 301402
<add>localeTitle: 将 Props 传递给无状态函数组件
<ide> ---
<ide>
<ide> ## Description
<del><section id="description">之前的挑战涉及在React中创建和组合JSX元素,功能组件和ES6样式类组件的很多内容。有了这个基础,现在是时候看看React中常见的另一个特性: <b>道具</b> 。在React中,您可以将props或属性传递给子组件。假设您有一个<code>App</code>组件,它呈现一个名为<code>Welcome</code>的子组件,它是一个无状态功能组件。您可以通过编写以下方式传递<code>Welcome</code> <code>user</code>属性: <blockquote> <应用> <br> <Welcome user ='Mark'/> <br> </应用> </blockquote>您使用React提供支持的<strong>自定义HTML属性</strong> ,以将属性<code>user</code>传递给组件<code>Welcome</code> 。由于<code>Welcome</code>是一个无状态功能组件,因此它可以访问此值,如下所示: <blockquote> const Welcome =(props)=> <h1> Hello,{props.user}!</ h1> </blockquote>调用此值<code>props</code>是标准的,在处理无状态函数组件时,您基本上将其视为返回JSX的函数的参数。您可以在函数体中访问参数的值。使用类组件,您会发现这有点不同。 </section>
<add><section id='description'>
<add>之前的挑战涵盖了关于在 React 中创建和组合 JSX 元素、函数组件和 ES6 风格的类组件的很多内容。有了这个基础,现在是时候看看 React 中的另一个常见特性 <b>props</b> 了。在 React 中,你可以将属性传递给子组件。假设你有一个<code>App</code>组件,该组件渲染了一个名为<code>Welcome</code>的子组件,它是一个无状态函数组件。你可以通过以下方式给<code>Welcome</code>传递一个<code>user</code>属性:
<add>
<add>```jsx
<add><App>
<add> <Welcome user='Mark' />
<add></App>
<add>```
<add>
<add>使用<strong>自定义 HTML 属性</strong>,React 支持将属性<code>user</code>传递给组件<code>Welcome</code>。由于<code>Welcome</code>是一个无状态函数组件,它可以像这样访问该值:
<add>
<add>```jsx
<add>const Welcome = (props) => <h1>Hello, {props.user}!</h1>
<add>```
<add>
<add>调用<code>props</code>这个值是常见做法,当处理无状态函数组件时,你基本上可以将其视为返回 JSX 的函数的参数。这样,你就可以在函数体中访问该值。但对于类组件,访问方式会略有不同。
<add></section>
<ide>
<ide> ## Instructions
<del><section id="instructions">代码编辑器中有<code>Calendar</code>和<code>CurrentDate</code>组件。当渲染<code>CurrentDate</code>从<code>Calendar</code>组件,通过在属性<code>date</code>分配给从JavaScript的当前日期<code>Date</code>对象。然后在<code>CurrentDate</code>组件中访问此<code>prop</code> ,在<code>p</code>标签中显示其值。请注意,对于要作为JavaScript计算的<code>prop</code>值,它们必须用大括号括起来,例如<code>date={Date()}</code> 。 </section>
<add><section id='instructions'>
<add>代码编辑器中有<code>Calendar</code>和<code>CurrentDate</code>组件。从<code>Calendar</code>组件渲染<code>CurrentDate</code>时,从 JavaScript 的<code>Date</code>对象分配当前日期,并将其作为<code>date</code>属性传入。然后访问<code>CurrentDate</code>组件的<code>prop</code>,并在<code>p</code>标签中显示其值。请注意,要将<code>prop</code>的值视为 JavaScript,必须将它们括在花括号中,例如<code>date={Date()}</code>。
<add></section>
<ide>
<ide> ## Tests
<ide> <section id='tests'>
<ide>
<ide> ```yml
<ide> tests:
<del> - text: <code>Calendar</code>组件应返回单个<code>div</code>元素。
<del> testString: 'assert((function() { const mockedComponent = Enzyme.mount(React.createElement(Calendar)); return mockedComponent.children().type() === "div"; })(), "The <code>Calendar</code> component should return a single <code>div</code> element.");'
<del> - text: <code>Calendar</code>组件的第二个子<code>CurrentDate</code>应该是<code>CurrentDate</code>组件。
<del> testString: 'assert((function() { const mockedComponent = Enzyme.mount(React.createElement(Calendar)); return mockedComponent.children().childAt(1).name() === "CurrentDate"; })(), "The second child of the <code>Calendar</code> component should be the <code>CurrentDate</code> component.");'
<del> - text: <code>CurrentDate</code>组件应该有一个名为<code>date</code>的prop。
<del> testString: 'assert((function() { const mockedComponent = Enzyme.mount(React.createElement(Calendar)); return mockedComponent.children().childAt(1).props().date })(), "The <code>CurrentDate</code> component should have a prop called <code>date</code>.");'
<del> - text: <code>CurrentDate</code>的<code>date</code>道具应包含一串文本。
<del> testString: 'assert((function() { const mockedComponent = Enzyme.mount(React.createElement(Calendar)); const prop = mockedComponent.children().childAt(1).props().date; return( typeof prop === "string" && prop.length > 0 ); })(), "The <code>date</code> prop of the <code>CurrentDate</code> should contain a string of text.");'
<del> - text: <code>CurrentDate</code>组件应该从<code>p</code>标记中的<code>date</code>道具中呈现值。
<del> testString: 'assert((function() { const mockedComponent = Enzyme.mount(React.createElement(Calendar)); return mockedComponent.find("p").html().includes(Date().substr(3)); })(), "The <code>CurrentDate</code> component should render the value from the <code>date</code> prop in the <code>p</code> tag.");'
<add> - text: <code>Calendar</code>组件应该返回单个<code>div</code>元素。
<add> testString: assert((function() { const mockedComponent = Enzyme.mount(React.createElement(Calendar)); return mockedComponent.children().type() === 'div'; })());
<add> - text: <code>Calendar</code>组件的第二个子元素应该是<code>CurrentDate</code>组件。
<add> testString: assert((function() { const mockedComponent = Enzyme.mount(React.createElement(Calendar)); return mockedComponent.children().childAt(1).name() === 'CurrentDate'; })());
<add> - text: <code>CurrentDate</code>组件应该有一个名为<code>date</code>的属性。
<add> testString: assert((function() { const mockedComponent = Enzyme.mount(React.createElement(Calendar)); return mockedComponent.children().childAt(1).props().date })());
<add> - text: <code>CurrentDate</code>的<code>date</code>属性应该包含一段文本字符串。
<add> testString: assert((function() { const mockedComponent = Enzyme.mount(React.createElement(Calendar)); const prop = mockedComponent.children().childAt(1).props().date; return( typeof prop === 'string' && prop.length > 0 ); })());
<add> - text: <code>CurrentDate</code>组件应该把<code>date</code>属性渲染在<code>p</code>标签内。
<add> testString: assert(/<CurrentDatedate={Date\(\)}\/>/.test(code.replace(/\s/g, '')))
<add> - text: <code>CurrentDate</code> 组件应该把 <code>date</code> 属性渲染在 <code>p</code> 标签内。
<add> testString: let date = "dummy date"; assert((function() { const mockedComponent = Enzyme.mount(React.createElement(CurrentDate, {date})); return mockedComponent.find('p').html().includes(date); })());
<add>
<ide>
<ide> ```
<ide>
<ide> tests:
<ide> <div id='jsx-seed'>
<ide>
<ide> ```jsx
<add>
<ide> const CurrentDate = (props) => {
<ide> return (
<ide> <div>
<ide> class Calendar extends React.Component {
<ide> );
<ide> }
<ide> };
<del>
<ide> ```
<ide>
<ide> </div>
<ide> class Calendar extends React.Component {
<ide> <div id='jsx-teardown'>
<ide>
<ide> ```js
<del>console.info('after the test');
<add>ReactDOM.render(<Calendar />, document.getElementById('root'))
<ide> ```
<ide>
<ide> </div>
<ide> console.info('after the test');
<ide> ## Solution
<ide> <section id='solution'>
<ide>
<add>
<ide> ```js
<del>// solution required
<add>const CurrentDate = (props) => {
<add> return (
<add> <div>
<add> { /* change code below this line */ }
<add> <p>The current date is: {props.date}</p>
<add> { /* change code above this line */ }
<add> </div>
<add> );
<add>};
<add>
<add>class Calendar extends React.Component {
<add> constructor(props) {
<add> super(props);
<add> }
<add> render() {
<add> return (
<add> <div>
<add> <h3>What date is it?</h3>
<add> { /* change code below this line */ }
<add> <CurrentDate date={Date()} />
<add> { /* change code above this line */ }
<add> </div>
<add> );
<add> }
<add>};
<ide> ```
<ide>
<del>/section>
<add></section>
<ide><path>curriculum/challenges/chinese/03-front-end-libraries/react/pass-state-as-props-to-child-components.chinese.md
<ide> id: 5a24c314108439a4d403617a
<ide> title: Pass State as Props to Child Components
<ide> challengeType: 6
<ide> isRequired: false
<del>videoUrl: ''
<del>localeTitle: 将状态作为道具传递给子组件
<add>forumTopicId: 301403
<add>localeTitle: 将 State 作为 Props 传递给子组件
<ide> ---
<ide>
<ide> ## Description
<del><section id="description">您看到了许多在先前的挑战中将道具传递给子JSX元素和子React组件的示例。您可能想知道这些道具来自哪里。一种常见的模式是让一个有状态的组件包含对您的应用程序很重要的<code>state</code> ,然后呈现子组件。您希望这些组件可以访问该<code>state</code>某些部分,这些部分作为props传递。例如,您可能有一个<code>App</code>组件可以呈现<code>Navbar</code>以及其他组件。在您的<code>App</code> ,您的<code>state</code>包含大量用户信息,但<code>Navbar</code>只需要访问用户的用户名,以便显示它。您将该<code>state</code>作为prop传递给<code>Navbar</code>组件。这种模式说明了React中的一些重要范例。第一种是<em>单向数据流</em> 。状态沿着应用程序组件树的一个方向流动,从有状态父组件到子组件。子组件仅接收所需的状态数据。第二,复杂的有状态应用程序可以分解为几个或者一个有状态的组件。其余组件只是从父级接收状态作为props,并从该状态呈现UI。它开始创建一个分离,其中状态管理在代码的一部分中处理,而UI在另一部分中呈现。将状态逻辑与UI逻辑分离的原则是React的关键原则之一。当它被正确使用时,它使复杂的有状态应用程序的设计更容易管理。 </section>
<add><section id='description'>
<add>在之前的挑战中,你看到了很多将 props 传递给子 JSX 元素和子 React 组件的例子。你可能想知道那些 props 是从哪里来的。一个常见的模式是:有状态组件中包含对应用程序很重要的<code>state</code>,然后用它渲染子组件。你希望这些组件能够访问该<code>state</code>的某些部分,就把这些部分作为 props 传入。
<add>例如,也许你有一个<code>App</code>组件可以渲染<code>Navbar</code>以及其他组件。在你的<code>App</code>中,你的<code>state</code>中包含大量用户信息,但是<code>Navbar</code>只需要访问用户的用户名就可以显示出来,这时你将该<code>state</code>作为一个 prop 传递给<code>Navbar</code>组件即可。
<add>这个模式说明了 React 中的一些重要范例。第一个是<em>单向数据流</em>,state 沿着应用程序组件树的一个方向流动,从有状态父组件到子组件,子组件只接收它们需要的 state 数据。第二,复杂的有状态应用程序可以分解成几个,或者可能是一个单一的有状态组件。其余组件只是从父组件简单的接收 state 作为 props,并从该 state 渲染 UI。它开始创建一种分离,在这种分离中,state 管理在代码的一部分中处理,而 UI 渲染在另一部分中处理。将 state 逻辑与 UI 逻辑分离是 React 的关键原则之一。当它被正确使用时,它使得复杂的、有状态的应用程序的设计变得更容易管理。
<add></section>
<ide>
<ide> ## Instructions
<del><section id="instructions"> <code>MyApp</code>组件是有状态的,并将<code>Navbar</code>组件呈现为子组件。将<code>name</code>属性的<code>state</code>向下传递给子组件,然后在<code>h1</code>标记中显示该<code>name</code> ,该<code>name</code>是<code>Navbar</code> render方法的一部分。 </section>
<add><section id='instructions'>
<add><code>MyApp</code>组件是有状态的,它将<code>Navbar</code>组件渲染成它的为子组件。将<code>MyApp</code>组件<code>state</code>中的<code>name</code>属性向下传递给子组件,然后在<code>h1</code>标签中显示<code>name</code>,<code>name</code>是<code>Navbar</code>render 方法的一部分。
<add></section>
<ide>
<ide> ## Tests
<ide> <section id='tests'>
<ide>
<ide> ```yml
<ide> tests:
<del> - text: <code>MyApp</code>组件应该使用内部的<code>Navbar</code>组件进行渲染。
<add> - text: <code>MyApp</code>组件应该在内部渲染一个<code>Navbar</code>组件。
<ide> testString: assert((function() { const mockedComponent = Enzyme.mount(React.createElement(MyApp)); return mockedComponent.find('MyApp').length === 1 && mockedComponent.find('Navbar').length === 1; })());
<del> - text: <code>Navbar</code>组件应该将<code>MyApp</code>状态属性<code>name</code>作为props接收。
<add> - text: <code>Navbar</code>组件应该接收<code>Navbar</code>的 state 中的<code>name</code>属性作为 props。
<ide> testString: 'async () => { const waitForIt = (fn) => new Promise((resolve, reject) => setTimeout(() => resolve(fn()), 250)); const mockedComponent = Enzyme.mount(React.createElement(MyApp)); const setState = () => { mockedComponent.setState({name: ''TestName''}); return waitForIt(() => mockedComponent.find(''Navbar'').props() )}; const navProps = await setState(); assert(navProps.name === ''TestName''); }; '
<del> - text: <code>Navbar</code>的<code>h1</code>元素应该呈现<code>name</code> prop。
<add> - text: <code>Navbar</code>中的<code>h1</code>元素应该渲染 prop<code>name</code>。
<ide> testString: 'async () => { const waitForIt = (fn) => new Promise((resolve, reject) => setTimeout(() => resolve(fn()), 250)); const mockedComponent = Enzyme.mount(React.createElement(MyApp)); const navH1Before = mockedComponent.find(''Navbar'').find(''h1'').text(); const setState = () => { mockedComponent.setState({name: ''TestName''}); return waitForIt(() => mockedComponent.find(''Navbar'').find(''h1'').text() )}; const navH1After = await setState(); assert(new RegExp(''TestName'').test(navH1After) && navH1After !== navH1Before); }; '
<ide>
<ide> ```
<ide> class Navbar extends React.Component {
<ide> render() {
<ide> return (
<ide> <div>
<del> <h1>Hello, my name is: /* your code here */ </h1>
<add> <h1>Hello, my name is: {/* your code here */} </h1>
<ide> </div>
<ide> );
<ide> }
<ide> };
<del>
<ide> ```
<ide>
<ide> </div>
<ide> class Navbar extends React.Component {
<ide> <div id='jsx-teardown'>
<ide>
<ide> ```js
<del>console.info('after the test');
<add>ReactDOM.render(<MyApp />, document.getElementById('root'))
<ide> ```
<ide>
<ide> </div>
<ide> console.info('after the test');
<ide> ## Solution
<ide> <section id='solution'>
<ide>
<add>
<ide> ```js
<del>// solution required
<add>class MyApp extends React.Component {
<add> constructor(props) {
<add> super(props);
<add> this.state = {
<add> name: 'CamperBot'
<add> }
<add> }
<add> render() {
<add> return (
<add> <div>
<add> <Navbar name={this.state.name}/>
<add> </div>
<add> );
<add> }
<add>};
<add>class Navbar extends React.Component {
<add> constructor(props) {
<add> super(props);
<add> }
<add> render() {
<add> return (
<add> <div>
<add> <h1>Hello, my name is: {this.props.name}</h1>
<add> </div>
<add> );
<add> }
<add>};
<ide> ```
<ide>
<del>/section>
<add></section>
<ide><path>curriculum/challenges/chinese/03-front-end-libraries/react/render-a-class-component-to-the-dom.chinese.md
<ide> id: 5a24c314108439a4d4036167
<ide> title: Render a Class Component to the DOM
<ide> challengeType: 6
<ide> isRequired: false
<del>videoUrl: ''
<del>localeTitle: 将类组件渲染到DOM
<add>forumTopicId: 301404
<add>localeTitle: 渲染 class 组件为 Dom 树
<ide> ---
<ide>
<ide> ## Description
<del><section id="description">您可能还记得在早期挑战中使用ReactDOM API将JSX元素呈现给DOM。渲染React组件的过程看起来非常相似。过去的几个挑战集中在组件和组合上,因此渲染是在幕后为您完成的。但是,您编写的React代码都不会在不调用ReactDOM API的情况下呈现给DOM。这是对语法的更新: <code>ReactDOM.render(componentToRender, targetNode)</code> 。第一个参数是要呈现的React组件。第二个参数是要在其中呈现该组件的DOM节点。 React组件传递到<code>ReactDOM.render()</code>与JSX元素略有不同。对于JSX元素,您传入要呈现的元素的名称。但是,对于React组件,您需要使用与渲染嵌套组件相同的语法,例如<code>ReactDOM.render(<ComponentToRender />, targetNode)</code> 。您可以将此语法用于ES6类组件和功能组件。 </section>
<add><section id='description'>
<add>你可能还记得在早期挑战中使用 ReactDOM API 将 JSX 元素渲染到 DOM,这与渲染 React 组件的过程十分相似。过去的几个挑战主要针对组件和组合,因此渲染是在幕后为你完成的。但是,如果不调用 ReactDOM API,你编写的任何 React 代码都不会渲染到 DOM。
<add>以下是语法的复习:<code>ReactDOM.render(componentToRender, targetNode)</code>。第一个参数是要渲染的 React 组件。第二个参数是要在其中渲染该组件的 DOM 节点。
<add>React 组件传递到<code>ReactDOM.render()</code>与 JSX 元素略有不同。对于 JSX 元素,你传入的是要渲染的元素的名称。但是,对于 React 组件,你需要使用与渲染嵌套组件相同的语法,例如<code>ReactDOM.render(<ComponentToRender />, targetNode)</code>。你可以将此语法用于ES6类组件和函数组件。
<add></section>
<ide>
<ide> ## Instructions
<del><section id="instructions"> <code>Fruits</code>和<code>Vegetables</code>组件都是在幕后为您定义的。将两个组件渲染为<code>TypesOfFood</code>组件的<code>TypesOfFood</code>组件,然后将<code>TypesOfFood</code>呈现给DOM。有一个<code>div</code> , <code>id='challenge-node'</code>可供您使用。 </section>
<add><section id='instructions'>
<add>在后台为你定义了<code>Fruits</code>和<code>Vegetables</code>组件。将两个组件渲染为<code>TypesOfFood</code>组件的子组件,然后将<code>TypesOfFood</code>渲染到 DOM 节点,在这个挑战中,请渲染到 id 为<code>challenge-node</code>的<code>div</code>中。
<add></section>
<ide>
<ide> ## Tests
<ide> <section id='tests'>
<ide>
<ide> ```yml
<ide> tests:
<del> - text: <code>TypesOfFood</code>组件应返回单个<code>div</code>元素。
<add> - text: <code>TypesOfFood</code>组件应该返回单个<code>div</code>元素。
<ide> testString: assert((function() { const mockedComponent = Enzyme.mount(React.createElement(TypesOfFood)); return mockedComponent.children().type() === 'div'; })());
<del> - text: <code>TypesOfFood</code>组件应该在<code>h1</code>元素之后呈现<code>Fruits</code>组件。
<add> - text: <code>TypesOfFood</code>组件应该在<code>h1</code>元素之后渲染<code>Fruits</code>组件。
<ide> testString: assert((function() { const mockedComponent = Enzyme.mount(React.createElement(TypesOfFood)); return mockedComponent.children().childAt(1).name() === 'Fruits'; })());
<del> - text: <code>TypesOfFood</code>组件应该在<code>Fruits</code>之后呈现<code>Vegetables</code>组件。
<add> - text: <code>TypesOfFood</code>组件应该在<code>Fruits</code>组件之后渲染<code>Vegetables</code>组件。
<ide> testString: assert((function() { const mockedComponent = Enzyme.mount(React.createElement(TypesOfFood)); return mockedComponent.children().childAt(2).name() === 'Vegetables'; })());
<del> - text: <code>TypesOfFood</code>组件应该使用id <code>challenge-node</code>呈现给<code>div</code>的DOM。
<add> - text: <code>TypesOfFood</code>组件应该渲染到 id 为<code>challenge-node</code>的<code>div</code>中。
<ide> testString: assert((function() { const html = document.getElementById('challenge-node').childNodes[0].innerHTML; return html.includes('<div><h2>Fruits:</h2><h4>Non-Citrus:</h4><ul><li>Apples</li><li>Blueberries</li><li>Strawberries</li><li>Bananas</li></ul><h4>Citrus:</h4><ul><li>Lemon</li><li>Lime</li><li>Orange</li><li>Grapefruit</li></ul></div>') && html.includes('<div><h2>Vegetables:</h2><ul><li>Brussel Sprouts</li><li>Broccoli</li><li>Squash</li></ul></div>'); })());
<ide>
<ide> ```
<ide> tests:
<ide> <div id='jsx-seed'>
<ide>
<ide> ```jsx
<add>
<ide> class TypesOfFood extends React.Component {
<ide> constructor(props) {
<ide> super(props);
<ide> class TypesOfFood extends React.Component {
<ide> <div id='jsx-setup'>
<ide>
<ide> ```jsx
<add>
<ide> const Fruits = () => {
<ide> return (
<ide> <div>
<ide> const Vegetables = () => {
<ide> ## Solution
<ide> <section id='solution'>
<ide>
<add>
<ide> ```js
<del>// solution required
<add>class TypesOfFood extends React.Component {
<add> constructor(props) {
<add> super(props);
<add> }
<add> render() {
<add> return (
<add> <div>
<add> <h1>Types of Food:</h1>
<add> {/* change code below this line */}
<add> <Fruits />
<add> <Vegetables />
<add> {/* change code above this line */}
<add> </div>
<add> );
<add> }
<add>};
<add>
<add>// change code below this line
<add>ReactDOM.render(<TypesOfFood />, document.getElementById('challenge-node'));
<ide> ```
<ide>
<del>/section>
<add></section>
<ide><path>curriculum/challenges/chinese/03-front-end-libraries/react/render-conditionally-from-props.chinese.md
<ide> id: 5a24c314108439a4d4036188
<ide> title: Render Conditionally from Props
<ide> challengeType: 6
<ide> isRequired: false
<del>videoUrl: ''
<del>localeTitle: 从道具有条理地渲染
<add>forumTopicId: 301405
<add>localeTitle: 根据 Props 有条件地渲染
<ide> ---
<ide>
<ide> ## Description
<del><section id="description">到目前为止,您已经了解了如何使用<code>if/else</code> , <code>&&,</code> <code>null</code>和三元运算符( <code>condition ? expressionIfTrue : expressionIfFalse</code> )来做出有关呈现内容和何时呈现的条件决策。但是,还有一个重要的话题要讨论,它可以让你将这些概念中的任何一个或全部与另一个强大的React功能结合起来:道具。使用props来有条件地呈现代码对于React开发人员来说非常普遍 - 也就是说,他们使用给定prop的值来自动决定渲染内容。在此挑战中,您将设置子组件以根据道具进行渲染决策。您还将使用三元运算符,但您可以看到在最后几个挑战中涵盖的其他几个概念在此上下文中可能同样有用。 </section>
<add><section id='description'>
<add>到目前为止,你已经看到了如何使用<code>if/else</code>、<code>&&,</code>、<code>null</code>和三元运算符(<code>condition ? expressionIfTrue : expressionIfFalse</code>)对渲染什么和何时渲染做出有条件的判定。然而,还有一个重要的话题需要讨论,让你将这些概念中的任何一个或所有概念与另一个强大的 React 功能结合起来:props。使用 props 有条件地渲染代码在 React 开发人员中很常见--也就是说:他们使用给定 prop 的值来自动决定渲染什么。
<add>在这个挑战中,你将设置一个子组件来根据 props 做出渲染决定。你可以使用三元运算符,但是你可以看到过去几个挑战中涵盖的其他几个概念在这种情况下可能同样有用。
<add></section>
<ide>
<ide> ## Instructions
<del><section id="instructions">代码编辑器有两个部分为您定义的组件:名为<code>GameOfChance</code>的父<code>GameOfChance</code>和名为<code>Results</code>的子级。它们用于创建一个简单的游戏,用户按下按钮以查看它们是赢还是输。首先,您需要一个简单的表达式,每次运行时都会随机返回一个不同的值。您可以使用<code>Math.random()</code> 。每次调用此方法时,此方法返回<code>0</code> (包括)和<code>1</code> (不包括)之间的值。因此,对于50/50赔率,请在表达式中使用<code>Math.random() > .5</code> 。从统计学上讲,这个表达式将在50%的时间内返回<code>true</code> ,而在其他50%时则返回<code>false</code> 。在第30行,用此表达式替换注释以完成变量声明。现在您有了一个表达式,您可以使用该表达式在代码中做出随机决策。接下来,您需要实现此功能。将<code>Results</code>组件渲染为<code>GameOfChance</code>的子<code>GameOfChance</code> ,并将<code>expression</code>作为名为<code>fiftyFifty</code>的prop <code>fiftyFifty</code> 。在<code>Results</code>组件中,编写一个三元表达式来呈现文本<code>"You win!"</code>或者<code>"You lose!"</code>基于从<code>GameOfChance</code>传入的<code>fiftyFifty</code>道具。最后,确保<code>handleClick()</code>方法正确计算每个回合,以便用户知道他们玩了多少次。这也用于让用户知道组件已经实际更新,以防它们连续两次赢或输。 </section>
<add><section id='instructions'>
<add>代码编辑器有两个部分为你定义的组件:一个名为<code>GameOfChance</code>的父组件和一个名为<code>Results</code>的子组件。他们被用来创建一个简单的游戏,用户按下按钮来看他们是赢还是输。
<add>首先,你需要一个简单的表达式,每次运行时都会随机返回一个不同的值。你可以使用<code>Math.random()</code>。每次调用此方法时,此方法返回<code>0</code>(包括)和<code>1</code>(不包括)之间的值。因此,对于50/50的几率,请在表达式中使用<code>Math.random() > .5</code>。从统计学上讲,这个表达式有 50% 的几率返回<code>true</code>,另外 50% 返回<code>false</code>。在第 30 行,用此表达式替换注释以完成变量声明。
<add>现在你有了一个表达式,可以用来在代码中做出随机决定,接下来你需要实现以下功能:将<code>Results</code>组件渲染为<code>GameOfChance</code>的子组件,并将<code>expression</code>作为 prop 传递出去,prop 的名字是<code>fiftyFifty</code>。在<code>Results</code>组件中,编写一个三元表达式基于从<code>GameOfChance</code>传来的 prop<code>fiftyFifty</code>来渲染文本<code>"You win!"</code>或者<code>"You lose!"</code>。最后,确保<code>handleClick()</code>方法正确计算每个回合,以便用户知道他们玩过多少次。这也可以让用户知道组件实际上已经更新,以防他们连续赢两次或输两次时自己不知道。
<add></section>
<ide>
<ide> ## Tests
<ide> <section id='tests'>
<ide>
<ide> ```yml
<ide> tests:
<del> - text: <code>GameOfChance</code>组件应存在并呈现给页面。
<add> - text: <code>GameOfChance</code>组件应该存在并渲染到页面。
<ide> testString: assert.strictEqual(Enzyme.mount(React.createElement(GameOfChance)).find('GameOfChance').length, 1);
<del> - text: <code>GameOfChance</code>应返回单个<code>button</code>元素。
<add> - text: <code>GameOfChance</code>应该返回单个<code>button</code>元素。
<ide> testString: assert.strictEqual(Enzyme.mount(React.createElement(GameOfChance)).find('button').length, 1);
<del> - text: <code>GameOfChance</code>应返回<code>Results</code>组件的单个实例,其中有一个名为<code>fiftyFifty</code>的prop。
<add> - text: <code>GameOfChance</code>应该返回<code>Results</code>组件的一个实例,它有一个名为<code>fiftyFifty</code>的 prop。
<ide> testString: assert(Enzyme.mount(React.createElement(GameOfChance)).find('Results').length === 1 && Enzyme.mount(React.createElement(GameOfChance)).find('Results').props().hasOwnProperty('fiftyFifty') === true);
<del> - text: 应该使用<code>counter</code>设置为值<code>1</code>的属性初始化<code>GameOfChance</code>状态。
<add> - text: <code>GameOfChance</code>的 state 应该使用值为<code>1</code>的<code>counter</code>属性来初始化。
<ide> testString: assert.strictEqual(Enzyme.mount(React.createElement(GameOfChance)).state().counter, 1);
<del> - text: '当<code>GameOfChance</code>组件首次呈现给DOM时,应返回一个<code>p</code>元素,内部文本为<code>Turn: 1</code> 。'
<add> - text: '当<code>GameOfChance</code>组件第一次渲染到 DOM 时,应该返回一个<code>p</code>元素,其内部文本为<code>Turn: 1</code>。'
<ide> testString: 'assert.strictEqual(Enzyme.mount(React.createElement(GameOfChance)).find(''p'').text(), ''Turn: 1'');'
<del> - text: 每次单击该按钮时,计数器状态应增加值1,并且应将单个<code>p</code>元素呈现给包含文本“Turn:N”的DOM,其中N是计数器状态的值。
<add> - text: '每次点击按钮,counter 应该增加 1,并且一个包含文本<code>"Turn: N"</code>的<code>p</code>元素应该渲染到DOM,其中<code>N</code>是 counter 的值。'
<ide> testString: 'async () => { const waitForIt = (fn) => new Promise((resolve, reject) => setTimeout(() => resolve(fn()), 250)); const comp = Enzyme.mount(React.createElement(GameOfChance)); const simulate = () => { comp.find(''button'').simulate(''click''); };const result = () => ({ count: comp.state(''counter''), text: comp.find(''p'').text() });const _1 = () => { simulate(); return waitForIt(() => result())}; const _2 = () => { simulate(); return waitForIt(() => result())}; const _3 = () => { simulate(); return waitForIt(() => result())}; const _4 = () => { simulate(); return waitForIt(() => result())}; const _5 = () => { simulate(); return waitForIt(() => result())}; const _1_val = await _1(); const _2_val = await _2(); const _3_val = await _3(); const _4_val = await _4(); const _5_val = await _5(); assert(_1_val.count === 2 && _1_val.text === ''Turn: 2'' && _2_val.count === 3 && _2_val.text === ''Turn: 3'' && _3_val.count === 4 && _3_val.text === ''Turn: 4'' && _4_val.count === 5 && _4_val.text === ''Turn: 5'' && _5_val.count === 6 && _5_val.text === ''Turn: 6''); }; '
<del> - text: 首次将<code>GameOfChance</code>组件安装到DOM时,每次单击该按钮时,应返回单个<code>h1</code>元素,随机呈现<code>You Win!</code>或者<code>You Lose!</code> 。
<add> - text: 当<code>GameOfChance</code>组件第一次挂载到 DOM 上时,每次按钮被点击,都应该返回一个<code>h1</code>元素,元素中随机渲染<code>You Win!</code>或者<code>You Lose!</code>。
<ide> testString: 'async () => { const waitForIt = (fn) => new Promise((resolve, reject) => setTimeout(() => resolve(fn()), 250)); const comp = Enzyme.mount(React.createElement(GameOfChance)); const simulate = () => { comp.find(''button'').simulate(''click''); };const result = () => ({ h1: comp.find(''h1'').length, text: comp.find(''h1'').text() });const _1 = result(); const _2 = () => { simulate(); return waitForIt(() => result())}; const _3 = () => { simulate(); return waitForIt(() => result())}; const _4 = () => { simulate(); return waitForIt(() => result())}; const _5 = () => { simulate(); return waitForIt(() => result())}; const _6 = () => { simulate(); return waitForIt(() => result())}; const _7 = () => { simulate(); return waitForIt(() => result())}; const _8 = () => { simulate(); return waitForIt(() => result())}; const _9 = () => { simulate(); return waitForIt(() => result())}; const _10 = () => { simulate(); return waitForIt(() => result())}; const _2_val = await _2(); const _3_val = await _3(); const _4_val = await _4(); const _5_val = await _5(); const _6_val = await _6(); const _7_val = await _7(); const _8_val = await _8(); const _9_val = await _9(); const _10_val = await _10(); const __text = new Set([_1.text, _2_val.text, _3_val.text, _4_val.text, _5_val.text, _6_val.text, _7_val.text, _8_val.text, _9_val.text, _10_val.text]); const __h1 = new Set([_1.h1, _2_val.h1, _3_val.h1, _4_val.h1, _5_val.h1, _6_val.h1, _7_val.h1, _8_val.h1, _9_val.h1, _10_val.h1]); assert(__text.size === 2 && __h1.size === 1); }; '
<ide>
<ide> ```
<ide> class GameOfChance extends React.Component {
<ide> });
<ide> }
<ide> render() {
<del> let expression = null; // change code here
<add> const expression = null; // change code here
<ide> return (
<ide> <div>
<ide> <button onClick={this.handleClick}>Play Again</button>
<ide> class GameOfChance extends React.Component {
<ide> );
<ide> }
<ide> };
<del>
<ide> ```
<ide>
<ide> </div>
<ide> class GameOfChance extends React.Component {
<ide> <div id='jsx-teardown'>
<ide>
<ide> ```js
<del>console.info('after the test');
<add>ReactDOM.render(<GameOfChance />, document.getElementById('root'))
<ide> ```
<ide>
<ide> </div>
<ide> console.info('after the test');
<ide> ## Solution
<ide> <section id='solution'>
<ide>
<add>
<ide> ```js
<del>// solution required
<add>class Results extends React.Component {
<add> constructor(props) {
<add> super(props);
<add> }
<add> render() {
<add> return (
<add> <h1>
<add> {
<add> this.props.fiftyFifty ?
<add> 'You Win!' :
<add> 'You Lose!'
<add> }
<add> </h1>
<add> )
<add> };
<add>};
<add>
<add>class GameOfChance extends React.Component {
<add> constructor(props) {
<add> super(props);
<add> this.state = {
<add> counter: 1
<add> }
<add> this.handleClick = this.handleClick.bind(this);
<add> }
<add> handleClick() {
<add> this.setState({
<add> counter: this.state.counter + 1
<add> });
<add> }
<add> render() {
<add> const expression = Math.random() >= .5;
<add> return (
<add> <div>
<add> <button onClick={this.handleClick}>Play Again</button>
<add> <Results fiftyFifty={expression} />
<add> <p>{'Turn: ' + this.state.counter}</p>
<add> </div>
<add> );
<add> }
<add>};
<ide> ```
<ide>
<del>/section>
<add></section>
<ide><path>curriculum/challenges/chinese/03-front-end-libraries/react/render-html-elements-to-the-dom.chinese.md
<ide> id: 5a24bbe0dba28a8d3cbd4c5f
<ide> title: Render HTML Elements to the DOM
<ide> challengeType: 6
<ide> isRequired: false
<del>videoUrl: ''
<del>localeTitle: 将HTML元素渲染到DOM
<add>forumTopicId: 301406
<add>localeTitle: 渲染 HTML 元素为 DOM 树
<ide> ---
<ide>
<ide> ## Description
<del><section id="description">到目前为止,您已经了解到JSX是一种在JavaScript中编写可读HTML的便捷工具。使用React,我们可以使用React的渲染API(称为ReactDOM)将此JSX直接渲染到HTML DOM。 ReactDOM提供了一种简单的方法来将React元素呈现给DOM,如下所示: <code>ReactDOM.render(componentToRender, targetNode)</code> ,其中第一个参数是要呈现的React元素或组件,第二个参数是DOM节点您想要将组件渲染到。正如您所料,必须在JSX元素声明之后调用<code>ReactDOM.render()</code> ,就像在使用它们之前必须声明变量一样。 </section>
<add><section id='description'>
<add>到目前为止,你已经了解到 JSX 是一种在 JavaScript 中编写可读 HTML 的便捷工具。在 React 中,我们可以使用它的的渲染 API(ReactDOM)将此 JSX 直接渲染到 HTML DOM。
<add>ReactDOM 提供了一个简单的方法来将 React 元素呈现给 DOM,如下所示:<code>ReactDOM.render(componentToRender, targetNode)</code>,其中第一个参数是要渲染的 React 元素或组件,第二个参数是要将组件渲染到的 DOM 节点。
<add>如你所料,必须在 JSX 元素声明之后调用<code>ReactDOM.render()</code>,就像你在使用变量之前必须声明它一样。
<add></section>
<ide>
<ide> ## Instructions
<del><section id="instructions">代码编辑器有一个简单的JSX组件。使用<code>ReactDOM.render()</code>方法将此组件呈现给页面。您可以直接将定义的JSX元素作为第一个参数传递,并使用<code>document.getElementById()</code>来选择要将其渲染到的DOM节点。有一个<code>div</code> , <code>id='challenge-node'</code>可供您使用。确保不要更改<code>JSX</code>常量。 </section>
<add><section id='instructions'>
<add>代码编辑器有一个简单的 JSX 组件。使用<code>ReactDOM.render()</code>方法将该组件渲染到页面。可以将定义好的 JSX 元素直接作为第一个参数传入,并使用<code>document.getElementById()</code>来选择要渲染到的 DOM 节点,在这个挑战中,请渲染到 id 为<code>challenge-node</code>的<code>div</code>中。
<add></section>
<ide>
<ide> ## Tests
<ide> <section id='tests'>
<ide> localeTitle: 将HTML元素渲染到DOM
<ide> tests:
<ide> - text: 常量<code>JSX</code>应该返回一个<code>div</code>元素。
<ide> testString: assert(JSX.type === 'div');
<del> - text: <code>div</code>应包含一个<code>h1</code>标记作为第一个元素。
<add> - text: <code>div</code>应该包含一个<code>h1</code>标签作为第一个元素。
<ide> testString: assert(JSX.props.children[0].type === 'h1');
<ide> - text: <code>div</code>应该包含一个<code>p</code>标签作为第二个元素。
<ide> testString: assert(JSX.props.children[1].type === 'p');
<del> - text: 提供的JSX元素应该使用id <code>challenge-node</code>呈现给DOM <code>challenge-node</code> 。
<add> - text: 提供的 JSX 元素应该渲染到 id 为<code>challenge-node</code>的 DOM 节点。
<ide> testString: assert(document.getElementById('challenge-node').childNodes[0].innerHTML === '<h1>Hello World</h1><p>Lets render this to the DOM</p>');
<ide>
<ide> ```
<ide> const JSX = (
<ide> ## Solution
<ide> <section id='solution'>
<ide>
<add>
<ide> ```js
<del>// solution required
<add>const JSX = (
<add><div>
<add> <h1>Hello World</h1>
<add> <p>Lets render this to the DOM</p>
<add></div>
<add>);
<add>// change code below this line
<add>ReactDOM.render(JSX, document.getElementById('challenge-node'));
<ide> ```
<ide>
<del>/section>
<add></section>
<ide><path>curriculum/challenges/chinese/03-front-end-libraries/react/render-react-on-the-server-with-rendertostring.chinese.md
<ide> id: 5a24c314108439a4d403618d
<ide> title: Render React on the Server with renderToString
<ide> challengeType: 6
<ide> isRequired: false
<del>videoUrl: ''
<del>localeTitle: 使用renderToString在服务器上渲染React
<add>forumTopicId: 301407
<add>localeTitle: 用 renderToString 在服务器上渲染 React
<ide> ---
<ide>
<ide> ## Description
<del><section id="description">到目前为止,您已在客户端上呈现React组件。通常,这是你将永远做的。但是,在某些用例中,在服务器上呈现React组件是有意义的。由于React是一个JavaScript视图库,您可以使用Node在服务器上运行JavaScript,这是可能的。实际上,React提供了一个<code>renderToString()</code>方法,您可以将其用于此目的。有两个关键原因可以解释为什么服务器上的渲染可能会在真实世界的应用程序中使用。首先,如果不这样做,你的React应用程序将包含一个相对空的HTML文件和一大堆JavaScript,当它最初加载到浏览器时。对于试图索引页面内容以便人们可以找到您的搜索引擎而言,这可能并不理想。如果在服务器上呈现初始HTML标记并将其发送到客户端,则初始页面加载包含搜索引擎可以抓取的所有页面标记。其次,这会创建更快的初始页面加载体验,因为呈现的HTML小于整个应用程序的JavaScript代码。 React仍然能够识别您的应用并在初始加载后进行管理。 </section>
<add><section id='description'>
<add>到目前为止,你已经能够在客户端上渲染 React 组件,一般来说我们都是这么做的。然而,在一些用例中,在服务器上渲染一个 React 组件是有意义的。由于 React 是一个 JavaScript 视图库,所以使用 Node 让 JavaScript 运行在服务器上是可行的。事实上,React 提供了一个可用于此目的的<code>renderToString()</code>方法。
<add>有两个关键原因可以解释为什么服务器上的渲染可能会在真实世界的应用程序中使用。首先,如果不这样做,你的 React 应用程序将包含一个代码量很少的 HTML 文件和一大堆 JavaScript,当它最初加载到浏览器时。这对于搜索引擎来说可能不太理想,因为它们试图为你的网页内容生成索引,以便人们可以找到你。如果在服务器上渲染初始 HTML 标记并将其发送到客户端,则初始页面加载的内容包含搜索引擎可以抓取的所有页面标记。其次,这创造了更快的初始页面加载体验,因为渲染的 HTML 代码量要比整个应用程序的 JavaScript 代码小。React 仍然能够识别你的应用并在初始加载后进行管理。
<add></section>
<ide>
<ide> ## Instructions
<del><section id="instructions"> <code>renderToString()</code>方法在<code>ReactDOMServer</code>上提供,在此处可用作全局对象。该方法采用一个参数,它是一个React元素。使用此选项将<code>App</code>呈现为字符串。 </section>
<add><section id='instructions'>
<add><code>renderToString()</code>方法由<code>ReactDOMServer</code>提供,在这里已为你定义成全局变量。这个方法接受一个 React 元素作为参数。用它来把<code>App</code>渲染成字符串。
<add></section>
<ide>
<ide> ## Tests
<ide> <section id='tests'>
<ide>
<ide> ```yml
<ide> tests:
<del> - text: <code>App</code>组件应使用<code>ReactDOMServer.renderToString</code>呈现为字符串。
<add> - text: <code>App</code>组件应该使用<code>ReactDOMServer.renderToString</code>渲染一个字符串。
<ide> testString: getUserInput => assert(getUserInput('index').replace(/ /g,'').includes('ReactDOMServer.renderToString(<App/>)') && Enzyme.mount(React.createElement(App)).children().name() === 'div');
<ide>
<ide> ```
<ide> tests:
<ide> <div id='jsx-seed'>
<ide>
<ide> ```jsx
<add>
<ide> class App extends React.Component {
<ide> constructor(props) {
<ide> super(props);
<ide> class App extends React.Component {
<ide>
<ide> ```jsx
<ide> var ReactDOMServer = { renderToString(x) { return null; } };
<del>
<ide> ```
<ide>
<ide> </div>
<ide> var ReactDOMServer = { renderToString(x) { return null; } };
<ide> <div id='jsx-teardown'>
<ide>
<ide> ```js
<del>console.info('after the test');
<add>ReactDOM.render(<App />, document.getElementById('root'))
<ide> ```
<ide>
<ide> </div>
<ide> console.info('after the test');
<ide> ## Solution
<ide> <section id='solution'>
<ide>
<add>
<ide> ```js
<del>// solution required
<add>class App extends React.Component {
<add> constructor(props) {
<add> super(props);
<add> }
<add> render() {
<add> return <div/>
<add> }
<add>};
<add>
<add>// change code below this line
<add>ReactDOMServer.renderToString(<App/>);
<ide> ```
<ide>
<del>/section>
<add></section>
<ide><path>curriculum/challenges/chinese/03-front-end-libraries/react/render-state-in-the-user-interface-another-way.chinese.md
<ide> id: 5a24c314108439a4d4036172
<ide> title: Render State in the User Interface Another Way
<ide> challengeType: 6
<ide> isRequired: false
<del>videoUrl: ''
<del>localeTitle: 用户界面中的渲染状态另一种方式
<add>forumTopicId: 301408
<add>localeTitle: 以另一种方式在用户界面中渲染状态
<ide> ---
<ide>
<ide> ## Description
<del><section id="description">还有另一种访问组件中<code>state</code>方法。在<code>render()</code>方法中,在<code>return</code>语句之前,您可以直接编写JavaScript。例如,您可以声明函数,从<code>state</code>或<code>props</code>访问数据,对此数据执行计算,等等。然后,您可以将任何数据分配给您可以在<code>return</code>语句中访问的变量。 </section>
<add><section id='description'>
<add>还有另一种方法可以访问组件中的<code>state</code>。在<code>render()</code>方法中,在<code>return</code>语句之前,你可以直接编写 JavaScript。例如,你可以声明函数、从<code>state</code>或<code>props</code>访问数据、对此数据执行计算等。然后,你可以将任何数据赋值给你在<code>return</code>语句中可以访问的变量。
<add></section>
<ide>
<ide> ## Instructions
<del><section id="instructions">在<code>MyComponent</code> render方法中,定义一个名为<code>name</code>的<code>const</code> ,并将其设置为等于组件<code>state</code>的name值。因为您可以直接在代码的这一部分编写JavaScript,所以您不必将此引用括在花括号中。接下来,在return语句中,使用变量<code>name</code>在<code>h1</code>标记中呈现此值。请记住,您需要在return语句中使用JSX语法(JavaScript的大括号)。 </section>
<add><section id='instructions'>
<add>在<code>MyComponent</code>的 render 方法中,定义一个名为<code>name</code>的<code>常量</code>,并将其设置为组件<code>state</code>中的 name 值。因为可以直接在代码部分编写 JavaScript,所以不需要用大括号括起来。
<add>接下来,在 return 语句中,在<code>h1</code>标签中渲染变量<code>name</code>的值。记住,在 return 语句中需要使用 JSX 语法(用到 JavaScript 的花括号)。
<add></section>
<ide>
<ide> ## Tests
<ide> <section id='tests'>
<ide>
<ide> ```yml
<ide> tests:
<del> - text: <code>MyComponent</code>应该有一个键<code>name</code> ,其<code>freeCodeCamp</code>值存储在其状态中。
<add> - text: <code>MyComponent</code>应该有一个键<code>name</code>,其值<code>freeCodeCamp</code>存储在其 state 中。
<ide> testString: assert(Enzyme.mount(React.createElement(MyComponent)).state('name') === 'freeCodeCamp');
<del> - text: <code>MyComponent</code>应该渲染一个包含在单个<code>div</code>的<code>h1</code>标头。
<add> - text: <code>MyComponent</code>应该在<code>div</code>中渲染一个<code>h1</code>标题。
<ide> testString: assert(/<div><h1>.*<\/h1><\/div>/.test(Enzyme.mount(React.createElement(MyComponent)).html()));
<del> - text: '渲染的<code>h1</code>标记应包含对<code>{name}</code>的引用。'
<add> - text: 渲染的<code>h1</code>标签应该包含<code>{name}</code>的引用。
<ide> testString: getUserInput => assert(/<h1>\n*\s*\{\s*name\s*\}\s*\n*<\/h1>/.test(getUserInput('index')));
<del> - text: 渲染的<code>h1</code>标头应包含从组件状态呈现的文本。
<add> - text: 渲染的<code>h1</code>标题中应该包含一段文本,这段文本是从组件的 state 中渲染出来的。
<ide> testString: 'async () => { const waitForIt = (fn) => new Promise((resolve, reject) => setTimeout(() => resolve(fn()), 250)); const mockedComponent = Enzyme.mount(React.createElement(MyComponent)); const first = () => { mockedComponent.setState({ name: ''TestName'' }); return waitForIt(() => mockedComponent.html()) }; const firstValue = await first(); assert(firstValue === ''<div><h1>TestName</h1></div>''); };'
<ide>
<ide> ```
<ide> class MyComponent extends React.Component {
<ide> );
<ide> }
<ide> };
<del>
<ide> ```
<ide>
<ide> </div>
<ide> class MyComponent extends React.Component {
<ide> <div id='jsx-teardown'>
<ide>
<ide> ```js
<del>console.info('after the test');
<add>ReactDOM.render(<MyComponent />, document.getElementById('root'))
<ide> ```
<ide>
<ide> </div>
<ide> console.info('after the test');
<ide> ## Solution
<ide> <section id='solution'>
<ide>
<add>
<ide> ```js
<del>// solution required
<add>class MyComponent extends React.Component {
<add> constructor(props) {
<add> super(props);
<add> this.state = {
<add> name: 'freeCodeCamp'
<add> }
<add> }
<add> render() {
<add> // change code below this line
<add> const name = this.state.name;
<add> // change code above this line
<add> return (
<add> <div>
<add> { /* change code below this line */ }
<add> <h1>{name}</h1>
<add> { /* change code above this line */ }
<add> </div>
<add> );
<add> }
<add>};
<ide> ```
<ide>
<del>/section>
<add></section>
<ide><path>curriculum/challenges/chinese/03-front-end-libraries/react/render-state-in-the-user-interface.chinese.md
<ide> id: 5a24c314108439a4d4036171
<ide> title: Render State in the User Interface
<ide> challengeType: 6
<ide> isRequired: false
<del>videoUrl: ''
<add>forumTopicId: 301409
<ide> localeTitle: 在用户界面中渲染状态
<ide> ---
<ide>
<ide> ## Description
<del><section id="description">定义组件的初始状态后,可以在呈现的UI中显示它的任何部分。如果组件是有状态的,它将始终可以访问其<code>render()</code>方法中的<code>state</code>数据。您可以使用<code>this.state</code>访问数据。如果要在render方法的<code>return</code>中访问状态值,则必须将值括在花括号中。 <code>State</code>是React中组件最强大的功能之一。它允许您跟踪应用程序中的重要数据并呈现UI以响应此数据中的更改。如果您的数据发生变化,您的UI将会发生变化React使用所谓的虚拟DOM来跟踪幕后的变化。当状态数据更新时,它会触发使用该数据重新呈现组件 - 包括作为道具接收数据的子组件。 React更新实际的DOM,但仅在必要时更新。这意味着您不必担心更改DOM。您只需声明UI应该是什么样子。请注意,如果使组件有状态,则其他组件不会知道其<code>state</code> 。它的<code>state</code>是完全封装的,或者是该组件的本地状态,除非您将状态数据作为<code>props</code>传递给子组件。这种封装<code>state</code>概念非常重要,因为它允许您编写某些逻辑,然后在代码中的某个位置包含和隔离该逻辑。 </section>
<add><section id='description'>
<add>一旦定义了组件的初始 state,你就可以在要渲染的 UI 中显示它的任何部分。如果组件是有状态的,它将始终可以访问<code>render()</code>方法中<code>state</code>的数据。你就可以使用<code>this.state</code>访问数据。
<add>如果你想在 render 方法的<code>return</code>中访问 state 值,你必须把这个值用花括号括起来。
<add><code>state</code>是 React 组件中最强大的特性之一,它允许你跟踪应用程序中的重要数据,并根据数据的变化渲染 UI。如果你的数据发生变化,你的 UI 也会随之改变。React 使用所谓的虚拟 DOM 来跟踪幕后的变化。当 state 数据更新时,它会使用该数据触发组件的重新渲染--包括接收 prop 数据的子组件。React 只在必要的时候更新实际的DOM,这意味着你不必担心 DOM 的变更,只需声明 UI 的外观即可。
<add>注意,如果组件有状态,则没有其他组件知道它的<code>state</code>。它的<code>state</code>是完全封装的,或者是局限于组件本身的,除非你将 state 数据作为<code>props</code>传递给子组件。封装<code>state</code>的概念非常重要,因为它允许你编写特定的逻辑,然后将该逻辑包含并隔离在代码中的某个位置。
<add></section>
<ide>
<ide> ## Instructions
<del><section id="instructions">在代码编辑器中, <code>MyComponent</code>已经是有状态的。在组件的render方法中定义<code>h1</code>标记,该方法从组件的状态呈现<code>name</code>的值。 <strong>注意:</strong> <code>h1</code>应该只从<code>state</code>呈现值而不是其他内容。在JSX中,您使用花括号<code>{ }</code>编写的任何代码都将被视为JavaScript。因此,要从<code>state</code>访问值,只需将引用括在花括号中。 </section>
<add><section id='instructions'>
<add>在代码编辑器中,<code>MyComponent</code>是一个有状态组件,在组件的 render 方法中定义一个<code>h1</code>标签,该方法从组件的 state 渲染<code>name</code>的值。
<add><strong>注意:</strong> <code>h1</code>应该只渲染来自<code>state</code>的值。在 JSX 中,使用花括号<code>{ }</code>编写的任何代码都将被视为 JavaScript。因此,要访问<code>state</code>中的值,只需将引用括在花括号中即可。
<add></section>
<ide>
<ide> ## Tests
<ide> <section id='tests'>
<ide>
<ide> ```yml
<ide> tests:
<del> - text: <code>MyComponent</code>应该有一个键<code>name</code> ,其<code>freeCodeCamp</code>值存储在其状态中。
<add> - text: <code>MyComponent</code>应该有一个键<code>name</code>,其值<code>freeCodeCamp</code>存储在其 state 中。
<ide> testString: assert(Enzyme.mount(React.createElement(MyComponent)).state('name') === 'freeCodeCamp');
<del> - text: <code>MyComponent</code>应该渲染一个包含在单个<code>div</code>的<code>h1</code>标头。
<add> - text: <code>MyComponent</code>应该在<code>div</code>中渲染一个<code>h1</code>标题。
<ide> testString: assert(/<div><h1>.*<\/h1><\/div>/.test(Enzyme.mount(React.createElement(MyComponent)).html()));
<del> - text: 渲染的<code>h1</code>标头应包含从组件状态呈现的文本。
<add> - text: 渲染的<code>h1</code>标题中应该包含一段文本,这段文本是从组件的 state 中渲染出来的。
<ide> testString: 'async () => { const waitForIt = (fn) => new Promise((resolve, reject) => setTimeout(() => resolve(fn()), 250)); const mockedComponent = Enzyme.mount(React.createElement(MyComponent)); const first = () => { mockedComponent.setState({ name: ''TestName'' }); return waitForIt(() => mockedComponent.html()) }; const firstValue = await first(); assert(firstValue === ''<div><h1>TestName</h1></div>'');};'
<ide>
<ide> ```
<ide> class MyComponent extends React.Component {
<ide> );
<ide> }
<ide> };
<del>
<ide> ```
<ide>
<ide> </div>
<ide> class MyComponent extends React.Component {
<ide> <div id='jsx-teardown'>
<ide>
<ide> ```js
<del>console.info('after the test');
<add>ReactDOM.render(<MyComponent />, document.getElementById('root'))
<ide> ```
<ide>
<ide> </div>
<ide> console.info('after the test');
<ide> ## Solution
<ide> <section id='solution'>
<ide>
<add>
<ide> ```js
<del>// solution required
<add>class MyComponent extends React.Component {
<add> constructor(props) {
<add> super(props);
<add> this.state = {
<add> name: 'freeCodeCamp'
<add> }
<add> }
<add> render() {
<add> return (
<add> <div>
<add> { /* change code below this line */ }
<add> <h1>{this.state.name}</h1>
<add> { /* change code above this line */ }
<add> </div>
<add> );
<add> }
<add>};
<ide> ```
<ide>
<del>/section>
<add></section>
<ide><path>curriculum/challenges/chinese/03-front-end-libraries/react/render-with-an-if-else-condition.chinese.md
<ide> id: 5a24c314108439a4d4036184
<ide> title: Render with an If-Else Condition
<ide> challengeType: 6
<ide> isRequired: false
<del>videoUrl: ''
<del>localeTitle: 使用If-Else条件渲染
<add>forumTopicId: 301410
<add>localeTitle: 使用 If-Else 条件进行渲染
<ide> ---
<ide>
<ide> ## Description
<del><section id="description">使用JavaScript控制渲染视图的另一个应用是将呈现的元素绑定到条件。当条件为真时,一个视图呈现。当它是假的时,它是一个不同的观点。您可以使用React组件的<code>render()</code>方法中的标准<code>if/else</code>语句执行此操作。 </section>
<add><section id='description'>
<add>使用 JavaScript 控制渲染视图的另一个应用是将渲染的元素绑定到一个条件。当条件为真时,将呈现一个视图,反之,则呈现另一种视图。你可以在 React 组件的<code>render()</code>方法中使用的标准<code>if/else</code>语句来实现这一点。
<add></section>
<ide>
<ide> ## Instructions
<del><section id="instructions"> MyComponent在其状态中包含一个<code>boolean</code> ,用于跟踪是否要在UI中显示某个元素。该<code>button</code>切换此值的状态。目前,它每次都呈现相同的UI。使用<code>if/else</code>语句重写<code>render()</code>方法,以便如果<code>display</code>为<code>true</code> ,则返回当前标记。否则,返回没有<code>h1</code>元素的标记。 <strong>注意:</strong>您必须编写<code>if/else</code>以传递测试。使用三元运算符不会通过此处。 </section>
<add><section id='instructions'>
<add>MyComponent 的 state 中包含一个<code>布尔值</code>,用于跟踪是否要在 UI 中显示某个元素。<code>按钮</code>切换此值的状态。目前,它每次都呈现相同的 UI。用<code>if/else</code>语句重写<code>render()</code>方法,如果<code>display</code>为<code>true</code>则返回当前标记。否则,返回不带<code>h1</code>元素的标记。
<add><strong>注意:</strong> 写<code>if/else</code>语句才能通过测试,使用三元运算符是不会通过的。
<add></section>
<ide>
<ide> ## Tests
<ide> <section id='tests'>
<ide>
<ide> ```yml
<ide> tests:
<del> - text: <code>MyComponent</code>应该存在并呈现。
<add> - text: <code>MyComponent</code>应该存在并被渲染。
<ide> testString: assert((function() { const mockedComponent = Enzyme.mount(React.createElement(MyComponent)); return mockedComponent.find('MyComponent').length === 1; })());
<del> - text: 当<code>display</code>设置为<code>true</code> ,应该渲染<code>div</code> , <code>button</code>和<code>h1</code> 。
<add> - text: 当<code>display</code>被设置为<code>true</code>时,<code>div</code>、<code>button</code>和<code>h1</code>标签应该被渲染。
<ide> testString: 'async () => { const waitForIt = (fn) => new Promise((resolve, reject) => setTimeout(() => resolve(fn()), 250)); const mockedComponent = Enzyme.mount(React.createElement(MyComponent)); const state_1 = () => { mockedComponent.setState({display: true}); return waitForIt(() => mockedComponent )}; const updated = await state_1(); assert(mockedComponent.find(''div'').length === 1 && mockedComponent.find(''div'').children().length === 2 && mockedComponent.find(''button'').length === 1 && mockedComponent.find(''h1'').length === 1); }; '
<del> - text: 当<code>display</code>设置为<code>false</code> ,只应呈现<code>div</code>和<code>button</code> 。
<add> - text: 当<code>display</code>被设置为<code>false</code>时,只有<code>div</code>和<code>button</code>应该被渲染。
<ide> testString: 'async () => { const waitForIt = (fn) => new Promise((resolve, reject) => setTimeout(() => resolve(fn()), 250)); const mockedComponent = Enzyme.mount(React.createElement(MyComponent)); const state_1 = () => { mockedComponent.setState({display: false}); return waitForIt(() => mockedComponent )}; const updated = await state_1(); assert(mockedComponent.find(''div'').length === 1 && mockedComponent.find(''div'').children().length === 1 && mockedComponent.find(''button'').length === 1 && mockedComponent.find(''h1'').length === 0); }; '
<del> - text: render方法应使用<code>if/else</code>语句来检查<code>this.state.display</code>的条件。
<add> - text: render 方法中应该使用<code>if/else</code>语句来检查<code>this.state.display</code>的条件。
<ide> testString: getUserInput => assert(getUserInput('index').includes('if') && getUserInput('index').includes('else'));
<ide>
<ide> ```
<ide> class MyComponent extends React.Component {
<ide> );
<ide> }
<ide> };
<del>
<ide> ```
<ide>
<ide> </div>
<ide> class MyComponent extends React.Component {
<ide> <div id='jsx-teardown'>
<ide>
<ide> ```js
<del>console.info('after the test');
<add>ReactDOM.render(<MyComponent />, document.getElementById('root'))
<ide> ```
<ide>
<ide> </div>
<ide> console.info('after the test');
<ide> ## Solution
<ide> <section id='solution'>
<ide>
<add>
<ide> ```js
<del>// solution required
<add>class MyComponent extends React.Component {
<add> constructor(props) {
<add> super(props);
<add> this.state = {
<add> display: true
<add> }
<add> this.toggleDisplay = this.toggleDisplay.bind(this);
<add> }
<add> toggleDisplay() {
<add> this.setState({
<add> display: !this.state.display
<add> });
<add> }
<add> render() {
<add> // change code below this line
<add> if (this.state.display) {
<add> return (
<add> <div>
<add> <button onClick={this.toggleDisplay}>Toggle Display</button>
<add> <h1>Displayed!</h1>
<add> </div>
<add> );
<add> } else {
<add> return (
<add> <div>
<add> <button onClick={this.toggleDisplay}>Toggle Display</button>
<add> </div>
<add> );
<add> }
<add> }
<add>};
<ide> ```
<ide>
<del>/section>
<add></section>
<ide><path>curriculum/challenges/chinese/03-front-end-libraries/react/review-using-props-with-stateless-functional-components.chinese.md
<ide> id: 5a24c314108439a4d403616f
<ide> title: Review Using Props with Stateless Functional Components
<ide> challengeType: 6
<ide> isRequired: false
<del>videoUrl: ''
<del>localeTitle: 查看使用无状态功能组件的道具
<add>forumTopicId: 301411
<add>localeTitle: 复习如何使用 Props 和无状态函数组件
<ide> ---
<ide>
<ide> ## Description
<del><section id="description">除了最后的挑战,你已经将道具传递给无状态功能组件。这些组件就像纯函数一样。他们接受道具作为输入,并在每次传递相同的道具时返回相同的视图。您可能想知道状态是什么,下一个挑战将更详细地介绍它。在此之前,这里是对组件术语的回顾。 <em>无状态功能组件</em>是您编写的任何接受道具并返回JSX的函数。另一方面, <em>无状态组件</em>是扩展<code>React.Component</code>的类,但不使用内部状态(在下一个挑战中涵盖)。最后,有<em>状态组件</em>是保持其自身内部状态的任何组件。您可能会看到有状态组件简称为组件或React组件。一种常见的模式是尽可能地减少有状态并创建无状态功能组件。这有助于将状态管理包含到应用程序的特定区域。反过来,通过更容易地了解状态更改如何影响其行为,这可以改善应用程序的开发和维护。 </section>
<add><section id='description'>
<add>除了上一个挑战,你一直在将 props 传递给无状态的函数组件。这些组件就像纯函数,它们接收 props 作为输入,并在每次传递相同 props 时返回相同的视图。你可能会想知道什么是状态,下一个挑战将会更详细地讲述它。在此之前,我们先来回顾一下组件的术语。
<add><em>无状态函数组件</em>是一个函数,它接收 props 作为输入并返回 JSX。另一方面,<em>无状态组件</em>是一个类,它扩展了<code>React.Component</code>,但是不使用内部状态(下一个挑战中讨论)。最后,<em>状态组件</em>是指维护其自身内部状态的组件,它简称组件或 React 组件。
<add>一种常见的应用模式是尽可能减少状态组件并创建无状态的函数组件。这有助于将状态管理包含到应用程序的特定区域。反过来,通过更容易地跟踪状态变化如何影响其行为,可以改进应用程序的开发和维护。
<add></section>
<ide>
<ide> ## Instructions
<del><section id="instructions">代码编辑器有一个<code>CampSite</code>组件,它将<code>Camper</code>组件呈现为子组件。定义<code>Camper</code>组件并为其指定<code>{ name: 'CamperBot' }</code>默认道具。在<code>Camper</code>组件内部,渲染您想要的任何代码,但要确保有一个<code>p</code>元素仅包含作为<code>prop</code>传递的<code>name</code>值。最后,在<code>Camper</code>组件上定义<code>propTypes</code> ,要求将<code>name</code>作为prop提供,并验证它是<code>string</code>类型。 </section>
<add><section id='instructions'>
<add>在代码编辑器中有一个<code>CampSite</code>组件,它把<code>Camper</code>组件渲染为自己的子组件。定义<code>Camper</code>组件,并为其分配默认 props<code>{ name: 'CamperBot' }</code>。你可以在<code>Camper</code>组件内部渲染任何你想要的代码,但是要确保有一个<code>p</code>元素,它只包含作为<code>prop</code>传递的<code>name</code>值。最后,在<code>Camper</code>组件上定义<code>propTypes</code>,要求提供<code>name</code>作为 prop,并验证它是<code>string</code>类型。
<add></section>
<ide>
<ide> ## Tests
<ide> <section id='tests'>
<ide>
<ide> ```yml
<ide> tests:
<del> - text: <code>CampSite</code>组件应该呈现。
<add> - text: 应该渲染<code>CampSite</code>组件。
<ide> testString: assert((function() { const mockedComponent = Enzyme.mount(React.createElement(CampSite)); return mockedComponent.find('CampSite').length === 1; })());
<del> - text: <code>Camper</code>组件应呈现。
<add> - text: 应该渲染<code>Camper</code>组件。
<ide> testString: assert((function() { const mockedComponent = Enzyme.mount(React.createElement(CampSite)); return mockedComponent.find('Camper').length === 1; })());
<del> - text: <code>Camper</code>组件应该包含默认道具,它将字符串<code>CamperBot</code>分配给键<code>name</code> 。
<add> - text: <code>Camper</code>组件应该包含默认 props,它将字符串<code>CamperBot</code>赋值给关键字<code>name</code>。
<ide> testString: assert(/Camper.defaultProps={name:(['"`])CamperBot\1,?}/.test(code.replace(/\s/g, '')));
<del> - text: <code>Camper</code>组件应包含要求<code>name</code> prop为<code>string</code>类型的prop类型。
<add> - text: <code>Camper</code>组件应该包含<code>string</code>类型的<code>name</code>prop。
<ide> testString: assert(/Camper.propTypes={name:PropTypes.string.isRequired,?}/.test(code.replace(/\s/g, '')));
<del> - text: <code>Camper</code>组件应包含一个<code>p</code>元素,其中只包含<code>name</code> prop的文本。
<add> - text: <code>Camper</code>组件应该包含一个<code>p</code>元素,元素内是来自prop<code>name</code>的唯一文本。
<ide> testString: assert((function() { const mockedComponent = Enzyme.mount(React.createElement(CampSite)); return mockedComponent.find('p').text() === mockedComponent.find('Camper').props().name; })());
<ide>
<ide> ```
<ide> class CampSite extends React.Component {
<ide> var PropTypes = {
<ide> string: { isRequired: true }
<ide> };
<del>
<ide> ```
<ide>
<ide> </div>
<ide> var PropTypes = {
<ide> <div id='jsx-teardown'>
<ide>
<ide> ```js
<del>console.info('after the test');
<add>ReactDOM.render(<CampSite />, document.getElementById('root'))
<ide> ```
<ide>
<ide> </div>
<ide> console.info('after the test');
<ide> ## Solution
<ide> <section id='solution'>
<ide>
<add>
<ide> ```js
<del>// solution required
<add>class CampSite extends React.Component {
<add> constructor(props) {
<add> super(props);
<add> }
<add> render() {
<add> return (
<add> <div>
<add> <Camper/>
<add> </div>
<add> );
<add> }
<add>};
<add>// change code below this line
<add>
<add>const Camper = (props) => {
<add> return (
<add> <div>
<add> <p>{props.name}</p>
<add> </div>
<add> );
<add>};
<add>
<add>Camper.propTypes = {
<add> name: PropTypes.string.isRequired
<add>};
<add>
<add>Camper.defaultProps = {
<add> name: 'CamperBot'
<add>};
<add>
<ide> ```
<ide>
<del>/section>
<add></section>
<ide><path>curriculum/challenges/chinese/03-front-end-libraries/react/set-state-with-this.setstate.chinese.md
<ide> id: 5a24c314108439a4d4036173
<ide> title: Set State with this.setState
<ide> challengeType: 6
<ide> isRequired: false
<del>videoUrl: ''
<del>localeTitle: 使用this.setState设置State
<add>forumTopicId: 301412
<add>localeTitle: 用 this.setState 设置状态
<ide> ---
<ide>
<ide> ## Description
<del><section id="description">之前的挑战包括组件<code>state</code>以及如何在<code>constructor</code>初始化状态。还有一种方法可以改变组件的<code>state</code> 。 React提供了一种更新名为<code>setState</code>组件<code>state</code>的方法。您可以在组件类中调用<code>setState</code>方法,如下所示: <code>this.setState()</code> ,传入一个具有键值对的对象。键是您的状态属性,值是更新的状态数据。例如,如果我们在状态中存储<code>username</code>并想要更新它,它将如下所示: <blockquote> this.setState({ <br>用户名:'Lewis' <br> }); </blockquote> React希望你永远不要直接修改<code>state</code> ,而是在状态发生变化时总是使用<code>this.setState()</code> 。此外,您应该注意React可以批量处理多个状态更新以提高性能。这意味着通过<code>setState</code>方法的状态更新可以是异步的。 <code>setState</code>方法有一种替代语法,它提供了解决此问题的方法。这很少需要,但记住它是件好事!有关更多详细信息,请参阅<a target="_blank" href="https://facebook.github.io/react/docs/state-and-lifecycle.html">React文档</a> 。 </section>
<add><section id='description'>
<add>前面的挑战涵盖了组件的<code>state</code>以及如何在<code>constructor</code>中初始化 state。还有一种方法可以更改组件的<code>state</code>,React 提供了<code>setState</code>方法来更新组件的<code>state</code>。在组件类中调用<code>setState</code>方法如下所示:<code>this.setState()</code>,传入键值对的对象,其中键是 state 属性,值是更新后的 state 数据。例如,如果我们在 state 中存储<code>username</code>,并想要更新它,代码如下所示:
<add>
<add>```jsx
<add>this.setState({
<add> username: 'Lewis'
<add>});
<add>```
<add>
<add>React 希望你永远不要直接修改<code>state</code>,而是在 state 发生改变时始终使用<code>this.setState()</code>。此外,你应该注意,React 可以批量处理多个 state 更新以提高性能。这意味着通过<code>setState</code>方法进行的 state 更新可以是异步的。<code>setState</code>方法有一种替代语法可以解决异步问题,虽然这很少用到,但是最好还是记住它!有关详细信息,请参阅<a target="_blank" href="https://facebook.github.io/react/docs/state-and-lifecycle.html">React 文档</a>。
<add></section>
<ide>
<ide> ## Instructions
<del><section id="instructions">代码编辑器中有一个<code>button</code>元素,它有一个<code>onClick()</code>处理程序。当<code>button</code>在浏览器中收到单击事件时,将触发此处理程序,并运行<code>MyComponent</code>定义的<code>handleClick</code>方法。在<code>handleClick</code>方法中,使用<code>this.setState()</code>更新组件<code>state</code> 。设置<code>name</code>的属性<code>state</code>为等于字符串<code>React Rocks!</code> 。单击按钮并观察呈现的状态更新。如果您还不完全了解点击处理程序代码在此时的工作原理,请不要担心。它涵盖了即将到来的挑战。 </section>
<add><section id='instructions'>
<add>代码编辑器中有一个<code>button</code>元素,它有一个<code>onClick()</code>处理程序。当<code>button</code>在浏览器中接收到单击事件时触发此处理程序,并运行<code>MyComponent</code>中定义的<code>handleClick</code>方法。在<code>handleClick</code>方法中,使用<code>this.setState()</code>更新组件的<code>state</code>。设置<code>state</code>中的<code>name</code>属性为字符串<code>React Rocks!</code>。
<add>单击按钮查看渲染的 state 的更新。如果你不完全理解单击处理程序代码在此时的工作方式,请不要担心。在接下来的挑战中会有讲述。
<add></section>
<ide>
<ide> ## Tests
<ide> <section id='tests'>
<ide>
<ide> ```yml
<ide> tests:
<del> - text: '<code>MyComponent</code>的状态应使用键值对<code>{ name: Initial State }</code> 。'
<add> - text: '<code>MyComponent</code>的 state 应该使用键值对 <code>{ name: Initial State }</code> 来初始化。'
<ide> testString: 'assert(Enzyme.mount(React.createElement(MyComponent)).state(''name'') === ''Initial State'');'
<del> - text: <code>MyComponent</code>应该呈现一个<code>h1</code>标头。
<add> - text: <code>MyComponent</code>应该渲染一个<code>h1</code>标题。
<ide> testString: assert(Enzyme.mount(React.createElement(MyComponent)).find('h1').length === 1);
<del> - text: 渲染的<code>h1</code>标头应包含从组件状态呈现的文本。
<add> - text: 渲染的<code>h1</code>标题中应该包含一段文本,这段文本是从组件的 state 中渲染出来的。
<ide> testString: 'async () => { const waitForIt = (fn) => new Promise((resolve, reject) => setTimeout(() => resolve(fn()), 250)); const mockedComponent = Enzyme.mount(React.createElement(MyComponent)); const first = () => { mockedComponent.setState({ name: ''TestName'' }); return waitForIt(() => mockedComponent.html()); }; const firstValue = await first(); assert(/<h1>TestName<\/h1>/.test(firstValue)); };'
<del> - text: 在<code>MyComponent</code>上调用<code>handleClick</code>方法应该将state属性设置为等于<code>React Rocks!</code> 。
<add> - text: 调用<code>MyComponent</code>的<code>handleClick</code>方法应该将 state 的 name 属性设置为<code>React Rocks!</code>。
<ide> testString: 'async () => { const waitForIt = (fn) => new Promise((resolve, reject) => setTimeout(() => resolve(fn()), 250)); const mockedComponent = Enzyme.mount(React.createElement(MyComponent)); const first = () => { mockedComponent.setState({ name: ''Before'' }); return waitForIt(() => mockedComponent.state(''name'')); }; const second = () => { mockedComponent.instance().handleClick(); return waitForIt(() => mockedComponent.state(''name'')); }; const firstValue = await first(); const secondValue = await second(); assert(firstValue === ''Before'' && secondValue === ''React Rocks!''); };'
<ide>
<ide> ```
<ide> class MyComponent extends React.Component {
<ide> );
<ide> }
<ide> };
<del>
<ide> ```
<ide>
<ide> </div>
<ide> class MyComponent extends React.Component {
<ide> <div id='jsx-teardown'>
<ide>
<ide> ```js
<del>console.info('after the test');
<add>ReactDOM.render(<MyComponent />, document.getElementById('root'))
<ide> ```
<ide>
<ide> </div>
<ide> console.info('after the test');
<ide> ## Solution
<ide> <section id='solution'>
<ide>
<add>
<ide> ```js
<del>// solution required
<add>class MyComponent extends React.Component {
<add> constructor(props) {
<add> super(props);
<add> this.state = {
<add> name: 'Initial State'
<add> };
<add> this.handleClick = this.handleClick.bind(this);
<add> }
<add> handleClick() {
<add> // change code below this line
<add> this.setState({
<add> name: 'React Rocks!'
<add> });
<add> // change code above this line
<add> }
<add> render() {
<add> return (
<add> <div>
<add> <button onClick = {this.handleClick}>Click Me</button>
<add> <h1>{this.state.name}</h1>
<add> </div>
<add> );
<add> }
<add>};
<ide> ```
<ide>
<del>/section>
<add></section>
<ide><path>curriculum/challenges/chinese/03-front-end-libraries/react/use--for-a-more-concise-conditional.chinese.md
<ide> id: 5a24c314108439a4d4036185
<ide> title: Use && for a More Concise Conditional
<ide> challengeType: 6
<ide> isRequired: false
<del>videoUrl: ''
<del>localeTitle: 使用&&获得更简洁的条件
<add>forumTopicId: 301413
<add>localeTitle: 使用 && 获得更简洁的条件
<ide> ---
<ide>
<ide> ## Description
<del><section id="description"> if / else语句在最后一次挑战中起作用,但是有一种更简洁的方法来实现相同的结果。想象一下,您正在跟踪组件中的多个条件,并且您希望根据这些条件中的每个条件呈现不同的元素。如果你写了很多<code>else if</code>语句来返回略有不同的UI,你可能会重复代码,这会留下错误的余地。相反,您可以使用<code>&&</code> logical运算符以更简洁的方式执行条件逻辑。这是可能的,因为您要检查条件是否为<code>true</code> ,如果是,则返回一些标记。下面是一个示例: <code>{condition && <p>markup</p>}</code>如果<code>condition</code>为<code>true</code> ,则返回标记。如果条件为<code>false</code> ,则在评估<code>condition</code>后操作将立即返回<code>false</code>并且不返回任何内容。您可以直接在JSX中包含这些语句,并在每个语句之后写入<code>&&</code>多个条件串在一起。这允许您在<code>render()</code>方法中处理更复杂的条件逻辑,而无需重复大量代码。 </section>
<add><section id='description'>
<add>if/else 语句在上一次挑战中是有效的,但是有一种更简洁的方法可以达到同样的结果。假设你正在跟踪组件中的几个条件,并且希望根据这些条件中的每一个来渲染不同的元素。如果你写了很多<code>else if</code>语句来返回稍微不同的 UI,你可能会写很多重复代码,这就留下了出错的空间。相反,你可以使用<code>&&</code>逻辑运算符以更简洁的方式执行条件逻辑。这是完全可行的,因为你希望检查条件是否为真,如果为真,则返回一些标记。这里有一个例子:
<add><code>{condition && <p>markup</p>}</code>
<add>如果<code>condition</code>为 true,则返回标记。如果 condition 为 false,操作将在判断<code>condition</code>后立即返回<code>false</code>,并且不返回任何内容。你可以将这些语句直接包含在 JSX 中,并通过在每个条件后面写<code>&&</code>来将多个条件串在一起。这允许你在<code>render()</code>方法中处理更复杂的条件逻辑,而无需重复大量代码。
<add></section>
<ide>
<ide> ## Instructions
<del><section id="instructions">再次解决前面的示例,因此<code>h1</code>仅在<code>display</code>为<code>true</code>呈现,但使用<code>&&</code> logical运算符而不是<code>if/else</code>语句。 </section>
<add><section id='instructions'>
<add>再来看看前面的示例,<code>h1</code>还是在<code>display</code>为<code>true</code>时被渲染,但使用<code>&&</code>逻辑运算符代替<code>if/else</code>语句。
<add></section>
<ide>
<ide> ## Tests
<ide> <section id='tests'>
<ide>
<ide> ```yml
<ide> tests:
<del> - text: <code>MyComponent</code>应该存在并呈现。
<add> - text: <code>MyComponent</code>应该存在并被渲染。
<ide> testString: assert((function() { const mockedComponent = Enzyme.mount(React.createElement(MyComponent)); return mockedComponent.find('MyComponent').length; })());
<del> - text: 当<code>display</code>设置为<code>true</code> ,应该渲染<code>div</code> , <code>button</code>和<code>h1</code> 。
<add> - text: 当<code>display</code>被设置为<code>true</code>时,<code>div</code>、<code>button</code>和<code>h1</code>标签应该被渲染。
<ide> testString: 'async () => { const waitForIt = (fn) => new Promise((resolve, reject) => setTimeout(() => resolve(fn()), 250)); const mockedComponent = Enzyme.mount(React.createElement(MyComponent)); const state_1 = () => { mockedComponent.setState({display: true}); return waitForIt(() => mockedComponent )}; const updated = await state_1(); assert(updated.find(''div'').length === 1 && updated.find(''div'').children().length === 2 && updated.find(''button'').length === 1 && updated.find(''h1'').length === 1); }; '
<del> - text: 当<code>display</code>设置为<code>false</code> ,只应呈现<code>div</code>和<code>button</code> 。
<add> - text: 当<code>display</code>被设置为<code>false</code>时,只有<code>div</code>和<code>button</code>应该被渲染。
<ide> testString: 'async () => { const waitForIt = (fn) => new Promise((resolve, reject) => setTimeout(() => resolve(fn()), 250)); const mockedComponent = Enzyme.mount(React.createElement(MyComponent)); const state_1 = () => { mockedComponent.setState({display: false}); return waitForIt(() => mockedComponent )}; const updated = await state_1(); assert(updated.find(''div'').length === 1 && updated.find(''div'').children().length === 1 && updated.find(''button'').length === 1 && updated.find(''h1'').length === 0); }; '
<del> - text: render方法应该使用&& logical运算符来检查this.state.display的条件。
<add> - text: render 方法应该使用<code>&&</code>逻辑运算符来检查<code>this.state.display</code>的条件。
<ide> testString: getUserInput => assert(getUserInput('index').includes('&&'));
<ide>
<ide> ```
<ide> class MyComponent extends React.Component {
<ide> this.toggleDisplay = this.toggleDisplay.bind(this);
<ide> }
<ide> toggleDisplay() {
<del> this.setState({
<del> display: !this.state.display
<del> });
<add> this.setState(state => ({
<add> display: !state.display
<add> }));
<ide> }
<ide> render() {
<ide> // change code below this line
<ide> class MyComponent extends React.Component {
<ide> );
<ide> }
<ide> };
<del>
<ide> ```
<ide>
<ide> </div>
<ide> class MyComponent extends React.Component {
<ide> <div id='jsx-teardown'>
<ide>
<ide> ```js
<del>console.info('after the test');
<add>ReactDOM.render(<MyComponent />, document.getElementById('root'))
<ide> ```
<ide>
<ide> </div>
<ide> console.info('after the test');
<ide> ## Solution
<ide> <section id='solution'>
<ide>
<add>
<ide> ```js
<del>// solution required
<add>class MyComponent extends React.Component {
<add> constructor(props) {
<add> super(props);
<add> this.state = {
<add> display: true
<add> }
<add> this.toggleDisplay = this.toggleDisplay.bind(this);
<add> }
<add> toggleDisplay() {
<add> this.setState(state => ({
<add> display: !state.display
<add> }));
<add> }
<add> render() {
<add> // change code below this line
<add> return (
<add> <div>
<add> <button onClick={this.toggleDisplay}>Toggle Display</button>
<add> {this.state.display && <h1>Displayed!</h1>}
<add> </div>
<add> );
<add> }
<add>};
<ide> ```
<ide>
<del>/section>
<add></section>
<ide><path>curriculum/challenges/chinese/03-front-end-libraries/react/use-a-ternary-expression-for-conditional-rendering.chinese.md
<ide> id: 5a24c314108439a4d4036187
<ide> title: Use a Ternary Expression for Conditional Rendering
<ide> challengeType: 6
<ide> isRequired: false
<del>videoUrl: ''
<add>forumTopicId: 301414
<ide> localeTitle: 使用三元表达式进行条件渲染
<ide> ---
<ide>
<ide> ## Description
<del><section id="description">在继续使用动态渲染技术之前,最后一种方法是使用内置的JavaScript条件来渲染你想要的东西: <em><strong>三元运算符</strong></em> 。三元运算符通常用作JavaScript中<code>if/else</code>语句的快捷方式。它们不像传统的<code>if/else</code>语句那样健壮,但它们在React开发人员中非常受欢迎。这样做的一个原因是因为JSX是如何编译的, <code>if/else</code>语句不能直接插入到JSX代码中。您可能已经注意到这几个挑战 - 当需要<code>if/else</code>语句时,它总是在<code>return</code>语句<em>之外</em> 。如果要在JSX中实现条件逻辑,三元表达式可能是一个很好的选择。回想一下,三元运算符有三个部分,但是你可以将几个三元表达式组合在一起。这是基本语法: <blockquote>条件? expressionIfTrue:expressionIfFalse </blockquote></section>
<add><section id='description'>
<add>在继续使用动态渲染技术之前,还有最后一种方法可以渲染你想要的东西,它使用内置的 JavaScript 条件:<em><strong>三元运算符</strong></em>。三元运算符经常被用作 JavaScript 中<code>if/else</code>语句的缩写。它们不像传统的<code>if/else</code>语句那样健壮,但是在 React 开发人员中非常流行,原因之一就是 JSX 的编译原理,<code>if/else</code>语句不能直接插入到 JSX 代码中。你可能在前几个挑战就注意到了这一点--当需要<code>if/else</code>语句时,它总是在<code>return</code>语句<em>外面</em>。如果你想在 JSX 中实现条件逻辑,三元表达式是一个很好的选择。回想一下,三元运算符有三个部分,但是你可以将多个三元表达式组合在一起。以下是基本语法:
<add>
<add>```js
<add>condition ? expressionIfTrue : expressionIfFalse
<add>```
<add>
<add></section>
<ide>
<ide> ## Instructions
<del><section id="instructions">代码编辑器在<code>CheckUserAge</code>组件的<code>render()</code>方法中定义了三个常量。它们被称为<code>buttonOne</code> , <code>buttonTwo</code>和<code>buttonThree</code> 。每个都分配了一个表示按钮元素的简单JSX表达式。首先,使用<code>input</code>和<code>userAge</code>初始化<code>CheckUserAge</code>的状态, <code>userAge</code>其设置为空字符串的值。一旦组件向页面呈现信息,用户就应该有办法与它进行交互。在组件的<code>return</code>语句中,设置一个实现以下逻辑的三元表达式:当页面首次加载时,将提交按钮<code>buttonOne</code>呈现给页面。然后,当用户输入他们的年龄并单击该按钮时,根据年龄呈现不同的按钮。如果用户输入的数字小于<code>18</code> ,则渲染<code>buttonThree</code> 。如果用户输入的数字大于或等于<code>18</code> ,则渲染<code>buttonTwo</code> 。 </section>
<add><section id='instructions'>
<add>代码编辑器在<code>CheckUserAge</code>组件的<code>render()</code>方法中定义了三个常量,它们分别是<code>buttonOne</code>、<code>buttonTwo</code>和<code>buttonThree</code>。每个都分配了一个表示按钮元素的简单 JSX 表达式。首先,使用<code>input</code>和<code>userAge</code>初始化<code>CheckUserAge</code>的 state,并将其值设置为空字符串。
<add>一旦组件将信息渲染给页面,用户应该有一种方法与之交互。在组件的<code>return</code>语句中,设置一个实现以下逻辑的三元表达式:当页面首次加载时,将提交按钮<code>buttonOne</code>渲染到页面。然后,当用户输入年龄并点击该按钮时,根据年龄渲染不同的按钮。如果用户输入的数字小于<code>18</code>,则渲染<code>buttonThree</code>。如果用户输入的数字大于或等于<code>18</code>,则渲染<code>buttonTwo</code>。
<add></section>
<ide>
<ide> ## Tests
<ide> <section id='tests'>
<ide>
<ide> ```yml
<ide> tests:
<del> - text: <code>CheckUserAge</code>组件应使用单个<code>input</code>元素和单个<code>button</code>元素进行渲染。
<add> - text: <code>CheckUserAge</code>组件应该渲染出单个<code>input</code>元素和单个<code>button</code>元素。
<ide> testString: assert(Enzyme.mount(React.createElement(CheckUserAge)).find('div').find('input').length === 1 && Enzyme.mount(React.createElement(CheckUserAge)).find('div').find('button').length === 1);
<del> - text: 应使用<code>userAge</code>属性和<code>input</code>属性初始化<code>CheckUserAge</code>组件的状态,两者都设置为空字符串的值。
<add> - text: <code>CheckUserAge</code>组件的 state 应该用<code>userAge</code>属性和<code>input</code>属性初始化,并且这两个属性的值都被设置为空字符串。
<ide> testString: assert(Enzyme.mount(React.createElement(CheckUserAge)).state().input === '' && Enzyme.mount(React.createElement(CheckUserAge)).state().userAge === '');
<del> - text: 当<code>CheckUserAge</code>组件首次呈现给DOM时, <code>button</code>的内部文本应该是Submit。
<add> - text: 当<code>CheckUserAge</code>组件首次渲染到 DOM 时,<code>按钮</code>内部的文本应为 Submit。
<ide> testString: assert(Enzyme.mount(React.createElement(CheckUserAge)).find('button').text() === 'Submit');
<del> - text: 当进入一个数小于18 <code>input</code>元件和<code>button</code>被点击, <code>button</code>的内部文本应该读<code>You Shall Not Pass</code> 。
<add> - text: 当小于 18 的数字输入到<code>input</code>元素中并点击该<code>按钮</code>时,该<code>按钮</code>的内部文本应该是<code>You Shall Not Pass</code>。
<ide> testString: 'async () => { const waitForIt = (fn) => new Promise((resolve, reject) => setTimeout(() => resolve(fn()), 250)); const mockedComponent = Enzyme.mount(React.createElement(CheckUserAge)); const initialButton = mockedComponent.find(''button'').text(); const enter3AndClickButton = () => { mockedComponent.find(''input'').simulate(''change'', {target: { value: ''3'' }}); mockedComponent.find(''button'').simulate(''click''); return waitForIt(() => { mockedComponent.update(); return mockedComponent.find(''button'').text(); }); }; const enter17AndClickButton = () => { mockedComponent.find(''input'').simulate(''change'', {target: { value: ''17'' }}); mockedComponent.find(''button'').simulate(''click''); return waitForIt(() => { mockedComponent.update(); return mockedComponent.find(''button'').text(); }); }; const userAge3 = await enter3AndClickButton(); const userAge17 = await enter17AndClickButton(); assert(initialButton === ''Submit'' && userAge3 === ''You Shall Not Pass'' && userAge17 === ''You Shall Not Pass''); }; '
<del> - text: 当数大于或等于18输入到<code>input</code>元件和<code>button</code>被点击, <code>button</code>的内部文本应该阅读<code>You May Enter</code> 。
<add> - text: 当大于或等于 18 的数字输入到<code>input</code>元素中并点击该<code>按钮</code>时,该<code>按钮</code>的内部文本应该是<code>You May Enter</code>。
<ide> testString: 'async () => { const waitForIt = (fn) => new Promise((resolve, reject) => setTimeout(() => resolve(fn()), 250)); const mockedComponent = Enzyme.mount(React.createElement(CheckUserAge)); const initialButton = mockedComponent.find(''button'').text(); const enter18AndClickButton = () => { mockedComponent.find(''input'').simulate(''change'', {target: { value: ''18'' }}); mockedComponent.find(''button'').simulate(''click''); return waitForIt(() => { mockedComponent.update(); return mockedComponent.find(''button'').text(); }); }; const enter35AndClickButton = () => { mockedComponent.find(''input'').simulate(''change'', {target: { value: ''35'' }}); mockedComponent.find(''button'').simulate(''click''); return waitForIt(() => { mockedComponent.update(); return mockedComponent.find(''button'').text(); }); }; const userAge18 = await enter18AndClickButton(); const userAge35 = await enter35AndClickButton(); assert(initialButton === ''Submit'' && userAge18 === ''You May Enter'' && userAge35 === ''You May Enter''); }; '
<del> - text: 一旦提交了一个数字,并再次更改了<code>input</code>的值,该<code>button</code>应返回到<code>Submit</code> 。
<add> - text: 一旦提交了一个数字,并再次更改了<code>input</code>的值,该<code>按钮</code>内部文本应该变回<code>Submit</code>。
<ide> testString: 'async () => { const waitForIt = (fn) => new Promise((resolve, reject) => setTimeout(() => resolve(fn()), 250)); const mockedComponent = Enzyme.mount(React.createElement(CheckUserAge)); const enter18AndClickButton = () => { mockedComponent.find(''input'').simulate(''change'', {target: { value: ''18'' }}); mockedComponent.find(''button'').simulate(''click''); return waitForIt(() => { mockedComponent.update(); return mockedComponent.find(''button'').text(); }); }; const changeInputDontClickButton = () => { mockedComponent.find(''input'').simulate(''change'', {target: { value: ''5'' }}); return waitForIt(() => { mockedComponent.update(); return mockedComponent.find(''button'').text(); }); }; const enter10AndClickButton = () => { mockedComponent.find(''input'').simulate(''change'', {target: { value: ''10'' }}); mockedComponent.find(''button'').simulate(''click''); return waitForIt(() => { mockedComponent.update(); return mockedComponent.find(''button'').text(); }); }; const userAge18 = await enter18AndClickButton(); const changeInput1 = await changeInputDontClickButton(); const userAge10 = await enter10AndClickButton(); const changeInput2 = await changeInputDontClickButton(); assert(userAge18 === ''You May Enter'' && changeInput1 === ''Submit'' && userAge10 === ''You Shall Not Pass'' && changeInput2 === ''Submit''); }; '
<del> - text: 您的代码不应包含任何<code>if/else</code>语句。
<add> - text: 你的代码不应该包含任何<code>if/else</code>语句。
<ide> testString: assert(new RegExp(/(\s|;)if(\s|\()/).test(Enzyme.mount(React.createElement(CheckUserAge)).instance().render.toString()) === false);
<ide>
<ide> ```
<ide> tests:
<ide> <div id='jsx-seed'>
<ide>
<ide> ```jsx
<add>
<ide> const inputStyle = {
<ide> width: 235,
<ide> margin: 5
<ide> class CheckUserAge extends React.Component {
<ide> handleChange(e) {
<ide> this.setState({
<ide> input: e.target.value,
<del> userAge: "
<add> userAge: ''
<ide> });
<ide> }
<ide> submit() {
<del> this.setState({
<del> userAge: this.state.input
<del> });
<add> this.setState(state => ({
<add> userAge: state.input
<add> }));
<ide> }
<ide> render() {
<ide> const buttonOne = <button onClick={this.submit}>Submit</button>;
<ide> class CheckUserAge extends React.Component {
<ide> );
<ide> }
<ide> };
<del>
<ide> ```
<ide>
<ide> </div>
<ide> class CheckUserAge extends React.Component {
<ide> <div id='jsx-teardown'>
<ide>
<ide> ```js
<del>console.info('after the test');
<add>ReactDOM.render(<CheckUserAge />, document.getElementById('root'))
<ide> ```
<ide>
<ide> </div>
<ide> console.info('after the test');
<ide> ## Solution
<ide> <section id='solution'>
<ide>
<add>
<ide> ```js
<del>// solution required
<add>const inputStyle = {
<add> width: 235,
<add> margin: 5
<add>}
<add>
<add>class CheckUserAge extends React.Component {
<add> constructor(props) {
<add> super(props);
<add> this.state = {
<add> userAge: '',
<add> input: ''
<add> }
<add> this.submit = this.submit.bind(this);
<add> this.handleChange = this.handleChange.bind(this);
<add> }
<add> handleChange(e) {
<add> this.setState({
<add> input: e.target.value,
<add> userAge: ''
<add> });
<add> }
<add> submit() {
<add> this.setState(state => ({
<add> userAge: state.input
<add> }));
<add> }
<add> render() {
<add> const buttonOne = <button onClick={this.submit}>Submit</button>;
<add> const buttonTwo = <button>You May Enter</button>;
<add> const buttonThree = <button>You Shall Not Pass</button>;
<add> return (
<add> <div>
<add> <h3>Enter Your Age to Continue</h3>
<add> <input
<add> style={inputStyle}
<add> type="number"
<add> value={this.state.input}
<add> onChange={this.handleChange} /><br />
<add> {
<add> this.state.userAge === '' ?
<add> buttonOne :
<add> this.state.userAge >= 18 ?
<add> buttonTwo :
<add> buttonThree
<add> }
<add> </div>
<add> );
<add> }
<add>};
<ide> ```
<ide>
<del>/section>
<add></section>
<ide><path>curriculum/challenges/chinese/03-front-end-libraries/react/use-advanced-javascript-in-react-render-method.chinese.md
<ide> id: 5a24c314108439a4d4036183
<ide> title: Use Advanced JavaScript in React Render Method
<ide> challengeType: 6
<ide> isRequired: false
<del>videoUrl: ''
<del>localeTitle: 在React Render方法中使用高级JavaScript
<add>forumTopicId: 301415
<add>localeTitle: 在 React Render 方法中使用 JavaScript
<ide> ---
<ide>
<ide> ## Description
<del><section id="description">在以前的挑战中,您学习了如何使用大括号<code>{ }</code>将JavaScript代码注入JSX代码,以执行诸如访问道具,传递道具,访问状态,在代码中插入注释以及最近为组件设置样式等任务。这些都是将JavaScript放入JSX的常见用例,但它们并不是您在React组件中使用JavaScript代码的唯一方法。您也可以在<code>return</code>语句之前直接在<code>render</code>方法中编写JavaScript, <strong><em>而不</em></strong>必将其插入花括号中。这是因为它还不在JSX代码中。当你想在<em>里面</em>的JSX代码后使用一个变量<code>return</code>的语句,你把变量名花括号内。 </section>
<add><section id='description'>
<add>在之前的挑战中,你学习了如何使用大括号<code>{ }</code>将 JavaScript 代码插入到 JSX 代码中,用于访问 props、传递 props、访问 state、在代码中插入注释以及最近学习的定制组件样式等任务。这些都是将 JavaScript 放在 JSX 中的常见用例,但是在 React 组件中使用 JavaScript 代码还有其他方式。
<add>在<code>render</code>方法中编写 JavaScript,你可以把 JavaScript 直接放在<code>return</code>语句之前,而<strong><em>不必</em></strong>将其插入大括号中。这是因为它还不在 JSX 代码中。当你稍后想在<code>return</code>语句中的 JSX 代码中使用变量时,可以将变量名放在大括号中。
<add></section>
<ide>
<ide> ## Instructions
<del><section id="instructions">在提供的代码中, <code>render</code>方法有一个数组,其中包含20个短语,用于表示经典1980年代Magic Eight Ball玩具中的答案。按钮单击事件绑定到<code>ask</code>方法,因此每次单击该按钮时,将生成随机数并将其存储为<code>randomIndex</code>状态。在第52行,删除字符串<code>"change me!"</code>并重新分配<code>answer</code> const,以便每次组件更新时,您的代码随机访问<code>possibleAnswers</code>数组的不同索引。最后,在<code>p</code>标签内插入<code>answer</code> const。 </section>
<add><section id='instructions'>
<add>在提供的代码中,<code>render</code>方法中有一个包含 20 个短语的数组,用于表示 20 世纪 80 年代经典魔术八球玩具中的答案。绑定<code>ask</code>方法到按钮的单击事件,每次单击该按钮时,将生成随机数并将其存储为 state 中的<code>randomIndex</code>。在第 52 行,删除字符串<code>"change me!"</code>并重新分配<code>answer</code>常量,以便每次组件更新时,你的代码随机访问<code>possibleAnswers</code>数组的不同索引。最后,在<code>p</code>标签内插入<code>answer</code>常量。
<add></section>
<ide>
<ide> ## Tests
<ide> <section id='tests'>
<ide>
<ide> ```yml
<ide> tests:
<del> - text: <code>MagicEightBall</code>组件应该存在并且应该呈现给页面。
<add> - text: <code>MagicEightBall</code>组件应该存在并被渲染到页面。
<ide> testString: assert.strictEqual(Enzyme.mount(React.createElement(MagicEightBall)).find('MagicEightBall').length, 1);
<del> - text: <code>MagicEightBall</code>的第一个孩子应该是一个<code>input</code>元素。
<add> - text: <code>MagicEightBall</code>的第一个子元素应该是<code>input</code>元素。
<ide> testString: assert.strictEqual(Enzyme.mount(React.createElement(MagicEightBall)).children().childAt(0).name(), 'input');
<del> - text: <code>MagicEightBall</code>的第三个孩子应该是一个<code>button</code>元素。
<add> - text: <code>MagicEightBall</code>的第三个子元素应该是<code>button</code>元素。
<ide> testString: assert.strictEqual(Enzyme.mount(React.createElement(MagicEightBall)).children().childAt(2).name(), 'button');
<del> - text: <code>MagicEightBall</code>的状态应的属性初始化<code>userInput</code>和属性<code>randomIndex</code>都设置为空字符串的值。
<add> - text: <code>MagicEightBall</code>的 state 应该用<code>userInput</code>属性和<code>randomIndex</code>属性初始化,并且这两个属性的值都应该是空字符串。
<ide> testString: assert(Enzyme.mount(React.createElement(MagicEightBall)).state('randomIndex') === '' && Enzyme.mount(React.createElement(MagicEightBall)).state('userInput') === '');
<del> - text: 当<code>MagicEightBall</code>首次挂载到DOM时,它应该返回一个空的<code>p</code>元素。
<add> - text: 当<code>MagicEightBall</code>第一次加载到 DOM 中时,它应该返回一个空的<code>p</code>元素。
<ide> testString: assert(Enzyme.mount(React.createElement(MagicEightBall)).find('p').length === 1 && Enzyme.mount(React.createElement(MagicEightBall)).find('p').text() === '');
<del> - text: 当文本输入到<code>input</code>元素并单击该按钮时, <code>MagicEightBall</code>组件应该返回一个<code>p</code>元素,该元素包含<code>possibleAnswers</code>数组中的随机元素。
<add> - text: 当文本被输入到<code>input</code>元素中并点击按钮时,<code>MagicEightBall</code>组件应该返回一个<code>p</code>元素,该元素包含数组<code>possibleAnswers</code>中的随机一个元素。
<ide> testString: 'async () => { const waitForIt = (fn) => new Promise((resolve, reject) => setTimeout(() => resolve(fn()), 250)); const comp = Enzyme.mount(React.createElement(MagicEightBall)); const simulate = () => { comp.find(''input'').simulate(''change'', { target: { value: ''test?'' }}); comp.find(''button'').simulate(''click''); }; const result = () => comp.find(''p'').text(); const _1 = () => { simulate(); return waitForIt(() => result()) }; const _2 = () => { simulate(); return waitForIt(() => result()) }; const _3 = () => { simulate(); return waitForIt(() => result()) }; const _4 = () => { simulate(); return waitForIt(() => result()) }; const _5 = () => { simulate(); return waitForIt(() => result()) }; const _6 = () => { simulate(); return waitForIt(() => result()) }; const _7 = () => { simulate(); return waitForIt(() => result()) }; const _8 = () => { simulate(); return waitForIt(() => result()) }; const _9 = () => { simulate(); return waitForIt(() => result()) }; const _10 = () => { simulate(); return waitForIt(() => result()) }; const _1_val = await _1(); const _2_val = await _2(); const _3_val = await _3(); const _4_val = await _4(); const _5_val = await _5(); const _6_val = await _6(); const _7_val = await _7(); const _8_val = await _8(); const _9_val = await _9(); const _10_val = await _10(); const actualAnswers = [_1_val, _2_val, _3_val, _4_val, _5_val, _6_val, _7_val, _8_val, _9_val, _10_val]; const hasIndex = actualAnswers.filter((answer, i) => possibleAnswers.indexOf(answer) !== -1); const notAllEqual = new Set(actualAnswers); assert(notAllEqual.size > 1 && hasIndex.length === 10);}'
<ide>
<ide> ```
<ide> class MagicEightBall extends React.Component {
<ide> constructor(props) {
<ide> super(props);
<ide> this.state = {
<del> userInput: ",
<del> randomIndex: "
<add> userInput: '',
<add> randomIndex: ''
<ide> }
<ide> this.ask = this.ask.bind(this);
<ide> this.handleChange = this.handleChange.bind(this);
<ide> class MagicEightBall extends React.Component {
<ide> if (this.state.userInput) {
<ide> this.setState({
<ide> randomIndex: Math.floor(Math.random() * 20),
<del> userInput: "
<add> userInput: ''
<ide> });
<ide> }
<ide> }
<ide> class MagicEightBall extends React.Component {
<ide> );
<ide> }
<ide> };
<del>
<ide> ```
<ide>
<ide> </div>
<ide> class MagicEightBall extends React.Component {
<ide> <div id='jsx-teardown'>
<ide>
<ide> ```js
<del>console.info('after the test');
<add>var possibleAnswers = [ 'It is certain', 'It is decidedly so', 'Without a doubt', 'Yes, definitely', 'You may rely on it', 'As I see it, yes', 'Outlook good', 'Yes', 'Signs point to yes', 'Reply hazy try again', 'Ask again later', 'Better not tell you now', 'Cannot predict now', 'Concentrate and ask again', 'Don\'t count on it', 'My reply is no', 'My sources say no', 'Outlook not so good','Very doubtful', 'Most likely' ];
<add>ReactDOM.render(<MagicEightBall />, document.getElementById('root'))
<ide> ```
<ide>
<ide> </div>
<ide> console.info('after the test');
<ide> ## Solution
<ide> <section id='solution'>
<ide>
<add>
<ide> ```js
<del>// solution required
<add>const inputStyle = {
<add> width: 235,
<add> margin: 5
<add>}
<add>
<add>class MagicEightBall extends React.Component {
<add> constructor(props) {
<add> super(props);
<add> this.state = {
<add> userInput: '',
<add> randomIndex: ''
<add> }
<add> this.ask = this.ask.bind(this);
<add> this.handleChange = this.handleChange.bind(this);
<add> }
<add> ask() {
<add> if (this.state.userInput) {
<add> this.setState({
<add> randomIndex: Math.floor(Math.random() * 20),
<add> userInput: ''
<add> });
<add> }
<add> }
<add> handleChange(event) {
<add> this.setState({
<add> userInput: event.target.value
<add> });
<add> }
<add> render() {
<add> const possibleAnswers = [
<add> "It is certain", "It is decidedly so", "Without a doubt",
<add> "Yes, definitely", "You may rely on it", "As I see it, yes",
<add> "Outlook good", "Yes", "Signs point to yes", "Reply hazy try again",
<add> "Ask again later", "Better not tell you now", "Cannot predict now",
<add> "Concentrate and ask again", "Don't count on it", "My reply is no",
<add> "My sources say no", "Outlook not so good","Very doubtful", "Most likely"
<add> ];
<add> const answer = possibleAnswers[this.state.randomIndex];
<add> return (
<add> <div>
<add> <input
<add> type="text"
<add> value={this.state.userInput}
<add> onChange={this.handleChange}
<add> style={inputStyle} /><br />
<add> <button onClick={this.ask}>Ask the Magic Eight Ball!</button><br />
<add> <h3>Answer:</h3>
<add> <p>
<add> {answer}
<add> </p>
<add> </div>
<add> );
<add> }
<add>};
<ide> ```
<ide>
<del>/section>
<add></section>
<ide><path>curriculum/challenges/chinese/03-front-end-libraries/react/use-array.filter-to-dynamically-filter-an-array.chinese.md
<ide> id: 5a24c314108439a4d403618c
<ide> title: Use Array.filter() to Dynamically Filter an Array
<ide> challengeType: 6
<ide> isRequired: false
<del>videoUrl: ''
<del>localeTitle: 使用Array.filter()动态过滤数组
<add>forumTopicId: 301416
<add>localeTitle: 使用 Array.Filter() 动态过滤数组
<ide> ---
<ide>
<ide> ## Description
<del><section id="description"> <code>map</code>数组方法是一个强大的工具,在使用React时经常会使用它。另一种与<code>map</code>相关的方法是<code>filter</code> ,它根据条件过滤数组的内容,然后返回一个新数组。例如,如果您的所有用户都具有<code>online</code>属性(可以设置为<code>true</code>或<code>false</code> ,则可以通过以下方式仅过滤那些在线用户: <code>let onlineUsers = users.filter(user => user.online);</code> </section>
<add><section id='description'>
<add><code>map</code>数组方法是一个强大的工具,在使用 React 时经常使用。与<code>map</code>相关的另一种方法是<code>filter</code>,它根据条件过滤数组的内容,然后返回一个新数组。例如,如果你有一个 users 数组,每个数组元素都有一个可以设置为<code>true</code>或<code>false</code>的<code>online</code>属性,你可以只过滤那些在线的用户:
<add><code>let onlineUsers = users.filter(user => user.online);</code>
<add></section>
<ide>
<ide> ## Instructions
<del><section id="instructions">在代码编辑器中, <code>MyComponent</code>的<code>state</code>是用一组用户初始化的。有些用户在线,有些则没有。过滤数组,以便只查看在线用户。要执行此操作,请首先使用<code>filter</code>返回仅包含<code>online</code>属性为<code>true</code>的用户的新数组。然后,在<code>renderOnline</code>变量中,映射已过滤的数组,并为包含其<code>username</code>文本的每个用户返回<code>li</code>元素。确保包括一个独特的<code>key</code> ,就像在最后的挑战中一样。 </section>
<add><section id='instructions'>
<add>在代码编辑器中,<code>MyComponent</code>的<code>state</code>由一个 users 数组初始化。有些用户在线,有些则不在线。过滤数组,以便你只看到在线用户。为此,首先使用<code>filter</code>返回一个新数组,该数组只包含<code>online</code>属性为<code>true</code>的用户。然后,在<code>renderOnline</code>变量中,映射经过过滤的数组,并为每个用户返回一个包含它们<code>username</code>文本的<code>li</code>元素。确保像上一个挑战一样包含一个独特的<code>key</code>。
<add></section>
<ide>
<ide> ## Tests
<ide> <section id='tests'>
<ide>
<ide> ```yml
<ide> tests:
<del> - text: <code>MyComponent</code>应该存在并呈现给页面。
<add> - text: <code>MyComponent</code>应该存在并被渲染到页面。
<ide> testString: assert.strictEqual(Enzyme.mount(React.createElement(MyComponent)).find('MyComponent').length, 1);
<del> - text: <code>MyComponent</code>的状态应初始化为六个用户的数组。“)
<add> - text: <code>MyComponent</code>的 state 应该初始化为包含 6 个用户的数组。
<ide> testString: assert(Array.isArray(Enzyme.mount(React.createElement(MyComponent)).state('users')) === true && Enzyme.mount(React.createElement(MyComponent)).state('users').length === 6);
<del> - text: <code>MyComponent</code>应该返回一个<code>div</code> ,一个<code>h1</code> ,然后是一个无序列表,其中包含每个在线状态设置为<code>true</code>用户的<code>li</code>元素。
<add> - text: <code>MyComponent</code>应该返回一个<code>div</code>、一个<code>h1</code>和一个包含<code>li</code>元素的无序列表,该列表用于展示在线状态为<code>true</code>的每个用户。
<ide> testString: 'async () => { const waitForIt = (fn) => new Promise((resolve, reject) => setTimeout(() => resolve(fn()), 250)); const comp = Enzyme.mount(React.createElement(MyComponent)); const users = (bool) => ({users:[ { username: ''Jeff'', online: bool }, { username: ''Alan'', online: bool }, { username: ''Mary'', online: bool }, { username: ''Jim'', online: bool }, { username: ''Laura'', online: bool } ]}); const result = () => comp.find(''li'').length; const _1 = result(); const _2 = () => { comp.setState(users(true)); return waitForIt(() => result()) }; const _3 = () => { comp.setState(users(false)); return waitForIt(() => result()) }; const _4 = () => { comp.setState({ users: [] }); return waitForIt(() => result()) }; const _2_val = await _2(); const _3_val = await _3(); const _4_val = await _4(); assert(comp.find(''div'').length === 1 && comp.find(''h1'').length === 1 && comp.find(''ul'').length === 1 && _1 === 4 && _2_val === 5 && _3_val === 0 && _4_val === 0); }; '
<del> - text: <code>MyComponent</code>应该呈现包含每个在线用户的用户名的<code>li</code>元素。
<add> - text: <code>MyComponent</code>应该渲染包含每个在线用户用户名的<code>li</code>元素。
<ide> testString: 'async () => { const waitForIt = (fn) => new Promise((resolve, reject) => setTimeout(() => resolve(fn()), 250)); const comp = Enzyme.mount(React.createElement(MyComponent)); const users = (bool) => ({users:[ { username: ''Jeff'', online: bool }, { username: ''Alan'', online: bool }, { username: ''Mary'', online: bool }, { username: ''Jim'', online: bool }, { username: ''Laura'', online: bool } ]}); const ul = () => { comp.setState(users(true)); return waitForIt(() => comp.find(''ul'').html()) }; const html = await ul(); assert(html === ''<ul><li>Jeff</li><li>Alan</li><li>Mary</li><li>Jim</li><li>Laura</li></ul>''); }; '
<del> - text: 每个列表项元素都应具有唯一的<code>key</code>属性。
<add> - text: 每个列表项元素都应该有一个唯一的<code>key</code>属性。
<ide> testString: assert((() => { const ul = Enzyme.mount(React.createElement(MyComponent)).find('ul'); console.log(ul.debug()); const keys = new Set([ ul.childAt(0).key(), ul.childAt(1).key(), ul.childAt(2).key(), ul.childAt(3).key() ]); return keys.size === 4; })());
<ide>
<ide> ```
<ide> class MyComponent extends React.Component {
<ide> );
<ide> }
<ide> };
<del>
<ide> ```
<ide>
<ide> </div>
<ide> class MyComponent extends React.Component {
<ide> <div id='jsx-teardown'>
<ide>
<ide> ```js
<del>console.info('after the test');
<add>ReactDOM.render(<MyComponent />, document.getElementById('root'))
<ide> ```
<ide>
<ide> </div>
<ide> console.info('after the test');
<ide> ## Solution
<ide> <section id='solution'>
<ide>
<add>
<ide> ```js
<del>// solution required
<add>class MyComponent extends React.Component {
<add> constructor(props) {
<add> super(props);
<add> this.state = {
<add> users: [
<add> {
<add> username: 'Jeff',
<add> online: true
<add> },
<add> {
<add> username: 'Alan',
<add> online: false
<add> },
<add> {
<add> username: 'Mary',
<add> online: true
<add> },
<add> {
<add> username: 'Jim',
<add> online: false
<add> },
<add> {
<add> username: 'Sara',
<add> online: true
<add> },
<add> {
<add> username: 'Laura',
<add> online: true
<add> }
<add> ]
<add> }
<add> }
<add> render() {
<add> const usersOnline = this.state.users.filter(user => {
<add> return user.online;
<add> });
<add> const renderOnlineUsers = usersOnline.map(user => {
<add> return (
<add> <li key={user.username}>{user.username}</li>
<add> );
<add> });
<add> return (
<add> <div>
<add> <h1>Current Online Users:</h1>
<add> <ul>
<add> {renderOnlineUsers}
<add> </ul>
<add> </div>
<add> );
<add> }
<add>};
<ide> ```
<ide>
<del>/section>
<add></section>
<ide><path>curriculum/challenges/chinese/03-front-end-libraries/react/use-array.map-to-dynamically-render-elements.chinese.md
<ide> id: 5a24c314108439a4d403618a
<ide> title: Use Array.map() to Dynamically Render Elements
<ide> challengeType: 6
<ide> isRequired: false
<del>videoUrl: ''
<del>localeTitle: 使用Array.map()动态渲染元素
<add>forumTopicId: 301417
<add>localeTitle: 使用 Array.map() 动态渲染元素
<ide> ---
<ide>
<ide> ## Description
<del><section id="description">条件渲染很有用,但您可能需要组件渲染未知数量的元素。通常在反应式编程中,程序员无法知道应用程序的状态直到运行时,因为这很大程度上取决于用户与该程序的交互。程序员需要编写代码以提前正确处理未知状态。在React中使用<code>Array.map()</code>说明了这个概念。例如,您创建一个简单的“待办事项列表”应用程序。作为程序员,您无法知道用户可能在其列表中有多少项。您需要设置组件,以便在使用该程序的人决定今天是洗衣日之前<em><strong>动态呈现</strong></em>正确数量的列表元素。 </section>
<add><section id='description'>
<add>条件渲染很有用,但是你可能需要组件来渲染未知数量的元素。通常在响应式编程中,程序员在应用程序运行时之前无法知道其 state,因为这在很大程度上取决于用户与该程序的交互。程序员需要提前编写代码来正确处理未知状态。在 React 中使用<code>Array.map()</code>阐明了这个概念。
<add>例如,你创建一个简单的“To Do List”应用程序。作为程序员,你无法知道用户可能在其列表中有多少项。你需要设置组件,以便在使用该程序的人决定今天今日待办事项之前<em><strong>动态渲染</strong></em>正确数量的列表元素。
<add></section>
<ide>
<ide> ## Instructions
<del><section id="instructions">代码编辑器设置了大部分<code>MyToDoList</code>组件。如果您完成了受控制的表单质询,那么这些代您会注意到一个<code>textarea</code>和一个<code>button</code> ,以及一些跟踪其状态的方法,但是还没有任何内容呈现给页面。在<code>constructor</code>内部,创建一个<code>this.state</code>对象并定义两个状态: <code>userInput</code>应初始化为空字符串, <code>toDoList</code>应初始化为空数组。接下来,删除<code>items</code>变量旁边的<code>render()</code>方法中的注释。取而代之,映射存储在组件内部状态中的<code>toDoList</code>数组,并为每个项目动态呈现<code>li</code> 。尝试输入字符串<code>eat, code, sleep, repeat</code>到<code>textarea</code> ,然后单击按钮,看看会发生什么。 <strong>注意:</strong>您可能知道由这样的映射操作创建的所有兄弟子元素都需要提供唯一的<code>key</code>属性。别担心,这是下一个挑战的主题。 </section>
<add><section id='instructions'>
<add>代码编辑器完成了<code>MyToDoList</code>组件的大部分设置。如果你完成了受控表单挑战,这些代码中的一些应该看起来很熟悉。你会注意到一个<code>textarea</code>和一个<code>button</code>,以及一些跟踪它们状态的方法,但是页面当前还没有任何东西被渲染。
<add>在<code>constructor</code>中,创建一个<code>this.state</code>对象并定义两个 state:<code>userInput</code>应该初始化为空字符串,<code>toDoList</code>应该初始化为空数组。接下来,删除<code>items</code>变量旁边<code>render()</code>方法中的注释。取而代之的是,将存储在组件内部 state 中的<code>toDoList</code>数组一一映射并相应的动态呈现<code>li</code>元素。尝试在<code>textarea</code>中输入<code>eat, code, sleep, repeat</code>,然后点击按钮,看看会发生什么。
<add><strong>注意:</strong> 你可能知道,像这样的映射操作创建的所有兄弟子元素都需要提供唯一的<code>key</code>属性。别担心,这是下一个挑战的主题。
<add></section>
<ide>
<ide> ## Tests
<ide> <section id='tests'>
<ide>
<ide> ```yml
<ide> tests:
<del> - text: MyToDoList组件应该存在并呈现给页面。
<del> testString: 'assert((function() { const mockedComponent = Enzyme.mount(React.createElement(MyToDoList)); return mockedComponent.find("MyToDoList").length === 1; })(), "The MyToDoList component should exist and render to the page.");'
<del> - text: <code>MyToDoList</code>的第一个子<code>MyToDoList</code>应该是<code>textarea</code>元素。
<del> testString: 'assert((function() { const mockedComponent = Enzyme.mount(React.createElement(MyToDoList)); return mockedComponent.find("MyToDoList").children().childAt(0).type() === "textarea"; })(), "The first child of <code>MyToDoList</code> should be a <code>textarea</code> element.");'
<del> - text: <code>MyToDoList</code>的第三个子<code>MyToDoList</code>应该是一个<code>button</code>元素。
<del> testString: 'assert((function() { const mockedComponent = Enzyme.mount(React.createElement(MyToDoList)); return mockedComponent.find("MyToDoList").children().childAt(2).type() === "button"; })(), "The third child of <code>MyToDoList</code> should be a <code>button</code> element.");'
<del> - text: 应使用<code>toDoList</code>将<code>MyToDoList</code>的状态初始化为空数组。
<del> testString: 'assert((function() { const mockedComponent = Enzyme.mount(React.createElement(MyToDoList)); const initialState = mockedComponent.state(); return Array.isArray(initialState.toDoList) === true && initialState.toDoList.length === 0; })(), "The state of <code>MyToDoList</code> should be initialized with <code>toDoList</code> as an empty array.");'
<del> - text: 应使用<code>userInput</code>将<code>MyToDoList</code>的状态初始化为空字符串。
<del> testString: 'assert((function() { const mockedComponent = Enzyme.mount(React.createElement(MyToDoList)); const initialState = mockedComponent.state(); return typeof initialState.userInput === "string" && initialState.userInput.length === 0; })(), "The state of <code>MyToDoList</code> should be initialized with <code>userInput</code> as an empty string.");'
<del> - text: 单击“ <code>Create List</code>按钮时, <code>MyToDoList</code>组件应动态返回无序列表,该列表包含输入到<code>textarea</code>元素中的逗号分隔列表的每个项目的列表项元素。
<del> testString: 'async () => { const waitForIt = (fn) => new Promise((resolve, reject) => setTimeout(() => resolve(fn()), 100)); const mockedComponent = Enzyme.mount(React.createElement(MyToDoList)); const simulateChange = (el, value) => el.simulate("change", {target: {value}}); const state_1 = () => { return waitForIt(() => mockedComponent.find("ul").find("li"))}; const setInput = () => { return waitForIt(() => simulateChange(mockedComponent.find("textarea"), "testA, testB, testC"))}; const click = () => { return waitForIt(() => mockedComponent.find("button").simulate("click"))}; const state_2 = () => { return waitForIt(() => { const nodes = mockedComponent.find("ul").find("li"); return { nodes, text: nodes.reduce((t, n) => t + n.text(), "") }; })}; const setInput_2 = () => { return waitForIt(() => simulateChange(mockedComponent.find("textarea"), "t1, t2, t3, t4, t5, t6"))}; const click_1 = () => { return waitForIt(() => mockedComponent.find("button").simulate("click"))}; const state_3 = () => { return waitForIt(() => { const nodes = mockedComponent.find("ul").find("li"); return { nodes, text: nodes.reduce((t, n) => t + n.text(), "") }; })}; const awaited_state_1 = await state_1(); const awaited_setInput = await setInput(); const awaited_click = await click(); const awaited_state_2 = await state_2(); const awaited_setInput_2 = await setInput_2(); const awaited_click_1 = await click_1(); const awaited_state_3 = await state_3(); assert(awaited_state_1.length === 0 && awaited_state_2.nodes.length === 3 && awaited_state_3.nodes.length === 6 && awaited_state_2.text === "testA testB testC" && awaited_state_3.text === "t1 t2 t3 t4 t5 t6", "When the <code>Create List</code> button is clicked, the <code>MyToDoList</code> component should dynamically return an unordered list that contains a list item element for every item of a comma-separated list entered into the <code>textarea</code> element."); }; '
<add> - text: <code>MyToDoList</code>组件应该存在并渲染到页面。
<add> testString: assert((function() { const mockedComponent = Enzyme.mount(React.createElement(MyToDoList)); return mockedComponent.find('MyToDoList').length === 1; })());
<add> - text: <code>MyToDoList</code>组件的第一个子元素应该是<code>textarea</code>元素。
<add> testString: assert((function() { const mockedComponent = Enzyme.mount(React.createElement(MyToDoList)); return mockedComponent.find('MyToDoList').children().childAt(0).type() === 'textarea'; })());
<add> - text: <code>MyToDoList</code>组件的第二个子元素应该是<code>br</code>元素。
<add> testString: assert((function() { const mockedComponent = Enzyme.mount(React.createElement(MyToDoList)); return mockedComponent.find('MyToDoList').children().childAt(1).type() === 'br'; })());
<add> - text: <code>MyToDoList</code>组件的第三个子元素应该是<code>button</code>元素。
<add> testString: assert((function() { const mockedComponent = Enzyme.mount(React.createElement(MyToDoList)); return mockedComponent.find('MyToDoList').children().childAt(2).type() === 'button'; })());
<add> - text: <code>MyToDoList</code>的 state 应该使用被设置为空数组的<code>toDoList</code>进行初始化。
<add> testString: assert((function() { const mockedComponent = Enzyme.mount(React.createElement(MyToDoList)); const initialState = mockedComponent.state(); return Array.isArray(initialState.toDoList) === true && initialState.toDoList.length === 0; })());
<add> - text: <code>MyToDoList</code>的 state 应该使用被设置为空字符串的<code>userInput</code>进行初始化。
<add> testString: assert((function() { const mockedComponent = Enzyme.mount(React.createElement(MyToDoList)); const initialState = mockedComponent.state(); return typeof initialState.userInput === 'string' && initialState.userInput.length === 0; })());
<add> - text: 单击<code>Create List</code>按钮时,<code>MyToDoList</code>组件应该动态返回一个无序列表,该列表包含输入到<code>textarea</code>元素中的逗号分隔列表的每个项目的列表项目元素。
<add> testString: 'async () => { const waitForIt = (fn) => new Promise((resolve, reject) => setTimeout(() => resolve(fn()), 100)); const mockedComponent = Enzyme.mount(React.createElement(MyToDoList)); const simulateChange = (el, value) => el.simulate(''change'', {target: {value}}); const state_1 = () => { return waitForIt(() => mockedComponent.find(''ul'').find(''li''))}; const setInput = () => { return waitForIt(() => simulateChange(mockedComponent.find(''textarea''), "testA, testB, testC"))}; const click = () => { return waitForIt(() => mockedComponent.find(''button'').simulate(''click''))}; const state_2 = () => { return waitForIt(() => { const nodes = mockedComponent.find(''ul'').find(''li''); return { nodes, text: nodes.reduce((t, n) => t + n.text(), '''') }; })}; const setInput_2 = () => { return waitForIt(() => simulateChange(mockedComponent.find(''textarea''), "t1, t2, t3, t4, t5, t6"))}; const click_1 = () => { return waitForIt(() => mockedComponent.find(''button'').simulate(''click''))}; const state_3 = () => { return waitForIt(() => { const nodes = mockedComponent.find(''ul'').find(''li''); return { nodes, text: nodes.reduce((t, n) => t + n.text(), '''') }; })}; const awaited_state_1 = await state_1(); const awaited_setInput = await setInput(); const awaited_click = await click(); const awaited_state_2 = await state_2(); const awaited_setInput_2 = await setInput_2(); const awaited_click_1 = await click_1(); const awaited_state_3 = await state_3(); assert(awaited_state_1.length === 0 && awaited_state_2.nodes.length === 3 && awaited_state_3.nodes.length === 6 && awaited_state_2.text === ''testA testB testC'' && awaited_state_3.text === ''t1 t2 t3 t4 t5 t6''); }; '
<ide>
<ide> ```
<ide>
<ide> class MyToDoList extends React.Component {
<ide> onChange={this.handleChange}
<ide> value={this.state.userInput}
<ide> style={textAreaStyles}
<del> placeholder="Separate Items With Commas" /><br />
<add> placeholder="Separate Items With Commas" />
<add> <br />
<ide> <button onClick={this.handleSubmit}>Create List</button>
<ide> <h1>My "To Do" List:</h1>
<ide> <ul>
<ide> class MyToDoList extends React.Component {
<ide> );
<ide> }
<ide> };
<del>
<ide> ```
<ide>
<ide> </div>
<ide>
<del>
<ide> ### After Test
<ide> <div id='jsx-teardown'>
<ide>
<ide> ```js
<del>console.info('after the test');
<add>ReactDOM.render(<MyToDoList />, document.getElementById('root'))
<ide> ```
<ide>
<ide> </div>
<ide> console.info('after the test');
<ide> ## Solution
<ide> <section id='solution'>
<ide>
<add>
<ide> ```js
<del>// solution required
<add>const textAreaStyles = {
<add> width: 235,
<add> margin: 5
<add>};
<add>
<add>class MyToDoList extends React.Component {
<add> constructor(props) {
<add> super(props);
<add> this.state = {
<add> toDoList: [],
<add> userInput: ''
<add> }
<add> this.handleSubmit = this.handleSubmit.bind(this);
<add> this.handleChange = this.handleChange.bind(this);
<add> }
<add> handleSubmit() {
<add> const itemsArray = this.state.userInput.split(',');
<add> this.setState({
<add> toDoList: itemsArray
<add> });
<add> }
<add> handleChange(e) {
<add> this.setState({
<add> userInput: e.target.value
<add> });
<add> }
<add> render() {
<add> const items = this.state.toDoList.map( (item, i) => {
<add> return <li key={i}>{item}</li>
<add> });
<add> return (
<add> <div>
<add> <textarea
<add> onChange={this.handleChange}
<add> value={this.state.userInput}
<add> style={textAreaStyles}
<add> placeholder="Separate Items With Commas" /><br />
<add> <button onClick={this.handleSubmit}>Create List</button>
<add> <h1>My "To Do" List:</h1>
<add> <ul>
<add> {items}
<add> </ul>
<add> </div>
<add> );
<add> }
<add>};
<ide> ```
<ide>
<del>/section>
<add></section>
<ide><path>curriculum/challenges/chinese/03-front-end-libraries/react/use-default-props.chinese.md
<ide> id: 5a24c314108439a4d403616b
<ide> title: Use Default Props
<ide> challengeType: 6
<ide> isRequired: false
<del>videoUrl: ''
<del>localeTitle: 使用默认道具
<add>forumTopicId: 301418
<add>localeTitle: 使用默认的 Props
<ide> ---
<ide>
<ide> ## Description
<del><section id="description"> React还有一个设置默认道具的选项。您可以将默认道具分配给组件作为组件本身的属性,如果需要,React会分配默认支柱。如果没有显式提供值,这允许您指定prop值应该是什么。例如,如果您声明<code>MyComponent.defaultProps = { location: 'San Francisco' }</code> ,则您已定义了设置为<code>San Francisco</code>字符串的位置道具,除非您另行指定。如果道具未定义,则React会指定默认道具,但如果您将<code>null</code>作为道具的值传递,则它将保持为<code>null</code> 。 </section>
<add><section id='description'>
<add>React 还有一个设置默认 props 的选项。你可以将默认 props 作为组件本身的属性分配给组件,React 会在必要时分配默认 prop。如果没有显式的提供任何值,这允许你指定 prop 值应该是什么。例如,如果你声明<code>MyComponent.defaultProps = { location: 'San Francisco' }</code>,即定义一个 location 属性,并且其值在没有另行制定的情况下被设置为字符串<code>San Francisco</code>。如果 props 未定义,则 React 会分配默认 props,但如果你将<code>null</code>作为 prop 的值,它将保持<code>null</code>。
<add></section>
<ide>
<ide> ## Instructions
<del><section id="instructions">代码编辑器显示<code>ShoppingCart</code>组件。在此组件上定义默认道具,指定值为<code>0</code>的道具<code>items</code> 。 </section>
<add><section id='instructions'>
<add>代码编辑器中有一个<code>ShoppingCart</code>组件。在这个组件上定义默认 props,它指定一个<code>items</code>prop,其值为<code>0</code>。
<add></section>
<ide>
<ide> ## Tests
<ide> <section id='tests'>
<ide>
<ide> ```yml
<ide> tests:
<del> - text: <code>ShoppingCart</code>组件应该呈现。
<add> - text: 应该渲染<code>ShoppingCart</code>组件。
<ide> testString: assert((function() { const mockedComponent = Enzyme.mount(React.createElement(ShoppingCart)); return mockedComponent.find('ShoppingCart').length === 1; })());
<del> - text: '<code>ShoppingCart</code>组件应具有<code>{ items: 0 }</code>的默认支柱。'
<add> - text: '<code>ShoppingCart</code>组件应该有一个<code>{ items: 0 }</code>的默认 prop。'
<ide> testString: 'assert((function() { const mockedComponent = Enzyme.mount(React.createElement(ShoppingCart)); mockedComponent.setProps({items: undefined}); return mockedComponent.find(''ShoppingCart'').props().items === 0; })());'
<ide>
<ide> ```
<ide> const ShoppingCart = (props) => {
<ide> <div id='jsx-teardown'>
<ide>
<ide> ```js
<del>console.info('after the test');
<add>ReactDOM.render(<ShoppingCart />, document.getElementById('root'))
<ide> ```
<ide>
<ide> </div>
<ide> console.info('after the test');
<ide> ## Solution
<ide> <section id='solution'>
<ide>
<add>
<ide> ```js
<del>// solution required
<add>const ShoppingCart = (props) => {
<add> return (
<add> <div>
<add> <h1>Shopping Cart Component</h1>
<add> </div>
<add> )
<add>};
<add>
<add>// change code below this line
<add>ShoppingCart.defaultProps = {
<add> items: 0
<add>}
<ide> ```
<ide>
<del>/section>
<add></section>
<ide><path>curriculum/challenges/chinese/03-front-end-libraries/react/use-proptypes-to-define-the-props-you-expect.chinese.md
<ide> id: 5a24c314108439a4d403616d
<ide> title: Use PropTypes to Define the Props You Expect
<ide> challengeType: 6
<ide> isRequired: false
<del>videoUrl: ''
<del>localeTitle: 使用PropTypes定义您期望的道具
<add>forumTopicId: 301419
<add>localeTitle: 使用 PropTypes 来定义你期望的 Props
<ide> ---
<ide>
<ide> ## Description
<del><section id="description"> React提供了有用的类型检查功能,以验证组件是否接收到正确类型的道具。例如,您的应用程序进行API调用以检索您希望在数组中的数据,然后将其作为prop传递给组件。您可以在组件上设置<code>propTypes</code> ,以要求数据类型为<code>array</code> 。当数据是任何其他类型时,这将抛出有用的警告。当您提前知道道具类型时,设置<code>propTypes</code>被认为是最佳做法。您可以使用与定义<code>defaultProps</code>相同的方式为组件定义<code>propTypes</code>属性。这样做将检查给定键的道具是否存在给定类型。这是一个需要类型<code>function</code>的例子,名为<code>handleClick</code> : <code>MyComponent.propTypes = { handleClick: PropTypes.func.isRequired }</code>在上面的例子中, <code>PropTypes.func</code>部分检查<code>handleClick</code>是一个函数。添加<code>isRequired</code>告诉React <code>handleClick</code>是该组件的必需属性。如果未提供支柱,您将看到警告。还要注意<code>func</code>代表<code>function</code> 。在七种JavaScript原语类型中, <code>function</code>和<code>boolean</code> (写为<code>bool</code> )是唯一使用异常拼写的两种类型。除了原始类型,还有其他类型可用。例如,您可以检查prop是否为React元素。有关所有选项,请参阅文档。 <strong>注意:</strong>从React v15.5.0开始, <code>PropTypes</code>独立于React <code>import PropTypes from 'prop-types';</code> ,如下所示: <code>import PropTypes from 'prop-types';</code> </section>
<add><section id='description'>
<add>React 提供了有用的类型检查特性,以验证组件是否接收了正确类型的 props。例如,你的应用程序调用 API 来检索你希望在数组中的数据,然后将数据作为 prop 传递给组件。你可以在组件上设置<code>propTypes</code>,以要求数据的类型为<code>array</code>。当数据是任何其他类型时,都会抛出警告。
<add>当你提前知道 prop 的类型时,最好的做法是设置<code>propTypes</code>。可以为组件定义<code>propTypes</code>属性,方法与定义<code>defaultProps</code>相同。这样做将检查给定键的 prop 是否是给定类型。这里有一个示例,名为<code>handleClick</code>的 prop 应为<code>function</code>类型:
<add><code>MyComponent.propTypes = { handleClick: PropTypes.func.isRequired }</code>
<add>
<add>在上面的示例中,<code>PropTypes.func</code>部分检查<code>handleClick</code>是否为函数。添加<code>isRequired</code>是为了告诉 React<code>handleClick</code>是该组件的必需属性。如果未提供该 prop,你将看到警告信息。另请注意,<code>func</code>表示<code>function</code>。在 7 种 JavaScript 基本类型中,<code>function</code>和<code>boolean</code>(写为<code>bool</code>)是仅有的使用异常拼写的两种类型。除了基本类型,还有其他类型可用。例如,你可以检查 prop 是否为 React 组件,请参阅文档以获取所有选项。
<add>
<add><strong>注意:</strong>在 React v15.5.0 版本中, <code>PropTypes</code>可以从 React 中单独引入,如下所示:
<add><code>import React, { PropTypes } from 'react';</code>
<add></section>
<ide>
<ide> ## Instructions
<del><section id="instructions">为<code>Items</code>组件定义<code>propTypes</code>以要求<code>quantity</code>作为prop并验证它是否为<code>number</code>类型。 </section>
<add><section id='instructions'>
<add>为<code>Items</code>组件定义<code>propTypes</code>,要求<code>quantity</code>作为 prop,并验证它是<code>number</code>类型。
<add></section>
<ide>
<ide> ## Tests
<ide> <section id='tests'>
<ide>
<ide> ```yml
<ide> tests:
<del> - text: <code>ShoppingCart</code>组件应该呈现。
<add> - text: 应该渲染<code>ShoppingCart</code>组件。
<ide> testString: assert((function() { const mockedComponent = Enzyme.mount(React.createElement(ShoppingCart)); return mockedComponent.find('ShoppingCart').length === 1; })());
<del> - text: <code>Items</code>组件应该呈现。
<add> - text: 应该渲染<code>Items</code>组件。
<ide> testString: assert((function() { const mockedComponent = Enzyme.mount(React.createElement(ShoppingCart)); return mockedComponent.find('Items').length === 1; })());
<del> - text: <code>Items</code>组件应包含<code>propTypes</code>检查,该检查要求<code>quantity</code>为<code>number</code> 。
<add> - text: <code>Items</code>组件应该包含一个<code>propTypes</code>,以检查<code>quantity</code>是<code>number</code>类型。
<ide> testString: getUserInput => assert((function() { const noWhiteSpace = getUserInput('index').replace(/ /g, ''); return noWhiteSpace.includes('quantity:PropTypes.number.isRequired') && noWhiteSpace.includes('Items.propTypes='); })());
<ide>
<ide> ```
<ide> class ShoppingCart extends React.Component {
<ide> return <Items />
<ide> }
<ide> };
<del>
<ide> ```
<ide>
<ide> </div>
<ide> var PropTypes = {
<ide> <div id='jsx-teardown'>
<ide>
<ide> ```js
<del>console.info('after the test');
<add>ReactDOM.render(<ShoppingCart />, document.getElementById('root'))
<ide> ```
<ide>
<ide> </div>
<ide> console.info('after the test');
<ide> ## Solution
<ide> <section id='solution'>
<ide>
<add>
<ide> ```js
<del>// solution required
<add>const Items = (props) => {
<add> return <h1>Current Quantity of Items in Cart: {props.quantity}</h1>
<add>};
<add>
<add>// change code below this line
<add>Items.propTypes = {
<add> quantity: PropTypes.number.isRequired
<add>};
<add>// change code above this line
<add>
<add>Items.defaultProps = {
<add> quantity: 0
<add>};
<add>
<add>class ShoppingCart extends React.Component {
<add> constructor(props) {
<add> super(props);
<add> }
<add> render() {
<add> return <Items />
<add> }
<add>};
<ide> ```
<ide>
<del>/section>
<add></section>
<ide><path>curriculum/challenges/chinese/03-front-end-libraries/react/use-react-to-render-nested-components.chinese.md
<ide> id: 5a24c314108439a4d4036165
<ide> title: Use React to Render Nested Components
<ide> challengeType: 6
<ide> isRequired: false
<del>videoUrl: ''
<del>localeTitle: 使用React渲染嵌套组件
<add>forumTopicId: 301420
<add>localeTitle: 使用 React 渲染嵌套组件
<ide> ---
<ide>
<ide> ## Description
<del><section id="description">最后一个挑战显示了组合两个组件的简单方法,但是有许多不同的方法可以使用React组合组件。组件组合是React强大的功能之一。当您使用React时,重要的是开始根据组件(如上一个挑战中的App示例)考虑您的用户界面。您将UI分解为其基本构建块,这些块成为组件。这有助于将负责UI的代码与负责处理应用程序逻辑的代码分开。它可以大大简化复杂项目的开发和维护。 </section>
<add><section id='description'>
<add>上一个挑战显示了组合两个组件的简单方法,但是有许多不同的方法可以把 React 组件组合在一起。
<add>组件组合是 React 的强大功能之一。当你使用 React 时,应当先用组件的思路考虑清楚用户界面的结构(如上一个挑战中的 App 示例)。可以将 UI 分解为基本的构建块,这些构建块就是组件。这样做有助于将负责 UI 的代码与负责处理应用程序逻辑的代码分开,并可以大大简化复杂项目的开发和维护。
<add></section>
<ide>
<ide> ## Instructions
<del><section id="instructions">代码编辑器中定义了两个功能组件,名为<code>TypesOfFruit</code>和<code>Fruits</code> 。取<code>TypesOfFruit</code>组分和构成它,或者它<em>窝</em> ,所述内<code>Fruits</code>组分。然后使用<code>Fruits</code>组件并将其嵌套在<code>TypesOfFood</code>组件中。结果应该是一个嵌套在父组件中的子组件,它嵌套在它自己的父组件中! </section>
<add><section id='instructions'>
<add>代码编辑器中定义了两个功能组件,分别是<code>TypesOfFruit</code>和<code>Fruits</code>。请把<code>TypesOfFruit</code>组件放到<code>Fruits</code>组件中,然后把<code>Fruits</code>组件放到<code>TypesOfFood</code>组件中。结果应该是子组件嵌套在父组件中,父组件嵌套在它本身的父组件中!
<add></section>
<ide>
<ide> ## Tests
<ide> <section id='tests'>
<ide>
<ide> ```yml
<ide> tests:
<del> - text: <code>TypesOfFood</code>组件应返回单个<code>div</code>元素。
<add> - text: <code>TypesOfFood</code>组件应该返回单个<code>div</code>元素。
<ide> testString: assert(Enzyme.shallow(React.createElement(TypesOfFood)).type() === 'div');
<del> - text: <code>TypesOfFood</code>组件应返回<code>Fruits</code>组件。
<add> - text: <code>TypesOfFood</code>组件应该返回<code>Fruits</code>组件。
<ide> testString: assert(Enzyme.shallow(React.createElement(TypesOfFood)).props().children[1].type.name === 'Fruits');
<del> - text: <code>Fruits</code>组件应返回<code>TypesOfFruit</code>组件。
<add> - text: <code>Fruits</code>组件应该返回<code>TypesOfFruit</code>组件。
<ide> testString: assert(Enzyme.mount(React.createElement(TypesOfFood)).find('h2').html() === '<h2>Fruits:</h2>');
<del> - text: <code>TypesOfFruit</code>组件应返回<code>h2</code>和<code>ul</code>元素。
<add> - text: <code>TypesOfFruit</code>组件应该返回<code>h2</code>和<code>ul</code>元素。
<ide> testString: assert(Enzyme.mount(React.createElement(TypesOfFood)).find('ul').text() === 'ApplesBlueberriesStrawberriesBananas');
<ide>
<ide> ```
<ide> class TypesOfFood extends React.Component {
<ide> );
<ide> }
<ide> };
<del>
<ide> ```
<ide>
<ide> </div>
<ide> class TypesOfFood extends React.Component {
<ide> <div id='jsx-teardown'>
<ide>
<ide> ```js
<del>console.info('after the test');
<add>ReactDOM.render(<TypesOfFood />, document.getElementById('root'))
<ide> ```
<ide>
<ide> </div>
<ide> console.info('after the test');
<ide> ## Solution
<ide> <section id='solution'>
<ide>
<add>
<ide> ```js
<del>// solution required
<add>const TypesOfFruit = () => {
<add> return (
<add> <div>
<add> <h2>Fruits:</h2>
<add> <ul>
<add> <li>Apples</li>
<add> <li>Blueberries</li>
<add> <li>Strawberries</li>
<add> <li>Bananas</li>
<add> </ul>
<add> </div>
<add> );
<add>};
<add>
<add>const Fruits = () => {
<add> return (
<add> <div>
<add> { /* change code below this line */ }
<add> <TypesOfFruit />
<add> { /* change code above this line */ }
<add> </div>
<add> );
<add>};
<add>
<add>class TypesOfFood extends React.Component {
<add> constructor(props) {
<add> super(props);
<add> }
<add>
<add> render() {
<add> return (
<add> <div>
<add> <h1>Types of Food:</h1>
<add> { /* change code below this line */ }
<add> <Fruits />
<add> { /* change code above this line */ }
<add> </div>
<add> );
<add> }
<add>};
<ide> ```
<ide>
<del>/section>
<add></section>
<ide><path>curriculum/challenges/chinese/03-front-end-libraries/react/use-state-to-toggle-an-element.chinese.md
<ide> id: 5a24c314108439a4d4036176
<ide> title: Use State to Toggle an Element
<ide> challengeType: 6
<ide> isRequired: false
<del>videoUrl: ''
<del>localeTitle: 使用State切换元素
<add>forumTopicId: 301421
<add>localeTitle: 使用 State 切换元素
<ide> ---
<ide>
<ide> ## Description
<del><section id="description">您可以以比您目前所见的更复杂的方式在React应用程序中使用<code>state</code> 。一个示例是监视值的状态,然后根据此值有条件地呈现UI。有几种不同的方法可以实现这一点,代码编辑器显示了一种方法。 </section>
<add><section id='description'>
<add>有时可能在更新状态的时候想知道上一个状态是什么。但是状态更新是异步的,这意味着 React 可能会把多个 <code>setState()</code> 集中在一起批量更新。所以设置 <code>this.state</code> 或者 <code>this.props</code> 后值没有立即更新。所以最好不要写如下的代码:
<add>
<add>```js
<add>this.setState({
<add> counter: this.state.counter + this.props.increment
<add>});
<add>```
<add>
<add>正确的做法是,给 <code>setState</code> 传入一个函数,这个函数可以访问 state 和 props。给 <code>setState</code> 传入函数可以返回赋值后的 state 和 props。代码可以重写为这样:
<add>
<add>```js
<add>this.setState((state, props) => ({
<add> counter: state.counter + props.increment
<add>}));
<add>```
<add>
<add>如果只需要 `state`,那么用下面的格式也是可以的:
<add>
<add>```js
<add>this.setState(state => ({
<add> counter: state.counter + 1
<add>}));
<add>```
<add>
<add>注意一定要把 object 放在括号里,否则 JavaScript 会认为这只是代码片段。
<add></section>
<ide>
<ide> ## Instructions
<del><section id="instructions"> <code>MyComponent</code>有一个<code>visibility</code>属性,初始化为<code>false</code> 。如果<code>visibility</code>值为true,则render方法返回一个视图;如果为false,则返回不同的视图。目前,无法更新组件<code>state</code>的<code>visibility</code>属性。该值应在true和false之间来回切换。按钮上有一个单击处理程序,它触发一个名为<code>toggleVisibility()</code>的类方法。定义此方法,以便在调用方法时, <code>visibility</code> <code>state</code>切换为相反的值。如果<code>visibility</code>是<code>false</code> ,该方法将其设置为<code>true</code> ,反之亦然。最后,单击按钮以根据其<code>state</code>查看组件的条件呈现。 <strong>提示:</strong>不要忘记将<code>this</code>关键字绑定到构造函数中的方法! </section>
<add><section id='instructions'>
<add><code>MyComponent</code>有一个初始值为<code>false</code>的<code>visibility</code>属性。如果<code>visibility</code>的值为 true,render 方法返回一个视图,如果为 false,返回另一个视图。
<add>目前,无法更新组件的<code>state</code>中的<code>visibility</code>属性,该值应在 true 和 false 之间来回切换。按钮上有一个单击处理程序,它触发一个名为<code>toggleVisibility()</code>的类方法。定义此方法,以便<code>visibility</code>的<code>state</code>在调用方法时切换到相反的值。如果<code>visibility</code>是<code>false</code>,则该方法将其设置为<code>true</code>,反之亦然。
<add>最后,单击按钮以查看基于其<code>state</code>的组件的条件渲染。
<add><strong>提示:</strong> 不要忘记将<code>this</code>关键字绑定到构造函数中的方法上!
<add></section>
<ide>
<ide> ## Tests
<ide> <section id='tests'>
<ide>
<ide> ```yml
<ide> tests:
<del> - text: <code>MyComponent</code>应该返回一个包含<code>button</code>的<code>div</code>元素。
<del> testString: 'assert.strictEqual(Enzyme.mount(React.createElement(MyComponent)).find("div").find("button").length, 1, "<code>MyComponent</code> should return a <code>div</code> element which contains a <code>button</code>.");'
<del> - text: <code>MyComponent</code>的状态应该初始化,并将<code>visibility</code>属性设置为<code>false</code> 。
<del> testString: 'assert.strictEqual(Enzyme.mount(React.createElement(MyComponent)).state("visibility"), false, "The state of <code>MyComponent</code> should initialize with a <code>visibility</code> property set to <code>false</code>.");'
<del> - text: 单击按钮元素应该在<code>true</code>和<code>false</code>之间切换状态的<code>visibility</code>属性。
<del> testString: 'async () => { const waitForIt = (fn) => new Promise((resolve, reject) => setTimeout(() => resolve(fn()), 250)); const mockedComponent = Enzyme.mount(React.createElement(MyComponent)); const first = () => { mockedComponent.setState({ visibility: false }); return waitForIt(() => mockedComponent.state("visibility")); }; const second = () => { mockedComponent.find("button").simulate("click"); return waitForIt(() => mockedComponent.state("visibility")); }; const third = () => { mockedComponent.find("button").simulate("click"); return waitForIt(() => mockedComponent.state("visibility")); }; const firstValue = await first(); const secondValue = await second(); const thirdValue = await third(); assert(!firstValue && secondValue && !thirdValue, "Clicking the button element should toggle the <code>visibility</code> property in state between <code>true</code> and <code>false</code>."); }; '
<add> - text: <code>MyComponent</code>应该返回一个<code>div</code>元素,其中包含一个<code>button</code>元素。
<add> testString: assert.strictEqual(Enzyme.mount(React.createElement(MyComponent)).find('div').find('button').length, 1);
<add> - text: <code>MyComponent</code>应该使用设置为<code>false</code>的<code>visibility</code>属性来初始化其 state。
<add> testString: assert.strictEqual(Enzyme.mount(React.createElement(MyComponent)).state('visibility'), false);
<add> - text: 单击按钮元素应在<code>true</code>和<code>false</code>之间切换<code>visibility</code>属性的状态。
<add> testString: 'async () => { const waitForIt = (fn) => new Promise((resolve, reject) => setTimeout(() => resolve(fn()), 250)); const mockedComponent = Enzyme.mount(React.createElement(MyComponent)); const first = () => { mockedComponent.setState({ visibility: false }); return waitForIt(() => mockedComponent.state(''visibility'')); }; const second = () => { mockedComponent.find(''button'').simulate(''click''); return waitForIt(() => mockedComponent.state(''visibility'')); }; const third = () => { mockedComponent.find(''button'').simulate(''click''); return waitForIt(() => mockedComponent.state(''visibility'')); }; const firstValue = await first(); const secondValue = await second(); const thirdValue = await third(); assert(!firstValue && secondValue && !thirdValue); }; '
<add> - text: 应该传入<code>setState</code> 一个匿名函数。
<add> testString: const paramRegex = '[a-zA-Z$_]\\w*(,[a-zA-Z$_]\\w*)?'; const noSpaces = code.replace(/\s/g, ''); assert(new RegExp('this\\.setState\\((function\\(' + paramRegex + '\\){|([a-zA-Z$_]\\w*|\\(' + paramRegex + '\\))=>)').test(noSpaces));
<add> - text: 不要在 <code>setState</code> 里面使用 <code>this</code>。
<add> testString: assert(!/this\.setState\([^}]*this/.test(code));
<ide>
<ide> ```
<ide>
<ide> class MyComponent extends React.Component {
<ide> }
<ide> }
<ide> };
<del>
<ide> ```
<ide>
<ide> </div>
<ide> class MyComponent extends React.Component {
<ide> <div id='jsx-teardown'>
<ide>
<ide> ```js
<del>console.info('after the test');
<add>ReactDOM.render(<MyComponent />, document.getElementById('root'))
<ide> ```
<ide>
<ide> </div>
<ide> console.info('after the test');
<ide> ## Solution
<ide> <section id='solution'>
<ide>
<add>
<ide> ```js
<del>// solution required
<add>class MyComponent extends React.Component {
<add> constructor(props) {
<add> super(props);
<add> this.state = {
<add> visibility: false
<add> };
<add> this.toggleVisibility = this.toggleVisibility.bind(this);
<add> }
<add> toggleVisibility() {
<add> this.setState(state => ({
<add> visibility: !state.visibility
<add> }));
<add> }
<add> render() {
<add> if (this.state.visibility) {
<add> return (
<add> <div>
<add> <button onClick = {this.toggleVisibility}>Click Me</button>
<add> <h1>Now you see me!</h1>
<add> </div>
<add> );
<add> } else {
<add> return (
<add> <div>
<add> <button onClick = {this.toggleVisibility}>Click Me</button>
<add> </div>
<add> );
<add> }
<add> }
<add>};
<ide> ```
<ide>
<del>/section>
<add></section>
<ide><path>curriculum/challenges/chinese/03-front-end-libraries/react/use-the-lifecycle-method-componentdidmount.chinese.md
<ide> id: 5a24c314108439a4d403617d
<ide> title: Use the Lifecycle Method componentDidMount
<ide> challengeType: 6
<ide> isRequired: false
<del>videoUrl: ''
<del>localeTitle: 使用生命周期方法componentDidMount
<add>forumTopicId: 301422
<add>localeTitle: 使用生命周期方法:componentDidMount
<ide> ---
<ide>
<ide> ## Description
<del><section id="description">大多数Web开发人员在某些时候需要调用API端点来检索数据。如果您正在使用React,那么知道执行此操作的位置非常重要。 React的最佳实践是在生命周期方法<code>componentDidMount()</code>中对服务器进行API调用或任何调用。将组件安装到DOM后调用此方法。此处对<code>setState()</code>任何调用都将触发组件的重新呈现。在此方法中调用API并使用API返回的数据设置状态时,一旦收到数据,它将自动触发更新。 </section>
<add><section id='description'>
<add>某些时候,大多数 web 开发人员需要调用 API 端点来检索数据。如果你正在使用 React,知道在哪里执行这个动作是很重要的。
<add>React 的最佳实践是在生命周期方法<code>componentDidMount()</code>中对服务器进行 API 调用或任何其他调用。将组件装载到 DOM 后会调用此方法。此处对<code>setState()</code>的任何调用都将触发组件的重新渲染。在此方法中调用 API 并使用 API 返回的数据设置 state 时,一旦收到数据,它将自动触发更新。
<add></section>
<ide>
<ide> ## Instructions
<del><section id="instructions"> <code>componentDidMount()</code>有一个模拟API调用。它在2.5秒后设置状态以模拟调用服务器以检索数据。此示例请求站点的当前活动用户总数。在render方法中,在<code>h1</code>呈现<code>activeUsers</code>的值。观看预览中发生的事情,并随时更改超时以查看不同的效果。 </section>
<add><section id='instructions'>
<add><code>componentDidMount()</code>中有一个模拟 API 调用。它在 2.5 秒后设置 state,以模拟调用服务器检索数据。本示例请求站点的当前活动用户总数。在 render 方法中,把<code>activeUsers</code>渲染到<code>h1</code>标签中。观看预览中发生的事情,随意更改超时时间以查看不同的效果。
<add></section>
<ide>
<ide> ## Tests
<ide> <section id='tests'>
<ide>
<ide> ```yml
<ide> tests:
<del> - text: <code>MyComponent</code>应该呈现一个包含<code>h1</code>标记的<code>div</code>元素。
<add> - text: <code>MyComponent</code>应该渲染一个包含<code>h1</code>标签的<code>div</code>元素。
<ide> testString: assert((() => { const mockedComponent = Enzyme.mount(React.createElement(MyComponent)); return (mockedComponent.find('div').length === 1 && mockedComponent.find('h1').length === 1); })());
<del> - text: 应使用<code>componentDidMount</code>的超时函数更新组件状态。
<add> - text: 组件 state 应该用<code>componentDidMount</code>中的延时函数来更新。
<ide> testString: assert((() => { const mockedComponent = Enzyme.mount(React.createElement(MyComponent)); return new RegExp('setTimeout(.|\n)+setState(.|\n)+activeUsers').test(String(mockedComponent.instance().componentDidMount)); })());
<del> - text: <code>h1</code>标记应该从<code>MyComponent</code>的状态呈现<code>activeUsers</code>值。
<add> - text: <code>h1</code>标签应该从<code>MyComponent</code>的 state 渲染<code>activeUsers</code>值。
<ide> testString: 'async () => { const mockedComponent = Enzyme.mount(React.createElement(MyComponent)); const first = () => { mockedComponent.setState({ activeUsers: 1237 }); return mockedComponent.find(''h1'').text(); }; const second = () => { mockedComponent.setState({ activeUsers: 1000 }); return mockedComponent.find(''h1'').text(); }; assert(new RegExp(''1237'').test(first()) && new RegExp(''1000'').test(second())); }; '
<ide>
<ide> ```
<ide> class MyComponent extends React.Component {
<ide> );
<ide> }
<ide> };
<del>
<ide> ```
<ide>
<ide> </div>
<ide> class MyComponent extends React.Component {
<ide> <div id='jsx-teardown'>
<ide>
<ide> ```js
<del>console.info('after the test');
<add>ReactDOM.render(<MyComponent />, document.getElementById('root'))
<ide> ```
<ide>
<ide> </div>
<ide> console.info('after the test');
<ide> ## Solution
<ide> <section id='solution'>
<ide>
<add>
<ide> ```js
<del>// solution required
<add>class MyComponent extends React.Component {
<add> constructor(props) {
<add> super(props);
<add> this.state = {
<add> activeUsers: null
<add> };
<add> }
<add> componentDidMount() {
<add> setTimeout( () => {
<add> this.setState({
<add> activeUsers: 1273
<add> });
<add> }, 2500);
<add> }
<add> render() {
<add> return (
<add> <div>
<add> <h1>Active Users: {this.state.activeUsers}</h1>
<add> </div>
<add> );
<add> }
<add>};
<ide> ```
<ide>
<del>/section>
<add></section>
<ide><path>curriculum/challenges/chinese/03-front-end-libraries/react/use-the-lifecycle-method-componentwillmount.chinese.md
<ide> id: 5a24c314108439a4d403617c
<ide> title: Use the Lifecycle Method componentWillMount
<ide> challengeType: 6
<ide> isRequired: false
<del>videoUrl: ''
<del>localeTitle: 使用生命周期方法componentWillMount
<add>forumTopicId: 301423
<add>localeTitle: 使用生命周期方法:componentWillMount
<ide> ---
<ide>
<ide> ## Description
<del><section id="description"> React组件有几种特殊方法,可以在组件生命周期的特定点执行操作。这些称为生命周期方法或生命周期钩子,允许您在特定时间点捕获组件。这可以在渲染之前,更新之前,接收道具之前,卸载之前等等。以下是一些主要生命周期方法的列表: <code>componentWillMount()</code> <code>componentDidMount()</code> <code>componentWillReceiveProps()</code> <code>shouldComponentUpdate()</code> <code>componentWillUpdate()</code> <code>componentDidUpdate()</code> <code>componentWillUnmount()</code>接下来的几节课将介绍这些生命周期方法的一些基本用例。 </section>
<add>
<add><section id='description'>
<add>
<add>React 组件有几种特殊方法,可以在组件生命周期的特定点执行操作。这些称为生命周期方法或生命周期钩子,允许你在特定时间点捕获组件。这可以在渲染之前、更新之前、接收 props 之前、卸载之前等等。以下是一些主要生命周期方法的列表:
<add><code>componentWillMount()</code>
<add><code>componentDidMount()</code>
<add><code>shouldComponentUpdate()</code>
<add><code>componentDidUpdate()</code>
<add><code>componentWillUnmount()</code>
<add>接下来的几节课将讲述这些生命周期方法的一些基本用例。
<add>
<add><strong>注意:</strong> `componentWillMount` 生命周期方法会在版本 16.X 废弃在版本 17 移除 [(Source)](https://reactjs.org/blog/2018/03/27/update-on-async-rendering.html)
<add></section>
<ide>
<ide> ## Instructions
<del><section id="instructions">在将组件装载到DOM时,在<code>render()</code>方法之前调用<code>componentWillMount()</code>方法。在<code>componentWillMount()</code>中将某些内容记录到控制台 - 您可能希望打开浏览器控制台以查看输出。 </section>
<add><section id='instructions'>
<add>
<add>当组件被挂载到 DOM 时,<code>componentWillMount()</code>方法在<code>render()</code>方法之前被调用。在<code>componentWillMount()</code>中将一些内容记录到控制台--你需要打开浏览器控制台以查看输出。
<add></section>
<ide>
<ide> ## Tests
<ide> <section id='tests'>
<ide>
<ide> ```yml
<ide> tests:
<del> - text: <code>MyComponent</code>应该呈现<code>div</code>元素。
<add> - text: <code>MyComponent</code>应该渲染一个<code>div</code>元素。
<ide> testString: assert((function() { const mockedComponent = Enzyme.mount(React.createElement(MyComponent)); return mockedComponent.find('div').length === 1; })());
<del> - text: 应该在<code>componentWillMount</code>调用<code>console.log</code> 。
<add> - text: 应该在<code>componentWillMount</code>中调用<code>console.log</code>。
<ide> testString: assert((function() { const lifecycle = React.createElement(MyComponent).type.prototype.componentWillMount.toString().replace(/ /g,''); return lifecycle.includes('console.log('); })());
<ide>
<ide> ```
<ide> class MyComponent extends React.Component {
<ide> return <div />
<ide> }
<ide> };
<del>
<ide> ```
<ide>
<ide> </div>
<ide> class MyComponent extends React.Component {
<ide> <div id='jsx-teardown'>
<ide>
<ide> ```js
<del>console.info('after the test');
<add>ReactDOM.render(<MyComponent />, document.getElementById('root'))
<ide> ```
<ide>
<ide> </div>
<ide> console.info('after the test');
<ide> ## Solution
<ide> <section id='solution'>
<ide>
<add>
<ide> ```js
<del>// solution required
<add>class MyComponent extends React.Component {
<add> constructor(props) {
<add> super(props);
<add> }
<add> componentWillMount() {
<add> // change code below this line
<add> console.log('Component is mounting...');
<add> // change code above this line
<add> }
<add> render() {
<add> return <div />
<add> }
<add>};
<ide> ```
<ide>
<del>/section>
<add></section>
<ide><path>curriculum/challenges/chinese/03-front-end-libraries/react/write-a-react-component-from-scratch.chinese.md
<ide> id: 5a24c314108439a4d4036168
<ide> title: Write a React Component from Scratch
<ide> challengeType: 6
<ide> isRequired: false
<del>videoUrl: ''
<del>localeTitle: 从Scratch写一个React组件
<add>forumTopicId: 301424
<add>localeTitle: 从零开始写一个 React 组件
<ide> ---
<ide>
<ide> ## Description
<del><section id="description">现在您已经学习了JSX和React组件的基础知识,现在是时候自己编写一个组件了。 React组件是React应用程序的核心构建块,因此非常熟悉编写它们非常重要。请记住,典型的React组件是扩展<code>React.Component</code>的ES6 <code>class</code> 。它有一个返回HTML(来自JSX)或<code>null</code>的render方法。这是React组件的基本形式。一旦你理解了这一点,你就会准备开始构建更复杂的React项目。 </section>
<add><section id='description'>
<add>现在你已经了解了 JSX 和 React 组件的基础知识,现在是时候自己编写一个组件了。React 组件是 React 应用程序的核心组成部分,因此熟练编写它们是非常重要的。记住,典型的 React 组件是 ES6<code>class</code>,它扩展了<code>React.Component</code>。它有一个返回 HTML(从 JSX 返回)或<code>null</code>的渲染方法,这是 React 组件的基本形式。一旦你深刻地理解了这一点,你就可以开始构建更复杂的 React 项目了。
<add></section>
<ide>
<ide> ## Instructions
<del><section id="instructions">定义一个扩展<code>React.Component</code>的类<code>MyComponent</code> 。它的render方法应该返回一个<code>div</code> ,其中包含一个带有文本的<code>h1</code>标签: <code>My First React Component!</code>在里面。准确使用此文本,案例和标点符号很重要。确保也调用组件的构造函数。使用<code>ReactDOM.render()</code>将此组件呈现给DOM。有一个<code>div</code> , <code>id='challenge-node'</code>可供您使用。 </section>
<add><section id='instructions'>
<add>定义一个<code>MyComponent</code>类,它是<code>React.Component</code>的扩展。它的渲染方法应该返回一个<code>div</code>,其中包含一个<code>h1</code>标签,标签文本为:<code>My First React Component!</code>。请确保文本内容、大小写和标点符号正确,以及调用了组件的构造函数。
<add>使用<code>ReactDOM.render()</code>把该组件渲染到 DOM 中。有一个<code>id='challenge-node'</code>的<code>div</code>可供你使用。
<add></section>
<ide>
<ide> ## Tests
<ide> <section id='tests'>
<ide> localeTitle: 从Scratch写一个React组件
<ide> tests:
<ide> - text: 应该有一个名为<code>MyComponent</code>的React组件。
<ide> testString: getUserInput => assert(getUserInput('index').replace(/\s/g, '').includes('classMyComponentextendsReact.Component{'));
<del> - text: <code>MyComponent</code>应该包含带有文本<code>My First React Component!</code>的<code>h1</code>标签<code>My First React Component!</code>案例和标点符号问题。
<add> - text: <code>MyComponent</code>应该包含一个<code>h1</code>标签,标签的文本为<code>My First React Component!</code>,区分大小写并有标点符号。
<ide> testString: assert((function() { const mockedComponent = Enzyme.mount(React.createElement(MyComponent)); return mockedComponent.find('h1').text() === 'My First React Component!'; })());
<del> - text: <code>MyComponent</code>应该呈现给DOM。
<add> - text: <code>MyComponent</code>应该渲染到 DOM。
<ide> testString: assert(document.getElementById('challenge-node').childNodes.length === 1);
<ide>
<ide> ```
<ide> tests:
<ide> ## Solution
<ide> <section id='solution'>
<ide>
<add>
<ide> ```js
<del>// solution required
<add>// change code below this line
<add>class MyComponent extends React.Component {
<add> constructor(props) {
<add> super(props);
<add> }
<add> render() {
<add> return (
<add> <div>
<add> <h1>My First React Component!</h1>
<add> </div>
<add> );
<add> }
<add>};
<add>
<add>ReactDOM.render(<MyComponent />, document.getElementById('challenge-node'));
<ide> ```
<ide>
<del>/section>
<add></section>
<ide><path>curriculum/challenges/chinese/03-front-end-libraries/react/write-a-simple-counter.chinese.md
<ide> id: 5a24c314108439a4d4036177
<ide> title: Write a Simple Counter
<ide> challengeType: 6
<ide> isRequired: false
<del>videoUrl: ''
<add>forumTopicId: 301425
<ide> localeTitle: 写一个简单的计数器
<ide> ---
<ide>
<ide> ## Description
<del><section id="description">您可以通过结合到目前为止所涵盖的概念来设计更复杂的有状态组件。这些包括初始化<code>state</code> ,编写设置<code>state</code>方法,以及分配单击处理程序以触发这些方法。 </section>
<add><section id='description'>
<add>你可以结合目前为止所涵盖的概念来设计更复杂的有状态组件。这包括初始化<code>state</code>,编写设置<code>state</code>的方法,以及指定单击处理程序来触发这些方法。
<add></section>
<ide>
<ide> ## Instructions
<del><section id="instructions">该<code>Counter</code>组件跟踪一个的<code>count</code>的价值<code>state</code> 。有两个按钮调用方法<code>increment()</code>和<code>decrement()</code> 。编写这些方法,以便在单击相应按钮时计数器值递增或递减1。此外,创建一个<code>reset()</code>方法,以便在单击重置按钮时,计数设置为0. <strong>注意:</strong>确保不要修改按钮的<code>classNames</code> 。另外,请记住在构造函数中为新创建的方法添加必要的绑定。 </section>
<add><section id='instructions'>
<add><code>Counter</code>组件跟踪<code>state</code>中的<code>count</code>值。有两个按钮分别调用<code>increment()</code>和<code>decrement()</code>方法。编写这些方法,使计数器值在单击相应按钮时增加或减少 1。另外,创建一个<code>reset()</code>方法,当单击 reset 按钮时,把计数设置为 0。
<add><strong>注意:</strong> 确保你没有修改按钮的<code>classNames</code>。另外,请记住在构造函数中为新创建的方法添加必要的绑定。
<add></section>
<ide>
<ide> ## Tests
<ide> <section id='tests'>
<ide>
<ide> ```yml
<ide> tests:
<del> - text: <code>Counter</code>应返回一个<code>div</code>元素,其中包含三个按钮,文本内容按此顺序<code>Increment!</code> , <code>Decrement!</code> , <code>Reset</code> 。
<add> - text: <code>Counter</code>应该返回一个<code>div</code>元素,它包含三个按钮,按钮内容依次是<code>Increment!</code>、<code>Decrement!</code>、<code>Reset</code>。
<ide> testString: assert((() => { const mockedComponent = Enzyme.mount(React.createElement(Counter)); return (mockedComponent.find('.inc').text() === 'Increment!' && mockedComponent.find('.dec').text() === 'Decrement!' && mockedComponent.find('.reset').text() === 'Reset'); })());
<del> - text: <code>Counter</code>的状态应该在<code>count</code>属性设置为<code>0</code>的情况下初始化。
<add> - text: <code>Counter</code>应该使用设置为<code>0</code>的<code>count</code>属性初始化 state。
<ide> testString: 'const mockedComponent = Enzyme.mount(React.createElement(Counter)); assert(mockedComponent.find("h1").text() === "Current Count: 0")'
<del> - text: 单击增量按钮应将计数增加<code>1</code> 。
<add> - text: 单击 increment 按钮应将计数增加<code>1</code>。
<ide> testString: 'const mockedComponent = Enzyme.mount(React.createElement(Counter)); mockedComponent.find(".inc").simulate("click"); assert(mockedComponent.find("h1").text() === "Current Count: 1")'
<del> - text: 单击减量按钮应将计数减<code>1</code> 。
<add> - text: 单击 decrement 按钮应将计数减少<code>1</code>。
<ide> testString: 'const mockedComponent = Enzyme.mount(React.createElement(Counter)); mockedComponent.find(".dec").simulate("click"); assert(mockedComponent.find("h1").text() === "Current Count: -1")'
<del> - text: 单击重置按钮应将计数重置为<code>0</code> 。
<add> - text: 单击 reset 按钮应将计数重置为<code>0</code>。
<ide> testString: 'const mockedComponent = Enzyme.mount(React.createElement(Counter)); mockedComponent.setState({ count: 5 }); const currentCountElement = mockedComponent.find("h1"); assert(currentCountElement.text() === "Current Count: 5"); mockedComponent.find(".reset").simulate("click"); assert(currentCountElement.text() === "Current Count: 0");'
<ide>
<ide> ```
<ide> class Counter extends React.Component {
<ide> );
<ide> }
<ide> };
<del>
<ide> ```
<ide>
<ide> </div>
<ide> class Counter extends React.Component {
<ide> <div id='jsx-teardown'>
<ide>
<ide> ```js
<del>console.info('after the test');
<add>ReactDOM.render(<Counter />, document.getElementById('root'))
<ide> ```
<ide>
<ide> </div>
<ide> console.info('after the test');
<ide> ## Solution
<ide> <section id='solution'>
<ide>
<add>
<ide> ```js
<del>// solution required
<add>class Counter extends React.Component {
<add> constructor(props) {
<add> super(props);
<add> this.state = {
<add> count: 0
<add> };
<add> this.increment = this.increment.bind(this);
<add> this.decrement = this.decrement.bind(this);
<add> this.reset = this.reset.bind(this);
<add> }
<add> reset() {
<add> this.setState({
<add> count: 0
<add> });
<add> }
<add> increment() {
<add> this.setState(state => ({
<add> count: state.count + 1
<add> }));
<add> }
<add> decrement() {
<add> this.setState(state => ({
<add> count: state.count - 1
<add> }));
<add> }
<add> render() {
<add> return (
<add> <div>
<add> <button className='inc' onClick={this.increment}>Increment!</button>
<add> <button className='dec' onClick={this.decrement}>Decrement!</button>
<add> <button className='reset' onClick={this.reset}>Reset</button>
<add> <h1>Current Count: {this.state.count}</h1>
<add> </div>
<add> );
<add> }
<add>};
<ide> ```
<ide>
<del>/section>
<add></section> | 47 |
Mixed | Python | update output of debug config command | 9b4cf7b0b6b614ff044ae610217a3a73dcf35851 | <ide><path>spacy/cli/_util.py
<ide> def show_validation_error(
<ide> "fill-config' command to fill in all the defaults, if possible:",
<ide> spaced=True,
<ide> )
<del> print(f"{COMMAND} init fill-config {config_path} --base {config_path}\n")
<add> print(f"{COMMAND} init fill-config {config_path} {config_path} \n")
<ide> sys.exit(1)
<ide> except InterpolationError as e:
<ide> msg.fail("Config validation error", e, exits=1)
<ide><path>website/docs/api/cli.md
<ide> $ python -m spacy debug config [config_path] [--code] [--show-functions] [--show
<ide>
<ide> ```
<ide> ✘ Config validation error
<add>dropout field required
<add>optimizer field required
<add>optimize extra fields not permitted
<ide>
<del>training -> dropout field required
<del>training -> optimizer field required
<del>training -> optimize extra fields not permitted
<del>
<del>{'vectors': 'en_vectors_web_lg', 'seed': 0, 'accumulate_gradient': 1, 'init_tok2vec': None, 'raw_text': None, 'patience': 1600, 'max_epochs': 0, 'max_steps': 20000, 'eval_frequency': 200, 'frozen_components': [], 'optimize': None, 'batcher': {'@batchers': 'spacy.batch_by_words.v1', 'discard_oversize': False, 'tolerance': 0.2, 'get_length': None, 'size': {'@schedules': 'compounding.v1', 'start': 100, 'stop': 1000, 'compound': 1.001, 't': 0.0}}, 'corpus': {'train': {'@readers': 'spacy.Corpus.v1', 'path': '', 'max_length': 0, 'gold_preproc': False, 'limit': 0}, 'dev': {'@readers': 'spacy.Corpus.v1', 'path': '', 'max_length': 0, 'gold_preproc': False, 'limit': 0}} 'score_weights': {'tag_acc': 0.5, 'dep_uas': 0.25, 'dep_las': 0.25, 'sents_f': 0.0}}
<add>{'seed': 0, 'accumulate_gradient': 1, 'dev_corpus': 'corpora.dev', 'train_corpus': 'corpora.train', 'gpu_allocator': None, 'patience': 1600, 'max_epochs': 0, 'max_steps': 20000, 'eval_frequency': 200, 'frozen_components': [], 'optimize': None, 'before_to_disk': None, 'batcher': {'@batchers': 'spacy.batch_by_words.v1', 'discard_oversize': False, 'tolerance': 0.2, 'get_length': None, 'size': {'@schedules': 'compounding.v1', 'start': 100, 'stop': 1000, 'compound': 1.001, 't': 0.0}}, 'logger': {'@loggers': 'spacy.ConsoleLogger.v1', 'progress_bar': False}, 'score_weights': {'tag_acc': 0.5, 'dep_uas': 0.25, 'dep_las': 0.25, 'sents_f': 0.0}}
<ide>
<ide> If your config contains missing values, you can run the 'init fill-config'
<ide> command to fill in all the defaults, if possible:
<ide>
<del>python -m spacy init fill-config tmp/starter-config_invalid.cfg --base tmp/starter-config_invalid.cfg
<add>python -m spacy init fill-config tmp/starter-config_invalid.cfg tmp/starter-config_invalid.cfg
<ide> ```
<ide>
<ide> </Accordion> | 2 |
Javascript | Javascript | improve reliability of the test server | b0ff49e4562ce1546dbd50c05d0ddafef5f076f5 | <ide><path>test/webserver.js
<ide> WebServer.prototype = {
<ide> this.server = null;
<ide> },
<ide> _handler: function (req, res) {
<del> var url = req.url;
<add> var url = req.url.replace(/\/\//g, '/');
<ide> var urlParts = /([^?]*)((?:\?(.*))?)/.exec(url);
<ide> var pathPart = decodeURI(urlParts[1]), queryPart = urlParts[3];
<ide> var verbose = this.verbose;
<ide> WebServer.prototype = {
<ide> serveRequestedFile(filePath);
<ide> }
<ide>
<add> function escapeHTML(untrusted) {
<add> // Escape untrusted input so that it can safely be used in a HTML response
<add> // in HTML and in HTML attributes.
<add> return untrusted
<add> .replace(/&/g, '&')
<add> .replace(/</g, '<')
<add> .replace(/>/g, '>')
<add> .replace(/"/g, '"')
<add> .replace(/'/g, ''');
<add> }
<add>
<ide> function serveDirectoryIndex(dir) {
<ide> res.setHeader('Content-Type', 'text/html');
<ide> res.writeHead(200);
<ide> WebServer.prototype = {
<ide> res.write('<a href=\"..\">..</a><br>\n');
<ide> }
<ide> files.forEach(function (file) {
<del> var stat = fs.statSync(path.join(dir, file));
<add> var stat;
<ide> var item = pathPart + file;
<del> if (stat.isDirectory()) {
<del> res.write('<a href=\"' + encodeURI(item) + '\">' +
<del> file + '</a><br>\n');
<del> return;
<add> var href = '';
<add> var label = '';
<add> var extraAttributes = '';
<add> try {
<add> stat = fs.statSync(path.join(dir, file));
<add> } catch (e) {
<add> href = encodeURI(item);
<add> label = file + ' (' + e + ')';
<add> extraAttributes = ' style="color:red"';
<add> }
<add> if (stat) {
<add> if (stat.isDirectory()) {
<add> href = encodeURI(item);
<add> label = file;
<add> } else if (path.extname(file).toLowerCase() === '.pdf') {
<add> href = '/web/viewer.html?file=' + encodeURIComponent(item);
<add> label = file;
<add> extraAttributes = ' target="pdf"';
<add> } else if (all) {
<add> href = encodeURI(item);
<add> label = file;
<add> }
<ide> }
<del> var ext = path.extname(file).toLowerCase();
<del> if (ext === '.pdf') {
<del> res.write('<a href=\"/web/viewer.html?file=' +
<del> encodeURI(item) + '\" target=pdf>' +
<del> file + '</a><br>\n');
<del> } else if (all) {
<del> res.write('<a href=\"' + encodeURI(item) + '\">' +
<del> file + '</a><br>\n');
<add> if (label) {
<add> res.write('<a href=\"' + escapeHTML(href) + '\"' +
<add> extraAttributes + '>' + escapeHTML(label) + '</a><br>\n');
<ide> }
<ide> });
<ide> if (files.length === 0) { | 1 |
Ruby | Ruby | adapt code to use array of licenses | b91587d1716636b345f13e6829e04ab3a684d5ed | <ide><path>Library/Homebrew/dev-cmd/audit.rb
<ide> def audit_formula_name
<ide>
<ide> def audit_license
<ide> if formula.license.present?
<del> if @spdx_data["licenses"].any? { |lic| lic["licenseId"] == formula.license }
<add> if formula.license.any? { |lic| @spdx_data["licenses"].any? { |standard_lic| standard_lic["licenseId"] == lic } }
<ide> return unless @online
<ide>
<ide> user, repo = get_repo_data(%r{https?://github\.com/([^/]+)/([^/]+)/?.*}) if @new_formula
<ide> return if user.blank?
<ide>
<ide> github_license = GitHub.get_repo_license(user, repo)
<del> return if github_license && [formula.license, "NOASSERTION"].include?(github_license)
<add> return if github_license && (formula.license + ["NOASSERTION"]).include?(github_license)
<ide>
<del> problem "License mismatch - GitHub license is: #{github_license}, "\
<add> problem "License mismatch - GitHub license is: #{Array(github_license)}, "\
<ide> "but Formulae license states: #{formula.license}."
<ide> else
<ide> problem "#{formula.license} is not a standard SPDX license." | 1 |
Python | Python | add error handling for slack api | 6ec028eca2a76b1888d6c5af996f905c1dee1e7a | <ide><path>airflow/operators/slack_operator.py
<ide> from slackclient import SlackClient
<ide> from airflow.models import BaseOperator
<del>from airflow.utils import apply_defaults
<add>from airflow.utils import apply_defaults, AirflowException
<ide> import json
<add>import logging
<ide>
<ide>
<ide> class SlackAPIOperator(BaseOperator):
<ide> def execute(self, **kwargs):
<ide> if not self.api_params:
<ide> self.construct_api_call_params()
<ide> sc = SlackClient(self.token)
<del> sc.api_call(self.method, **self.api_params)
<add> rc = json.loads(sc.api_call(self.method, **self.api_params).decode('utf-8'))
<add> if not rc['ok']:
<add> raise AirflowException("Slack API call failed: ({})".format(rc['error']))
<add> logging.error("Slack API call failed ({})".format(rc['error']))
<ide>
<ide>
<ide> class SlackAPIPostOperator(SlackAPIOperator): | 1 |
Javascript | Javascript | add share to website | 1430053b9f8d2c1a9995c5ef9087d321dc3233b5 | <ide><path>website/server/extractDocs.js
<ide> const apis = [
<ide> '../Libraries/Utilities/PixelRatio.js',
<ide> '../Libraries/PushNotificationIOS/PushNotificationIOS.js',
<ide> '../Libraries/Settings/Settings.ios.js',
<add> '../Libraries/Share/Share.js',
<ide> '../Libraries/Components/StatusBar/StatusBarIOS.ios.js',
<ide> '../Libraries/StyleSheet/StyleSheet.js',
<ide> '../Libraries/Performance/Systrace.js', | 1 |
Python | Python | expand the docstring as suggested in review | 0e2503bb6312e089b918c05ea667e5a591910903 | <ide><path>numpy/polynomial/_polybase.py
<ide> def fit(cls, x, y, deg, domain=None, rcond=None, full=False, w=None,
<ide> x : array_like, shape (M,)
<ide> x-coordinates of the M sample points ``(x[i], y[i])``.
<ide> y : array_like, shape (M,)
<del> y-coordinates of the sample points.
<add> y-coordinates of the sample points ``(x[i], y[i])``.
<ide> deg : int or 1-D array_like
<ide> Degree(s) of the fitting polynomials. If `deg` is a single integer
<ide> all terms up to and including the `deg`'th term are included in the | 1 |
Javascript | Javascript | fix jshint issue with _rendertobuffer refactor | 0b7e83b9f0eabe082837b63b6307c8e1096126be | <ide><path>packages/ember-views/lib/views/view.js
<ide> var View = CoreView.extend({
<ide>
<ide> _renderToBuffer: function(buffer) {
<ide> this.lengthBeforeRender = this._childViews.length;
<del> var buffer = this._super(buffer);
<add> buffer = this._super(buffer);
<ide> this.lengthAfterRender = this._childViews.length;
<ide>
<ide> return buffer; | 1 |
Python | Python | remove some relative imports from django | 87ffc6a6c2475fcbf61b4f27b49152901ca041cc | <ide><path>django/forms/formsets.py
<del>from forms import Form
<add>from __future__ import absolute_import
<add>
<ide> from django.core.exceptions import ValidationError
<add>from django.forms import Form
<add>from django.forms.fields import IntegerField, BooleanField
<add>from django.forms.util import ErrorList
<add>from django.forms.widgets import Media, HiddenInput
<ide> from django.utils.encoding import StrAndUnicode
<ide> from django.utils.safestring import mark_safe
<ide> from django.utils.translation import ugettext as _
<del>from fields import IntegerField, BooleanField
<del>from widgets import Media, HiddenInput
<del>from util import ErrorList
<add>
<ide>
<ide> __all__ = ('BaseFormSet', 'all_valid')
<ide> | 1 |
Go | Go | update iptable.exists api in integration-cli | dfc2d770e47f36ee24ff9b9c3b65683196355ddd | <ide><path>integration-cli/docker_cli_daemon_test.go
<ide> func (s *DockerDaemonSuite) TestDaemonLinksIpTablesRulesWhenLinkAndUnlink(c *tes
<ide>
<ide> sourceRule := []string{"-i", bridgeName, "-o", bridgeName, "-p", "tcp", "-s", childIP, "--sport", "80", "-d", parentIP, "-j", "ACCEPT"}
<ide> destinationRule := []string{"-i", bridgeName, "-o", bridgeName, "-p", "tcp", "-s", parentIP, "--dport", "80", "-d", childIP, "-j", "ACCEPT"}
<del> if !iptables.Exists("filter", "DOCKER", sourceRule...) || !iptables.Exists("filter", "DOCKER", destinationRule...) {
<add> iptable := iptables.GetIptable(iptables.IPv4)
<add> if !iptable.Exists("filter", "DOCKER", sourceRule...) || !iptable.Exists("filter", "DOCKER", destinationRule...) {
<ide> c.Fatal("Iptables rules not found")
<ide> }
<ide>
<ide> s.d.Cmd("rm", "--link", "parent/http")
<del> if iptables.Exists("filter", "DOCKER", sourceRule...) || iptables.Exists("filter", "DOCKER", destinationRule...) {
<add> if iptable.Exists("filter", "DOCKER", sourceRule...) || iptable.Exists("filter", "DOCKER", destinationRule...) {
<ide> c.Fatal("Iptables rules should be removed when unlink")
<ide> }
<ide> | 1 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.