问:
Excel/Google sheets - duplicating array and extending by value from different array
I have some problem with extending some array by values. The easiest way to explain will be show some example, so:

```<code>A       B       C
==================
A       11      A
B       22      B
C       33      C
                11
                A
                B
                C
                22
                A
                B
                C
                33
</code>```

Of course I can do sth like below:

```<code>=({A1:A3;B1;A1:A3;B2;A1:A3;B3})
</code>```

But it's not flexible at all.

The main problem is that I want to filter some table by value:

```<code>A       B       filter key
==================
A       11      11
B       11      33
B       33
B       33
C       33
F       44
G       55

</code>```

So I want to get all A column filtered by filter key, but I want also sum of results.
So in above example filtering by 11 is A,B by 33 is B, C.
Final result should be
ABBC

And yeah, this is possible to do like below:

```<code>=({UNIQUE(FILTER(A1:A10;B1:B10=C1));UNIQUE(FILTER(A1:A10;B1:B10=C2))})
</code>```

Do you have any idea?

Have a nice Sunday!

Update:

If someone will look for solution:

```<code>=FILTER(INDEX(UNIQUE(A:B);;1);REGEXMATCH(INDEX(UNIQUE(A:B);;2)&""; TEXTJOIN("|"; 1; ""&C:C)))
</code>```

Separated A and B columns (so it can be for instance columns A and Z or A from sheet_A, B from sheet_B):

```<code>=FILTER(INDEX(UNIQUE(UNIQUE({A:A\B:B}));;1);REGEXMATCH(INDEX(UNIQUE({A:A\B:B});;2)&""; TEXTJOIN("|"; 1; ""&C:C)))
</code>```

答:
```<code>=INDEX(FLATTEN(SPLIT(JOIN("×", TEXTJOIN("×", 1, A2:A)&"×"&FILTER(B2:B, B2:B<>"")), "×")))
</code>```

```<code>=FILTER(A2:A, REGEXMATCH(B2:B&"", TEXTJOIN("|", 1, C2:C&"")))
</code>```

update:

```<code>=FILTER(INDEX(UNIQUE(A:B);;1);
 REGEXMATCH(INDEX(UNIQUE(A:B);;2)&""; TEXTJOIN("|"; 1; ""&C:C)))
</code>```

Body:
I have some problem with extending some array by values. The easiest way to explain will be show some example, so:

A       B       C
==================
A       11      A
B       22      B
C       33      C
                11
                A
                B
                C
                22
                A
                B
                C
                33

Of course I can do sth like below:

=({A1:A3;B1;A1:A3;B2;A1:A3;B3})

But it's not flexible at all.

The main problem is that I want to filter some table by value:

A       B       filter key
==================
A       11      11
B       11      33
B       33
B       33
C       33
F       44
G       55

So I want to get all A column filtered by filter key, but I want also sum of results.
So in above example filtering by 11 is A,B by 33 is B, C.
Final result should be
ABBC

And yeah, this is possible to do like below:

=({UNIQUE(FILTER(A1:A10;B1:B10=C1));UNIQUE(FILTER(A1:A10;B1:B10=C2))})

Do you have any idea?

Have a nice Sunday!

Update:

If someone will look for solution:

=FILTER(INDEX(UNIQUE(A:B);;1);REGEXMATCH(INDEX(UNIQUE(A:B);;2)&""; TEXTJOIN("|"; 1; ""&C:C)))

Separated A and B columns (so it can be for instance columns A and Z or A from sheet_A, B from sheet_B):

=FILTER(INDEX(UNIQUE(UNIQUE({A:A\B:B}));;1);REGEXMATCH(INDEX(UNIQUE({A:A\B:B});;2)&""; TEXTJOIN("|"; 1; ""&C:C)))

Body:
=INDEX(FLATTEN(SPLIT(JOIN("×", TEXTJOIN("×", 1, A2:A)&"×"&FILTER(B2:B, B2:B<>"")), "×")))

=FILTER(A2:A, REGEXMATCH(B2:B&"", TEXTJOIN("|", 1, C2:C&"")))

update:

=FILTER(INDEX(UNIQUE(A:B);;1);
 REGEXMATCH(INDEX(UNIQUE(A:B);;2)&""; TEXTJOIN("|"; 1; ""&C:C)))


来源: stackexchange

问:
Retrieve a value of a specified line in a ListView
I have a ListView that is displaying data stored in a file, normally, we can also delete a line (data) from this ListView. The file's datas are stored within another class. i want to retreive value1(public) variable of a specified line in the ListView before deleting it(please see code). Can i specify value1 of arg2 line of the ListView ?

```<code>new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog,
int id) {
Carburant m= new Carburant(); //instanciate the class that contains the value1 variable
String value1= m.value1; //here i want to store value1 variable of arg2 line in the ListView
list.remove(arg2); //here all the line (data) will be deleted
</code>```

Thank you for helping.

答:
listeView.getItem(index);

You can get the index from onClick.

ContentLicense: CC BY-SA 3.0

Body:
I have a ListView that is displaying data stored in a file, normally, we can also delete a line (data) from this ListView. The file's datas are stored within another class. i want to retreive value1(public) variable of a specified line in the ListView before deleting it(please see code). Can i specify value1 of arg2 line of the ListView ?

