问:
Gensim Word2Vec lacks vectors for input words
Gensim Word2Vec that I've trained lacks vectors for some words. That is, although I have a word "yuval" as an input, the model lacks a vector for it. What is the cause?</p>

答:
To expand on @gojomo's answer, Word2Vec models during training are told to discard tokens below a min_count, as they are considered to be uninformative, meaning unable to extrapolate useful context.

This means, those tokens wont have vectors.

To check this, you an load the model, and check that the vocabulary contains the token you are interested in:

```<code>>>> import gensim
>>> model = gensim.models.KeyedVectors.load(...)
>>> 'car' in model
True
>>> 'yuval' in model
False
</code>```

Since 'yuval' is not in the vocabulary, it can't be found with the in operator, and will throw a key error if used.

```<code>>>> model['car']
...
...
<numpy array>
>>> model['yuval']
...
...
KeyError: "word 'yuval' not in vocabulary"
</code>```

If you really expect that the word should be in the list of vocabulary words, you can always print them out too:

```<code>>>> for token in model.wv.vocab.keys():
...     print(token)
...
</code>```

Body:
To expand on @gojomo's answer, Word2Vec models during training are told to discard tokens below a min_count, as they are considered to be uninformative, meaning unable to extrapolate useful context.

This means, those tokens wont have vectors.

To check this, you an load the model, and check that the vocabulary contains the token you are interested in:

>>> import gensim
>>> model = gensim.models.KeyedVectors.load(...)
>>> 'car' in model
True
>>> 'yuval' in model
False

Since 'yuval' is not in the vocabulary, it can't be found with the in operator, and will throw a key error if used.

>>> model['car']
...
...
<numpy array>
>>> model['yuval']
...
...
KeyError: "word 'yuval' not in vocabulary"

If you really expect that the word should be in the list of vocabulary words, you can always print them out too:

>>> for token in model.wv.vocab.keys():
...     print(token)
...


来源: stackexchange

问:
CEdit::GetLine() windows 7
I have the following segment of code where m_edit is a CEdit control:

```<code>TCHAR lpsz[MAX_PATH+1];

// get the edit box text
m_edit.GetLine(0,lpsz, MAX_PATH);
</code>```

This works perfectly on computers running Windows XP and earlier.  I have not tested this in Vista, but on Windows 7, lpsz gets junk unicode characters inserted into it (as well as the actual text sometimes).  Any idea as to what is going on here?

答:
Since you're using MFC, why aren't you taking advantage of its CString class? That's one of the reasons many programmers were drawn to MFC, because it makes working with strings so much easier.

For example, you could simply write:

```<code>int len = m_edit.LineLength(m_edit.LineIndex(0));
CString path;
LPTSTR p = path.GetBuffer(len);
m_edit.GetLine(0, p, len);
path.ReleaseBuffer();
</code>```

(The above code is tested to work fine on Windows 7.)

Note that the copied line does not contain a null-termination character (see the "Remarks" section in the documentation). That could explain the nonsense characters you're seeing in later versions of Windows.

ContentLicense: CC BY-SA 3.0

Title: CEdit::GetLine() windows 7

Body:
I have the following segment of code where m_edit is a CEdit control:

TCHAR lpsz[MAX_PATH+1];

// get the edit box text
m_edit.GetLine(0,lpsz, MAX_PATH);

This works perfectly on computers running Windows XP and earlier.  I have not tested this in Vista, but on Windows 7, lpsz gets junk unicode characters inserted into it (as well as the actual text sometimes).  Any idea as to what is going on here?

Body:
Since you're using MFC, why aren't you taking advantage of its CString class? That's one of the reasons many programmers were drawn to MFC, because it makes working with strings so much easier.

For example, you could simply write:

int len = m_edit.LineLength(m_edit.LineIndex(0));
CString path;
LPTSTR p = path.GetBuffer(len);
m_edit.GetLine(0, p, len);
path.ReleaseBuffer();

(The above code is tested to work fine on Windows 7.)

Note that the copied line does not contain a null-termination character (see the "Remarks" section in the documentation). That could explain the nonsense characters you're seeing in later versions of Windows.


问:
Android Build Failed, strings/google_app_id duplicate resources error
I am working on ionic 4. When I run this command in cmd:

```<code>ionic Cordova build android
</code>```

It gives me a duplicate resource error. I am using firebase and google services.json plugins in my project.

I have tried to remove google_app_id and google_api_key from Andriod.xml file but no change. The same error is displaying again and again. Here is the view of the android.xml file.

Android.xml File

```<code> "res/values/strings.xml": {
        "parents": {
          "/resources": [
              // removed google_app_id & google_api_key
]
        }
      }
    }
</code>```

Strings.xml File:

```<code><resources>
    <string name="app_name">UrbanX Driver</string>
    <string name="launcher_name">@string/app_name</string>
    <string name="activity_name">@string/launcher_name</string>
    <string name="google_app_id">@string/google_app_id</string>
    <string name="google_api_key">@string/google_api_key</string>
</resources>
</code>```

Config.xml File:

```<code>        <resource-file src="google-services.json" target="app/google-services.json" />
</code>```

答:
Install this plugin cordova-android-play-services-gradle-release:

```<code>ionic cordova plugin add cordova-android-play-services-gradle-release
</code>```

check this link for reason:

https://github.com/arnesson/cordova-plugin-firebase#google-play-services

ContentLicense: CC BY-SA 4.0

Body:
I am working on ionic 4. When I run this command in cmd:

ionic Cordova build android

It gives me a duplicate resource error. I am using firebase and google services.json plugins in my project.

I have tried to remove google_app_id and google_api_key from Andriod.xml file but no change. The same error is displaying again and again. Here is the view of the android.xml file.

Android.xml File

 "res/values/strings.xml": {
        "parents": {
          "/resources": [
              // removed google_app_id & google_api_key
]
        }
      }
    }

Strings.xml File:

<resources>
    <string name="app_name">UrbanX Driver</string>
    <string name="launcher_name">@string/app_name</string>
    <string name="activity_name">@string/launcher_name</string>
    <string name="google_app_id">@string/google_app_id</string>
    <string name="google_api_key">@string/google_api_key</string>
</resources>

Config.xml File:

        <resource-file src="google-services.json" target="app/google-services.json" />

Body:
Install this plugin cordova-android-play-services-gradle-release:

ionic cordova plugin add cordova-android-play-services-gradle-release

check this link for reason:

https://github.com/arnesson/cordova-plugin-firebase#google-play-services


问:
Need to run a stored procedure on all non system databases
I'm trying to loop through all non system databases and run a stored procedure. This stored procedure exists in all of the user databases.

This is what I have found so far:

```<code>DECLARE @command varchar(1000)
SELECT @command = 'USE ? SELECT name FROM sysobjects WHERE xtype = ''U'' ORDER BY name'

USE @command;
GO

EXECUTE Support.CleanIndiciesAndShrinkDatabase;
GO
</code>```

I get an error this error:

Msg 102, Level 15, State 1, Line 3

  Incorrect syntax near '@command'.

Msg 2812, Level 16, State 62, Line 1

  Could not find stored procedure 'Support.CleanIndiciesAndShrinkDatabase'.

Any suggestions on fixing this?

答:
Try something like this:</p>

```<code>DECLARE @DynamicTSQLStatement NVARCHAR(MAX);

SELECT @DynamicTSQLStatement = STUFF
(
    (
        SELECT 'USE [' + [name] + ']; EXECUTE Support.CleanIndiciesAndShrinkDatabase;'
        FROM [sys].[databases]
        WHERE [name] NOT IN ('master', 'tempdb', 'model', 'msdb')
        FOR XML PATH(''), TYPE
    ).value('.', 'NVARCHAR(MAX)')
    ,1
    ,1
    ,''
);

EXECUTE sp_executesql @DynamicTSQLStatement;
</code>```

Body:
I'm trying to loop through all non system databases and run a stored procedure. This stored procedure exists in all of the user databases.

This is what I have found so far:

DECLARE @command varchar(1000)
SELECT @command = 'USE ? SELECT name FROM sysobjects WHERE xtype = ''U'' ORDER BY name'

USE @command;
GO

EXECUTE Support.CleanIndiciesAndShrinkDatabase;
GO

I get an error this error:

Msg 102, Level 15, State 1, Line 3

  Incorrect syntax near '@command'.

Msg 2812, Level 16, State 62, Line 1

  Could not find stored procedure 'Support.CleanIndiciesAndShrinkDatabase'.

Any suggestions on fixing this?

Body:
Try something like this:

DECLARE @DynamicTSQLStatement NVARCHAR(MAX);

SELECT @DynamicTSQLStatement = STUFF
(
    (
        SELECT 'USE [' + [name] + ']; EXECUTE Support.CleanIndiciesAndShrinkDatabase;'
        FROM [sys].[databases]
        WHERE [name] NOT IN ('master', 'tempdb', 'model', 'msdb')
        FOR XML PATH(''), TYPE
    ).value('.', 'NVARCHAR(MAX)')
    ,1
    ,1
    ,''
);

EXECUTE sp_executesql @DynamicTSQLStatement;


问:
Concatenation of int with string to TextView gives a set of Integer
In my android app, I'm trying to set the text to a TextView with integer and a string value. I'm getting the length of the array and going to set it with a string value as below.

```<code>if (array.size() > 0) {
    textView.setText(array.size() + " " + R.string.lbl_text);
}
</code>```

When I run the App it give me a set of integers as shown below:

```<code>1 2345223232
</code>```

Then I covert array size to string as follow

```<code>if (array.size() > 0) {
    textView.setText(Integer.toString(array.size()) + " " + R.string.lbl_text);
}
</code>```

But the same output. What is the reason for getting Integer value for the string.lbl_text

答:
R.string.xxx is a resource identifier. In order it to convert to a String value you need to call getString() on a Resources or Context instance:

```<code>resources.getString(R.string.xxx);
</code>```

Body:
In my android app, I'm trying to set the text to a TextView with integer and a string value. I'm getting the length of the array and going to set it with a string value as below.

if (array.size() > 0) {
    textView.setText(array.size() + " " + R.string.lbl_text);
}

When I run the App it give me a set of integers as shown below:

1 2345223232

Then I covert array size to string as follow

if (array.size() > 0) {
    textView.setText(Integer.toString(array.size()) + " " + R.string.lbl_text);
}

But the same output. What is the reason for getting Integer value for the string.lbl_text

Body:
R.string.xxx is a resource identifier. In order it to convert to a String value you need to call getString() on a Resources or Context instance:

resources.getString(R.string.xxx);


问:
The best way to model a one-to-many relationship in hibernate
I am new to hibernate,
According to the article below it seems that the best way to map relationships is unidirectionally in most of the cases other than special cases like Q and A application where  the number of child entities is limited.

Link -
https://www.callicoder.com/hibernate-spring-boot-jpa-one-to-many-mapping-example/

Is this correct?? I want to clear my doughts and start my ralationship mappings.

答:
For a Q & A application I think we will need bi directional mapping.
For a given Question you need to know of the answers given already.
And for an Answer, you need to know what was the question.

```<code>@Entity
Class Answer {

 @Id
 @Column("answer_id")
 private Long answerId;

 @JoinColumn("question_id")
 @ManyToOne
 private Question question;

}

@Entity
class Question {

 @Id
 @Column("question_id")
 private Long id;

 @OneToMany(mappedBy = "question")
 private List<Answer> answers;
}
</code>```

