问:
Jest - Testing modals in React gives error
I am using react-test-renderer with Jest to test react components. But if I test a react-mui modal dialog like this:

```<code>describe('Dashboard', function () {
  let dashboard;
  beforeEach(async () => {
    testRenderer = TestRenderer.create(<MemoryRouter><Route component={Dashboard} /></MemoryRouter>);
    dashboard = testRenderer.root.findByType(Dashboard);
    await waitForExpect(() => expect(dashboard.instance.state.hasLoaded).toBeTruthy());
  });

  it('opens dialog on clicking the new class', async () => {
    const button = testRenderer.root.findByType(Button);
    expect(dashboard.instance.state.showDialog).toBeFalsy();
    button.props.onClick();
    expect(dashboard.instance.state.showDialog).toBeTruthy();
  });
});
</code>```

But, then I get an error:

Error: Failed: "Error: Uncaught 'Warning: An invalid container has
  been provided. This may indicate that another renderer is being used
  in addition to the test renderer. (For example, ReactDOM.createPortal
  inside of a ReactTestRenderer tree.) This is not supported.%s'

How should I test then react portals to make this test work?

答:
Based on Oliver's answer, but for TypeScript users:</p>
```<code>describe("Tests", () => {
  const oldCreatePortal = ReactDOM.createPortal;
  beforeAll(() => {
    ReactDOM.createPortal = (node: ReactNode): ReactPortal =>
      node as ReactPortal;
  });

  afterAll(() => {
    ReactDOM.createPortal = oldCreatePortal;
  });
});
</code>```

Body:
I am using react-test-renderer with Jest to test react components. But if I test a react-mui modal dialog like this:

describe('Dashboard', function () {
  let dashboard;
  beforeEach(async () => {
    testRenderer = TestRenderer.create(<MemoryRouter><Route component={Dashboard} /></MemoryRouter>);
    dashboard = testRenderer.root.findByType(Dashboard);
    await waitForExpect(() => expect(dashboard.instance.state.hasLoaded).toBeTruthy());
  });

  it('opens dialog on clicking the new class', async () => {
    const button = testRenderer.root.findByType(Button);
    expect(dashboard.instance.state.showDialog).toBeFalsy();
    button.props.onClick();
    expect(dashboard.instance.state.showDialog).toBeTruthy();
  });
});

But, then I get an error:

Error: Failed: "Error: Uncaught 'Warning: An invalid container has
  been provided. This may indicate that another renderer is being used
  in addition to the test renderer. (For example, ReactDOM.createPortal
  inside of a ReactTestRenderer tree.) This is not supported.%s'

How should I test then react portals to make this test work?

Body:
Based on Oliver's answer, but for TypeScript users:

describe("Tests", () => {
  const oldCreatePortal = ReactDOM.createPortal;
  beforeAll(() => {
    ReactDOM.createPortal = (node: ReactNode): ReactPortal =>
      node as ReactPortal;
  });

  afterAll(() => {
    ReactDOM.createPortal = oldCreatePortal;
  });
});


来源: stackexchange

问:
TailwindCss's mobile breakpoints do not work
I am building a custom navbar in Gatsby using TailwindCss for styling. For reference I am following a tutorial on YouTube which's code can be found here.

When I use the mobile breakpoints as prefix like in the example below only the div saying "mobile" works as it should be:

Layout.js

```<code><nav>
  <div className={"flex"}>
    <div className={"hidden md:flex"}>desktop</div>
    <div className={"md:hidden"}>mobile</div>
  </div>
</nav>
</code>```

tailwind.config.js

```<code>module.exports = {
  content: ["./public/**/*.html", "./src/**/*.{js,jsx,ts,tsx,vue}"],
  darkMode: "class",
  theme: {},
  plugins: []
};
</code>```

styles/global.css

```<code>@tailwind base;
@tailwind components;
@tailwind screens;
@tailwind utilities;
</code>```

The output "desktop" should be shown when the text "mobile" vanishes but for some reason it doesn't. Am I doing something wrong or is there a problem with Tailwind?

EDIT: Reproduction example here

答:
The problem seems to be in your global.css file.

You should not add the @tailwind screens;. Since you are using the latest TailwindCSS, @tailwind screens; was deprecated since 2.2 in JIT mode and it's now named: @tailwind variants;

Tailwind Changelog

As of v2.2, the @tailwind screens directive has been renamed to
@tailwind variants, since it is now the injection point for all
variants, not just responsive variants.

Some more info on when the @tailwind variants; should be added:

The @tailwind variants feature is considered an advanced escape hatch
and we recommend omitting it by default. You should only use it if
your project won't work properly without it, which is only ever really
true if you are introducing Tailwind to a legacy system with a very
fragile existing CSS codebase that has styles that absolutely need to
be at the very end of the stylesheet for things to work.

Also, according to the Tailwind installation with Gatsby instructions You should not add the @tailwind variants;

That being said, you should not need it in this case so, by just removing it in you global.css file will fix the issue.

Your new global.css file should be:

```<code>@tailwind base;
@tailwind components;
@tailwind utilities;
</code>```

Here is a working CodeSandbox

ContentLicense: CC BY-SA 4.0

Body:
I am building a custom navbar in Gatsby using TailwindCss for styling. For reference I am following a tutorial on YouTube which's code can be found here.

When I use the mobile breakpoints as prefix like in the example below only the div saying "mobile" works as it should be:

Layout.js

desktop

mobile

tailwind.config.js

module.exports = {
  content: ["./public/**/*.html", "./src/**/*.{js,jsx,ts,tsx,vue}"],
  darkMode: "class",
  theme: {},
  plugins: []
};

styles/global.css

@tailwind base;
@tailwind components;
@tailwind screens;
@tailwind utilities;

The output "desktop" should be shown when the text "mobile" vanishes but for some reason it doesn't. Am I doing something wrong or is there a problem with Tailwind?

EDIT: Reproduction example here

Body:
The problem seems to be in your global.css file.

You should not add the @tailwind screens;. Since you are using the latest TailwindCSS, @tailwind screens; was deprecated since 2.2 in JIT mode and it's now named: @tailwind variants;

Tailwind Changelog

As of v2.2, the @tailwind screens directive has been renamed to
@tailwind variants, since it is now the injection point for all
variants, not just responsive variants.

Some more info on when the @tailwind variants; should be added:

The @tailwind variants feature is considered an advanced escape hatch
and we recommend omitting it by default. You should only use it if
your project won't work properly without it, which is only ever really
true if you are introducing Tailwind to a legacy system with a very
fragile existing CSS codebase that has styles that absolutely need to
be at the very end of the stylesheet for things to work.

Also, according to the Tailwind installation with Gatsby instructions You should not add the @tailwind variants;

That being said, you should not need it in this case so, by just removing it in you global.css file will fix the issue.

Your new global.css file should be:

@tailwind base;
@tailwind components;
@tailwind utilities;

Here is a working CodeSandbox


问:
React Native Debugger "Unsupported DevTools backend version"
When I try to debug my app with React Native Debugger I got that error: "

error from react native debugger

then I do that instruction. install react devtool, and nothin happen.
I think, maybe, I have some error when installing the package, so I run react devtools and see that current version 4.23.0

react-devtools version

so anybody have any idea how I can fix that problem?

答:
I "npm install"ed 'react-devtools' and 'react-devtools-core' and set them to the same version

```<code>   "react-devtools": "~4.14.0",
   "react-devtools-core": "~4.14.0",
</code>```

and re-installed everything by deleting package-lock.json and node_modules

then ran npm install and it worked

I think the problem was those packages not being the same version

Body:
I "npm install"ed 'react-devtools' and 'react-devtools-core' and set them to the same version

   "react-devtools": "~4.14.0",
   "react-devtools-core": "~4.14.0",

and re-installed everything by deleting package-lock.json and node_modules

then ran npm install and it worked

I think the problem was those packages not being the same version


问:
Condition is not verifying the validity of the input
I'm doing an assignment that asks a user to input a student name, and then quiz scores until the user chooses to stop. It then calculates the total score and the average of all those scores and outputs them to the screen.

We are moving on to the subject of inheritance and now we are requested to make a class called MonitoredStudent which extends Student. The point of the MonitoredStudent class is to check if the average is above a user inputted average and display whether the student is off academic probation.

I have got most of the program written and when I input just one score (such as 71, when the average I set is 70) it is still displaying that I am on academic probation, even though the one quiz score is above the average I set of 70.

The main issue is that no matter what integer is set for the minimum passing average, I always get a return of false.

I added the "return false" statement in the isOffProbation method as when I add an if-else statement to check if the averageScore (from the Student class) is less than or equal to minPassingAvg eclipse tells me that the method needs a return type of boolean.

```<code>public class MonitoredStudent extends Student {

    int minPassingAvg;

    public MonitoredStudent(){
        super();
        minPassingAvg = 0;
    }

    public MonitoredStudent(String name, int minPassingAvg) {
        super(name);
        this.minPassingAvg = minPassingAvg;
    }

    public int getMinPassingAvg() {
        return minPassingAvg;
    }

    public void setMinPassingAvg(int minPassingAvg) {
        this.minPassingAvg = minPassingAvg;
    }

    boolean isOffProbation() {
        if(getAverageScore() >= minPassingAvg)
            return true;
        return false;
    }
}
</code>```

This is the Student super class:

```<code>public class Student{

   private String name;

   private double totalScore;

   private int quizCount;

   public Student(){
      name = "";
      totalScore = 0;
      quizCount = 0;
   }

   public Student(String n){
      name = n;
      totalScore = 0;
      quizCount = 0;
   }

   public void setName(String aName){
      name = aName;
   }

   public String getName(){
      return name;
   }

   public void addQuiz(int score){
      if(score >= 0 && score <= 100){
         totalScore = totalScore + score;
         quizCount = quizCount + 1;
      }else{
         System.out.println("Score must be between 0 and 100, inclusive");
      }
   }

   public double getTotalScore(){
      return totalScore;
   }

   public double getAverageScore(){
      return totalScore / quizCount;
   }
}
</code>```

This is the main method:

```<code>import java.util.Scanner;

public class MonitoredStudentTester{

    public static void main(String[] args) {
        Scanner scan = new Scanner(System.in);
        MonitoredStudent monStu = new MonitoredStudent();
        String repeat = "n";
        int currentScore = 0;
        int minPassAv;

        System.out.println("Enter the student's name:");
        String stuName = scan.next();
        Student sName = new Student(stuName);
        System.out.println("What is the minimum passing average score: ");
        minPassAv = scan.nextInt();

        Student stu = new Student();
        do {
            System.out.println("Enter a quiz score: ");
            currentScore = scan.nextInt();

            stu.addQuiz(currentScore);
            monStu.setMinPassingAvg(currentScore);

            System.out.println("Would you like to enter any more scores?: (Y for yes, N for no)");
            scan.nextLine();
            repeat = scan.nextLine();

        }while(repeat.equalsIgnoreCase("y"));

        String studName = stu.getName();
        double totalScore = stu.getTotalScore();
        double avgScore = stu.getAverageScore();
        boolean offProb = monStu.isOffProbation();

        System.out.println(studName + "'s Total Score is: " + totalScore);
        System.out.println(studName + "'s Average Score is: " + avgScore);
        System.out.println("Is " + studName + "off academic probation?: " + offProb);

    }
}
</code>```

