问:
How it works ResponseBody and what it returns
I have a problem. The thing is that @Reponsebody return the HTML DOM, but i dont want this. But if i remove the response body it return an error in the controller.
Here is the controller:

```<code>@GetMapping(value = "/isvoted")
public @ResponseBody List<Boolean> isvoted() {

    Authentication auth= SecurityContextHolder.getContext().getAuthentication();
    UserDetails userDetails = (UserDetails)auth.getPrincipal();
    Usuario usuario = (Usuario)usuarioService.findByUsername(userDetails.getUsername());
    Long id = usuario.getId();

    List<Tapas> tapas = tapaService.findAllTapas();
    List<Boolean> listavotos = new ArrayList<Boolean>();

    for (Tapas tapa : tapas) {
        if (voteService.selectVoteByUserAndTapa(id, tapa.getId()) != null) {
            listavotos.add(true);
        }else {
            listavotos.add(false);
        }
    }
    return listavotos;
</code>```

So, the method return a list of booleans and ajax get the reponse, but the reponse also return the body of the html, how can i implement for returning only the listavotos (list of boolean) without including the body of the HTML.

this is my ajax get request:

```<code>const full = $('input[name="voto"]').attr("value", "\uf004").css({"font-family": "'Font Awesome 5 Free'"});

    $.ajax({
        type: "GET",
        url: "/isvoted",
        success: function(result) {

            if (result === undefined || result.length == 0){
                console.log("no hay votos");
            }else{
                for (var voto of result) {
                  if(voto === true){
                      console.log("voto true");
                      full.css({"font-weight": "900"});
                  }else{
                      console.log("voto false");
                      full.css({"font-weight": ''});
                  }
                }
            }

        },
        error: function(result) {
            console.log("error");
        }
    });
</code>```

To resume, when the document is ready, it is called the ajax get request for kwnowing if theres votes, if there are votes it return the list of boolean (response), that it gets it from the controller isvoted, but also return the reponsebody (the html body), but i dont want this. I want that the controller only return the list to kwnow if an element it voted, and if its voted to have an css style, if isn voted, to have another style. Really thankfull for your help. If you need more information just posted and i will clarify.

the full controller (is not a restcontroller):

```<code>@Controller
</code>```

public class VoteController {

```<code>@Autowired
private IVoteService voteService;

@Autowired
private IUsuarioService usuarioService;

@Autowired
private ITapasService tapaService;

private final Logger log = LoggerFactory.getLogger(getClass());

@GetMapping(value = "/isvoted")
@ResponseBody
public List<Boolean> isvoted(@RequestBody List<Boolean> listavotos) {

    Authentication auth= SecurityContextHolder.getContext().getAuthentication();
    UserDetails userDetails = (UserDetails)auth.getPrincipal();
    Usuario usuario = (Usuario)usuarioService.findByUsername(userDetails.getUsername());
    Long id = usuario.getId();

    List<Tapas> tapas = tapaService.findAllTapas();
    listavotos = new ArrayList<Boolean>();

    for (Tapas tapa : tapas) {
        if (voteService.selectVoteByUserAndTapa(id, tapa.getId()) != null) {
            listavotos.add(true);
        }else {
            listavotos.add(false);
        }
    }
    return listavotos;

}

@PostMapping(value = "/votecreate")
public String guardar(@Valid Vote vote, BindingResult result, Model model,
        @RequestParam(name = "tapa", required = true) Tapas tapa,
        RedirectAttributes flash, SessionStatus status) {

    if (result.hasErrors()) {
        List<ObjectError> errors = result.getAllErrors();
        for(ObjectError error : errors) {
            System.out.println("This is the error: " +error);
        }
        return "redirect:/home";
    }

    //String mensajeFlash = (vote.getId() != null) ? "voto quitado con con exito" : "votado con exito!";

    Authentication auth= SecurityContextHolder.getContext().getAuthentication();
    UserDetails userDetails = (UserDetails)auth.getPrincipal();
    Usuario usuario = (Usuario)usuarioService.findByUsername(userDetails.getUsername());

    //Tapas tapa = tapaService.findTapaById(Long.parseLong(tapaid));

    vote.setTapa(tapa);
    vote.setUsuario(usuario);

    voteService.save(vote);
    status.setComplete();
    //flash.addFlashAttribute("success", mensajeFlash);

    return "redirect:/home";
}

@GetMapping(value = "/votedelete/{tapaId}")
public String eliminar(@PathVariable(value = "tapaId") Long tapaId, RedirectAttributes flash) {

    //Tapas tapa = tapaService.findTapaById(tapaId);

    Authentication auth= SecurityContextHolder.getContext().getAuthentication();
    UserDetails userDetails = (UserDetails)auth.getPrincipal();
    Usuario usuario = (Usuario)usuarioService.findByUsername(userDetails.getUsername());
    Long userId = usuario.getId();
    log.debug("Usuario id:", userId);

    if (userId != null && tapaId != null) {

        Vote vote = voteService.selectVoteByUserAndTapa(userId, tapaId);
        log.debug("vote:", vote.getId());
        voteService.delete(vote.getId());
        flash.addFlashAttribute("success", "Voto eliminado con exito");

        return "redirect:/home/";
    }

    flash.addFlashAttribute("error", "El bar no existe en la base de datos");
    return "redirect:/bares/";
}
</code>```

}

答:
The thing was that when in the controller on the mapping /isvoted the jQuery can be execute when the user is logged (it get auth details) and exists tapas (get id of the tapas), because the query of the repository can be made successfully but when a user isn't logged, it returns a string of the layout of thymeleaf, so I just only add a condition for knowing if the return of the controller is a string(DOM of the thymelead) and not a list of bool it console log a message that a user is not authenticated so there is not option for showing the result (list of booleans)</p>

```<code>if (result === undefined || result.length == 0)
    console.log("no hay votos");
else if (typeof(result) == "string")
    console.log("you are not logger, you should be logged to see the VOTES");
else
    for (var voto of result) {
        console.log(result);

        if (voto === true) {
            full.prop('disabled', true);
            console.log(voto);
        } else {
            full.prop('disabled', false);
            console.log(voto);
        }
    }
</code>```

Body:
I have a problem. The thing is that @Reponsebody return the HTML DOM, but i dont want this. But if i remove the response body it return an error in the controller.
Here is the controller:

