问:
Apply in pandas depending on row not working
I have a dataframe of buyer's and assistant's names as follows:

```<code>df = pd.DataFrame([
{ 'buyer': 'Lebron James', 'assistant': 'Lebron James' },
{ 'buyer': 'Jon Snow', 'assistant': 'Arya Stark' },
{ 'buyer': 'Frodo Baggins', 'assistant': 'Sam Gamyi' }
])
</code>```

I would like to split the buyer's names into their names and surnames, so the expected output would be:

first_name  surname
 Lebron       James
 Jon          Snow
 Frodo        Baggings

For so, I have defined a function and tried to use apply():

```<code>def first_name(row):
    return df['buyer'][row].split()[0]

df['first_name'] = df.apply(first_name, axis = 1)
</code>```

However, I get the following error:

```<code>    Traceback (most recent call last):

  File "<ipython-input-35-f3bcdf3bb991>", line 1, in <module>
    df.apply(first_name, axis = 1)

  File "/Users/javier.lopez/anaconda3/lib/python3.7/site-packages/pandas/core/frame.py", line 6487, in apply
    return op.get_result()

  File "/Users/javier.lopez/anaconda3/lib/python3.7/site-packages/pandas/core/apply.py", line 151, in get_result
    return self.apply_standard()

  File "/Users/javier.lopez/anaconda3/lib/python3.7/site-packages/pandas/core/apply.py", line 257, in apply_standard
    self.apply_series_generator()

  File "/Users/javier.lopez/anaconda3/lib/python3.7/site-packages/pandas/core/apply.py", line 286, in apply_series_generator
    results[i] = self.f(v)

  File "<ipython-input-32-410cb25f2482>", line 2, in first_name
    return df['buyer'][row].split()[0]

  File "/Users/javier.lopez/anaconda3/lib/python3.7/site-packages/pandas/core/generic.py", line 5067, in __getattr__
    return object.__getattribute__(self, name)

AttributeError: ("'Series' object has no attribute 'split'", 'occurred at index 0')
</code>```

I had understood that using apply with axis=1 sent the number of the row as argument, so I do not understand why it is not working. If I manually put a row number as argument it works as expected:

```<code>first_name(1)
</code>```

答:
To answer your question, you can use:

```<code>def first_name(x):
    return x.split()[0]
df['first']=df.buyer.apply(first_name)
print(df)
</code>```

```<code>      assistant          buyer   first
0  Lebron James   Lebron James  Lebron
1    Arya Stark       Jon Snow     Jon
2     Sam Gamyi  Frodo Baggins   Frodo
</code>```

However, as @Sandeep pointed, you should also consider inbuilt pandas solutions as series.str.split(), you can directly assign the column using df.assign()

```<code>df=df.assign(first=df.buyer.str.split().str[0])
</code>```

```<code>      assistant          buyer   first
0  Lebron James   Lebron James  Lebron
1    Arya Stark       Jon Snow     Jon
2     Sam Gamyi  Frodo Baggins   Frodo
</code>```

Body:
I have a dataframe of buyer's and assistant's names as follows:

df = pd.DataFrame([
{ 'buyer': 'Lebron James', 'assistant': 'Lebron James' },
{ 'buyer': 'Jon Snow', 'assistant': 'Arya Stark' },
{ 'buyer': 'Frodo Baggins', 'assistant': 'Sam Gamyi' }
])

I would like to split the buyer's names into their names and surnames, so the expected output would be:

first_name  surname
 Lebron       James
 Jon          Snow
 Frodo        Baggings

For so, I have defined a function and tried to use apply():

def first_name(row):
    return df['buyer'][row].split()[0]

df['first_name'] = df.apply(first_name, axis = 1)

However, I get the following error:

    Traceback (most recent call last):

  File "<ipython-input-35-f3bcdf3bb991>", line 1, in <module>
    df.apply(first_name, axis = 1)

  File "/Users/javier.lopez/anaconda3/lib/python3.7/site-packages/pandas/core/frame.py", line 6487, in apply
    return op.get_result()

  File "/Users/javier.lopez/anaconda3/lib/python3.7/site-packages/pandas/core/apply.py", line 151, in get_result
    return self.apply_standard()

  File "/Users/javier.lopez/anaconda3/lib/python3.7/site-packages/pandas/core/apply.py", line 257, in apply_standard
    self.apply_series_generator()

  File "/Users/javier.lopez/anaconda3/lib/python3.7/site-packages/pandas/core/apply.py", line 286, in apply_series_generator
    results[i] = self.f(v)

  File "<ipython-input-32-410cb25f2482>", line 2, in first_name
    return df['buyer'][row].split()[0]

  File "/Users/javier.lopez/anaconda3/lib/python3.7/site-packages/pandas/core/generic.py", line 5067, in __getattr__
    return object.__getattribute__(self, name)

AttributeError: ("'Series' object has no attribute 'split'", 'occurred at index 0')

I had understood that using apply with axis=1 sent the number of the row as argument, so I do not understand why it is not working. If I manually put a row number as argument it works as expected:

first_name(1)

Body:
To answer your question, you can use:

def first_name(x):
    return x.split()[0]
df['first']=df.buyer.apply(first_name)
print(df)

      assistant          buyer   first
0  Lebron James   Lebron James  Lebron
1    Arya Stark       Jon Snow     Jon
2     Sam Gamyi  Frodo Baggins   Frodo

However, as @Sandeep pointed, you should also consider inbuilt pandas solutions as series.str.split(), you can directly assign the column using df.assign()

df=df.assign(first=df.buyer.str.split().str[0])

      assistant          buyer   first
0  Lebron James   Lebron James  Lebron
1    Arya Stark       Jon Snow     Jon
2     Sam Gamyi  Frodo Baggins   Frodo


来源: stackexchange

问:
Removing measurement name from infosql output
I am running a query in a batch process to extract data from InfluxDB. Query output always contains the measurement name as part of each line of output. Is there a way to remove the measurement name from the query result?

This is the command I am using to generate the output file.

```<code>influx -database my_db -format csv -precision rfc3339
-execute "select column1, column2 from measurement1 limit 1" > 2.csv

name, time, column1, column2

measurement1, 2019-05-22T08:30:33Z, data1, data2
</code>```

Expected output

```<code>time, column1, column2

2019-05-22T08:30:33Z, data1, data2
</code>```

答:
InfluxDB does not provide a way to do this. However, with the help of cut on a *nix CLI:

cut -d, -f1 --complement influxdb.csv

This will remove the first column from your CSV file

ContentLicense: CC BY-SA 4.0

Body:
I am running a query in a batch process to extract data from InfluxDB. Query output always contains the measurement name as part of each line of output. Is there a way to remove the measurement name from the query result?

This is the command I am using to generate the output file.

influx -database my_db -format csv -precision rfc3339
-execute "select column1, column2 from measurement1 limit 1" > 2.csv

name, time, column1, column2

measurement1, 2019-05-22T08:30:33Z, data1, data2

Expected output

time, column1, column2

2019-05-22T08:30:33Z, data1, data2


问:
openCV and Threads issue
I'm trying to fit facedetect from openCV on my QT code, all run fine until i decided to create a thread for my openCV code so I can run another things while the face detect is on.

the problem is if i call class->start(); my program breaks in the while loop in the run() but if i call the class.run(); (like a normal function) it runs as usual! what can be wrong?

code:

```<code>faceTracker::faceTracker()
{

qDebug("teste1");
filename = "/Users/marcomartins/Documents/QT/DisplUM/haarcascades/haarcascade_frontalface_alt_tree.xml";

/* load the classifier
    note that I put the file in the same directory with this code */
cascade = ( CvHaarClassifierCascade* )cvLoad( filename, 0, 0, 0 );

/* setup memory buffer; needed by the face detector */
storage = cvCreateMemStorage( 0 );

/* initialize camera */
capture = cvCaptureFromCAM( 0 );

/* always check */
assert( cascade && storage && capture );

/* create a window */
cvNamedWindow( "video DisplUM", 1 );

}

void faceTracker::detectFaces( IplImage *img )
{

/* detect faces */
        faces = cvHaarDetectObjects(
        img,
        cascade,
        storage,
        1.1,
        3,
        0 /*CV_HAAR_DO_CANNY_PRUNNING*/,
        cvSize( 40, 40 ) );

/* for each face found, draw a red box */
for( i = 0 ; i < ( faces ? faces->total : 0 ) ; i++ ) {
    CvRect *r = ( CvRect* )cvGetSeqElem( faces, i );
    cvRectangle( img,
                 cvPoint( r->x, r->y ),
                 cvPoint( r->x + r->width, r->y + r->height ),
                 CV_RGB( 255, 0, 0 ), 1, 8, 0 );
    qDebug("caras: %d", faces->total);
}

/* display video */
cvShowImage( "video", img );
}

void faceTracker::run( )
{
qDebug("teste2");

while( key != 'q' ) {
    /* get a frame */
    frame = cvQueryFrame( capture );
qDebug("teste3");
    /* always check */
    if( !frame ) break;

    /* 'fix' frame */
    cvFlip( frame, frame, 1 );
    frame->origin = 0;

    /* detect faces and display video */
    detectFaces( frame );

    /* quit if user press 'q' */
    key = cvWaitKey( 10 );

}

/* free memory */
cvReleaseCapture( &capture );
cvDestroyWindow( "video" );
cvReleaseHaarClassifierCascade( &cascade );
cvReleaseMemStorage( &storage );
}
</code>```

main code:

```<code>int main(int argc, char *argv[])
{
  faceTracker * ft = new faceTracker();
  ft->start();
}
</code>```

thanks a lot!

答:
The loop will only break if cvQueryFrame() returns a NULL frame or if the user presses q on the keyboard.

Add a debug so you know when the first situation happens:

```<code>frame = cvQueryFrame( capture );
if( !frame )
{
  qDebug("cvQueryFrame failed!");
  break;
}
</code>```

Are you sure cvCaptureFromCAM(0) works ? Depending on the OS I have to pass -1 for it. But the fact is that you'll never know if cvCaptureFromCAM(0)succeeded because you don't check the return, and this might be the problem!

```<code>capture = cvCaptureFromCAM(0);
if (!capture)
{
  qDebug("cvCaptureFromCAM failed!");
  //exit(0); or whatever
}
</code>```

EDIT:

Pay huge attention to this: you are creating a window named "video DisplUM" but you are trying to display the frames on a different window, named "video".

Anyway, it's also better if you change the window creation function to use the appropriate enum:

```<code>cvNamedWindow("video DisplUM", CV_WINDOW_AUTOSIZE);
</code>```

and on faceTracker::run( ) comment detectFaces() for now and add a call to cvShowImage( "video DisplUM", frame );

Always be sure your application works with the minimum requirements before adding fancy stuffs, like face detection. My final suggestion is: write enough code just to capture the images from one thread and display them on a window, and then go from there.

ContentLicense: CC BY-SA 3.0

Title: openCV and Threads issue

Body:
I'm trying to fit facedetect from openCV on my QT code, all run fine until i decided to create a thread for my openCV code so I can run another things while the face detect is on.

the problem is if i call class->start(); my program breaks in the while loop in the run() but if i call the class.run(); (like a normal function) it runs as usual! what can be wrong?

code:

faceTracker::faceTracker()
{

qDebug("teste1");
filename = "/Users/marcomartins/Documents/QT/DisplUM/haarcascades/haarcascade_frontalface_alt_tree.xml";

/* load the classifier
    note that I put the file in the same directory with this code */
cascade = ( CvHaarClassifierCascade* )cvLoad( filename, 0, 0, 0 );

/* setup memory buffer; needed by the face detector */
storage = cvCreateMemStorage( 0 );

/* initialize camera */
capture = cvCaptureFromCAM( 0 );

/* always check */
assert( cascade && storage && capture );

/* create a window */
cvNamedWindow( "video DisplUM", 1 );

}

void faceTracker::detectFaces( IplImage *img )
{

/* detect faces */
        faces = cvHaarDetectObjects(
        img,
        cascade,
        storage,
        1.1,
        3,
        0 /*CV_HAAR_DO_CANNY_PRUNNING*/,
        cvSize( 40, 40 ) );

/* for each face found, draw a red box */
for( i = 0 ; i < ( faces ? faces->total : 0 ) ; i++ ) {
    CvRect *r = ( CvRect* )cvGetSeqElem( faces, i );
    cvRectangle( img,
                 cvPoint( r->x, r->y ),
                 cvPoint( r->x + r->width, r->y + r->height ),
                 CV_RGB( 255, 0, 0 ), 1, 8, 0 );
    qDebug("caras: %d", faces->total);
}

/* display video */
cvShowImage( "video", img );
}