答:
You main class should be something like this.

```<code>public class MonitoredStudentTester {

  public static void main(String[] args) {
    Scanner scan = new Scanner(System.in);
    MonitoredStudent monStu = new MonitoredStudent();
    String repeat = "n";
    int currentScore = 0;
    int minPassAv;

    System.out.println("Enter the student's name:");
    monStu.setName(scan.next());
    System.out.println("What is the minimum passing average score: ");
    minPassAv = scan.nextInt();

    do {
      System.out.println("Enter a quiz score: ");
      currentScore = scan.nextInt();

      monStu.addQuiz(currentScore);
      monStu.setMinPassingAvg(minPassAv);

      System.out.println("Would you like to enter any more scores?: (Y for yes, N for no)");
      scan.nextLine();
      repeat = scan.nextLine();

    } while (repeat.equalsIgnoreCase("y"));

    String studName = monStu.getName();
    double totalScore = monStu.getTotalScore();
    double avgScore = monStu.getAverageScore();
    boolean offProb = monStu.isOffProbation();

    System.out.println(studName + "'s Total Score is: " + totalScore);
    System.out.println(studName + "'s Average Score is: " + avgScore);
    System.out.println("Is " + studName + "off academic probation?: " + offProb);
  }
}
</code>```

When using inheritance you just need to create an object of child class.

Body:
I'm doing an assignment that asks a user to input a student name, and then quiz scores until the user chooses to stop. It then calculates the total score and the average of all those scores and outputs them to the screen.

We are moving on to the subject of inheritance and now we are requested to make a class called MonitoredStudent which extends Student. The point of the MonitoredStudent class is to check if the average is above a user inputted average and display whether the student is off academic probation.

I have got most of the program written and when I input just one score (such as 71, when the average I set is 70) it is still displaying that I am on academic probation, even though the one quiz score is above the average I set of 70.

The main issue is that no matter what integer is set for the minimum passing average, I always get a return of false.

I added the "return false" statement in the isOffProbation method as when I add an if-else statement to check if the averageScore (from the Student class) is less than or equal to minPassingAvg eclipse tells me that the method needs a return type of boolean.

public class MonitoredStudent extends Student {

    int minPassingAvg;

    public MonitoredStudent(){
        super();
        minPassingAvg = 0;
    }

    public MonitoredStudent(String name, int minPassingAvg) {
        super(name);
        this.minPassingAvg = minPassingAvg;
    }

    public int getMinPassingAvg() {
        return minPassingAvg;
    }

    public void setMinPassingAvg(int minPassingAvg) {
        this.minPassingAvg = minPassingAvg;
    }

    boolean isOffProbation() {
        if(getAverageScore() >= minPassingAvg)
            return true;
        return false;
    }
}

This is the Student super class:

public class Student{

   private String name;

   private double totalScore;

   private int quizCount;

   public Student(){
      name = "";
      totalScore = 0;
      quizCount = 0;
   }

   public Student(String n){
      name = n;
      totalScore = 0;
      quizCount = 0;
   }

   public void setName(String aName){
      name = aName;
   }

   public String getName(){
      return name;
   }

   public void addQuiz(int score){
      if(score >= 0 && score <= 100){
         totalScore = totalScore + score;
         quizCount = quizCount + 1;
      }else{
         System.out.println("Score must be between 0 and 100, inclusive");
      }
   }

   public double getTotalScore(){
      return totalScore;
   }

   public double getAverageScore(){
      return totalScore / quizCount;
   }
}

This is the main method:

import java.util.Scanner;

public class MonitoredStudentTester{

    public static void main(String[] args) {
        Scanner scan = new Scanner(System.in);
        MonitoredStudent monStu = new MonitoredStudent();
        String repeat = "n";
        int currentScore = 0;
        int minPassAv;

        System.out.println("Enter the student's name:");
        String stuName = scan.next();
        Student sName = new Student(stuName);
        System.out.println("What is the minimum passing average score: ");
        minPassAv = scan.nextInt();

        Student stu = new Student();
        do {
            System.out.println("Enter a quiz score: ");
            currentScore = scan.nextInt();

            stu.addQuiz(currentScore);
            monStu.setMinPassingAvg(currentScore);

            System.out.println("Would you like to enter any more scores?: (Y for yes, N for no)");
            scan.nextLine();
            repeat = scan.nextLine();

        }while(repeat.equalsIgnoreCase("y"));

        String studName = stu.getName();
        double totalScore = stu.getTotalScore();
        double avgScore = stu.getAverageScore();
        boolean offProb = monStu.isOffProbation();

        System.out.println(studName + "'s Total Score is: " + totalScore);
        System.out.println(studName + "'s Average Score is: " + avgScore);
        System.out.println("Is " + studName + "off academic probation?: " + offProb);

    }
}

Body:
You main class should be something like this.

public class MonitoredStudentTester {

  public static void main(String[] args) {
    Scanner scan = new Scanner(System.in);
    MonitoredStudent monStu = new MonitoredStudent();
    String repeat = "n";
    int currentScore = 0;
    int minPassAv;

    System.out.println("Enter the student's name:");
    monStu.setName(scan.next());
    System.out.println("What is the minimum passing average score: ");
    minPassAv = scan.nextInt();

    do {
      System.out.println("Enter a quiz score: ");
      currentScore = scan.nextInt();

      monStu.addQuiz(currentScore);
      monStu.setMinPassingAvg(minPassAv);

      System.out.println("Would you like to enter any more scores?: (Y for yes, N for no)");
      scan.nextLine();
      repeat = scan.nextLine();

    } while (repeat.equalsIgnoreCase("y"));

    String studName = monStu.getName();
    double totalScore = monStu.getTotalScore();
    double avgScore = monStu.getAverageScore();
    boolean offProb = monStu.isOffProbation();

    System.out.println(studName + "'s Total Score is: " + totalScore);
    System.out.println(studName + "'s Average Score is: " + avgScore);
    System.out.println("Is " + studName + "off academic probation?: " + offProb);
  }
}

When using inheritance you just need to create an object of child class.


问:
Azure Durable Functions - where's the HostBuilder equivalent?
I'm using an Azure Durable Function to orchestrate other functions, currently contained in the same project. I want to configure services and logging for those orchestrated functions. How can I do that?

Here is some more detail:

In a "normal" Azure Function I have a Program.cs and a Main method with the following code that sets up the environment for the function execution:

```<code>var host = new HostBuilder()
    .ConfigureFunctionsWorkerDefaults()
    .ConfigureLogging(loggingBuilder => { loggingBuilder.SetMinimumLevel(LogLevel.Trace); })... etc. pp.
</code>```

Using the HostBuilder I can add additional logging providers, add caching services etc. Those services are then injected via the constructor of the Azure Function.

Now in comparison when creating a Durable Function project via the VS Code "Durable Function Orchestration" template there is no Program.cs, no HostBuilder and no constructor. There are just some static methods representing the orchestrator and an orchestrated function.

As there is no out-of-the-box HostBuilder in the "Durable Function Orchestration" template - how does the HostBuilder equivalent look like for Durable Functions? Whats the pattern or convention here? Do I write it myself? Or is there some instance floating around or initialization I can hook into? Or should orchestrated functions be put into separate Azure Function projects where I can make use of the HostBuilder?

Any hints are appreciated.

答:
So the solution is to use a FunctionsStartup class as outlined here. This should make dependency injection work, also for Durable Functions.

For me it did not work immediately though and it took a while to figure out why. What I tried is adding an additional parameter (myService) to the static methods like so:

```<code>[FunctionName("DurableFunctionsOrchestrationCSharp1_Hello")]
public static string SayHello([ActivityTrigger] string name, ILogger log, IMyService myService)
{
    log.LogInformation($"Saying hello to {name}.");
    return $"Hello {name}!";
}
</code>```

I also added the startup class according to the documentation that is supposed to provide the implementation for IMyService.

This did never work. The error I got is this:

Microsoft.Azure.WebJobs.Host: Error indexing method
'DurableFunctionsOrchestrationCSharp1_Hello'.
Microsoft.Azure.WebJobs.Host: Cannot bind parameter 'myService' to
type IMyService. Make sure the parameter Type is supported by the
binding. If you're using binding extensions (e.g. Azure Storage,
ServiceBus, Timers, etc.) make sure you've called the registration
method for the extension(s) in your startup code (e.g.
builder.AddAzureStorage(), builder.AddServiceBus(),
builder.AddTimers(), etc.).

This error message suggests that it should work while in reality it never does.

The solution was to get rid of the static methods and use classes with constructors. Constructor injection WORKS.

The working class looks like this:

```<code>public class Activities
{
    IMyService _service;
    public Activities(IMyService service)
    {
        _service = service;
    }

    [FunctionName("DurableFunctionsOrchestrationCSharp1_Hello")]
    public string SayHello([ActivityTrigger] string name, ILogger log)
    {
        log.LogInformation($"Saying hello to {name} {_service.GetType()}.");

        return $"Hello {name}!";
    }
}
</code>```

Note that I moved the function here and made it non-static.

The constructor is properly invoked, given a IMyService instance created by the Startup class and then the function is executed.

The minimal startup class I used for testing looks like this:

```<code>using Microsoft.Azure.Functions.Extensions.DependencyInjection;
using Microsoft.Extensions.DependencyInjection;

[assembly: FunctionsStartup(typeof(MyNamespace.Startup))]

namespace MyNamespace
{
    public interface IMyService
    {
    }
    public class MyService : IMyService
    {
    }

    public class Startup : FunctionsStartup
    {
        public override void Configure(IFunctionsHostBuilder builder)
        {
            builder.Services.AddSingleton<IMyService>((s) => {
                return new MyService();
            });
        }
    }
}
</code>```

So dependency injection works for Durable Functions, if you are injecting into constructors.

Body:
I'm using an Azure Durable Function to orchestrate other functions, currently contained in the same project. I want to configure services and logging for those orchestrated functions. How can I do that?

Here is some more detail:

In a "normal" Azure Function I have a Program.cs and a Main method with the following code that sets up the environment for the function execution:

var host = new HostBuilder()
    .ConfigureFunctionsWorkerDefaults()
    .ConfigureLogging(loggingBuilder => { loggingBuilder.SetMinimumLevel(LogLevel.Trace); })... etc. pp.

Using the HostBuilder I can add additional logging providers, add caching services etc. Those services are then injected via the constructor of the Azure Function.

Now in comparison when creating a Durable Function project via the VS Code "Durable Function Orchestration" template there is no Program.cs, no HostBuilder and no constructor. There are just some static methods representing the orchestrator and an orchestrated function.

As there is no out-of-the-box HostBuilder in the "Durable Function Orchestration" template - how does the HostBuilder equivalent look like for Durable Functions? Whats the pattern or convention here? Do I write it myself? Or is there some instance floating around or initialization I can hook into? Or should orchestrated functions be put into separate Azure Function projects where I can make use of the HostBuilder?

Any hints are appreciated.

Body:
So the solution is to use a FunctionsStartup class as outlined here. This should make dependency injection work, also for Durable Functions.

For me it did not work immediately though and it took a while to figure out why. What I tried is adding an additional parameter (myService) to the static methods like so:

