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
|
|---|---|---|---|---|---|
Python
|
Python
|
remove unnecessary test from test set
|
1be8c3588e0bf28bdc26f3c12ec71d754ecc0625
|
<ide><path>numpy/core/tests/test_umath.py
<ide> def check(x, rtol):
<ide>
<ide> x_series = np.logspace(np.log10(info.tiny/eps).real, -3, 200,
<ide> endpoint=False)
<del> x_basic = np.logspace(dtype(-3.).real, -1e-8, 10)
<add> x_basic = np.logspace(dtype(-3.).real, 0, 10, endpoint=False)
<ide>
<ide> check(x_series, 2*eps)
<ide> check(x_basic, 2*eps/1e-3)
| 1
|
Text
|
Text
|
add notebook on fine-tuning bart
|
1f5ea9e04a27171a5034a61999bc6359d19fe4ef
|
<ide><path>docs/source/community.md
<ide> This page regroups resources around 🤗 Transformers developed by the community
<ide> |[Evaluate LED on Arxiv](https://github.com/patrickvonplaten/notebooks/blob/master/LED_on_Arxiv.ipynb) | How to effectively evaluate LED on long-range summarization | [Patrick von Platen](https://github.com/patrickvonplaten) | [](https://colab.research.google.com/github/patrickvonplaten/notebooks/blob/master/LED_on_Arxiv.ipynb)|
<ide> |[Fine-tune LayoutLM on RVL-CDIP (a document image classification dataset)](https://github.com/NielsRogge/Transformers-Tutorials/blob/master/LayoutLM/Fine_tuning_LayoutLMForSequenceClassification_on_RVL_CDIP.ipynb) | How to fine-tune *LayoutLMForSequenceClassification* on the RVL-CDIP dataset for scanned document classification | [Niels Rogge](https://github.com/nielsrogge) | [](https://colab.research.google.com/github/NielsRogge/Transformers-Tutorials/blob/master/LayoutLM/Fine_tuning_LayoutLMForSequenceClassification_on_RVL_CDIP.ipynb)|
<ide> |[Wav2Vec2 CTC decoding with GPT2 adjustment](https://github.com/voidful/huggingface_notebook/blob/main/xlsr_gpt.ipynb) | How to decode CTC sequence with language model adjustment | [Eric Lam](https://github.com/voidful) | [](https://colab.research.google.com/drive/1e_z5jQHYbO2YKEaUgzb1ww1WwiAyydAj?usp=sharing)|
<add>|[Fine-tune BART for summarization in two languages with Trainer class](https://github.com/elsanns/xai-nlp-notebooks/blob/master/fine_tune_bart_summarization_two_langs.ipynb) | How to fine-tune BART for summarization in two languages with Trainer class | [Eliza Szczechla](https://github.com/elsanns) | [](https://colab.research.google.com/github/elsanns/xai-nlp-notebooks/blob/master/fine_tune_bart_summarization_two_langs.ipynb)|
| 1
|
Java
|
Java
|
use modern language features in tests
|
f8a5a8d7be6040e60c21107c14fc394e67e75e6b
|
<ide><path>integration-tests/src/test/java/org/springframework/context/annotation/jsr330/ClassPathBeanDefinitionScannerJsr330ScopeIntegrationTests.java
<ide> /*
<del> * Copyright 2002-2019 the original author or authors.
<add> * Copyright 2002-2022 the original author or authors.
<ide> *
<ide> * Licensed under the Apache License, Version 2.0 (the "License");
<ide> * you may not use this file except in compliance with the License.
<ide> import org.springframework.context.ApplicationContext;
<ide> import org.springframework.context.annotation.ClassPathBeanDefinitionScanner;
<ide> import org.springframework.context.annotation.ScopeMetadata;
<del>import org.springframework.context.annotation.ScopeMetadataResolver;
<ide> import org.springframework.context.annotation.ScopedProxyMode;
<ide> import org.springframework.mock.web.MockHttpServletRequest;
<ide> import org.springframework.mock.web.MockHttpSession;
<ide> private ApplicationContext createContext(final ScopedProxyMode scopedProxyMode)
<ide> GenericWebApplicationContext context = new GenericWebApplicationContext();
<ide> ClassPathBeanDefinitionScanner scanner = new ClassPathBeanDefinitionScanner(context);
<ide> scanner.setIncludeAnnotationConfig(false);
<del> scanner.setScopeMetadataResolver(new ScopeMetadataResolver() {
<del> @Override
<del> public ScopeMetadata resolveScopeMetadata(BeanDefinition definition) {
<del> ScopeMetadata metadata = new ScopeMetadata();
<del> if (definition instanceof AnnotatedBeanDefinition) {
<del> AnnotatedBeanDefinition annDef = (AnnotatedBeanDefinition) definition;
<del> for (String type : annDef.getMetadata().getAnnotationTypes()) {
<del> if (type.equals(javax.inject.Singleton.class.getName())) {
<del> metadata.setScopeName(BeanDefinition.SCOPE_SINGLETON);
<del> break;
<del> }
<del> else if (annDef.getMetadata().getMetaAnnotationTypes(type).contains(javax.inject.Scope.class.getName())) {
<del> metadata.setScopeName(type.substring(type.length() - 13, type.length() - 6).toLowerCase());
<del> metadata.setScopedProxyMode(scopedProxyMode);
<del> break;
<del> }
<del> else if (type.startsWith("javax.inject")) {
<del> metadata.setScopeName(BeanDefinition.SCOPE_PROTOTYPE);
<del> }
<add> scanner.setScopeMetadataResolver(definition -> {
<add> ScopeMetadata metadata = new ScopeMetadata();
<add> if (definition instanceof AnnotatedBeanDefinition) {
<add> AnnotatedBeanDefinition annDef = (AnnotatedBeanDefinition) definition;
<add> for (String type : annDef.getMetadata().getAnnotationTypes()) {
<add> if (type.equals(javax.inject.Singleton.class.getName())) {
<add> metadata.setScopeName(BeanDefinition.SCOPE_SINGLETON);
<add> break;
<add> }
<add> else if (annDef.getMetadata().getMetaAnnotationTypes(type).contains(javax.inject.Scope.class.getName())) {
<add> metadata.setScopeName(type.substring(type.length() - 13, type.length() - 6).toLowerCase());
<add> metadata.setScopedProxyMode(scopedProxyMode);
<add> break;
<add> }
<add> else if (type.startsWith("javax.inject")) {
<add> metadata.setScopeName(BeanDefinition.SCOPE_PROTOTYPE);
<ide> }
<ide> }
<del> return metadata;
<ide> }
<add> return metadata;
<ide> });
<ide>
<ide> // Scan twice in order to find errors in the bean definition compatibility check.
<ide><path>spring-aop/src/test/java/org/springframework/aop/interceptor/ConcurrencyThrottleInterceptorTests.java
<ide> public void run() {
<ide> try {
<ide> this.proxy.exceptional(this.ex);
<ide> }
<del> catch (RuntimeException ex) {
<del> if (ex == this.ex) {
<del> logger.debug("Expected exception thrown", ex);
<del> }
<del> else {
<del> // should never happen
<del> ex.printStackTrace();
<del> }
<del> }
<del> catch (Error err) {
<add> catch (RuntimeException | Error err) {
<ide> if (err == this.ex) {
<ide> logger.debug("Expected exception thrown", err);
<ide> }
<ide><path>spring-beans/src/test/java/org/springframework/beans/AbstractPropertyValuesTests.java
<ide> protected void doTestTony(PropertyValues pvs) {
<ide> m.put("forname", "Tony");
<ide> m.put("surname", "Blair");
<ide> m.put("age", "50");
<del> for (int i = 0; i < ps.length; i++) {
<del> Object val = m.get(ps[i].getName());
<add> for (PropertyValue element : ps) {
<add> Object val = m.get(element.getName());
<ide> assertThat(val != null).as("Can't have unexpected value").isTrue();
<ide> boolean condition = val instanceof String;
<ide> assertThat(condition).as("Val i string").isTrue();
<del> assertThat(val.equals(ps[i].getValue())).as("val matches expected").isTrue();
<del> m.remove(ps[i].getName());
<add> assertThat(val.equals(element.getValue())).as("val matches expected").isTrue();
<add> m.remove(element.getName());
<ide> }
<ide> assertThat(m.size() == 0).as("Map size is 0").isTrue();
<ide> }
<ide><path>spring-beans/src/test/java/org/springframework/beans/factory/BeanFactoryUtilsTests.java
<ide> public Class<TestBean> getObjectType() {
<ide> return TestBean.class;
<ide> }
<ide>
<add> @Override
<ide> public TestBean getObject() {
<ide> // We don't really care if the actual instance is a singleton or prototype
<ide> // for the tests that use this factory.
<ide><path>spring-beans/src/test/java/org/springframework/beans/factory/DefaultListableBeanFactoryTests.java
<ide> import org.springframework.beans.BeansException;
<ide> import org.springframework.beans.MutablePropertyValues;
<ide> import org.springframework.beans.NotWritablePropertyException;
<del>import org.springframework.beans.PropertyEditorRegistrar;
<del>import org.springframework.beans.PropertyEditorRegistry;
<ide> import org.springframework.beans.PropertyValue;
<ide> import org.springframework.beans.TypeConverter;
<ide> import org.springframework.beans.TypeMismatchException;
<ide> import org.springframework.core.MethodParameter;
<ide> import org.springframework.core.ResolvableType;
<ide> import org.springframework.core.annotation.AnnotationAwareOrderComparator;
<del>import org.springframework.core.convert.converter.Converter;
<ide> import org.springframework.core.convert.support.DefaultConversionService;
<ide> import org.springframework.core.convert.support.GenericConversionService;
<ide> import org.springframework.core.io.Resource;
<ide> void customEditor() {
<ide> @Test
<ide> void customConverter() {
<ide> GenericConversionService conversionService = new DefaultConversionService();
<del> conversionService.addConverter(new Converter<String, Float>() {
<del> @Override
<del> public Float convert(String source) {
<del> try {
<del> NumberFormat nf = NumberFormat.getInstance(Locale.GERMAN);
<del> return nf.parse(source).floatValue();
<del> }
<del> catch (ParseException ex) {
<del> throw new IllegalArgumentException(ex);
<del> }
<add> conversionService.addConverter(String.class, Float.class, source -> {
<add> try {
<add> NumberFormat nf = NumberFormat.getInstance(Locale.GERMAN);
<add> return nf.parse(source).floatValue();
<add> }
<add> catch (ParseException ex) {
<add> throw new IllegalArgumentException(ex);
<ide> }
<ide> });
<ide> lbf.setConversionService(conversionService);
<ide> public Float convert(String source) {
<ide>
<ide> @Test
<ide> void customEditorWithBeanReference() {
<del> lbf.addPropertyEditorRegistrar(new PropertyEditorRegistrar() {
<del> @Override
<del> public void registerCustomEditors(PropertyEditorRegistry registry) {
<del> NumberFormat nf = NumberFormat.getInstance(Locale.GERMAN);
<del> registry.registerCustomEditor(Float.class, new CustomNumberEditor(Float.class, nf, true));
<del> }
<add> lbf.addPropertyEditorRegistrar(registry -> {
<add> NumberFormat nf = NumberFormat.getInstance(Locale.GERMAN);
<add> registry.registerCustomEditor(Float.class, new CustomNumberEditor(Float.class, nf, true));
<ide> });
<ide> MutablePropertyValues pvs = new MutablePropertyValues();
<ide> pvs.add("myFloat", new RuntimeBeanReference("myFloat"));
<ide> public void setBeanName(String name) {
<ide>
<ide> @Override
<ide> public boolean equals(Object o) {
<del> if (this == o) return true;
<del> if (o == null || getClass() != o.getClass()) return false;
<add> if (this == o) {
<add> return true;
<add> }
<add> if (o == null || getClass() != o.getClass()) {
<add> return false;
<add> }
<ide> ConstructorDependency that = (ConstructorDependency) o;
<ide> return spouseAge == that.spouseAge &&
<ide> Objects.equals(spouse, that.spouse) &&
<ide><path>spring-beans/src/test/java/org/springframework/beans/factory/annotation/AutowiredAnnotationBeanPostProcessorTests.java
<ide> import java.lang.annotation.RetentionPolicy;
<ide> import java.lang.annotation.Target;
<ide> import java.lang.reflect.InvocationHandler;
<del>import java.lang.reflect.Method;
<ide> import java.lang.reflect.Proxy;
<ide> import java.util.ArrayList;
<ide> import java.util.Arrays;
<ide> public static class MocksControl {
<ide> @SuppressWarnings("unchecked")
<ide> public <T> T createMock(Class<T> toMock) {
<ide> return (T) Proxy.newProxyInstance(AutowiredAnnotationBeanPostProcessorTests.class.getClassLoader(), new Class<?>[] {toMock},
<del> new InvocationHandler() {
<del> @Override
<del> public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
<del> throw new UnsupportedOperationException("mocked!");
<del> }
<add> (InvocationHandler) (proxy, method, args) -> {
<add> throw new UnsupportedOperationException("mocked!");
<ide> });
<ide> }
<ide> }
<ide><path>spring-beans/src/test/java/org/springframework/beans/factory/config/CustomEditorConfigurerTests.java
<ide>
<ide> import org.springframework.beans.MutablePropertyValues;
<ide> import org.springframework.beans.PropertyEditorRegistrar;
<del>import org.springframework.beans.PropertyEditorRegistry;
<ide> import org.springframework.beans.factory.support.DefaultListableBeanFactory;
<ide> import org.springframework.beans.factory.support.RootBeanDefinition;
<ide> import org.springframework.beans.propertyeditors.CustomDateEditor;
<ide> public void testCustomEditorConfigurerWithPropertyEditorRegistrar() throws Parse
<ide> CustomEditorConfigurer cec = new CustomEditorConfigurer();
<ide> final DateFormat df = DateFormat.getDateInstance(DateFormat.SHORT, Locale.GERMAN);
<ide> cec.setPropertyEditorRegistrars(new PropertyEditorRegistrar[] {
<del> new PropertyEditorRegistrar() {
<del> @Override
<del> public void registerCustomEditors(PropertyEditorRegistry registry) {
<del> registry.registerCustomEditor(Date.class, new CustomDateEditor(df, true));
<del> }
<del> }});
<add> registry -> registry.registerCustomEditor(Date.class, new CustomDateEditor(df, true))});
<ide> cec.postProcessBeanFactory(bf);
<ide>
<ide> MutablePropertyValues pvs = new MutablePropertyValues();
<ide><path>spring-beans/src/test/java/org/springframework/beans/factory/config/MethodInvokingFactoryBeanTests.java
<ide> public void testGetObjectType() throws Exception {
<ide> mcfb = new MethodInvokingFactoryBean();
<ide> mcfb.setTargetClass(TestClass1.class);
<ide> mcfb.setTargetMethod("supertypes");
<del> mcfb.setArguments(new ArrayList<>(), new ArrayList<Object>(), "hello");
<add> mcfb.setArguments(new ArrayList<>(), new ArrayList<>(), "hello");
<ide> mcfb.afterPropertiesSet();
<ide> mcfb.getObjectType();
<ide>
<ide> public void testGetObject() throws Exception {
<ide> mcfb = new MethodInvokingFactoryBean();
<ide> mcfb.setTargetClass(TestClass1.class);
<ide> mcfb.setTargetMethod("supertypes");
<del> mcfb.setArguments(new ArrayList<>(), new ArrayList<Object>(), "hello");
<add> mcfb.setArguments(new ArrayList<>(), new ArrayList<>(), "hello");
<ide> // should pass
<ide> mcfb.afterPropertiesSet();
<ide> }
<ide> public void testArgumentConversion() throws Exception {
<ide> MethodInvokingFactoryBean mcfb = new MethodInvokingFactoryBean();
<ide> mcfb.setTargetClass(TestClass1.class);
<ide> mcfb.setTargetMethod("supertypes");
<del> mcfb.setArguments(new ArrayList<>(), new ArrayList<Object>(), "hello", "bogus");
<add> mcfb.setArguments(new ArrayList<>(), new ArrayList<>(), "hello", "bogus");
<ide> assertThatExceptionOfType(NoSuchMethodException.class).as(
<ide> "Matched method with wrong number of args").isThrownBy(
<ide> mcfb::afterPropertiesSet);
<ide> public void testArgumentConversion() throws Exception {
<ide> mcfb = new MethodInvokingFactoryBean();
<ide> mcfb.setTargetClass(TestClass1.class);
<ide> mcfb.setTargetMethod("supertypes2");
<del> mcfb.setArguments(new ArrayList<>(), new ArrayList<Object>(), "hello", "bogus");
<add> mcfb.setArguments(new ArrayList<>(), new ArrayList<>(), "hello", "bogus");
<ide> mcfb.afterPropertiesSet();
<ide> assertThat(mcfb.getObject()).isEqualTo("hello");
<ide>
<ide> mcfb = new MethodInvokingFactoryBean();
<ide> mcfb.setTargetClass(TestClass1.class);
<ide> mcfb.setTargetMethod("supertypes2");
<del> mcfb.setArguments(new ArrayList<>(), new ArrayList<Object>(), new Object());
<add> mcfb.setArguments(new ArrayList<>(), new ArrayList<>(), new Object());
<ide> assertThatExceptionOfType(NoSuchMethodException.class).as(
<ide> "Matched method when shouldn't have matched").isThrownBy(
<ide> mcfb::afterPropertiesSet);
<ide><path>spring-beans/src/test/java/org/springframework/beans/factory/support/BeanFactoryGenericsTests.java
<ide> package org.springframework.beans.factory.support;
<ide>
<ide> import java.lang.reflect.InvocationHandler;
<del>import java.lang.reflect.Method;
<ide> import java.lang.reflect.Proxy;
<ide> import java.net.MalformedURLException;
<ide> import java.net.URI;
<ide> import org.junit.jupiter.api.Test;
<ide> import org.mockito.Mockito;
<ide>
<del>import org.springframework.beans.PropertyEditorRegistrar;
<del>import org.springframework.beans.PropertyEditorRegistry;
<ide> import org.springframework.beans.factory.BeanCreationException;
<ide> import org.springframework.beans.factory.NoUniqueBeanDefinitionException;
<ide> import org.springframework.beans.factory.ObjectProvider;
<ide> void testGenericMapWithKeyTypeConstructor() {
<ide> @Test
<ide> void testGenericMapWithCollectionValueConstructor() {
<ide> DefaultListableBeanFactory bf = new DefaultListableBeanFactory();
<del> bf.addPropertyEditorRegistrar(new PropertyEditorRegistrar() {
<del> @Override
<del> public void registerCustomEditors(PropertyEditorRegistry registry) {
<del> registry.registerCustomEditor(Number.class, new CustomNumberEditor(Integer.class, false));
<del> }
<del> });
<add> bf.addPropertyEditorRegistrar(registry -> registry.registerCustomEditor(Number.class, new CustomNumberEditor(Integer.class, false)));
<ide> RootBeanDefinition rbd = new RootBeanDefinition(GenericBean.class);
<ide>
<ide> Map<String, AbstractCollection<?>> input = new HashMap<>();
<ide> void testGenericMapWithKeyTypeFactoryMethod() {
<ide> @Test
<ide> void testGenericMapWithCollectionValueFactoryMethod() {
<ide> DefaultListableBeanFactory bf = new DefaultListableBeanFactory();
<del> bf.addPropertyEditorRegistrar(new PropertyEditorRegistrar() {
<del> @Override
<del> public void registerCustomEditors(PropertyEditorRegistry registry) {
<del> registry.registerCustomEditor(Number.class, new CustomNumberEditor(Integer.class, false));
<del> }
<del> });
<add> bf.addPropertyEditorRegistrar(registry -> registry.registerCustomEditor(Number.class, new CustomNumberEditor(Integer.class, false)));
<ide> RootBeanDefinition rbd = new RootBeanDefinition(GenericBean.class);
<ide> rbd.setFactoryMethodName("createInstance");
<ide>
<ide> public static class MocksControl {
<ide> @SuppressWarnings("unchecked")
<ide> public <T> T createMock(Class<T> toMock) {
<ide> return (T) Proxy.newProxyInstance(BeanFactoryGenericsTests.class.getClassLoader(), new Class<?>[] {toMock},
<del> new InvocationHandler() {
<del> @Override
<del> public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
<del> throw new UnsupportedOperationException("mocked!");
<del> }
<add> (InvocationHandler) (proxy, method, args) -> {
<add> throw new UnsupportedOperationException("mocked!");
<ide> });
<ide> }
<ide> }
<ide><path>spring-beans/src/test/java/org/springframework/beans/factory/support/DefaultSingletonBeanRegistryTests.java
<ide>
<ide> import org.junit.jupiter.api.Test;
<ide>
<del>import org.springframework.beans.BeansException;
<del>import org.springframework.beans.factory.ObjectFactory;
<ide> import org.springframework.beans.testfixture.beans.DerivedTestBean;
<ide> import org.springframework.beans.testfixture.beans.TestBean;
<ide>
<ide> public void testSingletons() {
<ide> beanRegistry.registerSingleton("tb", tb);
<ide> assertThat(beanRegistry.getSingleton("tb")).isSameAs(tb);
<ide>
<del> TestBean tb2 = (TestBean) beanRegistry.getSingleton("tb2", new ObjectFactory<Object>() {
<del> @Override
<del> public Object getObject() throws BeansException {
<del> return new TestBean();
<del> }
<del> });
<add> TestBean tb2 = (TestBean) beanRegistry.getSingleton("tb2", () -> new TestBean());
<ide> assertThat(beanRegistry.getSingleton("tb2")).isSameAs(tb2);
<ide>
<ide> assertThat(beanRegistry.getSingleton("tb")).isSameAs(tb);
<ide><path>spring-beans/src/testFixtures/java/org/springframework/beans/testfixture/beans/MustBeInitialized.java
<ide> public void afterPropertiesSet() throws Exception {
<ide> * managed the bean's lifecycle correctly
<ide> */
<ide> public void businessMethod() {
<del> if (!this.inited)
<add> if (!this.inited) {
<ide> throw new RuntimeException("Factory didn't call afterPropertiesSet() on MustBeInitialized object");
<add> }
<ide> }
<ide>
<ide> }
<ide><path>spring-beans/src/testFixtures/java/org/springframework/beans/testfixture/beans/Pet.java
<ide> public String toString() {
<ide>
<ide> @Override
<ide> public boolean equals(Object o) {
<del> if (this == o) return true;
<del> if (o == null || getClass() != o.getClass()) return false;
<add> if (this == o) {
<add> return true;
<add> }
<add> if (o == null || getClass() != o.getClass()) {
<add> return false;
<add> }
<ide>
<ide> final Pet pet = (Pet) o;
<ide>
<del> if (name != null ? !name.equals(pet.name) : pet.name != null) return false;
<add> if (name != null ? !name.equals(pet.name) : pet.name != null) {
<add> return false;
<add> }
<ide>
<ide> return true;
<ide> }
<ide><path>spring-context-support/src/test/java/org/springframework/cache/caffeine/CaffeineCacheManagerTests.java
<ide> public void setCacheNameNullRestoreDynamicMode() {
<ide> @Test
<ide> public void cacheLoaderUseLoadingCache() {
<ide> CaffeineCacheManager cm = new CaffeineCacheManager("c1");
<del> cm.setCacheLoader(new CacheLoader<Object, Object>() {
<del> @Override
<del> public Object load(Object key) throws Exception {
<del> if ("ping".equals(key)) {
<del> return "pong";
<del> }
<del> throw new IllegalArgumentException("I only know ping");
<add> cm.setCacheLoader(key -> {
<add> if ("ping".equals(key)) {
<add> return "pong";
<ide> }
<add> throw new IllegalArgumentException("I only know ping");
<ide> });
<ide> Cache cache1 = cm.getCache("c1");
<ide> Cache.ValueWrapper value = cache1.get("ping");
<ide><path>spring-context-support/src/test/java/org/springframework/mail/javamail/JavaMailSenderTests.java
<ide> public void javaMailSenderWithMimeMessagePreparator() {
<ide>
<ide> final List<Message> messages = new ArrayList<>();
<ide>
<del> MimeMessagePreparator preparator = new MimeMessagePreparator() {
<del> @Override
<del> public void prepare(MimeMessage mimeMessage) throws MessagingException {
<del> mimeMessage.setRecipient(Message.RecipientType.TO, new InternetAddress("you@mail.org"));
<del> messages.add(mimeMessage);
<del> }
<add> MimeMessagePreparator preparator = mimeMessage -> {
<add> mimeMessage.setRecipient(Message.RecipientType.TO, new InternetAddress("you@mail.org"));
<add> messages.add(mimeMessage);
<ide> };
<ide> sender.send(preparator);
<ide>
<ide> public void javaMailSenderWithMimeMessagePreparators() {
<ide>
<ide> final List<Message> messages = new ArrayList<>();
<ide>
<del> MimeMessagePreparator preparator1 = new MimeMessagePreparator() {
<del> @Override
<del> public void prepare(MimeMessage mimeMessage) throws MessagingException {
<del> mimeMessage.setRecipient(Message.RecipientType.TO, new InternetAddress("he@mail.org"));
<del> messages.add(mimeMessage);
<del> }
<add> MimeMessagePreparator preparator1 = mimeMessage -> {
<add> mimeMessage.setRecipient(Message.RecipientType.TO, new InternetAddress("he@mail.org"));
<add> messages.add(mimeMessage);
<ide> };
<del> MimeMessagePreparator preparator2 = new MimeMessagePreparator() {
<del> @Override
<del> public void prepare(MimeMessage mimeMessage) throws MessagingException {
<del> mimeMessage.setRecipient(Message.RecipientType.TO, new InternetAddress("she@mail.org"));
<del> messages.add(mimeMessage);
<del> }
<add> MimeMessagePreparator preparator2 = mimeMessage -> {
<add> mimeMessage.setRecipient(Message.RecipientType.TO, new InternetAddress("she@mail.org"));
<add> messages.add(mimeMessage);
<ide> };
<ide> sender.send(preparator1, preparator2);
<ide>
<ide> public void javaMailSenderWithParseExceptionOnSimpleMessage() {
<ide> @Test
<ide> public void javaMailSenderWithParseExceptionOnMimeMessagePreparator() {
<ide> MockJavaMailSender sender = new MockJavaMailSender();
<del> MimeMessagePreparator preparator = new MimeMessagePreparator() {
<del> @Override
<del> public void prepare(MimeMessage mimeMessage) throws MessagingException {
<del> mimeMessage.setFrom(new InternetAddress(""));
<del> }
<del> };
<add> MimeMessagePreparator preparator = mimeMessage -> mimeMessage.setFrom(new InternetAddress(""));
<ide> try {
<ide> sender.send(preparator);
<ide> }
<ide><path>spring-context/src/test/java/org/springframework/aop/aspectj/autoproxy/AspectJAutoProxyCreatorTests.java
<ide> /*
<del> * Copyright 2002-2021 the original author or authors.
<add> * Copyright 2002-2022 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> class TestBeanAdvisor extends StaticMethodMatcherPointcutAdvisor {
<ide> public int count;
<ide>
<ide> public TestBeanAdvisor() {
<del> setAdvice(new MethodBeforeAdvice() {
<del> @Override
<del> public void before(Method method, Object[] args, @Nullable Object target) throws Throwable {
<del> ++count;
<del> }
<del> });
<add> setAdvice((MethodBeforeAdvice) (method, args, target) -> ++count);
<ide> }
<ide>
<ide> @Override
<ide><path>spring-context/src/test/java/org/springframework/aop/framework/AbstractAopProxyTests.java
<ide> public void testNoContext() throws Throwable {
<ide> private void testContext(final boolean context) throws Throwable {
<ide> final String s = "foo";
<ide> // Test return value
<del> MethodInterceptor mi = new MethodInterceptor() {
<del> @Override
<del> public Object invoke(MethodInvocation invocation) throws Throwable {
<del> if (!context) {
<del> assertNoInvocationContext();
<del> }
<del> else {
<del> assertThat(ExposeInvocationInterceptor.currentInvocation()).as("have context").isNotNull();
<del> }
<del> return s;
<add> MethodInterceptor mi = invocation -> {
<add> if (!context) {
<add> assertNoInvocationContext();
<ide> }
<add> else {
<add> assertThat(ExposeInvocationInterceptor.currentInvocation()).as("have context").isNotNull();
<add> }
<add> return s;
<ide> };
<ide> AdvisedSupport pc = new AdvisedSupport(ITestBean.class);
<ide> if (context) {
<ide> public void testTargetReturnsThis() throws Throwable {
<ide> public void testDeclaredException() throws Throwable {
<ide> final Exception expectedException = new Exception();
<ide> // Test return value
<del> MethodInterceptor mi = new MethodInterceptor() {
<del> @Override
<del> public Object invoke(MethodInvocation invocation) throws Throwable {
<del> throw expectedException;
<del> }
<add> MethodInterceptor mi = invocation -> {
<add> throw expectedException;
<ide> };
<ide> AdvisedSupport pc = new AdvisedSupport(ITestBean.class);
<ide> pc.addAdvice(ExposeInvocationInterceptor.INSTANCE);
<ide> public Object invoke(MethodInvocation invocation) throws Throwable {
<ide> public void testUndeclaredCheckedException() throws Throwable {
<ide> final Exception unexpectedException = new Exception();
<ide> // Test return value
<del> MethodInterceptor mi = new MethodInterceptor() {
<del> @Override
<del> public Object invoke(MethodInvocation invocation) throws Throwable {
<del> throw unexpectedException;
<del> }
<add> MethodInterceptor mi = invocation -> {
<add> throw unexpectedException;
<ide> };
<ide> AdvisedSupport pc = new AdvisedSupport(ITestBean.class);
<ide> pc.addAdvice(ExposeInvocationInterceptor.INSTANCE);
<ide> public Object invoke(MethodInvocation invocation) throws Throwable {
<ide> public void testUndeclaredUncheckedException() throws Throwable {
<ide> final RuntimeException unexpectedException = new RuntimeException();
<ide> // Test return value
<del> MethodInterceptor mi = new MethodInterceptor() {
<del> @Override
<del> public Object invoke(MethodInvocation invocation) throws Throwable {
<del> throw unexpectedException;
<del> }
<add> MethodInterceptor mi = invocation -> {
<add> throw unexpectedException;
<ide> };
<ide> AdvisedSupport pc = new AdvisedSupport(ITestBean.class);
<ide> pc.addAdvice(ExposeInvocationInterceptor.INSTANCE);
<ide> public void testAdviceImplementsIntroductionInfo() throws Throwable {
<ide> NopInterceptor di = new NopInterceptor();
<ide> pc.addAdvice(di);
<ide> final long ts = 37;
<del> pc.addAdvice(new DelegatingIntroductionInterceptor(new TimeStamped() {
<del> @Override
<del> public long getTimeStamp() {
<del> return ts;
<del> }
<del> }));
<add> pc.addAdvice(new DelegatingIntroductionInterceptor((TimeStamped) () -> ts));
<ide>
<ide> ITestBean proxied = (ITestBean) createProxy(pc);
<ide> assertThat(proxied.getName()).isEqualTo(name);
<ide> public void testCloneInvocationToProceedThreeTimes() throws Throwable {
<ide> ProxyFactory pc = new ProxyFactory(tb);
<ide> pc.addInterface(ITestBean.class);
<ide>
<del> MethodInterceptor twoBirthdayInterceptor = new MethodInterceptor() {
<del> @Override
<del> public Object invoke(MethodInvocation mi) throws Throwable {
<del> // Clone the invocation to proceed three times
<del> // "The Moor's Last Sigh": this technology can cause premature aging
<del> MethodInvocation clone1 = ((ReflectiveMethodInvocation) mi).invocableClone();
<del> MethodInvocation clone2 = ((ReflectiveMethodInvocation) mi).invocableClone();
<del> clone1.proceed();
<del> clone2.proceed();
<del> return mi.proceed();
<del> }
<add> MethodInterceptor twoBirthdayInterceptor = mi -> {
<add> // Clone the invocation to proceed three times
<add> // "The Moor's Last Sigh": this technology can cause premature aging
<add> MethodInvocation clone1 = ((ReflectiveMethodInvocation) mi).invocableClone();
<add> MethodInvocation clone2 = ((ReflectiveMethodInvocation) mi).invocableClone();
<add> clone1.proceed();
<add> clone2.proceed();
<add> return mi.proceed();
<ide> };
<ide> @SuppressWarnings("serial")
<ide> StaticMethodMatcherPointcutAdvisor advisor = new StaticMethodMatcherPointcutAdvisor(twoBirthdayInterceptor) {
<ide> public void testCanChangeArgumentsIndependentlyOnClonedInvocation() throws Throw
<ide> /**
<ide> * Changes the name, then changes it back.
<ide> */
<del> MethodInterceptor nameReverter = new MethodInterceptor() {
<del> @Override
<del> public Object invoke(MethodInvocation mi) throws Throwable {
<del> MethodInvocation clone = ((ReflectiveMethodInvocation) mi).invocableClone();
<del> String oldName = ((ITestBean) mi.getThis()).getName();
<del> clone.getArguments()[0] = oldName;
<del> // Original method invocation should be unaffected by changes to argument list of clone
<del> mi.proceed();
<del> return clone.proceed();
<del> }
<add> MethodInterceptor nameReverter = mi -> {
<add> MethodInvocation clone = ((ReflectiveMethodInvocation) mi).invocableClone();
<add> String oldName = ((ITestBean) mi.getThis()).getName();
<add> clone.getArguments()[0] = oldName;
<add> // Original method invocation should be unaffected by changes to argument list of clone
<add> mi.proceed();
<add> return clone.proceed();
<ide> };
<ide>
<ide> class NameSaver implements MethodInterceptor {
<ide> public void testBeforeAdviceThrowsException() {
<ide> @Override
<ide> public void before(Method m, Object[] args, Object target) throws Throwable {
<ide> super.before(m, args, target);
<del> if (m.getName().startsWith("set"))
<add> if (m.getName().startsWith("set")) {
<ide> throw rex;
<add> }
<ide> }
<ide> };
<ide>
<ide> public Object invoke(MethodInvocation mi) throws Throwable {
<ide> @SuppressWarnings("serial")
<ide> protected static class StringSetterNullReplacementAdvice extends DefaultPointcutAdvisor {
<ide>
<del> private static MethodInterceptor cleaner = new MethodInterceptor() {
<del> @Override
<del> public Object invoke(MethodInvocation mi) throws Throwable {
<del> // We know it can only be invoked if there's a single parameter of type string
<del> mi.getArguments()[0] = "";
<del> return mi.proceed();
<del> }
<add> private static MethodInterceptor cleaner = mi -> {
<add> // We know it can only be invoked if there's a single parameter of type string
<add> mi.getArguments()[0] = "";
<add> return mi.proceed();
<ide> };
<ide>
<ide> public StringSetterNullReplacementAdvice() {
<ide> public TestDynamicPointcutAdvice(MethodInterceptor mi, final String pattern) {
<ide> @Override
<ide> public boolean matches(Method m, @Nullable Class<?> targetClass, Object... args) {
<ide> boolean run = m.getName().contains(pattern);
<del> if (run) ++count;
<add> if (run) {
<add> ++count;
<add> }
<ide> return run;
<ide> }
<ide> });
<ide> public TestDynamicPointcutForSettersOnly(MethodInterceptor mi, final String patt
<ide> @Override
<ide> public boolean matches(Method m, @Nullable Class<?> targetClass, Object... args) {
<ide> boolean run = m.getName().contains(pattern);
<del> if (run) ++count;
<add> if (run) {
<add> ++count;
<add> }
<ide> return run;
<ide> }
<ide> @Override
<ide> public Object getTarget() throws Exception {
<ide> */
<ide> @Override
<ide> public void releaseTarget(Object pTarget) throws Exception {
<del> if (pTarget != this.target)
<add> if (pTarget != this.target) {
<ide> throw new RuntimeException("Released wrong target");
<add> }
<ide> ++releases;
<ide> }
<ide>
<ide> public void releaseTarget(Object pTarget) throws Exception {
<ide> *
<ide> */
<ide> public void verify() {
<del> if (gets != releases)
<add> if (gets != releases) {
<ide> throw new RuntimeException("Expectation failed: " + gets + " gets and " + releases + " releases");
<add> }
<ide> }
<ide>
<ide> /**
<ide><path>spring-context/src/test/java/org/springframework/aop/framework/JdkDynamicProxyTests.java
<ide> public String getName() {
<ide>
<ide> @Override
<ide> public boolean equals(Object o) {
<del> if (this == o) return true;
<del> if (o == null || getClass() != o.getClass()) return false;
<add> if (this == o) {
<add> return true;
<add> }
<add> if (o == null || getClass() != o.getClass()) {
<add> return false;
<add> }
<ide> Person person = (Person) o;
<del> if (!name.equals(person.name)) return false;
<add> if (!name.equals(person.name)) {
<add> return false;
<add> }
<ide> return true;
<ide> }
<ide>
<ide><path>spring-context/src/test/java/org/springframework/aop/framework/ProxyFactoryBeanTests.java
<ide> public void testCanGetFactoryReferenceAndManipulate() {
<ide>
<ide> final Exception ex = new UnsupportedOperationException("invoke");
<ide> // Add evil interceptor to head of list
<del> config.addAdvice(0, new MethodInterceptor() {
<del> @Override
<del> public Object invoke(MethodInvocation invocation) throws Throwable {
<del> throw ex;
<del> }
<add> config.addAdvice(0, (MethodInterceptor) invocation -> {
<add> throw ex;
<ide> });
<ide> assertThat(config.getAdvisors().length).as("Have correct advisor count").isEqualTo(2);
<ide>
<ide> public static void reset() {
<ide> }
<ide>
<ide> public PointcutForVoid() {
<del> setAdvice(new MethodInterceptor() {
<del> @Override
<del> public Object invoke(MethodInvocation invocation) throws Throwable {
<del> methodNames.add(invocation.getMethod().getName());
<del> return invocation.proceed();
<del> }
<add> setAdvice((MethodInterceptor) invocation -> {
<add> methodNames.add(invocation.getMethod().getName());
<add> return invocation.proceed();
<ide> });
<ide> setPointcut(new DynamicMethodMatcherPointcut() {
<ide> @Override
<ide><path>spring-context/src/test/java/org/springframework/aop/framework/autoproxy/AutoProxyCreatorTests.java
<ide> /*
<del> * Copyright 2002-2021 the original author or authors.
<add> * Copyright 2002-2022 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> package org.springframework.aop.framework.autoproxy;
<ide>
<ide> import java.io.Serializable;
<del>import java.lang.reflect.InvocationHandler;
<del>import java.lang.reflect.Method;
<ide> import java.lang.reflect.Proxy;
<ide>
<ide> import org.aopalliance.intercept.MethodInterceptor;
<ide> public FallbackTestAutoProxyCreator() {
<ide> @SuppressWarnings("serial")
<ide> public static class IntroductionTestAutoProxyCreator extends TestAutoProxyCreator {
<ide>
<add> @Override
<ide> protected Object[] getAdvicesAndAdvisors() {
<ide> DefaultIntroductionAdvisor advisor = new DefaultIntroductionAdvisor(this.testInterceptor);
<ide> advisor.addInterface(Serializable.class);
<ide> public static class CustomProxyFactoryBean implements FactoryBean<ITestBean> {
<ide>
<ide> @Override
<ide> public ITestBean getObject() {
<del> return (ITestBean) Proxy.newProxyInstance(CustomProxyFactoryBean.class.getClassLoader(), new Class<?>[]{ITestBean.class}, new InvocationHandler() {
<del> @Override
<del> public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
<del> return ReflectionUtils.invokeMethod(method, tb, args);
<del> }
<del> });
<add> return (ITestBean) Proxy.newProxyInstance(CustomProxyFactoryBean.class.getClassLoader(), new Class<?>[]{ITestBean.class},
<add> (proxy, method, args) -> ReflectionUtils.invokeMethod(method, tb, args));
<ide> }
<ide>
<ide> @Override
<ide><path>spring-context/src/test/java/org/springframework/aop/target/CommonsPool2TargetSourceTests.java
<ide> void testHitMaxSize() throws Exception {
<ide> pooledInstances[9] = targetSource.getTarget();
<ide>
<ide> // release all objects
<del> for (int i = 0; i < pooledInstances.length; i++) {
<del> targetSource.releaseTarget(pooledInstances[i]);
<add> for (Object element : pooledInstances) {
<add> targetSource.releaseTarget(element);
<ide> }
<ide> }
<ide>
<ide><path>spring-context/src/test/java/org/springframework/context/LifecycleContextBean.java
<ide> public class LifecycleContextBean extends LifecycleBean implements ApplicationCo
<ide> @Override
<ide> public void setBeanFactory(BeanFactory beanFactory) {
<ide> super.setBeanFactory(beanFactory);
<del> if (this.owningContext != null)
<add> if (this.owningContext != null) {
<ide> throw new RuntimeException("Factory called setBeanFactory after setApplicationContext");
<add> }
<ide> }
<ide>
<ide> @Override
<ide> public void afterPropertiesSet() {
<ide> super.afterPropertiesSet();
<del> if (this.owningContext == null)
<add> if (this.owningContext == null) {
<ide> throw new RuntimeException("Factory didn't call setApplicationContext before afterPropertiesSet on lifecycle bean");
<add> }
<ide> }
<ide>
<ide> @Override
<ide> public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
<del> if (this.owningFactory == null)
<add> if (this.owningFactory == null) {
<ide> throw new RuntimeException("Factory called setApplicationContext before setBeanFactory");
<add> }
<ide>
<ide> this.owningContext = applicationContext;
<ide> }
<ide><path>spring-context/src/test/java/org/springframework/context/annotation/AnnotationConfigApplicationContextTests.java
<ide> public int hashCode() {
<ide>
<ide> @Override
<ide> public boolean equals(Object obj) {
<del> if (this == obj)
<add> if (this == obj) {
<ide> return true;
<del> if (obj == null)
<add> }
<add> if (obj == null) {
<ide> return false;
<del> if (getClass() != obj.getClass())
<add> }
<add> if (getClass() != obj.getClass()) {
<ide> return false;
<add> }
<ide> TestBean other = (TestBean) obj;
<ide> if (name == null) {
<del> if (other.name != null)
<add> if (other.name != null) {
<ide> return false;
<add> }
<ide> }
<del> else if (!name.equals(other.name))
<add> else if (!name.equals(other.name)) {
<ide> return false;
<add> }
<ide> return true;
<ide> }
<ide>
<ide><path>spring-context/src/test/java/org/springframework/context/annotation/CommonAnnotationBeanPostProcessorTests.java
<ide> public void testResourceInjectionWithResolvableDependencyType() {
<ide> bf.registerBeanDefinition("testBean4", tbd);
<ide>
<ide> bf.registerResolvableDependency(BeanFactory.class, bf);
<del> bf.registerResolvableDependency(INestedTestBean.class, new ObjectFactory<Object>() {
<del> @Override
<del> public Object getObject() throws BeansException {
<del> return new NestedTestBean();
<del> }
<del> });
<add> bf.registerResolvableDependency(INestedTestBean.class, (ObjectFactory<Object>) () -> new NestedTestBean());
<ide>
<ide> @SuppressWarnings("deprecation")
<ide> org.springframework.beans.factory.config.PropertyPlaceholderConfigurer ppc = new org.springframework.beans.factory.config.PropertyPlaceholderConfigurer();
<ide><path>spring-context/src/test/java/org/springframework/context/annotation/ConfigurationClassAndBFPPTests.java
<ide>
<ide> import org.junit.jupiter.api.Test;
<ide>
<del>import org.springframework.beans.BeansException;
<ide> import org.springframework.beans.factory.annotation.Autowired;
<ide> import org.springframework.beans.factory.config.BeanFactoryPostProcessor;
<del>import org.springframework.beans.factory.config.ConfigurableListableBeanFactory;
<ide> import org.springframework.beans.testfixture.beans.TestBean;
<ide>
<ide> import static org.assertj.core.api.Assertions.assertThat;
<ide> static class AutowiredConfigWithBFPPAsInstanceMethod {
<ide>
<ide> @Bean
<ide> public BeanFactoryPostProcessor bfpp() {
<del> return new BeanFactoryPostProcessor() {
<del> @Override
<del> public void postProcessBeanFactory(ConfigurableListableBeanFactory beanFactory) throws BeansException {
<del> // no-op
<del> }
<add> return beanFactory -> {
<add> // no-op
<ide> };
<ide> }
<ide> }
<ide> static class AutowiredConfigWithBFPPAsStaticMethod {
<ide>
<ide> @Bean
<ide> public static final BeanFactoryPostProcessor bfpp() {
<del> return new BeanFactoryPostProcessor() {
<del> @Override
<del> public void postProcessBeanFactory(ConfigurableListableBeanFactory beanFactory) throws BeansException {
<del> // no-op
<del> }
<add> return beanFactory -> {
<add> // no-op
<ide> };
<ide> }
<ide> }
<ide><path>spring-context/src/test/java/org/springframework/context/annotation/ConfigurationClassWithConditionTests.java
<ide> public ExampleBean bean1() {
<ide> static class ImportsNotCreated {
<ide>
<ide> static {
<del> if (true) throw new RuntimeException();
<add> if (true) {
<add> throw new RuntimeException();
<add> }
<ide> }
<ide> }
<ide>
<ide> @Configuration
<ide> static class ConfigurationNotCreated {
<ide>
<ide> static {
<del> if (true) throw new RuntimeException();
<add> if (true) {
<add> throw new RuntimeException();
<add> }
<ide> }
<ide> }
<ide>
<ide> static class RegistrarNotCreated implements ImportBeanDefinitionRegistrar {
<ide>
<ide> static {
<del> if (true) throw new RuntimeException();
<add> if (true) {
<add> throw new RuntimeException();
<add> }
<ide> }
<ide>
<ide> @Override
<ide> public void registerBeanDefinitions(AnnotationMetadata importingClassMetadata,
<ide> static class ImportSelectorNotCreated implements ImportSelector {
<ide>
<ide> static {
<del> if (true) throw new RuntimeException();
<add> if (true) {
<add> throw new RuntimeException();
<add> }
<ide> }
<ide>
<ide> @Override
<ide><path>spring-context/src/test/java/org/springframework/context/annotation/configuration/ConfigurationClassAspectIntegrationTests.java
<ide> public static class Application {
<ide>
<ide> @Bean
<ide> Runnable fromInnerClass() {
<del> return new Runnable() {
<del> @Override
<del> public void run() {
<del> }
<add> return () -> {
<ide> };
<ide> }
<ide>
<ide><path>spring-context/src/test/java/org/springframework/context/annotation/configuration/ConfigurationClassProcessingTests.java
<ide> import org.springframework.beans.factory.config.BeanDefinition;
<ide> import org.springframework.beans.factory.config.BeanFactoryPostProcessor;
<ide> import org.springframework.beans.factory.config.BeanPostProcessor;
<del>import org.springframework.beans.factory.config.ConfigurableListableBeanFactory;
<ide> import org.springframework.beans.factory.config.DependencyDescriptor;
<ide> import org.springframework.beans.factory.config.ListFactoryBean;
<ide> import org.springframework.beans.factory.parsing.BeanDefinitionParsingException;
<ide> public Object postProcessAfterInitialization(Object bean, String beanName) {
<ide>
<ide> // @Bean
<ide> public BeanFactoryPostProcessor beanFactoryPostProcessor() {
<del> return new BeanFactoryPostProcessor() {
<del> @Override
<del> public void postProcessBeanFactory(ConfigurableListableBeanFactory beanFactory) {
<del> BeanDefinition bd = beanFactory.getBeanDefinition("beanPostProcessor");
<del> bd.getPropertyValues().addPropertyValue("nameSuffix", "-processed-" + myProp);
<del> }
<add> return beanFactory -> {
<add> BeanDefinition bd = beanFactory.getBeanDefinition("beanPostProcessor");
<add> bd.getPropertyValues().addPropertyValue("nameSuffix", "-processed-" + myProp);
<ide> };
<ide> }
<ide>
<ide><path>spring-context/src/test/java/org/springframework/context/event/ApplicationContextEventTests.java
<ide> /*
<del> * Copyright 2002-2020 the original author or authors.
<add> * Copyright 2002-2022 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.util.HashSet;
<ide> import java.util.List;
<ide> import java.util.Set;
<del>import java.util.concurrent.Executor;
<ide>
<ide> import org.aopalliance.intercept.MethodInvocation;
<ide> import org.junit.jupiter.api.Test;
<ide> public void simpleApplicationEventMulticasterWithTaskExecutor() {
<ide> ApplicationEvent evt = new ContextClosedEvent(new StaticApplicationContext());
<ide>
<ide> SimpleApplicationEventMulticaster smc = new SimpleApplicationEventMulticaster();
<del> smc.setTaskExecutor(new Executor() {
<del> @Override
<del> public void execute(Runnable command) {
<del> command.run();
<del> command.run();
<del> }
<add> smc.setTaskExecutor(command -> {
<add> command.run();
<add> command.run();
<ide> });
<ide> smc.addApplicationListener(listener);
<ide>
<ide> public void innerBeanAsListener() {
<ide> public void anonymousClassAsListener() {
<ide> final Set<MyEvent> seenEvents = new HashSet<>();
<ide> StaticApplicationContext context = new StaticApplicationContext();
<del> context.addApplicationListener(new ApplicationListener<MyEvent>() {
<del> @Override
<del> public void onApplicationEvent(MyEvent event) {
<del> seenEvents.add(event);
<del> }
<del> });
<add> context.addApplicationListener((MyEvent event) -> seenEvents.add(event));
<ide> context.refresh();
<ide>
<ide> MyEvent event1 = new MyEvent(context);
<ide><path>spring-context/src/test/java/org/springframework/context/event/PayloadApplicationEventTests.java
<ide> public void testProgrammaticEventListener() {
<ide> public void testProgrammaticPayloadListener() {
<ide> List<String> events = new ArrayList<>();
<ide> ApplicationListener<PayloadApplicationEvent<String>> listener = ApplicationListener.forPayload(events::add);
<del> ApplicationListener<PayloadApplicationEvent<Integer>> mismatch = ApplicationListener.forPayload(payload -> payload.intValue());
<add> ApplicationListener<PayloadApplicationEvent<Integer>> mismatch = ApplicationListener.forPayload(Integer::intValue);
<ide>
<ide> ConfigurableApplicationContext ac = new GenericApplicationContext();
<ide> ac.addApplicationListener(listener);
<ide><path>spring-context/src/test/java/org/springframework/context/event/test/AbstractIdentifiable.java
<ide> public String getId() {
<ide>
<ide> @Override
<ide> public boolean equals(Object o) {
<del> if (this == o) return true;
<del> if (o == null || getClass() != o.getClass()) return false;
<add> if (this == o) {
<add> return true;
<add> }
<add> if (o == null || getClass() != o.getClass()) {
<add> return false;
<add> }
<ide>
<ide> AbstractIdentifiable that = (AbstractIdentifiable) o;
<ide>
<ide><path>spring-context/src/test/java/org/springframework/context/event/test/GenericEventPojo.java
<ide> public ResolvableType getResolvableType() {
<ide>
<ide> @Override
<ide> public boolean equals(Object o) {
<del> if (this == o) return true;
<del> if (o == null || getClass() != o.getClass()) return false;
<add> if (this == o) {
<add> return true;
<add> }
<add> if (o == null || getClass() != o.getClass()) {
<add> return false;
<add> }
<ide>
<ide> GenericEventPojo<?> that = (GenericEventPojo<?>) o;
<ide>
<ide><path>spring-context/src/test/java/org/springframework/context/event/test/IdentifiableApplicationEvent.java
<ide> public String getId() {
<ide>
<ide> @Override
<ide> public boolean equals(Object o) {
<del> if (this == o) return true;
<del> if (o == null || getClass() != o.getClass()) return false;
<add> if (this == o) {
<add> return true;
<add> }
<add> if (o == null || getClass() != o.getClass()) {
<add> return false;
<add> }
<ide>
<ide> IdentifiableApplicationEvent that = (IdentifiableApplicationEvent) o;
<ide>
<ide><path>spring-context/src/test/java/org/springframework/context/support/ConversionServiceFactoryBeanTests.java
<ide> /*
<del> * Copyright 2002-2019 the original author or authors.
<add> * Copyright 2002-2022 the original author or authors.
<ide> *
<ide> * Licensed under the Apache License, Version 2.0 (the "License");
<ide> * you may not use this file except in compliance with the License.
<ide> public void createDefaultConversionServiceWithInvalidSupplements() {
<ide> Set<Object> converters = new HashSet<>();
<ide> converters.add("bogus");
<ide> factory.setConverters(converters);
<del> assertThatIllegalArgumentException().isThrownBy(
<del> factory::afterPropertiesSet);
<add> assertThatIllegalArgumentException().isThrownBy(factory::afterPropertiesSet);
<ide> }
<ide>
<ide> @Test
<ide><path>spring-context/src/test/java/org/springframework/format/number/NumberFormattingTests.java
<ide> import org.springframework.format.annotation.NumberFormat;
<ide> import org.springframework.format.annotation.NumberFormat.Style;
<ide> import org.springframework.format.support.FormattingConversionService;
<del>import org.springframework.util.StringValueResolver;
<ide> import org.springframework.validation.DataBinder;
<ide>
<ide> import static org.assertj.core.api.Assertions.assertThat;
<ide> public class NumberFormattingTests {
<ide> @BeforeEach
<ide> public void setUp() {
<ide> DefaultConversionService.addDefaultConverters(conversionService);
<del> conversionService.setEmbeddedValueResolver(new StringValueResolver() {
<del> @Override
<del> public String resolveStringValue(String strVal) {
<del> if ("${pattern}".equals(strVal)) {
<del> return "#,##.00";
<del> }
<del> else {
<del> return strVal;
<del> }
<add> conversionService.setEmbeddedValueResolver(strVal -> {
<add> if ("${pattern}".equals(strVal)) {
<add> return "#,##.00";
<add> }
<add> else {
<add> return strVal;
<ide> }
<ide> });
<ide> conversionService.addFormatterForFieldType(Number.class, new NumberStyleFormatter());
<ide><path>spring-context/src/test/java/org/springframework/format/support/FormattingConversionServiceFactoryBeanTests.java
<ide> /*
<del> * Copyright 2002-2019 the original author or authors.
<add> * Copyright 2002-2022 the original author or authors.
<ide> *
<ide> * Licensed under the Apache License, Version 2.0 (the "License");
<ide> * you may not use this file except in compliance with the License.
<ide> public Set<Class<?>> getFieldTypes() {
<ide> public Printer<?> getPrinter(SpecialInt annotation, Class<?> fieldType) {
<ide> assertThat(annotation.value()).isEqualTo("aliased");
<ide> assertThat(annotation.alias()).isEqualTo("aliased");
<del> return new Printer<Integer>() {
<del> @Override
<del> public String print(Integer object, Locale locale) {
<del> return ":" + object.toString();
<del> }
<del> };
<add> return (object, locale) -> ":" + object.toString();
<ide> }
<ide>
<ide> @Override
<ide> public Parser<?> getParser(SpecialInt annotation, Class<?> fieldType) {
<ide> assertThat(annotation.value()).isEqualTo("aliased");
<ide> assertThat(annotation.alias()).isEqualTo("aliased");
<del> return new Parser<Integer>() {
<del> @Override
<del> public Integer parse(String text, Locale locale) throws ParseException {
<del> return Integer.parseInt(text.substring(1));
<del> }
<del> };
<add> return (text, locale) -> Integer.parseInt(text.substring(1));
<ide> }
<ide> }
<ide>
<ide><path>spring-context/src/test/java/org/springframework/jmx/export/MBeanExporterOperationsTests.java
<ide>
<ide> import org.springframework.jmx.AbstractMBeanServerTests;
<ide> import org.springframework.jmx.JmxTestBean;
<del>import org.springframework.jmx.export.naming.ObjectNamingStrategy;
<ide> import org.springframework.jmx.support.ObjectNameManager;
<ide>
<ide> import static org.assertj.core.api.Assertions.assertThat;
<ide> void testRegisterManagedResourceWithGeneratedObjectName() throws Exception {
<ide>
<ide> MBeanExporter exporter = new MBeanExporter();
<ide> exporter.setServer(getServer());
<del> exporter.setNamingStrategy(new ObjectNamingStrategy() {
<del> @Override
<del> public ObjectName getObjectName(Object managedBean, String beanKey) {
<del> return objectNameTemplate;
<del> }
<del> });
<add> exporter.setNamingStrategy((managedBean, beanKey) -> objectNameTemplate);
<ide>
<ide> JmxTestBean bean1 = new JmxTestBean();
<ide> JmxTestBean bean2 = new JmxTestBean();
<ide> void testRegisterManagedResourceWithGeneratedObjectNameWithoutUniqueness() throw
<ide> MBeanExporter exporter = new MBeanExporter();
<ide> exporter.setServer(getServer());
<ide> exporter.setEnsureUniqueRuntimeObjectNames(false);
<del> exporter.setNamingStrategy(new ObjectNamingStrategy() {
<del> @Override
<del> public ObjectName getObjectName(Object managedBean, String beanKey) {
<del> return objectNameTemplate;
<del> }
<del> });
<add> exporter.setNamingStrategy((managedBean, beanKey) -> objectNameTemplate);
<ide>
<ide> JmxTestBean bean1 = new JmxTestBean();
<ide> JmxTestBean bean2 = new JmxTestBean();
<ide><path>spring-context/src/test/java/org/springframework/jmx/export/MBeanExporterTests.java
<ide> void testRegisterNullNotificationListenerType() throws Exception {
<ide> @Test
<ide> void testRegisterNotificationListenerForNonExistentMBean() throws Exception {
<ide> Map<String, NotificationListener> listeners = new HashMap<>();
<del> NotificationListener dummyListener = new NotificationListener() {
<del> @Override
<del> public void handleNotification(Notification notification, Object handback) {
<del> throw new UnsupportedOperationException();
<del> }
<add> NotificationListener dummyListener = (notification, handback) -> {
<add> throw new UnsupportedOperationException();
<ide> };
<ide> // the MBean with the supplied object name does not exist...
<ide> listeners.put("spring:type=Test", dummyListener);
<ide><path>spring-context/src/test/java/org/springframework/jmx/export/NotificationListenerTests.java
<ide> /*
<del> * Copyright 2002-2020 the original author or authors.
<add> * Copyright 2002-2022 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 javax.management.AttributeChangeNotification;
<ide> import javax.management.MalformedObjectNameException;
<ide> import javax.management.Notification;
<del>import javax.management.NotificationFilter;
<ide> import javax.management.NotificationListener;
<ide> import javax.management.ObjectName;
<ide>
<ide> public void testRegisterNotificationListenerWithHandback() throws Exception {
<ide> MBeanExporter exporter = new MBeanExporter();
<ide> exporter.setServer(server);
<ide> exporter.setBeans(beans);
<del> exporter.setNotificationListeners(new NotificationListenerBean[] { listenerBean });
<add> exporter.setNotificationListeners(listenerBean);
<ide> start(exporter);
<ide>
<ide> // update the attribute
<ide> public void testRegisterNotificationListenerForAllMBeans() throws Exception {
<ide> MBeanExporter exporter = new MBeanExporter();
<ide> exporter.setServer(server);
<ide> exporter.setBeans(beans);
<del> exporter.setNotificationListeners(new NotificationListenerBean[] { listenerBean });
<add> exporter.setNotificationListeners(listenerBean);
<ide> start(exporter);
<ide>
<ide> // update the attribute
<ide> public void testRegisterNotificationListenerWithFilter() throws Exception {
<ide>
<ide> NotificationListenerBean listenerBean = new NotificationListenerBean();
<ide> listenerBean.setNotificationListener(listener);
<del> listenerBean.setNotificationFilter(new NotificationFilter() {
<del> @Override
<del> public boolean isNotificationEnabled(Notification notification) {
<del> if (notification instanceof AttributeChangeNotification) {
<del> AttributeChangeNotification changeNotification = (AttributeChangeNotification) notification;
<del> return "Name".equals(changeNotification.getAttributeName());
<del> }
<del> else {
<del> return false;
<del> }
<add> listenerBean.setNotificationFilter(notification -> {
<add> if (notification instanceof AttributeChangeNotification) {
<add> AttributeChangeNotification changeNotification = (AttributeChangeNotification) notification;
<add> return "Name".equals(changeNotification.getAttributeName());
<add> }
<add> else {
<add> return false;
<ide> }
<ide> });
<ide>
<ide> MBeanExporter exporter = new MBeanExporter();
<ide> exporter.setServer(server);
<ide> exporter.setBeans(beans);
<del> exporter.setNotificationListeners(new NotificationListenerBean[] { listenerBean });
<add> exporter.setNotificationListeners(listenerBean);
<ide> start(exporter);
<ide>
<ide> // update the attributes
<ide><path>spring-context/src/test/java/org/springframework/jmx/export/assembler/AbstractJmxAssemblerTests.java
<ide> public void testGetMBeanAttributeInfo() throws Exception {
<ide> MBeanAttributeInfo[] inf = info.getAttributes();
<ide> assertThat(inf).as("Invalid number of Attributes returned").hasSize(getExpectedAttributeCount());
<ide>
<del> for (int x = 0; x < inf.length; x++) {
<del> assertThat(inf[x]).as("MBeanAttributeInfo should not be null").isNotNull();
<del> assertThat(inf[x].getDescription()).as("Description for MBeanAttributeInfo should not be null").isNotNull();
<add> for (MBeanAttributeInfo element : inf) {
<add> assertThat(element).as("MBeanAttributeInfo should not be null").isNotNull();
<add> assertThat(element.getDescription()).as("Description for MBeanAttributeInfo should not be null").isNotNull();
<ide> }
<ide> }
<ide>
<ide> public void testGetMBeanOperationInfo() throws Exception {
<ide> MBeanOperationInfo[] inf = info.getOperations();
<ide> assertThat(inf).as("Invalid number of Operations returned").hasSize(getExpectedOperationCount());
<ide>
<del> for (int x = 0; x < inf.length; x++) {
<del> assertThat(inf[x]).as("MBeanOperationInfo should not be null").isNotNull();
<del> assertThat(inf[x].getDescription()).as("Description for MBeanOperationInfo should not be null").isNotNull();
<add> for (MBeanOperationInfo element : inf) {
<add> assertThat(element).as("MBeanOperationInfo should not be null").isNotNull();
<add> assertThat(element.getDescription()).as("Description for MBeanOperationInfo should not be null").isNotNull();
<ide> }
<ide> }
<ide>
<ide><path>spring-context/src/test/java/org/springframework/scheduling/annotation/AsyncExecutionTests.java
<ide> import java.util.concurrent.TimeUnit;
<ide>
<ide> import org.aopalliance.intercept.MethodInterceptor;
<del>import org.aopalliance.intercept.MethodInvocation;
<ide> import org.awaitility.Awaitility;
<ide> import org.junit.jupiter.api.Test;
<ide>
<ide> public static class DynamicAsyncInterfaceBean implements FactoryBean<AsyncInterf
<ide>
<ide> public DynamicAsyncInterfaceBean() {
<ide> ProxyFactory pf = new ProxyFactory(new HashMap<>());
<del> DefaultIntroductionAdvisor advisor = new DefaultIntroductionAdvisor(new MethodInterceptor() {
<del> @Override
<del> public Object invoke(MethodInvocation invocation) throws Throwable {
<del> boolean condition = !Thread.currentThread().getName().equals(originalThreadName);
<del> assertThat(condition).isTrue();
<del> if (Future.class.equals(invocation.getMethod().getReturnType())) {
<del> return new AsyncResult<>(invocation.getArguments()[0].toString());
<del> }
<del> return null;
<add> DefaultIntroductionAdvisor advisor = new DefaultIntroductionAdvisor((MethodInterceptor) invocation -> {
<add> boolean condition = !Thread.currentThread().getName().equals(originalThreadName);
<add> assertThat(condition).isTrue();
<add> if (Future.class.equals(invocation.getMethod().getReturnType())) {
<add> return new AsyncResult<>(invocation.getArguments()[0].toString());
<ide> }
<add> return null;
<ide> });
<ide> advisor.addInterface(AsyncInterface.class);
<ide> pf.addAdvisor(advisor);
<ide> public static class DynamicAsyncMethodsInterfaceBean implements FactoryBean<Asyn
<ide>
<ide> public DynamicAsyncMethodsInterfaceBean() {
<ide> ProxyFactory pf = new ProxyFactory(new HashMap<>());
<del> DefaultIntroductionAdvisor advisor = new DefaultIntroductionAdvisor(new MethodInterceptor() {
<del> @Override
<del> public Object invoke(MethodInvocation invocation) throws Throwable {
<del> boolean condition = !Thread.currentThread().getName().equals(originalThreadName);
<del> assertThat(condition).isTrue();
<del> if (Future.class.equals(invocation.getMethod().getReturnType())) {
<del> return new AsyncResult<>(invocation.getArguments()[0].toString());
<del> }
<del> return null;
<add> DefaultIntroductionAdvisor advisor = new DefaultIntroductionAdvisor((MethodInterceptor) invocation -> {
<add> boolean condition = !Thread.currentThread().getName().equals(originalThreadName);
<add> assertThat(condition).isTrue();
<add> if (Future.class.equals(invocation.getMethod().getReturnType())) {
<add> return new AsyncResult<>(invocation.getArguments()[0].toString());
<ide> }
<add> return null;
<ide> });
<ide> advisor.addInterface(AsyncMethodsInterface.class);
<ide> pf.addAdvisor(advisor);
<ide><path>spring-context/src/test/java/org/springframework/scheduling/config/ExecutorBeanDefinitionParserTests.java
<ide>
<ide> package org.springframework.scheduling.config;
<ide>
<del>import java.util.concurrent.Callable;
<ide> import java.util.concurrent.Executor;
<ide> import java.util.concurrent.FutureTask;
<ide>
<ide> public void defaultExecutor() throws Exception {
<ide> assertThat(getKeepAliveSeconds(executor)).isEqualTo(60);
<ide> assertThat(getAllowCoreThreadTimeOut(executor)).isFalse();
<ide>
<del> FutureTask<String> task = new FutureTask<>(new Callable<String>() {
<del> @Override
<del> public String call() throws Exception {
<del> return "foo";
<del> }
<del> });
<add> FutureTask<String> task = new FutureTask<>(() -> "foo");
<ide> executor.execute(task);
<ide> assertThat(task.get()).isEqualTo("foo");
<ide> }
<ide><path>spring-context/src/test/java/org/springframework/scripting/groovy/MyBytecodeProcessor.java
<ide> */
<ide> public class MyBytecodeProcessor implements BytecodeProcessor {
<ide>
<del> public final Set<String> processed = new HashSet<String>();
<add> public final Set<String> processed = new HashSet<>();
<ide>
<ide> @Override
<ide> public byte[] processBytecode(String name, byte[] original) {
<ide><path>spring-context/src/test/java/org/springframework/ui/ModelMapTests.java
<ide> /*
<del> * Copyright 2002-2019 the original author or authors.
<add> * Copyright 2002-2022 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> package org.springframework.ui;
<ide>
<ide> import java.io.Serializable;
<del>import java.lang.reflect.InvocationHandler;
<del>import java.lang.reflect.Method;
<ide> import java.lang.reflect.Proxy;
<ide> import java.util.ArrayList;
<ide> import java.util.Collection;
<ide> public void testRawJdkProxy() throws Exception {
<ide> Object proxy = Proxy.newProxyInstance(
<ide> getClass().getClassLoader(),
<ide> new Class<?>[] {Map.class},
<del> new InvocationHandler() {
<del> @Override
<del> public Object invoke(Object proxy, Method method, Object[] args) {
<del> return "proxy";
<del> }
<del> });
<add> (proxy1, method, args) -> "proxy");
<ide> map.addAttribute(proxy);
<ide> assertThat(map.get("map")).isSameAs(proxy);
<ide> }
<ide><path>spring-context/src/test/java/test/mixin/LockMixin.java
<ide> public boolean locked() {
<ide> */
<ide> @Override
<ide> public Object invoke(MethodInvocation invocation) throws Throwable {
<del> if (locked() && invocation.getMethod().getName().indexOf("set") == 0)
<add> if (locked() && invocation.getMethod().getName().indexOf("set") == 0) {
<ide> throw new LockedException();
<add> }
<ide> return super.invoke(invocation);
<ide> }
<ide>
<ide><path>spring-context/src/testFixtures/java/org/springframework/context/testfixture/SimpleMapScope.java
<ide> import java.io.Serializable;
<ide> import java.util.ArrayList;
<ide> import java.util.HashMap;
<del>import java.util.Iterator;
<ide> import java.util.List;
<ide> import java.util.Map;
<ide>
<ide> public Object resolveContextualObject(String key) {
<ide> }
<ide>
<ide> public void close() {
<del> for (Iterator<Runnable> it = this.callbacks.iterator(); it.hasNext();) {
<del> Runnable runnable = it.next();
<add> for (Runnable runnable : this.callbacks) {
<ide> runnable.run();
<ide> }
<ide> }
<ide><path>spring-core/src/test/java/org/springframework/core/annotation/MergedAnnotationsTests.java
<ide> void synthesizeFromMapWithNestedMap() throws Exception {
<ide> assertThat(componentScan).isNotNull();
<ide> assertThat(componentScan.value().pattern()).isEqualTo("*Foo");
<ide> Map<String, Object> map = MergedAnnotation.from(componentScan).asMap(
<del> annotation -> new LinkedHashMap<String, Object>(),
<add> annotation -> new LinkedHashMap<>(),
<ide> Adapt.ANNOTATION_TO_MAP);
<ide> Map<String, Object> filterMap = (Map<String, Object>) map.get("value");
<ide> assertThat(filterMap.get("pattern")).isEqualTo("*Foo");
<ide> void synthesizeFromMapWithNestedArrayOfMaps() throws Exception {
<ide> ComponentScan.class);
<ide> assertThat(componentScan).isNotNull();
<ide> Map<String, Object> map = MergedAnnotation.from(componentScan).asMap(
<del> annotation -> new LinkedHashMap<String, Object>(),
<add> annotation -> new LinkedHashMap<>(),
<ide> Adapt.ANNOTATION_TO_MAP);
<ide> Map<String, Object>[] filters = (Map[]) map.get("excludeFilters");
<ide> List<String> patterns = Arrays.stream(filters).map(
<ide><path>spring-core/src/test/java/org/springframework/core/convert/converter/ConvertingComparatorTests.java
<ide> public int compare(Integer o1, Integer o2) {
<ide> assertThat(o2).isInstanceOf(Integer.class);
<ide> this.called = true;
<ide> return super.compare(o1, o2);
<del> };
<add> }
<ide>
<ide> public void assertCalled() {
<ide> assertThat(this.called).isTrue();
<ide><path>spring-core/src/test/java/org/springframework/util/AutoPopulatingListTests.java
<ide> void withElementFactory() throws Exception {
<ide>
<ide> @Test
<ide> void withElementFactoryAndUserSuppliedBackingList() throws Exception {
<del> doTestWithElementFactory(new AutoPopulatingList<Object>(new ArrayList<>(), new MockElementFactory()));
<add> doTestWithElementFactory(new AutoPopulatingList<>(new ArrayList<>(), new MockElementFactory()));
<ide> }
<ide>
<ide> private void doTestWithClass(AutoPopulatingList<Object> list) {
<ide><path>spring-core/src/test/java/org/springframework/util/ConcurrentReferenceHashMapTests.java
<ide> */
<ide> class ConcurrentReferenceHashMapTests {
<ide>
<del> private static final Comparator<? super String> NULL_SAFE_STRING_SORT = new NullSafeComparator<String>(
<add> private static final Comparator<? super String> NULL_SAFE_STRING_SORT = new NullSafeComparator<>(
<ide> new ComparableComparator<String>(), true);
<ide>
<ide> private TestWeakConcurrentCache<Integer, String> map = new TestWeakConcurrentCache<>();
<ide><path>spring-core/src/test/java/org/springframework/util/ReflectionUtilsTests.java
<ide> void bar(String s) throws IllegalArgumentException {
<ide>
<ide> int add(int... args) {
<ide> int sum = 0;
<del> for (int i = 0; i < args.length; i++) {
<del> sum += args[i];
<add> for (int arg : args) {
<add> sum += arg;
<ide> }
<ide> return sum;
<ide> }
<ide><path>spring-core/src/test/java/org/springframework/util/StringUtilsTests.java
<ide> void commaDelimitedListToStringArrayEmptyStrings() {
<ide> }
<ide>
<ide> private void doTestCommaDelimitedListToStringArrayLegalMatch(String[] components) {
<del> StringBuilder sb = new StringBuilder();
<del> for (int i = 0; i < components.length; i++) {
<del> if (i != 0) {
<del> sb.append(',');
<del> }
<del> sb.append(components[i]);
<del> }
<del> String[] sa = StringUtils.commaDelimitedListToStringArray(sb.toString());
<add> String sb = String.join(String.valueOf(','), components);
<add> String[] sa = StringUtils.commaDelimitedListToStringArray(sb);
<ide> assertThat(sa != null).as("String array isn't null with legal match").isTrue();
<ide> assertThat(sa.length).as("String array length is correct with legal match").isEqualTo(components.length);
<ide> assertThat(Arrays.equals(sa, components)).as("Output equals input").isTrue();
<ide><path>spring-jdbc/src/test/java/org/springframework/jdbc/core/AbstractRowMapperTests.java
<ide> protected void verifyPerson(EmailPerson person) {
<ide> }
<ide>
<ide>
<del> protected enum MockType {ONE, TWO, THREE};
<add> protected enum MockType {ONE, TWO, THREE}
<ide>
<ide>
<ide> protected static class Mock {
<ide><path>spring-jdbc/src/test/java/org/springframework/jdbc/core/JdbcTemplateQueryTests.java
<ide> import java.sql.PreparedStatement;
<ide> import java.sql.ResultSet;
<ide> import java.sql.ResultSetMetaData;
<del>import java.sql.SQLException;
<ide> import java.sql.Statement;
<ide> import java.util.List;
<ide> import java.util.Map;
<ide> public void testQueryForObjectWithRowMapper() throws Exception {
<ide> String sql = "SELECT AGE FROM CUSTMR WHERE ID = 3";
<ide> given(this.resultSet.next()).willReturn(true, false);
<ide> given(this.resultSet.getInt(1)).willReturn(22);
<del> Object o = this.template.queryForObject(sql, new RowMapper<Integer>() {
<del> @Override
<del> public Integer mapRow(ResultSet rs, int rowNum) throws SQLException {
<del> return rs.getInt(1);
<del> }
<del> });
<add> Object o = this.template.queryForObject(sql, (RowMapper<Integer>) (rs, rowNum) -> rs.getInt(1));
<ide> assertThat(o instanceof Integer).as("Correct result type").isTrue();
<ide> verify(this.resultSet).close();
<ide> verify(this.statement).close();
<ide><path>spring-jdbc/src/test/java/org/springframework/jdbc/core/JdbcTemplateTests.java
<ide> public void testBogusUpdate() throws Exception {
<ide>
<ide> @Test
<ide> public void testStringsWithStaticSql() throws Exception {
<del> doTestStrings(null, null, null, null, (template, sql, rch) -> template.query(sql, rch));
<add> doTestStrings(null, null, null, null, JdbcTemplate::query);
<ide> }
<ide>
<ide> @Test
<ide> public void testStringsWithStaticSqlAndFetchSizeAndMaxRows() throws Exception {
<del> doTestStrings(10, 20, 30, null, (template, sql, rch) -> template.query(sql, rch));
<add> doTestStrings(10, 20, 30, null, JdbcTemplate::query);
<ide> }
<ide>
<ide> @Test
<ide> public void testLeaveConnectionOpenOnRequest() throws Exception {
<ide>
<ide> @Test
<ide> public void testConnectionCallback() throws Exception {
<del> String result = this.template.execute(new ConnectionCallback<String>() {
<del> @Override
<del> public String doInConnection(Connection con) {
<del> assertThat(con instanceof ConnectionProxy).isTrue();
<del> assertThat(((ConnectionProxy) con).getTargetConnection()).isSameAs(JdbcTemplateTests.this.connection);
<del> return "test";
<del> }
<add> String result = this.template.execute((ConnectionCallback<String>) con -> {
<add> assertThat(con instanceof ConnectionProxy).isTrue();
<add> assertThat(((ConnectionProxy) con).getTargetConnection()).isSameAs(JdbcTemplateTests.this.connection);
<add> return "test";
<ide> });
<ide> assertThat(result).isEqualTo("test");
<ide> }
<ide>
<ide> @Test
<ide> public void testConnectionCallbackWithStatementSettings() throws Exception {
<del> String result = this.template.execute(new ConnectionCallback<String>() {
<del> @Override
<del> public String doInConnection(Connection con) throws SQLException {
<del> PreparedStatement ps = con.prepareStatement("some SQL");
<del> ps.setFetchSize(10);
<del> ps.setMaxRows(20);
<del> ps.close();
<del> return "test";
<del> }
<add> String result = this.template.execute((ConnectionCallback<String>) con -> {
<add> PreparedStatement ps = con.prepareStatement("some SQL");
<add> ps.setFetchSize(10);
<add> ps.setMaxRows(20);
<add> ps.close();
<add> return "test";
<ide> });
<ide>
<ide> assertThat(result).isEqualTo("test");
<ide><path>spring-jdbc/src/test/java/org/springframework/jdbc/core/namedparam/NamedParameterQueryTests.java
<ide> import java.sql.PreparedStatement;
<ide> import java.sql.ResultSet;
<ide> import java.sql.ResultSetMetaData;
<del>import java.sql.SQLException;
<ide> import java.sql.Types;
<ide> import java.util.ArrayList;
<ide> import java.util.Arrays;
<ide> public void testQueryForObjectWithParamMapAndRowMapper() throws Exception {
<ide> MapSqlParameterSource params = new MapSqlParameterSource();
<ide> params.addValue("id", 3);
<ide> Object o = template.queryForObject("SELECT AGE FROM CUSTMR WHERE ID = :id",
<del> params, new RowMapper<Object>() {
<del> @Override
<del> public Object mapRow(ResultSet rs, int rowNum) throws SQLException {
<del> return rs.getInt(1);
<del> }
<del> });
<add> params, (RowMapper<Object>) (rs, rowNum) -> rs.getInt(1));
<ide>
<ide> boolean condition = o instanceof Integer;
<ide> assertThat(condition).as("Correct result type").isTrue();
<ide><path>spring-jdbc/src/test/java/org/springframework/jdbc/object/StoredProcedureTests.java
<ide> /*
<del> * Copyright 2002-2019 the original author or authors.
<add> * Copyright 2002-2022 the original author or authors.
<ide> *
<ide> * Licensed under the Apache License, Version 2.0 (the "License");
<ide> * you may not use this file except in compliance with the License.
<ide> import org.springframework.jdbc.core.SqlReturnResultSet;
<ide> import org.springframework.jdbc.core.support.AbstractSqlTypeValue;
<ide> import org.springframework.jdbc.datasource.ConnectionHolder;
<del>import org.springframework.jdbc.support.SQLExceptionTranslator;
<ide> import org.springframework.jdbc.support.SQLStateSQLExceptionTranslator;
<del>import org.springframework.lang.Nullable;
<ide> import org.springframework.transaction.support.TransactionSynchronizationManager;
<ide>
<ide> import static org.assertj.core.api.Assertions.assertThat;
<ide> public void testAddInvoicesWithinTransaction() throws Exception {
<ide> given(callableStatement.execute()).willReturn(false);
<ide> given(callableStatement.getUpdateCount()).willReturn(-1);
<ide> given(callableStatement.getObject(3)).willReturn(4);
<del> given(connection.prepareCall("{call " + AddInvoice.SQL + "(?, ?, ?)}")
<del> ).willReturn(callableStatement);
<add> given(connection.prepareCall("{call " + AddInvoice.SQL + "(?, ?, ?)}")).willReturn(callableStatement);
<ide> TransactionSynchronizationManager.bindResource(dataSource, new ConnectionHolder(connection));
<ide> try {
<ide> testAddInvoice(1106, 3);
<ide> public void testStoredProcedureConfiguredViaJdbcTemplateWithCustomExceptionTrans
<ide> given(callableStatement.execute()).willReturn(false);
<ide> given(callableStatement.getUpdateCount()).willReturn(-1);
<ide> given(callableStatement.getObject(2)).willReturn(5);
<del> given(connection.prepareCall("{call " + StoredProcedureConfiguredViaJdbcTemplate.SQL + "(?, ?)}")
<del> ).willReturn(callableStatement);
<add> given(connection.prepareCall("{call " + StoredProcedureConfiguredViaJdbcTemplate.SQL + "(?, ?)}")).willReturn(callableStatement);
<ide>
<ide> class TestJdbcTemplate extends JdbcTemplate {
<ide>
<ide> public void testStoredProcedureConfiguredViaJdbcTemplate() throws Exception {
<ide> given(callableStatement.execute()).willReturn(false);
<ide> given(callableStatement.getUpdateCount()).willReturn(-1);
<ide> given(callableStatement.getObject(2)).willReturn(4);
<del> given(connection.prepareCall("{call " + StoredProcedureConfiguredViaJdbcTemplate.SQL + "(?, ?)}")
<del> ).willReturn(callableStatement);
<add> given(connection.prepareCall("{call " + StoredProcedureConfiguredViaJdbcTemplate.SQL + "(?, ?)}")).willReturn(callableStatement);
<ide> JdbcTemplate t = new JdbcTemplate();
<ide> t.setDataSource(dataSource);
<ide> StoredProcedureConfiguredViaJdbcTemplate sp = new StoredProcedureConfiguredViaJdbcTemplate(t);
<ide> public void testNullArg() throws Exception {
<ide> public void testUnnamedParameter() throws Exception {
<ide> this.verifyClosedAfter = false;
<ide> // Shouldn't succeed in creating stored procedure with unnamed parameter
<del> assertThatExceptionOfType(InvalidDataAccessApiUsageException.class).isThrownBy(() ->
<del> new UnnamedParameterStoredProcedure(dataSource));
<add> assertThatExceptionOfType(InvalidDataAccessApiUsageException.class)
<add> .isThrownBy(() -> new UnnamedParameterStoredProcedure(dataSource));
<ide> }
<ide>
<ide> @Test
<ide> public void testMissingParameter() throws Exception {
<ide> this.verifyClosedAfter = false;
<ide> MissingParameterStoredProcedure mp = new MissingParameterStoredProcedure(dataSource);
<del> assertThatExceptionOfType(InvalidDataAccessApiUsageException.class).isThrownBy(
<del> mp::execute);
<add> assertThatExceptionOfType(InvalidDataAccessApiUsageException.class).isThrownBy(mp::execute);
<ide> }
<ide>
<ide> @Test
<ide> public void testStoredProcedureExceptionTranslator() throws Exception {
<del> SQLException sqlException = new SQLException(
<del> "Syntax error or access violation exception", "42000");
<add> SQLException sqlException = new SQLException("Syntax error or access violation exception", "42000");
<ide> given(callableStatement.execute()).willThrow(sqlException);
<del> given(connection.prepareCall("{call " + StoredProcedureExceptionTranslator.SQL + "()}")
<del> ).willReturn(callableStatement);
<add> given(connection.prepareCall("{call " + StoredProcedureExceptionTranslator.SQL + "()}")).willReturn(callableStatement);
<ide> StoredProcedureExceptionTranslator sproc = new StoredProcedureExceptionTranslator(dataSource);
<del> assertThatExceptionOfType(CustomDataException.class).isThrownBy(
<del> sproc::execute);
<add> assertThatExceptionOfType(CustomDataException.class).isThrownBy(sproc::execute);
<ide> }
<ide>
<ide> @Test
<ide> public void testStoredProcedureWithResultSet() throws Exception {
<ide> given(callableStatement.getUpdateCount()).willReturn(-1);
<ide> given(callableStatement.getResultSet()).willReturn(resultSet);
<ide> given(callableStatement.getUpdateCount()).willReturn(-1);
<del> given(connection.prepareCall("{call " + StoredProcedureWithResultSet.SQL + "()}")
<del> ).willReturn(callableStatement);
<add> given(connection.prepareCall("{call " + StoredProcedureWithResultSet.SQL + "()}")).willReturn(callableStatement);
<ide> StoredProcedureWithResultSet sproc = new StoredProcedureWithResultSet(dataSource);
<ide> sproc.execute();
<ide> assertThat(sproc.getCount()).isEqualTo(2);
<ide> public void testStoredProcedureWithResultSetMapped() throws Exception {
<ide> given(callableStatement.getResultSet()).willReturn(resultSet);
<ide> given(callableStatement.getMoreResults()).willReturn(false);
<ide> given(callableStatement.getUpdateCount()).willReturn(-1);
<del> given(connection.prepareCall("{call " + StoredProcedureWithResultSetMapped.SQL + "()}")
<del> ).willReturn(callableStatement);
<add> given(connection.prepareCall("{call " + StoredProcedureWithResultSetMapped.SQL + "()}")).willReturn(callableStatement);
<ide> StoredProcedureWithResultSetMapped sproc = new StoredProcedureWithResultSetMapped(dataSource);
<ide> Map<String, Object> res = sproc.execute();
<ide> List<String> rs = (List<String>) res.get("rs");
<del> assertThat(rs.size()).isEqualTo(2);
<del> assertThat(rs.get(0)).isEqualTo("Foo");
<del> assertThat(rs.get(1)).isEqualTo("Bar");
<add> assertThat(rs).containsExactly("Foo", "Bar");
<ide> verify(resultSet).close();
<ide> }
<ide>
<ide> public void testStoredProcedureWithUndeclaredResults() throws Exception {
<ide> given(callableStatement.getResultSet()).willReturn(resultSet1, resultSet2);
<ide> given(callableStatement.getMoreResults()).willReturn(true, false, false);
<ide> given(callableStatement.getUpdateCount()).willReturn(-1, -1, 0, -1);
<del> given(connection.prepareCall("{call " + StoredProcedureWithResultSetMapped.SQL + "()}")
<del> ).willReturn(callableStatement);
<add> given(connection.prepareCall("{call " + StoredProcedureWithResultSetMapped.SQL + "()}")).willReturn(callableStatement);
<ide>
<ide> StoredProcedureWithResultSetMapped sproc = new StoredProcedureWithResultSetMapped(dataSource);
<ide> Map<String, Object> res = sproc.execute();
<ide>
<ide> assertThat(res.size()).as("incorrect number of returns").isEqualTo(3);
<ide>
<ide> List<String> rs1 = (List<String>) res.get("rs");
<del> assertThat(rs1.size()).isEqualTo(2);
<del> assertThat(rs1.get(0)).isEqualTo("Foo");
<del> assertThat(rs1.get(1)).isEqualTo("Bar");
<add> assertThat(rs1).containsExactly("Foo", "Bar");
<ide>
<ide> List<Object> rs2 = (List<Object>) res.get("#result-set-2");
<ide> assertThat(rs2.size()).isEqualTo(1);
<ide> Object o2 = rs2.get(0);
<del> boolean condition = o2 instanceof Map;
<del> assertThat(condition).as("wron type returned for result set 2").isTrue();
<add> assertThat(o2).as("wron type returned for result set 2").isInstanceOf(Map.class);
<ide> Map<String, String> m2 = (Map<String, String>) o2;
<ide> assertThat(m2.get("spam")).isEqualTo("Spam");
<ide> assertThat(m2.get("eggs")).isEqualTo("Eggs");
<ide> public void testStoredProcedureWithUndeclaredResults() throws Exception {
<ide> public void testStoredProcedureSkippingResultsProcessing() throws Exception {
<ide> given(callableStatement.execute()).willReturn(true);
<ide> given(callableStatement.getUpdateCount()).willReturn(-1);
<del> given(connection.prepareCall("{call " + StoredProcedureWithResultSetMapped.SQL + "()}")
<del> ).willReturn(callableStatement);
<add> given(connection.prepareCall("{call " + StoredProcedureWithResultSetMapped.SQL + "()}")).willReturn(callableStatement);
<ide> JdbcTemplate jdbcTemplate = new JdbcTemplate(dataSource);
<ide> jdbcTemplate.setSkipResultsProcessing(true);
<del> StoredProcedureWithResultSetMapped sproc = new StoredProcedureWithResultSetMapped(
<del> jdbcTemplate);
<add> StoredProcedureWithResultSetMapped sproc = new StoredProcedureWithResultSetMapped(jdbcTemplate);
<ide> Map<String, Object> res = sproc.execute();
<ide> assertThat(res.size()).as("incorrect number of returns").isEqualTo(0);
<ide> }
<ide> public void testStoredProcedureSkippingUndeclaredResults() throws Exception {
<ide> given(callableStatement.getResultSet()).willReturn(resultSet);
<ide> given(callableStatement.getMoreResults()).willReturn(true, false);
<ide> given(callableStatement.getUpdateCount()).willReturn(-1, -1);
<del> given(connection.prepareCall("{call " + StoredProcedureWithResultSetMapped.SQL + "()}")
<del> ).willReturn(callableStatement);
<add> given(connection.prepareCall("{call " + StoredProcedureWithResultSetMapped.SQL + "()}")).willReturn(callableStatement);
<ide>
<ide> JdbcTemplate jdbcTemplate = new JdbcTemplate(dataSource);
<ide> jdbcTemplate.setSkipUndeclaredResults(true);
<del> StoredProcedureWithResultSetMapped sproc = new StoredProcedureWithResultSetMapped(
<del> jdbcTemplate);
<add> StoredProcedureWithResultSetMapped sproc = new StoredProcedureWithResultSetMapped(jdbcTemplate);
<ide> Map<String, Object> res = sproc.execute();
<ide>
<ide> assertThat(res.size()).as("incorrect number of returns").isEqualTo(1);
<ide> public void testParameterMapper() throws Exception {
<ide> given(callableStatement.execute()).willReturn(false);
<ide> given(callableStatement.getUpdateCount()).willReturn(-1);
<ide> given(callableStatement.getObject(2)).willReturn("OK");
<del> given(connection.prepareCall("{call " + ParameterMapperStoredProcedure.SQL + "(?, ?)}")
<del> ).willReturn(callableStatement);
<add> given(connection.prepareCall("{call " + ParameterMapperStoredProcedure.SQL + "(?, ?)}")).willReturn(callableStatement);
<ide>
<ide> ParameterMapperStoredProcedure pmsp = new ParameterMapperStoredProcedure(dataSource);
<ide> Map<String, Object> out = pmsp.executeTest();
<ide> public void testSqlTypeValue() throws Exception {
<ide> given(callableStatement.execute()).willReturn(false);
<ide> given(callableStatement.getUpdateCount()).willReturn(-1);
<ide> given(callableStatement.getObject(2)).willReturn("OK");
<del> given(connection.prepareCall("{call " + SqlTypeValueStoredProcedure.SQL + "(?, ?)}")
<del> ).willReturn(callableStatement);
<add> given(connection.prepareCall("{call " + SqlTypeValueStoredProcedure.SQL + "(?, ?)}")).willReturn(callableStatement);
<ide>
<ide> SqlTypeValueStoredProcedure stvsp = new SqlTypeValueStoredProcedure(dataSource);
<ide> Map<String, Object> out = stvsp.executeTest(testVal);
<ide> public void testNumericWithScale() throws Exception {
<ide> given(callableStatement.execute()).willReturn(false);
<ide> given(callableStatement.getUpdateCount()).willReturn(-1);
<ide> given(callableStatement.getObject(1)).willReturn(new BigDecimal("12345.6789"));
<del> given(connection.prepareCall("{call " + NumericWithScaleStoredProcedure.SQL + "(?)}")
<del> ).willReturn(callableStatement);
<add> given(connection.prepareCall("{call " + NumericWithScaleStoredProcedure.SQL + "(?)}")).willReturn(callableStatement);
<ide> NumericWithScaleStoredProcedure nwssp = new NumericWithScaleStoredProcedure(dataSource);
<ide> Map<String, Object> out = nwssp.executeTest();
<ide> assertThat(out.get("out")).isEqualTo(new BigDecimal("12345.6789"));
<ide> private static class StoredProcedureExceptionTranslator extends StoredProcedure
<ide> public StoredProcedureExceptionTranslator(DataSource ds) {
<ide> setDataSource(ds);
<ide> setSql(SQL);
<del> getJdbcTemplate().setExceptionTranslator(new SQLExceptionTranslator() {
<del> @Override
<del> public DataAccessException translate(String task, @Nullable String sql, SQLException ex) {
<del> return new CustomDataException(sql, ex);
<del> }
<del> });
<add> getJdbcTemplate().setExceptionTranslator((task, sql, ex) -> new CustomDataException(sql, ex));
<ide> compile();
<ide> }
<ide>
<ide><path>spring-jdbc/src/test/java/org/springframework/jdbc/support/SQLErrorCodeSQLExceptionTranslatorTests.java
<ide> /*
<del> * Copyright 2002-2020 the original author or authors.
<add> * Copyright 2002-2022 the original author or authors.
<ide> *
<ide> * Licensed under the Apache License, Version 2.0 (the "License");
<ide> * you may not use this file except in compliance with the License.
<ide> public void errorCodeTranslation() {
<ide>
<ide> SQLException dupKeyEx = new SQLException("", "", 10);
<ide> DataAccessException dksex = sext.translate("task", "SQL", dupKeyEx);
<del> assertThat(DataIntegrityViolationException.class.isInstance(dksex)).as("Not instance of DataIntegrityViolationException").isTrue();
<add> assertThat(dksex).isInstanceOf(DataIntegrityViolationException.class);
<ide>
<ide> // Test fallback. We assume that no database will ever return this error code,
<ide> // but 07xxx will be bad grammar picked up by the fallback SQLState translator
<ide><path>spring-jms/src/test/java/org/springframework/jms/core/JmsTemplateTests.java
<ide> void testSessionCallback() throws Exception {
<ide> JmsTemplate template = createTemplate();
<ide> template.setConnectionFactory(this.connectionFactory);
<ide>
<del> template.execute(new SessionCallback<Void>() {
<del> @Override
<del> public Void doInJms(Session session) throws JMSException {
<del> session.getTransacted();
<del> return null;
<del> }
<add> template.execute((SessionCallback<Void>) session -> {
<add> session.getTransacted();
<add> return null;
<ide> });
<ide>
<ide> verify(this.session).close();
<ide> void testSessionCallbackWithinSynchronizedTransaction() throws Exception {
<ide>
<ide> TransactionSynchronizationManager.initSynchronization();
<ide> try {
<del> template.execute(new SessionCallback<Void>() {
<del> @Override
<del> public Void doInJms(Session session) throws JMSException {
<del> session.getTransacted();
<del> return null;
<del> }
<add> template.execute((SessionCallback<Void>) session -> {
<add> session.getTransacted();
<add> return null;
<ide> });
<del> template.execute(new SessionCallback<Void>() {
<del> @Override
<del> public Void doInJms(Session session) throws JMSException {
<del> session.getTransacted();
<del> return null;
<del> }
<add> template.execute((SessionCallback<Void>) session -> {
<add> session.getTransacted();
<add> return null;
<ide> });
<ide>
<ide> assertThat(ConnectionFactoryUtils.getTransactionalSession(scf, null, false)).isSameAs(this.session);
<ide> private void doTestSendDestination(
<ide> }
<ide>
<ide> if (useDefaultDestination) {
<del> template.send(new MessageCreator() {
<del> @Override
<del> public Message createMessage(Session session) throws JMSException {
<del> return session.createTextMessage("just testing");
<del> }
<del> });
<add> template.send(session -> session.createTextMessage("just testing"));
<ide> }
<ide> else {
<ide> if (explicitDestination) {
<del> template.send(this.queue, new MessageCreator() {
<del> @Override
<del> public Message createMessage(Session session) throws JMSException {
<del> return session.createTextMessage("just testing");
<del> }
<del> });
<add> template.send(this.queue, (MessageCreator) session -> session.createTextMessage("just testing"));
<ide> }
<ide> else {
<del> template.send(destinationName, new MessageCreator() {
<del> @Override
<del> public Message createMessage(Session session) throws JMSException {
<del> return session.createTextMessage("just testing");
<del> }
<del> });
<add> template.send(destinationName, (MessageCreator) session -> session.createTextMessage("just testing"));
<ide> }
<ide> }
<ide>
<ide><path>spring-jms/src/test/java/org/springframework/jms/listener/SimpleMessageListenerContainerTests.java
<ide> import org.junit.jupiter.api.Test;
<ide>
<ide> import org.springframework.context.support.GenericApplicationContext;
<del>import org.springframework.core.task.TaskExecutor;
<ide> import org.springframework.jms.StubQueue;
<ide> import org.springframework.lang.Nullable;
<ide> import org.springframework.util.ErrorHandler;
<ide> public void testCorrectSessionExposedForSessionAwareMessageListenerInvocation()
<ide>
<ide> this.container.setConnectionFactory(connectionFactory);
<ide> this.container.setDestinationName(DESTINATION_NAME);
<del> this.container.setMessageListener(new SessionAwareMessageListener<Message>() {
<del> @Override
<del> public void onMessage(Message message, @Nullable Session sess) {
<del> try {
<del> // Check correct Session passed into SessionAwareMessageListener.
<del> assertThat(session).isSameAs(sess);
<del> }
<del> catch (Throwable ex) {
<del> failure.add("MessageListener execution failed: " + ex);
<del> }
<add> this.container.setMessageListener((SessionAwareMessageListener<Message>) (Message message, @Nullable Session sess) -> {
<add> try {
<add> // Check correct Session passed into SessionAwareMessageListener.
<add> assertThat(session).isSameAs(sess);
<add> }
<add> catch (Throwable ex) {
<add> failure.add("MessageListener execution failed: " + ex);
<ide> }
<ide> });
<ide>
<ide> public void testTaskExecutorCorrectlyInvokedWhenSpecified() throws Exception {
<ide> this.container.setConnectionFactory(connectionFactory);
<ide> this.container.setDestinationName(DESTINATION_NAME);
<ide> this.container.setMessageListener(listener);
<del> this.container.setTaskExecutor(new TaskExecutor() {
<del> @Override
<del> public void execute(Runnable task) {
<del> listener.executorInvoked = true;
<del> assertThat(listener.listenerInvoked).isFalse();
<del> task.run();
<del> assertThat(listener.listenerInvoked).isTrue();
<del> }
<add> this.container.setTaskExecutor(task -> {
<add> listener.executorInvoked = true;
<add> assertThat(listener.listenerInvoked).isFalse();
<add> task.run();
<add> assertThat(listener.listenerInvoked).isTrue();
<ide> });
<ide> this.container.afterPropertiesSet();
<ide> this.container.start();
<ide> public void testRegisteredExceptionListenerIsInvokedOnException() throws Excepti
<ide>
<ide> this.container.setConnectionFactory(connectionFactory);
<ide> this.container.setDestinationName(DESTINATION_NAME);
<del> this.container.setMessageListener(new SessionAwareMessageListener<Message>() {
<del> @Override
<del> public void onMessage(Message message, @Nullable Session session) throws JMSException {
<del> throw theException;
<del> }
<add> this.container.setMessageListener((SessionAwareMessageListener<Message>) (Message message, @Nullable Session session1) -> {
<add> throw theException;
<ide> });
<ide>
<ide> ExceptionListener exceptionListener = mock(ExceptionListener.class);
<ide> public void testRegisteredErrorHandlerIsInvokedOnException() throws Exception {
<ide>
<ide> this.container.setConnectionFactory(connectionFactory);
<ide> this.container.setDestinationName(DESTINATION_NAME);
<del> this.container.setMessageListener(new SessionAwareMessageListener<Message>() {
<del> @Override
<del> public void onMessage(Message message, @Nullable Session session) throws JMSException {
<del> throw theException;
<del> }
<add> this.container.setMessageListener((SessionAwareMessageListener<Message>) (Message message, @Nullable Session session1) -> {
<add> throw theException;
<ide> });
<ide>
<ide> ErrorHandler errorHandler = mock(ErrorHandler.class);
<ide> public void testNoRollbackOccursIfSessionIsNotTransactedAndThatExceptionsDo_NOT_
<ide>
<ide> this.container.setConnectionFactory(connectionFactory);
<ide> this.container.setDestinationName(DESTINATION_NAME);
<del> this.container.setMessageListener(new MessageListener() {
<del> @Override
<del> public void onMessage(Message message) {
<del> throw new UnsupportedOperationException();
<del> }
<add> this.container.setMessageListener((MessageListener) message -> {
<add> throw new UnsupportedOperationException();
<ide> });
<ide> this.container.afterPropertiesSet();
<ide> this.container.start();
<ide> public void testTransactedSessionsGetRollbackLogicAppliedAndThatExceptionsStillD
<ide>
<ide> this.container.setConnectionFactory(connectionFactory);
<ide> this.container.setDestinationName(DESTINATION_NAME);
<del> this.container.setMessageListener(new MessageListener() {
<del> @Override
<del> public void onMessage(Message message) {
<del> throw new UnsupportedOperationException();
<del> }
<add> this.container.setMessageListener((MessageListener) message -> {
<add> throw new UnsupportedOperationException();
<ide> });
<ide> this.container.afterPropertiesSet();
<ide> this.container.start();
<ide><path>spring-jms/src/test/java/org/springframework/jms/listener/adapter/MessagingMessageListenerAdapterTests.java
<ide> public void wrongParam(Integer i) {
<ide> }
<ide> }
<ide>
<del> interface Summary {};
<del> interface Full extends Summary {};
<add> interface Summary {}
<add> interface Full extends Summary {}
<ide>
<ide> @SuppressWarnings("unused")
<ide> private static class SampleResponse {
<ide><path>spring-jms/src/test/java/org/springframework/jms/support/SimpleMessageConverterTests.java
<ide> import javax.jms.TextMessage;
<ide>
<ide> import org.junit.jupiter.api.Test;
<del>import org.mockito.invocation.InvocationOnMock;
<del>import org.mockito.stubbing.Answer;
<ide>
<ide> import org.springframework.jms.support.converter.MessageConversionException;
<ide> import org.springframework.jms.support.converter.SimpleMessageConverter;
<ide> public void testByteArrayConversion() throws JMSException {
<ide>
<ide> given(session.createBytesMessage()).willReturn(message);
<ide> given(message.getBodyLength()).willReturn((long) content.length);
<del> given(message.readBytes(any(byte[].class))).willAnswer(new Answer<Integer>() {
<del> @Override
<del> public Integer answer(InvocationOnMock invocation) throws Throwable {
<del> return byteArrayInputStream.read((byte[]) invocation.getArguments()[0]);
<del> }
<del> });
<add> given(message.readBytes(any(byte[].class))).willAnswer(invocation -> byteArrayInputStream.read((byte[]) invocation.getArguments()[0]));
<ide>
<ide> SimpleMessageConverter converter = new SimpleMessageConverter();
<ide> Message msg = converter.toMessage(content, session);
<ide><path>spring-jms/src/test/java/org/springframework/jms/support/converter/MappingJackson2MessageConverterTests.java
<ide> public int hashCode() {
<ide> }
<ide>
<ide>
<del> private interface Summary {};
<add> private interface Summary {}
<ide>
<del> private interface Full extends Summary {};
<add> private interface Full extends Summary {}
<ide>
<ide>
<ide> @SuppressWarnings("unused")
<ide><path>spring-messaging/src/test/java/org/springframework/messaging/converter/MappingJackson2MessageConverterTests.java
<ide> public void setArray(String[] array) {
<ide> }
<ide>
<ide>
<del> public interface MyJacksonView1 {};
<add> public interface MyJacksonView1 {}
<ide>
<del> public interface MyJacksonView2 {};
<add> public interface MyJacksonView2 {}
<ide>
<ide>
<ide> public static class JacksonViewBean {
<ide><path>spring-messaging/src/test/java/org/springframework/messaging/core/GenericMessagingTemplateTests.java
<ide> import org.springframework.messaging.MessageDeliveryException;
<ide> import org.springframework.messaging.MessageHandler;
<ide> import org.springframework.messaging.MessageHeaders;
<del>import org.springframework.messaging.MessagingException;
<ide> import org.springframework.messaging.StubMessageChannel;
<ide> import org.springframework.messaging.SubscribableChannel;
<ide> import org.springframework.messaging.support.ExecutorSubscribableChannel;
<ide> public void sendWithTimeoutMutable() {
<ide> @Test
<ide> public void sendAndReceive() {
<ide> SubscribableChannel channel = new ExecutorSubscribableChannel(this.executor);
<del> channel.subscribe(new MessageHandler() {
<del> @Override
<del> public void handleMessage(Message<?> message) throws MessagingException {
<del> MessageChannel replyChannel = (MessageChannel) message.getHeaders().getReplyChannel();
<del> replyChannel.send(new GenericMessage<>("response"));
<del> }
<add> channel.subscribe(message -> {
<add> MessageChannel replyChannel = (MessageChannel) message.getHeaders().getReplyChannel();
<add> replyChannel.send(new GenericMessage<>("response"));
<ide> });
<ide>
<ide> String actual = this.template.convertSendAndReceive(channel, "request", String.class);
<ide> public void handleMessage(Message<?> message) throws MessagingException {
<ide>
<ide> @Test
<ide> public void sendAndReceiveTimeout() throws InterruptedException {
<del> final AtomicReference<Throwable> failure = new AtomicReference<Throwable>();
<add> final AtomicReference<Throwable> failure = new AtomicReference<>();
<ide> final CountDownLatch latch = new CountDownLatch(1);
<ide>
<ide> this.template.setReceiveTimeout(1);
<ide> public void sendAndReceiveTimeout() throws InterruptedException {
<ide>
<ide> @Test
<ide> public void sendAndReceiveVariableTimeout() throws InterruptedException {
<del> final AtomicReference<Throwable> failure = new AtomicReference<Throwable>();
<add> final AtomicReference<Throwable> failure = new AtomicReference<>();
<ide> final CountDownLatch latch = new CountDownLatch(1);
<ide>
<ide> this.template.setSendTimeout(20_000);
<ide> public void sendAndReceiveVariableTimeout() throws InterruptedException {
<ide>
<ide> @Test
<ide> public void sendAndReceiveVariableTimeoutCustomHeaders() throws InterruptedException {
<del> final AtomicReference<Throwable> failure = new AtomicReference<Throwable>();
<add> final AtomicReference<Throwable> failure = new AtomicReference<>();
<ide> final CountDownLatch latch = new CountDownLatch(1);
<ide>
<ide> this.template.setSendTimeout(20_000);
<ide><path>spring-messaging/src/test/java/org/springframework/messaging/handler/annotation/reactive/MessageMappingMessageHandlerTests.java
<ide> private MessageMappingMessageHandler initMesssageHandler() {
<ide> }
<ide>
<ide> private Message<?> message(String destination, String... content) {
<del> Flux<DataBuffer> payload = Flux.fromIterable(Arrays.asList(content)).map(parts -> toDataBuffer(parts));
<add> Flux<DataBuffer> payload = Flux.fromIterable(Arrays.asList(content)).map(this::toDataBuffer);
<ide> MessageHeaderAccessor headers = new MessageHeaderAccessor();
<ide> headers.setLeaveMutable(true);
<ide> headers.setHeader(DestinationPatternsMessageCondition.LOOKUP_DESTINATION_HEADER,
<ide><path>spring-messaging/src/test/java/org/springframework/messaging/handler/annotation/support/DefaultMessageHandlerMethodFactoryTests.java
<ide>
<ide> import org.springframework.beans.factory.support.StaticListableBeanFactory;
<ide> import org.springframework.core.MethodParameter;
<del>import org.springframework.core.convert.converter.Converter;
<ide> import org.springframework.core.convert.support.GenericConversionService;
<ide> import org.springframework.messaging.Message;
<ide> import org.springframework.messaging.converter.ByteArrayMessageConverter;
<ide> public class DefaultMessageHandlerMethodFactoryTests {
<ide> public void customConversion() throws Exception {
<ide> DefaultMessageHandlerMethodFactory instance = createInstance();
<ide> GenericConversionService conversionService = new GenericConversionService();
<del> conversionService.addConverter(SampleBean.class, String.class, new Converter<SampleBean, String>() {
<del> @Override
<del> public String convert(SampleBean source) {
<del> return "foo bar";
<del> }
<del> });
<add> conversionService.addConverter(SampleBean.class, String.class, source -> "foo bar");
<ide> instance.setConversionService(conversionService);
<ide> instance.afterPropertiesSet();
<ide>
<ide><path>spring-messaging/src/test/java/org/springframework/messaging/simp/SimpAttributesContextHolderTests.java
<ide> public void currentAttributes() {
<ide>
<ide> @Test
<ide> public void currentAttributesNone() {
<del> assertThatIllegalStateException().isThrownBy(() ->
<del> SimpAttributesContextHolder.currentAttributes())
<add> assertThatIllegalStateException().isThrownBy(SimpAttributesContextHolder::currentAttributes)
<ide> .withMessageStartingWith("No thread-bound SimpAttributes found");
<ide> }
<ide>
<ide><path>spring-messaging/src/test/java/org/springframework/messaging/simp/annotation/support/SubscriptionMethodReturnValueHandlerTests.java
<ide> public JacksonViewBean getJsonView() {
<ide> }
<ide>
<ide>
<del> private interface MyJacksonView1 {};
<del> private interface MyJacksonView2 {};
<add> private interface MyJacksonView1 {}
<add> private interface MyJacksonView2 {}
<ide>
<ide> private static class JacksonViewBean {
<ide>
<ide><path>spring-messaging/src/test/java/org/springframework/messaging/simp/stomp/StompBrokerRelayMessageHandlerTests.java
<ide> import java.util.ArrayList;
<ide> import java.util.Collections;
<ide> import java.util.List;
<del>import java.util.concurrent.Callable;
<ide>
<ide> import org.junit.jupiter.api.BeforeEach;
<ide> import org.junit.jupiter.api.Test;
<ide> private Message<byte[]> message(StompCommand command, String sessionId, String u
<ide>
<ide>
<ide> private static ListenableFutureTask<Void> getVoidFuture() {
<del> ListenableFutureTask<Void> futureTask = new ListenableFutureTask<>(new Callable<Void>() {
<del> @Override
<del> public Void call() {
<del> return null;
<del> }
<del> });
<add> ListenableFutureTask<Void> futureTask = new ListenableFutureTask<>(() -> null);
<ide> futureTask.run();
<ide> return futureTask;
<ide> }
<ide><path>spring-orm/src/test/java/org/springframework/orm/jpa/JpaTransactionManagerTests.java
<ide> import org.springframework.transaction.TransactionDefinition;
<ide> import org.springframework.transaction.TransactionStatus;
<ide> import org.springframework.transaction.TransactionSystemException;
<del>import org.springframework.transaction.support.TransactionCallback;
<ide> import org.springframework.transaction.support.TransactionCallbackWithoutResult;
<ide> import org.springframework.transaction.support.TransactionSynchronization;
<ide> import org.springframework.transaction.support.TransactionSynchronizationManager;
<ide> public void testTransactionCommit() {
<ide> boolean condition2 = !TransactionSynchronizationManager.isSynchronizationActive();
<ide> assertThat(condition2).isTrue();
<ide>
<del> Object result = tt.execute(new TransactionCallback() {
<del> @Override
<del> public Object doInTransaction(TransactionStatus status) {
<del> assertThat(TransactionSynchronizationManager.hasResource(factory)).isTrue();
<del> EntityManagerFactoryUtils.getTransactionalEntityManager(factory).flush();
<del> return l;
<del> }
<add> Object result = tt.execute(status -> {
<add> assertThat(TransactionSynchronizationManager.hasResource(factory)).isTrue();
<add> EntityManagerFactoryUtils.getTransactionalEntityManager(factory).flush();
<add> return l;
<ide> });
<ide> assertThat(result).isSameAs(l);
<ide>
<ide> public void testTransactionCommitWithRollbackException() {
<ide> assertThat(condition2).isTrue();
<ide>
<ide> try {
<del> Object result = tt.execute(new TransactionCallback() {
<del> @Override
<del> public Object doInTransaction(TransactionStatus status) {
<del> assertThat(TransactionSynchronizationManager.hasResource(factory)).isTrue();
<del> EntityManagerFactoryUtils.getTransactionalEntityManager(factory).flush();
<del> return l;
<del> }
<add> Object result = tt.execute(status -> {
<add> assertThat(TransactionSynchronizationManager.hasResource(factory)).isTrue();
<add> EntityManagerFactoryUtils.getTransactionalEntityManager(factory).flush();
<add> return l;
<ide> });
<ide> assertThat(result).isSameAs(l);
<ide> }
<ide> public void testTransactionRollback() {
<ide> assertThat(condition2).isTrue();
<ide>
<ide> assertThatExceptionOfType(RuntimeException.class).isThrownBy(() ->
<del> tt.execute(new TransactionCallback() {
<del> @Override
<del> public Object doInTransaction(TransactionStatus status) {
<del> assertThat(TransactionSynchronizationManager.hasResource(factory)).isTrue();
<del> EntityManagerFactoryUtils.getTransactionalEntityManager(factory);
<del> throw new RuntimeException("some exception");
<del> }
<add> tt.execute(status -> {
<add> assertThat(TransactionSynchronizationManager.hasResource(factory)).isTrue();
<add> EntityManagerFactoryUtils.getTransactionalEntityManager(factory);
<add> throw new RuntimeException("some exception");
<ide> })).withMessage("some exception");
<ide>
<ide> boolean condition1 = !TransactionSynchronizationManager.hasResource(factory);
<ide> public void testTransactionRollbackWithAlreadyRolledBack() {
<ide> assertThat(condition2).isTrue();
<ide>
<ide> assertThatExceptionOfType(RuntimeException.class).isThrownBy(() ->
<del> tt.execute(new TransactionCallback() {
<del> @Override
<del> public Object doInTransaction(TransactionStatus status) {
<del> assertThat(TransactionSynchronizationManager.hasResource(factory)).isTrue();
<del> EntityManagerFactoryUtils.getTransactionalEntityManager(factory);
<del> throw new RuntimeException("some exception");
<del> }
<add> tt.execute(status -> {
<add> assertThat(TransactionSynchronizationManager.hasResource(factory)).isTrue();
<add> EntityManagerFactoryUtils.getTransactionalEntityManager(factory);
<add> throw new RuntimeException("some exception");
<ide> }));
<ide>
<ide> boolean condition1 = !TransactionSynchronizationManager.hasResource(factory);
<ide> public void testTransactionRollbackOnly() {
<ide> boolean condition2 = !TransactionSynchronizationManager.isSynchronizationActive();
<ide> assertThat(condition2).isTrue();
<ide>
<del> tt.execute(new TransactionCallback() {
<del> @Override
<del> public Object doInTransaction(TransactionStatus status) {
<del> assertThat(TransactionSynchronizationManager.hasResource(factory)).isTrue();
<add> tt.execute(status -> {
<add> assertThat(TransactionSynchronizationManager.hasResource(factory)).isTrue();
<ide>
<del> EntityManagerFactoryUtils.getTransactionalEntityManager(factory).flush();
<del> status.setRollbackOnly();
<add> EntityManagerFactoryUtils.getTransactionalEntityManager(factory).flush();
<add> status.setRollbackOnly();
<ide>
<del> return l;
<del> }
<add> return l;
<ide> });
<ide>
<ide> boolean condition1 = !TransactionSynchronizationManager.hasResource(factory);
<ide> public void testParticipatingTransactionWithCommit() {
<ide> boolean condition2 = !TransactionSynchronizationManager.isSynchronizationActive();
<ide> assertThat(condition2).isTrue();
<ide>
<del> tt.execute(new TransactionCallback() {
<del> @Override
<del> public Object doInTransaction(TransactionStatus status) {
<del> assertThat(TransactionSynchronizationManager.hasResource(factory)).isTrue();
<add> tt.execute(status -> {
<add> assertThat(TransactionSynchronizationManager.hasResource(factory)).isTrue();
<ide>
<del> return tt.execute(new TransactionCallback() {
<del> @Override
<del> public Object doInTransaction(TransactionStatus status) {
<del> EntityManagerFactoryUtils.getTransactionalEntityManager(factory).flush();
<del> return l;
<del> }
<del> });
<del> }
<add> return tt.execute(status1 -> {
<add> EntityManagerFactoryUtils.getTransactionalEntityManager(factory).flush();
<add> return l;
<add> });
<ide> });
<ide>
<ide> boolean condition1 = !TransactionSynchronizationManager.hasResource(factory);
<ide> public void testParticipatingTransactionWithRollback() {
<ide> assertThat(condition2).isTrue();
<ide>
<ide> assertThatExceptionOfType(RuntimeException.class).isThrownBy(() ->
<del> tt.execute(new TransactionCallback() {
<del> @Override
<del> public Object doInTransaction(TransactionStatus status) {
<del> assertThat(TransactionSynchronizationManager.hasResource(factory)).isTrue();
<del> return tt.execute(new TransactionCallback() {
<del> @Override
<del> public Object doInTransaction(TransactionStatus status) {
<del> EntityManagerFactoryUtils.getTransactionalEntityManager(factory);
<del> throw new RuntimeException("some exception");
<del> }
<del> });
<del> }
<add> tt.execute(status -> {
<add> assertThat(TransactionSynchronizationManager.hasResource(factory)).isTrue();
<add> return tt.execute(status1 -> {
<add> EntityManagerFactoryUtils.getTransactionalEntityManager(factory);
<add> throw new RuntimeException("some exception");
<add> });
<ide> }));
<ide>
<ide> boolean condition1 = !TransactionSynchronizationManager.hasResource(factory);
<ide> public void testParticipatingTransactionWithRollbackOnly() {
<ide> assertThat(condition2).isTrue();
<ide>
<ide> assertThatExceptionOfType(TransactionSystemException.class).isThrownBy(() ->
<del> tt.execute(new TransactionCallback() {
<del> @Override
<del> public Object doInTransaction(TransactionStatus status) {
<del> assertThat(TransactionSynchronizationManager.hasResource(factory)).isTrue();
<del>
<del> return tt.execute(new TransactionCallback() {
<del> @Override
<del> public Object doInTransaction(TransactionStatus status) {
<del> EntityManagerFactoryUtils.getTransactionalEntityManager(factory).flush();
<del> status.setRollbackOnly();
<del> return null;
<del> }
<del> });
<del> }
<add> tt.execute(status -> {
<add> assertThat(TransactionSynchronizationManager.hasResource(factory)).isTrue();
<add>
<add> return tt.execute(status1 -> {
<add> EntityManagerFactoryUtils.getTransactionalEntityManager(factory).flush();
<add> status1.setRollbackOnly();
<add> return null;
<add> });
<ide> }))
<ide> .withCauseInstanceOf(RollbackException.class);
<ide>
<ide> public void testParticipatingTransactionWithRequiresNew() {
<ide> boolean condition2 = !TransactionSynchronizationManager.isSynchronizationActive();
<ide> assertThat(condition2).isTrue();
<ide>
<del> Object result = tt.execute(new TransactionCallback() {
<del> @Override
<del> public Object doInTransaction(TransactionStatus status) {
<del> assertThat(TransactionSynchronizationManager.hasResource(factory)).isTrue();
<del> return tt.execute(new TransactionCallback() {
<del> @Override
<del> public Object doInTransaction(TransactionStatus status) {
<del> EntityManagerFactoryUtils.getTransactionalEntityManager(factory).flush();
<del> return l;
<del> }
<del> });
<del> }
<add> Object result = tt.execute(status -> {
<add> assertThat(TransactionSynchronizationManager.hasResource(factory)).isTrue();
<add> return tt.execute(status1 -> {
<add> EntityManagerFactoryUtils.getTransactionalEntityManager(factory).flush();
<add> return l;
<add> });
<ide> });
<ide> assertThat(result).isSameAs(l);
<ide>
<ide> public void testParticipatingTransactionWithRequiresNewAndPrebound() {
<ide> TransactionSynchronizationManager.bindResource(factory, new EntityManagerHolder(manager));
<ide>
<ide> try {
<del> Object result = tt.execute(new TransactionCallback() {
<del> @Override
<del> public Object doInTransaction(TransactionStatus status) {
<del> EntityManagerFactoryUtils.getTransactionalEntityManager(factory);
<add> Object result = tt.execute(status -> {
<add> EntityManagerFactoryUtils.getTransactionalEntityManager(factory);
<ide>
<del> assertThat(TransactionSynchronizationManager.hasResource(factory)).isTrue();
<del> return tt.execute(new TransactionCallback() {
<del> @Override
<del> public Object doInTransaction(TransactionStatus status) {
<del> EntityManagerFactoryUtils.getTransactionalEntityManager(factory).flush();
<del> return l;
<del> }
<del> });
<del> }
<add> assertThat(TransactionSynchronizationManager.hasResource(factory)).isTrue();
<add> return tt.execute(status1 -> {
<add> EntityManagerFactoryUtils.getTransactionalEntityManager(factory).flush();
<add> return l;
<add> });
<ide> });
<ide> assertThat(result).isSameAs(l);
<ide> }
<ide> public void testPropagationSupportsAndRequiresNew() {
<ide> boolean condition2 = !TransactionSynchronizationManager.isSynchronizationActive();
<ide> assertThat(condition2).isTrue();
<ide>
<del> Object result = tt.execute(new TransactionCallback() {
<del> @Override
<del> public Object doInTransaction(TransactionStatus status) {
<del> assertThat(TransactionSynchronizationManager.hasResource(factory)).isFalse();
<del> TransactionTemplate tt2 = new TransactionTemplate(tm);
<del> tt2.setPropagationBehavior(TransactionDefinition.PROPAGATION_REQUIRES_NEW);
<del> return tt2.execute(new TransactionCallback() {
<del> @Override
<del> public Object doInTransaction(TransactionStatus status) {
<del> EntityManagerFactoryUtils.getTransactionalEntityManager(factory).flush();
<del> return l;
<del> }
<del> });
<del> }
<add> Object result = tt.execute(status -> {
<add> assertThat(TransactionSynchronizationManager.hasResource(factory)).isFalse();
<add> TransactionTemplate tt2 = new TransactionTemplate(tm);
<add> tt2.setPropagationBehavior(TransactionDefinition.PROPAGATION_REQUIRES_NEW);
<add> return tt2.execute(status1 -> {
<add> EntityManagerFactoryUtils.getTransactionalEntityManager(factory).flush();
<add> return l;
<add> });
<ide> });
<ide> assertThat(result).isSameAs(l);
<ide>
<ide> public void testPropagationSupportsAndRequiresNewAndEarlyAccess() {
<ide> boolean condition2 = !TransactionSynchronizationManager.isSynchronizationActive();
<ide> assertThat(condition2).isTrue();
<ide>
<del> Object result = tt.execute(new TransactionCallback() {
<del> @Override
<del> public Object doInTransaction(TransactionStatus status) {
<del> EntityManagerFactoryUtils.getTransactionalEntityManager(factory);
<add> Object result = tt.execute(status -> {
<add> EntityManagerFactoryUtils.getTransactionalEntityManager(factory);
<ide>
<del> assertThat(TransactionSynchronizationManager.hasResource(factory)).isTrue();
<del> TransactionTemplate tt2 = new TransactionTemplate(tm);
<del> tt2.setPropagationBehavior(TransactionDefinition.PROPAGATION_REQUIRES_NEW);
<del> return tt2.execute(new TransactionCallback() {
<del> @Override
<del> public Object doInTransaction(TransactionStatus status) {
<del> EntityManagerFactoryUtils.getTransactionalEntityManager(factory).flush();
<del> return l;
<del> }
<del> });
<del> }
<add> assertThat(TransactionSynchronizationManager.hasResource(factory)).isTrue();
<add> TransactionTemplate tt2 = new TransactionTemplate(tm);
<add> tt2.setPropagationBehavior(TransactionDefinition.PROPAGATION_REQUIRES_NEW);
<add> return tt2.execute(status1 -> {
<add> EntityManagerFactoryUtils.getTransactionalEntityManager(factory).flush();
<add> return l;
<add> });
<ide> });
<ide> assertThat(result).isSameAs(l);
<ide>
<ide> public void testTransactionWithRequiresNewInAfterCompletion() {
<ide> boolean condition2 = !TransactionSynchronizationManager.isSynchronizationActive();
<ide> assertThat(condition2).isTrue();
<ide>
<del> tt.execute(new TransactionCallback() {
<del> @Override
<del> public Object doInTransaction(TransactionStatus status) {
<del> EntityManagerFactoryUtils.getTransactionalEntityManager(factory).flush();
<del> TransactionSynchronizationManager.registerSynchronization(new TransactionSynchronization() {
<del> @Override
<del> public void afterCompletion(int status) {
<del> tt.execute(new TransactionCallback() {
<del> @Override
<del> public Object doInTransaction(TransactionStatus status) {
<del> EntityManagerFactoryUtils.getTransactionalEntityManager(factory).flush();
<del> return null;
<del> }
<del> });
<del> }
<del> });
<del> return null;
<del> }
<add> tt.execute(status -> {
<add> EntityManagerFactoryUtils.getTransactionalEntityManager(factory).flush();
<add> TransactionSynchronizationManager.registerSynchronization(new TransactionSynchronization() {
<add> @Override
<add> public void afterCompletion(int status) {
<add> tt.execute(status1 -> {
<add> EntityManagerFactoryUtils.getTransactionalEntityManager(factory).flush();
<add> return null;
<add> });
<add> }
<add> });
<add> return null;
<ide> });
<ide>
<ide> boolean condition1 = !TransactionSynchronizationManager.hasResource(factory);
<ide> public void testTransactionCommitWithPropagationSupports() {
<ide> boolean condition2 = !TransactionSynchronizationManager.isSynchronizationActive();
<ide> assertThat(condition2).isTrue();
<ide>
<del> Object result = tt.execute(new TransactionCallback() {
<del> @Override
<del> public Object doInTransaction(TransactionStatus status) {
<del> boolean condition1 = !TransactionSynchronizationManager.hasResource(factory);
<del> assertThat(condition1).isTrue();
<del> assertThat(TransactionSynchronizationManager.isSynchronizationActive()).isTrue();
<del> boolean condition = !status.isNewTransaction();
<del> assertThat(condition).isTrue();
<del> EntityManagerFactoryUtils.getTransactionalEntityManager(factory).flush();
<del> return l;
<del> }
<add> Object result = tt.execute(status -> {
<add> boolean condition1 = !TransactionSynchronizationManager.hasResource(factory);
<add> assertThat(condition1).isTrue();
<add> assertThat(TransactionSynchronizationManager.isSynchronizationActive()).isTrue();
<add> boolean condition = !status.isNewTransaction();
<add> assertThat(condition).isTrue();
<add> EntityManagerFactoryUtils.getTransactionalEntityManager(factory).flush();
<add> return l;
<ide> });
<ide> assertThat(result).isSameAs(l);
<ide>
<ide> public void testTransactionRollbackWithPropagationSupports() {
<ide> boolean condition2 = !TransactionSynchronizationManager.isSynchronizationActive();
<ide> assertThat(condition2).isTrue();
<ide>
<del> tt.execute(new TransactionCallback() {
<del> @Override
<del> public Object doInTransaction(TransactionStatus status) {
<del> boolean condition1 = !TransactionSynchronizationManager.hasResource(factory);
<del> assertThat(condition1).isTrue();
<del> assertThat(TransactionSynchronizationManager.isSynchronizationActive()).isTrue();
<del> boolean condition = !status.isNewTransaction();
<del> assertThat(condition).isTrue();
<del> EntityManagerFactoryUtils.getTransactionalEntityManager(factory).flush();
<del> status.setRollbackOnly();
<del> return null;
<del> }
<add> tt.execute(status -> {
<add> boolean condition1 = !TransactionSynchronizationManager.hasResource(factory);
<add> assertThat(condition1).isTrue();
<add> assertThat(TransactionSynchronizationManager.isSynchronizationActive()).isTrue();
<add> boolean condition = !status.isNewTransaction();
<add> assertThat(condition).isTrue();
<add> EntityManagerFactoryUtils.getTransactionalEntityManager(factory).flush();
<add> status.setRollbackOnly();
<add> return null;
<ide> });
<ide>
<ide> boolean condition1 = !TransactionSynchronizationManager.hasResource(factory);
<ide> public void testTransactionCommitWithPrebound() {
<ide> TransactionSynchronizationManager.bindResource(factory, new EntityManagerHolder(manager));
<ide>
<ide> try {
<del> Object result = tt.execute(new TransactionCallback() {
<del> @Override
<del> public Object doInTransaction(TransactionStatus status) {
<del> assertThat(TransactionSynchronizationManager.hasResource(factory)).isTrue();
<del> assertThat(TransactionSynchronizationManager.isSynchronizationActive()).isTrue();
<del> EntityManagerFactoryUtils.getTransactionalEntityManager(factory);
<del> return l;
<del> }
<add> Object result = tt.execute(status -> {
<add> assertThat(TransactionSynchronizationManager.hasResource(factory)).isTrue();
<add> assertThat(TransactionSynchronizationManager.isSynchronizationActive()).isTrue();
<add> EntityManagerFactoryUtils.getTransactionalEntityManager(factory);
<add> return l;
<ide> });
<ide> assertThat(result).isSameAs(l);
<ide>
<ide> public void testTransactionRollbackWithPrebound() {
<ide> TransactionSynchronizationManager.bindResource(factory, new EntityManagerHolder(manager));
<ide>
<ide> try {
<del> tt.execute(new TransactionCallback() {
<del> @Override
<del> public Object doInTransaction(TransactionStatus status) {
<del> assertThat(TransactionSynchronizationManager.hasResource(factory)).isTrue();
<del> assertThat(TransactionSynchronizationManager.isSynchronizationActive()).isTrue();
<del> EntityManagerFactoryUtils.getTransactionalEntityManager(factory);
<del> status.setRollbackOnly();
<del> return null;
<del> }
<add> tt.execute(status -> {
<add> assertThat(TransactionSynchronizationManager.hasResource(factory)).isTrue();
<add> assertThat(TransactionSynchronizationManager.isSynchronizationActive()).isTrue();
<add> EntityManagerFactoryUtils.getTransactionalEntityManager(factory);
<add> status.setRollbackOnly();
<add> return null;
<ide> });
<ide>
<ide> assertThat(TransactionSynchronizationManager.hasResource(factory)).isTrue();
<ide> public void testTransactionCommitWithPreboundAndPropagationSupports() {
<ide> TransactionSynchronizationManager.bindResource(factory, new EntityManagerHolder(manager));
<ide>
<ide> try {
<del> Object result = tt.execute(new TransactionCallback() {
<del> @Override
<del> public Object doInTransaction(TransactionStatus status) {
<del> assertThat(TransactionSynchronizationManager.hasResource(factory)).isTrue();
<del> assertThat(TransactionSynchronizationManager.isSynchronizationActive()).isTrue();
<del> boolean condition = !status.isNewTransaction();
<del> assertThat(condition).isTrue();
<del> EntityManagerFactoryUtils.getTransactionalEntityManager(factory).flush();
<del> return l;
<del> }
<add> Object result = tt.execute(status -> {
<add> assertThat(TransactionSynchronizationManager.hasResource(factory)).isTrue();
<add> assertThat(TransactionSynchronizationManager.isSynchronizationActive()).isTrue();
<add> boolean condition = !status.isNewTransaction();
<add> assertThat(condition).isTrue();
<add> EntityManagerFactoryUtils.getTransactionalEntityManager(factory).flush();
<add> return l;
<ide> });
<ide> assertThat(result).isSameAs(l);
<ide>
<ide> public void testTransactionRollbackWithPreboundAndPropagationSupports() {
<ide> TransactionSynchronizationManager.bindResource(factory, new EntityManagerHolder(manager));
<ide>
<ide> try {
<del> tt.execute(new TransactionCallback() {
<del> @Override
<del> public Object doInTransaction(TransactionStatus status) {
<del> assertThat(TransactionSynchronizationManager.hasResource(factory)).isTrue();
<del> assertThat(TransactionSynchronizationManager.isSynchronizationActive()).isTrue();
<del> boolean condition = !status.isNewTransaction();
<del> assertThat(condition).isTrue();
<del> EntityManagerFactoryUtils.getTransactionalEntityManager(factory).flush();
<del> status.setRollbackOnly();
<del> return null;
<del> }
<add> tt.execute(status -> {
<add> assertThat(TransactionSynchronizationManager.hasResource(factory)).isTrue();
<add> assertThat(TransactionSynchronizationManager.isSynchronizationActive()).isTrue();
<add> boolean condition = !status.isNewTransaction();
<add> assertThat(condition).isTrue();
<add> EntityManagerFactoryUtils.getTransactionalEntityManager(factory).flush();
<add> status.setRollbackOnly();
<add> return null;
<ide> });
<ide>
<ide> assertThat(TransactionSynchronizationManager.hasResource(factory)).isTrue();
<ide><path>spring-web/src/test/java/org/springframework/http/client/InterceptingClientHttpRequestFactoryTests.java
<ide> /*
<del> * Copyright 2002-2019 the original author or authors.
<add> * Copyright 2002-2022 the original author or authors.
<ide> *
<ide> * Licensed under the Apache License, Version 2.0 (the "License");
<ide> * you may not use this file except in compliance with the License.
<ide> public void basic() throws Exception {
<ide> @Test
<ide> public void noExecution() throws Exception {
<ide> List<ClientHttpRequestInterceptor> interceptors = new ArrayList<>();
<del> interceptors.add(new ClientHttpRequestInterceptor() {
<del> @Override
<del> public ClientHttpResponse intercept(HttpRequest request, byte[] body, ClientHttpRequestExecution execution)
<del> throws IOException {
<del> return responseMock;
<del> }
<del> });
<add> interceptors.add((request, body, execution) -> responseMock);
<ide>
<ide> interceptors.add(new NoOpInterceptor());
<ide> requestFactory = new InterceptingClientHttpRequestFactory(requestFactoryMock, interceptors);
<ide> public void changeHeaders() throws Exception {
<ide> final String headerValue = "Bar";
<ide> final String otherValue = "Baz";
<ide>
<del> ClientHttpRequestInterceptor interceptor = new ClientHttpRequestInterceptor() {
<del> @Override
<del> public ClientHttpResponse intercept(HttpRequest request, byte[] body, ClientHttpRequestExecution execution)
<del> throws IOException {
<add> ClientHttpRequestInterceptor interceptor = (request, body, execution) -> {
<ide> HttpRequestWrapper wrapper = new HttpRequestWrapper(request);
<ide> wrapper.getHeaders().add(headerName, otherValue);
<ide> return execution.execute(wrapper, body);
<del> }
<del> };
<add> };
<ide>
<ide> requestMock = new RequestMock() {
<ide> @Override
<ide> public ClientHttpResponse execute() throws IOException {
<ide> };
<ide> requestMock.getHeaders().add(headerName, headerValue);
<ide>
<del> requestFactory =
<del> new InterceptingClientHttpRequestFactory(requestFactoryMock, Collections.singletonList(interceptor));
<add> requestFactory = new InterceptingClientHttpRequestFactory(requestFactoryMock, Collections.singletonList(interceptor));
<ide>
<ide> ClientHttpRequest request = requestFactory.createRequest(new URI("https://example.com"), HttpMethod.GET);
<ide> request.execute();
<ide> public ClientHttpResponse execute() throws IOException {
<ide> public void changeURI() throws Exception {
<ide> final URI changedUri = new URI("https://example.com/2");
<ide>
<del> ClientHttpRequestInterceptor interceptor = new ClientHttpRequestInterceptor() {
<add> ClientHttpRequestInterceptor interceptor = (request, body, execution) -> execution.execute(new HttpRequestWrapper(request) {
<ide> @Override
<del> public ClientHttpResponse intercept(HttpRequest request, byte[] body, ClientHttpRequestExecution execution)
<del> throws IOException {
<del> return execution.execute(new HttpRequestWrapper(request) {
<del> @Override
<del> public URI getURI() {
<del> return changedUri;
<del> }
<del>
<del> }, body);
<add> public URI getURI() {
<add> return changedUri;
<ide> }
<del> };
<add>
<add> }, body);
<ide>
<ide> requestFactoryMock = new RequestFactoryMock() {
<ide> @Override
<ide> public ClientHttpRequest createRequest(URI uri, HttpMethod httpMethod) throws IO
<ide> }
<ide> };
<ide>
<del> requestFactory =
<del> new InterceptingClientHttpRequestFactory(requestFactoryMock, Collections.singletonList(interceptor));
<add> requestFactory = new InterceptingClientHttpRequestFactory(requestFactoryMock, Collections.singletonList(interceptor));
<ide>
<ide> ClientHttpRequest request = requestFactory.createRequest(new URI("https://example.com"), HttpMethod.GET);
<ide> request.execute();
<ide> public ClientHttpRequest createRequest(URI uri, HttpMethod httpMethod) throws IO
<ide> public void changeMethod() throws Exception {
<ide> final HttpMethod changedMethod = HttpMethod.POST;
<ide>
<del> ClientHttpRequestInterceptor interceptor = new ClientHttpRequestInterceptor() {
<add> ClientHttpRequestInterceptor interceptor = (request, body, execution) -> execution.execute(new HttpRequestWrapper(request) {
<ide> @Override
<del> public ClientHttpResponse intercept(HttpRequest request, byte[] body, ClientHttpRequestExecution execution)
<del> throws IOException {
<del> return execution.execute(new HttpRequestWrapper(request) {
<del> @Override
<del> public HttpMethod getMethod() {
<del> return changedMethod;
<del> }
<del>
<del> }, body);
<add> public HttpMethod getMethod() {
<add> return changedMethod;
<ide> }
<del> };
<add>
<add> }, body);
<ide>
<ide> requestFactoryMock = new RequestFactoryMock() {
<ide> @Override
<ide> public ClientHttpRequest createRequest(URI uri, HttpMethod httpMethod) throws IO
<ide> }
<ide> };
<ide>
<del> requestFactory =
<del> new InterceptingClientHttpRequestFactory(requestFactoryMock, Collections.singletonList(interceptor));
<add> requestFactory = new InterceptingClientHttpRequestFactory(requestFactoryMock, Collections.singletonList(interceptor));
<ide>
<ide> ClientHttpRequest request = requestFactory.createRequest(new URI("https://example.com"), HttpMethod.GET);
<ide> request.execute();
<ide> public ClientHttpRequest createRequest(URI uri, HttpMethod httpMethod) throws IO
<ide> public void changeBody() throws Exception {
<ide> final byte[] changedBody = "Foo".getBytes();
<ide>
<del> ClientHttpRequestInterceptor interceptor = new ClientHttpRequestInterceptor() {
<del> @Override
<del> public ClientHttpResponse intercept(HttpRequest request, byte[] body, ClientHttpRequestExecution execution)
<del> throws IOException {
<del> return execution.execute(request, changedBody);
<del> }
<del> };
<add> ClientHttpRequestInterceptor interceptor = (request, body, execution) -> execution.execute(request, changedBody);
<ide>
<del> requestFactory =
<del> new InterceptingClientHttpRequestFactory(requestFactoryMock, Collections.singletonList(interceptor));
<add> requestFactory = new InterceptingClientHttpRequestFactory(requestFactoryMock, Collections.singletonList(interceptor));
<ide>
<ide> ClientHttpRequest request = requestFactory.createRequest(new URI("https://example.com"), HttpMethod.GET);
<ide> request.execute();
<ide><path>spring-web/src/test/java/org/springframework/http/converter/xml/MappingJackson2XmlHttpMessageConverterTests.java
<ide> public void setArray(String[] array) {
<ide> }
<ide>
<ide>
<del> private interface MyJacksonView1 {};
<add> private interface MyJacksonView1 {}
<ide>
<del> private interface MyJacksonView2 {};
<add> private interface MyJacksonView2 {}
<ide>
<ide>
<ide> @SuppressWarnings("unused")
<ide><path>spring-web/src/test/java/org/springframework/web/bind/ServletRequestDataBinderTests.java
<ide> protected void doTestTony(PropertyValues pvs) throws Exception {
<ide> m.put("forname", "Tony");
<ide> m.put("surname", "Blair");
<ide> m.put("age", "50");
<del> for (int i = 0; i < ps.length; i++) {
<del> Object val = m.get(ps[i].getName());
<add> for (PropertyValue element : ps) {
<add> Object val = m.get(element.getName());
<ide> assertThat(val != null).as("Can't have unexpected value").isTrue();
<ide> boolean condition = val instanceof String;
<ide> assertThat(condition).as("Val i string").isTrue();
<del> assertThat(val.equals(ps[i].getValue())).as("val matches expected").isTrue();
<del> m.remove(ps[i].getName());
<add> assertThat(val.equals(element.getValue())).as("val matches expected").isTrue();
<add> m.remove(element.getName());
<ide> }
<ide> assertThat(m.size() == 0).as("Map size is 0").isTrue();
<ide> }
<ide><path>spring-web/src/test/java/org/springframework/web/context/request/async/DeferredResultTests.java
<ide>
<ide> package org.springframework.web.context.request.async;
<ide>
<del>import java.util.function.Consumer;
<del>
<ide> import org.junit.jupiter.api.Test;
<ide>
<ide> import org.springframework.web.context.request.async.DeferredResult.DeferredResultHandler;
<ide> public void onError() throws Exception {
<ide> DeferredResult<String> result = new DeferredResult<>(null, "error result");
<ide> result.setResultHandler(handler);
<ide> Exception e = new Exception();
<del> result.onError(new Consumer<Throwable>() {
<del> @Override
<del> public void accept(Throwable t) {
<del> sb.append("error event");
<del> }
<del> });
<add> result.onError(t -> sb.append("error event"));
<ide>
<ide> result.getInterceptor().handleError(null, null, e);
<ide>
<ide><path>spring-web/src/test/java/org/springframework/web/context/request/async/WebAsyncManagerErrorTests.java
<ide> package org.springframework.web.context.request.async;
<ide>
<ide> import java.util.concurrent.Callable;
<del>import java.util.function.Consumer;
<ide>
<ide> import javax.servlet.AsyncEvent;
<ide>
<ide> public void startCallableProcessingErrorAndResumeThroughCallback() throws Except
<ide>
<ide> StubCallable callable = new StubCallable();
<ide> WebAsyncTask<Object> webAsyncTask = new WebAsyncTask<>(callable);
<del> webAsyncTask.onError(new Callable<Object>() {
<del> @Override
<del> public Object call() throws Exception {
<del> return 7;
<del> }
<del> });
<add> webAsyncTask.onError(() -> 7);
<ide>
<ide> this.asyncManager.startCallableProcessing(webAsyncTask);
<ide>
<ide> public void startDeferredResultProcessingErrorAndResumeWithDefaultResult() throw
<ide> public void startDeferredResultProcessingErrorAndResumeThroughCallback() throws Exception {
<ide>
<ide> final DeferredResult<Throwable> deferredResult = new DeferredResult<>();
<del> deferredResult.onError(new Consumer<Throwable>() {
<del> @Override
<del> public void accept(Throwable t) {
<del> deferredResult.setResult(t);
<del> }
<del> });
<add> deferredResult.onError(t -> deferredResult.setResult(t));
<ide>
<ide> this.asyncManager.startDeferredResultProcessing(deferredResult);
<ide>
<ide><path>spring-web/src/test/java/org/springframework/web/context/request/async/WebAsyncManagerTimeoutTests.java
<ide> public void startCallableProcessingTimeoutAndResumeThroughCallback() throws Exce
<ide>
<ide> StubCallable callable = new StubCallable();
<ide> WebAsyncTask<Object> webAsyncTask = new WebAsyncTask<>(callable);
<del> webAsyncTask.onTimeout(new Callable<Object>() {
<del> @Override
<del> public Object call() throws Exception {
<del> return 7;
<del> }
<del> });
<add> webAsyncTask.onTimeout(() -> 7);
<ide>
<ide> this.asyncManager.startCallableProcessing(webAsyncTask);
<ide>
<ide><path>spring-web/src/test/java/org/springframework/web/filter/HiddenHttpMethodFilterTests.java
<ide> /*
<del> * Copyright 2002-2019 the original author or authors.
<add> * Copyright 2002-2022 the original author or authors.
<ide> *
<ide> * Licensed under the Apache License, Version 2.0 (the "License");
<ide> * you may not use this file except in compliance with the License.
<ide>
<ide> import javax.servlet.FilterChain;
<ide> import javax.servlet.ServletException;
<del>import javax.servlet.ServletRequest;
<del>import javax.servlet.ServletResponse;
<ide> import javax.servlet.http.HttpServletRequest;
<ide>
<ide> import org.junit.jupiter.api.Test;
<ide> private void filterWithParameterForMethod(String methodParam, String expectedMet
<ide> }
<ide> MockHttpServletResponse response = new MockHttpServletResponse();
<ide>
<del> FilterChain filterChain = new FilterChain() {
<del>
<del> @Override
<del> public void doFilter(ServletRequest filterRequest,
<del> ServletResponse filterResponse) throws IOException, ServletException {
<del> assertThat(((HttpServletRequest) filterRequest).getMethod()).as("Invalid method").isEqualTo(expectedMethod);
<del> }
<del> };
<add> FilterChain filterChain = (filterRequest, filterResponse) ->
<add> assertThat(((HttpServletRequest) filterRequest).getMethod())
<add> .as("Invalid method").isEqualTo(expectedMethod);
<ide> this.filter.doFilter(request, response, filterChain);
<ide> }
<ide>
<ide><path>spring-web/src/test/java/org/springframework/web/method/annotation/ModelFactoryOrderingTests.java
<ide> /*
<del> * Copyright 2002-2019 the original author or authors.
<add> * Copyright 2002-2022 the original author or authors.
<ide> *
<ide> * Licensed under the Apache License, Version 2.0 (the "License");
<ide> * you may not use this file except in compliance with the License.
<ide> *
<ide> * @author Rossen Stoyanchev
<ide> */
<del>public class ModelFactoryOrderingTests {
<add>class ModelFactoryOrderingTests {
<ide>
<ide> private static final Log logger = LogFactory.getLog(ModelFactoryOrderingTests.class);
<ide>
<del> private NativeWebRequest webRequest;
<add> private final NativeWebRequest webRequest = new ServletWebRequest(new MockHttpServletRequest(), new MockHttpServletResponse());
<ide>
<del> private ModelAndViewContainer mavContainer;
<add> private final ModelAndViewContainer mavContainer = new ModelAndViewContainer();
<ide>
<del> private SessionAttributeStore sessionAttributeStore;
<add> private final SessionAttributeStore sessionAttributeStore = new DefaultSessionAttributeStore();
<ide>
<ide>
<ide> @BeforeEach
<del> public void setup() {
<del> this.sessionAttributeStore = new DefaultSessionAttributeStore();
<del> this.webRequest = new ServletWebRequest(new MockHttpServletRequest(), new MockHttpServletResponse());
<del> this.mavContainer = new ModelAndViewContainer();
<add> void setup() {
<ide> this.mavContainer.addAttribute("methods", new ArrayList<String>());
<ide> }
<ide>
<ide> @Test
<del> public void straightLineDependency() throws Exception {
<add> void straightLineDependency() throws Exception {
<ide> runTest(new StraightLineDependencyController());
<ide> assertInvokedBefore("getA", "getB1", "getB2", "getC1", "getC2", "getC3", "getC4");
<ide> assertInvokedBefore("getB1", "getB2", "getC1", "getC2", "getC3", "getC4");
<ide> public void straightLineDependency() throws Exception {
<ide> }
<ide>
<ide> @Test
<del> public void treeDependency() throws Exception {
<add> void treeDependency() throws Exception {
<ide> runTest(new TreeDependencyController());
<ide> assertInvokedBefore("getA", "getB1", "getB2", "getC1", "getC2", "getC3", "getC4");
<ide> assertInvokedBefore("getB1", "getC1", "getC2");
<ide> assertInvokedBefore("getB2", "getC3", "getC4");
<ide> }
<ide>
<ide> @Test
<del> public void InvertedTreeDependency() throws Exception {
<add> void InvertedTreeDependency() throws Exception {
<ide> runTest(new InvertedTreeDependencyController());
<ide> assertInvokedBefore("getC1", "getA", "getB1");
<ide> assertInvokedBefore("getC2", "getA", "getB1");
<ide> public void InvertedTreeDependency() throws Exception {
<ide> }
<ide>
<ide> @Test
<del> public void unresolvedDependency() throws Exception {
<add> void unresolvedDependency() throws Exception {
<ide> runTest(new UnresolvedDependencyController());
<ide> assertInvokedBefore("getA", "getC1", "getC2", "getC3", "getC4");
<ide>
<ide> private void runTest(Object controller) throws Exception {
<ide> ModelFactory factory = new ModelFactory(modelMethods, dataBinderFactory, sessionHandler);
<ide> factory.initModel(this.webRequest, this.mavContainer, new HandlerMethod(controller, "handle"));
<ide> if (logger.isDebugEnabled()) {
<del> StringBuilder sb = new StringBuilder();
<del> for (String name : getInvokedMethods()) {
<del> sb.append(" >> ").append(name);
<del> }
<del> logger.debug(sb);
<add> logger.debug(String.join(" >> ", getInvokedMethods()));
<ide> }
<ide> }
<ide>
<ide> private void assertInvokedBefore(String beforeMethod, String... afterMethods) {
<ide> List<String> actual = getInvokedMethods();
<ide> for (String afterMethod : afterMethods) {
<del> assertThat(actual.indexOf(beforeMethod) < actual.indexOf(afterMethod)).as(beforeMethod + " should be before " + afterMethod + ". Actual order: " +
<del> actual.toString()).isTrue();
<add> assertThat(actual.indexOf(beforeMethod) < actual.indexOf(afterMethod))
<add> .as(beforeMethod + " should be before " + afterMethod + ". Actual order: " + actual.toString())
<add> .isTrue();
<ide> }
<ide> }
<ide>
<ide> private static class C3 { }
<ide> private static class C4 { }
<ide>
<ide>
<del> private static final ReflectionUtils.MethodFilter METHOD_FILTER = new ReflectionUtils.MethodFilter() {
<del>
<del> @Override
<del> public boolean matches(Method method) {
<del> return ((AnnotationUtils.findAnnotation(method, RequestMapping.class) == null) &&
<del> (AnnotationUtils.findAnnotation(method, ModelAttribute.class) != null));
<del> }
<del> };
<add> private static final ReflectionUtils.MethodFilter METHOD_FILTER = method ->
<add> ((AnnotationUtils.findAnnotation(method, RequestMapping.class) == null) &&
<add> (AnnotationUtils.findAnnotation(method, ModelAttribute.class) != null));
<ide>
<ide> }
<ide><path>spring-webflux/src/test/java/org/springframework/web/reactive/function/BodyExtractorsTests.java
<ide> public Map<String, Object> hints() {
<ide> return hints;
<ide> }
<ide> };
<del> this.hints = new HashMap<String, Object>();
<add> this.hints = new HashMap<>();
<ide> }
<ide>
<ide>
<ide><path>spring-webflux/src/test/java/org/springframework/web/reactive/function/server/RouterFunctionsTests.java
<ide> import org.springframework.web.server.ResponseStatusException;
<ide> import org.springframework.web.server.ServerWebExchange;
<ide> import org.springframework.web.server.WebFilter;
<del>import org.springframework.web.server.WebFilterChain;
<ide> import org.springframework.web.testfixture.http.server.reactive.MockServerHttpRequest;
<ide> import org.springframework.web.testfixture.http.server.reactive.MockServerHttpResponse;
<ide> import org.springframework.web.testfixture.server.MockServerWebExchange;
<ide> public Mono<Void> writeTo(ServerWebExchange exchange, Context context) {
<ide> public void toHttpHandlerWebFilter() {
<ide> AtomicBoolean filterInvoked = new AtomicBoolean();
<ide>
<del> WebFilter webFilter = new WebFilter() {
<del> @Override
<del> public Mono<Void> filter(ServerWebExchange exchange, WebFilterChain chain) {
<del> filterInvoked.set(true);
<del> return chain.filter(exchange);
<del> }
<add> WebFilter webFilter = (exchange, chain) -> {
<add> filterInvoked.set(true);
<add> return chain.filter(exchange);
<ide> };
<ide>
<ide> HandlerFunction<ServerResponse> handlerFunction = request -> ServerResponse.accepted().build();
<ide><path>spring-webflux/src/test/java/org/springframework/web/reactive/resource/ResourceUrlProviderTests.java
<ide> void initializeOnCurrentContext() {
<ide>
<ide>
<ide> private Condition<PathPattern> pathPatternStringOf(String expected) {
<del> return new Condition<PathPattern>(
<add> return new Condition<>(
<ide> actual -> actual != null && actual.getPatternString().equals(expected),
<ide> "Pattern %s", expected);
<ide> }
<ide><path>spring-webmvc/src/test/java/org/springframework/context/LifecycleContextBean.java
<ide> public class LifecycleContextBean extends LifecycleBean implements ApplicationCo
<ide> @Override
<ide> public void setBeanFactory(BeanFactory beanFactory) {
<ide> super.setBeanFactory(beanFactory);
<del> if (this.owningContext != null)
<add> if (this.owningContext != null) {
<ide> throw new RuntimeException("Factory called setBeanFactory after setApplicationContext");
<add> }
<ide> }
<ide>
<ide> @Override
<ide> public void afterPropertiesSet() {
<ide> super.afterPropertiesSet();
<del> if (this.owningContext == null)
<add> if (this.owningContext == null) {
<ide> throw new RuntimeException("Factory didn't call setApplicationContext before afterPropertiesSet on lifecycle bean");
<add> }
<ide> }
<ide>
<ide> @Override
<ide> public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
<del> if (this.owningFactory == null)
<add> if (this.owningFactory == null) {
<ide> throw new RuntimeException("Factory called setApplicationContext before setBeanFactory");
<add> }
<ide>
<ide> this.owningContext = applicationContext;
<ide> }
<ide><path>spring-webmvc/src/test/java/org/springframework/web/context/XmlWebApplicationContextTests.java
<ide> /*
<del> * Copyright 2002-2020 the original author or authors.
<add> * Copyright 2002-2022 the original author or authors.
<ide> *
<ide> * Licensed under the Apache License, Version 2.0 (the "License");
<ide> * you may not use this file except in compliance with the License.
<ide> import org.springframework.beans.BeansException;
<ide> import org.springframework.beans.factory.DisposableBean;
<ide> import org.springframework.beans.factory.InitializingBean;
<del>import org.springframework.beans.factory.config.BeanFactoryPostProcessor;
<ide> import org.springframework.beans.factory.config.BeanPostProcessor;
<del>import org.springframework.beans.factory.config.ConfigurableListableBeanFactory;
<ide> import org.springframework.beans.testfixture.beans.TestBean;
<ide> import org.springframework.context.ConfigurableApplicationContext;
<ide> import org.springframework.context.NoSuchMessageException;
<ide> protected ConfigurableApplicationContext createContext() throws Exception {
<ide> MockServletContext sc = new MockServletContext("");
<ide> root.setServletContext(sc);
<ide> root.setConfigLocations("/org/springframework/web/context/WEB-INF/applicationContext.xml");
<del> root.addBeanFactoryPostProcessor(new BeanFactoryPostProcessor() {
<add> root.addBeanFactoryPostProcessor(beanFactory -> beanFactory.addBeanPostProcessor(new BeanPostProcessor() {
<ide> @Override
<del> public void postProcessBeanFactory(ConfigurableListableBeanFactory beanFactory) {
<del> beanFactory.addBeanPostProcessor(new BeanPostProcessor() {
<del> @Override
<del> public Object postProcessBeforeInitialization(Object bean, String name) throws BeansException {
<del> if (bean instanceof TestBean) {
<del> ((TestBean) bean).getFriends().add("myFriend");
<del> }
<del> return bean;
<del> }
<del> @Override
<del> public Object postProcessAfterInitialization(Object bean, String name) throws BeansException {
<del> return bean;
<del> }
<del> });
<add> public Object postProcessBeforeInitialization(Object bean, String name) throws BeansException {
<add> if (bean instanceof TestBean) {
<add> ((TestBean) bean).getFriends().add("myFriend");
<add> }
<add> return bean;
<ide> }
<del> });
<add> }));
<ide> root.refresh();
<ide> XmlWebApplicationContext wac = new XmlWebApplicationContext();
<ide> wac.getEnvironment().addActiveProfile("wacProfile1");
<ide> protected void doTestEvents(TestApplicationListener listener, TestApplicationLis
<ide> @Test
<ide> @Override
<ide> public void count() {
<del> assertThat(this.applicationContext.getBeanDefinitionCount() == 14).as("should have 14 beans, not "+ this.applicationContext.getBeanDefinitionCount()).isTrue();
<add> assertThat(this.applicationContext.getBeanDefinitionCount()).as("should have 14 beans").isEqualTo(14);
<ide> }
<ide>
<ide> @Test
<ide><path>spring-webmvc/src/test/java/org/springframework/web/context/support/HttpRequestHandlerTests.java
<ide> /*
<del> * Copyright 2002-2019 the original author or authors.
<add> * Copyright 2002-2022 the original author or authors.
<ide> *
<ide> * Licensed under the Apache License, Version 2.0 (the "License");
<ide> * you may not use this file except in compliance with the License.
<ide>
<ide> import javax.servlet.Servlet;
<ide> import javax.servlet.ServletException;
<del>import javax.servlet.http.HttpServletRequest;
<del>import javax.servlet.http.HttpServletResponse;
<ide>
<ide> import org.junit.jupiter.api.Test;
<ide>
<ide> public class HttpRequestHandlerTests {
<ide> @Test
<ide> public void testHttpRequestHandlerServletPassThrough() throws Exception {
<ide> MockServletContext servletContext = new MockServletContext();
<del> final MockHttpServletRequest request = new MockHttpServletRequest();
<del> final MockHttpServletResponse response = new MockHttpServletResponse();
<add> MockHttpServletRequest request = new MockHttpServletRequest();
<add> MockHttpServletResponse response = new MockHttpServletResponse();
<ide>
<ide> StaticWebApplicationContext wac = new StaticWebApplicationContext();
<del> wac.getBeanFactory().registerSingleton("myHandler", new HttpRequestHandler() {
<del> @Override
<del> public void handleRequest(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException {
<del> assertThat(req).isSameAs(request);
<del> assertThat(res).isSameAs(response);
<del> String exception = request.getParameter("exception");
<del> if ("ServletException".equals(exception)) {
<del> throw new ServletException("test");
<del> }
<del> if ("IOException".equals(exception)) {
<del> throw new IOException("test");
<del> }
<del> res.getWriter().write("myResponse");
<add> wac.getBeanFactory().registerSingleton("myHandler", (HttpRequestHandler) (req, res) -> {
<add> assertThat(req).isSameAs(request);
<add> assertThat(res).isSameAs(response);
<add> String exception = request.getParameter("exception");
<add> if ("ServletException".equals(exception)) {
<add> throw new ServletException("test");
<ide> }
<add> if ("IOException".equals(exception)) {
<add> throw new IOException("test");
<add> }
<add> res.getWriter().write("myResponse");
<ide> });
<ide> wac.setServletContext(servletContext);
<ide> wac.refresh();
<ide> public void handleRequest(HttpServletRequest req, HttpServletResponse res) throw
<ide> assertThat(response.getContentAsString()).isEqualTo("myResponse");
<ide>
<ide> request.setParameter("exception", "ServletException");
<del> assertThatExceptionOfType(ServletException.class).isThrownBy(() ->
<del> servlet.service(request, response))
<add> assertThatExceptionOfType(ServletException.class)
<add> .isThrownBy(() -> servlet.service(request, response))
<ide> .withMessage("test");
<ide>
<ide> request.setParameter("exception", "IOException");
<del> assertThatIOException().isThrownBy(() ->
<del> servlet.service(request, response))
<add> assertThatIOException()
<add> .isThrownBy(() -> servlet.service(request, response))
<ide> .withMessage("test");
<ide> }
<ide>
<ide><path>spring-webmvc/src/test/java/org/springframework/web/servlet/config/annotation/WebMvcConfigurationSupportExtensionTests.java
<ide> import org.springframework.beans.DirectFieldAccessor;
<ide> import org.springframework.beans.testfixture.beans.TestBean;
<ide> import org.springframework.core.Ordered;
<del>import org.springframework.core.convert.converter.Converter;
<ide> import org.springframework.core.io.FileSystemResourceLoader;
<ide> import org.springframework.format.FormatterRegistry;
<ide> import org.springframework.http.HttpStatus;
<ide> private class TestWebMvcConfigurationSupport extends WebMvcConfigurationSupport
<ide>
<ide> @Override
<ide> public void addFormatters(FormatterRegistry registry) {
<del> registry.addConverter(new Converter<TestBean, String>() {
<del> @Override
<del> public String convert(TestBean source) {
<del> return "converted";
<del> }
<del> });
<add> registry.addConverter(TestBean.class, String.class, testBean -> "converted");
<ide> }
<ide>
<ide> @Override
<ide><path>spring-webmvc/src/test/java/org/springframework/web/servlet/function/DefaultEntityResponseBuilderTests.java
<ide> import org.springframework.http.HttpMethod;
<ide> import org.springframework.http.HttpStatus;
<ide> import org.springframework.http.MediaType;
<del>import org.springframework.http.converter.HttpMessageConverter;
<ide> import org.springframework.util.LinkedMultiValueMap;
<ide> import org.springframework.util.MultiValueMap;
<ide> import org.springframework.web.servlet.ModelAndView;
<ide> */
<ide> public class DefaultEntityResponseBuilderTests {
<ide>
<del> static final ServerResponse.Context EMPTY_CONTEXT = new ServerResponse.Context() {
<del> @Override
<del> public List<HttpMessageConverter<?>> messageConverters() {
<del> return Collections.emptyList();
<del> }
<del>
<del> };
<add> static final ServerResponse.Context EMPTY_CONTEXT = () -> Collections.emptyList();
<ide>
<ide> @Test
<ide> public void fromObject() {
<ide><path>spring-webmvc/src/test/java/org/springframework/web/servlet/function/DefaultRenderingResponseTests.java
<ide> import java.time.format.DateTimeFormatter;
<ide> import java.time.temporal.ChronoUnit;
<ide> import java.util.Collections;
<del>import java.util.List;
<ide> import java.util.Map;
<ide>
<ide> import javax.servlet.http.Cookie;
<ide>
<ide> import org.springframework.http.HttpHeaders;
<ide> import org.springframework.http.HttpStatus;
<del>import org.springframework.http.converter.HttpMessageConverter;
<ide> import org.springframework.util.LinkedMultiValueMap;
<ide> import org.springframework.util.MultiValueMap;
<ide> import org.springframework.web.servlet.ModelAndView;
<ide> */
<ide> public class DefaultRenderingResponseTests {
<ide>
<del> static final ServerResponse.Context EMPTY_CONTEXT = new ServerResponse.Context() {
<del> @Override
<del> public List<HttpMessageConverter<?>> messageConverters() {
<del> return Collections.emptyList();
<del> }
<del>
<del> };
<add> static final ServerResponse.Context EMPTY_CONTEXT = () -> Collections.emptyList();
<ide>
<ide> @Test
<ide> public void create() throws Exception {
<ide><path>spring-webmvc/src/test/java/org/springframework/web/servlet/function/DefaultServerRequestTests.java
<ide> void session() {
<ide> @Test
<ide> void principal() {
<ide> MockHttpServletRequest servletRequest = PathPatternsTestUtils.initRequest("GET", "/", true);
<del> Principal principal = new Principal() {
<del> @Override
<del> public String getName() {
<del> return "foo";
<del> }
<del> };
<add> Principal principal = () -> "foo";
<ide> servletRequest.setUserPrincipal(principal);
<ide>
<ide> DefaultServerRequest request = new DefaultServerRequest(servletRequest,
<ide><path>spring-webmvc/src/test/java/org/springframework/web/servlet/function/DefaultServerResponseBuilderTests.java
<ide> import org.springframework.http.HttpMethod;
<ide> import org.springframework.http.HttpStatus;
<ide> import org.springframework.http.MediaType;
<del>import org.springframework.http.converter.HttpMessageConverter;
<ide> import org.springframework.http.converter.StringHttpMessageConverter;
<ide> import org.springframework.http.converter.json.MappingJackson2HttpMessageConverter;
<ide> import org.springframework.util.LinkedMultiValueMap;
<ide> */
<ide> public class DefaultServerResponseBuilderTests {
<ide>
<del> static final ServerResponse.Context EMPTY_CONTEXT = new ServerResponse.Context() {
<del> @Override
<del> public List<HttpMessageConverter<?>> messageConverters() {
<del> return Collections.emptyList();
<del>
<del> }
<del>
<del> };
<add> static final ServerResponse.Context EMPTY_CONTEXT = () -> Collections.emptyList();
<ide>
<ide> @Test
<ide> public void status() {
<ide><path>spring-webmvc/src/test/java/org/springframework/web/servlet/tags/form/SelectTagTests.java
<ide> import java.text.ParseException;
<ide> import java.util.ArrayList;
<ide> import java.util.Collections;
<del>import java.util.Comparator;
<ide> import java.util.HashMap;
<ide> import java.util.List;
<ide> import java.util.Locale;
<ide> private void assertStringArray() throws JspException, DocumentException {
<ide> }
<ide>
<ide> private Map getCountryToLocaleMap() {
<del> Map map = new TreeMap(new Comparator() {
<del> @Override
<del> public int compare(Object o1, Object o2) {
<del> return ((Country)o1).getName().compareTo(((Country)o2).getName());
<del> }
<del> });
<add> Map map = new TreeMap((o1, o2) -> ((Country)o1).getName().compareTo(((Country)o2).getName()));
<ide> map.put(Country.COUNTRY_AT, LOCALE_AT);
<ide> map.put(Country.COUNTRY_NL, LOCALE_NL);
<ide> map.put(Country.COUNTRY_US, Locale.US);
<ide><path>spring-websocket/src/test/java/org/springframework/web/socket/messaging/DefaultSimpUserRegistryTests.java
<ide> import org.springframework.messaging.simp.SimpMessageHeaderAccessor;
<ide> import org.springframework.messaging.simp.SimpMessageType;
<ide> import org.springframework.messaging.simp.user.SimpSubscription;
<del>import org.springframework.messaging.simp.user.SimpSubscriptionMatcher;
<ide> import org.springframework.messaging.simp.user.SimpUser;
<ide> import org.springframework.messaging.support.MessageBuilder;
<ide> import org.springframework.web.socket.CloseStatus;
<ide> public void findSubscriptions() throws Exception {
<ide> subscribeEvent = new SessionSubscribeEvent(this, message, user);
<ide> registry.onApplicationEvent(subscribeEvent);
<ide>
<del> Set<SimpSubscription> matches = registry.findSubscriptions(new SimpSubscriptionMatcher() {
<del> @Override
<del> public boolean match(SimpSubscription subscription) {
<del> return subscription.getDestination().equals("/match");
<del> }
<del> });
<add> Set<SimpSubscription> matches = registry.findSubscriptions(subscription -> subscription.getDestination().equals("/match"));
<ide>
<ide> assertThat(matches.size()).isEqualTo(2);
<ide>
| 91
|
Go
|
Go
|
add missing error check
|
f84dc1e90858924f9fafe89e81005842a6b4f166
|
<ide><path>utils.go
<ide> func MergeConfig(userConf, imageConf *Config) error {
<ide> } else {
<ide> for _, imagePortSpec := range imageConf.PortSpecs {
<ide> found := false
<del> imageNat, _ := parseNat(imagePortSpec)
<add> imageNat, err := parseNat(imagePortSpec)
<add> if err != nil {
<add> return err
<add> }
<ide> for _, userPortSpec := range userConf.PortSpecs {
<ide> userNat, err := parseNat(userPortSpec)
<ide> if err != nil {
| 1
|
Javascript
|
Javascript
|
add migration middleware to map route
|
6b9044febd976e49730d34ff94754a7f67648c8e
|
<ide><path>app.js
<ide> app.get('/nonprofits/getNonprofitList', nonprofitController.showAllNonprofits);
<ide>
<ide> app.get('/nonprofits-form', resourcesController.nonprofitsForm);
<ide>
<del>app.get('/map', challengeMapController.challengeMap);
<add>app.get('/map',
<add> userController.userMigration,
<add> challengeMapController.challengeMap
<add>);
<ide>
<ide> app.get('/live-pair-programming', function(req, res) {
<ide> res.redirect(301, '/field-guide/live-stream-pair-programming-on-twitch.tv');
| 1
|
Javascript
|
Javascript
|
add harmony compatiblity also in case of import
|
0bcad134cbca36c36451c27cf198ede881f9e805
|
<ide><path>lib/dependencies/HarmonyImportDependencyParserPlugin.js
<ide> Author Tobias Koppers @sokra
<ide> */
<ide> var AbstractPlugin = require("../AbstractPlugin");
<add>var HarmonyCompatiblilityDependency = require("./HarmonyCompatiblilityDependency");
<ide> var HarmonyImportDependency = require("./HarmonyImportDependency");
<ide> var HarmonyImportSpecifierDependency = require("./HarmonyImportSpecifierDependency");
<ide> var HarmonyAcceptImportDependency = require("./HarmonyAcceptImportDependency");
<ide> var HarmonyAcceptDependency = require("./HarmonyAcceptDependency");
<ide> var HarmonyModulesHelpers = require("./HarmonyModulesHelpers");
<ide>
<add>function makeHarmonyModule(module, loc) {
<add> if(!module.meta.harmonyModule) {
<add> var dep = new HarmonyCompatiblilityDependency(module);
<add> dep.loc = loc;
<add> module.addDependency(dep);
<add> module.meta.harmonyModule = true;
<add> module.strict = true;
<add> }
<add>}
<add>
<ide> module.exports = AbstractPlugin.create({
<ide> "import": function(statement, source) {
<add> makeHarmonyModule(this.state.module, statement.loc);
<ide> var dep = new HarmonyImportDependency(source, HarmonyModulesHelpers.getNewModuleVar(this.state, source), statement.range);
<ide> dep.loc = statement.loc;
<ide> this.state.current.addDependency(dep);
| 1
|
Javascript
|
Javascript
|
disable the test for now
|
7ab501ce9d3556641a086f208dd76e51c44742e7
|
<ide><path>spec/git-repository-async-spec.js
<ide> describe('GitRepositoryAsync', () => {
<ide> })
<ide> })
<ide>
<del> describe('.checkoutHeadForEditor(editor)', () => {
<add> // @joshaber: Disabling for now. There seems to be some race with path
<add> // subscriptions leading to intermittent test failures, e.g.: https://travis-ci.org/atom/atom/jobs/102702554
<add> xdescribe('.checkoutHeadForEditor(editor)', () => {
<ide> let filePath
<ide> let editor
<ide>
| 1
|
Ruby
|
Ruby
|
cache the loaded relations
|
3c5a7dcaf55f427f3a48e206feb06410d011ca4f
|
<ide><path>activerecord/lib/active_record/relation.rb
<ide> def initialize(klass, relation, readonly = false, preload = [], eager_load = [])
<ide> @readonly = readonly
<ide> @associations_to_preload = preload
<ide> @eager_load_associations = eager_load
<add> @loaded = false
<ide> end
<ide>
<ide> def preload(*associations)
<ide> def readonly
<ide> create_new_relation(@relation, true)
<ide> end
<ide>
<del> def to_a
<del> records = if @eager_load_associations.any?
<del> catch :invalid_query do
<del> return @klass.send(:find_with_associations, {
<del> :select => @relation.send(:select_clauses).join(', '),
<del> :joins => @relation.joins(relation),
<del> :group => @relation.send(:group_clauses).join(', '),
<del> :order => @relation.send(:order_clauses).join(', '),
<del> :conditions => @relation.send(:where_clauses).join("\n\tAND "),
<del> :limit => @relation.taken,
<del> :offset => @relation.skipped
<del> },
<del> ActiveRecord::Associations::ClassMethods::JoinDependency.new(@klass, @eager_load_associations, nil))
<del> end
<del> []
<del> else
<del> @klass.find_by_sql(@relation.to_sql)
<del> end
<del>
<del> @associations_to_preload.each {|associations| @klass.send(:preload_associations, records, associations) }
<del> records.each { |record| record.readonly! } if @readonly
<del>
<del> records
<del> end
<del>
<del> alias all to_a
<del>
<del> def first
<del> @relation = @relation.take(1)
<del> to_a.first
<del> end
<del>
<ide> def select(selects)
<ide> create_new_relation(@relation.project(selects))
<ide> end
<ide> def respond_to?(method)
<ide> @relation.respond_to?(method) || Array.method_defined?(method) || super
<ide> end
<ide>
<add> def to_a
<add> return @records if loaded?
<add>
<add> @records = if @eager_load_associations.any?
<add> catch :invalid_query do
<add> return @klass.send(:find_with_associations, {
<add> :select => @relation.send(:select_clauses).join(', '),
<add> :joins => @relation.joins(relation),
<add> :group => @relation.send(:group_clauses).join(', '),
<add> :order => @relation.send(:order_clauses).join(', '),
<add> :conditions => @relation.send(:where_clauses).join("\n\tAND "),
<add> :limit => @relation.taken,
<add> :offset => @relation.skipped
<add> },
<add> ActiveRecord::Associations::ClassMethods::JoinDependency.new(@klass, @eager_load_associations, nil))
<add> end
<add> []
<add> else
<add> @klass.find_by_sql(@relation.to_sql)
<add> end
<add>
<add> @associations_to_preload.each {|associations| @klass.send(:preload_associations, @records, associations) }
<add> @records.each { |record| record.readonly! } if @readonly
<add>
<add> @loaded = true
<add> @records
<add> end
<add>
<add> alias all to_a
<add>
<add> def first
<add> if loaded?
<add> @records.first
<add> else
<add> @first ||= limit(1).to_a[0]
<add> end
<add> end
<add>
<add> def loaded?
<add> @loaded
<add> end
<add>
<ide> private
<ide>
<ide> def method_missing(method, *args, &block)
<ide><path>activerecord/test/cases/relations_test.rb
<ide> def test_scoped_all
<ide> assert_no_queries { assert_equal 4, topics.size }
<ide> end
<ide>
<add> def test_loaded_all
<add> topics = Topic.scoped
<add>
<add> assert_queries(1) do
<add> 2.times { assert_equal 4, topics.all.size }
<add> end
<add>
<add> assert topics.loaded?
<add> end
<add>
<add> def test_scoped_first
<add> topics = Topic.scoped
<add>
<add> assert_queries(1) do
<add> 2.times { assert_equal "The First Topic", topics.first.title }
<add> end
<add>
<add> assert ! topics.loaded?
<add> end
<add>
<add> def test_loaded_first
<add> topics = Topic.scoped
<add>
<add> assert_queries(1) do
<add> topics.all # force load
<add> 2.times { assert_equal "The First Topic", topics.first.title }
<add> end
<add>
<add> assert topics.loaded?
<add> end
<add>
<ide> def test_finding_with_conditions
<ide> assert_equal ["David"], Author.where(:name => 'David').map(&:name)
<ide> assert_equal ['Mary'], Author.where(["name = ?", 'Mary']).map(&:name)
<ide> def test_find_with_included_associations
<ide> end
<ide> end
<ide>
<del> def test_default_scope_with_conditions_string
<add> def test_default_scope_with_conditions_string
<ide> assert_equal Developer.find_all_by_name('David').map(&:id).sort, DeveloperCalledDavid.scoped.to_a.map(&:id).sort
<ide> assert_equal nil, DeveloperCalledDavid.create!.name
<ide> end
| 2
|
Javascript
|
Javascript
|
change default elixir file
|
f9d4bcd13dd4c6a1fbc990af0a4a404c9cf1a6cd
|
<ide><path>gulpfile.js
<ide> var elixir = require('laravel-elixir');
<ide>
<ide> elixir(function(mix) {
<ide> mix.sass("bootstrap.scss")
<del> .routes()
<del> .events()
<ide> .phpUnit();
<ide> });
| 1
|
Text
|
Text
|
remove references to react-page
|
470a7d11ee002392a7fa58e24b27f8578cc319e4
|
<ide><path>docs/docs/08-tooling-integration.md
<ide> The open-source community has built tools that integrate JSX with several build
<ide> that support `*.tmLanguage`.
<ide> * Linting provides accurate line numbers after compiling without sourcemaps.
<ide> * Elements use standard scoping so linters can find usage of out-of-scope components.
<del>
<del>## React Page
<del>
<del>To get started on a new project, you can use [react-page](https://github.com/facebook/react-page/), a complete React project creator. It supports both server-side and client-side rendering, source transform and packaging JSX files using CommonJS modules, and instant reload.
<ide><path>docs/docs/10-examples.md
<ide> prev: class-name-manipulation.html
<ide>
<ide> * We've included [a step-by-step comment box tutorial](/react/docs/tutorial.html).
<ide> * [The React starter kit](/react/downloads.html) includes several examples which you can [view online in our GitHub repository](https://github.com/facebook/react/tree/master/examples/).
<del>* [React Page](https://github.com/facebook/react-page) is a simple React project creator to get you up-and-running quickly with React. It supports both server-side and client-side rendering, source transform and packaging JSX files using CommonJS modules, and instant reload.
<ide> * [React one-hour email](https://github.com/petehunt/react-one-hour-email/commits/master) goes step-by-step from a static HTML mock to an interactive email reader (written in just one hour!)
<ide> * [Rendr + React app template](https://github.com/petehunt/rendr-react-template/) demonstrates how to use React's server rendering capabilities.
| 2
|
Text
|
Text
|
fix username key in database readme
|
6d4e5d2d508613e8873b8a8c6e7d93b04de20e2c
|
<ide><path>src/Database/README.md
<ide> use Cake\Database\Driver\Mysql;
<ide>
<ide> $driver = new Mysql([
<ide> 'database' => 'test',
<del> 'login' => 'root',
<add> 'username' => 'root',
<ide> 'password' => 'secret'
<ide> ]);
<ide> $connection = new Connection([
| 1
|
Ruby
|
Ruby
|
add test for build.include?
|
3ff8be1216388817dda2b4bb95aeaa5c3d3d5a6b
|
<ide><path>Library/Homebrew/rubocops/lines_cop.rb
<ide> def audit_formula(_node, _class_node, _parent_class_node, body_node)
<ide> problem "Don't duplicate 'with': Use `build.with? \"#{match[1]}\"` to check for \"--with-#{match[1]}\""
<ide> end
<ide>
<del> # find_instance_method_call(body_node, :build, :include?) do |m|
<del> # arg = parameters(m).first
<del> # next unless match = regex_match_group(arg, %r{with(out)?-(.*)})
<del> # problem "Use build.with#{match[1]}? \"#{match[2]}\" instead of build.include? 'with#{match[1]}-#{match[2]}'"
<del> # end
<add> find_instance_method_call(body_node, :build, :include?) do |m|
<add> arg = parameters(m).first
<add> next unless match = regex_match_group(arg, %r{with(out)?-(.*)})
<add> problem "Use build.with#{match[1]}? \"#{match[2]}\" instead of build.include? 'with#{match[1]}-#{match[2]}'"
<add> end
<ide> #
<ide> # find_instance_method_call(body_node, :build, :include?) do |m|
<ide> # arg = parameters(m).first
<ide><path>Library/Homebrew/test/rubocops/lines_cop_spec.rb
<ide> def post_install
<ide> expect_offense(expected, actual)
<ide> end
<ide> end
<add>
<add> it "with build.include?" do
<add> source = <<-EOS.undent
<add> class Foo < Formula
<add> desc "foo"
<add> url 'http://example.com/foo-1.0.tgz'
<add> def post_install
<add> return if build.include? "without-bar"
<add> end
<add> end
<add> EOS
<add>
<add> expected_offenses = [{ message: "Use build.without? \"bar\" instead of build.include? 'without-bar'",
<add> severity: :convention,
<add> line: 5,
<add> column: 30,
<add> source: source }]
<add>
<add> inspect_source(cop, source)
<add>
<add> expected_offenses.zip(cop.offenses).each do |expected, actual|
<add> expect_offense(expected, actual)
<add> end
<add> end
<ide> end
<ide> def expect_offense(expected, actual)
<ide> expect(actual.message).to eq(expected[:message])
| 2
|
Javascript
|
Javascript
|
remove `ensuredirsync` from mu blueprints tests
|
3f3f30b33a1926d156a7b26cb8fcede356ff9ea9
|
<ide><path>node-tests/blueprints/acceptance-test-test.js
<ide> const modifyPackages = blueprintHelpers.modifyPackages;
<ide>
<ide> const chai = require('ember-cli-blueprint-test-helpers/chai');
<ide> const expect = chai.expect;
<del>const fs = require('fs-extra');
<ide>
<ide> const generateFakePackageManifest = require('../helpers/generate-fake-package-manifest');
<ide> const enableModuleUnification = require('../helpers/module-unification').enableModuleUnification;
<ide> describe('Blueprint: acceptance-test', function() {
<ide> enableModuleUnification();
<ide>
<ide> beforeEach(function() {
<del> return emberNew().then(() => fs.ensureDirSync('src'));
<add> return emberNew();
<ide> });
<ide>
<ide> describe('with ember-cli-qunit@4.1.0', function() {
<ide> describe('Blueprint: acceptance-test', function() {
<ide> enableModuleUnification();
<ide>
<ide> beforeEach(function() {
<del> return emberNew({ target: 'addon' }).then(() => fs.ensureDirSync('src'));
<add> return emberNew({ target: 'addon' });
<ide> });
<ide>
<ide> describe('with ember-cli-qunit@4.1.0', function() {
<ide><path>node-tests/blueprints/component-test-test.js
<ide> describe('Blueprint: component-test', function() {
<ide> enableModuleUnification();
<ide>
<ide> beforeEach(function() {
<del> return emberNew().then(() => fs.ensureDirSync('src'));
<add> return emberNew();
<ide> });
<ide>
<ide> describe('with ember-cli-qunit@4.1.0', function() {
<ide><path>node-tests/blueprints/component-test.js
<ide> const modifyPackages = blueprintHelpers.modifyPackages;
<ide>
<ide> const chai = require('ember-cli-blueprint-test-helpers/chai');
<ide> const expect = chai.expect;
<del>const fs = require('fs-extra');
<ide>
<ide> const generateFakePackageManifest = require('../helpers/generate-fake-package-manifest');
<ide> const enableModuleUnification = require('../helpers/module-unification').enableModuleUnification;
<ide> describe('Blueprint: component', function() {
<ide>
<ide> beforeEach(function() {
<ide> return emberNew()
<del> .then(() => fs.ensureDirSync('src'))
<ide> .then(() =>
<ide> modifyPackages([
<ide> { name: 'ember-qunit', delete: true },
<ide> describe('Blueprint: component', function() {
<ide>
<ide> beforeEach(function() {
<ide> return emberNew({ target: 'addon' })
<del> .then(() => fs.ensureDirSync('src'))
<ide> .then(() =>
<ide> modifyPackages([
<ide> { name: 'ember-qunit', delete: true },
<ide> describe('Blueprint: component', function() {
<ide>
<ide> beforeEach(function() {
<ide> return emberNew({ target: 'in-repo-addon' })
<del> .then(() => fs.ensureDirSync('src'))
<ide> .then(() =>
<ide> modifyPackages([
<ide> { name: 'ember-qunit', delete: true },
<ide><path>node-tests/blueprints/controller-test-test.js
<ide> const expect = chai.expect;
<ide> const generateFakePackageManifest = require('../helpers/generate-fake-package-manifest');
<ide> const enableModuleUnification = require('../helpers/module-unification').enableModuleUnification;
<ide> const fixture = require('../helpers/fixture');
<del>const fs = require('fs-extra');
<ide>
<ide> describe('Blueprint: controller-test', function() {
<ide> setupTestHooks(this);
<ide> describe('Blueprint: controller-test', function() {
<ide> enableModuleUnification();
<ide>
<ide> beforeEach(function() {
<del> return emberNew().then(() => fs.ensureDirSync('src'));
<add> return emberNew();
<ide> });
<ide>
<ide> describe('with ember-cli-qunit@4.1.0', function() {
<ide> describe('Blueprint: controller-test', function() {
<ide>
<ide> beforeEach(function() {
<ide> return emberNew()
<del> .then(() => fs.ensureDirSync('src'))
<ide> .then(() =>
<ide> modifyPackages([
<ide> { name: 'ember-qunit', delete: true },
<ide><path>node-tests/blueprints/controller-test.js
<ide> const modifyPackages = blueprintHelpers.modifyPackages;
<ide>
<ide> const expectError = require('../helpers/expect-error');
<ide> const chai = require('ember-cli-blueprint-test-helpers/chai');
<del>const fs = require('fs-extra');
<ide> const expect = chai.expect;
<ide>
<ide> const generateFakePackageManifest = require('../helpers/generate-fake-package-manifest');
<ide> describe('Blueprint: controller', function() {
<ide>
<ide> beforeEach(function() {
<ide> return emberNew()
<del> .then(() => fs.ensureDirSync('src'))
<ide> .then(() =>
<ide> modifyPackages([
<ide> { name: 'ember-qunit', delete: true },
<ide> describe('Blueprint: controller', function() {
<ide>
<ide> beforeEach(function() {
<ide> return emberNew({ target: 'addon' })
<del> .then(() => fs.ensureDirSync('src'))
<ide> .then(() =>
<ide> modifyPackages([
<ide> { name: 'ember-qunit', delete: true },
<ide><path>node-tests/blueprints/helper-test-test.js
<ide> const expect = chai.expect;
<ide> const generateFakePackageManifest = require('../helpers/generate-fake-package-manifest');
<ide> const enableModuleUnification = require('../helpers/module-unification').enableModuleUnification;
<ide> const fixture = require('../helpers/fixture');
<del>const fs = require('fs-extra');
<ide>
<ide> describe('Blueprint: helper-test', function() {
<ide> setupTestHooks(this);
<ide> describe('Blueprint: helper-test', function() {
<ide> enableModuleUnification();
<ide>
<ide> beforeEach(function() {
<del> return emberNew().then(() => fs.ensureDirSync('src'));
<add> return emberNew();
<ide> });
<ide>
<ide> describe('with ember-cli-qunit@4.1.0', function() {
<ide> describe('Blueprint: helper-test', function() {
<ide> enableModuleUnification();
<ide>
<ide> beforeEach(function() {
<del> return emberNew({ target: 'addon' })
<del> .then(() => {
<del> modifyPackages([
<del> { name: 'ember-qunit', delete: true },
<del> { name: 'ember-cli-qunit', dev: true },
<del> ]);
<del> generateFakePackageManifest('ember-cli-qunit', '4.1.0');
<del> })
<del> .then(() => fs.ensureDirSync('src'));
<add> return emberNew({ target: 'addon' }).then(() => {
<add> modifyPackages([
<add> { name: 'ember-qunit', delete: true },
<add> { name: 'ember-cli-qunit', dev: true },
<add> ]);
<add> generateFakePackageManifest('ember-cli-qunit', '4.1.0');
<add> });
<ide> });
<ide>
<ide> it('helper-test foo/bar-baz', function() {
<ide><path>node-tests/blueprints/helper-test.js
<ide> const expect = chai.expect;
<ide> const generateFakePackageManifest = require('../helpers/generate-fake-package-manifest');
<ide> const fixture = require('../helpers/fixture');
<ide> const enableModuleUnification = require('../helpers/module-unification').enableModuleUnification;
<del>const fs = require('fs-extra');
<ide>
<ide> describe('Blueprint: helper', function() {
<ide> setupTestHooks(this);
<ide> describe('Blueprint: helper', function() {
<ide> enableModuleUnification();
<ide>
<ide> beforeEach(function() {
<del> return emberNew()
<del> .then(() => fs.ensureDirSync('src'))
<del> .then(() => {
<del> modifyPackages([
<del> { name: 'ember-qunit', delete: true },
<del> { name: 'ember-cli-qunit', dev: true },
<del> ]);
<del> generateFakePackageManifest('ember-cli-qunit', '4.1.0');
<del> });
<add> return emberNew().then(() => {
<add> modifyPackages([
<add> { name: 'ember-qunit', delete: true },
<add> { name: 'ember-cli-qunit', dev: true },
<add> ]);
<add> generateFakePackageManifest('ember-cli-qunit', '4.1.0');
<add> });
<ide> });
<ide>
<ide> it('helper foo/bar-baz', function() {
<ide> describe('Blueprint: helper', function() {
<ide> enableModuleUnification();
<ide>
<ide> beforeEach(function() {
<del> return emberNew({ target: 'addon' })
<del> .then(() => fs.ensureDirSync('src'))
<del> .then(() => {
<del> modifyPackages([
<del> { name: 'ember-qunit', delete: true },
<del> { name: 'ember-cli-qunit', dev: true },
<del> ]);
<del> generateFakePackageManifest('ember-cli-qunit', '4.1.0');
<del> });
<add> return emberNew({ target: 'addon' }).then(() => {
<add> modifyPackages([
<add> { name: 'ember-qunit', delete: true },
<add> { name: 'ember-cli-qunit', dev: true },
<add> ]);
<add> generateFakePackageManifest('ember-cli-qunit', '4.1.0');
<add> });
<ide> });
<ide>
<ide> it('helper foo/bar-baz', function() {
<ide> describe('Blueprint: helper', function() {
<ide> enableModuleUnification();
<ide>
<ide> beforeEach(function() {
<del> return emberNew({ target: 'in-repo-addon' })
<del> .then(() => fs.ensureDirSync('src'))
<del> .then(() => {
<del> modifyPackages([
<del> { name: 'ember-qunit', delete: true },
<del> { name: 'ember-cli-qunit', dev: true },
<del> ]);
<del> generateFakePackageManifest('ember-cli-qunit', '4.1.0');
<del> });
<add> return emberNew({ target: 'in-repo-addon' }).then(() => {
<add> modifyPackages([
<add> { name: 'ember-qunit', delete: true },
<add> { name: 'ember-cli-qunit', dev: true },
<add> ]);
<add> generateFakePackageManifest('ember-cli-qunit', '4.1.0');
<add> });
<ide> });
<ide>
<ide> it('helper foo/bar-baz --in-repo-addon=my-addon', function() {
<ide><path>node-tests/blueprints/initializer-test-test.js
<ide> const expect = chai.expect;
<ide> const generateFakePackageManifest = require('../helpers/generate-fake-package-manifest');
<ide> const enableModuleUnification = require('../helpers/module-unification').enableModuleUnification;
<ide> const fixture = require('../helpers/fixture');
<del>const fs = require('fs-extra');
<ide>
<ide> describe('Blueprint: initializer-test', function() {
<ide> setupTestHooks(this);
<ide> describe('Blueprint: initializer-test', function() {
<ide> enableModuleUnification();
<ide>
<ide> beforeEach(function() {
<del> return emberNew().then(() => fs.ensureDirSync('src'));
<add> return emberNew();
<ide> });
<ide>
<ide> describe('with ember-cli-qunit@4.1.0', function() {
<ide> describe('Blueprint: initializer-test', function() {
<ide> enableModuleUnification();
<ide>
<ide> beforeEach(function() {
<del> return emberNew({ target: 'addon' }).then(() => fs.ensureDirSync('src'));
<add> return emberNew({ target: 'addon' });
<ide> });
<ide>
<ide> describe('with ember-cli-qunit@4.1.0', function() {
<ide><path>node-tests/blueprints/initializer-test.js
<ide> const expectError = require('../helpers/expect-error');
<ide>
<ide> const chai = require('ember-cli-blueprint-test-helpers/chai');
<ide> const expect = chai.expect;
<del>const fs = require('fs-extra');
<ide>
<ide> const generateFakePackageManifest = require('../helpers/generate-fake-package-manifest');
<ide> const enableModuleUnification = require('../helpers/module-unification').enableModuleUnification;
<ide> describe('Blueprint: initializer', function() {
<ide>
<ide> beforeEach(function() {
<ide> return emberNew()
<del> .then(() => fs.ensureDirSync('src'))
<ide> .then(() =>
<ide> modifyPackages([
<ide> { name: 'ember-qunit', delete: true },
<ide> describe('Blueprint: initializer', function() {
<ide>
<ide> beforeEach(function() {
<ide> return emberNew({ target: 'addon' })
<del> .then(() => fs.ensureDirSync('src'))
<ide> .then(() =>
<ide> modifyPackages([
<ide> { name: 'ember-qunit', delete: true },
<ide><path>node-tests/blueprints/instance-initializer-test-test.js
<ide> const expect = chai.expect;
<ide> const generateFakePackageManifest = require('../helpers/generate-fake-package-manifest');
<ide> const enableModuleUnification = require('../helpers/module-unification').enableModuleUnification;
<ide> const fixture = require('../helpers/fixture');
<del>const fs = require('fs-extra');
<ide>
<ide> describe('Blueprint: instance-initializer-test', function() {
<ide> setupTestHooks(this);
<ide> describe('Blueprint: instance-initializer-test', function() {
<ide> enableModuleUnification();
<ide>
<ide> beforeEach(function() {
<del> return emberNew().then(() => fs.ensureDirSync('src'));
<add> return emberNew();
<ide> });
<ide>
<ide> describe('with ember-cli-qunit@4.1.0', function() {
<ide> describe('Blueprint: instance-initializer-test', function() {
<ide> enableModuleUnification();
<ide>
<ide> beforeEach(function() {
<del> return emberNew({ target: 'addon' }).then(() => fs.ensureDirSync('src'));
<add> return emberNew({ target: 'addon' });
<ide> });
<ide>
<ide> describe('with ember-cli-qunit@4.1.0', function() {
<ide><path>node-tests/blueprints/instance-initializer-test.js
<ide> const expectError = require('../helpers/expect-error');
<ide>
<ide> const chai = require('ember-cli-blueprint-test-helpers/chai');
<ide> const expect = chai.expect;
<del>const fs = require('fs-extra');
<ide>
<ide> const generateFakePackageManifest = require('../helpers/generate-fake-package-manifest');
<ide> const enableModuleUnification = require('../helpers/module-unification').enableModuleUnification;
<ide> describe('Blueprint: instance-initializer', function() {
<ide>
<ide> beforeEach(function() {
<ide> return emberNew()
<del> .then(() => fs.ensureDirSync('src'))
<ide> .then(() =>
<ide> modifyPackages([
<ide> { name: 'ember-qunit', delete: true },
<ide> describe('Blueprint: instance-initializer', function() {
<ide>
<ide> beforeEach(function() {
<ide> return emberNew({ target: 'addon' })
<del> .then(() => fs.ensureDirSync('src'))
<ide> .then(() =>
<ide> modifyPackages([
<ide> { name: 'ember-qunit', delete: true },
<ide><path>node-tests/blueprints/mixin-test-test.js
<ide> const modifyPackages = blueprintHelpers.modifyPackages;
<ide>
<ide> const chai = require('ember-cli-blueprint-test-helpers/chai');
<ide> const expect = chai.expect;
<del>const fs = require('fs-extra');
<ide>
<ide> const generateFakePackageManifest = require('../helpers/generate-fake-package-manifest');
<ide> const enableModuleUnification = require('../helpers/module-unification').enableModuleUnification;
<ide> describe('Blueprint: mixin-test', function() {
<ide> enableModuleUnification();
<ide>
<ide> beforeEach(function() {
<del> return emberNew().then(() => fs.ensureDirSync('src'));
<add> return emberNew();
<ide> });
<ide>
<ide> describe('with ember-cli-qunit@4.1.0', function() {
<ide> describe('Blueprint: mixin-test', function() {
<ide> enableModuleUnification();
<ide>
<ide> beforeEach(function() {
<del> return emberNew({ target: 'addon' })
<del> .then(() =>
<del> modifyPackages([
<del> { name: 'ember-qunit', delete: true },
<del> { name: 'ember-cli-qunit', dev: true },
<del> ])
<del> )
<del> .then(() => fs.ensureDirSync('src'));
<add> return emberNew({ target: 'addon' }).then(() =>
<add> modifyPackages([
<add> { name: 'ember-qunit', delete: true },
<add> { name: 'ember-cli-qunit', dev: true },
<add> ])
<add> );
<ide> });
<ide>
<ide> it('mixin-test foo', function() {
<ide><path>node-tests/blueprints/mixin-test.js
<ide> const enableModuleUnification = require('../helpers/module-unification').enableM
<ide>
<ide> const chai = require('ember-cli-blueprint-test-helpers/chai');
<ide> const expect = chai.expect;
<del>const fs = require('fs-extra');
<ide>
<ide> describe('Blueprint: mixin', function() {
<ide> setupTestHooks(this);
<ide> describe('Blueprint: mixin', function() {
<ide> enableModuleUnification();
<ide>
<ide> beforeEach(function() {
<del> return emberNew().then(() => fs.ensureDirSync('src'));
<add> return emberNew();
<ide> });
<ide>
<ide> it('mixin foo', function() {
<ide> describe('Blueprint: mixin', function() {
<ide> enableModuleUnification();
<ide>
<ide> beforeEach(function() {
<del> return emberNew({ target: 'addon' }).then(() => fs.ensureDirSync('src'));
<add> return emberNew({ target: 'addon' });
<ide> });
<ide>
<ide> it('mixin foo', function() {
<ide><path>node-tests/blueprints/route-test.js
<ide> describe('Blueprint: route', function() {
<ide>
<ide> beforeEach(function() {
<ide> return emberNew()
<del> .then(() => fs.ensureDirSync('src'))
<ide> .then(() =>
<ide> modifyPackages([
<ide> { name: 'ember-qunit', delete: true },
<ide> describe('Blueprint: route', function() {
<ide>
<ide> beforeEach(function() {
<ide> return emberNew({ target: 'addon' })
<del> .then(() => fs.ensureDirSync('src'))
<ide> .then(() =>
<ide> modifyPackages([
<ide> { name: 'ember-qunit', delete: true },
<ide><path>node-tests/blueprints/service-test.js
<ide> const expectError = require('../helpers/expect-error');
<ide>
<ide> const chai = require('ember-cli-blueprint-test-helpers/chai');
<ide> const expect = chai.expect;
<del>const fs = require('fs-extra');
<ide>
<ide> const generateFakePackageManifest = require('../helpers/generate-fake-package-manifest');
<ide> const enableModuleUnification = require('../helpers/module-unification').enableModuleUnification;
<ide> describe('Blueprint: service', function() {
<ide>
<ide> beforeEach(function() {
<ide> return emberNew()
<del> .then(() => fs.ensureDirSync('src'))
<ide> .then(() =>
<ide> modifyPackages([
<ide> { name: 'ember-qunit', delete: true },
<ide> describe('Blueprint: service', function() {
<ide>
<ide> beforeEach(function() {
<ide> return emberNew({ target: 'addon' })
<del> .then(() => fs.ensureDirSync('src'))
<ide> .then(() =>
<ide> modifyPackages([
<ide> { name: 'ember-qunit', delete: true },
<ide><path>node-tests/blueprints/template-test.js
<ide> const enableModuleUnification = require('../helpers/module-unification').enableM
<ide>
<ide> const chai = require('ember-cli-blueprint-test-helpers/chai');
<ide> const expect = chai.expect;
<del>const fs = require('fs-extra');
<ide>
<ide> describe('Blueprint: template', function() {
<ide> setupTestHooks(this);
<ide> describe('Blueprint: template', function() {
<ide> enableModuleUnification();
<ide>
<ide> beforeEach(function() {
<del> return emberNew().then(() => fs.ensureDirSync('src'));
<add> return emberNew();
<ide> });
<ide>
<ide> it('template foo', function() {
<ide> describe('Blueprint: template', function() {
<ide> enableModuleUnification();
<ide>
<ide> beforeEach(function() {
<del> return emberNew().then(() => fs.ensureDirSync('src'));
<add> return emberNew();
<ide> });
<ide>
<ide> it('shows an error', function() {
<ide> describe('Blueprint: template', function() {
<ide> enableModuleUnification();
<ide>
<ide> beforeEach(function() {
<del> return emberNew({ target: 'addon' }).then(() => fs.ensureDirSync('src'));
<add> return emberNew({ target: 'addon' });
<ide> });
<ide>
<ide> it('template foo', function() {
<ide><path>node-tests/blueprints/util-test-test.js
<ide> const modifyPackages = blueprintHelpers.modifyPackages;
<ide>
<ide> const chai = require('ember-cli-blueprint-test-helpers/chai');
<ide> const expect = chai.expect;
<del>const fs = require('fs-extra');
<ide>
<ide> const generateFakePackageManifest = require('../helpers/generate-fake-package-manifest');
<ide> const enableModuleUnification = require('../helpers/module-unification').enableModuleUnification;
<ide> describe('Blueprint: util-test', function() {
<ide> enableModuleUnification();
<ide>
<ide> beforeEach(function() {
<del> return emberNew().then(() => fs.ensureDirSync('src'));
<add> return emberNew();
<ide> });
<ide>
<ide> describe('with ember-cli-qunit@4.1.0', function() {
<ide> describe('Blueprint: util-test', function() {
<ide> enableModuleUnification();
<ide>
<ide> beforeEach(function() {
<del> return emberNew({ target: 'addon' }).then(() => fs.ensureDirSync('src'));
<add> return emberNew({ target: 'addon' });
<ide> });
<ide>
<ide> describe('with ember-cli-qunit@4.1.0', function() {
<ide><path>node-tests/blueprints/util-test.js
<ide> const expectError = require('../helpers/expect-error');
<ide>
<ide> const chai = require('ember-cli-blueprint-test-helpers/chai');
<ide> const expect = chai.expect;
<del>const fs = require('fs-extra');
<ide>
<ide> const generateFakePackageManifest = require('../helpers/generate-fake-package-manifest');
<ide> const enableModuleUnification = require('../helpers/module-unification').enableModuleUnification;
<ide> describe('Blueprint: util', function() {
<ide>
<ide> beforeEach(function() {
<ide> return emberNew()
<del> .then(() => fs.ensureDirSync('src'))
<ide> .then(() =>
<ide> modifyPackages([
<ide> { name: 'ember-qunit', delete: true },
<ide> describe('Blueprint: util', function() {
<ide>
<ide> beforeEach(function() {
<ide> return emberNew({ target: 'addon' })
<del> .then(() => fs.ensureDirSync('src'))
<ide> .then(() =>
<ide> modifyPackages([
<ide> { name: 'ember-qunit', delete: true },
| 18
|
PHP
|
PHP
|
add `dropconstrainedforeignid` method
|
86d08e4b743a37269790482a516936e63f4e881b
|
<ide><path>src/Illuminate/Database/Schema/Blueprint.php
<ide> public function dropForeign($index)
<ide> return $this->dropIndexCommand('dropForeign', 'foreign', $index);
<ide> }
<ide>
<add> /**
<add> * Indicate that the given column and foreign key should be dropped.
<add> *
<add> * @param string $column
<add> * @return \Illuminate\Support\Fluent
<add> */
<add> public function dropConstrainedForeignId($column)
<add> {
<add> $this->dropForeign([$column]);
<add>
<add> return $this->dropColumn($column);
<add> }
<add>
<ide> /**
<ide> * Indicate that the given indexes should be renamed.
<ide> *
<ide><path>tests/Database/DatabaseSqlServerSchemaGrammarTest.php
<ide> public function testDropForeign()
<ide> $this->assertSame('alter table "users" drop constraint "foo"', $statements[0]);
<ide> }
<ide>
<add> public function testdropConstrainedForeignId()
<add> {
<add> $blueprint = new Blueprint('users');
<add> $blueprint->dropConstrainedForeignId('foo');
<add> $statements = $blueprint->toSql($this->getConnection(), $this->getGrammar());
<add>
<add> $this->assertCount(2, $statements);
<add> $this->assertSame('alter table "users" drop constraint "users_foo_foreign"', $statements[0]);
<add> $this->assertSame('DECLARE @sql NVARCHAR(MAX) = \'\';SELECT @sql += \'ALTER TABLE [dbo].[users] DROP CONSTRAINT \' + OBJECT_NAME([default_object_id]) + \';\' FROM SYS.COLUMNS WHERE [object_id] = OBJECT_ID(\'[dbo].[users]\') AND [name] in (\'foo\') AND [default_object_id] <> 0;EXEC(@sql);alter table "users" drop column "foo"', $statements[1]);
<add> }
<add>
<ide> public function testDropTimestamps()
<ide> {
<ide> $blueprint = new Blueprint('users');
| 2
|
Python
|
Python
|
add `equal_nan` argument to allclose
|
e1d3a0c66d719fe908de317c08b1234b71af196f
|
<ide><path>numpy/core/numeric.py
<ide> def identity(n, dtype=None):
<ide> from numpy import eye
<ide> return eye(n, dtype=dtype)
<ide>
<del>def allclose(a, b, rtol=1.e-5, atol=1.e-8):
<add>def allclose(a, b, rtol=1.e-5, atol=1.e-8, equal_nan=False):
<ide> """
<ide> Returns True if two arrays are element-wise equal within a tolerance.
<ide>
<ide> def allclose(a, b, rtol=1.e-5, atol=1.e-8):
<ide> The relative tolerance parameter (see Notes).
<ide> atol : float
<ide> The absolute tolerance parameter (see Notes).
<add> equal_nan : bool
<add> Whether to compare NaN's as equal. If True, NaN's in `a` will be
<add> considered equal to NaN's in `b` in the output array.
<ide>
<ide> Returns
<ide> -------
<ide> def allclose(a, b, rtol=1.e-5, atol=1.e-8):
<ide> False
<ide> >>> np.allclose([1.0, np.nan], [1.0, np.nan])
<ide> False
<add> >>> np.allclose([1.0, np.nan], [1.0, np.nan], equal_nan=True)
<add> True
<ide>
<ide> """
<del> return all(isclose(a, b, rtol=rtol, atol=atol))
<add> return all(isclose(a, b, rtol=rtol, atol=atol, equal_nan=equal_nan))
<ide>
<ide> def isclose(a, b, rtol=1.e-5, atol=1.e-8, equal_nan=False):
<ide> """
<ide><path>numpy/testing/utils.py
<ide> def _assert_valid_refcount(op):
<ide>
<ide> assert_(sys.getrefcount(i) >= rc)
<ide>
<del>def assert_allclose(actual, desired, rtol=1e-7, atol=0,
<add>def assert_allclose(actual, desired, rtol=1e-7, atol=0, equal_nan=False,
<ide> err_msg='', verbose=True):
<ide> """
<ide> Raises an AssertionError if two objects are not equal up to desired
<ide> def assert_allclose(actual, desired, rtol=1e-7, atol=0,
<ide> Relative tolerance.
<ide> atol : float, optional
<ide> Absolute tolerance.
<add> equal_nan : bool, optional.
<add> If True, NaNs will compare equal.
<ide> err_msg : str, optional
<ide> The error message to be printed in case of failure.
<ide> verbose : bool, optional
<ide> def assert_allclose(actual, desired, rtol=1e-7, atol=0,
<ide> """
<ide> import numpy as np
<ide> def compare(x, y):
<del> return np.core.numeric._allclose_points(x, y, rtol=rtol, atol=atol)
<add> return np.core.numeric.isclose(x, y, rtol=rtol, atol=atol,
<add> equal_nan=equal_nan)
<ide>
<ide> actual, desired = np.asanyarray(actual), np.asanyarray(desired)
<ide> header = 'Not equal to tolerance rtol=%g, atol=%g' % (rtol, atol)
| 2
|
Javascript
|
Javascript
|
fix safari script test count
|
a277218db580eb5e7aec0594a823e766a937b363
|
<ide><path>test/integration/production/test/index.test.js
<ide> describe('Production Usage', () => {
<ide> if (browserName === 'safari') {
<ide> const elements = await browser.elementsByCss('link[rel=preload]')
<ide> // 4 page preloads and 5 existing preloads for _app, commons, main, etc
<del> expect(elements.length).toBe(9)
<add> expect(elements.length).toBe(13)
<ide> } else {
<ide> const elements = await browser.elementsByCss('link[rel=prefetch]')
<ide> expect(elements.length).toBe(4)
| 1
|
Javascript
|
Javascript
|
remove appendchecked detect and stranded markup
|
1e5b14a131fca29b97830168a1d743d007d1d761
|
<ide><path>src/support.js
<ide> jQuery.support = (function() {
<ide>
<del> var support, all, a, select, opt, input, fragment,
<add> var support, a, select, opt, input, fragment,
<ide> div = document.createElement("div");
<ide>
<del> // Setup
<del> div.setAttribute( "className", "t" );
<del> div.innerHTML = " <link/><table></table><a>a</a><input type='checkbox'/>";
<add> div.innerHTML = "<a>a</a><input type='checkbox'/>";
<ide>
<ide> // Support tests won't run in some limited or non-browser environments
<del> all = div.getElementsByTagName("*");
<ide> a = div.getElementsByTagName("a")[ 0 ];
<del> if ( !all || !a || !all.length ) {
<add> if ( !a ) {
<ide> return {};
<ide> }
<ide>
<ide> jQuery.support = (function() {
<ide> fragment = document.createDocumentFragment();
<ide> fragment.appendChild( input );
<ide>
<del> // Check if a disconnected checkbox will retain its checked
<del> // value of true after appended to the DOM (IE6/7)
<del> support.appendChecked = input.checked;
<del>
<ide> // WebKit doesn't clone checked state correctly in fragments
<ide> support.checkClone = fragment.cloneNode( true ).cloneNode( true ).lastChild.checked;
<ide>
<ide> jQuery.support = (function() {
<ide> });
<ide>
<ide> // Null elements to avoid leaks in IE
<del> all = select = fragment = opt = a = input = null;
<add> select = fragment = opt = a = input = null;
<ide>
<ide> return support;
<ide> })();
| 1
|
Ruby
|
Ruby
|
store the enum values in the defined_enum constant
|
5620e62f3f1920e70199a870a0a3c4feaedb9f98
|
<ide><path>activerecord/lib/active_record/enum.rb
<ide> module ActiveRecord
<ide> #
<ide> # Conversation.where("status <> ?", Conversation.statuses[:archived])
<ide> module Enum
<del> DEFINED_ENUMS = [] # :nodoc:
<add> DEFINED_ENUMS = {} # :nodoc:
<ide>
<del> def enum_attribute?(attr_name) # :nodoc:
<del> DEFINED_ENUMS.include?(attr_name.to_sym)
<add> def enum_mapping_for(attr_name) # :nodoc:
<add> DEFINED_ENUMS[attr_name.to_sym]
<ide> end
<ide>
<ide> def enum(definitions)
<ide> def enum(definitions)
<ide> enum_values = ActiveSupport::HashWithIndifferentAccess.new
<ide> name = name.to_sym
<ide>
<del> DEFINED_ENUMS.unshift name
<del>
<ide> # def self.statuses statuses end
<ide> klass.singleton_class.send(:define_method, name.to_s.pluralize) { enum_values }
<ide>
<ide> def enum(definitions)
<ide> # def active!() update! status: :active end
<ide> define_method("#{value}!") { update! name => value }
<ide> end
<add>
<add> DEFINED_ENUMS[name] = enum_values
<ide> end
<ide> end
<ide> end
<ide> def _enum_methods_module
<ide> mod = Module.new do
<ide> private
<ide> def save_changed_attribute(attr_name, value)
<del> if self.class.enum_attribute?(attr_name)
<add> if (mapping = self.class.enum_mapping_for(attr_name))
<ide> if attribute_changed?(attr_name)
<ide> old = changed_attributes[attr_name]
<ide>
<del> if self.class.public_send(attr_name.pluralize)[old] == value
<add> if mapping[old] == value
<ide> changed_attributes.delete(attr_name)
<ide> end
<ide> else
<ide> old = clone_attribute_value(:read_attribute, attr_name)
<ide>
<ide> if old != value
<del> changed_attributes[attr_name] = self.class.public_send(attr_name.pluralize).key old
<add> changed_attributes[attr_name] = mapping.key old
<ide> end
<ide> end
<ide> else
| 1
|
PHP
|
PHP
|
fix incorrect docs
|
4e168ca004ee8b0a5cdba7271d897c29cd652fc0
|
<ide><path>lib/Cake/View/Helper/TimeHelper.php
<ide> public function toRSS($dateString, $timezone = null) {
<ide> }
<ide>
<ide> /**
<del> * Formats date for RSS feeds
<add> * Formats a date into a phrase expressing the relative time.
<ide> *
<ide> * ## Addition options
<ide> *
| 1
|
Javascript
|
Javascript
|
add integrity to html property config
|
68eb1a6fb6266d128fd87cfac6a201f6eba13308
|
<ide><path>src/renderers/dom/shared/HTMLDOMPropertyConfig.js
<ide> var HTMLDOMPropertyConfig = {
<ide> icon: null,
<ide> id: MUST_USE_PROPERTY,
<ide> inputMode: MUST_USE_ATTRIBUTE,
<add> integrity: null,
<ide> is: MUST_USE_ATTRIBUTE,
<ide> keyParams: MUST_USE_ATTRIBUTE,
<ide> keyType: MUST_USE_ATTRIBUTE,
| 1
|
Ruby
|
Ruby
|
remove unused block local var `cli`
|
a0550aee11f0c849c071f65c94d7442ef84c4ed9
|
<ide><path>activerecord/test/cases/associations/has_many_associations_test.rb
<ide> def test_association_with_rewhere_doesnt_set_inverse_instance_key
<ide>
<ide> test "first_or_initialize adds the record to the association" do
<ide> firm = Firm.create! name: "omg"
<del> client = firm.clients_of_firm.where(name: "lol").first_or_initialize do |cli|
<add> client = firm.clients_of_firm.where(name: "lol").first_or_initialize do
<ide> assert_deprecated do
<ide> assert_equal 0, Client.count
<ide> end
<ide> def test_association_with_rewhere_doesnt_set_inverse_instance_key
<ide> test "first_or_create adds the record to the association" do
<ide> firm = Firm.create! name: "omg"
<ide> firm.clients_of_firm.load_target
<del> client = firm.clients_of_firm.where(name: "lol").first_or_create do |cli|
<add> client = firm.clients_of_firm.where(name: "lol").first_or_create do
<ide> assert_deprecated do
<ide> assert_equal 0, Client.count
<ide> end
<ide> def test_association_with_rewhere_doesnt_set_inverse_instance_key
<ide> test "first_or_create! adds the record to the association" do
<ide> firm = Firm.create! name: "omg"
<ide> firm.clients_of_firm.load_target
<del> client = firm.clients_of_firm.where(name: "lol").first_or_create! do |cli|
<add> client = firm.clients_of_firm.where(name: "lol").first_or_create! do
<ide> assert_deprecated do
<ide> assert_equal 0, Client.count
<ide> end
| 1
|
Text
|
Text
|
fix path in tf-slim readme
|
687e6fdfe2b925de362e9ef68b0b8a03ead4e277
|
<ide><path>slim/README.md
<ide> To verify that this has worked, execute the following commands; it should run
<ide> without raising any errors.
<ide>
<ide> ```
<del>cd $HOME/workspace/slim
<add>cd $HOME/workspace/models/slim
<ide> python -c "from nets import cifarnet; mynet = cifarnet.cifarnet"
<ide> ```
<ide>
| 1
|
Javascript
|
Javascript
|
remove weird white space not present locally
|
11821e40aa6ab6985da39198fe7845984732b72e
|
<ide><path>common/app/routes/Challenges/rechallenge/transformers.js
<ide> export function applyTransformers(file, transformers = _transformers) {
<ide> return obs.flatMap(file => castToObservable(transformer(file)));
<ide> },
<ide> Observable.of(file)
<del> );
<add> );
<ide> }
| 1
|
Python
|
Python
|
add kaggle otto example
|
6e3ec8ef69bd01e86d2575e9b7d84b35e549e3d8
|
<ide><path>examples/kaggle_otto_nn.py
<add>from __future__ import absolute_import
<add>from __future__ import print_function
<add>
<add>import numpy as np
<add>import pandas as pd
<add>
<add>from keras.models import Sequential
<add>from keras.layers.core import Dense, Dropout, Activation
<add>from keras.layers.normalization import BatchNormalization
<add>from keras.layers.advanced_activations import PReLU
<add>from keras.utils import np_utils, generic_utils
<add>
<add>from sklearn.preprocessing import LabelEncoder
<add>from sklearn.preprocessing import StandardScaler
<add>
<add>'''
<add> This demonstrates how to reach a score of 0.4890 (local validation)
<add> on the Kaggle Otto challenge, with a deep net using Keras.
<add>
<add> Compatible Python 2.7-3.4
<add>
<add> Recommended to run on GPU:
<add> Command: THEANO_FLAGS=mode=FAST_RUN,device=gpu,floatX=float32 python kaggle_otto_nn.py
<add> On EC2 g2.2xlarge instance: 10s/epoch. 6-7 minutes total training time.
<add>
<add> Best validation score at epoch 21: 0.4881
<add>
<add> Try it at home:
<add> - with/without BatchNormalization (BatchNormalization helps!)
<add> - with ReLU or with PReLU (PReLU helps!)
<add> - with smaller layers, largers layers
<add> - with more layers, less layers
<add> - with different optimizers (SGD+momentum+decay is probably better than Adam!)
<add>'''
<add>
<add>np.random.seed(1337) # for reproducibility
<add>
<add>def load_data(path, train=True):
<add> df = pd.read_csv(path)
<add> X = df.values.copy()
<add> if train:
<add> np.random.shuffle(X) # https://youtu.be/uyUXoap67N8
<add> X, labels = X[:, 1:-1].astype(np.float32), X[:, -1]
<add> return X, labels
<add> else:
<add> X, ids = X[:, 1:].astype(np.float32), X[:, 0].astype(str)
<add> return X, ids
<add>
<add>def preprocess_data(X, scaler=None):
<add> if not scaler:
<add> scaler = StandardScaler()
<add> scaler.fit(X)
<add> X = scaler.transform(X)
<add> return X, scaler
<add>
<add>def preprocess_labels(y, encoder=None, categorical=True):
<add> if not encoder:
<add> encoder = LabelEncoder()
<add> encoder.fit(labels)
<add> y = encoder.transform(labels).astype(np.int32)
<add> if categorical:
<add> y = np_utils.to_categorical(y)
<add> return y, encoder
<add>
<add>def make_submission(y_prob, ids, encoder, fname):
<add> with open(fname, 'w') as f:
<add> f.write('id,')
<add> f.write(','.join(encoder.classes_))
<add> f.write('\n')
<add> for i, probs in zip(ids, y_prob):
<add> probas = ','.join([i] + [str(p) for p in probs.tolist()])
<add> f.write(probas)
<add> f.write('\n')
<add> print("Wrote submission to file {}.".format(fname))
<add>
<add>
<add>print("Loading data...")
<add>X, labels = load_data('train.csv', train=True)
<add>X, scaler = preprocess_data(X)
<add>y, encoder = preprocess_labels(labels)
<add>
<add>X_test, ids = load_data('test.csv', train=False)
<add>X_test, _ = preprocess_data(X_test)
<add>
<add>nb_classes = y.shape[1]
<add>print(nb_classes, 'classes')
<add>
<add>dims = X.shape[1]
<add>print(dims, 'dims')
<add>
<add>print("Building model...")
<add>
<add>model = Sequential()
<add>model.add(Dense(dims, 512, init='glorot_uniform'))
<add>model.add(PReLU((512,)))
<add>model.add(BatchNormalization((512,)))
<add>model.add(Dropout(0.5))
<add>
<add>model.add(Dense(512, 512, init='glorot_uniform'))
<add>model.add(PReLU((512,)))
<add>model.add(BatchNormalization((512,)))
<add>model.add(Dropout(0.5))
<add>
<add>model.add(Dense(512, 512, init='glorot_uniform'))
<add>model.add(PReLU((512,)))
<add>model.add(BatchNormalization((512,)))
<add>model.add(Dropout(0.5))
<add>
<add>model.add(Dense(512, nb_classes, init='glorot_uniform'))
<add>model.add(Activation('softmax'))
<add>
<add>model.compile(loss='categorical_crossentropy', optimizer="adam")
<add>
<add>print("Training model...")
<add>
<add>model.fit(X, y, nb_epoch=20, batch_size=16, validation_split=0.15)
<add>
<add>print("Generating submission...")
<add>
<add>proba = model.predict_proba(X_test)
<add>make_submission(proba, ids, encoder, fname='keras-otto.csv')
<add>
| 1
|
Text
|
Text
|
update data analysis with python links
|
b74b32385bcc3bb3104729ff73339df00dc8016e
|
<ide><path>curriculum/challenges/english/08-data-analysis-with-python/data-analysis-with-python-course/parsing-html-and-saving-data.md
<ide> dashedName: parsing-html-and-saving-data
<ide>
<ide> More resources:
<ide>
<del>- [Notebooks on GitHub](https://github.com/ine-rmotr-curriculum/RDP-Reading-Data-with-Python-and-Pandas)
<add>- [Notebooks on GitHub](https://github.com/ine-rmotr-curriculum/RDP-Reading-Data-with-Python-and-Pandas/tree/master/unit-1-reading-data-with-python-and-pandas/lesson-17-reading-html-tables/files)
<ide> - [How to open Notebooks from GitHub using Google Colab.](https://colab.research.google.com/github/googlecolab/colabtools/blob/master/notebooks/colab-github-demo.ipynb)
<ide>
<ide> # --question--
<ide><path>curriculum/challenges/english/08-data-analysis-with-python/data-analysis-with-python-course/reading-data-csv-and-txt.md
<ide> dashedName: reading-data-csv-and-txt
<ide>
<ide> More resources:
<ide>
<del>- [Notebooks on GitHub](https://github.com/ine-rmotr-curriculum/RDP-Reading-Data-with-Python-and-Pandas)
<add>- [Notebooks on GitHub](https://github.com/ine-rmotr-curriculum/RDP-Reading-Data-with-Python-and-Pandas/tree/master/unit-1-reading-data-with-python-and-pandas/lesson-1-reading-csv-and-txt-files/files)
<ide> - [How to open Notebooks from GitHub using Google Colab.](https://colab.research.google.com/github/googlecolab/colabtools/blob/master/notebooks/colab-github-demo.ipynb)
<ide>
<ide> # --question--
<ide><path>curriculum/challenges/english/08-data-analysis-with-python/data-analysis-with-python-course/reading-data-from-databases.md
<ide> dashedName: reading-data-from-databases
<ide>
<ide> More resources:
<ide>
<del>- [Notebooks on GitHub](https://github.com/ine-rmotr-curriculum/RDP-Reading-Data-with-Python-and-Pandas)
<add>- [Notebooks on GitHub](https://github.com/ine-rmotr-curriculum/RDP-Reading-Data-with-Python-and-Pandas/tree/master/unit-1-reading-data-with-python-and-pandas/lesson-11-reading-data-from-relational-databases/files)
<ide> - [How to open Notebooks from GitHub using Google Colab.](https://colab.research.google.com/github/googlecolab/colabtools/blob/master/notebooks/colab-github-demo.ipynb)
<ide>
<ide> # --question--
<ide><path>curriculum/challenges/english/08-data-analysis-with-python/data-analysis-with-python-course/reading-data-introduction.md
<ide> dashedName: reading-data-introduction
<ide>
<ide> More resources:
<ide>
<del>- [Notebooks on GitHub](https://github.com/ine-rmotr-curriculum/RDP-Reading-Data-with-Python-and-Pandas)
<add>- [Notebooks on GitHub](https://github.com/ine-rmotr-curriculum/RDP-Reading-Data-with-Python-and-Pandas/tree/master/unit-1-reading-data-with-python-and-pandas/lesson-1-reading-csv-and-txt-files/files)
<ide> - [How to open Notebooks from GitHub using Google Colab.](https://colab.research.google.com/github/googlecolab/colabtools/blob/master/notebooks/colab-github-demo.ipynb)
<ide>
<ide> # --question--
| 4
|
Python
|
Python
|
fix modelcheckpoint callback
|
63f9a7955d81894a643bc292bcd522b3a391676a
|
<ide><path>keras/callbacks.py
<ide> class ModelCheckpoint(Callback):
<ide> def __init__(self, filepath, monitor='val_loss', verbose=0, save_best_only=False):
<ide> super(Callback, self).__init__()
<ide>
<del> self.monitor
<add> self.monitor = monitor
<ide> self.verbose = verbose
<ide> self.filepath = filepath
<ide> self.save_best_only = save_best_only
| 1
|
Javascript
|
Javascript
|
accept windows relative path
|
b36c581d5bd7e6087aab794af222e122e5a32f03
|
<ide><path>lib/internal/modules/cjs/loader.js
<ide> const {
<ide> CHAR_9,
<ide> } = require('internal/constants');
<ide>
<add>const isWindows = process.platform === 'win32';
<add>
<ide> function stat(filename) {
<ide> filename = path.toNamespacedPath(filename);
<ide> const cache = stat.cache;
<ide> Module._findPath = function(request, paths, isMain) {
<ide> // 'node_modules' character codes reversed
<ide> var nmChars = [ 115, 101, 108, 117, 100, 111, 109, 95, 101, 100, 111, 110 ];
<ide> var nmLen = nmChars.length;
<del>if (process.platform === 'win32') {
<add>if (isWindows) {
<ide> // 'from' is the __dirname of the module.
<ide> Module._nodeModulePaths = function(from) {
<ide> // guarantee that 'from' is absolute.
<ide> Module._resolveLookupPaths = function(request, parent, newReturn) {
<ide> return (newReturn ? null : [request, []]);
<ide> }
<ide>
<del> // Check for relative path
<add> // Check for non-relative path
<ide> if (request.length < 2 ||
<ide> request.charCodeAt(0) !== CHAR_DOT ||
<ide> (request.charCodeAt(1) !== CHAR_DOT &&
<del> request.charCodeAt(1) !== CHAR_FORWARD_SLASH)) {
<add> request.charCodeAt(1) !== CHAR_FORWARD_SLASH &&
<add> (!isWindows || request.charCodeAt(1) !== CHAR_BACKWARD_SLASH))) {
<ide> var paths = modulePaths;
<ide> if (parent) {
<ide> if (!parent.paths)
<ide> Module._resolveLookupPaths = function(request, parent, newReturn) {
<ide>
<ide> // make sure require('./path') and require('path') get distinct ids, even
<ide> // when called from the toplevel js file
<del> if (parentIdPath === '.' && id.indexOf('/') === -1) {
<add> if (parentIdPath === '.' &&
<add> id.indexOf('/') === -1 &&
<add> (!isWindows || id.indexOf('\\') === -1)) {
<ide> id = './' + id;
<ide> }
<ide>
<ide> Module.runMain = function() {
<ide> };
<ide>
<ide> Module._initPaths = function() {
<del> const isWindows = process.platform === 'win32';
<del>
<ide> var homeDir;
<ide> var nodePath;
<ide> if (isWindows) {
<ide><path>test/parallel/test-module-relative-lookup.js
<ide> 'use strict';
<ide>
<del>require('../common');
<add>const common = require('../common');
<ide> const assert = require('assert');
<ide> const _module = require('module'); // avoid collision with global.module
<del>const lookupResults = _module._resolveLookupPaths('./lodash');
<del>let paths = lookupResults[1];
<ide>
<ide> // Current directory gets highest priority for local modules
<del>assert.strictEqual(paths[0], '.');
<add>function testFirstInPath(moduleName, isLocalModule) {
<add> const assertFunction = isLocalModule ?
<add> assert.strictEqual :
<add> assert.notStrictEqual;
<ide>
<del>paths = _module._resolveLookupPaths('./lodash', null, true);
<add> const lookupResults = _module._resolveLookupPaths(moduleName);
<ide>
<del>// Current directory gets highest priority for local modules
<del>assert.strictEqual(paths && paths[0], '.');
<add> let paths = lookupResults[1];
<add> assertFunction(paths[0], '.');
<add>
<add> paths = _module._resolveLookupPaths(moduleName, null, true);
<add> assertFunction(paths && paths[0], '.');
<add>}
<add>
<add>testFirstInPath('./lodash', true);
<add>
<add>// Relative path on Windows, but a regular file name elsewhere
<add>testFirstInPath('.\\lodash', common.isWindows);
<ide><path>test/parallel/test-preload.js
<ide> childProcess.exec(
<ide> }
<ide> );
<ide>
<add>// test that preloading with a relative path works
<add>process.chdir(fixtures.fixturesDir);
<add>childProcess.exec(
<add> `"${nodeBinary}" ${preloadOption(['./printA.js'])} "${fixtureB}"`,
<add> common.mustCall(function(err, stdout, stderr) {
<add> assert.ifError(err);
<add> assert.strictEqual(stdout, 'A\nB\n');
<add> })
<add>);
<add>if (common.isWindows) {
<add> // https://github.com/nodejs/node/issues/21918
<add> childProcess.exec(
<add> `"${nodeBinary}" ${preloadOption(['.\\printA.js'])} "${fixtureB}"`,
<add> common.mustCall(function(err, stdout, stderr) {
<add> assert.ifError(err);
<add> assert.strictEqual(stdout, 'A\nB\n');
<add> })
<add> );
<add>}
<add>
<ide> // https://github.com/nodejs/node/issues/1691
<ide> process.chdir(fixtures.fixturesDir);
<ide> childProcess.exec(
| 3
|
PHP
|
PHP
|
fix docblocks, remove unnecessary array checks
|
bc115363d9940f10d58cbca2e65bb83027a620eb
|
<ide><path>src/Illuminate/Routing/PendingResourceRegistration.php
<ide> public function names(array $names)
<ide> }
<ide>
<ide> /**
<del> * Set the methods the controller should exclude.
<add> * Set the route name for controller action.
<ide> *
<ide> * @param string $method
<ide> * @param string $name
<ide> * @return \Illuminate\Routing\PendingResourceRegistration
<ide> */
<ide> public function name($method, $name)
<ide> {
<del> if (! isset($this->options['names'])) {
<del> $this->options['names'] = [];
<del> }
<del>
<ide> $this->options['names'][$method] = $name;
<ide>
<ide> return $this;
<ide> public function parameters(array $parameters)
<ide> */
<ide> public function parameter($previous, $new)
<ide> {
<del> if (! isset($this->options['parameters'])) {
<del> $this->options['parameters'] = [];
<del> }
<del>
<ide> $this->options['parameters'][$previous] = $new;
<ide>
<ide> return $this;
| 1
|
Java
|
Java
|
add utf8 problem+json media type constant
|
3dd6069578a2aea3f87bcfeec10d9156e038c4f5
|
<ide><path>spring-web/src/main/java/org/springframework/http/MediaType.java
<ide> public class MediaType extends MimeType implements Serializable {
<ide> * @since 5.0
<ide> */
<ide> public final static String APPLICATION_PROBLEM_JSON_VALUE = "application/problem+json";
<add>
<add> /**
<add> * Public constant media type for {@code application/problem+json}.
<add> * @since 5.0
<add> * @see <a href="https://tools.ietf.org/html/rfc7807#section-6.1">Problem Details for HTTP APIs, 6.1. application/problem+json</a>
<add> */
<add> public final static MediaType APPLICATION_PROBLEM_JSON_UTF8;
<add>
<add> /**
<add> * A String equivalent of {@link MediaType#APPLICATION_PROBLEM_JSON_UTF8}.
<add> * @since 5.0
<add> */
<add> public final static String APPLICATION_PROBLEM_JSON_UTF8_VALUE = APPLICATION_PROBLEM_JSON_VALUE + ";charset=UTF-8";
<ide>
<ide> /**
<ide> * Public constant media type for {@code application/problem+xml}.
<ide> public class MediaType extends MimeType implements Serializable {
<ide> APPLICATION_OCTET_STREAM = valueOf(APPLICATION_OCTET_STREAM_VALUE);
<ide> APPLICATION_PDF = valueOf(APPLICATION_PDF_VALUE);
<ide> APPLICATION_PROBLEM_JSON = valueOf(APPLICATION_PROBLEM_JSON_VALUE);
<add> APPLICATION_PROBLEM_JSON_UTF8 = valueOf(APPLICATION_PROBLEM_JSON_UTF8_VALUE);
<ide> APPLICATION_PROBLEM_XML = valueOf(APPLICATION_PROBLEM_XML_VALUE);
<ide> APPLICATION_RSS_XML = valueOf(APPLICATION_RSS_XML_VALUE);
<ide> APPLICATION_STREAM_JSON = valueOf(APPLICATION_STREAM_JSON_VALUE);
| 1
|
Javascript
|
Javascript
|
add logs in the getviewmanagerconfig
|
3d0e974ed86fb66cb2d8cab7f7c95d6a2e530197
|
<ide><path>Libraries/ReactNative/PaperUIManager.js
<ide> function getViewManagerConfig(viewManagerName: string): any {
<ide> viewManagerConfigs[
<ide> viewManagerName
<ide> ] = NativeUIManager.getConstantsForViewManager(viewManagerName);
<add>
<add> if (viewManagerConfigs[viewManagerName] === undefined) {
<add> console.warn(
<add> 'Error: Unable to find getConstantsForViewManager for viewManager: ' +
<add> viewManagerName +
<add> '.',
<add> );
<add> }
<ide> } catch (e) {
<ide> console.error(
<ide> "NativeUIManager.getConstantsForViewManager('" +
<ide> function getViewManagerConfig(viewManagerName: string): any {
<ide> if (result != null && result.viewConfig != null) {
<ide> getConstants()[viewManagerName] = result.viewConfig;
<ide> lazifyViewManagerConfig(viewManagerName);
<add> } else {
<add> console.warn(
<add> 'Error: Unable to find viewManagerConfigs for viewManager: ' +
<add> viewManagerName +
<add> ' using lazyLoadView.',
<add> );
<ide> }
<ide> }
<ide>
| 1
|
Python
|
Python
|
add versioning system to fast tokenizer files
|
786ced36390e9d1c4c5c32a81d7f00c36913aa2a
|
<ide><path>src/transformers/file_utils.py
<ide> def _resumable_file_manager() -> "io.BufferedWriter":
<ide> return cache_path
<ide>
<ide>
<add>def get_list_of_files(
<add> path_or_repo: Union[str, os.PathLike],
<add> revision: Optional[str] = None,
<add> use_auth_token: Optional[Union[bool, str]] = None,
<add>) -> List[str]:
<add> """
<add> Gets the list of files inside :obj:`path_or_repo`.
<add>
<add> Args:
<add> path_or_repo (:obj:`str` or :obj:`os.PathLike`):
<add> Can be either the id of a repo on huggingface.co or a path to a `directory`.
<add> revision (:obj:`str`, `optional`, defaults to :obj:`"main"`):
<add> The specific model version to use. It can be a branch name, a tag name, or a commit id, since we use a
<add> git-based system for storing models and other artifacts on huggingface.co, so ``revision`` can be any
<add> identifier allowed by git.
<add> use_auth_token (:obj:`str` or `bool`, `optional`):
<add> The token to use as HTTP bearer authorization for remote files. If :obj:`True`, will use the token
<add> generated when running :obj:`transformers-cli login` (stored in :obj:`~/.huggingface`).
<add>
<add> Returns:
<add> :obj:`List[str]`: The list of files available in :obj:`path_or_repo`.
<add> """
<add> path_or_repo = str(path_or_repo)
<add> # If path_or_repo is a folder, we just return what is inside (subdirectories included).
<add> if os.path.isdir(path_or_repo):
<add> list_of_files = []
<add> for path, dir_names, file_names in os.walk(path_or_repo):
<add> list_of_files.extend([os.path.join(path, f) for f in file_names])
<add> return list_of_files
<add>
<add> # Can't grab the files if we are on offline mode.
<add> if is_offline_mode():
<add> return []
<add>
<add> # Otherwise we grab the token and use the model_info method.
<add> if isinstance(use_auth_token, str):
<add> token = use_auth_token
<add> elif use_auth_token is True:
<add> token = HfFolder.get_token()
<add> else:
<add> token = None
<add> model_info = HfApi(endpoint=HUGGINGFACE_CO_RESOLVE_ENDPOINT).model_info(
<add> path_or_repo, revision=revision, token=token
<add> )
<add> return [f.rfilename for f in model_info.siblings]
<add>
<add>
<ide> class cached_property(property):
<ide> """
<ide> Descriptor that mimics @property but caches output in member variable.
<ide><path>src/transformers/tokenization_utils_base.py
<ide> import copy
<ide> import json
<ide> import os
<add>import re
<ide> import warnings
<ide> from collections import OrderedDict, UserDict
<ide> from contextlib import contextmanager
<ide> from dataclasses import dataclass, field
<ide> from typing import TYPE_CHECKING, Any, Dict, List, NamedTuple, Optional, Sequence, Tuple, Union
<ide>
<ide> import numpy as np
<add>from packaging import version
<ide>
<ide> import requests
<ide>
<add>from . import __version__
<ide> from .file_utils import (
<ide> ExplicitEnum,
<ide> PaddingStrategy,
<ide> add_end_docstrings,
<ide> cached_path,
<ide> copy_func,
<add> get_list_of_files,
<ide> hf_bucket_url,
<ide> is_flax_available,
<ide> is_offline_mode,
<ide> class EncodingFast:
<ide>
<ide> # Fast tokenizers (provided by HuggingFace tokenizer's library) can be saved in a single file
<ide> FULL_TOKENIZER_FILE = "tokenizer.json"
<add>_re_tokenizer_file = re.compile(r"tokenizer\.(.*)\.json")
<ide>
<ide>
<ide> class TruncationStrategy(ExplicitEnum):
<ide> def from_pretrained(cls, pretrained_model_name_or_path: Union[str, os.PathLike],
<ide> vocab_files[file_id] = pretrained_model_name_or_path
<ide> else:
<ide> # At this point pretrained_model_name_or_path is either a directory or a model identifier name
<add> fast_tokenizer_file = get_fast_tokenizer_file(
<add> pretrained_model_name_or_path, revision=revision, use_auth_token=use_auth_token
<add> )
<ide> additional_files_names = {
<ide> "added_tokens_file": ADDED_TOKENS_FILE,
<ide> "special_tokens_map_file": SPECIAL_TOKENS_MAP_FILE,
<ide> "tokenizer_config_file": TOKENIZER_CONFIG_FILE,
<del> "tokenizer_file": FULL_TOKENIZER_FILE,
<add> "tokenizer_file": fast_tokenizer_file,
<ide> }
<ide> # Look for the tokenizer files
<ide> for file_id, file_name in {**cls.vocab_files_names, **additional_files_names}.items():
<ide> def prepare_seq2seq_batch(
<ide> return model_inputs
<ide>
<ide>
<add>def get_fast_tokenizer_file(
<add> path_or_repo: Union[str, os.PathLike],
<add> revision: Optional[str] = None,
<add> use_auth_token: Optional[Union[bool, str]] = None,
<add>) -> str:
<add> """
<add> Get the tokenizer file to use for this version of transformers.
<add>
<add> Args:
<add> path_or_repo (:obj:`str` or :obj:`os.PathLike`):
<add> Can be either the id of a repo on huggingface.co or a path to a `directory`.
<add> revision(:obj:`str`, `optional`, defaults to :obj:`"main"`):
<add> The specific model version to use. It can be a branch name, a tag name, or a commit id, since we use a
<add> git-based system for storing models and other artifacts on huggingface.co, so ``revision`` can be any
<add> identifier allowed by git.
<add> use_auth_token (:obj:`str` or `bool`, `optional`):
<add> The token to use as HTTP bearer authorization for remote files. If :obj:`True`, will use the token
<add> generated when running :obj:`transformers-cli login` (stored in :obj:`~/.huggingface`).
<add>
<add> Returns:
<add> :obj:`str`: The tokenizer file to use.
<add> """
<add> # Inspect all files from the repo/folder.
<add> all_files = get_list_of_files(path_or_repo, revision=revision, use_auth_token=use_auth_token)
<add> tokenizer_files_map = {}
<add> for file_name in all_files:
<add> search = _re_tokenizer_file.search(file_name)
<add> if search is not None:
<add> v = search.groups()[0]
<add> tokenizer_files_map[v] = file_name
<add> available_versions = sorted(tokenizer_files_map.keys())
<add>
<add> # Defaults to FULL_TOKENIZER_FILE and then try to look at some newer versions.
<add> tokenizer_file = FULL_TOKENIZER_FILE
<add> transformers_version = version.parse(__version__)
<add> for v in available_versions:
<add> if version.parse(v) <= transformers_version:
<add> tokenizer_file = tokenizer_files_map[v]
<add> else:
<add> # No point going further since the versions are sorted.
<add> break
<add>
<add> return tokenizer_file
<add>
<add>
<ide> # To update the docstring, we need to copy the method, otherwise we change the original docstring.
<ide> PreTrainedTokenizerBase.push_to_hub = copy_func(PreTrainedTokenizerBase.push_to_hub)
<ide> PreTrainedTokenizerBase.push_to_hub.__doc__ = PreTrainedTokenizerBase.push_to_hub.__doc__.format(
<ide><path>src/transformers/training_args.py
<ide> def get_warmup_steps(self, num_training_steps: int):
<ide> Get number of steps used for a linear warmup.
<ide> """
<ide> warmup_steps = (
<del> self.warmup_steps
<del> if self.warmup_steps > 0
<del> else math.ceil(num_training_steps * self.warmup_ratio)
<add> self.warmup_steps if self.warmup_steps > 0 else math.ceil(num_training_steps * self.warmup_ratio)
<ide> )
<ide> return warmup_steps
<ide>
<ide><path>tests/test_tokenization_fast.py
<ide> # limitations under the License.
<ide>
<ide> import concurrent.futures
<add>import json
<add>import os
<ide> import shutil
<ide> import tempfile
<ide> import unittest
<ide>
<del>from transformers import PreTrainedTokenizerFast
<add>from transformers import AutoTokenizer, PreTrainedTokenizerFast
<ide> from transformers.testing_utils import require_tokenizers
<ide>
<ide> from .test_tokenization_common import TokenizerTesterMixin
<ide> def test_training_new_tokenizer_with_special_tokens_change(self):
<ide> self.tmpdirname = tmpdirname_orig
<ide>
<ide>
<add>@require_tokenizers
<add>class TokenizerVersioningTest(unittest.TestCase):
<add> def test_local_versioning(self):
<add> tokenizer = AutoTokenizer.from_pretrained("bert-base-cased")
<add> json_tokenizer = json.loads(tokenizer._tokenizer.to_str())
<add> json_tokenizer["model"]["vocab"]["huggingface"] = len(tokenizer)
<add>
<add> with tempfile.TemporaryDirectory() as tmp_dir:
<add> tokenizer.save_pretrained(tmp_dir)
<add> json.dump(json_tokenizer, open(os.path.join(tmp_dir, "tokenizer.4.0.0.json"), "w"))
<add>
<add> # This should pick the new tokenizer file as the version of Transformers is > 4.0.0
<add> new_tokenizer = AutoTokenizer.from_pretrained(tmp_dir)
<add> self.assertEqual(len(new_tokenizer), len(tokenizer) + 1)
<add> json_tokenizer = json.loads(new_tokenizer._tokenizer.to_str())
<add> self.assertIn("huggingface", json_tokenizer["model"]["vocab"])
<add>
<add> # Will need to be adjusted if we reach v42 and this test is still here.
<add> # Should pick the old tokenizer file as the version of Transformers is < 4.0.0
<add> shutil.move(os.path.join(tmp_dir, "tokenizer.4.0.0.json"), os.path.join(tmp_dir, "tokenizer.42.0.0.json"))
<add> new_tokenizer = AutoTokenizer.from_pretrained(tmp_dir)
<add> self.assertEqual(len(new_tokenizer), len(tokenizer))
<add> json_tokenizer = json.loads(new_tokenizer._tokenizer.to_str())
<add> self.assertNotIn("huggingface", json_tokenizer["model"]["vocab"])
<add>
<add> def test_repo_versioning(self):
<add> # This repo has two tokenizer files, one for v4.0.0 and above with an added token, one for versions lower.
<add> repo = "sgugger/finetuned-bert-mrpc"
<add>
<add> # This should pick the new tokenizer file as the version of Transformers is > 4.0.0
<add> tokenizer = AutoTokenizer.from_pretrained(repo)
<add> self.assertEqual(len(tokenizer), 28997)
<add> json_tokenizer = json.loads(tokenizer._tokenizer.to_str())
<add> self.assertIn("huggingface", json_tokenizer["model"]["vocab"])
<add>
<add> # Testing an older version by monkey-patching the version in the module it's used.
<add> import transformers as old_transformers
<add>
<add> old_transformers.tokenization_utils_base.__version__ = "3.0.0"
<add> old_tokenizer = old_transformers.models.auto.AutoTokenizer.from_pretrained(repo)
<add> self.assertEqual(len(old_tokenizer), 28996)
<add> json_tokenizer = json.loads(old_tokenizer._tokenizer.to_str())
<add> self.assertNotIn("huggingface", json_tokenizer["model"]["vocab"])
<add>
<add>
<ide> @require_tokenizers
<ide> class ReduceMutableBorrowTests(unittest.TestCase):
<ide> def test_async_share_tokenizer(self):
| 4
|
Javascript
|
Javascript
|
add regex check to test-module-loading
|
a4c3e31ac7c1d3092c7cd7fa306ce3f3382dc5fc
|
<ide><path>test/sequential/test-module-loading.js
<ide> console.error('test name clashes');
<ide> const my_path = require('../fixtures/path');
<ide> assert.ok(my_path.path_func instanceof Function);
<ide> // this one does not exist and should throw
<del>assert.throws(function() { require('./utils'); });
<add>assert.throws(function() { require('./utils'); },
<add> /^Error: Cannot find module '.\/utils'$/);
<ide>
<ide> let errorThrown = false;
<ide> try {
<ide> assert.strictEqual(require('../fixtures/registerExt.hello.world').test,
<ide> 'passed');
<ide>
<ide> console.error('load custom file types that return non-strings');
<del>require.extensions['.test'] = function(module, filename) {
<add>require.extensions['.test'] = function(module) {
<ide> module.exports = {
<ide> custom: 'passed'
<ide> };
| 1
|
PHP
|
PHP
|
convert closures to arrow functions
|
50bc15f87a78d5f336b2682195409682c75c9b11
|
<ide><path>src/Illuminate/Foundation/Bootstrap/LoadConfiguration.php
<ide> public function bootstrap(Application $app)
<ide> // Finally, we will set the application's environment based on the configuration
<ide> // values that were loaded. We will pass a callback which will be used to get
<ide> // the environment in a web context where an "--env" switch is not present.
<del> $app->detectEnvironment(function () use ($config) {
<del> return $config->get('app.env', 'production');
<del> });
<add> $app->detectEnvironment(fn () => $config->get('app.env', 'production'));
<ide>
<ide> date_default_timezone_set($config->get('app.timezone', 'UTC'));
<ide>
<ide><path>src/Illuminate/Routing/Route.php
<ide> public function originalParameters()
<ide> */
<ide> public function parametersWithoutNulls()
<ide> {
<del> return array_filter($this->parameters(), function ($p) {
<del> return ! is_null($p);
<del> });
<add> return array_filter($this->parameters(), fn ($p) => ! is_null($p));
<ide> }
<ide>
<ide> /**
<ide> protected function compileParameterNames()
<ide> {
<ide> preg_match_all('/\{(.*?)\}/', $this->getDomain().$this->uri, $matches);
<ide>
<del> return array_map(function ($m) {
<del> return trim($m, '?');
<del> }, $matches[1]);
<add> return array_map(fn ($m) => trim($m, '?'), $matches[1]);
<ide> }
<ide>
<ide> /**
| 2
|
Text
|
Text
|
fix mac os x installation instructions url
|
1f8b679b18984eeecc98d6de79a77cbd405cd56d
|
<ide><path>README.md
<ide> Note that some methods are community contributions and not yet officially suppor
<ide>
<ide> * [Ubuntu 12.04 and 12.10 (officially supported)](http://docs.docker.io/en/latest/installation/ubuntulinux/)
<ide> * [Arch Linux](http://docs.docker.io/en/latest/installation/archlinux/)
<del>* [MacOS X (with Vagrant)](http://docs.docker.io/en/latest/installation/macos/)
<add>* [Mac OS X (with Vagrant)](http://docs.docker.io/en/latest/installation/vagrant/)
<ide> * [Windows (with Vagrant)](http://docs.docker.io/en/latest/installation/windows/)
<ide> * [Amazon EC2 (with Vagrant)](http://docs.docker.io/en/latest/installation/amazon/)
<ide>
| 1
|
Ruby
|
Ruby
|
add test for string#get_make_var
|
866b3cf6a891b4d58969fc4471b7b4cb0cd39ed2
|
<ide><path>Library/Homebrew/test/test_inreplace.rb
<ide> def test_remove_make_vars
<ide> s1.remove_make_var! ["FLAG", "FLAG2"]
<ide> assert_equal "OTHER=def\nOTHER2=def", s1
<ide> end
<add>
<add> def test_get_make_var
<add> s = "CFLAGS = -Wall -O2\nLDFLAGS = -lcrypto -lssl"
<add> s.extend(StringInreplaceExtension)
<add> assert_equal "-Wall -O2", s.get_make_var("CFLAGS")
<add> end
<ide> end
| 1
|
Mixed
|
Java
|
remove ios platform check for running devtools
|
1c290d69c164f34ee00f57f92a203341aa202e26
|
<ide><path>Libraries/JavaScriptAppEngine/Initialization/InitializeJavaScriptAppEngine.js
<ide> function setUpCollections(): void {
<ide> function setUpDevTools(): void {
<ide> if (__DEV__) {
<ide> // not when debugging in chrome
<del> if (!window.document && require('Platform').OS === 'ios') {
<add> if (!window.document) {
<ide> const setupDevtools = require('setupDevtools');
<ide> setupDevtools();
<ide> }
<ide><path>ReactAndroid/src/androidTest/java/com/facebook/react/testing/FakeWebSocketModule.java
<add>/**
<add> * Copyright (c) 2014-present, Facebook, Inc.
<add> * All rights reserved.
<add> * This source code is licensed under the BSD-style license found in the
<add> * LICENSE file in the root directory of this source tree. An additional grant
<add> * of patent rights can be found in the PATENTS file in the same directory.
<add> */
<add>
<add>package com.facebook.react.testing;
<add>
<add>import javax.annotation.Nullable;
<add>
<add>import com.facebook.react.bridge.Arguments;
<add>import com.facebook.react.bridge.BaseJavaModule;
<add>import com.facebook.react.bridge.ReactMethod;
<add>import com.facebook.react.bridge.ReadableArray;
<add>import com.facebook.react.bridge.ReadableMap;
<add>import com.facebook.react.bridge.WritableMap;
<add>
<add>/**
<add> * Dummy implementation of storage module, used for testing
<add> */
<add>public final class FakeWebSocketModule extends BaseJavaModule {
<add>
<add> private static WritableMap errorMessage;
<add> static {
<add> errorMessage = Arguments.createMap();
<add> errorMessage.putString("message", "Fake Fake Web Socke tModule");
<add> }
<add>
<add> @Override
<add> public String getName() {
<add> return "WebSocketModule";
<add> }
<add>
<add> @Override
<add> public boolean canOverrideExistingModule() {
<add> return true;
<add> }
<add>
<add> @ReactMethod
<add> public void connect(
<add> final String url,
<add> @Nullable final ReadableArray protocols,
<add> @Nullable final ReadableMap headers,
<add> final int id) {
<add> }
<add>
<add> @ReactMethod
<add> public void close(int code, String reason, int id) {
<add> }
<add>
<add> @ReactMethod
<add> public void send(String message, int id) {
<add> }
<add>
<add> @ReactMethod
<add> public void sendBinary(String base64String, int id) {
<add> }
<add>}
<ide><path>ReactAndroid/src/androidTest/java/com/facebook/react/testing/ReactInstanceSpecForTest.java
<ide> package com.facebook.react.testing;
<ide>
<ide> import java.util.ArrayList;
<add>import java.util.Arrays;
<ide> import java.util.List;
<ide>
<ide> import android.annotation.SuppressLint;
<ide> @SuppressLint("JavatestsIncorrectFolder")
<ide> public class ReactInstanceSpecForTest {
<ide>
<del> private final List<NativeModule> mNativeModules = new ArrayList<>();
<add> private final List<NativeModule> mNativeModules =
<add> new ArrayList<NativeModule>(Arrays.asList(new FakeWebSocketModule()));
<ide> private final List<Class<? extends JavaScriptModule>> mJSModuleSpecs = new ArrayList<>();
<ide> private final List<ViewManager> mViewManagers = new ArrayList<>();
<ide> private ReactPackage mReactPackage = null;
<ide><path>ReactAndroid/src/androidTest/java/com/facebook/react/tests/CatalystNativeJSToJavaParametersTestCase.java
<ide> import com.facebook.react.bridge.WritableMap;
<ide> import com.facebook.react.bridge.WritableNativeMap;
<ide> import com.facebook.react.modules.systeminfo.AndroidInfoModule;
<add>import com.facebook.react.testing.FakeWebSocketModule;
<ide> import com.facebook.react.testing.ReactIntegrationTestCase;
<ide> import com.facebook.react.testing.ReactTestHelper;
<ide> import com.facebook.react.uimanager.UIImplementation;
<ide> import com.facebook.react.uimanager.UIManagerModule;
<ide> import com.facebook.react.uimanager.ViewManager;
<ide> import com.facebook.react.views.view.ReactViewManager;
<ide>
<del>import org.junit.Ignore;
<del>
<ide> /**
<ide> * Integration test to verify passing various types of parameters from JS to Java works
<ide> */
<ide> private interface TestJSToJavaParametersModule extends JavaScriptModule {
<ide> @Override
<ide> protected void setUp() throws Exception {
<ide> super.setUp();
<del>
<add>
<ide> List<ViewManager> viewManagers = Arrays.<ViewManager>asList(
<ide> new ReactViewManager());
<ide> final UIManagerModule mUIManager = new UIManagerModule(
<ide> public void run() {
<ide> mCatalystInstance = ReactTestHelper.catalystInstanceBuilder(this)
<ide> .addNativeModule(mRecordingTestModule)
<ide> .addNativeModule(new AndroidInfoModule())
<add> .addNativeModule(new FakeWebSocketModule())
<ide> .addNativeModule(mUIManager)
<ide> .addJSModule(TestJSToJavaParametersModule.class)
<ide> .build();
<ide><path>ReactAndroid/src/androidTest/java/com/facebook/react/tests/CatalystNativeJavaToJSArgumentsTestCase.java
<ide> import com.facebook.react.bridge.WritableNativeMap;
<ide> import com.facebook.react.bridge.UiThreadUtil;
<ide> import com.facebook.react.testing.AssertModule;
<add>import com.facebook.react.testing.FakeWebSocketModule;
<ide> import com.facebook.react.testing.ReactIntegrationTestCase;
<ide> import com.facebook.react.testing.ReactTestHelper;
<ide> import com.facebook.react.uimanager.UIImplementation;
<ide> public void run() {
<ide>
<ide> mInstance = ReactTestHelper.catalystInstanceBuilder(this)
<ide> .addNativeModule(mAssertModule)
<add> .addNativeModule(new FakeWebSocketModule())
<ide> .addJSModule(TestJavaToJSArgumentsModule.class)
<ide> .addNativeModule(mUIManager)
<ide> .build();
<ide><path>ReactAndroid/src/androidTest/java/com/facebook/react/tests/InitialPropsTestCase.java
<ide> import android.test.ActivityInstrumentationTestCase2;
<ide>
<ide> import com.facebook.react.bridge.BaseJavaModule;
<add>import com.facebook.react.testing.FakeWebSocketModule;
<ide> import com.facebook.react.testing.ReactInstanceSpecForTest;
<ide> import com.facebook.react.bridge.ReactMethod;
<ide> import com.facebook.react.bridge.ReadableArray;
<ide> public void testInitialProps() throws Throwable {
<ide> @Override
<ide> public void run() {
<ide> ReactInstanceSpecForTest catalystInstanceSpec = new ReactInstanceSpecForTest();
<add> catalystInstanceSpec.addNativeModule(new FakeWebSocketModule());
<ide> catalystInstanceSpec.addNativeModule(mRecordingModule);
<ide> Bundle props = new Bundle();
<ide> props.putString("key1", "string");
<ide><path>ReactAndroid/src/androidTest/java/com/facebook/react/tests/JSLocaleTest.java
<ide> import java.util.Arrays;
<ide> import java.util.List;
<ide>
<add>import com.facebook.react.testing.FakeWebSocketModule;
<ide> import com.facebook.react.testing.ReactIntegrationTestCase;
<ide> import com.facebook.react.testing.ReactTestHelper;
<ide> import com.facebook.react.testing.StringRecordingModule;
<ide> public void run() {
<ide> mInstance = ReactTestHelper.catalystInstanceBuilder(this)
<ide> .addNativeModule(mStringRecordingModule)
<ide> .addNativeModule(mUIManager)
<add> .addNativeModule(new FakeWebSocketModule())
<ide> .addJSModule(TestJSLocaleModule.class)
<ide> .build();
<del>
<ide> }
<ide>
<ide> public void testToUpper() {
<ide> public void testToLower() {
<ide> assertEquals("γαζίες καὶ μυρτιὲς δὲν θὰ βρῶ πιὰ στὸ χρυσαφὶ ξέφωτο", answers[3]);
<ide> assertEquals("chinese: 幓 厏吪吙 鈊釿閍 碞碠粻 曮禷", answers[4]);
<ide> }
<del>
<del>
<ide> }
<ide><path>ReactAndroid/src/androidTest/java/com/facebook/react/tests/ProgressBarTestCase.java
<ide> import com.facebook.react.uimanager.ViewManager;
<ide> import com.facebook.react.views.progressbar.ReactProgressBarViewManager;
<ide> import com.facebook.react.views.view.ReactViewManager;
<add>import com.facebook.react.testing.FakeWebSocketModule;
<ide> import com.facebook.react.testing.ReactIntegrationTestCase;
<ide> import com.facebook.react.testing.ReactTestHelper;
<ide>
<ide> public void run() {
<ide> mInstance = ReactTestHelper.catalystInstanceBuilder(this)
<ide> .addNativeModule(mUIManager)
<ide> .addNativeModule(new AndroidInfoModule())
<add> .addNativeModule(new FakeWebSocketModule())
<ide> .addJSModule(ProgressBarTestModule.class)
<ide> .build();
<ide>
<ide><path>ReactAndroid/src/androidTest/java/com/facebook/react/tests/ViewRenderingTestCase.java
<ide> import com.facebook.react.uimanager.ViewManager;
<ide> import com.facebook.react.views.view.ReactViewGroup;
<ide> import com.facebook.react.views.view.ReactViewManager;
<add>import com.facebook.react.testing.FakeWebSocketModule;
<ide> import com.facebook.react.testing.ReactIntegrationTestCase;
<ide> import com.facebook.react.testing.ReactTestHelper;
<ide>
<ide> public void run() {
<ide> mCatalystInstance = ReactTestHelper.catalystInstanceBuilder(this)
<ide> .addNativeModule(uiManager)
<ide> .addNativeModule(new AndroidInfoModule())
<add> .addNativeModule(new FakeWebSocketModule())
<ide> .addJSModule(ViewRenderingTestModule.class)
<ide> .build();
<ide>
| 9
|
Python
|
Python
|
accept callable as message in assert_
|
b0dd6901d54e687571e44c4fa1d9c7db0d00e299
|
<ide><path>numpy/core/tests/test_umath.py
<ide> def test_minmax_blocked(self):
<ide> for i in range(inp.size):
<ide> inp[:] = np.arange(inp.size, dtype=dt)
<ide> inp[i] = np.nan
<del> self.assertTrue(np.isnan(inp.max()),
<del> msg=repr(inp) + '\n' + msg)
<del> self.assertTrue(np.isnan(inp.min()),
<del> msg=repr(inp) + '\n' + msg)
<add> emsg = lambda: '%r\n%s' % (inp, msg)
<add> assert_(np.isnan(inp.max()), msg=emsg)
<add> assert_(np.isnan(inp.min()), msg=emsg)
<ide>
<ide> inp[i] = 1e10
<ide> assert_equal(inp.max(), 1e10, err_msg=msg)
<ide><path>numpy/testing/utils.py
<ide> def assert_(val, msg='') :
<ide> """
<ide> Assert that works in release mode.
<add> Accepts callable msg to allow deferring evaluation until failure.
<ide>
<ide> The Python built-in ``assert`` does not work when executing code in
<ide> optimized mode (the ``-O`` flag) - no byte-code is generated for it.
<ide> def assert_(val, msg='') :
<ide>
<ide> """
<ide> if not val :
<del> raise AssertionError(msg)
<add> try:
<add> smsg = msg()
<add> except TypeError:
<add> smsg = msg
<add> raise AssertionError(smsg)
<ide>
<ide> def gisnan(x):
<ide> """like isnan, but always raise an error if type not supported instead of
| 2
|
Java
|
Java
|
fix jsonobjectdecoder with '[' starting chunk
|
4021d239ab15dfd119d248c9e830ed2f2f935985
|
<ide><path>spring-web/src/main/java/org/springframework/http/codec/json/JsonObjectDecoder.java
<ide> else if (Character.isWhitespace(c)) {
<ide> }
<ide> }
<ide>
<del> if (this.input.readableBytes() == 0) {
<del> this.index = 0;
<del> }
<ide> return Flux.fromIterable(chunks);
<ide> }
<ide>
<ide><path>spring-web/src/test/java/org/springframework/http/codec/json/JsonObjectDecoderTests.java
<ide> public void decodeMultipleChunksToArray() throws InterruptedException {
<ide> .expectNext("{\"foo\": \"baz\"}")
<ide> .expectComplete()
<ide> .verify();
<add>
<add> // SPR-15013
<add> source = Flux.just(stringBuffer("["), stringBuffer("{\"id\":1,\"name\":\"Robert\"}"),
<add> stringBuffer(","), stringBuffer("{\"id\":2,\"name\":\"Raide\"}"),
<add> stringBuffer(","), stringBuffer("{\"id\":3,\"name\":\"Ford\"}"),
<add> stringBuffer("]"));
<add> output = decoder.decode(source, null, null, Collections.emptyMap()).map(JsonObjectDecoderTests::toString);
<add> StepVerifier.create(output)
<add> .expectNext("{\"id\":1,\"name\":\"Robert\"}")
<add> .expectNext("{\"id\":2,\"name\":\"Raide\"}")
<add> .expectNext("{\"id\":3,\"name\":\"Ford\"}")
<add> .expectComplete()
<add> .verify();
<ide> }
<ide>
<ide>
| 2
|
Text
|
Text
|
add cigtm to `glossary.md`
|
815e74b80d0f360ba89fa4fa9c4938580f9b9ea0
|
<ide><path>glossary.md
<ide> You may also need to check <https://chromium.googlesource.com/chromiumos/docs/+/HEAD/glossary.md>.
<ide>
<add>* CITGM: "The Canary in the Goldmine". CITGM is a simple tool for pulling down
<add> an arbitrary module from npm and testing it using a specific version of the
<add> node runtime. The Node.js project uses CITGM to smoke test our releases and
<add> controversial changes. See more details on the [CITGM repository](https://github.com/nodejs/citgm).
<ide> * LGTM: "Looks good to me", commonly used to approve a code review.
<ide> * PTAL: Please take a look.
<ide> * RSLGTM: "Rubber-stamp looks good to me". The reviewer approving without doing
| 1
|
PHP
|
PHP
|
fix uuid warning for invalid ones
|
12cf0e61fbd776cdc883d4635641e150ea8c2be1
|
<ide><path>src/Database/Type/BinaryUuidType.php
<ide> class BinaryUuidType extends BaseType
<ide> *
<ide> * @param mixed $value The value to convert.
<ide> * @param \Cake\Database\DriverInterface $driver The driver instance to convert with.
<del> * @return string|resource
<add> * @return string|resource|null
<ide> */
<ide> public function toDatabase($value, DriverInterface $driver)
<ide> {
<del> if (is_string($value)) {
<del> return $this->convertStringToBinaryUuid($value);
<add> if (!is_string($value)) {
<add> return $value;
<ide> }
<ide>
<del> return $value;
<add> $length = strlen($value);
<add> if ($length !== 36 && $length !== 32) {
<add> return null;
<add> }
<add>
<add> return $this->convertStringToBinaryUuid($value);
<ide> }
<ide>
<ide> /**
<ide> protected function convertBinaryUuidToString($binary): string
<ide> }
<ide>
<ide> /**
<del> * Converts a string uuid to a binary representation
<add> * Converts a string UUID (36 or 32 char) to a binary representation.
<ide> *
<ide> * @param string $string The value to convert.
<ide> * @return string Converted value.
<ide><path>tests/TestCase/Database/Type/BinaryUuidTypeTest.php
<ide> public function testToDatabase()
<ide> $this->assertSame(str_replace('-', '', $value), unpack('H*', $result)[1]);
<ide> }
<ide>
<add> /**
<add> * Test converting to database format fails
<add> *
<add> * @return void
<add> */
<add> public function testToDatabaseInvalid()
<add> {
<add> $value = 'mUMPWUxCpaCi685A9fEwJZ';
<add> $result = $this->type->toDatabase($value, $this->driver);
<add> $this->assertNull($result);
<add> }
<add>
<ide> /**
<ide> * Test that the PDO binding type is correct.
<ide> *
| 2
|
Ruby
|
Ruby
|
remove form feed properly
|
4401ee08191fa84b339ae4af33719f71c6a6bd17
|
<ide><path>Library/Contributions/cmd/brew-test-bot.rb
<ide> def run
<ide> failure = testcase.add_element 'failure' if step.failed?
<ide> if step.has_output?
<ide> # Remove invalid XML CData characters from step output.
<del> output = REXML::CData.new step.output.gsub(/\000\00c\e/, '')
<add> output = REXML::CData.new step.output.delete(/\000\f\e/)
<ide> if step.passed?
<ide> system_out = testcase.add_element 'system-out'
<ide> system_out.text = output
| 1
|
Javascript
|
Javascript
|
fix spelling of `dependon`
|
093a9bed160d3920e60fd773e441e24d7e24bffe
|
<ide><path>lib/optimize/SplitChunksPlugin.js
<ide> module.exports = class SplitChunksPlugin {
<ide> "SplitChunksPlugin\n" +
<ide> `Cache group "${cacheGroup.key}" conflicts with existing chunk.\n` +
<ide> `Both have the same name "${name}" and existing chunk is not a parent of the selected modules.\n` +
<del> "Use a different name for the cache group or make sure that the existing chunk is a parent (e. g. via dependsOn).\n" +
<add> "Use a different name for the cache group or make sure that the existing chunk is a parent (e. g. via dependOn).\n" +
<ide> 'HINT: You can omit "name" to automatically create a name.\n' +
<ide> "BREAKING CHANGE: webpack < 5 used to allow to use an entrypoint as splitChunk. " +
<ide> "This is no longer allowed when the entrypoint is not a parent of the selected modules.\n" +
| 1
|
Python
|
Python
|
add documentation for multi-label classification
|
4176bc161c359d0bcda0a3967e8ea711ac35642d
|
<ide><path>src/transformers/file_utils.py
<ide> def _prepare_output_docstrings(output_type, config_class):
<ide> """
<ide>
<ide> PT_SEQUENCE_CLASSIFICATION_SAMPLE = r"""
<del> Example::
<add> Example of single-label classification::
<ide>
<ide> >>> from transformers import {processor_class}, {model_class}
<ide> >>> import torch
<ide> def _prepare_output_docstrings(output_type, config_class):
<ide> >>> outputs = model(**inputs, labels=labels)
<ide> >>> loss = outputs.loss
<ide> >>> logits = outputs.logits
<add>
<add> Example of multi-label classification::
<add>
<add> >>> from transformers import {processor_class}, {model_class}
<add> >>> import torch
<add>
<add> >>> tokenizer = {processor_class}.from_pretrained('{checkpoint}')
<add> >>> model = {model_class}.from_pretrained('{checkpoint}', problem_type="multi_label_classification")
<add>
<add> >>> inputs = tokenizer("Hello, my dog is cute", return_tensors="pt")
<add> >>> labels = torch.tensor([[1, 1]], dtype=torch.float) # need dtype=float for BCEWithLogitsLoss
<add> >>> outputs = model(**inputs, labels=labels)
<add> >>> loss = outputs.loss
<add> >>> logits = outputs.logits
<ide> """
<ide>
<add>
<ide> PT_MASKED_LM_SAMPLE = r"""
<ide> Example::
<ide>
| 1
|
Javascript
|
Javascript
|
add additional pageprops check
|
ce56b601665a972f91ec5e6bf7ebd918bba2dcc0
|
<ide><path>packages/next/client/index.js
<ide> if (
<ide> !(
<ide> page === '/_error' &&
<ide> hydrateProps &&
<add> hydrateProps.pageProps &&
<ide> hydrateProps.pageProps.statusCode === '404'
<ide> )
<ide> ) {
<ide><path>test/integration/no-page-props/pages/_app.js
<add>function App({ Component, pageProps }) {
<add> return <Component {...pageProps} />
<add>}
<add>
<add>if (typeof window !== 'undefined') {
<add> window.uncaughtErrors = []
<add> window.addEventListener('error', (err) => {
<add> window.uncaughtErrors.push(err)
<add> })
<add> window.addEventListener('unhandledrejection', (err) => {
<add> window.uncaughtErrors.push(err)
<add> })
<add>}
<add>
<add>App.getInitialProps = async ({ Component, ctx }) => {
<add> const props = {}
<add>
<add> if (Component.getInitialProps) {
<add> props.initialProps = await Component.getInitialProps(ctx)
<add> }
<add> return props
<add>}
<add>
<add>export default App
<ide><path>test/integration/no-page-props/pages/gsp.js
<add>export default function Gsp() {
<add> return <p id="gsp">getStaticProps</p>
<add>}
<add>
<add>export const getStaticProps = () => {
<add> return {
<add> props: {
<add> hello: 'world',
<add> },
<add> }
<add>}
<ide><path>test/integration/no-page-props/pages/gssp.js
<add>export default function Gssp() {
<add> return <p id="gssp">getServerSideProps</p>
<add>}
<add>
<add>export const getServerSideProps = () => {
<add> return {
<add> props: {
<add> hello: 'world',
<add> },
<add> }
<add>}
<ide><path>test/integration/no-page-props/pages/index.js
<add>import Link from 'next/link'
<add>
<add>export default function Index() {
<add> return (
<add> <>
<add> <p id="index">index</p>
<add> <Link href="/gsp">
<add> <a id="to-gsp">to gsp</a>
<add> </Link>
<add> <br />
<add> <Link href="/gssp">
<add> <a id="to-gssp">to gssp</a>
<add> </Link>
<add> <br />
<add> <Link href="/non-existent">
<add> <a id="to-404">to non-existent</a>
<add> </Link>
<add> <br />
<add> </>
<add> )
<add>}
<ide><path>test/integration/no-page-props/test/index.test.js
<add>/* eslint-env jest */
<add>
<add>import { join } from 'path'
<add>import webdriver from 'next-webdriver'
<add>import {
<add> nextBuild,
<add> nextStart,
<add> findPort,
<add> killApp,
<add> launchApp,
<add>} from 'next-test-utils'
<add>
<add>jest.setTimeout(1000 * 60 * 1)
<add>const appDir = join(__dirname, '..')
<add>let app
<add>let appPort
<add>
<add>const runTests = () => {
<add> it('should load auto-export page correctly', async () => {
<add> const browser = await webdriver(appPort, '/')
<add> expect(await browser.elementByCss('#index').text()).toBe('index')
<add> expect(await browser.eval('window.uncaughtErrors')).toEqual([])
<add> })
<add>
<add> it('should load getStaticProps page correctly', async () => {
<add> const browser = await webdriver(appPort, '/gsp')
<add> expect(await browser.elementByCss('#gsp').text()).toBe('getStaticProps')
<add> expect(await browser.eval('window.uncaughtErrors')).toEqual([])
<add> })
<add>
<add> it('should load getServerSideProps page correctly', async () => {
<add> const browser = await webdriver(appPort, '/gssp')
<add> expect(await browser.elementByCss('#gssp').text()).toBe(
<add> 'getServerSideProps'
<add> )
<add> expect(await browser.eval('window.uncaughtErrors')).toEqual([])
<add> })
<add>
<add> it('should load 404 page correctly', async () => {
<add> const browser = await webdriver(appPort, '/non-existent')
<add> expect(await browser.elementByCss('h2').text()).toBe(
<add> 'An unexpected error has occurred.'
<add> )
<add> expect(await browser.eval('window.uncaughtErrors')).toEqual([])
<add> })
<add>
<add> it('should navigate between pages correctly', async () => {
<add> const browser = await webdriver(appPort, '/')
<add>
<add> await browser.eval('window.beforeNav = "hi"')
<add> await browser.elementByCss('#to-gsp').click()
<add> await browser.waitForElementByCss('#gsp')
<add>
<add> expect(await browser.elementByCss('#gsp').text()).toBe('getStaticProps')
<add> expect(await browser.eval('window.beforeNav')).toBe('hi')
<add>
<add> await browser.back()
<add> await browser.waitForElementByCss('#index')
<add> expect(await browser.eval('window.beforeNav')).toBe('hi')
<add>
<add> await browser.elementByCss('#to-gssp').click()
<add> await browser.waitForElementByCss('#gssp')
<add>
<add> expect(await browser.elementByCss('#gssp').text()).toBe(
<add> 'getServerSideProps'
<add> )
<add> expect(await browser.eval('window.beforeNav')).toBe('hi')
<add>
<add> await browser.back()
<add> await browser.waitForElementByCss('#index')
<add> expect(await browser.eval('window.beforeNav')).toBe('hi')
<add>
<add> await browser.elementByCss('#to-404').click()
<add> await browser.waitForElementByCss('h2')
<add> expect(await browser.eval('window.beforeNav')).toBe(null)
<add> expect(await browser.elementByCss('h2').text()).toBe(
<add> 'An unexpected error has occurred.'
<add> )
<add> expect(await browser.eval('window.uncaughtErrors')).toEqual([])
<add> })
<add>}
<add>
<add>describe('Error no pageProps', () => {
<add> describe('dev mode', () => {
<add> beforeAll(async () => {
<add> appPort = await findPort()
<add> app = await launchApp(appDir, appPort)
<add> })
<add> afterAll(() => killApp(app))
<add>
<add> runTests()
<add> })
<add>
<add> describe('production mode', () => {
<add> beforeAll(async () => {
<add> await nextBuild(appDir)
<add> appPort = await findPort()
<add> app = await nextStart(appDir, appPort)
<add> })
<add> afterAll(() => killApp(app))
<add>
<add> runTests()
<add> })
<add>})
| 6
|
Ruby
|
Ruby
|
prefer file.extname to regexp
|
ce367e711be8e4f2a08357705dafa5bc375da99b
|
<ide><path>Library/Homebrew/formulary.rb
<ide> class FromPathLoader < FormulaLoader
<ide> def initialize path
<ide> # require allows filenames to drop the .rb extension, but everything else
<ide> # in our codebase will require an exact and fullpath.
<del> path = "#{path}.rb" unless path =~ /\.rb$/
<add> path = "#{path}.rb" unless File.extname(path) == ".rb"
<ide> path = Pathname.new(path).expand_path
<ide> super path.stem, path
<ide> end
<ide> def self.factory ref
<ide> elsif name_or_path.include? "/"
<ide> # If name was a path or mapped to a cached formula
<ide> f = FromPathLoader.new(name_or_path)
<del> elsif name_or_path =~ /\.rb$/
<add> elsif File.extname(name_or_path) == ".rb"
<ide> f = FromPathLoader.new(File.expand_path(name_or_path))
<ide> else
<ide> f = StandardLoader.new(name_or_path)
| 1
|
Go
|
Go
|
catch sigwinch client
|
deb9963e6e5871d53ab1d75c90bbf2da53ffcb36
|
<ide><path>commands.go
<ide> import (
<ide> "net/http/httputil"
<ide> "net/url"
<ide> "os"
<add> "os/signal"
<ide> "path/filepath"
<ide> "reflect"
<ide> "strconv"
<ide> "strings"
<add> "syscall"
<ide> "text/tabwriter"
<ide> "time"
<ide> "unicode"
<ide> var (
<ide> func ParseCommands(args ...string) error {
<ide> cli := NewDockerCli("0.0.0.0", 4243)
<ide>
<add> c := make(chan os.Signal, 1)
<add> signal.Notify(c, syscall.SIGWINCH)
<add> go func() {
<add> for sig := range c {
<add> if sig == syscall.SIGWINCH {
<add> _, _, err := cli.call("GET", "/auth", nil)
<add> if err != nil {
<add> utils.Debugf("Error resize: %s", err)
<add> }
<add> }
<add> }
<add> }()
<add>
<ide> if len(args) > 0 {
<ide> methodName := "Cmd" + strings.ToUpper(args[0][:1]) + strings.ToLower(args[0][1:])
<ide> method, exists := reflect.TypeOf(cli).MethodByName(methodName)
<ide> func NewDockerCli(host string, port int) *DockerCli {
<ide> }
<ide>
<ide> type DockerCli struct {
<del> host string
<del> port int
<add> host string
<add> port int
<ide> }
| 1
|
Javascript
|
Javascript
|
allow an index argument
|
468dd028e0bd0dad93f2edba8e14352f0706f4ed
|
<ide><path>moment.js
<ide> return;
<ide> }
<ide>
<del> moment[field] = function (format) {
<del> var i, m, str,
<del> method = moment.fn._lang[field] || Language.prototype[field],
<del> results = [];
<del>
<del> for (i = 0; i < count; i++) {
<del> m = moment().utc().set(setter, i);
<del> str = method.call(moment.fn._lang, m, format || '');
<del> results.push(str);
<add> moment[field] = function (format, index) {
<add> var i,
<add> method = moment.fn._lang[field],
<add> results = [],
<add> getter = function (i) {
<add> var m = moment().utc().set(setter, i);
<add> return method.call(moment.fn._lang, m, format || '');
<add> };
<add>
<add> index = (typeof format === 'number') ? format : index;
<add>
<add> if (index) {
<add> return getter(index);
<add> }
<add> else {
<add> for (i = 0; i < count; i++) {
<add> results.push(getter(i));
<add> }
<add> return results;
<ide> }
<del>
<del> return results;
<ide> };
<ide> }
<ide>
<ide><path>test/moment/listers.js
<ide> exports.listers = {
<ide> test.done();
<ide> },
<ide>
<add> "index" : function (test) {
<add> test.expect(5);
<add> test.equal(moment.months(2), "March");
<add> test.equal(moment.monthsShort(2), "Mar");
<add> test.equal(moment.weekdays(2), "Tuesday");
<add> test.equal(moment.weekdaysShort(2), "Tue");
<add> test.equal(moment.weekdaysMin(2), "Tu");
<add> test.done();
<add> },
<add>
<ide> "localized" : function (test) {
<ide> var months = "one_two_three_four_five_six_seven_eight_nine_ten_eleven_twelve".split('_'),
<ide> monthsShort = "on_tw_th_fo_fi_si_se_ei_ni_te_el_tw".split("_"),
<ide> exports.listers = {
<ide> weekdaysMin: weekdaysMin
<ide> });
<ide>
<del> test.expect(5);
<add> test.expect(10);
<ide> test.deepEqual(moment.months(), months);
<ide> test.deepEqual(moment.monthsShort(), monthsShort);
<ide> test.deepEqual(moment.weekdays(), weekdays);
<ide> test.deepEqual(moment.weekdaysShort(), weekdaysShort);
<ide> test.deepEqual(moment.weekdaysMin(), weekdaysMin);
<add>
<add> test.equal(moment.months(2), "three");
<add> test.equal(moment.monthsShort(2), "th");
<add> test.equal(moment.weekdays(2), "three");
<add> test.equal(moment.weekdaysShort(2), "th");
<add> test.equal(moment.weekdaysMin(2), "3");
<add>
<ide> test.done();
<ide> },
<ide>
<ide> exports.listers = {
<ide> }
<ide> });
<ide>
<del> test.expect(3);
<add> test.expect(5);
<ide> test.deepEqual(moment.monthsShort(), monthsShort);
<ide> test.deepEqual(moment.monthsShort('MMM'), monthsShort);
<ide> test.deepEqual(moment.monthsShort('-MMM-'), monthsShortWeird);
<add>
<add> test.deepEqual(moment.monthsShort('MMM', 2), 'three');
<add> test.deepEqual(moment.monthsShort('-MMM-', 2), 'threesy');
<add>
<ide> test.done();
<ide> }
<ide> };
| 2
|
Python
|
Python
|
remove unnecessary helper function
|
949315787a51eb86db0f8a19b4c257a0ef739f32
|
<ide><path>numpy/fft/fftpack.py
<ide> __all__ = ['fft', 'ifft', 'rfft', 'irfft', 'hfft', 'ihfft', 'rfftn',
<ide> 'irfftn', 'rfft2', 'irfft2', 'fft2', 'ifft2', 'fftn', 'ifftn']
<ide>
<del>from numpy.core import asarray, zeros, swapaxes, shape, conjugate, \
<del> take
<add>import numpy as np
<add>from numpy.core import asarray, zeros, swapaxes, shape, conjugate, take
<ide> from . import fftpack_lite as fftpack
<ide>
<ide> _fft_cache = {}
<ide> _real_fft_cache = {}
<ide>
<ide>
<del>def _asarray_copy(*args, **kwargs):
<del> return asarray(*args, **kwargs).copy()
<del>
<del>
<ide> def _raw_fft(a, n=None, axis=-1, init_function=fftpack.cffti,
<ide> work_function=fftpack.cfftf, fft_cache=_fft_cache):
<ide> a = asarray(a)
<ide> def ifft(a, n=None, axis=-1):
<ide> >>> plt.show()
<ide>
<ide> """
<del> a = _asarray_copy(a, dtype=complex)
<add> a = np.array(a, dtype=complex)
<ide> if n is None:
<ide> n = shape(a)[axis]
<ide> return _raw_fft(a, n, axis, fftpack.cffti, fftpack.cfftb, _fft_cache) / n
<ide> def rfft(a, n=None, axis=-1):
<ide> exploited to compute only the non-negative frequency terms.
<ide>
<ide> """
<del> a = _asarray_copy(a, dtype=float)
<add> a = np.array(a, dtype=float)
<ide> return _raw_fft(a, n, axis, fftpack.rffti, fftpack.rfftf, _real_fft_cache)
<ide>
<ide>
<ide> def irfft(a, n=None, axis=-1):
<ide> specified, and the output array is purely real.
<ide>
<ide> """
<del> a = _asarray_copy(a, dtype=complex)
<add> a = np.array(a, dtype=complex)
<ide> if n is None:
<ide> n = (shape(a)[axis] - 1) * 2
<ide> return _raw_fft(a, n, axis, fftpack.rffti, fftpack.rfftb,
<ide> def hfft(a, n=None, axis=-1):
<ide> [ 2., -2.]])
<ide>
<ide> """
<del> a = _asarray_copy(a, dtype=complex)
<add> a = np.array(a, dtype=complex)
<ide> if n is None:
<ide> n = (shape(a)[axis] - 1) * 2
<ide> return irfft(conjugate(a), n, axis) * n
<ide> def ihfft(a, n=None, axis=-1):
<ide> array([ 1.-0.j, 2.-0.j, 3.-0.j, 4.-0.j])
<ide>
<ide> """
<del> a = _asarray_copy(a, dtype=float)
<add> a = np.array(a, dtype=float)
<ide> if n is None:
<ide> n = shape(a)[axis]
<ide> return conjugate(rfft(a, n, axis))/n
<ide> def rfftn(a, s=None, axes=None):
<ide> [ 0.+0.j, 0.+0.j]]])
<ide>
<ide> """
<del> a = _asarray_copy(a, dtype=float)
<add> a = np.array(a, dtype=float)
<ide> s, axes = _cook_nd_args(a, s, axes)
<ide> a = rfft(a, s[-1], axes[-1])
<ide> for ii in range(len(axes)-1):
<ide> def irfftn(a, s=None, axes=None):
<ide> [ 1., 1.]]])
<ide>
<ide> """
<del> a = _asarray_copy(a, dtype=complex)
<add> a = np.array(a, dtype=complex)
<ide> s, axes = _cook_nd_args(a, s, axes, invreal=1)
<ide> for ii in range(len(axes)-1):
<ide> a = ifft(a, s[ii], axes[ii])
| 1
|
Python
|
Python
|
rearrange methods per style guildelines
|
31650de24c545812d8f8542a205a257cbddea277
|
<ide><path>libcloud/common/gandi_live.py
<ide> def success(self):
<ide>
<ide> return True
<ide>
<del> # Errors are not described at all in Gandi's official documentation.
<del> # It appears when an error arises, a JSON object is returned along with
<del> # an HTTP 4xx class code. The object is structured as:
<del> # {
<del> # code: <code>,
<del> # object: <object>,
<del> # message: <message>,
<del> # cause: <cause>,
<del> # errors: [
<del> # {
<del> # location: <error-location>,
<del> # name: <error-name>,
<del> # description: <error-description>
<del> # }
<del> # ]
<del> # }
<del> # where
<del> # <code> is a number equal to the HTTP response status code
<del> # <object> is a string with some internal name for the status code
<del> # <message> is a string detailing what the problem is
<del> # <cause> is a string that comes from a set of succinct problem summaries
<del> # errors is optional; if present:
<del> # <error-location> is a string for which part of the request to look in
<del> # <error-name> is a string naming the parameter
<del> # <error-description> is a string detailing what the problem is
<del> # Here we ignore object and combine message and cause along with an error
<del> # if one or more exists.
<del> def _get_error(self, body):
<del> """
<del> Get the error code and message from a JSON response.
<del>
<del> Incorporate the first error if there are multiple errors.
<del>
<del> :param body: The body of the JSON response dictionary
<del> :type body: ``dict``
<del>
<del> :return: String containing error message
<del> :rtype: ``str``
<del> """
<del> message = '%s: %s' % (body['cause'], body['message'])
<del>
<del> if 'errors' in body:
<del> err = body['errors'][0]
<del> message = '%s (%s in %s: %s)' % (message,
<del> err.get('location'),
<del> err.get('name'),
<del> err.get('description'))
<del>
<del> return message
<del>
<ide> def parse_body(self):
<ide> """
<ide> Parse the JSON response body, or raise exceptions as appropriate.
<ide> def parse_body(self):
<ide> message = body
<ide> raise GandiLiveBaseError(message, self.status)
<ide>
<add> # Errors are not described at all in Gandi's official documentation.
<add> # It appears when an error arises, a JSON object is returned along with
<add> # an HTTP 4xx class code. The object is structured as:
<add> # {
<add> # code: <code>,
<add> # object: <object>,
<add> # message: <message>,
<add> # cause: <cause>,
<add> # errors: [
<add> # {
<add> # location: <error-location>,
<add> # name: <error-name>,
<add> # description: <error-description>
<add> # }
<add> # ]
<add> # }
<add> # where
<add> # <code> is a number equal to the HTTP response status code
<add> # <object> is a string with some internal name for the status code
<add> # <message> is a string detailing what the problem is
<add> # <cause> is a string that comes from a set of succinct problem summaries
<add> # errors is optional; if present:
<add> # <error-location> is a string for which part of the request to look in
<add> # <error-name> is a string naming the parameter
<add> # <error-description> is a string detailing what the problem is
<add> # Here we ignore object and combine message and cause along with an error
<add> # if one or more exists.
<add> def _get_error(self, body):
<add> """
<add> Get the error code and message from a JSON response.
<add>
<add> Incorporate the first error if there are multiple errors.
<add>
<add> :param body: The body of the JSON response dictionary
<add> :type body: ``dict``
<add>
<add> :return: String containing error message
<add> :rtype: ``str``
<add> """
<add> message = '%s: %s' % (body['cause'], body['message'])
<add>
<add> if 'errors' in body:
<add> err = body['errors'][0]
<add> message = '%s (%s in %s: %s)' % (message,
<add> err.get('location'),
<add> err.get('name'),
<add> err.get('description'))
<add>
<add> return message
<add>
<ide>
<ide> class GandiLiveConnection(ConnectionKey):
<ide> """
| 1
|
Javascript
|
Javascript
|
remove annotate since it's not public
|
6aee2938a71c99fdd35639725c6900347999f658
|
<ide><path>test/testabilityPatch.js
<ide> function dealoc(obj) {
<ide> }
<ide>
<ide> extend(angular, {
<del> 'annotate': annotate,
<ide> 'element': jqLite,
<ide> 'compile': compile,
<ide> 'scope': createScope,
| 1
|
Ruby
|
Ruby
|
define assert_empty for ruby <= 1.8
|
267ffddbd3042127d0c8b88580ba12df960981d0
|
<ide><path>Library/Homebrew/test/testing_env.rb
<ide> def assert_version_nil url
<ide> assert_nil Version.parse(url)
<ide> end
<ide> end
<add>
<add>module Test::Unit::Assertions
<add> def assert_empty(obj, msg=nil)
<add> assert_respond_to(obj, :empty?, msg)
<add> assert(obj.empty?, msg)
<add> end if RUBY_VERSION.to_f <= 1.8
<add>end
| 1
|
Python
|
Python
|
restore tokenization timing in language.evaluate
|
e750c1760c5ad4324e606c8dcc528d1b735d3941
|
<ide><path>spacy/language.py
<ide> def evaluate(
<ide> scorer = Scorer(**kwargs)
<ide> # reset annotation in predicted docs and time tokenization
<ide> start_time = timer()
<add> # this is purely for timing
<add> for eg in examples:
<add> self.make_doc(eg.reference.text)
<ide> # apply all pipeline components
<ide> for name, pipe in self.pipeline:
<ide> kwargs = component_cfg.get(name, {})
| 1
|
Go
|
Go
|
set -500 oom score for test daemons
|
561b8014c022bede412aee47e89cc11b648316ac
|
<ide><path>testutil/daemon/daemon.go
<ide> type Daemon struct {
<ide> DefaultAddrPool []string
<ide> SubnetSize uint32
<ide> DataPathPort uint32
<add> OOMScoreAdjust int
<ide> // cached information
<ide> CachedInfo types.Info
<ide> }
<ide> func New(t testing.TB, ops ...Option) *Daemon {
<ide> }
<ide> ops = append(ops, WithRootlessUser("unprivilegeduser"))
<ide> }
<add> ops = append(ops, WithOOMScoreAdjust(-500))
<ide>
<ide> d, err := NewDaemon(dest, ops...)
<ide> assert.NilError(t, err, "could not create daemon at %q", dest)
<ide><path>testutil/daemon/ops.go
<ide> func WithRootlessUser(username string) Option {
<ide> d.rootlessUser = u
<ide> }
<ide> }
<add>
<add>// WithOOMScoreAdjust sets OOM score for the daemon
<add>func WithOOMScoreAdjust(score int) Option {
<add> return func(d *Daemon) {
<add> d.OOMScoreAdjust = score
<add> }
<add>}
| 2
|
Javascript
|
Javascript
|
resolve the char->glyphs mapping issue
|
c9e0b056782a306da7f980db00388e73e0798572
|
<ide><path>PDFFont.js
<ide> var fontCount = 0;
<ide> var Fonts = {
<ide> _active: null,
<ide> get active() {
<del> return this._active || { encoding: {} };
<add> return this._active || { encoding: [] };
<ide> },
<ide>
<ide> set active(aName) {
<ide><path>pdf.js
<ide> var Lexer = (function() {
<ide> }
<ide> }
<ide>
<del> x = Fonts.unicodeFromCode(x);
<ide> str += String.fromCharCode(x);
<ide> break;
<ide> case '\r':
<ide> var Lexer = (function() {
<ide> }
<ide> break;
<ide> default:
<del> var unicode = Fonts.unicodeFromCode(ch.charCodeAt(0));
<del> str += String.fromCharCode(unicode);
<add> str += ch;
<ide> break;
<ide> }
<ide> } while (!done);
<ide> var CanvasGraphics = (function() {
<ide> var descriptor = xref.fetch(fontDict.get("FontDescriptor"));
<ide> var fontName = descriptor.get("FontName").name;
<ide> fontName = fontName.replace("+", "_");
<del>
<add>
<ide> var font = Fonts[fontName];
<ide> if (!font) {
<ide> var fontFile = descriptor.get2("FontFile", "FontFile2");
<ide> var CanvasGraphics = (function() {
<ide> for (var j = 0; j < widths.length; j++) {
<ide> var index = widths[j];
<ide> if (index)
<del> charset.push(encoding[j + firstchar]);
<add> charset.push(encoding[j + firstchar]);
<ide> }
<ide> }
<ide> }
<ide> var CanvasGraphics = (function() {
<ide> this.ctx.scale(1, -1);
<ide> this.ctx.transform.apply(this.ctx, this.current.textMatrix);
<ide>
<del> this.ctx.fillText(text, this.current.x, this.current.y);
<add> // Replace characters code by glyphs code
<add> var glyphs = [];
<add> for (var i = 0; i < text.length; i++)
<add> glyphs[i] = String.fromCharCode(Fonts.unicodeFromCode(text[i].charCodeAt(0)));
<add>
<add> this.ctx.fillText(glyphs.join(""), this.current.x, this.current.y);
<ide> this.current.x += this.ctx.measureText(text).width;
<ide>
<ide> this.ctx.restore();
<ide><path>test.js
<ide> /* -*- Mode: Java; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- /
<ide> /* vim: set shiftwidth=4 tabstop=8 autoindent cindent expandtab: */
<ide>
<del>var pdfDocument, canvas, pageDisplay, pageNum, pageTimeout;
<add>var pdfDocument, canvas, pageDisplay, pageNum, pageInterval;
<ide> function load() {
<ide> canvas = document.getElementById("canvas");
<ide> canvas.mozOpaque = true;
<ide> function gotoPage(num) {
<ide>
<ide> function displayPage(num) {
<ide> if (pageNum != num)
<del> window.clearTimeout(pageTimeout);
<add> window.clearTimeout(pageInterval);
<ide>
<ide> document.getElementById("pageNumber").value = num;
<ide>
<ide> function displayPage(num) {
<ide> var page = pdfDocument.getPage(pageNum = num);
<ide>
<ide> var t1 = Date.now();
<del>
<ide> var ctx = canvas.getContext("2d");
<ide> ctx.save();
<ide> ctx.fillStyle = "rgb(255, 255, 255)";
<ide> function displayPage(num) {
<ide> page.compile(gfx, fonts);
<ide> var t2 = Date.now();
<ide>
<del> var interval = setInterval(function() {
<add> // FIXME This need to be replaced by an event
<add> pageInterval = setInterval(function() {
<ide> for (var i = 0; i < fonts.length; i++) {
<ide> if (fonts[i].loading)
<ide> return;
<ide> }
<add> var t3 = Date.now();
<ide>
<add> clearInterval(pageInterval);
<ide> page.display(gfx);
<del> var t3 = Date.now();
<add>
<add> var t4 = Date.now();
<add>
<ide> var infoDisplay = document.getElementById("info");
<del> infoDisplay.innerHTML = "Time to load/compile/render: "+ (t1 - t0) + "/" + (t2 - t1) + "/" + (t3 - t2) + " ms";
<del> clearInterval(interval);
<add> infoDisplay.innerHTML = "Time to load/compile/fonts/render: "+ (t1 - t0) + "/" + (t2 - t1) + "/" + (t3 - t2) + "/" + (t4 - t3) + " ms";
<ide> }, 10);
<ide> }
<ide>
| 3
|
Python
|
Python
|
add note about --force flag to error message
|
a3ddbc0444c1f9ec49e59d8c58b1bb06fe595e1a
|
<ide><path>spacy/cli/package.py
<ide> def create_dirs(package_path, force):
<ide> shutil.rmtree(unicode_(package_path))
<ide> else:
<ide> util.sys_exit(unicode_(package_path),
<del> "Please delete the directory and try again.",
<add> "Please delete the directory and try again, or use the --force "
<add> "flag to overwrite existing directories.",
<ide> title="Package directory already exists")
<ide> Path.mkdir(package_path, parents=True)
<ide>
| 1
|
Java
|
Java
|
add null check for gesture ended notifier
|
36c4e42d82498a37b023f6a162b871581254ff2b
|
<ide><path>ReactAndroid/src/main/java/com/facebook/react/uimanager/events/NativeGestureUtil.java
<ide>
<ide> import android.view.MotionEvent;
<ide> import android.view.View;
<add>import com.facebook.react.uimanager.RootView;
<ide> import com.facebook.react.uimanager.RootViewUtil;
<ide>
<ide> /** Utilities for native Views that interpret native gestures (e.g. ScrollView, ViewPager, etc.). */
<ide> public static void notifyNativeGestureStarted(View view, MotionEvent event) {
<ide> * @param event the MotionEvent that caused the gesture to be ended
<ide> */
<ide> public static void notifyNativeGestureEnded(View view, MotionEvent event) {
<del> RootViewUtil.getRootView(view).onChildEndedNativeGesture(view, event);
<add> RootView rootView = RootViewUtil.getRootView(view);
<add> if (rootView != null) {
<add> rootView.onChildEndedNativeGesture(view, event);
<add> }
<ide> }
<ide> }
| 1
|
Javascript
|
Javascript
|
fix wrong place of isquaternion property
|
1a1772c0e8e2b3ca6bd4f98f4e20fc5adc347d00
|
<ide><path>src/math/Quaternion.js
<ide> function Quaternion( x, y, z, w ) {
<ide>
<ide> Object.assign( Quaternion, {
<ide>
<del> isQuaternion: true,
<del>
<ide> slerp: function ( qa, qb, qm, t ) {
<ide>
<ide> return qm.copy( qa ).slerp( qb, t );
<ide> Object.defineProperties( Quaternion.prototype, {
<ide>
<ide> Object.assign( Quaternion.prototype, {
<ide>
<add> isQuaternion: true,
<add>
<ide> set: function ( x, y, z, w ) {
<ide>
<ide> this._x = x;
| 1
|
PHP
|
PHP
|
fix escaping quotes
|
687df01fa19c99546c1ae1dd53c2a465459b50dc
|
<ide><path>src/Illuminate/Database/Query/Grammars/Grammar.php
<ide> protected function wrapJsonFieldAndPath($column)
<ide> */
<ide> protected function wrapJsonPath($value, $delimiter = '->')
<ide> {
<del> $value = preg_replace("/([\\\\]+)?\\'/", "\\'", $value);
<add> $value = preg_replace("/([\\\\]+)?\\'/", "''", $value);
<ide>
<ide> return '\'$."'.str_replace($delimiter, '"."', $value).'"\'';
<ide> }
<ide><path>tests/Database/DatabaseQueryBuilderTest.php
<ide> public function testMySqlWrappingJsonWithBooleanAndIntegerThatLooksLikeOne()
<ide> public function testJsonPathEscaping()
<ide> {
<ide> $expectedWithJsonEscaped = <<<SQL
<del>select json_unquote(json_extract(`json`, '$."\'))#"'))
<add>select json_unquote(json_extract(`json`, '$."''))#"'))
<ide> SQL;
<ide>
<ide> $builder = $this->getMySqlBuilder();
| 2
|
Javascript
|
Javascript
|
use possessive 'its' not 'it's'
|
fd34018d084e1868d87686c5c36818da2ebc00ab
|
<ide><path>Libraries/Lists/FlatList.js
<ide> type DefaultProps = typeof defaultProps;
<ide> * }
<ide> *
<ide> * This is a convenience wrapper around [`<VirtualizedList>`](docs/virtualizedlist.html),
<del> * and thus inherits it's props (as well as those of `ScrollView`) that aren't explicitly listed
<add> * and thus inherits its props (as well as those of `ScrollView`) that aren't explicitly listed
<ide> * here, along with the following caveats:
<ide> *
<ide> * - Internal state is not preserved when content scrolls out of the render window. Make sure all
| 1
|
PHP
|
PHP
|
apply fixes from styleci
|
3658477a86175c5537674dc968e580aba823525d
|
<ide><path>tests/Integration/Database/EloquentBelongsToManyTest.php
<ide> namespace Illuminate\Tests\Integration\Database\EloquentBelongsToManyTest;
<ide>
<ide> use Carbon\Carbon;
<del>use Illuminate\Support\Facades\DB;
<ide> use Orchestra\Testbench\TestCase;
<add>use Illuminate\Support\Facades\DB;
<ide> use Illuminate\Support\Facades\Schema;
<ide> use Illuminate\Database\Eloquent\Model;
<ide>
<ide> public function test_can_retrieve_related_ids()
<ide> ['post_id' => $post->id, 'tag_id' => 400, 'flag' => ''],
<ide> ]);
<ide>
<del>
<ide> $this->assertEquals([200, 400], $post->tags()->allRelatedIds()->toArray());
<ide> }
<ide>
| 1
|
Java
|
Java
|
add the new operation concat
|
a1f6e0bdf7e8a352ea1d3712623c52e5c81adf81
|
<ide><path>rxjava-core/src/main/java/rx/observables/Observable.java
<ide> import org.mockito.Mockito;
<ide> import org.mockito.MockitoAnnotations;
<ide>
<add>import rx.observables.operations.OperationConcat;
<ide> import rx.observables.operations.OperationFilter;
<ide> import rx.observables.operations.OperationLast;
<ide> import rx.observables.operations.OperationMap;
<ide> public static <T> Observable<T> merge(Observable<T>... source) {
<ide> return create(OperationMerge.merge(source));
<ide> }
<ide>
<add> /**
<add> * Combines the objects emitted by two or more Observables, and emits the result as a single Observable,
<add> * by using the <code>concat</code> method.
<add> *
<add> * @param source
<add> * a series of Observables that emit sequences of items
<add> * @return a Observable that emits a sequence of elements that are the result of flattening the
<add> * output from the <code>source</code> Observables
<add> * @see <a href="http://msdn.microsoft.com/en-us/library/hh229099(v=vs.103).aspx">MSDN: Observable.Merge Method</a>
<add> */
<add> public static <T> Observable<T> concat(Observable<T>... source) {
<add> return create(OperationConcat.concat(source));
<add> }
<add>
<ide> /**
<ide> * Same functionality as <code>merge</code> except that errors received to onError will be held until all sequences have finished (onComplete/onError) before sending the error.
<ide> * <p>
<ide><path>rxjava-core/src/main/java/rx/observables/operations/OperationConcat.java
<add>/**
<add> * Copyright 2013 Netflix, Inc.
<add> *
<add> * Licensed under the Apache License, Version 2.0 (the "License");
<add> * you may not use this file except in compliance with the License.
<add> * You may obtain a copy of the License at
<add> *
<add> * http://www.apache.org/licenses/LICENSE-2.0
<add> *
<add> * Unless required by applicable law or agreed to in writing, software
<add> * distributed under the License is distributed on an "AS IS" BASIS,
<add> * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
<add> * See the License for the specific language governing permissions and
<add> * limitations under the License.
<add> */
<add>package rx.observables.operations;
<add>
<add>
<add>import static org.junit.Assert.fail;
<add>import static org.mockito.Mockito.mock;
<add>import static org.mockito.Mockito.never;
<add>import static org.mockito.Mockito.times;
<add>import static org.mockito.Mockito.verify;
<add>
<add>import java.util.concurrent.CountDownLatch;
<add>
<add>import org.junit.Assert;
<add>import org.junit.Before;
<add>import org.junit.Test;
<add>
<add>import rx.observables.Observable;
<add>import rx.observables.Observer;
<add>import rx.observables.Subscription;
<add>import rx.util.AtomicObservableSubscription;
<add>import rx.util.functions.Func1;
<add>
<add>public final class OperationConcat {
<add>
<add> public static <T> Func1<Observer<T>, Subscription> concat(final Observable<T>... sequences) {
<add> return new OperatorSubscribeFunction<T>() {
<add>
<add> @Override
<add> public Subscription call(Observer<T> observer) {
<add> return new Concat<T>(sequences).call(observer);
<add> }
<add> };
<add> }
<add>
<add> private static class Concat<T> implements OperatorSubscribeFunction<T> {
<add> private final Observable<T>[] sequences;
<add> private int num = 0;
<add> private int count = 0;
<add> private Subscription s;
<add>
<add> Concat(final Observable<T>... sequences) {
<add> this.sequences = sequences;
<add> this.num = sequences.length - 1;
<add> }
<add> private final AtomicObservableSubscription Subscription = new AtomicObservableSubscription();
<add>
<add> private final Subscription actualSubscription = new Subscription() {
<add>
<add> @Override
<add> public void unsubscribe() {
<add> if (null != s)
<add> s.unsubscribe();
<add> }
<add> };
<add>
<add> public Subscription call(Observer<T> observer) {
<add> s = sequences[count].subscribe(new ConcatObserver(observer));
<add>
<add> return Subscription.wrap(actualSubscription);
<add> }
<add>
<add> private class ConcatObserver implements Observer<T> {
<add> private final Observer<T> observer;
<add>
<add> ConcatObserver(Observer<T> observer) {
<add> this.observer = observer;
<add> }
<add>
<add> @Override
<add> public void onCompleted() {
<add> if (num == count)
<add> observer.onCompleted();
<add> else {
<add> count++;
<add> s = sequences[count].subscribe(this);
<add> }
<add> }
<add>
<add> @Override
<add> public void onError(Exception e) {
<add> observer.onError(e);
<add>
<add> }
<add>
<add> @Override
<add> public void onNext(T args) {
<add> observer.onNext(args);
<add>
<add> }
<add> }
<add> }
<add>
<add> public static class UnitTest {
<add> private final static String[] expected = {"1", "3", "5", "7", "2", "4", "6"};
<add> private int index = 0;
<add>
<add> Observer<String> observer = new Observer<String>() {
<add>
<add> @Override
<add> public void onCompleted() {
<add> }
<add>
<add> @Override
<add> public void onError(Exception e) {
<add> // TODO Auto-generated method stub
<add> }
<add>
<add> @Override
<add> public void onNext(String args) {
<add> Assert.assertEquals(expected[index], args);
<add> index++;
<add> }
<add> };
<add>
<add> @Before
<add> public void before() {
<add> index = 0;
<add> }
<add>
<add> @Test
<add> public void testConcat() {
<add> String[] o = {"1", "3", "5", "7"};
<add> String[] e = {"2", "4", "6"};
<add>
<add> final Observable<String> odds = Observable.toObservable(o);
<add> final Observable<String> even = Observable.toObservable(e);
<add>
<add> @SuppressWarnings("unchecked")
<add> Observable<String> concat = Observable.create(concat(odds, even));
<add> concat.subscribe(observer);
<add> Assert.assertEquals(expected.length, index);
<add>
<add> }
<add>
<add> @Test
<add> public void testConcatUnsubscribe() {
<add> CountDownLatch callOnce = new CountDownLatch(1);
<add> CountDownLatch okToContinue = new CountDownLatch(1);
<add> TestObservable w = new TestObservable(callOnce, okToContinue, "one", "two", "three");
<add>
<add> @SuppressWarnings("unchecked")
<add> Observer<String> aObserver = mock(Observer.class);
<add> @SuppressWarnings("unchecked")
<add> Observable<String> concat = Observable.create(concat(w));
<add> Subscription s1 = concat.subscribe(aObserver);
<add>
<add> try {
<add> //Allow the observable to call onNext once.
<add> callOnce.await();
<add> s1.unsubscribe();
<add> //Unblock the observable to continue.
<add> okToContinue.countDown();
<add> w.t.join();
<add> } catch (Exception e) {
<add> e.printStackTrace();
<add> fail(e.getMessage());
<add> }
<add>
<add> System.out.println("TestObservable thread finished");
<add> verify(aObserver, times(1)).onNext("one");
<add> verify(aObserver, never()).onNext("two");
<add> verify(aObserver, never()).onNext("three");
<add> }
<add>
<add> private static class TestObservable extends Observable<String> {
<add>
<add> private final Subscription s = new Subscription() {
<add>
<add> @Override
<add> public void unsubscribe() {
<add> // TODO Auto-generated method stub
<add> subscribed = false;
<add> }
<add>
<add> };
<add> private final String[] values;
<add> private Thread t = null;
<add> private int count = 0;
<add> private boolean subscribed = true;
<add> private final CountDownLatch once;
<add> private final CountDownLatch okToContinue;
<add>
<add> public TestObservable(CountDownLatch once, CountDownLatch okToContinue, String... values) {
<add> super(new Func1<Observer<String>, Subscription>() {
<add>
<add> @Override
<add> public Subscription call(Observer<String> t1) {
<add> // do nothing as we are overriding subscribe for testing purposes
<add> return null;
<add> }
<add> });
<add>
<add> this.values = values;
<add> this.once = once;
<add> this.okToContinue = okToContinue;
<add> }
<add>
<add> @Override
<add> public Subscription subscribe(final Observer<String> observer) {
<add> System.out.println("TestObservable subscribed to ...");
<add> t = new Thread(new Runnable() {
<add>
<add> @Override
<add> public void run() {
<add> try {
<add> System.out.println("running TestObservable thread");
<add> while(count < values.length && subscribed) {
<add> System.out.println("TestObservable onNext: " + s);
<add> observer.onNext(values[count]);
<add> count++;
<add> //Unblock the main thread to call unsubscribe.
<add> once.countDown();
<add> //Block until the main thread has called unsubscribe.
<add> okToContinue.await();
<add> }
<add>
<add> if (subscribed)
<add> observer.onCompleted();
<add> } catch (Exception e) {
<add> throw new RuntimeException(e);
<add> }
<add> }
<add>
<add> });
<add> System.out.println("starting TestObservable thread");
<add> t.start();
<add> System.out.println("done starting TestObservable thread");
<add> return s;
<add> }
<add>
<add> }
<add>
<add> }
<add>}
<ide>\ No newline at end of file
| 2
|
Ruby
|
Ruby
|
move logic to test-bot
|
65bc39f952d5542e620d1711dd2337913c890f7a
|
<ide><path>Library/Homebrew/dev-cmd/bottle.rb
<ide> def bottle_args
<ide> end
<ide>
<ide> def bottle
<del> ENV["HOMEBREW_NO_PATCHELF_RB_WRITE"] = "1" unless ENV["HOMEBREW_PATCHELF_RB_WRITE"].present?
<del>
<ide> args = bottle_args.parse
<ide>
<ide> return merge(args: args) if args.merge?
<ide><path>Library/Homebrew/os/linux/elf.rb
<ide> def interpreter
<ide> def patch!(interpreter: nil, rpath: nil)
<ide> return if interpreter.blank? && rpath.blank?
<ide>
<del> if HOMEBREW_PATCHELF_RB_WRITE && ENV["HOMEBREW_NO_PATCHELF_RB_WRITE"].blank?
<add> if HOMEBREW_PATCHELF_RB_WRITE
<ide> save_using_patchelf_rb interpreter, rpath
<ide> else
<ide> save_using_patchelf interpreter, rpath
| 2
|
Javascript
|
Javascript
|
fix typo in comment
|
319b858e7767c974967ed3cd768855ad8e2172d3
|
<ide><path>examples/with-firebase/context/userContext.js
<ide> export default function UserContextComp({ children }) {
<ide> setUser({ uid, displayName, email, photoURL })
<ide> } else setUser(null)
<ide> } catch (error) {
<del> // Most probably a connection error. Handle appropiately.
<add> // Most probably a connection error. Handle appropriately.
<ide> } finally {
<ide> setLoadingUser(false)
<ide> }
| 1
|
PHP
|
PHP
|
add "url" option to configuration
|
6e5ca7331ebf511754d276cb40bc7b0eef4a463c
|
<ide><path>app/config/app.php
<ide>
<ide> 'debug' => true,
<ide>
<add>/*
<add>|--------------------------------------------------------------------------
<add>| Application URL
<add>|--------------------------------------------------------------------------
<add>|
<add>| This URL is used by the console to properly generate URLs when using
<add>| the Artisan command line tool. You should set this to the root of
<add>| your application so that it is used when running Artisan tasks.
<add>|
<add>*/
<add>
<add> 'url' => 'http://localhost',
<add>
<ide> /*
<ide> |--------------------------------------------------------------------------
<ide> | Application Timezone
| 1
|
Go
|
Go
|
remove useless lock
|
6f70ed3a742162c4cf374a2c2bbd094eed3b043b
|
<ide><path>builtins/builtins.go
<ide> func remote(eng *engine.Engine) {
<ide> func daemon(eng *engine.Engine) {
<ide> eng.Register("initserver", docker.InitServer)
<ide> eng.Register("init_networkdriver", lxc.InitDriver)
<del> eng.Register("version", docker.GetVersion)
<ide> }
<ide><path>server.go
<ide> func InitServer(job *engine.Job) engine.Status {
<ide> "search": srv.ImagesSearch,
<ide> "changes": srv.ContainerChanges,
<ide> "top": srv.ContainerTop,
<add> "version": srv.DockerVersion,
<ide> "load": srv.ImageLoad,
<ide> "build": srv.Build,
<ide> "pull": srv.ImagePull,
<ide> func (srv *Server) DockerInfo(job *engine.Job) engine.Status {
<ide> return engine.StatusOK
<ide> }
<ide>
<add>func (srv *Server) DockerVersion(job *engine.Job) engine.Status {
<add> v := &engine.Env{}
<add> v.Set("Version", dockerversion.VERSION)
<add> v.Set("GitCommit", dockerversion.GITCOMMIT)
<add> v.Set("GoVersion", goruntime.Version())
<add> v.Set("Os", goruntime.GOOS)
<add> v.Set("Arch", goruntime.GOARCH)
<add> if kernelVersion, err := utils.GetKernelVersion(); err == nil {
<add> v.Set("KernelVersion", kernelVersion.String())
<add> }
<add> if _, err := v.WriteTo(job.Stdout); err != nil {
<add> return job.Error(err)
<add> }
<add> return engine.StatusOK
<add>}
<add>
<ide> func (srv *Server) ImageHistory(job *engine.Job) engine.Status {
<ide> if n := len(job.Args); n != 1 {
<ide> return job.Errorf("Usage: %s IMAGE", job.Name)
<ide> func NewServer(eng *engine.Engine, config *daemonconfig.Config) (*Server, error)
<ide> }
<ide>
<ide> func (srv *Server) HTTPRequestFactory(metaHeaders map[string][]string) *utils.HTTPRequestFactory {
<del> srv.Lock()
<del> defer srv.Unlock()
<del> v := dockerVersion()
<ide> httpVersion := make([]utils.VersionInfo, 0, 4)
<del> httpVersion = append(httpVersion, &simpleVersionInfo{"docker", v.Get("Version")})
<del> httpVersion = append(httpVersion, &simpleVersionInfo{"go", v.Get("GoVersion")})
<del> httpVersion = append(httpVersion, &simpleVersionInfo{"git-commit", v.Get("GitCommit")})
<del> httpVersion = append(httpVersion, &simpleVersionInfo{"kernel", v.Get("KernelVersion")})
<del> httpVersion = append(httpVersion, &simpleVersionInfo{"os", v.Get("Os")})
<del> httpVersion = append(httpVersion, &simpleVersionInfo{"arch", v.Get("Arch")})
<add> httpVersion = append(httpVersion, &simpleVersionInfo{"docker", dockerversion.VERSION})
<add> httpVersion = append(httpVersion, &simpleVersionInfo{"go", goruntime.Version()})
<add> httpVersion = append(httpVersion, &simpleVersionInfo{"git-commit", dockerversion.GITCOMMIT})
<add> if kernelVersion, err := utils.GetKernelVersion(); err == nil {
<add> httpVersion = append(httpVersion, &simpleVersionInfo{"kernel", kernelVersion.String()})
<add> }
<add> httpVersion = append(httpVersion, &simpleVersionInfo{"os", goruntime.GOOS})
<add> httpVersion = append(httpVersion, &simpleVersionInfo{"arch", goruntime.GOARCH})
<ide> ud := utils.NewHTTPUserAgentDecorator(httpVersion...)
<ide> md := &utils.HTTPMetaHeadersDecorator{
<ide> Headers: metaHeaders,
<ide><path>version.go
<del>package docker
<del>
<del>import (
<del> "github.com/dotcloud/docker/dockerversion"
<del> "github.com/dotcloud/docker/engine"
<del> "github.com/dotcloud/docker/utils"
<del> "runtime"
<del>)
<del>
<del>func GetVersion(job *engine.Job) engine.Status {
<del> if _, err := dockerVersion().WriteTo(job.Stdout); err != nil {
<del> job.Errorf("%s", err)
<del> return engine.StatusErr
<del> }
<del> return engine.StatusOK
<del>}
<del>
<del>// dockerVersion returns detailed version information in the form of a queriable
<del>// environment.
<del>func dockerVersion() *engine.Env {
<del> v := &engine.Env{}
<del> v.Set("Version", dockerversion.VERSION)
<del> v.Set("GitCommit", dockerversion.GITCOMMIT)
<del> v.Set("GoVersion", runtime.Version())
<del> v.Set("Os", runtime.GOOS)
<del> v.Set("Arch", runtime.GOARCH)
<del> // FIXME:utils.GetKernelVersion should only be needed here
<del> if kernelVersion, err := utils.GetKernelVersion(); err == nil {
<del> v.Set("KernelVersion", kernelVersion.String())
<del> }
<del> return v
<del>}
| 3
|
Javascript
|
Javascript
|
restrict an event test fallback to testswarm
|
bde53edcf4bd6c975d068eed4eb16c5ba09c1cff
|
<ide><path>test/unit/event.js
<ide> QUnit.test( "focus-blur order (#12868)", function( assert ) {
<ide> setTimeout( function() {
<ide>
<ide> // DOM focus is unreliable in TestSwarm
<del> if ( order === 0 ) {
<add> if ( QUnit.isSwarm && order === 0 ) {
<ide> assert.ok( true, "GAP: Could not observe focus change" );
<ide> assert.ok( true, "GAP: Could not observe focus change" );
<ide> }
| 1
|
Javascript
|
Javascript
|
remove local variable bevelsubtract
|
08174e30235eb3b0e96166a5573418debec98c32
|
<ide><path>src/geometries/ExtrudeGeometry.js
<ide> function ExtrudeBufferGeometry( shapes, options ) {
<ide> var bevelThickness = options.bevelThickness !== undefined ? options.bevelThickness : 6;
<ide> var bevelSize = options.bevelSize !== undefined ? options.bevelSize : bevelThickness - 2;
<ide> var bevelSegments = options.bevelSegments !== undefined ? options.bevelSegments : 3;
<del> var bevelSubtract = false;
<del>
<del> if ( bevelSize < 0 ) {
<del>
<del> bevelSize = - bevelSize;
<del> bevelSubtract = true;
<del>
<del> }
<ide>
<ide> var extrudePath = options.extrudePath;
<ide>
<ide> function ExtrudeBufferGeometry( shapes, options ) {
<ide>
<ide> t = b / bevelSegments;
<ide> z = bevelThickness * Math.cos( t * Math.PI / 2 );
<del> bs = bevelSize * Math.sin( t * Math.PI / 2 );
<add> bs = Math.abs( bevelSize ) * Math.sin( t * Math.PI / 2 );
<ide>
<del> if ( bevelSubtract ) {
<add> if ( bevelSize < 0 ) {
<ide>
<del> bs -= bevelSize;
<add> bs += bevelSize;
<ide>
<ide> }
<ide>
<ide> function ExtrudeBufferGeometry( shapes, options ) {
<ide>
<ide> }
<ide>
<del> bs = ( bevelSubtract ? 0 : bevelSize );
<add> bs = ( bevelSize < 0 ? 0 : - bevelSize );
<ide>
<ide> // Back facing vertices
<ide>
<ide> function ExtrudeBufferGeometry( shapes, options ) {
<ide>
<ide> t = b / bevelSegments;
<ide> z = bevelThickness * Math.cos( t * Math.PI / 2 );
<del> bs = bevelSize * Math.sin( t * Math.PI / 2 );
<add> bs = Math.abs( bevelSize ) * Math.sin( t * Math.PI / 2 );
<ide>
<del> if ( bevelSubtract ) {
<add> if ( bevelSize < 0 ) {
<ide>
<del> bs -= bevelSize;
<add> bs += bevelSize;
<ide>
<ide> }
<ide>
| 1
|
Javascript
|
Javascript
|
remove unused var in build/version.js
|
6986dbb85138032468b2e4d79eb0d919fb0ff527
|
<ide><path>build/version.js
<ide> if (tuple[0]) {
<ide> }
<ide>
<ide> var sh = require('shelljs');
<del>var version = process.env.npm_package_version;
<ide> var prereleaseType = npm_config_argv['remain'][0];
<ide> var approvedTypes = {
<ide> 'major': 1,
| 1
|
Ruby
|
Ruby
|
fix rubocop warnings
|
fb3bec8d70d375a97554d4c3fed82ad2332b2191
|
<ide><path>Library/Homebrew/extend/ENV/super.rb
<ide> def determine_library_paths
<ide> end
<ide>
<ide> def determine_dependencies
<del> deps.map {|d| d.name}.join(",")
<add> deps.map(&:name).join(",")
<ide> end
<ide>
<ide> def determine_cmake_prefix_path
| 1
|
PHP
|
PHP
|
use post method when re-sending email verfication
|
e05c226c09031233acf79707635861932ec3b9b8
|
<ide><path>src/Illuminate/Routing/Router.php
<ide> public function emailVerification()
<ide> {
<ide> $this->get('email/verify', 'Auth\VerificationController@show')->name('verification.notice');
<ide> $this->get('email/verify/{id}', 'Auth\VerificationController@verify')->name('verification.verify');
<del> $this->get('email/resend', 'Auth\VerificationController@resend')->name('verification.resend');
<add> $this->post('email/resend', 'Auth\VerificationController@resend')->name('verification.resend');
<ide> }
<ide>
<ide> /**
| 1
|
Python
|
Python
|
remove some nose dependences in utils.py
|
04c23fa59e71fbfbbcf24849954d7651cc72285e
|
<ide><path>numpy/testing/nose_tools/utils.py
<ide> def rundocs(filename=None, raise_on_error=True):
<ide> raise AssertionError("Some doctests failed:\n%s" % "\n".join(msg))
<ide>
<ide>
<del>def raises(*args,**kwargs):
<add>def raises(*args):
<add> """Decorator to check for raised exceptions.
<add>
<add> The decorated test function must raise one of the passed exceptions to
<add> pass. If you want to test many assertions about exceptions in a single
<add> test, you may want to use `assert_raises` instead.
<add>
<add> .. warning::
<add> This decorator is nose specific, do not use it if you are using a
<add> different test framework.
<add>
<add> Parameters
<add> ----------
<add> args : exceptions
<add> The test passes if any of the passed exceptions is raised.
<add>
<add> Raises
<add> ------
<add> AssertionError
<add>
<add> Examples
<add> --------
<add>
<add> Usage::
<add>
<add> @raises(TypeError, ValueError)
<add> def test_raises_type_error():
<add> raise TypeError("This test passes")
<add>
<add> @raises(Exception)
<add> def test_that_fails_by_passing():
<add> pass
<add>
<add> """
<ide> nose = import_nose()
<del> return nose.tools.raises(*args,**kwargs)
<add> return nose.tools.raises(*args)
<ide>
<add>#
<add># assert_raises and assert_raises_regex are taken from unittest.
<add>#
<add>import unittest
<add>
<add>
<add>class _Dummy(unittest.TestCase):
<add> def nop(self):
<add> pass
<add>
<add>_d = _Dummy('nop')
<ide>
<ide> def assert_raises(*args, **kwargs):
<ide> """
<ide> def assert_raises(*args, **kwargs):
<ide>
<ide> """
<ide> __tracebackhide__ = True # Hide traceback for py.test
<del> nose = import_nose()
<del> return nose.tools.assert_raises(*args,**kwargs)
<add> return _d.assertRaises(*args,**kwargs)
<ide>
<ide>
<ide> def assert_raises_regex(exception_class, expected_regexp, *args, **kwargs):
<ide> def assert_raises_regex(exception_class, expected_regexp, *args, **kwargs):
<ide>
<ide> """
<ide> __tracebackhide__ = True # Hide traceback for py.test
<del> nose = import_nose()
<ide>
<ide> if sys.version_info.major >= 3:
<del> funcname = nose.tools.assert_raises_regex
<add> funcname = _d.assertRaisesRegex
<ide> else:
<ide> # Only present in Python 2.7, missing from unittest in 2.6
<del> funcname = nose.tools.assert_raises_regexp
<add> funcname = _d.assertRaisesRegexp
<ide>
<ide> return funcname(exception_class, expected_regexp, *args, **kwargs)
<ide>
| 1
|
Javascript
|
Javascript
|
check error and cleanups in test-fs-read-buffer
|
eab95630f1cc26932f7b850bb8385cad202160b2
|
<ide><path>test/parallel/test-fs-read-buffer.js
<ide> function test(bufferAsync, bufferSync, expected) {
<ide> expected.length,
<ide> 0,
<ide> common.mustCall((err, bytesRead) => {
<add> assert.ifError(err);
<ide> assert.strictEqual(bytesRead, expected.length);
<ide> assert.deepStrictEqual(bufferAsync, Buffer.from(expected));
<ide> }));
<ide><path>test/parallel/test-fs-write-buffer.js
<ide> common.refreshTmpDir();
<ide> // fs.write with all parameters provided:
<ide> {
<ide> const filename = path.join(common.tmpDir, 'write1.txt');
<del> fs.open(filename, 'w', 0o644, common.mustCall(function(err, fd) {
<add> fs.open(filename, 'w', 0o644, common.mustCall((err, fd) => {
<ide> assert.ifError(err);
<ide>
<del> const cb = common.mustCall(function(err, written) {
<add> const cb = common.mustCall((err, written) => {
<ide> assert.ifError(err);
<ide>
<ide> assert.strictEqual(expected.length, written);
<ide> fs.closeSync(fd);
<ide>
<ide> var found = fs.readFileSync(filename, 'utf8');
<del> assert.deepStrictEqual(expected.toString(), found);
<add> assert.strictEqual(expected.toString(), found);
<ide> });
<ide>
<ide> fs.write(fd, expected, 0, expected.length, null, cb);
<ide> common.refreshTmpDir();
<ide> // fs.write with a buffer, without the length parameter:
<ide> {
<ide> const filename = path.join(common.tmpDir, 'write2.txt');
<del> fs.open(filename, 'w', 0o644, common.mustCall(function(err, fd) {
<add> fs.open(filename, 'w', 0o644, common.mustCall((err, fd) => {
<ide> assert.ifError(err);
<ide>
<del> const cb = common.mustCall(function(err, written) {
<add> const cb = common.mustCall((err, written) => {
<ide> assert.ifError(err);
<ide>
<ide> assert.strictEqual(2, written);
<ide> fs.closeSync(fd);
<ide>
<ide> const found = fs.readFileSync(filename, 'utf8');
<del> assert.deepStrictEqual('lo', found);
<add> assert.strictEqual('lo', found);
<ide> });
<ide>
<ide> fs.write(fd, Buffer.from('hello'), 3, cb);
<ide> common.refreshTmpDir();
<ide> // fs.write with offset and length passed as undefined followed by the callback:
<ide> {
<ide> const filename = path.join(common.tmpDir, 'write5.txt');
<del> fs.open(filename, 'w', 0o644, common.mustCall(function(err, fd) {
<add> fs.open(filename, 'w', 0o644, common.mustCall((err, fd) => {
<ide> assert.ifError(err);
<ide>
<del> const cb = common.mustCall(function(err, written) {
<add> const cb = common.mustCall((err, written) => {
<ide> assert.ifError(err);
<ide>
<ide> assert.strictEqual(expected.length, written);
<ide> fs.closeSync(fd);
<ide>
<ide> const found = fs.readFileSync(filename, 'utf8');
<del> assert.deepStrictEqual(expected.toString(), found);
<add> assert.strictEqual(expected.toString(), found);
<ide> });
<ide>
<ide> fs.write(fd, expected, undefined, undefined, cb);
<ide> common.refreshTmpDir();
<ide> // fs.write with a Uint8Array, without the offset and length parameters:
<ide> {
<ide> const filename = path.join(common.tmpDir, 'write6.txt');
<del> fs.open(filename, 'w', 0o644, common.mustCall(function(err, fd) {
<add> fs.open(filename, 'w', 0o644, common.mustCall((err, fd) => {
<ide> assert.ifError(err);
<ide>
<del> const cb = common.mustCall(function(err, written) {
<add> const cb = common.mustCall((err, written) => {
<ide> assert.ifError(err);
<ide>
<ide> assert.strictEqual(expected.length, written);
<ide> fs.closeSync(fd);
<ide>
<ide> const found = fs.readFileSync(filename, 'utf8');
<del> assert.deepStrictEqual(expected.toString(), found);
<add> assert.strictEqual(expected.toString(), found);
<ide> });
<ide>
<ide> fs.write(fd, Uint8Array.from(expected), cb);
| 2
|
Javascript
|
Javascript
|
retain filter settings
|
a56e9baae23cb2e2abbae73606dda1694548f29f
|
<ide><path>src/renderers/WebGLCubeRenderTarget.js
<ide> WebGLCubeRenderTarget.prototype.fromEquirectangularTexture = function ( renderer
<ide> this.texture.format = texture.format;
<ide> this.texture.encoding = texture.encoding;
<ide>
<add> this.texture.generateMipmaps = texture.generateMipmaps;
<add> this.texture.minFilter = texture.minFilter;
<add> this.texture.magFilter = texture.magFilter;
<add>
<ide> const scene = new Scene();
<ide>
<ide> const shader = {
| 1
|
PHP
|
PHP
|
fix incorrect path list
|
24692b036bef38168e8851d601a1a3802caaf978
|
<ide><path>templates/Error/missing_cell_template.php
<ide> </p>
<ide> <ul>
<ide> <?php
<del> $paths = $this->_paths($this->plugin);
<ide> foreach ($paths as $path) :
<ide> if (strpos($path, CORE_PATH) !== false) {
<ide> continue;
<ide><path>templates/Error/missing_layout.php
<ide> </p>
<ide> <ul>
<ide> <?php
<del> $paths = $this->_paths($this->plugin);
<ide> foreach ($paths as $path):
<ide> if (strpos($path, CORE_PATH) !== false) {
<ide> continue;
<ide><path>templates/Error/missing_template.php
<ide> </p>
<ide> <ul>
<ide> <?php
<del> $paths = $this->_paths($this->plugin);
<ide> foreach ($paths as $path):
<ide> if (strpos($path, CORE_PATH) !== false) {
<ide> continue;
<ide><path>tests/TestCase/View/ViewTest.php
<ide> public function testMissingTemplate()
<ide> $this->expectExceptionMessage('Template file `does_not_exist.php` could not be found');
<ide> $this->expectExceptionMessage('The following paths were searched');
<ide> $this->expectExceptionMessage('- `' . ROOT . DS . 'templates' . DS . 'does_not_exist.php`');
<del> $viewOptions = ['plugin' => null,
<add> $viewOptions = [
<add> 'plugin' => null,
<ide> 'name' => 'Pages',
<ide> 'viewPath' => 'Pages',
<ide> ];
<ide> public function testMissingLayout()
<ide> $this->expectExceptionMessage('Layout file `whatever.php` could not be found');
<ide> $this->expectExceptionMessage('The following paths were searched');
<ide> $this->expectExceptionMessage('- `' . ROOT . DS . 'templates' . DS . 'layout' . DS . 'whatever.php`');
<del> $viewOptions = ['plugin' => null,
<add> $viewOptions = [
<add> 'plugin' => null,
<ide> 'name' => 'Pages',
<ide> 'viewPath' => 'Pages',
<ide> 'layout' => 'whatever',
| 4
|
Mixed
|
Python
|
fix nel config and io, and n_sents functionality
|
b92f81d5da43da759e44f1e1c6859805873546a4
|
<ide><path>spacy/pipeline/entity_linker.py
<ide> default_config={
<ide> "model": DEFAULT_NEL_MODEL,
<ide> "labels_discard": [],
<add> "n_sents": 0,
<ide> "incl_prior": True,
<ide> "incl_context": True,
<ide> "entity_vector_length": 64,
<ide> def make_entity_linker(
<ide> model: Model,
<ide> *,
<ide> labels_discard: Iterable[str],
<add> n_sents: int,
<ide> incl_prior: bool,
<ide> incl_context: bool,
<ide> entity_vector_length: int,
<ide> def make_entity_linker(
<ide> representations. Given a batch of Doc objects, it should return a single
<ide> array, with one row per item in the batch.
<ide> labels_discard (Iterable[str]): NER labels that will automatically get a "NIL" prediction.
<add> n_sents (int): The number of neighbouring sentences to take into account.
<ide> incl_prior (bool): Whether or not to include prior probabilities from the KB in the model.
<ide> incl_context (bool): Whether or not to include the local context in the model.
<ide> entity_vector_length (int): Size of encoding vectors in the KB.
<ide> def make_entity_linker(
<ide> model,
<ide> name,
<ide> labels_discard=labels_discard,
<add> n_sents=n_sents,
<ide> incl_prior=incl_prior,
<ide> incl_context=incl_context,
<ide> entity_vector_length=entity_vector_length,
<ide> def __init__(
<ide> name: str = "entity_linker",
<ide> *,
<ide> labels_discard: Iterable[str],
<add> n_sents: int,
<ide> incl_prior: bool,
<ide> incl_context: bool,
<ide> entity_vector_length: int,
<ide> def __init__(
<ide> name (str): The component instance name, used to add entries to the
<ide> losses during training.
<ide> labels_discard (Iterable[str]): NER labels that will automatically get a "NIL" prediction.
<add> n_sents (int): The number of neighbouring sentences to take into account.
<ide> incl_prior (bool): Whether or not to include prior probabilities from the KB in the model.
<ide> incl_context (bool): Whether or not to include the local context in the model.
<ide> entity_vector_length (int): Size of encoding vectors in the KB.
<ide> def __init__(
<ide> self.vocab = vocab
<ide> self.model = model
<ide> self.name = name
<del> cfg = {
<del> "labels_discard": list(labels_discard),
<del> "incl_prior": incl_prior,
<del> "incl_context": incl_context,
<del> "entity_vector_length": entity_vector_length,
<del> }
<add> self.labels_discard = list(labels_discard)
<add> self.n_sents = n_sents
<add> self.incl_prior = incl_prior
<add> self.incl_context = incl_context
<ide> self.get_candidates = get_candidates
<del> self.cfg = dict(cfg)
<add> self.cfg = {}
<ide> self.distance = CosineDistance(normalize=False)
<ide> # how many neightbour sentences to take into account
<del> self.n_sents = cfg.get("n_sents", 0)
<ide> # create an empty KB by default. If you want to load a predefined one, specify it in 'initialize'.
<ide> self.kb = empty_kb(entity_vector_length)(self.vocab)
<ide>
<ide> def set_kb(self, kb_loader: Callable[[Vocab], KnowledgeBase]):
<ide> raise ValueError(Errors.E885.format(arg_type=type(kb_loader)))
<ide>
<ide> self.kb = kb_loader(self.vocab)
<del> self.cfg["entity_vector_length"] = self.kb.entity_vector_length
<ide>
<ide> def validate_kb(self) -> None:
<ide> # Raise an error if the knowledge base is not initialized.
<ide> def predict(self, docs: Iterable[Doc]) -> List[str]:
<ide> sent_doc = doc[start_token:end_token].as_doc()
<ide> # currently, the context is the same for each entity in a sentence (should be refined)
<ide> xp = self.model.ops.xp
<del> if self.cfg.get("incl_context"):
<add> if self.incl_context:
<ide> sentence_encoding = self.model.predict([sent_doc])[0]
<ide> sentence_encoding_t = sentence_encoding.T
<ide> sentence_norm = xp.linalg.norm(sentence_encoding_t)
<ide> for ent in sent.ents:
<ide> entity_count += 1
<del> to_discard = self.cfg.get("labels_discard", [])
<del> if to_discard and ent.label_ in to_discard:
<add> if ent.label_ in self.labels_discard:
<ide> # ignoring this entity - setting to NIL
<ide> final_kb_ids.append(self.NIL)
<ide> else:
<ide> def predict(self, docs: Iterable[Doc]) -> List[str]:
<ide> prior_probs = xp.asarray(
<ide> [c.prior_prob for c in candidates]
<ide> )
<del> if not self.cfg.get("incl_prior"):
<add> if not self.incl_prior:
<ide> prior_probs = xp.asarray(
<ide> [0.0 for _ in candidates]
<ide> )
<ide> scores = prior_probs
<ide> # add in similarity from the context
<del> if self.cfg.get("incl_context"):
<add> if self.incl_context:
<ide> entity_encodings = xp.asarray(
<ide> [c.entity_vector for c in candidates]
<ide> )
<ide><path>spacy/tests/pipeline/test_entity_linker.py
<ide> def create_candidates() -> Callable[[KnowledgeBase, "Span"], Iterable[Candidate]
<ide> assert doc[2].ent_kb_id_ == "Q2"
<ide>
<ide>
<add>def test_nel_nsents(nlp):
<add> """Test that n_sents can be set through the configuration"""
<add> entity_linker = nlp.add_pipe("entity_linker", config={})
<add> assert entity_linker.n_sents == 0
<add> entity_linker = nlp.replace_pipe("entity_linker", "entity_linker", config={"n_sents": 2})
<add> assert entity_linker.n_sents == 2
<add>
<add>
<ide> def test_vocab_serialization(nlp):
<ide> """Test that string information is retained across storage"""
<ide> mykb = KnowledgeBase(nlp.vocab, entity_vector_length=1)
<ide><path>spacy/tests/pipeline/test_pipe_methods.py
<ide> def test_replace_last_pipe(nlp):
<ide> def test_replace_pipe_config(nlp):
<ide> nlp.add_pipe("entity_linker")
<ide> nlp.add_pipe("sentencizer")
<del> assert nlp.get_pipe("entity_linker").cfg["incl_prior"] is True
<add> assert nlp.get_pipe("entity_linker").incl_prior is True
<ide> nlp.replace_pipe("entity_linker", "entity_linker", config={"incl_prior": False})
<del> assert nlp.get_pipe("entity_linker").cfg["incl_prior"] is False
<add> assert nlp.get_pipe("entity_linker").incl_prior is False
<ide>
<ide>
<ide> @pytest.mark.parametrize("old_name,new_name", [("old_pipe", "new_pipe")])
<ide><path>website/docs/api/entitylinker.md
<ide> architectures and their arguments and hyperparameters.
<ide> > from spacy.pipeline.entity_linker import DEFAULT_NEL_MODEL
<ide> > config = {
<ide> > "labels_discard": [],
<add>> "n_sents": 0,
<ide> > "incl_prior": True,
<ide> > "incl_context": True,
<ide> > "model": DEFAULT_NEL_MODEL,
<ide> architectures and their arguments and hyperparameters.
<ide> | Setting | Description |
<ide> | ---------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ |
<ide> | `labels_discard` | NER labels that will automatically get a "NIL" prediction. Defaults to `[]`. ~~Iterable[str]~~ |
<add>| `n_sents` | The number of neighbouring sentences to take into account. Defaults to 0. ~~int~~ |
<ide> | `incl_prior` | Whether or not to include prior probabilities from the KB in the model. Defaults to `True`. ~~bool~~ |
<ide> | `incl_context` | Whether or not to include the local context in the model. Defaults to `True`. ~~bool~~ |
<ide> | `model` | The [`Model`](https://thinc.ai/docs/api-model) powering the pipeline component. Defaults to [EntityLinker](/api/architectures#EntityLinker). ~~Model~~ |
<ide> custom knowledge base, you should either call
<ide> | `entity_vector_length` | Size of encoding vectors in the KB. ~~int~~ |
<ide> | `get_candidates` | Function that generates plausible candidates for a given `Span` object. ~~Callable[[KnowledgeBase, Span], Iterable[Candidate]]~~ |
<ide> | `labels_discard` | NER labels that will automatically get a `"NIL"` prediction. ~~Iterable[str]~~ |
<add>| `n_sents` | The number of neighbouring sentences to take into account. ~~int~~ |
<ide> | `incl_prior` | Whether or not to include prior probabilities from the KB in the model. ~~bool~~ |
<ide> | `incl_context` | Whether or not to include the local context in the model. ~~bool~~ |
<ide>
<ide> pipe's entity linking model and context encoder. Delegates to
<ide> > losses = entity_linker.update(examples, sgd=optimizer)
<ide> > ```
<ide>
<del>| Name | Description |
<del>| ----------------- | ---------------------------------------------------------------------------------------------------------------------------------- |
<del>| `examples` | A batch of [`Example`](/api/example) objects to learn from. ~~Iterable[Example]~~ |
<del>| _keyword-only_ | |
<del>| `drop` | The dropout rate. ~~float~~ |
<del>| `sgd` | An optimizer. Will be created via [`create_optimizer`](#create_optimizer) if not set. ~~Optional[Optimizer]~~ |
<del>| `losses` | Optional record of the loss during training. Updated using the component name as the key. ~~Optional[Dict[str, float]]~~ |
<del>| **RETURNS** | The updated `losses` dictionary. ~~Dict[str, float]~~ |
<add>| Name | Description |
<add>| -------------- | ------------------------------------------------------------------------------------------------------------------------ |
<add>| `examples` | A batch of [`Example`](/api/example) objects to learn from. ~~Iterable[Example]~~ |
<add>| _keyword-only_ | |
<add>| `drop` | The dropout rate. ~~float~~ |
<add>| `sgd` | An optimizer. Will be created via [`create_optimizer`](#create_optimizer) if not set. ~~Optional[Optimizer]~~ |
<add>| `losses` | Optional record of the loss during training. Updated using the component name as the key. ~~Optional[Dict[str, float]]~~ |
<add>| **RETURNS** | The updated `losses` dictionary. ~~Dict[str, float]~~ |
<ide>
<ide> ## EntityLinker.score {#score tag="method" new="3"}
<ide>
| 4
|
Python
|
Python
|
add couple of test for authtoken
|
514b5a6dd11f9576c839b6a2469b48a0a1f91b89
|
<ide><path>tests/test_authtoken.py
<add>import pytest
<add>from django.contrib.admin import site
<add>from django.contrib.auth.models import User
<add>from django.test import TestCase
<add>
<add>from rest_framework.authtoken.admin import TokenAdmin
<add>from rest_framework.authtoken.models import Token
<add>from rest_framework.authtoken.serializers import AuthTokenSerializer
<add>from rest_framework.exceptions import ValidationError
<add>
<add>
<add>class AuthTokenTests(TestCase):
<add>
<add> def setUp(self):
<add> self.site = site
<add> self.user = User.objects.create_user(username='test_user')
<add> self.token = Token.objects.create(key='test token', user=self.user)
<add>
<add> def test_model_admin_displayed_fields(self):
<add> mock_request = object()
<add> token_admin = TokenAdmin(self.token, self.site)
<add> assert token_admin.get_fields(mock_request) == ('user',)
<add>
<add> def test_token_string_representation(self):
<add> assert str(self.token) == 'test token'
<add>
<add> def test_validate_raise_error_if_no_credentials_provided(self):
<add> with pytest.raises(ValidationError):
<add> AuthTokenSerializer().validate({})
| 1
|
Text
|
Text
|
add pending-deprecation to deprecations list
|
4efde4d0d4934dd8b47c11011e47eb27ad78a7ae
|
<ide><path>doc/api/deprecations.md
<ide> Node.js utilizes three kinds of Deprecations:
<ide>
<ide> A Documentation-only deprecation is one that is expressed only within the
<ide> Node.js API docs. These generate no side-effects while running Node.js.
<add>Some Documentation-only deprecations trigger a runtime warning when launched
<add>with [`--pending-deprecation`][] flag (or its alternative,
<add>`NODE_PENDING_DEPRECATION=1` environment variable), similarly to Runtime
<add>deprecations below. Documentation-only deprecations that support that flag
<add>are explicitly labeled as such in the
<add>[list of Deprecated APIs](#deprecations_list_of_deprecated_apis).
<ide>
<ide> A Runtime deprecation will, by default, generate a process warning that will
<ide> be printed to `stderr` the first time the deprecated API is used. When the
<ide> be used.
<ide> <a id="DEP0005"></a>
<ide> ### DEP0005: Buffer() constructor
<ide>
<del>Type: Documentation-only
<add>Type: Documentation-only (supports [`--pending-deprecation`][])
<ide>
<ide> The `Buffer()` function and `new Buffer()` constructor are deprecated due to
<ide> API usability issues that can potentially lead to accidental security issues.
<ide> a future version at which point only authentication tag lengths of 128, 120,
<ide> is not included in this list will be considered invalid in compliance with
<ide> [NIST SP 800-38D][].
<ide>
<add>[`--pending-deprecation`]: cli.html#cli_pending_deprecation
<ide> [`Buffer.allocUnsafeSlow(size)`]: buffer.html#buffer_class_method_buffer_allocunsafeslow_size
<ide> [`Buffer.from(array)`]: buffer.html#buffer_class_method_buffer_from_array
<ide> [`Buffer.from(buffer)`]: buffer.html#buffer_class_method_buffer_from_buffer
| 1
|
Text
|
Text
|
add benjamingr to collaborator list
|
a74bf87a48b99c004a9a2937a90b9366fce78efc
|
<ide><path>README.md
<ide> information about the governance of the Node.js project, see
<ide>
<ide> ### Collaborators
<ide>
<add>* [benjamingr](https://github.com/benjamingr) - **Benjamin Gruenbaum** <benjamingr@gmail.com>
<ide> * [brendanashworth](https://github.com/brendanashworth) - **Brendan Ashworth** <brendan.ashworth@me.com>
<ide> * [calvinmetcalf](https://github.com/calvinmetcalf) - **Calvin Metcalf** <calvin.metcalf@gmail.com>
<ide> * [domenic](https://github.com/domenic) - **Domenic Denicola** <d@domenic.me>
| 1
|
Text
|
Text
|
add cryptapi to docs homepage
|
c05998f5ddedec7c8c012a9be08aa41130a46b75
|
<ide><path>docs/index.md
<ide> continued development by **[signing up for a paid plan][funding]**.
<ide> <li><a href="https://rollbar.com" style="background-image: url(https://fund-rest-framework.s3.amazonaws.com/rollbar2.png)">Rollbar</a></li>
<ide> <li><a href="https://retool.com/?utm_source=djangorest&utm_medium=sponsorship" style="background-image: url(https://fund-rest-framework.s3.amazonaws.com/retool-sidebar.png)">Retool</a></li>
<ide> <li><a href="https://bit.io/jobs?utm_source=DRF&utm_medium=sponsor&utm_campaign=DRF_sponsorship" style="background-image: url(https://fund-rest-framework.s3.amazonaws.com/bitio_logo_gold_background.png)">bit.io</a></li>
<del> <li><a href="https://posthog.com?utm_source=DRF&utm_medium=sponsor&utm_campaign=DRF_sponsorship" style="background-image: url(https://fund-rest-framework.s3.amazonaws.com/posthog-130.png)">PostHog</a></li>
<add> <li><a href="https://posthog.com?utm_source=DRF&utm_medium=sponsor&utm_campaign=DRF_sponsorship" style="background-image: url(https://fund-rest-framework.s3.amazonaws.com/135996800-d49fe024-32d9-441a-98d9-4c7596287a67.png)">PostHog</a></li>
<add> <li><a href="https://cryptapi.io" style="background-image: url(https://fund-rest-framework.s3.amazonaws.com/cryptapi.png)">CryptAPI</a></li>
<ide> </ul>
<ide> <div style="clear: both; padding-bottom: 20px;"></div>
<ide>
<del>*Many thanks to all our [wonderful sponsors][sponsors], and in particular to our premium backers, [Sentry](https://getsentry.com/welcome/), [Stream](https://getstream.io/?utm_source=drf&utm_medium=sponsorship&utm_content=developer), [ESG](https://software.esg-usa.com/), [Rollbar](https://rollbar.com/?utm_source=django&utm_medium=sponsorship&utm_campaign=freetrial), [Cadre](https://cadre.com), [Kloudless](https://hubs.ly/H0f30Lf0), [Lights On Software](https://lightsonsoftware.com), [Retool](https://retool.com/?utm_source=djangorest&utm_medium=sponsorship), [bit.io](https://bit.io/jobs?utm_source=DRF&utm_medium=sponsor&utm_campaign=DRF_sponsorship), and [bit.io](https://posthog.com?utm_source=DRF&utm_medium=sponsor&utm_campaign=DRF_sponsorship).*
<add>*Many thanks to all our [wonderful sponsors][sponsors], and in particular to our premium backers, [Sentry](https://getsentry.com/welcome/), [Stream](https://getstream.io/?utm_source=drf&utm_medium=sponsorship&utm_content=developer), [ESG](https://software.esg-usa.com/), [Rollbar](https://rollbar.com/?utm_source=django&utm_medium=sponsorship&utm_campaign=freetrial), [Cadre](https://cadre.com), [Kloudless](https://hubs.ly/H0f30Lf0), [Lights On Software](https://lightsonsoftware.com), [Retool](https://retool.com/?utm_source=djangorest&utm_medium=sponsorship), [bit.io](https://bit.io/jobs?utm_source=DRF&utm_medium=sponsor&utm_campaign=DRF_sponsorship), [PostHog](https://posthog.com?utm_source=DRF&utm_medium=sponsor&utm_campaign=DRF_sponsorship), and [CryptAPI](https://cryptapi.io).*
<ide>
<ide> ---
<ide>
| 1
|
PHP
|
PHP
|
add method to driverinterface
|
1dcb47ef6afb939d97ce48b5233d81a2c0d87fbe
|
<ide><path>src/Database/Driver.php
<ide> public function enableAutoQuoting(bool $enable = true)
<ide> }
<ide>
<ide> /**
<del> * Disable auto quoting of identifiers in queries.
<del> *
<del> * @return $this
<add> * @inheritDoc
<ide> */
<ide> public function disableAutoQuoting()
<ide> {
<ide><path>src/Database/DriverInterface.php
<ide>
<ide> /**
<ide> * Interface for database driver.
<del> *
<del> * @method $this disableAutoQuoting()
<ide> */
<ide> interface DriverInterface
<ide> {
<ide> public function isConnected(): bool;
<ide> */
<ide> public function enableAutoQuoting(bool $enable = true);
<ide>
<add> /**
<add> * Disable auto quoting of identifiers in queries.
<add> *
<add> * @return $this
<add> */
<add> public function disableAutoQuoting();
<add>
<ide> /**
<ide> * Returns whether or not this driver should automatically quote identifiers
<ide> * in queries.
| 2
|
Ruby
|
Ruby
|
add a deprecation message to activerecord.errors
|
821a160a49529f449605e127e26b7376cc83d4d6
|
<ide><path>activerecord/lib/active_record/railtie.rb
<ide> class Railtie < Rails::Railtie
<ide> end
<ide> end
<ide>
<add> initializer "active_record.i18n_deprecation" do
<add> require 'active_support/i18n'
<add>
<add> begin
<add> I18n.t(:"activerecord.errors", :raise => true)
<add> warn "[DEPRECATION] \"activerecord.errors\" namespace is deprecated in I18n " <<
<add> "yml files, please use just \"errors\" instead."
<add> rescue Exception => e
<add> # No message then.
<add> end
<add> end
<ide> end
<ide> end
| 1
|
Python
|
Python
|
add missing type hints for qdqbertmodel
|
d37a68e6850e7c6941108de76a8e35ba7e726e51
|
<ide><path>src/transformers/models/qdqbert/modeling_qdqbert.py
<ide> import math
<ide> import os
<ide> import warnings
<del>from typing import Optional
<add>from typing import Dict, List, Optional, Tuple, Union
<ide>
<ide> import torch
<ide> import torch.utils.checkpoint
<ide> ]
<ide>
<ide>
<del>def load_tf_weights_in_qdqbert(model, config, tf_checkpoint_path):
<add>def load_tf_weights_in_qdqbert(model, tf_checkpoint_path):
<ide> """Load tf checkpoints in a pytorch model."""
<ide> try:
<ide> import re
<ide> class QDQBertModel(QDQBertPreTrainedModel):
<ide> `add_cross_attention` set to `True`; an `encoder_hidden_states` is then expected as an input to the forward pass.
<ide> """
<ide>
<del> def __init__(self, config, add_pooling_layer=True):
<add> def __init__(self, config, add_pooling_layer: bool = True):
<ide> requires_backends(self, "pytorch_quantization")
<ide> super().__init__(config)
<ide> self.config = config
<ide> def get_input_embeddings(self):
<ide> def set_input_embeddings(self, value):
<ide> self.embeddings.word_embeddings = value
<ide>
<del> def _prune_heads(self, heads_to_prune):
<add> def _prune_heads(self, heads_to_prune: Dict[int, List[int]]):
<ide> """
<ide> Prunes heads of the model. heads_to_prune: dict of {layer_num: list of heads to prune in this layer} See base
<ide> class PreTrainedModel
<ide> class PreTrainedModel
<ide> )
<ide> def forward(
<ide> self,
<del> input_ids=None,
<del> attention_mask=None,
<del> token_type_ids=None,
<del> position_ids=None,
<del> head_mask=None,
<del> inputs_embeds=None,
<del> encoder_hidden_states=None,
<del> encoder_attention_mask=None,
<del> past_key_values=None,
<del> use_cache=None,
<del> output_attentions=None,
<del> output_hidden_states=None,
<del> return_dict=None,
<del> ):
<add> input_ids: Optional[torch.LongTensor] = None,
<add> attention_mask: Optional[torch.FloatTensor] = None,
<add> token_type_ids: Optional[torch.LongTensor] = None,
<add> position_ids: Optional[torch.LongTensor] = None,
<add> head_mask: Optional[torch.FloatTensor] = None,
<add> inputs_embeds: Optional[torch.FloatTensor] = None,
<add> encoder_hidden_states: Optional[torch.FloatTensor] = None,
<add> encoder_attention_mask: Optional[torch.FloatTensor] = None,
<add> past_key_values: Optional[Tuple[Tuple[torch.FloatTensor]]] = None,
<add> use_cache: Optional[bool] = None,
<add> output_attentions: Optional[bool] = None,
<add> output_hidden_states: Optional[bool] = None,
<add> return_dict: Optional[bool] = None,
<add> ) -> Union[Tuple, BaseModelOutputWithPoolingAndCrossAttentions]:
<ide> r"""
<ide> encoder_hidden_states (`torch.FloatTensor` of shape `(batch_size, sequence_length, hidden_size)`, *optional*):
<ide> Sequence of hidden-states at the output of the last layer of the encoder. Used in the cross-attention if
<ide> def set_output_embeddings(self, new_embeddings):
<ide> @replace_return_docstrings(output_type=CausalLMOutputWithCrossAttentions, config_class=_CONFIG_FOR_DOC)
<ide> def forward(
<ide> self,
<del> input_ids=None,
<del> attention_mask=None,
<del> token_type_ids=None,
<del> position_ids=None,
<del> head_mask=None,
<del> inputs_embeds=None,
<del> encoder_hidden_states=None,
<del> encoder_attention_mask=None,
<del> labels=None,
<del> past_key_values=None,
<del> use_cache=None,
<del> output_attentions=None,
<del> output_hidden_states=None,
<del> return_dict=None,
<del> ):
<add> input_ids: Optional[torch.LongTensor] = None,
<add> attention_mask: Optional[torch.Tensor] = None,
<add> token_type_ids: Optional[torch.LongTensor] = None,
<add> position_ids: Optional[torch.LongTensor] = None,
<add> head_mask: Optional[torch.Tensor] = None,
<add> inputs_embeds: Optional[torch.Tensor] = None,
<add> encoder_hidden_states: Optional[torch.FloatTensor] = None,
<add> encoder_attention_mask: Optional[torch.FloatTensor] = None,
<add> labels: Optional[torch.LongTensor] = None,
<add> past_key_values: Optional[Tuple[Tuple[torch.LongTensor]]] = None,
<add> use_cache: Optional[bool] = None,
<add> output_attentions: Optional[bool] = None,
<add> output_hidden_states: Optional[bool] = None,
<add> return_dict: Optional[bool] = None,
<add> ) -> Union[Tuple, CausalLMOutputWithCrossAttentions]:
<ide> r"""
<ide> encoder_hidden_states (`torch.FloatTensor` of shape `(batch_size, sequence_length, hidden_size)`, *optional*):
<ide> Sequence of hidden-states at the output of the last layer of the encoder. Used in the cross-attention if
<ide> def forward(
<ide> cross_attentions=outputs.cross_attentions,
<ide> )
<ide>
<del> def prepare_inputs_for_generation(self, input_ids, past=None, attention_mask=None, **model_kwargs):
<add> def prepare_inputs_for_generation(
<add> self,
<add> input_ids: Optional[torch.LongTensor],
<add> past=None,
<add> attention_mask: Optional[torch.Tensor] = None,
<add> **model_kwargs
<add> ):
<ide> input_shape = input_ids.shape
<ide> # if model is used as a decoder in encoder-decoder model, the decoder attention mask is created on the fly
<ide> if attention_mask is None:
<ide> def set_output_embeddings(self, new_embeddings):
<ide> )
<ide> def forward(
<ide> self,
<del> input_ids=None,
<del> attention_mask=None,
<del> token_type_ids=None,
<del> position_ids=None,
<del> head_mask=None,
<del> inputs_embeds=None,
<del> encoder_hidden_states=None,
<del> encoder_attention_mask=None,
<del> labels=None,
<del> output_attentions=None,
<del> output_hidden_states=None,
<del> return_dict=None,
<del> ):
<add> input_ids: Optional[torch.LongTensor] = None,
<add> attention_mask: Optional[torch.FloatTensor] = None,
<add> token_type_ids: Optional[torch.LongTensor] = None,
<add> position_ids: Optional[torch.LongTensor] = None,
<add> head_mask: Optional[torch.FloatTensor] = None,
<add> inputs_embeds: Optional[torch.FloatTensor] = None,
<add> encoder_hidden_states: Optional[torch.FloatTensor] = None,
<add> encoder_attention_mask: Optional[torch.FloatTensor] = None,
<add> labels: Optional[torch.LongTensor] = None,
<add> output_attentions: Optional[bool] = None,
<add> output_hidden_states: Optional[bool] = None,
<add> return_dict: Optional[bool] = None,
<add> ) -> Union[Tuple, MaskedLMOutput]:
<ide> r"""
<ide> labels (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
<ide> Labels for computing the masked language modeling loss. Indices should be in `[-100, 0, ...,
<ide> def forward(
<ide> attentions=outputs.attentions,
<ide> )
<ide>
<del> def prepare_inputs_for_generation(self, input_ids, attention_mask=None, **model_kwargs):
<add> def prepare_inputs_for_generation(
<add> self, input_ids: torch.LongTensor, attention_mask: Optional[torch.FloatTensor] = None, **model_kwargs
<add> ):
<ide> input_shape = input_ids.shape
<ide> effective_batch_size = input_shape[0]
<ide>
<ide> def __init__(self, config):
<ide> @replace_return_docstrings(output_type=NextSentencePredictorOutput, config_class=_CONFIG_FOR_DOC)
<ide> def forward(
<ide> self,
<del> input_ids=None,
<del> attention_mask=None,
<del> token_type_ids=None,
<del> position_ids=None,
<del> head_mask=None,
<del> inputs_embeds=None,
<del> labels=None,
<del> output_attentions=None,
<del> output_hidden_states=None,
<del> return_dict=None,
<add> input_ids: Optional[torch.LongTensor] = None,
<add> attention_mask: Optional[torch.FloatTensor] = None,
<add> token_type_ids: Optional[torch.LongTensor] = None,
<add> position_ids: Optional[torch.LongTensor] = None,
<add> head_mask: Optional[torch.FloatTensor] = None,
<add> inputs_embeds: Optional[torch.FloatTensor] = None,
<add> labels: Optional[torch.LongTensor] = None,
<add> output_attentions: Optional[bool] = None,
<add> output_hidden_states: Optional[bool] = None,
<add> return_dict: Optional[bool] = None,
<ide> **kwargs,
<del> ):
<add> ) -> Union[Tuple, NextSentencePredictorOutput]:
<ide> r"""
<ide> labels (`torch.LongTensor` of shape `(batch_size,)`, *optional*):
<ide> Labels for computing the next sequence prediction (classification) loss. Input should be a sequence pair
<ide> def __init__(self, config):
<ide> )
<ide> def forward(
<ide> self,
<del> input_ids=None,
<del> attention_mask=None,
<del> token_type_ids=None,
<del> position_ids=None,
<del> head_mask=None,
<del> inputs_embeds=None,
<del> labels=None,
<del> output_attentions=None,
<del> output_hidden_states=None,
<del> return_dict=None,
<del> ):
<add> input_ids: Optional[torch.LongTensor] = None,
<add> attention_mask: Optional[torch.FloatTensor] = None,
<add> token_type_ids: Optional[torch.LongTensor] = None,
<add> position_ids: Optional[torch.LongTensor] = None,
<add> head_mask: Optional[torch.FloatTensor] = None,
<add> inputs_embeds: Optional[torch.FloatTensor] = None,
<add> labels: Optional[torch.LongTensor] = None,
<add> output_attentions: Optional[bool] = None,
<add> output_hidden_states: Optional[bool] = None,
<add> return_dict: Optional[bool] = None,
<add> ) -> Union[Tuple, SequenceClassifierOutput]:
<ide> r"""
<ide> labels (`torch.LongTensor` of shape `(batch_size,)`, *optional*):
<ide> Labels for computing the sequence classification/regression loss. Indices should be in `[0, ...,
<ide> def __init__(self, config):
<ide> )
<ide> def forward(
<ide> self,
<del> input_ids=None,
<del> attention_mask=None,
<del> token_type_ids=None,
<del> position_ids=None,
<del> head_mask=None,
<del> inputs_embeds=None,
<del> labels=None,
<del> output_attentions=None,
<del> output_hidden_states=None,
<del> return_dict=None,
<del> ):
<add> input_ids: Optional[torch.LongTensor] = None,
<add> attention_mask: Optional[torch.FloatTensor] = None,
<add> token_type_ids: Optional[torch.LongTensor] = None,
<add> position_ids: Optional[torch.LongTensor] = None,
<add> head_mask: Optional[torch.FloatTensor] = None,
<add> inputs_embeds: Optional[torch.FloatTensor] = None,
<add> labels: Optional[torch.LongTensor] = None,
<add> output_attentions: Optional[bool] = None,
<add> output_hidden_states: Optional[bool] = None,
<add> return_dict: Optional[bool] = None,
<add> ) -> Union[Tuple, MultipleChoiceModelOutput]:
<ide> r"""
<ide> labels (`torch.LongTensor` of shape `(batch_size,)`, *optional*):
<ide> Labels for computing the multiple choice classification loss. Indices should be in `[0, ...,
<ide> def __init__(self, config):
<ide> )
<ide> def forward(
<ide> self,
<del> input_ids=None,
<del> attention_mask=None,
<del> token_type_ids=None,
<del> position_ids=None,
<del> head_mask=None,
<del> inputs_embeds=None,
<del> labels=None,
<del> output_attentions=None,
<del> output_hidden_states=None,
<del> return_dict=None,
<del> ):
<add> input_ids: Optional[torch.LongTensor] = None,
<add> attention_mask: Optional[torch.FloatTensor] = None,
<add> token_type_ids: Optional[torch.LongTensor] = None,
<add> position_ids: Optional[torch.LongTensor] = None,
<add> head_mask: Optional[torch.FloatTensor] = None,
<add> inputs_embeds: Optional[torch.FloatTensor] = None,
<add> labels: Optional[torch.LongTensor] = None,
<add> output_attentions: Optional[bool] = None,
<add> output_hidden_states: Optional[bool] = None,
<add> return_dict: Optional[bool] = None,
<add> ) -> Union[Tuple, TokenClassifierOutput]:
<ide> r"""
<ide> labels (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
<ide> Labels for computing the token classification loss. Indices should be in `[0, ..., config.num_labels - 1]`.
<ide> def __init__(self, config):
<ide> )
<ide> def forward(
<ide> self,
<del> input_ids=None,
<del> attention_mask=None,
<del> token_type_ids=None,
<del> position_ids=None,
<del> head_mask=None,
<del> inputs_embeds=None,
<del> start_positions=None,
<del> end_positions=None,
<del> output_attentions=None,
<del> output_hidden_states=None,
<del> return_dict=None,
<del> ):
<add> input_ids: Optional[torch.LongTensor] = None,
<add> attention_mask: Optional[torch.FloatTensor] = None,
<add> token_type_ids: Optional[torch.LongTensor] = None,
<add> position_ids: Optional[torch.LongTensor] = None,
<add> head_mask: Optional[torch.FloatTensor] = None,
<add> inputs_embeds: Optional[torch.FloatTensor] = None,
<add> start_positions: Optional[torch.LongTensor] = None,
<add> end_positions: Optional[torch.LongTensor] = None,
<add> output_attentions: Optional[bool] = None,
<add> output_hidden_states: Optional[bool] = None,
<add> return_dict: Optional[bool] = None,
<add> ) -> Union[Tuple, QuestionAnsweringModelOutput]:
<ide> r"""
<ide> start_positions (`torch.LongTensor` of shape `(batch_size,)`, *optional*):
<ide> Labels for position (index) of the start of the labelled span for computing the token classification loss.
| 1
|
Javascript
|
Javascript
|
update time formatting
|
204248a0c3597b99dc4a706203292141fbaf85ed
|
<ide><path>lib/internal/console/constructor.js
<ide> // The Console constructor is not actually used to construct the global
<ide> // console. It's exported for backwards compatibility.
<ide>
<del>const { Object, ObjectPrototype, Reflect } = primordials;
<add>const { Object, ObjectPrototype, Reflect, Math } = primordials;
<ide>
<ide> const { trace } = internalBinding('trace_events');
<ide> const {
<ide> function timeLogImpl(self, name, label, data) {
<ide> return true;
<ide> }
<ide>
<add>function pad(value) {
<add> return `${value}`.padStart(2, '0');
<add>}
<add>
<ide> function formatTime(ms) {
<del> let value = ms;
<del> let unit = 'ms';
<del>
<del> if (ms >= kHour) {
<del> value = ms / kHour;
<del> unit = 'h';
<del> } else if (ms >= kMinute) {
<del> value = ms / kMinute;
<del> unit = 'min';
<del> } else if (ms >= kSecond) {
<del> value = ms / kSecond;
<del> unit = 's';
<add> let hours = 0;
<add> let minutes = 0;
<add> let seconds = 0;
<add>
<add> if (ms >= kSecond) {
<add> if (ms >= kMinute) {
<add> if (ms >= kHour) {
<add> hours = Math.floor(ms / kHour);
<add> ms = ms % kHour;
<add> }
<add> minutes = Math.floor(ms / kMinute);
<add> ms = ms % kMinute;
<add> }
<add> seconds = ms / kSecond;
<add> }
<add>
<add> if (hours !== 0 || minutes !== 0) {
<add> [seconds, ms] = seconds.toFixed(3).split('.');
<add> const res = hours !== 0 ? `${hours}:${pad(minutes)}` : minutes;
<add> return `${res}:${pad(seconds)}.${ms} (${hours !== 0 ? 'h:m' : ''}m:ss.mmm)`;
<add> }
<add>
<add> if (seconds !== 0) {
<add> return `${seconds.toFixed(3)}s`;
<ide> }
<ide>
<del> return value.toFixed(3) + unit;
<add> return `${Number(ms.toFixed(3))}ms`;
<ide> }
<ide>
<ide> const keyKey = 'Key';
<ide><path>test/parallel/test-console-formatTime.js
<ide> require('../common');
<ide> const { formatTime } = require('internal/console/constructor');
<ide> const assert = require('assert');
<ide>
<del>const test1 = formatTime(100);
<del>const test2 = formatTime(1500);
<del>const test3 = formatTime(60300);
<del>const test4 = formatTime(4000000);
<del>
<del>assert.strictEqual(test1, '100.000ms');
<del>assert.strictEqual(test2, '1.500s');
<del>assert.strictEqual(test3, '1.005min');
<del>assert.strictEqual(test4, '1.111h');
<add>assert.strictEqual(formatTime(100.0096), '100.01ms');
<add>assert.strictEqual(formatTime(100.0115), '100.011ms');
<add>assert.strictEqual(formatTime(1500.04), '1.500s');
<add>assert.strictEqual(formatTime(1000.056), '1.000s');
<add>assert.strictEqual(formatTime(60300.3), '1:00.300 (m:ss.mmm)');
<add>assert.strictEqual(formatTime(4000457.4), '1:06:40.457 (h:mm:ss.mmm)');
<add>assert.strictEqual(formatTime(3601310.4), '1:00:01.310 (h:mm:ss.mmm)');
<add>assert.strictEqual(formatTime(3213601017.6), '892:40:01.018 (h:mm:ss.mmm)');
<ide><path>test/parallel/test-console.js
<ide> assert.ok(strings[0].includes('foo: { bar: { baz:'));
<ide> assert.ok(strings[0].includes('quux'));
<ide> assert.ok(strings.shift().includes('quux: true'));
<ide>
<del>assert.ok(/^label: \d+\.\d{3}(ms|s|min|h)$/.test(strings.shift().trim()));
<del>assert.ok(/^__proto__: \d+\.\d{3}(ms|s|min|h)$/.test(strings.shift().trim()));
<del>assert.ok(/^constructor: \d+\.\d{3}(ms|s|min|h)$/.test(strings.shift().trim()));
<del>assert.ok(/^hasOwnProperty: \d+\.\d{3}(ms|s|min|h)$/.test(strings.shift().trim()));
<add>assert.ok(/^label: \d+(\.\d{1,3})?(ms|s)$/.test(strings.shift().trim()));
<add>assert.ok(/^__proto__: \d+(\.\d{1,3})?(ms|s)$/.test(strings.shift().trim()));
<add>assert.ok(/^constructor: \d+(\.\d{1,3})?(ms|s)$/.test(strings.shift().trim()));
<add>assert.ok(/^hasOwnProperty: \d+(\.\d{1,3})?(ms|s)$/.test(strings.shift().trim()));
<ide>
<ide> // Verify that console.time() coerces label values to strings as expected
<del>assert.ok(/^: \d+\.\d{3}(ms|s|min|h)$/.test(strings.shift().trim()));
<del>assert.ok(/^\[object Object\]: \d+\.\d{3}(ms|s|min|h)$/.test(strings.shift().trim()));
<del>assert.ok(/^\[object Object\]: \d+\.\d{3}(ms|s|min|h)$/.test(strings.shift().trim()));
<del>assert.ok(/^null: \d+\.\d{3}(ms|s|min|h)$/.test(strings.shift().trim()));
<del>assert.ok(/^default: \d+\.\d{3}(ms|s|min|h)$/.test(strings.shift().trim()));
<del>assert.ok(/^default: \d+\.\d{3}(ms|s|min|h)$/.test(strings.shift().trim()));
<del>assert.ok(/^NaN: \d+\.\d{3}(ms|s|min|h)$/.test(strings.shift().trim()));
<del>
<del>assert.ok(/^log1: \d+\.\d{3}(ms|s|min|h)$/.test(strings.shift().trim()));
<del>assert.ok(/^log1: \d+\.\d{3}(ms|s|min|h) test$/.test(strings.shift().trim()));
<del>assert.ok(/^log1: \d+\.\d{3}(ms|s|min|h) {} \[ 1, 2, 3 ]$/.test(strings.shift().trim()));
<del>assert.ok(/^log1: \d+\.\d{3}(ms|s|min|h)$/.test(strings.shift().trim()));
<add>assert.ok(/^: \d+(\.\d{1,3})?(ms|s)$/.test(strings.shift().trim()));
<add>assert.ok(/^\[object Object\]: \d+(\.\d{1,3})?(ms|s)$/.test(strings.shift().trim()));
<add>assert.ok(/^\[object Object\]: \d+(\.\d{1,3})?(ms|s)$/.test(strings.shift().trim()));
<add>assert.ok(/^null: \d+(\.\d{1,3})?(ms|s)$/.test(strings.shift().trim()));
<add>assert.ok(/^default: \d+(\.\d{1,3})?(ms|s)$/.test(strings.shift().trim()));
<add>assert.ok(/^default: \d+(\.\d{1,3})?(ms|s)$/.test(strings.shift().trim()));
<add>assert.ok(/^NaN: \d+(\.\d{1,3})?(ms|s)$/.test(strings.shift().trim()));
<add>
<add>assert.ok(/^log1: \d+(\.\d{1,3})?(ms|s)$/.test(strings.shift().trim()));
<add>assert.ok(/^log1: \d+(\.\d{1,3})?(ms|s) test$/.test(strings.shift().trim()));
<add>assert.ok(/^log1: \d+(\.\d{1,3})?(ms|s) {} \[ 1, 2, 3 ]$/.test(strings.shift().trim()));
<add>assert.ok(/^log1: \d+(\.\d{1,3})?(ms|s)$/.test(strings.shift().trim()));
<ide>
<ide> // Make sure that we checked all strings
<ide> assert.strictEqual(strings.length, 0);
| 3
|
PHP
|
PHP
|
use app_path in global file. closes
|
8709c6c6b062658eab23abf18aada550fb2efde9
|
<ide><path>app/start/global.php
<ide> |
<ide> */
<ide>
<del>require __DIR__.'/../filters.php';
<ide>\ No newline at end of file
<add>require app_path().'/filters.php';
<ide>\ No newline at end of file
| 1
|
PHP
|
PHP
|
fix styleci warnings
|
959b547fb26af22aced8358e34c3355a0928f813
|
<ide><path>tests/Integration/Database/EloquentRelationshipsTest.php
<ide>
<ide> namespace Illuminate\Tests\Integration\Database\EloquentRelationshipsTest;
<ide>
<del>use Illuminate\Database\Eloquent\Relations\HasOneThrough;
<ide> use Orchestra\Testbench\TestCase;
<ide> use Illuminate\Database\Eloquent\Model;
<ide> use Illuminate\Database\Eloquent\Builder;
<ide> use Illuminate\Database\Eloquent\Relations\MorphMany;
<ide> use Illuminate\Database\Eloquent\Relations\MorphToMany;
<ide> use Illuminate\Database\Eloquent\Relations\BelongsToMany;
<add>use Illuminate\Database\Eloquent\Relations\HasOneThrough;
<ide> use Illuminate\Database\Eloquent\Relations\HasManyThrough;
<ide>
<ide> /**
| 1
|
Python
|
Python
|
add bloom support for token classification
|
358478e7296cf3348e11901ddca1c25e3886b260
|
<ide><path>examples/pytorch/token-classification/run_ner.py
<ide> def get_label_list(labels):
<ide> )
<ide>
<ide> tokenizer_name_or_path = model_args.tokenizer_name if model_args.tokenizer_name else model_args.model_name_or_path
<del> if config.model_type in {"gpt2", "roberta"}:
<add> if config.model_type in {"bloom", "gpt2", "roberta"}:
<ide> tokenizer = AutoTokenizer.from_pretrained(
<ide> tokenizer_name_or_path,
<ide> cache_dir=model_args.cache_dir,
<ide><path>examples/pytorch/token-classification/run_ner_no_trainer.py
<ide> def get_label_list(labels):
<ide> "You can do it from another script, save it, and load it from here, using --tokenizer_name."
<ide> )
<ide>
<del> if config.model_type in {"gpt2", "roberta"}:
<add> if config.model_type in {"bloom", "gpt2", "roberta"}:
<ide> tokenizer = AutoTokenizer.from_pretrained(tokenizer_name_or_path, use_fast=True, add_prefix_space=True)
<ide> else:
<ide> tokenizer = AutoTokenizer.from_pretrained(tokenizer_name_or_path, use_fast=True)
| 2
|
PHP
|
PHP
|
fix distinct problems in paginator
|
cd17761f7220d193ec265a436b396ae5a1a640bc
|
<ide><path>laravel/database/query.php
<ide> public function get($columns = array('*'))
<ide> * Get an aggregate value.
<ide> *
<ide> * @param string $aggregator
<del> * @param string $column
<add> * @param array $columns
<ide> * @return mixed
<ide> */
<del> public function aggregate($aggregator, $column)
<add> public function aggregate($aggregator, $columns)
<ide> {
<del> $this->aggregate = compact('aggregator', 'column');
<add> $this->aggregate = compact('aggregator', 'columns');
<ide>
<ide> $sql = $this->grammar->select($this);
<ide>
<ide> public function paginate($per_page = 20, $columns = array('*'))
<ide> // we have the count.
<ide> list($orderings, $this->orderings) = array($this->orderings, null);
<ide>
<del> $page = Paginator::page($total = $this->count(), $per_page);
<add> $page = Paginator::page($total = $this->count($columns), $per_page);
<ide>
<ide> $this->orderings = $orderings;
<ide>
<ide> public function __call($method, $parameters)
<ide>
<ide> if (in_array($method, array('count', 'min', 'max', 'avg', 'sum')))
<ide> {
<del> if ($method == 'count')
<del> {
<del> return $this->aggregate(strtoupper($method), '*');
<del> }
<del> else
<del> {
<del> return $this->aggregate(strtoupper($method), $parameters[0]);
<del> }
<add> if (count($parameters) == 0) $parameters[0] = '*';
<add>
<add> return $this->aggregate(strtoupper($method), (array) $parameters[0]);
<ide> }
<ide>
<ide> throw new \Exception("Method [$method] is not defined on the Query class.");
<ide><path>laravel/database/query/grammars/grammar.php
<ide> protected function selects(Query $query)
<ide> */
<ide> protected function aggregate(Query $query)
<ide> {
<del> $column = $this->wrap($query->aggregate['column']);
<add> $column = $this->columnize($query->aggregate['columns']);
<add>
<add> if ($query->distinct and $column !== '*') $column = 'DISTINCT '.$column;
<ide>
<ide> return 'SELECT '.$query->aggregate['aggregator'].'('.$column.')';
<ide> }
| 2
|
Python
|
Python
|
fix the broken format of links and references
|
7875e856f8dc09372a83d8c5dc0af74a50d17d30
|
<ide><path>keras/layers/convolutional_recurrent.py
<ide> class ConvLSTM2DCell(Layer):
<ide> unit_forget_bias: Boolean.
<ide> If True, add 1 to the bias of the forget gate at initialization.
<ide> Use in combination with `bias_initializer="zeros"`.
<del> This is recommended in [Jozefowicz et al.]
<del> (http://www.jmlr.org/proceedings/papers/v37/jozefowicz15.pdf).
<add> This is recommended in [Jozefowicz et al. (2015)](
<add> http://www.jmlr.org/proceedings/papers/v37/jozefowicz15.pdf).
<ide> kernel_regularizer: Regularizer function applied to
<ide> the `kernel` weights matrix
<ide> (see [regularizer](../regularizers.md)).
<ide> class ConvLSTM2D(ConvRNN2D):
<ide> unit_forget_bias: Boolean.
<ide> If True, add 1 to the bias of the forget gate at initialization.
<ide> Use in combination with `bias_initializer="zeros"`.
<del> This is recommended in [Jozefowicz et al.]
<del> (http://www.jmlr.org/proceedings/papers/v37/jozefowicz15.pdf).
<add> This is recommended in [Jozefowicz et al. (2015)](
<add> http://www.jmlr.org/proceedings/papers/v37/jozefowicz15.pdf).
<ide> kernel_regularizer: Regularizer function applied to
<ide> the `kernel` weights matrix
<ide> (see [regularizer](../regularizers.md)).
<ide> class ConvLSTM2D(ConvRNN2D):
<ide>
<ide> # References
<ide> - [Convolutional LSTM Network: A Machine Learning Approach for
<del> Precipitation Nowcasting](http://arxiv.org/abs/1506.04214v1)
<del> The current implementation does not include the feedback loop on the
<del> cells output
<add> Precipitation Nowcasting](http://arxiv.org/abs/1506.04214v1)
<add> The current implementation does not include the feedback loop on the
<add> cells output
<ide> """
<ide>
<ide> @interfaces.legacy_convlstm2d_support
<ide><path>keras/layers/cudnn_recurrent.py
<ide> class CuDNNLSTM(_CuDNNRNN):
<ide> unit_forget_bias: Boolean.
<ide> If True, add 1 to the bias of the forget gate at initialization.
<ide> Setting it to true will also force `bias_initializer="zeros"`.
<del> This is recommended in [Jozefowicz et al.]
<del> (http://www.jmlr.org/proceedings/papers/v37/jozefowicz15.pdf).
<add> This is recommended in [Jozefowicz et al. (2015)](
<add> http://www.jmlr.org/proceedings/papers/v37/jozefowicz15.pdf).
<ide> recurrent_initializer: Initializer for the `recurrent_kernel`
<ide> weights matrix,
<ide> used for the linear transformation of the recurrent state.
<ide><path>keras/layers/recurrent.py
<ide> class LSTMCell(Layer):
<ide> unit_forget_bias: Boolean.
<ide> If True, add 1 to the bias of the forget gate at initialization.
<ide> Setting it to true will also force `bias_initializer="zeros"`.
<del> This is recommended in [Jozefowicz et al.]
<del> (http://www.jmlr.org/proceedings/papers/v37/jozefowicz15.pdf).
<add> This is recommended in [Jozefowicz et al. (2015)](
<add> http://www.jmlr.org/proceedings/papers/v37/jozefowicz15.pdf).
<ide> kernel_regularizer: Regularizer function applied to
<ide> the `kernel` weights matrix
<ide> (see [regularizer](../regularizers.md)).
<ide> class LSTM(RNN):
<ide> unit_forget_bias: Boolean.
<ide> If True, add 1 to the bias of the forget gate at initialization.
<ide> Setting it to true will also force `bias_initializer="zeros"`.
<del> This is recommended in [Jozefowicz et al.]
<del> (http://www.jmlr.org/proceedings/papers/v37/jozefowicz15.pdf).
<add> This is recommended in [Jozefowicz et al. (2015)](
<add> http://www.jmlr.org/proceedings/papers/v37/jozefowicz15.pdf).
<ide> kernel_regularizer: Regularizer function applied to
<ide> the `kernel` weights matrix
<ide> (see [regularizer](../regularizers.md)).
<ide> class LSTM(RNN):
<ide> Unrolling is only suitable for short sequences.
<ide>
<ide> # References
<del> - [Long short-term memory]
<del> (http://www.bioinf.jku.at/publications/older/2604.pdf)
<del> - [Learning to forget: Continual prediction with LSTM]
<del> (http://www.mitpressjournals.org/doi/pdf/10.1162/089976600300015015)
<del> - [Supervised sequence labeling with recurrent neural networks]
<del> (http://www.cs.toronto.edu/~graves/preprint.pdf)
<add> - [Long short-term memory](
<add> http://www.bioinf.jku.at/publications/older/2604.pdf)
<add> - [Learning to forget: Continual prediction with LSTM](
<add> http://www.mitpressjournals.org/doi/pdf/10.1162/089976600300015015)
<add> - [Supervised sequence labeling with recurrent neural networks](
<add> http://www.cs.toronto.edu/~graves/preprint.pdf)
<ide> - [A Theoretically Grounded Application of Dropout in
<ide> Recurrent Neural Networks](https://arxiv.org/abs/1512.05287)
<ide> """
| 3
|
Text
|
Text
|
correct fedora 22 install instructions
|
8384fdbaf382aa678dfe39d39388323ec3476b2c
|
<ide><path>README.md
<ide> repeat these steps to upgrade to future releases.
<ide> Currently only a 64-bit version is available.
<ide>
<ide> 1. Download `atom.x86_64.rpm` from the [Atom releases page](https://github.com/atom/atom/releases/latest).
<del>2. Run `sudo dnf atom.x86_64.rpm` on the downloaded package.
<add>2. Run `sudo dnf install atom.x86_64.rpm` on the downloaded package.
<ide> 3. Launch Atom using the installed `atom` command.
<ide>
<ide> The Linux version does not currently automatically update so you will need to
| 1
|
Javascript
|
Javascript
|
add setnativeprops type to fabricuimanager.js
|
c5b8b292e23f308fe15fef8e0dde1a10b149f898
|
<ide><path>Libraries/ReactNative/FabricUIManager.js
<ide> type Spec = {|
<ide> +appendChild: (parentNode: Node, child: Node) => Node,
<ide> +appendChildToSet: (childSet: NodeSet, child: Node) => void,
<ide> +completeRoot: (rootTag: number, childSet: NodeSet) => void,
<add> +setNativeProps: (node: Node, nativeProps: NodeProps) => void,
<ide> |};
<ide>
<ide> const FabricUIManager: ?Spec = global.nativeFabricUIManager;
| 1
|
Ruby
|
Ruby
|
fix undefined method error
|
a2c23dfec569c6e73d90cb20c7d4c26cced258d5
|
<ide><path>Library/Homebrew/cmd/test-bot.rb
<ide> def ruby_has_encoding?
<ide> String.method_defined?(:force_encoding)
<ide> end
<ide>
<add> if ruby_has_encoding?
<add> def fix_encoding!(str)
<add> # Assume we are starting from a "mostly" UTF-8 string
<add> str.force_encoding(Encoding::UTF_8)
<add> return str if str.valid_encoding?
<add> str.encode!(Encoding::UTF_16, :invalid => :replace)
<add> str.encode!(Encoding::UTF_8)
<add> end
<add> elsif require "iconv"
<add> def fix_encoding!(str)
<add> Iconv.conv("UTF-8//IGNORE", "UTF-8", str)
<add> end
<add> else
<add> def fix_encoding!(str)
<add> str
<add> end
<add> end
<add>
<ide> def resolve_test_tap
<ide> if tap = ARGV.value("tap")
<ide> return Tap.fetch(tap)
<ide> def run
<ide>
<ide> exit 1 if ARGV.include?("--fail-fast") && failed?
<ide> end
<del>
<del> private
<del>
<del> if Homebrew.ruby_has_encoding?
<del> def fix_encoding!(str)
<del> # Assume we are starting from a "mostly" UTF-8 string
<del> str.force_encoding(Encoding::UTF_8)
<del> return str if str.valid_encoding?
<del> str.encode!(Encoding::UTF_16, :invalid => :replace)
<del> str.encode!(Encoding::UTF_8)
<del> end
<del> elsif require "iconv"
<del> def fix_encoding!(str)
<del> Iconv.conv("UTF-8//IGNORE", "UTF-8", str)
<del> end
<del> else
<del> def fix_encoding!(str)
<del> str
<del> end
<del> end
<ide> end
<ide>
<ide> class Test
| 1
|
Text
|
Text
|
fix print statements
|
b6ee241e260d23bf5e21aad55e332b7f266c4ab4
|
<ide><path>spacy/tests/README.md
<ide> Here's how to quickly get these values from within spaCy:
<ide>
<ide> ```python
<ide> doc = nlp(u'Some text here')
<del>print [token.head.i-token.i for token in doc]
<del>print [token.tag_ for token in doc]
<del>print [token.pos_ for token in doc]
<del>print [token.dep_ for token in doc]
<add>print([token.head.i-token.i for token in doc])
<add>print([token.tag_ for token in doc])
<add>print([token.pos_ for token in doc])
<add>print([token.dep_ for token in doc])
<ide> ```
<ide>
<ide> **Note:** There's currently no way of setting the serializer data for the parser without loading the models. If this is relevant to your test, constructing the `Doc` via `get_doc()` won't work.
| 1
|
Java
|
Java
|
apply logformatutils in more places
|
e9083d7d2053fea3919bfeb9057e9fdba4049119
|
<ide><path>spring-web/src/main/java/org/springframework/web/util/UrlPathHelper.java
<ide> private String decodeInternal(HttpServletRequest request, String source) {
<ide> return UriUtils.decode(source, enc);
<ide> }
<ide> catch (UnsupportedCharsetException ex) {
<del> if (logger.isWarnEnabled()) {
<del> logger.warn("Could not decode request string [" + source + "] with encoding '" + enc +
<add> if (logger.isDebugEnabled()) {
<add> logger.debug("Could not decode request string [" + source + "] with encoding '" + enc +
<ide> "': falling back to platform default encoding; exception message: " + ex.getMessage());
<ide> }
<ide> return URLDecoder.decode(source);
<ide><path>spring-webflux/src/main/java/org/springframework/web/reactive/resource/PathResourceResolver.java
<ide> import org.springframework.core.io.ClassPathResource;
<ide> import org.springframework.core.io.Resource;
<ide> import org.springframework.core.io.UrlResource;
<add>import org.springframework.core.log.LogFormatUtils;
<ide> import org.springframework.lang.Nullable;
<ide> import org.springframework.util.StringUtils;
<ide> import org.springframework.web.server.ServerWebExchange;
<ide> protected Mono<Resource> getResource(String resourcePath, Resource location) {
<ide> return Mono.just(resource);
<ide> }
<ide> else if (logger.isWarnEnabled()) {
<del> Resource[] allowedLocations = getAllowedLocations();
<del> logger.warn("Resource path \"" + resourcePath + "\" was successfully resolved " +
<del> "but resource \"" + resource.getURL() + "\" is neither under the " +
<del> "current location \"" + location.getURL() + "\" nor under any of the " +
<del> "allowed locations " + (allowedLocations != null ? Arrays.asList(allowedLocations) : "[]"));
<add> Resource[] allowed = getAllowedLocations();
<add> logger.warn(LogFormatUtils.formatValue(
<add> "Resource path \"" + resourcePath + "\" was successfully resolved " +
<add> "but resource \"" + resource.getURL() + "\" is neither under the " +
<add> "current location \"" + location.getURL() + "\" nor under any of the " +
<add> "allowed locations " + (allowed != null ? Arrays.asList(allowed) : "[]"), -1, true));
<ide> }
<ide> }
<ide> return Mono.empty();
<ide> private boolean isInvalidEncodedPath(String resourcePath) {
<ide> try {
<ide> String decodedPath = URLDecoder.decode(resourcePath, "UTF-8");
<ide> if (decodedPath.contains("../") || decodedPath.contains("..\\")) {
<del> logger.warn("Resolved resource path contains encoded \"../\" or \"..\\\": " + resourcePath);
<add> logger.warn(LogFormatUtils.formatValue(
<add> "Resolved resource path contains encoded \"../\" or \"..\\\": " + resourcePath, -1, true));
<ide> return true;
<ide> }
<ide> }
<ide><path>spring-webflux/src/main/java/org/springframework/web/reactive/resource/ResourceWebHandler.java
<ide> import org.springframework.core.codec.Hints;
<ide> import org.springframework.core.io.Resource;
<ide> import org.springframework.core.io.ResourceLoader;
<add>import org.springframework.core.log.LogFormatUtils;
<ide> import org.springframework.http.CacheControl;
<ide> import org.springframework.http.HttpHeaders;
<ide> import org.springframework.http.HttpMethod;
<ide> private boolean isInvalidEncodedPath(String path) {
<ide> protected boolean isInvalidPath(String path) {
<ide> if (path.contains("WEB-INF") || path.contains("META-INF")) {
<ide> if (logger.isWarnEnabled()) {
<del> logger.warn("Path with \"WEB-INF\" or \"META-INF\": [" + path + "]");
<add> logger.warn(LogFormatUtils.formatValue(
<add> "Path with \"WEB-INF\" or \"META-INF\": [" + path + "]", -1, true));
<ide> }
<ide> return true;
<ide> }
<ide> if (path.contains(":/")) {
<ide> String relativePath = (path.charAt(0) == '/' ? path.substring(1) : path);
<ide> if (ResourceUtils.isUrl(relativePath) || relativePath.startsWith("url:")) {
<ide> if (logger.isWarnEnabled()) {
<del> logger.warn("Path represents URL or has \"url:\" prefix: [" + path + "]");
<add> logger.warn(LogFormatUtils.formatValue(
<add> "Path represents URL or has \"url:\" prefix: [" + path + "]", -1, true));
<ide> }
<ide> return true;
<ide> }
<ide> }
<ide> if (path.contains("..") && StringUtils.cleanPath(path).contains("../")) {
<ide> if (logger.isWarnEnabled()) {
<del> logger.warn("Path contains \"../\" after call to StringUtils#cleanPath: [" + path + "]");
<add> logger.warn(LogFormatUtils.formatValue(
<add> "Path contains \"../\" after call to StringUtils#cleanPath: [" + path + "]", -1, true));
<ide> }
<ide> return true;
<ide> }
<ide><path>spring-webmvc/src/main/java/org/springframework/web/servlet/mvc/method/annotation/ExtendedServletRequestDataBinder.java
<ide> /*
<del> * Copyright 2002-2020 the original author or authors.
<add> * Copyright 2002-2021 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> protected void addBindValues(MutablePropertyValues mpvs, ServletRequest request)
<ide> if (uriVars != null) {
<ide> uriVars.forEach((name, value) -> {
<ide> if (mpvs.contains(name)) {
<del> if (logger.isWarnEnabled()) {
<del> logger.warn("Skipping URI variable '" + name +
<del> "' because request contains bind value with same name.");
<add> if (logger.isDebugEnabled()) {
<add> logger.debug("URI variable '" + name + "' overridden by request bind value.");
<ide> }
<ide> }
<ide> else {
<ide><path>spring-webmvc/src/main/java/org/springframework/web/servlet/mvc/method/annotation/ReactiveTypeHandler.java
<ide> /*
<del> * Copyright 2002-2020 the original author or authors.
<add> * Copyright 2002-2021 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> private void logExecutorWarning(MethodParameter returnType) {
<ide> "-------------------------------\n" +
<ide> "Controller:\t" + returnType.getContainingClass().getName() + "\n" +
<ide> "Method:\t\t" + returnType.getMethod().getName() + "\n" +
<del> "Returning:\t" + ResolvableType.forMethodParameter(returnType).toString() + "\n" +
<add> "Returning:\t" + ResolvableType.forMethodParameter(returnType) + "\n" +
<ide> "!!!");
<ide> this.taskExecutorWarning = false;
<ide> }
<ide><path>spring-webmvc/src/main/java/org/springframework/web/servlet/resource/PathResourceResolver.java
<ide> import org.springframework.core.io.ClassPathResource;
<ide> import org.springframework.core.io.Resource;
<ide> import org.springframework.core.io.UrlResource;
<add>import org.springframework.core.log.LogFormatUtils;
<ide> import org.springframework.http.server.PathContainer;
<ide> import org.springframework.lang.Nullable;
<ide> import org.springframework.util.StringUtils;
<ide> protected Resource getResource(String resourcePath, Resource location) throws IO
<ide> return resource;
<ide> }
<ide> else if (logger.isWarnEnabled()) {
<del> Resource[] allowedLocations = getAllowedLocations();
<del> logger.warn("Resource path \"" + resourcePath + "\" was successfully resolved " +
<del> "but resource \"" + resource.getURL() + "\" is neither under the " +
<del> "current location \"" + location.getURL() + "\" nor under any of the " +
<del> "allowed locations " + (allowedLocations != null ? Arrays.asList(allowedLocations) : "[]"));
<add> Resource[] allowed = getAllowedLocations();
<add> logger.warn(LogFormatUtils.formatValue(
<add> "Resource path \"" + resourcePath + "\" was successfully resolved " +
<add> "but resource \"" + resource.getURL() + "\" is neither under " +
<add> "the current location \"" + location.getURL() + "\" nor under any of " +
<add> "the allowed locations " + (allowed != null ? Arrays.asList(allowed) : "[]"), -1, true));
<ide> }
<ide> }
<ide> return null;
<ide> private boolean isInvalidEncodedPath(String resourcePath) {
<ide> try {
<ide> String decodedPath = URLDecoder.decode(resourcePath, "UTF-8");
<ide> if (decodedPath.contains("../") || decodedPath.contains("..\\")) {
<del> logger.warn("Resolved resource path contains encoded \"../\" or \"..\\\": " + resourcePath);
<add> logger.warn(LogFormatUtils.formatValue(
<add> "Resolved resource path contains encoded \"../\" or \"..\\\": " + resourcePath, -1, true));
<ide> return true;
<ide> }
<ide> }
<ide><path>spring-webmvc/src/main/java/org/springframework/web/servlet/resource/ResourceHttpRequestHandler.java
<ide> import org.springframework.context.EmbeddedValueResolverAware;
<ide> import org.springframework.core.io.Resource;
<ide> import org.springframework.core.io.UrlResource;
<add>import org.springframework.core.log.LogFormatUtils;
<ide> import org.springframework.http.HttpHeaders;
<ide> import org.springframework.http.HttpMethod;
<ide> import org.springframework.http.HttpRange;
<ide> private boolean isInvalidEncodedPath(String path) {
<ide> protected boolean isInvalidPath(String path) {
<ide> if (path.contains("WEB-INF") || path.contains("META-INF")) {
<ide> if (logger.isWarnEnabled()) {
<del> logger.warn("Path with \"WEB-INF\" or \"META-INF\": [" + path + "]");
<add> logger.warn(LogFormatUtils.formatValue(
<add> "Path with \"WEB-INF\" or \"META-INF\": [" + path + "]", -1, true));
<ide> }
<ide> return true;
<ide> }
<ide> if (path.contains(":/")) {
<ide> String relativePath = (path.charAt(0) == '/' ? path.substring(1) : path);
<ide> if (ResourceUtils.isUrl(relativePath) || relativePath.startsWith("url:")) {
<ide> if (logger.isWarnEnabled()) {
<del> logger.warn("Path represents URL or has \"url:\" prefix: [" + path + "]");
<add> logger.warn(LogFormatUtils.formatValue(
<add> "Path represents URL or has \"url:\" prefix: [" + path + "]", -1, true));
<ide> }
<ide> return true;
<ide> }
<ide> }
<ide> if (path.contains("..") && StringUtils.cleanPath(path).contains("../")) {
<ide> if (logger.isWarnEnabled()) {
<del> logger.warn("Path contains \"../\" after call to StringUtils#cleanPath: [" + path + "]");
<add> logger.warn(LogFormatUtils.formatValue(
<add> "Path contains \"../\" after call to StringUtils#cleanPath: [" + path + "]", -1, true));
<ide> }
<ide> return true;
<ide> }
<ide><path>spring-websocket/src/main/java/org/springframework/web/socket/server/support/AbstractHandshakeHandler.java
<ide> import org.apache.commons.logging.LogFactory;
<ide>
<ide> import org.springframework.context.Lifecycle;
<add>import org.springframework.core.log.LogFormatUtils;
<ide> import org.springframework.http.HttpMethod;
<ide> import org.springframework.http.HttpStatus;
<ide> import org.springframework.http.server.ServerHttpRequest;
<ide> public final boolean doHandshake(ServerHttpRequest request, ServerHttpResponse r
<ide>
<ide> protected void handleInvalidUpgradeHeader(ServerHttpRequest request, ServerHttpResponse response) throws IOException {
<ide> if (logger.isErrorEnabled()) {
<del> logger.error("Handshake failed due to invalid Upgrade header: " + request.getHeaders().getUpgrade());
<add> logger.error(LogFormatUtils.formatValue(
<add> "Handshake failed due to invalid Upgrade header: " + request.getHeaders().getUpgrade(), -1, true));
<ide> }
<ide> response.setStatusCode(HttpStatus.BAD_REQUEST);
<ide> response.getBody().write("Can \"Upgrade\" only to \"WebSocket\".".getBytes(StandardCharsets.UTF_8));
<ide> }
<ide>
<ide> protected void handleInvalidConnectHeader(ServerHttpRequest request, ServerHttpResponse response) throws IOException {
<ide> if (logger.isErrorEnabled()) {
<del> logger.error("Handshake failed due to invalid Connection header " + request.getHeaders().getConnection());
<add> logger.error(LogFormatUtils.formatValue(
<add> "Handshake failed due to invalid Connection header" + request.getHeaders().getConnection(), -1, true));
<ide> }
<ide> response.setStatusCode(HttpStatus.BAD_REQUEST);
<ide> response.getBody().write("\"Connection\" must be \"upgrade\".".getBytes(StandardCharsets.UTF_8));
<ide> protected String[] getSupportedVersions() {
<ide> protected void handleWebSocketVersionNotSupported(ServerHttpRequest request, ServerHttpResponse response) {
<ide> if (logger.isErrorEnabled()) {
<ide> String version = request.getHeaders().getFirst("Sec-WebSocket-Version");
<del> logger.error("Handshake failed due to unsupported WebSocket version: " + version +
<del> ". Supported versions: " + Arrays.toString(getSupportedVersions()));
<add> logger.error(LogFormatUtils.formatValue(
<add> "Handshake failed due to unsupported WebSocket version: " + version +
<add> ". Supported versions: " + Arrays.toString(getSupportedVersions()), -1, true));
<ide> }
<ide> response.setStatusCode(HttpStatus.UPGRADE_REQUIRED);
<ide> response.getHeaders().set(WebSocketHttpHeaders.SEC_WEBSOCKET_VERSION,
<ide><path>spring-websocket/src/main/java/org/springframework/web/socket/sockjs/support/AbstractSockJsService.java
<ide> import org.apache.commons.logging.Log;
<ide> import org.apache.commons.logging.LogFactory;
<ide>
<add>import org.springframework.core.log.LogFormatUtils;
<ide> import org.springframework.http.HttpHeaders;
<ide> import org.springframework.http.HttpMethod;
<ide> import org.springframework.http.HttpStatus;
<ide> public final void handleRequest(ServerHttpRequest request, ServerHttpResponse re
<ide>
<ide> if (sockJsPath == null) {
<ide> if (logger.isWarnEnabled()) {
<del> logger.warn("Expected SockJS path. Failing request: " + request.getURI());
<add> logger.warn(LogFormatUtils.formatValue(
<add> "Expected SockJS path. Failing request: " + request.getURI(), -1, true));
<ide> }
<ide> response.setStatusCode(HttpStatus.NOT_FOUND);
<ide> return;
<ide> else if (requestInfo != null) {
<ide> String[] pathSegments = StringUtils.tokenizeToStringArray(sockJsPath.substring(1), "/");
<ide> if (pathSegments.length != 3) {
<ide> if (logger.isWarnEnabled()) {
<del> logger.warn("Invalid SockJS path '" + sockJsPath + "' - required to have 3 path segments");
<add> logger.warn(LogFormatUtils.formatValue("Invalid SockJS path '" + sockJsPath + "' - " +
<add> "required to have 3 path segments", -1, true));
<ide> }
<ide> if (requestInfo != null) {
<ide> logger.debug("Ignoring transport request: " + requestInfo);
<ide><path>spring-websocket/src/main/java/org/springframework/web/socket/sockjs/transport/TransportHandlingSockJsService.java
<ide> /*
<del> * Copyright 2002-2020 the original author or authors.
<add> * Copyright 2002-2021 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.util.concurrent.ScheduledFuture;
<ide>
<ide> import org.springframework.context.Lifecycle;
<add>import org.springframework.core.log.LogFormatUtils;
<ide> import org.springframework.http.HttpMethod;
<ide> import org.springframework.http.HttpStatus;
<ide> import org.springframework.http.server.ServerHttpRequest;
<ide> protected void handleTransportRequest(ServerHttpRequest request, ServerHttpRespo
<ide> TransportType transportType = TransportType.fromValue(transport);
<ide> if (transportType == null) {
<ide> if (logger.isWarnEnabled()) {
<del> logger.warn("Unknown transport type for " + request.getURI());
<add> logger.warn(LogFormatUtils.formatValue("Unknown transport type for " + request.getURI(), -1, true));
<ide> }
<ide> response.setStatusCode(HttpStatus.NOT_FOUND);
<ide> return;
<ide> protected void handleTransportRequest(ServerHttpRequest request, ServerHttpRespo
<ide> TransportHandler transportHandler = this.handlers.get(transportType);
<ide> if (transportHandler == null) {
<ide> if (logger.isWarnEnabled()) {
<del> logger.warn("No TransportHandler for " + request.getURI());
<add> logger.warn(LogFormatUtils.formatValue("No TransportHandler for " + request.getURI(), -1, true));
<ide> }
<ide> response.setStatusCode(HttpStatus.NOT_FOUND);
<ide> return;
| 10
|
PHP
|
PHP
|
add session access for integrationtest testing
|
a305f17724c8b8c990481e5f809667a1a615c9ff
|
<ide><path>src/TestSuite/IntegrationTestTrait.php
<ide> protected function extractExceptionMessage(Exception $exception): string
<ide> PHP_EOL .
<ide> $exception->getTraceAsString();
<ide> }
<add>
<add> /**
<add> * @return \Cake\TestSuite\TestSession
<add> */
<add> protected function getTestSession(): TestSession
<add> {
<add> return new TestSession($_SESSION);
<add> }
<ide> }
<ide><path>src/TestSuite/TestSession.php
<add><?php
<add>declare(strict_types=1);
<add>
<add>/**
<add> * A class to contain and retain the session during integration testing.
<add> *
<add> * CakePHP(tm) : Rapid Development Framework (https://cakephp.org)
<add> * Copyright (c) Cake Software Foundation, Inc. (https://cakefoundation.org)
<add> *
<add> * Licensed under The MIT License
<add> * For full copyright and license information, please see the LICENSE.txt
<add> * Redistributions of files must retain the above copyright notice.
<add> *
<add> * @copyright Copyright (c) Cake Software Foundation, Inc. (https://cakefoundation.org)
<add> * @link https://cakephp.org CakePHP(tm) Project
<add> * @since 4.0.5
<add> * @license https://opensource.org/licenses/mit-license.php MIT License
<add> */
<add>namespace Cake\TestSuite;
<add>
<add>use Cake\Utility\Hash;
<add>
<add>/**
<add> * Read only access to the session during testing.
<add> */
<add>class TestSession
<add>{
<add> /**
<add> * @var array|null
<add> */
<add> protected $session;
<add>
<add> /**
<add> * @param array|null $session Session data.
<add> */
<add> public function __construct(?array $session)
<add> {
<add> $this->session = $session;
<add> }
<add>
<add> /**
<add> * Returns true if given variable name is set in session.
<add> *
<add> * @param string|null $name Variable name to check for
<add> * @return bool True if variable is there
<add> */
<add> public function check(?string $name = null): bool
<add> {
<add> if ($this->session === null) {
<add> return false;
<add> }
<add>
<add> return Hash::get($this->session, $name) !== null;
<add> }
<add>
<add> /**
<add> * Returns given session variable, or all of them, if no parameters given.
<add> *
<add> * @param string|null $name The name of the session variable (or a path as sent to Hash.extract)
<add> * @return mixed The value of the session variable, null if session not available,
<add> * session not started, or provided name not found in the session.
<add> */
<add> public function read(?string $name = null)
<add> {
<add> if ($this->session === null) {
<add> return null;
<add> }
<add>
<add> if ($name === null) {
<add> return $this->session ?: [];
<add> }
<add>
<add> return Hash::get($this->session, $name);
<add> }
<add>}
| 2
|
Python
|
Python
|
improve qa pipeline error handling
|
7342d9a583e63ab1214b03c2bd7d5f613a535efb
|
<ide><path>src/transformers/pipelines.py
<ide> import uuid
<ide> import warnings
<ide> from abc import ABC, abstractmethod
<add>from collections.abc import Iterable
<ide> from contextlib import contextmanager
<ide> from os.path import abspath, exists
<ide> from typing import TYPE_CHECKING, Any, Dict, List, Optional, Tuple, Union
<ide> class QuestionAnsweringArgumentHandler(ArgumentHandler):
<ide> command-line supplied arguments.
<ide> """
<ide>
<add> def normalize(self, item):
<add> if isinstance(item, SquadExample):
<add> return item
<add> elif isinstance(item, dict):
<add> for k in ["question", "context"]:
<add> if k not in item:
<add> raise KeyError("You need to provide a dictionary with keys {question:..., context:...}")
<add> elif item[k] is None:
<add> raise ValueError("`{}` cannot be None".format(k))
<add> elif isinstance(item[k], str) and len(item[k]) == 0:
<add> raise ValueError("`{}` cannot be empty".format(k))
<add>
<add> return QuestionAnsweringPipeline.create_sample(**item)
<add> raise ValueError("{} argument needs to be of type (SquadExample, dict)".format(item))
<add>
<ide> def __call__(self, *args, **kwargs):
<del> # Position args, handling is sensibly the same as X and data, so forwarding to avoid duplicating
<add> # Detect where the actual inputs are
<ide> if args is not None and len(args) > 0:
<ide> if len(args) == 1:
<del> kwargs["X"] = args[0]
<add> inputs = args[0]
<add> elif len(args) == 2 and {type(el) for el in args} == {str}:
<add> inputs = [{"question": args[0], "context": args[1]}]
<ide> else:
<del> kwargs["X"] = list(args)
<del>
<add> inputs = list(args)
<ide> # Generic compatibility with sklearn and Keras
<ide> # Batched data
<del> if "X" in kwargs or "data" in kwargs:
<del> inputs = kwargs["X"] if "X" in kwargs else kwargs["data"]
<del>
<del> if isinstance(inputs, dict):
<del> inputs = [inputs]
<del> else:
<del> # Copy to avoid overriding arguments
<del> inputs = [i for i in inputs]
<del>
<del> for i, item in enumerate(inputs):
<del> if isinstance(item, dict):
<del> if any(k not in item for k in ["question", "context"]):
<del> raise KeyError("You need to provide a dictionary with keys {question:..., context:...}")
<del>
<del> inputs[i] = QuestionAnsweringPipeline.create_sample(**item)
<del>
<del> elif not isinstance(item, SquadExample):
<del> raise ValueError(
<del> "{} argument needs to be of type (list[SquadExample | dict], SquadExample, dict)".format(
<del> "X" if "X" in kwargs else "data"
<del> )
<del> )
<del>
<del> # Tabular input
<add> elif "X" in kwargs:
<add> inputs = kwargs["X"]
<add> elif "data" in kwargs:
<add> inputs = kwargs["data"]
<ide> elif "question" in kwargs and "context" in kwargs:
<del> if isinstance(kwargs["question"], str):
<del> kwargs["question"] = [kwargs["question"]]
<del>
<del> if isinstance(kwargs["context"], str):
<del> kwargs["context"] = [kwargs["context"]]
<del>
<del> inputs = [
<del> QuestionAnsweringPipeline.create_sample(q, c) for q, c in zip(kwargs["question"], kwargs["context"])
<del> ]
<add> inputs = [{"question": kwargs["question"], "context": kwargs["context"]}]
<ide> else:
<ide> raise ValueError("Unknown arguments {}".format(kwargs))
<ide>
<del> if not isinstance(inputs, list):
<add> # Normalize inputs
<add> if isinstance(inputs, dict):
<ide> inputs = [inputs]
<add> elif isinstance(inputs, Iterable):
<add> # Copy to avoid overriding arguments
<add> inputs = [i for i in inputs]
<add> else:
<add> raise ValueError("Invalid arguments {}".format(inputs))
<add>
<add> for i, item in enumerate(inputs):
<add> inputs[i] = self.normalize(item)
<ide>
<ide> return inputs
<ide>
<ide><path>tests/test_pipelines_question_answering.py
<ide> import unittest
<ide>
<del>from transformers.pipelines import Pipeline
<add>from transformers.data.processors.squad import SquadExample
<add>from transformers.pipelines import Pipeline, QuestionAnsweringArgumentHandler
<ide>
<ide> from .test_pipelines_common import CustomInputPipelineCommonMixin
<ide>
<ide> def _test_pipeline(self, nlp: Pipeline):
<ide> for key in output_keys:
<ide> self.assertIn(key, result)
<ide> for bad_input in invalid_inputs:
<del> self.assertRaises(Exception, nlp, bad_input)
<del> self.assertRaises(Exception, nlp, invalid_inputs)
<add> self.assertRaises(ValueError, nlp, bad_input)
<add> self.assertRaises(ValueError, nlp, invalid_inputs)
<add>
<add> def test_argument_handler(self):
<add> qa = QuestionAnsweringArgumentHandler()
<add>
<add> Q = "Where was HuggingFace founded ?"
<add> C = "HuggingFace was founded in Paris"
<add>
<add> normalized = qa(Q, C)
<add> self.assertEqual(type(normalized), list)
<add> self.assertEqual(len(normalized), 1)
<add> self.assertEqual({type(el) for el in normalized}, {SquadExample})
<add>
<add> normalized = qa(question=Q, context=C)
<add> self.assertEqual(type(normalized), list)
<add> self.assertEqual(len(normalized), 1)
<add> self.assertEqual({type(el) for el in normalized}, {SquadExample})
<add>
<add> normalized = qa(question=Q, context=C)
<add> self.assertEqual(type(normalized), list)
<add> self.assertEqual(len(normalized), 1)
<add> self.assertEqual({type(el) for el in normalized}, {SquadExample})
<add>
<add> normalized = qa({"question": Q, "context": C})
<add> self.assertEqual(type(normalized), list)
<add> self.assertEqual(len(normalized), 1)
<add> self.assertEqual({type(el) for el in normalized}, {SquadExample})
<add>
<add> normalized = qa([{"question": Q, "context": C}])
<add> self.assertEqual(type(normalized), list)
<add> self.assertEqual(len(normalized), 1)
<add> self.assertEqual({type(el) for el in normalized}, {SquadExample})
<add>
<add> normalized = qa([{"question": Q, "context": C}, {"question": Q, "context": C}])
<add> self.assertEqual(type(normalized), list)
<add> self.assertEqual(len(normalized), 2)
<add> self.assertEqual({type(el) for el in normalized}, {SquadExample})
<add>
<add> normalized = qa(X={"question": Q, "context": C})
<add> self.assertEqual(type(normalized), list)
<add> self.assertEqual(len(normalized), 1)
<add> self.assertEqual({type(el) for el in normalized}, {SquadExample})
<add>
<add> normalized = qa(X=[{"question": Q, "context": C}])
<add> self.assertEqual(type(normalized), list)
<add> self.assertEqual(len(normalized), 1)
<add> self.assertEqual({type(el) for el in normalized}, {SquadExample})
<add>
<add> normalized = qa(data={"question": Q, "context": C})
<add> self.assertEqual(type(normalized), list)
<add> self.assertEqual(len(normalized), 1)
<add> self.assertEqual({type(el) for el in normalized}, {SquadExample})
<add>
<add> def test_argument_handler_error_handling(self):
<add> qa = QuestionAnsweringArgumentHandler()
<add>
<add> Q = "Where was HuggingFace founded ?"
<add> C = "HuggingFace was founded in Paris"
<add>
<add> with self.assertRaises(KeyError):
<add> qa({"context": C})
<add> with self.assertRaises(KeyError):
<add> qa({"question": Q})
<add> with self.assertRaises(KeyError):
<add> qa([{"context": C}])
<add> with self.assertRaises(ValueError):
<add> qa(None, C)
<add> with self.assertRaises(ValueError):
<add> qa("", C)
<add> with self.assertRaises(ValueError):
<add> qa(Q, None)
<add> with self.assertRaises(ValueError):
<add> qa(Q, "")
<add>
<add> with self.assertRaises(ValueError):
<add> qa(question=None, context=C)
<add> with self.assertRaises(ValueError):
<add> qa(question="", context=C)
<add> with self.assertRaises(ValueError):
<add> qa(question=Q, context=None)
<add> with self.assertRaises(ValueError):
<add> qa(question=Q, context="")
<add>
<add> with self.assertRaises(ValueError):
<add> qa({"question": None, "context": C})
<add> with self.assertRaises(ValueError):
<add> qa({"question": "", "context": C})
<add> with self.assertRaises(ValueError):
<add> qa({"question": Q, "context": None})
<add> with self.assertRaises(ValueError):
<add> qa({"question": Q, "context": ""})
<add>
<add> with self.assertRaises(ValueError):
<add> qa([{"question": Q, "context": C}, {"question": None, "context": C}])
<add> with self.assertRaises(ValueError):
<add> qa([{"question": Q, "context": C}, {"question": "", "context": C}])
<add>
<add> with self.assertRaises(ValueError):
<add> qa([{"question": Q, "context": C}, {"question": Q, "context": None}])
<add> with self.assertRaises(ValueError):
<add> qa([{"question": Q, "context": C}, {"question": Q, "context": ""}])
<add>
<add> def test_argument_handler_error_handling_odd(self):
<add> qa = QuestionAnsweringArgumentHandler()
<add> with self.assertRaises(ValueError):
<add> qa(None)
<add>
<add> with self.assertRaises(ValueError):
<add> qa(Y=None)
<add>
<add> with self.assertRaises(ValueError):
<add> qa(1)
| 2
|
Mixed
|
Python
|
add three missing tags from the `nb` tag map
|
e172f2478e4f0083a703a0b55b7b92958651b977
|
<ide><path>.github/contributors/jarib.md
<add># spaCy contributor agreement
<add>
<add>This spaCy Contributor Agreement (**"SCA"**) is based on the
<add>[Oracle Contributor Agreement](http://www.oracle.com/technetwork/oca-405177.pdf).
<add>The SCA applies to any contribution that you make to any product or project
<add>managed by us (the **"project"**), and sets out the intellectual property rights
<add>you grant to us in the contributed materials. The term **"us"** shall mean
<add>[ExplosionAI UG (haftungsbeschränkt)](https://explosion.ai/legal). The term
<add>**"you"** shall mean the person or entity identified below.
<add>
<add>If you agree to be bound by these terms, fill in the information requested
<add>below and include the filled-in version with your first pull request, under the
<add>folder [`.github/contributors/`](/.github/contributors/). The name of the file
<add>should be your GitHub username, with the extension `.md`. For example, the user
<add>example_user would create the file `.github/contributors/example_user.md`.
<add>
<add>Read this agreement carefully before signing. These terms and conditions
<add>constitute a binding legal agreement.
<add>
<add>## Contributor Agreement
<add>
<add>1. The term "contribution" or "contributed materials" means any source code,
<add>object code, patch, tool, sample, graphic, specification, manual,
<add>documentation, or any other material posted or submitted by you to the project.
<add>
<add>2. With respect to any worldwide copyrights, or copyright applications and
<add>registrations, in your contribution:
<add>
<add> * you hereby assign to us joint ownership, and to the extent that such
<add> assignment is or becomes invalid, ineffective or unenforceable, you hereby
<add> grant to us a perpetual, irrevocable, non-exclusive, worldwide, no-charge,
<add> royalty-free, unrestricted license to exercise all rights under those
<add> copyrights. This includes, at our option, the right to sublicense these same
<add> rights to third parties through multiple levels of sublicensees or other
<add> licensing arrangements;
<add>
<add> * you agree that each of us can do all things in relation to your
<add> contribution as if each of us were the sole owners, and if one of us makes
<add> a derivative work of your contribution, the one who makes the derivative
<add> work (or has it made will be the sole owner of that derivative work;
<add>
<add> * you agree that you will not assert any moral rights in your contribution
<add> against us, our licensees or transferees;
<add>
<add> * you agree that we may register a copyright in your contribution and
<add> exercise all ownership rights associated with it; and
<add>
<add> * you agree that neither of us has any duty to consult with, obtain the
<add> consent of, pay or render an accounting to the other for any use or
<add> distribution of your contribution.
<add>
<add>3. With respect to any patents you own, or that you can license without payment
<add>to any third party, you hereby grant to us a perpetual, irrevocable,
<add>non-exclusive, worldwide, no-charge, royalty-free license to:
<add>
<add> * make, have made, use, sell, offer to sell, import, and otherwise transfer
<add> your contribution in whole or in part, alone or in combination with or
<add> included in any product, work or materials arising out of the project to
<add> which your contribution was submitted, and
<add>
<add> * at our option, to sublicense these same rights to third parties through
<add> multiple levels of sublicensees or other licensing arrangements.
<add>
<add>4. Except as set out above, you keep all right, title, and interest in your
<add>contribution. The rights that you grant to us under these terms are effective
<add>on the date you first submitted a contribution to us, even if your submission
<add>took place before the date you sign these terms.
<add>
<add>5. You covenant, represent, warrant and agree that:
<add>
<add> * Each contribution that you submit is and shall be an original work of
<add> authorship and you can legally grant the rights set out in this SCA;
<add>
<add> * to the best of your knowledge, each contribution will not violate any
<add> third party's copyrights, trademarks, patents, or other intellectual
<add> property rights; and
<add>
<add> * each contribution shall be in compliance with U.S. export control laws and
<add> other applicable export and import laws. You agree to notify us if you
<add> become aware of any circumstance which would make any of the foregoing
<add> representations inaccurate in any respect. We may publicly disclose your
<add> participation in the project, including the fact that you have signed the SCA.
<add>
<add>6. This SCA is governed by the laws of the State of California and applicable
<add>U.S. Federal law. Any choice of law rules will not apply.
<add>
<add>7. Please place an “x” on one of the applicable statement below. Please do NOT
<add>mark both statements:
<add>
<add> * [x] I am signing on behalf of myself as an individual and no other person
<add> or entity, including my employer, has or will have rights with respect to my
<add> contributions.
<add>
<add> * [ ] I am signing on behalf of my employer or a legal entity and I have the
<add> actual authority to contractually bind that entity.
<add>
<add>## Contributor Details
<add>
<add>| Field | Entry |
<add>|------------------------------- | -------------------- |
<add>| Name | Jari Bakken |
<add>| Company name (if applicable) | |
<add>| Title or role (if applicable) | |
<add>| Date | 2018-12-21 |
<add>| GitHub username | jarib |
<add>| Website (optional) | |
<ide><path>spacy/lang/nb/tag_map.py
<ide> "ADJ___": {"morph": "_", POS: ADJ},
<ide> "ADP___": {"morph": "_", POS: ADP},
<ide> "ADV___": {"morph": "_", POS: ADV},
<add> "ADV__Gender=Masc": {"morph": "Gender=Masc", POS: ADV},
<ide> "AUX__Mood=Imp|VerbForm=Fin": {"morph": "Mood=Imp|VerbForm=Fin", POS: AUX},
<ide> "AUX__Mood=Ind|Tense=Past|VerbForm=Fin": {
<ide> "morph": "Mood=Ind|Tense=Past|VerbForm=Fin",
<ide> POS: AUX,
<ide> },
<ide> "AUX__VerbForm=Inf": {"morph": "VerbForm=Inf", POS: AUX},
<add> "AUX__VerbForm=Inf|Voice=Pass": {"morph": "VerbForm=Inf|Voice=Pass", POS: AUX},
<ide> "AUX__VerbForm=Part": {"morph": "VerbForm=Part", POS: AUX},
<ide> "CONJ___": {"morph": "_", POS: CONJ},
<ide> "DET__Case=Gen|Definite=Ind|Gender=Masc|Number=Sing|PronType=Dem": {
<ide> POS: NOUN,
<ide> },
<ide> "NOUN__Definite=Ind|Number=Plur": {"morph": "Definite=Ind|Number=Plur", POS: NOUN},
<add> "NOUN__Definite=Ind|Number=Sing": {"morph": "Definite=Ind|Number=Sing", POS: NOUN},
<ide> "NOUN__Gender=Fem": {"morph": "Gender=Fem", POS: NOUN},
<ide> "NOUN__Gender=Masc": {"morph": "Gender=Masc", POS: NOUN},
<ide> "NOUN__Gender=Masc|Number=Sing": {"morph": "Gender=Masc|Number=Sing", POS: NOUN},
<ide> "morph": "Case=Nom|Number=Plur|Person=",
<ide> POS: PRON,
<ide> },
<add> "PRON__Case=Gen|Number=Plur|Person=3|PronType=Prs": {
<add> "morph": "Case=Gen|Number=Plur|Person=3|PronType=Prs",
<add> POS: PRON,
<add> },
<ide> "PRON__Gender=Fem,Masc|Number=Sing|Person=3|PronType=Prs": {
<ide> "morph": "Gender=Fem",
<ide> POS: PRON,
| 2
|
Python
|
Python
|
add test for nan and inf for spacing
|
111f37a04c6e85b202cc6f7c0bb46d750c2409b1
|
<ide><path>numpy/core/tests/test_umath.py
<ide> def test_spacing():
<ide> for t in [np.float32, np.float64, np.longdouble]:
<ide> one = t(1)
<ide> eps = np.finfo(t).eps
<add> nan = t(np.nan)
<add> inf = t(np.inf)
<ide> assert np.spacing(one) == eps
<add> assert np.isnan(np.spacing(nan))
<add> assert np.isnan(np.spacing(inf))
<add> assert np.isnan(np.spacing(-inf))
<ide>
<ide> def test_spacing_gfortran():
<ide> # Reference from this fortran file, built with gfortran 4.3.3 on linux
| 1
|
Java
|
Java
|
add bindtohttphandler to webtestclient
|
16901b14975273034194b9c8a109ab749a90f0bc
|
<ide><path>spring-test/src/main/java/org/springframework/test/web/reactive/server/DefaultWebTestClient.java
<ide> class DefaultWebTestClient implements WebTestClient {
<ide>
<ide>
<ide> DefaultWebTestClient(WebClient.Builder webClientBuilder, ClientHttpConnector connector,
<del> ExchangeMutatingWebFilter exchangeMutatingWebFilter, Duration timeout) {
<add> ExchangeMutatingWebFilter filter, Duration timeout) {
<ide>
<ide> Assert.notNull(webClientBuilder, "WebClient.Builder is required");
<ide>
<ide> this.wiretapConnector = new WiretapConnector(connector);
<ide> this.webClient = webClientBuilder.clientConnector(this.wiretapConnector).build();
<del> this.exchangeMutatingWebFilter = exchangeMutatingWebFilter;
<add> this.exchangeMutatingWebFilter = (filter != null ? filter : new ExchangeMutatingWebFilter());
<ide> this.timeout = (timeout != null ? timeout : Duration.ofSeconds(5));
<ide> }
<ide>
<ide><path>spring-test/src/main/java/org/springframework/test/web/reactive/server/WebTestClient.java
<ide> import org.springframework.http.MediaType;
<ide> import org.springframework.http.client.reactive.ClientHttpRequest;
<ide> import org.springframework.http.codec.ServerCodecConfigurer;
<add>import org.springframework.http.server.reactive.HttpHandler;
<ide> import org.springframework.util.MultiValueMap;
<ide> import org.springframework.validation.Validator;
<ide> import org.springframework.web.reactive.accept.RequestedContentTypeResolverBuilder;
<ide> public interface WebTestClient {
<ide> // Static, factory methods
<ide>
<ide> /**
<del> * Integration testing without a server, targeting specific annotated,
<add> * Integration testing without a server targeting specific annotated,
<ide> * WebFlux controllers. The default configuration is the same as for
<ide> * {@link org.springframework.web.reactive.config.EnableWebFlux @EnableWebFlux}
<ide> * but can also be further customized through the returned spec.
<ide> static ControllerSpec bindToController(Object... controllers) {
<ide> }
<ide>
<ide> /**
<del> * Integration testing without a server, with WebFlux infrastructure detected
<add> * Integration testing without a server with WebFlux infrastructure detected
<ide> * from an {@link ApplicationContext} such as {@code @EnableWebFlux}
<ide> * Java config and annotated controller Spring beans.
<ide> * @param applicationContext the context
<ide> static MockServerSpec<?> bindToApplicationContext(ApplicationContext application
<ide> }
<ide>
<ide> /**
<del> * Integration testing without a server, targeting WebFlux functional endpoints.
<add> * Integration testing without a server targeting WebFlux functional endpoints.
<ide> * @param routerFunction the RouterFunction to test
<ide> * @return the {@link WebTestClient} builder
<ide> */
<ide> static MockServerSpec<?> bindToRouterFunction(RouterFunction<?> routerFunction) {
<ide> return new RouterFunctionSpec(routerFunction);
<ide> }
<ide>
<add> /**
<add> * Integration testing without a server targeting the given HttpHandler.
<add> * @param httpHandler the handler to test
<add> * @return the {@link WebTestClient} builder
<add> */
<add> static Builder bindToHttpHandler(HttpHandler httpHandler) {
<add> return new DefaultWebTestClientBuilder(httpHandler, null);
<add> }
<add>
<ide> /**
<ide> * Complete end-to-end integration tests with actual requests to a running server.
<ide> * @return the {@link WebTestClient} builder
<ide><path>spring-test/src/test/java/org/springframework/test/web/reactive/server/samples/bind/HttpHandlerTests.java
<add>/*
<add> * Copyright 2002-2017 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.test.web.reactive.server.samples.bind;
<add>
<add>import java.nio.charset.StandardCharsets;
<add>import java.util.Collections;
<add>
<add>import org.junit.Test;
<add>import reactor.core.publisher.Mono;
<add>
<add>import org.springframework.core.io.buffer.DataBuffer;
<add>import org.springframework.core.io.buffer.DefaultDataBufferFactory;
<add>import org.springframework.http.server.reactive.HttpHandler;
<add>import org.springframework.test.web.reactive.server.WebTestClient;
<add>import org.springframework.web.server.WebFilter;
<add>import org.springframework.web.server.adapter.WebHttpHandlerBuilder;
<add>
<add>/**
<add> * Bind to an {@link HttpHandler}.
<add> * @author Rossen Stoyanchev
<add> */
<add>public class HttpHandlerTests {
<add>
<add>
<add> @Test
<add> public void testWebFilter() throws Exception {
<add>
<add> WebFilter myFilter = (exchange, chain) -> {
<add> DataBuffer buffer = new DefaultDataBufferFactory().allocateBuffer();
<add> buffer.write("It works!".getBytes(StandardCharsets.UTF_8));
<add> return exchange.getResponse().writeWith(Mono.just(buffer));
<add> };
<add>
<add> HttpHandler httpHandler = WebHttpHandlerBuilder.webHandler(exchange -> Mono.empty())
<add> .filters(Collections.singletonList(myFilter)).build();
<add>
<add> WebTestClient.bindToHttpHandler(httpHandler).build()
<add> .get().uri("/")
<add> .exchange()
<add> .expectStatus().isOk()
<add> .expectBody(String.class).isEqualTo("It works!");
<add> }
<add>
<add>}
| 3
|
Text
|
Text
|
update jwt docs.
|
9ecce21044d14b66a9e41f156eda0f13754c756e
|
<ide><path>docs/api-guide/authentication.md
<ide> HTTP digest authentication is a widely implemented scheme that was intended to r
<ide>
<ide> ## JSON Web Token Authentication
<ide>
<del>JSON Web Token is a fairly new standard which can be used for token-based authentication. Unlike the built-in TokenAuthentication scheme, JWT Authentication doesn't need to use a database to validate a token. [Blimp][blimp] maintains the [djangorestframework-jwt][djangorestframework-jwt] package which provides a JWT Authentication class as well as a mechanism for clients to obtain a JWT given the username and password. An alternative package for JWT authentication is [djangorestframework-simplejwt][djangorestframework-simplejwt] which provides different features as well as a pluggable token blacklist app.
<add>JSON Web Token is a fairly new standard which can be used for token-based authentication. Unlike the built-in TokenAuthentication scheme, JWT Authentication doesn't need to use a database to validate a token. A package for JWT authentication is [djangorestframework-simplejwt][djangorestframework-simplejwt] which provides some features as well as a pluggable token blacklist app.
<ide>
<ide> ## Hawk HTTP Authentication
<ide>
<ide> HTTP Signature (currently a [IETF draft][http-signature-ietf-draft]) provides a
<ide> [django-oauth-toolkit]: https://github.com/evonove/django-oauth-toolkit
<ide> [evonove]: https://github.com/evonove/
<ide> [oauthlib]: https://github.com/idan/oauthlib
<del>[blimp]: https://github.com/GetBlimp
<del>[djangorestframework-jwt]: https://github.com/GetBlimp/django-rest-framework-jwt
<ide> [djangorestframework-simplejwt]: https://github.com/davesque/django-rest-framework-simplejwt
<ide> [etoccalino]: https://github.com/etoccalino/
<ide> [djangorestframework-httpsignature]: https://github.com/etoccalino/django-rest-framework-httpsignature
| 1
|
Javascript
|
Javascript
|
add regression test for nghttp2 cve-2018-1000168
|
0d79c84a839fb52ccb9e3f0c46541613a1d3db3a
|
<ide><path>test/common/http2.js
<ide> class PingFrame extends Frame {
<ide> }
<ide> }
<ide>
<add>class AltSvcFrame extends Frame {
<add> constructor(size) {
<add> const buffers = [Buffer.alloc(size)];
<add> super(size, 10, 0, 0);
<add> buffers.unshift(this[kFrameData]);
<add> this[kFrameData] = Buffer.concat(buffers);
<add> }
<add>}
<add>
<ide> module.exports = {
<ide> Frame,
<add> AltSvcFrame,
<ide> DataFrame,
<ide> HeadersFrame,
<ide> SettingsFrame,
<ide><path>test/parallel/test-http2-malformed-altsvc.js
<add>'use strict';
<add>
<add>const common = require('../common');
<add>
<add>if (!common.hasCrypto)
<add> common.skip('missing crypto');
<add>
<add>const http2 = require('http2');
<add>const net = require('net');
<add>const h2test = require('../common/http2');
<add>
<add>const server = http2.createServer();
<add>server.on('stream', common.mustNotCall());
<add>
<add>const settings = new h2test.SettingsFrame();
<add>const settingsAck = new h2test.SettingsFrame(true);
<add>const altsvc = new h2test.AltSvcFrame((1 << 14) + 1);
<add>
<add>server.listen(0, () => {
<add> const client = net.connect(server.address().port, () => {
<add> client.write(h2test.kClientMagic, () => {
<add> client.write(settings.data, () => {
<add> client.write(settingsAck.data);
<add> // Prior to nghttp2 1.31.1, sending this malformed altsvc frame
<add> // would cause a segfault. This test is successful if a segfault
<add> // does not occur.
<add> client.write(altsvc.data, common.mustCall(() => {
<add> client.destroy();
<add> }));
<add> });
<add> });
<add> });
<add>
<add> // An error may or may not be emitted on the client side, we don't care
<add> // either way if it is, but we don't want to die if it is.
<add> client.on('error', () => {});
<add> client.on('close', common.mustCall(() => server.close()));
<add> client.resume();
<add>});
| 2
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.