void faceTracker::run( )
{
qDebug("teste2");

while( key != 'q' ) {
    /* get a frame */
    frame = cvQueryFrame( capture );
qDebug("teste3");
    /* always check */
    if( !frame ) break;

    /* 'fix' frame */
    cvFlip( frame, frame, 1 );
    frame->origin = 0;

    /* detect faces and display video */
    detectFaces( frame );

    /* quit if user press 'q' */
    key = cvWaitKey( 10 );

}

/* free memory */
cvReleaseCapture( &capture );
cvDestroyWindow( "video" );
cvReleaseHaarClassifierCascade( &cascade );
cvReleaseMemStorage( &storage );
}

main code:

int main(int argc, char *argv[])
{
  faceTracker * ft = new faceTracker();
  ft->start();
}

thanks a lot!

Body:
The loop will only break if cvQueryFrame() returns a NULL frame or if the user presses q on the keyboard.

Add a debug so you know when the first situation happens:

frame = cvQueryFrame( capture );
if( !frame )
{
  qDebug("cvQueryFrame failed!");
  break;
}

Are you sure cvCaptureFromCAM(0) works ? Depending on the OS I have to pass -1 for it. But the fact is that you'll never know if cvCaptureFromCAM(0)succeeded because you don't check the return, and this might be the problem!

capture = cvCaptureFromCAM(0);
if (!capture)
{
  qDebug("cvCaptureFromCAM failed!");
  //exit(0); or whatever
}

EDIT:

Pay huge attention to this: you are creating a window named "video DisplUM" but you are trying to display the frames on a different window, named "video".

Anyway, it's also better if you change the window creation function to use the appropriate enum:

cvNamedWindow("video DisplUM", CV_WINDOW_AUTOSIZE);

and on faceTracker::run( ) comment detectFaces() for now and add a call to cvShowImage( "video DisplUM", frame );

Always be sure your application works with the minimum requirements before adding fancy stuffs, like face detection. My final suggestion is: write enough code just to capture the images from one thread and display them on a window, and then go from there.


问:
laravel how to display pdf in any page
How can I display a PDF in a Laravel View like I can display a normal image?

The code I am using to implement an image is:

```<code><div class="u-img">
    <img
        src="image/{{ Auth::user()->photo_jpeg }}"
        alt="profile"
    />
</div>
</code>```

What options/HTML-tags can I use to display a PDF?

答:
you could use an object</p>

```<code>  <object data="/path/to/pdf.pdf"  type="application/pdf">

  </object>
</code>```

Title: laravel how to display pdf in any page

Body:
How can I display a PDF in a Laravel View like I can display a normal image?

The code I am using to implement an image is:

    photo_jpeg }}"
        alt="profile"
    />

What options/HTML-tags can I use to display a PDF?

Body:
you could use an object

  <object data="/path/to/pdf.pdf"  type="application/pdf">

  </object>


问:
wanted to merge the updated "Second" to the "MYJsonObj"
I have changed my json using map such as i have deleted some attributes and added some new attributes to MYJsonObj
.Second Now i wanted to merge the updated "Second" to the "MYJsonObj".

 var MYJsonObj={
 "First": [
        {
          "HNo": "1243",
          "Name": "Temp Address",
          "locality": "Temp locality",
           "id":1
        }],
        "Second": [
        {
          "H.No": "1243",
          "Name": "Temp Address",
          "locality": "Temp locality",
           "id":2
        }],
         "third": [
        {
          "H.No": "1243",
          "Name": "Temp Address",
          "locality": "Temp locality",
           "id":3
        }]
        }```

答:
Here you go mate

const originalObj = { a: 1, b: 2 };
const modifiedObj = { a: 4, c: 5 };
const finalObj = {};

Object.assign(finalObj, originalObj, modifiedObj);

console.log(finalObj);```


问:
401 (Unauthorized) request on Angular 7, .netcore application
Iam getting a 401 unauthorized error while authorizing an user to consume an api on .net core and angular 7 application.

My angular service has a function :-

```<code>getUserProfile() {
   var tokenHeader = new HttpHeaders({'Authorization':'Bearer ' + localStorage.getItem('token')});
   console.log(tokenHeader)
   return this.http.get('/api/ApplicationUser/UserProfile', { headers: tokenHeader});
}
</code>```

on tokenHeader I am sending the user jwt token.

My api is

```<code>[HttpGet]
[Authorize]
[Route("UserProfile")]
//'api/userProfile'
public async Task<Object> GetUserProfile()
{
    string userId = User.Claims.First(c => c.Type == "UserID").Value;
    var user = await _userManager.FindByIdAsync(userId);
    return new { user.fullName, user.Email, user.UserName };
}
</code>```

I have tried some answers from other questions but nothing helps.

Any helps appreciated.

答:
Can you share your request from network tab.
Also I recommend to use interceptors for make it global

```<code>@Injectable()
export class TokenInterceptor implements HttpInterceptor {

 private isRefreshing = false;
 private refreshTokenSubject: BehaviorSubject<any> = new BehaviorSubject<any>(null);

 constructor(public authService: AuthService) { }

 intercept(request: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {

   if (this.authService.getJwtToken()) {
     request = this.addToken(request, this.authService.getJwtToken());
   }

   return next.handle(request).pipe(catchError(error => {
     if (error instanceof HttpErrorResponse && error.status === 401) {
       return this.handle401Error(request, next);
     } else {
       return throwError(error);
     }
   }));
 }

 private addToken(request: HttpRequest<any>, token: string) {
   return request.clone({
     setHeaders: {
       'Authorization': `Bearer ${token}`
     }
   });
 }

 private handle401Error(request: HttpRequest<any>, next: HttpHandler) {
   if (!this.isRefreshing) {
     this.isRefreshing = true;
     this.refreshTokenSubject.next(null);

     return this.authService.refreshToken().pipe(
       switchMap((token: any) => {
         this.isRefreshing = false;
         this.refreshTokenSubject.next(token.jwt);
         return next.handle(this.addToken(request, token.jwt));
       }));

   } else {
     return this.refreshTokenSubject.pipe(
       filter(token => token != null),
       take(1),
       switchMap(jwt => {
         return next.handle(this.addToken(request, jwt));
       }));
   }
 }
}
</code>```

Full example https://github.com/bartosz-io/jwt-auth-angular/blob/master/src/app/auth/token.interceptor.ts

Body:
Iam getting a 401 unauthorized error while authorizing an user to consume an api on .net core and angular 7 application.

My angular service has a function :-

getUserProfile() {
   var tokenHeader = new HttpHeaders({'Authorization':'Bearer ' + localStorage.getItem('token')});
   console.log(tokenHeader)
   return this.http.get('/api/ApplicationUser/UserProfile', { headers: tokenHeader});
}

on tokenHeader I am sending the user jwt token.

My api is

[HttpGet]
[Authorize]
[Route("UserProfile")]
//'api/userProfile'
public async Task<Object> GetUserProfile()
{
    string userId = User.Claims.First(c => c.Type == "UserID").Value;
    var user = await _userManager.FindByIdAsync(userId);
    return new { user.fullName, user.Email, user.UserName };
}

I have tried some answers from other questions but nothing helps.

Any helps appreciated.

Body:
Can you share your request from network tab.
Also I recommend to use interceptors for make it global

@Injectable()
export class TokenInterceptor implements HttpInterceptor {

 private isRefreshing = false;
 private refreshTokenSubject: BehaviorSubject<any> = new BehaviorSubject<any>(null);

 constructor(public authService: AuthService) { }