[FunctionName("DurableFunctionsOrchestrationCSharp1_Hello")]
public static string SayHello([ActivityTrigger] string name, ILogger log, IMyService myService)
{
    log.LogInformation($"Saying hello to {name}.");
    return $"Hello {name}!";
}

I also added the startup class according to the documentation that is supposed to provide the implementation for IMyService.

This did never work. The error I got is this:

Microsoft.Azure.WebJobs.Host: Error indexing method
'DurableFunctionsOrchestrationCSharp1_Hello'.
Microsoft.Azure.WebJobs.Host: Cannot bind parameter 'myService' to
type IMyService. Make sure the parameter Type is supported by the
binding. If you're using binding extensions (e.g. Azure Storage,
ServiceBus, Timers, etc.) make sure you've called the registration
method for the extension(s) in your startup code (e.g.
builder.AddAzureStorage(), builder.AddServiceBus(),
builder.AddTimers(), etc.).

This error message suggests that it should work while in reality it never does.

The solution was to get rid of the static methods and use classes with constructors. Constructor injection WORKS.

The working class looks like this:

public class Activities
{
    IMyService _service;
    public Activities(IMyService service)
    {
        _service = service;
    }

    [FunctionName("DurableFunctionsOrchestrationCSharp1_Hello")]
    public string SayHello([ActivityTrigger] string name, ILogger log)
    {
        log.LogInformation($"Saying hello to {name} {_service.GetType()}.");

        return $"Hello {name}!";
    }
}

Note that I moved the function here and made it non-static.

The constructor is properly invoked, given a IMyService instance created by the Startup class and then the function is executed.

The minimal startup class I used for testing looks like this:

using Microsoft.Azure.Functions.Extensions.DependencyInjection;
using Microsoft.Extensions.DependencyInjection;

[assembly: FunctionsStartup(typeof(MyNamespace.Startup))]

namespace MyNamespace
{
    public interface IMyService
    {
    }
    public class MyService : IMyService
    {
    }

    public class Startup : FunctionsStartup
    {
        public override void Configure(IFunctionsHostBuilder builder)
        {
            builder.Services.AddSingleton<IMyService>((s) => {
                return new MyService();
            });
        }
    }
}

So dependency injection works for Durable Functions, if you are injecting into constructors.


问:
std::vector<std::pair<int,std::pair<Bone,std::string> > > not sorting by int?
I have a std::vector<std::pair<int,std::pair<Bone,std::string> > >

I'm trying to sort it with std sort, with the expectation that it is sorted by int, but instead I get 21 errors related to the sort call.

What could be wrong?

Code:

```<code>std::vector<std::pair<int,std::pair<Bone,std::string> > > tempBones;
std::sort(tempBones.begin(),tempBones.end());
</code>```

Errors:

Error  1   error C2784: 'bool std::operator <(const std::basic_string<_Elem,_Traits,_Alloc> &,const _Elem *)' : could not deduce template argument for 'const std::basic_string<_Elem,_Traits,_Alloc> &' from 'const skl::Bone'  c:\Program Files\Microsoft Visual Studio 9.0\VC\include\utility 102

Error  2   error C2784: 'bool std::operator <(const _Elem *,const std::basic_string<_Elem,_Traits,_Alloc> &)' : could not deduce template argument for 'const _Elem *' from 'const skl::Bone'    c:\Program Files\Microsoft Visual Studio 9.0\VC\include\utility 102

Error  3   error C2784: 'bool std::operator <(const std::basic_string<_Elem,_Traits,_Alloc> &,const std::basic_string<_Elem,_Traits,_Alloc> &)' : could not deduce template argument for 'const std::basic_string<_Elem,_Traits,_Alloc> &' from 'const skl::Bone'    c:\Program Files\Microsoft Visual Studio 9.0\VC\include\utility 102

Error  4   error C2784: 'bool std::operator <(const std::_Tree<_Traits> &,const std::_Tree<_Traits> &)' : could not deduce template argument for 'const std::_Tree<_Traits> &' from 'const skl::Bone'    c:\Program Files\Microsoft Visual Studio 9.0\VC\include\utility 102

Error  5   error C2784: 'bool std::operator <(const std::vector<_Ty,_Alloc> &,const std::vector<_Ty,_Alloc> &)' : could not deduce template argument for 'const std::vector<_Ty,_Alloc> &' from 'const skl::Bone'    c:\Program Files\Microsoft Visual Studio 9.0\VC\include\utility 102

Error  6   error C2784: 'bool std::operator <(const std::list<_Ty,_Ax> &,const std::list<_Ty,_Ax> &)' : could not deduce template argument for 'const std::list<_Ty,_Ax> &' from 'const skl::Bone'   c:\Program Files\Microsoft Visual Studio 9.0\VC\include\utility 102

Error  7   error C2784: 'bool std::operator <(const std::reverse_iterator<_RanIt> &,const std::reverse_iterator<_RanIt2> &)' : could not deduce template argument for 'const std::reverse_iterator<_RanIt> &' from 'const skl::Bone' c:\Program Files\Microsoft Visual Studio 9.0\VC\include\utility 102

Error  8   error C2784: 'bool std::operator <(const std::_Revranit<_RanIt,_Base> &,const std::_Revranit<_RanIt2,_Base2> &)' : could not deduce template argument for 'const std::_Revranit<_RanIt,_Base> &' from 'const skl::Bone'   c:\Program Files\Microsoft Visual Studio 9.0\VC\include\utility 102

Error  9   error C2784: 'bool std::operator <(const std::pair<_Ty1,_Ty2> &,const std::pair<_Ty1,_Ty2> &)' : could not deduce template argument for 'const std::pair<_Ty1,_Ty2> &' from 'const skl::Bone' c:\Program Files\Microsoft Visual Studio 9.0\VC\include\utility 102

Error  10  error C2676: binary '<' : 'const skl::Bone' does not define this operator or a conversion to a type acceptable to the predefined operator   c:\Program Files\Microsoft Visual Studio 9.0\VC\include\utility 10

Error  11  error C2784: 'bool std::operator <(const std::basic_string<_Elem,_Traits,_Alloc> &,const _Elem *)' : could not deduce template argument for 'const std::basic_string<_Elem,_Traits,_Alloc> &' from 'const skl::Bone'  c:\Program Files\Microsoft Visual Studio 9.0\VC\include\utility 103

Error  12  error C2784: 'bool std::operator <(const _Elem *,const std::basic_string<_Elem,_Traits,_Alloc> &)' : could not deduce template argument for 'const _Elem *' from 'const skl::Bone'    c:\Program Files\Microsoft Visual Studio 9.0\VC\include\utility 103

Error  13  error C2784: 'bool std::operator <(const std::basic_string<_Elem,_Traits,_Alloc> &,const std::basic_string<_Elem,_Traits,_Alloc> &)' : could not deduce template argument for 'const std::basic_string<_Elem,_Traits,_Alloc> &' from 'const skl::Bone'    c:\Program Files\Microsoft Visual Studio 9.0\VC\include\utility 103

Error  14  error C2784: 'bool std::operator <(const std::_Tree<_Traits> &,const std::_Tree<_Traits> &)' : could not deduce template argument for 'const std::_Tree<_Traits> &' from 'const skl::Bone'    c:\Program Files\Microsoft Visual Studio 9.0\VC\include\utility 103

Error  15  error C2784: 'bool std::operator <(const std::vector<_Ty,_Alloc> &,const std::vector<_Ty,_Alloc> &)' : could not deduce template argument for 'const std::vector<_Ty,_Alloc> &' from 'const skl::Bone'    c:\Program Files\Microsoft Visual Studio 9.0\VC\include\utility 103

Error  16  error C2784: 'bool std::operator <(const std::list<_Ty,_Ax> &,const std::list<_Ty,_Ax> &)' : could not deduce template argument for 'const std::list<_Ty,_Ax> &' from 'const skl::Bone'   c:\Program Files\Microsoft Visual Studio 9.0\VC\include\utility 103

Error  17  error C2784: 'bool std::operator <(const std::reverse_iterator<_RanIt> &,const std::reverse_iterator<_RanIt2> &)' : could not deduce template argument for 'const std::reverse_iterator<_RanIt> &' from 'const skl::Bone' c:\Program Files\Microsoft Visual Studio 9.0\VC\include\utility 103

Error  18  error C2784: 'bool std::operator <(const std::_Revranit<_RanIt,_Base> &,const std::_Revranit<_RanIt2,_Base2> &)' : could not deduce template argument for 'const std::_Revranit<_RanIt,_Base> &' from 'const skl::Bone'   c:\Program Files\Microsoft Visual Studio 9.0\VC\include\utility 103

Error  19  error C2784: 'bool std::operator <(const std::pair<_Ty1,_Ty2> &,const std::pair<_Ty1,_Ty2> &)' : could not deduce template argument for 'const std::pair<_Ty1,_Ty2> &' from 'const skl::Bone' c:\Program Files\Microsoft Visual Studio 9.0\VC\include\utility 103

Error  20  error C2676: binary '<' : 'const skl::Bone' does not define this operator or a conversion to a type acceptable to the predefined operator   c:\Program Files\Microsoft Visual Studio 9.0\VC\include\utility 103

答:
Without seeing the error I can't be sure about this, but one thing to note is that std::pair does not just sort by the first value; it also uses the second value if needed to break ties.  In the context of std::map this isn't an issue because internally the map uses a custom comparator instead of the default operator<, but if you sort pairs naturally the ordering may take the second element into account.

Because of this, if you didn't define operator< for Bone, you will get a compiler error because the template code for pair's operator< will try to use it.  On top of that, you'd get some ferocious compiler errors about it, since the compiler will only report the error after instantiating the templates for sort and pair.

Hope this helps!

ContentLicense: CC BY-SA 3.0

Body:
I have a std::vector<std::pair<int,std::pair<Bone,std::string> > >

I'm trying to sort it with std sort, with the expectation that it is sorted by int, but instead I get 21 errors related to the sort call.

What could be wrong?

Code:

std::vector<std::pair<int,std::pair<Bone,std::string> > > tempBones;
std::sort(tempBones.begin(),tempBones.end());

Errors:

Error  1   error C2784: 'bool std::operator <(const std::basic_string<_Elem,_Traits,_Alloc> &,const _Elem *)' : could not deduce template argument for 'const std::basic_string<_Elem,_Traits,_Alloc> &' from 'const skl::Bone'  c:\Program Files\Microsoft Visual Studio 9.0\VC\include\utility 102

Error  2   error C2784: 'bool std::operator <(const _Elem *,const std::basic_string<_Elem,_Traits,_Alloc> &)' : could not deduce template argument for 'const _Elem *' from 'const skl::Bone'    c:\Program Files\Microsoft Visual Studio 9.0\VC\include\utility 102

Error  3   error C2784: 'bool std::operator <(const std::basic_string<_Elem,_Traits,_Alloc> &,const std::basic_string<_Elem,_Traits,_Alloc> &)' : could not deduce template argument for 'const std::basic_string<_Elem,_Traits,_Alloc> &' from 'const skl::Bone'    c:\Program Files\Microsoft Visual Studio 9.0\VC\include\utility 102

