问:
Print last matching line
Using sed, I would like to print the last matching line of a file. I came across

sed: return last occurrence match until end of file

however, I would like only the matching line itself, not any range of lines. Using that page I actually came up with a working command

```<code>$ sed '/out_time=/h; $!d; x' progress.txt
out_time=00:00:07.720000
</code>```

The question is why does this work, or to put another way what is going on in this command. Also include a simpler sed command, if one exists.

答:
A very late answer without any pipes using awk (someone mentioned correct tools...):

```<code>awk '/out_time=/{last=$0} END{print last}'  progress.txt
</code>```

Explanation:

/$PAT/{...}: save the matched occurance to variable last, overwriting the previous occurance

END{...} : execute block whe exiting the program, in this case printing the value of last

Title: Print last matching line

Body:
Using sed, I would like to print the last matching line of a file. I came across

sed: return last occurrence match until end of file

however, I would like only the matching line itself, not any range of lines. Using that page I actually came up with a working command

$ sed '/out_time=/h; $!d; x' progress.txt
out_time=00:00:07.720000

The question is why does this work, or to put another way what is going on in this command. Also include a simpler sed command, if one exists.

Body:
A very late answer without any pipes using awk (someone mentioned correct tools...):

awk '/out_time=/{last=$0} END{print last}'  progress.txt

Explanation:

/$PAT/{...}: save the matched occurance to variable last, overwriting the previous occurance

END{...} : execute block whe exiting the program, in this case printing the value of last


来源: stackexchange

问:
after refreshing page and adding new values old localstorage values get erased
My local storage works correctly but the only issue I've ran it to is when I try adding a new value after a page refresh the previously stored values get erased. I think it may be because I'm using the same key.

```<code>I tried this localStorage.setItem("name_"+new Date().getTime(), JSON.stringify(favs))
</code>```

but it didn't help.

This is my function to add a value and store it in to localstorage

value is a string from an array

```<code>const favs [];

   function addValue(e) {
        if (e.target.value !== "") {
          if (!favs.includes(e.target.value)) {
            favs.push(e.target.value);
            localStorage.setItem("name", JSON.stringify(favs));
            console.log(favs);
            document.getElementById("favsarray").innerHTML =  favs
          }
        }
      }
</code>```

答:
Every time you reload the page you're re-initializing favs instead of loading it from the localStorage so it's overwriting it when you save the first value. What you need to do is get the value from the localStorage first and then push the new value. You can do this on page load or when you first try to push the value to localStorage, like so:</p>
```<code>let favs = [];

   function addValue(e) {
        if (e.target.value !== "") {
          if (favs === []) {
            favs = JSON.parse(localStorage.getItem("name"));
          }

          if (!favs.includes(e.target.value)) {
            favs.push(e.target.value);
            localStorage.setItem("name", JSON.stringify(favs));
            console.log(favs);
            document.getElementById("favsarray").innerHTML =  favs
          }
        }
      }
</code>```

ContentLicense: CC BY-SA 4.0

Body:
My local storage works correctly but the only issue I've ran it to is when I try adding a new value after a page refresh the previously stored values get erased. I think it may be because I'm using the same key.

I tried this localStorage.setItem("name_"+new Date().getTime(), JSON.stringify(favs))

but it didn't help.

This is my function to add a value and store it in to localstorage

value is a string from an array

const favs [];

   function addValue(e) {
        if (e.target.value !== "") {
          if (!favs.includes(e.target.value)) {
            favs.push(e.target.value);
            localStorage.setItem("name", JSON.stringify(favs));
            console.log(favs);
            document.getElementById("favsarray").innerHTML =  favs
          }
        }
      }

Body:
Every time you reload the page you're re-initializing favs instead of loading it from the localStorage so it's overwriting it when you save the first value. What you need to do is get the value from the localStorage first and then push the new value. You can do this on page load or when you first try to push the value to localStorage, like so:

let favs = [];

   function addValue(e) {
        if (e.target.value !== "") {
          if (favs === []) {
            favs = JSON.parse(localStorage.getItem("name"));
          }

          if (!favs.includes(e.target.value)) {
            favs.push(e.target.value);
            localStorage.setItem("name", JSON.stringify(favs));
            console.log(favs);
            document.getElementById("favsarray").innerHTML =  favs
          }
        }
      }


答:
Here you have a list of matrix with scenario in row and n columns.

```<code>genereting_fuction <- function(n, scenario, scenari){
  # added argument because you assume global variable use
  nr <- nrow(scenario)
  sample <- vector("list", length = nr) # sample<-list()
  # creating a list is better than expanding it each iteration
  for (i in 1:nr){
    X1=rnorm(n)+scenari[i,1]
    X4=rnorm(n)+scenari[i,4]
    X2=X1*p12+std_e2*rnorm(n)+scenari[i,2]
    X3=X1*p13+X4*p43+std_e3*rnorm(n)+scenari[i,3]
    X5=X2*p25+X3*p35+std_e5*rnorm(n)+scenari[i,5]
    sample[[i]]=cbind(X1,X2,X3,X4,X5)
    colnames(sample[[i]])<-c("X1","X2","X3","X4","X5")
  }
  sample
}

set.seed(123)
dati_fault<- lapply(rep(3, 2), function(x) genereting_fuction(x, scenario_1, scenari))
dati_fault

lapply(dati_fault, function(x) {
  tmp <- lapply(x, function(y) y[,"X1"])
  tmp <- do.call(rbind, tmp)
})
</code>```

If you want to assemble this list of matrix, like using cbind, I suggest you just use a single big n value and not the lapply with rep inside it.

Also I bet there is easier way to simulate this number of scenari, but it's difficult to estimate without knowing the context of your code piece.

Also, try to solve your issue with a minimal example, working with a list of 100 list of 32 matrix of 5*10 is a bit messy !

Good luck !

Title: Problems with the names of the elements of a list

Body:
I have created a list whose elements are themselves a list of matrices. I want to be able to extract the vectors of observations for each variable

    p13 = 0.493;p43 = 0.325;p25 = 0.335;p35 = 0.574;p12 = 0.868
    std_e2 = sqrt(1-p12^2)
    std_e3 = sqrt(1-(p13^2+p43^2))
    std_e5 = sqrt(1-(p25^2+p35^2+2*p25*p35*(p13*p12)))
    set.seed(1234)
    z1<-c(0,1)
    z2<-c(0,1)
    z3<-c(0,1)
    z4<-c(0,1)
    z5<-c(0,1)
    s<-expand.grid(z1,z2,z3,z4,z5); s
    s<-s[-1,];s
    shift<-3
    scenari<-s*shift;scenari
    scenario_1<-scenari[1];scenario_1
    genereting_fuction<-function(n){
      sample<-list()
      for (i in 1:nrow(scenario_1)){
        X1=rnorm(n)+scenari[i,1]
        X4=rnorm(n)+scenari[i,4]
        X2=X1*p12+std_e2*rnorm(n)+scenari[i,2]
        X3=X1*p13+X4*p43+std_e3*rnorm(n)+scenari[i,3]
        X5=X2*p25+X3*p35+std_e5*rnorm(n)+scenari[i,5]
        sample[[i]]=cbind(X1,X2,X3,X4,X5)
        colnames(sample[[i]])<-c("X1","X2","X3","X4","X5")
      }
      sample
    }
    set.seed(123)
    dati_fault<- lapply(rep(10, 100), genereting_fuction)

     dati_fault[[1]]
    [[1]]
                X1       X2        X3         X4         X5
     [1,] 2.505826 1.736593 1.0274581 -0.6038358  1.9967656
     [2,] 4.127593 3.294344 2.8777777  1.2386725  3.0207723
     [3,] 1.853050 1.312617 1.1875699  0.5994921  1.0471564
     [4,] 4.481019 3.330629 2.1880050 -0.1087338  2.7331061
     [5,] 3.916191 3.306036 0.7258404 -1.1388570  1.0293168
     [6,] 3.335131 2.379439 1.2407679  0.3198553  1.6755424
     [7,] 3.574675 3.769436 1.1084120 -1.0065481  2.0034434
     [8,] 3.203620 2.842074 0.6550587 -0.8516120 -0.1433508
     [9,] 2.552959 2.642094 2.5376430  2.0387860  3.5318055
    [10,] 2.656474 1.607934 2.2760391 -1.3959822  1.0095796

I only want to save the elements of X1 in an object, and so for the other variables. .

Body:
Here you have a list of matrix with scenario in row and n columns.

genereting_fuction <- function(n, scenario, scenari){
  # added argument because you assume global variable use
  nr <- nrow(scenario)
  sample <- vector("list", length = nr) # sample<-list()
  # creating a list is better than expanding it each iteration
  for (i in 1:nr){
    X1=rnorm(n)+scenari[i,1]
    X4=rnorm(n)+scenari[i,4]
    X2=X1*p12+std_e2*rnorm(n)+scenari[i,2]
    X3=X1*p13+X4*p43+std_e3*rnorm(n)+scenari[i,3]
    X5=X2*p25+X3*p35+std_e5*rnorm(n)+scenari[i,5]
    sample[[i]]=cbind(X1,X2,X3,X4,X5)
    colnames(sample[[i]])<-c("X1","X2","X3","X4","X5")
  }
  sample
}

set.seed(123)
dati_fault<- lapply(rep(3, 2), function(x) genereting_fuction(x, scenario_1, scenari))
dati_fault

lapply(dati_fault, function(x) {
  tmp <- lapply(x, function(y) y[,"X1"])
  tmp <- do.call(rbind, tmp)
})

If you want to assemble this list of matrix, like using cbind, I suggest you just use a single big n value and not the lapply with rep inside it.

Also I bet there is easier way to simulate this number of scenari, but it's difficult to estimate without knowing the context of your code piece.

Also, try to solve your issue with a minimal example, working with a list of 100 list of 32 matrix of 5*10 is a bit messy !

Good luck !


问:
Maven 3 and JUnit 4 compilation problem: package org.junit does not exist
I am trying to build a simple Java project with Maven. In my pom-file I declare JUnit 4.8.2 as the only dependency. Still Maven insists on using JUnit version 3.8.1. How do I fix it?

The problem manifests itself in a compilation failure: "package org.junit does not exist". This is because of the import statement in my source code. The correct package name in JUnit 4.* is org.junit.* while in version 3.* it is junit.framework.*

I think I have found documentation on the root of the problem on http://maven.apache.org/plugins/maven-surefire-plugin/examples/junit.html but the advice there seems to be meant for Maven experts. I did not understand what to do.

答:
I met this problem, this is how I soloved it:

Context:

SpringBoot application

Use maven to manage multiple modules

Add junit's maven dependency in root POM's dependencyManagement(rather than dependencies, their differences can be found here)

Intend to test class or folder inside one of the root module's child module

PS: If your situation does not match the context above, this solution may not solve your problem.

Steps

right click at the class or folder you want to test:

Choose More Run/Debug -> Modify Run Configuration

Change the module option to the one you want to test from root module

ContentLicense: CC BY-SA 3.0


问:
Show ActivityIndicator 5 seconds in react native splash screen
I wanted to show Activity indicator at least 5 seconds in this splash screen. I tried setTimeOut method but it doesn't worked. It disappeared quickly and show this warning also.

Warning: Can't perform a React state update on an unmounted component.
This is a no-op, but it indicates a memory leak in your application.
To fix, cancel all subscriptions and asynchronous tasks in a useEffect
cleanup function. at src/screens/SplashScreen.js:15:15 in
setTimeout$argument_0

Here is my code and how can I fixed this?

```<code>import React, { useEffect, useState } from 'react';
import { ActivityIndicator, View } from 'react-native';

const SplashScreen = () => {
  const [animate, setAnimate] = useState(true);

  useEffect(() => {
    closeActivityIndicator();
  }, []);

  const closeActivityIndicator = () => {
    setTimeout(() => {
      setAnimate(false);
    }, 5000);
  };

  return (
    <View
      style={{ flex: 1, justifyContent: 'center', backgroundColor: '#06bcee' }}
    >
      <ActivityIndicator animating={animate} size="large" color="#ffffff" />
    </View>
  );
};

export default SplashScreen;
</code>```

