问:
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>```

答: try to use @Mock instead of @MockBean. It should be ok</p>

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)


来源: stackexchange

问:
Display HTML code depending on which group a user is in
I would like to selectively display a block of text on a page depending on which AD-Group a user is in. The page is a simple list of links ATM, no controller necessary. I have the code below which works perfectly when I am developing locally (I am logged onto the AD) - as soon I publish the application to an IIS server I get a 404 error - I have been able to locate the exact line that is causing the error -> in ActiveDirectory.IsInGroup () the line group.Translate is the culprit.

I have checked the Event Viewer on the IIS Server (and the log for IIS) but nothing is being logged at all?

This is the index.html:

```<code>@page
@using System.Security.Principal
@{
    ViewData["Title"] = "Landing Page";
}

@{
   var principal = new WindowsPrincipal(WindowsIdentity.GetCurrent());
   bool itUser = ActiveDirectory.IsInGroup(principal, "IT Department");
}

<h4>Header</h4>

@if (itUser || adminUser)
    {
       <div class="card mb-4 shadow-sm">
          <div class="card-header">
             <h4 class="my-0 font-weight-normal">IT</h4>
          </div>
          <div class="card-body">
             <a target="_blank" href="http://www.test.com/Configuration/Index" class="btn btn-secondary my-2">Application Config</a><br />
          </div>
       </div>
    }
</code>```

here is the C# code:

```<code>public static class ActiveDirectory

       public static bool IsInGroup(ClaimsPrincipal checkUser, string checkGroupName)
    {
        var identity = (WindowsIdentity)checkUser.Identity;
        if (identity?.Groups == null) return false;

        foreach (var group in identity.Groups)
        {
            var groupName = group.Translate(typeof(NTAccount)).ToString(); // this gives me a 404 error
            if (groupName.ToLower().Contains(checkGroupName.ToLower())) return true;
        }

        return false;
    }
}
</code>```

答:
Not utilizing a controller is bad practice (and defeats the purpose of utilizing MVC Framework (Model View Controller)), especially with concern to establishing auditability and authentication/authorization checks.

Best practice would be to have your default ActionResult (which is set in your RouteConfig file) on your controller call a function that you define to get a list of which groups your end user is a part of

Example:

Pass in the following in each controller ActionResult:

```<code>// what will be needed:
using System.DirectoryServices;
using System.DirectoryServices.ActiveDirectory;

var userSignOn = System.Web.HttpContext.Current.Request.LogonUserIdentity.Name;

List<string> activedirectoryGroupList = new List<string>();

activedirectoryGroupList = GetGroupsFromSignOn(userSignOn);
</code>```

The function being called:

```<code>internal static List<string> GetGroupsFromSignOn(string signOn)
{
    string searchText = "(&(objectCategory=person)(objectClass=user)(sAMAccountName={0}))";
    searchText = searchText.Replace("{0}", signOn);

    Domain domain = Domain.GetCurrentDomain();
    DirectoryEntry userEntry = domain.GetDirectoryEntry();

    DirectorySearcher searcher = new DirectorySearcher(userEntry, searchText);
    SearchResult result = searcher.FindOne();

    DirectoryEntry currentUserEntry = result.GetDirectoryEntry();

    List<string> activedirectoryGroupList = new List<string>();

    if (currentUserEntry != null)
    {
        int propertyCount = currentUserEntry.Properties["memberOf"].Count;

        string activedirectoryGroup;

        for (int i = 0; i < propertyCount; i++)
        {
            activedirectoryGroup = Convert.ToString(currentUserEntry.Properties["memberOf"][i]);

            int startIndex = activedirectoryGroup.IndexOf('=');
            startIndex += 1;

            int endIndex = activedirectoryGroup.IndexOf(',');

            int stringLength = endIndex - startIndex;

            activedirectoryGroup = activedirectoryGroup.Substring(startIndex, stringLength);

            activedirectoryGroupList.Add(activedirectoryGroup);
        }

        return activedirectoryGroupList;
    }
    else
    {
        return null;
    }
}
</code>```

From there, you would have a list of the AD Groups your user would be a part of, and you can either cross reference these groups with your authorized group name(s) that you can set either in your web config file, or in a SQL database that you can call out to.

As for determining what would be displayed, you should likely set up a master view, with partial views rendered on that page depending upon your user's authorization status for that information.

Edit:

Useful thread about the challenges of authentication with asp.net MVC

ContentLicense: CC BY-SA 4.0

Body:
I would like to selectively display a block of text on a page depending on which AD-Group a user is in. The page is a simple list of links ATM, no controller necessary. I have the code below which works perfectly when I am developing locally (I am logged onto the AD) - as soon I publish the application to an IIS server I get a 404 error - I have been able to locate the exact line that is causing the error -> in ActiveDirectory.IsInGroup () the line group.Translate is the culprit.

I have checked the Event Viewer on the IIS Server (and the log for IIS) but nothing is being logged at all?

This is the index.html:

@page
@using System.Security.Principal
@{
    ViewData["Title"] = "Landing Page";
}

@{
   var principal = new WindowsPrincipal(WindowsIdentity.GetCurrent());
   bool itUser = ActiveDirectory.IsInGroup(principal, "IT Department");
}

Header

@if (itUser || adminUser)
    {

IT

             Application Config

    }

here is the C# code:

public static class ActiveDirectory

       public static bool IsInGroup(ClaimsPrincipal checkUser, string checkGroupName)
    {
        var identity = (WindowsIdentity)checkUser.Identity;
        if (identity?.Groups == null) return false;

        foreach (var group in identity.Groups)
        {
            var groupName = group.Translate(typeof(NTAccount)).ToString(); // this gives me a 404 error
            if (groupName.ToLower().Contains(checkGroupName.ToLower())) return true;
        }

        return false;
    }
}

Body:
Not utilizing a controller is bad practice (and defeats the purpose of utilizing MVC Framework (Model View Controller)), especially with concern to establishing auditability and authentication/authorization checks.

Best practice would be to have your default ActionResult (which is set in your RouteConfig file) on your controller call a function that you define to get a list of which groups your end user is a part of

Example:

Pass in the following in each controller ActionResult:

// what will be needed:
using System.DirectoryServices;
using System.DirectoryServices.ActiveDirectory;

var userSignOn = System.Web.HttpContext.Current.Request.LogonUserIdentity.Name;

List<string> activedirectoryGroupList = new List<string>();

activedirectoryGroupList = GetGroupsFromSignOn(userSignOn);

The function being called:

internal static List<string> GetGroupsFromSignOn(string signOn)
{
    string searchText = "(&(objectCategory=person)(objectClass=user)(sAMAccountName={0}))";
    searchText = searchText.Replace("{0}", signOn);

    Domain domain = Domain.GetCurrentDomain();
    DirectoryEntry userEntry = domain.GetDirectoryEntry();

    DirectorySearcher searcher = new DirectorySearcher(userEntry, searchText);
    SearchResult result = searcher.FindOne();

    DirectoryEntry currentUserEntry = result.GetDirectoryEntry();

    List<string> activedirectoryGroupList = new List<string>();

    if (currentUserEntry != null)
    {
        int propertyCount = currentUserEntry.Properties["memberOf"].Count;

        string activedirectoryGroup;

        for (int i = 0; i < propertyCount; i++)
        {
            activedirectoryGroup = Convert.ToString(currentUserEntry.Properties["memberOf"][i]);

            int startIndex = activedirectoryGroup.IndexOf('=');
            startIndex += 1;

            int endIndex = activedirectoryGroup.IndexOf(',');

            int stringLength = endIndex - startIndex;

            activedirectoryGroup = activedirectoryGroup.Substring(startIndex, stringLength);

            activedirectoryGroupList.Add(activedirectoryGroup);
        }

        return activedirectoryGroupList;
    }
    else
    {
        return null;
    }
}

From there, you would have a list of the AD Groups your user would be a part of, and you can either cross reference these groups with your authorized group name(s) that you can set either in your web config file, or in a SQL database that you can call out to.

As for determining what would be displayed, you should likely set up a master view, with partial views rendered on that page depending upon your user's authorization status for that information.

Edit:

Useful thread about the challenges of authentication with asp.net MVC


问:
any way to save multiple plots in for loop without overwriting in python?
I have a list of aggregated dataframes that hold trade statistics of different countries. I am able to make the respective plot by looping through this dataframe list. Now I intend to save those locally without overwriting, I mean saving each plot with its respective title name. To do so, I tried the following:

I have list of dataframe which have the following name:

```<code>[dfList[i].name for i in range(len(dfList))]

['AR  fresh-Beef-E',
 'AUC  fresh-Beef-E',
 'BR  fresh-Beef-E',
 'CA  fresh-Beef-E',
 'CL  fresh-Beef-E',
 'CN  fresh-Beef-E',
 'E28  fresh-Beef-E',
 'EG  fresh-Beef-E',
 'IN  fresh-Beef-E',
 'JP  fresh-Beef-E',
 'KR  fresh-Beef-E',
 'MX  fresh-Beef-E',
 'NZ  fresh-Beef-E',
 'PY  fresh-Beef-E',
 'US  fresh-Beef-E',
 'UY  fresh-Beef-E',
 'ZA  fresh-Beef-E']
