问:
NPE returned by a mocked function spring boot
I'm new to testing and I'm trying to learn unit testing using JUnit and spring boot and that exception popped up.
As you can see I mocked the behavior of the function I needed in the TopicSevices but I still get this NPE, I also tried to add

```<code>MockitoAnnotations.initMocks(this);
</code>```

But it didn't work.

The controller code

```<code>package com.example.test.controller;

import java.util.List;

import javax.validation.Valid;

import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import com.example.test.Services.ExerciceServices;
import com.example.test.Services.TopicService;
import com.example.test.model.Difficulty;
import com.example.test.model.Exercice;
import com.example.test.model.Status;
import com.example.test.model.dto.ExerciceDTO;

@CrossOrigin("*")
@RestController
public class ExerciceController {

    private final ExerciceServices exerciceServices;
    private final TopicService topicServices;

    public ExerciceController(ExerciceServices exerciceServices, TopicService topicServices) {

        this.exerciceServices = exerciceServices;
        this.topicServices = topicServices;
    }

    @GetMapping("/exercices")
    public List<Exercice> allExercices() {
        return exerciceServices.getAllExecices();
    }

    @PostMapping("/exercices")
    public Exercice createExercice(@Valid @RequestBody ExerciceDTO dto) {

        Exercice exercice = createExcerciceFromDto(dto);

        return exerciceServices.CreateeExercice(exercice);
    }

    public Exercice createExcerciceFromDto(ExerciceDTO dto) {

        Exercice exercice = new Exercice();

        exercice.setDifficulty(dto.getDifficulty());
        exercice.setImg(dto.getImg());
        exercice.setStatus(dto.getStatus());
        exercice.setTitle(dto.getTitle());

        for (Long id : dto.getListToppicId()) {
            try {
                System.out.println(topicServices.getTopicById(id));
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        return exercice;
    }

    @GetMapping("/exercices/filter")
    public List<Exercice> getExeerciceByDifficulty(@RequestParam(required = false) Long id,
            @RequestParam Difficulty difficulty, @RequestParam Status status) {

        return exerciceServices.exercicesFilterTopic(id, difficulty, status);

    }

}

</code>```

The test code

```<code>package com.example.test.controller;

import static org.junit.jupiter.api.Assertions.assertEquals;

import java.util.Arrays;
import java.util.HashSet;
import java.util.Optional;

import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.junit.runner.RunWith;
import org.mockito.InjectMocks;
import org.mockito.Mockito;
import org.mockito.junit.MockitoJUnitRunner;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.autoconfigure.web.servlet.WebMvcTest;
import org.springframework.boot.test.mock.mockito.MockBean;
import org.springframework.test.web.servlet.MockMvc;

import com.example.test.Services.ExerciceServices;
import com.example.test.Services.TopicService;
import com.example.test.model.Difficulty;
import com.example.test.model.Exercice;
import com.example.test.model.Status;
import com.example.test.model.Topic;
import com.example.test.model.dto.ExerciceDTO;

@RunWith(MockitoJUnitRunner.class)
@WebMvcTest

class ExerciceControllerTest {

    @MockBean
    private ExerciceServices exerciceServices;

    @MockBean
    private TopicService topicServices;

    @InjectMocks
    private ExerciceController exerciceController;

    ExerciceDTO dto = new ExerciceDTO();
    Exercice e = new Exercice();
    Topic t = new Topic();

    @BeforeEach
    public void setUp() throws Exception {
        Mockito.when(exerciceServices.getAllExecices()).thenReturn(Arrays.asList(e));
    }

    @Test
    public void givenDTOCreateTheExercice() {
        dto.setDifficulty(Difficulty.EASY);
        dto.setImg("link");
        dto.setStatus(Status.FINISHED);
        dto.setTitle("title");
        dto.setListToppicId(new HashSet<>(Arrays.asList(6L)));

        e.setDifficulty(Difficulty.EASY);
        e.setImg("link");
        e.setStatus(Status.FINISHED);
        e.setTitle("title");

        t.setId(6L);
        t.setTitle("romayssae");

        e.setTopics(new HashSet<>(Arrays.asList(t)));
        Optional<Topic> topic = Optional.of(t);

        Mockito.when(topicServices.getTopicById(6L)).thenReturn(topic);

        System.out.println(topicServices.getTopicById(6L));

        assertEquals(e, exerciceController.createExcerciceFromDto(dto));
    }

}

</code>```

The Exception

```<code>java.lang.NullPointerException
    at com.example.test.controller.ExerciceController.createExcerciceFromDto(ExerciceController.java:58)
    at com.example.test.controller.ExerciceControllerTest.givenDTOCreateTheExercice(ExcerciceControllerTest.java:77)
    at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at java.base/jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.base/java.lang.reflect.Method.invoke(Method.java:566)
    at org.junit.platform.commons.util.ReflectionUtils.invokeMethod(ReflectionUtils.java:675)
    at org.junit.jupiter.engine.execution.MethodInvocation.proceed(MethodInvocation.java:60)
    at org.junit.jupiter.engine.execution.InvocationInterceptorChain$ValidatingInvocation.proceed(InvocationInterceptorChain.java:125)
    at org.junit.jupiter.engine.extension.TimeoutExtension.intercept(TimeoutExtension.java:132)
    at org.junit.jupiter.engine.extension.TimeoutExtension.interceptTestableMethod(TimeoutExtension.java:124)
    at org.junit.jupiter.engine.extension.TimeoutExtension.interceptTestMethod(TimeoutExtension.java:74)
    at org.junit.jupiter.engine.execution.ExecutableInvoker$ReflectiveInterceptorCall.lambda$ofVoidMethod$0(ExecutableInvoker.java:115)
    at org.junit.jupiter.engine.execution.ExecutableInvoker.lambda$invoke$0(ExecutableInvoker.java:105)
    at org.junit.jupiter.engine.execution.InvocationInterceptorChain$InterceptedInvocation.proceed(InvocationInterceptorChain.java:104)
    at org.junit.jupiter.engine.execution.InvocationInterceptorChain.proceed(InvocationInterceptorChain.java:62)
    at org.junit.jupiter.engine.execution.InvocationInterceptorChain.chainAndInvoke(InvocationInterceptorChain.java:43)
    at org.junit.jupiter.engine.execution.InvocationInterceptorChain.invoke(InvocationInterceptorChain.java:35)
    at org.junit.jupiter.engine.execution.ExecutableInvoker.invoke(ExecutableInvoker.java:104)
    at org.junit.jupiter.engine.execution.ExecutableInvoker.invoke(ExecutableInvoker.java:98)
    at org.junit.jupiter.engine.descriptor.TestMethodTestDescriptor.lambda$invokeTestMethod$6(TestMethodTestDescriptor.java:202)
    at org.junit.platform.engine.support.hierarchical.ThrowableCollector.execute(ThrowableCollector.java:73)
    at org.junit.jupiter.engine.descriptor.TestMethodTestDescriptor.invokeTestMethod(TestMethodTestDescriptor.java:198)
    at org.junit.jupiter.engine.descriptor.TestMethodTestDescriptor.execute(TestMethodTestDescriptor.java:135)
    at org.junit.jupiter.engine.descriptor.TestMethodTestDescriptor.execute(TestMethodTestDescriptor.java:69)
    at org.junit.platform.engine.support.hierarchical.NodeTestTask.lambda$executeRecursively$5(NodeTestTask.java:135)
    at org.junit.platform.engine.support.hierarchical.ThrowableCollector.execute(ThrowableCollector.java:73)
    at org.junit.platform.engine.support.hierarchical.NodeTestTask.lambda$executeRecursively$7(NodeTestTask.java:125)
    at org.junit.platform.engine.support.hierarchical.Node.around(Node.java:135)
    at org.junit.platform.engine.support.hierarchical.NodeTestTask.lambda$executeRecursively$8(NodeTestTask.java:123)
    at org.junit.platform.engine.support.hierarchical.ThrowableCollector.execute(ThrowableCollector.java:73)
    at org.junit.platform.engine.support.hierarchical.NodeTestTask.executeRecursively(NodeTestTask.java:122)
    at org.junit.platform.engine.support.hierarchical.NodeTestTask.execute(NodeTestTask.java:80)
    at java.base/java.util.ArrayList.forEach(ArrayList.java:1540)
    at org.junit.platform.engine.support.hierarchical.SameThreadHierarchicalTestExecutorService.invokeAll(SameThreadHierarchicalTestExecutorService.java:38)
    at org.junit.platform.engine.support.hierarchical.NodeTestTask.lambda$executeRecursively$5(NodeTestTask.java:139)
    at org.junit.platform.engine.support.hierarchical.ThrowableCollector.execute(ThrowableCollector.java:73)
    at org.junit.platform.engine.support.hierarchical.NodeTestTask.lambda$executeRecursively$7(NodeTestTask.java:125)
    at org.junit.platform.engine.support.hierarchical.Node.around(Node.java:135)
    at org.junit.platform.engine.support.hierarchical.NodeTestTask.lambda$executeRecursively$8(NodeTestTask.java:123)
    at org.junit.platform.engine.support.hierarchical.ThrowableCollector.execute(ThrowableCollector.java:73)
    at org.junit.platform.engine.support.hierarchical.NodeTestTask.executeRecursively(NodeTestTask.java:122)
    at org.junit.platform.engine.support.hierarchical.NodeTestTask.execute(NodeTestTask.java:80)
    at java.base/java.util.ArrayList.forEach(ArrayList.java:1540)
    at org.junit.platform.engine.support.hierarchical.SameThreadHierarchicalTestExecutorService.invokeAll(SameThreadHierarchicalTestExecutorService.java:38)
    at org.junit.platform.engine.support.hierarchical.NodeTestTask.lambda$executeRecursively$5(NodeTestTask.java:139)
    at org.junit.platform.engine.support.hierarchical.ThrowableCollector.execute(ThrowableCollector.java:73)
    at org.junit.platform.engine.support.hierarchical.NodeTestTask.lambda$executeRecursively$7(NodeTestTask.java:125)
    at org.junit.platform.engine.support.hierarchical.Node.around(Node.java:135)
    at org.junit.platform.engine.support.hierarchical.NodeTestTask.lambda$executeRecursively$8(NodeTestTask.java:123)
    at org.junit.platform.engine.support.hierarchical.ThrowableCollector.execute(ThrowableCollector.java:73)
    at org.junit.platform.engine.support.hierarchical.NodeTestTask.executeRecursively(NodeTestTask.java:122)
    at org.junit.platform.engine.support.hierarchical.NodeTestTask.execute(NodeTestTask.java:80)
    at org.junit.platform.engine.support.hierarchical.SameThreadHierarchicalTestExecutorService.submit(SameThreadHierarchicalTestExecutorService.java:32)
    at org.junit.platform.engine.support.hierarchical.HierarchicalTestExecutor.execute(HierarchicalTestExecutor.java:57)
    at org.junit.platform.engine.support.hierarchical.HierarchicalTestEngine.execute(HierarchicalTestEngine.java:51)
    at org.junit.platform.launcher.core.DefaultLauncher.execute(DefaultLauncher.java:229)
    at org.junit.platform.launcher.core.DefaultLauncher.lambda$execute$6(DefaultLauncher.java:197)
    at org.junit.platform.launcher.core.DefaultLauncher.withInterceptedStreams(DefaultLauncher.java:211)
    at org.junit.platform.launcher.core.DefaultLauncher.execute(DefaultLauncher.java:191)
    at org.junit.platform.launcher.core.DefaultLauncher.execute(DefaultLauncher.java:137)
    at org.eclipse.jdt.internal.junit5.runner.JUnit5TestReference.run(JUnit5TestReference.java:89)
    at org.eclipse.jdt.internal.junit.runner.TestExecution.run(TestExecution.java:41)
    at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:541)
    at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:763)
    at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.run(RemoteTestRunner.java:463)
    at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.main(RemoteTestRunner.java:209)
</code>```

答:
I tried this and it worked for me, however, I did not understand why.

In short, I changed the @Mock instead of @MockBean as suggested by @arbuzov. Then I got this exception:

java.lang.IllegalStateException: Failed to load ApplicationContext

