问:
Noob Question How would I update a print a function's output without creating a new line in my term in python3?
I'm not exactly sure how to word this to be honest, but here's a simplified version of my current code.

```<code>for idx in range(0,11):
    print('Failed:',idx)
</code>```

This outputs:

```<code>Failed: 0
Failed: 1
Failed: 2
Failed: 3
Failed: 4
Failed: 5
Failed: 6
Failed: 7
Failed: 8
Failed: 9
Failed: 10
</code>```

I'm trying to replace the original int with the next int in the range instead of spamming my terminal with a new line for every int in the range.

How could I update "Failed: 1" to "Failed: 2" without creating a new line for "Failed: 2"?

Sorry if this is poorly worded, if you're willing to help me but like me to elaborate further please say so and I will try my best.

答:
What you probably want to do is change 'Failed: 1' to 'Failed: 2', not have 'Failed: 1 Failed: 2' on the same line or new lines.

The ASCII backslash b (backspace) helps erase characters on the same line. You'd want to move the cursor back to where the last number was and replace it.

Here's a simple program that moves back on the same line and replaces the counter.

```<code>import time
import sys

print(0, end="")
prev = 0
for i in range(20):
    print(("\b" * (len(str(prev)) + 1)), i, end="")
    sys.stdout.flush()
    prev = i

    time.sleep(1)
</code>```

And to complete your example:

```<code>import time
import sys

last_idx = None
prefix = ''
print("Failed: ", end="")
for idx in range(0,11):
    if last_idx is not None:
        prefix = '\b' * len(str(last_idx))

    print(prefix + str(idx), end='')
    # python buffers output so you want to flush it everytime.
    sys.stdout.flush()
    last_idx = idx
    # I've added a time.sleep here so you can see it happen rather than zoom past you
    time.sleep(1)
</code>```

Alternatively, instead of just backspacing few characters, you can go back to the beginning of the line with "carriage return" (\r instead of \b).

Body:
I'm not exactly sure how to word this to be honest, but here's a simplified version of my current code.

for idx in range(0,11):
    print('Failed:',idx)

This outputs:

Failed: 0
Failed: 1
Failed: 2
Failed: 3
Failed: 4
Failed: 5
Failed: 6
Failed: 7
Failed: 8
Failed: 9
Failed: 10

I'm trying to replace the original int with the next int in the range instead of spamming my terminal with a new line for every int in the range.

How could I update "Failed: 1" to "Failed: 2" without creating a new line for "Failed: 2"?

Sorry if this is poorly worded, if you're willing to help me but like me to elaborate further please say so and I will try my best.

Body:
What you probably want to do is change 'Failed: 1' to 'Failed: 2', not have 'Failed: 1 Failed: 2' on the same line or new lines.

The ASCII backslash b (backspace) helps erase characters on the same line. You'd want to move the cursor back to where the last number was and replace it.

Here's a simple program that moves back on the same line and replaces the counter.

import time
import sys

print(0, end="")
prev = 0
for i in range(20):
    print(("\b" * (len(str(prev)) + 1)), i, end="")
    sys.stdout.flush()
    prev = i

    time.sleep(1)

And to complete your example:

import time
import sys

last_idx = None
prefix = ''
print("Failed: ", end="")
for idx in range(0,11):
    if last_idx is not None:
        prefix = '\b' * len(str(last_idx))

    print(prefix + str(idx), end='')
    # python buffers output so you want to flush it everytime.
    sys.stdout.flush()
    last_idx = idx
    # I've added a time.sleep here so you can see it happen rather than zoom past you
    time.sleep(1)

Alternatively, instead of just backspacing few characters, you can go back to the beginning of the line with "carriage return" (\r instead of \b).


来源: stackexchange

问:
Regular Expression to trim number at the end of a string
I have a file which consists of string. The file also contains date.
I want to remove number at the end of the string.
For example-

```<code>Str = 'part-at-1234'
</code>```

New string should be str= 'part-at'

I have written the following regex

```<code>(-\d+)
</code>```

My regex also matches the date.
I want to write a regular expression that only matches the string not include date.
Thank you in advance

答:
Try the following</p>

```<code>s = re.sub("^\d+\s|\s\d+\s|\s\d+$", " ", p)
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I have a file which consists of string. The file also contains date.
I want to remove number at the end of the string.
For example-

Str = 'part-at-1234'

New string should be str= 'part-at'

I have written the following regex

(-\d+)

My regex also matches the date.
I want to write a regular expression that only matches the string not include date.
Thank you in advance

Body:
Try the following

s = re.sub("^\d+\s|\s\d+\s|\s\d+$", " ", p)


问:
Oracle issue with concat()
```<code>SELECT EMPLOYEE_ID, CONCAT(FIRST_NAME," ",LAST_NAME) AS EMPLOYEE_NAME, HIRE_DATE
FROM EMPLOYEES
</code>```

I tried running the above code and it's giving me error ( invalid number of arguments ) for concatenation. I am trying to add a space between FIRST_NAME and LAST_NAME.

答:
Please use below query,</p>

```<code>SELECT EMPLOYEE_ID, FIRST_NAME||' '||LAST_NAME AS EMPLOYEE_NAME, HIRE_DATE
FROM EMPLOYEES;
</code>```

Title: Oracle issue with concat()

Body:
SELECT EMPLOYEE_ID, CONCAT(FIRST_NAME," ",LAST_NAME) AS EMPLOYEE_NAME, HIRE_DATE
FROM EMPLOYEES

I tried running the above code and it's giving me error ( invalid number of arguments ) for concatenation. I am trying to add a space between FIRST_NAME and LAST_NAME.

Body:
Please use below query,

SELECT EMPLOYEE_ID, FIRST_NAME||' '||LAST_NAME AS EMPLOYEE_NAME, HIRE_DATE
FROM EMPLOYEES;


问:
Send and read data through socket from fiber
Trying to figure out how to send/read data through socket. On remote server I create new netcat -l 4444 and from local send text data echo "test" | netcat remote.host 4444. This is always works fine.

Trying to reproduce:

```<code>require "socket"

HOST = "remote.host"
PORT = 4444

ch_request = Channel(String).new
ch_response = Channel(String).new

spawn do
  socket = TCPSocket.new(HOST, PORT)
  loop do
    select
    when request = ch_request.receive
      socket << request
      socket.flush
    end

    if response = socket.gets
      ch_response.send response
    end
  end
end

sleep 0.1

ch_request.send "hello"

loop do
  select
  when response = ch_response.receive
    pp response
  end
end

</code>```

In my dream I send data to channel, read it from first loop then send to socket. The same way but reverse order need for read it from second loop.

On practice this is not happens. On local after connect I got "test" and can't send back anything. On remote I can send to local but on local got only empty string once and nothing more after.

What mean this behavior and how to achieve planned?

答:
You didn't show this, but I suppose you have a second implementation using TCPServer for the netcat -l equivalent.

You need to use separate fibers for reading/writing to the socket and the channel. It's a bit hard to judge what exactly happens without seeing the server, but I suppose you end up in a deadlock where both sides are waiting on input of the other side or user, but cannot proceed to  actually send or read anything. In other words you interlocked the sending/receiving part, requiring the other side to carefully react and interplay so to not lock up the client. This is obviously a brittle approach.

Instead you should make sure any fiber does not do more than one operation in a loop. One receives from the socket and forwards that to a channel, the second one receives from a channel and forwards that to the socket, the third one receives from the reader side channel and prints or does whatever you want to do the data and the last one fills the sender channel. This way no operation can block one of the others. Of course one of those fibers should simply be the main program one.

In the server you additionally need one fiber that accepts the client connections and spawns the sender and receiver loops for each.

Finally note that a select statement with a single when branch  has no  effect, you can make the call directly. select is useful if you need to read or write to multiple channels concurrently in the same fiber, so for example if you would have multiple channels  providing data to be send out to a socket, you would use select to not have the messages be corrupted by two fibers writing to the same socket at the same time. An additional usecase for select is to send or receive from a channel with a timeout.

Body:
Trying to figure out how to send/read data through socket. On remote server I create new netcat -l 4444 and from local send text data echo "test" | netcat remote.host 4444. This is always works fine.

Trying to reproduce:

require "socket"

HOST = "remote.host"
PORT = 4444

ch_request = Channel(String).new
ch_response = Channel(String).new

spawn do
  socket = TCPSocket.new(HOST, PORT)
  loop do
    select
    when request = ch_request.receive
      socket << request
      socket.flush
    end

    if response = socket.gets
      ch_response.send response
    end
  end
end

sleep 0.1

ch_request.send "hello"

loop do
  select
  when response = ch_response.receive
    pp response
  end
end

In my dream I send data to channel, read it from first loop then send to socket. The same way but reverse order need for read it from second loop.

On practice this is not happens. On local after connect I got "test" and can't send back anything. On remote I can send to local but on local got only empty string once and nothing more after.

What mean this behavior and how to achieve planned?


问:
in_category method in wordpress and script tags - AdjacentHTML
I am trying to show .gif banner on a posts only within specific category after first paragraph in wordpress, so I my code in loop-single.php looks like:

```<code><?php if(in_category('my_category')){ ?>
<script>
    const par = document.querySelector('p');
    par.insertAdjacentHTML('afterend', '<div><a href="other_page" target="_blank" rel="nofollow"><img src="some_gif" alt="" class=""></a></div>')
</script>

<?php } ?>
</code>```

But it doesn't work as expected. Anyone have an idea? Or may be some other solution that not recquires installing additional plugins (not that I don't want to, most of them just slow the site down).

Thank you

edit: 'after first paragraph' added

答:
So, I found a way, firstly I needed to check if the post is in wanted category, than create a function and call it afterwards. The code is set in single-loop.php file in my template:

```<code><?php if(in_category('my-category')){ ?>
<script type="text/javascript">
    function krasAd() {
    const par = document.querySelector("p");
    par.insertAdjacentHTML('afterend', '<div><a href="some-url-target" target="_blank" rel="nofollow"><img src="my-gif" alt="" class=""></a></div>')
};
    krasAd();
</script>

<?php } ?>
</code>```

There was also one way to check if you have a string in URL that only recquires JS. But it recquires you to have properly created URL structure, for example: domain.com/category/post

If I had category in my posts URL I would use code below, the code is set before closing footer tag in my single-loop.php template file:

```<code><script type="text/javascript">
    if (window.location.href.indexOf("my-string") > -1) {
        const par = document.querySelector("p");
        par.insertAdjacentHTML('afterend', '<div><a href="some-target-url" target="_blank" rel="nofollow"><img src="my-gif" alt="" class=""></a></div>')
    }