</code>```

current attempt:

intend to save figure locally with its plot title as filename:

```<code>import os
import pandas as pd
import matplotlib.pyplot as plt

outpath = r'C:/Users/plots'

if os.path.exists(outpath):
    shutil.rmtree(outpath)
_ = os.mkdir(outpath)

for i in range(len(dfList)) :
    plt.figure()
    my_plotter(dfList[i],title=dfList[i].name)
    plt.savefig(path.join(outpath,"dataname_{0}.png".format(i)))
    plt.close()
</code>```

new update

here is how my plotting function looks like:

```<code>def my_plotter(df, plot_type='something', ylab_nm='something', title=None):
    fig, ax1 = plt.subplots(figsize=figsize)
    if plot_type=='something':
        _ = df.plot(kind='line', ax=ax1, marker='o', ls='-', linewidth=2, color=colors)
    else:
        df.loc[:, 'Total'] = df.sum(axis=1)
        _ = df.div(df.Total, axis=0).iloc[:, :-1].plot(kind='line', ax=ax1, marker='o', ls='--', linewidth=4, color=colors)
        df.drop('Total', axis=1, inplace=True)
        ax1.yaxis.set_major_formatter(mtick.PercentFormatter(xmax=1, decimals=0))
        ax1.xaxis.set_major_locator(mdates.MonthLocator(bymonthday=1, interval=3))

    ax1.set(title=title)
    plt.title(title)
    ax1.xaxis.label.set_visible(False)
    plt.style.use('ggplot')
    plt.xticks(rotation=90)
    plt.show()
</code>```

but the above attempt didn't save the plot to the local directory. I looked into SO and tried possible suggestion but I still didn't get all plots which supposed to be named by taking its plot title and saved to the local file directory. In my attempt, none of the plots were saved to a local directory.

Can anyone point me out how to make this work? any idea?
goal

I intend to save each plot by taking its title as the filename and save it to the local directory. Any thoughts? thanks

答:
It's not a complete MWE, but I think the fixes below should help you out.</p>

```<code>import matplotlib.pyplot as plt
import pandas as pd
import os

# Only need to set the style once (not in loop)
plt.style.use('ggplot')

outpath = r'C:/Users/plots'

def my_plotter(df, plot_type='something', ylab_nm='something', title=None):
    fig, ax1 = plt.subplots(1, 1)
    if plot_type=='something':
        # Plots on ax1, so don't save output as another ax instance
        df.plot(kind='line', ax=ax1, marker='o', ls='-', linewidth=2)
    else:
        df.loc[:, 'Total'] = df.sum(axis=1)
        # Plots on ax1, so don't save output as another ax instance
        df.div(df.Total, axis=0).iloc[:, :-1].plot(kind='line', ax=ax1, marker='o', ls='--', linewidth=4, color=colors)
        df.drop('Total', axis=1, inplace=True)
        ax1.yaxis.set_major_formatter(mtick.PercentFormatter(xmax=1, decimals=0))
        ax1.xaxis.set_major_locator(mdates.MonthLocator(bymonthday=1, interval=3))

    ax1.set(title=title)
    ax1.set_title(title, size=24, verticalalignment='bottom')
    ax1.xaxis.set_major_formatter(mdates.DateFormatter('%b %Y'))
    ax1.xaxis.label.set_visible(False)

    plt.xticks(rotation=90)
    plt.show()
    return fig, ax1

if os.path.exists(outpath):
    shutil.rmtree(outpath)
_ = os.mkdir(outpath)

for i in range(len(dfList)):
    fig, ax1 = my_plotter(dfList[i], title=dfList[i].name)
    fig.savefig(path.join(outpath,"dataname_{}.png".format(dfList[i].name)))
    plt.close()
</code>```

Body:
I have a list of aggregated dataframes that hold trade statistics of different countries. I am able to make the respective plot by looping through this dataframe list. Now I intend to save those locally without overwriting, I mean saving each plot with its respective title name. To do so, I tried the following:

I have list of dataframe which have the following name:

[dfList[i].name for i in range(len(dfList))]

['AR  fresh-Beef-E',
 'AUC  fresh-Beef-E',
 'BR  fresh-Beef-E',
 'CA  fresh-Beef-E',
 'CL  fresh-Beef-E',
 'CN  fresh-Beef-E',
 'E28  fresh-Beef-E',
 'EG  fresh-Beef-E',
 'IN  fresh-Beef-E',
 'JP  fresh-Beef-E',
 'KR  fresh-Beef-E',
 'MX  fresh-Beef-E',
 'NZ  fresh-Beef-E',
 'PY  fresh-Beef-E',
 'US  fresh-Beef-E',
 'UY  fresh-Beef-E',
 'ZA  fresh-Beef-E']

current attempt:

intend to save figure locally with its plot title as filename:

import os
import pandas as pd
import matplotlib.pyplot as plt

outpath = r'C:/Users/plots'

if os.path.exists(outpath):
    shutil.rmtree(outpath)
_ = os.mkdir(outpath)

for i in range(len(dfList)) :
    plt.figure()
    my_plotter(dfList[i],title=dfList[i].name)
    plt.savefig(path.join(outpath,"dataname_{0}.png".format(i)))
    plt.close()

new update

here is how my plotting function looks like:

def my_plotter(df, plot_type='something', ylab_nm='something', title=None):
    fig, ax1 = plt.subplots(figsize=figsize)
    if plot_type=='something':
        _ = df.plot(kind='line', ax=ax1, marker='o', ls='-', linewidth=2, color=colors)
    else:
        df.loc[:, 'Total'] = df.sum(axis=1)
        _ = df.div(df.Total, axis=0).iloc[:, :-1].plot(kind='line', ax=ax1, marker='o', ls='--', linewidth=4, color=colors)
        df.drop('Total', axis=1, inplace=True)
        ax1.yaxis.set_major_formatter(mtick.PercentFormatter(xmax=1, decimals=0))
        ax1.xaxis.set_major_locator(mdates.MonthLocator(bymonthday=1, interval=3))

    ax1.set(title=title)
    plt.title(title)
    ax1.xaxis.label.set_visible(False)
    plt.style.use('ggplot')
    plt.xticks(rotation=90)
    plt.show()

but the above attempt didn't save the plot to the local directory. I looked into SO and tried possible suggestion but I still didn't get all plots which supposed to be named by taking its plot title and saved to the local file directory. In my attempt, none of the plots were saved to a local directory.

Can anyone point me out how to make this work? any idea?
goal

I intend to save each plot by taking its title as the filename and save it to the local directory. Any thoughts? thanks

Body:
It's not a complete MWE, but I think the fixes below should help you out.

import matplotlib.pyplot as plt
import pandas as pd
import os

# Only need to set the style once (not in loop)
plt.style.use('ggplot')

outpath = r'C:/Users/plots'

def my_plotter(df, plot_type='something', ylab_nm='something', title=None):
    fig, ax1 = plt.subplots(1, 1)
    if plot_type=='something':
        # Plots on ax1, so don't save output as another ax instance
        df.plot(kind='line', ax=ax1, marker='o', ls='-', linewidth=2)
    else:
        df.loc[:, 'Total'] = df.sum(axis=1)
        # Plots on ax1, so don't save output as another ax instance
        df.div(df.Total, axis=0).iloc[:, :-1].plot(kind='line', ax=ax1, marker='o', ls='--', linewidth=4, color=colors)
        df.drop('Total', axis=1, inplace=True)
        ax1.yaxis.set_major_formatter(mtick.PercentFormatter(xmax=1, decimals=0))
        ax1.xaxis.set_major_locator(mdates.MonthLocator(bymonthday=1, interval=3))

    ax1.set(title=title)
    ax1.set_title(title, size=24, verticalalignment='bottom')
    ax1.xaxis.set_major_formatter(mdates.DateFormatter('%b %Y'))
    ax1.xaxis.label.set_visible(False)

    plt.xticks(rotation=90)
    plt.show()
    return fig, ax1

if os.path.exists(outpath):
    shutil.rmtree(outpath)
_ = os.mkdir(outpath)

for i in range(len(dfList)):
    fig, ax1 = my_plotter(dfList[i], title=dfList[i].name)
    fig.savefig(path.join(outpath,"dataname_{}.png".format(dfList[i].name)))
    plt.close()


问:
Positioning ARKIT model
I am having a bit of trouble positioning a model on the screen. The model appears but it appears above me rather than in front of me. Ideally I want the model to appear where it is tapped. Please help!

This function here downloads the model successfully from AWS:

```<code> private func dowloadModel(){
        let url = URL(string: "url_string")!

        URLSession.shared.dataTask(with: url) { data, response, error in

            if let error = error{
                print(error.localizedDescription)
                return
            }

            if let data = data{
                print(data)

                let documentDirectories = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask)

                if let documentDirectory = documentDirectories.first{

                    let fileURL = documentDirectory.appendingPathComponent("Food.scn")
                    let dataNS : NSData? = data as NSData

                    try! dataNS?.write(to: fileURL, options: .atomic)

                    print("Saved!")
                }
            }

        }.resume()
    }
