问:
Stop pandas from grouping the data when reading csv
I have a problem, when I read a csv file with pandas and assign it the header to be row 0 with the following:

```<code>df = pd.read_csv(fileName, header = [0])
</code>```

The first x columns on each row is being grouped and surrounded by parenthesis.
For example, if I have the following:

```<code>Version, temp, altitude, oxygen, pressure, gas_temp, NH3, NO2
1,189,2980,489.9,594,345,345,22,00
2,11,33,423,554.9,2345,32,22,01
</code>```

When I try to print each row from the data frame, I get this:

```<code>(1,189,2980,489.9,594) 345 345 22 00
(2,11,33,423,554.9) 2345 32 22 01
</code>```

And if I call df['temp'] I get back [345, 2345] which is not correct because pandas is grouping the first x columns together.

答:
The firsr important discrepancy in your data sample is that it:

contains only 8 column names,

but there are 9 data columns.

Another disorder is that column names should be separated only with
commas, but your input contains also spaces.

The cumulated effect of the above is that read_csv is "fooled" and can read
data in such a weird way. Actually, at the first attempt I replicated your
case, but the next time (and all following times) I got an apparently
proper result.

The reason I wrote "apparently" is that when you print df.columns,
you wil see another flaw:

```<code>Index(['Version', ' temp', ' altitude', ' oxygen', ' pressure', ' gas_temp',
       ' NH3', ' NO2'],
      dtype='object')
</code>```

i.e. column names contain initial spaces, so an attempt to refer e.g.
to temp column throws exception:

```<code>AttributeError: 'DataFrame' object has no attribute 'temp'
</code>```

One thing you can do to read this file correctly is to pass skipinitialspace=True
parameter:

```<code>df = pd.read_csv(fileName, skipinitialspace=True, header=[0])
</code>```

The result of reading is:

```<code>   Version  temp  altitude  oxygen  pressure  gas_temp  NH3  NO2
1      189  2980     489.9   594.0       345       345   22    0
2       11    33     423.0   554.9      2345        32   22    1
</code>```

When you print df.columns, you will see that column names are without
initial spaces, so now these extra spaces in the header row are stripped.

Another detail in the way how read_csv operates is that it matches column names
with data columns from the end, so the "additional" column (in data rows)
is taken as the index column, with no name.

You can also add index_col=[0] parameter:

```<code>df = pd.read_csv(filename, skipinitialspace=True, index_col=[0], header=[0])
</code>```

to specify explicitely that the initial column is the index.

Body:
I have a problem, when I read a csv file with pandas and assign it the header to be row 0 with the following:

df = pd.read_csv(fileName, header = [0])

The first x columns on each row is being grouped and surrounded by parenthesis.
For example, if I have the following:

Version, temp, altitude, oxygen, pressure, gas_temp, NH3, NO2
1,189,2980,489.9,594,345,345,22,00
2,11,33,423,554.9,2345,32,22,01

When I try to print each row from the data frame, I get this:

(1,189,2980,489.9,594) 345 345 22 00
(2,11,33,423,554.9) 2345 32 22 01

And if I call df['temp'] I get back [345, 2345] which is not correct because pandas is grouping the first x columns together.

Body:
The firsr important discrepancy in your data sample is that it:

contains only 8 column names,

but there are 9 data columns.

Another disorder is that column names should be separated only with
commas, but your input contains also spaces.

The cumulated effect of the above is that read_csv is "fooled" and can read
data in such a weird way. Actually, at the first attempt I replicated your
case, but the next time (and all following times) I got an apparently
proper result.

The reason I wrote "apparently" is that when you print df.columns,
you wil see another flaw:

Index(['Version', ' temp', ' altitude', ' oxygen', ' pressure', ' gas_temp',
       ' NH3', ' NO2'],
      dtype='object')

i.e. column names contain initial spaces, so an attempt to refer e.g.
to temp column throws exception:

AttributeError: 'DataFrame' object has no attribute 'temp'

One thing you can do to read this file correctly is to pass skipinitialspace=True
parameter:

df = pd.read_csv(fileName, skipinitialspace=True, header=[0])

The result of reading is:

   Version  temp  altitude  oxygen  pressure  gas_temp  NH3  NO2
1      189  2980     489.9   594.0       345       345   22    0
2       11    33     423.0   554.9      2345        32   22    1

When you print df.columns, you will see that column names are without
initial spaces, so now these extra spaces in the header row are stripped.

Another detail in the way how read_csv operates is that it matches column names
with data columns from the end, so the "additional" column (in data rows)
is taken as the index column, with no name.

You can also add index_col=[0] parameter:

df = pd.read_csv(filename, skipinitialspace=True, index_col=[0], header=[0])

to specify explicitely that the initial column is the index.


来源: stackexchange

问:
Label component won't delete with BackSpace - React Native
I have a React Native App.

I have a TextInput that has Filter/Search logic and a simple FlatList.

Click inside the TextInput a dropdown menu of Filters appear.

I Select one Filter and it appears as a Label inside my TextInput.

Then I can search any text.

TextInput with filter options:

Select filter "rehab":

Search text "test" in filtered messages:

Now my issue is when I hit BACKSPACE text "test" is deleted but the label is not. Because for that label I have created a separate component (Label.js). In this component I have just added the styling that's it.

Code:

```<code>import Label from './Label.js';
  <Icon type='materialicons' name='search'  />.  //search icon
  { val === "" ? null :
  <Label val={this.state.val}> {val} </Label>.  //Label component I created
  }
  <TextInput                                  //TextInput
    value={value}
    placeholder='Search Here...'
    onChangeText={(text)=>{this.handleSearch(text, true))}}
    style={{ height: 40, flex: 1}}
    autoCapitalize='none'
    selectTextOnFocus={true}
  />
  <Icon type='materialicons' name='cancel' onPress={()=> {this.handleFilterIcon(false)}} />         // clear text icon
</code>```

So the CLEAR icon above will clear the Label. Thats working fine.
But if the user wants to just delete that label using "BackSpace" then that will create an issue.
Can the Label component be deleted using BackSpace key??? Is it possible??

Updated Issue:

As per the answer below I changed my code. Facing another issue.
 Filter is stored in "val" state.

Text string entered is stored in "value" state.

Using 2 conditions: 1) if both val and value are not initial then initialise "value" only
2)if only val is not initial then clear out "val"
How do I integrate both together????
Basically everything should be delete-able with "Backspace" key.

```<code>this.handleClearText(){
setState({
 value: ""
})
}

this.handleClearFilter(){
setState({
 val: ""
})
}

<TextInput
onKeyPress={({ nativeEvent }) => {
                      if (nativeEvent.key === 'Backspace' && val !== "" && value !== "") {
                        this.handleClearText();
                      }
                      if (nativeEvent.key === 'Backspace' && val !== "") {
                        this.handleClearFilter();
                      }
/>
</code>```

答:
You can remove the label if the text is empty and if the user presses backspace in an empty text,

```<code>    <TextInput
      onKeyPress={({ nativeEvent }) => {
        if (nativeEvent.key === 'Backspace' && value==='') {
     //set label state value as empty
        }
      }}
    />
</code>```

And inside the label you can handle displaying empty values.
You can also add conditions like the label value not being empty.

Update for Edited Question

You can use a custom component like this,
Here enter will create something similar to tag and backspace will keep deleting the text and when text is empty it will remove the label.

```<code>const CustomInput = () => {
  const [text, setText] = React.useState('');
  const [val, setVal] = React.useState('');

  return (
    <View style={{ flexDirection: 'row' }}>
      <Text
        style={{
          backgroundColor: 'aqua',
          alignSelf: 'flex-start',
          marginHorizontal: 10,
        }}>
        {val}
      </Text>
      <TextInput
        placeholder="text"
        value={text}
        onChangeText={(t) => setText(t)}
        onKeyPress={({ nativeEvent }) => {
          if (nativeEvent.key === 'Backspace' && text === '') {
            setVal('');
          }
          if (nativeEvent.key === 'Enter' && text !== '') {
            setVal(text);
            setText('');
          }
        }}
      />
    </View>
  );
};
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I have a React Native App.

I have a TextInput that has Filter/Search logic and a simple FlatList.

Click inside the TextInput a dropdown menu of Filters appear.

I Select one Filter and it appears as a Label inside my TextInput.

Then I can search any text.

TextInput with filter options:

Select filter "rehab":

Search text "test" in filtered messages:

Now my issue is when I hit BACKSPACE text "test" is deleted but the label is not. Because for that label I have created a separate component (Label.js). In this component I have just added the styling that's it.

Code:

import Label from './Label.js';
  <Icon type='materialicons' name='search'  />.  //search icon
  { val === "" ? null :
   {val} .  //Label component I created
  }
  <TextInput                                  //TextInput
    value={value}
    placeholder='Search Here...'
    onChangeText={(text)=>{this.handleSearch(text, true))}}
    style={{ height: 40, flex: 1}}
    autoCapitalize='none'
    selectTextOnFocus={true}
  />
  <Icon type='materialicons' name='cancel' onPress={()=> {this.handleFilterIcon(false)}} />         // clear text icon

So the CLEAR icon above will clear the Label. Thats working fine.
But if the user wants to just delete that label using "BackSpace" then that will create an issue.
Can the Label component be deleted using BackSpace key??? Is it possible??

Updated Issue:

As per the answer below I changed my code. Facing another issue.
 Filter is stored in "val" state.

Text string entered is stored in "value" state.

Using 2 conditions: 1) if both val and value are not initial then initialise "value" only
2)if only val is not initial then clear out "val"
How do I integrate both together????
Basically everything should be delete-able with "Backspace" key.

this.handleClearText(){
setState({
 value: ""
})
}

this.handleClearFilter(){
setState({
 val: ""
})
}

<TextInput
onKeyPress={({ nativeEvent }) => {
                      if (nativeEvent.key === 'Backspace' && val !== "" && value !== "") {
                        this.handleClearText();
                      }
                      if (nativeEvent.key === 'Backspace' && val !== "") {
                        this.handleClearFilter();
                      }
/>

Body:
You can remove the label if the text is empty and if the user presses backspace in an empty text,

    <TextInput
      onKeyPress={({ nativeEvent }) => {
        if (nativeEvent.key === 'Backspace' && value==='') {
     //set label state value as empty
        }
      }}
    />

And inside the label you can handle displaying empty values.
You can also add conditions like the label value not being empty.

Update for Edited Question

You can use a custom component like this,
Here enter will create something similar to tag and backspace will keep deleting the text and when text is empty it will remove the label.

const CustomInput = () => {
  const [text, setText] = React.useState('');
  const [val, setVal] = React.useState('');

  return (
    <View style={{ flexDirection: 'row' }}>
      <Text
        style={{
          backgroundColor: 'aqua',
          alignSelf: 'flex-start',
          marginHorizontal: 10,
        }}>
        {val}
      </Text>
      <TextInput
        placeholder="text"
        value={text}
        onChangeText={(t) => setText(t)}
        onKeyPress={({ nativeEvent }) => {
          if (nativeEvent.key === 'Backspace' && text === '') {
            setVal('');
          }
          if (nativeEvent.key === 'Enter' && text !== '') {
            setVal(text);
            setText('');
          }
        }}
      />
    </View>
  );
};


问:
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>```

答:
The answer is very simple. You have to remove this line of code from the count() function

```<code>c = 0
</code>```

and put it somewhere else.
REASON: When you put c = 0 inside the count() function, the value of c gets reset to 0. If you put it near the beginning of the program, it won't be reset and the value will only be incremented when the button is clicked

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:
The answer is very simple. You have to remove this line of code from the count() function