new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog,
int id) {
Carburant m= new Carburant(); //instanciate the class that contains the value1 variable
String value1= m.value1; //here i want to store value1 variable of arg2 line in the ListView
list.remove(arg2); //here all the line (data) will be deleted

Thank you for helping.


问:
How do I split one-column data separated by spaces into multiple columns?
I need to split the column "leg1" into three columns (v1,v2,v3). The problem is that the amount of blank spaces is different by rows.

```<code>> head(data[,2:3])
    name                           leg1
513    1      0.00000  0.00000  0.00000
514    2   -0.00000  -0.00000  -0.00000
515    3      0.00000  0.00000  0.00000
516    4   -0.03467  -0.03848  -0.02331
517    5   -0.00000  -0.00000  -0.00000
518    6   -0.00000  -0.00000  -0.00000
</code>```

I tried to use gsub or substr, but I couldn`t do it.

Could anyone help me, please?

Thanks in advance!!

答:
It may be easier to do this with read.table from base R on the 'leg1' column which will split by the default space

```<code>cbind(data[-2], read.table(text = data$leg1, header = FALSE))
</code>```

-output

```<code>  name       V1       V2       V3
1    1  0.00000  0.00000  0.00000
2    2  0.00000  0.00000  0.00000
3    3  0.00000  0.00000  0.00000
4    4 -0.03467 -0.03848 -0.02331
5    5  0.00000  0.00000  0.00000
</code>```

if there are more spaces, then specify strip.white = TRUE

```<code>cbind(data[-2], read.table(text = data$leg1, header = FALSE, strip.white = TRUE))
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I need to split the column "leg1" into three columns (v1,v2,v3). The problem is that the amount of blank spaces is different by rows.

> head(data[,2:3])
    name                           leg1
513    1      0.00000  0.00000  0.00000
514    2   -0.00000  -0.00000  -0.00000
515    3      0.00000  0.00000  0.00000
516    4   -0.03467  -0.03848  -0.02331
517    5   -0.00000  -0.00000  -0.00000
518    6   -0.00000  -0.00000  -0.00000

I tried to use gsub or substr, but I couldn`t do it.

Could anyone help me, please?

Thanks in advance!!

Body:
It may be easier to do this with read.table from base R on the 'leg1' column which will split by the default space

cbind(data[-2], read.table(text = data$leg1, header = FALSE))

-output

  name       V1       V2       V3
1    1  0.00000  0.00000  0.00000
2    2  0.00000  0.00000  0.00000
3    3  0.00000  0.00000  0.00000
4    4 -0.03467 -0.03848 -0.02331
5    5  0.00000  0.00000  0.00000

if there are more spaces, then specify strip.white = TRUE

cbind(data[-2], read.table(text = data$leg1, header = FALSE, strip.white = TRUE))


问:
How do I set the selected item in a comboBox to match my string using C#?
I have a string "test1" and my comboBox contains test1, test2, and test3. How do I set the selected item to "test1"? That is, how do I match my string to one of the comboBox items?

I was thinking of the line below, but this doesn't work.

```<code>comboBox1.SelectedText = "test1";
</code>```

答:
if you are binding Datasource via Dataset, then you should use "SelectedValue"</p>
```<code>cmbCategoryList.SelectedValue = (int)dsLookUp.Tables[0].Select("WHERE PRODUCTCATEGORYID = 1")[0]["ID"];
</code>```

OwnerDisplayName: May D

LastEditorDisplayName: Binary Worrier

Body:
I have a string "test1" and my comboBox contains test1, test2, and test3. How do I set the selected item to "test1"? That is, how do I match my string to one of the comboBox items?

I was thinking of the line below, but this doesn't work.

comboBox1.SelectedText = "test1";

Body:
if you are binding Datasource via Dataset, then you should use "SelectedValue"

cmbCategoryList.SelectedValue = (int)dsLookUp.Tables[0].Select("WHERE PRODUCTCATEGORYID = 1")[0]["ID"];


问:
Scrape Multiple Websites and Send Text Message if Conditions are met
I have two different snippets of code that scrape from two different websites. Code is a modified version from an answer from a user on SO. I would like to consolidate it to run both URLs in one code so I do not have to have two command prompts open. Not trying to create a retail bot, just status checks. I am not proficient at Python, so my question is how do I complete this code to have this workflow?

Scrape two different URLs at a set interval and have it running around the clock without terminating.

Check if the stock status has changed from out of stock to in stock and if conditions are met....

Sends a text message (not email) to me confirming it is in stock.

```<code>import re
import time
import smtplib
import requests
from datetime import datetime
from bs4 import BeautifulSoup

def stock_check(url):
    """Checks url for 'Out of stock' substring in stock out-of- stock"""
    soup = BeautifulSoup(url.content, "html.parser") #Need to use lxml parser
    stock = soup.find("p", "stock out-of-stock") #Check the html tags for sold out/coming soon info.
    stock_status = re.findall(r"Out of stock", str(stock)) #Returns list of captured substring if exists.
    return stock_status # returns "sold out!" from soup string.

def send_email(address, password, message):
    """Send an e-mail to yourself!"""
    server = smtplib.SMTP("smtp.gmail.com", 587) #e-mail server
    server.ehlo()
    server.starttls()
    server.login(address,password) #login
    message = str('K8-B is in stock at Kulp Lights') #message to email yourself
    server.sendmail(address,address,message) #send the email through dedicated server
    return

def stock_check_listener(url, address, password, run_hours):
    """Periodically checks stock information."""
    listen = True # listen boolean
    start = datetime.now() # start time
    while(listen): #while listen = True, run loop
        if "Out of stock" in stock_check(url): #check page
            now = datetime.now()
            print(str(now) + ": Not in stock at Kulp Lights.")
        else:
            now = datetime.now()
            message = str(now) + ": NOW IN STOCK at Kulp Lights!"
            print(message)
            send_email(address, password, message)
            listen = False

        duration = (now - start)
        seconds = duration.total_seconds()
        hours = int(seconds/3600)
        if hours >= run_hours: #check run time
            print("Finished.")
            listen = False

        time.sleep(60*60) #Wait N minutes to check again.
    return

    if __name__=="__main__":

    #Set url and userAgent header for javascript issues.
    page = "https://kulplights.com/product/k8-b/"

    headers = {'User-Agent': 'Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/46.0.2490.80 Safari/537.36',
'Content-Type': 'text/html'}

    #URL request.
    url = requests.get(url=page,
                   headers=headers)

    #Run listener to stream stock checks.
    address = "me@address.com" #your email
    password = "mypassword" #your email password
    stock_check_listener(url=url,
                         address=address,
                         password=password,
                         run_hours=24)
</code>```

答:
Scrape two different URLs

Unless both urls have the same html structure, you'd want to write a function for each

at a set interval and have it running around the clock without terminating.

Use  your OS for this; cron or Windows Scheduler, not a sleeping loop from Python. You can use a loop for capturing temporary errors like page timeouts, but otherwise you will want the script to terminate on each scheduled interval. Otherwise, your computer will accumulate a backlog of processes and eventually run out of memory.

run both URLs in one code

After you implement two functions, then call them both. Or call your current one with different urls

Check if the stock status has changed from out of stock to in stock

You'll need to know what html structure each site has when this things are in/out of stock

I'd suggest returning true/false, or a number of items in stock (if the amount is available), rather than only a string.

Sends a text message (not email)

You'll need a different library than smtp, then. There's no builtin module in python for sending sms. Telegram, Slack, or Discord might be better alternative if you don't want to pay for an SMS provider

Body:
I have two different snippets of code that scrape from two different websites. Code is a modified version from an answer from a user on SO. I would like to consolidate it to run both URLs in one code so I do not have to have two command prompts open. Not trying to create a retail bot, just status checks. I am not proficient at Python, so my question is how do I complete this code to have this workflow?

Scrape two different URLs at a set interval and have it running around the clock without terminating.

Check if the stock status has changed from out of stock to in stock and if conditions are met....

Sends a text message (not email) to me confirming it is in stock.

import re
import time
import smtplib
import requests
from datetime import datetime
from bs4 import BeautifulSoup

def stock_check(url):
    """Checks url for 'Out of stock' substring in stock out-of- stock"""
    soup = BeautifulSoup(url.content, "html.parser") #Need to use lxml parser
    stock = soup.find("p", "stock out-of-stock") #Check the html tags for sold out/coming soon info.
    stock_status = re.findall(r"Out of stock", str(stock)) #Returns list of captured substring if exists.
    return stock_status # returns "sold out!" from soup string.

def send_email(address, password, message):
    """Send an e-mail to yourself!"""
    server = smtplib.SMTP("smtp.gmail.com", 587) #e-mail server
    server.ehlo()
    server.starttls()
    server.login(address,password) #login
    message = str('K8-B is in stock at Kulp Lights') #message to email yourself
    server.sendmail(address,address,message) #send the email through dedicated server
    return

def stock_check_listener(url, address, password, run_hours):
    """Periodically checks stock information."""
    listen = True # listen boolean
    start = datetime.now() # start time
    while(listen): #while listen = True, run loop
        if "Out of stock" in stock_check(url): #check page
            now = datetime.now()
            print(str(now) + ": Not in stock at Kulp Lights.")
        else:
            now = datetime.now()
            message = str(now) + ": NOW IN STOCK at Kulp Lights!"
            print(message)
            send_email(address, password, message)
            listen = False

        duration = (now - start)
        seconds = duration.total_seconds()
        hours = int(seconds/3600)
        if hours >= run_hours: #check run time
            print("Finished.")
            listen = False

        time.sleep(60*60) #Wait N minutes to check again.
    return

    if __name__=="__main__":

    #Set url and userAgent header for javascript issues.
    page = "https://kulplights.com/product/k8-b/"

    headers = {'User-Agent': 'Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/46.0.2490.80 Safari/537.36',
'Content-Type': 'text/html'}

    #URL request.
    url = requests.get(url=page,
                   headers=headers)

    #Run listener to stream stock checks.
    address = "me@address.com" #your email
    password = "mypassword" #your email password
    stock_check_listener(url=url,
                         address=address,
                         password=password,
                         run_hours=24)


问:
Extract data from YouTube Data API with Java / Sprint Boot
I am trying to extract title, videoId, and description data of all the videos I got from using YT Data API. I was able to return the data in what looks like JSON format (but it is actually LinkedHashMap when I check with getClass()) in Postman and Chrome browser, but was unable to extract the value from specific keys I have mentioned above.

I tried:

System.out.println((rest.getForObject(url, Object.class, params)).get("items"));
It asks me to cast to JSONObject

Overall, I need to extract the data and convert into xml before sending it over to ActiveMQ

Edit:
Format I get in Postman/Chrome browser

```<code>{
  "kind": "youtube#searchListResponse",
  "etag": "3LV4enCWAzOaiqJb_cMIUVklXJY",
  "nextPageToken": "CAUQAA",
  "regionCode": "CA",
  "pageInfo": {
    "totalResults": 478712,
    "resultsPerPage": 5
  },
  "items": [
    {
      "kind": "youtube#searchResult",
      "etag": "gt6x7J2XpzU8Mpb3yv9_HmNTzWY",
      "id": {
        "kind": "youtube#video",
        "videoId": "I_ZK0t9-llo"
      },
      "snippet": {
        "publishedAt": "2021-03-01T18:15:13Z",
        "channelId": "UC2WHjPDvbE6O328n17ZGcfg",
        "title": "Stack Overflow is full of idiots.",
        "description": "The Stack Overflow culture needs to be fixed. The overall gatekeeping & elitism in computer science & programming - as a whole ...",
        "thumbnails": {
          "default": {
            "url": "https://i.ytimg.com/vi/I_ZK0t9-llo/default.jpg",
            "width": 120,
            "height": 90
          },
          "medium": {
            "url": "https://i.ytimg.com/vi/I_ZK0t9-llo/mqdefault.jpg",
            "width": 320,
            "height": 180
          },
          "high": {
            "url": "https://i.ytimg.com/vi/I_ZK0t9-llo/hqdefault.jpg",
            "width": 480,
            "height": 360
          }
        },
        "channelTitle": "ForrestKnight",
        "liveBroadcastContent": "none",
        "publishTime": "2021-03-01T18:15:13Z"
      }
    },
    {
      "kind": "youtube#searchResult",
      "etag": "RwmGP1qMzUCzK6oV82s0NUEOETw",
      "id": {
        "kind": "youtube#video",
        "videoId": "sMIslcynm0Q"
      },
      "snippet": {
        "publishedAt": "2021-03-07T16:00:13Z",
        "channelId": "UCXwjZTvpFiBl93ACCUh1NXQ",
        "title": "How To Use Stack Overflow (no, ForrestKnight, it's not full of idiots)",
        "description": "Hey everyone, I can't believe I have to make this video. Unfortunately ForrestKnight recently made a video saying Stack Overflow ...",
        "thumbnails": {
        ...

</code>```

Edit2: I tried

```<code>JSONObject jsonObject = new JSONObject( rest.getForObject(url, Object.class, params));

        JSONArray array = jsonObject.getJSONArray("items" );
        for(int i=0;i<array.length();i++){
            JSONObject snippet =array.getJSONObject(i);
            System.out.println(snippet.getJSONObject("snippet").get("title"));
        }

</code>```

JSONObject["items"] not found.

Edit3:
I also tried without Edit2 and just

```<code>JSONObject jsonObject = new JSONObject( rest.getForObject(url, Object.class, params));
System.out.println(jsonObject);
</code>```

No error and I was about to fetch data shown in Postman. But in console printed {}, meaning I might not have gotten the data and won't be able to extract.

I tried extracting using .get System.out.println(jsonObject.get("items"));
and I got the same error JSONObject["items"] not found.

Seems like it could be a format error, again it looks like json already and to use .get, I placed it inside jsonObject but found nothing

Edit4: I can confirm the data I get back is Json (like it says on the doc) using

```<code>try {
    new JSONObject(rest.getForObject(url, Object.class, params));
} catch (JSONException ex) {
    // edited, to include @Arthur's comment
    // e.g. in case JSONArray is valid as well...
    try {
        new JSONArray(rest.getForObject(url, Object.class, params));
    } catch (JSONException ex1) {
        return false;
    }
}
return true;
</code>```

Returned true

Edit5: Seems like the keys is null after trying

```<code>String[] keys = JSONObject.getNames(jsonObject);

// iterate over them
for (String key1 : keys) {
    // retrieve the values
    Object value = jsonObject.get(key1);
    // if you just have strings:
    String value1 = (String) jsonObject.get(key1);
    System.out.println(value);
    System.out.println(value1);
}
</code>```

Cannot read the array length because "keys" is null

答:
The RestTemplate delegates to the underlying Jackson to deserialize the JSON string to a java object .If you get the HTTP response as a generic object type , it will deserialize it into a Map.

You can simply create a POJO with the structure that is the same as the expected JSON response, and then use the Jackson annotations to configure how to deserialize the JSON into this POJO , and get the  HTTP response as this POJO class.

Something like :

public class Result {

  @JsonProperty("items")
  private List<Item> items = new ArrayList<>();

}

public class Item {
    @JsonProperty("kind")
    private String kind;

    @JsonProperty("etag")
    private String etag;

    @JsonProperty("snippet")
    private List<Snippet> snippets = new ArrayList<>();

}

public class Snippet {

  @JsonProperty("channelId")
  private String channelId;

  @JsonProperty("title")
  private String title;

}
```
<p>Then use the following to get the response :</p>
```Result result = rest.getForObject(url, Result.class, params);
```

Once you get the Result POJO , use the favourite library to serialize it into XML.

 P.S I just show you the ideas. You have to fine tune the POJO structure

Body:
I am trying to extract title, videoId, and description data of all the videos I got from using YT Data API. I was able to return the data in what looks like JSON format (but it is actually LinkedHashMap when I check with getClass()) in Postman and Chrome browser, but was unable to extract the value from specific keys I have mentioned above.

I tried:

System.out.println((rest.getForObject(url, Object.class, params)).get("items"));
It asks me to cast to JSONObject

Overall, I need to extract the data and convert into xml before sending it over to ActiveMQ

Edit:
Format I get in Postman/Chrome browser

{
  "kind": "youtube#searchListResponse",
  "etag": "3LV4enCWAzOaiqJb_cMIUVklXJY",
  "nextPageToken": "CAUQAA",
  "regionCode": "CA",
  "pageInfo": {
    "totalResults": 478712,
    "resultsPerPage": 5
  },
  "items": [
    {
      "kind": "youtube#searchResult",
      "etag": "gt6x7J2XpzU8Mpb3yv9_HmNTzWY",
      "id": {
        "kind": "youtube#video",
        "videoId": "I_ZK0t9-llo"
      },
      "snippet": {
        "publishedAt": "2021-03-01T18:15:13Z",
        "channelId": "UC2WHjPDvbE6O328n17ZGcfg",
        "title": "Stack Overflow is full of idiots.",
        "description": "The Stack Overflow culture needs to be fixed. The overall gatekeeping & elitism in computer science & programming - as a whole ...",
        "thumbnails": {
          "default": {
            "url": "https://i.ytimg.com/vi/I_ZK0t9-llo/default.jpg",
            "width": 120,
            "height": 90
          },
          "medium": {
            "url": "https://i.ytimg.com/vi/I_ZK0t9-llo/mqdefault.jpg",
            "width": 320,
            "height": 180
          },
          "high": {
            "url": "https://i.ytimg.com/vi/I_ZK0t9-llo/hqdefault.jpg",
            "width": 480,
            "height": 360
          }
        },
        "channelTitle": "ForrestKnight",
        "liveBroadcastContent": "none",
        "publishTime": "2021-03-01T18:15:13Z"
      }
    },
    {
      "kind": "youtube#searchResult",
      "etag": "RwmGP1qMzUCzK6oV82s0NUEOETw",
      "id": {
        "kind": "youtube#video",
        "videoId": "sMIslcynm0Q"
      },
      "snippet": {
        "publishedAt": "2021-03-07T16:00:13Z",
        "channelId": "UCXwjZTvpFiBl93ACCUh1NXQ",
        "title": "How To Use Stack Overflow (no, ForrestKnight, it's not full of idiots)",
        "description": "Hey everyone, I can't believe I have to make this video. Unfortunately ForrestKnight recently made a video saying Stack Overflow ...",
        "thumbnails": {
        ...

Edit2: I tried

JSONObject jsonObject = new JSONObject( rest.getForObject(url, Object.class, params));

        JSONArray array = jsonObject.getJSONArray("items" );
        for(int i=0;i<array.length();i++){
            JSONObject snippet =array.getJSONObject(i);
            System.out.println(snippet.getJSONObject("snippet").get("title"));
        }

JSONObject["items"] not found.

Edit3:
I also tried without Edit2 and just

JSONObject jsonObject = new JSONObject( rest.getForObject(url, Object.class, params));
System.out.println(jsonObject);

No error and I was about to fetch data shown in Postman. But in console printed {}, meaning I might not have gotten the data and won't be able to extract.

I tried extracting using .get System.out.println(jsonObject.get("items"));
and I got the same error JSONObject["items"] not found.

Seems like it could be a format error, again it looks like json already and to use .get, I placed it inside jsonObject but found nothing

Edit4: I can confirm the data I get back is Json (like it says on the doc) using

try {
    new JSONObject(rest.getForObject(url, Object.class, params));
} catch (JSONException ex) {
    // edited, to include @Arthur's comment
    // e.g. in case JSONArray is valid as well...
    try {
        new JSONArray(rest.getForObject(url, Object.class, params));
    } catch (JSONException ex1) {
        return false;
    }
}
return true;

Returned true

Edit5: Seems like the keys is null after trying

String[] keys = JSONObject.getNames(jsonObject);

// iterate over them
for (String key1 : keys) {
    // retrieve the values
    Object value = jsonObject.get(key1);
    // if you just have strings:
    String value1 = (String) jsonObject.get(key1);
    System.out.println(value);
    System.out.println(value1);
}

Cannot read the array length because "keys" is null

Body:
The RestTemplate delegates to the underlying Jackson to deserialize the JSON string to a java object .If you get the HTTP response as a generic object type , it will deserialize it into a Map.

You can simply create a POJO with the structure that is the same as the expected JSON response, and then use the Jackson annotations to configure how to deserialize the JSON into this POJO , and get the  HTTP response as this POJO class.

Something like :

public class Result {

  @JsonProperty("items")
  private List<Item> items = new ArrayList<>();

}

public class Item {
    @JsonProperty("kind")
    private String kind;

    @JsonProperty("etag")
    private String etag;

    @JsonProperty("snippet")
    private List<Snippet> snippets = new ArrayList<>();

}

public class Snippet {

  @JsonProperty("channelId")
  private String channelId;

  @JsonProperty("title")
  private String title;

}

Then use the following to get the response :

Result result = rest.getForObject(url, Result.class, params);

Once you get the Result POJO , use the favourite library to serialize it into XML.

 P.S I just show you the ideas. You have to fine tune the POJO structure


问:
R adding a new column in a data frame by recursivly filling 1:3 value based on another column
I have a dataframe, e.g.:

```<code>df <- data.frame(Group = rep(c("A", "B", "C"),  times = c(4, 4, 6))
> df
   Group
1      A
2      A
3      B
4      B
5      B
6      B
7      C
8      C
9      C
10     C
11     C
12     C
</code>```

I want to add a new column Type by recursively filling value 1:3 based on the Group column.

The resulting DF is like

```<code>> df2
   Group Type
1      A    1
2      A    2
3      B    1
4      B    2
5      B    3
6      B    1
7      C    1
8      C    2
9      C    3
10     C    1
11     C    2
12     C    3
</code>```

I don't know how to achieve this. Thanks a lot for your help

答:
You could just create a sequence of values 1:3 that repeats lots of times and then subset that within each group (updated based on suggestion in comments:

library(dplyr)
#>
#> Attaching package: 'dplyr'
#> The following objects are masked from 'package:stats':
#>
#>     filter, lag
#> The following objects are masked from 'package:base':
#>
#>     intersect, setdiff, setequal, union
  df <- data.frame(Group = rep(c("A", "B", "C"),
                               times = c(4, 4, 6)))
  df <- df %>%
    group_by(Group) %>%
    mutate(Type = rep(1:3, length=n()))
  df
#> # A tibble: 14 × 2
#> # Groups:   Group [3]
#>    Group  Type
#>    <chr> <int>
#>  1 A         1
#>  2 A         2
#>  3 A         3
#>  4 A         1
#>  5 B         1
#>  6 B         2
#>  7 B         3
#>  8 B         1
#>  9 C         1
#> 10 C         2
#> 11 C         3
#> 12 C         1
#> 13 C         2
#> 14 C         3
```

Created on 2022-02-13 by the reprex package (v2.0.1)

Body:
I have a dataframe, e.g.:

df <- data.frame(Group = rep(c("A", "B", "C"),  times = c(4, 4, 6))
> df
   Group
1      A
2      A
3      B
4      B
5      B
6      B
7      C
8      C
9      C
10     C
11     C
12     C

I want to add a new column Type by recursively filling value 1:3 based on the Group column.

The resulting DF is like

> df2
   Group Type
1      A    1
2      A    2
3      B    1
4      B    2
5      B    3
6      B    1
7      C    1
8      C    2
9      C    3
10     C    1
11     C    2
12     C    3

I don't know how to achieve this. Thanks a lot for your help

Body:
You could just create a sequence of values 1:3 that repeats lots of times and then subset that within each group (updated based on suggestion in comments:

library(dplyr)
#>
#> Attaching package: 'dplyr'
#> The following objects are masked from 'package:stats':
#>
#>     filter, lag
#> The following objects are masked from 'package:base':
#>
#>     intersect, setdiff, setequal, union
  df <- data.frame(Group = rep(c("A", "B", "C"),
                               times = c(4, 4, 6)))
  df <- df %>%
    group_by(Group) %>%
    mutate(Type = rep(1:3, length=n()))
  df
#> # A tibble: 14 × 2
#> # Groups:   Group [3]
#>    Group  Type
#>    <chr> <int>
#>  1 A         1
#>  2 A         2
#>  3 A         3
#>  4 A         1
#>  5 B         1
#>  6 B         2
#>  7 B         3
#>  8 B         1
#>  9 C         1
#> 10 C         2
#> 11 C         3
#> 12 C         1
#> 13 C         2
#> 14 C         3

Created on 2022-02-13 by the reprex package (v2.0.1)


问:
How to Resolve Undefined Array Key Warning?
I am trying to submit a form with two conditions regulated by a checkbox. If the second condition is true, I get a warning message--Undefined array key "outside" in C:\xampp\htdocs\Taxi. I tried the following code:</p>
```<code>if (isset($_POST['assign'])){
    $tid=addslashes($_POST['tid']);
    require 'dbconnect.php';
    if(addslashes($_POST['outside']))
    {
        $outside=addslashes($_POST['outside']);
        $outinv=addslashes($_POST['inv']);
        $sql = "UPDATE trips SET inventory='$outside',cardetails='$inv' WHERE id='$tid'";
        $stmt = $con->prepare($sql);
        $stmt->execute();
    }
    else if(!addslashes($_POST['outside'])){
        $asn=addslashes($_POST['asn']);
        echo $asn;
    }
}
</code>```

答:
Maybe you want this.</p>
```<code>if (isset($_POST['assign'])){

$tid=addslashes($_POST['tid']);

 require 'dbconnect.php';

if(isset($_POST['outside']))
{
$outside=addslashes($_POST['outside']);
 $outinv=addslashes($_POST['inv']);

 $sql = "UPDATE trips SET inventory='$outside',cardetails='$inv' WHERE id='$tid'";
$stmt = $con->prepare($sql); $stmt->execute();

 }
else {
$asn=addslashes($_POST['asn']);
echo $asn;

}
}
</code>```

Body:
I am trying to submit a form with two conditions regulated by a checkbox. If the second condition is true, I get a warning message--Undefined array key "outside" in C:\xampp\htdocs\Taxi. I tried the following code:

if (isset($_POST['assign'])){
    $tid=addslashes($_POST['tid']);
    require 'dbconnect.php';
    if(addslashes($_POST['outside']))
    {
        $outside=addslashes($_POST['outside']);
        $outinv=addslashes($_POST['inv']);
        $sql = "UPDATE trips SET inventory='$outside',cardetails='$inv' WHERE id='$tid'";
        $stmt = $con->prepare($sql);
        $stmt->execute();
    }
    else if(!addslashes($_POST['outside'])){
        $asn=addslashes($_POST['asn']);
        echo $asn;
    }
}

Body:
Maybe you want this.

if (isset($_POST['assign'])){

$tid=addslashes($_POST['tid']);

 require 'dbconnect.php';

if(isset($_POST['outside']))
{
$outside=addslashes($_POST['outside']);
 $outinv=addslashes($_POST['inv']);

 $sql = "UPDATE trips SET inventory='$outside',cardetails='$inv' WHERE id='$tid'";
$stmt = $con->prepare($sql); $stmt->execute();

 }
else {
$asn=addslashes($_POST['asn']);
echo $asn;

}
}


问:
Is it required to define doNothing()/when() on Objects mocked using Mockito
I am writing unit tests using JUnit5 and Mockito for a class Main.java.

The dependency class ExternalApi.java is injected in Main.java.

Here is my MainTest.java:

```<code>@ExtendWith(MockitoExtension.class)
public class MainTest {
    @InjectMocks
    Main main;

    @Mock
    ExternalApi externalApi;

    @Test
    void testAbcMethod() {

    }
}
</code>```

The abc() method in Main.java calls externalApi.doSomething() which does some stuff.

I don't want this original externalApi method to be called in my test. Do I need to define

```<code>doNothing().when(externalApi).when(doSomething());
</code>```

or is it just enough to mock ExternalApi?

What happens when we don't define what happens when we call a mocked object's methods?

答:
What happens when we don't define what happens when we call a mocked object's methods?

Nothing happens. Mocking is enough since it's not the real class/method that is called but the mocked one.

If you had spied on the instance, that would have triggered the real method call. Only then, you'd have thought of using doNothing to silence the method behavior.

@Test
public void whenNotDefineBehaviorOnMock_thenCorrect() {
    List mockList = Mockito.mock(ArrayList.class);

   // No behavior defined,
    mockList.add("one");
    Mockito.verify(mockList).add("one");
   // Size is still empty
    assertEquals(0, mockList.size());

   // Behavior defined
    Mockito.when(mockList.size()).thenReturn(100);
    assertEquals(100, mockList.size());
}

```

Body:
I am writing unit tests using JUnit5 and Mockito for a class Main.java.

The dependency class ExternalApi.java is injected in Main.java.

Here is my MainTest.java:

@ExtendWith(MockitoExtension.class)
public class MainTest {
    @InjectMocks
    Main main;

    @Mock
    ExternalApi externalApi;

    @Test
    void testAbcMethod() {

    }
}

The abc() method in Main.java calls externalApi.doSomething() which does some stuff.

I don't want this original externalApi method to be called in my test. Do I need to define

doNothing().when(externalApi).when(doSomething());

or is it just enough to mock ExternalApi?

What happens when we don't define what happens when we call a mocked object's methods?


问:
How to get validation errors in an array?
I am developing an REST API using Codeigniter.
I need to have all error messages from Form validation in array format so that
I can easily respond in either JSON or XML.

Right now Codeigniter is delivering error messages with
 as delimiters (see below)
but that is not good for a REST based API.

```<code><p>There was an error with this item</p>
</code>```

How can I get errors in an array?

Thankful for all input!

答:
The form validation library stores errors in an array and loops through them to generate the error string.  They are stored in a private variable called $_error_array.  You could extend the library with a simple method that returns the error array.

```<code>class MY_Form_validation extends CI_Form_validation
{
    function get_error_array()
    {
        return $this->_error_array;
    }
}
</code>```

I assume you are familiar with extending core CI libraries, but this extension of the form validation library will give you a method to return the errors as an array with the name attribute's value as the key and the message as the value.  I tested it out on one of my projects and it worked fine.

Body:
I am developing an REST API using Codeigniter.
I need to have all error messages from Form validation in array format so that
I can easily respond in either JSON or XML.

Right now Codeigniter is delivering error messages with
 as delimiters (see below)
but that is not good for a REST based API.

There was an error with this item

How can I get errors in an array?

Thankful for all input!

Body:
The form validation library stores errors in an array and loops through them to generate the error string.  They are stored in a private variable called $_error_array.  You could extend the library with a simple method that returns the error array.

class MY_Form_validation extends CI_Form_validation
{
    function get_error_array()
    {
        return $this->_error_array;
    }
}

I assume you are familiar with extending core CI libraries, but this extension of the form validation library will give you a method to return the errors as an array with the name attribute's value as the key and the message as the value.  I tested it out on one of my projects and it worked fine.


问:
How can I autopopulate selection list in javascript?
I would like to auto populate my HTML table with drop down list.

I used below code, but the problem is, I need to specify 24 option to this drop down list, and if I would like add all 24, this line will be extremly long.

Can I ask if there is any way to solve it a bit shorter code and better way?

List:

AC Propulsion

Ajax

AM General

Ambassador

AMC

American

American Underslung

Anteros Coachworks

Apollo

Apperson

Arnolt

Auburn

Aurica Motors

Avanti

Brewster

Brisco

Brush

BXR

Carroll Shelby

Case

Chadwick

Chandler

Checker

Comet

```<code>row2.insertCell(count + 1).innerHTML = '<select id="' + count2 + '"' + 'name="cars"><option value="volvo">Volvo</option><option value="saab">Saab</option></select>'
</code>```

答:
You can add your values to an object and then form a string from them in a loop. This method allows you to set different key and value</p>
```<code>var obj = {'volvo':'Volvo', 'saab':'Saab','audi':'Audi'};
var opt = '';
for (var key in obj) {
  opt += '<option value="' + key + '">' +obj[key]+ '</option>';
}
row2.insertCell(count + 1).innerHTML = '<select id="' + count2 + '"' +
'name="cars">'+opt+'</select>'
</code>```

Body:
I would like to auto populate my HTML table with drop down list.

I used below code, but the problem is, I need to specify 24 option to this drop down list, and if I would like add all 24, this line will be extremly long.

Can I ask if there is any way to solve it a bit shorter code and better way?

List:

AC Propulsion

Ajax

AM General

Ambassador

AMC

American

American Underslung

Anteros Coachworks

Apollo

Apperson

Arnolt

Auburn

Aurica Motors

Avanti

Brewster

Brisco

Brush

BXR

Carroll Shelby

Case

Chadwick

Chandler

Checker

Comet

row2.insertCell(count + 1).innerHTML = '<select id="' + count2 + '"' + 'name="cars"><option value="volvo">Volvo</option><option value="saab">Saab</option></select>'

Body:
You can add your values to an object and then form a string from them in a loop. This method allows you to set different key and value

var obj = {'volvo':'Volvo', 'saab':'Saab','audi':'Audi'};
var opt = '';
for (var key in obj) {
  opt += '<option value="' + key + '">' +obj[key]+ '</option>';
}
row2.insertCell(count + 1).innerHTML = '<select id="' + count2 + '"' +
'name="cars">'+opt+'</select>'


问:
Using tailscale is it secure to log into a server/nas via browser and http?
I would like to use tailscale to access my nas browser interface from anywhere. I read here that tailscale encrypts all traffic fully at the IP level, before it leaves the device.

Does this mean I can securely enter my login data, even though the nas browser interface has only a http connection (with a tailscale ip)?

答:
Tailscale encrypts all traffic at the IP layer. If you connect to the Tailscale IP address, the traffic is carried securely to that node.

If you want to additionally hook up HTTPS, there is support to help get certificates issued for your node: https://tailscale.com/blog/tls-certs/


问:
How do you add an amount of time (column 1) to a date/time (column 2) in a pandas data frame as a new column?
Here is what I tried so far, the context is that I have a set of scripts that run everyday. I can get a dump of the date and time it started and the duration, I need to calculate the end time for each line.

```<code>import pandas as pd

df = pd.read_csv("script.csv")
df['EOD_DATE'] = pd.to_datetime(df['EOD_DATE'], format='%d %m %Y')
df['START_TIME'] = pd.to_datetime(df['START_TIME'], format='%Y-%m-%d %H:%M:%S', errors='ignore')
df.index = df['ROW_NUM']
df['SCRIPT_DURATION'] = pd.to_datetime(df['SCRIPT_DURATION'], format='%H:%M:%S', errors='ignore')
sum_column = pd.to_timedelta(df['SCRIPT_DURATION'], errors='ignore') + df['START_TIME']
df["END_TIME"] = sum_column
print(df.head())
</code>```
```<code>#TypeError: unsupported operand type(s) for +: 'Timedelta' and 'str'
</code>```

csv input extract

Body:
Here is what I tried so far, the context is that I have a set of scripts that run everyday. I can get a dump of the date and time it started and the duration, I need to calculate the end time for each line.

import pandas as pd

df = pd.read_csv("script.csv")
df['EOD_DATE'] = pd.to_datetime(df['EOD_DATE'], format='%d %m %Y')
df['START_TIME'] = pd.to_datetime(df['START_TIME'], format='%Y-%m-%d %H:%M:%S', errors='ignore')
df.index = df['ROW_NUM']
df['SCRIPT_DURATION'] = pd.to_datetime(df['SCRIPT_DURATION'], format='%H:%M:%S', errors='ignore')
sum_column = pd.to_timedelta(df['SCRIPT_DURATION'], errors='ignore') + df['START_TIME']
df["END_TIME"] = sum_column
print(df.head())

#TypeError: unsupported operand type(s) for +: 'Timedelta' and 'str'

csv input extract

Body:
Is it what you need?

df = pd.DataFrame({
    "START_TIME": ["2018-01-01 20:51:54", "2018-01-03 07:06:21", "2018-01-04 23:59:59"],
    "SCRIPT_DURATION": ["00:00:00", "00:07:17", "01:59:00"]
})

df["END_TIME"] = pd.to_datetime(df['START_TIME']) + pd.to_timedelta(df['SCRIPT_DURATION'])

df:

         START_TIME SCRIPT_DURATION            END_TIME
2018-01-01 20:51:54        00:00:00 2018-01-01 20:51:54
2018-01-03 07:06:21        00:07:17 2018-01-03 07:13:38
2018-01-04 23:59:59        01:59:00 2018-01-05 01:58:59


问:
List All Users That Have Retweeted A Tweet
I have recently put out a tweet on my twitter account, and it was quickly retweeted well over 100 times. Now the counter on the page of my tweet says 100+ retweets, but the actual number of retweets is much much higher.

Now I need to get a list with all Twitter user ids that have retweeted my tweet.

I get about 15 users on the actual page of the tweet, but the remaining users do not show up.

Is there a way for me to get the twitter user ids of all users that have retweeted my tweet?

答:
Maybe this method can help:
https://dev.twitter.com/docs/api/1/get/statuses/retweets_of_me Make sure to set count=100 and iterate through all pages But i am not sure if it will give you all your unique tweets or all instances of retweeting.

Sure way to find them all is by searching: https://dev.twitter.com/docs/api/1/get/search either look for your '@screen_name' or 'chunk of your tweet'


问:
D3 mouse interactivity issues, circles not appearing at data points
I'm implementing some D3 code in class format so that I have a reusable chart.

The errors are as follows:

GetElementsByClassName returns an HTMLCollection of length 0, but elements to be selected are classed correctly.

Circles appear at x0 and yMax, rather than at data positions (Issue is probably connected to the first).

Text is not appended to circle and not visible (This might work when the circles work).

I'm implementing this pretty much exactly as it looks, with the exception that I'm putting tooltips on 2/4 of the lines, and I'm using a class.

<!DOCTYPE html>

  <meta charset="UTF-8">

```

As you can see the mouse interactions are pretty janky so I hope someone can help.

答:
There are some differences between arrow function and regular function.
 Fixed some more errors:

<!DOCTYPE html>

  <meta charset="UTF-8">

```

Instead of listing all of them, I've created a diff file. Download and check. Left side is the original code.

Body:
I'm implementing some D3 code in class format so that I have a reusable chart.

The errors are as follows:

GetElementsByClassName returns an HTMLCollection of length 0, but elements to be selected are classed correctly.

Circles appear at x0 and yMax, rather than at data positions (Issue is probably connected to the first).

Text is not appended to circle and not visible (This might work when the circles work).

I'm implementing this pretty much exactly as it looks, with the exception that I'm putting tooltips on 2/4 of the lines, and I'm using a class.

<!DOCTYPE html>

  <meta charset="UTF-8">

As you can see the mouse interactions are pretty janky so I hope someone can help.

Body:
There are some differences between arrow function and regular function.
 Fixed some more errors:

<!DOCTYPE html>
<html>

<head>
  <meta charset="UTF-8">
  <script src="https://d3js.org/d3.v7.js"></script>
</head>

<body>
  <div id="graph"></div>

  <script>
    let pos = null;
    class Chart {
      constructor(opts) {
        this.data = opts.data;
        this.element = opts.element;
      }

      draw() {
        this.width = this.element.offsetWidth;
        this.height = this.width / 2;
        this.padding = 50;
        this.margin = {
          top: 20,
          bottom: 20,
          left: 30,
          right: 50
        };

        this.element.innerHTML = '';
        const svg = d3.select(this.element).append('svg');
        svg.attr('width', this.width);
        svg.attr('height', this.height);

        this.plot = svg.append('g')
          .attr('transform', `translate(${this.margin.left},${this.margin.top})`);

        this.createScales();
        this.addAxes();
        this.addLine();
        this.tTip();
      }

      createScales() {
        this.keynames = d3.scaleOrdinal();

        this.keynames.domain(Object.keys(this.data[0]).filter(key => key !== 'date'));

        this.keymap = this.keynames.domain().map(
          keyname => ({
            name: keyname, values: this.data.map(
              d => ({ date: d.date, key: +d[keyname] })
            )
          })
        );

        const m = this.margin;

        const xExtent = d3.extent(this.data, d => d.date);

        const yExtent = [0, d3.max(this.keymap, d => d3.max(d.values, function (v) { return v.key }))];

        this.xScale = d3.scaleTime()
          .range([0, this.width - m.right])
          .domain(xExtent).nice();

        this.yScale = d3.scaleLinear()
          .range([this.height - (m.top + m.bottom), 0])
          .domain(yExtent).nice();
      }

      addAxes() {
        const m = this.margin;

        const xAxis = d3.axisBottom()
          .scale(this.xScale);

        const yAxis = d3.axisLeft()
          .scale(this.yScale);

        this.plot.append("g")
          .attr("class", "x axis")
          .attr("transform", `translate(0, ${this.height - (m.top + m.bottom)})`)
          .call(xAxis.ticks(8));

        this.plot.append("g")
          .attr("class", "y axis")
          .call(yAxis.ticks(4))
          .append("text")
          .attr("transform", "rotate(-90)")
          .attr("y", 6)
          .attr("dy", ".71em")
          .attr("fill", "black")
          .style("text-anchor", "end")
          .text("$USD");
      }

      addLine() {
        const line = d3.line()
          .x(d => this.xScale(d.date))
          .y(d => this.yScale(d.key));

        this.plot.append('g')
          .selectAll('path')
          .data(this.keymap)
          .join('path')
          .classed('line', true)
          .attr('d', function (d) { return line(d.values) })
          .style('stroke', this.lineColor || 'red')
          .style('fill', 'none');
      }

      tTip() {
        let mouseG = this.plot.append("g")
          .attr("class", "mouse-over-effects");

        mouseG.append("path")
          .attr("class", "mouse-line")
          .style("stroke", "rgba(50,50,50,1)")
          .style("stroke-width", "0.5px")
          .style("opacity", "0");

        var lines = document.getElementsByClassName('line'); //issue here

        let mousePerLine = mouseG.selectAll('.mouse-per-line')
          .data(this.keymap)
          .enter()
          .append("g") //join instead of append?
          .attr("class", "mouse-per-line");

        mousePerLine.append("circle") //join instead of append?
          .attr("r", 4)
          .style("stroke", "black"
          )
          .style("fill", "blue"
          )
          .style("fill-opacity", "0.3")
          .style("stroke-width", "1px")
          .style("opacity", "0");

        mousePerLine.append("text") //join instead of append?
          .attr("transform", function (d) {
            if (d.name == 'aapl') {
              return "translate(-50,30)"
            } else {
              return "translate(-50, -30)"
            }
          }).style("text-shadow",
            " -2px -2px 0 #FFF, 0   -2px 0 #FFF, 2px -2px 0 #FFF, 2px  0   0 #FFF, 2px  2px 0 #FFF, 0    2px 0 #FFF,-2px  2px 0 #FFF,-2px  0   0 #FFF");

        mouseG.append('svg:rect')
          .attr('width', this.width)
          .attr('height', this.height)
          .attr('x', '0')
          .attr('fill', 'none')
          .attr('pointer-events', 'all')
          .on('mouseout', function () {
            d3.select(".mouse-line")
              .style("opacity", "0");
            d3.selectAll(".mouse-per-line circle")
              .style("opacity", "0");
            d3.selectAll(".mouse-per-line text")
              .style("opacity", "0");
          })
          .on('mouseover', function () {
            d3.select(".mouse-line")
              .style("opacity", "1");
            d3.selectAll(".mouse-per-line circle")
              .style("opacity", "1");
            d3.selectAll(".mouse-per-line text")
              .style("opacity", "1");
          })
          .on('mousemove', () => {
            let mouse = d3.pointer(event);
            d3.select(".mouse-line")
              .attr("d", () => {
                let d = "M" + mouse[0] + "," + this.height;
                d += " " + mouse[0] + "," + 0;
                return d;
              });

            d3.selectAll(".mouse-per-line")
              .attr("transform", function (d, i) {
                let xDate = chart.xScale.invert(mouse[0]),
                  bisect = d3.bisector(d => d.date).right,
                  idx = bisect(d.values, xDate);

                let beginning = 0,
                  end = lines[i].getTotalLength(),
                  target = null;
                while (true) {
                  let target = Math.floor((beginning + end) / 2);
                  pos = lines[i].getPointAtLength(target); //issue here
                  if ((target === end || target === beginning) && pos.x !== mouse[0]) {
                    break;
                  }
                  if (pos.x > mouse[0]) {
                    end = target;
                  }
                  else if (pos.x < mouse[0]) {
                    beginning = target;
                  }
                  else break; //position found
                }

                d3.select(this).select('text')
                  .text("$" + chart.yScale.invert(pos.y).toFixed(2))
                return "translate(" + mouse[0] + "," + pos.y + ")";
              })
              .style('font-family', 'Helvetica')
              .style('font-size', '11px')
              .style('letter-spacing', '1px')
              .style('text-transform', 'uppercase');
          });
      }

      setColor(newColor) {
        this.plot.select('.line')
          .style('stroke', newColor);

        this.lineColor = newColor;
      }

      setData(data) {
        this.data = data;

        this.draw();
      }
    }

    const chart = new Chart({ element: document.querySelector('#graph') });

    const data = d3.csvParse(`Date,AAPL,SMA_AAPL,TSLA,SMA_TSLA
2018-12-31,38.33848571777344,,66.55999755859375,
2019-01-02,38.382225036621094,,62.02399826049805,
2019-01-03,34.55907440185547,,60.071998596191406,
2019-01-04,36.03437805175781,,63.53799819946289,
2019-01-07,35.95417022705078,,66.99199676513672,
2019-01-08,36.63956832885742,,67.06999969482422,
2019-01-09,37.26177215576172,,67.70600128173828,
2019-01-10,37.380863189697266,,68.99400329589844,
2019-01-11,37.013858795166016,,69.4520034790039,
2019-01-14,36.4572868347168,,66.87999725341797,
2019-01-15,37.20343780517578,,68.88600158691406,
2019-01-16,37.657936096191406,,69.20999908447266,
2019-01-17,37.88154602050781,,69.46199798583984,
2019-01-18,38.11487579345703,,60.45199966430664,
2019-01-22,37.259342193603516,,59.784000396728516,
2019-01-23,37.410030364990234,,57.518001556396484,
2019-01-24,37.113521575927734,,58.301998138427734,
2019-01-25,38.34333801269531,,59.40800094604492,
2019-01-28,37.988487243652344,,59.2760009765625,
2019-01-29,37.59474182128906,,59.492000579833984,
2019-01-30,40.16377258300781,,61.75400161743164,
2019-01-31,40.453006744384766,,61.40399932861328,
2019-02-01,40.472450256347656,,62.44200134277344,
2019-02-04,41.622066497802734,,62.577999114990234,
2019-02-05,42.33420181274414,,64.2699966430664,
2019-02-06,42.34878158569336,,63.444000244140625,
2019-02-07,41.546722412109375,,61.50199890136719,
2019-02-08,41.59553909301758,,61.15999984741211,
2019-02-11,41.35633087158203,,62.56800079345703,
2019-02-12,41.71269989013672,38.606483713785806,62.36199951171875,63.48539975484212
2019-02-13,41.539398193359375,38.71318079630534,61.63399887084961,63.32119979858398
2019-02-14,41.69073486328125,38.823464457194014,60.75400161743164,63.278866577148435
2019-02-15,41.59797286987305,39.05809440612793,61.57600021362305,63.32899996439616
2019-02-19,41.72246551513672,39.247697321573895,61.12799835205078,63.24866663614909
2019-02-20,41.990962982177734,39.44892374674479,60.512001037597656,63.032666778564455
2019-02-21,41.75419616699219,39.619411341349284,58.24599838256836,62.738533401489256
2019-02-22,42.22041702270508,39.78469950358073,58.94200134277344,62.44640007019043
2019-02-25,42.5279655456543,39.95626958211263,59.75400161743164,62.13840001424153`, function (d) {
      function removeNaN(e, c) {
        if (e > 0) { return e; } else { return c; }
      }
      return {
        date: d3.timeParse("%Y-%m-%d")(d.Date),
        aapl: +d.AAPL,
        tsla: +d.TSLA,
        aapl_sma: removeNaN(+d.SMA_AAPL, +d.AAPL),
        tsla_sma: removeNaN(+d.SMA_TSLA, +d.TSLA)
      };
    });

    chart.setData(data);
  </script>
</body>

</html>

Instead of listing all of them, I've created a diff file. Download and check. Left side is the original code.


问:
Upgrading Spring Boot 2.5.2 to 2.6.3 breaks all projection based JPA queries
When I try to upgrade to application's Spring Boot from 2.5.2 to 2.6.3 all projection based JpaRepository queries fail to be generated with the following:

```<code>......
......
......

Caused by: java.lang.IllegalArgumentException: Failed to create query for method public abstract java.util.Optional com.misc.project.ProjectRepository.getProjectionByIdAndField(java.lang.String,java.lang.String)! null
    at org.springframework.data.jpa.repository.query.PartTreeJpaQuery.<init>(PartTreeJpaQuery.java:96)
    at org.springframework.data.jpa.repository.query.JpaQueryLookupStrategy$CreateQueryLookupStrategy.resolveQuery(JpaQueryLookupStrategy.java:113)
    at org.springframework.data.jpa.repository.query.JpaQueryLookupStrategy$CreateIfNotFoundQueryLookupStrategy.resolveQuery(JpaQueryLookupStrategy.java:254)
    at org.springframework.data.jpa.repository.query.JpaQueryLookupStrategy$AbstractQueryLookupStrategy.resolveQuery(JpaQueryLookupStrategy.java:87)
    at org.springframework.data.repository.core.support.QueryExecutorMethodInterceptor.lookupQuery(QueryExecutorMethodInterceptor.java:102)
    ... 85 common frames omitted
Caused by: java.lang.NullPointerException: null
    at org.springframework.data.jpa.repository.query.JpaQueryCreator.complete(JpaQueryCreator.java:181)
    at org.springframework.data.jpa.repository.query.JpaQueryCreator.complete(JpaQueryCreator.java:152)
    at org.springframework.data.jpa.repository.query.JpaQueryCreator.complete(JpaQueryCreator.java:59)
    at org.springframework.data.repository.query.parser.AbstractQueryCreator.createQuery(AbstractQueryCreator.java:95)
    at org.springframework.data.repository.query.parser.AbstractQueryCreator.createQuery(AbstractQueryCreator.java:81)
    at org.springframework.data.jpa.repository.query.PartTreeJpaQuery$QueryPreparer.<init>(PartTreeJpaQuery.java:217)
    at org.springframework.data.jpa.repository.query.PartTreeJpaQuery.<init>(PartTreeJpaQuery.java:92)
    ... 89 common frames omitted
</code>```

Method looks like:

```<code>Optional<SomeProjection> getProjectionByIdAndField(String id, String field);
</code>```

Projection is interface based like so:

```<code>public interface SomeProjection {
  Long getSomething();
}
</code>```

If I write the query manually with @Query, it moves to the next projection. Is there some way I can fix this issue without having to write manually queries for all projection based JPA methods?

I cannot find any mention of this problem here:
https://github.com/spring-projects/spring-boot/wiki/Spring-Boot-2.6-Release-Notes#upgrading-from-spring-boot-25

I found they mention some improvements to projections in:
https://github.com/spring-projects/spring-data-commons/wiki/Release-Train-2021.1-%28Q%29-Release-Notes#jdbc.projections

But nothing about breaking old versions.

答: This is a bug introduced in Spring Data JPA 2.6.1. Upgrade to Spring Boot 2.6.4 to get the Spring Data JPA version containing the fix.</p>

Body:
When I try to upgrade to application's Spring Boot from 2.5.2 to 2.6.3 all projection based JpaRepository queries fail to be generated with the following:

......
......
......

Caused by: java.lang.IllegalArgumentException: Failed to create query for method public abstract java.util.Optional com.misc.project.ProjectRepository.getProjectionByIdAndField(java.lang.String,java.lang.String)! null
    at org.springframework.data.jpa.repository.query.PartTreeJpaQuery.<init>(PartTreeJpaQuery.java:96)
    at org.springframework.data.jpa.repository.query.JpaQueryLookupStrategy$CreateQueryLookupStrategy.resolveQuery(JpaQueryLookupStrategy.java:113)
    at org.springframework.data.jpa.repository.query.JpaQueryLookupStrategy$CreateIfNotFoundQueryLookupStrategy.resolveQuery(JpaQueryLookupStrategy.java:254)
    at org.springframework.data.jpa.repository.query.JpaQueryLookupStrategy$AbstractQueryLookupStrategy.resolveQuery(JpaQueryLookupStrategy.java:87)
    at org.springframework.data.repository.core.support.QueryExecutorMethodInterceptor.lookupQuery(QueryExecutorMethodInterceptor.java:102)
    ... 85 common frames omitted
Caused by: java.lang.NullPointerException: null
    at org.springframework.data.jpa.repository.query.JpaQueryCreator.complete(JpaQueryCreator.java:181)
    at org.springframework.data.jpa.repository.query.JpaQueryCreator.complete(JpaQueryCreator.java:152)
    at org.springframework.data.jpa.repository.query.JpaQueryCreator.complete(JpaQueryCreator.java:59)
    at org.springframework.data.repository.query.parser.AbstractQueryCreator.createQuery(AbstractQueryCreator.java:95)
    at org.springframework.data.repository.query.parser.AbstractQueryCreator.createQuery(AbstractQueryCreator.java:81)
    at org.springframework.data.jpa.repository.query.PartTreeJpaQuery$QueryPreparer.<init>(PartTreeJpaQuery.java:217)
    at org.springframework.data.jpa.repository.query.PartTreeJpaQuery.<init>(PartTreeJpaQuery.java:92)
    ... 89 common frames omitted

Method looks like:

Optional<SomeProjection> getProjectionByIdAndField(String id, String field);

Projection is interface based like so:

public interface SomeProjection {
  Long getSomething();
}

If I write the query manually with @Query, it moves to the next projection. Is there some way I can fix this issue without having to write manually queries for all projection based JPA methods?

I cannot find any mention of this problem here:
https://github.com/spring-projects/spring-boot/wiki/Spring-Boot-2.6-Release-Notes#upgrading-from-spring-boot-25

I found they mention some improvements to projections in:
https://github.com/spring-projects/spring-data-commons/wiki/Release-Train-2021.1-%28Q%29-Release-Notes#jdbc.projections

But nothing about breaking old versions.


问:
AudioKit - How to connect MIDI input to MIDISampler
My goal is to receive MIDI events from an external keyboard and trigger the appropriate notes on a sampler. I wasn't able to come up with a working solution so far and I haven't found an example covering that exact usecase.

My code so far (macOS, Swift):

let audioEngine = AudioEngine()
let sampler = MIDISampler()
audioEngine.output = sampler

try! audioEngine.start()
try! sampler.loadEXS24("...")

sampler.enableMIDI()
```

When I manually trigger a note via sampler.receivedMIDINoteOn, I hear a sound. The MIDI part itself also works - I hooked up a MIDIListener and logged the noteOn events. However I don't understand how to connect both parts together.

答:
Add a MidiListener Delegate like this:

```<code>class YourSamplerConductor: ObservableObject, MIDIListener
</code>```

This will in give you an error and when you click over the "X" you'll have the option to import the MidiListener delegate methods.

This is how I add the listener in my init method:

```<code>let midi = MIDI.sharedInstance
midi.openInput()
midi.addListener(self)
</code>```

Then pass your note info to the delegate methods.

```<code>func receivedMIDINoteOn(noteNumber: MIDINoteNumber, velocity: MIDIVelocity, channel: MIDIChannel, portID: MIDIUniqueID?, timeStamp: MIDITimeStamp?) {
    sampler.play(noteNumber: noteNumber, velocity: velocity, channel: channel)
}
</code>```

Body:
My goal is to receive MIDI events from an external keyboard and trigger the appropriate notes on a sampler. I wasn't able to come up with a working solution so far and I haven't found an example covering that exact usecase.

My code so far (macOS, Swift):

let audioEngine = AudioEngine()
let sampler = MIDISampler()
audioEngine.output = sampler

try! audioEngine.start()
try! sampler.loadEXS24("...")

sampler.enableMIDI()

When I manually trigger a note via sampler.receivedMIDINoteOn, I hear a sound. The MIDI part itself also works - I hooked up a MIDIListener and logged the noteOn events. However I don't understand how to connect both parts together.

Body:
Add a MidiListener Delegate like this:

class YourSamplerConductor: ObservableObject, MIDIListener

This will in give you an error and when you click over the "X" you'll have the option to import the MidiListener delegate methods.

This is how I add the listener in my init method:

let midi = MIDI.sharedInstance
midi.openInput()
midi.addListener(self)

Then pass your note info to the delegate methods.

func receivedMIDINoteOn(noteNumber: MIDINoteNumber, velocity: MIDIVelocity, channel: MIDIChannel, portID: MIDIUniqueID?, timeStamp: MIDITimeStamp?) {
    sampler.play(noteNumber: noteNumber, velocity: velocity, channel: channel)
}


问:
How do I call my Django REST API endpoint with CURL?
I want to call my Django REST Framework API using cURL, but it doesn't do anything.

My URL is like "https://MYURL/api/seedevents?secret=SECRET". In postman this works and returns a 201 Created HTTP response. If I call using CURL for example "curl -XGET 'https://MYURL/api/seedevents?secret=SECRET', then it doesn't do anything at all. I can see the request come in in the logs, but it just doesn't do anything.

Please can someone advise me what I can do?

答:
I guess it's probably missing some headers.

A helpful tip is to extract the curl command from Postman, on the right side you will find a code symbol as the below screenshot, that will make the same request in different form, choose cURL and use the command (make sure to use data instead of data-raw in case you have a payload)

Also add -vvv after curl to debug the curl


问:
Json deserialization error „'W' is an invalid start of a value
I need to create a simple game in Console. I have Serializing JSON and when i want to deserialize this file i have this error:
System.Text.Json.JsonException: „'W' is an invalid start of a value. Path: $ | LineNumber: 0 | BytePositionInLine: 0.”

This is code of my classes:

```<code>public class Person
{
    public string Speciality { get; set; }
    public int PWZ { get; set; }
    public string Name { get; set; }
    public string Surname { get; set; }
    public List<string> Items { get; set; }
}

public class Monster
{
    public string Name { get; set; }
    public List<string> Skills { get; set; }
}

public class Root
{
    public List<Person> people { get; set; }
    public List<Monster> monsters { get; set; }
}
</code>```

Json file

```<code>{
  "Person": [
    {
      "Speciality": "Archer",
      "PWZ": 432742,
      "Name": "Charlie",
      "Surname": "Evans",
      "Items": [
        "Bow",
        "Arrow",
      ]
    },
    {
      "Speciality": "Soldier",
      "PWZ": 432534879,
      "Name": "Harry",
      "Surname": "Thomas",
      "Items": [
        "Gun",
        "Knife",
     ]
    }
  ],
  "Monster": [
    {
      "Name": "Papua",
      "Skills": [
        "Jump",
        "SlowWalk",
      ]
    },
    {
     "Name": "Geot",
      "Skills": [
        "Run",
        "Push",
      ]
    }
  ]
}
</code>```

And it's my code used to deserialize json file:

```<code>string fileName = "Local.json";
var options = new JsonSerializerOptions { AllowTrailingCommas = true };
var result = JsonSerializer.Deserialize<Root>(fileName, options);
</code>```

I haven't worked with serialize and deserialize with JSON files.
Thanks in advance.

答:
In your previous question you were advised to update the model to rename the properties to  Person and Monster.

Assuming this hasn't reverted, then the issue here is how you're reading and trying to deserialize the file.  You need to open the contents of the file then deserialize, but you're mistakenly trying to deserialize the fileName string. Correct code below:

```<code>string fileName = "Local.json";
// open the file contents
string jsonContents = File.ReadAllText(fileName);
var options = new JsonSerializerOptions { AllowTrailingCommas = true };
// deserialize the file contents, not the fileName
var result = JsonSerializer.Deserialize<Root>(jsonContents, options);
</code>```

Body:
I need to create a simple game in Console. I have Serializing JSON and when i want to deserialize this file i have this error:
System.Text.Json.JsonException: „'W' is an invalid start of a value. Path: $ | LineNumber: 0 | BytePositionInLine: 0.”

This is code of my classes:

public class Person
{
    public string Speciality { get; set; }
    public int PWZ { get; set; }
    public string Name { get; set; }
    public string Surname { get; set; }
    public List<string> Items { get; set; }
}

public class Monster
{
    public string Name { get; set; }
    public List<string> Skills { get; set; }
}

public class Root
{
    public List<Person> people { get; set; }
    public List<Monster> monsters { get; set; }
}

Json file

{
  "Person": [
    {
      "Speciality": "Archer",
      "PWZ": 432742,
      "Name": "Charlie",
      "Surname": "Evans",
      "Items": [
        "Bow",
        "Arrow",
      ]
    },
    {
      "Speciality": "Soldier",
      "PWZ": 432534879,
      "Name": "Harry",
      "Surname": "Thomas",
      "Items": [
        "Gun",
        "Knife",
     ]
    }
  ],
  "Monster": [
    {
      "Name": "Papua",
      "Skills": [
        "Jump",
        "SlowWalk",
      ]
    },
    {
     "Name": "Geot",
      "Skills": [
        "Run",
        "Push",
      ]
    }
  ]
}

And it's my code used to deserialize json file:

string fileName = "Local.json";
var options = new JsonSerializerOptions { AllowTrailingCommas = true };
var result = JsonSerializer.Deserialize<Root>(fileName, options);

I haven't worked with serialize and deserialize with JSON files.
Thanks in advance.

Body:
In your previous question you were advised to update the model to rename the properties to  Person and Monster.

Assuming this hasn't reverted, then the issue here is how you're reading and trying to deserialize the file.  You need to open the contents of the file then deserialize, but you're mistakenly trying to deserialize the fileName string. Correct code below:

string fileName = "Local.json";
// open the file contents
string jsonContents = File.ReadAllText(fileName);
var options = new JsonSerializerOptions { AllowTrailingCommas = true };
// deserialize the file contents, not the fileName
var result = JsonSerializer.Deserialize<Root>(jsonContents, options);


问:
Correlation between the gain and the activity level of a microphone object in flash/flex
The microphone's gain property is default at 50 and ranges from 0 to 100, It boosts the signal from the microphone.

The microphone activityLevel property also ranges from 0 to 100, and describes the volume of the recorded mic audio.

I need to know the correlation between boosting the signal and the activity level, which does have an effect on each other that I have tested. What does a gain of 100 mean?

答:
The activityLevel property defines the sensitivity of the microphone - the range of sounds it will pick up - if you want it picking up everything it can, including background noise and quiet noises, assign this property to 100. If you want it picking up only LOUD noises, turn it to 0.

The gain is the strength of the amplification of the microphone's sound - 100 is the most, 0 is the least. Turning the gain up makes sound quality deteriorate (Depending on quality of equipment), while it gets louder.

Turning gain to 100 and activityLevel 0 means you're making Loud noises louder. Gain 0, activityLevel 100 means you're picking up every sound and not amplifying it.


问:
Cypress Cucumber, how Get to data from page in one step and use it another scenario step
Below is mine scenario  where in one scenario I'm getting data from page and saving it in a variable as alias.
tHen I want to use same variable/data in other scenario  to put in an input field.I'm using Alias but getting this error.

cy.wait() could not find a registered alias for: @Orderinfo.
You have not aliased anything yet.

Even it alliased properly. Data stores in @Orderinfo  but not accessable in other sceanrio step.

```<code>Then("Get Data from page", () => {
  cy.get(".os-order-number").invoke("text").then(($Oid) => {
    let Order = $Oid.text();
    let Order_id = Order.replace(/[^0-9]/g, "");
    cy.wrap(Order_id).as("Orderinfo");
  });
});

Given("Go to Login", () => {
  cy.visit("https://dev.simplifyshopping.com/register/");
});

When("Paste variable here", () => {
  cy.wait(2000);
  cy.wait("@Orderinfo")
  cy.get("@Orderinfo")).then((Orderinfo) => {
    console.log(Orderinfo);
    cy.get("#id_email").type(Orderinfo);
  });
});
</code>```

答:
So both, the use across several steps of the same scenario, as well as scenario overlapping are possible with Cypress using Cucumber Preprocessor.

1. Use of values across multiple steps of the same scenario

Referring to the example from the question, the Order_Id can be defined outside the steps and is thus accessible in the global scope from all steps. If I understood the code correctly, it would be something like this (probably unnecessary code commented out):

```<code>let Order_id;

Then("Get Data from page", () => {
  cy.get(".os-order-number").invoke("text").then(($Oid) => {
    let Order = $Oid.text();
    Order_id = Order.replace(/[^0-9]/g, "");
    // cy.wrap(Order_id).as("Orderinfo");
  });
});

Given("Go to Login", () => {
  cy.visit("https://dev.simplifyshopping.com/register/");
});

When("Paste variable here", () => {
  cy.wait(2000);
  // cy.wait("@Orderinfo")
  // cy.get("@Orderinfo")).then((Orderinfo) => {
  //  console.log(Orderinfo);
  //  cy.get("#id_email").type(Orderinfo);
  // });

  console.log(Order_id);
  cy.get("#id_email").type(Order_id);
});
</code>```

2. Use of values across scenarios (hold state across tests)

To make certain values accessible across the execution of different scenarios, for example, a helper.js file can be created containing the following code:

```<code>export const stateStore = {};
</code>```

Inside your step definition files, you can then import the stateStore and fill it with values as you like:

```<code>import { Given, When } from 'cypress-cucumber-preprocessor/steps';
import { stateStore } from '../helpers';

// step used in first scenario
Given('some value is made available in scenario 1', () => {
  stateStore.someValue = 'this is a value';
});

// step used in second scenario
When('this value can be used in another step of scneario 2', () => {
  console.log(`Print some value: ${stateStore.someValue}`);
});
</code>```

Body:
Below is mine scenario  where in one scenario I'm getting data from page and saving it in a variable as alias.
tHen I want to use same variable/data in other scenario  to put in an input field.I'm using Alias but getting this error.

cy.wait() could not find a registered alias for: @Orderinfo.
You have not aliased anything yet.

Even it alliased properly. Data stores in @Orderinfo  but not accessable in other sceanrio step.

Then("Get Data from page", () => {
  cy.get(".os-order-number").invoke("text").then(($Oid) => {
    let Order = $Oid.text();
    let Order_id = Order.replace(/[^0-9]/g, "");
    cy.wrap(Order_id).as("Orderinfo");
  });
});

Given("Go to Login", () => {
  cy.visit("https://dev.simplifyshopping.com/register/");
});

When("Paste variable here", () => {
  cy.wait(2000);
  cy.wait("@Orderinfo")
  cy.get("@Orderinfo")).then((Orderinfo) => {
    console.log(Orderinfo);
    cy.get("#id_email").type(Orderinfo);
  });
});

Body:
So both, the use across several steps of the same scenario, as well as scenario overlapping are possible with Cypress using Cucumber Preprocessor.

1. Use of values across multiple steps of the same scenario

Referring to the example from the question, the Order_Id can be defined outside the steps and is thus accessible in the global scope from all steps. If I understood the code correctly, it would be something like this (probably unnecessary code commented out):

let Order_id;

Then("Get Data from page", () => {
  cy.get(".os-order-number").invoke("text").then(($Oid) => {
    let Order = $Oid.text();
    Order_id = Order.replace(/[^0-9]/g, "");
    // cy.wrap(Order_id).as("Orderinfo");
  });
});

Given("Go to Login", () => {
  cy.visit("https://dev.simplifyshopping.com/register/");
});

When("Paste variable here", () => {
  cy.wait(2000);
  // cy.wait("@Orderinfo")
  // cy.get("@Orderinfo")).then((Orderinfo) => {
  //  console.log(Orderinfo);
  //  cy.get("#id_email").type(Orderinfo);
  // });

  console.log(Order_id);
  cy.get("#id_email").type(Order_id);
});

2. Use of values across scenarios (hold state across tests)

To make certain values accessible across the execution of different scenarios, for example, a helper.js file can be created containing the following code:

export const stateStore = {};

Inside your step definition files, you can then import the stateStore and fill it with values as you like:

import { Given, When } from 'cypress-cucumber-preprocessor/steps';
import { stateStore } from '../helpers';

// step used in first scenario
Given('some value is made available in scenario 1', () => {
  stateStore.someValue = 'this is a value';
});

// step used in second scenario
When('this value can be used in another step of scneario 2', () => {
  console.log(`Print some value: ${stateStore.someValue}`);
});


问:
How to select a random key from an UnorderedMap in NEAR Rust SDK?
How can one get a random key from an UnorderedMap in NEAR Rust SDK?</p>

答:
If you know you key space then you can use near_sdk::env::random_seed() to generate a random seed and use that to get any key from the unordered_map.

https://docs.rs/near-sdk/latest/near_sdk/env/fn.random_seed.html

For Example:
If you have a Unordered_map<u64, Some_Struct>

The You generate a seed and convert it from Vec which random_seed() gives to u64

let randomId = u64::from_be_bytes(env::random_seed())

And get this from unordered_map as

unordered_map.get(&randomId).unwrap()

Not the most efficient way but you can try this.
Open to better solutions.


问:
How do i bold a text in JavaScript?
I am trying to change text to bold, which is really hard.
I tried many times using various ways,
for example:

```<code>//1:

document.getElementById('boldtext').innerHTML = "<b>" += document.getElementById('boldtext').innerHTML += "</b>"; //which dosent work

//2:

document.getElementById('boldtext').bold(); //dosent work too

</code>```

Any ideas on how to bold text in Javascript?

```<code>//My code so far:
The whole code is this: function getSelectionText() { var text = ""; if (window.getSelection) { text = window.getSelection().toString(); } else if (document.selection && document.selection.type != "Control") { text = document.selection.createRange().text; } alert(text); }; let BoldButton = document.createElement('input'); /*boldbuttonlol*/ BoldButton.type = 'button'; BoldButton.value = 'bold highlighted text'; BoldButton.onclick = () => { getSelectionText(); }; document.body.appendChild(BoldButton);
</code>```

Thank you!!

答:
simply use</p>
```<code>document.getElementById('boldtext').style.fontWeight = "bold";
</code>```

Title: How do i bold a text in JavaScript?

Body:
I am trying to change text to bold, which is really hard.
I tried many times using various ways,
for example:

//1:

document.getElementById('boldtext').innerHTML = "" += document.getElementById('boldtext').innerHTML += ""; //which dosent work

//2:

document.getElementById('boldtext').bold(); //dosent work too

Any ideas on how to bold text in Javascript?

//My code so far:
The whole code is this: function getSelectionText() { var text = ""; if (window.getSelection) { text = window.getSelection().toString(); } else if (document.selection && document.selection.type != "Control") { text = document.selection.createRange().text; } alert(text); }; let BoldButton = document.createElement('input'); /*boldbuttonlol*/ BoldButton.type = 'button'; BoldButton.value = 'bold highlighted text'; BoldButton.onclick = () => { getSelectionText(); }; document.body.appendChild(BoldButton);

Thank you!!

Body:
simply use

document.getElementById('boldtext').style.fontWeight = "bold";


问:
python libxml2 serialization problem
I'm having some problems while attempting to serialize a libxml2 object in python.

In particular, if I run :

```<code>xmlstring = cdoc.serialize('UTF-8', 1)
</code>```

where cdoc is a libxml2 document created before,

I have something like this : ( on a mac - port python 2.5.6)

```<code><?xml version="1.0" encoding="UTF-8"?>
<body>
    <journal>
      <journal_metadata language="en">
        <full_title>Contributions of Lick Observatory</full_title>
        <issn media_type="print">1750-0095</issn>
        <coden>CoLic</coden>
      </journal_metadata>
    </journal>
</body>
</code>```

while on Linux (Centos 5.6 with python 2.4 or 2.6) I have :

```<code><?xml version="1.0" encoding="UTF-8"?>
<body>
    <journal>
      <journal_metadata language="en">
        <full_title>
Contributions of Lick Observatory
        </full_title>
        <issn media_type="print">
1750-0095
        </issn>
        <coden>
CoLic
        </coden>
      </journal_metadata>
    </journal>
</body>
</code>```

There is a problem in the indentation of the string node.

Now I could solve this by doing :

```<code>xmlstring = cdoc.serialize('UTF-8')
</code>```

without the option for the indentation, but the output format is not very readable.

Is there a way to fix the awkward indentation of the output?

答: It could be a behaviour difference between the version of libxml2 on the different machines. Try upgrading the oldest one to the newer release (or a more recent one). </p>

Title: python libxml2 serialization problem

Body:
I'm having some problems while attempting to serialize a libxml2 object in python.

In particular, if I run :

xmlstring = cdoc.serialize('UTF-8', 1)

where cdoc is a libxml2 document created before,

I have something like this : ( on a mac - port python 2.5.6)

<?xml version="1.0" encoding="UTF-8"?>

    <journal>
      <journal_metadata language="en">
        <full_title>Contributions of Lick Observatory</full_title>
        <issn media_type="print">1750-0095</issn>
        <coden>CoLic</coden>
      </journal_metadata>
    </journal>

while on Linux (Centos 5.6 with python 2.4 or 2.6) I have :

<?xml version="1.0" encoding="UTF-8"?>

    <journal>
      <journal_metadata language="en">
        <full_title>
Contributions of Lick Observatory
        </full_title>
        <issn media_type="print">
1750-0095
        </issn>
        <coden>
CoLic
        </coden>
      </journal_metadata>
    </journal>

There is a problem in the indentation of the string node.

Now I could solve this by doing :

xmlstring = cdoc.serialize('UTF-8')

without the option for the indentation, but the output format is not very readable.

Is there a way to fix the awkward indentation of the output?


问:
How to empty the file content in vi editor
I have a log file on a server called log.txt which has many lines. I open the file using the vi editor, and I want to empty the file content in command line mode of the vieditor. What's the key combination? please help me. Thank you!!!

答: First come out front input mode by pressing ESC key then apply gg to go to first line and then type dG to delete everything .after that save the file with :w command that way you will have a blank file :)


问:
How to code and compile mql4 and mql5 language in VS Code?
I moved to mql4 and mql5 programming language. But, MetaEditor is very noob to code with,

so I want to code mql4 language and compile with VS Code.

If you have any solution please share with us.....

Thanks

答:
In the very early years of MQL4 ( MetaTrader Terminal, versions in about 2008-2010 ), there was a separate compiler programme, thus was configurable into other IDE ( me, using Geany-IDE ecosystem for doing this since ever )

After MQL4 language-revision, somewhere about 2009-2010 iirc, this option ceased to exist.

Inside MQL5 ecosystem, this option was available never.

The maximum achievable comfort thus remains in code-syntax highlights, code-completion configurations, if doable & done manually for the sake of your individual preferences ( me, using Geany-IDE ecosystem, being happy with MQL4-language configurations ( revised whenever MQL4 took further language specification revisions ) & copy/paste "technology" or #include-trick for moving between the two distinct ecosystems )


问:
CakePHP 4 Bake Custom TemplateCommand in Plugin
I cannot seem to override TemplateCommand from my plugin.

Original TemplateCommand located here: vendor/cakephp/bake/src/Command/TemplateCommand.php

```<code>namespace Bake\Command;

...

class TemplateCommand extends BakeCommand
{...}
</code>```

I stored mine here: plugins/MyPlugin/src/Command/TemplateCommand:

```<code>namespace MyPlugin\Bake\Command;

...

use Bake\Command\TemplateCommand as MyTemplateCommand;

class TemplateCommand extends MyTemplateCommand
{...}
</code>```

When I run bin/cake bake template books -t "MyPlugin", I get:

```<code>Fatal error: Cannot declare class MyPlugin\Bake\Command\TemplateCommand, because the name is already in use in C:\path\to\app\plugins\MyPlugin\src\Command\TemplateCommand.php on line 39
</code>```

Edit #2

In Plugin.php, in bootstrap(), I was able to debug loaded plugins.

```<code>[
        (int) 0 => 'AuditStash',
        (int) 1 => 'Bake',
        (int) 2 => 'DebugKit',
        (int) 3 => 'Migrations',
        (int) 4 => 'MyPlugin'
]
</code>```

Edit #3

In plugins/MyPlugin/src/Command/TemplateCommand.php, I added ***MYPLUGIN*** to the output.

```<code>namespace MyPlugin\Command;

...

use Bake\Command\TemplateCommand as MyPluginTemplateCommand;

class TemplateCommand extends MyPluginTemplateCommand
{
    ...
    public function bake(
        Arguments $args,
        ConsoleIo $io,
        string $template,
        $content = '',
        ?string $outputFile = null
    ): void {
        if ($outputFile === null) {
            $outputFile = $template;
        }
        if ($content === true) {
            $content = $this->getContent($args, $io, $template);
        }
        if (empty($content)) {
            $io->err("<warning>No generated content for '{$template}.php', not generating template.</warning>");

            return;
        }
        $path = $this->getTemplatePath($args);
        $filename = $path . Inflector::underscore($outputFile) . '.php';

        $io->out("\n" . sprintf('***MYPLUGIN*** Baking `%s` view template file...', $outputFile), 1, ConsoleIo::QUIET);
        $io->createFile($filename, $content, $args->getOption('force'));
    }
    ...
}
</code>```

When I run bin/bake template books -t MyPlugin, I see this message without my added prefix:

Baking index view template file...

It doesn't seem to pickup my class.

Edit #4

In vendor/cakephp/cakephp/src/Console/CommandRunner.php, function run, I added var_dump:

```<code>...
$shell = $this->getCommand($io, $commands, $name);
var_dump($commands);
...
</code>```

Output:

```<code>object(Cake\Console\CommandCollection)#33 (1) {
  ["commands":protected]=>
  array(87) {
    ["help"]=>
    string(32) "Cake\Console\Command\HelpCommand"
    ["version"]=>
    string(27) "Cake\Command\VersionCommand"
    ["cache clear"]=>
    string(30) "Cake\Command\CacheClearCommand"
    ["cache clear_all"]=>
    string(33) "Cake\Command\CacheClearallCommand"
    ["cache list"]=>
    string(29) "Cake\Command\CacheListCommand"
    ["completion"]=>
    string(30) "Cake\Command\CompletionCommand"
    ["i18n"]=>
    string(24) "Cake\Command\I18nCommand"
    ["i18n extract"]=>
    string(31) "Cake\Command\I18nExtractCommand"
    ["i18n init"]=>
    string(28) "Cake\Command\I18nInitCommand"
    ["plugin assets copy"]=>
    string(36) "Cake\Command\PluginAssetsCopyCommand"
    ["plugin assets remove"]=>
    string(38) "Cake\Command\PluginAssetsRemoveCommand"
    ["plugin assets symlink"]=>
    string(39) "Cake\Command\PluginAssetsSymlinkCommand"
    ["plugin load"]=>
    string(30) "Cake\Command\PluginLoadCommand"
    ["plugin loaded"]=>
    string(32) "Cake\Command\PluginLoadedCommand"
    ["plugin unload"]=>
    string(32) "Cake\Command\PluginUnloadCommand"
    ["routes check"]=>
    string(31) "Cake\Command\RoutesCheckCommand"
    ["routes"]=>
    string(26) "Cake\Command\RoutesCommand"
    ["routes generate"]=>
    string(34) "Cake\Command\RoutesGenerateCommand"
    ["schema_cache build"]=>
    string(36) "Cake\Command\SchemacacheBuildCommand"
    ["schema_cache clear"]=>
    string(36) "Cake\Command\SchemacacheClearCommand"
    ["server"]=>
    string(26) "Cake\Command\ServerCommand"
    ["console"]=>
    string(22) "App\Shell\ConsoleShell"
    ["model"]=>
    string(29) "MyPlugin\Command\ModelCommand"
    ["my_plugin.model"]=>
    string(29) "MyPlugin\Command\ModelCommand"
    ["template"]=>
    string(32) "MyPlugin\Command\TemplateCommand"
    ["my_plugin.template"]=>
    string(32) "MyPlugin\Command\TemplateCommand"
    ...
    string(25) "Bake\Command\ModelCommand"
    ["bake template"]=>
    string(28) "Bake\Command\TemplateCommand"
    ...
  }
}
</code>```

In vendor/cakephp/cakephp/src/Console/CommandScanner.php, added var_dump:

```<code>public function scanPlugin(string $plugin): array
{
    if (!Plugin::isLoaded($plugin)) {
        return [];
    }
    $path = Plugin::classPath($plugin);
    $namespace = str_replace('/', '\\', $plugin);
    $prefix = Inflector::underscore($plugin) . '.';

    $commands = $this->scanDir($path . 'Command', $namespace . '\Command\\', $prefix, []);
    $shells = $this->scanDir($path . 'Shell', $namespace . '\Shell\\', $prefix, []);
    var_dump($commands);

    return array_merge($shells, $commands);
}
</code>```

Output:

```<code>array(0) {
}
array(2) {
  [0]=>
  array(4) {
    ["file"]=>
    string(94) "C:\path\to\MyPlugin\src\CommandModelCommand.php"
    ["fullName"]=>
    string(15) "my_plugin.model"
    ["name"]=>
    string(5) "model"
    ["class"]=>
    string(29) "MyPlugin\Command\ModelCommand"
  }
  [1]=>
  array(4) {
    ["file"]=>
    string(97) "C:\path\to\MyPlugin\src\CommandTemplateCommand.php"
    ["fullName"]=>
    string(18) "my_plugin.template"
    ["name"]=>
    string(8) "template"
    ["class"]=>
    string(32) "MyPlugin\Command\TemplateCommand"
  }
}
...
</code>```

Edit #5

I think I got it!

```<code>namespace MyPlugin\Command;

use Bake\Command\TemplateCommand as MyPluginTemplateCommand;

class TemplateCommand extends MyPluginTemplateCommand
{...}
</code>```

I also moved the addition of my plugin on the last line of the bootstrap() function.

The output from the CLI now reflects the changes I made.

Edit #6

Need to figure out why it's not writing the views to the appropriate folder. It doubles up on books: src/templates/Books/Books

Edit #7

To get rid of the doubling in the path, commented out the function getTemplatePath.

Edit #8

Final solution.

The class definition used, updated Edit #5 too.

```<code>namespace MyPlugin\Command;

use Bake\Command\TemplateCommand as MyPluginTemplateCommand;

class TemplateCommand extends MyPluginTemplateCommand
{...}
</code>```

答: Your namespace is wrong, there is no Bake folder in the path to your class file. This mismatch will cause checks for the class' existence to fail, and subsequently cause the autoloader to load the file multiple times, resulting in the error that you're seeing, as a class can only be declared once.

Body:
I cannot seem to override TemplateCommand from my plugin.

Original TemplateCommand located here: vendor/cakephp/bake/src/Command/TemplateCommand.php

namespace Bake\Command;

...

class TemplateCommand extends BakeCommand
{...}

I stored mine here: plugins/MyPlugin/src/Command/TemplateCommand:

namespace MyPlugin\Bake\Command;

...

use Bake\Command\TemplateCommand as MyTemplateCommand;

class TemplateCommand extends MyTemplateCommand
{...}

When I run bin/cake bake template books -t "MyPlugin", I get:

Fatal error: Cannot declare class MyPlugin\Bake\Command\TemplateCommand, because the name is already in use in C:\path\to\app\plugins\MyPlugin\src\Command\TemplateCommand.php on line 39

Edit #2

In Plugin.php, in bootstrap(), I was able to debug loaded plugins.

[
        (int) 0 => 'AuditStash',
        (int) 1 => 'Bake',
        (int) 2 => 'DebugKit',
        (int) 3 => 'Migrations',
        (int) 4 => 'MyPlugin'
]

Edit #3

In plugins/MyPlugin/src/Command/TemplateCommand.php, I added ***MYPLUGIN*** to the output.

namespace MyPlugin\Command;

...

use Bake\Command\TemplateCommand as MyPluginTemplateCommand;

class TemplateCommand extends MyPluginTemplateCommand
{
    ...
    public function bake(
        Arguments $args,
        ConsoleIo $io,
        string $template,
        $content = '',
        ?string $outputFile = null
    ): void {
        if ($outputFile === null) {
            $outputFile = $template;
        }
        if ($content === true) {
            $content = $this->getContent($args, $io, $template);
        }
        if (empty($content)) {
            $io->err("<warning>No generated content for '{$template}.php', not generating template.</warning>");

            return;
        }
        $path = $this->getTemplatePath($args);
        $filename = $path . Inflector::underscore($outputFile) . '.php';

        $io->out("\n" . sprintf('***MYPLUGIN*** Baking `%s` view template file...', $outputFile), 1, ConsoleIo::QUIET);
        $io->createFile($filename, $content, $args->getOption('force'));
    }
    ...
}

When I run bin/bake template books -t MyPlugin, I see this message without my added prefix:

Baking index view template file...

It doesn't seem to pickup my class.

Edit #4

In vendor/cakephp/cakephp/src/Console/CommandRunner.php, function run, I added var_dump:

...
$shell = $this->getCommand($io, $commands, $name);
var_dump($commands);
...

Output:

object(Cake\Console\CommandCollection)#33 (1) {
  ["commands":protected]=>
  array(87) {
    ["help"]=>
    string(32) "Cake\Console\Command\HelpCommand"
    ["version"]=>
    string(27) "Cake\Command\VersionCommand"
    ["cache clear"]=>
    string(30) "Cake\Command\CacheClearCommand"
    ["cache clear_all"]=>
    string(33) "Cake\Command\CacheClearallCommand"
    ["cache list"]=>
    string(29) "Cake\Command\CacheListCommand"
    ["completion"]=>
    string(30) "Cake\Command\CompletionCommand"
    ["i18n"]=>
    string(24) "Cake\Command\I18nCommand"
    ["i18n extract"]=>
    string(31) "Cake\Command\I18nExtractCommand"
    ["i18n init"]=>
    string(28) "Cake\Command\I18nInitCommand"
    ["plugin assets copy"]=>
    string(36) "Cake\Command\PluginAssetsCopyCommand"
    ["plugin assets remove"]=>
    string(38) "Cake\Command\PluginAssetsRemoveCommand"
    ["plugin assets symlink"]=>
    string(39) "Cake\Command\PluginAssetsSymlinkCommand"
    ["plugin load"]=>
    string(30) "Cake\Command\PluginLoadCommand"
    ["plugin loaded"]=>
    string(32) "Cake\Command\PluginLoadedCommand"
    ["plugin unload"]=>
    string(32) "Cake\Command\PluginUnloadCommand"
    ["routes check"]=>
    string(31) "Cake\Command\RoutesCheckCommand"
    ["routes"]=>
    string(26) "Cake\Command\RoutesCommand"
    ["routes generate"]=>
    string(34) "Cake\Command\RoutesGenerateCommand"
    ["schema_cache build"]=>
    string(36) "Cake\Command\SchemacacheBuildCommand"
    ["schema_cache clear"]=>
    string(36) "Cake\Command\SchemacacheClearCommand"
    ["server"]=>
    string(26) "Cake\Command\ServerCommand"
    ["console"]=>
    string(22) "App\Shell\ConsoleShell"
    ["model"]=>
    string(29) "MyPlugin\Command\ModelCommand"
    ["my_plugin.model"]=>
    string(29) "MyPlugin\Command\ModelCommand"
    ["template"]=>
    string(32) "MyPlugin\Command\TemplateCommand"
    ["my_plugin.template"]=>
    string(32) "MyPlugin\Command\TemplateCommand"
    ...
    string(25) "Bake\Command\ModelCommand"
    ["bake template"]=>
    string(28) "Bake\Command\TemplateCommand"
    ...
  }
}

In vendor/cakephp/cakephp/src/Console/CommandScanner.php, added var_dump:

public function scanPlugin(string $plugin): array
{
    if (!Plugin::isLoaded($plugin)) {
        return [];
    }
    $path = Plugin::classPath($plugin);
    $namespace = str_replace('/', '\\', $plugin);
    $prefix = Inflector::underscore($plugin) . '.';

    $commands = $this->scanDir($path . 'Command', $namespace . '\Command\\', $prefix, []);
    $shells = $this->scanDir($path . 'Shell', $namespace . '\Shell\\', $prefix, []);
    var_dump($commands);

    return array_merge($shells, $commands);
}

Output:

array(0) {
}
array(2) {
  [0]=>
  array(4) {
    ["file"]=>
    string(94) "C:\path\to\MyPlugin\src\CommandModelCommand.php"
    ["fullName"]=>
    string(15) "my_plugin.model"
    ["name"]=>
    string(5) "model"
    ["class"]=>
    string(29) "MyPlugin\Command\ModelCommand"
  }
  [1]=>
  array(4) {
    ["file"]=>
    string(97) "C:\path\to\MyPlugin\src\CommandTemplateCommand.php"
    ["fullName"]=>
    string(18) "my_plugin.template"
    ["name"]=>
    string(8) "template"
    ["class"]=>
    string(32) "MyPlugin\Command\TemplateCommand"
  }
}
...

Edit #5

I think I got it!

namespace MyPlugin\Command;

use Bake\Command\TemplateCommand as MyPluginTemplateCommand;

class TemplateCommand extends MyPluginTemplateCommand
{...}

I also moved the addition of my plugin on the last line of the bootstrap() function.

The output from the CLI now reflects the changes I made.

Edit #6

Need to figure out why it's not writing the views to the appropriate folder. It doubles up on books: src/templates/Books/Books

Edit #7

To get rid of the doubling in the path, commented out the function getTemplatePath.

Edit #8

Final solution.

The class definition used, updated Edit #5 too.

namespace MyPlugin\Command;

use Bake\Command\TemplateCommand as MyPluginTemplateCommand;

class TemplateCommand extends MyPluginTemplateCommand
{...}