Error  4   error C2784: 'bool std::operator <(const std::_Tree<_Traits> &,const std::_Tree<_Traits> &)' : could not deduce template argument for 'const std::_Tree<_Traits> &' from 'const skl::Bone'    c:\Program Files\Microsoft Visual Studio 9.0\VC\include\utility 102

Error  5   error C2784: 'bool std::operator <(const std::vector<_Ty,_Alloc> &,const std::vector<_Ty,_Alloc> &)' : could not deduce template argument for 'const std::vector<_Ty,_Alloc> &' from 'const skl::Bone'    c:\Program Files\Microsoft Visual Studio 9.0\VC\include\utility 102

Error  6   error C2784: 'bool std::operator <(const std::list<_Ty,_Ax> &,const std::list<_Ty,_Ax> &)' : could not deduce template argument for 'const std::list<_Ty,_Ax> &' from 'const skl::Bone'   c:\Program Files\Microsoft Visual Studio 9.0\VC\include\utility 102

Error  7   error C2784: 'bool std::operator <(const std::reverse_iterator<_RanIt> &,const std::reverse_iterator<_RanIt2> &)' : could not deduce template argument for 'const std::reverse_iterator<_RanIt> &' from 'const skl::Bone' c:\Program Files\Microsoft Visual Studio 9.0\VC\include\utility 102

Error  8   error C2784: 'bool std::operator <(const std::_Revranit<_RanIt,_Base> &,const std::_Revranit<_RanIt2,_Base2> &)' : could not deduce template argument for 'const std::_Revranit<_RanIt,_Base> &' from 'const skl::Bone'   c:\Program Files\Microsoft Visual Studio 9.0\VC\include\utility 102

Error  9   error C2784: 'bool std::operator <(const std::pair<_Ty1,_Ty2> &,const std::pair<_Ty1,_Ty2> &)' : could not deduce template argument for 'const std::pair<_Ty1,_Ty2> &' from 'const skl::Bone' c:\Program Files\Microsoft Visual Studio 9.0\VC\include\utility 102

Error  10  error C2676: binary '<' : 'const skl::Bone' does not define this operator or a conversion to a type acceptable to the predefined operator   c:\Program Files\Microsoft Visual Studio 9.0\VC\include\utility 10

Error  11  error C2784: 'bool std::operator <(const std::basic_string<_Elem,_Traits,_Alloc> &,const _Elem *)' : could not deduce template argument for 'const std::basic_string<_Elem,_Traits,_Alloc> &' from 'const skl::Bone'  c:\Program Files\Microsoft Visual Studio 9.0\VC\include\utility 103

Error  12  error C2784: 'bool std::operator <(const _Elem *,const std::basic_string<_Elem,_Traits,_Alloc> &)' : could not deduce template argument for 'const _Elem *' from 'const skl::Bone'    c:\Program Files\Microsoft Visual Studio 9.0\VC\include\utility 103

Error  13  error C2784: 'bool std::operator <(const std::basic_string<_Elem,_Traits,_Alloc> &,const std::basic_string<_Elem,_Traits,_Alloc> &)' : could not deduce template argument for 'const std::basic_string<_Elem,_Traits,_Alloc> &' from 'const skl::Bone'    c:\Program Files\Microsoft Visual Studio 9.0\VC\include\utility 103

Error  14  error C2784: 'bool std::operator <(const std::_Tree<_Traits> &,const std::_Tree<_Traits> &)' : could not deduce template argument for 'const std::_Tree<_Traits> &' from 'const skl::Bone'    c:\Program Files\Microsoft Visual Studio 9.0\VC\include\utility 103

Error  15  error C2784: 'bool std::operator <(const std::vector<_Ty,_Alloc> &,const std::vector<_Ty,_Alloc> &)' : could not deduce template argument for 'const std::vector<_Ty,_Alloc> &' from 'const skl::Bone'    c:\Program Files\Microsoft Visual Studio 9.0\VC\include\utility 103

Error  16  error C2784: 'bool std::operator <(const std::list<_Ty,_Ax> &,const std::list<_Ty,_Ax> &)' : could not deduce template argument for 'const std::list<_Ty,_Ax> &' from 'const skl::Bone'   c:\Program Files\Microsoft Visual Studio 9.0\VC\include\utility 103

Error  17  error C2784: 'bool std::operator <(const std::reverse_iterator<_RanIt> &,const std::reverse_iterator<_RanIt2> &)' : could not deduce template argument for 'const std::reverse_iterator<_RanIt> &' from 'const skl::Bone' c:\Program Files\Microsoft Visual Studio 9.0\VC\include\utility 103

Error  18  error C2784: 'bool std::operator <(const std::_Revranit<_RanIt,_Base> &,const std::_Revranit<_RanIt2,_Base2> &)' : could not deduce template argument for 'const std::_Revranit<_RanIt,_Base> &' from 'const skl::Bone'   c:\Program Files\Microsoft Visual Studio 9.0\VC\include\utility 103

Error  19  error C2784: 'bool std::operator <(const std::pair<_Ty1,_Ty2> &,const std::pair<_Ty1,_Ty2> &)' : could not deduce template argument for 'const std::pair<_Ty1,_Ty2> &' from 'const skl::Bone' c:\Program Files\Microsoft Visual Studio 9.0\VC\include\utility 103

Error  20  error C2676: binary '<' : 'const skl::Bone' does not define this operator or a conversion to a type acceptable to the predefined operator   c:\Program Files\Microsoft Visual Studio 9.0\VC\include\utility 103


问:
replace blank with 0 based on value in another column
I have a df like this:

```<code>                 NEW_df <- data.frame(CAR = c("YES","NO","NO","YES","NO"),
                                     BIKE = c(2,0,4,NA,9),
                                     PLANE = c(8,0,6,7,9),
                                   BOAT = c(NA,NA,NA,4,3),
                                   SCOOTER = c(2,3,6,9,0))
</code>```

I will like to replace NA's in column BOAT with '0'if the column CAR is 'NO', so I can have something like this:

```<code>                 NEW_df <- data.frame(CAR = c("YES","NO","NO","YES","NO"),
                                     BIKE = c(2,0,4,NA,9),
                                     PLANE = c(8,0,6,7,9),
                                   BOAT = c(NA,0,0,4,3),
                                   SCOOTER = c(2,3,6,9,0))
</code>```

I thought something like this, but it didnt work:

```<code>NEW_df %>%
  mutate(across(BOAT, ~ if_else(CAR == NO & is.na(.), 0, .)))
</code>```

Is it even possible to place the replaced values in a new column too.

答:
We can do this easily in base R

```<code>NEW_df$BOAT[is.na(NEW_df$BOAT) & NEW_df$CAR == "NO"] <- 0
</code>```

The %>% doesn't do replacement inplace.  We have to assign back with NEW_df <-.  Also, if it is single column, there is no need for across along with a syntax error (NO is not quoted)

```<code>library(dplyr)
NEW_df <- NEW_df %>%
      mutate(BOAT = replace(BOAT, CAR == "NO" & is.na(BOAT), 0))
</code>```

Body:
I have a df like this:

                 NEW_df <- data.frame(CAR = c("YES","NO","NO","YES","NO"),
                                     BIKE = c(2,0,4,NA,9),
                                     PLANE = c(8,0,6,7,9),
                                   BOAT = c(NA,NA,NA,4,3),
                                   SCOOTER = c(2,3,6,9,0))

I will like to replace NA's in column BOAT with '0'if the column CAR is 'NO', so I can have something like this:

                 NEW_df <- data.frame(CAR = c("YES","NO","NO","YES","NO"),
                                     BIKE = c(2,0,4,NA,9),
                                     PLANE = c(8,0,6,7,9),
                                   BOAT = c(NA,0,0,4,3),
                                   SCOOTER = c(2,3,6,9,0))

I thought something like this, but it didnt work:

NEW_df %>%
  mutate(across(BOAT, ~ if_else(CAR == NO & is.na(.), 0, .)))

Is it even possible to place the replaced values in a new column too.

Body:
We can do this easily in base R

NEW_df$BOAT[is.na(NEW_df$BOAT) & NEW_df$CAR == "NO"] <- 0

The %>% doesn't do replacement inplace.  We have to assign back with NEW_df <-.  Also, if it is single column, there is no need for across along with a syntax error (NO is not quoted)

library(dplyr)
NEW_df <- NEW_df %>%
      mutate(BOAT = replace(BOAT, CAR == "NO" & is.na(BOAT), 0))


问:
How can I add multiple conditions in react?
I have button Description. When clicked description is displayed. Now I want to add Read more/less on description.

With the belpw code, I do not see button Description, description is displayed directly

Flow- Display button-> On click-> Show 200 character text (With Read more option)

```<code>  const [readMore, setReadMore] = useState(false);

  const [displaydescription, setDisplayDescription] = useState(false);
  const clickHandler = () => {
    setDisplayDescription(true);
  };

 <p>
          {displaydescription || readMore
            ? description
            : `${description.substring(0, 200)}`}
        </p>
</code>```

答:
You have to change your code to first display description and then in second condition to verify if you want to show the full text like this:

const [readMore, setReadMore] = useState(false);
const [displaydescription, setDisplayDescription] = useState(false);
const clickHandler = () => {
    setDisplayDescription(true);
};

    {displaydescription
       ? (
            readMore
               ? description
               : `${description.substring(0, 200)
         )
       : null}`
    }

```

Body:
I have button Description. When clicked description is displayed. Now I want to add Read more/less on description.

With the belpw code, I do not see button Description, description is displayed directly

Flow- Display button-> On click-> Show 200 character text (With Read more option)

  const [readMore, setReadMore] = useState(false);

  const [displaydescription, setDisplayDescription] = useState(false);
  const clickHandler = () => {
    setDisplayDescription(true);
  };

          {displaydescription || readMore
            ? description
            : `${description.substring(0, 200)}`}

Body:
You have to change your code to first display description and then in second condition to verify if you want to show the full text like this:

const [readMore, setReadMore] = useState(false);
const [displaydescription, setDisplayDescription] = useState(false);
const clickHandler = () => {
    setDisplayDescription(true);
};

 <p>
    {displaydescription
       ? (
            readMore
               ? description
               : `${description.substring(0, 200)
         )
       : null}`
    }
 </p>


问:
How to increment version minor/patch based on the branch from which we merge
We have a simple GitHubFlow workflow with feature/* and bug/* branches.

When things are merged to master, then the version gets bumped whatever we specify in the GitVersion.yml file (minor/patch).

mode: Mainline
branches:
  main:
    regex: ^master$
    tag: ''
    # Increment is always the same regardless of the branch from which we are merging
    increment: Minor

  feature:
    regex: ^feature/
    tag: useBranchName
    increment: Minor
    source-branches:
    - main

  bug:
    regex: ^bug/
    tag: useBranchName
    increment: Patch
    source-branches:
    - main

```

However, I'd like to bump the minor or patch version depending on whether we merged from a feature or bug branch.

I'm using Squashing when merging to master.

Is there a way to do this please?

答:
Unfortunately, I was not able to increment the major, minor and patch versions based on the branch (the increment property inside each branch is ignored) so all merges to master increment the same way but with possibility to bump differently based on something added to the message e.g. Add +f (feature) to increment minor versions and +b (bug) to increment patch version.