</code>```

Here I render the model to the screen:

```<code>private func registerGestureRecogniser(){
        print("Tapped")
        let tapGestureRecognizer = UITapGestureRecognizer(target: self, action: #selector(handleTap))
        self.sceneView.addGestureRecognizer(tapGestureRecognizer)
    }
</code>```

Here is the tapped function:

```<code> @objc func handleTap(gesture: UITapGestureRecognizer) {

        let documentDirectories = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask)

        if let documentDirectory = documentDirectories.first{
            let fileURL = documentDirectory.appendingPathComponent("Food.scn")

            do{
                let scene = try SCNScene(url: fileURL, options: nil)
                let node = scene.rootNode.childNode(withName: "Burger", recursively: true)!

                node.position = SCNVector3Make(0, 0, 0);

                self.sceneView.scene.rootNode.addChildNode(node)
            }
            catch{
                print(error)
            }

        }
    }
</code>```

I also get the error:

```<code>Error: Failed to load <C3DImage
</code>```

答:
When you do

```<code>node.position = SCNVector3Make(0, 0, 0);
self.sceneView.scene.rootNode.addChildNode(node)
</code>```

you are positioning your model node at the rootNode of the scene, the position of which is determined by ARKit when the scene starts.

If you want the model to appear in front of the camera, then you need to grab the camera transform (session.currentFrame?.camera.transform), modify the -z component, and set that as the node's position. Or, if you want to place your model on a surface, do a raycast and use the raycastResult simdWorldPosition as your node's simdWorldPosition.

There are definitely examples of raycast around, but in brief, you first need to define a query:

```<code>let bounds = sceneView.bounds
let screenCenter = CGPoint(x: bounds.midX, y: bounds.midY)
let query = sceneView.raycastQuery(from: screenCenter, allowing: .estimatedPlane, alignment: .horizontal)
</code>```

The above defines a raycast extending from the center of the screen and finding only horizontal surfaces. Please explore the docs for more information about allowing and alignment options.

You can then use the session to cast your ray:

```<code>session.raycast(query)
</code>```

This will return an array of ARRaycastResult. You can examine them and choose if you wish, but I usually just take the .first one (note: it can be empty).

You would then want to take the translation component of your raycastResult transform and assign it as the simdWorldPosition of your node. Note that you can assign the entire transform to the nodes simdWorldTransform but this will also alter your node's orientation, which you may or may not want to do.

```<code>if let raycastResult = session.raycast(query).first {
    node.simdWorldPosition = raycastResult.worldTransform.translation
}
</code>```

Oh, also, I find this little extension to be handy:

```<code>extension float4x4 {
    /**
     Treats matrix as a (right-hand column-major convention) transform matrix
     and factors out the translation component of the transform.
    */
    var translation: SIMD3<Float> {
        let translation = columns.3
        return SIMD3<Float>(translation.x, translation.y, translation.z)
    }
}
</code>```

It's what allows you to do the worldTransform.translation in my code above.

Title: Positioning ARKIT model

Body:
I am having a bit of trouble positioning a model on the screen. The model appears but it appears above me rather than in front of me. Ideally I want the model to appear where it is tapped. Please help!

This function here downloads the model successfully from AWS:

 private func dowloadModel(){
        let url = URL(string: "url_string")!

        URLSession.shared.dataTask(with: url) { data, response, error in

            if let error = error{
                print(error.localizedDescription)
                return
            }

            if let data = data{
                print(data)

                let documentDirectories = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask)

                if let documentDirectory = documentDirectories.first{

                    let fileURL = documentDirectory.appendingPathComponent("Food.scn")
                    let dataNS : NSData? = data as NSData

                    try! dataNS?.write(to: fileURL, options: .atomic)

                    print("Saved!")
                }
            }

        }.resume()
    }

Here I render the model to the screen:

private func registerGestureRecogniser(){
        print("Tapped")
        let tapGestureRecognizer = UITapGestureRecognizer(target: self, action: #selector(handleTap))
        self.sceneView.addGestureRecognizer(tapGestureRecognizer)
    }

Here is the tapped function:

 @objc func handleTap(gesture: UITapGestureRecognizer) {

        let documentDirectories = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask)

        if let documentDirectory = documentDirectories.first{
            let fileURL = documentDirectory.appendingPathComponent("Food.scn")

            do{
                let scene = try SCNScene(url: fileURL, options: nil)
                let node = scene.rootNode.childNode(withName: "Burger", recursively: true)!

                node.position = SCNVector3Make(0, 0, 0);

                self.sceneView.scene.rootNode.addChildNode(node)
            }
            catch{
                print(error)
            }

        }
    }

I also get the error:

Error: Failed to load <C3DImage

Body:
When you do

node.position = SCNVector3Make(0, 0, 0);
self.sceneView.scene.rootNode.addChildNode(node)

you are positioning your model node at the rootNode of the scene, the position of which is determined by ARKit when the scene starts.

If you want the model to appear in front of the camera, then you need to grab the camera transform (session.currentFrame?.camera.transform), modify the -z component, and set that as the node's position. Or, if you want to place your model on a surface, do a raycast and use the raycastResult simdWorldPosition as your node's simdWorldPosition.

There are definitely examples of raycast around, but in brief, you first need to define a query:

let bounds = sceneView.bounds
let screenCenter = CGPoint(x: bounds.midX, y: bounds.midY)
let query = sceneView.raycastQuery(from: screenCenter, allowing: .estimatedPlane, alignment: .horizontal)

The above defines a raycast extending from the center of the screen and finding only horizontal surfaces. Please explore the docs for more information about allowing and alignment options.

You can then use the session to cast your ray:

session.raycast(query)

This will return an array of ARRaycastResult. You can examine them and choose if you wish, but I usually just take the .first one (note: it can be empty).

You would then want to take the translation component of your raycastResult transform and assign it as the simdWorldPosition of your node. Note that you can assign the entire transform to the nodes simdWorldTransform but this will also alter your node's orientation, which you may or may not want to do.

if let raycastResult = session.raycast(query).first {
    node.simdWorldPosition = raycastResult.worldTransform.translation
}

Oh, also, I find this little extension to be handy:

extension float4x4 {
    /**
     Treats matrix as a (right-hand column-major convention) transform matrix
     and factors out the translation component of the transform.
    */
    var translation: SIMD3<Float> {
        let translation = columns.3
        return SIMD3<Float>(translation.x, translation.y, translation.z)
    }
}

It's what allows you to do the worldTransform.translation in my code above.


问:
SqlFunctions.StringConvert() is not working ef core
I am migrating the application to the .net core.  but SqlFunctions.StringConvert() is not working in.netcore.
I am using the following code:</p>

```<code>using (var entity = new AppEntity())
            {
            var    physianAggregationList = (from physianAggregaton in entity.tbl_Physician_Aggregation_Year

                                          where (
                                                 (physianAggregaton.CMS_Submission_Year == cmsyear)
                                                 && (physianAggregaton.Physician_NPI == npi || (string.IsNullOrEmpty(npi)))
                                                 && physianAggregaton.Is_90Days == is_90Days && physianAggregaton.Exam_TIN == Tin
                                                 )
                                          select new Tindata
                                          {

                                              Performance_Rate = entity.tbl_Lookup_Measure.Where(i => i.Measure_num.ToLower() == physianAggregaton.Measure_Num.ToLower()
                                                                                && i.CMSYear == physianAggregaton.CMS_Submission_Year)
                                                                                .Select(x => x.Perf_Rate_Per_1000).FirstOrDefault() == boolValue
                                                                                ? (physianAggregaton.Performance_rate == null ? "NULL" : SqlFunctions.StringConvert(physianAggregaton.Performance_rate, 100, 2))
                                                                                : (physianAggregaton.Performance_rate == null ? "NULL" : SqlFunctions.StringConvert(physianAggregaton.Performance_rate, 100, 2) + "%"),

                                              Reporting_Rate = physianAggregaton.Reporting_Rate == null ? "NULL" : SqlFunctions.StringConvert(

                                              //}).Distinct().OrderBy(x=>x.displayorder).ToList();
                                          }).Distinct().OrderBy(x => x.LastName).ToList();
                ///logger.LogInfo("PhysianAggregation Count in getPhysianAggregationData():[" + physianAggregationList.Count()+"]");
            }
</code>```

答:
SqlFunctions is EF6 specific class and cannot be used in EF Core. EF Core custom functions are available as extension methods of EF.Functions.

Unfortunately currently EF Core does not provide equivalent of StringConvert. But it can be added relatively easy by using the EF Core Database scalar function mapping and mapping to STR method similar to what EF6 was doing.

For instance, add the following class (with the necessary usings):

```<code>public static class SqlFunctions
{
    public static string ToString(this decimal? value, int? length, int? decimalArg) => throw new NotSupportedException();
    public static string ToString(this double? value, int? length, int? decimalArg) => throw new NotSupportedException();
    public static ModelBuilder AddSqlFunctions(this ModelBuilder modelBuilder) => modelBuilder
        .MapToSTR(() => ToString(default(decimal?), null, null))
        .MapToSTR(() => ToString(default(double?), null, null));
    static ModelBuilder MapToSTR(this ModelBuilder modelBuilder, Expression<Func<string>> method)
    {
        modelBuilder.HasDbFunction(method).HasTranslation(args =>
            new SqlFunctionExpression(null, null, "STR", false, args, true, typeof(string), null));
        return modelBuilder;
    }
}
</code>```

then the following inside your OnModelCreating override:

```<code>if (Database.IsSqlServer()) modelBuilder.AddSqlFunctions();
</code>```

then inside the query, replace

```<code>SqlFunctions.StringConvert(physianAggregaton.Performance_rate, 100, 2)
</code>```

with

```<code>physianAggregaton.Performance_rate.ToString(100, 2)
</code>```

Body:
I am migrating the application to the .net core.  but SqlFunctions.StringConvert() is not working in.netcore.
I am using the following code:

using (var entity = new AppEntity())
            {
            var    physianAggregationList = (from physianAggregaton in entity.tbl_Physician_Aggregation_Year

                                          where (
                                                 (physianAggregaton.CMS_Submission_Year == cmsyear)
                                                 && (physianAggregaton.Physician_NPI == npi || (string.IsNullOrEmpty(npi)))
                                                 && physianAggregaton.Is_90Days == is_90Days && physianAggregaton.Exam_TIN == Tin
                                                 )
                                          select new Tindata
                                          {

                                              Performance_Rate = entity.tbl_Lookup_Measure.Where(i => i.Measure_num.ToLower() == physianAggregaton.Measure_Num.ToLower()
                                                                                && i.CMSYear == physianAggregaton.CMS_Submission_Year)
                                                                                .Select(x => x.Perf_Rate_Per_1000).FirstOrDefault() == boolValue
                                                                                ? (physianAggregaton.Performance_rate == null ? "NULL" : SqlFunctions.StringConvert(physianAggregaton.Performance_rate, 100, 2))
                                                                                : (physianAggregaton.Performance_rate == null ? "NULL" : SqlFunctions.StringConvert(physianAggregaton.Performance_rate, 100, 2) + "%"),

                                              Reporting_Rate = physianAggregaton.Reporting_Rate == null ? "NULL" : SqlFunctions.StringConvert(

                                              //}).Distinct().OrderBy(x=>x.displayorder).ToList();
                                          }).Distinct().OrderBy(x => x.LastName).ToList();
                ///logger.LogInfo("PhysianAggregation Count in getPhysianAggregationData():[" + physianAggregationList.Count()+"]");
            }

Body:
SqlFunctions is EF6 specific class and cannot be used in EF Core. EF Core custom functions are available as extension methods of EF.Functions.

Unfortunately currently EF Core does not provide equivalent of StringConvert. But it can be added relatively easy by using the EF Core Database scalar function mapping and mapping to STR method similar to what EF6 was doing.

For instance, add the following class (with the necessary usings):

public static class SqlFunctions
{
    public static string ToString(this decimal? value, int? length, int? decimalArg) => throw new NotSupportedException();
    public static string ToString(this double? value, int? length, int? decimalArg) => throw new NotSupportedException();
    public static ModelBuilder AddSqlFunctions(this ModelBuilder modelBuilder) => modelBuilder
        .MapToSTR(() => ToString(default(decimal?), null, null))
        .MapToSTR(() => ToString(default(double?), null, null));
    static ModelBuilder MapToSTR(this ModelBuilder modelBuilder, Expression<Func<string>> method)
    {
        modelBuilder.HasDbFunction(method).HasTranslation(args =>
            new SqlFunctionExpression(null, null, "STR", false, args, true, typeof(string), null));
        return modelBuilder;
    }
}

then the following inside your OnModelCreating override:

if (Database.IsSqlServer()) modelBuilder.AddSqlFunctions();

then inside the query, replace

SqlFunctions.StringConvert(physianAggregaton.Performance_rate, 100, 2)

with

physianAggregaton.Performance_rate.ToString(100, 2)


问:
Using the g++ C++ compiler from cygwin
I am trying to execute my first "Hello World!" in C++. I am using Windows XP, and I have installed cygwin, in which the g++ C++ compiler is installed. I have written a small hello-world program, and saved it in hello.cpp. From the command prompt I write:

g++ hello.cpp

But I get:

'g++' is not recognized as an internal or external command, operable program or batch file.

I have installed cygwin in my D:\programs\cygwin. I have made another directory with my hello-world file in D:\cpp. Something with my installation or my paths seems to be not Ok, but I cannot figure what. I have run the exe file of cygwin, and in the installation directory I have got all necessary files, I think: bin folder, lib, Cygwin.bat, etc.

I have read that in case of such error message I should check whether the cygwin1.dll file is copied into the main folder of Windows. Is this the C:\WINDOWS directory? I have looked there, and I don't have such a file there. I have cygwin1.dll in the bin folder of cygwin: D:\programs\cygwin\bin.
Also, how do I check whether the bin folder (D:\programs\cygwin\bin) is considered in the search path of commands?

I think that the hello-world program shouldn't contain any syntax errors, I have just copied it. Also, when I write

g++ -v

I get the same error message: that the command is not recognized.
I would appreciate if someone give me a hint what should I look at. Thank you.

Here is the code of the hello-world program:

```<code>#include <iostream>
using namespace std;

int main() {
  cout <<"Hello World!"<<endl;
  return 0;
}
</code>```

I have installed g++, and now when I type g++ -v, I get: Reading specs from: \d\cygnus\cygwin-b20\H-i586-cygwin32\bin..\lib\gcc-lib\i586-cygwin32\egcs-2.91.57\specs gcc version egcs-2.91.57 19980901 (egcs-1.1 release)

In the bin directory I have both g++.exe, and gcc.exe. I don't understand why I get "gcc" above and not "g++". I don't know how important this is, but I receive an error message when I try to compile the program in the DOS command prompt:

g++ hello.cpp

I get:

```<code>hello.cpp:1: parse error before character 0357
hello.cpp: In function 'int main()':
hello.cpp:'cout' undeclared (first use this function)
hello.cpp: (Each undeclared identifier is reported only once
hello.cpp: for each function it appears in.)
hello.cpp: 'endl' undeclared (first use this function)
</code>```

And here is what I get when I try to compile the program in the cygwin shell:

```<code>hello.cpp:1: parse error before character 0357
hello.cpp: In function 'int main()':
hello.cpp:'cout' undeclared (first use this function)
hello.cpp: (Each undeclared identifier is reported only once
hello.cpp: for each function it appears in.)
hello.cpp: 'endl' undeclared (first use this function)
g++.exe: hello.cpp: No such file or directory
g++.exe: No input files
g++.exe: hello.cpp: No such file or directory
g++.exe: No input files
g++.exe: hello.cpp: No such file or directory
g++.exe: No input files
g++.exe: hello.cpp: No such file or directory
g++.exe: No input files
g++.exe: hello.cpp: No such file or directory
g++.exe: No input files
</code>```

答: make sure it's on the path or you're running the bash shell cmd prompt.</p>

ContentLicense: CC BY-SA 2.5

Title: Using the g++ C++ compiler from cygwin

Body:
I am trying to execute my first "Hello World!" in C++. I am using Windows XP, and I have installed cygwin, in which the g++ C++ compiler is installed. I have written a small hello-world program, and saved it in hello.cpp. From the command prompt I write:

g++ hello.cpp

But I get:

'g++' is not recognized as an internal or external command, operable program or batch file.

I have installed cygwin in my D:\programs\cygwin. I have made another directory with my hello-world file in D:\cpp. Something with my installation or my paths seems to be not Ok, but I cannot figure what. I have run the exe file of cygwin, and in the installation directory I have got all necessary files, I think: bin folder, lib, Cygwin.bat, etc.

I have read that in case of such error message I should check whether the cygwin1.dll file is copied into the main folder of Windows. Is this the C:\WINDOWS directory? I have looked there, and I don't have such a file there. I have cygwin1.dll in the bin folder of cygwin: D:\programs\cygwin\bin.
Also, how do I check whether the bin folder (D:\programs\cygwin\bin) is considered in the search path of commands?

I think that the hello-world program shouldn't contain any syntax errors, I have just copied it. Also, when I write

g++ -v

I get the same error message: that the command is not recognized.
I would appreciate if someone give me a hint what should I look at. Thank you.

Here is the code of the hello-world program:

#include <iostream>
using namespace std;

int main() {
  cout <<"Hello World!"<<endl;
  return 0;
}

I have installed g++, and now when I type g++ -v, I get: Reading specs from: \d\cygnus\cygwin-b20\H-i586-cygwin32\bin..\lib\gcc-lib\i586-cygwin32\egcs-2.91.57\specs gcc version egcs-2.91.57 19980901 (egcs-1.1 release)

In the bin directory I have both g++.exe, and gcc.exe. I don't understand why I get "gcc" above and not "g++". I don't know how important this is, but I receive an error message when I try to compile the program in the DOS command prompt:

g++ hello.cpp

I get:

hello.cpp:1: parse error before character 0357
hello.cpp: In function 'int main()':
hello.cpp:'cout' undeclared (first use this function)
hello.cpp: (Each undeclared identifier is reported only once
hello.cpp: for each function it appears in.)
hello.cpp: 'endl' undeclared (first use this function)

And here is what I get when I try to compile the program in the cygwin shell:

hello.cpp:1: parse error before character 0357
hello.cpp: In function 'int main()':
hello.cpp:'cout' undeclared (first use this function)
hello.cpp: (Each undeclared identifier is reported only once
hello.cpp: for each function it appears in.)
hello.cpp: 'endl' undeclared (first use this function)
g++.exe: hello.cpp: No such file or directory
g++.exe: No input files
g++.exe: hello.cpp: No such file or directory
g++.exe: No input files
g++.exe: hello.cpp: No such file or directory
g++.exe: No input files
g++.exe: hello.cpp: No such file or directory
g++.exe: No input files
g++.exe: hello.cpp: No such file or directory
g++.exe: No input files

LastEditorDisplayName: Rich B

OwnerDisplayName: sfossen


问:
android: ScrollView in 1.5 doesn't work
My one layout works perfect on 1.6+ but throws error on 1.5 and results in shutting down the app with "Force Close". The layout contains RelativeLayout as parent, ScrollView which contains RelativeLayout as child and imagevite, textview, edittext, buttons in child relativeLayout. Here's the xml file :

```<code><?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
  xmlns:android="http://schemas.android.com/apk/res/android"
  android:layout_width="fill_parent"  android:layout_height="fill_parent"
  android:id="@+id/user_pswd_new_root" android:scrollbars="vertical" android:soundEffectsEnabled="true">

 <ScrollView android:id="@+id/ScrollViewLogin" android:layout_width="fill_parent" android:layout_height="wrap_content" android:scrollbarStyle="outsideInset" android:scrollbars="vertical" android:visibility="visible">
   <RelativeLayout android:layout_width="fill_parent" android:id="@+id/relativeLayout1" android:layout_height="fill_parent">

    <ImageView android:background="@drawable/logo_login_new" android:layout_height="wrap_content" android:id="@+id/imageView1"
    android:layout_width="wrap_content" android:layout_alignParentLeft="true" android:layout_marginLeft="40dp"></ImageView>
    <TextView android:layout_height="wrap_content" android:textStyle="bold"
    android:layout_width="wrap_content" android:text="@string/login_text" android:layout_marginRight="40dp"
    android:textSize="25dp" android:id="@+id/textView1" android:layout_alignParentRight="true" android:layout_marginTop="20dp"></TextView>
    <TextView android:layout_height="wrap_content" android:layout_width="wrap_content" android:layout_alignParentLeft="true" android:layout_below="@+id/imageView1" android:layout_margin="10dp" android:text="@string/username" android:id="@+id/textView2_usr" android:layout_marginTop="10dp"></TextView>
    <EditText android:layout_height="wrap_content" android:layout_alignParentRight="true" android:layout_width="wrap_content" android:text="" android:layout_toRightOf="@+id/textView2_usr" android:layout_alignTop="@+id/textView2_usr" android:layout_marginRight="10dp" android:id="@+id/user_pwd_username"></EditText>
    <TextView android:layout_height="wrap_content" android:layout_width="wrap_content" android:layout_alignParentLeft="true" android:layout_marginLeft="10dp" android:layout_below="@+id/user_pwd_username" android:id="@+id/textView3_usr" android:text="@string/password"></TextView>
    <EditText android:layout_height="wrap_content" android:layout_alignParentRight="true" android:layout_width="wrap_content" android:text="" android:layout_toRightOf="@+id/textView3_usr" android:layout_below="@+id/user_pwd_username" android:layout_marginRight="10dp" android:layout_alignLeft="@+id/user_pwd_username" android:id="@+id/user_pwd_password" android:password="true"></EditText>
    <CheckBox android:layout_height="wrap_content" android:layout_width="wrap_content" android:layout_alignParentLeft="true" android:layout_below="@+id/user_pwd_password" android:text="@string/remMe" android:layout_marginLeft="10dp" android:id="@+id/user_pwd_remMeChk"></CheckBox>
    <Button android:layout_height="wrap_content" android:layout_width="wrap_content" android:layout_alignParentLeft="true" android:layout_below="@+id/user_pwd_remMeChk" android:text="@string/loginBtn" android:id="@+id/user_pwd_btn_ok" android:layout_marginLeft="40dp" android:width="100dp"></Button>
    <Button android:layout_height="wrap_content" android:id="@+id/user_pwd_btn_cancel" android:layout_alignParentRight="true" android:layout_width="wrap_content" android:layout_marginRight="40dp" android:layout_alignTop="@+id/user_pwd_btn_ok" android:text="@string/cancelBtn" android:width="100dp"></Button>
    <TextView android:layout_height="wrap_content" android:layout_width="wrap_content" android:text="Version" android:layout_alignParentRight="true" android:layout_below="@+id/user_pwd_btn_cancel" android:layout_marginRight="10dp" android:id="@+id/versionText" android:textSize="6dp"></TextView>
    <TextView android:layout_height="wrap_content" android:layout_width="wrap_content" android:text="" android:layout_alignParentLeft="true" android:layout_below="@+id/versionText" android:layout_marginLeft="10dp" android:id="@+id/messageText" android:scrollbars="vertical"></TextView>

    </RelativeLayout>
 </ScrollView>

</RelativeLayout>
</code>```

The errors I get in LogCat is :

```<code>05-17 17:07:02.110: ERROR/AndroidRuntime(1215): Uncaught handler: thread main exiting due to uncaught exception
05-17 17:07:02.139: ERROR/AndroidRuntime(1215): java.lang.RuntimeException: Unable to start activity ComponentInfo{orange.android.vpn/orange.android.vpn.StartUltimate}: android.view.InflateException: Binary XML file line #11: Error inflating class java.lang.reflect.Constructor
05-17 17:07:02.139: ERROR/AndroidRuntime(1215):     at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2268)
05-17 17:07:02.139: ERROR/AndroidRuntime(1215):     at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2284)
05-17 17:07:02.139: ERROR/AndroidRuntime(1215):     at android.app.ActivityThread.access$1800(ActivityThread.java:112)
05-17 17:07:02.139: ERROR/AndroidRuntime(1215):     at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1692)
05-17 17:07:02.139: ERROR/AndroidRuntime(1215):     at android.os.Handler.dispatchMessage(Handler.java:99)
05-17 17:07:02.139: ERROR/AndroidRuntime(1215):     at android.os.Looper.loop(Looper.java:123)
05-17 17:07:02.139: ERROR/AndroidRuntime(1215):     at android.app.ActivityThread.main(ActivityThread.java:3948)
05-17 17:07:02.139: ERROR/AndroidRuntime(1215):     at java.lang.reflect.Method.invokeNative(Native Method)
05-17 17:07:02.139: ERROR/AndroidRuntime(1215):     at java.lang.reflect.Method.invoke(Method.java:521)
05-17 17:07:02.139: ERROR/AndroidRuntime(1215):     at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:782)
05-17 17:07:02.139: ERROR/AndroidRuntime(1215):     at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:540)
05-17 17:07:02.139: ERROR/AndroidRuntime(1215):     at dalvik.system.NativeStart.main(Native Method)
05-17 17:07:02.139: ERROR/AndroidRuntime(1215): Caused by: android.view.InflateException: Binary XML file line #11: Error inflating class java.lang.reflect.Constructor
05-17 17:07:02.139: ERROR/AndroidRuntime(1215):     at android.view.LayoutInflater.createView(LayoutInflater.java:512)
05-17 17:07:02.139: ERROR/AndroidRuntime(1215):     at com.android.internal.policy.impl.PhoneLayoutInflater.onCreateView(PhoneLayoutInflater.java:56)
05-17 17:07:02.139: ERROR/AndroidRuntime(1215):     at android.view.LayoutInflater.createViewFromTag(LayoutInflater.java:562)
05-17 17:07:02.139: ERROR/AndroidRuntime(1215):     at android.view.LayoutInflater.rInflate(LayoutInflater.java:617)
05-17 17:07:02.139: ERROR/AndroidRuntime(1215):     at android.view.LayoutInflater.rInflate(LayoutInflater.java:620)
05-17 17:07:02.139: ERROR/AndroidRuntime(1215):     at android.view.LayoutInflater.inflate(LayoutInflater.java:407)
05-17 17:07:02.139: ERROR/AndroidRuntime(1215):     at android.view.LayoutInflater.inflate(LayoutInflater.java:320)
05-17 17:07:02.139: ERROR/AndroidRuntime(1215):     at android.view.LayoutInflater.inflate(LayoutInflater.java:276)
05-17 17:07:02.139: ERROR/AndroidRuntime(1215):     at com.android.internal.policy.impl.PhoneWindow.setContentView(PhoneWindow.java:309)
05-17 17:07:02.139: ERROR/AndroidRuntime(1215):     at android.app.Dialog.setContentView(Dialog.java:400)
05-17 17:07:02.139: ERROR/AndroidRuntime(1215):     at orange.android.myw.LoginDialog.init(LoginDialog.java:78)
05-17 17:07:02.139: ERROR/AndroidRuntime(1215):     at orange.android.myw.LoginDialog.<init>(LoginDialog.java:72)
05-17 17:07:02.139: ERROR/AndroidRuntime(1215):     at orange.android.vpn.StartUltimate.onCreate(StartUltimate.java:129)
 05-17 17:07:02.139: ERROR/AndroidRuntime(1215):     at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1123)
 05-17 17:07:02.139: ERROR/AndroidRuntime(1215):     at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2231)