答:
I cannot see where your navigation function call is. Anyways, what you can do is keep your animate state to true, it doesn't matter the activity indicator is animating. The other problem I see is that your component unmounts but your setTimout() doesn't get cleared so it keeps on updating your state. You can do something like this.

const timerRef = React.useRef(null) // you can also import useRef() directly from 'react'

useEffect(() => {
  timerRef.current = setTimeout(() => {
    // code for navigation
  }, 5000);

  return () => clearTimeout(timerRef.current);
}, []);```

Body:
I wanted to show Activity indicator at least 5 seconds in this splash screen. I tried setTimeOut method but it doesn't worked. It disappeared quickly and show this warning also.

Warning: Can't perform a React state update on an unmounted component.
This is a no-op, but it indicates a memory leak in your application.
To fix, cancel all subscriptions and asynchronous tasks in a useEffect
cleanup function. at src/screens/SplashScreen.js:15:15 in
setTimeout$argument_0

Here is my code and how can I fixed this?

import React, { useEffect, useState } from 'react';
import { ActivityIndicator, View } from 'react-native';

const SplashScreen = () => {
  const [animate, setAnimate] = useState(true);

  useEffect(() => {
    closeActivityIndicator();
  }, []);

  const closeActivityIndicator = () => {
    setTimeout(() => {
      setAnimate(false);
    }, 5000);
  };

  return (
    <View
      style={{ flex: 1, justifyContent: 'center', backgroundColor: '#06bcee' }}
    >
      <ActivityIndicator animating={animate} size="large" color="#ffffff" />
    </View>
  );
};

export default SplashScreen;


问:
Simulate a data frame with different sequence per column
I would like to simulate in R a data frame with 4 columns with the above conditions:

Each row is summing up to 1

The first element of column 1 starts with being closer to 1, say 0.9, but gradually decreases per row.

The elements of the other 3 columns start low, say something between 0.02 - 0.05, but gradually increase with each row.

I would like the last row of the data frame being c(0.25, 0.25, 0.25, 0.25).

Can you help me with creating something like that ?
Thank you in advance!

答:
```<code># State the number of rows you want to create
rows <- 1000

# Create 4 randomly generated columns, the first ranging [.25, 1], the others [0, .25] and add .25 as the last row
x1<-c(runif(rows-1,.25,1), .25)
x2<-c(runif(rows-1,0,.25), .25)
x3<-c(runif(rows-1,0,.25), .25)
x4<-c(runif(rows-1,0,.25), .25)

library(dplyr)
# Combine the columns into a single table
df <- data.frame(x1, x2, x3, x4)

df %>%
  # Sort each column individually (meaning the sorting of 1 column doesn't affect another)
  mutate(x1 = sort(x1, decreasing = T)) %>%
  mutate(across(x2:x4, ~sort(.x))) %>%
  # Transpose the table so you can sort the rows
  t() %>%
  as_tibble() %>%
  mutate_all(.funs = ~sort(., decreasing = T)) %>%
  t() %>%
  as_tibble() %>%
  # Scale the table you have so the sum of each row equals to 1
  mutate_all(.funs = ~ ./rowSums(across(everything())))
</code>```


问:
Where does PostgreSQL store configuration/conf files?
I have recently installed PostgreSQL on Ubuntu with the EnterpriseDB package. I can connect to the database locally, but I can't configure it because I can't find config files. I searched through entire hard drive and found only samples like pg_hba.conf.sample

Where are the PostgreSQL .conf files?

答:
In ubuntu, you can find</p>
```<code>/etc/postgresql/11/main/pg_hba.conf

// after change restart it otherwise it won't be work

service postgresql restart
</code>```

Body:
In ubuntu, you can find

/etc/postgresql/11/main/pg_hba.conf

// after change restart it otherwise it won't be work

service postgresql restart


问:
Groovy JSONArray : org.json.JSONException: when decoding string with \"
I get no way to parse this Json which seems to be valid for me :

```<code>def diffOfApi='''[{"op":"replace","path":"/data/0/messageBody","value":"<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<WCS reference=\"336042800000431486\"><PREPARATION_REQUEST requestId=\"WDP_PICKVRAC3\" date=\"2022-02-08 18:33:39\"><CONTAINERS><CONTAINER containerId=\"336042800000431486_21_21121\" handle=\"CREATE\" wmsOrderId=\"WDP_PICKVRAC3\" site=\"CPEEPF\" status=\"CREATED\" referenceDate=\"2022-02-08 18:33:39\" purgeAuthorized=\"false\"><BARCODES><BARCODE main=\"false\" reusable=\"false\">336042800000431486</BARCODE></BARCODES><PACKAGING>TX</PACKAGING><WEIGHT_CHECKING mode=\"NO\"/></CONTAINER></CONTAINERS></PREPARATION_REQUEST></WCS>"}]'''

JSONArray jsonArray = new JSONArray(diffOfApi);
</code>```

I get this error :

```<code>Reason:
org.json.JSONException: Expected a ',' or '}' at 71 [character 72 line 1]
    at org.json.JSONTokener.syntaxError(JSONTokener.java:433)
    at org.json.JSONObject.<init>(JSONObject.java:229)
    at org.json.JSONTokener.nextValue(JSONTokener.java:363)
    at org.json.JSONArray.<init>(JSONArray.java:115)
    at org.json.JSONArray.<init>(JSONArray.java:144)
    at TEST.run(TEST:32)
    at com.kms.katalon.core.main.ScriptEngine.run(ScriptEngine.java:194)
    at com.kms.katalon.core.main.ScriptEngine.runScriptAsRawText(ScriptEngine.java:119)
    at com.kms.katalon.core.main.TestCaseExecutor.runScript(TestCaseExecutor.java:442)
    at com.kms.katalon.core.main.TestCaseExecutor.doExecute(TestCaseExecutor.java:433)
    at com.kms.katalon.core.main.TestCaseExecutor.processExecutionPhase(TestCaseExecutor.java:412)
    at com.kms.katalon.core.main.TestCaseExecutor.accessMainPhase(TestCaseExecutor.java:404)
    at com.kms.katalon.core.main.TestCaseExecutor.execute(TestCaseExecutor.java:281)
    at com.kms.katalon.core.main.TestCaseMain.runTestCase(TestCaseMain.java:142)
    at com.kms.katalon.core.main.TestCaseMain.runTestCase(TestCaseMain.java:133)
    at com.kms.katalon.core.main.TestCaseMain$runTestCase$0.call(Unknown Source)
    at TempTestCase1644483473725.run(TempTestCase1644483473725.groovy:25)
</code>```

I think it is due to " encapsulated xml in item value

Any idea to make it working ?

答:
You can replace the \" characters with ' to allow for JSON- and later XML-processing:

```<code>import groovy.json.*
import groovy.json.*

def diffOfApi='''[{"op":"replace","path":"/data/0/messageBody","value":"<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<WCS reference=\"336042800000431486\"><PREPARATION_REQUEST requestId=\"WDP_PICKVRAC3\" date=\"2022-02-08 18:33:39\"><CONTAINERS><CONTAINER containerId=\"336042800000431486_21_21121\" handle=\"CREATE\" wmsOrderId=\"WDP_PICKVRAC3\" site=\"CPEEPF\" status=\"CREATED\" referenceDate=\"2022-02-08 18:33:39\" purgeAuthorized=\"false\"><BARCODES><BARCODE main=\"false\" reusable=\"false\">336042800000431486</BARCODE></BARCODES><PACKAGING>TX</PACKAGING><WEIGHT_CHECKING mode=\"NO\"/></CONTAINER></CONTAINERS></PREPARATION_REQUEST></WCS>"}]'''