c = 0

and put it somewhere else.
REASON: When you put c = 0 inside the count() function, the value of c gets reset to 0. If you put it near the beginning of the program, it won't be reset and the value will only be incremented when the button is clicked


问:
FTPClient FTPFile details not available
I am trying to get the list of files from remote FTP server. The ftpClient.listFiles() returned null and I had to set setUnparseableEntries to true to get the list of files. Even then the list of files do not have any information like name and only information it has is rawlisting and others are null. So I cannot do ftpFile.getName. Here is the code

```<code>public FTPFile[] process() throws Exception {
 String message = null;
 FTPFile[] files = null;

 FTPClient ftpClient = new FTPClient();

 FTPClientConfig config = new FTPClientConfig();
 config.setServerTimeZoneId("America/Chicago");
 config.setUnparseableEntries(true);
 ftpClient.configure(config);

 if ( !connectToServer() ) return null;

 if ( !changeDirectory() ) {
    disconnectFromServer();
    return null;
 }
 files = getListofFiles();
 disconnectFromServer();

 return files;
}

private boolean connectToServer() {
 boolean result = true;
 String message = null, url = null;

 // attempt to connect to the target server
 try {
     url = fo.getServerInfo().getConnectionURL();
     LOGGER.debug("Connecting to: " + url);
     ftpClient.connect(fo.getServerInfo().getHostName(),
            fo.getServerInfo().getHostPort());
     ftpClient.enterLocalPassiveMode();
 } catch(SocketException e) {
     result = false;
     message = "Could not connect to server at " + url;
 } catch(IOException e) {
     result = false;
     message = "Could not connect to server at " + url;
 }
 if ( !result ) return result;

 // After connection attempt, you should check the reply code to verify success.
 Integer replyCode = ftpClient.getReplyCode();

 if ( !FTPReply.isPositiveCompletion(replyCode) ) {
    message = "Reply Code - " + replyCode.toString() + " is negative.";
    try {
        ftpClient.disconnect();
    } catch(Exception e) {
        message = "Could not disconnect cleanly from server.";
        LOGGER.error(message);
    }
 } else {
    message = "Reply Code - " + replyCode.toString() + " is positive.";
 }

 Boolean logonOk = false;
 try {
    logonOk = ftpClient.login(fo.getServerInfo().getUserName(),
            fo.getServerInfo().getUserPassword());
 } catch(IOException e) {
    message = "IOException during logon attempt.";
    LOGGER.error(message);
 }
 if ( !logonOk ) {
    result = false;
    message = "Logon UNsuccessful.";
 } else {
    message = "Logon successful.";
    LOGGER.error(message);
    executionMessageLog.add(message);
 }

 if ( !result ) return result;

 // attempt to log onto the target server

 return result;
}
</code>```

Following method is trying to get the list of files. I could see the file name using listNames and also listFiles shows list of files but name, modified date are empty and only has value in rawlisting in the format "04-01-20  11:31AM                 8975 test.TXT". So how to get the name and modified date from the raw listing and why I could not get FTPFile name using getName

```<code>private FTPFile[] getListofFiles(){
 String message = null;
 FTPFile[] files = null;
 try {
    String[] filenames = ftpClient.listNames(fileListInfo.getFilePath());
    files = ftpClient.listFiles(); /*Has only rawlisting and others are null*/
 }
 catch(IOException e) {
    message = "IOException during getListofFiles attempt:";
    LOGGER.error(message);
    executionMessageLog.add(message);
    message = e.getMessage();
    LOGGER.error(message);
    executionMessageLog.add(message);
 }
 return files;

}
</code>```

答:
04-01-20 11:31AM 8975 test.TXT
```

That's quite unusual format. So it's possible that Apache Commons Net library cannot parse it with the default configuration.

You might need to explicitly specify one of the available parsers. The available parsers are in src\main\java\org\apache\commons\net\ftp\parser. Or if there's no parser specifically compatible with your server, you might need to build your own (you can base it on ConfigurableFTPFileEntryParserImpl).

Though actually, for an ad-hoc solution, easier would be that you just parse the "rawlisting" you already have.

Title: FTPClient FTPFile details not available

Body:
I am trying to get the list of files from remote FTP server. The ftpClient.listFiles() returned null and I had to set setUnparseableEntries to true to get the list of files. Even then the list of files do not have any information like name and only information it has is rawlisting and others are null. So I cannot do ftpFile.getName. Here is the code

public FTPFile[] process() throws Exception {
 String message = null;
 FTPFile[] files = null;

 FTPClient ftpClient = new FTPClient();

 FTPClientConfig config = new FTPClientConfig();
 config.setServerTimeZoneId("America/Chicago");
 config.setUnparseableEntries(true);
 ftpClient.configure(config);

 if ( !connectToServer() ) return null;

 if ( !changeDirectory() ) {
    disconnectFromServer();
    return null;
 }
 files = getListofFiles();
 disconnectFromServer();

 return files;
}

private boolean connectToServer() {
 boolean result = true;
 String message = null, url = null;

 // attempt to connect to the target server
 try {
     url = fo.getServerInfo().getConnectionURL();
     LOGGER.debug("Connecting to: " + url);
     ftpClient.connect(fo.getServerInfo().getHostName(),
            fo.getServerInfo().getHostPort());
     ftpClient.enterLocalPassiveMode();
 } catch(SocketException e) {
     result = false;
     message = "Could not connect to server at " + url;
 } catch(IOException e) {
     result = false;
     message = "Could not connect to server at " + url;
 }
 if ( !result ) return result;

 // After connection attempt, you should check the reply code to verify success.
 Integer replyCode = ftpClient.getReplyCode();

 if ( !FTPReply.isPositiveCompletion(replyCode) ) {
    message = "Reply Code - " + replyCode.toString() + " is negative.";
    try {
        ftpClient.disconnect();
    } catch(Exception e) {
        message = "Could not disconnect cleanly from server.";
        LOGGER.error(message);
    }
 } else {
    message = "Reply Code - " + replyCode.toString() + " is positive.";
 }

 Boolean logonOk = false;
 try {
    logonOk = ftpClient.login(fo.getServerInfo().getUserName(),
            fo.getServerInfo().getUserPassword());
 } catch(IOException e) {
    message = "IOException during logon attempt.";
    LOGGER.error(message);
 }
 if ( !logonOk ) {
    result = false;
    message = "Logon UNsuccessful.";
 } else {
    message = "Logon successful.";
    LOGGER.error(message);
    executionMessageLog.add(message);
 }

 if ( !result ) return result;

 // attempt to log onto the target server

 return result;
}

Following method is trying to get the list of files. I could see the file name using listNames and also listFiles shows list of files but name, modified date are empty and only has value in rawlisting in the format "04-01-20  11:31AM                 8975 test.TXT". So how to get the name and modified date from the raw listing and why I could not get FTPFile name using getName

private FTPFile[] getListofFiles(){
 String message = null;
 FTPFile[] files = null;
 try {
    String[] filenames = ftpClient.listNames(fileListInfo.getFilePath());
    files = ftpClient.listFiles(); /*Has only rawlisting and others are null*/
 }
 catch(IOException e) {
    message = "IOException during getListofFiles attempt:";
    LOGGER.error(message);
    executionMessageLog.add(message);
    message = e.getMessage();
    LOGGER.error(message);
    executionMessageLog.add(message);
 }
 return files;

}

Body:
04-01-20 11:31AM 8975 test.TXT

That's quite unusual format. So it's possible that Apache Commons Net library cannot parse it with the default configuration.

You might need to explicitly specify one of the available parsers. The available parsers are in src\main\java\org\apache\commons\net\ftp\parser. Or if there's no parser specifically compatible with your server, you might need to build your own (you can base it on ConfigurableFTPFileEntryParserImpl).

Though actually, for an ad-hoc solution, easier would be that you just parse the "rawlisting" you already have.


问:
Error response from daemon: client version 1.40 is too new. Maximum supported API version is 1.39
After installing docker 19.03.09, any docker command involving the docker daemon is throwing the following error. </p>

```<code>Error response from daemon: client version 1.40 is too new. Maximum supported API version is 1.39
</code>```

答:
This is known issue with docker client 19.03.09. It happens if the daemon version supports only max api-version 1.39. Client is not downgrading the API version to match the server supported version automatically. It should be fixed in 19.03.10.

https://github.com/docker/cli/issues/2533

As a workaround, you can set the docker api version using following environment variable.

```<code>export DOCKER_API_VERSION=1.39
</code>```

Body:
After installing docker 19.03.09, any docker command involving the docker daemon is throwing the following error.

Error response from daemon: client version 1.40 is too new. Maximum supported API version is 1.39

Body:
This is known issue with docker client 19.03.09. It happens if the daemon version supports only max api-version 1.39. Client is not downgrading the API version to match the server supported version automatically. It should be fixed in 19.03.10.

https://github.com/docker/cli/issues/2533

As a workaround, you can set the docker api version using following environment variable.

export DOCKER_API_VERSION=1.39


问:
Celery task always PENDING
I try to run Celery example on Windows with redis backend. The code looks like:

```<code>from celery import Celery

app = Celery('risktools.distributed.celery_tasks',
             backend='redis://localhost',
             broker='redis://localhost')

@app.task(ignore_result=False)
def add(x, y):
    return x + y

@app.task(ignore_result=False)
def add_2(x, y):
    return x + y
</code>```

I start the tasks using iPython console:

```<code>>>> result_1 = add.delay(1, 2)
>>> result_1.state
'PENDING'
>>> result_2 = add_2.delay(2, 3)
>>> result_2.state
'PENDING'
</code>```

It seems that both tasks were not executed, but Celery worker output shows that they succeeded:

```<code>[2014-12-08 15:00:09,262: INFO/MainProcess] Received task: risktools.distributed.celery_tasks.add[01dedca1-2db2-48df-a4d6-2f06fe285e45]
[2014-12-08 15:00:09,267: INFO/MainProcess] Task celery_tasks.add[01dedca1-2db2-48df-a4d6-2f06fe28
5e45] succeeded in 0.0019998550415s: 3
[2014-12-08 15:00:24,219: INFO/MainProcess] Received task: risktools.distributed.celery_tasks.add[cb5505ce-cf93-4f5e-aebb-9b2d98a11320]
[2014-12-08 15:00:24,230: INFO/MainProcess] Task celery_tasks.add[cb5505ce-cf93-4f5e-aebb-9b2d98a1
1320] succeeded in 0.010999917984s: 5
</code>```

I've tried to troubleshoot this issue according to Celery documentation, but none of the advices were useful. What am I doing wrong and how can I receive results from a Celery task?

UPD:
I've added a task without ignore_result parameter, but nothing has changed

```<code>@app.task
def add_3(x, y):
    return x + y