So here the owning entity will be Answer
means Answer table will have the question_id
Question table wont store answer_id

Body:
For a Q & A application I think we will need bi directional mapping.
For a given Question you need to know of the answers given already.
And for an Answer, you need to know what was the question.

@Entity
Class Answer {

 @Id
 @Column("answer_id")
 private Long answerId;

 @JoinColumn("question_id")
 @ManyToOne
 private Question question;

}

@Entity
class Question {

 @Id
 @Column("question_id")
 private Long id;

 @OneToMany(mappedBy = "question")
 private List<Answer> answers;
}

So here the owning entity will be Answer
means Answer table will have the question_id
Question table wont store answer_id


问:
Have opencv trackbar display time of video
I have a simple media player in OpenCV (python). I wanted to show the "time" of the video using a trackbar. First of all, here are the functions I am using to convert a frame number to a time:

```<code>def _seconds(value, framerate):
    if isinstance(value, str):  # value seems to be a timestamp
        _zip_ft = zip((3600, 60, 1, 1/framerate), value.split(':'))
        return sum(f * float(t) for f,t in _zip_ft)
    elif isinstance(value, (int, float)):  # frames
        return value / framerate
    else:
        return 0

def _timecode(seconds, framerate):
    return '{h:02}:{m:02}:{s:02}' \
            .format(h=int(seconds/3600),
                    m=int(seconds/60%60),
                    s=int(seconds%60))

def _frames(seconds, framerate):
    return seconds * framerate

def timecode_to_frames(timecode, framerate, start=None):
    return _frames(_seconds(timecode, framerate) - _seconds(start, framerate), framerate)

def frames_to_timecode(frames, framerate, start=None):
    return _timecode(_seconds(frames, framerate) + _seconds(start,framerate), framerate)
</code>```

In the end of the day, the return is a string that is of format Hours:Minutes:Seconds.

So... I realize that using a trackbar to do this is probably impossible because definition...

```<code> C++: int createTrackbar(const string& trackbarname, const string& winname, int* value, int count, TrackbarCallback onChange=0, void* userdata=0)

Python: cv.CreateTrackbar(trackbarName, windowName, value, count, onChange) → None
    Parameters:

        trackbarname – Name of the created trackbar.
        winname – Name of the window that will be used as a parent of the created trackbar.
        value – Optional pointer to an integer variable whose value reflects the position of the slider. Upon creation, the slider position is defined by this variable.
        count – Maximal position of the slider. The minimal position is always 0.
        onChange – Pointer to the function to be called every time the slider changes position. This function should be prototyped as void Foo(int,void*); , where the first parameter is the trackbar position and the second parameter is the user data (see the next parameter). If the callback is the NULL pointer, no callbacks are called, but only value is updated.
        userdata – User data that is passed as is to the callback. It can be used to handle trackbar events without using global variables.
</code>```

...and...

```<code>Python: cv2.setTrackbarPos(trackbarname, winname, pos) → None

C: void cvSetTrackbarPos(const char* trackbar_name, const char* window_name, int pos)

Python: cv.SetTrackbarPos(trackbarName, windowName, pos) → None
    Parameters:

        trackbarname – Name of the trackbar.
        winname – Name of the window that is the parent of trackbar.
        pos – New position.
</code>```

...make it very clear that an int must be passed to the "pos" and basically everything else.

Do you guys have a solution for this?
Thanks.

答: Try to use Scale i.e. slider widget provided in tkinter</p>

Body:
I have a simple media player in OpenCV (python). I wanted to show the "time" of the video using a trackbar. First of all, here are the functions I am using to convert a frame number to a time:

def _seconds(value, framerate):
    if isinstance(value, str):  # value seems to be a timestamp
        _zip_ft = zip((3600, 60, 1, 1/framerate), value.split(':'))
        return sum(f * float(t) for f,t in _zip_ft)
    elif isinstance(value, (int, float)):  # frames
        return value / framerate
    else:
        return 0

def _timecode(seconds, framerate):
    return '{h:02}:{m:02}:{s:02}' \
            .format(h=int(seconds/3600),
                    m=int(seconds/60%60),
                    s=int(seconds%60))

def _frames(seconds, framerate):
    return seconds * framerate

def timecode_to_frames(timecode, framerate, start=None):
    return _frames(_seconds(timecode, framerate) - _seconds(start, framerate), framerate)

def frames_to_timecode(frames, framerate, start=None):
    return _timecode(_seconds(frames, framerate) + _seconds(start,framerate), framerate)

In the end of the day, the return is a string that is of format Hours:Minutes:Seconds.

So... I realize that using a trackbar to do this is probably impossible because definition...

 C++: int createTrackbar(const string& trackbarname, const string& winname, int* value, int count, TrackbarCallback onChange=0, void* userdata=0)

Python: cv.CreateTrackbar(trackbarName, windowName, value, count, onChange) → None
    Parameters:

        trackbarname – Name of the created trackbar.
        winname – Name of the window that will be used as a parent of the created trackbar.
        value – Optional pointer to an integer variable whose value reflects the position of the slider. Upon creation, the slider position is defined by this variable.
        count – Maximal position of the slider. The minimal position is always 0.
        onChange – Pointer to the function to be called every time the slider changes position. This function should be prototyped as void Foo(int,void*); , where the first parameter is the trackbar position and the second parameter is the user data (see the next parameter). If the callback is the NULL pointer, no callbacks are called, but only value is updated.
        userdata – User data that is passed as is to the callback. It can be used to handle trackbar events without using global variables.

...and...

Python: cv2.setTrackbarPos(trackbarname, winname, pos) → None

C: void cvSetTrackbarPos(const char* trackbar_name, const char* window_name, int pos)

Python: cv.SetTrackbarPos(trackbarName, windowName, pos) → None
    Parameters:

        trackbarname – Name of the trackbar.
        winname – Name of the window that is the parent of trackbar.
        pos – New position.

...make it very clear that an int must be passed to the "pos" and basically everything else.

Do you guys have a solution for this?
Thanks.


问:
In spring-batch, how can I get the exception when there is a chunk error?
Spring batch provides a listener for capturing when a chunk error has occurred (either the @AfterChunkError annotation or the ChunkListener.afterChunkError interface). Both receive the ChunkContext and the API says:

Parameters:

context - the chunk context containing the exception that caused the
  underlying rollback.

However, I don't see anything on the ChunkContext interface that would get me to the exception. How do I get from the ChunkContext to the relevant exception?

答:
Exception is located in ChunkListener.ROLLBACK_EXCEPTION_KEY attribute:

```<code>context.getAttribute(ChunkListener.ROLLBACK_EXCEPTION_KEY)
</code>```

Body:
Exception is located in ChunkListener.ROLLBACK_EXCEPTION_KEY attribute:

context.getAttribute(ChunkListener.ROLLBACK_EXCEPTION_KEY)


问:
Select data where condition matches and if none, then select all?

select * from (values
    ('dept1','user1'),
    ('dept2','user2'),
    ('dept3','user3'),
    ('dept4','user4')
    )table1([department],[user])
where [user] = @id
```

<p>scenario1:
     @id = 'user1'</p>

```dept1
```

<p>scenario2:
    @id = 'user5'</p>

```dept1
dept2
dept3
dept4
```

<p>this is what it looks like from a noobish query</p>

<pre class="lang-sql prettyprint-override"><code>declare @id varchar(12) = 'user1'
declare @var int = (select count(*) from table1 where [user] = @id)

select * from table1 where [user] = @id or @var = 0
</code>```

答:
You may have to do a check first something like this</p>

```<code>Declare @RowCount int
Select @RowCount = (select count(*) from [Table] Where [Column] = 'xxx')

If @RowCount > 0
 begin
  Select 1 -- put code here if records
 end
else
 begin
  Select 2 -- put code here if no records
 end
</code>```

Body:
select * from (values
    ('dept1','user1'),
    ('dept2','user2'),
    ('dept3','user3'),
    ('dept4','user4')
    )table1([department],[user])
where [user] = @id

scenario1:
     @id = 'user1'

dept1

scenario2:
    @id = 'user5'

dept1
dept2
dept3
dept4

this is what it looks like from a noobish query

declare @id varchar(12) = 'user1'
declare @var int = (select count(*) from table1 where [user] = @id)

select * from table1 where [user] = @id or @var = 0

Body:
You may have to do a check first something like this

Declare @RowCount int
Select @RowCount = (select count(*) from [Table] Where [Column] = 'xxx')

If @RowCount > 0
 begin
  Select 1 -- put code here if records
 end
else
 begin
  Select 2 -- put code here if no records
 end


问:
Show 1 item if another item comes empty (angular 6 material)
I've used material bootstrap with angular 6. In here I have bound area code and area description. In my database we have a record that only consists of area codes. If so, I need to show the record with only the area code. In here it looks like this:

ZA550D - // with small hyphen

But I need it to look like below:

ZA550D

```<code>  <mat-select formControlName="news" name="description" id="id" [(ngModel)]="model.newsId"
                                placeholder="{{'NewsName'}}" required>
                        <mat-option *ngFor="let news of newsDetails" [value]="news.id">
                            {{news.areaCode +"-"+news.areaDescription}}
                        </mat-option>
                    </mat-select>
</code>```

答:
There are many ways to do this, try out the following sample :

```<code><mat-select formControlName="news" name="description" id="id" [(ngModel)]="model.newsId" placeholder="{{'NewsName'}}" required>
   <mat-option *ngFor="let news of newsDetails" [value]="news.id">
       {{news.areaDescription ? news.areaCode +"-"+ news.areaDescription : news.areaCode }}
   </mat-option>
</mat-select>
</code>```

You can write a function for this to get a cleaner template.

Body:
I've used material bootstrap with angular 6. In here I have bound area code and area description. In my database we have a record that only consists of area codes. If so, I need to show the record with only the area code. In here it looks like this:

ZA550D - // with small hyphen

But I need it to look like below:

ZA550D

  <mat-select formControlName="news" name="description" id="id" [(ngModel)]="model.newsId"
                                placeholder="{{'NewsName'}}" required>
                        <mat-option *ngFor="let news of newsDetails" [value]="news.id">
                            {{news.areaCode +"-"+news.areaDescription}}
                        </mat-option>
                    </mat-select>

Body:
There are many ways to do this, try out the following sample :

<mat-select formControlName="news" name="description" id="id" [(ngModel)]="model.newsId" placeholder="{{'NewsName'}}" required>
   <mat-option *ngFor="let news of newsDetails" [value]="news.id">
       {{news.areaDescription ? news.areaCode +"-"+ news.areaDescription : news.areaCode }}
   </mat-option>
</mat-select>

You can write a function for this to get a cleaner template.


问:
Allow null - Javascript
I have this regex for a input only numbers and works fine. The problem is that I also want to allow null.

```<code>validator="/([0-9])$/"
</code>```

I tried using the | but now it allows everything

```<code>validator="/([0-9]|)$/"
</code>```

Any ideas?

答:
What you need is merely the simplest you can imagine:

validator="/\d*$/"

Title: Allow null - Javascript

Body:
I have this regex for a input only numbers and works fine. The problem is that I also want to allow null.

validator="/([0-9])$/"

I tried using the | but now it allows everything

validator="/([0-9]|)$/"

Any ideas?


问:
React - dynamic input fields based on count
I want create the textfields based on the count entered by the user. I have gone through many related questions, I cannot find the result as I want.

For Example: If the user enter 5 as input.. I want to create 5 text boxes for entering 5 people Name and Mobile.

