问:
How to properly refuse websocket upgrade request?
Sometimes I want to refuse a http client's request to upgrade connection to websocket.

Code

(using go's Gin and gorilla/websocket framework:)

To allow upgrade:

```<code>c, err := ctl.upgrader.Upgrade(ctx.Writer, ctx.Request, nil)
err = c.WriteJSON(resp)
</code>```

To refuse upgrade (due to invalid request params):

```<code>if contentId == "" || !exists {
    // FIXME: provide response in a way that ws client can recognize & show tip?
    ctx.String(http.StatusBadRequest, "invalid or non-existing contentId")
    return
}
</code>```

Explaination: Here to refuse the upgrade I just return a http 400 code, then terminate the connection, and didn't do the upgrade at all.

The issue

The problem to refuse websocket upgrade request with about code is that, the websocket client (e.g js), can't read data (text or json) in my response.

Code - client-side (js):

```<code>ws.onerror = function (evt) {
    // TOOD: handle error, (e.g print error msg?),
    print("ERROR");
}
</code>```

It does print the "ERROR" on refuse, but after checking chrome developer tool about the evt object, can't find a way to get server response data, so I can't show tip to frontend UI with reason of refuse.

Questions

How to refuse websocket upgrade request properly, and let client be able to receive the returned reason/data ? (e.g client is js, server is go / gin / gorilla/websocket).

Is there a better way to refuse websocket upgrade request, other than return http code like 400?

答:
To reject a websocket connection, do not upgrade the connection as described in the question.
The browser API does not provide information about why the connection was rejected because the information can violate the same-origin policy.

Do the following to send an error reason back to the client application or user:

Upgrade the connection.

Send a close message with the error reason.

Close the connection.

Here's an example:

```<code>c, err := ctl.upgrader.Upgrade(ctx.Writer, ctx.Request, nil)
if err != nil {
    // TODO: handle error
}
if contentId == "" || !exists {
    c.WriteMessage(websocket.CloseMessage,
         websocket.FormatCloseMessage(websocket.ClosePolicyViolation,
         "bad content id or not exist"))
    c.Close()
    return
}
// Continue with non-error case here.
</code>```

Access the reason from the close handler in JS:

```<code>ws.onclose = function (evt) {
    if (evt.code == 1008) {  // 1008 is policy violation
       console.log(evt.reason)
    }
}
</code>```

Body:
Sometimes I want to refuse a http client's request to upgrade connection to websocket.

Code

(using go's Gin and gorilla/websocket framework:)

To allow upgrade:

c, err := ctl.upgrader.Upgrade(ctx.Writer, ctx.Request, nil)
err = c.WriteJSON(resp)

To refuse upgrade (due to invalid request params):

if contentId == "" || !exists {
    // FIXME: provide response in a way that ws client can recognize & show tip?
    ctx.String(http.StatusBadRequest, "invalid or non-existing contentId")
    return
}

Explaination: Here to refuse the upgrade I just return a http 400 code, then terminate the connection, and didn't do the upgrade at all.

The issue

The problem to refuse websocket upgrade request with about code is that, the websocket client (e.g js), can't read data (text or json) in my response.

Code - client-side (js):

ws.onerror = function (evt) {
    // TOOD: handle error, (e.g print error msg?),
    print("ERROR");
}

It does print the "ERROR" on refuse, but after checking chrome developer tool about the evt object, can't find a way to get server response data, so I can't show tip to frontend UI with reason of refuse.

Questions

How to refuse websocket upgrade request properly, and let client be able to receive the returned reason/data ? (e.g client is js, server is go / gin / gorilla/websocket).

Is there a better way to refuse websocket upgrade request, other than return http code like 400?

Body:
To reject a websocket connection, do not upgrade the connection as described in the question.
The browser API does not provide information about why the connection was rejected because the information can violate the same-origin policy.

Do the following to send an error reason back to the client application or user:

Upgrade the connection.

Send a close message with the error reason.

Close the connection.

Here's an example:

c, err := ctl.upgrader.Upgrade(ctx.Writer, ctx.Request, nil)
if err != nil {
    // TODO: handle error
}
if contentId == "" || !exists {
    c.WriteMessage(websocket.CloseMessage,
         websocket.FormatCloseMessage(websocket.ClosePolicyViolation,
         "bad content id or not exist"))
    c.Close()
    return
}
// Continue with non-error case here.

Access the reason from the close handler in JS:

ws.onclose = function (evt) {
    if (evt.code == 1008) {  // 1008 is policy violation
       console.log(evt.reason)
    }
}


来源: stackexchange

问:
Flutter: How to define notification channel in firebase_messaging package?
I am sending this json to cloud messaging (with proper headers) and want to get notification on my device, but it does not appear on my phone. I think that maybe i am missing channel id initialization for Android ?

*Additional info

If i send "notification" payload with title or body it is receiving, but i dont want to use "notification" payload. I want to have "data" payload only

```<code>{
"to" : "my device token",
"mutable_content" : true,
"content_available": true,
    "data" : {
        "content": {
            "id": 100,
            "channelKey": "basic_channel",
            "title": "Huston!\nThe eagle has landed!",
            "body": "A small step for a man, but a giant leap to Flutter's community!",
            "notificationLayout": "BigPicture",
            "largeIcon": "https://media.fstatic.com/kdNpUx4VBicwDuRBnhBrNmVsaKU=/full-fit-in/290x478/media/artists/avatar/2013/08/neil-i-armstrong_a39978.jpeg",
            "bigPicture": "https://www.dw.com/image/49519617_303.jpg",
            "showWhen": true,
            "autoCancel": true,
            "privacy": "Private"
        },
        "actionButtons": [
            {
                "key": "REPLY",
                "label": "Reply",
                "autoCancel": true,
                "buttonType":  "InputField"
            },
            {
                "key": "ARCHIVE",
                "label": "Archive",
                "autoCancel": true
            }
        ]
    }
}
</code>```

答:
As simple as this. Just put your android channel name here below and it works with a charm:

```<code>"notification": {
            "body": "Test notification",
            "title": "Test Test Test",
            "click_action": "FLUTTER_NOTIFICATION_CLICK",

            "sound": "your_custom_sound"
            "android_channel_id": "channel_id_youcreated",
},

          'to':
              "",
        },
</code>```

Sound file name is not necessary in the above given notification payload if you assigned that sound to your notification channel thru MainActivity.kt or java file. However, it is necessary for older Android versions as they will use the sound file directly. Put your file inside res/raw folder.

ContentLicense: CC BY-SA 4.0

Body:
I am sending this json to cloud messaging (with proper headers) and want to get notification on my device, but it does not appear on my phone. I think that maybe i am missing channel id initialization for Android ?

*Additional info

If i send "notification" payload with title or body it is receiving, but i dont want to use "notification" payload. I want to have "data" payload only

{
"to" : "my device token",
"mutable_content" : true,
"content_available": true,
    "data" : {
        "content": {
            "id": 100,
            "channelKey": "basic_channel",
            "title": "Huston!\nThe eagle has landed!",
            "body": "A small step for a man, but a giant leap to Flutter's community!",
            "notificationLayout": "BigPicture",
            "largeIcon": "https://media.fstatic.com/kdNpUx4VBicwDuRBnhBrNmVsaKU=/full-fit-in/290x478/media/artists/avatar/2013/08/neil-i-armstrong_a39978.jpeg",
            "bigPicture": "https://www.dw.com/image/49519617_303.jpg",
            "showWhen": true,
            "autoCancel": true,
            "privacy": "Private"
        },
        "actionButtons": [
            {
                "key": "REPLY",
                "label": "Reply",
                "autoCancel": true,
                "buttonType":  "InputField"
            },
            {
                "key": "ARCHIVE",
                "label": "Archive",
                "autoCancel": true
            }
        ]
    }
}

Body:
As simple as this. Just put your android channel name here below and it works with a charm:

"notification": {
            "body": "Test notification",
            "title": "Test Test Test",
            "click_action": "FLUTTER_NOTIFICATION_CLICK",

            "sound": "your_custom_sound"
            "android_channel_id": "channel_id_youcreated",
},

          'to':
              "",
        },

Sound file name is not necessary in the above given notification payload if you assigned that sound to your notification channel thru MainActivity.kt or java file. However, it is necessary for older Android versions as they will use the sound file directly. Put your file inside res/raw folder.


问:
How can i get a specific data from my dataset using SQL and PHPmyadmin?
I'm new to sql.
I have 3 datasets ,
patient (columns : id age Zip_Code, size, weight, sex)
blood_tests (columns : test_ID, test_date, blood_sugar, laboratory_ID, patient_ID)
laboratory (columns : id, name, Zip_code, departments)

how can i get the number of patients per center ?
i did this code but it doesnt give the number per

```<code>select DISTINCT patient_ID, laboratory_ID from patient,blood_tests where patient.id = blood_tests.patient_ID AND blood_tests.laboratory_ID = laboratory.id;
</code>```

but i don't know how to get the total number of patients per center, because some of them did more than one exam in the same center and they have done tests in many labs?

For the second question. he aks us to get the 4 tests that a specific patient carried out in a laboratory called 'NWB'.
and i did this and noticed that he is patient with and ID = 25 but how can i get that without specifying that the id is 25.

```<code>select patient_ID, laboratory.name from patient, blood_tests,laboratory where patient_ID = blood_tests.patient_ID AND blood_tests.laboratory_ID = laboratory.id HAVING laboratory.name = "NWB";
</code>```

Thank You in advance.

答:
Assuming you're using Mysql with PhpMyAdmin (from now i'll call it PMA)
You get the COUNT of patients for each laboratory using GROUP BY keyword.
You can read the (unofficial) documentation here.
Using GROUP BY you can get the count of tests for each laboratory with
SELECT laboratory_ID, COUNT(*) As num_tests FROM blood_tests WHERE 1 GROUP BY laboratory_ID;
So the query returns 2 columns one for the laboratory ID and one for the number of tests for that one.

You can see the zip code of laboratory using JOINS statements, in this case you should use INNER JOIN click here for (unofficial) documentation

Body:
I'm new to sql.
I have 3 datasets ,
patient (columns : id age Zip_Code, size, weight, sex)
blood_tests (columns : test_ID, test_date, blood_sugar, laboratory_ID, patient_ID)
laboratory (columns : id, name, Zip_code, departments)

how can i get the number of patients per center ?
i did this code but it doesnt give the number per

select DISTINCT patient_ID, laboratory_ID from patient,blood_tests where patient.id = blood_tests.patient_ID AND blood_tests.laboratory_ID = laboratory.id;

but i don't know how to get the total number of patients per center, because some of them did more than one exam in the same center and they have done tests in many labs?

For the second question. he aks us to get the 4 tests that a specific patient carried out in a laboratory called 'NWB'.
and i did this and noticed that he is patient with and ID = 25 but how can i get that without specifying that the id is 25.

select patient_ID, laboratory.name from patient, blood_tests,laboratory where patient_ID = blood_tests.patient_ID AND blood_tests.laboratory_ID = laboratory.id HAVING laboratory.name = "NWB";

Thank You in advance.


问:
How to select all nodes of a DOMDocument with a single DOMXpath expression?
What is the xpath expression to select all nodes of a document?

Given this example XML:

```<code><div class="header"/>
</code>```

I contains three nodes:
 (element), class= (attribute) and "header" (text).