>>>r = add_3.delay(2, 2)
>>>r.state
'PENDING'
</code>```

答: Setting CELERY_TASK_TRACK_STARTED = True (or track_started=True on individual tasks) can also help - this will enable the STARTED status.

ContentLicense: CC BY-SA 3.0

Title: Celery task always PENDING

Body:
I try to run Celery example on Windows with redis backend. The code looks like:

from celery import Celery

app = Celery('risktools.distributed.celery_tasks',
             backend='redis://localhost',
             broker='redis://localhost')

@app.task(ignore_result=False)
def add(x, y):
    return x + y

@app.task(ignore_result=False)
def add_2(x, y):
    return x + y

I start the tasks using iPython console:

>>> result_1 = add.delay(1, 2)
>>> result_1.state
'PENDING'
>>> result_2 = add_2.delay(2, 3)
>>> result_2.state
'PENDING'

It seems that both tasks were not executed, but Celery worker output shows that they succeeded:

[2014-12-08 15:00:09,262: INFO/MainProcess] Received task: risktools.distributed.celery_tasks.add[01dedca1-2db2-48df-a4d6-2f06fe285e45]
[2014-12-08 15:00:09,267: INFO/MainProcess] Task celery_tasks.add[01dedca1-2db2-48df-a4d6-2f06fe28
5e45] succeeded in 0.0019998550415s: 3
[2014-12-08 15:00:24,219: INFO/MainProcess] Received task: risktools.distributed.celery_tasks.add[cb5505ce-cf93-4f5e-aebb-9b2d98a11320]
[2014-12-08 15:00:24,230: INFO/MainProcess] Task celery_tasks.add[cb5505ce-cf93-4f5e-aebb-9b2d98a1
1320] succeeded in 0.010999917984s: 5

I've tried to troubleshoot this issue according to Celery documentation, but none of the advices were useful. What am I doing wrong and how can I receive results from a Celery task?

UPD:
I've added a task without ignore_result parameter, but nothing has changed

@app.task
def add_3(x, y):
    return x + y

>>>r = add_3.delay(2, 2)
>>>r.state
'PENDING'


问:
Training and Validation Loss Graph Meaning
This is my first attempt at creating a LSTM RNN. I am confused about the meaning of the Training Loss & Validation Loss graphs I have generated. Here is an image of the graph:

Training and Validation Loss Graph

Here is a sample of the training data:

```<code>
                        lat         long    trip_id mode_cat
datetime            id
2011-08-27 06:13:01 20  39.979973   116.305745  1   1
2011-08-27 06:13:02 20  39.979957   116.305688  1   1
2011-08-27 06:13:03 20  39.979960   116.305693  1   1
2011-08-27 06:13:04 20  39.979970   116.305717  1   1
2011-08-27 06:13:05 20  39.979985   116.305732  1   1
</code>```

Datetime and Id (user_id) are set as indices.

Here is the code for creating the moving window and the LSTM:

```<code>def moving_window(dataset_x, dataset_y, past_history):
    data, labels = [], []
    for i in range(past_history, len(dataset_x)):
        indices = range(i-past_history, i)
        data.append(dataset_x[indices])
        labels.append(dataset_y[i])
    return np.array(data), np.array(labels)

past_history = 60

x_train_single, y_train_single = moving_window(dataset_train_x, dataset_train_y, past_history)
x_test_single, y_test_single = moving_window(dataset_test_x, dataset_test_y, past_history)

buffer_size = len(x_train_single)//10
batch_size = 256

train_data_single = tf.data.Dataset.from_tensor_slices((x_train_single, y_train_single))
train_data_single = train_data_single.cache().shuffle(buffer_size).batch(batch_size).repeat()

test_data_single = tf.data.Dataset.from_tensor_slices((x_test_single, y_test_single))
test_data_single = test_data_single.batch(batch_size).repeat()

single_step_model = tf.keras.models.Sequential()
single_step_model.add(tf.keras.layers.LSTM(32,
                                           input_shape=x_train_single.shape[-2:]))
single_step_model.add(tf.keras.layers.Dense(1))

single_step_model.compile(optimizer=tf.keras.optimizers.RMSprop(), loss='mae')

evaluation_interval = len(x_train_single)//batch_size
epochs = 10

single_step_history = single_step_model.fit(train_data_single, epochs=epochs,
                                            steps_per_epoch=evaluation_interval,
                                            validation_data=test_data_single,
                                            validation_steps=50)
</code>```

答:
If the gap between training loss and validation loss is large its means that your model is overfitting and if training loss is large its means your model is underfitting.
If your training loss and validation loss are overlapping or close to each other means your model is now good for prediction.

Here the model is overfitted

Body:
This is my first attempt at creating a LSTM RNN. I am confused about the meaning of the Training Loss & Validation Loss graphs I have generated. Here is an image of the graph:

Training and Validation Loss Graph

Here is a sample of the training data:

                        lat         long    trip_id mode_cat
datetime            id
2011-08-27 06:13:01 20  39.979973   116.305745  1   1
2011-08-27 06:13:02 20  39.979957   116.305688  1   1
2011-08-27 06:13:03 20  39.979960   116.305693  1   1
2011-08-27 06:13:04 20  39.979970   116.305717  1   1
2011-08-27 06:13:05 20  39.979985   116.305732  1   1

Datetime and Id (user_id) are set as indices.

Here is the code for creating the moving window and the LSTM:

def moving_window(dataset_x, dataset_y, past_history):
    data, labels = [], []
    for i in range(past_history, len(dataset_x)):
        indices = range(i-past_history, i)
        data.append(dataset_x[indices])
        labels.append(dataset_y[i])
    return np.array(data), np.array(labels)

past_history = 60

x_train_single, y_train_single = moving_window(dataset_train_x, dataset_train_y, past_history)
x_test_single, y_test_single = moving_window(dataset_test_x, dataset_test_y, past_history)

buffer_size = len(x_train_single)//10
batch_size = 256

train_data_single = tf.data.Dataset.from_tensor_slices((x_train_single, y_train_single))
train_data_single = train_data_single.cache().shuffle(buffer_size).batch(batch_size).repeat()

test_data_single = tf.data.Dataset.from_tensor_slices((x_test_single, y_test_single))
test_data_single = test_data_single.batch(batch_size).repeat()

single_step_model = tf.keras.models.Sequential()
single_step_model.add(tf.keras.layers.LSTM(32,
                                           input_shape=x_train_single.shape[-2:]))
single_step_model.add(tf.keras.layers.Dense(1))

single_step_model.compile(optimizer=tf.keras.optimizers.RMSprop(), loss='mae')

evaluation_interval = len(x_train_single)//batch_size
epochs = 10

single_step_history = single_step_model.fit(train_data_single, epochs=epochs,
                                            steps_per_epoch=evaluation_interval,
                                            validation_data=test_data_single,
                                            validation_steps=50)


问:
localhost is currently unable to handle this request.HTTP ERROR 500
localhost is currently unable to handle this request.HTTP ERROR 500

PHP Fatal error:  Allowed memory size of 2147483648 bytes exhausted (tried to allocate 16384 bytes) in C:\xampp\htdocs\laravel\storage\framework\views\9ce6cdaa24325154033f80a71530d196495aafb3.php on line 2

答:
Before you decide how much memory you're about to use for your application,
you can try to add the following line to the php function (DO NOT try this on production)

```<code>ini_set('memory_limit', '-1');
</code>```

It's a memory limitation problem if the application could run as expected after adding above line of code

Noted: it is an easy (lazy) way to find out if the culprit is memory-using-problem but NOT A SOLUTION (still it's risky and not recommended in production).

Body:
Before you decide how much memory you're about to use for your application,
you can try to add the following line to the php function (DO NOT try this on production)

ini_set('memory_limit', '-1');

It's a memory limitation problem if the application could run as expected after adding above line of code

Noted: it is an easy (lazy) way to find out if the culprit is memory-using-problem but NOT A SOLUTION (still it's risky and not recommended in production).


问:
Generate unique random numbers in Dart
How can I generate two different random numbers in dart?

I have generated two random numbers using code below.

```<code>int rand1 = Random().nextInt(16);
int rand2 = Random().nextInt(16);
</code>```

```<code>if(rand1 == rand2)
  // generate new random
</code>```

How do I generate new random numbers until rand1 != rand2?

答:
A potential solution for pulling many out of many (say, 50 out of thousands) is to loop and memoize with a hash set.

I pulled this from my code, but something like:

```<code>var hashSet = HashSet();
for (var i = 0; i < boardSize; i++) {
  words.add([]);
  for (var j = 0; j < boardSize; j++) {
    Random _random = new Random();
    String wordToAdd = abstractPossibleWords[_random.nextInt(abstractPossibleWords.length)];
    while (hashSet.contains(wordToAdd)) {
      wordToAdd = abstractPossibleWords[_random.nextInt(abstractPossibleWords.length)];
    }
    words[i].add(wordToAdd);
  }
}
</code>```

Title: Generate unique random numbers in Dart

Body:
How can I generate two different random numbers in dart?

I have generated two random numbers using code below.

int rand1 = Random().nextInt(16);
int rand2 = Random().nextInt(16);

if(rand1 == rand2)
  // generate new random

How do I generate new random numbers until rand1 != rand2?

Body:
A potential solution for pulling many out of many (say, 50 out of thousands) is to loop and memoize with a hash set.

I pulled this from my code, but something like:

var hashSet = HashSet();
for (var i = 0; i < boardSize; i++) {
  words.add([]);
  for (var j = 0; j < boardSize; j++) {
    Random _random = new Random();
    String wordToAdd = abstractPossibleWords[_random.nextInt(abstractPossibleWords.length)];
    while (hashSet.contains(wordToAdd)) {
      wordToAdd = abstractPossibleWords[_random.nextInt(abstractPossibleWords.length)];
    }
    words[i].add(wordToAdd);
  }
}


问:
Unable to remote-exec in AzureVM using Terraform
I want to copy file and run some shell commands after VM is created in Azure. I use provisioner 'file' and provisioner 'remote-exec' and created VM using ssh keys. Everything works fine till provisoner file and I get following error:

Error: timeout - last error: dial tcp :22: connect: connection refused

When I do ssh -i id_rsa <username>@<ip_address> it works fine. I get this IP address from Azure Portal.

Here is my tf file:

```<code>resource "azurerm_resource_group" "myterraformgroup" {
    name     = "terrafromresources"
    location = "eastus"
}

resource "azurerm_virtual_network" "myterraformnetwork" {
    name                = "terraformvnet"
    address_space       = ["10.0.0.0/16"]
    location            = "eastus"
    resource_group_name = "${azurerm_resource_group.myterraformgroup.name}"
}

resource "azurerm_network_security_group" "myterraformnsg" {
    name                = "terraformNetworkSecurityGroup"
    location            = "eastus"
    resource_group_name = "${azurerm_resource_group.myterraformgroup.name}"

    security_rule {
        name                       = "SSH"
        priority                   = 100
        direction                  = "Inbound"
        access                     = "Allow"
        protocol                   = "Tcp"
        source_port_range          = "*"
        destination_port_range     = "22"
        source_address_prefix      = "*"
        destination_address_prefix = "*"
    }
}

resource "azurerm_public_ip" "myterraformpublicip" {
    name                         = "myPublicIP"
    location                     = "eastus"
    resource_group_name          = "${azurerm_resource_group.myterraformgroup.name}"
    allocation_method            = "Dynamic"
}