How can I achieve this?

TextField to get count

```<code>  <GridItem xs={12} sm={12} md={12}>
                      <TextField
                        id="sp_Inhouse"
                        label="Number of Pilots Available "
                        type="number"
                        fullWidth
                        className={classes.textField}
                        value={this.state.sp_Inhousecount}
                        error={!!this.state.sp_InhouseError}
                        helperText={this.state.sp_InhouseError}
                        onChange={this.handleChangeInhouse}
                        margin="normal"
                        required
                      />
                    </GridItem>
</code>```

Tried adding the textboxes based on button click. It works fine. but I want the result as explained.

```<code>                    <GridItem xs={12} sm={12} md={12}>
                       <Button color="primary" onClick={this.handleCreatePilots}>
                      <AddIcon />  Add Pilots
                      </Button>
                      {this.state.inhouse.map((index) => {
                        return (
                          <div key={index}>
                          <TextField
                            id="sp_Name"

                            label="Name "
                            type="number"
                            fullWidth
                          />
 <TextField
                            id="sp_Mobile"

                            label="Name "
                            type="number"
                            fullWidth
                          />
                          </div>
                        )
                      })
                      }
                    </GridItem>
</code>```

```<code> handleCreatePilots=()=>{
    this.setState({
      inhouse:[...this.state.inhouse,'']
    })
  }
</code>```

答:
Loop through the number entered by the user.

```<code>const inputs = [];

for (let i = 1; i <= this.state.total; i++) {
  inputs.push(
    <input name={`input-${i}`} onChange={this.onChange} />
  )
}
</code>```

Render inputs

```<code>render() {
  return (
   ....
    {inputs}
  ...
  )
}
</code>```

```

Body:
I want create the textfields based on the count entered by the user. I have gone through many related questions, I cannot find the result as I want.

For Example: If the user enter 5 as input.. I want to create 5 text boxes for entering 5 people Name and Mobile.

How can I achieve this?

TextField to get count

  <GridItem xs={12} sm={12} md={12}>
                      <TextField
                        id="sp_Inhouse"
                        label="Number of Pilots Available "
                        type="number"
                        fullWidth
                        className={classes.textField}
                        value={this.state.sp_Inhousecount}
                        error={!!this.state.sp_InhouseError}
                        helperText={this.state.sp_InhouseError}
                        onChange={this.handleChangeInhouse}
                        margin="normal"
                        required
                      />
                    </GridItem>

Tried adding the textboxes based on button click. It works fine. but I want the result as explained.

                    <GridItem xs={12} sm={12} md={12}>
                       <Button color="primary" onClick={this.handleCreatePilots}>
                      <AddIcon />  Add Pilots
                      </Button>
                      {this.state.inhouse.map((index) => {
                        return (

                          <TextField
                            id="sp_Name"

                            label="Name "
                            type="number"
                            fullWidth
                          />
 <TextField
                            id="sp_Mobile"

                            label="Name "
                            type="number"
                            fullWidth
                          />

                        )
                      })
                      }
                    </GridItem>

 handleCreatePilots=()=>{
    this.setState({
      inhouse:[...this.state.inhouse,'']
    })
  }

Body:
Loop through the number entered by the user.

const inputs = [];

for (let i = 1; i <= this.state.total; i++) {
  inputs.push(
    <input name={`input-${i}`} onChange={this.onChange} />
  )
}

Render inputs

render() {
  return (
   ....
    {inputs}
  ...
  )
}

<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.6.0/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.6.0/umd/react-dom.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/babel-standalone/6.21.1/babel.min.js"></script>
<div id="root"></div>

<script type="text/babel">

class App extends React.Component {
  constructor() {
    super();
    this.state = {
      name: 'React',
      total: 0,
      totalInput: '',
      show: false,
    };
  }

  add = () => {
    this.setState({
      total: this.state.totalInput
    })
  }

  showValues = () => {
    this.setState({
      show: true
    })
  }

  onChange = (event) => {
    this.setState({
      [event.target.name]: event.target.value
    })
  }

  render() {

    const inputs = [];

    for (let i = 1; i <= this.state.total; i++) {
      inputs.push(
        <input name={`input-${i}`} onChange={this.onChange} />
      )
    }
    return (
      <div>
        <input onChange={(e) => this.setState({ totalInput: e.target.value})} value={this.state.totalInput}  placeholder="Enter Number" />
        <button onClick={this.add}>Add</button>
        <br />
        {inputs}
         <br />
        <button onClick={this.showValues}>Show Inputs values</button>
        { this.state.show &&
          <pre>{JSON.stringify(this.state, null, 4)}</pre>
        }
      </div>
    );
  }
}

ReactDOM.render(<App />, document.getElementById('root'));
</script>


问:
Scraping code found when viewing page source
I'm trying to scrape code from a website that is found when right-clicking and selecting "view page source." My code below scrapes from the output found when you right click then select "inspect" I think. I get an error that says "file was loaded in the wrong encoding: 'UTF-8' I'm data mining based upon the raw page source info and I don't know how to pull that in.

See below

```<code>from bs4 import BeautifulSoup
import requests
import urllib.request
import urllib.error
import os, os.path, csv
import sys
from lxml import html
import requests

sys.stdout = open('scrapingoutput', 'a')
print(sys.stdout)

url= "https://www.geodatadirect.com/SearchResults/SuffolkSearchResults.aspx?state=NY&id=Suffolk&type=Sales"

urllib.request.urlopen("https://www.geodatadirect.com/SearchResults/SuffolkSearchResults.aspx?state=NY&id=Suffolk&type=Sales").read()

content = urllib.request.urlopen(url).read()

soup = BeautifulSoup(content)

print(soup.prettify())
</code>```

答:
Try selenium library to the download web page. selenium library is also helpful for download dynamic data content.

for chrome browser:

http://chromedriver.chromium.org/downloads

Install web driver for chrome browser:

```<code>unzip ~/Downloads/chromedriver_linux64.zip -d ~/Downloads
chmod +x ~/Downloads/chromedriver
sudo mv -f ~/Downloads/chromedriver /usr/local/share/chromedriver
sudo ln -s /usr/local/share/chromedriver /usr/local/bin/chromedriver
sudo ln -s /usr/local/share/chromedriver /usr/bin/chromedriver
</code>```

selenium tutorial

https://selenium-python.readthedocs.io/

Replace your code to this.

```<code>from selenium import webdriver
from bs4 import BeautifulSoup
import time

driver = webdriver.Chrome('/usr/bin/chromedriver')
driver.get('https://www.geodatadirect.com/SearchResults/SuffolkSearchResults.aspx?state=NY&id=Suffolk&type=Sales')
time.sleep(3)

soup = BeautifulSoup(driver.page_source,'html.parser')

print(soup.prettify())
</code>```

O/P:

```<code><html>
 <head>
  <title>
   Nationwide Property Data, Reports, Sales Comps
  </title>
  <meta charset="utf-8"/>
  <meta content="width=device-width, initial-scale=1, maximum-scale=1, user-scalable=no" name="viewport"/>
  <meta content="--XLC17oYuQE6UEhT-9_rC13L639t4C53w40_nWSbDM" name="google-site-verification"/>
  <meta content="GeoData Plus provides nationwide property reports, sales comparables, foreclosures, mortgages. Property data for residential and commercial real estate." name="description"/>
  <meta content="GeoData Plus" property="og:title"/>
  <meta content="https://www.geodataplus.com" property="og:url"/>
  <link href="https://www.geodataplus.com" rel="canonical"/>
  <meta content="website" property="og:type"/>
  <link href="/favicon.ico?v=Kx5JMIU84bo6i-lOxVlIH29IO5Qc9QPT6ENpVMaN-JE" rel="shortcut icon"/>
  <link href="/css/master.css?v=Liu7xdmA3BH167YXbnG76LfxA58TPHQR1J4L4ZzM5Qk" rel="stylesheet"/>
  <link href="/fonts/stylesheet.css?v=3NqqVyD10iq4848EK3FrA0HOaygo2MyDfL49n8ftRB0" rel="stylesheet"/>
  <link href="/css/Jquery-ui-auto.css?v=Nul8_ltyyt4O0iNe5la8BhlJ-Z84SOdeInfup2plryA" media="all" onload="if(media!='all')media='all'" rel="stylesheet"/>
  <noscript>
   <link href="/css/Jquery-ui-auto.css?v=Nul8_ltyyt4O0iNe5la8BhlJ-Z84SOdeInfup2plryA" rel="stylesheet"/>
  </noscript>
  <link href="theme/default/style.css" rel="stylesheet" type="text/css"/>
 </head>
 <body data-offset="200" data-spy="scroll" data-target=".navbar">
  <div class="" id="mainDiv">
   <div class="load-complete" id="site-loader">
      .........
      ..........
    </div>
  </div>
</body>
</html>
</code>```

Where '/usr/bin/chromedriver' chrome driver path.

Body:
I'm trying to scrape code from a website that is found when right-clicking and selecting "view page source." My code below scrapes from the output found when you right click then select "inspect" I think. I get an error that says "file was loaded in the wrong encoding: 'UTF-8' I'm data mining based upon the raw page source info and I don't know how to pull that in.

See below

from bs4 import BeautifulSoup
import requests
import urllib.request
import urllib.error
import os, os.path, csv
import sys
from lxml import html
import requests

sys.stdout = open('scrapingoutput', 'a')
print(sys.stdout)

url= "https://www.geodatadirect.com/SearchResults/SuffolkSearchResults.aspx?state=NY&id=Suffolk&type=Sales"

urllib.request.urlopen("https://www.geodatadirect.com/SearchResults/SuffolkSearchResults.aspx?state=NY&id=Suffolk&type=Sales").read()

content = urllib.request.urlopen(url).read()

soup = BeautifulSoup(content)

print(soup.prettify())

Body:
Try selenium library to the download web page. selenium library is also helpful for download dynamic data content.

for chrome browser:

http://chromedriver.chromium.org/downloads

Install web driver for chrome browser:

unzip ~/Downloads/chromedriver_linux64.zip -d ~/Downloads
chmod +x ~/Downloads/chromedriver
sudo mv -f ~/Downloads/chromedriver /usr/local/share/chromedriver
sudo ln -s /usr/local/share/chromedriver /usr/local/bin/chromedriver
sudo ln -s /usr/local/share/chromedriver /usr/bin/chromedriver

selenium tutorial

https://selenium-python.readthedocs.io/

Replace your code to this.

from selenium import webdriver
from bs4 import BeautifulSoup
import time

driver = webdriver.Chrome('/usr/bin/chromedriver')
driver.get('https://www.geodatadirect.com/SearchResults/SuffolkSearchResults.aspx?state=NY&id=Suffolk&type=Sales')
time.sleep(3)

soup = BeautifulSoup(driver.page_source,'html.parser')

print(soup.prettify())

O/P:

<html>
 <head>
  <title>
   Nationwide Property Data, Reports, Sales Comps
  </title>
  <meta charset="utf-8"/>
  <meta content="width=device-width, initial-scale=1, maximum-scale=1, user-scalable=no" name="viewport"/>
  <meta content="--XLC17oYuQE6UEhT-9_rC13L639t4C53w40_nWSbDM" name="google-site-verification"/>
  <meta content="GeoData Plus provides nationwide property reports, sales comparables, foreclosures, mortgages. Property data for residential and commercial real estate." name="description"/>
  <meta content="GeoData Plus" property="og:title"/>
  <meta content="https://www.geodataplus.com" property="og:url"/>
  <link href="https://www.geodataplus.com" rel="canonical"/>
  <meta content="website" property="og:type"/>
  <link href="/favicon.ico?v=Kx5JMIU84bo6i-lOxVlIH29IO5Qc9QPT6ENpVMaN-JE" rel="shortcut icon"/>
  <link href="/css/master.css?v=Liu7xdmA3BH167YXbnG76LfxA58TPHQR1J4L4ZzM5Qk" rel="stylesheet"/>
  <link href="/fonts/stylesheet.css?v=3NqqVyD10iq4848EK3FrA0HOaygo2MyDfL49n8ftRB0" rel="stylesheet"/>
  <link href="/css/Jquery-ui-auto.css?v=Nul8_ltyyt4O0iNe5la8BhlJ-Z84SOdeInfup2plryA" media="all" onload="if(media!='all')media='all'" rel="stylesheet"/>
  <noscript>
   <link href="/css/Jquery-ui-auto.css?v=Nul8_ltyyt4O0iNe5la8BhlJ-Z84SOdeInfup2plryA" rel="stylesheet"/>
  </noscript>
  <link href="theme/default/style.css" rel="stylesheet" type="text/css"/>
 </head>
 <body data-offset="200" data-spy="scroll" data-target=".navbar">
  <div class="" id="mainDiv">
   <div class="load-complete" id="site-loader">
      .........
      ..........
    </div>
  </div>
</body>
</html>

Where '/usr/bin/chromedriver' chrome driver path.


问:
react-native -bash: react-native: command not found
I Install node and Watchman

```<code> brew install node
 brew install watchman