05-17 17:07:02.139: ERROR/AndroidRuntime(1215):     ... 11 more
05-17 17:07:02.139: ERROR/AndroidRuntime(1215): Caused by: java.lang.reflect.InvocationTargetException
05-17 17:07:02.139: ERROR/AndroidRuntime(1215):     at android.widget.ImageView.<init>(ImageView.java:103)
05-17 17:07:02.139: ERROR/AndroidRuntime(1215):     at java.lang.reflect.Constructor.constructNative(Native Method)
05-17 17:07:02.139: ERROR/AndroidRuntime(1215):     at java.lang.reflect.Constructor.newInstance(Constructor.java:446)
05-17 17:07:02.139: ERROR/AndroidRuntime(1215):     at android.view.LayoutInflater.createView(LayoutInflater.java:499)
05-17 17:07:02.139: ERROR/AndroidRuntime(1215):     ... 25 more
05-17 17:07:02.139: ERROR/AndroidRuntime(1215): Caused by: android.content.res.Resources$NotFoundException: File res/drawable/scrollbar_handle_vertical.9.png from drawable resource ID #0x7f020005
05-17 17:07:02.139: ERROR/AndroidRuntime(1215):     at android.content.res.Resources.loadDrawable(Resources.java:1641)
05-17 17:07:02.139: ERROR/AndroidRuntime(1215):     at android.content.res.TypedArray.getDrawable(TypedArray.java:548)
05-17 17:07:02.139: ERROR/AndroidRuntime(1215):     at android.view.View.<init>(View.java:1725)
05-17 17:07:02.139: ERROR/AndroidRuntime(1215):     at android.widget.ImageView.<init>(ImageView.java:107)
05-17 17:07:02.139: ERROR/AndroidRuntime(1215):     ... 29 more
05-17 17:07:02.139: ERROR/AndroidRuntime(1215): Caused by: java.io.FileNotFoundException: res/drawable/scrollbar_handle_vertical.9.png
05-17 17:07:02.139: ERROR/AndroidRuntime(1215):     at android.content.res.AssetManager.openNonAssetNative(Native Method)
05-17 17:07:02.139: ERROR/AndroidRuntime(1215):     at android.content.res.AssetManager.openNonAsset(AssetManager.java:392)
05-17 17:07:02.139: ERROR/AndroidRuntime(1215):     at android.content.res.Resources.loadDrawable(Resources.java:1634)
05-17 17:07:02.139: ERROR/AndroidRuntime(1215):     ... 32 more
</code>```

Error points to setContentView() line in the LoginDialog class.
Can anyone tell what is stopping it to show up in 1.5.

Thanks

答: The very first exception is a FileNotFoundException. Check if the file res/drawable/scrollbar_handle_vertical.9.png does exist.

ContentLicense: CC BY-SA 3.0

Title: android: ScrollView in 1.5 doesn't work

Body:
My one layout works perfect on 1.6+ but throws error on 1.5 and results in shutting down the app with "Force Close". The layout contains RelativeLayout as parent, ScrollView which contains RelativeLayout as child and imagevite, textview, edittext, buttons in child relativeLayout. Here's the xml file :

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
  xmlns:android="http://schemas.android.com/apk/res/android"
  android:layout_width="fill_parent"  android:layout_height="fill_parent"
  android:id="@+id/user_pswd_new_root" android:scrollbars="vertical" android:soundEffectsEnabled="true">

 <ScrollView android:id="@+id/ScrollViewLogin" android:layout_width="fill_parent" android:layout_height="wrap_content" android:scrollbarStyle="outsideInset" android:scrollbars="vertical" android:visibility="visible">
   <RelativeLayout android:layout_width="fill_parent" android:id="@+id/relativeLayout1" android:layout_height="fill_parent">

    <ImageView android:background="@drawable/logo_login_new" android:layout_height="wrap_content" android:id="@+id/imageView1"
    android:layout_width="wrap_content" android:layout_alignParentLeft="true" android:layout_marginLeft="40dp"></ImageView>
    <TextView android:layout_height="wrap_content" android:textStyle="bold"
    android:layout_width="wrap_content" android:text="@string/login_text" android:layout_marginRight="40dp"
    android:textSize="25dp" android:id="@+id/textView1" android:layout_alignParentRight="true" android:layout_marginTop="20dp"></TextView>
    <TextView android:layout_height="wrap_content" android:layout_width="wrap_content" android:layout_alignParentLeft="true" android:layout_below="@+id/imageView1" android:layout_margin="10dp" android:text="@string/username" android:id="@+id/textView2_usr" android:layout_marginTop="10dp"></TextView>
    <EditText android:layout_height="wrap_content" android:layout_alignParentRight="true" android:layout_width="wrap_content" android:text="" android:layout_toRightOf="@+id/textView2_usr" android:layout_alignTop="@+id/textView2_usr" android:layout_marginRight="10dp" android:id="@+id/user_pwd_username"></EditText>
    <TextView android:layout_height="wrap_content" android:layout_width="wrap_content" android:layout_alignParentLeft="true" android:layout_marginLeft="10dp" android:layout_below="@+id/user_pwd_username" android:id="@+id/textView3_usr" android:text="@string/password"></TextView>
    <EditText android:layout_height="wrap_content" android:layout_alignParentRight="true" android:layout_width="wrap_content" android:text="" android:layout_toRightOf="@+id/textView3_usr" android:layout_below="@+id/user_pwd_username" android:layout_marginRight="10dp" android:layout_alignLeft="@+id/user_pwd_username" android:id="@+id/user_pwd_password" android:password="true"></EditText>
    <CheckBox android:layout_height="wrap_content" android:layout_width="wrap_content" android:layout_alignParentLeft="true" android:layout_below="@+id/user_pwd_password" android:text="@string/remMe" android:layout_marginLeft="10dp" android:id="@+id/user_pwd_remMeChk"></CheckBox>
    <Button android:layout_height="wrap_content" android:layout_width="wrap_content" android:layout_alignParentLeft="true" android:layout_below="@+id/user_pwd_remMeChk" android:text="@string/loginBtn" android:id="@+id/user_pwd_btn_ok" android:layout_marginLeft="40dp" android:width="100dp"></Button>
    <Button android:layout_height="wrap_content" android:id="@+id/user_pwd_btn_cancel" android:layout_alignParentRight="true" android:layout_width="wrap_content" android:layout_marginRight="40dp" android:layout_alignTop="@+id/user_pwd_btn_ok" android:text="@string/cancelBtn" android:width="100dp"></Button>
    <TextView android:layout_height="wrap_content" android:layout_width="wrap_content" android:text="Version" android:layout_alignParentRight="true" android:layout_below="@+id/user_pwd_btn_cancel" android:layout_marginRight="10dp" android:id="@+id/versionText" android:textSize="6dp"></TextView>
    <TextView android:layout_height="wrap_content" android:layout_width="wrap_content" android:text="" android:layout_alignParentLeft="true" android:layout_below="@+id/versionText" android:layout_marginLeft="10dp" android:id="@+id/messageText" android:scrollbars="vertical"></TextView>

    </RelativeLayout>
 </ScrollView>

</RelativeLayout>

The errors I get in LogCat is :

05-17 17:07:02.110: ERROR/AndroidRuntime(1215): Uncaught handler: thread main exiting due to uncaught exception
05-17 17:07:02.139: ERROR/AndroidRuntime(1215): java.lang.RuntimeException: Unable to start activity ComponentInfo{orange.android.vpn/orange.android.vpn.StartUltimate}: android.view.InflateException: Binary XML file line #11: Error inflating class java.lang.reflect.Constructor
05-17 17:07:02.139: ERROR/AndroidRuntime(1215):     at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2268)
05-17 17:07:02.139: ERROR/AndroidRuntime(1215):     at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2284)
05-17 17:07:02.139: ERROR/AndroidRuntime(1215):     at android.app.ActivityThread.access$1800(ActivityThread.java:112)
05-17 17:07:02.139: ERROR/AndroidRuntime(1215):     at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1692)
05-17 17:07:02.139: ERROR/AndroidRuntime(1215):     at android.os.Handler.dispatchMessage(Handler.java:99)
05-17 17:07:02.139: ERROR/AndroidRuntime(1215):     at android.os.Looper.loop(Looper.java:123)
05-17 17:07:02.139: ERROR/AndroidRuntime(1215):     at android.app.ActivityThread.main(ActivityThread.java:3948)
05-17 17:07:02.139: ERROR/AndroidRuntime(1215):     at java.lang.reflect.Method.invokeNative(Native Method)
05-17 17:07:02.139: ERROR/AndroidRuntime(1215):     at java.lang.reflect.Method.invoke(Method.java:521)
05-17 17:07:02.139: ERROR/AndroidRuntime(1215):     at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:782)
05-17 17:07:02.139: ERROR/AndroidRuntime(1215):     at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:540)
05-17 17:07:02.139: ERROR/AndroidRuntime(1215):     at dalvik.system.NativeStart.main(Native Method)
05-17 17:07:02.139: ERROR/AndroidRuntime(1215): Caused by: android.view.InflateException: Binary XML file line #11: Error inflating class java.lang.reflect.Constructor
05-17 17:07:02.139: ERROR/AndroidRuntime(1215):     at android.view.LayoutInflater.createView(LayoutInflater.java:512)
05-17 17:07:02.139: ERROR/AndroidRuntime(1215):     at com.android.internal.policy.impl.PhoneLayoutInflater.onCreateView(PhoneLayoutInflater.java:56)
05-17 17:07:02.139: ERROR/AndroidRuntime(1215):     at android.view.LayoutInflater.createViewFromTag(LayoutInflater.java:562)
05-17 17:07:02.139: ERROR/AndroidRuntime(1215):     at android.view.LayoutInflater.rInflate(LayoutInflater.java:617)
05-17 17:07:02.139: ERROR/AndroidRuntime(1215):     at android.view.LayoutInflater.rInflate(LayoutInflater.java:620)
05-17 17:07:02.139: ERROR/AndroidRuntime(1215):     at android.view.LayoutInflater.inflate(LayoutInflater.java:407)
05-17 17:07:02.139: ERROR/AndroidRuntime(1215):     at android.view.LayoutInflater.inflate(LayoutInflater.java:320)
05-17 17:07:02.139: ERROR/AndroidRuntime(1215):     at android.view.LayoutInflater.inflate(LayoutInflater.java:276)
05-17 17:07:02.139: ERROR/AndroidRuntime(1215):     at com.android.internal.policy.impl.PhoneWindow.setContentView(PhoneWindow.java:309)
05-17 17:07:02.139: ERROR/AndroidRuntime(1215):     at android.app.Dialog.setContentView(Dialog.java:400)
05-17 17:07:02.139: ERROR/AndroidRuntime(1215):     at orange.android.myw.LoginDialog.init(LoginDialog.java:78)
05-17 17:07:02.139: ERROR/AndroidRuntime(1215):     at orange.android.myw.LoginDialog.<init>(LoginDialog.java:72)
05-17 17:07:02.139: ERROR/AndroidRuntime(1215):     at orange.android.vpn.StartUltimate.onCreate(StartUltimate.java:129)
 05-17 17:07:02.139: ERROR/AndroidRuntime(1215):     at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1123)
 05-17 17:07:02.139: ERROR/AndroidRuntime(1215):     at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2231)
05-17 17:07:02.139: ERROR/AndroidRuntime(1215):     ... 11 more
05-17 17:07:02.139: ERROR/AndroidRuntime(1215): Caused by: java.lang.reflect.InvocationTargetException
05-17 17:07:02.139: ERROR/AndroidRuntime(1215):     at android.widget.ImageView.<init>(ImageView.java:103)
05-17 17:07:02.139: ERROR/AndroidRuntime(1215):     at java.lang.reflect.Constructor.constructNative(Native Method)
05-17 17:07:02.139: ERROR/AndroidRuntime(1215):     at java.lang.reflect.Constructor.newInstance(Constructor.java:446)
05-17 17:07:02.139: ERROR/AndroidRuntime(1215):     at android.view.LayoutInflater.createView(LayoutInflater.java:499)
05-17 17:07:02.139: ERROR/AndroidRuntime(1215):     ... 25 more
05-17 17:07:02.139: ERROR/AndroidRuntime(1215): Caused by: android.content.res.Resources$NotFoundException: File res/drawable/scrollbar_handle_vertical.9.png from drawable resource ID #0x7f020005
05-17 17:07:02.139: ERROR/AndroidRuntime(1215):     at android.content.res.Resources.loadDrawable(Resources.java:1641)
05-17 17:07:02.139: ERROR/AndroidRuntime(1215):     at android.content.res.TypedArray.getDrawable(TypedArray.java:548)
05-17 17:07:02.139: ERROR/AndroidRuntime(1215):     at android.view.View.<init>(View.java:1725)
05-17 17:07:02.139: ERROR/AndroidRuntime(1215):     at android.widget.ImageView.<init>(ImageView.java:107)
05-17 17:07:02.139: ERROR/AndroidRuntime(1215):     ... 29 more
05-17 17:07:02.139: ERROR/AndroidRuntime(1215): Caused by: java.io.FileNotFoundException: res/drawable/scrollbar_handle_vertical.9.png
05-17 17:07:02.139: ERROR/AndroidRuntime(1215):     at android.content.res.AssetManager.openNonAssetNative(Native Method)
05-17 17:07:02.139: ERROR/AndroidRuntime(1215):     at android.content.res.AssetManager.openNonAsset(AssetManager.java:392)
05-17 17:07:02.139: ERROR/AndroidRuntime(1215):     at android.content.res.Resources.loadDrawable(Resources.java:1634)
05-17 17:07:02.139: ERROR/AndroidRuntime(1215):     ... 32 more

Error points to setContentView() line in the LoginDialog class.
Can anyone tell what is stopping it to show up in 1.5.

Thanks


问:
Rundeck - User Group Source Plugins - Java Plugin Type
I want to understand the use case/usage of "User Group Source Plugins - Java Plugin Type"

1) can I use the plugin's returned roles/groups in authorization policies(/etc/rundeck/myadmin.aclpolicy)

2) what is the property and its value of this plugin, I should mention here?
framework.plugin.UserGroupSource.[your_plugin_name].[property]=value
In below case, framework.plugin.UserGroupSource.example-user-group-source-plugin.[property]=value

3) Can I connect to a RDBMS and get the roles from DB using java class constuctor

package example;

```<code>@Plugin(name = "example-user-group-source-plugin",service= ServiceNameConstants.UserGroupSource)
public class ExampleUserGroupSourcePlugin implements UserGroupSourcePlugin {
    List<String> groups = new ArrayList<>();