resource "azurerm_linux_virtual_machine" "myterraformvm" {
    name                  = "terraformVM"
    location              = "eastus"
    resource_group_name   = "${azurerm_resource_group.myterraformgroup.name}"
    network_interface_ids = ["${azurerm_network_interface.myterraformnic.id}"]
    size                  = "Standard_DS1_v2"

    computer_name  = "terrafromvm"
    admin_username = "azureuser"
    disable_password_authentication = true

    admin_ssh_key {
        username       = "azureuser"
        public_key     = "${file("id_rsa.pub")}"
    }

    connection {
        type = "ssh"
        user = "azureuser"
        host = "${azurerm_public_ip.myterraformpublicip.fqdn}"
        private_key = "${file("id_rsa")}"
        timeout = "5m"
    }

    provisioner "file" {
        source = "example_file.txt"
        destination = "/tmp/example_file.yml"
    }

    provisioner "remote-exec" {
        inline = [
          "sudo apt-get update",
        ]
    }
}
</code>```

id_rsa and id_rsa.pub are in same folder are .tf file.

Also tried higher timeouts with 10m and 15m.

Thanks

答:
This github issue addresses the same problem as yours and proper explanation is provided for this issue.

The fix for this problem is updating the allocation_method to "Static".

Hope this helps!

Body:
I want to copy file and run some shell commands after VM is created in Azure. I use provisioner 'file' and provisioner 'remote-exec' and created VM using ssh keys. Everything works fine till provisoner file and I get following error:

Error: timeout - last error: dial tcp :22: connect: connection refused

When I do ssh -i id_rsa <username>@<ip_address> it works fine. I get this IP address from Azure Portal.

Here is my tf file:

resource "azurerm_resource_group" "myterraformgroup" {
    name     = "terrafromresources"
    location = "eastus"
}

resource "azurerm_virtual_network" "myterraformnetwork" {
    name                = "terraformvnet"
    address_space       = ["10.0.0.0/16"]
    location            = "eastus"
    resource_group_name = "${azurerm_resource_group.myterraformgroup.name}"
}

resource "azurerm_network_security_group" "myterraformnsg" {
    name                = "terraformNetworkSecurityGroup"
    location            = "eastus"
    resource_group_name = "${azurerm_resource_group.myterraformgroup.name}"

    security_rule {
        name                       = "SSH"
        priority                   = 100
        direction                  = "Inbound"
        access                     = "Allow"
        protocol                   = "Tcp"
        source_port_range          = "*"
        destination_port_range     = "22"
        source_address_prefix      = "*"
        destination_address_prefix = "*"
    }
}

resource "azurerm_public_ip" "myterraformpublicip" {
    name                         = "myPublicIP"
    location                     = "eastus"
    resource_group_name          = "${azurerm_resource_group.myterraformgroup.name}"
    allocation_method            = "Dynamic"
}

resource "azurerm_linux_virtual_machine" "myterraformvm" {
    name                  = "terraformVM"
    location              = "eastus"
    resource_group_name   = "${azurerm_resource_group.myterraformgroup.name}"
    network_interface_ids = ["${azurerm_network_interface.myterraformnic.id}"]
    size                  = "Standard_DS1_v2"

    computer_name  = "terrafromvm"
    admin_username = "azureuser"
    disable_password_authentication = true

    admin_ssh_key {
        username       = "azureuser"
        public_key     = "${file("id_rsa.pub")}"
    }

    connection {
        type = "ssh"
        user = "azureuser"
        host = "${azurerm_public_ip.myterraformpublicip.fqdn}"
        private_key = "${file("id_rsa")}"
        timeout = "5m"
    }

    provisioner "file" {
        source = "example_file.txt"
        destination = "/tmp/example_file.yml"
    }

    provisioner "remote-exec" {
        inline = [
          "sudo apt-get update",
        ]
    }
}

id_rsa and id_rsa.pub are in same folder are .tf file.

Also tried higher timeouts with 10m and 15m.

Thanks


问:
Bash: wrong pipe output when using "sudo sh -c"
I have a pipe of commands and I use "sudo sh -c" for getting sudo permission throughout the whole pipe commands.

The problem that I am facing is that commands like awk have different behaviour when "sudo sh -c" is used.

In particular,

sudo wc -c Mybib.bin |sudo awk '{print $1;}'

gives 1509644

while

sudo sh -c "wc -c Mybib.bin |awk '{print $1;}'"

gives 1509644 Mybib.bin

So, in the second case looks like the awk command is not invoked at all.

Thanks for any help.

答:
It is, but the double quotes are allowing the $1 to be replaced before invocation, resulting in {print ;}.

```<code>sudo sh -c "wc -c Mybib.bin |awk '"'{print $1;}'"'"
</code>```

Also...

```<code>sudo sh -c "wc -c < Mybib.bin"
</code>```

Body:
It is, but the double quotes are allowing the $1 to be replaced before invocation, resulting in {print ;}.

sudo sh -c "wc -c Mybib.bin |awk '"'{print $1;}'"'"

Also...

sudo sh -c "wc -c < Mybib.bin"


问:
Error in R - Number of columns of result is not a multiple of vector length (arg 1)
I received this error when I tried running this code in R

```<code>const1 = c(1,1,1,1,1)
const2 = c(1,1,1,1,1)
const3 = c(1,1,1,1,1)
const4 = c(1,1,1,1,1)
const5 = c(1,1,1,1,1)
const6 = c(1,1,1,1,1)
const7 = c(35,16,125,25,40,5)
const8 = c(37,17,130,27,43,7)
const9 = c(39,18,136,29,46,8)
const10 = c(42,19,139,30,50,10)
const11 = c(45,20,144,33,52,11)
f.con <- rbind(const1,const2,const3,const4,const5,const6,const7,const8,const9,const10,const11)
</code>```

Warning message:In rbind(const1, const2, const3, const4, const5, const6, const7,

  number of columns of result is not a multiple of vector length (arg 1)

答:
We can get all the vectors in to a list, convert to data.frame with map and bind them into a single dataset

```<code>library(purrr)
map_dfr(mget(ls(pattern = '^const\\d+$')), ~ as.data.frame(t(.x)))
</code>```

Or with unnest_wider

```<code>library(tidyr)
mget(paste0('const', 1:11)) %>%
      tibble(col1 = .) %>%
      unnest_wider(c(col1))
</code>```

Or using base R, after creating a list of vectors, pad NA at the end for shorter list elements and then rbind

```<code>lst1 <- mget(paste0('const', 1:11))
do.call(rbind, unname(lapply(lst1, `length<-`, max(lengths(lst1)))))
#        [,1] [,2] [,3] [,4] [,5] [,6]
# [1,]    1    1    1    1    1   NA
# [2,]    1    1    1    1    1   NA
# [3,]    1    1    1    1    1   NA
# [4,]    1    1    1    1    1   NA
# [5,]    1    1    1    1    1   NA
# [6,]    1    1    1    1    1   NA
# [7,]   35   16  125   25   40    5
# [8,]   37   17  130   27   43    7
# [9,]   39   18  136   29   46    8
#[10,]   42   19  139   30   50   10
#[11,]   45   20  144   33   52   11
</code>```

Body:
I received this error when I tried running this code in R

const1 = c(1,1,1,1,1)
const2 = c(1,1,1,1,1)
const3 = c(1,1,1,1,1)
const4 = c(1,1,1,1,1)
const5 = c(1,1,1,1,1)
const6 = c(1,1,1,1,1)
const7 = c(35,16,125,25,40,5)
const8 = c(37,17,130,27,43,7)
const9 = c(39,18,136,29,46,8)
const10 = c(42,19,139,30,50,10)
const11 = c(45,20,144,33,52,11)
f.con <- rbind(const1,const2,const3,const4,const5,const6,const7,const8,const9,const10,const11)

Warning message:In rbind(const1, const2, const3, const4, const5, const6, const7,

  number of columns of result is not a multiple of vector length (arg 1)

Body:
We can get all the vectors in to a list, convert to data.frame with map and bind them into a single dataset

library(purrr)
map_dfr(mget(ls(pattern = '^const\\d+$')), ~ as.data.frame(t(.x)))

Or with unnest_wider

library(tidyr)
mget(paste0('const', 1:11)) %>%
      tibble(col1 = .) %>%
      unnest_wider(c(col1))

Or using base R, after creating a list of vectors, pad NA at the end for shorter list elements and then rbind

lst1 <- mget(paste0('const', 1:11))
do.call(rbind, unname(lapply(lst1, `length<-`, max(lengths(lst1)))))
#        [,1] [,2] [,3] [,4] [,5] [,6]
# [1,]    1    1    1    1    1   NA
# [2,]    1    1    1    1    1   NA
# [3,]    1    1    1    1    1   NA
# [4,]    1    1    1    1    1   NA
# [5,]    1    1    1    1    1   NA
# [6,]    1    1    1    1    1   NA
# [7,]   35   16  125   25   40    5
# [8,]   37   17  130   27   43    7
# [9,]   39   18  136   29   46    8
#[10,]   42   19  139   30   50   10
#[11,]   45   20  144   33   52   11


问:
Compute and Analyze the run-time
```<code>public static long Compute(int x){
    long count = 0;
    if(x==1)
        return count=1;
    else if(x==3)
        for(int i =0;i<x;i++){
            count+=i;
    }
    else if (x==5)
            for(int j=0;j<x;j++)
                for(int k=0;j<=x;k++)
                     return +=(i*j);
                }
            }
    return result;
}
</code>```

Im trying to understand how to solve each of the statements to formulate the run-time T(n). I have 2 if statements and a for-loop and a nested for-loop. My answer here is O(n^2).

答:
f = O(g) means that there's a N and c, so that n>N implies f(n) <= c * g(n). (I assume f and g are non-negative).

The code takes constant time for x>5. So it's O(1).

Title: Compute and Analyze the run-time

Body:
public static long Compute(int x){
    long count = 0;
    if(x==1)
        return count=1;
    else if(x==3)
        for(int i =0;i<x;i++){
            count+=i;
    }
    else if (x==5)
            for(int j=0;j<x;j++)
                for(int k=0;j<=x;k++)
                     return +=(i*j);
                }
            }
    return result;
}

Im trying to understand how to solve each of the statements to formulate the run-time T(n). I have 2 if statements and a for-loop and a nested for-loop. My answer here is O(n^2).


问:
SessionNotCreatedException: Message: session not created: This version of ChromeDriver only supports Chrome version 81
I am currently new to robot framework.I am currently using latest window version of chrome and chromedriver which is 80 but when i try to run the test it gives the message "SessionNotCreatedException: Message: session not created: This version of ChromeDriver only supports Chrome version 81" in pycharm but currently beta version of 81 is only available. I have tried uninstalling everthing and reinstalling it again but nothing works can anyone help me with this.Thank you!

Screenshots below:

答: I too had a similar problem. And I've got a solution .. Download the matching chromedriver, and place the chromedriver under the /usr/local/bin path. It works.


问:
Performance of operator| vs operators+
Is there any major difference between | and + that would affect a code's performance in the long run? or are both O(1)? the code i am working with is something like this:

```<code>uint64_t dostuff(uint64_t a,uint64_t b){
        // the max values of the inputs are 2^32 - 1

        // lots of stuff involving boolean operators
        // that have no way of being substituted by
        // arithmetic operators

        return (a << 32) + b;
        //or
        return (a << 32) | b;
}
</code>```

the code will be used many times, so i want to speed it up as much as possible.

答:
This is platform-specific (and likely compiler-specific). On the SPU's on the PS3, dynamic OR's are quite expensive if I remember correctly. I'm not sure of the numbers but I think that it ends up by dividing it into multiple operations, causing the cost to expand to several instructions. On x86/x64 or most modern CISC it is quite likely that either one is just one instruction and is very unlikely to cause any pipeline stalls or other costly operations.

Edit:
The reason for the cost is because the Cell processor only has one general-purpose-register which means that it can't load both variables into standard registers and perform the optimization. Instead the values have to be loaded into the altivec-register set where the operation has to be done, the result then has to be fetched from the altivec registers into the gpr by a mask in order to retrieve the result.

If you are pushing these operations onto a PS3 or the GPU on any modern computer, you might want to look into how those processors behave. The GPU's might also have similar issues since they're also RISC-processors dedicated towards SIMD-operations.

Title: Performance of operator| vs operators+

Body:
Is there any major difference between | and + that would affect a code's performance in the long run? or are both O(1)? the code i am working with is something like this:

uint64_t dostuff(uint64_t a,uint64_t b){
        // the max values of the inputs are 2^32 - 1

        // lots of stuff involving boolean operators
        // that have no way of being substituted by
        // arithmetic operators

        return (a << 32) + b;
        //or
        return (a << 32) | b;
}

the code will be used many times, so i want to speed it up as much as possible.


问:
C++ insertion operator for class method
In C++ is there a way to use the insertion operator for a class method?

This operator<< overload is working:

```<code>class Complex {
public:
  //Normal overload:
  friend std::ostream& operator<<(std::ostream &out, const Complex &o) {
    out << "test overload";
    return out;
  }

  Complex() {};
  ~Complex() {};
};
</code>```

I can do this:

```<code>int main()
{
  Complex* o = new Complex();

  std::cout << "This is test: " << *o << "." << std::endl; // => This is test: test overload.
}
</code>```

I know about stream manipulators, like this:

```<code>std::ostream& welcome(std::ostream& out)
{
    int data = 1;
    out << "WELCOME " << data << "\r\n";
    return out;
}

