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
|
---|---|---|---|---|---|
PHP | PHP | fix broken test | 804d77ee7e5798a52fc08a7c5fe6dbb2ed7082a5 | <ide><path>tests/TestCase/Http/ClientTest.php
<ide> public function testCreateFromUrlOnlySetSchemePortHostBasePath(): void
<ide> $client = Client::createFromUrl('http://example.co:80/some/uri/?foo=bar');
<ide> $config = $client->getConfig();
<ide> $expected = [
<add> 'auth' => null,
<ide> 'adapter' => null,
<ide> 'host' => 'example.co',
<ide> 'port' => 80, | 1 |
Ruby | Ruby | pass format to the digestor | a3a98606f30e5d2b08419e0dcd1962fc52974c29 | <ide><path>actionmailer/test/caching_test.rb
<ide> def test_fragment_caching
<ide>
<ide> assert_match expected_body, email.body.encoded
<ide> assert_match expected_body,
<del> @store.read("views/caching_mailer/fragment_cache:#{template_digest("caching_mailer/fragment_cache")}/caching")
<add> @store.read("views/caching_mailer/fragment_cache:#{template_digest("caching_mailer/fragment_cache", "html")}/caching")
<ide> end
<ide>
<ide> def test_fragment_caching_in_partials
<ide> def test_fragment_caching_in_partials
<ide> assert_match(expected_body, email.body.encoded)
<ide>
<ide> assert_match(expected_body,
<del> @store.read("views/caching_mailer/_partial:#{template_digest("caching_mailer/_partial")}/caching"))
<add> @store.read("views/caching_mailer/_partial:#{template_digest("caching_mailer/_partial", "html")}/caching"))
<ide> end
<ide>
<ide> def test_skip_fragment_cache_digesting
<ide> def test_fragment_cache_instrumentation
<ide> end
<ide>
<ide> assert_equal "caching_mailer", payload[:mailer]
<del> assert_equal [ :views, "caching_mailer/fragment_cache:#{template_digest("caching_mailer/fragment_cache")}", :caching ], payload[:key]
<add> assert_equal [ :views, "caching_mailer/fragment_cache:#{template_digest("caching_mailer/fragment_cache", "html")}", :caching ], payload[:key]
<ide> ensure
<ide> @mailer.enable_fragment_cache_logging = true
<ide> end
<ide>
<ide> private
<ide>
<del> def template_digest(name)
<del> ActionView::Digestor.digest(name: name, finder: @mailer.lookup_context)
<add> def template_digest(name, format)
<add> ActionView::Digestor.digest(name: name, format: format, finder: @mailer.lookup_context)
<ide> end
<ide> end
<ide> | 1 |
Text | Text | add support doc | 122d0f8363ecc3588dc6a6187fd5cbb6a7e47f94 | <ide><path>SUPPORT.md
<add># Atom Support
<add>
<add>If you're looking for support for Atom there are a lot of options, check out:
<add>
<add>* User Documentation — [The Atom Flight Manual](http://flight-manual.atom.io)
<add>* Developer Documentation — [Atom API Documentation](https://atom.io/docs/api/latest)
<add>* FAQ — [The Atom FAQ on Discuss](https://discuss.atom.io/c/faq)
<add>* Message Board — [Discuss, the official Atom and Electron message board](https://discuss.atom.io)
<add>* Chat — [Join the Atom Slack team](http://atom-slack.herokuapp.com/)
<add>
<add>On Discuss and in the Atom Slack team, there are a bunch of helpful community members that should be willing to point you in the right direction. | 1 |
Ruby | Ruby | improve insufficient test for `safe_join` | b14ac2f7da5cbae0b6989c50f44d37a8304d86c1 | <ide><path>actionview/test/template/output_safety_helper_test.rb
<ide> def setup
<ide> end
<ide>
<ide> test "safe_join should return the safe string separated by $, when second argument is not passed" do
<del> joined = safe_join(["a", "b"])
<del> assert_equal "a#{$,}b", joined
<add> default_delimeter = $,
<add>
<add> begin
<add> $, = nil
<add> joined = safe_join(["a", "b"])
<add> assert_equal "ab", joined
<add>
<add> $, = "|"
<add> joined = safe_join(["a", "b"])
<add> assert_equal "a|b", joined
<add> ensure
<add> $, = default_delimeter
<add> end
<ide> end
<ide>
<ide> test "to_sentence should escape non-html_safe values" do | 1 |
Python | Python | move "private" method to the end, add a docstrings | 850c992029ccfaab1131f069e5f3e7a6ff0cb4eb | <ide><path>libcloud/compute/drivers/ec2.py
<ide> def _to_snapshot(self, element):
<ide> 'description': description,
<ide> 'state': state})
<ide>
<del> def _get_common_security_group_params(self, group_id, protocol,
<del> from_port, to_port, cidr_ips,
<del> group_pairs):
<del>
<del> params = {'GroupId': id,
<del> 'IpPermissions.1.IpProtocol': protocol,
<del> 'IpPermissions.1.FromPort': from_port,
<del> 'IpPermissions.1.ToPort': to_port}
<del>
<del> if cidr_ips is not None:
<del> ip_ranges = {}
<del> for index, cidr_ip in enumerate(cidr_ips, 1):
<del> ip_ranges['IpPermissions.1.IpRanges.%s.CidrIp'
<del> % (index)] = cidr_ip
<del>
<del> params.update(ip_ranges)
<del>
<del> if group_pairs is not None:
<del> user_groups = {}
<del> for index, group_pair in enumerate(group_pairs, 1):
<del> if 'group_id' in group_pair.keys():
<del> user_groups['IpPermissions.1.Groups.%s.GroupId'
<del> % (index)] = group_pair['group_id']
<del>
<del> if 'group_name' in group_pair.keys():
<del> user_groups['IpPermissions.1.Groups.%s.GroupName'
<del> % (index)] = group_pair['group_name']
<del>
<del> if 'user_id' in group_pair.keys():
<del> user_groups['IpPermissions.1.Groups.%s.UserId'
<del> % (index)] = group_pair['user_id']
<del>
<del> params.update(user_groups)
<del>
<del> return params
<del>
<ide> def list_nodes(self, ex_node_ids=None):
<ide> """
<ide> List all nodes
<ide> def destroy_node(self, node):
<ide> res = self.connection.request(self.path, params=params).object
<ide> return self._get_terminate_boolean(res)
<ide>
<add> def _get_common_security_group_params(self, group_id, protocol,
<add> from_port, to_port, cidr_ips,
<add> group_pairs):
<add> """
<add> Return a dictionary with common query parameters which are used when
<add> operating on security groups.
<add>
<add> :rtype: ``dict``
<add> """
<add> params = {'GroupId': id,
<add> 'IpPermissions.1.IpProtocol': protocol,
<add> 'IpPermissions.1.FromPort': from_port,
<add> 'IpPermissions.1.ToPort': to_port}
<add>
<add> if cidr_ips is not None:
<add> ip_ranges = {}
<add> for index, cidr_ip in enumerate(cidr_ips, 1):
<add> ip_ranges['IpPermissions.1.IpRanges.%s.CidrIp'
<add> % (index)] = cidr_ip
<add>
<add> params.update(ip_ranges)
<add>
<add> if group_pairs is not None:
<add> user_groups = {}
<add> for index, group_pair in enumerate(group_pairs, 1):
<add> if 'group_id' in group_pair.keys():
<add> user_groups['IpPermissions.1.Groups.%s.GroupId'
<add> % (index)] = group_pair['group_id']
<add>
<add> if 'group_name' in group_pair.keys():
<add> user_groups['IpPermissions.1.Groups.%s.GroupName'
<add> % (index)] = group_pair['group_name']
<add>
<add> if 'user_id' in group_pair.keys():
<add> user_groups['IpPermissions.1.Groups.%s.UserId'
<add> % (index)] = group_pair['user_id']
<add>
<add> params.update(user_groups)
<add>
<add> return params
<add>
<ide>
<ide> class EC2NodeDriver(BaseEC2NodeDriver):
<ide> """ | 1 |
Ruby | Ruby | eliminate boolean argument to version.new | 4bbefc12e36bb3cbe661983f7533110a0f85758e | <ide><path>Library/Homebrew/version.rb
<ide> def <=>(other)
<ide> StringToken::PATTERN
<ide> )
<ide>
<add> class FromURL < Version
<add> def detected_from_url?
<add> true
<add> end
<add> end
<add>
<ide> def self.detect(url, specs={})
<ide> if specs.has_key?(:tag)
<del> new(specs[:tag][/((?:\d+\.)*\d+)/, 1], true)
<add> FromURL.new(specs[:tag][/((?:\d+\.)*\d+)/, 1])
<ide> else
<del> parse(url)
<add> FromURL.parse(url)
<ide> end
<ide> end
<ide>
<del> def initialize(val, detected=false)
<add> def initialize(val)
<ide> if val.respond_to?(:to_str)
<ide> @version = val.to_str
<ide> else
<ide> raise TypeError, "Version value must be a string"
<ide> end
<del>
<del> @detected_from_url = detected
<ide> end
<ide>
<ide> def detected_from_url?
<del> @detected_from_url
<add> false
<ide> end
<ide>
<ide> def head?
<ide> def tokenize
<ide>
<ide> def self.parse spec
<ide> version = _parse(spec)
<del> new(version, true) unless version.nil?
<add> new(version) unless version.nil?
<ide> end
<ide>
<ide> def self._parse spec | 1 |
Python | Python | fix documentation for masking layer | 34bce5bac9f434dc501f4cbff37b44680271a337 | <ide><path>keras/layers/core.py
<ide> class Masking(Layer):
<ide> """Masks a sequence by using a mask value to skip timesteps.
<ide>
<del> For each timestep in the input tensor (dimension #1 in the tensor),
<del> if all values in the input tensor at that timestep
<del> are equal to `mask_value`, then the timestep will be masked (skipped)
<del> in all downstream layers (as long as they support masking).
<add> If all features for a given sample timestep are equal to `mask_value`,
<add> then the sample timestep will be masked (skipped) in all downstream layers
<add> (as long as they support masking).
<ide>
<ide> If any downstream layer does not support masking yet receives such
<ide> an input mask, an exception will be raised.
<ide> class Masking(Layer):
<ide>
<ide> Consider a Numpy data array `x` of shape `(samples, timesteps, features)`,
<ide> to be fed to an LSTM layer.
<del> You want to mask timestep #3 and #5 because you lack data for
<del> these timesteps. You can:
<add> You want to mask sample #0 at timestep #3, and sample #2 at timestep #5,
<add> because you lack features for these sample timesteps. You can do:
<ide>
<del> - set `x[:, 3, :] = 0.` and `x[:, 5, :] = 0.`
<add> - set `x[0, 3, :] = 0.` and `x[2, 5, :] = 0.`
<ide> - insert a `Masking` layer with `mask_value=0.` before the LSTM layer:
<ide>
<ide> ```python | 1 |
Javascript | Javascript | add matrix4 unittests | f0151321810eac88a04ec2509dde6a3a72869350 | <ide><path>test/unit/src/math/Matrix4.tests.js
<ide> export default QUnit.module( 'Maths', () => {
<ide> } );
<ide>
<ide> // PUBLIC STUFF
<del> QUnit.todo( "isMatrix4", ( assert ) => {
<add> QUnit.test( "isMatrix4", ( assert ) => {
<ide>
<del> assert.ok( false, "everything's gonna be alright" );
<add> var a = new Matrix4();
<add> assert.ok( a.isMatrix4 === true, "Passed!" );
<add>
<add> var b = new Vector3();
<add> assert.ok( ! b.isMatrix4, "Passed!" );
<ide>
<ide> } );
<ide>
<ide> export default QUnit.module( 'Maths', () => {
<ide>
<ide> } );
<ide>
<del> QUnit.todo( "extractRotation", ( assert ) => {
<del>
<del> assert.ok( false, "everything's gonna be alright" );
<del>
<del> } );
<del>
<ide> QUnit.test( "makeRotationFromEuler/extractRotation", ( assert ) => {
<ide>
<ide> var testValues = [
<ide> export default QUnit.module( 'Maths', () => {
<ide>
<ide> } );
<ide>
<del> QUnit.todo( "multiply", ( assert ) => {
<add> QUnit.test( "multiply", ( assert ) => {
<add>
<add> var lhs = new Matrix4().set( 2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47, 53 );
<add> var rhs = new Matrix4().set( 59, 61, 67, 71, 73, 79, 83, 89, 97, 101, 103, 107, 109, 113, 127, 131 );
<add>
<add> lhs.multiply( rhs );
<ide>
<del> assert.ok( false, "everything's gonna be alright" );
<add> assert.ok( lhs.elements[ 0 ] == 1585 );
<add> assert.ok( lhs.elements[ 1 ] == 5318 );
<add> assert.ok( lhs.elements[ 2 ] == 10514 );
<add> assert.ok( lhs.elements[ 3 ] == 15894 );
<add> assert.ok( lhs.elements[ 4 ] == 1655 );
<add> assert.ok( lhs.elements[ 5 ] == 5562 );
<add> assert.ok( lhs.elements[ 6 ] == 11006 );
<add> assert.ok( lhs.elements[ 7 ] == 16634 );
<add> assert.ok( lhs.elements[ 8 ] == 1787 );
<add> assert.ok( lhs.elements[ 9 ] == 5980 );
<add> assert.ok( lhs.elements[ 10 ] == 11840 );
<add> assert.ok( lhs.elements[ 11 ] == 17888 );
<add> assert.ok( lhs.elements[ 12 ] == 1861 );
<add> assert.ok( lhs.elements[ 13 ] == 6246 );
<add> assert.ok( lhs.elements[ 14 ] == 12378 );
<add> assert.ok( lhs.elements[ 15 ] == 18710 );
<ide>
<ide> } );
<ide>
<del> QUnit.todo( "premultiply", ( assert ) => {
<add> QUnit.test( "premultiply", ( assert ) => {
<add>
<add> var lhs = new Matrix4().set( 2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47, 53 );
<add> var rhs = new Matrix4().set( 59, 61, 67, 71, 73, 79, 83, 89, 97, 101, 103, 107, 109, 113, 127, 131 );
<add>
<add> rhs.premultiply( lhs );
<add>
<add> assert.ok( rhs.elements[ 0 ] == 1585 );
<add> assert.ok( rhs.elements[ 1 ] == 5318 );
<add> assert.ok( rhs.elements[ 2 ] == 10514 );
<add> assert.ok( rhs.elements[ 3 ] == 15894 );
<add> assert.ok( rhs.elements[ 4 ] == 1655 );
<add> assert.ok( rhs.elements[ 5 ] == 5562 );
<add> assert.ok( rhs.elements[ 6 ] == 11006 );
<add> assert.ok( rhs.elements[ 7 ] == 16634 );
<add> assert.ok( rhs.elements[ 8 ] == 1787 );
<add> assert.ok( rhs.elements[ 9 ] == 5980 );
<add> assert.ok( rhs.elements[ 10 ] == 11840 );
<add> assert.ok( rhs.elements[ 11 ] == 17888 );
<add> assert.ok( rhs.elements[ 12 ] == 1861 );
<add> assert.ok( rhs.elements[ 13 ] == 6246 );
<add> assert.ok( rhs.elements[ 14 ] == 12378 );
<add> assert.ok( rhs.elements[ 15 ] == 18710 );
<ide>
<del> assert.ok( false, "everything's gonna be alright" );
<ide>
<ide> } );
<ide>
<ide> export default QUnit.module( 'Maths', () => {
<ide>
<ide> } );
<ide>
<del> QUnit.todo( "setPosition", ( assert ) => {
<add> QUnit.test( "setPosition", ( assert ) => {
<ide>
<del> assert.ok( false, "everything's gonna be alright" );
<add> var a = new Matrix4().set( 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15 );
<add> var b = new Vector3( - 1, - 2, - 3 );
<add> var c = new Matrix4().set( 0, 1, 2, - 1, 4, 5, 6, - 2, 8, 9, 10, - 3, 12, 13, 14, 15 );
<add>
<add> a.setPosition( b );
<add> assert.ok( matrixEquals4( a, c ), "Passed!" );
<ide>
<ide> } );
<ide>
<ide> export default QUnit.module( 'Maths', () => {
<ide>
<ide> } );
<ide>
<del> QUnit.todo( "scale", ( assert ) => {
<add> QUnit.test( "scale", ( assert ) => {
<ide>
<del> assert.ok( false, "everything's gonna be alright" );
<add> var a = new Matrix4().set( 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16 );
<add> var b = new Vector3( 2, 3, 4 );
<add> var c = new Matrix4().set( 2, 6, 12, 4, 10, 18, 28, 8, 18, 30, 44, 12, 26, 42, 60, 16 );
<add>
<add> a.scale( b );
<add> assert.ok( matrixEquals4( a, c ), "Passed!" );
<ide>
<ide> } );
<ide>
<ide> export default QUnit.module( 'Maths', () => {
<ide>
<ide> } );
<ide>
<del> QUnit.todo( "makeTranslation", ( assert ) => {
<add> QUnit.test( "makeTranslation", ( assert ) => {
<add>
<add> var a = new Matrix4();
<add> var b = new Vector3( 2, 3, 4 );
<add> var c = new Matrix4().set( 1, 0, 0, 2, 0, 1, 0, 3, 0, 0, 1, 4, 0, 0, 0, 1 );
<ide>
<del> assert.ok( false, "everything's gonna be alright" );
<add> a.makeTranslation( b );
<add> assert.ok( matrixEquals4( a, c ), "Passed!" );
<ide>
<ide> } );
<ide>
<del> QUnit.todo( "makeRotationX", ( assert ) => {
<add> QUnit.test( "makeRotationX", ( assert ) => {
<add>
<add> var a = new Matrix4();
<add> var b = Math.sqrt( 3 ) / 2;
<add> var c = new Matrix4().set( 1, 0, 0, 0, 0, b, - 0.5, 0, 0, 0.5, b, 0, 0, 0, 0, 1 );
<ide>
<del> assert.ok( false, "everything's gonna be alright" );
<add> a.makeRotationX( Math.PI / 6 );
<add> assert.ok( matrixEquals4( a, c ), "Passed!" );
<ide>
<ide> } );
<ide>
<del> QUnit.todo( "makeRotationY", ( assert ) => {
<add> QUnit.test( "makeRotationY", ( assert ) => {
<add>
<add>
<add> var a = new Matrix4();
<add> var b = Math.sqrt( 3 ) / 2;
<add> var c = new Matrix4().set( b, 0, 0.5, 0, 0, 1, 0, 0, - 0.5, 0, b, 0, 0, 0, 0, 1 );
<ide>
<del> assert.ok( false, "everything's gonna be alright" );
<add> a.makeRotationY( Math.PI / 6 );
<add> assert.ok( matrixEquals4( a, c ), "Passed!" );
<ide>
<ide> } );
<ide>
<del> QUnit.todo( "makeRotationZ", ( assert ) => {
<add> QUnit.test( "makeRotationZ", ( assert ) => {
<add>
<ide>
<del> assert.ok( false, "everything's gonna be alright" );
<add> var a = new Matrix4();
<add> var b = Math.sqrt( 3 ) / 2;
<add> var c = new Matrix4().set( b, - 0.5, 0, 0, 0.5, b, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1 );
<add>
<add> a.makeRotationZ( Math.PI / 6 );
<add> assert.ok( matrixEquals4( a, c ), "Passed!" );
<ide>
<ide> } );
<ide>
<ide> export default QUnit.module( 'Maths', () => {
<ide>
<ide> } );
<ide>
<del> QUnit.todo( "makeScale", ( assert ) => {
<add> QUnit.test( "makeScale", ( assert ) => {
<add>
<add> var a = new Matrix4();
<add> var c = new Matrix4().set( 2, 0, 0, 0, 0, 3, 0, 0, 0, 0, 4, 0, 0, 0, 0, 1 );
<ide>
<del> assert.ok( false, "everything's gonna be alright" );
<add> a.makeScale( 2, 3, 4 );
<add> assert.ok( matrixEquals4( a, c ), "Passed!" );
<ide>
<ide> } );
<ide>
<del> QUnit.todo( "makeShear", ( assert ) => {
<add> QUnit.test( "makeShear", ( assert ) => {
<add>
<add> var a = new Matrix4();
<add> var c = new Matrix4().set( 1, 3, 4, 0, 2, 1, 4, 0, 2, 3, 1, 0, 0, 0, 0, 1 );
<ide>
<del> assert.ok( false, "everything's gonna be alright" );
<add> a.makeShear( 2, 3, 4 );
<add> assert.ok( matrixEquals4( a, c ), "Passed!" );
<ide>
<ide> } );
<ide>
<ide> export default QUnit.module( 'Maths', () => {
<ide>
<ide> } );
<ide>
<del> QUnit.todo( "makePerspective", ( assert ) => {
<add> QUnit.test( "makePerspective", ( assert ) => {
<ide>
<del> assert.ok( false, "everything's gonna be alright" );
<add> var a = new Matrix4().makePerspective( - 1, 1, - 1, 1, 1, 100 );
<add> var expected = new Matrix4().set(
<add> 1, 0, 0, 0,
<add> 0, - 1, 0, 0,
<add> 0, 0, - 101 / 99, - 200 / 99,
<add> 0, 0, - 1, 0
<add> );
<add> assert.ok( matrixEquals4( a, expected ), "Check result" );
<ide>
<ide> } );
<ide>
<ide> export default QUnit.module( 'Maths', () => {
<ide>
<ide> } );
<ide>
<del> QUnit.todo( "fromArray", ( assert ) => {
<add> QUnit.test( "fromArray", ( assert ) => {
<add>
<add> var a = new Matrix4();
<add> var b = new Matrix4().set( 1, 5, 9, 13, 2, 6, 10, 14, 3, 7, 11, 15, 4, 8, 12, 16 );
<ide>
<del> assert.ok( false, "everything's gonna be alright" );
<add> a.fromArray( [ 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16 ] );
<add> assert.ok( a.equals( b ), "Passed" );
<ide>
<ide> } );
<ide> | 1 |
Python | Python | fix code documentation | 279305eede83b12ec2d038caf86f16771443d7e0 | <ide><path>object_detection/create_pet_tf_record.py
<ide> def get_class_name_from_filename(file_name):
<ide> ie. "american_pit_bull_terrier_105.jpg"
<ide>
<ide> Returns:
<del> example: The converted tf.Example.
<add> A string of the class name.
<ide> """
<ide> match = re.match(r'([A-Za-z_]+)(_[0-9]+\.jpg)', file_name, re.I)
<ide> return match.groups()[0] | 1 |
Text | Text | use code markup/markdown in headers | 248f057509adb1c9ca6bd456b9ae98b885db11a8 | <ide><path>doc/api/modules.md
<ide> variable. Since the module lookups using `node_modules` folders are all
<ide> relative, and based on the real path of the files making the calls to
<ide> `require()`, the packages themselves can be anywhere.
<ide>
<del>## Addenda: The .mjs extension
<add>## Addenda: The `.mjs` extension
<ide>
<ide> It is not possible to `require()` files that have the `.mjs` extension.
<ide> Attempting to do so will throw [an error][]. The `.mjs` extension is
<ide> the module rather than the global object.
<ide>
<ide> ## The module scope
<ide>
<del>### \_\_dirname
<add>### `__dirname`
<ide> <!-- YAML
<ide> added: v0.1.27
<ide> -->
<ide> console.log(path.dirname(__filename));
<ide> // Prints: /Users/mjr
<ide> ```
<ide>
<del>### \_\_filename
<add>### `__filename`
<ide> <!-- YAML
<ide> added: v0.0.1
<ide> -->
<ide> References to `__filename` within `b.js` will return
<ide> `/Users/mjr/app/node_modules/b/b.js` while references to `__filename` within
<ide> `a.js` will return `/Users/mjr/app/a.js`.
<ide>
<del>### exports
<add>### `exports`
<ide> <!-- YAML
<ide> added: v0.1.12
<ide> -->
<ide> A reference to the `module.exports` that is shorter to type.
<ide> See the section about the [exports shortcut][] for details on when to use
<ide> `exports` and when to use `module.exports`.
<ide>
<del>### module
<add>### `module`
<ide> <!-- YAML
<ide> added: v0.1.16
<ide> -->
<ide> A reference to the current module, see the section about the
<ide> [`module` object][]. In particular, `module.exports` is used for defining what
<ide> a module exports and makes available through `require()`.
<ide>
<del>### require(id)
<add>### `require(id)`
<ide> <!-- YAML
<ide> added: v0.1.13
<ide> -->
<ide> const jsonData = require('./path/filename.json');
<ide> const crypto = require('crypto');
<ide> ```
<ide>
<del>#### require.cache
<add>#### `require.cache`
<ide> <!-- YAML
<ide> added: v0.3.0
<ide> -->
<ide> native modules and if a name matching a native module is added to the cache,
<ide> no require call is
<ide> going to receive the native module anymore. Use with care!
<ide>
<del>#### require.extensions
<add>#### `require.extensions`
<ide> <!-- YAML
<ide> added: v0.3.0
<ide> deprecated: v0.10.6
<ide> program, or compiling them to JavaScript ahead of time.
<ide> Avoid using `require.extensions`. Use could cause subtle bugs and resolving the
<ide> extensions gets slower with each registered extension.
<ide>
<del>#### require.main
<add>#### `require.main`
<ide> <!-- YAML
<ide> added: v0.1.17
<ide> -->
<ide> Module {
<ide> '/node_modules' ] }
<ide> ```
<ide>
<del>#### require.resolve(request\[, options\])
<add>#### `require.resolve(request[, options])`
<ide> <!-- YAML
<ide> added: v0.3.0
<ide> changes:
<ide> changes:
<ide> Use the internal `require()` machinery to look up the location of a module,
<ide> but rather than loading the module, just return the resolved filename.
<ide>
<del>##### require.resolve.paths(request)
<add>##### `require.resolve.paths(request)`
<ide> <!-- YAML
<ide> added: v8.9.0
<ide> -->
<ide> representing the current module. For convenience, `module.exports` is
<ide> also accessible via the `exports` module-global. `module` is not actually
<ide> a global but rather local to each module.
<ide>
<del>### module.children
<add>### `module.children`
<ide> <!-- YAML
<ide> added: v0.1.16
<ide> -->
<ide> added: v0.1.16
<ide>
<ide> The module objects required for the first time by this one.
<ide>
<del>### module.exports
<add>### `module.exports`
<ide> <!-- YAML
<ide> added: v0.1.16
<ide> -->
<ide> const x = require('./x');
<ide> console.log(x.a);
<ide> ```
<ide>
<del>#### exports shortcut
<add>#### `exports` shortcut
<ide> <!-- YAML
<ide> added: v0.1.16
<ide> -->
<ide> function require(/* ... */) {
<ide> }
<ide> ```
<ide>
<del>### module.filename
<add>### `module.filename`
<ide> <!-- YAML
<ide> added: v0.1.16
<ide> -->
<ide> added: v0.1.16
<ide>
<ide> The fully resolved filename of the module.
<ide>
<del>### module.id
<add>### `module.id`
<ide> <!-- YAML
<ide> added: v0.1.16
<ide> -->
<ide> added: v0.1.16
<ide> The identifier for the module. Typically this is the fully resolved
<ide> filename.
<ide>
<del>### module.loaded
<add>### `module.loaded`
<ide> <!-- YAML
<ide> added: v0.1.16
<ide> -->
<ide> added: v0.1.16
<ide> Whether or not the module is done loading, or is in the process of
<ide> loading.
<ide>
<del>### module.parent
<add>### `module.parent`
<ide> <!-- YAML
<ide> added: v0.1.16
<ide> -->
<ide> added: v0.1.16
<ide>
<ide> The module that first required this one.
<ide>
<del>### module.paths
<add>### `module.paths`
<ide> <!-- YAML
<ide> added: v0.4.0
<ide> -->
<ide> added: v0.4.0
<ide>
<ide> The search paths for the module.
<ide>
<del>### module.require(id)
<add>### `module.require(id)`
<ide> <!-- YAML
<ide> added: v0.5.1
<ide> -->
<ide> Provides general utility methods when interacting with instances of
<ide> `Module` — the `module` variable often seen in file modules. Accessed
<ide> via `require('module')`.
<ide>
<del>### module.builtinModules
<add>### `module.builtinModules`
<ide> <!-- YAML
<ide> added:
<ide> - v9.3.0
<ide> by the [module wrapper][]. To access it, require the `Module` module:
<ide> const builtin = require('module').builtinModules;
<ide> ```
<ide>
<del>### module.createRequire(filename)
<add>### `module.createRequire(filename)`
<ide> <!-- YAML
<ide> added: v12.2.0
<ide> -->
<ide> const require = createRequire(import.meta.url);
<ide> const siblingModule = require('./sibling-module');
<ide> ```
<ide>
<del>### module.createRequireFromPath(filename)
<add>### `module.createRequireFromPath(filename)`
<ide> <!-- YAML
<ide> added: v10.12.0
<ide> deprecated: v12.2.0
<ide> const requireUtil = createRequireFromPath('../src/utils/');
<ide> requireUtil('./some-tool');
<ide> ```
<ide>
<del>### module.syncBuiltinESMExports()
<add>### `module.syncBuiltinESMExports()`
<ide> <!-- YAML
<ide> added: v12.12.0
<ide> --> | 1 |
Go | Go | remove panic in lxc driver | 7c06d5e34e2ebf5006ce3a34438f18c071153e97 | <ide><path>execdriver/lxc/driver.go
<ide> func (i *info) IsRunning() bool {
<ide>
<ide> output, err := i.driver.getInfo(i.ID)
<ide> if err != nil {
<del> panic(err)
<add> utils.Errorf("Error getting info for lxc container %s: %s (%s)", i.ID, err, output)
<add> return false
<ide> }
<ide> if strings.Contains(string(output), "RUNNING") {
<ide> running = true | 1 |
Javascript | Javascript | clarify limitations of object iteration | 4ba8e3463adefe22e8779e1813bd75681773cbc4 | <ide><path>src/ng/directive/ngRepeat.js
<ide> * <div ng-repeat="(key, value) in myObj"> ... </div>
<ide> * ```
<ide> *
<del> * You need to be aware that the JavaScript specification does not define the order of keys
<del> * returned for an object. (To mitigate this in Angular 1.3 the `ngRepeat` directive
<del> * used to sort the keys alphabetically.)
<add> * However, there are a limitations compared to array iteration:
<ide> *
<del> * Version 1.4 removed the alphabetic sorting. We now rely on the order returned by the browser
<del> * when running `for key in myObj`. It seems that browsers generally follow the strategy of providing
<del> * keys in the order in which they were defined, although there are exceptions when keys are deleted
<del> * and reinstated. See the [MDN page on `delete` for more info](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/delete#Cross-browser_notes).
<add> * - The JavaScript specification does not define the order of keys
<add> * returned for an object, so Angular relies on the order returned by the browser
<add> * when running `for key in myObj`. Browsers generally follow the strategy of providing
<add> * keys in the order in which they were defined, although there are exceptions when keys are deleted
<add> * and reinstated. See the
<add> * [MDN page on `delete` for more info](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/delete#Cross-browser_notes).
<ide> *
<del> * If this is not desired, the recommended workaround is to convert your object into an array
<del> * that is sorted into the order that you prefer before providing it to `ngRepeat`. You could
<add> * - `ngRepeat` will silently *ignore* object keys starting with `$`, because
<add> * it's a prefix used by Angular for public (`$`) and private (`$$`) properties.
<add> *
<add> * - The built-in filters {@link ng.orderBy orderBy} and {@link ng.filter filter} do not work with
<add> * objects, and will throw if used with one.
<add> *
<add> * If you are hitting any of these limitations, the recommended workaround is to convert your object into an array
<add> * that is sorted into the order that you prefer before providing it to `ngRepeat`. You could
<ide> * do this with a filter such as [toArrayFilter](http://ngmodules.org/modules/angular-toArrayFilter)
<ide> * or implement a `$watch` on the object yourself.
<ide> * | 1 |
PHP | PHP | add tests for enable/disable/enabled | e600e54f80dfdcdd113c2f3590e4b8638e6d8d1e | <ide><path>lib/Cake/Test/TestCase/Cache/CacheTest.php
<ide> public function testSetOnAlternateConfigs() {
<ide> $this->assertEquals(strtotime('+1 year') - time(), $settings['duration']);
<ide> }
<ide>
<add>/**
<add> * Test toggling enabled state of cache.
<add> *
<add> * @return void
<add> */
<add> public function testEnableDisableEnabled() {
<add> $this->assertNull(Cache::enable());
<add> $this->assertTrue(Cache::enabled(), 'Should be on');
<add> $this->assertNull(Cache::disable());
<add> $this->assertFalse(Cache::enabled(), 'Should be off');
<add> }
<add>
<ide> } | 1 |
Ruby | Ruby | kill nonexistent method removal | db9e67a6c873a46e9eb1103d7f8c2113d2c82635 | <ide><path>actionmailer/test/old_base/url_test.rb
<ide> def signed_up_with_url(recipient)
<ide> end
<ide>
<ide> class <<self
<del> remove_method :received_body
<del> remove_method :received_body=
<ide> attr_accessor :received_body
<ide> end
<ide> | 1 |
Text | Text | fix typo in readme | 47298a7d1686096ddb12199de33deaf404b1a482 | <ide><path>README.md
<ide> The built version of jQuery will be put in the `dist/` subdirectory.
<ide>
<ide> ### Modules (new in 1.8)
<ide>
<del>Starting in jQuery 1.8, special builds can now be created that optionally exlude or include any of the following modules:
<add>Starting in jQuery 1.8, special builds can now be created that optionally exclude or include any of the following modules:
<ide>
<ide> - ajax
<ide> - dimensions | 1 |
Text | Text | stress the importance of cable management | 335c4b120b6333ea19688c538fc9e0461c702a13 | <ide><path>client/src/pages/guide/english/computer-hardware/cooling/index.md
<ide> Cooling devices are available for individual parts on the computer. The two most
<ide> Room ventilation - Locate the computer where it is neutral to the rooms environmental registers. Keep the computer away from room heaters or vents at all times.
<ide> * Room placement - Locate the computer away from windows or areas of strong sunlight exposure. Placement in closets can also provide challenges to cooling. It is recommended to keep the computer away from any carpet-like material, which can easily bring dust into the computer.
<ide> * Placement next to other computers - Locating the computer away from other equipment allows air to flow in and out of the computer. Placement close to other equipment can constrict air flow and increase heat.
<add>* Cable Management = Having a rat's nest of cables can block airflow and make your computer hotter. It is reccomended to take some time to cable manage after building a computer, because it can increase the lifespan of your computer in the future.
<ide>
<ide> [Wikipedia - Article on computer cooling](https://en.wikipedia.org/wiki/Computer_cooling) | 1 |
Python | Python | replace strided slice with tf.expand_dims | b82fe7d258a621b953dcb3b78bd03da4fef70a44 | <ide><path>src/transformers/modeling_tf_utils.py
<ide> def call(self, inputs, cls_index=None, training=False):
<ide> ) # A tensor full of shape [batch] or [batch, num choices] full of sequence length
<ide> cls_shape = shape_list(cls_index)
<ide> if len(cls_shape) <= len(hidden_shape) - 2:
<del> cls_index = cls_index[..., tf.newaxis]
<add> cls_index = tf.expand_dims(cls_index, axis=-1)
<ide> # else:
<ide> # cls_index = cls_index[..., tf.newaxis]
<ide> # cls_index = cls_index.expand((-1,) * (cls_index.dim()-1) + (hidden_states.size(-1),))
<ide><path>src/transformers/models/albert/modeling_tf_albert.py
<ide> def call(
<ide> token_type_ids = tf.fill(dims=input_shape, value=0)
<ide>
<ide> if position_ids is None:
<del> position_ids = tf.range(start=0, limit=input_shape[-1])[tf.newaxis, :]
<add> position_ids = tf.expand_dims(tf.range(start=0, limit=input_shape[-1]), axis=0)
<ide>
<ide> position_embeds = tf.gather(params=self.position_embeddings, indices=position_ids)
<ide> position_embeds = tf.tile(input=position_embeds, multiples=(input_shape[0], 1, 1))
<ide> def call(
<ide> # So we can broadcast to [batch_size, num_heads, from_seq_length, to_seq_length]
<ide> # this attention mask is more simple than the triangular masking of causal attention
<ide> # used in OpenAI GPT, we just need to prepare the broadcast dimension here.
<del> extended_attention_mask = inputs["attention_mask"][:, tf.newaxis, tf.newaxis, :]
<add> extended_attention_mask = tf.reshape(inputs["attention_mask"], (input_shape[0], 1, 1, input_shape[1]))
<ide>
<ide> # Since attention_mask is 1.0 for positions we want to attend and 0.0 for
<ide> # masked positions, this operation will create a tensor which is 0.0 for
<ide><path>src/transformers/models/bert/modeling_tf_bert.py
<ide> def call(
<ide> token_type_ids = tf.fill(dims=input_shape, value=0)
<ide>
<ide> if position_ids is None:
<del> position_ids = tf.range(start=0, limit=input_shape[-1])[tf.newaxis, :]
<add> position_ids = tf.expand_dims(tf.range(start=0, limit=input_shape[-1]), axis=0)
<ide>
<ide> position_embeds = tf.gather(params=self.position_embeddings, indices=position_ids)
<ide> position_embeds = tf.tile(input=position_embeds, multiples=(input_shape[0], 1, 1))
<ide> def call(
<ide> # So we can broadcast to [batch_size, num_heads, from_seq_length, to_seq_length]
<ide> # this attention mask is more simple than the triangular masking of causal attention
<ide> # used in OpenAI GPT, we just need to prepare the broadcast dimension here.
<del> extended_attention_mask = inputs["attention_mask"][:, tf.newaxis, tf.newaxis, :]
<add> extended_attention_mask = tf.reshape(inputs["attention_mask"], (input_shape[0], 1, 1, input_shape[1]))
<ide>
<ide> # Since attention_mask is 1.0 for positions we want to attend and 0.0 for
<ide> # masked positions, this operation will create a tensor which is 0.0 for
<ide><path>src/transformers/models/convbert/modeling_tf_convbert.py
<ide> def call(
<ide> token_type_ids = tf.fill(dims=input_shape, value=0)
<ide>
<ide> if position_ids is None:
<del> position_ids = tf.range(start=0, limit=input_shape[-1])[tf.newaxis, :]
<add> position_ids = tf.expand_dims(tf.range(start=0, limit=input_shape[-1]), axis=0)
<ide>
<ide> position_embeds = tf.gather(params=self.position_embeddings, indices=position_ids)
<ide> position_embeds = tf.tile(input=position_embeds, multiples=(input_shape[0], 1, 1))
<ide> def get_extended_attention_mask(self, attention_mask, input_shape, dtype):
<ide> # So we can broadcast to [batch_size, num_heads, from_seq_length, to_seq_length]
<ide> # this attention mask is more simple than the triangular masking of causal attention
<ide> # used in OpenAI GPT, we just need to prepare the broadcast dimension here.
<del> extended_attention_mask = attention_mask[:, tf.newaxis, tf.newaxis, :]
<add> extended_attention_mask = tf.reshape(attention_mask, (input_shape[0], 1, 1, input_shape[1]))
<ide>
<ide> # Since attention_mask is 1.0 for positions we want to attend and 0.0 for
<ide> # masked positions, this operation will create a tensor which is 0.0 for
<ide><path>src/transformers/models/ctrl/modeling_tf_ctrl.py
<ide> def call(
<ide> else:
<ide> past_length = shape_list(inputs["past"][0][0])[-2]
<ide> if inputs["position_ids"] is None:
<del> inputs["position_ids"] = tf.range(past_length, input_shape[-1] + past_length, dtype=tf.int32)[
<del> tf.newaxis, :
<del> ]
<add> inputs["position_ids"] = tf.expand_dims(
<add> tf.range(past_length, input_shape[-1] + past_length, dtype=tf.int32), axis=0
<add> )
<ide> inputs["position_ids"] = tf.tile(inputs["position_ids"], [input_shape[0], 1])
<ide>
<ide> # Attention mask.
<ide> def call(
<ide> # So we can broadcast to [batch_size, num_heads, from_seq_length, to_seq_length]
<ide> # this attention mask is more simple than the triangular masking of causal attention
<ide> # used in OpenAI GPT, we just need to prepare the broadcast dimension here.
<del> inputs["attention_mask"] = inputs["attention_mask"][:, tf.newaxis, tf.newaxis, :]
<add> inputs["attention_mask"] = tf.reshape(inputs["attention_mask"], (input_shape[0], 1, 1, input_shape[1]))
<ide>
<ide> # Since attention_mask is 1.0 for positions we want to attend and 0.0 for
<ide> # masked positions, this operation will create a tensor which is 0.0 for
<ide><path>src/transformers/models/distilbert/modeling_tf_distilbert.py
<ide> def call(self, input_ids=None, position_ids=None, inputs_embeds=None, training=F
<ide> input_shape = shape_list(inputs_embeds)[:-1]
<ide>
<ide> if position_ids is None:
<del> position_ids = tf.range(start=0, limit=input_shape[-1])[tf.newaxis, :]
<add> position_ids = tf.expand_dims(tf.range(start=0, limit=input_shape[-1]), axis=0)
<ide>
<ide> position_embeds = tf.gather(params=self.position_embeddings, indices=position_ids)
<ide> position_embeds = tf.tile(input=position_embeds, multiples=(input_shape[0], 1, 1))
<ide><path>src/transformers/models/electra/modeling_tf_electra.py
<ide> def call(
<ide> token_type_ids = tf.fill(dims=input_shape, value=0)
<ide>
<ide> if position_ids is None:
<del> position_ids = tf.range(start=0, limit=input_shape[-1])[tf.newaxis, :]
<add> position_ids = tf.expand_dims(tf.range(start=0, limit=input_shape[-1]), axis=0)
<ide>
<ide> position_embeds = tf.gather(params=self.position_embeddings, indices=position_ids)
<ide> position_embeds = tf.tile(input=position_embeds, multiples=(input_shape[0], 1, 1))
<ide> def get_extended_attention_mask(self, attention_mask, input_shape, dtype):
<ide> # So we can broadcast to [batch_size, num_heads, from_seq_length, to_seq_length]
<ide> # this attention mask is more simple than the triangular masking of causal attention
<ide> # used in OpenAI GPT, we just need to prepare the broadcast dimension here.
<del> extended_attention_mask = attention_mask[:, tf.newaxis, tf.newaxis, :]
<add> extended_attention_mask = tf.reshape(attention_mask, (input_shape[0], 1, 1, input_shape[1]))
<ide>
<ide> # Since attention_mask is 1.0 for positions we want to attend and 0.0 for
<ide> # masked positions, this operation will create a tensor which is 0.0 for
<ide><path>src/transformers/models/flaubert/modeling_tf_flaubert.py
<ide> def get_masks(slen, lengths, causal, padding_mask=None, dtype=tf.float32):
<ide> else:
<ide> # assert lengths.max().item() <= slen
<ide> alen = tf.range(slen)
<del> mask = tf.math.less(alen, lengths[:, tf.newaxis])
<add> mask = tf.math.less(alen, tf.expand_dims(lengths, axis=1))
<ide>
<ide> # attention mask is the same as mask, or triangular inferior attention (causal)
<ide> if causal:
<ide> attn_mask = tf.less_equal(
<del> tf.tile(alen[tf.newaxis, tf.newaxis, :], (bs, slen, 1)), alen[tf.newaxis, :, tf.newaxis]
<add> tf.tile(tf.reshape(alen, (1, 1, slen)), (bs, slen, 1)), tf.reshape(alen, (1, slen, 1))
<ide> )
<ide> else:
<ide> attn_mask = mask
<ide> def call(
<ide>
<ide> tensor = self.layer_norm_emb(tensor)
<ide> tensor = self.dropout(tensor, training=inputs["training"])
<del> tensor = tensor * mask[..., tf.newaxis]
<add> tensor = tensor * tf.expand_dims(mask, axis=-1)
<ide>
<ide> # hidden_states and attentions cannot be None in graph mode.
<ide> hidden_states = () if inputs["output_hidden_states"] else None
<ide> def call(
<ide> tensor_normalized = self.layer_norm2[i](tensor)
<ide> tensor = tensor + self.ffns[i](tensor_normalized)
<ide>
<del> tensor = tensor * mask[..., tf.newaxis]
<add> tensor = tensor * tf.expand_dims(mask, axis=-1)
<ide>
<ide> # Add last hidden state
<ide> if inputs["output_hidden_states"]:
<ide><path>src/transformers/models/gpt2/modeling_tf_gpt2.py
<ide> def call(
<ide> past_length = shape_list(inputs["past"][0][0])[-2]
<ide>
<ide> if inputs["position_ids"] is None:
<del> inputs["position_ids"] = tf.range(past_length, input_shape[-1] + past_length, dtype=tf.int32)[
<del> tf.newaxis, :
<del> ]
<add> inputs["position_ids"] = tf.expand_dims(
<add> tf.range(past_length, input_shape[-1] + past_length, dtype=tf.int32), axis=0
<add> )
<ide>
<ide> if inputs["attention_mask"] is not None:
<ide> # We create a 3D attention mask from a 2D tensor mask.
<ide> # Sizes are [batch_size, 1, 1, to_seq_length]
<ide> # So we can broadcast to [batch_size, num_heads, from_seq_length, to_seq_length]
<ide> # this attention mask is more simple than the triangular masking of causal attention
<ide> # used in OpenAI GPT, we just need to prepare the broadcast dimension here.
<del> inputs["attention_mask"] = inputs["attention_mask"][:, tf.newaxis, tf.newaxis, :]
<add> attention_mask_shape = shape_list(inputs["attention_mask"])
<add> inputs["attention_mask"] = tf.reshape(
<add> inputs["attention_mask"], (attention_mask_shape[0], 1, 1, attention_mask_shape[1])
<add> )
<ide>
<ide> # Since attention_mask is 1.0 for positions we want to attend and 0.0 for
<ide> # masked positions, this operation will create a tensor which is 0.0 for
<ide><path>src/transformers/models/longformer/modeling_tf_longformer.py
<ide> def call(self, input_ids=None, position_ids=None, token_type_ids=None, inputs_em
<ide> # Create the position ids from the input token ids. Any padded tokens remain padded.
<ide> position_ids = self.create_position_ids_from_input_ids(input_ids=input_ids)
<ide> else:
<del> position_ids = tf.range(start=self.padding_idx + 1, limit=input_shape[-1] + self.padding_idx + 1)[
<del> tf.newaxis, :
<del> ]
<add> position_ids = tf.expand_dims(
<add> tf.range(start=self.padding_idx + 1, limit=input_shape[-1] + self.padding_idx + 1), axis=0
<add> )
<ide> position_ids = tf.tile(input=position_ids, multiples=(input_shape[0], 1))
<ide>
<ide> position_embeds = tf.gather(params=self.position_embeddings, indices=position_ids)
<ide> def call(
<ide> # So we can broadcast to [batch_size, num_heads, from_seq_length, to_seq_length]
<ide> # this attention mask is more simple than the triangular masking of causal attention
<ide> # used in OpenAI GPT, we just need to prepare the broadcast dimension here.
<del> extended_attention_mask = inputs["attention_mask"][:, :, tf.newaxis, tf.newaxis]
<add> attention_mask_shape = shape_list(inputs["attention_mask"])
<add> extended_attention_mask = tf.reshape(
<add> inputs["attention_mask"], (attention_mask_shape[0], attention_mask_shape[1], 1, 1)
<add> )
<ide>
<ide> # Since attention_mask is 1.0 for positions we want to locall attend locally and 0.0 for
<ide> # masked and global attn positions, this operation will create a tensor which is 0.0 for
<ide><path>src/transformers/models/lxmert/modeling_tf_lxmert.py
<ide> def call(self, input_ids=None, token_type_ids=None, inputs_embeds=None, training
<ide> if token_type_ids is None:
<ide> token_type_ids = tf.fill(dims=input_shape, value=0)
<ide>
<del> position_ids = tf.range(start=0, limit=input_shape[-1])[tf.newaxis, :]
<add> position_ids = tf.expand_dims(tf.range(start=0, limit=input_shape[-1]), axis=0)
<ide> position_embeds = tf.gather(params=self.position_embeddings, indices=position_ids)
<ide> position_embeds = tf.tile(input=position_embeds, multiples=(input_shape[0], 1, 1))
<ide> token_type_embeds = tf.gather(params=self.token_type_embeddings, indices=token_type_ids)
<ide> def call(
<ide> # So we can broadcast to [batch_size, num_heads, from_seq_length, to_seq_length]
<ide> # this attention mask is more simple than the triangular masking of causal attention
<ide> # used in OpenAI GPT, we just need to prepare the broadcast dimension here.
<del> extended_attention_mask = inputs["attention_mask"][:, tf.newaxis, tf.newaxis, :]
<add> extended_attention_mask = tf.reshape(inputs["attention_mask"], (input_shape[0], 1, 1, input_shape[1]))
<ide>
<ide> # Since attention_mask is 1.0 for positions we want to attend and 0.0 for
<ide> # masked positions, this operation will create a tensor which is 0.0 for
<ide> def call(
<ide> extended_attention_mask = (1.0 - extended_attention_mask) * -10000.0
<ide>
<ide> if inputs["visual_attention_mask"] is not None:
<del> extended_visual_attention_mask = inputs["visual_attention_mask"][:, tf.newaxis, tf.newaxis, :]
<add> extended_visual_attention_mask = tf.reshape(
<add> inputs["visual_attention_mask"], (input_shape[0], 1, 1, input_shape[1])
<add> )
<add> extended_visual_attention_mask = tf.expand_dims(
<add> tf.expand_dims(inputs["visual_attention_mask"], axis=1), axis=1
<add> )
<ide>
<ide> extended_visual_attention_mask = tf.cast(extended_visual_attention_mask, tf.float32)
<ide> extended_visual_attention_mask = (1.0 - extended_visual_attention_mask) * -10000.0
<ide><path>src/transformers/models/mobilebert/modeling_tf_mobilebert.py
<ide> def call(self, input_ids=None, position_ids=None, token_type_ids=None, inputs_em
<ide> inputs_embeds = self.embedding_transformation(inputs_embeds)
<ide>
<ide> if position_ids is None:
<del> position_ids = tf.range(start=0, limit=input_shape[-1])[tf.newaxis, :]
<add> position_ids = tf.expand_dims(tf.range(start=0, limit=input_shape[-1]), axis=0)
<ide>
<ide> position_embeds = tf.gather(params=self.position_embeddings, indices=position_ids)
<ide> position_embeds = tf.tile(input=position_embeds, multiples=(input_shape[0], 1, 1))
<ide> def call(
<ide> # So we can broadcast to [batch_size, num_heads, from_seq_length, to_seq_length]
<ide> # this attention mask is more simple than the triangular masking of causal attention
<ide> # used in OpenAI GPT, we just need to prepare the broadcast dimension here.
<del> extended_attention_mask = inputs["attention_mask"][:, tf.newaxis, tf.newaxis, :]
<add> extended_attention_mask = tf.reshape(inputs["attention_mask"], (input_shape[0], 1, 1, input_shape[1]))
<ide>
<ide> # Since attention_mask is 1.0 for positions we want to attend and 0.0 for
<ide> # masked positions, this operation will create a tensor which is 0.0 for
<ide><path>src/transformers/models/mpnet/modeling_tf_mpnet.py
<ide> def call(self, input_ids=None, position_ids=None, inputs_embeds=None, training=F
<ide> # Create the position ids from the input token ids. Any padded tokens remain padded.
<ide> position_ids = self.create_position_ids_from_input_ids(input_ids=input_ids)
<ide> else:
<del> position_ids = tf.range(start=self.padding_idx + 1, limit=input_shape[-1] + self.padding_idx + 1)[
<del> tf.newaxis, :
<del> ]
<add> position_ids = tf.expand_dims(
<add> tf.range(start=self.padding_idx + 1, limit=input_shape[-1] + self.padding_idx + 1), axis=0
<add> )
<ide> position_ids = tf.tile(input=position_ids, multiples=(input_shape[0], 1))
<ide>
<ide> position_embeds = tf.gather(params=self.position_embeddings, indices=position_ids)
<ide> def call(
<ide> # So we can broadcast to [batch_size, num_heads, from_seq_length, to_seq_length]
<ide> # this attention mask is more simple than the triangular masking of causal attention
<ide> # used in OpenAI GPT, we just need to prepare the broadcast dimension here.
<del> extended_attention_mask = inputs["attention_mask"][:, tf.newaxis, tf.newaxis, :]
<add> extended_attention_mask = tf.reshape(inputs["attention_mask"], (input_shape[0], 1, 1, input_shape[1]))
<ide>
<ide> # Since attention_mask is 1.0 for positions we want to attend and 0.0 for
<ide> # masked positions, this operation will create a tensor which is 0.0 for
<ide><path>src/transformers/models/openai/modeling_tf_openai.py
<ide> def call(
<ide> raise ValueError("You have to specify either input_ids or inputs_embeds")
<ide>
<ide> if inputs["position_ids"] is None:
<del> inputs["position_ids"] = tf.range(input_shape[-1], dtype=tf.int32)[tf.newaxis, :]
<add> inputs["position_ids"] = tf.expand_dims(tf.range(input_shape[-1], dtype=tf.int32), axis=0)
<ide>
<ide> if inputs["attention_mask"] is not None:
<ide> # We create a 3D attention mask from a 2D tensor mask.
<ide> # Sizes are [batch_size, 1, 1, to_seq_length]
<ide> # So we can broadcast to [batch_size, num_heads, from_seq_length, to_seq_length]
<ide> # this attention mask is more simple than the triangular masking of causal attention
<ide> # used in OpenAI GPT, we just need to prepare the broadcast dimension here.
<del> inputs["attention_mask"] = inputs["attention_mask"][:, tf.newaxis, tf.newaxis, :]
<add> inputs["attention_mask"] = tf.reshape(inputs["attention_mask"], (input_shape[0], 1, 1, input_shape[1]))
<ide>
<ide> # Since attention_mask is 1.0 for positions we want to attend and 0.0 for
<ide> # masked positions, this operation will create a tensor which is 0.0 for
<ide><path>src/transformers/models/roberta/modeling_tf_roberta.py
<ide> def call(self, input_ids=None, position_ids=None, token_type_ids=None, inputs_em
<ide> # Create the position ids from the input token ids. Any padded tokens remain padded.
<ide> position_ids = self.create_position_ids_from_input_ids(input_ids=input_ids)
<ide> else:
<del> position_ids = tf.range(start=self.padding_idx + 1, limit=input_shape[-1] + self.padding_idx + 1)[
<del> tf.newaxis, :
<del> ]
<add> position_ids = tf.expand_dims(
<add> tf.range(start=self.padding_idx + 1, limit=input_shape[-1] + self.padding_idx + 1), axis=0
<add> )
<ide> position_ids = tf.tile(input=position_ids, multiples=(input_shape[0], 1))
<ide>
<ide> position_embeds = tf.gather(params=self.position_embeddings, indices=position_ids)
<ide> def call(
<ide> # So we can broadcast to [batch_size, num_heads, from_seq_length, to_seq_length]
<ide> # this attention mask is more simple than the triangular masking of causal attention
<ide> # used in OpenAI GPT, we just need to prepare the broadcast dimension here.
<del> extended_attention_mask = inputs["attention_mask"][:, tf.newaxis, tf.newaxis, :]
<add> extended_attention_mask = tf.reshape(inputs["attention_mask"], (input_shape[0], 1, 1, input_shape[1]))
<ide>
<ide> # Since attention_mask is 1.0 for positions we want to attend and 0.0 for
<ide> # masked positions, this operation will create a tensor which is 0.0 for
<ide><path>src/transformers/models/xlm/modeling_tf_xlm.py
<ide> def get_masks(slen, lengths, causal, padding_mask=None, dtype=tf.float32):
<ide> else:
<ide> # assert lengths.max().item() <= slen
<ide> alen = tf.range(slen)
<del> mask = tf.math.less(alen, lengths[:, tf.newaxis])
<add> mask = tf.math.less(alen, tf.expand_dims(lengths, axis=1))
<ide>
<ide> # attention mask is the same as mask, or triangular inferior attention (causal)
<ide> if causal:
<ide> attn_mask = tf.less_equal(
<del> tf.tile(alen[tf.newaxis, tf.newaxis, :], (bs, slen, 1)), alen[tf.newaxis, :, tf.newaxis]
<add> tf.tile(tf.reshape(alen, (1, 1, slen)), (bs, slen, 1)), tf.reshape(alen, (1, slen, 1))
<ide> )
<ide> else:
<ide> attn_mask = mask
<ide> def call(
<ide>
<ide> tensor = self.layer_norm_emb(tensor)
<ide> tensor = self.dropout(tensor, training=inputs["training"])
<del> tensor = tensor * mask[..., tf.newaxis]
<add> tensor = tensor * tf.expand_dims(mask, axis=-1)
<ide>
<ide> # transformer layers
<ide> hidden_states = () if inputs["output_hidden_states"] else None
<ide> def call(
<ide> # FFN
<ide> tensor = tensor + self.ffns[i](tensor)
<ide> tensor = self.layer_norm2[i](tensor)
<del> tensor = tensor * mask[..., tf.newaxis]
<add> tensor = tensor * tf.expand_dims(mask, axis=-1)
<ide>
<ide> # Add last hidden state
<ide> if inputs["output_hidden_states"]:
<ide><path>templates/adding_a_new_model/cookiecutter-template-{{cookiecutter.modelname}}/modeling_tf_{{cookiecutter.lowercase_modelname}}.py
<ide> def call(
<ide> token_type_ids = tf.fill(dims=input_shape, value=0)
<ide>
<ide> if position_ids is None:
<del> position_ids = tf.range(start=0, limit=input_shape[-1])[tf.newaxis, :]
<add> position_ids = tf.expand_dims(tf.range(start=0, limit=input_shape[-1]), axis=0)
<ide>
<ide> position_embeds = tf.gather(params=self.position_embeddings, indices=position_ids)
<ide> position_embeds = tf.tile(input=position_embeds, multiples=(input_shape[0], 1, 1))
<ide> def call(
<ide> # So we can broadcast to [batch_size, num_heads, from_seq_length, to_seq_length]
<ide> # this attention mask is more simple than the triangular masking of causal attention
<ide> # used in OpenAI GPT, we just need to prepare the broadcast dimension here.
<del> extended_attention_mask = inputs["attention_mask"][:, tf.newaxis, tf.newaxis, :]
<add> extended_attention_mask = tf.reshape(inputs["attention_mask"], (input_shape[0], 1, 1, input_shape[1]))
<ide>
<ide> # Since attention_mask is 1.0 for positions we want to attend and 0.0 for
<ide> # masked positions, this operation will create a tensor which is 0.0 for | 17 |
Javascript | Javascript | fix small lint issues | 5a3d85bf53341078186d7fda8688efab921e610f | <ide><path>charsets.js
<add>/* -*- Mode: Java; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
<add>/* vim: set shiftwidth=2 tabstop=2 autoindent cindent expandtab: */
<add>
<add>'use strict';
<ide>
<ide> var ISOAdobeCharset = [
<ide> '.notdef', 'space', 'exclam', 'quotedbl', 'numbersign', 'dollar',
<ide><path>extensions/firefox/components/pdfContentHandler.js
<ide> pdfContentHandler.prototype = {
<ide> throw Cr.NS_ERROR_WONT_HANDLE_CONTENT;
<ide>
<ide> let window = null;
<del> let callbacks = aRequest.notificationCallbacks ?
<del> aRequest.notificationCallbacks :
<add> let callbacks = aRequest.notificationCallbacks ||
<ide> aRequest.loadGroup.notificationCallbacks;
<ide> if (!callbacks)
<ide> return; | 2 |
Java | Java | introduce supplier<string> support in assert util | 17dd5dd22d9b68bf60c302833c8c33d3cb914ed3 | <ide><path>spring-core/src/main/java/org/springframework/util/Assert.java
<ide>
<ide> import java.util.Collection;
<ide> import java.util.Map;
<add>import java.util.function.Supplier;
<ide>
<ide> /**
<ide> * Assertion utility class that assists in validating arguments.
<ide> public abstract class Assert {
<ide>
<ide> /**
<del> * Assert a boolean expression, throwing {@code IllegalArgumentException}
<del> * if the test result is {@code false}.
<add> * Assert a boolean expression, throwing an {@code IllegalArgumentException}
<add> * if the expression evaluates to {@code false}.
<add> * <pre class="code">
<add> * Assert.isTrue(i > 0, () -> "The value '" + i + "' must be greater than zero");
<add> * </pre>
<add> * @param expression a boolean expression
<add> * @param messageSupplier a supplier for the exception message to use if the
<add> * assertion fails
<add> * @throws IllegalArgumentException if {@code expression} is {@code false}
<add> */
<add> public static void isTrue(boolean expression, Supplier<String> messageSupplier) {
<add> if (!expression) {
<add> throw new IllegalArgumentException(nullSafeGet(messageSupplier));
<add> }
<add> }
<add>
<add> /**
<add> * Assert a boolean expression, throwing an {@code IllegalArgumentException}
<add> * if the expression evaluates to {@code false}.
<ide> * <pre class="code">Assert.isTrue(i > 0, "The value must be greater than zero");</pre>
<ide> * @param expression a boolean expression
<ide> * @param message the exception message to use if the assertion fails
<del> * @throws IllegalArgumentException if expression is {@code false}
<add> * @throws IllegalArgumentException if {@code expression} is {@code false}
<ide> */
<ide> public static void isTrue(boolean expression, String message) {
<ide> if (!expression) {
<ide> public static void isTrue(boolean expression, String message) {
<ide> }
<ide>
<ide> /**
<del> * Assert a boolean expression, throwing {@code IllegalArgumentException}
<del> * if the test result is {@code false}.
<add> * Assert a boolean expression, throwing an {@code IllegalArgumentException}
<add> * if the expression evaluates to {@code false}.
<ide> * <pre class="code">Assert.isTrue(i > 0);</pre>
<ide> * @param expression a boolean expression
<del> * @throws IllegalArgumentException if expression is {@code false}
<add> * @throws IllegalArgumentException if {@code expression} is {@code false}
<ide> */
<ide> public static void isTrue(boolean expression) {
<ide> isTrue(expression, "[Assertion failed] - this expression must be true");
<ide> }
<ide>
<ide> /**
<del> * Assert that an object is {@code null} .
<add> * Assert that an object is {@code null}.
<add> * <pre class="code">
<add> * Assert.isNull(value, () -> "The value '" + value + "' must be null");
<add> * </pre>
<add> * @param object the object to check
<add> * @param messageSupplier a supplier for the exception message to use if the
<add> * assertion fails
<add> * @throws IllegalArgumentException if the object is not {@code null}
<add> */
<add> public static void isNull(Object object, Supplier<String> messageSupplier) {
<add> if (object != null) {
<add> throw new IllegalArgumentException(nullSafeGet(messageSupplier));
<add> }
<add> }
<add>
<add> /**
<add> * Assert that an object is {@code null}.
<ide> * <pre class="code">Assert.isNull(value, "The value must be null");</pre>
<ide> * @param object the object to check
<ide> * @param message the exception message to use if the assertion fails
<ide> public static void isNull(Object object, String message) {
<ide> }
<ide>
<ide> /**
<del> * Assert that an object is {@code null} .
<add> * Assert that an object is {@code null}.
<ide> * <pre class="code">Assert.isNull(value);</pre>
<ide> * @param object the object to check
<ide> * @throws IllegalArgumentException if the object is not {@code null}
<ide> public static void isNull(Object object) {
<ide> }
<ide>
<ide> /**
<del> * Assert that an object is not {@code null} .
<add> * Assert that an object is not {@code null}.
<add> * <pre class="code">
<add> * Assert.notNull(clazz, () -> "The class '" + clazz.getName() + "' must not be null");
<add> * </pre>
<add> * @param object the object to check
<add> * @param messageSupplier a supplier for the exception message to use if the
<add> * assertion fails
<add> * @throws IllegalArgumentException if the object is {@code null}
<add> */
<add> public static void notNull(Object object, Supplier<String> messageSupplier) {
<add> if (object == null) {
<add> throw new IllegalArgumentException(nullSafeGet(messageSupplier));
<add> }
<add> }
<add>
<add> /**
<add> * Assert that an object is not {@code null}.
<ide> * <pre class="code">Assert.notNull(clazz, "The class must not be null");</pre>
<ide> * @param object the object to check
<ide> * @param message the exception message to use if the assertion fails
<ide> public static void notNull(Object object, String message) {
<ide> }
<ide>
<ide> /**
<del> * Assert that an object is not {@code null} .
<add> * Assert that an object is not {@code null}.
<ide> * <pre class="code">Assert.notNull(clazz);</pre>
<ide> * @param object the object to check
<ide> * @throws IllegalArgumentException if the object is {@code null}
<ide> public static void notNull(Object object) {
<ide> notNull(object, "[Assertion failed] - this argument is required; it must not be null");
<ide> }
<ide>
<add> /**
<add> * Assert that the given String is not empty; that is,
<add> * it must not be {@code null} and not the empty String.
<add> * <pre class="code">
<add> * Assert.hasLength(name, () -> "Name for account '" + account.getId() + "' must not be empty");
<add> * </pre>
<add> * @param text the String to check
<add> * @param messageSupplier a supplier for the exception message to use if the
<add> * assertion fails
<add> * @see StringUtils#hasLength
<add> * @throws IllegalArgumentException if the text is empty
<add> */
<add> public static void hasLength(String text, Supplier<String> messageSupplier) {
<add> if (!StringUtils.hasLength(text)) {
<add> throw new IllegalArgumentException(nullSafeGet(messageSupplier));
<add> }
<add> }
<add>
<ide> /**
<ide> * Assert that the given String is not empty; that is,
<ide> * it must not be {@code null} and not the empty String.
<ide> public static void hasLength(String text) {
<ide> }
<ide>
<ide> /**
<del> * Assert that the given String has valid text content; that is, it must not
<add> * Assert that the given String contains valid text content; that is, it must not
<add> * be {@code null} and must contain at least one non-whitespace character.
<add> * <pre class="code">
<add> * Assert.hasText(name, () -> "Name for account '" + account.getId() + "' must not be empty");
<add> * </pre>
<add> * @param text the String to check
<add> * @param messageSupplier a supplier for the exception message to use if the
<add> * assertion fails
<add> * @see StringUtils#hasText
<add> * @throws IllegalArgumentException if the text does not contain valid text content
<add> */
<add> public static void hasText(String text, Supplier<String> messageSupplier) {
<add> if (!StringUtils.hasText(text)) {
<add> throw new IllegalArgumentException(nullSafeGet(messageSupplier));
<add> }
<add> }
<add>
<add> /**
<add> * Assert that the given String contains valid text content; that is, it must not
<ide> * be {@code null} and must contain at least one non-whitespace character.
<ide> * <pre class="code">Assert.hasText(name, "'name' must not be empty");</pre>
<ide> * @param text the String to check
<ide> public static void hasText(String text, String message) {
<ide> }
<ide>
<ide> /**
<del> * Assert that the given String has valid text content; that is, it must not
<add> * Assert that the given String contains valid text content; that is, it must not
<ide> * be {@code null} and must contain at least one non-whitespace character.
<ide> * <pre class="code">Assert.hasText(name, "'name' must not be empty");</pre>
<ide> * @param text the String to check
<ide> public static void hasText(String text) {
<ide> "[Assertion failed] - this String argument must have text; it must not be null, empty, or blank");
<ide> }
<ide>
<add> /**
<add> * Assert that the given text does not contain the given substring.
<add> * <pre class="code">
<add> * Assert.doesNotContain(name, forbidden, () -> "Name must not contain '" + forbidden + "'");
<add> * </pre>
<add> * @param textToSearch the text to search
<add> * @param substring the substring to find within the text
<add> * @param messageSupplier a supplier for the exception message to use if the
<add> * assertion fails
<add> * @throws IllegalArgumentException if the text contains the substring
<add> */
<add> public static void doesNotContain(String textToSearch, String substring, Supplier<String> messageSupplier) {
<add> if (StringUtils.hasLength(textToSearch) && StringUtils.hasLength(substring) &&
<add> textToSearch.contains(substring)) {
<add> throw new IllegalArgumentException(nullSafeGet(messageSupplier));
<add> }
<add> }
<add>
<ide> /**
<ide> * Assert that the given text does not contain the given substring.
<ide> * <pre class="code">Assert.doesNotContain(name, "rod", "Name must not contain 'rod'");</pre>
<ide> public static void doesNotContain(String textToSearch, String substring, String
<ide> */
<ide> public static void doesNotContain(String textToSearch, String substring) {
<ide> doesNotContain(textToSearch, substring,
<del> "[Assertion failed] - this String argument must not contain the substring [" + substring + "]");
<add> () -> "[Assertion failed] - this String argument must not contain the substring [" + substring + "]");
<add> }
<add>
<add> /**
<add> * Assert that an array contains elements; that is, it must not be
<add> * {@code null} and must contain at least one element.
<add> * <pre class="code">
<add> * Assert.notEmpty(array, () -> "The " + arrayType + " array must contain elements");
<add> * </pre>
<add> * @param array the array to check
<add> * @param messageSupplier a supplier for the exception message to use if the
<add> * assertion fails
<add> * @throws IllegalArgumentException if the object array is {@code null} or contains no elements
<add> */
<add> public static void notEmpty(Object[] array, Supplier<String> messageSupplier) {
<add> if (ObjectUtils.isEmpty(array)) {
<add> throw new IllegalArgumentException(nullSafeGet(messageSupplier));
<add> }
<ide> }
<ide>
<ide> /**
<del> * Assert that an array has elements; that is, it must not be
<del> * {@code null} and must have at least one element.
<del> * <pre class="code">Assert.notEmpty(array, "The array must have elements");</pre>
<add> * Assert that an array contains elements; that is, it must not be
<add> * {@code null} and must contain at least one element.
<add> * <pre class="code">Assert.notEmpty(array, "The array must contain elements");</pre>
<ide> * @param array the array to check
<ide> * @param message the exception message to use if the assertion fails
<del> * @throws IllegalArgumentException if the object array is {@code null} or has no elements
<add> * @throws IllegalArgumentException if the object array is {@code null} or contains no elements
<ide> */
<ide> public static void notEmpty(Object[] array, String message) {
<ide> if (ObjectUtils.isEmpty(array)) {
<ide> public static void notEmpty(Object[] array, String message) {
<ide> }
<ide>
<ide> /**
<del> * Assert that an array has elements; that is, it must not be
<del> * {@code null} and must have at least one element.
<add> * Assert that an array contains elements; that is, it must not be
<add> * {@code null} and must contain at least one element.
<ide> * <pre class="code">Assert.notEmpty(array);</pre>
<ide> * @param array the array to check
<del> * @throws IllegalArgumentException if the object array is {@code null} or has no elements
<add> * @throws IllegalArgumentException if the object array is {@code null} or
<add> * contains no elements
<ide> */
<ide> public static void notEmpty(Object[] array) {
<ide> notEmpty(array, "[Assertion failed] - this array must not be empty: it must contain at least 1 element");
<ide> }
<ide>
<ide> /**
<del> * Assert that an array has no null elements.
<del> * Note: Does not complain if the array is empty!
<del> * <pre class="code">Assert.noNullElements(array, "The array must have non-null elements");</pre>
<add> * Assert that an array contains no {@code null} elements.
<add> * <p>Note: Does not complain if the array is empty!
<add> * <pre class="code">
<add> * Assert.noNullElements(array, () -> "The " + arrayType + " array must contain non-null elements");
<add> * </pre>
<add> * @param array the array to check
<add> * @param messageSupplier a supplier for the exception message to use if the
<add> * assertion fails
<add> * @throws IllegalArgumentException if the object array contains a {@code null} element
<add> */
<add> public static void noNullElements(Object[] array, Supplier<String> messageSupplier) {
<add> if (array != null) {
<add> for (Object element : array) {
<add> if (element == null) {
<add> throw new IllegalArgumentException(nullSafeGet(messageSupplier));
<add> }
<add> }
<add> }
<add> }
<add>
<add> /**
<add> * Assert that an array contains no {@code null} elements.
<add> * <p>Note: Does not complain if the array is empty!
<add> * <pre class="code">Assert.noNullElements(array, "The array must contain non-null elements");</pre>
<ide> * @param array the array to check
<ide> * @param message the exception message to use if the assertion fails
<ide> * @throws IllegalArgumentException if the object array contains a {@code null} element
<ide> public static void noNullElements(Object[] array, String message) {
<ide> }
<ide>
<ide> /**
<del> * Assert that an array has no null elements.
<del> * Note: Does not complain if the array is empty!
<add> * Assert that an array contains no {@code null} elements.
<add> * <p>Note: Does not complain if the array is empty!
<ide> * <pre class="code">Assert.noNullElements(array);</pre>
<ide> * @param array the array to check
<ide> * @throws IllegalArgumentException if the object array contains a {@code null} element
<ide> public static void noNullElements(Object[] array) {
<ide> }
<ide>
<ide> /**
<del> * Assert that a collection has elements; that is, it must not be
<del> * {@code null} and must have at least one element.
<del> * <pre class="code">Assert.notEmpty(collection, "Collection must have elements");</pre>
<add> * Assert that a collection contains elements; that is, it must not be
<add> * {@code null} and must contain at least one element.
<add> * <pre class="code">
<add> * Assert.notEmpty(collection, () -> "The " + collectionType + " collection must contain elements");
<add> * </pre>
<add> * @param collection the collection to check
<add> * @param messageSupplier a supplier for the exception message to use if the
<add> * assertion fails
<add> * @throws IllegalArgumentException if the collection is {@code null} or
<add> * contains no elements
<add> */
<add> public static void notEmpty(Collection<?> collection, Supplier<String> messageSupplier) {
<add> if (CollectionUtils.isEmpty(collection)) {
<add> throw new IllegalArgumentException(nullSafeGet(messageSupplier));
<add> }
<add> }
<add>
<add> /**
<add> * Assert that a collection contains elements; that is, it must not be
<add> * {@code null} and must contain at least one element.
<add> * <pre class="code">Assert.notEmpty(collection, "Collection must contain elements");</pre>
<ide> * @param collection the collection to check
<ide> * @param message the exception message to use if the assertion fails
<del> * @throws IllegalArgumentException if the collection is {@code null} or has no elements
<add> * @throws IllegalArgumentException if the collection is {@code null} or
<add> * contains no elements
<ide> */
<ide> public static void notEmpty(Collection<?> collection, String message) {
<ide> if (CollectionUtils.isEmpty(collection)) {
<ide> public static void notEmpty(Collection<?> collection, String message) {
<ide> }
<ide>
<ide> /**
<del> * Assert that a collection has elements; that is, it must not be
<del> * {@code null} and must have at least one element.
<del> * <pre class="code">Assert.notEmpty(collection, "Collection must have elements");</pre>
<add> * Assert that a collection contains elements; that is, it must not be
<add> * {@code null} and must contain at least one element.
<add> * <pre class="code">Assert.notEmpty(collection, "Collection must contain elements");</pre>
<ide> * @param collection the collection to check
<del> * @throws IllegalArgumentException if the collection is {@code null} or has no elements
<add> * @throws IllegalArgumentException if the collection is {@code null} or
<add> * contains no elements
<ide> */
<ide> public static void notEmpty(Collection<?> collection) {
<ide> notEmpty(collection,
<ide> "[Assertion failed] - this collection must not be empty: it must contain at least 1 element");
<ide> }
<ide>
<ide> /**
<del> * Assert that a Map has entries; that is, it must not be {@code null}
<del> * and must have at least one entry.
<del> * <pre class="code">Assert.notEmpty(map, "Map must have entries");</pre>
<add> * Assert that a Map contains entries; that is, it must not be {@code null}
<add> * and must contain at least one entry.
<add> * <pre class="code">
<add> * Assert.notEmpty(map, () -> "The " + mapType + " map must contain entries");
<add> * </pre>
<add> * @param map the map to check
<add> * @param messageSupplier a supplier for the exception message to use if the
<add> * assertion fails
<add> * @throws IllegalArgumentException if the map is {@code null} or contains no entries
<add> */
<add> public static void notEmpty(Map<?, ?> map, Supplier<String> messageSupplier) {
<add> if (CollectionUtils.isEmpty(map)) {
<add> throw new IllegalArgumentException(nullSafeGet(messageSupplier));
<add> }
<add> }
<add>
<add> /**
<add> * Assert that a Map contains entries; that is, it must not be {@code null}
<add> * and must contain at least one entry.
<add> * <pre class="code">Assert.notEmpty(map, "Map must contain entries");</pre>
<ide> * @param map the map to check
<ide> * @param message the exception message to use if the assertion fails
<del> * @throws IllegalArgumentException if the map is {@code null} or has no entries
<add> * @throws IllegalArgumentException if the map is {@code null} or contains no entries
<ide> */
<ide> public static void notEmpty(Map<?, ?> map, String message) {
<ide> if (CollectionUtils.isEmpty(map)) {
<ide> public static void notEmpty(Map<?, ?> map, String message) {
<ide> }
<ide>
<ide> /**
<del> * Assert that a Map has entries; that is, it must not be {@code null}
<del> * and must have at least one entry.
<add> * Assert that a Map contains entries; that is, it must not be {@code null}
<add> * and must contain at least one entry.
<ide> * <pre class="code">Assert.notEmpty(map);</pre>
<ide> * @param map the map to check
<del> * @throws IllegalArgumentException if the map is {@code null} or has no entries
<add> * @throws IllegalArgumentException if the map is {@code null} or contains no entries
<ide> */
<ide> public static void notEmpty(Map<?, ?> map) {
<ide> notEmpty(map, "[Assertion failed] - this map must not be empty; it must contain at least one entry");
<ide> public static void notEmpty(Map<?, ?> map) {
<ide> /**
<ide> * Assert that the provided object is an instance of the provided class.
<ide> * <pre class="code">Assert.instanceOf(Foo.class, foo);</pre>
<del> * @param clazz the required class
<add> * @param type the type to check against
<ide> * @param obj the object to check
<del> * @throws IllegalArgumentException if the object is not an instance of clazz
<add> * @throws IllegalArgumentException if the object is not an instance of type
<ide> * @see Class#isInstance
<ide> */
<del> public static void isInstanceOf(Class<?> clazz, Object obj) {
<del> isInstanceOf(clazz, obj, "");
<add> public static void isInstanceOf(Class<?> type, Object obj) {
<add> isInstanceOf(type, obj, "");
<ide> }
<ide>
<ide> /**
<ide> * Assert that the provided object is an instance of the provided class.
<del> * <pre class="code">Assert.instanceOf(Foo.class, foo);</pre>
<add> * <pre class="code">
<add> * Assert.instanceOf(Foo.class, foo, () -> "Processing " + Foo.class.getSimpleName() + ":");
<add> * </pre>
<add> * @param type the type to check against
<add> * @param obj the object to check
<add> * @param messageSupplier a supplier for the exception message to use if the
<add> * assertion fails; the message will be prepended to the message generated
<add> * by this method in order to provide further context. It should normally end
<add> * in ":" or "." so that the generated message looks OK when appended to it.
<add> * @throws IllegalArgumentException if the object is not an instance of type
<add> * @see Class#isInstance
<add> */
<add> public static void isInstanceOf(Class<?> type, Object obj, Supplier<String> messageSupplier) {
<add> notNull(type, "Type to check against must not be null");
<add> if (!type.isInstance(obj)) {
<add> isInstanceCheckFailed(type, obj, nullSafeGet(messageSupplier));
<add> }
<add> }
<add>
<add> /**
<add> * Assert that the provided object is an instance of the provided class.
<add> * <pre class="code">Assert.instanceOf(Foo.class, foo, "Processing Foo:");</pre>
<ide> * @param type the type to check against
<ide> * @param obj the object to check
<del> * @param message a message which will be prepended to the message produced by
<del> * the function itself, and which may be used to provide context. It should
<del> * normally end in ":" or "." so that the generated message looks OK when
<del> * appended to it.
<del> * @throws IllegalArgumentException if the object is not an instance of clazz
<add> * @param message a message which will be prepended to the message generated
<add> * by this method in order to provide further context. It should normally end
<add> * in ":" or "." so that the generated message looks OK when appended to it.
<add> * @throws IllegalArgumentException if the object is not an instance of type
<ide> * @see Class#isInstance
<ide> */
<ide> public static void isInstanceOf(Class<?> type, Object obj, String message) {
<ide> notNull(type, "Type to check against must not be null");
<ide> if (!type.isInstance(obj)) {
<del> throw new IllegalArgumentException(
<del> (StringUtils.hasLength(message) ? message + " " : "") +
<del> "Object of class [" + (obj != null ? obj.getClass().getName() : "null") +
<del> "] must be an instance of " + type);
<add> isInstanceCheckFailed(type, obj, message);
<ide> }
<ide> }
<ide>
<add> private static void isInstanceCheckFailed(Class<?> type, Object obj, String message) {
<add> throw new IllegalArgumentException(
<add> (StringUtils.hasLength(message) ? message + " " : "") +
<add> "Object of class [" + (obj != null ? obj.getClass().getName() : "null") +
<add> "] must be an instance of " + type);
<add> }
<add>
<ide> /**
<ide> * Assert that {@code superType.isAssignableFrom(subType)} is {@code true}.
<ide> * <pre class="code">Assert.isAssignable(Number.class, myClass);</pre>
<ide> public static void isAssignable(Class<?> superType, Class<?> subType) {
<ide> isAssignable(superType, subType, "");
<ide> }
<ide>
<add> /**
<add> * Assert that {@code superType.isAssignableFrom(subType)} is {@code true}.
<add> * <pre class="code">
<add> * Assert.isAssignable(Number.class, myClass, () -> "Processing " + myClass.getSimpleName() + ":");
<add> * </pre>
<add> * @param superType the super type to check against
<add> * @param subType the sub type to check
<add> * @param messageSupplier a supplier for the exception message to use if the
<add> * assertion fails; the message will be prepended to the message generated
<add> * by this method in order to provide further context. It should normally end
<add> * in ":" or "." so that the generated message looks OK when appended to it.
<add> * @throws IllegalArgumentException if the classes are not assignable
<add> */
<add> public static void isAssignable(Class<?> superType, Class<?> subType, Supplier<String> messageSupplier) {
<add> notNull(superType, "Super type to check against must not be null");
<add> if (subType == null || !superType.isAssignableFrom(subType)) {
<add> isAssignableCheckFailed(superType, subType, nullSafeGet(messageSupplier));
<add> }
<add> }
<add>
<ide> /**
<ide> * Assert that {@code superType.isAssignableFrom(subType)} is {@code true}.
<ide> * <pre class="code">Assert.isAssignable(Number.class, myClass);</pre>
<ide> * @param superType the super type to check against
<ide> * @param subType the sub type to check
<del> * @param message a message which will be prepended to the message produced by
<del> * the function itself, and which may be used to provide context. It should
<del> * normally end in ":" or "." so that the generated message looks OK when
<del> * appended to it.
<add> * @param message a message which will be prepended to the message generated
<add> * by this method in order to provide further context. It should normally end
<add> * in ":" or "." so that the generated message looks OK when appended to it.
<ide> * @throws IllegalArgumentException if the classes are not assignable
<ide> */
<ide> public static void isAssignable(Class<?> superType, Class<?> subType, String message) {
<del> notNull(superType, "Type to check against must not be null");
<add> notNull(superType, "Super type to check against must not be null");
<ide> if (subType == null || !superType.isAssignableFrom(subType)) {
<del> throw new IllegalArgumentException((StringUtils.hasLength(message) ? message + " " : "") +
<del> subType + " is not assignable to " + superType);
<add> isAssignableCheckFailed(superType, subType, message);
<ide> }
<ide> }
<ide>
<add> private static void isAssignableCheckFailed(Class<?> superType, Class<?> subType, String message) {
<add> throw new IllegalArgumentException((StringUtils.hasLength(message) ? message + " " : "") +
<add> subType + " is not assignable to " + superType);
<add> }
<add>
<ide> /**
<del> * Assert a boolean expression, throwing {@code IllegalStateException}
<del> * if the test result is {@code false}. Call isTrue if you wish to
<del> * throw IllegalArgumentException on an assertion failure.
<add> * Assert a boolean expression, throwing an {@code IllegalStateException}
<add> * if the expression evaluates to {@code false}.
<add> * <p>Call {@link #isTrue} if you wish to throw an {@code IllegalArgumentException}
<add> * on an assertion failure.
<add> * <pre class="code">
<add> * Assert.state(id == null,
<add> * () -> "ID for " + entity.getName() + " must not already be initialized");
<add> * </pre>
<add> * @param expression a boolean expression
<add> * @param messageSupplier a supplier for the exception message to use if the
<add> * assertion fails
<add> * @throws IllegalStateException if {@code expression} is {@code false}
<add> */
<add> public static void state(boolean expression, Supplier<String> messageSupplier) {
<add> if (!expression) {
<add> throw new IllegalStateException(nullSafeGet(messageSupplier));
<add> }
<add> }
<add>
<add> /**
<add> * Assert a boolean expression, throwing an {@code IllegalStateException}
<add> * if the expression evaluates to {@code false}.
<add> * <p>Call {@link #isTrue} if you wish to throw an {@code IllegalArgumentException}
<add> * on an assertion failure.
<ide> * <pre class="code">Assert.state(id == null, "The id property must not already be initialized");</pre>
<ide> * @param expression a boolean expression
<ide> * @param message the exception message to use if the assertion fails
<del> * @throws IllegalStateException if expression is {@code false}
<add> * @throws IllegalStateException if {@code expression} is {@code false}
<ide> */
<ide> public static void state(boolean expression, String message) {
<ide> if (!expression) {
<ide> public static void state(boolean expression, String message) {
<ide> }
<ide>
<ide> /**
<del> * Assert a boolean expression, throwing {@link IllegalStateException}
<del> * if the test result is {@code false}.
<del> * <p>Call {@link #isTrue(boolean)} if you wish to
<del> * throw {@link IllegalArgumentException} on an assertion failure.
<add> * Assert a boolean expression, throwing an {@link IllegalStateException}
<add> * if the expression evaluates to {@code false}.
<add> * <p>Call {@link #isTrue} if you wish to throw an {@code IllegalArgumentException}
<add> * on an assertion failure.
<ide> * <pre class="code">Assert.state(id == null);</pre>
<ide> * @param expression a boolean expression
<del> * @throws IllegalStateException if the supplied expression is {@code false}
<add> * @throws IllegalStateException if {@code expression} is {@code false}
<ide> */
<ide> public static void state(boolean expression) {
<ide> state(expression, "[Assertion failed] - this state invariant must be true");
<ide> }
<ide>
<add> private static String nullSafeGet(Supplier<String> messageSupplier) {
<add> return (messageSupplier != null ? messageSupplier.get() : null);
<add> }
<add>
<ide> }
<ide><path>spring-core/src/test/java/org/springframework/util/AssertTests.java
<ide>
<ide> package org.springframework.util;
<ide>
<del>import java.util.ArrayList;
<ide> import java.util.Collection;
<del>import java.util.HashMap;
<del>import java.util.HashSet;
<del>import java.util.List;
<ide> import java.util.Map;
<del>import java.util.Set;
<add>import java.util.function.Supplier;
<ide>
<ide> import org.junit.Rule;
<ide> import org.junit.Test;
<ide> import org.junit.rules.ExpectedException;
<ide>
<add>import static java.util.Collections.*;
<add>import static org.hamcrest.CoreMatchers.*;
<add>
<ide> /**
<ide> * Unit tests for the {@link Assert} class.
<ide> *
<ide> public class AssertTests {
<ide>
<ide> @Rule
<del> public ExpectedException thrown = ExpectedException.none();
<add> public final ExpectedException thrown = ExpectedException.none();
<ide>
<ide>
<ide> @Test
<del> public void instanceOf() {
<del> Assert.isInstanceOf(HashSet.class, new HashSet<>());
<add> public void isTrue() {
<add> Assert.isTrue(true);
<ide> }
<ide>
<del> @Test(expected = IllegalArgumentException.class)
<del> public void instanceOfWithTypeMismatch() {
<del> Assert.isInstanceOf(HashMap.class, new HashSet<>());
<add> @Test
<add> public void isTrueWithFalseExpression() {
<add> thrown.expect(IllegalArgumentException.class);
<add> Assert.isTrue(false);
<ide> }
<ide>
<ide> @Test
<del> public void instanceOfNoMessage() throws Exception {
<del> thrown.expect(IllegalArgumentException.class);
<del> thrown.expectMessage("Object of class [java.lang.Object] must be an instance " +
<del> "of interface java.util.Set");
<del> Assert.isInstanceOf(Set.class, new Object(), null);
<add> public void isTrueWithMessageSupplier() {
<add> Assert.isTrue(true, () -> "enigma");
<ide> }
<ide>
<ide> @Test
<del> public void instanceOfMessage() throws Exception {
<add> public void isTrueWithFalseAndMessageSupplier() {
<ide> thrown.expect(IllegalArgumentException.class);
<del> thrown.expectMessage("Custom message. Object of class [java.lang.Object] must " +
<del> "be an instance of interface java.util.Set");
<del> Assert.isInstanceOf(Set.class, new Object(), "Custom message.");
<add> thrown.expectMessage("enigma");
<add> Assert.isTrue(false, () -> "enigma");
<ide> }
<ide>
<ide> @Test
<del> public void isNullDoesNotThrowExceptionIfArgumentIsNullWithMessage() {
<del> Assert.isNull(null, "Bla");
<add> public void isTrueWithFalseAndNullMessageSupplier() {
<add> thrown.expect(IllegalArgumentException.class);
<add> thrown.expectMessage(equalTo(null));
<add> Assert.isTrue(false, (Supplier<String>) null);
<ide> }
<ide>
<ide> @Test
<del> public void isNullDoesNotThrowExceptionIfArgumentIsNull() {
<add> public void isNull() {
<ide> Assert.isNull(null);
<ide> }
<ide>
<del> @Test(expected = IllegalArgumentException.class)
<del> public void isNullThrowsExceptionIfArgumentIsNotNull() {
<add> @Test
<add> public void isNullWithMessage() {
<add> Assert.isNull(null, "Bla");
<add> }
<add>
<add> @Test
<add> public void isNullWithNonNullObject() {
<add> thrown.expect(IllegalArgumentException.class);
<ide> Assert.isNull(new Object());
<ide> }
<ide>
<del> @Test(expected = IllegalArgumentException.class)
<del> public void isTrueWithFalseExpressionThrowsException() throws Exception {
<del> Assert.isTrue(false);
<add> @Test
<add> public void isNullWithMessageSupplier() {
<add> Assert.isNull(null, () -> "enigma");
<ide> }
<ide>
<ide> @Test
<del> public void isTrueWithTrueExpressionSunnyDay() throws Exception {
<del> Assert.isTrue(true);
<add> public void isNullWithNonNullObjectAndMessageSupplier() {
<add> thrown.expect(IllegalArgumentException.class);
<add> thrown.expectMessage("enigma");
<add> Assert.isNull("foo", () -> "enigma");
<ide> }
<ide>
<del> @Test(expected = IllegalArgumentException.class)
<del> public void testHasLengthWithNullStringThrowsException() throws Exception {
<del> Assert.hasLength(null);
<add> @Test
<add> public void isNullWithNonNullObjectAndNullMessageSupplier() {
<add> thrown.expect(IllegalArgumentException.class);
<add> thrown.expectMessage(equalTo(null));
<add> Assert.isNull("foo", (Supplier<String>) null);
<ide> }
<ide>
<del> @Test(expected = IllegalArgumentException.class)
<del> public void hasLengthWithEmptyStringThrowsException() throws Exception {
<del> Assert.hasLength("");
<add> @Test
<add> public void notNull() {
<add> Assert.notNull("foo");
<ide> }
<ide>
<ide> @Test
<del> public void hasLengthWithWhitespaceOnlyStringDoesNotThrowException() throws Exception {
<del> Assert.hasLength("\t ");
<add> public void notNullWithMessageSupplier() {
<add> Assert.notNull("foo", () -> "enigma");
<add> }
<add>
<add> @Test
<add> public void notNullWithNullAndMessageSupplier() {
<add> thrown.expect(IllegalArgumentException.class);
<add> thrown.expectMessage("enigma");
<add> Assert.notNull(null, () -> "enigma");
<add> }
<add>
<add> @Test
<add> public void notNullWithNullAndNullMessageSupplier() {
<add> thrown.expect(IllegalArgumentException.class);
<add> thrown.expectMessage(equalTo(null));
<add> Assert.notNull(null, (Supplier<String>) null);
<ide> }
<ide>
<ide> @Test
<del> public void hasLengthSunnyDay() throws Exception {
<add> public void hasLength() {
<ide> Assert.hasLength("I Heart ...");
<ide> }
<ide>
<ide> @Test
<del> public void doesNotContainWithNullSearchStringDoesNotThrowException() throws Exception {
<add> public void hasLengthWithWhitespaceOnly() {
<add> Assert.hasLength("\t ");
<add> }
<add>
<add> @Test
<add> public void hasLengthWithEmptyString() {
<add> thrown.expect(IllegalArgumentException.class);
<add> Assert.hasLength("");
<add> }
<add>
<add> @Test
<add> public void hasLengthWithNull() {
<add> thrown.expect(IllegalArgumentException.class);
<add> Assert.hasLength(null);
<add> }
<add>
<add> @Test
<add> public void hasLengthWithMessageSupplier() {
<add> Assert.hasLength("foo", () -> "enigma");
<add> }
<add>
<add> @Test
<add> public void hasLengthWithWhitespaceOnlyAndMessageSupplier() {
<add> Assert.hasLength("\t", () -> "enigma");
<add> }
<add>
<add> @Test
<add> public void hasLengthWithEmptyStringAndMessageSupplier() {
<add> thrown.expect(IllegalArgumentException.class);
<add> thrown.expectMessage("enigma");
<add> Assert.hasLength("", () -> "enigma");
<add> }
<add>
<add> @Test
<add> public void hasLengthWithNullAndMessageSupplier() {
<add> thrown.expect(IllegalArgumentException.class);
<add> thrown.expectMessage("enigma");
<add> Assert.hasLength(null, () -> "enigma");
<add> }
<add>
<add> @Test
<add> public void hasLengthWithNullAndNullMessageSupplier() {
<add> thrown.expect(IllegalArgumentException.class);
<add> thrown.expectMessage(equalTo(null));
<add> Assert.hasLength(null, (Supplier<String>) null);
<add> }
<add>
<add> @Test
<add> public void hasText() {
<add> Assert.hasText("foo");
<add> }
<add>
<add> @Test
<add> public void hasTextWithWhitespaceOnly() {
<add> thrown.expect(IllegalArgumentException.class);
<add> thrown.expectMessage("enigma");
<add> Assert.hasText("\t ", "enigma");
<add> }
<add>
<add> @Test
<add> public void hasTextWithEmptyString() {
<add> thrown.expect(IllegalArgumentException.class);
<add> thrown.expectMessage("enigma");
<add> Assert.hasText("", "enigma");
<add> }
<add>
<add> @Test
<add> public void hasTextWithNullAndMessage() {
<add> thrown.expect(IllegalArgumentException.class);
<add> thrown.expectMessage("enigma");
<add> Assert.hasText(null, "enigma");
<add> }
<add>
<add> @Test
<add> public void hasTextWithMessageSupplier() {
<add> Assert.hasText("foo", () -> "enigma");
<add> }
<add>
<add> @Test
<add> public void hasTextWithWhitespaceOnlyAndMessageSupplier() {
<add> thrown.expect(IllegalArgumentException.class);
<add> thrown.expectMessage("enigma");
<add> Assert.hasText("\t ", () -> "enigma");
<add> }
<add>
<add> @Test
<add> public void hasTextWithEmptyStringAndMessageSupplier() {
<add> thrown.expect(IllegalArgumentException.class);
<add> thrown.expectMessage("enigma");
<add> Assert.hasText("", () -> "enigma");
<add> }
<add>
<add> @Test
<add> public void hasTextWithNullAndMessageSupplier() {
<add> thrown.expect(IllegalArgumentException.class);
<add> thrown.expectMessage("enigma");
<add> Assert.hasText(null, () -> "enigma");
<add> }
<add>
<add> @Test
<add> public void hasTextWithNullAndNullMessageSupplier() {
<add> thrown.expect(IllegalArgumentException.class);
<add> thrown.expectMessage(equalTo(null));
<add> Assert.hasText(null, (Supplier<String>) null);
<add> }
<add>
<add> @Test
<add> public void doesNotContainWithNullSearchString() {
<ide> Assert.doesNotContain(null, "rod");
<ide> }
<ide>
<ide> @Test
<del> public void doesNotContainWithNullSubstringDoesNotThrowException() throws Exception {
<del> Assert.doesNotContain("A cool chick's name is Brod. ", null);
<add> public void doesNotContainWithNullSubstring() {
<add> Assert.doesNotContain("A cool chick's name is Brod.", null);
<add> }
<add>
<add> @Test
<add> public void doesNotContainWithEmptySubstring() {
<add> Assert.doesNotContain("A cool chick's name is Brod.", "");
<add> }
<add>
<add> @Test
<add> public void doesNotContainWithNullSearchStringAndNullSubstringAndMessage() {
<add> Assert.doesNotContain(null, null, "enigma");
<add> }
<add>
<add> @Test
<add> public void doesNotContainWithMessageSupplier() {
<add> Assert.doesNotContain("foo", "bar", () -> "enigma");
<add> }
<add>
<add> @Test
<add> public void doesNotContainWithNullSearchStringAndMessageSupplier() {
<add> Assert.doesNotContain(null, "bar", () -> "enigma");
<add> }
<add>
<add> @Test
<add> public void doesNotContainWithNullSubstringAndMessageSupplier() {
<add> Assert.doesNotContain("foo", null, () -> "enigma");
<add> }
<add>
<add> @Test
<add> public void doesNotContainWithNullSearchStringAndNullSubstringAndMessageSupplier() {
<add> Assert.doesNotContain(null, null, () -> "enigma");
<add> }
<add>
<add> @Test
<add> public void doesNotContainWithSubstringPresentInSearchStringAndMessageSupplier() {
<add> thrown.expect(IllegalArgumentException.class);
<add> thrown.expectMessage("enigma");
<add> Assert.doesNotContain("1234", "23", () -> "enigma");
<add> }
<add>
<add> @Test
<add> public void doesNotContainWithNullMessageSupplier() {
<add> thrown.expect(IllegalArgumentException.class);
<add> thrown.expectMessage(equalTo(null));
<add> Assert.doesNotContain("1234", "23", (Supplier<String>) null);
<add> }
<add>
<add> @Test
<add> public void notEmptyArray() {
<add> Assert.notEmpty(new String[] { "1234" });
<add> }
<add>
<add> @Test
<add> public void notEmptyArrayWithMessageSupplier() {
<add> Assert.notEmpty(new String[] { "1234" }, () -> "enigma");
<add> }
<add>
<add> @Test
<add> public void notEmptyArrayWithEmptyArrayAndMessageSupplier() {
<add> thrown.expect(IllegalArgumentException.class);
<add> thrown.expectMessage("enigma");
<add> Assert.notEmpty(new String[] {}, () -> "enigma");
<add> }
<add>
<add> @Test
<add> public void notEmptyArrayWithNullArrayAndMessageSupplier() {
<add> thrown.expect(IllegalArgumentException.class);
<add> thrown.expectMessage("enigma");
<add> Assert.notEmpty((Object[]) null, () -> "enigma");
<add> }
<add>
<add> @Test
<add> public void notEmptyArrayWithEmptyArrayAndNullMessageSupplier() {
<add> thrown.expect(IllegalArgumentException.class);
<add> thrown.expectMessage(equalTo(null));
<add> Assert.notEmpty(new String[] {}, (Supplier<String>) null);
<add> }
<add>
<add> @Test
<add> public void noNullElements() {
<add> Assert.noNullElements(new String[] { "1234" }, "enigma");
<add> }
<add>
<add> @Test
<add> public void noNullElementsWithEmptyArray() {
<add> Assert.noNullElements(new String[] {}, "enigma");
<add> }
<add>
<add> @Test
<add> public void noNullElementsWithMessageSupplier() {
<add> Assert.noNullElements(new String[] { "1234" }, () -> "enigma");
<add> }
<add>
<add> @Test
<add> public void noNullElementsWithEmptyArrayAndMessageSupplier() {
<add> Assert.noNullElements(new String[] {}, () -> "enigma");
<add> }
<add>
<add> @Test
<add> public void noNullElementsWithNullArrayAndMessageSupplier() {
<add> Assert.noNullElements((Object[]) null, () -> "enigma");
<add> }
<add>
<add> @Test
<add> public void noNullElementsWithNullElementsAndMessageSupplier() {
<add> thrown.expect(IllegalArgumentException.class);
<add> thrown.expectMessage("enigma");
<add> Assert.noNullElements(new String[] { "foo", null, "bar" }, () -> "enigma");
<add> }
<add>
<add> @Test
<add> public void noNullElementsWithNullElementsAndNullMessageSupplier() {
<add> thrown.expect(IllegalArgumentException.class);
<add> thrown.expectMessage(equalTo(null));
<add> Assert.noNullElements(new String[] { "foo", null, "bar" }, (Supplier<String>) null);
<ide> }
<ide>
<ide> @Test
<del> public void doesNotContainWithEmptySubstringDoesNotThrowException() throws Exception {
<del> Assert.doesNotContain("A cool chick's name is Brod. ", "");
<add> public void notEmptyCollection() {
<add> Assert.notEmpty(singletonList("foo"));
<ide> }
<ide>
<del> @Test(expected = IllegalArgumentException.class)
<del> public void assertNotEmptyWithNullCollectionThrowsException() throws Exception {
<add> @Test
<add> public void notEmptyCollectionWithEmptyCollection() {
<add> thrown.expect(IllegalArgumentException.class);
<add> Assert.notEmpty(emptyList());
<add> }
<add>
<add> @Test
<add> public void notEmptyCollectionWithNullCollection() {
<add> thrown.expect(IllegalArgumentException.class);
<ide> Assert.notEmpty((Collection<?>) null);
<ide> }
<ide>
<del> @Test(expected = IllegalArgumentException.class)
<del> public void assertNotEmptyWithEmptyCollectionThrowsException() throws Exception {
<del> Assert.notEmpty(new ArrayList<>());
<add> @Test
<add> public void notEmptyCollectionWithMessageSupplier() {
<add> Assert.notEmpty(singletonList("foo"), () -> "enigma");
<add> }
<add>
<add> @Test
<add> public void notEmptyCollectionWithEmptyCollectionAndMessageSupplier() {
<add> thrown.expect(IllegalArgumentException.class);
<add> thrown.expectMessage("enigma");
<add> Assert.notEmpty(emptyList(), () -> "enigma");
<add> }
<add>
<add> @Test
<add> public void notEmptyCollectionWithNullCollectionAndMessageSupplier() {
<add> thrown.expect(IllegalArgumentException.class);
<add> thrown.expectMessage("enigma");
<add> Assert.notEmpty((Collection<?>) null, () -> "enigma");
<add> }
<add>
<add> @Test
<add> public void notEmptyCollectionWithEmptyCollectionAndNullMessageSupplier() {
<add> thrown.expect(IllegalArgumentException.class);
<add> thrown.expectMessage(equalTo(null));
<add> Assert.notEmpty(emptyList(), (Supplier<String>) null);
<ide> }
<ide>
<ide> @Test
<del> public void assertNotEmptyWithCollectionSunnyDay() throws Exception {
<del> List<String> collection = new ArrayList<>();
<del> collection.add("");
<del> Assert.notEmpty(collection);
<add> public void notEmptyMap() {
<add> Assert.notEmpty(singletonMap("foo", "bar"));
<ide> }
<ide>
<del> @Test(expected = IllegalArgumentException.class)
<del> public void assertNotEmptyWithNullMapThrowsException() throws Exception {
<add> @Test
<add> public void notEmptyMapWithNullMap() {
<add> thrown.expect(IllegalArgumentException.class);
<ide> Assert.notEmpty((Map<?, ?>) null);
<ide> }
<ide>
<del> @Test(expected = IllegalArgumentException.class)
<del> public void assertNotEmptyWithEmptyMapThrowsException() throws Exception {
<del> Assert.notEmpty(new HashMap<>());
<add> @Test
<add> public void notEmptyMapWithEmptyMap() {
<add> thrown.expect(IllegalArgumentException.class);
<add> Assert.notEmpty(emptyMap());
<add> }
<add>
<add> @Test
<add> public void notEmptyMapWithMessageSupplier() {
<add> Assert.notEmpty(singletonMap("foo", "bar"), () -> "enigma");
<add> }
<add>
<add> @Test
<add> public void notEmptyMapWithEmptyMapAndMessageSupplier() {
<add> thrown.expect(IllegalArgumentException.class);
<add> thrown.expectMessage("enigma");
<add> Assert.notEmpty(emptyMap(), () -> "enigma");
<add> }
<add>
<add> @Test
<add> public void notEmptyMapWithNullMapAndMessageSupplier() {
<add> thrown.expect(IllegalArgumentException.class);
<add> thrown.expectMessage("enigma");
<add> Assert.notEmpty((Map<?, ?>) null, () -> "enigma");
<add> }
<add>
<add> @Test
<add> public void notEmptyMapWithEmptyMapAndNullMessageSupplier() {
<add> thrown.expect(IllegalArgumentException.class);
<add> thrown.expectMessage(equalTo(null));
<add> Assert.notEmpty(emptyMap(), (Supplier<String>) null);
<add> }
<add>
<add> @Test
<add> public void isInstanceOf() {
<add> Assert.isInstanceOf(String.class, "foo");
<ide> }
<ide>
<ide> @Test
<del> public void assertNotEmptyWithMapSunnyDay() throws Exception {
<del> Map<String, String> map = new HashMap<>();
<del> map.put("", "");
<del> Assert.notEmpty(map);
<add> public void isInstanceOfWithNullType() {
<add> thrown.expect(IllegalArgumentException.class);
<add> thrown.expectMessage("Type to check against must not be null");
<add> Assert.isInstanceOf(null, "foo");
<ide> }
<ide>
<del> @Test(expected = IllegalArgumentException.class)
<del> public void isInstanceofClassWithNullInstanceThrowsException() throws Exception {
<add> @Test
<add> public void isInstanceOfWithNullInstance() {
<add> thrown.expect(IllegalArgumentException.class);
<add> thrown.expectMessage("Object of class [null] must be an instance of class java.lang.String");
<ide> Assert.isInstanceOf(String.class, null);
<ide> }
<ide>
<del> @Test(expected = IllegalStateException.class)
<del> public void stateWithFalseExpressionThrowsException() throws Exception {
<del> Assert.state(false);
<add> @Test
<add> public void isInstanceOfWithTypeMismatchAndNullMessage() {
<add> thrown.expect(IllegalArgumentException.class);
<add> thrown.expectMessage("Object of class [java.lang.Long] must be an instance of class java.lang.String");
<add> Assert.isInstanceOf(String.class, 42L, (String) null);
<ide> }
<ide>
<ide> @Test
<del> public void stateWithTrueExpressionSunnyDay() throws Exception {
<add> public void isInstanceOfWithTypeMismatchAndCustomMessage() {
<add> thrown.expect(IllegalArgumentException.class);
<add> thrown.expectMessage(
<add> "Custom message. Object of class [java.lang.Long] must be an instance of class java.lang.String");
<add> Assert.isInstanceOf(String.class, 42L, "Custom message.");
<add> }
<add>
<add> @Test
<add> public void isInstanceOfWithMessageSupplier() {
<add> Assert.isInstanceOf(String.class, "foo", () -> "enigma");
<add> }
<add>
<add> @Test
<add> public void isInstanceOfWithNullTypeAndMessageSupplier() {
<add> thrown.expect(IllegalArgumentException.class);
<add> thrown.expectMessage("Type to check against must not be null");
<add> Assert.isInstanceOf(null, "foo", () -> "enigma");
<add> }
<add>
<add> @Test
<add> public void isInstanceOfWithNullInstanceAndMessageSupplier() {
<add> thrown.expect(IllegalArgumentException.class);
<add> thrown.expectMessage("enigma: Object of class [null] must be an instance of class java.lang.String");
<add> Assert.isInstanceOf(String.class, null, () -> "enigma:");
<add> }
<add>
<add> @Test
<add> public void isInstanceOfWithTypeMismatchAndNullMessageSupplier() {
<add> thrown.expect(IllegalArgumentException.class);
<add> thrown.expectMessage("Object of class [java.lang.Long] must be an instance of class java.lang.String");
<add> Assert.isInstanceOf(String.class, 42L, (Supplier<String>) null);
<add> }
<add>
<add> @Test
<add> public void isInstanceOfWithTypeMismatchAndMessageSupplier() {
<add> thrown.expect(IllegalArgumentException.class);
<add> thrown.expectMessage("enigma: Object of class [java.lang.Long] must be an instance of class java.lang.String");
<add> Assert.isInstanceOf(String.class, 42L, () -> "enigma:");
<add> }
<add>
<add> @Test
<add> public void isAssignable() {
<add> Assert.isAssignable(Number.class, Integer.class);
<add> }
<add>
<add> @Test
<add> public void isAssignableWithNullSupertype() {
<add> thrown.expect(IllegalArgumentException.class);
<add> thrown.expectMessage("Super type to check against must not be null");
<add> Assert.isAssignable(null, Integer.class);
<add> }
<add>
<add> @Test
<add> public void isAssignableWithNullSubtype() {
<add> thrown.expect(IllegalArgumentException.class);
<add> thrown.expectMessage("null is not assignable to class java.lang.Integer");
<add> Assert.isAssignable(Integer.class, null);
<add> }
<add>
<add> @Test
<add> public void isAssignableWithTypeMismatchAndNullMessage() {
<add> thrown.expect(IllegalArgumentException.class);
<add> thrown.expectMessage("class java.lang.Integer is not assignable to class java.lang.String");
<add> Assert.isAssignable(String.class, Integer.class, (String) null);
<add> }
<add>
<add> @Test
<add> public void isAssignableWithTypeMismatchAndCustomMessage() {
<add> thrown.expect(IllegalArgumentException.class);
<add> thrown.expectMessage("enigma: class java.lang.Integer is not assignable to class java.lang.String");
<add> Assert.isAssignable(String.class, Integer.class, "enigma:");
<add> }
<add>
<add> @Test
<add> public void isAssignableWithMessageSupplier() {
<add> Assert.isAssignable(Number.class, Integer.class, () -> "enigma");
<add> }
<add>
<add> @Test
<add> public void isAssignableWithNullSupertypeAndMessageSupplier() {
<add> thrown.expect(IllegalArgumentException.class);
<add> thrown.expectMessage("Super type to check against must not be null");
<add> Assert.isAssignable(null, Integer.class, () -> "enigma");
<add> }
<add>
<add> @Test
<add> public void isAssignableWithNullSubtypeAndMessageSupplier() {
<add> thrown.expect(IllegalArgumentException.class);
<add> thrown.expectMessage("enigma: null is not assignable to class java.lang.Integer");
<add> Assert.isAssignable(Integer.class, null, () -> "enigma:");
<add> }
<add>
<add> @Test
<add> public void isAssignableWithTypeMismatchAndNullMessageSupplier() {
<add> thrown.expect(IllegalArgumentException.class);
<add> thrown.expectMessage("class java.lang.Integer is not assignable to class java.lang.String");
<add> Assert.isAssignable(String.class, Integer.class, (Supplier<String>) null);
<add> }
<add>
<add> @Test
<add> public void isAssignableWithTypeMismatchAndMessageSupplier() {
<add> thrown.expect(IllegalArgumentException.class);
<add> thrown.expectMessage("enigma: class java.lang.Integer is not assignable to class java.lang.String");
<add> Assert.isAssignable(String.class, Integer.class, () -> "enigma:");
<add> }
<add>
<add> @Test
<add> public void state() {
<ide> Assert.state(true);
<ide> }
<ide>
<add> @Test
<add> public void stateWithFalseExpression() {
<add> thrown.expect(IllegalStateException.class);
<add> Assert.state(false);
<add> }
<add>
<add> @Test
<add> public void stateWithMessageSupplier() {
<add> Assert.state(true, () -> "enigma");
<add> }
<add>
<add> @Test
<add> public void stateWithFalseExpressionAndMessageSupplier() {
<add> thrown.expect(IllegalStateException.class);
<add> thrown.expectMessage("enigma");
<add> Assert.state(false, () -> "enigma");
<add> }
<add>
<add> @Test
<add> public void stateWithFalseExpressionAndNullMessageSupplier() {
<add> thrown.expect(IllegalStateException.class);
<add> thrown.expectMessage(equalTo(null));
<add> Assert.state(false, (Supplier<String>) null);
<add> }
<add>
<ide> } | 2 |
Ruby | Ruby | fix small typos in routing docs | 746331711585cfcb158dafcaf3ea5d60d9825ed2 | <ide><path>actionpack/lib/action_dispatch/routing/mapper.rb
<ide> def root(options = {})
<ide> # A pattern can also point to a +Rack+ endpoint i.e. anything that
<ide> # responds to +call+:
<ide> #
<del> # match 'photos/:id' => lambda {|hash| [200, {}, "Coming soon" }
<add> # match 'photos/:id' => lambda {|hash| [200, {}, "Coming soon"] }
<ide> # match 'photos/:id' => PhotoRackApp
<ide> # # Yes, controller actions are just rack endpoints
<ide> # match 'photos/:id' => PhotosController.action(:show)
<ide> def resource(*resources, &block)
<ide> # creates seven different routes in your application, all mapping to
<ide> # the +Photos+ controller:
<ide> #
<add> # GET /photos
<ide> # GET /photos/new
<ide> # POST /photos
<ide> # GET /photos/:id
<ide> def resource(*resources, &block)
<ide> #
<ide> # This generates the following comments routes:
<ide> #
<add> # GET /photos/:photo_id/comments
<ide> # GET /photos/:photo_id/comments/new
<ide> # POST /photos/:photo_id/comments
<ide> # GET /photos/:photo_id/comments/:id | 1 |
Java | Java | fix artsurfaceview with nodes | 7cc4e0364abbfe0a71ec47eac98f454166834028 | <ide><path>ReactAndroid/src/main/java/com/facebook/react/flat/FlatARTSurfaceViewManager.java
<add>/**
<add> * Copyright (c) 2015-present, Facebook, Inc.
<add> * All rights reserved.
<add> *
<add> * This source code is licensed under the BSD-style license found in the
<add> * LICENSE file in the root directory of this source tree. An additional grant
<add> * of patent rights can be found in the PATENTS file in the same directory.
<add> */
<add>
<add>package com.facebook.react.flat;
<add>
<add>import android.graphics.Bitmap;
<add>
<add>import com.facebook.csslayout.CSSMeasureMode;
<add>import com.facebook.csslayout.CSSNode;
<add>import com.facebook.csslayout.MeasureOutput;
<add>import com.facebook.react.uimanager.BaseViewManager;
<add>import com.facebook.react.uimanager.ThemedReactContext;
<add>import com.facebook.react.views.art.ARTSurfaceView;
<add>
<add>/* protected */ class FlatARTSurfaceViewManager extends
<add> BaseViewManager<ARTSurfaceView, FlatARTSurfaceViewShadowNode> {
<add>
<add> private static final String REACT_CLASS = "ARTSurfaceView";
<add>
<add> private static final CSSNode.MeasureFunction MEASURE_FUNCTION = new CSSNode.MeasureFunction() {
<add> @Override
<add> public void measure(
<add> CSSNode node,
<add> float width,
<add> CSSMeasureMode widthMode,
<add> float height,
<add> CSSMeasureMode heightMode,
<add> MeasureOutput measureOutput) {
<add> throw new IllegalStateException("SurfaceView should have explicit width and height set");
<add> }
<add> };
<add>
<add> @Override
<add> public String getName() {
<add> return REACT_CLASS;
<add> }
<add>
<add> @Override
<add> public FlatARTSurfaceViewShadowNode createShadowNodeInstance() {
<add> FlatARTSurfaceViewShadowNode node = new FlatARTSurfaceViewShadowNode();
<add> node.setMeasureFunction(MEASURE_FUNCTION);
<add> return node;
<add> }
<add>
<add> @Override
<add> public Class<FlatARTSurfaceViewShadowNode> getShadowNodeClass() {
<add> return FlatARTSurfaceViewShadowNode.class;
<add> }
<add>
<add> @Override
<add> protected ARTSurfaceView createViewInstance(ThemedReactContext reactContext) {
<add> return new ARTSurfaceView(reactContext);
<add> }
<add>
<add> @Override
<add> public void updateExtraData(ARTSurfaceView root, Object extraData) {
<add> root.setBitmap((Bitmap) extraData);
<add> }
<add>}
<ide><path>ReactAndroid/src/main/java/com/facebook/react/flat/FlatARTSurfaceViewShadowNode.java
<add>/**
<add> * Copyright (c) 2015-present, Facebook, Inc.
<add> * All rights reserved.
<add> *
<add> * This source code is licensed under the BSD-style license found in the
<add> * LICENSE file in the root directory of this source tree. An additional grant
<add> * of patent rights can be found in the PATENTS file in the same directory.
<add> */
<add>
<add>package com.facebook.react.flat;
<add>
<add>import android.graphics.Bitmap;
<add>import android.graphics.Canvas;
<add>import android.graphics.Paint;
<add>
<add>import com.facebook.react.uimanager.UIViewOperationQueue;
<add>import com.facebook.react.views.art.ARTVirtualNode;
<add>
<add>/* package */ class FlatARTSurfaceViewShadowNode extends FlatShadowNode implements AndroidView {
<add> private boolean mPaddingChanged = false;
<add>
<add> /* package */ FlatARTSurfaceViewShadowNode() {
<add> forceMountToView();
<add> forceMountChildrenToView();
<add> }
<add>
<add> @Override
<add> public boolean isVirtual() {
<add> return false;
<add> }
<add>
<add> @Override
<add> public boolean isVirtualAnchor() {
<add> return true;
<add> }
<add>
<add> @Override
<add> public void onCollectExtraUpdates(UIViewOperationQueue uiUpdater) {
<add> super.onCollectExtraUpdates(uiUpdater);
<add> uiUpdater.enqueueUpdateExtraData(getReactTag(), drawOutput());
<add> }
<add>
<add> private Object drawOutput() {
<add> // TODO(7255985): Use TextureView and pass Surface from the view to draw on it asynchronously
<add> // instead of passing the bitmap (which is inefficient especially in terms of memory usage)
<add> Bitmap bitmap = Bitmap.createBitmap(
<add> (int) getLayoutWidth(),
<add> (int) getLayoutHeight(),
<add> Bitmap.Config.ARGB_8888);
<add> Canvas canvas = new Canvas(bitmap);
<add> Paint paint = new Paint();
<add> for (int i = 0; i < getChildCount(); i++) {
<add> ARTVirtualNode child = (ARTVirtualNode) getChildAt(i);
<add> child.draw(canvas, paint, 1f);
<add> child.markUpdateSeen();
<add> }
<add> return bitmap;
<add> }
<add>
<add> @Override
<add> public boolean needsCustomLayoutForChildren() {
<add> return false;
<add> }
<add>
<add> @Override
<add> public boolean isPaddingChanged() {
<add> return mPaddingChanged;
<add> }
<add>
<add> @Override
<add> public void resetPaddingChanged() {
<add> mPaddingChanged = false;
<add> }
<add>
<add> @Override
<add> public void setPadding(int spacingType, float padding) {
<add> if (getPadding().set(spacingType, padding)) {
<add> mPaddingChanged = true;
<add> dirty();
<add> }
<add> }
<add>}
<ide><path>ReactAndroid/src/main/java/com/facebook/react/flat/FlatShadowNode.java
<ide> protected final void invalidate() {
<ide> }
<ide> }
<ide>
<add> @Override
<add> protected void markUpdated() {
<add> super.markUpdated();
<add> mIsUpdated = true;
<add> invalidate();
<add> }
<add>
<ide> /* package */ final boolean isUpdated() {
<ide> return mIsUpdated;
<ide> }
<ide><path>ReactAndroid/src/main/java/com/facebook/react/flat/FlatUIImplementation.java
<ide> public static FlatUIImplementation createInstance(
<ide> viewManagers.add(new RCTImageViewManager());
<ide> viewManagers.add(new RCTTextInputManager());
<ide> viewManagers.add(new RCTViewPagerManager());
<add> viewManagers.add(new FlatARTSurfaceViewManager());
<ide> viewManagers.add(new RCTModalHostManager(reactContext));
<ide>
<ide> ViewManagerRegistry viewManagerRegistry = new ViewManagerRegistry(viewManagers); | 4 |
Text | Text | update the passhref link | 166834e578461de1400ae145f2a20f050f8130ec | <ide><path>docs/api-reference/next/link.md
<ide> export default Home
<ide>
<ide> - `href` - The path inside `pages` directory. This is the only required prop
<ide> - `as` - The path that will be rendered in the browser URL bar. Used for dynamic routes
<del>- [`passHref`](#forcing-Link-to-expose-href-to-its-child) - Forces `Link` to send the `href` property to its child. Defaults to `false`
<add>- [`passHref`](#if-the-child-is-a-custom-component-that-wraps-an-a-tag) - Forces `Link` to send the `href` property to its child. Defaults to `false`
<ide> - `prefetch` - Prefetch the page in the background. Defaults to `true`. Any `<Link />` that is in the viewport (initially or through scroll) will be preloaded. Pages using [Static Generation](/docs/basic-features/data-fetching#getstaticprops-static-generation) will preload `JSON` files with the data for faster page transitions.
<ide> - [`replace`](#replace-the-url-instead-of-push) - Replace the current `history` state instead of adding a new url into the stack. Defaults to `false`
<ide> - [`scroll`](#disable-scrolling-to-the-top-of-the-page) - Scroll to the top of the page after a navigation. Defaults to `true` | 1 |
Java | Java | add support for generating method names | 16456342f5c55e691596c5577c72ed6dceef6ade | <ide><path>spring-core/src/main/java/org/springframework/aot/generate/MethodNameGenerator.java
<add>/*
<add> * Copyright 2002-2022 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> * https://www.apache.org/licenses/LICENSE-2.0
<add> *
<add> * Unless required by applicable law or agreed to in writing, software
<add> * distributed under the License is distributed on an "AS IS" BASIS,
<add> * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
<add> * See the License for the specific language governing permissions and
<add> * limitations under the License.
<add> */
<add>
<add>package org.springframework.aot.generate;
<add>
<add>import java.util.Arrays;
<add>import java.util.List;
<add>import java.util.Map;
<add>import java.util.concurrent.ConcurrentHashMap;
<add>import java.util.concurrent.atomic.AtomicInteger;
<add>import java.util.stream.Collectors;
<add>import java.util.stream.Stream;
<add>
<add>import org.springframework.lang.Nullable;
<add>import org.springframework.util.Assert;
<add>import org.springframework.util.ClassUtils;
<add>import org.springframework.util.StringUtils;
<add>
<add>/**
<add> * Generates unique method names that can be used in ahead-of-time generated
<add> * source code. This class is stateful so one instance should be used per
<add> * generated type.
<add> *
<add> * @author Phillip Webb
<add> * @since 6.0
<add> */
<add>public class MethodNameGenerator {
<add>
<add> private final Map<String, AtomicInteger> sequenceGenerator = new ConcurrentHashMap<>();
<add>
<add>
<add> /**
<add> * Create a new {@link MethodNameGenerator} instance without any reserved
<add> * names.
<add> */
<add> public MethodNameGenerator() {
<add> }
<add>
<add> /**
<add> * Create a new {@link MethodNameGenerator} instance with the specified
<add> * reserved names.
<add> * @param reservedNames the method names to reserve
<add> */
<add> public MethodNameGenerator(String... reservedNames) {
<add> this(List.of(reservedNames));
<add> }
<add>
<add> /**
<add> * Create a new {@link MethodNameGenerator} instance with the specified
<add> * reserved names.
<add> * @param reservedNames the method names to reserve
<add> */
<add> public MethodNameGenerator(Iterable<String> reservedNames) {
<add> Assert.notNull(reservedNames, "'reservedNames' must not be null");
<add> for (String reservedName : reservedNames) {
<add> addSequence(StringUtils.uncapitalize(reservedName));
<add> }
<add> }
<add>
<add>
<add> /**
<add> * Generate a new method name from the given parts.
<add> * @param parts the parts used to build the name.
<add> * @return the generated method name
<add> */
<add> public String generateMethodName(Object... parts) {
<add> String generatedName = join(parts);
<add> return addSequence(generatedName.isEmpty() ? "$$aot" : generatedName);
<add> }
<add>
<add> private String addSequence(String name) {
<add> int sequence = this.sequenceGenerator
<add> .computeIfAbsent(name, key -> new AtomicInteger()).getAndIncrement();
<add> return (sequence > 0) ? name + sequence : name;
<add> }
<add>
<add> /**
<add> * Join the specified parts to create a valid camel case method name.
<add> * @param parts the parts to join
<add> * @return a method name from the joined parts.
<add> */
<add> public static String join(Object... parts) {
<add> Stream<String> capitalizedPartNames = Arrays.stream(parts)
<add> .map(MethodNameGenerator::getPartName).map(StringUtils::capitalize);
<add> return StringUtils
<add> .uncapitalize(capitalizedPartNames.collect(Collectors.joining()));
<add> }
<add>
<add> private static String getPartName(@Nullable Object part) {
<add> if (part == null) {
<add> return "";
<add> }
<add> if (part instanceof Class<?> clazz) {
<add> return clean(ClassUtils.getShortName(clazz));
<add> }
<add> return clean(part.toString());
<add> }
<add>
<add> private static String clean(String string) {
<add> char[] chars = string.toCharArray();
<add> StringBuilder name = new StringBuilder(chars.length);
<add> boolean uppercase = false;
<add> for (char ch : chars) {
<add> char outputChar = (!uppercase) ? ch : Character.toUpperCase(ch);
<add> name.append((!Character.isLetter(ch)) ? "" : outputChar);
<add> uppercase = ch == '.';
<add> }
<add> return name.toString();
<add> }
<add>
<add>}
<ide><path>spring-core/src/test/java/org/springframework/aot/generate/MethodNameGeneratorTests.java
<add>/*
<add> * Copyright 2002-2022 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> * https://www.apache.org/licenses/LICENSE-2.0
<add> *
<add> * Unless required by applicable law or agreed to in writing, software
<add> * distributed under the License is distributed on an "AS IS" BASIS,
<add> * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
<add> * See the License for the specific language governing permissions and
<add> * limitations under the License.
<add> */
<add>
<add>package org.springframework.aot.generate;
<add>
<add>import java.io.InputStream;
<add>
<add>import org.junit.jupiter.api.Test;
<add>
<add>import static org.assertj.core.api.Assertions.assertThat;
<add>
<add>/**
<add> * Tests for {@link MethodNameGenerator}.
<add> *
<add> * @author Phillip Webb
<add> */
<add>class MethodNameGeneratorTests {
<add>
<add> private final MethodNameGenerator generator = new MethodNameGenerator();
<add>
<add> @Test
<add> void createWithReservedNamesReservesNames() {
<add> MethodNameGenerator generator = new MethodNameGenerator("testName");
<add> assertThat(generator.generateMethodName("test", "name")).hasToString("testName1");
<add> }
<add>
<add> @Test
<add> void generateMethodNameGeneratesName() {
<add> String generated = this.generator.generateMethodName("register", "myBean",
<add> "bean");
<add> assertThat(generated).isEqualTo("registerMyBeanBean");
<add> }
<add>
<add> @Test
<add> void generateMethodNameWhenHasNonLettersGeneratesName() {
<add> String generated = this.generator.generateMethodName("register", "myBean123",
<add> "bean");
<add> assertThat(generated).isEqualTo("registerMyBeanBean");
<add> }
<add>
<add> @Test
<add> void generateMethodNameWhenHasDotsGeneratesCamelCaseName() {
<add> String generated = this.generator.generateMethodName("register",
<add> "org.springframework.example.bean");
<add> assertThat(generated).isEqualTo("registerOrgSpringframeworkExampleBean");
<add> }
<add>
<add> @Test
<add> void generateMethodNameWhenMultipleCallsGeneratesSequencedName() {
<add> String generated1 = this.generator.generateMethodName("register", "myBean123",
<add> "bean");
<add> String generated2 = this.generator.generateMethodName("register", "myBean!",
<add> "bean");
<add> String generated3 = this.generator.generateMethodName("register", "myBean%%",
<add> "bean");
<add> assertThat(generated1).isEqualTo("registerMyBeanBean");
<add> assertThat(generated2).isEqualTo("registerMyBeanBean1");
<add> assertThat(generated3).isEqualTo("registerMyBeanBean2");
<add> }
<add>
<add> @Test
<add> void generateMethodNameWhenAllEmptyPartsGeneratesSetName() {
<add> String generated = this.generator.generateMethodName("123");
<add> assertThat(generated).isEqualTo("$$aot");
<add> }
<add>
<add> @Test
<add> void joinReturnsJoinedName() {
<add> assertThat(MethodNameGenerator.join("get", "bean", "factory"))
<add> .isEqualTo("getBeanFactory");
<add> assertThat(MethodNameGenerator.join("get", null, "factory"))
<add> .isEqualTo("getFactory");
<add> assertThat(MethodNameGenerator.join(null, null)).isEqualTo("");
<add> assertThat(MethodNameGenerator.join("", null)).isEqualTo("");
<add> assertThat(MethodNameGenerator.join("get", InputStream.class))
<add> .isEqualTo("getInputStream");
<add>
<add> }
<add>
<add>} | 2 |
Text | Text | use code markup/markdown in headers | f8795db8b3eb75b12bd42b3a033c59bd0423667a | <ide><path>doc/api/http.md
<ide> list like the following:
<ide> 'accepT', '*/*' ]
<ide> ```
<ide>
<del>## Class: http.Agent
<add>## Class: `http.Agent`
<ide> <!-- YAML
<ide> added: v0.3.4
<ide> -->
<ide> http.get({
<ide> });
<ide> ```
<ide>
<del>### new Agent(\[options\])
<add>### `new Agent([options])`
<ide> <!-- YAML
<ide> added: v0.3.4
<ide> -->
<ide> options.agent = keepAliveAgent;
<ide> http.request(options, onResponseCallback);
<ide> ```
<ide>
<del>### agent.createConnection(options\[, callback\])
<add>### `agent.createConnection(options[, callback])`
<ide> <!-- YAML
<ide> added: v0.11.4
<ide> -->
<ide> type other than {net.Socket}.
<ide>
<ide> `callback` has a signature of `(err, stream)`.
<ide>
<del>### agent.keepSocketAlive(socket)
<add>### `agent.keepSocketAlive(socket)`
<ide> <!-- YAML
<ide> added: v8.1.0
<ide> -->
<ide> it for use with the next request.
<ide> The `socket` argument can be an instance of {net.Socket}, a subclass of
<ide> {stream.Duplex}.
<ide>
<del>### agent.reuseSocket(socket, request)
<add>### `agent.reuseSocket(socket, request)`
<ide> <!-- YAML
<ide> added: v8.1.0
<ide> -->
<ide> This method can be overridden by a particular `Agent` subclass.
<ide> The `socket` argument can be an instance of {net.Socket}, a subclass of
<ide> {stream.Duplex}.
<ide>
<del>### agent.destroy()
<add>### `agent.destroy()`
<ide> <!-- YAML
<ide> added: v0.11.4
<ide> -->
<ide> the agent when it will no longer be used. Otherwise,
<ide> sockets may hang open for quite a long time before the server
<ide> terminates them.
<ide>
<del>### agent.freeSockets
<add>### `agent.freeSockets`
<ide> <!-- YAML
<ide> added: v0.11.4
<ide> -->
<ide> added: v0.11.4
<ide> An object which contains arrays of sockets currently awaiting use by
<ide> the agent when `keepAlive` is enabled. Do not modify.
<ide>
<del>### agent.getName(options)
<add>### `agent.getName(options)`
<ide> <!-- YAML
<ide> added: v0.11.4
<ide> -->
<ide> connection can be reused. For an HTTP agent, this returns
<ide> the name includes the CA, cert, ciphers, and other HTTPS/TLS-specific options
<ide> that determine socket reusability.
<ide>
<del>### agent.maxFreeSockets
<add>### `agent.maxFreeSockets`
<ide> <!-- YAML
<ide> added: v0.11.7
<ide> -->
<ide> By default set to 256. For agents with `keepAlive` enabled, this
<ide> sets the maximum number of sockets that will be left open in the free
<ide> state.
<ide>
<del>### agent.maxSockets
<add>### `agent.maxSockets`
<ide> <!-- YAML
<ide> added: v0.3.6
<ide> -->
<ide> added: v0.3.6
<ide> By default set to `Infinity`. Determines how many concurrent sockets the agent
<ide> can have open per origin. Origin is the returned value of [`agent.getName()`][].
<ide>
<del>### agent.requests
<add>### `agent.requests`
<ide> <!-- YAML
<ide> added: v0.5.9
<ide> -->
<ide> added: v0.5.9
<ide> An object which contains queues of requests that have not yet been assigned to
<ide> sockets. Do not modify.
<ide>
<del>### agent.sockets
<add>### `agent.sockets`
<ide> <!-- YAML
<ide> added: v0.3.6
<ide> -->
<ide> added: v0.3.6
<ide> An object which contains arrays of sockets currently in use by the
<ide> agent. Do not modify.
<ide>
<del>## Class: http.ClientRequest
<add>## Class: `http.ClientRequest`
<ide> <!-- YAML
<ide> added: v0.1.17
<ide> -->
<ide> Unlike the `request` object, if the response closes prematurely, the
<ide> Node.js does not check whether Content-Length and the length of the
<ide> body which has been transmitted are equal or not.
<ide>
<del>### Event: 'abort'
<add>### Event: `'abort'`
<ide> <!-- YAML
<ide> added: v1.4.1
<ide> -->
<ide>
<ide> Emitted when the request has been aborted by the client. This event is only
<ide> emitted on the first call to `abort()`.
<ide>
<del>### Event: 'connect'
<add>### Event: `'connect'`
<ide> <!-- YAML
<ide> added: v0.7.0
<ide> -->
<ide> proxy.listen(1337, '127.0.0.1', () => {
<ide> });
<ide> ```
<ide>
<del>### Event: 'continue'
<add>### Event: `'continue'`
<ide> <!-- YAML
<ide> added: v0.3.2
<ide> -->
<ide> Emitted when the server sends a '100 Continue' HTTP response, usually because
<ide> the request contained 'Expect: 100-continue'. This is an instruction that
<ide> the client should send the request body.
<ide>
<del>### Event: 'information'
<add>### Event: `'information'`
<ide> <!-- YAML
<ide> added: v10.0.0
<ide> -->
<ide> traditional HTTP request/response chain, such as web sockets, in-place TLS
<ide> upgrades, or HTTP 2.0. To be notified of 101 Upgrade notices, listen for the
<ide> [`'upgrade'`][] event instead.
<ide>
<del>### Event: 'response'
<add>### Event: `'response'`
<ide> <!-- YAML
<ide> added: v0.1.0
<ide> -->
<ide> added: v0.1.0
<ide> Emitted when a response is received to this request. This event is emitted only
<ide> once.
<ide>
<del>### Event: 'socket'
<add>### Event: `'socket'`
<ide> <!-- YAML
<ide> added: v0.5.3
<ide> -->
<ide> This event is guaranteed to be passed an instance of the {net.Socket} class,
<ide> a subclass of {stream.Duplex}, unless the user specifies a socket
<ide> type other than {net.Socket}.
<ide>
<del>### Event: 'timeout'
<add>### Event: `'timeout'`
<ide> <!-- YAML
<ide> added: v0.7.8
<ide> -->
<ide> that the socket has been idle. The request must be aborted manually.
<ide>
<ide> See also: [`request.setTimeout()`][].
<ide>
<del>### Event: 'upgrade'
<add>### Event: `'upgrade'`
<ide> <!-- YAML
<ide> added: v0.1.94
<ide> -->
<ide> srv.listen(1337, '127.0.0.1', () => {
<ide> });
<ide> ```
<ide>
<del>### request.abort()
<add>### `request.abort()`
<ide> <!-- YAML
<ide> added: v0.3.8
<ide> -->
<ide>
<ide> Marks the request as aborting. Calling this will cause remaining data
<ide> in the response to be dropped and the socket to be destroyed.
<ide>
<del>### request.aborted
<add>### `request.aborted`
<ide> <!-- YAML
<ide> added: v0.11.14
<ide> changes:
<ide> changes:
<ide> The `request.aborted` property will be `true` if the request has
<ide> been aborted.
<ide>
<del>### request.connection
<add>### `request.connection`
<ide> <!-- YAML
<ide> added: v0.3.0
<ide> deprecated: v13.0.0
<ide> deprecated: v13.0.0
<ide>
<ide> See [`request.socket`][].
<ide>
<del>### request.end(\[data\[, encoding\]\]\[, callback\])
<add>### `request.end([data[, encoding]][, callback])`
<ide> <!-- YAML
<ide> added: v0.1.90
<ide> changes:
<ide> If `data` is specified, it is equivalent to calling
<ide> If `callback` is specified, it will be called when the request stream
<ide> is finished.
<ide>
<del>### request.finished
<add>### `request.finished`
<ide> <!-- YAML
<ide> added: v0.0.1
<ide> deprecated: v13.4.0
<ide> The `request.finished` property will be `true` if [`request.end()`][]
<ide> has been called. `request.end()` will automatically be called if the
<ide> request was initiated via [`http.get()`][].
<ide>
<del>### request.flushHeaders()
<add>### `request.flushHeaders()`
<ide> <!-- YAML
<ide> added: v1.6.0
<ide> -->
<ide> That's usually desired (it saves a TCP round-trip), but not when the first
<ide> data is not sent until possibly much later. `request.flushHeaders()` bypasses
<ide> the optimization and kickstarts the request.
<ide>
<del>### request.getHeader(name)
<add>### `request.getHeader(name)`
<ide> <!-- YAML
<ide> added: v1.6.0
<ide> -->
<ide> const cookie = request.getHeader('Cookie');
<ide> // 'cookie' is of type string[]
<ide> ```
<ide>
<del>### request.maxHeadersCount
<add>### `request.maxHeadersCount`
<ide>
<ide> * {number} **Default:** `2000`
<ide>
<ide> Limits maximum response headers count. If set to 0, no limit will be applied.
<ide>
<del>### request.path
<add>### `request.path`
<ide> <!-- YAML
<ide> added: v0.4.0
<ide> -->
<ide>
<ide> * {string} The request path.
<ide>
<del>### request.removeHeader(name)
<add>### `request.removeHeader(name)`
<ide> <!-- YAML
<ide> added: v1.6.0
<ide> -->
<ide> Removes a header that's already defined into headers object.
<ide> request.removeHeader('Content-Type');
<ide> ```
<ide>
<del>### request.reusedSocket
<add>### `request.reusedSocket`
<ide>
<ide> <!-- YAML
<ide> added: v13.0.0
<ide> function retriableRequest() {
<ide> retriableRequest();
<ide> ```
<ide>
<del>### request.setHeader(name, value)
<add>### `request.setHeader(name, value)`
<ide> <!-- YAML
<ide> added: v1.6.0
<ide> -->
<ide> or
<ide> request.setHeader('Cookie', ['type=ninja', 'language=javascript']);
<ide> ```
<ide>
<del>### request.setNoDelay(\[noDelay\])
<add>### `request.setNoDelay([noDelay])`
<ide> <!-- YAML
<ide> added: v0.5.9
<ide> -->
<ide> added: v0.5.9
<ide> Once a socket is assigned to this request and is connected
<ide> [`socket.setNoDelay()`][] will be called.
<ide>
<del>### request.setSocketKeepAlive(\[enable\]\[, initialDelay\])
<add>### `request.setSocketKeepAlive([enable][, initialDelay])`
<ide> <!-- YAML
<ide> added: v0.5.9
<ide> -->
<ide> added: v0.5.9
<ide> Once a socket is assigned to this request and is connected
<ide> [`socket.setKeepAlive()`][] will be called.
<ide>
<del>### request.setTimeout(timeout\[, callback\])
<add>### `request.setTimeout(timeout[, callback])`
<ide> <!-- YAML
<ide> added: v0.5.9
<ide> changes:
<ide> changes:
<ide> Once a socket is assigned to this request and is connected
<ide> [`socket.setTimeout()`][] will be called.
<ide>
<del>### request.socket
<add>### `request.socket`
<ide> <!-- YAML
<ide> added: v0.3.0
<ide> -->
<ide> This property is guaranteed to be an instance of the {net.Socket} class,
<ide> a subclass of {stream.Duplex}, unless the user specified a socket
<ide> type other than {net.Socket}.
<ide>
<del>### request.writableEnded
<add>### `request.writableEnded`
<ide> <!-- YAML
<ide> added: v12.9.0
<ide> -->
<ide> Is `true` after [`request.end()`][] has been called. This property
<ide> does not indicate whether the data has been flushed, for this use
<ide> [`request.writableFinished`][] instead.
<ide>
<del>### request.writableFinished
<add>### `request.writableFinished`
<ide> <!-- YAML
<ide> added: v12.7.0
<ide> -->
<ide> added: v12.7.0
<ide> Is `true` if all data has been flushed to the underlying system, immediately
<ide> before the [`'finish'`][] event is emitted.
<ide>
<del>### request.write(chunk\[, encoding\]\[, callback\])
<add>### `request.write(chunk[, encoding][, callback])`
<ide> <!-- YAML
<ide> added: v0.1.29
<ide> -->
<ide> buffer. Returns `false` if all or part of the data was queued in user memory.
<ide> When `write` function is called with empty string or buffer, it does
<ide> nothing and waits for more input.
<ide>
<del>## Class: http.Server
<add>## Class: `http.Server`
<ide> <!-- YAML
<ide> added: v0.1.17
<ide> -->
<ide>
<ide> * Extends: {net.Server}
<ide>
<del>### Event: 'checkContinue'
<add>### Event: `'checkContinue'`
<ide> <!-- YAML
<ide> added: v0.3.0
<ide> -->
<ide> the request body.
<ide> When this event is emitted and handled, the [`'request'`][] event will
<ide> not be emitted.
<ide>
<del>### Event: 'checkExpectation'
<add>### Event: `'checkExpectation'`
<ide> <!-- YAML
<ide> added: v5.5.0
<ide> -->
<ide> automatically respond with a `417 Expectation Failed` as appropriate.
<ide> When this event is emitted and handled, the [`'request'`][] event will
<ide> not be emitted.
<ide>
<del>### Event: 'clientError'
<add>### Event: `'clientError'`
<ide> <!-- YAML
<ide> added: v0.1.94
<ide> changes:
<ide> ensure the response is a properly formatted HTTP response message.
<ide> correctly;
<ide> * `rawPacket`: the raw packet of current request.
<ide>
<del>### Event: 'close'
<add>### Event: `'close'`
<ide> <!-- YAML
<ide> added: v0.1.4
<ide> -->
<ide>
<ide> Emitted when the server closes.
<ide>
<del>### Event: 'connect'
<add>### Event: `'connect'`
<ide> <!-- YAML
<ide> added: v0.7.0
<ide> -->
<ide> After this event is emitted, the request's socket will not have a `'data'`
<ide> event listener, meaning it will need to be bound in order to handle data
<ide> sent to the server on that socket.
<ide>
<del>### Event: 'connection'
<add>### Event: `'connection'`
<ide> <!-- YAML
<ide> added: v0.1.0
<ide> -->
<ide> This event is guaranteed to be passed an instance of the {net.Socket} class,
<ide> a subclass of {stream.Duplex}, unless the user specifies a socket
<ide> type other than {net.Socket}.
<ide>
<del>### Event: 'request'
<add>### Event: `'request'`
<ide> <!-- YAML
<ide> added: v0.1.0
<ide> -->
<ide> added: v0.1.0
<ide> Emitted each time there is a request. There may be multiple requests
<ide> per connection (in the case of HTTP Keep-Alive connections).
<ide>
<del>### Event: 'upgrade'
<add>### Event: `'upgrade'`
<ide> <!-- YAML
<ide> added: v0.1.94
<ide> changes:
<ide> This event is guaranteed to be passed an instance of the {net.Socket} class,
<ide> a subclass of {stream.Duplex}, unless the user specifies a socket
<ide> type other than {net.Socket}.
<ide>
<del>### server.close(\[callback\])
<add>### `server.close([callback])`
<ide> <!-- YAML
<ide> added: v0.1.90
<ide> -->
<ide> added: v0.1.90
<ide>
<ide> Stops the server from accepting new connections. See [`net.Server.close()`][].
<ide>
<del>### server.headersTimeout
<add>### `server.headersTimeout`
<ide> <!-- YAML
<ide> added: v11.3.0
<ide> -->
<ide> event is emitted on the server object, and (by default) the socket is destroyed.
<ide> See [`server.timeout`][] for more information on how timeout behavior can be
<ide> customized.
<ide>
<del>### server.listen()
<add>### `server.listen()`
<ide>
<ide> Starts the HTTP server listening for connections.
<ide> This method is identical to [`server.listen()`][] from [`net.Server`][].
<ide>
<del>### server.listening
<add>### `server.listening`
<ide> <!-- YAML
<ide> added: v5.7.0
<ide> -->
<ide>
<ide> * {boolean} Indicates whether or not the server is listening for connections.
<ide>
<del>### server.maxHeadersCount
<add>### `server.maxHeadersCount`
<ide> <!-- YAML
<ide> added: v0.7.0
<ide> -->
<ide> added: v0.7.0
<ide>
<ide> Limits maximum incoming headers count. If set to 0, no limit will be applied.
<ide>
<del>### server.setTimeout(\[msecs\]\[, callback\])
<add>### `server.setTimeout([msecs][, callback])`
<ide> <!-- YAML
<ide> added: v0.9.12
<ide> changes:
<ide> By default, the Server does not timeout sockets. However, if a callback
<ide> is assigned to the Server's `'timeout'` event, timeouts must be handled
<ide> explicitly.
<ide>
<del>### server.timeout
<add>### `server.timeout`
<ide> <!-- YAML
<ide> added: v0.9.12
<ide> changes:
<ide> A value of `0` will disable the timeout behavior on incoming connections.
<ide> The socket timeout logic is set up on connection, so changing this
<ide> value only affects new connections to the server, not any existing connections.
<ide>
<del>### server.keepAliveTimeout
<add>### `server.keepAliveTimeout`
<ide> <!-- YAML
<ide> added: v8.0.0
<ide> -->
<ide> to 8.0.0, which did not have a keep-alive timeout.
<ide> The socket timeout logic is set up on connection, so changing this value only
<ide> affects new connections to the server, not any existing connections.
<ide>
<del>## Class: http.ServerResponse
<add>## Class: `http.ServerResponse`
<ide> <!-- YAML
<ide> added: v0.1.17
<ide> -->
<ide> added: v0.1.17
<ide> This object is created internally by an HTTP server — not by the user. It is
<ide> passed as the second parameter to the [`'request'`][] event.
<ide>
<del>### Event: 'close'
<add>### Event: `'close'`
<ide> <!-- YAML
<ide> added: v0.6.7
<ide> -->
<ide>
<ide> Indicates that the underlying connection was terminated.
<ide>
<del>### Event: 'finish'
<add>### Event: `'finish'`
<ide> <!-- YAML
<ide> added: v0.3.6
<ide> -->
<ide> emitted when the last segment of the response headers and body have been
<ide> handed off to the operating system for transmission over the network. It
<ide> does not imply that the client has received anything yet.
<ide>
<del>### response.addTrailers(headers)
<add>### `response.addTrailers(headers)`
<ide> <!-- YAML
<ide> added: v0.3.0
<ide> -->
<ide> response.end();
<ide> Attempting to set a header field name or value that contains invalid characters
<ide> will result in a [`TypeError`][] being thrown.
<ide>
<del>### response.connection
<add>### `response.connection`
<ide> <!-- YAML
<ide> added: v0.3.0
<ide> deprecated: v13.0.0
<ide> deprecated: v13.0.0
<ide>
<ide> See [`response.socket`][].
<ide>
<del>### response.cork()
<add>### `response.cork()`
<ide> <!-- YAML
<ide> added: v13.2.0
<ide> -->
<ide>
<ide> See [`writable.cork()`][].
<ide>
<del>### response.end(\[data\[, encoding\]\]\[, callback\])
<add>### `response.end([data[, encoding]][, callback])`
<ide> <!-- YAML
<ide> added: v0.1.90
<ide> changes:
<ide> If `data` is specified, it is similar in effect to calling
<ide> If `callback` is specified, it will be called when the response stream
<ide> is finished.
<ide>
<del>### response.finished
<add>### `response.finished`
<ide> <!-- YAML
<ide> added: v0.0.2
<ide> deprecated: v13.4.0
<ide> deprecated: v13.4.0
<ide> The `response.finished` property will be `true` if [`response.end()`][]
<ide> has been called.
<ide>
<del>### response.flushHeaders()
<add>### `response.flushHeaders()`
<ide> <!-- YAML
<ide> added: v1.6.0
<ide> -->
<ide>
<ide> Flushes the response headers. See also: [`request.flushHeaders()`][].
<ide>
<del>### response.getHeader(name)
<add>### `response.getHeader(name)`
<ide> <!-- YAML
<ide> added: v0.4.0
<ide> -->
<ide> const setCookie = response.getHeader('set-cookie');
<ide> // setCookie is of type string[]
<ide> ```
<ide>
<del>### response.getHeaderNames()
<add>### `response.getHeaderNames()`
<ide> <!-- YAML
<ide> added: v7.7.0
<ide> -->
<ide> const headerNames = response.getHeaderNames();
<ide> // headerNames === ['foo', 'set-cookie']
<ide> ```
<ide>
<del>### response.getHeaders()
<add>### `response.getHeaders()`
<ide> <!-- YAML
<ide> added: v7.7.0
<ide> -->
<ide> const headers = response.getHeaders();
<ide> // headers === { foo: 'bar', 'set-cookie': ['foo=bar', 'bar=baz'] }
<ide> ```
<ide>
<del>### response.hasHeader(name)
<add>### `response.hasHeader(name)`
<ide> <!-- YAML
<ide> added: v7.7.0
<ide> -->
<ide> outgoing headers. The header name matching is case-insensitive.
<ide> const hasContentType = response.hasHeader('content-type');
<ide> ```
<ide>
<del>### response.headersSent
<add>### `response.headersSent`
<ide> <!-- YAML
<ide> added: v0.9.3
<ide> -->
<ide> added: v0.9.3
<ide>
<ide> Boolean (read-only). True if headers were sent, false otherwise.
<ide>
<del>### response.removeHeader(name)
<add>### `response.removeHeader(name)`
<ide> <!-- YAML
<ide> added: v0.4.0
<ide> -->
<ide> Removes a header that's queued for implicit sending.
<ide> response.removeHeader('Content-Encoding');
<ide> ```
<ide>
<del>### response.sendDate
<add>### `response.sendDate`
<ide> <!-- YAML
<ide> added: v0.7.5
<ide> -->
<ide> the response if it is not already present in the headers. Defaults to true.
<ide> This should only be disabled for testing; HTTP requires the Date header
<ide> in responses.
<ide>
<del>### response.setHeader(name, value)
<add>### `response.setHeader(name, value)`
<ide> <!-- YAML
<ide> added: v0.4.0
<ide> -->
<ide> header will not yield the expected result. If progressive population of headers
<ide> is desired with potential future retrieval and modification, use
<ide> [`response.setHeader()`][] instead of [`response.writeHead()`][].
<ide>
<del>### response.setTimeout(msecs\[, callback\])
<add>### `response.setTimeout(msecs[, callback])`
<ide> <!-- YAML
<ide> added: v0.9.12
<ide> -->
<ide> the server, then sockets are destroyed when they time out. If a handler is
<ide> assigned to the request, the response, or the server's `'timeout'` events,
<ide> timed out sockets must be handled explicitly.
<ide>
<del>### response.socket
<add>### `response.socket`
<ide> <!-- YAML
<ide> added: v0.3.0
<ide> -->
<ide> This property is guaranteed to be an instance of the {net.Socket} class,
<ide> a subclass of {stream.Duplex}, unless the user specified a socket
<ide> type other than {net.Socket}.
<ide>
<del>### response.statusCode
<add>### `response.statusCode`
<ide> <!-- YAML
<ide> added: v0.4.0
<ide> -->
<ide> response.statusCode = 404;
<ide> After response header was sent to the client, this property indicates the
<ide> status code which was sent out.
<ide>
<del>### response.statusMessage
<add>### `response.statusMessage`
<ide> <!-- YAML
<ide> added: v0.11.8
<ide> -->
<ide> response.statusMessage = 'Not found';
<ide> After response header was sent to the client, this property indicates the
<ide> status message which was sent out.
<ide>
<del>### response.uncork()
<add>### `response.uncork()`
<ide> <!-- YAML
<ide> added: v13.2.0
<ide> -->
<ide>
<ide> See [`writable.uncork()`][].
<ide>
<del>### response.writableEnded
<add>### `response.writableEnded`
<ide> <!-- YAML
<ide> added: v12.9.0
<ide> -->
<ide> Is `true` after [`response.end()`][] has been called. This property
<ide> does not indicate whether the data has been flushed, for this use
<ide> [`response.writableFinished`][] instead.
<ide>
<del>### response.writableFinished
<add>### `response.writableFinished`
<ide> <!-- YAML
<ide> added: v12.7.0
<ide> -->
<ide> added: v12.7.0
<ide> Is `true` if all data has been flushed to the underlying system, immediately
<ide> before the [`'finish'`][] event is emitted.
<ide>
<del>### response.write(chunk\[, encoding\]\[, callback\])
<add>### `response.write(chunk[, encoding][, callback])`
<ide> <!-- YAML
<ide> added: v0.1.29
<ide> -->
<ide> Returns `true` if the entire data was flushed successfully to the kernel
<ide> buffer. Returns `false` if all or part of the data was queued in user memory.
<ide> `'drain'` will be emitted when the buffer is free again.
<ide>
<del>### response.writeContinue()
<add>### `response.writeContinue()`
<ide> <!-- YAML
<ide> added: v0.3.0
<ide> -->
<ide> Sends a HTTP/1.1 100 Continue message to the client, indicating that
<ide> the request body should be sent. See the [`'checkContinue'`][] event on
<ide> `Server`.
<ide>
<del>### response.writeHead(statusCode\[, statusMessage\]\[, headers\])
<add>### `response.writeHead(statusCode[, statusMessage][, headers])`
<ide> <!-- YAML
<ide> added: v0.1.30
<ide> changes:
<ide> which has been transmitted are equal or not.
<ide> Attempting to set a header field name or value that contains invalid characters
<ide> will result in a [`TypeError`][] being thrown.
<ide>
<del>### response.writeProcessing()
<add>### `response.writeProcessing()`
<ide> <!-- YAML
<ide> added: v10.0.0
<ide> -->
<ide>
<ide> Sends a HTTP/1.1 102 Processing message to the client, indicating that
<ide> the request body should be sent.
<ide>
<del>## Class: http.IncomingMessage
<add>## Class: `http.IncomingMessage`
<ide> <!-- YAML
<ide> added: v0.1.17
<ide> changes:
<ide> An `IncomingMessage` object is created by [`http.Server`][] or
<ide> and [`'response'`][] event respectively. It may be used to access response
<ide> status, headers and data.
<ide>
<del>### Event: 'aborted'
<add>### Event: `'aborted'`
<ide> <!-- YAML
<ide> added: v0.3.8
<ide> -->
<ide>
<ide> Emitted when the request has been aborted.
<ide>
<del>### Event: 'close'
<add>### Event: `'close'`
<ide> <!-- YAML
<ide> added: v0.4.2
<ide> -->
<ide>
<ide> Indicates that the underlying connection was closed.
<ide>
<del>### message.aborted
<add>### `message.aborted`
<ide> <!-- YAML
<ide> added: v10.1.0
<ide> -->
<ide> added: v10.1.0
<ide> The `message.aborted` property will be `true` if the request has
<ide> been aborted.
<ide>
<del>### message.complete
<add>### `message.complete`
<ide> <!-- YAML
<ide> added: v0.3.0
<ide> -->
<ide> const req = http.request({
<ide> });
<ide> ```
<ide>
<del>### message.destroy(\[error\])
<add>### `message.destroy([error])`
<ide> <!-- YAML
<ide> added: v0.3.0
<ide> -->
<ide> Calls `destroy()` on the socket that received the `IncomingMessage`. If `error`
<ide> is provided, an `'error'` event is emitted on the socket and `error` is passed
<ide> as an argument to any listeners on the event.
<ide>
<del>### message.headers
<add>### `message.headers`
<ide> <!-- YAML
<ide> added: v0.1.5
<ide> -->
<ide> header name:
<ide> * For duplicate `cookie` headers, the values are joined together with '; '.
<ide> * For all other headers, the values are joined together with ', '.
<ide>
<del>### message.httpVersion
<add>### `message.httpVersion`
<ide> <!-- YAML
<ide> added: v0.1.1
<ide> -->
<ide> Probably either `'1.1'` or `'1.0'`.
<ide> Also `message.httpVersionMajor` is the first integer and
<ide> `message.httpVersionMinor` is the second.
<ide>
<del>### message.method
<add>### `message.method`
<ide> <!-- YAML
<ide> added: v0.1.1
<ide> -->
<ide> added: v0.1.1
<ide>
<ide> The request method as a string. Read only. Examples: `'GET'`, `'DELETE'`.
<ide>
<del>### message.rawHeaders
<add>### `message.rawHeaders`
<ide> <!-- YAML
<ide> added: v0.11.6
<ide> -->
<ide> Header names are not lowercased, and duplicates are not merged.
<ide> console.log(request.rawHeaders);
<ide> ```
<ide>
<del>### message.rawTrailers
<add>### `message.rawTrailers`
<ide> <!-- YAML
<ide> added: v0.11.6
<ide> -->
<ide> added: v0.11.6
<ide> The raw request/response trailer keys and values exactly as they were
<ide> received. Only populated at the `'end'` event.
<ide>
<del>### message.setTimeout(msecs\[, callback\])
<add>### `message.setTimeout(msecs[, callback])`
<ide> <!-- YAML
<ide> added: v0.5.9
<ide> -->
<ide> added: v0.5.9
<ide>
<ide> Calls `message.connection.setTimeout(msecs, callback)`.
<ide>
<del>### message.socket
<add>### `message.socket`
<ide> <!-- YAML
<ide> added: v0.3.0
<ide> -->
<ide> This property is guaranteed to be an instance of the {net.Socket} class,
<ide> a subclass of {stream.Duplex}, unless the user specified a socket
<ide> type other than {net.Socket}.
<ide>
<del>### message.statusCode
<add>### `message.statusCode`
<ide> <!-- YAML
<ide> added: v0.1.1
<ide> -->
<ide> added: v0.1.1
<ide>
<ide> The 3-digit HTTP response status code. E.G. `404`.
<ide>
<del>### message.statusMessage
<add>### `message.statusMessage`
<ide> <!-- YAML
<ide> added: v0.11.10
<ide> -->
<ide> added: v0.11.10
<ide> The HTTP response status message (reason phrase). E.G. `OK` or `Internal Server
<ide> Error`.
<ide>
<del>### message.trailers
<add>### `message.trailers`
<ide> <!-- YAML
<ide> added: v0.3.0
<ide> -->
<ide> added: v0.3.0
<ide>
<ide> The request/response trailers object. Only populated at the `'end'` event.
<ide>
<del>### message.url
<add>### `message.url`
<ide> <!-- YAML
<ide> added: v0.1.90
<ide> -->
<ide> URL {
<ide> }
<ide> ```
<ide>
<del>## http.METHODS
<add>## `http.METHODS`
<ide> <!-- YAML
<ide> added: v0.11.8
<ide> -->
<ide> added: v0.11.8
<ide>
<ide> A list of the HTTP methods that are supported by the parser.
<ide>
<del>## http.STATUS_CODES
<add>## `http.STATUS_CODES`
<ide> <!-- YAML
<ide> added: v0.1.22
<ide> -->
<ide> A collection of all the standard HTTP response status codes, and the
<ide> short description of each. For example, `http.STATUS_CODES[404] === 'Not
<ide> Found'`.
<ide>
<del>## http.createServer(\[options\]\[, requestListener\])
<add>## `http.createServer([options][, requestListener])`
<ide> <!-- YAML
<ide> added: v0.1.13
<ide> changes:
<ide> Returns a new instance of [`http.Server`][].
<ide> The `requestListener` is a function which is automatically
<ide> added to the [`'request'`][] event.
<ide>
<del>## http.get(options\[, callback\])
<del>## http.get(url\[, options\]\[, callback\])
<add>## `http.get(options[, callback])`
<add>## `http.get(url[, options][, callback])`
<ide> <!-- YAML
<ide> added: v0.3.6
<ide> changes:
<ide> http.get('http://nodejs.org/dist/index.json', (res) => {
<ide> });
<ide> ```
<ide>
<del>## http.globalAgent
<add>## `http.globalAgent`
<ide> <!-- YAML
<ide> added: v0.5.9
<ide> -->
<ide> added: v0.5.9
<ide> Global instance of `Agent` which is used as the default for all HTTP client
<ide> requests.
<ide>
<del>## http.maxHeaderSize
<add>## `http.maxHeaderSize`
<ide> <!-- YAML
<ide> added: v11.6.0
<ide> -->
<ide> Defaults to 8KB. Configurable using the [`--max-http-header-size`][] CLI option.
<ide> This can be overridden for servers and client requests by passing the
<ide> `maxHeaderSize` option.
<ide>
<del>## http.request(options\[, callback\])
<del>## http.request(url\[, options\]\[, callback\])
<add>## `http.request(options[, callback])`
<add>## `http.request(url[, options][, callback])`
<ide> <!-- YAML
<ide> added: v0.3.6
<ide> changes: | 1 |
Text | Text | remove extra word | 814b1821e6616621248a2c7a83f5cd352f0c68e9 | <ide><path>readme.md
<ide> npm install --save next react react-dom
<ide> ```
<ide>
<ide> > Next.js 4 only supports [React 16](https://reactjs.org/blog/2017/09/26/react-v16.0.html).<br/>
<del>> We had to drop React 15 support due to the way how React 16 works and how we use it.
<add>> We had to drop React 15 support due to the way React 16 works and how we use it.
<ide>
<ide> and add a script to your package.json like this:
<ide> | 1 |
Ruby | Ruby | fix style complaint | 98959f1fb9c667abde593dcd92128aed5367d29a | <ide><path>Library/Homebrew/dev-cmd/release-notes.rb
<ide> def release_notes
<ide> .lines.grep(/Merge pull request/)
<ide>
<ide> output.map! do |s|
<del> s.gsub(/.*Merge pull request #(\d+) from ([^\/]+)\/[^>]*(>>)*/,
<add> s.gsub(%r{.*Merge pull request #(\d+) from ([^/]+)/[^>]*(>>)*},
<ide> "https://github.com/Homebrew/brew/pull/\\1 (@\\2)")
<ide> end
<ide> if ARGV.include?("--markdown") | 1 |
Text | Text | update writeable nested serializer doc | 764dabd29e127a0b1a07794f8268a1b1535d9507 | <ide><path>docs/api-guide/serializers.md
<ide> Here's an example for an `.update()` method on our previous `UserSerializer` cla
<ide> def update(self, instance, validated_data):
<ide> profile_data = validated_data.pop('profile')
<ide> # Unless the application properly enforces that this field is
<del> # always set, the follow could raise a `DoesNotExist`, which
<add> # always set, the following could raise a `DoesNotExist`, which
<ide> # would need to be handled.
<ide> profile = instance.profile
<ide> | 1 |
PHP | PHP | fix condition to appease psalm | 88856b765c91e212c96669342d897e8dd334183d | <ide><path>src/TestSuite/IntegrationTestTrait.php
<ide> protected function _addTokens(string $url, array $data): array
<ide> $token = $middleware->createToken();
<ide> } elseif (isset($this->_cookie['csrfToken'])) {
<ide> $token = $this->_cookie['csrfToken'];
<del> } elseif (isset($this->_session['csrfToken'])) {
<add> } else {
<ide> $token = $this->_session['csrfToken'];
<ide> }
<ide> | 1 |
Text | Text | add stability message for atom.io api | 126d0d1b3c7b8dd0291418bd8326206314854693 | <ide><path>docs/apm-rest-api.md
<ide> and making sure you have pushed your git tag. In fact, Atom itself shells out to
<ide> uses `apm`, see the [PackageManager class](https://github.com/atom/settings-view/blob/master/lib/package-manager.coffee)
<ide> in the `settings-view` package.
<ide>
<add>*This API should be considered pre-release and is subject to change (though significant breaking changes are unlikely).*
<add>
<ide> ### Authorization
<ide>
<ide> For calls to the API that require authentication, provide a valid token from your | 1 |
Java | Java | add @author tags for jdbc keyholder support | 50391ad3d7a2f16de7466e1cd60b8ac49929fd06 | <ide><path>spring-jdbc/src/main/java/org/springframework/jdbc/support/GeneratedKeyHolder.java
<ide> *
<ide> * @author Thomas Risberg
<ide> * @author Juergen Hoeller
<add> * @author Slawomir Dymitrow
<ide> * @since 1.1
<ide> */
<ide> public class GeneratedKeyHolder implements KeyHolder {
<ide><path>spring-jdbc/src/main/java/org/springframework/jdbc/support/KeyHolder.java
<ide> *
<ide> * @author Thomas Risberg
<ide> * @author Juergen Hoeller
<add> * @author Slawomir Dymitrow
<ide> * @since 1.1
<ide> * @see org.springframework.jdbc.core.JdbcTemplate
<ide> * @see org.springframework.jdbc.object.SqlUpdate | 2 |
PHP | PHP | adjust behavior of attribute bag | e9d3e71d529fcb5764c7d13eaab26deca0ffe4e1 | <ide><path>src/Illuminate/View/ComponentAttributeBag.php
<ide> namespace Illuminate\View;
<ide>
<ide> use ArrayAccess;
<add>use Illuminate\Support\Arr;
<ide> use Illuminate\Support\HtmlString;
<ide>
<ide> class ComponentAttributeBag implements ArrayAccess
<ide> public function __construct(array $attributes = [])
<ide> * @param mixed $default
<ide> * @return mixed
<ide> */
<del> public function only($key, $default = null)
<add> public function get($key, $default = null)
<ide> {
<ide> return $this->attributes[$key] ?? value($default);
<ide> }
<ide>
<add> /**
<add> * Get a given attribute from the attribute array.
<add> *
<add> * @param array|string $key
<add> * @param mixed $default
<add> * @return static
<add> */
<add> public function only($keys)
<add> {
<add> if (is_null($keys)) {
<add> $values = $this->attributes;
<add> } else {
<add> $keys = Arr::wrap($keys);
<add>
<add> $values = Arr::only($this->attributes, $keys);
<add> }
<add>
<add> return new static($values);
<add> }
<add>
<ide> /**
<ide> * Implode the given attributes into a single HTML ready string.
<ide> *
<ide> public function offsetExists($offset)
<ide> */
<ide> public function offsetGet($offset)
<ide> {
<del> return $this->only($offset);
<add> return $this->get($offset);
<ide> }
<ide>
<ide> /**
<ide><path>tests/View/ViewComponentTest.php
<ide>
<ide> class ViewComponentTest extends TestCase
<ide> {
<del> public function testAttributeRetrieval()
<del> {
<del> $component = new TestViewComponent;
<del> $component->withAttributes(['class' => 'font-bold', 'name' => 'test']);
<del>
<del> $this->assertEquals('class="mt-4 font-bold" name="test"', (string) $component->attributes(['class' => 'mt-4']));
<del> }
<del>
<ide> public function testDataExposure()
<ide> {
<ide> $component = new TestViewComponent; | 2 |
Text | Text | titlecase the word "with" | e54980efd8d2a409b2267d318182134b9a37b396 | <ide><path>docs/Typechecking.md
<del># Type Checking with Sorbet
<add># Type Checking With Sorbet
<ide>
<ide> The majority of the code in Homebrew is written in Ruby which is a dynamic
<ide> language. To avail the benefits of static type checking, we have set up Sorbet in | 1 |
Python | Python | improve error handling in run_command | 889128e5c586f39eb6f18ae6a6b6fbe1505f4080 | <ide><path>spacy/util.py
<ide> def join_command(command: List[str]) -> str:
<ide> def run_command(
<ide> command: Union[str, List[str]],
<ide> *,
<del> capture: bool = False,
<ide> stdin: Optional[Any] = None,
<add> capture: bool=False,
<ide> ) -> Optional[subprocess.CompletedProcess]:
<ide> """Run a command on the command line as a subprocess. If the subprocess
<ide> returns a non-zero exit code, a system exit is performed.
<ide>
<ide> command (str / List[str]): The command. If provided as a string, the
<ide> string will be split using shlex.split.
<ide> stdin (Optional[Any]): stdin to read from or None.
<del> capture (bool): Whether to capture the output.
<add> capture (bool): Whether to capture the output and errors. If False,
<add> the stdout and stderr will not be redirected, and if there's an error,
<add> sys.exit will be called with the returncode. You should use capture=False
<add> when you want to turn over execution to the command, and capture=True
<add> when you want to run the command more like a function.
<ide> RETURNS (Optional[CompletedProcess]): The process object.
<ide> """
<ide> if isinstance(command, str):
<del> command = split_command(command)
<add> cmd_list = split_command(command)
<add> cmd_str = command
<add> else:
<add> cmd_list = command
<add> cmd_str = " ".join(command)
<ide> try:
<ide> ret = subprocess.run(
<del> command,
<add> cmd_list,
<ide> env=os.environ.copy(),
<ide> input=stdin,
<ide> encoding="utf8",
<del> check=True,
<add> check=False,
<ide> stdout=subprocess.PIPE if capture else None,
<del> stderr=subprocess.PIPE if capture else None,
<add> stderr=subprocess.STDOUT if capture else None,
<ide> )
<ide> except FileNotFoundError:
<add> # Indicates the *command* wasn't found, it's an error before the command
<add> # is run.
<ide> raise FileNotFoundError(
<del> Errors.E970.format(str_command=" ".join(command), tool=command[0])
<add> Errors.E970.format(str_command=cmd_str, tool=cmd_list[0])
<ide> ) from None
<del> except subprocess.CalledProcessError as e:
<del> # We don't want a duplicate traceback here so we're making sure the
<del> # CalledProcessError isn't re-raised. We also print both the string
<del> # message and the stderr, in case the error only has one of them.
<del> print(e.stderr)
<del> print(e)
<del> sys.exit(1)
<del> if ret.returncode != 0:
<add> if ret.returncode != 0 and capture:
<add> message = f"Error running command:\n\n{cmd_str}\n\n"
<add> message += f"Subprocess exited with status {ret.returncode}"
<add> if ret.stdout is not None:
<add> message += f"\n\nProcess log (stdout and stderr):\n\n"
<add> message += ret.stdout
<add> error = subprocess.SubprocessError(message)
<add> error.ret = ret
<add> error.command = cmd_str
<add> raise error
<add> elif ret.returncode != 0:
<ide> sys.exit(ret.returncode)
<ide> return ret
<ide> | 1 |
Ruby | Ruby | use existing constant for joining instead of '_' | 25991b94c7cb3d1763b79c67dfadf2aec974eebe | <ide><path>actionview/lib/action_view/record_identifier.rb
<ide> def dom_id(record, prefix = nil)
<ide> # make sure yourself that your dom ids are valid, in case you overwrite this method.
<ide> def record_key_for_dom_id(record)
<ide> key = convert_to_model(record).to_key
<del> key ? key.join('_') : key
<add> key ? key.join(JOIN) : key
<ide> end
<ide> end
<ide> end | 1 |
Ruby | Ruby | add missing requires | 1cddc91a02be8627dd266d79af1ee2675218fdfe | <ide><path>activemodel/lib/active_model/attribute.rb
<ide> # frozen_string_literal: true
<ide>
<ide> require "active_support/core_ext/object/duplicable"
<add>require "active_model/type"
<ide>
<ide> module ActiveModel
<ide> class Attribute # :nodoc: | 1 |
Javascript | Javascript | expand test coverage of readline | d37f27a00830f364f3375fed996ecb75e61f7f9b | <ide><path>test/parallel/test-readline-csi.js
<add>// Flags: --expose-internals
<add>'use strict';
<add>
<add>const common = require('../common');
<add>const assert = require('assert');
<add>const readline = require('readline');
<add>const { Writable } = require('stream');
<add>const { CSI } = require('internal/readline');
<add>
<add>{
<add> assert(CSI);
<add> assert.strictEqual(CSI.kClearToBeginning, '\x1b[1K');
<add> assert.strictEqual(CSI.kClearToEnd, '\x1b[0K');
<add> assert.strictEqual(CSI.kClearLine, '\x1b[2K');
<add> assert.strictEqual(CSI.kClearScreenDown, '\x1b[0J');
<add> assert.strictEqual(CSI`1${2}3`, '\x1b[123');
<add>}
<add>
<add>class TestWritable extends Writable {
<add> constructor() {
<add> super();
<add> this.data = '';
<add> }
<add> _write(chunk, encoding, callback) {
<add> this.data += chunk.toString();
<add> callback();
<add> }
<add>}
<add>
<add>const writable = new TestWritable();
<add>
<add>readline.clearScreenDown(writable);
<add>assert.deepStrictEqual(writable.data, CSI.kClearScreenDown);
<add>
<add>writable.data = '';
<add>readline.clearLine(writable, -1);
<add>assert.deepStrictEqual(writable.data, CSI.kClearToBeginning);
<add>
<add>writable.data = '';
<add>readline.clearLine(writable, 1);
<add>assert.deepStrictEqual(writable.data, CSI.kClearToEnd);
<add>
<add>writable.data = '';
<add>readline.clearLine(writable, 0);
<add>assert.deepStrictEqual(writable.data, CSI.kClearLine);
<add>
<add>// Nothing is written when moveCursor 0, 0
<add>[
<add> [0, 0, ''],
<add> [1, 0, '\x1b[1C'],
<add> [-1, 0, '\x1b[1D'],
<add> [0, 1, '\x1b[1B'],
<add> [0, -1, '\x1b[1A'],
<add> [1, 1, '\x1b[1C\x1b[1B'],
<add> [-1, 1, '\x1b[1D\x1b[1B'],
<add> [-1, -1, '\x1b[1D\x1b[1A'],
<add> [1, -1, '\x1b[1C\x1b[1A'],
<add>].forEach((set) => {
<add> writable.data = '';
<add> readline.moveCursor(writable, set[0], set[1]);
<add> assert.deepStrictEqual(writable.data, set[2]);
<add>});
<add>
<add>assert.doesNotThrow(() => readline.cursorTo(null));
<add>assert.doesNotThrow(() => readline.cursorTo());
<add>
<add>writable.data = '';
<add>assert.doesNotThrow(() => readline.cursorTo(writable, 'a'));
<add>assert.strictEqual(writable.data, '');
<add>
<add>writable.data = '';
<add>assert.doesNotThrow(() => readline.cursorTo(writable, 'a', 'b'));
<add>assert.strictEqual(writable.data, '');
<add>
<add>writable.data = '';
<add>assert.throws(
<add> () => readline.cursorTo(writable, 'a', 1),
<add> common.expectsError({
<add> type: Error,
<add> message: /^Can't set cursor row without also setting it's column$/
<add> }));
<add>assert.strictEqual(writable.data, '');
<add>
<add>writable.data = '';
<add>assert.doesNotThrow(() => readline.cursorTo(writable, 1, 'a'));
<add>assert.strictEqual(writable.data, '\x1b[2G');
<add>
<add>writable.data = '';
<add>assert.doesNotThrow(() => readline.cursorTo(writable, 1, 2));
<add>assert.strictEqual(writable.data, '\x1b[3;2H'); | 1 |
Javascript | Javascript | remove function export from helper blueprint | e29a526b3c3a785b2830df2b55679667e9f0f24e | <ide><path>blueprints/helper/files/__root__/__collection__/__name__.js
<ide> import { helper } from '@ember/component/helper';
<ide>
<del>export function <%= camelizedModuleName %>(params/*, hash*/) {
<add>export default helper(function <%= camelizedModuleName %>(params/*, hash*/) {
<ide> return params;
<del>}
<del>
<del>export default helper(<%= camelizedModuleName %>);
<add>});
<ide><path>node-tests/fixtures/helper/helper.js
<ide> import { helper } from '@ember/component/helper';
<ide>
<del>export function fooBarBaz(params/*, hash*/) {
<add>export default helper(function fooBarBaz(params/*, hash*/) {
<ide> return params;
<del>}
<del>
<del>export default helper(fooBarBaz);
<add>}); | 2 |
PHP | PHP | stop email reverification with same link | f7b6362c6e46e759859a048cef02ff59a172329b | <ide><path>src/Illuminate/Foundation/Auth/VerifiesEmails.php
<ide> public function verify(Request $request)
<ide> if ($request->route('id') != $request->user()->getKey()) {
<ide> throw new AuthorizationException;
<ide> }
<add>
<add> if ($request->user()->hasVerifiedEmail()) {
<add> return redirect($this->redirectPath());
<add> }
<ide>
<ide> if ($request->user()->markEmailAsVerified()) {
<ide> event(new Verified($request->user())); | 1 |
Ruby | Ruby | handle false in relation strict loading checks | 226007daa1e1332da1b0b68a859913c43df0d2c7 | <ide><path>activerecord/lib/active_record/associations/association.rb
<ide> def create!(attributes = nil, &block)
<ide>
<ide> private
<ide> def find_target
<del> if (owner.strict_loading? || reflection.strict_loading?) && owner.validation_context.nil?
<add> if strict_loading? && owner.validation_context.nil?
<ide> Base.strict_loading_violation!(owner: owner.class, reflection: reflection)
<ide> end
<ide>
<ide> def find_target
<ide> sc.execute(binds, klass.connection) { |record| set_inverse_instance(record) }
<ide> end
<ide>
<add> def strict_loading?
<add> return reflection.strict_loading? if reflection.options.key?(:strict_loading)
<add>
<add> owner.strict_loading?
<add> end
<add>
<ide> # The scope for this association.
<ide> #
<ide> # Note that the association_scope is merged into the target_scope only when the
<ide><path>activerecord/test/cases/strict_loading_test.rb
<ide> def test_raises_on_lazy_loading_a_belongs_to_relation_if_strict_loading_by_defau
<ide> end
<ide> end
<ide>
<add> def test_raises_on_lazy_loading_a_belongs_to_relation_if_strict_loading_by_default
<add> with_strict_loading_by_default(Developer) do
<add> mentor = Mentor.create!(name: "Mentor")
<add>
<add> developer = Developer.first
<add> developer.update_column(:mentor_id, mentor.id)
<add>
<add> assert_nothing_raised do
<add> developer.strict_loading_off_mentor
<add> end
<add> end
<add> end
<add>
<add>
<ide> def test_does_not_raise_on_eager_loading_a_strict_loading_belongs_to_relation
<ide> mentor = Mentor.create!(name: "Mentor")
<ide>
<ide><path>activerecord/test/models/developer.rb
<ide> def find_most_recent
<ide>
<ide> belongs_to :mentor
<ide> belongs_to :strict_loading_mentor, strict_loading: true, foreign_key: :mentor_id, class_name: "Mentor"
<add> belongs_to :strict_loading_off_mentor, strict_loading: false, foreign_key: :mentor_id, class_name: "Mentor"
<ide>
<ide> accepts_nested_attributes_for :projects
<ide>
<ide><path>activestorage/test/models/attachment_test.rb
<ide> class ActiveStorage::AttachmentTest < ActiveSupport::TestCase
<ide> assert_equal blob, ActiveStorage::Blob.find_signed!(signed_id_generated_old_way)
<ide> end
<ide>
<add> test "attaching with strict_loading and getting a signed blob ID from an attachment" do
<add> blob = create_blob
<add> @user.strict_loading!(true)
<add> @user.avatar.attach(blob)
<add>
<add> signed_id = @user.avatar.signed_id
<add> assert_equal blob, ActiveStorage::Blob.find_signed(signed_id)
<add> end
<add>
<ide> private
<ide> def assert_blob_identified_before_owner_validated(owner, blob, content_type)
<ide> validated_content_type = nil | 4 |
Javascript | Javascript | add simple fullscreen config | d9d4e3756307dca5999b3099cf797b3859d0cb8d | <ide><path>src/config-schema.js
<ide> if (process.platform === 'darwin') {
<ide> description:
<ide> 'Experimental: A `custom` title bar adapts to theme colors. Choosing `custom-inset` adds a bit more padding. The title bar can also be completely `hidden`.<br>Note: Switching to a custom or hidden title bar will compromise some functionality.<br>This setting will require a relaunch of Atom to take effect.'
<ide> };
<add>
<add> configSchema.core.properties.simpleFullScreenWindows = {
<add> type: 'boolean',
<add> default: false,
<add> description:
<add> 'Use pre-Lion fullscreen on macOS. This does not create a new desktop space for the atom on fullscreen mode.'
<add> };
<ide> }
<ide>
<ide> module.exports = configSchema;
<ide><path>src/main-process/atom-window.js
<ide> module.exports = class AtomWindow extends EventEmitter {
<ide> disableBlinkFeatures: 'Auxclick',
<ide> nodeIntegration: true,
<ide> webviewTag: true
<del> }
<add> },
<add> simpleFullscreen: this.getSimpleFullscreen()
<ide> };
<ide>
<ide> // Don't set icon on Windows so the exe's ico will be used as window and
<ide> module.exports = class AtomWindow extends EventEmitter {
<ide> return { x, y, width, height };
<ide> }
<ide>
<add> getSimpleFullscreen() {
<add> return this.atomApplication.config.get('core.simpleFullScreenWindows');
<add> }
<add>
<ide> shouldAddCustomTitleBar() {
<ide> return (
<ide> !this.isSpec && | 2 |
Python | Python | support utf8 description | 2deb31d0968c77f40c63e0ffb9f655e69fbe1d96 | <ide><path>djangorestframework/views.py
<ide> def get_description(self, html=False):
<ide>
<ide> description = _remove_leading_indent(description)
<ide>
<add> if not isinstance(description, unicode):
<add> description = description.decode('UTF-8')
<add>
<ide> if html:
<ide> return self.markup_description(description)
<ide> return description | 1 |
Ruby | Ruby | fix typo in api docs | 1ae397b5b44eb0bbb797ba63cd9ff63854c4ff06 | <ide><path>actionpack/lib/action_controller/metal/strong_parameters.rb
<ide> def transform_keys!(&block)
<ide> # Deletes a key-value pair from +Parameters+ and returns the value. If
<ide> # +key+ is not found, returns +nil+ (or, with optional code block, yields
<ide> # +key+ and returns the result). Cf. +#extract!+, which returns the
<del> # corresponding +ActionController::Paramters+ object.
<add> # corresponding +ActionController::Parameters+ object.
<ide> def delete(key, &block)
<ide> convert_value_to_parameters(@parameters.delete(key, &block))
<ide> end | 1 |
Mixed | Javascript | add peeking feature in androidviewpage(rn) | c42080eaaf20710728975aec0180a81cfffb36f3 | <ide><path>Libraries/Components/ViewPager/ViewPagerAndroid.android.js
<ide> class ViewPagerAndroid extends React.Component {
<ide> onPageScrollStateChanged?: Function,
<ide> onPageSelected?: Function,
<ide> pageMargin?: number,
<add> peekEnabled?: boolean,
<ide> keyboardDismissMode?: 'none' | 'on-drag',
<ide> scrollEnabled?: boolean,
<ide> };
<ide> class ViewPagerAndroid extends React.Component {
<ide> * The default value is true.
<ide> */
<ide> scrollEnabled: PropTypes.bool,
<add>
<add> /**
<add> * Whether enable showing peekFraction or not. If this is true, the preview of
<add> * last and next page will show in current screen. Defaults to false.
<add> */
<add> peekEnabled: PropTypes.bool,
<ide> };
<ide>
<ide> componentDidMount() {
<ide><path>ReactAndroid/src/main/java/com/facebook/react/views/viewpager/ReactViewPagerManager.java
<ide> public void removeViewAt(ReactViewPager parent, int index) {
<ide> public void setPageMargin(ReactViewPager pager, float margin) {
<ide> pager.setPageMargin((int) PixelUtil.toPixelFromDIP(margin));
<ide> }
<add>
<add> @ReactProp(name = "peekEnabled", defaultBoolean = false)
<add> public void setPeekEnabled(ReactViewPager pager, boolean peekEnabled) {
<add> pager.setClipToPadding(!peekEnabled);
<add> }
<ide> } | 2 |
PHP | PHP | fix undefined variables | 52777eecdca8fbafe4ea07498953aabb548481f2 | <ide><path>src/Illuminate/Database/Connectors/Connector.php
<ide> public function createConnection($dsn, array $config, array $options)
<ide> );
<ide> } catch (Exception $e) {
<ide> return $this->tryAgainIfCausedByLostConnection(
<del> $e, $dsn, $username, $password, $options
<add> $e, $dsn, Arr::get($config, 'username'), Arr::get($config, 'password'), $options
<ide> );
<ide> }
<ide> } | 1 |
Javascript | Javascript | set testswarm.runmax from config file | 6af0bcc6262062aa99102a7a9bbde36779f1388f | <ide><path>grunt.js
<ide> module.exports = function( grunt ) {
<ide> authUsername: config.authUsername,
<ide> authToken: config.authToken,
<ide> jobName: 'jQuery commit #<a href="https://github.com/jquery/jquery/commit/' + commit + '">' + commit.substr( 0, 10 ) + '</a>',
<del> runMax: 4,
<add> runMax: config.runMax,
<ide> "runNames[]": tests,
<ide> "runUrls[]": testUrls,
<ide> "browserSets[]": ["popular"] | 1 |
Text | Text | add two css multi-column properties to index.md | 8448e712995c35a0b287832d137c3ae98508086e | <ide><path>guide/english/css/css3-multiple-columns/index.md
<ide> Unfortunately this is impossible to do with CSS and HTML without forcing column
<ide>
<ide> There are several properties that let you customize multi-column layout:
<ide> * column-count
<add>* column-fill
<ide> * column-gap
<ide> * column-rule-style
<ide> * column-rule-width
<ide> * column-rule-color
<ide> * column-rule
<ide> * column-span
<ide> * column-width
<add>* columns
<ide>
<ide> <!-- The article goes here, in GitHub-flavored Markdown. Feel free to add YouTube videos, images, and CodePen/JSBin embeds -->
<ide> | 1 |
Ruby | Ruby | use an empty attributemethodmatcher by default | 8b8b7143efe2e0bac5bcfe90264e4baa66bdb532 | <ide><path>activemodel/lib/active_model/attribute_methods.rb
<ide> module AttributeMethods
<ide>
<ide> included do
<ide> class_attribute :attribute_method_matchers, :instance_writer => false
<del> self.attribute_method_matchers = []
<add> self.attribute_method_matchers = [ClassMethods::AttributeMethodMatcher.new]
<ide> end
<ide>
<ide> module ClassMethods
<ide> def attribute_method_matcher(method_name)
<ide> if attribute_method_matchers_cache.key?(method_name)
<ide> attribute_method_matchers_cache[method_name]
<ide> else
<add> # Must try to match prefixes/suffixes first, or else the matcher with no prefix/suffix
<add> # will match every time.
<add> matchers = attribute_method_matchers.partition(&:plain?).reverse.flatten(1)
<ide> match = nil
<del> attribute_method_matchers.detect { |method| match = method.match(method_name) }
<add> matchers.detect { |method| match = method.match(method_name) }
<ide> attribute_method_matchers_cache[method_name] = match
<ide> end
<ide> end
<ide> def match(method_name)
<ide> def method_name(attr_name)
<ide> @method_name % attr_name
<ide> end
<add>
<add> def plain?
<add> prefix.empty? && suffix.empty?
<add> end
<ide> end
<ide> end
<ide>
<ide><path>activemodel/test/cases/attribute_methods_test.rb
<ide> def attribute(name)
<ide> class ModelWithAttributes2
<ide> include ActiveModel::AttributeMethods
<ide>
<add> attr_accessor :attributes
<add>
<ide> attribute_method_suffix '_test'
<add>
<add>private
<add> def attribute(name)
<add> attributes[name.to_s]
<add> end
<add>
<add> alias attribute_test attribute
<ide> end
<ide>
<ide> class ModelWithAttributesWithSpaces
<ide> class AttributeMethodsTest < ActiveModel::TestCase
<ide> assert !ModelWithAttributes.new.respond_to?(:foo)
<ide> assert_raises(NoMethodError) { ModelWithAttributes.new.foo }
<ide> end
<add>
<add> test 'acessing a suffixed attribute' do
<add> m = ModelWithAttributes2.new
<add> m.attributes = { 'foo' => 'bar' }
<add>
<add> assert_equal 'bar', m.foo
<add> assert_equal 'bar', m.foo_test
<add> end
<ide> end | 2 |
Go | Go | add flag for inter-container communication | ce965b8c43f91f0c32403cfaadfd4e279421090b | <ide><path>config.go
<ide> import (
<ide> )
<ide>
<ide> type DaemonConfig struct {
<del> Pidfile string
<del> GraphPath string
<del> ProtoAddresses []string
<del> AutoRestart bool
<del> EnableCors bool
<del> Dns []string
<del> EnableIptables bool
<del> BridgeIface string
<del> DefaultIp net.IP
<add> Pidfile string
<add> GraphPath string
<add> ProtoAddresses []string
<add> AutoRestart bool
<add> EnableCors bool
<add> Dns []string
<add> EnableIptables bool
<add> BridgeIface string
<add> DefaultIp net.IP
<add> InterContainerCommunication bool
<ide> }
<ide><path>docker/docker.go
<ide> func main() {
<ide> flag.Var(&flHosts, "H", "tcp://host:port to bind/connect to or unix://path/to/socket to use")
<ide> flEnableIptables := flag.Bool("iptables", true, "Disable iptables within docker")
<ide> flDefaultIp := flag.String("ip", "0.0.0.0", "Default ip address to use when binding a containers ports")
<add> flInterContainerComm := flag.Bool("enable-container-comm", false, "Enable inter-container communication")
<ide>
<ide> flag.Parse()
<ide>
<ide> func main() {
<ide> ip := net.ParseIP(*flDefaultIp)
<ide>
<ide> config := &docker.DaemonConfig{
<del> Pidfile: *pidfile,
<del> GraphPath: *flGraphPath,
<del> AutoRestart: *flAutoRestart,
<del> EnableCors: *flEnableCors,
<del> Dns: dns,
<del> EnableIptables: *flEnableIptables,
<del> BridgeIface: bridge,
<del> ProtoAddresses: flHosts,
<del> DefaultIp: ip,
<add> Pidfile: *pidfile,
<add> GraphPath: *flGraphPath,
<add> AutoRestart: *flAutoRestart,
<add> EnableCors: *flEnableCors,
<add> Dns: dns,
<add> EnableIptables: *flEnableIptables,
<add> BridgeIface: bridge,
<add> ProtoAddresses: flHosts,
<add> DefaultIp: ip,
<add> InterContainerCommunication: *flInterContainerComm,
<ide> }
<ide> if err := daemon(config); err != nil {
<ide> log.Fatal(err)
<ide><path>network.go
<ide> func CreateBridgeIface(config *DaemonConfig) error {
<ide> if output, err := ip("link", "set", config.BridgeIface, "up"); err != nil {
<ide> return fmt.Errorf("Unable to start network bridge: %s (%s)", err, output)
<ide> }
<add>
<ide> if config.EnableIptables {
<ide> if err := iptables.Raw("-t", "nat", "-A", "POSTROUTING", "-s", ifaceAddr,
<ide> "!", "-d", ifaceAddr, "-j", "MASQUERADE"); err != nil {
<ide> return fmt.Errorf("Unable to enable network bridge NAT: %s", err)
<ide> }
<del> // Prevent inter-container communication by default
<del> if err := iptables.Raw("-A", "FORWARD", "-i", config.BridgeIface, "-o", config.BridgeIface, "-j", "DROP"); err != nil {
<del> return fmt.Errorf("Unable to prevent intercontainer communication: %s", err)
<add>
<add> if !config.InterContainerCommunication {
<add> utils.Debugf("Disable inter-container communication")
<add> if err := iptables.Raw("-A", "FORWARD", "-i", config.BridgeIface, "-o", config.BridgeIface, "-j", "DROP"); err != nil {
<add> return fmt.Errorf("Unable to prevent intercontainer communication: %s", err)
<add> }
<add> } else {
<add> utils.Debugf("Enable inter-container communication")
<add> iptables.Raw("-D", "FORWARD", "-i", config.BridgeIface, "-o", config.BridgeIface, "-j", "DROP")
<ide> }
<ide> }
<ide> return nil | 3 |
Ruby | Ruby | use regex escape sequences to shorten stuff up | 9c219bf3616e62d607593bbb4b96c53f6d5436af | <ide><path>actionpack/lib/action_view/helpers/number_helper.rb
<ide> def number_to_phone(number, options = {})
<ide> country_code = options[:country_code]
<ide>
<ide> if area_code
<del> number.gsub!(/([0-9]{1,3})([0-9]{3})([0-9]{4}$)/,"(\\1) \\2#{delimiter}\\3")
<add> number.gsub!(/(\d{1,3})(\d{3})(\d{4}$)/,"(\\1) \\2#{delimiter}\\3")
<ide> else
<del> number.gsub!(/([0-9]{0,3})([0-9]{3})([0-9]{4})$/,"\\1#{delimiter}\\2#{delimiter}\\3")
<add> number.gsub!(/(\d{0,3})(\d{3})(\d{4})$/,"\\1#{delimiter}\\2#{delimiter}\\3")
<ide> number.slice!(0, 1) if number.starts_with?('-')
<ide> end
<ide> | 1 |
Text | Text | shorten some links in readme.md | aad17dac3580e80b9f4c915c9e7d9feac4e8eabd | <ide><path>README.md
<ide> Second, read the [Troubleshooting Checklist](https://docs.brew.sh/Troubleshootin
<ide> [](https://travis-ci.org/Homebrew/brew)
<ide> [](https://codecov.io/gh/Homebrew/brew)
<ide>
<del>We'd love you to contribute to Homebrew. First, please read our [Contribution Guide](https://github.com/Homebrew/brew/blob/master/CONTRIBUTING.md) and [Code of Conduct](https://github.com/Homebrew/brew/blob/master/CODE_OF_CONDUCT.md#code-of-conduct).
<add>We'd love you to contribute to Homebrew. First, please read our [Contribution Guide](CONTRIBUTING.md) and [Code of Conduct](CODE_OF_CONDUCT.md#code-of-conduct).
<ide>
<ide> We explicitly welcome contributions from people who have never contributed to open-source before: we were all beginners once! We can help build on a partially working pull request with the aim of getting it merged. We are also actively seeking to diversify our contributors and especially welcome contributions from women from all backgrounds and people of colour.
<ide>
<ide> Former maintainers with significant contributions include [Tim Smith](https://gi
<ide> - [@MacHomebrew (Twitter)](https://twitter.com/MacHomebrew)
<ide>
<ide> ## License
<del>Code is under the [BSD 2-clause "Simplified" License](https://github.com/Homebrew/brew/tree/master/LICENSE.txt).
<add>Code is under the [BSD 2-clause "Simplified" License](LICENSE.txt).
<ide> Documentation is under the [Creative Commons Attribution license](https://creativecommons.org/licenses/by/4.0/).
<ide>
<ide> ## Donations | 1 |
Javascript | Javascript | add comments for diff algorithm | eccc65919a6dc9a05936e070181a16604ba346e6 | <ide><path>lib/internal/assert.js
<ide> function createErrDiff(actual, expected, operator) {
<ide> // Only extra expected lines exist
<ide> const cur = i - lastPos;
<ide> if (actualLines.length < i + 1) {
<add> // If the last diverging line is more than one line above and the
<add> // current line is at least line three, add some of the former lines and
<add> // also add dots to indicate skipped entries.
<ide> if (cur > 1 && i > 2) {
<ide> if (cur > 4) {
<ide> res += `\n${blue}...${white}`;
<ide> function createErrDiff(actual, expected, operator) {
<ide> res += `\n ${expectedLines[i - 1]}`;
<ide> printedLines++;
<ide> }
<add> // Mark the current line as the last diverging one.
<ide> lastPos = i;
<add> // Add the expected line to the cache.
<ide> other += `\n${red}-${white} ${expectedLines[i]}`;
<ide> printedLines++;
<ide> // Only extra actual lines exist
<ide> } else if (expectedLines.length < i + 1) {
<add> // If the last diverging line is more than one line above and the
<add> // current line is at least line three, add some of the former lines and
<add> // also add dots to indicate skipped entries.
<ide> if (cur > 1 && i > 2) {
<ide> if (cur > 4) {
<ide> res += `\n${blue}...${white}`;
<ide> function createErrDiff(actual, expected, operator) {
<ide> res += `\n ${actualLines[i - 1]}`;
<ide> printedLines++;
<ide> }
<add> // Mark the current line as the last diverging one.
<ide> lastPos = i;
<add> // Add the actual line to the result.
<ide> res += `\n${green}+${white} ${actualLines[i]}`;
<ide> printedLines++;
<ide> // Lines diverge
<ide> } else {
<ide> const expectedLine = expectedLines[i];
<ide> let actualLine = actualLines[i];
<add> // If the lines diverge, specifically check for lines that only diverge by
<add> // a trailing comma. In that case it is actually identical and we should
<add> // mark it as such.
<ide> let divergingLines = actualLine !== expectedLine &&
<ide> (!actualLine.endsWith(',') ||
<ide> actualLine.slice(0, -1) !== expectedLine);
<add> // If the expected line has a trailing comma but is otherwise identical,
<add> // add a comma at the end of the actual line. Otherwise the output could
<add> // look weird as in:
<add> //
<add> // [
<add> // 1 // No comma at the end!
<add> // + 2
<add> // ]
<add> //
<ide> if (divergingLines &&
<ide> expectedLine.endsWith(',') &&
<ide> expectedLine.slice(0, -1) === actualLine) {
<ide> divergingLines = false;
<ide> actualLine += ',';
<ide> }
<ide> if (divergingLines) {
<add> // If the last diverging line is more than one line above and the
<add> // current line is at least line three, add some of the former lines and
<add> // also add dots to indicate skipped entries.
<ide> if (cur > 1 && i > 2) {
<ide> if (cur > 4) {
<ide> res += `\n${blue}...${white}`;
<ide> function createErrDiff(actual, expected, operator) {
<ide> res += `\n ${actualLines[i - 1]}`;
<ide> printedLines++;
<ide> }
<add> // Mark the current line as the last diverging one.
<ide> lastPos = i;
<add> // Add the actual line to the result and cache the expected diverging
<add> // line so consecutive diverging lines show up as +++--- and not +-+-+-.
<ide> res += `\n${green}+${white} ${actualLine}`;
<ide> other += `\n${red}-${white} ${expectedLine}`;
<ide> printedLines += 2;
<ide> // Lines are identical
<ide> } else {
<add> // Add all cached information to the result before adding other things
<add> // and reset the cache.
<ide> res += other;
<ide> other = '';
<add> // If the last diverging line is exactly one line above or if it is the
<add> // very first line, add the line to the result.
<ide> if (cur === 1 || i === 0) {
<ide> res += `\n ${actualLine}`;
<ide> printedLines++;
<ide> function createErrDiff(actual, expected, operator) {
<ide> // Inspected object to big (Show ~20 rows max)
<ide> if (printedLines > 20 && i < maxLines - 2) {
<ide> return `${msg}${skippedMsg}\n${res}\n${blue}...${white}${other}\n` +
<del> `${blue}...${white}`;
<add> `${blue}...${white}`;
<ide> }
<ide> }
<ide> | 1 |
Javascript | Javascript | improve serialization of lazy elements | 3db039a183cd836e2783bccd6e8a9d04d4b83b52 | <ide><path>lib/serialization/BinaryMiddleware.js
<ide> class BinaryMiddleware extends SerializerMiddleware {
<ide> case "function": {
<ide> if (!SerializerMiddleware.isLazy(thing))
<ide> throw new Error("Unexpected function " + thing);
<del> /** @type {SerializedType[0]} */
<del> const serializedData = SerializerMiddleware.getLazySerializedValue(
<add> /** @type {SerializedType | (() => SerializedType)} */
<add> let serializedData = SerializerMiddleware.getLazySerializedValue(
<ide> thing
<ide> );
<del> if (serializedData !== undefined) {
<del> if (typeof serializedData === "function") {
<del> flush();
<del> buffers.push(serializedData);
<add> if (serializedData === undefined) {
<add> if (SerializerMiddleware.isLazy(thing, this)) {
<add> const data = this._serialize(thing(), context);
<add> SerializerMiddleware.setLazySerializedValue(thing, data);
<add> serializedData = data;
<ide> } else {
<del> serializeData(serializedData);
<del> allocate(5);
<del> writeU8(LAZY_HEADER);
<del> writeU32(serializedData.length);
<add> serializedData = SerializerMiddleware.serializeLazy(
<add> thing,
<add> data => this._serialize(data, context)
<add> );
<ide> }
<del> } else if (SerializerMiddleware.isLazy(thing, this)) {
<del> /** @type {SerializedType} */
<del> const data = BinaryMiddleware.optimizeSerializedData(
<del> this._serialize(thing(), context)
<del> );
<del> SerializerMiddleware.setLazySerializedValue(thing, data);
<del> serializeData(data);
<del> allocate(5);
<del> writeU8(LAZY_HEADER);
<del> writeU32(data.length);
<del> } else {
<add> }
<add> if (typeof serializedData === "function") {
<ide> flush();
<del> buffers.push(
<del> SerializerMiddleware.serializeLazy(thing, data =>
<del> this._serialize(data, context)
<del> )
<del> );
<add> buffers.push(serializedData);
<add> } else {
<add> const lengths = [];
<add> for (const item of serializedData) {
<add> let last;
<add> if (typeof item === "function") {
<add> lengths.push(0);
<add> } else if (item.length === 0) {
<add> // ignore
<add> } else if (
<add> lengths.length > 0 &&
<add> (last = lengths[lengths.length - 1]) !== 0
<add> ) {
<add> const remaining = 0xffffffff - last;
<add> if (remaining >= item.length) {
<add> lengths[lengths.length - 1] += item.length;
<add> } else {
<add> lengths.push(item.length - remaining);
<add> lengths[lengths.length - 2] = 0xffffffff;
<add> }
<add> } else {
<add> lengths.push(item.length);
<add> }
<add> }
<add> allocate(5 + lengths.length * 4);
<add> writeU8(LAZY_HEADER);
<add> writeU32(lengths.length);
<add> for (const l of lengths) {
<add> writeU32(l);
<add> }
<add> for (const item of serializedData) {
<add> flush();
<add> buffers.push(item);
<add> }
<ide> }
<ide> break;
<ide> }
<ide> class BinaryMiddleware extends SerializerMiddleware {
<ide> checkOverflow();
<ide> return res;
<ide> };
<add> /**
<add> * Reads up to n bytes
<add> * @param {number} n amount of bytes to read
<add> * @returns {Buffer} buffer with bytes
<add> */
<add> const readUpTo = n => {
<add> if (!currentIsBuffer) {
<add> throw new Error(
<add> currentBuffer === null
<add> ? "Unexpected end of stream"
<add> : "Unexpected lazy element in stream"
<add> );
<add> }
<add> const rem = currentBuffer.length - currentPosition;
<add> if (rem < n) {
<add> n = rem;
<add> }
<add> const res = /** @type {Buffer} */ (currentBuffer).slice(
<add> currentPosition,
<add> currentPosition + n
<add> );
<add> currentPosition += n;
<add> checkOverflow();
<add> return res;
<add> };
<ide> const readU8 = () => {
<ide> if (!currentIsBuffer) {
<ide> throw new Error(
<ide> class BinaryMiddleware extends SerializerMiddleware {
<ide> case LAZY_HEADER:
<ide> return () => {
<ide> const count = readU32();
<del> const start = result.length - count;
<del> const data = /** @type {SerializedType} */ (result.slice(start));
<del> result.length = start;
<add> const lengths = Array.from({ length: count }).map(() => readU32());
<add> const content = [];
<add> for (let l of lengths) {
<add> if (l === 0) {
<add> if (typeof currentBuffer !== "function") {
<add> throw new Error("Unexpected non-lazy element in stream");
<add> }
<add> content.push(currentBuffer);
<add> currentDataItem++;
<add> currentBuffer =
<add> currentDataItem < data.length ? data[currentDataItem] : null;
<add> currentIsBuffer = Buffer.isBuffer(currentBuffer);
<add> } else {
<add> do {
<add> const buf = readUpTo(l);
<add> l -= buf.length;
<add> content.push(buf);
<add> } while (l > 0);
<add> }
<add> }
<ide> result.push(
<ide> SerializerMiddleware.createLazy(
<del> memorize(() => this._deserialize(data, context)),
<add> memorize(() => this._deserialize(content, context)),
<ide> this,
<ide> undefined,
<del> data
<add> content
<ide> )
<ide> );
<ide> };
<ide> class BinaryMiddleware extends SerializerMiddleware {
<ide> return () => result.push(null, false);
<ide> case NULL_AND_I8_HEADER:
<ide> return () => {
<del> if (currentBuffer) {
<add> if (currentIsBuffer) {
<ide> result.push(
<ide> null,
<ide> /** @type {Buffer} */ (currentBuffer).readInt8(currentPosition)
<ide> class BinaryMiddleware extends SerializerMiddleware {
<ide> return () => result.push("");
<ide> case SHORT_STRING_HEADER | 1:
<ide> return () => {
<del> if (currentBuffer) {
<add> if (currentIsBuffer) {
<ide> result.push(
<ide> currentBuffer.toString(
<ide> "latin1",
<ide> class BinaryMiddleware extends SerializerMiddleware {
<ide> };
<ide> case I8_HEADER:
<ide> return () => {
<del> if (currentBuffer) {
<add> if (currentIsBuffer) {
<ide> result.push(
<ide> /** @type {Buffer} */ (currentBuffer).readInt8(currentPosition)
<ide> );
<ide> class BinaryMiddleware extends SerializerMiddleware {
<ide> currentBuffer =
<ide> currentDataItem < data.length ? data[currentDataItem] : null;
<ide> currentIsBuffer = Buffer.isBuffer(currentBuffer);
<del> continue;
<add> } else {
<add> const header = readU8();
<add> dispatchTable[header]();
<ide> }
<del> const header = readU8();
<del> dispatchTable[header]();
<ide> }
<ide> return result;
<ide> }
<ide><path>test/BinaryMiddleware.unittest.js
<ide> const BinaryMiddleware = require("../lib/serialization/BinaryMiddleware");
<add>const SerializerMiddleware = require("../lib/serialization/SerializerMiddleware");
<ide>
<ide> const cont = (base, count) => {
<ide> const result = [];
<ide> const cont = (base, count) => {
<ide> return result;
<ide> };
<ide>
<add>const mw = new BinaryMiddleware();
<add>const other = { other: true };
<add>
<add>const resolveLazy = item => {
<add> if (SerializerMiddleware.isLazy(item)) {
<add> // console.log("resolve lazy", item);
<add> const data = item();
<add> // console.log("resolve lazy done", data);
<add> if (Array.isArray(data)) return { resolvesTo: data.map(resolveLazy) };
<add> return { resolvesTo: resolveLazy(data) };
<add> }
<add> return item;
<add>};
<add>
<ide> describe("BinaryMiddleware", () => {
<ide> const items = [
<del> undefined,
<ide> true,
<ide> false,
<ide> null,
<ide> describe("BinaryMiddleware", () => {
<ide> -1,
<ide> -11,
<ide> -0x100,
<del> -1.25
<add> -1.25,
<add> SerializerMiddleware.createLazy([5], other),
<add> SerializerMiddleware.createLazy(
<add> [SerializerMiddleware.createLazy([5], other)],
<add> mw
<add> ),
<add> SerializerMiddleware.createLazy(
<add> [
<add> 1,
<add> SerializerMiddleware.createLazy([2], mw),
<add> SerializerMiddleware.createLazy([5], other),
<add> 4
<add> ],
<add> mw
<add> )
<ide> ];
<add> items.push(SerializerMiddleware.createLazy(items.slice(), mw));
<add> items.push(SerializerMiddleware.createLazy(items.slice(), other));
<add> items.push(undefined);
<ide>
<ide> const cases = [
<ide> ...items.map(item => [item]),
<del> [true, true],
<add> [(true, true)],
<ide> [false, true],
<ide> [true, false],
<ide> [false, false],
<ide> describe("BinaryMiddleware", () => {
<ide> x => x !== undefined
<ide> );
<ide> if (data.length === 0) continue;
<del> const key = JSON.stringify(data);
<add> const key = JSON.stringify(data.map(resolveLazy));
<ide> it(`should serialize ${key} (${data.length}) correctly`, () => {
<del> const mw = new BinaryMiddleware();
<ide> const serialized = mw.serialize(data, {});
<ide> const newData = mw.deserialize(serialized, {});
<del> expect(newData).toEqual(data);
<add> expect(newData.map(resolveLazy)).toEqual(data.map(resolveLazy));
<ide> });
<ide> }
<ide> } | 2 |
Text | Text | improve note on zlib apis threadpool usage | 0234068f7f5d050b1c68bb02776f1da42e4ec0cf | <ide><path>doc/api/zlib.md
<ide> zlib.unzip(buffer, (err, buffer) => {
<ide> ## Threadpool Usage
<ide>
<ide> Note that all zlib APIs except those that are explicitly synchronous use libuv's
<del>threadpool, which can have surprising and negative performance implications for
<del>some applications, see the [`UV_THREADPOOL_SIZE`][] documentation for more
<del>information.
<add>threadpool. This can lead to surprising effects in some applications, such as
<add>subpar performance (which can be mitigated by adjusting the [pool size][])
<add>and/or unrecoverable and catastrophic memory fragmentation.
<ide>
<ide> ## Compressing HTTP requests and responses
<ide>
<ide> Decompress a chunk of data with [`Unzip`][].
<ide> [`Inflate`]: #zlib_class_zlib_inflate
<ide> [`InflateRaw`]: #zlib_class_zlib_inflateraw
<ide> [`TypedArray`]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/TypedArray
<del>[`UV_THREADPOOL_SIZE`]: cli.html#cli_uv_threadpool_size_size
<ide> [`Unzip`]: #zlib_class_zlib_unzip
<ide> [`options`]: #zlib_class_options
<ide> [`zlib.bytesWritten`]: #zlib_zlib_byteswritten
<ide> [Memory Usage Tuning]: #zlib_memory_usage_tuning
<add>[pool size]: cli.html#cli_uv_threadpool_size_size
<ide> [zlib documentation]: https://zlib.net/manual.html#Constants | 1 |
Ruby | Ruby | fix typo in [8287] | d7e978044548ee7b0e62282e6bb84629b5b8eddf | <ide><path>actionpack/lib/action_view/helpers/scriptaculous_helper.rb
<ide> def visual_effect(name, element_id = false, js_options = {})
<ide> # attributes in the form "string_identifier". For example, "item_1". Only
<ide> # the identifier part of the id attribute will be serialized.
<ide> #
<del> # Addtional +options+ are:
<add> # Additional +options+ are:
<ide> #
<ide> # <tt>:format</tt>:: A regular expression to determine what to send
<ide> # as the serialized id to the server (the default | 1 |
Javascript | Javascript | add period on line 9 | 84b5a13f204f901d4074b4737abda27e6b7c532f | <ide><path>src/index.js
<ide> import compose from './compose'
<ide>
<ide> /*
<ide> * This is a dummy function to check if the function name has been altered by minification.
<del>* If the function has been minified and NODE_ENV !== 'production', warn the user
<add>* If the function has been minified and NODE_ENV !== 'production', warn the user.
<ide> */
<ide> function isCrushed() {}
<ide> | 1 |
Go | Go | fix unmarshalling of command and entrypoint | 17d6f00ec2b8b9636f0bb64c55a5b3855e8f4bae | <ide><path>integration-cli/docker_api_containers_test.go
<ide> func (s *DockerSuite) TestPostContainerStop(c *check.C) {
<ide> c.Fatal(err)
<ide> }
<ide> }
<add>
<add>// #14170
<add>func (s *DockerSuite) TestPostContainersCreateWithStringOrSliceEntrypoint(c *check.C) {
<add> config := struct {
<add> Image string
<add> Entrypoint string
<add> Cmd []string
<add> }{"busybox", "echo", []string{"hello", "world"}}
<add> _, _, err := sockRequest("POST", "/containers/create?name=echotest", config)
<add> c.Assert(err, check.IsNil)
<add> out, _ := dockerCmd(c, "start", "-a", "echotest")
<add> c.Assert(strings.TrimSpace(out), check.Equals, "hello world")
<add>
<add> config2 := struct {
<add> Image string
<add> Entrypoint []string
<add> Cmd []string
<add> }{"busybox", []string{"echo"}, []string{"hello", "world"}}
<add> _, _, err = sockRequest("POST", "/containers/create?name=echotest2", config2)
<add> c.Assert(err, check.IsNil)
<add> out, _ = dockerCmd(c, "start", "-a", "echotest2")
<add> c.Assert(strings.TrimSpace(out), check.Equals, "hello world")
<add>}
<add>
<add>// #14170
<add>func (s *DockerSuite) TestPostContainersCreateWithStringOrSliceCmd(c *check.C) {
<add> config := struct {
<add> Image string
<add> Entrypoint string
<add> Cmd string
<add> }{"busybox", "echo", "hello world"}
<add> _, _, err := sockRequest("POST", "/containers/create?name=echotest", config)
<add> c.Assert(err, check.IsNil)
<add> out, _ := dockerCmd(c, "start", "-a", "echotest")
<add> c.Assert(strings.TrimSpace(out), check.Equals, "hello world")
<add>
<add> config2 := struct {
<add> Image string
<add> Cmd []string
<add> }{"busybox", []string{"echo", "hello", "world"}}
<add> _, _, err = sockRequest("POST", "/containers/create?name=echotest2", config2)
<add> c.Assert(err, check.IsNil)
<add> out, _ = dockerCmd(c, "start", "-a", "echotest2")
<add> c.Assert(strings.TrimSpace(out), check.Equals, "hello world")
<add>}
<ide><path>runconfig/config.go
<ide> func (e *Entrypoint) UnmarshalJSON(b []byte) error {
<ide>
<ide> p := make([]string, 0, 1)
<ide> if err := json.Unmarshal(b, &p); err != nil {
<del> p = append(p, string(b))
<add> var s string
<add> if err := json.Unmarshal(b, &s); err != nil {
<add> return err
<add> }
<add> p = append(p, s)
<ide> }
<ide> e.parts = p
<ide> return nil
<ide> func (e *Command) UnmarshalJSON(b []byte) error {
<ide>
<ide> p := make([]string, 0, 1)
<ide> if err := json.Unmarshal(b, &p); err != nil {
<del> p = append(p, string(b))
<add> var s string
<add> if err := json.Unmarshal(b, &s); err != nil {
<add> return err
<add> }
<add> p = append(p, s)
<ide> }
<ide> e.parts = p
<ide> return nil
<ide><path>runconfig/config_test.go
<ide> package runconfig
<ide>
<ide> import (
<ide> "bytes"
<add> "encoding/json"
<ide> "fmt"
<ide> "io/ioutil"
<ide> "strings"
<ide> func TestDecodeContainerConfig(t *testing.T) {
<ide> }
<ide> }
<ide> }
<add>
<add>func TestEntrypointUnmarshalString(t *testing.T) {
<add> var e *Entrypoint
<add> echo, err := json.Marshal("echo")
<add> if err != nil {
<add> t.Fatal(err)
<add> }
<add> if err := json.Unmarshal(echo, &e); err != nil {
<add> t.Fatal(err)
<add> }
<add>
<add> slice := e.Slice()
<add> if len(slice) != 1 {
<add> t.Fatalf("expected 1 element after unmarshal: %q", slice)
<add> }
<add>
<add> if slice[0] != "echo" {
<add> t.Fatalf("expected `echo`, got: %q", slice[0])
<add> }
<add>}
<add>
<add>func TestEntrypointUnmarshalSlice(t *testing.T) {
<add> var e *Entrypoint
<add> echo, err := json.Marshal([]string{"echo"})
<add> if err != nil {
<add> t.Fatal(err)
<add> }
<add> if err := json.Unmarshal(echo, &e); err != nil {
<add> t.Fatal(err)
<add> }
<add>
<add> slice := e.Slice()
<add> if len(slice) != 1 {
<add> t.Fatalf("expected 1 element after unmarshal: %q", slice)
<add> }
<add>
<add> if slice[0] != "echo" {
<add> t.Fatalf("expected `echo`, got: %q", slice[0])
<add> }
<add>}
<add>
<add>func TestCommandUnmarshalSlice(t *testing.T) {
<add> var e *Command
<add> echo, err := json.Marshal([]string{"echo"})
<add> if err != nil {
<add> t.Fatal(err)
<add> }
<add> if err := json.Unmarshal(echo, &e); err != nil {
<add> t.Fatal(err)
<add> }
<add>
<add> slice := e.Slice()
<add> if len(slice) != 1 {
<add> t.Fatalf("expected 1 element after unmarshal: %q", slice)
<add> }
<add>
<add> if slice[0] != "echo" {
<add> t.Fatalf("expected `echo`, got: %q", slice[0])
<add> }
<add>}
<add>
<add>func TestCommandUnmarshalString(t *testing.T) {
<add> var e *Command
<add> echo, err := json.Marshal("echo")
<add> if err != nil {
<add> t.Fatal(err)
<add> }
<add> if err := json.Unmarshal(echo, &e); err != nil {
<add> t.Fatal(err)
<add> }
<add>
<add> slice := e.Slice()
<add> if len(slice) != 1 {
<add> t.Fatalf("expected 1 element after unmarshal: %q", slice)
<add> }
<add>
<add> if slice[0] != "echo" {
<add> t.Fatalf("expected `echo`, got: %q", slice[0])
<add> }
<add>} | 3 |
Text | Text | update tutorial links | c0cf37e35dd51a1c5fb6e98d0bc3dcff0f60d412 | <ide><path>docs/community/tutorials-and-resources.md
<ide> Want your Django REST Framework talk/tutorial/article to be added to our website
<ide>
<ide>
<ide> [beginners-guide-to-the-django-rest-framework]: https://code.tutsplus.com/tutorials/beginners-guide-to-the-django-rest-framework--cms-19786
<del>[getting-started-with-django-rest-framework-and-angularjs]: https://blog.kevinastone.com/getting-started-with-django-rest-framework-and-angularjs.html
<add>[getting-started-with-django-rest-framework-and-angularjs]: https://blog.kevinastone.com/django-rest-framework-and-angular-js
<ide> [end-to-end-web-app-with-django-rest-framework-angularjs]: https://mourafiq.com/2013/07/01/end-to-end-web-app-with-django-angular-1.html
<del>[start-your-api-django-rest-framework-part-1]: https://godjango.com/41-start-your-api-django-rest-framework-part-1/
<del>[permissions-authentication-django-rest-framework-part-2]: https://godjango.com/43-permissions-authentication-django-rest-framework-part-2/
<del>[viewsets-and-routers-django-rest-framework-part-3]: https://godjango.com/45-viewsets-and-routers-django-rest-framework-part-3/
<add>[start-your-api-django-rest-framework-part-1]: https://www.youtube.com/watch?v=hqo2kk91WpE
<add>[permissions-authentication-django-rest-framework-part-2]: https://www.youtube.com/watch?v=R3xvUDUZxGU
<add>[viewsets-and-routers-django-rest-framework-part-3]: https://www.youtube.com/watch?v=2d6w4DGQ4OU
<ide> [django-rest-framework-user-endpoint]: https://richardtier.com/2014/02/25/django-rest-framework-user-endpoint/
<ide> [check-credentials-using-django-rest-framework]: https://richardtier.com/2014/03/06/110/
<ide> [ember-and-django-part 1-video]: http://www.neckbeardrepublic.com/screencasts/ember-and-django-part-1 | 1 |
Text | Text | fix some nits and typo | 68bf45084e3af9fa20d096b0d557bc1451aa5443 | <ide><path>README.md
<ide> of thousands of applications and databases.
<ide>
<ide> Security is very important to us. If you have any issue regarding security,
<ide> please disclose the information responsibly by sending an email to
<del>[email protected] and not by creating a github issue.
<add>[email protected] and not by creating a GitHub issue.
<ide>
<ide> ## Better than VMs
<ide>
<ide> Under the hood, Docker is built on the following components:
<ide> Contributing to Docker [](https://godoc.org/github.com/docker/docker)
<ide> ======================
<ide>
<del>| **Master** (Linux) | **Experimental** (linux) | **Windows** | **FreeBSD** |
<add>| **Master** (Linux) | **Experimental** (Linux) | **Windows** | **FreeBSD** |
<ide> |------------------|----------------------|---------|---------|
<ide> | [](https://jenkins.dockerproject.org/view/Docker/job/Docker%20Master/) | [](https://jenkins.dockerproject.org/view/Docker/job/Docker%20Master%20%28experimental%29/) | [/badge/icon)](http://jenkins.dockerproject.org/job/Docker%20Master%20(windows)/) | [/badge/icon)](http://jenkins.dockerproject.org/job/Docker%20Master%20(freebsd)/) |
<ide>
<ide> We are always open to suggestions on process improvements, and are always lookin
<ide> Google account by sending an email to <a
<ide> href="mailto:[email protected]">[email protected]</a>.
<ide> You'll receive a join-request message; simply reply to the message to
<del> confirm your subscribtion.
<add> confirm your subscription.
<ide> </td>
<ide> </tr>
<ide> <tr> | 1 |
Javascript | Javascript | store an applicationinstance on the application | 0941344b7cdc87046551b48be758d4aa1a6f7239 | <ide><path>packages/ember-application/lib/system/application.js
<ide> var Application = Namespace.extend(DeferredMixin, {
<ide> this.buildRegistry();
<ide>
<ide> // TODO:(tomdale+wycats) Move to session creation phase
<del> this.buildContainer();
<add> this.buildInstance();
<ide>
<ide> registerLibraries();
<ide> logLibraryVersions();
<ide> var Application = Namespace.extend(DeferredMixin, {
<ide> Create a container for the current application's registry.
<ide>
<ide> @private
<del> @method buildContainer
<add> @method buildInstance
<ide> @return {Ember.Container} the configured container
<ide> */
<del> buildContainer: function() {
<add> buildInstance: function() {
<ide> var container = this.__container__ = this.__registry__.container();
<ide>
<del> return container;
<add> var instance = this.__instance__ = ApplicationInstance.create({
<add> customEvents: get(this, 'customEvents'),
<add> rootElement: get(this, 'rootElement'),
<add> container: container
<add> });
<add>
<add> return instance;
<ide> },
<ide>
<ide> /**
<ide> var Application = Namespace.extend(DeferredMixin, {
<ide> @method reset
<ide> **/
<ide> reset: function() {
<add> var instance = this.__instance__;
<add>
<ide> this._readinessDeferrals = 1;
<ide>
<ide> function handleReset() {
<del> var router = this.__container__.lookup('router:main');
<del> router.reset();
<add> run(instance, 'destroy');
<ide>
<del> run(this.__container__, 'destroy');
<del>
<del> this.buildContainer();
<add> this.buildInstance();
<ide>
<ide> run.schedule('actions', this, '_initialize');
<ide> }
<ide> var Application = Namespace.extend(DeferredMixin, {
<ide> */
<ide> didBecomeReady: function() {
<ide> if (environment.hasDOM) {
<del> this.setupEventDispatcher();
<add> this.__instance__.setupEventDispatcher();
<ide> }
<ide>
<ide> this.ready(); // user hook
<ide> var Application = Namespace.extend(DeferredMixin, {
<ide> this.resolve(this);
<ide> },
<ide>
<del> /**
<del> Setup up the event dispatcher to receive events on the
<del> application's `rootElement` with any registered
<del> `customEvents`.
<del>
<del> @private
<del> @method setupEventDispatcher
<del> */
<del> setupEventDispatcher: function() {
<del> var customEvents = get(this, 'customEvents');
<del> var rootElement = get(this, 'rootElement');
<del> var dispatcher = this.__container__.lookup('event_dispatcher:main');
<del>
<del> set(this, 'eventDispatcher', dispatcher);
<del> dispatcher.setup(customEvents, rootElement);
<del> },
<del>
<ide> /**
<ide> If the application has a router, use it to route to the current URL, and
<ide> trigger a new call to `route` whenever the URL changes.
<ide> var Application = Namespace.extend(DeferredMixin, {
<ide> @property router {Ember.Router}
<ide> */
<ide> startRouting: function() {
<del> var router = this.__container__.lookup('router:main');
<del> if (!router) { return; }
<del>
<del> var moduleBasedResolver = this.Resolver && this.Resolver.moduleBasedResolver;
<del>
<del> router.startRouting(moduleBasedResolver);
<add> var isModuleBasedResolver = this.Resolver && this.Resolver.moduleBasedResolver;
<add> this.__instance__.startRouting(isModuleBasedResolver);
<ide> },
<ide>
<ide> handleURL: function(url) {
<del> var router = this.__container__.lookup('router:main');
<del>
<del> router.handleURL(url);
<add> return this.__instance__.handleURL(url);
<ide> },
<ide>
<ide> /**
<ide> var Application = Namespace.extend(DeferredMixin, {
<ide> */
<ide> Resolver: null,
<ide>
<add> // This method must be moved to the application instance object
<ide> willDestroy: function() {
<ide> Ember.BOOTED = false;
<del> // Ensure deactivation of routes before objects are destroyed
<del> this.__container__.lookup('router:main').reset();
<del>
<del> this.__container__.destroy();
<add> this.__instance__.destroy();
<ide> },
<ide>
<ide> initializer: function(options) {
<ide> function logLibraryVersions() {
<ide> }
<ide> }
<ide>
<add>var ApplicationInstance = Ember.Object.extend({
<add> container: null,
<add> customEvents: null,
<add> rootElement: null,
<add>
<add> startRouting: function(isModuleBasedResolver) {
<add> var router = this.container.lookup('router:main');
<add> if (!router) { return; }
<add>
<add> router.startRouting(isModuleBasedResolver);
<add> },
<add>
<add> handleURL: function(url) {
<add> var router = this.container.lookup('router:main');
<add>
<add> return router.handleURL(url);
<add> },
<add>
<add> setupEventDispatcher: function() {
<add> var dispatcher = this.container.lookup('event_dispatcher:main');
<add>
<add> dispatcher.setup(this.customEvents, this.rootElement);
<add>
<add> return dispatcher;
<add> },
<add>
<add> willDestroy: function() {
<add> run(this.container, 'destroy');
<add> }
<add>});
<add>
<ide> export default Application;
<ide><path>packages/ember-routing/lib/system/router.js
<ide> var EmberRouter = EmberObject.extend(Evented, {
<ide> }
<ide> },
<ide>
<add> willDestroy: function() {
<add> this.reset();
<add> },
<add>
<ide> _lookupActiveView: function(templateName) {
<ide> var active = this._activeViews[templateName];
<ide> return active && active[0]; | 2 |
PHP | PHP | use config_merge instead of array_merge | 0524af4e9d18f7a8d4b1f7e9b5958580d306f024 | <ide><path>src/Illuminate/Support/ServiceProvider.php
<ide> protected function loadConfigFrom($key, $path)
<ide> {
<ide> $defaults = $this->app['files']->getRequire($path);
<ide> $config = $this->app['config']->get($key, []);
<del> $this->app['config']->set($key, array_merge($defaults, $config));
<add> $this->app['config']->set($key, config_merge($defaults, $config));
<ide> }
<ide>
<ide> /** | 1 |
Python | Python | fix typos in trapz() | 6f1da5f8f5db99e7ca8397d925c8d2a013a305e0 | <ide><path>numpy/lib/function_base.py
<ide> def trapz(y, x=None, dx=1.0, axis=-1):
<ide> x : array_like, optional
<ide> If `x` is None, then spacing between all `y` elements is `dx`.
<ide> dx : scalar, optional
<del> If `x` is None, spacing given by `dx` is assumed. Default is 1.
<add> If `dx` is None, spacing given by `x` is assumed. Default is 1.
<ide> axis : int, optional
<ide> Specify the axis.
<ide> | 1 |
Go | Go | make o/p of ipam dumpdatabase() consistent | 04f5343139e2cc7b322aacab3e58a4387dbe080b | <ide><path>libnetwork/ipam/allocator.go
<ide> package ipam
<ide> import (
<ide> "fmt"
<ide> "net"
<add> "sort"
<ide> "sync"
<ide>
<ide> log "github.com/Sirupsen/logrus"
<ide> func (a *Allocator) getAddress(nw *net.IPNet, bitmask *bitseq.Handle, prefAddres
<ide> func (a *Allocator) DumpDatabase() string {
<ide> a.Lock()
<ide> aspaces := make(map[string]*addrSpace, len(a.addrSpaces))
<add> orderedAS := make([]string, 0, len(a.addrSpaces))
<ide> for as, aSpace := range a.addrSpaces {
<add> orderedAS = append(orderedAS, as)
<ide> aspaces[as] = aSpace
<ide> }
<ide> a.Unlock()
<ide>
<add> sort.Strings(orderedAS)
<add>
<ide> var s string
<del> for as, aSpace := range aspaces {
<add> for _, as := range orderedAS {
<add> aSpace := aspaces[as]
<ide> s = fmt.Sprintf("\n\n%s Config", as)
<ide> aSpace.Lock()
<ide> for k, config := range aSpace.subnets { | 1 |
Python | Python | reset warnings.showwarning on interpreter shutdown | 9583c1cab65d28146e73aab0993304886c724bf3 | <ide><path>airflow/settings.py
<ide> def custom_show_warning(message, category, filename, lineno, file=None, line=Non
<ide> write_console.print(msg, soft_wrap=True)
<ide>
<ide>
<del>warnings.showwarning = custom_show_warning
<add>def replace_showwarning(replacement):
<add> """Replace ``warnings.showwarning``, returning the original.
<add>
<add> This is useful since we want to "reset" the ``showwarning`` hook on exit to
<add> avoid lazy-loading issues. If a warning is emitted after Python cleaned up
<add> the import system, we would no longer be able to import ``rich``.
<add> """
<add> original = warnings.showwarning
<add> warnings.showwarning = replacement
<add> return original
<add>
<add>
<add>original_show_warning = replace_showwarning(custom_show_warning)
<add>atexit.register(functools.partial(replace_showwarning, original_show_warning))
<ide>
<ide>
<ide> def task_policy(task) -> None: | 1 |
Java | Java | add synchronous test of resubscribe after error | 69a1dbd753d1f060df38e47e6179cf05b6b62d63 | <ide><path>rxjava-core/src/test/java/rx/operators/OperatorRetryTest.java
<ide> import static org.junit.Assert.assertEquals;
<ide> import static org.junit.Assert.fail;
<ide> import static org.mockito.Matchers.any;
<add>import static org.mockito.Mockito.doThrow;
<ide> import static org.mockito.Mockito.inOrder;
<ide> import static org.mockito.Mockito.mock;
<ide> import static org.mockito.Mockito.never;
<ide>
<ide> import org.junit.Test;
<ide> import org.mockito.InOrder;
<add>import org.mockito.Mockito;
<ide>
<ide> import rx.Observable;
<ide> import rx.Observable.OnSubscribe;
<ide> public void testInfiniteRetry() {
<ide> inOrder.verify(observer, times(1)).onCompleted();
<ide> inOrder.verifyNoMoreInteractions();
<ide> }
<add>
<add> /**
<add> * Checks in a simple and synchronous way that retry resubscribes
<add> * after error. This test fails against 0.16.1-0.17.4, hangs on 0.17.5 and
<add> * passes in 0.17.6 thanks to fix for issue #1027.
<add> */
<add> @SuppressWarnings("unchecked")
<add> @Test
<add> public void testRetrySubscribesAgainAfterError() {
<add>
<add> // record emitted values with this action
<add> Action1<Integer> record = mock(Action1.class);
<add> InOrder inOrder = inOrder(record);
<add>
<add> // always throw an exception with this action
<add> Action1<Integer> throwException = mock(Action1.class);
<add> doThrow(new RuntimeException()).when(throwException).call(Mockito.anyInt());
<add>
<add> // create a retrying observable based on a PublishSubject
<add> PublishSubject<Integer> subject = PublishSubject.create();
<add> subject
<add> // record item
<add> .doOnNext(record)
<add> // throw a RuntimeException
<add> .doOnNext(throwException)
<add> // retry on error
<add> .retry()
<add> // subscribe and ignore
<add> .subscribe();
<add>
<add> inOrder.verifyNoMoreInteractions();
<add>
<add> subject.onNext(1);
<add> inOrder.verify(record).call(1);
<add>
<add> subject.onNext(2);
<add> inOrder.verify(record).call(2);
<add>
<add> subject.onNext(3);
<add> inOrder.verify(record).call(3);
<add>
<add> inOrder.verifyNoMoreInteractions();
<add> }
<add>
<ide>
<ide> public static class FuncWithErrors implements Observable.OnSubscribe<String> {
<ide>
<ide> public void testTimeoutWithRetry() {
<ide>
<ide> assertEquals("Start 6 threads, retry 5 then fail on 6", 6, so.efforts.get());
<ide> }
<add>
<ide> } | 1 |
Javascript | Javascript | pass invertstickyheaders to scrollview | dd479a93772c3a52561fc32ee84b25ce822a30fa | <ide><path>Libraries/Lists/VirtualizedList.js
<ide> class VirtualizedList extends React.PureComponent<Props, State> {
<ide> onScrollEndDrag: this._onScrollEndDrag,
<ide> onMomentumScrollEnd: this._onMomentumScrollEnd,
<ide> scrollEventThrottle: this.props.scrollEventThrottle, // TODO: Android support
<del> invertStickyHeaders: this.props.inverted,
<add> invertStickyHeaders: this.props.invertStickyHeaders !== undefined
<add> ? this.props.invertStickyHeaders
<add> : this.props.inverted,
<ide> stickyHeaderIndices,
<ide> };
<ide> if (inversionStyle) { | 1 |
Javascript | Javascript | move scheduler priority check into reactdom | 3d10eca241be7b51cd4d74cf69eb1f429818b71a | <ide><path>packages/react-dom/src/events/DOMEventNames.js
<ide> export type DOMEventName =
<ide> | 'loadeddata'
<ide> | 'loadedmetadata'
<ide> | 'lostpointercapture'
<add> | 'message'
<ide> | 'mousedown'
<ide> | 'mouseenter'
<ide> | 'mouseleave'
<ide><path>packages/react-dom/src/events/ReactDOMEventListener.js
<ide> import {
<ide> DefaultLanePriority as DefaultLanePriority_old,
<ide> getCurrentUpdateLanePriority as getCurrentUpdateLanePriority_old,
<ide> setCurrentUpdateLanePriority as setCurrentUpdateLanePriority_old,
<add> schedulerPriorityToLanePriority as schedulerPriorityToLanePriority_old,
<ide> } from 'react-reconciler/src/ReactFiberLane.old';
<ide> import {
<ide> InputDiscreteLanePriority as InputDiscreteLanePriority_new,
<ide> InputContinuousLanePriority as InputContinuousLanePriority_new,
<ide> DefaultLanePriority as DefaultLanePriority_new,
<ide> getCurrentUpdateLanePriority as getCurrentUpdateLanePriority_new,
<ide> setCurrentUpdateLanePriority as setCurrentUpdateLanePriority_new,
<add> schedulerPriorityToLanePriority as schedulerPriorityToLanePriority_new,
<ide> } from 'react-reconciler/src/ReactFiberLane.new';
<add>import {getCurrentPriorityLevel as getCurrentPriorityLevel_old} from 'react-reconciler/src/SchedulerWithReactIntegration.old';
<add>import {getCurrentPriorityLevel as getCurrentPriorityLevel_new} from 'react-reconciler/src/SchedulerWithReactIntegration.new';
<ide>
<ide> const InputDiscreteLanePriority = enableNewReconciler
<ide> ? InputDiscreteLanePriority_new
<ide> const getCurrentUpdateLanePriority = enableNewReconciler
<ide> const setCurrentUpdateLanePriority = enableNewReconciler
<ide> ? setCurrentUpdateLanePriority_new
<ide> : setCurrentUpdateLanePriority_old;
<add>const schedulerPriorityToLanePriority = enableNewReconciler
<add> ? schedulerPriorityToLanePriority_new
<add> : schedulerPriorityToLanePriority_old;
<add>const getCurrentPriorityLevel = enableNewReconciler
<add> ? getCurrentPriorityLevel_new
<add> : getCurrentPriorityLevel_old;
<ide>
<ide> const {
<ide> unstable_UserBlockingPriority: UserBlockingPriority,
<ide> export function getEventPriority(domEventName: DOMEventName): * {
<ide> case 'mouseenter':
<ide> case 'mouseleave':
<ide> return InputContinuousLanePriority;
<add> case 'message': {
<add> // We might be in the Scheduler callback.
<add> // Eventually this mechanism will be replaced by a check
<add> // of the current priority on the native scheduler.
<add> const schedulerPriority = getCurrentPriorityLevel();
<add> // TODO: Inline schedulerPriorityToLanePriority into this file
<add> // when we delete the enableNativeEventPriorityInference flag.
<add> return schedulerPriorityToLanePriority(schedulerPriority);
<add> }
<ide> default:
<ide> return DefaultLanePriority;
<ide> }
<ide><path>packages/react-reconciler/src/ReactFiberWorkLoop.old.js
<ide> export function requestUpdateLane(fiber: Fiber): Lane {
<ide> } else {
<ide> if (enableNativeEventPriorityInference) {
<ide> const eventLanePriority = getCurrentEventPriority();
<del> if (eventLanePriority === DefaultLanePriority) {
<del> // TODO: move this case into the ReactDOM host config.
<del> const schedulerLanePriority = schedulerPriorityToLanePriority(
<del> schedulerPriority,
<del> );
<del> lane = findUpdateLane(schedulerLanePriority, currentEventWipLanes);
<del> } else {
<del> lane = findUpdateLane(eventLanePriority, currentEventWipLanes);
<del> }
<add> lane = findUpdateLane(eventLanePriority, currentEventWipLanes);
<ide> } else {
<ide> const schedulerLanePriority = schedulerPriorityToLanePriority(
<ide> schedulerPriority, | 3 |
Python | Python | solve issue on process display | 22eaa0ea19b369587a629d5e400434d8d37026ea | <ide><path>glances/glances.py
<ide> import signal
<ide> import time
<ide> from datetime import datetime, timedelta
<add>import locale
<ide> import gettext
<add>locale.setlocale(locale.LC_ALL, '')
<ide> gettext.install(__appname__)
<ide>
<ide> # Specifics libs | 1 |
Ruby | Ruby | use interleaved output for `errorduringexecution` | 2712fcaa6728a5bfbf9a2113bdfd93b52370615b | <ide><path>Library/Homebrew/cask/lib/hbc/system_command.rb
<ide> def self.run!(command, **options)
<ide> end
<ide>
<ide> def run!
<add> @merged_output = []
<ide> @processed_output = { stdout: "", stderr: "" }
<ide> odebug command.shelljoin
<ide>
<ide> def run!
<ide> when :stdout
<ide> puts line.chomp if print_stdout?
<ide> processed_output[:stdout] << line
<add> @merged_output << [:stdout, line]
<ide> when :stderr
<ide> $stderr.puts Formatter.error(line.chomp) if print_stderr?
<ide> processed_output[:stderr] << line
<add> @merged_output << [:stderr, line]
<ide> end
<ide> end
<ide>
<ide> def sudo_prefix
<ide> def assert_success
<ide> return if processed_status&.success?
<ide> raise ErrorDuringExecution.new(command,
<del> stdout: processed_output[:stdout],
<del> stderr: processed_output[:stderr],
<del> status: processed_status)
<add> status: processed_status,
<add> output: @merged_output)
<ide> end
<ide>
<ide> def expanded_args
<ide><path>Library/Homebrew/exceptions.rb
<ide> def initialize(cause)
<ide>
<ide> # raised by safe_system in utils.rb
<ide> class ErrorDuringExecution < RuntimeError
<del> def initialize(cmd, status:, stdout: nil, stderr: nil)
<add> def initialize(cmd, status:, output: nil)
<ide> s = "Failure while executing; `#{cmd.shelljoin.gsub(/\\=/, "=")}` exited with #{status.exitstatus}."
<ide>
<del> if stdout
<del> s << "==> Standard Output of failed command:\n"
<del> s << stdout
<del> s << "\n" unless stdout.end_with?("\n")
<del> end
<add> unless [*output].empty?
<add> format_output_line = lambda do |type, line|
<add> if type == :stderr
<add> Formatter.error(line)
<add> else
<add> line
<add> end
<add> end
<ide>
<del> if stderr
<del> s << "==> Standard Error of failed command:\n"
<del> s << stderr
<del> s << "\n" unless stderr.end_with?("\n")
<add> s << " Here's the output:\n"
<add> s << output.map(&format_output_line).join
<add> s << "\n" unless s.end_with?("\n")
<ide> end
<ide>
<ide> super s
<ide><path>Library/Homebrew/extend/os/linux/keg_relocate.rb
<ide> def change_rpath(file, old_prefix, new_prefix)
<ide> # Skip ELF files that do not have a .dynstr section.
<ide> return if ["cannot find section .dynstr", "strange: no string table"].include?(old_rpath)
<ide> unless $CHILD_STATUS.success?
<del> raise ErrorDuringExecution.new(cmd_rpath, stdout: old_rpath, status: $CHILD_STATUS)
<add> raise ErrorDuringExecution.new(cmd_rpath, status: $CHILD_STATUS, output: [:stdout, old_rpath])
<ide> end
<ide>
<ide> rpath = old_rpath | 3 |
Go | Go | delete a function which isn't used in the project | 81849600fc1d7335f1ddc3ca5aa1cb5625bd2d30 | <ide><path>api/server/httputils/httputils.go
<ide> func ParseForm(r *http.Request) error {
<ide> return nil
<ide> }
<ide>
<del>// ParseMultipartForm ensures the request form is parsed, even with invalid content types.
<del>func ParseMultipartForm(r *http.Request) error {
<del> if err := r.ParseMultipartForm(4096); err != nil && !strings.HasPrefix(err.Error(), "mime:") {
<del> return err
<del> }
<del> return nil
<del>}
<del>
<ide> // WriteJSON writes the value v to the http response stream as json with standard json encoding.
<ide> func WriteJSON(w http.ResponseWriter, code int, v interface{}) error {
<ide> w.Header().Set("Content-Type", "application/json") | 1 |
Javascript | Javascript | show stacktrace in yellowbox | 8d038572f3c42033cfcc7a7901eea0ff75bbc32a | <ide><path>Libraries/ReactIOS/YellowBox.js
<ide> 'use strict';
<ide>
<ide> const EventEmitter = require('EventEmitter');
<del>import type EmitterSubscription from 'EmitterSubscription';
<ide> const Platform = require('Platform');
<ide> const React = require('React');
<ide> const StyleSheet = require('StyleSheet');
<add>const symbolicateStackTrace = require('symbolicateStackTrace');
<add>const parseErrorStack = require('parseErrorStack');
<add>
<add>import type EmitterSubscription from 'EmitterSubscription';
<add>import type {StackFrame} from 'parseErrorStack';
<add>
<add>type WarningInfo = {
<add> count: number;
<add> stacktrace: Array<StackFrame>;
<add>};
<ide>
<ide> const _warningEmitter = new EventEmitter();
<del>const _warningMap = new Map();
<add>const _warningMap: Map<string, WarningInfo> = new Map();
<ide>
<ide> /**
<ide> * YellowBox renders warnings at the bottom of the app being developed.
<ide> function updateWarningMap(format, ...args): void {
<ide> ...args.slice(argCount).map(stringifySafe),
<ide> ].join(' ');
<ide>
<del> const count = _warningMap.has(warning) ? _warningMap.get(warning) : 0;
<del> _warningMap.set(warning, count + 1);
<add> var warningInfo = _warningMap.get(warning);
<add> if (warningInfo) {
<add> warningInfo.count += 1;
<add> } else {
<add> warningInfo = {count: 1, stacktrace: []};
<add> }
<add>
<add> _warningMap.set(warning, warningInfo);
<ide> _warningEmitter.emit('warning', _warningMap);
<add>
<add> var error : any = new Error();
<add> error.framesToPop = 2;
<add>
<add> symbolicateStackTrace(parseErrorStack(error)).then(stack => {
<add> warningInfo = _warningMap.get(warning);
<add> if (warningInfo) {
<add> warningInfo.stacktrace = stack;
<add>
<add> _warningMap.set(warning, warningInfo);
<add> _warningEmitter.emit('warning', _warningMap);
<add> }
<add> }, () => { /* Do nothing when can't load source map */ });
<ide> }
<ide>
<ide> function isWarningIgnored(warning: string): boolean {
<ide> const WarningRow = ({count, warning, onPress}) => {
<ide> );
<ide> };
<ide>
<add>type StackRowProps = { frame: StackFrame };
<add>const StackRow = ({frame}: StackRowProps) => {
<add> const Text = require('Text');
<add> const fileParts = frame.file.split('/');
<add> const fileName = fileParts[fileParts.length - 1];
<add> return (
<add> <Text style={styles.inspectorCountText}>
<add> {`${fileName}:${frame.lineNumber}`}
<add> </Text>
<add> );
<add>};
<add>
<ide> const WarningInspector = ({
<del> count,
<add> warningInfo,
<ide> warning,
<add> stacktraceVisible,
<ide> onClose,
<ide> onDismiss,
<ide> onDismissAll,
<add> toggleStacktrace,
<ide> }) => {
<ide> const ScrollView = require('ScrollView');
<ide> const Text = require('Text');
<ide> const TouchableHighlight = require('TouchableHighlight');
<ide> const View = require('View');
<add> const {count, stacktrace} = warningInfo || {};
<ide>
<ide> const countSentence =
<del> /* $FlowFixMe(>=0.26.0) - count can be undefined! Look at WarningInspector
<del> * usage! */
<ide> 'Warning encountered ' + count + ' time' + (count - 1 ? 's' : '') + '.';
<ide>
<add> let stacktraceList;
<add> if (stacktraceVisible && stacktrace) {
<add> stacktraceList = (
<add> <View>
<add> {stacktrace.map((frame, ii) => <StackRow frame={frame} key={ii} />)}
<add> </View>
<add> );
<add> }
<add>
<ide> return (
<ide> <TouchableHighlight
<ide> activeOpacity={0.95}
<ide> const WarningInspector = ({
<ide> <View style={styles.inspectorContent}>
<ide> <View style={styles.inspectorCount}>
<ide> <Text style={styles.inspectorCountText}>{countSentence}</Text>
<add> <TouchableHighlight
<add> activeOpacity={0.5}
<add> onPress={toggleStacktrace}
<add> style={styles.stacktraceButton}
<add> underlayColor="transparent">
<add> <Text style={styles.inspectorButtonText}>
<add> {stacktraceVisible ? 'Hide' : 'Show'} stacktrace
<add> </Text>
<add> </TouchableHighlight>
<ide> </View>
<ide> <ScrollView style={styles.inspectorWarning}>
<add> {stacktraceList}
<ide> <Text style={styles.inspectorWarningText}>{warning}</Text>
<ide> </ScrollView>
<ide> <View style={styles.inspectorButtons}>
<ide> const WarningInspector = ({
<ide>
<ide> class YellowBox extends React.Component {
<ide> state: {
<add> stacktraceVisible: boolean;
<ide> inspecting: ?string;
<ide> warningMap: Map<any, any>;
<ide> };
<ide> class YellowBox extends React.Component {
<ide> super(props, context);
<ide> this.state = {
<ide> inspecting: null,
<add> stacktraceVisible: false,
<ide> warningMap: _warningMap,
<ide> };
<ide> this.dismissWarning = warning => {
<ide> class YellowBox extends React.Component {
<ide> const ScrollView = require('ScrollView');
<ide> const View = require('View');
<ide>
<del> const inspecting = this.state.inspecting;
<add> const {inspecting, stacktraceVisible} = this.state;
<ide> const inspector = inspecting !== null ?
<ide> <WarningInspector
<del> count={this.state.warningMap.get(inspecting)}
<add> warningInfo={this.state.warningMap.get(inspecting)}
<ide> warning={inspecting}
<add> stacktraceVisible={stacktraceVisible}
<ide> onClose={() => this.setState({inspecting: null})}
<ide> onDismiss={() => this.dismissWarning(inspecting)}
<ide> onDismissAll={() => this.dismissWarning(null)}
<add> toggleStacktrace={() => this.setState({stacktraceVisible: !stacktraceVisible})}
<ide> /> :
<ide> null;
<ide>
<ide> const rows = [];
<del> this.state.warningMap.forEach((count, warning) => {
<add> this.state.warningMap.forEach((warningInfo, warning) => {
<ide> if (!isWarningIgnored(warning)) {
<ide> rows.push(
<ide> <WarningRow
<ide> key={warning}
<del> count={count}
<add> count={warningInfo.count}
<ide> warning={warning}
<ide> onPress={() => this.setState({inspecting: warning})}
<ide> onDismiss={() => this.dismissWarning(warning)}
<ide> var styles = StyleSheet.create({
<ide> inspectorButton: {
<ide> flex: 1,
<ide> padding: 22,
<add> backgroundColor: backgroundColor(1),
<add> },
<add> stacktraceButton: {
<add> flex: 1,
<add> padding: 5,
<ide> },
<ide> inspectorButtonText: {
<ide> color: textColor,
<ide> var styles = StyleSheet.create({
<ide> fontSize: 14,
<ide> },
<ide> inspectorWarning: {
<del> padding: 15,
<del> position: 'absolute',
<del> top: 39,
<del> bottom: 60,
<add> paddingHorizontal: 15,
<ide> },
<ide> inspectorWarningText: {
<ide> color: textColor, | 1 |
Text | Text | remove undef ndebug from addons.md | 06ed0e81879c97d6f9cbbbc0bf2b3db06ba232cf | <ide><path>doc/api/addons.md
<ide> The following `addon.cc` implements AtExit:
<ide>
<ide> ```cpp
<ide> // addon.cc
<del>#undef NDEBUG
<ide> #include <assert.h>
<ide> #include <stdlib.h>
<ide> #include <node.h> | 1 |
Ruby | Ruby | remove unused `column#coder` | 748f070895dc0d76a02a45e1be5c50ea67a79e85 | <ide><path>activerecord/lib/active_record/connection_adapters/column.rb
<ide> module Format
<ide> end
<ide>
<ide> attr_reader :name, :default, :cast_type, :null, :sql_type, :default_function
<del> attr_accessor :coder
<del>
<del> alias :encoded? :coder
<ide>
<ide> delegate :type, :precision, :scale, :limit, :klass, :text?, :number?, :binary?,
<del> :type_cast_for_write, :type_cast_for_database, to: :cast_type
<add> :type_cast, :type_cast_for_write, :type_cast_for_database, to: :cast_type
<ide>
<ide> # Instantiates a new column in the table.
<ide> #
<ide> def initialize(name, default, cast_type, sql_type = nil, null = true)
<ide> @null = null
<ide> @default = extract_default(default)
<ide> @default_function = nil
<del> @coder = nil
<ide> end
<ide>
<ide> def has_default?
<ide> !default.nil?
<ide> end
<ide>
<del> # Casts value to an appropriate instance.
<del> def type_cast(value)
<del> if encoded?
<del> coder.load(value)
<del> else
<del> cast_type.type_cast(value)
<del> end
<del> end
<del>
<ide> # Returns the human name of the column name.
<ide> #
<ide> # ===== Examples
<ide><path>activerecord/test/cases/column_definition_test.rb
<ide> def @adapter.native_database_types
<ide> @viz = @adapter.schema_creation
<ide> end
<ide>
<del> def test_can_set_coder
<del> column = Column.new("title", nil, Type::String.new, "varchar(20)")
<del> column.coder = YAML
<del> assert_equal YAML, column.coder
<del> end
<del>
<del> def test_encoded?
<del> column = Column.new("title", nil, Type::String.new, "varchar(20)")
<del> assert !column.encoded?
<del>
<del> column.coder = YAML
<del> assert column.encoded?
<del> end
<del>
<del> def test_type_case_coded_column
<del> column = Column.new("title", nil, Type::String.new, "varchar(20)")
<del> column.coder = YAML
<del> assert_equal "hello", column.type_cast("--- hello")
<del> end
<del>
<ide> # Avoid column definitions in create table statements like:
<ide> # `title` varchar(255) DEFAULT NULL
<ide> def test_should_not_include_default_clause_when_default_is_null | 2 |
Go | Go | add tests for api container delete | 8771cafab65e50d09d3590a7f22758e919b78fe4 | <ide><path>integration-cli/docker_api_containers_test.go
<ide> import (
<ide> "encoding/json"
<ide> "io"
<ide> "net/http"
<add> "os"
<ide> "os/exec"
<ide> "strings"
<ide> "time"
<ide> func (s *DockerSuite) TestContainerApiCopyContainerNotFound(c *check.C) {
<ide> c.Assert(err, check.IsNil)
<ide> c.Assert(status, check.Equals, http.StatusNotFound)
<ide> }
<add>
<add>func (s *DockerSuite) TestContainerApiDelete(c *check.C) {
<add> runCmd := exec.Command(dockerBinary, "run", "-d", "busybox", "top")
<add> out, _, err := runCommandWithOutput(runCmd)
<add> c.Assert(err, check.IsNil)
<add>
<add> id := strings.TrimSpace(out)
<add> c.Assert(waitRun(id), check.IsNil)
<add>
<add> stopCmd := exec.Command(dockerBinary, "stop", id)
<add> _, err = runCommand(stopCmd)
<add> c.Assert(err, check.IsNil)
<add>
<add> status, _, err := sockRequest("DELETE", "/containers/"+id, nil)
<add> c.Assert(err, check.IsNil)
<add> c.Assert(status, check.Equals, http.StatusNoContent)
<add>}
<add>
<add>func (s *DockerSuite) TestContainerApiDeleteNotExist(c *check.C) {
<add> status, body, err := sockRequest("DELETE", "/containers/doesnotexist", nil)
<add> c.Assert(err, check.IsNil)
<add> c.Assert(status, check.Equals, http.StatusNotFound)
<add> c.Assert(string(body), check.Matches, "no such id: doesnotexist\n")
<add>}
<add>
<add>func (s *DockerSuite) TestContainerApiDeleteForce(c *check.C) {
<add> runCmd := exec.Command(dockerBinary, "run", "-d", "busybox", "top")
<add> out, _, err := runCommandWithOutput(runCmd)
<add> c.Assert(err, check.IsNil)
<add>
<add> id := strings.TrimSpace(out)
<add> c.Assert(waitRun(id), check.IsNil)
<add>
<add> status, _, err := sockRequest("DELETE", "/containers/"+id+"?force=1", nil)
<add> c.Assert(err, check.IsNil)
<add> c.Assert(status, check.Equals, http.StatusNoContent)
<add>}
<add>
<add>func (s *DockerSuite) TestContainerApiDeleteRemoveLinks(c *check.C) {
<add> runCmd := exec.Command(dockerBinary, "run", "-d", "--name", "tlink1", "busybox", "top")
<add> out, _, err := runCommandWithOutput(runCmd)
<add> c.Assert(err, check.IsNil)
<add>
<add> id := strings.TrimSpace(out)
<add> c.Assert(waitRun(id), check.IsNil)
<add>
<add> runCmd = exec.Command(dockerBinary, "run", "--link", "tlink1:tlink1", "--name", "tlink2", "-d", "busybox", "top")
<add> out, _, err = runCommandWithOutput(runCmd)
<add> c.Assert(err, check.IsNil)
<add>
<add> id2 := strings.TrimSpace(out)
<add> c.Assert(waitRun(id2), check.IsNil)
<add>
<add> links, err := inspectFieldJSON(id2, "HostConfig.Links")
<add> c.Assert(err, check.IsNil)
<add>
<add> if links != "[\"/tlink1:/tlink2/tlink1\"]" {
<add> c.Fatal("expected to have links between containers")
<add> }
<add>
<add> status, _, err := sockRequest("DELETE", "/containers/tlink2/tlink1?link=1", nil)
<add> c.Assert(err, check.IsNil)
<add> c.Assert(status, check.Equals, http.StatusNoContent)
<add>
<add> linksPostRm, err := inspectFieldJSON(id2, "HostConfig.Links")
<add> c.Assert(err, check.IsNil)
<add>
<add> if linksPostRm != "null" {
<add> c.Fatal("call to api deleteContainer links should have removed the specified links")
<add> }
<add>}
<add>
<add>func (s *DockerSuite) TestContainerApiDeleteConflict(c *check.C) {
<add> runCmd := exec.Command(dockerBinary, "run", "-d", "busybox", "top")
<add> out, _, err := runCommandWithOutput(runCmd)
<add> c.Assert(err, check.IsNil)
<add>
<add> id := strings.TrimSpace(out)
<add> c.Assert(waitRun(id), check.IsNil)
<add>
<add> status, _, err := sockRequest("DELETE", "/containers/"+id, nil)
<add> c.Assert(status, check.Equals, http.StatusConflict)
<add> c.Assert(err, check.IsNil)
<add>}
<add>
<add>func (s *DockerSuite) TestContainerApiDeleteRemoveVolume(c *check.C) {
<add> testRequires(c, SameHostDaemon)
<add>
<add> runCmd := exec.Command(dockerBinary, "run", "-d", "-v", "/testvolume", "busybox", "top")
<add> out, _, err := runCommandWithOutput(runCmd)
<add> c.Assert(err, check.IsNil)
<add>
<add> id := strings.TrimSpace(out)
<add> c.Assert(waitRun(id), check.IsNil)
<add>
<add> vol, err := inspectFieldMap(id, "Volumes", "/testvolume")
<add> c.Assert(err, check.IsNil)
<add>
<add> _, err = os.Stat(vol)
<add> c.Assert(err, check.IsNil)
<add>
<add> status, _, err := sockRequest("DELETE", "/containers/"+id+"?v=1&force=1", nil)
<add> c.Assert(status, check.Equals, http.StatusNoContent)
<add> c.Assert(err, check.IsNil)
<add>
<add> if _, err := os.Stat(vol); !os.IsNotExist(err) {
<add> c.Fatalf("expected to get ErrNotExist error, got %v", err)
<add> }
<add>}
<ide><path>integration-cli/docker_cli_rm_test.go
<ide> package main
<ide>
<ide> import (
<del> "net/http"
<ide> "os"
<ide> "os/exec"
<ide> "strings"
<ide> func (s *DockerSuite) TestRmRunningContainer(c *check.C) {
<ide>
<ide> }
<ide>
<del>func (s *DockerSuite) TestRmRunningContainerCheckError409(c *check.C) {
<del>
<del> createRunningContainer(c, "foo")
<del>
<del> endpoint := "/containers/foo"
<del> status, _, err := sockRequest("DELETE", endpoint, nil)
<del> c.Assert(status, check.Equals, http.StatusConflict)
<del> c.Assert(err, check.IsNil)
<del>}
<del>
<ide> func (s *DockerSuite) TestRmForceRemoveRunningContainer(c *check.C) {
<ide>
<ide> createRunningContainer(c, "foo") | 2 |
Ruby | Ruby | remove unused default argument | f80748096df45534e6f38cdfb2ee83e1051cb56b | <ide><path>Library/Homebrew/formula_versions.rb
<ide> def initialize(formula)
<ide> @entry_name = formula.path.relative_path_from(repository).to_s
<ide> end
<ide>
<del> def rev_list(branch="HEAD")
<add> def rev_list(branch)
<ide> repository.cd do
<ide> Utils.popen_read("git", "rev-list", "--abbrev-commit", "--remove-empty", branch, "--", entry_name) do |io|
<ide> yield io.readline.chomp until io.eof? | 1 |
PHP | PHP | correct doc blocks | 587617bf12a8b8c235ee9ee81276282045f8c813 | <ide><path>src/Network/Http/CookieCollection.php
<ide> class CookieCollection {
<ide> * Store the cookies that haven't expired. If a cookie has been expired
<ide> * and is currently stored, it will be removed.
<ide> *
<del> * @param Response $response The response to read cookies from
<add> * @param \Cake\Network\Response $response The response to read cookies from
<ide> * @param string $url The request URL used for default host/path values.
<ide> * @return void
<ide> */
<ide><path>src/Routing/Router.php
<ide> public static function extensions() {
<ide> *
<ide> * - `separator` The string to use as a separator. Defaults to `:`.
<ide> *
<del> * @param Request $request The request object to modify.
<add> * @param \Cake\Network\Request $request The request object to modify.
<ide> * @param array $options The array of options.
<ide> * @return \Cake\Network\Request The modified request
<ide> */ | 2 |
Go | Go | fix race condition in test case | 010077ba0fb53ef4b88cc5c8f03cd770481e7dd5 | <ide><path>libnetwork/drivers/bridge/bridge_test.go
<ide> func TestCreateParallel(t *testing.T) {
<ide> t.Fatalf("Failed to setup driver config: %v", err)
<ide> }
<ide>
<add> ipV4Data := getIPv4Data(t, "docker0")
<add>
<ide> ch := make(chan error, 100)
<ide> for i := 0; i < 100; i++ {
<ide> name := "net" + strconv.Itoa(i)
<ide> c.Go(t, func() {
<ide> config := &networkConfiguration{BridgeName: name}
<ide> genericOption := make(map[string]interface{})
<ide> genericOption[netlabel.GenericData] = config
<del> if err := d.CreateNetwork(name, genericOption, nil, getIPv4Data(t, "docker0"), nil); err != nil {
<add> if err := d.CreateNetwork(name, genericOption, nil, ipV4Data, nil); err != nil {
<ide> ch <- fmt.Errorf("failed to create %s", name)
<ide> return
<ide> }
<del> if err := d.CreateNetwork(name, genericOption, nil, getIPv4Data(t, "docker0"), nil); err == nil {
<add> if err := d.CreateNetwork(name, genericOption, nil, ipV4Data, nil); err == nil {
<ide> ch <- fmt.Errorf("failed was able to create overlap %s", name)
<ide> return
<ide> } | 1 |
Python | Python | raise error not string | daa1c7529ac6491338adb81622d5041a4ba1f446 | <ide><path>boolean_algebra/quine_mc_cluskey.py
<ide> from __future__ import annotations
<ide>
<ide> from collections.abc import Sequence
<add>from typing import Literal
<ide>
<ide>
<del>def compare_string(string1: str, string2: str) -> str:
<add>def compare_string(string1: str, string2: str) -> str | Literal[False]:
<ide> """
<ide> >>> compare_string('0010','0110')
<ide> '0_10'
<ide>
<ide> >>> compare_string('0110','1101')
<del> 'X'
<add> False
<ide> """
<ide> list1 = list(string1)
<ide> list2 = list(string2)
<ide> def compare_string(string1: str, string2: str) -> str:
<ide> count += 1
<ide> list1[i] = "_"
<ide> if count > 1:
<del> return "X"
<add> return False
<ide> else:
<ide> return "".join(list1)
<ide>
<ide> def check(binary: list[str]) -> list[str]:
<ide> for i in range(len(binary)):
<ide> for j in range(i + 1, len(binary)):
<ide> k = compare_string(binary[i], binary[j])
<del> if k != "X":
<add> if k is False:
<ide> check1[i] = "*"
<ide> check1[j] = "*"
<del> temp.append(k)
<add> temp.append("X")
<ide> for i in range(len(binary)):
<ide> if check1[i] == "$":
<ide> pi.append(binary[i])
<ide><path>ciphers/shuffled_shift_cipher.py
<ide> def __str__(self) -> str:
<ide> """
<ide> :return: passcode of the cipher object
<ide> """
<del> return "Passcode is: " + "".join(self.__passcode)
<add> return "".join(self.__passcode)
<ide>
<ide> def __neg_pos(self, iterlist: list[int]) -> list[int]:
<ide> """
<ide><path>computer_vision/harris_corner.py
<ide> def __init__(self, k: float, window_size: int):
<ide> raise ValueError("invalid k value")
<ide>
<ide> def __str__(self) -> str:
<del>
<del> return f"Harris Corner detection with k : {self.k}"
<add> return str(self.k)
<ide>
<ide> def detect(self, img_path: str) -> tuple[cv2.Mat, list[list[int]]]:
<ide>
<ide><path>data_structures/binary_tree/segment_tree_other.py
<ide> def __init__(self, start, end, val, left=None, right=None):
<ide> self.left = left
<ide> self.right = right
<ide>
<del> def __str__(self):
<del> return f"val: {self.val}, start: {self.start}, end: {self.end}"
<add> def __repr__(self):
<add> return f"SegmentTreeNode(start={self.start}, end={self.end}, val={self.val})"
<ide>
<ide>
<ide> class SegmentTree:
<ide> """
<ide> >>> import operator
<ide> >>> num_arr = SegmentTree([2, 1, 5, 3, 4], operator.add)
<del> >>> for node in num_arr.traverse():
<del> ... print(node)
<del> ...
<del> val: 15, start: 0, end: 4
<del> val: 8, start: 0, end: 2
<del> val: 7, start: 3, end: 4
<del> val: 3, start: 0, end: 1
<del> val: 5, start: 2, end: 2
<del> val: 3, start: 3, end: 3
<del> val: 4, start: 4, end: 4
<del> val: 2, start: 0, end: 0
<del> val: 1, start: 1, end: 1
<add> >>> tuple(num_arr.traverse()) # doctest: +NORMALIZE_WHITESPACE
<add> (SegmentTreeNode(start=0, end=4, val=15),
<add> SegmentTreeNode(start=0, end=2, val=8),
<add> SegmentTreeNode(start=3, end=4, val=7),
<add> SegmentTreeNode(start=0, end=1, val=3),
<add> SegmentTreeNode(start=2, end=2, val=5),
<add> SegmentTreeNode(start=3, end=3, val=3),
<add> SegmentTreeNode(start=4, end=4, val=4),
<add> SegmentTreeNode(start=0, end=0, val=2),
<add> SegmentTreeNode(start=1, end=1, val=1))
<ide> >>>
<ide> >>> num_arr.update(1, 5)
<del> >>> for node in num_arr.traverse():
<del> ... print(node)
<del> ...
<del> val: 19, start: 0, end: 4
<del> val: 12, start: 0, end: 2
<del> val: 7, start: 3, end: 4
<del> val: 7, start: 0, end: 1
<del> val: 5, start: 2, end: 2
<del> val: 3, start: 3, end: 3
<del> val: 4, start: 4, end: 4
<del> val: 2, start: 0, end: 0
<del> val: 5, start: 1, end: 1
<add> >>> tuple(num_arr.traverse()) # doctest: +NORMALIZE_WHITESPACE
<add> (SegmentTreeNode(start=0, end=4, val=19),
<add> SegmentTreeNode(start=0, end=2, val=12),
<add> SegmentTreeNode(start=3, end=4, val=7),
<add> SegmentTreeNode(start=0, end=1, val=7),
<add> SegmentTreeNode(start=2, end=2, val=5),
<add> SegmentTreeNode(start=3, end=3, val=3),
<add> SegmentTreeNode(start=4, end=4, val=4),
<add> SegmentTreeNode(start=0, end=0, val=2),
<add> SegmentTreeNode(start=1, end=1, val=5))
<ide> >>>
<ide> >>> num_arr.query_range(3, 4)
<ide> 7
<ide> class SegmentTree:
<ide> >>> for node in max_arr.traverse():
<ide> ... print(node)
<ide> ...
<del> val: 5, start: 0, end: 4
<del> val: 5, start: 0, end: 2
<del> val: 4, start: 3, end: 4
<del> val: 2, start: 0, end: 1
<del> val: 5, start: 2, end: 2
<del> val: 3, start: 3, end: 3
<del> val: 4, start: 4, end: 4
<del> val: 2, start: 0, end: 0
<del> val: 1, start: 1, end: 1
<add> SegmentTreeNode(start=0, end=4, val=5)
<add> SegmentTreeNode(start=0, end=2, val=5)
<add> SegmentTreeNode(start=3, end=4, val=4)
<add> SegmentTreeNode(start=0, end=1, val=2)
<add> SegmentTreeNode(start=2, end=2, val=5)
<add> SegmentTreeNode(start=3, end=3, val=3)
<add> SegmentTreeNode(start=4, end=4, val=4)
<add> SegmentTreeNode(start=0, end=0, val=2)
<add> SegmentTreeNode(start=1, end=1, val=1)
<ide> >>>
<ide> >>> max_arr.update(1, 5)
<ide> >>> for node in max_arr.traverse():
<ide> ... print(node)
<ide> ...
<del> val: 5, start: 0, end: 4
<del> val: 5, start: 0, end: 2
<del> val: 4, start: 3, end: 4
<del> val: 5, start: 0, end: 1
<del> val: 5, start: 2, end: 2
<del> val: 3, start: 3, end: 3
<del> val: 4, start: 4, end: 4
<del> val: 2, start: 0, end: 0
<del> val: 5, start: 1, end: 1
<add> SegmentTreeNode(start=0, end=4, val=5)
<add> SegmentTreeNode(start=0, end=2, val=5)
<add> SegmentTreeNode(start=3, end=4, val=4)
<add> SegmentTreeNode(start=0, end=1, val=5)
<add> SegmentTreeNode(start=2, end=2, val=5)
<add> SegmentTreeNode(start=3, end=3, val=3)
<add> SegmentTreeNode(start=4, end=4, val=4)
<add> SegmentTreeNode(start=0, end=0, val=2)
<add> SegmentTreeNode(start=1, end=1, val=5)
<ide> >>>
<ide> >>> max_arr.query_range(3, 4)
<ide> 4
<ide> class SegmentTree:
<ide> >>> for node in min_arr.traverse():
<ide> ... print(node)
<ide> ...
<del> val: 1, start: 0, end: 4
<del> val: 1, start: 0, end: 2
<del> val: 3, start: 3, end: 4
<del> val: 1, start: 0, end: 1
<del> val: 5, start: 2, end: 2
<del> val: 3, start: 3, end: 3
<del> val: 4, start: 4, end: 4
<del> val: 2, start: 0, end: 0
<del> val: 1, start: 1, end: 1
<add> SegmentTreeNode(start=0, end=4, val=1)
<add> SegmentTreeNode(start=0, end=2, val=1)
<add> SegmentTreeNode(start=3, end=4, val=3)
<add> SegmentTreeNode(start=0, end=1, val=1)
<add> SegmentTreeNode(start=2, end=2, val=5)
<add> SegmentTreeNode(start=3, end=3, val=3)
<add> SegmentTreeNode(start=4, end=4, val=4)
<add> SegmentTreeNode(start=0, end=0, val=2)
<add> SegmentTreeNode(start=1, end=1, val=1)
<ide> >>>
<ide> >>> min_arr.update(1, 5)
<ide> >>> for node in min_arr.traverse():
<ide> ... print(node)
<ide> ...
<del> val: 2, start: 0, end: 4
<del> val: 2, start: 0, end: 2
<del> val: 3, start: 3, end: 4
<del> val: 2, start: 0, end: 1
<del> val: 5, start: 2, end: 2
<del> val: 3, start: 3, end: 3
<del> val: 4, start: 4, end: 4
<del> val: 2, start: 0, end: 0
<del> val: 5, start: 1, end: 1
<add> SegmentTreeNode(start=0, end=4, val=2)
<add> SegmentTreeNode(start=0, end=2, val=2)
<add> SegmentTreeNode(start=3, end=4, val=3)
<add> SegmentTreeNode(start=0, end=1, val=2)
<add> SegmentTreeNode(start=2, end=2, val=5)
<add> SegmentTreeNode(start=3, end=3, val=3)
<add> SegmentTreeNode(start=4, end=4, val=4)
<add> SegmentTreeNode(start=0, end=0, val=2)
<add> SegmentTreeNode(start=1, end=1, val=5)
<ide> >>>
<ide> >>> min_arr.query_range(3, 4)
<ide> 3
<ide> class SegmentTree:
<ide> >>> min_arr.query_range(1, 3)
<ide> 3
<ide> >>>
<del>
<ide> """
<ide>
<ide> def __init__(self, collection: Sequence, function):
<ide><path>data_structures/binary_tree/wavelet_tree.py
<ide> def __repr__(self) -> str:
<ide> """
<ide> >>> node = Node(length=27)
<ide> >>> repr(node)
<del> 'min_value: -1, max_value: -1'
<add> 'Node(min_value=-1 max_value=-1)'
<ide> >>> repr(node) == str(node)
<ide> True
<ide> """
<del> return f"min_value: {self.minn}, max_value: {self.maxx}"
<add> return f"Node(min_value={self.minn} max_value={self.maxx})"
<ide>
<ide>
<ide> def build_tree(arr: list[int]) -> Node | None:
<ide> def build_tree(arr: list[int]) -> Node | None:
<ide> of the constructed tree
<ide>
<ide> >>> build_tree(test_array)
<del> min_value: 0, max_value: 9
<add> Node(min_value=0 max_value=9)
<ide> """
<ide> root = Node(len(arr))
<ide> root.minn, root.maxx = min(arr), max(arr)
<ide><path>data_structures/linked_list/doubly_linked_list.py
<ide> def delete(self, data) -> str:
<ide> if current.next:
<ide> current = current.next
<ide> else: # We have reached the end an no value matches
<del> return "No data matching given value"
<add> raise ValueError("No data matching given value")
<ide>
<ide> if current == self.head:
<ide> self.delete_head()
<ide><path>data_structures/queue/double_ended_queue.py
<ide> def __repr__(self) -> str:
<ide> values_list.append(aux.val)
<ide> aux = aux.next_node
<ide>
<del> return "[" + ", ".join(repr(val) for val in values_list) + "]"
<add> return f"[{', '.join(repr(val) for val in values_list)}]"
<ide>
<ide>
<ide> if __name__ == "__main__":
<ide><path>graphs/breadth_first_search_shortest_path.py
<ide> def shortest_path(self, target_vertex: str) -> str:
<ide>
<ide> Case 1 - No path is found.
<ide> >>> g.shortest_path("Foo")
<del> 'No path from vertex:G to vertex:Foo'
<add> Traceback (most recent call last):
<add> ...
<add> ValueError: No path from vertex: G to vertex: Foo
<ide>
<ide> Case 2 - The path is found.
<ide> >>> g.shortest_path("D")
<ide> def shortest_path(self, target_vertex: str) -> str:
<ide>
<ide> target_vertex_parent = self.parent.get(target_vertex)
<ide> if target_vertex_parent is None:
<del> return f"No path from vertex:{self.source_vertex} to vertex:{target_vertex}"
<add> raise ValueError(
<add> f"No path from vertex: {self.source_vertex} to vertex: {target_vertex}"
<add> )
<ide>
<ide> return self.shortest_path(target_vertex_parent) + f"->{target_vertex}"
<ide>
<ide><path>graphs/page_rank.py
<ide> def add_outbound(self, node):
<ide> self.outbound.append(node)
<ide>
<ide> def __repr__(self):
<del> return f"Node {self.name}: Inbound: {self.inbound} ; Outbound: {self.outbound}"
<add> return f"<node={self.name} inbound={self.inbound} outbound={self.outbound}>"
<ide>
<ide>
<ide> def page_rank(nodes, limit=3, d=0.85):
<ide><path>linear_algebra/src/polynom_for_points.py
<ide> def points_to_polynomial(coordinates: list[list[int]]) -> str:
<ide> number of points you want to use
<ide>
<ide> >>> print(points_to_polynomial([]))
<del> The program cannot work out a fitting polynomial.
<add> Traceback (most recent call last):
<add> ...
<add> ValueError: The program cannot work out a fitting polynomial.
<ide> >>> print(points_to_polynomial([[]]))
<del> The program cannot work out a fitting polynomial.
<add> Traceback (most recent call last):
<add> ...
<add> ValueError: The program cannot work out a fitting polynomial.
<ide> >>> print(points_to_polynomial([[1, 0], [2, 0], [3, 0]]))
<ide> f(x)=x^2*0.0+x^1*-0.0+x^0*0.0
<ide> >>> print(points_to_polynomial([[1, 1], [2, 1], [3, 1]]))
<ide> def points_to_polynomial(coordinates: list[list[int]]) -> str:
<ide> f(x)=x^2*5.0+x^1*-18.0+x^0*18.0
<ide> """
<ide> if len(coordinates) == 0 or not all(len(pair) == 2 for pair in coordinates):
<del> return "The program cannot work out a fitting polynomial."
<add> raise ValueError("The program cannot work out a fitting polynomial.")
<ide>
<ide> if len({tuple(pair) for pair in coordinates}) != len(coordinates):
<del> return "The program cannot work out a fitting polynomial."
<add> raise ValueError("The program cannot work out a fitting polynomial.")
<ide>
<ide> set_x = {x for x, _ in coordinates}
<ide> if len(set_x) == 1:
<ide> return f"x={coordinates[0][0]}"
<ide>
<ide> if len(set_x) != len(coordinates):
<del> return "The program cannot work out a fitting polynomial."
<add> raise ValueError("The program cannot work out a fitting polynomial.")
<ide>
<ide> x = len(coordinates)
<ide>
<ide><path>maths/monte_carlo_dice.py
<ide> def __init__(self):
<ide> def roll(self):
<ide> return random.choice(self.sides)
<ide>
<del> def _str_(self):
<del> return "Fair Dice"
<del>
<ide>
<ide> def throw_dice(num_throws: int, num_dice: int = 2) -> list[float]:
<ide> """
<ide><path>matrix/cramers_rule_2x2.py
<ide> # https://en.wikipedia.org/wiki/Cramer%27s_rule
<ide>
<ide>
<del>def cramers_rule_2x2(equation1: list[int], equation2: list[int]) -> str:
<add>def cramers_rule_2x2(equation1: list[int], equation2: list[int]) -> tuple[float, float]:
<ide> """
<ide> Solves the system of linear equation in 2 variables.
<ide> :param: equation1: list of 3 numbers
<ide> def cramers_rule_2x2(equation1: list[int], equation2: list[int]) -> str:
<ide> determinant_y = [[a1, d1], [a2, d2]]
<ide>
<ide> >>> cramers_rule_2x2([2, 3, 0], [5, 1, 0])
<del> 'Trivial solution. (Consistent system) x = 0 and y = 0'
<add> (0.0, 0.0)
<ide> >>> cramers_rule_2x2([0, 4, 50], [2, 0, 26])
<del> 'Non-Trivial Solution (Consistent system) x = 13.0, y = 12.5'
<add> (13.0, 12.5)
<ide> >>> cramers_rule_2x2([11, 2, 30], [1, 0, 4])
<del> 'Non-Trivial Solution (Consistent system) x = 4.0, y = -7.0'
<add> (4.0, -7.0)
<ide> >>> cramers_rule_2x2([4, 7, 1], [1, 2, 0])
<del> 'Non-Trivial Solution (Consistent system) x = 2.0, y = -1.0'
<add> (2.0, -1.0)
<ide>
<ide> >>> cramers_rule_2x2([1, 2, 3], [2, 4, 6])
<ide> Traceback (most recent call last):
<ide> def cramers_rule_2x2(equation1: list[int], equation2: list[int]) -> str:
<ide> raise ValueError("No solution. (Inconsistent system)")
<ide> else:
<ide> if determinant_x == determinant_y == 0:
<del> return "Trivial solution. (Consistent system) x = 0 and y = 0"
<add> # Trivial solution (Inconsistent system)
<add> return (0.0, 0.0)
<ide> else:
<ide> x = determinant_x / determinant
<ide> y = determinant_y / determinant
<del> return f"Non-Trivial Solution (Consistent system) x = {x}, y = {y}"
<add> # Non-Trivial Solution (Consistent system)
<add> return (x, y)
<ide><path>other/password.py
<ide> def random_characters(chars_incl, i):
<ide> # This Will Check Whether A Given Password Is Strong Or Not
<ide> # It Follows The Rule that Length Of Password Should Be At Least 8 Characters
<ide> # And At Least 1 Lower, 1 Upper, 1 Number And 1 Special Character
<del>def strong_password_detector(password: str, min_length: int = 8) -> str:
<add>def is_strong_password(password: str, min_length: int = 8) -> bool:
<ide> """
<del> >>> strong_password_detector('Hwea7$2!')
<del> 'This is a strong Password'
<del>
<del> >>> strong_password_detector('Sh0r1')
<del> 'Your Password must be at least 8 characters long'
<del>
<del> >>> strong_password_detector('Hello123')
<del> 'Password should contain UPPERCASE, lowercase, numbers, special characters'
<del>
<del> >>> strong_password_detector('Hello1238udfhiaf038fajdvjjf!jaiuFhkqi1')
<del> 'This is a strong Password'
<del>
<del> >>> strong_password_detector('0')
<del> 'Your Password must be at least 8 characters long'
<add> >>> is_strong_password('Hwea7$2!')
<add> True
<add> >>> is_strong_password('Sh0r1')
<add> False
<add> >>> is_strong_password('Hello123')
<add> False
<add> >>> is_strong_password('Hello1238udfhiaf038fajdvjjf!jaiuFhkqi1')
<add> True
<add> >>> is_strong_password('0')
<add> False
<ide> """
<ide>
<ide> if len(password) < min_length:
<del> return "Your Password must be at least 8 characters long"
<add> # Your Password must be at least 8 characters long
<add> return False
<ide>
<ide> upper = any(char in ascii_uppercase for char in password)
<ide> lower = any(char in ascii_lowercase for char in password)
<ide> num = any(char in digits for char in password)
<ide> spec_char = any(char in punctuation for char in password)
<ide>
<ide> if upper and lower and num and spec_char:
<del> return "This is a strong Password"
<add> return True
<ide>
<ide> else:
<del> return (
<del> "Password should contain UPPERCASE, lowercase, "
<del> "numbers, special characters"
<del> )
<add> # Passwords should contain UPPERCASE, lowerase
<add> # numbers, and special characters
<add> return False
<ide>
<ide>
<ide> def main():
<ide><path>strings/dna.py
<ide> def dna(dna: str) -> str:
<ide> >>> dna("CTGA")
<ide> 'GACT'
<ide> >>> dna("GFGG")
<del> 'Invalid Strand'
<add> Traceback (most recent call last):
<add> ...
<add> ValueError: Invalid Strand
<ide> """
<ide>
<del> r = len(re.findall("[ATCG]", dna)) != len(dna)
<del> val = dna.translate(dna.maketrans("ATCG", "TAGC"))
<del> return "Invalid Strand" if r else val
<add> if len(re.findall("[ATCG]", dna)) != len(dna):
<add> raise ValueError("Invalid Strand")
<add>
<add> return dna.translate(dna.maketrans("ATCG", "TAGC"))
<ide>
<ide>
<ide> if __name__ == "__main__":
<del> __import__("doctest").testmod()
<add> import doctest
<add>
<add> doctest.testmod() | 14 |
Javascript | Javascript | support odd value for kstringmaxlength | 753b68f9d8177d6af6da536b91d7660182c45406 | <ide><path>test/addons/stringbytes-external-exceed-max/test-stringbytes-external-exceed-max-by-2.js
<ide> if (!binding.ensureAllocation(2 * kStringMaxLength))
<ide> common.skip(skipMessage);
<ide>
<ide> const maxString = buf.toString('utf16le');
<del>assert.strictEqual(maxString.length, (kStringMaxLength + 2) / 2);
<add>assert.strictEqual(maxString.length, Math.floor((kStringMaxLength + 2) / 2)); | 1 |
Javascript | Javascript | upgrade requirecontextplugin to es6 | bca84363f88a4a646cc1e9f0c30ebb690c980acb | <ide><path>lib/dependencies/RequireContextPlugin.js
<ide> MIT License http://www.opensource.org/licenses/mit-license.php
<ide> Author Tobias Koppers @sokra
<ide> */
<del>var RequireContextDependency = require("./RequireContextDependency");
<del>var ContextElementDependency = require("./ContextElementDependency");
<add>"use strict";
<ide>
<del>var RequireContextDependencyParserPlugin = require("./RequireContextDependencyParserPlugin");
<add>const RequireContextDependency = require("./RequireContextDependency");
<add>const ContextElementDependency = require("./ContextElementDependency");
<ide>
<del>function RequireContextPlugin(modulesDirectories, extensions) {
<del> if(!Array.isArray(modulesDirectories))
<del> throw new Error("modulesDirectories must be an array");
<del> if(!Array.isArray(extensions))
<del> throw new Error("extensions must be an array");
<del> this.modulesDirectories = modulesDirectories;
<del> this.extensions = extensions;
<del>}
<del>module.exports = RequireContextPlugin;
<add>const RequireContextDependencyParserPlugin = require("./RequireContextDependencyParserPlugin");
<ide>
<del>RequireContextPlugin.prototype.apply = function(compiler) {
<del> var modulesDirectories = this.modulesDirectories;
<del> var extensions = this.extensions;
<del> compiler.plugin("compilation", function(compilation, params) {
<del> var contextModuleFactory = params.contextModuleFactory;
<del> var normalModuleFactory = params.normalModuleFactory;
<add>class RequireContextPlugin {
<add> constructor(modulesDirectories, extensions) {
<add> if(!Array.isArray(modulesDirectories))
<add> throw new Error("modulesDirectories must be an array");
<add> if(!Array.isArray(extensions))
<add> throw new Error("extensions must be an array");
<add> this.modulesDirectories = modulesDirectories;
<add> this.extensions = extensions;
<add> }
<ide>
<del> compilation.dependencyFactories.set(RequireContextDependency, contextModuleFactory);
<del> compilation.dependencyTemplates.set(RequireContextDependency, new RequireContextDependency.Template());
<add> apply(compiler) {
<add> const modulesDirectories = this.modulesDirectories;
<add> const extensions = this.extensions;
<add> compiler.plugin("compilation", (compilation, params) => {
<add> const contextModuleFactory = params.contextModuleFactory;
<add> const normalModuleFactory = params.normalModuleFactory;
<ide>
<del> compilation.dependencyFactories.set(ContextElementDependency, normalModuleFactory);
<add> compilation.dependencyFactories.set(RequireContextDependency, contextModuleFactory);
<add> compilation.dependencyTemplates.set(RequireContextDependency, new RequireContextDependency.Template());
<ide>
<del> params.normalModuleFactory.plugin("parser", function(parser, parserOptions) {
<add> compilation.dependencyFactories.set(ContextElementDependency, normalModuleFactory);
<ide>
<del> if(typeof parserOptions.requireContext !== "undefined" && !parserOptions.requireContext)
<del> return;
<add> params.normalModuleFactory.plugin("parser", (parser, parserOptions) => {
<ide>
<del> parser.apply(new RequireContextDependencyParserPlugin());
<del> });
<add> if(typeof parserOptions.requireContext !== "undefined" && !parserOptions.requireContext)
<add> return;
<ide>
<del> params.contextModuleFactory.plugin("alternatives", function(items, callback) {
<del> if(items.length === 0) return callback(null, items);
<add> parser.apply(new RequireContextDependencyParserPlugin());
<add> });
<ide>
<del> callback(null, items.map(function(obj) {
<del> return extensions.filter(function(ext) {
<del> var l = obj.request.length;
<del> return l > ext.length && obj.request.substr(l - ext.length, l) === ext;
<del> }).map(function(ext) {
<del> var l = obj.request.length;
<del> return {
<del> context: obj.context,
<del> request: obj.request.substr(0, l - ext.length)
<del> };
<del> }).concat(obj);
<del> }).reduce(function(a, b) {
<del> return a.concat(b);
<del> }, []));
<del> });
<add> params.contextModuleFactory.plugin("alternatives", (items, callback) => {
<add> if(items.length === 0) return callback(null, items);
<ide>
<del> params.contextModuleFactory.plugin("alternatives", function(items, callback) {
<del> if(items.length === 0) return callback(null, items);
<add> callback(null, items.map((obj) => {
<add> return extensions.filter((ext) => {
<add> const l = obj.request.length;
<add> return l > ext.length && obj.request.substr(l - ext.length, l) === ext;
<add> }).map((ext) => {
<add> const l = obj.request.length;
<add> return {
<add> context: obj.context,
<add> request: obj.request.substr(0, l - ext.length)
<add> };
<add> }).concat(obj);
<add> }).reduce((a, b) => a.concat(b), []));
<add> });
<ide>
<del> callback(null, items.map(function(obj) {
<del> for(var i = 0; i < modulesDirectories.length; i++) {
<del> var dir = modulesDirectories[i];
<del> var idx = obj.request.indexOf("./" + dir + "/");
<del> if(idx === 0) {
<del> obj.request = obj.request.slice(dir.length + 3);
<del> break;
<add> params.contextModuleFactory.plugin("alternatives", (items, callback) => {
<add> if(items.length === 0) return callback(null, items);
<add>
<add> callback(null, items.map((obj) => {
<add> for(let i = 0; i < modulesDirectories.length; i++) {
<add> const dir = modulesDirectories[i];
<add> const idx = obj.request.indexOf("./" + dir + "/");
<add> if(idx === 0) {
<add> obj.request = obj.request.slice(dir.length + 3);
<add> break;
<add> }
<ide> }
<del> }
<del> return obj;
<del> }));
<add> return obj;
<add> }));
<add> });
<ide> });
<del> });
<del>};
<add> }
<add>}
<add>module.exports = RequireContextPlugin;
<add>
<ide>\ No newline at end of file | 1 |
Text | Text | add translation kr/threejs-rendering-on-demand.md | 633dbb61bdfd242077b4c012fce7468c1e707c1a | <ide><path>threejs/lessons/kr/threejs-multiple-scenes.md
<add>Title: Three.js로 캔버스, 장면 여러 개 만들기
<add>Description: THREE.js로 다수의 장면을 렌더링해봅니다
<add>TOC: 다중 캔버스, 다중 장면 만들기
<add>
<add>사람들이 자주 하는 질문 중 하나는 Three.js로 여러 개의 캔버스(canvas)를 렌더링하려면
<add>어떻게 해야 하나요?"입니다. 쇼핑몰 사이트나 3D 도표가 여러 개 있는 웹 페이지를
<add>제작한다고 해봅시다. 얼핏 그리 어려울 건 없어 보입니다. 그냥 도표가 들어갈 곳마다
<add>각각 캔버스를 만들고, 각 캔버스마다 `Renderer`를 생성하면 되지 않을까요?
<add>
<add>하지만 이 방법을 적용하자마자 문제가 생깁니다.
<add>
<add>1. 브라우저의 WebGL 컨텍스트(context)는 제한적이다.
<add>
<add> 일반적으로 약 8개가 최대입니다. 9번째 컨텍스트를 만들면 제일 처음에 만들었던
<add> 컨텍스트가 사라지죠.
<add>
<add>2. WebGL 자원은 컨텍스트끼리 공유할 수 없다.
<add>
<add> 10MB짜리 모델을 캔버스 두 개에서 사용하려면 모델을 각각 총 두 번 로드해야 하고,
<add> 원래의 두 배인 20MB의 자원을 사용한다는 의미입니다. 컨텍스트끼리는 어떤 것도 공유할
<add> 수 없죠. 또한 초기화도 두 번, 쉐이더 컴파일도 두 번, 같은 동작은 모두 두 번씩
<add> 실행해야 합니다. 캔버스의 개수가 많아질수록 성능에 문제가 생기겠죠.
<add>
<add>그렇다면 어떻게 해야 할까요?
<add>
<add>방법 중 하나는 캔버스 하나로 화면 전체를 채우고, 각 "가상" 캔버스를 대신할 HTML 요소(element)를
<add>두는 겁니다. `Renderer`는 하나만 만들되 가상 캔버스에 각각 `Scene`을 만드는 거죠. 그리고
<add>가상 HTML 요소의 좌표를 계산해 요소가 화면에 보인다면 Three.js가 해당 장면(scene)을 가상
<add>요소의 좌표에 맞춰 렌더링하도록 합니다.
<add>
<add>이 방법은 캔버스를 하나만 사용하므로 위 1번과 2번 문제 모두 해결할 수 있습니다. 컨텍스트를
<add>하나만 사용하니 WebGL 컨텍스트 제한을 걱정할 일도 없고, 자원을 몇 배씩 더 사용할 일도 없죠.
<add>
<add>2개의 장면만 만들어 간단히 테스트를 해보겠습니다. 먼저 HTML을 작성합니다.
<add>
<add>```html
<add><canvas id="c"></canvas>
<add><p>
<add> <span id="box" class="diagram left"></span>
<add> I love boxes. Presents come in boxes.
<add> When I find a new box I'm always excited to find out what's inside.
<add></p>
<add><p>
<add> <span id="pyramid" class="diagram right"></span>
<add> When I was a kid I dreamed of going on an expedition inside a pyramid
<add> and finding a undiscovered tomb full of mummies and treasure.
<add></p>
<add>```
<add>
<add>다음으로 CSS를 작성합니다.
<add>
<add>```css
<add>#c {
<add> position: fixed;
<add> left: 0;
<add> top: 0;
<add> width: 100vw;
<add> height: 100vh;
<add> display: block;
<add> z-index: -1;
<add>}
<add>.diagram {
<add> display: inline-block;
<add> width: 5em;
<add> height: 3em;
<add> border: 1px solid black;
<add>}
<add>.left {
<add> float: left;
<add> margin-right: .25em;
<add>}
<add>.right {
<add> float: right;
<add> margin-left: .25em;
<add>}
<add>```
<add>
<add>캔버스가 화면 전체를 채우도록 하고 `z-index`를 -1로 설정해 다른 요소 뒤로 가도록 했습니다.
<add>가상 요소에 컨텐츠가 없어 크기가 0이니 별도의 width와 height도 지정해줬습니다.
<add>
<add>이제 각각의 카메라와 조명이 있는 장면 2개를 만듭니다. 하나에는 정육면체, 다른 하나에는
<add>다이아몬드 모양을 넣을 겁니다.
<add>
<add>```js
<add>function makeScene(elem) {
<add> const scene = new THREE.Scene();
<add>
<add> const fov = 45;
<add> const aspect = 2; // 캔버스 기본값
<add> const near = 0.1;
<add> const far = 5;
<add> const camera = new THREE.PerspectiveCamera(fov, aspect, near, far);
<add> camera.position.z = 2;
<add> camera.position.set(0, 1, 2);
<add> camera.lookAt(0, 0, 0);
<add>
<add> {
<add> const color = 0xFFFFFF;
<add> const intensity = 1;
<add> const light = new THREE.DirectionalLight(color, intensity);
<add> light.position.set(-1, 2, 4);
<add> scene.add(light);
<add> }
<add>
<add> return { scene, camera, elem };
<add>}
<add>
<add>function setupScene1() {
<add> const sceneInfo = makeScene(document.querySelector('#box'));
<add> const geometry = new THREE.BoxBufferGeometry(1, 1, 1);
<add> const material = new THREE.MeshPhongMaterial({color: 'red'});
<add> const mesh = new THREE.Mesh(geometry, material);
<add> sceneInfo.scene.add(mesh);
<add> sceneInfo.mesh = mesh;
<add> return sceneInfo;
<add>}
<add>
<add>function setupScene2() {
<add> const sceneInfo = makeScene(document.querySelector('#pyramid'));
<add> const radius = .8;
<add> const widthSegments = 4;
<add> const heightSegments = 2;
<add> const geometry = new THREE.SphereBufferGeometry(radius, widthSegments, heightSegments);
<add> const material = new THREE.MeshPhongMaterial({
<add> color: 'blue',
<add> flatShading: true,
<add> });
<add> const mesh = new THREE.Mesh(geometry, material);
<add> sceneInfo.scene.add(mesh);
<add> sceneInfo.mesh = mesh;
<add> return sceneInfo;
<add>}
<add>
<add>const sceneInfo1 = setupScene1();
<add>const sceneInfo2 = setupScene2();
<add>```
<add>
<add>이제 각 요소가 화면에 보일 때만 장면을 렌더링할 함수를 만듭니다. `Renderer.setScissorTest`를
<add>호출해 *가위(scissor)* 테스트를 활성화하면 Three.js가 캔버스의 특정 부분만 렌더링하도록
<add>할 수 있습니다. 그리고 `Renderer.setScissor`로 가위를 설정한 뒤 `Renderer.setViewport`로
<add>장면의 좌표를 설정합니다.
<add>
<add>```js
<add>function renderSceneInfo(sceneInfo) {
<add> const { scene, camera, elem } = sceneInfo;
<add>
<add> // 해당 요소의 화면 대비 좌표를 가져옵니다
<add> const { left, right, top, bottom, width, height } =
<add> elem.getBoundingClientRect();
<add>
<add> const isOffscreen =
<add> bottom < 0 ||
<add> top > renderer.domElement.clientHeight ||
<add> right < 0 ||
<add> left > renderer.domElement.clientWidth;
<add>
<add> if (isOffscreen) {
<add> return;
<add> }
<add>
<add> camera.aspect = width / height;
<add> camera.updateProjectionMatrix();
<add>
<add> const positiveYUpBottom = canvasRect.height - bottom;
<add> renderer.setScissor(left, positiveYUpBottom, width, height);
<add> renderer.setViewport(left, positiveYUpBottom, width, height);
<add>
<add> renderer.render(scene, camera);
<add>}
<add>```
<add>
<add>다음으로 `render` 함수 안에서 먼저 캔버스 전체를 비운 뒤 각 장면을 렌더링합니다.
<add>
<add>```js
<add>function render(time) {
<add> time *= 0.001;
<add>
<add> resizeRendererToDisplaySize(renderer);
<add>
<add> renderer.setScissorTest(false);
<add> renderer.clear(true, true);
<add> renderer.setScissorTest(true);
<add>
<add> sceneInfo1.mesh.rotation.y = time * .1;
<add> sceneInfo2.mesh.rotation.y = time * .1;
<add>
<add> renderSceneInfo(sceneInfo1);
<add> renderSceneInfo(sceneInfo2);
<add>
<add> requestAnimationFrame(render);
<add>}
<add>```
<add>
<add>결과를 확인해볼까요?
<add>
<add>{{{example url="../threejs-multiple-scenes-v1.html" }}}
<add>
<add>첫 번째 `<span>` 요소가 있는 곳에는 빨간 정육면체가, 두 번째 `<span>` 요소가 있는 곳에는
<add>파란 다이아몬드가 보일 겁니다.
<add>
<add>## 동기화하기
<add>
<add>위 코드는 나쁘지 않지만 작은 문제가 있습니다. 복잡한 장면 등 무슨 이유라도 렌더링하는
<add>데 시간이 오래 걸린다면, 장면의 좌표는 페이지의 다른 컨텐츠에 비해 더디게 내려올 겁니다.
<add>
<add>각 가상 요소에 테두리를 넣고
<add>
<add>```css
<add>.diagram {
<add> display: inline-block;
<add> width: 5em;
<add> height: 3em;
<add>+ border: 1px solid black;
<add>}
<add>```
<add>
<add>각 장면에 배경색도 넣어줍니다.
<add>
<add>```js
<add>const scene = new THREE.Scene();
<add>+scene.background = new THREE.Color('red');
<add>```
<add>
<add>그런 다음 <a href="../threejs-multiple-scenes-v2.html" target="_blank">빠르게 스크롤을 위아래로 반복해보면</a>
<add>문제가 보일겁니다. 아래는 스크롤 애니메이션 캡쳐본의 속도를 10배 낮춘 예시입니다.
<add>
<add><div class="threejs_center"><img class="border" src="resources/images/multi-view-skew.gif"></div>
<add>
<add>추가로 처리해줘야 할 것이 있긴 하지만, 캔버스의 CSS를 `position: fixed`에서 `position: absolute`로
<add>바꿔 문제를 해결할 수 있습니다.
<add>
<add>```css
<add>#c {
<add>- position: fixed;
<add>+ position: absolute;
<add>```
<add>
<add>그리고 페이지 스크롤에 상관 없이 캔버스가 항상 화면의 상단에 위치할 수 있도록 캔버스에
<add>transform 스타일을 지정해줍니다.
<add>
<add>```js
<add>function render(time) {
<add> ...
<add>
<add> const transform = `translateY(${ window.scrollY }px)`;
<add> renderer.domElement.style.transform = transform;
<add>
<add>```
<add>
<add>캔버스에 `position: fixed`를 적용하면 캔버스는 스크롤의 영향을 받지 않습니다. `position: absolute`를
<add>적용하면 렌더링하는 데 시간이 걸리더라도 일단 다른 페이지와 같이 스크롤이 되겠죠. 그리고
<add>렌더링하기 전에 캔버스를 다시 움직여 화면 전체에 맞춘 뒤 캔버스를 렌더링하는 겁니다. 이러면
<add>화면의 가장자리에 살짝 렌더링되지 않은 부분이 보일 수는 있어도 나머지 페이지에 있는 요소는
<add>버벅이지 않고 제자리에 있을 겁니다. 아래는 해당 코드를 적용한 화면의 캡쳐본을 아까와 마찬가지로
<add>10배 느리게 만든 것입니다.
<add>
<add><div class="threejs_center"><img class="border" src="resources/images/multi-view-fixed.gif"></div>
<add>
<add>## 확장하기 쉽게 만들기
<add>
<add>여러 장면을 구현했으니 이제 이 예제를 좀 더 확장하기 쉽게 만들어보겠습니다.
<add>
<add>먼저 기존처럼 캔버스 전체를 렌더링하는 `render` 함수를 두고, 각 장면에 해당하는 가상 요소,
<add>해당 장면을 렌더링하는 함수로 이루어진 객체의 배열을 만듭니다. `render` 함수에서 가상 요소가
<add>화면에 보이는지 확인한 뒤, 가상 요소가 화면에 보인다면 상응하는 렌더링 함수를 호출합니다. 이러면
<add>확장성은 물론 각 장면의 렌더링 함수를 작성할 때도 전체를 신경쓸 필요가 없죠.
<add>
<add>아래는 전체를 담당하는 `render` 함수입니다.
<add>
<add>```js
<add>const sceneElements = [];
<add>function addScene(elem, fn) {
<add> sceneElements.push({ elem, fn });
<add>}
<add>
<add>function render(time) {
<add> time *= 0.001;
<add>
<add> resizeRendererToDisplaySize(renderer);
<add>
<add> renderer.setScissorTest(false);
<add> renderer.setClearColor(clearColor, 0);
<add> renderer.clear(true, true);
<add> renderer.setScissorTest(true);
<add>
<add> const transform = `translateY(${ window.scrollY }px)`;
<add> renderer.domElement.style.transform = transform;
<add>
<add> for (const { elem, fn } of sceneElements) {
<add> // 해당 요소의 화면 대비 좌표를 가져옵니다
<add> const rect = elem.getBoundingClientRect();
<add> const {left, right, top, bottom, width, height} = rect;
<add>
<add> const isOffscreen =
<add> bottom < 0 ||
<add> top > renderer.domElement.clientHeight ||
<add> right < 0 ||
<add> left > renderer.domElement.clientWidth;
<add>
<add> if (!isOffscreen) {
<add> const positiveYUpBottom = renderer.domElement.clientHeight - bottom;
<add> renderer.setScissor(left, positiveYUpBottom, width, height);
<add> renderer.setViewport(left, positiveYUpBottom, width, height);
<add>
<add> fn(time, rect);
<add> }
<add> }
<add>
<add> requestAnimationFrame(render);
<add>}
<add>```
<add>
<add>`render` 함수는 `elem`과 `fn` 속성의 객체로 이루어진 `sceneElements` 배열을 순회합니다.
<add>
<add>그리고 각 요소가 화면에 보이는지 확인하고, 화면에 보인다면 `fn`에 해당 장면이 들어가야할
<add>사각 좌표와 현재 시간값을 넘겨주어 호출합니다.
<add>
<add>이제 각 장면을 만들고 상응하는 요소와 렌더링 함수를 추가합니다.
<add>
<add>```js
<add>{
<add> const elem = document.querySelector('#box');
<add> const { scene, camera } = makeScene();
<add> const geometry = new THREE.BoxBufferGeometry(1, 1, 1);
<add> const material = new THREE.MeshPhongMaterial({ color: 'red' });
<add> const mesh = new THREE.Mesh(geometry, material);
<add> scene.add(mesh);
<add> addScene(elem, (time, rect) => {
<add> camera.aspect = rect.width / rect.height;
<add> camera.updateProjectionMatrix();
<add> mesh.rotation.y = time * .1;
<add> renderer.render(scene, camera);
<add> });
<add>}
<add>
<add>{
<add> const elem = document.querySelector('#pyramid');
<add> const { scene, camera } = makeScene();
<add> const radius = .8;
<add> const widthSegments = 4;
<add> const heightSegments = 2;
<add> const geometry = new THREE.SphereBufferGeometry(radius, widthSegments, heightSegments);
<add> const material = new THREE.MeshPhongMaterial({
<add> color: 'blue',
<add> flatShading: true,
<add> });
<add> const mesh = new THREE.Mesh(geometry, material);
<add> scene.add(mesh);
<add> addScene(elem, (time, rect) => {
<add> camera.aspect = rect.width / rect.height;
<add> camera.updateProjectionMatrix();
<add> mesh.rotation.y = time * .1;
<add> renderer.render(scene, camera);
<add> });
<add>}
<add>```
<add>
<add>`sceneInfo1`, `sceneInfo2`는 더 이상 필요 없으니 제거합니다. 대신 각 mesh의 회전은 해당
<add>장면에서 처리해야 합니다.
<add>
<add>{{{example url="../threejs-multiple-scenes-generic.html" }}}
<add>
<add>## HTML Dataset 사용하기
<add>
<add>HTML의 [dataset](https://developer.mozilla.org/ko/docs/Web/API/HTMLElement/dataset)을
<add>이용하면 좀 더 확장하기 쉬운 환경을 만들 수 있습니다. `id="..."` 대신 `data-diagram="..."`을
<add>이용해 데이터를 직접 HTML 요소에 지정하는 거죠.
<add>
<add>```html
<add><canvas id="c"></canvas>
<add><p>
<add>- <span id="box" class="diagram left"></span>
<add>+ <span data-diagram="box" class="left"></span>
<add> I love boxes. Presents come in boxes.
<add> When I find a new box I'm always excited to find out what's inside.
<add></p>
<add><p>
<add>- <span id="pyramid" class="diagram left"></span>
<add>+ <span data-diagram="pyramid" class="right"></span>
<add> When I was a kid I dreamed of going on an expedition inside a pyramid
<add> and finding a undiscovered tomb full of mummies and treasure.
<add></p>
<add>```
<add>
<add>요소의 id를 제거했으니 CSS 셀렉터도 다음처럼 바꾸어야 합니다.
<add>
<add>```css
<add>-.diagram
<add>+*[data-diagram] {
<add> display: inline-block;
<add> width: 5em;
<add> height: 3em;
<add>}
<add>```
<add>
<add>또한 각 장면을 만드는 코드를 *scene initialization functions*라는 맵으로 만듭니다.
<add>이 맵은 키값에 대응하는 *장면 렌더링 함수*를 반환할 겁니다.
<add>
<add>```js
<add>const sceneInitFunctionsByName = {
<add> 'box': () => {
<add> const { scene, camera } = makeScene();
<add> const geometry = new THREE.BoxBufferGeometry(1, 1, 1);
<add> const material = new THREE.MeshPhongMaterial({color: 'red'});
<add> const mesh = new THREE.Mesh(geometry, material);
<add> scene.add(mesh);
<add> return (time, rect) => {
<add> mesh.rotation.y = time * .1;
<add> camera.aspect = rect.width / rect.height;
<add> camera.updateProjectionMatrix();
<add> renderer.render(scene, camera);
<add> };
<add> },
<add> 'pyramid': () => {
<add> const { scene, camera } = makeScene();
<add> const radius = .8;
<add> const widthSegments = 4;
<add> const heightSegments = 2;
<add> const geometry = new THREE.SphereBufferGeometry(radius, widthSegments, heightSegments);
<add> const material = new THREE.MeshPhongMaterial({
<add> color: 'blue',
<add> flatShading: true,
<add> });
<add> const mesh = new THREE.Mesh(geometry, material);
<add> scene.add(mesh);
<add> return (time, rect) => {
<add> mesh.rotation.y = time * .1;
<add> camera.aspect = rect.width / rect.height;
<add> camera.updateProjectionMatrix();
<add> renderer.render(scene, camera);
<add> };
<add> },
<add>};
<add>```
<add>
<add>그리고 `querySelectorAll`로 가상 요소를 전부 불러와 해당 요소에 상응하는 렌더링 함수를
<add>실행합니다.
<add>
<add>```js
<add>document.querySelectorAll('[data-diagram]').forEach((elem) => {
<add> const sceneName = elem.dataset.diagram;
<add> const sceneInitFunction = sceneInitFunctionsByName[sceneName];
<add> const sceneRenderFunction = sceneInitFunction(elem);
<add> addScene(elem, sceneRenderFunction);
<add>});
<add>```
<add>
<add>이제 코드를 확장하기가 한결 편해졌습니다.
<add>
<add>{{{examples url="../threejs-multiple-scenes-selector.html" }}}
<add>
<add>## 각 요소에 액션 추가하기
<add>
<add>사용자 액션, 예를 들어 `TrackballControls`를 추가하는 건 아주 간단합니다. 먼저 스크립트를
<add>불러옵니다.
<add>
<add>```js
<add>import { TrackballControls } from './resources/threejs/r115/examples/jsm/controls/TrackballControls.js';
<add>```
<add>
<add>그리고 각 장면에 대응하는 요소에 `TrackballControls`를 추가합니다.
<add>
<add>```js
<add>-function makeScene() {
<add>+function makeScene(elem) {
<add> const scene = new THREE.Scene();
<add>
<add> const fov = 45;
<add> const aspect = 2; // 캔버스 기본값
<add> const near = 0.1;
<add> const far = 5;
<add> const camera = new THREE.PerspectiveCamera(fov, aspect, near, far);
<add> camera.position.set(0, 1, 2);
<add> camera.lookAt(0, 0, 0);
<add>+ scene.add(camera);
<add>
<add>+ const controls = new TrackballControls(camera, elem);
<add>+ controls.noZoom = true;
<add>+ controls.noPan = true;
<add>
<add> {
<add> const color = 0xFFFFFF;
<add> const intensity = 1;
<add> const light = new THREE.DirectionalLight(color, intensity);
<add> light.position.set(-1, 2, 4);
<add>- scene.add(light);
<add>+ camera.add(light);
<add> }
<add>
<add>- return { scene, camera };
<add>+ return { scene, camera, controls };
<add>}
<add>```
<add>
<add>위 코드에서는 카메라를 장면에 추가하고, 카메라에 조명을 추가했습니다. 이러면 조명이 카메라를
<add>따라다니겠죠. `TrackballControls`는 카메라를 조정하기 때문에 이렇게 해야 빛이 계속 우리가
<add>바라보는 방향에서 나갑니다.
<add>
<add>또한 컨트롤을 렌더링 함수에서 업데이트해줘야 합니다.
<add>
<add>```js
<add>const sceneInitFunctionsByName = {
<add>- 'box': () => {
<add>- const {scene, camera} = makeScene();
<add>+ 'box': (elem) => {
<add>+ const { scene, camera, controls } = makeScene(elem);
<add> const geometry = new THREE.BoxBufferGeometry(1, 1, 1);
<add> const material = new THREE.MeshPhongMaterial({color: 'red'});
<add> const mesh = new THREE.Mesh(geometry, material);
<add> scene.add(mesh);
<add> return (time, rect) => {
<add> mesh.rotation.y = time * .1;
<add> camera.aspect = rect.width / rect.height;
<add> camera.updateProjectionMatrix();
<add>+ controls.handleResize();
<add>+ controls.update();
<add> renderer.render(scene, camera);
<add> };
<add> },
<add>- 'pyramid': () => {
<add>- const { scene, camera } = makeScene();
<add>+ 'pyramid': (elem) => {
<add>+ const { scene, camera, controls } = makeScene(elem);
<add> const radius = .8;
<add> const widthSegments = 4;
<add> const heightSegments = 2;
<add> const geometry = new THREE.SphereBufferGeometry(radius, widthSegments, heightSegments);
<add> const material = new THREE.MeshPhongMaterial({
<add> color: 'blue',
<add> flatShading: true,
<add> });
<add> const mesh = new THREE.Mesh(geometry, material);
<add> scene.add(mesh);
<add> return (time, rect) => {
<add> mesh.rotation.y = time * .1;
<add> camera.aspect = rect.width / rect.height;
<add> camera.updateProjectionMatrix();
<add>+ controls.handleResize();
<add>+ controls.update();
<add> renderer.render(scene, camera);
<add> };
<add> },
<add>};
<add>```
<add>
<add>이제 각 물체를 자유롭게 회전시킬 수 있습니다.
<add>
<add>{{{example url="../threejs-multiple-scenes-controls.html" }}}
<add>
<add>이 기법은 이 사이트 전체에 사용한 기법입니다. [원시 모델에 관한 글](threejs-primitives.html)과
<add>[재질에 관한 글](threejs-materials.html)에서 다양한 예시를 보여주기 위해 사용했죠.
<add>
<add>다른 방법으로는 화면 밖의 캔버스에서 장면을 렌더링해 각 요소에 2D 캔버스 형태로 넘겨주는
<add>방법이 있습니다. 이 방법의 장점은 각 영역을 어떻게 분리할지 고민하지 않아도 된다는 것이죠.
<add>위에서 살펴본 방법은 캔버스를 화면 전체의 배경으로 써야 하지만, 이 방법은 일반 HTML 형태로
<add>사용할 수 있습니다.
<add>
<add>하지만 이 방법은 각 영역을 복사하는 것이기에 성능이 더 느립니다. 얼마나 느릴지는 브라우저와
<add>GPU 성능에 따라 다르죠.
<add>
<add>바꿔야 하는 건 생각보다 많지 않습니다.
<add>
<add>먼저 배경에서 캔버스 요소를 제거합니다.
<add>
<add>```html
<add><body>
<add>- <canvas id="c"></canvas>
<add> ...
<add></body>
<add>```
<add>
<add>CSS도 바꿔줍니다.
<add>
<add>```css
<add>-#c {
<add>- position: absolute;
<add>- left: 0;
<add>- top: 0;
<add>- width: 100vw;
<add>- height: 100vh;
<add>- display: block;
<add>- z-index: -1;
<add>-}
<add>canvas {
<add> width: 100%;
<add> height: 100%;
<add> display: block;
<add>}
<add>*[data-diagram] {
<add> display: inline-block;
<add> width: 5em;
<add> height: 3em;
<add>}
<add>```
<add>
<add>캔버스 요소가 부모에 꽉 차도록 변경했습니다.
<add>
<add>이제 자바스크립트를 변경해봅시다. 먼저 캔버스를 참조할 필요가 없으니 대신 캔버스 요소를
<add>새로 만듭니다. 또한 가위 테스트를 처음에 활성화합니다.
<add>
<add>```js
<add>function main() {
<add>- const canvas = document.querySelector('#c');
<add>+ const canvas = document.createElement('canvas');
<add> const renderer = new THREE.WebGLRenderer({canvas, alpha: true});
<add>+ renderer.setScissorTest(true);
<add>
<add> ...
<add>```
<add>
<add>다음으로 각 장면에 2D 렌더링 컨텍스트를 생성하고 장면에 대응하는 요소에 캔버스를 추가합니다.
<add>
<add>```js
<add>const sceneElements = [];
<add>function addScene(elem, fn) {
<add>+ const ctx = document.createElement('canvas').getContext('2d');
<add>+ elem.appendChild(ctx.canvas);
<add>- sceneElements.push({ elem, fn });
<add>+ sceneElements.push({ elem, ctx, fn });
<add>}
<add>```
<add>
<add>만약 렌더링 시 렌더링용 캔버스의 크기가 장면의 크기보다 작을 경우, 렌더링용 캔버스의 크기를
<add>키웁니다. 또한 2D 캔버스의 크기가 부모 요소와 다르다면 2D 캔버스의 크기를 조정합니다. 마지막으로
<add>가위와 화면을 설정하고, 해당 장면을 렌더링한 뒤, 요소의 캔버스로 렌더링 결과물을 복사합니다.
<add>
<add>```js
<add>function render(time) {
<add> time *= 0.001;
<add>
<add>- resizeRendererToDisplaySize(renderer);
<add>-
<add>- renderer.setScissorTest(false);
<add>- renderer.setClearColor(clearColor, 0);
<add>- renderer.clear(true, true);
<add>- renderer.setScissorTest(true);
<add>-
<add>- const transform = `translateY(${ window.scrollY }px)`;
<add>- renderer.domElement.style.transform = transform;
<add>
<add>- for (const { elem, fn } of sceneElements) {
<add>+ for (const { elem, fn, ctx } of sceneElements) {
<add> // 해당 요소의 화면 대비 좌표를 가져옵니다
<add> const rect = elem.getBoundingClientRect();
<add> const { left, right, top, bottom, width, height } = rect;
<add>+ const rendererCanvas = renderer.domElement;
<add>
<add> const isOffscreen =
<add> bottom < 0 ||
<add>- top > renderer.domElement.clientHeight ||
<add>+ top > window.innerHeight ||
<add> right < 0 ||
<add>- left > renderer.domElement.clientWidth;
<add>+ left > window.innerWidth;
<add>
<add> if (!isOffscreen) {
<add>- const positiveYUpBottom = renderer.domElement.clientHeight - bottom;
<add>- renderer.setScissor(left, positiveYUpBottom, width, height);
<add>- renderer.setViewport(left, positiveYUpBottom, width, height);
<add>
<add>+ // 렌더링용 캔버스 크기 조정
<add>+ if (rendererCanvas.width < width || rendererCanvas.height < height) {
<add>+ renderer.setSize(width, height, false);
<add>+ }
<add>+
<add>+ // 2D 캔버스의 크기가 요소의 크기와 같도록 조정
<add>+ if (ctx.canvas.width !== width || ctx.canvas.height !== height) {
<add>+ ctx.canvas.width = width;
<add>+ ctx.canvas.height = height;
<add>+ }
<add>+
<add>+ renderer.setScissor(0, 0, width, height);
<add>+ renderer.setViewport(0, 0, width, height);
<add>
<add> fn(time, rect);
<add>
<add>+ // 렌더링된 장면을 2D 캔버스에 복사
<add>+ ctx.globalCompositeOperation = 'copy';
<add>+ ctx.drawImage(
<add>+ rendererCanvas,
<add>+ 0, rendererCanvas.height - height, width, height, // 원본 사각 좌표
<add>+ 0, 0, width, height); // 결과물 사각 좌표
<add> }
<add> }
<add>
<add> requestAnimationFrame(render);
<add>}
<add>```
<add>
<add>결과물은 위와 다르지 않습니다.
<add>
<add>{{{example url="../threejs-multiple-scenes-copy-canvas.html" }}}
<add>
<add>이 기법의 다른 장점은 [`OffscreenCanvas`](https://developer.mozilla.org/ko/docs/Web/API/OffscreenCanvas)
<add>웹 워커를 이용해 이 기능을 별도 스레드에서 구현할 수 있다는 겁니다. 하지만 아쉽게도
<add>2020년 7월을 기준으로 `OffscreenCanvas`는 아직 크로미움 기반 브라우저에서만 지원합니다.
<ide>\ No newline at end of file
<ide><path>threejs/lessons/kr/threejs-picking.md
<add>Title: Three.js 피킹(Picking)
<add>Description: Three.js에서 마우스로 요소를 선택하는 법을 알아봅니다
<add>TOC: 물체를 마우스로 피킹하기
<add>
<add>*피킹(picking)*이란 사용자가 클릭 또는 터치한 물체를 가려내는 작업을 말합니다. 피킹을 구현하는 방법은 수없이 많지만, 각자 단점이 있습니다. 이 글에서는 이 방법 중 흔히 사용하는 2가지 방법만 살펴보겠습니다.
<add>
<add>아마 *피킹*을 구현하는 가장 흔한 방법은 광선 투사(ray casting)일 겁니다. 광선 투사란 포인터(커서)에서 장면의 절두체로 광선을 쏴 광선이 닿는 물체를 감지하는 기법을 말하죠. 이론적으로 가장 간단한 방법입니다.
<add>
<add>먼저 포인터의 좌표를 구한 뒤, 이 좌표를 카메라의 시선과 방향에 따라 3D 좌표로 변환합니다. 그리고 near 면에서 far 면까지의 광선을 구해 이 광선이 장면 안 각 물체의 삼각형과 교차하는지 확인합니다. 만약 장면 안에 1000개의 삼각형을 가진 물체가 1000개 있다면 백만 개의 삼각형을 일일이 확인해야 하는 셈이죠.
<add>
<add>이를 최적화하려면 몇 가지 방법을 시도해볼 수 있습니다. 하나는 먼저 물체를 감싼 경계(bounding) 좌표가 광선과 교차하는지 확인하고, 교차하지 않는다면 해당 물체의 삼각형을 확인하지 않는 것이죠.
<add>
<add>Three.js에는 이런 작업을 대신해주는 `RayCaster` 클래스가 있습니다.
<add>
<add>한번 물체 100개가 있는 장면을 만들어 여기서 피킹을 구현해봅시다. 예제는 [반응형 디자인](threejs-responsive.html)에서 썼던 예제를 가져와 사용하겠습니다.
<add>
<add>우선 카메라를 별도 `Object3D`의 자식으로 추가해 카메라가 셀카봉처럼 장면 주위를 돌 수 있도록 합니다.
<add>
<add>```js
<add>*const fov = 60;
<add>const aspect = 2; // 캔버스 기본값
<add>const near = 0.1;
<add>*const far = 200;
<add>const camera = new THREE.PerspectiveCamera(fov, aspect, near, far);
<add>*camera.position.z = 30;
<add>
<add>const scene = new THREE.Scene();
<add>+scene.background = new THREE.Color('white');
<add>
<add>+// 카메라를 봉(pole)에 추가합니다.
<add>+// 이러면 봉을 회전시켜 카메라가 장면 주위를 돌도록 할 수 있습니다
<add>+const cameraPole = new THREE.Object3D();
<add>+scene.add(cameraPole);
<add>+cameraPole.add(camera);
<add>```
<add>
<add>그리고 `render` 함수 안에서 카메라 봉을 돌립니다.
<add>
<add>```js
<add>cameraPole.rotation.y = time * .1;
<add>```
<add>
<add>또한 카메라에 조명을 추가해 조명이 카메라와 같이 움직이도록 합니다.
<add>
<add>```js
<add>-scene.add(light);
<add>+camera.add(light);
<add>```
<add>
<add>정육면체 100개의 위치, 방향, 크기를 무작위로 설정해 생성합니다.
<add>
<add>```js
<add>const boxWidth = 1;
<add>const boxHeight = 1;
<add>const boxDepth = 1;
<add>const geometry = new THREE.BoxGeometry(boxWidth, boxHeight, boxDepth);
<add>
<add>function rand(min, max) {
<add> if (max === undefined) {
<add> max = min;
<add> min = 0;
<add> }
<add> return min + (max - min) * Math.random();
<add>}
<add>
<add>function randomColor() {
<add> return `hsl(${ rand(360) | 0 }, ${ rand(50, 100) | 0 }%, 50%)`;
<add>}
<add>
<add>const numObjects = 100;
<add>for (let i = 0; i < numObjects; ++i) {
<add> const material = new THREE.MeshPhongMaterial({
<add> color: randomColor(),
<add> });
<add>
<add> const cube = new THREE.Mesh(geometry, material);
<add> scene.add(cube);
<add>
<add> cube.position.set(rand(-20, 20), rand(-20, 20), rand(-20, 20));
<add> cube.rotation.set(rand(Math.PI), rand(Math.PI), 0);
<add> cube.scale.set(rand(3, 6), rand(3, 6), rand(3, 6));
<add>}
<add>```
<add>
<add>이제 피킹을 구현해봅시다.
<add>
<add>피킹을 관리할 간단한 클래스를 만들겠습니다.
<add>
<add>```js
<add>class PickHelper {
<add> constructor() {
<add> this.raycaster = new THREE.Raycaster();
<add> this.pickedObject = null;
<add> this.pickedObjectSavedColor = 0;
<add> }
<add> pick(normalizedPosition, scene, camera, time) {
<add> // 이미 다른 물체를 피킹했다면 색을 복원합니다
<add> if (this.pickedObject) {
<add> this.pickedObject.material.emissive.setHex(this.pickedObjectSavedColor);
<add> this.pickedObject = undefined;
<add> }
<add>
<add> // 절두체 안에 광선을 쏩니다
<add> this.raycaster.setFromCamera(normalizedPosition, camera);
<add> // 광선과 교차하는 물체들을 배열로 만듭니다
<add> const intersectedObjects = this.raycaster.intersectObjects(scene.children);
<add> if (intersectedObjects.length) {
<add> // 첫 번째 물체가 제일 가까우므로 해당 물체를 고릅니다
<add> this.pickedObject = intersectedObjects[0].object;
<add> // 기존 색을 저장해둡니다
<add> this.pickedObjectSavedColor = this.pickedObject.material.emissive.getHex();
<add> // emissive 색을 빨강/노랑으로 빛나게 만듭니다
<add> this.pickedObject.material.emissive.setHex((time * 8) % 2 > 1 ? 0xFFFF00 : 0xFF0000);
<add> }
<add> }
<add>}
<add>```
<add>
<add>위 클래스는 먼저 `RayCaster` 인스턴스를 만들고 `pick` 메서드를 호출하면 장면에 광선을 쏠 수 있게 해줍니다. 그리고 광선에 맞는 요소가 있으면 해당 요소 중 가장 첫 번째 요소의 색을 변경합니다.
<add>
<add>사용자가 마우스를 눌렀을 때(down)만 이 함수가 작동하도록 할 수도 있지만, 예제에서는 마우스 포인터 아래의 있는 요소를 피킹하도록 하겠습니다. 이를 구현하려면 먼저 포인터를 추적해야 합니다.
<add>
<add>```js
<add>const pickPosition = { x: 0, y: 0 };
<add>clearPickPosition();
<add>
<add>...
<add>
<add>function getCanvasRelativePosition(event) {
<add> const rect = canvas.getBoundingClientRect();
<add> return {
<add> x: (event.clientX - rect.left) * canvas.width / rect.width,
<add> y: (event.clientY - rect.top ) * canvas.height / rect.height,
<add> };
<add>}
<add>
<add>function setPickPosition(event) {
<add> const pos = getCanvasRelativePosition(event);
<add> pickPosition.x = (pos.x / canvas.width ) * 2 - 1;
<add> pickPosition.y = (pos.y / canvas.height) * -2 + 1; // Y 축을 뒤집었음
<add>}
<add>
<add>function clearPickPosition() {
<add> /**
<add> * 마우스의 경우는 항상 위치가 있어 그다지 큰
<add> * 상관이 없지만, 터치 같은 경우 사용자가 손가락을
<add> * 떼면 피킹을 멈춰야 합니다. 지금은 일단 어떤 것도
<add> * 선택할 수 없는 값으로 지정해두었습니다
<add> **/
<add> pickPosition.x = -100000;
<add> pickPosition.y = -100000;
<add>}
<add>
<add>window.addEventListener('mousemove', setPickPosition);
<add>window.addEventListener('mouseout', clearPickPosition);
<add>window.addEventListener('mouseleave', clearPickPosition);
<add>```
<add>
<add>위 예제에서는 마우스의 좌표를 정규화(normalize)했습니다. 캔버스의 크기와 상관없이 왼쪽 끝이 -1, 오른쪽 끝이 +1인 벡터값이 필요하기 때문이죠. 마찬가지로 아래쪽 끝은 -1, 위쪽 끝은 +1입니다.
<add>
<add>모바일도 환경도 지원하기 위해 리스너를 더 추가하겠습니다.
<add>
<add>```js
<add>window.addEventListener('touchstart', (event) => {
<add> event.preventDefault(); // 스크롤 이벤트 방지
<add> setPickPosition(event.touches[0]);
<add>}, { passive: false });
<add>
<add>window.addEventListener('touchmove', (event) => {
<add> setPickPosition(event.touches[0]);
<add>});
<add>
<add>window.addEventListener('touchend', clearPickPosition);
<add>```
<add>
<add>마지막으로 `render` 함수에서 `PickHelper`의 `pick` 메서드를 호출합니다.
<add>
<add>```js
<add>+const pickHelper = new PickHelper();
<add>
<add>function render(time) {
<add> time *= 0.001; // 초 단위로 변환
<add>
<add> ...
<add>
<add>+ pickHelper.pick(pickPosition, scene, camera, time);
<add>
<add> renderer.render(scene, camera);
<add>
<add> ...
<add>```
<add>
<add>결과를 볼까요?
<add>
<add>{{{example url="../threejs-picking-raycaster.html" }}}
<add>
<add>딱히 문제는 없어 보입니다. 실제로 사용하는 경우도 대부분 문제 없이 잘 되겠지만, 이 방법에는 몇 가지 문제점이 있습니다.
<add>
<add>1. CPU의 자원을 사용한다
<add>
<add> 자바스크립트 엔진은 각 요소를 돌며 광선이 요소의 경계 좌표 안에 교차하는지 확인합니다. 만약 교차할 경우, 해당 요소의 삼각형을 전부 돌며 광선과 교차하는 삼각형이 있는지 확인합니다.
<add>
<add> 이 방식의 장점은 자바스크립트가 교차하는 지점을 정확히 계산해 해당 데이터를 넘겨줄 수 있다는 점입니다. 예를 들어 교차가 발생한 지점에 특정 표시를 할 수 있겠죠.
<add>
<add> 대신 CPU가 할 일이 더 늘어난다는 점이 단점입니다. 요소가 가진 삼각형이 많을수록 더 느려지겠죠.
<add>
<add>2. 특이한 방식의 쉐이더나 변이를 감지하지 못한다
<add>
<add> 만약 장면에서 geometry를 변형하는 쉐이더를 사용한다면, 자바스크립트는 이 변형을 감지하지 못하기에 잘못된 값을 내놓을 겁니다. 제가 테스트해본 결과 스킨이 적용된 요소에는 이 방법이 먹히지 않습니다.
<add>
<add>3. 요소의 투명한 구멍을 처리하지 못한다.
<add>
<add>예제를 하나 만들어보죠. 아래와 같은 텍스처를 정육면체에 적용해봅시다.
<add>
<add><div class="threejs_center"><img class="checkerboard" src="../resources/images/frame.png"></div>
<add>
<add>그다지 추가할 건 많지 않습니다.
<add>
<add>```js
<add>+const loader = new THREE.TextureLoader();
<add>+const texture = loader.load('resources/images/frame.png');
<add>
<add>const numObjects = 100;
<add>for (let i = 0; i < numObjects; ++i) {
<add> const material = new THREE.MeshPhongMaterial({
<add> color: randomColor(),
<add> +map: texture,
<add> +transparent: true,
<add> +side: THREE.DoubleSide,
<add> +alphaTest: 0.1,
<add> });
<add>
<add> const cube = new THREE.Mesh(geometry, material);
<add> scene.add(cube);
<add>
<add> ...
<add>```
<add>
<add>예제를 실행시키면 바로 문제가 보일 겁니다.
<add>
<add>{{{example url="../threejs-picking-raycaster-transparency.html" }}}
<add>
<add>정육면체의 빈 공간을 통해 무언가를 선택할 수가 없죠.
<add>
<add><div class="threejs_center"><img src="resources/images/picking-transparent-issue.jpg" style="width: 635px;"></div>
<add>
<add>이는 자바스크립트가 텍스처나 재질을 보고 해당 요소가 투명한지 판단하기가 어렵기 때문입니다.
<add>
<add>이 문제를 해결하려면 GPU 기반 피킹을 구현해야 합니다. 이론적으로는 간단하지만 위에서 사용한 광선 투사법보다는 좀 더 복잡하죠.
<add>
<add>GPU 피킹을 구현하려면 각 요소를 별도의 화면에서 고유한 색상으로 렌더링해야 합니다. 그리고 포인터 아래에 있는 픽셀의 색을 가져와 해당 요소가 선택됐는지 확인하는 거죠.
<add>
<add>이러면 위에서 언급한 문제점 2, 3번이 해결됩니다. 1번, 성능의 경우는 상황에 따라 천차만별이죠. 눈에 보이는 화면을 위해 한 번, 피킹을 위해 한 번, 이렇게 매 요소를 총 두 번씩 렌더링해야 합니다. 더 복잡한 해결책을 쓰면 렌더링을 한 번만 할 수도 있지만, 이 글에서는 일단 더 간단한 방법을 사용하겠습니다.
<add>
<add>성능 최적화를 위해 시도할 수 있는 방법이 하나 있습니다. 어차피 픽셀을 하나만 읽을 것이니, 카메라를 픽셀 하나만 렌더링하도록 설정하는 것이죠. `PerspectiveCamera.setViewOffset` 메서드를 사용하면 카메라의 특정 부분만 렌더링하도록 할 수 있습니다. 이러면 성능 향상에 조금이나마 도움이 되겠죠.
<add>
<add>현재 Three.js에서 이 기법을 구현하려면 장면 2개를 사용해야 합니다. 하나는 기존 mesh를 그대로 쓰고, 나머지 하나는 피킹용 재질을 적용한 mesh를 쓸 겁니다.
<add>
<add>먼저 두 번째 장면을 추가하고 배경을 검정으로 지정합니다.
<add>
<add>```js
<add>const scene = new THREE.Scene();
<add>scene.background = new THREE.Color('white');
<add>const pickingScene = new THREE.Scene();
<add>pickingScene.background = new THREE.Color(0);
<add>```
<add>
<add>각 정육면체를 장면에 추가할 때 `pickingScene`의 같은 위치에 "피킹용 정육면체"를 추가합니다. 그리고 각 피킹용 정육면체에는 id로 쓸 고유 색상값을 지정한 뒤, 이 id 색상값으로 재질을 만들어 추가합니다. id 색상값을 정육면체의 키값으로 매핑해 놓으면 나중에 상응하는 정육면체를 바로 불러올 수 있겠죠.
<add>
<add>```js
<add>const idToObject = {};
<add>+const numObjects = 100;
<add>for (let i = 0; i < numObjects; ++i) {
<add>+ const id = i + 1;
<add> const material = new THREE.MeshPhongMaterial({
<add> color: randomColor(),
<add> map: texture,
<add> transparent: true,
<add> side: THREE.DoubleSide,
<add> alphaTest: 0.1,
<add> });
<add>
<add> const cube = new THREE.Mesh(geometry, material);
<add> scene.add(cube);
<add>+ idToObject[id] = cube;
<add>
<add> cube.position.set(rand(-20, 20), rand(-20, 20), rand(-20, 20));
<add> cube.rotation.set(rand(Math.PI), rand(Math.PI), 0);
<add> cube.scale.set(rand(3, 6), rand(3, 6), rand(3, 6));
<add>
<add>+ const pickingMaterial = new THREE.MeshPhongMaterial({
<add>+ emissive: new THREE.Color(id),
<add>+ color: new THREE.Color(0, 0, 0),
<add>+ specular: new THREE.Color(0, 0, 0),
<add>+ map: texture,
<add>+ transparent: true,
<add>+ side: THREE.DoubleSide,
<add>+ alphaTest: 0.5,
<add>+ blending: THREE.NoBlending,
<add>+ });
<add>+ const pickingCube = new THREE.Mesh(geometry, pickingMaterial);
<add>+ pickingScene.add(pickingCube);
<add>+ pickingCube.position.copy(cube.position);
<add>+ pickingCube.rotation.copy(cube.rotation);
<add>+ pickingCube.scale.copy(cube.scale);
<add>}
<add>```
<add>
<add>위 코드에서는 `MeshPhongMaterial`로 편법을 사용했습니다. `emissive` 속성을 id 색상값으로, `color`와 `specular` 속성을 0으로 설정하면 텍스처의 알파값이 `alphaTest`보다 큰 부분만 id 색상값으로 보이겠죠. 또 `blending` 속성을 `THREE.NoBlending`으로 설정해 id 색상값이 알파값의 영향을 받지 않도록 했습니다.
<add>
<add>제가 사용한 편법이 최적의 해결책은 아닙니다. 여러가지 옵션을 껐다고 해도 여전히 조명 관련 연산을 실행할 테니까요. 코드를 더 최적화하려면 `alphaTest` 값보다 높은 경우에만 id 색상을 렌더링하는 쉐이더를 직접 만들어야 합니다.
<add>
<add>광선 투사법을 쓸 때와 달리 픽셀을 하나만 사용하므로 위치값이 픽셀 하나만 가리키게 변경합니다.
<add>
<add>```js
<add>function setPickPosition(event) {
<add> const pos = getCanvasRelativePosition(event);
<add>- pickPosition.x = (pos.x / canvas.clientWidth ) * 2 - 1;
<add>- pickPosition.y = (pos.y / canvas.clientHeight) * -2 + 1; // Y 축을 뒤집었음
<add>+ pickPosition.x = pos.x;
<add>+ pickPosition.y = pos.y;
<add>}
<add>```
<add>
<add>`PickHelper` 클래스도 `GPUPickHelper`로 변경합니다. [렌더 타겟(render target)에 관한 글](threejs-rendertargets.html)에서 다룬 `WebGLRenderTarget`을 써 구현하되, 이번 렌더 타겟의 크기는 1x1, 1픽셀입니다.
<add>
<add>```js
<add>-class PickHelper {
<add>+class GPUPickHelper {
<add> constructor() {
<add>- this.raycaster = new THREE.Raycaster();
<add>+ // 1x1 픽셀 크기의 렌더 타겟을 생성합니다
<add>+ this.pickingTexture = new THREE.WebGLRenderTarget(1, 1);
<add>+ this.pixelBuffer = new Uint8Array(4);
<add> this.pickedObject = null;
<add> this.pickedObjectSavedColor = 0;
<add> }
<add> pick(cssPosition, scene, camera, time) {
<add>+ const {pickingTexture, pixelBuffer} = this;
<add>
<add> // 기존에 선택된 요소가 있는 경우 색을 복원합니다
<add> if (this.pickedObject) {
<add> this.pickedObject.material.emissive.setHex(this.pickedObjectSavedColor);
<add> this.pickedObject = undefined;
<add> }
<add>
<add>+ // view offset을 마우스 포인터 아래 1픽셀로 설정합니다
<add>+ const pixelRatio = renderer.getPixelRatio();
<add>+ camera.setViewOffset(
<add>+ renderer.getContext().drawingBufferWidth, // 전체 너비
<add>+ renderer.getContext().drawingBufferHeight, // 전체 높이
<add>+ cssPosition.x * pixelRatio | 0, // 사각 x 좌표
<add>+ cssPosition.y * pixelRatio | 0, // 사각 y 좌표
<add>+ 1, // 사각 좌표 width
<add>+ 1, // 사각 좌표 height
<add>+ );
<add>+ // 장면을 렌더링합니다
<add>+ renderer.setRenderTarget(pickingTexture)
<add>+ renderer.render(scene, camera);
<add>+ renderer.setRenderTarget(null);
<add>+
<add>+ // view offset을 정상으로 돌려 원래의 화면을 렌더링하도록 합니다
<add>+ camera.clearViewOffset();
<add>+ // 픽셀을 감지합니다
<add>+ renderer.readRenderTargetPixels(
<add>+ pickingTexture,
<add>+ 0, // x
<add>+ 0, // y
<add>+ 1, // width
<add>+ 1, // height
<add>+ pixelBuffer);
<add>+
<add>+ const id =
<add>+ (pixelBuffer[0] << 16) |
<add>+ (pixelBuffer[1] << 8) |
<add>+ (pixelBuffer[2] );
<add>
<add> // 절두체 안에 광선을 쏩니다
<add>- this.raycaster.setFromCamera(normalizedPosition, camera);
<add> // 광선과 교차하는 물체들을 배열로 만듭니다
<add>- const intersectedObjects = this.raycaster.intersectObjects(scene.children);
<add>- if (intersectedObjects.length) {
<add> // 첫 번째 물체가 제일 가까우므로 해당 물체를 고릅니다
<add>- this.pickedObject = intersectedObjects[0].object;
<add>
<add>+ const intersectedObject = idToObject[id];
<add>+ if (intersectedObject) {
<add> // 첫 번째 물체가 제일 가까우므로 해당 물체를 고릅니다
<add>+ this.pickedObject = intersectedObject;
<add> // 기존 색을 저장해둡니다
<add> this.pickedObjectSavedColor = this.pickedObject.material.emissive.getHex();
<add> // emissive 색을 빨강/노랑으로 빛나게 만듭니다
<add> this.pickedObject.material.emissive.setHex((time * 8) % 2 > 1 ? 0xFFFF00 : 0xFF0000);
<add> }
<add> }
<add>}
<add>```
<add>
<add>인스턴스를 만드는 쪽도 수정합니다.
<add>
<add>```js
<add>-const pickHelper = new PickHelper();
<add>+const pickHelper = new GPUPickHelper();
<add>```
<add>
<add>`pick` 메서드를 호출할 때 `scene` 대신 `pickScene`을 넘겨줍니다.
<add>
<add>```js
<add>- pickHelper.pick(pickPosition, scene, camera, time);
<add>+ pickHelper.pick(pickPosition, pickScene, camera, time);
<add>```
<add>
<add>이제 투명한 부분을 관통해 요소를 선택할 수 있습니다.
<add>
<add>{{{example url="../threejs-picking-gpu.html" }}}
<add>
<add>이 글이 피킹을 구현하는 데 도움이 되었으면 좋겠네요. 나중에 요소를 마우스로 조작하는 법에 대해서도 한 번 써보겠습니다.
<ide>\ No newline at end of file
<ide><path>threejs/lessons/kr/threejs-post-processing-3dlut.md
<add>Title: 3DLUT로 후처리하기
<add>Description: Three.js에서 3DLUT로 후처리하는 법을 알아봅니다
<add>TOC: LUT 파일로 후처리 효과 적용하기
<add>
<add>이전 글에서는 [후처리(Post processing)](threejs-post-processing.html)에 관해 알아보았습니다. 보통 후처리는 LUT 또는 3DLUT라고 부르기도 합니다. LUT는 룩업 테이블(Look-Up Table, 순람표)의 줄임말이고, 3DLUT는 3차원 룩업 테이블의 줄임말입니다.
<add>
<add>3DLUT는 2D 이미지를 특정한 색상 정육면체를 매핑한다고 생각하면 쉽습니다. 먼저 원본 이미지의 색상을 정육면체의 인덱스 값과 매칭시킵니다. 원본 이미지의 픽셀 하나당 해당 픽셀 색상의 빨강(red), 초록(green), 파랑(blue) 값을 이용해 정육면체의 특정 지점을 가리키는(look-up) 3D 벡터 인덱스를 만드는 것이죠. 이 인덱스를 통해 3DLUT에서 뽑아낸 값을 새로운 색으로 사용하는 겁니다.
<add>
<add>자바스크립트의 경우 아래처럼 구현할 수 있습니다. RGB 각 색상값을 0부터 255의 정수로 표현한 3차원 256x256x256 배열로 룩업 테이블을 구현하고, 이 룩업 테이블에서 RGB 색상값을 이용해 새로운 색상값을 선택하는 거죠.
<add>
<add>```js
<add>const newColor = lut[origColor.red][origColor.green][origColor.blue]
<add>```
<add>
<add>물론 256x256x256 배열은 큰 배열입니다. [텍스처에 관한 글](threejs-textures.html)에서 배웠듯 텍스처는 크기에 상관 없이 0.0에서 1.0로 값을 지정합니다.
<add>
<add>8x8x8 정육면체를 예로 들어보죠.
<add>
<add><div class="threejs_center"><img src="resources/images/3dlut-rgb.svg" class="noinvertdark" style="width: 500px"></div>
<add>
<add>먼저 0,0,0 부분을 검정색으로 채웁니다. 맞은편의 1,1,1 부분은 하얀색, 1,0,0 부분은 <span style="color:red;">빨강</span>, 0,1,0은 <span style="color:green;">초록</span>, 0,0,1은 <span style="color:blue;">파랑</span>으로 채웁니다.
<add>
<add><div class="threejs_center"><img src="resources/images/3dlut-axis.svg" class="noinvertdark" style="width: 500px"></div>
<add>
<add>그리고 각 축을 따라 색을 채워넣습니다.
<add>
<add><div class="threejs_center"><img src="resources/images/3dlut-edges.svg" class="noinvertdark" style="width: 500px"></div>
<add>
<add>빈 모서리를 2개 이상의 색상 채널을 사용하는 색으로 채웁니다(초록 + 빨강, 파랑 + 빨강 등).
<add>
<add><div class="threejs_center"><img src="resources/images/3dlut-standard.svg" class="noinvertdark" style="width: 500px"></div>
<add>
<add>마지막으로 빈 공간을 채웁니다. 이 형태가 3DLUT 기본 구조입니다. 지금은 효과를 주기 전과 후의 차이가 없습니다. 색상값을 인덱스로 사용해 새로운 색상값을 선택하면, 정확히 같은 색상값이 나오기 때문이죠.
<add>
<add><div class="threejs_center"><object type="image/svg+xml" data="resources/images/3dlut-standard-lookup.svg" class="noinvertdark" data-diagram="lookup" style="width: 600px"></object></div>
<add>
<add>이 정육면체를 호박색 쉐이드로 바꾸면 같은 인덱스를 참조하지만 전혀 다른 결과가 나옵니다.
<add>
<add><div class="threejs_center"><object type="image/svg+xml" data="resources/images/3dlut-amber-lookup.svg" class="noinvertdark" data-diagram="lookup" style="width: 600px"></object></div>
<add>
<add>이 기법을 사용하면 룩업 테이블을 교체하는 것으로 많은 효과를 구현할 수 있습니다. 색상 계산 기반의 효과는 대부분 하나의 색상값만을 사용합니다. 색상, 대비, 채도, 컬러 캐스트(color cast), 틴트(tint), 밝기, 노출도, 레벨, 커브, 포스터화, 그림자, 강조, 등 거의 모든 효과를 색상값 계산을 기반으로 구현하죠. 또 이 모든 효과를 하나의 룩업 테이블로 합칠 수도 있습니다.
<add>
<add>룩업 테이블을 사용하려면 먼저 적용할 장면이 필요하니 간단한 장면을 하나 만들어보겠습니다. [glTF 불러오기](threejs-load-gltf.html)에서 배웠듯 glTF 파일을 불러와 사용하겠습니다. 예제에 사용할 모델은 [The Ice Wolves](https://sketchfab.com/sarath.irn.kat005)의 [작품](https://sketchfab.com/models/a1d315908e9f45e5a3bc618bdfd2e7ee)입니다.
<add>
<add>[배경과 하늘 상자](threejs-backgrounds.html)에서 배웠던 대로 배경도 추가하겠습니다.
<add>
<add>{{{example url="../threejs-postprocessing-3dlut-prep.html" }}}
<add>
<add>이제 장면을 구현했으니 3DLUT를 만들어야 합니다. 가장 간단한 3DLUT는 2x2x2 identity LUT로, 여기서 *identity(동일한)*은 아무런 변화도 없음을 의미합니다. 1을 곱하거나 아무것도 안 하는 경우와 같죠. LUT 안의 색상값을 사용한다고 해도 입력된 값과 정확히 같은 값을 반환할 테니까요.
<add>
<add><div class="threejs_center"><img src="resources/images/3dlut-standard-2x2.svg" class="noinvertdark" style="width: 200px"></div>
<add>
<add>WebGL1은 3D 텍스쳐를 지원하지 않습니다. 따라서 3D 텍스처를 썰어 펼쳐 놓은 형태의 4x2짜리 2D 텍스처를 대신 사용하겠습니다.
<add>
<add>아래는 4x2 2D 텍스처로 identity LUT를 구현한 것입니다.
<add>
<add>```js
<add>const makeIdentityLutTexture = function() {
<add> const identityLUT = new Uint8Array([
<add> 0, 0, 0, 255, // black
<add> 255, 0, 0, 255, // red
<add> 0, 0, 255, 255, // blue
<add> 255, 0, 255, 255, // magenta
<add> 0, 255, 0, 255, // green
<add> 255, 255, 0, 255, // yellow
<add> 0, 255, 255, 255, // cyan
<add> 255, 255, 255, 255, // white
<add> ]);
<add>
<add> return function(filter) {
<add> const texture = new THREE.DataTexture(identityLUT, 4, 2, THREE.RGBAFormat);
<add> texture.minFilter = filter;
<add> texture.magFilter = filter;
<add> texture.needsUpdate = true;
<add> texture.flipY = false;
<add> return texture;
<add> };
<add>}();
<add>```
<add>
<add>필터가 들어간 것, 안 들어간 것 총 2개를 만들겠습니다.
<add>
<add>```js
<add>const lutTextures = [
<add> { name: 'identity', size: 2, texture: makeIdentityLutTexture(THREE.LinearFilter) },
<add> { name: 'identity not filtered', size: 2, texture: makeIdentityLutTexture(THREE.NearestFilter) },
<add>];
<add>```
<add>
<add>[후처리에 관한 글](threejs-post-processing.html)에서 작성했던 코드를 가져와 이 쉐이더들을 대신 쓰도록 합니다.
<add>
<add>```js
<add>const lutShader = {
<add> uniforms: {
<add> tDiffuse: { value: null },
<add> lutMap: { value: null },
<add> lutMapSize: { value: 1, },
<add> },
<add> vertexShader: `
<add> varying vec2 vUv;
<add> void main() {
<add> vUv = uv;
<add> gl_Position = projectionMatrix * modelViewMatrix * vec4( position, 1.0 );
<add> }
<add> `,
<add> fragmentShader: `
<add> #include <common>
<add>
<add> #define FILTER_LUT true
<add>
<add> uniform sampler2D tDiffuse;
<add> uniform sampler2D lutMap;
<add> uniform float lutMapSize;
<add>
<add> varying vec2 vUv;
<add>
<add> vec4 sampleAs3DTexture(sampler2D tex, vec3 texCoord, float size) {
<add> float sliceSize = 1.0 / size; // space of 1 slice
<add> float slicePixelSize = sliceSize / size; // space of 1 pixel
<add> float width = size - 1.0;
<add> float sliceInnerSize = slicePixelSize * width; // space of size pixels
<add> float zSlice0 = floor( texCoord.z * width);
<add> float zSlice1 = min( zSlice0 + 1.0, width);
<add> float xOffset = slicePixelSize * 0.5 + texCoord.x * sliceInnerSize;
<add> float yRange = (texCoord.y * width + 0.5) / size;
<add> float s0 = xOffset + (zSlice0 * sliceSize);
<add>
<add> #ifdef FILTER_LUT
<add>
<add> float s1 = xOffset + (zSlice1 * sliceSize);
<add> vec4 slice0Color = texture2D(tex, vec2(s0, yRange));
<add> vec4 slice1Color = texture2D(tex, vec2(s1, yRange));
<add> float zOffset = mod(texCoord.z * width, 1.0);
<add> return mix(slice0Color, slice1Color, zOffset);
<add>
<add> #else
<add>
<add> return texture2D(tex, vec2( s0, yRange));
<add>
<add> #endif
<add> }
<add>
<add> void main() {
<add> vec4 originalColor = texture2D(tDiffuse, vUv);
<add> gl_FragColor = sampleAs3DTexture(lutMap, originalColor.xyz, lutMapSize);
<add> }
<add> `,
<add>};
<add>
<add>const lutNearestShader = {
<add> uniforms: Object.assign( {}, lutShader.uniforms ),
<add> vertexShader: lutShader.vertexShader,
<add> fragmentShader: lutShader.fragmentShader.replace('#define FILTER_LUT', '//'),
<add>};
<add>```
<add>
<add>fragment 쉐이더의 다음 코드는
<add>
<add>```glsl
<add>#define FILTER_LUT true
<add>```
<add>
<add>주석 처리했던 두 번째 쉐이더를 생성하기 위한 것입니다.
<add>
<add>그리고 각 쉐이더로 `Pass`를 만듭니다.
<add>
<add>```js
<add>const effectLUT = new THREE.ShaderPass(lutShader);
<add>effectLUT.renderToScreen = true;
<add>const effectLUTNearest = new THREE.ShaderPass(lutNearestShader);
<add>effectLUTNearest.renderToScreen = true;
<add>```
<add>
<add>기존에 배경과 glTF를 별도 장면으로 분리했으므로 각 장면의 `RenderPass`를 따로 생성합니다.
<add>
<add>```js
<add>const renderModel = new THREE.RenderPass(scene, camera);
<add>renderModel.clear = false; // 배경을 지우지 않도록 합니다
<add>const renderBG = new THREE.RenderPass(sceneBG, cameraBG);
<add>```
<add>
<add>다음으로 사용할 pass*를 `EffectComposer`에 추가합니다.
<add>
<add>※ 편의상 `Pass` 인스턴스를 pass로 번역합니다.
<add>
<add>```js
<add>const rtParameters = {
<add> minFilter: THREE.LinearFilter,
<add> magFilter: THREE.LinearFilter,
<add> format: THREE.RGBFormat,
<add>};
<add>const composer = new THREE.EffectComposer(renderer, new THREE.WebGLRenderTarget(1, 1, rtParameters));
<add>
<add>composer.addPass(renderBG);
<add>composer.addPass(renderModel);
<add>composer.addPass(effectLUT);
<add>composer.addPass(effectLUTNearest);
<add>```
<add>
<add>GUI를 만들어 LUT를 바꿀 수 있도록 합니다.
<add>
<add>```js
<add>const lutNameIndexMap = {};
<add>lutTextures.forEach((info, ndx) => {
<add> lutNameIndexMap[info.name] = ndx;
<add>});
<add>
<add>const lutSettings = {
<add> lut: lutNameIndexMap.identity,
<add>};
<add>const gui = new GUI({ width: 300 });
<add>gui.add(lutSettings, 'lut', lutNameIndexMap);
<add>```
<add>
<add>마지막으로 필터링 여부에 따라 효과가 바뀌도록 설정합니다. LUT가 선택한 텍스처를 사용하도록 하고, `EffectComposer`로 렌더링 합니다.
<add>
<add>```js
<add>const lutInfo = lutTextures[lutSettings.lut];
<add>
<add>const effect = lutInfo.filter ? effectLUT : effectLUTNearest;
<add>effectLUT.enabled = lutInfo.filter;
<add>effectLUTNearest.enabled = !lutInfo.filter;
<add>
<add>const lutTexture = lutInfo.texture;
<add>effect.uniforms.lutMap.value = lutTexture;
<add>effect.uniforms.lutMapSize.value = lutInfo.size;
<add>
<add>composer.render(delta);
<add>```
<add>
<add>identity 3DLUT를 선택했을 때는 아무런 변화가 없습니다.
<add>
<add>{{{example url="../threejs-postprocessing-3dlut-identity.html" }}}
<add>
<add>하지만 필터가 identity not filtered LUT를 선택하면 재미있는 결과가 나옵니다.
<add>
<add><div class="threejs_center"><img src="resources/images/unfiltered-3dlut.jpg" style="width: 500px"></div>
<add>
<add>왜 이런 결과가 나온 걸까요? 필터링을 사용할 경우(linear), GPU는 선형적으로 색상값을 채워넣습니다. 필터링을 사용하지 않을 경우(nearest), 알아서 색상값을 채워넣지 않기에 3DLUT에서(근처의) 색상값이 있는 곳을 찾아 사용하는 것이죠.
<add>
<add>어느정도 이해했다면 더 다양한 3DLUT를 만들어봅시다.
<add>
<add>먼저 룩업 테이블의 해상도를 정하고 간단한 코드를 만들어 룩업 테이블 정육면체의 각 면을 만들겠습니다.
<add>
<add>```js
<add>const ctx = document.querySelector('canvas').getContext('2d');
<add>
<add>function drawColorCubeImage(ctx, size) {
<add> const canvas = ctx.canvas;
<add> canvas.width = size * size;
<add> canvas.height = size;
<add>
<add> for (let zz = 0; zz < size; ++zz) {
<add> for (let yy = 0; yy < size; ++yy) {
<add> for (let xx = 0; xx < size; ++xx) {
<add> const r = Math.floor(xx / (size - 1) * 255);
<add> const g = Math.floor(yy / (size - 1) * 255);
<add> const b = Math.floor(zz / (size - 1) * 255);
<add> ctx.fillStyle = `rgb(${ r },${ g },${ b })`;
<add> ctx.fillRect(zz * size + xx, yy, 1, 1);
<add> }
<add> }
<add> }
<add> document.querySelector('#width').textContent = canvas.width;
<add> document.querySelector('#height').textContent = canvas.height;
<add>}
<add>
<add>drawColorCubeImage(ctx, 8);
<add>```
<add>
<add>캔버스 요소도 만듭니다.
<add>
<add>```html
<add><canvas></canvas>
<add>```
<add>
<add>이제 어떤 identity 3D 룩업 테이블이든 만들 수 있습니다.
<add>
<add>{{{example url="../3dlut-base-cube-maker.html" }}}
<add>
<add>해상도가 높을수록 더 세밀한 효과를 줄 수 있지만 정육면체형 데이터의 크기는 기하급수적으로 늘어납니다. 크기 8x8 정육면체는 2kb 정도지만 64x64 정육면체는 약 1mb나 되죠. 그러니 충분히 효과를 구현할 수 있는 만큼만 사용하는 게 좋습니다.
<add>
<add>사이즈를 16으로 설정하고 `Save...` 버튼을 클릭하면 아래와 같은 파일이 나옵니다.
<add>
<add><div class="threejs_center"><img src="resources/images/identity-lut-s16.png"></div>
<add>
<add>그리고 LUT를 적용할 화면을 캡쳐해야 합니다. 이 경우에는 이전에 만든 장면에 아무런 효과를 주지 않은 화면이겠죠. 대게 위 예제를 오른쪽 클릭해 "다른 이름으로 저장..."을 클릭하면 되지만, OS에 따라 마우스 우클릭이 동작하지 않을 수 있습니다. 제 경우 OS에 내장된 스크린샷 기능을 이용해 화면을 캡쳐했습니다*.
<add>
<add>※ Windows 10 RS5(레드스톤 5) 이상이라면 `Windows + Shift + S`를 눌러 화면을 캡쳐할 수 있습니다. 역주.
<add>
<add><div class="threejs_center"><img src="resources/images/3dlut-screen-capture.jpg" style="width: 600px"></div>
<add>
<add>캡쳐본을 이미지 에디터에서 불러옵니다. 저는 포토샵을 사용해 샘플 이미지를 불러오고, 한쪽 귀퉁이에 3DLUT를 붙여 넣었습니다.
<add>
<add>> 참고: 제 경우 포토샵에서 캡쳐본 위에 lut 파일을 불러오려고 했을 때 이미지가 두 배 더 커졌습니다. 아마 DPI를 맞추거나 하는 이유 때문에 그런 거겠죠. lut 파일을 별도 탭에 불러와 캡쳐본 위에 복사 붙여 넣기 하니 정상적으로 불러와지더군요.
<add>
<add><div class="threejs_center"><img src="resources/images/3dlut-photoshop-before.jpg" style="width: 600px"></div>
<add>
<add>그리고 이미지에 부여하고 싶은 색상 효과를 부여합니다. 포토샵의 경우 대부분의 효과는 이미지(Image)->조정(Adjustments) 메뉴에 있습니다.
<add>
<add><div class="threejs_center"><img src="resources/images/3dlut-photoshop-after.jpg" style="width: 600px"></div>
<add>
<add>색상을 조정하면 3DLUT 이미지에도 같은 효과가 적용될 겁니다.
<add>
<add>자 그럼 이제 이걸 어떻게 쓸 수 있을까요?
<add>
<add>먼저 저는 3DLUT 이미지를 `3dlut-red-only-s16.png`라는 이름으로 저장했습니다. 메모리를 아끼려면 이미지를 LUT 부분만 잘라 16x256로 맞추는 것이 좋지만, 그냥 재미삼아 이미지를 불러온 이후 자르겠습니다*. 이 방법의 장점은 귀찮게 이미지를 자르는 과정 없이 효과를 적용해보고 싶은 대로 바로바로 적용할 수 있다는 것이죠. 물론 대역폭을 낭비한다는 게 단점입니다.
<add>
<add>※ 포토샵 CC 이후 버젼을 사용한다면 레이어를 오른쪽 클릭해 `PNG로 빠르게 내보내기` 메뉴로 해당 그룹 또는 레이어만 .png 파일로 내보낼 수 있습니다. 이미지를 귀찮게 자르는 과정 없이 .png 파일을 바로 생성할 수 있죠. 역주.
<add>
<add>아래는 이미지를 불러오는 코드입니다. 실제 코드에서는 텍스처를 불러왔을 때 바로 사용할 수 있도록 identity lut를 먼저 만들었습니다. 그 다음 이미지를 불러와 3DLUT 부분만 캔버스에 복사하고, 캔버스에서 가져온 데이터를 텍스처에 지정합니다. 또한 텍스처가 바뀌었을 때 바로 적용하도록 `needsUpdate` 속성도 true로 설정합니다.
<add>
<add>```js
<add>const makeLUTTexture = function() {
<add> const imgLoader = new THREE.ImageLoader();
<add> const ctx = document.createElement('canvas').getContext('2d');
<add>
<add> return function(info) {
<add> const texture = makeIdentityLutTexture(
<add> info.filter ? THREE.LinearFilter : THREE.NearestFilter);
<add>
<add> if (info.url) {
<add> const lutSize = info.size;
<add>
<add> /**
<add> * 크기를 2(identity LUT의 크기)로 설정합니다. 이 크기는 나중에 이미지를
<add> * 불러온 뒤 복원합니다. 이러면 lut를 사용하는 코드는 이미지의 적용 여부를
<add> * 신경쓰지 않아도 됩니다.
<add> **/
<add> info.size = 2;
<add>
<add> imgLoader.load(info.url, function(image) {
<add> const width = lutSize * lutSize;
<add> const height = lutSize;
<add> info.size = lutSize;
<add> ctx.canvas.width = width;
<add> ctx.canvas.height = height;
<add> ctx.drawImage(image, 0, 0);
<add> const imageData = ctx.getImageData(0, 0, width, height);
<add>
<add> texture.image.data = new Uint8Array(imageData.data.buffer);
<add> texture.image.width = width;
<add> texture.image.height = height;
<add> texture.needsUpdate = true;
<add> });
<add> }
<add>
<add> return texture;
<add> };
<add>}();
<add>```
<add>
<add>기존 코드가 LUT png 파일을 사용하도록 수정합니다.
<add>
<add>```js
<add>const lutTextures = [
<add> { name: 'identity', size: 2, filter: true , },
<add> { name: 'identity no filter', size: 2, filter: false, },
<add>+ { name: 'custom', url: 'resources/images/lut/3dlut-red-only-s16.png' },
<add>];
<add>
<add>+lutTextures.forEach((info) => {
<add>+ // 사이즈값이 없다면 사이즈 정보를 파일 이름에서 가져옵니다.
<add>+ if (!info.size) {
<add>+ /**
<add>+ * 파일 이름이 '-s<숫자>[n]' 이렇게 끝난다고 가정합니다.
<add>+ * <숫자>는 3DLUT 정육면체의 크기입니다.
<add>+ * [n]은 '필터링 없음' 또는 'nearest'를 의미합니다.
<add>+ *
<add>+ * 예시:
<add>+ * 'foo-s16.png' = 크기:16, 필터: true
<add>+ * 'bar-s8n.png' = 크기:8, 필터: false
<add>+ **/
<add>+ const m = /-s(\d+)(n*)\.[^.]+$/.exec(info.url);
<add>+ if (m) {
<add>+ info.size = parseInt(m[1]);
<add>+ info.filter = info.filter === undefined ? m[2] !== 'n' : info.filter;
<add>+ }
<add>+ }
<add>+
<add>+ info.texture = makeLUTTexture(info);
<add>+});
<add>```
<add>
<add>위 코드가 LUT의 사이즈를 파일 이름에 인코딩한 예입니다. 이러면 png로 LUT를 바꾸기가 훨씬 쉽죠.
<add>
<add>그냥은 좀 심심하니 lut png 파일을 더 많이 만들어봅시다.
<add>
<add>```js
<add>const lutTextures = [
<add> { name: 'identity', size: 2, filter: true , },
<add> { name: 'identity no filter', size: 2, filter: false, },
<add> { name: 'custom', url: 'resources/images/lut/3dlut-red-only-s16.png' },
<add>+ { name: 'monochrome', url: 'resources/images/lut/monochrome-s8.png' },
<add>+ { name: 'sepia', url: 'resources/images/lut/sepia-s8.png' },
<add>+ { name: 'saturated', url: 'resources/images/lut/saturated-s8.png', },
<add>+ { name: 'posterize', url: 'resources/images/lut/posterize-s8n.png', },
<add>+ { name: 'posterize-3-rgb', url: 'resources/images/lut/posterize-3-rgb-s8n.png', },
<add>+ { name: 'posterize-3-lab', url: 'resources/images/lut/posterize-3-lab-s8n.png', },
<add>+ { name: 'posterize-4-lab', url: 'resources/images/lut/posterize-4-lab-s8n.png', },
<add>+ { name: 'posterize-more', url: 'resources/images/lut/posterize-more-s8n.png', },
<add>+ { name: 'inverse', url: 'resources/images/lut/inverse-s8.png', },
<add>+ { name: 'color negative', url: 'resources/images/lut/color-negative-s8.png', },
<add>+ { name: 'high contrast', url: 'resources/images/lut/high-contrast-bw-s8.png', },
<add>+ { name: 'funky contrast', url: 'resources/images/lut/funky-contrast-s8.png', },
<add>+ { name: 'nightvision', url: 'resources/images/lut/nightvision-s8.png', },
<add>+ { name: 'thermal', url: 'resources/images/lut/thermal-s8.png', },
<add>+ { name: 'b/w', url: 'resources/images/lut/black-white-s8n.png', },
<add>+ { name: 'hue +60', url: 'resources/images/lut/hue-plus-60-s8.png', },
<add>+ { name: 'hue +180', url: 'resources/images/lut/hue-plus-180-s8.png', },
<add>+ { name: 'hue -60', url: 'resources/images/lut/hue-minus-60-s8.png', },
<add>+ { name: 'red to cyan', url: 'resources/images/lut/red-to-cyan-s8.png' },
<add>+ { name: 'blues', url: 'resources/images/lut/blues-s8.png' },
<add>+ { name: 'infrared', url: 'resources/images/lut/infrared-s8.png' },
<add>+ { name: 'radioactive', url: 'resources/images/lut/radioactive-s8.png' },
<add>+ { name: 'goolgey', url: 'resources/images/lut/googley-s8.png' },
<add>+ { name: 'bgy', url: 'resources/images/lut/bgy-s8.png' },
<add>];
<add>```
<add>
<add>아래 예제에서 여러 lut를 시험해볼 수 있습니다.
<add>
<add>{{{example url="../threejs-postprocessing-3dlut.html" }}}
<add>
<add>추가로 한 가지 덧붙이겠습니다. 인터넷을 뒤져보니 Adobe에서 만든 표준 LUT 형식이 있더군요. [인터넷에서 검색](https://www.google.com/search?q=lut+files)해보면 이런 LUT 형식의 파일을 쉽게 찾을 수 있을 겁니다.
<add>
<add>이를 기반으로 간단하게 로더를 작성했습니다. 총 4가지 형식이 있다고는 하나, 제가 찾은 형식은 하나뿐이라 모든 형식에서 테스트하진 못했습니다.
<add>
<add>여기에 간단한 드래그-앤-드롭 라이브러리도 만들었습니다. 이 두 라이브러리를 이용해 여러분이 직접 LUT 파일을 적용할 수 있도록 말이죠.
<add>
<add>먼저 앞서 만든 두 라이브러리를 불러온 뒤
<add>
<add>```js
<add>import * as lutParser from './resources/lut-reader.js';
<add>import * as dragAndDrop from './resources/drag-and-drop.js';
<add>```
<add>
<add>아래처럼 사용합니다.
<add>
<add>```js
<add>dragAndDrop.setup({ msg: 'Drop LUT File here' });
<add>dragAndDrop.onDropFile(readLUTFile);
<add>
<add>function readLUTFile(file) {
<add> const reader = new FileReader();
<add> reader.onload = (e) => {
<add> const lut = lutParser.lutTo2D3Drgb8(lutParser.parse(e.target.result));
<add> const {size, data, name} = lut;
<add> const texture = new THREE.DataTexture(data, size * size, size, THREE.RGBFormat);
<add> texture.minFilter = THREE.LinearFilter;
<add> texture.needsUpdate = true;
<add> texture.flipY = false;
<add> const lutTexture = {
<add> name: (name && name.toLowerCase().trim() !== 'untitled')
<add> ? name
<add> : file.name,
<add> size: size,
<add> filter: true,
<add> texture,
<add> };
<add> lutTextures.push(lutTexture);
<add> lutSettings.lut = lutTextures.length - 1;
<add> updateGUI();
<add> };
<add>
<add> reader.readAsText(file);
<add>}
<add>```
<add>
<add>GUI가 새로 불러온 파일을 반영하도록 코드를 추가합니다.
<add>
<add>```js
<add>const lutSettings = {
<add> lut: lutNameIndexMap.thermal,
<add>};
<add>const gui = new GUI({ width: 300 });
<add>gui.addFolder('Choose LUT or Drag&Drop LUT File(s)');
<add>
<add>let lutGUI;
<add>function updateGUI() {
<add> makeLutNameIndexMap();
<add> if (lutGUI) {
<add> gui.remove(lutGUI);
<add> }
<add> lutGUI = gui.add(lutSettings, 'lut', lutNameIndexMap);
<add>}
<add>updateGUI();
<add>```
<add>
<add>이제 [Adobe LUT 파일](https://www.google.com/search?q=lut+files)을 다운해 아래 예제에 드래그-앤-드롭으로 불러올 수 있을 겁니다.
<add>
<add>{{{example url="../threejs-postprocessing-3dlut-w-loader.html" }}}
<add>
<add>다만 Adobe LUT는 온라인 환경에 최적화되지 않았습니다. 파일 용량이 꽤 큰 편이죠. 아래 예제를 사용하면 용량을 좀 더 줄일 수 있습니다. 드래그-앤-드롭으로 파일을 불러오고 크기를 선택한 뒤 "Save..." 버튼을 클릭하면 되죠.
<add>
<add>아래 예제는 단순히 위에서 썼던 예제를 조금 수정한 것입니다. glFT 파일 없이 배경만 렌더링한 것이죠. 배경 이미지는 아까 본 스크립트로 만든 identity lut 이미지입니다. 여기에 LUT 파일을 불러와 해당 LUT 파일을 PNG로 만드는 데 사용하는 것이죠.
<add>
<add>{{{example url="../threejs-postprocessing-adobe-lut-to-png-converter.html" }}}
<add>
<add>이 글에서는 쉐이더가 어떻게 작동하는지에 대해서는 아예 설명하지 않았습니다. 나중에 GLSL에 대해 더 다룰 기회가 있었으면 좋겠네요. 쉐이더의 작동 방식을 알고 싶다면 [후처리에 관한 글](threejs-post-processing.html)에 있는 링크 또는 [이 유튜브 영상](https://www.youtube.com/watch?v=rfQ8rKGTVlg#t=24m30s)을 참고하기 바랍니다.
<add>
<add><script type="module" src="../resources/threejs-post-processing-3dlut.js"></script>
<ide><path>threejs/lessons/kr/threejs-post-processing.md
<add>Title: Three.js 후처리
<add>Description: Three.js로 후처리하는 법을 알아봅니다
<add>TOC: 후처리
<add>
<add>*후처리(post processing)*란 보통 2D 이미지에 어떤 효과나 필터를 넣는 것을 의미합니다. Three.js는 다양한 mesh로 이루어진 장면을 2D 이미지로 렌더링하죠. 일반적으로 이 이미지는 바로 캔버스를 통해 브라우저 화면에 렌더링됩니다. 하지만 대신 이 이미지를 [렌더 타겟에 렌더링하고](threejs-rendertargets.html) 캔버스에 보내기 전 임의의 *후처리* 효과를 줄 수 있습니다.
<add>
<add>인스타그램 필터, 포토샵 필터 등이 후처리의 좋은 예이죠.
<add>
<add>Three.js에는 후처리를 순차적으로 처리해주는 모범 클래스가 있습니다. 일단 `EffectComposer`의 인스턴스를 만들고 여기에 `Pass` 객체(효과, 필터)들을 추가합니다. 그리고 `EffectComposer.render` 메서드를 호출하면 현재 장면을 [렌더 타겟](threejs-rendertargets.html)에 렌더링한 뒤 각 pass*를 순서대로 적용합니다.
<add>
<add>※ 편의상 `Pass` 인스턴스를 pass로 번역합니다.
<add>
<add>이 pass는 비넷(vignette), 흐림(blur), 블룸(bloom), 필름 그레인(film grain) 효과 또는 hue, 채도(saturation), 대비(contrast) 조정 등의 후처리 효과로, 이 효과를 모두 적용한 결과물을 최종적으로 캔버스에 렌더링합니다.
<add>
<add>여기서 어느 정도 `EffectComposer`의 원리를 이해할 필요가 있습니다. `EffectComposer`는 두 개의 [렌더 타겟](threejs-rendertargets.html)을 사용합니다. 편의상 이 둘을 **rtA**, **rtB**라고 부르도록 하죠.
<add>
<add>`EffectComposer.addPass`를 각 pass를 적용할 순서대로 호출하고 `EffectComposer.render`를 호출하면 pass*는 아래 그림과 같은 순서로 적용됩니다.
<add>
<add><div class="threejs_center"><img src="resources/images/threejs-postprocessing.svg" style="width: 600px"></div>
<add>
<add>먼저 `RenderPass`에 넘긴 장면을 **rtA**에 렌더링합니다. 그리고 **rtA**를 다음 pass에 넘겨주면 해당 pass는 **rtA**에 pass를 적용한 결과를 **rtB**에 렌더링합니다. 그런 다음 **rtB**를 다음 pass로 넘겨 적용한 결과를 **rtA**에, **rtA**에 pass를 적용한 결과를 다시 **rtB**에, 이런 식으로 모든 pass가 끝날 때까지 계속 반복합니다.
<add>
<add>`Pass`에는 공통적으로 4가지 옵션이 있습니다.
<add>
<add>## `enabled`
<add>
<add>이 pass를 사용할지의 여부입니다.
<add>
<add>## `needsSwap`
<add>
<add>이 pass를 적용한 후 `rtA`와 `rtB`를 바꿀지의 여부입니다.
<add>
<add>## `clear`
<add>
<add>이 pass를 적용하기 전에 화면을 초기화할지의 여부입니다.
<add>
<add>## `renderToScreen`
<add>
<add>지정한 렌더 타겟이 아닌 캔버스에 렌더링할지의 여부입니다. 보통 `EffectComposer`에 추가하는 마지막 pass에 이 옵션을 true로 설정합니다.
<add>
<add>간단한 예제를 만들어봅시다. [반응형 디자인에 관한 글](threejs-responsive.html)에서 썼던 예제를 가져오겠습니다.
<add>
<add>추가로 먼저 `EffectComposer` 인스턴스를 생성합니다.
<add>
<add>```js
<add>const composer = new EffectComposer(renderer);
<add>```
<add>
<add>다음으로 `RenderPass`를 첫 pass로 추가합니다. 이 pass는 넘겨 받은 장면을 첫 렌더 타겟에 렌더링할 겁니다.
<add>
<add>```js
<add>composer.addPass(new RenderPass(scene, camera));
<add>```
<add>
<add>다음으로 `BloomPass`를 추가합니다. `BloomPass`는 장면을 원래의 장면보다 작게 렌더링해 흐림(blur) 효과를 줍니다. 그리고 효과가 적용된 장면을 원래 장면에 덮어 씌우는 식으로 *블룸* 효과를 구현합니다.
<add>
<add>```js
<add>const bloomPass = new BloomPass(
<add> 1, // 강도
<add> 25, // 커널(kernel) 크기
<add> 4, // 시그마 ?
<add> 256, // 렌더 타겟의 해상도를 낮춤
<add>);
<add>composer.addPass(bloomPass);
<add>```
<add>
<add>마지막으로 원본 장면에 노이즈와 스캔라인(scanline)을 추가하는 `FilmPass`를 추가합니다.
<add>
<add>```js
<add>const filmPass = new FilmPass(
<add> 0.35, // 노이즈 강도
<add> 0.025, // 스캔라인 강도
<add> 648, // 스캔라인 개수
<add> false, // 흑백
<add>);
<add>filmPass.renderToScreen = true;
<add>composer.addPass(filmPass);
<add>```
<add>
<add>`filmPass`가 마지막 pass이기에 캔버스에 결과를 바로 렌더링하도록 `renderToScreen` 옵션을 true로 설정했습니다. 이 옵션을 설정하지 않으면 캔버스가 아닌 다음 렌더 타겟에 장면을 렌더링할 거예요.
<add>
<add>또 이 클래스들을 사용하기 위해 여러 스크립트를 불러와야 합니다.
<add>
<add>```js
<add>import { EffectComposer } from './resources/threejs/r115/examples/jsm/postprocessing/EffectComposer.js';
<add>import { RenderPass } from './resources/threejs/r115/examples/jsm/postprocessing/RenderPass.js';
<add>import { BloomPass } from './resources/threejs/r115/examples/jsm/postprocessing/BloomPass.js';
<add>import { FilmPass } from './resources/threejs/r115/examples/jsm/postprocessing/FilmPass.js';
<add>```
<add>
<add>대부분의 후처리에는 `EffectComposer.js`와 `RenderPass.js`가 필수입니다.
<add>
<add>이제 `WebGLRenderer.render` 대신 `EffectComposer.render`를 사용*하고* `EffectComposer`가 결과물을 캔버스의 크기에 맞추도록 해야 합니다.
<add>
<add>```js
<add>-function render(now) {
<add>- time *= 0.001;
<add>+let then = 0;
<add>+function render(now) {
<add>+ now *= 0.001; // 초 단위로 변환
<add>+ const deltaTime = now - then;
<add>+ then = now;
<add>
<add> if (resizeRendererToDisplaySize(renderer)) {
<add> const canvas = renderer.domElement;
<add> camera.aspect = canvas.clientWidth / canvas.clientHeight;
<add> camera.updateProjectionMatrix();
<add>+ composer.setSize(canvas.width, canvas.height);
<add> }
<add>
<add> cubes.forEach((cube, ndx) => {
<add> const speed = 1 + ndx * .1;
<add>- const rot = time * speed;
<add>+ const rot = now * speed;
<add> cube.rotation.x = rot;
<add> cube.rotation.y = rot;
<add> });
<add>
<add>- renderer.render(scene, camera);
<add>+ composer.render(deltaTime);
<add>
<add> requestAnimationFrame(render);
<add>}
<add>```
<add>
<add>`EffectComposer.render` 메서드는 인자로 마지막 프레임을 렌더링한 이후의 시간값인 `deltaTime`을 인자로 받습니다. pass에 애니메이션이 필요할 경우를 대비해 이 값을 넘겨주기 위해서이죠. 예제의 경우에는 `FilmPass`에 애니메이션이 있습니다.
<add>
<add>{{{example url="../threejs-postprocessing.html" }}}
<add>
<add>런타임에 효과의 속성을 변경할 때는 보통 uniform의 value 값을 바꿉니다. GUI를 추가해 이 속성을 조정할 수 있게 만들어보죠. 어떤 속성을 어떻게 조작할 수 있는지는 해당 효과의 소스 코드를 열어봐야 알 수 있습니다.
<add>
<add>[`BloomPass.js`](https://github.com/mrdoob/three.js/blob/master/examples/js/postprocessing/BloomPass.js)에서
<add>아래 코드를 찾았습니다.
<add>
<add>```js
<add>this.copyUniforms[ "opacity" ].value = strength;
<add>```
<add>
<add>아래처럼 하면 강도를 런타임에 바꿀 수 있겠네요.
<add>
<add>```js
<add>bloomPass.copyUniforms.opacity.value = someValue;
<add>```
<add>
<add>마찬가지로 [`FilmPass.js`](https://github.com/mrdoob/three.js/blob/master/examples/js/postprocessing/FilmPass.js)에서
<add>아래 코드를 찾았습니다.
<add>
<add>```js
<add>if ( grayscale !== undefined ) this.uniforms.grayscale.value = grayscale;
<add>if ( noiseIntensity !== undefined ) this.uniforms.nIntensity.value = noiseIntensity;
<add>if ( scanlinesIntensity !== undefined ) this.uniforms.sIntensity.value = scanlinesIntensity;
<add>if ( scanlinesCount !== undefined ) this.uniforms.sCount.value = scanlinesCount;
<add>```
<add>
<add>이제 어떻게 값을 지정해야 하는지 알았으니 이 값을 조작하는 GUI를 만들어봅시다.
<add>
<add>```js
<add>import { GUI } from '../3rdparty/dat.gui.module.js';
<add>```
<add>
<add>일단 모듈을 로드합니다.
<add>
<add>```js
<add>const gui = new GUI();
<add>{
<add> const folder = gui.addFolder('BloomPass');
<add> folder.add(bloomPass.copyUniforms.opacity, 'value', 0, 2).name('strength');
<add> folder.open();
<add>}
<add>{
<add> const folder = gui.addFolder('FilmPass');
<add> folder.add(filmPass.uniforms.grayscale, 'value').name('grayscale');
<add> folder.add(filmPass.uniforms.nIntensity, 'value', 0, 1).name('noise intensity');
<add> folder.add(filmPass.uniforms.sIntensity, 'value', 0, 1).name('scanline intensity');
<add> folder.add(filmPass.uniforms.sCount, 'value', 0, 1000).name('scanline count');
<add> folder.open();
<add>}
<add>```
<add>
<add>이제 각 설정을 조작할 수 있습니다.
<add>
<add>{{{example url="../threejs-postprocessing-gui.html" }}}
<add>
<add>여기까지 잘 따라왔다면 이제 효과를 직접 만들어볼 수 있습니다.
<add>
<add>후처리 효과는 쉐이더를 사용합니다. 쉐이더는 [GLSL (Graphics Library Shading Language)](https://www.khronos.org/files/opengles_shading_language.pdf)이라는 언어를 사용하죠. 언어가 방대해 이 글에서 전부 다루기는 어렵습니다. 기초부터 알아보고 싶다면 [이 글](https://webglfundamentals.org/webgl/lessons/ko/webgl-shaders-and-glsl.html)과 [쉐이더란 무엇인가(The Book of Shaders)](https://thebookofshaders.com/)를 읽어보기 바랍니다.
<add>
<add>직접 예제를 만들어보는 게 도움이 될 테니 간단한 GLSL 후처리 쉐이더를 만들어봅시다. 이미지에 특정 색을 혼합하는 쉐이더를 만들 겁니다.
<add>
<add>Three.js에는 후처리를 도와주는 `ShaderPass` 헬퍼 클래스가 있습니다. 인자로 vertex 쉐이더, fragment 쉐이더, 기본값으로 이루어진 객체를 받죠. 이 클래스는 이전 pass의 결과물에서 어떤 텍스처를 읽을지, 그리고 `EffectComposer`의 렌더 타겟과 캔버스 중 어디에 렌더링할지를 결정할 겁니다.
<add>
<add>아래는 이전 pass의 결과물에 특정 색을 혼합하는 간단한 후처리 쉐이더입니다.
<add>
<add>```js
<add>const colorShader = {
<add> uniforms: {
<add> tDiffuse: { value: null },
<add> color: { value: new THREE.Color(0x88CCFF) },
<add> },
<add> vertexShader: `
<add> varying vec2 vUv;
<add> void main() {
<add> vUv = uv;
<add> gl_Position = projectionMatrix * modelViewMatrix * vec4(position, 1);
<add> }
<add> `,
<add> fragmentShader: `
<add> varying vec2 vUv;
<add> uniform sampler2D tDiffuse;
<add> uniform vec3 color;
<add> void main() {
<add> vec4 previousPassColor = texture2D(tDiffuse, vUv);
<add> gl_FragColor = vec4(
<add> previousPassColor.rgb * color,
<add> previousPassColor.a);
<add> }
<add> `,
<add>};
<add>```
<add>
<add>위 코드에서 `tDiffuse`는 이전 pass의 결과물을 받아오기 위한 것으로 거의 모든 경우에 필수입니다. 그리고 그 바로 밑에 `color` 속성을 Three.js의 `Color`로 선언했습니다.
<add>
<add>다음으로 vertex 쉐이더를 작성해야 합니다. 위 코드에서 작성한 vertex 쉐이더는 후처리에서 거의 표준처럼 사용하는 코드로, 대부분의 경우 바꿀 필요가 없습니다. 뭔가 많이 설정한 경우(아까 언급한 링크 참조)가 아니라면 `uv`, `projectionMatrix`, `modelViewMatrix`, `position` 변수는 Three.js가 알아서 넣어줍니다.
<add>
<add>마지막으로 fragment 쉐이더를 생성합니다. 아래 코드로 이전 pass에서 넘겨준 결과물의 픽셀 색상값을 가져올 수 있습니다.
<add>
<add>```glsl
<add>vec4 previousPassColor = texture2D(tDiffuse, vUv);
<add>```
<add>
<add>여기에 지정한 색상을 곱해 `gl_FragColor`에 결과를 저장합니다.
<add>
<add>```glsl
<add>gl_FragColor = vec4(
<add> previousPassColor.rgb * color,
<add> previousPassColor.a);
<add>```
<add>
<add>추가로 간단한 GUI를 만들어 rgb의 각 색상값을 조정할 수 있도록 합니다.
<add>
<add>```js
<add>const gui = new GUI();
<add>gui.add(colorPass.uniforms.color.value, 'r', 0, 4).name('red');
<add>gui.add(colorPass.uniforms.color.value, 'g', 0, 4).name('green');
<add>gui.add(colorPass.uniforms.color.value, 'b', 0, 4).name('blue');
<add>```
<add>
<add>색을 혼합하는 간단한 후처리 쉐이더를 완성했습니다.
<add>
<add>{{{example url="../threejs-postprocessing-custom.html" }}}
<add>
<add>언급했듯 이 글에서 GLSL의 작성법과 사용자 지정 쉐이더를 만드는 법을 모두 다루기는 무리입니다. WebGL이 어떻게 동작하는지 알고 싶다면 [이 시리즈](https://webglfundamentals.org)를 참고하세요. [Three.js의 후처리 쉐이더 소스 코드](https://github.com/mrdoob/three.js/tree/master/examples/js/shaders)를 분석하는 것도 좋은 방법입니다. 상대적으로 복잡한 쉐이더도 있지만 작은 것부터 차근차근 살펴본다면 언젠가 전체를 이해할 수 있을 거예요.
<add>
<add>아쉽게도 Three.js의 후처리 효과 대부분은 공식 문서가 없어 [예제를 참고하거나](https://github.com/mrdoob/three.js/tree/master/examples) [후처리 효과의 소스 코드](https://github.com/mrdoob/three.js/tree/master/examples/js/postprocessing)를 직접 분석해야 합니다. 부디 이 글과 이 시리즈의 [렌더 타겟에 관한 글](threejs-rendertargets.html)이 좋은 출발점을 마련해주었으면 좋겠네요.
<ide><path>threejs/lessons/kr/threejs-prerequisites.md
<ide> ES5에서 배열에 [`forEach`](https://developer.mozilla.org/ko/docs/Web/JavaSc
<ide>
<ide> 기존 방법
<ide>
<del> const width = dims.width;
<del> const height = dims.height;
<add>```js
<add>const width = dims.width;
<add>const height = dims.height;
<add>```
<add>
<add>새로운 방법
<add>
<add>```js
<add>const { width, height } = dims;
<add>```
<add>
<add>구조분해할당은 배열에도 적용할 수 있습니다. `const position = [1, 2, 3, 4]`.
<add>이런 배열이 있다고 해보죠.
<add>
<add>기존 방법
<add>
<add>```js
<add>const x = position[2];
<add>const y = position[1];
<add>```
<ide>
<ide> 새로운 방법
<ide>
<del> const { width, height } = dims;
<add>```js
<add>const [ , y, x ] = position;
<add>```
<add>
<add>또한 매개변수에도 구조분해할당을 적용할 수 있습니다.
<add>
<add>```js
<add>const dims = { width: 300, height: 150 };
<add>const position = [1, 2, 3, 4];
<add>
<add>function distFromOrig([x, y]) {
<add> return Math.sqrt(x * x + y * y);
<add>}
<add>
<add>const dist = distFromOrig(position); // dist = 2.236...
<add>
<add>function area({ width, height }) {
<add> return width * height;
<add>}
<add>const a = area(dims); // a = 45000
<add>```
<ide>
<ide> ### 객체 선언 시 축약 문법 사용
<ide>
<ide> ES5에서 배열에 [`forEach`](https://developer.mozilla.org/ko/docs/Web/JavaSc
<ide> function log(className, ...args) {
<ide> const elem = document.createElement('div');
<ide> elem.className = className;
<del> elem.textContent = [...args].join(' ');
<add> elem.textContent = args.join(' ');
<ide> document.body.appendChild(elem);
<ide> }
<ide> ```
<ide> const position = [1, 2, 3];
<ide> somemesh.position.set(...position);
<ide> ```
<ide>
<add>배열을 얕은 복사할 때 사용할 수도 있고
<add>
<add>```js
<add>const copiedPositionArray = [...position];
<add>copiedPositionArray.push(4); // [1,2,3,4]
<add>console.log(position); // [1,2,3] 기존 배열은 영향을 받지 않음
<add>```
<add>
<add>객체를 합칠 때도 사용할 수 있죠.
<add>
<add>```
<add>const a = { abc: 123 };
<add>const b = { def: 456 };
<add>const c = { ...a, ...b }; // c = { abc: 123, def: 456 }
<add>```
<add>
<ide> ### `class` 사용하기
<ide>
<ide> ES5 이하의 문법으로 클래스 스타일의 객체를 만드는 방법은 다른 개발자들에게 낯선 요소
<ide><path>threejs/lessons/kr/threejs-rendering-on-demand.md
<add>Title: 불필요한 렌더링 없애기
<add>Description: 불필요한 렌더링을 제거합니다
<add>TOC: 불필요한 렌더링 없애기
<add>
<add>대부분의 개발자에게 이 주제는 너무 뻔할 수 있지만, 필요한 누군가를 위해
<add>글을 써보려 합니다. 대부분의 Three.js 예제는 렌더링 과정을 계속 반복합니다.
<add>그러니까 아래와 같이 재귀적으로 `requestAnimationFrame` 함수를 사용한다는
<add>거죠.
<add>
<add>```js
<add>function render() {
<add> ...
<add> requestAnimationFrame(render);
<add>}
<add>requestAnimationFrame(render);
<add>```
<add>
<add>계속 애니메이션이 있는 경우에야 별 상관이 없지만, 애니메이션이 없는 경우라면
<add>어떨까요? 이 경우 불필요한 렌더링을 반복하는 것은 연산 낭비일 뿐더러 사용
<add>환경이 모바일이라면 사용자의 배터리까지 낭비하는 셈입니다.
<add>
<add>처음 한 번만 렌더링하고, 그 후에 변화가 있을 때만 렌더링하는 것이 가장 정확한
<add>해결책일 겁니다. 여기서 변화란 텍스처나 모델의 로딩이 끝났을 때, 외부에서
<add>데이터를 받았을 때, 사용자가 카메라를 조정하거나, 설정을 바꾸거나, 인풋 값이
<add>변경된 경우 등 다양하겠죠.
<add>
<add>[반응형 디자인에 관한 글](threejs-responsive.html)에서 썼던 예제를 수정해
<add>필요에 따른 렌더링을 구현해봅시다.
<add>
<add>먼저 뭔가 변화를 일으킬 수 있는 요소가 필요하니 `OrbitControls`를 추가합니다.
<add>
<add>```js
<add>import * as THREE from './resources/three/r115/build/three.module.js';
<add>+import { OrbitControls } from './resources/threejs/r115/examples/jsm/controls/OrbitControls.js';
<add>
<add>...
<add>
<add>const fov = 75;
<add>const aspect = 2; // canvas 기본값
<add>const near = 0.1;
<add>const far = 5;
<add>const camera = new THREE.PerspectiveCamera(fov, aspect, near, far);
<add>camera.position.z = 2;
<add>
<add>+const controls = new OrbitControls(camera, canvas);
<add>+controls.target.set(0, 0, 0);
<add>+controls.update();
<add>```
<add>
<add>정육면체에 애니메이션을 넣지 않을 것이니 이들을 참조할 필요가 없습니다.
<add>
<add>```js
<add>-const cubes = [
<add>- makeInstance(geometry, 0x44aa88, 0),
<add>- makeInstance(geometry, 0x8844aa, -2),
<add>- makeInstance(geometry, 0xaa8844, 2),
<add>-];
<add>+makeInstance(geometry, 0x44aa88, 0);
<add>+makeInstance(geometry, 0x8844aa, -2);
<add>+makeInstance(geometry, 0xaa8844, 2);
<add>```
<add>
<add>애니메이션과 `requestAnimationFrame` 관련 코드도 제거합니다.
<add>
<add>```js
<add>-function render(time) {
<add>- time *= 0.001;
<add>+function render() {
<add>
<add> if (resizeRendererToDisplaySize(renderer)) {
<add> const canvas = renderer.domElement;
<add> camera.aspect = canvas.clientWidth / canvas.clientHeight;
<add> camera.updateProjectionMatrix();
<add> }
<add>
<add>- cubes.forEach((cube, ndx) => {
<add>- const speed = 1 + ndx * .1;
<add>- const rot = time * speed;
<add>- cube.rotation.x = rot;
<add>- cube.rotation.y = rot;
<add>- });
<add>
<add> renderer.render(scene, camera);
<add>
<add>- requestAnimationFrame(render);
<add>}
<add>
<add>-requestAnimationFrame(render);
<add>```
<add>
<add>그리고 `render` 함수를 직접 호출합니다.
<add>
<add>```js
<add>render();
<add>```
<add>
<add>이제 `OrbitControls`가 카메라 설정을 바꿀 때마다 직접 `render` 함수를 호출해야
<add>합니다. 뭔가 복잡할 것 같지만 다행히 `OrbitControls`에는 `change` 이벤트가 있습니다.
<add>
<add>```js
<add>controls.addEventListener('change', render);
<add>```
<add>
<add>또한 창 크기가 바뀔 때의 동작도 직접 처리해야 합니다. `render` 함수를 계속 호출할
<add>때는 해당 동작을 자동으로 처리했지만, 지금은 `render` 함수를 수동으로 호출하므로
<add>창의 크기가 바뀔 때 `render` 함수를 호출하도록 하겠습니다.
<add>
<add>```js
<add>window.addEventListener('resize', render);
<add>```
<add>
<add>이제 불필요한 렌더링을 반복하지 않습니다.
<add>
<add>{{{example url="../threejs-render-on-demand.html" }}}
<add>
<add>`OrbitControls`에는 관성(inertia) 옵션이 있습니다. `enableDamping` 속성을 ture로
<add>설정하면 동작이 좀 더 부드러워지죠.
<add>
<add>※ damping: 감쇠.
<add>
<add>```js
<add>controls.enableDamping = true;
<add>```
<add>
<add>또한 `OrbitControls`가 부드러운 동작을 구현할 때 변경된 카메라 값을 계속 넘겨주도록
<add>`render` 함수 안에서 `controls.update` 메서드를 호출해야 합니다. 하지만 이렇게 하면
<add>`change` 이벤트가 발생했을 때 `render` 함수가 무한정 호출될 겁니다. controls가 `change`
<add>이벤트를 보내면 `render` 함수가 호출되고, `render` 함수는 `controls.update` 메서드를
<add>호출해 다시 `change` 이벤트를 보내게 만들 테니까요.
<add>
<add>`requestAnimationFrame`이 직접 `render` 함수를 호출하게 하면 이 문제를 해결 할 수
<add>있습니다. 너무 많은 프레임을 막기 위해 변수 하나를 두어 요청한 프레임이 없을 경우에만
<add>프레임을 요청하도록 하면 되겠네요.
<add>
<add>```js
<add>+let renderRequested = false;
<add>
<add>function render() {
<add>+ renderRequested = false;
<add>
<add> if (resizeRendererToDisplaySize(renderer)) {
<add> const canvas = renderer.domElement;
<add> camera.aspect = canvas.clientWidth / canvas.clientHeight;
<add> camera.updateProjectionMatrix();
<add> }
<add>
<add>+ controls.update();
<add> renderer.render(scene, camera);
<add>}
<add>render();
<add>
<add>+function requestRenderIfNotRequested() {
<add>+ if (!renderRequested) {
<add>+ renderRequested = true;
<add>+ requestAnimationFrame(render);
<add>+ }
<add>+}
<add>
<add>-controls.addEventListener('change', render);
<add>+controls.addEventListener('change', requestRenderIfNotRequested);
<add>```
<add>
<add>창 크기 변화가 일어났을 때도 `requestRenderIfNotRequested`를 호출하도록 합니다.
<add>
<add>```js
<add>-window.addEventListener('resize', render);
<add>+window.addEventListener('resize', requestRenderIfNotRequested);
<add>```
<add>
<add>차이점을 느끼기 어려울지도 모르겠습니다. 화살표 키를 쓰거나 예제를 드래그해 보고
<add>다시 위 예제를 이리저리 돌려보세요. 차이점이 느껴질 거예요. 위 예제는 화살표 키를
<add>눌렀을 때 일정 거리만큼 순간이동하지만 아래의 예제는 약간 미끄러집니다.
<add>
<add>{{{example url="../threejs-render-on-demand-w-damping.html" }}}
<add>
<add>간단한 dat.GUI를 추가해 반복 렌더링 여부를 제어할 수 있도록 하겠습니다.
<add>
<add>```js
<add>import * as THREE from './resources/three/r115/build/three.module.js';
<add>import { OrbitControls } from './resources/threejs/r115/examples/jsm/controls/OrbitControls.js';
<add>+import { GUI } from '../3rdparty/dat.gui.module.js';
<add>```
<add>
<add>먼저 각 정육면체의 색과 x축 스케일을 조정하는 GUI를 추가합니다. [조명에 관한 글](threejs-lights.html)에서
<add>썼던 `ColorGUIHelper`를 가져와 쓰도록 하죠.
<add>
<add>먼저 GUI를 생성합니다.
<add>
<add>```js
<add>const gui = new GUI();
<add>```
<add>
<add>그리고 각 정육면체에 `material.color`, `cube.scale.x` 설정을 폴더로 묶어
<add>추가합니다.
<add>
<add>```js
<add>function makeInstance(geometry, color, x) {
<add> const material = new THREE.MeshPhongMaterial({color});
<add>
<add> const cube = new THREE.Mesh(geometry, material);
<add> scene.add(cube);
<add>
<add> cube.position.x = x;
<add>
<add>+ const folder = gui.addFolder(`Cube${ x }`);
<add>+ folder.addColor(new ColorGUIHelper(material, 'color'), 'value')
<add>+ .name('color')
<add>+ .onChange(requestRenderIfNotRequested);
<add>+ folder.add(cube.scale, 'x', .1, 1.5)
<add>+ .name('scale x')
<add>+ .onChange(requestRenderIfNotRequested);
<add>+ folder.open();
<add>
<add> return cube;
<add>}
<add>```
<add>
<add>dat.GUI 컨트롤(control)의 `onChange` 메서드에 콜백 함수를 넘겨주면 GUI 값이 바뀔
<add>때마다 콜백 함수를 호출합니다. 예제의 경우에는 단순히 `requestRenderIfNotRequested`
<add>함수를 넘겨주면 되죠. 그리고 `folder.open` 메서드를 호출해 폴더를 열어 둡니다.
<add>
<add>{{{example url="../threejs-render-on-demand-w-gui.html" }}}
<add>
<add>이 글이 불필요한 렌더링 제거에 대한 개념을 조금이라도 잡아주었길 바랍니다. 보통
<add>Three.js를 사용할 때는 이렇게 렌더링 루프를 제어할 일이 없습니다. 대게 게임 또는
<add>애니메이션이 들어간 3D 컨텐츠이기 때문이죠. 하지만 지도나, 3D 에디터, 3D 그래프,
<add>상품 목록 등에서는 이런 기법이 필요할 수도 있습니다.
<ide><path>threejs/lessons/kr/threejs-transparency.md
<add>Title: Three.js 투명도
<add>Description: Three.js에서 투명도를 설정하는 법을 알아봅니다
<add>TOC: 물체의 투명도 설정하기
<add>
<add>Three.js에서 투명도는 간단하지만 동시에 까다로운 주제입니다.
<add>
<add>먼저 쉬운 것부터 알아보죠. 예제로 정육면체 8개를 2x2x2 그리드에 맞춘 장면을
<add>만들어보겠습니다.
<add>
<add>[불필요한 렌더링 제거하기](threejs-rendering-on-demand.html)에서 썼던
<add>예제를 가져와 정육면체 3개를 8개로 수정합니다. 먼저 `makeInstance` 함수가
<add>x, y, z 값을 받도록 수정하겠습니다.
<add>
<add>```js
<add>-function makeInstance(geometry, color) {
<add>+function makeInstance(geometry, color, x, y, z) {
<add> const material = new THREE.MeshPhongMaterial({color});
<add>
<add> const cube = new THREE.Mesh(geometry, material);
<add> scene.add(cube);
<add>
<add>- cube.position.x = x;
<add>+ cube.position.set(x, y, z);
<add>
<add> return cube;
<add>}
<add>```
<add>
<add>그리고 정육면체 8개를 만듭니다.
<add>
<add>```js
<add>+function hsl(h, s, l) {
<add>+ return (new THREE.Color()).setHSL(h, s, l);
<add>+}
<add>
<add>-makeInstance(geometry, 0x44aa88, 0);
<add>-makeInstance(geometry, 0x8844aa, -2);
<add>-makeInstance(geometry, 0xaa8844, 2);
<add>
<add>+{
<add>+ const d = 0.8;
<add>+ makeInstance(geometry, hsl(0 / 8, 1, .5), -d, -d, -d);
<add>+ makeInstance(geometry, hsl(1 / 8, 1, .5), d, -d, -d);
<add>+ makeInstance(geometry, hsl(2 / 8, 1, .5), -d, d, -d);
<add>+ makeInstance(geometry, hsl(3 / 8, 1, .5), d, d, -d);
<add>+ makeInstance(geometry, hsl(4 / 8, 1, .5), -d, -d, d);
<add>+ makeInstance(geometry, hsl(5 / 8, 1, .5), d, -d, d);
<add>+ makeInstance(geometry, hsl(6 / 8, 1, .5), -d, d, d);
<add>+ makeInstance(geometry, hsl(7 / 8, 1, .5), d, d, d);
<add>+}
<add>```
<add>
<add>카메라도 조정합니다.
<add>
<add>```js
<add>const fov = 75;
<add>const aspect = 2; // canvas 기본값
<add>const near = 0.1;
<add>-const far = 5;
<add>+const far = 25;
<add>const camera = new THREE.PerspectiveCamera(fov, aspect, near, far);
<add>-camera.position.z = 4;
<add>+camera.position.z = 2;
<add>```
<add>
<add>배경색은 하얀색으로 바꿔주고
<add>
<add>```js
<add>const scene = new THREE.Scene();
<add>+scene.background = new THREE.Color('white');
<add>```
<add>
<add>정육면체의 옆면도 빛을 받도록 조명을 하나 더 추가합니다.
<add>
<add>```js
<add>-{
<add>+function addLight(...pos) {
<add> const color = 0xFFFFFF;
<add> const intensity = 1;
<add> const light = new THREE.DirectionalLight(color, intensity);
<add>- light.position.set(-1, 2, 4);
<add>+ light.position.set(...pos);
<add> scene.add(light);
<add>}
<add>+addLight(-1, 2, 4);
<add>+addLight( 1, -1, -2);
<add>```
<add>
<add>정육면체를 투명하게 만들려면 [`transparent`](Material.transparent) 속성을
<add>켜고 [`opacity`](Material.opacity) 속성을 설정해줘야 합니다(CSS와 마찬가지로
<add>0은 완전히 투명함, 1은 완전히 불투명함을 의미).
<add>
<add>```js
<add>function makeInstance(geometry, color, x, y, z) {
<add>- const material = new THREE.MeshPhongMaterial({color});
<add>+ const material = new THREE.MeshPhongMaterial({
<add>+ color,
<add>+ opacity: 0.5,
<add>+ transparent: true,
<add>+ });
<add>
<add> const cube = new THREE.Mesh(geometry, material);
<add> scene.add(cube);
<add>
<add> cube.position.set(x, y, z);
<add>
<add> return cube;
<add>}
<add>```
<add>
<add>이제 8개의 반투명한 정육면체가 생겼습니다.
<add>
<add>{{{example url="../threejs-transparency.html"}}}
<add>
<add>예제를 드래그하면 화면을 회전시킬 수 있습니다.
<add>
<add>완벽한데요, 라고 생각했다면 좀 더 자세히 보세요. 정육면체의 뒷면이 하나도
<add>보이지 않습니다.
<add>
<add><div class="threejs_center"><img src="resources/images/transparency-cubes-no-backs.png" style="width: 416px;"></div>
<add><div class="threejs_center">뒷면이 보이지 않는다</div>
<add>
<add>이전에 [재질(material)에 관해](threejs-materials.html) 배울 때 [`side`](Material.side)
<add>속성에 대해 배웠었죠. 이 속성을 `THREE.DoubleSide`로 설정해 정육면체의
<add>양면이 모두 보이도록 해봅시다.
<add>
<add>```js
<add>const material = new THREE.MeshPhongMaterial({
<add> color,
<add> map: loader.load(url),
<add> opacity: 0.5,
<add> transparent: true,
<add>+ side: THREE.DoubleSide,
<add>});
<add>```
<add>
<add>{{{example url="../threejs-transparency-doubleside.html" }}}
<add>
<add>예제를 돌려보세요. 뭔가 해결된 듯 하지만 자세히 보면 가끔 뒷면 또는 뒷면의
<add>일부가 보이지 않습니다.
<add>
<add><div class="threejs_center"><img src="resources/images/transparency-cubes-some-backs.png" style="width: 368px;"></div>
<add><div class="threejs_center">정육면체의 왼쪽 뒷면이 보이지 않는다</div>
<add>
<add>이는 3D 요소를 렌더링하는 방식 때문입니다. WebGL은 각 geometry의 삼각형을
<add>한 번에 하나씩 렌더링합니다. 그리고 삼각형의 픽셀 하나를 렌더링할 때마다
<add>2개의 정보를 기록하는데, 하나는 해당 픽셀의 색이고 다른 하나는 픽셀의
<add>깊이(depth)입니다. 다음 삼각형을 그릴 때 해당 픽셀이 이미 그려진 픽셀보다
<add>깊이가 깊다면 해당 픽셀을 렌더링하지 않죠.
<add>
<add>이는 불투명한 물체에서는 문제가 되지 않았지만 투명한 물체에서는 문제가 됩니다.
<add>
<add>이 문제를 해결하려면 투명한 물체를 분류해 뒤에 있는 물체를 앞에 있는 물체보다
<add>먼저 렌더링해야 합니다. `Mesh` 같은 경우는 Three.js가 자동으로 이를 처리해주죠.
<add>만약 그러지 않았다면 제일 첫 번째 예제에서 뒤에 있는 정육면체를 아예 볼 수
<add>없었을 겁니다.
<add>
<add>정육면체에는 한 면에 2개, 총 12개의 삼각형이 있습니다. 각 삼각형의 렌더링 순서는
<add>[geometry에 관한 글에서 봤던 것](threejs-custom-buffergeometry.html)과 같죠.
<add>시선에 따라 카메라에서 가까운 삼각형을 먼저 렌더링할 겁니다. 앞면을 뒷면보다 먼저
<add>렌더링하니, 때때로 뒷면이 보이지 않을 수밖에 없죠.
<add>
<add>구체나 정육면체 등 볼록 물체(convex object)의 경우, 모든 물체를 한 번씩 더 렌더링해
<add>문제를 해결할 수 있습니다. 하나는 안쪽면 삼각형만 렌더링하고, 다른 하나는 바깥쪽
<add>삼각형만 렌더링하도록 만드는 것이죠.
<add>
<add>```js
<add>function makeInstance(geometry, color, x, y, z) {
<add>+ [THREE.BackSide, THREE.FrontSide].forEach((side) => {
<add> const material = new THREE.MeshPhongMaterial({
<add> color,
<add> opacity: 0.5,
<add> transparent: true,
<add>+ side,
<add> });
<add>
<add> const cube = new THREE.Mesh(geometry, material);
<add> scene.add(cube);
<add>
<add> cube.position.set(x, y, z);
<add>+ });
<add>}
<add>```
<add>
<add>어찌어찌 해결된 *것처럼* 보입니다.
<add>
<add>{{{example url="../threejs-transparency-doubleside-hack.html" }}}
<add>
<add>Three.js의 분류 기준은 고정적인 듯합니다. `side: THREE.BackSide` mesh를 먼저
<add>넣고, 그 다음 정확히 같은 위치에 `side: THREE.FrontSide` mesh를 넣었으니까요.
<add>
<add>이번에는 평면 2개를 교차로 배치해봅시다(정육면체 관련 코드를 전부 지운 뒤).
<add>각 평면에는 다른 텍스처를 넣을 겁니다.
<add>
<add>```js
<add>const planeWidth = 1;
<add>const planeHeight = 1;
<add>const geometry = new THREE.PlaneBufferGeometry(planeWidth, planeHeight);
<add>
<add>const loader = new THREE.TextureLoader();
<add>
<add>function makeInstance(geometry, color, rotY, url) {
<add> const texture = loader.load(url, render);
<add> const material = new THREE.MeshPhongMaterial({
<add> color,
<add> map: texture,
<add> opacity: 0.5,
<add> transparent: true,
<add> side: THREE.DoubleSide,
<add> });
<add>
<add> const mesh = new THREE.Mesh(geometry, material);
<add> scene.add(mesh);
<add>
<add> mesh.rotation.y = rotY;
<add>}
<add>
<add>makeInstance(geometry, 'pink', 0, 'resources/images/happyface.png');
<add>makeInstance(geometry, 'lightblue', Math.PI * 0.5, 'resources/images/hmmmface.png');
<add>```
<add>
<add>평면은 한 번에 한 면밖에 보지 못하니, `side: THREE.DoubleSide`로 설정했습니다. 또한
<add>텍스처를 전부 불러왔을 때 장면을 다시 렌더링하도록 `render` 함수를 `loader.load`
<add>메서드에 넘겨줬습니다. 이는 [필요에 따른 렌더링](threejs-rendering-on-demand.html)을
<add>구현하기 위한 것이죠.
<add>
<add>{{{example url="../threejs-transparency-intersecting-planes.html"}}}
<add>
<add>아까와 비슷한 문제가 보입니다.
<add>
<add><div class="threejs_center"><img src="resources/images/transparency-planes.png" style="width: 408px;"></div>
<add><div class="threejs_center">면의 반쪽이 사라졌다</div>
<add>
<add>평면을 둘로 쪼개 실제로는 교차하지 않게끔 만들면 문제를 해결할 수 있습니다.
<add>
<add>```js
<add>function makeInstance(geometry, color, rotY, url) {
<add>+ const base = new THREE.Object3D();
<add>+ scene.add(base);
<add>+ base.rotation.y = rotY;
<add>
<add>+ [-1, 1].forEach((x) => {
<add> const texture = loader.load(url, render);
<add>+ texture.offset.x = x < 0 ? 0 : 0.5;
<add>+ texture.repeat.x = .5;
<add> const material = new THREE.MeshPhongMaterial({
<add> color,
<add> map: texture,
<add> opacity: 0.5,
<add> transparent: true,
<add> side: THREE.DoubleSide,
<add> });
<add>
<add> const mesh = new THREE.Mesh(geometry, material);
<add>- scene.add(mesh);
<add>+ base.add(mesh);
<add>
<add>- mesh.rotation.y = rotY;
<add>+ mesh.position.x = x * .25;
<add> });
<add>}
<add>```
<add>
<add>저걸 어떻게 구현할지는 여러분의 선택입니다. [블렌더(Blender)](https://blender.org)
<add>같은 3D 에디터를 사용했다면 텍스처 좌표를 직접 수정했겠죠. 예제의 경우에는
<add>`PlaneBufferGeometry`를 썼습니다. [이전에 다뤘듯](threejs-textures.html)
<add>이 geometry는 기본적으로 텍스처를 크기에 맞춰 늘립니다. [`texture.repeat`](Texture.repeat)
<add>속성과 [`texture.offset`](Texture.offset) 속성을 조정해 각 면에 적절한
<add>텍스처를 입혀줄 수 있죠.
<add>
<add>위 코드에서는 `Object3D`를 만들어 두 평면의 부모로 지정했습니다. 이렇게
<add>하면 복잡한 계산 없이 간단하게 `Object3D`만 돌려서 두 평면 다 회전시킬
<add>수 있죠.
<add>
<add>{{{example url="../threejs-transparency-intersecting-planes-fixed.html"}}}
<add>
<add>이 방법은 교차점이 변하지 않는 정말 간단한 경우에만 가능합니다.
<add>
<add>텍스처가 들어간 요소는 알파 테스트(alpha test)를 활성화해 이를 해결할 수
<add>있죠.
<add>
<add>알파 테스트란 Three.js가 픽셀을 렌더링하지 않는 특정 *알파* 단계를 의미합니다.
<add>만약 아무것도 그리지 않게 설정한다면 위와 같은 문제는 사라지겠죠. 상대적으로
<add>경계가 분명한 텍스처, 나뭇잎, 잔디 등의 경우 이는 꽤 잘 작동합니다.
<add>
<add>이번에도 2개의 면을 만들어 테스트해보도록 합시다. 아까는 텍스처가 전부 불투명했죠.
<add>이번에는 각 면에는 각각 다른, 부분적으로 투명한 텍스처를 사용할 겁니다.
<add>
<add><div class="spread">
<add> <div><img class="checkerboard" src="../resources/images/tree-01.png"></div>
<add> <div><img class="checkerboard" src="../resources/images/tree-02.png"></div>
<add></div>
<add>
<add>아까 평면 2개를 교차해놓았던(반으로 가르기 전) 예제를 가져와 이 텍스처에
<add>[`alphaTest`](Material.alphaTest) 속성을 지정하겠습니다.
<add>
<add>```js
<add>function makeInstance(geometry, color, rotY, url) {
<add> const texture = loader.load(url, render);
<add> const material = new THREE.MeshPhongMaterial({
<add> color,
<add> map: texture,
<add>- opacity: 0.5,
<add> transparent: true,
<add>+ alphaTest: 0.5,
<add> side: THREE.DoubleSide,
<add> });
<add>
<add> const mesh = new THREE.Mesh(geometry, material);
<add> scene.add(mesh);
<add>
<add> mesh.rotation.y = rotY;
<add>}
<add>
<add>-makeInstance(geometry, 'pink', 0, 'resources/images/happyface.png');
<add>-makeInstance(geometry, 'lightblue', Math.PI * 0.5, 'resources/images/hmmmface.png');
<add>+makeInstance(geometry, 'white', 0, 'resources/images/tree-01.png');
<add>+makeInstance(geometry, 'white', Math.PI * 0.5, 'resources/images/tree-02.png');
<add>```
<add>
<add>이대로 실행해도 되지만, 간단한 UI를 만들어 `alphaTest`와 `transparent` 속성을
<add>갖고 놀 수 있게 해보겠습니다. [씬 그래프에 관한 글](threejs-scenegraph.html)에서
<add>소개했던 dat.GUI를 써서요.
<add>
<add>먼저 dat.GUI에 지정할 헬퍼 클래스를 만들겠습니다. 이 헬퍼 클래스는 장면 안 모든
<add>재질을 해당 값으로 변경할 겁니다.
<add>
<add>```js
<add>class AllMaterialPropertyGUIHelper {
<add> constructor(prop, scene) {
<add> this.prop = prop;
<add> this.scene = scene;
<add> }
<add> get value() {
<add> const { scene, prop } = this;
<add> let v;
<add> scene.traverse((obj) => {
<add> if (obj.material && obj.material[prop] !== undefined) {
<add> v = obj.material[prop];
<add> }
<add> });
<add> return v;
<add> }
<add> set value(v) {
<add> const { scene, prop } = this;
<add> scene.traverse((obj) => {
<add> if (obj.material && obj.material[prop] !== undefined) {
<add> obj.material[prop] = v;
<add> obj.material.needsUpdate = true;
<add> }
<add> });
<add> }
<add>}
<add>```
<add>
<add>다음으로 GUI를 추가합니다.
<add>
<add>```js
<add>const gui = new GUI();
<add>gui.add(new AllMaterialPropertyGUIHelper('alphaTest', scene), 'value', 0, 1)
<add> .name('alphaTest')
<add> .onChange(requestRenderIfNotRequested);
<add>gui.add(new AllMaterialPropertyGUIHelper('transparent', scene), 'value')
<add> .name('transparent')
<add> .onChange(requestRenderIfNotRequested);
<add>```
<add>
<add>물론 dat.GUI 모듈도 불러와야죠.
<add>
<add>```js
<add>import * as THREE from './resources/three/r115/build/three.module.js';
<add>import { OrbitControls } from './resources/threejs/r115/examples/jsm/controls/OrbitControls.js';
<add>+import { GUI } from '../3rdparty/dat.gui.module.js';
<add>```
<add>
<add>{{{example url="../threejs-transparency-intersecting-planes-alphatest.html"}}}
<add>
<add>예제를 확대해보면 평면에 하얀 테두리가 보일 겁니다.
<add>
<add><div class="threejs_center"><img src="resources/images/transparency-alphatest-issues.png" style="width: 532px;"></div>
<add>
<add>이는 앞서 봤던 예제와 같은 문제입니다. 하얀 테두리를 가진 요소가 먼저 그려져
<add>뒤에 있는 요소가 일부 가려진 것이죠. 완벽한 해결책은 없습니다. 그때그때 상황에
<add>따라 `alphaTest`나 `transparent` 옵션을 조정해서 상황에 맞는 해결책을 찾아야
<add>하죠.
<add>
<add>결국 이 글의 주제는 "완벽한 투명도는 구현하기 힘들다"가 되겠네요. 웬만한 방법에는
<add>모두 문제와, 타협점, 편법 등이 존재합니다.
<add>
<add>자동차의 경우를 예로 들어보죠. 자동차는 보통 4면에 유리창이 있습니다. 렌더링 순서를
<add>제대로 적용하려면 각각의 창문을 별도의 요소로 만들어야 합니다. 만약 하나의 요소라면
<add>Three.js가 렌더링 순서를 제대로 결정할 수 없겠죠.
<add>
<add>식물이나 잔디 등을 구현할 때는 일반적으로 알파 테스트를 사용합니다.
<add>
<add>어떤 방법을 사용할지는 전적으로 상황과 여러분의 판단에 달려 있죠. | 7 |
Javascript | Javascript | use stable paths for cache key | 188093ae29a7d1d7ba74ba35ce5f37984fc9c6f1 | <ide><path>packager/react-packager/src/Bundler/index.js
<ide> const HMRBundle = require('./HMRBundle');
<ide> const ModuleTransport = require('../lib/ModuleTransport');
<ide> const declareOpts = require('../lib/declareOpts');
<ide> const imageSize = require('image-size');
<add>const path = require('path');
<ide> const version = require('../../../../package.json').version;
<ide> const denodeify = require('denodeify');
<ide>
<ide> class Bundler {
<ide> transformModuleHash = '';
<ide> }
<ide>
<add> const stableProjectRoots = opts.projectRoots.map(p => {
<add> return path.relative(path.join(__dirname, '../../../..'), p);
<add> });
<add>
<ide> const cacheKeyParts = [
<ide> 'react-packager-cache',
<ide> version,
<ide> opts.cacheVersion,
<del> opts.projectRoots.join(',').split(pathSeparator).join('-'),
<add> stableProjectRoots.join(',').split(pathSeparator).join('-'),
<ide> transformModuleHash,
<ide> ];
<ide>
<ide> function verifyRootExists(root) {
<ide> function createModuleIdFactory() {
<ide> const fileToIdMap = Object.create(null);
<ide> let nextId = 0;
<del> return ({path}) => {
<del> if (!(path in fileToIdMap)) {
<del> fileToIdMap[path] = nextId;
<add> return ({path: modulePath}) => {
<add> if (!(modulePath in fileToIdMap)) {
<add> fileToIdMap[modulePath] = nextId;
<ide> nextId += 1;
<ide> }
<del> return fileToIdMap[path];
<add> return fileToIdMap[modulePath];
<ide> };
<ide> }
<ide> | 1 |
Python | Python | remove unused g3 dependency | b4bdc94c7b4fc4f11a446714b3edf7a7f3775e86 | <ide><path>research/slim/nets/nasnet/nasnet_utils.py
<ide> from __future__ import division
<ide> from __future__ import print_function
<ide>
<del>import google3
<del>
<ide> import tensorflow as tf
<ide>
<ide> | 1 |
Javascript | Javascript | simplify loading without globals | 91fb8594006d2014be9273da392e313c787f2570 | <ide><path>globals.js
<del>var document = global.document = require("jsdom").jsdom("<html><head></head><body></body></html>"),
<del> window = global.window = document.createWindow();
<del>
<del>// https://github.com/chad3814/CSSStyleDeclaration/issues/3
<del>var CSSStyleDeclaration_prototype = window.CSSStyleDeclaration.prototype,
<del> CSSStyleDeclaration_setProperty = CSSStyleDeclaration_prototype.setProperty;
<del>CSSStyleDeclaration_prototype.setProperty = function(name, value, priority) {
<del> return CSSStyleDeclaration_setProperty.call(this, name + "", value == null ? null : value + "", priority == null ? null : priority + "");
<del>};
<ide><path>index.js
<del>var globals = ["document", "window", "d3"],
<del> globalValues = {};
<del>
<del>globals.forEach(function(g) {
<del> if (g in global) globalValues[g] = global[g];
<del>});
<del>
<del>require("./globals");
<del>require("./d3");
<del>
<del>module.exports = d3;
<del>
<del>globals.forEach(function(g) {
<del> if (g in globalValues) global[g] = globalValues[g];
<del> else delete global[g];
<del>});
<add>var fs = require("fs"),
<add> document = require("jsdom").jsdom("<html><head></head><body></body></html>"),
<add> window = document.createWindow();
<add>
<add>// https://github.com/chad3814/CSSStyleDeclaration/issues/3
<add>var CSSStyleDeclaration_prototype = window.CSSStyleDeclaration.prototype,
<add> CSSStyleDeclaration_setProperty = CSSStyleDeclaration_prototype.setProperty;
<add>CSSStyleDeclaration_prototype.setProperty = function(name, value, priority) {
<add> return CSSStyleDeclaration_setProperty.call(this, name + "", value == null ? null : value + "", priority == null ? null : priority + "");
<add>};
<add>
<add>module.exports = (new Function("window", "document",
<add> "return " + fs.readFileSync("./d3.js", "utf-8"))
<add>)(window, document); | 2 |
Go | Go | update docker network inspect help syntax | 3dd50eaf054833280aad16e718bca4139d927532 | <ide><path>api/client/network.go
<ide> func (cli *DockerCli) CmdNetworkLs(args ...string) error {
<ide>
<ide> // CmdNetworkInspect inspects the network object for more details
<ide> //
<del>// Usage: docker network inspect <NETWORK> [<NETWORK>]
<del>// CmdNetworkInspect handles Network inspect UI
<add>// Usage: docker network inspect [OPTIONS] <NETWORK> [NETWORK...]
<ide> func (cli *DockerCli) CmdNetworkInspect(args ...string) error {
<del> cmd := Cli.Subcmd("network inspect", []string{"NETWORK"}, "Displays detailed information on a network", false)
<add> cmd := Cli.Subcmd("network inspect", []string{"NETWORK [NETWORK...]"}, "Displays detailed information on a network", false)
<ide> cmd.Require(flag.Min, 1)
<ide> err := cmd.ParseFlags(args, true)
<ide> if err != nil { | 1 |
PHP | PHP | add typehints for datasource/ | 2758d3cb554c7adfc627747850c28ccf3d4a3e69 | <ide><path>src/Datasource/ConnectionManager.php
<ide> public static function setConfig($key, $config = null): void
<ide> * @param string|null $config The DSN string to convert to a configuration array
<ide> * @return array The configuration array to be stored after parsing the DSN
<ide> */
<del> public static function parseDsn($config = null): array
<add> public static function parseDsn(?string $config = null): array
<ide> {
<ide> $config = static::_parseDsn($config);
<ide>
<ide><path>src/Datasource/ConnectionRegistry.php
<ide> protected function _throwMissingClassError(string $class, ?string $plugin): void
<ide> * @param array $settings An array of settings to use for the datasource.
<ide> * @return object A connection with the correct settings.
<ide> */
<del> protected function _create($class, string $alias, array $settings)
<add> protected function _create($class, string $alias, array $settings): object
<ide> {
<ide> if (is_callable($class)) {
<ide> return $class($alias);
<ide><path>src/Datasource/EntityInterface.php
<ide> public function getSource(): string;
<ide> * @param array $fields List of fields to be returned
<ide> * @return array
<ide> */
<del> public function extractOriginal(array $fields);
<add> public function extractOriginal(array $fields): array;
<ide>
<ide> /**
<ide> * Returns an array with only the original fields
<ide> public function extractOriginal(array $fields);
<ide> * @param array $fields List of fields to be returned
<ide> * @return array
<ide> */
<del> public function extractOriginalChanged(array $fields);
<add> public function extractOriginalChanged(array $fields): array;
<ide>
<ide> /**
<ide> * Sets one or multiple fields to the specified value
<ide> public function extractOriginalChanged(array $fields);
<ide> * first argument is also an array, in which case will be treated as $options
<ide> * @param array $options options to be used for setting the field. Allowed option
<ide> * keys are `setter` and `guard`
<del> * @return \Cake\Datasource\EntityInterface
<add> * @return $this
<ide> */
<ide> public function set($field, $value = null, array $options = []);
<ide>
<ide> public function &get(string $field);
<ide> * @param string|array $field The field to check.
<ide> * @return bool
<ide> */
<del> public function has($field);
<add> public function has($field): bool;
<ide>
<ide> /**
<ide> * Removes a field or list of fields from this entity
<ide> *
<ide> * @param string|array $field The field to unset.
<del> * @return \Cake\Datasource\EntityInterface
<add> * @return $this
<ide> */
<ide> public function unset($field);
<ide>
<ide> public function getVisible(): array;
<ide> *
<ide> * @return array
<ide> */
<del> public function toArray();
<add> public function toArray(): array;
<ide>
<ide> /**
<ide> * Returns an array with the requested fields
<ide><path>src/Datasource/EntityTrait.php
<ide> public function &__get(string $field)
<ide> * @param mixed $value The value to set to the field
<ide> * @return void
<ide> */
<del> public function __set(string $field, $value)
<add> public function __set(string $field, $value): void
<ide> {
<ide> $this->set($field, $value);
<ide> }
<ide> public function __set(string $field, $value)
<ide> * @return bool
<ide> * @see \Cake\ORM\Entity::has()
<ide> */
<del> public function __isset(string $field)
<add> public function __isset(string $field): bool
<ide> {
<ide> return $this->has($field);
<ide> }
<ide> public function __isset(string $field)
<ide> * @param string $field The field to unset
<ide> * @return void
<ide> */
<del> public function __unset(string $field)
<add> public function __unset(string $field): void
<ide> {
<ide> $this->unset($field);
<ide> }
<ide><path>src/Datasource/FactoryLocator.php
<ide> public static function drop(string $type): void
<ide> * @throws \InvalidArgumentException If the specified repository type has no factory.
<ide> * @return callable The factory for the repository type.
<ide> */
<del> public static function get(string $type)
<add> public static function get(string $type): callable
<ide> {
<ide> if (!isset(static::$_modelFactories['Table'])) {
<ide> static::$_modelFactories['Table'] = [TableRegistry::getTableLocator(), 'get'];
<ide><path>src/Datasource/Paginator.php
<ide> class Paginator implements PaginatorInterface
<ide> * to paginate.
<ide> * @param array $params Request params
<ide> * @param array $settings The settings/configuration used for pagination.
<del> * @return \Cake\Datasource\ResultSetInterface Query results
<add> * @return \Cake\Datasource\ResultSetInterface|array Query results
<ide> * @throws \Cake\Datasource\Exception\PageOutOfBoundsException
<ide> */
<ide> public function paginate(object $object, array $params = [], array $settings = [])
<ide> public function validateSort(RepositoryInterface $object, array $options): array
<ide> * @param string $model Current model alias
<ide> * @return array $fields Unaliased fields where applicable
<ide> */
<del> protected function _removeAliases($fields, $model)
<add> protected function _removeAliases(array $fields, string $model): array
<ide> {
<ide> $result = [];
<ide> foreach ($fields as $field => $sort) {
<ide><path>src/Datasource/PaginatorInterface.php
<ide> interface PaginatorInterface
<ide> * to paginate.
<ide> * @param array $params Request params
<ide> * @param array $settings The settings/configuration used for pagination.
<del> * @return \Cake\Datasource\ResultSetInterface Query results
<add> * @return \Cake\Datasource\ResultSetInterface|array Query results
<ide> */
<ide> public function paginate(object $object, array $params = [], array $settings = []);
<ide>
<ide><path>src/Datasource/QueryCacher.php
<ide> public function __construct($key, $config)
<ide> * Load the cached results from the cache or run the query.
<ide> *
<ide> * @param object $query The query the cache read is for.
<del> * @return \Cake\Datasource\ResultSetInterface|null Either the cached results or null.
<add> * @return mixed Either the cached results or null.
<ide> */
<del> public function fetch($query)
<add> public function fetch(object $query)
<ide> {
<ide> $key = $this->_resolveKey($query);
<ide> $storage = $this->_resolveCacher();
<ide> public function fetch($query)
<ide> * @param \Traversable $results The result set to store.
<ide> * @return bool True if the data was successfully cached, false on failure
<ide> */
<del> public function store($query, Traversable $results): bool
<add> public function store(object $query, Traversable $results): bool
<ide> {
<ide> $key = $this->_resolveKey($query);
<ide> $storage = $this->_resolveCacher();
<ide> public function store($query, Traversable $results): bool
<ide> * @return string
<ide> * @throws \RuntimeException
<ide> */
<del> protected function _resolveKey($query): string
<add> protected function _resolveKey(object $query): string
<ide> {
<ide> if (is_string($this->_key)) {
<ide> return $this->_key;
<ide> protected function _resolveKey($query): string
<ide> *
<ide> * @return \Cake\Cache\CacheEngine
<ide> */
<del> protected function _resolveCacher()
<add> protected function _resolveCacher(): CacheEngine
<ide> {
<ide> if (is_string($this->_config)) {
<ide> return Cache::pool($this->_config);
<ide><path>src/Datasource/QueryInterface.php
<ide> public function aliasField(string $field, ?string $alias = null): array;
<ide> * @param string|null $defaultAlias The default alias
<ide> * @return string[]
<ide> */
<del> public function aliasFields(array $fields, $defaultAlias = null): array;
<add> public function aliasFields(array $fields, ?string $defaultAlias = null): array;
<ide>
<ide> /**
<ide> * Fetch the results for this query.
<ide> public function aliasFields(array $fields, $defaultAlias = null): array;
<ide> * ResultSetDecorator is a traversable object that implements the methods found
<ide> * on Cake\Collection\Collection.
<ide> *
<del> * @return \Cake\Datasource\ResultSetInterface
<add> * @return \Cake\Datasource\ResultSetInterface|array
<ide> */
<ide> public function all();
<ide>
<ide> public function all();
<ide> * ```
<ide> *
<ide> * @param array $options list of query clauses to apply new parts to.
<del> * @return \Cake\Datasource\QueryInterface
<add> * @return $this
<ide> */
<ide> public function applyOptions(array $options);
<ide>
<ide> public function applyOptions(array $options);
<ide> *
<ide> * @param string $finder The finder method to use.
<ide> * @param array $options The options for the finder.
<del> * @return \Cake\Datasource\QueryInterface Returns a modified query.
<add> * @return $this Returns a modified query.
<ide> */
<del> public function find($finder, array $options = []);
<add> public function find(string $finder, array $options = []);
<ide>
<ide> /**
<ide> * Returns the first result out of executing this query, if the query has not been
<ide> public function repository(RepositoryInterface $repository);
<ide> *
<ide> * @return \Cake\Datasource\RepositoryInterface|null $repository The default repository object to use
<ide> */
<del> public function getRepository();
<add> public function getRepository(): ?RepositoryInterface;
<ide>
<ide> /**
<ide> * Adds a condition or set of conditions to be used in the WHERE clause for this
<ide><path>src/Datasource/QueryTrait.php
<ide> use Cake\Collection\Iterator\MapReduce;
<ide> use Cake\Datasource\Exception\RecordNotFoundException;
<ide> use InvalidArgumentException;
<add>use Traversable;
<ide>
<ide> /**
<ide> * Contains the characteristics for an object that is attached to a repository and
<ide> public function repository(RepositoryInterface $table)
<ide> *
<ide> * @return \Cake\Datasource\RepositoryInterface
<ide> */
<del> public function getRepository()
<add> public function getRepository(): RepositoryInterface
<ide> {
<ide> return $this->_repository;
<ide> }
<ide> public function getRepository()
<ide> *
<ide> * This method is most useful when combined with results stored in a persistent cache.
<ide> *
<del> * @param \Cake\Datasource\ResultSetInterface $results The results this query should return.
<add> * @param \Cake\Datasource\ResultSetInterface|array $results The results this query should return.
<ide> * @return $this
<ide> */
<ide> public function setResult($results)
<ide> public function isEagerLoaded(): bool
<ide> * @param bool $value Whether or not to eager load.
<ide> * @return $this
<ide> */
<del> public function eagerLoaded($value)
<add> public function eagerLoaded(bool $value)
<ide> {
<ide> $this->_eagerLoaded = $value;
<ide>
<ide> public function aliasField(string $field, ?string $alias = null): array
<ide> * @param string|null $defaultAlias The default alias
<ide> * @return array
<ide> */
<del> public function aliasFields(array $fields, $defaultAlias = null): array
<add> public function aliasFields(array $fields, ?string $defaultAlias = null): array
<ide> {
<ide> $aliased = [];
<ide> foreach ($fields as $alias => $field) {
<ide> public function aliasFields(array $fields, $defaultAlias = null): array
<ide> * ResultSetDecorator is a traversable object that implements the methods found
<ide> * on Cake\Collection\Collection.
<ide> *
<del> * @return \Cake\Datasource\ResultSetInterface
<add> * @return \Cake\Datasource\ResultSetInterface|array
<ide> */
<ide> public function all()
<ide> {
<ide> public function formatResults(?callable $formatter = null, $mode = 0)
<ide> *
<ide> * @return array
<ide> */
<del> public function getResultFormatters()
<add> public function getResultFormatters(): array
<ide> {
<ide> return $this->_formatters;
<ide> }
<ide> public function getOptions(): array
<ide> * @return mixed
<ide> * @throws \BadMethodCallException if no such method exists in result set
<ide> */
<del> public function __call($method, $arguments)
<add> public function __call(string $method, array $arguments)
<ide> {
<ide> $resultSetClass = $this->_decoratorClass();
<ide> if (in_array($method, get_class_methods($resultSetClass), true)) {
<ide> abstract public function applyOptions(array $options);
<ide> *
<ide> * @return \Traversable
<ide> */
<del> abstract protected function _execute();
<add> abstract protected function _execute(): Traversable;
<ide>
<ide> /**
<ide> * Decorates the results iterator with MapReduce routines and formatters
<ide> *
<ide> * @param \Traversable $result Original results
<ide> * @return \Cake\Datasource\ResultSetInterface
<ide> */
<del> protected function _decorateResults($result)
<add> protected function _decorateResults(Traversable $result): ResultSetInterface
<ide> {
<ide> $decorator = $this->_decoratorClass();
<ide> foreach ($this->_mapReduce as $functions) {
<ide> protected function _decorateResults($result)
<ide> *
<ide> * @return string
<ide> */
<del> protected function _decoratorClass()
<add> protected function _decoratorClass(): string
<ide> {
<ide> return ResultSetDecorator::class;
<ide> }
<ide><path>src/Datasource/RuleInvoker.php
<ide> class RuleInvoker
<ide> /**
<ide> * The rule name
<ide> *
<del> * @var string
<add> * @var string|null
<ide> */
<ide> protected $name;
<ide>
<ide> class RuleInvoker
<ide> * rule $scope.
<ide> *
<ide> * @param callable $rule The rule to be invoked.
<del> * @param string $name The name of the rule. Used in error messsages.
<add> * @param ?string $name The name of the rule. Used in error messsages.
<ide> * @param array $options The options for the rule. See above.
<ide> */
<del> public function __construct(callable $rule, $name, array $options = [])
<add> public function __construct(callable $rule, ?string $name, array $options = [])
<ide> {
<ide> $this->rule = $rule;
<ide> $this->name = $name;
<ide><path>src/ORM/Query.php
<ide> public function __call($method, $arguments)
<ide> /**
<ide> * @inheritDoc
<ide> */
<del> public function __debugInfo()
<add> public function __debugInfo(): array
<ide> {
<ide> $eagerLoader = $this->getEagerLoader();
<ide> | 12 |
Text | Text | add morphology and morphanalysis to overview | d3385f4be254bfb3a36ab8404ede3509e9bc7dc6 | <ide><path>website/docs/usage/101/_architecture.md
<ide> an **annotated document**. It also orchestrates training and serialization.
<ide> | [`Span`](/api/span) | A slice from a `Doc` object. |
<ide> | [`Token`](/api/token) | An individual token — i.e. a word, punctuation symbol, whitespace, etc. |
<ide> | [`Lexeme`](/api/lexeme) | An entry in the vocabulary. It's a word type with no context, as opposed to a word token. It therefore has no part-of-speech tag, dependency parse etc. |
<add>| [`MorphAnalysis`](/api/morphanalysis) | A morphological analysis. |
<ide>
<ide> ### Processing pipeline {#architecture-pipeline}
<ide>
<ide> an **annotated document**. It also orchestrates training and serialization.
<ide> | [`Language`](/api/language) | A text-processing pipeline. Usually you'll load this once per process as `nlp` and pass the instance around your application. |
<ide> | [`Tokenizer`](/api/tokenizer) | Segment text, and create `Doc` objects with the discovered segment boundaries. |
<ide> | [`Lemmatizer`](/api/lemmatizer) | Determine the base forms of words. |
<del>| `Morphology` | Assign linguistic features like lemmas, noun case, verb tense etc. based on the word and its part-of-speech tag. |
<add>| [`Morphology`](/api/morphology) | Assign linguistic features like lemmas, noun case, verb tense etc. based on the word and its part-of-speech tag. |
<ide> | [`Tagger`](/api/tagger) | Annotate part-of-speech tags on `Doc` objects. |
<ide> | [`DependencyParser`](/api/dependencyparser) | Annotate syntactic dependencies on `Doc` objects. |
<ide> | [`EntityRecognizer`](/api/entityrecognizer) | Annotate named entities, e.g. persons or products, on `Doc` objects. | | 1 |
Python | Python | use absolute imports in test files | 7bbf2bca11bee820086465853e5a6e813b4d02da | <ide><path>numpy/core/tests/test_longdouble.py
<ide> from numpy.testing import (
<ide> assert_, assert_equal, assert_raises, assert_array_equal, temppath,
<ide> )
<del>from ._locales import CommaDecimalPointLocale
<add>from numpy.core.tests._locales import CommaDecimalPointLocale
<ide>
<ide> LD_INFO = np.finfo(np.longdouble)
<ide> longdouble_longer_than_double = (LD_INFO.eps < np.finfo(np.double).eps)
<ide><path>numpy/core/tests/test_multiarray.py
<ide> assert_allclose, IS_PYPY, HAS_REFCOUNT, assert_array_less, runstring,
<ide> SkipTest, temppath, suppress_warnings
<ide> )
<del>from ._locales import CommaDecimalPointLocale
<add>from numpy.core.tests._locales import CommaDecimalPointLocale
<ide>
<ide> # Need to test an object that does not fully implement math interface
<ide> from datetime import timedelta, datetime
<ide><path>numpy/core/tests/test_print.py
<ide>
<ide> import numpy as np
<ide> from numpy.testing import assert_, assert_equal, SkipTest
<del>from ._locales import CommaDecimalPointLocale
<add>from numpy.core.tests._locales import CommaDecimalPointLocale
<ide>
<ide>
<ide> if sys.version_info[0] >= 3: | 3 |
Text | Text | improve i18n contribution guidelines | 40d7e04a61601121171bf1908d6dd9259c3a2506 | <ide><path>docs/FAQ.md
<ide>
<ide> Read our ["How to Contribute to Open Source Guide"](https://github.com/freeCodeCamp/how-to-contribute-to-open-source). It's a comprehensive reference for first-timer-friendly projects. And it includes a lot of open source contribution tips.
<ide>
<del>### Can I translate freeCodeCamp's curriculum?
<add>### Can I translate freeCodeCamp's resources?
<ide>
<del>Yes - Read [this guide](/how-to-translate-files) if you are interested in contributing to translations.
<add>Yes - You can contribute to any of the 30+ languages we have enabled on our translation platform.
<ide>
<del>Currently we have the user contributed translations being done in Chinese and Español. We intend to localize freeCodeCamp into several major world languages. You can read all about this in our [announcement here](https://www.freecodecamp.org/news/world-language-translation-effort).
<add>We have the user contributed translations live in Chinese (中文) and Spanish (Español). We intend to localize freeCodeCamp into several major world languages. You can read all about this in our [announcement here](https://www.freecodecamp.org/news/world-language-translation-effort).
<add>
<add>If you are interested in contributing to translations please makes sure you [read this guide](/how-to-translate-files) first.
<ide>
<ide> ### How can I report a new bug?
<ide>
<ide><path>docs/_sidebar.md
<ide> - [Work on the news theme](how-to-work-on-the-news-theme.md)
<ide> - [Work on the docs theme](how-to-work-on-the-docs-theme.md)
<ide> - **Translation Contribution**
<del> - [Translating a Curriculum File](how-to-translate-files.md)
<del> - [Proofreading a Curriculum File](how-to-proofread-files.md)
<del> - [How to Translate the Website](how-to-translate-the-website.md)
<add> - [Work on translating resources](how-to-translate-files.md)
<add> - [Work on proofreading translations](how-to-proofread-files.md)
<ide> - **Optional Guides**
<del> - [Set up freeCodeCamp on Windows(WSL)](how-to-setup-wsl.md)
<add> - [Set up freeCodeCamp on Windows (WSL)](how-to-setup-wsl.md)
<ide> - [Add Cypress tests](how-to-add-cypress-tests.md)
<add> - [Work on localized client web app](how-to-work-on-localized-client-webapp.md)
<ide> - [Catch outgoing emails locally](how-to-catch-outgoing-emails-locally.md)
<ide>
<ide> ---
<ide><path>docs/how-to-proofread-files.md
<ide> # How to Proofread Translations
<ide>
<del>Our proofreading team is responsible for ensuring that translations accurately reflect the source text.
<add>Our proofreading team is responsible for ensuring that translations accurately reflect the source text. We trust our proofreaders to ensure that we have very high quality translations.
<ide>
<del>To begin proofreading, visit [our translation site](https://translate.freecodecamp.org) and login. Then select "Go to console" in the top navigation bar to switch from the public view to the workspace view.
<add>All our translations are done by hand, by real humans. Proofreading ensures that there is a consistent tone across our all our translated resources like the curriculum.
<add>
<add>To begin proofreading, visit [our translation platform](https://translate.freecodecamp.org) and login. Select "Go to console" in the top navigation bar to switch from the public view to the workspace view.
<ide>
<ide> ## Select a File
<ide>
<ide> You should now see the list of available files. Choose your file by selecting th
<ide>
<ide> Here you will see the list of strings in the selected file, with their related translations. The translation that is displayed here is the translation that has received the highest score (between upvotes and downvotes) from the translation community.
<ide>
<del>While you can view *all* proposed translations for a given string, the community scores (determined by the upvotes and downvotes) should be taken into consideration when choosing which translation to approve. The community can review proposed translations and recommend which one is most accurate and clear.
<add>While you can view _all_ proposed translations for a given string, the community scores (determined by the upvotes and downvotes) should be taken into consideration when choosing which translation to approve. The community can review proposed translations and recommend which one is most accurate and clear.
<ide>
<ide> 1. This is the original string (in English).
<ide> 2. This is the matching translated string. The most popular translation proposal, based on upvotes and downvotes, will be displayed here.
<ide> 3. Clicking this checkmark button will approve that translation.
<del>4. Crowdin will display the status of each string. `Done` means a translation has been approved and will be downloaded on our next Crowdin pull. `Todo` means the string has not been proofread. `Hidden` means the string is locked and *should not be translated*. `Comment` means the string has a related comment.
<add>4. Crowdin will display the status of each string. `Done` means a translation has been approved and will be downloaded on our next Crowdin pull. `Todo` means the string has not been proofread. `Hidden` means the string is locked and _should not be translated_. `Comment` means the string has a related comment.
<ide> 5. Translations can be selected with the checkboxes and approved here in one bulk action.
<ide> 6. You can view the community proposed translations, their popularity scores, and Crowdin suggested translations here.
<ide> 7. This button shows/hides the right-hand side display pane, where you can view translations, comments, translation memory, and glossary terms.
<ide> 8. Crowdin displays error messages here from the quality assurance checks. In other words, if something does not seem correct in the translation, Crowdin will notify you. These translations should be approved with care.
<ide>
<del>> [!WARNING]
<add>No additional actions are required once a file has been proofread.
<add>
<add>> [!NOTE]
<ide> > Approving a string in the proofreading view will mark it as complete and it will be downloaded in our next pull from Crowdin to GitHub.
<ide>
<del>No additional actions are required once a file has been proofread. If you have any questions, or are interested in becoming a proofreader, feel free to reach out to us in our [translators chat room](https://chat.freecodecamp.org/channel/translators). If you are already a proofreader and are interested in having a dedicated channel for a specific language, [fill out our form](https://forms.gle/XU5CyutrYCgDYaVZA).
<add>## Becoming a proofreader
<add>
<add>If you have any questions, or are interested in becoming a proofreader, feel free to reach out to us in our [translators chat room](https://chat.freecodecamp.org/channel/translators). We will typically grant you proofreading access if you have been contributing to freeCodeCamp for a while.
<add>
<add>Our staff team and community moderators teams are always looking for kind volunteers like you who help us make high quality translations available to the world.
<ide>
<ide> > [!NOTE]
<ide> > Crowdin will allow you to approve your translations. In general, it is best to allow another proofreader to review your proposed translations as extra safety to ensure there are no errors.
<add>
<add>## Creating a channel on Chat for a world language
<add>
<add>For the most part we encourage you to use the [translators chat](https://chat.freecodecamp.org/channel/translators) room for all correspondence. However if the team of volunteer translators grows for a certain language, we can consider creating additional break-out channel for the language.
<add>
<add>If you are already a proofreader and are interested in having a dedicated channel on our chat servers for a specific language, [fill out this form](https://forms.gle/XU5CyutrYCgDYaVZA).
<ide><path>docs/how-to-translate-files.md
<del># How to Translate a File
<add># How to Translate freeCodeCamp's resources
<ide>
<del>> [!NOTE]
<del>> All translations are handled through https://translate.freecodecamp.org - we are no longer using GitHub to translate files directly.
<add>It's our dream to provide you with the resources to learn, no matter the world language you speak. To help us with this massive effort, we have integrated our open-source code-base & curriculum with [Crowdin](https://crowdin.com/) - A tool to help us localize our code-base.
<add>
<add>The translation workflow is split into two main activities:
<add>
<add>- **Translating** curriculum files, documentation and UI elements like buttons, labels, etc.:
<add>
<add> As a translator you can sign up on [our translation platform](https://translate.freecodecamp.org) and contribute translations in any of the 30+ languages enabled in there. If you do not see a language that you speak and are interested in translating, [visit this frequently asked question](/FAQ?id=can-i-translate-freecodecamp39s-resources).
<add>
<add>- **Proofreading** the translations for all of the above.
<add>
<add> Proofreaders verify that the community contributed translations are uniform in tone and free of common issues like typos, etc. In short, they ensure that the quality of translations is high. Note that we do not use machine translations for a reason.
<add>
<add>> [!WARNING]
<add>> We are no longer using GitHub to translate files directly, if you are a returning contributor head to our [translation platform](https://translate.freecodecamp.org/) instead.
<add>
<add>## Prepare yourself for contributions
<add>
<add>> The freeCodeCamp Localization Roadmap – There Are No Speed Limits
<add>
<add>You can translate as much as you want, when you want. It's only a matter of how much time and energy you are willing to invest as a volunteer translator.
<add>
<add>We just ask that you understand the following:
<add>
<add>1. **Translations are a team effort.**
<add>
<add> Translating freeCodeCamp's resources is one of the most fun and rewarding experiences as a contributor, and it works best if you involve your friends and colleagues who speak the same world language as you.
<add>
<add> We recommend joining [our community forum](https://forum.freecodecamp.org/c/contributors/3) and [translators chat room](https://chat.freecodecamp.org/channel/translators) with your friends and showing your interest before starting off with translations. Crowdin makes it easy to contribute translations, but it's still a lot of work.
<add>
<add> We want you to enjoy contributing and not burn out or lose interest.
<add>
<add> A small group of 4-5 individuals is a good size to start your niche for your world language. You can then recruit even more friends to join the team.
<ide>
<del>To begin, head to our translation website and login (if you have not contributed to translations before, you will need to create an account).
<add>2. **It costs quite a lot to spin servers for each language.**
<add>
<add> On the surface it might not seem how complicated the technical stack is, but it costs quite a lot to keep the engines running. This includes provisioning additional servers and dedicating staff to look after them.
<add>
<add> freeCodeCamp.org is committed to providing these for free as always, however we need to prioritize resources for those who need it the most. The last thing we want is to shutdown servers for a language if the translation activity dies off & things become outdated.
<add>
<add> Once a language reaches at least a few certifications on the curriculum we can begin deploying the language live on [`/learn`](https://www.freecodecamp.org/learn), while you continue to translate the remaining certifications.
<add>
<add> For example, we would want to deploy at least the entire front-end certifications suite when we ship a new world language for the first time.
<add>
<add>3. **But what about the languages not listed on the translation platform?**
<add>
<add> We have looked at our user base and added 30+ most widely spoken languages to the list of enabled languages on the translations platform. Some languages like Chinese and Spanish are already deployed live on **"/learn"** at this moment.
<add>
<add> Unfortunately, the list does not include hundreds of languages out there. We get dozens of requests from contributors like you every day who want to help translate the site into a language they speak.
<add>
<add> We are definitely looking forward to adding more languages to the list, but as you may already guess, it would only be feasible if we get enough momentum around a world language.
<add>
<add> If you would like us to include a new world language, we recommend getting your friends excited about this.
<add>
<add> Once you have a small group of people (at least 4-5) interested and committed, we can hop on a call. We will explain all the details and walk you through some of the tools and processes.
<add>
<add>## Getting started
<add>
<add>First, make sure you come say "Hi" in our [translators chat room](https://chat.freecodecamp.org/channel/translators). We post regular updates about translating resources and answer a lot of your queries in there.
<add>
<add>Next, head to our [translation platform](https://translate.freecodecamp.org/) and login (if you have not contributed to translations before, you will need to create an account).
<add>
<add>Finally, go through the detailed walk-thru below to understand the translation tools and workflows at your disposal.
<add>
<add>Happy translating.
<ide>
<ide> ## Select a Project and File
<ide>
<del>You should see two "projects" available for translation: The `Contributing Documentation` project, which contains the files for this documentation site, and the `Coding Curriculum` project, which contains our challenge files for `/learn`.
<add>Once you visit the translation platform, you should see multiple "projects" available for translation:
<add>
<add>1. [Contributing documentation](https://translate.freecodecamp.org/contributing-docs) project, which contains the files for this documentation site.
<add>2. [Coding Curriculum](https://translate.freecodecamp.org/curriculum) project, which contains our challenge files for our curriculum.
<add>3. [Learn User Interface](https://translate.freecodecamp.org/learn-ui) project which contains strings for UI elements like buttons, labels, etc. for our learning platform.
<ide>
<del>Select which project you want to contribute to, and you will see a list of available languages for translation.
<add>Select any project you want to contribute to, and you will see a list of available languages for translation.
<ide>
<ide> 
<ide>
<ide> Select a file to work on and Crowdin will open the editor view.
<ide> > [!NOTE]
<ide> > When the editor view opens, you will need to click the settings icon (shown as a gear) and switch the 'HTML tags displaying' setting to 'SHOW'. This will ensure you can see tags such as `<code></code>` instead of `<0></0>`.
<ide>
<del>## Translate the File
<add>## Translate Curriculum
<ide>
<ide> 
<ide>
<ide> You are welcome to translate as many strings as you like - there are no addition
<ide> > [!NOTE]
<ide> > If you see something in the English source file that is inaccurate or incorrect, please do not fix it through the translation flow. Instead, leave a comment on the string to notify us that there is a discrepancy, or create a GitHub issue.
<ide>
<del>### Translating Documentation
<add>## Translate Documentation
<ide>
<ide> Translating our contributing documentation is a similar flow to translating our curriculum files.
<ide>
<ide><path>docs/how-to-translate-the-website.md
<del>The client/react side of our website is translated into various world languages using [react-i18next](https://react.i18next.com/) and [i18next](https://www.i18next.com/).
<del>
<del>> [!NOTE]
<del>> Curriculum lesson content is [translated separately](./how-to-translate-files.md).
<del>
<del>## File Structure
<del>
<del>The files for translating the website are located in the `client/i18n` folder. Each language has a folder within that containing JSON files with the translations.
<del>
<del>The values in the `translations.json` file contain the majority of the text that appears on the website. The keys are used in the codebase to get the correct text for whatever language is set. This file needs to have the exact same keys in all languages.
<del>
<del>The `intro.json` file contains the key-value pairs for the introduction text on the certification pages.
<del>
<del>The `motivation.json` files are not required to have the same quotes, compliments, or array length. Just the same JSON structure. These are not translated via Crowdin.
<del>
<del>The `trending.json` file contians the titles and links for the trending news articles in the website's footer. These are not translated via Crowdin.
<del>
<del>The `meta-tags.json` file contains the information for our website's meta tag information. These are not translated via Crowdin.
<del>
<del>## Adding a Language
<del>
<del>To add a new language, create a folder with the language name as the title next to the other languages and copy the JSON files from another language into your new folder.
<del>
<del>In the `all-langs.js` file, add the language to the `client` array in the first variable. Then, follow the instructions in the comments to add the rest of the necessary variables.
<del>
<del>## How to Translate
<del>
<del>Translating the `intro.json` and `translations.json` are done through [our translation site](https://translate.freecodecamp.org). View our [translation documentation for that site](/how-to-translate-files.md).
<del>
<del>Modifications to the `trending.json`, `meta-tags.json`, and `motivation.json` files should typically only be done by staff.
<del>
<del>## Running it Locally
<del>
<del>Set the `CLIENT_LOCALE` variable in your `.env` file to the locale you want to build.
<del>
<del>> [!NOTE]
<del>> The value needs to be one of the client languages available in `config/i18n/all-langs.js`
<del>
<del>## How to Structure Components
<del>
<del>### Functional Component
<del>
<del>```js
<del>import { useTranslation } from 'react-i18next';
<del>
<del>// in the render method:
<del>const { t } = useTranslation();
<del>
<del>// call the "t" function with a key from the JSON file:
<del><p>{t('key')}</p> // more details below
<del>```
<del>
<del>### Class Component
<del>```js
<del>import { withTranslation } from 'react-i18next';
<del>
<del>// withTranslation adds the "t" function to props:
<del>const { t } = this.props;
<del>
<del>// call the "t" function with a key from the JSON file:
<del><h1>{t('key')}</h1> // more details below
<del>
<del>// export without redux:
<del>export default withTranslation()(Component);
<del>
<del>// or with redux:
<del>export default connect(...)(withTranslation()(Component));
<del>```
<del>
<del>## Translate Using the "t" Function
<del>
<del>### Basic Translation
<del>
<del>```js
<del>// in the component:
<del><p>{t('p1')}</p>
<del>
<del>// in the JSON file:
<del>{
<del> "p1": "My paragraph"
<del>}
<del>
<del>// output:
<del><p>My paragraph</p>
<del>```
<del>
<del>### With Dynamic Data
<del>
<del>```js
<del>// in the component:
<del>const username = 'moT';
<del>
<del><p>{t('welcome', { username: username })}</p>
<del>
<del>// in the JSON file:
<del>{
<del> "welcome": "Welcome {{username}}"
<del>}
<del>
<del>// output:
<del><p>Welcome moT</p>
<del>```
<del>
<del>The above example passes an object to the `t` function with a `username` variable. The variable will be used in the JSON value where `{{username}}` is.
<del>
<del>## Translate with the `Trans` Component
<del>
<del>The general rule is to use the "t" function when you can. But there's a `Trans` component for when that isn't enough, usually when you have elements embedded in the text. You can use the `Trans` component with any type of react component.
<del>
<del>### Basic Elements Nested
<del>
<del>```js
<del>// in the component:
<del>import { Trans } from 'react-i18next'
<del>
<del><p>
<del> <Trans>fcc.greeting</Trans>
<del></p>
<del>
<del>// in the JSON file:
<del>{
<del> "fcc": {
<del> "greeting": "Welcome to <strong>freeCodeCamp</strong>"
<del> }
<del>}
<del>
<del>// output:
<del><p>Welcome to <strong>freeCodeCamp</strong></p>
<del>```
<del>
<del>You can place the key inside the component tags like the above example if the text contains "simple" tags with no attributes. `br`, `strong`, `i`, and `p` are the default, but that list can be expanded in the i18n config.
<del>
<del>### Complex Elements Nested
<del>
<del>Other times, you will want to have certain text inside another element, an anchor tag is a good example:
<del>
<del>```js
<del>// in the component:
<del><p>
<del> <Trans i18nKey='check-forum'>
<del> <a href='https://forum.freecodecamp.org/'>placeholder</a>
<del> </Trans>
<del></p>
<del>
<del>// in the JSON file:
<del>{
<del> "check-forum": "Check out <0>our forum</0>."
<del>}
<del>
<del>// output:
<del><p>Check out <a href='https://forum.freecodecamp.org/'>our forum</a></p>
<del>```
<del>
<del>In the above example, the key is set in the attributes of the `Trans` component. The `<0>` and `</0>` in the JSON represent the first child of the component, in this case, the anchor element. If there were more children, they would just count up from there using the same syntax. You can find the children of a component in the react dev tools by inspecting it. `placeholder` is simply there because the linter was complaining at me about an empty `<a>` element.
<del>
<del>### With a Variable
<del>
<del>```js
<del>// in the component:
<del>const email = '[email protected]';
<del>
<del><p>
<del> <Trans email={email} i18nKey='fcc.email'>
<del> <a href={`mailto:${email}`}>
<del> {{ email }}
<del> </a>
<del> </Trans>
<del></p>
<del>
<del>// in the JSON file:
<del>{
<del> "fcc": {
<del> "email": "Send us an email at: <0>{{email}}</0>"
<del> }
<del>}
<del>
<del>// output:
<del><p>Send us an email at: <a href='mailto:[email protected]'>[email protected]</a><p>
<del>```
<del>
<del>In the above example, the key and a variable are set in the attributes of the `Trans` component. `{{ email }}` needs to be somewhere in the `Trans` component as well, it doesn't matter where.
<del>
<del>## Changing Text
<del>
<del>To change text on the client side of things, go to the relevant `.json` file, find the key that is being used in the React component, and change the value to the new text you want. You should search the codebase for that key to make sure it isn't being used elsewhere. Or, if it is, that the changes make sense in all places.
<del>
<del>## Adding Text
<del>
<del>If the text you want to add to the client exists in the relevant `.json` file, use the existing key. Otherwise, create a new key.
<del>
<del>The English file is the "source of truth" for all of the `.json` files sharing the same name. If you need to add a new key, add it there. Then, add the key to **all** of the `translations.json` files.
<del>
<del>> [!NOTE]
<del>> Use English text for all languages if the file is translated through Crowdin. The tests will fail if you don't.
<del>
<del>It would be nice to keep the keys in the same order across all the files as well. Also, try to put all punctuation, spacing, quotes, etc in the JSON files and not in the components or server files.
<del>
<del>> [!NOTE]
<del>> The underscore (`_`) is a reserved character for keys in the client side files. See [the documentation](https://www.i18next.com/translation-function/plurals) for how they are used.
<del>
<del>## Helpful Documentation
<del>
<del>- [react-i18next docs](https://react.i18next.com/latest/usetranslation-hook)
<del>- [i18next docs](https://www.i18next.com/translation-function/essentials)
<ide><path>docs/how-to-work-on-localized-client-webapp.md
<add># How to work on localized client webapp
<add>
<add>The react based client web app that powers our learning platform is built using Gatsby. It is translated into various world languages using [react-i18next](https://react.i18next.com/) and [i18next](https://www.i18next.com/).
<add>
<add>You can learn more about setting up the client application locally for development by following [our local setup guide here](/how-to-setup-freecodecamp-locally). By default the application is available only in English.
<add>
<add>Once you have setup the project locally you should be able to follow this documentation to run the client in the language of your choice from the list of available languages.
<add>
<add>This could be helpful when you are working on a feature that specifically targets something that involves localization, and requires you to validate for instance a button's label in a different language.
<add>
<add>> [!TIP]
<add>> You do not need to follow this document for translating freeCodeCamp's curriculum or contributing documentation. Read [this guide here](./how-to-translate-files.md) instead.
<add>
<add>Let's understand how the i18n frameworks and tooling work.
<add>
<add>## File Structure
<add>
<add>Most of files for translating the platform are located in the [`client/i18n`](https://github.com/freeCodeCamp/freeCodeCamp/tree/main/client/i18n) folder. Each language has a directory within that containing JSON files with the translations.
<add>
<add>```console
<add> config/i18n
<add> └── all-langs.js
<add> ...
<add> client/i18n
<add> ├── configForTests.js
<add> ├── config.js
<add> ├── locales
<add> │ ├── chinese
<add> │ │ ├── intro.json
<add> │ │ ├── links.json
<add> │ │ ├── meta-tags.json
<add> │ │ ├── motivation.json
<add> │ │ ├── translations.json
<add> │ │ └── trending.json
<add> ... ...
<add> │ ├── dothraki
<add> │ │ ├── intro.json
<add> │ │ ├── links.json
<add> │ │ ├── meta-tags.json
<add> │ │ ├── motivation.json
<add> │ │ ├── translations.json
<add> │ │ └── trending.json
<add> ... ...
<add> │ ├── english
<add> │ │ ├── intro.json
<add> │ │ ├── links.json
<add> │ │ ├── meta-tags.json
<add> │ │ ├── motivation.json
<add> │ │ ├── translations.json
<add> │ │ └── trending.json
<add> │ └── espanol
<add> │ ├── intro.json
<add> │ ├── links.json
<add> │ ├── meta-tags.json
<add> │ ├── motivation.json
<add> │ ├── translations.json
<add> │ └── trending.json
<add> ├── locales.test.js
<add> ├── schema-validation.js
<add> └── validate-keys.js
<add>```
<add>
<add>Some of these files are translated on our translation platform (Crowdin), some are not.
<add>
<add>**Files translated on our translation platform:**
<add>
<add>- The `translations.json` file contains the majority of the text that appears on the user interface elements. The keys are used in the codebase to get the correct text for whatever language is set. This file needs to have the exact same keys in all languages.
<add>
<add>- The `intro.json` file contains the key-value pairs for the introduction text on the certification pages.
<add>
<add> If you want to add/update translations for the keys please [read this guide here](/how-to-translate-files.md).
<add>
<add>**Files NOT translated on our translations platform:**
<add>
<add>- The `motivation.json` files are not required to have the same quotes, compliments, or array length. Just the same JSON structure.
<add>
<add>- The `trending.json` file contains the titles and links for the trending news articles in the website's footer.
<add>
<add>- The `meta-tags.json` file contains the information for our website's meta tag information.
<add>
<add> Changes to these files are typically done by the staff team. If you see something out of the ordinary we recommend you reach us in the [translators chat room](https://chat.freecodecamp.org/channel/translators).
<add>
<add>## Testing the client app in a world language
<add>
<add>You can test the client app in any language available in the [list of languages here](https://github.com/freeCodeCamp/freeCodeCamp/blob/6b4a6a02568b809fc216ea8566ff5df446d1da4e/config/i18n/all-langs.js#L5).
<add>
<add>```js
<add> const availableLangs = {
<add> client: ['english', 'espanol', 'chinese'],
<add> ...
<add> };
<add>```
<add>
<add>If you are testing a new language, create a folder with the language name as the title next to the other languages and copy the JSON files from another language into your new folder.
<add>
<add>Add the language to the `client` array as seen above in the [`config/i18n/all-langs.js`](https://github.com/freeCodeCamp/freeCodeCamp/blob/main/config/i18n/all-langs.js) file.
<add>
<add>Next, follow the instructions in the comments in the same file to add/update the rest of the variables as needed.
<add>
<add>Finally, set the `CLIENT_LOCALE` variable in your `.env` file to the locale you want to build and you're ready.
<add>
<add>## How to Structure Components
<add>
<add>If you are working on a feature or a bug for the client web app, say for example adding new UI items on the settings page, you should follow the guidelines below. They will help you prepare the components for localization into all the supported world languages.
<add>
<add>### Functional Component
<add>
<add>```js
<add>import { useTranslation } from 'react-i18next';
<add>
<add>// in the render method:
<add>const { t } = useTranslation();
<add>
<add>// call the "t" function with a key from the JSON file:
<add><p>{t('key')}</p>; // more details below
<add>```
<add>
<add>### Class Component
<add>
<add>```js
<add>import { withTranslation } from 'react-i18next';
<add>
<add>// withTranslation adds the "t" function to props:
<add>const { t } = this.props;
<add>
<add>// call the "t" function with a key from the JSON file:
<add><h1>{t('key')}</h1> // more details below
<add>
<add>// export without redux:
<add>export default withTranslation()(Component);
<add>
<add>// or with redux:
<add>export default connect(...)(withTranslation()(Component));
<add>```
<add>
<add>## Translate Using the "t" Function
<add>
<add>### Basic Translation
<add>
<add>```js
<add>// in the component:
<add><p>{t('p1')}</p>
<add>
<add>// in the JSON file:
<add>{
<add> "p1": "My paragraph"
<add>}
<add>
<add>// output:
<add><p>My paragraph</p>
<add>```
<add>
<add>### With Dynamic Data
<add>
<add>```js
<add>// in the component:
<add>const username = 'moT';
<add>
<add><p>{t('welcome', { username: username })}</p>
<add>
<add>// in the JSON file:
<add>{
<add> "welcome": "Welcome {{username}}"
<add>}
<add>
<add>// output:
<add><p>Welcome moT</p>
<add>```
<add>
<add>The above example passes an object to the `t` function with a `username` variable. The variable will be used in the JSON value where `{{username}}` is.
<add>
<add>## Translate with the `Trans` Component
<add>
<add>The general rule is to use the "t" function when you can. But there's a `Trans` component for when that isn't enough, usually when you have elements embedded in the text. You can use the `Trans` component with any type of react component.
<add>
<add>### Basic Elements Nested
<add>
<add>```js
<add>// in the component:
<add>import { Trans } from 'react-i18next'
<add>
<add><p>
<add> <Trans>fcc.greeting</Trans>
<add></p>
<add>
<add>// in the JSON file:
<add>{
<add> "fcc": {
<add> "greeting": "Welcome to <strong>freeCodeCamp</strong>"
<add> }
<add>}
<add>
<add>// output:
<add><p>Welcome to <strong>freeCodeCamp</strong></p>
<add>```
<add>
<add>You can place the key inside the component tags like the above example if the text contains "simple" tags with no attributes. `br`, `strong`, `i`, and `p` are the default, but that list can be expanded in the i18n config.
<add>
<add>### Complex Elements Nested
<add>
<add>Other times, you will want to have certain text inside another element, an anchor tag is a good example:
<add>
<add>```js
<add>// in the component:
<add><p>
<add> <Trans i18nKey='check-forum'>
<add> <a href='https://forum.freecodecamp.org/'>placeholder</a>
<add> </Trans>
<add></p>
<add>
<add>// in the JSON file:
<add>{
<add> "check-forum": "Check out <0>our forum</0>."
<add>}
<add>
<add>// output:
<add><p>Check out <a href='https://forum.freecodecamp.org/'>our forum</a></p>
<add>```
<add>
<add>In the above example, the key is set in the attributes of the `Trans` component. The `<0>` and `</0>` in the JSON represent the first child of the component, in this case, the anchor element. If there were more children, they would just count up from there using the same syntax. You can find the children of a component in the react dev tools by inspecting it. `placeholder` is simply there because the linter complains about empty `<a>` elements.
<add>
<add>### With a Variable
<add>
<add>```js
<add>// in the component:
<add>const email = '[email protected]';
<add>
<add><p>
<add> <Trans email={email} i18nKey='fcc.email'>
<add> <a href={`mailto:${email}`}>
<add> {{ email }}
<add> </a>
<add> </Trans>
<add></p>
<add>
<add>// in the JSON file:
<add>{
<add> "fcc": {
<add> "email": "Send us an email at: <0>{{email}}</0>"
<add> }
<add>}
<add>
<add>// output:
<add><p>Send us an email at: <a href='mailto:[email protected]'>[email protected]</a><p>
<add>```
<add>
<add>In the above example, the key and a variable are set in the attributes of the `Trans` component. `{{ email }}` needs to be somewhere in the `Trans` component as well, it doesn't matter where.
<add>
<add>## Changing Text
<add>
<add>To change text on the client side of things, go to the relevant `.json` file, find the key that is being used in the React component, and change the value to the new text you want. You should search the codebase for that key to make sure it isn't being used elsewhere. Or, if it is, that the changes make sense in all places.
<add>
<add>## Adding Text
<add>
<add>If the text you want to add to the client exists in the relevant `.json` file, use the existing key. Otherwise, create a new key.
<add>
<add>The English file is the "source of truth" for all of the `.json` files sharing the same name. If you need to add a new key, add it there. Then, add the key to **all** of the `translations.json` files.
<add>
<add>> [!NOTE]
<add>> Use English text for all languages if the file is translated through Crowdin. The tests will fail if you don't.
<add>
<add>It would be nice to keep the keys in the same order across all the files as well. Also, try to put all punctuation, spacing, quotes, etc in the JSON files and not in the components or server files.
<add>
<add>> [!NOTE]
<add>> The underscore (`_`) is a reserved character for keys in the client side files. See [the documentation](https://www.i18next.com/translation-function/plurals) for how they are used.
<add>
<add>## Helpful Documentation
<add>
<add>- [react-i18next docs](https://react.i18next.com/latest/usetranslation-hook)
<add>- [i18next docs](https://www.i18next.com/translation-function/essentials)
<ide><path>docs/index.md
<ide> You can help expand and improve the curriculum. You can also update project user
<ide>
<ide> ## Translations
<ide>
<del>We are localizing freeCodeCamp.org to world languages starting with Chinese and Español. We will be expanding the translations to more languages.
<add>We are localizing freeCodeCamp.org to major world languages. Some of the certifications are already live in [Chinese (中文)](https://chinese.freecodecamp.org/learn) and [Spanish (Español)](https://www.freecodecamp.org/espanol/learn/). We encourage you to read the [announcement here](https://www.freecodecamp.org/news/world-language-translation-effort) and share it your friends to get them excited about this.
<ide>
<del>To help us with this massive effort, we have integrated our open-source code-base & curriculum with [Crowdin](https://crowdin.com/). You can read all about this in our [announcement here](https://www.freecodecamp.org/news/world-language-translation-effort). We encourage you to read the announcement and share it your friends to get them excited about this.
<del>
<del>It's our dream to provide you with the resources to learn, no matter the world language you speak.
<del>
<del>**If you're interested in translating, here are the guides to translate our [curriculum](how-to-translate-files.md), the [learning platform](how-to-translate-the-website.md) and our [Contributing guidelines](https://translate.freecodecamp.org/contributing-docs).**
<add>**If you're interested in translating, here's [how to translate freCodeCamp's resources](how-to-translate-files.md).**
<ide>
<ide> ## Learning Platform
<ide> | 7 |
Javascript | Javascript | set locale for datetime-change-notify test | 80ed0a66b5ac5754168db2e9e6b8021d596a0679 | <ide><path>test/parallel/test-datetime-change-notify.js
<ide> if (!isMainThread)
<ide>
<ide> const assert = require('assert');
<ide>
<del>process.env.TZ = 'Etc/UTC';
<del>assert.match(new Date().toString(), /GMT\+0000/);
<del>
<del>process.env.TZ = 'America/New_York';
<del>assert.match(new Date().toString(), /Eastern (Standard|Daylight) Time/);
<del>
<del>process.env.TZ = 'America/Los_Angeles';
<del>assert.match(new Date().toString(), /Pacific (Standard|Daylight) Time/);
<del>
<del>process.env.TZ = 'Europe/Dublin';
<del>assert.match(new Date().toString(), /Irish/);
<add>const cases = [
<add> {
<add> timeZone: 'Etc/UTC',
<add> expected: /Coordinated Universal Time/,
<add> },
<add> {
<add> timeZone: 'America/New_York',
<add> expected: /Eastern (Standard|Daylight) Time/,
<add> },
<add> {
<add> timeZone: 'America/Los_Angeles',
<add> expected: /Pacific (Standard|Daylight) Time/,
<add> },
<add> {
<add> timeZone: 'Europe/Dublin',
<add> expected: /Irish/,
<add> },
<add>];
<add>
<add>for (const { timeZone, expected } of cases) {
<add> process.env.TZ = timeZone;
<add> const date = new Date().toLocaleString('en-US', { timeZoneName: 'long' });
<add> assert.match(date, expected);
<add>} | 1 |
Text | Text | fix typo in pull_request_template [ci skip] | 71686f09dfd06a8f000d16453d5e24e2e55a03a1 | <ide><path>.github/pull_request_template.md
<ide> benchmarks, or other information.
<ide>
<ide> Finally, if your pull request affects documentation or any non-code
<ide> changes, guidelines for those changes are [available
<del>here](http://guides.rubyonrails.org/contribution_to_ruby_on_rails.html#contributing-to-the-rails-documentation)
<add>here](http://guides.rubyonrails.org/contributing_to_ruby_on_rails.html#contributing-to-the-rails-documentation)
<ide>
<ide> Thanks for contributing to Rails! | 1 |
Ruby | Ruby | fix ci failure due to contain <u+2028> | 660e189c35ddd31fd131c2a360687f39a4ea8081 | <ide><path>actionpack/lib/action_controller/metal/redirecting.rb
<ide> module Redirecting
<ide> # redirect_to post_url(@post), status: 301, flash: { updated_post_id: @post.id }
<ide> # redirect_to({ action: 'atom' }, alert: "Something serious happened")
<ide> #
<del> # Statements after redirect_to in our controller get executed, so redirect_to doesn't stop the execution of the function.
<del>
<ide># To terminate the execution of the function immediately after the redirect_to, use return.
<add> # Statements after +redirect_to+ in our controller get executed, so +redirect_to+ doesn't stop the execution of the function.
<add> # To terminate the execution of the function immediately after the +redirect_to+, use return.
<ide> # redirect_to post_url(@post) and return
<ide> def redirect_to(options = {}, response_status = {})
<ide> raise ActionControllerError.new("Cannot redirect to nil!") unless options | 1 |
PHP | PHP | fix typos and missing boolean flags | ad8045c3e615aa8eb43cbeda1f812627de16aa00 | <ide><path>src/Console/Command/Task/ModelTask.php
<ide> public function execute() {
<ide> public function generate($name) {
<ide> $table = $this->getTable();
<ide>
<del> $object = $this->getTableObject($name, $table);
<del> $associations = $this->getAssociations($object);
<add> $model = $this->getTableObject($name, $table);
<add> $associations = $this->getAssociations($model);
<ide> $primaryKey = $this->getPrimaryKey($model);
<ide> $displayField = $this->getDisplayField($model);
<ide> $fields = $this->getFields($model);
<ide> public function generate($name) {
<ide> $data = compact(
<ide> 'associations', 'primaryKey', 'displayField',
<ide> 'table', 'fields', 'validation', 'behaviors');
<del> $this->bakeEntity($object, $data);
<del> $this->bakeTable($object, $data);
<add> $this->bakeEntity($model, $data);
<add> $this->bakeTable($model, $data);
<ide> $this->bakeFixture($model, $table);
<ide> $this->bakeTest($model);
<ide> }
<ide> public function getOptionParser() {
<ide> ])->addOption('display-field', [
<ide> 'help' => __d('cake_console', 'The displayField if you would like to choose one.')
<ide> ])->addOption('no-test', [
<add> 'boolean' => true,
<ide> 'help' => __d('cake_console', 'Do not generate a test case skeleton.')
<ide> ])->addOption('no-fixture', [
<add> 'boolean' => true,
<ide> 'help' => __d('cake_console', 'Do not generate a test fixture skeleton.')
<ide> ])->epilog(
<ide> __d('cake_console', 'Omitting all arguments and options will list ' . | 1 |
Java | Java | use map.getordefault in getsqltype implementation | c0f4d78ef9b9e03836baa31ac3ada0b4c48197e7 | <ide><path>spring-jdbc/src/main/java/org/springframework/jdbc/core/namedparam/AbstractSqlParameterSource.java
<ide> /*
<del> * Copyright 2002-2016 the original author or authors.
<add> * Copyright 2002-2017 the original author or authors.
<ide> *
<ide> * Licensed under the Apache License, Version 2.0 (the "License");
<ide> * you may not use this file except in compliance with the License.
<ide> public void registerTypeName(String paramName, String typeName) {
<ide> @Override
<ide> public int getSqlType(String paramName) {
<ide> Assert.notNull(paramName, "Parameter name must not be null");
<del> Integer sqlType = this.sqlTypes.get(paramName);
<del> if (sqlType != null) {
<del> return sqlType;
<del> }
<del> return TYPE_UNKNOWN;
<add> return this.sqlTypes.getOrDefault(paramName, TYPE_UNKNOWN);
<ide> }
<ide>
<ide> /** | 1 |
PHP | PHP | add missing braces | 746b8cafdbe0daffd0f918f5a85f5453cf9e4d4b | <ide><path>src/Database/Log/LoggingStatement.php
<ide> class LoggingStatement extends StatementDecorator {
<ide> * Wrapper for the execute function to calculate time spent
<ide> * and log the query afterwards.
<ide> *
<del> * @param array $params list of values to be bound to query
<del> * @return bool true on success, false otherwise
<add> * @param array $params List of values to be bound to query
<add> * @return bool True on success, false otherwise
<ide> * @throws \Exception Re-throws any exception raised during query execution.
<ide> */
<ide> public function execute($params = null) {
<ide> $t = microtime(true);
<del> $query = new LoggedQuery;
<add> $query = new LoggedQuery();
<ide>
<ide> try {
<ide> $result = parent::execute($params);
<ide> public function execute($params = null) {
<ide> * to the logging system.
<ide> *
<ide> * @param \Cake\Database\Log\LoggedQuery $query The query to log.
<del> * @param array $params list of values to be bound to query
<del> * @param float $startTime the microtime when the query was executed
<add> * @param array $params List of values to be bound to query.
<add> * @param float $startTime The microtime when the query was executed.
<ide> * @return void
<ide> */
<ide> protected function _log($query, $params, $startTime) {
<ide> protected function _log($query, $params, $startTime) {
<ide> * Wrapper for bindValue function to gather each parameter to be later used
<ide> * in the logger function.
<ide> *
<del> * @param string|int $column name or param position to be bound
<add> * @param string|int $column Name or param position to be bound
<ide> * @param mixed $value The value to bind to variable in query
<del> * @param string|int $type PDO type or name of configured Type class
<add> * @param string|int|null $type PDO type or name of configured Type class
<ide> * @return void
<ide> */
<ide> public function bindValue($column, $value, $type = 'string') {
<ide> public function bindValue($column, $value, $type = 'string') {
<ide> * Sets the logger object instance. When called with no arguments
<ide> * it returns the currently setup logger instance
<ide> *
<del> * @param object $instance logger object instance
<del> * @return object logger instance
<add> * @param object|null $instance Logger object instance.
<add> * @return object Logger instance
<ide> */
<ide> public function logger($instance = null) {
<ide> if ($instance === null) { | 1 |
Python | Python | remove unused variables in cifar10_cnn | fe48b41c2228b64357bedd1942ab981ef2ad3cbc | <ide><path>examples/cifar10_cnn.py
<ide> epochs = 200
<ide> data_augmentation = True
<ide>
<del># input image dimensions
<del>img_rows, img_cols = 32, 32
<del># The CIFAR10 images are RGB.
<del>img_channels = 3
<del>
<ide> # The data, shuffled and split between train and test sets:
<ide> (x_train, y_train), (x_test, y_test) = cifar10.load_data()
<ide> print('x_train shape:', x_train.shape) | 1 |
Go | Go | fix issue with plugin exit | 890a98ceed982454515f5b089d9772fc1e4eb6e0 | <ide><path>plugin/manager_linux.go
<ide> func (pm *Manager) enable(p *v2.Plugin, force bool) error {
<ide> }
<ide> p.Lock()
<ide> p.Restart = true
<add> p.ExitChan = make(chan bool)
<ide> p.Unlock()
<ide> if err := pm.containerdClient.Create(p.GetID(), "", "", specs.Spec(*spec), attachToLog(p.GetID())); err != nil {
<ide> return err
<ide> func (pm *Manager) Shutdown() {
<ide> }
<ide> if pm.containerdClient != nil && p.IsEnabled() {
<ide> p.Lock()
<del> p.ExitChan = make(chan bool)
<ide> p.Restart = false
<ide> p.Unlock()
<ide> shutdownPlugin(p, pm.containerdClient) | 1 |
PHP | PHP | add some minimizable (boolean) attributes | 94daf3d76665ab101211ca74d86d36951aa5af40 | <ide><path>src/View/StringTemplate.php
<ide> protected function _formatAttribute($key, $value, $escape = true)
<ide> $truthy = [1, '1', true, 'true', $key];
<ide> $isMinimized = isset($this->_compactAttributes[$key]);
<ide> if ($isMinimized && in_array($value, $truthy, true)) {
<del> return "$key";
<add> return "$key=\"$key\"";
<ide> }
<ide> if ($isMinimized) {
<ide> return '';
<ide><path>tests/TestCase/View/StringTemplateTest.php
<ide> public function testFormatAttributesCompact()
<ide> $attrs = ['disabled' => true, 'selected' => 1, 'checked' => '1', 'multiple' => 'multiple'];
<ide> $result = $this->template->formatAttributes($attrs);
<ide> $this->assertEquals(
<del> ' disabled selected checked multiple',
<add> ' disabled="disabled" selected="selected" checked="checked" multiple="multiple"',
<ide> $result
<ide> );
<ide> | 2 |
Python | Python | move setuptools import to the top. thanks iksaif | a394c4966f8d632e42cce784e87dea4a36168e9a | <ide><path>setup.py
<ide> #!/usr/bin/env python
<ide> # -*- coding: utf-8 -*-
<add>
<add>try:
<add> from setuptools import setup, find_packages
<add> from setuptools.command.test import test
<add>except ImportError:
<add> raise
<add> from ez_setup import use_setuptools
<add> use_setuptools()
<add> from setuptools import setup, find_packages # noqa
<add> from setuptools.command.test import test # noqa
<add>
<ide> import os
<ide> import sys
<ide> import codecs
<ide> pass
<ide>
<ide>
<del>try:
<del> from setuptools import setup, find_packages
<del> from setuptools.command.test import test
<del>except ImportError:
<del> raise
<del> from ez_setup import use_setuptools
<del> use_setuptools()
<del> from setuptools import setup, find_packages # noqa
<del> from setuptools.command.test import test # noqa
<del>
<ide> NAME = 'celery'
<ide> entrypoints = {}
<ide> extra = {} | 1 |
Javascript | Javascript | expose hidden docs | 3e12bc481d7a6b089c32e79b45991294d046872f | <ide><path>src/ng/directive/a.js
<ide> 'use strict';
<ide>
<del>/*
<add>/**
<add> * @ngdoc directive
<add> * @name ng.directive:a
<add> * @restrict E
<add> *
<add> * @description
<ide> * Modifies the default behavior of html A tag, so that the default action is prevented when href
<ide> * attribute is empty.
<ide> * | 1 |
Javascript | Javascript | add tests for the click user action | 8abe438b086fd8a54a66981189d3a41eaeddeaae | <ide><path>test/unit/player-user-actions.test.js
<ide> import sinon from 'sinon';
<ide> import TestHelpers from './test-helpers';
<ide> import FullscreenApi from '../../src/js/fullscreen-api.js';
<ide>
<add>QUnit.module('Player: User Actions: Click', {
<add>
<add> beforeEach() {
<add> this.clock = sinon.useFakeTimers();
<add> this.player = TestHelpers.makePlayer({controls: true});
<add> },
<add>
<add> afterEach() {
<add> this.player.dispose();
<add> this.clock.restore();
<add> }
<add>});
<add>
<add>QUnit.test('by default, click toggles play', function(assert) {
<add> let paused = true;
<add>
<add> this.player.paused = () => paused;
<add> this.player.play = sinon.spy();
<add> this.player.pause = sinon.spy();
<add>
<add> this.player.handleTechClick_({target: this.player.tech_.el_});
<add>
<add> assert.strictEqual(this.player.play.callCount, 1, 'has called play');
<add> assert.strictEqual(this.player.pause.callCount, 0, 'has not called pause');
<add>
<add> paused = false;
<add> this.player.handleTechClick_({target: this.player.tech_.el_});
<add>
<add> assert.strictEqual(this.player.play.callCount, 1, 'has called play, previously');
<add> assert.strictEqual(this.player.pause.callCount, 1, 'has called pause');
<add>});
<add>
<add>QUnit.test('when controls are disabled, click does nothing', function(assert) {
<add> let paused = true;
<add>
<add> this.player.controls(false);
<add>
<add> this.player.paused = () => paused;
<add> this.player.play = sinon.spy();
<add> this.player.pause = sinon.spy();
<add>
<add> this.player.handleTechClick_({target: this.player.tech_.el_});
<add>
<add> assert.strictEqual(this.player.play.callCount, 0, 'has not called play');
<add> assert.strictEqual(this.player.pause.callCount, 0, 'has not called pause');
<add>
<add> paused = false;
<add> this.player.handleTechClick_({target: this.player.tech_.el_});
<add>
<add> assert.strictEqual(this.player.play.callCount, 0, 'has not called play, previously');
<add> assert.strictEqual(this.player.pause.callCount, 0, 'has not called pause');
<add>});
<add>
<add>QUnit.test('when userActions.click is false, click does nothing', function(assert) {
<add> let paused = true;
<add>
<add> this.player.dispose();
<add> this.player = TestHelpers.makePlayer({
<add> controls: true,
<add> userActions: {
<add> click: false
<add> }
<add> });
<add>
<add> this.player.paused = () => paused;
<add> this.player.play = sinon.spy();
<add> this.player.pause = sinon.spy();
<add>
<add> this.player.handleTechClick_({target: this.player.tech_.el_});
<add>
<add> assert.strictEqual(this.player.play.callCount, 0, 'has not called play');
<add> assert.strictEqual(this.player.pause.callCount, 0, 'has not called pause');
<add>
<add> paused = false;
<add> this.player.handleTechClick_({target: this.player.tech_.el_});
<add>
<add> assert.strictEqual(this.player.play.callCount, 0, 'has not called play, previously');
<add> assert.strictEqual(this.player.pause.callCount, 0, 'has not called pause');
<add>});
<add>
<add>QUnit.test('when userActions.click is a function, that function is called instead of toggling play', function(assert) {
<add> let paused = true;
<add> const clickSpy = sinon.spy();
<add>
<add> this.player.dispose();
<add> this.player = TestHelpers.makePlayer({
<add> controls: true,
<add> userActions: {
<add> click: clickSpy
<add> }
<add> });
<add>
<add> this.player.paused = () => paused;
<add> this.player.play = sinon.spy();
<add> this.player.pause = sinon.spy();
<add>
<add> let event = {target: this.player.tech_.el_};
<add>
<add> this.player.handleTechClick_(event);
<add>
<add> assert.strictEqual(this.player.play.callCount, 0, 'has not called play');
<add> assert.strictEqual(this.player.pause.callCount, 0, 'has not called pause');
<add> assert.strictEqual(clickSpy.callCount, 1, 'has called the click handler');
<add> assert.strictEqual(clickSpy.getCall(0).args[0], event, 'has passed the event to the handler');
<add>
<add> paused = false;
<add> event = {target: this.player.tech_.el_};
<add> this.player.handleTechClick_(event);
<add>
<add> assert.strictEqual(this.player.play.callCount, 0, 'has not called play, previously');
<add> assert.strictEqual(this.player.pause.callCount, 0, 'has not called pause');
<add> assert.strictEqual(clickSpy.callCount, 2, 'has called the click handler');
<add> assert.strictEqual(clickSpy.getCall(1).args[0], event, 'has passed the event to the handler');
<add>});
<add>
<ide> QUnit.module('Player: User Actions: Double Click', {
<ide>
<ide> beforeEach() { | 1 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.