</code>```

then Install React Native CLI

```<code>npm install -g react-native-cli
</code>```

but when I use react-native init test

I have error:
-bash: react-native: command not found

答:
first

       sudo npm install -g react-native-cli

this command output path like this

/usr/local/bin/react-native -> /usr/local/lib/node_modules/react-native-cli/index.js

then(for above path example)

export PATH="/usr/local/lib/node_modules/react-native-cli/index.js"

react-native init appName

Body:
I Install node and Watchman

 brew install node
 brew install watchman

then Install React Native CLI

npm install -g react-native-cli

but when I use react-native init test

I have error:
-bash: react-native: command not found


问:
Passing authentication to a different domain Iframe
I have to different apps that requires the exact same autentication and i am trying to pass my authentication information from localStorage from one app to another without having the user login twice. I am trying to use the following guide btu i am not sure on how to proceed:

https://levelup.gitconnected.com/share-localstorage-sessionstorage-between-different-domains-eb07581e9384

This is the information i want to pass forward to my Iframe:

```<code>token: 1234567890abcdef
user: someUserName
expires: 987654321
</code>```

My component looks like the following:

```<code><template>
    <v-container grid-list-md text-xs-center>
      <v-content>
    <div>
      <ToolBar/>
    </div>
      <vue-friendly-iframe id="frame" name="frame" src="http://localhost:8081"></vue-friendly-iframe>
    </v-container>

</template>

<script>

import ToolBar from '@/components/component/ToolBar'

  const domains = [
    "http://localhost:8080",
    "http://localhost:8081"
  ]

  export default {

    name: 'Dashboard',

      components: {
        ToolBar
    },

    data () {
      return {
        //
      }
    },

  }
</script>
</code>```

Not really sure on how to proceed here

答:
TLDR: There is really no perfect solution for this.

Having said this, there are a couple of approaches you can take.

Using Reverse Proxy

As @David suggested, use a reverse proxy like Nginx or HAPorxy to serve both the applications from the same domain - protocol://host:port. All three things should be equal.

Using cookies instead of LocalStorage

If you use cookies instead of LocalStorage, then host ports do not participate in determining site policy. So two application running on the same host but the different port will share cookie without any extra work. To protect the cookie, use an HTTP-only cookie, same-site cookie.

Using URL to share - IFrame only

If you are using iFrame, then you can use URL to share the token. When the outer window is loading the iFrame, send this information via hash like http://localhost:8081/somepage#token=1234

Using hash will allow the page to send data to an inner page without being sent over the wire.

Using window.postMessage - IFrame only

Using window.postMessage, you can simply pass the required data to the inner window/iFrame. As long as you control both the endpoints, you can easily do cross-domain message sending.

In the end, it really depends on your security requirements, ease-of-maintenance, etc.

Body:
I have to different apps that requires the exact same autentication and i am trying to pass my authentication information from localStorage from one app to another without having the user login twice. I am trying to use the following guide btu i am not sure on how to proceed:

https://levelup.gitconnected.com/share-localstorage-sessionstorage-between-different-domains-eb07581e9384

This is the information i want to pass forward to my Iframe:

token: 1234567890abcdef
user: someUserName
expires: 987654321

My component looks like the following:

<template>
    <v-container grid-list-md text-xs-center>
      <v-content>

      <ToolBar/>

      <vue-friendly-iframe id="frame" name="frame" src="http://localhost:8081"></vue-friendly-iframe>
    </v-container>

</template>

Not really sure on how to proceed here


问:
Synchronize Data From Multiple Data Sources
Our team is trying to build a predictive maintenance system whose task is to look at a set of events and predict whether these events depict a set of known anomalies or not.

We are at the design phase and the current system design is as follows:

The events may occur on multiple sources of an IoT system (such as cloud platform, edge devices or any intermediate platforms)

The events are pushed by the data sources into a message queueing system (currently we have chosen Apache Kafka).

Each data source has its own queue (Kafka Topic).

From the queues, the data is consumed by multiple inference engines (which are actually neural networks).

Depending upon the feature set, an inference engine will subscribe to
multiple Kafka topics and stream data from those topics to continuously output the inference.

The overall architecture follows the single-responsibility principle meaning that every component will be separate from each other and run inside a separate Docker container.

Problem:

In order to classify a set of events as an anomaly, the events have to occur in the same time window. e.g. say there are three data sources pushing their respective events into Kafka topics, but due to some reason, the data is not synchronized.
So one of the inference engines pulls the latest entries from each of the kafka topics, but the corresponding events in the pulled data do not belong to the same time window (say 1 hour). That will result in invalid predictions due to out-of-sync data.

Question

We need to figure out how can we make sure that the data from all three sources are pushed in-order so that when an inference engine requests entries (say the last 100 entries) from multiple kakfa topics, the corresponding entries in each topic belong to the same time window?

答:
Some suggestions -

Handle delay at the producer end -
Ensure all three producers always send data in sync to Kafka topics by using batch.size and linger.ms.
eg. if linger.ms is set to 1000, all messages would be sent to Kafka within 1 second.

Handle delay at the consumer end -
Considering any streaming engine at the consumer side (be it Kafka-stream, spark-stream, Flink), provides windows functionality to join/aggregate stream data based on keys while considering delayed window function.

Check this - Flink windows for reference how to choose right window type link


问:
implementing long pull / comet in simple javascript no frameworks require XSS
I have my own stripped down script that currently makes uses of XHR or script tags depending on browser support. These requests ultimately return some JSON.  My problem is now elements of this object now need to be updated by the server while on the client i.e. i need to implement some kinda of long pull/comet soln.

Google seems to come up with lots of solns using various frameworks such as JQuery etc.. to do this on the client side. However this is not an option for me.

I was wondering if you guys had any suggestions on how I could extend my existing approach to allow comet style updates from the server. One of the standard approaches seems to be using hidden iframes. This is a no go as the app server that is providing me with my json data is different to the actual webserver.

答:
jQuery simply wraps around the XHR/XMLHTTPRequest object.
First of, you need a small function to return the object in a cross-browser manner. This is done in 3 lines or less, not too difficult. That said, the are great snippets for fixing different browser issues, such as memory leaks. I highly suggest you use this one. These of course span more than 3 lines (unless minified). But in either case, if you want repeated connections, you just can't do this from scratch.

Next, on the server side, assuming you're on PHP:

```<code>set_time_limit(300); // force connection only after 5 minutes
ignore_user_abort(false); // if the connection ends, terminate immediately

