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 | move word 'example' to correct position | 492ddcf6bd13a50e7a43055a2db527c10361cf28 | <ide><path>curriculum/challenges/english/10-coding-interview-prep/rosetta-code/kaprekar-numbers.md
<ide> A positive integer is a [Kaprekar number](<https://en.wikipedia.org/wiki/Kapreka
<ide> <li>The decimal representation of its square may be split once into two parts consisting of positive integers which sum to the original number. </li>
<ide> </ul>
<ide>
<del>Note that a split resulting in a part consisting purely of 0s is not valid, as 0 is not considered positive.Example
<add>Note that a split resulting in a part consisting purely of 0s is not valid, as 0 is not considered positive.
<ide>
<del>Kaprekar numbers:
<add>Example Kaprekar numbers:
<ide>
<ide> <ul>
<ide> <li><code>2223</code> is a Kaprekar number, as <code>2223 * 2223 = 4941729</code>, <code>4941729</code> may be split to <code>494</code> and <code>1729</code>, and <code>494 + 1729 = 2223</code></li> | 1 |
Text | Text | update minimum glibc requirements for linux | 3671cc043233d9e75994ce17abb050ee0581dce0 | <ide><path>BUILDING.md
<ide> Node.js does not support a platform version if a vendor has expired support
<ide> for it. In other words, Node.js does not support running on End-of-Life (EoL)
<ide> platforms. This is true regardless of entries in the table below.
<ide>
<del>| Operating System | Architectures | Versions | Support Type | Notes |
<del>| ---------------- | ---------------- | ------------------------------- | ------------------------------------------- | ----------------------------------------- |
<del>| GNU/Linux | x64 | kernel >= 3.10, glibc >= 2.17 | Tier 1 | e.g. Ubuntu 16.04[^1], Debian 9, EL 7[^2] |
<del>| GNU/Linux | x64 | kernel >= 3.10, musl >= 1.1.19 | Experimental | e.g. Alpine 3.8 |
<del>| GNU/Linux | x86 | kernel >= 3.10, glibc >= 2.17 | Experimental | Downgraded as of Node.js 10 |
<del>| GNU/Linux | arm64 | kernel >= 4.5, glibc >= 2.17 | Tier 1 | e.g. Ubuntu 16.04, Debian 9, EL 7[^3] |
<del>| GNU/Linux | armv7 | kernel >= 4.14, glibc >= 2.24 | Tier 1 | e.g. Ubuntu 18.04, Debian 9 |
<del>| GNU/Linux | armv6 | kernel >= 4.14, glibc >= 2.24 | Experimental | Downgraded as of Node.js 12 |
<del>| GNU/Linux | ppc64le >=power8 | kernel >= 3.10.0, glibc >= 2.17 | Tier 2 | e.g. Ubuntu 16.04[^1], EL 7[^2] |
<del>| GNU/Linux | s390x | kernel >= 3.10.0, glibc >= 2.17 | Tier 2 | e.g. EL 7[^2] |
<del>| Windows | x64 | >= Windows 10/Server 2016 | Tier 1 | [^4],[^5] |
<del>| Windows | x86 | >= Windows 10/Server 2016 | Experimental | [^6] |
<del>| Windows | x64, x86 | Windows 8.1/Server 2012 | Experimental | |
<del>| Windows | arm64 | >= Windows 10 | Tier 2 (compiling) / Experimental (running) | |
<del>| macOS | x64 | >= 10.15 | Tier 1 | For notes about compilation see [^7] |
<del>| macOS | arm64 | >= 11 | Tier 1 | |
<del>| SmartOS | x64 | >= 18 | Tier 2 | |
<del>| AIX | ppc64be >=power8 | >= 7.2 TL04 | Tier 2 | |
<del>| FreeBSD | x64 | >= 12.2 | Experimental | |
<del>
<del>[^1]: GCC 8 is not provided on the base platform. Users will
<del> need the
<del> [Toolchain test builds PPA](https://launchpad.net/\~ubuntu-toolchain-r/+archive/ubuntu/test?field.series_filter=xenial)
<del> or similar to source a newer compiler.
<del>
<del>[^2]: GCC 8 is not provided on the base platform. Users will
<del> need the
<del> [devtoolset-8](https://www.softwarecollections.org/en/scls/rhscl/devtoolset-8/)
<del> or later to source a newer compiler.
<del>
<del>[^3]: Older kernel versions may work for ARM64. However the
<del> Node.js test infrastructure only tests >= 4.5.
<del>
<del>[^4]: On Windows, running Node.js in Windows terminal emulators
<add>| Operating System | Architectures | Versions | Support Type | Notes |
<add>| ---------------- | ---------------- | --------------------------------- | ------------------------------------------- | ------------------------------------ |
<add>| GNU/Linux | x64 | kernel >= 4.18[^1], glibc >= 2.28 | Tier 1 | e.g. Ubuntu 20.04, Debian 10, RHEL 8 |
<add>| GNU/Linux | x64 | kernel >= 3.10, musl >= 1.1.19 | Experimental | e.g. Alpine 3.8 |
<add>| GNU/Linux | x86 | kernel >= 3.10, glibc >= 2.17 | Experimental | Downgraded as of Node.js 10 |
<add>| GNU/Linux | arm64 | kernel >= 4.18[^1], glibc >= 2.28 | Tier 1 | e.g. Ubuntu 20.04, Debian 10, RHEL 8 |
<add>| GNU/Linux | armv7 | kernel >= 4.18[^1], glibc >= 2.28 | Tier 1 | e.g. Ubuntu 20.04, Debian 10 |
<add>| GNU/Linux | armv6 | kernel >= 4.14, glibc >= 2.24 | Experimental | Downgraded as of Node.js 12 |
<add>| GNU/Linux | ppc64le >=power8 | kernel >= 4.18[^1], glibc >= 2.28 | Tier 2 | e.g. Ubuntu 20.04, RHEL 8 |
<add>| GNU/Linux | s390x | kernel >= 4.18[^1], glibc >= 2.28 | Tier 2 | e.g. RHEL 8 |
<add>| Windows | x64 | >= Windows 10/Server 2016 | Tier 1 | [^2],[^3] |
<add>| Windows | x86 | >= Windows 10/Server 2016 | Experimental | [^4] |
<add>| Windows | x64, x86 | Windows 8.1/Server 2012 | Experimental | |
<add>| Windows | arm64 | >= Windows 10 | Tier 2 (compiling) / Experimental (running) | |
<add>| macOS | x64 | >= 10.15 | Tier 1 | For notes about compilation see [^5] |
<add>| macOS | arm64 | >= 11 | Tier 1 | |
<add>| SmartOS | x64 | >= 18 | Tier 2 | |
<add>| AIX | ppc64be >=power8 | >= 7.2 TL04 | Tier 2 | |
<add>| FreeBSD | x64 | >= 12.2 | Experimental | |
<add>
<add>[^1]: Older kernel versions may work. However official Node.js release
<add> binaries are [built on RHEL 8 systems](#official-binary-platforms-and-toolchains)
<add> with kernel 4.18.
<add>
<add>[^2]: On Windows, running Node.js in Windows terminal emulators
<ide> like `mintty` requires the usage of [winpty](https://github.com/rprichard/winpty)
<ide> for the tty channels to work (e.g. `winpty node.exe script.js`).
<ide> In "Git bash" if you call the node shell alias (`node` without the `.exe`
<ide> extension), `winpty` is used automatically.
<ide>
<del>[^5]: The Windows Subsystem for Linux (WSL) is not
<add>[^3]: The Windows Subsystem for Linux (WSL) is not
<ide> supported, but the GNU/Linux build process and binaries should work. The
<ide> community will only address issues that reproduce on native GNU/Linux
<ide> systems. Issues that only reproduce on WSL should be reported in the
<ide> [WSL issue tracker](https://github.com/Microsoft/WSL/issues). Running the
<ide> Windows binary (`node.exe`) in WSL will not work without workarounds such as
<ide> stdio redirection.
<ide>
<del>[^6]: Compiling Node.js for x86 Windows is currently impossible due to
<add>[^4]: Compiling Node.js for x86 Windows is currently impossible due to
<ide> issues with version 10.1 of the V8 engine. Support will come back to its
<ide> previous status as soon as possible.
<ide>
<del>[^7]: Our macOS x64 Binaries are compiled with 10.15 as a target. Xcode11 is
<add>[^5]: Our macOS x64 Binaries are compiled with 10.15 as a target. Xcode11 is
<ide> required to compile.
<ide>
<ide> ### Supported toolchains
<ide> Binaries at <https://nodejs.org/download/release/> are produced on:
<ide> | aix-ppc64 | AIX 7.2 TL04 on PPC64BE with GCC 8 |
<ide> | darwin-x64 | macOS 10.15, Xcode Command Line Tools 11 with -mmacosx-version-min=10.15 |
<ide> | darwin-arm64 (and .pkg) | macOS 11 (arm64), Xcode Command Line Tools 12 with -mmacosx-version-min=10.15 |
<del>| linux-arm64 | CentOS 7 with devtoolset-8 / GCC 8[^8] |
<add>| linux-arm64 | RHEL 8 with GCC 8[^6] |
<ide> | linux-armv7l | Cross-compiled on Ubuntu 18.04 x64 with [custom GCC toolchain](https://github.com/rvagg/rpi-newer-crosstools) |
<del>| linux-ppc64le | CentOS 7 with devtoolset-8 / GCC 8[^8] |
<del>| linux-s390x | RHEL 7 with devtoolset-8 / GCC 8[^8] |
<del>| linux-x64 | CentOS 7 with devtoolset-8 / GCC 8[^8] |
<add>| linux-ppc64le | RHEL 8 with GCC 8[^6] |
<add>| linux-s390x | RHEL 8 with GCC 8[^6] |
<add>| linux-x64 | RHEL 8 with GCC 8[^6] |
<ide> | win-x64 and win-x86 | Windows 2012 R2 (x64) with Visual Studio 2019 |
<ide>
<del>[^8]: The Enterprise Linux devtoolset-8 allows us to compile binaries with GCC 8
<del> but linked to the glibc and libstdc++ versions of the host platforms
<del> (CentOS 7 / RHEL 7). Therefore, binaries produced on these systems are
<del> compatible with glibc >= 2.17 and libstdc++ >= 6.0.20 (`GLIBCXX_3.4.20`).
<del> These are available on distributions natively supporting GCC 4.9, such as
<del> Ubuntu 14.04 and Debian 8.
<add>[^6]: Binaries produced on these systems are compatible with glibc >= 2.28
<add> and libstdc++ >= 6.0.25 (`GLIBCXX_3.4.25`). These are available on
<add> distributions natively supporting GCC 8.1 or higher, such as Debian 10,
<add> RHEL 8 and Ubuntu 20.04.
<ide>
<ide> #### OpenSSL asm support
<ide> | 1 |
Javascript | Javascript | shorten the sha | 78be517727674d1e0a208e3e144eac8840d653e7 | <ide><path>src/traversing.js
<ide> jQuery.each({
<ide> jQuery.fn[ name ] = function( until, selector ) {
<ide> var ret = jQuery.map( this, fn, until ),
<ide> // The variable 'args' was introduced in
<del> // https://github.com/jquery/jquery/commit/52a02383fa521c51d9996a46f03a7080dd825f11
<add> // https://github.com/jquery/jquery/commit/52a0238
<ide> // to work around a bug in Chrome 10 (Dev) and should be removed when the bug is fixed.
<ide> // http://code.google.com/p/v8/issues/detail?id=1050
<ide> args = slice.call(arguments); | 1 |
Python | Python | fix exception thrown using mishactivation | baa00f65aeb7467075c87c9f769784ac3b86e94c | <ide><path>src/transformers/activations.py
<ide> class MishActivation(nn.Module):
<ide>
<ide> def __init__(self):
<ide> super().__init__()
<del> if version.parse(version.parse(torch.__version__).base_version) < version.parse("1.9"):
<add> if version.parse(torch.__version__) < version.parse("1.9.0"):
<ide> self.act = self._mish_python
<ide> else:
<ide> self.act = nn.functional.mish | 1 |
Python | Python | fix resnet xla with multi-gpus | 6dea4846eba601af35a2f741a839659f4ddfe61c | <ide><path>official/resnet/keras/keras_imagenet_main.py
<ide> def run(flags_obj):
<ide> optimizer, loss_scale=flags_core.get_loss_scale(flags_obj))
<ide>
<ide> if flags_obj.enable_xla:
<del> if strategy:
<del> per_replica_batch_size = (
<del> flags_obj.batch_size // strategy.num_replicas_in_sync)
<add> if strategy and strategy.num_replicas_in_sync > 1:
<add> # TODO(b/129791381): Specify `per_replica_batch_size` value in
<add> # DistributionStrategy multi-replica case.
<add> per_replica_batch_size = None
<ide> else:
<ide> per_replica_batch_size = flags_obj.batch_size
<ide> else: | 1 |
Python | Python | fix bigquerytomssqloperator documentation | 5c3e4538208cc317e6e45ae7b247e7fb83840f49 | <ide><path>airflow/providers/google/cloud/transfers/bigquery_to_mssql.py
<ide> class BigQueryToMsSqlOperator(BaseOperator):
<ide>
<ide> transfer_data = BigQueryToMsSqlOperator(
<ide> task_id='task_id',
<del> dataset_table='origin_bq_table',
<add> source_project_dataset_table='my-project.mydataset.mytable',
<ide> mssql_table='dest_table_name',
<ide> replace=True,
<ide> )
<ide>
<del> :param dataset_table: A dotted ``<dataset>.<table>``: the big query table of origin
<del> :type dataset_table: str
<add> :param source_project_dataset_table: A dotted ``<project>.<dataset>.<table>``:
<add> the big query table of origin
<add> :type source_project_dataset_table: str
<ide> :param selected_fields: List of fields to return (comma-separated). If
<ide> unspecified, all fields are returned.
<ide> :type selected_fields: str | 1 |
Java | Java | add support for generating class names | ca2b5e068bbecaac9f4170bc7c17d83008900f4d | <ide><path>spring-core/src/main/java/org/springframework/aot/generate/ClassNameGenerator.java
<add>/*
<add> * Copyright 2002-2022 the original author or authors.
<add> *
<add> * Licensed under the Apache License, Version 2.0 (the "License");
<add> * you may not use this file except in compliance with the License.
<add> * You may obtain a copy of the License at
<add> *
<add> * https://www.apache.org/licenses/LICENSE-2.0
<add> *
<add> * Unless required by applicable law or agreed to in writing, software
<add> * distributed under the License is distributed on an "AS IS" BASIS,
<add> * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
<add> * See the License for the specific language governing permissions and
<add> * limitations under the License.
<add> */
<add>
<add>package org.springframework.aot.generate;
<add>
<add>import java.util.Map;
<add>import java.util.concurrent.ConcurrentHashMap;
<add>import java.util.concurrent.atomic.AtomicInteger;
<add>
<add>import org.springframework.javapoet.ClassName;
<add>import org.springframework.util.Assert;
<add>import org.springframework.util.ClassUtils;
<add>import org.springframework.util.StringUtils;
<add>
<add>/**
<add> * Generates unique class names that can be used in ahead-of-time generated
<add> * source code. This class is stateful so the same instance should be used for
<add> * all name generation. Most commonly the class name generator is obtained via a
<add> * {@link GenerationContext}.
<add> *
<add> * @author Phillip Webb
<add> * @since 6.0
<add> * @see GeneratedClassName
<add> */
<add>public final class ClassNameGenerator {
<add>
<add> private static final String SEPARATOR = "__";
<add>
<add> private static final String AOT_PACKAGE = "__";
<add>
<add>
<add> private final Map<String, AtomicInteger> sequenceGenerator = new ConcurrentHashMap<>();
<add>
<add>
<add> /**
<add> * Generate a new class name for the given {@code target} /
<add> * {@code featureName} combination.
<add> * @param target the target of the newly generated class
<add> * @param featureName the name of the feature that the generated class
<add> * supports
<add> * @return a unique generated class name
<add> */
<add> public ClassName generateClassName(Class<?> target, String featureName) {
<add> Assert.notNull(target, "'target' must not be null");
<add> String rootName = target.getName().replace("$", "_");
<add> return generateSequencedClassName(rootName, featureName);
<add> }
<add>
<add> /**
<add> * Generate a new class name for the given {@code name} /
<add> * {@code featureName} combination.
<add> * @param target the target of the newly generated class. When possible,
<add> * this should be a class name
<add> * @param featureName the name of the feature that the generated class
<add> * supports
<add> * @return a unique generated class name
<add> */
<add> public ClassName generateClassName(String target, String featureName) {
<add> Assert.hasLength(target, "'target' must not be empty");
<add> target = clean(target);
<add> String rootName = AOT_PACKAGE + "." + ((!target.isEmpty()) ? target : "Aot");
<add> return generateSequencedClassName(rootName, featureName);
<add> }
<add>
<add> private String clean(String name) {
<add> StringBuilder rootName = new StringBuilder();
<add> boolean lastNotLetter = true;
<add> for (char ch : name.toCharArray()) {
<add> if (!Character.isLetter(ch)) {
<add> lastNotLetter = true;
<add> continue;
<add> }
<add> rootName.append(lastNotLetter ? Character.toUpperCase(ch) : ch);
<add> lastNotLetter = false;
<add> }
<add> return rootName.toString();
<add> }
<add>
<add> private ClassName generateSequencedClassName(String rootName, String featureName) {
<add> Assert.hasLength(featureName, "'featureName' must not be empty");
<add> Assert.isTrue(featureName.chars().allMatch(Character::isLetter),
<add> "'featureName' must contain only letters");
<add> String name = addSequence(
<add> rootName + SEPARATOR + StringUtils.capitalize(featureName));
<add> return ClassName.get(ClassUtils.getPackageName(name),
<add> ClassUtils.getShortName(name));
<add> }
<add>
<add> private String addSequence(String name) {
<add> int sequence = this.sequenceGenerator
<add> .computeIfAbsent(name, key -> new AtomicInteger()).getAndIncrement();
<add> return (sequence > 0) ? name + sequence : name;
<add> }
<add>
<add>}
<ide><path>spring-core/src/test/java/org/springframework/aot/generate/ClassNameGeneratorTests.java
<add>/*
<add> * Copyright 2002-2022 the original author or authors.
<add> *
<add> * Licensed under the Apache License, Version 2.0 (the "License");
<add> * you may not use this file except in compliance with the License.
<add> * You may obtain a copy of the License at
<add> *
<add> * https://www.apache.org/licenses/LICENSE-2.0
<add> *
<add> * Unless required by applicable law or agreed to in writing, software
<add> * distributed under the License is distributed on an "AS IS" BASIS,
<add> * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
<add> * See the License for the specific language governing permissions and
<add> * limitations under the License.
<add> */
<add>
<add>package org.springframework.aot.generate;
<add>
<add>import java.io.InputStream;
<add>
<add>import org.junit.jupiter.api.Test;
<add>
<add>import org.springframework.javapoet.ClassName;
<add>
<add>import static org.assertj.core.api.Assertions.assertThat;
<add>import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException;
<add>
<add>/**
<add> * Tests for {@link ClassNameGenerator}.
<add> *
<add> * @author Phillip Webb
<add> */
<add>class ClassNameGeneratorTests {
<add>
<add> private final ClassNameGenerator generator = new ClassNameGenerator();
<add>
<add> @Test
<add> void generateClassNameWhenTargetClassIsNullThrowsException() {
<add> assertThatIllegalArgumentException()
<add> .isThrownBy(
<add> () -> this.generator.generateClassName((Class<?>) null, "Test"))
<add> .withMessage("'target' must not be null");
<add> }
<add>
<add> @Test
<add> void generateClassNameWhenTargetStringIsEmptyThrowsException() {
<add> assertThatIllegalArgumentException()
<add> .isThrownBy(() -> this.generator.generateClassName("", "Test"))
<add> .withMessage("'target' must not be empty");
<add> }
<add>
<add> @Test
<add> void generatedClassNameWhenFeatureIsEmptyThrowsException() {
<add> assertThatIllegalArgumentException()
<add> .isThrownBy(() -> this.generator.generateClassName(InputStream.class, ""))
<add> .withMessage("'featureName' must not be empty");
<add> }
<add>
<add> @Test
<add> void generatedClassNameWhenFeatureIsNotAllLettersThrowsException() {
<add> String expectedMessage = "'featureName' must contain only letters";
<add> assertThatIllegalArgumentException().isThrownBy(
<add> () -> this.generator.generateClassName(InputStream.class, "noway!"))
<add> .withMessage(expectedMessage);
<add> assertThatIllegalArgumentException().isThrownBy(
<add> () -> this.generator.generateClassName(InputStream.class, "1WontWork"))
<add> .withMessage(expectedMessage);
<add> assertThatIllegalArgumentException()
<add> .isThrownBy(
<add> () -> this.generator.generateClassName(InputStream.class, "N0pe"))
<add> .withMessage(expectedMessage);
<add> }
<add>
<add> @Test
<add> void generateClassNameWithClassWhenLowercaseFeatureNameGeneratesName() {
<add> ClassName generated = this.generator.generateClassName(InputStream.class,
<add> "bytes");
<add> assertThat(generated).hasToString("java.io.InputStream__Bytes");
<add> }
<add>
<add> @Test
<add> void generateClassNameWithClassWhenInnerClassGeneratesName() {
<add> ClassName generated = this.generator.generateClassName(TestBean.class,
<add> "EventListener");
<add> assertThat(generated).hasToString(
<add> "org.springframework.aot.generate.ClassNameGeneratorTests_TestBean__EventListener");
<add> }
<add>
<add> @Test
<add> void generateClassWithClassWhenMultipleCallsGeneratesSequencedName() {
<add> ClassName generated1 = this.generator.generateClassName(InputStream.class,
<add> "bytes");
<add> ClassName generated2 = this.generator.generateClassName(InputStream.class,
<add> "bytes");
<add> ClassName generated3 = this.generator.generateClassName(InputStream.class,
<add> "bytes");
<add> assertThat(generated1).hasToString("java.io.InputStream__Bytes");
<add> assertThat(generated2).hasToString("java.io.InputStream__Bytes1");
<add> assertThat(generated3).hasToString("java.io.InputStream__Bytes2");
<add> }
<add>
<add> @Test
<add> void generateClassNameWithStringGeneratesNameUsingOnlyLetters() {
<add> ClassName generated = this.generator.generateClassName("my-bean--factoryStuff",
<add> "beans");
<add> assertThat(generated).hasToString("__.MyBeanFactoryStuff__Beans");
<add> }
<add>
<add> @Test
<add> void generateClassNameWithStringWhenNoLettersGeneratesAotName() {
<add> ClassName generated = this.generator.generateClassName("1234!@#", "beans");
<add> assertThat(generated).hasToString("__.Aot__Beans");
<add> }
<add>
<add> static class TestBean {
<add>
<add> }
<add>
<add>} | 2 |
Text | Text | add floret to static vectors docs | 7ce3460b23ea7fb7cf9fc905a4e68d71057443e6 | <ide><path>website/docs/usage/embeddings-transformers.md
<ide> models, which can **improve the accuracy** of your components.
<ide> Word vectors in spaCy are "static" in the sense that they are not learned
<ide> parameters of the statistical models, and spaCy itself does not feature any
<ide> algorithms for learning word vector tables. You can train a word vectors table
<del>using tools such as [Gensim](https://radimrehurek.com/gensim/),
<add>using tools such as [floret](https://github.com/explosion/floret),
<add>[Gensim](https://radimrehurek.com/gensim/),
<ide> [FastText](https://fasttext.cc/) or
<ide> [GloVe](https://nlp.stanford.edu/projects/glove/), or download existing
<ide> pretrained vectors. The [`init vectors`](/api/cli#init-vectors) command lets you | 1 |
Text | Text | clarify tier 2 implications in building.md | 76cbb6628c302119fbace82142d6be0a08b569de | <ide><path>BUILDING.md
<ide> There are three support tiers:
<ide> Test failures on tier 1 platforms will block releases.
<ide> * **Tier 2**: These platforms represent smaller segments of the Node.js user
<ide> base. The Node.js Build Working Group maintains infrastructure for full test
<del> coverage. Test failures on tier 2 platforms will block releases. Delays in
<del> release of binaries for these platforms are acceptable where necessary due to
<del> infrastructure concerns.
<add> coverage. Test failures on tier 2 platforms will block releases.
<add> Infrastructure issues may delay the release of binaries for these platforms.
<ide> * **Experimental**: May not compile or test suite may not pass. The core team
<ide> does not create releases for these platforms. Test failures on experimental
<ide> platforms do not block releases. Contributions to improve support for these | 1 |
Python | Python | halve the memory requirement of np.cov | 881849c5385524ceafc462d230960463a01e47a6 | <ide><path>numpy/lib/function_base.py
<ide> def cov(m, y=None, rowvar=1, bias=0, ddof=None, fweights=None, aweights=None):
<ide> X_T = X.T
<ide> else:
<ide> X_T = (X*w).T
<del> return (dot(X, X_T.conj())/fact).squeeze()
<add> c = dot(X, X_T.conj())
<add> c /= fact
<add> return c.squeeze()
<ide>
<ide>
<ide> def corrcoef(x, y=None, rowvar=1, bias=np._NoValue, ddof=np._NoValue): | 1 |
Python | Python | add dependency patterns example | 1b64a44d85e542c62ddeaf1f89622dcf3fa72229 | <ide><path>examples/dependency_patterns.py
<add>'''
<add>Match a dependency pattern. See https://github.com/explosion/spaCy/pull/1120
<add>
<add>We start by creating a DependencyTree for the Doc. This class models the document
<add>dependency tree. Then we compile the query into a Pattern using the PatternParser.
<add>The syntax is quite simple:
<add>
<add>we define a node named 'fox', that must match in the dep tree a token
<add>whose orth_ is 'fox'. an anonymous token whose lemma is 'quick' must have fox
<add>as parent, with a dep_ matching the regex am.* another anonymous token whose
<add>orth_ matches the regex brown|yellow has fox as parent, with whathever dep_
<add>DependencyTree.match returns a list of PatternMatch. Notice that we can assign
<add>names to anonymous or defined nodes ([word:fox]=f). We can get the Token mapped
<add>to the fox node using match['f'].
<add>'''
<add>import spacy
<add>from spacy.pattern import PatternParser, DependencyTree
<add>
<add>nlp = spacy.load('en')
<add>doc = nlp("The quick brown fox jumped over the lazy dog.")
<add>tree = DependencyTree(doc)
<add>
<add>query = """fox [word:fox]=f
<add> [lemma:quick]=q >/am.*/ fox
<add> [word:/brown|yellow/] > fox"""
<add>
<add>pattern = PatternParser.parse(query)
<add>matches = tree.match(pattern)
<add>
<add>assert len(matches) == 1
<add>match = matches[0]
<add>
<add>assert match['f'] == doc[3] | 1 |
Text | Text | add missing curly brace in nativemodulesios.md | 484e6403b3b60743bc780727a7d7a32c4b726afc | <ide><path>docs/NativeModulesIOS.md
<ide> You must create a class extension of RCTConvert like so:
<ide> @implementation RCTConvert (StatusBarAnimation)
<ide> RCT_ENUM_CONVERTER(UIStatusBarAnimation, (@{ @"statusBarAnimationNone" : @(UIStatusBarAnimationNone),
<ide> @"statusBarAnimationFade" : @(UIStatusBarAnimationFade),
<del> @"statusBarAnimationSlide" : @(UIStatusBarAnimationSlide),
<add> @"statusBarAnimationSlide" : @(UIStatusBarAnimationSlide)},
<ide> UIStatusBarAnimationNone, integerValue)
<ide> @end
<ide> ``` | 1 |
Java | Java | support custom devsupportmanager | 369b28ce014f76b4b47c4cf7632ac66f39a53fa2 | <ide><path>ReactAndroid/src/main/java/com/facebook/react/ReactInstanceManager.java
<ide> public static ReactInstanceManagerBuilder builder() {
<ide> @Nullable String jsMainModulePath,
<ide> List<ReactPackage> packages,
<ide> boolean useDeveloperSupport,
<add> DevSupportManagerFactory devSupportManagerFactory,
<ide> boolean requireActivity,
<ide> @Nullable NotThreadSafeBridgeIdleDebugListener bridgeIdleDebugListener,
<ide> LifecycleState initialLifecycleState,
<ide> public static ReactInstanceManagerBuilder builder() {
<ide> Systrace.beginSection(
<ide> Systrace.TRACE_TAG_REACT_JAVA_BRIDGE, "ReactInstanceManager.initDevSupportManager");
<ide> mDevSupportManager =
<del> DevSupportManagerFactory.create(
<add> devSupportManagerFactory.create(
<ide> applicationContext,
<ide> createDevHelperInterface(),
<ide> mJSMainModulePath,
<ide> private void attachRootViewToInstance(final ReactRoot reactRoot) {
<ide> // If we can't get a UIManager something has probably gone horribly wrong
<ide> if (uiManager == null) {
<ide> throw new IllegalStateException(
<del> "Unable to attach a rootView to ReactInstance when UIManager is not properly initialized.");
<add> "Unable to attach a rootView to ReactInstance when UIManager is not properly"
<add> + " initialized.");
<ide> }
<ide>
<ide> @Nullable Bundle initialProperties = reactRoot.getAppProperties();
<ide><path>ReactAndroid/src/main/java/com/facebook/react/ReactInstanceManagerBuilder.java
<ide> import com.facebook.react.bridge.NativeModuleCallExceptionHandler;
<ide> import com.facebook.react.bridge.NotThreadSafeBridgeIdleDebugListener;
<ide> import com.facebook.react.common.LifecycleState;
<add>import com.facebook.react.devsupport.DefaultDevSupportManagerFactory;
<add>import com.facebook.react.devsupport.DevSupportManagerFactory;
<ide> import com.facebook.react.devsupport.RedBoxHandler;
<ide> import com.facebook.react.devsupport.interfaces.DevBundleDownloadListener;
<ide> import com.facebook.react.devsupport.interfaces.DevSupportManager;
<ide> public class ReactInstanceManagerBuilder {
<ide> private @Nullable NotThreadSafeBridgeIdleDebugListener mBridgeIdleDebugListener;
<ide> private @Nullable Application mApplication;
<ide> private boolean mUseDeveloperSupport;
<add> private @Nullable DevSupportManagerFactory mDevSupportManagerFactory;
<ide> private boolean mRequireActivity;
<ide> private @Nullable LifecycleState mInitialLifecycleState;
<ide> private @Nullable UIImplementationProvider mUIImplementationProvider;
<ide> public ReactInstanceManagerBuilder setUseDeveloperSupport(boolean useDeveloperSu
<ide> return this;
<ide> }
<ide>
<add> /**
<add> * Set the custom {@link DevSupportManagerFactory}. If not set, will use {@link
<add> * DefaultDevSupportManagerFactory}.
<add> */
<add> public ReactInstanceManagerBuilder setDevSupportManagerFactory(
<add> final DevSupportManagerFactory devSupportManagerFactory) {
<add> mDevSupportManagerFactory = devSupportManagerFactory;
<add> return this;
<add> }
<add>
<ide> /**
<ide> * When {@code false}, indicates that correct usage of React Native will NOT involve an Activity.
<ide> * For the vast majority of Android apps in the ecosystem, this will not need to change. Unless
<ide> public ReactInstanceManager build() {
<ide> mJSMainModulePath,
<ide> mPackages,
<ide> mUseDeveloperSupport,
<add> mDevSupportManagerFactory == null
<add> ? new DefaultDevSupportManagerFactory()
<add> : mDevSupportManagerFactory,
<ide> mRequireActivity,
<ide> mBridgeIdleDebugListener,
<ide> Assertions.assertNotNull(mInitialLifecycleState, "Initial lifecycle state was not set"),
<ide><path>ReactAndroid/src/main/java/com/facebook/react/ReactNativeHost.java
<ide> import com.facebook.react.bridge.ReactMarker;
<ide> import com.facebook.react.bridge.ReactMarkerConstants;
<ide> import com.facebook.react.common.LifecycleState;
<add>import com.facebook.react.devsupport.DevSupportManagerFactory;
<ide> import com.facebook.react.devsupport.RedBoxHandler;
<ide> import com.facebook.react.uimanager.UIImplementationProvider;
<ide> import java.util.List;
<ide> protected ReactInstanceManager createReactInstanceManager() {
<ide> .setApplication(mApplication)
<ide> .setJSMainModulePath(getJSMainModuleName())
<ide> .setUseDeveloperSupport(getUseDeveloperSupport())
<add> .setDevSupportManagerFactory(getDevSupportManagerFactory())
<ide> .setRequireActivity(getShouldRequireActivity())
<ide> .setRedBoxHandler(getRedBoxHandler())
<ide> .setJavaScriptExecutorFactory(getJavaScriptExecutorFactory())
<ide> protected String getJSMainModuleName() {
<ide> /** Returns whether dev mode should be enabled. This enables e.g. the dev menu. */
<ide> public abstract boolean getUseDeveloperSupport();
<ide>
<add> /** Get the {@link DevSupportManagerFactory}. Override this to use a custom dev support manager */
<add> protected @Nullable DevSupportManagerFactory getDevSupportManagerFactory() {
<add> return null;
<add> }
<add>
<ide> /**
<ide> * Returns a list of {@link ReactPackage} used by the app. You'll most likely want to return at
<ide> * least the {@code MainReactPackage}. If your app uses additional views or modules besides the
<ide><path>ReactAndroid/src/main/java/com/facebook/react/devsupport/DefaultDevSupportManagerFactory.java
<add>/*
<add> * Copyright (c) Facebook, Inc. and its affiliates.
<add> *
<add> * This source code is licensed under the MIT license found in the
<add> * LICENSE file in the root directory of this source tree.
<add> */
<add>
<add>package com.facebook.react.devsupport;
<add>
<add>import android.content.Context;
<add>import androidx.annotation.Nullable;
<add>import com.facebook.react.devsupport.interfaces.DevBundleDownloadListener;
<add>import com.facebook.react.devsupport.interfaces.DevSupportManager;
<add>import com.facebook.react.packagerconnection.RequestHandler;
<add>import java.lang.reflect.Constructor;
<add>import java.util.Map;
<add>
<add>/**
<add> * A simple factory that creates instances of {@link DevSupportManager} implementations. Uses
<add> * reflection to create BridgeDevSupportManager if it exists. This allows ProGuard to strip that
<add> * class and its dependencies in release builds. If the class isn't found, {@link
<add> * DisabledDevSupportManager} is returned instead.
<add> */
<add>public class DefaultDevSupportManagerFactory implements DevSupportManagerFactory {
<add>
<add> private static final String DEVSUPPORT_IMPL_PACKAGE = "com.facebook.react.devsupport";
<add> private static final String DEVSUPPORT_IMPL_CLASS = "BridgeDevSupportManager";
<add>
<add> public DevSupportManager create(
<add> Context applicationContext,
<add> ReactInstanceDevHelper reactInstanceDevHelper,
<add> @Nullable String packagerPathForJSBundleName,
<add> boolean enableOnCreate,
<add> int minNumShakes) {
<add>
<add> return create(
<add> applicationContext,
<add> reactInstanceDevHelper,
<add> packagerPathForJSBundleName,
<add> enableOnCreate,
<add> null,
<add> null,
<add> minNumShakes,
<add> null);
<add> }
<add>
<add> @Override
<add> public DevSupportManager create(
<add> Context applicationContext,
<add> ReactInstanceDevHelper reactInstanceManagerHelper,
<add> @Nullable String packagerPathForJSBundleName,
<add> boolean enableOnCreate,
<add> @Nullable RedBoxHandler redBoxHandler,
<add> @Nullable DevBundleDownloadListener devBundleDownloadListener,
<add> int minNumShakes,
<add> @Nullable Map<String, RequestHandler> customPackagerCommandHandlers) {
<add> if (!enableOnCreate) {
<add> return new DisabledDevSupportManager();
<add> }
<add> try {
<add> // ProGuard is surprisingly smart in this case and will keep a class if it detects a call to
<add> // Class.forName() with a static string. So instead we generate a quasi-dynamic string to
<add> // confuse it.
<add> String className =
<add> new StringBuilder(DEVSUPPORT_IMPL_PACKAGE)
<add> .append(".")
<add> .append(DEVSUPPORT_IMPL_CLASS)
<add> .toString();
<add> Class<?> devSupportManagerClass = Class.forName(className);
<add> Constructor constructor =
<add> devSupportManagerClass.getConstructor(
<add> Context.class,
<add> ReactInstanceDevHelper.class,
<add> String.class,
<add> boolean.class,
<add> RedBoxHandler.class,
<add> DevBundleDownloadListener.class,
<add> int.class,
<add> Map.class);
<add> return (DevSupportManager)
<add> constructor.newInstance(
<add> applicationContext,
<add> reactInstanceManagerHelper,
<add> packagerPathForJSBundleName,
<add> true,
<add> redBoxHandler,
<add> devBundleDownloadListener,
<add> minNumShakes,
<add> customPackagerCommandHandlers);
<add> } catch (Exception e) {
<add> throw new RuntimeException(
<add> "Requested enabled DevSupportManager, but BridgeDevSupportManager class was not found"
<add> + " or could not be created",
<add> e);
<add> }
<add> }
<add>}
<ide><path>ReactAndroid/src/main/java/com/facebook/react/devsupport/DevSupportManagerFactory.java
<ide> import com.facebook.react.devsupport.interfaces.DevBundleDownloadListener;
<ide> import com.facebook.react.devsupport.interfaces.DevSupportManager;
<ide> import com.facebook.react.packagerconnection.RequestHandler;
<del>import java.lang.reflect.Constructor;
<ide> import java.util.Map;
<ide>
<del>/**
<del> * A simple factory that creates instances of {@link DevSupportManager} implementations. Uses
<del> * reflection to create BridgeDevSupportManager if it exists. This allows ProGuard to strip that
<del> * class and its dependencies in release builds. If the class isn't found, {@link
<del> * DisabledDevSupportManager} is returned instead.
<del> */
<del>public class DevSupportManagerFactory {
<del>
<del> private static final String DEVSUPPORT_IMPL_PACKAGE = "com.facebook.react.devsupport";
<del> private static final String DEVSUPPORT_IMPL_CLASS = "BridgeDevSupportManager";
<del>
<del> public static DevSupportManager create(
<del> Context applicationContext,
<del> ReactInstanceDevHelper reactInstanceDevHelper,
<del> @Nullable String packagerPathForJSBundleName,
<del> boolean enableOnCreate,
<del> int minNumShakes) {
<del>
<del> return create(
<del> applicationContext,
<del> reactInstanceDevHelper,
<del> packagerPathForJSBundleName,
<del> enableOnCreate,
<del> null,
<del> null,
<del> minNumShakes,
<del> null);
<del> }
<del>
<del> public static DevSupportManager create(
<add>public interface DevSupportManagerFactory {
<add> DevSupportManager create(
<ide> Context applicationContext,
<ide> ReactInstanceDevHelper reactInstanceManagerHelper,
<ide> @Nullable String packagerPathForJSBundleName,
<ide> boolean enableOnCreate,
<ide> @Nullable RedBoxHandler redBoxHandler,
<ide> @Nullable DevBundleDownloadListener devBundleDownloadListener,
<ide> int minNumShakes,
<del> @Nullable Map<String, RequestHandler> customPackagerCommandHandlers) {
<del> if (!enableOnCreate) {
<del> return new DisabledDevSupportManager();
<del> }
<del> try {
<del> // ProGuard is surprisingly smart in this case and will keep a class if it detects a call to
<del> // Class.forName() with a static string. So instead we generate a quasi-dynamic string to
<del> // confuse it.
<del> String className =
<del> new StringBuilder(DEVSUPPORT_IMPL_PACKAGE)
<del> .append(".")
<del> .append(DEVSUPPORT_IMPL_CLASS)
<del> .toString();
<del> Class<?> devSupportManagerClass = Class.forName(className);
<del> Constructor constructor =
<del> devSupportManagerClass.getConstructor(
<del> Context.class,
<del> ReactInstanceDevHelper.class,
<del> String.class,
<del> boolean.class,
<del> RedBoxHandler.class,
<del> DevBundleDownloadListener.class,
<del> int.class,
<del> Map.class);
<del> return (DevSupportManager)
<del> constructor.newInstance(
<del> applicationContext,
<del> reactInstanceManagerHelper,
<del> packagerPathForJSBundleName,
<del> true,
<del> redBoxHandler,
<del> devBundleDownloadListener,
<del> minNumShakes,
<del> customPackagerCommandHandlers);
<del> } catch (Exception e) {
<del> throw new RuntimeException(
<del> "Requested enabled DevSupportManager, but BridgeDevSupportManager class was not found"
<del> + " or could not be created",
<del> e);
<del> }
<del> }
<add> @Nullable Map<String, RequestHandler> customPackagerCommandHandlers);
<ide> } | 5 |
Javascript | Javascript | fix url matching on api e2e tests | 55244390c805ce95c967fa75759a971c2cd0ce09 | <ide><path>docs/app/e2e/api-docs/provider-pages.scenario.js
<ide> describe("provider pages", function() {
<ide> browser.get('index-debug.html#!/api/ng/provider/$compileProvider');
<ide> var serviceLink = element.all(by.css('ol.api-profile-header-structure li a')).first();
<ide> expect(serviceLink.getText()).toEqual('- $compile');
<del> expect(serviceLink.getAttribute('href')).toMatch('api/ng/service/$compile');
<add> expect(serviceLink.getAttribute('href')).toMatch(/api\/ng\/service\/\$compile/);
<ide> });
<ide>
<ide> });
<ide>\ No newline at end of file
<ide><path>docs/app/e2e/api-docs/service-pages.scenario.js
<ide> describe("service pages", function() {
<ide> browser.get('index-debug.html#!/api/ng/service/$compile');
<ide> var providerLink = element.all(by.css('ol.api-profile-header-structure li a')).first();
<ide> expect(providerLink.getText()).toEqual('- $compileProvider');
<del> expect(providerLink.getAttribute('href')).toMatch('api/ng/provider/$compileProvider');
<add> expect(providerLink.getAttribute('href')).toMatch(/api\/ng\/provider\/\$compileProvider/);
<ide>
<ide> browser.get('index-debug.html#!/api/ng/service/$q');
<ide> providerLink = element.all(by.css('ol.api-profile-header-structure li a')).first();
<ide> expect(providerLink.getText()).not.toEqual('- $qProvider');
<del> expect(providerLink.getAttribute('href')).not.toMatch('api/ng/provider/$compileProvider');
<add> expect(providerLink.getAttribute('href')).not.toMatch(/api\/ng\/provider\/\$compileProvider/);
<ide> });
<ide>
<ide> it("should show parameter defaults", function() { | 2 |
Ruby | Ruby | use assert_equal and assert_operator | 6548fc66178dd3d46e3a575e6937659c07293764 | <ide><path>actionpack/lib/action_dispatch/testing/assertions/selector.rb
<ide> def assert_select(*args, &block)
<ide> end
<ide> text.strip! unless NO_STRIP.include?(match.name)
<ide> unless match_with.is_a?(Regexp) ? (text =~ match_with) : (text == match_with.to_s)
<del> content_mismatch ||= build_message(message, "<?> expected but was\n<?>.", match_with, text)
<add> content_mismatch ||= sprintf("<%s> expected but was\n<%s>.", match_with, text)
<ide> true
<ide> end
<ide> end
<ide> def assert_select(*args, &block)
<ide> html = match.children.map(&:to_s).join
<ide> html.strip! unless NO_STRIP.include?(match.name)
<ide> unless match_with.is_a?(Regexp) ? (html =~ match_with) : (html == match_with.to_s)
<del> content_mismatch ||= build_message(message, "<?> expected but was\n<?>.", match_with, html)
<add> content_mismatch ||= sprintf("<%s> expected but was\n<%s>.", match_with, html)
<ide> true
<ide> end
<ide> end
<ide> def assert_select(*args, &block)
<ide> message ||= content_mismatch if matches.empty?
<ide> # Test minimum/maximum occurrence.
<ide> min, max, count = equals[:minimum], equals[:maximum], equals[:count]
<add>
<add> # FIXME: minitest provides messaging when we use assert_operator,
<add> # so is this custom message really needed?
<ide> message = message || %(Expected #{count_description(min, max, count)} matching "#{selector.to_s}", found #{matches.size}.)
<ide> if count
<del> assert matches.size == count, message
<add> assert_equal matches.size, count, message
<ide> else
<del> assert matches.size >= min, message if min
<del> assert matches.size <= max, message if max
<add> assert_operator matches.size, :>=, min, message if min
<add> assert_operator matches.size, :<=, max, message if max
<ide> end
<ide>
<ide> # If a block is given call that block. Set @selected to allow | 1 |
Go | Go | remove pkg/testutil tempfile and golden | 468154a841b599dd3a7acaf6162e2a73cf44d1f6 | <ide><path>pkg/testutil/golden/golden.go
<del>// Package golden provides function and helpers to use golden file for
<del>// testing purpose.
<del>package golden
<del>
<del>import (
<del> "flag"
<del> "io/ioutil"
<del> "path/filepath"
<del> "testing"
<del>)
<del>
<del>var update = flag.Bool("test.update", false, "update golden file")
<del>
<del>// Get returns the golden file content. If the `test.update` is specified, it updates the
<del>// file with the current output and returns it.
<del>func Get(t *testing.T, actual []byte, filename string) []byte {
<del> golden := filepath.Join("testdata", filename)
<del> if *update {
<del> if err := ioutil.WriteFile(golden, actual, 0644); err != nil {
<del> t.Fatal(err)
<del> }
<del> }
<del> expected, err := ioutil.ReadFile(golden)
<del> if err != nil {
<del> t.Fatal(err)
<del> }
<del> return expected
<del>}
<ide><path>pkg/testutil/tempfile/tempfile.go
<del>package tempfile
<del>
<del>import (
<del> "io/ioutil"
<del> "os"
<del>
<del> "github.com/stretchr/testify/require"
<del>)
<del>
<del>// TempFile is a temporary file that can be used with unit tests. TempFile
<del>// reduces the boilerplate setup required in each test case by handling
<del>// setup errors.
<del>type TempFile struct {
<del> File *os.File
<del>}
<del>
<del>// NewTempFile returns a new temp file with contents
<del>func NewTempFile(t require.TestingT, prefix string, content string) *TempFile {
<del> file, err := ioutil.TempFile("", prefix+"-")
<del> require.NoError(t, err)
<del>
<del> _, err = file.Write([]byte(content))
<del> require.NoError(t, err)
<del> file.Close()
<del> return &TempFile{File: file}
<del>}
<del>
<del>// Name returns the filename
<del>func (f *TempFile) Name() string {
<del> return f.File.Name()
<del>}
<del>
<del>// Remove removes the file
<del>func (f *TempFile) Remove() {
<del> os.Remove(f.Name())
<del>}
<del>
<del>// TempDir is a temporary directory that can be used with unit tests. TempDir
<del>// reduces the boilerplate setup required in each test case by handling
<del>// setup errors.
<del>type TempDir struct {
<del> Path string
<del>}
<del>
<del>// NewTempDir returns a new temp file with contents
<del>func NewTempDir(t require.TestingT, prefix string) *TempDir {
<del> path, err := ioutil.TempDir("", prefix+"-")
<del> require.NoError(t, err)
<del>
<del> return &TempDir{Path: path}
<del>}
<del>
<del>// Remove removes the file
<del>func (f *TempDir) Remove() {
<del> os.Remove(f.Path)
<del>} | 2 |
Ruby | Ruby | pass array of addresses | 5457770a36deef3047e37b5e5737b3fbc4705b00 | <ide><path>activesupport/lib/active_support/cache/mem_cache_store.rb
<ide> def initialize(*addresses)
<ide> addresses = addresses.flatten
<ide> addresses = ["localhost"] if addresses.empty?
<ide> @addresses = addresses
<del> @data = MemCache.new(*addresses)
<add> @data = MemCache.new(addresses)
<ide> end
<ide>
<ide> def read(key, options = nil) | 1 |
Python | Python | adapt earlystopping auto mode to auc | aa706f99a44f4c7436410e68ccc82ceb8c7a9955 | <ide><path>keras/callbacks.py
<ide> def __init__(self,
<ide> elif mode == 'max':
<ide> self.monitor_op = np.greater
<ide> else:
<del> if 'acc' in self.monitor:
<add> if (self.monitor.endswith('acc') or self.monitor.endswith('accuracy') or
<add> self.monitor.endswith('auc')):
<ide> self.monitor_op = np.greater
<ide> else:
<ide> self.monitor_op = np.less | 1 |
Javascript | Javascript | break the meta prototype chain! | 93743c1de5324d2dc5c7ad9e82a75c9adc7ef908 | <ide><path>packages/ember-metal/lib/meta.js
<ide> export function meta(obj, writable) {
<ide> ret.getOrCreateValues();
<ide> }
<ide> } else if (ret.source !== obj) {
<del> // temporary dance until I can eliminate remaining uses of
<del> // prototype chain
<del> let newRet = Object.create(ret);
<del> newRet.parent = ret;
<del> for (let i = 0; i < memberNames.length; i++) {
<del> newRet[memberProperty(memberNames[i])] = undefined;
<del> }
<del> ret = newRet;
<del> // end temporary dance
<del>
<del> ret.source = obj;
<add> ret = new Meta(obj, ret);
<ide> }
<ide> obj.__ember_meta__ = ret;
<ide> return ret; | 1 |
PHP | PHP | add missing spaces | 7b1086e632ee647496544dd87f0faf8c24c52060 | <ide><path>lib/Cake/Model/Datasource/Database/Sqlserver.php
<ide> public function describe($model) {
<ide> COLUMNPROPERTY(OBJECT_ID('" . $table . "'), COLUMN_NAME, 'IsIdentity') as [Key],
<ide> NUMERIC_SCALE as Size
<ide> FROM INFORMATION_SCHEMA.COLUMNS
<del> WHERE TABLE_NAME = '" . $table . "'".($schema?" AND TABLE_SCHEMA = '" . $schema . "'":'')
<add> WHERE TABLE_NAME = '" . $table . "'" . ($schema ? " AND TABLE_SCHEMA = '" . $schema . "'" : '')
<ide> );
<ide> if (!$cols) {
<ide> throw new CakeException(__d('cake_dev', 'Could not describe table for %s', $table)); | 1 |
Ruby | Ruby | add tests for plugin sanity check | dd05b6c543f48050f494214da7803da6f5655292 | <ide><path>railties/lib/rails/engine/configurable.rb
<ide> class Engine
<ide> module Configurable
<ide> def self.included(base)
<ide> base.extend ClassMethods
<del> base.delegate :middleware, :root, :paths, :to => :config
<ide> end
<ide>
<ide> module ClassMethods
<add> delegate :middleware, :root, :paths, :to => :config
<add>
<ide> def config
<ide> @config ||= Engine::Configuration.new(find_root_with_flag("lib"))
<ide> end
<ide><path>railties/lib/rails/plugin.rb
<ide> def config
<ide> eval(File.read(file), binding, file) if file && File.file?(file)
<ide> end
<ide>
<del> # TODO Write tests for this sanity check
<ide> initializer :sanity_check_railties_collision do
<ide> if Engine.subclasses.map { |k| k.root.to_s }.include?(root.to_s)
<del> raise "The plugin #{name.inspect} is a Railtie or an Engine and cannot be installed as Plugin"
<add> raise "\"#{name}\" is a Railtie/Engine and cannot be installed as plugin"
<ide> end
<ide> end
<ide> end
<ide><path>railties/test/plugins/vendored_test.rb
<ide> def index
<ide> assert_equal 200, last_response.status
<ide> assert_equal "Rendered from namespace", last_response.body
<ide> end
<add>
<add> test "plugin cannot declare an engine for it" do
<add> @plugin.write "lib/bukkits.rb", <<-RUBY
<add> class Bukkits
<add> class Engine < Rails::Engine
<add> end
<add> end
<add> RUBY
<add>
<add> @plugin.write "init.rb", <<-RUBY
<add> require "bukkits"
<add> RUBY
<add>
<add> rescued = false
<add>
<add> begin
<add> boot_rails
<add> rescue Exception => e
<add> rescued = true
<add> assert_equal '"bukkits" is a Railtie/Engine and cannot be installed as plugin', e.message
<add> end
<add>
<add> assert rescued, "Expected boot rails to fail"
<add> end
<ide> end
<ide>
<ide> class VendoredOrderingTest < Test::Unit::TestCase | 3 |
Java | Java | support bridged methods in mvcuricomponentsbuilder | 205e5dfd6fdf89e0049da29817a6474abddbc2e9 | <ide><path>spring-webmvc/src/main/java/org/springframework/web/servlet/mvc/method/annotation/MvcUriComponentsBuilder.java
<ide> import java.util.HashMap;
<ide> import java.util.List;
<ide> import java.util.Map;
<add>import java.util.Set;
<ide>
<ide> import javax.servlet.http.HttpServletRequest;
<ide>
<ide> import org.springframework.util.ObjectUtils;
<ide> import org.springframework.util.PathMatcher;
<ide> import org.springframework.util.ReflectionUtils;
<add>import org.springframework.util.ReflectionUtils.MethodFilter;
<ide> import org.springframework.util.StringUtils;
<ide> import org.springframework.web.bind.annotation.RequestMapping;
<ide> import org.springframework.web.context.WebApplicationContext;
<ide> import org.springframework.web.context.request.RequestAttributes;
<ide> import org.springframework.web.context.request.RequestContextHolder;
<ide> import org.springframework.web.context.request.ServletRequestAttributes;
<ide> import org.springframework.web.method.HandlerMethod;
<add>import org.springframework.web.method.HandlerMethodSelector;
<ide> import org.springframework.web.method.annotation.RequestParamMethodArgumentResolver;
<ide> import org.springframework.web.method.support.CompositeUriComponentsContributor;
<ide> import org.springframework.web.servlet.DispatcherServlet;
<ide> private static String getMethodRequestMapping(Method method) {
<ide> return paths[0];
<ide> }
<ide>
<del>
<del> private static Method getMethod(Class<?> controllerType, String methodName, Object... args) {
<del> Method match = null;
<del> for (Method method : controllerType.getDeclaredMethods()) {
<del> if (method.getName().equals(methodName) && method.getParameterTypes().length == args.length) {
<del> if (match != null) {
<del> throw new IllegalArgumentException(String.format(
<del> "Found two methods named '%s' accepting arguments %s in controller %s: [%s] and [%s]",
<del> methodName, Arrays.asList(args), controllerType.getName(), match.toGenericString(),
<del> method.toGenericString()));
<del> }
<del> match = method;
<add> private static Method getMethod(Class<?> controllerType, final String methodName, final Object... args) {
<add> MethodFilter selector = new MethodFilter() {
<add> @Override
<add> public boolean matches(Method method) {
<add> String name = method.getName();
<add> int argLength = method.getParameterTypes().length;
<add> return (name.equals(methodName) && argLength == args.length);
<ide> }
<add> };
<add> Set<Method> methods = HandlerMethodSelector.selectMethods(controllerType, selector);
<add> if (methods.size() == 1) {
<add> return methods.iterator().next();
<ide> }
<del> if (match == null) {
<add> else if (methods.size() > 1) {
<add> throw new IllegalArgumentException(String.format(
<add> "Found two methods named '%s' accepting arguments %s in controller %s: [%s]",
<add> methodName, Arrays.asList(args), controllerType.getName(), methods));
<add> }
<add> else {
<ide> throw new IllegalArgumentException("No method named '" + methodName + "' with " + args.length +
<ide> " arguments found in controller " + controllerType.getName());
<ide> }
<del> return match;
<ide> }
<ide>
<ide> private static UriComponents applyContributors(UriComponentsBuilder builder, Method method, Object... args) {
<ide><path>spring-webmvc/src/test/java/org/springframework/web/servlet/mvc/method/annotation/MvcUriComponentsBuilderTests.java
<ide>
<ide> package org.springframework.web.servlet.mvc.method.annotation;
<ide>
<add>import static org.hamcrest.Matchers.*;
<add>import static org.junit.Assert.*;
<add>import static org.springframework.web.servlet.mvc.method.annotation.MvcUriComponentsBuilder.*;
<add>
<ide> import java.lang.annotation.Documented;
<ide> import java.lang.annotation.ElementType;
<ide> import java.lang.annotation.Retention;
<ide> import java.util.List;
<ide>
<ide> import org.hamcrest.Matchers;
<del>
<ide> import org.joda.time.DateTime;
<ide> import org.joda.time.format.ISODateTimeFormat;
<del>
<ide> import org.junit.After;
<ide> import org.junit.Before;
<del>import org.junit.Ignore;
<ide> import org.junit.Test;
<ide>
<ide> import org.springframework.context.annotation.Bean;
<ide> import org.springframework.web.util.UriComponents;
<ide> import org.springframework.web.util.UriComponentsBuilder;
<ide>
<del>import static org.hamcrest.Matchers.*;
<del>import static org.junit.Assert.*;
<del>import static org.springframework.web.servlet.mvc.method.annotation.MvcUriComponentsBuilder.*;
<del>
<ide> /**
<ide> * Unit tests for {@link org.springframework.web.servlet.mvc.method.annotation.MvcUriComponentsBuilder}.
<ide> *
<ide> * @author Rossen Stoyanchev
<ide> * @author Sam Brannen
<ide> */
<add>@SuppressWarnings("unused")
<ide> public class MvcUriComponentsBuilderTests {
<ide>
<ide> private final MockHttpServletRequest request = new MockHttpServletRequest();
<ide> public void testFromMethodNameWithPathVarAndRequestParam() throws Exception {
<ide> assertThat(queryParams.get("offset"), contains("10"));
<ide> }
<ide>
<add> // SPR-12977
<add>
<ide> @Test
<del> // TODO [SPR-12977] Enable fromMethodNameWithBridgedMethod() test.
<del> @Ignore("Disabled until SPR-12977 is resolved")
<ide> public void fromMethodNameWithBridgedMethod() throws Exception {
<del> UriComponents uriComponents = fromMethodName(PersonCrudController.class, "get", new Long(42)).build();
<del> assertThat(uriComponents.toUriString(), is("http://localhost/get/42"));
<add> UriComponents uriComponents = fromMethodName(PersonCrudController.class, "get", (long) 42).build();
<add> assertThat(uriComponents.toUriString(), is("http://localhost/42"));
<ide> }
<ide>
<ide> // SPR-11391 | 2 |
Javascript | Javascript | remove some invariants and deadcode | 13ed0317fa4aeb2281dbd295b302d99ad2cd6aed | <ide><path>src/browser/ui/ReactDOMComponent.js
<ide> ReactDOMComponent.Mixin = {
<ide> * @return {string} The computed markup.
<ide> */
<ide> mountComponent: function(rootID, transaction, mountDepth, context) {
<del> invariant(context !== undefined, "Context is required parameter");
<ide> ReactComponent.Mixin.mountComponent.call(
<ide> this,
<ide> rootID,
<ide> ReactDOMComponent.Mixin = {
<ide> },
<ide>
<ide> receiveComponent: function(nextElement, transaction, context) {
<del> invariant(context !== undefined, "Context is required parameter");
<ide> if (nextElement === this._currentElement &&
<ide> nextElement._owner != null) {
<ide> // Since elements are immutable after the owner is rendered,
<ide> ReactDOMComponent.Mixin = {
<ide> * @overridable
<ide> */
<ide> updateComponent: function(transaction, prevElement, nextElement, context) {
<del> if(context === undefined) throw new Error("Context required for mounting");
<del> if(context === null) throw new Error("Assert: context is not null");
<ide> assertValidProps(this._currentElement.props);
<ide> ReactComponent.Mixin.updateComponent.call(
<ide> this,
<ide> ReactDOMComponent.Mixin = {
<ide> * @param {ReactReconcileTransaction} transaction
<ide> */
<ide> _updateDOMChildren: function(lastProps, transaction, context) {
<del> invariant(context !== undefined, "Context is required parameter");
<ide> var nextProps = this._currentElement.props;
<ide>
<ide> var lastContent =
<ide><path>src/core/ReactComponent.js
<ide> var ReactComponent = {
<ide> * @internal
<ide> */
<ide> mountComponent: function(rootID, transaction, mountDepth, context) {
<del> invariant(context !== undefined, "Context is required parameter");
<ide> var ref = this._currentElement.ref;
<ide> if (ref != null) {
<ide> var owner = this._currentElement._owner;
<ide> var ReactComponent = {
<ide> * @internal
<ide> */
<ide> updateComponent: function(transaction, prevElement, nextElement, context) {
<del> invariant(context !== undefined, "Context is required parameter");
<ide> // If either the owner or a `ref` has changed, make sure the newest owner
<ide> // has stored a reference to `this`, and the previous owner (if different)
<ide> // has forgotten the reference to `this`. We use the element instead
<ide><path>src/core/ReactCompositeComponent.js
<ide> var ReactCompositeComponentMixin = assign({},
<ide> * @internal
<ide> */
<ide> mountComponent: function(rootID, transaction, mountDepth, context) {
<del> invariant(context !== undefined, "Context is required parameter");
<ide> ReactComponent.Mixin.mountComponent.call(
<ide> this,
<ide> rootID,
<ide> var ReactCompositeComponentMixin = assign({},
<ide> },
<ide>
<ide> receiveComponent: function(nextElement, transaction, context) {
<del> invariant(context !== undefined, "Context is required parameter");
<ide> if (nextElement === this._currentElement &&
<ide> nextElement._owner != null) {
<ide> // Since elements are immutable after the owner is rendered,
<ide> var ReactCompositeComponentMixin = assign({},
<ide> * TODO: Remove this check when owner-context is removed
<ide> */
<ide> _warnIfContextsDiffer: function(ownerBasedContext, parentBasedContext) {
<del> invariant(ownerBasedContext !== undefined, "Owner based context is required parameter");
<del> invariant(parentBasedContext !== undefined, "Parent based ontext is required parameter");
<ide> var ownerKeys = Object.keys(ownerBasedContext).sort();
<ide> var parentKeys = Object.keys(parentBasedContext).sort();
<ide> if (ownerKeys.length != parentKeys.length || ownerKeys.toString() != parentKeys.toString()) {
<ide> var ReactCompositeComponentMixin = assign({},
<ide> transaction,
<ide> unmaskedContext
<ide> ) {
<del> invariant(unmaskedContext !== undefined, "Context required for mounting");
<del> invariant(unmaskedContext !== null, "Context must be non-null");
<ide> var inst = this._instance;
<ide>
<ide> var prevProps = inst.props;
<ide> var ReactCompositeComponentMixin = assign({},
<ide> * @internal
<ide> */
<ide> _updateRenderedComponent: function(transaction, context) {
<del> invariant(context !== undefined, "Context is required parameter");
<ide> var prevComponentInstance = this._renderedComponent;
<ide> var prevRenderedElement = prevComponentInstance._currentElement;
<ide> var nextRenderedElement = this._renderValidatedComponent();
<ide> var ShallowMixin = assign({},
<ide> var prevComponentInstance = this._renderedComponent;
<ide> var prevRenderedElement = prevComponentInstance._currentElement;
<ide> // Use the without-owner-or-context variant of _rVC below:
<del> var nextRenderedElement = this._renderValidatedComponentWithoutOwnerOrContext();
<del> if (shouldUpdateReactComponent(prevRenderedElement, nextRenderedElement)) {
<del> prevComponentInstance.receiveComponent(
<del> nextRenderedElement,
<del> transaction
<del> );
<del> } else {
<del> // These two IDs are actually the same! But nothing should rely on that.
<del> var thisID = this._rootNodeID;
<del> var prevComponentID = prevComponentInstance._rootNodeID;
<del> // Don't unmount previous instance since it was never mounted, due to
<del> // shallow render.
<del> //prevComponentInstance.unmountComponent();
<del> this._renderedComponent = nextRenderedElement;
<del> // ^ no instantiateReactComponent
<del> //
<del> // no recursive mountComponent
<del> return nextRenderedElement;
<del> }
<add> var nextRenderedElement =
<add> this._renderValidatedComponentWithoutOwnerOrContext();
<add> // This is a noop in shallow render
<add> shouldUpdateReactComponent(prevRenderedElement, nextRenderedElement);
<add> this._renderedComponent = nextRenderedElement;
<ide> }
<ide>
<ide> });
<ide><path>src/core/ReactMultiChild.js
<ide> var ReactMultiChildUpdateTypes = require('ReactMultiChildUpdateTypes');
<ide>
<ide> var flattenChildren = require('flattenChildren');
<ide> var instantiateReactComponent = require('instantiateReactComponent');
<del>var invariant = require('invariant');
<ide> var shouldUpdateReactComponent = require('shouldUpdateReactComponent');
<ide>
<ide> /**
<ide> var ReactMultiChild = {
<ide> * @internal
<ide> */
<ide> mountChildren: function(nestedChildren, transaction, context) {
<del> invariant(context !== undefined, "Context is required parameter");
<ide> var children = flattenChildren(nestedChildren);
<ide> var mountImages = [];
<ide> var index = 0;
<ide> var ReactMultiChild = {
<ide> * @internal
<ide> */
<ide> updateChildren: function(nextNestedChildren, transaction, context) {
<del> invariant(context !== undefined, "Context is required parameter");
<ide> updateDepth++;
<ide> var errorThrown = true;
<ide> try {
<ide> var ReactMultiChild = {
<ide> * @protected
<ide> */
<ide> _updateChildren: function(nextNestedChildren, transaction, context) {
<del> invariant(context !== undefined, "Context is required parameter");
<ide> var nextChildren = flattenChildren(nextNestedChildren);
<ide> var prevChildren = this._renderedChildren;
<ide> if (!nextChildren && !prevChildren) {
<ide> var ReactMultiChild = {
<ide> index,
<ide> transaction,
<ide> context) {
<del> invariant(context !== undefined, "Context is required parameter");
<ide> // Inlined for performance, see `ReactInstanceHandles.createReactID`.
<ide> var rootID = this._rootNodeID + name;
<ide> var mountImage = child.mountComponent( | 4 |
Text | Text | improve translate, added text in tests | 6985e4942b55b73e2b482e3cfae6f242211cf511 | <ide><path>curriculum/challenges/russian/01-responsive-web-design/applied-accessibility/improve-form-field-accessibility-with-the-label-element.russian.md
<ide> localeTitle: Улучшить доступность поля формы с по
<ide> ---
<ide>
<ide> ## Description
<del><section id="description"> Улучшение доступности с семантической разметкой HTML применяется к использованию как соответствующих имен тегов, так и атрибутов. Следующие несколько проблем охватывают некоторые важные сценарии с использованием атрибутов в формах. <code>label</code> метки обертывает текст для определенного элемента управления формой, как правило, имя или ярлык для выбора. Это связывает смысл с элементом и делает форму более читаемой. <code>for</code> атрибута на <code>label</code> тега явно связывает эту <code>label</code> с контролем формы и используется для чтения с экрана. Вы узнали о переключателях и их ярлыках в уроке в разделе «Основные HTML». В этом уроке мы завернули элемент ввода переключателя внутри элемента <code>label</code> вместе с текстом ярлыка, чтобы сделать текст кликабельным. Другой способ добиться этого - использовать атрибут <code>for</code> как объяснено в этом уроке. Значение атрибута <code>for</code> должно быть таким же, как значение атрибута <code>id</code> элемента управления формой. Вот пример: <blockquote> <Форма> <br> <label for = "name"> Имя: </ label> <br> <input type = "text" id = "name" name = "name"> <br> </ Форма> <br></blockquote></section>
<add><section id="description"> Улучшение доступности с семантической разметкой HTML применяется к использованию как соответствующих имен тегов, так и атрибутов. Следующие несколько проблем охватывают некоторые важные сценарии с использованием атрибутов в формах. <code>label</code> метки обертывают текст для определенного элемента управления формой, как правило это имя или ярлык для выбора. Это связывает смысл с элементом и делает форму более читаемой. <code>for</code> атрибут на <code>label</code> теге явно связывает этот <code>label</code> с контролем формы и используется для чтения с экрана. Вы узнали о переключателях и их ярлыках в уроке в разделе «Основы HTML». В этом уроке мы завернули элемент ввода переключателя внутри элемента <code>label</code> вместе с текстом ярлыка, чтобы сделать текст кликабельным. Другой способ добиться этого - использовать атрибут <code>for</code> как объяснено в этом уроке. Значение атрибута <code>for</code> должно быть таким же, как значение атрибута <code>id</code> элемента управления формой. Вот пример: <blockquote> <Форма> <br> <label for = "name"> Имя: </ label> <br> <input type = "text" id = "name" name = "name"> <br> </ Форма> <br></blockquote></section>
<ide>
<ide> ## Instructions
<del><section id="instructions"> Camper Cat ожидает большой интерес к его задумчивым сообщениям в блоге и хочет включить форму для регистрации электронной почты. Добавить <code>for</code> атрибута электронной <code>label</code> , которая соответствует <code>id</code> на его <code>input</code> поле. </section>
<add><section id="instructions"> Camper Cat рассчитывает на большой интерес к его вдумчивым сообщениям в блоге и хочет включить форму для регистрации электронной почты. Добавьте <code>for</code> атрибут к <code>label</code> электронной почты, которая соответствует <code>id</code> на его <code>input</code> поле. </section>
<ide>
<ide> ## Tests
<ide> <section id='tests'>
<ide>
<ide> ```yml
<ide> tests:
<del> - text: ''
<add> - text: 'Ваш код должен иметь атрибут <code>for</code> в теге <code>label</code>, который не является пустым.'
<ide> testString: 'assert($("label").attr("for"), "Your code should have a <code>for</code> attribute on the <code>label</code> tag that is not empty.");'
<del> - text: ''
<add> - text: 'Значение атрибута <code>for</code> должно соответствовать значению <code>id</code> электронной почты <code>input</code>.'
<ide> testString: 'assert($("label").attr("for") == "email", "Your <code>for</code> attribute value should match the <code>id</code> value on the email <code>input</code>.");'
<ide>
<ide> ``` | 1 |
Python | Python | correct a bug with special key (issue #163) | d767f717bb0d2a11bf6a67f661d9574cc070a7be | <ide><path>glances/glances.py
<ide> def __getProcessMemColor(self, current=0, max=100):
<ide> def __getProcessMemColor2(self, current=0, max=100):
<ide> return self.__colors_list2[self.__getProcessAlert(current, max, 'MEM')]
<ide>
<add> def __getkey(self, window):
<add> '''
<add> A getKey function to catch ESC key AND Numlock key (issue #163)
<add> '''
<add> keycode = [ 0, 0 ]
<add> keycode[0] = window.getch()
<add> keycode[1] = window.getch()
<add>
<add> if (keycode[0] == 27) and (keycode[1] != -1):
<add> # Do not escape on specials keys
<add> return -1
<add> else:
<add> return keycode[0]
<add>
<ide> def __catchKey(self):
<ide> # Get key
<del> self.pressedkey = self.term_window.getch()
<del>
<add> #~ self.pressedkey = self.term_window.getch()
<add> self.pressedkey = self.__getkey(self.term_window)
<add>
<ide> # Actions...
<ide> if self.pressedkey == 27 or self.pressedkey == 113:
<ide> # 'ESC'|'q' > Quit | 1 |
PHP | PHP | fix build failures | e59a9618b634bf66b6ee85891f19e656765a8c1f | <ide><path>tests/TestCase/Console/TaskRegistryTest.php
<ide> public function tearDown() {
<ide> * @return void
<ide> */
<ide> public function testLoad() {
<del> $result = $this->Tasks->load('DbConfig');
<del> $this->assertInstanceOf('Cake\Console\Command\Task\DbConfigTask', $result);
<del> $this->assertInstanceOf('Cake\Console\Command\Task\DbConfigTask', $this->Tasks->DbConfig);
<add> $result = $this->Tasks->load('Project');
<add> $this->assertInstanceOf('Cake\Console\Command\Task\ProjectTask', $result);
<add> $this->assertInstanceOf('Cake\Console\Command\Task\ProjectTask', $this->Tasks->Project);
<ide>
<ide> $result = $this->Tasks->loaded();
<del> $this->assertEquals(array('DbConfig'), $result, 'loaded() results are wrong.');
<add> $this->assertEquals(['Project'], $result, 'loaded() results are wrong.');
<ide> }
<ide>
<ide> /**
<ide> public function testLoadPluginTask() {
<ide> public function testLoadWithAlias() {
<ide> Plugin::load('TestPlugin');
<ide>
<del> $result = $this->Tasks->load('DbConfigAliased', array('className' => 'DbConfig'));
<del> $this->assertInstanceOf('Cake\Console\Command\Task\DbConfigTask', $result);
<del> $this->assertInstanceOf('Cake\Console\Command\Task\DbConfigTask', $this->Tasks->DbConfigAliased);
<add> $result = $this->Tasks->load('ProjectAliased', array('className' => 'Project'));
<add> $this->assertInstanceOf('Cake\Console\Command\Task\ProjectTask', $result);
<add> $this->assertInstanceOf('Cake\Console\Command\Task\ProjectTask', $this->Tasks->ProjectAliased);
<ide>
<ide> $result = $this->Tasks->loaded();
<del> $this->assertEquals(array('DbConfigAliased'), $result, 'loaded() results are wrong.');
<add> $this->assertEquals(array('ProjectAliased'), $result, 'loaded() results are wrong.');
<ide>
<ide> $result = $this->Tasks->load('SomeTask', array('className' => 'TestPlugin.OtherTask'));
<ide> $this->assertInstanceOf('TestPlugin\Console\Command\Task\OtherTaskTask', $result);
<ide> $this->assertInstanceOf('TestPlugin\Console\Command\Task\OtherTaskTask', $this->Tasks->SomeTask);
<ide>
<ide> $result = $this->Tasks->loaded();
<del> $this->assertEquals(array('DbConfigAliased', 'SomeTask'), $result, 'loaded() results are wrong.');
<add> $this->assertEquals(array('ProjectAliased', 'SomeTask'), $result, 'loaded() results are wrong.');
<ide> }
<ide>
<ide> } | 1 |
Text | Text | convert lib and frameworks to bulleted list-readme | 4b4f76df5afd3fa1cfc76acf9077140ab7624e48 | <ide><path>README.md
<ide> are bundled together in [Action Pack](actionpack/README.rdoc).
<ide> ## Frameworks and libraries
<ide>
<ide> [Active Record](activerecord/README.rdoc), [Active Model](activemodel/README.rdoc), [Action Pack](actionpack/README.rdoc), and [Action View](actionview/README.rdoc) can each be used independently outside Rails.
<del>In addition to that, Rails also comes with [Action Mailer](actionmailer/README.rdoc), a library
<del>to generate and send emails; [Action Mailbox](actionmailbox/README.md), a library to receive emails within a Rails application;
<del>[Active Job](activejob/README.md), a framework for declaring jobs and making them run on a variety of queuing
<del>backends; [Action Cable](actioncable/README.md), a framework to
<del>integrate WebSockets with a Rails application; [Active Storage](activestorage/README.md), a library to attach cloud
<del>and local files to Rails applications; [Action Text](actiontext/README.md), a library to handle rich text content;
<del>and [Active Support](activesupport/README.rdoc), a collection
<del>of utility classes and standard library extensions that are useful for Rails,
<del>and may also be used independently outside Rails.
<add>
<add>In addition to that, Rails also comes with:
<add>
<add>- [Action Mailer](actionmailer/README.rdoc), a library to generate and send emails
<add>- [Action Mailbox](actionmailbox/README.md), a library to receive emails within a Rails application
<add>- [Active Job](activejob/README.md), a framework for declaring jobs and making them run on a variety of queuing backends
<add>- [Action Cable](actioncable/README.md), a framework to integrate WebSockets with a Rails application
<add>- [Active Storage](activestorage/README.md), a library to attach cloud and local files to Rails applications
<add>- [Action Text](actiontext/README.md), a library to handle rich text content
<add>- [Active Support](activesupport/README.rdoc), a collection of utility classes and standard library extensions that are useful for Rails, and may also be used independently outside Rails
<ide>
<ide> ## Getting Started
<ide> | 1 |
PHP | PHP | add test case for patching | 47baf43aa137ec104331aab20375550fb40f8a4f | <ide><path>tests/TestCase/ORM/TableTest.php
<ide>
<ide> use ArrayObject;
<ide> use Cake\Collection\Collection;
<del>use Cake\Core\Plugin;
<ide> use Cake\Database\Exception;
<ide> use Cake\Database\Expression\QueryExpression;
<ide> use Cake\Database\Schema\TableSchema;
<ide> class UsersTable extends Table
<ide> class ProtectedEntity extends Entity
<ide> {
<ide> protected $_accessible = [
<del> 'id' => true,
<add> 'id' => false,
<ide> 'title' => false,
<add> 'body' => true,
<ide> ];
<ide> }
<ide>
<ide> public function testFindOrCreateAccessibleFields()
<ide> $this->assertSame('test', $article->title);
<ide> }
<ide>
<add> /**
<add> * Test that findOrCreate cannot accidentally bypass required validation.
<add> *
<add> * @return void
<add> */
<add> public function testFindOrCreatePartialValidation()
<add> {
<add> $articles = $this->getTableLocator()->get('Articles');
<add> $articles->setEntityClass(ProtectedEntity::class);
<add> $validator = new Validator();
<add> $validator->notBlank('title')->requirePresence('title', 'create');
<add> $validator->notBlank('body')->requirePresence('body', 'create');
<add> $articles->setValidator('default', $validator);
<add>
<add> $this->expectException(PersistenceFailedException::class);
<add> $this->expectExceptionMessage(
<add> 'Entity findOrCreate failure. ' .
<add> 'Found the following errors (title._required: "This field is required").'
<add> );
<add>
<add> $articles->findOrCreate(['body' => 'test']);
<add> }
<add>
<ide> /**
<ide> * Test that creating a table fires the initialize event.
<ide> * | 1 |
Go | Go | unify tempdir implementation | 3314f4ef09fbe6fa4c32f1b114959388d75210a4 | <ide><path>pkg/ioutils/temp_unix.go
<del>//go:build !windows
<del>// +build !windows
<del>
<del>package ioutils // import "github.com/docker/docker/pkg/ioutils"
<del>
<del>import "os"
<del>
<del>// TempDir on Unix systems is equivalent to os.MkdirTemp.
<del>func TempDir(dir, prefix string) (string, error) {
<del> return os.MkdirTemp(dir, prefix)
<del>}
<add><path>pkg/ioutils/tempdir.go
<del><path>pkg/ioutils/temp_windows.go
<ide> package ioutils // import "github.com/docker/docker/pkg/ioutils"
<ide>
<ide> import (
<ide> "os"
<add> "runtime"
<ide>
<ide> "github.com/docker/docker/pkg/longpath"
<ide> )
<ide>
<del>// TempDir is the equivalent of os.MkdirTemp, except that the result is in Windows longpath format.
<add>// TempDir is the equivalent of [os.MkdirTemp], except that on Windows
<add>// the result is in Windows longpath format. On Unix systems it is
<add>// equivalent to [os.MkdirTemp].
<ide> func TempDir(dir, prefix string) (string, error) {
<ide> tempDir, err := os.MkdirTemp(dir, prefix)
<ide> if err != nil {
<ide> return "", err
<ide> }
<add> if runtime.GOOS != "windows" {
<add> return tempDir, nil
<add> }
<ide> return longpath.AddPrefix(tempDir), nil
<ide> } | 2 |
Javascript | Javascript | remove deprecated extensions from ajax promise | 9d1b989f20b550af3590691723b0620f6914626e | <ide><path>src/ajax.js
<ide> jQuery.extend({
<ide> };
<ide>
<ide> // Attach deferreds
<del> deferred.promise( jqXHR ).complete = completeDeferred.add;
<del> jqXHR.success = jqXHR.done;
<del> jqXHR.error = jqXHR.fail;
<add> deferred.promise( jqXHR );
<ide>
<ide> // Remove hash character (#7531: and string promotion)
<ide> // Add protocol if not provided (prefilters might expect it)
<ide> jQuery.extend({
<ide> strAbort = "abort";
<ide>
<ide> // Install callbacks on deferreds
<del> for ( i in { success: 1, error: 1, complete: 1 } ) {
<del> jqXHR[ i ]( s[ i ] );
<del> }
<add> completeDeferred.add( s.complete );
<add> jqXHR.done( s.success );
<add> jqXHR.fail( s.error );
<ide>
<ide> // Get transport
<ide> transport = inspectPrefiltersOrTransports( transports, s, options, jqXHR );
<ide><path>test/unit/ajax.js
<ide> module( "ajax", {
<ide> },
<ide> success: true,
<ide> afterSend: function( request ) {
<del> request.complete(function() {
<add> request.always(function() {
<ide> ok( true, "complete" );
<del> }).success(function() {
<add> }).done(function() {
<ide> ok( true, "success" );
<del> }).error(function() {
<add> }).fail(function() {
<ide> ok( false, "error" );
<ide> });
<ide> }
<ide> module( "ajax", {
<ide> },
<ide> success: true,
<ide> complete: function( xhr ) {
<del> xhr.complete(function() {
<add> xhr.always(function() {
<ide> ok( true, "complete" );
<del> }).success(function() {
<add> }).done(function() {
<ide> ok( true, "success" );
<del> }).error(function() {
<add> }).fail(function() {
<ide> ok( false, "error" );
<ide> });
<ide> } | 2 |
Go | Go | add test to enforce volume build content | eac27ad46d7df4f11a28b84130ff484224f8b63d | <ide><path>integration-cli/docker_cli_build_test.go
<ide> RUN [ ! -e /injected ]`,
<ide>
<ide> logDone("build - xz host is being used")
<ide> }
<add>
<add>func TestBuildVolumesRetainContents(t *testing.T) {
<add> var (
<add> name = "testbuildvolumescontent"
<add> expected = "some text"
<add> )
<add> defer deleteImages(name)
<add> ctx, err := fakeContext(`
<add>FROM busybox
<add>COPY content /foo/file
<add>VOLUME /foo
<add>CMD cat /foo/file`,
<add> map[string]string{
<add> "content": expected,
<add> })
<add> if err != nil {
<add> t.Fatal(err)
<add> }
<add> defer ctx.Close()
<add>
<add> if _, err := buildImageFromContext(name, ctx, false); err != nil {
<add> t.Fatal(err)
<add> }
<add>
<add> out, _, err := runCommandWithOutput(exec.Command(dockerBinary, "run", "--rm", name))
<add> if err != nil {
<add> t.Fatal(err)
<add> }
<add> if out != expected {
<add> t.Fatalf("expected file contents for /foo/file to be %q but received %q", expected, out)
<add> }
<add>
<add> logDone("build - volumes retain contents in build")
<add>} | 1 |
PHP | PHP | fix misspellings in mailer implementation | cd9f1c77661112b835e9e8de7fed0eb365e498de | <ide><path>src/Illuminate/Mail/Mailer.php
<ide> public function bcc($users)
<ide> }
<ide>
<ide> /**
<del> * Send a new message with only an HTML part.
<add> * Send a new message with only a HTML part.
<ide> *
<ide> * @param string $html
<ide> * @param mixed $callback
<ide> public function html($html, $callback)
<ide> }
<ide>
<ide> /**
<del> * Send a new message when only a raw text part.
<add> * Send a new message with only a raw text part.
<ide> *
<ide> * @param string $text
<ide> * @param mixed $callback
<ide> public function raw($text, $callback)
<ide> }
<ide>
<ide> /**
<del> * Send a new message when only a plain part.
<add> * Send a new message with only a plain part.
<ide> *
<ide> * @param string $view
<ide> * @param array $data | 1 |
Java | Java | fix measure of reactslider for android api < 21 | 75e6f7961fb3f6de6afbe79d49c42ad55fba1673 | <ide><path>ReactAndroid/src/main/java/com/facebook/react/views/slider/ReactSlider.java
<ide> public ReactSlider(Context context, @Nullable AttributeSet attrs, int style) {
<ide> disableStateListAnimatorIfNeeded();
<ide> }
<ide>
<del> private void disableStateListAnimatorIfNeeded() {
<add> /* package */ void disableStateListAnimatorIfNeeded() {
<ide> // We disable the state list animator for Android 6 and 7; this is a hack to prevent T37452851
<ide> // and https://github.com/facebook/react-native/issues/9979
<ide> if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M
<ide><path>ReactAndroid/src/main/java/com/facebook/react/views/slider/ReactSliderManager.java
<ide> public long measure(
<ide> float height,
<ide> YogaMeasureMode heightMode) {
<ide> if (!mMeasured) {
<del> SeekBar reactSlider = new ReactSlider(getThemedContext(), null, STYLE);
<add> ReactSlider reactSlider = new ReactSlider(getThemedContext(), null, STYLE);
<ide> // reactSlider is used for measurements purposes, it is not necessary to set a
<ide> // StateListAnimator.
<ide> // It is not safe to access StateListAnimator from a background thread.
<del> reactSlider.setStateListAnimator(null);
<add> reactSlider.disableStateListAnimatorIfNeeded();
<ide> final int spec =
<ide> View.MeasureSpec.makeMeasureSpec(
<ide> ViewGroup.LayoutParams.WRAP_CONTENT, View.MeasureSpec.UNSPECIFIED); | 2 |
Text | Text | update the manuals of docker and dockerd | b3e14c25f2926bde61ead09cbe40fd549f76ab75 | <ide><path>man/docker.1.md
<ide> docker \- Docker image and container command line interface
<ide> # SYNOPSIS
<ide> **docker** [OPTIONS] COMMAND [ARG...]
<ide>
<del>**docker** daemon [--help|...]
<del>
<ide> **docker** [--help|-v|--version]
<ide>
<ide> # DESCRIPTION
<del>is a client for interacting with the daemon (see **dockerd(8)**) through the CLI.
<add>**docker** is a client for interacting with the daemon (see **dockerd(8)**) through the CLI.
<ide>
<ide> The Docker CLI has over 30 commands. The commands are listed below and each has
<ide> its own man page which explain usage and arguments.
<ide> unix://[/path/to/socket] to use.
<ide>
<ide> Use "docker help" or "docker --help" to get an overview of available commands.
<ide>
<del># RUNTIME EXECUTION OPTIONS
<del>
<del>Use the **--exec-opt** flags to specify options to the execution driver.
<del>The following options are available:
<del>
<del>#### native.cgroupdriver
<del>Specifies the management of the container's `cgroups`. You can specify `cgroupfs`
<del>or `systemd`. If you specify `systemd` and it is not available, the system errors
<del>out.
<del>
<del>#### Client
<add># EXAMPLES
<ide> For specific client examples please see the man page for the specific Docker
<ide> command. For example:
<ide>
<ide><path>man/dockerd.8.md
<ide> For information about how to create an authorization plugin, see [authorization
<ide> plugin](https://docs.docker.com/engine/extend/authorization/) section in the
<ide> Docker extend section of this documentation.
<ide>
<add># RUNTIME EXECUTION OPTIONS
<add>
<add>You can configure the runtime using options specified with the `--exec-opt` flag.
<add>All the flag's options have the `native` prefix. A single `native.cgroupdriver`
<add>option is available.
<add>
<add>The `native.cgroupdriver` option specifies the management of the container's
<add>cgroups. You can only specify `cgroupfs` or `systemd`. If you specify
<add>`systemd` and it is not available, the system errors out. If you omit the
<add>`native.cgroupdriver` option,` cgroupfs` is used.
<add>
<add>This example sets the `cgroupdriver` to `systemd`:
<add>
<add>```bash
<add>$ sudo dockerd --exec-opt native.cgroupdriver=systemd
<add>```
<add>
<add>Setting this option applies to all containers the daemon launches.
<ide>
<ide> # HISTORY
<ide> Sept 2015, Originally compiled by Shishir Mahajan <[email protected]> | 2 |
Text | Text | translate threejs lights to zh-cn | d3187f287817d1eeb05904ef762be9e3848e7a6d | <ide><path>threejs/lessons/zh_cn/threejs-lights.md
<add>Title: Three.js 光照
<add>Description: 设置光照
<add>TOC: 光照
<add>
<add>本文是关于 three.js 系列文章的一部分。第一篇文章是 [three.js 基础](threejs-fundamentals.html)。如果你还没看过而且对three.js 还不熟悉,那应该从那里开始,并且了解如何[设置开发环境](threejs-setup.html)。上一篇文章介绍了 three.js 中的 [纹理](threejs-textures.html)。
<add>
<add>接下来我们学习如何在 three.js 中使用各种不同类型的光照。
<add>
<add>在一个基本场景的基础上,我们调整一下相机的设置。将 fov 设置为 45, far 设置为 100,然后移动相机位置到 (0, 10, 20)。
<add>
<add>```js
<add>*const fov = 45;
<add>const aspect = 2; // canvas 的默认宽高 300:150
<add>const near = 0.1;
<add>*const far = 100;
<add>const camera = new THREE.PerspectiveCamera(fov, aspect, near, far);
<add>+camera.position.set(0, 10, 20);
<add>```
<add>
<add>然后我们添加一个 `OrbitControls`。`OrbitControls` 让我们可以围绕某一个点旋转控制相机。`OrbitControls` 是 three.js 的可选模块,所以我们首先需要引入这个模块。
<add>
<add>```js
<add>import * as THREE from './resources/three/r122/build/three.module.js';
<add>+import {OrbitControls} from './resources/threejs/r122/examples/jsm/controls/OrbitControls.js';
<add>```
<add>
<add>然后我们就可以使用了。创建 `OrbitControls` 时传入两个参数,一个是要控制的相机对象,第二个是检测事件的 DOM 元素。
<add>
<add>```js
<add>const controls = new OrbitControls(camera, canvas);
<add>controls.target.set(0, 5, 0);
<add>controls.update();
<add>```
<add>
<add>我们还将 `OrbitControls` 的观察点设置为 (0, 5, 0) 的位置,设置完需要调用一下 `controls.update`,这样才真正更新观察点位置。
<add>
<add>下面我们创建一些东西来打光。首先,创建一个地平面,并用下方展示的 2x2 像素的黑白格图片来作为纹理。
<add>
<add><div class="threejs_center">
<add> <img src="../resources/images/checker.png" class="border" style="
<add> image-rendering: pixelated;
<add> width: 128px;
<add> ">
<add></div>
<add>
<add>首先加载这个纹理,设置重复模式([`wrapS`](Texture.wrapS), [`wrapT`](Texture.wrapT)),采样模式([`magFilter`](Texture.magFilter))以及重复的次数。因为贴图是 2x2 大小,通过设置成平铺模式,并且重复次数是边长的一半,就可以让每个格子正好是1个单位的大小。
<add>
<add>```js
<add>const planeSize = 40;
<add>
<add>const loader = new THREE.TextureLoader();
<add>const texture = loader.load('resources/images/checker.png');
<add>texture.wrapS = THREE.RepeatWrapping;
<add>texture.wrapT = THREE.RepeatWrapping;
<add>texture.magFilter = THREE.NearestFilter;
<add>const repeats = planeSize / 2;
<add>texture.repeat.set(repeats, repeats);
<add>```
<add>
<add>接着我们创建一个平面几何体,一个材质,再用这两个作为参数,创建一个 `Mesh` 对象并且添加到场景中。因为创建的平面默认是在 XY 平面上(竖直平面),我们希望得到一个 XZ 平面(水平平面),所以我们将他旋转 90°。
<add>
<add>```js
<add>const planeGeo = new THREE.PlaneBufferGeometry(planeSize, planeSize);
<add>const planeMat = new THREE.MeshPhongMaterial({
<add> map: texture,
<add> side: THREE.DoubleSide,
<add>});
<add>const mesh = new THREE.Mesh(planeGeo, planeMat);
<add>mesh.rotation.x = Math.PI * -.5;
<add>scene.add(mesh);
<add>```
<add>
<add>接着再添加一个立方体和一个球体,这样我们就有三个物体可以打光。
<add>
<add>```js
<add>{
<add> const cubeSize = 4;
<add> const cubeGeo = new THREE.BoxBufferGeometry(cubeSize, cubeSize, cubeSize);
<add> const cubeMat = new THREE.MeshPhongMaterial({color: '#8AC'});
<add> const mesh = new THREE.Mesh(cubeGeo, cubeMat);
<add> mesh.position.set(cubeSize + 1, cubeSize / 2, 0);
<add> scene.add(mesh);
<add>}
<add>{
<add> const sphereRadius = 3;
<add> const sphereWidthDivisions = 32;
<add> const sphereHeightDivisions = 16;
<add> const sphereGeo = new THREE.SphereBufferGeometry(sphereRadius, sphereWidthDivisions, sphereHeightDivisions);
<add> const sphereMat = new THREE.MeshPhongMaterial({color: '#CA8'});
<add> const mesh = new THREE.Mesh(sphereGeo, sphereMat);
<add> mesh.position.set(-sphereRadius - 1, sphereRadius + 2, 0);
<add> scene.add(mesh);
<add>}
<add>```
<add>
<add>一切准备就绪,我们开始添加光源。
<add>
<add>## 环境光(`AmbientLight`)
<add>
<add>首先创建一个 `AmbientLight`
<add>
<add>```js
<add>const color = 0xFFFFFF;
<add>const intensity = 1;
<add>const light = new THREE.AmbientLight(color, intensity);
<add>scene.add(light);
<add>```
<add>
<add>我们添加一些控制代码,使我们可以动态地改变光照的参数,还是使用 [dat.GUI](https://github.com/dataarts/dat.gui) 来实现。为了可以通过 `dat.GUI` 调节颜色,我们创建一个辅助对象。对象内有一个 `getter` 和 `setter`,当 `dat.GUI` 从对象内获取 `value` 值的时候,触发了 `getter`,会根据创建对象实例时传入的 `object` 和 `prop`,返回一个十六进制色值的字符串,当通过 `dat.GUI` 控制改变这个 `value` 的时候,就触发了 `setter`,会用十六进制的色值字符串作为参数调用 `object.prop.set`。
<add>
<add>以下是 helper 类的代码:
<add>
<add>```js
<add>class ColorGUIHelper {
<add> constructor(object, prop) {
<add> this.object = object;
<add> this.prop = prop;
<add> }
<add> get value() {
<add> return `#${this.object[this.prop].getHexString()}`;
<add> }
<add> set value(hexString) {
<add> this.object[this.prop].set(hexString);
<add> }
<add>}
<add>```
<add>
<add>以及创建 dat.GUI 的代码:
<add>
<add>```js
<add>const gui = new GUI();
<add>gui.addColor(new ColorGUIHelper(light, 'color'), 'value').name('color');
<add>gui.add(light, 'intensity', 0, 2, 0.01);
<add>```
<add>
<add>结果如下所示:
<add>
<add>{{{example url="../threejs-lights-ambient.html" }}}
<add>
<add>可以在场景内点击和拖拽鼠标来改变相机的位置,观察场景。
<add>
<add>可以看到场景内的物体看起来没有立体感。环境光 (`AmbientLight`)只是简单地将材质的颜色与光照颜色进行叠加(PhotoShop 里的正片叠底模式),再乘以光照强度。
<add>
<add> // 这里的颜色计算是 RBG 通道上的值分别对应相乘
<add> // 例: rgb(0.64,0.64,0.64) = rgb(0.8,0.8,0.8) * rgb(0.8,0.8,0.8) * 1
<add> color = materialColor * light.color * light.intensity;
<add>
<add>这就是环境光,它没有方向,无法产生阴影,场景内任何一点受到的光照强度都是相同的,除了改变场景内所有物体的颜色以外,不会使物体产生明暗的变化,看起来并不像真正意义上的光照。通常的作用是提亮场景,让暗部不要太暗。
<add>
<add>## 半球光(`HemisphereLight`)
<add>
<add>接下来介绍半球光(`HemisphereLight`)。半球光(`HemisphereLight`)的颜色是从天空到地面两个颜色之间的渐变,与物体材质的颜色作叠加后得到最终的颜色效果。一个点受到的光照颜色是由所在平面的朝向(法向量)决定的 —— 面向正上方就受到天空的光照颜色,面向正下方就受到地面的光照颜色,其他角度则是两个颜色渐变区间的颜色。
<add>
<add>下面是修改后的代码:
<add>
<add>```js
<add>-const color = 0xFFFFFF;
<add>+const skyColor = 0xB1E1FF; // light blue
<add>+const groundColor = 0xB97A20; // brownish orange
<add>const intensity = 1;
<add>-const light = new THREE.AmbientLight(color, intensity);
<add>+const light = new THREE.HemisphereLight(skyColor, groundColor, intensity);
<add>scene.add(light);
<add>```
<add>
<add>同时修改一下 `dat.GUI` 部分,使得可以控制两种颜色:
<add>
<add>```js
<add>const gui = new GUI();
<add>-gui.addColor(new ColorGUIHelper(light, 'color'), 'value').name('color');
<add>+gui.addColor(new ColorGUIHelper(light, 'color'), 'value').name('skyColor');
<add>+gui.addColor(new ColorGUIHelper(light, 'groundColor'), 'value').name('groundColor');
<add>gui.add(light, 'intensity', 0, 2, 0.01);
<add>```
<add>
<add>结果如下:
<add>
<add>{{{example url="../threejs-lights-hemisphere.html" }}}
<add>
<add>场景基本上也没有太大的立体感。半球光 (`HemisphereLight`) 与其他类型光照结合使用,可以很好地表现天空和地面颜色照射到物体上时的效果。所以最好的使用场景就是与其他光照结合使用,或者作为环境光(`AmbientLight`)的一种替代方案。
<add>
<add>## 方向光(`DirectionalLight`)
<add>
<add>下面介绍方向光(`DirectionalLight`)。
<add>方向光(`DirectionalLight`)常常用来表现太阳光照的效果。
<add>
<add>```js
<add>const color = 0xFFFFFF;
<add>const intensity = 1;
<add>const light = new THREE.DirectionalLight(color, intensity);
<add>light.position.set(0, 10, 0);
<add>light.target.position.set(-5, 0, 0);
<add>scene.add(light);
<add>scene.add(light.target);
<add>```
<add>
<add>注意,不仅 `light` ,我们还把 [`light.target`](DirectionalLight.target) 也添加到了场景中。方向光(`DirectionalLight`)的方向是从它的位置照向目标点的位置。
<add>
<add>下面代码是将目标点坐标属性添加到 `dat.GUI`,使得我们可以控制目标位置
<add>
<add>```js
<add>const gui = new GUI();
<add>gui.addColor(new ColorGUIHelper(light, 'color'), 'value').name('color');
<add>gui.add(light, 'intensity', 0, 2, 0.01);
<add>gui.add(light.target.position, 'x', -10, 10);
<add>gui.add(light.target.position, 'z', -10, 10);
<add>gui.add(light.target.position, 'y', 0, 10);
<add>```
<add>
<add>{{{example url="../threejs-lights-directional.html" }}}
<add>
<add>目前有点难以观察。Three.js 提供了一些辅助对象,添加到场景中之后就可以显示出场景中的不可见对象(例如光照、相机等)。在这里我们使用 `DirectionalLightHelper`,它会绘制一个方形的小平面代表方向光的位置,一条连接光源与目标点的直线,代表了光的方向。创建对象时,传入光源对象作为参数,然后添加到场景中,就可以呈现。
<add>
<add>```js
<add>const helper = new THREE.DirectionalLightHelper(light);
<add>scene.add(helper);
<add>```
<add>
<add>我们顺便实现一下对光源位置和目标点位置的控制逻辑。我们创建一个辅助函数,使得可以通过 `dat.GUI` 改变传入的 `Vector3` 类型对象的 `x`,`y`,和 `z` 的值。
<add>
<add>```js
<add>function makeXYZGUI(gui, vector3, name, onChangeFn) {
<add> const folder = gui.addFolder(name);
<add> folder.add(vector3, 'x', -10, 10).onChange(onChangeFn);
<add> folder.add(vector3, 'y', 0, 10).onChange(onChangeFn);
<add> folder.add(vector3, 'z', -10, 10).onChange(onChangeFn);
<add> folder.open();
<add>}
<add>```
<add>
<add>注意,当辅助对象所表示的不可见对象有所改变的时候,我们必须调用辅助对象的 `update` 方法来更新辅助对象本身的状态。因此我们传入一个 `onChangeFn` 函数,每当 `dat.GUI` 改变了某个值的时候,就会被调用。
<add>
<add>应用到光照位置与目标点位置的控制,就如下所示:
<add>
<add>```js
<add>+function updateLight() {
<add>+ light.target.updateMatrixWorld();
<add>+ helper.update();
<add>+}
<add>+updateLight();
<add>
<add>const gui = new GUI();
<add>gui.addColor(new ColorGUIHelper(light, 'color'), 'value').name('color');
<add>gui.add(light, 'intensity', 0, 2, 0.01);
<add>
<add>+makeXYZGUI(gui, light.position, 'position', updateLight);
<add>+makeXYZGUI(gui, light.target.position, 'target', updateLight);
<add>```
<add>
<add>现在我们可以控制光源以及目标点位置了。
<add>
<add>{{{example url="../threejs-lights-directional-w-helper.html" }}}
<add>
<add>旋转相机可以看得更清楚。方形的小平面代表了一个方向光(`DirectionalLight`),方向光表示的是来自一个方向上的光,并不是从某个点发射出来的,而是从一个无限大的平面内,发射出全部相互平行的光线。
<add>
<add>## 点光源(`PointLight`)
<add>
<add>点光源(`PointLight`)表示的是从一个点朝各个方向发射出光线的一种光照效果。我们修改一下代码:
<add>
<add>```js
<add>const color = 0xFFFFFF;
<add>const intensity = 1;
<add>-const light = new THREE.DirectionalLight(color, intensity);
<add>+const light = new THREE.PointLight(color, intensity);
<add>light.position.set(0, 10, 0);
<add>-light.target.position.set(-5, 0, 0);
<add>scene.add(light);
<add>-scene.add(light.target);
<add>```
<add>
<add>同时添加一个 `PointLightHelper`
<add>
<add>```js
<add>-const helper = new THREE.DirectionalLightHelper(light);
<add>+const helper = new THREE.PointLightHelper(light);
<add>scene.add(helper);
<add>```
<add>
<add>因为点光源没有 `target` 属性,所以 `onChange` 函数可以简化。
<add>
<add>```js
<add>function updateLight() {
<add>- light.target.updateMatrixWorld();
<add> helper.update();
<add>}
<add>-updateLight();
<add>```
<add>
<add>`PointLightHelper` 不是一个点,而是在光源的位置绘制了一个小小的线框宝石体来代表点光源。也可以使用其他形状来表示点光源,只要给点光源添加一个自定义的 `Mesh` 子节点即可。
<add>
<add>点光源(`PointLight`)有额外的一个范围([`distance`](PointLight.distance))属性。
<add>如果 `distance` 设为 0,则光线可以照射到无限远处。如果大于 0,则只可以照射到指定的范围,光照强度在这个过程中逐渐衰减,在光源位置时,`intensity` 是设定的大小,在距离光源 `distance` 位置的时候,`intensity` 为 0。
<add>
<add>下面是添加对 distance 参数控制的代码:
<add>
<add>```js
<add>const gui = new GUI();
<add>gui.addColor(new ColorGUIHelper(light, 'color'), 'value').name('color');
<add>gui.add(light, 'intensity', 0, 2, 0.01);
<add>+gui.add(light, 'distance', 0, 40).onChange(updateLight);
<add>
<add>makeXYZGUI(gui, light.position, 'position', updateLight);
<add>-makeXYZGUI(gui, light.target.position, 'target', updateLight);
<add>```
<add>
<add>效果如下:
<add>
<add>{{{example url="../threejs-lights-point.html" }}}
<add>
<add>注意 `distance` > 0 时光照强度的衰减现象。
<add>
<add>## 聚光灯(`SpotLight`)
<add>
<add>聚光灯可以看成是一个点光源被一个圆锥体限制住了光照的范围。实际上有两个圆锥,内圆锥和外圆锥。光照强度在两个锥体之间从设定的强度递减到 0(具体可以看下方 [`penumbra`](SpotLight.penumbra) 参数)。
<add>
<add>聚光灯(`SpotLight`)类似方向光(`DirectionalLight`)一样需要一个目标点,光源的位置是圆锥的顶点,目标点处于圆锥的中轴线上。
<add>
<add>修改上面 `DirectionalLight` 的代码如下:
<add>
<add>```js
<add>const color = 0xFFFFFF;
<add>const intensity = 1;
<add>-const light = new THREE.DirectionalLight(color, intensity);
<add>+const light = new THREE.SpotLight(color, intensity);
<add>scene.add(light);
<add>scene.add(light.target);
<add>
<add>-const helper = new THREE.DirectionalLightHelper(light);
<add>+const helper = new THREE.SpotLightHelper(light);
<add>scene.add(helper);
<add>```
<add>
<add>聚光灯的圆锥顶部角度大小通过 [`angle`](SpotLight.angle) 属性设置,以弧度作单位。所以我们用介绍 [纹理](threejs-textures.html) 时用到的 `DegRadHelper` 来控制。
<add>
<add>```js
<add>gui.add(new DegRadHelper(light, 'angle'), 'value', 0, 90).name('angle').onChange(updateLight);
<add>```
<add>
<add>内圆锥是通过设置 [`penumbra`](SpotLight.penumbra) 属性来定义的,属性值代表了内圆锥相对外圆锥大小变化的百分比。当 `penumbra` 为 0 时,内圆锥大小与外圆锥大小一致;当 `penumbra` 为 1 时,内圆锥大小为 0,光照强度从中轴线就开始往外递减;当 `penumbra` 为 0.5 时,光照强度从外圆锥半径的中点处开始往外递减。
<add>
<add>```js
<add>gui.add(light, 'penumbra', 0, 1, 0.01);
<add>```
<add>
<add>{{{example url="../threejs-lights-spot-w-helper.html" }}}
<add>
<add>注意观察,当 `penumbra` 为默认值 0 的时候,聚光灯会有非常清晰的边缘,而当把 `penumbra` 向 1 调节的时候,边缘会开始模糊。
<add>
<add>示例中有点难以看到聚光灯的整个圆锥体,因为圆锥底部在平面下方。将 `distance` 减小到 5 左右,就可以看到圆锥的底部。
<add>
<add>## 矩形区域光(`RectAreaLight`)
<add>
<add>Three.js 中还有一种类型的光照,矩形区域光(`RectAreaLight`), 顾名思义,表示一个矩形区域的发射出来的光照,例如长条的日光灯或者天花板上磨砂玻璃透进来的自然光。
<add>
<add>`RectAreaLight` 只能影响 `MeshStandardMaterial` 和 `MeshPhysicalMaterial`,所以我们把所有的材质都改为 `MeshStandardMaterial`。
<add>
<add>```js
<add> ...
<add>
<add> const planeGeo = new THREE.PlaneBufferGeometry(planeSize, planeSize);
<add>- const planeMat = new THREE.MeshPhongMaterial({
<add>+ const planeMat = new THREE.MeshStandardMaterial({
<add> map: texture,
<add> side: THREE.DoubleSide,
<add> });
<add> const mesh = new THREE.Mesh(planeGeo, planeMat);
<add> mesh.rotation.x = Math.PI * -.5;
<add> scene.add(mesh);
<add>}
<add>{
<add> const cubeSize = 4;
<add> const cubeGeo = new THREE.BoxBufferGeometry(cubeSize, cubeSize, cubeSize);
<add>- const cubeMat = new THREE.MeshPhongMaterial({color: '#8AC'});
<add>+ const cubeMat = new THREE.MeshStandardMaterial({color: '#8AC'});
<add> const mesh = new THREE.Mesh(cubeGeo, cubeMat);
<add> mesh.position.set(cubeSize + 1, cubeSize / 2, 0);
<add> scene.add(mesh);
<add>}
<add>{
<add> const sphereRadius = 3;
<add> const sphereWidthDivisions = 32;
<add> const sphereHeightDivisions = 16;
<add> const sphereGeo = new THREE.SphereBufferGeometry(sphereRadius, sphereWidthDivisions, sphereHeightDivisions);
<add>- const sphereMat = new THREE.MeshPhongMaterial({color: '#CA8'});
<add>+ const sphereMat = new THREE.MeshStandardMaterial({color: '#CA8'});
<add> const mesh = new THREE.Mesh(sphereGeo, sphereMat);
<add> mesh.position.set(-sphereRadius - 1, sphereRadius + 2, 0);
<add> scene.add(mesh);
<add>}
<add>```
<add>
<add>为了使用 `RectAreaLight`,我们需要引入 three.js 的`RectAreaLightUniformsLib` 模块,同时使用 `RectAreaLightHelper` 来辅助查看灯光对象。
<add>
<add>```js
<add>import * as THREE from './resources/three/r122/build/three.module.js';
<add>+import {RectAreaLightUniformsLib} from './resources/threejs/r122/examples/jsm/lights/RectAreaLightUniformsLib.js';
<add>+import {RectAreaLightHelper} from './resources/threejs/r122/examples/jsm/helpers/RectAreaLightHelper.js';
<add>```
<add>
<add>我们需要先调用 `RectAreaLightUniformsLib.init`
<add>
<add>```js
<add>function main() {
<add> const canvas = document.querySelector('#c');
<add> const renderer = new THREE.WebGLRenderer({canvas});
<add>+ RectAreaLightUniformsLib.init();
<add>```
<add>
<add>如果忘了引入和使用 `RectAreaLightUniformsLib`,光照还是可以显示,但是会看起来很奇怪(译者注:在示例的简单场景中没有发现区别),所以要确保有使用。
<add>
<add>然后我们可以创建光照了
<add>
<add>```js
<add>const color = 0xFFFFFF;
<add>*const intensity = 5;
<add>+const width = 12;
<add>+const height = 4;
<add>*const light = new THREE.RectAreaLight(color, intensity, width, height);
<add>light.position.set(0, 10, 0);
<add>+light.rotation.x = THREE.MathUtils.degToRad(-90);
<add>scene.add(light);
<add>
<add>*const helper = new RectAreaLightHelper(light);
<add>*light.add(helper);
<add>```
<add>
<add>需要注意的是,与方向光(`DirectionalLight`)和聚光灯(`SpotLight`)不同,矩形光不是使用目标点(`target`),而是使用自身的旋转角度来确定光照方向。另外,矩形光的辅助对象(`RectAreaLightHelper`)应该添加为光照的子节点,而不是添加为场景的子节点。
<add>
<add>同时我们修改一下 GUI 代码,使我们可以旋转光源,调整 `width` 和 `height` 属性。
<add>
<add>```js
<add>const gui = new GUI();
<add>gui.addColor(new ColorGUIHelper(light, 'color'), 'value').name('color');
<add>gui.add(light, 'intensity', 0, 10, 0.01);
<add>gui.add(light, 'width', 0, 20).onChange(updateLight);
<add>gui.add(light, 'height', 0, 20).onChange(updateLight);
<add>gui.add(new DegRadHelper(light.rotation, 'x'), 'value', -180, 180).name('x rotation').onChange(updateLight);
<add>gui.add(new DegRadHelper(light.rotation, 'y'), 'value', -180, 180).name('y rotation').onChange(updateLight);
<add>gui.add(new DegRadHelper(light.rotation, 'z'), 'value', -180, 180).name('z rotation').onChange(updateLight);
<add>
<add>makeXYZGUI(gui, light.position, 'position', updateLight);
<add>```
<add>
<add>场景如下所示:
<add>
<add>{{{example url="../threejs-lights-rectarea.html" }}}
<add>
<add>关于光照,我们尚未提及的是 `WebGLRenderer` 中有一个设置项 `physicallyCorrectLights`。这个设置会影响(随着离光源的距离增加)光照如何减弱。这个设置会影响点光源(`PointLight`)和聚光灯(`SpotLight`),矩形区域光(`RectAreaLight`)会自动应用这个特性。
<add>
<add>在设置光照时,基本思路是不要设置 `distance` 来表现光照的衰减,也不要设置 `intensity`。而是设置光照的 [`power`](PointLight.power) 属性,以流明为单位,three.js 会进行物理计算,从而表现出接近真实的光照效果。在这种情况下 three.js 参与计算的长度单位是米,一个 60瓦 的灯泡大概是 800 流明强度。并且光源有一个 [`decay`](PointLight.decay) 属性,为了模拟真实效果,应该被设置为 `2`。
<add>
<add>下面让我们测试看看。
<add>
<add>首先开启 `physicallyCorrectLights` 模式
<add>
<add>```js
<add>const renderer = new THREE.WebGLRenderer({canvas});
<add>+renderer.physicallyCorrectLights = true;
<add>```
<add>
<add>然后我们设置光照的参数,`power` 设置为 800 流明,`decay` 设置为 2,`distance` 设置为 `Infinity`。
<add>
<add>```js
<add>const color = 0xFFFFFF;
<add>const intensity = 1;
<add>const light = new THREE.PointLight(color, intensity);
<add>light.power = 800;
<add>light.decay = 2;
<add>light.distance = Infinity;
<add>```
<add>
<add>并且添加 gui 控制 `power` 和 `decay`
<add>
<add>```js
<add>const gui = new GUI();
<add>gui.addColor(new ColorGUIHelper(light, 'color'), 'value').name('color');
<add>gui.add(light, 'decay', 0, 4, 0.01);
<add>gui.add(light, 'power', 0, 2000);
<add>```
<add>
<add>{{{example url="../threejs-lights-point-physically-correct.html" }}}
<add>
<add>需要注意,每添加一个光源到场景中,都会降低 three.js 渲染场景的速度,所以应该尽量使用最少的资源来实现想要的效果。
<add>
<add>接下来我们学习 three.js 中的 [相机](threejs-cameras.html)。
<add>
<add><canvas id="c"></canvas>
<add><script type="module" src="resources/threejs-lights.js"></script> | 1 |
PHP | PHP | fix mysql build | 62cb352e9635694917ca7cfccccf18fd57428094 | <ide><path>src/TestSuite/Fixture/FixtureManager.php
<ide> public function unload($test)
<ide> }
<ide> $truncate = function ($db, $fixtures) {
<ide> $configName = $db->configName();
<add>
<add> foreach ($fixtures as $name => $fixture) {
<add> if ($this->isFixtureSetup($configName, $fixture)) {
<add> $fixture->dropConstraints($db);
<add> }
<add> }
<add>
<ide> foreach ($fixtures as $fixture) {
<ide> if ($this->isFixtureSetup($configName, $fixture)) {
<ide> $fixture->truncate($db);
<ide><path>tests/TestCase/TestSuite/FixtureManagerTest.php
<ide> public function testFixturizeCoreConstraint()
<ide> $this->assertEquals($expectedConstraint, $schema->constraint('tag_id_fk'));
<ide>
<ide> $this->manager->unload($test);
<del> $this->manager->shutDown($test);
<ide> }
<ide>
<ide> /** | 2 |
Javascript | Javascript | avoid repeated calls to `normalizespawnarguments` | c030f88fcf9265bfc3ff98375bcbbbd7aa6e27d2 | <ide><path>lib/child_process.js
<ide> const {
<ide> ArrayPrototypeSort,
<ide> ArrayPrototypeSplice,
<ide> ArrayPrototypeUnshift,
<add> ArrayPrototypePushApply,
<ide> NumberIsInteger,
<ide> ObjectAssign,
<ide> ObjectDefineProperty,
<ide> ObjectDefineProperty(exec, promisify.custom, {
<ide> value: customPromiseExecFunction(exec)
<ide> });
<ide>
<add>function normalizeExecFileArgs(file, args, options, callback) {
<add> if (ArrayIsArray(args)) {
<add> args = ArrayPrototypeSlice(args);
<add> } else if (args != null && typeof args === 'object') {
<add> callback = options;
<add> options = args;
<add> args = null;
<add> } else if (typeof args === 'function') {
<add> callback = args;
<add> options = null;
<add> args = null;
<add> }
<add>
<add> if (args == null) {
<add> args = [];
<add> }
<add>
<add> if (typeof options === 'function') {
<add> callback = options;
<add> } else if (options != null) {
<add> validateObject(options, 'options');
<add> }
<add>
<add> if (options == null) {
<add> options = kEmptyObject;
<add> }
<add>
<add> if (callback != null) {
<add> validateFunction(callback, 'callback');
<add> }
<add>
<add> // Validate argv0, if present.
<add> if (options.argv0 != null) {
<add> validateString(options.argv0, 'options.argv0');
<add> }
<add>
<add> return { file, args, options, callback };
<add>}
<add>
<ide> /**
<ide> * Spawns the specified file as a shell.
<ide> * @param {string} file
<ide> ObjectDefineProperty(exec, promisify.custom, {
<ide> * ) => any} [callback]
<ide> * @returns {ChildProcess}
<ide> */
<del>function execFile(file, args = [], options, callback) {
<del> if (args != null && typeof args === 'object' && !ArrayIsArray(args)) {
<del> callback = options;
<del> options = args;
<del> args = null;
<del> } else if (typeof args === 'function') {
<del> callback = args;
<del> options = null;
<del> args = null;
<del> }
<del>
<del> if (typeof options === 'function') {
<del> callback = options;
<del> options = null;
<del> } else if (options != null) {
<del> validateObject(options, 'options');
<del> }
<del>
<del> if (callback != null) {
<del> validateFunction(callback, 'callback');
<del> }
<add>function execFile(file, args, options, callback) {
<add> ({ file, args, options, callback } = normalizeExecFileArgs(file, args, options, callback));
<ide>
<ide> options = {
<ide> encoding: 'utf8',
<ide> function checkExecSyncError(ret, args, cmd) {
<ide>
<ide> /**
<ide> * Spawns a file as a shell synchronously.
<del> * @param {string} command
<add> * @param {string} file
<ide> * @param {string[]} [args]
<ide> * @param {{
<ide> * cwd?: string;
<ide> function checkExecSyncError(ret, args, cmd) {
<ide> * }} [options]
<ide> * @returns {Buffer | string}
<ide> */
<del>function execFileSync(command, args, options) {
<del> options = normalizeSpawnArguments(command, args, options);
<add>function execFileSync(file, args, options) {
<add> ({ file, args, options } = normalizeExecFileArgs(file, args, options));
<ide>
<ide> const inheritStderr = !options.stdio;
<del> const ret = spawnSync(options.file,
<del> ArrayPrototypeSlice(options.args, 1), options);
<add> const ret = spawnSync(file, args, options);
<ide>
<ide> if (inheritStderr && ret.stderr)
<ide> process.stderr.write(ret.stderr);
<ide>
<del> const err = checkExecSyncError(ret, options.args, undefined);
<add> const errArgs = [options.argv0 || file];
<add> ArrayPrototypePushApply(errArgs, args);
<add> const err = checkExecSyncError(ret, errArgs);
<ide>
<ide> if (err)
<ide> throw err;
<ide><path>test/parallel/test-child-process-execfile.js
<ide>
<ide> const common = require('../common');
<ide> const assert = require('assert');
<del>const execFile = require('child_process').execFile;
<add>const { execFile, execFileSync } = require('child_process');
<ide> const { getEventListeners } = require('events');
<ide> const { getSystemErrorName } = require('util');
<ide> const fixtures = require('../common/fixtures');
<add>const os = require('os');
<ide>
<ide> const fixture = fixtures.path('exit.js');
<ide> const echoFixture = fixtures.path('echo.js');
<ide> const execOpts = { encoding: 'utf8', shell: true };
<ide> });
<ide> execFile(process.execPath, [fixture, 0], { signal }, callback);
<ide> }
<add>
<add>// Verify the execFile() stdout is the same as execFileSync().
<add>{
<add> const file = 'echo';
<add> const args = ['foo', 'bar'];
<add>
<add> // Test with and without `{ shell: true }`
<add> [
<add> // Skipping shell-less test on Windows because its echo command is a shell built-in command.
<add> ...(common.isWindows ? [] : [{ encoding: 'utf8' }]),
<add> { shell: true, encoding: 'utf8' },
<add> ].forEach((options) => {
<add> const execFileSyncStdout = execFileSync(file, args, options);
<add> assert.strictEqual(execFileSyncStdout, `foo bar${os.EOL}`);
<add>
<add> execFile(file, args, options, common.mustCall((_, stdout) => {
<add> assert.strictEqual(stdout, execFileSyncStdout);
<add> }));
<add> });
<add>} | 2 |
Ruby | Ruby | add root dirname as a escape value too | 601af55b43bc96627359eca06eeec4bf9881c890 | <ide><path>Library/Homebrew/download_strategy.rb
<ide> def ext
<ide> url_pathname = Pathname.new(@url)
<ide> until ext = url_pathname.extname[/[^?]+/]
<ide> url_pathname = url_pathname.dirname
<del> return if url_pathname.to_s == "."
<add> return if url_pathname.to_s == "." || url_pathname.to_s == "/"
<ide> end
<ide> ext
<ide> end | 1 |
Text | Text | remove stale badge from readme | bcd9c2bc3ddaa04f89f550681ca9c1ec5efc4328 | <ide><path>README.md
<ide> [jQuery](https://jquery.com/) — New Wave JavaScript
<ide> ==================================================
<ide>
<del>[](https://app.fossa.io/projects/git%2Bgithub.com%2Fjquery%2Fjquery?ref=badge_shield)
<del>
<ide> [](https://gitter.im/jquery/jquery?utm_source=badge&utm_medium=badge&utm_campaign=pr-badge)
<ide>
<ide> Contribution Guides | 1 |
Text | Text | update chinese translation of debugging | 2db889099dc6e0356381f6c422fe121935d98be5 | <ide><path>curriculum/challenges/chinese/02-javascript-algorithms-and-data-structures/debugging/catch-arguments-passed-in-the-wrong-order-when-calling-a-function.chinese.md
<ide> id: 587d7b85367417b2b2512b3a
<ide> title: Catch Arguments Passed in the Wrong Order When Calling a Function
<ide> challengeType: 1
<del>videoUrl: ''
<del>localeTitle: 调用函数时捕获以错误顺序传递的参数
<add>forumTopicId: 301184
<add>localeTitle: 调用函数时,捕获以错误顺序传递的参数
<ide> ---
<ide>
<ide> ## Description
<del><section id="description">继续讨论调用函数,需要注意的下一个错误是函数的参数是以错误的顺序提供的。如果参数是不同的类型,例如期望数组和整数的函数,则可能会引发运行时错误。如果参数是相同的类型(例如,所有整数),那么代码的逻辑将没有意义。确保以正确的顺序提供所有必需的参数以避免这些问题。 </section>
<add><section id='description'>
<add>继续讨论调用函数,需要注意的下一个 bug 是函数的参数传递顺序错误。 如果参数分别是不同的类型,例如接受数组和整数两个参数的函数,参数顺序传错就可能会引发运行时错误。对于接受相同类型参数的函数,传错参数也会导致逻辑错误或运行结果错误。确保以正确的顺序提供所有必需的参数以避免这些问题。
<add></section>
<ide>
<ide> ## Instructions
<del><section id="instructions">函数<code>raiseToPower</code>将基数提升为指数。不幸的是,它没有被正确调用 - 修复代码,因此<code>power</code>值是预期的8。 </section>
<add><section id='instructions'>
<add>函数<code>raiseToPower</code>返回基数 (base) 的指数 (exponent) 次幂。不幸的是,它没有被正确调用 ———— 修改代码,使<code>power</code>的值为 8。
<add></section>
<ide>
<ide> ## Tests
<ide> <section id='tests'>
<ide>
<ide> ```yml
<ide> tests:
<del> - text: 你的代码应该固定可变<code>power</code>因此它等于2提升到3功率,而不是3增加到2功率。
<add> - text: 你应修复变量<code>power</code>,使其等于 2 的 3 次方,而不是 3 的 2 次方。
<ide> testString: assert(power == 8);
<del> - text: 您的代码应使用<code>raiseToPower</code>函数调用的正确参数顺序。
<add> - text: 你调用<code>raiseToPower</code>函数时,传递参数的顺序应正确。
<ide> testString: assert(code.match(/raiseToPower\(\s*?base\s*?,\s*?exp\s*?\);/g));
<ide>
<ide> ```
<ide> let base = 2;
<ide> let exp = 3;
<ide> let power = raiseToPower(exp, base);
<ide> console.log(power);
<del>
<ide> ```
<ide>
<ide> </div>
<ide> console.log(power);
<ide> <section id='solution'>
<ide>
<ide> ```js
<del>// solution required
<add>function raiseToPower(b, e) {
<add> return Math.pow(b, e);
<add>}
<add>
<add>let base = 2;
<add>let exp = 3;
<add>let power = raiseToPower(base, exp);
<add>console.log(power);
<ide> ```
<ide>
<del>/section>
<add></section>
<ide><path>curriculum/challenges/chinese/02-javascript-algorithms-and-data-structures/debugging/catch-missing-open-and-closing-parenthesis-after-a-function-call.chinese.md
<ide> id: 587d7b85367417b2b2512b39
<ide> title: Catch Missing Open and Closing Parenthesis After a Function Call
<ide> challengeType: 1
<del>videoUrl: ''
<del>localeTitle: 在函数调用后捕获缺失的打开和关闭括号
<add>forumTopicId: 301185
<add>localeTitle: 捕捉函数调用后缺少的左括号和右括号
<ide> ---
<ide>
<ide> ## Description
<del><section id="description">当函数或方法不接受任何参数时,您可能忘记在调用它时包括(空)开括号和右括号。通常,函数调用的结果会保存在变量中,以供代码中的其他用途使用。可以通过将变量值(或其类型)记录到控制台并看到一个设置为函数引用而不是函数返回的期望值来检测此错误。以下示例中的变量不同: <blockquote> function myFunction(){ <br>回归“你摇滚!”; <br> } <br> let varOne = myFunction; //设置为等于函数<br> let varTwo = myFunction(); //设置为等于字符串“You rock!” </blockquote></section>
<add><section id='description'>
<add>当函数或方法不接受任何参数时,你可能忘记在调用它时加上空的左括号和右括号。通常,函数调用的结果会保存在变量中,供其他代码使用。可以通过将变量值(或其类型)打印到控制台,查看输出究竟是一个函数引用还是函数调用的返回值来检测这类错误。
<add>下面示例中的两个变量是不同的:
<add>
<add>```js
<add>function myFunction() {
<add> return "You rock!";
<add>}
<add>let varOne = myFunction; // set to equal a function
<add>let varTwo = myFunction(); // set to equal the string "You rock!"
<add>```
<add>
<add></section>
<ide>
<ide> ## Instructions
<del><section id="instructions">修复代码,使变量<code>result</code>设置为调用函数<code>getNine</code>返回的值。 </section>
<add><section id='instructions'>
<add>修复代码,把调用函数<code>getNine</code>的返回值赋给变量<code>result</code>。
<add></section>
<ide>
<ide> ## Tests
<ide> <section id='tests'>
<ide>
<ide> ```yml
<ide> tests:
<del> - text: 您的代码应修复变量<code>result</code>以便将其设置为函数<code>getNine</code>返回的数字。
<add> - text: 你应该修复变量<code>result</code>使其为函数<code>getNine</code>的返回值。
<ide> testString: assert(result == 9);
<del> - text: 您的代码应该调用<code>getNine</code>函数。
<add> - text: 你应该调用<code>getNine</code>函数。
<ide> testString: assert(code.match(/getNine\(\)/g).length == 2);
<ide>
<ide> ```
<ide> function getNine() {
<ide>
<ide> let result = getNine;
<ide> console.log(result);
<del>
<ide> ```
<ide>
<ide> </div>
<ide> console.log(result);
<ide> <section id='solution'>
<ide>
<ide> ```js
<del>// solution required
<add>function getNine() {
<add> let x = 6;
<add> let y = 3;
<add> return x + y;
<add>}
<add>
<add>let result = getNine();
<add>console.log(result);
<ide> ```
<ide>
<del>/section>
<add></section>
<add>
<ide><path>curriculum/challenges/chinese/02-javascript-algorithms-and-data-structures/debugging/catch-misspelled-variable-and-function-names.chinese.md
<ide> id: 587d7b84367417b2b2512b35
<ide> title: Catch Misspelled Variable and Function Names
<ide> challengeType: 1
<del>videoUrl: ''
<del>localeTitle: 捕获拼错的变量和函数名称
<add>forumTopicId: 301186
<add>localeTitle: 捕获拼错的变量名和函数名
<ide> ---
<ide>
<ide> ## Description
<del><section id="description"> <code>console.log()</code>和<code>typeof</code>方法是检查中间值和程序输出类型的两种主要方法。现在是时候进入错误所采用的常见形式了。快速打字机可以同意的一个语法级问题是简单的拼写错误。变量或函数名称中的转置,丢失或错误大写字符将使浏览器查找不存在的对象 - 并以引用错误的形式进行抱怨。 JavaScript变量和函数名称区分大小写。 </section>
<add><section id='description'>
<add><code>console.log()</code>和<code>typeof</code>方法是检查中间值和程序输出类型的两种主要方法。 现在是时候了解一下 bug 出现的常见的情形。一个语法级别的问题是打字太快带来的低级拼写错误。
<add>变量或函数名的错写、漏写或大小写弄混都会让浏览器尝试查找并不存在的东西,并报出“引用错误”。JavaScript 变量和函数名称区分大小写。
<add></section>
<ide>
<ide> ## Instructions
<del><section id="instructions">修复代码中的两个拼写错误,以便<code>netWorkingCapital</code>计算有效。 </section>
<add><section id='instructions'>
<add>修复代码中的两个拼写错误,以便<code>netWorkingCapital</code>计算有效。
<add></section>
<ide>
<ide> ## Tests
<ide> <section id='tests'>
<ide>
<ide> ```yml
<ide> tests:
<del> - text: 检查netWorkingCapital计算中使用的两个变量的拼写,控制台输出应显示“净营运资金为:2”。
<add> - text: '检查计算 netWorkingCapital 值时使用的两个变量的拼写是否正确,控制台应该输出 "Net working capital is: 2"。'
<ide> testString: 'assert(netWorkingCapital === 2);'
<ide> - text: 代码中不应存在拼写错误的变量。
<ide> testString: assert(!code.match(/recievables/g));
<del> - text: <code>receivables</code>在代码中声明并正确使用应<code>receivables</code>变量。
<add> - text: 应在代码中声明并正确使用<code>receivables</code>变量。
<ide> testString: assert(code.match(/receivables/g).length == 2);
<ide> - text: 代码中不应存在拼写错误的变量。
<ide> testString: assert(!code.match(/payable;/g));
<del> - text: 应在组织中声明并正确使用<code>payables</code>变量。
<add> - text: 应在代码中声明并正确使用<code>payables</code>变量。
<ide> testString: assert(code.match(/payables/g).length == 2);
<ide>
<ide> ```
<ide> let receivables = 10;
<ide> let payables = 8;
<ide> let netWorkingCapital = recievables - payable;
<ide> console.log(`Net working capital is: ${netWorkingCapital}`);
<del>
<ide> ```
<ide>
<ide> </div>
<ide> console.log(`Net working capital is: ${netWorkingCapital}`);
<ide> <section id='solution'>
<ide>
<ide> ```js
<del>// solution required
<add>let receivables = 10;
<add>let payables = 8;
<add>let netWorkingCapital = receivables - payables;
<add>console.log(`Net working capital is: ${netWorkingCapital}`);
<ide> ```
<ide>
<del>/section>
<add></section>
<ide><path>curriculum/challenges/chinese/02-javascript-algorithms-and-data-structures/debugging/catch-mixed-usage-of-single-and-double-quotes.chinese.md
<ide> id: 587d7b84367417b2b2512b37
<ide> title: Catch Mixed Usage of Single and Double Quotes
<ide> challengeType: 1
<del>videoUrl: ''
<del>localeTitle: 抓住单引号和双引号的混合使用
<add>forumTopicId: 301188
<add>localeTitle: 捕捉单引号和双引号的混合用法
<ide> ---
<ide>
<ide> ## Description
<del><section id="description"> JavaScript允许使用单个(“)和双(”“)引号来声明一个字符串。决定使用哪一个通常归结为个人偏好,但有一些例外。当字符串有收缩或另一个时,有两个选择很好引号中的文本片段。请注意,不要过早关闭字符串,这会导致语法错误。以下是混合引号的一些示例: <blockquote> //这些是正确的: <br> const grouchoContraction =“我度过了一个美好的夜晚,但事实并非如此。”; <br> const quoteInString =“Groucho Marx曾经说过'引用我的话说我被误引了'。”; <br> //这是不正确的: <br> const uhOhGroucho ='我度过了一个美妙的夜晚,但这不是它。'; </blockquote>当然,只使用一种报价样式是可以的。您可以使用反斜杠(\)转义字符来转义字符串中的引号: <blockquote> //正确使用相同的引号: <br> const allSameQuotes ='我度过了一个非常精彩的夜晚,但这不是它。'; </blockquote></section>
<add><section id='description'>
<add>JavaScript允许使用单引号('')和双引号("")声明字符串。决定使用哪一个通常看个人偏好,但有一些例外。
<add>如果字符串中有缩写或存在一段带引号的文本,你就会明白为什么 JavaScript 允许两种引号了。请注意,不要提前用引号结束字符串,这会导致语法错误。
<add>下面是混合使用引号的一些示例:
<add>
<add>```js
<add>// These are correct:
<add>const grouchoContraction = "I've had a perfectly wonderful evening, but this wasn't it.";
<add>const quoteInString = "Groucho Marx once said 'Quote me as saying I was mis-quoted.'";
<add>// This is incorrect:
<add>const uhOhGroucho = 'I've had a perfectly wonderful evening, but this wasn't it.';
<add>```
<add>
<add>当然,只使用一种引号是可以的。你可以使用反斜杠 (<code>\\</code>) 转义字符来转义字符串中的引号:
<add>
<add>```js
<add>// 一种引号的正确使用方式
<add>const allSameQuotes = 'I\'ve had a perfectly wonderful evening, but this wasn\'t it.';
<add>```
<add>
<add></section>
<ide>
<ide> ## Instructions
<del><section id="instructions">修复字符串,使其对<code>href</code>值使用不同的引号,或者转义现有的引号。在整个字符串周围保留双引号。 </section>
<add><section id='instructions'>
<add>修复字符串,对<code>href</code>属性的值使用不同的引号,或者转义现有的引号。注意,整个字符串外面的双引号要保留。
<add></section>
<ide>
<ide> ## Tests
<ide> <section id='tests'>
<ide>
<ide> ```yml
<ide> tests:
<del> - text: '您的代码应该通过更改或转义它们来修复<code>href</code>值“#Home”周围的引号。'
<add> - text: "你应通过更改或转义来修复<code>href</code>的值 '#Home' 周围的引号。"
<ide> testString: assert(code.match(/<a href=\s*?('|\\")#Home\1\s*?>/g));
<del> - text: 您的代码应该在整个字符串周围保留双引号。
<add> - text: 你应该在整个字符串外围保留双引号。
<ide> testString: assert(code.match(/"<p>.*?<\/p>";/g));
<ide>
<ide> ```
<ide> tests:
<ide> ```js
<ide> let innerHtml = "<p>Click here to <a href="#Home">return home</a></p>";
<ide> console.log(innerHtml);
<del>
<ide> ```
<ide>
<ide> </div>
<ide> console.log(innerHtml);
<ide> <section id='solution'>
<ide>
<ide> ```js
<del>// solution required
<add>let innerHtml = "<p>Click here to <a href=\"#Home\">return home</a></p>";
<add>console.log(innerHtml);
<ide> ```
<ide>
<del>/section>
<add></section>
<ide><path>curriculum/challenges/chinese/02-javascript-algorithms-and-data-structures/debugging/catch-off-by-one-errors-when-using-indexing.chinese.md
<ide> id: 587d7b86367417b2b2512b3b
<ide> title: Catch Off By One Errors When Using Indexing
<ide> challengeType: 1
<del>videoUrl: ''
<del>localeTitle: 使用索引时捕获一个错误
<add>forumTopicId: 301189
<add>localeTitle: 捕获使用索引的时候出现的错误
<ide> ---
<ide>
<ide> ## Description
<del><section id="description">当您尝试定位字符串或数组的特定索引(切片或访问段)或循环索引时,会<code>Off by one errors</code> (有时称为OBOE)。 JavaScript索引从零开始,而不是一个,这意味着最后一个索引总是小于项目的长度。如果您尝试访问等于长度的索引,程序可能会抛出“索引超出范围”引用错误或打印<code>undefined</code> 。当您使用将索引范围作为参数的字符串或数组方法时,它有助于阅读文档并了解它们是否包含(指定索引处的项目是否是返回的一部分)。以下是一些错误的示例: <blockquote> let alphabet =“abcdefghijklmnopqrstuvwxyz”; <br>让len = alphabet.length; <br> for(let i = 0; i <= len; i ++){ <br> //最后循环一次太多次<br>的console.log(字母[I]); <br> } <br> for(let j = 1; j <len; j ++){ <br> //循环一次太少次并错过索引0处的第一个字符<br>的console.log(字母[J]); <br> } <br> for(let k = 0; k <len; k ++){ <br> // Goldilocks赞成 - 这是正确的<br>的console.log(字母表[K]); <br> } </blockquote></section>
<add><section id='description'>
<add>当试图访问字符串或数组的特定索引(分割或访问一个片段)或循环索引时,有时会出现<code>Off by one errors</code>错误(有时称为 OBOE)。JavaScript 索引从<code>0</code>开始,而不是<code>1</code>,这意味着最后一个索引总会比字符串或数组的长度少 1。如果尝试访问等于长度的索引,程序可能会抛出“索引超出范围”引用错误或打印出<code>undefined</code>。
<add>当使用将索引范围作为参数的字符串或数组方法时,阅读相关的文档并了解参数中的索引的包含性(即是否考虑进返回值中)很重要。以下是一些错误的示例:
<add>
<add>```js
<add>let alphabet = "abcdefghijklmnopqrstuvwxyz";
<add>let len = alphabet.length;
<add>for (let i = 0; i <= len; i++) {
<add> // 在最后多了一次循环
<add> console.log(alphabet[i]);
<add>}
<add>for (let j = 1; j < len; j++) {
<add> // 循环少了一次,漏掉了索引 0 处的字符
<add> console.log(alphabet[j]);
<add>}
<add>for (let k = 0; k < len; k++) {
<add> // 不多不少,这才是正确的
<add> console.log(alphabet[k]);
<add>}
<add>```
<add>
<add></section>
<ide>
<ide> ## Instructions
<del><section id="instructions">修复以下函数中的两个索引错误,以便将所有数字1到5打印到控制台。 </section>
<add><section id='instructions'>
<add>修复以下函数中的两个索引错误,以便将 1 到 5 之间(包含 1 和 5)的所有数字打印到控制台。
<add></section>
<ide>
<ide> ## Tests
<ide> <section id='tests'>
<ide>
<ide> ```yml
<ide> tests:
<del> - text: 您的代码应该设置循环的初始条件,以便从第一个索引开始。
<add> - text: 你应该设置循环的初始条件,使循环从第一个索引开始。
<ide> testString: assert(code.match(/i\s*?=\s*?0\s*?;/g).length == 1);
<del> - text: 您的代码应该修复循环的初始条件,以便索引从0开始。
<add> - text: 你应修复循环的初始条件,使循环从索引 0 开始。
<ide> testString: assert(!code.match(/i\s?=\s*?1\s*?;/g));
<del> - text: 您的代码应设置循环的终端条件,以便它停在最后一个索引处。
<add> - text: 你应设置循环的终止条件,使循环在最后一个索引处停止。
<ide> testString: assert(code.match(/i\s*?<\s*?len\s*?;/g).length == 1);
<del> - text: 您的代码应该修复循环的终端条件,使其在长度之前停止在1。
<add> - text: 你应修复循环的终止条件,使循环在索引为字符串长度减 1 时停止。
<ide> testString: assert(!code.match(/i\s*?<=\s*?len;/g));
<ide>
<ide> ```
<ide> function countToFive() {
<ide> }
<ide>
<ide> countToFive();
<del>
<ide> ```
<ide>
<ide> </div>
<ide> countToFive();
<ide> <section id='solution'>
<ide>
<ide> ```js
<del>// solution required
<add>function countToFive() {
<add> let firstFive = "12345";
<add> let len = firstFive.length;
<add> // Fix the line below
<add> for (let i = 0; i < len; i++) {
<add> // Do not alter code below this line
<add> console.log(firstFive[i]);
<add> }
<add>}
<add>
<add>countToFive();
<ide> ```
<ide>
<del>/section>
<add>
<add></section>
<ide><path>curriculum/challenges/chinese/02-javascript-algorithms-and-data-structures/debugging/catch-unclosed-parentheses-brackets-braces-and-quotes.chinese.md
<ide> ---
<ide> id: 587d7b84367417b2b2512b36
<del>title: 'Catch Unclosed Parentheses, Brackets, Braces and Quotes'
<add>title: Catch Unclosed Parentheses, Brackets, Braces and Quotes
<ide> challengeType: 1
<del>videoUrl: ''
<del>localeTitle: 抓住未封闭的圆括号,括号,括号和引号
<add>forumTopicId: 301190
<add>localeTitle: 捕获未闭合的括号、方括号、大括号和引号
<ide> ---
<ide>
<ide> ## Description
<del><section id="description">要注意的另一个语法错误是所有左括号,括号,花括号和引号都有一个结束对。当您编辑现有代码并使用其中一种类型插入项目时,会忘记忘记一件事。此外,在将代码块嵌套到其他代码块时要小心,例如将回调函数作为参数添加到方法中。避免这种错误的一种方法是,只要输入开头字符,立即包括结束匹配,然后将光标移回它们之间并继续编码。幸运的是,大多数现代代码编辑器会自动生成对的后半部分。 </section>
<add><section id='description'>
<add>要注意的另一个语法错误是所有的小括号、方括号、花括号和引号都必须配对。当你编辑代码并插入新代码其中带有括号时,很容易忘记括号闭合。 此外,在将代码块嵌套到其他代码块时要小心,例如将回调函数作为参数添加到方法中。
<add>避免这种错误的一种方法是,一次性输入完这些符号,然后将光标移回它们之间继续编写。好在,现在大部分编辑器都会帮你自动补全。
<add></section>
<ide>
<ide> ## Instructions
<del><section id="instructions">修复代码中的两对错误。 </section>
<add><section id='instructions'>
<add>修复代码中的两个符号配对错误。
<add></section>
<ide>
<ide> ## Tests
<ide> <section id='tests'>
<ide>
<ide> ```yml
<ide> tests:
<del> - text: 您的代码应该修复数组中缺少的部分。
<add> - text: 你应该修复数组缺少的部分。
<ide> testString: assert(code.match(/myArray\s*?=\s*?\[\s*?1\s*?,\s*?2\s*?,\s*?3\s*?\];/g));
<del> - text: 您的代码应该修复<code>.reduce()</code>方法的缺失部分。控制台输出应显示“数组值的总和为:6”。
<add> - text: '你应该修复<code>.reduce()</code>方法缺少的部分。控制台应输出 "Sum of array values is: 6"。'
<ide> testString: 'assert(arraySum === 6);'
<ide>
<ide> ```
<ide> tests:
<ide> let myArray = [1, 2, 3;
<ide> let arraySum = myArray.reduce((previous, current => previous + current);
<ide> console.log(`Sum of array values is: ${arraySum}`);
<del>
<ide> ```
<ide>
<ide> </div>
<ide> console.log(`Sum of array values is: ${arraySum}`);
<ide> <section id='solution'>
<ide>
<ide> ```js
<del>// solution required
<add>let myArray = [1, 2, 3];
<add>let arraySum = myArray.reduce((previous, current) => previous + current);
<add>console.log(`Sum of array values is: ${arraySum}`);
<ide> ```
<ide>
<del>/section>
<add></section>
<ide><path>curriculum/challenges/chinese/02-javascript-algorithms-and-data-structures/debugging/catch-use-of-assignment-operator-instead-of-equality-operator.chinese.md
<ide> id: 587d7b85367417b2b2512b38
<ide> title: Catch Use of Assignment Operator Instead of Equality Operator
<ide> challengeType: 1
<del>videoUrl: ''
<del>localeTitle: 捕获使用赋值运算符而不是等式运算符
<add>forumTopicId: 301191
<add>localeTitle: 捕获使用赋值运算符而不是相等运算符
<ide> ---
<ide>
<ide> ## Description
<del><section id="description">分支程序,即在满足某些条件时执行不同操作的程序,依赖于JavaScript中的<code>if</code> , <code>else if</code>和<code>else</code>语句。条件有时采取测试结果是否等于值的形式。这种逻辑(至少在英语中)是“如果x等于y,则......”,它可以使用<code>=</code>或赋值运算符逐字地转换为代码。这会导致程序中出现意外的控制流。如前面的挑战所述,JavaScript中的赋值运算符( <code>=</code> )为变量名赋值。并且<code>==</code>和<code>===</code>运算符检查相等性(严格相等的三重<code>===</code>测试,意味着值和类型都相同)。下面的代码将<code>x</code>指定为2,其值为<code>true</code> 。几乎JavaScript中的每个值都评估为<code>true</code> ,除了所谓的“falsy”值: <code>false</code> , <code>0</code> , <code>""</code> (空字符串), <code>NaN</code> , <code>undefined</code>和<code>null</code> 。 <blockquote>设x = 1; <br>让y = 2; <br> if(x = y){ <br> //此代码块将针对y的任何值运行(除非y最初设置为假) <br> } else { <br> //这个代码块是本例中应该运行的(但不会) <br> } </blockquote></section>
<add><section id='description'>
<add>分支程序,即在满足某些条件时执行不同操作的程序,依赖于 JavaScript 中的<code>if</code>,<code>else if</code>、<code>else</code>语句。条件有时采取测试一个结果是否等于一个值的形式。
<add>这种逻辑可以表述为“如果 x 等于 y ,则......”,听起来像是可以使用<code>=</code>(即赋值运算符)。然而,这会导致程序中流程出问题。
<add>如前面的挑战所述,JavaScript 中的赋值运算符 (<code>=</code>) 是用来为变量名赋值的。并且<code>==</code>和<code>===</code>运算符检查相等性(三等号<code>===</code>是用来测试是否严格相等的,严格相等的意思是值和类型都必须相同)。
<add>下面的代码将<code>x</code>赋值为 2,表达式<code>x = y</code>会在执行后得到<code>true</code>。JavaScript 会把大部分的值都视为<code>true</code>,除了所谓的 "falsy" 值,即:<code>false</code>、<code>0</code>、<code>""</code>(空字符串)、<code>NaN</code>、<code>undefined</code> 和 <code>null</code>。
<add>
<add>```js
<add>let x = 1;
<add>let y = 2;
<add>if (x = y) {
<add> // 除了 "falsy" 值以外 y 为任意值时这个代码块都将执行
<add>} else {
<add> // 按本例用意这个代码块应该执行(但其实不会)。
<add>}
<add>```
<add></section>
<ide>
<ide> ## Instructions
<del><section id="instructions">修复条件,以便程序运行正确的分支,并为<code>result</code>分配适当的值。 </section>
<add><section id='instructions'>
<add>修复条件语句,以便程序运行正确的分支,并给<code>result</code>赋上正确的值。
<add></section>
<ide>
<ide> ## Tests
<ide> <section id='tests'>
<ide>
<ide> ```yml
<ide> tests:
<del> - text: 您的代码应该修复条件,以便检查是否相等,而不是使用赋值。
<add> - text: 你应该修复条件语句,使其判断是否相等,而不是赋值。
<ide> testString: assert(result == "Not equal!");
<del> - text: 条件可以使用<code>==</code>或<code>===</code>来测试相等性。
<add> - text: 条件语句可以使用<code>==</code>或<code>===</code>来测试是否相等。
<ide> testString: assert(code.match(/x\s*?===?\s*?y/g));
<ide>
<ide> ```
<ide> if(x = y) {
<ide> }
<ide>
<ide> console.log(result);
<del>
<ide> ```
<ide>
<ide> </div>
<ide> console.log(result);
<ide> <section id='solution'>
<ide>
<ide> ```js
<del>// solution required
<add>let x = 7;
<add>let y = 9;
<add>let result = "to come";
<add>
<add>if(x === y) {
<add> result = "Equal!";
<add>} else {
<add> result = "Not equal!";
<add>}
<add>
<add>console.log(result);
<ide> ```
<ide>
<del>/section>
<add></section>
<ide><path>curriculum/challenges/chinese/02-javascript-algorithms-and-data-structures/debugging/prevent-infinite-loops-with-a-valid-terminal-condition.chinese.md
<ide> id: 587d7b86367417b2b2512b3d
<ide> title: Prevent Infinite Loops with a Valid Terminal Condition
<ide> challengeType: 1
<del>videoUrl: ''
<del>localeTitle: 使用有效的终端条件防止无限循环
<add>forumTopicId: 301192
<add>localeTitle: 使用有效的终止条件防止无限循环
<ide> ---
<ide>
<ide> ## Description
<del><section id="description">最后一个话题是可怕的无限循环。当您需要程序运行代码块一定次数或满足条件时,循环是很好的工具,但是它们需要终止条件来结束循环。无限循环可能会冻结或崩溃浏览器,并导致一般程序执行混乱,没有人想要。在本节的介绍中有一个无限循环的例子 - 它没有终止条件来摆脱<code>loopy()</code>内的<code>while</code>循环。不要叫这个功能! <blockquote> function loopy(){ <br> while(true){ <br> console.log(“Hello,world!”); <br> } <br> } </blockquote>程序员的工作是确保最终达到终止条件,该条件告诉程序何时突破循环代码。一个错误是从终端条件向错误方向递增或递减计数器变量。另一个是在循环代码中意外重置计数器或索引变量,而不是递增或递减它。 </section>
<add><section id='description'>
<add>最后一个话题是可怕的无限循环。当需要程序运行代码块一定次数或满足条件时,循环是很好的工具,但是它们需要终止条件来结束循环。无限循环可能会使浏览器冻结或崩溃,并导致程序执行混乱,没有人想要这样的结果。
<add>在本节的介绍中有一个无限循环的例子——它没有终止条件来摆脱<code>loopy()</code>内的<code>while</code>循环。不要调用这个函数!
<add>
<add>```js
<add>function loopy() {
<add> while(true) {
<add> console.log("Hello, world!");
<add> }
<add>}
<add>```
<add>
<add>程序员的工作是确保最终达到终止条件,该条件告诉程序何时跳出循环。有一种错误是从终端条件向错误方向递增或递减计数器变量。另一种是在循环代码中意外重置计数器或索引变量,而不是递增或递减它。
<add></section>
<ide>
<ide> ## Instructions
<del><section id="instructions"> <code>myFunc()</code>函数包含一个无限循环,因为终端条件<code>i != 4</code>将永远不会计算为<code>false</code> (并且会中断循环) - <code>i</code>将每次递增2,然后跳过4,因为<code>i</code>是奇数启动。固定在终端条件比较运算符因此该循环仅运行<code>i</code>小于或等于4。 </section>
<add><section id='instructions'>
<add><code>myFunc()</code>函数包含一个无限循环,因为终止条件<code>i != 4</code>永远不会为<code>false</code>(并中断循环) -<code>i</code>将每次递增 2,然后跳过 4,因为<code>i</code>是从奇数开始递增。在终端条件中输入比较运算符,使循环仅在<code>i</code>小于或等于 4 的情况下运行。
<add></section>
<ide>
<ide> ## Tests
<ide> <section id='tests'>
<ide>
<ide> ```yml
<ide> tests:
<del> - text: 您的代码应该更改<code>for</code>循环的终端条件(中间部分)中的比较运算符。
<add> - text: 你应该在<code>for</code>循环的终止条件(中间部分)中更改比较运算符。
<ide> testString: assert(code.match(/i\s*?<=\s*?4;/g).length == 1);
<del> - text: 您的代码应该在循环的终端条件中修复比较运算符。
<add> - text: 你应该修改比较运算符来避免出现死循环。
<ide> testString: assert(!code.match(/i\s*?!=\s*?4;/g));
<ide>
<ide> ```
<ide> function myFunc() {
<ide> console.log("Still going!");
<ide> }
<ide> }
<del>
<ide> ```
<ide>
<ide> </div>
<ide> function myFunc() {
<ide> <section id='solution'>
<ide>
<ide> ```js
<del>// solution required
<add>function myFunc() {
<add> for (let i = 1; i <= 4; i += 2) {
<add> console.log("Still going!");
<add> }
<add>}
<ide> ```
<ide>
<del>/section>
<add></section>
<ide><path>curriculum/challenges/chinese/02-javascript-algorithms-and-data-structures/debugging/understanding-the-differences-between-the-freecodecamp-and-browser-console.chinese.md
<ide> id: 587d7b83367417b2b2512b37
<ide> title: Understanding the Differences between the freeCodeCamp and Browser Console
<ide> challengeType: 1
<del>videoUrl: ''
<del>localeTitle: 了解freeCodeCamp和浏览器控制台之间的差异
<add>forumTopicId: 301193
<add>localeTitle: 了解 freeCodeCamp 和浏览器控制台之间的差异
<ide> ---
<ide>
<ide> ## Description
<del><section id="description">您可能已经注意到一些freeCodeCamp JavaScript挑战包括他们自己的控制台。此控制台的行为与您在上一次挑战中使用的浏览器控制台略有不同。以下挑战旨在强调freeCodeCamp控制台与浏览器控制台之间的一些差异。首先,浏览器控制台。当您在浏览器中加载并运行普通JavaScript文件时, <code>console.log()</code>语句将准确打印您告诉他们打印到浏览器控制台的确切次数。在浏览器中的文本编辑器中,过程略有不同,最初可能会让人感到困惑。传递给文本编辑器块中的<code>console.log()</code>值运行每组测试以及您在代码中进行的任何函数调用的一次。这有助于一些有趣的行为,并且可能会在开始时将您绊倒,因为您希望只看到一次的记录值可能会打印出更多次,具体取决于测试次数和传递给这些测试的值。如果您只想查看单个输出而不必担心运行测试周期,可以使用<code>console.clear()</code> 。 </section>
<add><section id='description'>
<add>你可能已经注意到一些 freeCodeCamp JavaScript 的挑战有自己的控制台。这些控制台的行为与上一次挑战中使用的浏览器控制台略有不同。
<add>以下挑战旨在强调 freeCodeCamp 控制台与浏览器控制台之间的一些差异。
<add>对于浏览器控制台。当在浏览器中加载并运行 JavaScript 文件时,<code>console.log()</code>语句会在控制台中按照调用的次数准确地打印出要求的内容。然而,在 freeCodeCamp 的代码编辑器中使用<code>console.log()</code>会略有不同,一开始可能会让你感到困惑。
<add>在 freeCodeCamp 代码编辑器中,传给<code>console.log()</code>的值会在每组测试执行的时候输出。另外,如果在代码中还手动调用过挑战题目的函数,调用几次就会增加几次传入值的输出。
<add>这就产生了一些有趣的行为,并可能在一开始就让你感到困惑,因为你觉得只会输出一次的值可能会输出多次,具体次数取决于挑战题目本身测试的数量以及这些测试调用挑战函数的方式。
<add>如果你不打算执行挑战的测试,而只想查看自己调用<code>console.log()</code>的输出,可以使用<code>console.clear()</code>。
<add></section>
<ide>
<ide> ## Instructions
<del><section id="instructions">使用<code>console.log()</code>在指示的代码中打印变量。 </section>
<add><section id='instructions'>
<add>首先,使用 <code>console.clear()</code> 清空浏览器控制台。然后使用<code>console.log()</code>在代码中指定的位置打印 <code>output</code> 变量。
<add></section>
<ide>
<ide> ## Tests
<ide> <section id='tests'>
<ide>
<ide> ```yml
<ide> tests:
<del> - text: 使用<code>console.log()</code>打印<code>outputTwo</code>变量。在浏览器控制台中,这应该打印出变量的值两次。
<del> testString: 'assert(code.match(/console\.log\(outputTwo\)/g), "Use <code>console.log()</code> to print the <code>outputTwo</code> variable. In your Browser Console this should print out the value of the variable two times.");'
<del> - text: 使用<code>console.log()</code>打印<code>outputOne</code>变量。
<del> testString: 'assert(code.match(/console\.log\(outputOne\)/g), "Use <code>console.log()</code> to print the <code>outputOne</code> variable.");'
<del> - text: 使用<code>console.clear()</code>修改输出,以便<code>outputOne</code>变量只输出一次。
<del> testString: 'assert(code.match(/^(\s*console.clear\(\);?\s*)$/gm), "Use <code>console.clear()</code> to modify your output so that <code>outputOne</code> variable only outputs once.");'
<add> - text: 应该使用 <code>console.clear()</code> 来清空浏览器控制台。
<add> testString: const removeJSComments = code.replace(/\/\*[\s\S]*?\*\/|\/\/.*$/gm, ''); const noSpaces = removeJSComments.replace(/\s/g, ''); assert(noSpaces.match(/console.clear\(\)/));
<add> - text: 使用<code>console.log()</code>输出变量<code>output</code>的值。
<add> testString: const noSpaces = code.replace(/\s/g, ''); assert(noSpaces.match(/console\.log\(output\)/));
<ide>
<ide> ```
<ide>
<ide> tests:
<ide> <div id='js-seed'>
<ide>
<ide> ```js
<del>// Open your browser console
<del>let outputTwo = "This will print to the browser console 2 times";
<del>// Use console.log() to print the outputTwo variable
<add>// Open your browser console.
<add>let output = "Get this to log once in the browser console and twice in the freeCodeCamp console";
<add>// Use console.clear() on the next line to clear the browser console.
<ide>
<ide>
<del>let outputOne = "Try to get this to log only once to the browser console";
<del>// Use console.clear() in the next line to print the outputOne only once
<add>// Use console.log() to print the output variable.
<ide>
<ide>
<del>// Use console.log() to print the outputOne variable
<del>
<add>// Check the two consoles to see the difference. The freeCodeCamp console should have printed the variable twice, once for each test of this challenge. The browser console should only print the variable once because you cleared it first.
<ide> ```
<ide>
<ide> </div>
<ide> let outputOne = "Try to get this to log only once to the browser console";
<ide> ## Solution
<ide> <section id='solution'>
<ide>
<add>
<ide> ```js
<del>// solution required
<add>// Open your browser console.
<add>let output = "Get this to log once in the browser console and twice in the freeCodeCamp console";
<add>// Use console.clear() on the next line to clear the browser console.
<add>console.clear();
<add>
<add>// Use console.log() to print the output variable.
<add>console.log(output);
<add>
<add>// Check the two consoles to see the difference. The freeCodeCamp console should have printed the variable twice, one for each test of this challenge. The browser console should only print the variable once becuase you cleared it first.
<ide> ```
<ide>
<del>/section>
<add></section>
<add>
<ide><path>curriculum/challenges/chinese/02-javascript-algorithms-and-data-structures/debugging/use-caution-when-reinitializing-variables-inside-a-loop.chinese.md
<ide> id: 587d7b86367417b2b2512b3c
<ide> title: Use Caution When Reinitializing Variables Inside a Loop
<ide> challengeType: 1
<del>videoUrl: ''
<del>localeTitle: 在循环内重新初始化变量时请小心
<add>forumTopicId: 301194
<add>localeTitle: 重新初始化循环中的变量时要小心
<ide> ---
<ide>
<ide> ## Description
<del><section id="description">有时需要在循环中保存信息,增加计数器或重置变量。一个潜在的问题是变量要么重新初始化,要么不重新初始化,反之亦然。如果您不小心重置了用于终端条件的变量,导致无限循环,这将特别危险。使用<code>console.log()</code>在循环的每个循环中打印变量值可以发现与重置相关的错误行为,或者无法重置变量。 </section>
<add><section id='description'>
<add>有时需要在循环中保存信息以增加计数器或重置变量。一个潜在的问题是变量什么时候该重新初始化,什么时候不该重新初始化,反之亦然。如果你不小心重置了用于终止条件的变量,导致无限循环,这将特别危险。
<add>使用<code>console.log()</code>在每个循环中打印变量值可以发现与重置相关的错误或者重置变量失败。
<add></section>
<ide>
<ide> ## Instructions
<del><section id="instructions">以下函数应该创建一个具有<code>m</code>行和<code>n</code>列零的二维数组。不幸的是,它没有产生预期的输出,因为<code>row</code>变量没有在外部循环中重新初始化(设置回空数组)。修复代码,使其返回正确的3x2零数组,看起来像<code>[[0, 0], [0, 0], [0, 0]]</code> 。 </section>
<add><section id='instructions'>
<add>以下函数应该创建一个具有<code>m</code>行和<code>n</code>列“零”的二维数组。不幸的是,它没有产生预期的输出,因为<code>row</code>变量没有在外部循环中重新初始化(设置回空数组)。修改代码,使其正确地返回包含 3 行 2 列“零”的二维数组,即<code>[[0, 0], [0, 0], [0, 0]]</code>。
<add></section>
<ide>
<ide> ## Tests
<ide> <section id='tests'>
<ide>
<ide> ```yml
<ide> tests:
<del> - text: 您的代码应该将<code>matrix</code>变量设置为一个数组,每个数组包含3行,每列2列零。
<add> - text: 你应将变量<code>matrix</code>设置为 3 行 2 列“零”的二维数组。
<ide> testString: assert(JSON.stringify(matrix) == "[[0,0],[0,0],[0,0]]");
<del> - text: <code>matrix</code>变量应该有3行。
<add> - text: 变量<code>matrix</code>应有 3 行。
<ide> testString: assert(matrix.length == 3);
<del> - text: <code>matrix</code>变量每行应有2列。
<add> - text: 变量<code>matrix</code>每行应有 2 列。
<ide> testString: assert(matrix[0].length == 2 && matrix[1].length === 2 && matrix[2].length === 2);
<ide>
<ide> ```
<ide> function zeroArray(m, n) {
<ide>
<ide> let matrix = zeroArray(3, 2);
<ide> console.log(matrix);
<del>
<ide> ```
<ide>
<ide> </div>
<ide> console.log(matrix);
<ide> <section id='solution'>
<ide>
<ide> ```js
<del>// solution required
<add>function zeroArray(m, n) {
<add> // Creates a 2-D array with m rows and n columns of zeroes
<add> let newArray = [];
<add> for (let i = 0; i < m; i++) {
<add> let row = [];
<add> // Adds the m-th row into newArray
<add>
<add> for (let j = 0; j < n; j++) {
<add> // Pushes n zeroes into the current row to create the columns
<add> row.push(0);
<add> }
<add> // Pushes the current row, which now has n zeroes in it, to the array
<add> newArray.push(row);
<add> }
<add> return newArray;
<add>}
<add>
<add>let matrix = zeroArray(3, 2);
<add>console.log(matrix);
<ide> ```
<ide>
<del>/section>
<add></section>
<ide><path>curriculum/challenges/chinese/02-javascript-algorithms-and-data-structures/debugging/use-the-javascript-console-to-check-the-value-of-a-variable.chinese.md
<ide> id: 587d7b83367417b2b2512b33
<ide> title: Use the JavaScript Console to Check the Value of a Variable
<ide> challengeType: 1
<del>videoUrl: ''
<del>localeTitle: 使用JavaScript控制台检查变量的值
<add>forumTopicId: 18372
<add>localeTitle: 使用控制台检查变量值
<ide> ---
<ide>
<ide> ## Description
<del><section id="description"> Chrome和Firefox都有出色的JavaScript控制台,也称为DevTools,用于调试JavaScript。您可以在Chrome的菜单或FireFox菜单中的Web控制台中找到开发人员工具。如果您使用的是其他浏览器或手机,我们强烈建议您使用桌面版Firefox或Chrome。 <code>console.log()</code>方法将打印其括号内的输出“打印”到控制台,这可能是最有用的调试工具。将它放在代码中的关键点可以显示变量的中间值。在查看输出之前,最好先了解输出应该是什么。在整个代码中使用检查点来查看计算状态将有助于缩小问题所在。这是打印'Hello world!'的示例到控制台: <code>console.log('Hello world!');</code> </section>
<add><section id='description'>
<add>Chrome 和 Firefox 都有出色的 JavaScript 控制台(也称为 DevTools),可以用来调试 JavaScript 代码
<add>可以在 Chrome 的菜单中找到“开发者工具”或 FireFox 的菜单中的 “Web 控制台”。如果你使用其他浏览器或手机,我们强烈建议你切换到桌面版 Firefox 或 Chrome。
<add><code>console.log()</code>方法可能是最有用的调试工具,它可以将括号中的内容输出到控制台,将它放在代码中的关键点可以显示变量在当时的值。在查看输出之前,最好先想清楚输出应该是什么。在代码的合适位置打点来查看变量状态有助于定位问题。
<add>下面是输出 'Hello world!' 到控制台的示例:
<add><code>console.log('Hello world!');</code>
<add></section>
<ide>
<ide> ## Instructions
<del><section id="instructions">使用<code>console.log()</code>方法打印代码中记录的变量<code>a</code>的值。 </section>
<add><section id='instructions'>
<add>请使用<code>console.log()</code>方法在代码中注明的地方输出变量<code>a</code>的值。
<add></section>
<ide>
<ide> ## Tests
<ide> <section id='tests'>
<ide>
<ide> ```yml
<ide> tests:
<del> - text: 您的代码应使用<code>console.log()</code>来检查变量<code>a</code>的值。
<add> - text: 你应使用<code>console.log()</code>来检查变量<code>a</code>的值。
<ide> testString: assert(code.match(/console\.log\(a\)/g));
<ide>
<ide> ```
<ide> a++;
<ide>
<ide> let sumAB = a + b;
<ide> console.log(sumAB);
<del>
<ide> ```
<ide>
<ide> </div>
<ide> console.log(sumAB);
<ide> ## Solution
<ide> <section id='solution'>
<ide>
<add>
<ide> ```js
<del>// solution required
<add>var a = 5; console.log(a);
<ide> ```
<ide>
<del>/section>
<add></section>
<add>
<ide><path>curriculum/challenges/chinese/02-javascript-algorithms-and-data-structures/debugging/use-typeof-to-check-the-type-of-a-variable.chinese.md
<ide> id: 587d7b84367417b2b2512b34
<ide> title: Use typeof to Check the Type of a Variable
<ide> challengeType: 1
<del>videoUrl: ''
<del>localeTitle: 使用typeof检查变量的类型
<add>forumTopicId: 18374
<add>localeTitle: 使用 type of 检查变量的类型
<ide> ---
<ide>
<ide> ## Description
<del><section id="description">您可以使用<code>typeof</code>检查变量的数据结构或类型。在处理多种数据类型时,这在调试时很有用。如果您认为您正在添加两个数字,但其中一个实际上是一个字符串,则结果可能是意外的。类型错误可能潜伏在计算或函数调用中。特别是当您以JavaScript Object Notation(JSON)对象的形式访问和使用外部数据时要特别小心。以下是使用<code>typeof</code>一些示例: <blockquote> console.log(typeof“”); //输出“string” <br> console.log(typeof 0); //输出“数字” <br> console.log(typeof []); //输出“对象” <br> console.log(typeof {}); //输出“对象” </blockquote> JavaScript识别六种原始(不可变)数据类型: <code>Boolean</code> , <code>Null</code> , <code>Undefined</code> , <code>Number</code> , <code>String</code>和<code>Symbol</code> (ES6新增)和可变项的一种类型: <code>Object</code> 。请注意,在JavaScript中,数组在技术上是一种对象。 </section>
<add><section id='description'>
<add>可以使用<code>typeof</code>检查变量的数据结构或类型。在处理多种数据类型时,<code>typeof</code>会对调试很有帮助。如果想计算两数之和,但实际传入了一个字符串参数,则结果可能是错误的。类型错误可能隐藏在计算或函数调用中。当你以 JavaScript 对象(JSON)的形式访问和使用外部数据时尤其要小心。
<add>下面是使用<code>typeof</code>的一些示例:
<add>
<add>```js
<add>console.log(typeof ""); // 输出 "string"
<add>console.log(typeof 0); // 输出 "number"
<add>console.log(typeof []); // 输出 "object"
<add>console.log(typeof {}); // 输出 "object"
<add>```
<add>JavaScript 有六种原始(不可变)数据类型:<code>Boolean</code>,<code>Null</code>,<code>Undefined</code>,<code>Number</code>,<code>String</code>, 和<code>Symbol</code>(ES6 新增)和一种可变的数据类型:<code>Object</code>。注意,在 JavaScript 中,数组在本质上是一种对象
<add></section>
<ide>
<ide> ## Instructions
<del><section id="instructions">添加两个<code>console.log()</code>语句来检查<code>typeof</code>每两个变量的<code>seven</code>和<code>three</code>中的代码。 </section>
<add><section id='instructions'>
<add>添加两个<code>console.log()</code>语句来检查代码中的两个变量<code>seven</code>和<code>three</code>的 <code>typeof</code>值。
<add></section>
<ide>
<ide> ## Tests
<ide> <section id='tests'>
<ide>
<ide> ```yml
<ide> tests:
<del> - text: 您的代码应在两个<code>console.log()</code>语句中使用<code>typeof</code>来检查变量的类型。
<add> - text: 你应在两个<code>console.log()</code>语句中使用<code>typeof</code>来检查变量的类型。
<ide> testString: assert(code.match(/console\.log\(typeof[\( ].*\)?\)/g).length == 2);
<del> - text: 您的代码应使用<code>typeof</code>来检查变量类型<code>seven</code> 。
<add> - text: 你应使用<code>typeof</code>来检查变量<code>seven</code>的类型。
<ide> testString: assert(code.match(/typeof[\( ]seven\)?/g));
<del> - text: 您的代码应使用<code>typeof</code>来检查变量的类型<code>three</code> 。
<add> - text: 你应使用<code>typeof</code>来检查变量<code>three</code>的类型。
<ide> testString: assert(code.match(/typeof[\( ]three\)?/g));
<ide>
<ide> ```
<ide> console.log(seven + three);
<ide> ## Solution
<ide> <section id='solution'>
<ide>
<add>
<ide> ```js
<del>// solution required
<add>let seven = 7;let three = "3";console.log(typeof seven);
<add>console.log(typeof three);
<ide> ```
<ide>
<del>/section>
<add></section> | 12 |
Javascript | Javascript | add more warnings for responder based events | 3669b901011d4631e3efa9d9307683eac7801fcb | <ide><path>packages/react-dom/src/events/DOMEventResponderSystem.js
<ide> const eventResponderContext: ReactResponderContext = {
<ide> );
<ide> }
<ide> if (__DEV__) {
<del> possibleEventObject.preventDefault = () => {
<del> // Update this warning when we have a story around dealing with preventDefault
<add> const showWarning = name => {
<ide> warning(
<ide> false,
<del> 'preventDefault() is no longer available on event objects created from event responder modules.',
<add> '%s is not available on event objects created from event responder modules (React Flare).',
<add> name,
<ide> );
<ide> };
<add> possibleEventObject.preventDefault = () => {
<add> showWarning('preventDefault()');
<add> };
<ide> possibleEventObject.stopPropagation = () => {
<del> // Update this warning when we have a story around dealing with stopPropgation
<del> warning(
<del> false,
<del> 'stopPropagation() is no longer available on event objects created from event responder modules.',
<del> );
<add> showWarning('stopPropagation()');
<add> };
<add> possibleEventObject.isDefaultPrevented = () => {
<add> showWarning('isDefaultPrevented()');
<add> };
<add> possibleEventObject.isPropagationStopped = () => {
<add> showWarning('isPropagationStopped()');
<ide> };
<add> // $FlowFixMe: we don't need value, Flow thinks we do
<add> Object.defineProperty(possibleEventObject, 'nativeEvent', {
<add> get() {
<add> showWarning('nativeEvent');
<add> },
<add> });
<add> // $FlowFixMe: we don't need value, Flow thinks we do
<add> Object.defineProperty(possibleEventObject, 'defaultPrevented', {
<add> get() {
<add> showWarning('defaultPrevented');
<add> },
<add> });
<ide> }
<ide> const eventObject = ((possibleEventObject: any): $Shape<
<ide> PartialEventObject,
<ide><path>packages/react-dom/src/events/__tests__/DOMEventResponderSystem-test.internal.js
<ide> describe('DOMEventResponderSystem', () => {
<ide>
<ide> ReactDOM.render(<Test />, container);
<ide> });
<add>
<add> it('the event responder system should warn on accessing invalid properties', () => {
<add> const ClickEventComponent = createReactEventComponent(
<add> undefined,
<add> ['click'],
<add> undefined,
<add> undefined,
<add> undefined,
<add> (event, context, props) => {
<add> const syntheticEvent = {
<add> target: event.target,
<add> type: 'click',
<add> };
<add> context.dispatchEvent(syntheticEvent, props.onClick, {
<add> discrete: true,
<add> });
<add> },
<add> );
<add>
<add> let handler;
<add> const Test = () => (
<add> <ClickEventComponent onClick={handler}>
<add> <button>Click me!</button>
<add> </ClickEventComponent>
<add> );
<add> expect(() => {
<add> handler = event => {
<add> event.preventDefault();
<add> };
<add> ReactDOM.render(<Test />, container);
<add> dispatchClickEvent(document.body);
<add> }).toWarnDev(
<add> 'Warning: preventDefault() is not available on event objects created ' +
<add> 'from event responder modules (React Flare).',
<add> {withoutStack: true},
<add> );
<add> expect(() => {
<add> handler = event => {
<add> event.stopPropagation();
<add> };
<add> ReactDOM.render(<Test />, container);
<add> dispatchClickEvent(document.body);
<add> }).toWarnDev(
<add> 'Warning: stopPropagation() is not available on event objects created ' +
<add> 'from event responder modules (React Flare).',
<add> {withoutStack: true},
<add> );
<add> expect(() => {
<add> handler = event => {
<add> event.isDefaultPrevented();
<add> };
<add> ReactDOM.render(<Test />, container);
<add> dispatchClickEvent(document.body);
<add> }).toWarnDev(
<add> 'Warning: isDefaultPrevented() is not available on event objects created ' +
<add> 'from event responder modules (React Flare).',
<add> {withoutStack: true},
<add> );
<add> expect(() => {
<add> handler = event => {
<add> event.isPropagationStopped();
<add> };
<add> ReactDOM.render(<Test />, container);
<add> dispatchClickEvent(document.body);
<add> }).toWarnDev(
<add> 'Warning: isPropagationStopped() is not available on event objects created ' +
<add> 'from event responder modules (React Flare).',
<add> {withoutStack: true},
<add> );
<add> expect(() => {
<add> handler = event => {
<add> return event.nativeEvent;
<add> };
<add> ReactDOM.render(<Test />, container);
<add> dispatchClickEvent(document.body);
<add> }).toWarnDev(
<add> 'Warning: nativeEvent is not available on event objects created ' +
<add> 'from event responder modules (React Flare).',
<add> {withoutStack: true},
<add> );
<add> expect(() => {
<add> handler = event => {
<add> return event.defaultPrevented;
<add> };
<add> ReactDOM.render(<Test />, container);
<add> dispatchClickEvent(document.body);
<add> }).toWarnDev(
<add> 'Warning: defaultPrevented is not available on event objects created ' +
<add> 'from event responder modules (React Flare).',
<add> {withoutStack: true},
<add> );
<add>
<add> expect(container.innerHTML).toBe('<button>Click me!</button>');
<add> });
<ide> }); | 2 |
Ruby | Ruby | add ability to configure cache notifications info | e0874b6f88509270d7603184ecd158d55df7204f | <ide><path>activerecord/lib/active_record/connection_adapters/abstract/query_cache.rb
<ide> def cache_sql(sql, name, binds)
<ide> if @query_cache[sql].key?(binds)
<ide> ActiveSupport::Notifications.instrument(
<ide> "sql.active_record",
<del> sql: sql,
<del> binds: binds,
<del> type_casted_binds: -> { type_casted_binds(binds) },
<del> name: name,
<del> connection_id: object_id,
<del> cached: true,
<add> cache_notification_info(sql, name, binds)
<ide> )
<ide> @query_cache[sql][binds]
<ide> else
<ide> def cache_sql(sql, name, binds)
<ide> end
<ide> end
<ide>
<add> # Database adapters can override this method to
<add> # provide custom cache information.
<add> def cache_notification_info(sql, name, binds)
<add> {
<add> sql: sql,
<add> binds: binds,
<add> type_casted_binds: -> { type_casted_binds(binds) },
<add> name: name,
<add> connection_id: object_id,
<add> cached: true
<add> }
<add> end
<add>
<ide> # If arel is locked this is a SELECT ... FOR UPDATE or somesuch. Such
<ide> # queries should not be cached.
<ide> def locked?(arel)
<ide><path>activerecord/test/cases/query_cache_test.rb
<ide> class QueryCacheTest < ActiveRecord::TestCase
<ide> fixtures :tasks, :topics, :categories, :posts, :categories_posts
<ide>
<ide> class ShouldNotHaveExceptionsLogger < ActiveRecord::LogSubscriber
<del> attr_reader :logger
<add> attr_reader :logger, :events
<ide>
<ide> def initialize
<ide> super
<ide> @logger = ::Logger.new File::NULL
<ide> @exception = false
<add> @events = []
<ide> end
<ide>
<ide> def exception?
<ide> @exception
<ide> end
<ide>
<ide> def sql(event)
<add> @events << event
<ide> super
<ide> rescue
<ide> @exception = true
<ide> def test_query_cache_dups_results_correctly
<ide> end
<ide> end
<ide>
<add> def test_cache_notifications_can_be_overridden
<add> logger = ShouldNotHaveExceptionsLogger.new
<add> subscriber = ActiveSupport::Notifications.subscribe "sql.active_record", logger
<add>
<add> connection = ActiveRecord::Base.connection.dup
<add>
<add> def connection.cache_notification_info(sql, name, binds)
<add> super.merge(neat: true)
<add> end
<add>
<add> connection.cache do
<add> connection.select_all "select 1"
<add> connection.select_all "select 1"
<add> end
<add>
<add> assert_equal true, logger.events.last.payload[:neat]
<add> ensure
<add> ActiveSupport::Notifications.unsubscribe subscriber
<add> end
<add>
<ide> def test_cache_does_not_raise_exceptions
<ide> logger = ShouldNotHaveExceptionsLogger.new
<ide> subscriber = ActiveSupport::Notifications.subscribe "sql.active_record", logger | 2 |
Text | Text | add info osversion to api changelog | 53430f5fc14feb6d47d4bab740cf9d376e1c74aa | <ide><path>docs/api/version-history.md
<ide> keywords: "API, Docker, rcli, REST, documentation"
<ide> `private` to create the container in its own private cgroup namespace. The per-daemon
<ide> default is `host`, and can be changed by using the`CgroupNamespaceMode` daemon configuration
<ide> parameter.
<add>* `GET /info` now returns an `OSVersion` field, containing the operating system's
<add> version. This change is not versioned, and affects all API versions if the daemon
<add> has this patch.
<ide>
<ide> ## v1.40 API changes
<ide> | 1 |
Javascript | Javascript | squash getdomnode warning from isdomcomponent | 70985ba68dac9b3d01b1d59a86466a1c23e8180b | <ide><path>src/test/ReactTestUtils.js
<ide> var ReactTestUtils = {
<ide> isDOMComponent: function(inst) {
<ide> // TODO: Fix this heuristic. It's just here because composites can currently
<ide> // pretend to be DOM components.
<del> return !!(inst && inst.getDOMNode && inst.tagName);
<add> return !!(inst && inst.tagName && inst.getDOMNode);
<ide> },
<ide>
<ide> isDOMComponentElement: function(inst) {
<ide><path>src/test/__tests__/ReactTestUtils-test.js
<ide> describe('ReactTestUtils', function() {
<ide> // Should be document order, not mount order (which would be purple, orange)
<ide> expect(log).toEqual(['orangepurple', 'orange', 'purple']);
<ide> });
<add>
<add> it('does not warn for getDOMNode on ES6 classes', function() {
<add> var Foo = React.createClass({
<add> render: function() {
<add> return <div />;
<add> }
<add> });
<add>
<add> class Bar extends React.Component {
<add> render() {
<add> return <div />;
<add> }
<add> }
<add>
<add> spyOn(console, 'warn');
<add>
<add> var foo = ReactTestUtils.renderIntoDocument(<Foo />);
<add> expect(ReactTestUtils.isDOMComponent(foo)).toBe(false);
<add>
<add> var bar = ReactTestUtils.renderIntoDocument(<Bar />);
<add> expect(ReactTestUtils.isDOMComponent(bar)).toBe(false);
<add>
<add> var div = ReactTestUtils.renderIntoDocument(<div />);
<add> expect(ReactTestUtils.isDOMComponent(div)).toBe(true);
<add>
<add> expect(console.warn.calls.length).toBe(0);
<add> });
<ide> }); | 2 |
PHP | PHP | add additional tests for hidden input | 6177246ffaa4fa87faf91f09f5fe4873dbdacba2 | <ide><path>tests/TestCase/View/Helper/FormHelperTest.php
<ide> public function testHiddenField() {
<ide> $this->assertTags($result, array(
<ide> 'input' => array('type' => 'hidden', 'class' => 'form-error', 'name' => 'field', 'id' => 'theID', 'value' => 'test'))
<ide> );
<add>
<add> $result = $this->Form->hidden('field', ['value' => 'my value']);
<add> $expected = [
<add> 'input' => ['type' => 'hidden', 'class' => 'form-error', 'name' => 'field', 'value' => 'my value']
<add> ];
<add> $this->assertTags($result, $expected);
<ide> }
<ide>
<ide> /** | 1 |
Javascript | Javascript | give useful error when using two copies of react | 70bf3e1306395a2bd1e65bce60b5511875b00800 | <ide><path>src/browser/ui/ReactMount.js
<ide> "use strict";
<ide>
<ide> var DOMProperty = require('DOMProperty');
<del>var ReactCurrentOwner = require('ReactCurrentOwner');
<ide> var ReactBrowserEventEmitter = require('ReactBrowserEventEmitter');
<add>var ReactCurrentOwner = require('ReactCurrentOwner');
<add>var ReactDescriptor = require('ReactDescriptor');
<ide> var ReactInstanceHandles = require('ReactInstanceHandles');
<ide> var ReactPerf = require('ReactPerf');
<ide>
<ide> var ReactMount = {
<ide> * @return {ReactComponent} Component instance rendered in `container`.
<ide> */
<ide> renderComponent: function(nextDescriptor, container, callback) {
<add> invariant(
<add> ReactDescriptor.isValidDescriptor(nextDescriptor),
<add> 'renderComponent(): Invalid component descriptor.%s',
<add> (
<add> ReactDescriptor.isValidFactory(nextDescriptor) ?
<add> ' Instead of passing a component class, make sure to instantiate ' +
<add> 'it first by calling it with props.' :
<add> // Check if it quacks like a descriptor
<add> typeof nextDescriptor.props !== "undefined" ?
<add> ' This may be caused by unintentionally loading two independent ' +
<add> 'copies of React.' :
<add> ''
<add> )
<add> );
<add>
<ide> var prevComponent = instancesByReactRootID[getReactRootID(container)];
<ide>
<ide> if (prevComponent) {
<ide><path>src/browser/ui/__tests__/ReactMount-test.js
<ide> var mocks = require('mocks');
<ide> describe('ReactMount', function() {
<ide> var React = require('React');
<ide> var ReactMount = require('ReactMount');
<add> var ReactTestUtils = require('ReactTestUtils');
<ide>
<ide> describe('constructAndRenderComponentByID', function() {
<ide> it('throws if given an id for a component that doesn\'t exist', function() {
<ide> describe('ReactMount', function() {
<ide> });
<ide> });
<ide>
<add> it('throws when given a factory', function() {
<add> expect(function() {
<add> ReactTestUtils.renderIntoDocument(React.DOM.div);
<add> }).toThrow(
<add> 'Invariant Violation: renderComponent(): Invalid component descriptor. ' +
<add> 'Instead of passing a component class, make sure to instantiate it ' +
<add> 'first by calling it with props.'
<add> );
<add>
<add> var Component = React.createClass({
<add> render: function() {
<add> return <div />;
<add> }
<add> });
<add> expect(function() {
<add> ReactTestUtils.renderIntoDocument(Component);
<add> }).toThrow(
<add> 'Invariant Violation: renderComponent(): Invalid component descriptor. ' +
<add> 'Instead of passing a component class, make sure to instantiate it ' +
<add> 'first by calling it with props.'
<add> );
<add> });
<add>
<ide> it('should render different components in same root', function() {
<ide> var container = document.createElement('container');
<ide> document.documentElement.appendChild(container);
<ide><path>src/core/__tests__/ReactPropTypes-test.js
<ide>
<ide> "use strict";
<ide>
<add>var PropTypes;
<add>var React;
<add>var ReactPropTypeLocations;
<ide> var ReactTestUtils;
<ide>
<del>var PropTypes = require('ReactPropTypes');
<del>var React = require('React');
<del>var ReactPropTypeLocations = require('ReactPropTypeLocations');
<del>
<ide> var Component;
<ide> var MyComponent;
<ide> var requiredMessage =
<ide> function typeCheckPass(declaration, value) {
<ide> expect(error).toBe(undefined);
<ide> }
<ide>
<del>describe('Primitive Types', function() {
<del> it("should warn for invalid strings", function() {
<del> typeCheckFail(
<del> PropTypes.string,
<del> [],
<del> 'Invalid prop `testProp` of type `array` supplied to `testComponent`, ' +
<del> 'expected `string`.'
<del> );
<del> typeCheckFail(
<del> PropTypes.string,
<del> false,
<del> 'Invalid prop `testProp` of type `boolean` supplied to ' +
<del> '`testComponent`, expected `string`.'
<del> );
<del> typeCheckFail(
<del> PropTypes.string,
<del> 0,
<del> 'Invalid prop `testProp` of type `number` supplied to ' +
<del> '`testComponent`, expected `string`.'
<del> );
<del> typeCheckFail(
<del> PropTypes.string,
<del> {},
<del> 'Invalid prop `testProp` of type `object` supplied to ' +
<del> '`testComponent`, expected `string`.'
<del> );
<add>describe('ReactPropTypes', function() {
<add> beforeEach(function() {
<add> PropTypes = require('ReactPropTypes');
<add> React = require('React');
<add> ReactPropTypeLocations = require('ReactPropTypeLocations');
<add> ReactTestUtils = require('ReactTestUtils');
<ide> });
<ide>
<del> it('should fail date and regexp correctly', function() {
<del> typeCheckFail(
<del> PropTypes.string,
<del> new Date(),
<del> 'Invalid prop `testProp` of type `date` supplied to ' +
<del> '`testComponent`, expected `string`.'
<del> );
<del> typeCheckFail(
<del> PropTypes.string,
<del> /please/,
<del> 'Invalid prop `testProp` of type `regexp` supplied to ' +
<del> '`testComponent`, expected `string`.'
<del> );
<del> });
<add> describe('Primitive Types', function() {
<add> it("should warn for invalid strings", function() {
<add> typeCheckFail(
<add> PropTypes.string,
<add> [],
<add> 'Invalid prop `testProp` of type `array` supplied to ' +
<add> '`testComponent`, expected `string`.'
<add> );
<add> typeCheckFail(
<add> PropTypes.string,
<add> false,
<add> 'Invalid prop `testProp` of type `boolean` supplied to ' +
<add> '`testComponent`, expected `string`.'
<add> );
<add> typeCheckFail(
<add> PropTypes.string,
<add> 0,
<add> 'Invalid prop `testProp` of type `number` supplied to ' +
<add> '`testComponent`, expected `string`.'
<add> );
<add> typeCheckFail(
<add> PropTypes.string,
<add> {},
<add> 'Invalid prop `testProp` of type `object` supplied to ' +
<add> '`testComponent`, expected `string`.'
<add> );
<add> });
<ide>
<del> it("should not warn for valid values", function() {
<del> typeCheckPass(PropTypes.array, []);
<del> typeCheckPass(PropTypes.bool, false);
<del> typeCheckPass(PropTypes.func, function() {});
<del> typeCheckPass(PropTypes.number, 0);
<del> typeCheckPass(PropTypes.string, '');
<del> typeCheckPass(PropTypes.object, {});
<del> typeCheckPass(PropTypes.object, new Date());
<del> typeCheckPass(PropTypes.object, /please/);
<del> });
<add> it('should fail date and regexp correctly', function() {
<add> typeCheckFail(
<add> PropTypes.string,
<add> new Date(),
<add> 'Invalid prop `testProp` of type `date` supplied to ' +
<add> '`testComponent`, expected `string`.'
<add> );
<add> typeCheckFail(
<add> PropTypes.string,
<add> /please/,
<add> 'Invalid prop `testProp` of type `regexp` supplied to ' +
<add> '`testComponent`, expected `string`.'
<add> );
<add> });
<ide>
<del> it("should be implicitly optional and not warn without values", function() {
<del> typeCheckPass(PropTypes.string, null);
<del> typeCheckPass(PropTypes.string, undefined);
<del> });
<add> it("should not warn for valid values", function() {
<add> typeCheckPass(PropTypes.array, []);
<add> typeCheckPass(PropTypes.bool, false);
<add> typeCheckPass(PropTypes.func, function() {});
<add> typeCheckPass(PropTypes.number, 0);
<add> typeCheckPass(PropTypes.string, '');
<add> typeCheckPass(PropTypes.object, {});
<add> typeCheckPass(PropTypes.object, new Date());
<add> typeCheckPass(PropTypes.object, /please/);
<add> });
<ide>
<del> it("should warn for missing required values", function() {
<del> typeCheckFail(PropTypes.string.isRequired, null, requiredMessage);
<del> typeCheckFail(PropTypes.string.isRequired, undefined, requiredMessage);
<del> });
<del>});
<add> it("should be implicitly optional and not warn without values", function() {
<add> typeCheckPass(PropTypes.string, null);
<add> typeCheckPass(PropTypes.string, undefined);
<add> });
<ide>
<del>describe('Any type', function() {
<del> it('should should accept any value', function() {
<del> typeCheckPass(PropTypes.any, 0);
<del> typeCheckPass(PropTypes.any, 'str');
<del> typeCheckPass(PropTypes.any, []);
<add> it("should warn for missing required values", function() {
<add> typeCheckFail(PropTypes.string.isRequired, null, requiredMessage);
<add> typeCheckFail(PropTypes.string.isRequired, undefined, requiredMessage);
<add> });
<ide> });
<ide>
<del> it("should be implicitly optional and not warn without values", function() {
<del> typeCheckPass(PropTypes.any, null);
<del> typeCheckPass(PropTypes.any, undefined);
<del> });
<add> describe('Any type', function() {
<add> it('should should accept any value', function() {
<add> typeCheckPass(PropTypes.any, 0);
<add> typeCheckPass(PropTypes.any, 'str');
<add> typeCheckPass(PropTypes.any, []);
<add> });
<ide>
<del> it("should warn for missing required values", function() {
<del> typeCheckFail(PropTypes.any.isRequired, null, requiredMessage);
<del> typeCheckFail(PropTypes.any.isRequired, undefined, requiredMessage);
<del> });
<del>});
<add> it("should be implicitly optional and not warn without values", function() {
<add> typeCheckPass(PropTypes.any, null);
<add> typeCheckPass(PropTypes.any, undefined);
<add> });
<ide>
<del>describe('ArrayOf Type', function() {
<del> it('should support the arrayOf propTypes', function() {
<del> typeCheckPass(PropTypes.arrayOf(PropTypes.number), [1, 2, 3]);
<del> typeCheckPass(PropTypes.arrayOf(PropTypes.string), ['a', 'b', 'c']);
<del> typeCheckPass(PropTypes.arrayOf(PropTypes.oneOf(['a', 'b'])), ['a', 'b']);
<add> it("should warn for missing required values", function() {
<add> typeCheckFail(PropTypes.any.isRequired, null, requiredMessage);
<add> typeCheckFail(PropTypes.any.isRequired, undefined, requiredMessage);
<add> });
<ide> });
<ide>
<del> it('should support arrayOf with complex types', function() {
<del> typeCheckPass(
<del> PropTypes.arrayOf(PropTypes.shape({a: PropTypes.number.isRequired})),
<del> [{a: 1}, {a: 2}]
<del> );
<add> describe('ArrayOf Type', function() {
<add> it('should support the arrayOf propTypes', function() {
<add> typeCheckPass(PropTypes.arrayOf(PropTypes.number), [1, 2, 3]);
<add> typeCheckPass(PropTypes.arrayOf(PropTypes.string), ['a', 'b', 'c']);
<add> typeCheckPass(PropTypes.arrayOf(PropTypes.oneOf(['a', 'b'])), ['a', 'b']);
<add> });
<ide>
<del> function Thing() {}
<del> typeCheckPass(
<del> PropTypes.arrayOf(PropTypes.instanceOf(Thing)),
<del> [new Thing(), new Thing()]
<del> );
<del> });
<add> it('should support arrayOf with complex types', function() {
<add> typeCheckPass(
<add> PropTypes.arrayOf(PropTypes.shape({a: PropTypes.number.isRequired})),
<add> [{a: 1}, {a: 2}]
<add> );
<ide>
<del> it('should warn with invalid items in the array', function() {
<del> typeCheckFail(
<del> PropTypes.arrayOf(PropTypes.number),
<del> [1, 2, 'b'],
<del> 'Invalid prop `2` of type `string` supplied to `testComponent`, ' +
<del> 'expected `number`.'
<del> );
<del> });
<add> function Thing() {}
<add> typeCheckPass(
<add> PropTypes.arrayOf(PropTypes.instanceOf(Thing)),
<add> [new Thing(), new Thing()]
<add> );
<add> });
<ide>
<del> it('should warn with invalid complex types', function() {
<del> function Thing() {}
<del> var name = Thing.name || '<<anonymous>>';
<add> it('should warn with invalid items in the array', function() {
<add> typeCheckFail(
<add> PropTypes.arrayOf(PropTypes.number),
<add> [1, 2, 'b'],
<add> 'Invalid prop `2` of type `string` supplied to `testComponent`, ' +
<add> 'expected `number`.'
<add> );
<add> });
<ide>
<del> typeCheckFail(
<del> PropTypes.arrayOf(PropTypes.instanceOf(Thing)),
<del> [new Thing(), 'xyz'],
<del> 'Invalid prop `1` supplied to `testComponent`, expected instance of `' +
<del> name + '`.'
<del> );
<del> });
<add> it('should warn with invalid complex types', function() {
<add> function Thing() {}
<add> var name = Thing.name || '<<anonymous>>';
<ide>
<del> it('should warn when passed something other than an array', function() {
<del> typeCheckFail(
<del> PropTypes.arrayOf(PropTypes.number),
<del> {'0': 'maybe-array', length: 1},
<del> 'Invalid prop `testProp` of type `object` supplied to `testComponent`, ' +
<del> 'expected an array.'
<del> );
<del> typeCheckFail(
<del> PropTypes.arrayOf(PropTypes.number),
<del> 123,
<del> 'Invalid prop `testProp` of type `number` supplied to `testComponent`, ' +
<del> 'expected an array.'
<del> );
<del> typeCheckFail(
<del> PropTypes.arrayOf(PropTypes.number),
<del> 'string',
<del> 'Invalid prop `testProp` of type `string` supplied to `testComponent`, ' +
<del> 'expected an array.'
<del> );
<del> });
<add> typeCheckFail(
<add> PropTypes.arrayOf(PropTypes.instanceOf(Thing)),
<add> [new Thing(), 'xyz'],
<add> 'Invalid prop `1` supplied to `testComponent`, expected instance of `' +
<add> name + '`.'
<add> );
<add> });
<ide>
<del> it('should not warn when passing an empty array', function() {
<del> typeCheckPass(PropTypes.arrayOf(PropTypes.number), []);
<del> });
<add> it('should warn when passed something other than an array', function() {
<add> typeCheckFail(
<add> PropTypes.arrayOf(PropTypes.number),
<add> {'0': 'maybe-array', length: 1},
<add> 'Invalid prop `testProp` of type `object` supplied to ' +
<add> '`testComponent`, expected an array.'
<add> );
<add> typeCheckFail(
<add> PropTypes.arrayOf(PropTypes.number),
<add> 123,
<add> 'Invalid prop `testProp` of type `number` supplied to ' +
<add> '`testComponent`, expected an array.'
<add> );
<add> typeCheckFail(
<add> PropTypes.arrayOf(PropTypes.number),
<add> 'string',
<add> 'Invalid prop `testProp` of type `string` supplied to ' +
<add> '`testComponent`, expected an array.'
<add> );
<add> });
<ide>
<del> it("should be implicitly optional and not warn without values", function() {
<del> typeCheckPass(PropTypes.arrayOf(PropTypes.number), null);
<del> typeCheckPass(PropTypes.arrayOf(PropTypes.number), undefined);
<del> });
<add> it('should not warn when passing an empty array', function() {
<add> typeCheckPass(PropTypes.arrayOf(PropTypes.number), []);
<add> });
<ide>
<del> it("should warn for missing required values", function() {
<del> typeCheckFail(
<del> PropTypes.arrayOf(PropTypes.number).isRequired, null, requiredMessage
<del> );
<del> typeCheckFail(
<del> PropTypes.arrayOf(PropTypes.number).isRequired, undefined, requiredMessage
<del> );
<add> it("should be implicitly optional and not warn without values", function() {
<add> typeCheckPass(PropTypes.arrayOf(PropTypes.number), null);
<add> typeCheckPass(PropTypes.arrayOf(PropTypes.number), undefined);
<add> });
<add>
<add> it("should warn for missing required values", function() {
<add> typeCheckFail(
<add> PropTypes.arrayOf(PropTypes.number).isRequired,
<add> null,
<add> requiredMessage
<add> );
<add> typeCheckFail(
<add> PropTypes.arrayOf(PropTypes.number).isRequired,
<add> undefined,
<add> requiredMessage
<add> );
<add> });
<ide> });
<del>});
<ide>
<del>describe('Component Type', function() {
<del> beforeEach(function() {
<del> require('mock-modules').dumpCache();
<del> ReactTestUtils = require('ReactTestUtils');
<del> Component = React.createClass({
<del> propTypes: {
<del> label: PropTypes.component.isRequired
<del> },
<add> describe('Component Type', function() {
<add> beforeEach(function() {
<add> Component = React.createClass({
<add> propTypes: {
<add> label: PropTypes.component.isRequired
<add> },
<ide>
<del> render: function() {
<del> return <div>{this.props.label}</div>;
<del> }
<add> render: function() {
<add> return <div>{this.props.label}</div>;
<add> }
<add> });
<add> spyOn(console, 'warn');
<ide> });
<del> spyOn(console, 'warn');
<del> });
<ide>
<del> it('should support components', () => {
<del> typeCheckPass(PropTypes.component, <div />);
<del> });
<add> it('should support components', () => {
<add> typeCheckPass(PropTypes.component, <div />);
<add> });
<ide>
<del> it('should not support multiple components or scalar values', () => {
<del> var message = 'Invalid prop `testProp` supplied to `testComponent`, ' +
<del> 'expected a React component.';
<del> typeCheckFail(PropTypes.component, [<div />, <div />], message);
<del> typeCheckFail(PropTypes.component, 123, message);
<del> typeCheckFail(PropTypes.component, 'foo', message);
<del> typeCheckFail(PropTypes.component, false, message);
<del> });
<add> it('should not support multiple components or scalar values', () => {
<add> var message = 'Invalid prop `testProp` supplied to `testComponent`, ' +
<add> 'expected a React component.';
<add> typeCheckFail(PropTypes.component, [<div />, <div />], message);
<add> typeCheckFail(PropTypes.component, 123, message);
<add> typeCheckFail(PropTypes.component, 'foo', message);
<add> typeCheckFail(PropTypes.component, false, message);
<add> });
<ide>
<del> it('should be able to define a single child as label', () => {
<del> var instance = <Component label={<div />} />;
<del> instance = ReactTestUtils.renderIntoDocument(instance);
<add> it('should be able to define a single child as label', () => {
<add> var instance = <Component label={<div />} />;
<add> instance = ReactTestUtils.renderIntoDocument(instance);
<ide>
<del> expect(console.warn.argsForCall.length).toBe(0);
<del> });
<add> expect(console.warn.argsForCall.length).toBe(0);
<add> });
<ide>
<del> it('should warn when passing no label and isRequired is set', () => {
<del> var instance = <Component />;
<del> instance = ReactTestUtils.renderIntoDocument(instance);
<add> it('should warn when passing no label and isRequired is set', () => {
<add> var instance = <Component />;
<add> instance = ReactTestUtils.renderIntoDocument(instance);
<ide>
<del> expect(console.warn.argsForCall.length).toBe(1);
<del> });
<add> expect(console.warn.argsForCall.length).toBe(1);
<add> });
<ide>
<del> it("should be implicitly optional and not warn without values", function() {
<del> typeCheckPass(PropTypes.component, null);
<del> typeCheckPass(PropTypes.component, undefined);
<del> });
<add> it("should be implicitly optional and not warn without values", function() {
<add> typeCheckPass(PropTypes.component, null);
<add> typeCheckPass(PropTypes.component, undefined);
<add> });
<ide>
<del> it("should warn for missing required values", function() {
<del> typeCheckFail(PropTypes.component.isRequired, null, requiredMessage);
<del> typeCheckFail(PropTypes.component.isRequired, undefined, requiredMessage);
<add> it("should warn for missing required values", function() {
<add> typeCheckFail(PropTypes.component.isRequired, null, requiredMessage);
<add> typeCheckFail(PropTypes.component.isRequired, undefined, requiredMessage);
<add> });
<ide> });
<del>});
<ide>
<del>describe('Instance Types', function() {
<del> it("should warn for invalid instances", function() {
<del> function Person() {}
<del> var personName = Person.name || '<<anonymous>>';
<del> var dateName = Date.name || '<<anonymous>>';
<del> var regExpName = RegExp.name || '<<anonymous>>';
<del>
<del> typeCheckFail(
<del> PropTypes.instanceOf(Person),
<del> false,
<del> 'Invalid prop `testProp` supplied to `testComponent`, expected ' +
<del> 'instance of `' + personName + '`.'
<del> );
<del> typeCheckFail(
<del> PropTypes.instanceOf(Person),
<del> {},
<del> 'Invalid prop `testProp` supplied to `testComponent`, expected ' +
<del> 'instance of `' + personName + '`.'
<del> );
<del> typeCheckFail(
<del> PropTypes.instanceOf(Person),
<del> '',
<del> 'Invalid prop `testProp` supplied to `testComponent`, expected ' +
<del> 'instance of `' + personName + '`.'
<del> );
<del> typeCheckFail(
<del> PropTypes.instanceOf(Date),
<del> {},
<del> 'Invalid prop `testProp` supplied to `testComponent`, expected ' +
<del> 'instance of `' + dateName + '`.'
<del> );
<del> typeCheckFail(
<del> PropTypes.instanceOf(RegExp),
<del> {},
<del> 'Invalid prop `testProp` supplied to `testComponent`, expected ' +
<del> 'instance of `' + regExpName + '`.'
<del> );
<del> });
<add> describe('Instance Types', function() {
<add> it("should warn for invalid instances", function() {
<add> function Person() {}
<add> var personName = Person.name || '<<anonymous>>';
<add> var dateName = Date.name || '<<anonymous>>';
<add> var regExpName = RegExp.name || '<<anonymous>>';
<ide>
<del> it("should not warn for valid values", function() {
<del> function Person() {}
<del> function Engineer() {}
<del> Engineer.prototype = new Person();
<add> typeCheckFail(
<add> PropTypes.instanceOf(Person),
<add> false,
<add> 'Invalid prop `testProp` supplied to `testComponent`, expected ' +
<add> 'instance of `' + personName + '`.'
<add> );
<add> typeCheckFail(
<add> PropTypes.instanceOf(Person),
<add> {},
<add> 'Invalid prop `testProp` supplied to `testComponent`, expected ' +
<add> 'instance of `' + personName + '`.'
<add> );
<add> typeCheckFail(
<add> PropTypes.instanceOf(Person),
<add> '',
<add> 'Invalid prop `testProp` supplied to `testComponent`, expected ' +
<add> 'instance of `' + personName + '`.'
<add> );
<add> typeCheckFail(
<add> PropTypes.instanceOf(Date),
<add> {},
<add> 'Invalid prop `testProp` supplied to `testComponent`, expected ' +
<add> 'instance of `' + dateName + '`.'
<add> );
<add> typeCheckFail(
<add> PropTypes.instanceOf(RegExp),
<add> {},
<add> 'Invalid prop `testProp` supplied to `testComponent`, expected ' +
<add> 'instance of `' + regExpName + '`.'
<add> );
<add> });
<ide>
<del> typeCheckPass(PropTypes.instanceOf(Person), new Person());
<del> typeCheckPass(PropTypes.instanceOf(Person), new Engineer());
<add> it("should not warn for valid values", function() {
<add> function Person() {}
<add> function Engineer() {}
<add> Engineer.prototype = new Person();
<ide>
<del> typeCheckPass(PropTypes.instanceOf(Date), new Date());
<del> typeCheckPass(PropTypes.instanceOf(RegExp), /please/);
<del> });
<add> typeCheckPass(PropTypes.instanceOf(Person), new Person());
<add> typeCheckPass(PropTypes.instanceOf(Person), new Engineer());
<ide>
<del> it("should be implicitly optional and not warn without values", function() {
<del> typeCheckPass(PropTypes.instanceOf(String), null);
<del> typeCheckPass(PropTypes.instanceOf(String), undefined);
<del> });
<add> typeCheckPass(PropTypes.instanceOf(Date), new Date());
<add> typeCheckPass(PropTypes.instanceOf(RegExp), /please/);
<add> });
<ide>
<del> it("should warn for missing required values", function() {
<del> typeCheckFail(
<del> PropTypes.instanceOf(String).isRequired, null, requiredMessage
<del> );
<del> typeCheckFail(
<del> PropTypes.instanceOf(String).isRequired, undefined, requiredMessage
<del> );
<del> });
<del>});
<add> it("should be implicitly optional and not warn without values", function() {
<add> typeCheckPass(PropTypes.instanceOf(String), null);
<add> typeCheckPass(PropTypes.instanceOf(String), undefined);
<add> });
<ide>
<del>describe('React Component Types', function() {
<del> beforeEach(function() {
<del> MyComponent = React.createClass({
<del> render: function() {
<del> return <div />;
<del> }
<add> it("should warn for missing required values", function() {
<add> typeCheckFail(
<add> PropTypes.instanceOf(String).isRequired, null, requiredMessage
<add> );
<add> typeCheckFail(
<add> PropTypes.instanceOf(String).isRequired, undefined, requiredMessage
<add> );
<ide> });
<ide> });
<ide>
<del> it('should warn for invalid values', function() {
<del> var failMessage = 'Invalid prop `testProp` supplied to `testComponent`, ' +
<del> 'expected a renderable prop.';
<del> typeCheckFail(PropTypes.renderable, true, failMessage);
<del> typeCheckFail(PropTypes.renderable, function() {}, failMessage);
<del> typeCheckFail(PropTypes.renderable, {key: function() {}}, failMessage);
<del> });
<add> describe('React Component Types', function() {
<add> beforeEach(function() {
<add> MyComponent = React.createClass({
<add> render: function() {
<add> return <div />;
<add> }
<add> });
<add> });
<ide>
<del> it('should not warn for valid values', function() {
<del> typeCheckPass(PropTypes.renderable, <div />);
<del> typeCheckPass(PropTypes.renderable, false);
<del> typeCheckPass(PropTypes.renderable, <MyComponent />);
<del> typeCheckPass(PropTypes.renderable, 'Some string');
<del> typeCheckPass(PropTypes.renderable, []);
<del> typeCheckPass(PropTypes.renderable, {});
<del> typeCheckPass(PropTypes.renderable, [
<del> 123,
<del> 'Some string',
<del> <div />,
<del> ['Another string', [456], <span />, <MyComponent />],
<del> <MyComponent />
<del> ]);
<del>
<del> // Object of rendereable things
<del> typeCheckPass(PropTypes.renderable, {
<del> k0: 123,
<del> k1: 'Some string',
<del> k2: <div />,
<del> k3: {
<del> k30: <MyComponent />,
<del> k31: {k310: <a />},
<del> k32: 'Another string'
<del> }
<add> it('should warn for invalid values', function() {
<add> var failMessage = 'Invalid prop `testProp` supplied to ' +
<add> '`testComponent`, expected a renderable prop.';
<add> typeCheckFail(PropTypes.renderable, true, failMessage);
<add> typeCheckFail(PropTypes.renderable, function() {}, failMessage);
<add> typeCheckFail(PropTypes.renderable, {key: function() {}}, failMessage);
<ide> });
<del> });
<ide>
<del> it('should not warn for null/undefined if not required', function() {
<del> typeCheckPass(PropTypes.renderable, null);
<del> typeCheckPass(PropTypes.renderable, undefined);
<del> });
<add> it('should not warn for valid values', function() {
<add> typeCheckPass(PropTypes.renderable, <div />);
<add> typeCheckPass(PropTypes.renderable, false);
<add> typeCheckPass(PropTypes.renderable, <MyComponent />);
<add> typeCheckPass(PropTypes.renderable, 'Some string');
<add> typeCheckPass(PropTypes.renderable, []);
<add> typeCheckPass(PropTypes.renderable, {});
<add> typeCheckPass(PropTypes.renderable, [
<add> 123,
<add> 'Some string',
<add> <div />,
<add> ['Another string', [456], <span />, <MyComponent />],
<add> <MyComponent />
<add> ]);
<add>
<add> // Object of rendereable things
<add> typeCheckPass(PropTypes.renderable, {
<add> k0: 123,
<add> k1: 'Some string',
<add> k2: <div />,
<add> k3: {
<add> k30: <MyComponent />,
<add> k31: {k310: <a />},
<add> k32: 'Another string'
<add> }
<add> });
<add> });
<ide>
<del> it('should warn for missing required values', function() {
<del> typeCheckFail(
<del> PropTypes.renderable.isRequired,
<del> null,
<del> 'Required prop `testProp` was not specified in `testComponent`.'
<del> );
<del> typeCheckFail(
<del> PropTypes.renderable.isRequired,
<del> undefined,
<del> 'Required prop `testProp` was not specified in `testComponent`.'
<del> );
<del> });
<add> it('should not warn for null/undefined if not required', function() {
<add> typeCheckPass(PropTypes.renderable, null);
<add> typeCheckPass(PropTypes.renderable, undefined);
<add> });
<ide>
<del> it('should accept empty array & object for required props', function() {
<del> typeCheckPass(PropTypes.renderable.isRequired, []);
<del> typeCheckPass(PropTypes.renderable.isRequired, {});
<del> });
<del>});
<add> it('should warn for missing required values', function() {
<add> typeCheckFail(
<add> PropTypes.renderable.isRequired,
<add> null,
<add> 'Required prop `testProp` was not specified in `testComponent`.'
<add> );
<add> typeCheckFail(
<add> PropTypes.renderable.isRequired,
<add> undefined,
<add> 'Required prop `testProp` was not specified in `testComponent`.'
<add> );
<add> });
<ide>
<del>describe('ObjectOf Type', function() {
<del> it('should support the objectOf propTypes', function() {
<del> typeCheckPass(PropTypes.objectOf(PropTypes.number), {a: 1, b: 2, c: 3});
<del> typeCheckPass(
<del> PropTypes.objectOf(PropTypes.string),
<del> {a: 'a', b: 'b', c: 'c'}
<del> );
<del> typeCheckPass(
<del> PropTypes.objectOf(PropTypes.oneOf(['a', 'b'])),
<del> {a: 'a', b: 'b'}
<del> );
<add> it('should accept empty array & object for required props', function() {
<add> typeCheckPass(PropTypes.renderable.isRequired, []);
<add> typeCheckPass(PropTypes.renderable.isRequired, {});
<add> });
<ide> });
<ide>
<del> it('should support objectOf with complex types', function() {
<del> typeCheckPass(
<del> PropTypes.objectOf(PropTypes.shape({a: PropTypes.number.isRequired})),
<del> {a: {a: 1}, b: {a: 2}}
<del> );
<del>
<del> function Thing() {}
<del> typeCheckPass(
<del> PropTypes.objectOf(PropTypes.instanceOf(Thing)),
<del> {a: new Thing(), b: new Thing()}
<del> );
<del> });
<add> describe('ObjectOf Type', function() {
<add> it('should support the objectOf propTypes', function() {
<add> typeCheckPass(PropTypes.objectOf(PropTypes.number), {a: 1, b: 2, c: 3});
<add> typeCheckPass(
<add> PropTypes.objectOf(PropTypes.string),
<add> {a: 'a', b: 'b', c: 'c'}
<add> );
<add> typeCheckPass(
<add> PropTypes.objectOf(PropTypes.oneOf(['a', 'b'])),
<add> {a: 'a', b: 'b'}
<add> );
<add> });
<ide>
<del> it('should warn with invalid items in the object', function() {
<del> typeCheckFail(
<del> PropTypes.objectOf(PropTypes.number),
<del> {a: 1, b: 2, c: 'b'},
<del> 'Invalid prop `c` of type `string` supplied to `testComponent`, ' +
<del> 'expected `number`.'
<del> );
<del> });
<add> it('should support objectOf with complex types', function() {
<add> typeCheckPass(
<add> PropTypes.objectOf(PropTypes.shape({a: PropTypes.number.isRequired})),
<add> {a: {a: 1}, b: {a: 2}}
<add> );
<ide>
<del> it('should warn with invalid complex types', function() {
<del> function Thing() {}
<del> var name = Thing.name || '<<anonymous>>';
<add> function Thing() {}
<add> typeCheckPass(
<add> PropTypes.objectOf(PropTypes.instanceOf(Thing)),
<add> {a: new Thing(), b: new Thing()}
<add> );
<add> });
<ide>
<del> typeCheckFail(
<del> PropTypes.objectOf(PropTypes.instanceOf(Thing)),
<del> {a: new Thing(), b: 'xyz'},
<del> 'Invalid prop `b` supplied to `testComponent`, expected instance of `' +
<del> name + '`.'
<del> );
<del> });
<add> it('should warn with invalid items in the object', function() {
<add> typeCheckFail(
<add> PropTypes.objectOf(PropTypes.number),
<add> {a: 1, b: 2, c: 'b'},
<add> 'Invalid prop `c` of type `string` supplied to `testComponent`, ' +
<add> 'expected `number`.'
<add> );
<add> });
<ide>
<del> it('should warn when passed something other than an object', function() {
<del> typeCheckFail(
<del> PropTypes.objectOf(PropTypes.number),
<del> [1, 2],
<del> 'Invalid prop `testProp` of type `array` supplied to `testComponent`, ' +
<del> 'expected an object.'
<del> );
<del> typeCheckFail(
<del> PropTypes.objectOf(PropTypes.number),
<del> 123,
<del> 'Invalid prop `testProp` of type `number` supplied to `testComponent`, ' +
<del> 'expected an object.'
<del> );
<del> typeCheckFail(
<del> PropTypes.objectOf(PropTypes.number),
<del> 'string',
<del> 'Invalid prop `testProp` of type `string` supplied to `testComponent`, ' +
<del> 'expected an object.'
<del> );
<del> });
<add> it('should warn with invalid complex types', function() {
<add> function Thing() {}
<add> var name = Thing.name || '<<anonymous>>';
<ide>
<del> it('should not warn when passing an empty object', function() {
<del> typeCheckPass(PropTypes.objectOf(PropTypes.number), {});
<del> });
<add> typeCheckFail(
<add> PropTypes.objectOf(PropTypes.instanceOf(Thing)),
<add> {a: new Thing(), b: 'xyz'},
<add> 'Invalid prop `b` supplied to `testComponent`, expected instance of `' +
<add> name + '`.'
<add> );
<add> });
<ide>
<del> it("should be implicitly optional and not warn without values", function() {
<del> typeCheckPass(PropTypes.objectOf(PropTypes.number), null);
<del> typeCheckPass(PropTypes.objectOf(PropTypes.number), undefined);
<del> });
<add> it('should warn when passed something other than an object', function() {
<add> typeCheckFail(
<add> PropTypes.objectOf(PropTypes.number),
<add> [1, 2],
<add> 'Invalid prop `testProp` of type `array` supplied to ' +
<add> '`testComponent`, expected an object.'
<add> );
<add> typeCheckFail(
<add> PropTypes.objectOf(PropTypes.number),
<add> 123,
<add> 'Invalid prop `testProp` of type `number` supplied to ' +
<add> '`testComponent`, expected an object.'
<add> );
<add> typeCheckFail(
<add> PropTypes.objectOf(PropTypes.number),
<add> 'string',
<add> 'Invalid prop `testProp` of type `string` supplied to ' +
<add> '`testComponent`, expected an object.'
<add> );
<add> });
<ide>
<del> it("should warn for missing required values", function() {
<del> typeCheckFail(
<del> PropTypes.objectOf(PropTypes.number).isRequired,
<del> null,
<del> requiredMessage
<del> );
<del> typeCheckFail(
<del> PropTypes.objectOf(PropTypes.number).isRequired,
<del> undefined,
<del> requiredMessage
<del> );
<del> });
<del>});
<add> it('should not warn when passing an empty object', function() {
<add> typeCheckPass(PropTypes.objectOf(PropTypes.number), {});
<add> });
<ide>
<del>describe('OneOf Types', function() {
<del> it("should warn for invalid strings", function() {
<del> typeCheckFail(
<del> PropTypes.oneOf(['red', 'blue']),
<del> true,
<del> 'Invalid prop `testProp` of value `true` supplied to `testComponent`, ' +
<del> 'expected one of ["red","blue"].'
<del> );
<del> typeCheckFail(
<del> PropTypes.oneOf(['red', 'blue']),
<del> [],
<del> 'Invalid prop `testProp` of value `` supplied to `testComponent`, ' +
<del> 'expected one of ["red","blue"].'
<del> );
<del> typeCheckFail(
<del> PropTypes.oneOf(['red', 'blue']),
<del> '',
<del> 'Invalid prop `testProp` of value `` supplied to `testComponent`, ' +
<del> 'expected one of ["red","blue"].'
<del> );
<del> typeCheckFail(
<del> PropTypes.oneOf([0, 'false']),
<del> false,
<del> 'Invalid prop `testProp` of value `false` supplied to `testComponent`, ' +
<del> 'expected one of [0,"false"].'
<del> );
<del> });
<add> it("should be implicitly optional and not warn without values", function() {
<add> typeCheckPass(PropTypes.objectOf(PropTypes.number), null);
<add> typeCheckPass(PropTypes.objectOf(PropTypes.number), undefined);
<add> });
<ide>
<del> it("should not warn for valid values", function() {
<del> typeCheckPass(PropTypes.oneOf(['red', 'blue']), 'red');
<del> typeCheckPass(PropTypes.oneOf(['red', 'blue']), 'blue');
<add> it("should warn for missing required values", function() {
<add> typeCheckFail(
<add> PropTypes.objectOf(PropTypes.number).isRequired,
<add> null,
<add> requiredMessage
<add> );
<add> typeCheckFail(
<add> PropTypes.objectOf(PropTypes.number).isRequired,
<add> undefined,
<add> requiredMessage
<add> );
<add> });
<ide> });
<ide>
<del> it("should be implicitly optional and not warn without values", function() {
<del> typeCheckPass(PropTypes.oneOf(['red', 'blue']), null);
<del> typeCheckPass(PropTypes.oneOf(['red', 'blue']), undefined);
<del> });
<add> describe('OneOf Types', function() {
<add> it("should warn for invalid strings", function() {
<add> typeCheckFail(
<add> PropTypes.oneOf(['red', 'blue']),
<add> true,
<add> 'Invalid prop `testProp` of value `true` supplied to ' +
<add> '`testComponent`, expected one of ["red","blue"].'
<add> );
<add> typeCheckFail(
<add> PropTypes.oneOf(['red', 'blue']),
<add> [],
<add> 'Invalid prop `testProp` of value `` supplied to `testComponent`, ' +
<add> 'expected one of ["red","blue"].'
<add> );
<add> typeCheckFail(
<add> PropTypes.oneOf(['red', 'blue']),
<add> '',
<add> 'Invalid prop `testProp` of value `` supplied to `testComponent`, ' +
<add> 'expected one of ["red","blue"].'
<add> );
<add> typeCheckFail(
<add> PropTypes.oneOf([0, 'false']),
<add> false,
<add> 'Invalid prop `testProp` of value `false` supplied to ' +
<add> '`testComponent`, expected one of [0,"false"].'
<add> );
<add> });
<ide>
<del> it("should warn for missing required values", function() {
<del> typeCheckFail(
<del> PropTypes.oneOf(['red', 'blue']).isRequired,
<del> null,
<del> requiredMessage
<del> );
<del> typeCheckFail(
<del> PropTypes.oneOf(['red', 'blue']).isRequired,
<del> undefined,
<del> requiredMessage
<del> );
<del> });
<del>});
<add> it("should not warn for valid values", function() {
<add> typeCheckPass(PropTypes.oneOf(['red', 'blue']), 'red');
<add> typeCheckPass(PropTypes.oneOf(['red', 'blue']), 'blue');
<add> });
<ide>
<del>describe('Union Types', function() {
<del> it('should warn if none of the types are valid', function() {
<del> typeCheckFail(
<del> PropTypes.oneOfType([PropTypes.string, PropTypes.number]),
<del> [],
<del> 'Invalid prop `testProp` supplied to `testComponent`.'
<del> );
<add> it("should be implicitly optional and not warn without values", function() {
<add> typeCheckPass(PropTypes.oneOf(['red', 'blue']), null);
<add> typeCheckPass(PropTypes.oneOf(['red', 'blue']), undefined);
<add> });
<ide>
<del> var checker = PropTypes.oneOfType([
<del> PropTypes.shape({a: PropTypes.number.isRequired}),
<del> PropTypes.shape({b: PropTypes.number.isRequired})
<del> ]);
<del> typeCheckFail(
<del> checker,
<del> {c: 1},
<del> 'Invalid prop `testProp` supplied to `testComponent`.'
<del> );
<add> it("should warn for missing required values", function() {
<add> typeCheckFail(
<add> PropTypes.oneOf(['red', 'blue']).isRequired,
<add> null,
<add> requiredMessage
<add> );
<add> typeCheckFail(
<add> PropTypes.oneOf(['red', 'blue']).isRequired,
<add> undefined,
<add> requiredMessage
<add> );
<add> });
<ide> });
<ide>
<del> it('should not warn if one of the types are valid', function() {
<del> var checker = PropTypes.oneOfType([
<del> PropTypes.string,
<del> PropTypes.number
<del> ]);
<del> typeCheckPass(checker, null);
<del> typeCheckPass(checker, 'foo');
<del> typeCheckPass(checker, 123);
<del>
<del> checker = PropTypes.oneOfType([
<del> PropTypes.shape({a: PropTypes.number.isRequired}),
<del> PropTypes.shape({b: PropTypes.number.isRequired})
<del> ]);
<del> typeCheckPass(checker, {a: 1});
<del> typeCheckPass(checker, {b: 1});
<del> });
<add> describe('Union Types', function() {
<add> it('should warn if none of the types are valid', function() {
<add> typeCheckFail(
<add> PropTypes.oneOfType([PropTypes.string, PropTypes.number]),
<add> [],
<add> 'Invalid prop `testProp` supplied to `testComponent`.'
<add> );
<ide>
<del> it("should be implicitly optional and not warn without values", function() {
<del> typeCheckPass(
<del> PropTypes.oneOfType([PropTypes.string, PropTypes.number]), null
<del> );
<del> typeCheckPass(
<del> PropTypes.oneOfType([PropTypes.string, PropTypes.number]), undefined
<del> );
<del> });
<add> var checker = PropTypes.oneOfType([
<add> PropTypes.shape({a: PropTypes.number.isRequired}),
<add> PropTypes.shape({b: PropTypes.number.isRequired})
<add> ]);
<add> typeCheckFail(
<add> checker,
<add> {c: 1},
<add> 'Invalid prop `testProp` supplied to `testComponent`.'
<add> );
<add> });
<ide>
<del> it("should warn for missing required values", function() {
<del> typeCheckFail(
<del> PropTypes.oneOfType([PropTypes.string, PropTypes.number]).isRequired,
<del> null,
<del> requiredMessage
<del> );
<del> typeCheckFail(
<del> PropTypes.oneOfType([PropTypes.string, PropTypes.number]).isRequired,
<del> undefined,
<del> requiredMessage
<del> );
<del> });
<del>});
<add> it('should not warn if one of the types are valid', function() {
<add> var checker = PropTypes.oneOfType([
<add> PropTypes.string,
<add> PropTypes.number
<add> ]);
<add> typeCheckPass(checker, null);
<add> typeCheckPass(checker, 'foo');
<add> typeCheckPass(checker, 123);
<add>
<add> checker = PropTypes.oneOfType([
<add> PropTypes.shape({a: PropTypes.number.isRequired}),
<add> PropTypes.shape({b: PropTypes.number.isRequired})
<add> ]);
<add> typeCheckPass(checker, {a: 1});
<add> typeCheckPass(checker, {b: 1});
<add> });
<ide>
<del>describe('Shape Types', function() {
<del> it("should warn for non objects", function() {
<del> typeCheckFail(
<del> PropTypes.shape({}),
<del> 'some string',
<del> 'Invalid prop `testProp` of type `string` supplied to `testComponent`, ' +
<del> 'expected `object`.'
<del> );
<del> typeCheckFail(
<del> PropTypes.shape({}),
<del> ['array'],
<del> 'Invalid prop `testProp` of type `array` supplied to `testComponent`, ' +
<del> 'expected `object`.'
<del> );
<del> });
<add> it("should be implicitly optional and not warn without values", function() {
<add> typeCheckPass(
<add> PropTypes.oneOfType([PropTypes.string, PropTypes.number]), null
<add> );
<add> typeCheckPass(
<add> PropTypes.oneOfType([PropTypes.string, PropTypes.number]), undefined
<add> );
<add> });
<ide>
<del> it("should not warn for empty values", function() {
<del> typeCheckPass(PropTypes.shape({}), undefined);
<del> typeCheckPass(PropTypes.shape({}), null);
<del> typeCheckPass(PropTypes.shape({}), {});
<add> it("should warn for missing required values", function() {
<add> typeCheckFail(
<add> PropTypes.oneOfType([PropTypes.string, PropTypes.number]).isRequired,
<add> null,
<add> requiredMessage
<add> );
<add> typeCheckFail(
<add> PropTypes.oneOfType([PropTypes.string, PropTypes.number]).isRequired,
<add> undefined,
<add> requiredMessage
<add> );
<add> });
<ide> });
<ide>
<del> it("should not warn for an empty object", function() {
<del> typeCheckPass(PropTypes.shape({}).isRequired, {});
<del> });
<add> describe('Shape Types', function() {
<add> it("should warn for non objects", function() {
<add> typeCheckFail(
<add> PropTypes.shape({}),
<add> 'some string',
<add> 'Invalid prop `testProp` of type `string` supplied to ' +
<add> '`testComponent`, expected `object`.'
<add> );
<add> typeCheckFail(
<add> PropTypes.shape({}),
<add> ['array'],
<add> 'Invalid prop `testProp` of type `array` supplied to ' +
<add> '`testComponent`, expected `object`.'
<add> );
<add> });
<ide>
<del> it("should not warn for non specified types", function() {
<del> typeCheckPass(PropTypes.shape({}), {key: 1});
<del> });
<add> it("should not warn for empty values", function() {
<add> typeCheckPass(PropTypes.shape({}), undefined);
<add> typeCheckPass(PropTypes.shape({}), null);
<add> typeCheckPass(PropTypes.shape({}), {});
<add> });
<ide>
<del> it("should not warn for valid types", function() {
<del> typeCheckPass(PropTypes.shape({key: PropTypes.number}), {key: 1});
<del> });
<add> it("should not warn for an empty object", function() {
<add> typeCheckPass(PropTypes.shape({}).isRequired, {});
<add> });
<ide>
<del> it("should warn for required valid types", function() {
<del> typeCheckFail(
<del> PropTypes.shape({key: PropTypes.number.isRequired}),
<del> {},
<del> 'Required prop `key` was not specified in `testComponent`.'
<del> );
<del> });
<add> it("should not warn for non specified types", function() {
<add> typeCheckPass(PropTypes.shape({}), {key: 1});
<add> });
<ide>
<del> it("should warn for the first required type", function() {
<del> typeCheckFail(
<del> PropTypes.shape({
<del> key: PropTypes.number.isRequired,
<del> secondKey: PropTypes.number.isRequired
<del> }),
<del> {},
<del> 'Required prop `key` was not specified in `testComponent`.'
<del> );
<del> });
<add> it("should not warn for valid types", function() {
<add> typeCheckPass(PropTypes.shape({key: PropTypes.number}), {key: 1});
<add> });
<ide>
<del> it("should warn for invalid key types", function() {
<del> typeCheckFail(PropTypes.shape({key: PropTypes.number}),
<del> {key: 'abc'},
<del> 'Invalid prop `key` of type `string` supplied to `testComponent`, ' +
<del> 'expected `number`.'
<del> );
<del> });
<add> it("should warn for required valid types", function() {
<add> typeCheckFail(
<add> PropTypes.shape({key: PropTypes.number.isRequired}),
<add> {},
<add> 'Required prop `key` was not specified in `testComponent`.'
<add> );
<add> });
<ide>
<del> it("should be implicitly optional and not warn without values", function() {
<del> typeCheckPass(
<del> PropTypes.shape(PropTypes.shape({key: PropTypes.number})), null
<del> );
<del> typeCheckPass(
<del> PropTypes.shape(PropTypes.shape({key: PropTypes.number})), undefined
<del> );
<del> });
<add> it("should warn for the first required type", function() {
<add> typeCheckFail(
<add> PropTypes.shape({
<add> key: PropTypes.number.isRequired,
<add> secondKey: PropTypes.number.isRequired
<add> }),
<add> {},
<add> 'Required prop `key` was not specified in `testComponent`.'
<add> );
<add> });
<ide>
<del> it("should warn for missing required values", function() {
<del> typeCheckFail(
<del> PropTypes.shape({key: PropTypes.number}).isRequired,
<del> null,
<del> requiredMessage
<del> );
<del> typeCheckFail(
<del> PropTypes.shape({key: PropTypes.number}).isRequired,
<del> undefined,
<del> requiredMessage
<del> );
<del> });
<del>});
<add> it("should warn for invalid key types", function() {
<add> typeCheckFail(PropTypes.shape({key: PropTypes.number}),
<add> {key: 'abc'},
<add> 'Invalid prop `key` of type `string` supplied to `testComponent`, ' +
<add> 'expected `number`.'
<add> );
<add> });
<ide>
<del>describe('Custom validator', function() {
<del> beforeEach(function() {
<del> require('mock-modules').dumpCache();
<del> ReactTestUtils = require('ReactTestUtils');
<del> spyOn(console, 'warn');
<del> });
<add> it("should be implicitly optional and not warn without values", function() {
<add> typeCheckPass(
<add> PropTypes.shape(PropTypes.shape({key: PropTypes.number})), null
<add> );
<add> typeCheckPass(
<add> PropTypes.shape(PropTypes.shape({key: PropTypes.number})), undefined
<add> );
<add> });
<ide>
<del> it('should have been called with the right params', function() {
<del> var spy = jasmine.createSpy();
<del> var Component = React.createClass({
<del> propTypes: {num: spy},
<add> it("should warn for missing required values", function() {
<add> typeCheckFail(
<add> PropTypes.shape({key: PropTypes.number}).isRequired,
<add> null,
<add> requiredMessage
<add> );
<add> typeCheckFail(
<add> PropTypes.shape({key: PropTypes.number}).isRequired,
<add> undefined,
<add> requiredMessage
<add> );
<add> });
<add> });
<ide>
<del> render: function() {
<del> return <div />;
<del> }
<add> describe('Custom validator', function() {
<add> beforeEach(function() {
<add> require('mock-modules').dumpCache();
<add> spyOn(console, 'warn');
<ide> });
<ide>
<del> var instance = <Component num={5} />;
<del> instance = ReactTestUtils.renderIntoDocument(instance);
<add> it('should have been called with the right params', function() {
<add> var spy = jasmine.createSpy();
<add> var Component = React.createClass({
<add> propTypes: {num: spy},
<ide>
<del> expect(spy.argsForCall.length).toBe(2); // temp double validation
<del> expect(spy.argsForCall[0][1]).toBe('num');
<del> expect(spy.argsForCall[0][2]).toBe('Component');
<del> });
<add> render: function() {
<add> return <div />;
<add> }
<add> });
<ide>
<del> it('should have been called even if the prop is not present', function() {
<del> var spy = jasmine.createSpy();
<del> var Component = React.createClass({
<del> propTypes: {num: spy},
<add> var instance = <Component num={5} />;
<add> instance = ReactTestUtils.renderIntoDocument(instance);
<ide>
<del> render: function() {
<del> return <div />;
<del> }
<add> expect(spy.argsForCall.length).toBe(2); // temp double validation
<add> expect(spy.argsForCall[0][1]).toBe('num');
<add> expect(spy.argsForCall[0][2]).toBe('Component');
<ide> });
<ide>
<del> var instance = <Component bla={5} />;
<del> instance = ReactTestUtils.renderIntoDocument(instance);
<del>
<del> expect(spy.argsForCall.length).toBe(2); // temp double validation
<del> });
<add> it('should have been called even if the prop is not present', function() {
<add> var spy = jasmine.createSpy();
<add> var Component = React.createClass({
<add> propTypes: {num: spy},
<ide>
<del> it('should have received the validator\'s return value', function() {
<del> var spy = jasmine.createSpy().andCallFake(
<del> function(props, propName, componentName) {
<del> if (props[propName] !== 5) {
<del> return new Error('num must be 5!');
<add> render: function() {
<add> return <div />;
<ide> }
<del> }
<del> );
<del> var Component = React.createClass({
<del> propTypes: {num: spy},
<add> });
<ide>
<del> render: function() {
<del> return <div />;
<del> }
<del> });
<add> var instance = <Component bla={5} />;
<add> instance = ReactTestUtils.renderIntoDocument(instance);
<ide>
<del> var instance = <Component num={6} />;
<del> instance = ReactTestUtils.renderIntoDocument(instance);
<del> expect(console.warn.argsForCall.length).toBe(1);
<del> expect(console.warn.argsForCall[0][0]).toBe('Warning: num must be 5!');
<del> });
<add> expect(spy.argsForCall.length).toBe(2); // temp double validation
<add> });
<ide>
<del> it('should not warn if the validator returned anything else than an error',
<del> function() {
<add> it('should have received the validator\'s return value', function() {
<ide> var spy = jasmine.createSpy().andCallFake(
<ide> function(props, propName, componentName) {
<del> return 'This message will never reach anyone';
<add> if (props[propName] !== 5) {
<add> return new Error('num must be 5!');
<add> }
<ide> }
<ide> );
<ide> var Component = React.createClass({
<ide> describe('Custom validator', function() {
<ide> }
<ide> });
<ide>
<del> var instance = <Component num={5} />;
<add> var instance = <Component num={6} />;
<ide> instance = ReactTestUtils.renderIntoDocument(instance);
<del> expect(console.warn.argsForCall.length).toBe(0);
<del> }
<del> );
<add> expect(console.warn.argsForCall.length).toBe(1);
<add> expect(console.warn.argsForCall[0][0]).toBe('Warning: num must be 5!');
<add> });
<add>
<add> it('should not warn if the validator returned anything else than an error',
<add> function() {
<add> var spy = jasmine.createSpy().andCallFake(
<add> function(props, propName, componentName) {
<add> return 'This message will never reach anyone';
<add> }
<add> );
<add> var Component = React.createClass({
<add> propTypes: {num: spy},
<add>
<add> render: function() {
<add> return <div />;
<add> }
<add> });
<add>
<add> var instance = <Component num={5} />;
<add> instance = ReactTestUtils.renderIntoDocument(instance);
<add> expect(console.warn.argsForCall.length).toBe(0);
<add> }
<add> );
<add> });
<ide> }); | 3 |
Python | Python | remove some comments out-dated | 3c4a64cd1924984e66f9a4515a4f88a8c672ba05 | <ide><path>official/nlp/bert/model_saving_utils.py
<ide> def export_bert_model(model_export_path: typing.Text,
<ide> raise ValueError('model must be a tf.keras.Model object.')
<ide>
<ide> if checkpoint_dir:
<del> # Keras compile/fit() was used to save checkpoint using
<del> # model.save_weights().
<ide> if restore_model_using_load_weights:
<ide> model_weight_path = os.path.join(checkpoint_dir, 'checkpoint')
<ide> assert tf.io.gfile.exists(model_weight_path)
<ide> model.load_weights(model_weight_path)
<del>
<del> # tf.train.Checkpoint API was used via custom training loop logic.
<ide> else:
<ide> checkpoint = tf.train.Checkpoint(model=model)
<ide> | 1 |
Javascript | Javascript | make sure linting passes | c8059b9f12939ae2290af7017cc93c03e50abe8f | <ide><path>examples/active-class-name/components/Link.js
<del>import { withRouter } from 'next/router';
<del>import Link from 'next/link';
<del>import React, { Children } from 'react';
<add>import { withRouter } from 'next/router'
<add>import Link from 'next/link'
<add>import React, { Children } from 'react'
<ide>
<ide> const ActiveLink = ({ router, children, ...props }) => {
<del> const child = Children.only(children);
<add> const child = Children.only(children)
<ide>
<del> let className = child.props.className || '';
<add> let className = child.props.className || ''
<ide> if (router.pathname === props.href && props.activeClassName) {
<del> className = `${className} ${props.activeClassName}`.trim();
<add> className = `${className} ${props.activeClassName}`.trim()
<ide> }
<ide>
<del> delete props.activeClassName;
<add> delete props.activeClassName
<ide>
<del> return <Link {...props}>{React.cloneElement(child, { className })}</Link>;
<del>};
<add> return <Link {...props}>{React.cloneElement(child, { className })}</Link>
<add>}
<ide>
<del>export default withRouter(ActiveLink);
<add>export default withRouter(ActiveLink)
<ide><path>examples/active-class-name/components/Nav.js
<del>import Link from './Link';
<del>import Head from 'next/head';
<add>import Link from './Link'
<ide>
<ide> export default () => (
<ide> <nav>
<ide> export default () => (
<ide>
<ide> <ul>
<ide> <li>
<del> <Link activeClassName="active" href="/">
<del> <a className="nav-link home-link">Home</a>
<add> <Link activeClassName='active' href='/'>
<add> <a className='nav-link home-link'>Home</a>
<ide> </Link>
<ide> </li>
<ide> <li>
<del> <Link activeClassName="active" href="/about">
<del> <a className="nav-link">About</a>
<add> <Link activeClassName='active' href='/about'>
<add> <a className='nav-link'>About</a>
<ide> </Link>
<ide> </li>
<ide> </ul>
<ide> </nav>
<del>);
<add>)
<ide><path>examples/active-class-name/pages/about.js
<del>import Nav from '../components/Nav';
<add>import Nav from '../components/Nav'
<ide>
<ide> export default () => (
<ide> <div>
<ide> <Nav />
<ide> <p>Hello, I'm About.js</p>
<ide> </div>
<del>);
<add>)
<ide><path>examples/active-class-name/pages/index.js
<del>import Nav from '../components/Nav';
<add>import Nav from '../components/Nav'
<ide>
<ide> export default () => (
<ide> <div>
<ide> <Nav />
<ide> <p>Hello, I'm the home page</p>
<ide> </div>
<del>);
<add>) | 4 |
Java | Java | fix code completion typo | e9ed45ee3b3deb1fd0cb5973829e132b48a7b290 | <ide><path>spring-web/src/main/java/org/springframework/web/context/request/async/WebAsyncManager.java
<ide> import org.springframework.util.Assert;
<ide> import org.springframework.web.context.request.RequestAttributes;
<ide> import org.springframework.web.context.request.async.DeferredResult.DeferredResultHandler;
<del>import org.springframework.web.server.adapter.WebHttpHandlerBuilder;
<ide>
<ide> /**
<ide> * The central class for managing asynchronous request processing, mainly intended
<ide> public final class WebAsyncManager {
<ide> private static final Object RESULT_NONE = new Object();
<ide>
<ide> private static final AsyncTaskExecutor DEFAULT_TASK_EXECUTOR =
<del> new SimpleAsyncTaskExecutor(WebHttpHandlerBuilder.class.getSimpleName());
<add> new SimpleAsyncTaskExecutor(WebAsyncManager.class.getSimpleName());
<ide>
<ide> private static final Log logger = LogFactory.getLog(WebAsyncManager.class);
<ide> | 1 |
PHP | PHP | update doc blocks | c272a8b3ca5c4e04c2739344e812b88079426e34 | <ide><path>lib/Cake/View/Helper/FormHelper.php
<ide> protected function _extractOption($name, $options, $default = null) {
<ide> * @param string $label
<ide> * @param array $options Options for the label element.
<ide> * @return string Generated label element
<add> * @deprecated 'NONE' option is deprecated and will be removed in 3.0
<ide> */
<ide> protected function _inputLabel($fieldName, $label, $options) {
<ide> $labelAttributes = $this->domId(array(), 'for');
<ide> public function meridian($fieldName, $attributes = array()) {
<ide> * matching the field name will override this value. If no default is provided `time()` will be used.
<ide> *
<ide> * @param string $fieldName Prefix name for the SELECT element
<del> * @param string $dateFormat DMY, MDY, YMD.
<del> * @param string $timeFormat 12, 24.
<add> * @param string $dateFormat DMY, MDY, YMD, or null to not generate date inputs.
<add> * @param string $timeFormat 12, 24, or null to not generate time inputs.
<ide> * @param string $attributes array of Attributes
<ide> * @return string Generated set of select boxes for the date and time formats chosen.
<ide> * @link http://book.cakephp.org/2.0/en/core-libraries/helpers/form.html#FormHelper::dateTime | 1 |
Go | Go | append new line to multiline events | 4374f16667708118c126cd71f733493b0070e807 | <ide><path>daemon/logger/awslogs/cloudwatchlogs.go
<ide> func (l *logStream) collectBatch() {
<ide> events = l.processEvent(events, eventBuffer, eventBufferTimestamp)
<ide> eventBuffer = eventBuffer[:0]
<ide> }
<del> eventBuffer = append(eventBuffer, unprocessedLine...)
<add> // Append new line
<add> processedLine := append(unprocessedLine, "\n"...)
<add> eventBuffer = append(eventBuffer, processedLine...)
<ide> logger.PutMessage(msg)
<ide> continue
<ide> }
<ide><path>daemon/logger/awslogs/cloudwatchlogs_test.go
<ide> func TestCollectBatchMultilinePattern(t *testing.T) {
<ide> argument := <-mockClient.putLogEventsArgument
<ide> assert.NotNil(t, argument, "Expected non-nil PutLogEventsInput")
<ide> assert.Equal(t, 1, len(argument.LogEvents), "Expected LogEvents to contain 1 elements, but contains %d", len(argument.LogEvents))
<del> assert.Equal(t, logline+logline, *argument.LogEvents[0].Message, "Expected message to be %s but was %s", logline+logline, *argument.LogEvents[0].Message)
<add> assert.Equal(t, logline+"\n"+logline+"\n", *argument.LogEvents[0].Message, "Expected message to be %s but was %s", logline+logline, *argument.LogEvents[0].Message)
<ide>
<ide> stream.Close()
<ide>
<ide> // Verify single event
<ide> argument = <-mockClient.putLogEventsArgument
<ide> assert.NotNil(t, argument, "Expected non-nil PutLogEventsInput")
<ide> assert.Equal(t, 1, len(argument.LogEvents), "Expected LogEvents to contain 1 elements, but contains %d", len(argument.LogEvents))
<del> assert.Equal(t, "xxxx "+logline, *argument.LogEvents[0].Message, "Expected message to be %s but was %s", "xxxx "+logline, *argument.LogEvents[0].Message)
<add> assert.Equal(t, "xxxx "+logline+"\n", *argument.LogEvents[0].Message, "Expected message to be %s but was %s", "xxxx "+logline, *argument.LogEvents[0].Message)
<ide> }
<ide>
<ide> func BenchmarkCollectBatch(b *testing.B) {
<ide> func TestCollectBatchMultilinePatternMaxEventAge(t *testing.T) {
<ide> argument := <-mockClient.putLogEventsArgument
<ide> assert.NotNil(t, argument, "Expected non-nil PutLogEventsInput")
<ide> assert.Equal(t, 1, len(argument.LogEvents), "Expected LogEvents to contain 1 elements, but contains %d", len(argument.LogEvents))
<del> assert.Equal(t, logline+logline, *argument.LogEvents[0].Message, "Expected message to be %s but was %s", logline+logline, *argument.LogEvents[0].Message)
<add> assert.Equal(t, logline+"\n"+logline+"\n", *argument.LogEvents[0].Message, "Expected message to be %s but was %s", logline+logline, *argument.LogEvents[0].Message)
<ide>
<ide> stream.Close()
<ide> }
<ide> func TestCollectBatchMultilinePatternNegativeEventAge(t *testing.T) {
<ide> argument := <-mockClient.putLogEventsArgument
<ide> assert.NotNil(t, argument, "Expected non-nil PutLogEventsInput")
<ide> assert.Equal(t, 1, len(argument.LogEvents), "Expected LogEvents to contain 1 elements, but contains %d", len(argument.LogEvents))
<del> assert.Equal(t, logline+logline, *argument.LogEvents[0].Message, "Expected message to be %s but was %s", logline+logline, *argument.LogEvents[0].Message)
<add> assert.Equal(t, logline+"\n"+logline+"\n", *argument.LogEvents[0].Message, "Expected message to be %s but was %s", logline+logline, *argument.LogEvents[0].Message)
<ide>
<ide> stream.Close()
<ide> } | 2 |
Ruby | Ruby | remove unused methods | f9ea47736e270152c264bb5f8fdbfaa1d04fe82f | <ide><path>activerecord/lib/active_record/fixtures.rb
<ide> def size
<ide> fixtures.size
<ide> end
<ide>
<del> def delete_existing_fixtures
<del> tables.each do |table|
<del> @connection.delete "DELETE FROM #{@connection.quote_table_name(table)}", 'Fixture Delete'
<del> end
<del> end
<del>
<del> # Return a list of tables this fixture effect. This is typically the +table_name+
<del> # along with any habtm tables specified via Foxy Fixtures.
<del> def tables
<del> [table_name] + fixtures.values.map { |fixture|
<del> row = fixture.to_hash
<del>
<del> # If STI is used, find the correct subclass for association reflection
<del> associations = []
<del> if model_class && model_class < ActiveRecord::Base
<del> reflection_class = row[inheritance_column_name].constantize rescue model_class
<del> associations = reflection_class.reflect_on_all_associations
<del> end
<del>
<del> foxy_habtms = associations.find_all { |assoc|
<del> assoc.macro == :has_and_belongs_to_many && row.key?(assoc.name.to_s)
<del> }
<del>
<del> foxy_habtms.map { |assoc| assoc.options[:join_table] }
<del> }.flatten.uniq
<del> end
<del>
<ide> # Return a hash of rows to be inserted. The key is the table, the value is
<ide> # a list of rows to insert to that table.
<ide> def table_rows
<ide> def table_rows
<ide> rows
<ide> end
<ide>
<del> def insert_fixtures
<del> table_rows.each do |table_name, rows|
<del> rows.each do |row|
<del> @connection.insert_fixture(row, table_name)
<del> end
<del> end
<del> end
<del>
<ide> private
<ide> def primary_key_name
<ide> @primary_key_name ||= model_class && model_class.primary_key
<ide><path>activerecord/test/cases/fixtures_test.rb
<ide> def test_omap_fixtures
<ide> end
<ide> end
<ide>
<del> def test_tables
<del> fixtures = Fixtures.new(Parrot.connection, 'parrots', 'Parrot', FIXTURES_ROOT + "/parrots")
<del> assert_equal %w{parrots parrots_treasures}, fixtures.tables
<del> end
<del>
<ide> def test_yml_file_in_subdirectory
<ide> assert_equal(categories(:sub_special_1).name, "A special category in a subdir file")
<ide> assert_equal(categories(:sub_special_1).class, SpecialCategory) | 2 |
Ruby | Ruby | fix build failures | 6cd9e2bd29b26e1ea781fafce18614217b7adf7b | <ide><path>activerecord/lib/active_record/fixtures.rb
<ide> def [](key)
<ide>
<ide> def find
<ide> if model_class
<del> model_class.unscoped.find(fixture[model_class.primary_key])
<add> model_class.unscoped do
<add> model_class.find(fixture[model_class.primary_key])
<add> end
<ide> else
<ide> raise FixtureClassNotFound, "No class attached to find."
<ide> end | 1 |
Python | Python | improve parallel test stability for warnings | 2f44aff7414fbca294d3309814dc60caf3cfae02 | <ide><path>numpy/testing/tests/test_utils.py
<ide> def test_regex(self):
<ide>
<ide>
<ide> def assert_warn_len_equal(mod, n_in_context, py34=None, py37=None):
<del> mod_warns = mod.__warningregistry__
<add> try:
<add> mod_warns = mod.__warningregistry__
<add> except AttributeError:
<add> # the lack of a __warningregistry__
<add> # attribute means that no warning has
<add> # occurred; this can be triggered in
<add> # a parallel test scenario, while in
<add> # a serial test scenario an initial
<add> # warning (and therefore the attribute)
<add> # are always created first
<add> mod_warns = {}
<add>
<ide> num_warns = len(mod_warns)
<ide> # Python 3.4 appears to clear any pre-existing warnings of the same type,
<ide> # when raising warnings inside a catch_warnings block. So, there is a
<ide> def assert_warn_len_equal(mod, n_in_context, py34=None, py37=None):
<ide> n_in_context = py34
<ide> assert_equal(num_warns, n_in_context)
<ide>
<add>def test_warn_len_equal_call_scenarios():
<add> # assert_warn_len_equal is called under
<add> # varying circumstances depending on serial
<add> # vs. parallel test scenarios; this test
<add> # simply aims to probe both code paths and
<add> # check that no assertion is uncaught
<add>
<add> # parallel scenario -- no warning issued yet
<add> class mod(object):
<add> pass
<add>
<add> mod_inst = mod()
<add>
<add> assert_warn_len_equal(mod=mod_inst,
<add> n_in_context=0)
<add>
<add> # serial test scenario -- the __warningregistry__
<add> # attribute should be present
<add> class mod(object):
<add> def __init__(self):
<add> self.__warningregistry__ = {'warning1':1,
<add> 'warning2':2}
<add>
<add> mod_inst = mod()
<add> assert_warn_len_equal(mod=mod_inst,
<add> n_in_context=2)
<add>
<ide>
<ide> def _get_fresh_mod():
<ide> # Get this module, with warning registry empty | 1 |
Go | Go | fix vet error about passing mutex by value | bb96e53b0f947a31a4b66e76607eed0097917ed5 | <ide><path>daemon/graphdriver/devmapper/deviceset.go
<ide> func (devices *DeviceSet) poolStatus() (totalSizeInSectors, transactionId, dataU
<ide>
<ide> // MetadataDevicePath returns the path to the metadata storage for this deviceset,
<ide> // regardless of loopback or block device
<del>func (devices DeviceSet) DataDevicePath() string {
<add>func (devices *DeviceSet) DataDevicePath() string {
<ide> return devices.dataDevice
<ide> }
<ide>
<ide> // MetadataDevicePath returns the path to the metadata storage for this deviceset,
<ide> // regardless of loopback or block device
<del>func (devices DeviceSet) MetadataDevicePath() string {
<add>func (devices *DeviceSet) MetadataDevicePath() string {
<ide> return devices.metadataDevice
<ide> }
<ide> | 1 |
Javascript | Javascript | add call validation in net-write-callbacks | f63af64eb8da6424243ead150e0b2dd718bd95e9 | <ide><path>lib/_stream_writable.js
<ide> function WritableState(options, stream) {
<ide> // or on a later tick.
<ide> this.sync = false;
<ide>
<add> // a flag to know if we're processing previously buffered items, which
<add> // may call the _write() callback in the same tick, so that we don't
<add> // end up in an overlapped onwrite situation.
<add> this.bufferProcessing = false;
<add>
<ide> // the callback that's passed to _write(chunk,cb)
<ide> this.onwrite = function(er) {
<ide> onwrite(stream, er);
<ide> function onwrite(stream, er) {
<ide>
<ide> if (cb) {
<ide> // Don't call the cb until the next tick if we're in sync mode.
<del> // Also defer if we're about to write some more right now.
<del> if (sync || state.buffer.length)
<add> if (sync)
<ide> process.nextTick(cb);
<ide> else
<ide> cb();
<ide> function onwrite(stream, er) {
<ide> return;
<ide> }
<ide>
<del> // if there's something in the buffer waiting, then do that, too.
<del> if (state.buffer.length) {
<del> var chunkCb = state.buffer.shift();
<del> var chunk = chunkCb[0];
<del> cb = chunkCb[1];
<del>
<del> if (false === state.decodeStrings)
<del> l = chunk[0].length;
<del> else
<del> l = chunk.length;
<del>
<del> state.writelen = l;
<del> state.writecb = cb;
<del> state.writechunk = chunk;
<del> state.writing = true;
<del> stream._write(chunk, state.onwrite);
<del> }
<del>
<ide> if (state.length <= state.lowWaterMark && state.needDrain) {
<ide> // Must force callback to be called on nextTick, so that we don't
<ide> // emit 'drain' before the write() consumer gets the 'false' return
<ide><path>test/pummel/test-net-write-callbacks.js
<ide> var server = net.Server(function(socket) {
<ide> });
<ide> });
<ide>
<add>var lastCalled = -1;
<add>function makeCallback(c) {
<add> var called = false;
<add> return function() {
<add> if (called)
<add> throw new Error('called callback #' + c + ' more than once');
<add> called = true;
<add> if (c < lastCalled)
<add> throw new Error('callbacks out of order. last=' + lastCalled +
<add> ' current=' + c);
<add> lastCalled = c;
<add> cbcount++;
<add> };
<add>}
<add>
<ide> server.listen(common.PORT, function() {
<ide> var client = net.createConnection(common.PORT);
<ide>
<ide> client.on('connect', function() {
<ide> for (var i = 0; i < N; i++) {
<del> client.write('hello world', function() {
<del> cbcount++;
<del> });
<add> client.write('hello world', makeCallback(i));
<ide> }
<ide> client.end();
<ide> }); | 2 |
Text | Text | add new frameworks and improve structure | 6cfc0030ce8a042da93d765fb23dc7427221524e | <ide><path>guide/english/python/using-python-for-web-development/index.md
<ide> Python is known for its beautiful syntax and ease of readability. This scripting
<ide>
<ide> #### Most Popular Python Web Frameworks:
<ide>
<del>* [Django](https://www.djangoproject.com/)
<del>* [Flask](http://flask.pocoo.org/)
<del>* [Bottle](https://bottlepy.org/docs/dev/)
<del>* [Pyramid](https://trypyramid.com/)
<del>* [Web2py](http://www.web2py.com/)
<add>* Full-Stack Frameworks
<add>
<add> 1. [Django](https://www.djangoproject.com/)
<add>
<add> 2. [Pyramid](https://trypyramid.com/)
<add>
<add> 3. [Web2py](http://www.web2py.com/)
<add>
<add> 4. [TurboGears](http://www.turbogears.org/)
<add>
<add>
<add>* Microframeworks
<add>
<add> 1. [Flask](http://flask.pocoo.org/)
<add>
<add> 2. [Bottle](https://bottlepy.org/docs/dev/)
<add>
<add> 3. [CherryPy](http://cherrypy.org/)
<add>
<add>
<add>* Asynchronous frameworks
<add>
<add> 1. [Sanic](http://sanic.readthedocs.io/en/latest/)
<add>
<add> 2. [Tornado](http://www.tornadoweb.org/en/latest/)
<add>
<add>
<add>* Other
<add>
<add> 1. [Dash](https://plot.ly/products/dash/)
<add>
<ide>
<ide> So let's get started with some web frameworks and learn how they help build web app on-hands. But before that, we would need to set-up the development environment by completing [installation of web frameworks in Python](https://guide.freecodecamp.org/python/setting-up-python-web-framework-django-and-flask). | 1 |
Go | Go | reuse cpuacct stats for cpu subsystem | 3bfe13de2c38fda5b57e2499f474da701495c5ba | <ide><path>pkg/cgroups/fs/cpu.go
<ide> func (s *cpuGroup) Remove(d *data) error {
<ide> }
<ide>
<ide> func (s *cpuGroup) Stats(d *data) (map[string]float64, error) {
<del> return nil, ErrNotSupportStat
<add> // we can reuse the cpuacct subsystem to get the cpu stats
<add> sys := subsystems["cpuacct"]
<add> return sys.Stats(d)
<ide> } | 1 |
Javascript | Javascript | use /system/bin/sh on android | f4f6c6e8151071d6d866603d0837d851fdf49157 | <ide><path>lib/child_process.js
<ide> function normalizeSpawnArguments(file /*, args, options*/) {
<ide> args = ['/s', '/c', '"' + command + '"'];
<ide> options.windowsVerbatimArguments = true;
<ide> } else {
<del> file = typeof options.shell === 'string' ? options.shell : '/bin/sh';
<add> if (typeof options.shell === 'string')
<add> file = options.shell;
<add> else if (process.platform === 'android')
<add> file = '/system/bin/sh';
<add> else
<add> file = '/bin/sh';
<ide> args = ['-c', command];
<ide> }
<ide> } | 1 |
PHP | PHP | remove trait by default | 8f6a4897a2af3549ed12a000e5336dfa9faded6d | <ide><path>tests/Feature/ExampleTest.php
<ide>
<ide> class ExampleTest extends TestCase
<ide> {
<del> use FreshDatabase;
<del>
<ide> /**
<ide> * A basic test example.
<ide> * | 1 |
Javascript | Javascript | run `yarn prettier-all` | a40ddf31246628423236ad1d8c6549409822e253 | <ide><path>packages/react-devtools-shared/src/utils.js
<ide> export function saveComponentFilters(
<ide>
<ide> export function getAppendComponentStack(): boolean {
<ide> try {
<del> const raw = localStorageGetItem(LOCAL_STORAGE_SHOULD_APPEND_COMPONENT_STACK_KEY);
<add> const raw = localStorageGetItem(
<add> LOCAL_STORAGE_SHOULD_APPEND_COMPONENT_STACK_KEY,
<add> );
<ide> if (raw != null) {
<ide> return JSON.parse(raw);
<ide> } | 1 |
Javascript | Javascript | add attributes used in input[type=range] | 415192c0017cdef4887678f4f94109c95147f344 | <ide><path>src/domUtils/DOMProperty.js
<ide> var Properties = {
<ide> height: null,
<ide> href: null,
<ide> htmlFor: null,
<add> max: null,
<ide> method: null,
<add> min: null,
<ide> multiple: MustUseProperty | HasBooleanValue,
<ide> name: null,
<ide> poster: null,
<ide> var Properties = {
<ide> selected: MustUseProperty | HasBooleanValue,
<ide> spellCheck: null,
<ide> src: null,
<add> step: null,
<ide> style: null,
<ide> tabIndex: null,
<ide> target: null, | 1 |
Javascript | Javascript | remove unnecessary global variable named global | a101fc768cedc7ac9754006e5b7292bb7084ab54 | <ide><path>Libraries/Core/setUpGlobals.js
<ide> * Sets up global variables for React Native.
<ide> * You can use this module directly, or just require InitializeCore.
<ide> */
<del>if (global.GLOBAL === undefined) {
<del> global.GLOBAL = global;
<del>}
<del>
<ide> if (global.window === undefined) {
<ide> // $FlowFixMe[cannot-write]
<ide> global.window = global; | 1 |
PHP | PHP | remove unused use statement | 601b39cc844b1446d64871d9bd6af210827a707c | <ide><path>src/Console/Shell.php
<ide> use Cake\Console\Exception\ConsoleException;
<ide> use Cake\Console\Exception\StopException;
<ide> use Cake\Core\App;
<del>use Cake\Core\Plugin;
<ide> use Cake\Datasource\ModelAwareTrait;
<ide> use Cake\Filesystem\File;
<ide> use Cake\Log\LogTrait; | 1 |
Ruby | Ruby | add test for calling a url helper in mapper#direct | d67e2520289745913e7bab9a852c86b99245f738 | <ide><path>actionpack/test/dispatch/routing/custom_url_helpers_test.rb
<ide> class Product < Linkable; end
<ide>
<ide> direct(:website) { "http://www.rubyonrails.org" }
<ide> direct("string") { "http://www.rubyonrails.org" }
<add> direct(:helper) { basket_url }
<ide> direct(:linkable) { |linkable| [:"#{linkable.linkable_type}", { id: linkable.id }] }
<ide> direct(:params) { |params| params }
<ide> direct(:symbol) { :basket }
<ide> def test_direct_paths
<ide> assert_equal "http://www.rubyonrails.org", string_path
<ide> assert_equal "http://www.rubyonrails.org", Routes.url_helpers.string_path
<ide>
<add> assert_equal "http://www.example.com/basket", helper_url
<add> assert_equal "http://www.example.com/basket", Routes.url_helpers.helper_url
<add>
<ide> assert_equal "/categories/1", linkable_path(@category)
<ide> assert_equal "/categories/1", Routes.url_helpers.linkable_path(@category)
<ide> assert_equal "/collections/2", linkable_path(@collection)
<ide> def test_direct_urls
<ide> assert_equal "http://www.rubyonrails.org", string_url
<ide> assert_equal "http://www.rubyonrails.org", Routes.url_helpers.string_url
<ide>
<add> assert_equal "http://www.example.com/basket", helper_url
<add> assert_equal "http://www.example.com/basket", Routes.url_helpers.helper_url
<add>
<ide> assert_equal "http://www.example.com/categories/1", linkable_url(@category)
<ide> assert_equal "http://www.example.com/categories/1", Routes.url_helpers.linkable_url(@category)
<ide> assert_equal "http://www.example.com/collections/2", linkable_url(@collection) | 1 |
Mixed | Python | fix some minor api issues | 61b18977f0960984c7a053101ae656ebc860a5c3 | <ide><path>research/maskgan/README.md
<ide> tested. Pretraining may not work correctly.
<ide>
<ide> For training on PTB:
<ide>
<del>1. (Optional) Pretrain a LM on PTB and store the checkpoint in /tmp/pretrain-lm/.
<add>1. (Optional) Pretrain a LM on PTB and store the checkpoint in `/tmp/pretrain-lm/`.
<ide> Instructions WIP.
<ide>
<del>2. (Optional) Run MaskGAN in MLE pretraining mode:
<add>2. (Optional) Run MaskGAN in MLE pretraining mode. If step 1 was not run, set
<add>`language_model_ckpt_dir` to empty.
<ide>
<ide> ```bash
<ide> python train_mask_gan.py \
<ide> python train_mask_gan.py \
<ide> --seq2seq_share_embedding
<ide> ```
<ide>
<del>3. Run MaskGAN in GAN mode:
<add>3. Run MaskGAN in GAN mode. If step 2 was not run, set `maskgan_ckpt` to empty.
<ide> ```bash
<ide> python train_mask_gan.py \
<ide> --data_dir='/tmp/ptb' \
<ide><path>research/maskgan/train_mask_gan.py
<ide> tf.app.flags.DEFINE_enum(
<ide> 'mode', 'TRAIN', [MODE_TRAIN, MODE_VALIDATION, MODE_TEST, MODE_TRAIN_EVAL],
<ide> 'What this binary will do.')
<del>tf.app.flags.DEFINE_string('master', 'local',
<add>tf.app.flags.DEFINE_string('master', '',
<ide> """Name of the TensorFlow master to use.""")
<del>tf.app.flags.DEFINE_string('eval_master', 'local',
<add>tf.app.flags.DEFINE_string('eval_master', '',
<ide> """Name prefix of the Tensorflow eval master,
<ide> or "local".""")
<ide> tf.app.flags.DEFINE_integer('task', 0,
<ide> def train_model(hparams, data, log_dir, log, id_to_word, data_ngram_counts):
<ide> is_chief = FLAGS.task == 0
<ide>
<ide> with tf.Graph().as_default():
<del> with tf.device(tf.ReplicaDeviceSetter(FLAGS.ps_tasks)):
<add> with tf.device(tf.train.replica_device_setter(FLAGS.ps_tasks)):
<ide> container_name = ''
<ide> with tf.container(container_name):
<ide> # Construct the model.
<ide> def train_model(hparams, data, log_dir, log, id_to_word, data_ngram_counts):
<ide>
<ide> # Create the supervisor. It will take care of initialization,
<ide> # summaries, checkpoints, and recovery.
<del> sv = tf.Supervisor(
<add> sv = tf.train.Supervisor(
<ide> logdir=log_dir,
<ide> is_chief=is_chief,
<ide> saver=model.saver, | 2 |
Ruby | Ruby | generate migration thats adds removed index | b2a59388b2ad281ccce1f72dd5fda09ca746dc32 | <ide><path>activerecord/lib/rails/generators/active_record/migration/templates/migration.rb
<ide> def down
<ide> <% attributes.reverse.each do |attribute| -%>
<ide> <%- if migration_action -%>
<ide> <%= migration_action == 'add' ? 'remove' : 'add' %>_column :<%= table_name %>, :<%= attribute.name %><% if migration_action == 'remove' %>, :<%= attribute.type %><%= attribute.inject_options %><% end %>
<add> <%- if attribute.has_index? && migration_action == 'remove' -%>
<add> add_index :<%= table_name %>, :<%= attribute.index_name %><%= attribute.inject_index_options %>
<add> <%- end %>
<ide> <%- end -%>
<ide> <%- end -%>
<ide> end
<ide><path>railties/test/generators/migration_generator_test.rb
<ide> def test_add_migration_with_attributes
<ide> end
<ide> end
<ide>
<add> def test_remove_migration_with_indexed_attribute
<add> migration = "remove_title_body_from_posts"
<add> run_generator [migration, "title:string:index", "body:text"]
<add>
<add> assert_migration "db/migrate/#{migration}.rb" do |content|
<add> assert_method :up, content do |up|
<add> assert_match(/remove_column :posts, :title/, up)
<add> assert_match(/remove_column :posts, :body/, up)
<add> end
<add>
<add> assert_method :down, content do |down|
<add> assert_match(/add_column :posts, :title, :string/, down)
<add> assert_match(/add_column :posts, :body, :text/, down)
<add> assert_match(/add_index :posts, :title/, down)
<add> end
<add> end
<add> end
<add>
<ide> def test_remove_migration_with_attributes
<ide> migration = "remove_title_body_from_posts"
<ide> run_generator [migration, "title:string", "body:text"] | 2 |
Mixed | Javascript | add drop event for net server | e3bf5e620bd465df4085df074d40127af3f4b4d8 | <ide><path>doc/api/net.md
<ide> added: v0.1.90
<ide>
<ide> Emitted when the server has been bound after calling [`server.listen()`][].
<ide>
<add>### Event: `'drop'`
<add>
<add><!-- YAML
<add>added: REPLACEME
<add>-->
<add>
<add>When the number of connections reaches the threshold of `server.maxConnections`,
<add>the server will drop new connections and emit `'drop'` event instead. If it is a
<add>TCP server, the argument is as follows, otherwise the argument is `undefined`.
<add>
<add>* `data` {Object} The argument passed to event listener.
<add> * `localAddress` {string} Local address.
<add> * `localPort` {number} Local port.
<add> * `remoteAddress` {string} Remote address.
<add> * `remotePort` {number} Remote port.
<add> * `remoteFamily` {string} Remote IP family. `'IPv4'` or `'IPv6'`.
<add>
<ide> ### `server.address()`
<ide>
<ide> <!-- YAML
<ide><path>lib/net.js
<ide> const {
<ide> ObjectDefineProperty,
<ide> ObjectSetPrototypeOf,
<ide> Symbol,
<add> ObjectCreate,
<ide> } = primordials;
<ide>
<ide> const EventEmitter = require('events');
<ide> function onconnection(err, clientHandle) {
<ide> }
<ide>
<ide> if (self.maxConnections && self._connections >= self.maxConnections) {
<add> if (clientHandle.getsockname || clientHandle.getpeername) {
<add> const data = ObjectCreate(null);
<add> if (clientHandle.getsockname) {
<add> const localInfo = ObjectCreate(null);
<add> clientHandle.getsockname(localInfo);
<add> data.localAddress = localInfo.address;
<add> data.localPort = localInfo.port;
<add> }
<add> if (clientHandle.getpeername) {
<add> const remoteInfo = ObjectCreate(null);
<add> clientHandle.getpeername(remoteInfo);
<add> data.remoteAddress = remoteInfo.address;
<add> data.remotePort = remoteInfo.port;
<add> data.remoteFamily = remoteInfo.family;
<add> }
<add> self.emit('drop', data);
<add> } else {
<add> self.emit('drop');
<add> }
<ide> clientHandle.close();
<ide> return;
<ide> }
<ide><path>test/parallel/test-net-server-drop-connections.js
<add>'use strict';
<add>const common = require('../common');
<add>const assert = require('assert');
<add>const net = require('net');
<add>
<add>let firstSocket;
<add>const server = net.createServer(common.mustCall((socket) => {
<add> firstSocket = socket;
<add>}));
<add>
<add>server.maxConnections = 1;
<add>
<add>server.on('drop', common.mustCall((data) => {
<add> assert.strictEqual(!!data.localAddress, true);
<add> assert.strictEqual(!!data.localPort, true);
<add> assert.strictEqual(!!data.remoteAddress, true);
<add> assert.strictEqual(!!data.remotePort, true);
<add> assert.strictEqual(!!data.remoteFamily, true);
<add> firstSocket.destroy();
<add> server.close();
<add>}));
<add>
<add>server.listen(0, () => {
<add> net.createConnection(server.address().port);
<add> net.createConnection(server.address().port);
<add>}); | 3 |
Python | Python | avoid redundant set conversion | 35c43987e5b0751a601a241ca321665301c197e3 | <ide><path>airflow/www/security.py
<ide> # under the License.
<ide> #
<ide>
<add>from typing import Set
<add>
<ide> from flask import current_app, g
<ide> from flask_appbuilder.security.sqla import models as sqla_models
<ide> from flask_appbuilder.security.sqla.manager import SecurityManager
<ide> def get_accessible_dags(self, user_action, user, session=None):
<ide>
<ide> return session.query(DagModel).filter(DagModel.dag_id.in_(resources))
<ide>
<del> def get_accessible_dag_ids(self, username=None):
<add> def get_accessible_dag_ids(self, username=None) -> Set[str]:
<ide> """
<ide> Return a set of dags that user has access to(either read or write).
<ide>
<ide><path>airflow/www/views.py
<ide> def dag_stats(self, session=None):
<ide> @provide_session
<ide> def task_stats(self, session=None):
<ide> """Task Statistics"""
<del> allowed_dag_ids = set(current_app.appbuilder.sm.get_accessible_dag_ids())
<add> allowed_dag_ids = current_app.appbuilder.sm.get_accessible_dag_ids()
<ide>
<ide> if not allowed_dag_ids:
<ide> return wwwutils.json_response({}) | 2 |
PHP | PHP | remove un-needed method overwrites | d059f904aaacf9cf7486c7f8d8443aa07f084709 | <ide><path>src/Illuminate/Database/Query/Grammars/PostgresGrammar.php
<ide> protected function whereDate(Builder $query, $where)
<ide> return $this->wrap($where['column']).'::date '.$where['operator'].' '.$value;
<ide> }
<ide>
<del> /**
<del> * Compile a "where day" clause.
<del> *
<del> * @param \Illuminate\Database\Query\Builder $query
<del> * @param array $where
<del> * @return string
<del> */
<del> protected function whereDay(Builder $query, $where)
<del> {
<del> return $this->dateBasedWhere('day', $query, $where);
<del> }
<del>
<del> /**
<del> * Compile a "where month" clause.
<del> *
<del> * @param \Illuminate\Database\Query\Builder $query
<del> * @param array $where
<del> * @return string
<del> */
<del> protected function whereMonth(Builder $query, $where)
<del> {
<del> return $this->dateBasedWhere('month', $query, $where);
<del> }
<del>
<del> /**
<del> * Compile a "where year" clause.
<del> *
<del> * @param \Illuminate\Database\Query\Builder $query
<del> * @param array $where
<del> * @return string
<del> */
<del> protected function whereYear(Builder $query, $where)
<del> {
<del> return $this->dateBasedWhere('year', $query, $where);
<del> }
<del>
<ide> /**
<ide> * Compile a date based where clause.
<ide> * | 1 |
Mixed | Text | add types and their corresponding return values | 5689d553920e6276065517966fcaf8e02f498fc1 | <ide><path>doc/api/async_hooks.md
<ide> alternative.
<ide>
<ide> #### asyncResource.emitDestroy()
<ide>
<add>* Returns: {AsyncResource} A reference to `asyncResource`.
<add>
<ide> Call all `destroy` hooks. This should only ever be called once. An error will
<ide> be thrown if it is called more than once. This **must** be manually called. If
<ide> the resource is left to be collected by the GC then the `destroy` hooks will
<ide><path>doc/api/crypto.md
<ide> changes:
<ide> * `generator` {number | string | Buffer | TypedArray | DataView} **Default:**
<ide> `2`
<ide> * `generatorEncoding` {string}
<add>* Returns: {DiffieHellman}
<ide>
<ide> Creates a `DiffieHellman` key exchange object using the supplied `prime` and an
<ide> optional specific `generator`.
<ide> added: v0.5.0
<ide> * `primeLength` {number}
<ide> * `generator` {number | string | Buffer | TypedArray | DataView} **Default:**
<ide> `2`
<add>* Returns: {DiffieHellman}
<ide>
<ide> Creates a `DiffieHellman` key exchange object and generates a prime of
<ide> `primeLength` bits using an optional specific numeric `generator`.
<ide> If `generator` is not specified, the value `2` is used.
<ide> added: v0.11.14
<ide> -->
<ide> * `curveName` {string}
<add>* Returns: {ECDH}
<ide>
<ide> Creates an Elliptic Curve Diffie-Hellman (`ECDH`) key exchange object using a
<ide> predefined curve specified by the `curveName` string. Use
<ide> console.log(curves); // ['Oakley-EC2N-3', 'Oakley-EC2N-4', ...]
<ide> added: v0.7.5
<ide> -->
<ide> * `groupName` {string}
<del>* Returns: {Object}
<add>* Returns: {DiffieHellman}
<ide>
<ide> Creates a predefined `DiffieHellman` key exchange object. The
<ide> supported groups are: `'modp1'`, `'modp2'`, `'modp5'` (defined in
<ide><path>doc/api/https.md
<ide> This class is a subclass of `tls.Server` and emits events same as
<ide> added: v0.1.90
<ide> -->
<ide> * `callback` {Function}
<add>* Returns: {https.Server}
<ide>
<ide> See [`server.close()`][`http.close()`] from the HTTP module for details.
<ide>
<ide> added: v0.11.2
<ide> -->
<ide> * `msecs` {number} **Default:** `120000` (2 minutes)
<ide> * `callback` {Function}
<add>* Returns: {https.Server}
<ide>
<ide> See [`http.Server#setTimeout()`][].
<ide>
<ide> added: v0.3.4
<ide> * `options` {Object} Accepts `options` from [`tls.createServer()`][],
<ide> [`tls.createSecureContext()`][] and [`http.createServer()`][].
<ide> * `requestListener` {Function} A listener to be added to the `'request'` event.
<add>* Returns: {https.Server}
<ide>
<ide> ```js
<ide> // curl -k https://localhost:8000/
<ide><path>doc/api/repl.md
<ide> changes:
<ide> * `breakEvalOnSigint` - Stop evaluating the current piece of code when
<ide> `SIGINT` is received, i.e. `Ctrl+C` is pressed. This cannot be used together
<ide> with a custom `eval` function. **Default:** `false`.
<add>* Returns: {repl.REPLServer}
<ide>
<ide> The `repl.start()` method creates and starts a [`repl.REPLServer`][] instance.
<ide>
<ide><path>doc/api/tls.md
<ide> added: v0.3.2
<ide>
<ide> * `callback` {Function} A listener callback that will be registered to listen
<ide> for the server instance's `'close'` event.
<add>* Returns: {tls.Server}
<ide>
<ide> The `server.close()` method stops the server from accepting new connections.
<ide>
<ide> changes:
<ide> * ...: [`tls.createSecureContext()`][] options that are used if the
<ide> `secureContext` option is missing, otherwise they are ignored.
<ide> * `callback` {Function}
<add>* Returns: {tls.TLSSocket}
<ide>
<ide> The `callback` function, if specified, will be added as a listener for the
<ide> [`'secureConnect'`][] event.
<ide> added: v0.11.3
<ide> * `path` {string} Default value for `options.path`.
<ide> * `options` {Object} See [`tls.connect()`][].
<ide> * `callback` {Function} See [`tls.connect()`][].
<add>* Returns: {tls.TLSSocket}
<ide>
<ide> Same as [`tls.connect()`][] except that `path` can be provided
<ide> as an argument instead of an option.
<ide> added: v0.11.3
<ide> * `host` {string} Default value for `options.host`.
<ide> * `options` {Object} See [`tls.connect()`][].
<ide> * `callback` {Function} See [`tls.connect()`][].
<add>* Returns: {tls.TLSSocket}
<ide>
<ide> Same as [`tls.connect()`][] except that `port` and `host` can be provided
<ide> as arguments instead of options.
<ide> changes:
<ide> * ...: Any [`tls.createSecureContext()`][] option can be provided. For
<ide> servers, the identity options (`pfx` or `key`/`cert`) are usually required.
<ide> * `secureConnectionListener` {Function}
<add>* Returns: {tls.Server}
<ide>
<ide> Creates a new [`tls.Server`][]. The `secureConnectionListener`, if provided, is
<ide> automatically set as a listener for the [`'secureConnection'`][] event.
<ide><path>tools/doc/type-parser.js
<ide> const customTypesMap = {
<ide> `${jsDocPrefix}Reference/Iteration_protocols#The_iterator_protocol`,
<ide>
<ide> 'AsyncHook': 'async_hooks.html#async_hooks_async_hooks_createhook_callbacks',
<add> 'AsyncResource': 'async_hooks.html#async_hooks_class_asyncresource',
<ide>
<ide> 'Buffer': 'buffer.html#buffer_class_buffer',
<ide>
<ide> const customTypesMap = {
<ide>
<ide> 'Cipher': 'crypto.html#crypto_class_cipher',
<ide> 'Decipher': 'crypto.html#crypto_class_decipher',
<add> 'DiffieHellman': 'crypto.html#crypto_class_diffiehellman',
<add> 'ECDH': 'crypto.html#crypto_class_ecdh',
<ide> 'Hash': 'crypto.html#crypto_class_hash',
<ide> 'Hmac': 'crypto.html#crypto_class_hmac',
<ide> 'Sign': 'crypto.html#crypto_class_sign',
<ide> const customTypesMap = {
<ide> 'Http2Stream': 'http2.html#http2_class_http2stream',
<ide> 'ServerHttp2Stream': 'http2.html#http2_class_serverhttp2stream',
<ide>
<add> 'https.Server': 'https.html#https_class_https_server',
<add>
<ide> 'module': 'modules.html#modules_the_module_object',
<ide>
<ide> 'Handle': 'net.html#net_server_listen_handle_backlog_callback',
<ide> const customTypesMap = {
<ide>
<ide> 'readline.Interface': 'readline.html#readline_class_interface',
<ide>
<add> 'repl.REPLServer': 'repl.html#repl_class_replserver',
<add>
<ide> 'Stream': 'stream.html#stream_stream',
<ide> 'stream.Duplex': 'stream.html#stream_class_stream_duplex',
<ide> 'stream.Readable': 'stream.html#stream_class_stream_readable', | 6 |
Javascript | Javascript | add extra newline for better formatting | cf9331ac662d5f4d4a4b8470277b42f3e51595b0 | <ide><path>test/ng/directive/ngOptionsSpec.js
<ide> describe('ngOptions', function() {
<ide> expect(element).toEqualSelectValue(scope.selected);
<ide> });
<ide>
<add>
<ide> it('should update options in the DOM', function() {
<ide> compile(
<ide> '<select ng-model="selected" ng-options="item.id as item.name for item in values"></select>' | 1 |
Javascript | Javascript | drop third parameter to replacestate/pushstate | e904b8a67c1bb94a8286dd69292dbace33027d5c | <ide><path>web/pdf_history.js
<ide> class PDFHistory {
<ide> this._updateInternalState(destination, newState.uid);
<ide>
<ide> if (shouldReplace) {
<del> if (typeof PDFJSDev !== 'undefined' &&
<del> PDFJSDev.test('FIREFOX || MOZCENTRAL')) {
<del> // Providing the third argument causes a SecurityError for file:// URLs.
<del> window.history.replaceState(newState, '');
<del> } else {
<del> window.history.replaceState(newState, '', document.URL);
<del> }
<add> window.history.replaceState(newState, '');
<ide> } else {
<ide> this._maxUid = this._uid;
<del>
<del> if (typeof PDFJSDev !== 'undefined' &&
<del> PDFJSDev.test('FIREFOX || MOZCENTRAL')) {
<del> // Providing the third argument causes a SecurityError for file:// URLs.
<del> window.history.pushState(newState, '');
<del> } else {
<del> window.history.pushState(newState, '', document.URL);
<del> }
<add> window.history.pushState(newState, '');
<ide> }
<ide>
<ide> if (typeof PDFJSDev !== 'undefined' && PDFJSDev.test('CHROME') && | 1 |
Javascript | Javascript | remove debug statement in appactions | 8109c65f8d43052a91e426b01a8f7d2bcf1e15eb | <ide><path>common/app/flux/Actions.js
<ide> import { Actions } from 'thundercats';
<del>import debugFactory from 'debug';
<ide>
<del>const debug = debugFactory('freecc:app:actions');
<ide>
<ide> export default Actions({
<ide> shouldBindMethods: true,
<ide> export default Actions({
<ide> return null;
<ide> }
<ide>
<del> debug('fetching user data');
<ide> return this.readService$('user', null, null)
<del> .map(function({
<add> .map(({
<ide> username,
<ide> picture,
<ide> progressTimestamps = [],
<ide> isFrontEndCert,
<ide> isFullStackCert
<del> }) {
<add> }) => {
<ide> return {
<ide> username,
<ide> picture, | 1 |
Text | Text | use plularized urls for better consistency | 27aa2d6aad59c479de66e270b897c4fa4fdbac30 | <ide><path>docs/api-guide/format-suffixes.md
<ide> Example:
<ide>
<ide> urlpatterns = patterns('blog.views',
<ide> url(r'^/$', 'api_root'),
<del> url(r'^comment/$', 'comment_list'),
<del> url(r'^comment/(?P<pk>[0-9]+)/$', 'comment_detail')
<add> url(r'^comments/$', 'comment_list'),
<add> url(r'^comments/(?P<pk>[0-9]+)/$', 'comment_detail')
<ide> )
<ide>
<ide> urlpatterns = format_suffix_patterns(urlpatterns, allowed=['json', 'html']) | 1 |
Ruby | Ruby | specify verification purposes | 15efa6720f9dc6efe27c717d9e32b31b2d45b7b8 | <ide><path>app/controllers/active_storage/disk_controller.rb
<ide> def disk_service
<ide> end
<ide>
<ide> def decode_verified_key
<del> ActiveStorage.verifier.verified(params[:encoded_key])
<add> ActiveStorage.verifier.verified(params[:encoded_key], purpose: :blob_key)
<ide> end
<ide>
<ide> def disposition_param
<ide><path>app/models/active_storage/blob.rb
<ide> class ActiveStorage::Blob < ActiveRecord::Base
<ide>
<ide> class << self
<ide> def find_signed(id)
<del> find ActiveStorage.verifier.verify(id)
<add> find ActiveStorage.verifier.verify(id, purpose: :blob_id)
<ide> end
<ide>
<ide> def build_after_upload(io:, filename:, content_type: nil, metadata: nil)
<ide> def create_before_direct_upload!(filename:, byte_size:, checksum:, content_type:
<ide>
<ide>
<ide> def signed_id
<del> ActiveStorage.verifier.generate(id)
<add> ActiveStorage.verifier.generate(id, purpose: :blob_id)
<ide> end
<ide>
<ide> def key
<ide><path>app/models/active_storage/service/disk_service.rb
<ide> def exist?(key)
<ide>
<ide> def url(key, expires_in:, disposition:, filename:)
<ide> instrument :url, key do |payload|
<del> verified_key_with_expiration = ActiveStorage.verifier.generate(key, expires_in: expires_in)
<add> verified_key_with_expiration = ActiveStorage.verifier.generate(key, expires_in: expires_in, purpose: :blob_key)
<ide>
<ide> generated_url =
<ide> if defined?(Rails) && defined?(Rails.application)
<ide><path>app/models/active_storage/variation.rb
<ide> class ActiveStorage::Variation
<ide>
<ide> class << self
<ide> def decode(key)
<del> new ActiveStorage.verifier.verify(key)
<add> new ActiveStorage.verifier.verify(key, purpose: :variation)
<ide> end
<ide>
<ide> def encode(transformations)
<del> ActiveStorage.verifier.generate(transformations)
<add> ActiveStorage.verifier.generate(transformations, purpose: :variation)
<ide> end
<ide> end
<ide>
<ide><path>test/controllers/disk_controller_test.rb
<ide> class ActiveStorage::DiskControllerTest < ActionController::TestCase
<ide> end
<ide>
<ide> test "showing blob inline" do
<del> get :show, params: { filename: @blob.filename, encoded_key: ActiveStorage.verifier.generate(@blob.key, expires_in: 5.minutes) }
<add> get :show, params: { filename: @blob.filename, encoded_key: ActiveStorage.verifier.generate(@blob.key, expires_in: 5.minutes, purpose: :blob_key) }
<ide> assert_equal "inline; filename=\"#{@blob.filename}\"", @response.headers["Content-Disposition"]
<ide> assert_equal "text/plain", @response.headers["Content-Type"]
<ide> end
<ide>
<ide> test "sending blob as attachment" do
<del> get :show, params: { filename: @blob.filename, encoded_key: ActiveStorage.verifier.generate(@blob.key, expires_in: 5.minutes), disposition: :attachment }
<add> get :show, params: { filename: @blob.filename, encoded_key: ActiveStorage.verifier.generate(@blob.key, expires_in: 5.minutes, purpose: :blob_key), disposition: :attachment }
<ide> assert_equal "attachment; filename=\"#{@blob.filename}\"", @response.headers["Content-Disposition"]
<ide> assert_equal "text/plain", @response.headers["Content-Type"]
<ide> end
<ide><path>test/models/blob_test.rb
<ide> class ActiveStorage::BlobTest < ActiveSupport::TestCase
<ide>
<ide> private
<ide> def expected_url_for(blob, disposition: :inline)
<del> "/rails/active_storage/disk/#{ActiveStorage.verifier.generate(blob.key, expires_in: 5.minutes)}/#{blob.filename}?disposition=#{disposition}"
<add> "/rails/active_storage/disk/#{ActiveStorage.verifier.generate(blob.key, expires_in: 5.minutes, purpose: :blob_key)}/#{blob.filename}?disposition=#{disposition}"
<ide> end
<ide> end | 6 |
Python | Python | add missing whitespace | e54a06ca81dd93cfda4570ae03740711092e08d3 | <ide><path>numpy/lib/tests/test_function_base.py
<ide> def test_period(self):
<ide> assert_array_equal(sm_discont, [0, 75, 150, 225, 300, 430])
<ide> assert sm_discont.dtype == wrap_uneven.dtype
<ide>
<add>
<ide> class TestFilterwindows:
<ide>
<ide> def test_hanning(self): | 1 |
Javascript | Javascript | add test for selection.each | f4a7a610f69bde9909e447f7e5e00f5ef9a4d151 | <ide><path>test/core/selection-each-test.js
<add>require("../env");
<add>require("../../d3");
<add>
<add>var vows = require("vows"),
<add> assert = require("assert");
<add>
<add>var suite = vows.describe("selection.each");
<add>
<add>suite.addBatch({
<add> "select(body)": {
<add> topic: function() {
<add> return d3.select("body").html("");
<add> },
<add> "calls the function once per element": function(body) {
<add> var count = 0;
<add> body.each(function() { ++count; });
<add> assert.equal(count, 1);
<add> },
<add> "passes the data and index to the function": function(body) {
<add> var data = new Object(), dd, ii;
<add> body.data([data]).each(function(d, i) { dd = d; ii = i; });
<add> assert.isTrue(dd === data);
<add> assert.isTrue(ii === 0);
<add> },
<add> "uses the node as the context": function(body) {
<add> var node;
<add> body.each(function() { node = this; });
<add> assert.isTrue(node === document.body);
<add> },
<add> "returns the same selection": function(body) {
<add> assert.isTrue(body.each(function() {}) === body);
<add> },
<add> "ignores null nodes": function() {
<add> var count = 0, body = d3.select("body");
<add> body[0][0] = null;
<add> body.each(function() { ++count; });
<add> assert.equal(count, 0);
<add> }
<add> }
<add>});
<add>
<add>suite.addBatch({
<add> "selectAll(div)": {
<add> topic: function() {
<add> return d3.select("body").html("").selectAll("div").data(d3.range(2)).enter().append("div");
<add> },
<add> "calls the function once per element": function(div) {
<add> var count = 0;
<add> div.each(function() { ++count; });
<add> assert.equal(count, 2);
<add> },
<add> "passes the data and index to the function": function(div) {
<add> var data = [new Object(), new Object()], dd = [], ii = [];
<add> div.data(data).each(function(d, i) { dd.push(d); ii.push(i); });
<add> assert.deepEqual(dd, data);
<add> assert.deepEqual(ii, [0, 1]);
<add> },
<add> "uses the node as the context": function(div) {
<add> var nodes = [];
<add> div.each(function() { nodes.push(this); });
<add> assert.equal(nodes.length, 2);
<add> assert.isTrue(div[0][0] == nodes[0]);
<add> assert.isTrue(div[0][1] == nodes[1]);
<add> },
<add> "returns the same selection": function(div) {
<add> assert.isTrue(div.each(function() {}) === div);
<add> },
<add> "ignores null nodes": function(div) {
<add> var count = 0, some = d3.selectAll("div");
<add> some[0][0] = null;
<add> some.each(function() { ++count; });
<add> assert.equal(count, 1);
<add> }
<add> }
<add>});
<add>
<add>suite.export(module); | 1 |
Ruby | Ruby | add an missing assertion to inheritance_test.rb | 8b80311e5ff412f2956be38535e05999fa57e12c | <ide><path>activerecord/test/cases/inheritance_test.rb
<ide> def test_different_namespace_subclass_should_load_correctly_with_store_full_sti_
<ide> end
<ide>
<ide> def test_company_descends_from_active_record
<add> assert !ActiveRecord::Base.descends_from_active_record?
<ide> assert AbstractCompany.descends_from_active_record?, 'AbstractCompany should descend from ActiveRecord::Base'
<ide> assert Company.descends_from_active_record?, 'Company should descend from ActiveRecord::Base'
<ide> assert !Class.new(Company).descends_from_active_record?, 'Company subclass should not descend from ActiveRecord::Base' | 1 |
Javascript | Javascript | add test for selection.remove | ca8476097d7fc7068a7691b1a63ba7b8f42046b3 | <ide><path>test/core/selection-remove-test.js
<add>require("../env");
<add>require("../../d3");
<add>
<add>var vows = require("vows"),
<add> assert = require("assert");
<add>
<add>var suite = vows.describe("selection.remove");
<add>
<add>suite.addBatch({
<add> "select(body)": {
<add> topic: function() {
<add> return d3.select("body");
<add> },
<add> "removes the matching elements": function(body) {
<add> var div = body.append("div");
<add> div.remove();
<add> assert.domNull(div[0][0].parentNode);
<add> },
<add> "does not remove non-matching elements": function(body) {
<add> var div1 = body.append("div"), div2 = body.append("div");
<add> div1.remove();
<add> assert.domEqual(div2[0][0].parentNode, document.body);
<add> },
<add> "ignores null nodes": function(body) {
<add> var div = body.html("").selectAll("div").data([0, 1]).enter().append("div"),
<add> some = d3.selectAll("div");
<add> some[0][0] = null;
<add> some.remove();
<add> assert.domEqual(div[0][0].parentNode, document.body);
<add> assert.domNull(div[0][1].parentNode);
<add> },
<add> "returns the current selection": function(body) {
<add> var div = body.append("div");
<add> assert.isTrue(div.remove() === div);
<add> }
<add> }
<add>});
<add>
<add>suite.export(module); | 1 |
PHP | PHP | apply fixes from styleci | 5390126e81d67368c543cbf2660b788e2faad731 | <ide><path>src/Illuminate/Support/Str.php
<ide>
<ide> namespace Illuminate\Support;
<ide>
<del>use Illuminate\Support\Arr;
<ide> use Illuminate\Support\Traits\Macroable;
<ide> use League\CommonMark\GithubFlavoredMarkdownConverter;
<ide> use Ramsey\Uuid\Codec\TimestampFirstCombCodec;
<ide><path>tests/Support/SupportStrTest.php
<ide> public function testReplaceLast()
<ide>
<ide> public function testRemove()
<ide> {
<del> $this->assertSame("Fbar", Str::remove('o', 'Foobar'));
<del> $this->assertSame("Foo", Str::remove('bar', 'Foobar'));
<del> $this->assertSame("oobar", Str::remove('F', 'Foobar'));
<del> $this->assertSame("Foobar", Str::remove('f', 'Foobar'));
<del> $this->assertSame("oobar", Str::remove('f', 'Foobar', false));
<del>
<del> $this->assertSame("Fbr", Str::remove(["o", "a"], 'Foobar'));
<del> $this->assertSame("Fooar", Str::remove(["f", "b"], 'Foobar'));
<del> $this->assertSame("ooar", Str::remove(["f", "b"], 'Foobar', false));
<del> $this->assertSame("Foobar", Str::remove(["f", "|"], 'Foo|bar'));
<add> $this->assertSame('Fbar', Str::remove('o', 'Foobar'));
<add> $this->assertSame('Foo', Str::remove('bar', 'Foobar'));
<add> $this->assertSame('oobar', Str::remove('F', 'Foobar'));
<add> $this->assertSame('Foobar', Str::remove('f', 'Foobar'));
<add> $this->assertSame('oobar', Str::remove('f', 'Foobar', false));
<add>
<add> $this->assertSame('Fbr', Str::remove(['o', 'a'], 'Foobar'));
<add> $this->assertSame('Fooar', Str::remove(['f', 'b'], 'Foobar'));
<add> $this->assertSame('ooar', Str::remove(['f', 'b'], 'Foobar', false));
<add> $this->assertSame('Foobar', Str::remove(['f', '|'], 'Foo|bar'));
<ide> }
<ide>
<ide> public function testSnake()
<ide><path>tests/Support/SupportStringableTest.php
<ide> namespace Illuminate\Tests\Support;
<ide>
<ide> use Illuminate\Support\Collection;
<del>use Illuminate\Support\Str;
<ide> use Illuminate\Support\Stringable;
<ide> use PHPUnit\Framework\TestCase;
<ide>
<ide> public function testReplaceLast()
<ide>
<ide> public function testRemove()
<ide> {
<del> $this->assertSame("Fbar", (string) $this->stringable('Foobar')->remove('o'));
<del> $this->assertSame("Foo", (string) $this->stringable('Foobar')->remove('bar'));
<del> $this->assertSame("oobar", (string) $this->stringable('Foobar')->remove('F'));
<del> $this->assertSame("Foobar", (string) $this->stringable('Foobar')->remove('f'));
<del> $this->assertSame("oobar", (string) $this->stringable('Foobar')->remove('f', false));
<add> $this->assertSame('Fbar', (string) $this->stringable('Foobar')->remove('o'));
<add> $this->assertSame('Foo', (string) $this->stringable('Foobar')->remove('bar'));
<add> $this->assertSame('oobar', (string) $this->stringable('Foobar')->remove('F'));
<add> $this->assertSame('Foobar', (string) $this->stringable('Foobar')->remove('f'));
<add> $this->assertSame('oobar', (string) $this->stringable('Foobar')->remove('f', false));
<ide>
<del> $this->assertSame("Fbr", (string) $this->stringable('Foobar')->remove(["o", "a"]));
<del> $this->assertSame("Fooar", (string) $this->stringable('Foobar')->remove(["f", "b"]));
<del> $this->assertSame("ooar", (string) $this->stringable('Foobar')->remove(["f", "b"], false));
<del> $this->assertSame("Foobar", (string) $this->stringable('Foo|bar')->remove(["f", "|"]));
<add> $this->assertSame('Fbr', (string) $this->stringable('Foobar')->remove(['o', 'a']));
<add> $this->assertSame('Fooar', (string) $this->stringable('Foobar')->remove(['f', 'b']));
<add> $this->assertSame('ooar', (string) $this->stringable('Foobar')->remove(['f', 'b'], false));
<add> $this->assertSame('Foobar', (string) $this->stringable('Foo|bar')->remove(['f', '|']));
<ide> }
<ide>
<ide> public function testSnake() | 3 |
Ruby | Ruby | rename these collections for clarity | a21be66fc868c9c343372e1fb798f68087acc95b | <ide><path>Library/Homebrew/build.rb
<ide> def install f
<ide> end
<ide>
<ide> if superenv?
<del> ENV.deps = keg_only_deps.map(&:to_s)
<del> ENV.all_deps = deps.map(&:to_s)
<add> ENV.keg_only_deps = keg_only_deps.map(&:to_s)
<add> ENV.deps = deps.map(&:to_s)
<ide> ENV.x11 = f.recursive_requirements.detect { |rq| rq.kind_of?(X11Dependency) }
<ide> ENV.setup_build_environment
<ide> post_superenv_hacks(f)
<ide><path>Library/Homebrew/superenv.rb
<ide> def superenv?
<ide> end
<ide>
<ide> class << ENV
<del> attr :deps, true
<del> attr :all_deps, true # above is just keg-only-deps
<del> attr :x11, true
<add> attr_accessor :keg_only_deps, :deps, :x11
<ide> alias_method :x11?, :x11
<ide>
<ide> def reset
<ide> def determine_path
<ide> paths << "#{MacSystem.xcode43_developer_dir}/usr/bin"
<ide> paths << "#{MacSystem.xcode43_developer_dir}/Toolchains/XcodeDefault.xctoolchain/usr/bin"
<ide> end
<del> paths += all_deps.map{|dep| "#{HOMEBREW_PREFIX}/opt/#{dep}/bin" }
<add> paths += deps.map{|dep| "#{HOMEBREW_PREFIX}/opt/#{dep}/bin" }
<ide> paths << "#{HOMEBREW_PREFIX}/opt/python/bin" if brewed_python?
<ide> paths << "#{MacSystem.x11_prefix}/bin" if x11?
<ide> paths += %w{/usr/bin /bin /usr/sbin /sbin}
<ide> paths.to_path_s
<ide> end
<ide>
<ide> def determine_pkg_config_path
<del> paths = all_deps.map{|dep| "#{HOMEBREW_PREFIX}/opt/#{dep}/lib/pkgconfig" }
<del> paths += all_deps.map{|dep| "#{HOMEBREW_PREFIX}/opt/#{dep}/share/pkgconfig" }
<add> paths = deps.map{|dep| "#{HOMEBREW_PREFIX}/opt/#{dep}/lib/pkgconfig" }
<add> paths += deps.map{|dep| "#{HOMEBREW_PREFIX}/opt/#{dep}/share/pkgconfig" }
<ide> paths.to_path_s
<ide> end
<ide>
<ide> def determine_pkg_config_libdir
<ide> end
<ide>
<ide> def determine_cmake_prefix_path
<del> paths = deps.map{|dep| "#{HOMEBREW_PREFIX}/opt/#{dep}" }
<add> paths = keg_only_deps.map{|dep| "#{HOMEBREW_PREFIX}/opt/#{dep}" }
<ide> paths << HOMEBREW_PREFIX.to_s # put ourselves ahead of everything else
<ide> paths << "#{MacOS.sdk_path}/usr" if MacSystem.xcode43_without_clt?
<ide> paths.to_path_s
<ide> def determine_cmake_library_path
<ide> end
<ide>
<ide> def determine_aclocal_path
<del> paths = deps.map{|dep| "#{HOMEBREW_PREFIX}/opt/#{dep}/share/aclocal" }
<add> paths = keg_only_deps.map{|dep| "#{HOMEBREW_PREFIX}/opt/#{dep}/share/aclocal" }
<ide> paths << "#{HOMEBREW_PREFIX}/share/aclocal"
<ide> paths << "/opt/X11/share/aclocal" if x11?
<ide> paths.to_path_s
<ide> def + value
<ide> # we must do this or tools like pkg-config won't get found by configure scripts etc.
<ide> ENV.prepend 'PATH', "#{HOMEBREW_PREFIX}/bin", ':' unless ORIGINAL_PATHS.include? HOMEBREW_PREFIX/'bin'
<ide> else
<add> ENV.keg_only_deps = []
<ide> ENV.deps = []
<del> ENV.all_deps = []
<ide> end
<ide>
<ide> | 2 |
Javascript | Javascript | save a byte | 1052f9cb2bad094144fa1186b0be8f477a9d4fa1 | <ide><path>src/attributes.js
<ide> jQuery.extend({
<ide> ret = elem.getAttribute( name );
<ide>
<ide> // Non-existent attributes return null, we normalize to undefined
<del> return ret === null ?
<add> return ret == null ?
<ide> undefined :
<ide> ret;
<ide> }
<ide> if ( !jQuery.support.hrefNormalized ) {
<ide> jQuery.attrHooks[ name ] = jQuery.extend( jQuery.attrHooks[ name ], {
<ide> get: function( elem ) {
<ide> var ret = elem.getAttribute( name, 2 );
<del> return ret === null ? undefined : ret;
<add> return ret == null ? undefined : ret;
<ide> }
<ide> });
<ide> }); | 1 |
Text | Text | update docker guide with more info | 6b9e81cfdf692f90436c53f339a4bc09c739eafb | <ide><path>guide/english/docker/index.md
<ide> sh get-docker.sh
<ide> * For download and documentation check the docker official site: [Docker official site](https://www.docker.com)
<ide> * For more on containerization, checkout [Search IT Operations](https://searchitoperations.techtarget.com/definition/application-containerization-app-containerization)
<ide> * A Docker 101 course [Docker 101](https://github.com/docker/labs/tree/master/beginner/)
<add>* Online Docker [Classroom](https://training.play-with-docker.com/)
<ide> | 1 |
Text | Text | add comma to to make the information clear | d2a7b9898b89b5e96b840b7b79ac97502d99aff5 | <ide><path>guides/source/form_helpers.md
<ide> NOTE: If the user has not selected a file the corresponding parameter will be an
<ide>
<ide> ### Dealing with Ajax
<ide>
<del>Unlike other forms making an asynchronous file upload form is not as simple as providing `form_for` with `remote: true`. With an Ajax form the serialization is done by JavaScript running inside the browser and since JavaScript cannot read files from your hard drive the file cannot be uploaded. The most common workaround is to use an invisible iframe that serves as the target for the form submission.
<add>Unlike other forms, making an asynchronous file upload form is not as simple as providing `form_for` with `remote: true`. With an Ajax form the serialization is done by JavaScript running inside the browser and since JavaScript cannot read files from your hard drive the file cannot be uploaded. The most common workaround is to use an invisible iframe that serves as the target for the form submission.
<ide>
<ide> Customizing Form Builders
<ide> ------------------------- | 1 |
Javascript | Javascript | add posyt to showcase.js | 4e1ff687dd8f1175af60c1c2bf5b6f77c0a287be | <ide><path>website/src/react-native/showcase.js
<ide> var apps = [
<ide> link: 'https://itunes.apple.com/gb/app/night-light-feeding-light/id1016843582?mt=8',
<ide> author: 'Tian Yuan',
<ide> },
<add> {
<add> name: 'Posyt - Tinder for ideas',
<add> icon: 'http://a3.mzstatic.com/us/r30/Purple6/v4/a5/b3/86/a5b38618-a5e9-6089-7425-7fa51ecd5d30/icon175x175.jpeg',
<add> link: 'https://itunes.apple.com/us/app/posyt-anonymously-meet-right/id1037842845?mt=8',
<add> author: 'Posyt.com',
<add> },
<ide> {
<ide> name: 'ReactTo36',
<ide> icon: 'http://is2.mzstatic.com/image/pf/us/r30/Purple5/v4/e3/c8/79/e3c87934-70c6-4974-f20d-4adcfc68d71d/mzl.wevtbbkq.png', | 1 |
Java | Java | treat empty accept header as "*/*" | 4221a344dc799314b2a4711838e6f1a152811ec1 | <ide><path>spring-webflux/src/main/java/org/springframework/web/reactive/function/server/RequestPredicates.java
<ide>
<ide> import java.net.URI;
<ide> import java.util.Arrays;
<add>import java.util.Collections;
<ide> import java.util.HashSet;
<ide> import java.util.List;
<ide> import java.util.Map;
<ide> import org.springframework.http.MediaType;
<ide> import org.springframework.http.server.reactive.ServerHttpRequest;
<ide> import org.springframework.util.Assert;
<del>import org.springframework.util.StringUtils;
<ide> import org.springframework.web.reactive.function.BodyExtractor;
<ide> import org.springframework.web.server.WebSession;
<ide> import org.springframework.web.util.UriUtils;
<ide> public static RequestPredicate accept(MediaType... mediaTypes) {
<ide> @Override
<ide> public boolean test(ServerRequest.Headers headers) {
<ide> List<MediaType> acceptedMediaTypes = headers.accept();
<del> MediaType.sortBySpecificityAndQuality(acceptedMediaTypes);
<add> if (acceptedMediaTypes.isEmpty()) {
<add> acceptedMediaTypes = Collections.singletonList(MediaType.ALL);
<add> }
<add> else {
<add> MediaType.sortBySpecificityAndQuality(acceptedMediaTypes);
<add> }
<ide> boolean match = acceptedMediaTypes.stream()
<ide> .anyMatch(acceptedMediaType -> mediaTypeSet.stream()
<ide> .anyMatch(acceptedMediaType::isCompatibleWith));
<ide><path>spring-webflux/src/test/java/org/springframework/web/reactive/function/server/RequestPredicatesTests.java
<ide> public void accept() throws Exception {
<ide> MockServerRequest request = MockServerRequest.builder().header("Accept", json.toString()).build();
<ide> assertTrue(predicate.test(request));
<ide>
<del> request = MockServerRequest.builder().build();
<add> request = MockServerRequest.builder().header("Accept", MediaType.TEXT_XML_VALUE).build();
<ide> assertFalse(predicate.test(request));
<ide> }
<ide> | 2 |
Javascript | Javascript | add @param and @returns tags | e3bf1ed21745dad75866623a7b7a8828237b0527 | <ide><path>src/Angular.js
<ide> noop.$inject = [];
<ide> return (transformationFn || angular.identity)(value);
<ide> };
<ide> ```
<add> * @param {*} value to be returned.
<add> * @returns {*} the value passed in.
<ide> */
<ide> function identity($) {return $;}
<ide> identity.$inject = []; | 1 |
Text | Text | add github package items | 5d8e95b87a541ce478e5ca7186bd2a783a4b2a10 | <ide><path>docs/focus/2018-04-02.md
<ide>
<ide> - Atom IDE
<ide> - GitHub Package
<add> - Implement actions for most recent commit - undo and amend [atom/github#1364](https://github.com/atom/github/pull/1364)
<add> - Improved push/pull UX [atom/github#1308](https://github.com/atom/github/pull/1308)
<ide> - Teletype
<ide> - Published [Teletype 0.11.0](https://github.com/atom/teletype/releases/tag/v.0.11.0) with support for [sharing and joining a portal via URL](https://blog.atom.io/2018/03/29/new-in-teletype-faster-setup-and-improved-multi-file-support.html#joining-a-portal-is-as-easy-as-clicking-a-link)
<ide> - Updated RFC for streamlining collaboration set-up to incorporate feedback, and opened it up for another round of comments ([atom/teletype#344](https://github.com/atom/teletype/pull/344))
<ide> - GitHub Package
<ide> - Bring [atom/github#1138](https://github.com/atom/github/pull/1138) "create new pull request" over the finish line
<ide> - Write "vision" documents in atom/github
<add> - Implement prompt for adding a co-author who is not yet in the commit history for the repository
<ide> - Teletype
<ide> - Publish patch release with [potential fix](https://github.com/atom/teletype-client/pull/58) for [atom/teletype#233](https://github.com/atom/teletype/issues/233)
<ide> - Incorporate any new feedback and finalize RFC for streamlining collaboration set-up ([atom/teletype#344](https://github.com/atom/teletype/pull/344)) | 1 |
PHP | PHP | throw broadcast exception | dc5f1317364ac426b326052c213742b48316cb99 | <ide><path>src/Illuminate/Broadcasting/Broadcasters/PusherBroadcaster.php
<ide> namespace Illuminate\Broadcasting\Broadcasters;
<ide>
<ide> use Pusher;
<del>use RuntimeException;
<ide> use Illuminate\Support\Arr;
<ide> use Illuminate\Support\Str;
<add>use Illuminate\Broadcasting\BroadcastException;
<ide> use Symfony\Component\HttpKernel\Exception\HttpException;
<ide>
<ide> class PusherBroadcaster extends Broadcaster
<ide> public function broadcast(array $channels, $event, array $payload = [])
<ide>
<ide> $response = $this->pusher->trigger($this->formatChannels($channels), $event, $payload, $socket);
<ide>
<del> if ((is_array($response) && $response['status'] == 200) || $response === true) {
<add> if ((is_array($response) && $response['status'] >= 200 && $response['status'] <= 299)
<add> || $response === true) {
<ide> return;
<ide> }
<ide>
<del> throw new RuntimeException(
<add> throw new BroadcastException(
<ide> is_bool($response) ? 'Failed to connect to Pusher.' : $response['body']
<ide> );
<ide> } | 1 |
Javascript | Javascript | handle miscs better | 7af2d6b985192c17b68b7b1c4952df452d0e6f84 | <ide><path>tools/doc/json.js
<ide> function finishSection(section, parent) {
<ide>
<ide> if (!section.type) {
<ide> section.type = 'module';
<add> if (parent && (parent.type === 'misc')) {
<add> section.type = 'misc';
<add> }
<ide> section.displayName = section.name;
<ide> section.name = section.name.toLowerCase()
<ide> .trim().replace(/\s+/g, '_');
<ide> function finishSection(section, parent) {
<ide> case 'miscs':
<ide> return;
<ide> default:
<add> if (parent.type === 'misc') {
<add> return;
<add> }
<ide> if (Array.isArray(k) && parent[k]) {
<ide> parent[k] = parent[k].concat(section[k]);
<ide> } else if (!parent[k]) { | 1 |
PHP | PHP | correct doc blocks for authcomponent | a36456cc876ed52470beba92f28b0e245de6fe40 | <ide><path>lib/Cake/Controller/Component/AuthComponent.php
<ide> class AuthComponent extends Component {
<ide>
<ide> /**
<ide> * An URL (defined as a string or array) to the controller action that handles
<del> * logins. Defaults to `/users/login`
<add> * logins. Defaults to `/users/login`.
<ide> *
<ide> * @var mixed
<ide> */
<ide> class AuthComponent extends Component {
<ide> public $response;
<ide>
<ide> /**
<del> * Method list for bound controller
<add> * Method list for bound controller.
<ide> *
<ide> * @var array
<ide> */
<ide> protected $_methods = array();
<ide>
<ide> /**
<del> * Initializes AuthComponent for use in the controller
<add> * Initializes AuthComponent for use in the controller.
<ide> *
<ide> * @param Controller $controller A reference to the instantiating controller object
<ide> * @return void
<ide> public function login($user = null) {
<ide> /**
<ide> * Log a user out.
<ide> *
<del> * Returns the login action to redirect to. Triggers the logout() method of
<add> * Returns the logout action to redirect to. Triggers the logout() method of
<ide> * all the authenticate objects, so they can perform custom logout logic.
<ide> * AuthComponent will remove the session data, so there is no need to do that
<ide> * in an authentication object. Logging out will also renew the session id.
<ide> protected function _getUser() {
<ide> }
<ide>
<ide> /**
<del> * Backwards compatible alias for AuthComponent::redirectUrl()
<add> * Backwards compatible alias for AuthComponent::redirectUrl().
<ide> *
<ide> * @param string|array $url Optional URL to write as the login redirect URL.
<ide> * @return string Redirect URL
<ide> public function identify(CakeRequest $request, CakeResponse $response) {
<ide> }
<ide>
<ide> /**
<del> * loads the configured authentication objects.
<add> * Loads the configured authentication objects.
<ide> *
<ide> * @return mixed either null on empty authenticate value, or an array of loaded objects.
<ide> * @throws CakeException | 1 |
Ruby | Ruby | fix rubocop warnings | cc526601cfe14861260b76359f6f1a2ec5fa33d2 | <ide><path>Library/Homebrew/cmd/update-report.rb
<ide> def migrate_legacy_cache_if_necessary
<ide> world_writable = legacy_cache.stat.mode & 0777 == 0777
<ide> return if world_writable
<ide> return if legacy_cache.symlink?
<del> return if !legacy_cache.owned? && legacy_cache.lstat.uid != 0
<add> return if !legacy_cache.owned? && legacy_cache.lstat.uid.nonzero?
<ide>
<ide> ohai "Migrating #{legacy_cache} to #{HOMEBREW_CACHE}..."
<ide> HOMEBREW_CACHE.mkpath
<ide> legacy_cache.cd do
<ide> legacy_cache.entries.each do |f|
<del> next if [".", "..", ".migration_attempted"].include? "#{f}"
<add> next if [".", "..", ".migration_attempted"].include? f.to_s
<ide> begin
<ide> FileUtils.cp_r f, HOMEBREW_CACHE
<ide> rescue
<ide> def link_completions_and_docs
<ide> link_src_dst_dirs(HOMEBREW_REPOSITORY/"etc/bash_completion.d",
<ide> HOMEBREW_PREFIX/"etc/bash_completion.d", command)
<ide> link_src_dst_dirs(HOMEBREW_REPOSITORY/"share/doc/homebrew",
<del> HOMEBREW_PREFIX/"share/doc/homebrew", command, link_dir: true)
<add> HOMEBREW_PREFIX/"share/doc/homebrew", command, :link_dir => true)
<ide> link_src_dst_dirs(HOMEBREW_REPOSITORY/"share/zsh/site-functions",
<ide> HOMEBREW_PREFIX/"share/zsh/site-functions", command)
<ide> link_path_manpages(HOMEBREW_REPOSITORY/"share", command)
<ide> def migrate_formula_rename
<ide> private
<ide>
<ide> def repo_var
<del> @repo_var ||= tap.path.to_s.
<del> strip_prefix(Tap::TAP_DIRECTORY.to_s).
<del> tr("^A-Za-z0-9", "_").
<del> upcase
<add> @repo_var ||= tap.path.to_s
<add> .strip_prefix(Tap::TAP_DIRECTORY.to_s)
<add> .tr("^A-Za-z0-9", "_")
<add> .upcase
<ide> end
<ide>
<ide> def diff
<ide> def select_formula(key)
<ide>
<ide> def add(reporter)
<ide> @reporters << reporter
<del> report = reporter.report.delete_if { |k,v| v.empty? }
<add> report = reporter.report.delete_if { |_k, v| v.empty? }
<ide> @hash.update(report) { |_key, oldval, newval| oldval.concat(newval) }
<ide> end
<ide> | 1 |
Text | Text | add note on object permissions for fbvs | 43c2c91dde3be7128df01b53e114d65d8e23438d | <ide><path>docs/api-guide/permissions.md
<ide> If you need to test if a request is a read operation or a write operation, you s
<ide>
<ide> ---
<ide>
<del>**Note**: The instance-level `has_object_permission` method will only be called if the view-level `has_permission` checks have already passed. Also note that in order for the instance-level checks to run, the view code should explicitly call `.check_object_permissions(request, obj)`. If you are using the generic views then this will be handled for you by default.
<add>**Note**: The instance-level `has_object_permission` method will only be called if the view-level `has_permission` checks have already passed. Also note that in order for the instance-level checks to run, the view code should explicitly call `.check_object_permissions(request, obj)`. If you are using the generic views then this will be handled for you by default. (Function-based views will need to check object permissions explicitly, raising `PermissionDenied` on failure.)
<ide>
<ide> ---
<ide> | 1 |
PHP | PHP | fix double space | d16cb9010e02d1eb27e1d918fbc6c5faa58c7fa9 | <ide><path>tests/TestCase/View/Helper/HtmlHelperTest.php
<ide> public function testLink()
<ide> $expected = ['a' => ['href' => '/home'], 'preg:/\/home/', '/a'];
<ide> $this->assertHtml($expected, $result);
<ide>
<del> $result = $this->Html->link(['controller' => 'users', 'action' => 'login', '<[You]>']);
<add> $result = $this->Html->link(['controller' => 'users', 'action' => 'login', '<[You]>']);
<ide> $expected = [
<ide> 'a' => ['href' => '/users/login/%3C%5BYou%5D%3E'],
<ide> 'preg:/\/users\/login\/<\[You\]>/', | 1 |
Python | Python | add basesensoroperator to __init__ | 4522dc2811913c804a35a5bd4ec65a2df0f9df74 | <ide><path>airflow/operators/__init__.py
<ide> 'mysql_to_hive': ['MySqlToHiveTransfer'],
<ide> 'postgres_operator': ['PostgresOperator'],
<ide> 'sensors': [
<add> 'BaseSensorOperator',
<ide> 'SqlSensor',
<ide> 'ExternalTaskSensor',
<ide> 'HivePartitionSensor', | 1 |
Python | Python | add keyword nrows to genfromtxt | 0091499ec28cd9ceb30cd94c0e40191570b6fec6 | <ide><path>numpy/lib/npyio.py
<ide> def genfromtxt(fname, dtype=float, comments='#', delimiter=None,
<ide> usecols=None, names=None,
<ide> excludelist=None, deletechars=None, replace_space='_',
<ide> autostrip=False, case_sensitive=True, defaultfmt="f%i",
<del> unpack=None, usemask=False, loose=True, invalid_raise=True):
<add> unpack=None, usemask=False, loose=True, invalid_raise=True,
<add> nrows=None):
<ide> """
<ide> Load data from a text file, with missing values handled as specified.
<ide>
<ide> def genfromtxt(fname, dtype=float, comments='#', delimiter=None,
<ide> If True, an exception is raised if an inconsistency is detected in the
<ide> number of columns.
<ide> If False, a warning is emitted and the offending lines are skipped.
<add> nrows : int, optional
<add> The number of rows to read. Must not be used with skip_footer at the
<add> same time.
<add>
<add> .. versionadded:: 1.10.0
<ide>
<ide> Returns
<ide> -------
<ide> def genfromtxt(fname, dtype=float, comments='#', delimiter=None,
<ide> dtype=[('intvar', '<i8'), ('fltvar', '<f8'), ('strvar', '|S5')])
<ide>
<ide> """
<add> # Check keywords conflict
<add> if skip_footer and (nrows is not None):
<add> raise ValueError(
<add> "keywords 'skip_footer' and 'nrows' can not be specified "
<add> "at the same time")
<add>
<ide> # Py3 data conversions to bytes, for convenience
<ide> if comments is not None:
<ide> comments = asbytes(comments)
<ide> def genfromtxt(fname, dtype=float, comments='#', delimiter=None,
<ide>
<ide> # Parse each line
<ide> for (i, line) in enumerate(itertools.chain([first_line, ], fhd)):
<add> if (nrows is not None) and (len(rows) >= nrows):
<add> break
<ide> values = split_line(line)
<ide> nbvalues = len(values)
<ide> # Skip an empty line
<ide> def genfromtxt(fname, dtype=float, comments='#', delimiter=None,
<ide> if own_fhd:
<ide> fhd.close()
<ide>
<add> if (nrows is not None) and (len(rows) != nrows):
<add> raise AssertionError(
<add> "%d rows required but got %d valid rows instead"
<add> %(nrows, len(rows)))
<add>
<ide> # Upgrade the converters (if needed)
<ide> if dtype is None:
<ide> for (i, converter) in enumerate(converters):
<ide><path>numpy/lib/tests/test_io.py
<ide> def test_recfromcsv(self):
<ide> self.assertTrue(isinstance(test, np.recarray))
<ide> assert_equal(test, control)
<ide>
<add> def test_nrows(self):
<add> #
<add> data = '1 1\n2 2\n0 \n3 3\n4 4\n5 \n6 \n7 \n'
<add> test = np.genfromtxt(TextIO(data), nrows=2)
<add> control = np.array([[1., 1.], [2., 2.]])
<add> assert_equal(test, control)
<add> # Test keywords conflict
<add> assert_raises(ValueError, np.genfromtxt, TextIO(data), skip_footer=1, nrows=4)
<add> # Test with invalid value
<add> assert_raises(ValueError, np.genfromtxt, TextIO(data), nrows=4)
<add> # Test with invalid not raise
<add> with warnings.catch_warnings():
<add> warnings.filterwarnings("ignore")
<add> test = np.genfromtxt(TextIO(data), nrows=4, invalid_raise=False)
<add> control = np.array([[1., 1.], [2., 2.], [3., 3.], [4., 4.]])
<add> assert_equal(test, control)
<add> # Test without enough valid rows
<add> assert_raises(AssertionError, np.genfromtxt, TextIO(data), nrows=5)
<add>
<add> data = 'a b\n#c d\n1 1\n2 2\n#0 \n3 3\n4 4\n5 \n6 \n7 \n'
<add> # Test with header, names and comments
<add> test = np.genfromtxt(TextIO(data), skip_header=1, nrows=4, names=True)
<add> control = np.array([(1.0, 1.0), (2.0, 2.0), (3.0, 3.0), (4.0, 4.0)],
<add> dtype=[('c', '<f8'), ('d', '<f8')])
<add> assert_equal(test, control)
<add>
<ide> def test_gft_using_filename(self):
<ide> # Test that we can load data from a filename as well as a file object
<ide> wanted = np.arange(6).reshape((2, 3)) | 2 |
Text | Text | fix documentation of http2stream.pushstream() | b886c424fb9ff7a5880d4a4c5a4d69ba5710c475 | <ide><path>doc/api/http2.md
<ide> added: v8.4.0
<ide> created stream is dependent on.
<ide> * `callback` {Function} Callback that is called once the push stream has been
<ide> initiated.
<add> * `err` {Error}
<add> * `pushStream` {[`ServerHttp2Stream`][]} The returned pushStream object.
<add> * `headers` {[Headers Object][]} Headers object the pushStream was initiated
<add> with.
<ide> * Returns: {undefined}
<ide>
<ide> Initiates a push stream. The callback is invoked with the new `Http2Stream`
<ide> const http2 = require('http2');
<ide> const server = http2.createServer();
<ide> server.on('stream', (stream) => {
<ide> stream.respond({ ':status': 200 });
<del> stream.pushStream({ ':path': '/' }, (err, pushStream) => {
<add> stream.pushStream({ ':path': '/' }, (err, pushStream, headers) => {
<ide> if (err) throw err;
<ide> pushStream.respond({ ':status': 200 });
<ide> pushStream.end('some pushed data'); | 1 |
Text | Text | fix doc in with-firebase-authentication | 202ceca1af1baeab5f61d2812ec48b019c80919d | <ide><path>examples/with-firebase-authentication/README.md
<ide> Download the example [or clone the repo](https://github.com/zeit/next.js):
<ide>
<ide> ```bash
<ide> curl https://codeload.github.com/zeit/next.js/tar.gz/canary | tar -xz --strip=2 next.js-canary/examples/with-firebase-authentication
<del>cd with-firebase
<add>cd with-firebase-authentication
<ide> ```
<ide>
<ide> Set up firebase: | 1 |
Text | Text | fix documentation for provider's release | ad27e4d196e989c93193fed80667634b50bd6891 | <ide><path>dev/README_RELEASE_PROVIDER_PACKAGES.md
<ide> - [Commit the source packages to Apache SVN repo](#commit-the-source-packages-to-apache-svn-repo)
<ide> - [Publish the Regular convenience package to PyPI](#publish-the-regular-convenience-package-to-pypi)
<ide> - [Add tags in git](#add-tags-in-git)
<del> - [Publish documentation](#publish-documentation)
<add> - [Prepare documentation](#prepare-documentation)
<ide> - [Prepare voting email for Providers release candidate](#prepare-voting-email-for-providers-release-candidate)
<ide> - [Verify the release by PMC members](#verify-the-release-by-pmc-members)
<ide> - [Verify by Contributors](#verify-by-contributors)
<ide> - [Publish release](#publish-release)
<ide> - [Summarize the voting for the Apache Airflow release](#summarize-the-voting-for-the-apache-airflow-release)
<ide> - [Publish the Regular convenience package to PyPI](#publish-the-regular-convenience-package-to-pypi-1)
<add> - [Publish documentation prepared before](#publish-documentation-prepared-before)
<ide> - [Add tags in git](#add-tags-in-git-1)
<ide> - [Notify developers of release](#notify-developers-of-release)
<ide>
<ide> set tags for the providers in the repo.
<ide> ./dev/provider_packages/tag_providers.sh
<ide> ```
<ide>
<del>## Publish documentation
<add>## Prepare documentation
<ide>
<ide> Documentation is an essential part of the product and should be made available to users.
<ide> In our cases, documentation for the released versions is published in a separate repository -
<ide> export AIRFLOW_REPO_ROOT=$(pwd)
<ide>
<ide> # Go to the directory where you have checked out the dev svn release
<ide> # And go to the sub-folder with RC candidates
<del>cd "<ROOT_OF_YOUR_DEV_REPO>/backport-providers/${VERSION_RC}"
<add>cd "<ROOT_OF_YOUR_DEV_REPO>/providers/"
<ide> export SOURCE_DIR=$(pwd)
<ide>
<ide> # Go the folder where you have checked out the release repo
<ide> python ${AIRFLOW_REPO_ROOT}/dev/provider_packages/remove_old_releases.py \
<ide>
<ide>
<ide> # Commit to SVN
<del>svn commit -m "Release Airflow Backport Providers ${VERSION} from ${VERSION_RC}"
<add>svn commit -m "Release Airflow Providers on $(date)"
<ide> ```
<ide>
<ide> Verify that the packages appear in
<del>[backport-providers](https://dist.apache.org/repos/dist/release/airflow/backport-providers)
<add>[backport-providers](https://dist.apache.org/repos/dist/release/airflow/providers)
<ide>
<ide> ### Publish the final version convenience package to PyPI
<ide>
<del>Checkout the RC Version:
<add>Checkout the RC Version for the RC Version released (there is a batch of providers - one of them is enough):
<ide>
<ide> ```shell script
<del>git checkout backport-providers-${VERSION_RC}
<del>```
<del>
<del>Tag and push the final version (providing that your apache remote is named 'apache'):
<del>
<del>```shell script
<del>git tag backport-providers-${VERSION}
<del>git push apache backport-providers-${VERSION}
<add>git checkout providers-<PROVIDER_NAME>/<VERSION_RC>
<ide> ```
<ide>
<ide> In order to publish to PyPI you just need to build and release packages.
<ide> In order to publish to PyPI you just need to build and release packages.
<ide> if you ony build few packages, run:
<ide>
<ide> ```shell script
<del>./breeze --backports prepare-provider-packages <PACKAGE> ...
<add>./breeze prepare-provider-packages <PACKAGE> ...
<ide> ```
<ide>
<ide> In case you decided to remove some of the packages. remove them from dist folder now:
<ide> rm -rf ${AIRFLOW_REPO_ROOT}/dist/*
<ide> if you ony build few packages, run:
<ide>
<ide> ```shell script
<add>rm -rf ${AIRFLOW_REPO_ROOT}/dist/*
<ide> ./breeze prepare-provider-packages --package-format both PACKAGE PACKAGE ....
<ide> ```
<ide>
<ide> twine upload -r pypi ${AIRFLOW_REPO_ROOT}/dist/*
<ide>
<ide> * Again, confirm that the packages are available under the links printed.
<ide>
<add>## Publish documentation prepared before
<add>
<add>Merge the PR that you prepared before with the documentation. If you removed some of the providers
<add>from the release - remove the versions from the prepared documentation and update stable.txt with the
<add>previous version for those providers before merging the PR.
<add>
<ide>
<ide> ## Add tags in git
<ide>
<ide> Subject:
<ide>
<ide> ```shell script
<ide> cat <<EOF
<del>Airflow Providers are released
<add>Airflow Providers released on $(date) are ready
<ide> EOF
<ide> ```
<ide>
<ide> Body:
<ide> cat <<EOF
<ide> Dear Airflow community,
<ide>
<del>I'm happy to announce that new version of Airflow Providers packages were just released.
<add>I'm happy to announce that new versions of Airflow Providers packages were just released.
<ide>
<ide> The source release, as well as the binary releases, are available here:
<ide>
<ide> We also made those versions available on PyPi for convenience ('pip install apac
<ide>
<ide> https://pypi.org/search/?q=apache-airflow-providers
<ide>
<del>The documentation and changelogs are available in the PyPI packages:
<add>The documentation is available at http://airflow.apache.org/docs/ and linked from the PyPI packages:
<ide>
<ide> <PASTE TWINE UPLOAD LINKS HERE. SORT THEM BEFORE!>
<ide> | 1 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.