</script>
</code>```

Body:
I am trying to show .gif banner on a posts only within specific category after first paragraph in wordpress, so I my code in loop-single.php looks like:

<?php if(in_category('my_category')){ ?>

<?php } ?>

But it doesn't work as expected. Anyone have an idea? Or may be some other solution that not recquires installing additional plugins (not that I don't want to, most of them just slow the site down).

Thank you

edit: 'after first paragraph' added

Body:
So, I found a way, firstly I needed to check if the post is in wanted category, than create a function and call it afterwards. The code is set in single-loop.php file in my template:

<?php if(in_category('my-category')){ ?>
<script type="text/javascript">
    function krasAd() {
    const par = document.querySelector("p");
    par.insertAdjacentHTML('afterend', '<div><a href="some-url-target" target="_blank" rel="nofollow"><img src="my-gif" alt="" class=""></a></div>')
};
    krasAd();
</script>

<?php } ?>

There was also one way to check if you have a string in URL that only recquires JS. But it recquires you to have properly created URL structure, for example: domain.com/category/post

If I had category in my posts URL I would use code below, the code is set before closing footer tag in my single-loop.php template file:

<script type="text/javascript">
    if (window.location.href.indexOf("my-string") > -1) {
        const par = document.querySelector("p");
        par.insertAdjacentHTML('afterend', '<div><a href="some-target-url" target="_blank" rel="nofollow"><img src="my-gif" alt="" class=""></a></div>')
    }
</script>


问:
BigQuery Standard Get first not null value when grouping
I have a table like this:

```<code>CUSTOMERS_ID  DATE_SALES  DIMENSION
MARIO1        20200201    NULL
MARIO1        20200113    Spain
MARIO2        20200131    NULL
MARIO3        20200101    France
MARIO3        20191231    Spain
</code>```

and I need to order by CUSTOMERS_ID and DATE_SALES DESC fields. Then I want to group by CUSTOMERS_ID field and get first not null value of DIMENSION field.
The output table would be:

```<code>CUSTOMERS_ID  DIMENSION
MARIO1        Spain
MARIO2        NULL
MARIO3        France
</code>```

Any ideas? I have tried COALESCE functions, FIRST_VALUE, and I have not the results I had expected.

Thanks in advance!

答:
You can group by customer id and use ARRAY_AGG by ignoring NULLS, and you can also order by date in that field.
Limit 1 will make it more efficient by using less RAM storage.
And then, OFFSET(0) will make it an unnested field, so you can use that field easily.</p>
```<code>WITH
raw_data AS
(
  SELECT 'MARIO1' CUSTOMERS_ID, 20200201 DATE_SALES, NULL as DIMENSION UNION ALL
  SELECT 'MARIO1' CUSTOMERS_ID, 20200113 DATE_SALES, 'Spain' as DIMENSION UNION ALL
  SELECT 'MARIO2' CUSTOMERS_ID, 20200131 DATE_SALES, NULL as DIMENSION UNION ALL
  SELECT 'MARIO3' CUSTOMERS_ID, 20200101 DATE_SALES, 'France' as DIMENSION UNION ALL
  SELECT 'MARIO3' CUSTOMERS_ID, 20191231 DATE_SALES, 'Spain' as DIMENSION
)
SELECT CUSTOMERS_ID, ARRAY_AGG(DIMENSION IGNORE NULLS ORDER BY DATE_SALES DESC LIMIT 1)[OFFSET(0)] as DIMENSION
FROM raw_data
GROUP BY 1
</code>```

Body:
I have a table like this:

CUSTOMERS_ID  DATE_SALES  DIMENSION
MARIO1        20200201    NULL
MARIO1        20200113    Spain
MARIO2        20200131    NULL
MARIO3        20200101    France
MARIO3        20191231    Spain

and I need to order by CUSTOMERS_ID and DATE_SALES DESC fields. Then I want to group by CUSTOMERS_ID field and get first not null value of DIMENSION field.
The output table would be:

CUSTOMERS_ID  DIMENSION
MARIO1        Spain
MARIO2        NULL
MARIO3        France

Any ideas? I have tried COALESCE functions, FIRST_VALUE, and I have not the results I had expected.

Thanks in advance!

Body:
You can group by customer id and use ARRAY_AGG by ignoring NULLS, and you can also order by date in that field.
Limit 1 will make it more efficient by using less RAM storage.
And then, OFFSET(0) will make it an unnested field, so you can use that field easily.

WITH
raw_data AS
(
  SELECT 'MARIO1' CUSTOMERS_ID, 20200201 DATE_SALES, NULL as DIMENSION UNION ALL
  SELECT 'MARIO1' CUSTOMERS_ID, 20200113 DATE_SALES, 'Spain' as DIMENSION UNION ALL
  SELECT 'MARIO2' CUSTOMERS_ID, 20200131 DATE_SALES, NULL as DIMENSION UNION ALL
  SELECT 'MARIO3' CUSTOMERS_ID, 20200101 DATE_SALES, 'France' as DIMENSION UNION ALL
  SELECT 'MARIO3' CUSTOMERS_ID, 20191231 DATE_SALES, 'Spain' as DIMENSION
)
SELECT CUSTOMERS_ID, ARRAY_AGG(DIMENSION IGNORE NULLS ORDER BY DATE_SALES DESC LIMIT 1)[OFFSET(0)] as DIMENSION
FROM raw_data
GROUP BY 1


答:
try this, \d+ any digit one or more & $ matches the end of the string

```<code>import re

re.sub("-\d+$",'' , "part-at-1234")

'part-at'
</code>```

Title: Regular Expression to trim number at the end of a string

Body:
try this, \d+ any digit one or more & $ matches the end of the string

import re

re.sub("-\d+$",'' , "part-at-1234")

'part-at'


问:
How to handle this query in functional way?
//How can we handle the below code in functional way like collect all invalid sort params, prepare message with all them listed and finally throw InvalidSortParam exception.

DO you think the below query does it?

public Sort resolveArgument() {

```<code>    Sort sort = sortHandlerMethodArgumentResolver.resolveArgument();

    List<Sort.Order> orders = sort.stream().collect(Collectors.toList());
    List<String> invalidSortList = orders.stream().map(Sort.Order::getProperty)
            .filter(property -> !allowedSortParams.contains(property))
            .collect(Collectors.toList());

    if (orders.isEmpty()) {
        sort = Sort.by(Sort.Direction.DESC, defaultSortParam);
    } else {
        if (orders.size() > sortMaxCount) {
            throw new InvalidSortException(INVALID_SIZE_PARAMS);
        } else {
            if (!invalidSortList.isEmpty()) {
                throw new InvalidSortException(invalidSortList.stream()
                        .collect(Collectors.joining(",")) + INVALID_SORT_PARAMS);
            }
        }
    }

    return sort;
}
</code>```

答:
First of all - you do not take advantage of the streaming functionality, you divided it into two separate steps - loading data, and when it is completed - transforming it. You could merge it into a single pipeline. Secondly - throwing exceptions is not a functional way. You should use some type to return a state e.g with some Try implementation.

```<code>final class Try<T> {

    private final Exception e;
    private final T t;

    public Try(Exception e) {
        this.e = e;
        t = null;
    }

    public Try(T t) {
        this.t = t;
        e = null;
    }

    public Exception getE() {
        return e;
    }

    public T getT() {
        return t;
    }
}

</code>```

and the code itself could look something like

```<code>public Try<Sort> resolveArgument()  {
    int cnt = getCount();
    return cnt == 0 ? Sort.by(Sort.Direction.DESC, defaultSortParam) : someErrorHandlingLogic(cnt);

}

private static void getCount() {
    sort.stream().map(Sort.Order::getProperty)
            .filter(property -> !allowedSortParams.contains(property))
            .count();
}
</code>```

If you're interested in the Functional Programming paradigm in java - I recommend great presentation https://dev.tube/video/YnzisJh-ZNI

Body:
//How can we handle the below code in functional way like collect all invalid sort params, prepare message with all them listed and finally throw InvalidSortParam exception.

DO you think the below query does it?

public Sort resolveArgument() {

    Sort sort = sortHandlerMethodArgumentResolver.resolveArgument();

    List<Sort.Order> orders = sort.stream().collect(Collectors.toList());
    List<String> invalidSortList = orders.stream().map(Sort.Order::getProperty)
            .filter(property -> !allowedSortParams.contains(property))
            .collect(Collectors.toList());

    if (orders.isEmpty()) {
        sort = Sort.by(Sort.Direction.DESC, defaultSortParam);
    } else {
        if (orders.size() > sortMaxCount) {
            throw new InvalidSortException(INVALID_SIZE_PARAMS);
        } else {
            if (!invalidSortList.isEmpty()) {
                throw new InvalidSortException(invalidSortList.stream()
                        .collect(Collectors.joining(",")) + INVALID_SORT_PARAMS);
            }
        }
    }

    return sort;
}

Body:
First of all - you do not take advantage of the streaming functionality, you divided it into two separate steps - loading data, and when it is completed - transforming it. You could merge it into a single pipeline. Secondly - throwing exceptions is not a functional way. You should use some type to return a state e.g with some Try implementation.

final class Try<T> {

    private final Exception e;
    private final T t;

    public Try(Exception e) {
        this.e = e;
        t = null;
    }

    public Try(T t) {
        this.t = t;
        e = null;
    }

    public Exception getE() {
        return e;
    }

    public T getT() {
        return t;
    }
}

and the code itself could look something like

public Try<Sort> resolveArgument()  {
    int cnt = getCount();
    return cnt == 0 ? Sort.by(Sort.Direction.DESC, defaultSortParam) : someErrorHandlingLogic(cnt);

}

private static void getCount() {
    sort.stream().map(Sort.Order::getProperty)
            .filter(property -> !allowedSortParams.contains(property))
            .count();
}

If you're interested in the Functional Programming paradigm in java - I recommend great presentation https://dev.tube/video/YnzisJh-ZNI


问:
Array-index-out-of-bounds exception
I am getting an array-out-of-bounds exception error. This is my simple code:

for(int i=0; i<aa.length; i++) {
    String[] event = aa[i].split(" ");
    int mr = 0;
    mr = event[i].length();
    String eventtime = event[mr];
}
```

And this is my error caused:

Caused by: java.lang.ArrayIndexOutOfBoundsException: length=3; index=5.

The length of my events array is 3. Then the index has to be 3, but it shows me 5. Why?

答: I think you want mr = event.length here, although remember that array indices start at 0, so you'll want mr = event.length - 1.

Title: Array-index-out-of-bounds exception

Body:
I am getting an array-out-of-bounds exception error. This is my simple code:

for(int i=0; i<aa.length; i++) {
    String[] event = aa[i].split(" ");
    int mr = 0;
    mr = event[i].length();
    String eventtime = event[mr];
}

And this is my error caused:

Caused by: java.lang.ArrayIndexOutOfBoundsException: length=3; index=5.

The length of my events array is 3. Then the index has to be 3, but it shows me 5. Why?


问:
Telegram bot get forward_from user id
I'm trying to get the id of a user whose message has been forwarded. Like Message forwarded from X and I need to get X id

I tried with this but I don't receive anything about forward_from

```<code><?php
$update = file_get_contents('php://input');
$update = json_decode($update, TRUE);
$message = isset($update['message']) ? $update['message'] : "";
$reply = isset($message['reply_to_message']) ? $message['reply_to_message'] : "";
$reply_id_username = isset($reply['forward_from']['id']) ? $reply['forward_from']['id'] : "";
</code>```

$reply result is

```<code>{
    "message_id": 3,
    "from": {
        "id": BOT ID,
        "is_bot": true,
        "first_name": "X",
        "username": "X_Bot"
    },
    "chat": {
        "id": MY ID,
        "first_name": "Me",
        "username": "Me",
        "type": "private"
    },
    "date": 1590679285,
    "forward_sender_name": "User X",
    "forward_date": 1590679285,
    "text": "Text"
}
</code>```

It gives to me just his name