To solve this I added this two annotations @SpringBootTest and @AutoConfigureMockMvc. Then I tried to test another method using the MockMvc there again the mocked behavior was ignored somehow, so I changed back to @MockBean which worked.

I would be happy to receive any comments and explanations of how it works, if anyone has any.

```<code>package com.example.test.controller;

import static org.hamcrest.CoreMatchers.is;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.jsonPath;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;

import java.util.Arrays;
import java.util.HashSet;
import java.util.Optional;

import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.junit.runner.RunWith;
import org.mockito.InjectMocks;
import org.mockito.Mock;
import org.mockito.Mockito;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureMockMvc;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.boot.test.mock.mockito.MockBean;
import org.springframework.http.MediaType;
import org.springframework.test.context.junit4.SpringRunner;
import org.springframework.test.web.servlet.MockMvc;

import com.example.test.Services.ExerciceServices;
import com.example.test.Services.TopicService;
import com.example.test.model.Difficulty;
import com.example.test.model.Exercice;
import com.example.test.model.Status;
import com.example.test.model.Topic;
import com.example.test.model.dto.ExerciceDTO;

@RunWith(SpringRunner.class)
@SpringBootTest
@AutoConfigureMockMvc

class ExerciceControllerTest {

    @Autowired
    private MockMvc mockMvc;

    @MockBean
    private ExerciceServices exerciceServices;

    @Mock
    private TopicService topicServices;

    @InjectMocks
    private ExerciceController exerciceController;

    ExerciceDTO dto = new ExerciceDTO();
    Exercice e = new Exercice();
    Topic t = new Topic();

    @BeforeEach
    public void setUp() throws Exception {

    }

    @Test
    public void givenDTOCreateTheExercice() {

        assertEquals(e, exerciceController.createExcerciceFromDto(dto));
    }

    @Test
    public void eznekfnzre() throws Exception {
        dto.setDifficulty(Difficulty.EASY);
        dto.setImg("link");
        dto.setStatus(Status.FINISHED);
        dto.setTitle("title");
        dto.setListToppicId(new HashSet<>(Arrays.asList(6L)));

        e.setDifficulty(Difficulty.EASY);
        e.setImg("link");
        e.setStatus(Status.FINISHED);
        e.setTitle("title");

        t.setId(6L);
        t.setTitle("romayssae");

        e.setTopics(new HashSet<>(Arrays.asList(t)));
        Optional<Topic> topic = Optional.of(t);

        Mockito.when(topicServices.getTopicById(6L)).thenReturn(topic);
        Mockito.when(exerciceServices.getAllExecices()).thenReturn(Arrays.asList(e));
        mockMvc.perform(get("/exercices/").contentType(MediaType.APPLICATION_JSON)).andExpect(status().isOk())
                .andExpect(jsonPath("$[0].title", is(e.getTitle())));
    }

}
</code>```

Body:
I'm new to testing and I'm trying to learn unit testing using JUnit and spring boot and that exception popped up.
As you can see I mocked the behavior of the function I needed in the TopicSevices but I still get this NPE, I also tried to add

MockitoAnnotations.initMocks(this);

But it didn't work.

The controller code

package com.example.test.controller;

import java.util.List;

import javax.validation.Valid;

import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import com.example.test.Services.ExerciceServices;
import com.example.test.Services.TopicService;
import com.example.test.model.Difficulty;
import com.example.test.model.Exercice;
import com.example.test.model.Status;
import com.example.test.model.dto.ExerciceDTO;

@CrossOrigin("*")
@RestController
public class ExerciceController {

    private final ExerciceServices exerciceServices;
    private final TopicService topicServices;

    public ExerciceController(ExerciceServices exerciceServices, TopicService topicServices) {

        this.exerciceServices = exerciceServices;
        this.topicServices = topicServices;
    }

    @GetMapping("/exercices")
    public List<Exercice> allExercices() {
        return exerciceServices.getAllExecices();
    }

    @PostMapping("/exercices")
    public Exercice createExercice(@Valid @RequestBody ExerciceDTO dto) {

        Exercice exercice = createExcerciceFromDto(dto);

        return exerciceServices.CreateeExercice(exercice);
    }

    public Exercice createExcerciceFromDto(ExerciceDTO dto) {

        Exercice exercice = new Exercice();

        exercice.setDifficulty(dto.getDifficulty());
        exercice.setImg(dto.getImg());
        exercice.setStatus(dto.getStatus());
        exercice.setTitle(dto.getTitle());

        for (Long id : dto.getListToppicId()) {
            try {
                System.out.println(topicServices.getTopicById(id));
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        return exercice;
    }

    @GetMapping("/exercices/filter")
    public List<Exercice> getExeerciceByDifficulty(@RequestParam(required = false) Long id,
            @RequestParam Difficulty difficulty, @RequestParam Status status) {

        return exerciceServices.exercicesFilterTopic(id, difficulty, status);

    }

}

The test code

package com.example.test.controller;

import static org.junit.jupiter.api.Assertions.assertEquals;

import java.util.Arrays;
import java.util.HashSet;
import java.util.Optional;

import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.junit.runner.RunWith;
import org.mockito.InjectMocks;
import org.mockito.Mockito;
import org.mockito.junit.MockitoJUnitRunner;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.autoconfigure.web.servlet.WebMvcTest;
import org.springframework.boot.test.mock.mockito.MockBean;
import org.springframework.test.web.servlet.MockMvc;

import com.example.test.Services.ExerciceServices;
import com.example.test.Services.TopicService;
import com.example.test.model.Difficulty;
import com.example.test.model.Exercice;
import com.example.test.model.Status;
import com.example.test.model.Topic;
import com.example.test.model.dto.ExerciceDTO;

@RunWith(MockitoJUnitRunner.class)
@WebMvcTest

class ExerciceControllerTest {

    @MockBean
    private ExerciceServices exerciceServices;

    @MockBean
    private TopicService topicServices;

    @InjectMocks
    private ExerciceController exerciceController;

    ExerciceDTO dto = new ExerciceDTO();
    Exercice e = new Exercice();
    Topic t = new Topic();

    @BeforeEach
    public void setUp() throws Exception {
        Mockito.when(exerciceServices.getAllExecices()).thenReturn(Arrays.asList(e));
    }

    @Test
    public void givenDTOCreateTheExercice() {
        dto.setDifficulty(Difficulty.EASY);
        dto.setImg("link");
        dto.setStatus(Status.FINISHED);
        dto.setTitle("title");
        dto.setListToppicId(new HashSet<>(Arrays.asList(6L)));

        e.setDifficulty(Difficulty.EASY);
        e.setImg("link");
        e.setStatus(Status.FINISHED);
        e.setTitle("title");

        t.setId(6L);
        t.setTitle("romayssae");

        e.setTopics(new HashSet<>(Arrays.asList(t)));
        Optional<Topic> topic = Optional.of(t);

        Mockito.when(topicServices.getTopicById(6L)).thenReturn(topic);

        System.out.println(topicServices.getTopicById(6L));

        assertEquals(e, exerciceController.createExcerciceFromDto(dto));
    }

}

The Exception

java.lang.NullPointerException
    at com.example.test.controller.ExerciceController.createExcerciceFromDto(ExerciceController.java:58)
    at com.example.test.controller.ExerciceControllerTest.givenDTOCreateTheExercice(ExcerciceControllerTest.java:77)
    at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at java.base/jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.base/java.lang.reflect.Method.invoke(Method.java:566)
    at org.junit.platform.commons.util.ReflectionUtils.invokeMethod(ReflectionUtils.java:675)
    at org.junit.jupiter.engine.execution.MethodInvocation.proceed(MethodInvocation.java:60)
    at org.junit.jupiter.engine.execution.InvocationInterceptorChain$ValidatingInvocation.proceed(InvocationInterceptorChain.java:125)
    at org.junit.jupiter.engine.extension.TimeoutExtension.intercept(TimeoutExtension.java:132)
    at org.junit.jupiter.engine.extension.TimeoutExtension.interceptTestableMethod(TimeoutExtension.java:124)
    at org.junit.jupiter.engine.extension.TimeoutExtension.interceptTestMethod(TimeoutExtension.java:74)
    at org.junit.jupiter.engine.execution.ExecutableInvoker$ReflectiveInterceptorCall.lambda$ofVoidMethod$0(ExecutableInvoker.java:115)
    at org.junit.jupiter.engine.execution.ExecutableInvoker.lambda$invoke$0(ExecutableInvoker.java:105)
    at org.junit.jupiter.engine.execution.InvocationInterceptorChain$InterceptedInvocation.proceed(InvocationInterceptorChain.java:104)
    at org.junit.jupiter.engine.execution.InvocationInterceptorChain.proceed(InvocationInterceptorChain.java:62)
    at org.junit.jupiter.engine.execution.InvocationInterceptorChain.chainAndInvoke(InvocationInterceptorChain.java:43)
    at org.junit.jupiter.engine.execution.InvocationInterceptorChain.invoke(InvocationInterceptorChain.java:35)
    at org.junit.jupiter.engine.execution.ExecutableInvoker.invoke(ExecutableInvoker.java:104)
    at org.junit.jupiter.engine.execution.ExecutableInvoker.invoke(ExecutableInvoker.java:98)
    at org.junit.jupiter.engine.descriptor.TestMethodTestDescriptor.lambda$invokeTestMethod$6(TestMethodTestDescriptor.java:202)
    at org.junit.platform.engine.support.hierarchical.ThrowableCollector.execute(ThrowableCollector.java:73)
    at org.junit.jupiter.engine.descriptor.TestMethodTestDescriptor.invokeTestMethod(TestMethodTestDescriptor.java:198)
    at org.junit.jupiter.engine.descriptor.TestMethodTestDescriptor.execute(TestMethodTestDescriptor.java:135)
    at org.junit.jupiter.engine.descriptor.TestMethodTestDescriptor.execute(TestMethodTestDescriptor.java:69)
    at org.junit.platform.engine.support.hierarchical.NodeTestTask.lambda$executeRecursively$5(NodeTestTask.java:135)
    at org.junit.platform.engine.support.hierarchical.ThrowableCollector.execute(ThrowableCollector.java:73)
    at org.junit.platform.engine.support.hierarchical.NodeTestTask.lambda$executeRecursively$7(NodeTestTask.java:125)
    at org.junit.platform.engine.support.hierarchical.Node.around(Node.java:135)
    at org.junit.platform.engine.support.hierarchical.NodeTestTask.lambda$executeRecursively$8(NodeTestTask.java:123)
    at org.junit.platform.engine.support.hierarchical.ThrowableCollector.execute(ThrowableCollector.java:73)
    at org.junit.platform.engine.support.hierarchical.NodeTestTask.executeRecursively(NodeTestTask.java:122)
    at org.junit.platform.engine.support.hierarchical.NodeTestTask.execute(NodeTestTask.java:80)
    at java.base/java.util.ArrayList.forEach(ArrayList.java:1540)
    at org.junit.platform.engine.support.hierarchical.SameThreadHierarchicalTestExecutorService.invokeAll(SameThreadHierarchicalTestExecutorService.java:38)
    at org.junit.platform.engine.support.hierarchical.NodeTestTask.lambda$executeRecursively$5(NodeTestTask.java:139)
    at org.junit.platform.engine.support.hierarchical.ThrowableCollector.execute(ThrowableCollector.java:73)
    at org.junit.platform.engine.support.hierarchical.NodeTestTask.lambda$executeRecursively$7(NodeTestTask.java:125)
    at org.junit.platform.engine.support.hierarchical.Node.around(Node.java:135)
    at org.junit.platform.engine.support.hierarchical.NodeTestTask.lambda$executeRecursively$8(NodeTestTask.java:123)
    at org.junit.platform.engine.support.hierarchical.ThrowableCollector.execute(ThrowableCollector.java:73)
    at org.junit.platform.engine.support.hierarchical.NodeTestTask.executeRecursively(NodeTestTask.java:122)
    at org.junit.platform.engine.support.hierarchical.NodeTestTask.execute(NodeTestTask.java:80)
    at java.base/java.util.ArrayList.forEach(ArrayList.java:1540)
    at org.junit.platform.engine.support.hierarchical.SameThreadHierarchicalTestExecutorService.invokeAll(SameThreadHierarchicalTestExecutorService.java:38)
    at org.junit.platform.engine.support.hierarchical.NodeTestTask.lambda$executeRecursively$5(NodeTestTask.java:139)
    at org.junit.platform.engine.support.hierarchical.ThrowableCollector.execute(ThrowableCollector.java:73)
    at org.junit.platform.engine.support.hierarchical.NodeTestTask.lambda$executeRecursively$7(NodeTestTask.java:125)
    at org.junit.platform.engine.support.hierarchical.Node.around(Node.java:135)
    at org.junit.platform.engine.support.hierarchical.NodeTestTask.lambda$executeRecursively$8(NodeTestTask.java:123)
    at org.junit.platform.engine.support.hierarchical.ThrowableCollector.execute(ThrowableCollector.java:73)
    at org.junit.platform.engine.support.hierarchical.NodeTestTask.executeRecursively(NodeTestTask.java:122)
    at org.junit.platform.engine.support.hierarchical.NodeTestTask.execute(NodeTestTask.java:80)
    at org.junit.platform.engine.support.hierarchical.SameThreadHierarchicalTestExecutorService.submit(SameThreadHierarchicalTestExecutorService.java:32)
    at org.junit.platform.engine.support.hierarchical.HierarchicalTestExecutor.execute(HierarchicalTestExecutor.java:57)
    at org.junit.platform.engine.support.hierarchical.HierarchicalTestEngine.execute(HierarchicalTestEngine.java:51)
    at org.junit.platform.launcher.core.DefaultLauncher.execute(DefaultLauncher.java:229)
    at org.junit.platform.launcher.core.DefaultLauncher.lambda$execute$6(DefaultLauncher.java:197)
    at org.junit.platform.launcher.core.DefaultLauncher.withInterceptedStreams(DefaultLauncher.java:211)
    at org.junit.platform.launcher.core.DefaultLauncher.execute(DefaultLauncher.java:191)
    at org.junit.platform.launcher.core.DefaultLauncher.execute(DefaultLauncher.java:137)
    at org.eclipse.jdt.internal.junit5.runner.JUnit5TestReference.run(JUnit5TestReference.java:89)
    at org.eclipse.jdt.internal.junit.runner.TestExecution.run(TestExecution.java:41)
    at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:541)
    at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:763)
    at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.run(RemoteTestRunner.java:463)
    at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.main(RemoteTestRunner.java:209)