mode: Mainline
major-version-bump-message: '\+major'
minor-version-bump-message: '\+f'
patch-version-bump-message: '\+b'
branches:
  master:
    regex: ^master$
    tag: ""
    increment: Minor
    is-mainline: true

  feature:
    regex: ^feature/
    tag: useBranchName
    increment: Patch

  bug:
    regex: ^bug/
    tag: useBranchName
    increment: Patch
    source-branches:
      - master
```

Body:
We have a simple GitHubFlow workflow with feature/* and bug/* branches.

When things are merged to master, then the version gets bumped whatever we specify in the GitVersion.yml file (minor/patch).

mode: Mainline
branches:
  main:
    regex: ^master$
    tag: ''
    # Increment is always the same regardless of the branch from which we are merging
    increment: Minor

  feature:
    regex: ^feature/
    tag: useBranchName
    increment: Minor
    source-branches:
    - main

  bug:
    regex: ^bug/
    tag: useBranchName
    increment: Patch
    source-branches:
    - main

However, I'd like to bump the minor or patch version depending on whether we merged from a feature or bug branch.

I'm using Squashing when merging to master.

Is there a way to do this please?


问:
How to calculate cyclomatic complexity of a project (not a class/function)?
How to calculate cyclomatic complexity of the entire Java project? I have complexities for every method, but how to aggregate them all into one numeric metric? Any ideas or existing methods?

I'm not looking for a tool, but for an algorithm.

Simple average hardly works because there are many 1-complexity methods, which are not really of low complexity, but of low importance for the code base (in most cases).

答: To my best knowledge, there is no answer to your question yet. But what Microsoft Visual Studio is doing is summing up all Cyclomatic Complexities for a given project and considering the result as assembly level Cyclomatic Complexity. But I personally will suggest you go with Max Cyclomatic Complexity. Just simply consider the Maximum Cyclomatic Complexity as Project Cyclomatic Complexity. The reason for that is as long as there is a method with higher Cyclomatic Complexity within a Project that Project is gonna be your bottleneck for your Software System. The other reason is because of strongly connected graph theory, according to the original paper of McCabe Cyclomatic Complexity for a strongly connected graph is the maximum Cyclomatic Complexity between Cyclomatic Complexities within independently existing circuits.</p>


问:
Replace RestSharp GET request with Net.Http
I have a RestSharp Entitlement check code that works, but I need to replace it with one that uses native C# library (Net.Http). So I was wondering what will the equivalent of my code be using native C#.

Here is my code:

```<code>        public static bool Entitlement(string appId, string userId)
    {
        //REST API call for the entitlement API.
        //We are using RestSharp for simplicity.
        //You may choose to use another library.

        //(1) Build request
        var client = new RestClient();
        client.BaseUrl = new System.Uri(@"https://apps.example.com/");

        //Set resource/end point
        var request = new RestRequest();
        request.Resource = "webservices/checkentitlement";
        request.Method = Method.GET;

        //Add parameters
        request.AddParameter("userid", userId);
        request.AddParameter("appid", appId);

        //(2) Execute request and get response
        IRestResponse response = client.Execute(request);

        //Get the entitlement status.
        bool isValid = false;
        if (response.StatusCode == HttpStatusCode.OK)
        {
            JsonDeserializer deserial = new JsonDeserializer();
            EntitlementResponse entitlementResponse = deserial.Deserialize<EntitlementResponse>(response);
            isValid = entitlementResponse.IsValid;
        }

        //
        return isValid;
    }

    class EntitlementResponse
{
    public string UserId { get; set; }
    public string AppId { get; set; }
    public bool IsValid { get; set; }
    public string Message { get; set; }
}
</code>```

答:
try this</p>
```<code>public async Task<EntitlementResponse> Entitlement(string appId, string userId)
{
using (var client = new HttpClient())
{
    var baseAddress ="https://apps.example.com/";

var api = "/webservices/checkentitlement/"+  userId.ToString()+"/" + appId.ToString();

//or since I don't know how your API looks
var api = "/webservices/checkentitlement?userId="+  userId.ToString()+"&appId=" + appId.ToString()

    client.BaseAddress = new Uri(baseAddress);
    var contentType = new MediaTypeWithQualityHeaderValue("application/json");
    client.DefaultRequestHeaders.Accept.Add(contentType);
    var response = await client.GetAsync(api);
    var statusCode = response.StatusCode.ToString();
    if (response.IsSuccessStatusCode)
    {
        var json = await response.Content.ReadAsStringAsync();
        return JsonConvert.DeserializeObject<EntitlementResponse>(json);
    }
}
return null;
}
</code>```

Body:
I have a RestSharp Entitlement check code that works, but I need to replace it with one that uses native C# library (Net.Http). So I was wondering what will the equivalent of my code be using native C#.

Here is my code:

        public static bool Entitlement(string appId, string userId)
    {
        //REST API call for the entitlement API.
        //We are using RestSharp for simplicity.
        //You may choose to use another library.

        //(1) Build request
        var client = new RestClient();
        client.BaseUrl = new System.Uri(@"https://apps.example.com/");

        //Set resource/end point
        var request = new RestRequest();
        request.Resource = "webservices/checkentitlement";
        request.Method = Method.GET;

        //Add parameters
        request.AddParameter("userid", userId);
        request.AddParameter("appid", appId);

        //(2) Execute request and get response
        IRestResponse response = client.Execute(request);

        //Get the entitlement status.
        bool isValid = false;
        if (response.StatusCode == HttpStatusCode.OK)
        {
            JsonDeserializer deserial = new JsonDeserializer();
            EntitlementResponse entitlementResponse = deserial.Deserialize<EntitlementResponse>(response);
            isValid = entitlementResponse.IsValid;
        }

        //
        return isValid;
    }

    class EntitlementResponse
{
    public string UserId { get; set; }
    public string AppId { get; set; }
    public bool IsValid { get; set; }
    public string Message { get; set; }
}

Body:
try this

public async Task<EntitlementResponse> Entitlement(string appId, string userId)
{
using (var client = new HttpClient())
{
    var baseAddress ="https://apps.example.com/";

var api = "/webservices/checkentitlement/"+  userId.ToString()+"/" + appId.ToString();

//or since I don't know how your API looks
var api = "/webservices/checkentitlement?userId="+  userId.ToString()+"&appId=" + appId.ToString()

    client.BaseAddress = new Uri(baseAddress);
    var contentType = new MediaTypeWithQualityHeaderValue("application/json");
    client.DefaultRequestHeaders.Accept.Add(contentType);
    var response = await client.GetAsync(api);
    var statusCode = response.StatusCode.ToString();
    if (response.IsSuccessStatusCode)
    {
        var json = await response.Content.ReadAsStringAsync();
        return JsonConvert.DeserializeObject<EntitlementResponse>(json);
    }
}
return null;
}


问:
What are Python pandas equivalents for R functions like str(), summary(), and head()?
I'm only aware of the describe() function. Are there any other functions similar to str(), summary(), and head()?

答:
I don't think there is a direct equivalent to the str() function (or glimpse() from dplyr) in Pandas that gives the same information. I think an equivalent function would have to display the following:

The number of rows and columns in the data frame

The names of all the columns

The data type stored in each column

A quick look at the first few values in each column

Building on @jjurach's answer, I wrote a helper function that works as a stand-in for the R str or glimpse function to quickly get an overview of my DataFrames. Here's the code with an example:

```<code>import pandas as pd
import random

# an example dataframe to test the helper function
example_df = pd.DataFrame({
    "var_a": [random.choice(["foo","bar"]) for i in range(20)],
    "var_b": [random.randint(0, 1) for i in range(20)],
    "var_c": [random.random() for i in range(20)]
})

# helper function for viewing pandas dataframes
def glimpse_pd(df, max_width=76):

    # find the max string lengths of the column names and dtypes for formatting
    _max_len = max([len(col) for col in df])
    _max_dtype_label_len = max([len(str(df[col].dtype)) for col in df])

    # print the dimensions of the dataframe
    print(f"{type(df)}:  {df.shape[0]} rows of {df.shape[1]} columns")

    # print the name, dtype and first few values of each column
    for _column in df:

        _col_vals = df[_column].head(max_width).to_list()
        _col_type = str(df[_column].dtype)

        output_col = f"{_column}:".ljust(_max_len+1, ' ')
        output_dtype = f" {_col_type}".ljust(_max_dtype_label_len+3, ' ')

        output_combined = f"{output_col} {output_dtype} {_col_vals}"

        # trim the output if too long
        if len(output_combined) > max_width:
            output_combined = output_combined[0:(max_width-4)] + " ..."

        print(output_combined)
