content_type
stringclasses 8
values | main_lang
stringclasses 7
values | message
stringlengths 1
50
| sha
stringlengths 40
40
| patch
stringlengths 52
962k
| file_count
int64 1
300
|
---|---|---|---|---|---|
Text | Text | remove personal pronoun from domain.md | b32d067839ab507c8722d4d9e8ac245ed63dfa0b | <ide><path>doc/api/domain.md
<ide> Domain error handlers are not a substitute for closing down a
<ide> process when an error occurs.
<ide>
<ide> By the very nature of how [`throw`][] works in JavaScript, there is almost
<del>never any way to safely "pick up where you left off", without leaking
<add>never any way to safely "pick up where it left off", without leaking
<ide> references, or creating some other sort of undefined brittle state.
<ide>
<ide> The safest way to respond to a thrown error is to shut down the | 1 |
Python | Python | add simple neural network | f340bde6e047d86171385b90a023ac01e8914d0c | <ide><path>neural_network/simple_neural_network.py
<add>"""
<add>Forward propagation explanation:
<add>https://towardsdatascience.com/forward-propagation-in-neural-networks-simplified-math-and-code-version-bbcfef6f9250
<add>"""
<add>
<add>import math
<add>import random
<add>
<add>
<add># Sigmoid
<add>def sigmoid_function(value: float, deriv: bool = False) -> float:
<add> """Return the sigmoid function of a float.
<add>
<add> >>> sigmoid_function(3.5)
<add> 0.9706877692486436
<add> >>> sigmoid_function(3.5, True)
<add> -8.75
<add> """
<add> if deriv:
<add> return value * (1 - value)
<add> return 1 / (1 + math.exp(-value))
<add>
<add>
<add># Initial Value
<add>INITIAL_VALUE = 0.02
<add>
<add>
<add>def forward_propagation(expected: int, number_propagations: int) -> float:
<add> """Return the value found after the forward propagation training.
<add>
<add> >>> res = forward_propagation(32, 10000000)
<add> >>> res > 31 and res < 33
<add> True
<add>
<add> >>> res = forward_propagation(32, 1000)
<add> >>> res > 31 and res < 33
<add> False
<add> """
<add>
<add> # Random weight
<add> weight = float(2 * (random.randint(1, 100)) - 1)
<add>
<add> for _ in range(number_propagations):
<add> # Forward propagation
<add> layer_1 = sigmoid_function(INITIAL_VALUE * weight)
<add> # How much did we miss?
<add> layer_1_error = (expected / 100) - layer_1
<add> # Error delta
<add> layer_1_delta = layer_1_error * sigmoid_function(layer_1, True)
<add> # Update weight
<add> weight += INITIAL_VALUE * layer_1_delta
<add>
<add> return layer_1 * 100
<add>
<add>
<add>if __name__ == "__main__":
<add> import doctest
<add>
<add> doctest.testmod()
<add>
<add> expected = int(input("Expected value: "))
<add> number_propagations = int(input("Number of propagations: "))
<add> print(forward_propagation(expected, number_propagations)) | 1 |
Text | Text | fix broken ahafs link in fs doc | e8eb6ac31c5477b07fa08010f1e7d9885916f50e | <ide><path>doc/api/fs.md
<ide> the file contents.
<ide> [Readable Stream]: stream.md#stream_class_stream_readable
<ide> [Writable Stream]: stream.md#stream_class_stream_writable
<ide> [caveats]: #fs_caveats
<del>[`AHAFS`]: https://www.ibm.com/developerworks/aix/library/au-aix_event_infrastructure/
<add>[`AHAFS`]: https://developer.ibm.com/articles/au-aix_event_infrastructure/
<ide> [`Buffer.byteLength`]: buffer.md#buffer_static_method_buffer_bytelength_string_encoding
<ide> [`FSEvents`]: https://developer.apple.com/documentation/coreservices/file_system_events
<ide> [`Number.MAX_SAFE_INTEGER`]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Number/MAX_SAFE_INTEGER | 1 |
PHP | PHP | flatten the code | b79cc70a6b39ee3602191f9112a80026704171f1 | <ide><path>src/ORM/TableRegistry.php
<ide> public static function config($alias = null, $options = null)
<ide> */
<ide> public static function get($alias, array $options = [])
<ide> {
<del> list(, $classAlias) = pluginSplit($alias);
<del> $exists = isset(static::$_instances[$alias]);
<del>
<del> if ($exists && !empty($options)) {
<del> if (static::$_options[$alias] !== $options) {
<add> if (isset(static::$_instances[$alias])) {
<add> if (!empty($options) && static::$_options[$alias] !== $options) {
<ide> throw new RuntimeException(sprintf(
<ide> 'You cannot configure "%s", it already exists in the registry.',
<ide> $alias
<ide> ));
<ide> }
<del> }
<del> if ($exists) {
<ide> return static::$_instances[$alias];
<ide> }
<add>
<ide> static::$_options[$alias] = $options;
<add> list(, $classAlias) = pluginSplit($alias);
<ide> $options = ['alias' => $classAlias] + $options;
<ide>
<ide> if (empty($options['className'])) { | 1 |
Text | Text | add a missing changelog entry for [ci skip] | fe63933ceec7223beef06ff6f8d1e5b795e17f20 | <ide><path>railties/CHANGELOG.md
<add>* Ensure that `bin/rails` is a file before trying to execute it.
<add>
<add> Fixes #13825.
<add>
<add> *bronzle*
<add>
<ide> * Use single quotes in generated files.
<ide>
<ide> *Cristian Mircea Messel*, *Chulki Lee* | 1 |
Ruby | Ruby | add a test case for issue #476 | be199a1d53f9ceae5cfaac185bfd0d9c2a28f9d4 | <ide><path>railties/test/application/assets_test.rb
<ide> def setup
<ide> boot_rails
<ide> end
<ide>
<add> def app
<add> @app ||= Rails.application
<add> end
<add>
<ide> test "assets routes have higher priority" do
<ide> app_file "app/assets/javascripts/demo.js.erb", "<%= :alert %>();"
<ide>
<ide> def setup
<ide> get "/assets/demo.js"
<ide> assert_match "alert()", last_response.body
<ide> end
<add>
<add> test "does not stream session cookies back" do
<add> puts "PENDING SPROCKETS AND RACK RELEASE"
<add> # app_file "app/assets/javascripts/demo.js.erb", "<%= :alert %>();"
<add> #
<add> # app_file "config/routes.rb", <<-RUBY
<add> # AppTemplate::Application.routes.draw do
<add> # match '/omg', :to => "omg#index"
<add> # end
<add> # RUBY
<add> #
<add> # require "#{app_path}/config/environment"
<add> #
<add> # class ::OmgController < ActionController::Base
<add> # def index
<add> # flash[:cool_story] = true
<add> # render :text => "ok"
<add> # end
<add> # end
<add> #
<add> # get "/omg"
<add> # assert_equal 'ok', last_response.body
<add> #
<add> # get "/assets/demo.js"
<add> # assert_match "alert()", last_response.body
<add> # assert_equal nil, last_response.headers["Set-Cookie"]
<add> end
<ide> end
<ide> end | 1 |
Java | Java | use weak etags in versionresourceresolver | b883aad1f1541b07971f3f2e5da7ed9a9db8baf6 | <ide><path>spring-webflux/src/main/java/org/springframework/web/reactive/resource/VersionResourceResolver.java
<ide> /*
<del> * Copyright 2002-2019 the original author or authors.
<add> * Copyright 2002-2020 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 InputStream getInputStream() throws IOException {
<ide> public HttpHeaders getResponseHeaders() {
<ide> HttpHeaders headers = (this.original instanceof HttpResource ?
<ide> ((HttpResource) this.original).getResponseHeaders() : new HttpHeaders());
<del> headers.setETag("\"" + this.version + "\"");
<add> headers.setETag("W/\"" + this.version + "\"");
<ide> return headers;
<ide> }
<ide> }
<ide><path>spring-webflux/src/test/java/org/springframework/web/reactive/resource/ResourceWebHandlerTests.java
<ide> public void getVersionedResource() throws Exception {
<ide> setPathWithinHandlerMapping(exchange, "versionString/foo.css");
<ide> this.handler.handle(exchange).block(TIMEOUT);
<ide>
<del> assertThat(exchange.getResponse().getHeaders().getETag()).isEqualTo("\"versionString\"");
<add> assertThat(exchange.getResponse().getHeaders().getETag()).isEqualTo("W/\"versionString\"");
<ide> assertThat(exchange.getResponse().getHeaders().getFirst("Accept-Ranges")).isEqualTo("bytes");
<ide> assertThat(exchange.getResponse().getHeaders().get("Accept-Ranges").size()).isEqualTo(1);
<ide> }
<ide><path>spring-webflux/src/test/java/org/springframework/web/reactive/resource/VersionResourceResolverTests.java
<ide> /*
<del> * Copyright 2002-2019 the original author or authors.
<add> * Copyright 2002-2020 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 resolveResourceSuccess() {
<ide> assertThat(actual.getFilename()).isEqualTo(expected.getFilename());
<ide> verify(this.versionStrategy, times(1)).getResourceVersion(expected);
<ide> assertThat(actual).isInstanceOf(HttpResource.class);
<del> assertThat(((HttpResource) actual).getResponseHeaders().getETag()).isEqualTo(("\"" + version + "\""));
<add> assertThat(((HttpResource) actual).getResponseHeaders().getETag()).isEqualTo(("W/\"" + version + "\""));
<ide> }
<ide>
<ide> @Test
<ide><path>spring-webmvc/src/main/java/org/springframework/web/servlet/resource/VersionResourceResolver.java
<ide> /*
<del> * Copyright 2002-2019 the original author or authors.
<add> * Copyright 2002-2020 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 InputStream getInputStream() throws IOException {
<ide> public HttpHeaders getResponseHeaders() {
<ide> HttpHeaders headers = (this.original instanceof HttpResource ?
<ide> ((HttpResource) this.original).getResponseHeaders() : new HttpHeaders());
<del> headers.setETag("\"" + this.version + "\"");
<add> headers.setETag("W/\"" + this.version + "\"");
<ide> return headers;
<ide> }
<ide> }
<ide><path>spring-webmvc/src/test/java/org/springframework/web/servlet/resource/ResourceHttpRequestHandlerTests.java
<ide> public void getVersionedResource() throws Exception {
<ide> this.request.setAttribute(HandlerMapping.PATH_WITHIN_HANDLER_MAPPING_ATTRIBUTE, "versionString/foo.css");
<ide> this.handler.handleRequest(this.request, this.response);
<ide>
<del> assertThat(this.response.getHeader("ETag")).isEqualTo("\"versionString\"");
<add> assertThat(this.response.getHeader("ETag")).isEqualTo("W/\"versionString\"");
<ide> assertThat(this.response.getHeader("Accept-Ranges")).isEqualTo("bytes");
<ide> assertThat(this.response.getHeaders("Accept-Ranges").size()).isEqualTo(1);
<ide> }
<ide><path>spring-webmvc/src/test/java/org/springframework/web/servlet/resource/VersionResourceResolverTests.java
<ide> /*
<del> * Copyright 2002-2019 the original author or authors.
<add> * Copyright 2002-2020 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 resolveResourceSuccess() throws Exception {
<ide> assertThat(actual.getFilename()).isEqualTo(expected.getFilename());
<ide> verify(this.versionStrategy, times(1)).getResourceVersion(expected);
<ide> assertThat(actual).isInstanceOf(HttpResource.class);
<del> assertThat(((HttpResource)actual).getResponseHeaders().getETag()).isEqualTo("\"" + version + "\"");
<add> assertThat(((HttpResource)actual).getResponseHeaders().getETag()).isEqualTo("W/\"" + version + "\"");
<ide> }
<ide>
<ide> @Test | 6 |
Mixed | Ruby | fix collection_from_options to allow enumerators | ae75930b59e7b41133c5a62c09da3c02309f81f3 | <ide><path>actionview/CHANGELOG.md
<add>* Changed partial rendering with a collection to allow collections which
<add> don't implement `to_ary`.
<add>
<add> Extracting the collection option has an optimization to avoid unnecessary
<add> queries of ActiveRecord Relations by calling `to_ary` on the given
<add> collection. Instances of `Enumerator` or `Enumerable` are valid
<add> collections, but they do not implement `#to_ary`. They will now be
<add> extracted and rendered as expected.
<add>
<add> *Steven Harman*
<add>
<ide> * New syntax for tag helpers. Avoid positional parameters and support HTML5 by default.
<ide> Example usage of tag helpers before:
<ide>
<ide><path>actionview/lib/action_view/renderer/partial_renderer.rb
<ide> def setup(context, options, block)
<ide> def collection_from_options
<ide> if @options.key?(:collection)
<ide> collection = @options[:collection]
<del> collection.respond_to?(:to_ary) ? collection.to_ary : []
<add> collection = collection.to_ary if collection.respond_to?(:to_ary)
<add> collection
<ide> end
<ide> end
<ide>
<ide><path>actionview/test/template/render_test.rb
<ide> def test_render_partial_with_nil_collection_should_return_nil
<ide> assert_nil @view.render(:partial => "test/customer", :collection => nil)
<ide> end
<ide>
<add> def test_render_partial_collection_for_non_array
<add> customers = Enumerator.new do |y|
<add> y.yield(Customer.new("david"))
<add> y.yield(Customer.new("mary"))
<add> end
<add> assert_equal "Hello: davidHello: mary", @view.render(:partial => "test/customer", collection: customers)
<add> end
<add>
<ide> def test_render_partial_without_object_does_not_put_partial_name_to_local_assigns
<ide> assert_equal 'false', @view.render(partial: 'test/partial_name_in_local_assigns')
<ide> end | 3 |
Python | Python | add cross-links and `void` example | c63dd1316067f8d0ebe99f4f61cf9853b77e937d | <ide><path>numpy/core/_add_newdocs_scalars.py
<ide> def add_newdoc_for_scalar_type(obj, fixed_aliases, doc):
<ide> r"""
<ide> A unicode string.
<ide>
<add> When used in array, this type strips trailing nulls.
<add>
<ide> Unlike the builtin `str`, this supports the buffer protocol, exposing its
<ide> contents as UCS4:
<ide>
<ide> >>> memoryview(np.str_("abcd"))
<ide> b'a\x00\x00\x00b\x00\x00\x00c\x00\x00\x00d\x00\x00\x00'
<del>
<del> When used in array, this type cannot contain trailing nulls.
<ide> """)
<ide>
<ide> add_newdoc_for_scalar_type('bytes_', ['bytes0'],
<ide> r"""
<ide> A byte string.
<ide>
<del> When used in array, this type cannot contain trailing nulls.
<add> When used in array, this type strips trailing nulls.
<ide> """)
<ide>
<ide> add_newdoc_for_scalar_type('void', ['void0'],
<ide> """
<ide> Either an opaque sequence of bytes, or a structure.
<add>
<add> >>> np.void(b'abcd')
<add> void(b'\x61\x62\x63\x64')
<add>
<add> Structured `void` scalars can only be constructed via extraction from `structured_arrays`:
<add>
<add> >>> arr = np.array((1, 2), dtype=[('x', np.int8), ('y', np.int8)])
<add> >>> arr[()]
<add> (1, 2) # looks like a tuple, but is `np.void`
<ide> """)
<ide>
<ide> add_newdoc_for_scalar_type('datetime64', [],
<ide> def add_newdoc_for_scalar_type(obj, fixed_aliases, doc):
<ide> numpy.datetime64('1980')
<ide> >>> np.datetime64(10, 'D')
<ide> numpy.datetime64('1970-01-11')
<add>
<add> See `arrays.datetime` for more information.
<ide> """)
<ide>
<ide> add_newdoc_for_scalar_type('timedelta64', [],
<ide> """
<ide> A timedelta stored as a 64-bit integer.
<add>
<add> See `arrays.datetime` for more information.
<ide> """)
<ide>
<ide> # TODO: work out how to put this on the base class, np.floating | 1 |
Ruby | Ruby | fix a typo | 60d60b05418e274cdfb11fcc579e20f7d415dac0 | <ide><path>guides/rails_guides/kindle.rb
<ide> def generate(output_dir, mobi_outfile, logfile)
<ide>
<ide> generate_document_metadata(mobi_outfile)
<ide>
<del> puts "Creating MOBI document with kindlegen. This make take a while."
<add> puts "Creating MOBI document with kindlegen. This may take a while."
<ide> cmd = "kindlerb . > #{File.absolute_path logfile} 2>&1"
<ide> puts cmd
<ide> system(cmd) | 1 |
PHP | PHP | ignore hidden relationships in to_array() | ff4b43c72f9ae2a4af72e3fa7b58aecd78e6029c | <ide><path>laravel/database/eloquent/model.php
<ide> public function to_array()
<ide>
<ide> foreach ($this->relationships as $name => $models)
<ide> {
<add> // Relationships can be marked as "hidden", too.
<add> if (in_array($name, static::$hidden)) continue;
<add>
<ide> // If the relationship is not a "to-many" relationship, we can just
<ide> // to_array the related model and add it as an attribute to the
<ide> // array of existing regular attributes we gathered. | 1 |
Javascript | Javascript | use common.cancreatesymlink() consistently | 8e6601a789ec6c3657314f475f1493192a2fda2b | <ide><path>test/parallel/test-fs-realpath.js
<ide> const tmpdir = require('../common/tmpdir');
<ide> const assert = require('assert');
<ide> const fs = require('fs');
<ide> const path = require('path');
<del>const exec = require('child_process').exec;
<ide> let async_completed = 0;
<ide> let async_expected = 0;
<ide> const unlink = [];
<del>let skipSymlinks = false;
<add>const skipSymlinks = !common.canCreateSymLink();
<ide> const tmpDir = tmpdir.path;
<ide>
<ide> tmpdir.refresh();
<ide> if (common.isWindows) {
<ide> assert
<ide> .strictEqual(path_left.toLowerCase(), path_right.toLowerCase(), message);
<ide> };
<del>
<del> // On Windows, creating symlinks requires admin privileges.
<del> // We'll only try to run symlink test if we have enough privileges.
<del> try {
<del> exec('whoami /priv', function(err, o) {
<del> if (err || !o.includes('SeCreateSymbolicLinkPrivilege')) {
<del> skipSymlinks = true;
<del> }
<del> runTest();
<del> });
<del> } catch (er) {
<del> // better safe than sorry
<del> skipSymlinks = true;
<del> process.nextTick(runTest);
<del> }
<del>} else {
<del> process.nextTick(runTest);
<ide> }
<ide>
<add>process.nextTick(runTest);
<ide>
<ide> function tmp(p) {
<ide> return path.join(tmpDir, p);
<ide><path>test/parallel/test-trace-events-fs-sync.js
<ide> const traceFile = 'node_trace.1.log';
<ide>
<ide> let gid = 1;
<ide> let uid = 1;
<del>let skipSymlinks = false;
<ide>
<del>// On Windows, creating symlinks requires admin privileges.
<del>// We'll check if we have enough privileges.
<del>if (common.isWindows) {
<del> try {
<del> const o = cp.execSync('whoami /priv');
<del> if (!o.includes('SeCreateSymbolicLinkPrivilege')) {
<del> skipSymlinks = true;
<del> }
<del> } catch (er) {
<del> // better safe than sorry
<del> skipSymlinks = true;
<del> }
<del>} else {
<add>if (!common.isWindows) {
<ide> gid = process.getgid();
<ide> uid = process.getuid();
<ide> }
<ide> tests['fs.sync.write'] = 'fs.writeFileSync("fs.txt", "123", "utf8");' +
<ide>
<ide> // On windows, we need permissions to test symlink and readlink.
<ide> // We'll only try to run these tests if we have enough privileges.
<del>if (!skipSymlinks) {
<add>if (common.canCreateSymLink()) {
<ide> tests['fs.sync.symlink'] = 'fs.writeFileSync("fs.txt", "123", "utf8");' +
<ide> 'fs.symlinkSync("fs.txt", "linkx");' +
<ide> 'fs.unlinkSync("linkx");' + | 2 |
Javascript | Javascript | remove third argument from assert.strictequal() | f1d3f97c3bc813528e85b9c3e6506fc75b931d92 | <ide><path>test/parallel/test-util-inspect.js
<ide> if (typeof Symbol !== 'undefined') {
<ide> const npos = line.search(numRE);
<ide> if (npos !== -1) {
<ide> if (pos !== undefined) {
<del> assert.strictEqual(pos, npos, 'container items not aligned');
<add> assert.strictEqual(pos, npos);
<ide> }
<ide> pos = npos;
<ide> } | 1 |
Javascript | Javascript | improve docs of ember.alias and ember.aliasmethod | b53c217705331c2594faa780a83434b74ca7061f | <ide><path>packages/ember-metal/lib/mixin.js
<ide> Alias.prototype = new Ember.Descriptor();
<ide> ```javascript
<ide> App.PaintSample = Ember.Object.extend({
<ide> color: 'red',
<del> colour: Ember.aliasMethod('color'),
<add> colour: Ember.alias('color'),
<ide> name: function(){
<ide> return "Zed";
<ide> },
<del> moniker: Ember.aliasMethod("name")
<add> moniker: Ember.alias("name")
<ide> });
<ide>
<ide> var paintSample = App.PaintSample.create()
<ide> Alias.prototype = new Ember.Descriptor();
<ide> @for Ember
<ide> @param {String} methodName name of the method or property to alias
<ide> @return {Ember.Descriptor}
<add> @deprecated Use `Ember.aliasMethod` or `Ember.computed.alias` instead
<ide> */
<ide> Ember.alias = function(methodName) {
<ide> return new Alias(methodName);
<ide> };
<add>
<ide> Ember.deprecateFunc("Ember.alias is deprecated. Please use Ember.aliasMethod or Ember.computed.alias instead.", Ember.alias);
<ide>
<ide> /**
<del> Makes a property or method available via an additional name.
<add> Makes a method available via an additional name.
<ide>
<ide> ```javascript
<del> App.PaintSample = Ember.Object.extend({
<del> color: 'red',
<del> colour: Ember.aliasMethod('color'),
<add> App.Person = Ember.Object.extend({
<ide> name: function(){
<del> return "Zed";
<add> return 'Tomhuda Katzdale';
<ide> },
<del> moniker: Ember.aliasMethod("name")
<add> moniker: Ember.aliasMethod('name')
<ide> });
<ide>
<del> var paintSample = App.PaintSample.create()
<del> paintSample.get('colour'); // 'red'
<del> paintSample.moniker(); // 'Zed'
<add> var goodGuy = App.Person.create()
<ide> ```
<ide>
<ide> @method aliasMethod
<ide> @for Ember
<del> @param {String} methodName name of the method or property to alias
<add> @param {String} methodName name of the method to alias
<ide> @return {Ember.Descriptor}
<ide> */
<ide> Ember.aliasMethod = function(methodName) { | 1 |
PHP | PHP | use fqcn for auth facade | 9e07a6870b44e7a70155c58a60b51eed22984d0e | <ide><path>src/Illuminate/Foundation/Auth/AuthenticatesAndRegistersUsers.php
<ide> <?php namespace Illuminate\Foundation\Auth;
<ide>
<del>use Auth;
<ide> use Illuminate\Http\Request;
<add>use Illuminate\Support\Facades\Auth;
<ide> use Illuminate\Contracts\Auth\Guard;
<ide> use Illuminate\Contracts\Auth\Registrar;
<ide> | 1 |
Javascript | Javascript | move ref code to reactcompositecomponent | 9c3d6b8881dcacdb8a65482bc1da7e96ca7514d6 | <ide><path>src/core/ReactComponent.js
<ide> 'use strict';
<ide>
<ide> var ReactElementValidator = require('ReactElementValidator');
<del>var ReactOwner = require('ReactOwner');
<del>var ReactRef = require('ReactRef');
<ide>
<ide> var invariant = require('invariant');
<ide>
<del>function attachRef(ref, component, owner) {
<del> if (ref instanceof ReactRef) {
<del> ReactRef.attachRef(ref, component);
<del> } else {
<del> ReactOwner.addComponentAsRefTo(component, ref, owner);
<del> }
<del>}
<del>
<del>function detachRef(ref, component, owner) {
<del> if (ref instanceof ReactRef) {
<del> ReactRef.detachRef(ref, component);
<del> } else {
<del> ReactOwner.removeComponentAsRefFrom(component, ref, owner);
<del> }
<del>}
<del>
<ide> /**
<ide> * Components are the basic units of composition in React.
<ide> *
<ide> var ReactComponent = {
<ide> if (__DEV__) {
<ide> ReactElementValidator.checkAndWarnForMutatedProps(this._currentElement);
<ide> }
<del>
<del> var ref = this._currentElement.ref;
<del> if (ref != null) {
<del> var owner = this._currentElement._owner;
<del> attachRef(ref, this, owner);
<del> }
<ide> // Effectively: return '';
<ide> },
<ide>
<ide> var ReactComponent = {
<ide> * @internal
<ide> */
<ide> unmountComponent: function() {
<del> var ref = this._currentElement.ref;
<del> if (ref != null) {
<del> detachRef(ref, this, this._currentElement._owner);
<del> }
<ide> },
<ide>
<ide> /**
<ide> var ReactComponent = {
<ide> if (__DEV__) {
<ide> ReactElementValidator.checkAndWarnForMutatedProps(nextElement);
<ide> }
<del>
<del> // If either the owner or a `ref` has changed, make sure the newest owner
<del> // has stored a reference to `this`, and the previous owner (if different)
<del> // has forgotten the reference to `this`. We use the element instead
<del> // of the public this.props because the post processing cannot determine
<del> // a ref. The ref conceptually lives on the element.
<del>
<del> // TODO: Should this even be possible? The owner cannot change because
<del> // it's forbidden by shouldUpdateReactComponent. The ref can change
<del> // if you swap the keys of but not the refs. Reconsider where this check
<del> // is made. It probably belongs where the key checking and
<del> // instantiateReactComponent is done.
<del>
<del> if (nextElement._owner !== prevElement._owner ||
<del> nextElement.ref !== prevElement.ref) {
<del> if (prevElement.ref != null) {
<del> detachRef(prevElement.ref, this, prevElement._owner);
<del> }
<del> // Correct, even if the owner is the same, and only the ref has changed.
<del> if (nextElement.ref != null) {
<del> attachRef(nextElement.ref, this, nextElement._owner);
<del> }
<del> }
<ide> },
<ide>
<ide> /**
<ide><path>src/core/ReactCompositeComponent.js
<ide> var ReactInstanceMap = require('ReactInstanceMap');
<ide> var ReactPerf = require('ReactPerf');
<ide> var ReactPropTypeLocations = require('ReactPropTypeLocations');
<ide> var ReactPropTypeLocationNames = require('ReactPropTypeLocationNames');
<add>var ReactRef = require('ReactRef');
<ide> var ReactUpdates = require('ReactUpdates');
<ide>
<ide> var assign = require('Object.assign');
<ide> var ReactCompositeComponentMixin = assign({},
<ide> context
<ide> );
<ide>
<add> ReactRef.attachRefs(this, this._currentElement);
<add>
<ide> this._context = context;
<ide> this._mountOrder = nextMountID++;
<ide> this._rootNodeID = rootID;
<ide> var ReactCompositeComponentMixin = assign({},
<ide> this._pendingCallbacks = null;
<ide> this._pendingElement = null;
<ide>
<add> ReactRef.detachRefs(this, this._currentElement);
<add>
<ide> ReactComponent.Mixin.unmountComponent.call(this);
<ide>
<ide> ReactComponentEnvironment.unmountIDFromEnvironment(this._rootNodeID);
<ide> var ReactCompositeComponentMixin = assign({},
<ide> prevUnmaskedContext,
<ide> nextUnmaskedContext
<ide> ) {
<del> // Update refs regardless of what shouldComponentUpdate returns
<ide> ReactComponent.Mixin.updateComponent.call(
<ide> this,
<ide> transaction,
<ide> var ReactCompositeComponentMixin = assign({},
<ide> nextUnmaskedContext
<ide> );
<ide>
<add> // Update refs regardless of what shouldComponentUpdate returns
<add> ReactRef.updateRefs(this, prevParentElement, nextParentElement);
<add>
<ide> var inst = this._instance;
<ide>
<ide> var prevContext = inst.context;
<ide><path>src/core/ReactRef.js
<ide>
<ide> 'use strict';
<ide>
<add>var ReactOwner = require('ReactOwner');
<ide> var ReactUpdates = require('ReactUpdates');
<ide>
<ide> var accumulate = require('accumulate');
<ide> assign(ReactRef.prototype, {
<ide> }
<ide> });
<ide>
<del>ReactRef.attachRef = function(ref, value) {
<add>function attachFirstClassRef(ref, value) {
<ide> ref._value = value.getPublicInstance();
<del>};
<add>}
<ide>
<del>ReactRef.detachRef = function(ref, value) {
<add>function detachFirstClassRef(ref, value) {
<ide> // Check that `component` is still the current ref because we do not want to
<ide> // detach the ref if another component stole it.
<ide> if (ref._value === value) {
<ide> ref._value = null;
<ide> }
<add>}
<add>
<add>function attachRef(ref, component, owner) {
<add> if (ref instanceof ReactRef) {
<add> attachFirstClassRef(ref, component);
<add> } else {
<add> ReactOwner.addComponentAsRefTo(component, ref, owner);
<add> }
<add>}
<add>
<add>function detachRef(ref, component, owner) {
<add> if (ref instanceof ReactRef) {
<add> detachFirstClassRef(ref, component);
<add> } else {
<add> ReactOwner.removeComponentAsRefFrom(component, ref, owner);
<add> }
<add>}
<add>
<add>ReactRef.attachRefs = function(instance, element) {
<add> var ref = element.ref;
<add> if (ref != null) {
<add> attachRef(ref, instance, element._owner);
<add> }
<add>};
<add>
<add>ReactRef.updateRefs = function(instance, prevElement, nextElement) {
<add> // If either the owner or a `ref` has changed, make sure the newest owner
<add> // has stored a reference to `this`, and the previous owner (if different)
<add> // has forgotten the reference to `this`. We use the element instead
<add> // of the public this.props because the post processing cannot determine
<add> // a ref. The ref conceptually lives on the element.
<add>
<add> // TODO: Should this even be possible? The owner cannot change because
<add> // it's forbidden by shouldUpdateReactComponent. The ref can change
<add> // if you swap the keys of but not the refs. Reconsider where this check
<add> // is made. It probably belongs where the key checking and
<add> // instantiateReactComponent is done.
<add>
<add> if (nextElement._owner !== prevElement._owner ||
<add> nextElement.ref !== prevElement.ref) {
<add> if (prevElement.ref != null) {
<add> detachRef(prevElement.ref, instance, prevElement._owner);
<add> }
<add> // Correct, even if the owner is the same, and only the ref has changed.
<add> if (nextElement.ref != null) {
<add> attachRef(nextElement.ref, instance, nextElement._owner);
<add> }
<add> }
<add>};
<add>
<add>ReactRef.detachRefs = function(instance, element) {
<add> var ref = element.ref;
<add> if (ref != null) {
<add> detachRef(ref, instance, element._owner);
<add> }
<ide> };
<ide>
<ide> module.exports = ReactRef; | 3 |
Javascript | Javascript | allow ngform on attribute and class | e9e3ee012b50f868f4cd68f3571560680998a19b | <ide><path>src/AngularPublic.js
<ide> function publishExternalAPI(angular){
<ide> ngClassOdd: ngClassOddDirective,
<ide> ngCloak: ngCloakDirective,
<ide> ngController: ngControllerDirective,
<del> ngForm: formDirective,
<add> ngForm: ngFormDirective,
<ide> ngHide: ngHideDirective,
<ide> ngInclude: ngIncludeDirective,
<ide> ngInit: ngInitDirective,
<ide><path>src/directive/form.js
<ide> function FormController(name, element, attrs) {
<ide> </doc:scenario>
<ide> </doc:example>
<ide> */
<del>var formDirective = [function() {
<del> return {
<del> name: 'form',
<del> restrict: 'E',
<del> inject: {
<del> name: 'accessor'
<del> },
<del> controller: FormController,
<del> compile: function() {
<del> return {
<del> pre: function(scope, formElement, attr, controller) {
<del> formElement.bind('submit', function(event) {
<del> if (!attr.action) event.preventDefault();
<del> });
<add>var formDirectiveDev = {
<add> name: 'form',
<add> restrict: 'E',
<add> inject: {
<add> name: 'accessor'
<add> },
<add> controller: FormController,
<add> compile: function() {
<add> return {
<add> pre: function(scope, formElement, attr, controller) {
<add> formElement.bind('submit', function(event) {
<add> if (!attr.action) event.preventDefault();
<add> });
<ide>
<del> var parentFormCtrl = formElement.parent().inheritedData('$formController');
<del> if (parentFormCtrl) {
<del> formElement.bind('$destroy', function() {
<del> parentFormCtrl.$removeControl(controller);
<del> if (attr.name) delete scope[attr.name];
<del> extend(controller, nullFormCtrl); //stop propagating child destruction handlers upwards
<del> });
<del> }
<add> var parentFormCtrl = formElement.parent().inheritedData('$formController');
<add> if (parentFormCtrl) {
<add> formElement.bind('$destroy', function() {
<add> parentFormCtrl.$removeControl(controller);
<add> if (attr.name) delete scope[attr.name];
<add> extend(controller, nullFormCtrl); //stop propagating child destruction handlers upwards
<add> });
<ide> }
<del> };
<del> }
<del> };
<del>}];
<add> }
<add> };
<add> }
<add>};
<add>
<add>var formDirective = valueFn(formDirectiveDev);
<add>var ngFormDirective = valueFn(extend(copy(formDirectiveDev), {restrict:'EAC'}));
<ide><path>test/directive/formSpec.js
<ide> describe('form', function() {
<ide>
<ide> it('should deregister a child form when its DOM is removed', function() {
<ide> doc = jqLite(
<del> '<ng:form name="parent">' +
<del> '<ng:form name="child">' +
<add> '<form name="parent">' +
<add> '<div class="ng-form" name="child">' +
<ide> '<input ng:model="modelA" name="inputA" required>' +
<del> '</ng:form>' +
<del> '</ng:form>');
<add> '</div>' +
<add> '</form>');
<ide> $compile(doc)(scope);
<ide> scope.$apply();
<ide>
<ide> var parent = scope.parent,
<ide> child = scope.child;
<ide>
<add> expect(parent).toBeDefined();
<add> expect(child).toBeDefined();
<ide> expect(parent.$error.required).toEqual([child]);
<ide> doc.children().remove(); //remove child
<ide> | 3 |
Javascript | Javascript | capture errors on request data streams | c65065ac0f3f1af3986e881bc197362621fd550c | <ide><path>lib/adapters/http.js
<ide> module.exports = function httpAdapter(config) {
<ide>
<ide> // Send the request
<ide> if (utils.isStream(data)) {
<del> data.pipe(req);
<add> data.on('error', function handleStreamError(err) {
<add> reject(enhanceError(err, config, null, req));
<add> }).pipe(req);
<ide> } else {
<ide> req.end(data);
<ide> }
<ide><path>test/unit/adapters/http.js
<ide> module.exports = {
<ide> });
<ide> },
<ide>
<add> testFailedStream: function(test) {
<add> server = http.createServer(function (req, res) {
<add> req.pipe(res);
<add> }).listen(4444, function () {
<add> axios.post('http://localhost:4444/',
<add> fs.createReadStream('/does/not/exist')
<add> ).then(function (res) {
<add> test.fail();
<add> }).catch(function (err) {
<add> test.equal(err.message, 'ENOENT: no such file or directory, open \'/does/not/exist\'');
<add> test.done();
<add> });
<add> });
<add> },
<add>
<ide> testBuffer: function(test) {
<ide> var buf = new Buffer(1024); // Unsafe buffer < Buffer.poolSize (8192 bytes)
<ide> buf.fill('x'); | 2 |
Javascript | Javascript | use const in pdf_thumbnail_viewer.js | 74e442ef4c43f82ba6945cf1795b722e1ff5122e | <ide><path>web/pdf_thumbnail_viewer.js
<ide> * See the License for the specific language governing permissions and
<ide> * limitations under the License.
<ide> */
<add>/* eslint no-var: error, prefer-const: error */
<ide>
<ide> import {
<ide> getVisibleElements, isValidRotation, NullL10n, scrollIntoView, watchScroll
<ide> class PDFThumbnailViewer {
<ide> // ... and add the highlight to the new thumbnail.
<ide> thumbnailView.div.classList.add(THUMBNAIL_SELECTED_CLASS);
<ide> }
<del> let visibleThumbs = this._getVisibleThumbs();
<del> let numVisibleThumbs = visibleThumbs.views.length;
<add> const visibleThumbs = this._getVisibleThumbs();
<add> const numVisibleThumbs = visibleThumbs.views.length;
<ide>
<ide> // If the thumbnail isn't currently visible, scroll it into view.
<ide> if (numVisibleThumbs > 0) {
<del> let first = visibleThumbs.first.id;
<add> const first = visibleThumbs.first.id;
<ide> // Account for only one thumbnail being visible.
<del> let last = (numVisibleThumbs > 1 ? visibleThumbs.last.id : first);
<add> const last = (numVisibleThumbs > 1 ? visibleThumbs.last.id : first);
<ide>
<ide> let shouldScroll = false;
<ide> if (pageNumber <= first || pageNumber >= last) {
<ide> class PDFThumbnailViewer {
<ide> }
<ide>
<ide> pdfDocument.getPage(1).then((firstPdfPage) => {
<del> let pagesCount = pdfDocument.numPages;
<add> const pagesCount = pdfDocument.numPages;
<ide> const viewport = firstPdfPage.getViewport({ scale: 1, });
<ide> for (let pageNum = 1; pageNum <= pagesCount; ++pageNum) {
<del> let thumbnail = new PDFThumbnailView({
<add> const thumbnail = new PDFThumbnailView({
<ide> container: this.container,
<ide> id: pageNum,
<ide> defaultViewport: viewport.clone(),
<ide> class PDFThumbnailViewer {
<ide> }
<ide> // Update all the `PDFThumbnailView` instances.
<ide> for (let i = 0, ii = this._thumbnails.length; i < ii; i++) {
<del> let label = this._pageLabels && this._pageLabels[i];
<add> const label = this._pageLabels && this._pageLabels[i];
<ide> this._thumbnails[i].setPageLabel(label);
<ide> }
<ide> }
<ide> class PDFThumbnailViewer {
<ide> }
<ide>
<ide> forceRendering() {
<del> let visibleThumbs = this._getVisibleThumbs();
<del> let thumbView = this.renderingQueue.getHighestPriority(visibleThumbs,
<del> this._thumbnails,
<del> this.scroll.down);
<add> const visibleThumbs = this._getVisibleThumbs();
<add> const thumbView = this.renderingQueue.getHighestPriority(visibleThumbs,
<add> this._thumbnails,
<add> this.scroll.down);
<ide> if (thumbView) {
<ide> this._ensurePdfPageLoaded(thumbView).then(() => {
<ide> this.renderingQueue.renderView(thumbView); | 1 |
PHP | PHP | fix failing testlogerror | 85cd11384a2d0ac6641253cc95d23e4444dddf7e | <ide><path>lib/Cake/Test/Case/BasicsTest.php
<ide> public function testDebug() {
<ide> if (php_sapi_name() === 'cli') {
<ide> $expected = sprintf($expectedText, str_replace(CAKE_CORE_INCLUDE_PATH, '', __FILE__), __LINE__ - 18);
<ide> } else {
<del> $expected = sprintf($expectedHtml, str_replace(CAKE_CORE_INCLUDE_PATH, '', __FILE__), __LINE__ - 19);
<add> $expected = sprintf($expectedHtml, str_replace(CAKE_CORE_INCLUDE_PATH, '', __FILE__), __LINE__ - 20);
<ide> }
<ide> $this->assertEquals($expected, $result);
<ide> | 1 |
Ruby | Ruby | fix missed smtp_session changes to base.rb. | 416091d8b50ac855f175c004821a5d9831e21bd0 | <ide><path>actionmailer/lib/action_mailer/base.rb
<ide> def perform_delivery_smtp(mail)
<ide> destinations = mail.destinations
<ide> mail.ready_to_send
<ide>
<del> Net::SMTP.start(server_settings[:address], server_settings[:port], server_settings[:domain],
<del> server_settings[:user_name], server_settings[:password], server_settings[:authentication]) do |smtp|
<add> Net::SMTP.start(smtp_settings[:address], smtp_settings[:port], smtp_settings[:domain],
<add> smtp_settings[:user_name], smtp_settings[:password], smtp_settings[:authentication]) do |smtp|
<ide> smtp.sendmail(mail.encoded, mail.from, destinations)
<ide> end
<ide> end | 1 |
Text | Text | fix the space thing | 5057d7da132c287d52749b6c73a9cd6129a1c05a | <ide><path>docs/sources/reference/commandline/cli.md
<ide> available in the default container, you can set these using the `--ulimit` flag.
<ide> values. If no `ulimits` are set, they will be inherited from the default `ulimits`
<ide> set on the daemon.
<ide> > `as` option is disabled now. In other words, the following script is not supported:
<del>> `$docker run -it --ulimit as=1024 fedora /bin/bash`
<add>> `$ docker run -it --ulimit as=1024 fedora /bin/bash`
<ide>
<ide> ## save
<ide> | 1 |
Javascript | Javascript | add support for stream | d23f9d5d4782e5849362895f8b648ed587999706 | <ide><path>lib/adapters/http.js
<ide> var zlib = require('zlib');
<ide> var pkg = require('./../../package.json');
<ide> var Buffer = require('buffer').Buffer;
<ide>
<add>// Resolve or reject the Promise based on the status
<add>function settle(resolve, reject, response) {
<add> (response.status >= 200 && response.status < 300 ?
<add> resolve :
<add> reject)(response);
<add>}
<add>
<ide> /*eslint consistent-return:0*/
<ide> module.exports = function httpAdapter(resolve, reject, config) {
<ide> var data = config.data;
<ide> module.exports = function httpAdapter(resolve, reject, config) {
<ide> headers['User-Agent'] = 'axios/' + pkg.version;
<ide> }
<ide>
<del> if (data) {
<add> if (data && !utils.isStream(data)) {
<ide> if (utils.isArrayBuffer(data)) {
<ide> data = new Buffer(new Uint8Array(data));
<ide> } else if (utils.isString(data)) {
<ide> data = new Buffer(data, 'utf-8');
<ide> } else {
<del> return reject(new Error('Data after transformation must be a string or an ArrayBuffer'));
<add> return reject(new Error('Data after transformation must be a string, an ArrayBuffer, or a Stream'));
<ide> }
<ide>
<ide> // Add Content-Length header if data exists
<ide> module.exports = function httpAdapter(resolve, reject, config) {
<ide> break;
<ide> }
<ide>
<del> var responseBuffer = [];
<del> stream.on('data', function handleStreamData(chunk) {
<del> responseBuffer.push(chunk);
<del>
<del> // make sure the content length is not over the maxContentLength if specified
<del> if (config.maxContentLength > -1 && Buffer.concat(responseBuffer).length > config.maxContentLength) {
<del> reject(new Error('maxContentLength size of ' + config.maxContentLength + ' exceeded'));
<del> }
<del> });
<del>
<del> stream.on('end', function handleStreamEnd() {
<del> var d = Buffer.concat(responseBuffer);
<del> if (config.responseType !== 'arraybuffer') {
<del> d = d.toString('utf8');
<del> }
<del> var response = {
<del> data: transformData(
<del> d,
<del> res.headers,
<del> config.transformResponse
<del> ),
<del> status: res.statusCode,
<del> statusText: res.statusMessage,
<del> headers: res.headers,
<del> config: config,
<del> request: req
<del> };
<del>
<del> // Resolve or reject the Promise based on the status
<del> (res.statusCode >= 200 && res.statusCode < 300 ?
<del> resolve :
<del> reject)(response);
<del> });
<add> var response = {
<add> status: res.statusCode,
<add> statusText: res.statusMessage,
<add> headers: res.headers,
<add> config: config,
<add> request: req
<add> };
<add>
<add> if (config.responseType === 'stream') {
<add> response.data = stream;
<add> settle(resolve, reject, response);
<add> } else {
<add> var responseBuffer = [];
<add> stream.on('data', function handleStreamData(chunk) {
<add> responseBuffer.push(chunk);
<add>
<add> // make sure the content length is not over the maxContentLength if specified
<add> if (config.maxContentLength > -1 && Buffer.concat(responseBuffer).length > config.maxContentLength) {
<add> reject(new Error('maxContentLength size of ' + config.maxContentLength + ' exceeded'));
<add> }
<add> });
<add>
<add> stream.on('end', function handleStreamEnd() {
<add> var responseData = Buffer.concat(responseBuffer);
<add> if (config.responseType !== 'arraybuffer') {
<add> responseData = responseData.toString('utf8');
<add> }
<add> response.data = transformData(responseData, res.headers, config.transformResponse);
<add> settle(resolve, reject, response);
<add> });
<add> }
<ide> });
<ide>
<ide> // Handle errors
<ide> module.exports = function httpAdapter(resolve, reject, config) {
<ide> }
<ide>
<ide> // Send the request
<del> req.end(data);
<add> if (utils.isStream(data)) {
<add> data.pipe(req);
<add> } else {
<add> req.end(data);
<add> }
<ide> };
<ide><path>lib/defaults.js
<ide> var DEFAULT_CONTENT_TYPE = {
<ide> };
<ide>
<ide> module.exports = {
<del> transformRequest: [function transformRequestJSON(data, headers) {
<del> if (utils.isFormData(data)) {
<del> return data;
<del> }
<del> if (utils.isArrayBuffer(data)) {
<add> transformRequest: [function transformRequest(data, headers) {
<add> if (utils.isFormData(data) || utils.isArrayBuffer(data) || utils.isStream(data)) {
<ide> return data;
<ide> }
<ide> if (utils.isArrayBufferView(data)) {
<ide> module.exports = {
<ide> return data;
<ide> }],
<ide>
<del> transformResponse: [function transformResponseJSON(data) {
<add> transformResponse: [function transformResponse(data) {
<ide> /*eslint no-param-reassign:0*/
<ide> if (typeof data === 'string') {
<ide> data = data.replace(PROTECTION_PREFIX, '');
<ide><path>test/unit/adapters/http.js
<ide> var axios = require('../../../index');
<ide> var http = require('http');
<ide> var url = require('url');
<ide> var zlib = require('zlib');
<add>var fs = require('fs');
<ide> var server;
<ide>
<ide> module.exports = {
<ide> module.exports = {
<ide> });
<ide> });
<ide> },
<del>
<add>
<ide> testMaxContentLength: function(test) {
<ide> var str = Array(100000).join('ж');
<ide>
<ide> module.exports = {
<ide> error = res;
<ide> failure = true;
<ide> });
<del>
<add>
<ide> setTimeout(function () {
<ide> test.equal(success, false, 'request should not succeed');
<ide> test.equal(failure, true, 'request should fail');
<ide> test.equal(error.message, 'maxContentLength size of 2000 exceeded');
<ide> test.done();
<ide> }, 100);
<ide> });
<add> },
<add>
<add> testStream: function(test) {
<add> server = http.createServer(function (req, res) {
<add> req.pipe(res);
<add> }).listen(4444, function () {
<add> axios.post('http://localhost:4444/',
<add> fs.createReadStream(__filename), {
<add> responseType: 'stream'
<add> }).then(function (res) {
<add> var stream = res.data;
<add> var string = '';
<add> stream.on('data', function (chunk) {
<add> string += chunk.toString('utf8');
<add> });
<add> stream.on('end', function () {
<add> test.equal(string, fs.readFileSync(__filename, 'utf8'));
<add> test.done();
<add> });
<add> });
<add> });
<ide> }
<ide> }; | 3 |
Python | Python | remove unnecessary special case for n == 0 | b274299278c2fc4b534a2af0933dc2d122135eee | <ide><path>numpy/lib/histograms.py
<ide> def histogramdd(sample, bins=10, range=None, normed=False, weights=None):
<ide> nbin[i] = len(edges[i]) + 1 # includes an outlier on each end
<ide> dedges[i] = np.diff(edges[i])
<ide>
<del> # Handle empty input.
<del> if N == 0:
<del> return np.zeros(nbin-2), edges
<del>
<ide> # Compute the bin number each sample falls into.
<ide> Ncount = tuple(
<ide> np.digitize(sample[:, i], edges[i]) | 1 |
Javascript | Javascript | replace fburl.com link with public fb.me link | c91d87213e6862019b9ef7df7c38551bd6d659fd | <ide><path>Libraries/ReactNative/renderApplication.js
<ide> function renderApplication<Props: Object>(
<ide>
<ide> // If the root component is async, the user probably wants the initial render
<ide> // to be async also. To do this, wrap AppContainer with an async marker.
<del> // For more info see https://fburl.com/tjpe0gpx
<add> // For more info see https://fb.me/is-component-async
<ide> if (
<ide> RootComponent.prototype != null &&
<ide> RootComponent.prototype.unstable_isAsyncReactComponent === true | 1 |
Text | Text | move @phillipj to emeriti | d36abb5d0b9470a237a2614c743ae28115bd86d6 | <ide><path>README.md
<ide> For information about the governance of the Node.js project, see
<ide> **Alexis Campailla** <[email protected]>
<ide> * [othiym23](https://github.com/othiym23) -
<ide> **Forrest L Norvell** <[email protected]> (he/him)
<del>* [phillipj](https://github.com/phillipj) -
<del>**Phillip Johnsen** <[email protected]>
<ide> * [pmq20](https://github.com/pmq20) -
<ide> **Minqi Pan** <[email protected]>
<ide> * [princejwesley](https://github.com/princejwesley) -
<ide> For information about the governance of the Node.js project, see
<ide> **Oleg Elifantiev** <[email protected]>
<ide> * [petkaantonov](https://github.com/petkaantonov) -
<ide> **Petka Antonov** <[email protected]>
<add>* [phillipj](https://github.com/phillipj) -
<add>**Phillip Johnsen** <[email protected]>
<ide> * [piscisaureus](https://github.com/piscisaureus) -
<ide> **Bert Belder** <[email protected]>
<ide> * [rlidwka](https://github.com/rlidwka) - | 1 |
Javascript | Javascript | fix lint errors for examples/real-world/ | 095688e05c0e5197505485ba32c7ab4939f571f7 | <ide><path>examples/real-world/actions/index.js
<del>import { CALL_API, Schemas } from '../middleware/api';
<add>import { CALL_API, Schemas } from '../middleware/api'
<ide>
<del>export const USER_REQUEST = 'USER_REQUEST';
<del>export const USER_SUCCESS = 'USER_SUCCESS';
<del>export const USER_FAILURE = 'USER_FAILURE';
<add>export const USER_REQUEST = 'USER_REQUEST'
<add>export const USER_SUCCESS = 'USER_SUCCESS'
<add>export const USER_FAILURE = 'USER_FAILURE'
<ide>
<ide> // Fetches a single user from Github API.
<ide> // Relies on the custom API middleware defined in ../middleware/api.js.
<ide> function fetchUser(login) {
<ide> return {
<ide> [CALL_API]: {
<del> types: [USER_REQUEST, USER_SUCCESS, USER_FAILURE],
<add> types: [ USER_REQUEST, USER_SUCCESS, USER_FAILURE ],
<ide> endpoint: `users/${login}`,
<ide> schema: Schemas.USER
<ide> }
<del> };
<add> }
<ide> }
<ide>
<ide> // Fetches a single user from Github API unless it is cached.
<ide> // Relies on Redux Thunk middleware.
<ide> export function loadUser(login, requiredFields = []) {
<ide> return (dispatch, getState) => {
<del> const user = getState().entities.users[login];
<add> const user = getState().entities.users[login]
<ide> if (user && requiredFields.every(key => user.hasOwnProperty(key))) {
<del> return null;
<add> return null
<ide> }
<ide>
<del> return dispatch(fetchUser(login));
<del> };
<add> return dispatch(fetchUser(login))
<add> }
<ide> }
<ide>
<del>export const REPO_REQUEST = 'REPO_REQUEST';
<del>export const REPO_SUCCESS = 'REPO_SUCCESS';
<del>export const REPO_FAILURE = 'REPO_FAILURE';
<add>export const REPO_REQUEST = 'REPO_REQUEST'
<add>export const REPO_SUCCESS = 'REPO_SUCCESS'
<add>export const REPO_FAILURE = 'REPO_FAILURE'
<ide>
<ide> // Fetches a single repository from Github API.
<ide> // Relies on the custom API middleware defined in ../middleware/api.js.
<ide> function fetchRepo(fullName) {
<ide> return {
<ide> [CALL_API]: {
<del> types: [REPO_REQUEST, REPO_SUCCESS, REPO_FAILURE],
<add> types: [ REPO_REQUEST, REPO_SUCCESS, REPO_FAILURE ],
<ide> endpoint: `repos/${fullName}`,
<ide> schema: Schemas.REPO
<ide> }
<del> };
<add> }
<ide> }
<ide>
<ide> // Fetches a single repository from Github API unless it is cached.
<ide> // Relies on Redux Thunk middleware.
<ide> export function loadRepo(fullName, requiredFields = []) {
<ide> return (dispatch, getState) => {
<del> const repo = getState().entities.repos[fullName];
<add> const repo = getState().entities.repos[fullName]
<ide> if (repo && requiredFields.every(key => repo.hasOwnProperty(key))) {
<del> return null;
<add> return null
<ide> }
<ide>
<del> return dispatch(fetchRepo(fullName));
<del> };
<add> return dispatch(fetchRepo(fullName))
<add> }
<ide> }
<ide>
<del>export const STARRED_REQUEST = 'STARRED_REQUEST';
<del>export const STARRED_SUCCESS = 'STARRED_SUCCESS';
<del>export const STARRED_FAILURE = 'STARRED_FAILURE';
<add>export const STARRED_REQUEST = 'STARRED_REQUEST'
<add>export const STARRED_SUCCESS = 'STARRED_SUCCESS'
<add>export const STARRED_FAILURE = 'STARRED_FAILURE'
<ide>
<ide> // Fetches a page of starred repos by a particular user.
<ide> // Relies on the custom API middleware defined in ../middleware/api.js.
<ide> function fetchStarred(login, nextPageUrl) {
<ide> return {
<ide> login,
<ide> [CALL_API]: {
<del> types: [STARRED_REQUEST, STARRED_SUCCESS, STARRED_FAILURE],
<add> types: [ STARRED_REQUEST, STARRED_SUCCESS, STARRED_FAILURE ],
<ide> endpoint: nextPageUrl,
<ide> schema: Schemas.REPO_ARRAY
<ide> }
<del> };
<add> }
<ide> }
<ide>
<ide> // Fetches a page of starred repos by a particular user.
<ide> export function loadStarred(login, nextPage) {
<ide> const {
<ide> nextPageUrl = `users/${login}/starred`,
<ide> pageCount = 0
<del> } = getState().pagination.starredByUser[login] || {};
<add> } = getState().pagination.starredByUser[login] || {}
<ide>
<ide> if (pageCount > 0 && !nextPage) {
<del> return null;
<add> return null
<ide> }
<ide>
<del> return dispatch(fetchStarred(login, nextPageUrl));
<del> };
<add> return dispatch(fetchStarred(login, nextPageUrl))
<add> }
<ide> }
<ide>
<del>export const STARGAZERS_REQUEST = 'STARGAZERS_REQUEST';
<del>export const STARGAZERS_SUCCESS = 'STARGAZERS_SUCCESS';
<del>export const STARGAZERS_FAILURE = 'STARGAZERS_FAILURE';
<add>export const STARGAZERS_REQUEST = 'STARGAZERS_REQUEST'
<add>export const STARGAZERS_SUCCESS = 'STARGAZERS_SUCCESS'
<add>export const STARGAZERS_FAILURE = 'STARGAZERS_FAILURE'
<ide>
<ide> // Fetches a page of stargazers for a particular repo.
<ide> // Relies on the custom API middleware defined in ../middleware/api.js.
<ide> function fetchStargazers(fullName, nextPageUrl) {
<ide> return {
<ide> fullName,
<ide> [CALL_API]: {
<del> types: [STARGAZERS_REQUEST, STARGAZERS_SUCCESS, STARGAZERS_FAILURE],
<add> types: [ STARGAZERS_REQUEST, STARGAZERS_SUCCESS, STARGAZERS_FAILURE ],
<ide> endpoint: nextPageUrl,
<ide> schema: Schemas.USER_ARRAY
<ide> }
<del> };
<add> }
<ide> }
<ide>
<ide> // Fetches a page of stargazers for a particular repo.
<ide> export function loadStargazers(fullName, nextPage) {
<ide> const {
<ide> nextPageUrl = `repos/${fullName}/stargazers`,
<ide> pageCount = 0
<del> } = getState().pagination.stargazersByRepo[fullName] || {};
<add> } = getState().pagination.stargazersByRepo[fullName] || {}
<ide>
<ide> if (pageCount > 0 && !nextPage) {
<del> return null;
<add> return null
<ide> }
<ide>
<del> return dispatch(fetchStargazers(fullName, nextPageUrl));
<del> };
<add> return dispatch(fetchStargazers(fullName, nextPageUrl))
<add> }
<ide> }
<ide>
<del>export const RESET_ERROR_MESSAGE = 'RESET_ERROR_MESSAGE';
<add>export const RESET_ERROR_MESSAGE = 'RESET_ERROR_MESSAGE'
<ide>
<ide> // Resets the currently visible error message.
<ide> export function resetErrorMessage() {
<ide> return {
<ide> type: RESET_ERROR_MESSAGE
<del> };
<add> }
<ide> }
<ide><path>examples/real-world/components/Explore.js
<del>import React, { Component, PropTypes } from 'react';
<add>import React, { Component, PropTypes } from 'react'
<ide>
<del>const GITHUB_REPO = 'https://github.com/rackt/redux';
<add>const GITHUB_REPO = 'https://github.com/rackt/redux'
<ide>
<ide> export default class Explore extends Component {
<ide> constructor(props) {
<del> super(props);
<del> this.handleKeyUp = this.handleKeyUp.bind(this);
<del> this.handleGoClick = this.handleGoClick.bind(this);
<add> super(props)
<add> this.handleKeyUp = this.handleKeyUp.bind(this)
<add> this.handleGoClick = this.handleGoClick.bind(this)
<ide> }
<ide>
<ide> componentWillReceiveProps(nextProps) {
<ide> if (nextProps.value !== this.props.value) {
<del> this.setInputValue(nextProps.value);
<add> this.setInputValue(nextProps.value)
<ide> }
<ide> }
<ide>
<ide> getInputValue() {
<del> return this.refs.input.value;
<add> return this.refs.input.value
<ide> }
<ide>
<ide> setInputValue(val) {
<ide> // Generally mutating DOM is a bad idea in React components,
<ide> // but doing this for a single uncontrolled field is less fuss
<ide> // than making it controlled and maintaining a state for it.
<del> this.refs.input.value = val;
<add> this.refs.input.value = val
<ide> }
<ide>
<ide> handleKeyUp(e) {
<ide> if (e.keyCode === 13) {
<del> this.handleGoClick();
<add> this.handleGoClick()
<ide> }
<ide> }
<ide>
<ide> handleGoClick() {
<del> this.props.onChange(this.getInputValue());
<add> this.props.onChange(this.getInputValue())
<ide> }
<ide>
<ide> render() {
<ide> export default class Explore extends Component {
<ide> Move the DevTools with Ctrl+W or hide them with Ctrl+H.
<ide> </p>
<ide> </div>
<del> );
<add> )
<ide> }
<ide> }
<ide>
<ide> Explore.propTypes = {
<ide> value: PropTypes.string.isRequired,
<ide> onChange: PropTypes.func.isRequired
<del>};
<add>}
<ide><path>examples/real-world/components/List.js
<del>import React, { Component, PropTypes } from 'react';
<add>import React, { Component, PropTypes } from 'react'
<ide>
<ide> export default class List extends Component {
<ide> renderLoadMore() {
<del> const { isFetching, onLoadMoreClick } = this.props;
<add> const { isFetching, onLoadMoreClick } = this.props
<ide> return (
<ide> <button style={{ fontSize: '150%' }}
<ide> onClick={onLoadMoreClick}
<ide> disabled={isFetching}>
<ide> {isFetching ? 'Loading...' : 'Load More'}
<ide> </button>
<del> );
<add> )
<ide> }
<ide>
<ide> render() {
<ide> const {
<ide> isFetching, nextPageUrl, pageCount,
<ide> items, renderItem, loadingLabel
<del> } = this.props;
<add> } = this.props
<ide>
<del> const isEmpty = items.length === 0;
<add> const isEmpty = items.length === 0
<ide> if (isEmpty && isFetching) {
<del> return <h2><i>{loadingLabel}</i></h2>;
<add> return <h2><i>{loadingLabel}</i></h2>
<ide> }
<ide>
<del> const isLastPage = !nextPageUrl;
<add> const isLastPage = !nextPageUrl
<ide> if (isEmpty && isLastPage) {
<del> return <h1><i>Nothing here!</i></h1>;
<add> return <h1><i>Nothing here!</i></h1>
<ide> }
<ide>
<ide> return (
<ide> <div>
<ide> {items.map(renderItem)}
<ide> {pageCount > 0 && !isLastPage && this.renderLoadMore()}
<ide> </div>
<del> );
<add> )
<ide> }
<ide> }
<ide>
<ide> List.propTypes = {
<ide> isFetching: PropTypes.bool.isRequired,
<ide> onLoadMoreClick: PropTypes.func.isRequired,
<ide> nextPageUrl: PropTypes.string
<del>};
<add>}
<ide>
<ide> List.defaultProps = {
<ide> isFetching: true,
<ide> loadingLabel: 'Loading...'
<del>};
<add>}
<ide><path>examples/real-world/components/Repo.js
<del>import React, { Component, PropTypes } from 'react';
<del>import { Link } from 'react-router';
<add>import React, { Component, PropTypes } from 'react'
<add>import { Link } from 'react-router'
<ide>
<ide> export default class Repo extends Component {
<ide>
<ide> render() {
<del> const { repo, owner } = this.props;
<del> const { login } = owner;
<del> const { name, description } = repo;
<add> const { repo, owner } = this.props
<add> const { login } = owner
<add> const { name, description } = repo
<ide>
<ide> return (
<ide> <div className="Repo">
<ide> export default class Repo extends Component {
<ide> <p>{description}</p>
<ide> }
<ide> </div>
<del> );
<add> )
<ide> }
<ide> }
<ide>
<ide> Repo.propTypes = {
<ide> owner: PropTypes.shape({
<ide> login: PropTypes.string.isRequired
<ide> }).isRequired
<del>};
<add>}
<ide><path>examples/real-world/components/User.js
<del>import React, { Component, PropTypes } from 'react';
<del>import { Link } from 'react-router';
<add>import React, { Component, PropTypes } from 'react'
<add>import { Link } from 'react-router'
<ide>
<ide> export default class User extends Component {
<ide> render() {
<del> const { login, avatarUrl, name } = this.props.user;
<add> const { login, avatarUrl, name } = this.props.user
<ide>
<ide> return (
<ide> <div className="User">
<ide> export default class User extends Component {
<ide> </h3>
<ide> </Link>
<ide> </div>
<del> );
<add> )
<ide> }
<ide> }
<ide>
<ide> User.propTypes = {
<ide> avatarUrl: PropTypes.string.isRequired,
<ide> name: PropTypes.string
<ide> }).isRequired
<del>};
<add>}
<ide><path>examples/real-world/containers/App.js
<del>import React, { Component, PropTypes } from 'react';
<del>import { connect } from 'react-redux';
<del>import { pushState } from 'redux-router';
<del>import Explore from '../components/Explore';
<del>import { resetErrorMessage } from '../actions';
<add>import React, { Component, PropTypes } from 'react'
<add>import { connect } from 'react-redux'
<add>import { pushState } from 'redux-router'
<add>import Explore from '../components/Explore'
<add>import { resetErrorMessage } from '../actions'
<ide>
<ide> class App extends Component {
<ide> constructor(props) {
<del> super(props);
<del> this.handleChange = this.handleChange.bind(this);
<del> this.handleDismissClick = this.handleDismissClick.bind(this);
<add> super(props)
<add> this.handleChange = this.handleChange.bind(this)
<add> this.handleDismissClick = this.handleDismissClick.bind(this)
<ide> }
<ide>
<ide> handleDismissClick(e) {
<del> this.props.resetErrorMessage();
<del> e.preventDefault();
<add> this.props.resetErrorMessage()
<add> e.preventDefault()
<ide> }
<ide>
<ide> handleChange(nextValue) {
<del> this.props.pushState(null, `/${nextValue}`);
<add> this.props.pushState(null, `/${nextValue}`)
<ide> }
<ide>
<ide> renderErrorMessage() {
<del> const { errorMessage } = this.props;
<add> const { errorMessage } = this.props
<ide> if (!errorMessage) {
<del> return null;
<add> return null
<ide> }
<ide>
<ide> return (
<ide> class App extends Component {
<ide> Dismiss
<ide> </a>)
<ide> </p>
<del> );
<add> )
<ide> }
<ide>
<ide> render() {
<del> const { children, inputValue } = this.props;
<add> const { children, inputValue } = this.props
<ide> return (
<ide> <div>
<ide> <Explore value={inputValue}
<ide> class App extends Component {
<ide> {this.renderErrorMessage()}
<ide> {children}
<ide> </div>
<del> );
<add> )
<ide> }
<ide> }
<ide>
<ide> App.propTypes = {
<ide> inputValue: PropTypes.string.isRequired,
<ide> // Injected by React Router
<ide> children: PropTypes.node
<del>};
<add>}
<ide>
<ide> function mapStateToProps(state) {
<ide> return {
<ide> errorMessage: state.errorMessage,
<ide> inputValue: state.router.location.pathname.substring(1)
<del> };
<add> }
<ide> }
<ide>
<ide> export default connect(mapStateToProps, {
<ide> resetErrorMessage,
<ide> pushState
<del>})(App);
<add>})(App)
<ide><path>examples/real-world/containers/DevTools.js
<del>import React from 'react';
<del>import { createDevTools } from 'redux-devtools';
<del>import LogMonitor from 'redux-devtools-log-monitor';
<del>import DockMonitor from 'redux-devtools-dock-monitor';
<add>import React from 'react'
<add>import { createDevTools } from 'redux-devtools'
<add>import LogMonitor from 'redux-devtools-log-monitor'
<add>import DockMonitor from 'redux-devtools-dock-monitor'
<ide>
<ide> export default createDevTools(
<ide> <DockMonitor toggleVisibilityKey="H"
<ide> changePositionKey="W">
<ide> <LogMonitor />
<ide> </DockMonitor>
<del>);
<add>)
<ide><path>examples/real-world/containers/RepoPage.js
<del>import React, { Component, PropTypes } from 'react';
<del>import { connect } from 'react-redux';
<del>import { loadRepo, loadStargazers } from '../actions';
<del>import Repo from '../components/Repo';
<del>import User from '../components/User';
<del>import List from '../components/List';
<add>import React, { Component, PropTypes } from 'react'
<add>import { connect } from 'react-redux'
<add>import { loadRepo, loadStargazers } from '../actions'
<add>import Repo from '../components/Repo'
<add>import User from '../components/User'
<add>import List from '../components/List'
<ide>
<ide> function loadData(props) {
<del> const { fullName } = props;
<del> props.loadRepo(fullName, ['description']);
<del> props.loadStargazers(fullName);
<add> const { fullName } = props
<add> props.loadRepo(fullName, [ 'description' ])
<add> props.loadStargazers(fullName)
<ide> }
<ide>
<ide> class RepoPage extends Component {
<ide> constructor(props) {
<del> super(props);
<del> this.renderUser = this.renderUser.bind(this);
<del> this.handleLoadMoreClick = this.handleLoadMoreClick.bind(this);
<add> super(props)
<add> this.renderUser = this.renderUser.bind(this)
<add> this.handleLoadMoreClick = this.handleLoadMoreClick.bind(this)
<ide> }
<ide>
<ide> componentWillMount() {
<del> loadData(this.props);
<add> loadData(this.props)
<ide> }
<ide>
<ide> componentWillReceiveProps(nextProps) {
<ide> if (nextProps.fullName !== this.props.fullName) {
<del> loadData(nextProps);
<add> loadData(nextProps)
<ide> }
<ide> }
<ide>
<ide> handleLoadMoreClick() {
<del> this.props.loadStargazers(this.props.fullName, true);
<add> this.props.loadStargazers(this.props.fullName, true)
<ide> }
<ide>
<ide> renderUser(user) {
<ide> return (
<ide> <User user={user}
<ide> key={user.login} />
<del> );
<add> )
<ide> }
<ide>
<ide> render() {
<del> const { repo, owner, name } = this.props;
<add> const { repo, owner, name } = this.props
<ide> if (!repo || !owner) {
<del> return <h1><i>Loading {name} details...</i></h1>;
<add> return <h1><i>Loading {name} details...</i></h1>
<ide> }
<ide>
<del> const { stargazers, stargazersPagination } = this.props;
<add> const { stargazers, stargazersPagination } = this.props
<ide> return (
<ide> <div>
<ide> <Repo repo={repo}
<ide> class RepoPage extends Component {
<ide> loadingLabel={`Loading stargazers of ${name}...`}
<ide> {...stargazersPagination} />
<ide> </div>
<del> );
<add> )
<ide> }
<ide> }
<ide>
<ide> RepoPage.propTypes = {
<ide> stargazersPagination: PropTypes.object,
<ide> loadRepo: PropTypes.func.isRequired,
<ide> loadStargazers: PropTypes.func.isRequired
<del>};
<add>}
<ide>
<ide> function mapStateToProps(state) {
<del> const { login, name } = state.router.params;
<add> const { login, name } = state.router.params
<ide> const {
<ide> pagination: { stargazersByRepo },
<ide> entities: { users, repos }
<del> } = state;
<add> } = state
<ide>
<del> const fullName = `${login}/${name}`;
<del> const stargazersPagination = stargazersByRepo[fullName] || { ids: [] };
<del> const stargazers = stargazersPagination.ids.map(id => users[id]);
<add> const fullName = `${login}/${name}`
<add> const stargazersPagination = stargazersByRepo[fullName] || { ids: [] }
<add> const stargazers = stargazersPagination.ids.map(id => users[id])
<ide>
<ide> return {
<ide> fullName,
<ide> function mapStateToProps(state) {
<ide> stargazersPagination,
<ide> repo: repos[fullName],
<ide> owner: users[login]
<del> };
<add> }
<ide> }
<ide>
<ide> export default connect(mapStateToProps, {
<ide> loadRepo,
<ide> loadStargazers
<del>})(RepoPage);
<add>})(RepoPage)
<ide><path>examples/real-world/containers/Root.dev.js
<del>import React, { Component, PropTypes } from 'react';
<del>import { Provider } from 'react-redux';
<del>import { ReduxRouter } from 'redux-router';
<del>import DevTools from './DevTools';
<add>import React, { Component, PropTypes } from 'react'
<add>import { Provider } from 'react-redux'
<add>import { ReduxRouter } from 'redux-router'
<add>import DevTools from './DevTools'
<ide>
<ide> export default class Root extends Component {
<ide> render() {
<del> const { store } = this.props;
<add> const { store } = this.props
<ide> return (
<ide> <Provider store={store}>
<ide> <div>
<ide> <ReduxRouter />
<ide> <DevTools />
<ide> </div>
<ide> </Provider>
<del> );
<add> )
<ide> }
<ide> }
<ide>
<ide> Root.propTypes = {
<ide> store: PropTypes.object.isRequired
<del>};
<add>}
<ide><path>examples/real-world/containers/Root.js
<ide> if (process.env.NODE_ENV === 'production') {
<del> module.exports = require('./Root.prod');
<add> module.exports = require('./Root.prod')
<ide> } else {
<del> module.exports = require('./Root.dev');
<add> module.exports = require('./Root.dev')
<ide> }
<ide><path>examples/real-world/containers/Root.prod.js
<del>import React, { Component, PropTypes } from 'react';
<del>import { Provider } from 'react-redux';
<del>import { ReduxRouter } from 'redux-router';
<add>import React, { Component, PropTypes } from 'react'
<add>import { Provider } from 'react-redux'
<add>import { ReduxRouter } from 'redux-router'
<ide>
<ide> export default class Root extends Component {
<ide> render() {
<del> const { store } = this.props;
<add> const { store } = this.props
<ide> return (
<ide> <Provider store={store}>
<ide> <ReduxRouter />
<ide> </Provider>
<del> );
<add> )
<ide> }
<ide> }
<ide>
<ide> Root.propTypes = {
<ide> store: PropTypes.object.isRequired
<del>};
<add>}
<ide><path>examples/real-world/containers/UserPage.js
<del>import React, { Component, PropTypes } from 'react';
<del>import { connect } from 'react-redux';
<del>import { loadUser, loadStarred } from '../actions';
<del>import User from '../components/User';
<del>import Repo from '../components/Repo';
<del>import List from '../components/List';
<del>import zip from 'lodash/array/zip';
<add>import React, { Component, PropTypes } from 'react'
<add>import { connect } from 'react-redux'
<add>import { loadUser, loadStarred } from '../actions'
<add>import User from '../components/User'
<add>import Repo from '../components/Repo'
<add>import List from '../components/List'
<add>import zip from 'lodash/array/zip'
<ide>
<ide> function loadData(props) {
<del> const { login } = props;
<del> props.loadUser(login, ['name']);
<del> props.loadStarred(login);
<add> const { login } = props
<add> props.loadUser(login, [ 'name' ])
<add> props.loadStarred(login)
<ide> }
<ide>
<ide> class UserPage extends Component {
<ide> constructor(props) {
<del> super(props);
<del> this.renderRepo = this.renderRepo.bind(this);
<del> this.handleLoadMoreClick = this.handleLoadMoreClick.bind(this);
<add> super(props)
<add> this.renderRepo = this.renderRepo.bind(this)
<add> this.handleLoadMoreClick = this.handleLoadMoreClick.bind(this)
<ide> }
<ide>
<ide> componentWillMount() {
<del> loadData(this.props);
<add> loadData(this.props)
<ide> }
<ide>
<ide> componentWillReceiveProps(nextProps) {
<ide> if (nextProps.login !== this.props.login) {
<del> loadData(nextProps);
<add> loadData(nextProps)
<ide> }
<ide> }
<ide>
<ide> handleLoadMoreClick() {
<del> this.props.loadStarred(this.props.login, true);
<add> this.props.loadStarred(this.props.login, true)
<ide> }
<ide>
<del> renderRepo([repo, owner]) {
<add> renderRepo([ repo, owner ]) {
<ide> return (
<ide> <Repo repo={repo}
<ide> owner={owner}
<ide> key={repo.fullName} />
<del> );
<add> )
<ide> }
<ide>
<ide> render() {
<del> const { user, login } = this.props;
<add> const { user, login } = this.props
<ide> if (!user) {
<del> return <h1><i>Loading {login}’s profile...</i></h1>;
<add> return <h1><i>Loading {login}’s profile...</i></h1>
<ide> }
<ide>
<del> const { starredRepos, starredRepoOwners, starredPagination } = this.props;
<add> const { starredRepos, starredRepoOwners, starredPagination } = this.props
<ide> return (
<ide> <div>
<ide> <User user={user} />
<ide> class UserPage extends Component {
<ide> loadingLabel={`Loading ${login}’s starred...`}
<ide> {...starredPagination} />
<ide> </div>
<del> );
<add> )
<ide> }
<ide> }
<ide>
<ide> UserPage.propTypes = {
<ide> starredRepoOwners: PropTypes.array.isRequired,
<ide> loadUser: PropTypes.func.isRequired,
<ide> loadStarred: PropTypes.func.isRequired
<del>};
<add>}
<ide>
<ide> function mapStateToProps(state) {
<del> const { login } = state.router.params;
<add> const { login } = state.router.params
<ide> const {
<ide> pagination: { starredByUser },
<ide> entities: { users, repos }
<del> } = state;
<add> } = state
<ide>
<del> const starredPagination = starredByUser[login] || { ids: [] };
<del> const starredRepos = starredPagination.ids.map(id => repos[id]);
<del> const starredRepoOwners = starredRepos.map(repo => users[repo.owner]);
<add> const starredPagination = starredByUser[login] || { ids: [] }
<add> const starredRepos = starredPagination.ids.map(id => repos[id])
<add> const starredRepoOwners = starredRepos.map(repo => users[repo.owner])
<ide>
<ide> return {
<ide> login,
<ide> starredRepos,
<ide> starredRepoOwners,
<ide> starredPagination,
<ide> user: users[login]
<del> };
<add> }
<ide> }
<ide>
<ide> export default connect(mapStateToProps, {
<ide> loadUser,
<ide> loadStarred
<del>})(UserPage);
<add>})(UserPage)
<ide><path>examples/real-world/index.js
<del>import 'babel-core/polyfill';
<del>import React from 'react';
<del>import { render } from 'react-dom';
<del>import Root from './containers/Root';
<del>import configureStore from './store/configureStore';
<add>import 'babel-core/polyfill'
<add>import React from 'react'
<add>import { render } from 'react-dom'
<add>import Root from './containers/Root'
<add>import configureStore from './store/configureStore'
<ide>
<del>const store = configureStore();
<add>const store = configureStore()
<ide>
<ide> render(
<ide> <Root store={store} />,
<ide> document.getElementById('root')
<del>);
<add>)
<ide><path>examples/real-world/middleware/api.js
<del>import { Schema, arrayOf, normalize } from 'normalizr';
<del>import { camelizeKeys } from 'humps';
<del>import 'isomorphic-fetch';
<add>import { Schema, arrayOf, normalize } from 'normalizr'
<add>import { camelizeKeys } from 'humps'
<add>import 'isomorphic-fetch'
<ide>
<ide> // Extracts the next page URL from Github API response.
<ide> function getNextPageUrl(response) {
<del> const link = response.headers.get('link');
<add> const link = response.headers.get('link')
<ide> if (!link) {
<del> return null;
<add> return null
<ide> }
<ide>
<del> const nextLink = link.split(',').find(s => s.indexOf('rel="next"') > -1);
<add> const nextLink = link.split(',').find(s => s.indexOf('rel="next"') > -1)
<ide> if (!nextLink) {
<del> return null;
<add> return null
<ide> }
<ide>
<del> return nextLink.split(';')[0].slice(1, -1);
<add> return nextLink.split('')[0].slice(1, -1)
<ide> }
<ide>
<del>const API_ROOT = 'https://api.github.com/';
<add>const API_ROOT = 'https://api.github.com/'
<ide>
<ide> // Fetches an API response and normalizes the result JSON according to schema.
<ide> // This makes every API response have the same shape, regardless of how nested it was.
<ide> function callApi(endpoint, schema) {
<del> const fullUrl = (endpoint.indexOf(API_ROOT) === -1) ? API_ROOT + endpoint : endpoint;
<add> const fullUrl = (endpoint.indexOf(API_ROOT) === -1) ? API_ROOT + endpoint : endpoint
<ide>
<ide> return fetch(fullUrl)
<ide> .then(response =>
<ide> response.json().then(json => ({ json, response }))
<ide> ).then(({ json, response }) => {
<ide> if (!response.ok) {
<del> return Promise.reject(json);
<add> return Promise.reject(json)
<ide> }
<ide>
<del> const camelizedJson = camelizeKeys(json);
<del> const nextPageUrl = getNextPageUrl(response) || undefined;
<add> const camelizedJson = camelizeKeys(json)
<add> const nextPageUrl = getNextPageUrl(response) || undefined
<ide>
<ide> return Object.assign({},
<ide> normalize(camelizedJson, schema),
<ide> { nextPageUrl }
<del> );
<del> });
<add> )
<add> })
<ide> }
<ide>
<ide> // We use this Normalizr schemas to transform API responses from a nested form
<ide> function callApi(endpoint, schema) {
<ide>
<ide> const userSchema = new Schema('users', {
<ide> idAttribute: 'login'
<del>});
<add>})
<ide>
<ide> const repoSchema = new Schema('repos', {
<ide> idAttribute: 'fullName'
<del>});
<add>})
<ide>
<ide> repoSchema.define({
<ide> owner: userSchema
<del>});
<add>})
<ide>
<ide> // Schemas for Github API responses.
<ide> export const Schemas = {
<ide> USER: userSchema,
<ide> USER_ARRAY: arrayOf(userSchema),
<ide> REPO: repoSchema,
<ide> REPO_ARRAY: arrayOf(repoSchema)
<del>};
<add>}
<ide>
<ide> // Action key that carries API call info interpreted by this Redux middleware.
<del>export const CALL_API = Symbol('Call API');
<add>export const CALL_API = Symbol('Call API')
<ide>
<ide> // A Redux middleware that interprets actions with CALL_API info specified.
<ide> // Performs the call and promises when such actions are dispatched.
<ide> export default store => next => action => {
<del> const callAPI = action[CALL_API];
<add> const callAPI = action[CALL_API]
<ide> if (typeof callAPI === 'undefined') {
<del> return next(action);
<add> return next(action)
<ide> }
<ide>
<del> let { endpoint } = callAPI;
<del> const { schema, types } = callAPI;
<add> let { endpoint } = callAPI
<add> const { schema, types } = callAPI
<ide>
<ide> if (typeof endpoint === 'function') {
<del> endpoint = endpoint(store.getState());
<add> endpoint = endpoint(store.getState())
<ide> }
<ide>
<ide> if (typeof endpoint !== 'string') {
<del> throw new Error('Specify a string endpoint URL.');
<add> throw new Error('Specify a string endpoint URL.')
<ide> }
<ide> if (!schema) {
<del> throw new Error('Specify one of the exported Schemas.');
<add> throw new Error('Specify one of the exported Schemas.')
<ide> }
<ide> if (!Array.isArray(types) || types.length !== 3) {
<del> throw new Error('Expected an array of three action types.');
<add> throw new Error('Expected an array of three action types.')
<ide> }
<ide> if (!types.every(type => typeof type === 'string')) {
<del> throw new Error('Expected action types to be strings.');
<add> throw new Error('Expected action types to be strings.')
<ide> }
<ide>
<ide> function actionWith(data) {
<del> const finalAction = Object.assign({}, action, data);
<del> delete finalAction[CALL_API];
<del> return finalAction;
<add> const finalAction = Object.assign({}, action, data)
<add> delete finalAction[CALL_API]
<add> return finalAction
<ide> }
<ide>
<del> const [requestType, successType, failureType] = types;
<del> next(actionWith({ type: requestType }));
<add> const [ requestType, successType, failureType ] = types
<add> next(actionWith({ type: requestType }))
<ide>
<ide> return callApi(endpoint, schema).then(
<ide> response => next(actionWith({
<ide> export default store => next => action => {
<ide> type: failureType,
<ide> error: error.message || 'Something bad happened'
<ide> }))
<del> );
<del>};
<add> )
<add>}
<ide><path>examples/real-world/reducers/index.js
<del>import * as ActionTypes from '../actions';
<del>import merge from 'lodash/object/merge';
<del>import paginate from './paginate';
<del>import { routerStateReducer as router } from 'redux-router';
<del>import { combineReducers } from 'redux';
<add>import * as ActionTypes from '../actions'
<add>import merge from 'lodash/object/merge'
<add>import paginate from './paginate'
<add>import { routerStateReducer as router } from 'redux-router'
<add>import { combineReducers } from 'redux'
<ide>
<ide> // Updates an entity cache in response to any action with response.entities.
<ide> function entities(state = { users: {}, repos: {} }, action) {
<ide> if (action.response && action.response.entities) {
<del> return merge({}, state, action.response.entities);
<add> return merge({}, state, action.response.entities)
<ide> }
<ide>
<del> return state;
<add> return state
<ide> }
<ide>
<ide> // Updates error message to notify about the failed fetches.
<ide> function errorMessage(state = null, action) {
<del> const { type, error } = action;
<add> const { type, error } = action
<ide>
<ide> if (type === ActionTypes.RESET_ERROR_MESSAGE) {
<del> return null;
<add> return null
<ide> } else if (error) {
<del> return action.error;
<add> return action.error
<ide> }
<ide>
<del> return state;
<add> return state
<ide> }
<ide>
<ide> // Updates the pagination data for different actions.
<ide> const pagination = combineReducers({
<ide> ActionTypes.STARGAZERS_FAILURE
<ide> ]
<ide> })
<del>});
<add>})
<ide>
<ide> const rootReducer = combineReducers({
<ide> entities,
<ide> pagination,
<ide> errorMessage,
<ide> router
<del>});
<add>})
<ide>
<del>export default rootReducer;
<add>export default rootReducer
<ide><path>examples/real-world/reducers/paginate.js
<del>import merge from 'lodash/object/merge';
<del>import union from 'lodash/array/union';
<add>import merge from 'lodash/object/merge'
<add>import union from 'lodash/array/union'
<ide>
<ide> // Creates a reducer managing pagination, given the action types to handle,
<ide> // and a function telling how to extract the key from an action.
<ide> export default function paginate({ types, mapActionToKey }) {
<ide> if (!Array.isArray(types) || types.length !== 3) {
<del> throw new Error('Expected types to be an array of three elements.');
<add> throw new Error('Expected types to be an array of three elements.')
<ide> }
<ide> if (!types.every(t => typeof t === 'string')) {
<del> throw new Error('Expected types to be strings.');
<add> throw new Error('Expected types to be strings.')
<ide> }
<ide> if (typeof mapActionToKey !== 'function') {
<del> throw new Error('Expected mapActionToKey to be a function.');
<add> throw new Error('Expected mapActionToKey to be a function.')
<ide> }
<ide>
<del> const [requestType, successType, failureType] = types;
<add> const [ requestType, successType, failureType ] = types
<ide>
<ide> function updatePagination(state = {
<ide> isFetching: false,
<ide> export default function paginate({ types, mapActionToKey }) {
<ide> ids: []
<ide> }, action) {
<ide> switch (action.type) {
<del> case requestType:
<del> return merge({}, state, {
<del> isFetching: true
<del> });
<del> case successType:
<del> return merge({}, state, {
<del> isFetching: false,
<del> ids: union(state.ids, action.response.result),
<del> nextPageUrl: action.response.nextPageUrl,
<del> pageCount: state.pageCount + 1
<del> });
<del> case failureType:
<del> return merge({}, state, {
<del> isFetching: false
<del> });
<del> default:
<del> return state;
<add> case requestType:
<add> return merge({}, state, {
<add> isFetching: true
<add> })
<add> case successType:
<add> return merge({}, state, {
<add> isFetching: false,
<add> ids: union(state.ids, action.response.result),
<add> nextPageUrl: action.response.nextPageUrl,
<add> pageCount: state.pageCount + 1
<add> })
<add> case failureType:
<add> return merge({}, state, {
<add> isFetching: false
<add> })
<add> default:
<add> return state
<ide> }
<ide> }
<ide>
<ide> return function updatePaginationByKey(state = {}, action) {
<ide> switch (action.type) {
<del> case requestType:
<del> case successType:
<del> case failureType:
<del> const key = mapActionToKey(action);
<del> if (typeof key !== 'string') {
<del> throw new Error('Expected key to be a string.');
<del> }
<del> return merge({}, state, {
<del> [key]: updatePagination(state[key], action)
<del> });
<del> default:
<del> return state;
<add> case requestType:
<add> case successType:
<add> case failureType:
<add> const key = mapActionToKey(action)
<add> if (typeof key !== 'string') {
<add> throw new Error('Expected key to be a string.')
<add> }
<add> return merge({}, state, {
<add> [key]: updatePagination(state[key], action)
<add> })
<add> default:
<add> return state
<ide> }
<del> };
<add> }
<ide> }
<ide><path>examples/real-world/routes.js
<del>import React from 'react';
<del>import { Route } from 'react-router';
<del>import App from './containers/App';
<del>import UserPage from './containers/UserPage';
<del>import RepoPage from './containers/RepoPage';
<add>import React from 'react'
<add>import { Route } from 'react-router'
<add>import App from './containers/App'
<add>import UserPage from './containers/UserPage'
<add>import RepoPage from './containers/RepoPage'
<ide>
<ide> export default (
<ide> <Route path="/" component={App}>
<ide> export default (
<ide> <Route path="/:login"
<ide> component={UserPage} />
<ide> </Route>
<del>);
<add>)
<ide><path>examples/real-world/server.js
<del>var webpack = require('webpack');
<del>var webpackDevMiddleware = require('webpack-dev-middleware');
<del>var webpackHotMiddleware = require('webpack-hot-middleware');
<del>var config = require('./webpack.config');
<add>var webpack = require('webpack')
<add>var webpackDevMiddleware = require('webpack-dev-middleware')
<add>var webpackHotMiddleware = require('webpack-hot-middleware')
<add>var config = require('./webpack.config')
<ide>
<del>var app = new require('express')();
<del>var port = 3000;
<add>var app = new require('express')()
<add>var port = 3000
<ide>
<del>var compiler = webpack(config);
<del>app.use(webpackDevMiddleware(compiler, { noInfo: true, publicPath: config.output.publicPath }));
<del>app.use(webpackHotMiddleware(compiler));
<add>var compiler = webpack(config)
<add>app.use(webpackDevMiddleware(compiler, { noInfo: true, publicPath: config.output.publicPath }))
<add>app.use(webpackHotMiddleware(compiler))
<ide>
<ide> app.use(function(req, res) {
<del> res.sendFile(__dirname + '/index.html');
<del>});
<add> res.sendFile(__dirname + '/index.html')
<add>})
<ide>
<ide> app.listen(port, function(error) {
<ide> if (error) {
<del> console.error(error);
<add> console.error(error)
<ide> } else {
<del> console.info("==> 🌎 Listening on port %s. Open up http://localhost:%s/ in your browser.", port, port);
<add> console.info("==> 🌎 Listening on port %s. Open up http://localhost:%s/ in your browser.", port, port)
<ide> }
<del>});
<add>})
<ide><path>examples/real-world/store/configureStore.dev.js
<del>import { createStore, applyMiddleware, compose } from 'redux';
<del>import { reduxReactRouter } from 'redux-router';
<del>import DevTools from '../containers/DevTools';
<del>import createHistory from 'history/lib/createBrowserHistory';
<del>import routes from '../routes';
<del>import thunk from 'redux-thunk';
<del>import api from '../middleware/api';
<del>import createLogger from 'redux-logger';
<del>import rootReducer from '../reducers';
<add>import { createStore, applyMiddleware, compose } from 'redux'
<add>import { reduxReactRouter } from 'redux-router'
<add>import DevTools from '../containers/DevTools'
<add>import createHistory from 'history/lib/createBrowserHistory'
<add>import routes from '../routes'
<add>import thunk from 'redux-thunk'
<add>import api from '../middleware/api'
<add>import createLogger from 'redux-logger'
<add>import rootReducer from '../reducers'
<ide>
<ide> const finalCreateStore = compose(
<ide> applyMiddleware(thunk, api),
<ide> reduxReactRouter({ routes, createHistory }),
<ide> applyMiddleware(createLogger()),
<ide> DevTools.instrument()
<del>)(createStore);
<add>)(createStore)
<ide>
<ide> export default function configureStore(initialState) {
<del> const store = finalCreateStore(rootReducer, initialState);
<add> const store = finalCreateStore(rootReducer, initialState)
<ide>
<ide> if (module.hot) {
<ide> // Enable Webpack hot module replacement for reducers
<ide> module.hot.accept('../reducers', () => {
<del> const nextRootReducer = require('../reducers');
<del> store.replaceReducer(nextRootReducer);
<del> });
<add> const nextRootReducer = require('../reducers')
<add> store.replaceReducer(nextRootReducer)
<add> })
<ide> }
<ide>
<del> return store;
<add> return store
<ide> }
<ide><path>examples/real-world/store/configureStore.js
<ide> if (process.env.NODE_ENV === 'production') {
<del> module.exports = require('./configureStore.prod');
<add> module.exports = require('./configureStore.prod')
<ide> } else {
<del> module.exports = require('./configureStore.dev');
<add> module.exports = require('./configureStore.dev')
<ide> }
<ide><path>examples/real-world/store/configureStore.prod.js
<del>import { createStore, applyMiddleware, compose } from 'redux';
<del>import { reduxReactRouter } from 'redux-router';
<del>import createHistory from 'history/lib/createBrowserHistory';
<del>import routes from '../routes';
<del>import thunk from 'redux-thunk';
<del>import api from '../middleware/api';
<del>import rootReducer from '../reducers';
<add>import { createStore, applyMiddleware, compose } from 'redux'
<add>import { reduxReactRouter } from 'redux-router'
<add>import createHistory from 'history/lib/createBrowserHistory'
<add>import routes from '../routes'
<add>import thunk from 'redux-thunk'
<add>import api from '../middleware/api'
<add>import rootReducer from '../reducers'
<ide>
<ide> const finalCreateStore = compose(
<ide> applyMiddleware(thunk, api),
<ide> reduxReactRouter({ routes, createHistory })
<del>)(createStore);
<add>)(createStore)
<ide>
<ide> export default function configureStore(initialState) {
<del> return finalCreateStore(rootReducer, initialState);
<add> return finalCreateStore(rootReducer, initialState)
<ide> }
<ide><path>examples/real-world/webpack.config.js
<del>var path = require('path');
<del>var webpack = require('webpack');
<add>var path = require('path')
<add>var webpack = require('webpack')
<ide>
<ide> module.exports = {
<ide> devtool: 'cheap-module-eval-source-map',
<ide> module.exports = {
<ide> module: {
<ide> loaders: [{
<ide> test: /\.js$/,
<del> loaders: ['babel'],
<add> loaders: [ 'babel' ],
<ide> exclude: /node_modules/,
<ide> include: __dirname
<ide> }]
<ide> }
<del>};
<add>}
<ide>
<ide>
<ide> // When inside Redux repo, prefer src to compiled version.
<ide> // You can safely delete these lines in your project.
<del>var reduxSrc = path.join(__dirname, '..', '..', 'src');
<del>var reduxNodeModules = path.join(__dirname, '..', '..', 'node_modules');
<del>var fs = require('fs');
<add>var reduxSrc = path.join(__dirname, '..', '..', 'src')
<add>var reduxNodeModules = path.join(__dirname, '..', '..', 'node_modules')
<add>var fs = require('fs')
<ide> if (fs.existsSync(reduxSrc) && fs.existsSync(reduxNodeModules)) {
<ide> // Resolve Redux to source
<del> module.exports.resolve = { alias: { 'redux': reduxSrc } };
<add> module.exports.resolve = { alias: { 'redux': reduxSrc } }
<ide> // Compile Redux from source
<ide> module.exports.module.loaders.push({
<ide> test: /\.js$/,
<del> loaders: ['babel'],
<add> loaders: [ 'babel' ],
<ide> include: reduxSrc
<del> });
<add> })
<ide> } | 22 |
Python | Python | change function signature | 0b2b899744ff990ff1e329c55c623e281193d4c7 | <ide><path>official/recommendation/data_preprocessing.py
<ide> def _filter_index_sort(raw_rating_path, cache_path):
<ide>
<ide> def instantiate_pipeline(dataset, data_dir, params, constructor_type=None,
<ide> deterministic=False, epoch_dir=None):
<del> # type: (str, str, dict, typing.Optional[str], bool, typing.Optional[str]) -> (NCFDataset, typing.Callable)
<add> # type: (str, str, dict, typing.Optional[str], bool, typing.Optional[str]) -> (int, int, data_pipeline.BaseDataConstructor)
<ide> """Load and digest data CSV into a usable form.
<ide>
<ide> Args: | 1 |
Python | Python | add param to clouddatatransferserviceoperator | 02288cf2baf590e448cd008f6216ccf8b776a67a | <ide><path>airflow/providers/google/cloud/operators/cloud_storage_transfer_service.py
<ide> HTTP_DATA_SOURCE,
<ide> MINUTES,
<ide> MONTH,
<add> NAME,
<ide> OBJECT_CONDITIONS,
<ide> PROJECT_ID,
<ide> SCHEDULE,
<ide> class CloudDataTransferServiceS3ToGCSOperator(BaseOperator):
<ide> :param transfer_options: Optional transfer service transfer options; see
<ide> https://cloud.google.com/storage-transfer/docs/reference/rest/v1/TransferSpec
<ide> :type transfer_options: dict
<del> :param wait: Wait for transfer to finish
<add> :param wait: Wait for transfer to finish. It must be set to True, if
<add> 'delete_job_after_completion' is set to True.
<ide> :type wait: bool
<ide> :param timeout: Time to wait for the operation to end in seconds. Defaults to 60 seconds if not specified.
<ide> :type timeout: Optional[Union[float, timedelta]]
<ide> class CloudDataTransferServiceS3ToGCSOperator(BaseOperator):
<ide> Service Account Token Creator IAM role to the directly preceding identity, with first
<ide> account from the list granting this role to the originating account (templated).
<ide> :type google_impersonation_chain: Union[str, Sequence[str]]
<add> :param delete_job_after_completion: If True, delete the job after complete.
<add> If set to True, 'wait' must be set to True.
<add> :type delete_job_after_completion: bool
<ide> """
<ide>
<ide> template_fields = (
<ide> def __init__( # pylint: disable=too-many-arguments
<ide> wait: bool = True,
<ide> timeout: Optional[float] = None,
<ide> google_impersonation_chain: Optional[Union[str, Sequence[str]]] = None,
<add> delete_job_after_completion: bool = False,
<ide> **kwargs,
<ide> ) -> None:
<ide>
<ide> def __init__( # pylint: disable=too-many-arguments
<ide> self.wait = wait
<ide> self.timeout = timeout
<ide> self.google_impersonation_chain = google_impersonation_chain
<add> self.delete_job_after_completion = delete_job_after_completion
<add> self._validate_inputs()
<add>
<add> def _validate_inputs(self) -> None:
<add> if self.delete_job_after_completion and not self.wait:
<add> raise AirflowException("If 'delete_job_after_completion' is True, then 'wait' must also be True.")
<ide>
<ide> def execute(self, context) -> None:
<ide> hook = CloudDataTransferServiceHook(
<ide> def execute(self, context) -> None:
<ide>
<ide> if self.wait:
<ide> hook.wait_for_transfer_job(job, timeout=self.timeout)
<add> if self.delete_job_after_completion:
<add> hook.delete_transfer_job(job_name=job[NAME], project_id=self.project_id)
<ide>
<ide> def _create_body(self) -> dict:
<ide> body = {
<ide> class CloudDataTransferServiceGCSToGCSOperator(BaseOperator):
<ide> :param transfer_options: Optional transfer service transfer options; see
<ide> https://cloud.google.com/storage-transfer/docs/reference/rest/v1/TransferSpec#TransferOptions
<ide> :type transfer_options: dict
<del> :param wait: Wait for transfer to finish; defaults to `True`
<add> :param wait: Wait for transfer to finish. It must be set to True, if
<add> 'delete_job_after_completion' is set to True.
<ide> :type wait: bool
<ide> :param timeout: Time to wait for the operation to end in seconds. Defaults to 60 seconds if not specified.
<ide> :type timeout: Optional[Union[float, timedelta]]
<ide> class CloudDataTransferServiceGCSToGCSOperator(BaseOperator):
<ide> Service Account Token Creator IAM role to the directly preceding identity, with first
<ide> account from the list granting this role to the originating account (templated).
<ide> :type google_impersonation_chain: Union[str, Sequence[str]]
<add> :param delete_job_after_completion: If True, delete the job after complete.
<add> If set to True, 'wait' must be set to True.
<add> :type delete_job_after_completion: bool
<ide> """
<ide>
<ide> template_fields = (
<ide> def __init__( # pylint: disable=too-many-arguments
<ide> wait: bool = True,
<ide> timeout: Optional[float] = None,
<ide> google_impersonation_chain: Optional[Union[str, Sequence[str]]] = None,
<add> delete_job_after_completion: bool = False,
<ide> **kwargs,
<ide> ) -> None:
<ide>
<ide> def __init__( # pylint: disable=too-many-arguments
<ide> self.wait = wait
<ide> self.timeout = timeout
<ide> self.google_impersonation_chain = google_impersonation_chain
<add> self.delete_job_after_completion = delete_job_after_completion
<add> self._validate_inputs()
<add>
<add> def _validate_inputs(self) -> None:
<add> if self.delete_job_after_completion and not self.wait:
<add> raise AirflowException("If 'delete_job_after_completion' is True, then 'wait' must also be True.")
<ide>
<ide> def execute(self, context) -> None:
<ide> hook = CloudDataTransferServiceHook(
<ide> def execute(self, context) -> None:
<ide>
<ide> if self.wait:
<ide> hook.wait_for_transfer_job(job, timeout=self.timeout)
<add> if self.delete_job_after_completion:
<add> hook.delete_transfer_job(job_name=job[NAME], project_id=self.project_id)
<ide>
<ide> def _create_body(self) -> dict:
<ide> body = {
<ide><path>tests/providers/google/cloud/operators/test_cloud_storage_transfer_service.py
<ide> def test_execute(self, mock_aws_hook, mock_transfer_hook):
<ide> )
<ide>
<ide> assert mock_transfer_hook.return_value.wait_for_transfer_job.called
<add> assert not mock_transfer_hook.return_value.delete_transfer_job.called
<ide>
<ide> @mock.patch(
<ide> 'airflow.providers.google.cloud.operators.cloud_storage_transfer_service.CloudDataTransferServiceHook'
<ide> def test_execute_skip_wait(self, mock_aws_hook, mock_transfer_hook):
<ide> )
<ide>
<ide> assert not mock_transfer_hook.return_value.wait_for_transfer_job.called
<add> assert not mock_transfer_hook.return_value.delete_transfer_job.called
<add>
<add> @mock.patch(
<add> 'airflow.providers.google.cloud.operators.cloud_storage_transfer_service.CloudDataTransferServiceHook'
<add> )
<add> @mock.patch('airflow.providers.google.cloud.operators.cloud_storage_transfer_service.AwsBaseHook')
<add> def test_execute_delete_job_after_completion(self, mock_aws_hook, mock_transfer_hook):
<add> mock_aws_hook.return_value.get_credentials.return_value = Credentials(
<add> TEST_AWS_ACCESS_KEY_ID, TEST_AWS_ACCESS_SECRET, None
<add> )
<add>
<add> operator = CloudDataTransferServiceS3ToGCSOperator(
<add> task_id=TASK_ID,
<add> s3_bucket=AWS_BUCKET_NAME,
<add> gcs_bucket=GCS_BUCKET_NAME,
<add> description=DESCRIPTION,
<add> schedule=SCHEDULE_DICT,
<add> wait=True,
<add> delete_job_after_completion=True,
<add> )
<add>
<add> operator.execute(None)
<add>
<add> mock_transfer_hook.return_value.create_transfer_job.assert_called_once_with(
<add> body=VALID_TRANSFER_JOB_AWS_RAW
<add> )
<add>
<add> assert mock_transfer_hook.return_value.wait_for_transfer_job.called
<add> assert mock_transfer_hook.return_value.delete_transfer_job.called
<add>
<add> @mock.patch(
<add> 'airflow.providers.google.cloud.operators.cloud_storage_transfer_service.CloudDataTransferServiceHook'
<add> )
<add> @mock.patch('airflow.providers.google.cloud.operators.cloud_storage_transfer_service.AwsBaseHook')
<add> def test_execute_should_throw_ex_when_delete_job_without_wait(self, mock_aws_hook, mock_transfer_hook):
<add> mock_aws_hook.return_value.get_credentials.return_value = Credentials(
<add> TEST_AWS_ACCESS_KEY_ID, TEST_AWS_ACCESS_SECRET, None
<add> )
<add>
<add> with pytest.raises(AirflowException) as ctx:
<add>
<add> operator = CloudDataTransferServiceS3ToGCSOperator(
<add> task_id=TASK_ID,
<add> s3_bucket=AWS_BUCKET_NAME,
<add> gcs_bucket=GCS_BUCKET_NAME,
<add> description=DESCRIPTION,
<add> schedule=SCHEDULE_DICT,
<add> wait=False,
<add> delete_job_after_completion=True,
<add> )
<add>
<add> operator.execute(None)
<add>
<add> err = ctx.value
<add> assert "If 'delete_job_after_completion' is True, then 'wait' must also be True." in str(err)
<add> mock_aws_hook.assert_not_called()
<add> mock_transfer_hook.assert_not_called()
<ide>
<ide>
<ide> class TestGoogleCloudStorageToGoogleCloudStorageTransferOperator(unittest.TestCase):
<ide> def test_execute(self, mock_transfer_hook):
<ide> body=VALID_TRANSFER_JOB_GCS_RAW
<ide> )
<ide> assert mock_transfer_hook.return_value.wait_for_transfer_job.called
<add> assert not mock_transfer_hook.return_value.delete_transfer_job.called
<ide>
<ide> @mock.patch(
<ide> 'airflow.providers.google.cloud.operators.cloud_storage_transfer_service.CloudDataTransferServiceHook'
<ide> def test_execute_skip_wait(self, mock_transfer_hook):
<ide> body=VALID_TRANSFER_JOB_GCS_RAW
<ide> )
<ide> assert not mock_transfer_hook.return_value.wait_for_transfer_job.called
<add> assert not mock_transfer_hook.return_value.delete_transfer_job.called
<add>
<add> @mock.patch(
<add> 'airflow.providers.google.cloud.operators.cloud_storage_transfer_service.CloudDataTransferServiceHook'
<add> )
<add> def test_execute_delete_job_after_completion(self, mock_transfer_hook):
<add>
<add> operator = CloudDataTransferServiceGCSToGCSOperator(
<add> task_id=TASK_ID,
<add> source_bucket=GCS_BUCKET_NAME,
<add> destination_bucket=GCS_BUCKET_NAME,
<add> description=DESCRIPTION,
<add> schedule=SCHEDULE_DICT,
<add> wait=True,
<add> delete_job_after_completion=True,
<add> )
<add>
<add> operator.execute(None)
<add>
<add> mock_transfer_hook.return_value.create_transfer_job.assert_called_once_with(
<add> body=VALID_TRANSFER_JOB_GCS_RAW
<add> )
<add> assert mock_transfer_hook.return_value.wait_for_transfer_job.called
<add> assert mock_transfer_hook.return_value.delete_transfer_job.called
<add>
<add> @mock.patch(
<add> 'airflow.providers.google.cloud.operators.cloud_storage_transfer_service.CloudDataTransferServiceHook'
<add> )
<add> def test_execute_should_throw_ex_when_delete_job_without_wait(self, mock_transfer_hook):
<add>
<add> with pytest.raises(AirflowException) as ctx:
<add>
<add> operator = CloudDataTransferServiceS3ToGCSOperator(
<add> task_id=TASK_ID,
<add> s3_bucket=AWS_BUCKET_NAME,
<add> gcs_bucket=GCS_BUCKET_NAME,
<add> description=DESCRIPTION,
<add> schedule=SCHEDULE_DICT,
<add> wait=False,
<add> delete_job_after_completion=True,
<add> )
<add>
<add> operator.execute(None)
<add>
<add> err = ctx.value
<add> assert "If 'delete_job_after_completion' is True, then 'wait' must also be True." in str(err)
<add> mock_transfer_hook.assert_not_called() | 2 |
Python | Python | fix python 2 tests | c079d7ddff7eeb653842f33f1f3fecd8b210e616 | <ide><path>pytorch_transformers/tests/tokenization_bert_test.py
<ide> _is_control, _is_punctuation,
<ide> _is_whitespace, VOCAB_FILES_NAMES)
<ide>
<del>from .tokenization_tests_commons import create_and_check_tokenizer_commons
<add>from .tokenization_tests_commons import create_and_check_tokenizer_commons, TemporaryDirectory
<ide>
<ide> class TokenizationTest(unittest.TestCase):
<ide>
<ide> def test_full_tokenizer(self):
<ide> "[UNK]", "[CLS]", "[SEP]", "want", "##want", "##ed", "wa", "un", "runn",
<ide> "##ing", ",", "low", "lowest",
<ide> ]
<del> vocab_directory = "/tmp/"
<del> vocab_file = os.path.join(vocab_directory, VOCAB_FILES_NAMES['vocab_file'])
<del> with open(vocab_file, "w", encoding='utf-8') as vocab_writer:
<del> vocab_writer.write("".join([x + "\n" for x in vocab_tokens]))
<del> vocab_file = vocab_writer.name
<add> with TemporaryDirectory() as tmpdirname:
<add> vocab_file = os.path.join(tmpdirname, VOCAB_FILES_NAMES['vocab_file'])
<add> with open(vocab_file, "w", encoding='utf-8') as vocab_writer:
<add> vocab_writer.write("".join([x + "\n" for x in vocab_tokens]))
<ide>
<del> create_and_check_tokenizer_commons(self, BertTokenizer, pretrained_model_name_or_path=vocab_directory)
<add> create_and_check_tokenizer_commons(self, BertTokenizer, tmpdirname)
<ide>
<del> tokenizer = BertTokenizer(vocab_file)
<add> tokenizer = BertTokenizer(vocab_file)
<ide>
<del> tokens = tokenizer.tokenize(u"UNwant\u00E9d,running")
<del> self.assertListEqual(tokens, ["un", "##want", "##ed", ",", "runn", "##ing"])
<del> self.assertListEqual(tokenizer.convert_tokens_to_ids(tokens), [7, 4, 5, 10, 8, 9])
<del>
<del> os.remove(vocab_file)
<add> tokens = tokenizer.tokenize(u"UNwant\u00E9d,running")
<add> self.assertListEqual(tokens, ["un", "##want", "##ed", ",", "runn", "##ing"])
<add> self.assertListEqual(tokenizer.convert_tokens_to_ids(tokens), [7, 4, 5, 10, 8, 9])
<ide>
<ide> def test_chinese(self):
<ide> tokenizer = BasicTokenizer()
<ide><path>pytorch_transformers/tests/tokenization_gpt2_test.py
<ide> import os
<ide> import unittest
<ide> import json
<del>import tempfile
<ide>
<ide> from pytorch_transformers.tokenization_gpt2 import GPT2Tokenizer, VOCAB_FILES_NAMES
<ide>
<del>from .tokenization_tests_commons import create_and_check_tokenizer_commons
<add>from .tokenization_tests_commons import create_and_check_tokenizer_commons, TemporaryDirectory
<ide>
<ide> class GPT2TokenizationTest(unittest.TestCase):
<ide>
<ide> def test_full_tokenizer(self):
<ide> merges = ["#version: 0.2", "l o", "lo w", "e r", ""]
<ide> special_tokens_map = {"unk_token": "<unk>"}
<ide>
<del> with tempfile.TemporaryDirectory() as tmpdirname:
<add> with TemporaryDirectory() as tmpdirname:
<ide> vocab_file = os.path.join(tmpdirname, VOCAB_FILES_NAMES['vocab_file'])
<ide> merges_file = os.path.join(tmpdirname, VOCAB_FILES_NAMES['merges_file'])
<ide> with open(vocab_file, "w") as fp:
<ide><path>pytorch_transformers/tests/tokenization_openai_test.py
<ide> import os
<ide> import unittest
<ide> import json
<del>import tempfile
<ide>
<ide> from pytorch_transformers.tokenization_openai import OpenAIGPTTokenizer, VOCAB_FILES_NAMES
<ide>
<del>from.tokenization_tests_commons import create_and_check_tokenizer_commons
<add>from .tokenization_tests_commons import create_and_check_tokenizer_commons, TemporaryDirectory
<ide>
<ide>
<ide> class OpenAIGPTTokenizationTest(unittest.TestCase):
<ide> def test_full_tokenizer(self):
<ide> vocab_tokens = dict(zip(vocab, range(len(vocab))))
<ide> merges = ["#version: 0.2", "l o", "lo w", "e r</w>", ""]
<ide>
<del> with tempfile.TemporaryDirectory() as tmpdirname:
<add> with TemporaryDirectory() as tmpdirname:
<ide> vocab_file = os.path.join(tmpdirname, VOCAB_FILES_NAMES['vocab_file'])
<ide> merges_file = os.path.join(tmpdirname, VOCAB_FILES_NAMES['merges_file'])
<ide> with open(vocab_file, "w") as fp:
<ide><path>pytorch_transformers/tests/tokenization_tests_commons.py
<ide> # limitations under the License.
<ide> from __future__ import absolute_import, division, print_function, unicode_literals
<ide>
<del>import os
<ide> import sys
<ide> from io import open
<ide> import tempfile
<del>
<del>if sys.version_info[0] == 3:
<del> unicode = str
<add>import shutil
<ide>
<ide> if sys.version_info[0] == 2:
<ide> import cPickle as pickle
<add>
<add> class TemporaryDirectory(object):
<add> """Context manager for tempfile.mkdtemp() so it's usable with "with" statement."""
<add> def __enter__(self):
<add> self.name = tempfile.mkdtemp()
<add> return self.name
<add> def __exit__(self, exc_type, exc_value, traceback):
<add> shutil.rmtree(self.name)
<ide> else:
<ide> import pickle
<add> TemporaryDirectory = tempfile.TemporaryDirectory
<add> unicode = str
<ide>
<ide>
<ide> def create_and_check_save_and_load_tokenizer(tester, tokenizer_class, *inputs, **kwargs):
<ide> tokenizer = tokenizer_class.from_pretrained(*inputs, **kwargs)
<ide>
<ide> before_tokens = tokenizer.encode(u"He is very happy, UNwant\u00E9d,running")
<ide>
<del> with tempfile.TemporaryDirectory() as tmpdirname:
<add> with TemporaryDirectory() as tmpdirname:
<ide> tokenizer.save_pretrained(tmpdirname)
<ide> tokenizer = tokenizer.from_pretrained(tmpdirname)
<ide>
<ide><path>pytorch_transformers/tests/tokenization_transfo_xl_test.py
<ide> import os
<ide> import unittest
<ide> from io import open
<del>import tempfile
<ide>
<ide> from pytorch_transformers.tokenization_transfo_xl import TransfoXLTokenizer, VOCAB_FILES_NAMES
<ide>
<del>from.tokenization_tests_commons import create_and_check_tokenizer_commons
<add>from.tokenization_tests_commons import create_and_check_tokenizer_commons, TemporaryDirectory
<ide>
<ide> class TransfoXLTokenizationTest(unittest.TestCase):
<ide>
<ide> def test_full_tokenizer(self):
<ide> "<unk>", "[CLS]", "[SEP]", "want", "unwanted", "wa", "un",
<ide> "running", ",", "low", "l",
<ide> ]
<del> with tempfile.TemporaryDirectory() as tmpdirname:
<add> with TemporaryDirectory() as tmpdirname:
<ide> vocab_file = os.path.join(tmpdirname, VOCAB_FILES_NAMES['vocab_file'])
<ide> with open(vocab_file, "w", encoding='utf-8') as vocab_writer:
<ide> vocab_writer.write("".join([x + "\n" for x in vocab_tokens]))
<ide><path>pytorch_transformers/tests/tokenization_xlm_test.py
<ide> import os
<ide> import unittest
<ide> import json
<del>import tempfile
<ide>
<ide> from pytorch_transformers.tokenization_xlm import XLMTokenizer, VOCAB_FILES_NAMES
<ide>
<del>from .tokenization_tests_commons import create_and_check_tokenizer_commons
<add>from .tokenization_tests_commons import create_and_check_tokenizer_commons, TemporaryDirectory
<ide>
<ide> class XLMTokenizationTest(unittest.TestCase):
<ide>
<ide> def test_full_tokenizer(self):
<ide> vocab_tokens = dict(zip(vocab, range(len(vocab))))
<ide> merges = ["l o 123", "lo w 1456", "e r</w> 1789", ""]
<ide>
<del> with tempfile.TemporaryDirectory() as tmpdirname:
<add> with TemporaryDirectory() as tmpdirname:
<ide> vocab_file = os.path.join(tmpdirname, VOCAB_FILES_NAMES['vocab_file'])
<ide> merges_file = os.path.join(tmpdirname, VOCAB_FILES_NAMES['merges_file'])
<ide> with open(vocab_file, "w") as fp:
<ide><path>pytorch_transformers/tests/tokenization_xlnet_test.py
<ide>
<ide> import os
<ide> import unittest
<del>import tempfile
<ide>
<del>from pytorch_transformers.tokenization_xlnet import (XLNetTokenizer, SPIECE_UNDERLINE, VOCAB_FILES_NAMES)
<add>from pytorch_transformers.tokenization_xlnet import (XLNetTokenizer, SPIECE_UNDERLINE)
<ide>
<del>from.tokenization_tests_commons import create_and_check_tokenizer_commons
<add>from .tokenization_tests_commons import create_and_check_tokenizer_commons, TemporaryDirectory
<ide>
<ide> SAMPLE_VOCAB = os.path.join(os.path.dirname(os.path.abspath(__file__)),
<ide> 'fixtures/test_sentencepiece.model')
<ide> class XLNetTokenizationTest(unittest.TestCase):
<ide> def test_full_tokenizer(self):
<ide> tokenizer = XLNetTokenizer(SAMPLE_VOCAB, keep_accents=True)
<ide>
<del> with tempfile.TemporaryDirectory() as tmpdirname:
<add> with TemporaryDirectory() as tmpdirname:
<ide> tokenizer.save_pretrained(tmpdirname)
<ide>
<ide> create_and_check_tokenizer_commons(self, XLNetTokenizer, tmpdirname)
<ide><path>pytorch_transformers/tokenization_utils.py
<ide> def _from_pretrained(cls, pretrained_model_name_or_path, cache_dir=None, *inputs
<ide>
<ide> # Add supplementary tokens.
<ide> if added_tokens_file is not None:
<del> added_tokens = json.load(open(added_tokens_file, encoding="utf-8"))
<del> added_tok_encoder = dict((tok, len(tokenizer) + i) for i, tok in enumerate(added_tokens))
<add> added_tok_encoder = json.load(open(added_tokens_file, encoding="utf-8"))
<ide> added_tok_decoder = {v:k for k, v in added_tok_encoder.items()}
<ide> tokenizer.added_tokens_encoder.update(added_tok_encoder)
<ide> tokenizer.added_tokens_decoder.update(added_tok_decoder)
<ide> def save_pretrained(self, save_directory):
<ide> f.write(json.dumps(self.special_tokens_map, ensure_ascii=False))
<ide>
<ide> with open(added_tokens_file, 'w', encoding='utf-8') as f:
<del> f.write(json.dumps(self.added_tokens_decoder, ensure_ascii=False))
<add> if self.added_tokens_encoder:
<add> out_str = json.dumps(self.added_tokens_decoder, ensure_ascii=False)
<add> else:
<add> out_str = u"{}"
<add> f.write(out_str)
<ide>
<ide> vocab_files = self.save_vocabulary(save_directory)
<ide> | 8 |
Javascript | Javascript | fix context problem | 9850915eeaefeae87f2c34f221fba2bb5f62c4c1 | <ide><path>lib/dependencies/HarmonyImportDependencyParserPlugin.js
<ide> module.exports = class HarmonyImportDependencyParserPlugin {
<ide> expr.range,
<ide> this.strictExportPresence
<ide> );
<del> dep.directImport = false;
<add> dep.directImport = members.length === 0;
<ide> dep.call = true;
<ide> // only in case when we strictly follow the spec we need a special case here
<ide> dep.namespaceObjectAsContext = | 1 |
Java | Java | introduce annotationconfigwac #scan and #register | e128ee2464b1d4bcc988999f4e05da5e8ecdf0ed | <ide><path>org.springframework.web/src/main/java/org/springframework/web/context/support/AnnotationConfigWebApplicationContext.java
<ide>
<ide> package org.springframework.web.context.support;
<ide>
<del>import org.springframework.beans.factory.config.BeanDefinition;
<ide> import org.springframework.beans.factory.support.BeanNameGenerator;
<ide> import org.springframework.beans.factory.support.DefaultListableBeanFactory;
<ide> import org.springframework.context.annotation.AnnotatedBeanDefinitionReader;
<ide> import org.springframework.context.annotation.ClassPathBeanDefinitionScanner;
<ide> import org.springframework.context.annotation.ScopeMetadataResolver;
<add>import org.springframework.util.Assert;
<add>import org.springframework.util.ObjectUtils;
<add>import org.springframework.util.StringUtils;
<ide>
<ide> /**
<ide> * {@link org.springframework.web.context.WebApplicationContext} implementation
<ide> */
<ide> public class AnnotationConfigWebApplicationContext extends AbstractRefreshableWebApplicationContext {
<ide>
<add> private Class<?>[] annotatedClasses;
<add>
<add> private String[] basePackages;
<add>
<add> /**
<add> * {@inheritDoc}
<add> * <p>This implementation accepts delimited values in the form of fully-qualified
<add> * class names, (typically of {@code Configuration} classes) or fully-qualified
<add> * packages to scan for annotated classes. During {@link #loadBeanDefinitions}, these
<add> * locations will be processed in their given order, first attempting to load each
<add> * value as a class. If class loading fails (i.e. a {@code ClassNotFoundException}
<add> * occurs), the value is assumed to be a package and scanning is attempted.
<add> * <p>Note that this method exists primarily for compatibility with Spring's
<add> * {@link org.springframework.web.context.ContextLoader} and that if this application
<add> * context is being configured through an
<add> * {@link org.springframework.context.ApplicationContextInitializer}, use of the
<add> * {@link #register} and {@link #scan} methods are preferred.
<add> * @see #register(Class...)
<add> * @see #scan(String...)
<add> * @see #setConfigLocations(String[])
<add> * @see #loadBeanDefinitions(DefaultListableBeanFactory)
<add> */
<add> @Override
<add> public void setConfigLocation(String location) {
<add> super.setConfigLocation(location);
<add> }
<add>
<add> /**
<add> * {@inheritDoc}
<add> * <p>This implementation accepts individual location values as fully-qualified class
<add> * names (typically {@code @Configuration} classes) or fully-qualified packages to
<add> * scan. During {@link #loadBeanDefinitions}, these locations will be processed in
<add> * order, first attempting to load values as a class, and upon class loading failure
<add> * the value is assumed to be a package to be scanned.
<add> * <p>Note that this method exists primarily for compatibility with Spring's
<add> * {@link org.springframework.web.context.ContextLoader} and that if this application
<add> * context is being configured through an
<add> * {@link org.springframework.context.ApplicationContextInitializer}, use of the
<add> * {@link #register} and {@link #scan} methods are preferred.
<add> * @see #scan(String...)
<add> * @see #register(Class...)
<add> * @see #setConfigLocation(String)
<add> * @see #loadBeanDefinitions(DefaultListableBeanFactory)
<add> */
<add> @Override
<add> public void setConfigLocations(String[] locations) {
<add> super.setConfigLocations(locations);
<add> }
<add>
<add> /**
<add> * Set the annotated classes (typically {@code @Configuration} classes)
<add> * for this web application context.
<add> * @see #loadBeanDefinitions(DefaultListableBeanFactory)
<add> */
<add> public void register(Class<?>... annotatedClasses) {
<add> Assert.notEmpty(annotatedClasses, "At least one annotated class must be specified");
<add> this.annotatedClasses = annotatedClasses;
<add> }
<add>
<add> /**
<add> * Set the base packages to be scanned for annotated classes.
<add> * @see #loadBeanDefinitions(DefaultListableBeanFactory)
<add> */
<add> public void scan(String... basePackages) {
<add> Assert.notEmpty(basePackages, "At least one base package must be specified");
<add> this.basePackages = basePackages;
<add> }
<add>
<ide> /**
<del> * Register a {@link BeanDefinition} for each class specified by {@link #getConfigLocations()},
<del> * or scan each specified package for annotated classes. Enables the default set of
<del> * annotation configuration post processors, such that {@code @Autowired},
<del> * {@code @Required}, and associated annotations can be used.
<del> * <p>Configuration class bean definitions are registered with generated bean definition
<del> * names unless the {@code value} attribute is provided to the stereotype annotation.
<del> * @see #getConfigLocations()
<add> * Register a {@link org.springframework.beans.factory.config.BeanDefinition} for
<add> * any classes specified by {@link #register(Class...)} and scan any packages
<add> * specified by {@link #scan(String...)}.
<add> * <p>For any values specified by {@link #setConfigLocation(String)} or
<add> * {@link #setConfigLocations(String[])}, attempt first to load each location as a
<add> * class, registering a {@code BeanDefinition} if class loading is successful,
<add> * and if class loading fails (i.e. a {@code ClassNotFoundException} is raised),
<add> * assume the value is a package and attempt to scan it for annotated classes.
<add> * <p>Enables the default set of annotation configuration post processors, such that
<add> * {@code @Autowired}, {@code @Required}, and associated annotations can be used.
<add> * <p>Configuration class bean definitions are registered with generated bean
<add> * definition names unless the {@code value} attribute is provided to the stereotype
<add> * annotation.
<add> * @see #register(Class...)
<add> * @see #scan(String...)
<add> * @see #setConfigLocation()
<add> * @see #setConfigLocations()
<ide> * @see AnnotatedBeanDefinitionReader
<ide> * @see ClassPathBeanDefinitionScanner
<ide> */
<ide> protected void loadBeanDefinitions(DefaultListableBeanFactory beanFactory) {
<ide> scanner.setScopeMetadataResolver(scopeMetadataResolver);
<ide> }
<ide>
<add> if (!ObjectUtils.isEmpty(this.annotatedClasses)) {
<add> if (logger.isInfoEnabled()) {
<add> logger.info("Registering annotated classes: [" +
<add> StringUtils.arrayToCommaDelimitedString(this.annotatedClasses) + "]");
<add> }
<add> reader.register(this.annotatedClasses);
<add> }
<add>
<add> if (!ObjectUtils.isEmpty(this.basePackages)) {
<add> if (logger.isInfoEnabled()) {
<add> logger.info("Scanning base packages: [" +
<add> StringUtils.arrayToCommaDelimitedString(this.basePackages) + "]");
<add> }
<add> scanner.scan(this.basePackages);
<add> }
<add>
<ide> String[] configLocations = getConfigLocations();
<ide> if (configLocations != null) {
<ide> for (String configLocation : configLocations) {
<ide><path>org.springframework.web/src/test/java/org/springframework/web/context/support/AnnotationConfigWebApplicationContextTests.java
<ide>
<ide> package org.springframework.web.context.support;
<ide>
<del>import static org.junit.Assert.*;
<del>import org.junit.Test;
<add>import static org.junit.Assert.assertNotNull;
<ide>
<add>import org.junit.Test;
<ide> import org.springframework.context.annotation.Bean;
<ide> import org.springframework.context.annotation.Configuration;
<ide>
<ide> public class AnnotationConfigWebApplicationContextTests {
<ide>
<ide> @Test
<del> public void testSingleWellFormedConfigLocation() {
<del> AnnotationConfigWebApplicationContext ctx = new AnnotationConfigWebApplicationContext();
<add> public void registerSingleClass() {
<add> AnnotationConfigWebApplicationContext ctx =
<add> new AnnotationConfigWebApplicationContext();
<add> ctx.register(Config.class);
<add> ctx.refresh();
<add>
<add> TestBean bean = ctx.getBean(TestBean.class);
<add> assertNotNull(bean);
<add> }
<add>
<add> @Test
<add> public void configLocationWithSingleClass() {
<add> AnnotationConfigWebApplicationContext ctx =
<add> new AnnotationConfigWebApplicationContext();
<ide> ctx.setConfigLocation(Config.class.getName());
<ide> ctx.refresh();
<ide>
<ide> public void testSingleWellFormedConfigLocation() {
<ide> @Configuration
<ide> static class Config {
<ide> @Bean
<del> public TestBean testBean() {
<add> public TestBean myTestBean() {
<ide> return new TestBean();
<ide> }
<ide> } | 2 |
Javascript | Javascript | fix unused variable lint from | 036d342189d6e4b7489af1f0146a7f7164714745 | <ide><path>src/browser/ui/dom/components/ReactDOMSelect.js
<ide> function selectValueType(props, propName, componentName) {
<ide> * @private
<ide> */
<ide> function updateOptions(component, propValue) {
<del> var selectedValue, i, l;
<add> var selectedValue, i;
<ide> var options = findDOMNode(component).options;
<ide>
<ide> if (component.props.multiple) { | 1 |
Text | Text | fix some typos and other errors | 440d61ab364da971973ae8d784e77e21e5cdaa7f | <ide><path>docs/topics/contributing.md
<ide> There are many ways you can contribute to Django REST framework. We'd like it t
<ide>
<ide> The most important thing you can do to help push the REST framework project forward is to be actively involved wherever possible. Code contributions are often overvalued as being the primary way to get involved in a project, we don't believe that needs to be the case.
<ide>
<del>If you use REST framework, we'd love you to be vocal about your experiences with it - you might consider writing a blog post about using REST framework, or publishing a tutorial about building a project with a particular Javascript framework. Experiences from beginners can be particularly helpful because you'll be in the best position to assess which bits of REST framework are more difficult to understand and work with.
<add>If you use REST framework, we'd love you to be vocal about your experiences with it - you might consider writing a blog post about using REST framework, or publishing a tutorial about building a project with a particular JavaScript framework. Experiences from beginners can be particularly helpful because you'll be in the best position to assess which bits of REST framework are more difficult to understand and work with.
<ide>
<del>Other really great ways you can help move the community forward include helping answer questions on the [discussion group][google-group], or setting up an [email alert on StackOverflow][so-filter] so that you get notified of any new questions with the `django-rest-framework` tag.
<add>Other really great ways you can help move the community forward include helping to answer questions on the [discussion group][google-group], or setting up an [email alert on StackOverflow][so-filter] so that you get notified of any new questions with the `django-rest-framework` tag.
<ide>
<ide> When answering questions make sure to help future contributors find their way around by hyperlinking wherever possible to related threads and tickets, and include backlinks from those items if relevant.
<ide>
<ide> Some tips on good issue reporting:
<ide> * When describing issues try to phrase your ticket in terms of the *behavior* you think needs changing rather than the *code* you think need changing.
<ide> * Search the issue list first for related items, and make sure you're running the latest version of REST framework before reporting an issue.
<ide> * If reporting a bug, then try to include a pull request with a failing test case. This will help us quickly identify if there is a valid issue, and make sure that it gets fixed more quickly if there is one.
<del>* Feature requests will often be closed with a recommendation that they be implemented outside of the core REST framework library. Keeping new feature requests implemented as third party libraries allows us to keep down the maintainence overhead of REST framework, so that the focus can be on continued stability, bugfixes, and great documentation.
<add>* Feature requests will often be closed with a recommendation that they be implemented outside of the core REST framework library. Keeping new feature requests implemented as third party libraries allows us to keep down the maintenance overhead of REST framework, so that the focus can be on continued stability, bugfixes, and great documentation.
<ide> * Closing an issue doesn't necessarily mean the end of a discussion. If you believe your issue has been closed incorrectly, explain why and we'll consider if it needs to be reopened.
<ide>
<ide> ## Triaging issues
<ide> To start developing on Django REST framework, clone the repo:
<ide>
<ide> git clone [email protected]:tomchristie/django-rest-framework.git
<ide>
<del>Changes should broadly follow the [PEP 8][pep-8] style conventions, and we recommend you setup your editor to automatically indicated non-conforming styles.
<add>Changes should broadly follow the [PEP 8][pep-8] style conventions, and we recommend you set up your editor to automatically indicate non-conforming styles.
<ide>
<ide> ## Testing
<ide>
<ide> GitHub's documentation for working on pull requests is [available here][pull-req
<ide>
<ide> Always run the tests before submitting pull requests, and ideally run `tox` in order to check that your modifications are compatible with both Python 2 and Python 3, and that they run properly on all supported versions of Django.
<ide>
<del>Once you've made a pull request take a look at the travis build status in the GitHub interface and make sure the tests are runnning as you'd expect.
<add>Once you've made a pull request take a look at the Travis build status in the GitHub interface and make sure the tests are running as you'd expect.
<ide>
<ide> ![Travis status][travis-status]
<ide>
<ide> Sometimes, in order to ensure your code works on various different versions of D
<ide>
<ide> The documentation for REST framework is built from the [Markdown][markdown] source files in [the docs directory][docs].
<ide>
<del>There are many great markdown editors that make working with the documentation really easy. The [Mou editor for Mac][mou] is one such editor that comes highly recommended.
<add>There are many great Markdown editors that make working with the documentation really easy. The [Mou editor for Mac][mou] is one such editor that comes highly recommended.
<ide>
<ide> ## Building the documentation
<ide>
<ide> Some other tips:
<ide>
<ide> * Keep paragraphs reasonably short.
<ide> * Use double spacing after the end of sentences.
<del>* Don't use the abbreviations such as 'e.g.' but instead use long form, such as 'For example'.
<add>* Don't use abbreviations such as 'e.g.' but instead use the long form, such as 'For example'.
<ide>
<ide> ## Markdown style
<ide>
<ide> If you are hyperlinking to another REST framework document, you should use a rel
<ide>
<ide> [authentication]: ../api-guide/authentication.md
<ide>
<del>Linking in this style means you'll be able to click the hyperlink in your markdown editor to open the referenced document. When the documentation is built, these links will be converted into regular links to HTML pages.
<add>Linking in this style means you'll be able to click the hyperlink in your Markdown editor to open the referenced document. When the documentation is built, these links will be converted into regular links to HTML pages.
<ide>
<ide> ##### 3. Notes
<ide> | 1 |
Text | Text | update readme to include link to middleware docs | 8ba8fe25a9d95d581337702ca9334258152b784a | <ide><path>README.md
<ide> is in fact a shortcut for this:
<ide>
<ide> ```js
<ide> import { createRedux, createDispatcher, composeStores } from 'redux';
<add>import thunkMiddleware from 'redux/lib/middleware/thunk';
<ide> import * as stores from '../stores/index';
<ide>
<ide> // Compose all your Stores into a single Store function with `composeStores`:
<ide> const store = composeStores(stores);
<ide>
<ide> // Create a Dispatcher function for your composite Store:
<del>const dispatcher = createDispatcher(store);
<add>const dispatcher = createDispatcher(
<add> store,
<add> getState => [thunkMiddleware(getState)] // Pass the default middleware
<add>);
<ide>
<ide> // Create a Redux instance using the dispatcher function:
<ide> const redux = createRedux(dispatcher);
<ide> ```
<ide>
<ide> Why would you want to write it longer? Maybe you're an advanced user and want to provide a custom Dispatcher function, or maybe you have a different idea of how to compose your Stores (or you're satisfied with a single Store). Redux lets you do all of this.
<ide>
<add>`createDispatcher()` also gives you the ability to specify middleware -- for example, to add support for promises. [Learn more](https://github.com/gaearon/redux/blob/master/docs/middleware.md) about how to create and use middleware in Redux.
<add>
<ide> When in doubt, use the shorter option!
<ide>
<ide> ## FAQ | 1 |
Python | Python | update rehearsal example | 7ac0f9626c8590b3f88ab31eff3beecd6de0fd2e | <ide><path>examples/training/rehearsal.py
<ide> import srsly
<ide> import spacy
<ide> from spacy.gold import GoldParse
<del>from spacy.util import minibatch
<add>from spacy.util import minibatch, compounding
<ide>
<ide>
<ide> LABEL = "ANIMAL"
<ide> def main(model_name, unlabelled_loc):
<ide> nlp.get_pipe("ner").add_label(LABEL)
<ide> raw_docs = list(read_raw_data(nlp, unlabelled_loc))
<ide> optimizer = nlp.resume_training()
<add> # Avoid use of Adam when resuming training. I don't understand this well
<add> # yet, but I'm getting weird results from Adam. Try commenting out the
<add> # nlp.update(), and using Adam -- you'll find the models drift apart.
<add> # I guess Adam is losing precision, introducing gradient noise?
<add> optimizer.alpha = 0.1
<add> optimizer.b1 = 0.0
<add> optimizer.b2 = 0.0
<ide>
<ide> # get names of other pipes to disable them during training
<ide> other_pipes = [pipe for pipe in nlp.pipe_names if pipe != "ner"]
<add> sizes = compounding(1.0, 4.0, 1.001)
<ide> with nlp.disable_pipes(*other_pipes):
<ide> for itn in range(n_iter):
<ide> random.shuffle(TRAIN_DATA)
<ide> random.shuffle(raw_docs)
<ide> losses = {}
<ide> r_losses = {}
<ide> # batch up the examples using spaCy's minibatch
<del> raw_batches = minibatch(raw_docs, size=batch_size)
<del> for doc, gold in TRAIN_DATA:
<del> nlp.update([doc], [gold], sgd=optimizer, drop=dropout, losses=losses)
<add> raw_batches = minibatch(raw_docs, size=4)
<add> for batch in minibatch(TRAIN_DATA, size=sizes):
<add> docs, golds = zip(*batch)
<add> nlp.update(docs, golds, sgd=optimizer, drop=dropout, losses=losses)
<ide> raw_batch = list(next(raw_batches))
<ide> nlp.rehearse(raw_batch, sgd=optimizer, losses=r_losses)
<ide> print("Losses", losses)
<ide> print("R. Losses", r_losses)
<add> print(nlp.get_pipe('ner').model.unseen_classes)
<add> test_text = "Do you like horses?"
<add> doc = nlp(test_text)
<add> print("Entities in '%s'" % test_text)
<add> for ent in doc.ents:
<add> print(ent.label_, ent.text)
<add>
<add>
<ide>
<ide>
<ide> if __name__ == "__main__": | 1 |
Text | Text | apply suggestions from code review | 57f70e2d7d30f485dc879fd4d1130752c1a42709 | <ide><path>CONTRIBUTING.md
<ide> Include details about your configuration and environment:
<ide>
<ide> This section guides you through submitting an enhancement suggestion for Atom, including completely new features and minor improvements to existing functionality. Following these guidelines helps maintainers and the community understand your suggestion :pencil: and find related suggestions :mag_right:.
<ide>
<del>Before creating enhancement suggestions, please check [this list](#before-submitting-an-enhancement-suggestion) as you might find out that you don't need to create one. When you are creating an enhancement suggestion, please [include as many details as possible](#how-do-i-submit-a-good-enhancement-suggestion). Fill in [the template](https://github.com/atom/.github/blob/master/.github/ISSUE_TEMPLATE/bug_report.md), including the steps that you imagine you would take if the feature you're requesting existed.
<add>Before creating enhancement suggestions, please check [this list](#before-submitting-an-enhancement-suggestion) as you might find out that you don't need to create one. When you are creating an enhancement suggestion, please [include as many details as possible](#how-do-i-submit-a-good-enhancement-suggestion). Fill in [the template](https://github.com/atom/.github/blob/master/.github/ISSUE_TEMPLATE/feature_request.md), including the steps that you imagine you would take if the feature you're requesting existed.
<ide>
<ide> #### Before Submitting An Enhancement Suggestion
<ide>
<ide><path>PULL_REQUEST_TEMPLATE.md
<ide> ⚛👋 Hello there! Welcome. Please follow the steps below to tell us about your contribution.
<ide>
<ide> 1. Copy the correct template for your contribution
<del> - 🐛 Are you fixing a bug? Copy the template from <https://bit.ly/atom-bugfix>
<del> - 📈 Are you improving performance? Copy the template from <https://bit.ly/atom-perf>
<del> - 📝 Are you updating documentation? Copy the template from <https://bit.ly/atom-docs>
<del> - 💻 Are you changing functionality? Copy the template from <https://bit.ly/atom-behavior>
<add> - 🐛 Are you fixing a bug? Copy the template from <https://bit.ly/atom-bugfix-pr>
<add> - 📈 Are you improving performance? Copy the template from <https://bit.ly/atom-perf-pr>
<add> - 📝 Are you updating documentation? Copy the template from <https://bit.ly/atom-docs-pr>
<add> - 💻 Are you changing functionality? Copy the template from <https://bit.ly/atom-behavior-pr>
<ide> 2. Replace this text with the contents of the template
<ide> 3. Fill in all sections of the template
<ide> 4. Click "Create pull request" | 2 |
Java | Java | simplify comparator using method references | f39c6d36c70fbbbbb0323fabf7a1ee6d1c0f4d7c | <ide><path>spring-expression/src/main/java/org/springframework/expression/spel/support/ReflectiveConstructorResolver.java
<ide> import java.lang.reflect.Constructor;
<ide> import java.util.ArrayList;
<ide> import java.util.Arrays;
<add>import java.util.Comparator;
<ide> import java.util.List;
<ide>
<ide> import org.springframework.core.MethodParameter;
<ide> public ConstructorExecutor resolve(EvaluationContext context, String typeName, L
<ide> Class<?> type = context.getTypeLocator().findType(typeName);
<ide> Constructor<?>[] ctors = type.getConstructors();
<ide>
<del> Arrays.sort(ctors, (c1, c2) -> {
<del> int c1pl = c1.getParameterCount();
<del> int c2pl = c2.getParameterCount();
<del> return Integer.compare(c1pl, c2pl);
<del> });
<add> Arrays.sort(ctors, Comparator.comparingInt(Constructor::getParameterCount));
<ide>
<ide> Constructor<?> closeMatch = null;
<ide> Constructor<?> matchRequiringConversion = null; | 1 |
Ruby | Ruby | use relation.from when constructing a relation | 6a776dcc9df437c0bcc3c1ff1d2a79966264bac9 | <ide><path>activerecord/lib/active_record/associations.rb
<ide> def select_all_rows(options, join_dependency)
<ide> def construct_finder_arel_with_included_associations(options, join_dependency)
<ide> scope = scope(:find)
<ide>
<del> relation = arel_table((scope && scope[:from]) || options[:from])
<add> relation = arel_table
<ide>
<ide> for association in join_dependency.join_associations
<ide> relation = association.join_relation(relation)
<ide> def construct_finder_arel_with_included_associations(options, join_dependency)
<ide> select(column_aliases(join_dependency)).
<ide> group(construct_group(options[:group], options[:having], scope)).
<ide> order(construct_order(options[:order], scope)).
<del> where(construct_conditions(options[:conditions], scope))
<add> where(construct_conditions(options[:conditions], scope)).
<add> from((scope && scope[:from]) || options[:from])
<ide>
<ide> relation = relation.where(construct_arel_limited_ids_condition(options, join_dependency)) if !using_limitable_reflections?(join_dependency.reflections) && ((scope && scope[:limit]) || options[:limit])
<ide> relation = relation.limit(construct_limit(options[:limit], scope)) if using_limitable_reflections?(join_dependency.reflections)
<ide><path>activerecord/lib/active_record/base.rb
<ide> def construct_finder_arel(options = {}, scope = scope(:find))
<ide> # TODO add lock to Arel
<ide> validate_find_options(options)
<ide>
<del> relation = arel_table(options[:from]).
<add> relation = arel_table.
<ide> joins(construct_join(options[:joins], scope)).
<ide> where(construct_conditions(options[:conditions], scope)).
<ide> select(options[:select] || (scope && scope[:select]) || default_select(options[:joins] || (scope && scope[:joins]))). | 2 |
Python | Python | add license for images | d490379c71d7c9ad082ee33dc764f5eceb228b1d | <ide><path>libcloud/compute/drivers/gce.py
<ide> def ex_create_forwarding_rule(self, name, target=None, region=None,
<ide>
<ide> def ex_create_image(self, name, volume, description=None, family=None,
<ide> guest_os_features=None, use_existing=True,
<del> wait_for_completion=True):
<add> wait_for_completion=True, ex_licenses=None):
<ide> """
<ide> Create an image from the provided volume.
<ide>
<ide> def ex_create_image(self, name, volume, description=None, family=None,
<ide> valid for bootable images only.
<ide> :type guest_os_features: ``list`` of ``str`` or ``None``
<ide>
<add> :keyword ex_licenses: List of strings representing licenses
<add> to be associated with the image.
<add> :type ex_licenses: ``list`` of ``str``
<add>
<ide> :keyword use_existing: If True and an image with the given name
<ide> already exists, return an object for that
<ide> image instead of attempting to create
<ide> def ex_create_image(self, name, volume, description=None, family=None,
<ide> image_data['rawDisk'] = {'source': volume, 'containerType': 'TAR'}
<ide> else:
<ide> raise ValueError('Source must be instance of StorageVolume or URI')
<add> if ex_licenses:
<add> if isinstance(ex_licenses, str):
<add> ex_licenses = [ex_licenses]
<add> image_data['licenses'] = ex_licenses
<add>
<ide> if guest_os_features:
<ide> image_data['guestOsFeatures'] = []
<ide> if isinstance(guest_os_features, str): | 1 |
Java | Java | revise "streaming" mediatype support | 2896c5d2ab23b6faf1004d3e9aef18d23d790c04 | <ide><path>spring-web/src/main/java/org/springframework/http/codec/DecoderHttpMessageReader.java
<ide> public Mono<T> readMono(ResolvableType actualType, ResolvableType elementType,
<ide> /**
<ide> * Get additional hints for decoding for example based on the server request
<ide> * or annotations from controller method parameters. By default, delegate to
<del> * the decoder if it is an instance of {@link ServerHttpDecoder}.
<add> * the decoder if it is an instance of {@link HttpDecoder}.
<ide> */
<ide> protected Map<String, Object> getReadHints(ResolvableType streamType,
<ide> ResolvableType elementType, ServerHttpRequest request, ServerHttpResponse response) {
<ide>
<del> if (this.decoder instanceof ServerHttpDecoder) {
<del> ServerHttpDecoder<?> httpDecoder = (ServerHttpDecoder<?>) this.decoder;
<add> if (this.decoder instanceof HttpDecoder) {
<add> HttpDecoder<?> httpDecoder = (HttpDecoder<?>) this.decoder;
<ide> return httpDecoder.getDecodeHints(streamType, elementType, request, response);
<ide> }
<ide> return Collections.emptyMap();
<ide><path>spring-web/src/main/java/org/springframework/http/codec/EncoderHttpMessageWriter.java
<ide>
<ide> package org.springframework.http.codec;
<ide>
<del>import java.util.ArrayList;
<ide> import java.util.Collections;
<ide> import java.util.HashMap;
<ide> import java.util.List;
<ide> */
<ide> public class EncoderHttpMessageWriter<T> implements ServerHttpMessageWriter<T> {
<ide>
<del> /**
<del> * Default list of media types that signify a "streaming" scenario such that
<del> * there may be a time lag between items written and hence requires flushing.
<del> */
<del> public static final List<MediaType> DEFAULT_STREAMING_MEDIA_TYPES =
<del> Collections.singletonList(MediaType.APPLICATION_STREAM_JSON);
<del>
<del>
<ide> private final Encoder<T> encoder;
<ide>
<ide> private final List<MediaType> mediaTypes;
<ide>
<ide> private final MediaType defaultMediaType;
<ide>
<del> private final List<MediaType> streamingMediaTypes = new ArrayList<>(1);
<del>
<ide>
<ide> /**
<ide> * Create an instance wrapping the given {@link Encoder}.
<ide> public EncoderHttpMessageWriter(Encoder<T> encoder) {
<ide> this.encoder = encoder;
<ide> this.mediaTypes = MediaType.asMediaTypes(encoder.getEncodableMimeTypes());
<ide> this.defaultMediaType = initDefaultMediaType(this.mediaTypes);
<del> this.streamingMediaTypes.addAll(DEFAULT_STREAMING_MEDIA_TYPES);
<ide> }
<ide>
<ide> private static MediaType initDefaultMediaType(List<MediaType> mediaTypes) {
<ide> public List<MediaType> getWritableMediaTypes() {
<ide> return this.mediaTypes;
<ide> }
<ide>
<del> /**
<del> * Configure "streaming" media types for which flushing should be performed
<del> * automatically vs at the end of the input stream.
<del> * <p>By default this is set to {@link #DEFAULT_STREAMING_MEDIA_TYPES}.
<del> * @param mediaTypes one or more media types to add to the list
<del> */
<del> public void setStreamingMediaTypes(List<MediaType> mediaTypes) {
<del> this.streamingMediaTypes.addAll(mediaTypes);
<del> }
<del>
<del> /**
<del> * Return the configured list of "streaming" media types.
<del> */
<del> public List<MediaType> getStreamingMediaTypes() {
<del> return Collections.unmodifiableList(this.streamingMediaTypes);
<del> }
<del>
<ide>
<ide> @Override
<ide> public boolean canWrite(ResolvableType elementType, MediaType mediaType) {
<ide> private static MediaType addDefaultCharset(MediaType main, MediaType defaultType
<ide> }
<ide>
<ide> private boolean isStreamingMediaType(MediaType contentType) {
<del> return this.streamingMediaTypes.stream().anyMatch(contentType::isCompatibleWith);
<add> return this.encoder instanceof HttpEncoder &&
<add> ((HttpEncoder<?>) this.encoder).getStreamingMediaTypes().stream()
<add> .anyMatch(contentType::isCompatibleWith);
<ide> }
<ide>
<ide>
<ide> public Mono<Void> write(Publisher<? extends T> inputStream, ResolvableType actua
<ide> /**
<ide> * Get additional hints for encoding for example based on the server request
<ide> * or annotations from controller method parameters. By default, delegate to
<del> * the encoder if it is an instance of {@link ServerHttpEncoder}.
<add> * the encoder if it is an instance of {@link HttpEncoder}.
<ide> */
<ide> protected Map<String, Object> getWriteHints(ResolvableType streamType, ResolvableType elementType,
<ide> MediaType mediaType, ServerHttpRequest request, ServerHttpResponse response) {
<ide>
<del> if (this.encoder instanceof ServerHttpEncoder) {
<del> ServerHttpEncoder<?> httpEncoder = (ServerHttpEncoder<?>) this.encoder;
<add> if (this.encoder instanceof HttpEncoder) {
<add> HttpEncoder<?> httpEncoder = (HttpEncoder<?>) this.encoder;
<ide> return httpEncoder.getEncodeHints(streamType, elementType, mediaType, request, response);
<ide> }
<ide> return Collections.emptyMap();
<add><path>spring-web/src/main/java/org/springframework/http/codec/HttpDecoder.java
<del><path>spring-web/src/main/java/org/springframework/http/codec/ServerHttpDecoder.java
<ide> import org.springframework.http.server.reactive.ServerHttpResponse;
<ide>
<ide> /**
<del> * {@code Decoder} extension for server-side decoding of the HTTP request body.
<add> * Extension of {@code Decoder} exposing extra methods relevant in the context
<add> * of HTTP applications.
<ide> *
<ide> * @author Rossen Stoyanchev
<ide> * @since 5.0
<ide> */
<del>public interface ServerHttpDecoder<T> extends Decoder<T> {
<add>public interface HttpDecoder<T> extends Decoder<T> {
<ide>
<ide> /**
<ide> * Get decoding hints based on the server request or annotations on the
<add><path>spring-web/src/main/java/org/springframework/http/codec/HttpEncoder.java
<del><path>spring-web/src/main/java/org/springframework/http/codec/ServerHttpEncoder.java
<ide>
<ide> package org.springframework.http.codec;
<ide>
<add>import java.util.Collections;
<add>import java.util.List;
<ide> import java.util.Map;
<ide>
<ide> import org.springframework.core.ResolvableType;
<ide>
<ide>
<ide> /**
<del> * {@code Encoder} extension for server-side encoding of the HTTP response body.
<add> * Extension of {@code Encoder} exposing extra methods relevant in the context
<add> * of HTTP applications.
<ide> *
<ide> * @author Rossen Stoyanchev
<ide> * @since 5.0
<ide> */
<del>public interface ServerHttpEncoder<T> extends Encoder<T> {
<add>public interface HttpEncoder<T> extends Encoder<T> {
<add>
<add> /**
<add> * Return "streaming" media types for which flushing should be performed
<add> * automatically vs at the end of the input stream.
<add> */
<add> List<MediaType> getStreamingMediaTypes();
<ide>
<ide> /**
<ide> * Get decoding hints based on the server request or annotations on the
<ide> * @param response the current response
<ide> * @return a Map with hints, possibly empty
<ide> */
<del> Map<String, Object> getEncodeHints(ResolvableType actualType, ResolvableType elementType,
<del> MediaType mediaType, ServerHttpRequest request, ServerHttpResponse response);
<add> default Map<String, Object> getEncodeHints(ResolvableType actualType, ResolvableType elementType,
<add> MediaType mediaType, ServerHttpRequest request, ServerHttpResponse response) {
<add>
<add> return Collections.emptyMap();
<add> }
<ide>
<ide> }
<ide><path>spring-web/src/main/java/org/springframework/http/codec/ServerSentEventHttpMessageReader.java
<ide> public ServerSentEventHttpMessageReader(Decoder<?> decoder) {
<ide> }
<ide>
<ide>
<add> /**
<add> * Return the configured {@code Decoder}.
<add> */
<add> public Decoder<?> getDecoder() {
<add> return this.decoder;
<add> }
<add>
<ide> @Override
<ide> public List<MediaType> getReadableMediaTypes() {
<ide> return Collections.singletonList(MediaType.TEXT_EVENT_STREAM);
<ide><path>spring-web/src/main/java/org/springframework/http/codec/ServerSentEventHttpMessageWriter.java
<ide> public ServerSentEventHttpMessageWriter(Encoder<?> encoder) {
<ide> }
<ide>
<ide>
<add> /**
<add> * Return the configured {@code Encoder}.
<add> */
<add> public Encoder<?> getEncoder() {
<add> return this.encoder;
<add> }
<add>
<ide> @Override
<ide> public List<MediaType> getWritableMediaTypes() {
<ide> return WRITABLE_MEDIA_TYPES;
<ide> public Mono<Void> write(Publisher<?> input, ResolvableType actualType, Resolvabl
<ide> private Map<String, Object> getEncodeHints(ResolvableType actualType, ResolvableType elementType,
<ide> MediaType mediaType, ServerHttpRequest request, ServerHttpResponse response) {
<ide>
<del> if (this.encoder instanceof ServerHttpEncoder) {
<del> ServerHttpEncoder<?> httpEncoder = (ServerHttpEncoder<?>) this.encoder;
<add> if (this.encoder instanceof HttpEncoder) {
<add> HttpEncoder<?> httpEncoder = (HttpEncoder<?>) this.encoder;
<ide> return httpEncoder.getEncodeHints(actualType, elementType, mediaType, request, response);
<ide> }
<ide> return Collections.emptyMap();
<ide><path>spring-web/src/main/java/org/springframework/http/codec/json/Jackson2JsonDecoder.java
<ide> import org.springframework.core.codec.CodecException;
<ide> import org.springframework.core.io.buffer.DataBuffer;
<ide> import org.springframework.core.io.buffer.DataBufferUtils;
<del>import org.springframework.http.codec.ServerHttpDecoder;
<add>import org.springframework.http.codec.HttpDecoder;
<ide> import org.springframework.http.converter.json.Jackson2ObjectMapperBuilder;
<ide> import org.springframework.http.server.reactive.ServerHttpRequest;
<ide> import org.springframework.http.server.reactive.ServerHttpResponse;
<ide> * @since 5.0
<ide> * @see Jackson2JsonEncoder
<ide> */
<del>public class Jackson2JsonDecoder extends Jackson2CodecSupport implements ServerHttpDecoder<Object> {
<add>public class Jackson2JsonDecoder extends Jackson2CodecSupport implements HttpDecoder<Object> {
<ide>
<ide> private final JsonObjectDecoder fluxDecoder = new JsonObjectDecoder(true);
<ide>
<ide> private Flux<Object> decodeInternal(JsonObjectDecoder objectDecoder, Publisher<D
<ide> }
<ide>
<ide>
<del> // ServerHttpDecoder...
<add> // HttpDecoder...
<ide>
<ide> @Override
<ide> public Map<String, Object> getDecodeHints(ResolvableType actualType, ResolvableType elementType,
<ide><path>spring-web/src/main/java/org/springframework/http/codec/json/Jackson2JsonEncoder.java
<ide> import java.io.IOException;
<ide> import java.io.OutputStream;
<ide> import java.lang.annotation.Annotation;
<add>import java.util.ArrayList;
<add>import java.util.Collections;
<ide> import java.util.List;
<ide> import java.util.Map;
<ide>
<ide> import org.springframework.core.io.buffer.DataBuffer;
<ide> import org.springframework.core.io.buffer.DataBufferFactory;
<ide> import org.springframework.http.MediaType;
<del>import org.springframework.http.codec.ServerHttpEncoder;
<add>import org.springframework.http.codec.HttpEncoder;
<ide> import org.springframework.http.converter.json.Jackson2ObjectMapperBuilder;
<ide> import org.springframework.http.server.reactive.ServerHttpRequest;
<ide> import org.springframework.http.server.reactive.ServerHttpResponse;
<ide> import org.springframework.util.Assert;
<ide> import org.springframework.util.MimeType;
<ide>
<del>import static org.springframework.http.MediaType.APPLICATION_STREAM_JSON;
<ide>
<ide> /**
<ide> * Encode from an {@code Object} stream to a byte stream of JSON objects,
<ide> * @since 5.0
<ide> * @see Jackson2JsonDecoder
<ide> */
<del>public class Jackson2JsonEncoder extends Jackson2CodecSupport implements ServerHttpEncoder<Object> {
<add>public class Jackson2JsonEncoder extends Jackson2CodecSupport implements HttpEncoder<Object> {
<add>
<add> private final List<MediaType> streamingMediaTypes = new ArrayList<>(1);
<ide>
<ide> private final PrettyPrinter ssePrettyPrinter;
<ide>
<ide>
<add>
<ide> public Jackson2JsonEncoder() {
<ide> this(Jackson2ObjectMapperBuilder.json().build());
<ide> }
<ide>
<ide> public Jackson2JsonEncoder(ObjectMapper mapper) {
<ide> super(mapper);
<del> DefaultPrettyPrinter prettyPrinter = new DefaultPrettyPrinter();
<del> prettyPrinter.indentObjectsWith(new DefaultIndenter(" ", "\ndata:"));
<del> this.ssePrettyPrinter = prettyPrinter;
<add> this.streamingMediaTypes.add(MediaType.APPLICATION_STREAM_JSON);
<add> this.ssePrettyPrinter = initSsePrettyPrinter();
<ide> }
<ide>
<add> private static PrettyPrinter initSsePrettyPrinter() {
<add> DefaultPrettyPrinter printer = new DefaultPrettyPrinter();
<add> printer.indentObjectsWith(new DefaultIndenter(" ", "\ndata:"));
<add> return printer;
<add> }
<ide>
<del> @Override
<del> public boolean canEncode(ResolvableType elementType, MimeType mimeType) {
<del> return this.mapper.canSerialize(elementType.getRawClass()) &&
<del> (mimeType == null || JSON_MIME_TYPES.stream().anyMatch(m -> m.isCompatibleWith(mimeType)));
<add>
<add> /**
<add> * Configure "streaming" media types for which flushing should be performed
<add> * automatically vs at the end of the stream.
<add> * <p>By default this is set to {@link MediaType#APPLICATION_STREAM_JSON}.
<add> * @param mediaTypes one or more media types to add to the list
<add> * @see HttpEncoder#getStreamingMediaTypes()
<add> */
<add> public void setStreamingMediaTypes(List<MediaType> mediaTypes) {
<add> this.streamingMediaTypes.clear();
<add> this.streamingMediaTypes.addAll(mediaTypes);
<ide> }
<ide>
<ide> @Override
<ide> public List<MimeType> getEncodableMimeTypes() {
<ide> return JSON_MIME_TYPES;
<ide> }
<ide>
<add>
<add> @Override
<add> public boolean canEncode(ResolvableType elementType, MimeType mimeType) {
<add> return this.mapper.canSerialize(elementType.getRawClass()) &&
<add> (mimeType == null || JSON_MIME_TYPES.stream().anyMatch(m -> m.isCompatibleWith(mimeType)));
<add> }
<add>
<ide> @Override
<ide> public Flux<DataBuffer> encode(Publisher<?> inputStream, DataBufferFactory bufferFactory,
<ide> ResolvableType elementType, MimeType mimeType, Map<String, Object> hints) {
<ide> public Flux<DataBuffer> encode(Publisher<?> inputStream, DataBufferFactory buffe
<ide> return Flux.from(inputStream).map(value ->
<ide> encodeValue(value, mimeType, bufferFactory, elementType, hints));
<ide> }
<del> else if (APPLICATION_STREAM_JSON.isCompatibleWith(mimeType)) {
<add> else if (MediaType.APPLICATION_STREAM_JSON.isCompatibleWith(mimeType)) {
<ide> return Flux.from(inputStream).map(value -> {
<ide> DataBuffer buffer = encodeValue(value, mimeType, bufferFactory, elementType, hints);
<ide> buffer.write(new byte[]{'\n'});
<ide> private DataBuffer encodeValue(Object value, MimeType mimeType, DataBufferFactor
<ide> }
<ide>
<ide>
<del> // ServerHttpEncoder...
<add> // HttpEncoder...
<add>
<add> @Override
<add> public List<MediaType> getStreamingMediaTypes() {
<add> return Collections.unmodifiableList(this.streamingMediaTypes);
<add> }
<ide>
<ide> @Override
<ide> public Map<String, Object> getEncodeHints(ResolvableType actualType, ResolvableType elementType, | 8 |
Java | Java | pass mono to reactor netty when feasible | 5b711a964bfb64c80bde72ebc48e706f9fe2f000 | <ide><path>spring-test/src/main/java/org/springframework/mock/http/server/reactive/MockServerHttpResponse.java
<ide> /*
<del> * Copyright 2002-2018 the original author or authors.
<add> * Copyright 2002-2019 the original author or authors.
<ide> *
<ide> * Licensed under the Apache License, Version 2.0 (the "License");
<ide> * you may not use this file except in compliance with the License.
<ide> import org.reactivestreams.Publisher;
<ide> import reactor.core.publisher.Flux;
<ide> import reactor.core.publisher.Mono;
<add>import reactor.core.publisher.MonoProcessor;
<ide>
<ide> import org.springframework.core.io.buffer.DataBuffer;
<add>import org.springframework.core.io.buffer.DataBufferFactory;
<ide> import org.springframework.core.io.buffer.DataBufferUtils;
<ide> import org.springframework.core.io.buffer.DefaultDataBufferFactory;
<ide> import org.springframework.http.HttpHeaders;
<ide> public class MockServerHttpResponse extends AbstractServerHttpResponse {
<ide>
<ide>
<ide> public MockServerHttpResponse() {
<del> super(new DefaultDataBufferFactory());
<add> this(new DefaultDataBufferFactory());
<add> }
<add>
<add> public MockServerHttpResponse(DataBufferFactory dataBufferFactory) {
<add> super(dataBufferFactory);
<ide> this.writeHandler = body -> {
<del> this.body = body.cache();
<del> return this.body.then();
<add> // Avoid .then() which causes data buffers to be released
<add> MonoProcessor<Void> completion = MonoProcessor.create();
<add> this.body = body.doOnComplete(completion::onComplete).doOnError(completion::onError).cache();
<add> this.body.subscribe();
<add> return completion;
<ide> };
<ide> }
<ide>
<ide> public Flux<DataBuffer> getBody() {
<ide> * charset or "UTF-8" by default.
<ide> */
<ide> public Mono<String> getBodyAsString() {
<add>
<ide> Charset charset = Optional.ofNullable(getHeaders().getContentType()).map(MimeType::getCharset)
<ide> .orElse(StandardCharsets.UTF_8);
<add>
<ide> return getBody()
<ide> .reduce(bufferFactory().allocateBuffer(), (previous, current) -> {
<ide> previous.write(current);
<ide> public Mono<String> getBodyAsString() {
<ide> }
<ide>
<ide> private static String bufferToString(DataBuffer buffer, Charset charset) {
<add> Assert.notNull(charset, "'charset' must not be null");
<ide> byte[] bytes = new byte[buffer.readableByteCount()];
<ide> buffer.read(bytes);
<add> DataBufferUtils.release(buffer);
<ide> return new String(bytes, charset);
<ide> }
<ide>
<ide><path>spring-web/src/main/java/org/springframework/http/client/reactive/ReactorClientHttpRequest.java
<ide> /*
<del> * Copyright 2002-2018 the original author or authors.
<add> * Copyright 2002-2019 the original author or authors.
<ide> *
<ide> * Licensed under the Apache License, Version 2.0 (the "License");
<ide> * you may not use this file except in compliance with the License.
<ide> public URI getURI() {
<ide> @Override
<ide> public Mono<Void> writeWith(Publisher<? extends DataBuffer> body) {
<ide> return doCommit(() -> {
<del> Flux<ByteBuf> byteBufFlux = Flux.from(body).map(NettyDataBufferFactory::toByteBuf);
<del> return this.outbound.send(byteBufFlux).then();
<add> // Send as Mono if possible as an optimization hint to Reactor Netty
<add> if (body instanceof Mono) {
<add> Mono<ByteBuf> byteBufMono = Mono.from(body).map(NettyDataBufferFactory::toByteBuf);
<add> return this.outbound.send(byteBufMono).then();
<add>
<add> }
<add> else {
<add> Flux<ByteBuf> byteBufFlux = Flux.from(body).map(NettyDataBufferFactory::toByteBuf);
<add> return this.outbound.send(byteBufFlux).then();
<add> }
<ide> });
<ide> }
<ide>
<ide><path>spring-web/src/main/java/org/springframework/http/server/reactive/AbstractServerHttpResponse.java
<ide> /*
<del> * Copyright 2002-2018 the original author or authors.
<add> * Copyright 2002-2019 the original author or authors.
<ide> *
<ide> * Licensed under the Apache License, Version 2.0 (the "License");
<ide> * you may not use this file except in compliance with the License.
<ide>
<ide> import org.springframework.core.io.buffer.DataBuffer;
<ide> import org.springframework.core.io.buffer.DataBufferFactory;
<add>import org.springframework.core.io.buffer.DataBufferUtils;
<add>import org.springframework.core.io.buffer.PooledDataBuffer;
<ide> import org.springframework.http.HttpHeaders;
<ide> import org.springframework.http.HttpLogging;
<ide> import org.springframework.http.HttpStatus;
<ide> public boolean isCommitted() {
<ide> }
<ide>
<ide> @Override
<add> @SuppressWarnings("unchecked")
<ide> public final Mono<Void> writeWith(Publisher<? extends DataBuffer> body) {
<del> return new ChannelSendOperator<>(body,
<del> writePublisher -> doCommit(() -> writeWithInternal(writePublisher)))
<add> // Write as Mono if possible as an optimization hint to Reactor Netty
<add> // ChannelSendOperator not necessary for Mono
<add> if (body instanceof Mono) {
<add> return ((Mono<? extends DataBuffer>) body).flatMap(buffer ->
<add> doCommit(() -> writeWithInternal(Mono.just(buffer)))
<add> .doOnDiscard(PooledDataBuffer.class, DataBufferUtils::release));
<add> }
<add> return new ChannelSendOperator<>(body, inner -> doCommit(() -> writeWithInternal(inner)))
<ide> .doOnError(t -> removeContentLength());
<ide> }
<ide>
<ide><path>spring-web/src/test/java/org/springframework/http/codec/FormHttpMessageWriterTests.java
<ide> /*
<del> * Copyright 2002-2018 the original author or authors.
<add> * Copyright 2002-2019 the original author or authors.
<ide> *
<ide> * Licensed under the Apache License, Version 2.0 (the "License");
<ide> * you may not use this file except in compliance with the License.
<ide> public void writeForm() {
<ide>
<ide> String expected = "name+1=value+1&name+2=value+2%2B1&name+2=value+2%2B2&name+3";
<ide> StepVerifier.create(response.getBody())
<del> .consumeNextWith(stringConsumer(
<del> expected))
<add> .consumeNextWith(stringConsumer(expected))
<ide> .expectComplete()
<ide> .verify();
<ide> HttpHeaders headers = response.getHeaders();
<ide> public void writeForm() {
<ide>
<ide> private Consumer<DataBuffer> stringConsumer(String expected) {
<ide> return dataBuffer -> {
<del> String value =
<del> DataBufferTestUtils.dumpString(dataBuffer, StandardCharsets.UTF_8);
<add> String value = DataBufferTestUtils.dumpString(dataBuffer, StandardCharsets.UTF_8);
<ide> DataBufferUtils.release(dataBuffer);
<ide> assertEquals(expected, value);
<ide> };
<ide><path>spring-web/src/test/java/org/springframework/mock/http/server/reactive/test/MockServerHttpResponse.java
<ide> import org.reactivestreams.Publisher;
<ide> import reactor.core.publisher.Flux;
<ide> import reactor.core.publisher.Mono;
<add>import reactor.core.publisher.MonoProcessor;
<ide>
<ide> import org.springframework.core.io.buffer.DataBuffer;
<ide> import org.springframework.core.io.buffer.DataBufferFactory;
<ide> public MockServerHttpResponse() {
<ide> public MockServerHttpResponse(DataBufferFactory dataBufferFactory) {
<ide> super(dataBufferFactory);
<ide> this.writeHandler = body -> {
<del> this.body = body.cache();
<del> return this.body.then();
<add> // Avoid .then() which causes data buffers to be released
<add> MonoProcessor<Void> completion = MonoProcessor.create();
<add> this.body = body.doOnComplete(completion::onComplete).doOnError(completion::onError).cache();
<add> this.body.subscribe();
<add> return completion;
<ide> };
<ide> }
<ide> | 5 |
Text | Text | add link to project wiki in readme.md | 6078e0852da884fc8aec918ffe0d5c540c52a529 | <ide><path>README.md
<ide> three.js
<ide>
<ide> The aim of the project is to create an easy to use, lightweight, 3D library. The library provides <canvas>, <svg>, CSS3D and WebGL renderers.
<ide>
<del>[Examples](http://threejs.org/examples/) — [Documentation](http://threejs.org/docs/) — [Migrating](https://github.com/mrdoob/three.js/wiki/Migration) — [Help](http://stackoverflow.com/questions/tagged/three.js)
<del>
<add>[Examples](http://threejs.org/examples/) —
<add>[Documentation](http://threejs.org/docs/) —
<add>[Wiki](https://github.com/mrdoob/three.js/wiki) —
<add>[Migrating](https://github.com/mrdoob/three.js/wiki/Migration) —
<add>[Help](http://stackoverflow.com/questions/tagged/three.js)
<ide>
<ide> ### Usage ###
<ide> | 1 |
Javascript | Javascript | add tests for and | 8caf7fdb05b29325c57807074d55fa3f2713d197 | <ide><path>test/simple/test-http-client-abort2.js
<add>// Copyright Joyent, Inc. and other Node contributors.
<add>//
<add>// Permission is hereby granted, free of charge, to any person obtaining a
<add>// copy of this software and associated documentation files (the
<add>// "Software"), to deal in the Software without restriction, including
<add>// without limitation the rights to use, copy, modify, merge, publish,
<add>// distribute, sublicense, and/or sell copies of the Software, and to permit
<add>// persons to whom the Software is furnished to do so, subject to the
<add>// following conditions:
<add>//
<add>// The above copyright notice and this permission notice shall be included
<add>// in all copies or substantial portions of the Software.
<add>//
<add>// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
<add>// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
<add>// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
<add>// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
<add>// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
<add>// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
<add>// USE OR OTHER DEALINGS IN THE SOFTWARE.
<add>
<add>var common = require('../common');
<add>var assert = require('assert');
<add>var http = require('http');
<add>
<add>var server = http.createServer(function(req, res) {
<add> res.end('Hello');
<add>});
<add>
<add>server.listen(common.PORT, function() {
<add> var req = http.get({port: common.PORT}, function(res) {
<add> res.on('data', function(data) {
<add> req.abort();
<add> server.close();
<add> });
<add> });
<add>});
<add>
<ide><path>test/simple/test-tls-client-abort.js
<add>// Copyright Joyent, Inc. and other Node contributors.
<add>//
<add>// Permission is hereby granted, free of charge, to any person obtaining a
<add>// copy of this software and associated documentation files (the
<add>// "Software"), to deal in the Software without restriction, including
<add>// without limitation the rights to use, copy, modify, merge, publish,
<add>// distribute, sublicense, and/or sell copies of the Software, and to permit
<add>// persons to whom the Software is furnished to do so, subject to the
<add>// following conditions:
<add>//
<add>// The above copyright notice and this permission notice shall be included
<add>// in all copies or substantial portions of the Software.
<add>//
<add>// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
<add>// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
<add>// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
<add>// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
<add>// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
<add>// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
<add>// USE OR OTHER DEALINGS IN THE SOFTWARE.
<add>
<add>if (!process.versions.openssl) {
<add> console.error("Skipping because node compiled without OpenSSL.");
<add> process.exit(0);
<add>}
<add>
<add>var common = require('../common');
<add>var assert = require('assert');
<add>var fs = require('fs');
<add>var tls = require('tls');
<add>var path = require('path');
<add>
<add>(function() {
<add> var cert = fs.readFileSync(path.join(common.fixturesDir, 'test_cert.pem'));
<add> var key = fs.readFileSync(path.join(common.fixturesDir, 'test_key.pem'));
<add>
<add> var errorEmitted = false;
<add>
<add> process.on('exit', function() {
<add> assert.ok(!errorEmitted);
<add> });
<add>
<add> var conn = tls.connect(common.PORT, {cert:cert, key:key}, function() {
<add> assert.ok(false); // callback should never be executed
<add> });
<add> conn.destroy();
<add>
<add> conn.on('error', function() {
<add> errorEmitted = true;
<add> });
<add>})();
<add> | 2 |
Javascript | Javascript | improve util.inspect performance | 95bbb6817532a2cdf1991f452ebbc5a5b5d5a112 | <ide><path>benchmark/util/inspect-array.js
<add>'use strict';
<add>
<add>const common = require('../common');
<add>const util = require('util');
<add>
<add>const bench = common.createBenchmark(main, {
<add> n: [1e2],
<add> len: [1e5],
<add> type: [
<add> 'denseArray',
<add> 'sparseArray',
<add> 'mixedArray'
<add> ]
<add>});
<add>
<add>function main(conf) {
<add> const { n, len, type } = conf;
<add> var arr = Array(len);
<add> var i;
<add>
<add> switch (type) {
<add> case 'denseArray':
<add> arr = arr.fill(0);
<add> break;
<add> case 'sparseArray':
<add> break;
<add> case 'mixedArray':
<add> for (i = 0; i < n; i += 2)
<add> arr[i] = i;
<add> break;
<add> default:
<add> throw new Error(`Unsupported type ${type}`);
<add> }
<add> bench.start();
<add> for (i = 0; i < n; i++) {
<add> util.inspect(arr);
<add> }
<add> bench.end(n);
<add>}
<ide><path>lib/util.js
<ide> const inspectDefaultOptions = Object.seal({
<ide>
<ide> const numbersOnlyRE = /^\d+$/;
<ide>
<del>const objectHasOwnProperty = Object.prototype.hasOwnProperty;
<ide> const propertyIsEnumerable = Object.prototype.propertyIsEnumerable;
<ide> const regExpToString = RegExp.prototype.toString;
<ide> const dateToISOString = Date.prototype.toISOString;
<ide> function formatArray(ctx, value, recurseTimes, visibleKeys, keys) {
<ide> var output = [];
<ide> let visibleLength = 0;
<ide> let index = 0;
<del> while (index < value.length && visibleLength < ctx.maxArrayLength) {
<del> let emptyItems = 0;
<del> while (index < value.length && !hasOwnProperty(value, String(index))) {
<del> emptyItems++;
<del> index++;
<del> }
<del> if (emptyItems > 0) {
<add> for (const elem of keys) {
<add> if (visibleLength === ctx.maxArrayLength)
<add> break;
<add> // Symbols might have been added to the keys
<add> if (typeof elem !== 'string')
<add> continue;
<add> const i = +elem;
<add> if (index !== i) {
<add> // Skip zero and negative numbers as well as non numbers
<add> if (i > 0 === false)
<add> continue;
<add> const emptyItems = i - index;
<ide> const ending = emptyItems > 1 ? 's' : '';
<ide> const message = `<${emptyItems} empty item${ending}>`;
<ide> output.push(ctx.stylize(message, 'undefined'));
<del> } else {
<del> output.push(formatProperty(ctx, value, recurseTimes, visibleKeys,
<del> String(index), true));
<del> index++;
<add> index = i;
<add> if (++visibleLength === ctx.maxArrayLength)
<add> break;
<ide> }
<add> output.push(formatProperty(ctx, value, recurseTimes, visibleKeys,
<add> elem, true));
<ide> visibleLength++;
<add> index++;
<add> }
<add> if (index < value.length && visibleLength !== ctx.maxArrayLength) {
<add> const len = value.length - index;
<add> const ending = len > 1 ? 's' : '';
<add> const message = `<${len} empty item${ending}>`;
<add> output.push(ctx.stylize(message, 'undefined'));
<add> index = value.length;
<ide> }
<ide> var remaining = value.length - index;
<ide> if (remaining > 0) {
<ide> function formatProperty(ctx, value, recurseTimes, visibleKeys, key, array) {
<ide> str = ctx.stylize('[Setter]', 'special');
<ide> }
<ide> }
<del> if (!hasOwnProperty(visibleKeys, key)) {
<add> if (visibleKeys[key] === undefined) {
<ide> if (typeof key === 'symbol') {
<ide> name = `[${ctx.stylize(key.toString(), 'symbol')}]`;
<ide> } else {
<ide> function _extend(target, source) {
<ide> return target;
<ide> }
<ide>
<del>function hasOwnProperty(obj, prop) {
<del> return objectHasOwnProperty.call(obj, prop);
<del>}
<del>
<del>
<ide> // Deprecated old stuff.
<ide>
<ide> function print(...args) {
<ide><path>test/parallel/test-util-inspect.js
<ide> assert.strictEqual(
<ide> get: function() { this.push(true); return this.length; }
<ide> }
<ide> );
<add> Object.defineProperty(
<add> value,
<add> '-1',
<add> {
<add> enumerable: true,
<add> value: -1
<add> }
<add> );
<ide> assert.strictEqual(util.inspect(value),
<del> '[ 1, 2, 3, growingLength: [Getter] ]');
<add> '[ 1, 2, 3, growingLength: [Getter], \'-1\': -1 ]');
<add>}
<add>
<add>// Array with inherited number properties
<add>{
<add> class CustomArray extends Array {}
<add> CustomArray.prototype[5] = 'foo';
<add> const arr = new CustomArray(50);
<add> assert.strictEqual(util.inspect(arr), 'CustomArray [ <50 empty items> ]');
<ide> }
<ide>
<ide> // Function with properties | 3 |
Java | Java | revise cache api | 861e4817559dfb956512775665c8f0c9da9c99c1 | <ide><path>org.springframework.context/src/test/java/org/springframework/cache/config/AbstractAnnotationTest.java
<ide> public void testMethodName(CacheableService service, String keyName)
<ide> assertSame(r1, service.name(key));
<ide> Cache<Object, Object> cache = cm.getCache("default");
<ide> // assert the method name is used
<del> assertTrue(cache.containsKey(keyName));
<add> assertNotNull(cache.get(keyName));
<ide> }
<ide>
<ide> public void testRootVars(CacheableService service) {
<ide> public void testRootVars(CacheableService service) {
<ide> Cache<Object, Object> cache = cm.getCache("default");
<ide> // assert the method name is used
<ide> String expectedKey = "rootVarsrootVars" + AopProxyUtils.ultimateTargetClass(service) + service;
<del> assertTrue(cache.containsKey(expectedKey));
<add> assertNotNull(cache.get(expectedKey));
<ide> }
<ide>
<ide> public void testNullArg(CacheableService service) { | 1 |
Ruby | Ruby | use nex hash syntax on tests | 4c1b437ed7dea3660065c03e5e056a8aac700e21 | <ide><path>actionpack/test/controller/api/conditional_get_test.rb
<ide> require 'active_support/core_ext/numeric/time'
<ide>
<ide> class ConditionalGetApiController < ActionController::API
<del> before_action :handle_last_modified_and_etags, :only => :two
<add> before_action :handle_last_modified_and_etags, only: :two
<ide>
<ide> def one
<del> if stale?(:last_modified => Time.now.utc.beginning_of_day, :etag => [:foo, 123])
<del> render :text => "Hi!"
<add> if stale?(last_modified: Time.now.utc.beginning_of_day, etag: [:foo, 123])
<add> render text: "Hi!"
<ide> end
<ide> end
<ide>
<ide> def two
<del> render :text => "Hi!"
<add> render text: "Hi!"
<ide> end
<ide>
<ide> private
<ide>
<ide> def handle_last_modified_and_etags
<del> fresh_when(:last_modified => Time.now.utc.beginning_of_day, :etag => [ :foo, 123 ])
<add> fresh_when(last_modified: Time.now.utc.beginning_of_day, etag: [ :foo, 123 ])
<ide> end
<ide> end
<ide> | 1 |
Go | Go | remove non-service cluster info on sbleave | c4d507b566c31c9d1ddceba4f189b83566ba93e0 | <ide><path>libnetwork/endpoint.go
<ide> func (ep *endpoint) sbLeave(sb *sandbox, force bool, options ...EndpointOption)
<ide> }
<ide> }
<ide>
<del> if ep.svcID != "" {
<del> if err := ep.deleteServiceInfoFromCluster(sb, true, "sbLeave"); err != nil {
<del> logrus.Warnf("Failed to clean up service info on container %s disconnect: %v", ep.name, err)
<del> }
<add> if err := ep.deleteServiceInfoFromCluster(sb, true, "sbLeave"); err != nil {
<add> logrus.Warnf("Failed to clean up service info on container %s disconnect: %v", ep.name, err)
<ide> }
<ide>
<ide> if err := sb.clearNetworkResources(ep); err != nil { | 1 |
Python | Python | update bertencoderv2 max_sequence_length docstring | c9e4db9c21d75991587ede6ddd0280734869f81a | <ide><path>official/nlp/modeling/networks/bert_encoder.py
<ide> class BertEncoderV2(tf.keras.layers.Layer):
<ide> num_attention_heads: The number of attention heads for each transformer. The
<ide> hidden size must be divisible by the number of attention heads.
<ide> max_sequence_length: The maximum sequence length that this encoder can
<del> consume. If None, max_sequence_length uses the value from sequence length.
<del> This determines the variable shape for positional embeddings.
<add> consume. This determines the variable shape for positional embeddings.
<ide> type_vocab_size: The number of types that the 'type_ids' input can take.
<ide> inner_dim: The output dimension of the first Dense layer in a two-layer
<ide> feedforward network for each transformer. | 1 |
PHP | PHP | remove null retrun | 664a6bd465719ec72a60950691d7f134c21c5e4a | <ide><path>src/Error/Debugger.php
<ide> public static function getOutputAs()
<ide> * Set the output format for Debugger error rendering.
<ide> *
<ide> * @param string $format The format you want errors to be output as.
<del> * @return null
<add> * @return void
<ide> * @throws \InvalidArgumentException When choosing a format that doesn't exist.
<ide> */
<ide> public static function setOutputAs($format)
<ide> public static function setOutputAs($format)
<ide> throw new InvalidArgumentException('Invalid Debugger output format.');
<ide> }
<ide> $self->_outputFormat = $format;
<del>
<del> return null;
<ide> }
<ide>
<ide> /** | 1 |
Python | Python | remove side-effect of session in fab | a9dfd7d1cfa9bdef5fd294d593ba752ea1949d33 | <ide><path>airflow/cli/commands/webserver_command.py
<ide> def webserver(args):
<ide> print(
<ide> "Starting the web server on port {0} and host {1}.".format(
<ide> args.port, args.hostname))
<del> app, _ = create_app(None, testing=conf.getboolean('core', 'unit_test_mode'))
<add> app, _ = create_app(testing=conf.getboolean('core', 'unit_test_mode'))
<ide> app.run(debug=True, use_reloader=not app.config['TESTING'],
<ide> port=args.port, host=args.hostname,
<ide> ssl_context=(ssl_cert, ssl_key) if ssl_cert and ssl_key else None)
<ide><path>airflow/www/app.py
<ide> log = logging.getLogger(__name__)
<ide>
<ide>
<del>def create_app(config=None, session=None, testing=False, app_name="Airflow"):
<add>def create_app(config=None, testing=False, app_name="Airflow"):
<ide> global app, appbuilder
<ide> app = Flask(__name__)
<ide> app.secret_key = conf.get('webserver', 'SECRET_KEY')
<ide> def create_app(config=None, session=None, testing=False, app_name="Airflow"):
<ide> app.json_encoder = AirflowJsonEncoder
<ide>
<ide> csrf.init_app(app)
<del>
<del> db = SQLA(app)
<add> db = SQLA()
<add> db.session = settings.Session
<add> db.init_app(app)
<ide>
<ide> from airflow import api
<ide> api.load_auth()
<ide> def create_app(config=None, session=None, testing=False, app_name="Airflow"):
<ide> """Your CUSTOM_SECURITY_MANAGER must now extend AirflowSecurityManager,
<ide> not FAB's security manager.""")
<ide>
<del> appbuilder = AppBuilder(
<del> app,
<del> db.session if not session else session,
<add> class AirflowAppBuilder(AppBuilder):
<add>
<add> def _check_and_init(self, baseview):
<add> if hasattr(baseview, 'datamodel'):
<add> # Delete sessions if initiated previously to limit side effects. We want to use
<add> # the current session in the current application.
<add> baseview.datamodel.session = None
<add> return super()._check_and_init(baseview)
<add>
<add> appbuilder = AirflowAppBuilder(
<add> app=app,
<add> session=settings.Session,
<ide> security_manager_class=security_manager_class,
<ide> base_template='airflow/master.html',
<ide> update_perms=conf.getboolean('webserver', 'UPDATE_FAB_PERMS'))
<ide> def apply_caching(response):
<ide> response.headers["X-Frame-Options"] = "DENY"
<ide> return response
<ide>
<del> @app.teardown_appcontext
<del> def shutdown_session(exception=None): # pylint: disable=unused-variable
<del> settings.Session.remove()
<del>
<ide> @app.before_request
<ide> def make_session_permanent():
<ide> flask_session.permanent = True
<ide> def root_app(env, resp):
<ide> return [b'Apache Airflow is not at this location']
<ide>
<ide>
<del>def cached_app(config=None, session=None, testing=False):
<add>def cached_app(config=None, testing=False):
<ide> global app, appbuilder
<ide> if not app or not appbuilder:
<ide> base_url = urlparse(conf.get('webserver', 'base_url'))[2]
<ide> if not base_url or base_url == '/':
<ide> base_url = ""
<ide>
<del> app, _ = create_app(config, session, testing)
<add> app, _ = create_app(config=config, testing=testing)
<ide> app = DispatcherMiddleware(root_app, {base_url: app})
<ide> if conf.getboolean('webserver', 'ENABLE_PROXY_FIX'):
<ide> app = ProxyFix(
<ide><path>tests/cli/commands/test_role_command.py
<ide> from airflow import models
<ide> from airflow.cli import cli_parser
<ide> from airflow.cli.commands import role_command
<del>from airflow.settings import Session
<ide>
<ide> TEST_USER1_EMAIL = '[email protected]'
<ide> TEST_USER2_EMAIL = '[email protected]'
<ide> def setUpClass(cls):
<ide>
<ide> def setUp(self):
<ide> from airflow.www import app as application
<del> self.app, self.appbuilder = application.create_app(session=Session, testing=True)
<add> self.app, self.appbuilder = application.create_app(testing=True)
<ide> self.clear_roles_and_roles()
<ide>
<ide> def tearDown(self):
<ide><path>tests/cli/commands/test_sync_perm_command.py
<ide> from airflow.cli.commands import sync_perm_command
<ide> from airflow.models.dag import DAG
<ide> from airflow.models.dagbag import DagBag
<del>from airflow.settings import Session
<ide>
<ide>
<ide> class TestCliSyncPerm(unittest.TestCase):
<ide> def setUpClass(cls):
<ide>
<ide> def setUp(self):
<ide> from airflow.www import app as application
<del> self.app, self.appbuilder = application.create_app(session=Session, testing=True)
<add> self.app, self.appbuilder = application.create_app(testing=True)
<ide>
<ide> @mock.patch("airflow.cli.commands.sync_perm_command.DagBag")
<ide> def test_cli_sync_perm(self, dagbag_mock):
<ide><path>tests/cli/commands/test_user_command.py
<ide> from airflow import models
<ide> from airflow.cli import cli_parser
<ide> from airflow.cli.commands import user_command
<del>from airflow.settings import Session
<ide>
<ide> TEST_USER1_EMAIL = '[email protected]'
<ide> TEST_USER2_EMAIL = '[email protected]'
<ide> def setUpClass(cls):
<ide>
<ide> def setUp(self):
<ide> from airflow.www import app as application
<del> self.app, self.appbuilder = application.create_app(session=Session, testing=True)
<add> self.app, self.appbuilder = application.create_app(testing=True)
<ide> self.clear_roles_and_roles()
<ide>
<ide> def tearDown(self):
<ide><path>tests/www/api/experimental/test_endpoints.py
<ide>
<ide> class TestBase(unittest.TestCase):
<ide> def setUp(self):
<del> self.app, self.appbuilder = application.create_app(session=Session, testing=True)
<add> self.app, self.appbuilder = application.create_app(testing=True)
<ide> self.app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///'
<ide> self.app.config['SECRET_KEY'] = 'secret_key'
<ide> self.app.config['CSRF_ENABLED'] = False
<ide><path>tests/www/test_views.py
<ide> def local_context(self):
<ide> class TestBase(unittest.TestCase):
<ide> @classmethod
<ide> def setUpClass(cls):
<del> cls.app, cls.appbuilder = application.create_app(session=Session, testing=True)
<add> settings.configure_orm()
<add> cls.session = settings.Session
<add> cls.app, cls.appbuilder = application.create_app(testing=True)
<ide> cls.app.config['WTF_CSRF_ENABLED'] = False
<ide> cls.app.jinja_env.undefined = jinja2.StrictUndefined
<del> settings.configure_orm()
<del> cls.session = Session
<ide>
<ide> @classmethod
<ide> def tearDownClass(cls) -> None:
<ide> class TestMountPoint(unittest.TestCase):
<ide> def setUpClass(cls):
<ide> application.app = None
<ide> application.appbuilder = None
<del> app = application.cached_app(config={'WTF_CSRF_ENABLED': False}, session=Session, testing=True)
<add> app = application.cached_app(config={'WTF_CSRF_ENABLED': False}, testing=True)
<ide> cls.client = Client(app, BaseResponse)
<ide>
<ide> @classmethod
<ide> def prepare_dagruns(self):
<ide> state=State.RUNNING)
<ide>
<ide> def test_index(self):
<del> with assert_queries_count(5):
<add> with assert_queries_count(37):
<ide> resp = self.client.get('/', follow_redirects=True)
<ide> self.check_content_in_response('DAGs', resp)
<ide>
<ide> def setUp(self):
<ide> sys.path.append(self.settings_folder)
<ide>
<ide> with conf_vars({('logging', 'logging_config_class'): 'airflow_local_settings.LOGGING_CONFIG'}):
<del> self.app, self.appbuilder = application.create_app(session=Session, testing=True)
<add> self.app, self.appbuilder = application.create_app(testing=True)
<ide> self.app.config['WTF_CSRF_ENABLED'] = False
<ide> self.client = self.app.test_client()
<ide> settings.configure_orm() | 7 |
Text | Text | fix typo in text and change the verb | 6cff62641ceaa98df4234f4b2009b0221208b838 | <ide><path>guide/english/vagrant/index.md
<ide> title: Vagrant
<ide> ---
<ide> ## Vagrant
<ide>
<del><!-- The article goes here, in GitHub-flavored Markdown. Feel free to add YouTube videos, images, and CodePen/JSBin embeds -->
<del>Vagrant is an automation tool that aids in creating and managing virtual machines that is simple to use and allows you to set up an environment quickly. This environment's exact installation and configuration can then be shared by using a Vagrantfile so other team members are all using the same environment, no matter what computer they are using.
<add>Vagrant is an automation tool that aids in creating and managing virtual machines that are simple to use and allows you to set up a environment quickly. This environment's exact installation and configuration can then be shared by using a Vagrantfile so other team members are all using the same environment no matter what computer they are using.
<ide>
<ide> Vagrant can also be used with docker to start multiple containers, that are connected for one project.
<ide> | 1 |
Python | Python | apply exec fixer results | 2429298dd8ddf797c3c89e65eb8a9b9e8f72a299 | <ide><path>doc/numpybook/runcode.py
<ide> def getoutput(tstr, dic):
<ide> except SyntaxError:
<ide> try:
<ide> res = None
<del> exec code in dic
<add> exec(code, dic)
<ide> finally:
<ide> sys.stdout = sys.__stdout__
<ide> if res is None:
<ide> def runpycode(lyxstr, name='MyCode'):
<ide> del indx[0]
<ide> indx.append(len(lyxstr))
<ide> edic = {}
<del> exec 'from numpy import *' in edic
<del> exec 'set_printoptions(linewidth=65)' in edic
<add> exec('from numpy import *', edic)
<add> exec('set_printoptions(linewidth=65)', edic)
<ide> # indx now contains [st0,en0, ..., stN,enN]
<ide> # where stX is the start of code segment X
<ide> # and enX is the start of \layout MyCode for
<ide> def runpycode(lyxstr, name='MyCode'):
<ide> # if PYNEW found, then start a new namespace
<ide> if mat:
<ide> edic = {}
<del> exec 'from numpy import *' in edic
<del> exec 'set_printoptions(linewidth=65)' in edic
<add> exec('from numpy import *', edic)
<add> exec('set_printoptions(linewidth=65)', edic)
<ide> # now find the code in the code segment
<ide> # endoutput will contain the index just past any output
<ide> # already present in the lyx string.
<ide><path>doc/sphinxext/plot_directive.py
<ide> def run_code(code, code_path, ns=None):
<ide> if ns is None:
<ide> ns = {}
<ide> if not ns:
<del> exec setup.config.plot_pre_code in ns
<del> exec code in ns
<add> exec(setup.config.plot_pre_code, ns)
<add> exec(code, ns)
<ide> except (Exception, SystemExit) as err:
<ide> raise PlotError(traceback.format_exc())
<ide> finally:
<ide><path>numpy/_import_tools.py
<ide> def _init_info_modules(self, packages=None):
<ide> break
<ide> else:
<ide> try:
<del> exec 'import %s.info as info' % (package_name)
<add> exec('import %s.info as info' % (package_name))
<ide> info_modules[package_name] = info
<ide> except ImportError as msg:
<ide> self.warn('No scipy-style subpackage %r found in %s. '\
<ide><path>numpy/f2py/tests/test_array_from_pyobj.py
<ide> def test_inplace_from_casttype(self):
<ide>
<ide>
<ide> for t in Type._type_names:
<del> exec '''\
<add> exec('''\
<ide> class test_%s_gen(unittest.TestCase,
<ide> _test_shared_memory
<ide> ):
<ide> def setUp(self):
<ide> self.type = Type(%r)
<ide> array = lambda self,dims,intent,obj: Array(Type(%r),dims,intent,obj)
<del>''' % (t,t,t)
<add>''' % (t,t,t))
<ide>
<ide> if __name__ == "__main__":
<ide> setup()
<ide><path>numpy/lib/function_base.py
<ide> def add_newdoc(place, obj, doc):
<ide> """
<ide> try:
<ide> new = {}
<del> exec 'from %s import %s' % (place, obj) in new
<add> exec('from %s import %s' % (place, obj), new)
<ide> if isinstance(doc, str):
<ide> add_docstring(new[obj], doc.strip())
<ide> elif isinstance(doc, tuple):
<ide><path>numpy/numarray/session.py
<ide> def _loadmodule(module):
<ide> s = ""
<ide> for i in range(len(modules)):
<ide> s = ".".join(modules[:i+1])
<del> exec "import " + s
<add> exec("import " + s)
<ide> return sys.modules[module]
<ide>
<ide> class _ObjectProxy(object):
<ide><path>numpy/polynomial/chebyshev.py
<ide> def chebpts2(npts):
<ide> # Chebyshev series class
<ide> #
<ide>
<del>exec polytemplate.substitute(name='Chebyshev', nick='cheb', domain='[-1,1]')
<add>exec(polytemplate.substitute(name='Chebyshev', nick='cheb', domain='[-1,1]'))
<ide><path>numpy/polynomial/hermite.py
<ide> def hermweight(x):
<ide> # Hermite series class
<ide> #
<ide>
<del>exec polytemplate.substitute(name='Hermite', nick='herm', domain='[-1,1]')
<add>exec(polytemplate.substitute(name='Hermite', nick='herm', domain='[-1,1]'))
<ide><path>numpy/polynomial/hermite_e.py
<ide> def hermeweight(x):
<ide> # HermiteE series class
<ide> #
<ide>
<del>exec polytemplate.substitute(name='HermiteE', nick='herme', domain='[-1,1]')
<add>exec(polytemplate.substitute(name='HermiteE', nick='herme', domain='[-1,1]'))
<ide><path>numpy/polynomial/laguerre.py
<ide> def lagweight(x):
<ide> # Laguerre series class
<ide> #
<ide>
<del>exec polytemplate.substitute(name='Laguerre', nick='lag', domain='[-1,1]')
<add>exec(polytemplate.substitute(name='Laguerre', nick='lag', domain='[-1,1]'))
<ide><path>numpy/polynomial/legendre.py
<ide> def legweight(x):
<ide> # Legendre series class
<ide> #
<ide>
<del>exec polytemplate.substitute(name='Legendre', nick='leg', domain='[-1,1]')
<add>exec(polytemplate.substitute(name='Legendre', nick='leg', domain='[-1,1]'))
<ide><path>numpy/polynomial/polynomial.py
<ide> def polyroots(c):
<ide> # polynomial class
<ide> #
<ide>
<del>exec polytemplate.substitute(name='Polynomial', nick='poly', domain='[-1,1]')
<add>exec(polytemplate.substitute(name='Polynomial', nick='poly', domain='[-1,1]'))
<ide><path>numpy/testing/numpytest.py
<ide> def importall(package):
<ide> continue
<ide> name = package_name+'.'+subpackage_name
<ide> try:
<del> exec 'import %s as m' % (name)
<add> exec('import %s as m' % (name))
<ide> except Exception as msg:
<ide> print 'Failed importing %s: %s' %(name, msg)
<ide> continue
<ide><path>numpy/testing/utils.py
<ide> def assert_array_less(x, y, err_msg='', verbose=True):
<ide> header='Arrays are not less-ordered')
<ide>
<ide> def runstring(astr, dict):
<del> exec astr in dict
<add> exec(astr, dict)
<ide>
<ide> def assert_string_equal(actual, desired):
<ide> """
<ide> def measure(code_str,times=1,label=None):
<ide> elapsed = jiffies()
<ide> while i < times:
<ide> i += 1
<del> exec code in globs,locs
<add> exec(code, globs,locs)
<ide> elapsed = jiffies() - elapsed
<ide> return 0.01*elapsed
<ide> | 14 |
Mixed | Javascript | remove usage of *state.highwatermark | 157df5a47c3aa8951e5dba4f0b05c7a9c7d9ecb1 | <ide><path>doc/api/stream.md
<ide> process.nextTick(() => {
<ide>
<ide> See also: [`writable.cork()`][].
<ide>
<add>##### writable.writableHighWaterMark
<add><!-- YAML
<add>added: REPLACEME
<add>-->
<add>
<add>Return the value of `highWaterMark` passed when constructing this
<add>`Writable`.
<add>
<ide> ##### writable.write(chunk[, encoding][, callback])
<ide> <!-- YAML
<ide> added: v0.9.4
<ide> to prevent memory leaks.
<ide> never closed until the Node.js process exits, regardless of the specified
<ide> options.
<ide>
<add>##### readable.readableHighWaterMark
<add><!-- YAML
<add>added: REPLACEME
<add>-->
<add>
<add>Return the value of `highWaterMark` passed when constructing this
<add>`Readable`.
<add>
<ide> ##### readable.read([size])
<ide> <!-- YAML
<ide> added: v0.9.4
<ide><path>lib/_http_server.js
<ide> function connectionListener(socket) {
<ide> function updateOutgoingData(socket, state, delta) {
<ide> state.outgoingData += delta;
<ide> if (socket._paused &&
<del> state.outgoingData < socket._writableState.highWaterMark) {
<add> state.outgoingData < socket.writeHWM) {
<ide> return socketOnDrain(socket, state);
<ide> }
<ide> }
<ide>
<ide> function socketOnDrain(socket, state) {
<del> var needPause = state.outgoingData > socket._writableState.highWaterMark;
<add> var needPause = state.outgoingData > socket.writeHWM;
<ide>
<ide> // If we previously paused, then start reading again.
<ide> if (socket._paused && !needPause) {
<ide> function parserOnIncoming(server, socket, state, req, keepAlive) {
<ide> // pipelined requests that may never be resolved.
<ide> if (!socket._paused) {
<ide> var ws = socket._writableState;
<del> if (ws.needDrain || state.outgoingData >= ws.highWaterMark) {
<add> if (ws.needDrain || state.outgoingData >= socket.writableHighWaterMark) {
<ide> socket._paused = true;
<ide> // We also need to pause the parser, but don't do that until after
<ide> // the call to execute, because we may still be processing the last
<ide><path>lib/_stream_duplex.js
<ide> const Writable = require('_stream_writable');
<ide>
<ide> util.inherits(Duplex, Readable);
<ide>
<del>var keys = Object.keys(Writable.prototype);
<del>for (var v = 0; v < keys.length; v++) {
<del> var method = keys[v];
<del> if (!Duplex.prototype[method])
<del> Duplex.prototype[method] = Writable.prototype[method];
<add>{
<add> // avoid scope creep, the keys array can then be collected
<add> const keys = Object.keys(Writable.prototype);
<add> for (var v = 0; v < keys.length; v++) {
<add> const method = keys[v];
<add> if (!Duplex.prototype[method])
<add> Duplex.prototype[method] = Writable.prototype[method];
<add> }
<ide> }
<ide>
<ide> function Duplex(options) {
<ide> function Duplex(options) {
<ide> this.once('end', onend);
<ide> }
<ide>
<add>Object.defineProperty(Duplex.prototype, 'writableHighWaterMark', {
<add> // making it explicit this property is not enumerable
<add> // because otherwise some prototype manipulation in
<add> // userland will fail
<add> enumerable: false,
<add> get: function() {
<add> return this._writableState.highWaterMark;
<add> }
<add>});
<add>
<ide> // the no-half-open enforcer
<ide> function onend() {
<ide> // if we allow half-open state, or if the writable side ended,
<ide><path>lib/_stream_readable.js
<ide> Readable.prototype.wrap = function(stream) {
<ide> return self;
<ide> };
<ide>
<add>Object.defineProperty(Readable.prototype, 'readableHighWaterMark', {
<add> // making it explicit this property is not enumerable
<add> // because otherwise some prototype manipulation in
<add> // userland will fail
<add> enumerable: false,
<add> get: function() {
<add> return this._readableState.highWaterMark;
<add> }
<add>});
<ide>
<ide> // exposed for testing purposes only.
<ide> Readable._fromList = fromList;
<ide><path>lib/_stream_writable.js
<ide> function decodeChunk(state, chunk, encoding) {
<ide> return chunk;
<ide> }
<ide>
<add>Object.defineProperty(Writable.prototype, 'writableHighWaterMark', {
<add> // making it explicit this property is not enumerable
<add> // because otherwise some prototype manipulation in
<add> // userland will fail
<add> enumerable: false,
<add> get: function() {
<add> return this._writableState.highWaterMark;
<add> }
<add>});
<add>
<ide> // if we're already writing something, then just put this
<ide> // in the queue, and wait our turn. Otherwise, call _write
<ide> // If we return false, then we need a drain event, so set that flag.
<ide><path>lib/fs.js
<ide> ReadStream.prototype._read = function(n) {
<ide>
<ide> if (!pool || pool.length - pool.used < kMinPoolSpace) {
<ide> // discard the old pool.
<del> allocNewPool(this._readableState.highWaterMark);
<add> allocNewPool(this.readableHighWaterMark);
<ide> }
<ide>
<ide> // Grab another reference to the pool in the case that while we're
<ide><path>test/parallel/test-http-pipeline-regr-3508.js
<ide> const server = http.createServer(function(req, res) {
<ide> res.end(chunk);
<ide> }
<ide> size += res.outputSize;
<del> if (size <= req.socket._writableState.highWaterMark) {
<add> if (size <= req.socket.writableHighWaterMark) {
<ide> more();
<ide> return;
<ide> }
<ide><path>test/parallel/test-stream-big-packet.js
<ide> s1.pipe(s3);
<ide> s2.pipe(s3, { end: false });
<ide>
<ide> // We must write a buffer larger than highWaterMark
<del>const big = Buffer.alloc(s1._writableState.highWaterMark + 1, 'x');
<add>const big = Buffer.alloc(s1.writableHighWaterMark + 1, 'x');
<ide>
<ide> // Since big is larger than highWaterMark, it will be buffered internally.
<ide> assert(!s1.write(big));
<ide><path>test/parallel/test-stream-readable-flow-recursion.js
<ide> flow(stream, 5000, function() {
<ide> process.on('exit', function(code) {
<ide> assert.strictEqual(reads, 2);
<ide> // we pushed up the high water mark
<del> assert.strictEqual(stream._readableState.highWaterMark, 8192);
<add> assert.strictEqual(stream.readableHighWaterMark, 8192);
<ide> // length is 0 right now, because we pulled it all out.
<ide> assert.strictEqual(stream._readableState.length, 0);
<ide> assert(!code);
<ide><path>test/parallel/test-stream-transform-split-objectmode.js
<ide> const parser = new Transform({ readableObjectMode: true });
<ide>
<ide> assert(parser._readableState.objectMode);
<ide> assert(!parser._writableState.objectMode);
<del>assert.strictEqual(parser._readableState.highWaterMark, 16);
<del>assert.strictEqual(parser._writableState.highWaterMark, 16 * 1024);
<add>assert.strictEqual(parser.readableHighWaterMark, 16);
<add>assert.strictEqual(parser.writableHighWaterMark, 16 * 1024);
<add>assert.strictEqual(parser.readableHighWaterMark,
<add> parser._readableState.highWaterMark);
<add>assert.strictEqual(parser.writableHighWaterMark,
<add> parser._writableState.highWaterMark);
<ide>
<ide> parser._transform = function(chunk, enc, callback) {
<ide> callback(null, { val: chunk[0] });
<ide> const serializer = new Transform({ writableObjectMode: true });
<ide>
<ide> assert(!serializer._readableState.objectMode);
<ide> assert(serializer._writableState.objectMode);
<del>assert.strictEqual(serializer._readableState.highWaterMark, 16 * 1024);
<del>assert.strictEqual(serializer._writableState.highWaterMark, 16);
<add>assert.strictEqual(serializer.readableHighWaterMark, 16 * 1024);
<add>assert.strictEqual(serializer.writableHighWaterMark, 16);
<add>assert.strictEqual(parser.readableHighWaterMark,
<add> parser._readableState.highWaterMark);
<add>assert.strictEqual(parser.writableHighWaterMark,
<add> parser._writableState.highWaterMark);
<ide>
<ide> serializer._transform = function(obj, _, callback) {
<ide> callback(null, Buffer.from([obj.val]));
<ide><path>test/parallel/test-stream2-unpipe-leak.js
<ide> console.error(src._readableState);
<ide> process.on('exit', function() {
<ide> src._readableState.buffer.length = 0;
<ide> console.error(src._readableState);
<del> assert(src._readableState.length >= src._readableState.highWaterMark);
<add> assert(src._readableState.length >= src.readableHighWaterMark);
<ide> console.log('ok');
<ide> }); | 11 |
Javascript | Javascript | add bonfire to challenge types | c0f4fecb6fc9137261c3388328b574864eb858b9 | <ide><path>common/app/routes/challenges/redux/reducer.js
<ide> import { handleActions } from 'redux-actions';
<ide> import { createPoly } from '../../../../utils/polyvinyl';
<ide>
<ide> import types from './types';
<del>import { HTML, JS } from '../../../utils/challengeTypes';
<add>import { BONFIRE, HTML, JS } from '../../../utils/challengeTypes';
<ide> import { buildSeed, getPath } from '../utils';
<ide>
<ide> const initialState = {
<ide> const filesReducer = handleActions(
<ide> }
<ide> if (
<ide> challenge.challengeType !== HTML &&
<del> challenge.challengeType !== JS
<add> challenge.challengeType !== JS &&
<add> challenge.challengeType !== BONFIRE
<ide> ) {
<ide> return {};
<ide> } | 1 |
Python | Python | ignore unknown events in consumer | 52b50e8cf453ba64838fc1398b23ffb0ef674cbe | <ide><path>celery/worker/consumer.py
<ide> def on_message(self, prepare, message):
<ide> message.payload['hostname'])
<ide> if hostname != self.hostname:
<ide> type, event = prepare(message.payload)
<del> obj, subject = self.update_state(event)
<add> self.update_state(event)
<ide> else:
<ide> self.clock.forward()
<ide> | 1 |
Python | Python | fix doc typo | 4ea064b1d028d8ecd1b4353f22409e1714ec75dc | <ide><path>numpy/lib/format.py
<ide>
<ide> - Is straightforward to reverse engineer. Datasets often live longer than
<ide> the programs that created them. A competent developer should be
<del> able create a solution in his preferred programming language to
<add> able to create a solution in his preferred programming language to
<ide> read most ``.npy`` files that he has been given without much
<ide> documentation.
<ide> | 1 |
Javascript | Javascript | drop confusing comment | d408de0438bc186cf460f01c075a055cbb96dcda | <ide><path>babel-preset/configs/main.js
<ide> const defaultPlugins = [
<ide> [
<ide> require('@babel/plugin-proposal-class-properties'),
<ide> // use `this.foo = bar` instead of `this.defineProperty('foo', ...)`
<del> // (Makes the properties enumerable)
<ide> {loose: true},
<ide> ],
<ide> [require('@babel/plugin-transform-computed-properties')],
<ide><path>jest/preprocessor.js
<ide> module.exports = {
<ide> [
<ide> require('@babel/plugin-proposal-class-properties'),
<ide> // use `this.foo = bar` instead of `this.defineProperty('foo', ...)`
<del> // (Makes the properties enumerable)
<ide> {loose: true},
<ide> ],
<ide> [require('@babel/plugin-transform-computed-properties')], | 2 |
Text | Text | use present tense in error messages | 9d12c14b19bc30baa4cf556a0b8281e76637f7db | <ide><path>doc/api/errors.md
<ide> specifier.
<ide> <a id="ERR_INVALID_PACKAGE_CONFIG"></a>
<ide> ### `ERR_INVALID_PACKAGE_CONFIG`
<ide>
<del>An invalid [`package.json`][] file was found which failed parsing.
<add>An invalid [`package.json`][] file failed parsing.
<ide>
<ide> <a id="ERR_INVALID_PACKAGE_TARGET"></a>
<ide> ### `ERR_INVALID_PACKAGE_TARGET`
<ide> added: REPLACEME
<ide> -->
<ide>
<ide> An object that needs to be explicitly listed in the `transferList` argument
<del>was found in the object passed to a [`postMessage()`][] call, but not provided
<add>is in the object passed to a [`postMessage()`][] call, but is not provided
<ide> in the `transferList` for that call. Usually, this is a `MessagePort`.
<ide>
<ide> In Node.js versions prior to REPLACEME, the error code being used here was
<ide> import 'package-name'; // supported
<ide> ### `ERR_VALID_PERFORMANCE_ENTRY_TYPE`
<ide>
<ide> While using the Performance Timing API (`perf_hooks`), no valid performance
<del>entry types were found.
<add>entry types are found.
<ide>
<ide> <a id="ERR_VM_DYNAMIC_IMPORT_CALLBACK_MISSING"></a>
<ide> ### `ERR_VM_DYNAMIC_IMPORT_CALLBACK_MISSING` | 1 |
Ruby | Ruby | anticipate python 3.5 in .pth audit | 86612c253db302a4e5e2c4790f1cadc1d31812c6 | <ide><path>Library/Homebrew/formula_cellar_checks.rb
<ide> def check_shadowed_headers
<ide> end
<ide>
<ide> def check_easy_install_pth lib
<del> pth_found = Dir["#{lib}/python{2.7,3.4}/site-packages/easy-install.pth"].map { |f| File.dirname(f) }
<add> pth_found = Dir["#{lib}/python{2.7,3}*/site-packages/easy-install.pth"].map { |f| File.dirname(f) }
<ide> return if pth_found.empty?
<ide>
<ide> <<-EOS.undent | 1 |
Java | Java | add separate jsbunldeloader for assets | 0c2fdf4b6af3c4193d351ed615b9fc12c941173a | <ide><path>ReactAndroid/src/androidTest/java/com/facebook/react/testing/ReactTestHelper.java
<ide> public CatalystInstance build() {
<ide> .setJSExecutor(executor)
<ide> .setRegistry(mNativeModuleRegistryBuilder.build())
<ide> .setJSModuleRegistry(mJSModuleRegistryBuilder.build())
<del> .setJSBundleLoader(JSBundleLoader.createFileLoader(
<add> .setJSBundleLoader(JSBundleLoader.createAssetLoader(
<ide> mContext,
<ide> "assets://AndroidTestBundle.js"))
<ide> .setNativeModuleCallExceptionHandler(
<ide><path>ReactAndroid/src/main/java/com/facebook/react/ReactInstanceManager.java
<ide> public static class Builder {
<ide>
<ide> protected final List<ReactPackage> mPackages = new ArrayList<>();
<ide>
<del> protected @Nullable String mJSBundleFile;
<add> protected @Nullable String mJSBundleAssetUrl;
<ide> protected @Nullable JSBundleLoader mJSBundleLoader;
<ide> protected @Nullable String mJSMainModuleName;
<ide> protected @Nullable NotThreadSafeBridgeIdleDebugListener mBridgeIdleDebugListener;
<ide> public Builder setUIImplementationProvider(
<ide> * Example: {@code "index.android.js"}
<ide> */
<ide> public Builder setBundleAssetName(String bundleAssetName) {
<del> return this.setJSBundleFile(bundleAssetName == null ? null : "assets://" + bundleAssetName);
<add> mJSBundleAssetUrl = (bundleAssetName == null ? null : "assets://" + bundleAssetName);
<add> mJSBundleLoader = null;
<add> return this;
<ide> }
<ide>
<ide> /**
<ide> public Builder setBundleAssetName(String bundleAssetName) {
<ide> * Example: {@code "assets://index.android.js" or "/sdcard/main.jsbundle"}
<ide> */
<ide> public Builder setJSBundleFile(String jsBundleFile) {
<del> mJSBundleFile = jsBundleFile;
<del> mJSBundleLoader = null;
<del> return this;
<add> if (jsBundleFile.startsWith("assets://")) {
<add> mJSBundleAssetUrl = jsBundleFile;
<add> mJSBundleLoader = null;
<add> return this;
<add> }
<add> return setJSBundleLoader(JSBundleLoader.createFileLoader(jsBundleFile));
<ide> }
<ide>
<ide> /**
<ide> public Builder setJSBundleFile(String jsBundleFile) {
<ide> */
<ide> public Builder setJSBundleLoader(JSBundleLoader jsBundleLoader) {
<ide> mJSBundleLoader = jsBundleLoader;
<del> mJSBundleFile = null;
<add> mJSBundleAssetUrl = null;
<ide> return this;
<ide> }
<ide>
<ide> public ReactInstanceManager build() {
<ide> "Application property has not been set with this builder");
<ide>
<ide> Assertions.assertCondition(
<del> mUseDeveloperSupport || mJSBundleFile != null || mJSBundleLoader != null,
<del> "JS Bundle File has to be provided when dev support is disabled");
<add> mUseDeveloperSupport || mJSBundleAssetUrl != null || mJSBundleLoader != null,
<add> "JS Bundle File or Asset URL has to be provided when dev support is disabled");
<ide>
<ide> Assertions.assertCondition(
<del> mJSMainModuleName != null || mJSBundleFile != null || mJSBundleLoader != null,
<add> mJSMainModuleName != null || mJSBundleAssetUrl != null || mJSBundleLoader != null,
<ide> "Either MainModuleName or JS Bundle File needs to be provided");
<ide>
<ide> if (mUIImplementationProvider == null) {
<ide> public ReactInstanceManager build() {
<ide> mApplication,
<ide> mCurrentActivity,
<ide> mDefaultHardwareBackBtnHandler,
<del> (mJSBundleLoader == null && mJSBundleFile != null) ?
<del> JSBundleLoader.createFileLoader(mApplication, mJSBundleFile) : mJSBundleLoader,
<add> (mJSBundleLoader == null && mJSBundleAssetUrl != null) ?
<add> JSBundleLoader.createAssetLoader(mApplication, mJSBundleAssetUrl) : mJSBundleLoader,
<ide> mJSMainModuleName,
<ide> mPackages,
<ide> mUseDeveloperSupport,
<ide><path>ReactAndroid/src/main/java/com/facebook/react/cxxbridge/JSBundleLoader.java
<ide> public abstract class JSBundleLoader {
<ide>
<ide> /**
<ide> * This loader is recommended one for release version of your app. In that case local JS executor
<del> * should be used. JS bundle will be read from assets directory in native code to save on passing
<del> * large strings from java to native memory.
<add> * should be used. JS bundle will be read from assets in native code to save on passing large
<add> * strings from java to native memory.
<ide> */
<del> public static JSBundleLoader createFileLoader(
<add> public static JSBundleLoader createAssetLoader(
<ide> final Context context,
<del> final String fileName) {
<add> final String assetUrl) {
<ide> return new JSBundleLoader() {
<ide> @Override
<ide> public void loadScript(CatalystInstanceImpl instance) {
<del> if (fileName.startsWith("assets://")) {
<del> instance.loadScriptFromAssets(context.getAssets(), fileName);
<del> } else {
<del> instance.loadScriptFromFile(fileName, fileName);
<del> }
<add> instance.loadScriptFromAssets(context.getAssets(), assetUrl);
<add> }
<add>
<add> @Override
<add> public String getSourceUrl() {
<add> return assetUrl;
<add> }
<add> };
<add> }
<add>
<add> /**
<add> * This loader loads bundle from file system. The bundle will be read in native code to save on
<add> * passing large strings from java to native memorory.
<add> */
<add> public static JSBundleLoader createFileLoader(final String fileName) {
<add> return new JSBundleLoader() {
<add> @Override
<add> public void loadScript(CatalystInstanceImpl instance) {
<add> instance.loadScriptFromFile(fileName, fileName);
<ide> }
<ide>
<ide> @Override | 3 |
Text | Text | update chinese translation of basic css | 8c1834badb356f9173c4aaddc52a4279b43015c8 | <ide><path>curriculum/challenges/chinese/01-responsive-web-design/basic-css/add-a-negative-margin-to-an-element.chinese.md
<ide> id: bad87fee1348bd9aedf08823
<ide> title: Add a Negative Margin to an Element
<ide> challengeType: 0
<del>videoUrl: ''
<del>localeTitle: 向元素添加负边距
<add>videoUrl: 'https://scrimba.com/c/cnpyGs3'
<add>forumTopicId: 16166
<add>localTitle: 给元素添加负外边距
<ide> ---
<ide>
<ide> ## Description
<del><section id="description">元素的<code>margin</code>控制元素<code>border</code>与周围元素之间的空间量。如果将元素的<code>margin</code>设置为负值,则元素将变大。 </section>
<add><section id='description'>
<add>元素的<code>margin(外边距)</code>控制元素边框与其他周围元素之间的距离大小。
<add>如果你设置元素<code>margin</code>为负值,元素会变得更大。
<add></section>
<ide>
<ide> ## Instructions
<del><section id="instructions">尝试将<code>margin</code>设置为负值,如红色框的值。将蓝色框的<code>margin</code>更改为<code>-15px</code> ,因此它会填充其周围黄色框的整个水平宽度。 </section>
<add><section id='instructions'>
<add>尝试设置蓝色盒子的<code>margin</code>为负值,跟红色盒子一样大小。
<add>蓝色盒子的<code>margin</code>设置为<code>-15px</code>,它会填满与黄色盒子之间的距离。
<add></section>
<ide>
<ide> ## Tests
<ide> <section id='tests'>
<ide>
<ide> ```yml
<ide> tests:
<del> - text: 你的<code>blue-box</code>类应该给出<code>-15px</code>的<code>margin</code>元素。
<del> testString: 'assert($(".blue-box").css("margin-top") === "-15px", "Your <code>blue-box</code> class should give elements <code>-15px</code> of <code>margin</code>.");'
<add> - text: '你的<code>blue-box</code> class的<code>margin</code>应该设置为<code>-15px</code>。'
<add> testString: assert($(".blue-box").css("margin-top") === "-15px", '你的<code>blue-box</code> class的<code>margin</code>应该设置为<code>-15px</code>。');
<ide>
<ide> ```
<ide>
<ide> tests:
<ide> background-color: yellow;
<ide> padding: 10px;
<ide> }
<del>
<add>
<ide> .red-box {
<ide> background-color: crimson;
<ide> color: #fff;
<ide> tests:
<ide> <h5 class="box red-box">padding</h5>
<ide> <h5 class="box blue-box">padding</h5>
<ide> </div>
<del>
<ide> ```
<ide>
<ide> </div>
<ide> tests:
<ide> ## Solution
<ide> <section id='solution'>
<ide>
<del>```js
<add>```html
<ide> // solution required
<ide> ```
<add>
<ide> </section>
<add>
<ide>\ No newline at end of file
<ide><path>curriculum/challenges/chinese/01-responsive-web-design/basic-css/add-borders-around-your-elements.chinese.md
<ide> id: bad87fee1348bd9bedf08813
<ide> title: Add Borders Around Your Elements
<ide> challengeType: 0
<del>videoUrl: ''
<del>localeTitle: 添加元素周围的边框
<add>videoUrl: 'https://scrimba.com/c/c2MvnHZ'
<add>forumTopicId: 16630
<add>localTitle: 在元素周围添加边框
<ide> ---
<ide>
<ide> ## Description
<del><section id="description"> CSS边框具有<code>style</code> , <code>color</code>和<code>width</code>等属性。例如,如果我们想要在HTML元素周围创建一个红色的5像素边框,我们可以使用此类: <blockquote> <风格> <br> .thin-red-border { <br>边框颜色:红色; <br> border-width:5px; <br>边框式:坚固; <br> } <br> </样式> </blockquote></section>
<add><section id='description'>
<add>CSS 边框具有<code>style</code>,<code>color</code>和<code>width</code>属性。
<add>假如,我们想要创建一个 5px 的红色实线边框包围一个 HTML 元素,我们可以这样做:
<add>
<add>```html
<add><style>
<add> .thin-red-border {
<add> border-color: red;
<add> border-width: 5px;
<add> border-style: solid;
<add> }
<add></style>
<add>```
<add>
<add></section>
<ide>
<ide> ## Instructions
<del><section id="instructions">创建一个名为<code>thick-green-border</code> 。这个类应该在HTML元素周围添加一个10px的实心绿色边框。将课程应用于您的猫照片。请记住,您可以使用其<code>class</code>属性将多个类应用于元素,方法是使用空格分隔每个类名。例如: <code><img class="class1 class2"></code> </section>
<add><section id='instructions'>
<add>创建一个<code>thick-green-border</code> CSS class,该 class 应在 HTML 元素周围添加一个 10px 的绿色实线边框,将它应用在你的猫咪照片上。
<add>记得,在一个元素上可以同时应用多个<code>class</code>,通过使用空格来分隔。例子如下:
<add><code><img class="class1 class2"></code>
<add></section>
<ide>
<ide> ## Tests
<ide> <section id='tests'>
<ide>
<ide> ```yml
<ide> tests:
<del> - text: 您的<code>img</code>元素应该具有<code>smaller-image</code>类。
<del> testString: 'assert($("img").hasClass("smaller-image"), "Your <code>img</code> element should have the class <code>smaller-image</code>.");'
<del> - text: 你的<code>img</code>元素应该有类<code>thick-green-border</code> 。
<del> testString: 'assert($("img").hasClass("thick-green-border"), "Your <code>img</code> element should have the class <code>thick-green-border</code>.");'
<del> - text: 为图像提供<code>10px</code>的边框宽度。
<del> testString: 'assert($("img").hasClass("thick-green-border") && parseInt($("img").css("border-top-width"), 10) >= 8 && parseInt($("img").css("border-top-width"), 10) <= 12, "Give your image a border width of <code>10px</code>.");'
<del> - text: 为您的图像提供<code>solid</code>的边框样式。
<del> testString: 'assert($("img").css("border-right-style") === "solid", "Give your image a border style of <code>solid</code>.");'
<del> - text: <code>img</code>元素周围的边框应为绿色。
<del> testString: 'assert($("img").css("border-left-color") === "rgb(0, 128, 0)", "The border around your <code>img</code> element should be green.");'
<add> - text: '你的<code>img</code>元素应该含有<code>smaller-image</code> class。'
<add> testString: assert($("img").hasClass("smaller-image"), '你的<code>img</code>元素应该含有<code>smaller-image</code> class。');
<add> - text: '同时,你的<code>img</code>元素应该含有<code>thick-green-border</code> class。'
<add> testString: assert($("img").hasClass("thick-green-border"), '同时,你的<code>img</code>元素应该含有<code>thick-green-border</code> class。');
<add> - text: '设置你的图片边框为<code>10px</code>。'
<add> testString: assert($("img").hasClass("thick-green-border") && parseInt($("img").css("border-top-width"), 10) >= 8 && parseInt($("img").css("border-top-width"), 10) <= 12, '设置你的图片边框为<code>10px</code>。');
<add> - text: '设置你的图片边框为<code>solid</code>实线。'
<add> testString: assert($("img").css("border-right-style") === "solid", '设置你的图片边框为<code>solid</code>实线。');
<add> - text: '<code>img</code>元素的边框颜色应该为绿色。'
<add> testString: assert($("img").css("border-left-color") === "rgb(0, 128, 0)", '<code>img</code>元素的边框颜色应该为绿色。');
<ide>
<ide> ```
<ide>
<ide> tests:
<ide>
<ide> <h2 class="red-text">CatPhotoApp</h2>
<ide> <main>
<del> <p class="red-text">Click here to view more <a href="#">cat photos</a>.</p>
<del>
<del> <a href="#"><img class="smaller-image" src="https://bit.ly/fcc-relaxing-cat" alt="A cute orange cat lying on its back."></a>
<del>
<add> <p class="red-text">点击查看更多<a href="#">猫图</a>.</p>
<add>
<add> <a href="#"><img src="https://bit.ly/fcc-relaxing-cat" alt="一只仰卧着的萌猫" class="smaller-image"></a>
<add>
<ide> <div>
<del> <p>Things cats love:</p>
<add> <p>猫咪最喜欢的三件东西:</p>
<ide> <ul>
<del> <li>cat nip</li>
<del> <li>laser pointers</li>
<del> <li>lasagna</li>
<add> <li>猫薄荷</li>
<add> <li>激光笔</li>
<add> <li>千层饼</li>
<ide> </ul>
<del> <p>Top 3 things cats hate:</p>
<add> <p>猫咪最讨厌的三件东西:</p>
<ide> <ol>
<del> <li>flea treatment</li>
<del> <li>thunder</li>
<del> <li>other cats</li>
<add> <li>跳蚤</li>
<add> <li>打雷</li>
<add> <li>同类</li>
<ide> </ol>
<ide> </div>
<del>
<add>
<ide> <form action="/submit-cat-photo">
<del> <label><input type="radio" name="indoor-outdoor" checked> Indoor</label>
<del> <label><input type="radio" name="indoor-outdoor"> Outdoor</label><br>
<del> <label><input type="checkbox" name="personality" checked> Loving</label>
<del> <label><input type="checkbox" name="personality"> Lazy</label>
<del> <label><input type="checkbox" name="personality"> Energetic</label><br>
<del> <input type="text" placeholder="cat photo URL" required>
<del> <button type="submit">Submit</button>
<add> <label><input type="radio" name="indoor-outdoor">室内</label>
<add> <label><input type="radio" name="indoor-outdoor">室外</label><br>
<add> <label><input type="checkbox" name="personality">忠诚</label>
<add> <label><input type="checkbox" name="personality">懒惰</label>
<add> <label><input type="checkbox" name="personality">积极</label><br>
<add> <input type="text" placeholder="猫咪图片地址" required>
<add> <button type="submit">提交</button>
<ide> </form>
<ide> </main>
<del>
<ide> ```
<ide>
<ide> </div>
<ide>
<del>
<del>
<ide> </section>
<ide>
<ide> ## Solution
<ide> <section id='solution'>
<ide>
<del>```js
<add>```html
<ide> // solution required
<ide> ```
<ide> </section>
<add>
<ide>\ No newline at end of file
<ide><path>curriculum/challenges/chinese/01-responsive-web-design/basic-css/add-different-margins-to-each-side-of-an-element.chinese.md
<ide> id: bad87fee1248bd9aedf08824
<ide> title: Add Different Margins to Each Side of an Element
<ide> challengeType: 0
<del>videoUrl: ''
<del>localeTitle: 在元素的每一侧添加不同的边距
<add>videoUrl: 'https://scrimba.com/c/cg4RWh4'
<add>forumTopicId: 16633
<add>localTitle: 给元素的每一侧添加不同的外边距
<ide> ---
<ide>
<ide> ## Description
<del><section id="description">有时您会想要自定义元素,使其每边都有不同的<code>margin</code> 。 CSS允许您控制的<code>margin</code>与元素的所有四个单项两侧<code>margin-top</code> , <code>margin-right</code> , <code>margin-bottom</code> ,和<code>margin-left</code>属性。 </section>
<add><section id='description'>
<add>有时候,你会想给一个元素每个方向的<code>margin</code>都设置成一个特定的值。
<add>CSS 允许你使用<code>margin-top</code>,<code>margin-right</code>,<code>margin-bottom</code>和<code>margin-left</code>属性来设置四个不同方向的<code>margin</code>值。
<add></section>
<ide>
<ide> ## Instructions
<del><section id="instructions">蓝色框的顶部和左侧<code>margin</code>为<code>40px</code> ,底部和右侧仅为<code>20px</code> 。 </section>
<add><section id='instructions'>
<add>蓝色盒子的顶部和左侧的<code>margin</code>值设置为<code>40px</code>,底部和右侧设置为<code>20px</code>。
<add></section>
<ide>
<ide> ## Tests
<ide> <section id='tests'>
<ide>
<ide> ```yml
<ide> tests:
<del> - text: 你的<code>blue-box</code>类应该给元素顶部<code>40px</code>的<code>margin</code> 。
<del> testString: 'assert($(".blue-box").css("margin-top") === "40px", "Your <code>blue-box</code> class should give the top of elements <code>40px</code> of <code>margin</code>.");'
<del> - text: 您的<code>blue-box</code>类应该赋予元素<code>20px</code> <code>margin</code>的权利。
<del> testString: 'assert($(".blue-box").css("margin-right") === "20px", "Your <code>blue-box</code> class should give the right of elements <code>20px</code> of <code>margin</code>.");'
<del> - text: 你的<code>blue-box</code>类应该给元素的底部提供<code>20px</code>的<code>margin</code> 。
<del> testString: 'assert($(".blue-box").css("margin-bottom") === "20px", "Your <code>blue-box</code> class should give the bottom of elements <code>20px</code> of <code>margin</code>.");'
<del> - text: 你的<code>blue-box</code>类应该给元素左边<code>40px</code>的<code>margin</code> 。
<del> testString: 'assert($(".blue-box").css("margin-left") === "40px", "Your <code>blue-box</code> class should give the left of elements <code>40px</code> of <code>margin</code>.");'
<add> - text: '你的<code>blue-box</code> class 的右侧<code>margin</code>(上外边距)值应为<code>40px</code>。'
<add> testString: assert($(".blue-box").css("margin-top") === "40px", '你的<code>blue-box</code> class 的顶部<code>margin</code>(上外边距)值应为<code>40px</code>。');
<add> - text: '你的<code>blue-box</code> class 的右侧<code>margin</code>(右外边距)值应为<code>20px</code>。'
<add> testString: assert($(".blue-box").css("margin-right") === "20px", '你的<code>blue-box</code> class 的右侧<code>margin</code>(右外边距)值应为<code>20px</code>。');
<add> - text: '你的<code>blue-box</code> class 的底部<code>margin</code>(下外边距)值应为<code>20px</code>。'
<add> testString: assert($(".blue-box").css("margin-bottom") === "20px", '你的<code>blue-box</code> class 的底部<code>margin</code>(下外边距)值应为<code>20px</code>。');
<add> - text: '你的<code>blue-box</code> class 的左侧<code>margin</code>(左外边距)值应为<code>40px</code>。'
<add> testString: assert($(".blue-box").css("margin-left") === "40px", '你的<code>blue-box</code> class 的左侧<code>margin</code>(左外边距)值应为<code>40px</code>。');
<ide>
<ide> ```
<ide>
<ide> tests:
<ide> background-color: yellow;
<ide> padding: 10px;
<ide> }
<del>
<add>
<ide> .red-box {
<ide> background-color: crimson;
<ide> color: #fff;
<ide> tests:
<ide> <h5 class="box red-box">padding</h5>
<ide> <h5 class="box blue-box">padding</h5>
<ide> </div>
<del>
<ide> ```
<ide>
<ide> </div>
<ide> tests:
<ide> ```js
<ide> // solution required
<ide> ```
<add>
<ide> </section>
<add>
<ide>\ No newline at end of file
<ide><path>curriculum/challenges/chinese/01-responsive-web-design/basic-css/add-different-padding-to-each-side-of-an-element.chinese.md
<ide> id: bad87fee1348bd9aedf08824
<ide> title: Add Different Padding to Each Side of an Element
<ide> challengeType: 0
<del>videoUrl: ''
<del>localeTitle: 在元素的每一侧添加不同的填充
<add>videoUrl: 'https://scrimba.com/c/cB7mwUw'
<add>forumTopicId: 16634
<add>localTitle: 给元素的每一侧添加不同的内边距
<ide> ---
<ide>
<ide> ## Description
<del><section id="description">有时您会想要自定义一个元素,使其每边都有不同数量的<code>padding</code> 。 CSS允许您控制的<code>padding</code>与元素的所有四个单项两侧<code>padding-top</code> , <code>padding-right</code> , <code>padding-bottom</code> ,并<code>padding-left</code>属性。 </section>
<add><section id='description'>
<add>有时候,你会想给一个元素每个方向的<code>padding</code>都设置成一个特定的值
<add>CSS 允许你使用<code>padding-top</code>,<code>padding-right</code>, <code>padding-bottom</code>和<code>padding-left</code>属性来设置四个不同方向的<code>padding</code>值。
<add></section>
<ide>
<ide> ## Instructions
<del><section id="instructions">在蓝色框的顶部和左侧给出<code>40px</code>的<code>padding</code> ,但在其底部和右侧只有<code>20px</code> 。 </section>
<add><section id='instructions'>
<add>蓝色盒子的顶部和左侧的<code>padding</code>值设置为<code>40px</code>,底部和右侧设置为<code>20px</code>。
<add></section>
<ide>
<ide> ## Tests
<ide> <section id='tests'>
<ide>
<ide> ```yml
<ide> tests:
<del> - text: 你的<code>blue-box</code>类应该给出<code>40px</code> <code>padding</code>元素的顶部。
<del> testString: 'assert($(".blue-box").css("padding-top") === "40px", "Your <code>blue-box</code> class should give the top of the elements <code>40px</code> of <code>padding</code>.");'
<del> - text: 你的<code>blue-box</code>类应该给出<code>20px</code> <code>padding</code>元素的权利。
<del> testString: 'assert($(".blue-box").css("padding-right") === "20px", "Your <code>blue-box</code> class should give the right of the elements <code>20px</code> of <code>padding</code>.");'
<del> - text: 你的<code>blue-box</code>类应该给出<code>20px</code> <code>padding</code>元素的底部。
<del> testString: 'assert($(".blue-box").css("padding-bottom") === "20px", "Your <code>blue-box</code> class should give the bottom of the elements <code>20px</code> of <code>padding</code>.");'
<del> - text: 你的<code>blue-box</code>类应该给元素左边<code>padding</code> <code>40px</code> 。
<del> testString: 'assert($(".blue-box").css("padding-left") === "40px", "Your <code>blue-box</code> class should give the left of the elements <code>40px</code> of <code>padding</code>.");'
<add> - text: '你的<code>blue-box</code> class 的顶部<code>padding</code>(上内边距)值应为<code>40px</code>。'
<add> testString: assert($(".blue-box").css("padding-top") === "40px", '你的<code>blue-box</code> class 的顶部<code>padding</code>(上内边距)值应为<code>40px</code>。');
<add> - text: '你的<code>blue-box</code> class 的右侧<code>padding</code>(右内边距)值应为<code>20px</code>。'
<add> testString: assert($(".blue-box").css("padding-right") === "20px", '你的<code>blue-box</code> class 的右侧<code>padding</code>(右内边距)值应为<code>20px</code>。');
<add> - text: '你的<code>blue-box</code> class 的底部<code>padding</code>(下内边距)值应为<code>20px</code>。'
<add> testString: assert($(".blue-box").css("padding-bottom") === "20px", '你的<code>blue-box</code> class 的底部<code>padding</code>(下内边距)值应为<code>20px</code>。');
<add> - text: '你的<code>blue-box</code> class 的左侧<code>padding</code>(左内边距)值应为<code>40px</code>。'
<add> testString: assert($(".blue-box").css("padding-left") === "40px", '你的<code>blue-box</code> class 的左侧<code>padding</code>(左内边距)值应为<code>40px</code>。');
<ide>
<ide> ```
<ide>
<ide> tests:
<ide> background-color: yellow;
<ide> padding: 10px;
<ide> }
<del>
<add>
<ide> .red-box {
<ide> background-color: crimson;
<ide> color: #fff;
<ide> tests:
<ide> <h5 class="box red-box">padding</h5>
<ide> <h5 class="box blue-box">padding</h5>
<ide> </div>
<del>
<ide> ```
<ide>
<ide> </div>
<ide> tests:
<ide> ## Solution
<ide> <section id='solution'>
<ide>
<del>```js
<add>```html
<ide> // solution required
<ide> ```
<ide> </section>
<add>
<ide>\ No newline at end of file
<ide><path>curriculum/challenges/chinese/01-responsive-web-design/basic-css/add-rounded-corners-with-border-radius.chinese.md
<ide> id: bad87fee1348bd9aedf08814
<ide> title: Add Rounded Corners with border-radius
<ide> challengeType: 0
<del>videoUrl: ''
<del>localeTitle: 添加带有border-radius的圆角
<add>videoUrl: 'https://scrimba.com/c/cbZm2hg'
<add>forumTopicId: 16649
<add>localTitle: 用 border-radius 添加圆角边框
<ide> ---
<ide>
<ide> ## Description
<del><section id="description">你的猫照片目前有尖角。我们可以使用名为<code>border-radius</code>的CSS属性来舍入这些角。 </section>
<add><section id='description'>
<add>你的猫咪图片边角很尖锐,我们可以使用<code>border-radius</code>属性来让它变得圆润。
<add></section>
<ide>
<ide> ## Instructions
<del><section id="instructions">您可以使用像素指定<code>border-radius</code> 。给你的猫照片<code>border-radius</code> <code>10px</code> 。注意:此挑战允许多种可能的解决方案。例如,您可以将<code>border-radius</code>添加到<code>.thick-green-border</code>类或<code>.smaller-image</code>类。 </section>
<add><section id='instructions'>
<add><code>border-radius</code>可以用<code>px</code>像素单位来赋值。给你的猫咪图片设置 10px 的<code>border-radius</code>。
<add>注意:这个挑战有多个解决方法。例如,添加<code>border-radius</code>属性到<code>.thick-green-border</code>class 或<code>.smaller-image</code>class 里都是可行的。
<add></section>
<ide>
<ide> ## Tests
<ide> <section id='tests'>
<ide>
<ide> ```yml
<ide> tests:
<del> - text: 您的图片元素应该具有“thick-green-border”类。
<del> testString: 'assert($("img").hasClass("thick-green-border"), "Your image element should have the class "thick-green-border".");'
<del> - text: 您的图像的边框半径应为<code>10px</code>
<del> testString: 'assert(parseInt($("img").css("border-top-left-radius")) > 8, "Your image should have a border radius of <code>10px</code>");'
<add> - text: '你的图片元素应具有 "thick-green-border" class 属性。'
<add> testString: assert($("img").hasClass("thick-green-border"), '你的图片元素应具有 "thick-green-border" class 属性。');
<add> - text: '你的图片应含有<code>10px</code>的边框圆角。'
<add> testString: assert(parseInt($("img").css("border-top-left-radius")) > 8, '你的图片应含有<code>10px</code>的边框圆角。');
<ide>
<ide> ```
<ide>
<ide> tests:
<ide>
<ide> <h2 class="red-text">CatPhotoApp</h2>
<ide> <main>
<del> <p class="red-text">Click here to view more <a href="#">cat photos</a>.</p>
<del>
<del> <a href="#"><img class="smaller-image thick-green-border" src="https://bit.ly/fcc-relaxing-cat" alt="A cute orange cat lying on its back."></a>
<del>
<add> <p class="red-text">点击查看更多<a href="#">猫图</a>.</p>
<add>
<add> <a href="#"><img src="https://bit.ly/fcc-relaxing-cat" alt="一只仰卧着的萌猫" class="smaller-image thick-green-border"></a>
<add>
<ide> <div>
<del> <p>Things cats love:</p>
<add> <p>猫咪最喜欢的三件东西:</p>
<ide> <ul>
<del> <li>cat nip</li>
<del> <li>laser pointers</li>
<del> <li>lasagna</li>
<add> <li>猫薄荷</li>
<add> <li>激光笔</li>
<add> <li>千层饼</li>
<ide> </ul>
<del> <p>Top 3 things cats hate:</p>
<add> <p>猫咪最讨厌的三件东西:</p>
<ide> <ol>
<del> <li>flea treatment</li>
<del> <li>thunder</li>
<del> <li>other cats</li>
<add> <li>跳蚤</li>
<add> <li>打雷</li>
<add> <li>同类</li>
<ide> </ol>
<ide> </div>
<del>
<add>
<ide> <form action="/submit-cat-photo">
<del> <label><input type="radio" name="indoor-outdoor" checked> Indoor</label>
<del> <label><input type="radio" name="indoor-outdoor"> Outdoor</label><br>
<del> <label><input type="checkbox" name="personality" checked> Loving</label>
<del> <label><input type="checkbox" name="personality"> Lazy</label>
<del> <label><input type="checkbox" name="personality"> Energetic</label><br>
<del> <input type="text" placeholder="cat photo URL" required>
<del> <button type="submit">Submit</button>
<add> <label><input type="radio" name="indoor-outdoor">室内</label>
<add> <label><input type="radio" name="indoor-outdoor">室外</label><br>
<add> <label><input type="checkbox" name="personality">忠诚</label>
<add> <label><input type="checkbox" name="personality">懒惰</label>
<add> <label><input type="checkbox" name="personality">积极</label><br>
<add> <input type="text" placeholder="猫咪图片地址" required>
<add> <button type="submit">提交</button>
<ide> </form>
<ide> </main>
<del>
<ide> ```
<ide>
<ide> </div>
<ide> tests:
<ide> ## Solution
<ide> <section id='solution'>
<ide>
<del>```js
<add>```html
<ide> // solution required
<ide> ```
<ide> </section>
<add>
<ide>\ No newline at end of file
<ide><path>curriculum/challenges/chinese/01-responsive-web-design/basic-css/adjust-the-margin-of-an-element.chinese.md
<ide> id: bad87fee1348bd9aedf08822
<ide> title: Adjust the Margin of an Element
<ide> challengeType: 0
<del>videoUrl: ''
<del>localeTitle: 调整元素的边距
<add>videoUrl: 'https://scrimba.com/c/cVJarHW'
<add>forumTopicId: 16654
<add>localTitle: 调整元素的外边距
<ide> ---
<ide>
<ide> ## Description
<del><section id="description">元素的<code>margin</code>控制元素<code>border</code>与周围元素之间的空间量。在这里,我们可以看到蓝色框和红色框嵌套在黄色框中。请注意,红色框的<code>margin</code>大于蓝色框,使其看起来更小。当您增加蓝框的<code>margin</code> ,它将增加其边框与周围元素之间的距离。 </section>
<add><section id='description'>
<add><code>margin(外边距)</code>控制元素的边框与其他元素之间的距离。
<add>在这里,我们可以看到蓝色盒子和红色盒子都在黄色盒子里。请注意,红色盒子的<code>margin</code>值要比蓝色盒子的大,让它看起来比蓝色盒子要小。
<add>当你增加蓝色的<code>margin</code>值,它会增加元素边框到其他周围元素的距离。
<add></section>
<ide>
<ide> ## Instructions
<del><section id="instructions">更改蓝色框的<code>margin</code>以匹配红色框的<code>margin</code> 。 </section>
<add><section id='instructions'>
<add>蓝色的盒子<code>margin</code>的值要跟红色盒子的一样大小。
<add></section>
<ide>
<ide> ## Tests
<ide> <section id='tests'>
<ide>
<ide> ```yml
<ide> tests:
<del> - text: 你的<code>blue-box</code>类应该给出<code>20px</code>的<code>margin</code>元素。
<del> testString: 'assert($(".blue-box").css("margin-top") === "20px", "Your <code>blue-box</code> class should give elements <code>20px</code> of <code>margin</code>.");'
<add> - text: '你的<code>blue-box</code> class 的<code>margin</code>值应为<code>20px</code>。'
<add> testString: assert($(".blue-box").css("margin-top") === "20px", '你的<code>blue-box</code> class 的<code>margin</code>值应为<code>20px</code>。');
<ide>
<ide> ```
<ide>
<ide> tests:
<ide> background-color: yellow;
<ide> padding: 10px;
<ide> }
<del>
<add>
<ide> .red-box {
<ide> background-color: crimson;
<ide> color: #fff;
<ide> tests:
<ide> <h5 class="box red-box">padding</h5>
<ide> <h5 class="box blue-box">padding</h5>
<ide> </div>
<del>
<ide> ```
<ide>
<ide> </div>
<ide> tests:
<ide> // solution required
<ide> ```
<ide> </section>
<add>
<ide>\ No newline at end of file
<ide><path>curriculum/challenges/chinese/01-responsive-web-design/basic-css/adjust-the-padding-of-an-element.chinese.md
<ide> id: bad88fee1348bd9aedf08825
<ide> title: Adjust the Padding of an Element
<ide> challengeType: 0
<del>videoUrl: ''
<del>localeTitle: 调整元素的填充
<add>videoUrl: 'https://scrimba.com/c/cED8ZC2'
<add>forumTopicId: 301083
<add>localTitle: 调整元素的内边距
<ide> ---
<ide>
<ide> ## Description
<del><section id="description">现在让我们将我们的Cat Photo App放一段时间,了解更多关于样式HTML的信息。您可能已经注意到了这一点,但所有HTML元素基本上都是小矩形。三个重要属性控制每个HTML元素周围的空间: <code>padding</code> , <code>margin</code>和<code>border</code> 。元素的<code>padding</code>控制元素内容与其<code>border</code>之间的空间量。在这里,我们可以看到蓝色框和红色框嵌套在黄色框中。请注意,红色框具有比蓝色框更多的<code>padding</code> 。当您增加蓝框的<code>padding</code> ,它将增加文本与其周围边框之间的距离( <code>padding</code> )。 </section>
<add><section id='description'>
<add>我们先暂时把猫咪图片放在一边,让我们去学习更多 HTML 相关样式。
<add>你可能已经注意到了,所有的 HTML 元素基本都是以矩形为基础。
<add>每个 HTML 元素周围的矩形空间由三个重要的属性来控制:<code>padding(内边距)</code>,<code>margin(外边距)</code>和<code>border(边框)</code>。
<add><code>padding</code>控制着元素内容与<code>border</code>之间的空隙大小。
<add>在这里,我们可以看到蓝色盒子和红色盒子都在黄色盒子里面。可以发现,红色盒子比蓝色盒子有着更多的<code>padding</code>填充空间。
<add>当你增加蓝色盒子的<code>padding</code>值,文本内容与边框的距离会逐渐拉大。
<add></section>
<ide>
<ide> ## Instructions
<del><section id="instructions">更改蓝色框的<code>padding</code>以匹配红色框的<code>padding</code> 。 </section>
<add><section id='instructions'>
<add>蓝色的盒子<code>padding</code>的值要跟红色盒子的一样大小。
<add></section>
<ide>
<ide> ## Tests
<ide> <section id='tests'>
<ide>
<ide> ```yml
<ide> tests:
<del> - text: 你的<code>blue-box</code>类应该给出<code>20px</code>的<code>padding</code>元素。
<del> testString: 'assert($(".blue-box").css("padding-top") === "20px", "Your <code>blue-box</code> class should give elements <code>20px</code> of <code>padding</code>.");'
<add> - text: '你的<code>blue-box</code> class 的<code>padding</code>值应为<code>20px</code>。'
<add> testString: assert($(".blue-box").css("padding-top") === "20px", '你的<code>blue-box</code> class 的<code>padding</code>值应为<code>20px</code>。');
<ide>
<ide> ```
<ide>
<ide> tests:
<ide> background-color: yellow;
<ide> padding: 10px;
<ide> }
<del>
<add>
<ide> .red-box {
<ide> background-color: crimson;
<ide> color: #fff;
<ide> tests:
<ide> <h5 class="box red-box">padding</h5>
<ide> <h5 class="box blue-box">padding</h5>
<ide> </div>
<del>
<ide> ```
<ide>
<ide> </div>
<ide> tests:
<ide> ## Solution
<ide> <section id='solution'>
<ide>
<del>```js
<add>```html
<ide> // solution required
<ide> ```
<add>
<ide> </section>
<add>
<ide>\ No newline at end of file
<ide><path>curriculum/challenges/chinese/01-responsive-web-design/basic-css/attach-a-fallback-value-to-a-css-variable.chinese.md
<ide> id: 5a9d7286424fe3d0e10cad13
<ide> title: Attach a Fallback value to a CSS Variable
<ide> challengeType: 0
<del>videoUrl: ''
<del>localeTitle: 将Fallback值附加到CSS变量
<add>videoUrl: 'https://scrimba.com/c/c6bDNfp'
<add>forumTopicId: 301084
<add>localTitle: 给 CSS 变量附加回退值
<ide> ---
<ide>
<ide> ## Description
<del><section id="description">将变量用作CSS属性值时,如果给定变量无效,则可以附加浏览器将恢复的回退值。 <strong>注意:</strong>此回退不用于增加浏览器兼容性,并且它不适用于IE浏览器。而是使用它,以便浏览器在无法找到变量时显示颜色。这是你如何做到的: <blockquote>背景:var( - 企鹅皮,黑色); </blockquote>如果未设置变量,则会将背景设置为黑色。请注意,这对于调试很有用。 </section>
<add><section id='description'>
<add>使用变量来作为 CSS 属性值的时候,可以设置一个备用值来防止由于某些原因导致变量不生效的情况。
<add>或许有些人正在使用着不支持 CSS 变量的旧浏览器,又或者,设备不支持你设置的变量值。为了防止这种情况出现,那么你可以这样写:
<add>
<add>```css
<add>background: var(--penguin-skin, black);
<add>```
<add>
<add>这样,当你的变量有问题的时候,它会设置你的背景颜色为黑色。
<add>提示:这对调试会很有帮助。
<add></section>
<ide>
<ide> ## Instructions
<del><section id="instructions">它看起来提供给<code>.penguin-top</code>和<code>.penguin-bottom</code>类的变量存在问题。而不是修复拼写错误,将<code>.penguin-top</code>值的<code>black</code>添加到<code>.penguin-top</code>和<code>.penguin-bottom</code>类的<code>background</code>属性中。 </section>
<add><section id='instructions'>
<add>在<code>penguin-top</code>和<code>penguin-bottom</code>class 里面,<code>background</code>属性设置一个<code>black</code>的备用色。
<add><strong>注意:</strong>因为 CSS 变量名拼写错了,所以备用值会被使用。
<add></section>
<ide>
<ide> ## Tests
<ide> <section id='tests'>
<ide>
<ide> ```yml
<ide> tests:
<del> - text: 的后退值应用于<code>black</code>为<code>background</code>的财产<code>penguin-top</code>班。
<del> testString: 'assert(code.match(/.penguin-top\s*?{[\s\S]*background\s*?:\s*?var\(\s*?--pengiun-skin\s*?,\s*?black\s*?\)\s*?;[\s\S]*}[\s\S]*.penguin-bottom\s{/gi), "Apply the fallback value of <code>black</code> to the <code>background</code> property of the <code>penguin-top</code> class.");'
<del> - text: 将<code>black</code>的后备值应用于<code>penguin-bottom</code>类的<code>background</code>属性。
<del> testString: 'assert(code.match(/.penguin-bottom\s*?{[\s\S]*background\s*?:\s*?var\(\s*?--pengiun-skin\s*?,\s*?black\s*?\)\s*?;[\s\S]*}/gi), "Apply the fallback value of <code>black</code> to the <code>background</code> property of the <code>penguin-bottom</code> class.");'
<add> - text: '<code>penguin-top</code> class 的<code>background</code>属性应设置一个<code>black</code>备用颜色。'
<add> testString: 'assert(code.match(/.penguin-top\s*?{[\s\S]*background\s*?:\s*?var\(\s*?--pengiun-skin\s*?,\s*?black\s*?\)\s*?;[\s\S]*}[\s\S]*.penguin-bottom\s{/gi), ''<code>penguin-top</code> class 的<code>background</code>属性应设置一个<code>black</code>备用颜色。'');'
<add> - text: '<code>penguin-bottom</code> class 的<code>background</code>属性应设置一个<code>black</code>备用颜色。'
<add> testString: 'assert(code.match(/.penguin-bottom\s*?{[\s\S]*background\s*?:\s*?var\(\s*?--pengiun-skin\s*?,\s*?black\s*?\)\s*?;[\s\S]*}/gi), ''<code>penguin-bottom</code> class 的<code>background</code>属性应设置一个<code>black</code>备用颜色。'');'
<ide>
<ide> ```
<ide>
<ide> tests:
<ide> width: 300px;
<ide> height: 300px;
<ide> }
<del>
<add>
<ide> .penguin-top {
<ide> top: 10%;
<ide> left: 25%;
<del>
<add>
<ide> /* change code below */
<ide> background: var(--pengiun-skin);
<ide> /* change code above */
<del>
<add>
<ide> width: 50%;
<ide> height: 45%;
<ide> border-radius: 70% 70% 60% 60%;
<ide> }
<del>
<add>
<ide> .penguin-bottom {
<ide> top: 40%;
<ide> left: 23.5%;
<del>
<add>
<ide> /* change code below */
<ide> background: var(--pengiun-skin);
<ide> /* change code above */
<del>
<add>
<ide> width: 53%;
<ide> height: 45%;
<ide> border-radius: 70% 70% 100% 100%;
<ide> }
<del>
<add>
<ide> .right-hand {
<ide> top: 0%;
<ide> left: -5%;
<ide> tests:
<ide> transform: rotate(45deg);
<ide> z-index: -1;
<ide> }
<del>
<add>
<ide> .left-hand {
<ide> top: 0%;
<ide> left: 75%;
<ide> tests:
<ide> transform: rotate(-45deg);
<ide> z-index: -1;
<ide> }
<del>
<add>
<ide> .right-cheek {
<ide> top: 15%;
<ide> left: 35%;
<ide> tests:
<ide> height: 70%;
<ide> border-radius: 70% 70% 60% 60%;
<ide> }
<del>
<add>
<ide> .left-cheek {
<ide> top: 15%;
<ide> left: 5%;
<ide> tests:
<ide> height: 70%;
<ide> border-radius: 70% 70% 60% 60%;
<ide> }
<del>
<add>
<ide> .belly {
<ide> top: 60%;
<ide> left: 2.5%;
<ide> tests:
<ide> height: 100%;
<ide> border-radius: 120% 120% 100% 100%;
<ide> }
<del>
<add>
<ide> .right-feet {
<ide> top: 85%;
<ide> left: 60%;
<ide> tests:
<ide> transform: rotate(-80deg);
<ide> z-index: -2222;
<ide> }
<del>
<add>
<ide> .left-feet {
<ide> top: 85%;
<ide> left: 25%;
<ide> tests:
<ide> transform: rotate(80deg);
<ide> z-index: -2222;
<ide> }
<del>
<add>
<ide> .right-eye {
<ide> top: 45%;
<ide> left: 60%;
<ide> tests:
<ide> height: 17%;
<ide> border-radius: 50%;
<ide> }
<del>
<add>
<ide> .left-eye {
<ide> top: 45%;
<ide> left: 25%;
<ide> tests:
<ide> height: 17%;
<ide> border-radius: 50%;
<ide> }
<del>
<add>
<ide> .sparkle {
<ide> top: 25%;
<ide> left: 15%;
<ide> tests:
<ide> height: 35%;
<ide> border-radius: 50%;
<ide> }
<del>
<add>
<ide> .blush-right {
<ide> top: 65%;
<ide> left: 15%;
<ide> tests:
<ide> height: 10%;
<ide> border-radius: 50%;
<ide> }
<del>
<add>
<ide> .blush-left {
<ide> top: 65%;
<ide> left: 70%;
<ide> tests:
<ide> height: 10%;
<ide> border-radius: 50%;
<ide> }
<del>
<add>
<ide> .beak-top {
<ide> top: 60%;
<ide> left: 40%;
<ide> tests:
<ide> height: 10%;
<ide> border-radius: 50%;
<ide> }
<del>
<add>
<ide> .beak-bottom {
<ide> top: 65%;
<ide> left: 42%;
<ide> tests:
<ide> height: 10%;
<ide> border-radius: 50%;
<ide> }
<del>
<add>
<ide> body {
<ide> background:#c6faf1;
<ide> }
<del>
<add>
<ide> .penguin * {
<ide> position: absolute;
<ide> }
<ide> tests:
<ide> <div class="beak-bottom"></div>
<ide> </div>
<ide> </div>
<del>
<ide> ```
<ide>
<ide> </div>
<ide> tests:
<ide> ## Solution
<ide> <section id='solution'>
<ide>
<add>
<ide> ```js
<ide> // solution required
<ide> ```
<add>
<ide> </section>
<add>
<ide>\ No newline at end of file
<ide><path>curriculum/challenges/chinese/01-responsive-web-design/basic-css/change-a-variable-for-a-specific-area.chinese.md
<ide> id: 5a9d72a1424fe3d0e10cad15
<ide> title: Change a variable for a specific area
<ide> challengeType: 0
<del>videoUrl: ''
<del>localeTitle: 更改特定区域的变量
<add>videoUrl: 'https://scrimba.com/c/cdRwbuW'
<add>forumTopicId: 301085
<add>localTitle: 更改特定区域的变量
<ide> ---
<ide>
<ide> ## Description
<del><section id="description">当您在创建变量<code>:root</code> ,他们将设置可变整个页面的价值。然后,您可以通过在特定元素中再次设置它们来覆盖这些变量。 </section>
<add><section id='description'>
<add>当你在<code>:root</code>里创建变量时,这些变量的作用域是整个页面。
<add>如果在元素里创建相同的变量,会重写<code>:root</code>变量设置的值。
<add>
<add></section>
<ide>
<ide> ## Instructions
<del><section id="instructions">在<code>penguin</code>类<code>--penguin-belly</code>的值更改为<code>white</code> 。 </section>
<add><section id='instructions'>
<add>在<code>penguin</code>class 里,设置<code>--penguin-belly</code>的值为<code>white</code>。
<add></section>
<ide>
<ide> ## Tests
<ide> <section id='tests'>
<ide>
<ide> ```yml
<ide> tests:
<del> - text: <code>penguin</code>类应该将<code>--penguin-belly</code>变量重新分配为<code>white</code> 。
<del> testString: 'assert(code.match(/.penguin\s*?{[\s\S]*--penguin-belly\s*?:\s*?white\s*?;[\s\S]*}/gi), "The <code>penguin</code> class should reassign the <code>--penguin-belly</code> variable to <code>white</code>.");'
<add> - text: '应该在<code>penguin</code>clas 里重定义<code>--penguin-belly</code>的变量值,且它的值为<code>white</code>。'
<add> testString: 'assert(code.match(/.penguin\s*?{[\s\S]*--penguin-belly\s*?:\s*?white\s*?;[\s\S]*}/gi), ''应该在<code>penguin</code>clas 里重定义<code>--penguin-belly</code>的变量值,且它的值为<code>white</code>。'');'
<ide>
<ide> ```
<ide>
<ide> tests:
<ide> --penguin-belly: pink;
<ide> --penguin-beak: orange;
<ide> }
<del>
<add>
<ide> body {
<ide> background: var(--penguin-belly, #c6faf1);
<ide> }
<del>
<add>
<ide> .penguin {
<del>
<add>
<ide> /* add code below */
<del>
<add>
<ide> /* add code above */
<del>
<add>
<ide> position: relative;
<ide> margin: auto;
<ide> display: block;
<ide> margin-top: 5%;
<ide> width: 300px;
<ide> height: 300px;
<ide> }
<del>
<add>
<ide> .right-cheek {
<ide> top: 15%;
<ide> left: 35%;
<ide> tests:
<ide> height: 70%;
<ide> border-radius: 70% 70% 60% 60%;
<ide> }
<del>
<add>
<ide> .left-cheek {
<ide> top: 15%;
<ide> left: 5%;
<ide> tests:
<ide> height: 70%;
<ide> border-radius: 70% 70% 60% 60%;
<ide> }
<del>
<add>
<ide> .belly {
<ide> top: 60%;
<ide> left: 2.5%;
<ide> tests:
<ide> height: 100%;
<ide> border-radius: 120% 120% 100% 100%;
<ide> }
<del>
<add>
<ide> .penguin-top {
<ide> top: 10%;
<ide> left: 25%;
<ide> tests:
<ide> height: 45%;
<ide> border-radius: 70% 70% 60% 60%;
<ide> }
<del>
<add>
<ide> .penguin-bottom {
<ide> top: 40%;
<ide> left: 23.5%;
<ide> tests:
<ide> height: 45%;
<ide> border-radius: 70% 70% 100% 100%;
<ide> }
<del>
<add>
<ide> .right-hand {
<ide> top: 0%;
<ide> left: -5%;
<ide> tests:
<ide> transform: rotate(45deg);
<ide> z-index: -1;
<ide> }
<del>
<add>
<ide> .left-hand {
<ide> top: 0%;
<ide> left: 75%;
<ide> tests:
<ide> transform: rotate(-45deg);
<ide> z-index: -1;
<ide> }
<del>
<add>
<ide> .right-feet {
<ide> top: 85%;
<ide> left: 60%;
<ide> tests:
<ide> transform: rotate(-80deg);
<ide> z-index: -2222;
<ide> }
<del>
<add>
<ide> .left-feet {
<ide> top: 85%;
<ide> left: 25%;
<ide> tests:
<ide> transform: rotate(80deg);
<ide> z-index: -2222;
<ide> }
<del>
<add>
<ide> .right-eye {
<ide> top: 45%;
<ide> left: 60%;
<ide> tests:
<ide> height: 17%;
<ide> border-radius: 50%;
<ide> }
<del>
<add>
<ide> .left-eye {
<ide> top: 45%;
<ide> left: 25%;
<ide> tests:
<ide> height: 17%;
<ide> border-radius: 50%;
<ide> }
<del>
<add>
<ide> .sparkle {
<ide> top: 25%;
<ide> left: 15%;
<ide> tests:
<ide> height: 35%;
<ide> border-radius: 50%;
<ide> }
<del>
<add>
<ide> .blush-right {
<ide> top: 65%;
<ide> left: 15%;
<ide> tests:
<ide> height: 10%;
<ide> border-radius: 50%;
<ide> }
<del>
<add>
<ide> .blush-left {
<ide> top: 65%;
<ide> left: 70%;
<ide> tests:
<ide> height: 10%;
<ide> border-radius: 50%;
<ide> }
<del>
<add>
<ide> .beak-top {
<ide> top: 60%;
<ide> left: 40%;
<ide> tests:
<ide> height: 10%;
<ide> border-radius: 50%;
<ide> }
<del>
<add>
<ide> .beak-bottom {
<ide> top: 65%;
<ide> left: 42%;
<ide> tests:
<ide> height: 10%;
<ide> border-radius: 50%;
<ide> }
<del>
<add>
<ide> .penguin * {
<ide> position: absolute;
<ide> }
<ide> tests:
<ide> <div class="beak-bottom"></div>
<ide> </div>
<ide> </div>
<del>
<ide> ```
<ide>
<ide> </div>
<ide> tests:
<ide> ## Solution
<ide> <section id='solution'>
<ide>
<add>
<ide> ```js
<ide> // solution required
<ide> ```
<add>
<ide> </section>
<add>
<ide>\ No newline at end of file
<ide><path>curriculum/challenges/chinese/01-responsive-web-design/basic-css/change-the-color-of-text.chinese.md
<ide> id: bad87fee1348bd9aedf08803
<ide> title: Change the Color of Text
<ide> challengeType: 0
<del>videoUrl: ''
<del>localeTitle: 更改文本的颜色
<add>videoUrl: 'https://scrimba.com/c/cPp7VfD'
<add>forumTopicId: 1
<add>localTitle: 更改文本的颜色
<ide> ---
<ide>
<ide> ## Description
<del><section id="description">现在让我们改变一些文字的颜色。我们可以通过改变你的<code>h2</code>元素的<code>style</code>来做到这一点。负责元素文本<code>color</code>属性是<code>color</code>样式属性。以下是将<code>h2</code>元素的文本颜色设置为蓝色的方法: <code><h2 style="color: blue;">CatPhotoApp</h2></code>请注意,最好使用<code>;</code>结束内联<code>style</code>声明<code>;</code> 。 </section>
<add><section id='description'>
<add>现在让我们来修改一下文本的颜色。
<add>我们通过修改<code>h2</code>元素的<code>style</code>属性的<code>color</code>值来改变文本颜色。
<add>以下是改变<code>h2</code>元素为蓝色的方法:
<add><code><h2 style="color: blue;">CatPhotoApp</h2></code>
<add>请注意行内<code>style</code>最好以<code>;</code>来结束。
<add></section>
<ide>
<ide> ## Instructions
<del><section id="instructions">更改<code>h2</code>元素的样式,使其文本颜色为红色。 </section>
<add><section id='instructions'>
<add>请把<code>h2</code>元素的文本颜色设置为红色。
<add></section>
<ide>
<ide> ## Tests
<ide> <section id='tests'>
<ide>
<ide> ```yml
<ide> tests:
<del> - text: 你的<code>h2</code>元素应该是红色的。
<del> testString: 'assert($("h2").css("color") === "rgb(255, 0, 0)", "Your <code>h2</code> element should be red.");'
<del> - text: 你的<code>style</code>声明应以a结尾<code>;</code> 。
<del> testString: 'assert(code.match(/<h2\s+style\s*=\s*(\"|")\s*color\s*:\s*(?:rgb\(\s*255\s*,\s*0\s*,\s*0\s*\)|rgb\(\s*100%\s*,\s*0%\s*,\s*0%\s*\)|red|#ff0000|#f00|hsl\(\s*0\s*,\s*100%\s*,\s*50%\s*\))\s*\;(\"|")>\s*CatPhotoApp\s*<\/h2>/)," Your <code>style</code> declaration should end with a <code>;</code> .");'
<add> - text: '<code>h2</code>元素应该为红色。'
<add> testString: assert($("h2").css("color") === "rgb(255, 0, 0)", '<code>h2</code>元素应该为红色。');
<add> - text: '<code>h2</code>元素的<code>style</code>属性值应该以<code>;</code>结束。'
<add> testString: 'assert(code.match(/<h2\s+style\s*=\s*(\''|")\s*color\s*:\s*(?:rgb\(\s*255\s*,\s*0\s*,\s*0\s*\)|rgb\(\s*100%\s*,\s*0%\s*,\s*0%\s*\)|red|#ff0000|#f00|hsl\(\s*0\s*,\s*100%\s*,\s*50%\s*\))\s*\;(\''|")>\s*CatPhotoApp\s*<\/h2>/),''<code>h2</code>元素的<code>style</code>属性值应该以<code>;</code>结束。'');'
<add> - text: '<code>style</code> 声明应该以 <code>;</code> 结尾'
<add> testString: assert($("h2").attr('style') && $("h2").attr('style').endsWith(';'));
<ide>
<ide> ```
<ide>
<ide> tests:
<ide> ```html
<ide> <h2>CatPhotoApp</h2>
<ide> <main>
<del> <p>Click here to view more <a href="#">cat photos</a>.</p>
<add> <p class="red-text">点击查看更多<a href="#">猫图</a>.</p>
<ide>
<del> <a href="#"><img src="https://bit.ly/fcc-relaxing-cat" alt="A cute orange cat lying on its back."></a>
<add> <a href="#"><img src="https://bit.ly/fcc-relaxing-cat" alt="一只仰卧着的萌猫"></a>
<ide>
<ide> <div>
<del> <p>Things cats love:</p>
<add> <p>猫咪最喜欢的三件东西:</p>
<ide> <ul>
<del> <li>cat nip</li>
<del> <li>laser pointers</li>
<del> <li>lasagna</li>
<add> <li>猫薄荷</li>
<add> <li>激光笔</li>
<add> <li>千层饼</li>
<ide> </ul>
<del> <p>Top 3 things cats hate:</p>
<add> <p>猫咪最讨厌的三件东西:</p>
<ide> <ol>
<del> <li>flea treatment</li>
<del> <li>thunder</li>
<del> <li>other cats</li>
<add> <li>跳蚤</li>
<add> <li>打雷</li>
<add> <li>同类</li>
<ide> </ol>
<ide> </div>
<del>
<add>
<ide> <form action="/submit-cat-photo">
<del> <label><input type="radio" name="indoor-outdoor" checked> Indoor</label>
<del> <label><input type="radio" name="indoor-outdoor"> Outdoor</label><br>
<del> <label><input type="checkbox" name="personality" checked> Loving</label>
<del> <label><input type="checkbox" name="personality"> Lazy</label>
<del> <label><input type="checkbox" name="personality"> Energetic</label><br>
<del> <input type="text" placeholder="cat photo URL" required>
<del> <button type="submit">Submit</button>
<add> <label><input type="radio" name="indoor-outdoor">室内</label>
<add> <label><input type="radio" name="indoor-outdoor">室外</label><br>
<add> <label><input type="checkbox" name="personality">忠诚</label>
<add> <label><input type="checkbox" name="personality">懒惰</label>
<add> <label><input type="checkbox" name="personality">积极</label><br>
<add> <input type="text" placeholder="猫咪图片地址" required>
<add> <button type="submit">提交</button>
<ide> </form>
<ide> </main>
<del>
<ide> ```
<ide>
<ide> </div>
<ide> tests:
<ide> ## Solution
<ide> <section id='solution'>
<ide>
<del>```js
<add>```html
<ide> // solution required
<ide> ```
<ide> </section>
<add>
<ide>\ No newline at end of file
<ide><path>curriculum/challenges/chinese/01-responsive-web-design/basic-css/change-the-font-size-of-an-element.chinese.md
<ide> id: bad87fee1348bd9aedf08806
<ide> title: Change the Font Size of an Element
<ide> challengeType: 0
<del>videoUrl: ''
<del>localeTitle: 更改元素的字体大小
<add>videoUrl: 'https://scrimba.com/c/cPp7VfD'
<add>forumTopicId: 1
<add>localTitle: 更改元素的字体大小
<ide> ---
<ide>
<ide> ## Description
<del><section id="description">字体大小由<code>font-size</code> CSS属性控制,如下所示: <blockquote> h1 { <br> font-size:30px; <br> } </blockquote></section>
<add><section id='description'>
<add>字体大小由<code>font-size</code>属性控制,如下所示:
<add>
<add>```css
<add>h1 {
<add> font-size: 30px;
<add>}
<add>```
<add>
<add></section>
<ide>
<ide> ## Instructions
<del><section id="instructions">里面的相同<code><style></code>包含您的标记<code>red-text</code>类,创建一个条目<code>p</code>元素和设置<code>font-size</code>为16个像素( <code>16px</code> )。 </section>
<add><section id='instructions'>
<add>在包含<code>red-text</code>class 选择器的<code><style></code>声明区域的里,创建一个<code>p</code>元素样式规则,并设置<code>font-size</code>为<code>16px</code>。
<add></section>
<ide>
<ide> ## Tests
<ide> <section id='tests'>
<ide>
<ide> ```yml
<ide> tests:
<del> - text: 在<code>style</code>标记之间,给出<code>p</code>元素<code>font-size</code>为<code>16px</code> 。浏览器和文本缩放应为100%。
<del> testString: 'assert(code.match(/p\s*{\s*font-size\s*:\s*16\s*px\s*;\s*}/i), "Between the <code>style</code> tags, give the <code>p</code> elements <code>font-size</code> of <code>16px</code>. Browser and Text zoom should be at 100%.");'
<add> - text: '在<code>style</code>样式声明区域里,<code>p</code>元素的<code>font-size</code>的值应为<code>16px</code>,浏览器和文本缩放应设置为 100%。'
<add> testString: 'assert(code.match(/p\s*{\s*font-size\s*:\s*16\s*px\s*;\s*}/i), ''在<code>style</code>样式声明区域里,<code>p</code>元素的<code>font-size</code>的值应为<code>16px</code>,浏览器和文本缩放应设置为 100%。'');'
<ide>
<ide> ```
<ide>
<ide> tests:
<ide>
<ide> <h2 class="red-text">CatPhotoApp</h2>
<ide> <main>
<del> <p class="red-text">Click here to view more <a href="#">cat photos</a>.</p>
<add> <p class="red-text">点击查看更多<a href="#">猫图</a>.</p>
<ide>
<del> <a href="#"><img src="https://bit.ly/fcc-relaxing-cat" alt="A cute orange cat lying on its back."></a>
<add> <a href="#"><img src="https://bit.ly/fcc-relaxing-cat" alt="一只仰卧着的萌猫"></a>
<ide>
<ide> <div>
<del> <p>Things cats love:</p>
<add> <p>猫咪最喜欢的三件东西:</p>
<ide> <ul>
<del> <li>cat nip</li>
<del> <li>laser pointers</li>
<del> <li>lasagna</li>
<add> <li>猫薄荷</li>
<add> <li>激光笔</li>
<add> <li>千层饼</li>
<ide> </ul>
<del> <p>Top 3 things cats hate:</p>
<add> <p>猫咪最讨厌的三件东西:</p>
<ide> <ol>
<del> <li>flea treatment</li>
<del> <li>thunder</li>
<del> <li>other cats</li>
<add> <li>跳蚤</li>
<add> <li>打雷</li>
<add> <li>同类</li>
<ide> </ol>
<ide> </div>
<del>
<add>
<ide> <form action="/submit-cat-photo">
<del> <label><input type="radio" name="indoor-outdoor" checked> Indoor</label>
<del> <label><input type="radio" name="indoor-outdoor"> Outdoor</label><br>
<del> <label><input type="checkbox" name="personality" checked> Loving</label>
<del> <label><input type="checkbox" name="personality"> Lazy</label>
<del> <label><input type="checkbox" name="personality"> Energetic</label><br>
<del> <input type="text" placeholder="cat photo URL" required>
<del> <button type="submit">Submit</button>
<add> <label><input type="radio" name="indoor-outdoor">室内</label>
<add> <label><input type="radio" name="indoor-outdoor">室外</label><br>
<add> <label><input type="checkbox" name="personality">忠诚</label>
<add> <label><input type="checkbox" name="personality">懒惰</label>
<add> <label><input type="checkbox" name="personality">积极</label><br>
<add> <input type="text" placeholder="猫咪图片地址" required>
<add> <button type="submit">提交</button>
<ide> </form>
<ide> </main>
<del>
<ide> ```
<ide>
<ide> </div>
<ide> tests:
<ide> ## Solution
<ide> <section id='solution'>
<ide>
<del>```js
<add>```html
<ide> // solution required
<ide> ```
<ide> </section>
<add>
<ide>\ No newline at end of file
<ide><path>curriculum/challenges/chinese/01-responsive-web-design/basic-css/create-a-custom-css-variable.chinese.md
<ide> id: 5a9d726c424fe3d0e10cad11
<ide> title: Create a custom CSS Variable
<ide> challengeType: 0
<del>videoUrl: ''
<del>localeTitle: 创建自定义CSS变量
<add>videoUrl: 'https://scrimba.com/c/cQd27Hr'
<add>forumTopicId: 301086
<add>localTitle: 创建一个自定义的 CSS 变量
<ide> ---
<ide>
<ide> ## Description
<del><section id="description">要创建一个CSS变量,你只需要给它一个<code>name</code>有<code>two dashes</code>在它前面,并为其分配一个<code>value</code>是这样的: <blockquote> - penguin-skin:灰色; </blockquote>这将创建一个名为<code>--penguin-skin</code>的变量,并为其赋值为<code>gray</code> 。现在,您可以在CSS中的其他位置使用该变量将其他元素的值更改为灰色。 </section>
<add><section id='description'>
<add>创建一个 CSS 变量,你只需要在变量名前添加两个<code>破折号</code>,并为其赋值,例子如下:
<add>
<add>```css
<add>--penguin-skin: gray;
<add>```
<add>
<add>这样会创建一个<code>--penguin-skin</code>变量并赋值为<code>gray(灰色)</code>。
<add>现在,其他元素可通过该变量来设置为<code>gray(灰色)</code>。
<add></section>
<ide>
<ide> ## Instructions
<del><section id="instructions">在<code>penguin</code>类中,创建一个变量名称<code>--penguin-skin</code>并赋予它一个<code>gray</code>值</section>
<add><section id='instructions'>
<add>在<code>penguin</code>class 里面,创建一个<code>--penguin-skin</code>变量,且赋值为<code>gray(灰色)</code>。
<add></section>
<ide>
<ide> ## Tests
<ide> <section id='tests'>
<ide>
<ide> ```yml
<ide> tests:
<del> - text: <code>penguin</code>类应声明<code>--penguin-skin</code>变量并将其指定为<code>gray</code> 。
<del> testString: 'assert(code.match(/.penguin\s*?{[\s\S]*--penguin-skin\s*?:\s*?gray\s*?;[\s\S]*}/gi), "<code>penguin</code> class should declare the <code>--penguin-skin</code> variable and assign it to <code>gray</code>.");'
<add> - text: '<code>penguin</code> class 里应声明<code>--penguin-skin</code>变量,且赋值为<code>gray</code>。'
<add> testString: 'assert(code.match(/.penguin\s*?{[\s\S]*--penguin-skin\s*?:\s*?gray\s*?;[\s\S]*}/gi), ''<code>penguin</code> class 里应声明<code>--penguin-skin</code>变量,且赋值为<code>gray</code>。'');'
<ide>
<ide> ```
<ide>
<ide> tests:
<ide> ```html
<ide> <style>
<ide> .penguin {
<del>
<add>
<ide> /* add code below */
<del>
<add>
<ide> /* add code above */
<ide> position: relative;
<ide> margin: auto;
<ide> tests:
<ide> width: 300px;
<ide> height: 300px;
<ide> }
<del>
<add>
<ide> .penguin-top {
<ide> top: 10%;
<ide> left: 25%;
<ide> tests:
<ide> height: 45%;
<ide> border-radius: 70% 70% 60% 60%;
<ide> }
<del>
<add>
<ide> .penguin-bottom {
<ide> top: 40%;
<ide> left: 23.5%;
<ide> tests:
<ide> height: 45%;
<ide> border-radius: 70% 70% 100% 100%;
<ide> }
<del>
<add>
<ide> .right-hand {
<ide> top: 0%;
<ide> left: -5%;
<ide> tests:
<ide> transform: rotate(45deg);
<ide> z-index: -1;
<ide> }
<del>
<add>
<ide> .left-hand {
<ide> top: 0%;
<ide> left: 75%;
<ide> tests:
<ide> transform: rotate(-45deg);
<ide> z-index: -1;
<ide> }
<del>
<add>
<ide> .right-cheek {
<ide> top: 15%;
<ide> left: 35%;
<ide> tests:
<ide> height: 70%;
<ide> border-radius: 70% 70% 60% 60%;
<ide> }
<del>
<add>
<ide> .left-cheek {
<ide> top: 15%;
<ide> left: 5%;
<ide> tests:
<ide> height: 70%;
<ide> border-radius: 70% 70% 60% 60%;
<ide> }
<del>
<add>
<ide> .belly {
<ide> top: 60%;
<ide> left: 2.5%;
<ide> tests:
<ide> height: 100%;
<ide> border-radius: 120% 120% 100% 100%;
<ide> }
<del>
<add>
<ide> .right-feet {
<ide> top: 85%;
<ide> left: 60%;
<ide> tests:
<ide> height: 30%;
<ide> border-radius: 50% 50% 50% 50%;
<ide> transform: rotate(-80deg);
<del> z-index: -2222;
<add> z-index: -2222;
<ide> }
<del>
<add>
<ide> .left-feet {
<ide> top: 85%;
<ide> left: 25%;
<ide> tests:
<ide> height: 30%;
<ide> border-radius: 50% 50% 50% 50%;
<ide> transform: rotate(80deg);
<del> z-index: -2222;
<add> z-index: -2222;
<ide> }
<del>
<add>
<ide> .right-eye {
<ide> top: 45%;
<ide> left: 60%;
<ide> background: black;
<ide> width: 15%;
<ide> height: 17%;
<del> border-radius: 50%;
<add> border-radius: 50%;
<ide> }
<del>
<add>
<ide> .left-eye {
<ide> top: 45%;
<ide> left: 25%;
<ide> background: black;
<ide> width: 15%;
<ide> height: 17%;
<del> border-radius: 50%;
<add> border-radius: 50%;
<ide> }
<del>
<add>
<ide> .sparkle {
<ide> top: 25%;
<ide> left: 15%;
<ide> background: white;
<ide> width: 35%;
<ide> height: 35%;
<del> border-radius: 50%;
<add> border-radius: 50%;
<ide> }
<del>
<add>
<ide> .blush-right {
<ide> top: 65%;
<ide> left: 15%;
<ide> background: pink;
<ide> width: 15%;
<ide> height: 10%;
<del> border-radius: 50%;
<add> border-radius: 50%;
<ide> }
<del>
<add>
<ide> .blush-left {
<ide> top: 65%;
<ide> left: 70%;
<ide> background: pink;
<ide> width: 15%;
<ide> height: 10%;
<del> border-radius: 50%;
<add> border-radius: 50%;
<ide> }
<del>
<add>
<ide> .beak-top {
<ide> top: 60%;
<ide> left: 40%;
<ide> background: orange;
<ide> width: 20%;
<ide> height: 10%;
<del> border-radius: 50%;
<add> border-radius: 50%;
<ide> }
<del>
<add>
<ide> .beak-bottom {
<ide> top: 65%;
<ide> left: 42%;
<ide> background: orange;
<ide> width: 16%;
<ide> height: 10%;
<del> border-radius: 50%;
<add> border-radius: 50%;
<ide> }
<del>
<add>
<ide> body {
<ide> background:#c6faf1;
<ide> }
<del>
<add>
<ide> .penguin * {
<ide> position: absolute;
<ide> }
<ide> tests:
<ide> <div class="beak-bottom"></div>
<ide> </div>
<ide> </div>
<del>
<ide> ```
<ide>
<ide> </div>
<ide> tests:
<ide> ## Solution
<ide> <section id='solution'>
<ide>
<add>
<ide> ```js
<ide> // solution required
<ide> ```
<add>
<ide> </section>
<add>
<ide>\ No newline at end of file
<ide><path>curriculum/challenges/chinese/01-responsive-web-design/basic-css/give-a-background-color-to-a-div-element.chinese.md
<ide> id: bad87fed1348bd9aede07836
<ide> title: Give a Background Color to a div Element
<ide> challengeType: 0
<del>videoUrl: ''
<del>localeTitle: 为div元素提供背景颜色
<add>videoUrl: 'https://scrimba.com/c/cdRKMCk'
<add>forumTopicId: 18190
<add>localTitle: 给 div 元素添加背景色
<ide> ---
<ide>
<ide> ## Description
<del><section id="description">您可以使用<code>background-color</code>属性设置元素的背景颜色。例如,如果您希望元素的背景颜色为<code>green</code> ,则将其放在<code>style</code>元素中: <blockquote> .green-background { <br>背景颜色:绿色; <br> } </blockquote></section>
<add><section id='description'>
<add><code>background-color</code>属性可以设置元素的背景颜色。
<add>例如,你想将一个元素的背景颜色改为<code>green</code>,可以在你的<code>style</code>里面这样写:
<add>
<add>```css
<add>.green-background {
<add> background-color: green;
<add>}
<add>```
<add>
<add></section>
<ide>
<ide> ## Instructions
<del><section id="instructions">创建一个名为<code>silver-background</code>的类, <code>background-color</code>为银色。将此类分配给<code>div</code>元素。 </section>
<add><section id='instructions'>
<add>创建一个<code>silver-background</code>class 并设置<code>background-color</code>为<code>silver</code>。 并用在<code>div</code>元素上。
<add></section>
<ide>
<ide> ## Tests
<ide> <section id='tests'>
<ide>
<ide> ```yml
<ide> tests:
<del> - text: 给你的<code>div</code>元素类<code>silver-background</code> 。
<del> testString: 'assert($("div").hasClass("silver-background"), "Give your <code>div</code> element the class <code>silver-background</code>.");'
<del> - text: 你的<code>div</code>元素应该有银色背景。
<del> testString: 'assert($("div").css("background-color") === "rgb(192, 192, 192)", "Your <code>div</code> element should have a silver background.");'
<del> - text: 定义一个类名为<code>silver-background</code>的内<code>style</code>元素的值赋给<code>silver</code>的<code>background-color</code>属性。
<del> testString: 'assert(code.match(/\.silver-background\s*{\s*background-color:\s*silver;\s*}/), "Define a class named <code>silver-background</code> within the <code>style</code> element and assign the value of <code>silver</code> to the <code>background-color</code> property.");'
<add> - text: '<code>div</code>元素应有<code>silver-background</code> class。'
<add> testString: assert($("div").hasClass("silver-background"), '<code>div</code>元素应有<code>silver-background</code> class。');
<add> - text: '<code>div</code>元素背景颜色应设置为<code>silver</code>。'
<add> testString: assert($("div").css("background-color") === "rgb(192, 192, 192)", '<code>div</code>元素背景颜色应设置为<code>silver</code>。');
<add> - text: 'class 名 <code>silver-background</code> 应该定义在 <code>style</code> 元素内,<code>silver</code> 的值应该指定 <code>background-color</code> 属性'
<add> testString: assert(code.match(/\.silver-background\s*{\s*background-color:\s*silver;\s*}/));
<ide>
<ide> ```
<ide>
<ide> tests:
<ide>
<ide> <h2 class="red-text">CatPhotoApp</h2>
<ide> <main>
<del> <p class="red-text">Click here to view more <a href="#">cat photos</a>.</p>
<add> <p class="red-text">点击查看更多<a href="#">猫图</a>.</p>
<ide>
<del> <a href="#"><img class="smaller-image thick-green-border" src="https://bit.ly/fcc-relaxing-cat" alt="A cute orange cat lying on its back."></a>
<add> <a href="#"><img src="https://bit.ly/fcc-relaxing-cat" alt="一只仰卧着的萌猫" class="smaller-image thick-green-border"></a>
<ide>
<ide> <div>
<del> <p>Things cats love:</p>
<add> <p>猫咪最喜欢的三件东西:</p>
<ide> <ul>
<del> <li>cat nip</li>
<del> <li>laser pointers</li>
<del> <li>lasagna</li>
<add> <li>猫薄荷</li>
<add> <li>激光笔</li>
<add> <li>千层饼</li>
<ide> </ul>
<del> <p>Top 3 things cats hate:</p>
<add> <p>猫咪最讨厌的三件东西:</p>
<ide> <ol>
<del> <li>flea treatment</li>
<del> <li>thunder</li>
<del> <li>other cats</li>
<add> <li>跳蚤</li>
<add> <li>打雷</li>
<add> <li>同类</li>
<ide> </ol>
<ide> </div>
<del>
<add>
<ide> <form action="/submit-cat-photo">
<del> <label><input type="radio" name="indoor-outdoor" checked> Indoor</label>
<del> <label><input type="radio" name="indoor-outdoor"> Outdoor</label><br>
<del> <label><input type="checkbox" name="personality" checked> Loving</label>
<del> <label><input type="checkbox" name="personality"> Lazy</label>
<del> <label><input type="checkbox" name="personality"> Energetic</label><br>
<del> <input type="text" placeholder="cat photo URL" required>
<del> <button type="submit">Submit</button>
<add> <label><input type="radio" name="indoor-outdoor">室内</label>
<add> <label><input type="radio" name="indoor-outdoor">室外</label><br>
<add> <label><input type="checkbox" name="personality">忠诚</label>
<add> <label><input type="checkbox" name="personality">懒惰</label>
<add> <label><input type="checkbox" name="personality">积极</label><br>
<add> <input type="text" placeholder="猫咪图片地址" required>
<add> <button type="submit">提交</button>
<ide> </form>
<ide> </main>
<del>
<ide> ```
<ide>
<ide> </div>
<ide> tests:
<ide> ## Solution
<ide> <section id='solution'>
<ide>
<del>```js
<add>```html
<ide> // solution required
<ide> ```
<add>
<ide> </section>
<add>
<ide>\ No newline at end of file
<ide><path>curriculum/challenges/chinese/01-responsive-web-design/basic-css/import-a-google-font.chinese.md
<ide> id: bad87fee1348bd9aedf08807
<ide> title: Import a Google Font
<ide> challengeType: 0
<del>videoUrl: ''
<del>localeTitle: 导入Google字体
<add>videoUrl: 'https://scrimba.com/c/cM9MRsJ'
<add>forumTopicId: 18200
<add>localTitle: 引入谷歌字体
<ide> ---
<ide>
<ide> ## Description
<del><section id="description">除了指定在大多数操作系统上找到的常用字体外,我们还可以指定在我们的网站上使用的非标准自定义Web字体。互联网上有各种网络字体来源,但在本例中,我们将重点关注Google字体库。 <a href="https://fonts.google.com/" target="_blank">Google字体</a>是一个免费的网络字体库,您可以通过引用字体的URL在CSS中使用它。因此,让我们继续导入并应用Google字体(请注意,如果Google在您所在的国家/地区被屏蔽,则需要跳过此挑战)。要导入Google字体,您可以从Google字体库中复制字体网址,然后将其粘贴到HTML中。对于这个挑战,我们将导入<code>Lobster</code>字体。为此,请复制以下代码段并将其粘贴到代码编辑器的顶部(在开始<code>style</code>元素之前): <code><link href="https://fonts.googleapis.com/css?family=Lobster" rel="stylesheet" type="text/css"></code>现在,您可以使用<code>Lobster</code>作为FAMILY_NAME在CSS中使用<code>Lobster</code>字体,如下例所示: <br> <code>font-family: FAMILY_NAME, GENERIC_NAME;</code> 。 GENERIC_NAME是可选的,如果其他指定的字体不可用,则为后备字体。这将在下一个挑战中得到体现。系列名称区分大小写,如果名称中有空格,则需要用引号括起来。例如,您需要引号才能使用<code>"Open Sans"</code>字体,但不能使用<code>Lobster</code>字体。 </section>
<add><section id='description'>
<add>除了大多数系统提供的默认字体以外,我们也可以使用自定义字体。网络上有各种各样的字体,不过在这个例子中,我们将会尝试使用<code>Google</code>字体库。
<add><a href='https://fonts.google.com/' target='_blank'>Google 字体</a>是一个免费的字体库,可以通过在 CSS 里面设置字体的 URL 来引用。
<add>因此,下一步,我们将引入和使用<code>Google</code>字体。
<add>引入<code>Google</code>字体,你需要复制<code>Google</code>字体的 URL,并粘贴到你的 HTML 里面。在这个挑战中,我们需要引入<code>Lobster</code>字体。因此,请复制以下代码段,并粘贴到代码编辑器顶部,即放到<code>style</code>标签之前。
<add><code><link href="https://fonts.googleapis.com/css?family=Lobster" rel="stylesheet" type="text/css"></code>
<add>现在你可以设置<code>font-family</code>属性为<code>Lobster</code>,来使用<code>Lobster</code>字体。例子如下:<br><code>font-family: FAMILY_NAME, GENERIC_NAME;</code>.
<add><code>GENERIC_NAME</code>是可选的,其他字体不可用时便作为后备字体,在下一个挑战中可以得到体现。
<add>字体名区分大小写,并且如果字体名含有空格,需要用引号括起来。例如,使用<code>"Open Sans"</code>字体需要添加引号,而<code>Lobster</code>字体则不需要。
<add></section>
<ide>
<ide> ## Instructions
<del><section id="instructions">创建使用<code>Lobster</code>字体的<code>font-family</code> CSS规则,并确保它将应用于您的<code>h2</code>元素。 </section>
<add><section id='instructions'>
<add>创建一个 CSS 规则,<code>font-family</code>属性里设置为<code>Lobster</code>字体,并把这个字体应用到所有的<code>h2</code>元素。
<add></section>
<ide>
<ide> ## Tests
<ide> <section id='tests'>
<ide>
<ide> ```yml
<ide> tests:
<del> - text: 导入<code>Lobster</code>字体。
<del> testString: 'assert(new RegExp("googleapis", "gi").test(code), "Import the <code>Lobster</code> font.");'
<del> - text: 你的<code>h2</code>元素应该使用字体<code>Lobster</code> 。
<del> testString: 'assert($("h2").css("font-family").match(/lobster/i), "Your <code>h2</code> element should use the font <code>Lobster</code>.");'
<del> - text: 使用<code>h2</code> CSS选择器更改字体。
<del> testString: 'assert(/\s*h2\s*\{\s*font-family\:\s*(\"|")?Lobster(\"|")?\s*;\s*\}/gi.test(code), "Use an <code>h2</code> CSS selector to change the font.");'
<del> - text: 你的<code>p</code>元素仍然应该使用字体<code>monospace</code> 。
<del> testString: 'assert($("p").css("font-family").match(/monospace/i), "Your <code>p</code> element should still use the font <code>monospace</code>.");'
<add> - text: '引入<code>Lobster</code>字体。'
<add> testString: assert(new RegExp("gdgdocs|googleapis", "gi").test(code), '引入<code>Lobster</code>字体。');
<add> - text: '<code>h2</code>元素必须使用<code>Lobster</code>字体。'
<add> testString: assert($("h2").css("font-family").match(/lobster/i), '<code>h2</code>元素必须使用<code>Lobster</code>字体。');
<add> - text: '使用<code>h2</code>选择器去改变字体样式。'
<add> testString: 'assert(/\s*h2\s*\{\s*font-family\:\s*(\''|")?Lobster(\''|")?\s*;\s*\}/gi.test(code), ''使用<code>h2</code>选择器去改变字体样式。'');'
<add> - text: '<code>p</code>元素应该保持使用<code>monospace</code>字体。'
<add> testString: assert($("p").css("font-family").match(/monospace/i), '<code>p</code>元素应该保持使用<code>monospace</code>字体。');
<ide>
<ide> ```
<ide>
<ide> tests:
<ide>
<ide> <h2 class="red-text">CatPhotoApp</h2>
<ide> <main>
<del> <p class="red-text">Click here to view more <a href="#">cat photos</a>.</p>
<add> <p class="red-text">点击查看更多<a href="#">猫图</a>.</p>
<ide>
<del> <a href="#"><img src="https://bit.ly/fcc-relaxing-cat" alt="A cute orange cat lying on its back."></a>
<add> <a href="#"><img src="https://bit.ly/fcc-relaxing-cat" alt="一只仰卧着的萌猫"></a>
<ide>
<ide> <div>
<del> <p>Things cats love:</p>
<add> <p>猫咪最喜欢的三件东西:</p>
<ide> <ul>
<del> <li>cat nip</li>
<del> <li>laser pointers</li>
<del> <li>lasagna</li>
<add> <li>猫薄荷</li>
<add> <li>激光笔</li>
<add> <li>千层饼</li>
<ide> </ul>
<del> <p>Top 3 things cats hate:</p>
<add> <p>猫咪最讨厌的三件东西:</p>
<ide> <ol>
<del> <li>flea treatment</li>
<del> <li>thunder</li>
<del> <li>other cats</li>
<add> <li>跳蚤</li>
<add> <li>打雷</li>
<add> <li>同类</li>
<ide> </ol>
<ide> </div>
<del>
<add>
<ide> <form action="/submit-cat-photo">
<del> <label><input type="radio" name="indoor-outdoor" checked> Indoor</label>
<del> <label><input type="radio" name="indoor-outdoor"> Outdoor</label><br>
<del> <label><input type="checkbox" name="personality" checked> Loving</label>
<del> <label><input type="checkbox" name="personality"> Lazy</label>
<del> <label><input type="checkbox" name="personality"> Energetic</label><br>
<del> <input type="text" placeholder="cat photo URL" required>
<del> <button type="submit">Submit</button>
<add> <label><input type="radio" name="indoor-outdoor">室内</label>
<add> <label><input type="radio" name="indoor-outdoor">室外</label><br>
<add> <label><input type="checkbox" name="personality">忠诚</label>
<add> <label><input type="checkbox" name="personality">懒惰</label>
<add> <label><input type="checkbox" name="personality">积极</label><br>
<add> <input type="text" placeholder="猫咪图片地址" required>
<add> <button type="submit">提交</button>
<ide> </form>
<ide> </main>
<del>
<ide> ```
<ide>
<ide> </div>
<ide> tests:
<ide> ## Solution
<ide> <section id='solution'>
<ide>
<del>```js
<add>```html
<ide> // solution required
<ide> ```
<add>
<ide> </section>
<add>
<ide>\ No newline at end of file
<ide><path>curriculum/challenges/chinese/01-responsive-web-design/basic-css/improve-compatibility-with-browser-fallbacks.chinese.md
<ide> id: 5b7d72c338cd7e35b63f3e14
<ide> title: Improve Compatibility with Browser Fallbacks
<ide> challengeType: 0
<ide> videoUrl: ''
<del>localeTitle: 改善与浏览器回退的兼容性
<add>forumTopicId: 301087
<add>localTitle: 通过浏览器降级提高兼容性
<ide> ---
<ide>
<ide> ## Description
<del><section id="description">使用CSS时,您可能会在某些时候遇到浏览器兼容性问题。这就是为什么提供浏览器回退以避免潜在问题的重要性。当您的浏览器解析网页的CSS时,它会忽略它无法识别或支持的任何属性。例如,如果使用CSS变量在站点上分配背景颜色,Internet Explorer将忽略背景颜色,因为它不支持CSS变量。在这种情况下,浏览器将使用它对该属性的任何值。如果找不到该属性的任何其他值集,它将恢复为默认值,这通常不理想。这意味着如果您确实希望提供浏览器回退,那么就像在声明之前提供另一个更广泛支持的值一样简单。这样,较旧的浏览器将有一些东西可以依赖,而较新的浏览器只会解释级联后期的任何声明。 </section>
<add><section id='description'>
<add>使用 CSS 时可能会遇到浏览器兼容性问题。提供浏览器降级方案来避免潜在的问题就显得很重要。
<add>当浏览器解析页面的 CSS 时,会自动忽视不能识别或者不支持的属性。举个栗子,如果使用 CSS 变量来指定站点的背景色, IE 浏览器由于不支持 CSS 变量会忽视背景色。因此,浏览器会使用其它值。如果没有找到其它值,会使用默认值,也就是没有背景色。
<add>这意味着如果想提供浏览器降级方案,在声明之前提供另一个更宽泛的值即可。这样老旧的浏览器会降级使用这个方案,新的浏览器会在后面的声明里覆盖降级方案。
<add></section>
<ide>
<ide> ## Instructions
<del><section id="instructions">它看起来像一个变量用于设置<code>.red-box</code>类的背景颜色。让我们通过在现有声明之前添加另一个<code>background</code>声明来提高我们的浏览器兼容性,并将其值设置为红色。 </section>
<add><section id='instructions'>
<add>看来已经使用了变量做为 <code>.red-box</code> class 的背景色。来通过在存在的声明前添加其它的值为 red 的 <code>background</code> 声明来提高浏览器的兼容性。
<add></section>
<ide>
<ide> ## Tests
<ide> <section id='tests'>
<ide>
<ide> ```yml
<ide> tests:
<del> - text: 您的<code>.red-box</code>规则应包括在现有<code>background</code>声明之前立即将<code>background</code>设置为红色的后备。
<del> testString: 'assert(code.match(/.red-box\s*{[^}]*background:\s*(red|#ff0000|#f00|rgb\(\s*255\s*,\s*0\s*,\s*0\s*\)|rgb\(\s*100%\s*,\s*0%\s*,\s*0%\s*\)|hsl\(\s*0\s*,\s*100%\s*,\s*50%\s*\))\s*;\s*background:\s*var\(\s*--red-color\s*\);/gi), "Your <code>.red-box</code> rule should include a fallback with the <code>background</code> set to red immediately before the existing <code>background</code> declaration.");'
<add> - text: '<code>.red-box</code> 应该通过在存在的 <code>background</code> 声明前添加其它的值为 red 的<code>background</code> 来提供降级。'
<add> testString: assert(code.replace(/\s/g, "").match(/\.red-box{background:(red|#ff0000|#f00|rgb\(255,0,0\)|rgb\(100%,0%,0%\)|hsl\(0,100%,50%\));background:var\(--red-color\);height:200px;width:200px;}/gi));
<ide>
<ide> ```
<ide>
<ide> tests:
<ide> }
<ide> </style>
<ide> <div class="red-box"></div>
<del>
<ide> ```
<ide>
<ide> </div>
<ide> tests:
<ide> ## Solution
<ide> <section id='solution'>
<ide>
<del>```js
<del>// solution required
<add>
<add>```html
<add><style>
<add> :root {
<add> --red-color: red;
<add> }
<add> .red-box {
<add> background: red;
<add> background: var(--red-color);
<add> height: 200px;
<add> width:200px;
<add> }
<add></style>
<add><div class="red-box"></div>
<ide> ```
<add>
<ide> </section>
<add><path>curriculum/challenges/chinese/01-responsive-web-design/basic-css/inherit-css-variables.chinese.md
<del><path>curriculum/challenges/chinese/01-responsive-web-design/basic-css/cascading-css-variables.chinese.md
<ide> ---
<ide> id: 5a9d7295424fe3d0e10cad14
<del>title: Cascading CSS variables
<add>title: Inherit CSS Variables
<ide> challengeType: 0
<del>videoUrl: ''
<del>localeTitle: 级联CSS变量
<add>videoUrl: 'https://scrimba.com/c/cyLZZhZ'
<add>forumTopicId: 301088
<add>localTitle: 继承 CSS 变量
<ide> ---
<ide>
<ide> ## Description
<del><section id="description">创建变量时,您可以在创建变量的元素内使用它。它也可以在嵌套在其中的任何元素中使用。这种效应称为<dfn>级联</dfn> 。由于级联,CSS变量通常在<dfn>:root</dfn>元素中定义。 <code>:root</code>是一个<dfn>伪类</dfn>选择器,它匹配文档的根元素,通常是<code></code>元件。通过在<code>:root</code>创建变量,它们将在全局可用,并且可以在样式表中的任何其他选择器中访问。 </section>
<add><section id='description'>
<add>当创建一个变量时,变量会在创建的选择器里可用。同时,在这个选择器的后代里面也是可用的。这是因为 CSS 变量是可继承的,和普通的属性一样。
<add>CSS 变量经常会定义在 <dfn>:root</dfn> 元素内,这样就可被所有选择器继承。<code>:root</code> 是一个 <dfn>pseudo-class</dfn> 选择器匹配文档的根选择器,通常指 <code>html</code> 元素。通过在 <code>:root</code> 里创建变量,变量在全局可用,以及在 style 样式的选择器里也生效。
<add></section>
<ide>
<ide> ## Instructions
<del><section id="instructions">在<code>:root</code>选择器中定义一个名为<code>--penguin-belly</code>的变量,并为其赋值<code>pink</code> 。然后,您可以在任何使用该变量的位置查看该值将如何级联以将值更改为粉红色。 </section>
<add><section id='instructions'>
<add>在 <code>:root</code> 选择器里定义变量 <code>--penguin-belly</code> 并赋值 <code>pink</code>。会发现变量被继承,所有使用该变量的子元素都会有 pink 背景。
<add></section>
<ide>
<ide> ## Tests
<ide> <section id='tests'>
<ide>
<ide> ```yml
<ide> tests:
<del> - text: '在<code>:root</code>声明<code>--penguin-belly</code>变量并将其指定为<code>pink</code> 。'
<del> testString: 'assert(code.match(/:root\s*?{[\s\S]*--penguin-belly\s*?:\s*?pink\s*?;[\s\S]*}/gi), "declare the <code>--penguin-belly</code> variable in the <code>:root</code> and assign it to <code>pink</code>.");'
<add> - text: '应该在 <code>:root</code> 里声明 <code>--penguin-belly</code> 变量并赋值 <code>pink</code>。'
<add> testString: assert(code.match(/:root\s*?{[\s\S]*--penguin-belly\s*?:\s*?pink\s*?;[\s\S]*}/gi));
<ide>
<ide> ```
<ide>
<ide> tests:
<ide> <div class="beak-bottom"></div>
<ide> </div>
<ide> </div>
<del>
<ide> ```
<ide>
<ide> </div>
<ide> tests:
<ide> ## Solution
<ide> <section id='solution'>
<ide>
<add>
<ide> ```js
<del>// solution required
<add>var code = ":root {--penguin-belly: pink;}"
<ide> ```
<add>
<ide> </section>
<ide><path>curriculum/challenges/chinese/01-responsive-web-design/basic-css/inherit-styles-from-the-body-element.chinese.md
<ide> id: bad87fee1348bd9aedf08746
<ide> title: Inherit Styles from the Body Element
<ide> challengeType: 0
<del>videoUrl: ''
<del>localeTitle: 从Body元素继承样式
<add>videoUrl: 'https://scrimba.com/c/c9bmdtR'
<add>forumTopicId: 18204
<add>localTitle: 从 Body 元素继承样式
<ide> ---
<ide>
<ide> ## Description
<del><section id="description">现在我们已经证明每个HTML页面都有一个<code>body</code>元素,并且它的<code>body</code>元素也可以用CSS设置样式。记住,你可以风格你<code>body</code>元素,就像任何其他HTML元素,和所有其他元素将继承你的<code>body</code>元素的样式。 </section>
<add><section id='description'>
<add>我们已经证明每一个 HTML 页面都含有<code>body</code>元素,<code>body</code>元素也可以使用 CSS 样式。
<add>设置<code>body</code>元素的样式的方式跟设置其他 HTML 元素的样式一样,并且其他元素也会继承到<code>body</code>设置的样式。
<add></section>
<ide>
<ide> ## Instructions
<del><section id="instructions">首先,创建一个<code>h1</code>与文本元素<code>Hello World</code>然后,让我们给您的网页上的所有元素的颜色<code>green</code>中加入<code>color: green;</code>你的<code>body</code>元素的风格声明。最后,通过添加<code>font-family: monospace;</code> ,为你的<code>body</code>元素提供<code>monospace</code>的<code>font-family: monospace;</code>你的<code>body</code>元素的风格声明。 </section>
<add><section id='instructions'>
<add>首先,创建一个文本内容为<code>Hello World</code>的<code>h1</code>标签元素。
<add>接着,在<code>body</code>CSS 规则里面添加一句<code>color: green;</code>,改变页面其他元素的字体颜色为<code>green(绿色)</code>。
<add>最后,同样在<code>body</code>CSS 规则里面添加<code>font-family: monospace;</code>,设置其他元素字体为<code>font-family: monospace;</code>。
<add></section>
<ide>
<ide> ## Tests
<ide> <section id='tests'>
<ide>
<ide> ```yml
<ide> tests:
<del> - text: 创建一个<code>h1</code>元素。
<del> testString: 'assert(($("h1").length > 0), "Create an <code>h1</code> element.");'
<del> - text: 你的<code>h1</code>元素应该有文本<code>Hello World</code> 。
<del> testString: 'assert(($("h1").length > 0 && $("h1").text().match(/hello world/i)), "Your <code>h1</code> element should have the text <code>Hello World</code>.");'
<del> - text: 确保您的<code>h1</code>元素具有结束标记。
<del> testString: 'assert(code.match(/<\/h1>/g) && code.match(/<h1/g) && code.match(/<\/h1>/g).length === code.match(/<h1/g).length, "Make sure your <code>h1</code> element has a closing tag.");'
<del> - text: 为你的<code>body</code>元素赋予<code>green</code>的<code>color</code>属性。
<del> testString: 'assert(($("body").css("color") === "rgb(0, 128, 0)"), "Give your <code>body</code> element the <code>color</code> property of <code>green</code>.");'
<del> - text: 为<code>body</code>元素提供<code>monospace</code>的<code>font-family</code>属性。
<del> testString: 'assert(($("body").css("font-family").match(/monospace/i)), "Give your <code>body</code> element the <code>font-family</code> property of <code>monospace</code>.");'
<del> - text: 你的<code>h1</code>元素应该从你的<code>body</code>元素继承font <code>monospace</code> 。
<del> testString: 'assert(($("h1").length > 0 && $("h1").css("font-family").match(/monospace/i)), "Your <code>h1</code> element should inherit the font <code>monospace</code> from your <code>body</code> element.");'
<del> - text: 您的<code>h1</code>元素应该从您的<code>body</code>元素继承绿色。
<del> testString: 'assert(($("h1").length > 0 && $("h1").css("color") === "rgb(0, 128, 0)"), "Your <code>h1</code> element should inherit the color green from your <code>body</code> element.");'
<add> - text: '创建一个<code>h1</code>元素。'
<add> testString: assert(($("h1").length > 0), '创建一个<code>h1</code>元素。');
<add> - text: '<code>h1</code>元素的文本内容应该为<code>Hello World</code>。'
<add> testString: assert(($("h1").length > 0 && $("h1").text().match(/hello world/i)), '<code>h1</code>元素的文本内容应该为<code>Hello World</code>。');
<add> - text: '确保你的<code>h1</code>元素具有结束标记。'
<add> testString: assert(code.match(/<\/h1>/g) && code.match(/<h1/g) && code.match(/<\/h1>/g).length === code.match(/<h1/g).length, '确保你的<code>h1</code>元素具有结束标记。');
<add> - text: '<code>body</code>元素的<code>color</code>属性值应为<code>green</code>。'
<add> testString: assert(($("body").css("color") === "rgb(0, 128, 0)"), '<code>body</code>元素的<code>color</code>属性值应为<code>green</code>。');
<add> - text: '<code>body</code>元素的<code>font-family</code>属性值应为<code>monospace</code>。'
<add> testString: assert(($("body").css("font-family").match(/monospace/i)), '<code>body</code>元素的<code>font-family</code>属性值应为<code>monospace</code>。');
<add> - text: '<code>h1</code>元素应该继承<code>body</code>的<code>monospace</code>字体属性。'
<add> testString: assert(($("h1").length > 0 && $("h1").css("font-family").match(/monospace/i)), '<code>h1</code>元素应该继承<code>body</code>的<code>monospace</code>字体属性。');
<add> - text: '<code>h1</code>元素的字体颜色也应该继承<code>body</code>元素的绿色。'
<add> testString: assert(($("h1").length > 0 && $("h1").css("color") === "rgb(0, 128, 0)"), '<code>h1</code>元素的字体颜色也应该继承<code>body</code>元素的绿色。');
<ide>
<ide> ```
<ide>
<ide> tests:
<ide> }
<ide>
<ide> </style>
<del>
<ide> ```
<ide>
<ide> </div>
<ide> tests:
<ide> ## Solution
<ide> <section id='solution'>
<ide>
<del>```js
<add>```html
<ide> // solution required
<ide> ```
<ide> </section>
<add>
<ide>\ No newline at end of file
<ide><path>curriculum/challenges/chinese/01-responsive-web-design/basic-css/make-circular-images-with-a-border-radius.chinese.md
<ide> id: bad87fee1348bd9aedf08815
<ide> title: Make Circular Images with a border-radius
<ide> challengeType: 0
<del>videoUrl: ''
<del>localeTitle: 使用border-radius制作圆形图像
<add>videoUrl: 'https://scrimba.com/c/c2MvrcB'
<add>forumTopicId: 18229
<add>localTitle: 用 border-radius 制作圆形图片
<ide> ---
<ide>
<ide> ## Description
<del><section id="description">除像素外,您还可以使用百分比指定<code>border-radius</code> 。 </section>
<add><section id='description'>
<add>除像素外,你也可以使用百分比来指定<code>border-radius</code>的值。
<add></section>
<ide>
<ide> ## Instructions
<del><section id="instructions">给你的猫照片<code>border-radius</code>为<code>50%</code> 。 </section>
<add><section id='instructions'>
<add>将<code>border-radius</code>的值设置为<code>50%</code>。
<add></section>
<ide>
<ide> ## Tests
<ide> <section id='tests'>
<ide>
<ide> ```yml
<ide> tests:
<del> - text: 您的图像应具有<code>50%</code>的边框半径,使其完美呈圆形。
<del> testString: 'assert(parseInt($("img").css("border-top-left-radius")) > 48, "Your image should have a border radius of <code>50%</code>, making it perfectly circular.");'
<del> - text: 请务必使用<code>50%</code>的百分比值。
<del> testString: 'assert(code.match(/50%/g), "Be sure to use a percentage value of <code>50%</code>.");'
<add> - text: '你图片的边框圆角应设置为<code>50%</code>,让它看起来就像一个完整的圆。'
<add> testString: assert(parseInt($("img").css("border-top-left-radius")) > 48, '你图片的边框圆角应设置为<code>50%</code>,让它看起来就像一个完整的圆。');
<add> - text: '请确保百分值为<code>50%</code>。'
<add> testString: assert(code.match(/50%/g), '请确保百分值为<code>50%</code>。');
<ide>
<ide> ```
<ide>
<ide> tests:
<ide>
<ide> <h2 class="red-text">CatPhotoApp</h2>
<ide> <main>
<del> <p class="red-text">Click here to view more <a href="#">cat photos</a>.</p>
<add> <p class="red-text">点击查看更多<a href="#">猫图</a>.</p>
<ide>
<del> <a href="#"><img class="smaller-image thick-green-border" src="https://bit.ly/fcc-relaxing-cat" alt="A cute orange cat lying on its back."></a>
<add> <a href="#"><img src="https://bit.ly/fcc-relaxing-cat" alt="一只仰卧着的萌猫" class="smaller-image thick-green-border"></a>
<ide>
<ide> <div>
<del> <p>Things cats love:</p>
<add> <p>猫咪最喜欢的三件东西:</p>
<ide> <ul>
<del> <li>cat nip</li>
<del> <li>laser pointers</li>
<del> <li>lasagna</li>
<add> <li>猫薄荷</li>
<add> <li>激光笔</li>
<add> <li>千层饼</li>
<ide> </ul>
<del> <p>Top 3 things cats hate:</p>
<add> <p>猫咪最讨厌的三件东西:</p>
<ide> <ol>
<del> <li>flea treatment</li>
<del> <li>thunder</li>
<del> <li>other cats</li>
<add> <li>跳蚤</li>
<add> <li>打雷</li>
<add> <li>同类</li>
<ide> </ol>
<ide> </div>
<del>
<add>
<ide> <form action="/submit-cat-photo">
<del> <label><input type="radio" name="indoor-outdoor" checked> Indoor</label>
<del> <label><input type="radio" name="indoor-outdoor"> Outdoor</label><br>
<del> <label><input type="checkbox" name="personality" checked> Loving</label>
<del> <label><input type="checkbox" name="personality"> Lazy</label>
<del> <label><input type="checkbox" name="personality"> Energetic</label><br>
<del> <input type="text" placeholder="cat photo URL" required>
<del> <button type="submit">Submit</button>
<add> <label><input type="radio" name="indoor-outdoor">室内</label>
<add> <label><input type="radio" name="indoor-outdoor">室外</label><br>
<add> <label><input type="checkbox" name="personality">忠诚</label>
<add> <label><input type="checkbox" name="personality">懒惰</label>
<add> <label><input type="checkbox" name="personality">积极</label><br>
<add> <input type="text" placeholder="猫咪图片地址" required>
<add> <button type="submit">提交</button>
<ide> </form>
<ide> </main>
<del>
<ide> ```
<ide>
<ide> </div>
<ide> tests:
<ide> ## Solution
<ide> <section id='solution'>
<ide>
<del>```js
<add>```html
<ide> // solution required
<ide> ```
<add>
<ide> </section>
<add>
<ide>\ No newline at end of file
<ide><path>curriculum/challenges/chinese/01-responsive-web-design/basic-css/override-all-other-styles-by-using-important.chinese.md
<ide> id: bad87fee1348bd9aedf07756
<ide> title: Override All Other Styles by using Important
<ide> challengeType: 0
<del>videoUrl: ''
<del>localeTitle: 使用重要覆盖所有其他样式
<add>videoUrl: 'https://scrimba.com/c/cm24rcp'
<add>forumTopicId: 18249
<add>localTitle: Important 的优先级最高
<ide> ---
<ide>
<ide> ## Description
<del><section id="description">好极了!我们刚刚证明了内联样式将覆盖<code>style</code>元素中的所有CSS声明。可是等等。有一种覆盖CSS的最后一种方法。这是所有人中最强大的方法。但在我们这样做之前,让我们谈谈为什么你想要覆盖CSS。在许多情况下,您将使用CSS库。这些可能会意外地覆盖您自己的CSS。所以当你绝对需要确定一个元素有特定的CSS时,你可以使用<code>!important</code>让我们一直回到我们的<code>pink-text</code>类声明。请记住,我们的<code>pink-text</code>类被后续的类声明,id声明和内联样式覆盖。 </section>
<add><section id='description'>
<add>耶!我们刚刚又证明了行内样式会覆盖<code>style</code>标签里面所有的 CSS 声明。
<add>不过,还有一种方式可以覆盖重新 CSS 样式。这是所有方法里面最强大的一个。在此之前,我们要考虑清楚,为什么我们需要覆盖 CSS 样式。
<add>在很多时候,你使用 CSS 库,有时候它们声明的样式会意外的覆盖你的 CSS 样式。当你需要保证你的 CSS 样式不受影响,你可以使用<code>!important</code>。
<add>让我们回到<code>pink-text</code>class 声明之中,它已经被随其后的 class 声明,id 声明,以及行内样式所覆盖。
<add></section>
<ide>
<ide> ## Instructions
<del><section id="instructions">让我们在粉红色文本元素的颜色声明中添加关键字<code>!important</code> ,以100%确定你的<code>h1</code>元素是粉红色的。如何执行此操作的示例是: <code>color: red !important;</code> </section>
<add><section id='instructions'>
<add>
<add>在<code>pink-text</code>class 的<code>color</code>声明里面使用<code>!important</code>关键字,去确保<code>h1</code>元素的字体颜色一定为粉色。
<add>操作的方法大概如下:
<add><code>color: red !important;</code>
<add></section>
<ide>
<ide> ## Tests
<ide> <section id='tests'>
<ide>
<ide> ```yml
<ide> tests:
<del> - text: 您的<code>h1</code>元素应该具有<code>pink-text</code>类。
<del> testString: 'assert($("h1").hasClass("pink-text"), "Your <code>h1</code> element should have the class <code>pink-text</code>.");'
<del> - text: 你的<code>h1</code>元素应该有<code>blue-text</code> 。
<del> testString: 'assert($("h1").hasClass("blue-text"), "Your <code>h1</code> element should have the class <code>blue-text</code>.");'
<del> - text: 您的<code>h1</code>元素应具有<code>orange-text</code>的ID。
<del> testString: 'assert($("h1").attr("id") === "orange-text", "Your <code>h1</code> element should have the id of <code>orange-text</code>.");'
<del> - text: '您的<code>h1</code>元素应具有内联样式的<code>color: white</code> 。'
<del> testString: 'assert(code.match(/<h1.*style/gi) && code.match(/<h1.*style.*color\s*?:/gi), "Your <code>h1</code> element should have the inline style of <code>color: white</code>.");'
<del> - text: 你的<code>pink-text</code>类声明应该有<code>!important</code>关键字来覆盖所有其他声明。
<del> testString: 'assert(code.match(/\.pink-text\s*?\{[\s\S]*?color:.*pink.*!important\s*;?[^\.]*\}/g), "Your <code>pink-text</code> class declaration should have the <code>!important</code> keyword to override all other declarations.");'
<del> - text: 你的<code>h1</code>元素应该是粉红色的。
<del> testString: 'assert($("h1").css("color") === "rgb(255, 192, 203)", "Your <code>h1</code> element should be pink.");'
<add> - text: '<code>h1</code>元素应该包含<code>pink-text</code> class。'
<add> testString: assert($("h1").hasClass("pink-text"), '<code>h1</code>元素应该包含<code>pink-text</code> class。');
<add> - text: '<code>h1</code>元素应该包含<code>blue-text</code> class。'
<add> testString: assert($("h1").hasClass("blue-text"), '<code>h1</code>元素应该包含<code>blue-text</code> class。');
<add> - text: '<code>h1</code>元素应该包含一个名为<code>orange-text</code>的id。'
<add> testString: assert($("h1").attr("id") === "orange-text", '<code>h1</code>元素应该包含一个名为<code>orange-text</code>的id。');
<add> - text: '<code>h1</code>元素应该包含<code>color: white</code>的行内样式声明。'
<add> testString: 'assert(code.match(/<h1.*style/gi) && code.match(/<h1.*style.*color\s*?:/gi), ''<code>h1</code>元素应该包含<code>color: white</code>的行内样式声明。'');'
<add> - text: '<code>pink-text</code> class 声明应该含有<code>!important</code>关键字。'
<add> testString: 'assert(code.match(/\.pink-text\s*?\{[\s\S]*?color:.*pink.*!important\s*;?[^\.]*\}/g), ''<code>pink-text</code> class 声明应该含有<code>!important</code>关键字。'');'
<add> - text: '<code>h1</code>元素的字体颜色应该为粉色。'
<add> testString: assert($("h1").css("color") === "rgb(255, 192, 203)", '<code>h1</code>元素的字体颜色应该为粉色。');
<ide>
<ide> ```
<ide>
<ide> tests:
<ide> }
<ide> </style>
<ide> <h1 id="orange-text" class="pink-text blue-text" style="color: white">Hello World!</h1>
<del>
<ide> ```
<ide>
<ide> </div>
<ide> tests:
<ide> ## Solution
<ide> <section id='solution'>
<ide>
<del>```js
<add>```html
<ide> // solution required
<ide> ```
<add>
<ide> </section>
<add>
<ide>\ No newline at end of file
<ide><path>curriculum/challenges/chinese/01-responsive-web-design/basic-css/override-class-declarations-by-styling-id-attributes.chinese.md
<ide> id: bad87fee1348bd8aedf06756
<ide> title: Override Class Declarations by Styling ID Attributes
<ide> challengeType: 0
<del>videoUrl: ''
<del>localeTitle: 通过样式ID属性覆盖类声明
<add>videoUrl: 'https://scrimba.com/c/cRkpDhB'
<add>forumTopicId: 18251
<add>localTitle: ID 选择器优先级高于 Class 选择器
<ide> ---
<ide>
<ide> ## Description
<del><section id="description">我们刚刚证明了浏览器从上到下读取CSS。这意味着,如果发生冲突,浏览器将使用最后的CSS声明。但我们还没有完成。还有其他方法可以覆盖CSS。你还记得id属性吗?让我们覆盖你的<code>pink-text</code>和<code>blue-text</code>类,并通过给<code>h1</code>元素一个id然后设置那个id样式,使你的<code>h1</code>元素变成橙色。 </section>
<add><section id='description'>
<add>我们刚刚证明了浏览器读取 CSS 是由上到下的。这就意味着,如果发生冲突,浏览器将会应用最后声明的样式。
<add>不过我们还没结束,还有其他方法来覆盖 CSS 样式。你还记得 id 属性吗?
<add>通过给<code>h1</code>元素添加 id 属性,来覆盖 class 属性定义的同名样式。
<add></section>
<ide>
<ide> ## Instructions
<del><section id="instructions">为你的<code>h1</code>元素提供<code>orange-text</code>的<code>id</code>属性。请记住,id样式如下所示: <code><h1 id="orange-text"></code>在<code>h1</code>元素上保留<code>blue-text</code>和<code>pink-text</code>类。在<code>style</code>元素中为您的<code>orange-text</code> id创建一个CSS声明。这是一个示例: <blockquote> #brown-text { <br>颜色:棕色; <br> } </blockquote>注意:无论您是在粉红色文本类之上还是之下声明此CSS都无关紧要,因为id属性始终优先。 </section>
<add><section id='instructions'>
<add>给<code>h1</code>元素添加 id 属性,属性值为<code>orange-text</code>。设置方式如下:
<add><code><h1 id="orange-text"></code>
<add><code>h1</code>元素继续保留<code>blue-text</code>和<code>pink-text</code>class。
<add>在<code>style</code>元素中创建名为<code>orange-text</code>的 id 选择器。例子如下:
<add>
<add>```css
<add>#brown-text {
<add> color: brown;
<add>}
<add>```
<add>
<add>注意:无论在<code>pink-text</code>class 的上面或者下面声明,id 选择器的优先级总是会高于 class 选择器。
<add></section>
<ide>
<ide> ## Tests
<ide> <section id='tests'>
<ide>
<ide> ```yml
<ide> tests:
<del> - text: 您的<code>h1</code>元素应该具有<code>pink-text</code>类。
<del> testString: 'assert($("h1").hasClass("pink-text"), "Your <code>h1</code> element should have the class <code>pink-text</code>.");'
<del> - text: 你的<code>h1</code>元素应该有<code>blue-text</code> 。
<del> testString: 'assert($("h1").hasClass("blue-text"), "Your <code>h1</code> element should have the class <code>blue-text</code>.");'
<del> - text: 为你的<code>h1</code>元素提供<code>orange-text</code>的id。
<del> testString: 'assert($("h1").attr("id") === "orange-text", "Give your <code>h1</code> element the id of <code>orange-text</code>.");'
<del> - text: 应该只有一个<code>h1</code>元素。
<del> testString: 'assert(($("h1").length === 1), "There should be only one <code>h1</code> element.");'
<del> - text: 为您的<code>orange-text</code> ID创建一个CSS声明
<del> testString: 'assert(code.match(/#orange-text\s*{/gi), "Create a CSS declaration for your <code>orange-text</code> id");'
<del> - text: 不要给你的<code>h1</code>任何<code>style</code>属性。
<del> testString: 'assert(!code.match(/<h1.*style.*>/gi), "Do not give your <code>h1</code> any <code>style</code> attributes.");'
<del> - text: 你的<code>h1</code>元素应该是橙色的。
<del> testString: 'assert($("h1").css("color") === "rgb(255, 165, 0)", "Your <code>h1</code> element should be orange.");'
<add> - text: '<code>h1</code>元素应该包含<code>pink-text</code> class。'
<add> testString: assert($("h1").hasClass("pink-text"), '<code>h1</code>元素应该包含<code>pink-text</code> class。');
<add> - text: '<code>h1</code>元素应该包含<code>blue-text</code> class。'
<add> testString: assert($("h1").hasClass("blue-text"), '<code>h1</code>元素应该包含<code>blue-text</code> class。');
<add> - text: '<code>h1</code>的 id 属性值为<code>orange-text</code>。'
<add> testString: assert($("h1").attr("id") === "orange-text", '<code>h1</code>的 id 属性值为<code>orange-text</code>。');
<add> - text: '应该只有一个<code>h1</code>元素。'
<add> testString: assert(($("h1").length === 1), '应该只有一个<code>h1</code>元素。');
<add> - text: '创建名为<code>orange-text</code>的 id 选择器。'
<add> testString: assert(code.match(/#orange-text\s*{/gi), '创建名为<code>orange-text</code>的 id 选择器。');
<add> - text: '不要在<code>h1</code>元素里面使用<code>style(行内样式)</code>。'
<add> testString: assert(!code.match(/<h1.*style.*>/gi), '不要在<code>h1</code>元素里面使用<code>style(行内样式)</code>。');
<add> - text: '<code>h1</code>元素的字体颜色应为橘色。'
<add> testString: assert($("h1").css("color") === "rgb(255, 165, 0)", '<code>h1</code>元素的字体颜色应为橘色。');
<ide>
<ide> ```
<ide>
<ide> tests:
<ide> }
<ide> </style>
<ide> <h1 class="pink-text blue-text">Hello World!</h1>
<del>
<ide> ```
<ide>
<ide> </div>
<ide> tests:
<ide> ## Solution
<ide> <section id='solution'>
<ide>
<del>```js
<add>```html
<ide> // solution required
<ide> ```
<add>
<ide> </section>
<add>
<ide>\ No newline at end of file
<ide><path>curriculum/challenges/chinese/01-responsive-web-design/basic-css/override-class-declarations-with-inline-styles.chinese.md
<ide> id: bad87fee1348bd9aedf06756
<ide> title: Override Class Declarations with Inline Styles
<ide> challengeType: 0
<del>videoUrl: ''
<del>localeTitle: 使用内联样式覆盖类声明
<add>videoUrl: 'https://scrimba.com/c/cGJDRha'
<add>forumTopicId: 18252
<add>localTitle: 内联样式的优先级高于 ID 选择器
<ide> ---
<ide>
<ide> ## Description
<del><section id="description">所以我们已经证明了id声明覆盖了类声明,无论它们在<code>style</code>元素CSS中的声明位置如何。还有其他方法可以覆盖CSS。你还记得内联样式吗? </section>
<add><section id='description'>
<add>我们刚刚证明了,id 选择器无论在<code>style</code>标签哪里声明,都会覆盖 class 声明的样式,
<add>其实还有其他方法可以覆盖重写 CSS 样式。你还记得行内样式吗?
<add></section>
<ide>
<ide> ## Instructions
<del><section id="instructions">使用<code>inline style</code>尝试使我们的<code>h1</code>元素变白。请记住,在线条样式中如下所示: <code><h1 style="color: green;"></code>在<code>h1</code>元素上保留<code>blue-text</code>和<code>pink-text</code>类。 </section>
<add><section id='instructions'>
<add>使用行内样式尝试让<code>h1</code>的字体颜色变白。像下面这样使用:
<add><code><h1 style="color: green"></code>
<add>你的<code>h1</code>元素需继续保留<code>blue-text</code>和<code>pink-text</code>class。
<add></section>
<ide>
<ide> ## Tests
<ide> <section id='tests'>
<ide>
<ide> ```yml
<ide> tests:
<del> - text: 您的<code>h1</code>元素应该具有<code>pink-text</code>类。
<del> testString: 'assert($("h1").hasClass("pink-text"), "Your <code>h1</code> element should have the class <code>pink-text</code>.");'
<del> - text: 你的<code>h1</code>元素应该有<code>blue-text</code> 。
<del> testString: 'assert($("h1").hasClass("blue-text"), "Your <code>h1</code> element should have the class <code>blue-text</code>.");'
<del> - text: 您的<code>h1</code>元素应具有<code>orange-text</code>的ID。
<del> testString: 'assert($("h1").attr("id") === "orange-text", "Your <code>h1</code> element should have the id of <code>orange-text</code>.");'
<del> - text: 为您的<code>h1</code>元素提供内联样式。
<del> testString: 'assert(document.querySelector("h1[style]"), "Give your <code>h1</code> element an inline style.");'
<del> - text: 你的<code>h1</code>元素应该是白色的。
<del> testString: 'assert($("h1").css("color") === "rgb(255, 255, 255)", "Your <code>h1</code> element should be white.");'
<add> - text: '<code>h1</code>元素应该包含<code>pink-text</code> class。'
<add> testString: assert($("h1").hasClass("pink-text"), '<code>h1</code>元素应该包含<code>pink-text</code> class。');
<add> - text: '<code>h1</code>元素应该包含<code>blue-text</code> class。'
<add> testString: assert($("h1").hasClass("blue-text"), '<code>h1</code>元素应该包含<code>blue-text</code> class。');
<add> - text: '<code>h1</code>元素应该包含一个名为<code>orange-text</code>的id。'
<add> testString: assert($("h1").attr("id") === "orange-text", '<code>h1</code>元素应该包含一个名为<code>orange-text</code>的id。');
<add> - text: '<code>h1</code>元素应该含有行内样式。'
<add> testString: assert(document.querySelector('h1[style]'), '<code>h1</code>元素应该含有行内样式。');
<add> - text: '<code>h1</code>元素的字体颜色应该为白色。'
<add> testString: assert($("h1").css("color") === "rgb(255, 255, 255)", '<code>h1</code>元素的字体颜色应该为白色。');
<ide>
<ide> ```
<ide>
<ide> tests:
<ide> }
<ide> </style>
<ide> <h1 id="orange-text" class="pink-text blue-text">Hello World!</h1>
<del>
<ide> ```
<ide>
<ide> </div>
<ide> tests:
<ide> ## Solution
<ide> <section id='solution'>
<ide>
<del>```js
<add>```html
<ide> // solution required
<ide> ```
<add>
<ide> </section>
<add>
<ide>\ No newline at end of file
<ide><path>curriculum/challenges/chinese/01-responsive-web-design/basic-css/override-styles-in-subsequent-css.chinese.md
<ide> id: bad87fee1348bd9aedf04756
<ide> title: Override Styles in Subsequent CSS
<ide> challengeType: 0
<del>videoUrl: ''
<del>localeTitle: 覆盖后续CSS中的样式
<add>videoUrl: 'https://scrimba.com/c/cGJDQug'
<add>forumTopicId: 18253
<add>localTitle: Class 选择器的优先级高于继承样式
<ide> ---
<ide>
<ide> ## Description
<del><section id="description">我们的“粉红色文本”类覆盖了我们的<code>body</code>元素的CSS声明!我们刚刚证明我们的类将覆盖<code>body</code>元素的CSS。所以下一个合乎逻辑的问题是,我们可以做些什么来覆盖我们的<code>pink-text</code>类? </section>
<add><section id='description'>
<add>"pink-text" class 覆盖了<code>body</code>元素的 CSS 声明。
<add>我们刚刚证明了我们的 class 会覆盖<code>body</code>的 CSS 样式。那么,下一个问题是,我们要怎么样才能覆盖我们的<code>pink-text</code>class?
<add></section>
<ide>
<ide> ## Instructions
<del><section id="instructions">创建一个名为<code>blue-text</code>的附加CSS类,它为元素提供蓝色。确保它低于<code>pink-text</code>类声明。除了<code>pink-text</code>类之外,将<code>blue-text</code>类应用于<code>h1</code>元素,让我们看看哪个获胜。将多个类属性应用于HTML元素是通过它们之间的空格完成的,如下所示: <code>class="class1 class2"</code>注意:HTML元素中列出的类的顺序无关紧要。但是, <code><style></code>部分中的<code>class</code>声明的顺序是重要的。第二个声明将始终优先于第一个声明。因为<code>.blue-text</code>被声明为第二个,所以它会覆盖<code>.pink-text</code>的属性</section>
<add><section id='instructions'>
<add>创建一个字体颜色为<code>blue</code>的<code>blue-text</code>CSS class,并确保它在<code>pink-text</code>下方声明。
<add>在含有<code>pink-text</code>class 的<code>h1</code>元素里面,再添加一个<code>blue-text</code>class,这时候,我们将能看到到底是谁获胜。
<add>HTML 同时应用多个 class 属性需以空格来间隔,例子如下:
<add><code>class="class1 class2"</code>
<add>注意:HTML 元素里应用的 class 的先后顺序无关紧要。
<add>但是,在<code><style></code>标签里面声明的<code>class</code>顺序十分重要。第二个声明始终优于第一个声明。因为<code>.blue-text</code>在<code>.pink-text</code>的后面声明,所以<code>.blue-text</code>会覆盖<code>.pink-text</code>的样式。
<add></section>
<ide>
<ide> ## Tests
<ide> <section id='tests'>
<ide>
<ide> ```yml
<ide> tests:
<del> - text: 您的<code>h1</code>元素应该具有<code>pink-text</code>类。
<del> testString: 'assert($("h1").hasClass("pink-text"), "Your <code>h1</code> element should have the class <code>pink-text</code>.");'
<del> - text: 你的<code>h1</code>元素应该有<code>blue-text</code> 。
<del> testString: 'assert($("h1").hasClass("blue-text"), "Your <code>h1</code> element should have the class <code>blue-text</code>.");'
<del> - text: <code>blue-text</code>和<code>pink-text</code>都应属于同一个<code>h1</code>元素。
<del> testString: 'assert($(".pink-text").hasClass("blue-text"), "Both <code>blue-text</code> and <code>pink-text</code> should belong to the same <code>h1</code> element.");'
<del> - text: 你的<code>h1</code>元素应该是蓝色的。
<del> testString: 'assert($("h1").css("color") === "rgb(0, 0, 255)", "Your <code>h1</code> element should be blue.");'
<add> - text: '<code>h1</code>元素应该包含<code>pink-text</code> class。'
<add> testString: assert($("h1").hasClass("pink-text"), '<code>h1</code>元素应该包含<code>pink-text</code> class。');
<add> - text: '<code>h1</code>元素应该包含<code>blue-text</code> class。'
<add> testString: assert($("h1").hasClass("blue-text"), '<code>h1</code>元素应该包含<code>blue-text</code> class。');
<add> - text: '<code>blue-text</code>和<code>pink-text</code>需同时应用于<code>h1</code>元素上。'
<add> testString: assert($(".pink-text").hasClass("blue-text"), '<code>blue-text</code>和<code>pink-text</code>需同时应用于<code>h1</code>元素上。');
<add> - text: '<code>h1</code>元素的颜色应为蓝色。'
<add> testString: assert($("h1").css("color") === "rgb(0, 0, 255)", '<code>h1</code>元素的颜色应为蓝色。');
<ide>
<ide> ```
<ide>
<ide> tests:
<ide> }
<ide> </style>
<ide> <h1 class="pink-text">Hello World!</h1>
<del>
<ide> ```
<ide>
<ide> </div>
<ide> tests:
<ide> ## Solution
<ide> <section id='solution'>
<ide>
<del>```js
<add>```html
<ide> // solution required
<ide> ```
<add>
<ide> </section>
<add>
<ide>\ No newline at end of file
<ide><path>curriculum/challenges/chinese/01-responsive-web-design/basic-css/prioritize-one-style-over-another.chinese.md
<ide> id: bad87fee1348bd9aedf08756
<ide> title: Prioritize One Style Over Another
<ide> challengeType: 0
<del>videoUrl: ''
<del>localeTitle: 将一种风格优先于另一种风格
<add>videoUrl: 'https://scrimba.com/c/cZ8wnHv'
<add>forumTopicId: 18258
<add>localTitle: 样式中的优先级
<ide> ---
<ide>
<ide> ## Description
<del><section id="description">有时,您的HTML元素将收到多个彼此冲突的样式。例如,您的<code>h1</code>元素不能同时为绿色和粉红色。让我们看看当我们创建一个使文本变为粉红色的类,然后将其应用于元素时会发生什么。我们的类<em>会覆盖</em> <code>body</code>元素的<code>color: green;</code> CSS属性? </section>
<add><section id='description'>
<add>有时候,你的 HTML 元素的样式会跟其他样式发生冲突。
<add>就像,你的<code>h1</code>元素也不能同时设置<code>green</code>和<code>pink</code>两种样式。
<add>让我们尝试创建一个字体颜色为<code>pink</code>的 class,并应于用其中一个元素中。猜一猜,它会覆盖<code>body</code>元素设置的<code>color: green;</code>CSS 属性吗?
<add></section>
<ide>
<ide> ## Instructions
<del><section id="instructions">创建一个名为<code>pink-text</code>的CSS类,它为元素提供粉红色。为你的<code>h1</code>元素提供<code>pink-text</code>类。 </section>
<add><section id='instructions'>
<add>创建一个能将元素的字体颜色改为<code>pink</code>的CSS class,并起名为<code>pink-text</code>。
<add>给你的<code>h1</code>元素添加<code>pink-text</code>class。
<add></section>
<ide>
<ide> ## Tests
<ide> <section id='tests'>
<ide>
<ide> ```yml
<ide> tests:
<del> - text: 您的<code>h1</code>元素应该具有<code>pink-text</code>类。
<del> testString: 'assert($("h1").hasClass("pink-text"), "Your <code>h1</code> element should have the class <code>pink-text</code>.");'
<del> - text: 你的<code><style></code>应该有一个改变<code>color</code>的<code>pink-text</code> CSS类。
<del> testString: 'assert(code.match(/\.pink-text\s*\{\s*color\s*:\s*.+\s*;\s*\}/g), "Your <code><style></code> should have a <code>pink-text</code> CSS class that changes the <code>color</code>.");'
<del> - text: 你的<code>h1</code>元素应该是粉红色的。
<del> testString: 'assert($("h1").css("color") === "rgb(255, 192, 203)", "Your <code>h1</code> element should be pink.");'
<add> - text: '<code>h1</code>元素应该含有<code>pink-text</code> class。'
<add> testString: assert($("h1").hasClass("pink-text"), '<code>h1</code>元素应该含有<code>pink-text</code> class。');
<add> - text: '<code><style></code>标签应该含有一个可以改变字体颜色的<code>pink-text</code> class。'
<add> testString: 'assert(code.match(/\.pink-text\s*\{\s*color\s*:\s*.+\s*;\s*\}/g), ''<code><style></code>标签应该含有一个可以改变字体颜色的<code>pink-text</code> class。'');'
<add> - text: '<code>h1</code>元素的字体颜色应该为<code>pink(粉色)</code>。'
<add> testString: assert($("h1").css("color") === "rgb(255, 192, 203)", '<code>h1</code>元素的字体颜色应该为<code>pink(粉色)</code>。');
<ide>
<ide> ```
<ide>
<ide> tests:
<ide> }
<ide> </style>
<ide> <h1>Hello World!</h1>
<del>
<ide> ```
<ide>
<ide> </div>
<ide> tests:
<ide> ```js
<ide> // solution required
<ide> ```
<add>
<ide> </section>
<add>
<ide>\ No newline at end of file
<ide><path>curriculum/challenges/chinese/01-responsive-web-design/basic-css/set-the-font-family-of-an-element.chinese.md
<ide> id: bad87fee1348bd9aede08807
<ide> title: Set the Font Family of an Element
<ide> challengeType: 0
<del>videoUrl: ''
<del>localeTitle: 设置元素的字体系列
<add>videoUrl: 'https://scrimba.com/c/c3bvpCg'
<add>forumTopicId: 18278
<add>localTitle: 设置元素的字体家族
<ide> ---
<ide>
<ide> ## Description
<del><section id="description">您可以使用<code>font-family</code>属性设置元素应使用的<code>font-family</code> 。例如,如果要将<code>h2</code>元素的字体设置为<code>sans-serif</code> ,则可以使用以下CSS: <blockquote> h2 { <br> font-family:sans-serif; <br> } </blockquote></section>
<add><section id='description'>
<add>通过<code>font-family</code>属性,可以设置元素里面的字体样式。
<add>如果你想设置<code>h2</code>元素的字体为<code>sans-serif</code>,你可以用以下的 CSS 规则:
<add>
<add>```css
<add>h2 {
<add> font-family: sans-serif;
<add>}
<add>```
<add>
<add></section>
<ide>
<ide> ## Instructions
<del><section id="instructions">使所有<code>p</code>元素都使用<code>monospace</code>字体。 </section>
<add><section id='instructions'>
<add>确保<code>p</code>元素使用<code>monospace</code>字体。
<add></section>
<ide>
<ide> ## Tests
<ide> <section id='tests'>
<ide>
<ide> ```yml
<ide> tests:
<del> - text: 你的<code>p</code>元素应该使用字体<code>monospace</code> 。
<del> testString: 'assert($("p").not(".red-text").css("font-family").match(/monospace/i), "Your <code>p</code> elements should use the font <code>monospace</code>.");'
<add> - text: '<code>p</code>元素应该使用<code>monospace</code>字体。'
<add> testString: assert($("p").not(".red-text").css("font-family").match(/monospace/i), '<code>p</code>元素应该使用<code>monospace</code>字体。');
<ide>
<ide> ```
<ide>
<ide> tests:
<ide>
<ide> <h2 class="red-text">CatPhotoApp</h2>
<ide> <main>
<del> <p class="red-text">Click here to view more <a href="#">cat photos</a>.</p>
<del>
<del> <a href="#"><img src="https://bit.ly/fcc-relaxing-cat" alt="A cute orange cat lying on its back."></a>
<del>
<add><p class="red-text">点击查看更多<a href="#">猫图</a>.</p>
<add>
<add> <a href="#"><img src="https://bit.ly/fcc-relaxing-cat" alt="一只仰卧着的萌猫"></a>
<add>
<ide> <div>
<del> <p>Things cats love:</p>
<add> <p>猫咪最喜欢的三件东西:</p>
<ide> <ul>
<del> <li>cat nip</li>
<del> <li>laser pointers</li>
<del> <li>lasagna</li>
<add> <li>猫薄荷</li>
<add> <li>激光笔</li>
<add> <li>千层饼</li>
<ide> </ul>
<del> <p>Top 3 things cats hate:</p>
<add> <p>猫咪最讨厌的三件东西:</p>
<ide> <ol>
<del> <li>flea treatment</li>
<del> <li>thunder</li>
<del> <li>other cats</li>
<add> <li>跳蚤</li>
<add> <li>打雷</li>
<add> <li>同类</li>
<ide> </ol>
<ide> </div>
<del>
<add>
<ide> <form action="/submit-cat-photo">
<del> <label><input type="radio" name="indoor-outdoor" checked> Indoor</label>
<del> <label><input type="radio" name="indoor-outdoor"> Outdoor</label><br>
<del> <label><input type="checkbox" name="personality" checked> Loving</label>
<del> <label><input type="checkbox" name="personality"> Lazy</label>
<del> <label><input type="checkbox" name="personality"> Energetic</label><br>
<del> <input type="text" placeholder="cat photo URL" required>
<del> <button type="submit">Submit</button>
<add> <label><input type="radio" name="indoor-outdoor">室内</label>
<add> <label><input type="radio" name="indoor-outdoor">室外</label><br>
<add> <label><input type="checkbox" name="personality">忠诚</label>
<add> <label><input type="checkbox" name="personality">懒惰</label>
<add> <label><input type="checkbox" name="personality">积极</label><br>
<add> <input type="text" placeholder="猫咪图片地址" required>
<add> <button type="submit">提交</button>
<ide> </form>
<ide> </main>
<del>
<ide> ```
<ide>
<ide> </div>
<ide> tests:
<ide> ## Solution
<ide> <section id='solution'>
<ide>
<del>```js
<add>```html
<ide> // solution required
<ide> ```
<add>
<ide> </section>
<add>
<ide>\ No newline at end of file
<ide><path>curriculum/challenges/chinese/01-responsive-web-design/basic-css/set-the-id-of-an-element.chinese.md
<ide> id: bad87eee1348bd9aede07836
<ide> title: Set the id of an Element
<ide> challengeType: 0
<del>videoUrl: ''
<del>localeTitle: 设置元素的id
<add>videoUrl: 'https://scrimba.com/c/cN6MEc2'
<add>forumTopicId: 18279
<add>localTitle: 设置元素的 id
<ide> ---
<ide>
<ide> ## Description
<del><section id="description">除了类之外,每个HTML元素还可以具有<code>id</code>属性。使用<code>id</code>属性有几个好处:您可以使用<code>id</code>来设置单个元素的样式,稍后您将学习如何使用它来使用JavaScript选择和修改特定元素。 <code>id</code>属性应该是唯一的。浏览器不会强制执行此操作,但这是广泛认可的最佳实践。所以请不要给多个元素赋予相同的<code>id</code>属性。这里有一个例子,说明如何为你的<code>h2</code>元素提供<code>cat-photo-app</code> <code><h2 id="cat-photo-app"></code> : <code><h2 id="cat-photo-app"></code> </section>
<add><section id='description'>
<add>除了class属性,每一个 HTML 元素也都有<code>id</code>属性。
<add>使用<code>id</code>有几个好处:你可以通过<code>id</code>选择器来改变单个元素的样式,稍后的课程中,你也会了解到在 JavaScript 里面,可以通过<code>id</code>来选择元素和操作元素。
<add><code>id</code>属性应是唯一的。浏览器不强迫执行这规范,但是这是广泛认可的最佳实践。所以,请不要给多个元素设置相同的<code>id</code>属性。
<add>设置<code>h2</code>元素的 id 为<code>cat-photo-app</code>的方法如下:
<add><code><h2 id="cat-photo-app"></code>
<add></section>
<ide>
<ide> ## Instructions
<del><section id="instructions">为<code>form</code>元素添加id <code>cat-photo-form</code> 。 </section>
<add><section id='instructions'>
<add>设置<code>form</code>元素的 id 为<code>cat-photo-form</code>。
<add></section>
<ide>
<ide> ## Tests
<ide> <section id='tests'>
<ide>
<ide> ```yml
<ide> tests:
<del> - text: 为<code>form</code>元素添加<code>cat-photo-form</code>的id。
<del> testString: 'assert($("form").attr("id") === "cat-photo-form", "Give your <code>form</code> element the id of <code>cat-photo-form</code>.");'
<add> - text: '你的<code>form</code>元素的 id 应为<code>cat-photo-form</code>。'
<add> testString: assert($("form").attr("id") === "cat-photo-form", '你的<code>form</code>元素的 id 应为<code>cat-photo-form</code>。');
<ide>
<ide> ```
<ide>
<ide> tests:
<ide>
<ide> <h2 class="red-text">CatPhotoApp</h2>
<ide> <main>
<del> <p class="red-text">Click here to view more <a href="#">cat photos</a>.</p>
<del>
<del> <a href="#"><img class="smaller-image thick-green-border" src="https://bit.ly/fcc-relaxing-cat" alt="A cute orange cat lying on its back."></a>
<del>
<add> <p class="red-text">点击查看更多<a href="#">猫图</a>.</p>
<add>
<add> <a href="#"><img src="https://bit.ly/fcc-relaxing-cat" alt="一只仰卧着的萌猫" class="smaller-image thick-green-border"></a>
<add>
<ide> <div class="silver-background">
<del> <p>Things cats love:</p>
<add> <p>猫咪最喜欢的三件东西:</p>
<ide> <ul>
<del> <li>cat nip</li>
<del> <li>laser pointers</li>
<del> <li>lasagna</li>
<add> <li>猫薄荷</li>
<add> <li>激光笔</li>
<add> <li>千层饼</li>
<ide> </ul>
<del> <p>Top 3 things cats hate:</p>
<add> <p>猫咪最讨厌的三件东西:</p>
<ide> <ol>
<del> <li>flea treatment</li>
<del> <li>thunder</li>
<del> <li>other cats</li>
<add> <li>跳蚤</li>
<add> <li>打雷</li>
<add> <li>同类</li>
<ide> </ol>
<ide> </div>
<del>
<add>
<ide> <form action="/submit-cat-photo">
<del> <label><input type="radio" name="indoor-outdoor" checked> Indoor</label>
<del> <label><input type="radio" name="indoor-outdoor"> Outdoor</label><br>
<del> <label><input type="checkbox" name="personality" checked> Loving</label>
<del> <label><input type="checkbox" name="personality"> Lazy</label>
<del> <label><input type="checkbox" name="personality"> Energetic</label><br>
<del> <input type="text" placeholder="cat photo URL" required>
<del> <button type="submit">Submit</button>
<add> <label><input type="radio" name="indoor-outdoor">室内</label>
<add> <label><input type="radio" name="indoor-outdoor">室外</label><br>
<add> <label><input type="checkbox" name="personality">忠诚</label>
<add> <label><input type="checkbox" name="personality">懒惰</label>
<add> <label><input type="checkbox" name="personality">积极</label><br>
<add> <input type="text" placeholder="猫咪图片地址" required>
<add> <button type="submit">提交</button>
<ide> </form>
<ide> </main>
<del>
<ide> ```
<ide>
<ide> </div>
<ide> tests:
<ide> ## Solution
<ide> <section id='solution'>
<ide>
<del>```js
<add>```html
<ide> // solution required
<ide> ```
<ide> </section>
<add>
<ide>\ No newline at end of file
<ide><path>curriculum/challenges/chinese/01-responsive-web-design/basic-css/size-your-images.chinese.md
<ide> id: bad87fee1348bd9acdf08812
<ide> title: Size Your Images
<ide> challengeType: 0
<del>videoUrl: ''
<del>localeTitle: 调整图像大小
<add>videoUrl: 'https://scrimba.com/c/cM9MmCP'
<add>forumTopicId: 18282
<add>localTitle: 调整图片的大小
<ide> ---
<ide>
<ide> ## Description
<del><section id="description"> CSS有一个名为<code>width</code>的属性,用于控制元素的宽度。就像字体一样,我们将使用<code>px</code> (像素)来指定图像的宽度。例如,如果我们想要创建一个名为<code>larger-image</code>的CSS类,它给HTML元素的宽度为500像素,我们将使用: <blockquote> <风格> <br> .larger-image { <br>宽度:500px; <br> } <br> </样式> </blockquote></section>
<add><section id='description'>
<add>CSS 的<code>width</code>属性可以控制元素的宽度。图片的<code>width</code>宽度类似于字体的<code>px</code>(像素)值。
<add>假如,你想创建一个叫<code>larger-image</code>的 CSS class 来控制 HTML 元素的宽度为 500px,我们可以这样做:
<add>
<add>```html
<add><style>
<add> .larger-image {
<add> width: 500px;
<add> }
<add></style>
<add>```
<add>
<add></section>
<ide>
<ide> ## Instructions
<del><section id="instructions">创建一个名为<code>smaller-image</code>的类,并使用它来调整图像大小,使其只有100像素宽。 <strong>注意</strong> <br>由于浏览器实现的差异,您可能需要100%缩放才能通过此挑战的测试。 </section>
<add><section id='instructions'>
<add>创建一个<code>smaller-image</code>的 CSS class,设置图片的宽度为 100px。
<add><strong>注意:</strong><br>由于不同浏览器的差异性,你可能需要将浏览器缩放到 100% 来通过该挑战。
<add></section>
<ide>
<ide> ## Tests
<ide> <section id='tests'>
<ide>
<ide> ```yml
<ide> tests:
<del> - text: 您的<code>img</code>元素应该具有<code>smaller-image</code>类。
<del> testString: 'assert($("img[src="https://bit.ly/fcc-relaxing-cat"]").attr("class") === "smaller-image", "Your <code>img</code> element should have the class <code>smaller-image</code>.");'
<del> - text: 您的图片应为100像素宽。浏览器缩放应为100%。
<del> testString: 'assert($("img").width() === 100, "Your image should be 100 pixels wide. Browser zoom should be at 100%.");'
<add> - text: '<code>img</code>元素应该含有<code>smaller-image</code> class。'
<add> testString: 'assert($("img[src=''https://bit.ly/fcc-relaxing-cat'']").attr(''class'') === "smaller-image", ''<code>img</code>元素应该含有<code>smaller-image</code> class。'');'
<add> - text: '图片宽度应为 100px(像素),且浏览器缩放应为默认 100%。'
<add> testString: assert($("img").width() === 100, '你的图片应为 100px(像素),且浏览器缩放应为默认 100%。');
<ide>
<ide> ```
<ide>
<ide> tests:
<ide>
<ide> <h2 class="red-text">CatPhotoApp</h2>
<ide> <main>
<del> <p class="red-text">Click here to view more <a href="#">cat photos</a>.</p>
<del>
<del> <a href="#"><img src="https://bit.ly/fcc-relaxing-cat" alt="A cute orange cat lying on its back."></a>
<del>
<add> <p class="red-text">点击查看更多<a href="#">猫图</a>.</p>
<add>
<add> <a href="#"><img src="https://bit.ly/fcc-relaxing-cat" alt="一只仰卧着的萌猫"></a>
<add>
<ide> <div>
<del> <p>Things cats love:</p>
<add> <p>猫咪最喜欢的三件东西:</p>
<ide> <ul>
<del> <li>cat nip</li>
<del> <li>laser pointers</li>
<del> <li>lasagna</li>
<add> <li>猫薄荷</li>
<add> <li>激光笔</li>
<add> <li>千层饼</li>
<ide> </ul>
<del> <p>Top 3 things cats hate:</p>
<add> <p>猫咪最讨厌的三件东西:</p>
<ide> <ol>
<del> <li>flea treatment</li>
<del> <li>thunder</li>
<del> <li>other cats</li>
<add> <li>跳蚤</li>
<add> <li>打雷</li>
<add> <li>同类</li>
<ide> </ol>
<ide> </div>
<del>
<add>
<ide> <form action="/submit-cat-photo">
<del> <label><input type="radio" name="indoor-outdoor" checked> Indoor</label>
<del> <label><input type="radio" name="indoor-outdoor"> Outdoor</label><br>
<del> <label><input type="checkbox" name="personality" checked> Loving</label>
<del> <label><input type="checkbox" name="personality"> Lazy</label>
<del> <label><input type="checkbox" name="personality"> Energetic</label><br>
<del> <input type="text" placeholder="cat photo URL" required>
<del> <button type="submit">Submit</button>
<add> <label><input type="radio" name="indoor-outdoor">室内</label>
<add> <label><input type="radio" name="indoor-outdoor">室外</label><br>
<add> <label><input type="checkbox" name="personality">忠诚</label>
<add> <label><input type="checkbox" name="personality">懒惰</label>
<add> <label><input type="checkbox" name="personality">积极</label><br>
<add> <input type="text" placeholder="猫咪图片地址" required>
<add> <button type="submit">提交</button>
<ide> </form>
<ide> </main>
<del>
<ide> ```
<ide>
<ide> </div>
<ide> tests:
<ide> <section id='solution'>
<ide>
<ide> ```js
<del><link href="https://fonts.googleapis.com/css?family=Lobster" rel="stylesheet" type="text/css">
<del><style>
<del> .red-text {
<del> color: red;
<del> }
<del>
<del> h2 {
<del> font-family: Lobster, monospace;
<del> }
<del>
<del> p {
<del> font-size: 16px;
<del> font-family: monospace;
<del> }
<del>
<del> .smaller-image {
<del> width: 100px;
<del> }
<del></style>
<del>
<del><h2 class="red-text">CatPhotoApp</h2>
<del><main>
<del> <p class="red-text">Click here to view more <a href="#">cat photos</a>.</p>
<del>
<del> <a href="#"><img class="smaller-image" src="https://bit.ly/fcc-relaxing-cat" alt="A cute orange cat lying on its back."></a>
<del>
<del> <div>
<del> <p>Things cats love:</p>
<del> <ul>
<del> <li>cat nip</li>
<del> <li>laser pointers</li>
<del> <li>lasagna</li>
<del> </ul>
<del> <p>Top 3 things cats hate:</p>
<del> <ol>
<del> <li>flea treatment</li>
<del> <li>thunder</li>
<del> <li>other cats</li>
<del> </ol>
<del> </div>
<del>
<del> <form action="/submit-cat-photo">
<del> <label><input type="radio" name="indoor-outdoor" checked> Indoor</label>
<del> <label><input type="radio" name="indoor-outdoor"> Outdoor</label><br>
<del> <label><input type="checkbox" name="personality" checked> Loving</label>
<del> <label><input type="checkbox" name="personality"> Lazy</label>
<del> <label><input type="checkbox" name="personality"> Energetic</label><br>
<del> <input type="text" placeholder="cat photo URL" required>
<del> <button type="submit">Submit</button>
<del> </form>
<del></main>
<add>// solution required
<ide> ```
<ide> </section>
<add>
<ide>\ No newline at end of file
<ide><path>curriculum/challenges/chinese/01-responsive-web-design/basic-css/specify-how-fonts-should-degrade.chinese.md
<ide> id: bad87fee1348bd9aedf08808
<ide> title: Specify How Fonts Should Degrade
<ide> challengeType: 0
<del>videoUrl: ''
<del>localeTitle: 指定字体应如何降级
<add>videoUrl: 'https://scrimba.com/c/cpVKBfQ'
<add>forumTopicId: 18304
<add>localTitle: 字体如何优雅降级
<ide> ---
<ide>
<ide> ## Description
<del><section id="description">所有浏览器都有几种默认字体。这些通用字体系列包括<code>monospace</code> , <code>serif</code>和<code>sans-serif</code>当一个字体不可用时,您可以告诉浏览器“降级”为另一种字体。例如,如果您希望元素使用<code>Helvetica</code>字体,但在<code>Helvetica</code>不可用时降级为<code>sans-serif</code>字体,则将按如下方式指定: <blockquote> p { <br> font-family:Helvetica,sans-serif; <br> } </blockquote>通用字体系列名称不区分大小写。此外,它们不需要引号,因为它们是CSS关键字。 </section>
<add><section id='description'>
<add>所有浏览器都有几种默认字体。这些通用字体包括<code>monospace</code>,<code>serif</code>和<code>sans-serif</code>。
<add>当字体不可用,你可以告诉浏览器通过 “降级” 去使用其他字体。
<add>例如,如果你想将一个元素的字体设置成<code>Helvetica</code>,当<code>Helvetica</code>不可用时,降级使用<code>sans-serif</code>字体,那么可以这样写:
<add>
<add>```css
<add>p {
<add> font-family: Helvetica, sans-serif;
<add>}
<add>```
<add>
<add>通用字体名字不区分大小写。同时,也不需要使用引号,因为它们是 CSS 关键字。
<add></section>
<ide>
<ide> ## Instructions
<del><section id="instructions">首先,将<code>monospace</code>字体应用于<code>h2</code>元素,以便它现在有两种字体 - <code>Lobster</code>和<code>monospace</code>字体。在上一个挑战中,您使用<code>link</code>标记导入了<code>Lobster</code>字体。现在注释掉谷歌字体导入的<code>Lobster</code>字体(使用之前学过的HTML评论),以便它不再可用。注意你的<code>h2</code>元素如何降级为<code>monospace</code>字体。 <strong>注意</strong> <br>如果您的计算机上安装了Lobster字体,您将看不到降级,因为您的浏览器能够找到该字体。 </section>
<add><section id='instructions'>
<add>首先,添加<code>monospace</code>字体到<code>h2</code>元素里,它现在拥有着<code>Lobster</code>和<code>monospace</code>两种字体。
<add>在上一个挑战里,你已经通过<code>link</code>标签引入谷歌<code>Lobster</code>字体。现在让我们注释掉谷歌<code>Lobster</code>字体的引入(使用我们之前学过的<code>HTML</code>注释),使字体失效。你会发现你的<code>h2</code>元素降级到了<code>monospace</code>字体。
<add><strong>注意:</strong><br>如果你的电脑已经安装了<code>Lobster</code>字体,你将看不到这个降级过程,因为你的浏览器会找到该字体。
<add></section>
<ide>
<ide> ## Tests
<ide> <section id='tests'>
<ide>
<ide> ```yml
<ide> tests:
<del> - text: 你的h2元素应该使用字体<code>Lobster</code> 。
<del> testString: 'assert($("h2").css("font-family").match(/^"?lobster/i), "Your h2 element should use the font <code>Lobster</code>.");'
<del> - text: 当<code>Lobster</code>不可用时,你的h2元素会降级为<code>monospace</code>字体。
<del> testString: 'assert(/\s*h2\s*\{\s*font-family\:\s*(\"|")?Lobster(\"|")?,\s*monospace\s*;\s*\}/gi.test(code), "Your h2 element should degrade to the font <code>monospace</code> when <code>Lobster</code> is not available.");'
<del> - text: 通过在其前面放置<code><!--</code>来注释您对Google的<code>Lobster</code>字体的调用。
<del> testString: 'assert(new RegExp("<!--[^fc]", "gi").test(code), "Comment out your call to Google for the <code>Lobster</code> font by putting <code><!--</code> in front of it.");'
<del> - text: 请务必通过添加<code>--></code>来关闭您的评论。
<del> testString: 'assert(new RegExp("[^fc]-->", "gi").test(code), "Be sure to close your comment by adding <code>--></code>.");'
<add> - text: '<code>h2</code>元素应该含有<code>Lobster</code>字体。'
<add> testString: assert($("h2").css("font-family").match(/^"?lobster/i), '<code>h2</code>元素应该含有<code>Lobster</code>字体。');
<add> - text: '当<code>Lobster</code>字体失效时,<code>h2</code>元素应该降级使用<code>monospace</code>字体。'
<add> testString: 'assert(/\s*h2\s*\{\s*font-family\:\s*(\''|")?Lobster(\''|")?,\s*monospace\s*;\s*\}/gi.test(code), ''当<code>Lobster</code>字体失效时,<code>h2</code>元素应该降级使用<code>monospace</code>字体。'');'
<add> - text: '通过添加<code><!--</code>,注释掉谷歌<code>Lobster</code>字体的引入。'
<add> testString: assert(new RegExp("<!--[^fc]", "gi").test(code), '通过添加<code><!--</code>,注释掉谷歌<code>Lobster</code>字体的引入。');
<add> - text: '确保注释要以<code>--></code>结束。'
<add> testString: assert(new RegExp("[^fc]-->", "gi").test(code), '确保注释要以<code>--></code>结束。');
<ide>
<ide> ```
<ide>
<ide> tests:
<ide>
<ide> <h2 class="red-text">CatPhotoApp</h2>
<ide> <main>
<del> <p class="red-text">Click here to view more <a href="#">cat photos</a>.</p>
<del>
<del> <a href="#"><img src="https://bit.ly/fcc-relaxing-cat" alt="A cute orange cat lying on its back."></a>
<del>
<add> <p class="red-text">点击查看更多<a href="#">猫图</a>.</p>
<add>
<add> <a href="#"><img src="https://bit.ly/fcc-relaxing-cat" alt="一只仰卧着的萌猫"></a>
<add>
<ide> <div>
<del> <p>Things cats love:</p>
<add> <p>猫咪最喜欢的三件东西:</p>
<ide> <ul>
<del> <li>cat nip</li>
<del> <li>laser pointers</li>
<del> <li>lasagna</li>
<add> <li>猫薄荷</li>
<add> <li>激光笔</li>
<add> <li>千层饼</li>
<ide> </ul>
<del> <p>Top 3 things cats hate:</p>
<add> <p>猫咪最讨厌的三件东西:</p>
<ide> <ol>
<del> <li>flea treatment</li>
<del> <li>thunder</li>
<del> <li>other cats</li>
<add> <li>跳蚤</li>
<add> <li>打雷</li>
<add> <li>同类</li>
<ide> </ol>
<ide> </div>
<del>
<add>
<ide> <form action="/submit-cat-photo">
<del> <label><input type="radio" name="indoor-outdoor" checked> Indoor</label>
<del> <label><input type="radio" name="indoor-outdoor"> Outdoor</label><br>
<del> <label><input type="checkbox" name="personality" checked> Loving</label>
<del> <label><input type="checkbox" name="personality"> Lazy</label>
<del> <label><input type="checkbox" name="personality"> Energetic</label><br>
<del> <input type="text" placeholder="cat photo URL" required>
<del> <button type="submit">Submit</button>
<add> <label><input type="radio" name="indoor-outdoor">室内</label>
<add> <label><input type="radio" name="indoor-outdoor">室外</label><br>
<add> <label><input type="checkbox" name="personality">忠诚</label>
<add> <label><input type="checkbox" name="personality">懒惰</label>
<add> <label><input type="checkbox" name="personality">积极</label><br>
<add> <input type="text" placeholder="猫咪图片地址" required>
<add> <button type="submit">提交</button>
<ide> </form>
<ide> </main>
<del>
<ide> ```
<ide>
<ide> </div>
<ide> tests:
<ide> ## Solution
<ide> <section id='solution'>
<ide>
<del>```js
<add>```html
<ide> // solution required
<ide> ```
<add>
<ide> </section>
<add>
<ide>\ No newline at end of file
<ide><path>curriculum/challenges/chinese/01-responsive-web-design/basic-css/style-multiple-elements-with-a-css-class.chinese.md
<ide> id: bad87fee1348bd9aefe08806
<ide> title: Style Multiple Elements with a CSS Class
<ide> challengeType: 0
<del>videoUrl: ''
<del>localeTitle: 使用CSS类设置多个元素的样式
<add>videoUrl: 'https://scrimba.com/c/cRkVbsQ'
<add>forumTopicId: 18311
<add>localTitle: 使用 class 选择器设置多个元素的样式
<ide> ---
<ide>
<ide> ## Description
<del><section id="description">类允许您在多个HTML元素上使用相同的CSS样式。您可以通过将<code>red-text</code>类应用于第一个<code>p</code>元素来查看。 </section>
<add><section id='description'>
<add>通过 CSS class 选择器,多个 HTML 元素可以使用相同的 CSS 样式规则。你可以将<code>red-text</code>class 选择器应用在第一个<code>p</code>元素上。
<add></section>
<ide>
<ide> ## Instructions
<del><section id="instructions">
<add><section id='instructions'>
<add>
<ide> </section>
<ide>
<ide> ## Tests
<ide> <section id='tests'>
<ide>
<ide> ```yml
<ide> tests:
<del> - text: 你的<code>h2</code>元素应该是红色的。
<del> testString: 'assert($("h2").css("color") === "rgb(255, 0, 0)", "Your <code>h2</code> element should be red.");'
<del> - text: 你的<code>h2</code>元素应该有<code>red-text</code>类。
<del> testString: 'assert($("h2").hasClass("red-text"), "Your <code>h2</code> element should have the class <code>red-text</code>.");'
<del> - text: 你的第一个<code>p</code>元素应该是红色的。
<del> testString: 'assert($("p:eq(0)").css("color") === "rgb(255, 0, 0)", "Your first <code>p</code> element should be red.");'
<del> - text: 你的第二和第三个<code>p</code>元素不应该是红色的。
<del> testString: 'assert(!($("p:eq(1)").css("color") === "rgb(255, 0, 0)") && !($("p:eq(2)").css("color") === "rgb(255, 0, 0)"), "Your second and third <code>p</code> elements should not be red.");'
<del> - text: 你的第一个<code>p</code>元素应该有<code>red-text</code>类。
<del> testString: 'assert($("p:eq(0)").hasClass("red-text"), "Your first <code>p</code> element should have the class <code>red-text</code>.");'
<add> - text: '<code>h2</code>元素应该是红色的。'
<add> testString: assert($("h2").css("color") === "rgb(255, 0, 0)", '<code>h2</code>元素应该是红色的。');
<add> - text: '<code>h2</code>元素应该含有<code>red-text</code> class 选择器。'
<add> testString: assert($("h2").hasClass("red-text"), '<code>h2</code>元素应该含有<code>red-text</code> class 选择器。');
<add> - text: '第一个<code>p</code>元素应该为红色。'
<add> testString: 'assert($("p:eq(0)").css("color") === "rgb(255, 0, 0)", ''第一个<code>p</code>元素应该为红色。'');'
<add> - text: '第二和第三个<code>p</code>元素不应该为红色。'
<add> testString: 'assert(!($("p:eq(1)").css("color") === "rgb(255, 0, 0)") && !($("p:eq(2)").css("color") === "rgb(255, 0, 0)"), ''第二和第三个<code>p</code>元素不应该为红色。'');'
<add> - text: '第一个<code>p</code>元素应该包含<code>red-text</code> class 选择器。'
<add> testString: 'assert($("p:eq(0)").hasClass("red-text"), ''第一个<code>p</code>元素应该包含<code>red-text</code> class 选择器。'');'
<ide>
<ide> ```
<ide>
<ide> tests:
<ide>
<ide> <h2 class="red-text">CatPhotoApp</h2>
<ide> <main>
<del> <p>Click here to view more <a href="#">cat photos</a>.</p>
<del>
<del> <a href="#"><img src="https://bit.ly/fcc-relaxing-cat" alt="A cute orange cat lying on its back."></a>
<del>
<add> <p class="red-text">点击查看更多<a href="#">猫图</a>.</p>
<add>
<add> <a href="#"><img src="https://bit.ly/fcc-relaxing-cat" alt="一只仰卧着的萌猫"></a>
<add>
<ide> <div>
<del> <p>Things cats love:</p>
<add> <p>猫咪最喜欢的三件东西:</p>
<ide> <ul>
<del> <li>cat nip</li>
<del> <li>laser pointers</li>
<del> <li>lasagna</li>
<add> <li>猫薄荷</li>
<add> <li>激光笔</li>
<add> <li>千层饼</li>
<ide> </ul>
<del> <p>Top 3 things cats hate:</p>
<add> <p>猫咪最讨厌的三件东西:</p>
<ide> <ol>
<del> <li>flea treatment</li>
<del> <li>thunder</li>
<del> <li>other cats</li>
<add> <li>跳蚤</li>
<add> <li>打雷</li>
<add> <li>同类</li>
<ide> </ol>
<ide> </div>
<del>
<add>
<ide> <form action="/submit-cat-photo">
<del> <label><input type="radio" name="indoor-outdoor" checked> Indoor</label>
<del> <label><input type="radio" name="indoor-outdoor"> Outdoor</label><br>
<del> <label><input type="checkbox" name="personality" checked> Loving</label>
<del> <label><input type="checkbox" name="personality"> Lazy</label>
<del> <label><input type="checkbox" name="personality"> Energetic</label><br>
<del> <input type="text" placeholder="cat photo URL" required>
<del> <button type="submit">Submit</button>
<add> <label><input type="radio" name="indoor-outdoor">室内</label>
<add> <label><input type="radio" name="indoor-outdoor">室外</label><br>
<add> <label><input type="checkbox" name="personality">忠诚</label>
<add> <label><input type="checkbox" name="personality">懒惰</label>
<add> <label><input type="checkbox" name="personality">积极</label><br>
<add> <input type="text" placeholder="猫咪图片地址" required>
<add> <button type="submit">提交</button>
<ide> </form>
<ide> </main>
<del>
<ide> ```
<ide>
<ide> </div>
<ide> tests:
<ide> ## Solution
<ide> <section id='solution'>
<ide>
<del>```js
<add>```html
<ide> // solution required
<ide> ```
<add>
<ide> </section>
<add>
<ide>\ No newline at end of file
<ide><path>curriculum/challenges/chinese/01-responsive-web-design/basic-css/style-the-html-body-element.chinese.md
<ide> id: bad87fee1348bd9aedf08736
<ide> title: Style the HTML Body Element
<ide> challengeType: 0
<del>videoUrl: ''
<del>localeTitle: 设置HTML Body Element的样式
<add>videoUrl: 'https://scrimba.com/c/cB77PHW'
<add>forumTopicId: 18313
<add>localTitle: 给 HTML 的 Body 元素添加样式
<ide> ---
<ide>
<ide> ## Description
<del><section id="description">现在让我们重新开始讨论CSS继承。每个HTML页面都有一个<code>body</code>元素。 </section>
<add><section id='description'>
<add>现在让我们来讨论一下 CSS 继承。
<add>每一个 HTML 页面都含有一个<code>body</code>元素。
<add></section>
<ide>
<ide> ## Instructions
<del><section id="instructions">我们可以通过给它一个黑色的<code>background-color</code>来证明<code>body</code>元素存在。我们可以通过在<code>style</code>元素中添加以下内容来实现: <blockquote>身体 { <br>背景颜色:黑色; <br> } </blockquote></section>
<add><section id='instructions'>
<add>我们可以通过设置<code>background-color</code>为<code>black</code>,来证明<code>body</code>元素的存在。
<add>添加以下的代码到<code>style</code>标签里面:
<add>
<add>```css
<add>body {
<add> background-color: black;
<add>}
<add>```
<add>
<add></section>
<ide>
<ide> ## Tests
<ide> <section id='tests'>
<ide>
<ide> ```yml
<ide> tests:
<del> - text: 给你的<code>body</code>元素黑色的<code>background-color</code> 。
<del> testString: 'assert($("body").css("background-color") === "rgb(0, 0, 0)", "Give your <code>body</code> element the <code>background-color</code> of black.");'
<del> - text: 确保您的CSS规则使用左右大括号正确格式化。
<del> testString: 'assert(code.match(/<style>\s*body\s*\{\s*background.*\s*:\s*.*;\s*\}\s*<\/style>/i), "Make sure your CSS rule is properly formatted with both opening and closing curly brackets.");'
<del> - text: 确保您的CSS规则以分号结尾。
<del> testString: 'assert(code.match(/<style>\s*body\s*\{\s*background.*\s*:\s*.*;\s*\}\s*<\/style>/i), "Make sure your CSS rule ends with a semi-colon.");'
<add> - text: '<code>body</code>元素的<code>background-color</code>应该是黑色的。'
<add> testString: assert($("body").css("background-color") === "rgb(0, 0, 0)", '<code>body</code>元素的<code>background-color</code>应该是黑色的。');
<add> - text: '确保你的 CSS 规则格式书写正确,需要开关大括号。'
<add> testString: 'assert(code.match(/<style>\s*body\s*\{\s*background.*\s*:\s*.*;\s*\}\s*<\/style>/i), ''确保你的 CSS 规则格式书写正确,需要开关大括号。'');'
<add> - text: '确保你的 CSS 规则要以分号结尾。'
<add> testString: 'assert(code.match(/<style>\s*body\s*\{\s*background.*\s*:\s*.*;\s*\}\s*<\/style>/i), ''确保你的 CSS 规则要以分号结尾。'');'
<ide>
<ide> ```
<ide>
<ide> tests:
<ide> <style>
<ide>
<ide> </style>
<del>
<ide> ```
<ide>
<ide> </div>
<ide> tests:
<ide> ## Solution
<ide> <section id='solution'>
<ide>
<del>```js
<add>```html
<ide> // solution required
<ide> ```
<add>
<ide> </section>
<add>
<ide>\ No newline at end of file
<ide><path>curriculum/challenges/chinese/01-responsive-web-design/basic-css/understand-absolute-versus-relative-units.chinese.md
<ide> id: bad82fee1322bd9aedf08721
<ide> title: Understand Absolute versus Relative Units
<ide> challengeType: 0
<del>videoUrl: ''
<del>localeTitle: 了解绝对与相对单位
<add>videoUrl: 'https://scrimba.com/c/cN66JSL'
<add>forumTopicId: 301089
<add>localTitle: 理解绝对单位与相对单位
<ide> ---
<ide>
<ide> ## Description
<del><section id="description">最后几个挑战都设置元素的边距或填充像素( <code>px</code> )。像素是一种长度单位,它告诉浏览器如何调整项目的大小或空间。除了<code>px</code> ,CSS还有许多不同的长度单位选项供您使用。两种主要类型的长度单位是绝对的和相对的。绝对单位与长度的物理单位相关联。例如, <code>in</code>和<code>mm</code>表示英寸和毫米。绝对长度单位接近屏幕上的实际测量值,但根据屏幕的分辨率存在一些差异。相对单位,例如<code>em</code>或<code>rem</code> ,相对于另一个长度值。例如, <code>em</code>基于元素字体的大小。如果您使用它来设置<code>font-size</code>属性本身,则它相对于父级的<code>font-size</code> 。 <strong>注意</strong> <br>有几个相对单位选项与视口的大小相关联。它们包含在响应式Web设计原则部分中。 </section>
<add><section id='description'>
<add>最近的几个挑战都是设置元素的内边距和外边距的<code>px</code>值。像素<code>px</code>是一种长度单位,来告诉浏览器应该如何调整元素大小和空间大小。其实除了像素,CSS 也有其他不同的长度单位供我们使用。
<add>单位长度的类型可以分成 2 种,一种是相对的,一种是绝对的。例如,<code>in</code>和<code>mm</code>分别代表着英寸和毫米。绝对长度单位会接近屏幕上的实际测量值,不过不同屏幕的分辨率会存在差异,可能会导致一些误差。
<add>相对单位长度,就像<code>em</code>和<code>rem</code>,它们会依赖其他长度的值。就好像<code>em</code>的大小基于元素的字体的<code>font-size</code>值,如果你使用<code>em</code>单位来设置<code>font-size</code>值,它的值会跟随父元素的<code>font-size</code>值来改变。
<add><strong>注意:</strong><br>有些单位长度选项是相对视窗大小来改变值的,符合了响应式 web 的设计原则。
<add></section>
<ide>
<ide> ## Instructions
<del><section id="instructions">使用类<code>red-box</code>向元素添加<code>padding</code>属性并将其设置为<code>1.5em</code> 。 </section>
<add><section id='instructions'>
<add>给<code>red-box</code> class 添加<code>padding</code>属性,并设置为<code>1.5em</code>。
<add></section>
<ide>
<ide> ## Tests
<ide> <section id='tests'>
<ide>
<ide> ```yml
<ide> tests:
<del> - text: 你的<code>red-box</code>类应该有一个<code>padding</code>属性。
<del> testString: 'assert($(".red-box").css("padding-top") != "0px" && $(".red-box").css("padding-right") != "0px" && $(".red-box").css("padding-bottom") != "0px" && $(".red-box").css("padding-left") != "0px", "Your <code>red-box</code> class should have a <code>padding</code> property.");'
<del> - text: 你的<code>red-box</code>类应该给出1.5em的<code>padding</code>元素。
<del> testString: 'assert(code.match(/\.red-box\s*?{\s*?.*?\s*?.*?\s*?padding:\s*?1\.5em/gi), "Your <code>red-box</code> class should give elements 1.5em of <code>padding</code>.");'
<add> - text: '<code>red-box</code> class 应该含有<code>padding</code>属性。'
<add> testString: assert($('.red-box').css('padding-top') != '0px' && $('.red-box').css('padding-right') != '0px' && $('.red-box').css('padding-bottom') != '0px' && $('.red-box').css('padding-left') != '0px', '<code>red-box</code> class 应该含有<code>padding</code>属性。');
<add> - text: '<code>red-box</code> class 的<code>padding</code>值应为 1.5em。'
<add> testString: 'assert(code.match(/\.red-box\s*?{\s*?.*?\s*?.*?\s*?padding:\s*?1\.5em/gi), ''<code>red-box</code> class 的<code>padding</code>值应为 1.5em。'');'
<ide>
<ide> ```
<ide>
<ide> tests:
<ide> .red-box {
<ide> background-color: red;
<ide> margin: 20px 40px 20px 40px;
<del>
<add>
<ide> }
<ide>
<ide> .green-box {
<ide> background-color: green;
<del> margin: 20px 40px 20px 40px;
<add> margin: 40px 20px 20px 40px;
<ide> }
<ide> </style>
<ide> <h5 class="injected-text">margin</h5>
<ide> tests:
<ide> <h5 class="box red-box">padding</h5>
<ide> <h5 class="box green-box">padding</h5>
<ide> </div>
<del>
<ide> ```
<ide>
<ide> </div>
<ide> tests:
<ide> ## Solution
<ide> <section id='solution'>
<ide>
<del>```js
<add>```html
<ide> // solution required
<ide> ```
<add>
<ide> </section>
<add>
<ide>\ No newline at end of file
<ide><path>curriculum/challenges/chinese/01-responsive-web-design/basic-css/use-a-css-class-to-style-an-element.chinese.md
<ide> id: bad87fee1348bd9aecf08806
<ide> title: Use a CSS Class to Style an Element
<ide> challengeType: 0
<del>videoUrl: ''
<del>localeTitle: 使用CSS类来设置元素的样式
<add>videoUrl: 'https://scrimba.com/c/c2MvDtV'
<add>forumTopicId: 18337
<add>localTitle: 使用 class 选择器设置单个元素的样式
<ide> ---
<ide>
<ide> ## Description
<del><section id="description">类是可重用的样式,可以添加到HTML元素中。这是一个CSS类声明示例: <blockquote> <风格> <br> .blue-text { <br>颜色:蓝色; <br> } <br> </样式> </blockquote>您可以看到我们在<code><style></code>标记内创建了一个名为<code>blue-text</code>的CSS类。您可以将类应用于HTML元素,如下所示: <code><h2 class="blue-text">CatPhotoApp</h2></code>请注意,在CSS <code>style</code>元素中,类名以句点开头。在HTML元素的class属性中,类名不包含句点。 </section>
<add><section id='description'>
<add>CSS 的<code>class</code>具有可重用性,可应用于各种 HTML 元素。
<add>一个 CSS<code>class</code>声明示例,如下所示:
<add>
<add>```html
<add><style>
<add> .blue-text {
<add> color: blue;
<add> }
<add></style>
<add>```
<add>
<add>可以看到,我们在<code><style></code>样式声明区域里,创建了一个名为<code>blue-text</code>的<code>class</code>选择器。
<add>你可以将 CSS<code>class</code>选择器应用到一个HTML元素里,如下所示:
<add><code><h2 class="blue-text">CatPhotoApp</h2></code>
<add>注意:在<code>style</code>样式区域声明里,<code>class</code>需以<code>.</code>开头。而在 HTML 元素里,<code>class</code>属性的前面不能添加<code>.</code>。
<add></section>
<ide>
<ide> ## Instructions
<del><section id="instructions">在<code>style</code>元素中,将<code>h2</code>选择器更改为<code>.red-text</code>并将颜色的值从<code>blue</code>更新为<code>red</code> 。为您的<code>h2</code>元素提供值为<code>'red-text'</code>的<code>class</code>属性。 </section>
<add><section id='instructions'>
<add>在<code>style</code>样式声明里,把<code>h2</code>元素选择器改为<code>.red-text</code>class 选择器,同时将颜色<code>blue</code>变为<code>red</code>。
<add>在<code>h2</code>元素里,添加一个<code>class</code>属性,且值为<code>'red-text'</code>。
<add></section>
<ide>
<ide> ## Tests
<ide> <section id='tests'>
<ide>
<ide> ```yml
<ide> tests:
<del> - text: 你的<code>h2</code>元素应该是红色的。
<del> testString: 'assert($("h2").css("color") === "rgb(255, 0, 0)", "Your <code>h2</code> element should be red.");'
<del> - text: 你的<code>h2</code>元素应该有<code>red-text</code>类。
<del> testString: 'assert($("h2").hasClass("red-text"), "Your <code>h2</code> element should have the class <code>red-text</code>.");'
<del> - text: 样式表应声明一个<code>red-text</code>类,并将其颜色设置为红色。
<del> testString: 'assert(code.match(/\.red-text\s*\{\s*color\s*:\s*red;\s*\}/g), "Your stylesheet should declare a <code>red-text</code> class and have its color set to red.");'
<del> - text: '不要在<code>h2</code>元素中使用<code>style="color: red"</code>内联样式声明。'
<del> testString: 'assert($("h2").attr("style") === undefined, "Do not use inline style declarations like <code>style="color: red"</code> in your <code>h2</code> element.");'
<add> - text: '<code>h2</code>元素应该为红色。'
<add> testString: assert($("h2").css("color") === "rgb(255, 0, 0)", '<code>h2</code>元素应该为红色。');
<add> - text: '<code>h2</code>元素应含有<code>red-text</code> class 选择器。'
<add> testString: assert($("h2").hasClass("red-text"), '<code>h2</code>元素应含有<code>red-text</code> class 选择器。');
<add> - text: '<code>style</code>样式声明区域里应该包含一个<code>red-text</code> class 选择器,并且它的颜色应为红色。'
<add> testString: 'assert(code.match(/\.red-text\s*\{\s*color\s*:\s*red;\s*\}/g), ''<code>style</code>样式声明区域里应该包含一个<code>red-text</code> class 选择器,并且它的颜色应为红色。'');'
<add> - text: '不要在<code>h2</code>元素里使用行内样式:<code>style="color: red"</code>。'
<add> testString: assert($("h2").attr("style") === undefined, '不要在<code>h2</code>元素里使用行内样式:<code>style="color: red"</code>。');
<ide>
<ide> ```
<ide>
<ide> tests:
<ide>
<ide> <h2>CatPhotoApp</h2>
<ide> <main>
<del> <p>Click here to view more <a href="#">cat photos</a>.</p>
<del>
<del> <a href="#"><img src="https://bit.ly/fcc-relaxing-cat" alt="A cute orange cat lying on its back."></a>
<del>
<add> <p class="red-text">点击查看更多<a href="#">猫图</a>.</p>
<add>
<add> <a href="#"><img src="https://bit.ly/fcc-relaxing-cat" alt="一只仰卧着的萌猫"></a>
<add>
<ide> <div>
<del> <p>Things cats love:</p>
<add> <p>猫咪最喜欢的三件东西:</p>
<ide> <ul>
<del> <li>cat nip</li>
<del> <li>laser pointers</li>
<del> <li>lasagna</li>
<add> <li>猫薄荷</li>
<add> <li>激光笔</li>
<add> <li>千层饼</li>
<ide> </ul>
<del> <p>Top 3 things cats hate:</p>
<add> <p>猫咪最讨厌的三件东西:</p>
<ide> <ol>
<del> <li>flea treatment</li>
<del> <li>thunder</li>
<del> <li>other cats</li>
<add> <li>跳蚤</li>
<add> <li>打雷</li>
<add> <li>同类</li>
<ide> </ol>
<ide> </div>
<del>
<add>
<ide> <form action="/submit-cat-photo">
<del> <label><input type="radio" name="indoor-outdoor" checked> Indoor</label>
<del> <label><input type="radio" name="indoor-outdoor"> Outdoor</label><br>
<del> <label><input type="checkbox" name="personality" checked> Loving</label>
<del> <label><input type="checkbox" name="personality"> Lazy</label>
<del> <label><input type="checkbox" name="personality"> Energetic</label><br>
<del> <input type="text" placeholder="cat photo URL" required>
<del> <button type="submit">Submit</button>
<add> <label><input type="radio" name="indoor-outdoor">室内</label>
<add> <label><input type="radio" name="indoor-outdoor">室外</label><br>
<add> <label><input type="checkbox" name="personality">忠诚</label>
<add> <label><input type="checkbox" name="personality">懒惰</label>
<add> <label><input type="checkbox" name="personality">积极</label><br>
<add> <input type="text" placeholder="猫咪图片地址" required>
<add> <button type="submit">提交</button>
<ide> </form>
<ide> </main>
<del>
<ide> ```
<ide>
<ide> </div>
<ide> tests:
<ide> ## Solution
<ide> <section id='solution'>
<ide>
<del>```js
<add>```html
<ide> // solution required
<ide> ```
<ide> </section>
<add>
<ide>\ No newline at end of file
<ide><path>curriculum/challenges/chinese/01-responsive-web-design/basic-css/use-a-custom-css-variable.chinese.md
<ide> id: 5a9d727a424fe3d0e10cad12
<ide> title: Use a custom CSS Variable
<ide> challengeType: 0
<del>videoUrl: ''
<del>localeTitle: 使用自定义CSS变量
<add>videoUrl: 'https://scrimba.com/c/cM989ck'
<add>forumTopicId: 301090
<add>localTitle: 使用一个自定义的 CSS 变量
<ide> ---
<ide>
<ide> ## Description
<del><section id="description">创建变量后,可以通过引用您提供的名称将其值分配给其他CSS属性。 <blockquote>背景:var( - penguin-skin); </blockquote>这会将您要定位的任何元素的背景更改为灰色,因为这是<code>--penguin-skin</code>变量的值。请注意,除非变量名称完全匹配,否则不会应用样式。 </section>
<add><section id='description'>
<add>创建变量后,CSS 属性可以通过引用变量名来使用它的值。
<add>
<add>```css
<add>background: var(--penguin-skin);
<add>```
<add>
<add>因为引用了<code>--penguin-skin</code>变量的值,使用了这个样式的元素背景颜色会是灰色。
<add>注意:如果变量名不匹配,样式不会生效。
<add></section>
<ide>
<ide> ## Instructions
<del><section id="instructions">将<code>--penguin-skin</code>变量应用于<code>penguin-top</code> , <code>penguin-bottom</code> , <code>right-hand</code>和<code>left-hand</code>类的<code>background</code>属性。 </section>
<add><section id='instructions'>
<add><code>penguin-top</code>,<code>penguin-bottom</code>,<code>right-hand</code>和<code>left-hand</code>class 的<code>background</code>属性均使用<code>--penguin-skin</code>变量值。
<add></section>
<ide>
<ide> ## Tests
<ide> <section id='tests'>
<ide>
<ide> ```yml
<ide> tests:
<del> - text: 将<code>--penguin-skin</code>变量应用于<code>penguin-top</code>类的<code>background</code>属性。
<del> testString: 'assert(code.match(/.penguin-top\s*?{[\s\S]*background\s*?:\s*?var\s*?\(\s*?--penguin-skin\s*?\)\s*?;[\s\S]*}[\s\S]*.penguin-bottom\s{/gi), "Apply the <code>--penguin-skin</code> variable to the <code>background</code> property of the <code>penguin-top</code> class.");'
<del> - text: 将<code>--penguin-skin</code>变量应用于<code>penguin-bottom</code>类的<code>background</code>属性。
<del> testString: 'assert(code.match(/.penguin-bottom\s*?{[\s\S]*background\s*?:\s*?var\s*?\(\s*?--penguin-skin\s*?\)\s*?;[\s\S]*}[\s\S]*.right-hand\s{/gi), "Apply the <code>--penguin-skin</code> variable to the <code>background</code> property of the <code>penguin-bottom</code> class.");'
<del> - text: 将<code>--penguin-skin</code>变量应用于<code>right-hand</code>类的<code>background</code>属性。
<del> testString: 'assert(code.match(/.right-hand\s*?{[\s\S]*background\s*?:\s*?var\s*?\(\s*?--penguin-skin\s*?\)\s*?;[\s\S]*}[\s\S]*.left-hand\s{/gi), "Apply the <code>--penguin-skin</code> variable to the <code>background</code> property of the <code>right-hand</code> class.");'
<del> - text: 将<code>--penguin-skin</code>变量应用于<code>left-hand</code>类的<code>background</code>属性。
<del> testString: 'assert(code.match(/.left-hand\s*?{[\s\S]*background\s*?:\s*?var\s*?\(\s*?--penguin-skin\s*?\)\s*?;[\s\S]*}/gi), "Apply the <code>--penguin-skin</code> variable to the <code>background</code> property of the <code>left-hand</code> class.");'
<add> - text: '<code>penguin-top</code> class 的<code>background</code>属性应使用<code>--penguin-skin</code>变量值。'
<add> testString: 'assert(code.match(/.penguin-top\s*?{[\s\S]*background\s*?:\s*?var\s*?\(\s*?--penguin-skin\s*?\)\s*?;[\s\S]*}[\s\S]*.penguin-bottom\s{/gi), ''<code>penguin-top</code> class 的<code>background</code>属性应使用<code>--penguin-skin</code>变量值。'');'
<add> - text: '<code>penguin-bottom</code> class 的<code>background</code>属性应使用<code>--penguin-skin</code>变量值。'
<add> testString: 'assert(code.match(/.penguin-bottom\s*?{[\s\S]*background\s*?:\s*?var\s*?\(\s*?--penguin-skin\s*?\)\s*?;[\s\S]*}[\s\S]*.right-hand\s{/gi), ''<code>penguin-bottom</code> class 的<code>background</code>属性应使用<code>--penguin-skin</code>变量值。'');'
<add> - text: '<code>right-hand</code> class 的<code>background</code>属性应使用<code>--penguin-skin</code>变量值。'
<add> testString: 'assert(code.match(/.right-hand\s*?{[\s\S]*background\s*?:\s*?var\s*?\(\s*?--penguin-skin\s*?\)\s*?;[\s\S]*}[\s\S]*.left-hand\s{/gi), ''<code>right-hand</code> class 的<code>background</code>属性应使用<code>--penguin-skin</code>变量值。'');'
<add> - text: '<code>left-hand</code> class 的<code>background</code>属性应使用<code>--penguin-skin</code>变量值。'
<add> testString: 'assert(code.match(/.left-hand\s*?{[\s\S]*background\s*?:\s*?var\s*?\(\s*?--penguin-skin\s*?\)\s*?;[\s\S]*}/gi), ''<code>left-hand</code> class 的<code>background</code>属性应使用<code>--penguin-skin</code>变量值。'');'
<ide>
<ide> ```
<ide>
<ide> tests:
<ide> width: 300px;
<ide> height: 300px;
<ide> }
<del>
<add>
<ide> .penguin-top {
<ide> top: 10%;
<ide> left: 25%;
<del>
<add>
<ide> /* change code below */
<ide> background: black;
<ide> /* change code above */
<del>
<add>
<ide> width: 50%;
<ide> height: 45%;
<ide> border-radius: 70% 70% 60% 60%;
<ide> }
<del>
<add>
<ide> .penguin-bottom {
<ide> top: 40%;
<ide> left: 23.5%;
<del>
<add>
<ide> /* change code below */
<ide> background: black;
<ide> /* change code above */
<del>
<add>
<ide> width: 53%;
<ide> height: 45%;
<ide> border-radius: 70% 70% 100% 100%;
<ide> }
<del>
<add>
<ide> .right-hand {
<ide> top: 0%;
<ide> left: -5%;
<del>
<add>
<ide> /* change code below */
<ide> background: black;
<ide> /* change code above */
<del>
<add>
<ide> width: 30%;
<ide> height: 60%;
<ide> border-radius: 30% 30% 120% 30%;
<ide> transform: rotate(45deg);
<ide> z-index: -1;
<ide> }
<del>
<add>
<ide> .left-hand {
<ide> top: 0%;
<ide> left: 75%;
<del>
<add>
<ide> /* change code below */
<ide> background: black;
<ide> /* change code above */
<del>
<add>
<ide> width: 30%;
<ide> height: 60%;
<ide> border-radius: 30% 30% 30% 120%;
<ide> transform: rotate(-45deg);
<ide> z-index: -1;
<ide> }
<del>
<add>
<ide> .right-cheek {
<ide> top: 15%;
<ide> left: 35%;
<ide> tests:
<ide> height: 70%;
<ide> border-radius: 70% 70% 60% 60%;
<ide> }
<del>
<add>
<ide> .left-cheek {
<ide> top: 15%;
<ide> left: 5%;
<ide> tests:
<ide> height: 70%;
<ide> border-radius: 70% 70% 60% 60%;
<ide> }
<del>
<add>
<ide> .belly {
<ide> top: 60%;
<ide> left: 2.5%;
<ide> tests:
<ide> height: 100%;
<ide> border-radius: 120% 120% 100% 100%;
<ide> }
<del>
<add>
<ide> .right-feet {
<ide> top: 85%;
<ide> left: 60%;
<ide> tests:
<ide> height: 30%;
<ide> border-radius: 50% 50% 50% 50%;
<ide> transform: rotate(-80deg);
<del> z-index: -2222;
<add> z-index: -2222;
<ide> }
<del>
<add>
<ide> .left-feet {
<ide> top: 85%;
<ide> left: 25%;
<ide> tests:
<ide> height: 30%;
<ide> border-radius: 50% 50% 50% 50%;
<ide> transform: rotate(80deg);
<del> z-index: -2222;
<add> z-index: -2222;
<ide> }
<del>
<add>
<ide> .right-eye {
<ide> top: 45%;
<ide> left: 60%;
<ide> background: black;
<ide> width: 15%;
<ide> height: 17%;
<del> border-radius: 50%;
<add> border-radius: 50%;
<ide> }
<del>
<add>
<ide> .left-eye {
<ide> top: 45%;
<ide> left: 25%;
<ide> tests:
<ide> height: 17%;
<ide> border-radius: 50%;
<ide> }
<del>
<add>
<ide> .sparkle {
<ide> top: 25%;
<ide> left: 15%;
<ide> tests:
<ide> height: 35%;
<ide> border-radius: 50%;
<ide> }
<del>
<add>
<ide> .blush-right {
<ide> top: 65%;
<ide> left: 15%;
<ide> tests:
<ide> height: 10%;
<ide> border-radius: 50%;
<ide> }
<del>
<add>
<ide> .blush-left {
<ide> top: 65%;
<ide> left: 70%;
<ide> tests:
<ide> height: 10%;
<ide> border-radius: 50%;
<ide> }
<del>
<add>
<ide> .beak-top {
<ide> top: 60%;
<ide> left: 40%;
<ide> tests:
<ide> height: 10%;
<ide> border-radius: 50%;
<ide> }
<del>
<add>
<ide> .beak-bottom {
<ide> top: 65%;
<ide> left: 42%;
<ide> tests:
<ide> height: 10%;
<ide> border-radius: 50%;
<ide> }
<del>
<add>
<ide> body {
<ide> background:#c6faf1;
<ide> }
<del>
<add>
<ide> .penguin * {
<ide> position: absolute;
<ide> }
<ide> tests:
<ide> <div class="beak-bottom"></div>
<ide> </div>
<ide> </div>
<del>
<ide> ```
<ide>
<ide> </div>
<del>
<del>
<del>
<ide> </section>
<ide>
<ide> ## Solution
<ide> <section id='solution'>
<ide>
<add>
<ide> ```js
<ide> // solution required
<ide> ```
<add>
<ide> </section>
<add>
<ide>\ No newline at end of file
<ide><path>curriculum/challenges/chinese/01-responsive-web-design/basic-css/use-a-media-query-to-change-a-variable.chinese.md
<ide> id: 5a9d72ad424fe3d0e10cad16
<ide> title: Use a media query to change a variable
<ide> challengeType: 0
<del>videoUrl: ''
<del>localeTitle: 使用媒体查询更改变量
<add>videoUrl: 'https://scrimba.com/c/cWmL8UP'
<add>forumTopicId: 301091
<add>localTitle: 使用媒体查询更改变量
<ide> ---
<ide>
<ide> ## Description
<del><section id="description"> CSS变量可以简化您使用媒体查询的方式。例如,当您的屏幕小于或大于媒体查询断点时,您可以更改变量的值,并且无论在何处使用它都将应用其样式。 </section>
<add><section id='description'>
<add>CSS 变量可以简化媒体查询的方式。
<add>例如,当屏幕小于或大于媒体查询所设置的值,通过改变变量的值,那么应用了变量的元素样式都会得到响应修改。
<add></section>
<ide>
<ide> ## Instructions
<del><section id="instructions">在<code>media query</code>的<code>:root</code>选择器中,对其进行更改,以便重新定义<code>--penguin-size</code>并赋值为<code>200px</code> 。此外,重新定义<code>--penguin-skin</code>并赋予其<code>black</code>值。然后调整预览大小以查看此更改的操作。 </section>
<add><section id='instructions'>
<add>在<code>media query(媒体查询)</code>声明的<code>:root</code>选择器里,重定义<code>--penguin-size</code>的值为 200px,且重定义<code>--penguin-skin</code>的值为<code>black</code>,然后通过缩放页面来查看是否生效。
<add></section>
<ide>
<ide> ## Tests
<ide> <section id='tests'>
<ide>
<ide> ```yml
<ide> tests:
<del> - text: '<code>:root</code>应该将<code>--penguin-size</code>变量重新分配给<code>200px</code> 。'
<del> testString: 'assert(code.match(/media\s*?\(\s*?max-width\s*?:\s*?350px\s*?\)\s*?{[\s\S]*:root\s*?{[\s\S]*--penguin-size\s*?:\s*?200px\s*?;[\s\S]*}[\s\S]*}/gi), "<code>:root</code> should reassign the <code>--penguin-size</code> variable to <code>200px</code>.");'
<del> - text: '<code>:root</code>应该将<code>--penguin-skin</code>变量重新分配给<code>black</code> 。'
<del> testString: 'assert(code.match(/media\s*?\(\s*?max-width\s*?:\s*?350px\s*?\)\s*?{[\s\S]*:root\s*?{[\s\S]*--penguin-skin\s*?:\s*?black\s*?;[\s\S]*}[\s\S]*}/gi), "<code>:root</code> should reassign the <code>--penguin-skin</code> variable to <code>black</code>.");'
<add> - text: '<code>:root</code>中的<code>--penguin-size</code>值应为<code>200px</code>。'
<add> testString: 'assert(code.match(/media\s*?\(\s*?max-width\s*?:\s*?350px\s*?\)\s*?{[\s\S]*:root\s*?{[\s\S]*--penguin-size\s*?:\s*?200px\s*?;[\s\S]*}[\s\S]*}/gi), ''<code>:root</code>中的<code>--penguin-size</code>值应为<code>200px</code>。'');'
<add> - text: '<code>:root</code>中的<code>--penguin-skin</code>值应为<code>black</code>。'
<add> testString: 'assert(code.match(/media\s*?\(\s*?max-width\s*?:\s*?350px\s*?\)\s*?{[\s\S]*:root\s*?{[\s\S]*--penguin-skin\s*?:\s*?black\s*?;[\s\S]*}[\s\S]*}/gi), ''<code>:root</code>中的<code>--penguin-skin</code>值应为<code>black</code>。'');'
<ide>
<ide> ```
<ide>
<ide> tests:
<ide> --penguin-belly: white;
<ide> --penguin-beak: orange;
<ide> }
<del>
<add>
<ide> @media (max-width: 350px) {
<ide> :root {
<del>
<add>
<ide> /* add code below */
<del>
<add>
<ide> /* add code above */
<del>
<add>
<ide> }
<ide> }
<del>
<add>
<ide> .penguin {
<ide> position: relative;
<ide> margin: auto;
<ide> tests:
<ide> width: var(--penguin-size, 300px);
<ide> height: var(--penguin-size, 300px);
<ide> }
<del>
<add>
<ide> .right-cheek {
<ide> top: 15%;
<ide> left: 35%;
<ide> tests:
<ide> height: 70%;
<ide> border-radius: 70% 70% 60% 60%;
<ide> }
<del>
<add>
<ide> .left-cheek {
<ide> top: 15%;
<ide> left: 5%;
<ide> tests:
<ide> height: 70%;
<ide> border-radius: 70% 70% 60% 60%;
<ide> }
<del>
<add>
<ide> .belly {
<ide> top: 60%;
<ide> left: 2.5%;
<ide> tests:
<ide> height: 100%;
<ide> border-radius: 120% 120% 100% 100%;
<ide> }
<del>
<add>
<ide> .penguin-top {
<ide> top: 10%;
<ide> left: 25%;
<ide> tests:
<ide> height: 45%;
<ide> border-radius: 70% 70% 60% 60%;
<ide> }
<del>
<add>
<ide> .penguin-bottom {
<ide> top: 40%;
<ide> left: 23.5%;
<ide> tests:
<ide> height: 45%;
<ide> border-radius: 70% 70% 100% 100%;
<ide> }
<del>
<add>
<ide> .right-hand {
<ide> top: 5%;
<ide> left: 25%;
<ide> tests:
<ide> transform-origin:0% 0%;
<ide> animation-timing-function: linear;
<ide> }
<del>
<add>
<ide> @keyframes wave {
<ide> 10% {
<ide> transform: rotate(110deg);
<ide> tests:
<ide> }
<ide> 30% {
<ide> transform: rotate(110deg);
<del> }
<add> }
<ide> 40% {
<ide> transform: rotate(130deg);
<del> }
<add> }
<ide> }
<del>
<add>
<ide> .left-hand {
<ide> top: 0%;
<ide> left: 75%;
<ide> tests:
<ide> transform: rotate(-45deg);
<ide> z-index: -1;
<ide> }
<del>
<add>
<ide> .right-feet {
<ide> top: 85%;
<ide> left: 60%;
<ide> tests:
<ide> transform: rotate(-80deg);
<ide> z-index: -2222;
<ide> }
<del>
<add>
<ide> .left-feet {
<ide> top: 85%;
<ide> left: 25%;
<ide> tests:
<ide> transform: rotate(80deg);
<ide> z-index: -2222;
<ide> }
<del>
<add>
<ide> .right-eye {
<ide> top: 45%;
<ide> left: 60%;
<ide> tests:
<ide> height: 17%;
<ide> border-radius: 50%;
<ide> }
<del>
<add>
<ide> .left-eye {
<ide> top: 45%;
<ide> left: 25%;
<ide> tests:
<ide> height: 17%;
<ide> border-radius: 50%;
<ide> }
<del>
<add>
<ide> .sparkle {
<ide> top: 25%;
<ide> left:-23%;
<ide> tests:
<ide> height: 100%;
<ide> border-radius: 50%;
<ide> }
<del>
<add>
<ide> .blush-right {
<ide> top: 65%;
<ide> left: 15%;
<ide> tests:
<ide> height: 10%;
<ide> border-radius: 50%;
<ide> }
<del>
<add>
<ide> .blush-left {
<ide> top: 65%;
<ide> left: 70%;
<ide> tests:
<ide> height: 10%;
<ide> border-radius: 50%;
<ide> }
<del>
<add>
<ide> .beak-top {
<ide> top: 60%;
<ide> left: 40%;
<ide> tests:
<ide> height: 10%;
<ide> border-radius: 50%;
<ide> }
<del>
<add>
<ide> .beak-bottom {
<ide> top: 65%;
<ide> left: 42%;
<ide> tests:
<ide> height: 10%;
<ide> border-radius: 50%;
<ide> }
<del>
<add>
<ide> body {
<ide> background:#c6faf1;
<ide> }
<del>
<add>
<ide> .penguin * {
<ide> position: absolute;
<ide> }
<ide> tests:
<ide> <div class="beak-bottom"></div>
<ide> </div>
<ide> </div>
<del>
<ide> ```
<ide>
<ide> </div>
<ide> tests:
<ide> ## Solution
<ide> <section id='solution'>
<ide>
<add>
<ide> ```js
<ide> // solution required
<ide> ```
<add>
<ide> </section>
<add>
<ide>\ No newline at end of file
<ide><path>curriculum/challenges/chinese/01-responsive-web-design/basic-css/use-abbreviated-hex-code.chinese.md
<ide> id: bad87fee1348bd9aedf08719
<ide> title: Use Abbreviated Hex Code
<ide> challengeType: 0
<del>videoUrl: ''
<del>localeTitle: 使用缩写的十六进制代码
<add>videoUrl: 'https://scrimba.com/c/cRkpKAm'
<add>forumTopicId: 18338
<add>localTitle: 使用缩写的十六进制编码
<ide> ---
<ide>
<ide> ## Description
<del><section id="description">许多人对超过1600万种颜色的可能性感到不知所措。并且很难记住十六进制代码。幸运的是,你可以缩短它。例如,红色的十六进制代码<code>#FF0000</code>可以缩短为<code>#F00</code> 。这个缩短的形式给出一个红色数字,一个数字表示绿色,一个数字表示蓝色。这将可能的颜色总数减少到大约4,000。但浏览器会将<code>#FF0000</code>和<code>#F00</code>解释为完全相同的颜色。 </section>
<add><section id='description'>
<add>许多人对超过 1600 万种颜色的可能性感到不知所措,并且很难记住十六进制编码。幸运的是,它也提供缩写的方法。
<add>例如,红色的<code>#FF0000</code>十六进制编码可以缩写成<code>#F00</code>。在这种缩写形式里,三个数字分别代表着红(R),绿(G),蓝(B)颜色。
<add>这样,颜色的可能性减少到了大约 4000 种。且在浏览器里<code>#FF0000</code>和<code>#F00</code>完全是同一种颜色。
<add></section>
<ide>
<ide> ## Instructions
<del><section id="instructions">继续,尝试使用缩写的十六进制代码为正确的元素着色。 <table class="table table-striped"><tbody><tr><th>颜色</th><th>短十六进制代码</th></tr><tr><td>青色</td><td> <code>#0FF</code> </td> </tr><tr><td>绿色</td><td> <code>#0F0</code> </td> </tr><tr><td>红</td><td> <code>#F00</code> </td> </tr><tr><td>紫红色</td><td> <code>#F0F</code> </td> </tr></tbody></table></section>
<add><section id='instructions'>
<add>接下来,使用缩写的十六进制编码给元素设置正确的颜色。
<add><table class='table table-striped'><tr><th>Color</th><th>Short Hex Code</th></tr><tr><td>Cyan</td><td><code>#0FF</code></td></tr><tr><td>Green</td><td><code>#0F0</code></td></tr><tr><td>Red</td><td><code>#F00</code></td></tr><tr><td>Fuchsia</td><td><code>#F0F</code></td></tr></table>
<add></section>
<ide>
<ide> ## Tests
<ide> <section id='tests'>
<ide>
<ide> ```yml
<ide> tests:
<del> - text: 给你的<code>h1</code>元素添加<code>I am red!</code>的文本<code>I am red!</code> <code>color</code>红色。
<del> testString: 'assert($(".red-text").css("color") === "rgb(255, 0, 0)", "Give your <code>h1</code> element with the text <code>I am red!</code> the <code>color</code> red.");'
<del> - text: '使用缩写<code>hex code</code>表示红色而不是十六进制代码<code>#FF0000</code> 。'
<del> testString: 'assert(code.match(/\.red-text\s*?{\s*?color:\s*?#F00\s*?;\s*?}/gi), "Use the abbreviate <code>hex code</code> for the color red instead of the hex code <code>#FF0000</code>.");'
<del> - text: 给你的<code>h1</code>元素添加<code>I am green!</code>的文本<code>I am green!</code> <code>color</code>绿色。
<del> testString: 'assert($(".green-text").css("color") === "rgb(0, 255, 0)", "Give your <code>h1</code> element with the text <code>I am green!</code> the <code>color</code> green.");'
<del> - text: '使用缩写的<code>hex code</code>表示绿色而不是十六进制代码<code>#00FF00</code> 。'
<del> testString: 'assert(code.match(/\.green-text\s*?{\s*?color:\s*?#0F0\s*?;\s*?}/gi), "Use the abbreviated <code>hex code</code> for the color green instead of the hex code <code>#00FF00</code>.");'
<del> - text: 给你的<code>h1</code>元素添加<code>I am cyan!</code>文字<code>I am cyan!</code>在<code>color</code>青色。
<del> testString: 'assert($(".cyan-text").css("color") === "rgb(0, 255, 255)", "Give your <code>h1</code> element with the text <code>I am cyan!</code> the <code>color</code> cyan.");'
<del> - text: '使用缩写的<code>hex code</code>代替十六进制代码<code>#00FFFF</code> 。'
<del> testString: 'assert(code.match(/\.cyan-text\s*?{\s*?color:\s*?#0FF\s*?;\s*?}/gi), "Use the abbreviated <code>hex code</code> for the color cyan instead of the hex code <code>#00FFFF</code>.");'
<del> - text: 给你的<code>h1</code>元素文字<code>I am fuchsia!</code> <code>color</code>紫红色。
<del> testString: 'assert($(".fuchsia-text").css("color") === "rgb(255, 0, 255)", "Give your <code>h1</code> element with the text <code>I am fuchsia!</code> the <code>color</code> fuchsia.");'
<del> - text: '使用缩写的<code>hex code</code>作为颜色的紫红色而不是十六进制代码<code>#FF00FF</code> 。'
<del> testString: 'assert(code.match(/\.fuchsia-text\s*?{\s*?color:\s*?#F0F\s*?;\s*?}/gi), "Use the abbreviated <code>hex code</code> for the color fuchsia instead of the hex code <code>#FF00FF</code>.");'
<add> - text: '文本内容为<code>I am red!</code>的<code>h1</code>元素的字体颜色应该为<code>red</code>。'
<add> testString: assert($('.red-text').css('color') === 'rgb(255, 0, 0)', '文本内容为<code>I am red!</code>的<code>h1</code>元素的字体颜色应该为<code>red</code>。');
<add> - text: '要使用缩写的<code>red</code>的<code>十六进制编码</code>,而不是<code>#FF0000</code>。'
<add> testString: 'assert(code.match(/\.red-text\s*?{\s*?color:\s*?#F00\s*?;\s*?}/gi), ''要使用缩写的<code>red</code>的<code>十六进制编码</code>,而不是<code>#FF0000</code>。'');'
<add> - text: '文本内容为<code>I am green!</code>的<code>h1</code>元素的字体颜色应该为<code>green</code>。'
<add> testString: assert($('.green-text').css('color') === 'rgb(0, 255, 0)', '文本内容为<code>I am green!</code>的<code>h1</code>元素的字体颜色应该为<code>green</code>。');
<add> - text: '要使用缩写的<code>green</code>的<code>十六进制编码</code>,而不是<code>#00FF00</code>的十六进制编码。'
<add> testString: 'assert(code.match(/\.green-text\s*?{\s*?color:\s*?#0F0\s*?;\s*?}/gi), ''要使用缩写的<code>green</code>的<code>十六进制编码</code>,而不是<code>#00FF00</code>。'');'
<add> - text: '文本内容为<code>I am cyan!</code>的<code>h1</code>元素的字体颜色应该为<code>cyan</code>。'
<add> testString: assert($('.cyan-text').css('color') === 'rgb(0, 255, 255)', '文本内容为<code>I am cyan!</code>的<code>h1</code>元素的字体颜色应该为<code>cyan</code>。');
<add> - text: '要使用缩写的<code>cyan</code>的<code>十六进制编码</code>,而不是<code>#00FFFF</code>的十六进制编码。'
<add> testString: 'assert(code.match(/\.cyan-text\s*?{\s*?color:\s*?#0FF\s*?;\s*?}/gi), ''要使用缩写的<code>cyan</code>的<code>十六进制编码</code>,而不是<code>#00FFFF</code>。'');'
<add> - text: '文本内容为<code>I am fuchsia!</code>的<code>h1</code>元素的字体颜色应该为<code>fuchsia</code>。'
<add> testString: assert($('.fuchsia-text').css('color') === 'rgb(255, 0, 255)', '文本内容为<code>I am fuchsia!</code>的<code>h1</code>元素的字体颜色应该为<code>fuchsia</code>。');
<add> - text: '要使用缩写的<code>fuchsia</code>的<code>十六进制编码</code>,而不是<code>#FF00FF</code>的十六进制编码。'
<add> testString: 'assert(code.match(/\.fuchsia-text\s*?{\s*?color:\s*?#F0F\s*?;\s*?}/gi), ''要使用缩写的<code>fuchsia</code>的<code>十六进制编码</code>,而不是<code>#FF00FF</code>。'');'
<ide>
<ide> ```
<ide>
<ide> tests:
<ide> <h1 class="cyan-text">I am cyan!</h1>
<ide>
<ide> <h1 class="green-text">I am green!</h1>
<del>
<ide> ```
<ide>
<ide> </div>
<ide> tests:
<ide> ## Solution
<ide> <section id='solution'>
<ide>
<del>```js
<add>```html
<ide> // solution required
<ide> ```
<add>
<ide> </section>
<add>
<ide>\ No newline at end of file
<ide><path>curriculum/challenges/chinese/01-responsive-web-design/basic-css/use-an-id-attribute-to-style-an-element.chinese.md
<ide> id: bad87dee1348bd9aede07836
<ide> title: Use an id Attribute to Style an Element
<ide> challengeType: 0
<del>videoUrl: ''
<del>localeTitle: 使用id属性为元素设置样式
<add>videoUrl: 'https://scrimba.com/c/cakyZfL'
<add>forumTopicId: 18339
<add>localTitle: 使用 id 属性来设定元素的样式
<ide> ---
<ide>
<ide> ## Description
<del><section id="description">关于<code>id</code>属性的一个很酷的事情是,像类一样,你可以使用CSS来设置它们的样式。但是, <code>id</code>不可重用,只应应用于一个元素。 <code>id</code>也具有比类更高的特异性(重要性),因此如果两者都应用于同一元素并且具有冲突的样式,则将应用<code>id</code>的样式。下面是一个示例,说明如何使用<code>cat-photo-element</code>的<code>id</code>属性获取<code>cat-photo-element</code>并为其指定绿色的背景颜色。在你的<code>style</code>元素中: <blockquote> #cat-photo-element { <br>背景颜色:绿色; <br> } </blockquote>请注意,在<code>style</code>元素中,您始终通过放置a来引用类<code>.</code>在他们的名字前面。你总是通过在他们的名字前放一个<code>#</code>来引用id。 </section>
<add><section id='description'>
<add>通过<code>id</code>属性,你可以做一些很酷的事情,例如,就像 class 一样,你可以使用 CSS 来设置他们的样式
<add>可是,<code>id</code>不可以重用,只应用于一个元素上。同时,在 CSS 里,<code>id</code>的优先级要高于<code>class</code>,如果一个元素同时应用了<code>class</code>和<code>id</code>,并设置样式有冲突,会优先应用<code>id</code>的样式。
<add>选择<code>id</code>为<code>cat-photo-element</code>的元素,并设置它的背景样式为<code>green</code>,可以在你的<code>style</code>标签里这样写:
<add>
<add>```css
<add>#cat-photo-element {
<add> background-color: green;
<add>}
<add>```
<add>
<add>注意在<code>style</code>标签里,声明 class 的时候必须在名字前插入<code>.</code>符号。同样,在声明 id 的时候,也必须在名字前插入<code>#</code>符号。
<add></section>
<ide>
<ide> ## Instructions
<del><section id="instructions">尝试提供您的表单,该表单现在具有<code>cat-photo-form</code>的<code>id</code>属性,绿色背景。 </section>
<add><section id='instructions'>
<add>尝试给含有<code>cat-photo-form</code>id属性的<code>form</code>表单的背景颜色设置为<code>green</code>。
<add></section>
<ide>
<ide> ## Tests
<ide> <section id='tests'>
<ide>
<ide> ```yml
<ide> tests:
<del> - text: 为<code>form</code>元素添加<code>cat-photo-form</code>的id。
<del> testString: 'assert($("form").attr("id") === "cat-photo-form", "Give your <code>form</code> element the id of <code>cat-photo-form</code>.");'
<del> - text: 您的<code>form</code>元素应具有绿色的<code>background-color</code> 。
<del> testString: 'assert($("#cat-photo-form").css("background-color") === "rgb(0, 128, 0)", "Your <code>form</code> element should have the <code>background-color</code> of green.");'
<del> - text: 确保您的<code>form</code>元素具有<code>id</code>属性。
<del> testString: 'assert(code.match(/<form.*cat-photo-form.*>/gi) && code.match(/<form.*cat-photo-form.*>/gi).length > 0, "Make sure your <code>form</code> element has an <code>id</code> attribute.");'
<del> - text: 不要为<code>form</code>任何<code>class</code>或<code>style</code>属性。
<del> testString: 'assert(!code.match(/<form.*style.*>/gi) && !code.match(/<form.*class.*>/gi), "Do not give your <code>form</code> any <code>class</code> or <code>style</code> attributes.");'
<add> - text: '设置<code>form</code>元素的 id 为<code>cat-photo-form</code>。'
<add> testString: assert($("form").attr("id") === "cat-photo-form", '设置<code>form</code>元素的 id 为<code>cat-photo-form</code>。');
<add> - text: '你的<code>form</code>元素应该含有<code>background-color</code>css 属性并且值为 <code>green</code>。'
<add> testString: assert($("#cat-photo-form").css("background-color") === "rgb(0, 128, 0)", '你的<code>form</code>元素应该含有<code>background-color</code>css 属性并且值为 <code>green</code>。');
<add> - text: '确保你的<code>form</code>元素含有<code>id</code>属性。'
<add> testString: assert(code.match(/<form.*cat-photo-form.*>/gi) && code.match(/<form.*cat-photo-form.*>/gi).length > 0, '确保你的<code>form</code>元素含有<code>id</code>属性。');
<add> - text: '不要在<code>form</code>元素上添加其他<code>class</code>属性或者<code>style</code>行内样式。'
<add> testString: assert(!code.match(/<form.*style.*>/gi) && !code.match(/<form.*class.*>/gi), '不要在<code>form</code>元素上添加其他<code>class</code>属性或者<code>style</code>行内样式。');
<ide>
<ide> ```
<ide>
<ide> tests:
<ide>
<ide> <h2 class="red-text">CatPhotoApp</h2>
<ide> <main>
<del> <p class="red-text">Click here to view more <a href="#">cat photos</a>.</p>
<del>
<del> <a href="#"><img class="smaller-image thick-green-border" src="https://bit.ly/fcc-relaxing-cat" alt="A cute orange cat lying on its back."></a>
<del>
<add>
<add> <a href="#"><img class="smaller-image thick-green-border" src="https://bit.ly/fcc-relaxing-cat" alt="一只仰卧着的萌猫"></a>
<add>
<ide> <div class="silver-background">
<del> <p>Things cats love:</p>
<add> <p>猫咪最喜欢的三件东西:</p>
<ide> <ul>
<del> <li>cat nip</li>
<del> <li>laser pointers</li>
<del> <li>lasagna</li>
<add> <li>猫薄荷</li>
<add> <li>激光笔</li>
<add> <li>千层饼</li>
<ide> </ul>
<del> <p>Top 3 things cats hate:</p>
<add> <p>猫咪最讨厌的三件东西:</p>
<ide> <ol>
<del> <li>flea treatment</li>
<del> <li>thunder</li>
<del> <li>other cats</li>
<add> <li>跳蚤</li>
<add> <li>打雷</li>
<add> <li>同类</li>
<ide> </ol>
<ide> </div>
<del>
<add>
<ide> <form action="/submit-cat-photo" id="cat-photo-form">
<del> <label><input type="radio" name="indoor-outdoor" checked> Indoor</label>
<del> <label><input type="radio" name="indoor-outdoor"> Outdoor</label><br>
<del> <label><input type="checkbox" name="personality" checked> Loving</label>
<del> <label><input type="checkbox" name="personality"> Lazy</label>
<del> <label><input type="checkbox" name="personality"> Energetic</label><br>
<del> <input type="text" placeholder="cat photo URL" required>
<del> <button type="submit">Submit</button>
<add> <label><input type="radio" name="indoor-outdoor">室内</label>
<add> <label><input type="radio" name="indoor-outdoor">室外</label><br>
<add> <label><input type="checkbox" name="personality">忠诚</label>
<add> <label><input type="checkbox" name="personality">懒惰</label>
<add> <label><input type="checkbox" name="personality">积极</label><br>
<add> <input type="text" placeholder="猫咪图片地址" required>
<add> <button type="submit">提交</button>
<ide> </form>
<ide> </main>
<del>
<ide> ```
<ide>
<ide> </div>
<ide> tests:
<ide> ## Solution
<ide> <section id='solution'>
<ide>
<del>```js
<add>```html
<ide> // solution required
<ide> ```
<add>
<ide> </section>
<add>
<ide>\ No newline at end of file
<ide><path>curriculum/challenges/chinese/01-responsive-web-design/basic-css/use-attribute-selectors-to-style-elements.chinese.md
<ide> id: 58c383d33e2e3259241f3076
<ide> title: Use Attribute Selectors to Style Elements
<ide> challengeType: 0
<del>videoUrl: ''
<del>localeTitle: 使用属性选择器来设置样式元素
<add>videoUrl: 'https://scrimba.com/c/cnpymfJ'
<add>forumTopicId: 301092
<add>localTitle: 使用属性选择器来设置元素的样式
<ide> ---
<ide>
<ide> ## Description
<del><section id="description">您已经为要特定样式的元素提供了<code>id</code>或<code>class</code>属性。这些被称为ID和类选择器。您可以使用其他CSS选择器来选择要设置样式的自定义元素组。让我们再次带出CatPhotoApp来练习使用CSS选择器。对于此挑战,您将使用<code>[attr=value]</code>属性选择器设置CatPhotoApp中复选框的样式。此选择器使用特定属性值匹配和设置元素样式。例如,下面的代码使用属性<code>type</code>和相应的<code>radio</code>值更改所有元素的边距: <blockquote> [type ='radio'] { <br>保证金:20px 0px 20px 0px; <br> } </blockquote></section>
<add><section id='description'>
<add>你已经通过设置元素的<code>id</code>和<code>class</code>,来显示你想要的样式,而它们也被分别叫做 ID 选择器和 Class 选择器。另外,也还有其他的 CSS 选择器,可以让我们给特定的元素设置样式。
<add>让我们再次通过猫咪图片项目来练习 CSS 选择器。
<add>在这个挑战里,你会使用<code>[attr=value]</code>属性选择器修改复选框的样式。这个选择器使用特定的属性值来匹配和设置元素样式。例如,下面的代码会改变所有<code>type</code>为<code>radio</code>的元素的外边距。
<add>
<add>```css
<add>[type='radio'] {
<add> margin: 20px 0px 20px 0px;
<add>}
<add>```
<add>
<add></section>
<ide>
<ide> ## Instructions
<del><section id="instructions">使用<code>type</code>属性选择器,尝试在CatPhotoApp中为复选框提供10px的上边距和15px的下边距。 </section>
<add><section id='instructions'>
<add>使用<code>type</code>属性选择器,尝试改变复选框的上外边距为 10px,下外边距为 15px。
<add></section>
<ide>
<ide> ## Tests
<ide> <section id='tests'>
<ide>
<ide> ```yml
<ide> tests:
<del> - text: 应使用<code>type</code>属性选择器来选中复选框。
<del> testString: 'assert(code.match(/<style>[\s\S]*?\[type=("|")checkbox\1\]\s*?{[\s\S]*?}[\s\S]*?<\/style>/gi),"The <code>type</code> attribute selector should be used to select the checkboxes.");'
<del> - text: 复选框的顶部边距应为10px。
<del> testString: 'assert((function() {var count=0; $("[type="checkbox"]").each(function() { if($(this).css("marginTop") === "10px") {count++;}});return (count===3)}()),"The top margins of the checkboxes should be 10px.");'
<del> - text: 复选框的下边距应为15px。
<del> testString: 'assert((function() {var count=0; $("[type="checkbox"]").each(function() { if($(this).css("marginBottom") === "15px") {count++;}});return (count===3)}()),"The bottom margins of the checkboxes should be 15px.");'
<add> - text: '使用<code>type</code>属性选择器来匹配复选框。'
<add> testString: assert(code.match(/<style>[\s\S]*?\[type=("|')checkbox\1\]\s*?{[\s\S]*?}[\s\S]*?<\/style>/gi),'使用<code>type</code>属性选择器来匹配复选框。');
<add> - text: '复选框的上外边距应为 10px。'
<add> testString: assert((function() {var count=0; $("[type='checkbox']").each(function() { if($(this).css('marginTop') === '10px') {count++;}});return (count===3)}()),'复选框的上外边距应为 10px。');
<add> - text: '复选框的下外边距应为 15px。'
<add> testString: assert((function() {var count=0; $("[type='checkbox']").each(function() { if($(this).css('marginBottom') === '15px') {count++;}});return (count===3)}()),'复选框的下外边距应为 15px。');
<ide>
<ide> ```
<ide>
<ide> tests:
<ide>
<ide> <h2 class="red-text">CatPhotoApp</h2>
<ide> <main>
<del> <p class="red-text">Click here to view more <a href="#">cat photos</a>.</p>
<del>
<del> <a href="#"><img class="smaller-image thick-green-border" src="https://bit.ly/fcc-relaxing-cat" alt="A cute orange cat lying on its back."></a>
<del>
<add> <p class="red-text">点击查看更多<a href="#">猫图</a>.</p>
<add>
<add> <a href="#"><img src="https://bit.ly/fcc-relaxing-cat" alt="一只仰卧着的萌猫" class="smaller-image thick-green-border"></a>
<add>
<ide> <div class="silver-background">
<del> <p>Things cats love:</p>
<add> <p>猫咪最喜欢的三件东西:</p>
<ide> <ul>
<del> <li>cat nip</li>
<del> <li>laser pointers</li>
<del> <li>lasagna</li>
<add> <li>猫薄荷</li>
<add> <li>激光笔</li>
<add> <li>千层饼</li>
<ide> </ul>
<del> <p>Top 3 things cats hate:</p>
<add> <p>猫咪最讨厌的三件东西:</p>
<ide> <ol>
<del> <li>flea treatment</li>
<del> <li>thunder</li>
<del> <li>other cats</li>
<add> <li>跳蚤</li>
<add> <li>打雷</li>
<add> <li>同类</li>
<ide> </ol>
<ide> </div>
<del>
<add>
<ide> <form action="/submit-cat-photo" id="cat-photo-form">
<del> <label><input type="radio" name="indoor-outdoor" checked> Indoor</label>
<del> <label><input type="radio" name="indoor-outdoor"> Outdoor</label><br>
<del> <label><input type="checkbox" name="personality" checked> Loving</label>
<del> <label><input type="checkbox" name="personality"> Lazy</label>
<del> <label><input type="checkbox" name="personality"> Energetic</label><br>
<del> <input type="text" placeholder="cat photo URL" required>
<del> <button type="submit">Submit</button>
<add> <label><input type="radio" name="indoor-outdoor">室内</label>
<add> <label><input type="radio" name="indoor-outdoor">室外</label><br>
<add> <label><input type="checkbox" name="personality">忠诚</label>
<add> <label><input type="checkbox" name="personality">懒惰</label>
<add> <label><input type="checkbox" name="personality">积极</label><br>
<add> <input type="text" placeholder="猫咪图片地址" required>
<add> <button type="submit">提交</button>
<ide> </form>
<ide> </main>
<del>
<ide> ```
<ide>
<ide> </div>
<ide> tests:
<ide> ## Solution
<ide> <section id='solution'>
<ide>
<del>```js
<add>```html
<ide> // solution required
<ide> ```
<add>
<ide> </section>
<add>
<ide>\ No newline at end of file
<ide><path>curriculum/challenges/chinese/01-responsive-web-design/basic-css/use-clockwise-notation-to-specify-the-margin-of-an-element.chinese.md
<ide> id: bad87fee1348bd9afdf08726
<ide> title: Use Clockwise Notation to Specify the Margin of an Element
<ide> challengeType: 0
<del>videoUrl: ''
<del>localeTitle: 使用顺时针符号指定元素的边距
<add>videoUrl: 'https://scrimba.com/c/cnpybAd'
<add>forumTopicId: 18345
<add>localTitle: 使用顺时针方向指定元素的外边距
<ide> ---
<ide>
<ide> ## Description
<del><section id="description">让我们再试一次,但这次有<code>margin</code> 。不是单独指定元素的<code>margin-top</code> , <code>margin-right</code> , <code>margin-bottom</code>和<code>margin-left</code>属性,而是可以在一行中指定它们,如下所示: <code>margin: 10px 20px 10px 20px;</code>这四个值的工作方式类似于时钟:top,right,bottom,left,并且将产生与使用边特定边距指令完全相同的结果。 </section>
<add><section id='description'>
<add>让我们再试一次,不过这一次轮到<code>margin</code>了。
<add>同样,每个方向的外边距值可以在<code>margin</code>属性里面汇总声明,来代替分别声明<code>margin-top</code>,<code>margin-right</code>,<code>margin-bottom</code>和<code>margin-left</code>属性的方式,代码如下:
<add><code>margin: 10px 20px 10px 20px;</code>
<add>这四个值按顺时针排序:上,右,下,左,并且设置的效果等同于特定声明每一个方向的<code>margin</code>。
<add></section>
<ide>
<ide> ## Instructions
<del><section id="instructions">使用<code>Clockwise Notation</code>为<code>blue-box</code>的元素在其顶部和左侧提供<code>40px</code>的边距,但在其底部和右侧仅为<code>20px</code> 。 </section>
<add><section id='instructions'>
<add>按照顺时针顺序,给".blue-box" class的上外边距以及左外边距设置为<code>40px</code>,右外边距和下外边距则设置为<code>20px</code>。
<add></section>
<ide>
<ide> ## Tests
<ide> <section id='tests'>
<ide>
<ide> ```yml
<ide> tests:
<del> - text: 你的<code>blue-box</code>类应该给元素顶部<code>40px</code>的<code>margin</code> 。
<del> testString: 'assert($(".blue-box").css("margin-top") === "40px", "Your <code>blue-box</code> class should give the top of elements <code>40px</code> of <code>margin</code>.");'
<del> - text: 您的<code>blue-box</code>类应该赋予元素<code>20px</code> <code>margin</code>的权利。
<del> testString: 'assert($(".blue-box").css("margin-right") === "20px", "Your <code>blue-box</code> class should give the right of elements <code>20px</code> of <code>margin</code>.");'
<del> - text: 你的<code>blue-box</code>类应该给元素的底部提供<code>20px</code>的<code>margin</code> 。
<del> testString: 'assert($(".blue-box").css("margin-bottom") === "20px", "Your <code>blue-box</code> class should give the bottom of elements <code>20px</code> of <code>margin</code>.");'
<del> - text: 你的<code>blue-box</code>类应该给元素左边<code>40px</code>的<code>margin</code> 。
<del> testString: 'assert($(".blue-box").css("margin-left") === "40px", "Your <code>blue-box</code> class should give the left of elements <code>40px</code> of <code>margin</code>.");'
<add> - text: '<code>blue-box</code> class 的上外边距应为<code>40px</code>。'
<add> testString: assert($(".blue-box").css("margin-top") === "40px", '<code>blue-box</code> class 的上外边距应为<code>40px</code>。');
<add> - text: '<code>blue-box</code> class 的右外边距应为<code>20px</code>。'
<add> testString: assert($(".blue-box").css("margin-right") === "20px", '<code>blue-box</code> class 的右外边距应为<code>20px</code>。');
<add> - text: '<code>blue-box</code> class 的下外边距应为<code>20px</code>。'
<add> testString: assert($(".blue-box").css("margin-bottom") === "20px", '<code>blue-box</code> class 的下外边距应为<code>20px</code>。');
<add> - text: '<code>blue-box</code> class 的左外边距应为<code>40px</code>。'
<add> testString: assert($(".blue-box").css("margin-left") === "40px", '<code>blue-box</code> class 的左外边距应为<code>40px</code>。');
<ide>
<ide> ```
<ide>
<ide> tests:
<ide> background-color: yellow;
<ide> padding: 20px 40px 20px 40px;
<ide> }
<del>
<add>
<ide> .red-box {
<ide> background-color: crimson;
<ide> color: #fff;
<ide> tests:
<ide> <h5 class="box red-box">padding</h5>
<ide> <h5 class="box blue-box">padding</h5>
<ide> </div>
<del>
<ide> ```
<ide>
<ide> </div>
<ide>
<del>
<del>
<ide> </section>
<ide>
<ide> ## Solution
<ide> <section id='solution'>
<ide>
<del>```js
<add>```html
<ide> // solution required
<ide> ```
<ide> </section>
<add>
<ide>\ No newline at end of file
<ide><path>curriculum/challenges/chinese/01-responsive-web-design/basic-css/use-clockwise-notation-to-specify-the-padding-of-an-element.chinese.md
<ide> id: bad87fee1348bd9aedf08826
<ide> title: Use Clockwise Notation to Specify the Padding of an Element
<ide> challengeType: 0
<del>videoUrl: ''
<del>localeTitle: 使用顺时针符号指定元素的填充
<add>videoUrl: 'https://scrimba.com/c/cB7mBS9'
<add>forumTopicId: 18346
<add>localTitle: 使用顺时针方向指定元素的内边距
<ide> ---
<ide>
<ide> ## Description
<del><section id="description">不是单独指定元素的<code>padding-top</code> , <code>padding-right</code> , <code>padding-bottom</code>和<code>padding-left</code>属性,而是可以在一行中指定它们,如下所示: <code>padding: 10px 20px 10px 20px;</code>这四个值的工作方式类似于时钟:顶部,右侧,底部,左侧,并且将产生与使用侧面特定填充指令完全相同的结果。 </section>
<add><section id='description'>
<add>如果不想每次都要分别声明<code>padding-top</code>,<code>padding-right</code>,<code>padding-bottom</code>和<code>padding-left</code>属性,可以把它们汇总在<code>padding</code>属性里面声明,如下:
<add><code>padding: 10px 20px 10px 20px;</code>
<add>这四个值按顺时针排序:上,右,下,左,并且设置的效果等同于特定声明每一个方向的<code>padding</code>。
<add></section>
<ide>
<ide> ## Instructions
<del><section id="instructions">使用顺时针符号为“.blue-box”类在其顶部和左侧提供<code>40px</code>的<code>padding</code> ,但在其底部和右侧仅为<code>20px</code> 。 </section>
<add><section id='instructions'>
<add>按照顺时针顺序,给".blue-box" class的上内边距以及左内边距设置为<code>40px</code>,右内边距和下内边距则设置为<code>20px</code>。
<add></section>
<ide>
<ide> ## Tests
<ide> <section id='tests'>
<ide>
<ide> ```yml
<ide> tests:
<del> - text: 你的<code>blue-box</code>类应该给出<code>40px</code> <code>padding</code>元素的顶部。
<del> testString: 'assert($(".blue-box").css("padding-top") === "40px", "Your <code>blue-box</code> class should give the top of elements <code>40px</code> of <code>padding</code>.");'
<del> - text: 你的<code>blue-box</code>类应该给出<code>20px</code> <code>padding</code>元素的权利。
<del> testString: 'assert($(".blue-box").css("padding-right") === "20px", "Your <code>blue-box</code> class should give the right of elements <code>20px</code> of <code>padding</code>.");'
<del> - text: 你的<code>blue-box</code>类应该给元素的底部提供<code>20px</code>的<code>padding</code> 。
<del> testString: 'assert($(".blue-box").css("padding-bottom") === "20px", "Your <code>blue-box</code> class should give the bottom of elements <code>20px</code> of <code>padding</code>.");'
<del> - text: 你的<code>blue-box</code>类应该给元素左边<code>padding</code> <code>40px</code> 。
<del> testString: 'assert($(".blue-box").css("padding-left") === "40px", "Your <code>blue-box</code> class should give the left of elements <code>40px</code> of <code>padding</code>.");'
<del> - text: 您应该使用顺时针符号来设置<code>blue-box</code>类的填充。
<del> testString: 'assert(!/padding-top|padding-right|padding-bottom|padding-left/.test(code), "You should use the clockwise notation to set the padding of <code>blue-box</code> class.");'
<add> - text: '<code>blue-box</code> class 的上内边距应为<code>40px</code>。'
<add> testString: assert($(".blue-box").css("padding-top") === "40px", '<code>blue-box</code> class 的上内边距应为<code>40px</code>。');
<add> - text: '<code>blue-box</code> class 的右内边距应为<code>20px</code>。'
<add> testString: assert($(".blue-box").css("padding-right") === "20px", '<code>blue-box</code> class 的右内边距应为<code>40px</code>。');
<add> - text: '<code>blue-box</code> class 的下内边距应为<code>20px</code>。'
<add> testString: assert($(".blue-box").css("padding-bottom") === "20px", '<code>blue-box</code> class 的下内边距应为<code>20px</code>。');
<add> - text: '<code>blue-box</code> class 的左内边距应为<code>40px</code>。'
<add> testString: assert($(".blue-box").css("padding-left") === "40px", '<code>blue-box</code> class 的左内边距应为<code>40px</code>。');
<add> - text: '你应该按照顺时针排序,汇总声明的方式来设置<code>blue-box</code>的<code>padding</code>值。'
<add> testString: assert(!/padding-top|padding-right|padding-bottom|padding-left/.test(code), '你应该按照顺时针排序,汇总声明的方式来设置<code>blue-box</code>的<code>padding</code>值。');
<ide>
<ide> ```
<ide>
<ide> tests:
<ide> background-color: yellow;
<ide> padding: 20px 40px 20px 40px;
<ide> }
<del>
<add>
<ide> .red-box {
<ide> background-color: crimson;
<ide> color: #fff;
<ide> tests:
<ide> <h5 class="box red-box">padding</h5>
<ide> <h5 class="box blue-box">padding</h5>
<ide> </div>
<del>
<ide> ```
<ide>
<ide> </div>
<ide> tests:
<ide> ## Solution
<ide> <section id='solution'>
<ide>
<del>```js
<add>```html
<ide> // solution required
<ide> ```
<add>
<ide> </section>
<add>
<ide>\ No newline at end of file
<ide><path>curriculum/challenges/chinese/01-responsive-web-design/basic-css/use-css-selectors-to-style-elements.chinese.md
<ide> id: bad87fee1348bd9aedf08805
<ide> title: Use CSS Selectors to Style Elements
<ide> challengeType: 0
<del>videoUrl: ''
<del>localeTitle: 使用CSS选择器设置样式元素
<add>videoUrl: 'https://scrimba.com/c/cJKMBT2'
<add>forumTopicId: 18349
<add>localTitle: 使用元素选择器来设置元素的样式
<ide> ---
<ide>
<ide> ## Description
<del><section id="description">使用CSS,您可以使用数百种CSS <code>properties</code>来更改元素在页面上的显示方式。当您输入<code><h2 style="color: red;">CatPhotoApp</h2></code> ,您使用<code>inline CSS</code> (代表<code>Cascading Style Sheets</code>对单个<code>h2</code>元素进行<code>Cascading Style Sheets</code> 。这是指定元素样式的一种方法,但有一种更好的方法来应用<code>CSS</code> 。在代码的顶部,创建一个<code>style</code>块,如下所示: <blockquote> <风格> <br> </样式> </blockquote>在该样式块中,您可以为所有<code>h2</code>元素创建<code>CSS selector</code> 。例如,如果您希望所有<code>h2</code>元素都是红色,则可以添加如下所示的样式规则: <blockquote> <风格> <br> h2 {color:red;} <br> </样式> </blockquote>请注意,在每个元素的样式规则周围同时打开和关闭花括号( <code>{</code>和<code>}</code> )非常重要。您还需要确保元素的样式定义位于开始和结束样式标记之间。最后,请务必在每个元素的样式规则的末尾添加分号。 </section>
<add><section id='description'>
<add>在 CSS 中,页面样式的属性有几百个,但常用的不过几十个。
<add>通过行内样式<code><h2 style="color: red;">CatPhotoApp</h2></code>,就可以修改<code>h2</code>元素的颜色为红色。
<add>当我们只需要改变元素的某个样式时,行内样式最简单直观。当我们需要同时改变元素的很多样式时,<code>层叠样式表</code>往往是一个更好的选择。
<add>在代码的顶部,创建一个<code>style</code>声明区域,如下方所示:
<add>
<add>```html
<add><style>
<add></style>
<add>```
<add>
<add>在<code>style</code>样式声明区域内,可以创建一个<code>元素选择器</code>,应用于所有的<code>h2</code>元素。例如,如果你想所有<code>h2</code>元素变成红色,可以添加下方的样式规则:
<add>
<add>```html
<add><style>
<add> h2 {
<add> color: red;
<add> }
<add></style>
<add>```
<add>
<add>注意,在每个元素的样式声明区域里,左右花括号(<code>{</code> 和 <code>}</code>)一定要写全。你需要确保所有样式规则位于花括号之间,并且每条样式规则都以分号结束。
<add></section>
<ide>
<ide> ## Instructions
<del><section id="instructions">删除<code>h2</code>元素的样式属性,而不是创建CSS <code>style</code>块。添加必要的CSS以将所有<code>h2</code>元素变为蓝色。 </section>
<add><section id='instructions'>
<add>删除<code>h2</code>元素的行内样式,然后创建<code>style</code>样式声明区域,最后添加 CSS 样式规则使<code>h2</code>元素变为蓝色。
<add></section>
<ide>
<ide> ## Tests
<ide> <section id='tests'>
<ide>
<ide> ```yml
<ide> tests:
<del> - text: 从<code>h2</code>元素中删除style属性。
<del> testString: 'assert(!$("h2").attr("style"), "Remove the style attribute from your <code>h2</code> element.");'
<del> - text: 创建<code>style</code>元素。
<del> testString: 'assert($("style") && $("style").length > 1, "Create a <code>style</code> element.");'
<del> - text: 你的<code>h2</code>元素应该是蓝色的。
<del> testString: 'assert($("h2").css("color") === "rgb(0, 0, 255)", "Your <code>h2</code> element should be blue.");'
<del> - text: 确保样式表<code>h2</code>声明对分号和右括号有效。
<del> testString: 'assert(code.match(/h2\s*\{\s*color\s*:.*;\s*\}/g), "Ensure that your stylesheet <code>h2</code> declaration is valid with a semicolon and closing brace.");'
<del> - text: 确保所有<code>style</code>元素都有效并具有结束标记。
<del> testString: 'assert(code.match(/<\/style>/g) && code.match(/<\/style>/g).length === (code.match(/<style((\s)*((type|media|scoped|title|disabled)="[^"]*")?(\s)*)*>/g) || []).length, "Make sure all your <code>style</code> elements are valid and have a closing tag.");'
<add> - text: '删除<code>h2</code>元素的行内样式。'
<add> testString: assert(!$("h2").attr("style"), '删除<code>h2</code>元素的行内样式。');
<add> - text: '创建一个<code>style</code>样式声明区域。'
<add> testString: assert($("style") && $("style").length >= 1, '创建一个<code>style</code>样式声明区域。');
<add> - text: '<code>h2</code>元素颜色应为蓝色。'
<add> testString: assert($("h2").css("color") === "rgb(0, 0, 255)", '<code>h2</code>元素颜色应为蓝色。');
<add> - text: '确保<code>h2</code>选择器的内容被花括号所围绕,并且样式规则以分号结束。'
<add> testString: 'assert(code.match(/h2\s*\{\s*color\s*:.*;\s*\}/g), ''确保<code>h2</code>选择器的内容被花括号所围绕,并且样式规则以分号结束。'');'
<ide>
<ide> ```
<ide>
<ide> tests:
<ide> ```html
<ide> <h2 style="color: red;">CatPhotoApp</h2>
<ide> <main>
<del> <p>Click here to view more <a href="#">cat photos</a>.</p>
<del>
<del> <a href="#"><img src="https://bit.ly/fcc-relaxing-cat" alt="A cute orange cat lying on its back."></a>
<del>
<add> <p class="red-text">点击查看更多<a href="#">猫图</a>.</p>
<add>
<add> <a href="#"><img src="https://bit.ly/fcc-relaxing-cat" alt="一只仰卧着的萌猫"></a>
<add>
<ide> <div>
<del> <p>Things cats love:</p>
<add> <p>猫咪最喜欢的三件东西:</p>
<ide> <ul>
<del> <li>cat nip</li>
<del> <li>laser pointers</li>
<del> <li>lasagna</li>
<add> <li>猫薄荷</li>
<add> <li>激光笔</li>
<add> <li>千层饼</li>
<ide> </ul>
<del> <p>Top 3 things cats hate:</p>
<add> <p>猫咪最讨厌的三件东西:</p>
<ide> <ol>
<del> <li>flea treatment</li>
<del> <li>thunder</li>
<del> <li>other cats</li>
<add> <li>跳蚤</li>
<add> <li>打雷</li>
<add> <li>同类</li>
<ide> </ol>
<ide> </div>
<del>
<add>
<ide> <form action="/submit-cat-photo">
<del> <label><input type="radio" name="indoor-outdoor" checked> Indoor</label>
<del> <label><input type="radio" name="indoor-outdoor"> Outdoor</label><br>
<del> <label><input type="checkbox" name="personality" checked> Loving</label>
<del> <label><input type="checkbox" name="personality"> Lazy</label>
<del> <label><input type="checkbox" name="personality"> Energetic</label><br>
<del> <input type="text" placeholder="cat photo URL" required>
<del> <button type="submit">Submit</button>
<add> <label><input type="radio" name="indoor-outdoor">室内</label>
<add> <label><input type="radio" name="indoor-outdoor">室外</label><br>
<add> <label><input type="checkbox" name="personality">忠诚</label>
<add> <label><input type="checkbox" name="personality">懒惰</label>
<add> <label><input type="checkbox" name="personality">积极</label><br>
<add> <input type="text" placeholder="猫咪图片地址" required>
<add> <button type="submit">提交</button>
<ide> </form>
<ide> </main>
<del>
<ide> ```
<ide>
<ide> </div>
<ide> tests:
<ide> ## Solution
<ide> <section id='solution'>
<ide>
<del>```js
<add>```html
<ide> // solution required
<ide> ```
<ide> </section>
<add>
<ide>\ No newline at end of file
<ide><path>curriculum/challenges/chinese/01-responsive-web-design/basic-css/use-css-variables-to-change-several-elements-at-once.chinese.md
<ide> id: 5a9d725e424fe3d0e10cad10
<ide> title: Use CSS Variables to change several elements at once
<ide> challengeType: 0
<del>videoUrl: ''
<del>localeTitle: 使用CSS变量一次更改多个元素
<add>videoUrl: 'https://scrimba.com/c/c6bDECm'
<add>forumTopicId: 301093
<add>localTitle: 使用 CSS 变量一次更改多个元素
<ide> ---
<ide>
<ide> ## Description
<del><section id="description"> <dfn>CSS变量</dfn>是一种通过仅更改一个值来一次更改许多CSS样式属性的强大方法。按照以下说明查看如何仅更改三个值可以更改许多元素的样式。 </section>
<add><section id='description'>
<add><dfn>CSS 变量</dfn>是一种仅更改一个值,来一次性更改多个 CSS 样式属性的强大方法。
<add>按照下面指示的来做,我们只需要改变三个值,多个样式将会同时被修改。
<add></section>
<ide>
<ide> ## Instructions
<del><section id="instructions">在<code>penguin</code>类中,将<code>black</code>值更改为<code>gray</code> ,将<code>gray</code>值更改为<code>white</code> ,将<code>yellow</code>值更改为<code>orange</code> 。 </section>
<add><section id='instructions'>
<add>在<code>penguin</code>class 里,将<code>black</code>改为<code>gray</code>,<code>gray</code>改为<code>white</code>,<code>yellow</code>改为<code>orange</code>。
<add></section>
<ide>
<ide> ## Tests
<ide> <section id='tests'>
<ide>
<ide> ```yml
<ide> tests:
<del> - text: <code>penguin</code>类应声明<code>--penguin-skin</code>变量并将其指定为<code>gray</code> 。
<del> testString: 'assert(code.match(/.penguin\s*?{[\s\S]*--penguin-skin\s*?:\s*?gray\s*?;[\s\S]*}/gi), "<code>penguin</code> class should declare the <code>--penguin-skin</code> variable and assign it to <code>gray</code>.");'
<del> - text: <code>penguin</code>类应声明<code>--penguin-belly</code>变量并将其指定为<code>white</code> 。
<del> testString: 'assert(code.match(/.penguin\s*?{[\s\S]*--penguin-belly\s*?:\s*?white\s*?;[\s\S]*}/gi), "<code>penguin</code> class should declare the <code>--penguin-belly</code> variable and assign it to <code>white</code>.");'
<del> - text: <code>penguin</code>类应声明<code>--penguin-beak</code>变量并将其指定为<code>orange</code> 。
<del> testString: 'assert(code.match(/.penguin\s*?{[\s\S]*--penguin-beak\s*?:\s*?orange\s*?;[\s\S]*}/gi), "<code>penguin</code> class should declare the <code>--penguin-beak</code> variable and assign it to <code>orange</code>.");'
<add> - text: '<code>penguin</code> class 声明的<code>--penguin-skin</code>变量的值应为<code>gray</code>。'
<add> testString: 'assert(code.match(/.penguin\s*?{[\s\S]*--penguin-skin\s*?:\s*?gray\s*?;[\s\S]*}/gi), ''<code>penguin</code> class 声明的<code>--penguin-skin</code>变量的值应为<code>gray</code>。'');'
<add> - text: '<code>penguin</code> class 声明的<code>--penguin-belly</code>变量的值应为<code>white</code>。'
<add> testString: 'assert(code.match(/.penguin\s*?{[\s\S]*--penguin-belly\s*?:\s*?white\s*?;[\s\S]*}/gi), ''<code>penguin</code> class 声明的<code>--penguin-belly</code>变量的值应为<code>white</code>。'');'
<add> - text: '<code>penguin</code> class 声明的<code>--penguin-beak</code>变量的值应为<code>orange</code>。'
<add> testString: 'assert(code.match(/.penguin\s*?{[\s\S]*--penguin-beak\s*?:\s*?orange\s*?;[\s\S]*}/gi), ''<code>penguin</code> class 声明的<code>--penguin-beak</code>变量的值应为<code>orange</code>。'');'
<ide>
<ide> ```
<ide>
<ide> tests:
<ide> ```html
<ide> <style>
<ide> .penguin {
<del>
<add>
<ide> /* change code below */
<ide> --penguin-skin: black;
<ide> --penguin-belly: gray;
<ide> --penguin-beak: yellow;
<ide> /* change code above */
<del>
<add>
<ide> position: relative;
<ide> margin: auto;
<ide> display: block;
<ide> margin-top: 5%;
<ide> width: 300px;
<ide> height: 300px;
<ide> }
<del>
<add>
<ide> .penguin-top {
<ide> top: 10%;
<ide> left: 25%;
<ide> tests:
<ide> height: 45%;
<ide> border-radius: 70% 70% 60% 60%;
<ide> }
<del>
<add>
<ide> .penguin-bottom {
<ide> top: 40%;
<ide> left: 23.5%;
<ide> tests:
<ide> height: 45%;
<ide> border-radius: 70% 70% 100% 100%;
<ide> }
<del>
<add>
<ide> .right-hand {
<ide> top: 0%;
<ide> left: -5%;
<ide> tests:
<ide> transform: rotate(45deg);
<ide> z-index: -1;
<ide> }
<del>
<add>
<ide> .left-hand {
<ide> top: 0%;
<ide> left: 75%;
<ide> tests:
<ide> transform: rotate(-45deg);
<ide> z-index: -1;
<ide> }
<del>
<add>
<ide> .right-cheek {
<ide> top: 15%;
<ide> left: 35%;
<ide> tests:
<ide> height: 70%;
<ide> border-radius: 70% 70% 60% 60%;
<ide> }
<del>
<add>
<ide> .left-cheek {
<ide> top: 15%;
<ide> left: 5%;
<ide> tests:
<ide> height: 70%;
<ide> border-radius: 70% 70% 60% 60%;
<ide> }
<del>
<add>
<ide> .belly {
<ide> top: 60%;
<ide> left: 2.5%;
<ide> tests:
<ide> height: 100%;
<ide> border-radius: 120% 120% 100% 100%;
<ide> }
<del>
<add>
<ide> .right-feet {
<ide> top: 85%;
<ide> left: 60%;
<ide> tests:
<ide> height: 30%;
<ide> border-radius: 50% 50% 50% 50%;
<ide> transform: rotate(-80deg);
<del> z-index: -2222;
<add> z-index: -2222;
<ide> }
<del>
<add>
<ide> .left-feet {
<ide> top: 85%;
<ide> left: 25%;
<ide> tests:
<ide> height: 30%;
<ide> border-radius: 50% 50% 50% 50%;
<ide> transform: rotate(80deg);
<del> z-index: -2222;
<add> z-index: -2222;
<ide> }
<del>
<add>
<ide> .right-eye {
<ide> top: 45%;
<ide> left: 60%;
<ide> background: black;
<ide> width: 15%;
<ide> height: 17%;
<del> border-radius: 50%;
<add> border-radius: 50%;
<ide> }
<del>
<add>
<ide> .left-eye {
<ide> top: 45%;
<ide> left: 25%;
<ide> background: black;
<ide> width: 15%;
<ide> height: 17%;
<del> border-radius: 50%;
<add> border-radius: 50%;
<ide> }
<del>
<add>
<ide> .sparkle {
<ide> top: 25%;
<ide> left: 15%;
<ide> background: white;
<ide> width: 35%;
<ide> height: 35%;
<del> border-radius: 50%;
<add> border-radius: 50%;
<ide> }
<del>
<add>
<ide> .blush-right {
<ide> top: 65%;
<ide> left: 15%;
<ide> background: pink;
<ide> width: 15%;
<ide> height: 10%;
<del> border-radius: 50%;
<add> border-radius: 50%;
<ide> }
<del>
<add>
<ide> .blush-left {
<ide> top: 65%;
<ide> left: 70%;
<ide> background: pink;
<ide> width: 15%;
<ide> height: 10%;
<del> border-radius: 50%;
<add> border-radius: 50%;
<ide> }
<del>
<add>
<ide> .beak-top {
<ide> top: 60%;
<ide> left: 40%;
<ide> background: var(--penguin-beak, orange);
<ide> width: 20%;
<ide> height: 10%;
<del> border-radius: 50%;
<add> border-radius: 50%;
<ide> }
<del>
<add>
<ide> .beak-bottom {
<ide> top: 65%;
<ide> left: 42%;
<ide> background: var(--penguin-beak, orange);
<ide> width: 16%;
<ide> height: 10%;
<del> border-radius: 50%;
<add> border-radius: 50%;
<ide> }
<del>
<add>
<ide> body {
<ide> background:#c6faf1;
<ide> }
<del>
<add>
<ide> .penguin * {
<ide> position: absolute;
<ide> }
<ide> tests:
<ide> <div class="beak-bottom"></div>
<ide> </div>
<ide> </div>
<del>
<ide> ```
<ide>
<ide> </div>
<ide> tests:
<ide> ## Solution
<ide> <section id='solution'>
<ide>
<add>
<ide> ```js
<ide> // solution required
<ide> ```
<add>
<ide> </section>
<add>
<ide>\ No newline at end of file
<ide><path>curriculum/challenges/chinese/01-responsive-web-design/basic-css/use-hex-code-for-specific-colors.chinese.md
<ide> id: bad87fee1348bd9aedf08726
<ide> title: Use Hex Code for Specific Colors
<ide> challengeType: 0
<del>videoUrl: ''
<del>localeTitle: 使用Hex代码表示特定颜色
<add>videoUrl: 'https://scrimba.com/c/c8W9mHM'
<add>forumTopicId: 18350
<add>localTitle: 使用十六进制编码获得指定颜色
<ide> ---
<ide>
<ide> ## Description
<del><section id="description">您知道还有其他方法可以在CSS中表示颜色吗?其中一种方法称为十六进制代码,或简称为<code>hex code</code> 。我们通常使用<code>decimals</code>或基数为10的数字,每个数字使用符号0到9。 <code>Hexadecimals</code> (或<code>hex</code> )是16位数字。这意味着它使用十六个不同的符号。与小数一样,符号0-9表示0到9的值。然后A,B,C,D,E,F代表十到十五的值。总而言之,0到F可以用<code>hexadecimal</code>表示一个数字,总共给出16个可能值。您可以<a target="_blank" href="https://en.wikipedia.org/wiki/Hexadecimal">在此处</a>找到有关<a target="_blank" href="https://en.wikipedia.org/wiki/Hexadecimal">十六进制数的</a>更多信息。在CSS中,我们可以使用6个十六进制数字来表示颜色,红色(R),绿色(G)和蓝色(B)组件各有两个。例如, <code>#000000</code>是黑色,也是可能的最低值。您可以<a target="_blank" href="https://en.wikipedia.org/wiki/RGB_color_model">在此处</a>找到有关<a target="_blank" href="https://en.wikipedia.org/wiki/RGB_color_model">RGB颜色系统的</a>更多信息。 <blockquote>身体 { <br>颜色:#000000; <br> } </blockquote></section>
<add><section id='description'>
<add>你知道在 CSS 里面还有其他方式来代表颜色吗?其中一个方法叫做十六进制编码,简称<code>hex</code>。
<add>我们日常使用最多的计数方法,基于十进制,使用 0 到 9 数字来表示。而<code>十六进制编码</code>(<code>hex</code>)基于 16 位数字,它含有 16 种不同字符。十六进制与十进制一样,0-9 表示着 0 到 9 的值,不同的是,A,B,C,D,E,F 表示着十六进制 10 到 15 的值。总的来说,0 到 F 在<code>十六进制</code>里代表着数字,提供了 16 种可能性。你可以在<a target='_blank' href='https://zh.wikipedia.org/wiki/%E5%8D%81%E5%85%AD%E8%BF%9B%E5%88%B6'>这里</a>找到更多的相关信息。
<add>在 CSS 里面,我们可以用使用 6 个十六进制的数字来代表颜色,每两个数字控制一种颜色,分别是红(R),绿(G),蓝(B)。例如,<code>#000000</code>代表着黑色,同时也是最小的值。你可以在<a target='_blank' href='https://zh.wikipedia.org/wiki/%E4%B8%89%E5%8E%9F%E8%89%B2%E5%85%89%E6%A8%A1%E5%BC%8F'>这里</a>找到更多的相关信息。
<add>
<add>```css
<add>body {
<add> color: #000000;
<add>}
<add>```
<add>
<add></section>
<ide>
<ide> ## Instructions
<del><section id="instructions">更换字<code>black</code>在我们的<code>body</code>元素的背景色与它的<code>hex code</code>表示, <code>#000000</code> 。 </section>
<add><section id='instructions'>
<add>使用<code>#000000</code>的十六进制编码来替换<code>body</code>元素的黑色背景。
<add></section>
<ide>
<ide> ## Tests
<ide> <section id='tests'>
<ide>
<ide> ```yml
<ide> tests:
<del> - text: 给你的<code>body</code>元素黑色的背景颜色。
<del> testString: 'assert($("body").css("background-color") === "rgb(0, 0, 0)", "Give your <code>body</code> element the background-color of black.");'
<del> - text: 使用<code>hex code</code>替换黑色而不是<code>black</code> 。
<del> testString: 'assert(code.match(/body\s*{(([\s\S]*;\s*?)|\s*?)background.*\s*:\s*?#000(000)?((\s*})|(;[\s\S]*?}))/gi), "Use the <code>hex code</code> for the color black instead of the word <code>black</code>.");'
<add> - text: '<code>body</code>元素的背景颜色应该是黑色。'
<add> testString: assert($("body").css("background-color") === "rgb(0, 0, 0)", '<code>body</code>元素的背景颜色应该是黑色。');
<add> - text: '使用<code>十六进制编码</code>来替换<code>black</code>的写法。'
<add> testString: 'assert(code.match(/body\s*{(([\s\S]*;\s*?)|\s*?)background.*\s*:\s*?#000(000)?((\s*})|(;[\s\S]*?}))/gi), ''使用<code>十六进制编码</code>来替换<code>black</code>的写法。'');'
<ide>
<ide> ```
<ide>
<ide> tests:
<ide> background-color: black;
<ide> }
<ide> </style>
<del>
<ide> ```
<ide>
<ide> </div>
<ide> tests:
<ide> ## Solution
<ide> <section id='solution'>
<ide>
<del>```js
<add>```html
<ide> // solution required
<ide> ```
<ide> </section>
<add>
<ide>\ No newline at end of file
<ide><path>curriculum/challenges/chinese/01-responsive-web-design/basic-css/use-hex-code-to-mix-colors.chinese.md
<ide> id: bad87fee1348bd9aedf08721
<ide> title: Use Hex Code to Mix Colors
<ide> challengeType: 0
<del>videoUrl: ''
<del>localeTitle: 使用十六进制代码混合颜色
<add>videoUrl: 'https://scrimba.com/c/cK89PhP'
<add>forumTopicId: 18359
<add>localTitle: 使用十六进制编码混合颜色
<ide> ---
<ide>
<ide> ## Description
<del><section id="description">要查看,十六进制代码使用6个十六进制数字来表示颜色,红色(R),绿色(G)和蓝色(B)组件各有两个。从这三种纯色(红色,绿色和蓝色),我们可以改变每种颜色的数量,创造超过1600万种其他颜色!例如,橙色是纯红色,混合了一些绿色,没有蓝色。在十六进制代码中,这转换为<code>#FFA500</code> 。数字<code>0</code>是十六进制代码中的最小数字,表示完全没有颜色。数字<code>F</code>是十六进制代码中的最大数字,表示最大可能的亮度。 </section>
<add><section id='description'>
<add>回顾一下,<code>hex</code>使用 6 个十六进制编码来表示颜色,2 个一组,分别代表着红(R),绿(G),蓝(B)。
<add>通过三原色,我们可以创建 1600 万种不同颜色!
<add>例如,橘色是纯红色混合一些绿色而成的,没有蓝色的参与。在十六进制编码里面,它被转译为<code>#FFA500</code>。
<add><code>0</code>是十六进制里面最小的数字,表示着没有颜色。
<add><code>F</code>是十六进制里面最大的数字,表示着最高的亮度。
<add></section>
<ide>
<ide> ## Instructions
<del><section id="instructions">将<code>style</code>元素中的颜色词替换为正确的十六进制代码。 <table class="table table-striped"><tbody><tr><th>颜色</th><th> Hex代码</th></tr><tr><td>道奇蓝</td><td> <code>#1E90FF</code> </td> </tr><tr><td>绿色</td><td> <code>#00FF00</code> </td> </tr><tr><td>橙子</td><td> <code>#FFA500</code> </td> </tr><tr><td>红</td><td> <code>#FF0000</code> </td> </tr></tbody></table></section>
<add><section id='instructions'>
<add>把<code>style</code>标签里面的颜色值用正确的十六进制编码替换。
<add><table class='table table-striped'><tr><th>Color</th><th>Hex Code</th></tr><tr><td>Dodger Blue</td><td><code>#1E90FF</code></td></tr><tr><td>Green</td><td><code>#00FF00</code></td></tr><tr><td>Orange</td><td><code>#FFA500</code></td></tr><tr><td>Red</td><td><code>#FF0000</code></td></tr></table>
<add></section>
<ide>
<ide> ## Tests
<ide> <section id='tests'>
<ide>
<ide> ```yml
<ide> tests:
<del> - text: 给你的<code>h1</code>元素添加<code>I am red!</code>的文本<code>I am red!</code> <code>color</code>红色。
<del> testString: 'assert($(".red-text").css("color") === "rgb(255, 0, 0)", "Give your <code>h1</code> element with the text <code>I am red!</code> the <code>color</code> red.");'
<del> - text: 使用<code>hex code</code>为红色而不是<code>red</code> 。
<del> testString: 'assert(code.match(/\.red-text\s*?{\s*?color:\s*?#FF0000\s*?;\s*?}/gi), "Use the <code>hex code</code> for the color red instead of the word <code>red</code>.");'
<del> - text: 给你的<code>h1</code>元素添加<code>I am green!</code>的文本<code>I am green!</code> <code>color</code>绿色。
<del> testString: 'assert($(".green-text").css("color") === "rgb(0, 255, 0)", "Give your <code>h1</code> element with the text <code>I am green!</code> the <code>color</code> green.");'
<del> - text: 使用<code>hex code</code>表示绿色而不是<code>green</code> 。
<del> testString: 'assert(code.match(/\.green-text\s*?{\s*?color:\s*?#00FF00\s*?;\s*?}/gi), "Use the <code>hex code</code> for the color green instead of the word <code>green</code>.");'
<del> - text: 给你的<code>h1</code>元素提供<code>I am dodger blue!</code>的文字<code>I am dodger blue!</code> <code>color</code>道奇蓝色。
<del> testString: 'assert($(".dodger-blue-text").css("color") === "rgb(30, 144, 255)", "Give your <code>h1</code> element with the text <code>I am dodger blue!</code> the <code>color</code> dodger blue.");'
<del> - text: 使用颜色<code>dodgerblue</code>蓝色的<code>hex code</code>而不是单词<code>dodgerblue</code> 。
<del> testString: 'assert(code.match(/\.dodger-blue-text\s*?{\s*?color:\s*?#1E90FF\s*?;\s*?}/gi), "Use the <code>hex code</code> for the color dodger blue instead of the word <code>dodgerblue</code>.");'
<del> - text: 给你的<code>h1</code>元素添加<code>I am orange!</code>的文本<code>I am orange!</code>在<code>color</code>为橙色。
<del> testString: 'assert($(".orange-text").css("color") === "rgb(255, 165, 0)", "Give your <code>h1</code> element with the text <code>I am orange!</code> the <code>color</code> orange.");'
<del> - text: 使用<code>hex code</code>表示橙色而不是<code>orange</code> 。
<del> testString: 'assert(code.match(/\.orange-text\s*?{\s*?color:\s*?#FFA500\s*?;\s*?}/gi), "Use the <code>hex code</code> for the color orange instead of the word <code>orange</code>.");'
<add> - text: '文本内容为<code>I am red!</code>的<code>h1</code>元素的字体颜色应该为<code>red</code>。'
<add> testString: assert($('.red-text').css('color') === 'rgb(255, 0, 0)', '文本内容为<code>I am red!</code>的<code>h1</code>元素的字体颜色应该为<code>red</code>。');
<add> - text: '使用<code>十六进制编码</code>替换<code>red</code>关键词。'
<add> testString: 'assert(code.match(/\.red-text\s*?{\s*?color:\s*?#FF0000\s*?;\s*?}/gi), ''使用<code>十六进制编码</code>替换<code>red</code>关键词。'');'
<add> - text: '文本内容为<code>I am green!</code>的<code>h1</code>元素的字体颜色应该为<code>green</code>。'
<add> testString: assert($('.green-text').css('color') === 'rgb(0, 255, 0)', '文本内容为<code>I am green!</code>的<code>h1</code>元素的字体颜色应该为<code>green</code>。');
<add> - text: '使用<code>十六进制编码</code>替换<code>green</code>关键词。'
<add> testString: 'assert(code.match(/\.green-text\s*?{\s*?color:\s*?#00FF00\s*?;\s*?}/gi), ''使用<code>十六进制编码</code>替换<code>green</code>关键词。'');'
<add> - text: '文本内容为<code>I am dodger blue!</code>的<code>h1</code>元素的字体颜色应该为<code>dodger blue</code>。'
<add> testString: assert($('.dodger-blue-text').css('color') === 'rgb(30, 144, 255)', '文本内容为<code>I am dodger blue!</code>的<code>h1</code>元素的字体颜色应该为<code>dodger blue</code>。');
<add> - text: '使用<code>十六进制编码</code>替换<code>dodgerblue</code>关键词。'
<add> testString: 'assert(code.match(/\.dodger-blue-text\s*?{\s*?color:\s*?#1E90FF\s*?;\s*?}/gi), ''使用<code>十六进制编码</code>替换<code>dodgerblue</code>关键词。'');'
<add> - text: '文本内容为<code>I am orange!</code>的<code>h1</code>元素的字体颜色应该为<code>orange</code>。'
<add> testString: assert($('.orange-text').css('color') === 'rgb(255, 165, 0)', '文本内容为<code>I am orange!</code>的<code>h1</code>元素的字体颜色应该为<code>orange</code>。');
<add> - text: '使用<code>十六进制编码</code>替换<code>orange</code>关键词。'
<add> testString: 'assert(code.match(/\.orange-text\s*?{\s*?color:\s*?#FFA500\s*?;\s*?}/gi), ''使用<code>十六进制编码</code>替换<code>orange</code>关键词。'');'
<ide>
<ide> ```
<ide>
<ide> tests:
<ide> <h1 class="dodger-blue-text">I am dodger blue!</h1>
<ide>
<ide> <h1 class="orange-text">I am orange!</h1>
<del>
<ide> ```
<ide>
<ide> </div>
<ide> tests:
<ide> ## Solution
<ide> <section id='solution'>
<ide>
<del>```js
<add>```html
<ide> // solution required
<ide> ```
<add>
<ide> </section>
<add>
<ide>\ No newline at end of file
<ide><path>curriculum/challenges/chinese/01-responsive-web-design/basic-css/use-rgb-to-mix-colors.chinese.md
<ide> id: bad82fee1348bd9aedf08721
<ide> title: Use RGB to Mix Colors
<ide> challengeType: 0
<del>videoUrl: ''
<del>localeTitle: 使用RGB混合颜色
<add>videoUrl: 'https://scrimba.com/c/cm24JU6'
<add>forumTopicId: 18368
<add>localTitle: 使用 RGB 混合颜色
<ide> ---
<ide>
<ide> ## Description
<del><section id="description">就像使用十六进制代码一样,您可以使用不同值的组合来混合RGB中的颜色。 </section>
<add><section id='description'>
<add>就像使用十六进制编码一样,你可以通过不同值的组合,来混合得到不同的 RGB 颜色。
<add></section>
<ide>
<ide> ## Instructions
<del><section id="instructions">将<code>style</code>元素中的十六进制代码替换为正确的RGB值。 <table class="table table-striped"><tbody><tr><th>颜色</th><th> RGB </th></tr><tr><td>蓝色</td><td> <code>rgb(0, 0, 255)</code> </td> </tr><tr><td>红</td><td> <code>rgb(255, 0, 0)</code> </td> </tr><tr><td>兰花</td><td> <code>rgb(218, 112, 214)</code> </td> </tr><tr><td>赭色</td><td> <code>rgb(160, 82, 45)</code> </td> </tr></tbody></table></section>
<add><section id='instructions'>
<add>将<code>style</code>标签里面中的十六进制编码替换为正确的 RGB 值。
<add><table class='table table-striped'><tr><th>Color</th><th>RGB</th></tr><tr><td>Blue</td><td><code>rgb(0, 0, 255)</code></td></tr><tr><td>Red</td><td><code>rgb(255, 0, 0)</code></td></tr><tr><td>Orchid</td><td><code>rgb(218, 112, 214)</code></td></tr><tr><td>Sienna</td><td><code>rgb(160, 82, 45)</code></td></tr></table>
<add></section>
<ide>
<ide> ## Tests
<ide> <section id='tests'>
<ide>
<ide> ```yml
<ide> tests:
<del> - text: 给你的<code>h1</code>元素添加<code>I am red!</code>的文本<code>I am red!</code> <code>color</code>红色。
<del> testString: 'assert($(".red-text").css("color") === "rgb(255, 0, 0)", "Give your <code>h1</code> element with the text <code>I am red!</code> the <code>color</code> red.");'
<del> - text: 使用<code>rgb</code>表示红色。
<del> testString: 'assert(code.match(/\.red-text\s*?{\s*?color:\s*?rgb\(\s*?255\s*?,\s*?0\s*?,\s*?0\s*?\)\s*?;\s*?}/gi), "Use <code>rgb</code> for the color red.");'
<del> - text: 给你的<code>h1</code>元素文字<code>I am orchid!</code>兰花的<code>color</code> 。
<del> testString: 'assert($(".orchid-text").css("color") === "rgb(218, 112, 214)", "Give your <code>h1</code> element with the text <code>I am orchid!</code> the <code>color</code> orchid.");'
<del> - text: 使用<code>rgb</code>作为颜色兰花。
<del> testString: 'assert(code.match(/\.orchid-text\s*?{\s*?color:\s*?rgb\(\s*?218\s*?,\s*?112\s*?,\s*?214\s*?\)\s*?;\s*?}/gi), "Use <code>rgb</code> for the color orchid.");'
<del> - text: 给你的<code>h1</code>元素添加<code>I am blue!</code>的文本<code>I am blue!</code> <code>color</code>蓝色。
<del> testString: 'assert($(".blue-text").css("color") === "rgb(0, 0, 255)", "Give your <code>h1</code> element with the text <code>I am blue!</code> the <code>color</code> blue.");'
<del> - text: 使用<code>rgb</code>作为蓝色。
<del> testString: 'assert(code.match(/\.blue-text\s*?{\s*?color:\s*?rgb\(\s*?0\s*?,\s*?0\s*?,\s*?255\s*?\)\s*?;\s*?}/gi), "Use <code>rgb</code> for the color blue.");'
<del> - text: 给你的<code>h1</code>元素添加<code>I am sienna!</code>的文本<code>I am sienna!</code> <code>color</code> sienna。
<del> testString: 'assert($(".sienna-text").css("color") === "rgb(160, 82, 45)", "Give your <code>h1</code> element with the text <code>I am sienna!</code> the <code>color</code> sienna.");'
<del> - text: 使用<code>rgb</code>作为颜色sienna。
<del> testString: 'assert(code.match(/\.sienna-text\s*?{\s*?color:\s*?rgb\(\s*?160\s*?,\s*?82\s*?,\s*?45\s*?\)\s*?;\s*?}/gi), "Use <code>rgb</code> for the color sienna.");'
<add> - text: '文本内容为<code>I am red!</code>的<code>h1</code>元素的字体颜色应该为<code>red</code>。'
<add> testString: assert($('.red-text').css('color') === 'rgb(255, 0, 0)', '文本内容为<code>I am red!</code>的<code>h1</code>元素的字体颜色应该为<code>red</code>。');
<add> - text: '<code>red</code>颜色应使用<code>RGB</code>值。'
<add> testString: 'assert(code.match(/\.red-text\s*?{\s*?color:\s*?rgb\(\s*?255\s*?,\s*?0\s*?,\s*?0\s*?\)\s*?;\s*?}/gi), ''<code>red</code>颜色应使用<code>RGB</code>值。'');'
<add> - text: '文本内容为<code>I am orchid!</code>的<code>h1</code>元素的字体颜色应该为<code>orchid</code>。'
<add> testString: assert($('.orchid-text').css('color') === 'rgb(218, 112, 214)', '文本内容为<code>I am orchid!</code>的<code>h1</code>元素的字体颜色应该为<code>orchid</code>。');
<add> - text: '<code>orchid</code>颜色应使用<code>RGB</code>值。'
<add> testString: 'assert(code.match(/\.orchid-text\s*?{\s*?color:\s*?rgb\(\s*?218\s*?,\s*?112\s*?,\s*?214\s*?\)\s*?;\s*?}/gi), ''<code>red</code>颜色应使用<code>RGB</code>值。'');'
<add> - text: '文本内容为<code>I am blue!</code>的<code>h1</code>元素的字体颜色应该为<code>blue</code>。'
<add> testString: assert($('.blue-text').css('color') === 'rgb(0, 0, 255)', '文本内容为<code>I am blue!</code>的<code>h1</code>元素的字体颜色应该为<code>blue</code>。');
<add> - text: '<code>blue</code>颜色应使用<code>RGB</code>值。'
<add> testString: 'assert(code.match(/\.blue-text\s*?{\s*?color:\s*?rgb\(\s*?0\s*?,\s*?0\s*?,\s*?255\s*?\)\s*?;\s*?}/gi), ''<code>blue</code>颜色应使用<code>RGB</code>值。'');'
<add> - text: '文本内容为<code>I am sienna!</code>的<code>h1</code>元素的字体颜色应该为<code>sienna</code>。'
<add> testString: assert($('.sienna-text').css('color') === 'rgb(160, 82, 45)', '文本内容为<code>I am sienna!</code>的<code>h1</code>元素的字体颜色应该为<code>sienna</code>。');
<add> - text: '<code>sienna</code>颜色应使用<code>RGB</code>值。'
<add> testString: 'assert(code.match(/\.sienna-text\s*?{\s*?color:\s*?rgb\(\s*?160\s*?,\s*?82\s*?,\s*?45\s*?\)\s*?;\s*?}/gi), ''<code>sienna</code>颜色应使用<code>RGB</code>值。'');'
<ide>
<ide> ```
<ide>
<ide> tests:
<ide> <h1 class="sienna-text">I am sienna!</h1>
<ide>
<ide> <h1 class="blue-text">I am blue!</h1>
<del>
<ide> ```
<ide>
<ide> </div>
<ide> tests:
<ide> ```js
<ide> // solution required
<ide> ```
<add>
<ide> </section>
<add>
<ide>\ No newline at end of file
<ide><path>curriculum/challenges/chinese/01-responsive-web-design/basic-css/use-rgb-values-to-color-elements.chinese.md
<ide> id: bad87fee1348bd9aede08718
<ide> title: Use RGB values to Color Elements
<ide> challengeType: 0
<del>videoUrl: ''
<del>localeTitle: 将RGB值用于颜色元素
<add>videoUrl: 'https://scrimba.com/c/cRkp2fr'
<add>forumTopicId: 18369
<add>localTitle: 使用 RGB 值为元素上色
<ide> ---
<ide>
<ide> ## Description
<del><section id="description">另一种可以在CSS中表示颜色的方法是使用<code>RGB</code>值。黑色的RGB值如下所示: <code>rgb(0, 0, 0)</code>白色的RGB值如下所示: <code>rgb(255, 255, 255)</code>而不是像使用十六进制代码那样使用六个十六进制数字,使用<code>RGB</code>使用0到255之间的数字指定每种颜色的亮度。如果进行数学计算,一种颜色的两位数等于16乘以16,这总共得到256个值。因此,从零开始计数的<code>RGB</code>具有与十六进制代码完全相同的可能值。以下是使用RGB代码将身体背景更改为橙色的示例。 <blockquote>身体 { <br> background-color:rgb(255,165,0); <br> } </blockquote></section>
<add><section id='description'>
<add>另一种可以在 CSS 中表示颜色的方法是使用 RGB 值。
<add>黑色的 RGB 值声明如下:
<add><code>rgb(0, 0, 0)</code>
<add>白色的 RGB 值声明如下:
<add><code>rgb(255, 255, 255)</code>
<add>RGB 不像十六进制编码,并不需要用到 6 位十六进制数字。在 RGB 里,你只需要指定每种颜色的亮度大小,从 0 到 255。
<add>在数学的角度来看,如果将十六进制的一种颜色的两位数字相乘,16 乘以 16 也等于 256。所以,从 0 到 255 计算的 RGB 值的具有十六进制编码相同的颜色可能性。
<add>下面是通过使用 RGB 值设置背景颜色为橘色的例子:
<add>
<add>```css
<add>body {
<add> background-color: rgb(255, 165, 0);
<add>}
<add>```
<add>
<add></section>
<ide>
<ide> ## Instructions
<del><section id="instructions">让我们用黑色的RGB值替换<code>body</code>元素背景颜色中的十六进制代码: <code>rgb(0, 0, 0)</code> </section>
<add><section id='instructions'>
<add>让我们用<code>rgb(0, 0, 0)</code>的 RGB 值替换<code>body</code>元素背景颜色的十六进制编码。
<add></section>
<ide>
<ide> ## Tests
<ide> <section id='tests'>
<ide>
<ide> ```yml
<ide> tests:
<del> - text: 你的<code>body</code>元素应该有黑色背景。
<del> testString: 'assert($("body").css("background-color") === "rgb(0, 0, 0)", "Your <code>body</code> element should have a black background.");'
<del> - text: 使用<code>rgb</code>为您的<code>body</code>元素提供黑色。
<del> testString: 'assert(code.match(/rgb\s*\(\s*0\s*,\s*0\s*,\s*0\s*\)/ig), "Use <code>rgb</code> to give your <code>body</code> element a color of black.");'
<add> - text: '<code>body</code>元素的背景颜色应该是黑色的。'
<add> testString: assert($("body").css("background-color") === "rgb(0, 0, 0)", '<code>body</code>元素的背景颜色应该是黑色的。');
<add> - text: '<code>body</code>元素的背景颜色的黑色值应该为<code>RGB</code>值。'
<add> testString: assert(code.match(/rgb\s*\(\s*0\s*,\s*0\s*,\s*0\s*\)/ig), '<code>body</code>元素的背景颜色的黑色值应该为<code>RGB</code>值。');
<ide>
<ide> ```
<ide>
<ide> tests:
<ide> background-color: #F00;
<ide> }
<ide> </style>
<del>
<ide> ```
<ide>
<ide> </div>
<ide> tests:
<ide> ## Solution
<ide> <section id='solution'>
<ide>
<del>```js
<add>```html
<ide> // solution required
<ide> ```
<add>
<ide> </section>
<add>
<ide>\ No newline at end of file | 44 |
Text | Text | add additional test case to fix hard code issue | a34921a5b3d19218bb844000b3a76328cf388161 | <ide><path>curriculum/challenges/english/02-javascript-algorithms-and-data-structures/debugging/use-caution-when-reinitializing-variables-inside-a-loop.md
<ide> assert(
<ide> );
<ide> ```
<ide>
<add>`zeroArray(4,3)` should return an array holding 4 rows of 3 columns of zeroes each.
<add>
<add>```js
<add>assert(JSON.stringify(zeroArray(4,3)) == '[[0,0,0],[0,0,0],[0,0,0],[0,0,0]]');
<add>```
<add>
<ide> # --seed--
<ide>
<ide> ## --seed-contents--
<ide> function zeroArray(m, n) {
<ide>
<ide> let matrix = zeroArray(3, 2);
<ide> console.log(matrix);
<add>
<ide> ```
<ide>
<ide> # --solutions--
<ide> function zeroArray(m, n) {
<ide>
<ide> let matrix = zeroArray(3, 2);
<ide> console.log(matrix);
<add>
<ide> ``` | 1 |
Text | Text | fix typo in issue template | d7eea1b49a5ea67dd9f39b9fa0a823466433f486 | <ide><path>.github/ISSUE_TEMPLATE.md
<ide> Please use the #pocoo IRC channel on freenode or Stack Overflow for general
<ide> questions about using Flask or issues not related to Flask.**
<ide>
<ide> If you'd like to report a bug in Flask, fill out the template below. Provide
<del>any any extra information that may be useful / related to your problem.
<add>any extra information that may be useful / related to your problem.
<ide> Ideally, create an [MCVE](http://stackoverflow.com/help/mcve), which helps us
<ide> understand the problem and helps check that it is not caused by something in
<ide> your code. | 1 |
Javascript | Javascript | pass tests and flow | 9e87e654f5bd223ef2c5fc920bd778ca2eb31521 | <ide><path>src/__tests__/inspectedElementContext-test.js
<ide> import type Store from 'src/devtools/store';
<ide> describe('InspectedElementContext', () => {
<ide> let React;
<ide> let ReactDOM;
<add> let act;
<ide> let TestRenderer: ReactTestRenderer;
<ide> let bridge: Bridge;
<ide> let store: Store;
<ide> describe('InspectedElementContext', () => {
<ide> let StoreContext;
<ide> let TreeContextController;
<ide>
<add> // a version of actAsync that *doesn't* recursively flush timers
<add> async function actAsync(cb: () => *): Promise<void> {
<add>
<add> // $FlowFixMe Flow doesn't know about "await act()" yet
<add> await act(async () => {
<add> await cb();
<add> });
<add> // $FlowFixMe Flow doesn't know about "await act()" yet
<add> await act(async () => {
<add> jest.runOnlyPendingTimers();
<add> });
<add> }
<add>
<add>
<ide> beforeEach(() => {
<ide> utils = require('./utils');
<ide> utils.beforeEachProfiling();
<ide> describe('InspectedElementContext', () => {
<ide>
<ide> React = require('react');
<ide> ReactDOM = require('react-dom');
<add> act = require('react-dom/test-utils').act
<ide> TestRenderer = utils.requireTestRenderer();
<ide>
<ide> BridgeContext = require('src/devtools/views/context').BridgeContext;
<ide> describe('InspectedElementContext', () => {
<ide> return null;
<ide> }
<ide>
<del> await utils.actAsync(
<add> await actAsync(
<ide> () =>
<ide> TestRenderer.create(
<ide> <Contexts
<ide> describe('InspectedElementContext', () => {
<ide> <Suspender target={example} />
<ide> </React.Suspense>
<ide> </Contexts>
<del> ),
<del> 3
<add> )
<ide> );
<ide> expect(didFinish).toBe(true);
<ide>
<ide> describe('InspectedElementContext', () => {
<ide> return null;
<ide> }
<ide>
<del> await utils.actAsync(
<add> await actAsync(
<ide> () =>
<ide> TestRenderer.create(
<ide> <Contexts
<ide> describe('InspectedElementContext', () => {
<ide> <Suspender target={example} />
<ide> </React.Suspense>
<ide> </Contexts>
<del> ),
<del> 3
<add> )
<ide> );
<ide> expect(inspectedElement).toMatchSnapshot('2: initial render');
<ide>
<del> await utils.actAsync(() =>
<add> await actAsync(() =>
<ide> ReactDOM.render(<Example foo={2} bar="def" />, container)
<ide> );
<ide>
<ide> inspectedElement = null;
<del> await utils.actAsync(
<add> await actAsync(
<ide> () =>
<ide> TestRenderer.create(
<ide> <Contexts
<ide> describe('InspectedElementContext', () => {
<ide> <Suspender target={example} />
<ide> </React.Suspense>
<ide> </Contexts>
<del> ),
<del> 1
<add> )
<ide> );
<ide> expect(inspectedElement).toMatchSnapshot('2: updated state');
<ide>
<ide> describe('InspectedElementContext', () => {
<ide> targetRenderCount = 0;
<ide>
<ide> let renderer;
<del> await utils.actAsync(
<add> await actAsync(
<ide> () =>
<ide> (renderer = TestRenderer.create(
<ide> <Contexts
<ide> describe('InspectedElementContext', () => {
<ide> <Suspender target={id} />
<ide> </React.Suspense>
<ide> </Contexts>
<del> )),
<del> 3
<add> ))
<ide> );
<ide> expect(targetRenderCount).toBe(1);
<ide> expect(inspectedElement).toMatchSnapshot('2: initial render');
<ide> describe('InspectedElementContext', () => {
<ide>
<ide> targetRenderCount = 0;
<ide> inspectedElement = null;
<del> await utils.actAsync(
<add> await actAsync(
<ide> () =>
<ide> renderer.update(
<ide> <Contexts
<ide> describe('InspectedElementContext', () => {
<ide> <Suspender target={id} />
<ide> </React.Suspense>
<ide> </Contexts>
<del> ),
<del> 1
<add> )
<ide> );
<ide> expect(targetRenderCount).toBe(0);
<ide> expect(inspectedElement).toEqual(initialInspectedElement);
<ide>
<ide> targetRenderCount = 0;
<ide>
<del> await utils.actAsync(() =>
<add> await actAsync(() =>
<ide> ReactDOM.render(
<ide> <Wrapper>
<ide> <Target foo={2} bar="def" />
<ide><path>src/__tests__/ownersListContext-test.js
<ide> describe('OwnersListContext', () => {
<ide> <Suspender owner={parent} />
<ide> </React.Suspense>
<ide> </Contexts>
<del> ),
<del> 3
<add> )
<ide> );
<ide> expect(didFinish).toBe(true);
<ide>
<ide> describe('OwnersListContext', () => {
<ide> <Suspender owner={firstChild} />
<ide> </React.Suspense>
<ide> </Contexts>
<del> ),
<del> 3
<add> )
<ide> );
<ide> expect(didFinish).toBe(true);
<ide>
<ide> describe('OwnersListContext', () => {
<ide> <Suspender owner={firstChild} />
<ide> </React.Suspense>
<ide> </Contexts>
<del> ),
<del> 3
<add> )
<ide> );
<ide> expect(didFinish).toBe(true);
<ide>
<ide> describe('OwnersListContext', () => {
<ide> <Suspender owner={grandparent} />
<ide> </React.Suspense>
<ide> </Contexts>
<del> ),
<del> 3
<add> )
<ide> );
<ide> expect(didFinish).toBe(true);
<ide> | 2 |
Text | Text | relax prohibition on personal pronouns | 448834c9504b8e6bcf44716b1f512da25fee8147 | <ide><path>doc/guides/doc-style-guide.md
<ide> this guide.
<ide> * Check changes to documentation with `make lint-md`.
<ide> * [Use US spelling][].
<ide> * [Use serial commas][].
<del>* Avoid personal pronouns (_I_, _you_, _we_) in reference documentation.
<del> * Personal pronouns are acceptable in colloquial documentation such as guides.
<del> * Use gender-neutral pronouns and gender-neutral plural nouns.
<del> * OK: _they_, _their_, _them_, _folks_, _people_, _developers_
<del> * NOT OK: _his_, _hers_, _him_, _her_, _guys_, _dudes_
<add>* Avoid first-person pronouns (_I_, _we_).
<add> * Exception: _we recommend foo_ is preferable to _foo is recommended_.
<add>* Use gender-neutral pronouns and gender-neutral plural nouns.
<add> * OK: _they_, _their_, _them_, _folks_, _people_, _developers_
<add> * NOT OK: _his_, _hers_, _him_, _her_, _guys_, _dudes_
<ide> * When combining wrapping elements (parentheses and quotes), place terminal
<ide> punctuation:
<ide> * Inside the wrapping element if the wrapping element contains a complete | 1 |
Javascript | Javascript | drop size and andself methods | f110360f65a268e959ae892ca36e85da3d91e606 | <ide><path>src/deprecated.js
<del>define([
<del> "./core",
<del> "./traversing"
<del>], function( jQuery ) {
<del>
<del>// The number of elements contained in the matched element set
<del>jQuery.fn.size = function() {
<del> return this.length;
<del>};
<del>
<del>jQuery.fn.andSelf = jQuery.fn.addBack;
<del>
<add>define(function() {
<ide> });
<ide><path>test/unit/deprecated.js
<ide> module("deprecated", { teardown: moduleTeardown });
<ide>
<del>if ( jQuery.fn.size ) {
<del> test("size()", function() {
<del> expect(1);
<del> equal( jQuery("#qunit-fixture p").size(), 6, "Get Number of Elements Found" );
<del> });
<del>} | 2 |
Mixed | Text | add the `--api` option for the plugin generator | 9a7f011da196f93cec285a6227ad9499434da4d1 | <ide><path>railties/CHANGELOG.md
<add>* Add a `--api` option in order to generate plugins that can be added
<add> inside an API application.
<add>
<add> *Robin Dupret*
<add>
<ide> * Fix `NoMethodError` when generating a scaffold inside a full engine.
<ide>
<ide> *Yuji Yaginuma*
<ide><path>railties/lib/rails/generators/rails/plugin/plugin_generator.rb
<ide> class PluginGenerator < AppBase # :nodoc:
<ide> desc: "If creating plugin in application's directory " +
<ide> "skip adding entry to Gemfile"
<ide>
<add> class_option :api, type: :boolean, default: false,
<add> desc: "Generate a smaller stack for API application plugins"
<add>
<ide> def initialize(*args)
<ide> @dummy_path = nil
<ide> super
<ide> def with_dummy_app?
<ide> options[:skip_test].blank? || options[:dummy_path] != 'test/dummy'
<ide> end
<ide>
<add> def api?
<add> options[:api]
<add> end
<add>
<ide> def self.banner
<ide> "rails plugin new #{self.arguments.map(&:usage).join(' ')} [options]"
<ide> end | 2 |
PHP | PHP | fix pivot serialization | b52d3143c6b4b5eacbb21a5c83873fd1d43289e9 | <ide><path>src/Illuminate/Database/Eloquent/Collection.php
<ide>
<ide> use LogicException;
<ide> use Illuminate\Support\Arr;
<add>use Illuminate\Database\Eloquent\Relations\Pivot;
<ide> use Illuminate\Contracts\Queue\QueueableCollection;
<ide> use Illuminate\Support\Collection as BaseCollection;
<ide>
<ide> public function getQueueableClass()
<ide> */
<ide> public function getQueueableIds()
<ide> {
<del> return $this->modelKeys();
<add> if ($this->isEmpty()) {
<add> return [];
<add> }
<add>
<add> return $this->first() instanceof Pivot
<add> ? $this->map->getQueueableId()->all()
<add> : $this->modelKeys();
<ide> }
<ide>
<ide> /**
<ide><path>src/Illuminate/Database/Eloquent/Relations/MorphPivot.php
<ide>
<ide> namespace Illuminate\Database\Eloquent\Relations;
<ide>
<add>use Illuminate\Support\Str;
<ide> use Illuminate\Database\Eloquent\Builder;
<ide>
<ide> class MorphPivot extends Pivot
<ide> public function setMorphClass($morphClass)
<ide>
<ide> return $this;
<ide> }
<add>
<add> /**
<add> * Get the queueable identity for the entity.
<add> *
<add> * @return mixed
<add> */
<add> public function getQueueableId()
<add> {
<add> if (isset($this->attributes[$this->getKeyName()])) {
<add> return $this->getKey();
<add> }
<add>
<add> return sprintf(
<add> '%s:%s:%s:%s:%s:%s',
<add> $this->foreignKey, $this->getAttribute($this->foreignKey),
<add> $this->relatedKey, $this->getAttribute($this->relatedKey),
<add> $this->morphType, $this->morphClass
<add> );
<add> }
<add>
<add> /**
<add> * Get a new query to restore one or more models by their queueable IDs.
<add> *
<add> * @param array|int $ids
<add> * @return \Illuminate\Database\Eloquent\Builder
<add> */
<add> public function newQueryForRestoration($ids)
<add> {
<add> if (is_array($ids)) {
<add> return $this->newQueryForCollectionRestoration($ids);
<add> }
<add>
<add> if (! Str::contains($ids, ':')) {
<add> return parent::newQueryForRestoration($ids);
<add> }
<add>
<add> $segments = explode(':', $ids);
<add>
<add> return $this->newQueryWithoutScopes()
<add> ->where($segments[0], $segments[1])
<add> ->where($segments[2], $segments[3])
<add> ->where($segments[4], $segments[5]);
<add> }
<add>
<add> /**
<add> * Get a new query to restore multiple models by their queueable IDs.
<add> *
<add> * @param array|int $ids
<add> * @return \Illuminate\Database\Eloquent\Builder
<add> */
<add> protected function newQueryForCollectionRestoration(array $ids)
<add> {
<add> if (! Str::contains($ids[0], ':')) {
<add> return parent::newQueryForRestoration($ids);
<add> }
<add>
<add> $query = $this->newQueryWithoutScopes();
<add>
<add> foreach ($ids as $id) {
<add> $segments = explode(':', $id);
<add>
<add> $query->orWhere(function ($query) use ($segments) {
<add> return $query->where($segments[0], $segments[1])
<add> ->where($segments[2], $segments[3])
<add> ->where($segments[4], $segments[5]);
<add> });
<add> }
<add>
<add> return $query;
<add> }
<ide> }
<ide><path>src/Illuminate/Database/Eloquent/Relations/MorphToMany.php
<ide> public function newPivot(array $attributes = [], $exists = false)
<ide> return $pivot;
<ide> }
<ide>
<add> /**
<add> * Get the pivot columns for the relation.
<add> *
<add> * "pivot_" is prefixed ot each column for easy removal later.
<add> *
<add> * @return array
<add> */
<add> protected function aliasedPivotColumns()
<add> {
<add> $defaults = [$this->foreignPivotKey, $this->relatedPivotKey, $this->morphType];
<add>
<add> return collect(array_merge($defaults, $this->pivotColumns))->map(function ($column) {
<add> return $this->table.'.'.$column.' as pivot_'.$column;
<add> })->unique()->all();
<add> }
<add>
<ide> /**
<ide> * Get the foreign key "type" name.
<ide> *
<ide><path>src/Illuminate/Database/Eloquent/Relations/Pivot.php
<ide> public function getUpdatedAtColumn()
<ide> {
<ide> return $this->pivotParent->getUpdatedAtColumn();
<ide> }
<add>
<add> /**
<add> * Get the queueable identity for the entity.
<add> *
<add> * @return mixed
<add> */
<add> public function getQueueableId()
<add> {
<add> if (isset($this->attributes[$this->getKeyName()])) {
<add> return $this->getKey();
<add> }
<add>
<add> return sprintf(
<add> '%s:%s:%s:%s',
<add> $this->foreignKey, $this->getAttribute($this->foreignKey),
<add> $this->relatedKey, $this->getAttribute($this->relatedKey)
<add> );
<add> }
<add>
<add> /**
<add> * Get a new query to restore one or more models by their queueable IDs.
<add> *
<add> * @param array|int $ids
<add> * @return \Illuminate\Database\Eloquent\Builder
<add> */
<add> public function newQueryForRestoration($ids)
<add> {
<add> if (is_array($ids)) {
<add> return $this->newQueryForCollectionRestoration($ids);
<add> }
<add>
<add> if (! Str::contains($ids, ':')) {
<add> return parent::newQueryForRestoration($ids);
<add> }
<add>
<add> $segments = explode(':', $ids);
<add>
<add> return $this->newQueryWithoutScopes()
<add> ->where($segments[0], $segments[1])
<add> ->where($segments[2], $segments[3]);
<add> }
<add>
<add> /**
<add> * Get a new query to restore multiple models by their queueable IDs.
<add> *
<add> * @param array|int $ids
<add> * @return \Illuminate\Database\Eloquent\Builder
<add> */
<add> protected function newQueryForCollectionRestoration(array $ids)
<add> {
<add> if (! Str::contains($ids[0], ':')) {
<add> return parent::newQueryForRestoration($ids);
<add> }
<add>
<add> $query = $this->newQueryWithoutScopes();
<add>
<add> foreach ($ids as $id) {
<add> $segments = explode(':', $id);
<add>
<add> $query->orWhere(function ($query) use ($segments) {
<add> return $query->where($segments[0], $segments[1])
<add> ->where($segments[2], $segments[3]);
<add> });
<add> }
<add>
<add> return $query;
<add> }
<ide> }
<ide><path>tests/Integration/Database/EloquentPivotSerializationTest.php
<add><?php
<add>
<add>namespace Illuminate\Tests\Integration\Database;
<add>
<add>use Illuminate\Queue\SerializesModels;
<add>use Illuminate\Support\Facades\Schema;
<add>use Illuminate\Database\Eloquent\Model;
<add>use Illuminate\Database\Eloquent\Relations\Pivot;
<add>use Illuminate\Database\Eloquent\Relations\MorphPivot;
<add>use Illuminate\Database\Eloquent\Collection as DatabaseCollection;
<add>
<add>/**
<add> * @group integration
<add> */
<add>class EloquentPivotSerializationTest extends DatabaseTestCase
<add>{
<add> public function setUp()
<add> {
<add> parent::setUp();
<add>
<add> Schema::create('users', function ($table) {
<add> $table->increments('id');
<add> $table->string('email');
<add> $table->timestamps();
<add> });
<add>
<add> Schema::create('projects', function ($table) {
<add> $table->increments('id');
<add> $table->string('name');
<add> $table->timestamps();
<add> });
<add>
<add> Schema::create('project_users', function ($table) {
<add> $table->integer('user_id');
<add> $table->integer('project_id');
<add> });
<add>
<add> Schema::create('tags', function ($table) {
<add> $table->increments('id');
<add> $table->string('name');
<add> $table->timestamps();
<add> });
<add>
<add> Schema::create('taggables', function ($table) {
<add> $table->integer('tag_id');
<add> $table->integer('taggable_id');
<add> $table->string('taggable_type');
<add> });
<add> }
<add>
<add> public function test_pivot_can_be_serialized_and_restored()
<add> {
<add> $user = PivotSerializationTestUser::forceCreate(['email' => '[email protected]']);
<add> $project = PivotSerializationTestProject::forceCreate(['name' => 'Test Project']);
<add> $project->collaborators()->attach($user);
<add>
<add> $project = $project->fresh();
<add>
<add> $class = new PivotSerializationTestClass($project->collaborators->first()->pivot);
<add> $class = unserialize(serialize($class));
<add>
<add> $this->assertEquals($project->collaborators->first()->pivot->user_id, $class->pivot->user_id);
<add> $this->assertEquals($project->collaborators->first()->pivot->project_id, $class->pivot->project_id);
<add>
<add> $class->pivot->save();
<add> }
<add>
<add> public function test_morph_pivot_can_be_serialized_and_restored()
<add> {
<add> $project = PivotSerializationTestProject::forceCreate(['name' => 'Test Project']);
<add> $tag = PivotSerializationTestTag::forceCreate(['name' => 'Test Tag']);
<add> $project->tags()->attach($tag);
<add>
<add> $project = $project->fresh();
<add>
<add> $class = new PivotSerializationTestClass($project->tags->first()->pivot);
<add> $class = unserialize(serialize($class));
<add>
<add> $this->assertEquals($project->tags->first()->pivot->tag_id, $class->pivot->tag_id);
<add> $this->assertEquals($project->tags->first()->pivot->taggable_id, $class->pivot->taggable_id);
<add> $this->assertEquals($project->tags->first()->pivot->taggable_type, $class->pivot->taggable_type);
<add>
<add> $class->pivot->save();
<add> }
<add>
<add> public function test_collection_of_pivots_can_be_serialized_and_restored()
<add> {
<add> $user = PivotSerializationTestUser::forceCreate(['email' => '[email protected]']);
<add> $user2 = PivotSerializationTestUser::forceCreate(['email' => '[email protected]']);
<add> $project = PivotSerializationTestProject::forceCreate(['name' => 'Test Project']);
<add>
<add> $project->collaborators()->attach($user);
<add> $project->collaborators()->attach($user2);
<add>
<add> $project = $project->fresh();
<add>
<add> $class = new PivotSerializationTestCollectionClass(DatabaseCollection::make($project->collaborators->map->pivot));
<add> $class = unserialize(serialize($class));
<add>
<add> $this->assertEquals($project->collaborators[0]->pivot->user_id, $class->pivots[0]->user_id);
<add> $this->assertEquals($project->collaborators[1]->pivot->project_id, $class->pivots[1]->project_id);
<add> }
<add>
<add> public function test_collection_of_morph_pivots_can_be_serialized_and_restored()
<add> {
<add> $tag = PivotSerializationTestTag::forceCreate(['name' => 'Test Tag 1']);
<add> $tag2 = PivotSerializationTestTag::forceCreate(['name' => 'Test Tag 2']);
<add> $project = PivotSerializationTestProject::forceCreate(['name' => 'Test Project']);
<add>
<add> $project->tags()->attach($tag);
<add> $project->tags()->attach($tag2);
<add>
<add> $project = $project->fresh();
<add>
<add> $class = new PivotSerializationTestCollectionClass(DatabaseCollection::make($project->tags->map->pivot));
<add> $class = unserialize(serialize($class));
<add>
<add> $this->assertEquals($project->tags[0]->pivot->tag_id, $class->pivots[0]->tag_id);
<add> $this->assertEquals($project->tags[0]->pivot->taggable_id, $class->pivots[0]->taggable_id);
<add> $this->assertEquals($project->tags[0]->pivot->taggable_type, $class->pivots[0]->taggable_type);
<add>
<add> $this->assertEquals($project->tags[1]->pivot->tag_id, $class->pivots[1]->tag_id);
<add> $this->assertEquals($project->tags[1]->pivot->taggable_id, $class->pivots[1]->taggable_id);
<add> $this->assertEquals($project->tags[1]->pivot->taggable_type, $class->pivots[1]->taggable_type);
<add> }
<add>}
<add>
<add>class PivotSerializationTestClass
<add>{
<add> use SerializesModels;
<add>
<add> public $pivot;
<add>
<add> public function __construct($pivot)
<add> {
<add> $this->pivot = $pivot;
<add> }
<add>}
<add>
<add>class PivotSerializationTestCollectionClass
<add>{
<add> use SerializesModels;
<add>
<add> public $pivots;
<add>
<add> public function __construct($pivots)
<add> {
<add> $this->pivots = $pivots;
<add> }
<add>}
<add>
<add>class PivotSerializationTestUser extends Model
<add>{
<add> public $table = 'users';
<add>}
<add>
<add>class PivotSerializationTestProject extends Model
<add>{
<add> public $table = 'projects';
<add>
<add> public function collaborators()
<add> {
<add> return $this->belongsToMany(
<add> PivotSerializationTestUser::class, 'project_users', 'project_id', 'user_id'
<add> )->using(PivotSerializationTestCollaborator::class);
<add> }
<add>
<add> public function tags()
<add> {
<add> return $this->morphToMany(PivotSerializationTestTag::class, 'taggable', 'taggables', 'taggable_id', 'tag_id')
<add> ->using(PivotSerializationTestTagAttachment::class);
<add> }
<add>}
<add>
<add>class PivotSerializationTestTag extends Model
<add>{
<add> public $table = 'tags';
<add>
<add> public function projects()
<add> {
<add> return $this->morphedByMany(PivotSerializationTestProject::class, 'taggable', 'taggables', 'tag_id', 'taggable_id')
<add> ->using(PivotSerializationTestTagAttachment::class);
<add> }
<add>}
<add>
<add>class PivotSerializationTestCollaborator extends Pivot
<add>{
<add> public $table = 'project_users';
<add>}
<add>
<add>class PivotSerializationTestTagAttachment extends MorphPivot
<add>{
<add> public $table = 'taggables';
<add>} | 5 |
Python | Python | update message with new breeze subcommand | 9a6fc73aba75a03b0dd6c700f0f8932f6a474ff7 | <ide><path>dev/breeze/src/airflow_breeze/utils/reinstall.py
<ide> def warn_non_editable():
<ide> "\n[error]Breeze is installed in a wrong way.[/]\n"
<ide> "\n[error]It should only be installed in editable mode[/]\n\n"
<ide> "[info]Please go to Airflow sources and run[/]\n\n"
<del> f" {NAME} self-upgrade --force --use-current-airflow-sources\n"
<add> f" {NAME} setup self-upgrade --force --use-current-airflow-sources\n"
<ide> )
<ide>
<ide>
<ide> def warn_dependencies_changed():
<ide> f"\n[warning]Breeze dependencies changed since the installation![/]\n\n"
<ide> f"[warning]This might cause various problems!![/]\n\n"
<ide> f"If you experience problems - reinstall Breeze with:\n\n"
<del> f" {NAME} self-upgrade --force\n"
<add> f" {NAME} setup self-upgrade --force\n"
<ide> "\nThis should usually take couple of seconds.\n"
<ide> ) | 1 |
PHP | PHP | use basepath helper | 0984411bda2cd2cc62a698f222b32ee991d57ff5 | <ide><path>src/Illuminate/Database/Console/Migrations/MigrateCommand.php
<ide> public function fire()
<ide> // so that migrations may be run for any path within the applications.
<ide> if ( ! is_null($path = $this->input->getOption('path')))
<ide> {
<del> $path = $this->laravel['path.base'].'/'.$path;
<add> $path = $this->laravel->basePath().'/'.$path;
<ide> }
<ide> else
<ide> {
<ide><path>src/Illuminate/Foundation/Bootstrap/DetectEnvironment.php
<ide> public function bootstrap(Application $app)
<ide> {
<ide> try
<ide> {
<del> Dotenv::load($app['path.base'], $app->environmentFile());
<add> Dotenv::load($app->basePath(), $app->environmentFile());
<ide> }
<ide> catch (InvalidArgumentException $e)
<ide> {
<ide><path>src/Illuminate/Foundation/Console/AppNameCommand.php
<ide> protected function getUserClassPath()
<ide> */
<ide> protected function getBootstrapPath()
<ide> {
<del> return $this->laravel['path.base'].'/bootstrap/app.php';
<add> return $this->laravel->basePath().'/bootstrap/app.php';
<ide> }
<ide>
<ide> /**
<ide> protected function getBootstrapPath()
<ide> */
<ide> protected function getComposerPath()
<ide> {
<del> return $this->laravel['path.base'].'/composer.json';
<add> return $this->laravel->basePath().'/composer.json';
<ide> }
<ide>
<ide> /**
<ide> protected function getServicesConfigPath()
<ide> */
<ide> protected function getPhpSpecConfigPath()
<ide> {
<del> return $this->laravel['path.base'].'/phpspec.yml';
<add> return $this->laravel->basePath().'/phpspec.yml';
<ide> }
<ide>
<ide> /**
<ide><path>src/Illuminate/Foundation/Console/ConfigCacheCommand.php
<ide> public function fire()
<ide> */
<ide> protected function getFreshConfiguration()
<ide> {
<del> $app = require $this->laravel['path.base'].'/bootstrap/app.php';
<add> $app = require $this->laravel->basePath().'/bootstrap/app.php';
<ide>
<ide> $app->make('Illuminate\Contracts\Console\Kernel')->bootstrap();
<ide>
<ide><path>src/Illuminate/Foundation/Console/RouteCacheCommand.php
<ide> public function fire()
<ide> */
<ide> protected function getFreshApplicationRoutes()
<ide> {
<del> $app = require $this->laravel['path.base'].'/bootstrap/app.php';
<add> $app = require $this->laravel->basePath().'/bootstrap/app.php';
<ide>
<ide> $app->make('Illuminate\Contracts\Console\Kernel')->bootstrap();
<ide>
<ide><path>src/Illuminate/Foundation/Providers/ComposerServiceProvider.php
<ide> public function register()
<ide> {
<ide> $this->app->singleton('composer', function($app)
<ide> {
<del> return new Composer($app['files'], $app['path.base']);
<add> return new Composer($app['files'], $app->basePath());
<ide> });
<ide> }
<ide>
<ide><path>src/Illuminate/Foundation/helpers.php
<ide> function auth()
<ide> */
<ide> function base_path($path = '')
<ide> {
<del> return app()->make('path.base').($path ? '/'.$path : $path);
<add> return app()->basePath().($path ? '/'.$path : $path);
<ide> }
<ide> }
<ide>
<ide><path>src/Illuminate/Queue/QueueServiceProvider.php
<ide> protected function registerListener()
<ide>
<ide> $this->app->singleton('queue.listener', function($app)
<ide> {
<del> return new Listener($app['path.base']);
<add> return new Listener($app->basePath());
<ide> });
<ide> }
<ide> | 8 |
Ruby | Ruby | remove outdated comment | 051061827cbcbcf26f77b01efa41347bde3933fa | <ide><path>Library/Homebrew/cmd/doctor.rb
<ide> def check_for_unlinked_but_not_keg_only
<ide> end
<ide> end.map{ |pn| pn.basename }
<ide>
<del> # NOTE very old kegs will be linked without the LinkedKegs symlink
<del> # this will trigger this warning but it's wrong, we could detect that though
<del> # but I don't feel like writing the code.
<del>
<ide> if not unlinked.empty? then <<-EOS.undent
<ide> You have unlinked kegs in your Cellar
<ide> Leaving kegs unlinked can lead to build-trouble and cause brews that depend on | 1 |
Text | Text | add a changelog entry for to_h deprecation | 694c9629804dc3ba1b3edf390e552070d841077b | <ide><path>activerecord/CHANGELOG.md
<add>* Deprecate `DatabaseConfigurations#to_h`. These connection hashes are still available via `ActiveRecord::Base.configurations.configs_for`.
<add>
<add> *Eileen Uchitelle*, *John Crepezzi*
<add>
<ide> * Add `DatabaseConfig#configuration_hash` to return database configuration hashes with symbol keys, and use all symbol-key configuration hashes internally. Deprecate `DatabaseConfig#config` which returns a String-keyed `Hash` with the same values.
<ide>
<ide> *John Crepezzi*, *Eileen Uchitelle* | 1 |
Ruby | Ruby | teach patch to uncompress patches if necessary | 0a2cdea5fd3f2c62bf79a99477ee6c177e5242a1 | <ide><path>Library/Homebrew/formula.rb
<ide> def stage
<ide> def patch
<ide> return if patches.empty?
<ide> ohai "Patching"
<del> if patches.kind_of? Hash
<del> patch_args=[]
<del> curl_args=[]
<del> n=0
<del> patches.each do |arg, urls|
<del> urls.each do |url|
<del> dst='%03d-homebrew.patch' % n+=1
<del> curl_args<<url<<'-o'<<dst
<del> patch_args<<["-#{arg}",'-i',dst]
<add> if not patches.kind_of? Hash
<add> # We assume -p0
<add> patch_defns = { :p0 => patches }
<add> else
<add> patch_defns = patches
<add> end
<add>
<add> patch_list=[]
<add> n=0
<add> patch_defns.each do |arg, urls|
<add> urls.each do |url|
<add> dst='%03d-homebrew.patch' % n+=1
<add> compression = false
<add> case url
<add> when /\.gz$/
<add> compression = :gzip
<add> when /\.bz2$/
<add> compression = :bzip2
<ide> end
<add> patch_list << {
<add> :curl_args => [url, '-o', dst],
<add> :args => ["-#{arg}",'-i', dst],
<add> :filename => dst,
<add> :compression => compression
<add> }
<ide> end
<del> # downloading all at once is much more efficient, espeically for FTP
<del> curl *curl_args
<del> patch_args.each do |args|
<del> # -f means it doesn't prompt the user if there are errors, if just
<del> # exits with non-zero status
<del> safe_system 'patch', '-f', *args
<add> end
<add> # downloading all at once is much more efficient, espeically for FTP
<add> curl *(patch_list.collect { |p| p[:curl_args] }).flatten
<add> patch_list.each do |p|
<add> case p[:compression]
<add> when :gzip
<add> # We rename with a .gz since gunzip -S '' deletes the file mysteriously
<add> FileUtils.mv p[:filename], p[:filename] + '.gz'
<add> `gunzip #{p[:filename] + '.gz'}`
<add> when :bzip2
<add> # We rename with a .bz2 since bunzip2 can't guess the original filename
<add> # without it
<add> FileUtils.mv p[:filename], p[:filename] + '.bz2'
<add> `bunzip2 #{p[:filename] + '.bz2'}`
<ide> end
<del> else
<del> ff=(1..patches.length).collect {|n| '%03d-homebrew.patch'%n}
<del> curl *patches+ff.collect {|f|"-o#{f}"}
<del> ff.each {|f| safe_system 'patch', '-p0', '-i', f}
<add> # -f means it doesn't prompt the user if there are errors, if just
<add> # exits with non-zero status
<add> safe_system 'patch', '-f', *(p[:args])
<ide> end
<ide> end
<ide> | 1 |
PHP | PHP | shuffle() | 43851636c4b5bf87ea81f6bfb108bc14db445446 | <ide><path>src/Illuminate/Support/Arr.php
<ide> public static function set(&$array, $key, $value)
<ide> * Shuffle the given array and return the result.
<ide> *
<ide> * @param array $array
<add> * @param int $seed
<ide> * @return array
<ide> */
<del> public static function shuffle($array)
<add> public static function shuffle($array, $seed = null)
<ide> {
<del> shuffle($array);
<add> if (is_null($seed)) {
<add> shuffle($array);
<add> } else {
<add> srand($seed);
<add>
<add> usort($array, function () {
<add> return rand(-1, 1);
<add> });
<add> }
<ide>
<ide> return $array;
<ide> }
<ide><path>src/Illuminate/Support/Collection.php
<ide> public function shift()
<ide> */
<ide> public function shuffle($seed = null)
<ide> {
<del> $items = $this->items;
<del>
<del> if (is_null($seed)) {
<del> shuffle($items);
<del> } else {
<del> srand($seed);
<del>
<del> usort($items, function () {
<del> return rand(-1, 1);
<del> });
<del> }
<del>
<del> return new static($items);
<add> return new static(Arr::shuffle($this->items, $seed));
<ide> }
<ide>
<ide> /**
<ide><path>tests/Support/SupportArrTest.php
<ide> public function testSet()
<ide> $this->assertEquals(['products' => ['desk' => ['price' => 200]]], $array);
<ide> }
<ide>
<add> public function testShuffleWithSeed()
<add> {
<add> $this->assertEquals(
<add> Arr::shuffle(range(0, 100, 10), 1234),
<add> Arr::shuffle(range(0, 100, 10), 1234)
<add> );
<add> }
<add>
<ide> public function testSort()
<ide> {
<ide> $unsorted = [ | 3 |
PHP | PHP | add text as a debugger output type | dfd860de7147d8759d6a68397fd44d68e6c92ceb | <ide><path>src/Error/Debugger.php
<ide> class Debugger
<ide> * @var array<string, class-string>
<ide> */
<ide> protected $renderers = [
<add> // Backwards compatible alias for text
<ide> 'txt' => TextRenderer::class,
<add> 'text' => TextRenderer::class,
<ide> ];
<ide>
<ide> /** | 1 |
Javascript | Javascript | add oninjecthelpers method | 1e86986a930c61c912effe0a62fa659f7ada15f7 | <ide><path>packages/ember-testing/lib/helpers.js
<ide> require('ember-testing/test');
<ide>
<ide> var Promise = Ember.RSVP.Promise,
<ide> get = Ember.get,
<del> helper = Ember.Test.registerHelper;
<add> helper = Ember.Test.registerHelper,
<add> pendingAjaxRequests = 0;
<add>
<add>
<add>Ember.Test.onInjectHelpers(function() {
<add> Ember.$(document).ajaxStart(function() {
<add> pendingAjaxRequests++;
<add> });
<add>
<add> Ember.$(document).ajaxStop(function() {
<add> pendingAjaxRequests--;
<add> });
<add>});
<add>
<ide>
<ide> function visit(app, url) {
<ide> Ember.run(app, app.handleURL, url);
<ide> function wait(app, value) {
<ide> var watcher = setInterval(function() {
<ide> var routerIsLoading = app.__container__.lookup('router:main').router.isLoading;
<ide> if (routerIsLoading) { return; }
<del> if (Ember.Test.pendingAjaxRequests) { return; }
<add> if (pendingAjaxRequests) { return; }
<ide> if (Ember.run.hasScheduledTimers() || Ember.run.currentRunLoop) { return; }
<ide> clearInterval(watcher);
<ide> start();
<ide><path>packages/ember-testing/lib/test.js
<ide> var slice = [].slice,
<ide> helpers = {},
<del> originalMethods = {};
<add> originalMethods = {},
<add> injectHelpersCallbacks = [];
<ide>
<ide> /**
<ide> @class Test
<ide> Ember.Test = {
<ide> helpers[name] = helperMethod;
<ide> },
<ide> /**
<add> @public
<ide> @method unregisterHelper
<ide> @param name {String}
<ide> */
<ide> Ember.Test = {
<ide> delete originalMethods[name];
<ide> },
<ide>
<del> pendingAjaxRequests: 0
<add> /**
<add> @public
<add>
<add> Used to register callbacks to be fired
<add> whenever `App.injectTestHelpers` is called
<add>
<add> The callback will receive the current application
<add> as an argument.
<add>
<add> @method unregisterHelper
<add> @param name {String}
<add> */
<add> onInjectHelpers: function(callback) {
<add> injectHelpersCallbacks.push(callback);
<add> }
<ide> };
<ide>
<ide>
<ide> Ember.Application.reopen({
<ide>
<ide> injectTestHelpers: function() {
<ide> this.testHelpers = {};
<del>
<del> Ember.$(document).ajaxStart(function() {
<del> Ember.Test.pendingAjaxRequests++;
<del> });
<del>
<del> Ember.$(document).ajaxStop(function() {
<del> Ember.Test.pendingAjaxRequests--;
<del> });
<del>
<ide> for (var name in helpers) {
<ide> originalMethods[name] = window[name];
<ide> this.testHelpers[name] = window[name] = curry(this, helpers[name]);
<ide> }
<add>
<add> for(var i = 0, l = injectHelpersCallbacks.length; i < l; i++) {
<add> injectHelpersCallbacks[i](this);
<add> }
<ide> },
<ide>
<ide> removeTestHelpers: function() { | 2 |
PHP | PHP | add boolean methods to schema facade | ae478939655c2e01cd59c14aef6454c5a3a72e4a | <ide><path>src/Illuminate/Support/Facades/Schema.php
<ide> * @method static \Illuminate\Database\Schema\Builder table(string $table, \Closure $callback)
<ide> * @method static \Illuminate\Database\Schema\Builder rename(string $from, string $to)
<ide> * @method static void defaultStringLength(int $length)
<add> * @method static bool hasTable(string $table)
<add> * @method static bool hasColumn(string $table, string $column)
<add> * @method static bool hasColumns(string $table, array $columns)
<ide> * @method static \Illuminate\Database\Schema\Builder disableForeignKeyConstraints()
<ide> * @method static \Illuminate\Database\Schema\Builder enableForeignKeyConstraints()
<ide> * @method static void registerCustomDoctrineType(string $class, string $name, string $type) | 1 |
Text | Text | standardize rest parameters | e1ddcb7219c8900473ecc343db2db86984d1688d | <ide><path>doc/api/console.md
<ide> The global `console` is a special `Console` whose output is sent to
<ide> new Console(process.stdout, process.stderr);
<ide> ```
<ide>
<del>### console.assert(value[, message][, ...])
<add>### console.assert(value[, message][, ...args])
<ide> <!-- YAML
<ide> added: v0.1.101
<ide> -->
<ide> Defaults to `2`. To make it recurse indefinitely, pass `null`.
<ide> Defaults to `false`. Colors are customizable; see
<ide> [customizing `util.inspect()` colors][].
<ide>
<del>### console.error([data][, ...])
<add>### console.error([data][, ...args])
<ide> <!-- YAML
<ide> added: v0.1.100
<ide> -->
<ide> If formatting elements (e.g. `%d`) are not found in the first string then
<ide> [`util.inspect()`][] is called on each argument and the resulting string
<ide> values are concatenated. See [`util.format()`][] for more information.
<ide>
<del>### console.info([data][, ...])
<add>### console.info([data][, ...args])
<ide> <!-- YAML
<ide> added: v0.1.100
<ide> -->
<ide>
<ide> The `console.info()` function is an alias for [`console.log()`][].
<ide>
<del>### console.log([data][, ...])
<add>### console.log([data][, ...args])
<ide> <!-- YAML
<ide> added: v0.1.100
<ide> -->
<ide> leaking it. On older versions, the timer persisted. This allowed
<ide> `console.timeEnd()` to be called multiple times for the same label. This
<ide> functionality was unintended and is no longer supported.*
<ide>
<del>### console.trace(message[, ...])
<add>### console.trace(message[, ...args])
<ide> <!-- YAML
<ide> added: v0.1.104
<ide> -->
<ide> console.trace('Show me');
<ide> // at REPLServer.Interface._ttyWrite (readline.js:826:14)
<ide> ```
<ide>
<del>### console.warn([data][, ...])
<add>### console.warn([data][, ...args])
<ide> <!-- YAML
<ide> added: v0.1.100
<ide> -->
<ide>
<ide> The `console.warn()` function is an alias for [`console.error()`][].
<ide>
<del>[`console.error()`]: #console_console_error_data
<del>[`console.log()`]: #console_console_log_data
<add>[`console.error()`]: #console_console_error_data_args
<add>[`console.log()`]: #console_console_log_data_args
<ide> [`console.time()`]: #console_console_time_label
<ide> [`console.timeEnd()`]: #console_console_timeend_label
<ide> [`process.stderr`]: process.html#process_process_stderr
<ide> [`process.stdout`]: process.html#process_process_stdout
<del>[`util.format()`]: util.html#util_util_format_format
<add>[`util.format()`]: util.html#util_util_format_format_args
<ide> [`util.inspect()`]: util.html#util_util_inspect_object_options
<ide> [customizing `util.inspect()` colors]: util.html#util_customizing_util_inspect_colors
<ide> [web-api-assert]: https://developer.mozilla.org/en-US/docs/Web/API/console/assert
<ide><path>doc/api/domain.md
<ide> uncaught exceptions to the active Domain object.
<ide> Domain is a child class of [`EventEmitter`][]. To handle the errors that it
<ide> catches, listen to its `'error'` event.
<ide>
<del>### domain.run(fn[, arg][, ...])
<add>### domain.run(fn[, ...args])
<ide>
<ide> * `fn` {Function}
<add>* `...args` {any}
<ide>
<ide> Run the supplied function in the context of the domain, implicitly
<ide> binding all event emitters, timers, and lowlevel requests that are
<ide> is emitted.
<ide> [`domain.exit()`]: #domain_domain_exit
<ide> [`Error`]: errors.html#errors_class_error
<ide> [`EventEmitter`]: events.html#events_class_eventemitter
<del>[`setInterval()`]: timers.html#timers_setinterval_callback_delay_arg
<del>[`setTimeout()`]: timers.html#timers_settimeout_callback_delay_arg
<add>[`setInterval()`]: timers.html#timers_setinterval_callback_delay_args
<add>[`setTimeout()`]: timers.html#timers_settimeout_callback_delay_args
<ide> [`throw`]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/throw
<ide><path>doc/api/events.md
<ide> added: v0.1.26
<ide>
<ide> Alias for `emitter.on(eventName, listener)`.
<ide>
<del>### emitter.emit(eventName[, arg1][, arg2][, ...])
<add>### emitter.emit(eventName[, ...args])
<ide> <!-- YAML
<ide> added: v0.1.26
<ide> -->
<ide><path>doc/api/globals.md
<ide> left untouched.
<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>## setImmediate(callback[, arg][, ...])
<add>## setImmediate(callback[, ...args])
<ide>
<ide> <!-- type=global -->
<ide>
<ide> [`setImmediate`] is described in the [timers][] section.
<ide>
<del>## setInterval(callback, delay[, arg][, ...])
<add>## setInterval(callback, delay[, ...args])
<ide>
<ide> <!-- type=global -->
<ide>
<ide> [`setInterval`] is described in the [timers][] section.
<ide>
<del>## setTimeout(callback, delay[, arg][, ...])
<add>## setTimeout(callback, delay[, ...args])
<ide>
<ide> <!-- type=global -->
<ide>
<ide> but rather than loading the module, just return the resolved filename.
<ide> [`clearImmediate`]: timers.html#timers_clearimmediate_immediate
<ide> [`clearInterval`]: timers.html#timers_clearinterval_timeout
<ide> [`clearTimeout`]: timers.html#timers_cleartimeout_timeout
<del>[`setImmediate`]: timers.html#timers_setimmediate_callback_arg
<del>[`setInterval`]: timers.html#timers_setinterval_callback_delay_arg
<del>[`setTimeout`]: timers.html#timers_settimeout_callback_delay_arg
<add>[`setImmediate`]: timers.html#timers_setimmediate_callback_args
<add>[`setInterval`]: timers.html#timers_setinterval_callback_delay_args
<add>[`setTimeout`]: timers.html#timers_settimeout_callback_delay_args
<ide> [built-in objects]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects
<ide><path>doc/api/path.md
<ide> path.isAbsolute('.') // false
<ide>
<ide> A [`TypeError`][] is thrown if `path` is not a string.
<ide>
<del>## path.join([path[, ...]])
<add>## path.join([...paths])
<ide> <!-- YAML
<ide> added: v0.1.16
<ide> -->
<ide>
<del>* `[path[, ...]]` {String} A sequence of path segments
<add>* `...paths` {String} A sequence of path segments
<ide>
<ide> The `path.join()` method join all given `path` segments together using the
<ide> platform specific separator as a delimiter, then normalizes the resulting path.
<ide> path.relative('C:\\orandea\\test\\aaa', 'C:\\orandea\\impl\\bbb')
<ide>
<ide> A [`TypeError`][] is thrown if neither `from` nor `to` is a string.
<ide>
<del>## path.resolve([path[, ...]])
<add>## path.resolve([...paths])
<ide> <!-- YAML
<ide> added: v0.3.4
<ide> -->
<ide>
<del>* `[path[, ...]]` {String} A sequence of paths or path segments
<add>* `...paths` {String} A sequence of paths or path segments
<ide>
<ide> The `path.resolve()` method resolves a sequence of paths or path segments into
<ide> an absolute path.
<ide><path>doc/api/process.md
<ide> Will generate:
<ide>
<ide> `heapTotal` and `heapUsed` refer to V8's memory usage.
<ide>
<del>## process.nextTick(callback[, arg][, ...])
<add>## process.nextTick(callback[, ...args])
<ide> <!-- YAML
<ide> added: v0.1.26
<ide> -->
<ide>
<ide> * `callback` {Function}
<del>* `[, arg][, ...]` {any} Additional arguments to pass when invoking the
<del> `callback`
<add>* `...args` {any} Additional arguments to pass when invoking the `callback`
<ide>
<ide> The `process.nextTick()` method adds the `callback` to the "next tick queue".
<ide> Once the current turn of the event loop turn runs to completion, all callbacks
<ide> cases:
<ide> [`process.execPath`]: #process_process_execpath
<ide> [`promise.catch()`]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise/catch
<ide> [`require.main`]: modules.html#modules_accessing_the_main_module
<del>[`setTimeout(fn, 0)`]: timers.html#timers_settimeout_callback_delay_arg
<add>[`setTimeout(fn, 0)`]: timers.html#timers_settimeout_callback_delay_args
<ide> [process_emit_warning]: #process_process_emitwarning_warning_name_ctor
<ide> [process_warning]: #process_event_warning
<ide> [Signal Events]: #process_signal_events
<ide><path>doc/api/timers.md
<ide> a certain period of time. When a timer's function is called varies depending on
<ide> which method was used to create the timer and what other work the Node.js
<ide> event loop is doing.
<ide>
<del>### setImmediate(callback[, ...arg])
<add>### setImmediate(callback[, ...args])
<ide> <!-- YAML
<ide> added: v0.9.1
<ide> -->
<ide>
<ide> * `callback` {Function} The function to call at the end of this turn of
<ide> [the Node.js Event Loop]
<del>* `[, ...arg]` Optional arguments to pass when the `callback` is called.
<add>* `...args` {any} Optional arguments to pass when the `callback` is called.
<ide>
<ide> Schedules the "immediate" execution of the `callback` after I/O events'
<ide> callbacks and before timers created using [`setTimeout()`][] and
<ide> next event loop iteration.
<ide>
<ide> If `callback` is not a function, a [`TypeError`][] will be thrown.
<ide>
<del>### setInterval(callback, delay[, ...arg])
<add>### setInterval(callback, delay[, ...args])
<ide> <!-- YAML
<ide> added: v0.0.1
<ide> -->
<ide>
<ide> * `callback` {Function} The function to call when the timer elapses.
<ide> * `delay` {number} The number of milliseconds to wait before calling the
<ide> `callback`.
<del>* `[, ...arg]` Optional arguments to pass when the `callback` is called.
<add>* `...args` {any} Optional arguments to pass when the `callback` is called.
<ide>
<ide> Schedules repeated execution of `callback` every `delay` milliseconds.
<ide> Returns a `Timeout` for use with [`clearInterval()`][].
<ide> set to `1`.
<ide>
<ide> If `callback` is not a function, a [`TypeError`][] will be thrown.
<ide>
<del>### setTimeout(callback, delay[, ...arg])
<add>### setTimeout(callback, delay[, ...args])
<ide> <!-- YAML
<ide> added: v0.0.1
<ide> -->
<ide>
<ide> * `callback` {Function} The function to call when the timer elapses.
<ide> * `delay` {number} The number of milliseconds to wait before calling the
<ide> `callback`.
<del>* `[, ...arg]` Optional arguments to pass when the `callback` is called.
<add>* `...args` {any} Optional arguments to pass when the `callback` is called.
<ide>
<ide> Schedules execution of a one-time `callback` after `delay` milliseconds.
<ide> Returns a `Timeout` for use with [`clearTimeout()`][].
<ide> Cancels a `Timeout` object created by [`setTimeout()`][].
<ide> [`clearImmediate()`]: timers.html#timers_clearimmediate_immediate
<ide> [`clearInterval()`]: timers.html#timers_clearinterval_timeout
<ide> [`clearTimeout()`]: timers.html#timers_cleartimeout_timeout
<del>[`setImmediate()`]: timers.html#timers_setimmediate_callback_arg
<del>[`setInterval()`]: timers.html#timers_setinterval_callback_delay_arg
<del>[`setTimeout()`]: timers.html#timers_settimeout_callback_delay_arg
<add>[`setImmediate()`]: timers.html#timers_setimmediate_callback_args
<add>[`setInterval()`]: timers.html#timers_setinterval_callback_delay_args
<add>[`setTimeout()`]: timers.html#timers_settimeout_callback_delay_args
<ide><path>doc/api/util.md
<ide> The `--throw-deprecation` command line flag and `process.throwDeprecation`
<ide> property take precedence over `--trace-deprecation` and
<ide> `process.traceDeprecation`.
<ide>
<del>## util.format(format[, ...])
<add>## util.format(format[, ...args])
<ide> <!-- YAML
<ide> added: v0.5.3
<ide> -->
<ide>
<del>* `format` {string} A `printf`-like format string.
<add>* `format` {String} A `printf`-like format string.
<ide>
<ide> The `util.format()` method returns a formatted string using the first argument
<ide> as a `printf`-like format.
<ide> deprecated: v0.11.3
<ide>
<ide> > Stability: 0 - Deprecated: Use [`console.error()`][] instead.
<ide>
<del>* `string` {string} The message to print to `stderr`
<add>* `string` {String} The message to print to `stderr`
<ide>
<ide> Deprecated predecessor of `console.error`.
<ide>
<del>### util.error([...])
<add>### util.error([...strings])
<ide> <!-- YAML
<ide> added: v0.3.0
<ide> deprecated: v0.11.3
<ide> -->
<ide>
<ide> > Stability: 0 - Deprecated: Use [`console.error()`][] instead.
<ide>
<del>* `string` {string} The message to print to `stderr`
<add>* `...strings` {String} The message to print to `stderr`
<ide>
<ide> Deprecated predecessor of `console.error`.
<ide>
<ide> deprecated: v6.0.0
<ide>
<ide> > Stability: 0 - Deprecated: Use a third party module instead.
<ide>
<del>* `string` {string}
<add>* `string` {String}
<ide>
<ide> The `util.log()` method prints the given `string` to `stdout` with an included
<ide> timestamp.
<ide> const util = require('util');
<ide> util.log('Timestamped message.');
<ide> ```
<ide>
<del>### util.print([...])
<add>### util.print([...strings])
<ide> <!-- YAML
<ide> added: v0.3.0
<ide> deprecated: v0.11.3
<ide> deprecated: v0.11.3
<ide>
<ide> Deprecated predecessor of `console.log`.
<ide>
<del>### util.puts([...])
<add>### util.puts([...strings])
<ide> <!-- YAML
<ide> added: v0.3.0
<ide> deprecated: v0.11.3
<ide> similar built-in functionality through [`Object.assign()`].
<ide> [Customizing `util.inspect` colors]: #util_customizing_util_inspect_colors
<ide> [Custom inspection functions on Objects]: #util_custom_inspection_functions_on_objects
<ide> [`Error`]: errors.html#errors_class_error
<del>[`console.log()`]: console.html#console_console_log_data
<del>[`console.error()`]: console.html#console_console_error_data
<add>[`console.log()`]: console.html#console_console_log_data_args
<add>[`console.error()`]: console.html#console_console_error_data_args
<ide> [`Buffer.isBuffer()`]: buffer.html#buffer_class_method_buffer_isbuffer_obj
<ide> [`Object.assign()`]: https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/Object/assign | 8 |
Text | Text | improve sentence structure | 11a0829e2d6c9c2947e2fdb18fc3df36d88aebfd | <ide><path>guides/source/action_controller_overview.md
<ide> In addition to "before" filters, you can also run filters after an action has be
<ide>
<ide> "around" filters are responsible for running their associated actions by yielding, similar to how Rack middlewares work.
<ide>
<del>For example, in a website where changes have an approval workflow an administrator could be able to preview them easily, just apply them within a transaction:
<add>For example, in a website where changes have an approval workflow, an administrator could preview them easily by applying them within a transaction:
<ide>
<ide> ```ruby
<ide> class ChangesController < ApplicationController
<ide> class ChangesController < ApplicationController
<ide> end
<ide> ```
<ide>
<del>Note that an "around" filter also wraps rendering. In particular, if in the example above, the view itself reads from the database (e.g. via a scope), it will do so within the transaction and thus present the data to preview.
<add>Note that an "around" filter also wraps rendering. In particular, in the example above, if the view itself reads from the database (e.g. via a scope), it will do so within the transaction and thus present the data to preview.
<ide>
<ide> You can choose not to yield and build the response yourself, in which case the action will not be run.
<ide>
<ide> class ApplicationController < ActionController::Base
<ide> end
<ide> ```
<ide>
<del>Note that the filter in this case uses `send` because the `logged_in?` method is private and the filter does not run in the scope of the controller. This is not the recommended way to implement this particular filter, but in more simple cases it might be useful.
<add>Note that the filter in this case uses `send` because the `logged_in?` method is private and the filter does not run in the scope of the controller. This is not the recommended way to implement this particular filter, but in simpler cases it might be useful.
<ide>
<ide> Specifically for `around_action`, the block also yields in the `action`:
<ide> | 1 |
Python | Python | fix verification of managed identity | c5c18c54fa83463bc953249dc28edcbf7179da17 | <ide><path>airflow/providers/databricks/hooks/databricks.py
<ide> def _check_azure_metadata_service() -> None:
<ide> """
<ide> try:
<ide> jsn = requests.get(
<del> AZURE_METADATA_SERVICE_TOKEN_URL,
<add> AZURE_METADATA_SERVICE_INSTANCE_URL,
<ide> params={"api-version": "2021-02-01"},
<ide> headers={"Metadata": "true"},
<ide> timeout=2,
<ide><path>tests/providers/databricks/hooks/test_databricks.py
<ide> from airflow.providers.databricks.hooks.databricks import (
<ide> AZURE_DEFAULT_AD_ENDPOINT,
<ide> AZURE_MANAGEMENT_ENDPOINT,
<del> AZURE_METADATA_SERVICE_TOKEN_URL,
<add> AZURE_METADATA_SERVICE_INSTANCE_URL,
<ide> AZURE_TOKEN_SERVICE_URL,
<ide> DEFAULT_DATABRICKS_SCOPE,
<ide> SUBMIT_RUN_ENDPOINT,
<ide> def test_submit_run(self, mock_requests):
<ide> run_id = self.hook.submit_run(data)
<ide>
<ide> ad_call_args = mock_requests.method_calls[0]
<del> assert ad_call_args[1][0] == AZURE_METADATA_SERVICE_TOKEN_URL
<add> assert ad_call_args[1][0] == AZURE_METADATA_SERVICE_INSTANCE_URL
<ide> assert ad_call_args[2]['params']['api-version'] > '2018-02-01'
<ide> assert ad_call_args[2]['headers']['Metadata'] == 'true'
<ide> | 2 |
PHP | PHP | apply fixes from styleci | f646f8a8c594e83217079763b8ac20c260828da4 | <ide><path>tests/Support/SupportCollectionTest.php
<ide> public function testReduce($collection)
<ide> $this->assertEquals(6, $data->reduce(function ($carry, $element) {
<ide> return $carry += $element;
<ide> }));
<del>
<add>
<ide> $data = new $collection([
<ide> 'foo' => 'bar',
<ide> 'baz' => 'qux', | 1 |
Javascript | Javascript | show error for component class/invocation mismatch | 912392ea5d7d5bb607c0914c40b5810dbef3d4bd | <ide><path>packages/ember-htmlbars/lib/node-managers/component-node-manager.js
<ide> import setProperties from 'ember-metal/set_properties';
<ide> import { MUTABLE_CELL } from 'ember-views/compat/attrs-proxy';
<ide> import SafeString from 'htmlbars-util/safe-string';
<ide> import { instrument } from 'ember-htmlbars/system/instrumentation-support';
<del>import EmberComponent from 'ember-views/components/component';
<add>import LegacyEmberComponent from 'ember-views/components/component';
<add>import GlimmerComponent from 'ember-htmlbars/glimmer-component';
<ide> import Stream from 'ember-metal/streams/stream';
<ide> import { readArray } from 'ember-metal/streams/utils';
<ide>
<ide> ComponentNodeManager.create = function(renderNode, env, options) {
<ide> return component || layout;
<ide> });
<ide>
<del> component = component || EmberComponent;
<add> component = component || (isAngleBracket ? GlimmerComponent : LegacyEmberComponent);
<ide>
<ide> let createOptions = { parentView };
<ide>
<ide> ComponentNodeManager.create = function(renderNode, env, options) {
<ide> // Instantiate the component
<ide> component = createComponent(component, isAngleBracket, createOptions, renderNode, env, attrs, proto);
<ide>
<add> Ember.runInDebug(() => {
<add> if (isAngleBracket) {
<add> Ember.assert(`You cannot invoke the '${tagName}' component with angle brackets, because it's a subclass of Component. Please upgrade to GlimmerComponent. Alternatively, you can invoke as '{{${tagName}}}'.`, component.isGlimmerComponent);
<add> } else {
<add> Ember.assert(`You cannot invoke the '${tagName}' component with curly braces, because it's a subclass of GlimmerComponent. Please invoke it as '<${tagName}>' instead.`, !component.isGlimmerComponent);
<add> }
<add> });
<add>
<ide> // If the component specifies its template via the `layout` or `template`
<ide> // properties instead of using the template looked up in the container, get
<ide> // them now that we have the component instance.
<ide><path>packages/ember-htmlbars/tests/integration/component_invocation_test.js
<ide> QUnit.test('non-block without properties', function() {
<ide> equal(jQuery('#qunit-fixture').text(), 'In layout');
<ide> });
<ide>
<add>QUnit.test('GlimmerComponent cannot be invoked with curly braces', function() {
<add> registry.register('template:components/non-block', compile('In layout'));
<add> registry.register('component:non-block', GlimmerComponent.extend());
<add>
<add> expectAssertion(function() {
<add> view = appendViewFor('{{non-block}}');
<add> }, /cannot invoke the 'non-block' component with curly braces/);
<add>});
<add>
<ide> QUnit.test('block without properties', function() {
<ide> expect(1);
<ide>
<ide> if (isEnabled('ember-htmlbars-component-generation')) {
<ide> equal(view.$().html(), 'In layout', 'Just the fragment was used');
<ide> });
<ide>
<add> QUnit.test('legacy components cannot be invoked with angle brackets', function() {
<add> registry.register('template:components/non-block', compile('In layout'));
<add> registry.register('component:non-block', Component.extend());
<add>
<add> expectAssertion(function() {
<add> view = appendViewFor('<non-block />');
<add> }, /cannot invoke the 'non-block' component with angle brackets/);
<add> });
<add>
<ide> QUnit.test('non-block without properties replaced with a fragment when the content is multiple elements', function() {
<ide> registry.register('template:components/non-block', compile('<div>This is a</div><div>fragment</div>'));
<ide>
<ide> if (isEnabled('ember-htmlbars-component-generation')) {
<ide> registry.register('template:components/non-block', compile('<non-block>In layout - someProp: {{attrs.someProp}}</non-block>'));
<ide>
<ide> view = appendViewFor('<non-block someProp="something here" />');
<add> console.log(jQuery('#qunit-fixture').html());
<ide>
<ide> equal(jQuery('#qunit-fixture').text(), 'In layout - someProp: something here');
<ide> });
<ide> if (isEnabled('ember-htmlbars-component-generation')) {
<ide> moduleName: layoutModuleName
<ide> });
<ide> registry.register('template:components/sample-component', sampleComponentLayout);
<del> registry.register('component:sample-component', Component.extend({
<add> registry.register('component:sample-component', GlimmerComponent.extend({
<ide> didInsertElement: function() {
<ide> equal(this._renderNode.lastResult.template.meta.moduleName, layoutModuleName);
<ide> } | 2 |
Javascript | Javascript | move _detailedexception into util | 3937e8566da9eef72072d9b1737cf5859c65b543 | <ide><path>lib/net.js
<ide> var WriteWrap = process.binding('stream_wrap').WriteWrap;
<ide>
<ide> var cluster;
<ide> var errnoException = util._errnoException;
<add>var detailedException = util._detailedException;
<ide>
<ide> function noop() {}
<ide>
<ide> function isPipeName(s) {
<ide> return util.isString(s) && toNumber(s) === false;
<ide> }
<ide>
<del>// format exceptions
<del>function detailedException(err, syscall, address, port, additional) {
<del> var details;
<del> if (port && port > 0) {
<del> details = address + ':' + port;
<del> } else {
<del> details = address;
<del> }
<del>
<del> if (additional) {
<del> details += ' - Local (' + additional + ')';
<del> }
<del> var ex = errnoException(err, syscall, details);
<del> ex.address = address;
<del> if (port) {
<del> ex.port = port;
<del> }
<del> return ex;
<del>}
<del>
<ide> exports.createServer = function() {
<ide> return new Server(arguments[0], arguments[1]);
<ide> };
<ide><path>lib/util.js
<ide> exports._errnoException = function(err, syscall, original) {
<ide> e.syscall = syscall;
<ide> return e;
<ide> };
<add>
<add>
<add>exports._detailedException = function(err, syscall, address, port, additional) {
<add> var details;
<add> if (port && port > 0) {
<add> details = address + ':' + port;
<add> } else {
<add> details = address;
<add> }
<add>
<add> if (additional) {
<add> details += ' - Local (' + additional + ')';
<add> }
<add> var ex = exports._errnoException(err, syscall, details);
<add> ex.address = address;
<add> if (port) {
<add> ex.port = port;
<add> }
<add> return ex;
<add>}; | 2 |
Javascript | Javascript | ignore coverage for tostringtag | e80bcac1b5cac99cf003c3236490bf35bc350bed | <ide><path>lib/util/LazySet.js
<ide> class LazySet {
<ide> return this._set[Symbol.iterator]();
<ide> }
<ide>
<add> /* istanbul ignore next */
<ide> get [Symbol.toStringTag]() {
<ide> return "LazySet";
<ide> } | 1 |
Ruby | Ruby | add missing sentence | bba22cedb4f3fc2554ab54175be3e20a701d53c8 | <ide><path>actionpack/lib/action_controller/url_rewriter.rb
<ide> def self.included(base) #:nodoc:
<ide> end
<ide>
<ide> # Generate a url based on the options provided, default_url_options and the
<del> # routes defined in routes.rb
<del> #
<del> # Options used by <tt>url_for</tt>:
<add> # routes defined in routes.rb. The following options are supported:
<ide> #
<ide> # * <tt>:only_path</tt> If true, the relative url is returned. Defaults to false.
<ide> # * <tt>:protocol</tt> The protocol to connect to. Defaults to 'http'. | 1 |
Javascript | Javascript | add expando prop to disabledlog function | 9e5b2c94e63fdd007afcc21535f07b4f61b05ddc | <ide><path>packages/shared/ConsolePatchingDev.js
<ide> let prevWarn;
<ide> let prevError;
<ide>
<ide> function disabledLog() {}
<add>disabledLog.__reactDisabledLog = true;
<ide>
<ide> export function disableLogs(): void {
<ide> if (__DEV__) { | 1 |
Javascript | Javascript | add test for setcomponentmanager with a factory | 05301603cdb00f800473ca3d8eb941ea63254f07 | <ide><path>packages/@ember/-internals/glimmer/tests/integration/custom-component-manager-test.js
<ide> import {
<ide> import { setComponentManager, capabilities } from '@ember/-internals/glimmer';
<ide>
<ide> if (GLIMMER_CUSTOM_COMPONENT_MANAGER) {
<del> class ComponentManagerTest extends RenderingTest {
<del> constructor(assert) {
<del> super(...arguments);
<add> let BasicComponentManager = EmberObject.extend({
<add> capabilities: capabilities('3.4'),
<ide>
<del> this.registerComponentManager(
<del> 'basic',
<del> EmberObject.extend({
<del> capabilities: capabilities('3.4'),
<add> createComponent(factory, args) {
<add> return factory.create({ args });
<add> },
<ide>
<del> createComponent(factory, args) {
<del> return factory.create({ args });
<del> },
<add> updateComponent(component, args) {
<add> set(component, 'args', args);
<add> },
<ide>
<del> updateComponent(component, args) {
<del> set(component, 'args', args);
<del> },
<add> getContext(component) {
<add> return component;
<add> },
<add> });
<ide>
<del> getContext(component) {
<del> return component;
<del> },
<del> })
<del> );
<add> class ComponentManagerTest extends RenderingTest {
<add> constructor(assert) {
<add> super(...arguments);
<add>
<add> this.registerComponentManager('basic', BasicComponentManager);
<ide>
<ide> this.registerComponentManager(
<ide> 'instrumented-full',
<ide> if (GLIMMER_CUSTOM_COMPONENT_MANAGER) {
<ide> this.assertHTML(`<p>hello world</p>`);
<ide> }
<ide>
<add> ['@test it can render a basic component with custom component manager with a factory']() {
<add> let ComponentClass = setComponentManager(
<add> () => BasicComponentManager.create(),
<add> EmberObject.extend({
<add> greeting: 'hello',
<add> })
<add> );
<add>
<add> this.registerComponent('foo-bar', {
<add> template: `<p>{{greeting}} world</p>`,
<add> ComponentClass,
<add> });
<add>
<add> this.render('{{foo-bar}}');
<add>
<add> this.assertHTML(`<p>hello world</p>`);
<add> }
<add>
<ide> ['@test it can have no template context']() {
<ide> this.registerComponentManager(
<ide> 'pseudo-template-only', | 1 |
Javascript | Javascript | keep variable names for skinindex and nodeindex | 6f5c72e9ecf6507bff3dff43e9d50b2134fcebb5 | <ide><path>examples/js/loaders/GLTFLoader.js
<ide> THREE.GLTFLoader = ( function () {
<ide>
<ide> // Nothing in the node definition indicates whether it is a Bone or an
<ide> // Object3D. Use the skins' joint references to mark bones.
<del> for ( var i = 0; i < skins.length; i ++ ) {
<add> for ( var skinIndex = 0; skinIndex < skins.length; skinIndex ++ ) {
<ide>
<del> var joints = skins[ i ].joints;
<add> var joints = skins[ skinIndex ].joints;
<ide>
<del> for ( var j = 0; j < joints.length; ++ j ) {
<add> for ( var i = 0; i < joints.length; ++ i ) {
<ide>
<del> nodes[ joints[ j ] ].isBone = true;
<add> nodes[ joints[ i ] ].isBone = true;
<ide>
<ide> }
<ide>
<ide> THREE.GLTFLoader = ( function () {
<ide> // references and rename instances below.
<ide> //
<ide> // Example: CesiumMilkTruck sample model reuses "Wheel" meshes.
<del> for ( var i = 0; i < nodes.length; i ++ ) {
<add> for ( var nodeIndex = 0; nodeIndex < nodes.length; nodeIndex ++ ) {
<ide>
<del> var nodeDef = nodes[ i ];
<add> var nodeDef = nodes[ nodeIndex ];
<ide>
<ide> if ( nodeDef.mesh !== undefined ) {
<ide> | 1 |
PHP | PHP | fix failing test | 453b5988b74ed51a2b3243bf3d3323bb0db91ba4 | <ide><path>tests/TestCase/Utility/DebuggerTest.php
<ide> public function testExportVar() {
<ide> (int) 10 => 'passedArgs',
<ide> (int) 11 => 'cacheAction'
<ide> ]
<del> [protected] _scripts => []
<ide> [protected] _paths => []
<ide> [protected] _pathsForPlugin => []
<ide> [protected] _parents => [] | 1 |
PHP | PHP | add a set method to object registry | 90946c3d29da6f51448188f8209be2a3d2234e88 | <ide><path>Cake/Utility/ObjectRegistry.php
<ide> abstract class ObjectRegistry {
<ide> * If a subclass provides event support, you can use `$settings['enabled'] = false`
<ide> * to exclude constructed objects from being registered for events.
<ide> *
<del> * Using Cake\Controller\Controller::$components as an example. You can alias
<add> * Using Cake\Controller\Controller::$components as an example. You can alias
<ide> * an object by setting the 'className' key, i.e.,
<ide> *
<ide> * {{{
<ide> public function reset() {
<ide> $this->_loaded = [];
<ide> }
<ide>
<add>/**
<add> * set an object directly into the registry by name
<add> *
<add> * This is primarily to aide testing
<add> *
<add> * @param string $objectName
<add> * @param object $object instance to store in the registry
<add> * @return void
<add> */
<add> public function set($objectName, $object) {
<add> list($plugin, $name) = pluginSplit($objectName);
<add> $this->_loaded[$name] = $object;
<add> }
<add>
<ide> } | 1 |
Javascript | Javascript | keep the routes in jsx | aec8ca40dc49600b3b5c068bcab4b6a2394e9c61 | <ide><path>examples/real-world/containers/Root.dev.js
<ide> import React, { Component, PropTypes } from 'react'
<ide> import { Provider } from 'react-redux'
<del>import Routes from '../routes'
<add>import routes from '../routes'
<ide> import DevTools from './DevTools'
<add>import { Router, browserHistory } from 'react-router'
<ide>
<ide> export default class Root extends Component {
<ide> render() {
<ide> const { store } = this.props
<ide> return (
<ide> <Provider store={store}>
<ide> <div>
<del> <Routes />
<add> <Router history={browserHistory} routes={routes} />
<ide> <DevTools />
<ide> </div>
<ide> </Provider>
<ide><path>examples/real-world/containers/Root.prod.js
<ide> import React, { Component, PropTypes } from 'react'
<ide> import { Provider } from 'react-redux'
<del>
<del>import Routes from '../routes'
<add>import routes from '../routes'
<add>import { Router, browserHistory } from 'react-router'
<ide>
<ide> export default class Root extends Component {
<ide> render() {
<ide> const { store } = this.props
<ide> return (
<ide> <Provider store={store}>
<del> <Routes />
<add> <Router history={browserHistory} routes={routes} />
<ide> </Provider>
<ide> )
<ide> }
<ide><path>examples/real-world/routes.js
<ide> import React from 'react'
<del>import { Route, browserHistory, Router } from 'react-router'
<add>import { Route } from 'react-router'
<ide> import App from './containers/App'
<ide> import UserPage from './containers/UserPage'
<ide> import RepoPage from './containers/RepoPage'
<ide>
<del>export default function Routes() {
<del> return (
<del> <Router history={browserHistory}>
<del> <Route path="/" component={App}>
<del> <Route path="/:login/:name"
<del> component={RepoPage} />
<del> <Route path="/:login"
<del> component={UserPage} />
<del> </Route>
<del> </Router>
<del> )
<del>}
<add>export default (
<add> <Route path="/" component={App}>
<add> <Route path="/:login/:name"
<add> component={RepoPage} />
<add> <Route path="/:login"
<add> component={UserPage} />
<add> </Route>
<add>) | 3 |
Javascript | Javascript | use log only in test-child-process-fork-net | c82a9583ce9ac3af18e4eaea96145fec57bf6a10 | <ide><path>test/parallel/test-child-process-fork-net.js
<ide> const assert = require('assert');
<ide> const fork = require('child_process').fork;
<ide> const net = require('net');
<ide>
<del>// progress tracker
<ide> function ProgressTracker(missing, callback) {
<ide> this.missing = missing;
<ide> this.callback = callback;
<ide> if (process.argv[2] === 'child') {
<ide> socket.destroy();
<ide> });
<ide>
<del> // start making connection from parent
<add> // Start making connection from parent.
<ide> console.log('CHILD: server listening');
<ide> process.send({ what: 'listening' });
<ide> });
<ide> if (process.argv[2] === 'child') {
<ide> assert.strictEqual(code, 0, message);
<ide> }));
<ide>
<del> // send net.Server to child and test by connecting
<add> // Send net.Server to child and test by connecting.
<ide> function testServer(callback) {
<ide>
<del> // destroy server execute callback when done
<add> // Destroy server execute callback when done.
<ide> const progress = new ProgressTracker(2, function() {
<ide> server.on('close', function() {
<ide> console.log('PARENT: server closed');
<ide> if (process.argv[2] === 'child') {
<ide> server.close();
<ide> });
<ide>
<del> // we expect 4 connections and close events
<add> // We expect 4 connections and close events.
<ide> const connections = new ProgressTracker(4, progress.done.bind(progress));
<ide> const closed = new ProgressTracker(4, progress.done.bind(progress));
<ide>
<del> // create server and send it to child
<add> // Create server and send it to child.
<ide> const server = net.createServer();
<ide> server.on('connection', function(socket) {
<ide> console.log('PARENT: got connection');
<ide> if (process.argv[2] === 'child') {
<ide> });
<ide> server.listen(0);
<ide>
<del> // handle client messages
<add> // Handle client messages.
<ide> function messageHandlers(msg) {
<ide>
<ide> if (msg.what === 'listening') {
<del> // make connections
<add> // Make connections.
<ide> let socket;
<ide> for (let i = 0; i < 4; i++) {
<ide> socket = net.connect(server.address().port, function() {
<ide> if (process.argv[2] === 'child') {
<ide> child.on('message', messageHandlers);
<ide> }
<ide>
<del> // send net.Socket to child
<add> // Send net.Socket to child.
<ide> function testSocket(callback) {
<ide>
<del> // create a new server and connect to it,
<del> // but the socket will be handled by the child
<add> // Create a new server and connect to it,
<add> // but the socket will be handled by the child.
<ide> const server = net.createServer();
<ide> server.on('connection', function(socket) {
<ide> socket.on('close', function() {
<ide> if (process.argv[2] === 'child') {
<ide> console.log('PARENT: server closed');
<ide> callback();
<ide> });
<del> // don't listen on the same port, because SmartOS sometimes says
<add> // Don't listen on the same port, because SmartOS sometimes says
<ide> // that the server's fd is closed, but it still cannot listen
<ide> // on the same port again.
<ide> //
<ide> // An isolated test for this would be lovely, but for now, this
<ide> // will have to do.
<ide> server.listen(0, function() {
<del> console.error('testSocket, listening');
<add> console.log('testSocket, listening');
<ide> const connect = net.connect(server.address().port);
<ide> let store = '';
<ide> connect.on('data', function(chunk) {
<ide> if (process.argv[2] === 'child') {
<ide> });
<ide> }
<ide>
<del> // create server and send it to child
<add> // Create server and send it to child.
<ide> let serverSuccess = false;
<ide> let socketSuccess = false;
<ide> child.on('message', function onReady(msg) { | 1 |
Java | Java | improve performance of stompencoder | 774e4c3dc10035448d12e5f883823c260569f891 | <ide><path>spring-messaging/src/main/java/org/springframework/messaging/simp/stomp/StompEncoder.java
<ide> public byte[] encode(Map<String, Object> headers, byte[] payload) {
<ide> }
<ide> else {
<ide> StompCommand command = StompHeaderAccessor.getCommand(headers);
<del> Assert.notNull(command, "Missing STOMP command: " + headers);
<add> if (command == null) {
<add> throw new IllegalStateException("Missing STOMP command: " + headers);
<add> }
<add>
<ide> output.write(command.toString().getBytes(StandardCharsets.UTF_8));
<ide> output.write(LF);
<ide> writeHeaders(command, headers, payload, output);
<ide> private void writeHeaders(StompCommand command, Map<String, Object> headers, byt
<ide> boolean shouldEscape = (command != StompCommand.CONNECT && command != StompCommand.CONNECTED);
<ide>
<ide> for (Entry<String, List<String>> entry : nativeHeaders.entrySet()) {
<del> byte[] key = encodeHeaderString(entry.getKey(), shouldEscape);
<ide> if (command.requiresContentLength() && "content-length".equals(entry.getKey())) {
<ide> continue;
<ide> }
<add>
<ide> List<String> values = entry.getValue();
<ide> if (StompCommand.CONNECT.equals(command) &&
<ide> StompHeaderAccessor.STOMP_PASSCODE_HEADER.equals(entry.getKey())) {
<ide> values = Arrays.asList(StompHeaderAccessor.getPasscode(headers));
<ide> }
<add>
<add> byte[] encodedKey = encodeHeaderString(entry.getKey(), shouldEscape);
<ide> for (String value : values) {
<del> output.write(key);
<add> output.write(encodedKey);
<ide> output.write(COLON);
<ide> output.write(encodeHeaderString(value, shouldEscape));
<ide> output.write(LF);
<ide> }
<ide> }
<add>
<ide> if (command.requiresContentLength()) {
<ide> int contentLength = payload.length;
<ide> output.write("content-length:".getBytes(StandardCharsets.UTF_8)); | 1 |
Python | Python | fix typo in setup.py | 271c0809d29acbf75d2b4d637fa78a5fc5ce6ebb | <ide><path>numpy/random/setup.py
<ide> def generate_libraries(ext, build_dir):
<ide> if sys.platform == 'cygwin':
<ide> # Export symbols without __declspec(dllexport) for using by cython.
<ide> # Using __declspec(dllexport) does not export other necessary symbols
<del> # in Cygwin package's Cython enviroment, making it impossible to
<add> # in Cygwin package's Cython environment, making it impossible to
<ide> # import modules.
<ide> EXTRA_LINK_ARGS += ['-Wl,--export-all-symbols']
<ide> | 1 |
Text | Text | update redis cache store docs | a6b82a37797bad04ef32b2ec500ad1a2107ea5f0 | <ide><path>guides/source/caching_with_rails.md
<ide> config.cache_store = :mem_cache_store, "cache-1.example.com", "cache-2.example.c
<ide>
<ide> ### ActiveSupport::Cache::RedisCacheStore
<ide>
<del>The Redis cache store takes advantage of Redis support for least-recently-used
<del>and least-frequently-used key eviction when it reaches max memory, allowing it
<del>to behave much like a Memcached cache server.
<add>The Redis cache store takes advantage of Redis support for automatic eviction
<add>when it reaches max memory, allowing it to behave much like a Memcached cache server.
<ide>
<ide> Deployment note: Redis doesn't expire keys by default, so take care to use a
<ide> dedicated Redis cache server. Don't fill up your persistent-Redis server with
<ide> volatile cache data! Read the
<ide> [Redis cache server setup guide](https://redis.io/topics/lru-cache) in detail.
<ide>
<del>For an all-cache Redis server, set `maxmemory-policy` to an `allkeys` policy.
<del>Redis 4+ support least-frequently-used (`allkeys-lfu`) eviction, an excellent
<del>default choice. Redis 3 and earlier should use `allkeys-lru` for
<del>least-recently-used eviction.
<add>For a cache-only Redis server, set `maxmemory-policy` to one of the variants of allkeys.
<add>Redis 4+ supports least-frequently-used eviction (`allkeys-lfu`), an excellent
<add>default choice. Redis 3 and earlier should use least-recently-used eviction (`allkeys-lru`).
<ide>
<ide> Set cache read and write timeouts relatively low. Regenerating a cached value
<ide> is often faster than waiting more than a second to retrieve it. Both read and
<ide> write timeouts default to 1 second, but may be set lower if your network is
<del>consistently low latency.
<add>consistently low-latency.
<ide>
<ide> By default, the cache store will not attempt to reconnect to Redis if the
<ide> connection fails during a request. If you experience frequent disconnects you
<ide> may wish to enable reconnect attempts.
<ide>
<del>Cache reads and writes never raise exceptions. They just return `nil` instead,
<add>Cache reads and writes never raise exceptions; they just return `nil` instead,
<ide> behaving as if there was nothing in the cache. To gauge whether your cache is
<ide> hitting exceptions, you may provide an `error_handler` to report to an
<ide> exception gathering service. It must accept three keyword arguments: `method`,
<ide> the cache store method that was originally called; `returning`, the value that
<ide> was returned to the user, typically `nil`; and `exception`, the exception that
<ide> was rescued.
<ide>
<del>Putting it all together, a production Redis cache store may look something
<del>like this:
<add>To get started, add the redis gem to your Gemfile:
<ide>
<ide> ```ruby
<del>cache_servers = %w[ "redis://cache-01:6379/0", "redis://cache-02:6379/0", … ],
<del>config.cache_store = :redis_cache_store, url: cache_servers,
<add>gem 'redis'
<add>```
<add>
<add>You can enable support for the faster [hiredis](https://github.com/redis/hiredis)
<add>connection library by additionally adding its ruby wrapper to your Gemfile:
<add>
<add>```ruby
<add>gem 'hiredis'
<add>```
<add>
<add>Redis cache store will automatically require & use hiredis if available. No further
<add>configuration is needed.
<add>
<add>Finally, add the configuration in the relevant `config/environments/*.rb` file:
<add>
<add>```ruby
<add>config.cache_store = :redis_cache_store, { url: ENV['REDIS_URL'] }
<add>```
<add>
<add>A more complex, production Redis cache store may look something like this:
<add>
<add>```ruby
<add>cache_servers = %w(redis://cache-01:6379/0 redis://cache-02:6379/0)
<add>config.cache_store = :redis_cache_store, { url: cache_servers,
<ide>
<ide> connect_timeout: 30, # Defaults to 20 seconds
<ide> read_timeout: 0.2, # Defaults to 1 second
<ide> config.cache_store = :redis_cache_store, url: cache_servers,
<ide>
<ide> error_handler: -> (method:, returning:, exception:) {
<ide> # Report errors to Sentry as warnings
<del> Raven.capture_exception exception, level: 'warning",
<add> Raven.capture_exception exception, level: 'warning',
<ide> tags: { method: method, returning: returning }
<ide> }
<add>}
<ide> ```
<ide>
<ide> ### ActiveSupport::Cache::NullStore | 1 |
Javascript | Javascript | fix lgtm error | e879da10e2ccc9d05200c9f36259638e3b02ac8a | <ide><path>examples/js/renderers/WebGLDeferredRenderer.js
<ide> THREE.WebGLDeferredRenderer = function ( parameters ) {
<ide>
<ide> }
<ide>
<del> updateDeferredColorUniforms( renderer, scene, camera, geometry, material, group );
<add> updateDeferredColorUniforms( renderer, scene, camera, geometry, material );
<ide>
<ide> material.uniforms.samplerLight.value = _compLight.renderTarget2.texture;
<ide> | 1 |
Javascript | Javascript | standardize indexof comparisons | 53aa87f3bf4284763405f3eb8affff296e55ba4f | <ide><path>src/ajax/jsonp.js
<ide> jQuery.ajaxPrefilter( "json jsonp", function( s, originalSettings, jqXHR ) {
<ide> jsonProp = s.jsonp !== false && ( rjsonp.test( s.url ) ?
<ide> "url" :
<ide> typeof s.data === "string" &&
<del> !( s.contentType || "" ).indexOf("application/x-www-form-urlencoded") &&
<add> ( s.contentType || "" )
<add> .indexOf("application/x-www-form-urlencoded") === 0 &&
<ide> rjsonp.test( s.data ) && "data"
<ide> );
<ide>
<ide><path>src/ajax/load.js
<ide> jQuery.fn.load = function( url, params, callback ) {
<ide> self = this,
<ide> off = url.indexOf(" ");
<ide>
<del> if ( off >= 0 ) {
<add> if ( off > -1 ) {
<ide> selector = jQuery.trim( url.slice( off ) );
<ide> url = url.slice( 0, off );
<ide> }
<ide><path>src/attributes/classes.js
<ide> jQuery.fn.extend({
<ide> j = 0;
<ide> while ( (clazz = classes[j++]) ) {
<ide> // Remove *all* instances
<del> while ( cur.indexOf( " " + clazz + " " ) >= 0 ) {
<add> while ( cur.indexOf( " " + clazz + " " ) > -1 ) {
<ide> cur = cur.replace( " " + clazz + " ", " " );
<ide> }
<ide> }
<ide> jQuery.fn.extend({
<ide> l = this.length;
<ide> for ( ; i < l; i++ ) {
<ide> if ( this[i].nodeType === 1 &&
<del> (" " + this[i].className + " ").replace(rclass, " ").indexOf( className ) >= 0 ) {
<add> (" " + this[i].className + " ").replace(rclass, " ").indexOf( className ) > -1 ) {
<ide>
<ide> return true;
<ide> }
<ide><path>src/attributes/val.js
<ide> jQuery.extend({
<ide> while ( i-- ) {
<ide> option = options[ i ];
<ide> if ( (option.selected =
<del> jQuery.inArray( jQuery.valHooks.option.get( option ), values ) >= 0) ) {
<add> jQuery.inArray( jQuery.valHooks.option.get( option ), values ) > -1) ) {
<ide> optionSet = true;
<ide> }
<ide> }
<ide> jQuery.each([ "radio", "checkbox" ], function() {
<ide> jQuery.valHooks[ this ] = {
<ide> set: function( elem, value ) {
<ide> if ( jQuery.isArray( value ) ) {
<del> return ( elem.checked = jQuery.inArray( jQuery(elem).val(), value ) >= 0 );
<add> return ( elem.checked = jQuery.inArray( jQuery(elem).val(), value ) > -1 );
<ide> }
<ide> }
<ide> };
<ide><path>src/data.js
<ide> jQuery.fn.extend({
<ide> // *... In the case of properties that might _actually_
<ide> // have dashes, we need to also store a copy of that
<ide> // unchanged property.
<del> if ( key.indexOf("-") !== -1 && data !== undefined ) {
<add> if ( key.indexOf("-") > -1 && data !== undefined ) {
<ide> dataUser.set( this, key, value );
<ide> }
<ide> });
<ide><path>src/event.js
<ide> jQuery.event = {
<ide> return;
<ide> }
<ide>
<del> if ( type.indexOf(".") >= 0 ) {
<add> if ( type.indexOf(".") > -1 ) {
<ide> // Namespaced trigger; create a regexp to match event type in handle()
<ide> namespaces = type.split(".");
<ide> type = namespaces.shift();
<ide> jQuery.event = {
<ide>
<ide> if ( matches[ sel ] === undefined ) {
<ide> matches[ sel ] = handleObj.needsContext ?
<del> jQuery( sel, this ).index( cur ) >= 0 :
<add> jQuery( sel, this ).index( cur ) > -1 :
<ide> jQuery.find( sel, this, null, [ cur ] ).length;
<ide> }
<ide> if ( matches[ sel ] ) {
<ide><path>src/manipulation.js
<ide> jQuery.extend({
<ide>
<ide> // #4087 - If origin and destination elements are the same, and this is
<ide> // that element, do not do anything
<del> if ( selection && jQuery.inArray( elem, selection ) !== -1 ) {
<add> if ( selection && jQuery.inArray( elem, selection ) > -1 ) {
<ide> continue;
<ide> }
<ide>
<ide><path>src/traversing/findFilter.js
<ide> function winnow( elements, qualifier, not ) {
<ide> }
<ide>
<ide> return jQuery.grep( elements, function( elem ) {
<del> return ( indexOf.call( qualifier, elem ) >= 0 ) !== not;
<add> return ( indexOf.call( qualifier, elem ) > -1 ) !== not;
<ide> });
<ide> }
<ide> | 8 |
Mixed | Javascript | change windowshide default to true" | ad6ead3aab24e6b703d4982ba0563a15561a2915 | <ide><path>doc/api/child_process.md
<ide> exec('"my script.cmd" a b', (err, stdout, stderr) => {
<ide> <!-- YAML
<ide> added: v0.1.90
<ide> changes:
<del> - version: v11.0.0
<del> pr-url: https://github.com/nodejs/node/pull/21316
<del> description: The `windowsHide` option now defaults to `true`.
<ide> - version: v8.8.0
<ide> pr-url: https://github.com/nodejs/node/pull/15380
<ide> description: The `windowsHide` option is supported now.
<ide> changes:
<ide> * `uid` {number} Sets the user identity of the process (see setuid(2)).
<ide> * `gid` {number} Sets the group identity of the process (see setgid(2)).
<ide> * `windowsHide` {boolean} Hide the subprocess console window that would
<del> normally be created on Windows systems. **Default:** `true`.
<add> normally be created on Windows systems. **Default:** `false`.
<ide> * `callback` {Function} called with the output when process terminates.
<ide> * `error` {Error}
<ide> * `stdout` {string|Buffer}
<ide> lsExample();
<ide> <!-- YAML
<ide> added: v0.1.91
<ide> changes:
<del> - version: v11.0.0
<del> pr-url: https://github.com/nodejs/node/pull/21316
<del> description: The `windowsHide` option now defaults to `true`.
<ide> - version: v8.8.0
<ide> pr-url: https://github.com/nodejs/node/pull/15380
<ide> description: The `windowsHide` option is supported now.
<ide> changes:
<ide> * `uid` {number} Sets the user identity of the process (see setuid(2)).
<ide> * `gid` {number} Sets the group identity of the process (see setgid(2)).
<ide> * `windowsHide` {boolean} Hide the subprocess console window that would
<del> normally be created on Windows systems. **Default:** `true`.
<add> normally be created on Windows systems. **Default:** `false`.
<ide> * `windowsVerbatimArguments` {boolean} No quoting or escaping of arguments is
<ide> done on Windows. Ignored on Unix. **Default:** `false`.
<ide> * `shell` {boolean|string} If `true`, runs `command` inside of a shell. Uses
<ide> The `shell` option available in [`child_process.spawn()`][] is not supported by
<ide> <!-- YAML
<ide> added: v0.1.90
<ide> changes:
<del> - version: v11.0.0
<del> pr-url: https://github.com/nodejs/node/pull/21316
<del> description: The `windowsHide` option now defaults to `true`.
<ide> - version: v8.8.0
<ide> pr-url: https://github.com/nodejs/node/pull/15380
<ide> description: The `windowsHide` option is supported now.
<ide> changes:
<ide> done on Windows. Ignored on Unix. This is set to `true` automatically
<ide> when `shell` is specified and is CMD. **Default:** `false`.
<ide> * `windowsHide` {boolean} Hide the subprocess console window that would
<del> normally be created on Windows systems. **Default:** `true`.
<add> normally be created on Windows systems. **Default:** `false`.
<ide> * Returns: {ChildProcess}
<ide>
<ide> The `child_process.spawn()` method spawns a new process using the given
<ide> changes:
<ide> pr-url: https://github.com/nodejs/node/pull/22409
<ide> description: The `input` option can now be any `TypedArray` or a
<ide> `DataView`.
<del> - version: v11.0.0
<del> pr-url: https://github.com/nodejs/node/pull/21316
<del> description: The `windowsHide` option now defaults to `true`.
<ide> - version: v8.8.0
<ide> pr-url: https://github.com/nodejs/node/pull/15380
<ide> description: The `windowsHide` option is supported now.
<ide> changes:
<ide> * `encoding` {string} The encoding used for all stdio inputs and outputs.
<ide> **Default:** `'buffer'`.
<ide> * `windowsHide` {boolean} Hide the subprocess console window that would
<del> normally be created on Windows systems. **Default:** `true`.
<add> normally be created on Windows systems. **Default:** `false`.
<ide> * `shell` {boolean|string} If `true`, runs `command` inside of a shell. Uses
<ide> `'/bin/sh'` on UNIX, and `process.env.ComSpec` on Windows. A different
<ide> shell can be specified as a string. See [Shell Requirements][] and
<ide> changes:
<ide> pr-url: https://github.com/nodejs/node/pull/22409
<ide> description: The `input` option can now be any `TypedArray` or a
<ide> `DataView`.
<del> - version: v11.0.0
<del> pr-url: https://github.com/nodejs/node/pull/21316
<del> description: The `windowsHide` option now defaults to `true`.
<ide> - version: v8.8.0
<ide> pr-url: https://github.com/nodejs/node/pull/15380
<ide> description: The `windowsHide` option is supported now.
<ide> changes:
<ide> * `encoding` {string} The encoding used for all stdio inputs and outputs.
<ide> **Default:** `'buffer'`.
<ide> * `windowsHide` {boolean} Hide the subprocess console window that would
<del> normally be created on Windows systems. **Default:** `true`.
<add> normally be created on Windows systems. **Default:** `false`.
<ide> * Returns: {Buffer|string} The stdout from the command.
<ide>
<ide> The `child_process.execSync()` method is generally identical to
<ide> changes:
<ide> pr-url: https://github.com/nodejs/node/pull/22409
<ide> description: The `input` option can now be any `TypedArray` or a
<ide> `DataView`.
<del> - version: v11.0.0
<del> pr-url: https://github.com/nodejs/node/pull/21316
<del> description: The `windowsHide` option now defaults to `true`.
<ide> - version: v8.8.0
<ide> pr-url: https://github.com/nodejs/node/pull/15380
<ide> description: The `windowsHide` option is supported now.
<ide> changes:
<ide> done on Windows. Ignored on Unix. This is set to `true` automatically
<ide> when `shell` is specified and is CMD. **Default:** `false`.
<ide> * `windowsHide` {boolean} Hide the subprocess console window that would
<del> normally be created on Windows systems. **Default:** `true`.
<add> normally be created on Windows systems. **Default:** `false`.
<ide> * Returns: {Object}
<ide> * `pid` {number} Pid of the child process.
<ide> * `output` {Array} Array of results from stdio output.
<ide><path>doc/api/cluster.md
<ide> values are `'rr'` and `'none'`.
<ide> <!-- YAML
<ide> added: v0.7.1
<ide> changes:
<del> - version: v11.0.0
<del> pr-url: https://github.com/nodejs/node/pull/21316
<del> description: The `windowsHide` option now defaults to `true`.
<ide> - version: v9.5.0
<ide> pr-url: https://github.com/nodejs/node/pull/18399
<ide> description: The `cwd` option is supported now.
<ide> changes:
<ide> number. By default each worker gets its own port, incremented from the
<ide> master's `process.debugPort`.
<ide> * `windowsHide` {boolean} Hide the forked processes console window that would
<del> normally be created on Windows systems. **Default:** `true`.
<add> normally be created on Windows systems. **Default:** `false`.
<ide>
<ide> After calling `.setupMaster()` (or `.fork()`) this settings object will contain
<ide> the settings, including the default values.
<ide><path>lib/child_process.js
<ide> exports.execFile = function execFile(file /* , args, options, callback */) {
<ide> gid: options.gid,
<ide> uid: options.uid,
<ide> shell: options.shell,
<del> windowsHide: options.windowsHide !== false,
<add> windowsHide: !!options.windowsHide,
<ide> windowsVerbatimArguments: !!options.windowsVerbatimArguments
<ide> });
<ide>
<ide> var spawn = exports.spawn = function spawn(/* file, args, options */) {
<ide> file: opts.file,
<ide> args: opts.args,
<ide> cwd: options.cwd,
<del> windowsHide: options.windowsHide !== false,
<add> windowsHide: !!options.windowsHide,
<ide> windowsVerbatimArguments: !!options.windowsVerbatimArguments,
<ide> detached: !!options.detached,
<ide> envPairs: opts.envPairs,
<ide> function spawnSync(/* file, args, options */) {
<ide>
<ide> options.stdio = _validateStdio(options.stdio || 'pipe', true).stdio;
<ide>
<del> options.windowsHide = options.windowsHide !== false;
<del>
<ide> if (options.input) {
<ide> var stdin = options.stdio[0] = util._extend({}, options.stdio[0]);
<ide> stdin.input = options.input;
<ide><path>test/parallel/test-child-process-spawnsync-shell.js
<ide> assert.strictEqual(env.stdout.toString().trim(), 'buzz');
<ide> assert.strictEqual(opts.options.shell, shell);
<ide> assert.strictEqual(opts.options.file, opts.file);
<ide> assert.deepStrictEqual(opts.options.args, opts.args);
<del> assert.strictEqual(opts.options.windowsHide, true);
<add> assert.strictEqual(opts.options.windowsHide, undefined);
<ide> assert.strictEqual(opts.options.windowsVerbatimArguments,
<ide> windowsVerbatim);
<ide> }); | 4 |
Java | Java | add equals/hashcode to flashmap | 1ca0460534d207a4f3d2861d34dbb8bacb76eb27 | <ide><path>spring-webmvc/src/main/java/org/springframework/web/servlet/FlashMap.java
<ide>
<ide> import org.springframework.util.LinkedMultiValueMap;
<ide> import org.springframework.util.MultiValueMap;
<add>import org.springframework.util.ObjectUtils;
<ide> import org.springframework.util.StringUtils;
<ide>
<ide> /**
<ide> public int compareTo(FlashMap other) {
<ide> }
<ide> }
<ide>
<add> @Override
<add> public boolean equals(Object obj) {
<add> if (this == obj) {
<add> return true;
<add> }
<add> if (obj != null && obj instanceof FlashMap) {
<add> FlashMap other = (FlashMap) obj;
<add> if (this.targetRequestParams.equals(other.targetRequestParams) &&
<add> ObjectUtils.nullSafeEquals(this.targetRequestPath, other.targetRequestPath)) {
<add> return true;
<add> }
<add> }
<add> return false;
<add> }
<add>
<add> @Override
<add> public int hashCode() {
<add> int result = super.hashCode();
<add> result = 31 * result + (this.targetRequestPath != null ? this.targetRequestPath.hashCode() : 0);
<add> result = 31 * result + this.targetRequestParams.hashCode();
<add> return result;
<add> }
<add>
<ide> @Override
<ide> public String toString() {
<ide> StringBuilder sb = new StringBuilder(); | 1 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.