int main()
{
  std::cout << "Hello " << welcome; // => "Hello WELCOME 1\r\n"
}
</code>```

How can I put the welcome method into the Complex class and then how shall I call it from cout (please note that welcome method must access some class member variables)?

My trial:

```<code>class Complex {
public:
  //Normal overload:
  friend std::ostream& operator<<(std::ostream &out, const Complex &o) {
    out << "test overload";
    return out;
  }

  std::ostream& welcome(std::ostream& out) {
    out << "WELCOME " << data << "\r\n";
    return out;
  }

  Complex() { data = 1; };
  ~Complex() {};
private:
  int data;
};

int main()
{
  Complex* o = new Complex();

  std::cout << "This is test2: " << o->welcome << std::endl; // compile error
}
</code>```

答:
One easy way to pick a different << overload is to use a different type.

```<code>#include <iostream>

class Complex {
public:
  //Normal overload:
  friend std::ostream& operator<<(std::ostream &out, const Complex &o) {
    out << "test overload";
    return out;
  }

  struct extra_info {
      const Complex& parent;
      extra_info(const Complex& p) : parent(p) {}
      friend std::ostream& operator<<(std::ostream& out, const extra_info& ei){
        int i = 1;
        out << "extrainfo " << i;
        return out;
      }
  };
  extra_info extrainfo() {
      return {*this};
  }

  Complex() {};
  ~Complex() {};
};

int main() {
    Complex c;
    std::cout << c << "\n";
    std::cout << c.extrainfo();
}
</code>```

Output:

```<code>test overload
extrainfo 1
</code>```

I suppose in your real code you are using members. Hence the helper type must hold a reference to the Complex instance.

Title: C++ insertion operator for class method

Body:
In C++ is there a way to use the insertion operator for a class method?

This operator<< overload is working:

class Complex {
public:
  //Normal overload:
  friend std::ostream& operator<<(std::ostream &out, const Complex &o) {
    out << "test overload";
    return out;
  }

  Complex() {};
  ~Complex() {};
};

I can do this:

int main()
{
  Complex* o = new Complex();

  std::cout << "This is test: " << *o << "." << std::endl; // => This is test: test overload.
}

I know about stream manipulators, like this:

std::ostream& welcome(std::ostream& out)
{
    int data = 1;
    out << "WELCOME " << data << "\r\n";
    return out;
}

int main()
{
  std::cout << "Hello " << welcome; // => "Hello WELCOME 1\r\n"
}

How can I put the welcome method into the Complex class and then how shall I call it from cout (please note that welcome method must access some class member variables)?

My trial:

class Complex {
public:
  //Normal overload:
  friend std::ostream& operator<<(std::ostream &out, const Complex &o) {
    out << "test overload";
    return out;
  }

  std::ostream& welcome(std::ostream& out) {
    out << "WELCOME " << data << "\r\n";
    return out;
  }

  Complex() { data = 1; };
  ~Complex() {};
private:
  int data;
};

int main()
{
  Complex* o = new Complex();

  std::cout << "This is test2: " << o->welcome << std::endl; // compile error
}

Body:
One easy way to pick a different << overload is to use a different type.

#include <iostream>

class Complex {
public:
  //Normal overload:
  friend std::ostream& operator<<(std::ostream &out, const Complex &o) {
    out << "test overload";
    return out;
  }

  struct extra_info {
      const Complex& parent;
      extra_info(const Complex& p) : parent(p) {}
      friend std::ostream& operator<<(std::ostream& out, const extra_info& ei){
        int i = 1;
        out << "extrainfo " << i;
        return out;
      }
  };
  extra_info extrainfo() {
      return {*this};
  }

  Complex() {};
  ~Complex() {};
};

int main() {
    Complex c;
    std::cout << c << "\n";
    std::cout << c.extrainfo();
}

Output:

test overload
extrainfo 1

I suppose in your real code you are using members. Hence the helper type must hold a reference to the Complex instance.


问:
index.js not found in React application using Express (Node.js)
I am trying to use my own express server for the production of a React app, but I am getting a 404 status of not found for my index.js which have the React js script.

The folder structure that I am using is the following

```<code>server.js
+public
| index.html
|
__+ src
   |
   __ index.js
</code>```

(index.html is in the public folder, index.js is in the src folder)

So In my server.js I have :

```<code>// Built-in Node.js modules
let fs = require('fs');
let path = require('path');

// Third-party Node.js modules
let express = require('express');

// Express App
let public_dir = path.join(__dirname, 'public');

// let port = 80; // production port
let port = 8000; // test/debug port

let app = express();
app.use(express.static(public_dir));

app.listen(port, () => {
    console.log("Now listening on port " + port);
});
</code>```

and in my index.html I am calling in my head tag:

```<code><script src="https://unpkg.com/react@16/umd/react.development.js" crossorigin></script>
<script src="https://unpkg.com/react-dom@16/umd/react-dom.development.js" crossorigin></script>
<script src="./src/index.js"></script>
</code>```

At the end, when I run the server.js I am getting the following error:

```<code>Failed to load resource: the server responded with a status of 404 (Not Found)
</code>```

In case you might need this is my index.js

```<code>import React from 'react';
import ReactDOM from 'react-dom';
import './index.css';
import App from './App';
import * as serviceWorker from './serviceWorker';

ReactDOM.render(
  <React.StrictMode>

    <App />

  </React.StrictMode>,
  document.getElementById('root')
);

// If you want your app to work offline and load faster, you can change
// unregister() to register() below. Note this comes with some pitfalls.
serviceWorker.unregister();
</code>```

Thank you!

答:
An node.js server isnt like an apache server where you upload an index file and it automatically renders it , you need to tell node.js what to do at route /

```<code>// Built-in Node.js modules
let fs = require('fs');
let path = require('path');

// Third-party Node.js modules
let express = require('express');

// Express App
let public_dir = path.join(__dirname, 'public');

// let port = 80; // production port
let port = 8000; // test/debug port

let app = express();
app.use(express.static(public_dir));

//response with index file

app.get('/', function (req, res) {
   res.sendFile( __dirname + "/" + "index.html" );
})
app.listen(port, () => {
    console.log("Now listening on port " + port);
});
</code>```

Body:
I am trying to use my own express server for the production of a React app, but I am getting a 404 status of not found for my index.js which have the React js script.

The folder structure that I am using is the following

server.js
+public
| index.html
|
__+ src
   |
   __ index.js

(index.html is in the public folder, index.js is in the src folder)

So In my server.js I have :

// Built-in Node.js modules
let fs = require('fs');
let path = require('path');

// Third-party Node.js modules
let express = require('express');

// Express App
let public_dir = path.join(__dirname, 'public');

// let port = 80; // production port
let port = 8000; // test/debug port

let app = express();
app.use(express.static(public_dir));

app.listen(port, () => {
    console.log("Now listening on port " + port);
});

and in my index.html I am calling in my head tag:

At the end, when I run the server.js I am getting the following error:

Failed to load resource: the server responded with a status of 404 (Not Found)

In case you might need this is my index.js

import React from 'react';
import ReactDOM from 'react-dom';
import './index.css';
import App from './App';
import * as serviceWorker from './serviceWorker';

ReactDOM.render(
  <React.StrictMode>

    <App />

  </React.StrictMode>,
  document.getElementById('root')
);

// If you want your app to work offline and load faster, you can change
// unregister() to register() below. Note this comes with some pitfalls.
serviceWorker.unregister();

Thank you!

Body:
An node.js server isnt like an apache server where you upload an index file and it automatically renders it , you need to tell node.js what to do at route /

// Built-in Node.js modules
let fs = require('fs');
let path = require('path');

// Third-party Node.js modules
let express = require('express');

// Express App
let public_dir = path.join(__dirname, 'public');

// let port = 80; // production port
let port = 8000; // test/debug port

let app = express();
app.use(express.static(public_dir));

//response with index file

app.get('/', function (req, res) {
   res.sendFile( __dirname + "/" + "index.html" );
})
app.listen(port, () => {
    console.log("Now listening on port " + port);
});


问:
weighted least absolute regression in python?
I was wondering if there's a function in Python that can find the best-fitted line (in 2D) or best-fitted plane (in 3D) of a set of data by least absolute deviation and while considering uncertainties of the points.

In fact, I have 3d points, which I want the best-fit plane of them. There is Weighted least square (WLS) fit function in both sklearn and statsmodel python libraries, and by putting q=0.5 in quantile regression of statsmodel I get the least absolute deviation. However, how can I have Weighted Least Absolute regression fit function?

答: Least-squares, or equivalently chi^2-based, methods are easier because their first derivative is a smooth function. If you want absolute deviation to be minimized then you can use scipy.minimize() with appropriately defined objective function. The other approach is to find ranges on which your objective function is smooth, optimize each range in a linear fashion, and then choose optimal value among these results.


问:
SpringBoot complementary configuration file in system directory
I need some help to consume another .yml file that complement the original one in the application. Then I have a file filled by me(dev) however some configuration(as database infos) should be inserted by our clients.

The one which is in the application(application.yml) have general configs, the other on path C:\Users\Public\ datasource.yml have:

```<code>spring:
  datasource:
    platform: postgres
    driverClassName: org.postgresql.Driver
    url: jdbc:postgresql://localhost:5432/mydb
    username: foo
    password: bar