```<code>$doc = new DOMDocument;
$doc->loadXml('<div class="header"/>');
$xpath = new DOMXPath($doc);
</code>```

I tried with //node():

```<code>$xpath->query('//node()');
</code>```

which returns all element nodes only (I assume because of //). Is there a way to add other nodes like attributes and textnodes in attribute values?

Additional example:

I can obtain each node by using the DOMDocument API, e.g. to obtain the text node of the attribute value:

```<code>$doc = new DOMDocument;
$doc->loadXml('<div class="header"/>');
$class = $doc->documentElement->getAttributeNode('class');
echo $class->childNodes->item(0)->nodeName;
</code>```

Which gives:

```<code>#text
</code>```

How to obtain the superset of all nodes with one xpath expression, especially including that exemplary class attribute-node child text-node?

答:
```<code>$doc = new DOMDocument;

// We don't want to bother with white spaces
$doc->preserveWhiteSpace = false;

$doc->load('book.xml');

$xpath = new DOMXPath($doc);

// We start from the root element
$query = '//book/chapter/para/informaltable/tgroup/tbody/row/entry[. =
"en"]';

$entries = $xpath->query($query);

foreach ($entries as $entry) {
     echo "Found {$entry->previousSibling->previousSibling->nodeValue}," .
         " by {$entry->previousSibling->nodeValue}\n";
}
</code>```

ContentLicense: CC BY-SA 3.0

Body:
What is the xpath expression to select all nodes of a document?

Given this example XML:

I contains three nodes:
 (element), class= (attribute) and "header" (text).

$doc = new DOMDocument;
$doc->loadXml('
');
$xpath = new DOMXPath($doc);

I tried with //node():

$xpath->query('//node()');

which returns all element nodes only (I assume because of //). Is there a way to add other nodes like attributes and textnodes in attribute values?

Additional example:

I can obtain each node by using the DOMDocument API, e.g. to obtain the text node of the attribute value:

$doc = new DOMDocument;
$doc->loadXml('
');
$class = $doc->documentElement->getAttributeNode('class');
echo $class->childNodes->item(0)->nodeName;

Which gives:

#text

How to obtain the superset of all nodes with one xpath expression, especially including that exemplary class attribute-node child text-node?


问:
With pandas, how to create a table of average ocurrences, using more than one column?
Say I have a df that looks like this:

```<code>    name  day  var_A   var_B
0   Pete  Wed      4       5
1   Luck  Thu      1      10
2   Pete  Sun     10      10
</code>```

And I want to sum var_A and var_B for every name/person and then get the average of this sum by the number of ocurrences of that name/person.

Let's take Pete for example. Sum his variables (in this case, (4+10) + (5+10) = 29), and divide this sum by the ocurrences of Pete in the df (29/2 = 14,5). And the "day" column would be eliminated, there would be only one column for the name and another for the average.
Would look like this:

```<code>>>> df.method().method()

        name   avg
    0   Pete  14.5
    1   Luck  11.0
</code>```

I've been trying to do this using groupby and other methods, but I eventually got stuck.
Any help would be appreciated.

答:
I came up with

```<code>df.groupby('name')['var_A', 'var_B'].apply(lambda g: g.stack().sum()/len(g)).rename('avg').reset_index()
</code>```

which produces the correct result, but I'm not sure it's the most elegant way.

Body:
Say I have a df that looks like this:

    name  day  var_A   var_B
0   Pete  Wed      4       5
1   Luck  Thu      1      10
2   Pete  Sun     10      10

And I want to sum var_A and var_B for every name/person and then get the average of this sum by the number of ocurrences of that name/person.

Let's take Pete for example. Sum his variables (in this case, (4+10) + (5+10) = 29), and divide this sum by the ocurrences of Pete in the df (29/2 = 14,5). And the "day" column would be eliminated, there would be only one column for the name and another for the average.
Would look like this:

>>> df.method().method()

        name   avg
    0   Pete  14.5
    1   Luck  11.0

I've been trying to do this using groupby and other methods, but I eventually got stuck.
Any help would be appreciated.

Body:
I came up with

df.groupby('name')['var_A', 'var_B'].apply(lambda g: g.stack().sum()/len(g)).rename('avg').reset_index()

which produces the correct result, but I'm not sure it's the most elegant way.


问:
Why is the BigInteger.ModPow function in C# much slower than that in Java?
I have found that the BigInteger.ModPow function in C# is very slow compared to the BigInteger.modPow function in Java. This makes me reluctant to use C# to implement functions that perform modular exponentiation.

I have written a test program to prove it.

C#

static void Main(string[] args)
{
    BigInteger num = BigInteger.Parse("444266014606582911577255360081280172978907874637194279031281180366057");
    BigInteger m = 2;
    Console.WriteLine("Start multiply.");
    Stopwatch stopwatch = Stopwatch.StartNew();
    for (int i = 3; i <= 200000; i++)
        m *= i;
    stopwatch.Stop();
    Console.WriteLine(stopwatch.ElapsedMilliseconds);
    stopwatch.Reset();
    Console.WriteLine("Start mod pow.");
    stopwatch.Start();
    for (int i = 0; i < 10; i++)
        BigInteger.ModPow(3, m, num);
    stopwatch.Stop();
    Console.WriteLine(stopwatch.ElapsedMilliseconds);
}
```
<p>An equivalent program in <strong>Java</strong></p>
<pre class="lang-java prettyprint-override"><code>public static void main(String[] args) {
    BigInteger num = new BigInteger("444266014606582911577255360081280172978907874637194279031281180366057");
    BigInteger m = BigInteger.TWO;
    System.out.println("Start multiply.");
    long startTime = System.currentTimeMillis();
    for (int i = 3; i <= 200000; i++)
        m = m.multiply(BigInteger.valueOf(i));
    System.out.println(System.currentTimeMillis() - startTime);
    System.out.println("Start mod pow.");
    startTime = System.currentTimeMillis();
    for (int i = 0; i < 10; i++)
        BigInteger.valueOf(3).modPow(m, num);
    System.out.println(System.currentTimeMillis() - startTime);
}
</code>```

The program consists of 2 parts:

Calculate 200000! to produce a very large number m.

Calculate 3 ^ m mod num 10 times.

You may change the numbers or the loop count to try finding different results.

Here is an execution result on my computer.

Specifications

CPU: Intel(R) Core(TM) i3-8100 CPU @ 3.60GHz

.Net Version: .NET 6.0.102

Java Version: 17.0.1

C#

```
Start multiply.
19443
Start mod pow.
35292
```

Java

```
Start multiply.
14668
Start mod pow.
3462
```

It shows that the BigInteger.ModPow function in C# is about 10 times slower than that in Java. Does anyone know the reason? Is that a bug?

答:
You can take a look at the .Net implémentation here and the java ones here.

It appears that the java ones was more heavily studied.

Body:
I have found that the BigInteger.ModPow function in C# is very slow compared to the BigInteger.modPow function in Java. This makes me reluctant to use C# to implement functions that perform modular exponentiation.

I have written a test program to prove it.

C#

static void Main(string[] args)
{
    BigInteger num = BigInteger.Parse("444266014606582911577255360081280172978907874637194279031281180366057");
    BigInteger m = 2;
    Console.WriteLine("Start multiply.");
    Stopwatch stopwatch = Stopwatch.StartNew();
    for (int i = 3; i <= 200000; i++)
        m *= i;
    stopwatch.Stop();
    Console.WriteLine(stopwatch.ElapsedMilliseconds);
    stopwatch.Reset();
    Console.WriteLine("Start mod pow.");
    stopwatch.Start();
    for (int i = 0; i < 10; i++)
        BigInteger.ModPow(3, m, num);
    stopwatch.Stop();
    Console.WriteLine(stopwatch.ElapsedMilliseconds);
}

An equivalent program in Java

public static void main(String[] args) {
    BigInteger num = new BigInteger("444266014606582911577255360081280172978907874637194279031281180366057");
    BigInteger m = BigInteger.TWO;
    System.out.println("Start multiply.");
    long startTime = System.currentTimeMillis();
    for (int i = 3; i <= 200000; i++)
        m = m.multiply(BigInteger.valueOf(i));
    System.out.println(System.currentTimeMillis() - startTime);
    System.out.println("Start mod pow.");
    startTime = System.currentTimeMillis();
    for (int i = 0; i < 10; i++)
        BigInteger.valueOf(3).modPow(m, num);
    System.out.println(System.currentTimeMillis() - startTime);
}

The program consists of 2 parts:

Calculate 200000! to produce a very large number m.

Calculate 3 ^ m mod num 10 times.

You may change the numbers or the loop count to try finding different results.

Here is an execution result on my computer.

Specifications

CPU: Intel(R) Core(TM) i3-8100 CPU @ 3.60GHz

.Net Version: .NET 6.0.102

Java Version: 17.0.1

C#

Start multiply.
19443
Start mod pow.
35292

Java

Start multiply.
14668
Start mod pow.
3462

It shows that the BigInteger.ModPow function in C# is about 10 times slower than that in Java. Does anyone know the reason? Is that a bug?


问:
Where to tell the F# compiler to locate an assembly?
I'm trying to compile an F# program that wants to use arbitrary precision rational numbers. The source code contains

```<code>open MathNet.Numerics
</code>```

and MathNet.Numerics and MathNet.Numerics.FSharp are installed in such a way that Visual Studio is happy. Now I'm trying to compile the program from the command line using fsc directly (in order to have more control over what's going on). Clearly, the compiler needs to be told about the referenced assembly.

I've tried

```<code>fsc -r:MathNet.Numerics ...
</code>```

but it says

error FS0082: Could not resolve this reference. Could not locate the assembly "MathNet.Numerics". Check to make sure the assembly exists on disk. If this reference is required by your code, you may get compilation errors. (Code=MSB3245)

Presumably I need to use some other option that tells fsc where to look for the assembly in question. Which option should I use, and what location should I supply? (There are quite a few copies of various versions of MathNet.Numerics.dll on the machine; it's not clear which should be regarded as canonical for this purpose.)

答:
You can specify the full path to the assembly with -r, not just the file name. For me, it looks like this:

-r:C:\Users\MyName\.nuget\packages\mathnet.numerics\4.15.0\lib\netstandard2.0\MathNet.Numerics.dll
```

Alternatively, you can use -I:folder-name to specify a directory to be searched for assemblies that are referenced.

These compiler options are documented here.

Body:
I'm trying to compile an F# program that wants to use arbitrary precision rational numbers. The source code contains

open MathNet.Numerics

and MathNet.Numerics and MathNet.Numerics.FSharp are installed in such a way that Visual Studio is happy. Now I'm trying to compile the program from the command line using fsc directly (in order to have more control over what's going on). Clearly, the compiler needs to be told about the referenced assembly.

I've tried

fsc -r:MathNet.Numerics ...

but it says

error FS0082: Could not resolve this reference. Could not locate the assembly "MathNet.Numerics". Check to make sure the assembly exists on disk. If this reference is required by your code, you may get compilation errors. (Code=MSB3245)

Presumably I need to use some other option that tells fsc where to look for the assembly in question. Which option should I use, and what location should I supply? (There are quite a few copies of various versions of MathNet.Numerics.dll on the machine; it's not clear which should be regarded as canonical for this purpose.)

Body:
You can specify the full path to the assembly with -r, not just the file name. For me, it looks like this:

-r:C:\Users\MyName\.nuget\packages\mathnet.numerics\4.15.0\lib\netstandard2.0\MathNet.Numerics.dll

Alternatively, you can use -I:folder-name to specify a directory to be searched for assemblies that are referenced.

These compiler options are documented here.


问:
Find all words with 3 letters with regex
I'm trying to find all words with 3 letters in a string.

So in this list

```<code>cat monkey dog mouse
</code>```

I only want

```<code>cat dog
</code>```

This is my expression:

```<code>^[a-zA-Z]{3}$
</code>```

I tested it with different online regex tester, but none of them matched my expression.

答:
This worked for me.

```<code>grep -e "\b...\b" all-words.txt
</code>```

This works too:

```<code>grep -E "\b.{3}\b" all-words.txt
</code>```

Body:
I'm trying to find all words with 3 letters in a string.

So in this list

cat monkey dog mouse

I only want

cat dog

This is my expression:

^[a-zA-Z]{3}$

I tested it with different online regex tester, but none of them matched my expression.

Body:
This worked for me.

grep -e "\b...\b" all-words.txt

This works too:

grep -E "\b.{3}\b" all-words.txt


问:
sendPoll to Telegram from Google Sheets App Script with open_period time and reply_markup buttons
I've already this code working to send Polls from a Google Sheet, but I want to add the open_period for one day, and if it is possible add the reply_markup option to add buttons to choose the answer instead of a list, and plus, how can I read the JSON possible answers form a cell and not defined by var answers = ['✌ VOY', 'NO PUEDO IR', 'POSIBLEMENTE SI VAYA'];?

```<code>function sendPoll() {
var sheet = SpreadsheetApp.getActive().getSheetByName("DATA");
var question = sheet.getRange("B1").getValues();
//var answers = sheet.getRange("B2").getValues(); //How can I read the poll answers from a cell?
var answers = ['✌ VOY', 'NO PUEDO IR', 'POSIBLEMENTE SI VAYA'];
var bot = sheet.getRange("B3").getValues();
var chatId = sheet.getRange("B4").getValues();

    var payload = {
      "method": 'sendPoll',
      "chat_id": String(chatId),
      "question": String(question),
      "parse_mode": 'HTML',
      "options": JSON.stringify(answers),
      "is_anonymous": false,
      "type": 'regular',
      "allows_multiple_answers": false,
      "open_period": 0
    }
    var data = {
        "method": "post",
        "payload": payload,
        "muteHttpExceptions":true
    };

  var response = UrlFetchApp.fetch('https://api.telegram.org/bot' + bot + '/', data);
  Logger.log(response);
};
</code>```

答:
You can use variable for each option and use them in answers . I have little modify this code and this is working.</p>
```<code>function sendPoll() {
var sheet = SpreadsheetApp.getActive().getSheetByName("DATA");
var question = sheet.getRange("B1").getValues();
var option1 = sheet.getRange("C1").getValues();
var option2 = sheet.getRange("C2").getValues();
var option3 = sheet.getRange("C3").getValues();
var option4 = sheet.getRange("C4").getValues();
var answers = [''+option1+'', ''+option2+'', ''+option3+'', ''+option4+''];
var bot = sheet.getRange("B3").getValues();
var chatId = sheet.getRange("B4").getValues();
var explanation = sheet.getRange("B4").getValues();

    var payload = {
      "method": 'sendPoll',
      "chat_id": String(chatId),
      "question": String(question),
      "parse_mode": 'HTML',
      "options": JSON.stringify(answers),
      "is_anonymous": true,
      "type": 'quiz',
      "allows_multiple_answers": false,
      "open_period": 0,
      "correct_option_id": 1,
      "explanation": String(explanation)
    }
    var data = {
        "method": "post",
        "payload": payload,
        "muteHttpExceptions":true
    };

  var response = UrlFetchApp.fetch('https://api.telegram.org/bot' + bot + '/', data);
  Logger.log(response);
};
</code>```

Body:
I've already this code working to send Polls from a Google Sheet, but I want to add the open_period for one day, and if it is possible add the reply_markup option to add buttons to choose the answer instead of a list, and plus, how can I read the JSON possible answers form a cell and not defined by var answers = ['✌ VOY', 'NO PUEDO IR', 'POSIBLEMENTE SI VAYA'];?

function sendPoll() {
var sheet = SpreadsheetApp.getActive().getSheetByName("DATA");
var question = sheet.getRange("B1").getValues();
//var answers = sheet.getRange("B2").getValues(); //How can I read the poll answers from a cell?
var answers = ['✌ VOY', 'NO PUEDO IR', 'POSIBLEMENTE SI VAYA'];
var bot = sheet.getRange("B3").getValues();
var chatId = sheet.getRange("B4").getValues();

    var payload = {
      "method": 'sendPoll',
      "chat_id": String(chatId),
      "question": String(question),
      "parse_mode": 'HTML',
      "options": JSON.stringify(answers),
      "is_anonymous": false,
      "type": 'regular',
      "allows_multiple_answers": false,
      "open_period": 0
    }
    var data = {
        "method": "post",
        "payload": payload,
        "muteHttpExceptions":true
    };

  var response = UrlFetchApp.fetch('https://api.telegram.org/bot' + bot + '/', data);
  Logger.log(response);
};

Body:
You can use variable for each option and use them in answers . I have little modify this code and this is working.

function sendPoll() {
var sheet = SpreadsheetApp.getActive().getSheetByName("DATA");
var question = sheet.getRange("B1").getValues();
var option1 = sheet.getRange("C1").getValues();
var option2 = sheet.getRange("C2").getValues();
var option3 = sheet.getRange("C3").getValues();
var option4 = sheet.getRange("C4").getValues();
var answers = [''+option1+'', ''+option2+'', ''+option3+'', ''+option4+''];
var bot = sheet.getRange("B3").getValues();
var chatId = sheet.getRange("B4").getValues();
var explanation = sheet.getRange("B4").getValues();

    var payload = {
      "method": 'sendPoll',
      "chat_id": String(chatId),
      "question": String(question),
      "parse_mode": 'HTML',
      "options": JSON.stringify(answers),
      "is_anonymous": true,
      "type": 'quiz',
      "allows_multiple_answers": false,
      "open_period": 0,
      "correct_option_id": 1,
      "explanation": String(explanation)
    }
    var data = {
        "method": "post",
        "payload": payload,
        "muteHttpExceptions":true
    };

  var response = UrlFetchApp.fetch('https://api.telegram.org/bot' + bot + '/', data);
  Logger.log(response);
};


问:
Having trouble with the data from Firestore coming back undefined
I get back data from the console.log results but the useState hook setDocuments is returns undefined in the following Code:

```<code>import { useEffect, useState, useRef } from "react"
import { projectFirestore } from "../firebase/config"

export const useCollection = (collection, _query, _orderBy) => {
  const [documents, setDocuments] = useState(null)
  const [error, setError] = useState(null)

  // if we don't use a ref --> infinite loop in useEffect
  // _query is an array and is "different" on every function call
  const query = useRef(_query).current
  const orderBy = useRef(_orderBy).current

  useEffect(() => {
    let ref = projectFirestore.collection(collection)

    if (query) {
      ref = ref.where(...query)
    }
    if (orderBy) {
      ref = ref.orderBy(...orderBy)
    }

    const unsubscribe = ref.onSnapshot(snapshot => {
      let results = []
      snapshot.docs.forEach(doc => {
        console.log(doc)
        results.push({...doc.data(), id: doc.id})
      });
      console.log(results)
      // update state
      setDocuments(results)

      setError(null)
    }, error => {
      console.log(error)
      setError('could not fetch the data')
    })

    // unsubscribe on unmount
    return () => unsubscribe()

  }, [collection, query, orderBy])

  return { documents, error}
}
</code>```

The code above is imported into a page as a useCollection hook to call data from firestore 8.

答:
You just have to remove "doc" from snapshot.doc.forEach and you can get your data by forEach function

```<code>const unsubscribe = ref.onSnapshot(snapshot => {
  ....
  snapshot.forEach(doc => {
    console.log(doc)
    results.push({...doc.data(), id: doc.id})
  });
  ...
}, error => {
  ...
})
</code>```

Body:
I get back data from the console.log results but the useState hook setDocuments is returns undefined in the following Code:

import { useEffect, useState, useRef } from "react"
import { projectFirestore } from "../firebase/config"

export const useCollection = (collection, _query, _orderBy) => {
  const [documents, setDocuments] = useState(null)
  const [error, setError] = useState(null)

  // if we don't use a ref --> infinite loop in useEffect
  // _query is an array and is "different" on every function call
  const query = useRef(_query).current
  const orderBy = useRef(_orderBy).current

  useEffect(() => {
    let ref = projectFirestore.collection(collection)

    if (query) {
      ref = ref.where(...query)
    }
    if (orderBy) {
      ref = ref.orderBy(...orderBy)
    }

    const unsubscribe = ref.onSnapshot(snapshot => {
      let results = []
      snapshot.docs.forEach(doc => {
        console.log(doc)
        results.push({...doc.data(), id: doc.id})
      });
      console.log(results)
      // update state
      setDocuments(results)

      setError(null)
    }, error => {
      console.log(error)
      setError('could not fetch the data')
    })

    // unsubscribe on unmount
    return () => unsubscribe()

  }, [collection, query, orderBy])

  return { documents, error}
}

The code above is imported into a page as a useCollection hook to call data from firestore 8.

Body:
You just have to remove "doc" from snapshot.doc.forEach and you can get your data by forEach function

const unsubscribe = ref.onSnapshot(snapshot => {
  ....
  snapshot.forEach(doc => {
    console.log(doc)
    results.push({...doc.data(), id: doc.id})
  });
  ...
}, error => {
  ...
})


问:
Expression (!a && b) || (!a && c) || (b && c) with minimum gates
I want to create a logical circuit

(!a && b) || (!a && c) || (b && c)

using as few logical gates (~ a nand b) nand NOT, AND, OR, NAND, NOR, XOR, NXOR as possible. The gate types can be mixxed. I have found some online calculators that can convert the above expression to NANDs  only like

(!a nand b) nand (!a nand c) nand (b nand c)

But I wonder if there is a way to do it by using less than four gates.

答:
It seems like it cannot be minimized more than this: a'b + c(a' + b) or can even be written as follows a'(b + c) + bc

which is actually identical to a'b  + a'c + bc (has same truth table).


问:
Is it safe to delete the pack files from .git/objects/?
I'm now planning to archive/deprecate a repository and move it to an external drive. However, some large pack files in .git/objects/pack could not be transferred because they were larger than 4GB. I'm aware that directly deleting the pack files would rewrite the history, but I'm wondering whether it is fine to just remove the files if I am sure that I'm not going to retrieve any files from the history in the future. Are there any other drawbacks of directly removing the whole pack folder? I assume that other files in the repo won't be influenced, but just their backups. Is this correct?

答:
If you do that, you'll make the whole thing useless as a git repo, in which case you might as well remove all of .git.

If your concern is files over 4GiB (presumably because of FAT filesystems), how about using git repack -ad --max-pack-size=3G, which will rewrite all of the objects into new packs, ensuring that none of the pack files is too large?


问:
sas proc means. Fill in gaps

was wondering if anyone knows how to fill in the missing boxes with the categories. Also is it possible to format proc mean generated values like mean and median? Was trying to add a dollar $ sign to it using the dollar infomat.

```<code>title1   height= 0.25in  'Total Medical Expenditures by Sex, Age and Smoking Status';
title2   height= 0.15in  'U.S Adults, Medical Expenditure Panel Survey 2018';
proc means data=mepsUse n mean median std maxdec=0 ;
 var   totexp18;
 class sex ageGrp currSmoke;
 format sex MaleFemale. ageGrp AgeCategory. currSmoke Smoker.;
run;
</code>```

答:
I think you want to create a data set.  For example.

```<code>proc means data=sashelp.class stackods completetypes;
   ods output summary=classsummary;
   class sex age;
   var height weight;
   run;
proc print;
   run;
</code>```

Title: sas proc means. Fill in gaps

Body:
was wondering if anyone knows how to fill in the missing boxes with the categories. Also is it possible to format proc mean generated values like mean and median? Was trying to add a dollar $ sign to it using the dollar infomat.

title1   height= 0.25in  'Total Medical Expenditures by Sex, Age and Smoking Status';
title2   height= 0.15in  'U.S Adults, Medical Expenditure Panel Survey 2018';
proc means data=mepsUse n mean median std maxdec=0 ;
 var   totexp18;
 class sex ageGrp currSmoke;
 format sex MaleFemale. ageGrp AgeCategory. currSmoke Smoker.;
run;

Body:
I think you want to create a data set.  For example.

proc means data=sashelp.class stackods completetypes;
   ods output summary=classsummary;
   class sex age;
   var height weight;
   run;
proc print;
   run;


问:
C# AJAX reloading the form
I'm learning C# MVC and now creating a project.
I have a problem with understanding AJAX - I can't understand why it doesn't work. After clicking the save button the form is reloading (?). After the second click, the code goes to SearchRouts(). But then - just nothing happens. Neither code from success, nor from error block (I set simple alerts to check it). It looks like the form just reloads (?). I can't figure out what's happening.
I think it is something with the end of SearchRoutes() - should I send the response in another way?
Thank you for your help.

Here is my code:

Index.cs.html:

```<code><form id="search_form" method="post">
    <label class="search__header">Długość: </label></br>
    <div class="search__options">
        <select class="search__select" name="search_len" id="search_len" multiple>
            <option value="len1">0-100 km</option>
            <option value="len2">100-150 km</option>
            <option value="len3">150-300 km</option>
            <option value="len4">+300 km</option>
        </select>
    </div>
    <label class="search__header">Difficulty: </label></br>
    <div class="search__options">
        <select class="search__select" name="search_dif" id="search_dif" multiple>
            <option value="easy">Easy</option>
            <option value="medium">Medium</option>
            <option value="hard">Hard</option>
        </select>
    </div>
    <label class="search__header">Pavement: </label></br>
    <div class="search__options">
        <select class="search__select" name="search_pav" id="search_pav" multiple>
            <option value="asphalt">Asphalt</option>
            <option value="forest">Forest</option>
            <option value="mix">Mix</option>
        </select>
    </div>
    <div class="search_options search__options--submit">
        <img class="search__img" src="img/compass.png">
        <button class="panel__button panel__button--submit" id="search_submit" type="submit">Search</button>
    </div>
</form>
</code>```

search.js:

```<code>    $("#search_submit").on("click", function () {
        console.log("SUBMIT CLICKED!");
        var search_obj = {}
        search_obj.Length = $("#search_len").val()[0];
        search_obj.Difficulty = $('#search_dif').val()[0];
        search_obj.Pavement = $('#search_pav').val()[0];
        console.log(search_obj);
        alert("ALERT!");

        $.ajax({
            type: "POST",
            url: '/User/SearchRoutes',
            data: JSON.stringify(search_obj),
            dataType: "json",
            contentType: "application/json; charset=utf-8",
            success: function (response) {
                alert("Success!");
                console.log(response);
            },
            error: function (response) {
                alert("Error. Try again.");
            }
        });

    });
</code>```

UserController.cs:

```<code>    public ActionResult SearchRoutes([FromBody] JsonSearch search)
            {
                double min = 0;
                double max = 1000;
                if(search.Length=="len1")
                {
                    max = 100;
                }
                else if(search.Length=="len2") {
                    min = 100;
                    max = 150;
                }
                else if(search.Length=="len3")
                {
                    min = 150;
                    max = 300;
                }
                else
                {
                    min = 300;
                }
                var list = _userService.FindRoutes(min, max, search.Difficulty, search.Pavement);  // returns C# list of routes objects from database
                var json = JsonSerializer.Serialize(list);
                return Json(json);
            }
</code>```

答:
In the javascript function call use

```<code>$("#search_submit").on("click", function (e) {
    console.log("SUBMIT CLICKED!");
    e.preventDefault();
    ...
</code>```

To skip the reload event after submit is pressed.

Title: C# AJAX reloading the form

Body:
I'm learning C# MVC and now creating a project.
I have a problem with understanding AJAX - I can't understand why it doesn't work. After clicking the save button the form is reloading (?). After the second click, the code goes to SearchRouts(). But then - just nothing happens. Neither code from success, nor from error block (I set simple alerts to check it). It looks like the form just reloads (?). I can't figure out what's happening.
I think it is something with the end of SearchRoutes() - should I send the response in another way?
Thank you for your help.

Here is my code:

Index.cs.html:

<form id="search_form" method="post">
    Długość:

        <select class="search__select" name="search_len" id="search_len" multiple>
            <option value="len1">0-100 km</option>
            <option value="len2">100-150 km</option>
            <option value="len3">150-300 km</option>
            <option value="len4">+300 km</option>
        </select>

    Difficulty:

        <select class="search__select" name="search_dif" id="search_dif" multiple>
            <option value="easy">Easy</option>
            <option value="medium">Medium</option>
            <option value="hard">Hard</option>
        </select>

    Pavement:

        <select class="search__select" name="search_pav" id="search_pav" multiple>
            <option value="asphalt">Asphalt</option>
            <option value="forest">Forest</option>
            <option value="mix">Mix</option>
        </select>

        <button class="panel__button panel__button--submit" id="search_submit" type="submit">Search</button>

</form>

search.js:

    $("#search_submit").on("click", function () {
        console.log("SUBMIT CLICKED!");
        var search_obj = {}
        search_obj.Length = $("#search_len").val()[0];
        search_obj.Difficulty = $('#search_dif').val()[0];
        search_obj.Pavement = $('#search_pav').val()[0];
        console.log(search_obj);
        alert("ALERT!");

        $.ajax({
            type: "POST",
            url: '/User/SearchRoutes',
            data: JSON.stringify(search_obj),
            dataType: "json",
            contentType: "application/json; charset=utf-8",
            success: function (response) {
                alert("Success!");
                console.log(response);
            },
            error: function (response) {
                alert("Error. Try again.");
            }
        });

    });

UserController.cs:

    public ActionResult SearchRoutes([FromBody] JsonSearch search)
            {
                double min = 0;
                double max = 1000;
                if(search.Length=="len1")
                {
                    max = 100;
                }
                else if(search.Length=="len2") {
                    min = 100;
                    max = 150;
                }
                else if(search.Length=="len3")
                {
                    min = 150;
                    max = 300;
                }
                else
                {
                    min = 300;
                }
                var list = _userService.FindRoutes(min, max, search.Difficulty, search.Pavement);  // returns C# list of routes objects from database
                var json = JsonSerializer.Serialize(list);
                return Json(json);
            }

Body:
In the javascript function call use

$("#search_submit").on("click", function (e) {
    console.log("SUBMIT CLICKED!");
    e.preventDefault();
    ...

To skip the reload event after submit is pressed.


问:
need help for developing android restaurant menu application
I want to develop restaurant menu application
functions: application contains list of items available in restaurant. waiter takes order from customer by selecting various items in the list. On submitting order it goes to chef,who has android device with him, he will ack the requested order.

i want to simulate this app on emulator, i have designed some basic interface. problems is that i want to transfer selected item data to other application running on other emulator,in short communication between two application running on different device. What should i do ? as far as my knowledge AIDL feature of android facilitates common between two app running on the same device.
thanks!!

答: You can use Bluetooth or email the order from one device to another.</p>


问:
White space outside html on mobile Safari when keyboard is open
I have a very weird bug in my JavaScript library on mobile Safari, that I've tried to reproduce with a simple example:

I have basic css and html:

html,
body {
    margin: 0;
    padding: 0;
    font-family: monospace;
}
body {
  min-height: 100vh;
  /* mobile viewport bug fix */
  min-height: -webkit-fill-available;
}
html {
  height: -webkit-fill-available;
}
#term {
    background: black;
    color: #ccc;
    height: 100%;
}
h1 {
    margin: 0;
    font-weight: normal;
}
```
<p><em>html</em>:</p>
<pre class="lang-html prettyprint-override"><code>    ...
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
</head>
<body>
  <div id="term" contenteditable>
    <h1>HELLO Mobile</h1>
    ...
</code>```

and when I open the website on mobile Safari and open the virtual keyboard, I can scroll down outside of the content.

Here is the screenshot from BrowserStack when I hover over body, I'm not able to hover over html to highlight it.

Does anybody know how to fix this issue? It looks like a basic page.

Here is the link to the website: https://terminal.jcubic.pl/mobile.html

As you can see from the code I've tried to fix the issue by adding:

```<code>-webkit-fill-available
</code>```

Found in an article: CSS fix for 100vh in mobile WebKit by Chris Coyier. But it doesn't make any change.

Is there a way to get rid of that white space, it seems that even CodePen has this issue. Is it a bug in Mobile Safari, is there a hack to fix it?

EDIT:

I think that this is a long-standing issue and Apple doesn't care how miserable users and developers are. Safari on iOS scrolls beyond  element when virtual keyboard is opened

答:
Have you tried:

body {
margin: 0 auto;
}
```

Body:
I have a very weird bug in my JavaScript library on mobile Safari, that I've tried to reproduce with a simple example:

I have basic css and html:

html,
body {
    margin: 0;
    padding: 0;
    font-family: monospace;
}
body {
  min-height: 100vh;
  /* mobile viewport bug fix */
  min-height: -webkit-fill-available;
}
html {
  height: -webkit-fill-available;
}
#term {
    background: black;
    color: #ccc;
    height: 100%;
}
h1 {
    margin: 0;
    font-weight: normal;
}

html:

    ...
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />

HELLO Mobile

    ...

and when I open the website on mobile Safari and open the virtual keyboard, I can scroll down outside of the content.

Here is the screenshot from BrowserStack when I hover over body, I'm not able to hover over html to highlight it.

Does anybody know how to fix this issue? It looks like a basic page.

Here is the link to the website: https://terminal.jcubic.pl/mobile.html

As you can see from the code I've tried to fix the issue by adding:

-webkit-fill-available

Found in an article: CSS fix for 100vh in mobile WebKit by Chris Coyier. But it doesn't make any change.

Is there a way to get rid of that white space, it seems that even CodePen has this issue. Is it a bug in Mobile Safari, is there a hack to fix it?

EDIT:

I think that this is a long-standing issue and Apple doesn't care how miserable users and developers are. Safari on iOS scrolls beyond  element when virtual keyboard is opened


问:
Static Comparison of Record Layouts
I have two records, some fields of which need to be in the same positions within each record. Although this has been heavily commented in the code, it is possible that, in 10 years time, a programmer may change one of the records without changing the other and I would like to create a static check that this has not occurred.

I can create an "active" check in a procedure or function as follows:

```<code>
procedure Main is

    type SimpleRecord1 is record
        FirstItem  : Integer;
        SecondItem : Boolean;
        ThirdItem  : Integer;
        DoNotCare  : Float;
    end record;

    type SimpleRecord2 is record
        Foo        : Integer;
        Bar        : Boolean;
        Baz        : Integer;
        Rfc3092    : Boolean;
    end record;

    MyRecord1 : SimpleRecord1;
    MyRecord2 : SimpleRecord2;
begin
    Pragma Assert ((MyRecord1.FirstItem'Position = MyRecord2.Foo'Position) and
                   (MyRecord1.SecondItem'Position = MyRecord2.Bar'Position) and
                   (MyRecord1.ThirdItem'Position = MyRecord2.Baz'Position));

    Put_Line ("The assert didn't fire");

end Main;
</code>```

I am concerned that the first three vairiables have the same offsets within the two records. In the real code there are dozens of other variables within each record which are not the same between the records.

However, I would really like this to be a check, not on instances of the records (MyRecord1, MyRecord2), but on the records themselves (SimpleRecord1, SimpleRecord2). Then it could be placed in the .ads file where the records are defined.

SimpleRecord1.FirstItem'Position

is illegal. Is there a way to create a check without having to make instances and put the code into a function or procedure?

答:
I would do this - especially if you are going to go with Address Overlays and/or Unchecked_Conversion

```<code>-----------------------------------------------------------------------------

   type Header_Record is
      record
         First_Item  : Integer;
         Second_Item : Boolean;
         Third_item  : Integer;
      end record
     with Convention => C;

   for Header_Record use
      record
         First_Item  at 0 range  0 .. 31;
         Second_Item at 0 range 32 .. 47;
         Third_Item  at 0 range 48 .. 79;
      end record;

-----------------------------------------------------------------------------

   type Item_Record_1 is
      record
         Header    : Header_Record;
         DoNotCare : Float;
      end record
     with Convention => C;

   for Item_Record_1 use
      record
         Header    at 0 range  0 .. 79;
         DoNotCare at 0 range 80 .. 111;
      end record;

--------------------------------------------------------------------------------

   type Item_Record2 is
      record
         Header : Header_Record;
         Rfc3092 : Boolean;
      end record
     with Convention => C;

   for Item_Record2 use
      record
         Header  at 0 range  0 .. 79;
         Rfc3092 at 0 range 80 .. 95;
      end record;

-----------------------------------------------------------------------------
</code>```

Here, we are specifying the exact bit layout. It's a bit of pain that you'll need to use one level of indirection ie

```<code>Item_Record1.Header.First_Item
</code>```

However, this should work. Also, always remember to use

```<code>Convention => C
</code>```

Since Ada record layouts and C struct layouts may vary considerably - which is to be expected, given Ada's rich semantics.

EDIT: In response to portability issues. Although, the OP did not specify that it must be portable, it's still no problem ...

```<code>   with Interfaces.C;

   subtype int is Interfaces.C.int;

   type Header_Record is
      record
         First_Item  : Interfaces.C.int;
         Second_Item : Interfaces.C.int; --bool?
         Third_item  : Interfaces.C.int;
      end record
     with Convention => C;

   -- Exact values very likely to be different, for demo only
   for Header_Record use
      record
         First_Item  at 0 range  0 .. int'Size;
         Second_Item at 0 range  int'Size + 1 .. int'Size * 2;
         Third_Item  at 0 range  int'Size * 2 + 1 .. int'Size * 3;
      end record;
</code>```

Title: Static Comparison of Record Layouts

Body:
I have two records, some fields of which need to be in the same positions within each record. Although this has been heavily commented in the code, it is possible that, in 10 years time, a programmer may change one of the records without changing the other and I would like to create a static check that this has not occurred.

I can create an "active" check in a procedure or function as follows:

procedure Main is

    type SimpleRecord1 is record
        FirstItem  : Integer;
        SecondItem : Boolean;
        ThirdItem  : Integer;
        DoNotCare  : Float;
    end record;

    type SimpleRecord2 is record
        Foo        : Integer;
        Bar        : Boolean;
        Baz        : Integer;
        Rfc3092    : Boolean;
    end record;

    MyRecord1 : SimpleRecord1;
    MyRecord2 : SimpleRecord2;
begin
    Pragma Assert ((MyRecord1.FirstItem'Position = MyRecord2.Foo'Position) and
                   (MyRecord1.SecondItem'Position = MyRecord2.Bar'Position) and
                   (MyRecord1.ThirdItem'Position = MyRecord2.Baz'Position));

    Put_Line ("The assert didn't fire");

end Main;

I am concerned that the first three vairiables have the same offsets within the two records. In the real code there are dozens of other variables within each record which are not the same between the records.

However, I would really like this to be a check, not on instances of the records (MyRecord1, MyRecord2), but on the records themselves (SimpleRecord1, SimpleRecord2). Then it could be placed in the .ads file where the records are defined.

SimpleRecord1.FirstItem'Position

is illegal. Is there a way to create a check without having to make instances and put the code into a function or procedure?

Body:
I would do this - especially if you are going to go with Address Overlays and/or Unchecked_Conversion

-----------------------------------------------------------------------------

   type Header_Record is
      record
         First_Item  : Integer;
         Second_Item : Boolean;
         Third_item  : Integer;
      end record
     with Convention => C;

   for Header_Record use
      record
         First_Item  at 0 range  0 .. 31;
         Second_Item at 0 range 32 .. 47;
         Third_Item  at 0 range 48 .. 79;
      end record;

-----------------------------------------------------------------------------

   type Item_Record_1 is
      record
         Header    : Header_Record;
         DoNotCare : Float;
      end record
     with Convention => C;

   for Item_Record_1 use
      record
         Header    at 0 range  0 .. 79;
         DoNotCare at 0 range 80 .. 111;
      end record;

--------------------------------------------------------------------------------

   type Item_Record2 is
      record
         Header : Header_Record;
         Rfc3092 : Boolean;
      end record
     with Convention => C;

   for Item_Record2 use
      record
         Header  at 0 range  0 .. 79;
         Rfc3092 at 0 range 80 .. 95;
      end record;

-----------------------------------------------------------------------------

Here, we are specifying the exact bit layout. It's a bit of pain that you'll need to use one level of indirection ie

Item_Record1.Header.First_Item

However, this should work. Also, always remember to use

Convention => C

Since Ada record layouts and C struct layouts may vary considerably - which is to be expected, given Ada's rich semantics.

EDIT: In response to portability issues. Although, the OP did not specify that it must be portable, it's still no problem ...

   with Interfaces.C;

   subtype int is Interfaces.C.int;

   type Header_Record is
      record
         First_Item  : Interfaces.C.int;
         Second_Item : Interfaces.C.int; --bool?
         Third_item  : Interfaces.C.int;
      end record
     with Convention => C;

   -- Exact values very likely to be different, for demo only
   for Header_Record use
      record
         First_Item  at 0 range  0 .. int'Size;
         Second_Item at 0 range  int'Size + 1 .. int'Size * 2;
         Third_Item  at 0 range  int'Size * 2 + 1 .. int'Size * 3;
      end record;


问:
There is a problem with the server configuration. NextAuth
I used google as an auth provider with next auth. Configured all the the environment variables both in production and development. It's working perfectly in dev mode but in production it shows this error whenever i try to sign in.

I deployed the site to vercel and had setup google id, secret and NEXTAUTH_URL variables there.

答:
edit pages/api/auth/[...nextauth].js
add(In same level as providers and possible callbacks):

```<code>secret:process.env.SECRET
</code>```

and add a SECRET environment variable containing anything you want

SECRET env variable in vercel

Body:
edit pages/api/auth/[...nextauth].js
add(In same level as providers and possible callbacks):

secret:process.env.SECRET

and add a SECRET environment variable containing anything you want

SECRET env variable in vercel


问:
How can i use python coroutines as celery tasks
I have old celery version in my tornado project. My current celery version is 3.1.23. There was an old library https://github.com/mher/tornado-celery which is dead now, so i would like to get rid of it and update celery to new version.

I don't want to change a tons of code, so i would like to have an ability to use async/await syntax in my celery tasks. Is it possible to do something like this

```<code>@app.task
async def add(x, y):
    res = await some_async_function(x)
    ......
</code>```

?

I've seen only examples with synchronous code and i'm not sure if my case is suitable for celery

Any tip will be good for asyncio or tornado.

UPD:

Even though celery tasks are already asynchronous, i need ability to use coroutines. I need coroutines, because currently we have a lot of tasks written with asynchronous calls, it was possible thanks to the tornado-celery library and some kind of black magic. We have database calls via async driver, async calls to AWS and so on. And because of that i need a possibility to work with asyncronous syntax inside celery tasks. I can use something like event_loop.run_until_complete(...) in asyncio or tornado.ioloop.IOLoop.instance().run_sync(lambda: do_something(1)) in tornado for example, but it's definitely not preferable way

答:
This is not the most efficient solution but it is stable and idiot-proof.

I have created a simple decorator for running async functions in a sync way using asyncio.run.

def async_to_sync(func):
    @functools.wraps(func)
    def wrapped(*args, **kwargs):
        return asyncio.run(func(*args, **kwargs))

    return wrapped
```
<p>How to use it?</p>
<ol>
<li>Copy decorator somewhere</li>
<li>Create your async function</li>
<li>Add decorator</li>
<li>Do whatever you would do with regular sync function</li>
</ol>
<p><img src="https://i.stack.imgur.com/cxOI9.png" alt="enter image description here" />
<img src="https://i.stack.imgur.com/5UfyI.png" alt="enter image description here" /></p>
<p>Alternative if you don't want to use decorator:</p>
<pre class="lang-py prettyprint-override"><code>@app.task()
def that_one_task():
    async def body():
        ac = AsyncClient()
        print(await ac.get('https://httpbin.org/get'))
        await ac.aclose()

    return asyncio.run(body())
</code>```

Body:
I have old celery version in my tornado project. My current celery version is 3.1.23. There was an old library https://github.com/mher/tornado-celery which is dead now, so i would like to get rid of it and update celery to new version.

I don't want to change a tons of code, so i would like to have an ability to use async/await syntax in my celery tasks. Is it possible to do something like this

@app.task
async def add(x, y):
    res = await some_async_function(x)
    ......

?

I've seen only examples with synchronous code and i'm not sure if my case is suitable for celery

Any tip will be good for asyncio or tornado.

UPD:

Even though celery tasks are already asynchronous, i need ability to use coroutines. I need coroutines, because currently we have a lot of tasks written with asynchronous calls, it was possible thanks to the tornado-celery library and some kind of black magic. We have database calls via async driver, async calls to AWS and so on. And because of that i need a possibility to work with asyncronous syntax inside celery tasks. I can use something like event_loop.run_until_complete(...) in asyncio or tornado.ioloop.IOLoop.instance().run_sync(lambda: do_something(1)) in tornado for example, but it's definitely not preferable way

Body:
This is not the most efficient solution but it is stable and idiot-proof.

I have created a simple decorator for running async functions in a sync way using asyncio.run.

def async_to_sync(func):
    @functools.wraps(func)
    def wrapped(*args, **kwargs):
        return asyncio.run(func(*args, **kwargs))

    return wrapped

How to use it?

Copy decorator somewhere

Create your async function

Add decorator

Do whatever you would do with regular sync function

Alternative if you don't want to use decorator:

@app.task()
def that_one_task():
    async def body():
        ac = AsyncClient()
        print(await ac.get('https://httpbin.org/get'))
        await ac.aclose()

    return asyncio.run(body())


问:
How to ignore a Task in F#?
If we have a function f that returns Async<something>, we can ignore the return value with do! f() |> Async.Ignore. Is there a similar construct for ignoring Tasks? Right now, I'm having to do something like this:

task {
    let! result = SomeOperation()
    result |> ignore
}
```

Technically I could do |> Async.AwaitTask |> Async.Ignore, but I'm not sure how wasteful it is to convert a task to async just to ignore it...

If it matters, I'm using task{} computation expressions from Ply.

答:
If you don't care for the return value, then you don't have to wait for the task to finish, you can just ignore the whole task:</p>
```<code>SomeOperation() |> ignore
</code>```

Title: How to ignore a Task in F#?

Body:
If we have a function f that returns Async<something>, we can ignore the return value with do! f() |> Async.Ignore. Is there a similar construct for ignoring Tasks? Right now, I'm having to do something like this:

task {
    let! result = SomeOperation()
    result |> ignore
}

Technically I could do |> Async.AwaitTask |> Async.Ignore, but I'm not sure how wasteful it is to convert a task to async just to ignore it...

If it matters, I'm using task{} computation expressions from Ply.

Body:
If you don't care for the return value, then you don't have to wait for the task to finish, you can just ignore the whole task:

SomeOperation() |> ignore


问:
BarChart X-Value does not correspond with Y-Value
I've got the following BarEntry List:

```<code>for (Map.Entry<Date, Float> keyVal : allIncTypesWithAmount.entrySet()) {
    long timeToDays = TimeUnit.MILLISECONDS.toDays(keyVal.getKey().getTime());
    float perDay = timeToDays/30;
    values.add(new BarEntry(perDay,keyVal.getValue()));
}
</code>```

Which results in following values:

```<code>Tue Feb 01 01:00:00 GMT+01:00 2005 value 47.0
Mon Nov 01 01:00:00 GMT+01:00 2021 value 12.0
Mon Apr 01 02:00:00 GMT+02:00 2013 value 76.0
Tue Feb 01 01:00:00 GMT+01:00 2022 value 50.0
</code>```

My XAxis ValueFormatter:

```<code>public class BarChartXAxisValueFormatter extends ValueFormatter
{

    SimpleDateFormat sdf = new SimpleDateFormat("MM/yyyy", Locale.GERMANY);
    Calendar calendar = Calendar.getInstance(TimeZone.getTimeZone("GMT"));

    @Override
    public String getFormattedValue(float value) {

        float timeToDays = value * 30;
        long emissionsMilliSince1970Time =  TimeUnit.DAYS.toMillis((long) timeToDays) ;
        return sdf.format(getBeginOfMonth(new Date(emissionsMilliSince1970Time)));
    }

    public static Date getBeginOfMonth(Date d ) {
        calendar.setTime(d);
        calendar.set(Calendar.DAY_OF_MONTH, 1);
        return calendar.getTime();
    }

}
</code>```

The current chart looks like this:

That's not how I expected it to be.

I'm trying that my chart to look like this:

Basically, my aim is to ALIGN the X-Value towards the Y-Bar.
Of course, if there are many X-Values it wont be possible, but since there are only 4 bars, I want that all 4 X-Value align with the Y-Bar.

Few things I tried:

xAxis.setGranularity(1f);

setting maxLabelCount

Is there a solution for this?

答:
Use numbers 1,2,3,4,5 etc. as the x value instead of date.
Each number should represend a date:

```<code>0 value 47.0
1 value 12.0
2 value 76.0
3 value 50.0
</code>```

Define the strings, which will be shown for the x value:

```<code>ArrayList<String> xVals = new ArrayList<>();
xVals.add("04/2020");
xVals.add("06/2020");
xVals.add("11/2020");
xVals.add("01/2021");
</code>```

Pass the List to the ValueFormatter:

```<code>new ValueFormatter(xVals));
</code>```

Last but not least, set the granularity:

```<code>xAxis.setGranularity(1f);
</code>```

Body:
I've got the following BarEntry List:

for (Map.Entry<Date, Float> keyVal : allIncTypesWithAmount.entrySet()) {
    long timeToDays = TimeUnit.MILLISECONDS.toDays(keyVal.getKey().getTime());
    float perDay = timeToDays/30;
    values.add(new BarEntry(perDay,keyVal.getValue()));
}

Which results in following values:

Tue Feb 01 01:00:00 GMT+01:00 2005 value 47.0
Mon Nov 01 01:00:00 GMT+01:00 2021 value 12.0
Mon Apr 01 02:00:00 GMT+02:00 2013 value 76.0
Tue Feb 01 01:00:00 GMT+01:00 2022 value 50.0

My XAxis ValueFormatter:

public class BarChartXAxisValueFormatter extends ValueFormatter
{

    SimpleDateFormat sdf = new SimpleDateFormat("MM/yyyy", Locale.GERMANY);
    Calendar calendar = Calendar.getInstance(TimeZone.getTimeZone("GMT"));

    @Override
    public String getFormattedValue(float value) {

        float timeToDays = value * 30;
        long emissionsMilliSince1970Time =  TimeUnit.DAYS.toMillis((long) timeToDays) ;
        return sdf.format(getBeginOfMonth(new Date(emissionsMilliSince1970Time)));
    }

    public static Date getBeginOfMonth(Date d ) {
        calendar.setTime(d);
        calendar.set(Calendar.DAY_OF_MONTH, 1);
        return calendar.getTime();
    }

}

The current chart looks like this:

That's not how I expected it to be.

I'm trying that my chart to look like this:

Basically, my aim is to ALIGN the X-Value towards the Y-Bar.
Of course, if there are many X-Values it wont be possible, but since there are only 4 bars, I want that all 4 X-Value align with the Y-Bar.

Few things I tried:

xAxis.setGranularity(1f);

setting maxLabelCount

Is there a solution for this?

Body:
Use numbers 1,2,3,4,5 etc. as the x value instead of date.
Each number should represend a date:

0 value 47.0
1 value 12.0
2 value 76.0
3 value 50.0

Define the strings, which will be shown for the x value:

ArrayList<String> xVals = new ArrayList<>();
xVals.add("04/2020");
xVals.add("06/2020");
xVals.add("11/2020");
xVals.add("01/2021");

Pass the List to the ValueFormatter:

new ValueFormatter(xVals));

Last but not least, set the granularity:

xAxis.setGranularity(1f);


问:
OpenCV python: ValueError: too many values to unpack , img
I am writing an opencv project which is a fingers distance finder and making an image(its complicated to explain but I try my best.

When i run the script, I get this error

```<code>Traceback (most recent call last):
  File "D:/P4rakash_Python_Projects/Python Projects/adding things/python.py", line 16, in <module>
    hands, img2 = detector.findHands(img)
ValueError: too many values to unpack (expected 2)
[ WARN:0] global D:\a\opencv-python\opencv-python\opencv\modules\videoio\src\cap_msmf.cpp (438) `anonymous-namespace'::SourceReaderCB::~SourceReaderCB terminating async callback

</code>```

I dont understand this error if someone fix this and answer me I can get the hang off it.

this is the full code

```<code>from cv2 import cv2
from cvzone.HandTrackingModule import HandDetector

cap = cv2.VideoCapture(0)
cap.set(3, 1280)
cap.set(4, 720)

detector = HandDetector(detectionCon=0.8)

startDist = None

scale = 0.
cx, cy = 500, 500
while True:
    Success, img = cap.read()
    hands, img = detector.findHands(img)
    img1 = cv2.imread("kisspng-computer-icons-code-coupon-font-computer-coding-5b4cbf4c6bb012.9457556415317563644411.png")

    if len(hands) == 2:
        # print(detector.fingersUp(hands[0]), detector.fingersUp(hands[1]))
        if detector.fingersUp(hands[0]) == [1, 1, 0, 0, 0] and detector.fingersUp(hands[1]) == [1, 1, 0, 0, 0]:
            # print("ZOOMMING GESTUREs")
            lmList1 = hands[0]["lmList"]
            lmList2 = hands[1]["lmList"]

            # Point 8 is teh tip of the finger
            if startDist is None:
                length, info, img = detector.findDistance(lmList1[8], lmList2[8], img)

                startDist = length

            length, info, img = detector.findDistance(lmList1[8], lmList2[8], img)
            scale = int((length - startDist) // 2)
            cx, cy = info[4:]
            # print(scale)
    else:
        startDist = None
    try:
        h1, w1, _ = img1.shape
        newH, newW = ((h1 + scale) // 2) * 2, ((w1 + scale) // 2) * 2
        img1 = cv2.resize(img1, (newW, newH))

        img[cy - newH // 2:cy + newH // 2, cx - newW // 2:cx + newW // 2] = img1

    except:
        pass

    img = cv2.flip(img, 1)
    cv2.imshow("Hollow.os", img)
    cv2.waitKey(1)

</code>```

when I do this code there is a warning coming called Unexpected argument

help is mostly what I want now

答:
Turns out I been using a 1.4.1 cvzone library to make the findposition to work then I changed it back.  And this works just fine

```<code>Change your cvzone library version to 1.5.6 so the code will work.
</code>```

please check your cvzone version because if this error comes for you then change it to the latest version it works fine now

Body:
I am writing an opencv project which is a fingers distance finder and making an image(its complicated to explain but I try my best.

When i run the script, I get this error

Traceback (most recent call last):
  File "D:/P4rakash_Python_Projects/Python Projects/adding things/python.py", line 16, in <module>
    hands, img2 = detector.findHands(img)
ValueError: too many values to unpack (expected 2)
[ WARN:0] global D:\a\opencv-python\opencv-python\opencv\modules\videoio\src\cap_msmf.cpp (438) `anonymous-namespace'::SourceReaderCB::~SourceReaderCB terminating async callback

I dont understand this error if someone fix this and answer me I can get the hang off it.

this is the full code

from cv2 import cv2
from cvzone.HandTrackingModule import HandDetector

cap = cv2.VideoCapture(0)
cap.set(3, 1280)
cap.set(4, 720)

detector = HandDetector(detectionCon=0.8)

startDist = None

scale = 0.
cx, cy = 500, 500
while True:
    Success, img = cap.read()
    hands, img = detector.findHands(img)
    img1 = cv2.imread("kisspng-computer-icons-code-coupon-font-computer-coding-5b4cbf4c6bb012.9457556415317563644411.png")

    if len(hands) == 2:
        # print(detector.fingersUp(hands[0]), detector.fingersUp(hands[1]))
        if detector.fingersUp(hands[0]) == [1, 1, 0, 0, 0] and detector.fingersUp(hands[1]) == [1, 1, 0, 0, 0]:
            # print("ZOOMMING GESTUREs")
            lmList1 = hands[0]["lmList"]
            lmList2 = hands[1]["lmList"]

            # Point 8 is teh tip of the finger
            if startDist is None:
                length, info, img = detector.findDistance(lmList1[8], lmList2[8], img)

                startDist = length

            length, info, img = detector.findDistance(lmList1[8], lmList2[8], img)
            scale = int((length - startDist) // 2)
            cx, cy = info[4:]
            # print(scale)
    else:
        startDist = None
    try:
        h1, w1, _ = img1.shape
        newH, newW = ((h1 + scale) // 2) * 2, ((w1 + scale) // 2) * 2
        img1 = cv2.resize(img1, (newW, newH))

        img[cy - newH // 2:cy + newH // 2, cx - newW // 2:cx + newW // 2] = img1

    except:
        pass

    img = cv2.flip(img, 1)
    cv2.imshow("Hollow.os", img)
    cv2.waitKey(1)

when I do this code there is a warning coming called Unexpected argument

help is mostly what I want now

Body:
Turns out I been using a 1.4.1 cvzone library to make the findposition to work then I changed it back.  And this works just fine

Change your cvzone library version to 1.5.6 so the code will work.

please check your cvzone version because if this error comes for you then change it to the latest version it works fine now


问:
ANGULAR InvalidValueError: Map: Expected mapDiv of type HTMLElement but was passed null
I have this problem when trying to initialize google maps.
As you can see Im trying to load the map in this div but I always get the same message.

tried using

 ngAfterViewInit()

because I thought maybe the view doesn't finish loading before the function is called but it didn't help.

Error Message (same as title) -

```<code>Uncaught (in promise): InvalidValueError: Map: Expected mapDiv of type HTMLElement but was passed null.
</code>```

my code:

map.component.ts -

```<code>import { Component, Input, OnInit } from "@angular/core";
import { Loader } from "@googlemaps/js-api-loader";
import { GoogleMapsService } from "src/app/Services/GoogleMapsService/google-maps.service";

@Component({
  selector: "app-maps",
  templateUrl: "./maps.component.html",
  styleUrls: ["./maps.component.scss"],
})
export class MapsComponent implements OnInit {
  @Input() inputVal: HTMLInputElement;

  constructor(private googlemapsService: GoogleMapsService) {}
  loader = new Loader({
    apiKey: API_KEY,
    version: "weekly",
  });

  ngOnInit(): void {
    console.log("YO");
  }
  ngAfterViewInit(): void {
    this.loader.load().then(this.googlemapsService.initMap);
  }
}
</code>```

googlemaps.service.ts -

```<code>Import { Injectable } from "@angular/core";

let map: google.maps.Map;

@Injectable({
  providedIn: "root",
})
export class GoogleMapsService {
  constructor() {}

  initMap() {
    const mapOptions = {
      // center: this.userCenter,
      zoom: 8,
      mapTypeId: google.maps.MapTypeId.ROADMAP,

      panControl: true,
      mapTypeControl: false,
      panControlOptions: {
        position: google.maps.ControlPosition.RIGHT_CENTER,
      },
      zoomControl: true,
      zoomControlOptions: {
        style: google.maps.ZoomControlStyle.LARGE,
        position: google.maps.ControlPosition.RIGHT_CENTER,
      },
      scaleControl: false,
      streetViewControl: false,
    };
    const userCenter = new google.maps.LatLng(51.508742, -0.12085);

    const userCenterMarker = new google.maps.Marker({
      position: userCenter,
    });
    userCenterMarker.setAnimation(google.maps.Animation.BOUNCE);
    map = new google.maps.Map(
      document.getElementById("map") as HTMLElement,
      mapOptions
    );
  }
}
</code>```

maps.component.html -

```<code><input type="text" [(ngModel)]="inputVal" />

<div id="map"></div>
</code>```

答:
The API can be loaded when the component is actually used by using the Angular HttpClient jsonp method to make sure that the component doesn't load until after the API has loaded.

Try looking at this stackblitz. If that doesn't spark something, maybe share a stackblitz of your own.

Body:
I have this problem when trying to initialize google maps.
As you can see Im trying to load the map in this div but I always get the same message.

tried using

 ngAfterViewInit()

because I thought maybe the view doesn't finish loading before the function is called but it didn't help.

Error Message (same as title) -

Uncaught (in promise): InvalidValueError: Map: Expected mapDiv of type HTMLElement but was passed null.

my code:

map.component.ts -

import { Component, Input, OnInit } from "@angular/core";
import { Loader } from "@googlemaps/js-api-loader";
import { GoogleMapsService } from "src/app/Services/GoogleMapsService/google-maps.service";

@Component({
  selector: "app-maps",
  templateUrl: "./maps.component.html",
  styleUrls: ["./maps.component.scss"],
})
export class MapsComponent implements OnInit {
  @Input() inputVal: HTMLInputElement;

  constructor(private googlemapsService: GoogleMapsService) {}
  loader = new Loader({
    apiKey: API_KEY,
    version: "weekly",
  });

  ngOnInit(): void {
    console.log("YO");
  }
  ngAfterViewInit(): void {
    this.loader.load().then(this.googlemapsService.initMap);
  }
}

googlemaps.service.ts -

Import { Injectable } from "@angular/core";

let map: google.maps.Map;

@Injectable({
  providedIn: "root",
})
export class GoogleMapsService {
  constructor() {}

  initMap() {
    const mapOptions = {
      // center: this.userCenter,
      zoom: 8,
      mapTypeId: google.maps.MapTypeId.ROADMAP,

      panControl: true,
      mapTypeControl: false,
      panControlOptions: {
        position: google.maps.ControlPosition.RIGHT_CENTER,
      },
      zoomControl: true,
      zoomControlOptions: {
        style: google.maps.ZoomControlStyle.LARGE,
        position: google.maps.ControlPosition.RIGHT_CENTER,
      },
      scaleControl: false,
      streetViewControl: false,
    };
    const userCenter = new google.maps.LatLng(51.508742, -0.12085);

    const userCenterMarker = new google.maps.Marker({
      position: userCenter,
    });
    userCenterMarker.setAnimation(google.maps.Animation.BOUNCE);
    map = new google.maps.Map(
      document.getElementById("map") as HTMLElement,
      mapOptions
    );
  }
}

maps.component.html -

<input type="text" [(ngModel)]="inputVal" />


问:
Generate Random numbers in array, add them together and store the answers in array
I am new to Java and trying to solve the problem below

So this is my story:
Program generates 20 numbers up to 100 and stores every number in array. Once generated the program has to add two numbers and stores the answer in array.. Example

```<code>randomNumber[0]+randomNumber[1]=answer[0]
randomNumber[2]+randomNumber[3]=answer[1]
randomNumber[4]+randomNumber[5]=answer[2]
</code>```

etc..

Once done I check user input with answers and count the correct answers.

The problem is: I can't figure out how to add two numbers together and store it in Array. It seems easy but I am not experienced enough :)

Currently I am stuck here, I would really appreciate if someone could explain or help me how to solve this problem.

```<code>public class gNumber {
    private final int[] num = new int[20]; // array of randomly generated numbers
    private int[] answers; // array of correct answers and UserAnswers
    private final int[] userAnswers = new int[10];
    private int numOfCorrect = 0;

    // Accessor to get the randomly generated number
    int getNumbers(final int n) {
        return num[n];
    }

    int numOfCorrectAnswers() {
        return numOfCorrect;
    }

    // Mutator to store store user input
    void setUsrAnswers(final int _index, final int answer) {
        userAnswers[_index] = answer;
    }

    // Method to generate random 20 numbers
    public void RandomN() {

        for (int i = 0; i < num.length; i++) {
            final int randomNum = (int) (Math.random() * 100);
            num[i] = randomNum;
            final int a = num[i];
            // int b =num[i];
            answers[i] = a + a;
            System.out.println(i + ")" + num[i] + answers[i]);
        }

    }

    // method to add two numbers and store in in answers array
    public void add(int arg1, int arg2) {
        int b = 0;
        while (b < 10) {
            arg1 = num[b];
            arg2 = num[b + 1];
            answers[b] = arg1 + arg2;

            System.out.println(answers[b]);
            b = b + 1;
        }
    }

    // method to check user answers
    public void usrInput(final int usrAnwer) {
        for (final int num : answers) {
            if (num == usrAnwer) {
                numOfCorrect++;
            }
        }

    }
}
</code>```

答:
You need to step through the num array by 2 when adding up answers:

```<code>public void add(int arg1, int arg2) {
    int b = 0;
    while (b < 10) {
        arg1 = num[2*b];
        arg2 = num[2*b + 1];
        answers[b] = arg1 + arg2;

        System.out.println(answers[b]);
        b = b + 1;
    }
}
</code>```

Body:
I am new to Java and trying to solve the problem below

So this is my story:
Program generates 20 numbers up to 100 and stores every number in array. Once generated the program has to add two numbers and stores the answer in array.. Example

randomNumber[0]+randomNumber[1]=answer[0]
randomNumber[2]+randomNumber[3]=answer[1]
randomNumber[4]+randomNumber[5]=answer[2]

etc..

Once done I check user input with answers and count the correct answers.

The problem is: I can't figure out how to add two numbers together and store it in Array. It seems easy but I am not experienced enough :)

Currently I am stuck here, I would really appreciate if someone could explain or help me how to solve this problem.

public class gNumber {
    private final int[] num = new int[20]; // array of randomly generated numbers
    private int[] answers; // array of correct answers and UserAnswers
    private final int[] userAnswers = new int[10];
    private int numOfCorrect = 0;

    // Accessor to get the randomly generated number
    int getNumbers(final int n) {
        return num[n];
    }

    int numOfCorrectAnswers() {
        return numOfCorrect;
    }

    // Mutator to store store user input
    void setUsrAnswers(final int _index, final int answer) {
        userAnswers[_index] = answer;
    }

    // Method to generate random 20 numbers
    public void RandomN() {

        for (int i = 0; i < num.length; i++) {
            final int randomNum = (int) (Math.random() * 100);
            num[i] = randomNum;
            final int a = num[i];
            // int b =num[i];
            answers[i] = a + a;
            System.out.println(i + ")" + num[i] + answers[i]);
        }

    }

    // method to add two numbers and store in in answers array
    public void add(int arg1, int arg2) {
        int b = 0;
        while (b < 10) {
            arg1 = num[b];
            arg2 = num[b + 1];
            answers[b] = arg1 + arg2;

            System.out.println(answers[b]);
            b = b + 1;
        }
    }

    // method to check user answers
    public void usrInput(final int usrAnwer) {
        for (final int num : answers) {
            if (num == usrAnwer) {
                numOfCorrect++;
            }
        }

    }
}

Body:
You need to step through the num array by 2 when adding up answers:

public void add(int arg1, int arg2) {
    int b = 0;
    while (b < 10) {
        arg1 = num[2*b];
        arg2 = num[2*b + 1];
        answers[b] = arg1 + arg2;

        System.out.println(answers[b]);
        b = b + 1;
    }
}


问:
missing nodes in node view of graph after randomly removed some nodes
I created a graph G and I have a node view  as following < 0, 1,2,... 100>
I randomly removed 20 nodes and the node view of this new graph misses the nodes I removed randomly. to be precise for example , in the new graph there are some nodes missing(since they are removed
node view <0,1,3,5,6,7,9 ...100>
however, I want this graph to be a new graph having node view such as the following:
<0,1,2....80>
is there any solution? I tried relabeling, coping the same graph, they didn't work

PS. my nodes have attribute label equal to either 0,1
and i want to preserve them

答:
Here is one approach you can take. After removing your nodes from the graph you can relabel the remaining nodes using nx.relabel_nodes to get the node view you want. See example below:

import networkx as nx
import numpy as np

#Creating random graph
N_nodes=50
G=nx.erdos_renyi_graph(N_nodes,p=0.25)

#Removing random nodes
N_del_nodes=10
del_node_list=np.random.choice(N_nodes,size=N_del_nodes,replace=False)
G.remove_nodes_from(del_node_list)
print('Node view without relabelling:' +str(G.nodes))

#Relabelling graph
label_mapping={list(G.nodes)[j]:j for j in range(N_nodes-N_del_nodes)}
G_rel=nx.relabel_nodes(G, label_mapping)
print('Node view with relabelling:' +str(G_rel.nodes))
```
<p>And the output gives:</p>
```Node view without relabelling:[0, 1, 2, 5, 6, 8, 9, 10, 11, 12, 13, 14, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 27, 28, 30, 31, 32, 33, 34, 36, 37, 38, 40, 41, 44, 45, 46, 47, 48, 49]
Node view with relabelling:[0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39]
```

Body:
Here is one approach you can take. After removing your nodes from the graph you can relabel the remaining nodes using nx.relabel_nodes to get the node view you want. See example below:

import networkx as nx
import numpy as np

#Creating random graph
N_nodes=50
G=nx.erdos_renyi_graph(N_nodes,p=0.25)

#Removing random nodes
N_del_nodes=10
del_node_list=np.random.choice(N_nodes,size=N_del_nodes,replace=False)
G.remove_nodes_from(del_node_list)
print('Node view without relabelling:' +str(G.nodes))

#Relabelling graph
label_mapping={list(G.nodes)[j]:j for j in range(N_nodes-N_del_nodes)}
G_rel=nx.relabel_nodes(G, label_mapping)
print('Node view with relabelling:' +str(G_rel.nodes))

And the output gives:

Node view without relabelling:[0, 1, 2, 5, 6, 8, 9, 10, 11, 12, 13, 14, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 27, 28, 30, 31, 32, 33, 34, 36, 37, 38, 40, 41, 44, 45, 46, 47, 48, 49]
Node view with relabelling:[0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39]


问:
How can I turn multiple categorical data for the forecasting using LSTM model?
Here is a part of my dataset but I am not 100% sure how I am supposed to categorise my dataset. I have been thinking about dummy and one-hot encoding methods for Districts and Crime types and set month as an index but I don't see the pattern for it. My goal is to forecast the total amount of crimes in the city and per district and the total specific crime types in the city and per district. So for instance, the total amount of crimes from 2011-2025 in the city and the total amount of shoplifting in Stoke Bishop in 2011-2025.</p>
```<code>        Month          Districts                    Crime type
0  2018-01-01       Stoke Bishop  Violence and sexual offences
1  2018-01-01  St Philip's Marsh                   Shoplifting
2  2018-01-01        Barton Hill                         Drugs
3  2018-01-01  St Philip's Marsh                   Shoplifting
4  2018-01-01  St Philip's Marsh                   Shoplifting
</code>```

答: as you said you can use one-hot-encoding for Regions and Crime types. You can create 3 different variables as a month, year, and day from the Month variable and make the filtering you want over these variables.</p>

Body:
Here is a part of my dataset but I am not 100% sure how I am supposed to categorise my dataset. I have been thinking about dummy and one-hot encoding methods for Districts and Crime types and set month as an index but I don't see the pattern for it. My goal is to forecast the total amount of crimes in the city and per district and the total specific crime types in the city and per district. So for instance, the total amount of crimes from 2011-2025 in the city and the total amount of shoplifting in Stoke Bishop in 2011-2025.

        Month          Districts                    Crime type
0  2018-01-01       Stoke Bishop  Violence and sexual offences
1  2018-01-01  St Philip's Marsh                   Shoplifting
2  2018-01-01        Barton Hill                         Drugs
3  2018-01-01  St Philip's Marsh                   Shoplifting
4  2018-01-01  St Philip's Marsh                   Shoplifting


问:
How to split an element on R?
Well, I'm working on a data frame that has a column where some elements have two or more words. I'm trying to use this column as a vector to make a pie chart, and I need the words on these elements to be split into single ones to be counted as individuals for the chart.

That's the vector in question:

```<code>science$area
 [1] "Matematica"                          "Filosofia"
 [3] "Arqueologia"                         "Astronomia"
 [5] "Biologia, Paleontologia"             "Biologia"
 [7] "Psicologia"                          "Astronomia"
 [9] "Fisica"                              "Biologia, Paleontologia"
[11] "Astronomia"                          "Biologia"
[13] "Biologia, Fisica, Matematica, Saude" "Fisica"
[15] "Paleontologia"                       "Saude"
[17] "Biologia, Saude"                     "Biologia, Saude"
[19] "Saude"                               NA
[21] "Biologia"                            "Fisica"
[23] "Psicologia"                          "Biologia"
[25] "Fisica"                              "Biologia"
[27] NA                                    "Historia"
[29] "Experiencias"                        "Astronomia"
[31] "Geografia"                           "Matematica"
[33] "Astronomia"                          "Filosofia, Literatura"
[35] "Biologia"                            "Psicologia"
[37] "Biologia, Saude"                     "Saude"
[39] "Fisica"                              "Experiencias, Fisica"
[41] "Biologia, Saude"                     "Biologia"
[43] "Computacao"                          "Biologia"
[45] "Fisica"                              "Fisica"
[47] "Filosofia, Historia, Literatura"     NA
[49] "Literatura"                          "Astronomia"
[51] "Geografia, Meio Ambiente"            "Geografia"
[53] "Biologia, Paleontologia"             "Computacao"
[55] "Fisica, Literatura"                  "Filosofia"
[57] "Geografia, Meio Ambiente"            "Fisica"
[59] "Biologia"                            "Geografia, Historia"
</code>```

When I summarize it, this returns:

```<code>> summary(factor(science$area))
                    Arqueologia                          Astronomia
                              1                                   6
                       Biologia Biologia, Fisica, Matematica, Saude
                              9                                   1
        Biologia, Paleontologia                     Biologia, Saude
                              3                                   4
                     Computacao                        Experiencias
                              2                                   1
           Experiencias, Fisica                           Filosofia
                              1                                   2
Filosofia, Historia, Literatura               Filosofia, Literatura
                              1                                   1
                         Fisica                  Fisica, Literatura
                              8                                   1
                      Geografia                 Geografia, Historia
                              2                                   1
       Geografia, Meio Ambiente                            Historia
                              2                                   1
                     Literatura                          Matematica
                              1                                   2
                  Paleontologia                          Psicologia
                              1                                   3
                          Saude                                NA's
                              3                                   3
</code>```

So, as you can see, "Biologia, Paleontologia" is being treated as a level for example, and I need it to count to both "Biologia" and "Paleontologia" instead. How can I do this?? I've already tried, unsuccessfully, to write these elements using c() and using "" amongst them, and also tried to use the split(), but it just split without considering the words...

答:
With tidyverse, we can use separate_rows with count

```<code>library(dplyr)
library(tidyr)
library(ggplot2)
separate_rows(science, area, sep = ",\\s*") %>%
    count(area) %>%
    ggplot(aes(x = "", y = n, fill = area)) +
      geom_bar(stat = "identity") +
      coord_polar("y", start=0)
</code>```

Title: How to split an element on R?

Body:
Well, I'm working on a data frame that has a column where some elements have two or more words. I'm trying to use this column as a vector to make a pie chart, and I need the words on these elements to be split into single ones to be counted as individuals for the chart.

That's the vector in question:

science$area
 [1] "Matematica"                          "Filosofia"
 [3] "Arqueologia"                         "Astronomia"
 [5] "Biologia, Paleontologia"             "Biologia"
 [7] "Psicologia"                          "Astronomia"
 [9] "Fisica"                              "Biologia, Paleontologia"
[11] "Astronomia"                          "Biologia"
[13] "Biologia, Fisica, Matematica, Saude" "Fisica"
[15] "Paleontologia"                       "Saude"
[17] "Biologia, Saude"                     "Biologia, Saude"
[19] "Saude"                               NA
[21] "Biologia"                            "Fisica"
[23] "Psicologia"                          "Biologia"
[25] "Fisica"                              "Biologia"
[27] NA                                    "Historia"
[29] "Experiencias"                        "Astronomia"
[31] "Geografia"                           "Matematica"
[33] "Astronomia"                          "Filosofia, Literatura"
[35] "Biologia"                            "Psicologia"
[37] "Biologia, Saude"                     "Saude"
[39] "Fisica"                              "Experiencias, Fisica"
[41] "Biologia, Saude"                     "Biologia"
[43] "Computacao"                          "Biologia"
[45] "Fisica"                              "Fisica"
[47] "Filosofia, Historia, Literatura"     NA
[49] "Literatura"                          "Astronomia"
[51] "Geografia, Meio Ambiente"            "Geografia"
[53] "Biologia, Paleontologia"             "Computacao"
[55] "Fisica, Literatura"                  "Filosofia"
[57] "Geografia, Meio Ambiente"            "Fisica"
[59] "Biologia"                            "Geografia, Historia"

When I summarize it, this returns:

> summary(factor(science$area))
                    Arqueologia                          Astronomia
                              1                                   6
                       Biologia Biologia, Fisica, Matematica, Saude
                              9                                   1
        Biologia, Paleontologia                     Biologia, Saude
                              3                                   4
                     Computacao                        Experiencias
                              2                                   1
           Experiencias, Fisica                           Filosofia
                              1                                   2
Filosofia, Historia, Literatura               Filosofia, Literatura
                              1                                   1
                         Fisica                  Fisica, Literatura
                              8                                   1
                      Geografia                 Geografia, Historia
                              2                                   1
       Geografia, Meio Ambiente                            Historia
                              2                                   1
                     Literatura                          Matematica
                              1                                   2
                  Paleontologia                          Psicologia
                              1                                   3
                          Saude                                NA's
                              3                                   3

So, as you can see, "Biologia, Paleontologia" is being treated as a level for example, and I need it to count to both "Biologia" and "Paleontologia" instead. How can I do this?? I've already tried, unsuccessfully, to write these elements using c() and using "" amongst them, and also tried to use the split(), but it just split without considering the words...

Body:
With tidyverse, we can use separate_rows with count

library(dplyr)
library(tidyr)
library(ggplot2)
separate_rows(science, area, sep = ",\\s*") %>%
    count(area) %>%
    ggplot(aes(x = "", y = n, fill = area)) +
      geom_bar(stat = "identity") +
      coord_polar("y", start=0)


问:
How do I get video dimensions from a video url in python?
I need to get the video dimensions of some videos using there urls on python. Can some one help me?</p>

答:
You can do this using the pafy library:

```<code>import pafy

url = "https://www.youtube.com / watch?v = **id**"

video = pafy.new(url)

streams = video.allstreams

stream = streams[7]

value = stream.dimensions

print("Dimension : " + str(value))
</code>```

Stream is basically the available resolution of the video.

Body:
You can do this using the pafy library:

import pafy

url = "https://www.youtube.com / watch?v = **id**"

video = pafy.new(url)

streams = video.allstreams

stream = streams[7]

value = stream.dimensions

print("Dimension : " + str(value))

Stream is basically the available resolution of the video.