while(true){
    if(some_condition()){
        echo some_response();
        break; // break the loop
    }
    sleep(2); // wait for a second or two
}
</code>```

Client side, just repeat the query whenever the connection ends. At this point, also handle the output.

Clients-side example:

```<code>function poll(){
    jQuery.get('http://somesite.com/poll.php',function(data){
        alert('Just received: '+data);
        poll(); // repeat poll
    });
}
poll(); // begin polling
</code>```

Body:
jQuery simply wraps around the XHR/XMLHTTPRequest object.
First of, you need a small function to return the object in a cross-browser manner. This is done in 3 lines or less, not too difficult. That said, the are great snippets for fixing different browser issues, such as memory leaks. I highly suggest you use this one. These of course span more than 3 lines (unless minified). But in either case, if you want repeated connections, you just can't do this from scratch.

Next, on the server side, assuming you're on PHP:

set_time_limit(300); // force connection only after 5 minutes
ignore_user_abort(false); // if the connection ends, terminate immediately

while(true){
    if(some_condition()){
        echo some_response();
        break; // break the loop
    }
    sleep(2); // wait for a second or two
}

Client side, just repeat the query whenever the connection ends. At this point, also handle the output.

Clients-side example:

function poll(){
    jQuery.get('http://somesite.com/poll.php',function(data){
        alert('Just received: '+data);
        poll(); // repeat poll
    });
}
poll(); // begin polling


问:
How do I modify my settings to allow VS2010 to load 3rd party XSD files from the "Unauthorized Zone"?
I have opened a 3rd party XSD file in Visual Studio 2010 that imports namespaces from other schema files from the same 3rd party.

In the XML editor view of the schema file, the xs:import element is underlined with the following error: Request for the permission of type 'System.Security.Permissions.FileIOPermission', mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089' failed.

I read the following blog post: Link which states that it's a security zone violation and Visual Studio places the schemas in the "Unauthorized zone" in the XML Schema Explorer.

My question is - how do I change my security settings to allow these schemas to be referenced, or is there something I can do to make the schemas and namespaces associated with them "trusted"?

答:
I had the same situation that I did not have unblock button. In my case helped the following
If Windows policy does not allow to unlock.

Try to archive the file eg. with 7zip in local drive (but not any shared drive and not directory of Onedrive/Dropbox/etc.. because those soft can add zones to files depending on system configuration).

Then unpack the archive to another local directory

File now should be without unauthorized zone.


问:
what is the advantage of map over heap in c++
currently i am doing problem on data structure and i have a question in which i have to find kth largest element in an array. the actual problem is here:
https://www.geeksforgeeks.org/kth-smallestlargest-element-unsorted-array/.

i did this question in two different way using heap and second is using map.

my solution using map.

```<code>   int t;
cin>>t;
while(--t>=0){
int n,k;
cin>>n;
vector<int> A(n);
for(int i=0;i<n;i++){
cin>>A[i];
 }
cin>>k;
map<int,int> m;
for(int i=0;i<n;i++){
    m[A[i]]++;
}
auto it=m.begin();
for(int i=1;i<=k-1;i++){
    it++;
}
cout<<it->first<<endl;
</code>```

but my map solution is giving Time Limit Exceeded. according to me map solution also has a time complexity of (n+klog(n)), same as heap solution.
so why is map solution giving TLE?

答:
Without seeing your heap version I would guess the map's allocation is the cause of the trouble. Each node needs an allocation, which implies a lock and some additional management.

And you have to follow the pointers internally in the map data structure, which is usually not the case in heaps.

In big O notation this doesn't add anything to the time, but in practice each can slow down the program by a large factor.

Body:
currently i am doing problem on data structure and i have a question in which i have to find kth largest element in an array. the actual problem is here:
https://www.geeksforgeeks.org/kth-smallestlargest-element-unsorted-array/.

i did this question in two different way using heap and second is using map.

my solution using map.

   int t;
cin>>t;
while(--t>=0){
int n,k;
cin>>n;
vector<int> A(n);
for(int i=0;i<n;i++){
cin>>A[i];
 }
cin>>k;
map<int,int> m;
for(int i=0;i<n;i++){
    m[A[i]]++;
}
auto it=m.begin();
for(int i=1;i<=k-1;i++){
    it++;
}
cout<<it->first<<endl;

but my map solution is giving Time Limit Exceeded. according to me map solution also has a time complexity of (n+klog(n)), same as heap solution.
so why is map solution giving TLE?


问:
NPM Cannot read property '0' of undefined
After updated Node (upto v8.6.0) and npm (upto v5.5.1) I cannot execute command npm install.
After npm install I've error message:

```<code>npm ERR! Cannot read property '0' of undefined
</code>```

What's trouble or I need downgrade node/npm ?

答: I bumped into this issue using nvs (Node Version Switcher -  https://github.com/jasongin/nvs) node@10.15.3 and npm@6.9.0. The reason was a local package I had linked with npm link. The solution was to remove that folder.

Body:
After updated Node (upto v8.6.0) and npm (upto v5.5.1) I cannot execute command npm install.
After npm install I've error message:

npm ERR! Cannot read property '0' of undefined

What's trouble or I need downgrade node/npm ?


问:
Error while reading XML from blob Container mycontainer in account .blob.core.windows.net not found
I use the following to read xml
val df = spark.read
.option("rowTag", "testing")
.xml(xmlpath)
xmlpath is a wasbs://mycontainer@.blob.core.windows.net/
but it has the following error
shaded.databricks.org.apache.hadoop.fs.azure.AzureException: shaded.databricks.org.apache.hadoop.fs.azure.AzureException: Container mycontainer in account .blob.core.windows.net not found, and we can't create it using anoynomous credentials, and no credentials found for them in the configuration.
what's happening

I put the same file to another blob account, the code run successfully . I don't know what happen to that blob account.

答:
According to the error message, I think your SAS token is not working. An easy way to create a SAS token is by using Microsoft Azure Storage Explorer as shown below.

For more information on how to connect Azure blob, please refer to this doc or the code below.

```<code>spark.conf.set(
  "fs.azure.sas.<your-container-name>.<your-storage-account-name>.blob.core.windows.net",
  "<the query string you copy>")

dbutils.fs.ls("wasbs://<your-container-name>@<your-storage-account-name>.blob.core.windows.net/<your-directory-name>")
</code>```

Expected output :

Hope this helps.

Body:
According to the error message, I think your SAS token is not working. An easy way to create a SAS token is by using Microsoft Azure Storage Explorer as shown below.

For more information on how to connect Azure blob, please refer to this doc or the code below.

spark.conf.set(
  "fs.azure.sas.<your-container-name>.<your-storage-account-name>.blob.core.windows.net",
  "<the query string you copy>")

dbutils.fs.ls("wasbs://<your-container-name>@<your-storage-account-name>.blob.core.windows.net/<your-directory-name>")

Expected output :

Hope this helps.


问:
Upgrading to Hibernate 4.1 and the "infamous" HibernateTemplate
I'm upgrading our project from Hibernate 3.0 to Hibernate 4.1.6. (And we are currently using spring 3.1)

I read in many articles and in HibernateTemplate documentation, that since version 4.0 HibernateTemplate is not supported and that I should replace it's usage with calling sessionFactory.getCurrentSession() to get a session.

Since this project was started with older version of Hibernate, where the use of HibernateTemplate was encouraged, we currently have 124 usages of HibernateTemplate across our project. I'm afraid that replacing all these occurrences with sessionFactory.getCurrentSession() might insert regression bugs in our project. In addition, there are some places where HibernateTemplate was used in a non-transactional context, where there is no 'current' session. What should I do in those cases? Open a new session and handle (close) it myself? That wasn't the case when I used HibernateTemplate.

Do you have some good strategy addressing these issues?

Thanks.

Relevant reading:

Hibernate Vs. Spring - HibernateTemplate history

Hibernate Core Migration Guide

MIGRATING TO SPRING 3.1 AND HIBERNATE 4.1

org.springframework.orm.hibernate3.HibernateTemplate

答:
You can also continue to use HibernateTemplate with getCurrentSession(), as in many cases openSession() might not be the best choice as you will need to close sessions on your own.
To use currentSession you can add the following to manage transactions:

<prop key="hibernate.transaction.jta.platform">org.hibernate.engine.transaction.jta.platform.internal.JBossAppServerJtaPlatform</prop>

where the key's value will depend on your AS.


问:
Is there a way to collapse all code blocks in Eclipse?
Eclipse has that "+/-" on the left to expand and collapse blocks of code.

I've got tens of thousands of lines to go through and would really like to just collapse everything, and selectively expand blocks to look at them.

答:
Shortcuts that worked for me in Versions Oxygen.2 Release (PHP/WINDOWS 7) were

Collapse all code blocks: CTRL + SHIFT + NUMPAD_DIVIDE

Expand all code blocks : CTRL + NUMPAD_MULTIPLY


问:
Suitescript, How to use query.Operator.ON to get record has exact day from database?
I'm trying to get records has a birthday in [day] by using query ('N/query'). And I'm looking for using the operator "Operator.ON".
However, I always get the empty list from DB.
When I change from "Operator.ON" to "Operator.ON_AFTER" I can get results.

My date format is "D/M/YYYY"
In DB, the record date is '1/5/2019'

The full script is attached.
Please let me know the best ways to get record by an exact date.

```<code> require(['N','N/search','N/record','N/query', 'N/currentRecord', 'N/format']);
    var query = require('N/query');
    var search = require('N/search');
    var currentRecord = require('N/currentRecord');

    var birth = currentRecord.get().getValue({
                fieldId: 'custentity_date_of_birth'
            });

    var customSearch = query.create({
                type: query.Type.CUSTOMER
            });

    var relContact = customSearch.autoJoin({
                fieldId: 'contact'
            });

            customSearch.columns = [
                customSearch.createColumn({
                    fieldId: 'Id'
                }),
                customSearch.createColumn({
                    fieldId: 'firstname'
                }),
                customSearch.createColumn({
                    fieldId: 'lastname'
                }),
                customSearch.createColumn({
                    fieldId: 'email'
                }),
                customSearch.createColumn({
                    fieldId: 'custentity_date_of_birth'
                }),
                relContact.createColumn({
                    fieldId: 'Id'
                })
            ];

    var condFName = customSearch.createCondition({
                fieldId: 'firstname',
                operator: query.Operator.IS,
                values: 'trung'
            });

            var condLName = customSearch.createCondition({
                fieldId: 'lastname',
                operator: query.Operator.IS,
                values: 'null'
            });

            var condBirth = customSearch.createCondition({
                fieldId: 'custentity_date_of_birth',
                operator: query.Operator.ON,
                values: '1/5/2019'
            });

            var condGetBirth = customSearch.createCondition({
                fieldId: 'custentity_date_of_birth',
                operator: query.Operator.EMPTY_NOT
            });

            customSearch.condition = customSearch.and(condFName, condLName, condBirth);

            var sResult = customSearch.run();
            sResult.results
</code>```

答:
the reason is my application is using GTM+7
In form, the date picker get date '1/5/2019' and passing this string to script

In backend, Netsuite get this day '1/5/2019' and parse it to GTM+7 -> 30/4/2019 and compare in data. It never match with the record '1/5/2019' in db

I tried to convert date & timezone from date picker but useless. I must hardcode date+1 day and pass to the condition then it can get exact day from DB.

Body:
I'm trying to get records has a birthday in [day] by using query ('N/query'). And I'm looking for using the operator "Operator.ON".
However, I always get the empty list from DB.
When I change from "Operator.ON" to "Operator.ON_AFTER" I can get results.

My date format is "D/M/YYYY"
In DB, the record date is '1/5/2019'

The full script is attached.
Please let me know the best ways to get record by an exact date.

 require(['N','N/search','N/record','N/query', 'N/currentRecord', 'N/format']);
    var query = require('N/query');
    var search = require('N/search');
    var currentRecord = require('N/currentRecord');

    var birth = currentRecord.get().getValue({
                fieldId: 'custentity_date_of_birth'
            });

    var customSearch = query.create({
                type: query.Type.CUSTOMER
            });

    var relContact = customSearch.autoJoin({
                fieldId: 'contact'
            });

            customSearch.columns = [
                customSearch.createColumn({
                    fieldId: 'Id'
                }),
                customSearch.createColumn({
                    fieldId: 'firstname'
                }),
                customSearch.createColumn({
                    fieldId: 'lastname'
                }),
                customSearch.createColumn({
                    fieldId: 'email'
                }),
                customSearch.createColumn({
                    fieldId: 'custentity_date_of_birth'
                }),
                relContact.createColumn({
                    fieldId: 'Id'
                })
            ];

    var condFName = customSearch.createCondition({
                fieldId: 'firstname',
                operator: query.Operator.IS,
                values: 'trung'
            });

            var condLName = customSearch.createCondition({
                fieldId: 'lastname',
                operator: query.Operator.IS,
                values: 'null'
            });

            var condBirth = customSearch.createCondition({
                fieldId: 'custentity_date_of_birth',
                operator: query.Operator.ON,
                values: '1/5/2019'
            });

            var condGetBirth = customSearch.createCondition({
                fieldId: 'custentity_date_of_birth',
                operator: query.Operator.EMPTY_NOT
            });

            customSearch.condition = customSearch.and(condFName, condLName, condBirth);

            var sResult = customSearch.run();
            sResult.results


问:
What's the difference between ++$i and $i++ in PHP?
What's the difference between ++$i and $i++ in PHP?

答:
Both operators still do what their syntax implies: to increment. Regardless of prefix or postfix, the variable is sure to be incremented by 1. The difference between the two lies in their return values.

1. The prefix increment returns the value of a variable after it has been incremented.

2. On the other hand, the more commonly used postfix increment returns the value of a variable before it has been incremented.

```<code>// Prefix increment

let prefix = 1;
console.log(++prefix); // 2

console.log(prefix); // 2

// Postfix increment

let postfix = 1;

console.log(postfix++); // 1

console.log(postfix); // 2
</code>```

To remember this rule, I think about the syntax of the two. When one types in the prefix increment, one says ++x. The position of the ++ is important here. Saying ++x means to increment (++) first then return the value of x, thus we have ++x. The postfix increment works conversely. Saying x++ means to return the value of x first then increment (++) it after, thus x++.

Body:
Both operators still do what their syntax implies: to increment. Regardless of prefix or postfix, the variable is sure to be incremented by 1. The difference between the two lies in their return values.

1. The prefix increment returns the value of a variable after it has been incremented.

2. On the other hand, the more commonly used postfix increment returns the value of a variable before it has been incremented.

// Prefix increment

let prefix = 1;
console.log(++prefix); // 2

console.log(prefix); // 2

// Postfix increment

let postfix = 1;

console.log(postfix++); // 1

console.log(postfix); // 2

To remember this rule, I think about the syntax of the two. When one types in the prefix increment, one says ++x. The position of the ++ is important here. Saying ++x means to increment (++) first then return the value of x, thus we have ++x. The postfix increment works conversely. Saying x++ means to return the value of x first then increment (++) it after, thus x++.


问:
Why won't my If statement with multiple -AND conditions function correctly?
I am wanting to meet multiple conditions in my Powershell If statement and am trying to use the -AND operator to achieve it, but it seems to be just jumping straight to the else clause.

In the code below I want to make sure both folders have no files and that the "watcher.txt" file exists.

```<code>$Success = "C:\temp\Success"
$Failed = "C:\temp\failed"
$watcher = "C:\temp\watcher.txt"

$directoryInfo3 = get-childitem "$Success\\*" -file | Measure-Object
$directoryInfo3.count
$directoryInfo4 = get-childitem "$Failed\\*" -file | Measure-Object
$directoryInfo4.count
    if ((test-path -path $Watcher) -AND
        ($directoryInfo3 -eq 0) -AND
        ($directoryInfo4 -eq 0)){
         Write-host "Success folder and Failed folder are empty, and Watcher file exists."}
         else
         {Write-host "Not complete yet, rechecking folders."}
</code>```

If all three statements are true, then I should see "Success folder and Failed folder are empty, and Watcher file exists."

Instead I am seeing "Not complete yet, rechecking folders." no matter what the condition is, even if all three are true.

答:
You will need to call $directoryInfo3.count for the statement to result in true.
i.e.:

```<code>PS C:\> $dir = gci c:\temp\ -file | measure
PS C:\> $dir

Count    : 36
Average  :
Sum      :
Maximum  :
Minimum  :
Property :

PS C:\> $dir -eq 36
False
PS C:\> $dir.count -eq 36
True
</code>```

Body:
I am wanting to meet multiple conditions in my Powershell If statement and am trying to use the -AND operator to achieve it, but it seems to be just jumping straight to the else clause.

In the code below I want to make sure both folders have no files and that the "watcher.txt" file exists.

$Success = "C:\temp\Success"
$Failed = "C:\temp\failed"
$watcher = "C:\temp\watcher.txt"

$directoryInfo3 = get-childitem "$Success\\*" -file | Measure-Object
$directoryInfo3.count
$directoryInfo4 = get-childitem "$Failed\\*" -file | Measure-Object
$directoryInfo4.count
    if ((test-path -path $Watcher) -AND
        ($directoryInfo3 -eq 0) -AND
        ($directoryInfo4 -eq 0)){
         Write-host "Success folder and Failed folder are empty, and Watcher file exists."}
         else
         {Write-host "Not complete yet, rechecking folders."}

If all three statements are true, then I should see "Success folder and Failed folder are empty, and Watcher file exists."

Instead I am seeing "Not complete yet, rechecking folders." no matter what the condition is, even if all three are true.

Body:
You will need to call $directoryInfo3.count for the statement to result in true.
i.e.:

PS C:\> $dir = gci c:\temp\ -file | measure
PS C:\> $dir

Count    : 36
Average  :
Sum      :
Maximum  :
Minimum  :
Property :

PS C:\> $dir -eq 36
False
PS C:\> $dir.count -eq 36
True


问:
What is best way to externalize error messages(resource bundles) out of src code in spring and springboot?
I am looking for best way to externalize my validation error messages out of my src code in spring and spring boot application, in order to avoid build/deployment on each time the error messages changes. Is there possibly any such ways to achieve it?</p>

答:
You can maintain all the validation error or success messages in a properties file. If you want to externalize, you can place the properties file outside the spring boot jar file. It is not necessary to put the configuration inside jar. I provide below the code snippet to achieve it.

```<code>import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.PropertySource;
import org.springframework.context.annotation.PropertySources;
import org.springframework.context.support.PropertySourcesPlaceholderConfigurer;

    @Configuration
    @PropertySources({
      @PropertySource("file:config/other-config.properties"),
      @PropertySource("file:config/app-config.properties")
    })
    public class ExternalConfig {

      @Bean
      public static PropertySourcesPlaceholderConfigurer propertyConfigInDev() {
        return new PropertySourcesPlaceholderConfigurer();
      }
    }
</code>```

In the above code, in the line @PropertySource("file:config/app-config.properties"), config is the name of the folder or directory which contains many properties files like "app-config.properties". For better understanding, I provide below the image, external config file and spring boot jar will look like this finally.

Body:
You can maintain all the validation error or success messages in a properties file. If you want to externalize, you can place the properties file outside the spring boot jar file. It is not necessary to put the configuration inside jar. I provide below the code snippet to achieve it.

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.PropertySource;
import org.springframework.context.annotation.PropertySources;
import org.springframework.context.support.PropertySourcesPlaceholderConfigurer;

    @Configuration
    @PropertySources({
      @PropertySource("file:config/other-config.properties"),
      @PropertySource("file:config/app-config.properties")
    })
    public class ExternalConfig {

      @Bean
      public static PropertySourcesPlaceholderConfigurer propertyConfigInDev() {
        return new PropertySourcesPlaceholderConfigurer();
      }
    }

In the above code, in the line @PropertySource("file:config/app-config.properties"), config is the name of the folder or directory which contains many properties files like "app-config.properties". For better understanding, I provide below the image, external config file and spring boot jar will look like this finally.


问:
Concatenation of int with string to TextView gives a set of Integer
In my android app, I'm trying to set the text to a TextView with integer and a string value. I'm getting the length of the array and going to set it with a string value as below.

```<code>if (array.size() > 0) {
    textView.setText(array.size() + " " + R.string.lbl_text);
}
</code>```

When I run the App it give me a set of integers as shown below:

```<code>1 2345223232
</code>```

Then I covert array size to string as follow

```<code>if (array.size() > 0) {
    textView.setText(Integer.toString(array.size()) + " " + R.string.lbl_text);
}
</code>```

But the same output. What is the reason for getting Integer value for the string.lbl_text

答:
```<code>Use getResources().getString(R.string.lbl_text) and then you would be able to access the string text. as @pskink told already
</code>```

Body:
In my android app, I'm trying to set the text to a TextView with integer and a string value. I'm getting the length of the array and going to set it with a string value as below.

if (array.size() > 0) {
    textView.setText(array.size() + " " + R.string.lbl_text);
}

When I run the App it give me a set of integers as shown below:

1 2345223232

Then I covert array size to string as follow

if (array.size() > 0) {
    textView.setText(Integer.toString(array.size()) + " " + R.string.lbl_text);
}

But the same output. What is the reason for getting Integer value for the string.lbl_text


问:
How to fix state change in VUEX?
I have a problem with changing state while splicing element from another array then changes in state. TO be clear, i don't want state to change, just want to splice one element from array  arrayWithFilters = []

export const SHOW_RESULTS_WHEN_NOTHING = (state) => {
  let selectedFilters = {...state.selected.filters},
  arrayWithFilters = []; //Making splice from this array, but it also removes from state.selected.filters.

  for (let filter in selectedFilters) {
    arrayWithFilters.push(selectedFilters[filter])
  }

  arrayWithFilters.forEach((filter) => {
    if (filter.values.includes('qcontrast')) {
      filter.values.splice('qcolor', 1);
      console.log(filter)
    }
  })
}
```

答:
problem solved with the next code

```<code>export const SHOW_RESULTS_WHEN_NOTHING = (state) => {
let selectedFilters = {...state.selected.filters},
    arrayWithFilters = [];

let selectedFiltersCopy = JSON.parse(JSON.stringify(selectedFilters));

arrayWithFilters = Object.values(selectedFiltersCopy);

arrayWithFilters.forEach((filter) => {

    if (filter.values.includes('qcontrast')) {

        filter.values.splice('qcontrast', 1);

    }
})

console.log(arrayWithFilters)
</code>```

}