</code>```

Has anyone done this before?

答:
configure the below annotation at your main configuration class

```<code>@PropertySource("classpath:datasource.yml")
</code>```

Body:
I need some help to consume another .yml file that complement the original one in the application. Then I have a file filled by me(dev) however some configuration(as database infos) should be inserted by our clients.

The one which is in the application(application.yml) have general configs, the other on path C:\Users\Public\ datasource.yml have:

spring:
  datasource:
    platform: postgres
    driverClassName: org.postgresql.Driver
    url: jdbc:postgresql://localhost:5432/mydb
    username: foo
    password: bar

Has anyone done this before?

Body:
configure the below annotation at your main configuration class

@PropertySource("classpath:datasource.yml")


问:
how to provide inbound access from public internet to an app hosted in an Azure private kubernetes cluster
I deployed an application in an Azure K8S cluster, using NGINX as gateway, with a public static IP, based on AKS & PUBLIC-IP and on AKS & NGINX.

Now I need to deploy the application in an Azure private cluster, ie, running in a private vnet (see CREATE PRIVATE AKS); attempting to assign a public static IP to NGINX does not work, which can be expected as the load-balancer expects a private IP, not a public IP.

How can I provide inbound access to my app hosted in a private cluster, using NGINX and a public static IP?

答:
Based on your description i understand that you want to have ingress traffic through your NGINX ingress controller which has a Loadbalancer service with static IP. If your deployment is correctly configured the a Loadbalancer service should be assigned to your NGINX ingress controller with a public IP. Since i dont know your namespaces, naming of deployments etc try:

```<code>kubectl get services --all-namespaces | grep -i loadbalancer
</code>```

You should be able to find that an nginx loadbalancer service has a public IP. Now since NGINX is your ingress controller this means that you have a Layer 7 loadbalancer as ingress so you need to create an ingress route to your application running in AKS. This is documented here from Azure NGINX ingress but also here Ingress K8s

Body:
Based on your description i understand that you want to have ingress traffic through your NGINX ingress controller which has a Loadbalancer service with static IP. If your deployment is correctly configured the a Loadbalancer service should be assigned to your NGINX ingress controller with a public IP. Since i dont know your namespaces, naming of deployments etc try:

kubectl get services --all-namespaces | grep -i loadbalancer

You should be able to find that an nginx loadbalancer service has a public IP. Now since NGINX is your ingress controller this means that you have a Layer 7 loadbalancer as ingress so you need to create an ingress route to your application running in AKS. This is documented here from Azure NGINX ingress but also here Ingress K8s


问:
Select the First value Greater than a specific value
I have two tables first table is Stock Receiving

```<code>  Store   Item_No        Receiving_Time

   2       1         2020-05-27 13:44:27.829 UTC
   2       1         2020-05-27 17:44:28.829 UTC
   2       1         2020-05-28 14:44:28.829 UTC
   2       1         2020-05-29 14:44:28.829 UTC
</code>```

Second one is item going Out of Stock

```<code>   Store   Item_No        Out_OF_Stock_Time

       2       1         2020-05-26 13:44:27.829 UTC
       2       1         2020-05-27 18:44:28.829 UTC
       2       1         2020-05-27 20:44:28.829 UTC
</code>```

So i want to find the value when the last out of stock was filled in my case last out of stock happens on 2020-05-27 20:44:28.829 UTC so output value should be 2020-05-28 14:44:28.829 UTC
from Stock Receiving Table

SO output:

```<code>Store Item_No.    Last_OutOfStock.              Received Time                   Difference Time
2.      1        2020-05-27 20:44:28.829 UTC    2020-05-28 14:44:28.829 UTC
</code>```

My Query:

```<code>Select  o.store, o.item_No, Max(o.Out_OF_Stock_Time) as S, Min(r.Receiving_Time) as R
from Out_of_Stock o
join Stock_Receiving r on o.store = r.store and o.item_no = r.item_no
and S < R
group By o.store, o.item_No;
</code>```

So it's not getting me the right result.

答:
If your dbms supports you can use OUTER APPLY</p>

```<code>SELECT * FROM
    (
        Select  o.store, o.item_No, Max(o.Out_OF_Stock_Time) as s
        from Out_of_Stock o
        group by o.store, o.item_No
    ) xo
    OUTER APPLY (SELECT Min(Receiving_Time) Receiving_Time FROM Stock_Receiving r
        WHERE xo.store = r.store and xo.item_no = r.item_no and r.Receiving_Time > xo.S) xs
</code>```

Body:
I have two tables first table is Stock Receiving

  Store   Item_No        Receiving_Time

   2       1         2020-05-27 13:44:27.829 UTC
   2       1         2020-05-27 17:44:28.829 UTC
   2       1         2020-05-28 14:44:28.829 UTC
   2       1         2020-05-29 14:44:28.829 UTC

Second one is item going Out of Stock

   Store   Item_No        Out_OF_Stock_Time

       2       1         2020-05-26 13:44:27.829 UTC
       2       1         2020-05-27 18:44:28.829 UTC
       2       1         2020-05-27 20:44:28.829 UTC

So i want to find the value when the last out of stock was filled in my case last out of stock happens on 2020-05-27 20:44:28.829 UTC so output value should be 2020-05-28 14:44:28.829 UTC
from Stock Receiving Table

SO output:

Store Item_No.    Last_OutOfStock.              Received Time                   Difference Time
2.      1        2020-05-27 20:44:28.829 UTC    2020-05-28 14:44:28.829 UTC

My Query:

Select  o.store, o.item_No, Max(o.Out_OF_Stock_Time) as S, Min(r.Receiving_Time) as R
from Out_of_Stock o
join Stock_Receiving r on o.store = r.store and o.item_no = r.item_no
and S < R
group By o.store, o.item_No;

So it's not getting me the right result.

Body:
If your dbms supports you can use OUTER APPLY

SELECT * FROM
    (
        Select  o.store, o.item_No, Max(o.Out_OF_Stock_Time) as s
        from Out_of_Stock o
        group by o.store, o.item_No
    ) xo
    OUTER APPLY (SELECT Min(Receiving_Time) Receiving_Time FROM Stock_Receiving r
        WHERE xo.store = r.store and xo.item_no = r.item_no and r.Receiving_Time > xo.S) xs


问:
R plot line directly as raster array without saving to file
I have been looking around for how to plot directly as raster array, rather than have to plot to a file and then load it back. See the code below

```<code>iter=1;
thumbnail_list=list();
tr=apply(datamatrix,1,function(x){
        png(sprintf("./tmpplot/p_%s.png",iter), height=40,width=80)    #plot to a png file
        par(mar=c(0,0,0,0));
        plot(x,type="l",xlab="",ylab="")
        dev.off()
        thumbnail_list[[iter]]<<-readPNG(sprintf("./tmpplot/p_%s.png",iter)).  #load it back to memory
        iter<<-iter+1
})
</code>```

datamatrix contains 100 rows, each row 50 columns (i.e. each row is a line with 50 points).
I think my current strategy is tedious and there should be better way.

Basically I want to generate an image labeled plot like this

Currently I have to "plot each of those small image to file" separately and the load back through readPNG, and add to plot with rasterimage.

How to avoid the "plot to file" step?

答:
Is this what you are looking for?

```<code>library(raster)
r <- raster(datamatrix)
plot(r)
image(r)
</code>```

And more advanced plotting in other packages

Body:
I have been looking around for how to plot directly as raster array, rather than have to plot to a file and then load it back. See the code below

iter=1;
thumbnail_list=list();
tr=apply(datamatrix,1,function(x){
        png(sprintf("./tmpplot/p_%s.png",iter), height=40,width=80)    #plot to a png file
        par(mar=c(0,0,0,0));
        plot(x,type="l",xlab="",ylab="")
        dev.off()
        thumbnail_list[[iter]]<<-readPNG(sprintf("./tmpplot/p_%s.png",iter)).  #load it back to memory
        iter<<-iter+1
})

datamatrix contains 100 rows, each row 50 columns (i.e. each row is a line with 50 points).
I think my current strategy is tedious and there should be better way.

Basically I want to generate an image labeled plot like this

Currently I have to "plot each of those small image to file" separately and the load back through readPNG, and add to plot with rasterimage.

How to avoid the "plot to file" step?

Body:
Is this what you are looking for?

library(raster)
r <- raster(datamatrix)
plot(r)
image(r)

And more advanced plotting in other packages


问:
How to check if consecutive digits in a number are even or odd?
I am doing some exercises and learning Python. I need to be able to check for an input number whether its consecutive digits are even or odd. So, if the first number is odd, the next should be even and so on in order for the terms to comply. I have the following code:

```<code>def par_nepar(n):
    cifre = []

    while n != 0:
        cifre.append(n % 10)
        n //= 10

    cifre = cifre[::-1]
    ind = cifre[0]
    for broj in cifre:
        if cifre[0] % 2 == 0:
            # for br in range(len(cifre)):
            if cifre[ind + 1] % 2 != 0:
                ind = cifre[ind+1]

n = int(input("Unesite broj n: "))
print(par_nepar(n))
</code>```

As you can see, I am struggling with index looping. I took the input number and transformed it into a list. Created a variable for index[0] and don't really know how to loop through consecutive indexes. I know I might be able to use zip or enumerate but I think that is not a truly pythonic solution here and probably there is a simpler way to loop over consecutive list numbers and compare them to index[-1].

Input examples:

```<code>>>>print(par_nepar(2749)) # Every consecutive digits shifts odd->even or even->odd
True
>>>print(par_nepar(2744)) # Two last digits are even
False
</code>```

答:
I think instead of getting an integer as input you can get a string and convert it to a list of integers</p>

```<code>def par_nepar(n):
    s,h=0,0
    for i in range(len(n)-1):
        if n[i]%2==0 and n[i+1]%2!=0:
            s+=1
        elif n[i]%2!=0 and n[i+1]%2==0:
            h+=1
    if s==len(n)//2 or h==len(n)//2:
        print("The number complies to the needed terms")
    else:
        print("The number does not complies to the needed terms")

# list of digits in the provided input
n = list(map(lambda x: int(x),list(input("Unesite broj n: "))))
par_nepar(n)
</code>```

Body:
I am doing some exercises and learning Python. I need to be able to check for an input number whether its consecutive digits are even or odd. So, if the first number is odd, the next should be even and so on in order for the terms to comply. I have the following code:

def par_nepar(n):
    cifre = []

    while n != 0:
        cifre.append(n % 10)
        n //= 10

    cifre = cifre[::-1]
    ind = cifre[0]
    for broj in cifre:
        if cifre[0] % 2 == 0:
            # for br in range(len(cifre)):
            if cifre[ind + 1] % 2 != 0:
                ind = cifre[ind+1]

n = int(input("Unesite broj n: "))
print(par_nepar(n))

As you can see, I am struggling with index looping. I took the input number and transformed it into a list. Created a variable for index[0] and don't really know how to loop through consecutive indexes. I know I might be able to use zip or enumerate but I think that is not a truly pythonic solution here and probably there is a simpler way to loop over consecutive list numbers and compare them to index[-1].

Input examples:

>>>print(par_nepar(2749)) # Every consecutive digits shifts odd->even or even->odd
True
>>>print(par_nepar(2744)) # Two last digits are even
False

Body:
I think instead of getting an integer as input you can get a string and convert it to a list of integers

def par_nepar(n):
    s,h=0,0
    for i in range(len(n)-1):
        if n[i]%2==0 and n[i+1]%2!=0:
            s+=1
        elif n[i]%2!=0 and n[i+1]%2==0:
            h+=1
    if s==len(n)//2 or h==len(n)//2:
        print("The number complies to the needed terms")
    else:
        print("The number does not complies to the needed terms")

# list of digits in the provided input
n = list(map(lambda x: int(x),list(input("Unesite broj n: "))))
par_nepar(n)


问:
Python, element wise sorting of a DataFrame
I am trying to sort each row of a DataFrame element wise.

Input:

```<code>    A   B   C
0   10  5   6
1   3   6   5
2   1   2   3
</code>```

Output:

```<code>    A   B   C
0   10  6   5
1   6   5   3
2   3   2   1
</code>```

It feels this should be easy but I've been failing for  while... Very much a beginner in Python.

答:
Use np.sort with swap ordering by indexing:

```<code>df1 = pd.DataFrame(np.sort(df.to_numpy(), axis=1)[:, ::-1],
                   index=df.index,
                   columns=df.columns)
print (df1)
    A  B  C
0  10  6  5
1   6  5  3
2   3  2  1
</code>```

Pandas solution, slowier, is apply sorting for each row separately, convert to array and then to Series:

```<code>f = lambda x: pd.Series(x.sort_values(ascending=False).to_numpy(), index=df.columns)
df1 = df.apply(f, axis=1)
print (df1)
    A  B  C
