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 |
|---|---|---|---|---|---|
Javascript | Javascript | remove dead has_side_effects logic | 416b5ef17343acebfd19e1436e3b2990e99e1d0e | <ide><path>src/renderers/dom/shared/DOMProperty.js
<ide> var DOMPropertyInjection = {
<ide> * specifies how the associated DOM property should be accessed or rendered.
<ide> */
<ide> MUST_USE_PROPERTY: 0x1,
<del> HAS_SIDE_EFFECTS: 0x2,
<ide> HAS_BOOLEAN_VALUE: 0x4,
<ide> HAS_NUMERIC_VALUE: 0x8,
<ide> HAS_POSITIVE_NUMERIC_VALUE: 0x10 | 0x8,
<ide> var DOMPropertyInjection = {
<ide> mutationMethod: null,
<ide>
<ide> mustUseProperty: checkMask(propConfig, Injection.MUST_USE_PROPERTY),
<del> hasSideEffects: checkMask(propConfig, Injection.HAS_SIDE_EFFECTS),
<ide> hasBooleanValue: checkMask(propConfig, Injection.HAS_BOOLEAN_VALUE),
<ide> hasNumericValue: checkMask(propConfig, Injection.HAS_NUMERIC_VALUE),
<ide> hasPositiveNumericValue:
<ide> checkMask(propConfig, Injection.HAS_POSITIVE_NUMERIC_VALUE),
<ide> hasOverloadedBooleanValue:
<ide> checkMask(propConfig, Injection.HAS_OVERLOADED_BOOLEAN_VALUE),
<ide> };
<del>
<del> invariant(
<del> propertyInfo.mustUseProperty || !propertyInfo.hasSideEffects,
<del> 'DOMProperty: Properties that have side effects must use property: %s',
<del> propName
<del> );
<ide> invariant(
<ide> propertyInfo.hasBooleanValue + propertyInfo.hasNumericValue +
<ide> propertyInfo.hasOverloadedBooleanValue <= 1,
<ide> var DOMProperty = {
<ide> * initial render.
<ide> * mustUseProperty:
<ide> * Whether the property must be accessed and mutated as an object property.
<del> * hasSideEffects:
<del> * Whether or not setting a value causes side effects such as triggering
<del> * resources to be loaded or text selection changes. If true, we read from
<del> * the DOM before updating to ensure that the value is only set if it has
<del> * changed.
<ide> * hasBooleanValue:
<ide> * Whether the property should be removed when set to a falsey value.
<ide> * hasNumericValue:
<ide><path>src/renderers/dom/shared/DOMPropertyOperations.js
<ide> var DOMPropertyOperations = {
<ide> this.deleteValueForProperty(node, name);
<ide> return;
<ide> } else if (propertyInfo.mustUseProperty) {
<del> var propName = propertyInfo.propertyName;
<del> // Must explicitly cast values for HAS_SIDE_EFFECTS-properties to the
<del> // property type before comparing; only `value` does and is string.
<del> if (!propertyInfo.hasSideEffects ||
<del> ('' + node[propName]) !== ('' + value)) {
<del> // Contrary to `setAttribute`, object properties are properly
<del> // `toString`ed by IE8/9.
<del> node[propName] = value;
<del> }
<add> // Contrary to `setAttribute`, object properties are properly
<add> // `toString`ed by IE8/9.
<add> node[propertyInfo.propertyName] = value;
<ide> } else {
<ide> var attributeName = propertyInfo.attributeName;
<ide> var namespace = propertyInfo.attributeNamespace;
<ide> var DOMPropertyOperations = {
<ide> } else if (propertyInfo.mustUseProperty) {
<ide> var propName = propertyInfo.propertyName;
<ide> if (propertyInfo.hasBooleanValue) {
<del> // No HAS_SIDE_EFFECTS logic here, only `value` has it and is string.
<ide> node[propName] = false;
<ide> } else {
<del> if (!propertyInfo.hasSideEffects ||
<del> ('' + node[propName]) !== '') {
<del> node[propName] = '';
<del> }
<add> node[propName] = '';
<ide> }
<ide> } else {
<ide> node.removeAttribute(propertyInfo.attributeName); | 2 |
Ruby | Ruby | remove sneaky empty line | dd9415c8d3c07b4fa2ac066e867297ff06c64568 | <ide><path>Library/Homebrew/extend/os/mac/caveats.rb
<ide> def plist_caveats
<ide> end
<ide> s.join("\n") + "\n" unless s.empty?
<ide> end
<del>
<ide> end | 1 |
Python | Python | update the typing tests for `np.core.shape_base` | 76bad5650e4c741c7104060302d18e9b114b6bdb | <ide><path>numpy/typing/tests/data/fail/array_constructors.py
<ide> np.geomspace(None, 'bob') # E: Argument 1
<ide>
<ide> np.stack(generator) # E: No overload variant
<del>np.hstack({1, 2}) # E: incompatible type
<del>np.vstack(1) # E: incompatible type
<add>np.hstack({1, 2}) # E: No overload variant
<add>np.vstack(1) # E: No overload variant
<ide><path>numpy/typing/tests/data/reveal/array_constructors.py
<ide> def func(i: int, j: int, **kwargs: Any) -> SubClass[np.float64]: ...
<ide>
<ide> reveal_type(np.identity(10)) # E: numpy.ndarray[Any, Any]
<ide>
<del>reveal_type(np.atleast_1d(A)) # E: numpy.ndarray[Any, Any]
<del>reveal_type(np.atleast_1d(C)) # E: numpy.ndarray[Any, Any]
<del>reveal_type(np.atleast_1d(A, A)) # E: list[numpy.ndarray[Any, Any]]
<del>reveal_type(np.atleast_1d(A, C)) # E: list[numpy.ndarray[Any, Any]]
<del>reveal_type(np.atleast_1d(C, C)) # E: list[numpy.ndarray[Any, Any]]
<add>reveal_type(np.atleast_1d(A)) # E: numpy.ndarray[Any, numpy.dtype[{float64}]]
<add>reveal_type(np.atleast_1d(C)) # E: numpy.ndarray[Any, numpy.dtype[Any]]
<add>reveal_type(np.atleast_1d(A, A)) # E: list[numpy.ndarray[Any, numpy.dtype[Any]]]
<add>reveal_type(np.atleast_1d(A, C)) # E: list[numpy.ndarray[Any, numpy.dtype[Any]]]
<add>reveal_type(np.atleast_1d(C, C)) # E: list[numpy.ndarray[Any, numpy.dtype[Any]]]
<ide>
<del>reveal_type(np.atleast_2d(A)) # E: numpy.ndarray[Any, Any]
<add>reveal_type(np.atleast_2d(A)) # E: numpy.ndarray[Any, numpy.dtype[{float64}]]
<ide>
<del>reveal_type(np.atleast_3d(A)) # E: numpy.ndarray[Any, Any]
<add>reveal_type(np.atleast_3d(A)) # E: numpy.ndarray[Any, numpy.dtype[{float64}]]
<ide>
<del>reveal_type(np.vstack([A, A])) # E: numpy.ndarray[Any, Any]
<del>reveal_type(np.vstack([A, C])) # E: numpy.ndarray[Any, Any]
<del>reveal_type(np.vstack([C, C])) # E: numpy.ndarray[Any, Any]
<add>reveal_type(np.vstack([A, A])) # E: numpy.ndarray[Any, numpy.dtype[{float64}]]
<add>reveal_type(np.vstack([A, C])) # E: numpy.ndarray[Any, numpy.dtype[Any]]
<add>reveal_type(np.vstack([C, C])) # E: numpy.ndarray[Any, numpy.dtype[Any]]
<ide>
<del>reveal_type(np.hstack([A, A])) # E: numpy.ndarray[Any, Any]
<add>reveal_type(np.hstack([A, A])) # E: numpy.ndarray[Any, numpy.dtype[{float64}]]
<ide>
<del>reveal_type(np.stack([A, A])) # E: numpy.ndarray[Any, Any]
<del>reveal_type(np.stack([A, A], axis=0)) # E: numpy.ndarray[Any, Any]
<del>reveal_type(np.stack([A, A], out=B)) # E: SubClass
<add>reveal_type(np.stack([A, A])) # E: numpy.ndarray[Any, numpy.dtype[{float64}]]
<add>reveal_type(np.stack([A, C])) # E: numpy.ndarray[Any, numpy.dtype[Any]]
<add>reveal_type(np.stack([C, C])) # E: numpy.ndarray[Any, numpy.dtype[Any]]
<add>reveal_type(np.stack([A, A], axis=0)) # E: numpy.ndarray[Any, numpy.dtype[{float64}]]
<add>reveal_type(np.stack([A, A], out=B)) # E: SubClass[{float64}]
<ide>
<del>reveal_type(np.block([[A, A], [A, A]])) # E: numpy.ndarray[Any, Any]
<del>reveal_type(np.block(C)) # E: numpy.ndarray[Any, Any]
<add>reveal_type(np.block([[A, A], [A, A]])) # E: numpy.ndarray[Any, numpy.dtype[{float64}]]
<add>reveal_type(np.block(C)) # E: numpy.ndarray[Any, numpy.dtype[Any]] | 2 |
PHP | PHP | pass the key to the keyby callback | bccaf7c179237ca558be5df2d7e8e44ef52136cc | <ide><path>src/Illuminate/Support/Collection.php
<ide> public function keyBy($keyBy)
<ide>
<ide> $results = [];
<ide>
<del> foreach ($this->items as $item) {
<del> $results[$keyBy($item)] = $item;
<add> foreach ($this->items as $key => $item) {
<add> $results[$keyBy($item, $key)] = $item;
<ide> }
<ide>
<ide> return new static($results);
<ide><path>tests/Support/SupportCollectionTest.php
<ide> public function testKeyByClosure()
<ide> ['firstname' => 'Taylor', 'lastname' => 'Otwell', 'locale' => 'US'],
<ide> ['firstname' => 'Lucas', 'lastname' => 'Michot', 'locale' => 'FR'],
<ide> ]);
<del> $result = $data->keyBy(function ($item) {
<del> return strtolower($item['firstname'].$item['lastname']);
<add> $result = $data->keyBy(function ($item, $key) {
<add> return strtolower($key.'-'.$item['firstname'].$item['lastname']);
<ide> });
<ide> $this->assertEquals([
<del> 'taylorotwell' => ['firstname' => 'Taylor', 'lastname' => 'Otwell', 'locale' => 'US'],
<del> 'lucasmichot' => ['firstname' => 'Lucas', 'lastname' => 'Michot', 'locale' => 'FR'],
<add> '0-taylorotwell' => ['firstname' => 'Taylor', 'lastname' => 'Otwell', 'locale' => 'US'],
<add> '1-lucasmichot' => ['firstname' => 'Lucas', 'lastname' => 'Michot', 'locale' => 'FR'],
<ide> ], $result->all());
<ide> }
<ide> | 2 |
Java | Java | restore support of list of inner bean definitions | 6d688e196d8f4c41284087e5346da29770349b0c | <ide><path>spring-beans/src/main/java/org/springframework/beans/factory/aot/BeanDefinitionMethodGenerator.java
<ide> class BeanDefinitionMethodGenerator {
<ide> private final Executable constructorOrFactoryMethod;
<ide>
<ide> @Nullable
<del> private final String innerBeanPropertyName;
<add> private final String currentPropertyName;
<ide>
<ide> private final List<BeanRegistrationAotContribution> aotContributions;
<ide>
<ide> class BeanDefinitionMethodGenerator {
<ide> * Create a new {@link BeanDefinitionMethodGenerator} instance.
<ide> * @param methodGeneratorFactory the method generator factory
<ide> * @param registeredBean the registered bean
<del> * @param innerBeanPropertyName the inner bean property name
<add> * @param currentPropertyName the current property name
<ide> * @param aotContributions the AOT contributions
<ide> */
<ide> BeanDefinitionMethodGenerator(
<ide> BeanDefinitionMethodGeneratorFactory methodGeneratorFactory,
<del> RegisteredBean registeredBean, @Nullable String innerBeanPropertyName,
<add> RegisteredBean registeredBean, @Nullable String currentPropertyName,
<ide> List<BeanRegistrationAotContribution> aotContributions) {
<ide>
<ide> this.methodGeneratorFactory = methodGeneratorFactory;
<ide> this.registeredBean = registeredBean;
<ide> this.constructorOrFactoryMethod = registeredBean.resolveConstructorOrFactoryMethod();
<del> this.innerBeanPropertyName = innerBeanPropertyName;
<add> this.currentPropertyName = currentPropertyName;
<ide> this.aotContributions = aotContributions;
<ide> }
<ide>
<ide> private GeneratedMethod generateBeanDefinitionMethod(
<ide> }
<ide>
<ide> private String getName() {
<del> if (this.innerBeanPropertyName != null) {
<del> return this.innerBeanPropertyName;
<add> if (this.currentPropertyName != null) {
<add> return this.currentPropertyName;
<ide> }
<ide> if (!this.registeredBean.isGeneratedBeanName()) {
<ide> return getSimpleBeanName(this.registeredBean.getBeanName());
<ide><path>spring-beans/src/main/java/org/springframework/beans/factory/aot/BeanDefinitionMethodGeneratorFactory.java
<ide> * {@link RegisteredBean}.
<ide> *
<ide> * @author Phillip Webb
<add> * @author Stephane Nicoll
<ide> * @since 6.0
<ide> * @see BeanDefinitionMethodGenerator
<del> * @see #getBeanDefinitionMethodGenerator(RegisteredBean, String)
<add> * @see #getBeanDefinitionMethodGenerator(RegisteredBean)
<ide> */
<ide> class BeanDefinitionMethodGeneratorFactory {
<ide>
<ide> class BeanDefinitionMethodGeneratorFactory {
<ide>
<ide> /**
<ide> * Return a {@link BeanDefinitionMethodGenerator} for the given
<del> * {@link RegisteredBean} or {@code null} if the registered bean is excluded
<del> * by a {@link BeanRegistrationExcludeFilter}. The resulting
<add> * {@link RegisteredBean} defined with the specified property name, or
<add> * {@code null} if the registered bean is excluded by a
<add> * {@link BeanRegistrationExcludeFilter}. The resulting
<ide> * {@link BeanDefinitionMethodGenerator} will include all
<ide> * {@link BeanRegistrationAotProcessor} provided contributions.
<ide> * @param registeredBean the registered bean
<del> * @param innerBeanPropertyName the inner bean property name or {@code null}
<add> * @param currentPropertyName the property name that this bean belongs to
<ide> * @return a new {@link BeanDefinitionMethodGenerator} instance or
<ide> * {@code null}
<ide> */
<ide> @Nullable
<ide> BeanDefinitionMethodGenerator getBeanDefinitionMethodGenerator(
<del> RegisteredBean registeredBean, @Nullable String innerBeanPropertyName) {
<add> RegisteredBean registeredBean, @Nullable String currentPropertyName) {
<ide>
<ide> if (isExcluded(registeredBean)) {
<ide> return null;
<ide> }
<ide> List<BeanRegistrationAotContribution> contributions = getAotContributions(
<ide> registeredBean);
<ide> return new BeanDefinitionMethodGenerator(this, registeredBean,
<del> innerBeanPropertyName, contributions);
<add> currentPropertyName, contributions);
<add> }
<add>
<add> /**
<add> * Return a {@link BeanDefinitionMethodGenerator} for the given
<add> * {@link RegisteredBean} or {@code null} if the registered bean is excluded
<add> * by a {@link BeanRegistrationExcludeFilter}. The resulting
<add> * {@link BeanDefinitionMethodGenerator} will include all
<add> * {@link BeanRegistrationAotProcessor} provided contributions.
<add> * @param registeredBean the registered bean
<add> * @return a new {@link BeanDefinitionMethodGenerator} instance or
<add> * {@code null}
<add> */
<add> @Nullable
<add> BeanDefinitionMethodGenerator getBeanDefinitionMethodGenerator(RegisteredBean registeredBean) {
<add> return getBeanDefinitionMethodGenerator(registeredBean, null);
<ide> }
<ide>
<ide> private boolean isExcluded(RegisteredBean registeredBean) {
<ide><path>spring-beans/src/main/java/org/springframework/beans/factory/aot/BeanDefinitionPropertiesCodeGenerator.java
<ide>
<ide> import java.beans.PropertyDescriptor;
<ide> import java.lang.reflect.Method;
<add>import java.util.ArrayDeque;
<ide> import java.util.Arrays;
<ide> import java.util.Collections;
<ide> import java.util.HashMap;
<ide> class BeanDefinitionPropertiesCodeGenerator {
<ide>
<ide> private final Predicate<String> attributeFilter;
<ide>
<del> private final BiFunction<String, Object, CodeBlock> customValueCodeGenerator;
<del>
<ide> private final BeanDefinitionPropertyValueCodeGenerator valueCodeGenerator;
<ide>
<ide>
<ide> class BeanDefinitionPropertiesCodeGenerator {
<ide>
<ide> this.hints = hints;
<ide> this.attributeFilter = attributeFilter;
<del> this.customValueCodeGenerator = customValueCodeGenerator;
<del> this.valueCodeGenerator = new BeanDefinitionPropertyValueCodeGenerator(
<del> generatedMethods);
<add> this.valueCodeGenerator = new BeanDefinitionPropertyValueCodeGenerator(generatedMethods,
<add> (object, type) -> customValueCodeGenerator.apply(PropertyNamesStack.peek(), object));
<ide> }
<ide>
<ide>
<ide> private void addConstructorArgumentValues(CodeBlock.Builder code,
<ide> .getConstructorArgumentValues().getIndexedArgumentValues();
<ide> if (!argumentValues.isEmpty()) {
<ide> argumentValues.forEach((index, valueHolder) -> {
<del> String name = valueHolder.getName();
<del> Object value = valueHolder.getValue();
<del> CodeBlock valueCode = this.customValueCodeGenerator.apply(name, value);
<del> if (valueCode == null) {
<del> valueCode = this.valueCodeGenerator.generateCode(value);
<del> }
<add> CodeBlock valueCode = generateValue(valueHolder.getName(), valueHolder.getValue());
<ide> code.addStatement(
<ide> "$L.getConstructorArgumentValues().addIndexedArgumentValue($L, $L)",
<ide> BEAN_DEFINITION_VARIABLE, index, valueCode);
<ide> private void addPropertyValues(CodeBlock.Builder code,
<ide> if (!propertyValues.isEmpty()) {
<ide> for (PropertyValue propertyValue : propertyValues) {
<ide> String name = propertyValue.getName();
<del> Object value = propertyValue.getValue();
<del> CodeBlock valueCode = this.customValueCodeGenerator.apply(name, value);
<del> if (valueCode == null) {
<del> valueCode = this.valueCodeGenerator.generateCode(value);
<del> }
<add> CodeBlock valueCode = generateValue(name, propertyValue.getValue());
<ide> code.addStatement("$L.getPropertyValues().addPropertyValue($S, $L)",
<ide> BEAN_DEFINITION_VARIABLE, propertyValue.getName(), valueCode);
<ide> }
<ide> private void addPropertyValues(CodeBlock.Builder code,
<ide> }
<ide> }
<ide>
<add> private CodeBlock generateValue(@Nullable String name, @Nullable Object value) {
<add> try {
<add> PropertyNamesStack.push(name);
<add> return this.valueCodeGenerator.generateCode(value);
<add> }
<add> finally {
<add> PropertyNamesStack.pop();
<add> }
<add> }
<add>
<ide> private Class<?> getInfrastructureType(RootBeanDefinition beanDefinition) {
<ide> if (beanDefinition.hasBeanClass()) {
<ide> Class<?> beanClass = beanDefinition.getBeanClass();
<ide> private <B extends BeanDefinition, T> void addStatementForValue(
<ide> }
<ide> }
<ide>
<add> static class PropertyNamesStack {
<add>
<add> private static final ThreadLocal<ArrayDeque<String>> threadLocal = ThreadLocal.withInitial(ArrayDeque::new);
<add>
<add> static void push(@Nullable String name) {
<add> String valueToSet = (name != null) ? name : "";
<add> threadLocal.get().push(valueToSet);
<add> }
<add>
<add> static void pop() {
<add> threadLocal.get().pop();
<add> }
<add>
<add> @Nullable
<add> static String peek() {
<add> String value = threadLocal.get().peek();
<add> return ("".equals(value) ? null : value);
<add> }
<add>
<add> }
<add>
<ide> }
<ide><path>spring-beans/src/main/java/org/springframework/beans/factory/aot/BeanDefinitionPropertyValueCodeGenerator.java
<ide> package org.springframework.beans.factory.aot;
<ide>
<ide> import java.nio.charset.Charset;
<add>import java.util.ArrayList;
<ide> import java.util.Arrays;
<ide> import java.util.Collection;
<ide> import java.util.Collections;
<ide> import java.util.Set;
<ide> import java.util.TreeMap;
<ide> import java.util.TreeSet;
<add>import java.util.function.BiFunction;
<ide> import java.util.stream.Stream;
<ide>
<ide> import org.springframework.aot.generate.GeneratedMethod;
<ide> class BeanDefinitionPropertyValueCodeGenerator {
<ide>
<ide> private final GeneratedMethods generatedMethods;
<ide>
<del> private final List<Delegate> delegates = List.of(
<del> new PrimitiveDelegate(),
<del> new StringDelegate(),
<del> new CharsetDelegate(),
<del> new EnumDelegate(),
<del> new ClassDelegate(),
<del> new ResolvableTypeDelegate(),
<del> new ArrayDelegate(),
<del> new ManagedListDelegate(),
<del> new ManagedSetDelegate(),
<del> new ManagedMapDelegate(),
<del> new ListDelegate(),
<del> new SetDelegate(),
<del> new MapDelegate(),
<del> new BeanReferenceDelegate()
<del> );
<del>
<del>
<del> BeanDefinitionPropertyValueCodeGenerator(GeneratedMethods generatedMethods) {
<add> private final List<Delegate> delegates;
<add>
<add>
<add> BeanDefinitionPropertyValueCodeGenerator(GeneratedMethods generatedMethods,
<add> @Nullable BiFunction<Object, ResolvableType, CodeBlock> customValueGenerator) {
<ide> this.generatedMethods = generatedMethods;
<add> this.delegates = new ArrayList<>();
<add> if (customValueGenerator != null) {
<add> this.delegates.add(customValueGenerator::apply);
<add> }
<add> this.delegates.addAll(List.of(
<add> new PrimitiveDelegate(),
<add> new StringDelegate(),
<add> new CharsetDelegate(),
<add> new EnumDelegate(),
<add> new ClassDelegate(),
<add> new ResolvableTypeDelegate(),
<add> new ArrayDelegate(),
<add> new ManagedListDelegate(),
<add> new ManagedSetDelegate(),
<add> new ManagedMapDelegate(),
<add> new ListDelegate(),
<add> new SetDelegate(),
<add> new MapDelegate(),
<add> new BeanReferenceDelegate()
<add> ));
<ide> }
<ide>
<ide>
<ide><path>spring-beans/src/main/java/org/springframework/beans/factory/aot/BeanRegistrationsAotProcessor.java
<ide> public BeanRegistrationsAotContribution processAheadOfTime(ConfigurableListableB
<ide> for (String beanName : beanFactory.getBeanDefinitionNames()) {
<ide> RegisteredBean registeredBean = RegisteredBean.of(beanFactory, beanName);
<ide> BeanDefinitionMethodGenerator beanDefinitionMethodGenerator = beanDefinitionMethodGeneratorFactory
<del> .getBeanDefinitionMethodGenerator(registeredBean, null);
<add> .getBeanDefinitionMethodGenerator(registeredBean);
<ide> if (beanDefinitionMethodGenerator != null) {
<ide> registrations.put(beanName, beanDefinitionMethodGenerator);
<ide> }
<ide><path>spring-beans/src/test/java/org/springframework/beans/factory/aot/BeanDefinitionMethodGeneratorFactoryTests.java
<ide> void getBeanDefinitionMethodGeneratorWhenExcludedByBeanRegistrationExcludeFilter
<ide> RegisteredBean registeredBean = registerTestBean(beanFactory);
<ide> BeanDefinitionMethodGeneratorFactory methodGeneratorFactory = new BeanDefinitionMethodGeneratorFactory(
<ide> AotServices.factoriesAndBeans(springFactoriesLoader, beanFactory));
<del> assertThat(methodGeneratorFactory.getBeanDefinitionMethodGenerator(registeredBean,
<del> null)).isNull();
<add> assertThat(methodGeneratorFactory.getBeanDefinitionMethodGenerator(registeredBean)).isNull();
<ide> }
<ide>
<ide> @Test
<ide> void getBeanDefinitionMethodGeneratorWhenExcludedByBeanRegistrationExcludeFilter
<ide> new MockBeanRegistrationExcludeFilter(true, 0));
<ide> BeanDefinitionMethodGeneratorFactory methodGeneratorFactory = new BeanDefinitionMethodGeneratorFactory(
<ide> AotServices.factoriesAndBeans(springFactoriesLoader, beanFactory));
<del> assertThat(methodGeneratorFactory.getBeanDefinitionMethodGenerator(registeredBean,
<del> null)).isNull();
<add> assertThat(methodGeneratorFactory.getBeanDefinitionMethodGenerator(registeredBean)).isNull();
<ide> }
<ide>
<ide> @Test
<ide> void getBeanDefinitionMethodGeneratorConsidersFactoryLoadedExcludeFiltersAndBean
<ide> RegisteredBean registeredBean = registerTestBean(beanFactory);
<ide> BeanDefinitionMethodGeneratorFactory methodGeneratorFactory = new BeanDefinitionMethodGeneratorFactory(
<ide> AotServices.factoriesAndBeans(springFactoriesLoader, beanFactory));
<del> assertThat(methodGeneratorFactory.getBeanDefinitionMethodGenerator(registeredBean,
<del> null)).isNull();
<add> assertThat(methodGeneratorFactory.getBeanDefinitionMethodGenerator(registeredBean)).isNull();
<ide> assertThat(filter1.wasCalled()).isTrue();
<ide> assertThat(filter2.wasCalled()).isTrue();
<ide> assertThat(filter3.wasCalled()).isTrue();
<ide> void getBeanDefinitionMethodGeneratorAddsContributionsFromProcessors() {
<ide> BeanDefinitionMethodGeneratorFactory methodGeneratorFactory = new BeanDefinitionMethodGeneratorFactory(
<ide> AotServices.factoriesAndBeans(springFactoriesLoader, beanFactory));
<ide> BeanDefinitionMethodGenerator methodGenerator = methodGeneratorFactory
<del> .getBeanDefinitionMethodGenerator(registeredBean, null);
<add> .getBeanDefinitionMethodGenerator(registeredBean);
<ide> assertThat(methodGenerator).extracting("aotContributions").asList()
<ide> .containsExactly(beanContribution, loaderContribution);
<ide> }
<ide> void getBeanDefinitionMethodGeneratorWhenRegisteredBeanIsAotProcessorFiltersBean
<ide> RegisteredBean registeredBean2 = RegisteredBean.of(beanFactory, "test2");
<ide> BeanDefinitionMethodGeneratorFactory methodGeneratorFactory = new BeanDefinitionMethodGeneratorFactory(
<ide> AotServices.factoriesAndBeans(springFactoriesLoader, beanFactory));
<del> assertThat(methodGeneratorFactory.getBeanDefinitionMethodGenerator(registeredBean1, null)).isNull();
<del> assertThat(methodGeneratorFactory.getBeanDefinitionMethodGenerator(registeredBean2, null)).isNull();
<add> assertThat(methodGeneratorFactory.getBeanDefinitionMethodGenerator(registeredBean1)).isNull();
<add> assertThat(methodGeneratorFactory.getBeanDefinitionMethodGenerator(registeredBean2)).isNull();
<ide> }
<ide>
<ide> @Test
<ide> void getBeanDefinitionMethodGeneratorWhenRegisteredBeanIsAotProcessorAndIsNotExc
<ide> RegisteredBean registeredBean1 = RegisteredBean.of(beanFactory, "test");
<ide> BeanDefinitionMethodGeneratorFactory methodGeneratorFactory = new BeanDefinitionMethodGeneratorFactory(
<ide> AotServices.factoriesAndBeans(springFactoriesLoader, beanFactory));
<del> assertThat(methodGeneratorFactory.getBeanDefinitionMethodGenerator(registeredBean1, null)).isNotNull();
<add> assertThat(methodGeneratorFactory.getBeanDefinitionMethodGenerator(registeredBean1)).isNotNull();
<ide> }
<ide>
<ide> private RegisteredBean registerTestBean(DefaultListableBeanFactory beanFactory) {
<ide><path>spring-beans/src/test/java/org/springframework/beans/factory/aot/BeanDefinitionMethodGeneratorTests.java
<ide> import org.springframework.beans.factory.support.BeanDefinitionBuilder;
<ide> import org.springframework.beans.factory.support.DefaultListableBeanFactory;
<ide> import org.springframework.beans.factory.support.InstanceSupplier;
<add>import org.springframework.beans.factory.support.ManagedList;
<ide> import org.springframework.beans.factory.support.RegisteredBean;
<ide> import org.springframework.beans.factory.support.RootBeanDefinition;
<ide> import org.springframework.beans.testfixture.beans.AnnotatedBean;
<ide> void generateBeanDefinitionMethodWhenHasInnerBeanPropertyValueGeneratesMethod()
<ide> });
<ide> }
<ide>
<add> @SuppressWarnings("unchecked")
<add> @Test
<add> void generateBeanDefinitionMethodWhenHasListOfInnerBeansPropertyValueGeneratesMethod() {
<add> RootBeanDefinition firstInnerBeanDefinition = (RootBeanDefinition) BeanDefinitionBuilder
<add> .rootBeanDefinition(TestBean.class).addPropertyValue("name", "one")
<add> .getBeanDefinition();
<add> RootBeanDefinition secondInnerBeanDefinition = (RootBeanDefinition) BeanDefinitionBuilder
<add> .rootBeanDefinition(TestBean.class).addPropertyValue("name", "two")
<add> .getBeanDefinition();
<add> ManagedList<RootBeanDefinition> list = new ManagedList<>();
<add> list.add(firstInnerBeanDefinition);
<add> list.add(secondInnerBeanDefinition);
<add> RootBeanDefinition beanDefinition = new RootBeanDefinition(TestBean.class);
<add> beanDefinition.getPropertyValues().add("someList", list);
<add> RegisteredBean registeredBean = registerBean(beanDefinition);
<add> BeanDefinitionMethodGenerator generator = new BeanDefinitionMethodGenerator(
<add> this.methodGeneratorFactory, registeredBean, null,
<add> Collections.emptyList());
<add> MethodReference method = generator.generateBeanDefinitionMethod(
<add> this.generationContext, this.beanRegistrationsCode);
<add> compile(method, (actual, compiled) -> {
<add> ManagedList<RootBeanDefinition> actualPropertyValue = (ManagedList<RootBeanDefinition>) actual
<add> .getPropertyValues().get("someList");
<add> assertThat(actualPropertyValue).isNotNull().hasSize(2);
<add> assertThat(actualPropertyValue.get(0).getPropertyValues().get("name")).isEqualTo("one");
<add> assertThat(actualPropertyValue.get(1).getPropertyValues().get("name")).isEqualTo("two");
<add> assertThat(compiled.getSourceFileFromPackage(TestBean.class.getPackageName()))
<add> .contains("getSomeListBeanDefinition()", "getSomeListBeanDefinition1()");
<add> });
<add> }
<add>
<ide> @Test
<ide> void generateBeanDefinitionMethodWhenHasInnerBeanConstructorValueGeneratesMethod() {
<ide> RootBeanDefinition innerBeanDefinition = (RootBeanDefinition) BeanDefinitionBuilder
<ide><path>spring-beans/src/test/java/org/springframework/beans/factory/aot/BeanDefinitionPropertyValueCodeGeneratorTests.java
<ide> */
<ide> class BeanDefinitionPropertyValueCodeGeneratorTests {
<ide>
<add> private static BeanDefinitionPropertyValueCodeGenerator createPropertyValuesCodeGenerator(GeneratedClass generatedClass) {
<add> return new BeanDefinitionPropertyValueCodeGenerator(generatedClass.getMethods(), null);
<add> }
<add>
<ide> private void compile(Object value, BiConsumer<Object, Compiled> result) {
<ide> TestGenerationContext generationContext = new TestGenerationContext();
<ide> DeferredTypeBuilder typeBuilder = new DeferredTypeBuilder();
<ide> GeneratedClass generatedClass = generationContext.getGeneratedClasses().addForFeature("TestCode", typeBuilder);
<del> CodeBlock generatedCode = new BeanDefinitionPropertyValueCodeGenerator(
<del> generatedClass.getMethods()).generateCode(value);
<add> CodeBlock generatedCode = createPropertyValuesCodeGenerator(generatedClass).generateCode(value);
<ide> typeBuilder.set(type -> {
<ide> type.addModifiers(Modifier.PUBLIC);
<ide> type.addSuperinterface(
<ide> private void generateCode(Object value) {
<ide> TestGenerationContext context = new TestGenerationContext();
<ide> GeneratedClass generatedClass = context.getGeneratedClasses()
<ide> .addForFeature("Test", type -> {});
<del> new BeanDefinitionPropertyValueCodeGenerator(generatedClass.getMethods())
<del> .generateCode(value);
<add> createPropertyValuesCodeGenerator(generatedClass).generateCode(value);
<ide> }
<ide>
<ide> record SampleValue(String name) {} | 8 |
Javascript | Javascript | update running animations | b73b8f98633f399ac804d52bb0c8ed6d2212d3ea | <ide><path>src/core/core.animation.js
<ide> export default class Animation {
<ide> return this._active;
<ide> }
<ide>
<add> update(cfg, to, date) {
<add> const me = this;
<add> if (me._active) {
<add> const currentValue = me._target[me._prop];
<add> const elapsed = date - me._start;
<add> const remain = me._duration - elapsed;
<add> me._start = date;
<add> me._duration = Math.floor(Math.max(remain, cfg.duration));
<add> me._to = resolve([cfg.to, to, currentValue, cfg.from]);
<add> me._from = resolve([cfg.from, currentValue, to]);
<add> }
<add> }
<add>
<ide> cancel() {
<ide> const me = this;
<ide> if (me._active) {
<ide><path>src/core/core.animations.js
<ide> export default class Animations {
<ide> const animations = [];
<ide> const running = target.$animations || (target.$animations = {});
<ide> const props = Object.keys(values);
<add> const date = Date.now();
<ide> let i;
<ide>
<ide> for (i = props.length - 1; i >= 0; --i) {
<ide> export default class Animations {
<ide> }
<ide> const value = values[prop];
<ide> let animation = running[prop];
<add> const cfg = animatedProps.get(prop);
<add>
<ide> if (animation) {
<del> animation.cancel();
<add> if (cfg && animation.active()) {
<add> // There is an existing active animation, let's update that
<add> animation.update(cfg, value, date);
<add> continue;
<add> } else {
<add> animation.cancel();
<add> }
<ide> }
<del>
<del> const cfg = animatedProps.get(prop);
<ide> if (!cfg || !cfg.duration) {
<ide> // not animated, set directly to new value
<ide> target[prop] = value;
<ide><path>src/core/core.controller.js
<ide> export default class Chart {
<ide> options.onResize(me, newSize);
<ide> }
<ide>
<del> me.stop();
<ide> me.update('resize');
<ide> }
<ide> } | 3 |
Python | Python | return default value if comment is malformed | 77765efd94f1e17c2b93607f16b47417d7dc7d29 | <ide><path>libcloud/utils/publickey.py
<ide> def get_pubkey_ssh2_fingerprint(pubkey):
<ide>
<ide>
<ide> def get_pubkey_comment(pubkey, default=None):
<del> if pubkey.startswith("ssh-"):
<del> # This is probably an OpenSSH key
<del> return pubkey.strip().split(' ', 3)[2]
<add> try:
<add> if pubkey.startswith("ssh-"):
<add> # This is probably an OpenSSH key
<add> return pubkey.strip().split(' ', 3)[2]
<add> except IndexError:
<add> pass
<ide> if default:
<ide> return default
<ide> raise ValueError('Public key is not in a supported format') | 1 |
Javascript | Javascript | remove thirdparty fixme | e42af973452ed639ed34dadfd8eff0453f6501ce | <ide><path>actioncable/test/javascript/vendor/mock-socket.js
<ide> if (root.IPv6 === this) {
<ide> root.IPv6 = _IPv6;
<ide> }
<del>
<add>
<ide> return this;
<ide> }
<ide>
<ide> }(this, function (punycode, IPv6, SLD, root) {
<ide> 'use strict';
<ide> /*global location, escape, unescape */
<del> // FIXME: v2.0.0 renamce non-camelCase properties to uppercase
<ide> /*jshint camelcase: false */
<ide>
<ide> // save current URI variable, if any | 1 |
Javascript | Javascript | add a timeout to address a ci failures | b419a7b20b49425d6fa9d29ca254036263138f82 | <ide><path>test/configCases/plugins/profiling-plugin/index.js
<ide> import "./test.json";
<ide>
<del>it("should generate a events.json file", () => {
<add>it("should generate a events.json file", (done) => {
<ide> var fs = require("fs"),
<ide> path = require("path"),
<del> os = require("os");
<del> expect(fs.existsSync(path.join(__dirname, "events.json"))).toBe(true);
<add> os = require("os");
<add>
<add> // HACK: we need this timeout on the CI only,
<add> // because the filesystem is less responsive
<add> setTimeout(() => {
<add> expect(fs.existsSync(path.join(__dirname, "events.json"))).toBe(true);
<add> done();
<add> }, 500)
<ide> });
<ide>
<del>it("should have proper setup record inside of the json stream", () => {
<add>it("should have proper setup record inside of the json stream", (done) => {
<ide> var fs = require("fs"),
<ide> path = require("path"),
<ide> os = require("os");
<ide>
<del> // convert json stream to valid
<del> var source = JSON.parse(fs.readFileSync(path.join(__dirname, "events.json"), "utf-8").toString() + "{}]");
<del> expect(source[0].id).toEqual(1);
<add> // HACK: we need this timeout on the CI only,
<add> // because the filesystem is less responsive
<add> setTimeout(() => {
<add> // convert json stream to valid
<add> var source = JSON.parse(fs.readFileSync(path.join(__dirname, "events.json"), "utf-8").toString() + "{}]");
<add> expect(source[0].id).toEqual(1);
<add> }, 500)
<ide> }); | 1 |
Javascript | Javascript | fix priority of clean-up function on deletion | 05dce7598a60d38d39a6b32572b54e1408c29d9b | <ide><path>packages/react-reconciler/src/ReactFiberCommitWork.js
<ide> import type {CapturedValue, CapturedError} from './ReactCapturedValue';
<ide> import type {SuspenseState} from './ReactFiberSuspenseComponent';
<ide> import type {FunctionComponentUpdateQueue} from './ReactFiberHooks';
<ide> import type {Thenable} from './ReactFiberWorkLoop';
<add>import type {ReactPriorityLevel} from './SchedulerWithReactIntegration';
<ide>
<ide> import {unstable_wrap as Schedule_tracing_wrap} from 'scheduler/tracing';
<ide> import {
<ide> import {
<ide> MountPassive,
<ide> } from './ReactHookEffectTags';
<ide> import {didWarnAboutReassigningProps} from './ReactFiberBeginWork';
<add>import {runWithPriority, NormalPriority} from './SchedulerWithReactIntegration';
<ide>
<ide> let didWarnAboutUndefinedSnapshotBeforeUpdate: Set<mixed> | null = null;
<ide> if (__DEV__) {
<ide> function commitDetachRef(current: Fiber) {
<ide> // User-originating errors (lifecycles and refs) should not interrupt
<ide> // deletion, so don't let them throw. Host-originating errors should
<ide> // interrupt deletion, so it's okay
<del>function commitUnmount(current: Fiber): void {
<add>function commitUnmount(
<add> current: Fiber,
<add> renderPriorityLevel: ReactPriorityLevel,
<add>): void {
<ide> onCommitUnmount(current);
<ide>
<ide> switch (current.tag) {
<ide> function commitUnmount(current: Fiber): void {
<ide> const lastEffect = updateQueue.lastEffect;
<ide> if (lastEffect !== null) {
<ide> const firstEffect = lastEffect.next;
<del> let effect = firstEffect;
<del> do {
<del> const destroy = effect.destroy;
<del> if (destroy !== undefined) {
<del> safelyCallDestroy(current, destroy);
<del> }
<del> effect = effect.next;
<del> } while (effect !== firstEffect);
<add>
<add> // When the owner fiber is deleted, the destroy function of a passive
<add> // effect hook is called during the synchronous commit phase. This is
<add> // a concession to implementation complexity. Calling it in the
<add> // passive effect phase (like they usually are, when dependencies
<add> // change during an update) would require either traversing the
<add> // children of the deleted fiber again, or including unmount effects
<add> // as part of the fiber effect list.
<add> //
<add> // Because this is during the sync commit phase, we need to change
<add> // the priority.
<add> //
<add> // TODO: Reconsider this implementation trade off.
<add> const priorityLevel =
<add> renderPriorityLevel > NormalPriority
<add> ? NormalPriority
<add> : renderPriorityLevel;
<add> runWithPriority(priorityLevel, () => {
<add> let effect = firstEffect;
<add> do {
<add> const destroy = effect.destroy;
<add> if (destroy !== undefined) {
<add> safelyCallDestroy(current, destroy);
<add> }
<add> effect = effect.next;
<add> } while (effect !== firstEffect);
<add> });
<ide> }
<ide> }
<ide> break;
<ide> function commitUnmount(current: Fiber): void {
<ide> // We are also not using this parent because
<ide> // the portal will get pushed immediately.
<ide> if (supportsMutation) {
<del> unmountHostComponents(current);
<add> unmountHostComponents(current, renderPriorityLevel);
<ide> } else if (supportsPersistence) {
<ide> emptyPortalContainer(current);
<ide> }
<ide> function commitUnmount(current: Fiber): void {
<ide> }
<ide> }
<ide>
<del>function commitNestedUnmounts(root: Fiber): void {
<add>function commitNestedUnmounts(
<add> root: Fiber,
<add> renderPriorityLevel: ReactPriorityLevel,
<add>): void {
<ide> // While we're inside a removed host node we don't want to call
<ide> // removeChild on the inner nodes because they're removed by the top
<ide> // call anyway. We also want to call componentWillUnmount on all
<ide> // composites before this host node is removed from the tree. Therefore
<ide> // we do an inner loop while we're still inside the host node.
<ide> let node: Fiber = root;
<ide> while (true) {
<del> commitUnmount(node);
<add> commitUnmount(node, renderPriorityLevel);
<ide> // Visit children because they may contain more composite or host nodes.
<ide> // Skip portals because commitUnmount() currently visits them recursively.
<ide> if (
<ide> function commitPlacement(finishedWork: Fiber): void {
<ide> }
<ide> }
<ide>
<del>function unmountHostComponents(current): void {
<add>function unmountHostComponents(current, renderPriorityLevel): void {
<ide> // We only have the top Fiber that was deleted but we need to recurse down its
<ide> // children to find all the terminal nodes.
<ide> let node: Fiber = current;
<ide> function unmountHostComponents(current): void {
<ide> }
<ide>
<ide> if (node.tag === HostComponent || node.tag === HostText) {
<del> commitNestedUnmounts(node);
<add> commitNestedUnmounts(node, renderPriorityLevel);
<ide> // After all the children have unmounted, it is now safe to remove the
<ide> // node from the tree.
<ide> if (currentParentIsContainer) {
<ide> function unmountHostComponents(current): void {
<ide> // Don't visit children because we already visited them.
<ide> } else if (node.tag === FundamentalComponent) {
<ide> const fundamentalNode = node.stateNode.instance;
<del> commitNestedUnmounts(node);
<add> commitNestedUnmounts(node, renderPriorityLevel);
<ide> // After all the children have unmounted, it is now safe to remove the
<ide> // node from the tree.
<ide> if (currentParentIsContainer) {
<ide> function unmountHostComponents(current): void {
<ide> continue;
<ide> }
<ide> } else {
<del> commitUnmount(node);
<add> commitUnmount(node, renderPriorityLevel);
<ide> // Visit children because we may find more host components below.
<ide> if (node.child !== null) {
<ide> node.child.return = node;
<ide> function unmountHostComponents(current): void {
<ide> }
<ide> }
<ide>
<del>function commitDeletion(current: Fiber): void {
<add>function commitDeletion(
<add> current: Fiber,
<add> renderPriorityLevel: ReactPriorityLevel,
<add>): void {
<ide> if (supportsMutation) {
<ide> // Recursively delete all host nodes from the parent.
<ide> // Detach refs and call componentWillUnmount() on the whole subtree.
<del> unmountHostComponents(current);
<add> unmountHostComponents(current, renderPriorityLevel);
<ide> } else {
<ide> // Detach refs and call componentWillUnmount() on the whole subtree.
<del> commitNestedUnmounts(current);
<add> commitNestedUnmounts(current, renderPriorityLevel);
<ide> }
<ide> detachFiber(current);
<ide> }
<ide><path>packages/react-reconciler/src/ReactFiberWorkLoop.js
<ide> function commitRootImpl(root, renderPriorityLevel) {
<ide> nextEffect = firstEffect;
<ide> do {
<ide> if (__DEV__) {
<del> invokeGuardedCallback(null, commitMutationEffects, null);
<add> invokeGuardedCallback(
<add> null,
<add> commitMutationEffects,
<add> null,
<add> renderPriorityLevel,
<add> );
<ide> if (hasCaughtError()) {
<ide> invariant(nextEffect !== null, 'Should be working on an effect.');
<ide> const error = clearCaughtError();
<ide> function commitRootImpl(root, renderPriorityLevel) {
<ide> }
<ide> } else {
<ide> try {
<del> commitMutationEffects();
<add> commitMutationEffects(renderPriorityLevel);
<ide> } catch (error) {
<ide> invariant(nextEffect !== null, 'Should be working on an effect.');
<ide> captureCommitPhaseError(nextEffect, error);
<ide> function commitBeforeMutationEffects() {
<ide> }
<ide> }
<ide>
<del>function commitMutationEffects() {
<add>function commitMutationEffects(renderPriorityLevel) {
<ide> // TODO: Should probably move the bulk of this function to commitWork.
<ide> while (nextEffect !== null) {
<ide> setCurrentDebugFiberInDEV(nextEffect);
<ide> function commitMutationEffects() {
<ide> break;
<ide> }
<ide> case Deletion: {
<del> commitDeletion(nextEffect);
<add> commitDeletion(nextEffect, renderPriorityLevel);
<ide> break;
<ide> }
<ide> }
<ide><path>packages/react-reconciler/src/__tests__/ReactSchedulerIntegration-test.internal.js
<ide> describe('ReactSchedulerIntegration', () => {
<ide> Scheduler.unstable_yieldValue(
<ide> `Effect priority: ${getCurrentPriorityAsString()}`,
<ide> );
<add> return () => {
<add> Scheduler.unstable_yieldValue(
<add> `Effect clean-up priority: ${getCurrentPriorityAsString()}`,
<add> );
<add> };
<ide> });
<ide> return null;
<ide> }
<ide> describe('ReactSchedulerIntegration', () => {
<ide> });
<ide> expect(Scheduler).toHaveYielded([
<ide> 'Render priority: UserBlocking',
<add> 'Effect clean-up priority: Normal',
<ide> 'Effect priority: Normal',
<ide> ]);
<ide>
<ide> describe('ReactSchedulerIntegration', () => {
<ide> });
<ide> expect(Scheduler).toHaveYielded([
<ide> 'Render priority: Idle',
<add> 'Effect clean-up priority: Idle',
<ide> 'Effect priority: Idle',
<ide> ]);
<ide> });
<ide> describe('ReactSchedulerIntegration', () => {
<ide> ]);
<ide> });
<ide>
<add> it('passive effect clean-up functions have correct priority even when component is deleted', async () => {
<add> const {useEffect} = React;
<add> function ReadPriority({step}) {
<add> useEffect(() => {
<add> return () => {
<add> Scheduler.unstable_yieldValue(
<add> `Effect clean-up priority: ${getCurrentPriorityAsString()}`,
<add> );
<add> };
<add> });
<add> return null;
<add> }
<add>
<add> await ReactNoop.act(async () => {
<add> ReactNoop.render(<ReadPriority />);
<add> });
<add> await ReactNoop.act(async () => {
<add> Scheduler.unstable_runWithPriority(ImmediatePriority, () => {
<add> ReactNoop.render(null);
<add> });
<add> });
<add> expect(Scheduler).toHaveYielded(['Effect clean-up priority: Normal']);
<add>
<add> await ReactNoop.act(async () => {
<add> ReactNoop.render(<ReadPriority />);
<add> });
<add> await ReactNoop.act(async () => {
<add> Scheduler.unstable_runWithPriority(UserBlockingPriority, () => {
<add> ReactNoop.render(null);
<add> });
<add> });
<add> expect(Scheduler).toHaveYielded(['Effect clean-up priority: Normal']);
<add>
<add> // Renders lower than normal priority spawn effects at the same priority
<add> await ReactNoop.act(async () => {
<add> ReactNoop.render(<ReadPriority />);
<add> });
<add> await ReactNoop.act(async () => {
<add> Scheduler.unstable_runWithPriority(IdlePriority, () => {
<add> ReactNoop.render(null);
<add> });
<add> });
<add> expect(Scheduler).toHaveYielded(['Effect clean-up priority: Idle']);
<add> });
<add>
<ide> it('after completing a level of work, infers priority of the next batch based on its expiration time', () => {
<ide> function App({label}) {
<ide> Scheduler.unstable_yieldValue( | 3 |
PHP | PHP | add validator as a string | 5cdef0d31228b53ea50c1d5aa7bd42954468d4f3 | <ide><path>src/View/Form/EntityContext.php
<ide>
<ide> use Cake\Network\Request;
<ide> use Cake\ORM\Entity;
<add>use Cake\ORM\TableRegistry;
<ide> use Cake\Validation\Validator;
<ide> use Traversable;
<ide>
<ide> class EntityContext {
<ide> */
<ide> protected $_validators = [];
<ide>
<add>/**
<add> * A dictionary of tables
<add> *
<add> * @var array
<add> */
<add> protected $_tables = [];
<add>
<ide> /**
<ide> * Constructor.
<ide> *
<ide> protected function _prepare() {
<ide> if (is_string($this->_context['table'])) {
<ide> $plural = $this->_context['table'];
<ide> }
<del> $this->_pluralName = $plural;
<add> $table = TableRegistry::get($plural);
<ide>
<ide> if (is_object($this->_context['validator'])) {
<ide> $this->_validators['_default'] = $this->_context['validator'];
<add> } elseif (is_string($this->_context['validator'])) {
<add> $this->_validators['_default'] = $table->validator($this->_context['validator']);
<ide> }
<add>
<add> $this->_pluralName = $plural;
<add> $this->_tables[$plural] = $table;
<ide> }
<ide>
<ide> /**
<ide><path>tests/TestCase/View/Form/EntityContextTest.php
<ide> public function testIsRequired() {
<ide> $this->assertFalse($context->isRequired('nope'));
<ide> }
<ide>
<del> public function testIsRequiredCustomValidationMethod() {
<del> $this->markTestIncomplete();
<add>/**
<add> * Test validator as a string.
<add> *
<add> * @return void
<add> */
<add> public function testIsRequiredStringValidator() {
<add> $articles = TableRegistry::get('Articles');
<add>
<add> $validator = $articles->validator();
<add> $validator->add('title', 'minlength', [
<add> 'rule' => ['minlength', 10]
<add> ])
<add> ->add('body', 'maxlength', [
<add> 'rule' => ['maxlength', 1000]
<add> ])->allowEmpty('body');
<add>
<add> $context = new EntityContext($this->request, [
<add> 'entity' => new Entity(),
<add> 'table' => 'Articles',
<add> 'validator' => 'default',
<add> ]);
<add>
<add> $this->assertTrue($context->isRequired('Articles.title'));
<add> $this->assertTrue($context->isRequired('title'));
<add> $this->assertFalse($context->isRequired('Articles.body'));
<add> $this->assertFalse($context->isRequired('body'));
<ide> }
<ide>
<ide> public function testIsRequiredAssociated() { | 2 |
PHP | PHP | add auth directive | 71d38b044dad82eb8dfdba2ee2edb69eca415324 | <ide><path>resources/views/welcome.blade.php
<ide> <div class="flex-center position-ref full-height">
<ide> @if (Route::has('login'))
<ide> <div class="top-right links">
<del> @if (Auth::check())
<add> @auth
<ide> <a href="{{ url('/home') }}">Home</a>
<ide> @else
<ide> <a href="{{ route('login') }}">Login</a>
<ide> <a href="{{ route('register') }}">Register</a>
<del> @endif
<add> @endauth
<ide> </div>
<ide> @endif
<ide> | 1 |
Text | Text | add dev report 2017-06-26 | 8b0384fd8918e82459aab037d50bca6394bbf781 | <ide><path>reports/2017-06-26.md
<add># Development Report for June 26, 2017
<add>
<add>## Moby Summit
<add>
<add>The Moby Summit held in San Francisco was very active and well attended ([blog](http://mobyproject.org/blog/2017/06/26/moby-summit-recap/) / [linuxkit table notes](https://github.com/linuxkit/linuxkit/blob/master/reports/2017-06-19-summit.md) [#2090](https://github.com/linuxkit/linuxkit/pull/2090) [#2033](https://github.com/linuxkit/linuxkit/pull/2033) [@mgoelzer] [@justincormack]).
<add>
<add>## Container Engine
<add>
<add>Thanks to @fabiokung there is no container locks anymore on `docker ps` [#31273](https://github.com/moby/moby/pull/31273)
<add>
<add>## BuildKit
<add>
<add>[Repo](https://github.com/moby/buildkit)
<add>[Proposal](https://github.com/moby/moby/issues/32925)
<add>
<add>New development repo is open at https://github.com/moby/buildkit
<add>
<add>The readme file provides examples how to get started. You can see an example of building BuildKit with BuildKit.
<add>
<add>There are lots of new issues opened as well to track the missing functionality. You are welcomed to help on any of them or discuss the design there.
<add>
<add>Last week most of the work was done on improving the `llb` client library for more complicated use cases and providing traces and interactive progress of executed build jobs.
<add>
<add>The `llb` client package is a go library that helps you to generate the build definition graph. It uses chained methods to make it easy to describe what steps need to be running. Mounts can be added to the execution steps for defining multiple inputs or outputs. To prepare the graph, you just have to call `Marshal()` on a leaf node that will generate the protobuf definition for everything required to build that node.
<add>
<add>### Typed Dockerfile parsing
<add>
<add>[PR](https://github.com/moby/moby/pull/33492)
<add>
<add>This PR that enables parsing Dockerfiles into typed structures so they can be preprocessed to eliminate unnecessary build stages and reused with different kinds of dispatchers(eg. BuildKit).
<add>
<add>The PR had some review and updates in last week. Should be ready to code review soon.
<add>
<add>### Merged: Long running session & incremental file sending
<add>
<add>[PR](https://github.com/moby/moby/pull/32677)
<add>
<add>Incremental context sending PR was merged and is expected to land in `v17.07`.
<add>
<add>This feature experimental feature lets you skip sending the build context to the daemon on repeated builder invocations during development. Currently, this feature requires a CLI flag `--stream=true`. If this flag is used, one first builder invocation full build context is sent to the daemon. On a second attempt, only the changed files are transferred.
<add>
<add>Previous build context is saved in the build cache, and you can see how much space it takes form `docker system df`. Build cache will be automatically garbage collected and can also be manually cleared with `docker prune`.
<add>
<add>### Quality: Dependency interface switch
<add>
<add>[Move file copying from the daemon to the builder](https://github.com/moby/moby/pull/33454) PR was merged.
<add>
<add>
<add>### Proposals for new Dockerfile features that need design feedback:
<add>
<add>[Add IMPORT/EXPORT commands to Dockerfile](https://github.com/moby/moby/issues/32100)
<add>
<add>[Add `DOCKEROS/DOCKERARCH` default ARG to Dockerfile](https://github.com/moby/moby/issues/32487)
<add>
<add>[Add support for `RUN --mount`](https://github.com/moby/moby/issues/32507)
<add>
<add>[DAG image builder](https://github.com/moby/moby/issues/32550)
<add>
<add>[Option to export the hash of the build context](https://github.com/moby/moby/issues/32963) (new)
<add>
<add>[Allow --cache-from=*](https://github.com/moby/moby/issues/33002#issuecomment-299041162) (new)
<add>
<add>[Provide advanced .dockeringore use-cases](https://github.com/moby/moby/issues/12886) [2](https://github.com/moby/moby/issues/12886#issuecomment-306247989)
<add>
<add>If you are interested in implementing any of them, leave a comment on the specific issues.
<add>
<add>### Other builder PRs merged last week
<add>
<add>[Warn/deprecate continuing on empty lines in `Dockerfile`](https://github.com/moby/moby/pull/29161)
<add>
<add>[Fix behavior of absolute paths in .dockerignore](https://github.com/moby/moby/pull/32088)
<add>
<add>[fix copy —from conflict with force pull](https://github.com/moby/moby/pull/33735)
<add>
<add>### Builder features currently in code-review:
<add>
<add>[Fix handling of remote "git@" notation](https://github.com/moby/moby/pull/33696)
<add>
<add>[builder: Emit a BuildResult after squashing.](https://github.com/moby/moby/pull/33824)
<add>
<add>[Fix shallow git clone in docker-build](https://github.com/moby/moby/pull/33704)
<add>
<add>### Backlog
<add>
<add>[Build secrets](https://github.com/moby/moby/issues/33343) has not got much traction. If you want this feature to become a reality, please make yourself heard.
<add>
<add>## LinuxKit
<add>
<add>* **Kernel GPG verification:** The kernel compilation containers now verify the GPG and SHA256
<add> checksums before building the binaries. ([#2062](https://github.com/linuxkit/linuxkit/issues/2062) [#2083](https://github.com/linuxkit/linuxkit/issues/2083) [@mscribe] [@justincormack] [@rn] [@riyazdf]).
<add> The base Alpine build image now includes `gnupg` to support this feature ([#2091](https://github.com/linuxkit/linuxkit/issues/2091) [@riyazdf] [@rn]).
<add>
<add>* **Security SIG on Landlock:** The third Moby Security SIG focussed on the [Landlock](https://github.com/landlock-lsm) security module that provides unprivileged fine-grained sandboxing to applications. There are videos and forum links ([#2087](https://github.com/linuxkit/linuxkit/issues/2087) [#2089](https://github.com/linuxkit/linuxkit/issues/2089) [#2073](https://github.com/linuxkit/linuxkit/issues/2073) [@riyazdf]).
<add>
<add>* **Networking drivers now modules:** The kernels have been updated to 4.11.6/4.9.33/4.4.73, and many drivers are now loaded as modules to speed up boot-time ([#2095](https://github.com/linuxkit/linuxkit/issues/2095) [#2061](https://github.com/linuxkit/linuxkit/issues/2061) [@rn] [@justincormack] [@tych0])
<add>
<add>- **Whaley important update:** The ASCII logo was updated and we fondly wave goodbye to the waves. ([#2084](https://github.com/linuxkit/linuxkit/issues/2084) [@thaJeztah] [@rn])
<add>
<add>- **Containerised getty and sshd:** The login services now run in their own mount namespace, which was confusing people since they were expecting it to be on the host filesystem. This is now being addressed via a reminder in the `motd` upon login ([#2078](https://github.com/linuxkit/linuxkit/issues/2078) [#2097](https://github.com/linuxkit/linuxkit/issues/2097) [@deitch] [@ijc] [@justincormack] [@riyazdf] [@rn])
<add>
<add>- **Hardened user copying:** The RFC on ensuring that we use a hardened kernel/userspace copying system was closed, as it is enabled by default on all our modern kernels and a regression test is included by default ([#2086](https://github.com/linuxkit/linuxkit/issues/2086) [@fntlnz] [@riyazdf]).
<add>
<add>- **Vultr provider:** There is an ongoing effort to add a metadata provider for [Vultr](http://vultr.com) ([#2101](https://github.com/linuxkit/linuxkit/issues/2101) [@furious-luke] [@justincormack]).
<add>
<add>### Packages and Projects
<add>
<add>- Simplified Makefiles for packages ([#2080](https://github.com/linuxkit/linuxkit/issues/2080) [@justincormack] [@rn])
<add>- The MirageOS SDK is integrating many upstream changes from dependent libraries, for the DHCP client ([#2070](https://github.com/linuxkit/linuxkit/issues/2070) [#2072](https://github.com/linuxkit/linuxkit/issues/2072) [@samoht] [@talex5] [@avsm]).
<add>
<add>### Documentation and Tests
<add>
<add>- A comprehensive test suite for containerd is now integrated into LinuxKit tests ([#2062](https://github.com/linuxkit/linuxkit/issues/2062) [@AkihiroSuda] [@justincormack] [@rn])
<add>- Fix documentation links ([#2074](https://github.com/linuxkit/linuxkit/issues/2074) [@ndauten] [@justincormack])
<add>- Update RTF version ([#2077](https://github.com/linuxkit/linuxkit/issues/2077) [@justincormack])
<add>- tests: add build test for Docker for Mac blueprint ([#2093](https://github.com/linuxkit/linuxkit/issues/2093) [@riyazdf] [@MagnusS])
<add>- Disable Qemu EFI ISO test for now ([#2100](https://github.com/linuxkit/linuxkit/issues/2100) [@justincormack])
<add>- The CI whitelists and ACLs were updated ([linuxkit-ci#11](https://github.com/linuxkit/linuxkit-ce/issues/11) [linuxkit-ci#15](https://github.com/linuxkit/linuxkit-ce/issues/15) [linuxkit/linuxkit-ci#10](https://github.com/linuxkit/linuxkit-ce/issues/10) [@rn] [@justincormack])
<add>- Fix spelling errors ([#2079](https://github.com/linuxkit/linuxkit/issues/2079) [@ndauten])
<add>- Fix typo in dev report ([#2094](https://github.com/linuxkit/linuxkit/issues/2094) [@justincormack])
<add>- Fix dead Link to VMWare File ([#2082](https://github.com/linuxkit/linuxkit/issues/2082) [@davefreitag])
<ide>\ No newline at end of file | 1 |
Ruby | Ruby | remove unnecessary full paths | 1aded31fec4a98c2521bca685166f82a8d7d66c6 | <ide><path>Library/Homebrew/test/test_utils.rb
<ide> def test_shell_profile
<ide> end
<ide>
<ide> def test_popen_read
<del> out = Utils.popen_read("/bin/sh", "-c", "echo success").chomp
<add> out = Utils.popen_read("sh", "-c", "echo success").chomp
<ide> assert_equal "success", out
<ide> assert_predicate $?, :success?
<ide> end
<ide>
<ide> def test_popen_read_with_block
<del> out = Utils.popen_read("/bin/sh", "-c", "echo success") do |pipe|
<add> out = Utils.popen_read("sh", "-c", "echo success") do |pipe|
<ide> pipe.read.chomp
<ide> end
<ide> assert_equal "success", out
<ide> assert_predicate $?, :success?
<ide> end
<ide>
<ide> def test_popen_write_with_block
<del> Utils.popen_write("/usr/bin/grep", "-q", "success") do |pipe|
<add> Utils.popen_write("grep", "-q", "success") do |pipe|
<ide> pipe.write("success\n")
<ide> end
<ide> assert_predicate $?, :success? | 1 |
Ruby | Ruby | use ruby for mocking | caf1bfccc680510b48e058d40c2a99cae965b5cb | <ide><path>actionpack/test/controller/url_for_test.rb
<ide> def test_subdomain_may_be_changed
<ide> end
<ide>
<ide> def test_subdomain_may_be_object
<del> model = mock(:to_param => 'api')
<add> model = Class.new { def self.to_param; 'api'; end }
<ide> add_host!
<ide> assert_equal('http://api.basecamphq.com/c/a/i',
<ide> W.new.url_for(:subdomain => model, :controller => 'c', :action => 'a', :id => 'i') | 1 |
Python | Python | add log level as prefixes to respective messages | d04c9ef75a711c9117f5c5662ca604ed5b88607d | <ide><path>numpy/distutils/log.py
<ide> def set_verbosity(v, force=False):
<ide>
<ide> # don't use INFO,.. flags in set_verbosity, these flags are for set_threshold.
<ide> set_verbosity(0, force=True)
<add>
<add>
<add>_error = error
<add>_warn = warn
<add>_info = info
<add>_debug = debug
<add>
<add>
<add>def error(msg, *a, **kw):
<add> _error(f"ERROR: {msg}", *a, **kw)
<add>
<add>
<add>def warn(msg, *a, **kw):
<add> _warn(f"WARN: {msg}", *a, **kw)
<add>
<add>
<add>def info(msg, *a, **kw):
<add> _info(f"INFO: {msg}", *a, **kw)
<add>
<add>
<add>def debug(msg, *a, **kw):
<add> _debug(f"DEBUG: {msg}", *a, **kw)
<ide><path>numpy/distutils/tests/test_log.py
<add>import io
<add>import re
<add>from contextlib import redirect_stdout
<add>
<add>import pytest
<add>
<add>from numpy.distutils import log
<add>
<add>
<add>def setup_module():
<add> log.set_verbosity(2, force=True) # i.e. DEBUG
<add>
<add>
<add>def teardown_module():
<add> log.set_verbosity(0, force=True) # the default
<add>
<add>
<add>r_ansi = re.compile(r"\x1B(?:[@-Z\\-_]|\[[0-?]*[ -/]*[@-~])")
<add>
<add>
<add>@pytest.mark.parametrize("func_name", ["error", "warn", "info", "debug"])
<add>def test_log_prefix(func_name):
<add> func = getattr(log, func_name)
<add> msg = f"{func_name} message"
<add> f = io.StringIO()
<add> with redirect_stdout(f):
<add> func(msg)
<add> out = f.getvalue()
<add> assert out # sanity check
<add> clean_out = r_ansi.sub("", out)
<add> line = next(line for line in clean_out.splitlines())
<add> assert line == f"{func_name.upper()}: {msg}" | 2 |
Ruby | Ruby | initialize attributes in initializer | 566d6b3a462c740913852d889f39d6f6824d8c88 | <ide><path>Library/Homebrew/download_strategy.rb
<ide> def head?
<ide> end
<ide>
<ide> class CurlDownloadStrategy < AbstractDownloadStrategy
<del> def mirrors
<del> @mirrors ||= resource.mirrors.dup
<del> end
<del>
<del> def tarball_path
<del> @tarball_path ||= Pathname.new("#{HOMEBREW_CACHE}/#{name}-#{resource.version}#{ext}")
<del> end
<add> attr_reader :mirrors, :tarball_path, :temporary_path
<ide>
<del> def temporary_path
<del> @temporary_path ||= Pathname.new("#{tarball_path}.incomplete")
<add> def initialize(name, resource)
<add> super
<add> @mirrors = resource.mirrors.dup
<add> @tarball_path = HOMEBREW_CACHE.join("#{name}-#{resource.version}#{ext}")
<add> @temporary_path = Pathname.new("#{tarball_path}.incomplete")
<ide> end
<ide>
<ide> def cached_location | 1 |
Ruby | Ruby | add missing configuration to middleware test | 5aa60833355416f1b877967cdd2c22b37e119102 | <ide><path>railties/test/application/middleware_test.rb
<ide> def app
<ide> test "default middleware stack when requests are local" do
<ide> add_to_config "config.consider_all_requests_local = true"
<ide> add_to_config "config.active_record.migration_error = :page_load"
<add> add_to_config "config.server_timing = true"
<ide>
<ide> boot!
<ide> | 1 |
Python | Python | copy `node.d` only with node_use_dtrace | e0c530259050c4ecc6fe9cf8963992575e43f376 | <ide><path>tools/install.py
<ide> def subdir_files(path, dest, action):
<ide> def files(action):
<ide> action(['out/Release/node'], 'bin/node')
<ide>
<del> # install unconditionally, checking if the platform supports dtrace doesn't
<del> # work when cross-compiling and besides, there's at least one linux flavor
<del> # with dtrace support now (oracle's "unbreakable" linux)
<del> action(['out/Release/node.d'], 'lib/dtrace/node.d')
<add> if 'true' == variables.get('node_use_dtrace'):
<add> action(['out/Release/node.d'], 'lib/dtrace/node.d')
<ide>
<ide> if 'freebsd' in sys.platform or 'openbsd' in sys.platform:
<ide> action(['doc/node.1'], 'man/man1/') | 1 |
Python | Python | update tests with new behavior | b196eca17de42aab4819f9b735fb277c5c034190 | <ide><path>t/unit/worker/test_loops.py
<ide> def test_on_task_message_missing_name(self):
<ide> on_task(msg)
<ide> x.on_unknown_message.assert_called_with(msg.decode(), msg)
<ide>
<del> def test_on_task_not_registered(self):
<add> def test_on_task_pool_raises(self):
<ide> x, on_task, msg, strategy = self.task_context(self.add.s(2, 2))
<del> exc = strategy.side_effect = KeyError(self.add.name)
<del> on_task(msg)
<del> x.on_invalid_task.assert_called_with(None, msg, exc)
<add> exc = strategy.side_effect = ValueError()
<add> with pytest.raises(ValueError):
<add> on_task(msg)
<ide>
<ide> def test_on_task_InvalidTaskError(self):
<ide> x, on_task, msg, strategy = self.task_context(self.add.s(2, 2))
<ide><path>t/unit/worker/test_worker.py
<ide> def test_process_task_raise_regular(self):
<ide> args=[4, 8, 10], kwargs={},
<ide> )
<ide> task = Request(m, app=self.app)
<del> worker._process_task(task)
<add> with pytest.raises(KeyError):
<add> worker._process_task(task)
<ide> worker.pool.stop()
<ide>
<ide> def test_start_catches_base_exceptions(self): | 2 |
Ruby | Ruby | remove legacy cask cache instead of migrating | f7c6fc058f5eff55281fd7559b4217184162edcf | <ide><path>Library/Homebrew/cask/lib/hbc.rb
<ide> module Hbc
<ide>
<ide> def self.init
<ide> Cache.ensure_cache_exists
<del> Cache.migrate_legacy_cache
<add> Cache.delete_legacy_cache
<ide>
<ide> Caskroom.migrate_caskroom_from_repo_to_prefix
<ide> Caskroom.ensure_caskroom_exists
<ide><path>Library/Homebrew/cask/lib/hbc/cache.rb
<ide> def ensure_cache_exists
<ide> Hbc.cache.mkpath
<ide> end
<ide>
<del> def migrate_legacy_cache
<add> def delete_legacy_cache
<ide> return unless Hbc.legacy_cache.exist?
<ide>
<del> ohai "Migrating cached files to #{Hbc.cache}..."
<del> Hbc.legacy_cache.children.select(&:symlink?).each do |symlink|
<del> file = symlink.readlink
<del>
<del> new_name = file.basename
<del> .sub(/\-((?:(\d|#{DSL::Version::DIVIDER_REGEX})*\-\2*)*[^\-]+)$/x,
<del> '--\1')
<del>
<del> renamed_file = Hbc.cache.join(new_name)
<del>
<del> if file.exist?
<del> puts "#{file} -> #{renamed_file}"
<del> FileUtils.mv(file, renamed_file)
<del> end
<del>
<del> FileUtils.rm(symlink)
<del> end
<del>
<add> ohai "Deleting legacy cache at #{Hbc.legacy_cache}..."
<ide> FileUtils.remove_entry_secure(Hbc.legacy_cache)
<ide> end
<ide> end | 2 |
Python | Python | add distant debugging | 5adc20723bbff4fea628f526b256a60ccd98dbf5 | <ide><path>examples/run_openai_gpt.py
<ide> def main():
<ide> parser.add_argument('--weight_decay', type=float, default=0.01)
<ide> parser.add_argument('--lm_coef', type=float, default=0.5)
<ide> parser.add_argument('--n_valid', type=int, default=374)
<add>
<add> parser.add_argument('--server_ip', type=str, default='')
<add> parser.add_argument('--server_port', type=str, default='')
<ide> args = parser.parse_args()
<ide> print(args)
<ide>
<add> # Some distant debugging
<add> # See https://code.visualstudio.com/docs/python/debugging#_attach-to-a-local-script
<add> import ptvsd
<add> print(sys.argv)
<add> print("Waiting for debugger attach")
<add> ptvsd.enable_attach(address=(args.server_ip, args.server_port), redirect_output=True)
<add> ptvsd.wait_for_attach()
<add>
<add>
<ide> random.seed(args.seed)
<ide> np.random.seed(args.seed)
<ide> torch.manual_seed(args.seed) | 1 |
Text | Text | add dev docs on satellite packages | 515d5c65d5f5d05eb8d2777e59cb5680dfcb4bd9 | <ide><path>extra/DEVELOPER_DOCS/Satellite Packages.md
<add># spaCy Satellite Packages
<add>
<add>This is a list of all the active repos relevant to spaCy besides the main one, with short descriptions, history, and current status. Archived repos will not be covered.
<add>
<add>## Always Included in spaCy
<add>
<add>These packages are always pulled in when you install spaCy. Most of them are direct dependencies, but some are transitive dependencies through other packages.
<add>
<add>- [spacy-legacy](https://github.com/explosion/spacy-legacy): When an architecture in spaCy changes enough to get a new version, the old version is frozen and moved to spacy-legacy. This allows us to keep the core library slim while also preserving backwards compatability.
<add>- [thinc](https://github.com/explosion/thinc): Thinc is the machine learning library that powers trainable components in spaCy. It wraps backends like Numpy, PyTorch, and Tensorflow to provide a functional interface for specifying architectures.
<add>- [catalogue](https://github.com/explosion/catalogue): Small library for adding function registries, like those used for model architectures in spaCy.
<add>- [confection](https://github.com/explosion/confection): This library contains the functionality for config parsing that was formerly contained directly in Thinc.
<add>- [spacy-loggers](https://github.com/explosion/spacy-loggers): Contains loggers beyond the default logger available in spaCy's core code base. This includes loggers integrated with third-party services, which may differ in release cadence from spaCy itself.
<add>- [wasabi](https://github.com/explosion/wasabi): A command line formatting library, used for terminal output in spaCy.
<add>- [srsly](https://github.com/explosion/srsly): A wrapper that vendors several serialization libraries for spaCy. Includes parsers for JSON, JSONL, MessagePack, (extended) Pickle, and YAML.
<add>- [preshed](https://github.com/explosion/preshed): A Cython library for low-level data structures like hash maps, used for memory efficient data storage.
<add>- [cython-blis](https://github.com/explosion/cython-blis): Fast matrix multiplication using BLIS without depending on system libraries. Required by Thinc, rather than spaCy directly.
<add>- [murmurhash](https://github.com/explosion/murmurhash): A wrapper library for a C++ murmurhash implementation, used for string IDs in spaCy and preshed.
<add>- [cymem](https://github.com/explosion/cymem): A small library for RAII-style memory management in Cython.
<add>
<add>## Optional Extensions for spaCy
<add>
<add>These are repos that can be used by spaCy but aren't part of a default installation. Many of these are wrappers to integrate various kinds of third-party libraries.
<add>
<add>- [spacy-transformers](https://github.com/explosion/spacy-transformers): A wrapper for the [HuggingFace Transformers](https://huggingface.co/docs/transformers/index) library, this handles the extensive conversion necessary to coordinate spaCy's powerful `Doc` representation, training pipeline, and the Transformer embeddings. When released, this was known as `spacy-pytorch-transformers`, but it changed to the current name when HuggingFace update the name of their library as well.
<add>- [spacy-huggingface-hub](https://github.com/explosion/spacy-huggingface-hub): This package has a CLI script for uploading a packaged spaCy pipeline (created with `spacy package`) to the [Hugging Face Hub](https://huggingface.co/models).
<add>- [spacy-alignments](https://github.com/explosion/spacy-alignments): A wrapper for the tokenizations library (mentioned below) with a modified build system to simplify cross-platform wheel creation. Used in spacy-transformers for aligning spaCy and HuggingFace tokenizations.
<add>- [spacy-experimental](https://github.com/explosion/spacy-experimental): Experimental components that are not quite ready for inclusion in the main spaCy library. Usually there are unresolved questions around their APIs, so the experimental library allows us to expose them to the community for feedback before fully integrating them.
<add>- [spacy-lookups-data](https://github.com/explosion/spacy-lookups-data): A repository of linguistic data, such as lemmas, that takes up a lot of disk space. Originally created to reduce the size of the spaCy core library. This is mainly useful if you want the data included but aren't using a pretrained pipeline; for the affected languages, the relevant data is included in pretrained pipelines directly.
<add>- [coreferee](https://github.com/explosion/coreferee): Coreference resolution for English, French, German and Polish, optimised for limited training data and easily extensible for further languages. Used as a spaCy pipeline component.
<add>- [spacy-stanza](https://github.com/explosion/spacy-stanza): This is a wrapper that allows the use of Stanford's Stanza library in spaCy.
<add>- [spacy-streamlit](https://github.com/explosion/spacy-streamlit): A wrapper for the Streamlit dashboard building library to help with integrating [displaCy](https://spacy.io/api/top-level/#displacy).
<add>- [spacymoji](https://github.com/explosion/spacymoji): A library to add extra support for emoji to spaCy, such as including character names.
<add>- [thinc-apple-ops](https://github.com/explosion/thinc-apple-ops): A special backend for OSX that uses Apple's native libraries for improved performance.
<add>- [os-signpost](https://github.com/explosion/os-signpost): A Python package that allows you to use the `OSSignposter` API in OSX for performance analysis.
<add>- [spacy-ray](https://github.com/explosion/spacy-ray): A wrapper to integrate spaCy with Ray, a distributed training framework. Currently a work in progress.
<add>
<add>## Prodigy
<add>
<add>[Prodigy](https://prodi.gy) is Explosion's easy to use and highly customizable tool for annotating data. Prodigy itself requires a license, but the repos below contain documentation, examples, and editor or notebook integrations.
<add>
<add>- [prodigy-recipes](https://github.com/explosion/prodigy-recipes): Sample recipes for Prodigy, along with notebooks and other examples of usage.
<add>- [vscode-prodigy](https://github.com/explosion/vscode-prodigy): A VS Code extension that lets you run Prodigy inside VS Code.
<add>- [jupyterlab-prodigy](https://github.com/explosion/jupyterlab-prodigy): An extension for JupyterLab that lets you run Prodigy inside JupyterLab.
<add>
<add>## Independent Tools or Projects
<add>
<add>These are tools that may be related to or use spaCy, but are functional independent projects in their own right as well.
<add>
<add>- [floret](https://github.com/explosion/floret): A modification of fastText to use Bloom Embeddings. Can be used to add vectors with subword features to spaCy, and also works independently in the same manner as fastText.
<add>- [sense2vec](https://github.com/explosion/sense2vec): A library to make embeddings of noun phrases or words coupled with their part of speech. This library uses spaCy.
<add>- [spacy-vectors-builder](https://github.com/explosion/spacy-vectors-builder): This is a spaCy project that builds vectors using floret and a lot of input text. It handles downloading the input data as well as the actual building of vectors.
<add>- [holmes-extractor](https://github.com/explosion/holmes-extractor): Information extraction from English and German texts based on predicate logic. Uses spaCy.
<add>- [healthsea](https://github.com/explosion/healthsea): Healthsea is a project to extract information from comments about health supplements. Structurally, it's a self-contained, large spaCy project.
<add>- [spacy-pkuseg](https://github.com/explosion/spacy-pkuseg): A fork of the pkuseg Chinese tokenizer. Used for Chinese support in spaCy, but also works independently.
<add>- [ml-datasets](https://github.com/explosion/ml-datasets): This repo includes loaders for several standard machine learning datasets, like MNIST or WikiNER, and has historically been used in spaCy example code and documentation.
<add>
<add>## Documentation and Informational Repos
<add>
<add>These repos are used to support the spaCy docs or otherwise present information about spaCy or other Explosion projects.
<add>
<add>- [projects](https://github.com/explosion/projects): The projects repo is used to show detailed examples of spaCy usage. Individual projects can be checked out using the spaCy command line tool, rather than checking out the projects repo directly.
<add>- [spacy-course](https://github.com/explosion/spacy-course): Home to the interactive spaCy course for learning about how to use the library and some basic NLP principles.
<add>- [spacy-io-binder](https://github.com/explosion/spacy-io-binder): Home to the notebooks used for interactive examples in the documentation.
<add>
<add>## Organizational / Meta
<add>
<add>These repos are used for organizing data around spaCy, but are not something an end user would need to install as part of using the library.
<add>
<add>- [spacy-models](https://github.com/explosion/spacy-models): This repo contains metadata (but not training data) for all the spaCy models. This includes information about where their training data came from, version compatability, and performance information. It also includes tests for the model packages, and the built models are hosted as releases of this repo.
<add>- [wheelwright](https://github.com/explosion/wheelwright): A tool for automating our PyPI builds and releases.
<add>- [ec2buildwheel](https://github.com/explosion/ec2buildwheel): A small project that allows you to build Python packages in the manner of cibuildwheel, but on any EC2 image. Used by wheelwright.
<add>
<add>## Other
<add>
<add>Repos that don't fit in any of the above categories.
<add>
<add>- [blis](https://github.com/explosion/blis): A fork of the official BLIS library. The main branch is not updated, but work continues in various branches. This is used for cython-blis.
<add>- [tokenizations](https://github.com/explosion/tokenizations): A library originally by Yohei Tamura to align strings with tolerance to some variations in features like case and diacritics, used for aligning tokens and wordpieces. Adopted and maintained by Explosion, but usually spacy-alignments is used instead.
<add>- [conll-2012](https://github.com/explosion/conll-2012): A repo to hold some slightly cleaned up versions of the official scripts for the CoNLL 2012 shared task involving coreference resolution. Used in the coref project.
<add>- [fastapi-explosion-extras](https://github.com/explosion/fastapi-explosion-extras): Some small tweaks to FastAPI used at Explosion.
<add> | 1 |
Text | Text | use sentence case in readme headers | 044110e6a94ad280ca64e82476996f6ef2b190d2 | <ide><path>README.md
<ide> The Node.js project uses an [open governance model](./GOVERNANCE.md). The
<ide>
<ide> **This project is bound by a [Code of Conduct][].**
<ide>
<del># Table of Contents
<add># Table of contents
<ide>
<ide> * [Support](#support)
<ide> * [Release Types](#release-types)
<ide> The Node.js project uses an [open governance model](./GOVERNANCE.md). The
<ide> Looking for help? Check out the
<ide> [instructions for getting support](.github/SUPPORT.md).
<ide>
<del>## Release Types
<add>## Release types
<ide>
<ide> * **Current**: Under active development. Code for the Current release is in the
<ide> branch for its major version number (for example,
<ide> For more information, see the
<ide> Binaries, installers, and source tarballs are available at
<ide> <https://nodejs.org/en/download/>.
<ide>
<del>#### Current and LTS Releases
<add>#### Current and LTS releases
<ide> <https://nodejs.org/download/release/>
<ide>
<ide> The [latest](https://nodejs.org/download/release/latest/) directory is an
<ide> alias for the latest release from an LTS line. For example, the
<ide> [latest-carbon](https://nodejs.org/download/release/latest-carbon/) directory
<ide> contains the latest Carbon (Node.js 8) release.
<ide>
<del>#### Nightly Releases
<add>#### Nightly releases
<ide> <https://nodejs.org/download/nightly/>
<ide>
<ide> Each directory name and filename contains a date (in UTC) and the commit
<ide> SHA at the HEAD of the release.
<ide>
<del>#### API Documentation
<add>#### API documentation
<ide>
<ide> Documentation for the latest Current release is at <https://nodejs.org/api/>.
<ide> Version-specific documentation is available in each release directory in the
<ide> _docs_ subdirectory. Version-specific documentation is also at
<ide> <https://nodejs.org/download/docs/>.
<ide>
<del>### Verifying Binaries
<add>### Verifying binaries
<ide>
<ide> Download directories contain a `SHASUMS256.txt` file with SHA checksums for the
<ide> files.
<ide> For information on reporting security vulnerabilities in Node.js, see
<ide> * [Strategic Initiatives][]
<ide> * [Technical values and prioritization][]
<ide>
<del>## Current Project Team Members
<add>## Current project team members
<ide>
<ide> For information about the governance of the Node.js project, see
<ide> [GOVERNANCE.md](./GOVERNANCE.md).
<ide> For information about the governance of the Node.js project, see
<ide> * [Trott](https://github.com/Trott) -
<ide> **Rich Trott** <rtrott@gmail.com> (he/him)
<ide>
<del>### TSC Emeriti
<add>### TSC emeriti
<ide>
<ide> * [addaleax](https://github.com/addaleax) -
<ide> **Anna Henningsen** <anna@addaleax.net> (she/her)
<ide> For information about the governance of the Node.js project, see
<ide> * [ZYSzys](https://github.com/ZYSzys) -
<ide> **Yongsheng Zhang** <zyszys98@gmail.com> (he/him)
<ide>
<del>### Collaborator Emeriti
<add>### Collaborator emeriti
<ide>
<ide> * [andrasq](https://github.com/andrasq) -
<ide> **Andras** <andras@kinvey.com>
<ide> maintaining the Node.js project.
<ide> * [RaisinTen](https://github.com/RaisinTen) -
<ide> **Darshan Sen** <raisinten@gmail.com>
<ide>
<del>### Release Keys
<add>### Release keys
<ide>
<ide> Primary GPG keys for Node.js Releasers (some Releasers sign with subkeys):
<ide> | 1 |
Go | Go | generate imports based on what is avaliable | 3061a6a2ab0395c626f9acaa2e5d9c17152b0475 | <ide><path>pkg/apparmor/gen.go
<add>package apparmor
<add>
<add>import (
<add> "io"
<add> "os"
<add> "text/template"
<add>)
<add>
<add>type data struct {
<add> Name string
<add> Imports []string
<add> InnerImports []string
<add>}
<add>
<add>const baseTemplate = `
<add>{{range $value := .Imports}}
<add>{{$value}}
<add>{{end}}
<add>
<add>profile {{.Name}} flags=(attach_disconnected,mediate_deleted) {
<add>{{range $value := .InnerImports}}
<add> {{$value}}
<add>{{end}}
<add>
<add> network,
<add> capability,
<add> file,
<add> umount,
<add>
<add> mount fstype=tmpfs,
<add> mount fstype=mqueue,
<add> mount fstype=fuse.*,
<add> mount fstype=binfmt_misc -> /proc/sys/fs/binfmt_misc/,
<add> mount fstype=efivarfs -> /sys/firmware/efi/efivars/,
<add> mount fstype=fusectl -> /sys/fs/fuse/connections/,
<add> mount fstype=securityfs -> /sys/kernel/security/,
<add> mount fstype=debugfs -> /sys/kernel/debug/,
<add> mount fstype=proc -> /proc/,
<add> mount fstype=sysfs -> /sys/,
<add>
<add> deny @{PROC}/sys/fs/** wklx,
<add> deny @{PROC}/sysrq-trigger rwklx,
<add> deny @{PROC}/mem rwklx,
<add> deny @{PROC}/kmem rwklx,
<add> deny @{PROC}/sys/kernel/[^s][^h][^m]* wklx,
<add> deny @{PROC}/sys/kernel/*/** wklx,
<add>
<add> deny mount options=(ro, remount) -> /,
<add> deny mount fstype=debugfs -> /var/lib/ureadahead/debugfs/,
<add> deny mount fstype=devpts,
<add>
<add> deny /sys/[^f]*/** wklx,
<add> deny /sys/f[^s]*/** wklx,
<add> deny /sys/fs/[^c]*/** wklx,
<add> deny /sys/fs/c[^g]*/** wklx,
<add> deny /sys/fs/cg[^r]*/** wklx,
<add> deny /sys/firmware/efi/efivars/** rwklx,
<add> deny /sys/kernel/security/** rwklx,
<add>}
<add>`
<add>
<add>func generateProfile(out io.Writer) error {
<add> compiled, err := template.New("apparmor_profile").Parse(baseTemplate)
<add> if err != nil {
<add> return err
<add> }
<add> data := &data{
<add> Name: "docker-default",
<add> }
<add> if tuntablesExists() {
<add> data.Imports = append(data.Imports, "#include <tunables/global>")
<add> }
<add> if abstrctionsEsists() {
<add> data.InnerImports = append(data.InnerImports, "#include <abstractions/base>")
<add> }
<add> if err := compiled.Execute(out, data); err != nil {
<add> return err
<add> }
<add> return nil
<add>}
<add>
<add>// check if the tunables/global exist
<add>func tuntablesExists() bool {
<add> _, err := os.Stat("/etc/apparmor.d/tunables/global")
<add> return err == nil
<add>}
<add>
<add>// check if abstractions/base exist
<add>func abstrctionsEsists() bool {
<add> _, err := os.Stat("/etc/apparmor.d/abstractions/base")
<add> return err == nil
<add>}
<ide><path>pkg/apparmor/setup.go
<ide> package apparmor
<ide> import (
<ide> "fmt"
<ide> "io"
<del> "io/ioutil"
<ide> "os"
<ide> "os/exec"
<ide> "path"
<ide> const (
<ide> DefaultProfilePath = "/etc/apparmor.d/docker"
<ide> )
<ide>
<del>const DefaultProfile = `
<del>#include <tunables/global>
<del>profile docker-default flags=(attach_disconnected,mediate_deleted) {
<del> #include <abstractions/base>
<del> network,
<del> capability,
<del> file,
<del> umount,
<del>
<del> mount fstype=tmpfs,
<del> mount fstype=mqueue,
<del> mount fstype=fuse.*,
<del> mount fstype=binfmt_misc -> /proc/sys/fs/binfmt_misc/,
<del> mount fstype=efivarfs -> /sys/firmware/efi/efivars/,
<del> mount fstype=fusectl -> /sys/fs/fuse/connections/,
<del> mount fstype=securityfs -> /sys/kernel/security/,
<del> mount fstype=debugfs -> /sys/kernel/debug/,
<del> mount fstype=proc -> /proc/,
<del> mount fstype=sysfs -> /sys/,
<del>
<del> deny @{PROC}/sys/fs/** wklx,
<del> deny @{PROC}/sysrq-trigger rwklx,
<del> deny @{PROC}/mem rwklx,
<del> deny @{PROC}/kmem rwklx,
<del> deny @{PROC}/sys/kernel/[^s][^h][^m]* wklx,
<del> deny @{PROC}/sys/kernel/*/** wklx,
<del>
<del> deny mount options=(ro, remount) -> /,
<del> deny mount fstype=debugfs -> /var/lib/ureadahead/debugfs/,
<del> deny mount fstype=devpts,
<del>
<del> deny /sys/[^f]*/** wklx,
<del> deny /sys/f[^s]*/** wklx,
<del> deny /sys/fs/[^c]*/** wklx,
<del> deny /sys/fs/c[^g]*/** wklx,
<del> deny /sys/fs/cg[^r]*/** wklx,
<del> deny /sys/firmware/efi/efivars/** rwklx,
<del> deny /sys/kernel/security/** rwklx,
<del>}
<del>`
<del>
<ide> func InstallDefaultProfile(backupPath string) error {
<ide> if !IsEnabled() {
<ide> return nil
<ide> func InstallDefaultProfile(backupPath string) error {
<ide> return err
<ide> }
<ide>
<del> if err := ioutil.WriteFile(DefaultProfilePath, []byte(DefaultProfile), 0644); err != nil {
<add> f, err := os.OpenFile(DefaultProfilePath, os.O_WRONLY|os.O_CREATE|os.O_TRUNC, 0644)
<add> if err != nil {
<add> return err
<add> }
<add> if err := generateProfile(f); err != nil {
<add> f.Close()
<ide> return err
<ide> }
<add> f.Close()
<add>
<add> cmd := exec.Command("/sbin/apparmor_parser", "-r", "-W", "docker")
<add> // to use the parser directly we have to make sure we are in the correct
<add> // dir with the profile
<add> cmd.Dir = "/etc/apparmor.d"
<ide>
<del> output, err := exec.Command("/sbin/apparmor_parser", "-r", "-W", "docker").CombinedOutput()
<add> output, err := cmd.CombinedOutput()
<ide> if err != nil && !os.IsNotExist(err) {
<ide> if e, ok := err.(*exec.Error); ok {
<del> // keeping with the current profile load code, if the parser does not exist then
<del> // just return
<add> // keeping with the current profile load code, if the parser does not
<add> // exist then just return
<ide> if e.Err == exec.ErrNotFound || os.IsNotExist(e.Err) {
<ide> return nil
<ide> } | 2 |
Javascript | Javascript | add target to getclearcolor | 380067c434f2afcbce6a2f33e72b711039d2b955 | <ide><path>src/renderers/WebGLRenderer.js
<ide> function WebGLRenderer( parameters ) {
<ide>
<ide> // Clearing
<ide>
<del> this.getClearColor = function () {
<add> this.getClearColor = function ( target ) {
<ide>
<del> return background.getClearColor();
<add> if ( target === undefined ) {
<add>
<add> console.warn( 'WebGLRenderer: .getClearColor() now requires a Color as an argument' );
<add>
<add> target = new Color();
<add>
<add> }
<add>
<add> return target.copy( background.getClearColor() );
<ide>
<ide> };
<ide> | 1 |
Mixed | Text | add new error to api docs | b0089e48272f18d856ba147b393371c18d5683fb | <ide><path>api/server/router/network/network_routes.go
<ide> func (n *networkRouter) postNetworkConnect(ctx context.Context, w http.ResponseW
<ide> }
<ide>
<ide> if nw.Info().Dynamic() {
<del> return newNetworkForbiddenError("Operation not supported for swarm scoped networks")
<add> return newNetworkForbiddenError("operation not supported for swarm scoped networks")
<ide> }
<ide>
<ide> return n.backend.ConnectContainerToNetwork(connect.Container, nw.Name(), connect.EndpointConfig)
<ide> func (n *networkRouter) postNetworkDisconnect(ctx context.Context, w http.Respon
<ide> }
<ide>
<ide> if nw.Info().Dynamic() {
<del> return newNetworkForbiddenError("Operation not supported for swarm scoped networks")
<add> return newNetworkForbiddenError("operation not supported for swarm scoped networks")
<ide> }
<ide>
<ide> return n.backend.DisconnectContainerFromNetwork(disconnect.Container, nw, disconnect.Force)
<ide><path>docs/reference/api/docker_remote_api_v1.24.md
<ide> Content-Type: application/json
<ide> **Status codes**:
<ide>
<ide> - **200** - no error
<add>- **403** - operation not supported for swarm scoped networks
<ide> - **404** - network or container is not found
<ide> - **500** - Internal Server Error
<ide>
<ide> Content-Type: application/json
<ide> **Status codes**:
<ide>
<ide> - **200** - no error
<add>- **403** - operation not supported for swarm scoped networks
<ide> - **404** - network or container not found
<ide> - **500** - Internal Server Error
<ide>
<ide><path>docs/reference/api/docker_remote_api_v1.25.md
<ide> Content-Type: application/json
<ide> **Status codes**:
<ide>
<ide> - **200** - no error
<add>- **403** - operation not supported for swarm scoped networks
<ide> - **404** - network or container is not found
<ide> - **500** - Internal Server Error
<ide>
<ide> Content-Type: application/json
<ide> **Status codes**:
<ide>
<ide> - **200** - no error
<add>- **403** - operation not supported for swarm scoped networks
<ide> - **404** - network or container not found
<ide> - **500** - Internal Server Error
<ide> | 3 |
Go | Go | pass info rather than hash to deletedevice | 8e39b35c7cd02bbb644b7faf2a434de0098e6dea | <ide><path>runtime/graphdriver/devmapper/deviceset.go
<ide> func (devices *DeviceSet) setupBaseImage() error {
<ide>
<ide> if oldInfo != nil && !oldInfo.Initialized {
<ide> utils.Debugf("Removing uninitialized base image")
<del> if err := devices.deleteDevice(""); err != nil {
<add> if err := devices.deleteDevice(oldInfo); err != nil {
<ide> utils.Debugf("\n--->Err: %s\n", err)
<ide> return err
<ide> }
<ide> func (devices *DeviceSet) AddDevice(hash, baseHash string) error {
<ide> return nil
<ide> }
<ide>
<del>func (devices *DeviceSet) deleteDevice(hash string) error {
<del> info := devices.Devices[hash]
<del> if info == nil {
<del> return fmt.Errorf("hash %s doesn't exists", hash)
<del> }
<del>
<add>func (devices *DeviceSet) deleteDevice(info *DevInfo) error {
<ide> // This is a workaround for the kernel not discarding block so
<ide> // on the thin pool when we remove a thinp device, so we do it
<ide> // manually
<ide> func (devices *DeviceSet) DeleteDevice(hash string) error {
<ide> info.lock.Lock()
<ide> defer info.lock.Unlock()
<ide>
<del> return devices.deleteDevice(hash)
<add> return devices.deleteDevice(info)
<ide> }
<ide>
<ide> func (devices *DeviceSet) deactivatePool() error { | 1 |
Javascript | Javascript | keep option object as it is | cc5997a2b1cb8a2b66a9b2b7a12e391ad2bb0a6f | <ide><path>packager/src/node-haste/DependencyGraph/ResolutionRequest.js
<ide> function tryResolveSync<T>(action: () => T, secondaryAction: () => T): T {
<ide> }
<ide>
<ide> class ResolutionRequest<TModule: Moduleish, TPackage: Packageish> {
<del> _dirExists: DirExistsFn;
<del> _entryPath: string;
<del> _extraNodeModules: ?Object;
<del> _hasteFS: HasteFS;
<del> _helpers: DependencyGraphHelpers;
<add>
<ide> _immediateResolutionCache: {[key: string]: TModule};
<del> _matchFiles: MatchFilesByDirAndPattern;
<del> _moduleCache: ModuleishCache<TModule, TPackage>;
<del> _moduleMap: ModuleMap;
<del> _platform: ?string;
<del> _platforms: Set<string>;
<del> _preferNativePlatform: boolean;
<add> _options: Options<TModule, TPackage>;
<ide> static emptyModule: string;
<ide>
<del> constructor({
<del> dirExists,
<del> entryPath,
<del> extraNodeModules,
<del> hasteFS,
<del> helpers,
<del> matchFiles,
<del> moduleCache,
<del> moduleMap,
<del> platform,
<del> platforms,
<del> preferNativePlatform,
<del> }: Options<TModule, TPackage>) {
<del> this._dirExists = dirExists;
<del> this._entryPath = entryPath;
<del> this._extraNodeModules = extraNodeModules;
<del> this._hasteFS = hasteFS;
<del> this._helpers = helpers;
<del> this._matchFiles = matchFiles;
<del> this._moduleCache = moduleCache;
<del> this._moduleMap = moduleMap;
<del> this._platform = platform;
<del> this._platforms = platforms;
<del> this._preferNativePlatform = preferNativePlatform;
<add> constructor(options: Options<TModule, TPackage>) {
<add> this._options = options;
<ide> this._resetResolutionCache();
<ide> }
<ide>
<ide> class ResolutionRequest<TModule: Moduleish, TPackage: Packageish> {
<ide> return result;
<ide> };
<ide>
<del> if (!this._helpers.isNodeModulesDir(fromModule.path)
<add> if (!this._options.helpers.isNodeModulesDir(fromModule.path)
<ide> && !(isRelativeImport(toModuleName) || isAbsolutePath(toModuleName))) {
<ide> const result = tryResolveSync(
<ide> () => this._resolveHasteDependency(fromModule, toModuleName),
<ide> class ResolutionRequest<TModule: Moduleish, TPackage: Packageish> {
<ide> onProgress?: ?(finishedModules: number, totalModules: number) => mixed,
<ide> recursive: boolean,
<ide> }) {
<del> const entry = this._moduleCache.getModule(this._entryPath);
<add> const entry = this._options.moduleCache.getModule(this._options.entryPath);
<ide>
<ide> response.pushDependency(entry);
<ide> let totalModules = 1;
<ide> class ResolutionRequest<TModule: Moduleish, TPackage: Packageish> {
<ide> realModuleName = toModuleName;
<ide> }
<ide>
<del> const modulePath = this._moduleMap
<del> .getModule(realModuleName, this._platform, /* supportsNativePlatform */ true);
<add> const modulePath = this._options.moduleMap
<add> .getModule(realModuleName, this._options.platform, /* supportsNativePlatform */ true);
<ide> if (modulePath != null) {
<del> const module = this._moduleCache.getModule(modulePath);
<add> const module = this._options.moduleCache.getModule(modulePath);
<ide> /* temporary until we strengthen the typing */
<ide> invariant(module.type === 'Module', 'expected Module type');
<ide> return module;
<ide> class ResolutionRequest<TModule: Moduleish, TPackage: Packageish> {
<ide> let packageName = realModuleName;
<ide> let packagePath;
<ide> while (packageName && packageName !== '.') {
<del> packagePath = this._moduleMap
<del> .getPackage(packageName, this._platform, /* supportsNativePlatform */ true);
<add> packagePath = this._options.moduleMap
<add> .getPackage(packageName, this._options.platform, /* supportsNativePlatform */ true);
<ide> if (packagePath != null) {
<ide> break;
<ide> }
<ide> class ResolutionRequest<TModule: Moduleish, TPackage: Packageish> {
<ide>
<ide> if (packagePath != null) {
<ide>
<del> const package_ = this._moduleCache.getPackage(packagePath);
<add> const package_ = this._options.moduleCache.getPackage(packagePath);
<ide> /* temporary until we strengthen the typing */
<ide> invariant(package_.type === 'Package', 'expected Package type');
<ide>
<ide> class ResolutionRequest<TModule: Moduleish, TPackage: Packageish> {
<ide> currDir !== '.' && currDir !== realPath.parse(fromModule.path).root;
<ide> currDir = path.dirname(currDir)) {
<ide> const searchPath = path.join(currDir, 'node_modules');
<del> if (this._dirExists(searchPath)) {
<add> if (this._options.dirExists(searchPath)) {
<ide> searchQueue.push(
<ide> path.join(searchPath, realModuleName)
<ide> );
<ide> }
<ide> }
<ide>
<del> if (this._extraNodeModules) {
<del> const {_extraNodeModules} = this;
<add> if (this._options.extraNodeModules) {
<add> const {extraNodeModules} = this._options;
<ide> const bits = toModuleName.split(path.sep);
<ide> const packageName = bits[0];
<del> if (_extraNodeModules[packageName]) {
<del> bits[0] = _extraNodeModules[packageName];
<add> if (extraNodeModules[packageName]) {
<add> bits[0] = extraNodeModules[packageName];
<ide> searchQueue.push(path.join.apply(path, bits));
<ide> }
<ide> }
<ide> class ResolutionRequest<TModule: Moduleish, TPackage: Packageish> {
<ide> }
<ide>
<ide> _loadAsFile(potentialModulePath: string, fromModule: TModule, toModule: string): TModule {
<del> if (this._helpers.isAssetFile(potentialModulePath)) {
<add> if (this._options.helpers.isAssetFile(potentialModulePath)) {
<ide> const dirname = path.dirname(potentialModulePath);
<del> if (!this._dirExists(dirname)) {
<add> if (!this._options.dirExists(dirname)) {
<ide> throw new UnableToResolveError(
<ide> fromModule,
<ide> toModule,
<ide> `Directory ${dirname} doesn't exist`,
<ide> );
<ide> }
<ide>
<del> const {name, type} = getAssetDataFromName(potentialModulePath, this._platforms);
<add> const {name, type} = getAssetDataFromName(potentialModulePath, this._options.platforms);
<ide>
<ide> let pattern = '^' + name + '(@[\\d\\.]+x)?';
<del> if (this._platform != null) {
<del> pattern += '(\\.' + this._platform + ')?';
<add> if (this._options.platform != null) {
<add> pattern += '(\\.' + this._options.platform + ')?';
<ide> }
<ide> pattern += '\\.' + type + '$';
<ide>
<del> const assetFiles = this._matchFiles(dirname, new RegExp(pattern));
<add> const assetFiles = this._options.matchFiles(dirname, new RegExp(pattern));
<ide> // We arbitrarly grab the lowest, because scale selection will happen
<ide> // somewhere else. Always the lowest so that it's stable between builds.
<ide> const assetFile = getArrayLowestItem(assetFiles);
<ide> if (assetFile) {
<del> return this._moduleCache.getAssetModule(assetFile);
<add> return this._options.moduleCache.getAssetModule(assetFile);
<ide> }
<ide> }
<ide>
<ide> let file;
<del> if (this._hasteFS.exists(potentialModulePath)) {
<add> if (this._options.hasteFS.exists(potentialModulePath)) {
<ide> file = potentialModulePath;
<del> } else if (this._platform != null &&
<del> this._hasteFS.exists(potentialModulePath + '.' + this._platform + '.js')) {
<del> file = potentialModulePath + '.' + this._platform + '.js';
<add> } else if (this._options.platform != null &&
<add> this._options.hasteFS.exists(potentialModulePath + '.' + this._options.platform + '.js')) {
<add> file = potentialModulePath + '.' + this._options.platform + '.js';
<ide> } else if (this._preferNativePlatform &&
<del> this._hasteFS.exists(potentialModulePath + '.native.js')) {
<add> this._options.hasteFS.exists(potentialModulePath + '.native.js')) {
<ide> file = potentialModulePath + '.native.js';
<del> } else if (this._hasteFS.exists(potentialModulePath + '.js')) {
<add> } else if (this._options.hasteFS.exists(potentialModulePath + '.js')) {
<ide> file = potentialModulePath + '.js';
<del> } else if (this._hasteFS.exists(potentialModulePath + '.json')) {
<add> } else if (this._options.hasteFS.exists(potentialModulePath + '.json')) {
<ide> file = potentialModulePath + '.json';
<ide> } else {
<ide> throw new UnableToResolveError(
<ide> class ResolutionRequest<TModule: Moduleish, TPackage: Packageish> {
<ide> );
<ide> }
<ide>
<del> return this._moduleCache.getModule(file);
<add> return this._options.moduleCache.getModule(file);
<ide> }
<ide>
<ide> _loadAsDir(potentialDirPath: string, fromModule: TModule, toModule: string): TModule {
<del> if (!this._dirExists(potentialDirPath)) {
<add> if (!this._options.dirExists(potentialDirPath)) {
<ide> throw new UnableToResolveError(
<ide> fromModule,
<ide> toModule,
<ide> class ResolutionRequest<TModule: Moduleish, TPackage: Packageish> {
<ide> }
<ide>
<ide> const packageJsonPath = path.join(potentialDirPath, 'package.json');
<del> if (this._hasteFS.exists(packageJsonPath)) {
<del> const main = this._moduleCache.getPackage(packageJsonPath).getMain();
<add> if (this._options.hasteFS.exists(packageJsonPath)) {
<add> const main = this._options.moduleCache.getPackage(packageJsonPath).getMain();
<ide> return tryResolveSync(
<ide> () => this._loadAsFile(main, fromModule, toModule),
<ide> () => this._loadAsDir(main, fromModule, toModule), | 1 |
Ruby | Ruby | add (more) documentation to to_time | 881def43e326c36a7870bcc3ba56dc4a006b9a38 | <ide><path>activesupport/lib/active_support/core_ext/date/conversions.rb
<ide> def readable_inspect
<ide> # date.to_time(:local) # => 2007-11-10 00:00:00 0800
<ide> #
<ide> # date.to_time(:utc) # => 2007-11-10 00:00:00 UTC
<add> #
<add> # NOTE: The :local timezone is Ruby's *process* timezone, i.e. ENV['TZ']
<add> # If the *application's* timezone is needed, then use +in_time_zone+ instead
<ide> def to_time(form = :local)
<ide> raise ArgumentError, "Expected :local or :utc, got #{form.inspect}." unless [:local, :utc].include?(form)
<ide> ::Time.send(form, year, month, day) | 1 |
Javascript | Javascript | allow empty parameters | 72d0f8821530bc77a369914c285a45991b2bf465 | <ide><path>benchmark/common.js
<ide> function parseOpts(options) {
<ide> var num = keys.length;
<ide> var conf = {};
<ide> for (var i = 2; i < process.argv.length; i++) {
<del> var match = process.argv[i].match(/^(.+)=(.+)$/);
<del> if (!match || !match[1] || !match[2] || !options[match[1]]) {
<add> var match = process.argv[i].match(/^(.+)=(.*)$/);
<add> if (!match || !match[1] || !options[match[1]]) {
<ide> return null;
<ide> } else {
<del> conf[match[1]] = isFinite(match[2]) ? +match[2] : match[2]
<add> conf[match[1]] = (match[2].length && isFinite(match[2])
<add> ? +match[2]
<add> : match[2]);
<ide> num--;
<ide> }
<ide> } | 1 |
Go | Go | remove last trace of daemon->server dependency | 20b0841c1bd07c6add812597e0d656d7584e48ac | <ide><path>daemon/container.go
<ide> func (container *Container) monitor(callback execdriver.StartCallback) error {
<ide> if container.Config.OpenStdin {
<ide> container.stdin, container.stdinPipe = io.Pipe()
<ide> }
<del> if container.daemon != nil && container.daemon.srv != nil {
<del> container.LogEvent("die")
<del> }
<add> container.LogEvent("die")
<ide> // If the engine is shutting down, don't save the container state as stopped.
<ide> // This will cause it to be restarted when the engine is restarted.
<ide> if container.daemon != nil && container.daemon.eng != nil && !container.daemon.eng.IsShutdown() {
<ide><path>daemon/daemon.go
<ide> type Daemon struct {
<ide> idIndex *truncindex.TruncIndex
<ide> sysInfo *sysinfo.SysInfo
<ide> volumes *graph.Graph
<del> srv Server
<ide> eng *engine.Engine
<ide> config *daemonconfig.Config
<ide> containerGraph *graphdb.Database
<ide> func (daemon *Daemon) ContainerGraph() *graphdb.Database {
<ide> return daemon.containerGraph
<ide> }
<ide>
<del>func (daemon *Daemon) SetServer(server Server) {
<del> daemon.srv = server
<del>}
<del>
<ide> func (daemon *Daemon) checkLocaldns() error {
<ide> resolvConf, err := resolvconf.Get()
<ide> if err != nil {
<ide><path>daemon/server.go
<del>package daemon
<del>
<del>// FIXME: this shim interface is no longer needed, it can be removed
<del>type Server interface {
<del>}
<ide><path>server/init.go
<ide> func NewServer(eng *engine.Engine, config *daemonconfig.Config) (*Server, error)
<ide> pullingPool: make(map[string]chan struct{}),
<ide> pushingPool: make(map[string]chan struct{}),
<ide> }
<del> daemon.SetServer(srv)
<ide> return srv, nil
<ide> } | 4 |
Javascript | Javascript | remove dependency on internal data structure | 86fad4b2f38001374a77abdf12cb9a1ae23e572c | <ide><path>Libraries/Inspector/Inspector.js
<ide> class Inspector extends React.Component {
<ide> // instance that contains it (like View)
<ide> const {
<ide> hierarchy,
<del> instance,
<ide> props,
<ide> selection,
<ide> source,
<ide> } = renderer.getInspectorDataForViewTag(touchedViewTag);
<ide>
<ide> if (this.state.devtoolsAgent) {
<del> this.state.devtoolsAgent.selectFromReactInstance(instance, true);
<add> // Skip host leafs
<add> const offsetFromLeaf = hierarchy.length - 1 - selection;
<add> this.state.devtoolsAgent.selectFromDOMNode(touchedViewTag, true, offsetFromLeaf);
<ide> }
<ide>
<ide> this.setState({ | 1 |
Go | Go | add version pkg | 8dad771daa6572ca15949d3e53e825f4837c0af9 | <ide><path>api/server.go
<ide> import (
<ide> "github.com/dotcloud/docker/pkg/listenbuffer"
<ide> "github.com/dotcloud/docker/pkg/systemd"
<ide> "github.com/dotcloud/docker/pkg/user"
<add> "github.com/dotcloud/docker/pkg/version"
<ide> "github.com/dotcloud/docker/utils"
<ide> "github.com/gorilla/mux"
<ide> "io"
<ide> var (
<ide> activationLock chan struct{}
<ide> )
<ide>
<del>type HttpApiFunc func(eng *engine.Engine, version string, w http.ResponseWriter, r *http.Request, vars map[string]string) error
<add>type HttpApiFunc func(eng *engine.Engine, version version.Version, w http.ResponseWriter, r *http.Request, vars map[string]string) error
<ide>
<ide> func hijackServer(w http.ResponseWriter) (io.ReadCloser, io.Writer, error) {
<ide> conn, _, err := w.(http.Hijacker).Hijack()
<ide> func getBoolParam(value string) (bool, error) {
<ide> return ret, nil
<ide> }
<ide>
<del>func postAuth(eng *engine.Engine, version string, w http.ResponseWriter, r *http.Request, vars map[string]string) error {
<add>func postAuth(eng *engine.Engine, version version.Version, w http.ResponseWriter, r *http.Request, vars map[string]string) error {
<ide> var (
<ide> authConfig, err = ioutil.ReadAll(r.Body)
<ide> job = eng.Job("auth")
<ide> func postAuth(eng *engine.Engine, version string, w http.ResponseWriter, r *http
<ide> return nil
<ide> }
<ide>
<del>func getVersion(eng *engine.Engine, version string, w http.ResponseWriter, r *http.Request, vars map[string]string) error {
<add>func getVersion(eng *engine.Engine, version version.Version, w http.ResponseWriter, r *http.Request, vars map[string]string) error {
<ide> w.Header().Set("Content-Type", "application/json")
<ide> eng.ServeHTTP(w, r)
<ide> return nil
<ide> }
<ide>
<del>func postContainersKill(eng *engine.Engine, version string, w http.ResponseWriter, r *http.Request, vars map[string]string) error {
<add>func postContainersKill(eng *engine.Engine, version version.Version, w http.ResponseWriter, r *http.Request, vars map[string]string) error {
<ide> if vars == nil {
<ide> return fmt.Errorf("Missing parameter")
<ide> }
<ide> func postContainersKill(eng *engine.Engine, version string, w http.ResponseWrite
<ide> return nil
<ide> }
<ide>
<del>func getContainersExport(eng *engine.Engine, version string, w http.ResponseWriter, r *http.Request, vars map[string]string) error {
<add>func getContainersExport(eng *engine.Engine, version version.Version, w http.ResponseWriter, r *http.Request, vars map[string]string) error {
<ide> if vars == nil {
<ide> return fmt.Errorf("Missing parameter")
<ide> }
<ide> func getContainersExport(eng *engine.Engine, version string, w http.ResponseWrit
<ide> return nil
<ide> }
<ide>
<del>func getImagesJSON(eng *engine.Engine, version string, w http.ResponseWriter, r *http.Request, vars map[string]string) error {
<add>func getImagesJSON(eng *engine.Engine, version version.Version, w http.ResponseWriter, r *http.Request, vars map[string]string) error {
<ide> if err := parseForm(r); err != nil {
<ide> return err
<ide> }
<ide> func getImagesJSON(eng *engine.Engine, version string, w http.ResponseWriter, r
<ide> job.Setenv("filter", r.Form.Get("filter"))
<ide> job.Setenv("all", r.Form.Get("all"))
<ide>
<del> if utils.CompareVersion(version, "1.7") >= 0 {
<add> if version.GreaterThanOrEqualTo("1.7") {
<ide> streamJSON(job, w, false)
<ide> } else if outs, err = job.Stdout.AddListTable(); err != nil {
<ide> return err
<ide> func getImagesJSON(eng *engine.Engine, version string, w http.ResponseWriter, r
<ide> return err
<ide> }
<ide>
<del> if utils.CompareVersion(version, "1.7") < 0 && outs != nil { // Convert to legacy format
<add> if version.LessThan("1.7") && outs != nil { // Convert to legacy format
<ide> outsLegacy := engine.NewTable("Created", 0)
<ide> for _, out := range outs.Data {
<ide> for _, repoTag := range out.GetList("RepoTags") {
<ide> func getImagesJSON(eng *engine.Engine, version string, w http.ResponseWriter, r
<ide> return nil
<ide> }
<ide>
<del>func getImagesViz(eng *engine.Engine, version string, w http.ResponseWriter, r *http.Request, vars map[string]string) error {
<del> if utils.CompareVersion(version, "1.6") > 0 {
<add>func getImagesViz(eng *engine.Engine, version version.Version, w http.ResponseWriter, r *http.Request, vars map[string]string) error {
<add> if version.GreaterThan("1.6") {
<ide> w.WriteHeader(http.StatusNotFound)
<ide> return fmt.Errorf("This is now implemented in the client.")
<ide> }
<ide> eng.ServeHTTP(w, r)
<ide> return nil
<ide> }
<ide>
<del>func getInfo(eng *engine.Engine, version string, w http.ResponseWriter, r *http.Request, vars map[string]string) error {
<add>func getInfo(eng *engine.Engine, version version.Version, w http.ResponseWriter, r *http.Request, vars map[string]string) error {
<ide> w.Header().Set("Content-Type", "application/json")
<ide> eng.ServeHTTP(w, r)
<ide> return nil
<ide> }
<ide>
<del>func getEvents(eng *engine.Engine, version string, w http.ResponseWriter, r *http.Request, vars map[string]string) error {
<add>func getEvents(eng *engine.Engine, version version.Version, w http.ResponseWriter, r *http.Request, vars map[string]string) error {
<ide> if err := parseForm(r); err != nil {
<ide> return err
<ide> }
<ide> func getEvents(eng *engine.Engine, version string, w http.ResponseWriter, r *htt
<ide> return job.Run()
<ide> }
<ide>
<del>func getImagesHistory(eng *engine.Engine, version string, w http.ResponseWriter, r *http.Request, vars map[string]string) error {
<add>func getImagesHistory(eng *engine.Engine, version version.Version, w http.ResponseWriter, r *http.Request, vars map[string]string) error {
<ide> if vars == nil {
<ide> return fmt.Errorf("Missing parameter")
<ide> }
<ide> func getImagesHistory(eng *engine.Engine, version string, w http.ResponseWriter,
<ide> return nil
<ide> }
<ide>
<del>func getContainersChanges(eng *engine.Engine, version string, w http.ResponseWriter, r *http.Request, vars map[string]string) error {
<add>func getContainersChanges(eng *engine.Engine, version version.Version, w http.ResponseWriter, r *http.Request, vars map[string]string) error {
<ide> if vars == nil {
<ide> return fmt.Errorf("Missing parameter")
<ide> }
<ide> func getContainersChanges(eng *engine.Engine, version string, w http.ResponseWri
<ide> return job.Run()
<ide> }
<ide>
<del>func getContainersTop(eng *engine.Engine, version string, w http.ResponseWriter, r *http.Request, vars map[string]string) error {
<del> if utils.CompareVersion(version, "1.4") < 0 {
<add>func getContainersTop(eng *engine.Engine, version version.Version, w http.ResponseWriter, r *http.Request, vars map[string]string) error {
<add> if version.LessThan("1.4") {
<ide> return fmt.Errorf("top was improved a lot since 1.3, Please upgrade your docker client.")
<ide> }
<ide> if vars == nil {
<ide> func getContainersTop(eng *engine.Engine, version string, w http.ResponseWriter,
<ide> return job.Run()
<ide> }
<ide>
<del>func getContainersJSON(eng *engine.Engine, version string, w http.ResponseWriter, r *http.Request, vars map[string]string) error {
<add>func getContainersJSON(eng *engine.Engine, version version.Version, w http.ResponseWriter, r *http.Request, vars map[string]string) error {
<ide> if err := parseForm(r); err != nil {
<ide> return err
<ide> }
<ide> func getContainersJSON(eng *engine.Engine, version string, w http.ResponseWriter
<ide> job.Setenv("before", r.Form.Get("before"))
<ide> job.Setenv("limit", r.Form.Get("limit"))
<ide>
<del> if utils.CompareVersion(version, "1.5") >= 0 {
<add> if version.GreaterThanOrEqualTo("1.5") {
<ide> streamJSON(job, w, false)
<ide> } else if outs, err = job.Stdout.AddTable(); err != nil {
<ide> return err
<ide> }
<ide> if err = job.Run(); err != nil {
<ide> return err
<ide> }
<del> if utils.CompareVersion(version, "1.5") < 0 { // Convert to legacy format
<add> if version.LessThan("1.5") { // Convert to legacy format
<ide> for _, out := range outs.Data {
<ide> ports := engine.NewTable("", 0)
<ide> ports.ReadListFrom([]byte(out.Get("Ports")))
<ide> func getContainersJSON(eng *engine.Engine, version string, w http.ResponseWriter
<ide> return nil
<ide> }
<ide>
<del>func postImagesTag(eng *engine.Engine, version string, w http.ResponseWriter, r *http.Request, vars map[string]string) error {
<add>func postImagesTag(eng *engine.Engine, version version.Version, w http.ResponseWriter, r *http.Request, vars map[string]string) error {
<ide> if err := parseForm(r); err != nil {
<ide> return err
<ide> }
<ide> func postImagesTag(eng *engine.Engine, version string, w http.ResponseWriter, r
<ide> return nil
<ide> }
<ide>
<del>func postCommit(eng *engine.Engine, version string, w http.ResponseWriter, r *http.Request, vars map[string]string) error {
<add>func postCommit(eng *engine.Engine, version version.Version, w http.ResponseWriter, r *http.Request, vars map[string]string) error {
<ide> if err := parseForm(r); err != nil {
<ide> return err
<ide> }
<ide> func postCommit(eng *engine.Engine, version string, w http.ResponseWriter, r *ht
<ide> }
<ide>
<ide> // Creates an image from Pull or from Import
<del>func postImagesCreate(eng *engine.Engine, version string, w http.ResponseWriter, r *http.Request, vars map[string]string) error {
<add>func postImagesCreate(eng *engine.Engine, version version.Version, w http.ResponseWriter, r *http.Request, vars map[string]string) error {
<ide> if err := parseForm(r); err != nil {
<ide> return err
<ide> }
<ide> func postImagesCreate(eng *engine.Engine, version string, w http.ResponseWriter,
<ide> }
<ide> }
<ide> job = eng.Job("pull", r.Form.Get("fromImage"), tag)
<del> job.SetenvBool("parallel", utils.CompareVersion(version, "1.3") > 0)
<add> job.SetenvBool("parallel", version.GreaterThan("1.3"))
<ide> job.SetenvJson("metaHeaders", metaHeaders)
<ide> job.SetenvJson("authConfig", authConfig)
<ide> } else { //import
<ide> job = eng.Job("import", r.Form.Get("fromSrc"), r.Form.Get("repo"), tag)
<ide> job.Stdin.Add(r.Body)
<ide> }
<ide>
<del> if utils.CompareVersion(version, "1.0") > 0 {
<add> if version.GreaterThan("1.0") {
<ide> job.SetenvBool("json", true)
<ide> streamJSON(job, w, true)
<ide> } else {
<ide> func postImagesCreate(eng *engine.Engine, version string, w http.ResponseWriter,
<ide> if !job.Stdout.Used() {
<ide> return err
<ide> }
<del> sf := utils.NewStreamFormatter(utils.CompareVersion(version, "1.0") > 0)
<add> sf := utils.NewStreamFormatter(version.GreaterThan("1.0"))
<ide> w.Write(sf.FormatError(err))
<ide> }
<ide>
<ide> return nil
<ide> }
<ide>
<del>func getImagesSearch(eng *engine.Engine, version string, w http.ResponseWriter, r *http.Request, vars map[string]string) error {
<add>func getImagesSearch(eng *engine.Engine, version version.Version, w http.ResponseWriter, r *http.Request, vars map[string]string) error {
<ide> if err := parseForm(r); err != nil {
<ide> return err
<ide> }
<ide> func getImagesSearch(eng *engine.Engine, version string, w http.ResponseWriter,
<ide> return job.Run()
<ide> }
<ide>
<del>func postImagesInsert(eng *engine.Engine, version string, w http.ResponseWriter, r *http.Request, vars map[string]string) error {
<add>func postImagesInsert(eng *engine.Engine, version version.Version, w http.ResponseWriter, r *http.Request, vars map[string]string) error {
<ide> if err := parseForm(r); err != nil {
<ide> return err
<ide> }
<ide> if vars == nil {
<ide> return fmt.Errorf("Missing parameter")
<ide> }
<ide> job := eng.Job("insert", vars["name"], r.Form.Get("url"), r.Form.Get("path"))
<del> if utils.CompareVersion(version, "1.0") > 0 {
<add> if version.GreaterThan("1.0") {
<ide> job.SetenvBool("json", true)
<ide> streamJSON(job, w, false)
<ide> } else {
<ide> func postImagesInsert(eng *engine.Engine, version string, w http.ResponseWriter,
<ide> if !job.Stdout.Used() {
<ide> return err
<ide> }
<del> sf := utils.NewStreamFormatter(utils.CompareVersion(version, "1.0") > 0)
<add> sf := utils.NewStreamFormatter(version.GreaterThan("1.0"))
<ide> w.Write(sf.FormatError(err))
<ide> }
<ide>
<ide> return nil
<ide> }
<ide>
<del>func postImagesPush(eng *engine.Engine, version string, w http.ResponseWriter, r *http.Request, vars map[string]string) error {
<add>func postImagesPush(eng *engine.Engine, version version.Version, w http.ResponseWriter, r *http.Request, vars map[string]string) error {
<ide> if vars == nil {
<ide> return fmt.Errorf("Missing parameter")
<ide> }
<ide> func postImagesPush(eng *engine.Engine, version string, w http.ResponseWriter, r
<ide> job := eng.Job("push", vars["name"])
<ide> job.SetenvJson("metaHeaders", metaHeaders)
<ide> job.SetenvJson("authConfig", authConfig)
<del> if utils.CompareVersion(version, "1.0") > 0 {
<add> if version.GreaterThan("1.0") {
<ide> job.SetenvBool("json", true)
<ide> streamJSON(job, w, true)
<ide> } else {
<ide> func postImagesPush(eng *engine.Engine, version string, w http.ResponseWriter, r
<ide> if !job.Stdout.Used() {
<ide> return err
<ide> }
<del> sf := utils.NewStreamFormatter(utils.CompareVersion(version, "1.0") > 0)
<add> sf := utils.NewStreamFormatter(version.GreaterThan("1.0"))
<ide> w.Write(sf.FormatError(err))
<ide> }
<ide> return nil
<ide> }
<ide>
<del>func getImagesGet(eng *engine.Engine, version string, w http.ResponseWriter, r *http.Request, vars map[string]string) error {
<add>func getImagesGet(eng *engine.Engine, version version.Version, w http.ResponseWriter, r *http.Request, vars map[string]string) error {
<ide> if vars == nil {
<ide> return fmt.Errorf("Missing parameter")
<ide> }
<del> if utils.CompareVersion(version, "1.0") > 0 {
<add> if version.GreaterThan("1.0") {
<ide> w.Header().Set("Content-Type", "application/x-tar")
<ide> }
<ide> job := eng.Job("image_export", vars["name"])
<ide> job.Stdout.Add(w)
<ide> return job.Run()
<ide> }
<ide>
<del>func postImagesLoad(eng *engine.Engine, version string, w http.ResponseWriter, r *http.Request, vars map[string]string) error {
<add>func postImagesLoad(eng *engine.Engine, version version.Version, w http.ResponseWriter, r *http.Request, vars map[string]string) error {
<ide> job := eng.Job("load")
<ide> job.Stdin.Add(r.Body)
<ide> return job.Run()
<ide> }
<ide>
<del>func postContainersCreate(eng *engine.Engine, version string, w http.ResponseWriter, r *http.Request, vars map[string]string) error {
<add>func postContainersCreate(eng *engine.Engine, version version.Version, w http.ResponseWriter, r *http.Request, vars map[string]string) error {
<ide> if err := parseForm(r); err != nil {
<ide> return nil
<ide> }
<ide> func postContainersCreate(eng *engine.Engine, version string, w http.ResponseWri
<ide> return writeJSON(w, http.StatusCreated, out)
<ide> }
<ide>
<del>func postContainersRestart(eng *engine.Engine, version string, w http.ResponseWriter, r *http.Request, vars map[string]string) error {
<add>func postContainersRestart(eng *engine.Engine, version version.Version, w http.ResponseWriter, r *http.Request, vars map[string]string) error {
<ide> if err := parseForm(r); err != nil {
<ide> return err
<ide> }
<ide> func postContainersRestart(eng *engine.Engine, version string, w http.ResponseWr
<ide> return nil
<ide> }
<ide>
<del>func deleteContainers(eng *engine.Engine, version string, w http.ResponseWriter, r *http.Request, vars map[string]string) error {
<add>func deleteContainers(eng *engine.Engine, version version.Version, w http.ResponseWriter, r *http.Request, vars map[string]string) error {
<ide> if err := parseForm(r); err != nil {
<ide> return err
<ide> }
<ide> func deleteContainers(eng *engine.Engine, version string, w http.ResponseWriter,
<ide> return nil
<ide> }
<ide>
<del>func deleteImages(eng *engine.Engine, version string, w http.ResponseWriter, r *http.Request, vars map[string]string) error {
<add>func deleteImages(eng *engine.Engine, version version.Version, w http.ResponseWriter, r *http.Request, vars map[string]string) error {
<ide> if err := parseForm(r); err != nil {
<ide> return err
<ide> }
<ide> func deleteImages(eng *engine.Engine, version string, w http.ResponseWriter, r *
<ide> return job.Run()
<ide> }
<ide>
<del>func postContainersStart(eng *engine.Engine, version string, w http.ResponseWriter, r *http.Request, vars map[string]string) error {
<add>func postContainersStart(eng *engine.Engine, version version.Version, w http.ResponseWriter, r *http.Request, vars map[string]string) error {
<ide> if vars == nil {
<ide> return fmt.Errorf("Missing parameter")
<ide> }
<ide> func postContainersStart(eng *engine.Engine, version string, w http.ResponseWrit
<ide> return nil
<ide> }
<ide>
<del>func postContainersStop(eng *engine.Engine, version string, w http.ResponseWriter, r *http.Request, vars map[string]string) error {
<add>func postContainersStop(eng *engine.Engine, version version.Version, w http.ResponseWriter, r *http.Request, vars map[string]string) error {
<ide> if err := parseForm(r); err != nil {
<ide> return err
<ide> }
<ide> func postContainersStop(eng *engine.Engine, version string, w http.ResponseWrite
<ide> return nil
<ide> }
<ide>
<del>func postContainersWait(eng *engine.Engine, version string, w http.ResponseWriter, r *http.Request, vars map[string]string) error {
<add>func postContainersWait(eng *engine.Engine, version version.Version, w http.ResponseWriter, r *http.Request, vars map[string]string) error {
<ide> if vars == nil {
<ide> return fmt.Errorf("Missing parameter")
<ide> }
<ide> func postContainersWait(eng *engine.Engine, version string, w http.ResponseWrite
<ide> return writeJSON(w, http.StatusOK, env)
<ide> }
<ide>
<del>func postContainersResize(eng *engine.Engine, version string, w http.ResponseWriter, r *http.Request, vars map[string]string) error {
<add>func postContainersResize(eng *engine.Engine, version version.Version, w http.ResponseWriter, r *http.Request, vars map[string]string) error {
<ide> if err := parseForm(r); err != nil {
<ide> return err
<ide> }
<ide> func postContainersResize(eng *engine.Engine, version string, w http.ResponseWri
<ide> return nil
<ide> }
<ide>
<del>func postContainersAttach(eng *engine.Engine, version string, w http.ResponseWriter, r *http.Request, vars map[string]string) error {
<add>func postContainersAttach(eng *engine.Engine, version version.Version, w http.ResponseWriter, r *http.Request, vars map[string]string) error {
<ide> if err := parseForm(r); err != nil {
<ide> return err
<ide> }
<ide> func postContainersAttach(eng *engine.Engine, version string, w http.ResponseWri
<ide>
<ide> fmt.Fprintf(outStream, "HTTP/1.1 200 OK\r\nContent-Type: application/vnd.docker.raw-stream\r\n\r\n")
<ide>
<del> if c.GetSubEnv("Config") != nil && !c.GetSubEnv("Config").GetBool("Tty") && utils.CompareVersion(version, "1.6") >= 0 {
<add> if c.GetSubEnv("Config") != nil && !c.GetSubEnv("Config").GetBool("Tty") && version.GreaterThanOrEqualTo("1.6") {
<ide> errStream = utils.NewStdWriter(outStream, utils.Stderr)
<ide> outStream = utils.NewStdWriter(outStream, utils.Stdout)
<ide> } else {
<ide> func postContainersAttach(eng *engine.Engine, version string, w http.ResponseWri
<ide> return nil
<ide> }
<ide>
<del>func wsContainersAttach(eng *engine.Engine, version string, w http.ResponseWriter, r *http.Request, vars map[string]string) error {
<add>func wsContainersAttach(eng *engine.Engine, version version.Version, w http.ResponseWriter, r *http.Request, vars map[string]string) error {
<ide> if err := parseForm(r); err != nil {
<ide> return err
<ide> }
<ide> func wsContainersAttach(eng *engine.Engine, version string, w http.ResponseWrite
<ide> return nil
<ide> }
<ide>
<del>func getContainersByName(eng *engine.Engine, version string, w http.ResponseWriter, r *http.Request, vars map[string]string) error {
<add>func getContainersByName(eng *engine.Engine, version version.Version, w http.ResponseWriter, r *http.Request, vars map[string]string) error {
<ide> if vars == nil {
<ide> return fmt.Errorf("Missing parameter")
<ide> }
<ide> func getContainersByName(eng *engine.Engine, version string, w http.ResponseWrit
<ide> return job.Run()
<ide> }
<ide>
<del>func getImagesByName(eng *engine.Engine, version string, w http.ResponseWriter, r *http.Request, vars map[string]string) error {
<add>func getImagesByName(eng *engine.Engine, version version.Version, w http.ResponseWriter, r *http.Request, vars map[string]string) error {
<ide> if vars == nil {
<ide> return fmt.Errorf("Missing parameter")
<ide> }
<ide> func getImagesByName(eng *engine.Engine, version string, w http.ResponseWriter,
<ide> return job.Run()
<ide> }
<ide>
<del>func postBuild(eng *engine.Engine, version string, w http.ResponseWriter, r *http.Request, vars map[string]string) error {
<del> if utils.CompareVersion(version, "1.3") < 0 {
<add>func postBuild(eng *engine.Engine, version version.Version, w http.ResponseWriter, r *http.Request, vars map[string]string) error {
<add> if version.LessThan("1.3") {
<ide> return fmt.Errorf("Multipart upload for build is no longer supported. Please upgrade your docker client.")
<ide> }
<ide> var (
<ide> func postBuild(eng *engine.Engine, version string, w http.ResponseWriter, r *htt
<ide> // Both headers will be parsed and sent along to the daemon, but if a non-empty
<ide> // ConfigFile is present, any value provided as an AuthConfig directly will
<ide> // be overridden. See BuildFile::CmdFrom for details.
<del> if utils.CompareVersion(version, "1.9") < 0 && authEncoded != "" {
<add> if version.LessThan("1.9") && authEncoded != "" {
<ide> authJson := base64.NewDecoder(base64.URLEncoding, strings.NewReader(authEncoded))
<ide> if err := json.NewDecoder(authJson).Decode(authConfig); err != nil {
<ide> // for a pull it is not an error if no auth was given
<ide> func postBuild(eng *engine.Engine, version string, w http.ResponseWriter, r *htt
<ide> }
<ide> }
<ide>
<del> if utils.CompareVersion(version, "1.8") >= 0 {
<add> if version.GreaterThanOrEqualTo("1.8") {
<ide> job.SetenvBool("json", true)
<ide> streamJSON(job, w, true)
<ide> } else {
<ide> func postBuild(eng *engine.Engine, version string, w http.ResponseWriter, r *htt
<ide> if !job.Stdout.Used() {
<ide> return err
<ide> }
<del> sf := utils.NewStreamFormatter(utils.CompareVersion(version, "1.8") >= 0)
<add> sf := utils.NewStreamFormatter(version.GreaterThanOrEqualTo("1.8"))
<ide> w.Write(sf.FormatError(err))
<ide> }
<ide> return nil
<ide> }
<ide>
<del>func postContainersCopy(eng *engine.Engine, version string, w http.ResponseWriter, r *http.Request, vars map[string]string) error {
<add>func postContainersCopy(eng *engine.Engine, version version.Version, w http.ResponseWriter, r *http.Request, vars map[string]string) error {
<ide> if vars == nil {
<ide> return fmt.Errorf("Missing parameter")
<ide> }
<ide> func postContainersCopy(eng *engine.Engine, version string, w http.ResponseWrite
<ide> return nil
<ide> }
<ide>
<del>func optionsHandler(eng *engine.Engine, version string, w http.ResponseWriter, r *http.Request, vars map[string]string) error {
<add>func optionsHandler(eng *engine.Engine, version version.Version, w http.ResponseWriter, r *http.Request, vars map[string]string) error {
<ide> w.WriteHeader(http.StatusOK)
<ide> return nil
<ide> }
<ide> func writeCorsHeaders(w http.ResponseWriter, r *http.Request) {
<ide> w.Header().Add("Access-Control-Allow-Methods", "GET, POST, DELETE, PUT, OPTIONS")
<ide> }
<ide>
<del>func makeHttpHandler(eng *engine.Engine, logging bool, localMethod string, localRoute string, handlerFunc HttpApiFunc, enableCors bool, dockerVersion string) http.HandlerFunc {
<add>func makeHttpHandler(eng *engine.Engine, logging bool, localMethod string, localRoute string, handlerFunc HttpApiFunc, enableCors bool, dockerVersion version.Version) http.HandlerFunc {
<ide> return func(w http.ResponseWriter, r *http.Request) {
<ide> // log the request
<ide> utils.Debugf("Calling %s %s", localMethod, localRoute)
<ide> func makeHttpHandler(eng *engine.Engine, logging bool, localMethod string, local
<ide>
<ide> if strings.Contains(r.Header.Get("User-Agent"), "Docker-Client/") {
<ide> userAgent := strings.Split(r.Header.Get("User-Agent"), "/")
<del> if len(userAgent) == 2 && userAgent[1] != dockerVersion {
<add> if len(userAgent) == 2 && !dockerVersion.Equal(userAgent[1]) {
<ide> utils.Debugf("Warning: client and server don't have the same version (client: %s, server: %s)", userAgent[1], dockerVersion)
<ide> }
<ide> }
<del> version := mux.Vars(r)["version"]
<add> version := version.Version(mux.Vars(r)["version"])
<ide> if version == "" {
<ide> version = APIVERSION
<ide> }
<ide> if enableCors {
<ide> writeCorsHeaders(w, r)
<ide> }
<ide>
<del> if utils.CompareVersion(version, APIVERSION) == 1 {
<add> if version.GreaterThan(APIVERSION) {
<ide> http.Error(w, fmt.Errorf("client and server don't have same version (client : %s, server: %s)", version, APIVERSION).Error(), http.StatusNotFound)
<ide> return
<ide> }
<ide> func createRouter(eng *engine.Engine, logging, enableCors bool, dockerVersion st
<ide> localMethod := method
<ide>
<ide> // build the handler function
<del> f := makeHttpHandler(eng, logging, localMethod, localRoute, localFct, enableCors, dockerVersion)
<add> f := makeHttpHandler(eng, logging, localMethod, localRoute, localFct, enableCors, version.Version(dockerVersion))
<ide>
<ide> // add the new route
<ide> if localRoute == "" {
<ide> func createRouter(eng *engine.Engine, logging, enableCors bool, dockerVersion st
<ide> // ServeRequest processes a single http request to the docker remote api.
<ide> // FIXME: refactor this to be part of Server and not require re-creating a new
<ide> // router each time. This requires first moving ListenAndServe into Server.
<del>func ServeRequest(eng *engine.Engine, apiversion string, w http.ResponseWriter, req *http.Request) error {
<add>func ServeRequest(eng *engine.Engine, apiversion version.Version, w http.ResponseWriter, req *http.Request) error {
<ide> router, err := createRouter(eng, false, true, "")
<ide> if err != nil {
<ide> return err
<ide><path>integration/server_test.go
<ide> package docker
<ide>
<ide> import (
<ide> "github.com/dotcloud/docker"
<add> "github.com/dotcloud/docker/engine"
<ide> "github.com/dotcloud/docker/runconfig"
<ide> "strings"
<ide> "testing"
<ide><path>pkg/version/version.go
<add>package version
<add>
<add>import (
<add> "strconv"
<add> "strings"
<add>)
<add>
<add>type Version string
<add>
<add>func (me Version) compareTo(other string) int {
<add> var (
<add> meTab = strings.Split(string(me), ".")
<add> otherTab = strings.Split(other, ".")
<add> )
<add> for i, s := range meTab {
<add> var meInt, otherInt int
<add> meInt, _ = strconv.Atoi(s)
<add> if len(otherTab) > i {
<add> otherInt, _ = strconv.Atoi(otherTab[i])
<add> }
<add> if meInt > otherInt {
<add> return 1
<add> }
<add> if otherInt > meInt {
<add> return -1
<add> }
<add> }
<add> if len(otherTab) > len(meTab) {
<add> return -1
<add> }
<add> return 0
<add>}
<add>
<add>func (me Version) LessThan(other string) bool {
<add> return me.compareTo(other) == -1
<add>}
<add>
<add>func (me Version) LessThanOrEqualTo(other string) bool {
<add> return me.compareTo(other) <= 0
<add>}
<add>
<add>func (me Version) GreaterThan(other string) bool {
<add> return me.compareTo(other) == 1
<add>}
<add>
<add>func (me Version) GreaterThanOrEqualTo(other string) bool {
<add> return me.compareTo(other) >= 0
<add>}
<add>
<add>func (me Version) Equal(other string) bool {
<add> return me.compareTo(other) == 0
<add>}
<ide><path>pkg/version/version_test.go
<add>package version
<add>
<add>import (
<add> "testing"
<add>)
<add>
<add>func assertVersion(t *testing.T, a, b string, result int) {
<add> if r := Version(a).compareTo(b); r != result {
<add> t.Fatalf("Unexpected version comparison result. Found %d, expected %d", r, result)
<add> }
<add>}
<add>
<add>func TestCompareVersion(t *testing.T) {
<add> assertVersion(t, "1.12", "1.12", 0)
<add> assertVersion(t, "1.05.00.0156", "1.0.221.9289", 1)
<add> assertVersion(t, "1", "1.0.1", -1)
<add> assertVersion(t, "1.0.1", "1", 1)
<add> assertVersion(t, "1.0.1", "1.0.2", -1)
<add> assertVersion(t, "1.0.2", "1.0.3", -1)
<add> assertVersion(t, "1.0.3", "1.1", -1)
<add> assertVersion(t, "1.1", "1.1.1", -1)
<add> assertVersion(t, "1.1.1", "1.1.2", -1)
<add> assertVersion(t, "1.1.2", "1.2", -1)
<add>
<add>}
<ide><path>utils/utils.go
<ide> func NewReadCloserWrapper(r io.Reader, closer func() error) io.ReadCloser {
<ide> closer: closer,
<ide> }
<ide> }
<del>
<del>func CompareVersion(a, b string) int {
<del> var (
<del> aa = strings.Split(a, ".")
<del> bb = strings.Split(b, ".")
<del> )
<del> for i, s := range aa {
<del> var ai, bi int
<del> ai, _ = strconv.Atoi(s)
<del> if len(bb) > i {
<del> bi, _ = strconv.Atoi(bb[i])
<del> }
<del> if ai > bi {
<del> return 1
<del> }
<del> if bi > ai {
<del> return -1
<del> }
<del> }
<del> if len(bb) > len(aa) {
<del> return -1
<del> }
<del> return 0
<del>}
<ide><path>utils/utils_test.go
<ide> func StrSlicesEqual(a, b []string) bool {
<ide>
<ide> return true
<ide> }
<del>
<del>func asserVersion(t *testing.T, a, b string, result int) {
<del> if r := CompareVersion(a, b); r != result {
<del> t.Fatalf("Unexpected version comparison result. Found %d, expected %d", r, result)
<del> }
<del>}
<del>
<del>func TestCompareVersion(t *testing.T) {
<del> asserVersion(t, "1.12", "1.12", 0)
<del> asserVersion(t, "1.05.00.0156", "1.0.221.9289", 1)
<del> asserVersion(t, "1", "1.0.1", -1)
<del> asserVersion(t, "1.0.1", "1", 1)
<del> asserVersion(t, "1.0.1", "1.0.2", -1)
<del> asserVersion(t, "1.0.2", "1.0.3", -1)
<del> asserVersion(t, "1.0.3", "1.1", -1)
<del> asserVersion(t, "1.1", "1.1.1", -1)
<del> asserVersion(t, "1.1.1", "1.1.2", -1)
<del> asserVersion(t, "1.1.2", "1.2", -1)
<del>
<del>} | 6 |
Go | Go | fix getmetadata() comment | 15a232fd06e062f8aae4e89e1f520f44c875daeb | <ide><path>daemon/graphdriver/zfs/zfs.go
<ide> func (d *Driver) Status() [][2]string {
<ide> }
<ide> }
<ide>
<del>// GetMetadata is used for implementing the graphdriver.ProtoDriver interface. ZFS does not currently have any meta data.
<add>// GetMetadata returns image/container metadata related to graph driver
<ide> func (d *Driver) GetMetadata(id string) (map[string]string, error) {
<ide> return nil, nil
<ide> } | 1 |
PHP | PHP | use json_pretty_print available in php 5.4 | ef2220995f73155fd5ebedd754c89656bcb49c25 | <ide><path>src/Illuminate/Foundation/ProviderRepository.php
<ide> public function writeManifest($manifest)
<ide> {
<ide> $path = $this->manifestPath.'/services.json';
<ide>
<del> $this->files->put($path, json_encode($manifest));
<add> $this->files->put($path, json_encode($manifest, JSON_PRETTY_PRINT));
<ide>
<ide> return $manifest;
<ide> } | 1 |
Text | Text | clarify use of `0` port value | 60891c6ef0dc3bf9518d7132da6498c66f26763e | <ide><path>doc/api/http.md
<ide> a listener for the `'listening'` event. See also [`net.Server.listen(path)`][].
<ide>
<ide> Begin accepting connections on the specified `port` and `hostname`. If the
<ide> `hostname` is omitted, the server will accept connections on any IPv6 address
<del>(`::`) when IPv6 is available, or any IPv4 address (`0.0.0.0`) otherwise. A
<del>port value of zero will assign a random port.
<add>(`::`) when IPv6 is available, or any IPv4 address (`0.0.0.0`) otherwise. Use a
<add>port value of zero to have the operating system assign an available port.
<ide>
<ide> To listen to a unix socket, supply a filename instead of port and hostname.
<ide>
<ide><path>doc/api/net.md
<ide> added: v0.1.90
<ide>
<ide> Begin accepting connections on the specified `port` and `hostname`. If the
<ide> `hostname` is omitted, the server will accept connections on any IPv6 address
<del>(`::`) when IPv6 is available, or any IPv4 address (`0.0.0.0`) otherwise. A
<del>port value of zero will assign a random port.
<add>(`::`) when IPv6 is available, or any IPv4 address (`0.0.0.0`) otherwise. Use a
<add>port value of `0` to have the operating system assign an available port.
<ide>
<ide> Backlog is the maximum length of the queue of pending connections.
<ide> The actual length will be determined by the OS through sysctl settings such as | 2 |
Python | Python | fix special tokens not correctly tokenized | da8beaaf762c0ea4eecb150039be63949fe5cf94 | <ide><path>src/transformers/tokenization_utils.py
<ide> def tokenize(self, text: TextInput, **kwargs) -> List[str]:
<ide> # TODO: should this be in the base class?
<ide> if hasattr(self, "do_lower_case") and self.do_lower_case:
<ide> # convert non-special tokens to lowercase
<del> escaped_special_toks = [re.escape(s_tok) for s_tok in self.all_special_tokens]
<add> escaped_special_toks = [
<add> re.escape(s_tok) for s_tok in (self.unique_no_split_tokens + self.all_special_tokens)
<add> ]
<ide> pattern = r"(" + r"|".join(escaped_special_toks) + r")|" + r"(.+?)"
<ide> text = re.sub(pattern, lambda m: m.groups()[0] or m.groups()[1].lower(), text)
<ide>
<ide><path>tests/test_tokenization_canine.py
<ide> def test_add_special_tokens(self):
<ide> decoded = tokenizer.decode(encoded, skip_special_tokens=True)
<ide> self.assertTrue(special_token not in decoded)
<ide>
<add> def test_tokenize_special_tokens(self):
<add> tokenizers = self.get_tokenizers(do_lower_case=True)
<add> for tokenizer in tokenizers:
<add> with self.subTest(f"{tokenizer.__class__.__name__}"):
<add> SPECIAL_TOKEN_1 = chr(0xE005)
<add> SPECIAL_TOKEN_2 = chr(0xE006)
<add>
<add> # `add_tokens` method stores special tokens only in `tokenizer.unique_no_split_tokens`. (in tokenization_utils.py)
<add> tokenizer.add_tokens([SPECIAL_TOKEN_1], special_tokens=True)
<add> # `add_special_tokens` method stores special tokens in `tokenizer.additional_special_tokens`,
<add> # which also occur in `tokenizer.all_special_tokens`. (in tokenization_utils_base.py)
<add> tokenizer.add_special_tokens({"additional_special_tokens": [SPECIAL_TOKEN_2]})
<add>
<add> token_1 = tokenizer.tokenize(SPECIAL_TOKEN_1)
<add> token_2 = tokenizer.tokenize(SPECIAL_TOKEN_2)
<add>
<add> self.assertEqual(len(token_1), 1)
<add> self.assertEqual(len(token_2), 1)
<add> self.assertEqual(token_1[0], SPECIAL_TOKEN_1)
<add> self.assertEqual(token_2[0], SPECIAL_TOKEN_2)
<add>
<ide> @require_tokenizers
<ide> def test_added_token_serializable(self):
<ide> tokenizers = self.get_tokenizers(do_lower_case=False)
<ide><path>tests/test_tokenization_common.py
<ide> def convert_batch_encode_plus_format_to_encode_plus(batch_encode_plus_sequences)
<ide> for i in range(len(batch_encode_plus_sequences["input_ids"]))
<ide> ]
<ide>
<add> # TODO: this test can be combined with `test_sentencepiece_tokenize_and_convert_tokens_to_string` after the latter is extended to all tokenizers.
<add> def test_tokenize_special_tokens(self):
<add> """Test `tokenize` with special tokens."""
<add> tokenizers = self.get_tokenizers(fast=True)
<add> for tokenizer in tokenizers:
<add> with self.subTest(f"{tokenizer.__class__.__name__}"):
<add> SPECIAL_TOKEN_1 = "[SPECIAL_TOKEN_1]"
<add> SPECIAL_TOKEN_2 = "[SPECIAL_TOKEN_2]"
<add>
<add> # TODO:
<add> # Can we combine `unique_no_split_tokens` and `all_special_tokens`(and properties related to it)
<add> # with one variable(property) for a better maintainability?
<add>
<add> # `add_tokens` method stores special tokens only in `tokenizer.unique_no_split_tokens`. (in tokenization_utils.py)
<add> tokenizer.add_tokens([SPECIAL_TOKEN_1], special_tokens=True)
<add> # `add_special_tokens` method stores special tokens in `tokenizer.additional_special_tokens`,
<add> # which also occur in `tokenizer.all_special_tokens`. (in tokenization_utils_base.py)
<add> tokenizer.add_special_tokens({"additional_special_tokens": [SPECIAL_TOKEN_2]})
<add>
<add> token_1 = tokenizer.tokenize(SPECIAL_TOKEN_1)
<add> token_2 = tokenizer.tokenize(SPECIAL_TOKEN_2)
<add>
<add> self.assertEqual(len(token_1), 1)
<add> self.assertEqual(len(token_2), 1)
<add> self.assertEqual(token_1[0], SPECIAL_TOKEN_1)
<add> self.assertEqual(token_2[0], SPECIAL_TOKEN_2)
<add>
<ide> # TODO: this test could be extended to all tokenizers - not just the sentencepiece
<ide> def test_sentencepiece_tokenize_and_convert_tokens_to_string(self):
<ide> """Test ``_tokenize`` and ``convert_tokens_to_string``.""" | 3 |
Text | Text | add pr template | 951d42f54af7bf84897d3d2907e8476a4d2a26db | <ide><path>.github/PULL_REQUEST_TEMPLATE.md
<add><!--
<add>Pull Requests without a descriptive title, thorough description, or tests will be closed.
<add>
<add>Please include the benefit to end users; the reasons it does not break any existing features; how it makes building web applications easier, etc.
<add>--> | 1 |
Python | Python | improve lithuanian tokenization | 86c43e55fa3a9557e838998bc288bb4833c2d0ec | <ide><path>spacy/lang/lt/__init__.py
<ide> # coding: utf8
<ide> from __future__ import unicode_literals
<ide>
<add>from .punctuation import TOKENIZER_INFIXES, TOKENIZER_SUFFIXES
<ide> from .tokenizer_exceptions import TOKENIZER_EXCEPTIONS
<ide> from .stop_words import STOP_WORDS
<ide> from .lex_attrs import LEX_ATTRS
<ide> class LithuanianDefaults(Language.Defaults):
<ide> )
<ide> lex_attr_getters.update(LEX_ATTRS)
<ide>
<del> tokenizer_exceptions = update_exc(BASE_EXCEPTIONS, TOKENIZER_EXCEPTIONS)
<add> infixes = TOKENIZER_INFIXES
<add> suffixes = TOKENIZER_SUFFIXES
<add> mod_base_exceptions = {exc: val for exc, val in BASE_EXCEPTIONS.items() if not exc.endswith(".")}
<add> del mod_base_exceptions["8)"]
<add> tokenizer_exceptions = update_exc(mod_base_exceptions, TOKENIZER_EXCEPTIONS)
<ide> stop_words = STOP_WORDS
<ide> tag_map = TAG_MAP
<ide> morph_rules = MORPH_RULES
<ide><path>spacy/lang/lt/punctuation.py
<add># coding: utf8
<add>from __future__ import unicode_literals
<add>
<add>from ..char_classes import LIST_ICONS, LIST_ELLIPSES
<add>from ..char_classes import CONCAT_QUOTES, ALPHA_LOWER, ALPHA_UPPER, ALPHA
<add>from ..char_classes import HYPHENS
<add>from ..punctuation import TOKENIZER_SUFFIXES
<add>
<add>
<add>_infixes = (
<add> LIST_ELLIPSES
<add> + LIST_ICONS
<add> + [
<add> r"(?<=[0-9])[+\*^](?=[0-9-])",
<add> r"(?<=[{al}{q}])\.(?=[{au}{q}])".format(
<add> al=ALPHA_LOWER, au=ALPHA_UPPER, q=CONCAT_QUOTES
<add> ),
<add> r"(?<=[{a}]),(?=[{a}])".format(a=ALPHA),
<add> r"(?<=[{a}])(?:{h})(?=[{a}])".format(a=ALPHA, h=HYPHENS),
<add> r"(?<=[{a}0-9])[:<>=/](?=[{a}])".format(a=ALPHA),
<add> ]
<add>)
<add>
<add>
<add>_suffixes = ["\."] + list(TOKENIZER_SUFFIXES)
<add>
<add>
<add>TOKENIZER_INFIXES = _infixes
<add>TOKENIZER_SUFFIXES = _suffixes
<ide><path>spacy/lang/lt/tokenizer_exceptions.py
<ide> _exc = {}
<ide>
<ide> for orth in [
<del> "G.",
<del> "J. E.",
<del> "J. Em.",
<del> "J.E.",
<del> "J.Em.",
<del> "K.",
<del> "N.",
<del> "V.",
<del> "Vt.",
<del> "a.",
<del> "a.k.",
<del> "a.s.",
<del> "adv.",
<del> "akad.",
<del> "aklg.",
<del> "akt.",
<del> "al.",
<del> "ang.",
<del> "angl.",
<del> "aps.",
<del> "apskr.",
<del> "apyg.",
<del> "arbat.",
<del> "asist.",
<del> "asm.",
<del> "asm.k.",
<del> "asmv.",
<del> "atk.",
<del> "atsak.",
<del> "atsisk.",
<del> "atsisk.sąsk.",
<del> "atv.",
<del> "aut.",
<del> "avd.",
<del> "b.k.",
<del> "baud.",
<del> "biol.",
<del> "bkl.",
<del> "bot.",
<del> "bt.",
<del> "buv.",
<del> "ch.",
<del> "chem.",
<del> "corp.",
<del> "d.",
<del> "dab.",
<del> "dail.",
<del> "dek.",
<del> "deš.",
<del> "dir.",
<del> "dirig.",
<del> "doc.",
<del> "dol.",
<del> "dr.",
<del> "drp.",
<del> "dvit.",
<del> "dėst.",
<del> "dš.",
<del> "dž.",
<del> "e.b.",
<del> "e.bankas",
<del> "e.p.",
<del> "e.parašas",
<del> "e.paštas",
<del> "e.v.",
<del> "e.valdžia",
<del> "egz.",
<del> "eil.",
<del> "ekon.",
<del> "el.",
<del> "el.bankas",
<del> "el.p.",
<del> "el.parašas",
<del> "el.paštas",
<del> "el.valdžia",
<del> "etc.",
<del> "ež.",
<del> "fak.",
<del> "faks.",
<del> "feat.",
<del> "filol.",
<del> "filos.",
<del> "g.",
<del> "gen.",
<del> "geol.",
<del> "gerb.",
<del> "gim.",
<del> "gr.",
<del> "gv.",
<del> "gyd.",
<del> "gyv.",
<del> "habil.",
<del> "inc.",
<del> "insp.",
<del> "inž.",
<del> "ir pan.",
<del> "ir t. t.",
<del> "isp.",
<del> "istor.",
<del> "it.",
<del> "just.",
<del> "k.",
<del> "k. a.",
<del> "k.a.",
<del> "kab.",
<del> "kand.",
<del> "kart.",
<del> "kat.",
<del> "ketv.",
<del> "kh.",
<del> "kl.",
<del> "kln.",
<del> "km.",
<del> "kn.",
<del> "koresp.",
<del> "kpt.",
<del> "kr.",
<del> "kt.",
<del> "kub.",
<del> "kun.",
<del> "kv.",
<del> "kyš.",
<del> "l. e. p.",
<del> "l.e.p.",
<del> "lenk.",
<del> "liet.",
<del> "lot.",
<del> "lt.",
<del> "ltd.",
<del> "ltn.",
<del> "m.",
<del> "m.e..",
<del> "m.m.",
<del> "mat.",
<del> "med.",
<del> "mgnt.",
<del> "mgr.",
<del> "min.",
<del> "mjr.",
<del> "ml.",
<del> "mln.",
<del> "mlrd.",
<del> "mob.",
<del> "mok.",
<del> "moksl.",
<del> "mokyt.",
<del> "mot.",
<del> "mr.",
<del> "mst.",
<del> "mstl.",
<del> "mėn.",
<del> "nkt.",
<del> "no.",
<del> "nr.",
<del> "ntk.",
<del> "nuotr.",
<del> "op.",
<del> "org.",
<del> "orig.",
<del> "p.",
<del> "p.d.",
<del> "p.m.e.",
<del> "p.s.",
<del> "pab.",
<del> "pan.",
<del> "past.",
<del> "pav.",
<del> "pavad.",
<del> "per.",
<del> "perd.",
<del> "pirm.",
<del> "pl.",
<del> "plg.",
<del> "plk.",
<del> "pr.",
<del> "pr.Kr.",
<del> "pranc.",
<del> "proc.",
<del> "prof.",
<del> "prom.",
<del> "prot.",
<del> "psl.",
<del> "pss.",
<del> "pvz.",
<del> "pšt.",
<del> "r.",
<del> "raj.",
<del> "red.",
<del> "rez.",
<del> "rež.",
<del> "rus.",
<del> "rš.",
<del> "s.",
<del> "sav.",
<del> "saviv.",
<del> "sek.",
<del> "sekr.",
<del> "sen.",
<del> "sh.",
<del> "sk.",
<del> "skg.",
<del> "skv.",
<del> "skyr.",
<del> "sp.",
<del> "spec.",
<del> "sr.",
<del> "st.",
<del> "str.",
<del> "stud.",
<del> "sąs.",
<del> "t.",
<del> "t. p.",
<del> "t. y.",
<del> "t.p.",
<del> "t.t.",
<del> "t.y.",
<del> "techn.",
<del> "tel.",
<del> "teol.",
<del> "th.",
<del> "tir.",
<del> "trit.",
<del> "trln.",
<del> "tšk.",
<del> "tūks.",
<del> "tūkst.",
<del> "up.",
<del> "upl.",
<del> "v.s.",
<del> "vad.",
<del> "val.",
<del> "valg.",
<del> "ved.",
<del> "vert.",
<del> "vet.",
<del> "vid.",
<del> "virš.",
<del> "vlsč.",
<del> "vnt.",
<del> "vok.",
<del> "vs.",
<del> "vtv.",
<del> "vv.",
<del> "vyr.",
<del> "vyresn.",
<del> "zool.",
<del> "Įn",
<del> "įl.",
<del> "š.m.",
<del> "šnek.",
<del> "šv.",
<del> "švč.",
<del> "ž.ū.",
<del> "žin.",
<del> "žml.",
<del> "žr.",
<add> "n-tosios",
<add> "?!",
<add># "G.",
<add># "J. E.",
<add># "J. Em.",
<add># "J.E.",
<add># "J.Em.",
<add># "K.",
<add># "N.",
<add># "V.",
<add># "Vt.",
<add># "a.",
<add># "a.k.",
<add># "a.s.",
<add># "adv.",
<add># "akad.",
<add># "aklg.",
<add># "akt.",
<add># "al.",
<add># "ang.",
<add># "angl.",
<add># "aps.",
<add># "apskr.",
<add># "apyg.",
<add># "arbat.",
<add># "asist.",
<add># "asm.",
<add># "asm.k.",
<add># "asmv.",
<add># "atk.",
<add># "atsak.",
<add># "atsisk.",
<add># "atsisk.sąsk.",
<add># "atv.",
<add># "aut.",
<add># "avd.",
<add># "b.k.",
<add># "baud.",
<add># "biol.",
<add># "bkl.",
<add># "bot.",
<add># "bt.",
<add># "buv.",
<add># "ch.",
<add># "chem.",
<add># "corp.",
<add># "d.",
<add># "dab.",
<add># "dail.",
<add># "dek.",
<add># "deš.",
<add># "dir.",
<add># "dirig.",
<add># "doc.",
<add># "dol.",
<add># "dr.",
<add># "drp.",
<add># "dvit.",
<add># "dėst.",
<add># "dš.",
<add># "dž.",
<add># "e.b.",
<add># "e.bankas",
<add># "e.p.",
<add># "e.parašas",
<add># "e.paštas",
<add># "e.v.",
<add># "e.valdžia",
<add># "egz.",
<add># "eil.",
<add># "ekon.",
<add># "el.",
<add># "el.bankas",
<add># "el.p.",
<add># "el.parašas",
<add># "el.paštas",
<add># "el.valdžia",
<add># "etc.",
<add># "ež.",
<add># "fak.",
<add># "faks.",
<add># "feat.",
<add># "filol.",
<add># "filos.",
<add># "g.",
<add># "gen.",
<add># "geol.",
<add># "gerb.",
<add># "gim.",
<add># "gr.",
<add># "gv.",
<add># "gyd.",
<add># "gyv.",
<add># "habil.",
<add># "inc.",
<add># "insp.",
<add># "inž.",
<add># "ir pan.",
<add># "ir t. t.",
<add># "isp.",
<add># "istor.",
<add># "it.",
<add># "just.",
<add># "k.",
<add># "k. a.",
<add># "k.a.",
<add># "kab.",
<add># "kand.",
<add># "kart.",
<add># "kat.",
<add># "ketv.",
<add># "kh.",
<add># "kl.",
<add># "kln.",
<add># "km.",
<add># "kn.",
<add># "koresp.",
<add># "kpt.",
<add># "kr.",
<add># "kt.",
<add># "kub.",
<add># "kun.",
<add># "kv.",
<add># "kyš.",
<add># "l. e. p.",
<add># "l.e.p.",
<add># "lenk.",
<add># "liet.",
<add># "lot.",
<add># "lt.",
<add># "ltd.",
<add># "ltn.",
<add># "m.",
<add># "m.e..",
<add># "m.m.",
<add># "mat.",
<add># "med.",
<add># "mgnt.",
<add># "mgr.",
<add># "min.",
<add># "mjr.",
<add># "ml.",
<add># "mln.",
<add># "mlrd.",
<add># "mob.",
<add># "mok.",
<add># "moksl.",
<add># "mokyt.",
<add># "mot.",
<add># "mr.",
<add># "mst.",
<add># "mstl.",
<add># "mėn.",
<add># "nkt.",
<add># "no.",
<add># "nr.",
<add># "ntk.",
<add># "nuotr.",
<add># "op.",
<add># "org.",
<add># "orig.",
<add># "p.",
<add># "p.d.",
<add># "p.m.e.",
<add># "p.s.",
<add># "pab.",
<add># "pan.",
<add># "past.",
<add># "pav.",
<add># "pavad.",
<add># "per.",
<add># "perd.",
<add># "pirm.",
<add># "pl.",
<add># "plg.",
<add># "plk.",
<add># "pr.",
<add># "pr.Kr.",
<add># "pranc.",
<add># "proc.",
<add># "prof.",
<add># "prom.",
<add># "prot.",
<add># "psl.",
<add># "pss.",
<add># "pvz.",
<add># "pšt.",
<add># "r.",
<add># "raj.",
<add># "red.",
<add># "rez.",
<add># "rež.",
<add># "rus.",
<add># "rš.",
<add># "s.",
<add># "sav.",
<add># "saviv.",
<add># "sek.",
<add># "sekr.",
<add># "sen.",
<add># "sh.",
<add># "sk.",
<add># "skg.",
<add># "skv.",
<add># "skyr.",
<add># "sp.",
<add># "spec.",
<add># "sr.",
<add># "st.",
<add># "str.",
<add># "stud.",
<add># "sąs.",
<add># "t.",
<add># "t. p.",
<add># "t. y.",
<add># "t.p.",
<add># "t.t.",
<add># "t.y.",
<add># "techn.",
<add># "tel.",
<add># "teol.",
<add># "th.",
<add># "tir.",
<add># "trit.",
<add># "trln.",
<add># "tšk.",
<add># "tūks.",
<add># "tūkst.",
<add># "up.",
<add># "upl.",
<add># "v.s.",
<add># "vad.",
<add># "val.",
<add># "valg.",
<add># "ved.",
<add># "vert.",
<add># "vet.",
<add># "vid.",
<add># "virš.",
<add># "vlsč.",
<add># "vnt.",
<add># "vok.",
<add># "vs.",
<add># "vtv.",
<add># "vv.",
<add># "vyr.",
<add># "vyresn.",
<add># "zool.",
<add># "Įn",
<add># "įl.",
<add># "š.m.",
<add># "šnek.",
<add># "šv.",
<add># "švč.",
<add># "ž.ū.",
<add># "žin.",
<add># "žml.",
<add># "žr.",
<ide> ]:
<ide> _exc[orth] = [{ORTH: orth}]
<ide>
<ide><path>spacy/tests/lang/lt/test_text.py
<ide> def test_lt_tokenizer_handles_long_text(lt_tokenizer):
<ide> [
<ide> (
<ide> "177R Parodų rūmai–Ozo g. nuo vasario 18 d. bus skelbiamas interneto tinklalapyje.",
<del> 15,
<add> 17,
<ide> ),
<ide> (
<ide> "ISM universiteto doc. dr. Ieva Augutytė-Kvedaravičienė pastebi, kad tyrimais nustatyti elgesio pokyčiai.",
<del> 16,
<add> 18,
<ide> ),
<ide> ],
<ide> )
<ide> def test_lt_tokenizer_handles_punct_abbrev(lt_tokenizer, text, length):
<ide> @pytest.mark.parametrize("text", ["km.", "pvz.", "biol."])
<ide> def test_lt_tokenizer_abbrev_exceptions(lt_tokenizer, text):
<ide> tokens = lt_tokenizer(text)
<del> assert len(tokens) == 1
<add> assert len(tokens) == 2
<ide>
<ide>
<ide> @pytest.mark.parametrize( | 4 |
Text | Text | remove keyword for cifar10.load_data | 0cd9d4682888c4ae6616c784d46ca4a4a44fe581 | <ide><path>docs/templates/preprocessing/image.md
<ide> Generate batches of tensor image data with real-time data augmentation. The data
<ide> Example of using `.flow(X, y)`:
<ide>
<ide> ```python
<del>(X_train, y_train), (X_test, y_test) = cifar10.load_data(test_split=0.1)
<add>(X_train, y_train), (X_test, y_test) = cifar10.load_data()
<ide> Y_train = np_utils.to_categorical(y_train, nb_classes)
<ide> Y_test = np_utils.to_categorical(y_test, nb_classes)
<ide> | 1 |
Text | Text | add note about symbols vs strings | 797317089301ca469e113ca3f46f29c129246c3e | <ide><path>guides/source/routing.md
<ide> resources :photos do
<ide> end
<ide> ```
<ide>
<add>NOTE: If you're defining additional resource routes with a symbol as the first positional argument, be mindful that it is not equivalent to using a string. Symbols infer controller actions while strings infer paths.
<add>
<ide> #### Adding Routes for Additional New Actions
<ide>
<ide> To add an alternate new action using the `:on` shortcut: | 1 |
Javascript | Javascript | use displayerrors for syntaxerror | 68ac0d0d7d82f8fde114ef4644c59ae6060e0b01 | <ide><path>lib/repl.js
<ide> function REPLServer(prompt,
<ide> }
<ide> var script = vm.createScript(code, {
<ide> filename: file,
<del> displayErrors: false
<add> displayErrors: true
<ide> });
<ide> } catch (e) {
<ide> debug('parse error %j', code, e);
<ide> function REPLServer(prompt,
<ide> try {
<ide> try {
<ide> const scriptOptions = {
<del> displayErrors: false,
<add> displayErrors: true,
<ide> breakOnSigint: self.breakEvalOnSigint
<ide> };
<ide>
<ide> function REPLServer(prompt,
<ide> debug('domain error');
<ide> const top = replMap.get(self);
<ide> internalUtil.decorateErrorStack(e);
<del> if (e.stack && self.replMode === exports.REPL_MODE_STRICT) {
<add> if (e instanceof SyntaxError && e.stack) {
<add> // remove repl:line-number and stack trace
<add> e.stack = e.stack
<add> .replace(/^repl:\d+\r?\n/, '')
<add> .replace(/^\s+at\s.*\n?/gm, '');
<add> } else if (e.stack && self.replMode === exports.REPL_MODE_STRICT) {
<ide> e.stack = e.stack.replace(/(\s+at\s+repl:)(\d+)/,
<ide> (_, pre, line) => pre + (line - 1));
<ide> }
<ide><path>test/parallel/test-repl.js
<ide> function error_test() {
<ide> expect: prompt_unix },
<ide> // But passing the same string to eval() should throw
<ide> { client: client_unix, send: 'eval("function test_func() {")',
<del> expect: /^SyntaxError: Unexpected end of input/ },
<add> expect: /\bSyntaxError: Unexpected end of input/ },
<ide> // Can handle multiline template literals
<ide> { client: client_unix, send: '`io.js',
<ide> expect: prompt_multiline },
<ide> function error_test() {
<ide> // invalid input to JSON.parse error is special case of syntax error,
<ide> // should throw
<ide> { client: client_unix, send: 'JSON.parse(\'{invalid: \\\'json\\\'}\');',
<del> expect: /^SyntaxError: Unexpected token i/ },
<add> expect: /\bSyntaxError: Unexpected token i/ },
<ide> // end of input to JSON.parse error is special case of syntax error,
<ide> // should throw
<ide> { client: client_unix, send: 'JSON.parse(\'066\');',
<del> expect: /^SyntaxError: Unexpected number/ },
<add> expect: /\bSyntaxError: Unexpected number/ },
<ide> // should throw
<ide> { client: client_unix, send: 'JSON.parse(\'{\');',
<del> expect: /^SyntaxError: Unexpected end of JSON input/ },
<add> expect: /\bSyntaxError: Unexpected end of JSON input/ },
<ide> // invalid RegExps are a special case of syntax error,
<ide> // should throw
<ide> { client: client_unix, send: '/(/;',
<del> expect: /^SyntaxError: Invalid regular expression\:/ },
<add> expect: /\bSyntaxError: Invalid regular expression\:/ },
<ide> // invalid RegExp modifiers are a special case of syntax error,
<ide> // should throw (GH-4012)
<ide> { client: client_unix, send: 'new RegExp("foo", "wrong modifier");',
<del> expect: /^SyntaxError: Invalid flags supplied to RegExp constructor/ },
<add> expect: /\bSyntaxError: Invalid flags supplied to RegExp constructor/ },
<ide> // strict mode syntax errors should be caught (GH-5178)
<ide> { client: client_unix, send: '(function() { "use strict"; return 0755; })()',
<del> expect: /^SyntaxError: Octal literals are not allowed in strict mode/ },
<add> expect: /\bSyntaxError: Octal literals are not allowed in strict mode/ },
<ide> { client: client_unix, send: '(function(a, a, b) { "use strict"; return a + b + c; })()',
<del> expect: /^SyntaxError: Duplicate parameter name not allowed in this context/ },
<add> expect: /\bSyntaxError: Duplicate parameter name not allowed in this context/ },
<ide> { client: client_unix, send: '(function() { "use strict"; with (this) {} })()',
<del> expect: /^SyntaxError: Strict mode code may not include a with statement/ },
<add> expect: /\bSyntaxError: Strict mode code may not include a with statement/ },
<ide> { client: client_unix, send: '(function() { "use strict"; var x; delete x; })()',
<del> expect: /^SyntaxError: Delete of an unqualified identifier in strict mode/ },
<add> expect: /\bSyntaxError: Delete of an unqualified identifier in strict mode/ },
<ide> { client: client_unix, send: '(function() { "use strict"; eval = 17; })()',
<del> expect: /^SyntaxError: Unexpected eval or arguments in strict mode/ },
<add> expect: /\bSyntaxError: Unexpected eval or arguments in strict mode/ },
<ide> { client: client_unix, send: '(function() { "use strict"; if (true) function f() { } })()',
<del> expect: /^SyntaxError: In strict mode code, functions can only be declared at top level or inside a block./ },
<add> expect: /\bSyntaxError: In strict mode code, functions can only be declared at top level or inside a block./ },
<ide> // Named functions can be used:
<ide> { client: client_unix, send: 'function blah() { return 1; }',
<ide> expect: prompt_unix },
<ide> function error_test() {
<ide> expect: 'Invalid REPL keyword\n' + prompt_unix },
<ide> // fail when we are not inside a String and a line continuation is used
<ide> { client: client_unix, send: '[] \\',
<del> expect: /^SyntaxError: Invalid or unexpected token/ },
<add> expect: /\bSyntaxError: Invalid or unexpected token/ },
<ide> // do not fail when a String is created with line continuation
<ide> { client: client_unix, send: '\'the\\\nfourth\\\neye\'',
<ide> expect: prompt_multiline + prompt_multiline +
<ide> function error_test() {
<ide> // Illegal token is not recoverable outside string literal, RegExp literal,
<ide> // or block comment. https://github.com/nodejs/node/issues/3611
<ide> { client: client_unix, send: 'a = 3.5e',
<del> expect: /^SyntaxError: Invalid or unexpected token/ },
<add> expect: /\bSyntaxError: Invalid or unexpected token/ },
<ide> // Mitigate https://github.com/nodejs/node/issues/548
<ide> { client: client_unix, send: 'function name(){ return "node"; };name()',
<ide> expect: "'node'\n" + prompt_unix },
<ide> { client: client_unix, send: 'function name(){ return "nodejs"; };name()',
<ide> expect: "'nodejs'\n" + prompt_unix },
<add> // Avoid emitting repl:line-number for SyntaxError
<add> { client: client_unix, send: 'a = 3.5e',
<add> expect: /^(?!repl)/ },
<add> // Avoid emitting stack trace
<add> { client: client_unix, send: 'a = 3.5e',
<add> expect: /^(?!\s+at\s)/gm },
<ide> ]);
<ide> }
<ide> | 2 |
Python | Python | update punctuation rules | edec51b1b1999b09ccbbea6c836d47db498a40ef | <ide><path>spacy/lang/id/punctuation.py
<ide>
<ide> UNITS = merge_chars(_units)
<ide> CURRENCY = merge_chars(_currency)
<del>HTML_PREFIX = r'<(b|strong|i|em|p|span|div|br)\s?/>'
<del>HTML_SUFFIX = r'</(b|strong|i|em|p|span|div)>'
<add>HTML_PREFIX = r'<(b|strong|i|em|p|span|div|br)\s?/>|<a([^>]+)>'
<add>HTML_SUFFIX = r'</(b|strong|i|em|p|span|div|a)>'
<ide> MONTHS = merge_chars(_months)
<ide> LIST_CURRENCY = split_chars(_currency)
<ide>
<ide>
<del>_prefixes = TOKENIZER_PREFIXES + LIST_CURRENCY + [HTML_PREFIX] + ['[Kk]e-', '/', '—']
<add>_prefixes = TOKENIZER_PREFIXES + LIST_CURRENCY + [HTML_PREFIX] + ['/', '—']
<ide>
<del>_suffixes = TOKENIZER_SUFFIXES + [r'\-[Nn]ya', '—', '-'] + [
<add>_suffixes = TOKENIZER_SUFFIXES + [r'\-[Nn]ya', '-[KkMm]u' '-el', '[—-]'] + [
<ide> r'(?<=[0-9])(?:{c})'.format(c=CURRENCY),
<ide> r'(?<=[0-9])(?:{u})'.format(u=UNITS),
<ide> r'(?<=[0-9])%', | 1 |
Javascript | Javascript | convert arrow function to normal function | 1248616af0ad6cdfc7c5b1113e092ec5b3b484f6 | <ide><path>test/HotTestCases.test.js
<ide> describe("HotTestCases", () => {
<ide> const suite = describe(testName, function() {
<ide> this.timeout(10000);
<ide> });
<del> it(testName + " should compile", done => {
<add> it(testName + " should compile", function(done) {
<ide> this.timeout(10000);
<ide> const testDirectory = path.join(casesPath, category.name, testName);
<ide> const outputDirectory = path.join( | 1 |
Java | Java | switch defaultsockjsservice to constructor di | 36148b7cb1066b77b7849f9852d36d0fcf0f5db0 | <ide><path>spring-websocket/src/main/java/org/springframework/sockjs/server/AbstractServerSockJsSession.java
<ide> public synchronized void sendHeartbeat() throws Exception {
<ide> }
<ide>
<ide> protected void scheduleHeartbeat() {
<del> Assert.notNull(getSockJsConfig().getHeartbeatScheduler(), "heartbeatScheduler not configured");
<add> Assert.notNull(getSockJsConfig().getTaskScheduler(), "heartbeatScheduler not configured");
<ide> cancelHeartbeat();
<ide> if (!isActive()) {
<ide> return;
<ide> }
<ide> Date time = new Date(System.currentTimeMillis() + getSockJsConfig().getHeartbeatTime());
<del> this.heartbeatTask = getSockJsConfig().getHeartbeatScheduler().schedule(new Runnable() {
<add> this.heartbeatTask = getSockJsConfig().getTaskScheduler().schedule(new Runnable() {
<ide> public void run() {
<ide> try {
<ide> sendHeartbeat();
<ide><path>spring-websocket/src/main/java/org/springframework/sockjs/server/AbstractSockJsService.java
<ide>
<ide> import org.apache.commons.logging.Log;
<ide> import org.apache.commons.logging.LogFactory;
<del>import org.springframework.beans.factory.DisposableBean;
<del>import org.springframework.beans.factory.InitializingBean;
<ide> import org.springframework.http.HttpMethod;
<ide> import org.springframework.http.HttpStatus;
<ide> import org.springframework.http.MediaType;
<ide> import org.springframework.http.server.ServerHttpRequest;
<ide> import org.springframework.http.server.ServerHttpResponse;
<ide> import org.springframework.scheduling.TaskScheduler;
<del>import org.springframework.scheduling.concurrent.ThreadPoolTaskScheduler;
<ide> import org.springframework.util.Assert;
<ide> import org.springframework.util.CollectionUtils;
<ide> import org.springframework.util.DigestUtils;
<ide> * @author Rossen Stoyanchev
<ide> * @since 4.0
<ide> */
<del>public abstract class AbstractSockJsService
<del> implements SockJsService, SockJsConfiguration, InitializingBean, DisposableBean {
<add>public abstract class AbstractSockJsService implements SockJsService, SockJsConfiguration {
<ide>
<ide> protected final Log logger = LogFactory.getLog(getClass());
<ide>
<ide>
<ide> private boolean webSocketsEnabled = true;
<ide>
<del> private final TaskSchedulerHolder heartbeatSchedulerHolder;
<add> private final TaskScheduler taskScheduler;
<ide>
<ide>
<ide>
<del> public AbstractSockJsService() {
<del> this.heartbeatSchedulerHolder = new TaskSchedulerHolder("SockJs-heartbeat-");
<del> }
<del>
<del> public AbstractSockJsService(TaskScheduler heartbeatScheduler) {
<del> Assert.notNull(heartbeatScheduler, "heartbeatScheduler is required");
<del> this.heartbeatSchedulerHolder = new TaskSchedulerHolder(heartbeatScheduler);
<add> public AbstractSockJsService(TaskScheduler scheduler) {
<add> Assert.notNull(scheduler, "scheduler is required");
<add> this.taskScheduler = scheduler;
<ide> }
<ide>
<ide> /**
<ide> public long getHeartbeatTime() {
<ide> return this.heartbeatTime;
<ide> }
<ide>
<del> public TaskScheduler getHeartbeatScheduler() {
<del> return this.heartbeatSchedulerHolder.getScheduler();
<add> public TaskScheduler getTaskScheduler() {
<add> return this.taskScheduler;
<ide> }
<ide>
<ide> /**
<ide> public boolean isWebSocketEnabled() {
<ide> return this.webSocketsEnabled;
<ide> }
<ide>
<del> @Override
<del> public void afterPropertiesSet() throws Exception {
<del> this.heartbeatSchedulerHolder.initialize();
<del> }
<del>
<del> @Override
<del> public void destroy() throws Exception {
<del> this.heartbeatSchedulerHolder.destroy();
<del> }
<del>
<ide> /**
<ide> * TODO
<ide> *
<ide> public void handle(ServerHttpRequest request, ServerHttpResponse response) throw
<ide> }
<ide> };
<ide>
<del>
<del> /**
<del> * Holds an externally provided or an internally managed TaskScheduler. Provides
<del> * initialize and destroy methods have no effect if the scheduler is externally
<del> * managed.
<del> */
<del> protected static class TaskSchedulerHolder {
<del>
<del> private final TaskScheduler taskScheduler;
<del>
<del> private final boolean isDefaultTaskScheduler;
<del>
<del> public TaskSchedulerHolder(TaskScheduler taskScheduler) {
<del> Assert.notNull(taskScheduler, "taskScheduler is required");
<del> this.taskScheduler = taskScheduler;
<del> this.isDefaultTaskScheduler = false;
<del> }
<del>
<del> public TaskSchedulerHolder(String threadNamePrefix) {
<del> ThreadPoolTaskScheduler scheduler = new ThreadPoolTaskScheduler();
<del> scheduler.setThreadNamePrefix(threadNamePrefix);
<del> this.taskScheduler = scheduler;
<del> this.isDefaultTaskScheduler = true;
<del> }
<del>
<del> public TaskScheduler getScheduler() {
<del> return this.taskScheduler;
<del> }
<del>
<del> public void initialize() {
<del> if (this.isDefaultTaskScheduler) {
<del> ((ThreadPoolTaskScheduler) this.taskScheduler).afterPropertiesSet();
<del> }
<del> }
<del>
<del> public void destroy() {
<del> if (this.isDefaultTaskScheduler) {
<del> ((ThreadPoolTaskScheduler) this.taskScheduler).shutdown();
<del> }
<del> }
<del> }
<del>
<ide> }
<ide><path>spring-websocket/src/main/java/org/springframework/sockjs/server/SockJsConfiguration.java
<ide> public interface SockJsConfiguration {
<ide> public long getHeartbeatTime();
<ide>
<ide> /**
<del> * A scheduler instance to use for scheduling heartbeat frames.
<del> * <p>
<del> * By default a {@link ThreadPoolTaskScheduler} with default settings is used.
<add> * A scheduler instance to use for scheduling heart-beat messages.
<ide> */
<del> public TaskScheduler getHeartbeatScheduler();
<add> public TaskScheduler getTaskScheduler();
<ide>
<ide> }
<ide><path>spring-websocket/src/main/java/org/springframework/sockjs/server/support/DefaultSockJsService.java
<ide> package org.springframework.sockjs.server.support;
<ide>
<ide> import java.util.Arrays;
<add>import java.util.Collection;
<add>import java.util.Collections;
<ide> import java.util.HashMap;
<add>import java.util.HashSet;
<ide> import java.util.List;
<ide> import java.util.Map;
<add>import java.util.Set;
<ide> import java.util.concurrent.ConcurrentHashMap;
<add>import java.util.concurrent.ScheduledFuture;
<ide>
<ide> import org.springframework.http.Cookie;
<ide> import org.springframework.http.HttpMethod;
<ide> import org.springframework.sockjs.server.transport.XhrPollingTransportHandler;
<ide> import org.springframework.sockjs.server.transport.XhrStreamingTransportHandler;
<ide> import org.springframework.sockjs.server.transport.XhrTransportHandler;
<del>import org.springframework.util.Assert;
<add>import org.springframework.util.CollectionUtils;
<ide> import org.springframework.websocket.HandlerProvider;
<ide> import org.springframework.websocket.WebSocketHandler;
<ide> import org.springframework.websocket.server.DefaultHandshakeHandler;
<ide> public class DefaultSockJsService extends AbstractSockJsService {
<ide>
<ide> private final Map<TransportType, TransportHandler> transportHandlers = new HashMap<TransportType, TransportHandler>();
<ide>
<del> private final Map<TransportType, TransportHandler> transportHandlerOverrides = new HashMap<TransportType, TransportHandler>();
<del>
<del> private TaskSchedulerHolder sessionTimeoutSchedulerHolder;
<del>
<ide> private final Map<String, AbstractSockJsSession> sessions = new ConcurrentHashMap<String, AbstractSockJsSession>();
<ide>
<add> private ScheduledFuture sessionCleanupTask;
<ide>
<del> public DefaultSockJsService() {
<del> this.sessionTimeoutSchedulerHolder = new TaskSchedulerHolder("SockJs-sessionTimeout-");
<del> }
<ide>
<del> public DefaultSockJsService(TaskScheduler heartbeatScheduler, TaskScheduler sessionTimeoutScheduler) {
<del> Assert.notNull(sessionTimeoutScheduler, "sessionTimeoutScheduler is required");
<del> this.sessionTimeoutSchedulerHolder = new TaskSchedulerHolder(sessionTimeoutScheduler);
<add> public DefaultSockJsService(TaskScheduler taskScheduler) {
<add> this(taskScheduler, null);
<ide> }
<ide>
<del> public void setTransportHandlers(TransportHandler... handlers) {
<del> this.transportHandlers.clear();
<del> for (TransportHandler handler : handlers) {
<del> this.transportHandlers.put(handler.getTransportType(), handler);
<del> }
<del> }
<add> public DefaultSockJsService(TaskScheduler taskScheduler, Set<TransportHandler> transportHandlers,
<add> TransportHandler... transportHandlerOverrides) {
<ide>
<del> public void setTransportHandlerOverrides(TransportHandler... handlers) {
<del> this.transportHandlerOverrides.clear();
<del> for (TransportHandler handler : handlers) {
<del> this.transportHandlerOverrides.put(handler.getTransportType(), handler);
<del> }
<del> }
<add> super(taskScheduler);
<ide>
<add> transportHandlers = CollectionUtils.isEmpty(transportHandlers) ? getDefaultTransportHandlers() : transportHandlers;
<add> addTransportHandlers(transportHandlers);
<add> addTransportHandlers(Arrays.asList(transportHandlerOverrides));
<add> }
<ide>
<del> @Override
<del> public void afterPropertiesSet() throws Exception {
<del>
<del> super.afterPropertiesSet();
<del>
<del> if (this.transportHandlers.isEmpty()) {
<del> if (isWebSocketEnabled() && (this.transportHandlerOverrides.get(TransportType.WEBSOCKET) == null)) {
<del> this.transportHandlers.put(TransportType.WEBSOCKET,
<del> new WebSocketTransportHandler(new DefaultHandshakeHandler()));
<add> protected Set<TransportHandler> getDefaultTransportHandlers() {
<add> Set<TransportHandler> result = new HashSet<TransportHandler>();
<add> result.add(new XhrPollingTransportHandler());
<add> result.add(new XhrTransportHandler());
<add> result.add(new JsonpPollingTransportHandler());
<add> result.add(new JsonpTransportHandler());
<add> result.add(new XhrStreamingTransportHandler());
<add> result.add(new EventSourceTransportHandler());
<add> result.add(new HtmlFileTransportHandler());
<add> if (isWebSocketEnabled()) {
<add> try {
<add> result.add(new WebSocketTransportHandler(new DefaultHandshakeHandler()));
<ide> }
<del> this.transportHandlers.put(TransportType.XHR, new XhrPollingTransportHandler());
<del> this.transportHandlers.put(TransportType.XHR_SEND, new XhrTransportHandler());
<del> this.transportHandlers.put(TransportType.JSONP, new JsonpPollingTransportHandler());
<del> this.transportHandlers.put(TransportType.JSONP_SEND, new JsonpTransportHandler());
<del> this.transportHandlers.put(TransportType.XHR_STREAMING, new XhrStreamingTransportHandler());
<del> this.transportHandlers.put(TransportType.EVENT_SOURCE, new EventSourceTransportHandler());
<del> this.transportHandlers.put(TransportType.HTML_FILE, new HtmlFileTransportHandler());
<del> }
<del>
<del> if (!this.transportHandlerOverrides.isEmpty()) {
<del> for (TransportHandler transportHandler : this.transportHandlerOverrides.values()) {
<del> this.transportHandlers.put(transportHandler.getTransportType(), transportHandler);
<add> catch (Exception ex) {
<add> if (logger.isWarnEnabled()) {
<add> logger.warn("Failed to add default WebSocketTransportHandler: " + ex.getMessage());
<add> }
<ide> }
<ide> }
<add> return result;
<add> }
<ide>
<del> for (TransportHandler h : this.transportHandlers.values()) {
<del> if (h instanceof ConfigurableTransportHandler) {
<del> ((ConfigurableTransportHandler) h).setSockJsConfiguration(this);
<add> protected void addTransportHandlers(Collection<TransportHandler> handlers) {
<add> for (TransportHandler handler : handlers) {
<add> if (handler instanceof ConfigurableTransportHandler) {
<add> ((ConfigurableTransportHandler) handler).setSockJsConfiguration(this);
<ide> }
<add> this.transportHandlers.put(handler.getTransportType(), handler);
<ide> }
<del>
<del> this.sessionTimeoutSchedulerHolder.initialize();
<del>
<del> this.sessionTimeoutSchedulerHolder.getScheduler().scheduleAtFixedRate(new Runnable() {
<del> public void run() {
<del> try {
<del> int count = sessions.size();
<del> if (logger.isTraceEnabled() && (count != 0)) {
<del> logger.trace("Checking " + count + " session(s) for timeouts [" + getName() + "]");
<del> }
<del> for (AbstractSockJsSession session : sessions.values()) {
<del> if (session.getTimeSinceLastActive() > getDisconnectDelay()) {
<del> if (logger.isTraceEnabled()) {
<del> logger.trace("Removing " + session + " for [" + getName() + "]");
<del> }
<del> session.close();
<del> sessions.remove(session.getId());
<del> }
<del> }
<del> if (logger.isTraceEnabled() && (count != 0)) {
<del> logger.trace(sessions.size() + " remaining session(s) [" + getName() + "]");
<del> }
<del> }
<del> catch (Throwable t) {
<del> logger.error("Failed to complete session timeout checks for [" + getName() + "]", t);
<del> }
<del> }
<del> }, getDisconnectDelay());
<ide> }
<ide>
<del> @Override
<del> public void destroy() throws Exception {
<del> super.destroy();
<del> this.sessionTimeoutSchedulerHolder.destroy();
<add> public Map<TransportType, TransportHandler> getTransportHandlers() {
<add> return Collections.unmodifiableMap(this.transportHandlers);
<ide> }
<ide>
<ide> @Override
<ide> public AbstractSockJsSession getSockJsSession(String sessionId, HandlerProvider<
<ide> if (session != null) {
<ide> return session;
<ide> }
<add> if (this.sessionCleanupTask == null) {
<add> scheduleSessionTask();
<add> }
<ide> logger.debug("Creating new session with session id \"" + sessionId + "\"");
<ide> session = (AbstractSockJsSession) sessionFactory.createSession(sessionId, handler);
<ide> this.sessions.put(sessionId, session);
<ide> public AbstractSockJsSession getSockJsSession(String sessionId, HandlerProvider<
<ide> return null;
<ide> }
<ide>
<add> private void scheduleSessionTask() {
<add> this.sessionCleanupTask = getTaskScheduler().scheduleAtFixedRate(new Runnable() {
<add> public void run() {
<add> try {
<add> int count = sessions.size();
<add> if (logger.isTraceEnabled() && (count != 0)) {
<add> logger.trace("Checking " + count + " session(s) for timeouts [" + getName() + "]");
<add> }
<add> for (AbstractSockJsSession session : sessions.values()) {
<add> if (session.getTimeSinceLastActive() > getDisconnectDelay()) {
<add> if (logger.isTraceEnabled()) {
<add> logger.trace("Removing " + session + " for [" + getName() + "]");
<add> }
<add> session.close();
<add> sessions.remove(session.getId());
<add> }
<add> }
<add> if (logger.isTraceEnabled() && (count != 0)) {
<add> logger.trace(sessions.size() + " remaining session(s) [" + getName() + "]");
<add> }
<add> }
<add> catch (Throwable t) {
<add> logger.error("Failed to complete session timeout checks for [" + getName() + "]", t);
<add> }
<add> }
<add> }, getDisconnectDelay());
<add> }
<add>
<ide> }
<ide><path>spring-websocket/src/main/java/org/springframework/websocket/client/WebSocketConnectionManager.java
<ide> */
<ide> package org.springframework.websocket.client;
<ide>
<add>import java.util.ArrayList;
<ide> import java.util.List;
<ide>
<ide> import org.springframework.http.HttpHeaders;
<add>import org.springframework.util.CollectionUtils;
<ide> import org.springframework.websocket.HandlerProvider;
<ide> import org.springframework.websocket.WebSocketHandler;
<ide> import org.springframework.websocket.WebSocketSession;
<ide> public class WebSocketConnectionManager extends AbstractWebSocketConnectionManag
<ide>
<ide> private WebSocketSession webSocketSession;
<ide>
<del> private List<String> subProtocols;
<add> private final List<String> subProtocols = new ArrayList<String>();
<ide>
<ide>
<ide> public WebSocketConnectionManager(WebSocketClient webSocketClient,
<ide> public WebSocketConnectionManager(WebSocketClient webSocketClient,
<ide> }
<ide>
<ide> public void setSubProtocols(List<String> subProtocols) {
<del> this.subProtocols = subProtocols;
<add> this.subProtocols.clear();
<add> if (!CollectionUtils.isEmpty(subProtocols)) {
<add> this.subProtocols.addAll(subProtocols);
<add> }
<ide> }
<ide>
<ide> public List<String> getSubProtocols() {
<ide><path>spring-websocket/src/test/java/org/springframework/sockjs/server/support/DefaultSockJsServiceTests.java
<add>/*
<add> * Copyright 2002-2013 the original author or authors.
<add> *
<add> * Licensed under the Apache License, Version 2.0 (the "License");
<add> * you may not use this file except in compliance with the License.
<add> * You may obtain a copy of the License at
<add> *
<add> * http://www.apache.org/licenses/LICENSE-2.0
<add> *
<add> * Unless required by applicable law or agreed to in writing, software
<add> * distributed under the License is distributed on an "AS IS" BASIS,
<add> * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
<add> * See the License for the specific language governing permissions and
<add> * limitations under the License.
<add> */
<add>
<add>package org.springframework.sockjs.server.support;
<add>
<add>import java.util.Map;
<add>
<add>import org.junit.Test;
<add>import org.springframework.scheduling.concurrent.ThreadPoolTaskScheduler;
<add>import org.springframework.sockjs.server.TransportHandler;
<add>import org.springframework.sockjs.server.TransportType;
<add>
<add>import static org.junit.Assert.*;
<add>
<add>
<add>/**
<add> * Test fixture for {@link DefaultSockJsService}.
<add> *
<add> * @author Rossen Stoyanchev
<add> */
<add>public class DefaultSockJsServiceTests {
<add>
<add>
<add> @Test
<add> public void testDefaultTransportHandlers() {
<add>
<add> DefaultSockJsService sockJsService = new DefaultSockJsService(new ThreadPoolTaskScheduler());
<add> Map<TransportType, TransportHandler> handlers = sockJsService.getTransportHandlers();
<add>
<add> assertEquals(8, handlers.size());
<add> assertNotNull(handlers.get(TransportType.WEBSOCKET));
<add> assertNotNull(handlers.get(TransportType.XHR));
<add> assertNotNull(handlers.get(TransportType.XHR_SEND));
<add> assertNotNull(handlers.get(TransportType.XHR_STREAMING));
<add> assertNotNull(handlers.get(TransportType.JSONP));
<add> assertNotNull(handlers.get(TransportType.JSONP_SEND));
<add> assertNotNull(handlers.get(TransportType.HTML_FILE));
<add> assertNotNull(handlers.get(TransportType.EVENT_SOURCE));
<add> }
<add>
<add>
<add>} | 6 |
Javascript | Javascript | remove dataset while hovered | f191f2f5f9a1e1e1a95f1722b41d168244b1d554 | <ide><path>src/core/core.controller.js
<ide> class Chart {
<ide> hidden: null, // See isDatasetVisible() comment
<ide> xAxisID: null,
<ide> yAxisID: null,
<del> order: dataset.order || 0,
<add> order: dataset && dataset.order || 0,
<ide> index: datasetIndex,
<ide> _dataset: dataset,
<ide> _parsed: [],
<ide> class Chart {
<ide> const me = this;
<ide> const meta = me._metasets && me._metasets[datasetIndex];
<ide>
<del> if (meta) {
<add> if (meta && meta.controller) {
<ide> meta.controller._destroy();
<ide> delete me._metasets[datasetIndex];
<ide> }
<ide> class Chart {
<ide>
<ide> for (i = 0, ilen = items.length; i < ilen; ++i) {
<ide> item = items[i];
<del> if (item) {
<del> this.getDatasetMeta(item.datasetIndex).controller[prefix + 'HoverStyle'](item.element, item.datasetIndex, item.index);
<add> const controller = item && this.getDatasetMeta(item.datasetIndex).controller;
<add> if (controller) {
<add> controller[prefix + 'HoverStyle'](item.element, item.datasetIndex, item.index);
<ide> }
<ide> }
<ide> } | 1 |
Python | Python | start the timeouthandler thread on demand | 15c34855a6177a5d9bb2497b8e8eef9ddb59272e | <ide><path>celery/concurrency/base.py
<ide> def start(self):
<ide>
<ide> def apply_async(self, target, args=None, kwargs=None, callbacks=None,
<ide> errbacks=None, accept_callback=None, timeout_callback=None,
<del> **compat):
<add> soft_timeout=None, timeout=None, **compat):
<ide> """Equivalent of the :func:`apply` built-in function.
<ide>
<ide> All `callbacks` and `errbacks` should complete immediately since
<ide> def apply_async(self, target, args=None, kwargs=None, callbacks=None,
<ide> accept_callback=accept_callback,
<ide> timeout_callback=timeout_callback,
<ide> error_callback=on_worker_error,
<del> waitforslot=self.putlocks)
<add> waitforslot=self.putlocks,
<add> soft_timeout=soft_timeout,
<add> timeout=timeout)
<ide>
<ide> def on_ready(self, callbacks, errbacks, ret_value):
<ide> """What to do when a worker task is ready and its return value has
<ide><path>celery/concurrency/processes/__init__.py
<ide> def on_terminate(self):
<ide> self._pool.terminate()
<ide> self._pool = None
<ide>
<del> def apply_async(self, target, args=None, kwargs=None, callbacks=None,
<del> errbacks=None, accept_callback=None, timeout_callback=None,
<del> soft_timeout=None, timeout=None, **compat):
<del> """Equivalent of the :func:``apply`` built-in function.
<del>
<del> All ``callbacks`` and ``errbacks`` should complete immediately since
<del> otherwise the thread which handles the result will get blocked.
<del>
<del> """
<del> args = args or []
<del> kwargs = kwargs or {}
<del> callbacks = callbacks or []
<del> errbacks = errbacks or []
<del>
<del> on_ready = curry(self.on_ready, callbacks, errbacks)
<del> on_worker_error = curry(self.on_worker_error, errbacks)
<del>
<del> self.logger.debug("TaskPool: Apply %s (args:%s kwargs:%s)" % (
<del> target, args, kwargs))
<del>
<del> return self._pool.apply_async(target, args, kwargs,
<del> callback=on_ready,
<del> accept_callback=accept_callback,
<del> timeout_callback=timeout_callback,
<del> error_callback=on_worker_error,
<del> waitforslot=self.putlocks,
<del> soft_timeout=soft_timeout,
<del> timeout=timeout)
<del>
<del> def on_worker_error(self, errbacks, exc):
<del> einfo = ExceptionInfo((exc.__class__, exc, None))
<del> [errback(einfo) for errback in errbacks]
<del>
<del> def on_ready(self, callbacks, errbacks, ret_value):
<del> """What to do when a worker task is ready and its return value has
<del> been collected."""
<del>
<del> if isinstance(ret_value, ExceptionInfo):
<del> if isinstance(ret_value.exception, (
<del> SystemExit, KeyboardInterrupt)):
<del> raise ret_value.exception
<del> [self.safe_apply_callback(errback, ret_value)
<del> for errback in errbacks]
<del> else:
<del> [self.safe_apply_callback(callback, ret_value)
<del> for callback in callbacks]
<del>
<del> def safe_apply_callback(self, fun, *args):
<del> try:
<del> fun(*args)
<del> except:
<del> self.logger.error("Pool callback raised exception: %s" % (
<del> traceback.format_exc(), ))
<del>
<ide> def terminate_job(self, pid, signal=None):
<ide> os.kill(pid, signal or _signal.SIGTERM)
<ide>
<ide><path>celery/concurrency/processes/pool.py
<ide> import collections
<ide> import time
<ide> import signal
<add>import warnings
<ide>
<ide> from multiprocessing import Process, cpu_count, TimeoutError
<ide> from multiprocessing import util
<ide> def body(self):
<ide>
<ide> class TimeoutHandler(PoolThread):
<ide>
<del> def __init__(self, processes, cache, t_soft, t_hard, putlock):
<add> def __init__(self, processes, cache, t_soft, t_hard):
<ide> self.processes = processes
<ide> self.cache = cache
<ide> self.t_soft = t_soft
<ide> def __init__(self, processes, cache, t_soft, t_hard, putlock):
<ide> def body(self):
<ide> processes = self.processes
<ide> cache = self.cache
<del> putlock = self.putlock
<ide> t_hard, t_soft = self.t_hard, self.t_soft
<ide> dirty = set()
<ide>
<ide> def __init__(self, processes=None, initializer=None, initargs=(),
<ide> self._initializer = initializer
<ide> self._initargs = initargs
<ide>
<del> if self.soft_timeout and SIG_SOFT_TIMEOUT is None:
<del> raise NotImplementedError("Soft timeouts not supported: "
<del> "Your platform does not have the SIGUSR1 signal.")
<add> if soft_timeout and SIG_SOFT_TIMEOUT is None:
<add> warnings.warn(UserWarning("Soft timeouts are not supported: "
<add> "on this platform: It does not have the SIGUSR1 signal."))
<add> soft_timeout = None
<ide>
<ide> if processes is None:
<ide> try:
<ide> def __init__(self, processes=None, initializer=None, initargs=(),
<ide> self._task_handler.start()
<ide>
<ide> # Thread killing timedout jobs.
<add> self._timeout_handler = None
<add> self._timeout_handler_mutex = threading.Lock()
<ide> if self.timeout is not None or self.soft_timeout is not None:
<del> self._timeout_handler = self.TimeoutHandler(
<del> self._pool, self._cache,
<del> self.soft_timeout, self.timeout, self._putlock)
<del> self._timeout_handler.start()
<del> else:
<del> self._timeout_handler = None
<add> self._start_timeout_handler()
<ide>
<ide> # Thread processing results in the outqueue.
<ide> self._result_handler = self.ResultHandler(self._outqueue,
<ide> def _poll_result(timeout):
<ide> return False, None
<ide> self._poll_result = _poll_result
<ide>
<add> def _start_timeout_handler(self):
<add> # ensure more than one thread does not start the timeout handler
<add> # thread at once.
<add> self._timeout_handler_mutex.acquire()
<add> try:
<add> if self._timeout_handler is None:
<add> self._timeout_handler = self.TimeoutHandler(
<add> self._pool, self._cache,
<add> self.soft_timeout, self.timeout)
<add> self._timeout_handler.start()
<add> finally:
<add> self._timeout_handler_mutex.release()
<add>
<ide> def apply(self, func, args=(), kwds={}):
<ide> '''
<ide> Equivalent of `apply()` builtin
<ide> def apply_async(self, func, args=(), kwds={},
<ide>
<ide> '''
<ide> assert self._state == RUN
<add> if soft_timeout and SIG_SOFT_TIMEOUT is None:
<add> warnings.warn(UserWarning("Soft timeouts are not supported: "
<add> "on this platform: It does not have the SIGUSR1 signal."))
<add> soft_timeout = None
<ide> result = ApplyResult(self._cache, callback,
<ide> accept_callback, timeout_callback,
<ide> error_callback, soft_timeout, timeout)
<ide> def apply_async(self, func, args=(), kwds={},
<ide> self._putlock.acquire()
<ide> if self._state != RUN:
<ide> return
<add> if timeout or soft_timeout:
<add> # start the timeout handler thread when required.
<add> self._start_timeout_handler()
<ide> self._taskqueue.put(([(result._job, None, func, args, kwds)], None))
<ide> return result
<ide>
<ide><path>celery/tests/test_worker/test_worker_job.py
<ide> def error(self, msg, *args, **kwargs):
<ide>
<ide> tw = TaskRequest(mytask.name, gen_unique_id(), [1], {"f": "x"})
<ide> tw.logger = MockLogger()
<del> tw.on_timeout(soft=True)
<del> self.assertIn("Soft time limit exceeded", tw.logger.warnings[0])
<del> tw.on_timeout(soft=False)
<del> self.assertIn("Hard time limit exceeded", tw.logger.errors[0])
<add> tw.on_timeout(soft=True, timeout=1337)
<add> self.assertIn("Soft time limit (1337s) exceeded",
<add> tw.logger.warnings[0])
<add> tw.on_timeout(soft=False, timeout=1337)
<add> self.assertIn("Hard time limit (1337s) exceeded", tw.logger.errors[0])
<ide> self.assertEqual(mytask.backend.get_status(tw.task_id),
<ide> states.FAILURE)
<ide>
<ide> def error(self, msg, *args, **kwargs):
<ide> tw.logger = MockLogger()
<ide> finally:
<ide> mytask.ignore_result = False
<del> tw.on_timeout(soft=True)
<add> tw.on_timeout(soft=True, timeout=1336)
<ide> self.assertEqual(mytask.backend.get_status(tw.task_id),
<ide> states.PENDING)
<ide>
<ide><path>celery/worker/__init__.py
<ide> def _shutdown(self, warm=True):
<ide> stop = getattr(component, "terminate", stop)
<ide> stop()
<ide>
<add> self.priority_timer.stop()
<ide> self.consumer.close_connection()
<ide> self._state = self.TERMINATE
<ide>
<ide><path>celery/worker/job.py
<ide> def on_timeout(self, soft, timeout):
<ide> """Handler called if the task times out."""
<ide> state.task_ready(self)
<ide> if soft:
<del> self.logger.warning("Soft time limit (%s) exceeded for %s[%s]" % (
<add> self.logger.warning("Soft time limit (%ss) exceeded for %s[%s]" % (
<ide> timeout, self.task_name, self.task_id))
<ide> exc = SoftTimeLimitExceeded(timeout)
<ide> else:
<del> self.logger.error("Hard time limit (%s) exceeded for %s[%s]" % (
<add> self.logger.error("Hard time limit (%ss) exceeded for %s[%s]" % (
<ide> timeout, self.task_name, self.task_id))
<ide> exc = TimeLimitExceeded(timeout)
<ide> | 6 |
Text | Text | add v3.16.0-beta.2 to changelog | 7f6cd8f743a7cc2f762a69f44455a7f169ac7bac | <ide><path>CHANGELOG.md
<ide> # Ember Changelog
<ide>
<add>### v3.26.0-beta.2 (February 15, 2021)
<add>
<add>- [#19387](https://github.com/emberjs/ember.js/pull/19387) [BUGFIX] LinkTo with incomplete model failing in rendering tests
<add>- [#19395](https://github.com/emberjs/ember.js/pull/19395) [BUGFIX] Only return empty href when LinkTo href generation throws error
<add>- [#19396](https://github.com/emberjs/ember.js/pull/19396) [BUGFIX] Revert deprecation of htmlSafe and isHTMLSafe
<add>- [#19397](https://github.com/emberjs/ember.js/pull/19397) [BUGFIX] Force building Ember bundles when `targets.node` is defined
<add>
<ide> ### v3.26.0-beta.1 (February 08, 2021)
<ide>
<ide> - [#19255](https://github.com/emberjs/ember.js/pull/19255) [DEPRECATION] Deprecate transition methods of controller and route per [RFC #674](https://github.com/emberjs/rfcs/blob/master/text/0674-deprecate-transition-methods-of-controller-and-route.md). | 1 |
Mixed | Ruby | use different namespace for proxy calls | 81519dec1add5ee5d93cc24239283ca56379eb9a | <ide><path>activemodel/CHANGELOG.md
<add>* Use different cache namespace for proxy calls
<ide>
<add> Models can currently have different attribute bodies for the same method
<add> names, leading to conflicts. Adding a new namespace `:active_model_proxy`
<add> fixes the issue.
<add>
<add> *Chris Salzberg*
<ide>
<ide> Please check [7-0-stable](https://github.com/rails/rails/blob/7-0-stable/activemodel/CHANGELOG.md) for previous changes.
<ide><path>activemodel/lib/active_model/attribute_methods.rb
<ide> def define_attribute_method(attr_name, _owner: generated_attribute_methods)
<ide> if respond_to?(generate_method, true)
<ide> send(generate_method, attr_name.to_s, owner: owner)
<ide> else
<del> define_proxy_call(owner, method_name, matcher.target, matcher.parameters, attr_name.to_s, namespace: :active_model)
<add> define_proxy_call(owner, method_name, matcher.target, matcher.parameters, attr_name.to_s, namespace: :active_model_proxy)
<ide> end
<ide> end
<ide> end
<ide><path>activemodel/test/cases/attributes_test.rb
<ide> class GrandchildModelForAttributesTest < ChildModelForAttributesTest
<ide> attribute :string_field, default: "default string"
<ide> end
<ide>
<add> class ModelWithGeneratedAttributeMethods
<add> include ActiveModel::Attributes
<add>
<add> attribute :foo
<add> end
<add>
<add> class ModelWithProxiedAttributeMethods
<add> include ActiveModel::AttributeMethods
<add>
<add> attribute_method_suffix "="
<add>
<add> define_attribute_method(:foo)
<add>
<add> def attribute=(_, _)
<add> end
<add> end
<add>
<add> test "models that proxy attributes do not conflict with models with generated methods" do
<add> ModelWithGeneratedAttributeMethods.new
<add>
<add> model = ModelWithProxiedAttributeMethods.new
<add>
<add> assert_nothing_raised do
<add> model.foo = "foo"
<add> end
<add> end
<add>
<ide> test "properties assignment" do
<ide> data = ModelForAttributesTest.new(
<ide> integer_field: "2.3", | 3 |
Ruby | Ruby | streamline loading casks from api | 1e536217b2cb4395f1ebe5c0ba5c8bf1db4e7926 | <ide><path>Library/Homebrew/cask/cask.rb
<ide> require "cask/dsl"
<ide> require "cask/metadata"
<ide> require "searchable"
<del>require "api"
<ide>
<ide> module Cask
<ide> # An instance of a cask.
<ide> def outdated_versions(greedy: false, greedy_latest: false, greedy_auto_updates:
<ide> # special case: tap version is not available
<ide> return [] if version.nil?
<ide>
<del> latest_version = if Homebrew::EnvConfig.install_from_api? &&
<del> (latest_cask_version = Homebrew::API::Versions.latest_cask_version(token))
<del> DSL::Version.new latest_cask_version.to_s
<del> else
<del> version
<del> end
<del>
<del> if latest_version.latest?
<add> if version.latest?
<ide> return versions if (greedy || greedy_latest) && outdated_download_sha?
<ide>
<ide> return []
<ide> def outdated_versions(greedy: false, greedy_latest: false, greedy_auto_updates:
<ide> current = installed.last
<ide>
<ide> # not outdated unless there is a different version on tap
<del> return [] if current == latest_version
<add> return [] if current == version
<ide>
<ide> # collect all installed versions that are different than tap version and return them
<del> installed.reject { |v| v == latest_version }
<add> installed.reject { |v| v == version }
<ide> end
<ide>
<ide> def outdated_info(greedy, verbose, json, greedy_latest, greedy_auto_updates)
<ide><path>Library/Homebrew/cask/cask_loader.rb
<ide> def self.for(ref)
<ide> FromTapPathLoader,
<ide> FromPathLoader,
<ide> ].each do |loader_class|
<del> return loader_class.new(ref) if loader_class.can_load?(ref)
<add> next unless loader_class.can_load?(ref)
<add>
<add> if loader_class == FromTapLoader && Homebrew::EnvConfig.install_from_api? &&
<add> ref.start_with?("homebrew/cask/") && !Tap.fetch("homebrew/cask").installed? &&
<add> Homebrew::API::CaskSource.available?(ref)
<add> return FromContentLoader.new(Homebrew::API::CaskSource.fetch(ref))
<add> end
<add>
<add> return loader_class.new(ref)
<ide> end
<ide>
<ide> return FromTapPathLoader.new(default_path(ref)) if FromTapPathLoader.can_load?(default_path(ref))
<ide> def self.for(ref)
<ide> EOS
<ide> end
<ide>
<add> if Homebrew::EnvConfig.install_from_api? && Homebrew::API::CaskSource.available?(ref)
<add> return FromContentLoader.new(Homebrew::API::CaskSource.fetch(ref))
<add> end
<add>
<ide> possible_installed_cask = Cask.new(ref)
<ide> return FromPathLoader.new(possible_installed_cask.installed_caskfile) if possible_installed_cask.installed?
<ide>
<ide><path>Library/Homebrew/cask/caskroom.rb
<ide> def self.casks(config: nil)
<ide> begin
<ide> if (tap_path = CaskLoader.tap_paths(token).first)
<ide> CaskLoader::FromTapPathLoader.new(tap_path).load(config: config)
<del> elsif (caskroom_path = Pathname.glob(path.join(".metadata/*/*/*/*.rb")).first)
<add> elsif (caskroom_path = Pathname.glob(path.join(".metadata/*/*/*/*.rb")).first) &&
<add> (!Homebrew::EnvConfig.install_from_api? || !Homebrew::API::CaskSource.available?(token))
<ide> CaskLoader::FromPathLoader.new(caskroom_path).load(config: config)
<ide> else
<ide> CaskLoader.load(token, config: config)
<ide><path>Library/Homebrew/cli/named_args.rb
<ide> def to_formulae
<ide> # the formula and prints a warning unless `only` is specified.
<ide> sig {
<ide> params(
<del> only: T.nilable(Symbol),
<del> ignore_unavailable: T.nilable(T::Boolean),
<del> method: T.nilable(Symbol),
<del> uniq: T::Boolean,
<del> prefer_loading_from_api: T::Boolean,
<add> only: T.nilable(Symbol),
<add> ignore_unavailable: T.nilable(T::Boolean),
<add> method: T.nilable(Symbol),
<add> uniq: T::Boolean,
<ide> ).returns(T::Array[T.any(Formula, Keg, Cask::Cask)])
<ide> }
<del> def to_formulae_and_casks(only: parent&.only_formula_or_cask, ignore_unavailable: nil, method: nil, uniq: true,
<del> prefer_loading_from_api: false)
<add> def to_formulae_and_casks(only: parent&.only_formula_or_cask, ignore_unavailable: nil, method: nil, uniq: true)
<ide> @to_formulae_and_casks ||= {}
<ide> @to_formulae_and_casks[only] ||= downcased_unique_named.flat_map do |name|
<del> load_formula_or_cask(name, only: only, method: method, prefer_loading_from_api: prefer_loading_from_api)
<add> load_formula_or_cask(name, only: only, method: method)
<ide> rescue FormulaUnreadableError, FormulaClassUnavailableError,
<ide> TapFormulaUnreadableError, TapFormulaClassUnavailableError,
<ide> Cask::CaskUnreadableError
<ide> def to_formulae_and_casks_and_unavailable(only: parent&.only_formula_or_cask, me
<ide> end.uniq.freeze
<ide> end
<ide>
<del> def load_formula_or_cask(name, only: nil, method: nil, prefer_loading_from_api: false)
<add> def load_formula_or_cask(name, only: nil, method: nil)
<ide> unreadable_error = nil
<ide>
<ide> if only != :cask
<ide> def load_formula_or_cask(name, only: nil, method: nil, prefer_loading_from_api:
<ide> end
<ide>
<ide> if only != :formula
<del> if prefer_loading_from_api && Homebrew::EnvConfig.install_from_api? &&
<del> Homebrew::API::CaskSource.available?(name)
<del> contents = Homebrew::API::CaskSource.fetch(name)
<del> end
<del>
<ide> want_keg_like_cask = [:latest_kegs, :default_kegs, :kegs].include?(method)
<ide>
<ide> begin
<ide> config = Cask::Config.from_args(@parent) if @cask_options
<del> cask = Cask::CaskLoader.load(contents || name, config: config)
<add> cask = Cask::CaskLoader.load(name, config: config)
<ide>
<ide> if unreadable_error.present?
<ide> onoe <<~EOS
<ide><path>Library/Homebrew/cmd/install.rb
<ide> def install
<ide> end
<ide>
<ide> begin
<del> formulae, casks = args.named.to_formulae_and_casks(prefer_loading_from_api: true)
<add> formulae, casks = args.named.to_formulae_and_casks
<ide> .partition { |formula_or_cask| formula_or_cask.is_a?(Formula) }
<ide> rescue FormulaOrCaskUnavailableError, Cask::CaskUnavailableError => e
<ide> retry if Tap.install_default_cask_tap_if_necessary(force: args.cask?)
<ide><path>Library/Homebrew/cmd/upgrade.rb
<ide> def upgrade_outdated_formulae(formulae, args:)
<ide> def upgrade_outdated_casks(casks, args:)
<ide> return false if args.formula?
<ide>
<del> if Homebrew::EnvConfig.install_from_api?
<del> casks = casks.map do |cask|
<del> next cask if cask.tap.present? && cask.tap != "homebrew/cask"
<del> next cask unless Homebrew::API::CaskSource.available?(cask.token)
<del>
<del> Cask::CaskLoader.load Homebrew::API::CaskSource.fetch(cask.token)
<del> end
<del> end
<del>
<ide> Cask::Cmd::Upgrade.upgrade_casks(
<ide> *casks,
<ide> force: args.force?, | 6 |
Javascript | Javascript | increase default file size for large-file warning | 4a12354e9acd6d6464c91cfdc9a1699b985aa5cb | <ide><path>src/config-schema.js
<ide> const configSchema = {
<ide> warnOnLargeFileLimit: {
<ide> description: 'Warn before opening files larger than this number of megabytes.',
<ide> type: 'number',
<del> default: 20
<add> default: 40
<ide> }
<ide> }
<ide> }, | 1 |
Javascript | Javascript | apply suggestions from code review | 62aa54efbaa8e4100689e6ddd42e69bbecf99eca | <ide><path>client/src/components/Donation/components/DonateForm.js
<ide> class DonateForm extends Component {
<ide> this.amounts = amountsConfig;
<ide>
<ide> this.state = {
<add> ...defaultStateConfig,
<ide> processing: false,
<del> isDonating: this.props.isDonating,
<del> ...defaultStateConfig
<add> isDonating: this.props.isDonating
<ide> };
<ide>
<ide> this.getActiveDonationAmount = this.getActiveDonationAmount.bind(this);
<ide><path>client/src/components/Donation/components/DonateServicebotEmbed.js
<ide> export class DonationServicebotEmbed extends Component {
<ide> disableCoupon: true,
<ide> forceCard: true,
<ide> disableTiers: [
<del> 'Monthly $10 Donation - Unavailable',
<add> 'Monthly $10 Donation - Unavailable',
<ide> 'Monthly $3 Donation - Unavailable'
<ide> ],
<ide> card: {
<ide><path>client/src/pages/donation/settings.js
<ide> export class DonationSettingsPage extends Component {
<ide>
<ide> renderServicebotEmbed() {
<ide> const { currentSettingsEmail, hash } = this.state;
<del> if (!hash && !currentSettingsEmail) {
<add> if (!hash || !currentSettingsEmail) {
<ide> return null;
<ide> }
<ide> return (
<ide> export class DonationSettingsPage extends Component {
<ide> const { donationEmails } = this.props;
<ide> return (
<ide> <div>
<del> {uniq(donationEmails).map((email, index) => (
<del> <div key={email + '-' + index}>
<add> {uniq(donationEmails).map(email => (
<add> <div key={email}>
<ide> <Button
<ide> bsStyle='primary'
<ide> className='btn btn-block'
<ide> export class DonationSettingsPage extends Component {
<ide> return <Loader fullScreen={true} />;
<ide> }
<ide>
<del> if (!showLoading && !isSignedIn) {
<add> if (!isSignedIn) {
<ide> navigate(`${apiLocation}/signin?returnTo=donation/settings`);
<ide> return <Loader fullScreen={true} />;
<ide> }
<ide>
<del> if (!showLoading && !isDonating) {
<add> if (!isDonating) {
<ide> navigate(`/donate`);
<ide> return <Loader fullScreen={true} />;
<ide> } | 3 |
PHP | PHP | use data_get in request | 3586d080ea048cf1fa4430dc85e707bb9b0e7473 | <ide><path>src/Illuminate/Http/Request.php
<ide> public function input($key = null, $default = null)
<ide> {
<ide> $input = $this->getInputSource()->all() + $this->query->all();
<ide>
<del> return Arr::get($input, $key, $default);
<add> return data_get($input, $key, $default);
<ide> }
<ide>
<ide> /**
<ide> public function only($keys)
<ide> $input = $this->all();
<ide>
<ide> foreach ($keys as $key) {
<del> Arr::set($results, $key, Arr::get($input, $key));
<add> Arr::set($results, $key, data_get($input, $key));
<ide> }
<ide>
<ide> return $results;
<ide> public function cookie($key = null, $default = null)
<ide> */
<ide> public function file($key = null, $default = null)
<ide> {
<del> return Arr::get($this->files->all(), $key, $default);
<add> return data_get($this->files->all(), $key, $default);
<ide> }
<ide>
<ide> /**
<ide> public function json($key = null, $default = null)
<ide> return $this->json;
<ide> }
<ide>
<del> return Arr::get($this->json->all(), $key, $default);
<add> return data_get($this->json->all(), $key, $default);
<ide> }
<ide>
<ide> /**
<ide> public function offsetExists($offset)
<ide> */
<ide> public function offsetGet($offset)
<ide> {
<del> return Arr::get($this->all(), $offset);
<add> return data_get($this->all(), $offset);
<ide> }
<ide>
<ide> /** | 1 |
Python | Python | improve documentation for session attributes | 0a339545551b5303fb2750e6e5b0e72acbea60d4 | <ide><path>flask/sessions.py
<ide> """
<ide> import hashlib
<ide> import warnings
<add>from collections import MutableMapping
<ide> from datetime import datetime
<ide>
<ide> from itsdangerous import BadSignature, URLSafeTimedSerializer
<ide> from flask.json.tag import TaggedJSONSerializer
<ide>
<ide>
<del>class SessionMixin(object):
<del> """Expands a basic dictionary with an accessors that are expected
<del> by Flask extensions and users for the session.
<del> """
<add>class SessionMixin(MutableMapping):
<add> """Expands a basic dictionary with session attributes."""
<ide>
<del> def _get_permanent(self):
<add> @property
<add> def permanent(self):
<add> """This reflects the ``'_permanent'`` key in the dict."""
<ide> return self.get('_permanent', False)
<ide>
<del> def _set_permanent(self, value):
<add> @permanent.setter
<add> def permanent(self, value):
<ide> self['_permanent'] = bool(value)
<ide>
<del> #: this reflects the ``'_permanent'`` key in the dict.
<del> permanent = property(_get_permanent, _set_permanent)
<del> del _get_permanent, _set_permanent
<del>
<del> #: some session backends can tell you if a session is new, but that is
<del> #: not necessarily guaranteed. Use with caution. The default mixin
<del> #: implementation just hardcodes ``False`` in.
<add> #: Some implementations can detect whether a session is newly
<add> #: created, but that is not guaranteed. Use with caution. The mixin
<add> # default is hard-coded ``False``.
<ide> new = False
<ide>
<del> #: for some backends this will always be ``True``, but some backends will
<del> #: default this to false and detect changes in the dictionary for as
<del> #: long as changes do not happen on mutable structures in the session.
<del> #: The default mixin implementation just hardcodes ``True`` in.
<add> #: Some implementations can detect changes to the session and set
<add> #: this when that happens. The mixin default is hard coded to
<add> #: ``True``.
<ide> modified = True
<ide>
<del> #: the accessed variable indicates whether or not the session object has
<del> #: been accessed in that request. This allows flask to append a `Vary:
<del> #: Cookie` header to the response if the session is being accessed. This
<del> #: allows caching proxy servers, like Varnish, to use both the URL and the
<del> #: session cookie as keys when caching pages, preventing multiple users
<del> #: from being served the same cache.
<add> #: Some implementations can detect when session data is read or
<add> #: written and set this when that happens. The mixin default is hard
<add> #: coded to ``True``.
<ide> accessed = True
<ide>
<ide>
<ide> class SecureCookieSession(CallbackDict, SessionMixin):
<del> """Base class for sessions based on signed cookies."""
<add> """Base class for sessions based on signed cookies.
<add>
<add> This session backend will set the :attr:`modified` and
<add> :attr:`accessed` attributes. It cannot reliably track whether a
<add> session is new (vs. empty), so :attr:`new` remains hard coded to
<add> ``False``.
<add> """
<add>
<add> #: When data is changed, this is set to ``True``. Only the session
<add> #: dictionary itself is tracked; if the session contains mutable
<add> #: data (for example a nested dict) then this must be set to
<add> #: ``True`` manually when modifying that data. The session cookie
<add> #: will only be written to the response if this is ``True``.
<add> modified = False
<add>
<add> #: When data is read or written, this is set to ``True``. Used by
<add> # :class:`.SecureCookieSessionInterface` to add a ``Vary: Cookie``
<add> #: header, which allows caching proxies to cache different pages for
<add> #: different users.
<add> accessed = False
<ide>
<ide> def __init__(self, initial=None):
<ide> def on_update(self):
<ide> self.modified = True
<ide> self.accessed = True
<ide>
<ide> super(SecureCookieSession, self).__init__(initial, on_update)
<del> self.modified = False
<del> self.accessed = False
<ide>
<ide> def __getitem__(self, key):
<ide> self.accessed = True
<ide><path>tests/test_basic.py
<ide> def index():
<ide> def test_session(app, client):
<ide> @app.route('/set', methods=['POST'])
<ide> def set():
<add> assert not flask.session.accessed
<add> assert not flask.session.modified
<ide> flask.session['value'] = flask.request.form['value']
<add> assert flask.session.accessed
<add> assert flask.session.modified
<ide> return 'value set'
<ide>
<ide> @app.route('/get')
<ide> def get():
<del> return flask.session['value']
<add> assert not flask.session.accessed
<add> assert not flask.session.modified
<add> v = flask.session.get('value', 'None')
<add> assert flask.session.accessed
<add> assert not flask.session.modified
<add> return v
<ide>
<ide> assert client.post('/set', data={'value': '42'}).data == b'value set'
<ide> assert client.get('/get').data == b'42' | 2 |
Ruby | Ruby | improve test description | 11bd0ea01c8ea7aed68ca0c4f73cefe1408465a9 | <ide><path>activerecord/test/cases/associations/inverse_associations_test.rb
<ide> def test_inverse_instance_should_be_set_before_initialize_callbacks_are_run
<ide> end
<ide> end
<ide>
<del> def test_association_stuff
<add> def test_inverse_works_when_the_association_self_references_the_same_object
<ide> comment = comments(:greetings)
<ide> Comment.create!(parent: comment, post_id: comment.post_id, body: "New Comment")
<ide> | 1 |
Javascript | Javascript | replace \w with [^\s] | ffea217069b6bddbec2bc2e7048f59f4158f0560 | <ide><path>examples/js/loaders/VRMLLoader.js
<ide> THREE.VRMLLoader.prototype = {
<ide>
<ide> if ( /USE/.exec( data ) ) {
<ide>
<del> var defineKey = /USE\s+?(\w+)/.exec( data )[ 1 ];
<add> var defineKey = /USE\s+?([^\s]+)/.exec( data )[ 1 ];
<ide>
<ide> if ( undefined == defines[ defineKey ] ) {
<ide>
<ide> THREE.VRMLLoader.prototype = {
<ide>
<ide> if ( /DEF/.exec( data.string ) ) {
<ide>
<del> object.name = /DEF\s+(\w+)/.exec( data.string )[ 1 ];
<add> object.name = /DEF\s+([^\s]+)/.exec( data.string )[ 1 ];
<ide> defines[ object.name ] = object;
<ide>
<ide> }
<ide> THREE.VRMLLoader.prototype = {
<ide>
<ide> if ( /DEF/.exec( data.string ) ) {
<ide>
<del> object.name = /DEF\s+(\w+)/.exec( data.string )[ 1 ];
<add> object.name = /DEF\s+([^\s]+)/.exec( data.string )[ 1 ];
<ide>
<ide> defines[ object.name ] = object;
<ide>
<ide> THREE.VRMLLoader.prototype = {
<ide>
<ide> if ( child.string.indexOf ( 'DEF' ) > -1 ) {
<ide>
<del> var name = /DEF\s+(\w+)/.exec( child.string )[ 1 ];
<add> var name = /DEF\s+([^\s]+)/.exec( child.string )[ 1 ];
<ide>
<ide> defines[ name ] = geometry.vertices;
<ide>
<ide> }
<ide>
<ide> if ( child.string.indexOf ( 'USE' ) > -1 ) {
<ide>
<del> var defineKey = /USE\s+(\w+)/.exec( child.string )[ 1 ];
<add> var defineKey = /USE\s+([^\s]+)/.exec( child.string )[ 1 ];
<ide>
<ide> geometry.vertices = defines[ defineKey ];
<ide> }
<ide> THREE.VRMLLoader.prototype = {
<ide> // see if it's a define
<ide> if ( /DEF/.exec( data.string ) ) {
<ide>
<del> geometry.name = /DEF (\w+)/.exec( data.string )[ 1 ];
<add> geometry.name = /DEF ([^\s]+)/.exec( data.string )[ 1 ];
<ide> defines[ geometry.name ] = geometry;
<ide>
<ide> }
<ide> THREE.VRMLLoader.prototype = {
<ide>
<ide> if ( /DEF/.exec( data.string ) ) {
<ide>
<del> material.name = /DEF (\w+)/.exec( data.string )[ 1 ];
<add> material.name = /DEF ([^\s]+)/.exec( data.string )[ 1 ];
<ide>
<ide> defines[ material.name ] = material;
<ide> | 1 |
Python | Python | use commin method to compare array values | a6772327279d39fb5e8637fb807451879d1cf828 | <ide><path>numpy/core/tests/test_numeric.py
<ide> def setUp(self):
<ide> (arange(24).reshape(4,3,2).swapaxes(0,1), '?'),
<ide> ]
<ide>
<add> def compare_array_value(self, dz, value, fill_value):
<add> if not value is None:
<add> if fill_value:
<add> try:
<add> z = dz.dtype.type(value)
<add> except OverflowError:
<add> pass
<add> else:
<add> assert_(all(dz == z))
<add> else:
<add> assert_(all(dz == value))
<add>
<ide> def check_like_function(self, like_function, value, fill_value=False):
<ide> if fill_value:
<ide> fill_kwarg = {'val': value}
<ide> def check_like_function(self, like_function, value, fill_value=False):
<ide> assert_equal(dz.dtype, d.dtype)
<ide> else:
<ide> assert_equal(dz.dtype, np.dtype(dtype))
<del> if not value is None:
<del> if fill_value:
<del> try:
<del> z = dz.dtype.type(value)
<del> except OverflowError:
<del> pass
<del> else:
<del> assert_(all(dz == z))
<del> else:
<del> assert_(all(dz == value))
<add> self.compare_array_value(dz, value, fill_value)
<ide>
<ide> # C order, default dtype
<ide> dz = like_function(d, order='C', dtype=dtype, **fill_kwarg)
<ide> def check_like_function(self, like_function, value, fill_value=False):
<ide> assert_equal(dz.dtype, d.dtype)
<ide> else:
<ide> assert_equal(dz.dtype, np.dtype(dtype))
<del> if not value is None:
<del> if fill_value:
<del> try:
<del> z = dz.dtype.type(value)
<del> except OverflowError:
<del> pass
<del> else:
<del> assert_(all(dz == z))
<del> else:
<del> assert_(all(dz == value))
<add> self.compare_array_value(dz, value, fill_value)
<ide>
<ide> # F order, default dtype
<ide> dz = like_function(d, order='F', dtype=dtype, **fill_kwarg)
<ide> def check_like_function(self, like_function, value, fill_value=False):
<ide> assert_equal(dz.dtype, d.dtype)
<ide> else:
<ide> assert_equal(dz.dtype, np.dtype(dtype))
<del> if not value is None:
<del> if fill_value:
<del> try:
<del> z = dz.dtype.type(value)
<del> except OverflowError:
<del> pass
<del> else:
<del> assert_(all(dz == z))
<del> else:
<del> assert_(all(dz == value))
<add> self.compare_array_value(dz, value, fill_value)
<ide>
<ide> # A order
<ide> dz = like_function(d, order='A', dtype=dtype, **fill_kwarg)
<ide> def check_like_function(self, like_function, value, fill_value=False):
<ide> assert_equal(dz.dtype, d.dtype)
<ide> else:
<ide> assert_equal(dz.dtype, np.dtype(dtype))
<del> if not value is None:
<del> if fill_value:
<del> try:
<del> z = dz.dtype.type(value)
<del> except OverflowError:
<del> pass
<del> else:
<del> assert_(all(dz == z))
<del> else:
<del> assert_(all(dz == value))
<add> self.compare_array_value(dz, value, fill_value)
<ide>
<ide> # Test the 'subok' parameter
<ide> a = np.matrix([[1,2],[3,4]]) | 1 |
Javascript | Javascript | fix icon [ci skip] | 44dc987d8542e842b958bb5b9450f83e8e71933d | <ide><path>website/gatsby-config.js
<ide> module.exports = {
<ide> background_color: site.theme,
<ide> theme_color: site.theme,
<ide> display: `minimal-ui`,
<del> icon: legacy ? `src/images/icon.png` : `src/images/icon_legacy.png`,
<add> icon: legacy ? `src/images/icon_legacy.png` : `src/images/icon.png`,
<ide> },
<ide> },
<ide> { | 1 |
Javascript | Javascript | fix lesson links | 3eb72fb10de61fe45012d47c8ba6ed37283fcbf1 | <ide><path>threejs/lessons/resources/lesson.js
<ide> function getQueryParams() {
<ide> $(document).ready(function($){
<ide>
<ide> const codeKeywordLinks = {
<del> AnimationAction: 'https://threejs.org/docs/api/animation/AnimationAction.html',
<del> AnimationClip: 'https://threejs.org/docs/api/animation/AnimationClip.html',
<del> AnimationMixer: 'https://threejs.org/docs/api/animation/AnimationMixer.html',
<del> AnimationObjectGroup: 'https://threejs.org/docs/api/animation/AnimationObjectGroup.html',
<del> AnimationUtils: 'https://threejs.org/docs/api/animation/AnimationUtils.html',
<del> KeyframeTrack: 'https://threejs.org/docs/api/animation/KeyframeTrack.html',
<del> PropertyBinding: 'https://threejs.org/docs/api/animation/PropertyBinding.html',
<del> PropertyMixer: 'https://threejs.org/docs/api/animation/PropertyMixer.html',
<del> BooleanKeyframeTrack: 'https://threejs.org/docs/api/animation/tracks/BooleanKeyframeTrack.html',
<del> ColorKeyframeTrack: 'https://threejs.org/docs/api/animation/tracks/ColorKeyframeTrack.html',
<del> NumberKeyframeTrack: 'https://threejs.org/docs/api/animation/tracks/NumberKeyframeTrack.html',
<del> QuaternionKeyframeTrack: 'https://threejs.org/docs/api/animation/tracks/QuaternionKeyframeTrack.html',
<del> StringKeyframeTrack: 'https://threejs.org/docs/api/animation/tracks/StringKeyframeTrack.html',
<del> VectorKeyframeTrack: 'https://threejs.org/docs/api/animation/tracks/VectorKeyframeTrack.html',
<del> Audio: 'https://threejs.org/docs/api/audio/Audio.html',
<del> AudioAnalyser: 'https://threejs.org/docs/api/audio/AudioAnalyser.html',
<del> AudioContext: 'https://threejs.org/docs/api/audio/AudioContext.html',
<del> AudioListener: 'https://threejs.org/docs/api/audio/AudioListener.html',
<del> PositionalAudio: 'https://threejs.org/docs/api/audio/PositionalAudio.html',
<del> ArrayCamera: 'https://threejs.org/docs/api/cameras/ArrayCamera.html',
<del> Camera: 'https://threejs.org/docs/api/cameras/Camera.html',
<del> CubeCamera: 'https://threejs.org/docs/api/cameras/CubeCamera.html',
<del> OrthographicCamera: 'https://threejs.org/docs/api/cameras/OrthographicCamera.html',
<del> PerspectiveCamera: 'https://threejs.org/docs/api/cameras/PerspectiveCamera.html',
<del> StereoCamera: 'https://threejs.org/docs/api/cameras/StereoCamera.html',
<del> Animation: 'https://threejs.org/docs/api/constants/Animation.html',
<del> Core: 'https://threejs.org/docs/api/constants/Core.html',
<del> CustomBlendingEquation: 'https://threejs.org/docs/api/constants/CustomBlendingEquations.html',
<del> DrawModes: 'https://threejs.org/docs/api/constants/DrawModes.html',
<del> Materials: 'https://threejs.org/docs/api/constants/Materials.html',
<del> Renderer: 'https://threejs.org/docs/api/constants/Renderer.html',
<del> Textures: 'https://threejs.org/docs/api/constants/Textures.html',
<del> BufferAttribute: 'https://threejs.org/docs/api/core/BufferAttribute.html',
<del> BufferGeometry: 'https://threejs.org/docs/api/core/BufferGeometry.html',
<del> Clock: 'https://threejs.org/docs/api/core/Clock.html',
<del> DirectGeometry: 'https://threejs.org/docs/api/core/DirectGeometry.html',
<del> EventDispatcher: 'https://threejs.org/docs/api/core/EventDispatcher.html',
<del> Face3: 'https://threejs.org/docs/api/core/Face3.html',
<del> Geometry: 'https://threejs.org/docs/api/core/Geometry.html',
<del> InstancedBufferAttribute: 'https://threejs.org/docs/api/core/InstancedBufferAttribute.html',
<del> InstancedBufferGeometry: 'https://threejs.org/docs/api/core/InstancedBufferGeometry.html',
<del> InstancedInterleavedBuffer: 'https://threejs.org/docs/api/core/InstancedInterleavedBuffer.html',
<del> InterleavedBuffer: 'https://threejs.org/docs/api/core/InterleavedBuffer.html',
<del> InterleavedBufferAttribute: 'https://threejs.org/docs/api/core/InterleavedBufferAttribute.html',
<del> Layers: 'https://threejs.org/docs/api/core/Layers.html',
<del> Object3D: 'https://threejs.org/docs/api/core/Object3D.html',
<del> Raycaster: 'https://threejs.org/docs/api/core/Raycaster.html',
<del> Uniform: 'https://threejs.org/docs/api/core/Uniform.html',
<del> BufferAttributeTypes: 'https://threejs.org/docs/api/core/bufferAttributeTypes/BufferAttributeTypes.html',
<del> Earcut: 'https://threejs.org/docs/api/extras/Earcut.html',
<del> ShapeUtils: 'https://threejs.org/docs/api/extras/ShapeUtils.html',
<del> Curve: 'https://threejs.org/docs/api/extras/core/Curve.html',
<del> CurvePath: 'https://threejs.org/docs/api/extras/core/CurvePath.html',
<del> Font: 'https://threejs.org/docs/api/extras/core/Font.html',
<del> Interpolations: 'https://threejs.org/docs/api/extras/core/Interpolations.html',
<del> Path: 'https://threejs.org/docs/api/extras/core/Path.html',
<del> Shape: 'https://threejs.org/docs/api/extras/core/Shape.html',
<del> ShapePath: 'https://threejs.org/docs/api/extras/core/ShapePath.html',
<del> ArcCurve: 'https://threejs.org/docs/api/extras/curves/ArcCurve.html',
<del> CatmullRomCurve3: 'https://threejs.org/docs/api/extras/curves/CatmullRomCurve3.html',
<del> CubicBezierCurve: 'https://threejs.org/docs/api/extras/curves/CubicBezierCurve.html',
<del> CubicBezierCurve3: 'https://threejs.org/docs/api/extras/curves/CubicBezierCurve3.html',
<del> EllipseCurve: 'https://threejs.org/docs/api/extras/curves/EllipseCurve.html',
<del> LineCurve: 'https://threejs.org/docs/api/extras/curves/LineCurve.html',
<del> LineCurve3: 'https://threejs.org/docs/api/extras/curves/LineCurve3.html',
<del> QuadraticBezierCurve: 'https://threejs.org/docs/api/extras/curves/QuadraticBezierCurve.html',
<del> QuadraticBezierCurve3: 'https://threejs.org/docs/api/extras/curves/QuadraticBezierCurve3.html',
<del> SplineCurve: 'https://threejs.org/docs/api/extras/curves/SplineCurve.html',
<del> ImmediateRenderObject: 'https://threejs.org/docs/api/extras/objects/ImmediateRenderObject.html',
<del> BoxBufferGeometry: 'https://threejs.org/docs/api/geometries/BoxBufferGeometry.html',
<del> BoxGeometry: 'https://threejs.org/docs/api/geometries/BoxGeometry.html',
<del> CircleBufferGeometry: 'https://threejs.org/docs/api/geometries/CircleBufferGeometry.html',
<del> CircleGeometry: 'https://threejs.org/docs/api/geometries/CircleGeometry.html',
<del> ConeBufferGeometry: 'https://threejs.org/docs/api/geometries/ConeBufferGeometry.html',
<del> ConeGeometry: 'https://threejs.org/docs/api/geometries/ConeGeometry.html',
<del> CylinderBufferGeometry: 'https://threejs.org/docs/api/geometries/CylinderBufferGeometry.html',
<del> CylinderGeometry: 'https://threejs.org/docs/api/geometries/CylinderGeometry.html',
<del> DodecahedronBufferGeometry: 'https://threejs.org/docs/api/geometries/DodecahedronBufferGeometry.html',
<del> DodecahedronGeometry: 'https://threejs.org/docs/api/geometries/DodecahedronGeometry.html',
<del> EdgesGeometry: 'https://threejs.org/docs/api/geometries/EdgesGeometry.html',
<del> ExtrudeBufferGeometry: 'https://threejs.org/docs/api/geometries/ExtrudeBufferGeometry.html',
<del> ExtrudeGeometry: 'https://threejs.org/docs/api/geometries/ExtrudeGeometry.html',
<del> IcosahedronBufferGeometry: 'https://threejs.org/docs/api/geometries/IcosahedronBufferGeometry.html',
<del> IcosahedronGeometry: 'https://threejs.org/docs/api/geometries/IcosahedronGeometry.html',
<del> LatheBufferGeometry: 'https://threejs.org/docs/api/geometries/LatheBufferGeometry.html',
<del> LatheGeometry: 'https://threejs.org/docs/api/geometries/LatheGeometry.html',
<del> OctahedronBufferGeometry: 'https://threejs.org/docs/api/geometries/OctahedronBufferGeometry.html',
<del> OctahedronGeometry: 'https://threejs.org/docs/api/geometries/OctahedronGeometry.html',
<del> ParametricBufferGeometry: 'https://threejs.org/docs/api/geometries/ParametricBufferGeometry.html',
<del> ParametricGeometry: 'https://threejs.org/docs/api/geometries/ParametricGeometry.html',
<del> PlaneBufferGeometry: 'https://threejs.org/docs/api/geometries/PlaneBufferGeometry.html',
<del> PlaneGeometry: 'https://threejs.org/docs/api/geometries/PlaneGeometry.html',
<del> PolyhedronBufferGeometry: 'https://threejs.org/docs/api/geometries/PolyhedronBufferGeometry.html',
<del> PolyhedronGeometry: 'https://threejs.org/docs/api/geometries/PolyhedronGeometry.html',
<del> RingBufferGeometry: 'https://threejs.org/docs/api/geometries/RingBufferGeometry.html',
<del> RingGeometry: 'https://threejs.org/docs/api/geometries/RingGeometry.html',
<del> ShapeBufferGeometry: 'https://threejs.org/docs/api/geometries/ShapeBufferGeometry.html',
<del> ShapeGeometry: 'https://threejs.org/docs/api/geometries/ShapeGeometry.html',
<del> SphereBufferGeometry: 'https://threejs.org/docs/api/geometries/SphereBufferGeometry.html',
<del> SphereGeometry: 'https://threejs.org/docs/api/geometries/SphereGeometry.html',
<del> TetrahedronBufferGeometry: 'https://threejs.org/docs/api/geometries/TetrahedronBufferGeometry.html',
<del> TetrahedronGeometry: 'https://threejs.org/docs/api/geometries/TetrahedronGeometry.html',
<del> TextBufferGeometry: 'https://threejs.org/docs/api/geometries/TextBufferGeometry.html',
<del> TextGeometry: 'https://threejs.org/docs/api/geometries/TextGeometry.html',
<del> TorusBufferGeometry: 'https://threejs.org/docs/api/geometries/TorusBufferGeometry.html',
<del> TorusGeometry: 'https://threejs.org/docs/api/geometries/TorusGeometry.html',
<del> TorusKnotBufferGeometry: 'https://threejs.org/docs/api/geometries/TorusKnotBufferGeometry.html',
<del> TorusKnotGeometry: 'https://threejs.org/docs/api/geometries/TorusKnotGeometry.html',
<del> TubeBufferGeometry: 'https://threejs.org/docs/api/geometries/TubeBufferGeometry.html',
<del> TubeGeometry: 'https://threejs.org/docs/api/geometries/TubeGeometry.html',
<del> WireframeGeometry: 'https://threejs.org/docs/api/geometries/WireframeGeometry.html',
<del> ArrowHelper: 'https://threejs.org/docs/api/helpers/ArrowHelper.html',
<del> AxesHelper: 'https://threejs.org/docs/api/helpers/AxesHelper.html',
<del> BoxHelper: 'https://threejs.org/docs/api/helpers/BoxHelper.html',
<del> Box3Helper: 'https://threejs.org/docs/api/helpers/Box3Helper.html',
<del> CameraHelper: 'https://threejs.org/docs/api/helpers/CameraHelper.html',
<del> DirectionalLightHelper: 'https://threejs.org/docs/api/helpers/DirectionalLightHelper.html',
<del> FaceNormalsHelper: 'https://threejs.org/docs/api/helpers/FaceNormalsHelper.html',
<del> GridHelper: 'https://threejs.org/docs/api/helpers/GridHelper.html',
<del> PolarGridHelper: 'https://threejs.org/docs/api/helpers/PolarGridHelper.html',
<del> HemisphereLightHelper: 'https://threejs.org/docs/api/helpers/HemisphereLightHelper.html',
<del> PlaneHelper: 'https://threejs.org/docs/api/helpers/PlaneHelper.html',
<del> PointLightHelper: 'https://threejs.org/docs/api/helpers/PointLightHelper.html',
<del> RectAreaLightHelper: 'https://threejs.org/docs/api/helpers/RectAreaLightHelper.html',
<del> SkeletonHelper: 'https://threejs.org/docs/api/helpers/SkeletonHelper.html',
<del> SpotLightHelper: 'https://threejs.org/docs/api/helpers/SpotLightHelper.html',
<del> VertexNormalsHelper: 'https://threejs.org/docs/api/helpers/VertexNormalsHelper.html',
<del> AmbientLight: 'https://threejs.org/docs/api/lights/AmbientLight.html',
<del> DirectionalLight: 'https://threejs.org/docs/api/lights/DirectionalLight.html',
<del> HemisphereLight: 'https://threejs.org/docs/api/lights/HemisphereLight.html',
<del> Light: 'https://threejs.org/docs/api/lights/Light.html',
<del> PointLight: 'https://threejs.org/docs/api/lights/PointLight.html',
<del> RectAreaLight: 'https://threejs.org/docs/api/lights/RectAreaLight.html',
<del> SpotLight: 'https://threejs.org/docs/api/lights/SpotLight.html',
<del> DirectionalLightShadow: 'https://threejs.org/docs/api/lights/shadows/DirectionalLightShadow.html',
<del> LightShadow: 'https://threejs.org/docs/api/lights/shadows/LightShadow.html',
<del> SpotLightShadow: 'https://threejs.org/docs/api/lights/shadows/SpotLightShadow.html',
<del> AnimationLoader: 'https://threejs.org/docs/api/loaders/AnimationLoader.html',
<del> AudioLoader: 'https://threejs.org/docs/api/loaders/AudioLoader.html',
<del> BufferGeometryLoader: 'https://threejs.org/docs/api/loaders/BufferGeometryLoader.html',
<del> Cache: 'https://threejs.org/docs/api/loaders/Cache.html',
<del> CompressedTextureLoader: 'https://threejs.org/docs/api/loaders/CompressedTextureLoader.html',
<del> CubeTextureLoader: 'https://threejs.org/docs/api/loaders/CubeTextureLoader.html',
<del> DataTextureLoader: 'https://threejs.org/docs/api/loaders/DataTextureLoader.html',
<del> FileLoader: 'https://threejs.org/docs/api/loaders/FileLoader.html',
<del> FontLoader: 'https://threejs.org/docs/api/loaders/FontLoader.html',
<del> ImageBitmapLoader: 'https://threejs.org/docs/api/loaders/ImageBitmapLoader.html',
<del> ImageLoader: 'https://threejs.org/docs/api/loaders/ImageLoader.html',
<del> JSONLoader: 'https://threejs.org/docs/api/loaders/JSONLoader.html',
<del> Loader: 'https://threejs.org/docs/api/loaders/Loader.html',
<del> LoaderUtils: 'https://threejs.org/docs/api/loaders/LoaderUtils.html',
<del> MaterialLoader: 'https://threejs.org/docs/api/loaders/MaterialLoader.html',
<del> ObjectLoader: 'https://threejs.org/docs/api/loaders/ObjectLoader.html',
<del> TextureLoader: 'https://threejs.org/docs/api/loaders/TextureLoader.html',
<del> DefaultLoadingManager: 'https://threejs.org/docs/api/loaders/managers/DefaultLoadingManager.html',
<del> LoadingManager: 'https://threejs.org/docs/api/loaders/managers/LoadingManager.html',
<del> LineBasicMaterial: 'https://threejs.org/docs/api/materials/LineBasicMaterial.html',
<del> LineDashedMaterial: 'https://threejs.org/docs/api/materials/LineDashedMaterial.html',
<del> Material: 'https://threejs.org/docs/api/materials/Material.html',
<del> MeshBasicMaterial: 'https://threejs.org/docs/api/materials/MeshBasicMaterial.html',
<del> MeshDepthMaterial: 'https://threejs.org/docs/api/materials/MeshDepthMaterial.html',
<del> MeshLambertMaterial: 'https://threejs.org/docs/api/materials/MeshLambertMaterial.html',
<del> MeshNormalMaterial: 'https://threejs.org/docs/api/materials/MeshNormalMaterial.html',
<del> MeshPhongMaterial: 'https://threejs.org/docs/api/materials/MeshPhongMaterial.html',
<del> MeshPhysicalMaterial: 'https://threejs.org/docs/api/materials/MeshPhysicalMaterial.html',
<del> MeshStandardMaterial: 'https://threejs.org/docs/api/materials/MeshStandardMaterial.html',
<del> MeshToonMaterial: 'https://threejs.org/docs/api/materials/MeshToonMaterial.html',
<del> PointsMaterial: 'https://threejs.org/docs/api/materials/PointsMaterial.html',
<del> RawShaderMaterial: 'https://threejs.org/docs/api/materials/RawShaderMaterial.html',
<del> ShaderMaterial: 'https://threejs.org/docs/api/materials/ShaderMaterial.html',
<del> ShadowMaterial: 'https://threejs.org/docs/api/materials/ShadowMaterial.html',
<del> SpriteMaterial: 'https://threejs.org/docs/api/materials/SpriteMaterial.html',
<del> Box2: 'https://threejs.org/docs/api/math/Box2.html',
<del> Box3: 'https://threejs.org/docs/api/math/Box3.html',
<del> Color: 'https://threejs.org/docs/api/math/Color.html',
<del> Cylindrical: 'https://threejs.org/docs/api/math/Cylindrical.html',
<del> Euler: 'https://threejs.org/docs/api/math/Euler.html',
<del> Frustum: 'https://threejs.org/docs/api/math/Frustum.html',
<del> Interpolant: 'https://threejs.org/docs/api/math/Interpolant.html',
<del> Line3: 'https://threejs.org/docs/api/math/Line3.html',
<del> Math: 'https://threejs.org/docs/api/math/Math.html',
<del> Matrix3: 'https://threejs.org/docs/api/math/Matrix3.html',
<del> Matrix4: 'https://threejs.org/docs/api/math/Matrix4.html',
<del> Plane: 'https://threejs.org/docs/api/math/Plane.html',
<del> Quaternion: 'https://threejs.org/docs/api/math/Quaternion.html',
<del> Ray: 'https://threejs.org/docs/api/math/Ray.html',
<del> Sphere: 'https://threejs.org/docs/api/math/Sphere.html',
<del> Spherical: 'https://threejs.org/docs/api/math/Spherical.html',
<del> Triangle: 'https://threejs.org/docs/api/math/Triangle.html',
<del> Vector2: 'https://threejs.org/docs/api/math/Vector2.html',
<del> Vector3: 'https://threejs.org/docs/api/math/Vector3.html',
<del> Vector4: 'https://threejs.org/docs/api/math/Vector4.html',
<del> CubicInterpolant: 'https://threejs.org/docs/api/math/interpolants/CubicInterpolant.html',
<del> DiscreteInterpolant: 'https://threejs.org/docs/api/math/interpolants/DiscreteInterpolant.html',
<del> LinearInterpolant: 'https://threejs.org/docs/api/math/interpolants/LinearInterpolant.html',
<del> QuaternionLinearInterpolant: 'https://threejs.org/docs/api/math/interpolants/QuaternionLinearInterpolant.html',
<del> Bone: 'https://threejs.org/docs/api/objects/Bone.html',
<del> Group: 'https://threejs.org/docs/api/objects/Group.html',
<del> Line: 'https://threejs.org/docs/api/objects/Line.html',
<del> LineLoop: 'https://threejs.org/docs/api/objects/LineLoop.html',
<del> LineSegments: 'https://threejs.org/docs/api/objects/LineSegments.html',
<del> LOD: 'https://threejs.org/docs/api/objects/LOD.html',
<del> Mesh: 'https://threejs.org/docs/api/objects/Mesh.html',
<del> Points: 'https://threejs.org/docs/api/objects/Points.html',
<del> Skeleton: 'https://threejs.org/docs/api/objects/Skeleton.html',
<del> SkinnedMesh: 'https://threejs.org/docs/api/objects/SkinnedMesh.html',
<del> Sprite: 'https://threejs.org/docs/api/objects/Sprite.html',
<del> WebGLRenderer: 'https://threejs.org/docs/api/renderers/WebGLRenderer.html',
<del> WebGLRenderTarget: 'https://threejs.org/docs/api/renderers/WebGLRenderTarget.html',
<del> WebGLRenderTargetCube: 'https://threejs.org/docs/api/renderers/WebGLRenderTargetCube.html',
<del> ShaderChunk: 'https://threejs.org/docs/api/renderers/shaders/ShaderChunk.html',
<del> ShaderLib: 'https://threejs.org/docs/api/renderers/shaders/ShaderLib.html',
<del> UniformsLib: 'https://threejs.org/docs/api/renderers/shaders/UniformsLib.html',
<del> UniformsUtils: 'https://threejs.org/docs/api/renderers/shaders/UniformsUtils.html',
<del> Fog: 'https://threejs.org/docs/api/scenes/Fog.html',
<del> FogExp2: 'https://threejs.org/docs/api/scenes/FogExp2.html',
<del> Scene: 'https://threejs.org/docs/api/scenes/Scene.html',
<del> CanvasTexture: 'https://threejs.org/docs/api/textures/CanvasTexture.html',
<del> CompressedTexture: 'https://threejs.org/docs/api/textures/CompressedTexture.html',
<del> CubeTexture: 'https://threejs.org/docs/api/textures/CubeTexture.html',
<del> DataTexture: 'https://threejs.org/docs/api/textures/DataTexture.html',
<del> DepthTexture: 'https://threejs.org/docs/api/textures/DepthTexture.html',
<del> Texture: 'https://threejs.org/docs/api/textures/Texture.html',
<del> VideoTexture: 'https://threejs.org/docs/api/textures/VideoTexture.html',
<del> CCDIKSolver: 'https://threejs.org/docs/examples/animations/CCDIKSolver.html',
<del> MMDAnimationHelper: 'https://threejs.org/docs/examples/animations/MMDAnimationHelper.html',
<del> MMDPhysics: 'https://threejs.org/docs/examples/animations/MMDPhysics.html',
<del> OrbitControls: 'https://threejs.org/docs/examples/controls/OrbitControls.html',
<del> ConvexBufferGeometry: 'https://threejs.org/docs/examples/geometries/ConvexBufferGeometry.html',
<del> ConvexGeometry: 'https://threejs.org/docs/examples/geometries/ConvexGeometry.html',
<del> DecalGeometry: 'https://threejs.org/docs/examples/geometries/DecalGeometry.html',
<del> BabylonLoader: 'https://threejs.org/docs/examples/loaders/BabylonLoader.html',
<del> GLTFLoader: 'https://threejs.org/docs/examples/loaders/GLTFLoader.html',
<del> MMDLoader: 'https://threejs.org/docs/examples/loaders/MMDLoader.html',
<del> MTLLoader: 'https://threejs.org/docs/examples/loaders/MTLLoader.html',
<del> OBJLoader: 'https://threejs.org/docs/examples/loaders/OBJLoader.html',
<del> OBJLoader2: 'https://threejs.org/docs/examples/loaders/OBJLoader2.html',
<del> LoaderSupport: 'https://threejs.org/docs/examples/loaders/LoaderSupport.html',
<del> PCDLoader: 'https://threejs.org/docs/examples/loaders/PCDLoader.html',
<del> PDBLoader: 'https://threejs.org/docs/examples/loaders/PDBLoader.html',
<del> SVGLoader: 'https://threejs.org/docs/examples/loaders/SVGLoader.html',
<del> TGALoader: 'https://threejs.org/docs/examples/loaders/TGALoader.html',
<del> PRWMLoader: 'https://threejs.org/docs/examples/loaders/PRWMLoader.html',
<del> Lensflare: 'https://threejs.org/docs/examples/objects/Lensflare.html',
<del> GLTFExporter: 'https://threejs.org/docs/examples/exporters/GLTFExporter.html',
<add> AnimationAction: 'https://threejs.org/docs/#api/animation/AnimationAction',
<add> AnimationClip: 'https://threejs.org/docs/#api/animation/AnimationClip',
<add> AnimationMixer: 'https://threejs.org/docs/#api/animation/AnimationMixer',
<add> AnimationObjectGroup: 'https://threejs.org/docs/#api/animation/AnimationObjectGroup',
<add> AnimationUtils: 'https://threejs.org/docs/#api/animation/AnimationUtils',
<add> KeyframeTrack: 'https://threejs.org/docs/#api/animation/KeyframeTrack',
<add> PropertyBinding: 'https://threejs.org/docs/#api/animation/PropertyBinding',
<add> PropertyMixer: 'https://threejs.org/docs/#api/animation/PropertyMixer',
<add> BooleanKeyframeTrack: 'https://threejs.org/docs/#api/animation/tracks/BooleanKeyframeTrack',
<add> ColorKeyframeTrack: 'https://threejs.org/docs/#api/animation/tracks/ColorKeyframeTrack',
<add> NumberKeyframeTrack: 'https://threejs.org/docs/#api/animation/tracks/NumberKeyframeTrack',
<add> QuaternionKeyframeTrack: 'https://threejs.org/docs/#api/animation/tracks/QuaternionKeyframeTrack',
<add> StringKeyframeTrack: 'https://threejs.org/docs/#api/animation/tracks/StringKeyframeTrack',
<add> VectorKeyframeTrack: 'https://threejs.org/docs/#api/animation/tracks/VectorKeyframeTrack',
<add> Audio: 'https://threejs.org/docs/#api/audio/Audio',
<add> AudioAnalyser: 'https://threejs.org/docs/#api/audio/AudioAnalyser',
<add> AudioContext: 'https://threejs.org/docs/#api/audio/AudioContext',
<add> AudioListener: 'https://threejs.org/docs/#api/audio/AudioListener',
<add> PositionalAudio: 'https://threejs.org/docs/#api/audio/PositionalAudio',
<add> ArrayCamera: 'https://threejs.org/docs/#api/cameras/ArrayCamera',
<add> Camera: 'https://threejs.org/docs/#api/cameras/Camera',
<add> CubeCamera: 'https://threejs.org/docs/#api/cameras/CubeCamera',
<add> OrthographicCamera: 'https://threejs.org/docs/#api/cameras/OrthographicCamera',
<add> PerspectiveCamera: 'https://threejs.org/docs/#api/cameras/PerspectiveCamera',
<add> StereoCamera: 'https://threejs.org/docs/#api/cameras/StereoCamera',
<add> Animation: 'https://threejs.org/docs/#api/constants/Animation',
<add> Core: 'https://threejs.org/docs/#api/constants/Core',
<add> CustomBlendingEquation: 'https://threejs.org/docs/#api/constants/CustomBlendingEquations',
<add> DrawModes: 'https://threejs.org/docs/#api/constants/DrawModes',
<add> Materials: 'https://threejs.org/docs/#api/constants/Materials',
<add> Renderer: 'https://threejs.org/docs/#api/constants/Renderer',
<add> Textures: 'https://threejs.org/docs/#api/constants/Textures',
<add> BufferAttribute: 'https://threejs.org/docs/#api/core/BufferAttribute',
<add> BufferGeometry: 'https://threejs.org/docs/#api/core/BufferGeometry',
<add> Clock: 'https://threejs.org/docs/#api/core/Clock',
<add> DirectGeometry: 'https://threejs.org/docs/#api/core/DirectGeometry',
<add> EventDispatcher: 'https://threejs.org/docs/#api/core/EventDispatcher',
<add> Face3: 'https://threejs.org/docs/#api/core/Face3',
<add> Geometry: 'https://threejs.org/docs/#api/core/Geometry',
<add> InstancedBufferAttribute: 'https://threejs.org/docs/#api/core/InstancedBufferAttribute',
<add> InstancedBufferGeometry: 'https://threejs.org/docs/#api/core/InstancedBufferGeometry',
<add> InstancedInterleavedBuffer: 'https://threejs.org/docs/#api/core/InstancedInterleavedBuffer',
<add> InterleavedBuffer: 'https://threejs.org/docs/#api/core/InterleavedBuffer',
<add> InterleavedBufferAttribute: 'https://threejs.org/docs/#api/core/InterleavedBufferAttribute',
<add> Layers: 'https://threejs.org/docs/#api/core/Layers',
<add> Object3D: 'https://threejs.org/docs/#api/core/Object3D',
<add> Raycaster: 'https://threejs.org/docs/#api/core/Raycaster',
<add> Uniform: 'https://threejs.org/docs/#api/core/Uniform',
<add> BufferAttributeTypes: 'https://threejs.org/docs/#api/core/bufferAttributeTypes/BufferAttributeTypes',
<add> Earcut: 'https://threejs.org/docs/#api/extras/Earcut',
<add> ShapeUtils: 'https://threejs.org/docs/#api/extras/ShapeUtils',
<add> Curve: 'https://threejs.org/docs/#api/extras/core/Curve',
<add> CurvePath: 'https://threejs.org/docs/#api/extras/core/CurvePath',
<add> Font: 'https://threejs.org/docs/#api/extras/core/Font',
<add> Interpolations: 'https://threejs.org/docs/#api/extras/core/Interpolations',
<add> Path: 'https://threejs.org/docs/#api/extras/core/Path',
<add> Shape: 'https://threejs.org/docs/#api/extras/core/Shape',
<add> ShapePath: 'https://threejs.org/docs/#api/extras/core/ShapePath',
<add> ArcCurve: 'https://threejs.org/docs/#api/extras/curves/ArcCurve',
<add> CatmullRomCurve3: 'https://threejs.org/docs/#api/extras/curves/CatmullRomCurve3',
<add> CubicBezierCurve: 'https://threejs.org/docs/#api/extras/curves/CubicBezierCurve',
<add> CubicBezierCurve3: 'https://threejs.org/docs/#api/extras/curves/CubicBezierCurve3',
<add> EllipseCurve: 'https://threejs.org/docs/#api/extras/curves/EllipseCurve',
<add> LineCurve: 'https://threejs.org/docs/#api/extras/curves/LineCurve',
<add> LineCurve3: 'https://threejs.org/docs/#api/extras/curves/LineCurve3',
<add> QuadraticBezierCurve: 'https://threejs.org/docs/#api/extras/curves/QuadraticBezierCurve',
<add> QuadraticBezierCurve3: 'https://threejs.org/docs/#api/extras/curves/QuadraticBezierCurve3',
<add> SplineCurve: 'https://threejs.org/docs/#api/extras/curves/SplineCurve',
<add> ImmediateRenderObject: 'https://threejs.org/docs/#api/extras/objects/ImmediateRenderObject',
<add> BoxBufferGeometry: 'https://threejs.org/docs/#api/geometries/BoxBufferGeometry',
<add> BoxGeometry: 'https://threejs.org/docs/#api/geometries/BoxGeometry',
<add> CircleBufferGeometry: 'https://threejs.org/docs/#api/geometries/CircleBufferGeometry',
<add> CircleGeometry: 'https://threejs.org/docs/#api/geometries/CircleGeometry',
<add> ConeBufferGeometry: 'https://threejs.org/docs/#api/geometries/ConeBufferGeometry',
<add> ConeGeometry: 'https://threejs.org/docs/#api/geometries/ConeGeometry',
<add> CylinderBufferGeometry: 'https://threejs.org/docs/#api/geometries/CylinderBufferGeometry',
<add> CylinderGeometry: 'https://threejs.org/docs/#api/geometries/CylinderGeometry',
<add> DodecahedronBufferGeometry: 'https://threejs.org/docs/#api/geometries/DodecahedronBufferGeometry',
<add> DodecahedronGeometry: 'https://threejs.org/docs/#api/geometries/DodecahedronGeometry',
<add> EdgesGeometry: 'https://threejs.org/docs/#api/geometries/EdgesGeometry',
<add> ExtrudeBufferGeometry: 'https://threejs.org/docs/#api/geometries/ExtrudeBufferGeometry',
<add> ExtrudeGeometry: 'https://threejs.org/docs/#api/geometries/ExtrudeGeometry',
<add> IcosahedronBufferGeometry: 'https://threejs.org/docs/#api/geometries/IcosahedronBufferGeometry',
<add> IcosahedronGeometry: 'https://threejs.org/docs/#api/geometries/IcosahedronGeometry',
<add> LatheBufferGeometry: 'https://threejs.org/docs/#api/geometries/LatheBufferGeometry',
<add> LatheGeometry: 'https://threejs.org/docs/#api/geometries/LatheGeometry',
<add> OctahedronBufferGeometry: 'https://threejs.org/docs/#api/geometries/OctahedronBufferGeometry',
<add> OctahedronGeometry: 'https://threejs.org/docs/#api/geometries/OctahedronGeometry',
<add> ParametricBufferGeometry: 'https://threejs.org/docs/#api/geometries/ParametricBufferGeometry',
<add> ParametricGeometry: 'https://threejs.org/docs/#api/geometries/ParametricGeometry',
<add> PlaneBufferGeometry: 'https://threejs.org/docs/#api/geometries/PlaneBufferGeometry',
<add> PlaneGeometry: 'https://threejs.org/docs/#api/geometries/PlaneGeometry',
<add> PolyhedronBufferGeometry: 'https://threejs.org/docs/#api/geometries/PolyhedronBufferGeometry',
<add> PolyhedronGeometry: 'https://threejs.org/docs/#api/geometries/PolyhedronGeometry',
<add> RingBufferGeometry: 'https://threejs.org/docs/#api/geometries/RingBufferGeometry',
<add> RingGeometry: 'https://threejs.org/docs/#api/geometries/RingGeometry',
<add> ShapeBufferGeometry: 'https://threejs.org/docs/#api/geometries/ShapeBufferGeometry',
<add> ShapeGeometry: 'https://threejs.org/docs/#api/geometries/ShapeGeometry',
<add> SphereBufferGeometry: 'https://threejs.org/docs/#api/geometries/SphereBufferGeometry',
<add> SphereGeometry: 'https://threejs.org/docs/#api/geometries/SphereGeometry',
<add> TetrahedronBufferGeometry: 'https://threejs.org/docs/#api/geometries/TetrahedronBufferGeometry',
<add> TetrahedronGeometry: 'https://threejs.org/docs/#api/geometries/TetrahedronGeometry',
<add> TextBufferGeometry: 'https://threejs.org/docs/#api/geometries/TextBufferGeometry',
<add> TextGeometry: 'https://threejs.org/docs/#api/geometries/TextGeometry',
<add> TorusBufferGeometry: 'https://threejs.org/docs/#api/geometries/TorusBufferGeometry',
<add> TorusGeometry: 'https://threejs.org/docs/#api/geometries/TorusGeometry',
<add> TorusKnotBufferGeometry: 'https://threejs.org/docs/#api/geometries/TorusKnotBufferGeometry',
<add> TorusKnotGeometry: 'https://threejs.org/docs/#api/geometries/TorusKnotGeometry',
<add> TubeBufferGeometry: 'https://threejs.org/docs/#api/geometries/TubeBufferGeometry',
<add> TubeGeometry: 'https://threejs.org/docs/#api/geometries/TubeGeometry',
<add> WireframeGeometry: 'https://threejs.org/docs/#api/geometries/WireframeGeometry',
<add> ArrowHelper: 'https://threejs.org/docs/#api/helpers/ArrowHelper',
<add> AxesHelper: 'https://threejs.org/docs/#api/helpers/AxesHelper',
<add> BoxHelper: 'https://threejs.org/docs/#api/helpers/BoxHelper',
<add> Box3Helper: 'https://threejs.org/docs/#api/helpers/Box3Helper',
<add> CameraHelper: 'https://threejs.org/docs/#api/helpers/CameraHelper',
<add> DirectionalLightHelper: 'https://threejs.org/docs/#api/helpers/DirectionalLightHelper',
<add> FaceNormalsHelper: 'https://threejs.org/docs/#api/helpers/FaceNormalsHelper',
<add> GridHelper: 'https://threejs.org/docs/#api/helpers/GridHelper',
<add> PolarGridHelper: 'https://threejs.org/docs/#api/helpers/PolarGridHelper',
<add> HemisphereLightHelper: 'https://threejs.org/docs/#api/helpers/HemisphereLightHelper',
<add> PlaneHelper: 'https://threejs.org/docs/#api/helpers/PlaneHelper',
<add> PointLightHelper: 'https://threejs.org/docs/#api/helpers/PointLightHelper',
<add> RectAreaLightHelper: 'https://threejs.org/docs/#api/helpers/RectAreaLightHelper',
<add> SkeletonHelper: 'https://threejs.org/docs/#api/helpers/SkeletonHelper',
<add> SpotLightHelper: 'https://threejs.org/docs/#api/helpers/SpotLightHelper',
<add> VertexNormalsHelper: 'https://threejs.org/docs/#api/helpers/VertexNormalsHelper',
<add> AmbientLight: 'https://threejs.org/docs/#api/lights/AmbientLight',
<add> DirectionalLight: 'https://threejs.org/docs/#api/lights/DirectionalLight',
<add> HemisphereLight: 'https://threejs.org/docs/#api/lights/HemisphereLight',
<add> Light: 'https://threejs.org/docs/#api/lights/Light',
<add> PointLight: 'https://threejs.org/docs/#api/lights/PointLight',
<add> RectAreaLight: 'https://threejs.org/docs/#api/lights/RectAreaLight',
<add> SpotLight: 'https://threejs.org/docs/#api/lights/SpotLight',
<add> DirectionalLightShadow: 'https://threejs.org/docs/#api/lights/shadows/DirectionalLightShadow',
<add> LightShadow: 'https://threejs.org/docs/#api/lights/shadows/LightShadow',
<add> SpotLightShadow: 'https://threejs.org/docs/#api/lights/shadows/SpotLightShadow',
<add> AnimationLoader: 'https://threejs.org/docs/#api/loaders/AnimationLoader',
<add> AudioLoader: 'https://threejs.org/docs/#api/loaders/AudioLoader',
<add> BufferGeometryLoader: 'https://threejs.org/docs/#api/loaders/BufferGeometryLoader',
<add> Cache: 'https://threejs.org/docs/#api/loaders/Cache',
<add> CompressedTextureLoader: 'https://threejs.org/docs/#api/loaders/CompressedTextureLoader',
<add> CubeTextureLoader: 'https://threejs.org/docs/#api/loaders/CubeTextureLoader',
<add> DataTextureLoader: 'https://threejs.org/docs/#api/loaders/DataTextureLoader',
<add> FileLoader: 'https://threejs.org/docs/#api/loaders/FileLoader',
<add> FontLoader: 'https://threejs.org/docs/#api/loaders/FontLoader',
<add> ImageBitmapLoader: 'https://threejs.org/docs/#api/loaders/ImageBitmapLoader',
<add> ImageLoader: 'https://threejs.org/docs/#api/loaders/ImageLoader',
<add> JSONLoader: 'https://threejs.org/docs/#api/loaders/JSONLoader',
<add> Loader: 'https://threejs.org/docs/#api/loaders/Loader',
<add> LoaderUtils: 'https://threejs.org/docs/#api/loaders/LoaderUtils',
<add> MaterialLoader: 'https://threejs.org/docs/#api/loaders/MaterialLoader',
<add> ObjectLoader: 'https://threejs.org/docs/#api/loaders/ObjectLoader',
<add> TextureLoader: 'https://threejs.org/docs/#api/loaders/TextureLoader',
<add> DefaultLoadingManager: 'https://threejs.org/docs/#api/loaders/managers/DefaultLoadingManager',
<add> LoadingManager: 'https://threejs.org/docs/#api/loaders/managers/LoadingManager',
<add> LineBasicMaterial: 'https://threejs.org/docs/#api/materials/LineBasicMaterial',
<add> LineDashedMaterial: 'https://threejs.org/docs/#api/materials/LineDashedMaterial',
<add> Material: 'https://threejs.org/docs/#api/materials/Material',
<add> MeshBasicMaterial: 'https://threejs.org/docs/#api/materials/MeshBasicMaterial',
<add> MeshDepthMaterial: 'https://threejs.org/docs/#api/materials/MeshDepthMaterial',
<add> MeshLambertMaterial: 'https://threejs.org/docs/#api/materials/MeshLambertMaterial',
<add> MeshNormalMaterial: 'https://threejs.org/docs/#api/materials/MeshNormalMaterial',
<add> MeshPhongMaterial: 'https://threejs.org/docs/#api/materials/MeshPhongMaterial',
<add> MeshPhysicalMaterial: 'https://threejs.org/docs/#api/materials/MeshPhysicalMaterial',
<add> MeshStandardMaterial: 'https://threejs.org/docs/#api/materials/MeshStandardMaterial',
<add> MeshToonMaterial: 'https://threejs.org/docs/#api/materials/MeshToonMaterial',
<add> PointsMaterial: 'https://threejs.org/docs/#api/materials/PointsMaterial',
<add> RawShaderMaterial: 'https://threejs.org/docs/#api/materials/RawShaderMaterial',
<add> ShaderMaterial: 'https://threejs.org/docs/#api/materials/ShaderMaterial',
<add> ShadowMaterial: 'https://threejs.org/docs/#api/materials/ShadowMaterial',
<add> SpriteMaterial: 'https://threejs.org/docs/#api/materials/SpriteMaterial',
<add> Box2: 'https://threejs.org/docs/#api/math/Box2',
<add> Box3: 'https://threejs.org/docs/#api/math/Box3',
<add> Color: 'https://threejs.org/docs/#api/math/Color',
<add> Cylindrical: 'https://threejs.org/docs/#api/math/Cylindrical',
<add> Euler: 'https://threejs.org/docs/#api/math/Euler',
<add> Frustum: 'https://threejs.org/docs/#api/math/Frustum',
<add> Interpolant: 'https://threejs.org/docs/#api/math/Interpolant',
<add> Line3: 'https://threejs.org/docs/#api/math/Line3',
<add> Math: 'https://threejs.org/docs/#api/math/Math',
<add> Matrix3: 'https://threejs.org/docs/#api/math/Matrix3',
<add> Matrix4: 'https://threejs.org/docs/#api/math/Matrix4',
<add> Plane: 'https://threejs.org/docs/#api/math/Plane',
<add> Quaternion: 'https://threejs.org/docs/#api/math/Quaternion',
<add> Ray: 'https://threejs.org/docs/#api/math/Ray',
<add> Sphere: 'https://threejs.org/docs/#api/math/Sphere',
<add> Spherical: 'https://threejs.org/docs/#api/math/Spherical',
<add> Triangle: 'https://threejs.org/docs/#api/math/Triangle',
<add> Vector2: 'https://threejs.org/docs/#api/math/Vector2',
<add> Vector3: 'https://threejs.org/docs/#api/math/Vector3',
<add> Vector4: 'https://threejs.org/docs/#api/math/Vector4',
<add> CubicInterpolant: 'https://threejs.org/docs/#api/math/interpolants/CubicInterpolant',
<add> DiscreteInterpolant: 'https://threejs.org/docs/#api/math/interpolants/DiscreteInterpolant',
<add> LinearInterpolant: 'https://threejs.org/docs/#api/math/interpolants/LinearInterpolant',
<add> QuaternionLinearInterpolant: 'https://threejs.org/docs/#api/math/interpolants/QuaternionLinearInterpolant',
<add> Bone: 'https://threejs.org/docs/#api/objects/Bone',
<add> Group: 'https://threejs.org/docs/#api/objects/Group',
<add> Line: 'https://threejs.org/docs/#api/objects/Line',
<add> LineLoop: 'https://threejs.org/docs/#api/objects/LineLoop',
<add> LineSegments: 'https://threejs.org/docs/#api/objects/LineSegments',
<add> LOD: 'https://threejs.org/docs/#api/objects/LOD',
<add> Mesh: 'https://threejs.org/docs/#api/objects/Mesh',
<add> Points: 'https://threejs.org/docs/#api/objects/Points',
<add> Skeleton: 'https://threejs.org/docs/#api/objects/Skeleton',
<add> SkinnedMesh: 'https://threejs.org/docs/#api/objects/SkinnedMesh',
<add> Sprite: 'https://threejs.org/docs/#api/objects/Sprite',
<add> WebGLRenderer: 'https://threejs.org/docs/#api/renderers/WebGLRenderer',
<add> WebGLRenderTarget: 'https://threejs.org/docs/#api/renderers/WebGLRenderTarget',
<add> WebGLRenderTargetCube: 'https://threejs.org/docs/#api/renderers/WebGLRenderTargetCube',
<add> ShaderChunk: 'https://threejs.org/docs/#api/renderers/shaders/ShaderChunk',
<add> ShaderLib: 'https://threejs.org/docs/#api/renderers/shaders/ShaderLib',
<add> UniformsLib: 'https://threejs.org/docs/#api/renderers/shaders/UniformsLib',
<add> UniformsUtils: 'https://threejs.org/docs/#api/renderers/shaders/UniformsUtils',
<add> Fog: 'https://threejs.org/docs/#api/scenes/Fog',
<add> FogExp2: 'https://threejs.org/docs/#api/scenes/FogExp2',
<add> Scene: 'https://threejs.org/docs/#api/scenes/Scene',
<add> CanvasTexture: 'https://threejs.org/docs/#api/textures/CanvasTexture',
<add> CompressedTexture: 'https://threejs.org/docs/#api/textures/CompressedTexture',
<add> CubeTexture: 'https://threejs.org/docs/#api/textures/CubeTexture',
<add> DataTexture: 'https://threejs.org/docs/#api/textures/DataTexture',
<add> DepthTexture: 'https://threejs.org/docs/#api/textures/DepthTexture',
<add> Texture: 'https://threejs.org/docs/#api/textures/Texture',
<add> VideoTexture: 'https://threejs.org/docs/#api/textures/VideoTexture',
<add> CCDIKSolver: 'https://threejs.org/docs/#examples/animations/CCDIKSolver',
<add> MMDAnimationHelper: 'https://threejs.org/docs/#examples/animations/MMDAnimationHelper',
<add> MMDPhysics: 'https://threejs.org/docs/#examples/animations/MMDPhysics',
<add> OrbitControls: 'https://threejs.org/docs/#examples/controls/OrbitControls',
<add> ConvexBufferGeometry: 'https://threejs.org/docs/#examples/geometries/ConvexBufferGeometry',
<add> ConvexGeometry: 'https://threejs.org/docs/#examples/geometries/ConvexGeometry',
<add> DecalGeometry: 'https://threejs.org/docs/#examples/geometries/DecalGeometry',
<add> BabylonLoader: 'https://threejs.org/docs/#examples/loaders/BabylonLoader',
<add> GLTFLoader: 'https://threejs.org/docs/#examples/loaders/GLTFLoader',
<add> MMDLoader: 'https://threejs.org/docs/#examples/loaders/MMDLoader',
<add> MTLLoader: 'https://threejs.org/docs/#examples/loaders/MTLLoader',
<add> OBJLoader: 'https://threejs.org/docs/#examples/loaders/OBJLoader',
<add> OBJLoader2: 'https://threejs.org/docs/#examples/loaders/OBJLoader2',
<add> LoaderSupport: 'https://threejs.org/docs/#examples/loaders/LoaderSupport',
<add> PCDLoader: 'https://threejs.org/docs/#examples/loaders/PCDLoader',
<add> PDBLoader: 'https://threejs.org/docs/#examples/loaders/PDBLoader',
<add> SVGLoader: 'https://threejs.org/docs/#examples/loaders/SVGLoader',
<add> TGALoader: 'https://threejs.org/docs/#examples/loaders/TGALoader',
<add> PRWMLoader: 'https://threejs.org/docs/#examples/loaders/PRWMLoader',
<add> Lensflare: 'https://threejs.org/docs/#examples/objects/Lensflare',
<add> GLTFExporter: 'https://threejs.org/docs/#examples/exporters/GLTFExporter',
<ide> };
<ide>
<ide> function getKeywordLink(keyword) {
<add> const dotNdx = keyword.indexOf('.');
<add> if (dotNdx) {
<add> const before = keyword.substring(0, dotNdx);
<add> const link = codeKeywordLinks[before];
<add> if (link) {
<add> return `${link}.${keyword.substr(dotNdx + 1)}`;
<add> }
<add> }
<ide> return keyword.startsWith('THREE.')
<ide> ? codeKeywordLinks[keyword.substring(6)]
<ide> : codeKeywordLinks[keyword]; | 1 |
Python | Python | raise correct error | e1e73936b150aaa9b9b22afcd5fabbf5e49841ae | <ide><path>spacy/util.py
<ide> def get_model_meta(path):
<ide> meta = read_json(meta_path)
<ide> for setting in ['lang', 'name', 'version']:
<ide> if setting not in meta:
<del> raise IOError('No %s setting found in model meta.json' % setting)
<add> raise ValueError('No %s setting found in model meta.json' % setting)
<ide> return meta
<ide>
<ide> | 1 |
Ruby | Ruby | remove invalid copied comment | 5a48d297f283371e2d8b94f2c4c09896629ce938 | <ide><path>Library/Homebrew/download_strategy.rb
<ide> def fetch
<ide> def stage
<ide> dst=Dir.getwd
<ide> Dir.chdir @clone do
<del> # http://stackoverflow.com/questions/160608/how-to-do-a-git-export-like-svn-export
<ide> safe_system 'hg', 'archive', '-y', '-t', 'files', dst
<ide> end
<ide> end | 1 |
Ruby | Ruby | remove warning from `bin/setup` test | 30206aeff9a106131b2bb241476f0ff5250df862 | <ide><path>railties/test/application/bin_setup_test.rb
<ide> def test_bin_setup_output
<ide> output = `bin/setup 2>&1`
<ide>
<ide> # Ignore line that's only output by Bundler < 1.14
<del> output.sub! /^Resolving dependencies\.\.\.\n/, ""
<add> output.sub!(/^Resolving dependencies\.\.\.\n/, "")
<ide>
<ide> assert_equal(<<-OUTPUT, output)
<ide> == Installing dependencies == | 1 |
Text | Text | make url paths no longer experimental | 2287deab94cb409ee808d0c6338bc5b08a0c6c80 | <ide><path>doc/api/fs.md
<ide> example `fs.readdirSync('c:\\')` can potentially return a different result than
<ide> <!-- YAML
<ide> added: v7.6.0
<ide> -->
<del>
<del>> Stability: 1 - Experimental
<del>
<ide> For most `fs` module functions, the `path` or `filename` argument may be passed
<ide> as a WHATWG [`URL`][] object. Only [`URL`][] objects using the `file:` protocol
<ide> are supported. | 1 |
Ruby | Ruby | remove integration tests | 56bde378f3732353be869e7f925002a4b3b2b525 | <ide><path>Library/Homebrew/test/cmd/install_spec.rb
<ide> expect(HOMEBREW_CELLAR/"testball1/0.1/foo/test").not_to be_a_file
<ide> end
<ide>
<del> it "does not install formulae with forbidden license" do
<del> setup_test_formula "package_license"
<del>
<del> expect { brew "install", "package_license", "HOMEBREW_FORBIDDEN_LICENSES" => "0BSD MIT" }
<del> .to output("Error: package_license has a forbidden license 0BSD.\n").to_stderr
<del> .and not_to_output.to_stdout
<del> .and be_a_failure
<del> expect(HOMEBREW_CELLAR/"testball1/0.1/foo/test").not_to be_a_file
<del> end
<del>
<del> it "installs formulae if formulae license is not forbidden" do
<del> setup_test_formula "testball1"
<del>
<del> expect { brew "install", "testball1", "HOMEBREW_FORBIDDEN_LICENSES" => "AAK ADSL AML" }
<del> .to output(%r{#{HOMEBREW_CELLAR}/testball1/0\.1}).to_stdout
<del> .and not_to_output.to_stderr
<del> .and be_a_success
<del> expect(HOMEBREW_CELLAR/"testball1/0.1/foo/test").not_to be_a_file
<del> end
<del>
<ide> it "installs formulae with options" do
<ide> setup_test_formula "testball1"
<ide> | 1 |
Javascript | Javascript | fix dag last run link | d944f5a59daf0c4512f87369c6eabb27666376bf | <ide><path>airflow/www/static/js/dags.js
<ide> function blockedHandler(error, json) {
<ide>
<ide> function lastDagRunsHandler(error, json) {
<ide> Object.keys(json).forEach((safeDagId) => {
<del> const { dagId } = json[safeDagId];
<add> const dagId = json[safeDagId].dag_id;
<ide> const executionDate = json[safeDagId].execution_date;
<ide> const startDate = json[safeDagId].start_date;
<ide> const g = d3.select(`#last-run-${safeDagId}`); | 1 |
Text | Text | correct introduced_in metadata for buffer doc | 2289267fc28d4cef0f754fba3f065d5083d7839f | <ide><path>doc/api/buffer.md
<ide> # Buffer
<ide>
<del><!--introduced_in=v0.10.0-->
<add><!--introduced_in=v0.1.90-->
<ide> <!--lint disable maximum-line-length-->
<ide>
<ide> > Stability: 2 - Stable | 1 |
PHP | PHP | apply fixes from styleci | 7af11f5acd7b76df47ad3e2453c8de49da27660f | <ide><path>src/Illuminate/Database/Eloquent/Model.php
<ide> protected function removeTableFromKey($key)
<ide> if (strpos($key, '.') !== false) {
<ide> if (! empty($this->getGuarded()) &&
<ide> $this->getGuarded() !== ['*']) {
<del> throw new LogicException("Mass assignment of Eloquent attributes including table names is unsafe when guarding attributes.");
<add> throw new LogicException('Mass assignment of Eloquent attributes including table names is unsafe when guarding attributes.');
<ide> }
<ide>
<ide> return last(explode('.', $key)); | 1 |
PHP | PHP | convert looping event into an object | f1978c4c99e3b2edce33b22f383f0a9d3e47791a | <ide><path>src/Illuminate/Queue/Events/Looping.php
<add><?php
<add>
<add>namespace Illuminate\Queue\Events;
<add>
<add>class Looping
<add>{
<add> //
<add>}
<ide><path>src/Illuminate/Queue/QueueManager.php
<ide> public function exceptionOccurred($callback)
<ide> */
<ide> public function looping($callback)
<ide> {
<del> $this->app['events']->listen('illuminate.queue.looping', $callback);
<add> $this->app['events']->listen(Events\Looping::class, $callback);
<ide> }
<ide>
<ide> /**
<ide> protected function resolve($name)
<ide> */
<ide> protected function getConnector($driver)
<ide> {
<del> if (isset($this->connectors[$driver])) {
<del> return call_user_func($this->connectors[$driver]);
<add> if (! isset($this->connectors[$driver])) {
<add> throw new InvalidArgumentException("No connector for [$driver]");
<ide> }
<ide>
<del> throw new InvalidArgumentException("No connector for [$driver]");
<add> return call_user_func($this->connectors[$driver]);
<ide> }
<ide>
<ide> /**
<ide> public function addConnector($driver, Closure $resolver)
<ide> */
<ide> protected function getConfig($name)
<ide> {
<del> if (is_null($name) || $name === 'null') {
<del> return ['driver' => 'null'];
<add> if (! is_null($name) && $name !== 'null') {
<add> return $this->app['config']["queue.connections.{$name}"];
<ide> }
<ide>
<del> return $this->app['config']["queue.connections.{$name}"];
<add> return ['driver' => 'null'];
<ide> }
<ide>
<ide> /**
<ide><path>src/Illuminate/Queue/Worker.php
<ide> protected function registerTimeoutHandler($job, WorkerOptions $options)
<ide> protected function daemonShouldRun(WorkerOptions $options)
<ide> {
<ide> if (($this->manager->isDownForMaintenance() && ! $options->force) ||
<del> $this->events->until('illuminate.queue.looping') === false) {
<add> $this->events->until(new Events\Looping) === false) {
<ide> // If the application is down for maintenance or doesn't want the queues to run
<ide> // we will sleep for one second just in case the developer has it set to not
<ide> // sleep at all. This just prevents CPU from maxing out in this situation. | 3 |
Javascript | Javascript | add example for setproperties | 1745e57010f3807c2aec8cab43c280fe28723237 | <ide><path>packages/ember-metal/lib/set_properties.js
<ide> var changeProperties = Ember.changeProperties,
<ide> a single `beginPropertyChanges` and `endPropertyChanges` batch, so
<ide> observers will be buffered.
<ide>
<add> ```javascript
<add> anObject.setProperties({
<add> firstName: "Stanley",
<add> lastName: "Stuart",
<add> age: "21"
<add> })
<add> ```
<add>
<ide> @method setProperties
<ide> @param self
<ide> @param {Object} hash | 1 |
PHP | PHP | fix tabs to spaces | b48f105b3fc1dbc5a145965e5513f7d48a657827 | <ide><path>lib/Cake/Test/Case/Model/Behavior/TreeBehaviorNumberTest.php
<ide> public function testRecoverUsingParentMode() {
<ide>
<ide> $this->Tree->create();
<ide> $this->Tree->save(array('name' => 'About Us', $parentField => $node1, $leftField => 0, $rightField => 0));
<del> $node11 = $this->Tree->id;
<add> $node11 = $this->Tree->id;
<ide> $this->Tree->create();
<ide> $this->Tree->save(array('name' => 'Programs', $parentField => $node1, $leftField => 0, $rightField => 0));
<del> $node12 = $this->Tree->id;
<add> $node12 = $this->Tree->id;
<ide> $this->Tree->create();
<ide> $this->Tree->save(array('name' => 'Mission and History', $parentField => $node11, $leftField => 0, $rightField => 0));
<ide> $this->Tree->create();
<ide> public function testRecoverUsingParentModeAndDelete() {
<ide>
<ide> $this->Tree->create();
<ide> $this->Tree->save(array('name' => 'About Us', $parentField => $node1, $leftField => 0, $rightField => 0));
<del> $node11 = $this->Tree->id;
<add> $node11 = $this->Tree->id;
<ide> $this->Tree->create();
<ide> $this->Tree->save(array('name' => 'Programs', $parentField => $node1, $leftField => 0, $rightField => 0));
<del> $node12 = $this->Tree->id;
<add> $node12 = $this->Tree->id;
<ide> $this->Tree->create();
<ide> $this->Tree->save(array('name' => 'Mission and History', $parentField => $node11, $leftField => 0, $rightField => 0));
<ide> $this->Tree->create(); | 1 |
Javascript | Javascript | use duplex streams in duplex stream test | c083a200b07f998649b52d80ff653219a691d0e2 | <ide><path>test/parallel/test-stream-duplex.js
<ide>
<ide> const common = require('../common');
<ide> const assert = require('assert');
<del>const Duplex = require('stream').Transform;
<add>const Duplex = require('stream').Duplex;
<ide>
<ide> const stream = new Duplex({ objectMode: true });
<ide> | 1 |
Ruby | Ruby | fix collection of `unused_pyc_files` | 155f4d73946c522f3224288546c70085fb0ff44b | <ide><path>Library/Homebrew/cleanup.rb
<ide> def cleanup_python_site_packages
<ide>
<ide> unused_pyc_files += pyc_files.reject { |k,| seen_non_pyc_file[k] }
<ide> .values
<add> .flatten
<ide> return if unused_pyc_files.blank?
<ide>
<ide> unused_pyc_files.each do |pyc| | 1 |
Ruby | Ruby | add a branch to eliminate multiple nil checks | cf985d1a4e7da2ba52f968aceee650bbdda6287e | <ide><path>actionpack/lib/action_dispatch/middleware/request_id.rb
<ide> def initialize(app)
<ide>
<ide> def call(env)
<ide> req = ActionDispatch::Request.new env
<del> req.request_id = external_request_id(req) || internal_request_id
<add> req.request_id = make_request_id(req.x_request_id)
<ide> @app.call(env).tap { |_status, headers, _body| headers[X_REQUEST_ID] = req.request_id }
<ide> end
<ide>
<ide> private
<del> def external_request_id(req)
<del> if request_id = req.x_request_id.presence
<add> def make_request_id(request_id)
<add> if request_id.presence
<ide> request_id.gsub(/[^\w\-]/, "".freeze).first(255)
<add> else
<add> internal_request_id
<ide> end
<ide> end
<ide> | 1 |
Python | Python | display bug for duration | c6ea5ad18834bf7d915af05795b5b5a122068e03 | <ide><path>airflow/www/app.py
<ide> def dag_link(v, c, m, p):
<ide> '<a href="{url}">{m.dag_id}</a>'.format(**locals()))
<ide>
<ide> def duration_f(v, c, m, p):
<del> return timedelta(seconds=m.duration)
<add> if m.end_date:
<add> return timedelta(seconds=m.duration)
<ide>
<ide> class TaskInstanceModelView(ModelViewOnly):
<ide> column_filters = ('dag_id', 'task_id', 'state', 'execution_date') | 1 |
PHP | PHP | prevent array_forget() from mixing up references | 8f1c4334297d4aad9ccbd3bac7b894b3ff662855 | <ide><path>src/Illuminate/Support/Arr.php
<ide> public static function flatten($array)
<ide> */
<ide> public static function forget(&$array, $keys)
<ide> {
<add> $original =& $array;
<add>
<ide> foreach ((array) $keys as $key)
<ide> {
<ide> $parts = explode('.', $key);
<ide> public static function forget(&$array, $keys)
<ide> }
<ide>
<ide> unset($array[array_shift($parts)]);
<add>
<add> // clean up after each pass
<add> $array =& $original;
<ide> }
<ide> }
<ide>
<ide><path>tests/Support/SupportHelpersTest.php
<ide> public function testArrayForget()
<ide> $this->assertFalse(isset($array['names']['developer']));
<ide> $this->assertFalse(isset($array['names']['otherDeveloper']));
<ide> $this->assertTrue(isset($array['names']['thirdDeveloper']));
<add>
<add> $array = ['names' => ['developer' => 'taylor', 'otherDeveloper' => 'dayle'], 'otherNames' => ['developer' => 'Lucas', 'otherDeveloper' => 'Graham']];
<add> array_forget($array, ['names.developer', 'otherNames.otherDeveloper']);
<add> $expected = ['names' => ['otherDeveloper' => 'dayle'], 'otherNames' => ['developer' => 'Lucas']];
<add> $this->assertEquals($expected, $array);
<ide> }
<ide>
<ide> | 2 |
Javascript | Javascript | move binding init in constructor | c13354e339da3849156287b0ad3bb70b9c115632 | <ide><path>lib/child_process.js
<ide> function maybeClose(subprocess) {
<ide> function ChildProcess() {
<ide> EventEmitter.call(this);
<ide>
<add> // Initialize TCPWrap and PipeWrap
<add> process.binding('tcp_wrap');
<add> process.binding('pipe_wrap');
<add>
<ide> var self = this;
<ide>
<ide> this._closesNeeded = 1;
<ide><path>lib/net.js
<ide> function Socket(options) {
<ide> stream.Duplex.call(this, options);
<ide>
<ide> if (options.handle) {
<del> // Initialize TCPWrap and PipeWrap
<del> process.binding('tcp_wrap');
<del> process.binding('pipe_wrap');
<del>
<ide> this._handle = options.handle; // private
<ide> } else if (typeof options.fd !== 'undefined') {
<ide> this._handle = createPipe(); | 2 |
Javascript | Javascript | fix race conditions in tests | 9395786d11b759bdefaa3ce0e6eb99582a5706fd | <ide><path>test/pummel/test-http-client-reconnect-bug.js
<ide> common = require("../common");
<ide> assert = common.assert
<ide>
<del>var tcp = require("tcp"),
<add>var net = require("net"),
<ide> sys = require("sys"),
<ide> http = require("http");
<ide>
<ide> var errorCount = 0;
<ide> var eofCount = 0;
<ide>
<del>var server = tcp.createServer(function(socket) {
<add>var server = net.createServer(function(socket) {
<ide> socket.end();
<ide> });
<del>server.listen(common.PORT);
<del>
<del>var client = http.createClient(common.PORT);
<del>
<del>client.addListener("error", function() {
<del> console.log("ERROR!");
<del> errorCount++;
<del>});
<del>
<del>client.addListener("end", function() {
<del> console.log("EOF!");
<del> eofCount++;
<del>});
<del>
<del>var request = client.request("GET", "/", {"host": "localhost"});
<del>request.end();
<del>request.addListener('response', function(response) {
<del> console.log("STATUS: " + response.statusCode);
<add>server.on('listening', function(){
<add> var client = http.createClient(common.PORT);
<add>
<add> client.addListener("error", function(err) {
<add> console.log("ERROR! "+(err.stack||err));
<add> errorCount++;
<add> });
<add>
<add> client.addListener("end", function() {
<add> console.log("EOF!");
<add> eofCount++;
<add> });
<add>
<add> var request = client.request("GET", "/", {"host": "localhost"});
<add> request.end();
<add> request.addListener('response', function(response) {
<add> console.log("STATUS: " + response.statusCode);
<add> });
<ide> });
<add>server.listen(common.PORT);
<ide>
<ide> setTimeout(function () {
<ide> server.close();
<ide><path>test/pummel/test-net-pause.js
<del>common = require("../common");
<del>assert = common.assert
<del>net = require("net");
<del>N = 200;
<add>var common = require("../common");
<add>var assert = common.assert;
<add>var net = require("net");
<add>var N = 200;
<add>var recv = "", chars_recved = 0;
<ide>
<ide> server = net.createServer(function (connection) {
<ide> function write (j) {
<ide> server = net.createServer(function (connection) {
<ide> }
<ide> write(0);
<ide> });
<del>server.listen(common.PORT);
<del>
<del>
<del>recv = "";
<del>chars_recved = 0;
<del>
<del>client = net.createConnection(common.PORT);
<del>client.setEncoding("ascii");
<del>client.addListener("data", function (d) {
<del> print(d);
<del> recv += d;
<del>});
<add>server.on('listening', function(){
<add> client = net.createConnection(common.PORT);
<add> client.setEncoding("ascii");
<add> client.addListener("data", function (d) {
<add> print(d);
<add> recv += d;
<add> });
<ide>
<del>setTimeout(function () {
<del> chars_recved = recv.length;
<del> console.log("pause at: " + chars_recved);
<del> assert.equal(true, chars_recved > 1);
<del> client.pause();
<ide> setTimeout(function () {
<del> console.log("resume at: " + chars_recved);
<del> assert.equal(chars_recved, recv.length);
<del> client.resume();
<del>
<add> chars_recved = recv.length;
<add> console.log("pause at: " + chars_recved);
<add> assert.equal(true, chars_recved > 1);
<add> client.pause();
<ide> setTimeout(function () {
<del> chars_recved = recv.length;
<del> console.log("pause at: " + chars_recved);
<del> client.pause();
<add> console.log("resume at: " + chars_recved);
<add> assert.equal(chars_recved, recv.length);
<add> client.resume();
<ide>
<ide> setTimeout(function () {
<del> console.log("resume at: " + chars_recved);
<del> assert.equal(chars_recved, recv.length);
<del> client.resume();
<add> chars_recved = recv.length;
<add> console.log("pause at: " + chars_recved);
<add> client.pause();
<add>
<add> setTimeout(function () {
<add> console.log("resume at: " + chars_recved);
<add> assert.equal(chars_recved, recv.length);
<add> client.resume();
<add>
<add> }, 500);
<ide>
<ide> }, 500);
<ide>
<ide> }, 500);
<ide>
<ide> }, 500);
<ide>
<del>}, 500);
<del>
<del>client.addListener("end", function () {
<del> server.close();
<del> client.end();
<add> client.addListener("end", function () {
<add> server.close();
<add> client.end();
<add> });
<ide> });
<add>server.listen(common.PORT);
<ide>
<ide> process.addListener("exit", function () {
<ide> assert.equal(N, recv.length);
<ide><path>test/simple/test-dgram-unix-anon.js
<ide> server.on("close", function () {
<ide>
<ide> timer = setTimeout(function () {
<ide> throw new Error("Timeout");
<del>}, 200);
<add>}, 500); | 3 |
Python | Python | add model saving functionality | ea561ba6d87879b9a67a7454e1d29777fb59132d | <ide><path>keras/callbacks.py
<ide> class ModelCheckpoint(Callback):
<ide> this should be `max`, for `val_loss` this should
<ide> be `min`, etc. In `auto` mode, the direction is
<ide> automatically inferred from the name of the monitored quantity.
<add> save_weights_only: if True, then only the model's weights will be
<add> saved (`model.save_weights(filepath)`), else the full model
<add> is saved (`model.save(filepath)`).
<ide>
<ide> '''
<ide> def __init__(self, filepath, monitor='val_loss', verbose=0,
<del> save_best_only=False, mode='auto'):
<del>
<add> save_best_only=False, save_weights_only=False,
<add> mode='auto'):
<ide> super(ModelCheckpoint, self).__init__()
<ide> self.monitor = monitor
<ide> self.verbose = verbose
<ide> self.filepath = filepath
<ide> self.save_best_only = save_best_only
<add> self.save_weights_only = save_weights_only
<ide>
<ide> if mode not in ['auto', 'min', 'max']:
<ide> warnings.warn('ModelCheckpoint mode %s is unknown, '
<ide> def on_epoch_end(self, epoch, logs={}):
<ide> % (epoch, self.monitor, self.best,
<ide> current, filepath))
<ide> self.best = current
<del> self.model.save_weights(filepath, overwrite=True)
<add> if self.save_weights_only:
<add> self.model.save_weights(filepath, overwrite=True)
<add> else:
<add> self.model.save(filepath, overwrite=True)
<ide> else:
<ide> if self.verbose > 0:
<ide> print('Epoch %05d: %s did not improve' %
<ide> (epoch, self.monitor))
<ide> else:
<ide> if self.verbose > 0:
<ide> print('Epoch %05d: saving model to %s' % (epoch, filepath))
<del> self.model.save_weights(filepath, overwrite=True)
<add> if self.save_weights_only:
<add> self.model.save_weights(filepath, overwrite=True)
<add> else:
<add> self.model.save(filepath, overwrite=True)
<ide>
<ide>
<ide> class EarlyStopping(Callback):
<ide><path>keras/engine/topology.py
<ide> import types as python_types
<ide> import warnings
<ide> import copy
<add>import os
<ide> from six.moves import zip
<ide>
<del>from keras import backend as K
<add>from .. import backend as K
<add>from ..utils.io_utils import ask_to_proceed_with_overwrite
<ide>
<ide>
<ide> def to_list(x):
<ide> def process_layer(layer_data):
<ide> output_tensors.append(layer_output_tensors[tensor_index])
<ide> return cls(input=input_tensors, output=output_tensors, name=name)
<ide>
<del> def save_weights(self, filepath, overwrite=False):
<add> def save(self, filepath, overwrite=True):
<add> '''Save into a single HDF5 file:
<add> - the model architecture, allowing to re-instantiate the model
<add> - the model weights
<add> - the state of the optimizer, allowing to resume training
<add> exactly where you left off.
<add>
<add> This allows you to save the entirety of the state of a model
<add> in a single file.
<add>
<add> Saved models can be reinstantiated via `keras.models.load_model`.
<add> The model returned by `load_model`
<add> is a compiled model ready to be used (unless the saved model
<add> was never compiled in the first place).
<add>
<add> # Example usage
<add>
<add> ```python
<add> from keras.models import load_model
<add>
<add> model.save('my_model.h5') # creates a HDF5 file 'my_model.h5'
<add> del model # deletes the existing model
<add>
<add> # returns a compiled model
<add> # identical to the previous one
<add> model = load_model('my_model.h5')
<add> ```
<add> '''
<add> from ..models import save_model
<add> save_model(self, filepath, overwrite)
<add>
<add> def save_weights(self, filepath, overwrite=True):
<ide> '''Dumps all layer weights to a HDF5 file.
<ide>
<ide> The weight file has:
<ide> def save_weights(self, filepath, overwrite=False):
<ide> storing the weight value, named after the weight tensor
<ide> '''
<ide> import h5py
<del> import os.path
<ide> # if file exists and should not be overwritten
<ide> if not overwrite and os.path.isfile(filepath):
<del> import sys
<del> get_input = input
<del> if sys.version_info[:2] <= (2, 7):
<del> get_input = raw_input
<del> overwrite = get_input('[WARNING] %s already exists - overwrite? '
<del> '[y/n]' % (filepath))
<del> while overwrite not in ['y', 'n']:
<del> overwrite = get_input('Enter "y" (overwrite) or "n" (cancel).')
<del> if overwrite == 'n':
<add> proceed = ask_to_proceed_with_overwrite(filepath)
<add> if not proceed:
<ide> return
<del> print('[TIP] Next time specify overwrite=True in save_weights!')
<add> f = h5py.File(filepath, 'w')
<add> self.save_weights_to_hdf5_group(f)
<add> f.flush()
<add> f.close()
<ide>
<add> def save_weights_to_hdf5_group(self, f):
<ide> if hasattr(self, 'flattened_layers'):
<ide> # support for legacy Sequential/Merge behavior
<ide> flattened_layers = self.flattened_layers
<ide> else:
<ide> flattened_layers = self.layers
<ide>
<del> f = h5py.File(filepath, 'w')
<ide> f.attrs['layer_names'] = [layer.name.encode('utf8') for layer in flattened_layers]
<ide>
<ide> for layer in flattened_layers:
<ide> def save_weights(self, filepath, overwrite=False):
<ide> for name, val in zip(weight_names, weight_values):
<ide> param_dset = g.create_dataset(name, val.shape,
<ide> dtype=val.dtype)
<del> param_dset[:] = val
<del> f.flush()
<del> f.close()
<add> if not val.shape:
<add> # scalar
<add> param_dset[()] = val
<add> else:
<add> param_dset[:] = val
<ide>
<ide> def load_weights(self, filepath):
<ide> '''Load all layer weights from a HDF5 save file.
<ide> '''
<ide> import h5py
<ide> f = h5py.File(filepath, mode='r')
<add> self.load_weights_from_hdf5_group(f)
<add> f.close()
<ide>
<add> def load_weights_from_hdf5_group(self, f):
<add> '''Weight loading is based on layer order in a list
<add> (matching model.flattened_layers for Sequential models,
<add> and model.layers for Model class instances), not
<add> on layer names.
<add> Layers that have no weights are skipped.
<add> '''
<ide> if hasattr(self, 'flattened_layers'):
<ide> # support for legacy Sequential/Merge behavior
<ide> flattened_layers = self.flattened_layers
<ide> else:
<ide> flattened_layers = self.layers
<add> filtered_layers = []
<add> for layer in flattened_layers:
<add> weights = layer.trainable_weights + layer.non_trainable_weights
<add> if weights:
<add> filtered_layers.append(layer)
<add> flattened_layers = filtered_layers
<ide>
<ide> if 'nb_layers' in f.attrs:
<ide> # legacy format
<ide> def load_weights(self, filepath):
<ide> else:
<ide> # new file format
<ide> layer_names = [n.decode('utf8') for n in f.attrs['layer_names']]
<add> filtered_layer_names = []
<add> for name in layer_names:
<add> g = f[name]
<add> weight_names = [n.decode('utf8') for n in g.attrs['weight_names']]
<add> if len(weight_names):
<add> filtered_layer_names.append(name)
<add> layer_names = filtered_layer_names
<ide> if len(layer_names) != len(flattened_layers):
<ide> raise Exception('You are trying to load a weight file '
<ide> 'containing ' + str(len(layer_names)) +
<ide> def load_weights(self, filepath):
<ide> for k, name in enumerate(layer_names):
<ide> g = f[name]
<ide> weight_names = [n.decode('utf8') for n in g.attrs['weight_names']]
<del> if len(weight_names):
<del> weight_values = [g[weight_name] for weight_name in weight_names]
<del> layer = flattened_layers[k]
<del> symbolic_weights = layer.trainable_weights + layer.non_trainable_weights
<del> if len(weight_values) != len(symbolic_weights):
<del> raise Exception('Layer #' + str(k) +
<del> ' (named "' + layer.name +
<del> '" in the current model) was found to '
<del> 'correspond to layer ' + name +
<del> ' in the save file. '
<del> 'However the new layer ' + layer.name +
<del> ' expects ' + str(len(symbolic_weights)) +
<del> ' weights, but the saved weights have ' +
<del> str(len(weight_values)) +
<del> ' elements.')
<del> weight_value_tuples += zip(symbolic_weights, weight_values)
<add> weight_values = [g[weight_name] for weight_name in weight_names]
<add> layer = flattened_layers[k]
<add> symbolic_weights = layer.trainable_weights + layer.non_trainable_weights
<add> if len(weight_values) != len(symbolic_weights):
<add> raise Exception('Layer #' + str(k) +
<add> ' (named "' + layer.name +
<add> '" in the current model) was found to '
<add> 'correspond to layer ' + name +
<add> ' in the save file. '
<add> 'However the new layer ' + layer.name +
<add> ' expects ' + str(len(symbolic_weights)) +
<add> ' weights, but the saved weights have ' +
<add> str(len(weight_values)) +
<add> ' elements.')
<add> weight_value_tuples += zip(symbolic_weights, weight_values)
<ide> K.batch_set_value(weight_value_tuples)
<del> f.close()
<ide>
<ide> def _updated_config(self):
<ide> '''shared between different serialization methods'''
<ide> def _updated_config(self):
<ide> 'config': config,
<ide> 'keras_version': keras_version
<ide> }
<del>
<del> if hasattr(self, 'optimizer'):
<del> model_config['optimizer'] = self.optimizer.get_config()
<del> model_config['loss'] = getattr(self.loss, '__name__', self.loss)
<del> model_config['sample_weight_mode'] = self.sample_weight_mode
<del>
<del> if hasattr(self, 'loss_weights'):
<del> model_config['loss_weights'] = self.loss_weights
<ide> return model_config
<ide>
<ide> def to_json(self, **kwargs):
<ide> def get_json_type(obj):
<ide> if type(obj).__name__ == type.__name__:
<ide> return obj.__name__
<ide>
<del> raise TypeError('Not JSON Serializable')
<add> raise TypeError('Not JSON Serializable:', obj)
<ide>
<ide> model_config = self._updated_config()
<ide> return json.dumps(model_config, default=get_json_type, **kwargs)
<ide><path>keras/engine/training.py
<ide> def compile(self, optimizer, loss, metrics=[], loss_weights=None,
<ide> self.targets.append(K.placeholder(ndim=len(shape), name=name + '_target'))
<ide>
<ide> # prepare metrics
<add> self.metrics = metrics
<ide> self.metrics_names = ['loss']
<del> self.metrics = []
<add> self.metrics_tensors = []
<ide>
<ide> # compute total loss
<ide> total_loss = None
<ide> def compile(self, optimizer, loss, metrics=[], loss_weights=None,
<ide> output_loss = weighted_loss(y_true, y_pred,
<ide> sample_weight, mask)
<ide> if len(self.outputs) > 1:
<del> self.metrics.append(output_loss)
<add> self.metrics_tensors.append(output_loss)
<ide> self.metrics_names.append(self.output_names[i] + '_loss')
<ide> if total_loss is None:
<ide> total_loss = loss_weight * output_loss
<ide> def compile(self, optimizer, loss, metrics=[], loss_weights=None,
<ide> output_shape = self.internal_output_shapes[i]
<ide> if output_shape[-1] == 1 or self.loss_functions[i] == objectives.binary_crossentropy:
<ide> # case: binary accuracy
<del> self.metrics.append(metrics_module.binary_accuracy(y_true, y_pred))
<add> self.metrics_tensors.append(metrics_module.binary_accuracy(y_true, y_pred))
<ide> elif self.loss_functions[i] == objectives.sparse_categorical_crossentropy:
<ide> # case: categorical accuracy with sparse targets
<del> self.metrics.append(
<add> self.metrics_tensors.append(
<ide> metrics_module.sparse_categorical_accuracy(y_true, y_pred))
<ide> else:
<ide> # case: categorical accuracy with dense targets
<del> self.metrics.append(metrics_module.categorical_accuracy(y_true, y_pred))
<add> self.metrics_tensors.append(metrics_module.categorical_accuracy(y_true, y_pred))
<ide> if len(self.output_names) == 1:
<ide> self.metrics_names.append('acc')
<ide> else:
<ide> self.metrics_names.append(self.output_layers[i].name + '_acc')
<ide> else:
<ide> metric_fn = metrics_module.get(metric)
<del> self.metrics.append(metric_fn(y_true, y_pred))
<add> self.metrics_tensors.append(metric_fn(y_true, y_pred))
<ide> if len(self.output_names) == 1:
<ide> self.metrics_names.append(metric_fn.__name__)
<ide> else:
<ide> def _make_train_function(self):
<ide>
<ide> # returns loss and metrics. Updates weights at each call.
<ide> self.train_function = K.function(inputs,
<del> [self.total_loss] + self.metrics,
<add> [self.total_loss] + self.metrics_tensors,
<ide> updates=updates,
<ide> **self._function_kwargs)
<ide>
<ide> def _make_test_function(self):
<ide> # return loss and metrics, no gradient updates.
<ide> # Does update the network states.
<ide> self.test_function = K.function(inputs,
<del> [self.total_loss] + self.metrics,
<add> [self.total_loss] + self.metrics_tensors,
<ide> updates=self.state_updates,
<ide> **self._function_kwargs)
<ide>
<ide><path>keras/models.py
<ide> from __future__ import print_function
<ide> import warnings
<ide> import copy
<add>import json
<add>import os
<add>import numpy as np
<ide>
<ide> from . import backend as K
<add>from .utils.io_utils import ask_to_proceed_with_overwrite
<ide> from .engine.training import Model
<ide> from .engine.topology import get_source_inputs, Node
<add>from .optimizers import optimizer_from_config
<ide> from .legacy.models import Graph
<ide>
<ide>
<add>def save_model(model, filepath, overwrite=True):
<add>
<add> def get_json_type(obj):
<add> # if obj is a serializable Keras class instance
<add> # e.g. optimizer, layer
<add> if hasattr(obj, 'get_config'):
<add> return {'class_name': obj.__class__.__name__,
<add> 'config': obj.get_config()}
<add>
<add> # if obj is any numpy type
<add> if type(obj).__module__ == np.__name__:
<add> return obj.item()
<add>
<add> # misc functions (e.g. loss function)
<add> if hasattr(obj, '__call__'):
<add> return obj.__name__
<add>
<add> # if obj is a python 'type'
<add> if type(obj).__name__ == type.__name__:
<add> return obj.__name__
<add>
<add> raise TypeError('Not JSON Serializable:', obj)
<add>
<add> import h5py
<add> # if file exists and should not be overwritten
<add> if not overwrite and os.path.isfile(filepath):
<add> proceed = ask_to_proceed_with_overwrite(filepath)
<add> if not proceed:
<add> return
<add>
<add> f = h5py.File(filepath, 'w')
<add>
<add> f.attrs['model_config'] = json.dumps({
<add> 'class_name': model.__class__.__name__,
<add> 'config': model.get_config()
<add> }, default=get_json_type).encode('utf8')
<add>
<add> model_weights_group = f.create_group('model_weights')
<add> model.save_weights_to_hdf5_group(model_weights_group)
<add>
<add> if hasattr(model, 'optimizer'):
<add> f.attrs['training_config'] = json.dumps({
<add> 'optimizer_config': {
<add> 'class_name': model.optimizer.__class__.__name__,
<add> 'config': model.optimizer.get_config()
<add> },
<add> 'loss': model.loss,
<add> 'metrics': model.metrics,
<add> 'sample_weight_mode': model.sample_weight_mode,
<add> 'loss_weights': model.loss_weights,
<add> }, default=get_json_type).encode('utf8')
<add>
<add> # save optimizer weights
<add> symbolic_weights = getattr(model.optimizer, 'weights')
<add> if symbolic_weights:
<add> optimizer_weights_group = f.create_group('optimizer_weights')
<add> weight_values = K.batch_get_value(symbolic_weights)
<add> weight_names = []
<add> for i, (w, val) in enumerate(zip(symbolic_weights, weight_values)):
<add> if hasattr(w, 'name') and w.name:
<add> name = str(w.name)
<add> else:
<add> name = 'param_' + str(i)
<add> weight_names.append(name.encode('utf8'))
<add> optimizer_weights_group.attrs['weight_names'] = weight_names
<add> for name, val in zip(weight_names, weight_values):
<add> param_dset = optimizer_weights_group.create_dataset(
<add> name,
<add> val.shape,
<add> dtype=val.dtype)
<add> if not val.shape:
<add> # scalar
<add> param_dset[()] = val
<add> else:
<add> param_dset[:] = val
<add> f.flush()
<add> f.close()
<add>
<add>
<add>def load_model(filepath, custom_objects={}):
<add>
<add> def deserialize(obj):
<add> if type(obj) is list:
<add> deserialized = []
<add> for value in obj:
<add> if value in custom_objects:
<add> deserialized.append(custom_objects[value])
<add> else:
<add> deserialized.append(value)
<add> return deserialized
<add> if type(obj) is dict:
<add> deserialized = {}
<add> for key, value in obj.items():
<add> if value in custom_objects:
<add> deserialized[key] = custom_objects[value]
<add> else:
<add> deserialized[key] = value
<add> return deserialized
<add> if obj in custom_objects:
<add> return custom_objects[obj]
<add> return obj
<add>
<add> import h5py
<add> f = h5py.File(filepath, mode='r')
<add>
<add> # instantiate model
<add> model_config = f.attrs.get('model_config')
<add> if model_config is None:
<add> raise ValueError('No model found in config file.')
<add> model_config = json.loads(model_config.decode('utf-8'))
<add> model = model_from_config(model_config, custom_objects=custom_objects)
<add>
<add> # set weights
<add> model.load_weights_from_hdf5_group(f['model_weights'])
<add>
<add> # instantiate optimizer
<add> training_config = f.attrs.get('training_config')
<add> if training_config is None:
<add> warnings.warn('No training configuration found in save file: '
<add> 'the model was *not* compiled. Compile it manually.')
<add> f.close()
<add> return model
<add> training_config = json.loads(training_config.decode('utf-8'))
<add> optimizer_config = training_config['optimizer_config']
<add> optimizer = optimizer_from_config(optimizer_config)
<add>
<add> # recover loss functions and metrics
<add> loss = deserialize(training_config['loss'])
<add> metrics = deserialize(training_config['metrics'])
<add> sample_weight_mode = training_config['sample_weight_mode']
<add> loss_weights = training_config['loss_weights']
<add>
<add> # compile model
<add> model.compile(optimizer=optimizer,
<add> loss=loss,
<add> metrics=metrics,
<add> loss_weights=loss_weights,
<add> sample_weight_mode=sample_weight_mode)
<add>
<add> # set optimizer weights
<add> if 'optimizer_weights' in f:
<add> # build train function (to get weight updates)
<add> if model.__class__.__name__ == 'Sequential':
<add> model.model._make_train_function()
<add> else:
<add> model._make_train_function()
<add> optimizer_weights_group = f['optimizer_weights']
<add> optimizer_weight_names = [n.decode('utf8') for n in optimizer_weights_group.attrs['weight_names']]
<add> optimizer_weight_values = [optimizer_weights_group[n] for n in optimizer_weight_names]
<add> model.optimizer.set_weights(optimizer_weight_values)
<add> f.close()
<add> return model
<add>
<add>
<ide> def model_from_config(config, custom_objects={}):
<ide> from keras.utils.layer_utils import layer_from_config
<ide> if isinstance(config, list):
<ide> def compile(self, optimizer, loss,
<ide> **kwargs)
<ide> self.optimizer = self.model.optimizer
<ide> self.loss = self.model.loss
<add> self.loss_weights = self.model.loss_weights
<add> self.metrics = self.model.metrics
<add> self.metrics_tensors = self.model.metrics_tensors
<ide> self.metrics_names = self.model.metrics_names
<ide> self.sample_weight_mode = self.model.sample_weight_mode
<ide>
<ide><path>keras/optimizers.py
<ide> from __future__ import absolute_import
<ide> from . import backend as K
<del>import numpy as np
<ide> from .utils.generic_utils import get_from_module
<ide> from six.moves import zip
<ide>
<ide> def clip_norm(g, c, n):
<ide> return g
<ide>
<ide>
<del>def kl_divergence(p, p_hat):
<del> return p_hat - p + p * K.log(p / p_hat)
<add>def optimizer_from_config(config, custom_objects={}):
<add> all_classes = {
<add> 'sgd': SGD,
<add> 'rmsprop': RMSprop,
<add> 'adagrad': Adagrad,
<add> 'adadelta': Adadelta,
<add> 'adam': Adam,
<add> 'adamax': Adamax,
<add> 'nadam': Nadam,
<add> }
<add> class_name = config['class_name']
<add> if class_name in custom_objects:
<add> cls = custom_objects[class_name]
<add> else:
<add> if class_name.lower() not in all_classes:
<add> raise ValueError('Optimizer class not found:', class_name)
<add> cls = all_classes[class_name.lower()]
<add> return cls.from_config(config['config'])
<ide>
<ide>
<ide> class Optimizer(object):
<ide> def get_weights(self):
<ide> return K.batch_get_value(self.weights)
<ide>
<ide> def get_config(self):
<del> config = {'name': self.__class__.__name__}
<add> config = {}
<ide> if hasattr(self, 'clipnorm'):
<ide> config['clipnorm'] = self.clipnorm
<ide> if hasattr(self, 'clipvalue'):
<ide> config['clipvalue'] = self.clipvalue
<ide> return config
<ide>
<add> @classmethod
<add> def from_config(cls, config):
<add> return cls(**config)
<add>
<ide>
<ide> class SGD(Optimizer):
<ide> '''Stochastic gradient descent, with support for momentum,
<ide><path>keras/utils/io_utils.py
<ide> from __future__ import absolute_import
<add>from __future__ import print_function
<ide> import h5py
<ide> import numpy as np
<add>import sys
<ide> from collections import defaultdict
<ide>
<ide>
<ide> def load_array(name):
<ide> a[:] = array[:]
<ide> f.close()
<ide> return a
<add>
<add>
<add>def ask_to_proceed_with_overwrite(filepath):
<add> get_input = input
<add> if sys.version_info[:2] <= (2, 7):
<add> get_input = raw_input
<add> overwrite = get_input('[WARNING] %s already exists - overwrite? '
<add> '[y/n]' % (filepath))
<add> while overwrite not in ['y', 'n']:
<add> overwrite = get_input('Enter "y" (overwrite) or "n" (cancel).')
<add> if overwrite == 'n':
<add> return False
<add> print('[TIP] Next time specify overwrite=True!')
<add> return True
<ide><path>tests/test_loss_masking.py
<ide> from keras.models import Sequential
<ide> from keras.engine.training import weighted_objective
<ide> from keras.layers.core import TimeDistributedDense, Masking
<add>from keras.utils.test_utils import keras_test
<ide> from keras import objectives
<ide> from keras import backend as K
<ide>
<ide>
<add>@keras_test
<ide> def test_masking():
<ide> np.random.seed(1337)
<ide> X = np.array([[[1], [1]],
<ide> def test_masking():
<ide> assert loss == 0
<ide>
<ide>
<add>@keras_test
<ide> def test_loss_masking():
<ide> weighted_loss = weighted_objective(objectives.get('mae'))
<ide> shape = (3, 4, 2)
<ide><path>tests/test_loss_weighting.py
<ide> from keras.models import Sequential, Graph
<ide> from keras.layers import Dense, Activation, RepeatVector, TimeDistributedDense, GRU
<ide> from keras.utils import np_utils
<add>from keras.utils.test_utils import keras_test
<ide>
<ide> nb_classes = 10
<ide> batch_size = 128
<ide> def create_temporal_sequential_model():
<ide> return model
<ide>
<ide>
<add>@keras_test
<ide> def _test_weights_sequential(model, class_weight=None, sample_weight=None,
<ide> X_train=X_train, Y_train=Y_train,
<ide> X_test=X_test, Y_test=Y_test):
<ide> def _test_weights_sequential(model, class_weight=None, sample_weight=None,
<ide> standard_score_sequential = _test_weights_sequential(model)
<ide>
<ide>
<add>@keras_test
<ide> def test_sequential_class_weights():
<ide> model = create_sequential_model()
<ide> model.compile(loss=loss, optimizer='rmsprop')
<ide> score = _test_weights_sequential(model, class_weight=class_weight)
<ide> assert(score < standard_score_sequential)
<ide>
<ide>
<add>@keras_test
<ide> def test_sequential_sample_weights():
<ide> model = create_sequential_model()
<ide> model.compile(loss=loss, optimizer='rmsprop')
<ide> score = _test_weights_sequential(model, sample_weight=sample_weight)
<ide> assert(score < standard_score_sequential)
<ide>
<ide>
<add>@keras_test
<ide> def test_sequential_temporal_sample_weights():
<ide> model = create_temporal_sequential_model()
<ide> model.compile(loss=loss, optimizer='rmsprop',
<ide><path>tests/test_model_saving.py
<add>import pytest
<add>import numpy as np
<add>from numpy.testing import assert_allclose
<add>
<add>from keras.models import Model, Sequential
<add>from keras.layers import Dense, Dropout, RepeatVector, TimeDistributed
<add>from keras.layers import Input
<add>from keras import optimizers
<add>from keras import objectives
<add>from keras import metrics
<add>from keras.utils.test_utils import keras_test
<add>from keras.models import save_model, load_model
<add>
<add>
<add>@keras_test
<add>def test_sequential_model_saving():
<add> model = Sequential()
<add> model.add(Dense(2, input_dim=3))
<add> model.add(Dense(3))
<add> model.compile(loss='mse', optimizer='sgd', metrics=['acc'])
<add>
<add> x = np.random.random((1, 3))
<add> y = np.random.random((1, 3))
<add> model.train_on_batch(x, y)
<add>
<add> out = model.predict(x)
<add> fname = 'tmp_' + str(np.random.randint(10000)) + '.h5'
<add> save_model(model, fname)
<add>
<add> new_model = load_model(fname)
<add> out2 = new_model.predict(x)
<add> assert_allclose(out, out2)
<add>
<add> # test that new updates are the same with both models
<add> x = np.random.random((1, 3))
<add> y = np.random.random((1, 3))
<add> model.train_on_batch(x, y)
<add> new_model.train_on_batch(x, y)
<add> out = model.predict(x)
<add> out2 = new_model.predict(x)
<add> assert_allclose(out, out2)
<add>
<add>
<add>@keras_test
<add>def test_sequential_model_saving_2():
<add> # test with funkier config
<add> model = Sequential()
<add> model.add(Dense(2, input_dim=3))
<add> model.add(RepeatVector(3))
<add> model.add(TimeDistributed(Dense(3)))
<add> model.compile(loss=objectives.MSE,
<add> optimizer=optimizers.RMSprop(lr=0.0001),
<add> metrics=[metrics.categorical_accuracy],
<add> sample_weight_mode='temporal')
<add> x = np.random.random((1, 3))
<add> y = np.random.random((1, 3, 3))
<add> model.train_on_batch(x, y)
<add>
<add> out = model.predict(x)
<add> fname = 'tmp_' + str(np.random.randint(10000)) + '.h5'
<add> save_model(model, fname)
<add>
<add> new_model = load_model(fname)
<add> out2 = new_model.predict(x)
<add> assert_allclose(out, out2)
<add>
<add> # test that new updates are the same with both models
<add> x = np.random.random((1, 3))
<add> y = np.random.random((1, 3, 3))
<add> model.train_on_batch(x, y)
<add> new_model.train_on_batch(x, y)
<add> out = model.predict(x)
<add> out2 = new_model.predict(x)
<add> assert_allclose(out, out2)
<add>
<add>
<add>@keras_test
<add>def test_sequential_model_saving_3():
<add> # test with custom optimizer, loss
<add> custom_opt = optimizers.rmsprop
<add> custom_loss = objectives.mse
<add> model = Sequential()
<add> model.add(Dense(2, input_dim=3))
<add> model.add(Dense(3))
<add> model.compile(loss=custom_loss, optimizer=custom_opt(), metrics=['acc'])
<add>
<add> x = np.random.random((1, 3))
<add> y = np.random.random((1, 3))
<add> model.train_on_batch(x, y)
<add>
<add> out = model.predict(x)
<add> fname = 'tmp_' + str(np.random.randint(10000)) + '.h5'
<add> save_model(model, fname)
<add>
<add> model = load_model(fname,
<add> custom_objects={'custom_opt': custom_opt,
<add> 'custom_loss': custom_loss})
<add> out2 = model.predict(x)
<add> assert_allclose(out, out2)
<add>
<add>
<add>@keras_test
<add>def test_fuctional_model_saving():
<add> input = Input(shape=(3,))
<add> x = Dense(2)(input)
<add> output = Dense(3)(x)
<add>
<add> model = Model(input, output)
<add> model.compile(loss=objectives.MSE,
<add> optimizer=optimizers.RMSprop(lr=0.0001),
<add> metrics=[metrics.categorical_accuracy])
<add> x = np.random.random((1, 3))
<add> y = np.random.random((1, 3))
<add> model.train_on_batch(x, y)
<add>
<add> out = model.predict(x)
<add> fname = 'tmp_' + str(np.random.randint(10000)) + '.h5'
<add> save_model(model, fname)
<add>
<add> model = load_model(fname)
<add> out2 = model.predict(x)
<add> assert_allclose(out, out2)
<add>
<add>
<add>@keras_test
<add>def test_saving_without_compilation():
<add> model = Sequential()
<add> model.add(Dense(2, input_dim=3))
<add> model.add(Dense(3))
<add> model.compile(loss='mse', optimizer='sgd', metrics=['acc'])
<add>
<add> fname = 'tmp_' + str(np.random.randint(10000)) + '.h5'
<add> save_model(model, fname)
<add> model = load_model(fname)
<add>
<add>
<add>@keras_test
<add>def test_saving_right_after_compilation():
<add> model = Sequential()
<add> model.add(Dense(2, input_dim=3))
<add> model.add(Dense(3))
<add> model.compile(loss='mse', optimizer='sgd', metrics=['acc'])
<add> model.model._make_train_function()
<add>
<add> fname = 'tmp_' + str(np.random.randint(10000)) + '.h5'
<add> save_model(model, fname)
<add> model = load_model(fname)
<add>
<add>
<add>if __name__ == '__main__':
<add> pytest.main([__file__]) | 9 |
Text | Text | remove empty block from console.timeend() example | 8997bd8af279b532bbf61960ee0b8607cc2c5707 | <ide><path>doc/api/console.md
<ide> Stops a timer that was previously started by calling [`console.time()`][] and
<ide> prints the result to `stdout`:
<ide>
<ide> ```js
<del>console.time('100-elements');
<del>for (let i = 0; i < 100; i++) {}
<del>console.timeEnd('100-elements');
<del>// prints 100-elements: 225.438ms
<add>console.time('bunch-of-stuff');
<add>// Do a bunch of stuff.
<add>console.timeEnd('bunch-of-stuff');
<add>// Prints: bunch-of-stuff: 225.438ms
<ide> ```
<ide>
<ide> ### `console.timeLog([label][, ...data])` | 1 |
Go | Go | probe what filesystem to use when mounting | 10083f414017636065aa50610f07784738df8e7a | <ide><path>daemon/graphdriver/devmapper/deviceset.go
<ide> func (devices *DeviceSet) MountDevice(hash, path, mountLabel string) error {
<ide>
<ide> var flags uintptr = syscall.MS_MGC_VAL
<ide>
<add> fstype, err := ProbeFsType(info.DevName())
<add> if err != nil {
<add> return err
<add> }
<add>
<ide> mountOptions := label.FormatMountLabel("discard", mountLabel)
<del> err = syscall.Mount(info.DevName(), path, "ext4", flags, mountOptions)
<add> err = syscall.Mount(info.DevName(), path, fstype, flags, mountOptions)
<ide> if err != nil && err == syscall.EINVAL {
<ide> mountOptions = label.FormatMountLabel("", mountLabel)
<del> err = syscall.Mount(info.DevName(), path, "ext4", flags, mountOptions)
<add> err = syscall.Mount(info.DevName(), path, fstype, flags, mountOptions)
<ide> }
<ide> if err != nil {
<ide> return fmt.Errorf("Error mounting '%s' on '%s': %s", info.DevName(), path, err)
<ide><path>daemon/graphdriver/devmapper/mount.go
<ide> package devmapper
<ide>
<ide> import (
<add> "bytes"
<add> "fmt"
<ide> "os"
<ide> "path/filepath"
<ide> "syscall"
<ide> func Mounted(mountpoint string) (bool, error) {
<ide> parentSt := parent.Sys().(*syscall.Stat_t)
<ide> return mntpointSt.Dev != parentSt.Dev, nil
<ide> }
<add>
<add>type probeData struct {
<add> fsName string
<add> magic string
<add> offset uint64
<add>}
<add>
<add>func ProbeFsType(device string) (string, error) {
<add> probes := []probeData{
<add> {"btrfs", "_BHRfS_M", 0x10040},
<add> {"ext4", "\123\357", 0x438},
<add> {"xfs", "XFSB", 0},
<add> }
<add>
<add> maxLen := uint64(0)
<add> for _, p := range probes {
<add> l := p.offset + uint64(len(p.magic))
<add> if l > maxLen {
<add> maxLen = l
<add> }
<add> }
<add>
<add> file, err := os.Open(device)
<add> if err != nil {
<add> return "", err
<add> }
<add>
<add> buffer := make([]byte, maxLen)
<add> l, err := file.Read(buffer)
<add> if err != nil {
<add> return "", err
<add> }
<add> file.Close()
<add> if uint64(l) != maxLen {
<add> return "", fmt.Errorf("unable to detect filesystem type of %s, short read", device)
<add> }
<add>
<add> for _, p := range probes {
<add> if bytes.Equal([]byte(p.magic), buffer[p.offset:p.offset+uint64(len(p.magic))]) {
<add> return p.fsName, nil
<add> }
<add> }
<add>
<add> return "", fmt.Errorf("Unknown filesystem type on %s", device)
<add>} | 2 |
Javascript | Javascript | simplify glyph segment writing code | e97f74f6e3a1462c2314b4442189d7feddbce66b | <ide><path>fonts.js
<ide> var Font = (function () {
<ide> var bias = 0;
<ide> for (var i = 0; i < segCount - 1; i++) {
<ide> var range = ranges[i];
<del> var start = FontsUtils.integerToBytes(range[0], 2);
<del> var end = FontsUtils.integerToBytes(range[1], 2);
<add> var start = range[0];
<add> var end = range[1];
<add> var delta = (((start - 1) - bias) ^ 0xffff) + 1;
<add> bias += (end - start + 1);
<ide>
<del> var delta = FontsUtils.integerToBytes(((range[0] - 1) - bias) % 65536, 2);
<del> bias += (range[1] - range[0] + 1);
<del>
<del> // deltas are signed shorts
<del> delta[0] ^= 0xFF;
<del> delta[1] ^= 0xFF;
<del> delta[1] += 1;
<add> var start = FontsUtils.integerToBytes(start, 2);
<add> var end = FontsUtils.integerToBytes(end, 2);
<add> var delta = FontsUtils.integerToBytes(delta, 2);
<ide>
<ide> startCount.push(start[0], start[1]);
<ide> endCount.push(end[0], end[1]);
<ide> idDeltas.push(delta[0], delta[1]);
<ide> idRangeOffsets.push(0x00, 0x00);
<ide>
<del> for (var j = range[0]; j <= range[1]; j++)
<add> for (var j = start; j <= end; j++)
<ide> glyphsIdsArray.push(j);
<ide> }
<ide> startCount.push(0xFF, 0xFF); | 1 |
Go | Go | remove solaris left-over | d33428f0bf3638b3cef0d8095972cc660383e2c8 | <ide><path>pkg/system/stat_solaris.go
<del>package system // import "github.com/docker/docker/pkg/system"
<del>
<del>import "syscall"
<del>
<del>// fromStatT converts a syscall.Stat_t type to a system.Stat_t type
<del>func fromStatT(s *syscall.Stat_t) (*StatT, error) {
<del> return &StatT{size: s.Size,
<del> mode: s.Mode,
<del> uid: s.Uid,
<del> gid: s.Gid,
<del> rdev: s.Rdev,
<del> mtim: s.Mtim}, nil
<del>} | 1 |
Ruby | Ruby | add test for keg#mach_o_files hardlink behavior." | 70ceb851a596c4f40ccfb448d543bb5eb5089b4a | <ide><path>Library/Homebrew/test/test_keg.rb
<ide> def test_removes_broken_symlinks_that_conflict_with_directories
<ide> keg.unlink
<ide> keg.uninstall
<ide> end
<del>
<del> def test_mach_o_files_skips_hardlinks
<del> a = HOMEBREW_CELLAR.join("a", "1.0")
<del> a.join("lib").mkpath
<del> FileUtils.cp dylib_path("i386"), a.join("lib", "i386.dylib")
<del> FileUtils.ln a.join("lib", "i386.dylib"), a.join("lib", "i386_link.dylib")
<del>
<del> keg = Keg.new(a)
<del> keg.link
<del>
<del> assert_equal 1, keg.mach_o_files.size
<del> ensure
<del> keg.unlink
<del> keg.uninstall
<del> end
<ide> end
<ide><path>Library/Homebrew/test/test_mach.rb
<ide> require "testing_env"
<ide>
<ide> class MachOPathnameTests < Homebrew::TestCase
<add> def dylib_path(name)
<add> Pathname.new("#{TEST_DIRECTORY}/mach/#{name}.dylib")
<add> end
<add>
<add> def bundle_path(name)
<add> Pathname.new("#{TEST_DIRECTORY}/mach/#{name}.bundle")
<add> end
<add>
<ide> def test_fat_dylib
<ide> pn = dylib_path("fat")
<ide> assert_predicate pn, :universal?
<ide><path>Library/Homebrew/test/testing_env.rb
<ide> def refute_eql(exp, act, msg = nil)
<ide> }
<ide> refute exp.eql?(act), msg
<ide> end
<del>
<del> def dylib_path(name)
<del> Pathname.new("#{TEST_DIRECTORY}/mach/#{name}.dylib")
<del> end
<del>
<del> def bundle_path(name)
<del> Pathname.new("#{TEST_DIRECTORY}/mach/#{name}.bundle")
<del> end
<ide> end
<ide> end | 3 |
PHP | PHP | fix cs error | a7f4af32283bd7290e06d180cbf811ce3d82f912 | <ide><path>src/View/Widget/SelectBoxWidget.php
<ide> * This class is intended as an internal implementation detail
<ide> * of Cake\View\Helper\FormHelper and is not intended for direct use.
<ide> */
<del>class SelectBoxWidget extends BasicWidget
<add>class SelectBoxWidget extends BasicWidget
<ide> {
<ide>
<ide> /** | 1 |
Ruby | Ruby | require yaml for isolation test | 109e71d2bb6d2305a091fe7ea96d4f6e9c7cd52d | <ide><path>activemodel/test/cases/serializers/xml_serialization_test.rb
<ide> require 'models/contact'
<ide> require 'active_support/core_ext/object/instance_variables'
<ide> require 'ostruct'
<add>require 'yaml'
<ide>
<ide> module Admin
<ide> class Contact < ::Contact | 1 |
Javascript | Javascript | replace common.fixturesdir w/ fixtures.path | 85a5a2c228594005280d4b7cd70741eae575a490 | <ide><path>test/parallel/test-tls-connect-secure-context.js
<ide> 'use strict';
<del>const common = require('../common');
<add>require('../common');
<ide>
<ide> // Verify connection with explicitly created client SecureContext.
<ide>
<del>const join = require('path').join;
<add>const fixtures = require('../common/fixtures');
<ide> const {
<ide> assert, connect, keys, tls
<del>} = require(join(common.fixturesDir, 'tls-connect'));
<add>} = require(fixtures.path('tls-connect'));
<ide>
<ide> connect({
<ide> client: { | 1 |
PHP | PHP | update phpdoc return values | d88b4c7374b8caf0c7eccafe7fdc5e15bfb6b7c8 | <ide><path>src/Illuminate/Foundation/Auth/ResetsPasswords.php
<ide> public function showResetForm(Request $request, $token = null)
<ide> * Reset the given user's password.
<ide> *
<ide> * @param \Illuminate\Http\Request $request
<del> * @return \Illuminate\Http\Response
<add> * @return \Illuminate\Http\RedirectResponse
<ide> */
<ide> public function reset(Request $request)
<ide> {
<ide> protected function resetPassword($user, $password)
<ide> * Get the response for a successful password reset.
<ide> *
<ide> * @param string $response
<del> * @return \Illuminate\Http\Response
<add> * @return \Illuminate\Http\RedirectResponse
<ide> */
<ide> protected function sendResetResponse($response)
<ide> {
<ide><path>src/Illuminate/Foundation/Auth/SendsPasswordResetEmails.php
<ide> public function sendResetLinkEmail(Request $request)
<ide> * Get the response for a successful password reset link.
<ide> *
<ide> * @param string $response
<del> * @return \Illuminate\Http\Response
<add> * @return \Illuminate\Http\RedirectResponse
<ide> */
<ide> protected function sendResetLinkResponse($response)
<ide> { | 2 |
Javascript | Javascript | remove output message in test cases | 264aa3a5c8df60712b1411e88885833ceb9cf477 | <ide><path>test/configCases/dll-plugin/0-issue-10475/node_modules/test-package/index.js
<ide> import * as _constants from './constants';
<ide> export var constants = _constants;
<ide> export { default as someFunction } from './someFunction';
<ide>
<del>console.log(constants);
<add>if(Math.random() < 0) console.log(constants); | 1 |
Python | Python | update on_finish from async to sync | e0f6a3928ec386e3b9f4277d82aa4a8f5da36cdd | <ide><path>official/utils/logs/logger.py
<ide> def log_run_info(self, model_name, dataset_name, run_params, test_id=None):
<ide> RUN_STATUS_RUNNING))
<ide>
<ide> def on_finish(self, status):
<del> thread.start_new_thread(
<del> self._bigquery_uploader.update_run_status,
<del> (self._bigquery_data_set,
<del> self._bigquery_run_status_table,
<del> self._run_id,
<del> status))
<add> self._bigquery_uploader.update_run_status(
<add> self._bigquery_data_set,
<add> self._bigquery_run_status_table,
<add> self._run_id,
<add> status)
<ide>
<ide>
<ide> def _gather_run_info(model_name, dataset_name, run_params, test_id): | 1 |
Python | Python | remove print statement | 4e48862fa8a8a25fe7a03fd6c3b01269262463fb | <ide><path>spacy/en/language_data.py
<ide> def get_time_exc(hours):
<ide> {ORTH: hour},
<ide> {ORTH: "pm", LEMMA: "p.m."}
<ide> ]
<del> print(exc)
<ide> return exc
<ide>
<ide> | 1 |
Python | Python | improve test for the next_execution cli command | e9ecf0ae10dffcd9ccaf22cc9f19f140fbc5ee55 | <ide><path>tests/cli/commands/test_dag_command.py
<ide> import contextlib
<ide> import io
<ide> import os
<del>import subprocess
<ide> import tempfile
<ide> import unittest
<ide> from datetime import datetime, time, timedelta
<ide> from airflow.cli.commands import dag_command
<ide> from airflow.exceptions import AirflowException
<ide> from airflow.models import DagBag, DagModel, DagRun
<del>from airflow.settings import Session
<ide> from airflow.utils import timezone
<add>from airflow.utils.session import create_session
<ide> from airflow.utils.state import State
<add>from airflow.utils.types import DagRunType
<ide> from tests.test_utils.config import conf_vars
<ide>
<ide> dag_folder_path = '/'.join(os.path.realpath(__file__).split('/')[:-1])
<ide> def test_cli_backfill_depends_on_past_backwards(self, mock_run):
<ide> verbose=False,
<ide> )
<ide>
<del> @pytest.mark.quarantined
<ide> def test_next_execution(self):
<del> # A scaffolding function
<del> def reset_dr_db(dag_id):
<del> session = Session()
<del> dr = session.query(DagRun).filter_by(dag_id=dag_id)
<del> dr.delete()
<del> session.commit()
<del> session.close()
<del>
<ide> dag_ids = ['example_bash_operator', # schedule_interval is '0 0 * * *'
<ide> 'latest_only', # schedule_interval is timedelta(hours=4)
<ide> 'example_python_operator', # schedule_interval=None
<ide> 'example_xcom'] # schedule_interval="@once"
<ide>
<add> # Delete DagRuns
<add> with create_session() as session:
<add> dr = session.query(DagRun).filter(DagRun.dag_id.in_(dag_ids))
<add> dr.delete(synchronize_session=False)
<add>
<add> args = self.parser.parse_args(['dags',
<add> 'next_execution',
<add> dag_ids[0]])
<add>
<add> with contextlib.redirect_stdout(io.StringIO()) as temp_stdout:
<add> dag_command.dag_next_execution(args)
<add> out = temp_stdout.getvalue()
<add> # `next_execution` function is inapplicable if no execution record found
<add> # It prints `None` in such cases
<add> self.assertIn("None", out)
<add>
<ide> # The details below is determined by the schedule_interval of example DAGs
<del> now = timezone.utcnow()
<add> now = DEFAULT_DATE
<ide> next_execution_time_for_dag1 = pytz.utc.localize(
<ide> datetime.combine(
<ide> now.date() + timedelta(days=1),
<ide> def reset_dr_db(dag_id):
<ide> "None",
<ide> "None"]
<ide>
<del> for i in range(len(dag_ids)): # pylint: disable=consider-using-enumerate
<del> dag_id = dag_ids[i]
<del>
<del> # Clear dag run so no execution history fo each DAG
<del> reset_dr_db(dag_id)
<del>
<del> proc = subprocess.Popen(["airflow", "dags", "next_execution", dag_id,
<del> "--subdir", EXAMPLE_DAGS_FOLDER],
<del> stdout=subprocess.PIPE)
<del> proc.wait()
<del> stdout = []
<del> for line in proc.stdout:
<del> stdout.append(str(line.decode("utf-8").rstrip()))
<del>
<del> # `next_execution` function is inapplicable if no execution record found
<del> # It prints `None` in such cases
<del> self.assertEqual(stdout[-1], "None")
<add> for i, dag_id in enumerate(dag_ids):
<add> args = self.parser.parse_args(['dags',
<add> 'next_execution',
<add> dag_id])
<ide>
<ide> dag = self.dagbag.dags[dag_id]
<ide> # Create a DagRun for each DAG, to prepare for next step
<ide> dag.create_dagrun(
<del> run_id='manual__' + now.isoformat(),
<add> run_id=DagRunType.MANUAL.value,
<ide> execution_date=now,
<ide> start_date=now,
<ide> state=State.FAILED
<ide> )
<ide>
<del> proc = subprocess.Popen(["airflow", "dags", "next_execution", dag_id,
<del> "--subdir", EXAMPLE_DAGS_FOLDER],
<del> stdout=subprocess.PIPE)
<del> proc.wait()
<del> stdout = []
<del> for line in proc.stdout:
<del> stdout.append(str(line.decode("utf-8").rstrip()))
<del> self.assertEqual(stdout[-1], expected_output[i])
<add> with contextlib.redirect_stdout(io.StringIO()) as temp_stdout:
<add> dag_command.dag_next_execution(args)
<add> out = temp_stdout.getvalue()
<add> self.assertIn(expected_output[i], out)
<ide>
<del> reset_dr_db(dag_id)
<add> # Clean up before leaving
<add> with create_session() as session:
<add> dr = session.query(DagRun).filter(DagRun.dag_id.in_(dag_ids))
<add> dr.delete(synchronize_session=False)
<ide>
<ide> @conf_vars({
<ide> ('core', 'load_examples'): 'true' | 1 |
Python | Python | avoid url error exception | aa8d7f76a047b24a97614524d29fb5070cf549c7 | <ide><path>keras/utils/data_utils.py
<ide> def dl_progress(count, block_size, total_size):
<ide> try:
<ide> try:
<ide> urlretrieve(origin, fpath, dl_progress)
<del> except URLError as e:
<del> raise Exception(error_msg.format(origin, e.errno, e.reason))
<ide> except HTTPError as e:
<ide> raise Exception(error_msg.format(origin, e.code, e.msg))
<add> except URLError as e:
<add> raise Exception(error_msg.format(origin, e.errno, e.reason))
<ide> except (Exception, KeyboardInterrupt):
<ide> if os.path.exists(fpath):
<ide> os.remove(fpath) | 1 |
Java | Java | register runtime hints for @testexecutionlisteners | cced3cba0925b3c5e4f1754a514595511fa15004 | <ide><path>spring-test/src/main/java/org/springframework/test/context/aot/TestContextAotGenerator.java
<ide> MergedContextConfiguration buildMergedContextConfiguration(Class<?> testClass) {
<ide> TestContextBootstrapper testContextBootstrapper =
<ide> BootstrapUtils.resolveTestContextBootstrapper(testClass);
<ide> registerDeclaredConstructors(testContextBootstrapper.getClass());
<add> testContextBootstrapper.getTestExecutionListeners().stream()
<add> .map(Object::getClass)
<add> .forEach(this::registerDeclaredConstructors);
<ide> return testContextBootstrapper.buildMergedContextConfiguration();
<ide> }
<ide>
<ide><path>spring-test/src/test/java/org/springframework/test/context/aot/TestContextAotGeneratorTests.java
<ide> private static void assertRuntimeHints(RuntimeHints runtimeHints) {
<ide>
<ide> // TestExecutionListener
<ide> Stream.of(
<add> org.springframework.test.context.aot.samples.basic.BasicSpringJupiterTests.DummyTestExecutionListener.class,
<ide> org.springframework.test.context.event.ApplicationEventsTestExecutionListener.class,
<ide> org.springframework.test.context.event.EventPublishingTestExecutionListener.class,
<ide> org.springframework.test.context.jdbc.SqlScriptsTestExecutionListener.class,
<ide><path>spring-test/src/test/java/org/springframework/test/context/aot/samples/basic/BasicSpringJupiterTests.java
<ide> import org.springframework.beans.factory.annotation.Autowired;
<ide> import org.springframework.beans.factory.annotation.Value;
<ide> import org.springframework.context.ApplicationContext;
<add>import org.springframework.test.context.TestExecutionListeners;
<ide> import org.springframework.test.context.TestPropertySource;
<add>import org.springframework.test.context.aot.samples.basic.BasicSpringJupiterTests.DummyExtension;
<add>import org.springframework.test.context.aot.samples.basic.BasicSpringJupiterTests.DummyTestExecutionListener;
<ide> import org.springframework.test.context.aot.samples.common.MessageService;
<ide> import org.springframework.test.context.junit.jupiter.SpringJUnitConfig;
<add>import org.springframework.test.context.support.AbstractTestExecutionListener;
<ide>
<ide> import static org.assertj.core.api.Assertions.assertThat;
<add>import static org.springframework.test.context.TestExecutionListeners.MergeMode.MERGE_WITH_DEFAULTS;
<ide>
<ide> /**
<ide> * @author Sam Brannen
<ide> // for repeated annotations.
<ide> @ExtendWith(DummyExtension.class)
<ide> @SpringJUnitConfig(BasicTestConfiguration.class)
<add>@TestExecutionListeners(listeners = DummyTestExecutionListener.class, mergeMode = MERGE_WITH_DEFAULTS)
<ide> @TestPropertySource(properties = "test.engine = jupiter")
<ide> public class BasicSpringJupiterTests {
<ide>
<ide> void test(@Autowired ApplicationContext context, @Autowired MessageService messa
<ide>
<ide> }
<ide>
<del>}
<add> static class DummyExtension implements Extension {
<add> }
<add>
<add> public static class DummyTestExecutionListener extends AbstractTestExecutionListener {
<add> }
<ide>
<del>class DummyExtension implements Extension {
<ide> }
<add> | 3 |
Ruby | Ruby | fix env typo | 3589e24df03adc074081549229d8cc244643eee4 | <ide><path>Library/Homebrew/tap.rb
<ide> def read_or_set_private_config
<ide> # A specialized {Tap} class for the core formulae
<ide> class CoreTap < Tap
<ide> def default_remote
<del> if OS.mac? || ENV["$HOMEBREW_FORCE_HOMEBREW_ORG"]
<add> if OS.mac? || ENV["HOMEBREW_FORCE_HOMEBREW_ORG"]
<ide> "https://github.com/Homebrew/homebrew-core".freeze
<ide> else
<ide> "https://github.com/Linuxbrew/homebrew-core".freeze | 1 |
PHP | PHP | improve parameter type of `destroy()` | 1b90dc48d4e9d020569d63eef142cbf14e0c824d | <ide><path>src/Illuminate/Database/Eloquent/Model.php
<ide> protected function insertAndSetId(Builder $query, $attributes)
<ide> /**
<ide> * Destroy the models for the given IDs.
<ide> *
<del> * @param \Illuminate\Support\Collection|array|int $ids
<add> * @param \Illuminate\Support\Collection|array|int|string $ids
<ide> * @return int
<ide> */
<ide> public static function destroy($ids) | 1 |
Javascript | Javascript | update example to use a module | 282ed94cf99ebf12af19ac63004ffeceabcbfe4d | <ide><path>src/Angular.js
<ide> function isLeafNode (node) {
<ide> * @returns {*} The copy or updated `destination`, if `destination` was specified.
<ide> *
<ide> * @example
<del> <example>
<add> <example module="copyExample">
<ide> <file name="index.html">
<del> <div ng-controller="Controller">
<add> <div ng-controller="ExampleController">
<ide> <form novalidate class="simple-form">
<ide> Name: <input type="text" ng-model="user.name" /><br />
<ide> E-mail: <input type="email" ng-model="user.email" /><br />
<ide> function isLeafNode (node) {
<ide> </div>
<ide>
<ide> <script>
<del> function Controller($scope) {
<del> $scope.master= {};
<add> angular.module('copyExample')
<add> .controller('ExampleController', ['$scope', function($scope) {
<add> $scope.master= {};
<ide>
<del> $scope.update = function(user) {
<del> // Example with 1 argument
<del> $scope.master= angular.copy(user);
<del> };
<add> $scope.update = function(user) {
<add> // Example with 1 argument
<add> $scope.master= angular.copy(user);
<add> };
<ide>
<del> $scope.reset = function() {
<del> // Example with 2 arguments
<del> angular.copy($scope.master, $scope.user);
<del> };
<add> $scope.reset = function() {
<add> // Example with 2 arguments
<add> angular.copy($scope.master, $scope.user);
<add> };
<ide>
<del> $scope.reset();
<del> }
<add> $scope.reset();
<add> }]);
<ide> </script>
<ide> </file>
<ide> </example> | 1 |
Java | Java | retain order of active profiles in the tcf | 68a704373dfcc3438eabb98f0767aed9cec4f95b | <ide><path>spring-test/src/main/java/org/springframework/test/context/MergedContextConfiguration.java
<ide> /*
<del> * Copyright 2002-2014 the original author or authors.
<add> * Copyright 2002-2015 the original author or authors.
<ide> *
<ide> * Licensed under the Apache License, Version 2.0 (the "License");
<ide> * you may not use this file except in compliance with the License.
<ide> import java.io.Serializable;
<ide> import java.util.Arrays;
<ide> import java.util.Collections;
<add>import java.util.LinkedHashSet;
<ide> import java.util.Set;
<del>import java.util.SortedSet;
<del>import java.util.TreeSet;
<ide>
<ide> import org.springframework.context.ApplicationContext;
<ide> import org.springframework.context.ApplicationContextInitializer;
<ide> * <p>A {@link SmartContextLoader} uses {@code MergedContextConfiguration}
<ide> * to load an {@link org.springframework.context.ApplicationContext ApplicationContext}.
<ide> *
<del> * <p>{@code MergedContextConfiguration} is also used by the {@link TestContext}
<del> * as the context cache key for caching an
<add> * <p>{@code MergedContextConfiguration} is also used by the
<add> * {@link org.springframework.test.context.cache.ContextCache ContextCache}
<add> * as the key for caching an
<ide> * {@link org.springframework.context.ApplicationContext ApplicationContext}
<ide> * that was loaded using properties of this {@code MergedContextConfiguration}.
<ide> *
<ide> private static String[] processActiveProfiles(String[] activeProfiles) {
<ide> return EMPTY_STRING_ARRAY;
<ide> }
<ide>
<del> // Active profiles must be unique and sorted in order to support proper
<del> // cache key generation. Specifically, profile sets {foo,bar} and
<del> // {bar,foo} must both result in the same array (e.g., [bar,foo]).
<del> SortedSet<String> sortedProfilesSet = new TreeSet<String>(Arrays.asList(activeProfiles));
<del> return StringUtils.toStringArray(sortedProfilesSet);
<add> // Active profiles must be unique
<add> Set<String> profilesSet = new LinkedHashSet<String>(Arrays.asList(activeProfiles));
<add> return StringUtils.toStringArray(profilesSet);
<ide> }
<ide>
<ide> /**
<ide><path>spring-test/src/main/java/org/springframework/test/context/support/ActiveProfilesUtils.java
<ide>
<ide> package org.springframework.test.context.support;
<ide>
<del>import java.util.HashSet;
<add>import java.util.ArrayList;
<add>import java.util.Collections;
<add>import java.util.LinkedHashSet;
<add>import java.util.List;
<ide> import java.util.Set;
<ide>
<ide> import org.apache.commons.logging.Log;
<ide> private ActiveProfilesUtils() {
<ide> static String[] resolveActiveProfiles(Class<?> testClass) {
<ide> Assert.notNull(testClass, "Class must not be null");
<ide>
<del> final Set<String> activeProfiles = new HashSet<String>();
<add> final List<String[]> profileArrays = new ArrayList<String[]>();
<ide>
<ide> Class<ActiveProfiles> annotationType = ActiveProfiles.class;
<ide> AnnotationDescriptor<ActiveProfiles> descriptor = MetaAnnotationUtils.findAnnotationDescriptor(testClass,
<ide> static String[] resolveActiveProfiles(Class<?> testClass) {
<ide> throw new IllegalStateException(msg);
<ide> }
<ide>
<add> profileArrays.add(profiles);
<add>
<add> descriptor = (annotation.inheritProfiles() ? MetaAnnotationUtils.findAnnotationDescriptor(
<add> rootDeclaringClass.getSuperclass(), annotationType) : null);
<add> }
<add>
<add> // Reverse the list so that we can traverse "down" the hierarchy.
<add> Collections.reverse(profileArrays);
<add>
<add> final Set<String> activeProfiles = new LinkedHashSet<String>();
<add> for (String[] profiles : profileArrays) {
<ide> for (String profile : profiles) {
<ide> if (StringUtils.hasText(profile)) {
<ide> activeProfiles.add(profile.trim());
<ide> }
<ide> }
<del>
<del> descriptor = (annotation.inheritProfiles() ? MetaAnnotationUtils.findAnnotationDescriptor(
<del> rootDeclaringClass.getSuperclass(), annotationType) : null);
<ide> }
<ide>
<ide> return StringUtils.toStringArray(activeProfiles);
<ide><path>spring-test/src/main/java/org/springframework/test/context/support/DefaultActiveProfilesResolver.java
<ide>
<ide> package org.springframework.test.context.support;
<ide>
<del>import java.util.HashSet;
<add>import java.util.LinkedHashSet;
<ide> import java.util.Set;
<ide>
<ide> import org.apache.commons.logging.Log;
<ide> public class DefaultActiveProfilesResolver implements ActiveProfilesResolver {
<ide> public String[] resolve(Class<?> testClass) {
<ide> Assert.notNull(testClass, "Class must not be null");
<ide>
<del> final Set<String> activeProfiles = new HashSet<String>();
<add> final Set<String> activeProfiles = new LinkedHashSet<String>();
<ide>
<ide> Class<ActiveProfiles> annotationType = ActiveProfiles.class;
<ide> AnnotationDescriptor<ActiveProfiles> descriptor = findAnnotationDescriptor(testClass, annotationType);
<ide><path>spring-test/src/test/java/org/springframework/test/context/MergedContextConfigurationTests.java
<ide> public void hashCodeWithSameProfilesReversed() {
<ide> EMPTY_STRING_ARRAY, EMPTY_CLASS_ARRAY, activeProfiles1, loader);
<ide> MergedContextConfiguration mergedConfig2 = new MergedContextConfiguration(getClass(),
<ide> EMPTY_STRING_ARRAY, EMPTY_CLASS_ARRAY, activeProfiles2, loader);
<del> assertEquals(mergedConfig1.hashCode(), mergedConfig2.hashCode());
<add> assertNotEquals(mergedConfig1.hashCode(), mergedConfig2.hashCode());
<ide> }
<ide>
<ide> @Test
<ide> public void equalsWithSameProfilesReversed() {
<ide> EMPTY_STRING_ARRAY, EMPTY_CLASS_ARRAY, activeProfiles1, loader);
<ide> MergedContextConfiguration mergedConfig2 = new MergedContextConfiguration(getClass(),
<ide> EMPTY_STRING_ARRAY, EMPTY_CLASS_ARRAY, activeProfiles2, loader);
<del> assertEquals(mergedConfig1, mergedConfig2);
<add> assertNotEquals(mergedConfig1, mergedConfig2);
<ide> }
<ide>
<ide> @Test
<ide><path>spring-test/src/test/java/org/springframework/test/context/cache/ContextCacheTests.java
<ide> public void verifyCacheKeyIsBasedOnContextLoader() {
<ide>
<ide> @Test
<ide> public void verifyCacheKeyIsBasedOnActiveProfiles() {
<del> loadCtxAndAssertStats(FooBarProfilesTestCase.class, 1, 0, 1);
<del> loadCtxAndAssertStats(FooBarProfilesTestCase.class, 1, 1, 1);
<del> // Profiles {foo, bar} should hash to the same as {bar,foo}
<del> loadCtxAndAssertStats(BarFooProfilesTestCase.class, 1, 2, 1);
<del> loadCtxAndAssertStats(FooBarProfilesTestCase.class, 1, 3, 1);
<del> loadCtxAndAssertStats(FooBarProfilesTestCase.class, 1, 4, 1);
<del> loadCtxAndAssertStats(BarFooProfilesTestCase.class, 1, 5, 1);
<del> loadCtxAndAssertStats(FooBarActiveProfilesResolverTestCase.class, 1, 6, 1);
<add> int size = 0, hit = 0, miss = 0;
<add> loadCtxAndAssertStats(FooBarProfilesTestCase.class, ++size, hit, ++miss);
<add> loadCtxAndAssertStats(FooBarProfilesTestCase.class, size, ++hit, miss);
<add> // Profiles {foo, bar} should not hash to the same as {bar,foo}
<add> loadCtxAndAssertStats(BarFooProfilesTestCase.class, ++size, hit, ++miss);
<add> loadCtxAndAssertStats(FooBarProfilesTestCase.class, size, ++hit, miss);
<add> loadCtxAndAssertStats(FooBarProfilesTestCase.class, size, ++hit, miss);
<add> loadCtxAndAssertStats(BarFooProfilesTestCase.class, size, ++hit, miss);
<add> loadCtxAndAssertStats(FooBarActiveProfilesResolverTestCase.class, size, ++hit, miss);
<ide> }
<ide>
<ide> @Test
<ide><path>spring-test/src/test/java/org/springframework/test/context/support/AbstractContextConfigurationUtilsTests.java
<ide> /*
<del> * Copyright 2002-2014 the original author or authors.
<add> * Copyright 2002-2015 the original author or authors.
<ide> *
<ide> * Licensed under the Apache License, Version 2.0 (the "License");
<ide> * you may not use this file except in compliance with the License.
<ide> static class MetaLocationsFooWithOverriddenAttributes {
<ide> }
<ide>
<ide> @ContextConfiguration(locations = "/foo.xml", inheritLocations = false)
<del> @ActiveProfiles(profiles = "foo")
<add> @ActiveProfiles("foo")
<ide> static class LocationsFoo {
<ide> }
<ide>
<ide> @ContextConfiguration(classes = FooConfig.class, inheritLocations = false)
<del> @ActiveProfiles(profiles = "foo")
<add> @ActiveProfiles("foo")
<ide> static class ClassesFoo {
<ide> }
<ide>
<ide> static class OverriddenClassesBar extends ClassesFoo {
<ide> }
<ide>
<ide> @ContextConfiguration(locations = "/foo.properties", loader = GenericPropertiesContextLoader.class)
<del> @ActiveProfiles(profiles = "foo")
<add> @ActiveProfiles("foo")
<ide> static class PropertiesLocationsFoo {
<ide> }
<ide>
<ide> // Combining @Configuration classes with a Properties based loader doesn't really make
<ide> // sense, but that's OK for unit testing purposes.
<ide> @ContextConfiguration(classes = FooConfig.class, loader = GenericPropertiesContextLoader.class)
<del> @ActiveProfiles(profiles = "foo")
<add> @ActiveProfiles("foo")
<ide> static class PropertiesClassesFoo {
<ide> }
<ide>
<ide><path>spring-test/src/test/java/org/springframework/test/context/support/ActiveProfilesUtilsTests.java
<ide> import java.lang.annotation.Target;
<ide> import java.util.ArrayList;
<ide> import java.util.Arrays;
<del>import java.util.HashSet;
<ide> import java.util.List;
<del>import java.util.Set;
<ide>
<ide> import org.junit.Test;
<ide>
<ide> public class ActiveProfilesUtilsTests extends AbstractContextConfigurationUtilsTests {
<ide>
<ide> private void assertResolvedProfiles(Class<?> testClass, String... expected) {
<del> assertNotNull(testClass);
<del> assertNotNull(expected);
<del> String[] actual = resolveActiveProfiles(testClass);
<del> Set<String> expectedSet = new HashSet<String>(Arrays.asList(expected));
<del> Set<String> actualSet = new HashSet<String>(Arrays.asList(actual));
<del> assertEquals(expectedSet, actualSet);
<add> assertArrayEquals(expected, resolveActiveProfiles(testClass));
<ide> }
<ide>
<ide> @Test
<ide> public void resolveActiveProfilesWithoutAnnotation() {
<del> assertArrayEquals(EMPTY_STRING_ARRAY, resolveActiveProfiles(Enigma.class));
<add> assertResolvedProfiles(Enigma.class, EMPTY_STRING_ARRAY);
<ide> }
<ide>
<ide> @Test
<ide> public void resolveActiveProfilesWithNoProfilesDeclared() {
<del> assertArrayEquals(EMPTY_STRING_ARRAY, resolveActiveProfiles(BareAnnotations.class));
<add> assertResolvedProfiles(BareAnnotations.class, EMPTY_STRING_ARRAY);
<ide> }
<ide>
<ide> @Test
<ide> public void resolveActiveProfilesWithEmptyProfiles() {
<del> assertArrayEquals(EMPTY_STRING_ARRAY, resolveActiveProfiles(EmptyProfiles.class));
<add> assertResolvedProfiles(EmptyProfiles.class, EMPTY_STRING_ARRAY);
<ide> }
<ide>
<ide> @Test
<ide> public void resolveActiveProfilesWithDuplicatedProfiles() {
<ide> assertResolvedProfiles(DuplicatedProfiles.class, "foo", "bar", "baz");
<ide> }
<ide>
<add> @Test
<add> public void resolveActiveProfilesWithLocalAndInheritedDuplicatedProfiles() {
<add> assertResolvedProfiles(ExtendedDuplicatedProfiles.class, "foo", "bar", "baz", "cat", "dog");
<add> }
<add>
<ide> @Test
<ide> public void resolveActiveProfilesWithLocalAnnotation() {
<ide> assertResolvedProfiles(LocationsFoo.class, "foo");
<ide> private static class EmptyProfiles {
<ide> private static class DuplicatedProfiles {
<ide> }
<ide>
<add> @ActiveProfiles({ "cat", "dog", " foo", "bar ", "cat" })
<add> private static class ExtendedDuplicatedProfiles extends DuplicatedProfiles {
<add> }
<add>
<ide> @ActiveProfiles(profiles = { "dog", "cat" }, inheritProfiles = false)
<ide> private static class Animals extends LocationsBar {
<ide> } | 7 |
Javascript | Javascript | remove common.port from multiple tests | 2e5188de928946c81266b149887d9b31111a5267 | <ide><path>test/parallel/test-cluster-master-error.js
<ide> if (cluster.isWorker) {
<ide> const http = require('http');
<ide> http.Server(() => {
<ide>
<del> }).listen(common.PORT, '127.0.0.1');
<add> }).listen(0, '127.0.0.1');
<ide>
<ide> } else if (process.argv[2] === 'cluster') {
<ide>
<ide><path>test/parallel/test-cluster-master-kill.js
<ide> if (cluster.isWorker) {
<ide>
<ide> // keep the worker alive
<ide> const http = require('http');
<del> http.Server().listen(common.PORT, '127.0.0.1');
<add> http.Server().listen(0, '127.0.0.1');
<ide>
<ide> } else if (process.argv[2] === 'cluster') {
<ide>
<ide><path>test/parallel/test-cluster-net-send.js
<ide> if (process.argv[2] !== 'child') {
<ide> socketConnected();
<ide> });
<ide>
<del> server.listen(common.PORT, function() {
<del> socket = net.connect(common.PORT, '127.0.0.1', socketConnected);
<add> server.listen(0, function() {
<add> socket = net.connect(server.address().port, '127.0.0.1', socketConnected);
<ide> });
<ide>
<ide> process.on('disconnect', function() {
<ide><path>test/parallel/test-cluster-rr-domain-listen.js
<ide> if (cluster.isWorker) {
<ide> d.run(common.noop);
<ide>
<ide> const http = require('http');
<del> http.Server(common.noop).listen(common.PORT, '127.0.0.1');
<add> http.Server(common.noop).listen(0, '127.0.0.1');
<ide>
<ide> } else if (cluster.isMaster) {
<ide>
<ide><path>test/parallel/test-cluster-rr-ref.js
<ide> if (cluster.isMaster) {
<ide> });
<ide> } else {
<ide> const server = net.createServer(common.mustNotCall());
<del> server.listen(common.PORT, function() {
<add> server.listen(0, function() {
<ide> server.unref();
<ide> server.ref();
<ide> server.close(function() {
<ide><path>test/parallel/test-cluster-shared-leak.js
<ide> if (cluster.isMaster) {
<ide> let conn, worker2;
<ide>
<ide> const worker1 = cluster.fork();
<del> worker1.on('message', common.mustCall(function() {
<add> worker1.on('listening', common.mustCall(function(address) {
<ide> worker2 = cluster.fork();
<ide> worker2.on('online', function() {
<del> conn = net.connect(common.PORT, common.mustCall(function() {
<add> conn = net.connect(address.port, common.mustCall(function() {
<ide> worker1.disconnect();
<ide> worker2.disconnect();
<ide> }));
<ide> const server = net.createServer(function(c) {
<ide> c.end('bye');
<ide> });
<ide>
<del>server.listen(common.PORT, function() {
<del> process.send('listening');
<del>});
<add>server.listen(0);
<ide><path>test/parallel/test-cluster-worker-no-exit.js
<ide> // USE OR OTHER DEALINGS IN THE SOFTWARE.
<ide>
<ide> 'use strict';
<del>const common = require('../common');
<add>require('../common');
<ide> const assert = require('assert');
<ide> const cluster = require('cluster');
<ide> const net = require('net');
<ide> if (cluster.isMaster) {
<ide> success = true;
<ide> });
<ide>
<del> }).listen(common.PORT, function() {
<add> }).listen(0, function() {
<ide> const port = this.address().port;
<ide>
<ide> worker = cluster.fork() | 7 |
Ruby | Ruby | handle response_body= when body is nil | c4d85dfbc71043e2a746acd310e32f4f04db801a | <ide><path>actionpack/lib/action_controller/metal.rb
<ide> def url_for(string)
<ide> def response_body=(body)
<ide> body = [body] unless body.nil? || body.respond_to?(:each)
<ide> response.reset_body!
<add> return unless body
<ide> body.each { |part|
<ide> next if part.empty?
<ide> response.write part
<ide><path>actionpack/test/controller/new_base/bare_metal_test.rb
<ide> class BareTest < ActiveSupport::TestCase
<ide> end
<ide> end
<ide>
<add> class BareEmptyController < ActionController::Metal
<add> def index
<add> self.response_body = nil
<add> end
<add> end
<add>
<add> class BareEmptyTest < ActiveSupport::TestCase
<add> test "response body is nil" do
<add> controller = BareEmptyController.new
<add> controller.set_request!(ActionDispatch::Request.empty)
<add> controller.set_response!(BareController.make_response!(controller.request))
<add> controller.index
<add> assert_equal nil, controller.response_body
<add> end
<add> end
<add>
<ide> class HeadController < ActionController::Metal
<ide> include ActionController::Head
<ide> | 2 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.