@GetMapping(value = "/isvoted")
public @ResponseBody List<Boolean> isvoted() {

    Authentication auth= SecurityContextHolder.getContext().getAuthentication();
    UserDetails userDetails = (UserDetails)auth.getPrincipal();
    Usuario usuario = (Usuario)usuarioService.findByUsername(userDetails.getUsername());
    Long id = usuario.getId();

    List<Tapas> tapas = tapaService.findAllTapas();
    List<Boolean> listavotos = new ArrayList<Boolean>();

    for (Tapas tapa : tapas) {
        if (voteService.selectVoteByUserAndTapa(id, tapa.getId()) != null) {
            listavotos.add(true);
        }else {
            listavotos.add(false);
        }
    }
    return listavotos;

So, the method return a list of booleans and ajax get the reponse, but the reponse also return the body of the html, how can i implement for returning only the listavotos (list of boolean) without including the body of the HTML.

this is my ajax get request:

const full = $('input[name="voto"]').attr("value", "\uf004").css({"font-family": "'Font Awesome 5 Free'"});

    $.ajax({
        type: "GET",
        url: "/isvoted",
        success: function(result) {

            if (result === undefined || result.length == 0){
                console.log("no hay votos");
            }else{
                for (var voto of result) {
                  if(voto === true){
                      console.log("voto true");
                      full.css({"font-weight": "900"});
                  }else{
                      console.log("voto false");
                      full.css({"font-weight": ''});
                  }
                }
            }

        },
        error: function(result) {
            console.log("error");
        }
    });

To resume, when the document is ready, it is called the ajax get request for kwnowing if theres votes, if there are votes it return the list of boolean (response), that it gets it from the controller isvoted, but also return the reponsebody (the html body), but i dont want this. I want that the controller only return the list to kwnow if an element it voted, and if its voted to have an css style, if isn voted, to have another style. Really thankfull for your help. If you need more information just posted and i will clarify.

the full controller (is not a restcontroller):

@Controller

public class VoteController {

@Autowired
private IVoteService voteService;

@Autowired
private IUsuarioService usuarioService;

@Autowired
private ITapasService tapaService;

private final Logger log = LoggerFactory.getLogger(getClass());

@GetMapping(value = "/isvoted")
@ResponseBody
public List<Boolean> isvoted(@RequestBody List<Boolean> listavotos) {

    Authentication auth= SecurityContextHolder.getContext().getAuthentication();
    UserDetails userDetails = (UserDetails)auth.getPrincipal();
    Usuario usuario = (Usuario)usuarioService.findByUsername(userDetails.getUsername());
    Long id = usuario.getId();

    List<Tapas> tapas = tapaService.findAllTapas();
    listavotos = new ArrayList<Boolean>();

    for (Tapas tapa : tapas) {
        if (voteService.selectVoteByUserAndTapa(id, tapa.getId()) != null) {
            listavotos.add(true);
        }else {
            listavotos.add(false);
        }
    }
    return listavotos;

}

@PostMapping(value = "/votecreate")
public String guardar(@Valid Vote vote, BindingResult result, Model model,
        @RequestParam(name = "tapa", required = true) Tapas tapa,
        RedirectAttributes flash, SessionStatus status) {

    if (result.hasErrors()) {
        List<ObjectError> errors = result.getAllErrors();
        for(ObjectError error : errors) {
            System.out.println("This is the error: " +error);
        }
        return "redirect:/home";
    }

    //String mensajeFlash = (vote.getId() != null) ? "voto quitado con con exito" : "votado con exito!";

    Authentication auth= SecurityContextHolder.getContext().getAuthentication();
    UserDetails userDetails = (UserDetails)auth.getPrincipal();
    Usuario usuario = (Usuario)usuarioService.findByUsername(userDetails.getUsername());

    //Tapas tapa = tapaService.findTapaById(Long.parseLong(tapaid));

    vote.setTapa(tapa);
    vote.setUsuario(usuario);

    voteService.save(vote);
    status.setComplete();
    //flash.addFlashAttribute("success", mensajeFlash);

    return "redirect:/home";
}

@GetMapping(value = "/votedelete/{tapaId}")
public String eliminar(@PathVariable(value = "tapaId") Long tapaId, RedirectAttributes flash) {

    //Tapas tapa = tapaService.findTapaById(tapaId);

    Authentication auth= SecurityContextHolder.getContext().getAuthentication();
    UserDetails userDetails = (UserDetails)auth.getPrincipal();
    Usuario usuario = (Usuario)usuarioService.findByUsername(userDetails.getUsername());
    Long userId = usuario.getId();
    log.debug("Usuario id:", userId);

    if (userId != null && tapaId != null) {

        Vote vote = voteService.selectVoteByUserAndTapa(userId, tapaId);
        log.debug("vote:", vote.getId());
        voteService.delete(vote.getId());
        flash.addFlashAttribute("success", "Voto eliminado con exito");

        return "redirect:/home/";
    }

    flash.addFlashAttribute("error", "El bar no existe en la base de datos");
    return "redirect:/bares/";
}

}

Body:
The thing was that when in the controller on the mapping /isvoted the jQuery can be execute when the user is logged (it get auth details) and exists tapas (get id of the tapas), because the query of the repository can be made successfully but when a user isn't logged, it returns a string of the layout of thymeleaf, so I just only add a condition for knowing if the return of the controller is a string(DOM of the thymelead) and not a list of bool it console log a message that a user is not authenticated so there is not option for showing the result (list of booleans)

if (result === undefined || result.length == 0)
    console.log("no hay votos");
else if (typeof(result) == "string")
    console.log("you are not logger, you should be logged to see the VOTES");
else
    for (var voto of result) {
        console.log(result);

        if (voto === true) {
            full.prop('disabled', true);
            console.log(voto);
        } else {
            full.prop('disabled', false);
            console.log(voto);
        }
    }


来源: stackexchange

问:
I get this error when trying to set up a virtual environment using cmd on windows 10
```<code>'setprojectdir' is not recognized as an internal or external command,
operable program or batch file.
</code>```

I have activated the environment and was following this tutorial

答: setprojectdir is a command from virtualenvwrapper. Do you have virtualenvwrapper-win installed? Check its bat-files are in the %PATH%.

ContentLicense: CC BY-SA 4.0

Body:
'setprojectdir' is not recognized as an internal or external command,
operable program or batch file.

I have activated the environment and was following this tutorial


问:
How to get all websphere application configuration using Jython?
I need to collect all the WAS configuration detail in json format. I thought of using Jython for that. Can you please help how I can achieve it.</p>

答: This functionality doesn't exist in WAS. The closest you will come is by using wsadmin to extract the configuration to a properties file. If you then need that in JSON you will have to convert it manually. Note that properties-based configuration doesn't include some configuration in the cell.</p>


问:
Redirect after form submit React Native
I have a simple connection form, I want my user to be redirected to my homepage after connection.
action in my form doesn't seem to work as the URL doesn't change after sending the form.

Here is the content of my Login class in my Login.tsx file

```<code>constructor(props) {
    super(props);
    this.state = {
      email: "",
      password: ""
    }
  }

  handleSubmit() {
    const email = this.state.email;
    console.log(email);
    const password = this.state.password;
    console.log(password);
    axios.post("http://snapi.epitech.eu/connection", { email, password }
        ).then(reponse => {
            console.log('connect', reponse);
        }).catch(error => {
            console.log('error', error);
    });

}

  render() {
    //const { dataSource, fromFetch, fromAxios, loading, axiosData } = this.state
    return (
    <View style={styles.container}>
      <Text>Connection</Text>
      <form onSubmit={ this.handleSubmit }
            action="localhost:19006/home">
        <label>email</label>
        <TextInput
          //name="email"
          style={styles.input}
          value={ this.state.email }
          onChangeText={ email => this.setState({email}) }
          //onChange={val => this.onChange('email', val)}
        />
        <label>password</label>
        <TextInput
          style={styles.input}
          secureTextEntry={true}
          value={ this.state.password }
          onChangeText={ password => this.setState({password}) }
          //onChange={val => this.onChange('password', val)}
        />
        <Button title="Inscription"
          type="submit"
          onPress={this.handleSubmit.bind(this)}
        />
      </form>
    </View>
  );
  }
};
</code>```

答:
You need to use react native navigation like below:</p>

```<code>import { NavigationActions } from 'react-navigation';
const routeName = "Home" // string e.g 'Home'
const params = {         // object (key value pair)
     key1: value1,
     key2: value2
}
NavigationActions.navigate({ routeName, params }),

or

this.props.navigation.navigate(routeName, params)

</code>```

Title: Redirect after form submit React Native

Body:
I have a simple connection form, I want my user to be redirected to my homepage after connection.
action in my form doesn't seem to work as the URL doesn't change after sending the form.

Here is the content of my Login class in my Login.tsx file

constructor(props) {
    super(props);
    this.state = {
      email: "",
      password: ""
    }
  }

  handleSubmit() {
    const email = this.state.email;
    console.log(email);
    const password = this.state.password;
    console.log(password);
    axios.post("http://snapi.epitech.eu/connection", { email, password }
        ).then(reponse => {
            console.log('connect', reponse);
        }).catch(error => {
            console.log('error', error);
    });

}

  render() {
    //const { dataSource, fromFetch, fromAxios, loading, axiosData } = this.state
    return (
    <View style={styles.container}>
      <Text>Connection</Text>
      <form onSubmit={ this.handleSubmit }
            action="localhost:19006/home">
        email
        <TextInput
          //name="email"
          style={styles.input}
          value={ this.state.email }
          onChangeText={ email => this.setState({email}) }
          //onChange={val => this.onChange('email', val)}
        />
        password
        <TextInput
          style={styles.input}
          secureTextEntry={true}
          value={ this.state.password }
          onChangeText={ password => this.setState({password}) }
          //onChange={val => this.onChange('password', val)}
        />
        <Button title="Inscription"
          type="submit"
          onPress={this.handleSubmit.bind(this)}
        />
      </form>
    </View>
  );
  }
};

Body:
You need to use react native navigation like below:

import { NavigationActions } from 'react-navigation';
const routeName = "Home" // string e.g 'Home'
const params = {         // object (key value pair)
     key1: value1,
     key2: value2
}
NavigationActions.navigate({ routeName, params }),

or

this.props.navigation.navigate(routeName, params)


问:
numpy random matrix with bounds along each axis
with

a = numpy.random.randomint(lo,hi,(m,n))

I can create a numpy matrix of size m, populated with random values between 'hi' and 'lo'.

Is there a way to create a numpy matrix with say random values such that

along column 1 I have numbers btween 'hi1', 'lo1' and

along column 2 I have numbers between 'hi2' and 'lo2' etc.

i.e. each column will have its own hi,low.

Any help will be much appreciated.

答:
You can provide an array for lo & hi (depending on numpy version -- check with numpy.version.version). See the documentation: https://numpy.org/devdocs/reference/random/generated/numpy.random.randint.html.

So for the new version of numpy you could write something like this:

```<code>low = [0,1,2,3]
high = [4,5,6,7]
a = numpy.random.randint(low, high, size=(3,4))
</code>```

And for an older version of numpy this could work:

```<code>low = [0,1,2,3]
high = [4,5,6,7]
a = numpy.concatenate([numpy.random.randint(low[idx], high[idx], size=(3,1)) for idx in range(4)], axis=1)
</code>```

Body:
You can provide an array for lo & hi (depending on numpy version -- check with numpy.version.version). See the documentation: https://numpy.org/devdocs/reference/random/generated/numpy.random.randint.html.

So for the new version of numpy you could write something like this:

low = [0,1,2,3]
high = [4,5,6,7]
a = numpy.random.randint(low, high, size=(3,4))

And for an older version of numpy this could work:

low = [0,1,2,3]
high = [4,5,6,7]
a = numpy.concatenate([numpy.random.randint(low[idx], high[idx], size=(3,1)) for idx in range(4)], axis=1)


问:
Flutter: Move dialog up to make room for soft keyboard?
Is there a way to move a Dialog (an AlertDialog in my case) up to make room for the soft keyboard when it is visible?

答: add this margin margin: MediaQuery.of(context).viewInsets, , it worked for me in a custom Alert Dialog .

ContentLicense: CC BY-SA 3.0


问:
How to change the size of FloatingActionButton?
I'm trying to set a size to a FloatingActionButton in flutter, I wanna set width/height, I mean, make the button bigger, I was looking for a circular button, but the only one that I got was this one, so, I started to work with this, but I need it a little bigger.

答:
Most of the answers here using hardcoded values, but actually we have to apply generic solutions here, which should be constant in all the UI.

```<code>Scaffold(
      floatingActionButton: Container(
        height: MediaQuery.of(context).size.width * 0.2,
        width: MediaQuery.of(context).size.width * 0.2,
        child: FloatingActionButton(onPressed: () {}),
      ),
</code>```

Set width and height using MediaQuery which will be same across the devices.

Output:

Body:
Most of the answers here using hardcoded values, but actually we have to apply generic solutions here, which should be constant in all the UI.