0  10  6  5
1   6  5  3
2   3  2  1
</code>```

If possible missing values for me working:

```<code>print (df)
      A    B    C
0  10.0  6.0  5.0
1   5.0  3.0  NaN
2   2.0  1.0  NaN

df1 = pd.DataFrame(np.sort(df.to_numpy(), axis=1)[:, ::-1],
                   index=df.index,
                   columns=df.columns)
print (df1)
      A    B    C
0  10.0  6.0  5.0
1   NaN  5.0  3.0
2   NaN  2.0  1.0
</code>```

In pandas is possible use na_position parameter for specify order of them:

```<code>f = lambda x: pd.Series(x.sort_values(ascending=False, na_position='first').to_numpy(),
                        index=df.columns)
df1 = df.apply(f, axis=1)
print (df1)
      A    B    C
0  10.0  6.0  5.0
1   NaN  5.0  3.0
2   NaN  2.0  1.0

f = lambda x: pd.Series(x.sort_values(ascending=False, na_position='last').to_numpy(),
                        index=df.columns)
df1 = df.apply(f, axis=1)
print (df1)
      A    B    C
0  10.0  6.0  5.0
1   5.0  3.0  NaN
2   2.0  1.0  NaN
</code>```

Body:
I am trying to sort each row of a DataFrame element wise.

Input:

    A   B   C
0   10  5   6
1   3   6   5
2   1   2   3

Output:

    A   B   C
0   10  6   5
1   6   5   3
2   3   2   1

It feels this should be easy but I've been failing for  while... Very much a beginner in Python.

Body:
Use np.sort with swap ordering by indexing:

df1 = pd.DataFrame(np.sort(df.to_numpy(), axis=1)[:, ::-1],
                   index=df.index,
                   columns=df.columns)
print (df1)
    A  B  C
0  10  6  5
1   6  5  3
2   3  2  1

Pandas solution, slowier, is apply sorting for each row separately, convert to array and then to Series:

f = lambda x: pd.Series(x.sort_values(ascending=False).to_numpy(), index=df.columns)
df1 = df.apply(f, axis=1)
print (df1)
    A  B  C
0  10  6  5
1   6  5  3
2   3  2  1

If possible missing values for me working:

print (df)
      A    B    C
0  10.0  6.0  5.0
1   5.0  3.0  NaN
2   2.0  1.0  NaN

df1 = pd.DataFrame(np.sort(df.to_numpy(), axis=1)[:, ::-1],
                   index=df.index,
                   columns=df.columns)
print (df1)
      A    B    C
0  10.0  6.0  5.0
1   NaN  5.0  3.0
2   NaN  2.0  1.0

In pandas is possible use na_position parameter for specify order of them:

f = lambda x: pd.Series(x.sort_values(ascending=False, na_position='first').to_numpy(),
                        index=df.columns)
df1 = df.apply(f, axis=1)
print (df1)
      A    B    C
0  10.0  6.0  5.0
1   NaN  5.0  3.0
2   NaN  2.0  1.0

f = lambda x: pd.Series(x.sort_values(ascending=False, na_position='last').to_numpy(),
                        index=df.columns)
df1 = df.apply(f, axis=1)
print (df1)
      A    B    C
0  10.0  6.0  5.0
1   5.0  3.0  NaN
2   2.0  1.0  NaN


问:
Bulk deleting from extension's localstorage by value?
I'm using localstorage to track domain visits and their timestamp.

Here's how I'm setting it:

```<code>localStorage.setItem(`${domain[0]}`, JSON.stringify(Date.now()));
</code>```

What code would I use to delete all rows with a timestamp that's older than 30 days so users don't end up with too much extra data that probably won't be used?

I've seen a lot of examples about deleting individual rows based on the key.  But I can't find anything related to bulk deleting based upon the values.

答:
Enumerate all key/value pairs explicitly:</p>

```<code>const cutOff = Date.now() - 30 * 24 * 3600 * 1000;
Object.entries(localStorage).forEach(([k, v]) => {
  const time = JSON.parse(v);
  if (time < cutOff) {
    delete localStorage[k];
  }
});
</code>```

Body:
I'm using localstorage to track domain visits and their timestamp.

Here's how I'm setting it:

localStorage.setItem(`${domain[0]}`, JSON.stringify(Date.now()));

What code would I use to delete all rows with a timestamp that's older than 30 days so users don't end up with too much extra data that probably won't be used?

I've seen a lot of examples about deleting individual rows based on the key.  But I can't find anything related to bulk deleting based upon the values.

Body:
Enumerate all key/value pairs explicitly:

const cutOff = Date.now() - 30 * 24 * 3600 * 1000;
Object.entries(localStorage).forEach(([k, v]) => {
  const time = JSON.parse(v);
  if (time < cutOff) {
    delete localStorage[k];
  }
});


问:
replace a pipe delimited column using awk
I have a column seperated using pipe delimited , I have to replace the entire column with some other value .

Example :

A|B|C
I want to replace second column with "Z" as ,
A|Z|C

答:
Below command provided the expected solution,

```<code>awk -F'|' '{$2="string";print}' file_name > new_file_name
</code>```

$2 --> denotes the second position of the delimiter, |

Body:
Below command provided the expected solution,

awk -F'|' '{$2="string";print}' file_name > new_file_name

$2 --> denotes the second position of the delimiter, |


问:
Intellij create sample struts web project with java,then show this error
Failed to download 'http://central.maven.org/maven2/org/apache/struts/struts2-core/2.5.14.1/struts2-core-2.5.14.1.jar':
central.maven.org</p>

答:
If you have URL to Maven Central Repository in your pom.xml defined like:

```<code>    <repository>
        <id>Maven Central</id>
        <name>Maven Central Repository</name>
        <url>http://central.maven.org/maven2</url>
    </repository>
</code>```

then url needs to be updated, to

```<code>    <repository>
        <id>Maven Central</id>
        <name>Maven Central Repository</name>
        <url>https://repo1.maven.org/maven2</url>
    </repository>