</code>```

Running the function returns the following output:

```<code>glimpse_pd(example_df)
<class 'pandas.core.frame.DataFrame'>:  20 rows of 3 columns
var_a:  object    ['foo', 'bar', 'foo', 'foo', 'bar', 'bar', 'foo', 'bar ...
var_b:  int64     [0, 0, 0, 1, 0, 0, 1, 0, 0, 1, 1, 0, 1, 0, 0, 0, 0, 0, ...
var_c:  float64   [0.7346545694885085, 0.7776711488732364, 0.49558114902 ...
</code>```

Body:
I don't think there is a direct equivalent to the str() function (or glimpse() from dplyr) in Pandas that gives the same information. I think an equivalent function would have to display the following:

The number of rows and columns in the data frame

The names of all the columns

The data type stored in each column

A quick look at the first few values in each column

Building on @jjurach's answer, I wrote a helper function that works as a stand-in for the R str or glimpse function to quickly get an overview of my DataFrames. Here's the code with an example:

import pandas as pd
import random

# an example dataframe to test the helper function
example_df = pd.DataFrame({
    "var_a": [random.choice(["foo","bar"]) for i in range(20)],
    "var_b": [random.randint(0, 1) for i in range(20)],
    "var_c": [random.random() for i in range(20)]
})

# helper function for viewing pandas dataframes
def glimpse_pd(df, max_width=76):

    # find the max string lengths of the column names and dtypes for formatting
    _max_len = max([len(col) for col in df])
    _max_dtype_label_len = max([len(str(df[col].dtype)) for col in df])

    # print the dimensions of the dataframe
    print(f"{type(df)}:  {df.shape[0]} rows of {df.shape[1]} columns")

    # print the name, dtype and first few values of each column
    for _column in df:

        _col_vals = df[_column].head(max_width).to_list()
        _col_type = str(df[_column].dtype)

        output_col = f"{_column}:".ljust(_max_len+1, ' ')
        output_dtype = f" {_col_type}".ljust(_max_dtype_label_len+3, ' ')

        output_combined = f"{output_col} {output_dtype} {_col_vals}"

        # trim the output if too long
        if len(output_combined) > max_width:
            output_combined = output_combined[0:(max_width-4)] + " ..."

        print(output_combined)

Running the function returns the following output:

glimpse_pd(example_df)
<class 'pandas.core.frame.DataFrame'>:  20 rows of 3 columns
var_a:  object    ['foo', 'bar', 'foo', 'foo', 'bar', 'bar', 'foo', 'bar ...
var_b:  int64     [0, 0, 0, 1, 0, 0, 1, 0, 0, 1, 1, 0, 1, 0, 0, 0, 0, 0, ...
var_c:  float64   [0.7346545694885085, 0.7776711488732364, 0.49558114902 ...


问:
PowerShell - Double loop possible?
I want to compress a directory in a specific place.
The source path is :  \\$Computers\Users\$Names

I want than for each computers a copy of each users directory in the sources path of each computers

I tried to use a foreach loop like :

```<code>$Computers = Get-ADComputer -Filter "Name -like 'PC*'" | Select-Object -ExpandProperty Name
$Names = Get-aduser -filter * | Select-Object -ExpandProperty givenname

Foreach($Computer in $Computers)
{
    Compress-Archive -Path \\$Computer\Users\* -DestinationPath C:\Saves\\$Computer\Test.zip -Force
}
</code>```

This actually work, but I don't know how can I add a second loop inside the loop.

If anyone can just explain me the function or just some advises please for trying to do that.

Thank you for your time.

答:
You're approaching the problem with the wrong logic, you do need an inner loop, however, instead of attempting to compress a user profile that you don't know for sure is there you can instead query the remote computer's Users folder to see which ones are there and compress only those ones:

```<code>$Computers = (Get-ADComputer -Filter "Name -like 'PC*'").Name
# Add the profiles you want to exclude here:
$toExclude = 'Administrator', 'Public'
$params = @{
    Force = $true
    CompressionLevel = 'Optimal'
}

foreach($Computer in $Computers)
{
    $source = "\\$Computer\Users"
    Get-ChildItem $source -Exclude $toExclude -Directory | ForEach-Object {
        $params.LiteralPath = $_.FullName
        # Name of the zipped file would be "ComputerExample - UserExample.zip"
        $params.DestinationPath = "C:\Saves\$computer - {0}.zip" -f $_.Name
        Compress-Archive @params
    }
}
</code>```

Title: PowerShell - Double loop possible?

Body:
I want to compress a directory in a specific place.
The source path is :  \\$Computers\Users\$Names

I want than for each computers a copy of each users directory in the sources path of each computers

I tried to use a foreach loop like :

$Computers = Get-ADComputer -Filter "Name -like 'PC*'" | Select-Object -ExpandProperty Name
$Names = Get-aduser -filter * | Select-Object -ExpandProperty givenname

Foreach($Computer in $Computers)
{
    Compress-Archive -Path \\$Computer\Users\* -DestinationPath C:\Saves\\$Computer\Test.zip -Force
}

This actually work, but I don't know how can I add a second loop inside the loop.

If anyone can just explain me the function or just some advises please for trying to do that.

Thank you for your time.

Body:
You're approaching the problem with the wrong logic, you do need an inner loop, however, instead of attempting to compress a user profile that you don't know for sure is there you can instead query the remote computer's Users folder to see which ones are there and compress only those ones:

$Computers = (Get-ADComputer -Filter "Name -like 'PC*'").Name
# Add the profiles you want to exclude here:
$toExclude = 'Administrator', 'Public'
$params = @{
    Force = $true
    CompressionLevel = 'Optimal'
}

foreach($Computer in $Computers)
{
    $source = "\\$Computer\Users"
    Get-ChildItem $source -Exclude $toExclude -Directory | ForEach-Object {
        $params.LiteralPath = $_.FullName
        # Name of the zipped file would be "ComputerExample - UserExample.zip"
        $params.DestinationPath = "C:\Saves\$computer - {0}.zip" -f $_.Name
        Compress-Archive @params
    }
}


问:
Running one web page across devices with the same data
I want to make a simple todo list web page for myself so that I can be a more organized person but I have a problem. I want to be able to close the website or switch to another computer and still keep the data of what I have done or not done on this to do list. I have tried to search up ways that I could do this online but I don't know what to search to find the right results.

I know about js and web design stuff but I don't know any back end stuff so.

答:
You need to have some kind of backend for what you are planing to accomplish. Such a backend could be a database storing each of your to-dos on a single database row, or some sort of file, which is located on a central server (the file could for example be a .json, .xml or .csv).

However, you can also write a JavaScript app, that stores your to-dos in your local browser storage, but then you would have to implement an export, import logic for a manual sync.

I assume that is not what you are looking for, so I would suggest checking out some services like for example the Google Drive API. You can interact with JavaScript with it and store your to-dos in your Google account: https://developers.google.com/drive/api/v3/quickstart/js


问:
Trying to take the file extension out of my URL
Curious on how to take the file extension out of my URL to make it appear as "https://thedigitalagetech.info/" instead of "https://thedigitalagetech.info/index.html."</p>

答:
Depending on how your apache server is configured.

You can try to create a .htaccess file in your root directory, and add the following content to see if it works.

```<code>RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME}\.html -f
RewriteRule ^(.*)$ $1.html [NC,L]
</code>```

We can only trial and error because we don't know your set up.

Body:
Depending on how your apache server is configured.

You can try to create a .htaccess file in your root directory, and add the following content to see if it works.

RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME}\.html -f
RewriteRule ^(.*)$ $1.html [NC,L]

We can only trial and error because we don't know your set up.


问:
What is the TypeScript type of failed useMutation requests?
Consider the following code:

```<code>const {
  mutate: storeData,
} = useMutation(...) // useMutation from @vue/apollo-composable

const sendForm = handleSubmit(async (values) => {
  try {
    const result = await storeData()
    console.log(result)
  } catch (e) { // <---- what is the TypeScript type of e?
    ...
  }
})
</code>```

I want to annotate the e parameter of catch(e) with its TypeScript type - but which type is it? If you know the solution, if possible also explain how I could have figured that out myself, thanks!

答:
After having a quick look at the source code of the function, it seems like it throws an ApolloError, which, according to this answer, can be imported from the client:

```<code>import { ApolloError } from '@apollo/client/errors';
</code>```

explain how I could have figured that out myself

Basically just have a look at what the function might throw and after that find out how to import it (stackoverflow can be really helpful here). Of course this only works if the other package is also written in typescript. Otherwise the best option is probably to use Error.

Body:
Consider the following code:

const {
  mutate: storeData,
} = useMutation(...) // useMutation from @vue/apollo-composable

const sendForm = handleSubmit(async (values) => {
  try {
    const result = await storeData()
    console.log(result)
  } catch (e) { // <---- what is the TypeScript type of e?
    ...
  }
})

I want to annotate the e parameter of catch(e) with its TypeScript type - but which type is it? If you know the solution, if possible also explain how I could have figured that out myself, thanks!

Body:
After having a quick look at the source code of the function, it seems like it throws an ApolloError, which, according to this answer, can be imported from the client:

import { ApolloError } from '@apollo/client/errors';

explain how I could have figured that out myself

Basically just have a look at what the function might throw and after that find out how to import it (stackoverflow can be really helpful here). Of course this only works if the other package is also written in typescript. Otherwise the best option is probably to use Error.


问:
My update is running WAY SLOWER than it should
I am trying to create a program that writes sheet music as you play. My first goal was to get an update cruising along at 64 times per beat (this is all the accuracy I need for my purposes). However, when I set up my code the update runs WAY SLOWER than it should.

My code is set up to run at 140 beats per minute, but it only sounds like about 50 beats per minute.

I have a theory that it is an issue with the calculating of the delay between updates, but I can't figure out what I've done wrong. Here's the entirety of my code:

```<code>#include <raylib.h>
#include <iostream>
#include <chrono>
#include <string>

#include "filestuff.h"

Sound metVoices[1];
int metSelectedVoice = 0;

float bpm = 140;

void initSounds() {

    using str = std::string;

    str v1p = getExeDir() + "\\sounds\\met voice 1.wav";
    metVoices[0] = LoadSound(v1p.data());
}

void update64() {

    std::cout << "64th note" << std::endl;
}

void updateBeat() {

    //PlaySound is asynchronous
    PlaySound(metVoices[metSelectedVoice]);
}

int main() {

    InitAudioDevice();
    initSounds();

    long double delay64;

    //bps and beat will clear from memory because they go out of scope
    {
        long double bps = bpm / 60;
        long double beat = 1 / bps;
        delay64 = beat / 64;
    }

    long double update64Timer = delay64;
    long double beatTimer = 64;
    long double dt = 0;

    while (true) {

        std::chrono::steady_clock::time_point frameStart = std::chrono::steady_clock::now();

        update64Timer -= dt;

        if (update64Timer <= 0) {

            update64();
            beatTimer--;
            update64Timer = delay64;
        }

        if (beatTimer <= 0) {

            updateBeat();
            beatTimer = 64;
        }

        dt = std::chrono::duration<long double>(std::chrono::steady_clock::now() - frameStart).count();
    }

    CloseAudioDevice();

    return 0;
}
</code>```

It's been pointed out that my code is not exeption safe, and that there are some magic numbers in there. I plan on improving these things, but I need to get something working first.

If any more information is needed I will gladly share it. Thanks in advance to anybody that helps me out!

答: I found my issue. The code was so inefficient that it could keep up with the 64 times per beat pulse.</p>

Body:
I am trying to create a program that writes sheet music as you play. My first goal was to get an update cruising along at 64 times per beat (this is all the accuracy I need for my purposes). However, when I set up my code the update runs WAY SLOWER than it should.

My code is set up to run at 140 beats per minute, but it only sounds like about 50 beats per minute.

I have a theory that it is an issue with the calculating of the delay between updates, but I can't figure out what I've done wrong. Here's the entirety of my code:

#include <raylib.h>
#include <iostream>
#include <chrono>
#include <string>

#include "filestuff.h"

Sound metVoices[1];
int metSelectedVoice = 0;

float bpm = 140;

void initSounds() {

    using str = std::string;

    str v1p = getExeDir() + "\\sounds\\met voice 1.wav";
    metVoices[0] = LoadSound(v1p.data());
}

void update64() {

    std::cout << "64th note" << std::endl;
}

void updateBeat() {

    //PlaySound is asynchronous
    PlaySound(metVoices[metSelectedVoice]);
}

int main() {

    InitAudioDevice();
    initSounds();

    long double delay64;

    //bps and beat will clear from memory because they go out of scope
    {
        long double bps = bpm / 60;
        long double beat = 1 / bps;
        delay64 = beat / 64;
    }

    long double update64Timer = delay64;
    long double beatTimer = 64;
    long double dt = 0;

    while (true) {

        std::chrono::steady_clock::time_point frameStart = std::chrono::steady_clock::now();

        update64Timer -= dt;

        if (update64Timer <= 0) {

            update64();
            beatTimer--;
            update64Timer = delay64;
        }

        if (beatTimer <= 0) {

            updateBeat();
            beatTimer = 64;
        }

        dt = std::chrono::duration<long double>(std::chrono::steady_clock::now() - frameStart).count();
    }

    CloseAudioDevice();

    return 0;
}

It's been pointed out that my code is not exeption safe, and that there are some magic numbers in there. I plan on improving these things, but I need to get something working first.

If any more information is needed I will gladly share it. Thanks in advance to anybody that helps me out!


问:
Moq - Verify no methods were called except one
I have a controller with a method that reads configuration to determine which other method(s) to call. Depending on the config, it may call zero, one, or all of the WorkerMethodN() methods.

```<code>public class MyController
{
   public virtual bool EntranceMethod()
   {
      // read configuration to determine which methods to call
   }

   public virtual void WorkerMethod1() { ... }
   public virtual void WorkerMethod2() { ... }
   public virtual void WorkerMethod3() { ... }
}
</code>```

I am trying to test this EntranceMethod() and my first test is to determine behavior when the configuration is empty. When the configuration returns nothing, I want to ensure that none of the WorkerMethodN() methods are called.

My test so far:

```<code>[TestMethod]
public void ShouldNotCallAnyMethodsWhenConfigurationReturnsNull()
{
   this.mockConfigurationReader
       .Setup(cr => cr.GetEnabledConfigurations())
       .Returns((IEnumerable<Configuration>)null);

   Mock<MyController> mockController =
      new Mock<MyController>(MockBehavior.Strict, this.mockConfigurationReader.Object);

   mockController.Object.EntranceMethod();

   // todo: verify no additional methods are called
}
</code>```

This call fails with the Exception: invocation failed with mock behavior Strict. All invocations on the mock must have a corresponding setup. when the call to EntranceMethod() is made.

How do I use MockBehavior.Strict and setup my controller to call EntranceMethod() and verify that no other methods are called? If I call .Setup() on my EntranceMethod(), it won't run the actual code I want it to. But if I don't call .Setup(), I get an exception.

答:
Modern answer (Moq 4.8 or later):

```<code>mock.Verify(...);
mock.VerifyNoOtherCalls();
</code>```

That code does 2 things:

Verifies that any expected calls were made

Verifies that no other calls were made

Source: Moq Quickstart

Body:
I have a controller with a method that reads configuration to determine which other method(s) to call. Depending on the config, it may call zero, one, or all of the WorkerMethodN() methods.

public class MyController
{
   public virtual bool EntranceMethod()
   {
      // read configuration to determine which methods to call
   }

   public virtual void WorkerMethod1() { ... }
   public virtual void WorkerMethod2() { ... }
   public virtual void WorkerMethod3() { ... }
}

I am trying to test this EntranceMethod() and my first test is to determine behavior when the configuration is empty. When the configuration returns nothing, I want to ensure that none of the WorkerMethodN() methods are called.

My test so far:

[TestMethod]
public void ShouldNotCallAnyMethodsWhenConfigurationReturnsNull()
{
   this.mockConfigurationReader
       .Setup(cr => cr.GetEnabledConfigurations())
       .Returns((IEnumerable<Configuration>)null);

   Mock<MyController> mockController =
      new Mock<MyController>(MockBehavior.Strict, this.mockConfigurationReader.Object);

   mockController.Object.EntranceMethod();

   // todo: verify no additional methods are called
}

This call fails with the Exception: invocation failed with mock behavior Strict. All invocations on the mock must have a corresponding setup. when the call to EntranceMethod() is made.

How do I use MockBehavior.Strict and setup my controller to call EntranceMethod() and verify that no other methods are called? If I call .Setup() on my EntranceMethod(), it won't run the actual code I want it to. But if I don't call .Setup(), I get an exception.

Body:
Modern answer (Moq 4.8 or later):

mock.Verify(...);
mock.VerifyNoOtherCalls();

That code does 2 things:

Verifies that any expected calls were made

Verifies that no other calls were made

Source: Moq Quickstart


问:
What is the best way to add a value to an array in state
I have an array in state, let's say this.state.arr.
I want to add something to this state property, and then change some more properties.

Option 1

```<code>onChange(event){
    this.state.arr.push('newvalue');
    ...
    this.setState({some:'val',arr:this.state.arr})
}
</code>```

Option 2

```<code>onChange(event){
    var newArr = this.state.arr;
    ...
    newArr.push('newvalue');
    ...
    this.setState({some:'val',arr:newArr})
}
</code>```

So... I know this.state is supposed to be treated immutable, but is it ok to use it like in option 1 where I still set the state from it, or do I need to go with something like option 2, and thus always first making a copy in memory?

答:
React hook - useState (2022)

```<code>const [array, setArray] = useState([]);

const handleChange = (newValue) => {
  setArray((array) => [...array, newValue]);
};
</code>```

Body:
I have an array in state, let's say this.state.arr.
I want to add something to this state property, and then change some more properties.

Option 1

onChange(event){
    this.state.arr.push('newvalue');
    ...
    this.setState({some:'val',arr:this.state.arr})
}

Option 2

onChange(event){
    var newArr = this.state.arr;
    ...
    newArr.push('newvalue');
    ...
    this.setState({some:'val',arr:newArr})
}

So... I know this.state is supposed to be treated immutable, but is it ok to use it like in option 1 where I still set the state from it, or do I need to go with something like option 2, and thus always first making a copy in memory?

Body:
React hook - useState (2022)

const [array, setArray] = useState([]);

const handleChange = (newValue) => {
  setArray((array) => [...array, newValue]);
};


问:
Value cannot be null; Parameter Name: constructor when using SqlExecuteQuery with an abstract Entity model
We are storing items in our database which are derived from a single abstract Entity named SurveyItem. We are trying to find SurveyItems that contain some query string. I apologize for the wall of code, but I think this is as small as I can make it while staying in our situation. I suspect the problem is caused by having object inheritance and using an abstract root. When using the method below with Entities without inheritance all is fine.

Our entities are stored using TpH and look like this:

```<code>public abstract class SurveyItem
{
    [ScaffoldColumn(false)]
    public int Id { get; set; }

    [ScaffoldColumn(false)]
    public virtual ICollection<Survey_SurveyItem> SurveyLinks { get; private set; }

    [ScaffoldColumn(false)]
    public abstract string Identifier { get; }

    public SurveyItem()
    {
        SurveyLinks = new List<Survey_SurveyItem>();
    }
}

public class SurveyHeaderItem : SurveyItem
{
    [Required]
    [Display(Name = "title", ResourceType = typeof(Caracal.Resources.GUI))]
    public Translated Title { get; set; }

    [ScaffoldColumn(false)]
    public override string Identifier
    {
        get { return Title.NL + " / " + Title.EN; }
    }
    // ...
}

public class SurveyQuestion : SurveyItem
{
    [Required]
    [Order(1)]
    [Display(Name = "question", ResourceType = typeof(Caracal.Resources.GUI))]
    public Translated Question { get; set; }

    [Order(2)]
    [Display(Name = "description", ResourceType = typeof(Caracal.Resources.GUI))]
    public TranslatedMultilineOptional Description { get; set; }
    //...
}
</code>```

The abstract root class does not contain the fields we want to be able to inspect so something like the following is not possible:

```<code>Context.SurveyItems.Where(x => x.Field.contains(q));
</code>```

So what we tried is the following Stored Procedure combined with the code below:

```<code>CREATE PROCEDURE SearchSurveyItems (@Q nvarchar(255))
AS
BEGIN
    SET NOCOUNT ON;
    SELECT i.*
    FROM [dbo].SurveyItems AS i
    WHERE
        i.Question_NL LIKE ('%' + @Q + '%') OR
        i.Question_EN LIKE ('%' + @Q + '%') OR
        i.Description_NL LIKE ('%' + @Q + '%') OR
        i.Description_EN LIKE ('%' + @Q + '%') OR
        i.Title_NL LIKE ('%' + @Q + '%') OR
        i.Title_EN LIKE ('%' + @Q + '%') OR
        i.Text_NL LIKE ('%' + @Q + '%') OR
        i.Text_EN LIKE ('%' + @Q + '%')
END
</code>```

And the call from C#:

```<code>public IEnumerable<SurveyItem> SearchSurveyItems(string q)
{
    return this.Database.SqlQuery<SurveyItem>("dbo.SearchSurveyItems @Q", new SqlParameter("Q", q)).ToList();
}
</code>```

This results in the error from the title:

```<code>System.ArgumentNullException was unhandled by user code
  Message=Value cannot be null.
Parameter name: constructor
  Source=System.Core
  ParamName=constructor
  StackTrace:
       at System.Linq.Expressions.Expression.New(ConstructorInfo constructor, IEnumerable`1 arguments)
       at System.Data.Common.Internal.Materialization.Translator.Emit_ConstructEntity(EntityType oSpaceType, IEnumerable`1 propertyBindings, Expression entityKeyReader, Expression entitySetReader, TranslatorArg arg, EntityProxyTypeInfo proxyTypeInfo)
       at System.Data.Common.Internal.Materialization.Translator.Visit(EntityColumnMap columnMap, TranslatorArg arg)
       at System.Data.Query.InternalTrees.EntityColumnMap.Accept[TResultType,TArgType](ColumnMapVisitorWithResults`2 visitor, TArgType arg)
       at System.Data.Common.Internal.Materialization.Translator.ProcessCollectionColumnMap(CollectionColumnMap columnMap, TranslatorArg arg, ColumnMap discriminatorColumnMap, Object discriminatorValue)
       at System.Data.Common.Internal.Materialization.Translator.Visit(SimpleCollectionColumnMap columnMap, TranslatorArg arg)
       at System.Data.Query.InternalTrees.SimpleCollectionColumnMap.Accept[TResultType,TArgType](ColumnMapVisitorWithResults`2 visitor, TArgType arg)
       at System.Data.Common.Internal.Materialization.Translator.TranslateColumnMap[TRequestedType](QueryCacheManager queryCacheManager, ColumnMap columnMap, MetadataWorkspace workspace, SpanIndex spanIndex, MergeOption mergeOption, Boolean valueLayer)
       at System.Data.Objects.ObjectContext.InternalTranslate[TElement](DbDataReader reader, String entitySetName, MergeOption mergeOption, Boolean readerOwned)
       at System.Data.Objects.ObjectContext.ExecuteStoreQueryInternal[TElement](String commandText, String entitySetName, MergeOption mergeOption, Object[] parameters)
       at System.Data.Objects.ObjectContext.ExecuteStoreQuery[TElement](String commandText, Object[] parameters)
       at System.Data.Entity.Internal.InternalContext.ExecuteSqlQuery[TElement](String sql, Object[] parameters)
       at System.Data.Entity.Internal.InternalContext.ExecuteSqlQueryAsIEnumerable[TElement](String sql, Object[] parameters)
       at System.Data.Entity.Internal.InternalContext.ExecuteSqlQuery(Type elementType, String sql, Object[] parameters)
       at System.Data.Entity.Internal.InternalSqlNonSetQuery.GetEnumerator()
       at System.Data.Entity.Internal.InternalSqlQuery`1.GetEnumerator()
       at System.Collections.Generic.List`1..ctor(IEnumerable`1 collection)
       at System.Linq.Enumerable.ToList[TSource](IEnumerable`1 source)
       at Caracal.Entities.CaracalContext.SearchSurveyItems(String q) in J:\Caracal\Entities\CaracalContextDataAccessors.cs:line 48
       at Caracal.Application.Controllers.SearchController.SurveyItem(String q) in J:\Caracal\application\Controllers\SearchController.cs:line 75
       at lambda_method(Closure , ControllerBase , Object[] )
       at System.Web.Mvc.ActionMethodDispatcher.Execute(ControllerBase controller, Object[] parameters)
       at System.Web.Mvc.ReflectedActionDescriptor.Execute(ControllerContext controllerContext, IDictionary`2 parameters)
       at System.Web.Mvc.ControllerActionInvoker.InvokeActionMethod(ControllerContext controllerContext, ActionDescriptor actionDescriptor, IDictionary`2 parameters)
       at System.Web.Mvc.ControllerActionInvoker.<>c__DisplayClass15.<InvokeActionMethodWithFilters>b__12()
       at System.Web.Mvc.ControllerActionInvoker.InvokeActionMethodFilter(IActionFilter filter, ActionExecutingContext preContext, Func`1 continuation)
  InnerException:
</code>```

Update

This problem is fixed when I rename the class SurveyItem to AbstractSurveyItem and I create a new class SurveyItem, inheriting from AbstractSurveyItem. It can then create the SurveyItem objects perfectly.

However, I do not consider this a real solution as you now loose the safety and features of the abstract-mechanism. Is there a way I can keep the class abstract but that EF can still construct it somehow? It has the type of the class in each row, so in theory at least it should have enough information to create the correct instance.

Update 2*

In fact, the solution from the first update does remove the exception, however it gives also the following problem. Namely every object that comes out is only a SurveyItem, and never a subclass, resulting in a useless object.

答:
You could cast your SurveyItems collection to the correct type before trying to query them?  Perhaps something like:

```<code>string q = "[some search term]";
Context.SurveyItems.Where(x => x is SurveyQuestion).Where(x => x.Field.Contains(q));
</code>```

I might expand that a bit for readability, like so:

```<code>string q = "[some search term]";
IEnumerable<SurveyQuestion> surveyQuestions = Context.SurveyItems.Where(x => x is SurveyQuestion);
IEnumerable<SurveyQuestion> matchingSurveyQuestions = surveyQuestions.Where(x => x.Field.Contains(q));
</code>```

Or for even better readability (at least in my eyes - I like shorter code):

```<code>var searchTerm = "[some search term]";
var questions = Context.SurveyItems.Where(si => si is SurveyQuestion);
var matchingQuestions = questions.Where(q => q.Field.Contains(searchTerm));
</code>```

Body:
We are storing items in our database which are derived from a single abstract Entity named SurveyItem. We are trying to find SurveyItems that contain some query string. I apologize for the wall of code, but I think this is as small as I can make it while staying in our situation. I suspect the problem is caused by having object inheritance and using an abstract root. When using the method below with Entities without inheritance all is fine.

Our entities are stored using TpH and look like this:

public abstract class SurveyItem
{
    [ScaffoldColumn(false)]
    public int Id { get; set; }

    [ScaffoldColumn(false)]
    public virtual ICollection<Survey_SurveyItem> SurveyLinks { get; private set; }

    [ScaffoldColumn(false)]
    public abstract string Identifier { get; }

    public SurveyItem()
    {
        SurveyLinks = new List<Survey_SurveyItem>();
    }
}

public class SurveyHeaderItem : SurveyItem
{
    [Required]
    [Display(Name = "title", ResourceType = typeof(Caracal.Resources.GUI))]
    public Translated Title { get; set; }

    [ScaffoldColumn(false)]
    public override string Identifier
    {
        get { return Title.NL + " / " + Title.EN; }
    }
    // ...
}

public class SurveyQuestion : SurveyItem
{
    [Required]
    [Order(1)]
    [Display(Name = "question", ResourceType = typeof(Caracal.Resources.GUI))]
    public Translated Question { get; set; }

    [Order(2)]
    [Display(Name = "description", ResourceType = typeof(Caracal.Resources.GUI))]
    public TranslatedMultilineOptional Description { get; set; }
    //...
}

The abstract root class does not contain the fields we want to be able to inspect so something like the following is not possible:

Context.SurveyItems.Where(x => x.Field.contains(q));

So what we tried is the following Stored Procedure combined with the code below:

CREATE PROCEDURE SearchSurveyItems (@Q nvarchar(255))
AS
BEGIN
    SET NOCOUNT ON;
    SELECT i.*
    FROM [dbo].SurveyItems AS i
    WHERE
        i.Question_NL LIKE ('%' + @Q + '%') OR
        i.Question_EN LIKE ('%' + @Q + '%') OR
        i.Description_NL LIKE ('%' + @Q + '%') OR
        i.Description_EN LIKE ('%' + @Q + '%') OR
        i.Title_NL LIKE ('%' + @Q + '%') OR
        i.Title_EN LIKE ('%' + @Q + '%') OR
        i.Text_NL LIKE ('%' + @Q + '%') OR
        i.Text_EN LIKE ('%' + @Q + '%')
END

And the call from C#:

public IEnumerable<SurveyItem> SearchSurveyItems(string q)
{
    return this.Database.SqlQuery<SurveyItem>("dbo.SearchSurveyItems @Q", new SqlParameter("Q", q)).ToList();
}

This results in the error from the title:

System.ArgumentNullException was unhandled by user code
  Message=Value cannot be null.
Parameter name: constructor
  Source=System.Core
  ParamName=constructor
  StackTrace:
       at System.Linq.Expressions.Expression.New(ConstructorInfo constructor, IEnumerable`1 arguments)
       at System.Data.Common.Internal.Materialization.Translator.Emit_ConstructEntity(EntityType oSpaceType, IEnumerable`1 propertyBindings, Expression entityKeyReader, Expression entitySetReader, TranslatorArg arg, EntityProxyTypeInfo proxyTypeInfo)
       at System.Data.Common.Internal.Materialization.Translator.Visit(EntityColumnMap columnMap, TranslatorArg arg)
       at System.Data.Query.InternalTrees.EntityColumnMap.Accept[TResultType,TArgType](ColumnMapVisitorWithResults`2 visitor, TArgType arg)
       at System.Data.Common.Internal.Materialization.Translator.ProcessCollectionColumnMap(CollectionColumnMap columnMap, TranslatorArg arg, ColumnMap discriminatorColumnMap, Object discriminatorValue)
       at System.Data.Common.Internal.Materialization.Translator.Visit(SimpleCollectionColumnMap columnMap, TranslatorArg arg)
       at System.Data.Query.InternalTrees.SimpleCollectionColumnMap.Accept[TResultType,TArgType](ColumnMapVisitorWithResults`2 visitor, TArgType arg)
       at System.Data.Common.Internal.Materialization.Translator.TranslateColumnMap[TRequestedType](QueryCacheManager queryCacheManager, ColumnMap columnMap, MetadataWorkspace workspace, SpanIndex spanIndex, MergeOption mergeOption, Boolean valueLayer)
       at System.Data.Objects.ObjectContext.InternalTranslate[TElement](DbDataReader reader, String entitySetName, MergeOption mergeOption, Boolean readerOwned)
       at System.Data.Objects.ObjectContext.ExecuteStoreQueryInternal[TElement](String commandText, String entitySetName, MergeOption mergeOption, Object[] parameters)
       at System.Data.Objects.ObjectContext.ExecuteStoreQuery[TElement](String commandText, Object[] parameters)
       at System.Data.Entity.Internal.InternalContext.ExecuteSqlQuery[TElement](String sql, Object[] parameters)
       at System.Data.Entity.Internal.InternalContext.ExecuteSqlQueryAsIEnumerable[TElement](String sql, Object[] parameters)
       at System.Data.Entity.Internal.InternalContext.ExecuteSqlQuery(Type elementType, String sql, Object[] parameters)
       at System.Data.Entity.Internal.InternalSqlNonSetQuery.GetEnumerator()
       at System.Data.Entity.Internal.InternalSqlQuery`1.GetEnumerator()
       at System.Collections.Generic.List`1..ctor(IEnumerable`1 collection)
       at System.Linq.Enumerable.ToList[TSource](IEnumerable`1 source)
       at Caracal.Entities.CaracalContext.SearchSurveyItems(String q) in J:\Caracal\Entities\CaracalContextDataAccessors.cs:line 48
       at Caracal.Application.Controllers.SearchController.SurveyItem(String q) in J:\Caracal\application\Controllers\SearchController.cs:line 75
       at lambda_method(Closure , ControllerBase , Object[] )
       at System.Web.Mvc.ActionMethodDispatcher.Execute(ControllerBase controller, Object[] parameters)
       at System.Web.Mvc.ReflectedActionDescriptor.Execute(ControllerContext controllerContext, IDictionary`2 parameters)
       at System.Web.Mvc.ControllerActionInvoker.InvokeActionMethod(ControllerContext controllerContext, ActionDescriptor actionDescriptor, IDictionary`2 parameters)
       at System.Web.Mvc.ControllerActionInvoker.<>c__DisplayClass15.<InvokeActionMethodWithFilters>b__12()
       at System.Web.Mvc.ControllerActionInvoker.InvokeActionMethodFilter(IActionFilter filter, ActionExecutingContext preContext, Func`1 continuation)
  InnerException:

Update

This problem is fixed when I rename the class SurveyItem to AbstractSurveyItem and I create a new class SurveyItem, inheriting from AbstractSurveyItem. It can then create the SurveyItem objects perfectly.

However, I do not consider this a real solution as you now loose the safety and features of the abstract-mechanism. Is there a way I can keep the class abstract but that EF can still construct it somehow? It has the type of the class in each row, so in theory at least it should have enough information to create the correct instance.

Update 2*

In fact, the solution from the first update does remove the exception, however it gives also the following problem. Namely every object that comes out is only a SurveyItem, and never a subclass, resulting in a useless object.

Body:
You could cast your SurveyItems collection to the correct type before trying to query them?  Perhaps something like:

string q = "[some search term]";
Context.SurveyItems.Where(x => x is SurveyQuestion).Where(x => x.Field.Contains(q));

I might expand that a bit for readability, like so:

string q = "[some search term]";
IEnumerable<SurveyQuestion> surveyQuestions = Context.SurveyItems.Where(x => x is SurveyQuestion);
IEnumerable<SurveyQuestion> matchingSurveyQuestions = surveyQuestions.Where(x => x.Field.Contains(q));

Or for even better readability (at least in my eyes - I like shorter code):

var searchTerm = "[some search term]";
var questions = Context.SurveyItems.Where(si => si is SurveyQuestion);
var matchingQuestions = questions.Where(q => q.Field.Contains(searchTerm));


答:
An alternative using dplyr ...</p>
```<code>library(dplyr)

NEW_df <-
    NEW_df %>%
    mutate(BOAT = if_else(CAR=='NO' & is.na(BOAT), 0, BOAT))
</code>```

Title: replace blank with 0 based on value in another column

Body:
I have a df like this:

                 NEW_df <- data.frame(CAR = c("YES","NO","NO","YES","NO"),
                                     BIKE = c(2,0,4,NA,9),
                                     PLANE = c(8,0,6,7,9),
                                   BOAT = c(NA,NA,NA,4,3),
                                   SCOOTER = c(2,3,6,9,0))

I will like to replace NA's in column BOAT with '0'if the column CAR is 'NO', so I can have something like this:

                 NEW_df <- data.frame(CAR = c("YES","NO","NO","YES","NO"),
                                     BIKE = c(2,0,4,NA,9),
                                     PLANE = c(8,0,6,7,9),
                                   BOAT = c(NA,0,0,4,3),
                                   SCOOTER = c(2,3,6,9,0))

I thought something like this, but it didnt work:

NEW_df %>%
  mutate(across(BOAT, ~ if_else(CAR == NO & is.na(.), 0, .)))

Is it even possible to place the replaced values in a new column too.

Body:
An alternative using dplyr ...

library(dplyr)

NEW_df <-
    NEW_df %>%
    mutate(BOAT = if_else(CAR=='NO' & is.na(BOAT), 0, BOAT))