Scaffold(
      floatingActionButton: Container(
        height: MediaQuery.of(context).size.width * 0.2,
        width: MediaQuery.of(context).size.width * 0.2,
        child: FloatingActionButton(onPressed: () {}),
      ),

Set width and height using MediaQuery which will be same across the devices.

Output:


问:
NodeJS - Child node process?
I'm using NodeJS to run a socket server (using socket.io). When a client connects, I want am opening and running a module which does a bunch of stuff. Even though I am careful to try and catch as much as possible, when this module throws an error, it obviously takes down the entire socket server with it.

Is there a way I can separate the two so if the connected clients module script fails, it doesn't necessarily take down the entire server?

I'm assuming this is what child process is for, but the documentation doesn't mention starting other node instances.

I'd obviously need to kill the process if the client disconnected too.

答:
As the other poster noted, you could leverage the 'vm' module, but as you might be able to tell from the rest of the response, doing so adds significant complexity.

Also, from the 'vm' doc:

```
Note that running untrusted code is a tricky business requiring great care.
To prevent accidental global variable leakage, vm.runInNewContext is quite
useful, but safely running untrusted code requires a separate process.
```

While I'm sure you could run a new nodejs instance in a child process, the best practice here is to understand where your application can and will fail, and then program defensively to handle all possible error conditions.

If some part of your code "take(s) down the entire ... server", then you really to understand why this occurred and solve that problem rather than rely on another process to shield you from the work required to design and build a production-quality service.

Title: NodeJS - Child node process?

Body:
As the other poster noted, you could leverage the 'vm' module, but as you might be able to tell from the rest of the response, doing so adds significant complexity.

Also, from the 'vm' doc:

Note that running untrusted code is a tricky business requiring great care.
To prevent accidental global variable leakage, vm.runInNewContext is quite
useful, but safely running untrusted code requires a separate process.

While I'm sure you could run a new nodejs instance in a child process, the best practice here is to understand where your application can and will fail, and then program defensively to handle all possible error conditions.

If some part of your code "take(s) down the entire ... server", then you really to understand why this occurred and solve that problem rather than rely on another process to shield you from the work required to design and build a production-quality service.


问:
prop.test display the confidence interval in percentage terms instead of decimal in R?
I am wondering if there is a way to change the output settings of the prop.test function in R so that it displays the confidence interval already in percentage terms instead of a decimal? For example, I am trying to find the 95% confidence interval for the proportion of immigrants in the West with diabetes. Here is my code and the output: </p>

```<code>    sum(Immigrant_West$DIABETES)= 8, nrow(Immigrant_West)=144
prop.test(x=sum(Immigrant_West$DIABETES),n=nrow(Immigrant_West),conf.level = .95,correct=TRUE)

    > 1-sample proportions test with continuity correction
    data:  sum(Immigrant_West$DIABETES) out of nrow(Immigrant_West), null probability 0.5
   X-squared = 112, df = 1, p-value <2e-16
alternative hypothesis: true p is not equal to 0.5
95 percent confidence interval:
 0.02606 0.11017
sample estimates:
      p
0.05556
</code>```

<p>So is there a way to change the confidence interval output to show [2.606%, 11.017%] instead of as decimals? Thank you! </p>

答:
Not easily.  The print format is controlled by the print.htest() function, which is documented in ?print.htest: it doesn't seem to offer any options other than the number of digits and the prefix for the "method" component.

If you want, you can hack the function yourself. (More details to follow, maybe; dump stats:::print.htest to a file, then edit it, then source() it.

As suggested by @CarlWitthoft:

```<code>p <- prop.test(x=8,n=144)
str(p) ## see what's there
p$estimate <- p$estimate*100
p$conf.int <- p$conf.int*100
</code>```

Body:
I am wondering if there is a way to change the output settings of the prop.test function in R so that it displays the confidence interval already in percentage terms instead of a decimal? For example, I am trying to find the 95% confidence interval for the proportion of immigrants in the West with diabetes. Here is my code and the output:

    sum(Immigrant_West$DIABETES)= 8, nrow(Immigrant_West)=144
prop.test(x=sum(Immigrant_West$DIABETES),n=nrow(Immigrant_West),conf.level = .95,correct=TRUE)

    > 1-sample proportions test with continuity correction
    data:  sum(Immigrant_West$DIABETES) out of nrow(Immigrant_West), null probability 0.5
   X-squared = 112, df = 1, p-value <2e-16
alternative hypothesis: true p is not equal to 0.5
95 percent confidence interval:
 0.02606 0.11017
sample estimates:
      p
0.05556

So is there a way to change the confidence interval output to show [2.606%, 11.017%] instead of as decimals? Thank you!

Body:
Not easily.  The print format is controlled by the print.htest() function, which is documented in ?print.htest: it doesn't seem to offer any options other than the number of digits and the prefix for the "method" component.

If you want, you can hack the function yourself. (More details to follow, maybe; dump stats:::print.htest to a file, then edit it, then source() it.

As suggested by @CarlWitthoft:

p <- prop.test(x=8,n=144)
str(p) ## see what's there
p$estimate <- p$estimate*100
p$conf.int <- p$conf.int*100


问:
How to order a list of objects with matching keys from another list?
I need to sort an existing list of object based on another list of objects (with matching keys), but both lists may or may not contain the same keys and number of items. Example:

```<code>struct Item
{
    public string _id;
    public Item(string id) { _id = id; }
}

List<Item> totalItems = new List<Item>()
{
    new Item("foo"), new Item("bar"),
    new Item("baz"), new Item("monkey"),
    new Item("cat"), new Item("apple")
};

List<string> preferredSortOrder = new List<string>()
{
    "monkey",
    "cat",
    "zebra",
    "baz"
};
</code>```

So the output would be:

```<code>monkey
cat
baz
apple
bar
foo
</code>```

This is because the sort order from preferredSortOrder takes precedence, so monkey, cat, and baz are first in the list because they exist in totalItems. If something in preferredSortOrder list doesn't exist in totalItems, it should be ignored. All remaining items in totalItems should then be ordered alphabetically (as you can see above).

I haven't coded in linq for years and everything I've tried so far hasn't worked.

Edit: Based on Calimero's answer, here is the solution:

```<code>totalItems = totalItems
.OrderBy(item => item._id)
.OrderBy(item => {
    var i = preferredSortOrder.IndexOf(item._id);
    return i == -1 ? totalItems.Count : i;
}).ToList();
</code>```

答:
Use List.IndexOf method of your reference list as your keySelector function parameter of Enumerable.OrderBy with Linq.

```<code>totalItems.OrderBy(item => preferredSortOrder.IndexOf(item._id)).ToList();
</code>```

EDIT : This would put the elements that are not in the reference list first (because IndexOf will return -1). But you can easily return a value that is greater than any possible index for this case

```<code>totalItems.OrderBy(item =>
{
   var index = preferredSortOrder.IndexOf(item._id);
   return index == -1 ? totalItems.Count : index
}).ToList();
</code>```

You can make an extension method out of this if you have repeated usage.

EDIT 2 : I didnt pay attention that your _id is private (you didnt specify accessibility and it is default accessibility here). You probably want to have a property that uses it as a backing field, or make it public

Body:
I need to sort an existing list of object based on another list of objects (with matching keys), but both lists may or may not contain the same keys and number of items. Example:

struct Item
{
    public string _id;
    public Item(string id) { _id = id; }
}

List<Item> totalItems = new List<Item>()
{
    new Item("foo"), new Item("bar"),
    new Item("baz"), new Item("monkey"),
    new Item("cat"), new Item("apple")
};

List<string> preferredSortOrder = new List<string>()
{
    "monkey",
    "cat",
    "zebra",
    "baz"
};

So the output would be:

monkey
cat
baz
apple
bar
foo

This is because the sort order from preferredSortOrder takes precedence, so monkey, cat, and baz are first in the list because they exist in totalItems. If something in preferredSortOrder list doesn't exist in totalItems, it should be ignored. All remaining items in totalItems should then be ordered alphabetically (as you can see above).

I haven't coded in linq for years and everything I've tried so far hasn't worked.

Edit: Based on Calimero's answer, here is the solution:

totalItems = totalItems
.OrderBy(item => item._id)
.OrderBy(item => {
    var i = preferredSortOrder.IndexOf(item._id);
    return i == -1 ? totalItems.Count : i;
}).ToList();

Body:
Use List.IndexOf method of your reference list as your keySelector function parameter of Enumerable.OrderBy with Linq.

totalItems.OrderBy(item => preferredSortOrder.IndexOf(item._id)).ToList();

EDIT : This would put the elements that are not in the reference list first (because IndexOf will return -1). But you can easily return a value that is greater than any possible index for this case

totalItems.OrderBy(item =>
{
   var index = preferredSortOrder.IndexOf(item._id);
   return index == -1 ? totalItems.Count : index
}).ToList();

You can make an extension method out of this if you have repeated usage.

EDIT 2 : I didnt pay attention that your _id is private (you didnt specify accessibility and it is default accessibility here). You probably want to have a property that uses it as a backing field, or make it public


问:
Callable function from yaml
I'm trying to implement a CommandHandler that reads a command dictionary from a .yml and should call the method based on the user input

commands.yml:

```<code>'help': {
    'message': 'message',
    'help': 'help-message',
    'action': help_command
},
'news': {
    'message': 'news-message',
    'help': 'help-message',
    'action': news_command
}
</code>```

CommandHandler.py:

```<code>def handle_command(self, command, parameters, message):
    self.commands.get(command).get('action')(parameters, message)
</code>```

I get a TypeError: 'str' is not callable. With.json its the same error.
Saving it as commands.py and importing it gets me a NameError: name 'help_command' is not defined.

However, if I just throw the dict into the code directly it works fine.
Is there any solution besides defining the dict in the code directly?

答:
help_command in YAML loads as a string. YAML does not know about symbols defined in the Python file where it is loaded and anyway won't map strings to symbols.

You can, of course, do

def handle_command(self, command, parameters, message):
    eval(self.commands.get(command).get('action'))(parameters, message)
```

Be aware of eval's security implications though. You should never run this if the YAML comes from an untrusted source, it can do anything.

Title: Callable function from yaml

Body:
I'm trying to implement a CommandHandler that reads a command dictionary from a .yml and should call the method based on the user input

commands.yml:

'help': {
    'message': 'message',
    'help': 'help-message',
    'action': help_command
},
'news': {
    'message': 'news-message',
    'help': 'help-message',
    'action': news_command
}

CommandHandler.py:

def handle_command(self, command, parameters, message):
    self.commands.get(command).get('action')(parameters, message)

I get a TypeError: 'str' is not callable. With.json its the same error.
Saving it as commands.py and importing it gets me a NameError: name 'help_command' is not defined.

However, if I just throw the dict into the code directly it works fine.
Is there any solution besides defining the dict in the code directly?

Body:
help_command in YAML loads as a string. YAML does not know about symbols defined in the Python file where it is loaded and anyway won't map strings to symbols.

You can, of course, do

def handle_command(self, command, parameters, message):
    eval(self.commands.get(command).get('action'))(parameters, message)

Be aware of eval's security implications though. You should never run this if the YAML comes from an untrusted source, it can do anything.


问:
Loop over a List getting an increasing number of elements each time
Let's say I have a list that looks like

```<code>{A, B, C, D, E}
</code>```

And I want to loop over this list, getting an increasing number of elements each time, so each iteration would look like:

```<code>Iteration 1: {A}
Iteration 2: {A, B}
Iteration 3: {A, B, C}
Iteration 4: {A, B, C, D}
Iteration 5: {A, B, C, D, E}
</code>```

Currently I am accomplishing this with:

```<code>(1 to list.size).foreach( n => {
  val elements = list.take(n)
  // Do something with elements
})
</code>```

But that feels messy. Is there a more 'scala' way of accomplishing this behavior?

答:
Here is a recursive version. You will need to reverse the list first.</p>

```<code>@tailrec
def doIt(l: List[Int], acc: List[List[Int]] = Nil): List[List[Int]] = l match {
  case Nil => acc
  case h :: t => doIt(t, List(h) :: acc.map(l => h :: l))
}

doIt(List(1,2,3).reverse).foreach(println)

// output
List(1)
List(1, 2)
List(1, 2, 3)
</code>```

Body:
Let's say I have a list that looks like

{A, B, C, D, E}

And I want to loop over this list, getting an increasing number of elements each time, so each iteration would look like:

Iteration 1: {A}
Iteration 2: {A, B}
Iteration 3: {A, B, C}
Iteration 4: {A, B, C, D}
Iteration 5: {A, B, C, D, E}

Currently I am accomplishing this with:

(1 to list.size).foreach( n => {
  val elements = list.take(n)
  // Do something with elements
})

But that feels messy. Is there a more 'scala' way of accomplishing this behavior?

Body:
Here is a recursive version. You will need to reverse the list first.

@tailrec
def doIt(l: List[Int], acc: List[List[Int]] = Nil): List[List[Int]] = l match {
  case Nil => acc
  case h :: t => doIt(t, List(h) :: acc.map(l => h :: l))
}

doIt(List(1,2,3).reverse).foreach(println)

// output
List(1)
List(1, 2)
List(1, 2, 3)


问:
Spark Scala : how to slice an array in array of array
for an array of array:

```<code>val arrarr = Array(Array(0.37,1),Array(145.38,100),Array(149.37,100),Array(149.37,300),Array(119.37,5),Array(144.37,100))
</code>```

For example, if the input value is 149.37, I want to do some sort of indexing to get 300. 149.37 occurs two times in arrarr(Array(149.37,100),Array(149.37,300). I want to return the last value using spark scala.

Can you please help? Thanks!

答:
you can do it like this : </p>

```<code>val result : Doulbe = arrarr.filter(_(0) == 149.37).last(1)
</code>```

<p>or </p>

```<code>val result: Option[Double] = arrarr.reverse.find(_ (0) == 149.37).map(_ (1))
</code>```

Body:
for an array of array:

val arrarr = Array(Array(0.37,1),Array(145.38,100),Array(149.37,100),Array(149.37,300),Array(119.37,5),Array(144.37,100))

For example, if the input value is 149.37, I want to do some sort of indexing to get 300. 149.37 occurs two times in arrarr(Array(149.37,100),Array(149.37,300). I want to return the last value using spark scala.

Can you please help? Thanks!

Body:
you can do it like this :

val result : Doulbe = arrarr.filter(_(0) == 149.37).last(1)

or

val result: Option[Double] = arrarr.reverse.find(_ (0) == 149.37).map(_ (1))


问:
Computer try to guess user number in C
I made a programme to guess user number.
I miss something in my code, but i dont know what.
If i give input b (bigger) or s (lower), its still give me the same result.
Can you tell me please what should i add to Code to work correctly?</p>

```<code>#include <stdio.h>
#include <ctype.h>

int main(void)
{
  char answer, input;
  int untere_grenze=1, upper_limit=999, tipp=0, try1=0;

  printf("\n\nThis program tries to guess a number you choose between 1 and 999\n\n");
  do
  {
    try1=0;
    do
    {
      //I think here is my problem

      try1+=1;
      tipp=untere_grenze+(upper_limit-untere_grenze)/2;

      printf("\n%d. try: %d\n", try1, tipp);

      upper_limit=tipp-1;
      untere_grenze=tipp+1;

      //I think here is my problem

      do
      {
        printf("Please enter s (number to be guessed is smaller), b (number to be guessed is larger) or = (guess!):");
        scanf(" %c", &input);
        input=toupper(input);
      } while (input!='S' && input!='B' && input!='=');

    } while(input!='=');

    printf("\n\nThe computer guessed your number in %d attempts.\n\n", try1);
    do
    {
      printf("Do you want to run the program again (J/N)?\n\n");
      scanf(" %c", &answer);
      answer=toupper(answer);
    } while (answer!='J' && answer!='N');
  }  while (answer=='J');

  return 0;
}
</code>```

答:
I don't see your program doing anything with the input.
You should guess lower or higher in the next iteration based on the input.</p>

Title: Computer try to guess user number in C

Body:
I made a programme to guess user number.
I miss something in my code, but i dont know what.
If i give input b (bigger) or s (lower), its still give me the same result.
Can you tell me please what should i add to Code to work correctly?

#include <stdio.h>
#include <ctype.h>

int main(void)
{
  char answer, input;
  int untere_grenze=1, upper_limit=999, tipp=0, try1=0;

  printf("\n\nThis program tries to guess a number you choose between 1 and 999\n\n");
  do
  {
    try1=0;
    do
    {
      //I think here is my problem

      try1+=1;
      tipp=untere_grenze+(upper_limit-untere_grenze)/2;

      printf("\n%d. try: %d\n", try1, tipp);

      upper_limit=tipp-1;
      untere_grenze=tipp+1;

      //I think here is my problem

      do
      {
        printf("Please enter s (number to be guessed is smaller), b (number to be guessed is larger) or = (guess!):");
        scanf(" %c", &input);
        input=toupper(input);
      } while (input!='S' && input!='B' && input!='=');

    } while(input!='=');

    printf("\n\nThe computer guessed your number in %d attempts.\n\n", try1);
    do
    {
      printf("Do you want to run the program again (J/N)?\n\n");
      scanf(" %c", &answer);
      answer=toupper(answer);
    } while (answer!='J' && answer!='N');
  }  while (answer=='J');

  return 0;
}


问:
How do I optimize a "latest sales" sql query?
This query has become my nemesis over the past few years because I've never found a way to optimize it. Now my nemesis becomes your nemesis! :)

Consider the following table:

```<code>create table Sales (
  SaleId int identity(1,1) primary key,
  SalesmanId int not null,
  Amount smallmoney not null
)
</code>```

For the sake of argument, assume that this table has 10^100 rows (business is brisk) and therefore a table scan is out of the question.

Now we want to determine the SaleId of each salesman's most recent sale. Simple enough, right? Here is the query for that:

```<code>select
  SalesmanId,
  max(SaleId) SaleId
from Sales
group by Sales.SalesmanId
</code>```

When we run this query the query optimizer does a full table scan, which is expected because it has no way of knowing where each salesman's sales fall within the table. So let's help it out by adding the following index:

```<code>create unique nonclustered index IX_Sales on Sales
(
  SalesmanId asc,
  SaleId asc
)
</code>```

Now it should be trivial (for a human, anyway) to find the most recent values because we use the values of the first column of the index to identify all possible salesmen and the last entries of the second column to locate each salesman's latest sale. Unfortunately, the query optimizer still does an index seek over the entire index (all 10^100 rows) in this case, so it takes just as long.

Interestingly, if we write the query to find the latest sale for a given salesman,

```<code>select max(SaleId)
from Sales
where SalesmanId = 1
</code>```

the query optimizer uses an index seek on IX_Sales and gets it with one row of I/O. Even without IX_Sales, it does a clustered index scan that somehow gets it in one row of I/O (maybe using the table statistics?). But if we modify this to

```<code>select max(SaleId)
from Sales
where SalesmanId = 1
group by SalesmanId
</code>```

or

```<code>select max(SaleId)
from Sales
group by SalesmanId
having SalesmanId = 1
</code>```

we're back to a high row-count index seek over lots of rows (although less than if you'd omitted the filter altogether, again probably due to statistics).

So ... any ideas on how I could defeat my nemesis?

Update

Some have suggested joining against a table of possible SalesmanId values, like so

```<code>select Latest.*
from
(
  select
    SalesmanId,
    max(SaleId) SaleId
  from Sales
  group by SalesmanId
) Latest
inner join Salesmen on
  Salesmen.SalesmanId = Latest.SalesmanId
</code>```

I tested this idea but the query optimizer still chooses to do a full table scan.

答:
Because you stated this this:

```<code>select max(SaleId)
from Sales
where SalesmanId = 1
</code>```

Is fast, but the grouping is not... try putting that particular query in a view, then SELECT all the salesman and JOIN the view.
That should force the the query plan on the view for each JOIN. Normally I wouldn't think this approach would be the most efficient, but given how your queries are processing it just might work.

Body:
This query has become my nemesis over the past few years because I've never found a way to optimize it. Now my nemesis becomes your nemesis! :)

Consider the following table:

create table Sales (
  SaleId int identity(1,1) primary key,
  SalesmanId int not null,
  Amount smallmoney not null
)

For the sake of argument, assume that this table has 10^100 rows (business is brisk) and therefore a table scan is out of the question.

Now we want to determine the SaleId of each salesman's most recent sale. Simple enough, right? Here is the query for that:

select
  SalesmanId,
  max(SaleId) SaleId
from Sales
group by Sales.SalesmanId

When we run this query the query optimizer does a full table scan, which is expected because it has no way of knowing where each salesman's sales fall within the table. So let's help it out by adding the following index:

create unique nonclustered index IX_Sales on Sales
(
  SalesmanId asc,
  SaleId asc
)

Now it should be trivial (for a human, anyway) to find the most recent values because we use the values of the first column of the index to identify all possible salesmen and the last entries of the second column to locate each salesman's latest sale. Unfortunately, the query optimizer still does an index seek over the entire index (all 10^100 rows) in this case, so it takes just as long.

Interestingly, if we write the query to find the latest sale for a given salesman,

select max(SaleId)
from Sales
where SalesmanId = 1

the query optimizer uses an index seek on IX_Sales and gets it with one row of I/O. Even without IX_Sales, it does a clustered index scan that somehow gets it in one row of I/O (maybe using the table statistics?). But if we modify this to

select max(SaleId)
from Sales
where SalesmanId = 1
group by SalesmanId

or

select max(SaleId)
from Sales
group by SalesmanId
having SalesmanId = 1

we're back to a high row-count index seek over lots of rows (although less than if you'd omitted the filter altogether, again probably due to statistics).

So ... any ideas on how I could defeat my nemesis?

Update

Some have suggested joining against a table of possible SalesmanId values, like so

select Latest.*
from
(
  select
    SalesmanId,
    max(SaleId) SaleId
  from Sales
  group by SalesmanId
) Latest
inner join Salesmen on
  Salesmen.SalesmanId = Latest.SalesmanId

I tested this idea but the query optimizer still chooses to do a full table scan.

Body:
Because you stated this this:

select max(SaleId)
from Sales
where SalesmanId = 1

Is fast, but the grouping is not... try putting that particular query in a view, then SELECT all the salesman and JOIN the view.
That should force the the query plan on the view for each JOIN. Normally I wouldn't think this approach would be the most efficient, but given how your queries are processing it just might work.


答:
Add a second string field to struct Item, call it 'sortOrder'.

Create a class or struct for 'preferredSortOrder', add a second string field ('sortOrder') that indicates the sort order. Use numbers as they will sort ahead of alpha.

Do a first pass through 'totalItems', do a lookup on 'preferredSortOrder', copy the sortOrder. If the item is not found, copy its string (eg "apple").

Sort totalItems on sortOrder. Presto!

Title: How to order a list of objects with matching keys from another list?


问:
Persist Youtube Data API access token in Python desktop app
I have a Python application that accesses Youtube-Data-API v3.

After the program runs for an hour, it throws an error suggesting the access token has expired.

How can I persist the token for a longer period?

答:
There is now way to extend the time for access token. They get expired after an hour. The only way of using a token is to get a new token using refresh_token provided by the api.

First you get offline token by setting access_type to offine while authenticating  the user.

```<code>{
    'response_type': 'code',
    'client_id': 'client_id',
    'redirect_uri': '...',
    'access_type':'offline',
    'scope': 'https://www.googleapis.com/auth/youtube.readonly',
}
</code>```

you will get refresh_token, access_token, id_token along with expiry and some other fields which you can save in you database and fetch later when needed.

Before using the access_token you check if it is valid

```<code>creds = google.oauth2.credentials.Credentials(access_token,refresh_token=refresh_token,id_token=id_token,token_uri=token_uri,client_id=client_id,client_secret=client_secret,scopes=scopes,expiry=expirytime)
if creds.valid == False:
  // Refresh to get the new token
  req =google.auth.transport.requests.Request()
  creds.refresh(req)
  // Now Save new Credentials from "creds" so that you can use later.
</code>```

After verifying the access_token you can now query youtube data api requests

```<code>youtube = googleapiclient.discovery.build(
    "youtube", "v3",credentials=creds)
req = youtube.videos().getRating(id="xxxxxxxxx")
resp =req.execute()
</code>```

Body:
There is now way to extend the time for access token. They get expired after an hour. The only way of using a token is to get a new token using refresh_token provided by the api.

First you get offline token by setting access_type to offine while authenticating  the user.

{
    'response_type': 'code',
    'client_id': 'client_id',
    'redirect_uri': '...',
    'access_type':'offline',
    'scope': 'https://www.googleapis.com/auth/youtube.readonly',
}

you will get refresh_token, access_token, id_token along with expiry and some other fields which you can save in you database and fetch later when needed.

Before using the access_token you check if it is valid

creds = google.oauth2.credentials.Credentials(access_token,refresh_token=refresh_token,id_token=id_token,token_uri=token_uri,client_id=client_id,client_secret=client_secret,scopes=scopes,expiry=expirytime)
if creds.valid == False:
  // Refresh to get the new token
  req =google.auth.transport.requests.Request()
  creds.refresh(req)
  // Now Save new Credentials from "creds" so that you can use later.

After verifying the access_token you can now query youtube data api requests

youtube = googleapiclient.discovery.build(
    "youtube", "v3",credentials=creds)
req = youtube.videos().getRating(id="xxxxxxxxx")
resp =req.execute()


问:
Reverse dataframe and merge columns in R
Hello I have a df such as :

```<code>COL1 COL2 COL3 COL4
SP1  OK   2    87
SP2  NO   8    90
SP3  NO   2    56
SP4  OK   3    45
</code>```

and I would like to put COL2,COL3 and COL4 into one unique column called Categorie and add the values associated into a column calles Value;

```<code>COL1 Categorie Value
SP1  COL2     OK
SP2 COL2     NO
SP3 COL2     NO
SP4 COL2     OK
SP1 COL3     2
SP2 COL3     8
SP3 COL3     2
SP4 COL3     3
SP1 COL4     87
SP2 COL4     90
SP3 COL4     56
SP4 COL4     45
</code>```

答:
We can use pivot_longer

```<code>library(tidyr)
library(dplyr)
df %>%
     mutate_at(vars(COL2:COL4), as.character) %>%
     pivot_longer(cols = -COL1, names_to = 'Categorie', values_to = 'Value')
# A tibble: 12 x 3
#   COL1  Categorie Value
#   <chr> <chr>     <chr>
# 1 SP1   COL2      OK
# 2 SP1   COL3      2
# 3 SP1   COL4      87
# 4 SP2   COL2      NO
# 5 SP2   COL3      8
# 6 SP2   COL4      90
# 7 SP3   COL2      NO
# 8 SP3   COL3      2
# 9 SP3   COL4      56
#10 SP4   COL2      OK
#11 SP4   COL3      3
#12 SP4   COL4      45
</code>```

data

```<code>df <- structure(list(COL1 = c("SP1", "SP2", "SP3", "SP4"), COL2 = c("OK",
"NO", "NO", "OK"), COL3 = c(2, 8, 2, 3), COL4 = c(87, 90, 56,
45)), class = "data.frame", row.names = c(NA, -4L))
</code>```

Body:
Hello I have a df such as :

COL1 COL2 COL3 COL4
SP1  OK   2    87
SP2  NO   8    90
SP3  NO   2    56
SP4  OK   3    45

and I would like to put COL2,COL3 and COL4 into one unique column called Categorie and add the values associated into a column calles Value;

COL1 Categorie Value
SP1  COL2     OK
SP2 COL2     NO
SP3 COL2     NO
SP4 COL2     OK
SP1 COL3     2
SP2 COL3     8
SP3 COL3     2
SP4 COL3     3
SP1 COL4     87
SP2 COL4     90
SP3 COL4     56
SP4 COL4     45

Body:
We can use pivot_longer

library(tidyr)
library(dplyr)
df %>%
     mutate_at(vars(COL2:COL4), as.character) %>%
     pivot_longer(cols = -COL1, names_to = 'Categorie', values_to = 'Value')
# A tibble: 12 x 3
#   COL1  Categorie Value
#   <chr> <chr>     <chr>
# 1 SP1   COL2      OK
# 2 SP1   COL3      2
# 3 SP1   COL4      87
# 4 SP2   COL2      NO
# 5 SP2   COL3      8
# 6 SP2   COL4      90
# 7 SP3   COL2      NO
# 8 SP3   COL3      2
# 9 SP3   COL4      56
#10 SP4   COL2      OK
#11 SP4   COL3      3
#12 SP4   COL4      45

data

df <- structure(list(COL1 = c("SP1", "SP2", "SP3", "SP4"), COL2 = c("OK",
"NO", "NO", "OK"), COL3 = c(2, 8, 2, 3), COL4 = c(87, 90, 56,
45)), class = "data.frame", row.names = c(NA, -4L))


问:
When creating a form in React .map() does not populate select > options correctly, but works for a normal div
I am using React (and Redux) and have a form that I need to populate a dropdown with data via an API call.

When I use .map() within a standard div the list of results outputs correct. This is the code:

```<code><div>
  {categories &&
    categories.map((category, i) => (
      <option
        key={i}
        label={category.categoryName}
        value={category._id}
        name={category.categoryName}
        category={category}
      >
        {category.categoryName}
      </option>
    ))}
</div>
</code>```

When I then try and map the same data within a select/option dropdown it only renders the first result. i.e. there is no dropdown. Here's this code:

```<code><select
          value={categoryName}
          onChange={(e) => setCategoryName(e.target.value)}
        >
          {categories &&
            categories.map((category, i) => (
              <option
                key={i}
                label={category.categoryName}
                value={category._id}
                name={category.categoryName}
                category={category}
              >
                {category.categoryName}
              </option>
            ))}
</code>```

Here's the full code for the component in a github gist

Thanks in advance for any additional insight you can provide.

Edited to add in actions and reducer:

```<code> export const getCategories = () => async (dispatch) => {
  try {
    const config = {
      headers: {
        "Content-Type": "application/json",
      },
    };
    const res = await axios.get(
      "http://localhost:5000/category/getallcategories",
      config
    );

    dispatch({
      type: GET_CATEGORIES,
      payload: res.data,
    });
    console.log("2222" + res.data);
  } catch (err) {
    dispatch({
      type: CATEGORY_ERROR,
      payload: { msg: err.response.statusText, status: err.response.status },
    });
  }
};
</code>```

And Reducer:

```<code>    export default function (state = initialState, action) {
  const { type, payload } = action;
  switch (type) {
    case GET_CATEGORIES:
      return {
        ...state,
        categories: payload,
        loading: false,
      };
</code>```

答:
<select> tag should contain the value. In your case it is the state: taskTitle. Onchange should also be under select.
In your code you use this useState:

```<code>const [taskTitle, setTaskTitle] = useState("");
</code>```

So try to change the select to this:

```<code><select
   value={taskTitle}
   onChange={(e) => setTaskTitle(e.target.value)}>
      {categories &&
      categories.map((category, i) => (
         <option
            key={i}
            label={category.categoryName}
            value={category._id}
            name={category.categoryName}
            category={category}
         >
           {category.categoryName}
         </option>
       ))}
</select>
</code>```

Body:
I am using React (and Redux) and have a form that I need to populate a dropdown with data via an API call.

When I use .map() within a standard div the list of results outputs correct. This is the code:

  {categories &&
    categories.map((category, i) => (
      <option
        key={i}
        label={category.categoryName}
        value={category._id}
        name={category.categoryName}
        category={category}
      >
        {category.categoryName}
      </option>
    ))}

When I then try and map the same data within a select/option dropdown it only renders the first result. i.e. there is no dropdown. Here's this code:

<select
          value={categoryName}
          onChange={(e) => setCategoryName(e.target.value)}
        >
          {categories &&
            categories.map((category, i) => (
              <option
                key={i}
                label={category.categoryName}
                value={category._id}
                name={category.categoryName}
                category={category}
              >
                {category.categoryName}
              </option>
            ))}

Here's the full code for the component in a github gist

Thanks in advance for any additional insight you can provide.

Edited to add in actions and reducer:

 export const getCategories = () => async (dispatch) => {
  try {
    const config = {
      headers: {
        "Content-Type": "application/json",
      },
    };
    const res = await axios.get(
      "http://localhost:5000/category/getallcategories",
      config
    );

    dispatch({
      type: GET_CATEGORIES,
      payload: res.data,
    });
    console.log("2222" + res.data);
  } catch (err) {
    dispatch({
      type: CATEGORY_ERROR,
      payload: { msg: err.response.statusText, status: err.response.status },
    });
  }
};

And Reducer:

    export default function (state = initialState, action) {
  const { type, payload } = action;
  switch (type) {
    case GET_CATEGORIES:
      return {
        ...state,
        categories: payload,
        loading: false,
      };

Body:
<select> tag should contain the value. In your case it is the state: taskTitle. Onchange should also be under select.
In your code you use this useState:

const [taskTitle, setTaskTitle] = useState("");

So try to change the select to this:

<select
   value={taskTitle}
   onChange={(e) => setTaskTitle(e.target.value)}>
      {categories &&
      categories.map((category, i) => (
         <option
            key={i}
            label={category.categoryName}
            value={category._id}
            name={category.categoryName}
            category={category}
         >
           {category.categoryName}
         </option>
       ))}
</select>


问:
Sumifs to sum the column using excel formula
How to sum 4th column satisfying the difference between first and second column equal to 2 and also satisfying a criteria in the third column using excel formulas</p>

Body:
use SUMPRODUCT:

=SUMPRODUCT((A2:A10-B2:B10=2)*(C2:C10="A")*D2:D10)


问:
Universal Windows UI Responsiveness with Async/Await
Please help me understand how to properly await long executing tasks to keep the UI responsive in a Universal Windows application.

In the code below OperateSystem is a model class which inherits ObservableObject.  OperateSystem.GetLatestDataFromAllDevices connects to a variety of instruments, collects data, and updates class properties with the information from the instruments.  The views update with values from Operate System.

The UI is not responsive while the dispatcher.RunAsync task is running, I added a Thread.Sleep(5000) to GetLatestDataFromAllDevices() to make sure and it locks up the UI for 5 seconds.  Without the await Task.Delay(refreshTimer) the UI never updates (I'm assuming it instantly goes back into the GetLatestDataFromAllDevies before the UI can update).  Setting the refreshTimer to 1ms allows the UI to update, but I know that's a workaround for another issue that needs to be fixed.

```<code>   public ProductionViewModel()
    {
        OperateSystem = new OperateSystem();
        StartButtonCommand = new RelayCommand(StartMeasurementSystem);
        StopButtonCommand = new RelayCommand(StopMeasurementSystem);

        if (!Windows.ApplicationModel.DesignMode.DesignModeEnabled)
        {
            dispatcher = CoreWindow.GetForCurrentThread().Dispatcher;
        }
    }

    private async void StartMeasurementSystem()
    {
            stopRequest = false;
            StopButtonEnabled = true;
            StartButtonEnabled = false;
            while (!stopRequest)
            {
                await dispatcher.RunAsync(CoreDispatcherPriority.Normal, () => OperateSystem.GetLatestDataFromAllDevices(ConfigurationSettingsInstance));
                await Task.Delay(refreshTimer);
            }
    }
</code>```

In OperateSystem

```<code>    internal void GetLatestDataFromAllDevices(ConfigurationSettings configurationSettings)
    {
        GetDataInstrument1(configurationSettings);
        GetDataInstrument2(configurationSettings);
        GetDataInstrument3(configurationSettings);
        GetDatainstrumetn4(configurationSettings);
    }
</code>```

Each of the GetDataInstrumnet methods connect to an instrument, gathers data, performs some scaling/formatting, and updates a class property with the current value.

I followed other S.O. answers to use the dispatcher.RunAsync as using other async methods I would get thread mashalling errors.  But now I think the dispatcher is just marshaling these tasks on the UI thread anyway so it still blocks UI udpates.

To recreate the thread marshalling errors, I made GetLatestDataFromAllDevices async, and awaited a method executed as a task.

```<code>    internal async void GetLatestDataFromAllDevices(ConfigurationSettings configurationSettings)
    {
        await Task.Run(()=>GetDataInstrument1(configurationSettings));
        GetDataInstrument2(configurationSettings);
        GetDataInstrument3(configurationSettings);
        GetDatainstrumetn4(configurationSettings);
    }
</code>```

This results in:
System.Exception: 'The application called an interface that was marshalled for a different thread. (Exception from HRESULT: 0x8001010E (RPC_E_WRONG_THREAD))'

I've refactored in circles a few times and keep running into either thread marshaling errors or an unresponsive UI, what's a good way to get this done?

答:
I've refactored in circles a few times and keep running into either thread marshaling errors or an unresponsive UI, what's a good way to get this done?

Since you have an unresponsive UI, you must push the work to a background thread (e.g., Task.Run).

For marshalling updates back to the UI thread, I recommend (in order of preference):

Using the return value of asynchronous methods. E.g., MyUiProperty = await Task.Run(() => MyBackgroundMethod(...));.

Using Progress<T> to get multiple values from asynchronous methods. E.g., var progress = new Progress<string>(update => MyUiProperty = update); await Task.Run(() => MyBackgroundMethod(..., progress));.

Capturing a SynchronizationContext in your background classes and using that for sending updates to the UI thread. This is the least recommended because it results in your background driving your UI instead of the other way around.

Body:
Please help me understand how to properly await long executing tasks to keep the UI responsive in a Universal Windows application.

In the code below OperateSystem is a model class which inherits ObservableObject.  OperateSystem.GetLatestDataFromAllDevices connects to a variety of instruments, collects data, and updates class properties with the information from the instruments.  The views update with values from Operate System.

The UI is not responsive while the dispatcher.RunAsync task is running, I added a Thread.Sleep(5000) to GetLatestDataFromAllDevices() to make sure and it locks up the UI for 5 seconds.  Without the await Task.Delay(refreshTimer) the UI never updates (I'm assuming it instantly goes back into the GetLatestDataFromAllDevies before the UI can update).  Setting the refreshTimer to 1ms allows the UI to update, but I know that's a workaround for another issue that needs to be fixed.

   public ProductionViewModel()
    {
        OperateSystem = new OperateSystem();
        StartButtonCommand = new RelayCommand(StartMeasurementSystem);
        StopButtonCommand = new RelayCommand(StopMeasurementSystem);

        if (!Windows.ApplicationModel.DesignMode.DesignModeEnabled)
        {
            dispatcher = CoreWindow.GetForCurrentThread().Dispatcher;
        }
    }

    private async void StartMeasurementSystem()
    {
            stopRequest = false;
            StopButtonEnabled = true;
            StartButtonEnabled = false;
            while (!stopRequest)
            {
                await dispatcher.RunAsync(CoreDispatcherPriority.Normal, () => OperateSystem.GetLatestDataFromAllDevices(ConfigurationSettingsInstance));
                await Task.Delay(refreshTimer);
            }
    }

In OperateSystem

    internal void GetLatestDataFromAllDevices(ConfigurationSettings configurationSettings)
    {
        GetDataInstrument1(configurationSettings);
        GetDataInstrument2(configurationSettings);
        GetDataInstrument3(configurationSettings);
        GetDatainstrumetn4(configurationSettings);
    }

Each of the GetDataInstrumnet methods connect to an instrument, gathers data, performs some scaling/formatting, and updates a class property with the current value.

I followed other S.O. answers to use the dispatcher.RunAsync as using other async methods I would get thread mashalling errors.  But now I think the dispatcher is just marshaling these tasks on the UI thread anyway so it still blocks UI udpates.

To recreate the thread marshalling errors, I made GetLatestDataFromAllDevices async, and awaited a method executed as a task.

    internal async void GetLatestDataFromAllDevices(ConfigurationSettings configurationSettings)
    {
        await Task.Run(()=>GetDataInstrument1(configurationSettings));
        GetDataInstrument2(configurationSettings);
        GetDataInstrument3(configurationSettings);
        GetDatainstrumetn4(configurationSettings);
    }

This results in:
System.Exception: 'The application called an interface that was marshalled for a different thread. (Exception from HRESULT: 0x8001010E (RPC_E_WRONG_THREAD))'

I've refactored in circles a few times and keep running into either thread marshaling errors or an unresponsive UI, what's a good way to get this done?


问:
Simple addClass on mouseover problem
I'm trying to set a class for a li item, with no luck. I have tried many things (to much to post) but I can't figure it out:

```<code>$("li").live("mouseover",function(){
    $(this).addClass('current');
});
</code>```

The li item has to change class on mouseover(/hover) and keep that class state even if the mouse hovers outside the ul. But (and this is the tricky part) lose the class if another li item is hovered. Which means that the item being hovered gets the ''current'' class.

Hope it makes some sense..This is the fiddle jsfiddle

答:
You should remove the class from all the elements that currently have it before adding it to the new element:

```<code>$("li").live("mouseover", function() {
    $('.current').removeClass('current');
    $(this).addClass('current');
});
</code>```

jsFiddle

For added optimisation (i.e. to save the $('.current') selection, which can be expensive in some older browsers), you could check to see if the element hovered already has the class:

```<code>$("li").live("mouseover", function() {
    if (!$(this).hasClass('current')) {
        $('.current').removeClass('current');
        $(this).addClass('current');
    }
});
</code>```

Or, per Felix's excellent idea,

```<code>var current;
$("li").live("mouseover", function() {
    if (this !== current) {
        $(current).removeClass('current');
        $(this).addClass('current');
        current = this;
    }
});
</code>```

jsFiddle

Title: Simple addClass on mouseover problem

Body:
I'm trying to set a class for a li item, with no luck. I have tried many things (to much to post) but I can't figure it out:

$("li").live("mouseover",function(){
    $(this).addClass('current');
});

The li item has to change class on mouseover(/hover) and keep that class state even if the mouse hovers outside the ul. But (and this is the tricky part) lose the class if another li item is hovered. Which means that the item being hovered gets the ''current'' class.

Hope it makes some sense..This is the fiddle jsfiddle

Body:
You should remove the class from all the elements that currently have it before adding it to the new element:

$("li").live("mouseover", function() {
    $('.current').removeClass('current');
    $(this).addClass('current');
});

jsFiddle

For added optimisation (i.e. to save the $('.current') selection, which can be expensive in some older browsers), you could check to see if the element hovered already has the class:

$("li").live("mouseover", function() {
    if (!$(this).hasClass('current')) {
        $('.current').removeClass('current');
        $(this).addClass('current');
    }
});

Or, per Felix's excellent idea,

var current;
$("li").live("mouseover", function() {
    if (this !== current) {
        $(current).removeClass('current');
        $(this).addClass('current');
        current = this;
    }
});

jsFiddle


问:
laravel 2 tables have 1:n relationship with the same table
I have a users table, a products table, and and an assets table. A user can have many assets, as can a product, meaning both Users, and Products have a 1:n relationship with assets. In Laravel how would show this relationship in Eloquent, is this a Polymorphic relationship, with the struct of the assets table columns being something like, </p>

```<code>ID, type, file_path, ownable_id, ownable_type
</code>```

答:
relation of user model

```<code> public function assets()
    {
        return $this->morphMany(Asset::class, 'assetable');
    }
</code>```

relation of asset model

```<code>public function assetable()
{
    return $this->morphTo();
}
</code>```

Body:
I have a users table, a products table, and and an assets table. A user can have many assets, as can a product, meaning both Users, and Products have a 1:n relationship with assets. In Laravel how would show this relationship in Eloquent, is this a Polymorphic relationship, with the struct of the assets table columns being something like,

ID, type, file_path, ownable_id, ownable_type

Body:
relation of user model

 public function assets()
    {
        return $this->morphMany(Asset::class, 'assetable');
    }

relation of asset model

public function assetable()
{
    return $this->morphTo();
}


问:
java.io.FileNotFoundException: /storage/emulated/0/Android/data/MyApplication/MyFile.ics. (No such file or directory) / Android Studio / Ical4j
I'm calling for your help, I'm stuck for my android project, and I can't find a solution.

Explanation :

I retrieve an .ics (iCalendar) file from a URL on the internet with the Apache Common library using FileUtils.copyURLToFile(url, file).
It works very well, my file is created with my data and it is readable.

I save my file in  the path : /storage/emulated/0/Android/data/MyApplication/MyFile.ics.

I can see it in the files of the phone (Android Pie) and/or the emulator (Android Oreo) at this address. So it is well created and present.

But when I want to parse my file with the iCal4j library, I get an error with the line containing FileInputStream, telling me that my file or directory does not exist at this address.

EDIT
  I specify that I check that my file exists with file.exist(). If it exists then it calls the function to parse my file. Where I have a problem with the FileInputStream.
  So yes, file.exist() tells me that it exists.

```<code>    File file = new File(Environment.getExternalStorageDirectory() + "/Android/data/MyApplication/MyFile.ics");

    FileInputStream fin = new FileInputStream(file.getPath());

    CalendarBuilder builder = new CalendarBuilder();

    Calendar calendar = builder.build(fin);
</code>```

I get one mistake.

My errors :

```<code>W/System.err: java.io.FileNotFoundException: /storage/emulated/0/Android/data/MyApplication/MyFile.ics (No such file or directory)
    at java.io.FileInputStream.open0(Native Method)
    at java.io.FileInputStream.open(FileInputStream.java:200)
    at java.io.FileInputStream.<init>(FileInputStream.java:150)
    at java.io.FileInputStream.<init>(FileInputStream.java:103)
</code>```

My manifest.xml :

```<code><uses-permission android:name="android.permission.INTERNET"/>
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
</code>```

and I also asked the user's permission to access the storage:

```<code>requestPermissions(new String[]{WRITE_EXTERNAL_STORAGE,READ_EXTERNAL_STORAGE}, 1);
</code>```

I hope I was clear enough to get help, thank you.

答: try with following code File file = new File(Environment.getExternalStorageDirectory() + "/MyApplication/MyFile.ics");

Body:
I'm calling for your help, I'm stuck for my android project, and I can't find a solution.

Explanation :

I retrieve an .ics (iCalendar) file from a URL on the internet with the Apache Common library using FileUtils.copyURLToFile(url, file).
It works very well, my file is created with my data and it is readable.

I save my file in  the path : /storage/emulated/0/Android/data/MyApplication/MyFile.ics.

I can see it in the files of the phone (Android Pie) and/or the emulator (Android Oreo) at this address. So it is well created and present.

But when I want to parse my file with the iCal4j library, I get an error with the line containing FileInputStream, telling me that my file or directory does not exist at this address.

EDIT
  I specify that I check that my file exists with file.exist(). If it exists then it calls the function to parse my file. Where I have a problem with the FileInputStream.
  So yes, file.exist() tells me that it exists.

    File file = new File(Environment.getExternalStorageDirectory() + "/Android/data/MyApplication/MyFile.ics");

    FileInputStream fin = new FileInputStream(file.getPath());

    CalendarBuilder builder = new CalendarBuilder();

    Calendar calendar = builder.build(fin);

I get one mistake.

My errors :

W/System.err: java.io.FileNotFoundException: /storage/emulated/0/Android/data/MyApplication/MyFile.ics (No such file or directory)
    at java.io.FileInputStream.open0(Native Method)
    at java.io.FileInputStream.open(FileInputStream.java:200)
    at java.io.FileInputStream.<init>(FileInputStream.java:150)
    at java.io.FileInputStream.<init>(FileInputStream.java:103)

My manifest.xml :

<uses-permission android:name="android.permission.INTERNET"/>
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />

and I also asked the user's permission to access the storage:

requestPermissions(new String[]{WRITE_EXTERNAL_STORAGE,READ_EXTERNAL_STORAGE}, 1);

I hope I was clear enough to get help, thank you.


问:
How to delete a function effect when a second click on the button in javascript?
maybe one of you can help me. I've written a feature in javascript that adds underlining to all "a" selectors. The function is called with the "onclick" attribute. I would like to reverse the effect, i.e. remove the underscore at second click on the same button. The question is how to do it ?

HTML code:

```<code><button type="button" class="underlineLinks" id="underlineLinks" onclick="underlineLinks()">Click</button>
</code>```

JS code:

```<code>function underlineLinks() {
    const links = document.querySelectorAll("a");
    links.forEach(a => a.style.textDecoration = "underline");
}
</code>```

答:
you could do this

```<code>function getUnderLineLinksSetter() {
  let areLinksUnderlines = false;
  return () => {
    const links = document.querySelectorAll('a');
    areLinksUnderlines = !areLinksUnderlines;
    links.forEach(a => {
      if (areLinksUnderlines) {
        a.style.textDecoration = 'initial';
      } else {
        a.style.textDecoration = 'underline';
      }
    });
  };
}
</code>```

and then use the following html

```<code><button type="button" class="underlineLinks" id="underlineLinks" onclick="getUnderLineLinksSetter()()">Click</button>

</code>```

Its better to add event listeners from code and not using html inline functions by that i mean instead of setting the on click using html, you set it using javascript like this

```<code>// put this code inside a load event in the page so you make sure the button is in the dom
function getUnderLineLinksSetter() {
  let areLinksUnderlines = false;
  return () => {
    const links = document.querySelectorAll('a');
    areLinksUnderlines = !areLinksUnderlines;
    links.forEach(a => {
      if (areLinksUnderlines) {
        a.style.textDecoration = 'initial';
      } else {
        a.style.textDecoration = 'underline';
      }
    });
  };
}

document.getElementById('underlineLinks').addEventLisetner('click', getUnderLineLinksSetter())

</code>```

And then remove the onclick from html

```<code><button type="button" class="underlineLinks" id="underlineLinks">Click</button>

</code>```

Body:
maybe one of you can help me. I've written a feature in javascript that adds underlining to all "a" selectors. The function is called with the "onclick" attribute. I would like to reverse the effect, i.e. remove the underscore at second click on the same button. The question is how to do it ?

HTML code:

<button type="button" class="underlineLinks" id="underlineLinks" onclick="underlineLinks()">Click</button>

JS code:

function underlineLinks() {
    const links = document.querySelectorAll("a");
    links.forEach(a => a.style.textDecoration = "underline");
}

Body:
you could do this

function getUnderLineLinksSetter() {
  let areLinksUnderlines = false;
  return () => {
    const links = document.querySelectorAll('a');
    areLinksUnderlines = !areLinksUnderlines;
    links.forEach(a => {
      if (areLinksUnderlines) {
        a.style.textDecoration = 'initial';
      } else {
        a.style.textDecoration = 'underline';
      }
    });
  };
}

and then use the following html

<button type="button" class="underlineLinks" id="underlineLinks" onclick="getUnderLineLinksSetter()()">Click</button>

Its better to add event listeners from code and not using html inline functions by that i mean instead of setting the on click using html, you set it using javascript like this

// put this code inside a load event in the page so you make sure the button is in the dom
function getUnderLineLinksSetter() {
  let areLinksUnderlines = false;
  return () => {
    const links = document.querySelectorAll('a');
    areLinksUnderlines = !areLinksUnderlines;
    links.forEach(a => {
      if (areLinksUnderlines) {
        a.style.textDecoration = 'initial';
      } else {
        a.style.textDecoration = 'underline';
      }
    });
  };
}

document.getElementById('underlineLinks').addEventLisetner('click', getUnderLineLinksSetter())

And then remove the onclick from html

<button type="button" class="underlineLinks" id="underlineLinks">Click</button>


问:
Font-size that expands when you resize the window
How do I make my font in HTML such that when I expand the window, the size of the text expands also. Sort of like setting a percentage for the text that will take on a percentage of the size of the box it is in.

Here is an illustration of what I would like to happen:

```<code>#box #text {
   font-size: 50%;
}
</code>```

Now lets say #box is 200px, #text should be 100px.
Obviously I can't just put a fix width for #text because in the site #box will be a dynamic width.

答: Use the vh (viewport height), vw (viewport width), and/or vm (viewport minimum (smallest of the dimensions)) units in browsers that fully support CSS3, and for other browsers listen for resize and JavaScript such as in Razor Storm's answer.

Body:
How do I make my font in HTML such that when I expand the window, the size of the text expands also. Sort of like setting a percentage for the text that will take on a percentage of the size of the box it is in.

Here is an illustration of what I would like to happen:

#box #text {
   font-size: 50%;
}

Now lets say #box is 200px, #text should be 100px.
Obviously I can't just put a fix width for #text because in the site #box will be a dynamic width.


问:
Improper usage of mutex c++
i have problem with my code. This function pushes a product into queue.

```<code>void producent(bool &cont,std::queue<std::string> &queue,std::mutex &mtx, int &milliseconds)
{
    while (cont)
    {
        mtx.lock();
        if (queue.size() >= MAX_QUEUE_SIZE)
        {
            mtx.unlock();
            std::cerr << "buffor full " << std::endl;
        }
        else
        {
            std::string product = generate();
            std::cerr << "producent: " << product << " " << std::endl;
            queue.push(product);
            mtx.unlock();
        }
        std::this_thread::sleep_for(std::chrono::milliseconds(milliseconds));
    }
}
</code>```

this function generates a string of 10 signs, which are pushed by void producent function().

```<code>std::string generate() {
    std::string temp;
    temp.resize(10);
    for (int i = 0; i < 10; i++) {
        temp[i] = rand() % ('z' - 'a' + 1) + 'a';
    }
    return temp;
}
</code>```

My question is: why, when i create 2 threads like this:

```<code>std::thread prod(producent, std::ref(wykonuj),std::ref(kolejka), std::ref(kolejka_mtx),std::ref(t));
std::thread prod1(producent, std::ref(wykonuj), std::ref(kolejka), std::ref(kolejka_mtx), std::ref(t));
</code>```

both of them give me same result, for example the outcome is:

```<code>producent: qweasdzxca
producent: qweasdzxca
</code>```

i wanted those outcomes to be different, thats why i used mutex, but it didnt work. Can someone give me some advices?

答:
rand doesn't share a seed between threads.  Each thread has its own seed - but without explicitly setting it differently in both threads via srand(), it's going to be the same.

Hence, generate invoked by both threads will produce the same string.

The docs suggest rand_r is the thread safe version, but both functions are threads safe in modern implementations.

Title: Improper usage of mutex c++

Body:
i have problem with my code. This function pushes a product into queue.

void producent(bool &cont,std::queue<std::string> &queue,std::mutex &mtx, int &milliseconds)
{
    while (cont)
    {
        mtx.lock();
        if (queue.size() >= MAX_QUEUE_SIZE)
        {
            mtx.unlock();
            std::cerr << "buffor full " << std::endl;
        }
        else
        {
            std::string product = generate();
            std::cerr << "producent: " << product << " " << std::endl;
            queue.push(product);
            mtx.unlock();
        }
        std::this_thread::sleep_for(std::chrono::milliseconds(milliseconds));
    }
}

this function generates a string of 10 signs, which are pushed by void producent function().

std::string generate() {
    std::string temp;
    temp.resize(10);
    for (int i = 0; i < 10; i++) {
        temp[i] = rand() % ('z' - 'a' + 1) + 'a';
    }
    return temp;
}

My question is: why, when i create 2 threads like this:

std::thread prod(producent, std::ref(wykonuj),std::ref(kolejka), std::ref(kolejka_mtx),std::ref(t));
std::thread prod1(producent, std::ref(wykonuj), std::ref(kolejka), std::ref(kolejka_mtx), std::ref(t));

both of them give me same result, for example the outcome is:

producent: qweasdzxca
producent: qweasdzxca

i wanted those outcomes to be different, thats why i used mutex, but it didnt work. Can someone give me some advices?


问:
How are hardware interruptions handled in non-preemtive scheduling?
Let's say I have a process A that is currently running. Then I press Ctrl+C, how is this interruption handled?

Does A finish executing first and then the interruption is handled?

Does A get put in the ready queue?

答:
You are confusing interrupts, signals and task scheduling. Those are all very different concepts.

I press Ctrl+C, how is this interruption handled?

CTRL+C has nothing to do with interrupts. It's a key combination that is intercepted by your terminal emulator, which then sends a signal (SIGINT) to the currently running process. Signal delivery is done through the kill syscall (which, contrary to its name, does not necessarily kill the process).

Does A finish executing first and then the interruption is handled?

What happens when your program receives a SIGINT signal depends on the specific case. A program can register a signal handler, and decide what to do in case it receives a specific signal. In other words, this "interruption" as you call it, happens while the process is running: when the signal is delivered, the kernel will temporarily "pause" the normal process code, let the process run its signal handler, and then resume the process from where it left.

A process can only register handlers for signals that are catchable (SIGINT is). The only two signals that are uncatchable in Linux are SIGKILL and SIGSTOP. In case the process has not registered a signal handler, the default handler defined by the kernel will do its job: for SIGINT, the default handler just terminates the process.

See man 7 signal for more information.

Does A get put in the ready queue?

There is no such thing as a "ready queue", I suppose you mean runqueue. If the process gets killed by the signal, then it will cease to exist and will be removed from its runqueue, therefore no runqueue will have A anymore.

If the process is not terminated, it will still exist in the system, and the kernel will keep executing it along with other processes that are executing on the same CPU. There is one runqueue per CPU, and the scheduler uses it to determine which processes to run when. Processes can also be moved from one runqueue to another (for example for load balancing purposes), but this is a different topic.


问:
Pandas Week of the Month Business Day Stock Price Data
My question is different than the following:

Question1: Week of a month pandas
Quesiton2: Week number of the month

The above question deals with assuming 7 days in a week. It attempts to count the number of 7 days week there are. My data is composed of (business days) daily prices and there can be at times missing days of the week because the market was closed for holiday.

My question is how does one find the week of the month given a date. Note I highlighted "given a date" because this process is processed daily so any answers that looks ahead till the end of the month will likely not work.

My attempts has been the look ahead which isn't optimal:

```<code>def is_third_friday(s):
    d = datetime.datetime.strptime(s, '%Y-%m-%d')
    return d.weekday() == 5 and 15 <= d.day <= 21

dow = deepcopy(data['Close'] * np.nan).to_frame()
dow.columns = ['OpexFriday']
dow['next_date'] = pd.Series([str(i.date() + datetime.timedelta(days=1)) for i in dow.index]).values
dow['OpexFriday'] = pd.Series([is_third_friday(str(i)) for i in dow['next_date']]).values
dow['OpexWeek'] = (dow['OpexFriday'] * 1).replace(0, np.nan).fillna(method='bfill', limit=4).replace(np.nan, 0) == True
</code>```

I don't know how to provide some sample data but if  you go to "https://aroussi.com/post/python-yahoo-finance" page and use the authors yfinance package, you will be able to get some price data to work with.

The functions above will find the 3rd week of the month (all True). In addition, it will set the Friday of that week too.

Let me know if you see any problem with the question or if its a duplicate. I have searched a while for a solution.

答:
We can easily modify your function to work on the index:

```<code># sample data
dow = pd.DataFrame(index=pd.date_range('2020-01-01', '2020-01-31'),
                   columns=['OpexFriday'])

isFriday = dow.index.dayofweek == 5
thirdWeek = dow.index.day.to_series().between(15,21)

# third Friday
dow['OpexFriday'] = (isFriday & thirdWeek).values

# third work week
dow['OpexWeek'] = dow['OpexFriday'].where(dow['OpexFriday']).bfill(limit=4).fillna(0)

# extract the third week:
dow[dow['OpexWeek']==1]
</code>```

Output:

```<code>            OpexFriday  OpexWeek
2020-01-14       False       1.0
2020-01-15       False       1.0
2020-01-16       False       1.0
2020-01-17       False       1.0
2020-01-18        True       1.0
</code>```

Body:
My question is different than the following:

Question1: Week of a month pandas
Quesiton2: Week number of the month

The above question deals with assuming 7 days in a week. It attempts to count the number of 7 days week there are. My data is composed of (business days) daily prices and there can be at times missing days of the week because the market was closed for holiday.

My question is how does one find the week of the month given a date. Note I highlighted "given a date" because this process is processed daily so any answers that looks ahead till the end of the month will likely not work.

My attempts has been the look ahead which isn't optimal:

def is_third_friday(s):
    d = datetime.datetime.strptime(s, '%Y-%m-%d')
    return d.weekday() == 5 and 15 <= d.day <= 21

dow = deepcopy(data['Close'] * np.nan).to_frame()
dow.columns = ['OpexFriday']
dow['next_date'] = pd.Series([str(i.date() + datetime.timedelta(days=1)) for i in dow.index]).values
dow['OpexFriday'] = pd.Series([is_third_friday(str(i)) for i in dow['next_date']]).values
dow['OpexWeek'] = (dow['OpexFriday'] * 1).replace(0, np.nan).fillna(method='bfill', limit=4).replace(np.nan, 0) == True

I don't know how to provide some sample data but if  you go to "https://aroussi.com/post/python-yahoo-finance" page and use the authors yfinance package, you will be able to get some price data to work with.

The functions above will find the 3rd week of the month (all True). In addition, it will set the Friday of that week too.

Let me know if you see any problem with the question or if its a duplicate. I have searched a while for a solution.

Body:
We can easily modify your function to work on the index:

# sample data
dow = pd.DataFrame(index=pd.date_range('2020-01-01', '2020-01-31'),
                   columns=['OpexFriday'])

isFriday = dow.index.dayofweek == 5
thirdWeek = dow.index.day.to_series().between(15,21)

# third Friday
dow['OpexFriday'] = (isFriday & thirdWeek).values

# third work week
dow['OpexWeek'] = dow['OpexFriday'].where(dow['OpexFriday']).bfill(limit=4).fillna(0)

# extract the third week:
dow[dow['OpexWeek']==1]

Output:

            OpexFriday  OpexWeek
2020-01-14       False       1.0
2020-01-15       False       1.0
2020-01-16       False       1.0
2020-01-17       False       1.0
2020-01-18        True       1.0


问:
Replace all matches in string and return updated string
I have a string on a server (no DOM parsing), where I need to replace all matches and return an updated string. Challenging part is that match contains a part that I need to be preserved.

const data =
  '
Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod Link tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud Link exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur Link sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.';
const regex = /Link<\/a>/g;
const newData = [...data.matchAll(regex)].map((match) => {
  const [string] = match;
  const [end] = string
    .split(/ val);
  const [href] = end.split(/\">/g);
  const newString = `<div data-href="${href}"></div>`;
  return newString;
});
console.log(newData);```
</div>
</div>
</p>

<p>So there in <code>data</code> are three matches eg. <code>Link</code>, where I need to extract <code>http://google.com</code> etc. from and "inject" it into updated string. I managed to do this, but question is how to replace matches.</p>

<p>In fact I have a working solution with <code>split/join</code>:</p>

<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>const data =
  '<p>Lorem ipsum dolor sit amet, Another link consectetur adipiscing elit, sed do eiusmod Link tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud Link exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur data-type=\"embed\" href="http://tested.com">Link sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.';
const newData = data
  .split('data-type=\"embed\" href="')
  .join('<div data-href="')
  .split('">Link')
  .join('"></div>');
console.log(newData);</code>```

This solution however will cause undesired results, if there is no match in second split/join, or it can modify also links, which are not supposed to be modified.

So my target is get a result as in the second case, but with correct replacements, as in first one.

答:
Here is a simple solution to get a single string back with links modified as desired:

```<code>const data =
  '<p>Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod <a data-type=\"embed\" href="http://google.com">Link</a> tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud <a data-type=\"embed\" href="http://wired.com">Link</a> exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur <a data-type=\"embed\" href="http://tested.com">Link</a> sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.';
const regex = /<a data-type="embed" href="(http:\/\/[^"]+)">Link<\/a>/g;

var result = data.replace(regex, '<div data-href="$1"></div>')
console.log(result);
</code>```

Resulting output:

Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod

 tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud

 exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur

 sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.

Old answer before clarification of desired output:

Here is a working solution:

const data = '
Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod Link tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud Link exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur Link sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.';

const regex = /data-type="embed" href="(http:\/\/[^"]+)">Link<\/a>/g;

function extractLinks(data) {
    var links = [];
    data.replace(regex, (m, p1) => {
        links.push(p1);
    });
    return links.map((link) => {
        return '

';
    });
}

console.log(extractLinks(data));```

Body:
I have a string on a server (no DOM parsing), where I need to replace all matches and return an updated string. Challenging part is that match contains a part that I need to be preserved.

const data =
  '
Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod Link tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud Link exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur Link sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.';
const regex = /Link<\/a>/g;
const newData = [...data.matchAll(regex)].map((match) => {
  const [string] = match;
  const [end] = string
    .split(/ val);
  const [href] = end.split(/\">/g);
  const newString = `<div data-href="${href}"></div>`;
  return newString;
});
console.log(newData);

So there in data are three matches eg. Link, where I need to extract http://google.com etc. from and "inject" it into updated string. I managed to do this, but question is how to replace matches.

In fact I have a working solution with split/join:

const data =
  '
Lorem ipsum dolor sit amet, Another link consectetur adipiscing elit, sed do eiusmod Link tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud Link exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur Link sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.';
const newData = data
  .split('<a data-type=\"embed\" href="')
  .join('
Link')
  .join('">
');
console.log(newData);

This solution however will cause undesired results, if there is no match in second split/join, or it can modify also links, which are not supposed to be modified.

So my target is get a result as in the second case, but with correct replacements, as in first one.

Body:
Here is a simple solution to get a single string back with links modified as desired:

const data =
  '<p>Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod <a data-type=\"embed\" href="http://google.com">Link</a> tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud <a data-type=\"embed\" href="http://wired.com">Link</a> exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur <a data-type=\"embed\" href="http://tested.com">Link</a> sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.';
const regex = /<a data-type="embed" href="(http:\/\/[^"]+)">Link<\/a>/g;

var result = data.replace(regex, '<div data-href="$1"></div>')
console.log(result);

Resulting output:

<p>Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod <div data-href="http://google.com"></div> tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud <div data-href="http://wired.com"></div> exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur <div data-href="http://tested.com"></div> sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.

Old answer before clarification of desired output:

Here is a working solution:

const data = '<p>Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod <a data-type=\"embed\" href="http://google.com">Link</a> tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud <a data-type=\"embed\" href="http://wired.com">Link</a> exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur <a data-type=\"embed\" href="http://tested.com">Link</a> sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.';

const regex = /<a data-type="embed" href="(http:\/\/[^"]+)">Link<\/a>/g;

function extractLinks(data) {
    var links = [];
    data.replace(regex, (m, p1) => {
        links.push(p1);
    });
    return links.map((link) => {
        return '<div data-href="' + link + '"></div>';
    });
}

console.log(extractLinks(data));