Body:
I tried this and it worked for me, however, I did not understand why.

In short, I changed the @Mock instead of @MockBean as suggested by @arbuzov. Then I got this exception:

java.lang.IllegalStateException: Failed to load ApplicationContext

To solve this I added this two annotations @SpringBootTest and @AutoConfigureMockMvc. Then I tried to test another method using the MockMvc there again the mocked behavior was ignored somehow, so I changed back to @MockBean which worked.

I would be happy to receive any comments and explanations of how it works, if anyone has any.

package com.example.test.controller;

import static org.hamcrest.CoreMatchers.is;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.jsonPath;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;

import java.util.Arrays;
import java.util.HashSet;
import java.util.Optional;

import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.junit.runner.RunWith;
import org.mockito.InjectMocks;
import org.mockito.Mock;
import org.mockito.Mockito;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureMockMvc;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.boot.test.mock.mockito.MockBean;
import org.springframework.http.MediaType;
import org.springframework.test.context.junit4.SpringRunner;
import org.springframework.test.web.servlet.MockMvc;

import com.example.test.Services.ExerciceServices;
import com.example.test.Services.TopicService;
import com.example.test.model.Difficulty;
import com.example.test.model.Exercice;
import com.example.test.model.Status;
import com.example.test.model.Topic;
import com.example.test.model.dto.ExerciceDTO;

@RunWith(SpringRunner.class)
@SpringBootTest
@AutoConfigureMockMvc

class ExerciceControllerTest {

    @Autowired
    private MockMvc mockMvc;

    @MockBean
    private ExerciceServices exerciceServices;

    @Mock
    private TopicService topicServices;

    @InjectMocks
    private ExerciceController exerciceController;

    ExerciceDTO dto = new ExerciceDTO();
    Exercice e = new Exercice();
    Topic t = new Topic();

    @BeforeEach
    public void setUp() throws Exception {

    }

    @Test
    public void givenDTOCreateTheExercice() {

        assertEquals(e, exerciceController.createExcerciceFromDto(dto));
    }

    @Test
    public void eznekfnzre() throws Exception {
        dto.setDifficulty(Difficulty.EASY);
        dto.setImg("link");
        dto.setStatus(Status.FINISHED);
        dto.setTitle("title");
        dto.setListToppicId(new HashSet<>(Arrays.asList(6L)));

        e.setDifficulty(Difficulty.EASY);
        e.setImg("link");
        e.setStatus(Status.FINISHED);
        e.setTitle("title");

        t.setId(6L);
        t.setTitle("romayssae");

        e.setTopics(new HashSet<>(Arrays.asList(t)));
        Optional<Topic> topic = Optional.of(t);

        Mockito.when(topicServices.getTopicById(6L)).thenReturn(topic);
        Mockito.when(exerciceServices.getAllExecices()).thenReturn(Arrays.asList(e));
        mockMvc.perform(get("/exercices/").contentType(MediaType.APPLICATION_JSON)).andExpect(status().isOk())
                .andExpect(jsonPath("$[0].title", is(e.getTitle())));
    }

}


来源: stackexchange

问:
Reading .data file using Pandas
I am working on a Deep Learning project, the data was provided to me in a file with the ".data" extension. Able to read the data from the file using the Pandas "read_csv" function. I tried to search about the file properties on the web, but i am not clear about the file properties, usage, etc. Here are the few questions i have,

What is the ".data" file?

How they are created? (Mean exported from any application or database)

Is this the correct way to read the ".data" file using the pd.read_csv method? (Tried read_table as well)

Is there any other way to read the ".data" file?

答:
Recently i found a solution for .data files using pandas.

```<code>import pandas as pd
data = pd.read_fwf("example.data")
</code>```

For more details check here.

ContentLicense: CC BY-SA 4.0

Title: Reading .data file using Pandas

Body:
Recently i found a solution for .data files using pandas.

import pandas as pd
data = pd.read_fwf("example.data")

For more details check here.


问:
Create thumbnail file when cropping and converting in FFMPEG
I'm currently using the following:

```<code>ffmpeg -y -i input.mov -i watermark.png -filter_complex "[0:v]crop=iw-0:ih-440,scale=480:640[bg];[bg][1:v]overlay=W-w-10:H-h-10" output.mp4
</code>```

To resize, crop and watermark a video, all is working perfectly, however I'd like to grab a screenshot midway through. I've tried adding:

```<code>-qscale:v 2 thumbnail.jpg
</code>```

After the input.mov, however it then ruins the rest of the script. Bit of a noob to FFMpeg.

EDIT:

The following:

```<code>ffmpeg -y -i input.mov -vframes 1 -q:v 2 thumbnail.jpg -i watermark.png -filter_complex "[0:v]crop=iw-0:ih-440,scale=480:640[bg];[bg][1:v]overlay=W-w-10:H-h-10" output.mp4
</code>```

Creates the thumbnail and creates output.mp4, but not cropped or with the thumbnail. I'm assuming the thumbnail creation needs to go in that same sequence?

答:
If the 10th frame is fine, then you can use

ffmpeg -y -i input.mov -i watermark.png -filter_complex "[0:v]crop=iw-0:ih-440,scale=480:640[bg];[bg][1:v]overlay=W-w-10:H-h-10,split=2[v][pic];[pic]trim=start_frame=10[pic]" -map "[v]" -map 0:a? output.mp4 -vframes 1 -map "[pic]" out.jpg

If you know the midway duration, e.g. 12.5s, then your trim arg can be trim=st=12.5