答:
During forwarding the returned message object only provides forward_sender_name (text with sender's name) if the user does not allow including the account information with the forwarded message. It is controlled by the Privacy Policy

If profile sharing is enabled this information should be available in forward_from field of the Message

Title: Telegram bot get forward_from user id

Body:
I'm trying to get the id of a user whose message has been forwarded. Like Message forwarded from X and I need to get X id

I tried with this but I don't receive anything about forward_from

<?php
$update = file_get_contents('php://input');
$update = json_decode($update, TRUE);
$message = isset($update['message']) ? $update['message'] : "";
$reply = isset($message['reply_to_message']) ? $message['reply_to_message'] : "";
$reply_id_username = isset($reply['forward_from']['id']) ? $reply['forward_from']['id'] : "";

$reply result is

{
    "message_id": 3,
    "from": {
        "id": BOT ID,
        "is_bot": true,
        "first_name": "X",
        "username": "X_Bot"
    },
    "chat": {
        "id": MY ID,
        "first_name": "Me",
        "username": "Me",
        "type": "private"
    },
    "date": 1590679285,
    "forward_sender_name": "User X",
    "forward_date": 1590679285,
    "text": "Text"
}

It gives to me just his name


问:
access youtube analytics api via content manager account's client id
We have content manager account which has been granted to access to all channels we have.
We do authorization procedure for each service accounts to get access tokens for analytics-API,
it works well, but it also demands when new channel is added.

Is it possible that issuing an access token via client id of content manager account, and use it to call API to access all channels that content manager account handles?

答:
Youtube api is channel + user based.  Each access token is authorized to access a single user + channel.

If you have five channels you will need to login five times and each access token you get back will have access to the single channel.


问:
how do I read a textfile into a 2D array in c++?
I am really struggling with trying to pass a comma separated integer textfile into a 2d array in c++.
example, if the textfile looks like

```
2,4,5,6
3,7,5,3
4,8,4,2
6,7,3,0
```

how will I be able to put this into a 4 by 4 array please? I will later need to do calculations on it, which I know how to once it is in the 2d array.
thank you in advance

so far I have

```<code>#include <iostream>
#include <sstream>
#include <string>
#include <fstream>
using namespace std;
int main()
{

const int row =4;
const int col =4;
int array[row][col];
int r =0;
int c =0;
ifstream inputfile("numbers.txt");
if (!inputfile.is_open())
{cout<<"error"<<endl;
}
string line,num;
int number;
while(get line(inputfile,line))
{
string stream ss(line);
getline(ss,num,',');
number= stop(num);

for (int r=0; r<row;r++)
{
for (int c=0; c<col; c++)
{
array[row][col] =number;
}

}

inputfile.close();
return 0;
}
</code>```

答:
The good news is you have collected the right pieces of the puzzle to do what it is you are attempting to do. The bad news is ... you put the puzzle together wrong ... (but not terribly so).

The key is to systematically program each step you need to accomplish to read the csv file into a 2D array. (you should be using std::vector<std::vector<int>>, but I suspect the 2D array is an assignment requirement -- and it is also good to know how to handle arrays of fundamental types -- there are a lot out there in legacy code). Up through the point of reading each line from the file and populating the stringstream and then looking to parse with getline using the ',' as a delimiter everything looks okay.

What you are missing are protections to prevent reading more columns than you have storage for and more rows than you have declared. While this will not impact your read of the values from you file if your file contains exactly the number of values as you have declared for your array, it is vital for using arrays of fundamental types correctly. They are of fixed size and there is no auto-allocation that will save you if you attempt to write beyond the bounds of your array (you will just corrupt your program stack)

How do you protect your arrays bound? Simple, just check the the current row doesn't exceed the number allocated and the same for the columns, e.g.

```<code>    /* read each line, protect row bounds */
    while (r < row && getline (inputfile,line)) {
        int c = 0;      /* declare c local to loop so it is reset each iteration */
        std::string num;
        std::stringstream ss (line);
        /* loop reading from stringstream, protect column bounds */
        while (c < col && getline (ss, num, ',')) {
            try {   /* try/catch exception handling required for stoi conversion */
                array[r][c++] = std::stoi (num);    /* convert, increment col count */
            }
            catch (const std::exception & e) {
                std::cerr << "error: invalid conversion " << e.what() << '\n';
                return 1;
            }
        }
        if (c != col) { /* validate col number of values read & stored */
            std::cerr << "error: invalid number of columns '" << c << "' row: "
                        << r << '\n';
            return 1;
        }
        r++;    /* increment row count */
    }
</code>```

Also note the use of try/catch exception handling. When using std::stoi that is the only manner you have to validate the conversion, see cppreference.com - std::stoi and note the Exception heading detailing the two exception (std::invalid_argument and std::out_of_range) that must be handled. You cannot simply guess that all input files will be in the needed format with the correct values and hope for the best -- you must validate every input.

This applies to the number of columns in each row as well (and the number of rows filled when your read-loop is done). When you are done reading from the stringstring, you need to validate the number of column-values read is the number expected and that you have not encountered a short row. Note: these are the minimum-validations needed. You are free to write additional validations such as to check to ensure the stringstring is empty and that additional valued do not remain unread (not critical to the operation of the code, but may flag an invalidly formatted input file)

Lastly, while the remainder of the code simply outputs the values, take a look at Why is “using namespace std;” considered bad practice?. Develop good habits early. That also means Don't Hardcode Filenames. The arguments to main() provide a way to pass needed information into your program on startup -- use them, or at minimum, prompt for the filename to open.

Further, always compile with warnings enabled. That means -Wall -Wextra -pedantic -Wshadow for gcc/clang and for VS /W3. Including -Wshadow you would find that you shadow the previous declaration for variable c in for (int c=0; c<col; c++)

Putting it altogether, you could do something similar to:

```<code>#include <iostream>
#include <sstream>
#include <string>
#include <fstream>

#define ROW 4       /* while const int is fine, if you #define your constants  */
#define COL ROW     /* you have one single location at the top to make changes */

int main (int argc, char **argv) {

    const int row = ROW, col = COL; /* optional, you can just use ROW & COL */
    int array[row][col], r = 0;
    std::string line;

    if (argc < 2) { /* validate at least 1 argument given for filename */
        std::cerr << "error: insufficient arguments\nusage: ./prog filename\n";
        return 1;
    }

    std::ifstream inputfile (argv[1]);  /* open file provided as 1st argument */
    if (!inputfile.is_open()) { /* use std::cerr for error output, handle error */
        std::cerr << "error: file open failed '" << argv[1] << "'.\n";
        return 1;
    }

    /* read each line, protect row bounds */
    while (r < row && getline (inputfile,line)) {
        int c = 0;      /* declare c local to loop so it is reset each iteration */
        std::string num;
        std::stringstream ss (line);
        /* loop reading from stringstream, protect column bounds */
        while (c < col && getline (ss, num, ',')) {
            try {   /* try/catch exception handling required for stoi conversion */
                array[r][c++] = std::stoi (num);    /* convert, increment col count */
            }
            catch (const std::exception & e) {
                std::cerr << "error: invalid conversion " << e.what() << '\n';
                return 1;
            }
        }
        if (c != col) { /* validate col number of values read & stored */
            std::cerr << "error: invalid number of columns '" << c << "' row: "
                        << r << '\n';
            return 1;
        }
        r++;    /* increment row count */
    }

    if (r < row) {  /* validate row number of arrays stored in 2D array */
        std::cerr << "error: invalid number of rows '" << r << "'\n";
        return 1;
    }

    for (r = 0; r < row; r++) {         /* loop outputting results */
        for (int c = 0; c < col; c++)
            std::cout << " " << array[r][c];
        std::cout << '\n';
    }
}
</code>```

(note: the #define statements are optional, but provide a convenient place at the top of your code to adjust your constants if the need arises)

Example Use/Output

While your input file in dat/2darr.csv, you would execute and receive the following output:

```<code>$ ./bin/read2darrcsv dat/2darr.csv
 2 4 5 6
 3 7 5 3
 4 8 4 2
 6 7 3 0
</code>```

Let me know if you have further questions.

Body:
I am really struggling with trying to pass a comma separated integer textfile into a 2d array in c++.
example, if the textfile looks like

2,4,5,6
3,7,5,3
4,8,4,2
6,7,3,0

how will I be able to put this into a 4 by 4 array please? I will later need to do calculations on it, which I know how to once it is in the 2d array.
thank you in advance

so far I have

#include <iostream>
#include <sstream>
#include <string>
#include <fstream>
using namespace std;
int main()
{

const int row =4;
const int col =4;
int array[row][col];
int r =0;
int c =0;
ifstream inputfile("numbers.txt");
if (!inputfile.is_open())
{cout<<"error"<<endl;
}
string line,num;
int number;
while(get line(inputfile,line))
{
string stream ss(line);
getline(ss,num,',');
number= stop(num);

for (int r=0; r<row;r++)
{
for (int c=0; c<col; c++)
{
array[row][col] =number;
}

}

inputfile.close();
return 0;
}

Body:
The good news is you have collected the right pieces of the puzzle to do what it is you are attempting to do. The bad news is ... you put the puzzle together wrong ... (but not terribly so).

The key is to systematically program each step you need to accomplish to read the csv file into a 2D array. (you should be using std::vector<std::vector<int>>, but I suspect the 2D array is an assignment requirement -- and it is also good to know how to handle arrays of fundamental types -- there are a lot out there in legacy code). Up through the point of reading each line from the file and populating the stringstream and then looking to parse with getline using the ',' as a delimiter everything looks okay.

What you are missing are protections to prevent reading more columns than you have storage for and more rows than you have declared. While this will not impact your read of the values from you file if your file contains exactly the number of values as you have declared for your array, it is vital for using arrays of fundamental types correctly. They are of fixed size and there is no auto-allocation that will save you if you attempt to write beyond the bounds of your array (you will just corrupt your program stack)

How do you protect your arrays bound? Simple, just check the the current row doesn't exceed the number allocated and the same for the columns, e.g.

    /* read each line, protect row bounds */
    while (r < row && getline (inputfile,line)) {
        int c = 0;      /* declare c local to loop so it is reset each iteration */
        std::string num;
        std::stringstream ss (line);
        /* loop reading from stringstream, protect column bounds */
        while (c < col && getline (ss, num, ',')) {
            try {   /* try/catch exception handling required for stoi conversion */
                array[r][c++] = std::stoi (num);    /* convert, increment col count */
            }
            catch (const std::exception & e) {
                std::cerr << "error: invalid conversion " << e.what() << '\n';
                return 1;
            }
        }
        if (c != col) { /* validate col number of values read & stored */
            std::cerr << "error: invalid number of columns '" << c << "' row: "
                        << r << '\n';
            return 1;
        }
        r++;    /* increment row count */
    }

Also note the use of try/catch exception handling. When using std::stoi that is the only manner you have to validate the conversion, see cppreference.com - std::stoi and note the Exception heading detailing the two exception (std::invalid_argument and std::out_of_range) that must be handled. You cannot simply guess that all input files will be in the needed format with the correct values and hope for the best -- you must validate every input.

This applies to the number of columns in each row as well (and the number of rows filled when your read-loop is done). When you are done reading from the stringstring, you need to validate the number of column-values read is the number expected and that you have not encountered a short row. Note: these are the minimum-validations needed. You are free to write additional validations such as to check to ensure the stringstring is empty and that additional valued do not remain unread (not critical to the operation of the code, but may flag an invalidly formatted input file)

Lastly, while the remainder of the code simply outputs the values, take a look at Why is “using namespace std;” considered bad practice?. Develop good habits early. That also means Don't Hardcode Filenames. The arguments to main() provide a way to pass needed information into your program on startup -- use them, or at minimum, prompt for the filename to open.

Further, always compile with warnings enabled. That means -Wall -Wextra -pedantic -Wshadow for gcc/clang and for VS /W3. Including -Wshadow you would find that you shadow the previous declaration for variable c in for (int c=0; c<col; c++)

Putting it altogether, you could do something similar to:

#include <iostream>
#include <sstream>
#include <string>
#include <fstream>

#define ROW 4       /* while const int is fine, if you #define your constants  */
#define COL ROW     /* you have one single location at the top to make changes */

int main (int argc, char **argv) {

    const int row = ROW, col = COL; /* optional, you can just use ROW & COL */
    int array[row][col], r = 0;
    std::string line;

    if (argc < 2) { /* validate at least 1 argument given for filename */
        std::cerr << "error: insufficient arguments\nusage: ./prog filename\n";
        return 1;
    }

    std::ifstream inputfile (argv[1]);  /* open file provided as 1st argument */
    if (!inputfile.is_open()) { /* use std::cerr for error output, handle error */
        std::cerr << "error: file open failed '" << argv[1] << "'.\n";
        return 1;
    }

    /* read each line, protect row bounds */
    while (r < row && getline (inputfile,line)) {
        int c = 0;      /* declare c local to loop so it is reset each iteration */
        std::string num;
        std::stringstream ss (line);
        /* loop reading from stringstream, protect column bounds */
        while (c < col && getline (ss, num, ',')) {
            try {   /* try/catch exception handling required for stoi conversion */
                array[r][c++] = std::stoi (num);    /* convert, increment col count */
            }
            catch (const std::exception & e) {
                std::cerr << "error: invalid conversion " << e.what() << '\n';
                return 1;
            }
        }
        if (c != col) { /* validate col number of values read & stored */
            std::cerr << "error: invalid number of columns '" << c << "' row: "
                        << r << '\n';
            return 1;
        }
        r++;    /* increment row count */
    }

    if (r < row) {  /* validate row number of arrays stored in 2D array */
        std::cerr << "error: invalid number of rows '" << r << "'\n";
        return 1;
    }

    for (r = 0; r < row; r++) {         /* loop outputting results */
        for (int c = 0; c < col; c++)
            std::cout << " " << array[r][c];
        std::cout << '\n';
    }
}

(note: the #define statements are optional, but provide a convenient place at the top of your code to adjust your constants if the need arises)

Example Use/Output

While your input file in dat/2darr.csv, you would execute and receive the following output:

$ ./bin/read2darrcsv dat/2darr.csv
 2 4 5 6
 3 7 5 3
 4 8 4 2
 6 7 3 0

Let me know if you have further questions.


问:
How to use Kuzzle & GraphQL & Apollo & Realtime
I'm developing a set of services / applications to allow to manage Archery Tournaments.
It consist on a web application that would manage the creation of different tournaments, and will handle the subscription of archers as contenders, mailing and classifications. And a mobile application that will be installed into several tablets that are going to be used for annotate each archer arrow point in realtime during the tournament.

This last part will be deploy and used in a local network that won't have external internet access (although it will be able to connect to retrieve the tournament data).
So I decided to use kuzzle (https://kuzzle.io/) as backend as I could deploy it on site, developing the web app in angular and the realtime capabilities.

The only think that is not covered is to have offline capabilities, so if the annotation tablets lost connection to the kuzzle server the archers must still be able to take note of the points.
So one of the solutions is to define a GraphQl endpoint into kuzzle (https://github.com/kuzzleio/kuzzle-plugin-graphql) and using a Graphql client that would allow some kind of offline cache like https://www.apollographql.com/ but I will still miss the realtime syncronization that kuzzle provides.

Is there any way / idea on how to map from the apollo graphql queries to kuzzle runtime so the later could update the apollo cache?
Is any other configuration better?

答:
Kuzzle core team member here.

TL;DR - GQL Live Subscriptions aren't supported yet by Kuzzle. You can use the Kuzzle Realtime engine to subscribe to data and retrigger GQL queries.

The current offline capabilities the Kuzzle SDK offers enable you to recover a live subscription upon reconnection and to replay enqueued actions that couldn't be sent to the server while offline, but has actually no opinion (nor tool) on how you should handle unsynced data.

In this situation, it is complex to have two datastores (the backend and the frontend) that might not be in sync (due to limited connectivity), specially if you need to query the data.

Many frontend DB solutions exist, but they imply you should double the queries on each data-fetch (with different DSLs) then reconciliate the results, as they might differ. It's not impossible, but it's an effort.

This is a good motivation to use GraphQL in conjunction with Kuzzle, which is a good take, but the GraphQL Live Queries aren't supported yet, so you won't be able to use GQL queries to express your realtime subscription filters. The core team is actively considering supporting them during this year.

A workaround is to give up the GQL Live-Queries for the moment and make your subscriptions using Kuzzle (via the realtime.subscribe call). Each time the subscription receives a notification, it would re-trigger the GQL query to fetch the fresh dataset. The only overhead would be that your subscription filter must be expressed in the Koncorde DSL, which might be annoying at scale, but IMHO, still viable.


问:
How can I get image from api rest using reactjs
I am developping an application which is based on Images, first I save data (title, description, images...) on mySql database using API rest and spring boot in the backend, I need to show and display what I saved I use react as a frondend on other hand I use "react-images-upload"to upload, preview and handle images.
Until this instance this what I did in my code react:

item.js:

```<code>import React, { useState, Component } from 'react';
import axios from 'axios';
import ItemList from './itemList'

class Item extends Component{

        constructor(props){
            super(props);
            this.state={
                items:[],
                ...//others
            }
        }

        componentDidMount(){
            this.getItems();
          }

        getItems(){
            const url="MY_API_URL";
            axios({
                method: 'get',
                dataType: 'json',
                url: 'URL',
                headers: { 'Accept': 'application/json',
                'Content-Type': 'application/json' }
    }).then((resp:AxiosResponse<T>)=>{
                console.log(resp.data);//on my browser's console I get:[object Object],[object Object]
                console.log(resp.data.photo);//on my browser's console I get:undefined
                this.setState({
                    items:resp.data
                });

            }).catch((err=>{
                console.log(err);
            }));

        }

    render(){
        return (
            <div className="">
                <div className="row">
                {
                    this.state.items.map(item=>
                        <ItemList item={item}/>
                    )
                }
                </div>
            </div>
        );
    }
}
export default Item;
</code>```

itemList.js:

```<code>import React, { Component } from 'react';

class itemList extends Component {
    constructor(props){
        super(props);
    }

    render() {
        return (
           <div className="col-md-4" key={this.props.item.id}>
                <div className="card">
                 <div className="card-header">{this.props.item.title}</div>
                 <div className="card-body">
                   {this.props.item.photo.map(photo=><img src={photo} />=)}{/* I can't display the image! */}
                 </div>
                </div>
          </div>
        );
    }
}
export default itemList;
</code>```

I get this result:

And this is how images stored on my database:

Please can someone help me to dispolay images from database

Edit1: the response from api request look like :

```<code>        "id": 1,
        "title": "test with pic 3",
        "description": "descp how are you",
        "photo": [
            "[object File]",
            "[object File]",
            "[object File]"
        ]
</code>```

答:
The problem is, that it is a Blob you are sending. Looking at the picture it looks like MySQL. You have to transform it on your server-side code because only MySQL knows what a Blob is.. React doesn't.

Solution 1: Base64, you can transform the blob into a base64 string on your server, and then you can actually just keep all of your code. Then you will just have a very long string, which is a string representation of your image. A regular jsx  tag will be sufficient.

Solution 2: Serving image statically, you can also make your server serve the images in a static fashion, similarly, if you go to a website, and see an image, you can see some URL, where the image is stored. You can do this with most server-side technologies or on the cloud. Then you can just pass the image URL to your React client, and it will work.

Let me know if you have any more questions.

Body:
I am developping an application which is based on Images, first I save data (title, description, images...) on mySql database using API rest and spring boot in the backend, I need to show and display what I saved I use react as a frondend on other hand I use "react-images-upload"to upload, preview and handle images.
Until this instance this what I did in my code react:

item.js:

import React, { useState, Component } from 'react';
import axios from 'axios';
import ItemList from './itemList'

class Item extends Component{

        constructor(props){
            super(props);
            this.state={
                items:[],
                ...//others
            }
        }

        componentDidMount(){
            this.getItems();
          }

        getItems(){
            const url="MY_API_URL";
            axios({
                method: 'get',
                dataType: 'json',
                url: 'URL',
                headers: { 'Accept': 'application/json',
                'Content-Type': 'application/json' }
    }).then((resp:AxiosResponse<T>)=>{
                console.log(resp.data);//on my browser's console I get:[object Object],[object Object]
                console.log(resp.data.photo);//on my browser's console I get:undefined
                this.setState({
                    items:resp.data
                });

            }).catch((err=>{
                console.log(err);
            }));

        }

    render(){
        return (

                {
                    this.state.items.map(item=>
                        <ItemList item={item}/>
                    )
                }

        );
    }
}
export default Item;

itemList.js:

import React, { Component } from 'react';

class itemList extends Component {
    constructor(props){
        super(props);
    }

    render() {
        return (

{this.props.item.title}

                   {this.props.item.photo.map(photo=>=)}{/* I can't display the image! */}

        );
    }
}
export default itemList;

I get this result:

And this is how images stored on my database:

Please can someone help me to dispolay images from database

Edit1: the response from api request look like :

        "id": 1,
        "title": "test with pic 3",
        "description": "descp how are you",
        "photo": [
            "[object File]",
            "[object File]",
            "[object File]"
        ]

Body:
The problem is, that it is a Blob you are sending. Looking at the picture it looks like MySQL. You have to transform it on your server-side code because only MySQL knows what a Blob is.. React doesn't.

Solution 1: Base64, you can transform the blob into a base64 string on your server, and then you can actually just keep all of your code. Then you will just have a very long string, which is a string representation of your image. A regular jsx <img src={} /> tag will be sufficient.

Solution 2: Serving image statically, you can also make your server serve the images in a static fashion, similarly, if you go to a website, and see an image, you can see some URL, where the image is stored. You can do this with most server-side technologies or on the cloud. Then you can just pass the image URL to your React client, and it will work.

Let me know if you have any more questions.


答:
Try this :</p>

```<code>import sys
import time

for i in range(10):
    sys.stdout.write("\rFailed: {}".format(i))
    sys.stdout.flush()
    time.sleep(0.5)
</code>```

Title: Noob Question How would I update a print a function's output without creating a new line in my term in python3?

Body:
I'm not exactly sure how to word this to be honest, but here's a simplified version of my current code.

for idx in range(0,11):
    print('Failed:',idx)

This outputs:

Failed: 0
Failed: 1
Failed: 2
Failed: 3
Failed: 4
Failed: 5
Failed: 6
Failed: 7
Failed: 8
Failed: 9
Failed: 10

I'm trying to replace the original int with the next int in the range instead of spamming my terminal with a new line for every int in the range.

How could I update "Failed: 1" to "Failed: 2" without creating a new line for "Failed: 2"?

Sorry if this is poorly worded, if you're willing to help me but like me to elaborate further please say so and I will try my best.

Body:
Try this :

import sys
import time

for i in range(10):
    sys.stdout.write("\rFailed: {}".format(i))
    sys.stdout.flush()
    time.sleep(0.5)


问:
How can I represent a 2-dimensional array in Protocol Buffers?
How can I represent a 2-dimensional array in Protocol Buffers?

I need to store int and double 2d arrays as a field on a PB message, for example:

```<code>int[][] multi = new int[5][10];
</code>```

I'm using C++, Java and C#.

Thanks in advance.

答:
It does not work.

I look up the grpc guide, which just supports the key-value structure. I advise you:

```<code>
message ListResp {
   repeated Array list = 1;

}

message Array{
     int64 id = 1; //
    string name = 2; //
}
</code>```

ContentLicense: CC BY-SA 3.0

Body:
How can I represent a 2-dimensional array in Protocol Buffers?

I need to store int and double 2d arrays as a field on a PB message, for example:

int[][] multi = new int[5][10];

I'm using C++, Java and C#.

Thanks in advance.

Body:
It does not work.

I look up the grpc guide, which just supports the key-value structure. I advise you:

message ListResp {
   repeated Array list = 1;

}

message Array{
     int64 id = 1; //
    string name = 2; //
}


问:
Optional spaces \s+? are not honoured in regular expression
I am expecting the following regex to allow 0-n spaces between operators, but it is forcing at least one. Can someone please correct the error of my ways?

```<code>((\d+\.?\d*|\d*\.?\d+\s+?[\+\-\/\*]\s+?)+)(\d+\.?\d*|\d*\.?\d+)
</code>```

Examples

```<code>24*3.2
24 * 3.2
</code>```

Only the 2nd example is allowed through.

I understood \s+? should be an optional number of spaces?

Playpen

答:
What you need is \s*, i.e., 0 or more white spaces.
Your \s+? says 1 or more white spaces and non greedy match for spaces.
The ? modifier after * or + means non-greedy match.

Body:
I am expecting the following regex to allow 0-n spaces between operators, but it is forcing at least one. Can someone please correct the error of my ways?

((\d+\.?\d*|\d*\.?\d+\s+?[\+\-\/\*]\s+?)+)(\d+\.?\d*|\d*\.?\d+)

Examples

24*3.2
24 * 3.2

Only the 2nd example is allowed through.

I understood \s+? should be an optional number of spaces?

Playpen


问:
How to draw a line cube with OpenGL?
Im trying to draw a cube with lines.

And here's my code. It just gives me a white frame with nothing inside it. Nothing happens. What am I doing wrong here? Is it a problem with the order of calling out the functions or something wrong with the projection?

```<code>
def myInit():
    glClearColor(0.0, 0.0, 0.0, 1.0)
    glColor3f(0.2, 0.5, 0.4)
    gluPerspective(45, 1.33, 0.1, 50.0)

vertices= (
    (100, -100, -100),
    (100, 100, -100),
    (-100, 100, -100),
    (-100, -100, -100),
    (100, -100, 100),
    (100, 100, 100),
    (-100, -100, 100),
    (-100, 100, 100)
    )

edges = (
    (0,1),
    (0,3),
    (0,4),
    (2,1),
    (2,3),
    (2,7),
    (6,3),
    (6,4),
    (6,7),
    (5,1),
    (5,4),
    (5,7)
    )

def Display():
    glBegin(GL_LINES)
    for edge in edges:
        for vertex in edge:
            glVertex3fv(vertices[vertex])
    glEnd()

glutInit()
glutInitDisplayMode(GLUT_SINGLE | GLUT_RGB)
glutInitWindowSize(800, 600)
myInit()
glutDisplayFunc(Display)
glutMainLoop()

</code>```

答:
All the geometry which is not in the Viewing frustum is clipped. The size of the cube i 200x200x200. You've to create a viewing frustum which is large enough.

For instance set a perspective projection matrix gluPerspective with a far plane of 1000.0. The projection matrix is intended to be set to the current projection matrix (GL_PROJECTION). See glMatrixMode:

glMatrixMode(GL_PROJECTION)
glLoadIdentity()
gluPerspective(45, 1.33, 0.1, 1000.0)

Translate ([`glTranslate`](https://www.khronos.org/registry/OpenGL-Refpages/gl2.1/xhtml/glTranslate.xml)) the model along the negative z axis, in between the near plane (0.1) and far (plane). The model or view matrix has to be set to the current model view matrix (`GL_MODELVIEW`):

```py
glMatrixMode(GL_MODELVIEW)
glLoadIdentity()
glTranslate(0, 0, -500)
</code>```

Clear the display in every frame by glClear:

def Display():
    glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT)

    # [...]
```
<p>Swaps the buffers of the current double buffered window by <code>glutSwapBuffers</code> and continuously update the display by invoking <code>glutPostRedisplay</code>.</p>
<pre class="lang-py prettyprint-override"><code>def Display():
    # [...]

    glutSwapBuffers()
    glutPostRedisplay()
</code>```

See also Immediate mode and legacy OpenGL

See the example:

def init():
    glClearColor(0.0, 0.0, 0.0, 1.0)

    glMatrixMode(GL_PROJECTION)
    glLoadIdentity()
    gluPerspective(45, 1.33, 0.1, 1000.0)

    glMatrixMode(GL_MODELVIEW)
    glLoadIdentity()
    glTranslate(0, 0, -500)

def Display():
    glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT)

    glColor3f(0.2, 0.5, 0.4)
    glBegin(GL_LINES)
    for edge in edges:
        for vertex in edge:
            glVertex3fv(vertices[vertex])
    glEnd()

    glutSwapBuffers()
    glutPostRedisplay()
```

Title: How to draw a line cube with OpenGL?

Body:
Im trying to draw a cube with lines.

And here's my code. It just gives me a white frame with nothing inside it. Nothing happens. What am I doing wrong here? Is it a problem with the order of calling out the functions or something wrong with the projection?

def myInit():
    glClearColor(0.0, 0.0, 0.0, 1.0)
    glColor3f(0.2, 0.5, 0.4)
    gluPerspective(45, 1.33, 0.1, 50.0)

vertices= (
    (100, -100, -100),
    (100, 100, -100),
    (-100, 100, -100),
    (-100, -100, -100),
    (100, -100, 100),
    (100, 100, 100),
    (-100, -100, 100),
    (-100, 100, 100)
    )

edges = (
    (0,1),
    (0,3),
    (0,4),
    (2,1),
    (2,3),
    (2,7),
    (6,3),
    (6,4),
    (6,7),
    (5,1),
    (5,4),
    (5,7)
    )

def Display():
    glBegin(GL_LINES)
    for edge in edges:
        for vertex in edge:
            glVertex3fv(vertices[vertex])
    glEnd()

glutInit()
glutInitDisplayMode(GLUT_SINGLE | GLUT_RGB)
glutInitWindowSize(800, 600)
myInit()
glutDisplayFunc(Display)
glutMainLoop()

Body:
All the geometry which is not in the Viewing frustum is clipped. The size of the cube i 200x200x200. You've to create a viewing frustum which is large enough.

For instance set a perspective projection matrix gluPerspective with a far plane of 1000.0. The projection matrix is intended to be set to the current projection matrix (GL_PROJECTION). See glMatrixMode:

glMatrixMode(GL_PROJECTION)
glLoadIdentity()
gluPerspective(45, 1.33, 0.1, 1000.0)

Translate ([`glTranslate`](https://www.khronos.org/registry/OpenGL-Refpages/gl2.1/xhtml/glTranslate.xml)) the model along the negative z axis, in between the near plane (0.1) and far (plane). The model or view matrix has to be set to the current model view matrix (`GL_MODELVIEW`):

```py
glMatrixMode(GL_MODELVIEW)
glLoadIdentity()
glTranslate(0, 0, -500)

Clear the display in every frame by glClear:

def Display():
    glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT)

    # [...]

Swaps the buffers of the current double buffered window by glutSwapBuffers and continuously update the display by invoking glutPostRedisplay.

def Display():
    # [...]

    glutSwapBuffers()
    glutPostRedisplay()

See also Immediate mode and legacy OpenGL

See the example:

def init():
    glClearColor(0.0, 0.0, 0.0, 1.0)

    glMatrixMode(GL_PROJECTION)
    glLoadIdentity()
    gluPerspective(45, 1.33, 0.1, 1000.0)

    glMatrixMode(GL_MODELVIEW)
    glLoadIdentity()
    glTranslate(0, 0, -500)

def Display():
    glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT)

    glColor3f(0.2, 0.5, 0.4)
    glBegin(GL_LINES)
    for edge in edges:
        for vertex in edge:
            glVertex3fv(vertices[vertex])
    glEnd()

    glutSwapBuffers()
    glutPostRedisplay()


问:
Format a number to string, fill 0 when it's not enough two characters
I want to format the number to String and fill 0 when it's not enough two characters

```<code>fun formatDuration(val duration):String {
    val minutes = duration.toInt() / 60
    return  "$minutes"
}
</code>```

For example, if minutes is 6， it should displayed 06 rather than 6.

答:
You can padStart the toString() result of minutes.

I tried your code in the Kotlin Playground and it wasn't compilable / runnable. For the following example, I had to change parts of your fun:

```<code>fun main() {
    println(formatDuration(364.34))
}

fun formatDuration(duration: Double): String {
    val minutes = duration.toInt() / 60
    // fill the result to be of 2 characters, use 0 as padding char
    return minutes.toString().padStart(2, '0')
}
</code>```

Executing this results in the output 06.

Alternatively, you can simply use String.format() from Java, just

return "%02d".format(minutes)
```

instead of return minutes.toString().padStart(2, '0'), the result stays the same.

Body:
I want to format the number to String and fill 0 when it's not enough two characters

fun formatDuration(val duration):String {
    val minutes = duration.toInt() / 60
    return  "$minutes"
}

For example, if minutes is 6， it should displayed 06 rather than 6.

Body:
You can padStart the toString() result of minutes.

I tried your code in the Kotlin Playground and it wasn't compilable / runnable. For the following example, I had to change parts of your fun:

fun main() {
    println(formatDuration(364.34))
}

fun formatDuration(duration: Double): String {
    val minutes = duration.toInt() / 60
    // fill the result to be of 2 characters, use 0 as padding char
    return minutes.toString().padStart(2, '0')
}

Executing this results in the output 06.

Alternatively, you can simply use String.format() from Java, just

return "%02d".format(minutes)

instead of return minutes.toString().padStart(2, '0'), the result stays the same.


问:
What is a service mesh?
In the context of cloud computing, backend developers frequently refer to building (or using) "service mesh" but I don't fully understand what it is. Can you tell more?</p>

答:
The term service mesh is used to describe the network of microservices that make up such applications and the interactions between them [src].
Service mesh enables managed, observable, and secure communication across your services, letting you create robust enterprise applications made up of many microservices on your chosen infrastructure.

A service mesh architecture uses a proxy instance called a sidecar in whichever development paradigm is in use, commonly containers and/or microservices. In a microservice application, a sidecar will attach to each service. In a container, the sidecar is attached to each application container, VM or container orchestration unit, such as a Kubernetes pod [src].

Sidecar Proxy : A sidecar proxy runs alongside a single instance or pod. Sidecars can handle tasks abstracted from the service itself, such as route, or proxy, traffic to and from the container it runs alongside, monitoring and security. Sidecars and their interactions make up what is called the data plane in a service mesh.

Control Plane : The control plane manages tasks such as creating instances, monitoring and implementing policies for network management and security. Control planes can connect to a CLI or a GUI interface for application management [src].

img src

Title: What is a service mesh?


问:
Java 8 : how to extract a HashMap from a ArrayList of HashMap in Java 8 using streams?
I have the following sample result when I query a database :

```<code>dataList  = [{ name : name1, rollno: rollno1 }, { name : name2, rollno: rollno2 } ]
</code>```

I want to convert this list of hashmaps into a single hashmap using Java 8 streams.
I tried using Collectors.toMap() but i am not sure how to refer to rollNo as key and the hashmap as the value inside the toMap method.

Exected output :

```<code>{ rollno1 : { name : name1, rollno: rollno1 } , rollno2 : { name : name2, rollno: rollno2 } }
</code>```

I tried doing it using a for each loop on the list and then adding the rollno as key to a hashmap and the hashmap as value itself of that rollno.

```<code>
    HashMap<String,HashMap<String,String>> newMap = new HashMap();

    for(HashMap<String,String> record : dataList){
        String key = record.get("rollno").toString();
        newMap.put(key,record);
    }

</code>```

Is there a way to refactor this code using functional streams in Java 8?
Will using streams collect method give any performance advantage over the foreach for doing this?

Will appreciate any leads. Thanks

答:
Probably something like this:

```<code>Map<RollNo, List<Roll>> rollsPerType = rolls.stream()
  .collect(groupingBy(Roll::getRollNo));
</code>```

where Roll is the main object and RollNo is the property inside (since you didn't provide the actual definitions).

Body:
I have the following sample result when I query a database :

dataList  = [{ name : name1, rollno: rollno1 }, { name : name2, rollno: rollno2 } ]

I want to convert this list of hashmaps into a single hashmap using Java 8 streams.
I tried using Collectors.toMap() but i am not sure how to refer to rollNo as key and the hashmap as the value inside the toMap method.

Exected output :

{ rollno1 : { name : name1, rollno: rollno1 } , rollno2 : { name : name2, rollno: rollno2 } }

I tried doing it using a for each loop on the list and then adding the rollno as key to a hashmap and the hashmap as value itself of that rollno.

    HashMap<String,HashMap<String,String>> newMap = new HashMap();

    for(HashMap<String,String> record : dataList){
        String key = record.get("rollno").toString();
        newMap.put(key,record);
    }

Is there a way to refactor this code using functional streams in Java 8?
Will using streams collect method give any performance advantage over the foreach for doing this?

Will appreciate any leads. Thanks

Body:
Probably something like this:

Map<RollNo, List<Roll>> rollsPerType = rolls.stream()
  .collect(groupingBy(Roll::getRollNo));

where Roll is the main object and RollNo is the property inside (since you didn't provide the actual definitions).


问:
C++ - How to use a stream to parse a file?
I have a file and I need to loop through it assigning an int foo, string type, 64/128 bit long. How would I use a stream to parse these lines into the following variables - I want to stick with the stream syntax ( ifs >> foo >> type ) but in this case type would end up being the rest of the line after the 0/52 ... and at that point I'd just get a char* and use strtoull and such so why use the stream in the first place... I'm hoping for readable code without horrid performance over char strings / strtok / strtoull </p>

```<code>//input file:
0ULL'04001C0180000000000000000EE317BC'
52L'04001C0180000000'
//ouput:
//0 ULL 0x04001C0180000000 0x000000000EE317BC
//52 L 0x04001C0180000000

  ifstream ifs("input.data");
  int foo;
  string type;
  unsigned long long ull[2];
</code>```

答:
Boost Spirit implementation

Here is the mandatory Boost Spirit (Qi) based implementation. For good measure, including formatting using Boost Spirit (Karma):

```<code>#include <string>
#include <iostream>
#include <fstream>
#include <boost/spirit/include/qi.hpp>
#include <boost/spirit/include/karma.hpp>

namespace karma=boost::spirit::karma;
namespace qi   =boost::spirit::qi;

static qi::uint_parser<unsigned long long, 16, 16, 16> hex16_p; // parse long hex
static karma::uint_generator<unsigned long long, 16>   hex16_f; // format long hex

int main(int argc, char** args)
{
    std::ifstream ifs("input.data");
    std::string line;
    while (std::getline(ifs, line))
    {
        std::string::iterator begin = line.begin(), end = line.end();

        int                             f0;
        std::string                     f1;
        std::vector<unsigned long long> f2;

        bool ok = parse(begin, end,
                qi::int_                    // an integer
                >> *qi::alpha               // alternatively: *(qi::char_ - '\'')
                >> '\'' >> +hex16_p >> '\'' // accepts 'n x 16' hex digits
            , f0, f1, f2);

        if (ok)
            std::cout << "Parsed: " << karma::format(
                 karma::int_
                 << ' ' << karma::string
                 << ' ' << ("0x" << hex16_f) % ' '
             , f0, f1, f2) << std::endl;
        else
            std::cerr << "Parse failed: " << line << std::endl;
    }

    return 0;
}
</code>```

Test run:

```<code>Parsed: 0 ULL 0x4001c0180000000 0xee317bc
Parsed: 52 L 0x4001c0180000000
</code>```

see Tweaks and samples below for info on how to tweak e.g. hex output

Benchmark

I had benchmarked @Cubbi's version and the above as written on 100,000x the sample inputs you provided. This initially gave Cubbi's version a slight advantage: 0.786s versus 0.823s.

Now, that of course wasn't fair comparison, since my code is constructing the parser on the fly each time. With that taken out of the loop like so:

```<code>typedef std::string::iterator It;

const static qi::rule<It> parser = qi::int_ >> *qi::alpha >> '\'' >> +hex16_p >> '\'';
bool ok = parse(begin, end, parser, f0, f1, f2);
</code>```

Boost Spirit comes out a clear winner with only 0.093s; already a factor 8.5x faster, and that is even with the karma formatter still being constructed each iteration.

with the output formatting commented out in both versions, Boost Spirit is >11x faster

Tweaks, samples

Note how you can easily tweak things:

```<code>//  >> '\'' >> +hex16_p >> '\'' // accepts 'n x 16' hex digits
    >> '\'' >> qi::repeat(1,2)[ hex16_p ] >> '\'' // accept 16 or 32 digits
</code>```

Or format the hex output just like the input:

```<code>// ("0x" << hex16_f) % ' '
karma::right_align(16, '0')[ karma::upper [ hex16_f ] ] % ""
</code>```

Changed sample output:

```<code>0ULL'04001C0180000000000000000EE317BC'
Parsed: 0 ULL 04001C0180000000000000000EE317BC
52L'04001C0180000000'
Parsed: 52 L 04001C0180000000
</code>```

HTH

Body:
I have a file and I need to loop through it assigning an int foo, string type, 64/128 bit long. How would I use a stream to parse these lines into the following variables - I want to stick with the stream syntax ( ifs >> foo >> type ) but in this case type would end up being the rest of the line after the 0/52 ... and at that point I'd just get a char* and use strtoull and such so why use the stream in the first place... I'm hoping for readable code without horrid performance over char strings / strtok / strtoull

//input file:
0ULL'04001C0180000000000000000EE317BC'
52L'04001C0180000000'
//ouput:
//0 ULL 0x04001C0180000000 0x000000000EE317BC
//52 L 0x04001C0180000000

  ifstream ifs("input.data");
  int foo;
  string type;
  unsigned long long ull[2];

Body:
Boost Spirit implementation

Here is the mandatory Boost Spirit (Qi) based implementation. For good measure, including formatting using Boost Spirit (Karma):

#include <string>
#include <iostream>
#include <fstream>
#include <boost/spirit/include/qi.hpp>
#include <boost/spirit/include/karma.hpp>

namespace karma=boost::spirit::karma;
namespace qi   =boost::spirit::qi;

static qi::uint_parser<unsigned long long, 16, 16, 16> hex16_p; // parse long hex
static karma::uint_generator<unsigned long long, 16>   hex16_f; // format long hex

int main(int argc, char** args)
{
    std::ifstream ifs("input.data");
    std::string line;
    while (std::getline(ifs, line))
    {
        std::string::iterator begin = line.begin(), end = line.end();

        int                             f0;
        std::string                     f1;
        std::vector<unsigned long long> f2;

        bool ok = parse(begin, end,
                qi::int_                    // an integer
                >> *qi::alpha               // alternatively: *(qi::char_ - '\'')
                >> '\'' >> +hex16_p >> '\'' // accepts 'n x 16' hex digits
            , f0, f1, f2);

        if (ok)
            std::cout << "Parsed: " << karma::format(
                 karma::int_
                 << ' ' << karma::string
                 << ' ' << ("0x" << hex16_f) % ' '
             , f0, f1, f2) << std::endl;
        else
            std::cerr << "Parse failed: " << line << std::endl;
    }

    return 0;
}

Test run:

Parsed: 0 ULL 0x4001c0180000000 0xee317bc
Parsed: 52 L 0x4001c0180000000

see Tweaks and samples below for info on how to tweak e.g. hex output

Benchmark

I had benchmarked @Cubbi's version and the above as written on 100,000x the sample inputs you provided. This initially gave Cubbi's version a slight advantage: 0.786s versus 0.823s.

Now, that of course wasn't fair comparison, since my code is constructing the parser on the fly each time. With that taken out of the loop like so:

typedef std::string::iterator It;

const static qi::rule<It> parser = qi::int_ >> *qi::alpha >> '\'' >> +hex16_p >> '\'';
bool ok = parse(begin, end, parser, f0, f1, f2);

Boost Spirit comes out a clear winner with only 0.093s; already a factor 8.5x faster, and that is even with the karma formatter still being constructed each iteration.

with the output formatting commented out in both versions, Boost Spirit is >11x faster

Tweaks, samples

Note how you can easily tweak things:

//  >> '\'' >> +hex16_p >> '\'' // accepts 'n x 16' hex digits
    >> '\'' >> qi::repeat(1,2)[ hex16_p ] >> '\'' // accept 16 or 32 digits

Or format the hex output just like the input:

// ("0x" << hex16_f) % ' '
karma::right_align(16, '0')[ karma::upper [ hex16_f ] ] % ""

Changed sample output:

0ULL'04001C0180000000000000000EE317BC'
Parsed: 0 ULL 04001C0180000000000000000EE317BC
52L'04001C0180000000'
Parsed: 52 L 04001C0180000000

HTH


问:
Determine if react component is null
I have a component that renders if some conditions are met, otherwise it returns null.

I'd like to know how to determine if the component is returning null from its parent.

I have tried logging the component to see what properties are changing when it is rendered or when returning null but can not detect any difference.

Any suggestions?

答:
You can just use a fallback prop.

Instead of:

function Child(){
 if(something) return null

 return
content

}

function Parent(){
 // try to find out if child is null
 return <Child />
}
```

<p>Just do:</p>

<pre class="lang-js prettyprint-override"><code>function Child({ fallback = null }){
 if(something) return fallback

 return <div>content</div>
}

function Fallback() {
 return 'some fallback'
}

function Parent(){
 return <Child fallback={<Fallback />} />
}
</code>```

Title: Determine if react component is null

Body:
You can just use a fallback prop.

Instead of:

function Child(){
 if(something) return null

 return <div>content</div>
}

function Parent(){
 // try to find out if child is null
 return <Child />
}

Just do:

function Child({ fallback = null }){
 if(something) return fallback

 return <div>content</div>
}

function Fallback() {
 return 'some fallback'
}

function Parent(){
 return <Child fallback={<Fallback />} />
}


问:
Insert different HTML based on switch statement
I have this element in a form:

```<code><a id="dyLink" href="">
</code>```

Depending on calculation of the form the href tag changes depending on different cases:

switch (week) {
  case 1:
    link = "https://schwangerschaftswochen.ch/die-erste-schwangerschaftswoche/";
    break;
  case 2:
    link = "https://schwangerschaftswochen.ch/die-zweite-schwangerschaftswoche/";
    break;
  case 3:
    link = "https://schwangerschaftswochen.ch/die-dritte-schwangerschaftswoche/";
    break;
  case 4:
    link = "https://schwangerschaftswochen.ch/die-vierte-schwangerschaftswoche/";
    break;
  case 5:
    link = "https://schwangerschaftswochen.ch/geburtsterminrechner/#lepopup-Newsletteranmeldung";
}

jQuery("#dyLink").attr("href", link)
```

However I don't want to have different links, but different HTML elements for every case. I have no idea about coding. How can I do it?

答:
include the html you want to put in every case :

E.g:

HTML: where you want to put the HTML :

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

JS:

```<code>    switch(week)
                {
                    case 1:
                    document.getElementById("mydiv").innerHTML="<a href='case1.com' id='case1' >"
                    break;
                    case 2:
                    document.getElementById("mydiv").innerHTML="<a href='case2.com' id='case2' >"
                    break;
}
</code>```

Body:
I have this element in a form:

Depending on calculation of the form the href tag changes depending on different cases:

switch (week) {
  case 1:
    link = "https://schwangerschaftswochen.ch/die-erste-schwangerschaftswoche/";
    break;
  case 2:
    link = "https://schwangerschaftswochen.ch/die-zweite-schwangerschaftswoche/";
    break;
  case 3:
    link = "https://schwangerschaftswochen.ch/die-dritte-schwangerschaftswoche/";
    break;
  case 4:
    link = "https://schwangerschaftswochen.ch/die-vierte-schwangerschaftswoche/";
    break;
  case 5:
    link = "https://schwangerschaftswochen.ch/geburtsterminrechner/#lepopup-Newsletteranmeldung";
}

jQuery("#dyLink").attr("href", link)

However I don't want to have different links, but different HTML elements for every case. I have no idea about coding. How can I do it?

Body:
include the html you want to put in every case :

E.g:

HTML: where you want to put the HTML :

<div class="mydiv"></div>

JS:

    switch(week)
                {
                    case 1:
                    document.getElementById("mydiv").innerHTML="<a href='case1.com' id='case1' >"
                    break;
                    case 2:
                    document.getElementById("mydiv").innerHTML="<a href='case2.com' id='case2' >"
                    break;
}


问:
How to make tkinter counter when click on botton
i'm beginner for python i try to make counter when click on button but its not working as i expect

what i really need when i click on button its will add number like 1,2,3 but this result is 1111111

```<code>from tkinter import *

root = Tk()
root.title("Counter")
root.geometry("100x100")

def count():
    c = 0
    c += 1
    entry.insert(0,c)

button = Button(text="Count",command = count,)
label = Label(text="Time")
entry = Entry(root)
label.pack(side = TOP , pady = 5)
entry.pack(side = TOP , pady = 5)
button.pack(side=TOP , pady = 5)
mainloop()
</code>```

答:
You need to keep track of the value of c, the number of clicks - this can be done with a closure, created with a mutable default parameter in the example below.

You also need to delete the text displayed in the entry, prior to displaying the new value:

```<code>import tkinter as tk

def count(_c=[0]):   # <-- this creates a closure that keeps track of the number of clicks.
    _c[0] += 1
    entry.delete(0, tk.END)
    entry.insert(0, _c[0])

root = tk.Tk()
root.title("Counter")
root.geometry("100x100")

button = tk.Button(text="Count", command=count)
label = tk.Label(text="Time")

entry = tk.Entry(root)

label.pack(side=tk.TOP , pady=5)
entry.pack(side=tk.TOP , pady=5)
button.pack(side=tk.TOP , pady=5)

mainloop()
</code>```

Alternatively, you could keep track of the value of c if you create it in the global namespace, and declare it global in the function.

```<code>import tkinter as tk

def count():
    global c
    c += 1
    entry.delete(0, tk.END)
    entry.insert(0, c)

c = 0

root = tk.Tk()
root.title("Counter")
root.geometry("100x100")

button = tk.Button(text="Count", command=count)
label = tk.Label(text="Time")

entry = tk.Entry(root)

label.pack(side=tk.TOP , pady=5)
entry.pack(side=tk.TOP , pady=5)
button.pack(side=tk.TOP , pady=5)

mainloop()
</code>```

Body:
i'm beginner for python i try to make counter when click on button but its not working as i expect

what i really need when i click on button its will add number like 1,2,3 but this result is 1111111

from tkinter import *

root = Tk()
root.title("Counter")
root.geometry("100x100")

def count():
    c = 0
    c += 1
    entry.insert(0,c)

button = Button(text="Count",command = count,)
label = Label(text="Time")
entry = Entry(root)
label.pack(side = TOP , pady = 5)
entry.pack(side = TOP , pady = 5)
button.pack(side=TOP , pady = 5)
mainloop()

Body:
You need to keep track of the value of c, the number of clicks - this can be done with a closure, created with a mutable default parameter in the example below.

You also need to delete the text displayed in the entry, prior to displaying the new value:

import tkinter as tk

def count(_c=[0]):   # <-- this creates a closure that keeps track of the number of clicks.
    _c[0] += 1
    entry.delete(0, tk.END)
    entry.insert(0, _c[0])

root = tk.Tk()
root.title("Counter")
root.geometry("100x100")

button = tk.Button(text="Count", command=count)
label = tk.Label(text="Time")

entry = tk.Entry(root)

label.pack(side=tk.TOP , pady=5)
entry.pack(side=tk.TOP , pady=5)
button.pack(side=tk.TOP , pady=5)

mainloop()

Alternatively, you could keep track of the value of c if you create it in the global namespace, and declare it global in the function.

import tkinter as tk

def count():
    global c
    c += 1
    entry.delete(0, tk.END)
    entry.insert(0, c)

c = 0

root = tk.Tk()
root.title("Counter")
root.geometry("100x100")

button = tk.Button(text="Count", command=count)
label = tk.Label(text="Time")

entry = tk.Entry(root)

label.pack(side=tk.TOP , pady=5)
entry.pack(side=tk.TOP , pady=5)
button.pack(side=tk.TOP , pady=5)

mainloop()


问:
Building n-grams for token level text classification
I am trying to classify multiclass data at the token-level using scikit-learn.  I already have a train and test split. The tokens occurs in batches of the same class, e.g. first 10 tokens belonging to class0, the next 20 belonging to class4 and so on.
The data is in the following \t seperated format:

```<code>-----------------
token       tag
-----------------
way          6
to           6
reduce       6
the          6
amount       6
of           6
traffic      6
   ....
public       2
transport    5
is           5
a            5
key          5
factor       5
to           5
minimize     5
   ....
</code>```

The data is distributed as follows:

```<code>                              Training Data                    Test Data
# Total:                        119490                          29699
# Class 0:                      52631                           13490
# Class 1:                      35116                           8625
# Class 2:                      17968                           4161
# Class 3:                      8658                            2088
# Class 4:                      3002                            800
# Class 5:                      1201                            302
# Class 6:                      592                             153
</code>```

The code I am trying  is:

```<code>import pandas as pd
from sklearn.feature_extraction.text import CountVectorizer
from sklearn.pipeline import Pipeline
from sklearn.feature_extraction.text import TfidfTransformer
from sklearn.naive_bayes import MultinomialNB
from sklearn.linear_model import SGDClassifier
from sklearn.metrics import f1_score
from sklearn.model_selection import KFold
from imblearn.over_sampling import SMOTE

if __name__ == '__main__':
    # reading Files
    train_df = pd.read_csv(TRAINING_DATA_PATH, names=['token', 'tag'], sep='\t').dropna().reset_index(drop=True)
    test_df = pd.read_csv(TEST_DATA_PATH, names=['token', 'tag'], sep='\t')

    # getting training and testing data
    train_X = train_df['token']
    test_X = test_df['token'].astype('U')
    train_y = train_df['tag']
    test_y = test_df['tag'].astype('U')

    # Naive-Bayes
    nb_pipeline = Pipeline([('vect', CountVectorizer()),        # Counts occurrences of each word
                            ('tfidf', TfidfTransformer()),      # Normalize the counts based on document length
                            ])
    f1_list = []
    cv = KFold(n_splits=5)
    for train_index, test_index in cv.split(train_X):
        train_text = train_X[train_index]
        train_label = train_y[train_index]
        val_text = train_X[test_index]
        val_y = train_y[test_index]
        vectorized_text = nb_pipeline.fit_transform(train_text)
        sm = SMOTE(random_state=42)
        train_text_res, train_y_res = sm.fit_sample(vectorized_text, train_label)
        print("\nTraining Data Class Distribution:")
        print(train_label.value_counts())
        print("\nRe-sampled Training Data Class Distribution:")
        print(train_y_res.value_counts())
        # clf = SVC(kernel='rbf', max_iter=1000, class_weight='balanced', verbose=1)
        clf = MultinomialNB()
        # clf = SGDClassifier(loss='log', penalty='l2', alpha=1e-3, max_iter=100, tol=None,
        #                    n_jobs=-1, verbose=1)
        clf.fit(train_text_res, train_y_res)
        predictions = clf.predict(nb_pipeline.transform(val_text))
        f1 = f1_score(val_y, predictions, average='macro')
        f1_list.append(f1)
    print(f1_list)
    pred = clf.predict(nb_pipeline.transform(test_X))
    print('F1-macro: %s' % f1_score(pred, test_y, average='macro'))
</code>```

I wanna build n-grams and add that as a feature to the model so it can understand the context better but am not sure how that would work as testing would be done at the token level again. How can I build and feed the n-grams to the model and then predict at the token-level again for the test data?

答:
Instead of:

```<code>nb_pipeline = Pipeline([('vect', CountVectorizer()),
                        ('tfidf', TfidfTransformer())])
</code>```

do at once counts, tfidf for unigrams and bigrams:

```<code>from sklearn.feature_extraction.text import TfidfVectorizer
nb_pipeline = Pipeline([('tfidf', TfidfVectorizer(ngram_range=(1, 2)))])
</code>```

See docs for more.

Body:
I am trying to classify multiclass data at the token-level using scikit-learn.  I already have a train and test split. The tokens occurs in batches of the same class, e.g. first 10 tokens belonging to class0, the next 20 belonging to class4 and so on.
The data is in the following \t seperated format:

-----------------
token       tag
-----------------
way          6
to           6
reduce       6
the          6
amount       6
of           6
traffic      6
   ....
public       2
transport    5
is           5
a            5
key          5
factor       5
to           5
minimize     5
   ....

The data is distributed as follows:

                              Training Data                    Test Data
# Total:                        119490                          29699
# Class 0:                      52631                           13490
# Class 1:                      35116                           8625
# Class 2:                      17968                           4161
# Class 3:                      8658                            2088
# Class 4:                      3002                            800
# Class 5:                      1201                            302
# Class 6:                      592                             153

The code I am trying  is:

import pandas as pd
from sklearn.feature_extraction.text import CountVectorizer
from sklearn.pipeline import Pipeline
from sklearn.feature_extraction.text import TfidfTransformer
from sklearn.naive_bayes import MultinomialNB
from sklearn.linear_model import SGDClassifier
from sklearn.metrics import f1_score
from sklearn.model_selection import KFold
from imblearn.over_sampling import SMOTE

if __name__ == '__main__':
    # reading Files
    train_df = pd.read_csv(TRAINING_DATA_PATH, names=['token', 'tag'], sep='\t').dropna().reset_index(drop=True)
    test_df = pd.read_csv(TEST_DATA_PATH, names=['token', 'tag'], sep='\t')

    # getting training and testing data
    train_X = train_df['token']
    test_X = test_df['token'].astype('U')
    train_y = train_df['tag']
    test_y = test_df['tag'].astype('U')

    # Naive-Bayes
    nb_pipeline = Pipeline([('vect', CountVectorizer()),        # Counts occurrences of each word
                            ('tfidf', TfidfTransformer()),      # Normalize the counts based on document length
                            ])
    f1_list = []
    cv = KFold(n_splits=5)
    for train_index, test_index in cv.split(train_X):
        train_text = train_X[train_index]
        train_label = train_y[train_index]
        val_text = train_X[test_index]
        val_y = train_y[test_index]
        vectorized_text = nb_pipeline.fit_transform(train_text)
        sm = SMOTE(random_state=42)
        train_text_res, train_y_res = sm.fit_sample(vectorized_text, train_label)
        print("\nTraining Data Class Distribution:")
        print(train_label.value_counts())
        print("\nRe-sampled Training Data Class Distribution:")
        print(train_y_res.value_counts())
        # clf = SVC(kernel='rbf', max_iter=1000, class_weight='balanced', verbose=1)
        clf = MultinomialNB()
        # clf = SGDClassifier(loss='log', penalty='l2', alpha=1e-3, max_iter=100, tol=None,
        #                    n_jobs=-1, verbose=1)
        clf.fit(train_text_res, train_y_res)
        predictions = clf.predict(nb_pipeline.transform(val_text))
        f1 = f1_score(val_y, predictions, average='macro')
        f1_list.append(f1)
    print(f1_list)
    pred = clf.predict(nb_pipeline.transform(test_X))
    print('F1-macro: %s' % f1_score(pred, test_y, average='macro'))

I wanna build n-grams and add that as a feature to the model so it can understand the context better but am not sure how that would work as testing would be done at the token level again. How can I build and feed the n-grams to the model and then predict at the token-level again for the test data?

Body:
Instead of:

nb_pipeline = Pipeline([('vect', CountVectorizer()),
                        ('tfidf', TfidfTransformer())])

do at once counts, tfidf for unigrams and bigrams:

from sklearn.feature_extraction.text import TfidfVectorizer
nb_pipeline = Pipeline([('tfidf', TfidfVectorizer(ngram_range=(1, 2)))])

See docs for more.


问:
How to insert data from html form into database without using HTML POST method?
Hi I would like to know if there is any other way using javascript or something to enter the user input directly to database without using POST method.</p>

答:
There are several HTTP commands:

```<code>GET POST PUT DELETE HEAD CONNECT TRACE
</code>```

The only ones that will do what you want according to the specification are PUT and POST.

You shouldn't use GET to send data back to the server for storage. So if you don't want to use POST, use PUT.

OwnerDisplayName: johnnaples

ContentLicense: CC BY-SA 2.5

Body:
There are several HTTP commands:

GET POST PUT DELETE HEAD CONNECT TRACE

The only ones that will do what you want according to the specification are PUT and POST.

You shouldn't use GET to send data back to the server for storage. So if you don't want to use POST, use PUT.

OwnerDisplayName: RibaldEddie


问:
Large performance difference: Using sysdate vs using pre-formatted date
Why is there such a huge performance difference between these two queries?

```<code>-- (89 seconds)
SELECT max(mydate) FROM mytable WHERE eqpid = 'ABCDEFG'
AND mydate < sysdate - 5
</code>```

vs.

```<code>-- (0.6 seconds)
SELECT max(mydate) FROM mytable WHERE eqpid = 'ABCDEFG'
AND mydate < TO_DATE('05/27/2011 03:13:00', 'MM/DD/YYYY HH24:MI:SS') -- 5 days ago
</code>```

Regardless of indexes, it seems that both to_date and sysdate just return "some date value".

Notes: A composite index exists on this table including eqpid and 2 other columns.
An index also exists for mydate. Both are b-tree. There are about 29 million rows.

Why would the optimizer choose such an obviously different (and in one case, awful) plan for these?

答: I don't know Oracle, but in Postgresql a possible source of ignoring an index is mismatched types. Maybe doing the straight - 5 makes Oracle think the rhs is numeric. Can you do a cast to date (or whatever is the exact type of mydate) on sysdate - 5?

Body:
Why is there such a huge performance difference between these two queries?

-- (89 seconds)
SELECT max(mydate) FROM mytable WHERE eqpid = 'ABCDEFG'
AND mydate < sysdate - 5

vs.

-- (0.6 seconds)
SELECT max(mydate) FROM mytable WHERE eqpid = 'ABCDEFG'
AND mydate < TO_DATE('05/27/2011 03:13:00', 'MM/DD/YYYY HH24:MI:SS') -- 5 days ago

Regardless of indexes, it seems that both to_date and sysdate just return "some date value".

Notes: A composite index exists on this table including eqpid and 2 other columns.
An index also exists for mydate. Both are b-tree. There are about 29 million rows.

Why would the optimizer choose such an obviously different (and in one case, awful) plan for these?


答:
It's in the keys of uploaded. You can use iter() and next() to get it.</p>

```<code>filename = next(iter(uploaded))
</code>```

Title: Getting a file name after being loaded into Google Colab

Body:
What I want: to get the file name of the file that was just uploaded into Google Colab via the following code.

from google.colab import files
uploaded = files.upload()

I tried: printing the file once I uploaded it and I get the following output.

print(uploaded)
{'2019.06.01_Short Maintenance - Vehicle, Malibu_TGZ.csv': b'Year,Miles,$/Gallon,Total $,Vehicle\r\n6/1/2019,343.4,2.529,28,Malibu\r\n6/8/2019,34.3,2.529,5,Malibu\r\n6/8/2019,315.6,2.529,33.1,Malibu\r\n6/30/2019,323,2.399,30,Malibu\r\n7/5/2019,316.4,2.559,31,Malibu\r\n7/12/2019,334.6,2.529,30.45,Malibu\r\n7/21/2019,288.7,2.459,33.75,Malibu\r\n7/29/2019,336.7,2.419,28,Malibu\r\n8/6/2019,317.3,2.379,30.45,Malibu\r\n8/14/2019,340.9,2.359,30.1,Malibu\r\n8/22/2019,307.4,2.299,29.85,Malibu\r\n9/1/2019,239.1,2.279,29.7,Malibu\r\n9/14/2019,237.8,2.419,28.9,Malibu\r\n9/6/2019,288,2.469,30.4,Malibu\r\n10/13/2019,305.7,2.299,27.81,Malibu\r\n10/20/2019,330.7,2.369,30.05,Malibu\r\n11/8/2019,257,2.429,32.4,Malibu\r\n12/3/2019,249.3,2.319,5.01,Malibu\r\n12/7/2019,37.2,2.099,25,Malibu\r\n12/22/2019,276.4,2.229,29.4,Malibu\r\n1/12/2020,334,2.199,5,Malibu\r\n1/19/2020,51,2.009,28.15,Malibu\r\n2/8/2020,231.5,2.079,25.8,Malibu\r\n2/23/2020,254.7,2.159,25.75,Malibu\r\n3/19/2020,235.3,1.879,23.15,Malibu\r\n5/22/2020,303,1.699,23.15,Malibu\r\n'}

It appears to be a dic with the key as the file name, and value as a string of all the data in the file. I don't know how to ge the key value, assuming that is what I need to do.

Body:
It's in the keys of uploaded. You can use iter() and next() to get it.

filename = next(iter(uploaded))


问:
rearrange apps in launchers app drawer android studio
I am trying to make a launcher app I have made the app drawer and got apps with this code

```<code>override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_app_drawer)
        view.adapter = getInstalledApps()?.let { AppDrawerAdapter(this, it) }
        view.layoutManager = GridLayoutManager(this, 5)
        view.hasFixedSize()
    }
    private fun getInstalledApps(): List<AppItem>? {
        val apps: MutableList<AppItem> = ArrayList()
        val intent = Intent(Intent.ACTION_MAIN, null)
        intent.addCategory(Intent.CATEGORY_LAUNCHER)
        val untreatedAppList =
            applicationContext.packageManager.queryIntentActivities(intent, 0)

        for (untreatedApp in untreatedAppList) {
            val appName =
                untreatedApp.activityInfo.loadLabel(packageManager).toString()
            val appPackageName = untreatedApp.activityInfo.packageName
            val appImage = untreatedApp.activityInfo.loadIcon(packageManager)
            val app = AppItem(appName, appImage, appPackageName)
            if (!apps.contains(app)) apps.add(app)
        }
        return apps
    }
</code>```

the apps are displaying in a nonspecific order how to arrange them alphabetically

答:
Well, you simply sort the list.
Replace </p>

```<code>return apps
</code>```

<p>with </p>

```<code>return apps.sortedBy { it.appName }
</code>```

Body:
I am trying to make a launcher app I have made the app drawer and got apps with this code

override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_app_drawer)
        view.adapter = getInstalledApps()?.let { AppDrawerAdapter(this, it) }
        view.layoutManager = GridLayoutManager(this, 5)
        view.hasFixedSize()
    }
    private fun getInstalledApps(): List<AppItem>? {
        val apps: MutableList<AppItem> = ArrayList()
        val intent = Intent(Intent.ACTION_MAIN, null)
        intent.addCategory(Intent.CATEGORY_LAUNCHER)
        val untreatedAppList =
            applicationContext.packageManager.queryIntentActivities(intent, 0)

        for (untreatedApp in untreatedAppList) {
            val appName =
                untreatedApp.activityInfo.loadLabel(packageManager).toString()
            val appPackageName = untreatedApp.activityInfo.packageName
            val appImage = untreatedApp.activityInfo.loadIcon(packageManager)
            val app = AppItem(appName, appImage, appPackageName)
            if (!apps.contains(app)) apps.add(app)
        }
        return apps
    }

the apps are displaying in a nonspecific order how to arrange them alphabetically

Body:
Well, you simply sort the list.
Replace

return apps

with

return apps.sortedBy { it.appName }


问:
rel="canonical" html5 unable to validate
Should the link attribute rel="canonical" validate against html5?

It is the first time I am using this and I am getting the following validation errors:

"Bad value canonical for attribute rel on element link: Keyword canonical is not registered."

It kind of suggests it shouldnt although I cant find any concrete documentation on this.

Edit - Here is the line that is throwing the validator off:

```<code><link rel="canonical" href="http://dev.local/" />
</code>```

I have  tried it with and  without the closing slash

答:
From what I can gather from the output of the validator and the part of the spec that defines the link's rel attribute I'd say the validator is marking the document as invalid due to the "canonical" type being only a proposal and not part of the official linkTypes right now.

At the same time that page also says ...

Types defined as extensions in the
  Microformats wiki existing-rel-values
  page with the status "proposed" or
  "ratified" may be used with the rel
  attribute on link, a, and area
  elements in accordance to the "Effect
  on..." field. [MFREL]

The validation message refers to this list of currently valid extensions to the "official catalog".
Up until June 2 this list did not contain the canonical link type so the validator was IMO correct in marking the document as invalid.

But now that the canonical type is is in the list of proposed types, I think this is just a matter of time before also the validator will recognize it :-)

Body:
Should the link attribute rel="canonical" validate against html5?

It is the first time I am using this and I am getting the following validation errors:

"Bad value canonical for attribute rel on element link: Keyword canonical is not registered."

It kind of suggests it shouldnt although I cant find any concrete documentation on this.

Edit - Here is the line that is throwing the validator off:

<link rel="canonical" href="http://dev.local/" />

I have  tried it with and  without the closing slash