</code>```

because: "Beginning January 15, 2020, The Central Repository will no longer support communication over HTTP" (https://blog.sonatype.com/central-repository-moving-to-https)

Body:
If you have URL to Maven Central Repository in your pom.xml defined like:

    <repository>
        <id>Maven Central</id>
        <name>Maven Central Repository</name>
        <url>http://central.maven.org/maven2</url>
    </repository>

then url needs to be updated, to

    <repository>
        <id>Maven Central</id>
        <name>Maven Central Repository</name>
        <url>https://repo1.maven.org/maven2</url>
    </repository>

because: "Beginning January 15, 2020, The Central Repository will no longer support communication over HTTP" (https://blog.sonatype.com/central-repository-moving-to-https)


问:
GraphAPI Schema Extensions don't appear for Messages
I would like to add some custom data to emails and to be able to filter them by using GraphAPI.

So far, I was able to create a Schema Extension and it gets returned successfully when I query https://graph.microsoft.com/v1.0/schemaExtensions/ourdomain_EmailCustomFields:

```<code>{
    "@odata.context": "https://graph.microsoft.com/v1.0/$metadata#schemaExtensions/$entity",
    "id": "ourdomain_EmailCustomFields",
    "description": "Custom data for emails",
    "targetTypes": [
        "Message"
    ],
    "status": "InDevelopment",
    "owner": "hiding",
    "properties": [
        {
            "name": "MailID",
            "type": "String"
        },
        {
            "name": "ProcessedAt",
            "type": "DateTime"
        }
    ]
}
</code>```

Then I patched a specific message https://graph.microsoft.com/v1.0/me/mailFolders/Inbox/Messages/hidingmessageid:

```<code>PATCH Request
{"ourdomain_EmailCustomFields":{"MailID":"12","ProcessedAt":"2020-05-27T16:21:19.0204032-07:00"}}
</code>```

The problem is that when I select the message, the added custom data doesn't appear by executing a GET request: https://graph.microsoft.com/v1.0/me/mailFolders/Inbox/Messages?$top=1&$select=id,subject,ourdomain_EmailCustomFields

Also, the following GET request gives me an error.

Request: https://graph.microsoft.com/v1.0/me/mailFolders/Inbox/Messages?$filter=ourdomain_EmailCustomFields/MailID eq '12'

Response:

```<code>{
    "error": {
        "code": "RequestBroker--ParseUri",
        "message": "Could not find a property named 'e2_someguid_ourdomain_EmailCustomFields' on type 'Microsoft.OutlookServices.Message'.",
        "innerError": {
            "request-id": "someguid",
            "date": "2020-05-29T01:04:53"
        }
    }
}
</code>```

Do you have any ideas on how to resolve the issues?
Thank you!

答:
I took your schema extension and copied and pasted it into my tenant, except with a random app registration I created as owner. then patched an email with your statement, and it does work correctly.

A couple of things here,
I would verify using microsoft graph explorer that everything is correct. eg, log into graph explorer with an admin account  https://developer.microsoft.com/en-us/graph/graph-explorer#
first make sure the schema extensions exists

run a get request for

https://graph.microsoft.com/v1.0/schemaExtensions/DOMAIN_EmailCustomFields

It should return the schemaextension you created.
then

Run a get request for the actual message you patched not all messages that you filtered for now.

https://graph.microsoft.com/v1.0/me/mailFolders/Inbox/Messages/MESSAGEID?$select=DOMAIN_EmailCustomFields

here the response should be the email you patched and your EmailCustomField should be in the data somewhere, if it is not, that means that your patch did not work.

then you can run patch again from graph explorer

I did all this from graph explorer, easiest way to confirm.

two other things,
1) maybe the ?$top=1 in your get first message isn't the same message that you patched?

2) as per the documentation, you cannot use $filter for schema extensions with the message entity. (https://learn.microsoft.com/en-us/graph/known-issues#filtering-on-schema-extension-properties-not-supported-on-all-entity-types) So that second Get will never work.

Hopefully this helps you troubleshoot.

Body:
I would like to add some custom data to emails and to be able to filter them by using GraphAPI.

So far, I was able to create a Schema Extension and it gets returned successfully when I query https://graph.microsoft.com/v1.0/schemaExtensions/ourdomain_EmailCustomFields:

{
    "@odata.context": "https://graph.microsoft.com/v1.0/$metadata#schemaExtensions/$entity",
    "id": "ourdomain_EmailCustomFields",
    "description": "Custom data for emails",
    "targetTypes": [
        "Message"
    ],
    "status": "InDevelopment",
    "owner": "hiding",
    "properties": [
        {
            "name": "MailID",
            "type": "String"
        },
        {
            "name": "ProcessedAt",
            "type": "DateTime"
        }
    ]
}

Then I patched a specific message https://graph.microsoft.com/v1.0/me/mailFolders/Inbox/Messages/hidingmessageid:

PATCH Request
{"ourdomain_EmailCustomFields":{"MailID":"12","ProcessedAt":"2020-05-27T16:21:19.0204032-07:00"}}

The problem is that when I select the message, the added custom data doesn't appear by executing a GET request: https://graph.microsoft.com/v1.0/me/mailFolders/Inbox/Messages?$top=1&$select=id,subject,ourdomain_EmailCustomFields

Also, the following GET request gives me an error.

Request: https://graph.microsoft.com/v1.0/me/mailFolders/Inbox/Messages?$filter=ourdomain_EmailCustomFields/MailID eq '12'

Response:

{
    "error": {
        "code": "RequestBroker--ParseUri",
        "message": "Could not find a property named 'e2_someguid_ourdomain_EmailCustomFields' on type 'Microsoft.OutlookServices.Message'.",
        "innerError": {
            "request-id": "someguid",
            "date": "2020-05-29T01:04:53"
        }
    }
}

Do you have any ideas on how to resolve the issues?
Thank you!


问:
The type org.eclipse.ui.texteditor.* is not visible
I am trying to reimplement the AbstractTextEditor class but the problem that I couldn't add org.eclipse.ui.texteditor in dependencies section. Does it depend on other one?

答:
The org.eclipse.ui.texteditor Java package containing AbstractTextEditor is in the org.eclipse.ui.workbench.texteditor plug-in which you already have in your dependencies. You do not need to do anything else to the dependencies.

Although Java package names are often similar to the plug-in id that contains them this is not a required.

Also I see you have org.eclipse.ui.editors.source and org.eclipse.ui.workbench.texteditor.source in your dependencies - these are source code only plug-ins used internally by Eclipse you don't need them in the dependencies list. They may cause complications when you try and build the plug-in.


问:
Update and Insert vs Upsert in PostgreSQL
Say, I am building a camera app. Every time the user clicks a photo, the image is stored on the cloud. Because I want to restrict how many images are stored on the cloud, the app gets 10 URLs in an array called listURLs when it is initialised.

The first 10 clicks get PUT into the cloud, exhausting listURLs. Then, every time a click happens, a coin toss determines whether the latest click replaces an existing click on the cloud. Typical numbers would be 50 clicks, first 10 clicks get assigned a URL, and of the remaining 40 clicks, 20 of them overwrite an existing URL.

I store records of each app session in a Postgres DB. Each session will have an ID and all instances of clicks (which may or may not have a corresponding url). I also need to know the url corresponding to each click, if one exists. So, if there are 30 clicks, I will need to know which 10 of these have a corresponding url.

I can think of two ways of storing this data.

tblClicksURLs as a Table that has click_id, url and url_active as its fields. Every time a click_id and non-null url need to be inserted, update all other records with the same url to have url_active as false.

Two tables tblClicks and tblURLs. tblURLs has a click_id foreign key. Every time a click_id and non-null url need to be inserted, the click_id gets inserted into tblClicks and click_id and url get upserted into tblURLs. The upsert is based on whether the url already exists in tblURLs. So, for a given url, there will only be one click_id in tblURLs

So, in Case 1, I will have an UPDATE of url_active followed by  INSERT on the same table. In Case 2, I will have an INSERT into one table and an UPSERT into another. I will need indexing on click_id, but not on url.

If you are looking at writes of > 10k rows per second, maybe even more, which of these two would be more efficient? Assume that the numbers per session are similar to the one quoted above (50 clicks, etc.)

I could also register a created_at datetime for each record in Case 1, and just use the first non-null url ordered reverse-chronologically. But, I am trying to avoid this, unless the performance benefits are enormous.

答:
After thinking about it for a while, I decided to use UPSERT along with a Unique Constraint on tblClicksURLs. The constraint is on (url, url_active). Every time a new (click_id, url, url_active) record needs to be added, this record is UPSERT'ed. On conflict url_active is set to null. So, all records with this url will have their url_active set to null.

I then use

```<code>RETURNING (xmax = 0) AS inserted
</code>```

as discussed here to check if the record was inserted or upserted. If the record was upserted, I update the url_active field of the latest record to true.

In this way, if a url is being inserted for the first time, it happens in a single transaction. If the url exists, it happens via two transactions.

Body:
After thinking about it for a while, I decided to use UPSERT along with a Unique Constraint on tblClicksURLs. The constraint is on (url, url_active). Every time a new (click_id, url, url_active) record needs to be added, this record is UPSERT'ed. On conflict url_active is set to null. So, all records with this url will have their url_active set to null.

I then use

RETURNING (xmax = 0) AS inserted

as discussed here to check if the record was inserted or upserted. If the record was upserted, I update the url_active field of the latest record to true.

In this way, if a url is being inserted for the first time, it happens in a single transaction. If the url exists, it happens via two transactions.


问:
Extract the address of a search criteria in a list combining Cell/Index
I have the below Excel sheet:

```<code>        A             B            C            D            E         F
1     CW10          CW14         $A$5
2     CW11
3     CW12
4     CW13
5     CW14
6     CW15
7
</code>```

In Column A I have a list of calender weeks.

In Cell B1 I enter a certain calender week and in Cell D1 I get the corresponding address of this calender week in Column A.

For this functionality in Cell C1 I use the formula: =CELL("address",INDEX(A1:A7,MATCH(B1,A1:A7,0),0))

Now, I want use the exact same formula in VBA. Therefore, I first created the INDEX part of it:

```<code>WorksheetFunction.Index(Sheet1.Range("A1:A7").Value, WorksheetFunction.Match(Sheet1.Range("B1").Value, Sheet1.Range("A1:A7").Value, 0), 0)
</code>```

This part already worsk perfectly.

Then I tried to add CELL("address") to it:

```<code>WorksheetFunction.Cell("address", WorksheetFunction.Index(Sheet1.Range("A1:A7").Value, WorksheetFunction.Match(Sheet1.Range("B1").Value, Sheet1.Range("A1:A7").Value, 0), 0))
.Value)
</code>```

However, for this I get runtime error 424.

What do I need to change in my formula to make it work or is there any other alternative to extract the address of a search criteria in a range?

答:
With reference to the comments there are two solutions for this issue:

Option 1: Range.Find

```<code>Sub Option_01()
Range_01 = Sheet1.Range("A1:A7").Find(WorksheetFunction.Index(Sheet1.Range("A1:A7").Value, WorksheetFunction.Match(Sheet1.Range("B1").Value, Sheet1.Range("A1:A7").Value, 0), 0)).Address
Sheet1.Range("C1").Value = Range_01
End Sub
</code>```

Unfortunately, by testing this solution with more complex data I got some issues.

Option 2: Application.Match

```<code>Sub Option_02()
Row = Application.Match(Sheet1.Range("B1").Value, Sheet1.Range("A1:A7"), 0) + Sheet1.Range("A1:A7").Row - 1
Range_01 = ("$" & Split(Sheet1.Range("A1:A7").Address, "$")(1)) & "$"
Sheet1.Range("C1").Value = Range_01 & Row
End Sub
</code>```

Body:
I have the below Excel sheet:

        A             B            C            D            E         F
1     CW10          CW14         $A$5
2     CW11
3     CW12
4     CW13
5     CW14
6     CW15
7

In Column A I have a list of calender weeks.

In Cell B1 I enter a certain calender week and in Cell D1 I get the corresponding address of this calender week in Column A.

For this functionality in Cell C1 I use the formula: =CELL("address",INDEX(A1:A7,MATCH(B1,A1:A7,0),0))

Now, I want use the exact same formula in VBA. Therefore, I first created the INDEX part of it:

WorksheetFunction.Index(Sheet1.Range("A1:A7").Value, WorksheetFunction.Match(Sheet1.Range("B1").Value, Sheet1.Range("A1:A7").Value, 0), 0)

This part already worsk perfectly.

Then I tried to add CELL("address") to it:

WorksheetFunction.Cell("address", WorksheetFunction.Index(Sheet1.Range("A1:A7").Value, WorksheetFunction.Match(Sheet1.Range("B1").Value, Sheet1.Range("A1:A7").Value, 0), 0))
.Value)

However, for this I get runtime error 424.

What do I need to change in my formula to make it work or is there any other alternative to extract the address of a search criteria in a range?

Body:
With reference to the comments there are two solutions for this issue:

Option 1: Range.Find

Sub Option_01()
Range_01 = Sheet1.Range("A1:A7").Find(WorksheetFunction.Index(Sheet1.Range("A1:A7").Value, WorksheetFunction.Match(Sheet1.Range("B1").Value, Sheet1.Range("A1:A7").Value, 0), 0)).Address
Sheet1.Range("C1").Value = Range_01
End Sub

Unfortunately, by testing this solution with more complex data I got some issues.

Option 2: Application.Match

Sub Option_02()
Row = Application.Match(Sheet1.Range("B1").Value, Sheet1.Range("A1:A7"), 0) + Sheet1.Range("A1:A7").Row - 1
Range_01 = ("$" & Split(Sheet1.Range("A1:A7").Address, "$")(1)) & "$"
Sheet1.Range("C1").Value = Range_01 & Row
End Sub


问:
How to check git commit is from cherry-pick, and from which one?
Can we know any git commit is from cherry-pick, and from which commit?</p>

答:
As I look in git source, there is no differences in commit itself. You could check differences in all commits and check how many changes is same, but it is slow and not guarantee all results (cherry pick could be merged, not fast forward).
Another solution is referencing by commit message when cherry picking. In most cases you have same commit message, so you can check by this.</p>


问:
Javascript opencv (opencv.js) grabcut GC_INIT_WITH_MASK issue example?
I am trying to a run grabcut on opencv.js with having the grabcut mode as GC_INIT_WITH_MASK. But not getting the results i need. I am getting the same results from that as i got from using the grabcut mode as GC_INIT_WITH_RECT.

there isn't any online exmples of calling opencv.js cv.grabcut with having GC_INIT_WITH_MASK as the mode.

so,i checked the official opencv documentation which provides a python example.

in that,

```<code>cv.grabCut(img,mask,None,bgdModel,fgdModel,5,cv.GC_INIT_WITH_MASK)
</code>```

there is None (which is the equivalent of null in javascript) as the 3rd parameter which requires a rectangle object,  And it makes sense to not pass a rectangle here when the mode is INIT_WITH_MASK.

But when i call cv.grabcut function in javascript using null in that place. it gives an error,

TypeError: Cannot use 'in' operator to search for 'x' in null

it runs when i pass a rectangle object. but gives the same result as using GC_INIT_WITH_RECT mode.

How to run it properly using INIT_WITH_MASK mode?

答:
I faced similar problem and tried to initialize rectangle without any parameters and provide it to the GrabCut:

```<code> let rect = new cv.Rect();
 cv.grabCut(src, mask, rect, bgdModel, fgdModel, 1, cv.GC_INIT_WITH_MASK);
</code>```

And it works (I can see difference with my own mask). At first, I did not see any difference too, but it reveals that I used the same mask as before with GC_INIT_WITH_RECT option.

Have a good day

Body:
I am trying to a run grabcut on opencv.js with having the grabcut mode as GC_INIT_WITH_MASK. But not getting the results i need. I am getting the same results from that as i got from using the grabcut mode as GC_INIT_WITH_RECT.

there isn't any online exmples of calling opencv.js cv.grabcut with having GC_INIT_WITH_MASK as the mode.

so,i checked the official opencv documentation which provides a python example.

in that,

cv.grabCut(img,mask,None,bgdModel,fgdModel,5,cv.GC_INIT_WITH_MASK)

there is None (which is the equivalent of null in javascript) as the 3rd parameter which requires a rectangle object,  And it makes sense to not pass a rectangle here when the mode is INIT_WITH_MASK.

But when i call cv.grabcut function in javascript using null in that place. it gives an error,

TypeError: Cannot use 'in' operator to search for 'x' in null

it runs when i pass a rectangle object. but gives the same result as using GC_INIT_WITH_RECT mode.

How to run it properly using INIT_WITH_MASK mode?

Body:
I faced similar problem and tried to initialize rectangle without any parameters and provide it to the GrabCut:

 let rect = new cv.Rect();
 cv.grabCut(src, mask, rect, bgdModel, fgdModel, 1, cv.GC_INIT_WITH_MASK);

And it works (I can see difference with my own mask). At first, I did not see any difference too, but it reveals that I used the same mask as before with GC_INIT_WITH_RECT option.

Have a good day