(If you're on a shell where [] are special characters, use single quotes for mapping)

Body:
I'm currently using the following:

ffmpeg -y -i input.mov -i watermark.png -filter_complex "[0:v]crop=iw-0:ih-440,scale=480:640[bg];[bg][1:v]overlay=W-w-10:H-h-10" output.mp4

To resize, crop and watermark a video, all is working perfectly, however I'd like to grab a screenshot midway through. I've tried adding:

-qscale:v 2 thumbnail.jpg

After the input.mov, however it then ruins the rest of the script. Bit of a noob to FFMpeg.

EDIT:

The following:

ffmpeg -y -i input.mov -vframes 1 -q:v 2 thumbnail.jpg -i watermark.png -filter_complex "[0:v]crop=iw-0:ih-440,scale=480:640[bg];[bg][1:v]overlay=W-w-10:H-h-10" output.mp4

Creates the thumbnail and creates output.mp4, but not cropped or with the thumbnail. I'm assuming the thumbnail creation needs to go in that same sequence?


问:
npm error - Cannot find module './selenium-webdriver/lib/input'
After I updated my Angular project's version from 5 to 7, I was getting a lot of vulnerabilities, to fix it - I ran all the commands that was suggested in the "npm audit" and all the vulnerabilities was fixed.

But now when I run:

```<code>ng serve
</code>```

I get this error:

ERROR in node_modules/protractor/built/ptor.d.ts(33,17): error TS2307: Cannot find module './selenium-webdriver/lib/input'.

Edit

If I get in to the errors sources I can see the problem line:

```<code>// node_modules/protractor/built/ptor.d.ts
 Key: import("./selenium-webdriver/lib/input").IKey;
</code>```

and if I change the line to:

```<code> Key: import("../../selenium-webdriver/lib/input").IKey;
</code>```

it's fix the error.

I guess it's a versions issue, but now remains to find out what the correct versions.

This is my package.json file:

```<code>{
"name": "test",
 "version": "1.0.0",
"license": "MIT",
"scripts": {
"ng": "ng",
"start": "ng serve",
"build": "ng build --prod",
"test": "ng test",
"lint": "ng lint",
"e2e": "ng e2e"
},
"private": true,
"dependencies": {
"@angular-devkit/core": "7.3.6",
"@angular/animations": "7.2.11",
"@angular/common": "7.2.11",
"@angular/compiler": "7.2.11",
"@angular/core": "7.2.11",
"@angular/forms": "7.2.11",
"@angular/http": "7.2.11",
"@angular/platform-browser": "7.2.11",
"@angular/platform-browser-dynamic": "7.2.11",
"@angular/router": "7.2.11",
"core-js": "^2.4.1",
"rxjs": "^6.4.0",
"selenium-webdriver": "^4.0.0-alpha.1",
"tslib": "^1.9.0",
"zone.js": "^0.8.29"
},
"devDependencies": {
"@angular-devkit/build-angular": "^0.13.7",
"@angular/cli": "7.3.6",
"@angular/compiler-cli": "7.2.11",
"@angular/language-service": "7.2.11",
"@types/jasmine": "~2.5.53",
"@types/jasminewd2": "~2.0.2",
"@types/node": "~6.0.60",
"codelyzer": "^4.0.1",
"jasmine-core": "~2.6.2",
"jasmine-spec-reporter": "~4.1.0",
"karma": "^4.0.1",
"karma-chrome-launcher": "~2.1.1",
"karma-cli": "~1.0.1",
"karma-coverage-istanbul-reporter": "^1.2.1",
"karma-jasmine": "~1.1.0",
"karma-jasmine-html-reporter": "^0.2.2",
"protractor": "^6.0.0",
"ts-node": "~3.2.0",
"tslint": "~5.7.0",
"typescript": "3.2.4"
 },
"description": "This project was generated with [Angular CLI]
(https://github.com/angular/angular-cli) version 1.6.3.",
"main": "/",
"repository": {
"type": "git",
"url": "/"
 },
"keywords": [
"/"
],
"author": "/"
}
</code>```

Any ideas why?

答:
If this happens suddenly after saving your code and you are using visual studio code:
Search for protractor and consider checking your created typescript files for unused imports.

You can delete them using alt+shift+o

Save your files and run ng serve, this should solve your problem

Body:
After I updated my Angular project's version from 5 to 7, I was getting a lot of vulnerabilities, to fix it - I ran all the commands that was suggested in the "npm audit" and all the vulnerabilities was fixed.

But now when I run:

ng serve

I get this error:

ERROR in node_modules/protractor/built/ptor.d.ts(33,17): error TS2307: Cannot find module './selenium-webdriver/lib/input'.

Edit

If I get in to the errors sources I can see the problem line:

// node_modules/protractor/built/ptor.d.ts
 Key: import("./selenium-webdriver/lib/input").IKey;

and if I change the line to:

 Key: import("../../selenium-webdriver/lib/input").IKey;

it's fix the error.

I guess it's a versions issue, but now remains to find out what the correct versions.

This is my package.json file:

{
"name": "test",
 "version": "1.0.0",
"license": "MIT",
"scripts": {
"ng": "ng",
"start": "ng serve",
"build": "ng build --prod",
"test": "ng test",
"lint": "ng lint",
"e2e": "ng e2e"
},
"private": true,
"dependencies": {
"@angular-devkit/core": "7.3.6",
"@angular/animations": "7.2.11",
"@angular/common": "7.2.11",
"@angular/compiler": "7.2.11",
"@angular/core": "7.2.11",
"@angular/forms": "7.2.11",
"@angular/http": "7.2.11",
"@angular/platform-browser": "7.2.11",
"@angular/platform-browser-dynamic": "7.2.11",
"@angular/router": "7.2.11",
"core-js": "^2.4.1",
"rxjs": "^6.4.0",
"selenium-webdriver": "^4.0.0-alpha.1",
"tslib": "^1.9.0",
"zone.js": "^0.8.29"
},
"devDependencies": {
"@angular-devkit/build-angular": "^0.13.7",
"@angular/cli": "7.3.6",
"@angular/compiler-cli": "7.2.11",
"@angular/language-service": "7.2.11",
"@types/jasmine": "~2.5.53",
"@types/jasminewd2": "~2.0.2",
"@types/node": "~6.0.60",
"codelyzer": "^4.0.1",
"jasmine-core": "~2.6.2",
"jasmine-spec-reporter": "~4.1.0",
"karma": "^4.0.1",
"karma-chrome-launcher": "~2.1.1",
"karma-cli": "~1.0.1",
"karma-coverage-istanbul-reporter": "^1.2.1",
"karma-jasmine": "~1.1.0",
"karma-jasmine-html-reporter": "^0.2.2",
"protractor": "^6.0.0",
"ts-node": "~3.2.0",
"tslint": "~5.7.0",
"typescript": "3.2.4"
 },
"description": "This project was generated with [Angular CLI]
(https://github.com/angular/angular-cli) version 1.6.3.",
"main": "/",
"repository": {
"type": "git",
"url": "/"
 },
"keywords": [
"/"
],
"author": "/"
}

Any ideas why?


问:
What should be the top level of a Backbone.js application? A view, generic object,?
I'm confused about what code I should instantiate directly in Backbone.js.  Should I create a generic object App that instantiates my views?  Should I instantiate an App View that instantiates all the other views on the page and coordinates everything?  Should I create views, models and collections and attach them to the window ?

Also, are controllers even necessary?  So far I'm not finding any use for them and they are missing from many of the examples out there.  Should I instantiate a controller and have it create the other objects as I do in other languages' MVC frameworks?

My guess is I am free to do what I want but I would prefer some advice from somebody who has used it quite a lot.

答:
Controllers are useful for managing the hashbang URL.

If you don't have multiple pages, states you want to save or want to use the back and forwards buttons then controllers have no use.

Most examples of backbone I've seen have a AppView class that manages views and collections.

See the Annotated Example

ContentLicense: CC BY-SA 3.0


问:
Is there an kotlin equivalent of ?: java operator?
Reluctant kotlin newbie here.

Is there an kotlin equivalent of ?: java operator?

I tried searching on google. Most results talk about ?: (elvis operator) in kotlin.

Looking for a way to write this in kotlin:

```<code>//java example
//return condition ? a : b;
</code>```

答:
The nicest way to do it is this: </p>

```<code>return when {
    condition -> a
    else -> b
}
</code>```

Body:
Reluctant kotlin newbie here.

Is there an kotlin equivalent of ?: java operator?

I tried searching on google. Most results talk about ?: (elvis operator) in kotlin.

Looking for a way to write this in kotlin:

//java example
//return condition ? a : b;

Body:
The nicest way to do it is this:

return when {
    condition -> a
    else -> b
}


问:
Using Python to zip and list functions to combine two 2D arrays to produce x,y coordinates?
I have two, 2D-arrays each of dimensions 831 x 918. If:

Matrix A =[[a(1,1), a(1,2),...],[a(2,1),a(2,2)...]]
Matrix B =[[b(1,1), b(1,2),...],[b(2,1),b(2,2)...]]

I would like to combine the two matrices to create a list with ((a(1,1),b(1,1)),(a(1,2),b(1,2)),...).

What is the best way to do this? I have tried to use the zip and list functions as shown below:

```<code>import numpy as np
from astropy.io import fits
import matplotlib.pyplot as plt

ly=fits.open(lightyield.fits)
ly=ly[0].data
dx=fits.open(de.fits)
dx=dx[0].data
combo=list(zip(dx,ly))
</code>```

However, this returns a list that is 831 elements long, but each position on the list has a lot of elements. I only want to have a single (x,y) point for each element in the list, not an entire array.

Thanks for any help.
EDIT: As a basic example, for:
 A=[[1,2,3],[4,5,6],[7,8,9]]
 B=[[10,11,12],[13,14,15],[16,17,18]]

I want to get a list to plot of ((1,10),(2,11),(3,12),...).

答:
you can achieve it as...convert A and B to np object of shape=(813,918) then</p>

```<code> result = np.vstack((A[0],B[0])).T
</code>```

Body:
I have two, 2D-arrays each of dimensions 831 x 918. If:

Matrix A =[[a(1,1), a(1,2),...],[a(2,1),a(2,2)...]]
Matrix B =[[b(1,1), b(1,2),...],[b(2,1),b(2,2)...]]

I would like to combine the two matrices to create a list with ((a(1,1),b(1,1)),(a(1,2),b(1,2)),...).

What is the best way to do this? I have tried to use the zip and list functions as shown below:

import numpy as np
from astropy.io import fits
import matplotlib.pyplot as plt

ly=fits.open(lightyield.fits)
ly=ly[0].data
dx=fits.open(de.fits)
dx=dx[0].data
combo=list(zip(dx,ly))

However, this returns a list that is 831 elements long, but each position on the list has a lot of elements. I only want to have a single (x,y) point for each element in the list, not an entire array.

Thanks for any help.
EDIT: As a basic example, for:
 A=[[1,2,3],[4,5,6],[7,8,9]]
 B=[[10,11,12],[13,14,15],[16,17,18]]

I want to get a list to plot of ((1,10),(2,11),(3,12),...).

Body:
you can achieve it as...convert A and B to np object of shape=(813,918) then

 result = np.vstack((A[0],B[0])).T


问:
How to render the ReactDOM every second?
I'm new to React, I'm trying to follow this ticking clock example but do something a bit different. I'd like the ReactDOM to be rendered in the index.js. Here is my code:

Timer.js:

import React from 'react';

const Timer = () => {
    const tick = () => {
        return new Date().toLocaleTimeString().toString();
    };

    const element = (

Hello World!

It is {tick()} !

    );

    return (
        element
    );
};

export default Timer;```
</div>
</div>
</p>

<p><strong>App.js:</strong> </p>

<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>/*jshint esversion: 8 */
import React from 'react';
import logo from './logo.svg';
import './App.css';
import Timer from './Timer'

function App() {
  return (
    <div className="App">
      <Timer />
    </div>
  );
}

export default App;</code>```

index.js:

import React from "react";
import ReactDOM from "react-dom";
import "./index.css";
import * as serviceWorker from "./serviceWorker";
import App from './App';

setInterval(ReactDOM.render(<App />, document.getElementById("root")), 1000);

serviceWorker.unregister();```

But it only prints the current time on screen, not ticking. Why does the code setInterval(ReactDOM.render(<App />, document.getElementById("root")), 1000); not work on index.js?

答:
It is a good practice to avoid calling directly the render function, you could make your Timer a Component and let it update with state changes, which is how react would do it with its life cycle. For example:

```<code>class Timer extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      time: new Date().toLocaleTimeString().toString()
    };
  }
  tick() {
    this.setState({
      time: new Date().toLocaleTimeString().toString()
    });
  }
  componentDidMount() {
    this.intervalID = setInterval(
      () => this.tick(),
      1000
    );
  }
  componentWillUnmount() {
    clearInterval(this.intervalID);
  }
  render() {
    return (
      <div>
            <h1>Hello World!</h1>
            <h2>It is {this.state.time} !</h2>
        </div>
    );
  }
}

export default Timer;
</code>```

Notice I used two of React cycle functions componentDidMount and componentWillUnmount, in order to make the component update once again after finished mouting, and the other to clear the interval variable once react unmounts your component.

Body:
I'm new to React, I'm trying to follow this ticking clock example but do something a bit different. I'd like the ReactDOM to be rendered in the index.js. Here is my code:

Timer.js:

import React from 'react';

const Timer = () => {
    const tick = () => {
        return new Date().toLocaleTimeString().toString();
    };

    const element = (

Hello World!

It is {tick()} !

    );

    return (
        element
    );
};

export default Timer;

App.js:

/*jshint esversion: 8 */
import React from 'react';
import logo from './logo.svg';
import './App.css';
import Timer from './Timer'

function App() {
  return (

      <Timer />

  );
}

export default App;

index.js:

import React from "react";
import ReactDOM from "react-dom";
import "./index.css";
import * as serviceWorker from "./serviceWorker";
import App from './App';

setInterval(ReactDOM.render(<App />, document.getElementById("root")), 1000);

serviceWorker.unregister();

But it only prints the current time on screen, not ticking. Why does the code setInterval(ReactDOM.render(<App />, document.getElementById("root")), 1000); not work on index.js?

Body:
It is a good practice to avoid calling directly the render function, you could make your Timer a Component and let it update with state changes, which is how react would do it with its life cycle. For example:

class Timer extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      time: new Date().toLocaleTimeString().toString()
    };
  }
  tick() {
    this.setState({
      time: new Date().toLocaleTimeString().toString()
    });
  }
  componentDidMount() {
    this.intervalID = setInterval(
      () => this.tick(),
      1000
    );
  }
  componentWillUnmount() {
    clearInterval(this.intervalID);
  }
  render() {
    return (
      <div>
            <h1>Hello World!</h1>
            <h2>It is {this.state.time} !</h2>
        </div>
    );
  }
}

export default Timer;

Notice I used two of React cycle functions componentDidMount and componentWillUnmount, in order to make the component update once again after finished mouting, and the other to clear the interval variable once react unmounts your component.


问:
Parse XML via OPENXML SQL Server 2008
Context: I have an XML document below that I am trying to query in SQL Server 2008. I've followed the tips here: https://www.youtube.com/watch?v=vy2Nv26UzAU and have a query that executes without errors however returns nulls in fields that are clearly not empty.

Question: Can someone please provide some pointers/troubleshooting hints as to why the query is returning null results? Is it an issue with the hierarchy path or data types?

Here is the XML Document:

```<code><Order_Details>
<Selection_ID>2100</Selection_ID>
<Order_Details>
  <Able_To_Use>Y</Able_To_Use>
  <Purchase_ID>GF-00000001</Purchase_ID>
  <QTY>1</QTY>
  <Subdetails>
    <REGION_QTY>2</REGION_QTY>
    <Testing_NO>00.05.04.01.00</Testing_NO>
  </Subdetails>
</Order_Details>
<Order_Details>
  <Able_To_Use>Y</Able_To_Use>
  <Purchase_ID>GF-00000002</Purchase_ID>
  <QTY>1</QTY>
  <Subdetails>
    <REGION_QTY>2</REGION_QTY>
    <Testing_NO>00.05.04.01.034</Testing_NO>
  </Subdetails>
</Order_Details>
</code>```

Here is the query:

```<code>--Declare a table variable to hold the data in single column of XML data type
DECLARE @xml_data XML

SELECT @xml_data=O
FROM OPENROWSET(BULK N'C:\Users\Desktop\Important Docs & Links\Important     Documents\Python Scripts\separate_xml_doc.xml', SINGLE_BLOB) as file_output(O)