 intercept(request: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {

   if (this.authService.getJwtToken()) {
     request = this.addToken(request, this.authService.getJwtToken());
   }

   return next.handle(request).pipe(catchError(error => {
     if (error instanceof HttpErrorResponse && error.status === 401) {
       return this.handle401Error(request, next);
     } else {
       return throwError(error);
     }
   }));
 }

 private addToken(request: HttpRequest<any>, token: string) {
   return request.clone({
     setHeaders: {
       'Authorization': `Bearer ${token}`
     }
   });
 }

 private handle401Error(request: HttpRequest<any>, next: HttpHandler) {
   if (!this.isRefreshing) {
     this.isRefreshing = true;
     this.refreshTokenSubject.next(null);

     return this.authService.refreshToken().pipe(
       switchMap((token: any) => {
         this.isRefreshing = false;
         this.refreshTokenSubject.next(token.jwt);
         return next.handle(this.addToken(request, token.jwt));
       }));

   } else {
     return this.refreshTokenSubject.pipe(
       filter(token => token != null),
       take(1),
       switchMap(jwt => {
         return next.handle(this.addToken(request, jwt));
       }));
   }
 }
}

Full example https://github.com/bartosz-io/jwt-auth-angular/blob/master/src/app/auth/token.interceptor.ts


问:
ADODB5 (PHP): Dynamically Build Table Columns
I'm wanting to know how to dynamically generate the table columns in adodb5.

Here's my current code:

```<code><?php
$sql = "SELECT id FROM customers";
$query = $db->Execute($sql);
$rows = $query->GetRows();
$fields = $query->fields;

foreach($rows as $row) {
    print_r($row). '<br />';
}
?>
</code>```

The output I recieve is:

```
Array
(
    [id] => 280
)
Array
(
    [id] => 1024
)
Array
(
    [id] => 474
)
Array
(
    [id] => 476
)
Array
(
    [id] => 564
)
Array
(
    [id] => 569
)
Array
(
    [id] => 594
)
Array
(
    [id] => 385
)
Array
(
    [id] => 304
)
Array
(
    [id] => 700
)
Array
(
    [id] => 285
)
Array
(
    [id] => 205
)
Array
(
    [id] => 536
)
Array
(
    [id] => 140
)
```

I'm literally just wanting it to grab all the columns in the query and build the table headers.  So basically, I will have a table that has all the "ID"'s under one columns.  I actually want the columns labeled, so in case I have more than one columns, for example, ID, Name, Date, Comment; it would dynamically know how to make the headers for each columns.  Is this someone that can help me with?

答:
You first need to modify your query that gets the data rows:

```<code>select * from customers
</code>```

or if you only want certain columns:

```<code>select id, name from customers
</code>```

you can then iterate through the rows and see you have an object or an associative array (I forget which) that allows you to lay out your table.  For the headers you already have the $fields so just iterate to form the header:

```<code>foreach ($fields as $name) {
    echo $name;
}
</code>```

Hope this helps.

Body:
I'm wanting to know how to dynamically generate the table columns in adodb5.

Here's my current code:

<?php
$sql = "SELECT id FROM customers";
$query = $db->Execute($sql);
$rows = $query->GetRows();
$fields = $query->fields;

foreach($rows as $row) {
    print_r($row). '
';
}
?>

The output I recieve is:

Array
(
    [id] => 280
)
Array
(
    [id] => 1024
)
Array
(
    [id] => 474
)
Array
(
    [id] => 476
)
Array
(
    [id] => 564
)
Array
(
    [id] => 569
)
Array
(
    [id] => 594
)
Array
(
    [id] => 385
)
Array
(
    [id] => 304
)
Array
(
    [id] => 700
)
Array
(
    [id] => 285
)
Array
(
    [id] => 205
)
Array
(
    [id] => 536
)
Array
(
    [id] => 140
)

I'm literally just wanting it to grab all the columns in the query and build the table headers.  So basically, I will have a table that has all the "ID"'s under one columns.  I actually want the columns labeled, so in case I have more than one columns, for example, ID, Name, Date, Comment; it would dynamically know how to make the headers for each columns.  Is this someone that can help me with?

Body:
You first need to modify your query that gets the data rows:

select * from customers

or if you only want certain columns:

select id, name from customers

you can then iterate through the rows and see you have an object or an associative array (I forget which) that allows you to lay out your table.  For the headers you already have the $fields so just iterate to form the header:

foreach ($fields as $name) {
    echo $name;
}

Hope this helps.


问:
Checkbox value is always empty even if i check it
I made a button to delete files from a database, to delete a file you need to check a checkbox and then click a button. somewhy when i click the button and write the checkbox value to the html it always says false...

ASPX:

<asp:GridView HorizontalAlign="Center" ID="GridView1" runat="server" class="" AutoGenerateColumns="False" BackColor="White" BorderColor="#CCCCCC" BorderStyle="None" BorderWidth="1px" CellPadding="4" ForeColor="Black" GridLines="Horizontal" DataKeyNames="ID">
    <Columns>
        <asp:TemplateField HeaderText="Name">< ItemTemplate >
                            < asp:LinkButton ID = "LinkButton2" runat="server" OnClick="OpenDocument" Text='<%# Eval("File_Name") %>'></asp:LinkButton>
                        </ItemTemplate>
        </asp:TemplateField>
        <asp:TemplateField HeaderText="Delete?">< ItemTemplate >
                            < asp:CheckBox ID = "CheckBox1" runat="server" />
                        </ItemTemplate>
        </asp:TemplateField>
    </Columns>
</asp:GridView>
<asp:Button runat="server" Text="Update" ID="Update" class="button" OnClick="UpdateTable" Style="font-size: 20px" />
```

<p>Code Behind:</p>

<pre class="lang-cs prettyprint-override"><code>protected void UpdateTable(object sender, EventArgs e)
{
    foreach (GridViewRow item in GridView1.Rows)
    {
        CheckBox chk = (CheckBox)item.FindControl("CheckBox1");
        if (chk != null)
        {
            //This is being written and always false
            Response.Write(chk.Checked);
            if (chk.Checked)
            {
               //Delete the item. (never being executed)
            }
        }
    }
}
</code>```

I expected chk.Checked to be True since i've clicked it...

答:
item.Cells[0].Text will not work as the grid column is defined as TemplateField and not as BoundField. So we need to access the control using FindControl and retrieve the text from it.</p>

```<code>protected void UpdateTable(object sender, EventArgs e)
        {
            foreach (GridViewRow item in GridView1.Rows)
            {
                CheckBox chk = (CheckBox)item.FindControl("CheckBox1");
                if (chk != null)
                {
                    //This is being written and always false
                    Response.Write(chk.Checked);
                    if (chk.Checked)
                    {
                        //Delete the item. (never being executed)
                    }
                }
                LinkButton lnk = (LinkButton)item.FindControl("LinkButton2");
                if (lnk != null)
                {
                    Response.Write(lnk.Text);
                }
            }
        }
</code>```

Body:
I made a button to delete files from a database, to delete a file you need to check a checkbox and then click a button. somewhy when i click the button and write the checkbox value to the html it always says false...

ASPX:

<asp:GridView HorizontalAlign="Center" ID="GridView1" runat="server" class="" AutoGenerateColumns="False" BackColor="White" BorderColor="#CCCCCC" BorderStyle="None" BorderWidth="1px" CellPadding="4" ForeColor="Black" GridLines="Horizontal" DataKeyNames="ID">
    <Columns>
        <asp:TemplateField HeaderText="Name">< ItemTemplate >
                            < asp:LinkButton ID = "LinkButton2" runat="server" OnClick="OpenDocument" Text='<%# Eval("File_Name") %>'></asp:LinkButton>
                        </ItemTemplate>
        </asp:TemplateField>
        <asp:TemplateField HeaderText="Delete?">< ItemTemplate >
                            < asp:CheckBox ID = "CheckBox1" runat="server" />
                        </ItemTemplate>
        </asp:TemplateField>
    </Columns>
</asp:GridView>
<asp:Button runat="server" Text="Update" ID="Update" class="button" OnClick="UpdateTable" Style="font-size: 20px" />

Code Behind:

protected void UpdateTable(object sender, EventArgs e)
{
    foreach (GridViewRow item in GridView1.Rows)
    {
        CheckBox chk = (CheckBox)item.FindControl("CheckBox1");
        if (chk != null)
        {
            //This is being written and always false
            Response.Write(chk.Checked);
            if (chk.Checked)
            {
               //Delete the item. (never being executed)
            }
        }
    }
}

I expected chk.Checked to be True since i've clicked it...

Body:
item.Cells[0].Text will not work as the grid column is defined as TemplateField and not as BoundField. So we need to access the control using FindControl and retrieve the text from it.

protected void UpdateTable(object sender, EventArgs e)
        {
            foreach (GridViewRow item in GridView1.Rows)
            {
                CheckBox chk = (CheckBox)item.FindControl("CheckBox1");
                if (chk != null)
                {
                    //This is being written and always false
                    Response.Write(chk.Checked);
                    if (chk.Checked)
                    {
                        //Delete the item. (never being executed)
                    }
                }
                LinkButton lnk = (LinkButton)item.FindControl("LinkButton2");
                if (lnk != null)
                {
                    Response.Write(lnk.Text);
                }
            }
        }


问:
Laravel Validation amount array of fields not work
I have created rule validation as follow :

```<code>$rules = [
  'items.*.qty' => ['required', 'integer', 'min:1'],
  'items.*.ordered_qty' => ['required','numeric','min:1']
]
$this->validate($request, $rules);
</code>```

here i need to validate that each ordered_qty should be greater than qty I have tried the below way but it doesn't work for me

```<code>$rules = [
  'items.*.qty' => ['required', 'integer', 'min:1','max:items.*.ordered_qty'],
  'items.*.ordered_qty' => ['required','numeric','min:1']
]
$this->validate($request, $rules);
</code>```

i tried custom validation also but i could not able to getting the value of other field

```<code>$rules = [
  'items.*.qty' => ['required', 'integer', 'min:1',function ($attribute, $value, $fail) {
            if ($value > ordered_qty) {
                $fail(':attribute qty is invalid!');
            }
        }],
  'items.*.ordered_qty' => ['required','numeric','min:1']
]
</code>```

It validate wrong. How can i do the comparision on array of objects among their attributes

答: You are using the max on qty but max suspect a value while you are trying to validate it with the input of another field. I think you need to use lte, see: https://laravel.com/docs/5.8/validation#rule-lte</p>

Body:
I have created rule validation as follow :

$rules = [
  'items.*.qty' => ['required', 'integer', 'min:1'],
  'items.*.ordered_qty' => ['required','numeric','min:1']
]
$this->validate($request, $rules);

here i need to validate that each ordered_qty should be greater than qty I have tried the below way but it doesn't work for me

$rules = [
  'items.*.qty' => ['required', 'integer', 'min:1','max:items.*.ordered_qty'],
  'items.*.ordered_qty' => ['required','numeric','min:1']
]
$this->validate($request, $rules);

i tried custom validation also but i could not able to getting the value of other field

$rules = [
  'items.*.qty' => ['required', 'integer', 'min:1',function ($attribute, $value, $fail) {
            if ($value > ordered_qty) {
                $fail(':attribute qty is invalid!');
            }
        }],
  'items.*.ordered_qty' => ['required','numeric','min:1']
]

It validate wrong. How can i do the comparision on array of objects among their attributes


问:
SQL Server 2014 bulk insert not working
Please excuse the newbie question, but I have an issue I haven't been able to work out. Trying to do a bulk insert of a .csv into a SQL Server 2014 table, and the last 2 columns are blank.  No matter what I've tried, I cannot get it to pick up any data (keep getting 0 rows affected).

File is below, as is the DDL for the table. Have tried with and without using a format file, as well as numerous versions of BULK INSERT, including using , and t as field terminators and  and r as row terminators. Any and all help is very much appreciated, this has got me totally stuck.

Have tried using just the format file, and also spelling everything out (numerous variations).

Thanks in advance!!

Table DDL:

```<code>SET ANSI_NULLS ON
GO

SET QUOTED_IDENTIFIER ON
GO

SET ANSI_PADDING ON
GO

CREATE TABLE [dbo].[Expireds_New]
(
    [Address] [nvarchar](50) NOT NULL,
    [City] [nvarchar](50) NULL,
    [State] [text] NULL,
    [Zip] [nvarchar](15) NOT NULL,
    [MLS#] [nchar](10) NULL,
    [Status] [varchar](20) NULL,
    [OMD] [date] NULL,
    [Followup_Date] [date] NULL,
    [First_Owner] [varchar](50) NULL,
    [Second_Owner] [varchar](50) NULL,
    [Phone1] [nvarchar](15) NULL,
    [Phone2] [nvarchar](15) NULL,
    [Phone3] [nvarchar](15) NULL,
    [Email] [varchar](50) NULL,
    [Remarks] [nvarchar](max) NULL
) ON [PRIMARY] TEXTIMAGE_ON [PRIMARY]
GO

SET ANSI_PADDING OFF
GO
</code>```

FMT file:

```<code>12
15
1       SQLCHAR             0       100     "\t"     1     Address                        SQL_Latin1_General_CP1_CI_AS
2       SQLCHAR             0       100     "\t"     2     City                           SQL_Latin1_General_CP1_CI_AS
3       SQLCHAR             0       0       "\t"     3     State                          SQL_Latin1_General_CP1_CI_AS
4       SQLCHAR             0       30      "\t"     4     Zip                            SQL_Latin1_General_CP1_CI_AS
5       SQLCHAR             0       20      "\t"     5     MLS#                           SQL_Latin1_General_CP1_CI_AS
6       SQLCHAR             0       20      "\t"     6     Status                         SQL_Latin1_General_CP1_CI_AS
7       SQLCHAR             0       11      "\t"     7     OMD                            ""
8       SQLCHAR             0       11      "\t"     8     Followup_Date                  ""
9       SQLCHAR             0       50      "\t"     9     First_Owner                    SQL_Latin1_General_CP1_CI_AS
10      SQLCHAR             0       50      "\t"     10    Second_Owner                   SQL_Latin1_General_CP1_CI_AS
11      SQLCHAR             0       30      "\t"     11    Phone1                         SQL_Latin1_General_CP1_CI_AS
12      SQLCHAR             0       30      "\t"     12    Phone2                         SQL_Latin1_General_CP1_CI_AS
13      SQLCHAR             0       30      "\t"     13    Phone3                         SQL_Latin1_General_CP1_CI_AS
14      SQLCHAR             0       50      "\t"     14    Email                          SQL_Latin1_General_CP1_CI_AS
15      SQLCHAR             0       0       "\r\n"   15    Remarks                        SQL_Latin1_General_CP1_CI_AS
</code>```

File format (first 3 lines of csv):

```<code>Address1    City    State   Postal Code Gender  Extension   Fax Web Name    Company Phone Number 1  Phone Number 2  Phone Number 3  Email   Address2
139 27th St Del Mar CA  92014   150045904   Expired 11/2/2015       139 27th Street Llc     16195551212 16195551212
1021 Costa Pacifica Way  2  Oceanside   CA  92054   150056483   Expired 11/1/2015       2000 Family Trust Nack      16195551212 16195551212 16195551212
</code>```

Bulk Insert with Format File and parameters (I have used numerous variations of this statement, both with and without the format file):

```<code>SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

ALTER PROCEDURE [dbo].[sp_load_expireds_new]
AS
BEGIN
    BULK INSERT Prospects.dbo.Expireds_New
    FROM 'C:\prospects\expireds_new_contacts.csv'
    WITH
        (KEEPNULLS,
         FORMATFILE = 'C:\Commands\expireds.FMT',
         FIRSTROW = 2,
         FIELDTERMINATOR = '\t',
         ROWTERMINATOR = '\r\n'
         --ERRORFILE ='C:\Commands\err.txt'
        )
END
</code>```

Bulk Insert using format file only:

```<code>SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

ALTER PROCEDURE [dbo].[sp_load_expireds_new]
AS
BEGIN
    BULK INSERT Prospects.dbo.Expireds_New
    FROM 'C:\prospects\expireds_new_contacts.csv'
    WITH
        (FORMATFILE = 'C:\Commands\expireds.FMT'
         --ERRORFILE ='C:\Commands\err.txt'
        )
END
</code>```

No errors are generated, both of these statements complete successfully.  However, when I execute either procedure, no data is imported. No errors are generated to the error file, or to SQL Server Management Studio.

Thank you for any and all assistance!

答: In order to specify the newline character, instead of using ROWTERMINATOR = '\r\n', try using ROWTERMINATOR = '0x0A'

Title: SQL Server 2014 bulk insert not working

Body:
Please excuse the newbie question, but I have an issue I haven't been able to work out. Trying to do a bulk insert of a .csv into a SQL Server 2014 table, and the last 2 columns are blank.  No matter what I've tried, I cannot get it to pick up any data (keep getting 0 rows affected).

File is below, as is the DDL for the table. Have tried with and without using a format file, as well as numerous versions of BULK INSERT, including using , and t as field terminators and  and r as row terminators. Any and all help is very much appreciated, this has got me totally stuck.

Have tried using just the format file, and also spelling everything out (numerous variations).

Thanks in advance!!

Table DDL:

SET ANSI_NULLS ON
GO

SET QUOTED_IDENTIFIER ON
GO

SET ANSI_PADDING ON
GO

CREATE TABLE [dbo].[Expireds_New]
(
    [Address] [nvarchar](50) NOT NULL,
    [City] [nvarchar](50) NULL,
    [State] [text] NULL,
    [Zip] [nvarchar](15) NOT NULL,
    [MLS#] [nchar](10) NULL,
    [Status] [varchar](20) NULL,
    [OMD] [date] NULL,
    [Followup_Date] [date] NULL,
    [First_Owner] [varchar](50) NULL,
    [Second_Owner] [varchar](50) NULL,
    [Phone1] [nvarchar](15) NULL,
    [Phone2] [nvarchar](15) NULL,
    [Phone3] [nvarchar](15) NULL,
    [Email] [varchar](50) NULL,
    [Remarks] [nvarchar](max) NULL
) ON [PRIMARY] TEXTIMAGE_ON [PRIMARY]
GO

SET ANSI_PADDING OFF
GO

FMT file:

12
15
1       SQLCHAR             0       100     "\t"     1     Address                        SQL_Latin1_General_CP1_CI_AS
2       SQLCHAR             0       100     "\t"     2     City                           SQL_Latin1_General_CP1_CI_AS
3       SQLCHAR             0       0       "\t"     3     State                          SQL_Latin1_General_CP1_CI_AS
4       SQLCHAR             0       30      "\t"     4     Zip                            SQL_Latin1_General_CP1_CI_AS
5       SQLCHAR             0       20      "\t"     5     MLS#                           SQL_Latin1_General_CP1_CI_AS
6       SQLCHAR             0       20      "\t"     6     Status                         SQL_Latin1_General_CP1_CI_AS
7       SQLCHAR             0       11      "\t"     7     OMD                            ""
8       SQLCHAR             0       11      "\t"     8     Followup_Date                  ""
9       SQLCHAR             0       50      "\t"     9     First_Owner                    SQL_Latin1_General_CP1_CI_AS
10      SQLCHAR             0       50      "\t"     10    Second_Owner                   SQL_Latin1_General_CP1_CI_AS
11      SQLCHAR             0       30      "\t"     11    Phone1                         SQL_Latin1_General_CP1_CI_AS
12      SQLCHAR             0       30      "\t"     12    Phone2                         SQL_Latin1_General_CP1_CI_AS
13      SQLCHAR             0       30      "\t"     13    Phone3                         SQL_Latin1_General_CP1_CI_AS
14      SQLCHAR             0       50      "\t"     14    Email                          SQL_Latin1_General_CP1_CI_AS
15      SQLCHAR             0       0       "\r\n"   15    Remarks                        SQL_Latin1_General_CP1_CI_AS

File format (first 3 lines of csv):

Address1    City    State   Postal Code Gender  Extension   Fax Web Name    Company Phone Number 1  Phone Number 2  Phone Number 3  Email   Address2
139 27th St Del Mar CA  92014   150045904   Expired 11/2/2015       139 27th Street Llc     16195551212 16195551212
1021 Costa Pacifica Way  2  Oceanside   CA  92054   150056483   Expired 11/1/2015       2000 Family Trust Nack      16195551212 16195551212 16195551212

Bulk Insert with Format File and parameters (I have used numerous variations of this statement, both with and without the format file):

SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

ALTER PROCEDURE [dbo].[sp_load_expireds_new]
AS
BEGIN
    BULK INSERT Prospects.dbo.Expireds_New
    FROM 'C:\prospects\expireds_new_contacts.csv'
    WITH
        (KEEPNULLS,
         FORMATFILE = 'C:\Commands\expireds.FMT',
         FIRSTROW = 2,
         FIELDTERMINATOR = '\t',
         ROWTERMINATOR = '\r\n'
         --ERRORFILE ='C:\Commands\err.txt'
        )
END

Bulk Insert using format file only:

SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

ALTER PROCEDURE [dbo].[sp_load_expireds_new]
AS
BEGIN
    BULK INSERT Prospects.dbo.Expireds_New
    FROM 'C:\prospects\expireds_new_contacts.csv'
    WITH
        (FORMATFILE = 'C:\Commands\expireds.FMT'
         --ERRORFILE ='C:\Commands\err.txt'
        )
END

No errors are generated, both of these statements complete successfully.  However, when I execute either procedure, no data is imported. No errors are generated to the error file, or to SQL Server Management Studio.

Thank you for any and all assistance!


问:
Each VBA sub works perfectly separately, but calling subs from another function doesn't work
I wrote 2 subs to automate a daily task.

First sub MatriksFlowUpdate calls 2 other subs RightClick and SingleClick to simulate a right click and then a left click on a certain part of the screen.  This is done in order to prompt another program to create an Excel file and save it under C:.  This sub works correctly on its own (i.e. it simulates a right click and a left click at the desired locations on the screen, prompting another program to produce an Excel sheet)

Second sub CloseInstance finds the Excel sheet created above, and closes it.  This sub also works correctly on its own.

However, when I try to call these 2 subs one after the other in another sub MainSequence, I get an error saying the Excel that should be found and closed by the second sub can't be found. So I get an error on the CloseInstance sub at the location below

```<code>    Set xlApp =GetObject("C:\MATRIKS\USER\REPORTS\EXCEL\Temp.xls").Application
</code>```

I've tried many things to fix this, but I feel like I am going around in circles for the past few days.  Any help would be much much appreciated.

P.S. My first time posting a q on stackoverflow so please bear with me with the formatting.

```<code>    Public Declare PtrSafe Function SetCursorPos Lib "user32" (ByVal x As Long, ByVal y As Long) As Long
    Public Declare PtrSafe Sub mouse_event Lib "user32" (ByVal dwFlags As Long, ByVal dx As Long, ByVal dy As Long, ByVal cButtons As Long, ByVal dwExtraInfo As Long)
    Public Const MOUSEEVENTF_LEFTDOWN = &H2
    Public Const MOUSEEVENTF_LEFTUP = &H4
    Public Const MOUSEEVENTF_RIGHTDOWN As Long = &H8
    Public Const MOUSEEVENTF_RIGHTUP As Long = &H10
    Public Declare PtrSafe Sub Sleep Lib "kernel32" (ByVal dwMilliseconds As LongPtr)

    Sub MainSequence()
        'This sub pieces together MatriksFlowUpdate and CloseInstance
        Call MatriksFlowUpdate
        Sleep 2000
        Call CloseInstance
        End Sub

    Sub MatriksFlowUpdate()
        'Prompts 3rd party software (Matriks) to produce Excel with latest flow data
        Call RightClick
        Call SingleClick
        End Sub

    Private Sub RightClick()
    'Simulates a mouse right click at desired screen coordinates
    Sleep 1000
    SetCursorPos 1750, 750 'x and y position
    mouse_event MOUSEEVENTF_RIGHTDOWN, 0, 0, 0, 0
    mouse_event MOUSEEVENTF_RIGHTUP, 0, 0, 0, 0
    End Sub

    Private Sub SingleClick()
    'Simulates a mouse left click at desired screen coordinates
    Sleep 1000
    SetCursorPos 1750, 650 'x and y position
    mouse_event MOUSEEVENTF_LEFTDOWN, 0, 0, 0, 0
    mouse_event MOUSEEVENTF_LEFTUP, 0, 0, 0, 0
    End Sub

    Sub CloseInstance()
    'Finds the instance of Excel where Matriks exported its excel and closes that instance of Excel
    Dim xlApp As Excel.Application
    Dim WB As Workbook
    Set xlApp =GetObject("C:\MATRIKS\USER\REPORTS\EXCEL\Temp.xls").Application
    Set WB = xlApp.Workbooks("Temp.xls")
    WB.Close
    End Sub
</code>```

答:
Thanks to all your help, I was able to solve the problem as below:

as per DisplayName's suggestion, this was an Excel freeze issue when Sleep function was called. When Sleep function was called, Excel froze and blocked the 3rd party program from creating its own Excel instance.

I built on this idea and created a new function called WasteTime and added it to my code.  I am using this function instead of Sleep in the code, thereby bypassing the Excel freeze problem.

Full code below now.

Please note that WasteTime sub was found on myonlinetraininghub.com

```<code>Public Declare PtrSafe Function SetCursorPos Lib "user32" (ByVal x As Long, ByVal y As Long) As Long
Public Declare PtrSafe Sub mouse_event Lib "user32" (ByVal dwFlags As Long, ByVal dx As Long, ByVal dy As Long, ByVal cButtons As Long, ByVal dwExtraInfo As Long)
Public Const MOUSEEVENTF_LEFTDOWN = &H2
Public Const MOUSEEVENTF_LEFTUP = &H4
Public Const MOUSEEVENTF_RIGHTDOWN As Long = &H8
Public Const MOUSEEVENTF_RIGHTUP As Long = &H10
Public Declare PtrSafe Sub Sleep Lib "kernel32" (ByVal dwMilliseconds As LongPtr)

Sub MainSequence()
    'This sub pieces together MatriksFlowUpdate and CloseInstance
    Call MatriksFlowUpdate
    WasteTime(2) #This is the code change, it was Sleep 2000 before
    Call CloseInstance
    End Sub

Sub MatriksFlowUpdate()
    'Prompts 3rd party software (Matriks) to produce Excel with latest flow data
    Call RightClick
    Call SingleClick
    End Sub

Private Sub RightClick()
'Simulates a mouse right click at desired screen coordinates
Sleep 1000
SetCursorPos 1750, 750 'x and y position
mouse_event MOUSEEVENTF_RIGHTDOWN, 0, 0, 0, 0
mouse_event MOUSEEVENTF_RIGHTUP, 0, 0, 0, 0
End Sub

Private Sub SingleClick()
'Simulates a mouse left click at desired screen coordinates
Sleep 1000
SetCursorPos 1750, 650 'x and y position
mouse_event MOUSEEVENTF_LEFTDOWN, 0, 0, 0, 0
mouse_event MOUSEEVENTF_LEFTUP, 0, 0, 0, 0
End Sub

Sub CloseInstance()
'Finds the instance of Excel where Matriks exported its excel and closes that instance of Excel
Dim xlApp As Excel.Application
Dim WB As Workbook
Set xlApp =GetObject("C:\MATRIKS\USER\REPORTS\EXCEL\Temp.xls").Application
Set WB = xlApp.Workbooks("Temp.xls")
WB.Close
End Sub

Sub WasteTime(Finish As Long) #This is what I use instead of Sleep
Dim NowTick As Long
Dim EndTick As Long

EndTick = GetTickCount + (Finish * 1000)

Do
    NowTick = GetTickCount
    DoEvents
Loop Until NowTick >= EndTick
</code>```

End Sub

Body:
I wrote 2 subs to automate a daily task.

First sub MatriksFlowUpdate calls 2 other subs RightClick and SingleClick to simulate a right click and then a left click on a certain part of the screen.  This is done in order to prompt another program to create an Excel file and save it under C:.  This sub works correctly on its own (i.e. it simulates a right click and a left click at the desired locations on the screen, prompting another program to produce an Excel sheet)

Second sub CloseInstance finds the Excel sheet created above, and closes it.  This sub also works correctly on its own.

However, when I try to call these 2 subs one after the other in another sub MainSequence, I get an error saying the Excel that should be found and closed by the second sub can't be found. So I get an error on the CloseInstance sub at the location below

    Set xlApp =GetObject("C:\MATRIKS\USER\REPORTS\EXCEL\Temp.xls").Application

I've tried many things to fix this, but I feel like I am going around in circles for the past few days.  Any help would be much much appreciated.

P.S. My first time posting a q on stackoverflow so please bear with me with the formatting.

    Public Declare PtrSafe Function SetCursorPos Lib "user32" (ByVal x As Long, ByVal y As Long) As Long
    Public Declare PtrSafe Sub mouse_event Lib "user32" (ByVal dwFlags As Long, ByVal dx As Long, ByVal dy As Long, ByVal cButtons As Long, ByVal dwExtraInfo As Long)
    Public Const MOUSEEVENTF_LEFTDOWN = &H2
    Public Const MOUSEEVENTF_LEFTUP = &H4
    Public Const MOUSEEVENTF_RIGHTDOWN As Long = &H8
    Public Const MOUSEEVENTF_RIGHTUP As Long = &H10
    Public Declare PtrSafe Sub Sleep Lib "kernel32" (ByVal dwMilliseconds As LongPtr)

    Sub MainSequence()
        'This sub pieces together MatriksFlowUpdate and CloseInstance
        Call MatriksFlowUpdate
        Sleep 2000
        Call CloseInstance
        End Sub

    Sub MatriksFlowUpdate()
        'Prompts 3rd party software (Matriks) to produce Excel with latest flow data
        Call RightClick
        Call SingleClick
        End Sub

    Private Sub RightClick()
    'Simulates a mouse right click at desired screen coordinates
    Sleep 1000
    SetCursorPos 1750, 750 'x and y position
    mouse_event MOUSEEVENTF_RIGHTDOWN, 0, 0, 0, 0
    mouse_event MOUSEEVENTF_RIGHTUP, 0, 0, 0, 0
    End Sub

    Private Sub SingleClick()
    'Simulates a mouse left click at desired screen coordinates
    Sleep 1000
    SetCursorPos 1750, 650 'x and y position
    mouse_event MOUSEEVENTF_LEFTDOWN, 0, 0, 0, 0
    mouse_event MOUSEEVENTF_LEFTUP, 0, 0, 0, 0
    End Sub

    Sub CloseInstance()
    'Finds the instance of Excel where Matriks exported its excel and closes that instance of Excel
    Dim xlApp As Excel.Application
    Dim WB As Workbook
    Set xlApp =GetObject("C:\MATRIKS\USER\REPORTS\EXCEL\Temp.xls").Application
    Set WB = xlApp.Workbooks("Temp.xls")
    WB.Close
    End Sub

Body:
Thanks to all your help, I was able to solve the problem as below:

as per DisplayName's suggestion, this was an Excel freeze issue when Sleep function was called. When Sleep function was called, Excel froze and blocked the 3rd party program from creating its own Excel instance.

I built on this idea and created a new function called WasteTime and added it to my code.  I am using this function instead of Sleep in the code, thereby bypassing the Excel freeze problem.

Full code below now.

Please note that WasteTime sub was found on myonlinetraininghub.com

Public Declare PtrSafe Function SetCursorPos Lib "user32" (ByVal x As Long, ByVal y As Long) As Long
Public Declare PtrSafe Sub mouse_event Lib "user32" (ByVal dwFlags As Long, ByVal dx As Long, ByVal dy As Long, ByVal cButtons As Long, ByVal dwExtraInfo As Long)
Public Const MOUSEEVENTF_LEFTDOWN = &H2
Public Const MOUSEEVENTF_LEFTUP = &H4
Public Const MOUSEEVENTF_RIGHTDOWN As Long = &H8
Public Const MOUSEEVENTF_RIGHTUP As Long = &H10
Public Declare PtrSafe Sub Sleep Lib "kernel32" (ByVal dwMilliseconds As LongPtr)

Sub MainSequence()
    'This sub pieces together MatriksFlowUpdate and CloseInstance
    Call MatriksFlowUpdate
    WasteTime(2) #This is the code change, it was Sleep 2000 before
    Call CloseInstance
    End Sub

Sub MatriksFlowUpdate()
    'Prompts 3rd party software (Matriks) to produce Excel with latest flow data
    Call RightClick
    Call SingleClick
    End Sub

Private Sub RightClick()
'Simulates a mouse right click at desired screen coordinates
Sleep 1000
SetCursorPos 1750, 750 'x and y position
mouse_event MOUSEEVENTF_RIGHTDOWN, 0, 0, 0, 0
mouse_event MOUSEEVENTF_RIGHTUP, 0, 0, 0, 0
End Sub

Private Sub SingleClick()
'Simulates a mouse left click at desired screen coordinates
Sleep 1000
SetCursorPos 1750, 650 'x and y position
mouse_event MOUSEEVENTF_LEFTDOWN, 0, 0, 0, 0
mouse_event MOUSEEVENTF_LEFTUP, 0, 0, 0, 0
End Sub

Sub CloseInstance()
'Finds the instance of Excel where Matriks exported its excel and closes that instance of Excel
Dim xlApp As Excel.Application
Dim WB As Workbook
Set xlApp =GetObject("C:\MATRIKS\USER\REPORTS\EXCEL\Temp.xls").Application
Set WB = xlApp.Workbooks("Temp.xls")
WB.Close
End Sub

Sub WasteTime(Finish As Long) #This is what I use instead of Sleep
Dim NowTick As Long
Dim EndTick As Long

EndTick = GetTickCount + (Finish * 1000)

Do
    NowTick = GetTickCount
    DoEvents
Loop Until NowTick >= EndTick

End Sub


答:
Your code should be like this

```<code>const httpOptions = {
  headers: new HttpHeaders({
    'Authorization': `Bearer ${localStorage.getItem('token')}`
  })
};

return this.http.get('/api/ApplicationUser/UserProfile', httpOptions);
</code>```

Also make sure you have this line in your controller

```<code>[Authorize(AuthenticationSchemes = "Bearer")]
</code>```

Title: 401 (Unauthorized) request on Angular 7, .netcore application

Body:
Your code should be like this

const httpOptions = {
  headers: new HttpHeaders({
    'Authorization': `Bearer ${localStorage.getItem('token')}`
  })
};

return this.http.get('/api/ApplicationUser/UserProfile', httpOptions);

Also make sure you have this line in your controller

[Authorize(AuthenticationSchemes = "Bearer")]


问:
How to validate if an element is enabled only after 60 seconds
I have a link in my application which gets enabled after 60 seconds. I have to verify , that the link only gets enabled after 60 seconds not before that.
Have tried below ways:

I have tried element to be clickable()  with fluent wait/webdriver wait/thread.sleep and all are returning that element is enabled where as it's actually disabled till 60 seconds.

i have tried getAttribute("disabled")also , it also returns false.

The only difference i can see in the html is the class attribute. When it is disabled , class attribute value has additional text (disabled) added to it.

答:
Try with this (and tweek as needed):

```<code>long ts1 = System.currentTimeMillis()/1000;
new WebDriverWait(driver, 60).until(ExpectedConditions.attributeToBe(element, "disabled", null);
long ts2 = System.currentTimeMillis()/1000;
Assert.assertTrue((ts2-ts1)>=60);
</code>```

If the element becomes not disabled before 60 seconds is up, assert will fail.

Body:
Try with this (and tweek as needed):

long ts1 = System.currentTimeMillis()/1000;
new WebDriverWait(driver, 60).until(ExpectedConditions.attributeToBe(element, "disabled", null);
long ts2 = System.currentTimeMillis()/1000;
Assert.assertTrue((ts2-ts1)>=60);

If the element becomes not disabled before 60 seconds is up, assert will fail.


问:
Download and run sub install - Inno Download Plugin progress bar does not move during download
Ok, so I created the following iss but I the progress bar does not move.  I want the setup file to download and run the other setup program.  Everything works fine except the progress bar does not move.

#define MyAppName "My Program Setup Downloader"
#define MySetupAppName "My Program Setup.exe"
#define MySetupUrlFolder "https://www.example.com/folder/"
#pragma include __INCLUDE__ + ";" + "c:\Program Files (x86)\Inno Download Plugin\"

[Setup]

AppName={#MyAppName}
AppVerName={#MyAppName}
DisableReadyPage=yes
DisableFinishedPage=yes
CreateAppDir=no
Uninstallable=no

#include <idp.iss>

[Code]

var FileName: string;

procedure InitializeWizard;
var DownloadUrl: String;
begin
  FileName := ExpandConstant('{tmp}\{#MySetupAppName}');
  DownloadUrl := '{#MySetupUrlFolder}{#MySetupAppName}';
  idpAddFile(DownloadUrl, FileName);
  idpDownloadAfter(wpSelectDir);
end;

function NextButtonClick(CurPageID: Integer) : boolean;
var ResultCode: Integer;
begin
  if CurPageID = IDPForm.Page.ID then
  begin
    Result := Exec(FileName, '', '', SW_SHOW, ewWaitUntilTerminated, ResultCode);
    if not Result then MsgBox('Error Running Downloaded Setup File', mbError, MB_OK);
    Result := True;
  end
    else Result := True;
end;
```

<p>Any Ideas? Everything else works fine.</p>

<hr>

<p>Edit: I have a workaround that will show the details section.  This might be more appropriate anyways.  Still not sure why the Total progress is not updating.</p>

<pre class="lang-pascal prettyprint-override"><code>procedure CurPageChanged(CurPageID: Integer);
begin
  if CurPageID = IDPForm.Page.ID then
  begin
    idpShowDetails(True);
    IDPForm.TotalProgressBar.Visible := false;
    IDPForm.TotalProgressLabel.Visible := false;
    IDPForm.TotalDownloaded.Visible := false;
    IDPForm.CurrentFileLabel.Caption := 'Downloading...';
    IDPForm.DetailsButton.Visible := False;
    WizardForm.NextButton.Visible := False;
    WizardForm.PageNameLabel.Caption := 'Downloading Setup File';
    WizardForm.PageDescriptionLabel.Caption := 'Please wait while the Setup file is being downloaded.';
  end;
end;
</code>```

答:
I indeed get the same behavior. I do not understand why.

But as you have a single file, you can replace the total progress bar with file progress bar:

procedure CurPageChanged(CurPageID: Integer);
begin
  if CurPageID = IDPForm.Page.ID then
  begin
    IDPForm.TotalProgressBar.Visible := False;
    IDPForm.FileProgressBar.Top := IDPForm.TotalProgressBar.Top;
    IDPForm.FileProgressBar.Visible := True;
    IDPForm.DetailsButton.Visible := False;

    IDPForm.DetailsVisible := True;
  end;
end;
```

Body:
Ok, so I created the following iss but I the progress bar does not move.  I want the setup file to download and run the other setup program.  Everything works fine except the progress bar does not move.

#define MyAppName "My Program Setup Downloader"
#define MySetupAppName "My Program Setup.exe"
#define MySetupUrlFolder "https://www.example.com/folder/"
#pragma include __INCLUDE__ + ";" + "c:\Program Files (x86)\Inno Download Plugin\"

[Setup]

AppName={#MyAppName}
AppVerName={#MyAppName}
DisableReadyPage=yes
DisableFinishedPage=yes
CreateAppDir=no
Uninstallable=no

#include <idp.iss>

[Code]

var FileName: string;

procedure InitializeWizard;
var DownloadUrl: String;
begin
  FileName := ExpandConstant('{tmp}\{#MySetupAppName}');
  DownloadUrl := '{#MySetupUrlFolder}{#MySetupAppName}';
  idpAddFile(DownloadUrl, FileName);
  idpDownloadAfter(wpSelectDir);
end;

function NextButtonClick(CurPageID: Integer) : boolean;
var ResultCode: Integer;
begin
  if CurPageID = IDPForm.Page.ID then
  begin
    Result := Exec(FileName, '', '', SW_SHOW, ewWaitUntilTerminated, ResultCode);
    if not Result then MsgBox('Error Running Downloaded Setup File', mbError, MB_OK);
    Result := True;
  end
    else Result := True;
end;

Any Ideas? Everything else works fine.

Edit: I have a workaround that will show the details section.  This might be more appropriate anyways.  Still not sure why the Total progress is not updating.

procedure CurPageChanged(CurPageID: Integer);
begin
  if CurPageID = IDPForm.Page.ID then
  begin
    idpShowDetails(True);
    IDPForm.TotalProgressBar.Visible := false;
    IDPForm.TotalProgressLabel.Visible := false;
    IDPForm.TotalDownloaded.Visible := false;
    IDPForm.CurrentFileLabel.Caption := 'Downloading...';
    IDPForm.DetailsButton.Visible := False;
    WizardForm.NextButton.Visible := False;
    WizardForm.PageNameLabel.Caption := 'Downloading Setup File';
    WizardForm.PageDescriptionLabel.Caption := 'Please wait while the Setup file is being downloaded.';
  end;
end;


问:
Create multiple files with Powershell?
From this answer I can create multiple files a.txt, b.txt, ... , z.txt. in Bash with:

```<code>touch {a..z}.txt
</code>```

Or 152 with:

```<code>touch {{a..z},{A..Z},{0..99}}.txt
</code>```

How can I do this in Powershell?
I know New-Item a.txt, but If I want multiple files as above?

For curiosity, what are the equivalent commands in Command Prompt (cmd.exe)?

答:
For Powershell:

```<code>1..5 | foreach { new-item -path c:\temp\$_.txt }
</code>```

The foreach loop will run for each number in 1 to 5, and generate a file in the desired path with the name of that number passed to the command (represented by the $_)

You could also write it as:

```<code>%{1..5} | new-item c:\temp\$_.txt
</code>```

For cmd:

```<code>for /L %v in (1,1,5) do type nul > %v.txt
</code>```

More information here: cmd/batch looping

Title: Create multiple files with Powershell?

Body:
From this answer I can create multiple files a.txt, b.txt, ... , z.txt. in Bash with:

touch {a..z}.txt

Or 152 with:

touch {{a..z},{A..Z},{0..99}}.txt

How can I do this in Powershell?
I know New-Item a.txt, but If I want multiple files as above?

For curiosity, what are the equivalent commands in Command Prompt (cmd.exe)?

Body:
For Powershell:

1..5 | foreach { new-item -path c:\temp\$_.txt }

The foreach loop will run for each number in 1 to 5, and generate a file in the desired path with the name of that number passed to the command (represented by the $_)

You could also write it as:

%{1..5} | new-item c:\temp\$_.txt

For cmd:

for /L %v in (1,1,5) do type nul > %v.txt

More information here: cmd/batch looping


问:
Calling stored procedure with parameter to return list
I have a stored procedure with parameters, which i want to submit the parameters in a view which returns a index of the list. How do i go about this in my controller

```<code>CREATE PROCEDURE [dbo].[spFlugReport]
(
   @AccNo INTEGER,
   @DateFrom DATE,
   @DateTo DATE
)
AS
BEGIN
    SELECT *
    FROM [dbo].[KIRData]
    WHERE AccNo = @AccNo
      AND StartDate >= @DateFrom
      AND EndDate <= @DateTo
      AND Prod = 'Air'
END
</code>```

C# code:

```<code>public ActionResult Report()
{
    using(DataModel db = new DataModel())
    {
        SqlParameter[] param = new SqlParameter[] {
            new SqlParameter("@AccNo ,"),
            new SqlParameter("@DateFrom ,"),
            new SqlParameter("@DateTo ,")
        };

    }
}
</code>```

答:
I believe you're looking for something like this. If not, could you provide more detail.

```<code>DataTable database = new DataTable();
string dbString = ConfigurationManager.ConnectionStrings["YourConnection"].ConnectionString;
using (SqlConnection con = new SqlConnection(dbString))
using (SqlCommand cmd = new SqlCommand("dbo.spFlugReport", con))
{
    using(DataModel db = new DataModel())
    {
        cmd.CommandType = CommandType.StoredProcedure;

        cmd.Parameters.AddWithValue("@AccNo", AccNo);
        cmd.Parameters.AddWithValue("@DateFrom", DateFrom);
        cmd.Parameters.AddWithValue("@DateTo", DateTo);

        con.Open();
        cmd.ExecuteNonQuery();
    }
}
</code>```

This link is how you created a ConnectionString  for YourConnection: https://learn.microsoft.com/en-us/aspnet/mvc/overview/getting-started/introduction/creating-a-connection-string

Body:
I have a stored procedure with parameters, which i want to submit the parameters in a view which returns a index of the list. How do i go about this in my controller

CREATE PROCEDURE [dbo].[spFlugReport]
(
   @AccNo INTEGER,
   @DateFrom DATE,
   @DateTo DATE
)
AS
BEGIN
    SELECT *
    FROM [dbo].[KIRData]
    WHERE AccNo = @AccNo
      AND StartDate >= @DateFrom
      AND EndDate <= @DateTo
      AND Prod = 'Air'
END

C# code:

public ActionResult Report()
{
    using(DataModel db = new DataModel())
    {
        SqlParameter[] param = new SqlParameter[] {
            new SqlParameter("@AccNo ,"),
            new SqlParameter("@DateFrom ,"),
            new SqlParameter("@DateTo ,")
        };

    }
}

Body:
I believe you're looking for something like this. If not, could you provide more detail.

DataTable database = new DataTable();
string dbString = ConfigurationManager.ConnectionStrings["YourConnection"].ConnectionString;
using (SqlConnection con = new SqlConnection(dbString))
using (SqlCommand cmd = new SqlCommand("dbo.spFlugReport", con))
{
    using(DataModel db = new DataModel())
    {
        cmd.CommandType = CommandType.StoredProcedure;

        cmd.Parameters.AddWithValue("@AccNo", AccNo);
        cmd.Parameters.AddWithValue("@DateFrom", DateFrom);
        cmd.Parameters.AddWithValue("@DateTo", DateTo);

        con.Open();
        cmd.ExecuteNonQuery();
    }
}

This link is how you created a ConnectionString  for YourConnection: https://learn.microsoft.com/en-us/aspnet/mvc/overview/getting-started/introduction/creating-a-connection-string


问:
How to make input read only based on particular value in Vue?
How to make an input field read only based on Vue data?

For example:

```<code><select class="form-control"
        id="selectCategory"
        :disabled="cat_id >=
            1"
        name="cat_id">
</code>```

I want to make the field read only but not disabled. How can I achieve this?

答:
I ran into this issue while making a form for a password changing form and I encountered the browser trying to autocomplete everything. This should prevent the autocomplete from firing and also provide a method to change the value to suit your needs.

For some reason adding a v-bind:readonly property of true reverts to readonly="readonly"

Here is my currently working example which removes and re-adds the readonly property on focusout.

Vue Template HTML

```<code><input type="password" v-model="user.password" placeholder="Password" @focusin="toggleReadonly" @focusout="toggleReadonly" :readonly="true">
</code>```

Method

```<code>toggleReadonly(event){
          event.preventDefault()
          if(event.target.getAttribute('readonly') == 'readonly'){
              event.target.removeAttribute('readonly')
          }
          else{
              event.target.setAttribute('readonly', 'readonly')
         }
 }
</code>```

Body:
How to make an input field read only based on Vue data?

For example:

<select class="form-control"
        id="selectCategory"
        :disabled="cat_id >=
            1"
        name="cat_id">

I want to make the field read only but not disabled. How can I achieve this?

Body:
I ran into this issue while making a form for a password changing form and I encountered the browser trying to autocomplete everything. This should prevent the autocomplete from firing and also provide a method to change the value to suit your needs.

For some reason adding a v-bind:readonly property of true reverts to readonly="readonly"

Here is my currently working example which removes and re-adds the readonly property on focusout.

Vue Template HTML

<input type="password" v-model="user.password" placeholder="Password" @focusin="toggleReadonly" @focusout="toggleReadonly" :readonly="true">

Method

toggleReadonly(event){
          event.preventDefault()
          if(event.target.getAttribute('readonly') == 'readonly'){
              event.target.removeAttribute('readonly')
          }
          else{
              event.target.setAttribute('readonly', 'readonly')
         }
 }


答:
Use Series.str.split:

```<code>df1 = df['buyer'].str.split(expand=True).rename(columns={0:'first_name',1:"surname"})

print(df1)
  first_name  surname
0     Lebron    James
1        Jon     Snow
2      Frodo  Baggins
</code>```

or:

```<code>df = df.join(df1)

print(df)
      assistant          buyer first_name  surname
0  Lebron James   Lebron James     Lebron    James
1    Arya Stark       Jon Snow        Jon     Snow
2     Sam Gamyi  Frodo Baggins      Frodo  Baggins
</code>```

Title: Apply in pandas depending on row not working

Body:
I have a dataframe of buyer's and assistant's names as follows:

df = pd.DataFrame([
{ 'buyer': 'Lebron James', 'assistant': 'Lebron James' },
{ 'buyer': 'Jon Snow', 'assistant': 'Arya Stark' },
{ 'buyer': 'Frodo Baggins', 'assistant': 'Sam Gamyi' }
])

I would like to split the buyer's names into their names and surnames, so the expected output would be:

first_name  surname
 Lebron       James
 Jon          Snow
 Frodo        Baggings

For so, I have defined a function and tried to use apply():

def first_name(row):
    return df['buyer'][row].split()[0]

df['first_name'] = df.apply(first_name, axis = 1)

However, I get the following error:

    Traceback (most recent call last):

  File "<ipython-input-35-f3bcdf3bb991>", line 1, in <module>
    df.apply(first_name, axis = 1)

  File "/Users/javier.lopez/anaconda3/lib/python3.7/site-packages/pandas/core/frame.py", line 6487, in apply
    return op.get_result()

  File "/Users/javier.lopez/anaconda3/lib/python3.7/site-packages/pandas/core/apply.py", line 151, in get_result
    return self.apply_standard()

  File "/Users/javier.lopez/anaconda3/lib/python3.7/site-packages/pandas/core/apply.py", line 257, in apply_standard
    self.apply_series_generator()

  File "/Users/javier.lopez/anaconda3/lib/python3.7/site-packages/pandas/core/apply.py", line 286, in apply_series_generator
    results[i] = self.f(v)

  File "<ipython-input-32-410cb25f2482>", line 2, in first_name
    return df['buyer'][row].split()[0]

  File "/Users/javier.lopez/anaconda3/lib/python3.7/site-packages/pandas/core/generic.py", line 5067, in __getattr__
    return object.__getattribute__(self, name)

AttributeError: ("'Series' object has no attribute 'split'", 'occurred at index 0')

I had understood that using apply with axis=1 sent the number of the row as argument, so I do not understand why it is not working. If I manually put a row number as argument it works as expected:

first_name(1)

Body:
Use Series.str.split:

df1 = df['buyer'].str.split(expand=True).rename(columns={0:'first_name',1:"surname"})

print(df1)
  first_name  surname
0     Lebron    James
1        Jon     Snow
2      Frodo  Baggins

or:

df = df.join(df1)

print(df)
      assistant          buyer first_name  surname
0  Lebron James   Lebron James     Lebron    James
1    Arya Stark       Jon Snow        Jon     Snow
2     Sam Gamyi  Frodo Baggins      Frodo  Baggins


问:
Pandas fill NaN base on last available value and the next available value
I have csv data looks like this:

```<code>     A     B
0   x aa
1   z aa
2
3
4   x aa
5   z bb
6   x bb
7
8   z cc
</code>```

I would like to fill the empty cells in B column with values in A, if in A column

```<code>last_available_value_before_the_NaNs_in_A.split()[-1] == next_available_value_after_the_NaNs_in_A.split()[-1]
</code>```

the wanted result would be:

```<code>     A     B
0   x aa   aa
1   z aa   aa
2          aa
3          aa
4   x aa   aa
5   z bb   bb
6   x bb   bb
7
8   z cc   cc

</code>```

data.loc(7,'B') will be NaN because data.loc(6,'A').split()[-1] ==
data.loc(8,'A').split()[-1] is false.

data.loc(5,'B') is 'bb' because data.loc(5,'A').split()[-1] == 'bb'

Thanks for your help!

答:
This is verbose to illustrate the idea.</p>

```<code># create a column that jsut holds the last value
df["lastval"] = df.A.str.split().str[-1]
# fill blanks in a feed-forward manner
df["ffill"] = df.lastval.fillna(method="ffill")
# fill blanks in a feed-backward manner
df["bfill"] = df.lastval.fillna(method="bfill")

# create a mask that handles your logic
m = df.lastval.isnull() & (df["ffill"] == df["bfill"])
# fill those values into B from lastval
df["B"] = df["lastval"]
df.loc[m,"B"] = df.loc[m, "ffill"]
</code>```

Body:
I have csv data looks like this:

     A     B
0   x aa
1   z aa
2
3
4   x aa
5   z bb
6   x bb
7
8   z cc

I would like to fill the empty cells in B column with values in A, if in A column

last_available_value_before_the_NaNs_in_A.split()[-1] == next_available_value_after_the_NaNs_in_A.split()[-1]

the wanted result would be:

     A     B
0   x aa   aa
1   z aa   aa
2          aa
3          aa
4   x aa   aa
5   z bb   bb
6   x bb   bb
7
8   z cc   cc

data.loc(7,'B') will be NaN because data.loc(6,'A').split()[-1] ==
data.loc(8,'A').split()[-1] is false.

data.loc(5,'B') is 'bb' because data.loc(5,'A').split()[-1] == 'bb'

Thanks for your help!

Body:
This is verbose to illustrate the idea.

# create a column that jsut holds the last value
df["lastval"] = df.A.str.split().str[-1]
# fill blanks in a feed-forward manner
df["ffill"] = df.lastval.fillna(method="ffill")
# fill blanks in a feed-backward manner
df["bfill"] = df.lastval.fillna(method="bfill")

# create a mask that handles your logic
m = df.lastval.isnull() & (df["ffill"] == df["bfill"])
# fill those values into B from lastval
df["B"] = df["lastval"]
df.loc[m,"B"] = df.loc[m, "ffill"]


问:
How can we add a request header in Leaflet tile layer wms request
I want to make a wms request using L.tileLayer.wms, Is there a way to add a request header to the request for authorization purposes? If not what would be a good possible workaround?</p>

答: you can use leaflet-wms-header plugin https://github.com/ticinum-aerospace/leaflet-wms-header or try to create a custom wms layer as in this example https://github.com/ticinum-aerospace/leaflet-wms-header/blob/master/index.js</p>


问:
Is there a way to get the String value of an HttpEntity when EntityUtils.toString() returns an exception?
I keep running into this situation where I get back a bad HTTP response (like a 400) but cannot look at the HttpEntity in the HttpResponse object.  When I step through with the debugger, I can see that the entity has content (length > 0) and I can even look at the content, but all I see is an array of numbers (ASCII codes I guess?) which isn't helpful.  I'll call EntityUtils.toString() on the entity, but I get back an exception -- either an IOException, or some kind of "object is in an invalid state" exception.  This is really frustrating!  Is there any way to get at this content in a human-readable form?

Here is my code :

```<code>    protected JSONObject makeRequest(HttpRequestBase request) throws ClientProtocolException, IOException, JSONException, WebRequestBadStatusException {

    HttpClient httpclient = new DefaultHttpClient();

    try {
        request.addHeader("Content-Type", "application/json");
        request.addHeader("Authorization", "OAuth " + accessToken);
        request.addHeader("X-PrettyPrint", "1");

        HttpResponse response = httpclient.execute(request);
        int statusCode = response.getStatusLine().getStatusCode();

        if (statusCode < 200 || statusCode >= 300) {
            throw new WebRequestBadStatusException(statusCode);
        }

        HttpEntity entity = response.getEntity();

        if (entity != null) {
            return new JSONObject(EntityUtils.toString(entity));
        } else {
            return null;
        }

    } finally {
        httpclient.getConnectionManager().shutdown();
    }
}
</code>```

See where I throw the exception?  What I'd like to do is suck out the content of the HttpEntity and put it in the exception.

答:
In general if you want to convert your DTO to String format then you can use ObjectMapper. Please find the following example if it helpful.</p>

```<code>public static String getObjectAsString(Object object) {
    ObjectMapper mapper = new ObjectMapper();
    try {
        return mapper.writeValueAsString(object);
    } catch (Exception e) {
        return null;
    }
}
</code>```

Body:
I keep running into this situation where I get back a bad HTTP response (like a 400) but cannot look at the HttpEntity in the HttpResponse object.  When I step through with the debugger, I can see that the entity has content (length > 0) and I can even look at the content, but all I see is an array of numbers (ASCII codes I guess?) which isn't helpful.  I'll call EntityUtils.toString() on the entity, but I get back an exception -- either an IOException, or some kind of "object is in an invalid state" exception.  This is really frustrating!  Is there any way to get at this content in a human-readable form?

Here is my code :

    protected JSONObject makeRequest(HttpRequestBase request) throws ClientProtocolException, IOException, JSONException, WebRequestBadStatusException {

    HttpClient httpclient = new DefaultHttpClient();

    try {
        request.addHeader("Content-Type", "application/json");
        request.addHeader("Authorization", "OAuth " + accessToken);
        request.addHeader("X-PrettyPrint", "1");

        HttpResponse response = httpclient.execute(request);
        int statusCode = response.getStatusLine().getStatusCode();

        if (statusCode < 200 || statusCode >= 300) {
            throw new WebRequestBadStatusException(statusCode);
        }

        HttpEntity entity = response.getEntity();

        if (entity != null) {
            return new JSONObject(EntityUtils.toString(entity));
        } else {
            return null;
        }

    } finally {
        httpclient.getConnectionManager().shutdown();
    }
}

See where I throw the exception?  What I'd like to do is suck out the content of the HttpEntity and put it in the exception.

Body:
In general if you want to convert your DTO to String format then you can use ObjectMapper. Please find the following example if it helpful.

public static String getObjectAsString(Object object) {
    ObjectMapper mapper = new ObjectMapper();
    try {
        return mapper.writeValueAsString(object);
    } catch (Exception e) {
        return null;
    }
}


答:
You could compare a version that uses ffill and one that uses bfill:

```<code>f = df.A.fillna(method='ffill').str.split().str[-1]
b = df.A.fillna(method='bfill').str.split().str[-1]
df.B.where(f != b, f, inplace=True)
</code>```

Title: Pandas fill NaN base on last available value and the next available value

Body:
You could compare a version that uses ffill and one that uses bfill:

f = df.A.fillna(method='ffill').str.split().str[-1]
b = df.A.fillna(method='bfill').str.split().str[-1]
df.B.where(f != b, f, inplace=True)


问:
Azure OCR is skipping some values (especially numbers)
I created a simple grid on a paper with numbers and it skips some numbers. I tested it on multiple models and it seems Azure OCR is really skipping some numbers.

Anyone did a succesfully grid (or similar) that do not skip data? Maybe some design patterns that increase consistency?

https://azure.microsoft.com/en-us/services/cognitive-services/computer-vision/#detect-text

https://azure.microsoft.com/en-US/services/cognitive-services/ - sample

答: Azure Form Recognizer is a cognitive service that uses machine learning technology to identify and extract key-value pairs and table data from form documents. The  Supported types: pdf, image/jpeg, image/png.Can you try this one?</p>


问:
How to get the SPRING Boot HOST and PORT address during run time?
How could I get the host and port where my application is deployed during run-time so that I can use it in my java method?</p>

答:
Here is an util component:

EnvUtil.java

(Put it in proper package, to become a component.)

```<code>import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.env.Environment;
import org.springframework.stereotype.Component;

import java.net.InetAddress;
import java.net.UnknownHostException;

/**
 * Environment util.
 */
@Component
public class EnvUtil {
    @Autowired
    Environment environment;

    private String port;
    private String hostname;

    /**
     * Get port.
     *
     * @return
     */
    public String getPort() {
        if (port == null) port = environment.getProperty("local.server.port");
        return port;
    }

    /**
     * Get port, as Integer.
     *
     * @return
     */
    public Integer getPortAsInt() {
        return Integer.valueOf(getPort());
    }

    /**
     * Get hostname.
     *
     * @return
     */
    public String getHostname() throws UnknownHostException {
        // TODO ... would this cache cause issue, when network env change ???
        if (hostname == null) hostname = InetAddress.getLocalHost().getHostAddress();
        return hostname;
    }

    public String getServerUrlPrefi() throws UnknownHostException {
        return "http://" + getHostname() + ":" + getPort();
    }
}
</code>```

Example - use the util:

Then could inject the util, and call its method.

Here is an example in a controller:

```<code>// inject it,
@Autowired
private EnvUtil envUtil;

/**
 * env
 *
 * @return
 */
@GetMapping(path = "/env")
@ResponseBody
public Object env() throws UnknownHostException {
    Map<String, Object> map = new HashMap<>();
    map.put("port", envUtil.getPort());
    map.put("host", envUtil.getHostname());
    return map;
}
</code>```

Body:
Here is an util component:

EnvUtil.java

(Put it in proper package, to become a component.)

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.env.Environment;
import org.springframework.stereotype.Component;

import java.net.InetAddress;
import java.net.UnknownHostException;

/**
 * Environment util.
 */
@Component
public class EnvUtil {
    @Autowired
    Environment environment;

    private String port;
    private String hostname;

    /**
     * Get port.
     *
     * @return
     */
    public String getPort() {
        if (port == null) port = environment.getProperty("local.server.port");
        return port;
    }

    /**
     * Get port, as Integer.
     *
     * @return
     */
    public Integer getPortAsInt() {
        return Integer.valueOf(getPort());
    }

    /**
     * Get hostname.
     *
     * @return
     */
    public String getHostname() throws UnknownHostException {
        // TODO ... would this cache cause issue, when network env change ???
        if (hostname == null) hostname = InetAddress.getLocalHost().getHostAddress();
        return hostname;
    }

    public String getServerUrlPrefi() throws UnknownHostException {
        return "http://" + getHostname() + ":" + getPort();
    }
}

Example - use the util:

Then could inject the util, and call its method.

Here is an example in a controller:

// inject it,
@Autowired
private EnvUtil envUtil;

/**
 * env
 *
 * @return
 */
@GetMapping(path = "/env")
@ResponseBody
public Object env() throws UnknownHostException {
    Map<String, Object> map = new HashMap<>();
    map.put("port", envUtil.getPort());
    map.put("host", envUtil.getHostname());
    return map;
}


问:
InfluxDB returns bad timestamp. I have no idea why
I doubt this is a duplicate issue but it might be the same problem as seen elsewhere.

When I try to insert things into InfluxDB via CURL, it just keeps giving me the same invalid timestamp error. I can't really tell why. Below is the data.

```<code>metaRead=3 metaWrite=0 dspaceOps=0 keyValOps=0 scheduled=1 requests=66 smallReads=0 smallWrites=0 flowReads=0 flowWrites=0 creates=0 removes=0 mkdirs=0 rmdirs=0 getattrs=0 setattrs=0 3862710532
</code>```

Any help would be appreciated. I'm using the CURL library to send the requests but sending them manually via the command line yields the same response.

答:
InfluxDB expects/defaults to nanosecond precision. You're using seconds, by the looks of it. You'll need to modify your curl command with the precision query arg:

curl -i -XPOST "http://localhost:8086/write?db=weather&precision=s" --data-binary 'temperature,location=1 value=90 1472666050'

Body:
I doubt this is a duplicate issue but it might be the same problem as seen elsewhere.

When I try to insert things into InfluxDB via CURL, it just keeps giving me the same invalid timestamp error. I can't really tell why. Below is the data.

metaRead=3 metaWrite=0 dspaceOps=0 keyValOps=0 scheduled=1 requests=66 smallReads=0 smallWrites=0 flowReads=0 flowWrites=0 creates=0 removes=0 mkdirs=0 rmdirs=0 getattrs=0 setattrs=0 3862710532

Any help would be appreciated. I'm using the CURL library to send the requests but sending them manually via the command line yields the same response.


问:
How do I implement UserPassesTestMixin in function based views?
I can implement UserPassesTestMixin in class based views,

```<code>class PostDeleteView(LoginRequiredMixin, UserPassesTestMixin, DeleteView):
    model = Post
    success_url = '/'

    def test_func(self):
        post = self.get_object()
        if self.request.user == post.author:
            return True
        return False

</code>```

but I don't know how to implement this in function based view? Thank you

edit:

```<code>def permission_of_user_for_posts(request,**kwargs):
    post = get_object_or_404(Blog, slug= request.GET.get('blog_slug'))
    if request.user.username == post.author:
        return True
    return False

@user_passes_test(permission_of_user_for_posts)
def blog_create(request):
    if request.method == 'POST':
        form = BlogForm(request.POST, request.FILES)
        if form.is_valid():
            form.instance.author = request.user
            slug = form.instance.slug
            form.save()
            return redirect('/')
    form = BlogForm()
    context = {
        'form':form,
    }
    return render(request, 'blogs/form.html', context)
</code>```

答:
```<code>from django.contrib.auth.decorators import user_passes_test

def email_check(user):
    return user.email.endswith('@example.com')

@user_passes_test(email_check)
def my_view(request):
    ...
</code>```

Body:
I can implement UserPassesTestMixin in class based views,

class PostDeleteView(LoginRequiredMixin, UserPassesTestMixin, DeleteView):
    model = Post
    success_url = '/'

    def test_func(self):
        post = self.get_object()
        if self.request.user == post.author:
            return True
        return False

but I don't know how to implement this in function based view? Thank you

edit:

def permission_of_user_for_posts(request,**kwargs):
    post = get_object_or_404(Blog, slug= request.GET.get('blog_slug'))
    if request.user.username == post.author:
        return True
    return False

@user_passes_test(permission_of_user_for_posts)
def blog_create(request):
    if request.method == 'POST':
        form = BlogForm(request.POST, request.FILES)
        if form.is_valid():
            form.instance.author = request.user
            slug = form.instance.slug
            form.save()
            return redirect('/')
    form = BlogForm()
    context = {
        'form':form,
    }
    return render(request, 'blogs/form.html', context)


问:
How to horizontally align text within a rotated table cell in XSL-FO?
With Antenna House 5.3 I haven't found how to create a table cell that is rotated 90 degrees "left aligned" (so, on the bottom vertically on the page) and "vertically centered" (in the middle horizontally on the page). I have tried all the combinations of text-align display-align that I think I can, but the result is still "top aligned" (on the bottom vertically, and on the left horizontally).

Do you know how to make text left aligned and vertically centered, in a rotated table cell? Here is an example of a cell:

```<code><fo:table-cell display-align="after">
  <fo:block-container reference-orientation="90" display-align="center">
    <fo:block>Text</fo:block>
  </fo:block-container>
</fo:table-cell>
</code>```

The result is that the text is not centered left-to-right on the page.

答:
Using AH Formatter V6.6 (I don't have V5.3 installed), if you give the table column a width (using fo:column and column-width) and set height="100%" on the fo:block-container, then the formatter has more to work with so that it can center the text in the column.

The screenshot below is from the AH Formatter GUI with the 'Show Border' option enabled so that you can see the extent of the areas and see the (rotated) height of the fo:block-container in the second table header cell.

```<code><fo:table start-indent="0" end-indent="0">
  <fo:table-column column-width="50pt" />
  <fo:table-column column-width="50pt" />
  <fo:table-header>
    <fo:table-row>
      <fo:table-cell display-align="after" padding="6pt">
        <fo:block-container reference-orientation="90" display-align="center">
          <fo:block>Text</fo:block>
        </fo:block-container>
      </fo:table-cell>
      <fo:table-cell display-align="after" padding="6pt">
        <fo:block-container height="100%" reference-orientation="90" display-align="center">
          <fo:block>Text</fo:block>
        </fo:block-container>
      </fo:table-cell>
    </fo:table-row>
  </fo:table-header>
  <fo:table-body>
    <fo:table-row>
      <fo:table-cell padding="6pt">
        <fo:block>Text</fo:block>
      </fo:table-cell>
      <fo:table-cell padding="6pt">
        <fo:block>Text</fo:block>
      </fo:table-cell>
    </fo:table-row>
  </fo:table-body>
</fo:table>
</code>```

Body:
With Antenna House 5.3 I haven't found how to create a table cell that is rotated 90 degrees "left aligned" (so, on the bottom vertically on the page) and "vertically centered" (in the middle horizontally on the page). I have tried all the combinations of text-align display-align that I think I can, but the result is still "top aligned" (on the bottom vertically, and on the left horizontally).

Do you know how to make text left aligned and vertically centered, in a rotated table cell? Here is an example of a cell:

<fo:table-cell display-align="after">
  <fo:block-container reference-orientation="90" display-align="center">
    <fo:block>Text</fo:block>
  </fo:block-container>
</fo:table-cell>

The result is that the text is not centered left-to-right on the page.

Body:
Using AH Formatter V6.6 (I don't have V5.3 installed), if you give the table column a width (using fo:column and column-width) and set height="100%" on the fo:block-container, then the formatter has more to work with so that it can center the text in the column.

The screenshot below is from the AH Formatter GUI with the 'Show Border' option enabled so that you can see the extent of the areas and see the (rotated) height of the fo:block-container in the second table header cell.

<fo:table start-indent="0" end-indent="0">
  <fo:table-column column-width="50pt" />
  <fo:table-column column-width="50pt" />
  <fo:table-header>
    <fo:table-row>
      <fo:table-cell display-align="after" padding="6pt">
        <fo:block-container reference-orientation="90" display-align="center">
          <fo:block>Text</fo:block>
        </fo:block-container>
      </fo:table-cell>
      <fo:table-cell display-align="after" padding="6pt">
        <fo:block-container height="100%" reference-orientation="90" display-align="center">
          <fo:block>Text</fo:block>
        </fo:block-container>
      </fo:table-cell>
    </fo:table-row>
  </fo:table-header>
  <fo:table-body>
    <fo:table-row>
      <fo:table-cell padding="6pt">
        <fo:block>Text</fo:block>
      </fo:table-cell>
      <fo:table-cell padding="6pt">
        <fo:block>Text</fo:block>
      </fo:table-cell>
    </fo:table-row>
  </fo:table-body>
</fo:table>


问:
Nested SELECT "works" when using nonexistant column - why?
folks, I have the following query in SQLite:

select license, username from check_table where
(
    username not in (
        select username from Address
    )
) order by license, username;
```

Address is another table. The fun part is: Address has no usernamecolumn!!

Details:

Result: Query finished in 0.004 second(s)

If I modify the username part (e.g. to userrname) I get a no such column error, which is totally fine

it never returns any results, even when I replace username with mail_username (which actually exists) in the sub-select - which is totally strange, because it really should.

Now, my question is: Why don't I get an error here?! And does it have something to do with the fact that I never get any results?

答:
You're selecting username from the check_table, not from the address table.

Try to add aliases and check it out:

```<code>select ct.license, ct.username
from check_table as ct
where
(
    ct.username not in (
        select ct.username
        from Address as a
    )
) order by ct.license, ct.username;
</code>```

I bet if you will try to use select a.username... you'll get an error about not existing column.

For this purpose, all the time when you're using multiple tables in the query is good to use aliases.

Body:
folks, I have the following query in SQLite:

select license, username from check_table where
(
    username not in (
        select username from Address
    )
) order by license, username;

Address is another table. The fun part is: Address has no usernamecolumn!!

Details:

Result: Query finished in 0.004 second(s)

If I modify the username part (e.g. to userrname) I get a no such column error, which is totally fine

it never returns any results, even when I replace username with mail_username (which actually exists) in the sub-select - which is totally strange, because it really should.

Now, my question is: Why don't I get an error here?! And does it have something to do with the fact that I never get any results?

Body:
You're selecting username from the check_table, not from the address table.

Try to add aliases and check it out:

select ct.license, ct.username
from check_table as ct
where
(
    ct.username not in (
        select ct.username
        from Address as a
    )
) order by ct.license, ct.username;

I bet if you will try to use select a.username... you'll get an error about not existing column.

For this purpose, all the time when you're using multiple tables in the query is good to use aliases.


问:
optional POST parameter in spring MVC?
I have the following code:

```<code>@RequestMapping(method = RequestMethod.POST)
public ModelAndView editItem(String name, String description)
</code>```

However, sometime description is not passed in (this is a simplified example than the real one), and i would like to make description optional, perhaps by filling in a default value if none is passed in.

Anyone have any idea how to do that?

thanks a lot!

Jason

答:
If you are using Spring MVC 3.0 or higher then just set defaultValue parameter of @RequestParam:

```<code>public ModelAndView editItem(@RequestParam(value = "description", defaultValue = "new value") String description)
</code>```

In Spring MVC 2.5, I suggest to mark value as required = false and check their value against null manually:

```<code>public ModelAndView editItem(@RequestParam(value = "description", required = false) String description) {
    if (description == null) {
        description = "new value";
    }
    ...
}
</code>```

See also corresponding documentation about @RequestParam annotation.

UPDATE for JDK 8 & Spring 4.1+: now you could use java.util.Optional like this:

```<code>public ModelAndView editItem(@RequestParam("description") Optional<String> description) {

    item.setDescription(description.getOrElse("default value"));

    // or only if it's present:
    description.ifPresent(value -> item.setDescription(description));
    ...
}
</code>```

ContentLicense: CC BY-SA 2.5

Title: optional POST parameter in spring MVC?

Body:
I have the following code:

@RequestMapping(method = RequestMethod.POST)
public ModelAndView editItem(String name, String description)

However, sometime description is not passed in (this is a simplified example than the real one), and i would like to make description optional, perhaps by filling in a default value if none is passed in.

Anyone have any idea how to do that?

thanks a lot!

Jason

Body:
If you are using Spring MVC 3.0 or higher then just set defaultValue parameter of @RequestParam:

public ModelAndView editItem(@RequestParam(value = "description", defaultValue = "new value") String description)

In Spring MVC 2.5, I suggest to mark value as required = false and check their value against null manually:

public ModelAndView editItem(@RequestParam(value = "description", required = false) String description) {
    if (description == null) {
        description = "new value";
    }
    ...
}

See also corresponding documentation about @RequestParam annotation.

UPDATE for JDK 8 & Spring 4.1+: now you could use java.util.Optional like this:

public ModelAndView editItem(@RequestParam("description") Optional<String> description) {

    item.setDescription(description.getOrElse("default value"));

    // or only if it's present:
    description.ifPresent(value -> item.setDescription(description));
    ...
}


问:
Doing HTTP request in Scala
I am trying to issue a simple POST request to a webservice which returns some XML in Scala.

It seems that Dispatch is the standard library used for this task, but I cannot find documentation for it. The main site, which I link above, explains at length what is a promise and how to do asynchronous programming, but does not actually document the API. There is a periodic table - which looks a bit scary - but it only seems useful to people who already know what to do and only need a reminder for the cryptic syntax.

It also seems that Scalaz has some facility for HTTP, but I cannot find any documentation for it either.

答:
Using my Requests-Scala library:

```<code>// Mill
ivy"com.lihaoyi::requests:0.1.8"
// SBT
"com.lihaoyi" %% "requests" % "0.1.8"
</code>```

This is as simple as

```<code>val r = requests.get("https://api.github.com/users/lihaoyi")

r.statusCode
// 200

r.headers("content-type")
// Buffer("application/json; charset=utf-8")

r.text
// {"login":"lihaoyi","id":934140,"node_id":"MDQ6VXNlcjkzNDE0MA==",...
</code>```

```<code>val r = requests.post("http://httpbin.org/post", data = Map("key" -> "value"))

val r = requests.put("http://httpbin.org/put", data = Map("key" -> "value"))

val r = requests.delete("http://httpbin.org/delete")

val r = requests.head("http://httpbin.org/head")

val r = requests.options("http://httpbin.org/get")
</code>```

Title: Doing HTTP request in Scala

Body:
Using my Requests-Scala library:

// Mill
ivy"com.lihaoyi::requests:0.1.8"
// SBT
"com.lihaoyi" %% "requests" % "0.1.8"

This is as simple as

val r = requests.get("https://api.github.com/users/lihaoyi")

r.statusCode
// 200

r.headers("content-type")
// Buffer("application/json; charset=utf-8")

r.text
// {"login":"lihaoyi","id":934140,"node_id":"MDQ6VXNlcjkzNDE0MA==",...

val r = requests.post("http://httpbin.org/post", data = Map("key" -> "value"))

val r = requests.put("http://httpbin.org/put", data = Map("key" -> "value"))

val r = requests.delete("http://httpbin.org/delete")

val r = requests.head("http://httpbin.org/head")

val r = requests.options("http://httpbin.org/get")


问:
How to override parent class?
I have two classes:

```<code>class Parent(object):
    def __init__(self):
        self.a = 0
        self.b = self.a + 1

class Child(Parent):
    def __init__(self):
        super().__init__()
        self.a = 1

print(Child().b)
</code>```

Output is 1 (0+1) but I expect to have 2 (1+1). How can I achieve such result?

答:
assign a attribute outside of Parent.__init__:

```<code>class Parent(object):
    a = 0
    def __init__(self):
        self.b = self.a + 1

class Child(Parent):
    def __init__(self):
        self.a = 1
        super().__init__()

print(Child().b)
</code>```

Title: How to override parent class?

Body:
I have two classes:

class Parent(object):
    def __init__(self):
        self.a = 0
        self.b = self.a + 1

class Child(Parent):
    def __init__(self):
        super().__init__()
        self.a = 1

print(Child().b)

Output is 1 (0+1) but I expect to have 2 (1+1). How can I achieve such result?

Body:
assign a attribute outside of Parent.__init__:

class Parent(object):
    a = 0
    def __init__(self):
        self.b = self.a + 1

class Child(Parent):
    def __init__(self):
        self.a = 1
        super().__init__()

print(Child().b)