    public ExampleUserGroupSourcePlugin() {
        groups.add("RUNDECK_USER"); //This group would get added to all users
        //TODO: DBConnect code to get roles from RDBMS
    }
    @Override
    public List<String> getGroups(final String username, final Map<String, Object> config) {
        //some code
        return groups;
    }
}```

```

答:
Yes, the ACL definition can take the roles defined in your plugin. In the same way which LDAP roles for example.

What you define in your code as you see here (maybe the documentation needs some update to specify that).

Theoretically yes, using the right way to connect to DB like this.

Body:
I want to understand the use case/usage of "User Group Source Plugins - Java Plugin Type"

1) can I use the plugin's returned roles/groups in authorization policies(/etc/rundeck/myadmin.aclpolicy)

2) what is the property and its value of this plugin, I should mention here?
framework.plugin.UserGroupSource.[your_plugin_name].[property]=value
In below case, framework.plugin.UserGroupSource.example-user-group-source-plugin.[property]=value

3) Can I connect to a RDBMS and get the roles from DB using java class constuctor

package example;

@Plugin(name = "example-user-group-source-plugin",service= ServiceNameConstants.UserGroupSource)
public class ExampleUserGroupSourcePlugin implements UserGroupSourcePlugin {
    List<String> groups = new ArrayList<>();