DECLARE @xml_doc int

--Procedure below takes 2 parameters: 1) output parameter to store handle to xml document and 2) the xml document itself
EXEC sp_xml_preparedocument @xml_doc OUTPUT, @xml_data

SELECT *
FROM OPENXML(@xml_doc,'/Order_Details/Order_Details/',2)
WITH (
        Able_To_Use nvarchar(10),
        Purchase_ID nvarchar(20),
        QTY int
        )

--This procedre removes the saved prepared xml document from memory once finished using
EXEC sp_xml_removedocument @xml_doc
</code>```

These are the results:

答:
In order to get your own attempt running, there's nothing more than one / to much:

```<code>FROM OPENXML(@xml_doc,'/Order_Details/Order_Details',2)
</code>```

But this approach is outdated. FROM OPENXML, together with the SPs to prepare and to remove a document should not be used any more (rare exceptions exist).

The modern way for XML (since v2005 :-) ) is to use the native XML methods, the XML type provides:

```<code>--Declare a table variable to hold the data in single column of XML data type
DECLARE @xml_data XML

SELECT @xml_data=
N'<Order_Details>
<Selection_ID>2100</Selection_ID>
<Order_Details>
  <Able_To_Use>Y</Able_To_Use>
  <Purchase_ID>GF-00000001</Purchase_ID>
  <QTY>1</QTY>
  <Subdetails>
    <REGION_QTY>2</REGION_QTY>
    <Testing_NO>00.05.04.01.00</Testing_NO>
  </Subdetails>
</Order_Details>
<Order_Details>
  <Able_To_Use>Y</Able_To_Use>
  <Purchase_ID>GF-00000002</Purchase_ID>
  <QTY>1</QTY>
  <Subdetails>
    <REGION_QTY>2</REGION_QTY>
    <Testing_NO>00.05.04.01.034</Testing_NO>
  </Subdetails>
</Order_Details>
</Order_Details>';
</code>```

--The query

```<code>SELECT @xml_data.value('(/Order_Details/Selection_ID/text())[1]','int') AS SelectionId
      ,od.value('(Able_To_Use/text())[1]','nchar(1)') AS AbleToUse
      ,od.value('(Purchase_ID/text())[1]','nvarchar(10)') AS PurchaseId
      ,od.value('(QTY/text())[1]','int') AS Quantity
      ,od.value('(Subdetails/REGION_QTY/text())[1]','int') AS RegionQty
      ,od.value('(Subdetails/Testing_NO/text())[1]','nvarchar(10)') AS TestingNo
FROM @xml_data.nodes('/Order_Details/Order_Details') A(od)
</code>```

I pick various levels here.

The Selection_ID can be taken from the variable directly.

We can use .nodes() to retrieve a set of repeating elements

We can use .value() with a XPath to grab into the elements and fetch their text nodes.

The code above is the most explicit. This can be put simpler, but it is a good idea with XML to keep it as explicit as possible. Just to demonstrate, what would work doo:

This query has the same result, but it is not recommended...

```<code>SELECT @xml_data.value('(//Selection_ID)[1]','int') AS SelectionId
      ,od.value('Able_To_Use[1]','nchar(1)') AS AbleToUse
      ,od.value('Purchase_ID[1]','nvarchar(10)') AS PurchaseId
      ,od.value('QTY[1]','int') AS Quantity
      ,od.value('(Subdetails/REGION_QTY)[1]','int') AS RegionQty
      ,od.value('(Subdetails/Testing_NO)[1]','nvarchar(10)') AS TestingNo