Title: How to fix state change in VUEX?

Body:
problem solved with the next code

export const SHOW_RESULTS_WHEN_NOTHING = (state) => {
let selectedFilters = {...state.selected.filters},
    arrayWithFilters = [];

let selectedFiltersCopy = JSON.parse(JSON.stringify(selectedFilters));

arrayWithFilters = Object.values(selectedFiltersCopy);

arrayWithFilters.forEach((filter) => {

    if (filter.values.includes('qcontrast')) {

        filter.values.splice('qcontrast', 1);

    }
})

console.log(arrayWithFilters)

}


问:
Trying the find a more semantic way for writing Spring Entity in Kotlin
I have an Spring entity written in Kotlin:

```<code>@Entity
class Book(
    @Id
    var id: Long? = null,
    var title: String? = null, // cannot actually be null, immutable
    var isInStock: Boolean? = null, // cannot actually be null
    var description: String? = null,
 )
</code>```

All the fields must be nullable, because Spring needs to initialize empty objects.

However, this makes using the entity complicated, because I always have to convert the nullable types to their not nullable equivalents. This is not semantic: I would like to really see, which fields can actually be nullable and which ones cannot (or can only be null during the initialization process).

Furthermore, some fields are mutable, but some should never be altered after the entity has been created. It would be nice to use Kotlin's val and var to make this distinction.

So, I would like to work with the following class:

```<code>class BetterBook(
    val id: Long,
    val title: String,
    var isInStock: Boolean,
    var description: String? = null,
 )
</code>```

This way it is very clear which fields are mutable and which fields can be null.

I pondered upon creating a wrapper around Book. Has anybody had a similar thought? Would it be a good solution architecturally?

答: You can actually do exactly what you want: define the class with val instead of var for the immutable properties, give them non-nullable types, and have no default constructor. Spring uses Reflection to get at the member variables underlying the (read-only) properties generated by the Kotlin code when setting the values from the database. And for a default-constructor (which it does need at runtime) there's a kotlin-jpa plugin that will generate this for you automatically in the compiled code. So basically keep your code exactly as you'd idiomatically write it (as you did for BetterBook), and annotate the class with @Entity, but make sure to apply that plugin.

Body:
I have an Spring entity written in Kotlin:

@Entity
class Book(
    @Id
    var id: Long? = null,
    var title: String? = null, // cannot actually be null, immutable
    var isInStock: Boolean? = null, // cannot actually be null
    var description: String? = null,
 )

All the fields must be nullable, because Spring needs to initialize empty objects.

However, this makes using the entity complicated, because I always have to convert the nullable types to their not nullable equivalents. This is not semantic: I would like to really see, which fields can actually be nullable and which ones cannot (or can only be null during the initialization process).

Furthermore, some fields are mutable, but some should never be altered after the entity has been created. It would be nice to use Kotlin's val and var to make this distinction.

So, I would like to work with the following class:

class BetterBook(
    val id: Long,
    val title: String,
    var isInStock: Boolean,
    var description: String? = null,
 )

This way it is very clear which fields are mutable and which fields can be null.

I pondered upon creating a wrapper around Book. Has anybody had a similar thought? Would it be a good solution architecturally?


问:
Loading multiply csv in pandas dataframe array with index as file name
I have tried this:

```<code>>>> df = [pd.read_csv(x,header=None,names=["L1","L2","cache","cached","result"]) for x in iglob(os.path.join("test","**","*.csv"), recursive=True)]
>>> df
[   L1  L2  cache  cached  result
0   0   0      0       0       0
1   1   2      3       4       5
2   1   1      1       1       1
3   2   2      2       2       2
4   4   4      4       4       4,    L1  L2  cache  cached  result
0   1   2      3       4       5
1   1   2      3       4       5
2   3   4      5       6       7
3   2   1      3       2       4]
</code>```

The folder structure is:

```<code>test
|
|_______ wait
         |
         |______ 0.2322.csv
         |______ 1.234.csv
</code>```

The two files contain:

0.2322.csv

```<code>0,0,0,0,0
1,2,3,4,5
1,1,1,1,1
2,2,2,2,2
4,4,4,4,4
</code>```

1.234.csv

```<code>1,2,3,4,5
1,2,3,4,5
3,4,5,6,7
2,1,3,2,4
</code>```

When I am trying to access the dataframes from the df array, I have to call it with the index values as 0,1 i.e. df[0] and df[1].

But I want to call the dataframe of the respective files with there file name as index as df["0.2322"] and df["1.234"]. But I am not getting a clue how that is possible. Please let me know what I can do to achieve what I expect.

答:
I think you need dictionary comprehension with parse filename without extension:

```<code>import os

#https://stackoverflow.com/a/678242
df = {os.path.splitext(x)[0]: pd.read_csv(x,header=None,names=["L1","L2","cache","cached","result"]) for x in iglob(os.path.join("test","**","*.csv"), recursive=True)}
</code>```

EDIT:

```<code>#https://stackoverflow.com/a/37760212
df = {os.path.splitext(os.path.basename(x))[0]: pd.read_csv(x,header=None,names=["L1","L2","cache","cached","result"]) for x in iglob(os.path.join("test","**","*.csv"), recursive=True)}
</code>```

Body:
I have tried this:

>>> df = [pd.read_csv(x,header=None,names=["L1","L2","cache","cached","result"]) for x in iglob(os.path.join("test","**","*.csv"), recursive=True)]
>>> df
[   L1  L2  cache  cached  result
0   0   0      0       0       0
1   1   2      3       4       5
2   1   1      1       1       1
3   2   2      2       2       2
4   4   4      4       4       4,    L1  L2  cache  cached  result
0   1   2      3       4       5
1   1   2      3       4       5
2   3   4      5       6       7
3   2   1      3       2       4]

The folder structure is:

test
|
|_______ wait
         |
         |______ 0.2322.csv
         |______ 1.234.csv

The two files contain:

0.2322.csv

0,0,0,0,0
1,2,3,4,5
1,1,1,1,1
2,2,2,2,2
4,4,4,4,4

1.234.csv

1,2,3,4,5
1,2,3,4,5
3,4,5,6,7
2,1,3,2,4

When I am trying to access the dataframes from the df array, I have to call it with the index values as 0,1 i.e. df[0] and df[1].

But I want to call the dataframe of the respective files with there file name as index as df["0.2322"] and df["1.234"]. But I am not getting a clue how that is possible. Please let me know what I can do to achieve what I expect.

Body:
I think you need dictionary comprehension with parse filename without extension:

import os

#https://stackoverflow.com/a/678242
df = {os.path.splitext(x)[0]: pd.read_csv(x,header=None,names=["L1","L2","cache","cached","result"]) for x in iglob(os.path.join("test","**","*.csv"), recursive=True)}

EDIT:

#https://stackoverflow.com/a/37760212
df = {os.path.splitext(os.path.basename(x))[0]: pd.read_csv(x,header=None,names=["L1","L2","cache","cached","result"]) for x in iglob(os.path.join("test","**","*.csv"), recursive=True)}


问:
Outputting Images in ASP FPDF problem
Hi
I'm attempting to use the ASPFPDF class to output an image on a pdf using the very simple code below:

```<code><!--#include file="fpdf.asp"-->
<%
 Dim pages

 Dim pdf
 Set pdf=CreateJsObject("FPDF")

 pdf.CreatePDF "P", "mm", "A4"

 pdf.SetPath "fpdf/"

 pdf.Open()
 pdf.AddPage("P")

 pdf.Image "invoiceheader.jpg"
 pdf.Output ()
%>
</code>```

When run, this script should open the pdf but with Adobe Reader I get a "File does not begin with %pdf" message. I've tried using other readers with similar results.

If I remove the image line and output some text (e.g. pdf.Cell 40,5,"Date",0,1,"R"), everything works perfectly.

Anyone got any ideas before I go mad!

Thank you.

答:
I found that the only way I could add images was as follows:-

pdf.Image "./byimage.jpg",x,y,width

ContentLicense: CC BY-SA 2.5

Title: Outputting Images in ASP FPDF problem

Body:
Hi
I'm attempting to use the ASPFPDF class to output an image on a pdf using the very simple code below:

<%
 Dim pages

 Dim pdf
 Set pdf=CreateJsObject("FPDF")

 pdf.CreatePDF "P", "mm", "A4"

 pdf.SetPath "fpdf/"

 pdf.Open()
 pdf.AddPage("P")

 pdf.Image "invoiceheader.jpg"
 pdf.Output ()
%>

When run, this script should open the pdf but with Adobe Reader I get a "File does not begin with %pdf" message. I've tried using other readers with similar results.

If I remove the image line and output some text (e.g. pdf.Cell 40,5,"Date",0,1,"R"), everything works perfectly.

Anyone got any ideas before I go mad!

Thank you.


问:
What is the difference between DownloadText() and DownloadTextAsync()?
In my code, I am fetching a reference of a blob in a container and I am calling DownloadText() method on it but I get an error
 no accessible extension method 'DownloadText' accepting a first argument of type 'CloudBlockBlob' could be found

As one of the potential fixes, visual studio tells me to use DownloadTextAsync() method. What is the difference between the two methods?

I am getting my storage account using new CloudStorageAccount and then getting the BlobClient using storageAccount.CreateCloudBlobClient(). Then getting the reference to container using GetContainerReference() on the client and to BlockBlob using GetBlockBlobReference() on the container reference, I am then calling blockBlob.DownloadText() which is showing me the error 'CloudBlockBlob' does not contain a definition for 'DownloadText' and no accessible extension method 'DownloadText' accepting a first argument of type 'CloudBlockBlob' could be found (are you missing a using directive or an assembly reference?) and shows me to use DownloadTextAsync() as a potential fix.

答:
In .net core project, if you're using WindowsAzure.Storage nuget package, there is only async method like DownloadTextAsync, no sync method like DownloadText.

But the new package Microsoft.Azure.Storage.Blob does support sync and async method like DownloadTextAsync and DownloadText.

It depends on you to choose sync or async method.

If the file is very large, and it will take a long time to download it, and you have some other things to do during download, you can choose async method.

Sample async code like below:

```<code>class Program
{
    static void Main(string[] args)
    {
        //your other code
        CloudBlockBlob myblob = cloudBlobContainer.GetBlockBlobReference("mytemp.txt");

        Console.WriteLine("in main thread: start download 111");

        //assume the download would take 10 minutes.
        Task<string> s = myblob.DownloadTextAsync();

        //The message will print out immediately even if the download is in progress.
        Console.WriteLine("in main thread 222!");

        //use this code to check if the download complete or not
        while (!s.IsCompleted)
        {
            Console.WriteLine("not completed");
            System.Threading.Thread.Sleep(2000);
        }

        Console.WriteLine("the string length in MB: "+s.Result.Length/1024/1024);

        Console.ReadLine();
    }

}
</code>```

When run the above code, you can see that the message in main thread 222! is printed out immediately, even if the download is in progress. And it means that you can do others thing(some other operation) when the download is in progress. They do not block each other.

And if you're using sync method, like code below:

```<code>        static void Main(string[] args)
        {
            CloudStorageAccount storageAccount = CloudStorageAccount.Parse("xxxx");

            var blobClient = storageAccount.CreateCloudBlobClient();
            CloudBlobContainer cloudBlobContainer = blobClient.GetContainerReference("f22");
            CloudBlockBlob myblob = cloudBlobContainer.GetBlockBlobReference("mytemp.txt");

            Console.WriteLine("in main thread: start download 111");

            string s = myblob.DownloadText();

            //if the download takes 10 minutes, then the following message will be printed out after 10 minutes.
            Console.WriteLine("in main thread 222!");

            Console.ReadLine();
        }
</code>```

if the file is large, and would take 10 minutes to complete downloading. When run the code, the message in main thread 222! will be blocked 10 minites(after the downloading completes), then print out.

Body:
In .net core project, if you're using WindowsAzure.Storage nuget package, there is only async method like DownloadTextAsync, no sync method like DownloadText.

But the new package Microsoft.Azure.Storage.Blob does support sync and async method like DownloadTextAsync and DownloadText.

It depends on you to choose sync or async method.

If the file is very large, and it will take a long time to download it, and you have some other things to do during download, you can choose async method.

Sample async code like below:

class Program
{
    static void Main(string[] args)
    {
        //your other code
        CloudBlockBlob myblob = cloudBlobContainer.GetBlockBlobReference("mytemp.txt");

        Console.WriteLine("in main thread: start download 111");

        //assume the download would take 10 minutes.
        Task<string> s = myblob.DownloadTextAsync();

        //The message will print out immediately even if the download is in progress.
        Console.WriteLine("in main thread 222!");

        //use this code to check if the download complete or not
        while (!s.IsCompleted)
        {
            Console.WriteLine("not completed");
            System.Threading.Thread.Sleep(2000);
        }

        Console.WriteLine("the string length in MB: "+s.Result.Length/1024/1024);

        Console.ReadLine();
    }

}

When run the above code, you can see that the message in main thread 222! is printed out immediately, even if the download is in progress. And it means that you can do others thing(some other operation) when the download is in progress. They do not block each other.

And if you're using sync method, like code below:

        static void Main(string[] args)
        {
            CloudStorageAccount storageAccount = CloudStorageAccount.Parse("xxxx");

            var blobClient = storageAccount.CreateCloudBlobClient();
            CloudBlobContainer cloudBlobContainer = blobClient.GetContainerReference("f22");
            CloudBlockBlob myblob = cloudBlobContainer.GetBlockBlobReference("mytemp.txt");

            Console.WriteLine("in main thread: start download 111");

            string s = myblob.DownloadText();

            //if the download takes 10 minutes, then the following message will be printed out after 10 minutes.
            Console.WriteLine("in main thread 222!");

            Console.ReadLine();
        }

if the file is large, and would take 10 minutes to complete downloading. When run the code, the message in main thread 222! will be blocked 10 minites(after the downloading completes), then print out.


问:
Get a tag value in multi line XML using shell script
I have a xml file as follows

```<code><Module dataPath="/abc/def/xyz" handler="DataRegistry" id="id1" path="test.so"/>
<Module id="id2" path="/my/file/path">
  <Config>
    <Source cutoffpackage="1" dailyStart="20060819" dataPath="/abc/def/xyz" />
    <Source cutoffpackage="1" dailyStart="20060819" dataPath="/abc/def/xyz" id="V2"/>
  </Config>
</Module>
</code>```

I just want to extract value of dataPath from every moduleid.

I was using, the command like

```<code>`grep 'id2' file | grep -ioPm1 "(?<=DataPath=)[^ ]+"`
</code>```

which is giving me from the first module id, not for second module id. because second module is in multiple lines.

How can i do this using shell script?

Desired output would be– if i want to get the datapath of id1 module, then is should get

```<code>/my/file/path
</code>```

Of for second module id, say id2, i should get datapath separated by comma

```<code>/my/file/path, /my/file/path
</code>```

Or my second approach to grep the datapath is to replace the newline character between <Module and </Module> only, then i can use grep.

答:
-m1 tells grep to exit after first matching line, that's why it prints only one line of output.

I wouldn't use a line oriented tool for this though. There are more convenient tools out there for parsing XML, such as xmlstarlet:

```<code>xml sel -t -m '//@dataPath' -v . -n file.xml
</code>```

Body:
I have a xml file as follows

<Module dataPath="/abc/def/xyz" handler="DataRegistry" id="id1" path="test.so"/>
<Module id="id2" path="/my/file/path">
  <Config>
    <Source cutoffpackage="1" dailyStart="20060819" dataPath="/abc/def/xyz" />
    <Source cutoffpackage="1" dailyStart="20060819" dataPath="/abc/def/xyz" id="V2"/>
  </Config>
</Module>

I just want to extract value of dataPath from every moduleid.

I was using, the command like

`grep 'id2' file | grep -ioPm1 "(?<=DataPath=)[^ ]+"`

which is giving me from the first module id, not for second module id. because second module is in multiple lines.

How can i do this using shell script?

Desired output would be– if i want to get the datapath of id1 module, then is should get

/my/file/path

Of for second module id, say id2, i should get datapath separated by comma

/my/file/path, /my/file/path

Or my second approach to grep the datapath is to replace the newline character between <Module and </Module> only, then i can use grep.

Body:
-m1 tells grep to exit after first matching line, that's why it prints only one line of output.

I wouldn't use a line oriented tool for this though. There are more convenient tools out there for parsing XML, such as xmlstarlet:

xml sel -t -m '//@dataPath' -v . -n file.xml


问:
how can I post to api running on remote desktop?
I'm creating a python flask api on remote desktop and running it on localhost of remote desktop.
Is there anyway I can access this api from my local machine?
We are working in a team and I want to share this with my team members, but this is confidential and not to be deployed on open server.
We want to post and get the result with every member's local machine from api runnnig on remote desktop.
Both of our local machines and remote desktop are windows10.
Sorry for being abstract but I'm searching for any way out. Thanks.</p>

答:
Short term solution:

Firstly download ngrok for your operating system.

For debugging and testing purposes you can expose a secure tunnel connection to your API by running this command in your command prompt / terminal.

```<code>ngrok http <PORT_NUMBER>-host-header="localhost:<PORT_NUMBER>"
</code>```

Where PORT_NUMBER is the port number in which your flask application is running.

Example if your flask application is running at port 5000 then simply execute this command:

```<code>ngrok http 5000 -host-header="localhost:5000"
</code>```

Running this will give you two hostnames one with HTTP and other a secure HTTPS connected by a tunnel like this for a duration of 8 hours after which the command needs to again re-run.

Which you can call remotely

Long term solution:

Deploy flask application using FastCGI

or

To a cloud infrastructure provider like Microsoft Azure which gives readymade templates for flask applications.

Body:
Short term solution:

Firstly download ngrok for your operating system.

For debugging and testing purposes you can expose a secure tunnel connection to your API by running this command in your command prompt / terminal.

ngrok http <PORT_NUMBER>-host-header="localhost:<PORT_NUMBER>"

Where PORT_NUMBER is the port number in which your flask application is running.

Example if your flask application is running at port 5000 then simply execute this command:

ngrok http 5000 -host-header="localhost:5000"

Running this will give you two hostnames one with HTTP and other a secure HTTPS connected by a tunnel like this for a duration of 8 hours after which the command needs to again re-run.

Which you can call remotely

Long term solution:

Deploy flask application using FastCGI

or

To a cloud infrastructure provider like Microsoft Azure which gives readymade templates for flask applications.


问:
How to provide a list of textboxes and file input textboxes based on 2 arrays
i have 2 arrays - Array $doc_list_submitted for a list of docs a user have submitted and $listDocToProvide for a list of docs a user need to provide.

i need to list all docs provided in a textbox and with it a file input textbox if the user want to edit the file uploaded and other file input textboxes for the user to upload files not yet uploaded.

Here is what i have so far:

```<code><?php
//list of doc to provide
$listDocToProvide  = clients::recupereListDocToProvide($projet_id);

//list of docs a user have submitted
$doc_list_submitted  = clients::recupereListDocSubmitted($client_projet_id);

//categorise $doc_list_submitted par doc_type_id
$result = array();
foreach ($doc_list_submitted as $element) {
    $result[$element['DOC_CLIENT_ID']][] = $element;
}

$iDocsx = 0;
foreach ($result as $key=>$row)
{
?>
    <input type="text" id="docfile" name="docfile[]" value="<?php echo ($result[$iDocsx]['DOC_CLIENT_NOM']); ?>" >
    <?php echo "<br>"; ?>
    <input type="file" id="docfile" name="docfileUpload[]" value="<?php echo basename($result[$iDocsx]['CLIENT_PROJET_DOC_CLIENT_MODELE_DOC']); ?>" >
<?php
    $iDocsx++;
                }
?>
</code>```

I get the list of docs submitted, now i need to put textboxes for docs not yet uploaded. I have spend a whole night on this but i have not been able to do it. I need to list each file under its category like this:

Cat 1:

```<code>Uploaded : File 1 / File 2
Need : Textbox 1 / Textbox 2 / Textbox 3
</code>```

Cat 2:

```<code>Uploaded : File 1
Need : Textbox 1 / Textbox 2
</code>```

Could somebody please assist me.

Here is the array $doc_list_submitted:

```<code>[1101] => Array
    (
        [0] => Array
            (
                [CLIENT_PROJET_DOC_CLIENT_ID] => 6301
                [CLIENT_PROJET_ID] => 8701
                [CLIENT_ID] => 4401
                [PROJET_ID] => 4101
                [DOC_CLIENT_ID] => 1101
                [CLIENT_PROJET_DOC_CLIENT_MODELE_DOC] => upload/doc_client_document/test 1.txt
                [CLIENT_PROJET_DOC_CLIENT_MODELE_DOC_REF] =>
                [CLIENT_PROJET_DOC_CLIENT_QTY] =>
                [DOC_CLIENT_NOM] => Lettre de référence bancaire
            )
    )

[901] => Array
    (
        [0] => Array
            (
                [CLIENT_PROJET_DOC_CLIENT_ID] => 6401
                [CLIENT_PROJET_ID] => 8701
                [CLIENT_ID] => 4401
                [PROJET_ID] => 4101
                [DOC_CLIENT_ID] => 901
                [CLIENT_PROJET_DOC_CLIENT_MODELE_DOC] => upload/doc_client_document/test 2.txt
                [CLIENT_PROJET_DOC_CLIENT_QTY] =>
                [DOC_CLIENT_NOM] => Pièce identité
            )
    )
</code>```

Here is the array $listDocToProvide:

```<code>[1101] => Array
    (
        [0] => Array
            (
                [PROJET_DOC_CLIENT_ID] => 4301
                [PROJET_ID] => 4101
                [DOC_CLIENT_ID] => 1101
                [DOC_CLIENT_NUM] => 2
                [DOC_CLIENT_NOM] => Lettre de référence bancaire
            )
    )

[901] => Array
    (
        [0] => Array
            (
                [PROJET_DOC_CLIENT_ID] => 4401
                [PROJET_ID] => 4101
                [DOC_CLIENT_ID] => 901
                [DOC_CLIENT_NUM] => 3
                [DOC_CLIENT_NOM] => Pièce identité
            )
    )
</code>```

答:
In this part of your code you have same id for file and textbox change it like this:</p>

```<code><input type="text" id="doctext" name="docfile[]" value="<?php echo ($result[$iDocsx]['doc_name']); ?>" >
       echo "br";
<input type="file" id="docfile" name="docfileUpload[]" value="<?php echo basename($result[$iDocsx]['doc_modele']); ?>" >
</code>```

Body:
i have 2 arrays - Array $doc_list_submitted for a list of docs a user have submitted and $listDocToProvide for a list of docs a user need to provide.

i need to list all docs provided in a textbox and with it a file input textbox if the user want to edit the file uploaded and other file input textboxes for the user to upload files not yet uploaded.

Here is what i have so far:

<?php
//list of doc to provide
$listDocToProvide  = clients::recupereListDocToProvide($projet_id);

//list of docs a user have submitted
$doc_list_submitted  = clients::recupereListDocSubmitted($client_projet_id);

//categorise $doc_list_submitted par doc_type_id
$result = array();
foreach ($doc_list_submitted as $element) {
    $result[$element['DOC_CLIENT_ID']][] = $element;
}

$iDocsx = 0;
foreach ($result as $key=>$row)
{
?>
    <input type="text" id="docfile" name="docfile[]" value="<?php echo ($result[$iDocsx]['DOC_CLIENT_NOM']); ?>" >
    <?php echo "
"; ?>
    <input type="file" id="docfile" name="docfileUpload[]" value="<?php echo basename($result[$iDocsx]['CLIENT_PROJET_DOC_CLIENT_MODELE_DOC']); ?>" >
<?php
    $iDocsx++;
                }
?>

I get the list of docs submitted, now i need to put textboxes for docs not yet uploaded. I have spend a whole night on this but i have not been able to do it. I need to list each file under its category like this:

Cat 1:

Uploaded : File 1 / File 2
Need : Textbox 1 / Textbox 2 / Textbox 3

Cat 2:

Uploaded : File 1
Need : Textbox 1 / Textbox 2

Could somebody please assist me.

Here is the array $doc_list_submitted:

[1101] => Array
    (
        [0] => Array
            (
                [CLIENT_PROJET_DOC_CLIENT_ID] => 6301
                [CLIENT_PROJET_ID] => 8701
                [CLIENT_ID] => 4401
                [PROJET_ID] => 4101
                [DOC_CLIENT_ID] => 1101
                [CLIENT_PROJET_DOC_CLIENT_MODELE_DOC] => upload/doc_client_document/test 1.txt
                [CLIENT_PROJET_DOC_CLIENT_MODELE_DOC_REF] =>
                [CLIENT_PROJET_DOC_CLIENT_QTY] =>
                [DOC_CLIENT_NOM] => Lettre de référence bancaire
            )
    )

[901] => Array
    (
        [0] => Array
            (
                [CLIENT_PROJET_DOC_CLIENT_ID] => 6401
                [CLIENT_PROJET_ID] => 8701
                [CLIENT_ID] => 4401
                [PROJET_ID] => 4101
                [DOC_CLIENT_ID] => 901
                [CLIENT_PROJET_DOC_CLIENT_MODELE_DOC] => upload/doc_client_document/test 2.txt
                [CLIENT_PROJET_DOC_CLIENT_QTY] =>
                [DOC_CLIENT_NOM] => Pièce identité
            )
    )

Here is the array $listDocToProvide:

[1101] => Array
    (
        [0] => Array
            (
                [PROJET_DOC_CLIENT_ID] => 4301
                [PROJET_ID] => 4101
                [DOC_CLIENT_ID] => 1101
                [DOC_CLIENT_NUM] => 2
                [DOC_CLIENT_NOM] => Lettre de référence bancaire
            )
    )

[901] => Array
    (
        [0] => Array
            (
                [PROJET_DOC_CLIENT_ID] => 4401
                [PROJET_ID] => 4101
                [DOC_CLIENT_ID] => 901
                [DOC_CLIENT_NUM] => 3
                [DOC_CLIENT_NOM] => Pièce identité
            )
    )

Body:
In this part of your code you have same id for file and textbox change it like this:

<input type="text" id="doctext" name="docfile[]" value="<?php echo ($result[$iDocsx]['doc_name']); ?>" >
       echo "br";
<input type="file" id="docfile" name="docfileUpload[]" value="<?php echo basename($result[$iDocsx]['doc_modele']); ?>" >