    public ExampleUserGroupSourcePlugin() {
        groups.add("RUNDECK_USER"); //This group would get added to all users
        //TODO: DBConnect code to get roles from RDBMS
    }
    @Override
    public List<String> getGroups(final String username, final Map<String, Object> config) {
        //some code
        return groups;
    }
}```


问:
WPF - How can I create menu and submenus using binding
I am trying to create a dynamic menu using binding. I my viewmodel I have a list of objects which contains an header and a command. However, it is not working. I think the problem is in the data template. See my code below:

```<code><Menu Background="{x:Null}" Grid.Row="0" Grid.Column="1" Panel.ZIndex="2" Width="865" Height="85" HorizontalAlignment="Left" ItemsSource="{Binding Path=MenuItems}">

        <Menu.ItemTemplate>
            <HierarchicalDataTemplate DataType="MenuItemViewModel" ItemsSource="{Binding Path=MenuItems}">
                <MenuItem Header="{Binding Header}" Style="{DynamicResource MenuItemStyle1}" ItemsSource="{Binding Path=MenuItems}" Padding="10,12,10,0" Height="44.1" Margin="30,0,0,0" FontWeight="Bold">
                    <MenuItem.ItemsPanel>
                        <ItemsPanelTemplate>
                            <VirtualizingStackPanel Orientation="Horizontal"/>
                        </ItemsPanelTemplate>
                    </MenuItem.ItemsPanel>
                </MenuItem>
                <HierarchicalDataTemplate.ItemTemplate>
                    <DataTemplate>
                        <MenuItem Header="{Binding Header}" Style="{DynamicResource MenuItemStyle1}" Padding="0,8,0,0" Height="38">
                        </MenuItem>
                    </DataTemplate>
                </HierarchicalDataTemplate.ItemTemplate>
            </HierarchicalDataTemplate>
        </Menu.ItemTemplate>
    </Menu>