FROM @xml_data.nodes('/Order_Details/Order_Details') A(od)
</code>```

Title: Parse XML via OPENXML SQL Server 2008

Body:
Context: I have an XML document below that I am trying to query in SQL Server 2008. I've followed the tips here: https://www.youtube.com/watch?v=vy2Nv26UzAU and have a query that executes without errors however returns nulls in fields that are clearly not empty.

Question: Can someone please provide some pointers/troubleshooting hints as to why the query is returning null results? Is it an issue with the hierarchy path or data types?

Here is the XML Document:

<Order_Details>
<Selection_ID>2100</Selection_ID>
<Order_Details>
  <Able_To_Use>Y</Able_To_Use>
  <Purchase_ID>GF-00000001</Purchase_ID>
  <QTY>1</QTY>
  <Subdetails>
    <REGION_QTY>2</REGION_QTY>
    <Testing_NO>00.05.04.01.00</Testing_NO>
  </Subdetails>
</Order_Details>
<Order_Details>
  <Able_To_Use>Y</Able_To_Use>
  <Purchase_ID>GF-00000002</Purchase_ID>
  <QTY>1</QTY>
  <Subdetails>
    <REGION_QTY>2</REGION_QTY>
    <Testing_NO>00.05.04.01.034</Testing_NO>
  </Subdetails>
</Order_Details>

Here is the query:

--Declare a table variable to hold the data in single column of XML data type
DECLARE @xml_data XML

SELECT @xml_data=O
FROM OPENROWSET(BULK N'C:\Users\Desktop\Important Docs & Links\Important     Documents\Python Scripts\separate_xml_doc.xml', SINGLE_BLOB) as file_output(O)

DECLARE @xml_doc int

--Procedure below takes 2 parameters: 1) output parameter to store handle to xml document and 2) the xml document itself
EXEC sp_xml_preparedocument @xml_doc OUTPUT, @xml_data

SELECT *
FROM OPENXML(@xml_doc,'/Order_Details/Order_Details/',2)
WITH (
        Able_To_Use nvarchar(10),
        Purchase_ID nvarchar(20),
        QTY int
        )

--This procedre removes the saved prepared xml document from memory once finished using
EXEC sp_xml_removedocument @xml_doc

These are the results:

Body:
In order to get your own attempt running, there's nothing more than one / to much:

FROM OPENXML(@xml_doc,'/Order_Details/Order_Details',2)

But this approach is outdated. FROM OPENXML, together with the SPs to prepare and to remove a document should not be used any more (rare exceptions exist).

The modern way for XML (since v2005 :-) ) is to use the native XML methods, the XML type provides:

--Declare a table variable to hold the data in single column of XML data type
DECLARE @xml_data XML

SELECT @xml_data=
N'<Order_Details>
<Selection_ID>2100</Selection_ID>
<Order_Details>
  <Able_To_Use>Y</Able_To_Use>
  <Purchase_ID>GF-00000001</Purchase_ID>
  <QTY>1</QTY>
  <Subdetails>
    <REGION_QTY>2</REGION_QTY>
    <Testing_NO>00.05.04.01.00</Testing_NO>
  </Subdetails>
</Order_Details>
<Order_Details>
  <Able_To_Use>Y</Able_To_Use>
  <Purchase_ID>GF-00000002</Purchase_ID>
  <QTY>1</QTY>
  <Subdetails>
    <REGION_QTY>2</REGION_QTY>
    <Testing_NO>00.05.04.01.034</Testing_NO>
  </Subdetails>
</Order_Details>
</Order_Details>';

--The query

SELECT @xml_data.value('(/Order_Details/Selection_ID/text())[1]','int') AS SelectionId
      ,od.value('(Able_To_Use/text())[1]','nchar(1)') AS AbleToUse
      ,od.value('(Purchase_ID/text())[1]','nvarchar(10)') AS PurchaseId
      ,od.value('(QTY/text())[1]','int') AS Quantity
      ,od.value('(Subdetails/REGION_QTY/text())[1]','int') AS RegionQty
      ,od.value('(Subdetails/Testing_NO/text())[1]','nvarchar(10)') AS TestingNo
FROM @xml_data.nodes('/Order_Details/Order_Details') A(od)

I pick various levels here.

The Selection_ID can be taken from the variable directly.

We can use .nodes() to retrieve a set of repeating elements

We can use .value() with a XPath to grab into the elements and fetch their text nodes.

The code above is the most explicit. This can be put simpler, but it is a good idea with XML to keep it as explicit as possible. Just to demonstrate, what would work doo:

This query has the same result, but it is not recommended...

SELECT @xml_data.value('(//Selection_ID)[1]','int') AS SelectionId
      ,od.value('Able_To_Use[1]','nchar(1)') AS AbleToUse
      ,od.value('Purchase_ID[1]','nvarchar(10)') AS PurchaseId
      ,od.value('QTY[1]','int') AS Quantity
      ,od.value('(Subdetails/REGION_QTY)[1]','int') AS RegionQty
      ,od.value('(Subdetails/Testing_NO)[1]','nvarchar(10)') AS TestingNo
FROM @xml_data.nodes('/Order_Details/Order_Details') A(od)


问:
Powershell batch of commands response into JSON
I'm trying to capture a list of users and groups on my windows host.
I can capture the user and groups info and assign them to varaibles $users and $groups with the following commands:

```<code>    $groups=$(Get-WmiObject win32_group | Select Name | Sort Name); $users=$(Get-WmiObject -Class Win32_UserAccount | Select Name | Sort Name)
</code>```

What I can't figure out is how to pass these to the ConvertTo-JSON function where they each get their own keys i.e, I'd like the response to look like this:

```<code>{
    "users": ["john", "geroge", "ringo"],
    "groups": ["drums", "guitar"]
}
</code>```

I have tried a few variations of this, but can't quite get the correct syntax for powershell and the ConvertTo-JSON function.

```<code>    $jsonBlob=$(\"groups\" : $(groups), \"users"\ : $(users); ConvertTo-Json $jsonBlob;
</code>```

Any suggestions on how to achieve this?

答:
I would recommend using DirectorySearcher to look up users and groups. It will be more efficient and focused on just the name.

```<code>$usearcher = [adsisearcher]'(&(objectCategory=User)(objectclass=person))'
$gsearcher = [adsisearcher]'(objectCategory=group)'

$usearcher.PropertiesToLoad.Add("name")
$gsearcher.PropertiesToLoad.Add("name")

$usearcher.SizeLimit = 1000
$gsearcher.SizeLimit = 1000

$obj = [pscustomobject]@{
           users  = $usearcher.FindAll() | % { $_.properties['name'][0] }
           groups = $gsearcher.FindAll() | % { $_.properties['name'][0] }
           }

$json = $obj | ConvertTo-Json
</code>```

This will run on the local domain of the account you are using to run this.

Body:
I'm trying to capture a list of users and groups on my windows host.
I can capture the user and groups info and assign them to varaibles $users and $groups with the following commands:

    $groups=$(Get-WmiObject win32_group | Select Name | Sort Name); $users=$(Get-WmiObject -Class Win32_UserAccount | Select Name | Sort Name)

What I can't figure out is how to pass these to the ConvertTo-JSON function where they each get their own keys i.e, I'd like the response to look like this:

{
    "users": ["john", "geroge", "ringo"],
    "groups": ["drums", "guitar"]
}

I have tried a few variations of this, but can't quite get the correct syntax for powershell and the ConvertTo-JSON function.

    $jsonBlob=$(\"groups\" : $(groups), \"users"\ : $(users); ConvertTo-Json $jsonBlob;

Any suggestions on how to achieve this?

Body:
I would recommend using DirectorySearcher to look up users and groups. It will be more efficient and focused on just the name.

$usearcher = [adsisearcher]'(&(objectCategory=User)(objectclass=person))'
$gsearcher = [adsisearcher]'(objectCategory=group)'

$usearcher.PropertiesToLoad.Add("name")
$gsearcher.PropertiesToLoad.Add("name")

$usearcher.SizeLimit = 1000
$gsearcher.SizeLimit = 1000

$obj = [pscustomobject]@{
           users  = $usearcher.FindAll() | % { $_.properties['name'][0] }
           groups = $gsearcher.FindAll() | % { $_.properties['name'][0] }
           }

$json = $obj | ConvertTo-Json

This will run on the local domain of the account you are using to run this.


问:
Spring batch with jdbc for audit data
Hi i have an requirement to update spring batch with jdbc

My requirement is

I have to audit the database table having emp details like name,age,project etc..
for ex the first row is having emp details like

```<code>name age project address phno.
sus  45   java    xyz     456
</code>```

When i audit the phone number and save it in the same database table the table must be like

```<code>sus 45   java  xyz  456
sus null null  null 435
</code>```

So the logic is like only key column and changed value will be reflected in the next row and other not changed column must be null

I have to do it with spring batch program with jdbc connectivity..

Please help me out to find out the logic and coding idea..

答:
Yes, I think you can. See how to create an after-update trigger:

using Oracle

using MySql

Title: Spring batch with jdbc for audit data

Body:
Hi i have an requirement to update spring batch with jdbc

My requirement is

I have to audit the database table having emp details like name,age,project etc..
for ex the first row is having emp details like

name age project address phno.
sus  45   java    xyz     456

When i audit the phone number and save it in the same database table the table must be like

sus 45   java  xyz  456
sus null null  null 435

So the logic is like only key column and changed value will be reflected in the next row and other not changed column must be null

I have to do it with spring batch program with jdbc connectivity..

Please help me out to find out the logic and coding idea..


问:
How to set postion to the tick if you use scaleLinear
Using d3 in react having 0 in domain, it centers "zero" tick.

While useing in HTML  there's no such "problem", how to reach the same result in react?

Code example:

```<code>var width = 400, height = 400;
var data = [10, 15, 20, 25, 30];

var svg = d3.select("body")
    .append("svg")
    .attr("width", width)
    .attr("height", height);

var yscale = d3.scaleLinear()
     // if value is 0, the tick is centered, if there is a range, it draws the ticks first tick is on the needed position
        .domain([0, value])
        .range([height/2, 0]);

var y_axis = d3.axisLeft()
        .scale(yscale);

    svg.append("g")
       .attr("transform", "translate(50, 10)")
       .call(y_axis);
</code>```

答:
Yes, it is the desired behavior and i would say that the d3 is working perfectly.

if data in value is 0, the we are mapping [0,0] for entire y axis and d3 rendering it in middle of axis.

var yscale = d3.scaleLinear()
     // if value is 0, the tick is centered, if there is a range, it draws the ticks first tick is on the needed position
        .domain([0, value])
        .range([height/2, 0]);```
</div>
</div>
</p>

<p>In order to fix this issue, we need to make our code more logical. We can check for maximum entry for "value" and respond according. Just set a minimum value if the value is less than that value.For eg: i am using 5. In this way your chart would look a lot better.</p>

<p>Please use below code and let me know if it resolves your issue.</p>

<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>value = value <= 5 ? 5: value;

var yscale = d3.scaleLinear()
  // if value is 0, the tick is centered, if there is a range, it draws the ticks first tick is on the needed position
  .domain([0, value])
  .range([height / 2, 0]);</code>```

Body:
Using d3 in react having 0 in domain, it centers "zero" tick.

While useing in HTML  there's no such "problem", how to reach the same result in react?

Code example:

var width = 400, height = 400;
var data = [10, 15, 20, 25, 30];

var svg = d3.select("body")
    .append("svg")
    .attr("width", width)
    .attr("height", height);

var yscale = d3.scaleLinear()
     // if value is 0, the tick is centered, if there is a range, it draws the ticks first tick is on the needed position
        .domain([0, value])
        .range([height/2, 0]);

var y_axis = d3.axisLeft()
        .scale(yscale);

    svg.append("g")
       .attr("transform", "translate(50, 10)")
       .call(y_axis);

Body:
Yes, it is the desired behavior and i would say that the d3 is working perfectly.

if data in value is 0, the we are mapping [0,0] for entire y axis and d3 rendering it in middle of axis.

var yscale = d3.scaleLinear()
     // if value is 0, the tick is centered, if there is a range, it draws the ticks first tick is on the needed position
        .domain([0, value])
        .range([height/2, 0]);

In order to fix this issue, we need to make our code more logical. We can check for maximum entry for "value" and respond according. Just set a minimum value if the value is less than that value.For eg: i am using 5. In this way your chart would look a lot better.

Please use below code and let me know if it resolves your issue.

value = value <= 5 ? 5: value;

var yscale = d3.scaleLinear()
  // if value is 0, the tick is centered, if there is a range, it draws the ticks first tick is on the needed position
  .domain([0, value])
  .range([height / 2, 0]);


问:
In Powershell: Remove lines from a text file if it contains a set words stored in another text file
I know:

```<code>Get-Content C:\new\temp_*.txt | Select-String -pattern "H|159" -notmatch | Out-File C:\new\newfile.txt
</code>```

But i need to fetch -pattern from another text file as the patterns are 300k so cannot be piped.

What is the modified command?

答:
$pattern = Get-Content fileWithRegexPattern.txt; Get-Content text.txt |Select-String -Pattern $pattern

and pipe the output.

Body:
I know:

Get-Content C:\new\temp_*.txt | Select-String -pattern "H|159" -notmatch | Out-File C:\new\newfile.txt

But i need to fetch -pattern from another text file as the patterns are 300k so cannot be piped.

What is the modified command?


问:
Renaming project name shown in JetBrains Toolbox
I've recently made a new Empty Project in IntelliJ IDEA and added a couple Gradle based modules to it. The project and the modules are under W:\IJ Workspace\ProjectName directory - the project itself is in W:\IJ Workspace\ProjectName\ProjectName folder, and the modules are in W:\IJ Workspace\ProjectName\ModuleName folders.

JetBrains Toolbox shows the project and its correct directory (W:\IJ Workspace\ProjectName\ProjectName) but the name it displays - is the name of first module I created in the project, not ProjectName. Is there any way to change the name Toolbox is displaying for that project? Or is there a way to manually add a project to Toolbox, forcing it to use its actual name?

答:
Do this while IDE is closed (at very least while that project is closed).

Locate a folder with project settings (.idea subfolder, usually that would be PROJECT_ROOT/.idea).

See if you have .name file there. If not -- create new one.

Open that .name file in any text editor and write desired project name there -- it's a plain text file with a single line of text (no new lines).

Save the file and launch IDE.

Next time you open that project is should use the name from that .name file.

P.S. This works in PhpStorm (where IDE also has a special "Rename Project" action) but should work in IntelliJ IDEA (and other IDEA-based IDEs) as well.


问:
Swagger documentation tools for a Rails API application
I googled a little bit to find a proper and easy to implement way to generate Swagger documentation for an existing Rails API app. To be short, there are 2 ways of implementation: either via controllers, models or via Rspec controller/request specs. The list is not too long and the choice is not so easy to make:

swagger-docs gem, - the oldest one. Pros: implementation is to be
done in  controllers. Cons: does not support Swagger V2 version
and limited to 1.2 only.

swagger-blocks gem, - improved version of swagger-docs, supports Swagger V2 version, implementation is to be done in controllers, models. But I couldn't make it work, Swagger Editor could not parse the generated json file.

rswag gem:  extends rspec-rails "request specs" with a Swagger-based DSL. Personally, I found it really difficult to implement in an existing Rails app for 2 reasons:

you will have to modify existing request specs

request specs look really weird and the syntax is not RSpec-ish.

rspec-rails-swagger gem: implementation via request specs. The same cons as above.

Does anybody know other gems to generate Swagger documentation for an existing Rails API app ? Any suggestions are welcome ! Thank you.

答:
Our working solution is to use:

swagger-blocks gem to generate the Swagger JSON

Swagger UI Console Chrome
Extension to provide the Swagger UI


问:
Unexpected behavior using transform column and transform table, SymmetricDS
I have the followings transformation columns

insert into SYM_TRANSFORM_COLUMN (
        transform_id, include_on, target_column_name, source_column_name, pk,
        transform_type, transform_expression, transform_order, last_update_time,
        create_time
) values (
        'send_source_node_id', '*', 'node_id', 'employee_id', 1,
        'bsh', 'String node = targetNode.getNodeId(); String value = currentValue; return value + "-" + sourceNodeId;', 1, current_timestamp, current_timestamp
);

insert into SYM_TRANSFORM_COLUMN (
        transform_id, include_on, target_column_name, source_column_name, pk,
        transform_type, transform_expression, transform_order, last_update_time,
        create_time
) values (
        'copy_employee_id', '*', 'employee_id', 'employee_id', 0,
        'copy', '', 10, current_timestamp, current_timestamp
);

insert into SYM_TRANSFORM_COLUMN (
        transform_id, include_on, target_column_name, source_column_name, pk,
        transform_type, transform_expression, transform_order, last_update_time,
        create_time
) values (
        'copy_employee_name', '*', 'name', 'name', 0,
        'copy', '', 10, current_timestamp, current_timestamp
);
```

<p>With its transform tables</p>

<pre class="lang-sql prettyprint-override"><code>insert into SYM_TRANSFORM_TABLE (
        transform_id, source_node_group_id, target_node_group_id, transform_point, source_table_name,
        target_table_name, update_action, delete_action, transform_order, column_policy, update_first,
        last_update_time, create_time
) values (
        'copy_employee_id', 'school', 'main-school', 'EXTRACT', 'employees',
        'employees', 'UPDATE_COL', 'DEL_ROW', 1, 'IMPLIED', 0,
         current_timestamp, current_timestamp
);

insert into SYM_TRANSFORM_TABLE (
        transform_id, source_node_group_id, target_node_group_id, transform_point, source_table_name,
        target_table_name, update_action, delete_action, transform_order, column_policy, update_first,
        last_update_time, create_time
) values (
        'copy_employee_name', 'school', 'main-school', 'EXTRACT', 'employees',
        'employees', 'UPDATE_COL', 'DEL_ROW', 1, 'IMPLIED', 0,
         current_timestamp, current_timestamp
);

insert into SYM_TRANSFORM_TABLE (
        transform_id, source_node_group_id, target_node_group_id, transform_point, source_table_name,
        target_table_name, update_action, delete_action, transform_order, column_policy, update_first,
        last_update_time, create_time
) values (
        'send_source_node_id', 'school', 'main-school', 'EXTRACT', 'employees',
        'employees', 'UPDATE_COL', 'DEL_ROW', 1, 'IMPLIED', 0,
         current_timestamp, current_timestamp
);
</code>```

Structure of my source table

create table  employees (
    employee_id serial,
    name varchar(50),
    CONSTRAINT departments_pk PRIMARY KEY (employee_id)
);
```

<p>Structure of my target table</p>

<pre class="lang-sql prettyprint-override"><code>create table  employees (
    master_employee_id uuid default uuid_generate_v1(),
    employee_id integer,
    name varchar(50),
    node_id varchar(50),
    CONSTRAINT employees_pk PRIMARY KEY (master_employee_id)
);
</code>```

The synchronization works fine with other tables that are identical, but these tables do not work fine, because when a new employee is added in the source table two records will be added to the target table.
I not idea about this behavior,  can someone explain to me?

Example of the result in the target table

答:
Each entry in sym_transform_table represents a table mapping that will process row changes for the source table.  Since you have 3 table mappings for the same source table, each row change on that table will result in 3 transformed rows.

I think you wanted to use 1 table mapping in sym_transform_table, like this:

```<code>insert into SYM_TRANSFORM_TABLE (
    transform_id, source_node_group_id, target_node_group_id, transform_point, source_table_name,
    target_table_name, update_action, delete_action, transform_order, column_policy, update_first,
    last_update_time, create_time
) values (
    'employees_to_employees', 'school', 'main-school', 'EXTRACT', 'employees',
    'employees', 'UPDATE_COL', 'DEL_ROW', 1, 'IMPLIED', 0,
     current_timestamp, current_timestamp
);
</code>```

Then change your entries in sym_transform_column to reference it by using the same "employees_to_employees" transform ID.

Body:
I have the followings transformation columns

insert into SYM_TRANSFORM_COLUMN (
        transform_id, include_on, target_column_name, source_column_name, pk,
        transform_type, transform_expression, transform_order, last_update_time,
        create_time
) values (
        'send_source_node_id', '*', 'node_id', 'employee_id', 1,
        'bsh', 'String node = targetNode.getNodeId(); String value = currentValue; return value + "-" + sourceNodeId;', 1, current_timestamp, current_timestamp
);

insert into SYM_TRANSFORM_COLUMN (
        transform_id, include_on, target_column_name, source_column_name, pk,
        transform_type, transform_expression, transform_order, last_update_time,
        create_time
) values (
        'copy_employee_id', '*', 'employee_id', 'employee_id', 0,
        'copy', '', 10, current_timestamp, current_timestamp
);

insert into SYM_TRANSFORM_COLUMN (
        transform_id, include_on, target_column_name, source_column_name, pk,
        transform_type, transform_expression, transform_order, last_update_time,
        create_time
) values (
        'copy_employee_name', '*', 'name', 'name', 0,
        'copy', '', 10, current_timestamp, current_timestamp
);

With its transform tables

insert into SYM_TRANSFORM_TABLE (
        transform_id, source_node_group_id, target_node_group_id, transform_point, source_table_name,
        target_table_name, update_action, delete_action, transform_order, column_policy, update_first,
        last_update_time, create_time
) values (
        'copy_employee_id', 'school', 'main-school', 'EXTRACT', 'employees',
        'employees', 'UPDATE_COL', 'DEL_ROW', 1, 'IMPLIED', 0,
         current_timestamp, current_timestamp
);

insert into SYM_TRANSFORM_TABLE (
        transform_id, source_node_group_id, target_node_group_id, transform_point, source_table_name,
        target_table_name, update_action, delete_action, transform_order, column_policy, update_first,
        last_update_time, create_time
) values (
        'copy_employee_name', 'school', 'main-school', 'EXTRACT', 'employees',
        'employees', 'UPDATE_COL', 'DEL_ROW', 1, 'IMPLIED', 0,
         current_timestamp, current_timestamp
);

insert into SYM_TRANSFORM_TABLE (
        transform_id, source_node_group_id, target_node_group_id, transform_point, source_table_name,
        target_table_name, update_action, delete_action, transform_order, column_policy, update_first,
        last_update_time, create_time
) values (
        'send_source_node_id', 'school', 'main-school', 'EXTRACT', 'employees',
        'employees', 'UPDATE_COL', 'DEL_ROW', 1, 'IMPLIED', 0,
         current_timestamp, current_timestamp
);

Structure of my source table

create table  employees (
    employee_id serial,
    name varchar(50),
    CONSTRAINT departments_pk PRIMARY KEY (employee_id)
);

Structure of my target table

create table  employees (
    master_employee_id uuid default uuid_generate_v1(),
    employee_id integer,
    name varchar(50),
    node_id varchar(50),
    CONSTRAINT employees_pk PRIMARY KEY (master_employee_id)
);

The synchronization works fine with other tables that are identical, but these tables do not work fine, because when a new employee is added in the source table two records will be added to the target table.
I not idea about this behavior,  can someone explain to me?

Example of the result in the target table

Body:
Each entry in sym_transform_table represents a table mapping that will process row changes for the source table.  Since you have 3 table mappings for the same source table, each row change on that table will result in 3 transformed rows.

I think you wanted to use 1 table mapping in sym_transform_table, like this:

insert into SYM_TRANSFORM_TABLE (
    transform_id, source_node_group_id, target_node_group_id, transform_point, source_table_name,
    target_table_name, update_action, delete_action, transform_order, column_policy, update_first,
    last_update_time, create_time
) values (
    'employees_to_employees', 'school', 'main-school', 'EXTRACT', 'employees',
    'employees', 'UPDATE_COL', 'DEL_ROW', 1, 'IMPLIED', 0,
     current_timestamp, current_timestamp
);

Then change your entries in sym_transform_column to reference it by using the same "employees_to_employees" transform ID.


问:
Assign value if another value is contained in a list (power bi, dax)
I imported a table into Power BI that looks as follows:

```<code>  id  value
  01    123
  02    456
  03    789
  04    999
</code>```

I want to declare a new column called KIND using an IF statement. Something along the lines of:

KIND = if(id is in ("01", "02", "22", "89"), "baker", "other").

The desired result looks as follows:

```<code>  id  value   KIND
  01    123  baker
  02    456  baker
  03    789  other
  04    999  other
</code>```

答:
Just so there's an answer not just in the comments:

```<code>KIND := IF ( TableName[id] IN {"01", "02", "22", "89"}, "baker", "other" )
</code>```

Note that the IN function won't work in some older versions of Excel and you'll have to use CONTAINSROW instead.

```<code>KIND := IF ( CONTAINSROW ( {"01", "02", "22", "89"}, TableName[id] ), "baker", "other" )
</code>```

Body:
I imported a table into Power BI that looks as follows:

  id  value
  01    123
  02    456
  03    789
  04    999

I want to declare a new column called KIND using an IF statement. Something along the lines of:

KIND = if(id is in ("01", "02", "22", "89"), "baker", "other").

The desired result looks as follows:

  id  value   KIND
  01    123  baker
  02    456  baker
  03    789  other
  04    999  other

Body:
Just so there's an answer not just in the comments:

KIND := IF ( TableName[id] IN {"01", "02", "22", "89"}, "baker", "other" )

Note that the IN function won't work in some older versions of Excel and you'll have to use CONTAINSROW instead.

KIND := IF ( CONTAINSROW ( {"01", "02", "22", "89"}, TableName[id] ), "baker", "other" )


问:
Auto create directories after uploading with PHP
I'm creating a php site where a company will upload a lot of images. I'd like one folder to contain upto 500-1000 files and PHP automatically creates a new one if previous contains more that 1000 files.

For example, px300 has folder dir1 which stores 500 files, then a new one dir2 will be created.

Are there any existed a solutions?

答:
This task is simple enough not to require an existing solution.  You can make use of scandir to count the number of files in a directory, and then mkdir to make a directory.

```<code>// Make sure we don't count . and .. as proper directories
if (count(scandir("dir")) - 2 > 1000) {
    mkdir("newdir");
}
</code>```

Body:
This task is simple enough not to require an existing solution.  You can make use of scandir to count the number of files in a directory, and then mkdir to make a directory.

// Make sure we don't count . and .. as proper directories
if (count(scandir("dir")) - 2 > 1000) {
    mkdir("newdir");
}


问:
Unable to export multiple cloud functions
I am using the organization structure described here. I have the following functions/ folder:

My index.js file is as follows:

```<code>const glob = require('glob')
const camelCase = require('camelcase')
const FUNCTIONS_FOLDER = './src'

const files = glob.sync('./src/**/*.func.js', {
    cwd: __dirname,
    ignore: './node_modules/**'
})

console.log('FILE LENGTH: ', files.length)

for (let f = 0, fl = files.length; f < fl; f++) {
    const file = files[f]
    console.log('FILE: ', file)

    const functionName = camelCase(
        file
            .slice(5, -8)
            .split('/')
            .join('_')
    ) // Strip off '.func.js' and 'src/'
    console.log('FUNCTION - PRE: ', functionName)
    console.log('ENV ', process.env.FUNCTION_NAME)
    if (
        !process.env.FUNCTION_NAME ||
        process.env.FUNCTION_NAME === functionName
    ) {
        console.log('FUNCTION: ', functionName, file)
        exports[functionName] = require(file)
    }
}
</code>```

and I am trying to deploy the two cloud functions defined in the functions/src/votes directory, however, when I run firebase deploy --only functions, only my onRequest.func.js function is being deployed. I looked at the firebase functions:log and I got the following:

Even when I remove the check

```<code>if (!process.env.FUNCTION_NAME || process.env.FUNCTION_NAME === functionName)
</code>```

my onWrite.func.js still is not deployed.

Am I doing something wrong? I would greatly appreciate any help!

Edit: Here is my entire functions/ directory:
  https://github.com/markoelez/temp_functions

答:
There is no problem in the code you've posted in the question. The issue is in the *.func.js files. This is the culprit:

try {
    admin.initializeApp(functions.config().firebase)
} catch (err) {
    return err // looks like you should remove this line
}
```

When you require the second file admin.initializeApp() fails with

Error: The default Firebase app already exists. This means you called initializeApp() more than once without providing an app name as the second argument. In most cases you only need to call initializeApp() once. But if you do want to initialize multiple apps, pass a second argument to initializeApp() to give each app a unique name.

Then you exit the second module without assigning to exports.

If you remove return err you will have 2 exported functions in index.js:exports.

Don't know about the rest of the code, but that should resolve the issue in question.

Body:
I am using the organization structure described here. I have the following functions/ folder:

My index.js file is as follows:

const glob = require('glob')
const camelCase = require('camelcase')
const FUNCTIONS_FOLDER = './src'

const files = glob.sync('./src/**/*.func.js', {
    cwd: __dirname,
    ignore: './node_modules/**'
})

console.log('FILE LENGTH: ', files.length)

for (let f = 0, fl = files.length; f < fl; f++) {
    const file = files[f]
    console.log('FILE: ', file)

    const functionName = camelCase(
        file
            .slice(5, -8)
            .split('/')
            .join('_')
    ) // Strip off '.func.js' and 'src/'
    console.log('FUNCTION - PRE: ', functionName)
    console.log('ENV ', process.env.FUNCTION_NAME)
    if (
        !process.env.FUNCTION_NAME ||
        process.env.FUNCTION_NAME === functionName
    ) {
        console.log('FUNCTION: ', functionName, file)
        exports[functionName] = require(file)
    }
}

and I am trying to deploy the two cloud functions defined in the functions/src/votes directory, however, when I run firebase deploy --only functions, only my onRequest.func.js function is being deployed. I looked at the firebase functions:log and I got the following:

Even when I remove the check

if (!process.env.FUNCTION_NAME || process.env.FUNCTION_NAME === functionName)

my onWrite.func.js still is not deployed.

Am I doing something wrong? I would greatly appreciate any help!

Edit: Here is my entire functions/ directory:
  https://github.com/markoelez/temp_functions

Body:
There is no problem in the code you've posted in the question. The issue is in the *.func.js files. This is the culprit:

try {
    admin.initializeApp(functions.config().firebase)
} catch (err) {
    return err // looks like you should remove this line
}

When you require the second file admin.initializeApp() fails with

Error: The default Firebase app already exists. This means you called initializeApp() more than once without providing an app name as the second argument. In most cases you only need to call initializeApp() once. But if you do want to initialize multiple apps, pass a second argument to initializeApp() to give each app a unique name.

Then you exit the second module without assigning to exports.

If you remove return err you will have 2 exported functions in index.js:exports.

Don't know about the rest of the code, but that should resolve the issue in question.


问:
when i build the docker with pip install psycopg2 has error
```<code>the error:

Skipping optional fixer: ws_comma
running build_ext
building 'psycopg2._psycopg' extension
creating build/temp.linux-x86_64-3.8
creating build/temp.linux-x86_64-3.8/psycopg
gcc -pthread -Wno-unused-result -Wsign-compare -DNDEBUG -g -fwrapv -O3 -Wall -fPIC -DPSYCOPG_DEFAULT_PYDATETIME=1 -DPSYCOPG_VERSION="2.7.3.1 (dt dec pq3 ext lo64)" -DPG_VERSION_NUM=110500 -DHAVE_LO64=1 -I/usr/local/include/python3.8 -I. -I/usr/include/postgresql -I/usr/include/postgresql/11/server -c psycopg/psycopgmodule.c -o build/temp.linux-x86_64-3.8/psycopg/psycopgmodule.o -Wdeclaration-after-statement
psycopg/psycopgmodule.c: In function ‘psyco_is_main_interp’:
psycopg/psycopgmodule.c:685:18: error: dereferencing pointer to incomplete type ‘PyInterpreterState’ {aka ‘struct _is’}
     while (interp->next)
                  ^~
error: command 'gcc' failed with exit status 1
</code>```

When I build the dockerc-compose to pip install psycopg2 and has the issue.

The Dockerfile:

```<code>RUN sed -i "s@http://deb.debian.org@http://mirrors.aliyun.com@g" /etc/apt/sources.list
RUN cat /etc/apt/sources.list
RUN apt-get clean  && apt-get update

RUN apt-get install -y python3-dev \
    && apt-get install -y libevent-dev \
    && pip install --default-timeout=1000 --no-cache-dir -r requirements.txt
</code>```

答:
You are trying to build psycopg2 version 2.7.3.1: that version is not compatible with Python 3.8.

You must use psycopg2 version at least 2.8.4.

https://www.psycopg.org/docs/news.html#what-s-new-in-psycopg-2-8-4

Body:
the error:

Skipping optional fixer: ws_comma
running build_ext
building 'psycopg2._psycopg' extension
creating build/temp.linux-x86_64-3.8
creating build/temp.linux-x86_64-3.8/psycopg
gcc -pthread -Wno-unused-result -Wsign-compare -DNDEBUG -g -fwrapv -O3 -Wall -fPIC -DPSYCOPG_DEFAULT_PYDATETIME=1 -DPSYCOPG_VERSION="2.7.3.1 (dt dec pq3 ext lo64)" -DPG_VERSION_NUM=110500 -DHAVE_LO64=1 -I/usr/local/include/python3.8 -I. -I/usr/include/postgresql -I/usr/include/postgresql/11/server -c psycopg/psycopgmodule.c -o build/temp.linux-x86_64-3.8/psycopg/psycopgmodule.o -Wdeclaration-after-statement
psycopg/psycopgmodule.c: In function ‘psyco_is_main_interp’:
psycopg/psycopgmodule.c:685:18: error: dereferencing pointer to incomplete type ‘PyInterpreterState’ {aka ‘struct _is’}
     while (interp->next)
                  ^~
error: command 'gcc' failed with exit status 1

When I build the dockerc-compose to pip install psycopg2 and has the issue.

The Dockerfile:

RUN sed -i "s@http://deb.debian.org@http://mirrors.aliyun.com@g" /etc/apt/sources.list
RUN cat /etc/apt/sources.list
RUN apt-get clean  && apt-get update

RUN apt-get install -y python3-dev \
    && apt-get install -y libevent-dev \
    && pip install --default-timeout=1000 --no-cache-dir -r requirements.txt


问:
Incorrect output from inner_join of dplyr package
I have two datasets, named "results" and "support2", available here.

I want to merge the two datasets by the only common column name "SNP". Code below:

```<code>> library(dplyr)
> results <- read_delim("<path>\\results", delim = "\t", col_name = T)
> support2 <- read_delim("<path>\\support2", delim = "\t", col_name = T)

> head(results)
# A tibble: 6 x 2
  SNP        p.value
  <chr>        <dbl>
1 rs28436661   0.334
2 rs9922067    0.322
3 rs2562132    0.848
4 rs3930588    0.332
5 rs2562137    0.323
6 rs3848343    0.363

 > head(support2)
# A tibble: 6 x 2
  SNP         position
  <chr>          <dbl>
1 rs62028702     60054
2 rs190434815    60085
3 rs62028703     60087
4 rs62028704     60095
5 rs181534180    60164
6 rs186233776    60177

> dim(results)
[1] 188242      2
> dim(support2)
[1] 1210619       2

# determine the number of common SNPs
length(Reduce(intersect, list(results$SNP, support2$SNP)))
[1] 187613

I would expect that after inner_join, the new data would have 187613 rows.

> newdata <- inner_join(results, support2)
Joining, by = "SNP"
> dim(newdata)
[1] 1409812       3
</code>```

Strangely, instead of have 187613 rows, the new data have 1409812 rows, which is even larger than the sum of the number of rows of the two dataframes.

I switched to the merge function as below:

```<code>> newdata2 <- merge(results, support2)
> dim(newdata2)
[1] 1409812       3
</code>```

This second new dataframe has the same issue. No idea why.

I wish to know how should I obtain a new dataframe whose rows represent the common rows of the two dataframes (should have 187613 rows) and whose columns contain columns of both dataframes.

答:
It could be a result of duplicate elements

```<code>results <- data.frame(col1 = rep(letters[1:3], each = 3), col2 = rnorm(9))
support2 <- data.frame(col1 = rep(letters[1:5],each = 2), newcol = runif(10))

library(dplyr)
out <- inner_join(results, support2)
nrow(out)
#[1] 18
</code>```

Here, the initial datasets in the common column ('col1') are duplicated which confuses  the join statement as to which row it should take as a match resulting in a situation similar to a cross join but not exactly that

Body:
I have two datasets, named "results" and "support2", available here.

I want to merge the two datasets by the only common column name "SNP". Code below:

> library(dplyr)
> results <- read_delim("<path>\\results", delim = "\t", col_name = T)
> support2 <- read_delim("<path>\\support2", delim = "\t", col_name = T)

> head(results)
# A tibble: 6 x 2
  SNP        p.value
  <chr>        <dbl>
1 rs28436661   0.334
2 rs9922067    0.322
3 rs2562132    0.848
4 rs3930588    0.332
5 rs2562137    0.323
6 rs3848343    0.363

 > head(support2)
# A tibble: 6 x 2
  SNP         position
  <chr>          <dbl>
1 rs62028702     60054
2 rs190434815    60085
3 rs62028703     60087
4 rs62028704     60095
5 rs181534180    60164
6 rs186233776    60177

> dim(results)
[1] 188242      2
> dim(support2)
[1] 1210619       2

# determine the number of common SNPs
length(Reduce(intersect, list(results$SNP, support2$SNP)))
[1] 187613

I would expect that after inner_join, the new data would have 187613 rows.

> newdata <- inner_join(results, support2)
Joining, by = "SNP"
> dim(newdata)
[1] 1409812       3

Strangely, instead of have 187613 rows, the new data have 1409812 rows, which is even larger than the sum of the number of rows of the two dataframes.

I switched to the merge function as below:

> newdata2 <- merge(results, support2)
> dim(newdata2)
[1] 1409812       3

This second new dataframe has the same issue. No idea why.

I wish to know how should I obtain a new dataframe whose rows represent the common rows of the two dataframes (should have 187613 rows) and whose columns contain columns of both dataframes.

Body:
It could be a result of duplicate elements

results <- data.frame(col1 = rep(letters[1:3], each = 3), col2 = rnorm(9))
support2 <- data.frame(col1 = rep(letters[1:5],each = 2), newcol = runif(10))

library(dplyr)
out <- inner_join(results, support2)
nrow(out)
#[1] 18

Here, the initial datasets in the common column ('col1') are duplicated which confuses  the join statement as to which row it should take as a match resulting in a situation similar to a cross join but not exactly that


问:
From array and array of objects extract property of objects as an array
I have an array:
var a = ['h1', 'h2', 'h3']

and array of objects:
var b = [{name: 'h1', id: 3}, {name: 'h2', id: 4}, {name: 'h3', id: 5}]

How do I find common part and extract id's only as a new array:

[3, 4, 5]

with pure javascript?

答:
This should output the values to c.</p>

```<code>let c = [];
b.forEach(obj => {
   const i = a.indexOf(obj.name);
    c[i] = obj.id;
})
</code>```

Body:
This should output the values to c.

let c = [];
b.forEach(obj => {
   const i = a.indexOf(obj.name);
    c[i] = obj.id;
})


问:
Are string arrays immutable in C#?
I am a little confused. I know a string is immutable, but how about a string array?

Whenever I add something to an empty array, does it create a new instance of that array?

How about when I change something in it?

```<code>string[] array = new string[5];

array[0] = "my favourite string"; //does it create a new instance of the array here?
array[0] = "changed that"; //how about now?
</code>```

答:
Here is the IL for your code ..

```<code>IL_0000:  nop
IL_0001:  ldc.i4.5
IL_0002:  newarr      System.String
IL_0007:  stloc.0     // array
IL_0008:  ldloc.0     // array
IL_0009:  ldc.i4.0
IL_000A:  ldstr       "my favourite string"
IL_000F:  stelem.ref
IL_0010:  ldloc.0     // array
IL_0011:  ldc.i4.0
IL_0012:  ldstr       "changed that"
IL_0017:  stelem.ref
IL_0018:  ret
</code>```

As you can see, the array is instantiated only once.

Title: Are string arrays immutable in C#?

Body:
I am a little confused. I know a string is immutable, but how about a string array?

Whenever I add something to an empty array, does it create a new instance of that array?

How about when I change something in it?

string[] array = new string[5];

array[0] = "my favourite string"; //does it create a new instance of the array here?
array[0] = "changed that"; //how about now?

Body:
Here is the IL for your code ..

IL_0000:  nop
IL_0001:  ldc.i4.5
IL_0002:  newarr      System.String
IL_0007:  stloc.0     // array
IL_0008:  ldloc.0     // array
IL_0009:  ldc.i4.0
IL_000A:  ldstr       "my favourite string"
IL_000F:  stelem.ref
IL_0010:  ldloc.0     // array
IL_0011:  ldc.i4.0
IL_0012:  ldstr       "changed that"
IL_0017:  stelem.ref
IL_0018:  ret

As you can see, the array is instantiated only once.


答:
Here's one approach:

```<code>df.index = pd.to_datetime(df.index)
year_month = df.index.strftime('%Y-%m')
#format the date so its simpler to find where the changes occur
rows_diff = np.flatnonzero(year_month[:-1]!= year_month[1:])+1
#see where the Value1 is 0 in the first row
m = df.iloc[rows_diff, 0] == 0
#set those values to whatever Value2 is
df.loc[m.index, 'Value1'] = df.loc[m.index, 'Value2']
</code>```

```<code>print(df)

              Value1  Value2
2008-01-01      -1       5
2008-01-03      -1       6
2008-02-25       7       7
2008-02-26      -1       8
2008-02-27       0       9
2008-03-02      10      10
2008-03-16      -1      11
2008-03-17      -1      12
2009-04-04      13      13
2009-04-07       0      14
</code>```

Title: How to replace the value of a dataframe column with the value of another column using groupby.first()?

Body:
I have a df like this:

               Value1     Value2
2008-01-01       -1          4
2008-01-01       -1          5
2008-01-03       -1          6
2008-02-25        0          7
2008-02-26       -1          8
2008-02-27        0          9
2008-03-02        5         10
2008-03-16       -1         11
2008-03-17       -1         12
2009-04-04       -1         13
2009-04-07        0         14

I want to check the first value1 of every Year-Month. If it's < 0, I want value2 to replace with value1. How can I do that?

In this example, the result should be:

               Value1     Value2
2008-01-01       -1         -1
2008-01-01       -1          5
2008-01-03       -1          6
2008-02-25        0          7
2008-02-26       -1          8
2008-02-27        0          9
2008-03-02        5         10
2008-03-16       -1         11
2008-03-17       -1         12
2009-04-04       -1         -1
2009-04-07        0         14

Because only 2008-01, 2009-04 first value1 are negative, 2008-2, 2008-03 first value1 are positive, just leave it.

I used:

g = df.groupby([df.index.year,df.index.month])

if g['value1'].first() < 0:
   g['value1'].first() = g['value2'].first()

it doesn't seem to work. Thanks.

Body:
Here's one approach:

df.index = pd.to_datetime(df.index)
year_month = df.index.strftime('%Y-%m')
#format the date so its simpler to find where the changes occur
rows_diff = np.flatnonzero(year_month[:-1]!= year_month[1:])+1
#see where the Value1 is 0 in the first row
m = df.iloc[rows_diff, 0] == 0
#set those values to whatever Value2 is
df.loc[m.index, 'Value1'] = df.loc[m.index, 'Value2']

print(df)

              Value1  Value2
2008-01-01      -1       5
2008-01-03      -1       6
2008-02-25       7       7
2008-02-26      -1       8
2008-02-27       0       9
2008-03-02      10      10
2008-03-16      -1      11
2008-03-17      -1      12
2009-04-04      13      13
2009-04-07       0      14


问:
When should I use Web SQL versus IndexedDB?
Recently, I have come across the Web SQL and IndexedDB APIs that are provided by browsers. What are the use cases for Web SQL and IndexedDB and when should I use one over the other?</p>

答:
Why not Web SQL?

The Web SQL database specification has been deprecated since November 2010. The browser vendors are not encouraged to support this technology and it's important that anyone reading this understands this. You can read more about Web SQL on its Wikipedia page. Now back to the other important segment of your question.

When to use the IndexedDB API?

You can use IndexedDB to store data of any JavaScript type, such as an object or array, without having to serialize it. All requests against the database are asynchronous. The browser's implementation allows you to set callbacks for when successes or errors occur. Modern abstractions over this implementation allow you to use promises instead.

One of the major use cases for IndexedDB is creating an offline database that will be synchronized with the actual database once online. This allows an application to continue to work while offline and persist past reloads. A now-dead famous example of this is Wunderlist, you can add and edit tasks even when offline. These operations go in a synchronization queue which is processed and emptied when the network is available again. This is how a lot of to-do list applications work when offline.