diffOfApi = diffOfApi.replaceAll( /=.{1}([^"]+)"/, "='\$1'" )

def jsonArray = new JsonSlurper().parseText diffOfApi

assert 3 == jsonArray.first().size()

def xml = new XmlSlurper().parseText jsonArray.first().value // root element points to <WCS/>

assert 'WDP_PICKVRAC3' == xml.PREPARATION_REQUEST.@requestId.text()
</code>```

Body:
I get no way to parse this Json which seems to be valid for me :

def diffOfApi='''[{"op":"replace","path":"/data/0/messageBody","value":"<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<WCS reference=\"336042800000431486\"><PREPARATION_REQUEST requestId=\"WDP_PICKVRAC3\" date=\"2022-02-08 18:33:39\"><CONTAINERS><CONTAINER containerId=\"336042800000431486_21_21121\" handle=\"CREATE\" wmsOrderId=\"WDP_PICKVRAC3\" site=\"CPEEPF\" status=\"CREATED\" referenceDate=\"2022-02-08 18:33:39\" purgeAuthorized=\"false\"><BARCODES><BARCODE main=\"false\" reusable=\"false\">336042800000431486</BARCODE></BARCODES><PACKAGING>TX</PACKAGING><WEIGHT_CHECKING mode=\"NO\"/></CONTAINER></CONTAINERS></PREPARATION_REQUEST></WCS>"}]'''

JSONArray jsonArray = new JSONArray(diffOfApi);

I get this error :

Reason:
org.json.JSONException: Expected a ',' or '}' at 71 [character 72 line 1]
    at org.json.JSONTokener.syntaxError(JSONTokener.java:433)
    at org.json.JSONObject.<init>(JSONObject.java:229)
    at org.json.JSONTokener.nextValue(JSONTokener.java:363)
    at org.json.JSONArray.<init>(JSONArray.java:115)
    at org.json.JSONArray.<init>(JSONArray.java:144)
    at TEST.run(TEST:32)
    at com.kms.katalon.core.main.ScriptEngine.run(ScriptEngine.java:194)
    at com.kms.katalon.core.main.ScriptEngine.runScriptAsRawText(ScriptEngine.java:119)
    at com.kms.katalon.core.main.TestCaseExecutor.runScript(TestCaseExecutor.java:442)
    at com.kms.katalon.core.main.TestCaseExecutor.doExecute(TestCaseExecutor.java:433)
    at com.kms.katalon.core.main.TestCaseExecutor.processExecutionPhase(TestCaseExecutor.java:412)
    at com.kms.katalon.core.main.TestCaseExecutor.accessMainPhase(TestCaseExecutor.java:404)
    at com.kms.katalon.core.main.TestCaseExecutor.execute(TestCaseExecutor.java:281)
    at com.kms.katalon.core.main.TestCaseMain.runTestCase(TestCaseMain.java:142)
    at com.kms.katalon.core.main.TestCaseMain.runTestCase(TestCaseMain.java:133)
    at com.kms.katalon.core.main.TestCaseMain$runTestCase$0.call(Unknown Source)
    at TempTestCase1644483473725.run(TempTestCase1644483473725.groovy:25)

I think it is due to " encapsulated xml in item value

Any idea to make it working ?

Body:
You can replace the \" characters with ' to allow for JSON- and later XML-processing:

import groovy.json.*
import groovy.json.*

def diffOfApi='''[{"op":"replace","path":"/data/0/messageBody","value":"<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<WCS reference=\"336042800000431486\"><PREPARATION_REQUEST requestId=\"WDP_PICKVRAC3\" date=\"2022-02-08 18:33:39\"><CONTAINERS><CONTAINER containerId=\"336042800000431486_21_21121\" handle=\"CREATE\" wmsOrderId=\"WDP_PICKVRAC3\" site=\"CPEEPF\" status=\"CREATED\" referenceDate=\"2022-02-08 18:33:39\" purgeAuthorized=\"false\"><BARCODES><BARCODE main=\"false\" reusable=\"false\">336042800000431486</BARCODE></BARCODES><PACKAGING>TX</PACKAGING><WEIGHT_CHECKING mode=\"NO\"/></CONTAINER></CONTAINERS></PREPARATION_REQUEST></WCS>"}]'''

diffOfApi = diffOfApi.replaceAll( /=.{1}([^"]+)"/, "='\$1'" )

def jsonArray = new JsonSlurper().parseText diffOfApi

assert 3 == jsonArray.first().size()

def xml = new XmlSlurper().parseText jsonArray.first().value // root element points to <WCS/>

assert 'WDP_PICKVRAC3' == xml.PREPARATION_REQUEST.@requestId.text()


问:
AWS MSK - Update storage volume size by modifying the CF
I have created an MSK cluster and all associated configuration using cloud formation template. Now I have to update the stack with more storage. Can I just modify the CF and specify the new storage requirement in the template and run the CF again?  Will it create a new MSK cluster?</p>

答:
Updating a version in CF manifest will update a kafka version since May 2021.
Be sure, that you have enough disk space free for update though, otherwise you'll get the error: Amazon CloudFormation wasn't able to complete the request because of an issue with the server.

This operation will never create a new cluster since the cluster id will stay the same all the time


问:
Render MarkerClusterer with Custom Marker and Dynamic location
I have a issue when rendering markers and clustering them. When i fetch location data list from api completely, map doesn't re-render marker.

When i use custom marker child component, that can re-render map when api is fetch completely. But I can't Clustering these custom marker.

As i know that onGoogleApiLoaded just called once times at the first render so now I have no solution to solve this issue.

Here my code below. Thanks for any help.

```<code>  const get_list_unit_location = useCallback(() => {
    if (units.length) {
      const listLocation = [];
      units.forEach((unit) => {
        if (unit.lat && unit.lng) {
          listLocation.push({
            lat: unit.lat,
            lng: unit.lng,
            subUnitQuantity: unit.sub_units.length,
          });
        }
      });
      setUnitLocations(listLocation);
    }
  }, [units]);

  useEffect(() => {
    get_list_unit_location();
  }, [get_list_unit_location]);

  const setGoogleMapRef = useCallback(
    (map, maps) => {
      if (unitLocations.length) {
        const markers = unitLocations.map((location) => {
          return new maps.Marker({ position: location, map });
        });
        // eslint-disable-next-line no-unused-vars
        const markerCluster = new MarkerClusterer({ map, markers });
      }
    },
    [unitLocations]
  );

<GoogleMapReact
          bootstrapURLKeys={{ key: process.env.REACT_APP_GOOGLE_MAP_API_KEY }}
          defaultCenter={center}
          defaultZoom={zoom}
          options={{
            fullscreenControl: false,
            zoomControl: false,
          }}
          yesIWantToUseGoogleMapApiInternals
          onGoogleApiLoaded={({ map, maps }) => setGoogleMapRef(map, maps)}
        >
          {unitLocations.map((location) => (
            // eslint-disable-next-line react/jsx-key
            <Marker
              lat={location.lat}
              lng={location.lng}
              text={location.subUnitQuantity}
            />
          ))}
        </GoogleMapReact>
</code>```

答:
One solution would be to have setGoogleMapRef do nothing more than store map and maps into some state, and then have a separate useEffect that creates the MarkerClusterer. This will ensure that the clusterer isn't created until both map and data are loaded (and will be recreated if the data changes.) Something like:

```<code>const [ map, setMap ] = useState();
const [ maps, setMaps ] = useState();

const setGoogleMapRef = useCallback((map, maps) => {
    setMap(map);
    setMaps(maps);
}, [ setMap, setMaps ]);

useEffect(() => {
    if (unitLocations.length && map && maps) {
        // create markers and clusterer
    }
}, [ unitLocations, map, maps]);
</code>```

Alternatively, if you're willing to look at a different package, @react-google-maps/api has a component for the clusterer as well as the map, marker, etc:

```<code><GoogleMap ...>
    <MarkerClusterer ...>
        {clusterer => unitLocations.map((location, index) => {
           <Marker position={location} clusterer={clusterer}/>
        }
    </MarkerClusterer>
</GoogleMap >
</code>```

Body:
I have a issue when rendering markers and clustering them. When i fetch location data list from api completely, map doesn't re-render marker.

When i use custom marker child component, that can re-render map when api is fetch completely. But I can't Clustering these custom marker.

As i know that onGoogleApiLoaded just called once times at the first render so now I have no solution to solve this issue.

Here my code below. Thanks for any help.

  const get_list_unit_location = useCallback(() => {
    if (units.length) {
      const listLocation = [];
      units.forEach((unit) => {
        if (unit.lat && unit.lng) {
          listLocation.push({
            lat: unit.lat,
            lng: unit.lng,
            subUnitQuantity: unit.sub_units.length,
          });
        }
      });
      setUnitLocations(listLocation);
    }
  }, [units]);

  useEffect(() => {
    get_list_unit_location();
  }, [get_list_unit_location]);

  const setGoogleMapRef = useCallback(
    (map, maps) => {
      if (unitLocations.length) {
        const markers = unitLocations.map((location) => {
          return new maps.Marker({ position: location, map });
        });
        // eslint-disable-next-line no-unused-vars
        const markerCluster = new MarkerClusterer({ map, markers });
      }
    },
    [unitLocations]
  );

<GoogleMapReact
          bootstrapURLKeys={{ key: process.env.REACT_APP_GOOGLE_MAP_API_KEY }}
          defaultCenter={center}
          defaultZoom={zoom}
          options={{
            fullscreenControl: false,
            zoomControl: false,
          }}
          yesIWantToUseGoogleMapApiInternals
          onGoogleApiLoaded={({ map, maps }) => setGoogleMapRef(map, maps)}
        >
          {unitLocations.map((location) => (
            // eslint-disable-next-line react/jsx-key
            <Marker
              lat={location.lat}
              lng={location.lng}
              text={location.subUnitQuantity}
            />
          ))}
        </GoogleMapReact>

Body:
One solution would be to have setGoogleMapRef do nothing more than store map and maps into some state, and then have a separate useEffect that creates the MarkerClusterer. This will ensure that the clusterer isn't created until both map and data are loaded (and will be recreated if the data changes.) Something like:

const [ map, setMap ] = useState();
const [ maps, setMaps ] = useState();

const setGoogleMapRef = useCallback((map, maps) => {
    setMap(map);
    setMaps(maps);
}, [ setMap, setMaps ]);

useEffect(() => {
    if (unitLocations.length && map && maps) {
        // create markers and clusterer
    }
}, [ unitLocations, map, maps]);

Alternatively, if you're willing to look at a different package, @react-google-maps/api has a component for the clusterer as well as the map, marker, etc:

<GoogleMap ...>
    <MarkerClusterer ...>
        {clusterer => unitLocations.map((location, index) => {
           <Marker position={location} clusterer={clusterer}/>
        }
    </MarkerClusterer>
</GoogleMap >


问:
how to update selective fields in jsp (leaving some fields unchanged)
i have created a page with text boxes, details are:

```
         house no:
         streetname:
         cityname:
         pincode:

         contact :
         bloodgroup  :
```

my requirement is to update the details of user.

i wrote an update query,but with that all details are updating.

If the user dont want to change only contact n the remaining details should b the same, then how to do that?

i know how to update, but how to get the old details as it is if user wont update it.

答:
For this you need to build the SQL query dynamically using a StringBuffer inside your DAO layer .
Then update only those fields

Update table Tablename (col1 , col2) values( val1, vale2) .

Body:
i have created a page with text boxes, details are:

         house no:
         streetname:
         cityname:
         pincode:

         contact :
         bloodgroup  :

my requirement is to update the details of user.

i wrote an update query,but with that all details are updating.

If the user dont want to change only contact n the remaining details should b the same, then how to do that?

i know how to update, but how to get the old details as it is if user wont update it.


问:
Swift OSX- View Loading Late (viewDidLoad) (applicationDidFinishLaunching)
Thanks for the help!

Whenever I enter any code after viewDidLoad or applicationDidFinishLaunching,  my view is delayed until after that code has finished. Also tried viewDidAppear.

*Not Using SwiftUI
*Running Big Sur Xcode 13.2.1

Let's say I've entered

```<code>override func viewDidLoad() {
    super.viewDidLoad()

sleep(5) }
</code>```

The view will load after the sleep...  I know sleep isn't a great example, but I've tried it with many functions.

Also if I run any code in AppDelegate - in applicationDidFinishLaunching
Same Result.

Any Tips/ Help/ Updates are greatly appreciated!

答:
You can use DispatchQueue to resolve that issue.

Run your code in another thread using your own queue or predetermined:

```<code>override func viewDidLoad() {
    super.viewDidLoad()

    DispatchQueue.global(qos: .utility).async {
        //your code here
        sleep(5)
    }
}
</code>```

Body:
Thanks for the help!

Whenever I enter any code after viewDidLoad or applicationDidFinishLaunching,  my view is delayed until after that code has finished. Also tried viewDidAppear.

*Not Using SwiftUI
*Running Big Sur Xcode 13.2.1

Let's say I've entered

override func viewDidLoad() {
    super.viewDidLoad()

sleep(5) }

The view will load after the sleep...  I know sleep isn't a great example, but I've tried it with many functions.

Also if I run any code in AppDelegate - in applicationDidFinishLaunching
Same Result.

Any Tips/ Help/ Updates are greatly appreciated!

Body:
You can use DispatchQueue to resolve that issue.

Run your code in another thread using your own queue or predetermined:

override func viewDidLoad() {
    super.viewDidLoad()

    DispatchQueue.global(qos: .utility).async {
        //your code here
        sleep(5)
    }
}


问:
bootstrap 5 popover with html content
I am trying to get separate the bootstrap5 popover content from the HTML attributes like you can do with other components, but I can't get it to work.

var popoverTriggerList = [].slice.call(document.querySelectorAll('[data-bs-toggle="popover"]'))
var popoverList = popoverTriggerList.map(function(popoverTriggerEl) {
  return new bootstrap.Popover(popoverTriggerEl)
})```
<pre class="snippet-code-html lang-html prettyprint-override"><code><!-- Bootstrap CSS -->
<link href="https://cdn.jsdelivr.net/npm/bootstrap@5.0.0-beta3/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-eOJMYsd53ii+scO/bJGFsiCZc+5NDVN2yr8+0RDqr0Ql0h+rP48ckxlpbzKgwra6" crossorigin="anonymous">

Click to toggle popover
<div id="customdiv" style="display: none">
  <h1> popover </h1>
</div>

<script src="https://cdn.jsdelivr.net/npm/@popperjs/core@2.9.1/dist/umd/popper.min.js" integrity="sha384-SR1sx49pcuLnqZUnnPwx6FCym0wLsk5JZuNx2bPPENzswTNFaQU1RDvt3wT4gWFG" crossorigin="anonymous"></script>
<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.0.0-beta3/dist/js/bootstrap.min.js" integrity="sha384-j0CNLUeiqtyaRmlzUHCPZ+Gy5fQu0dQ6eZ/xAww941Ai1SxSY+0EQqNXNE6DZiVc" crossorigin="anonymous"></script></code>```

答:
var popoverTriggerList = [].slice.call(document.querySelectorAll('[data-bs-toggle="popover"]'))
var popoverList = popoverTriggerList.map(function (popoverTriggerEl) {
  return new bootstrap.Popover(popoverTriggerEl)
})
var popover = new bootstrap.Popover(document.querySelector('.element'), {
        trigger: 'hover',
        html: true,
        content:function () {
            return 'Test';
        },
})```

Title: bootstrap 5 popover with html content

Body:
I am trying to get separate the bootstrap5 popover content from the HTML attributes like you can do with other components, but I can't get it to work.

var popoverTriggerList = [].slice.call(document.querySelectorAll('[data-bs-toggle="popover"]'))
var popoverList = popoverTriggerList.map(function(popoverTriggerEl) {
  return new bootstrap.Popover(popoverTriggerEl)
})

<link href="https://cdn.jsdelivr.net/npm/bootstrap@5.0.0-beta3/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-eOJMYsd53ii+scO/bJGFsiCZc+5NDVN2yr8+0RDqr0Ql0h+rP48ckxlpbzKgwra6" crossorigin="anonymous">

Click to toggle popover

 popover

Body:
var popoverTriggerList = [].slice.call(document.querySelectorAll('[data-bs-toggle="popover"]'))
var popoverList = popoverTriggerList.map(function (popoverTriggerEl) {
  return new bootstrap.Popover(popoverTriggerEl)
})
var popover = new bootstrap.Popover(document.querySelector('.element'), {
        trigger: 'hover',
        html: true,
        content:function () {
            return '<label>Test</label>';
        },
})


问:
TypeError: ObjectId('') is not JSON serializable
My response back from MongoDB after querying an aggregated function on document using Python, It returns valid response and i can print it but can not return it.

Error:

```<code>TypeError: ObjectId('51948e86c25f4b1d1c0d303c') is not JSON serializable
</code>```

Print:

```<code>{'result': [{'_id': ObjectId('51948e86c25f4b1d1c0d303c'), 'api_calls_with_key': 4, 'api_calls_per_day': 0.375, 'api_calls_total': 6, 'api_calls_without_key': 2}], 'ok': 1.0}
</code>```

But When i try to return:

```<code>TypeError: ObjectId('51948e86c25f4b1d1c0d303c') is not JSON serializable
</code>```

It is RESTfull call:

```<code>@appv1.route('/v1/analytics')
def get_api_analytics():
    # get handle to collections in MongoDB
    statistics = sldb.statistics

    objectid = ObjectId("51948e86c25f4b1d1c0d303c")

    analytics = statistics.aggregate([
    {'$match': {'owner': objectid}},
    {'$project': {'owner': "$owner",
    'api_calls_with_key': {'$cond': [{'$eq': ["$apikey", None]}, 0, 1]},
    'api_calls_without_key': {'$cond': [{'$ne': ["$apikey", None]}, 0, 1]}
    }},
    {'$group': {'_id': "$owner",
    'api_calls_with_key': {'$sum': "$api_calls_with_key"},
    'api_calls_without_key': {'$sum': "$api_calls_without_key"}
    }},
    {'$project': {'api_calls_with_key': "$api_calls_with_key",
    'api_calls_without_key': "$api_calls_without_key",
    'api_calls_total': {'$add': ["$api_calls_with_key", "$api_calls_without_key"]},
    'api_calls_per_day': {'$divide': [{'$add': ["$api_calls_with_key", "$api_calls_without_key"]}, {'$dayOfMonth': datetime.now()}]},
    }}
    ])

    print(analytics)

    return analytics
</code>```

db is well connected and collection is there too and I got back valid expected result but when i try to return it gives me Json error. Any idea how to convert the response back into JSON. Thanks

答:
If you want to send it as a JSON response you need to format in two steps

Using json_util.dumps() from bson to covert ObjectId in BSON response to
JSON compatible format i.e. "_id": {"$oid": "123456789"}

The above JSON Response obtained from json_util.dumps()  will have backslashes and quotes

To remove backslashes and quotes use json.loads() from json

from bson import json_util
import json

bson_data = [{'_id': ObjectId('123456789'), 'field': 'somedata'},{'_id': ObjectId('123456781'), 'field': 'someMoredata'}]

json_data_with_backslashes = json_util.dumps(bson_data)

# output will look like this
# "[{\"_id\": {\"$oid\": \"123456789\"}, \"field\": \"somedata\"},{\"_id\": {\"$oid\": \"123456781\"}, \"field\": \"someMoredata\"}]"

json_data = json.loads(json_data_with_backslashes)

# output will look like this
# [{"_id": {"$oid": "123456789"},"field": "somedata"},{"_id": {"$oid": "123456781"},"field": "someMoredata"}]

```

Body:
My response back from MongoDB after querying an aggregated function on document using Python, It returns valid response and i can print it but can not return it.

Error:

TypeError: ObjectId('51948e86c25f4b1d1c0d303c') is not JSON serializable

Print:

{'result': [{'_id': ObjectId('51948e86c25f4b1d1c0d303c'), 'api_calls_with_key': 4, 'api_calls_per_day': 0.375, 'api_calls_total': 6, 'api_calls_without_key': 2}], 'ok': 1.0}

But When i try to return:

TypeError: ObjectId('51948e86c25f4b1d1c0d303c') is not JSON serializable

It is RESTfull call:

@appv1.route('/v1/analytics')
def get_api_analytics():
    # get handle to collections in MongoDB
    statistics = sldb.statistics

    objectid = ObjectId("51948e86c25f4b1d1c0d303c")

    analytics = statistics.aggregate([
    {'$match': {'owner': objectid}},
    {'$project': {'owner': "$owner",
    'api_calls_with_key': {'$cond': [{'$eq': ["$apikey", None]}, 0, 1]},
    'api_calls_without_key': {'$cond': [{'$ne': ["$apikey", None]}, 0, 1]}
    }},
    {'$group': {'_id': "$owner",
    'api_calls_with_key': {'$sum': "$api_calls_with_key"},
    'api_calls_without_key': {'$sum': "$api_calls_without_key"}
    }},
    {'$project': {'api_calls_with_key': "$api_calls_with_key",
    'api_calls_without_key': "$api_calls_without_key",
    'api_calls_total': {'$add': ["$api_calls_with_key", "$api_calls_without_key"]},
    'api_calls_per_day': {'$divide': [{'$add': ["$api_calls_with_key", "$api_calls_without_key"]}, {'$dayOfMonth': datetime.now()}]},
    }}
    ])

    print(analytics)

    return analytics

db is well connected and collection is there too and I got back valid expected result but when i try to return it gives me Json error. Any idea how to convert the response back into JSON. Thanks


问:
How to iterate through Hashtable that has values as List?
I wanted to have multiple values for a single key in my hashtable, so I created key value pair as

```<code>Hashtable A = new Hashtable(StringComparer.InvariantCultureIgnoreCase);

List<string> DataList = new List<string>();
DataList.Add(userName);
DataList.Add(firstName);
DataList.Add(lastName);
DataList.Add(Pwd);

if (!A.ContainsKey(ID))
{
    A.Add(ID, DataList);
}

</code>```

For example, my hashtable contains values as

```<code>Hashtable A -> Key : 1 , Value : {'A','B','1234','@red'}

Hashtable B -> Key : 2, Value : {'Emma','B','111','@blue'}
</code>```

I have two hashtables and I want to compare the date using the key. If the key is present in both tables, then I wish to compare the values of that key in both tables. If there is any change, then I output it.

For example, if ID- 1001 is present in both A and B, then I check the list of values in both table for 1001. If for example, A has third value '1234' and B has third value as '111', then I output 111.

Its just a comparison of hashtable but I am stuck at iterating through the values.

```<code>foreach(DictionaryEntry details in A)
{
    if(details.Key.Equals(Key of Hashtable B))
    {
        //I want to do something like this if both Hashtables have same key
        string firstname = 'A';
        string lastname = 'B';
        string password ='1234' and so on...
        // I just wish to store the values of first hashtable in some variables so that I can use them further.
    }
}
</code>```

I tried using foreach but it gave me error that

```<code>Foreach statement cannot operate on variables of type 'object' because 'object' does not contain a public definition for 'GetEnumerator'
</code>```

How do I parse through this list of values in Hashtable?

答:
From your comments and your question, I gather you want to iterate over the values and do something with them. The reason you can't is because the HashTable is a non-generic collection, so all your values are stored as type object, ergo the error. To fix this, you need to type-cast what you receive as a List<string>:

```<code>foreach(DictionaryEntry details in A)
{
    if(B.ContainsKey(details.Key))
    {
        List<string> data = B[details.Key] as List<string>;
        // Do the thing here
    }
}
</code>```

Body:
I wanted to have multiple values for a single key in my hashtable, so I created key value pair as

Hashtable A = new Hashtable(StringComparer.InvariantCultureIgnoreCase);

List<string> DataList = new List<string>();
DataList.Add(userName);
DataList.Add(firstName);
DataList.Add(lastName);
DataList.Add(Pwd);

if (!A.ContainsKey(ID))
{
    A.Add(ID, DataList);
}

For example, my hashtable contains values as

Hashtable A -> Key : 1 , Value : {'A','B','1234','@red'}

Hashtable B -> Key : 2, Value : {'Emma','B','111','@blue'}

I have two hashtables and I want to compare the date using the key. If the key is present in both tables, then I wish to compare the values of that key in both tables. If there is any change, then I output it.

For example, if ID- 1001 is present in both A and B, then I check the list of values in both table for 1001. If for example, A has third value '1234' and B has third value as '111', then I output 111.

Its just a comparison of hashtable but I am stuck at iterating through the values.

foreach(DictionaryEntry details in A)
{
    if(details.Key.Equals(Key of Hashtable B))
    {
        //I want to do something like this if both Hashtables have same key
        string firstname = 'A';
        string lastname = 'B';
        string password ='1234' and so on...
        // I just wish to store the values of first hashtable in some variables so that I can use them further.
    }
}

I tried using foreach but it gave me error that

Foreach statement cannot operate on variables of type 'object' because 'object' does not contain a public definition for 'GetEnumerator'

How do I parse through this list of values in Hashtable?

Body:
From your comments and your question, I gather you want to iterate over the values and do something with them. The reason you can't is because the HashTable is a non-generic collection, so all your values are stored as type object, ergo the error. To fix this, you need to type-cast what you receive as a List<string>:

foreach(DictionaryEntry details in A)
{
    if(B.ContainsKey(details.Key))
    {
        List<string> data = B[details.Key] as List<string>;
        // Do the thing here
    }
}


问:
how can i fix this runtime error for a simple code written in c?
My code shows me a wrong output by showing the area to be zero:

```<code>#include <stdio.h>
double calc(float rad);
void main(void) {
    float rad;
    printf("Enter the circle radius: \n");
    scanf("%f",&rad);
    printf("You entered: %f\n",rad);
        printf("Area is %d\n",calc(rad));
    if(calc(rad)>1000){
       printf("Area is > 1000");
    }
    else{
         printf("Area is < 1000");
    }

}

double calc(float rad){
   double area=3.14*rad*rad;
   return area;
}
</code>```

Output:

Enter the circle radius : 20
you entered 20.000000
area is 0
area > 1000
```
<p>Desired output:</p>
<pre class="lang-none prettyprint-override"><code>Enter the circle radius : 20
you entered 20.000000
area is 1256.000000
area > 1000
</code>```

答:
```<code>#include <stdio.h>
double calc(float rad);
void main(void) {
   float rad;
   printf("Enter the circle radius: \n");
   scanf("%f",&rad);
   printf("You entered: %d\n",rad);
       printf("Area is %f\n",calc(rad));
   if(calc(rad)>1000){
      printf("Area is > 1000");
   }
   else{
        printf("Area is < 1000");
   }

}

double calc(float rad){
  double area=3.14*rad*rad;
  return area;
}
</code>```

This is the correct code.
if you want more information :

https://codeforwin.org/2015/05/list-of-all-format-specifiers-in-c-programming.html

https://www.cplusplus.com/reference/cstdio/printf/

https://aticleworld.com/format-specifiers-in-c/
Please go to the last link first.I am sorry for any bad english.

Body:
My code shows me a wrong output by showing the area to be zero:

#include <stdio.h>
double calc(float rad);
void main(void) {
    float rad;
    printf("Enter the circle radius: \n");
    scanf("%f",&rad);
    printf("You entered: %f\n",rad);
        printf("Area is %d\n",calc(rad));
    if(calc(rad)>1000){
       printf("Area is > 1000");
    }
    else{
         printf("Area is < 1000");
    }

}

double calc(float rad){
   double area=3.14*rad*rad;
   return area;
}

Output:

Enter the circle radius : 20
you entered 20.000000
area is 0
area > 1000

Desired output:

Enter the circle radius : 20
you entered 20.000000
area is 1256.000000
area > 1000

Body:
#include <stdio.h>
double calc(float rad);
void main(void) {
   float rad;
   printf("Enter the circle radius: \n");
   scanf("%f",&rad);
   printf("You entered: %d\n",rad);
       printf("Area is %f\n",calc(rad));
   if(calc(rad)>1000){
      printf("Area is > 1000");
   }
   else{
        printf("Area is < 1000");
   }

}

double calc(float rad){
  double area=3.14*rad*rad;
  return area;
}

This is the correct code.
if you want more information :

https://codeforwin.org/2015/05/list-of-all-format-specifiers-in-c-programming.html

https://www.cplusplus.com/reference/cstdio/printf/

https://aticleworld.com/format-specifiers-in-c/
Please go to the last link first.I am sorry for any bad english.


问:
Visual Studio 2010 opens wrong file
Visual Studio has a habit of opening the wrong file in my solution - only a small proportion of the time, but several times a day and often enough to be annoying.  It can happen when doing any of the following:

Opening a file from solution explorer

Using F7 to switch between aspx and code behind

Right clicking a method and selecting "go to declaration"

Has anyone else experienced this and have any ideas as to what could cause / fix this?

Update: I've finally got round to installing SP1 and it still occurs so I'm back to looking for a solution.

In case it's relevant, I've got both Resharper 5.1 and Visual Studio Productivity Power Tools installed.

Update 2: It looks like Visual Studio Productivity Power Tools was part of the problem, I’ve uninstalled it and have not had issues since.

答: I uninstalled Visual Studio Productivity Power Tools and it now works.</p>

Title: Visual Studio 2010 opens wrong file


问:
Crash in GStreamer qmlglsink pipeline dynamically rebind to different GstGLVideoItem
I've used one of existing qmlglsink examples to stream video feed from 4 IP Cameras.
4 Pipelines are created before engine load.

```<code>for(int i = 0; i < maxCameras; ++i) {
    GstElement* pipeline = gst_pipeline_new (NULL);
    GstElement* src = gst_element_factory_make ("udpsrc", NULL);
    GstElement* parse = gst_element_factory_make ("jpegparse", NULL);
    GstElement* decoder = gst_element_factory_make ("jpegdec", NULL);
    GstElement* glcolorconvert = gst_element_factory_make ("glcolorconvert", NULL);
    GstElement* glupload = gst_element_factory_make ("glupload", NULL);
    GstElement *sink = gst_element_factory_make ("qmlglsink", NULL);

    g_assert (src && parse && decoder && glupload && glcolorconvert && sink);

    g_object_set (G_OBJECT (src), "port", startingPort + i, NULL);

    g_object_set (G_OBJECT (sink), "sync", FALSE, NULL);

    gst_bin_add_many (GST_BIN (pipeline), src, parse, decoder, glupload, glcolorconvert, sink, NULL);
    if (!gst_element_link_many ( src, parse, decoder, glupload, glcolorconvert, sink, NULL)) {
        qDebug() << "Linking GStreamer pipeline elements failed";
    }

    sinks.insert(std::make_pair(QString::number(startingPort+i), sink));
    pipelines.insert(std::make_pair(QString::number(startingPort+i), pipeline));
}
</code>```

In Qml sink is connected and processed with

```<code>import QtQuick 2.15
import QtQuick.Layouts 1.15
import CustomProject 1.0
import org.freedesktop.gstreamer.GLVideoItem 1.0

Item {
    id: root

    signal clicked()
    required property int udpPort
    property var camConnect: undefined
    onUdpPortChanged: { setupConnection(); }

    onVisibleChanged: {
        if (visible) { setupConnection();
        } else { camConnect = undefined }
    }

    GstGLVideoItem {
        id: videoItem
        anchors.fill: parent
        function connect() {
            CameraSinksFactory.connectSink(this, udpPort)
        }
    }
    MouseArea {
        anchors.fill: parent
        onClicked: {
            CameraSinksFactory.stopPipeline(udpPort)
            root.clicked()
        }
    }

    function setupConnection() {
        if (udpPort <= 0 || !root.visible) return;
        videoItem.connect()
        root.camConnect = CameraSinksFactory.getCamConnection(udpPort);
        root.camConnect.resolutionX =// - 15 root.width
        root.camConnect.resolutionY = root.height
        root.camConnect.bitrate = 15000000
        root.camConnect.streaming = root.visible
        CameraSinksFactory.startPipeline(udpPort)
    }
}
</code>```

Problem: Main screen display 4 (2x2 grid) items using Model (which provides udpPort as unique ID). When User clicks on one Item - feed from this camera should fill whole screen. In Examples they create GridLayout with 4/6 explicit items and just manipulate their visiblity (in effect clicked item is only one remaining and take whole screen).

In my case - I'm using separate Item for full screen view. So I'm disabling streaming (CamConnection class communicating with Cameras and sending commands) and hide GridView. New GstGLVideoItem binds to qmlglsink in pipeline.

Everything is OK, until I repeat click sequence (back to GridView and to fullview). Every time it ends with:

Bail out! ERROR:../ext/qt/gstqsgtexture.cc:134:virtual void
GstQSGTexture::bind(): code should not be reached

** (KMS:20495): CRITICAL **: 15:47:36.937: gst_video_frame_map_id: assertion 'info->width <= meta->width' failed

** ERROR:../ext/qt/gstqsgtexture.cc:134:virtual void GstQSGTexture::bind(): code should not be reached

From plugins code analysis it's happening when INFO (image size read from CAPS) is bigger then size in metadata in provided buffer. Which is understandable - buffer is too small.

I used GST_DEBUG=4/5/6/7 and logs confirm that autodetected caps are matching request in commands sent to camera.

I can use example, but project assumes another panel with those cameras - so above problem will hit me in near future.

How to make this whole setup working?  How to rebind pipeline qmlglsink to new QML VideoItem safely?

答:
Two possible solutions:

set gst_element_set_state (pipeline, GST_STATE_NULL);, change sink widget to new item and start pipeline gst_element_set_state (pipeline, GST_STATE_PLAYING);

use Qt 5 MediaPlayer with gst-pipeline as source. When visible set source and execute start(). When not visible reset source to empty (important) and execute stop().

In general - possible benefits from NOT creating pipeline each time are not worth hassle when we dynamically assign new QML Item to pipeline sink.

Body:
I've used one of existing qmlglsink examples to stream video feed from 4 IP Cameras.
4 Pipelines are created before engine load.

for(int i = 0; i < maxCameras; ++i) {
    GstElement* pipeline = gst_pipeline_new (NULL);
    GstElement* src = gst_element_factory_make ("udpsrc", NULL);
    GstElement* parse = gst_element_factory_make ("jpegparse", NULL);
    GstElement* decoder = gst_element_factory_make ("jpegdec", NULL);
    GstElement* glcolorconvert = gst_element_factory_make ("glcolorconvert", NULL);
    GstElement* glupload = gst_element_factory_make ("glupload", NULL);
    GstElement *sink = gst_element_factory_make ("qmlglsink", NULL);

    g_assert (src && parse && decoder && glupload && glcolorconvert && sink);

    g_object_set (G_OBJECT (src), "port", startingPort + i, NULL);

    g_object_set (G_OBJECT (sink), "sync", FALSE, NULL);

    gst_bin_add_many (GST_BIN (pipeline), src, parse, decoder, glupload, glcolorconvert, sink, NULL);
    if (!gst_element_link_many ( src, parse, decoder, glupload, glcolorconvert, sink, NULL)) {
        qDebug() << "Linking GStreamer pipeline elements failed";
    }

    sinks.insert(std::make_pair(QString::number(startingPort+i), sink));
    pipelines.insert(std::make_pair(QString::number(startingPort+i), pipeline));
}

In Qml sink is connected and processed with

import QtQuick 2.15
import QtQuick.Layouts 1.15
import CustomProject 1.0
import org.freedesktop.gstreamer.GLVideoItem 1.0

Item {
    id: root

    signal clicked()
    required property int udpPort
    property var camConnect: undefined
    onUdpPortChanged: { setupConnection(); }

    onVisibleChanged: {
        if (visible) { setupConnection();
        } else { camConnect = undefined }
    }

    GstGLVideoItem {
        id: videoItem
        anchors.fill: parent
        function connect() {
            CameraSinksFactory.connectSink(this, udpPort)
        }
    }
    MouseArea {
        anchors.fill: parent
        onClicked: {
            CameraSinksFactory.stopPipeline(udpPort)
            root.clicked()
        }
    }

    function setupConnection() {
        if (udpPort <= 0 || !root.visible) return;
        videoItem.connect()
        root.camConnect = CameraSinksFactory.getCamConnection(udpPort);
        root.camConnect.resolutionX =// - 15 root.width
        root.camConnect.resolutionY = root.height
        root.camConnect.bitrate = 15000000
        root.camConnect.streaming = root.visible
        CameraSinksFactory.startPipeline(udpPort)
    }
}

Problem: Main screen display 4 (2x2 grid) items using Model (which provides udpPort as unique ID). When User clicks on one Item - feed from this camera should fill whole screen. In Examples they create GridLayout with 4/6 explicit items and just manipulate their visiblity (in effect clicked item is only one remaining and take whole screen).

In my case - I'm using separate Item for full screen view. So I'm disabling streaming (CamConnection class communicating with Cameras and sending commands) and hide GridView. New GstGLVideoItem binds to qmlglsink in pipeline.

Everything is OK, until I repeat click sequence (back to GridView and to fullview). Every time it ends with:

Bail out! ERROR:../ext/qt/gstqsgtexture.cc:134:virtual void
GstQSGTexture::bind(): code should not be reached

** (KMS:20495): CRITICAL **: 15:47:36.937: gst_video_frame_map_id: assertion 'info->width <= meta->width' failed

** ERROR:../ext/qt/gstqsgtexture.cc:134:virtual void GstQSGTexture::bind(): code should not be reached

From plugins code analysis it's happening when INFO (image size read from CAPS) is bigger then size in metadata in provided buffer. Which is understandable - buffer is too small.

I used GST_DEBUG=4/5/6/7 and logs confirm that autodetected caps are matching request in commands sent to camera.

I can use example, but project assumes another panel with those cameras - so above problem will hit me in near future.

How to make this whole setup working?  How to rebind pipeline qmlglsink to new QML VideoItem safely?


问:
Jest beforeAll() share between multiple test files
I have a Node.js project that I'm testing using Jest.  I have several test files that have the same setup requirement.  Previously, all these tests were in one file, so I just had a beforeAll(...) that performed the common setup.  Now, with the tests split into multiple files, it seems like I have to copy/paste that beforeAll(...) code into each of the files.  That seems inelegant - is there a better way to do this, ideally where I can just write my beforeAll(...)/setup logic once, and "require" it from multiple test files?  Note that there are other tests in my test suite that don't require this setup functionality, so I don't want to make all my tests run this setup (just a particular subset of test files).

答:
Create a function somewhere like so:

export function setupBeforeAndAfter(putParamsHereIfYouHaveAny) {
  beforeAll(() => shared-before-all-code);
  afterAll(() => shared-after-all-code);
  beforeEach(() => shared-before-each-code);
  afterEach(() => shared-after-each-code);
}
```
<p>Then just call it wherever you would otherwise have manually written these functions:</p>
<pre class="lang-js prettyprint-override"><code>describe('My test', () => {
  setupBeforeAndAfter(putParamsHereIfYouHaveAny)

  it('is amazing', () => {
    // Stuff in setupBeforeAndAfter() will run before/after this test as appropriate
  })
})
</code>```

Body:
Create a function somewhere like so:

export function setupBeforeAndAfter(putParamsHereIfYouHaveAny) {
  beforeAll(() => shared-before-all-code);
  afterAll(() => shared-after-all-code);
  beforeEach(() => shared-before-each-code);
  afterEach(() => shared-after-each-code);
}

Then just call it wherever you would otherwise have manually written these functions:

describe('My test', () => {
  setupBeforeAndAfter(putParamsHereIfYouHaveAny)

  it('is amazing', () => {
    // Stuff in setupBeforeAndAfter() will run before/after this test as appropriate
  })
})


问:
How to concatenate multiple rows list with same value into single row
I have the following class called "Person".

```<code>public class Person
{
    public int Id { get; set; }
    public string Name { get; set; }
    public string Hobby { get; set; }
}
</code>```

I created a list with the following data:

```<code>List<Person> users = new List<Person>()
{
    new Person {Id= 1, Name = "Silva", Hobby = "Football" },
    new Person {Id= 2, Name = "Bob", Hobby = "Golf"},
    new Person {Id= 2, Name = "Bob", Hobby = "Tennis"},
    new Person {Id= 1, Name = "Silva", Hobby = "Sleeping"},
    new Person {Id= 3, Name = "Sue", Hobby = "Drinking"}
    new Person {Id= 1, Name = "Silva", Hobby = "Handball"},
    new Person {Id= 3, Name = "Sue", Hobby = "Football"},
};
</code>```

Now I need to create a new list called "usersHobbies" that when called returns the following result.

```<code>Id    Name        Hobby
1     Silva       Football, Sleeping, Handball
2     Bob         Golf, Tennis
3     Sue         Drinking, Football
</code>```

答:
.GroupBy() has an override that lets you define a key selector, an element selector and the result selector (docs), which could suit your use case:

```<code>var result = users
    .GroupBy(
        u => new { u.Id, u.Name }, // key selector
        u => u.Hobby, // element selector
        (user, hobbies) => new Person {
            Id = user.Id,
            Name = user.Name,
            Hobby = string.Join(", ", hobbies) })
    .ToList();

</code>```

Here, (user, hobbies) are referencing the key selector and the element selector, respectively.

What happens is:

the users are grouped into unique users based on the combination of Id and Name (key selector)

the hobbies of each unique user are collected into an IEnumerable<string> (element selector)

for each unique user, a Person object is created and populated with all of the users hobbies.

Body:
I have the following class called "Person".

public class Person
{
    public int Id { get; set; }
    public string Name { get; set; }
    public string Hobby { get; set; }
}

I created a list with the following data:

List<Person> users = new List<Person>()
{
    new Person {Id= 1, Name = "Silva", Hobby = "Football" },
    new Person {Id= 2, Name = "Bob", Hobby = "Golf"},
    new Person {Id= 2, Name = "Bob", Hobby = "Tennis"},
    new Person {Id= 1, Name = "Silva", Hobby = "Sleeping"},
    new Person {Id= 3, Name = "Sue", Hobby = "Drinking"}
    new Person {Id= 1, Name = "Silva", Hobby = "Handball"},
    new Person {Id= 3, Name = "Sue", Hobby = "Football"},
};

Now I need to create a new list called "usersHobbies" that when called returns the following result.

Id    Name        Hobby
1     Silva       Football, Sleeping, Handball
2     Bob         Golf, Tennis
3     Sue         Drinking, Football

Body:
.GroupBy() has an override that lets you define a key selector, an element selector and the result selector (docs), which could suit your use case:

var result = users
    .GroupBy(
        u => new { u.Id, u.Name }, // key selector
        u => u.Hobby, // element selector
        (user, hobbies) => new Person {
            Id = user.Id,
            Name = user.Name,
            Hobby = string.Join(", ", hobbies) })
    .ToList();

Here, (user, hobbies) are referencing the key selector and the element selector, respectively.

What happens is:

the users are grouped into unique users based on the combination of Id and Name (key selector)

the hobbies of each unique user are collected into an IEnumerable<string> (element selector)

for each unique user, a Person object is created and populated with all of the users hobbies.


问:
Short way to write IF Statement + Assignment of Async Function in one line
Consider the code

```<code>let promiseEmployees;
const employeeFlag = DB.GetFromEMPDB(); // Goes to DAL and gets results

if (employeeFlag) {
    promiseEmployees = async () => {
            // Imp
            // ...
            // ...
            // ...
    };
}
</code>```

Is it possible to rewrite this code in one line without writing literally the if (...) {...} ?

答:
This should work the following way:

const promiseEmployees = !DB.GetFromEMPDB()
  ? undefined
  : async () => {
      // Imp
    };
```

Body:
Consider the code

let promiseEmployees;
const employeeFlag = DB.GetFromEMPDB(); // Goes to DAL and gets results

if (employeeFlag) {
    promiseEmployees = async () => {
            // Imp
            // ...
            // ...
            // ...
    };
}

Is it possible to rewrite this code in one line without writing literally the if (...) {...} ?


问:
c# splitting and retrieving values from a string
I have a string like this:

```<code>"http://localhost:55164/Images/photos/2/2.jpg"
</code>```

I need to retrieve the filename and the 2 out of the /2/ and put them into their own strings. I've been messing around with StringBuilder and replace and substr to no avail since the filename length is variable.  Anyone have a quick way to do this?

Thanks

答:
I would suggest using the Path class:

```<code>string filename = Path.GetFileName(s);
string dir = Path.GetDirectoryName(s).GetFileName(s);
</code>```

Body:
I have a string like this:

"http://localhost:55164/Images/photos/2/2.jpg"

I need to retrieve the filename and the 2 out of the /2/ and put them into their own strings. I've been messing around with StringBuilder and replace and substr to no avail since the filename length is variable.  Anyone have a quick way to do this?

Thanks

Body:
I would suggest using the Path class:

string filename = Path.GetFileName(s);
string dir = Path.GetDirectoryName(s).GetFileName(s);


问:
Jquery submit button click after error message show
** Jquery submit button click after error message show **

jquery submit button after all field message show before error message not show.

i not want to fire error on click element, currently when I click on element it shows error directly.

```<code>$.validator.addMethod("PhoneValidation", (function(e) {
        let regex =  /^(0)(3)[0-9]{7}$/.test(e);
        return(regex);
    }), PHONE_VALIDATE);
    $("#Number_validation_form").validate({
        rules: {
          pho_no: {
            required: true,
            PhoneValidation: true
          }
        },
        messages: {
          pho_no: {
            required: PHONE_VAL_REQUIRED
          }
        },
        errorPlacement: function(e, t) {
            t.is('input[name="accepted"]') ? e.insertAfter($(".checkboxlabel")) : e.insertAfter(t)
        },
        onfocusin: function(element) {
            $(element).valid();
        },
        success: function(e){
            $("#right-mark-img").removeClass( "opacity_0" );
            $("#pho_noNumberSubscriptionBtn").prop('disabled', false);
        },
        submitHandler: function(e) {
            //console.log(e);
        let load = '<span class="spinner-border spinner-border-sm spin" role="status" aria-hidden="true"></span><span class="sr-only">' + LOADING + '...</span>';
        $("#pho_noNumberSubscriptionBtn").html(load);
        $("#pho_noNumberSubscriptionBtn").prop("disabled", true);
        }
      })
</code>```

答:
Your checking validation on focus element just remove onfocusin code.
your final code like below

$.validator.addMethod("PhoneValidation", (function (e) {
                let regex = /^(0)(3)[0-9]{7}$/.test(e);
                return(regex);
            }), "Phone number is not validate");
            $("#Number_validation_form").validate({
                rules: {
                    pho_no: {
                        required: true,
                        PhoneValidation: true
                    }
                },
                messages: {
                    pho_no: {
                        required: "Phone number is required"
                    }
                },
                errorPlacement: function (e, t) {
                    t.is('input[name="accepted"]') ? e.insertAfter($(".checkboxlabel")) : e.insertAfter(t)
                },
                success: function (e) {
                    $("#right-mark-img").removeClass("opacity_0");
                    $("#pho_noNumberSubscriptionBtn").prop('disabled', false);
                },
                submitHandler: function (e) {
                    //console.log(e);
                    let load = 'loading...';
                    $("#pho_noNumberSubscriptionBtn").html(load);
                    $("#pho_noNumberSubscriptionBtn").prop("disabled", true);
                }
            });```
<pre class="snippet-code-html lang-html prettyprint-override"><code><html>
    <head>
        <script
            src="https://code.jquery.com/jquery-3.6.0.min.js"
            integrity="sha256-/xUj+3OJU5yExlq6GSYGSHk7tPXikynS7ogEvDej/m4="
            crossorigin="anonymous"></script>
         <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery-validate/1.19.3/jquery.validate.min.js" integrity="sha512-37T7leoNS06R80c8Ulq7cdCDU5MNQBwlYoy1TX/WUsLFC2eYNqtKlV0QjH7r8JpG/S0GUMZwebnVFLPd6SU5yg==" crossorigin="anonymous" referrerpolicy="no-referrer"></script>
    </head>
    <body>
        <form  id="Number_validation_form" method="post" action="javascript:void(0);">
            <input type="text" name="pho_no"  placeholder="Phone Number">
            <input type="submit" value="Validate">
        </form>

    </body>
</html></code>```

Now Validation is fire on focus out of element

Body:
** Jquery submit button click after error message show **

jquery submit button after all field message show before error message not show.

i not want to fire error on click element, currently when I click on element it shows error directly.

$.validator.addMethod("PhoneValidation", (function(e) {
        let regex =  /^(0)(3)[0-9]{7}$/.test(e);
        return(regex);
    }), PHONE_VALIDATE);
    $("#Number_validation_form").validate({
        rules: {
          pho_no: {
            required: true,
            PhoneValidation: true
          }
        },
        messages: {
          pho_no: {
            required: PHONE_VAL_REQUIRED
          }
        },
        errorPlacement: function(e, t) {
            t.is('input[name="accepted"]') ? e.insertAfter($(".checkboxlabel")) : e.insertAfter(t)
        },
        onfocusin: function(element) {
            $(element).valid();
        },
        success: function(e){
            $("#right-mark-img").removeClass( "opacity_0" );
            $("#pho_noNumberSubscriptionBtn").prop('disabled', false);
        },
        submitHandler: function(e) {
            //console.log(e);
        let load = '' + LOADING + '...';
        $("#pho_noNumberSubscriptionBtn").html(load);
        $("#pho_noNumberSubscriptionBtn").prop("disabled", true);
        }
      })

Body:
Your checking validation on focus element just remove onfocusin code.
your final code like below

$.validator.addMethod("PhoneValidation", (function (e) {
                let regex = /^(0)(3)[0-9]{7}$/.test(e);
                return(regex);
            }), "Phone number is not validate");
            $("#Number_validation_form").validate({
                rules: {
                    pho_no: {
                        required: true,
                        PhoneValidation: true
                    }
                },
                messages: {
                    pho_no: {
                        required: "Phone number is required"
                    }
                },
                errorPlacement: function (e, t) {
                    t.is('input[name="accepted"]') ? e.insertAfter($(".checkboxlabel")) : e.insertAfter(t)
                },
                success: function (e) {
                    $("#right-mark-img").removeClass("opacity_0");
                    $("#pho_noNumberSubscriptionBtn").prop('disabled', false);
                },
                submitHandler: function (e) {
                    //console.log(e);
                    let load = '<span class="spinner-border spinner-border-sm spin" role="status" aria-hidden="true"></span><span class="sr-only">loading...</span>';
                    $("#pho_noNumberSubscriptionBtn").html(load);
                    $("#pho_noNumberSubscriptionBtn").prop("disabled", true);
                }
            });

<html>
    <head>
        <script
            src="https://code.jquery.com/jquery-3.6.0.min.js"
            integrity="sha256-/xUj+3OJU5yExlq6GSYGSHk7tPXikynS7ogEvDej/m4="
            crossorigin="anonymous"></script>
         <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery-validate/1.19.3/jquery.validate.min.js" integrity="sha512-37T7leoNS06R80c8Ulq7cdCDU5MNQBwlYoy1TX/WUsLFC2eYNqtKlV0QjH7r8JpG/S0GUMZwebnVFLPd6SU5yg==" crossorigin="anonymous" referrerpolicy="no-referrer"></script>
    </head>
    <body>
        <form  id="Number_validation_form" method="post" action="javascript:void(0);">
            <input type="text" name="pho_no"  placeholder="Phone Number">
            <input type="submit" value="Validate">
        </form>

    </body>
</html>

Now Validation is fire on focus out of element


问:
Get random password in javascript
I'm making a course and one of the tasks is to generate four different passwords that should fill the four different paragraphs

,

,

,

I have created a script that creates a password but somehow it doesn't print the first password. When I do console.log(password) it shows that creates a password on the console. But when I try to put first.textContent = password it shows nothing.

let chars = ["0", "1", "2", "3", "4", "5", "6", "7", "8", "9", "a", "b", "c", "d", "A", "B", "C", "D"]
let number = 10
let password = ""
let first = document.getElementById("first")
let second = document.getElementById("second")
let third = document.getElementById("third")
let fourth = document.getElementById("fourth")

function generate() {
  for (let i = 0; i < number; i++) {
    let passwordChar = Math.floor(Math.random() * chars.length)
    password += chars[passwordChar]
    return password
  }
}
first.textContent = password```
<pre class="snippet-code-html lang-html prettyprint-override"><code><html>

<head>
  <link rel="stylesheet" href="index.css">
</head>

<body>
  <h1>Generate a random password</h1>
  <p id="description">Never use an insecure password again</p>
  <button onclick="generate()">Generate passwords</button>
  <p id="line"></p>
  <p id="first"></p>
  <p id="second"></p>
  <p id="third"></p>
  <p id="fourth"></p>
</body>

</html></code>```

I'm also stuck to generate each time the function is running a new password and put it on the next paragraph. Like so:

```<code>first.textContent = password
second.textContent = password
third.textContent = password
fourth.textContent = password
</code>```

Any help will be appreciated

答:
It is generally not a good idea to use inline event handlers.

Here is a snippet using event delegation. For retrieving and filling certain elements, use a single identifier for them (here: a data attribute). Now you can loop the elements and fill them with your password values (forEach). In this snippet the passwords are generated using Array.map.

See also...

document.addEventListener(`click`, handle);

function handle(evt) {
// ↓ only do things if button#passGen is clicked
  if (evt.target.id === `passGen`) {
    return generate();
  }
}

function generate() {
  const chars = `0123456789abcdefghijk`;
  document.querySelectorAll(`[data-passgenerated]`)
  //                         ↑ retrieve all p[data-passgenerated]
  // ↓ Loop through the elements and fill them
  .forEach(elem =>  elem.textContent = [...Array(10)].map(v =>
    chars[Math.floor(Math.random() * chars.length)]).join(``)
);
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><p data-passgenerated="1"></p>
<p data-passgenerated="2"></p>
<p data-passgenerated="3"></p>
<p data-passgenerated="4"></p>
<button id="passGen">Create passwords</button></code>```

Title: Get random password in javascript

Body:
I'm making a course and one of the tasks is to generate four different passwords that should fill the four different paragraphs

,

,

,

I have created a script that creates a password but somehow it doesn't print the first password. When I do console.log(password) it shows that creates a password on the console. But when I try to put first.textContent = password it shows nothing.

let chars = ["0", "1", "2", "3", "4", "5", "6", "7", "8", "9", "a", "b", "c", "d", "A", "B", "C", "D"]
let number = 10
let password = ""
let first = document.getElementById("first")
let second = document.getElementById("second")
let third = document.getElementById("third")
let fourth = document.getElementById("fourth")

function generate() {
  for (let i = 0; i < number; i++) {
    let passwordChar = Math.floor(Math.random() * chars.length)
    password += chars[passwordChar]
    return password
  }
}
first.textContent = password

  <link rel="stylesheet" href="index.css">

Generate a random password

Never use an insecure password again

  <button onclick="generate()">Generate passwords</button>

I'm also stuck to generate each time the function is running a new password and put it on the next paragraph. Like so:

first.textContent = password
second.textContent = password
third.textContent = password
fourth.textContent = password

Any help will be appreciated

Body:
It is generally not a good idea to use inline event handlers.

Here is a snippet using event delegation. For retrieving and filling certain elements, use a single identifier for them (here: a data attribute). Now you can loop the elements and fill them with your password values (forEach). In this snippet the passwords are generated using Array.map.

See also...

document.addEventListener(`click`, handle);

function handle(evt) {
// ↓ only do things if button#passGen is clicked
  if (evt.target.id === `passGen`) {
    return generate();
  }
}

function generate() {
  const chars = `0123456789abcdefghijk`;
  document.querySelectorAll(`[data-passgenerated]`)
  //                         ↑ retrieve all p[data-passgenerated]
  // ↓ Loop through the elements and fill them
  .forEach(elem =>  elem.textContent = [...Array(10)].map(v =>
    chars[Math.floor(Math.random() * chars.length)]).join(``)
);
}

<p data-passgenerated="1"></p>
<p data-passgenerated="2"></p>
<p data-passgenerated="3"></p>
<p data-passgenerated="4"></p>
<button id="passGen">Create passwords</button>


问:
How do I configure an AWS Lambda in a VPC to be able to log to another Cloudwatch log group?
How do you configure an AWS Lambda that is in a VPC to be able to log to a Cloudwatch log group other than the one that is associated with the lambda itself?

This is required so that I can avoid the cost of the summary logs that are created with every request, eg:

```<code>2022-02-10T10:16:19.133+00:00   START RequestId: 52cbfd7e-71ec-4499-a292-7c81c94535f3 Version: $LATEST
2022-02-10T10:16:24.250+00:00   END RequestId: 52cbfd7e-71ec-4499-a292-7c81c94535f3
2022-02-10T10:16:24.250+00:00   REPORT RequestId: 52cbfd7e-71ec-4499-a292-7c81c94535f3 Duration: 5100.10 ms Billed Duration: 7412 ms Memory Size: 256 MB Max Memory Used: 201 MB Init Duration: 2311.15 ms
</code>```

So I wish to log my own logs to a separate Cloudwatch log group and add a Deny policy to prevent logging to the default Cloudwatch group that's associated with the lambda by default.

I'm using NLog, so I've done the following so far (following Nlog instructions from here):

Installed Nuget package AWS.Logger.Nlog

Added nlog.config and set it to copy if newer

The contents of nlog.config:

```<code><?xml version="1.0" encoding="utf-8" ?>
<nlog xmlns="http://www.nlog-project.org/schemas/NLog.xsd"
      xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
      throwConfigExceptions="true">
  <extensions>
    <add assembly="AWS.Logger.NLog" />
  </extensions>
  <targets>
    <target name="logconsole" xsi:type="Console" />
    <target name="aws" type="AWSTarget" logGroup="my-lambda-logs" region="us-east-1"/>
  </targets>
  <rules>
    <logger name="*" minlevel="Info" writeTo="logconsole,aws" />
  </rules>
</nlog>
</code>```

The name of my cloudwatch log group is my-lambda-logs and the region is set to us-east-1

When I run my lambda at the moment I'm getting a timeout because it is not able to log to Cloudwatch from within a VPC.

答:
If you haven't already created your lambda, create it within your VPC, specify your private subnet ids and attach a security group that allows outbound (egress) communication on at least port 443 TCP aka HTTPS.

Within VPC on the AWS console, create a VPC Endpoint for Cloudwatch Logs in the region that you wish to log to in the same subnets as your lambda VPC configuration. This will allow your lambda to use the normal cloudwatch endpoint from within your VPC without any log traffic leaving the AWS network.

Ensure that you set Private Dns Enabled to true (you can do this by modifying after creation if you can't find this during creation)

Specify a security group for your new VPC endpoint that includes an inbound (ingress) rule to allow the security group of your lambda to communicate over port 443.

Now that you can communicate with Cloudwatch, you just need to create your log group and give your lamda a policy that allows it to log to your cloudwatch log group.

```<code>{
 "Version": "2012-10-17",
 "Statement": [
 {
   "Action": [
     "logs:CreateLogStream",
     "logs:PutLogEvents",
     "logs:DescribeLogGroups"
   ],
   "Resource": [
      "arn:aws:logs:us-east-1:369074612400:log-group:my-lambda-logs:*",
      "arn:aws:logs:us-east-1:369074612400:log-group:my-lambda-logs:*:*"
   ],
   "Effect": "Allow"
 }
]
</code>```

}

For the sake of this example the ARN of the cloudwatch log group is:

arn:aws:logs:us-east-1:000000000001:log-group:my-lambda-logs

... but you can get yours from the AWS console (it will contain your account id and the correct region of the Cloudwatch group.

Voilá your lambda should now be able to use NLog (or another logging framework) to log to Cloudwatch logs.

Body:
How do you configure an AWS Lambda that is in a VPC to be able to log to a Cloudwatch log group other than the one that is associated with the lambda itself?

This is required so that I can avoid the cost of the summary logs that are created with every request, eg:

2022-02-10T10:16:19.133+00:00   START RequestId: 52cbfd7e-71ec-4499-a292-7c81c94535f3 Version: $LATEST
2022-02-10T10:16:24.250+00:00   END RequestId: 52cbfd7e-71ec-4499-a292-7c81c94535f3
2022-02-10T10:16:24.250+00:00   REPORT RequestId: 52cbfd7e-71ec-4499-a292-7c81c94535f3 Duration: 5100.10 ms Billed Duration: 7412 ms Memory Size: 256 MB Max Memory Used: 201 MB Init Duration: 2311.15 ms

So I wish to log my own logs to a separate Cloudwatch log group and add a Deny policy to prevent logging to the default Cloudwatch group that's associated with the lambda by default.

I'm using NLog, so I've done the following so far (following Nlog instructions from here):

Installed Nuget package AWS.Logger.Nlog

Added nlog.config and set it to copy if newer

The contents of nlog.config:

<?xml version="1.0" encoding="utf-8" ?>
<nlog xmlns="http://www.nlog-project.org/schemas/NLog.xsd"
      xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
      throwConfigExceptions="true">
  <extensions>
    <add assembly="AWS.Logger.NLog" />
  </extensions>
  <targets>
    <target name="logconsole" xsi:type="Console" />
    <target name="aws" type="AWSTarget" logGroup="my-lambda-logs" region="us-east-1"/>
  </targets>
  <rules>
    <logger name="*" minlevel="Info" writeTo="logconsole,aws" />
  </rules>
</nlog>

The name of my cloudwatch log group is my-lambda-logs and the region is set to us-east-1

When I run my lambda at the moment I'm getting a timeout because it is not able to log to Cloudwatch from within a VPC.

Body:
If you haven't already created your lambda, create it within your VPC, specify your private subnet ids and attach a security group that allows outbound (egress) communication on at least port 443 TCP aka HTTPS.

Within VPC on the AWS console, create a VPC Endpoint for Cloudwatch Logs in the region that you wish to log to in the same subnets as your lambda VPC configuration. This will allow your lambda to use the normal cloudwatch endpoint from within your VPC without any log traffic leaving the AWS network.

Ensure that you set Private Dns Enabled to true (you can do this by modifying after creation if you can't find this during creation)

Specify a security group for your new VPC endpoint that includes an inbound (ingress) rule to allow the security group of your lambda to communicate over port 443.

Now that you can communicate with Cloudwatch, you just need to create your log group and give your lamda a policy that allows it to log to your cloudwatch log group.

{
 "Version": "2012-10-17",
 "Statement": [
 {
   "Action": [
     "logs:CreateLogStream",
     "logs:PutLogEvents",
     "logs:DescribeLogGroups"
   ],
   "Resource": [
      "arn:aws:logs:us-east-1:369074612400:log-group:my-lambda-logs:*",
      "arn:aws:logs:us-east-1:369074612400:log-group:my-lambda-logs:*:*"
   ],
   "Effect": "Allow"
 }
]

}

For the sake of this example the ARN of the cloudwatch log group is:

arn:aws:logs:us-east-1:000000000001:log-group:my-lambda-logs

... but you can get yours from the AWS console (it will contain your account id and the correct region of the Cloudwatch group.

Voilá your lambda should now be able to use NLog (or another logging framework) to log to Cloudwatch logs.


问:
Accessing the data interval of a Dag Run inside a task
I'm building an ETL pipeline with Apache Airflow. I have to extract the latest data added to a SQL database (say daily). Therefore, I want to construct a query as follows:

```<code>SELECT foo
FROM bar
WHERE insert_date >= "DATA_INTERVAL_START_HERE"
   AND insert_date < "DATA_INTERVAL_END_HERE"
</code>```

To execute this query in a task (with e.g. pyodbc), I need to access the data interval start and end time of the Dag Run object inside the extract task. How can I retrieve this information?

答:
A similar question was asked here:
Airflow ETL pipeline - using schedule date in functions?
However, the answer is not updated to the TaskFlow API since Airflow 2.0.

A concise way to access the data interval parameters:

```<code>@dag(schedule_interval="@daily", start_date=datetime(2022, 2, 8), catchup=True)
def tutorial_access_data_interval():
     @task()
     def extract(data_interval_start=None, data_interval_end=None, **kwargs):
          #Use data_interval_start, data_interval_end here
</code>```

The Airflow engine will provide the parameters by default.

References:

https://airflow.apache.org/docs/apache-airflow/stable/howto/operator/python.html
https://airflow.apache.org/docs/apache-airflow/stable/templates-ref.html#variables

Body:
I'm building an ETL pipeline with Apache Airflow. I have to extract the latest data added to a SQL database (say daily). Therefore, I want to construct a query as follows:

SELECT foo
FROM bar
WHERE insert_date >= "DATA_INTERVAL_START_HERE"
   AND insert_date < "DATA_INTERVAL_END_HERE"

To execute this query in a task (with e.g. pyodbc), I need to access the data interval start and end time of the Dag Run object inside the extract task. How can I retrieve this information?

Body:
A similar question was asked here:
Airflow ETL pipeline - using schedule date in functions?
However, the answer is not updated to the TaskFlow API since Airflow 2.0.

A concise way to access the data interval parameters:

@dag(schedule_interval="@daily", start_date=datetime(2022, 2, 8), catchup=True)
def tutorial_access_data_interval():
     @task()
     def extract(data_interval_start=None, data_interval_end=None, **kwargs):
          #Use data_interval_start, data_interval_end here

The Airflow engine will provide the parameters by default.

References:

https://airflow.apache.org/docs/apache-airflow/stable/howto/operator/python.html
https://airflow.apache.org/docs/apache-airflow/stable/templates-ref.html#variables


问:
PHP not creating $_SESSION variable on session_start();
I have 3 pages in my set up here:

login.php: The login page that contains the username and password fields which submits to

checklogin.php: Which checks to see if the credentials are right which redirects to

login_successful.php: Which displays the user's name

login.php starts with

```<code><?php session_start(); ?>

<html xmlns="http://www.w3.org/1999/xhtml">

<head>
    <?php
        include 'content.php';
        echo $head;
    ?>
</head>
</code>```

Which should initialize a global $_SESSION variable right?

checklogin.php has some code which looks like this:

```<code>if (mysql_num_rows($result) < 1)
{
    /* Access denied */
    echo 'Sorry, your username or password was incorrect!';
}
else
{
    $_SESSION['username'] = $username;

    /* Log user in */
    header("location:login_successful.php");
}
</code>```

login_successful.php looks like this:

```<code><div id="title" style="margin:5px">
    <h2>Welcome back <?php echo $_SESSION['username']; ?>!</p>
</div>
</code>```

Unfortunately when I go through the login procedure and get to login_successful.php, I get this error "Notice: Undefined variable: _SESSION in C:\wamp\www\login_successful.php on line 15" even though I clearly started a session in login.php.

Why is it doing this?

答: You need to call session_start() at the top of each of your scripts

Body:
I have 3 pages in my set up here:

login.php: The login page that contains the username and password fields which submits to

checklogin.php: Which checks to see if the credentials are right which redirects to

login_successful.php: Which displays the user's name

login.php starts with

<?php session_start(); ?>

    <?php
        include 'content.php';
        echo $head;
    ?>

Which should initialize a global $_SESSION variable right?

checklogin.php has some code which looks like this:

if (mysql_num_rows($result) < 1)
{
    /* Access denied */
    echo 'Sorry, your username or password was incorrect!';
}
else
{
    $_SESSION['username'] = $username;

    /* Log user in */
    header("location:login_successful.php");
}

login_successful.php looks like this:

Welcome back <?php echo $_SESSION['username']; ?>!

Unfortunately when I go through the login procedure and get to login_successful.php, I get this error "Notice: Undefined variable: _SESSION in C:\wamp\www\login_successful.php on line 15" even though I clearly started a session in login.php.

Why is it doing this?


问:
Draw circle with longitude, latitude and radius (km) in cartopy of python
```<code>#!/usr/bin/env python

import os, sys
import pandas as pd
import cartopy
import cartopy.crs as ccrs
import matplotlib.pyplot as plt
import shapely.geometry as sgeom
import numpy as np
from cartopy.geodesic import Geodesic

if __name__ == '__main__':

    stn = pd.read_csv('obs_station.csv')
    gd = Geodesic()

    lcc = ccrs.LambertConformal(central_longitude=126., central_latitude=38.)
    fig = plt.figure(figsize=(7,7))
    ax = fig.add_subplot(111, projection=lcc)
    ax.coastlines(resolution='50m')
    geoms = []
    for lon, lat in zip(stn['longitude'], stn['latitude']):
        cp = gd.circle(lon=lon, lat=lat, radius=250000.)
        geoms.append(sgeom.Polygon(cp))
    ax.add_geometries(geoms, crs=lcc, edgecolor='r')
    ax.set_extent([120., 133., 30., 43.])
    plt.show()
</code>```

The file 'obs_station.csv' contain several coordinates of longitudes and latitudes.

Using code above, I try to draw circles with specific radius (250 km).
But, nothing is on the map as below. Only show the map with coastlines.

I don't know what is the problem. Help please.

Result:

答:
You did not get the plots of the circles because of wrong coordinate transformation you specifies in .add_geometries() statement.

To get it right, suppose I use this data file:
'obs_station.csv':

```<code>longitude,latitude
127.603897,36.932988
126.505337,38.555939
</code>```

And the modified code:-

```<code>#import os, sys
import pandas as pd
import cartopy
import cartopy.crs as ccrs
import matplotlib.pyplot as plt
import shapely.geometry as sgeom
import numpy as np
from cartopy.geodesic import Geodesic

if __name__ == '__main__':

    stn = pd.read_csv('obs_station.csv')
    gd = Geodesic()

    # This is long-lat coordinate system for use in ..
    # .. coordinate transformation options
    src_crs = ccrs.PlateCarree()

    lcc = ccrs.LambertConformal(central_longitude=126., central_latitude=38.)
    fig = plt.figure(figsize=(7,7))
    ax = fig.add_subplot(111, projection=lcc)
    ax.coastlines(resolution='50m')
    geoms = []
    for lon, lat in zip(stn['longitude'], stn['latitude']):
        cp = gd.circle(lon=lon, lat=lat, radius=250000.)

        #x,y = lcc.transform_point(lon, lat, src_crs)
        #cp = gd.circle(lon=x, lat=y, radius=250000.)
        geoms.append(sgeom.Polygon(cp))

    # Note the specification of coordinate transformation, using the
    # .. correct parameter:  crs=src_crs
    ax.add_geometries(geoms, crs=src_crs, edgecolor='r', alpha=0.5)
    ax.set_extent([120., 133., 30., 43.])

    plt.show()
</code>```

The output:

In conclusion, your line of code:

```<code>ax.add_geometries(geoms, crs=lcc, edgecolor='r')
</code>```

needs correct CRS. And the correct CRS is

```<code>ccrs.PlateCarree()
</code>```

Edit

```
Some useful notes:
1. `from cartopy.geodesic import Geodesic` imports geodesic module from `geographiclib` for our uses. It is one of cartopy's dependencies.
2. The circles that are generated and plotted on any conformal projection (i.e. `LambertConformal`, `Mercator`, etc.) will appear as circles (NOT ellipses). And appear as ellipses in general on non-conformal projections.
3. Shapely geometry object is created from the the circle by `sgeom.Polygon(cp)`. It can be used to do geometric operations with predicates like `within, touches` etc.
4. The creation of point buffers from shapely's point objects is not correct. Create geodesic circles first, then convert it to shapely polygon.
5. Under the hood, geodesic circle is used to create/plot Tissot indicatrices.
```

Body:
#!/usr/bin/env python

import os, sys
import pandas as pd
import cartopy
import cartopy.crs as ccrs
import matplotlib.pyplot as plt
import shapely.geometry as sgeom
import numpy as np
from cartopy.geodesic import Geodesic

if __name__ == '__main__':

    stn = pd.read_csv('obs_station.csv')
    gd = Geodesic()

    lcc = ccrs.LambertConformal(central_longitude=126., central_latitude=38.)
    fig = plt.figure(figsize=(7,7))
    ax = fig.add_subplot(111, projection=lcc)
    ax.coastlines(resolution='50m')
    geoms = []
    for lon, lat in zip(stn['longitude'], stn['latitude']):
        cp = gd.circle(lon=lon, lat=lat, radius=250000.)
        geoms.append(sgeom.Polygon(cp))
    ax.add_geometries(geoms, crs=lcc, edgecolor='r')
    ax.set_extent([120., 133., 30., 43.])
    plt.show()

The file 'obs_station.csv' contain several coordinates of longitudes and latitudes.

Using code above, I try to draw circles with specific radius (250 km).
But, nothing is on the map as below. Only show the map with coastlines.

I don't know what is the problem. Help please.

Result:

Body:
You did not get the plots of the circles because of wrong coordinate transformation you specifies in .add_geometries() statement.

To get it right, suppose I use this data file:
'obs_station.csv':

longitude,latitude
127.603897,36.932988
126.505337,38.555939

And the modified code:-

#import os, sys
import pandas as pd
import cartopy
import cartopy.crs as ccrs
import matplotlib.pyplot as plt
import shapely.geometry as sgeom
import numpy as np
from cartopy.geodesic import Geodesic

if __name__ == '__main__':

    stn = pd.read_csv('obs_station.csv')
    gd = Geodesic()

    # This is long-lat coordinate system for use in ..
    # .. coordinate transformation options
    src_crs = ccrs.PlateCarree()

    lcc = ccrs.LambertConformal(central_longitude=126., central_latitude=38.)
    fig = plt.figure(figsize=(7,7))
    ax = fig.add_subplot(111, projection=lcc)
    ax.coastlines(resolution='50m')
    geoms = []
    for lon, lat in zip(stn['longitude'], stn['latitude']):
        cp = gd.circle(lon=lon, lat=lat, radius=250000.)

        #x,y = lcc.transform_point(lon, lat, src_crs)
        #cp = gd.circle(lon=x, lat=y, radius=250000.)
        geoms.append(sgeom.Polygon(cp))

    # Note the specification of coordinate transformation, using the
    # .. correct parameter:  crs=src_crs
    ax.add_geometries(geoms, crs=src_crs, edgecolor='r', alpha=0.5)
    ax.set_extent([120., 133., 30., 43.])

    plt.show()

The output:

In conclusion, your line of code:

ax.add_geometries(geoms, crs=lcc, edgecolor='r')

needs correct CRS. And the correct CRS is

ccrs.PlateCarree()

Edit

Some useful notes:
1. `from cartopy.geodesic import Geodesic` imports geodesic module from `geographiclib` for our uses. It is one of cartopy's dependencies.
2. The circles that are generated and plotted on any conformal projection (i.e. `LambertConformal`, `Mercator`, etc.) will appear as circles (NOT ellipses). And appear as ellipses in general on non-conformal projections.
3. Shapely geometry object is created from the the circle by `sgeom.Polygon(cp)`. It can be used to do geometric operations with predicates like `within, touches` etc.
4. The creation of point buffers from shapely's point objects is not correct. Create geodesic circles first, then convert it to shapely polygon.
5. Under the hood, geodesic circle is used to create/plot Tissot indicatrices.


问:
C# ToList inside LINQ
I'm working with LINQ and I wonder what's the difference between the two codes below. The result seems same but does using ToList() inside the query like student1 makes one more access to Database?

var students1 = (from stud in dbContext.Students.Where(s => s.LastName == "Doe").ToList()
               join class in dbContext.Classes
               on ...).ToList();

var students2 = (from stud in dbContext.Students.Where(s => s.LastName == "Doe")
               join class in dbContext.Classes
               on ...).ToList();
```

答: ToList materializes the query. Note that when accessing the database you are working with IQueryable and your join and where clauses get passed to the database. If you materialize the queryable by calling ToList the database does not process the join but you join the inmemory data with LinqToObjects instead of with LinqToSql.</p>

Title: C# ToList inside LINQ


问:
Android Emulator issues in new versions - The emulator process has terminated
After updating to Android Studio 2020.3.1 canary 15, when I try to run an emulator, it gets killed with this error:

The emulator process for AVD Pixel_4_API_30 has terminated.

It was working correctly in the previous version (4.1.3), but now after installing the new one, it shows the same error.

I've tried some solutions had suggested in almost similar cases; however, It still doesn't work.

I deleted my emulator (also I cleared inside of directory: /.android/avd/) and created a new one again

I updated the HAXM installer to version 7.6.5

I tried to run an emulator with lower APIs but...

Image of the error:

答: If emulator is terminating and it was properly running earlier and even if you have enough disk space. You can delete and create a new Virtual device which is almost same as "Wipe Data" action on existing Emulator. But if you do not want to wipe data and loose any kind of progress made on the Emulator, There is a "Cold Boot" option for you which helps. It actually solved the problem for me.</p>