</code>```

The result only shows the first menu. The submenus are not shown but they are there since the menus which have children, the arrow is print after menu header.

Could anyone find something wrong on the binding? Or any suggestion?

Just for information, MenuItems is a list of MenuItemViewModel objects which has an header and a list of MenuItemViewModel objects (submenus) called MenuItems too.

答:
If like me you are keen to keep UI constructs in the XAML code, after some difficulty, I have worked a nice way of binding custom-typed collections to create menu items.

In XAML:

```<code><Menu DockPanel.Dock="Top">
    <MenuItem Header="SomeHeaderName" ItemsSource="{Binding Path=MyCollection}">
        <MenuItem.ItemsContainerStyle>
            <Setter Property="Header" Value="{Binding Path=SomeRelevantTextProperty}"/>
            <EventSetter Event="Click" Handler="SomeMenuItemClickEventHandler"/>
        </MenuItem.ItemsContainerStyle>
    </MenuItem>
</Menu>
</code>```

In code-behind:

```<code>ObservableCollection<MyClass> MyCollection;

private void SomeMenuItemClickEventHandler(object sender, RoutedEventArgs e)
{
    MenuItem menuItem = sender as MenuItem;
    MyClass myClass = menuItem.DataContext as MyClass;
    // do something useful!
}
</code>```

```<code>public class MyClass
{
    public string SomeRelevantTextProperty { get; }
}
</code>```

Body:
I am trying to create a dynamic menu using binding. I my viewmodel I have a list of objects which contains an header and a command. However, it is not working. I think the problem is in the data template. See my code below:

<Menu Background="{x:Null}" Grid.Row="0" Grid.Column="1" Panel.ZIndex="2" Width="865" Height="85" HorizontalAlignment="Left" ItemsSource="{Binding Path=MenuItems}">

        <Menu.ItemTemplate>
            <HierarchicalDataTemplate DataType="MenuItemViewModel" ItemsSource="{Binding Path=MenuItems}">
                <MenuItem Header="{Binding Header}" Style="{DynamicResource MenuItemStyle1}" ItemsSource="{Binding Path=MenuItems}" Padding="10,12,10,0" Height="44.1" Margin="30,0,0,0" FontWeight="Bold">
                    <MenuItem.ItemsPanel>
                        <ItemsPanelTemplate>
                            <VirtualizingStackPanel Orientation="Horizontal"/>
                        </ItemsPanelTemplate>
                    </MenuItem.ItemsPanel>
                </MenuItem>
                <HierarchicalDataTemplate.ItemTemplate>
                    <DataTemplate>
                        <MenuItem Header="{Binding Header}" Style="{DynamicResource MenuItemStyle1}" Padding="0,8,0,0" Height="38">
                        </MenuItem>
                    </DataTemplate>
                </HierarchicalDataTemplate.ItemTemplate>
            </HierarchicalDataTemplate>
        </Menu.ItemTemplate>
    </Menu>

The result only shows the first menu. The submenus are not shown but they are there since the menus which have children, the arrow is print after menu header.

Could anyone find something wrong on the binding? Or any suggestion?

Just for information, MenuItems is a list of MenuItemViewModel objects which has an header and a list of MenuItemViewModel objects (submenus) called MenuItems too.

Body:
If like me you are keen to keep UI constructs in the XAML code, after some difficulty, I have worked a nice way of binding custom-typed collections to create menu items.

In XAML:

<Menu DockPanel.Dock="Top">
    <MenuItem Header="SomeHeaderName" ItemsSource="{Binding Path=MyCollection}">
        <MenuItem.ItemsContainerStyle>
            <Setter Property="Header" Value="{Binding Path=SomeRelevantTextProperty}"/>
            <EventSetter Event="Click" Handler="SomeMenuItemClickEventHandler"/>
        </MenuItem.ItemsContainerStyle>
    </MenuItem>
</Menu>

In code-behind:

ObservableCollection<MyClass> MyCollection;

private void SomeMenuItemClickEventHandler(object sender, RoutedEventArgs e)
{
    MenuItem menuItem = sender as MenuItem;
    MyClass myClass = menuItem.DataContext as MyClass;
    // do something useful!
}

public class MyClass
{
    public string SomeRelevantTextProperty { get; }
}


问:
How to keep the hover state with Highcharts
Currently it is possible for me to manually trigger hover event of highcharts like below code to show tooltip and highlight the series.

```<code>chart.series[0].points[2].onMouseOver()
</code>```

However the state can be easily changed after moving the mouse.Is there a way for me to keep the state?

答:
If you want to keep your tooltip visible when mouse pointer is out you need to disabled tooltip.hide functionality.

```<code>Highcharts.Tooltip.prototype.hide = function() {};
</code>```

and highligt point again after mouse out:

```<code>    events: {
      mouseOut() {
        let series = this;

        series.points[2].onMouseOver();
      }
    }
</code>```

Demo: https://jsfiddle.net/BlackLabel/xjzc25aL/

Body:
Currently it is possible for me to manually trigger hover event of highcharts like below code to show tooltip and highlight the series.

chart.series[0].points[2].onMouseOver()

However the state can be easily changed after moving the mouse.Is there a way for me to keep the state?

Body:
If you want to keep your tooltip visible when mouse pointer is out you need to disabled tooltip.hide functionality.

Highcharts.Tooltip.prototype.hide = function() {};

and highligt point again after mouse out:

    events: {
      mouseOut() {
        let series = this;

        series.points[2].onMouseOver();
      }
    }

Demo: https://jsfiddle.net/BlackLabel/xjzc25aL/


问:
Why is there no std::stou?
C++11 added some new string conversion functions:

http://en.cppreference.com/w/cpp/string/basic_string/stoul

It includes stoi (string to int), stol (string to long), stoll (string to long long), stoul (string to unsigned long), stoull (string to unsigned long long). Notable in its absence is a stou (string to unsigned) function. Is there some reason it is not needed but all of the others are?

related: No "sto{short, unsigned short}" functions in C++11?

答:
```<code>unsigned long ulval = std::stoul(buf);
unsigned long mask = ~0xffffffffl;
unsigned int uival;
if( (ulval & mask) == 0 )
    uival = (unsigned int)ulval;
else {
    ...range error...
}
</code>```

Using masks to do this with the expected value size in bits expressed in the mask, will make this work for 64-bit longs vs 32-bit ints, but also for 32-bit longs vs 32-bit ints.

In the case of 64-bit longs, ~0xffffffffl will become 0xffffffff00000000 and will thus see if any of the top 32 bits are set.  With 32-bit longs, it ~0xffffffffl becomes 0x00000000 and the mask check will always be zero.

Title: Why is there no std::stou?

Body:
unsigned long ulval = std::stoul(buf);
unsigned long mask = ~0xffffffffl;
unsigned int uival;
if( (ulval & mask) == 0 )
    uival = (unsigned int)ulval;
else {
    ...range error...
}

Using masks to do this with the expected value size in bits expressed in the mask, will make this work for 64-bit longs vs 32-bit ints, but also for 32-bit longs vs 32-bit ints.

In the case of 64-bit longs, ~0xffffffffl will become 0xffffffff00000000 and will thus see if any of the top 32 bits are set.  With 32-bit longs, it ~0xffffffffl becomes 0x00000000 and the mask check will always be zero.


问:
TYPO3: SQL error: 'Incorrect integer value: '' for column 'sys_language_uid' at row 1'
I have newly setup TYPO3, but when I try to add/save content, it gives me this error:

SQL error: 'Incorrect integer value: '' for column 'sys_language_uid'
  at row 1

答:
In latest TYPO3 Versions you have to add this in LocalConfiguration.php</p>

```<code>'setDBinit' => 'SET SESSION sql_mode = \'NO_ENGINE_SUBSTITUTION\';',
</code>```

Body:
In latest TYPO3 Versions you have to add this in LocalConfiguration.php

'setDBinit' => 'SET SESSION sql_mode = \'NO_ENGINE_SUBSTITUTION\';',


问:
Swift perform action when become first responder
Is there a default method that is called when a UITextField or similar becomes the first responder, in order to have actions occur at that point?</p>

答:
The apple documentation says this in its first step

Before becoming the first responder, the text field calls its delegate’s textFieldShouldBeginEditing(_:) method. Use that method to allow or prevent the editing of the text field’s contents.

UITextFieldDelegate:
https://developer.apple.com/documentation/uikit/uitextfielddelegate

UITextViewDelegate:
https://developer.apple.com/documentation/uikit/uitextviewdelegate

How to implement UITextFieldDelegate


问:
Making the configuration available to all classes
I'm writing a small web server, and it takes a configuration file with all sorts of different options: how many threads to run, which class deals which each file extension, which file to display by default and so on and so forth. To represent this, I'm parsing the config file into a Configuration object which contains all these settings, and the main class holds this object.

However, the config data is required on almost every level of the server - classes within classes within classes...

My question is, what is the best practice to use here? Should I give the config as a parameter for many many classes and pass it back and forth? Should I make it a singleton? Is there another solution I don't see?

答: I definitively would make the configuration holder class a Singleton! I's the classical use case for a Singleton instance. </p>