问:
Configuring json parser to parse escaped json string in json
Assume you have the following json snippet

```<code>{
    "topic":"foo",
    "payload":"{\"type\":\"String\",\"value\":\"44\"}",
    "type":"ItemStateEvent"
}
</code>```

At first glance it seems that payload has been converted to a json string twice. Naive approach would be calling the parsing function twice on this entire snippet. First time on the entire thing and the second time on the payload field.

Now for the question: How do you configure parser of your choice so it would do the menial work for you?

答:
Jackson, java json parsing library, seems to have support per field deserializers. As a result, you can add @JsonDeserialize(using = NestedDeserializer.class) to the particular "nested" json field. NestedDeserializer is an implementation of com.fasterxml.jackson.databind.JsonDeserializer. Currently I'm playing around with the following implementation:

    @Override
    public LinkedHashMap<String, String> deserialize(JsonParser p, DeserializationContext ctxt) throws IOException, JsonProcessingException {
        ObjectMapper m  = (ObjectMapper) p.getCodec(); // am I sure that codec will always be ObjectMapper?
        TextNode textNode = m.readTree(p);
        LinkedHashMap<String, String> datum = m.readValue(textNode.asText(), LinkedHashMap.class);
        return datum;
    }
```

What the snippet does is it deserializes the current token into string and just runs it through the parser a second time.

Body:
Assume you have the following json snippet

{
    "topic":"foo",
    "payload":"{\"type\":\"String\",\"value\":\"44\"}",
    "type":"ItemStateEvent"
}

At first glance it seems that payload has been converted to a json string twice. Naive approach would be calling the parsing function twice on this entire snippet. First time on the entire thing and the second time on the payload field.

Now for the question: How do you configure parser of your choice so it would do the menial work for you?

Body:
Jackson, java json parsing library, seems to have support per field deserializers. As a result, you can add @JsonDeserialize(using = NestedDeserializer.class) to the particular "nested" json field. NestedDeserializer is an implementation of com.fasterxml.jackson.databind.JsonDeserializer. Currently I'm playing around with the following implementation:

    @Override
    public LinkedHashMap<String, String> deserialize(JsonParser p, DeserializationContext ctxt) throws IOException, JsonProcessingException {
        ObjectMapper m  = (ObjectMapper) p.getCodec(); // am I sure that codec will always be ObjectMapper?
        TextNode textNode = m.readTree(p);
        LinkedHashMap<String, String> datum = m.readValue(textNode.asText(), LinkedHashMap.class);
        return datum;
    }

What the snippet does is it deserializes the current token into string and just runs it through the parser a second time.


来源: stackexchange

问:
How to download a file in angular, which is received as application/octet-stream
I'm creating a webpage that has to download a file in CSV format. The REST API returns the file.

I get an error while accessing the API. I guess that is because the file is getting converted to JSON. How can I get it from the back end and handle it?

service.ts

```<code>return this.http.get(URL);
</code>```

答:
You can use file-saver

import * as FileSaver from 'file-saver';

```<code>this.http.post(url, resource, { responseType: 'blob' })
 .subscribe((resp: any) => {
    FileSaver.saveAs(resp, `filename.csv`)
 });
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I'm creating a webpage that has to download a file in CSV format. The REST API returns the file.

I get an error while accessing the API. I guess that is because the file is getting converted to JSON. How can I get it from the back end and handle it?

service.ts

return this.http.get(URL);

Body:
You can use file-saver

import * as FileSaver from 'file-saver';

this.http.post(url, resource, { responseType: 'blob' })
 .subscribe((resp: any) => {
    FileSaver.saveAs(resp, `filename.csv`)
 });


问:
How to export Certificate and private key as a single file using java code?
My requirement is to combine a certificate and private key and then, using PEMwriter, I need to export the file.

I used bouncycastle to generate private key and csr. Then, I submitted the CSR to CA and got the certificate.
THe following code is for generating keypair

```<code>KeyPair idPair = KeyPairGenerator.getInstance("RSA").genKeyPair();
PublicKey publicKey = idPair.getPublic();
PrivateKey privkey = idPair.getPrivate();
</code>```

THe following code is for receiving the certificate and exporting it to .cer file.

```<code>CertStore store = response.getCertStore();
            Collection<? extends Certificate> certs = store
                    .getCertificates(null);
            Certificate[] chain = new Certificate[certs.size()];

            int i = 0;
            for (Certificate certificate : certs) {
                chain[i++] = certificate;
            }

            FileOutputStream os = new FileOutputStream("cert.cer");
            os.write("-----BEGIN CERTIFICATE-----\n".getBytes("US-ASCII"));
            os.write(Base64.encodeBase64(chain[0].getEncoded(), true));
            os.write("-----END CERTIFICATE-----\n".getBytes("US-ASCII"));
            os.close();
</code>```

Now, my goal is when I open the exported file, I must be prompted to input password to install/view the certificate. I'm really confused about this part. Previously I added password to keystore like the following

```<code>KeyStore keyStore = KeyStore.getInstance("PKCS12", "BC");
        keyStore.load(null, null);

        keyStore.setKeyEntry("mykey", (Key) keyPair.getPrivate(), "Password1!".toCharArray(), certz);

        ByteArrayOutputStream bout = new ByteArrayOutputStream();
        keyStore.store(bout, "Password1!".toCharArray()); // this is the password to open the .p12

        byte[] keystore = bout.toByteArray();
        bout.close();
</code>```

But, now, I need to protect the certificate with password. Is this even possible? If so, what will be the file extension? And please guide me in the coding part (PemWriter).
Thanks

答:
As mentioned above for normal use you don't need to protect certificates with passwords. But if you want to store some certificates in a safe place, you can do it in a password-protected keystore file (only java.security code, no PemWriter necessary). </p>

```<code>            KeyStore ks = KeyStore.getInstance("PKCS12");
            ks.load(null, null);

            Certificate cert = getX509Cert(); // load certificate
            ks.setCertificateEntry("myCertAlias", cert);

            FileOutputStream fos = null;
            try {
                fos = new FileOutputStream(PATH + "newKeyStore.p12");
                char[] password = PASSWORD_.toCharArray();
                ks.store(fos, password);
            } finally {
                if (fos != null) {
                    fos.close();
                }
            }
</code>```

Body:
My requirement is to combine a certificate and private key and then, using PEMwriter, I need to export the file.

I used bouncycastle to generate private key and csr. Then, I submitted the CSR to CA and got the certificate.
THe following code is for generating keypair

KeyPair idPair = KeyPairGenerator.getInstance("RSA").genKeyPair();
PublicKey publicKey = idPair.getPublic();
PrivateKey privkey = idPair.getPrivate();

THe following code is for receiving the certificate and exporting it to .cer file.

CertStore store = response.getCertStore();
            Collection<? extends Certificate> certs = store
                    .getCertificates(null);
            Certificate[] chain = new Certificate[certs.size()];

            int i = 0;
            for (Certificate certificate : certs) {
                chain[i++] = certificate;
            }

            FileOutputStream os = new FileOutputStream("cert.cer");
            os.write("-----BEGIN CERTIFICATE-----\n".getBytes("US-ASCII"));
            os.write(Base64.encodeBase64(chain[0].getEncoded(), true));
            os.write("-----END CERTIFICATE-----\n".getBytes("US-ASCII"));
            os.close();

Now, my goal is when I open the exported file, I must be prompted to input password to install/view the certificate. I'm really confused about this part. Previously I added password to keystore like the following

KeyStore keyStore = KeyStore.getInstance("PKCS12", "BC");
        keyStore.load(null, null);

        keyStore.setKeyEntry("mykey", (Key) keyPair.getPrivate(), "Password1!".toCharArray(), certz);

        ByteArrayOutputStream bout = new ByteArrayOutputStream();
        keyStore.store(bout, "Password1!".toCharArray()); // this is the password to open the .p12

        byte[] keystore = bout.toByteArray();
        bout.close();

But, now, I need to protect the certificate with password. Is this even possible? If so, what will be the file extension? And please guide me in the coding part (PemWriter).
Thanks

Body:
As mentioned above for normal use you don't need to protect certificates with passwords. But if you want to store some certificates in a safe place, you can do it in a password-protected keystore file (only java.security code, no PemWriter necessary).

            KeyStore ks = KeyStore.getInstance("PKCS12");
            ks.load(null, null);

            Certificate cert = getX509Cert(); // load certificate
            ks.setCertificateEntry("myCertAlias", cert);

            FileOutputStream fos = null;
            try {
                fos = new FileOutputStream(PATH + "newKeyStore.p12");
                char[] password = PASSWORD_.toCharArray();
                ks.store(fos, password);
            } finally {
                if (fos != null) {
                    fos.close();
                }
            }


问:
Xamarin forms: How to add events in `XamForms.Controls.Calendar`?
I am using XamForms.Controls.Calendar for showing calendar in my application, I have added this package in all platforms.

Added following codes in xaml:

```<code><StackLayout>
        <controls:Calendar
            HorizontalOptions="FillAndExpand"
            VerticalOptions="CenterAndExpand"
            x:Name="calendar"
            DateClicked="CurrentDate"/>
    </StackLayout>
</code>```

In c#:

```<code>XamForms.Controls.Calendar calendar = new XamForms.Controls.Calendar()
            {
                WidthRequest = 300,
                HeightRequest = 300
            };
        }
        public async void CurrentDate(Object sender, EventArgs args)
        {
            var dateSelect = calendar.SelectedDate;
        }
</code>```

I need to add events for dates in the calendar like school day, school mass or exam(Please see the screenshot added below). Is this possible in  XamForms.Controls.Calendar?

答:
This plugin can add special dates: https://github.com/rebeccaXam/XamForms.Controls.Calendar/wiki/SpecialDates

```<code>calendar.SpecialDates = new List<SpecialDate>
{
    new SpecialDate(DateTime.Now.AddDays(3))
    {
        Selectable = true,
        BackgroundPattern = new BackgroundPattern(1)
        {
            Pattern = new List<Pattern>
            {
                new Pattern { WidthPercent = 1f, HightPercent = 0.6f, Color = Color.Transparent },
                new Pattern{ WidthPercent = 1f, HightPercent = 0.4f, Color = Color.Transparent, Text = "Mass", TextColor=Color.Black, TextSize=11, TextAlign=TextAlign.Middle},
            }
        }
    }
};
</code>```

Is this effect what you want?

Body:
I am using XamForms.Controls.Calendar for showing calendar in my application, I have added this package in all platforms.

Added following codes in xaml:

<StackLayout>
        <controls:Calendar
            HorizontalOptions="FillAndExpand"
            VerticalOptions="CenterAndExpand"
            x:Name="calendar"
            DateClicked="CurrentDate"/>
    </StackLayout>

In c#:

XamForms.Controls.Calendar calendar = new XamForms.Controls.Calendar()
            {
                WidthRequest = 300,
                HeightRequest = 300
            };
        }
        public async void CurrentDate(Object sender, EventArgs args)
        {
            var dateSelect = calendar.SelectedDate;
        }

I need to add events for dates in the calendar like school day, school mass or exam(Please see the screenshot added below). Is this possible in  XamForms.Controls.Calendar?

Body:
This plugin can add special dates: https://github.com/rebeccaXam/XamForms.Controls.Calendar/wiki/SpecialDates

calendar.SpecialDates = new List<SpecialDate>
{
    new SpecialDate(DateTime.Now.AddDays(3))
    {
        Selectable = true,
        BackgroundPattern = new BackgroundPattern(1)
        {
            Pattern = new List<Pattern>
            {
                new Pattern { WidthPercent = 1f, HightPercent = 0.6f, Color = Color.Transparent },
                new Pattern{ WidthPercent = 1f, HightPercent = 0.4f, Color = Color.Transparent, Text = "Mass", TextColor=Color.Black, TextSize=11, TextAlign=TextAlign.Middle},
            }
        }
    }
};

Is this effect what you want?


问:
I'm getting a "this.container is undefined" error when using mat-paginator
I have a mat-table that has a list of users called from a database using a spring REST API which works perfectly but when I wanted to add a paginator to help go through the whole list of users I started getting a "this.container is undefined" error when trying to click on the paginator.

Also, for some reason It showing "Items per page: 5" only even though I have almost 27 users.

Here's my html code:

```<code><mat-form-field>
  <input matInput (keyup)="applyFilter($event.target.value)" placeholder="Filter" style="width: 500px !important">
</mat-form-field>
        <mat-table class="lessons-table mat-elevation-z8" [dataSource]="dataSource">
            <ng-container matColumnDef="id" class=".mat-column-id">
                <mat-header-cell *matHeaderCellDef>#</mat-header-cell>
                <mat-cell *matCellDef="let user">{{user.id}}</mat-cell>
            </ng-container>
            <ng-container matColumnDef="username" class=".mat-column-username">
                <mat-header-cell *matHeaderCellDef>Username</mat-header-cell>
                <mat-cell class="description-cell" *matCellDef="let user">{{user.username}}</mat-cell>
            </ng-container>
            <ng-container matColumnDef="email" class=".mat-column-email">
                <mat-header-cell *matHeaderCellDef>Email</mat-header-cell>
                <mat-cell class="duration-cell" *matCellDef="let user">{{user.email}}</mat-cell>
            </ng-container>
            <ng-container matColumnDef="firstname" class=".mat-column-name">
                <mat-header-cell *matHeaderCellDef>firstname</mat-header-cell>
                <mat-cell class="duration-cell" *matCellDef="let user">{{user.firstName}}</mat-cell>
            </ng-container>
            <ng-container matColumnDef="lastname"class=".mat-column-name">
                <mat-header-cell *matHeaderCellDef>Last Name</mat-header-cell>
                <mat-cell class="duration-cell" *matCellDef="let user">{{user.lastName}}</mat-cell>
            </ng-container>
            <ng-container matColumnDef="enabled" class=".mat-column-enabled">
                <mat-header-cell *matHeaderCellDef>Enabled</mat-header-cell>
                <mat-cell class="duration-cell" *matCellDef="let user">{{user.enabled}}</mat-cell>
            </ng-container>
            <ng-container matColumnDef="registeredDate" class=".mat-column-date">
                <mat-header-cell *matHeaderCellDef>Registered Date</mat-header-cell>
                <mat-cell class="duration-cell" *matCellDef="let user">{{user.registeredDate | date: shortDate}}</mat-cell>
            </ng-container>
            <mat-header-row *matHeaderRowDef="displayedColumns; sticky: true"></mat-header-row>
            <mat-row class="mat-row" *matRowDef="let row; columns: displayedColumns" (click)="onRowClicked(row)"></mat-row>
        </mat-table>
        <mat-paginator [pageSizeOptions]="[5, 10, 25, 100]"></mat-paginator>
</code>```

and the ts file:

```<code>import { Component, OnInit, ViewChild } from '@angular/core';
import { ViewEncapsulation } from '@angular/core';
import { HttpClient, HttpHeaders } from '@angular/common/http';
import { UserService } from '../user.service';
import { MatDialog, MatDialogConfig, MatTableDataSource, MatPaginator, MatSort } from '@angular/material';
import { NewDialogComponent } from '../new-dialog/new-dialog.component';
import { DomSanitizer } from '@angular/platform-browser';
import { map } from 'rxjs-compat/operator/map';
import { Observable, Observer } from 'rxjs';

@Component({
  selector: 'app-dashboard',
  templateUrl: './dashboard.component.html',
  styleUrls: ['../app.component.scss', './dashboard.component.scss'],
  encapsulation: ViewEncapsulation.None
})
export class DashboardComponent implements OnInit {
  loginuser: any = {};
  imgSrc: any = {};
  users: any[] = [];
  imageToShow: any;
  public dataSource = new MatTableDataSource<User>();
  displayedColumns = ['id', 'username', 'email', 'firstname', 'lastname', 'registeredDate', 'enabled'];
  @ViewChild(MatPaginator) paginator: MatPaginator;
  @ViewChild(MatSort) sort: MatSort;
  constructor(private service: UserService, private http: HttpClient, private sanitizer: DomSanitizer) {
   this.loginuser = JSON.parse(localStorage.getItem('currentUser'));
   this.service.getAllUsers(this.loginuser.token).subscribe(u => {
   this.dataSource.data = u as User[];
   this.users = u;
  // console.log('user: ', this.users);
   });
   this.dataSource.paginator = this.paginator;
   this.dataSource.sort = this.sort;
 }

 ngOnInit() {
 }

 applyFilter(filterValue: string) {
   this.dataSource.filter = filterValue.trim().toLowerCase();
   if (this.dataSource.paginator) {
   this.dataSource.paginator.firstPage();
   }
 }
}
</code>```

答:
The value of this injected member variable is not immediately available at component construction time!

Angular will fill in this property automatically, but only later in the component lifecycle, after the view initialization is completed.

If we want to write component initialization code that uses the references injected by @ViewChild, we need to do it inside the AfterViewInit lifecycle hook.

```<code>@Component({
      selector: 'app-root',
      templateUrl: './app.component.html'
    })
    export class AppComponent implements  AfterViewInit {
      @ViewChild(SomeComponent)
      someComponent: SomeComponent;

      ngAfterViewInit() {
        console.log('Values on ngAfterViewInit():');
        console.log("someComponent:", this.someComponent);
      }

    }
</code>```

In Your case just put these two line in NgAfterViewInit LifeCyle as:

```<code>    import { Component, OnInit, ViewChild } from '@angular/core';
import { ViewEncapsulation } from '@angular/core';
import { HttpClient, HttpHeaders } from '@angular/common/http';
import { UserService } from '../user.service';
import { MatDialog, MatDialogConfig, MatTableDataSource, MatPaginator, MatSort } from '@angular/material';
import { NewDialogComponent } from '../new-dialog/new-dialog.component';
import { DomSanitizer } from '@angular/platform-browser';
import { map } from 'rxjs-compat/operator/map';
import { Observable, Observer } from 'rxjs';

@Component({
  selector: 'app-dashboard',
  templateUrl: './dashboard.component.html',
  styleUrls: ['../app.component.scss', './dashboard.component.scss'],
  encapsulation: ViewEncapsulation.None
})
export class DashboardComponent implements OnInit, AfterViewInit {
  loginuser: any = {};
  imgSrc: any = {};
  users: any[] = [];
  imageToShow: any;
  public dataSource = new MatTableDataSource<User>();
  displayedColumns = ['id', 'username', 'email', 'firstname', 'lastname', 'registeredDate', 'enabled'];
  @ViewChild(MatPaginator) paginator: MatPaginator;
  @ViewChild(MatSort) sort: MatSort;
  constructor(private service: UserService, private http: HttpClient, private sanitizer: DomSanitizer) {
   this.loginuser = JSON.parse(localStorage.getItem('currentUser'));
   this.service.getAllUsers(this.loginuser.token).subscribe(u => {
   this.dataSource.data = u as User[];
   this.users = u;
  // console.log('user: ', this.users);
   });
 ngAfterViewInit() {
     this.dataSource.paginator = this.paginator;
   this.dataSource.sort = this.sort;
  }

 }
</code>```

Body:
I have a mat-table that has a list of users called from a database using a spring REST API which works perfectly but when I wanted to add a paginator to help go through the whole list of users I started getting a "this.container is undefined" error when trying to click on the paginator.

Also, for some reason It showing "Items per page: 5" only even though I have almost 27 users.

Here's my html code:

<mat-form-field>
  <input matInput (keyup)="applyFilter($event.target.value)" placeholder="Filter" style="width: 500px !important">
</mat-form-field>
        <mat-table class="lessons-table mat-elevation-z8" [dataSource]="dataSource">
            <ng-container matColumnDef="id" class=".mat-column-id">
                <mat-header-cell *matHeaderCellDef>#</mat-header-cell>
                <mat-cell *matCellDef="let user">{{user.id}}</mat-cell>
            </ng-container>
            <ng-container matColumnDef="username" class=".mat-column-username">
                <mat-header-cell *matHeaderCellDef>Username</mat-header-cell>
                <mat-cell class="description-cell" *matCellDef="let user">{{user.username}}</mat-cell>
            </ng-container>
            <ng-container matColumnDef="email" class=".mat-column-email">
                <mat-header-cell *matHeaderCellDef>Email</mat-header-cell>
                <mat-cell class="duration-cell" *matCellDef="let user">{{user.email}}</mat-cell>
            </ng-container>
            <ng-container matColumnDef="firstname" class=".mat-column-name">
                <mat-header-cell *matHeaderCellDef>firstname</mat-header-cell>
                <mat-cell class="duration-cell" *matCellDef="let user">{{user.firstName}}</mat-cell>
            </ng-container>
            <ng-container matColumnDef="lastname"class=".mat-column-name">
                <mat-header-cell *matHeaderCellDef>Last Name</mat-header-cell>
                <mat-cell class="duration-cell" *matCellDef="let user">{{user.lastName}}</mat-cell>
            </ng-container>
            <ng-container matColumnDef="enabled" class=".mat-column-enabled">
                <mat-header-cell *matHeaderCellDef>Enabled</mat-header-cell>
                <mat-cell class="duration-cell" *matCellDef="let user">{{user.enabled}}</mat-cell>
            </ng-container>
            <ng-container matColumnDef="registeredDate" class=".mat-column-date">
                <mat-header-cell *matHeaderCellDef>Registered Date</mat-header-cell>
                <mat-cell class="duration-cell" *matCellDef="let user">{{user.registeredDate | date: shortDate}}</mat-cell>
            </ng-container>
            <mat-header-row *matHeaderRowDef="displayedColumns; sticky: true"></mat-header-row>
            <mat-row class="mat-row" *matRowDef="let row; columns: displayedColumns" (click)="onRowClicked(row)"></mat-row>
        </mat-table>
        <mat-paginator [pageSizeOptions]="[5, 10, 25, 100]"></mat-paginator>

and the ts file:

import { Component, OnInit, ViewChild } from '@angular/core';
import { ViewEncapsulation } from '@angular/core';
import { HttpClient, HttpHeaders } from '@angular/common/http';
import { UserService } from '../user.service';
import { MatDialog, MatDialogConfig, MatTableDataSource, MatPaginator, MatSort } from '@angular/material';
import { NewDialogComponent } from '../new-dialog/new-dialog.component';
import { DomSanitizer } from '@angular/platform-browser';
import { map } from 'rxjs-compat/operator/map';
import { Observable, Observer } from 'rxjs';

@Component({
  selector: 'app-dashboard',
  templateUrl: './dashboard.component.html',
  styleUrls: ['../app.component.scss', './dashboard.component.scss'],
  encapsulation: ViewEncapsulation.None
})
export class DashboardComponent implements OnInit {
  loginuser: any = {};
  imgSrc: any = {};
  users: any[] = [];
  imageToShow: any;
  public dataSource = new MatTableDataSource<User>();
  displayedColumns = ['id', 'username', 'email', 'firstname', 'lastname', 'registeredDate', 'enabled'];
  @ViewChild(MatPaginator) paginator: MatPaginator;
  @ViewChild(MatSort) sort: MatSort;
  constructor(private service: UserService, private http: HttpClient, private sanitizer: DomSanitizer) {
   this.loginuser = JSON.parse(localStorage.getItem('currentUser'));
   this.service.getAllUsers(this.loginuser.token).subscribe(u => {
   this.dataSource.data = u as User[];
   this.users = u;
  // console.log('user: ', this.users);
   });
   this.dataSource.paginator = this.paginator;
   this.dataSource.sort = this.sort;
 }

 ngOnInit() {
 }

 applyFilter(filterValue: string) {
   this.dataSource.filter = filterValue.trim().toLowerCase();
   if (this.dataSource.paginator) {
   this.dataSource.paginator.firstPage();
   }
 }
}

Body:
The value of this injected member variable is not immediately available at component construction time!

Angular will fill in this property automatically, but only later in the component lifecycle, after the view initialization is completed.

If we want to write component initialization code that uses the references injected by @ViewChild, we need to do it inside the AfterViewInit lifecycle hook.

@Component({
      selector: 'app-root',
      templateUrl: './app.component.html'
    })
    export class AppComponent implements  AfterViewInit {
      @ViewChild(SomeComponent)
      someComponent: SomeComponent;

      ngAfterViewInit() {
        console.log('Values on ngAfterViewInit():');
        console.log("someComponent:", this.someComponent);
      }

    }

In Your case just put these two line in NgAfterViewInit LifeCyle as:

    import { Component, OnInit, ViewChild } from '@angular/core';
import { ViewEncapsulation } from '@angular/core';
import { HttpClient, HttpHeaders } from '@angular/common/http';
import { UserService } from '../user.service';
import { MatDialog, MatDialogConfig, MatTableDataSource, MatPaginator, MatSort } from '@angular/material';
import { NewDialogComponent } from '../new-dialog/new-dialog.component';
import { DomSanitizer } from '@angular/platform-browser';
import { map } from 'rxjs-compat/operator/map';
import { Observable, Observer } from 'rxjs';

@Component({
  selector: 'app-dashboard',
  templateUrl: './dashboard.component.html',
  styleUrls: ['../app.component.scss', './dashboard.component.scss'],
  encapsulation: ViewEncapsulation.None
})
export class DashboardComponent implements OnInit, AfterViewInit {
  loginuser: any = {};
  imgSrc: any = {};
  users: any[] = [];
  imageToShow: any;
  public dataSource = new MatTableDataSource<User>();
  displayedColumns = ['id', 'username', 'email', 'firstname', 'lastname', 'registeredDate', 'enabled'];
  @ViewChild(MatPaginator) paginator: MatPaginator;
  @ViewChild(MatSort) sort: MatSort;
  constructor(private service: UserService, private http: HttpClient, private sanitizer: DomSanitizer) {
   this.loginuser = JSON.parse(localStorage.getItem('currentUser'));
   this.service.getAllUsers(this.loginuser.token).subscribe(u => {
   this.dataSource.data = u as User[];
   this.users = u;
  // console.log('user: ', this.users);
   });
 ngAfterViewInit() {
     this.dataSource.paginator = this.paginator;
   this.dataSource.sort = this.sort;
  }

 }


问:
Writing output in a sub-process leads to error
Keras forces output to sys.stderr (for which a fix was rejected on GitHub). There seems to be a problem writing to system outputs from a child process in a Web App. This leads to my code throwing the appropriate error when attempting to inform about the backend implementation when Keras is imported.

AttributeError: 'NoneType' object has no attribute 'write'

I tried to redirect output to os.devnull according to this answer before instantiating a Flask application and starting it with a web.config. However, the error persisted. Curiously, writing output without multiprocessing worked just fine.

```<code>import sys
from flask import Flask
import keras

app = Flask(__name__)

@app.route('/')
def main():
    print('Hello!')
    sys.stdout.write('test\n')
    sys.stderr.write('emsg\n')
    return 'OK.', 200
</code>```

Even from keras import backend as k works. That's the statement that originally produced the error. This left me baffled. What could possibly be the matter?

Minimal example

In my application, a sub process is spawned for training models. When trying to write output within the multiprocessing.Process, an error is thrown. Here's some code to reproduce the situation.

```<code>import sys
from flask import Flask
from multiprocessing import Process

def write_output():
    sys.stdout.write('hello\n')

def create_app():
    apl = Flask(__name__)
    Process(target=write_output).start()

    @apl.route('/')
    def main():
        return 'OK.', 200

    return apl
</code>```

This application is then instantiated in another file and called from web.config. Basic logging confirmed the error was still being thrown.

Almost a fix

Although not a fix, I got the system working using threading. By simply switching multiprocessing.Queue and Process to queue.Queue and threading.Thread, no errors like above are thrown. For my use case this is acceptable for now. Of course it's not a solution to the problem of writing output in a child process.

答:
I noticed that you mentioned the web.config file for Azure WebApp on Windows. And there is a limitation about Azure Web App sandbox you need to know. After I reviewed it with your scenario, I think your app was rejected by some restrictions. Per my experience, I think the task of trainning model is not suitable for running on Azure WebApp, especially for a Windows instance, even just on a sandbox based on CPU.

My suggestion is to move your app to a high-performace Azure VM with GPU, such as NC-series you can see from https://azure.microsoft.com/en-us/pricing/details/virtual-machines/linux/.

Otherwise, you may have other reason to use Azure WebApp for your app, I recommanded that you could try Azure WebApp for Linux based on Docker.

Hope it helps.

Body:
Keras forces output to sys.stderr (for which a fix was rejected on GitHub). There seems to be a problem writing to system outputs from a child process in a Web App. This leads to my code throwing the appropriate error when attempting to inform about the backend implementation when Keras is imported.

AttributeError: 'NoneType' object has no attribute 'write'

I tried to redirect output to os.devnull according to this answer before instantiating a Flask application and starting it with a web.config. However, the error persisted. Curiously, writing output without multiprocessing worked just fine.

import sys
from flask import Flask
import keras

app = Flask(__name__)

@app.route('/')
def main():
    print('Hello!')
    sys.stdout.write('test\n')
    sys.stderr.write('emsg\n')
    return 'OK.', 200

Even from keras import backend as k works. That's the statement that originally produced the error. This left me baffled. What could possibly be the matter?

Minimal example

In my application, a sub process is spawned for training models. When trying to write output within the multiprocessing.Process, an error is thrown. Here's some code to reproduce the situation.

import sys
from flask import Flask
from multiprocessing import Process

def write_output():
    sys.stdout.write('hello\n')

def create_app():
    apl = Flask(__name__)
    Process(target=write_output).start()

    @apl.route('/')
    def main():
        return 'OK.', 200

    return apl

This application is then instantiated in another file and called from web.config. Basic logging confirmed the error was still being thrown.

Almost a fix

Although not a fix, I got the system working using threading. By simply switching multiprocessing.Queue and Process to queue.Queue and threading.Thread, no errors like above are thrown. For my use case this is acceptable for now. Of course it's not a solution to the problem of writing output in a child process.


问:
Not Understanding C++ Memory Alignment
I understand that in C++, if we have a struct like this:

```<code>struct x_
{
   char a;     // 1 byte
   int b;      // 4 bytes
   short c;    // 2 bytes
   char d;     // 1 byte
} MyStruct;
</code>```

Memory structure will look like this due to compiler padding:

```<code>struct x_
{
   char a;            // 1 byte
   char _pad0[3];     // padding to put 'b' on 4-byte boundary
   int b;            // 4 bytes
   short c;          // 2 bytes
   char d;           // 1 byte
   char _pad1[1];    // padding to make sizeof(x_) multiple of 4
}
</code>```

Can somebody please help me understand why sizeof(x_) must be a multiple of 4, and not any other number?

答:
At least, a class must have the same alignment largest alignment of any of its non-static data member. So x_ must be aligned as b. If x_ had a lower alignment requirement, then b could be misaligned. Imagine an object x_ at address 3 then its b member would also be at an address 3+alignof(int). If alignof(int)==4 then b would be at address 7, so it would be misaligned. So following this example, alignof(x_)==4;

Then the size of an object must be a multiple of the alignment because elements of an array are required to be contiguous: a pointer to the end of element n must be a pointer to the element n+1. So in your case x size must be a multiple of 4.

Title: Not Understanding C++ Memory Alignment

Body:
I understand that in C++, if we have a struct like this:

struct x_
{
   char a;     // 1 byte
   int b;      // 4 bytes
   short c;    // 2 bytes
   char d;     // 1 byte
} MyStruct;

Memory structure will look like this due to compiler padding:

struct x_
{
   char a;            // 1 byte
   char _pad0[3];     // padding to put 'b' on 4-byte boundary
   int b;            // 4 bytes
   short c;          // 2 bytes
   char d;           // 1 byte
   char _pad1[1];    // padding to make sizeof(x_) multiple of 4
}

Can somebody please help me understand why sizeof(x_) must be a multiple of 4, and not any other number?


问:
Python, BeautifulSoup - Can't get specific element's text without its siblings as well
I'm a bit of a novice here, so please forgive my ignorance. I'm trying to get a line of code to return just on specific tag's elements. The problem is, my approaches yield these respective results...:

```<code>for items in soup.find('td', text='Trading Symbol').parent.find_all('td'):
ticker = [items.text.strip()]
print(ticker)

['Trading Symbol']
['AAPL']
['']
</code>```

and

```<code>    for items in soup.find('td', text='Trading Symbol').parent.find_all('td'):
    for td in items.find('td', {'class':['text']}):
        ticker = [td.text.strip()]
        print(ticker)

....error message....for td in items.find('td', {'class':['text']}):
    TypeError: 'NoneType' object is not iterable
</code>```

I understand why the first code does what it does-I've not specified exactly what I'm after (the stock ticker AAPL), but I don't know why adding one additional line of code specifying the class doesn't narrow the list down. By looking at the soup (which I've provided below) I figure the additional line of code would remove 'Trading Symbol' and leave 'AAPL' and '[]' but it comes up with nothing. Any help here?

Here's the soup. There are hundreds of "re" class tags so filtering using that may be helpful but it won't be the end-all.

```<code>##      <tr class="re">
##      <td class="pl " style="border-bottom: 0px;" valign="top"><a class="a" href="javascript:void(0);" onclick="top.Show.showAR( this, 'defref_dei_TradingSymbol', window );">Trading Symbol</a></td>
##      <td class="text">AAPL<span></span>
##      </td>
</code>```

答:
You are already at the level of td.
If you want the code snippet to work try </p>

```<code>for td in items.parent.find('td', {'class':['text']}):
</code>```

Body:
I'm a bit of a novice here, so please forgive my ignorance. I'm trying to get a line of code to return just on specific tag's elements. The problem is, my approaches yield these respective results...:

for items in soup.find('td', text='Trading Symbol').parent.find_all('td'):
ticker = [items.text.strip()]
print(ticker)

['Trading Symbol']
['AAPL']
['']

and

    for items in soup.find('td', text='Trading Symbol').parent.find_all('td'):
    for td in items.find('td', {'class':['text']}):
        ticker = [td.text.strip()]
        print(ticker)

....error message....for td in items.find('td', {'class':['text']}):
    TypeError: 'NoneType' object is not iterable

I understand why the first code does what it does-I've not specified exactly what I'm after (the stock ticker AAPL), but I don't know why adding one additional line of code specifying the class doesn't narrow the list down. By looking at the soup (which I've provided below) I figure the additional line of code would remove 'Trading Symbol' and leave 'AAPL' and '[]' but it comes up with nothing. Any help here?

Here's the soup. There are hundreds of "re" class tags so filtering using that may be helpful but it won't be the end-all.

##

##      Trading Symbol
##      AAPL
##

Body:
You are already at the level of td.
If you want the code snippet to work try

for td in items.parent.find('td', {'class':['text']}):


问:
How to play video in HTML page
I am trying to play a mp4 video on my HTML page, I have searched the web and found that in HTML5 I can do this with video tag like this below

```<code><video width="320" height="240" autoplay>
  <source src="movie.mp4" type="video/mp4">
</video>
</code>```

Issue I am facing

My main issue is my video is stored in my local computer in some location, So how can I call that from that path

In my system it is located in D drive so I want to call it from there

I am new to this so I don't know if I am doing it the right way; is my approach correct?

My requirement is to auto-play video on my web page

I am doing like this

```<code><video width="320" height="240" autoplay>
  <source src="D:\Video\samplevideo.mp4" type="video/mp4">
</video>
</code>```

D:\Video\samplevideo.mp4 is the path of my file and samplevideo.mp4 is the name of the video

On Chrome it show error Not allowed to load local resource: file:///D:/Video/samplevideo.mp4

And on Firefox All candidate resources failed to load. Media load paused.

Edit

My main focus is to play video on webpage.

I need to play a video on the web (HTML page) when page is loaded I have that video in my system at D:\Video\samplevideo.mp4 this path, how can I play that video when page is loaded.

答:
Can you try this

```<code><video width="320" height="240" controls>
  <source src="movie.mp4" type="video/mp4">
  <source src="movie.ogg" type="video/ogg">
Your browser does not support the video tag.
</video>
</code>```

Also follow this link for more info.

http://mrbool.com/how-to-add-and-play-videos-in-html/26171

Title: How to play video in HTML page

Body:
I am trying to play a mp4 video on my HTML page, I have searched the web and found that in HTML5 I can do this with video tag like this below

<video width="320" height="240" autoplay>
  <source src="movie.mp4" type="video/mp4">
</video>

Issue I am facing

My main issue is my video is stored in my local computer in some location, So how can I call that from that path

In my system it is located in D drive so I want to call it from there

I am new to this so I don't know if I am doing it the right way; is my approach correct?

My requirement is to auto-play video on my web page

I am doing like this

<video width="320" height="240" autoplay>
  <source src="D:\Video\samplevideo.mp4" type="video/mp4">
</video>

D:\Video\samplevideo.mp4 is the path of my file and samplevideo.mp4 is the name of the video

On Chrome it show error Not allowed to load local resource: file:///D:/Video/samplevideo.mp4

And on Firefox All candidate resources failed to load. Media load paused.

Edit

My main focus is to play video on webpage.

I need to play a video on the web (HTML page) when page is loaded I have that video in my system at D:\Video\samplevideo.mp4 this path, how can I play that video when page is loaded.

Body:
Can you try this

<video width="320" height="240" controls>
  <source src="movie.mp4" type="video/mp4">
  <source src="movie.ogg" type="video/ogg">
Your browser does not support the video tag.
</video>

Also follow this link for more info.

http://mrbool.com/how-to-add-and-play-videos-in-html/26171


问:
UNDERSTANDING how to count trailing zeros for a number using bitwise operators in C
Note - This is NOT a duplicate of this question - Count the consecutive zero bits (trailing) on the right in parallel: an explanation? . The linked question has a different context, it only asks the purpose of signed() being use. DO NOT mark this question as duplicate.

I've been finding a way to acquire the number of trailing zeros in a number. I found a bit twiddling Stanford University Write up HERE here that gives the following explanation.

```<code>unsigned int v;      // 32-bit word input to count zero bits on right
unsigned int c = 32; // c will be the number of zero bits on the right
v &= -signed(v);
if (v) c--;
if (v & 0x0000FFFF) c -= 16;
if (v & 0x00FF00FF) c -= 8;
if (v & 0x0F0F0F0F) c -= 4;
if (v & 0x33333333) c -= 2;
if (v & 0x55555555) c -= 1;
</code>```

Why does this end up working ? I have an understanding of how Hex numbers are represented as binary and bitwise operators, but I am unable to figure out the intuition behind this working ? What is the working mechanism ?

答:
The code is broken (undefined behavior is present).  Here is a fixed version which is also slightly easier to understand (and probably faster):

```<code>uint32_t v;  // 32-bit word input to count zero bits on right
unsigned c;  // c will be the number of zero bits on the right
if (v) {
    v &= -v; // keep rightmost set bit (the one that determines the answer) clear all others
    c = 0;
    if (v & 0xAAAAAAAAu) c |= 1; // binary 10..1010
    if (v & 0xCCCCCCCCu) c |= 2; // binary 1100..11001100
    if (v & 0xF0F0F0F0u) c |= 4;
    if (v & 0xFF00FF00u) c |= 8;
    if (v & 0xFFFF0000u) c |= 16;
}
else c = 32;
</code>```

Once we know only one bit is set, we determine one bit of the result at a time, by simultaneously testing all bits where the result is odd, then all bits where the result has the 2's-place set, etc.

The original code worked in reverse, starting with all bits of the result set (after the if (c) c--;) and then determining which needed to be zero and clearing them.

Since we are learning one bit of the output at a time, I think it's more clear to build the output using bit operations not arithmetic.

Body:
Note - This is NOT a duplicate of this question - Count the consecutive zero bits (trailing) on the right in parallel: an explanation? . The linked question has a different context, it only asks the purpose of signed() being use. DO NOT mark this question as duplicate.

I've been finding a way to acquire the number of trailing zeros in a number. I found a bit twiddling Stanford University Write up HERE here that gives the following explanation.

unsigned int v;      // 32-bit word input to count zero bits on right
unsigned int c = 32; // c will be the number of zero bits on the right
v &= -signed(v);
if (v) c--;
if (v & 0x0000FFFF) c -= 16;
if (v & 0x00FF00FF) c -= 8;
if (v & 0x0F0F0F0F) c -= 4;
if (v & 0x33333333) c -= 2;
if (v & 0x55555555) c -= 1;

Why does this end up working ? I have an understanding of how Hex numbers are represented as binary and bitwise operators, but I am unable to figure out the intuition behind this working ? What is the working mechanism ?

Body:
The code is broken (undefined behavior is present).  Here is a fixed version which is also slightly easier to understand (and probably faster):

uint32_t v;  // 32-bit word input to count zero bits on right
unsigned c;  // c will be the number of zero bits on the right
if (v) {
    v &= -v; // keep rightmost set bit (the one that determines the answer) clear all others
    c = 0;
    if (v & 0xAAAAAAAAu) c |= 1; // binary 10..1010
    if (v & 0xCCCCCCCCu) c |= 2; // binary 1100..11001100
    if (v & 0xF0F0F0F0u) c |= 4;
    if (v & 0xFF00FF00u) c |= 8;
    if (v & 0xFFFF0000u) c |= 16;
}
else c = 32;

Once we know only one bit is set, we determine one bit of the result at a time, by simultaneously testing all bits where the result is odd, then all bits where the result has the 2's-place set, etc.

The original code worked in reverse, starting with all bits of the result set (after the if (c) c--;) and then determining which needed to be zero and clearing them.

Since we are learning one bit of the output at a time, I think it's more clear to build the output using bit operations not arithmetic.


问:
Efficient way to pass Bitmap into registered COM component
I have registered COM Class and interface written in .NET 2.0 . Now i am looking for a way to pass Bitmap object from WindowsForms .Net 4.5 application into COM component.

When i try to do this code:

```<code> Type type = Type.GetTypeFromCLSID(clsid);
 source = (IBaseFilter) Activator.CreateInstance(type);
        public void SetBitmap(Bitmap input)
        {
 IImageSourceFilter advSource = (IImageSourceFilter)source;
 advSource.SetBitmapObj(input);
        }
</code>```

I get next exception

```<code>    System.InvalidCastException
  HResult=0x80004002
  Message=Unable to cast COM object of type 'System.__ComObject' to class type 'System.Drawing.Bitmap'. Instances of types that represent COM components cannot be cast to types that do not represent COM components; however they can be cast to interfaces as long as the underlying COM component supports QueryInterface calls for the IID of the interface.
  Source=DShow
  StackTrace:
   at RTSPTestAPP.Camera.BMPtoCam.IImageSourceFilter.SetBitmapObj(Object inp)
   at RTSPTestAPP.Camera.BMPtoCam.SetBitmap(Bitmap input) in C:\Users\...\BMPtoCam.cs:line 43
</code>```

Passing it as byte array is not efficient and locates a lot CPU resources (and i am sending alot bitmaps from decoded videostream).

答: Found a way: i just develop COM component with same .net as program which will use it. Then on Type type = Type.GetTypeFromCLSID(clsid); i'll get not raw type (System.__ComObject), instead i`ll get correct interface, with correct methods. And i just pass bitmap as argument. Its important too add reference to this assembly too.

Body:
I have registered COM Class and interface written in .NET 2.0 . Now i am looking for a way to pass Bitmap object from WindowsForms .Net 4.5 application into COM component.

When i try to do this code:

 Type type = Type.GetTypeFromCLSID(clsid);
 source = (IBaseFilter) Activator.CreateInstance(type);
        public void SetBitmap(Bitmap input)
        {
 IImageSourceFilter advSource = (IImageSourceFilter)source;
 advSource.SetBitmapObj(input);
        }

I get next exception

    System.InvalidCastException
  HResult=0x80004002
  Message=Unable to cast COM object of type 'System.__ComObject' to class type 'System.Drawing.Bitmap'. Instances of types that represent COM components cannot be cast to types that do not represent COM components; however they can be cast to interfaces as long as the underlying COM component supports QueryInterface calls for the IID of the interface.
  Source=DShow
  StackTrace:
   at RTSPTestAPP.Camera.BMPtoCam.IImageSourceFilter.SetBitmapObj(Object inp)
   at RTSPTestAPP.Camera.BMPtoCam.SetBitmap(Bitmap input) in C:\Users\...\BMPtoCam.cs:line 43

Passing it as byte array is not efficient and locates a lot CPU resources (and i am sending alot bitmaps from decoded videostream).


问:
NSDate date returns 2h less than it should
When i call <code>[NSDate date]</code> it returns 2 hours less than it should. I've checked my computer clock settings and they are all ok. I've checked settings in iPhone and time zone and clock are all OK. Even simulator shows correct time on top toolbar. But when I try to log current date it shows 2 hours less than it should. I ran out of ideas where to look. </p>

答: Look carefully at the output of the NSLog() statement. You will see that the output always contains the timezone using standard UTC. Therefore, the date is actually correct, taking into account the timezone. </p>

ContentLicense: CC BY-SA 3.0

Body: When i call [NSDate date] it returns 2 hours less than it should. I've checked my computer clock settings and they are all ok. I've checked settings in iPhone and time zone and clock are all OK. Even simulator shows correct time on top toolbar. But when I try to log current date it shows 2 hours less than it should. I ran out of ideas where to look.


问:
How to make a pop up alert while selecting a particular cell
I am trying to code in VBA for making a pop-up alert while selecting a particular cell, this is like a missing out of a mandatory field, it needs to display an alert for missed out cell while going on next cell </p>

```<code>Sub macro1(ByVal Target As Range)
If Range("F3").Value = "NWOO" Then
    If Not Intersect(Target, Range("E4:F4")) Is Nothing Then
        MsgBox "You have missed a cell " & Target.Address & vbCrLf & "Please input a number", vbInformation, "Kutools for Excel"
' Macro1 Macro
' Keyboard Shortcut: Ctrl+z
End If
End Sub
</code>```

答:
You're close, the code is good. However, you need to code in a SelectionChange event, which will be triggered when a sheet's range selection changes.

Place sub below in your sheet's module:

```<code>Private Sub Worksheet_SelectionChange(ByVal Target As Range)

If Range("F3").Value = "NWOO" Then
    If Not Intersect(Target, Range("E4:F4")) Is Nothing Then
        MsgBox "You have missed a cell " & Target.Address & vbCrLf & "Please input a number", vbInformation, "Kutools for Excel"
    End If
' Keyboard Shortcut: Ctrl+z
End If

End Sub

</code>```

For the keyboard shortcut you will probably be better off using Application.Undo than using SendKeys. SendKeys can be very unreliable.

Body:
I am trying to code in VBA for making a pop-up alert while selecting a particular cell, this is like a missing out of a mandatory field, it needs to display an alert for missed out cell while going on next cell

Sub macro1(ByVal Target As Range)
If Range("F3").Value = "NWOO" Then
    If Not Intersect(Target, Range("E4:F4")) Is Nothing Then
        MsgBox "You have missed a cell " & Target.Address & vbCrLf & "Please input a number", vbInformation, "Kutools for Excel"
' Macro1 Macro
' Keyboard Shortcut: Ctrl+z
End If
End Sub

Body:
You're close, the code is good. However, you need to code in a SelectionChange event, which will be triggered when a sheet's range selection changes.

Place sub below in your sheet's module:

Private Sub Worksheet_SelectionChange(ByVal Target As Range)

If Range("F3").Value = "NWOO" Then
    If Not Intersect(Target, Range("E4:F4")) Is Nothing Then
        MsgBox "You have missed a cell " & Target.Address & vbCrLf & "Please input a number", vbInformation, "Kutools for Excel"
    End If
' Keyboard Shortcut: Ctrl+z
End If

End Sub

For the keyboard shortcut you will probably be better off using Application.Undo than using SendKeys. SendKeys can be very unreliable.


问:
Need help on extracting and spliting url in to seperate variables
I have one raw input from end user in to a variable as below
javascript:DS('https://HS/v1/dev/A/Machinename/SNAPNAME','XXXXX')

I want to extract url from the above input.

I want to split the url using '/' in to seperate variables.

Input :

$DSURL = "javascript:DS('https://HS/v1/dev/A/Machinename/SNAPNAME','XXXXX')"

```<code>
[regex]$regex = '(?<=https:\/\/\HS\\/v1\/dev\/A\?t=)(.*)(?=' )'

$regex.Matches($DSURL).Value
</code>```

$1 = https://HS/v1/dev/A/Machinename/SNAPNAME
$2 = Machinename
$3 = SNAPNAME

But it is not working,
I think the regex used is wrong,
Please help

答:
I have managed to pull this and it is picking the output URL properly.

```<code>$text = "javascript:DS('https://HS/v1/dev/A/Machinename/SNAPNAME','XXXXX')"
($text | Select-String -Pattern @"
(?i)\b((?:https?://|www\d{0,3}[.]|[a-z0-9.\-]+[.][a-z]{2,4}/)(?:[^\s()<>]+|\(([^\s()<>]+|(\([^\s()<>]+\)))*\))+(?:\(([^\s()<>]+|(\([^\s()<>]+\)))*\)|[^\s`!()\[\]{};:'".,<>?«»“”‘’]))
"@).Matches.Value
</code>```

OUTPUT:

```<code>https://HS/v1/dev/A/Machinename/SNAPNAME','XXXXX
</code>```

Hope it helps.

Body:
I have one raw input from end user in to a variable as below
javascript:DS('https://HS/v1/dev/A/Machinename/SNAPNAME','XXXXX')

I want to extract url from the above input.

I want to split the url using '/' in to seperate variables.

Input :

$DSURL = "javascript:DS('https://HS/v1/dev/A/Machinename/SNAPNAME','XXXXX')"

[regex]$regex = '(?<=https:\/\/\HS\\/v1\/dev\/A\?t=)(.*)(?=' )'

$regex.Matches($DSURL).Value

$1 = https://HS/v1/dev/A/Machinename/SNAPNAME
$2 = Machinename
$3 = SNAPNAME

But it is not working,
I think the regex used is wrong,
Please help

Body:
I have managed to pull this and it is picking the output URL properly.

$text = "javascript:DS('https://HS/v1/dev/A/Machinename/SNAPNAME','XXXXX')"
($text | Select-String -Pattern @"
(?i)\b((?:https?://|www\d{0,3}[.]|[a-z0-9.\-]+[.][a-z]{2,4}/)(?:[^\s()<>]+|\(([^\s()<>]+|(\([^\s()<>]+\)))*\))+(?:\(([^\s()<>]+|(\([^\s()<>]+\)))*\)|[^\s`!()\[\]{};:'".,<>?«»“”‘’]))
"@).Matches.Value

OUTPUT:

https://HS/v1/dev/A/Machinename/SNAPNAME','XXXXX

Hope it helps.


问:
How to load a pickle file containing machine learning in c?
I need to load the sklearn model via pickle file in C. But I do not find how to do that. This is my code and my model:

```<code>import pandas
from sklearn import model_selection
from sklearn.linear_model import LogisticRegression
import pickle

url = "https://raw.githubusercontent.com/jbrownlee/Datasets/master/pima-indians-diabetes.data.csv"
names = ['preg', 'plas', 'pres', 'skin', 'test', 'mass', 'pedi', 'age', 'class']
dataframe = pandas.read_csv(url, names=names)
array = dataframe.values
X = array[:, 0:8]
Y = array[:, 8]
test_size = 0.33
seed = 7
X_train, X_test, Y_train, Y_test = model_selection.train_test_split(X, Y, test_size=test_size, random_state=seed)
# Fit the model on 33%
model = LogisticRegression()
model.fit(X_train, Y_train)
print(model.score(X_test, Y_test))
# save the model to disk
filename = 'finalized_model.sav'
pickle.dump(model, open(filename, 'wb'))
</code>```

I do not know how to do that. I would be grateful if you could help me, please.

答:
There are always workarounds, One such way could be

Write a python flask based API/microservice over your python code & call it in c using the LibCurl library. I've made an asumption that your test_data will be a single column csv file, All flask apps runs on localhost:5000 by default. I will suggest you to write your own app with proper requests for arguments if your data doesnt't look like this. This piece of code is for reference only.

```<code>#python flask code

from flask import Flask
app = Flask(__name__)

@app.route('/')
def your_model():
   test_data = pandas.read_csv('test_data.csv')
   model = pickle.load("your_model.pkl")
   pred_result = model.predict(test_data)
   return(pred_result)

app.run()

/* c code*/

CURL *hnd = curl_easy_init();

curl_easy_setopt(hnd, CURLOPT_CUSTOMREQUEST, "POST");
curl_easy_setopt(hnd, CURLOPT_URL, "http://localhost:5000/your_API_name");

struct curl_slist *headers = NULL;
test_data_as_json_string = {""};
headers = curl_slist_append(headers, "any_parameter: value");
headers = curl_slist_append(headers, "content-type: application/json");
curl_easy_setopt(hnd, CURLOPT_HTTPHEADER, headers);

curl_easy_setopt(hnd, CURLOPT_POSTFIELDS, test_data_as_json_string);

CURLcode ret = curl_easy_perform(hnd);
</code>```

This code too is for reference write your own c code or you can copy paste similar kind of code from Postman's code section while running the flask api.

Body:
I need to load the sklearn model via pickle file in C. But I do not find how to do that. This is my code and my model:

import pandas
from sklearn import model_selection
from sklearn.linear_model import LogisticRegression
import pickle

url = "https://raw.githubusercontent.com/jbrownlee/Datasets/master/pima-indians-diabetes.data.csv"
names = ['preg', 'plas', 'pres', 'skin', 'test', 'mass', 'pedi', 'age', 'class']
dataframe = pandas.read_csv(url, names=names)
array = dataframe.values
X = array[:, 0:8]
Y = array[:, 8]
test_size = 0.33
seed = 7
X_train, X_test, Y_train, Y_test = model_selection.train_test_split(X, Y, test_size=test_size, random_state=seed)
# Fit the model on 33%
model = LogisticRegression()
model.fit(X_train, Y_train)
print(model.score(X_test, Y_test))
# save the model to disk
filename = 'finalized_model.sav'
pickle.dump(model, open(filename, 'wb'))

I do not know how to do that. I would be grateful if you could help me, please.

Body:
There are always workarounds, One such way could be

Write a python flask based API/microservice over your python code & call it in c using the LibCurl library. I've made an asumption that your test_data will be a single column csv file, All flask apps runs on localhost:5000 by default. I will suggest you to write your own app with proper requests for arguments if your data doesnt't look like this. This piece of code is for reference only.

#python flask code

from flask import Flask
app = Flask(__name__)

@app.route('/')
def your_model():
   test_data = pandas.read_csv('test_data.csv')
   model = pickle.load("your_model.pkl")
   pred_result = model.predict(test_data)
   return(pred_result)

app.run()

/* c code*/

CURL *hnd = curl_easy_init();

curl_easy_setopt(hnd, CURLOPT_CUSTOMREQUEST, "POST");
curl_easy_setopt(hnd, CURLOPT_URL, "http://localhost:5000/your_API_name");

struct curl_slist *headers = NULL;
test_data_as_json_string = {""};
headers = curl_slist_append(headers, "any_parameter: value");
headers = curl_slist_append(headers, "content-type: application/json");
curl_easy_setopt(hnd, CURLOPT_HTTPHEADER, headers);

curl_easy_setopt(hnd, CURLOPT_POSTFIELDS, test_data_as_json_string);

CURLcode ret = curl_easy_perform(hnd);

This code too is for reference write your own c code or you can copy paste similar kind of code from Postman's code section while running the flask api.


问:
How to output Select Statement inside oracle Begin- End
basically  i am from MS SQL background but the situation is that i need to create a query in Oracle that has a temp table and inside Begin - End i m updating that table's row and at the end i want a select Statement to output that table.</p>

```<code>CREATE GLOBAL TEMPORARY TABLE temp_users (
   id number(5)  NOT NULL,
   name varchar2(50)  NOT NULL,
   surname varchar2(50)  NOT NULL ) ON COMMIT DELETE ROWS;

Declare
dd varchar(400);
Begin

    INSERT INTO temp_users VALUES (1, 'John', 'Smith');
    INSERT INTO temp_users VALUES (2, 'Anne', 'Parker');
    INSERT INTO temp_users VALUES (3, 'Kate', 'Doe');
    INSERT INTO temp_users VALUES (1, 'John', 'Smith');
    INSERT INTO temp_users VALUES (2, 'Anne', 'Parker');
    INSERT INTO temp_users VALUES (3, 'Kate', 'Doe');

    // this code i have used to return the table
     execute immediate'SELECT * FROM temp_users';

     execute immediate 'drop table temp_users';

End;
</code>```

答:
There are several options, you can either simply return everything using bulk collect into clause, like in this Oracle example and return it outside.

Or you can use PIPELINED clause, in which case you create a cursor and pipe it outside like:

FUNCTION some_fn
(
  in_1 IN NUMBER,
  in_2 IN VARCHAR2 DEFAULT NULL
)
RETURN some_table_type PIPELINED
[…]
FOR l_row IN c_some_cursor
      LOOP
        PIPE ROW(l_row);
 END LOOP;
```

In both cases you should declare table variable TYPE like here. Your function should (because function is probably what would suit you best) return that table variable type.

Body:
basically  i am from MS SQL background but the situation is that i need to create a query in Oracle that has a temp table and inside Begin - End i m updating that table's row and at the end i want a select Statement to output that table.

CREATE GLOBAL TEMPORARY TABLE temp_users (
   id number(5)  NOT NULL,
   name varchar2(50)  NOT NULL,
   surname varchar2(50)  NOT NULL ) ON COMMIT DELETE ROWS;

Declare
dd varchar(400);
Begin

    INSERT INTO temp_users VALUES (1, 'John', 'Smith');
    INSERT INTO temp_users VALUES (2, 'Anne', 'Parker');
    INSERT INTO temp_users VALUES (3, 'Kate', 'Doe');
    INSERT INTO temp_users VALUES (1, 'John', 'Smith');
    INSERT INTO temp_users VALUES (2, 'Anne', 'Parker');
    INSERT INTO temp_users VALUES (3, 'Kate', 'Doe');

    // this code i have used to return the table
     execute immediate'SELECT * FROM temp_users';

     execute immediate 'drop table temp_users';

End;

Body:
There are several options, you can either simply return everything using bulk collect into clause, like in this Oracle example and return it outside.

Or you can use PIPELINED clause, in which case you create a cursor and pipe it outside like:

FUNCTION some_fn
(
  in_1 IN NUMBER,
  in_2 IN VARCHAR2 DEFAULT NULL
)
RETURN some_table_type PIPELINED
[…]
FOR l_row IN c_some_cursor
      LOOP
        PIPE ROW(l_row);
 END LOOP;

In both cases you should declare table variable TYPE like here. Your function should (because function is probably what would suit you best) return that table variable type.


问:
scrapy runspider: error: Unable to load 'WebHarvestSpider.py': cannot import name 'squeue' from 'scrapy'
I am trying to run a Scrapy spider with this command:

```<code>scrapy runspider -a main_url=https://www.imperium42.com WebHarvestSpider.py
</code>```

and I get this error:

```<code>Usage
=====
  scrapy runspider [options] <spider_file>

runspider: error: Unable to load 'WebHarvestSpider.py': cannot import name 'squeue' from 'scrapy' (Usage
=====
  scrapy runspider [options] <spider_file>

runspider: error: Unable to load 'WebHarvestSpider.py': cannot import name 'squeue' from 'scrapy' (/Users/jv/anaconda3/lib/python3.7/site-packages/scrapy/__init__.py)
)
</code>```

答:
scrapy.squeue was renamed to scrapy.squeues in Scrapy 1.0.

If the error comes from Scrapy itself, try reinstalling the latest version of Scrapy.

If you are importing scrapy.squeue in your code, you need to update your code. See the Scrapy changelog for a complete history of Scrapy API changes.

Body:
I am trying to run a Scrapy spider with this command:

scrapy runspider -a main_url=https://www.imperium42.com WebHarvestSpider.py

and I get this error:

Usage
=====
  scrapy runspider [options] <spider_file>

runspider: error: Unable to load 'WebHarvestSpider.py': cannot import name 'squeue' from 'scrapy' (Usage
=====
  scrapy runspider [options] <spider_file>

runspider: error: Unable to load 'WebHarvestSpider.py': cannot import name 'squeue' from 'scrapy' (/Users/jv/anaconda3/lib/python3.7/site-packages/scrapy/__init__.py)
)


问:
Deinstalling OpenCL under Ubuntu
I am writing a short tutorial about OpenCL under Ubuntu with the NVIDIA SDK, so I think a short passage aboutHow to get rid of it?! would be appropriate.

So would it be sufficient

to change the driver to a 'standard' driver via the Menu -> System Preferences -> Additional Driver and

to delete the folder with the SDK, aka $(HOME)/NVIDIA_GPU_Computing_SDK?

Would you recommend deleting all the OpenCL files in /usr/lib(32) and user/local as well? Is there something, which I have overlooked?

Cheers

答:
The Getting Started Guide (PDF; for Linux) explains that you can uninstall the SDK by just deleting the directory.

Note that the "standard" NVIDIA driver also comes with CUDA and OpenCL libraries. I would not delete these manually when attempting to de-install a development version of the driver. As far as I know, when you install an NVIDIA driver, it will automatically de-install older / other versions of the driver; you shouldn't need to do anything manually.

Title: Deinstalling OpenCL under Ubuntu


问:
Conditional (Dynamic) Struct Tags
I'm trying to parse some xml documents in Go. I need to define a few structs for this purpose, and my struct tags depend on a certain condition.

Imagine the following code (even though I know it won't work)

```<code>if someCondition {
    type MyType struct {
        // some common fields
        Date    []string `xml:"value"`
    }
} else {
    type MyType struct {
        // some common fields
        Date    []string `xml:"anotherValue"`
    }
}

var t MyType
// do the unmarshalling ...
</code>```

The problem is that these two structs have lots of fields in common. The only difference is in one of the fields and I want to prevent duplication. How can I solve this problem?

答:
As already indicated, you must duplicate the field. The question is where the duplication should exist.

If it's just a single field of many, one option is to use embedding, and field shadowing:

```<code>type MyType struct {
    Date    []string `xml:"value"`
    // many other fields
}
</code>```

Then when Date uses the other field name:

```<code>type MyOtherType struct {
    MyType // Embed the original type for all other fields
    Date     []string `xml:"anotherValue"`
}
</code>```

Then after unmarshaling of MyOtherType, it's easy to move the Date value into the original struct:

```<code>type data MyOtherType
err := json.Unmarshal(..., &data)
data.MyType.Date = data.Date
return data.MyType // will of MyType, and fully populated
</code>```

Note that this only works for unmarshaling. If you need to also marshal this data, a similar trick can be used, but the mechanics around it must be essentially reversed.

Title: Conditional (Dynamic) Struct Tags

Body:
I'm trying to parse some xml documents in Go. I need to define a few structs for this purpose, and my struct tags depend on a certain condition.

Imagine the following code (even though I know it won't work)

if someCondition {
    type MyType struct {
        // some common fields
        Date    []string `xml:"value"`
    }
} else {
    type MyType struct {
        // some common fields
        Date    []string `xml:"anotherValue"`
    }
}

var t MyType
// do the unmarshalling ...

The problem is that these two structs have lots of fields in common. The only difference is in one of the fields and I want to prevent duplication. How can I solve this problem?

Body:
As already indicated, you must duplicate the field. The question is where the duplication should exist.

If it's just a single field of many, one option is to use embedding, and field shadowing:

type MyType struct {
    Date    []string `xml:"value"`
    // many other fields
}

Then when Date uses the other field name:

type MyOtherType struct {
    MyType // Embed the original type for all other fields
    Date     []string `xml:"anotherValue"`
}

Then after unmarshaling of MyOtherType, it's easy to move the Date value into the original struct:

type data MyOtherType
err := json.Unmarshal(..., &data)
data.MyType.Date = data.Date
return data.MyType // will of MyType, and fully populated

Note that this only works for unmarshaling. If you need to also marshal this data, a similar trick can be used, but the mechanics around it must be essentially reversed.


问:
calling serial.read from other function
I'm trying to connect python with Arduino code using serial but I cannot call serial.read() within the led_on_off() function.

This is the Arduino code:

```<code>int led=13;
int val=0;
char functionname='K';
#include <string.h>
void setup()
   {
      Serial.begin(9600);
      pinMode(led, OUTPUT);
      digitalWrite (led, LOW);
      Serial.println("Connection established...");
   }

void loop()
{

    functionname = Serial.read();
 if (functionname= 'L')
  {
    led_on_off();
    }

 }//void loop
void led_on_off()
{
  val=Serial.read()
  if (val= 1)
  digitalWrite(led,HIGH)
  else if (val == 0)
  digitalWrite(led,LOW)
}
</code>```

And this is the python code:

```<code>import serial

Arduino_Serial = serial.Serial('com18',9600)  # Create Serial port object called arduinoSerialData
print(Arduino_Serial.readline())             # read the serial data and print it as line
print("Enter L to ON LED and M dc motor")

input_data = input()
Arduino_Serial.write(input_data.encode())
print(Arduino_Serial.readline())
input_value=input("enter 1 or 0")
Arduino_Serial.write(input_value.encode())
</code>```

my expectation is to get input (1 or 0) from python code and process it within the led_on_off function in Arduino code using the serial.read() function and turn on or off the led at pin 13.

答:
As already stated by @KIIV your Arduino code has some syntax errors. Besides that, you are sending a string from your Python script (input function) so you need to read it as a string on Arduino. Something like this would do the job:

Python script:

```<code>import serial

# Create Serial port object called arduinoSerialData
Arduino_Serial = serial.Serial('com18', 9600)
# read the serial data and print it as line
print(Arduino_Serial.readline())

input_data = input("Enter L to ON LED and M dc motor: ")
Arduino_Serial.write(input_data.encode())
print("Received Command:", Arduino_Serial.readline())
while True:
    input_value = input("enter 1 or 0")
    Arduino_Serial.write(input_value.encode())
</code>```

Arduino code:

```<code>int led = 13;

void setup()
{
    Serial.begin(9600);
    pinMode(led, OUTPUT);
    digitalWrite(led, LOW);
}

void loop()
{
    //void loop
    if (Serial.available())
    {
        String functionname = Serial.readString();
        if (functionname == "L")
        {
            Serial.println("Command received from Arduino!");
            while (1)
            {
                led_on_off();
            }
        }
    }
}
void led_on_off()
{
    if (Serial.available())
    {
        String val = Serial.readString();
        if (val == "1")
            digitalWrite(led, HIGH);
        else if (val == "0")
            digitalWrite(led, LOW);
    }
}
</code>```

Title: calling serial.read from other function

Body:
I'm trying to connect python with Arduino code using serial but I cannot call serial.read() within the led_on_off() function.

This is the Arduino code:

int led=13;
int val=0;
char functionname='K';
#include <string.h>
void setup()
   {
      Serial.begin(9600);
      pinMode(led, OUTPUT);
      digitalWrite (led, LOW);
      Serial.println("Connection established...");
   }

void loop()
{

    functionname = Serial.read();
 if (functionname= 'L')
  {
    led_on_off();
    }

 }//void loop
void led_on_off()
{
  val=Serial.read()
  if (val= 1)
  digitalWrite(led,HIGH)
  else if (val == 0)
  digitalWrite(led,LOW)
}

And this is the python code:

import serial

Arduino_Serial = serial.Serial('com18',9600)  # Create Serial port object called arduinoSerialData
print(Arduino_Serial.readline())             # read the serial data and print it as line
print("Enter L to ON LED and M dc motor")

input_data = input()
Arduino_Serial.write(input_data.encode())
print(Arduino_Serial.readline())
input_value=input("enter 1 or 0")
Arduino_Serial.write(input_value.encode())

my expectation is to get input (1 or 0) from python code and process it within the led_on_off function in Arduino code using the serial.read() function and turn on or off the led at pin 13.

Body:
As already stated by @KIIV your Arduino code has some syntax errors. Besides that, you are sending a string from your Python script (input function) so you need to read it as a string on Arduino. Something like this would do the job:

Python script:

import serial

# Create Serial port object called arduinoSerialData
Arduino_Serial = serial.Serial('com18', 9600)
# read the serial data and print it as line
print(Arduino_Serial.readline())

input_data = input("Enter L to ON LED and M dc motor: ")
Arduino_Serial.write(input_data.encode())
print("Received Command:", Arduino_Serial.readline())
while True:
    input_value = input("enter 1 or 0")
    Arduino_Serial.write(input_value.encode())

Arduino code:

int led = 13;

void setup()
{
    Serial.begin(9600);
    pinMode(led, OUTPUT);
    digitalWrite(led, LOW);
}

void loop()
{
    //void loop
    if (Serial.available())
    {
        String functionname = Serial.readString();
        if (functionname == "L")
        {
            Serial.println("Command received from Arduino!");
            while (1)
            {
                led_on_off();
            }
        }
    }
}
void led_on_off()
{
    if (Serial.available())
    {
        String val = Serial.readString();
        if (val == "1")
            digitalWrite(led, HIGH);
        else if (val == "0")
            digitalWrite(led, LOW);
    }
}


问:
How to put exception for .isalnum()?
I'm trying to remove the unwanted special symbols from my string in a list by using .isalnum() function in looping through each character in the words and I use the condition for putting exception for apostrophe symbol for cases, like "can't", "didn't", "won't". But it also keeps this symbol for the cases I don't need like " ' ", " 'cant", " 'hello' ". Is there a way to keep just for when the symbol is in the middle of the words?

data_set = "Hello WOrld &()*hello world ////dog /// cat world hello can't "

split_it = data_set.lower().split()
new_word = ''
new_list = list()
for word in split_it:
    new_word = ''.join([x for x in word if x.isalnum() or x == " ' "])
    new_list.append(new_word)

print(new_list)
```

['hello', 'world', 'hello', 'world', 'dog', '', 'cat', 'world', 'hello', "can't"]

答:
If you know all of the characters you don't want, you could use .strip() to only remove them from the start and end:

>>> words = "Hello WOrld &()*hello world ////dog /// cat world hello can't ".lower().split()
>>> cleaned_words = [word.strip("&()*/") for word in words]
>>> print(cleaned_words)
['hello', 'world', 'hello', 'world', 'dog', '', 'cat', 'world', 'hello', "can't"]
```

<p>Otherwise, you'll probably want a regexp that matches any character except those whitelisted, anchored to the start or end of the string, and then use <code>re.sub()</code> to remove them:</p>

```>>> import re
>>> nonalnum_at_edge_re = re.compile(r'^[^a-z0-9]+|[^a-z0-9]+$', re.I)
>>> cleaned_words = [re.sub(nonalnum_at_edge_re, '', word) for word in words]
['hello', 'world', 'hello', 'world', 'dog', '', 'cat', 'world', 'hello', "can't"]
```

Title: How to put exception for .isalnum()?

Body:
I'm trying to remove the unwanted special symbols from my string in a list by using .isalnum() function in looping through each character in the words and I use the condition for putting exception for apostrophe symbol for cases, like "can't", "didn't", "won't". But it also keeps this symbol for the cases I don't need like " ' ", " 'cant", " 'hello' ". Is there a way to keep just for when the symbol is in the middle of the words?

data_set = "Hello WOrld &()*hello world ////dog /// cat world hello can't "

split_it = data_set.lower().split()
new_word = ''
new_list = list()
for word in split_it:
    new_word = ''.join([x for x in word if x.isalnum() or x == " ' "])
    new_list.append(new_word)

print(new_list)

['hello', 'world', 'hello', 'world', 'dog', '', 'cat', 'world', 'hello', "can't"]

Body:
If you know all of the characters you don't want, you could use .strip() to only remove them from the start and end:

>>> words = "Hello WOrld &()*hello world ////dog /// cat world hello can't ".lower().split()
>>> cleaned_words = [word.strip("&()*/") for word in words]
>>> print(cleaned_words)
['hello', 'world', 'hello', 'world', 'dog', '', 'cat', 'world', 'hello', "can't"]

Otherwise, you'll probably want a regexp that matches any character except those whitelisted, anchored to the start or end of the string, and then use re.sub() to remove them:

>>> import re
>>> nonalnum_at_edge_re = re.compile(r'^[^a-z0-9]+|[^a-z0-9]+$', re.I)
>>> cleaned_words = [re.sub(nonalnum_at_edge_re, '', word) for word in words]
['hello', 'world', 'hello', 'world', 'dog', '', 'cat', 'world', 'hello', "can't"]


问:
Datatable is not working when there is data from DB
Jquery datatable plugin is not working when it has data that selected from database by date. But it's working if there is no data in table. Here some code

Select all data from database table in controller :

```<code>$inbound['inbound'] = DB::table('REPORT_INBOUND')
    ->where('regdate', '=', date('Y-m-d', strtotime("2019-05-21")))
    ->get();
return view('/traffic', $inbound, $outbound);
</code>```

And i did copy paste that necessary scripts for example :

```<code><link rel="stylesheet" href="https://cdn.datatables.net/1.10.19/css/dataTables.bootstrap4.min.css">

<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://cdn.datatables.net/1.10.19/js/jquery.dataTables.min.js"></script>
</code>```

```<code><table id="ahhhaa" width="90%" class="table table-striped table-bordered table-hover display">
            <thead class="thead-light">
            <tr>
                <th>ID</th>
                <th>RegDate</th>
                <th>HPMN Code</th>
                <th>Country</th>
                <th>HPMN Name</th>
            </tr>
            </head>
            <tbody>
            @foreach($inbound as $value)
                <tr class="table table-hover">
                    <td>{{ $value->id }}</td>
                    <td>{{ $value->regdate }}</td>
                    <td>{{ $value->hpmn_code }}</td>
                    <td>{{ $value->country }}</td>
                    <td>{{ $value->hpmn_name }}</td>
            @endforeach
            </tbody>
</table>
</code>```

```<code>$(document).ready(function () {
   $('#ahhhaa').DataTable()
});
</code>```

Is there any error ?

答:
Change the id of the table.Otherwise the laravel will not identify the table as a datatable.</p>

```<code><table id="datatable-buttons" class="table table-responsive">
</code>```

Body:
Jquery datatable plugin is not working when it has data that selected from database by date. But it's working if there is no data in table. Here some code

Select all data from database table in controller :

$inbound['inbound'] = DB::table('REPORT_INBOUND')
    ->where('regdate', '=', date('Y-m-d', strtotime("2019-05-21")))
    ->get();
return view('/traffic', $inbound, $outbound);

And i did copy paste that necessary scripts for example :

<link rel="stylesheet" href="https://cdn.datatables.net/1.10.19/css/dataTables.bootstrap4.min.css">

                ID
                RegDate
                HPMN Code
                Country
                HPMN Name

            @foreach($inbound as $value)

                    {{ $value->id }}
                    {{ $value->regdate }}
                    {{ $value->hpmn_code }}
                    {{ $value->country }}
                    {{ $value->hpmn_name }}
            @endforeach

$(document).ready(function () {
   $('#ahhhaa').DataTable()
});

Is there any error ?

Body:
Change the id of the table.Otherwise the laravel will not identify the table as a datatable.

<table id="datatable-buttons" class="table table-responsive">


问:
executing java command remotely via ssh fails with GC error
I've been attempting to execute a java application using SSH from a remote machine
but it quite doesn't work well :(

To execute this application on the local machine,
I wrote a shell script including java command, and it works okay on local.

So, I tried to execute this shell script remotely via ssh like below

```<code>ssh username@hostname execute.sh
</code>```

It seemed to worked out at first, but then result in the following error, and shutdown.

GC Warning: Repeated allocation of very large block (appr. size 929792): May lead to memory leak and poor performance.

GC Warning: Out of Memory! Returning NIL!

I understood what the message means reading this page ( http://www.hpl.hp.com/personal/Hans_Boehm/gc/debugging.html ),
yet, I have no idea how come this error occur only when I execute java command remotely.

Does anyone know anything about this?
Or, is there any better way to execute java command remotely
other than ssh?

Any idea or information will be greatly appreciated!

Regards,
May

java version: Java(TM) SE Runtime Environment (build 1.6.0_18-b07)

答: The only difference between exec'ing a command locally vs remotely would be the environmental variable setup. Please check that environment variables your program might be using (such as JAVA_HOME) are being set to expected values</p>

Body:
I've been attempting to execute a java application using SSH from a remote machine
but it quite doesn't work well :(

To execute this application on the local machine,
I wrote a shell script including java command, and it works okay on local.

So, I tried to execute this shell script remotely via ssh like below

ssh username@hostname execute.sh

It seemed to worked out at first, but then result in the following error, and shutdown.

GC Warning: Repeated allocation of very large block (appr. size 929792): May lead to memory leak and poor performance.

GC Warning: Out of Memory! Returning NIL!

I understood what the message means reading this page ( http://www.hpl.hp.com/personal/Hans_Boehm/gc/debugging.html ),
yet, I have no idea how come this error occur only when I execute java command remotely.

Does anyone know anything about this?
Or, is there any better way to execute java command remotely
other than ssh?

Any idea or information will be greatly appreciated!

Regards,
May

java version: Java(TM) SE Runtime Environment (build 1.6.0_18-b07)


问:
How can i find `SENDER ID` in firebase?
I am creating Push notification demo in ionic 2. I have tried to generate server key and sender key from firebase. i have follow this tutorial. but I can not found cloud messaging tab in my firebase project setting screen as shown bellow image and there is no Server key and sender Id.

I need SENDER ID for create push notification in my app as bellow,

cordova plugin add phonegap-plugin-push --variable SENDER_ID=12341234 --save

答: Login firebase account go to project Setting. Here you can get Sender Id

Title: How can i find `SENDER ID` in firebase?


问:
How to read content from a file and then save them in a file?
Not very good at programming. Need to change the script code. It is necessary to read the contents of the file and split it into separate keys, and then save them in a file. Thank you in advance for your help!!!

'text.txt'

File:

0200e7c810f4553fe1722522f8dcfc8e810757ef427efefef79bdf08ddf3700fd5
0216b3e68fed004b2fea2119cdbb8ab2393dfe8fc99398da18e40b6e949e9e1278
022bbf0fcde9bcba6e1038b78bd6906ed00be95d1a6f912a7352f5aca2d7bb6bbc
021060631ef4a610aebc3c9e24f5b0e33dcd0eb422b8223dbd75c1e6edfd21dd72
0218cbb66d6a417890aea6bf5f8a83a4d181a89c5aba8121e20def5b42c311514e
025d8ea956802ed00ebec42b480c0eb77c6ada6ed3fceb40e5fff9aed0fa31c6b4
02264a8c56551abeb68d6112863249857a4360c38528d02b9313988ba062e6efed

```<code>import binascii

with open('text.txt') as f:
    text = f.read()
compressed_key_hex = text.split('\n')

computed_uncompressed_key = []

p_hex = 'FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEFFFFFC2F'
p = int(p_hex, 16)
x_hex = compressed_key_hex[2:66]
x = int(x_hex, 16)
prefix = compressed_key_hex[0:2]

y_square = (pow(x, 3, p)  + 7) % p
y_square_square_root = pow(y_square, (p+1)//4, p)
if prefix == "02":
    y = (-y_square_square_root) % p
else:
    y = y_square_square_root

computed_y_hex = hex(y)[2:66]
computed_uncompressed_key = "04" + x_hex + computed_y_hex

with open('result.txt', 'w') as f:
    f.write('\n'.join(computed_uncompressed_key))
</code>```

I get the error:

```<code>===================== RESTART: D:\detailALL\03\Bit06.py =====================
Traceback (most recent call last):
  File "D:\detailALL\03\Bit06.py", line 12, in <module>
    x = int(x_hex, 16)
TypeError: int() can't convert non-string with explicit base
>>>
</code>```

答:
You are passing a list rather than a str. In the following code x_hex is a list.

```<code>x_hex = compressed_key_hex[2:66]
</code>```

So you need to convert the list to str, you can do that using the following:

```<code>x_hex = ''.join(compressed_key_hex[2:66])
</code>```

I guess the following might be your required solution:

```<code>import binascii

with open('text.txt') as f:
    text = f.read()
compressed_key_hex = text.split('\n')
print(compressed_key_hex)
computed_uncompressed_key_list = []
p_hex = 'FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEFFFFFC2F'
p = int(p_hex, 16)
for val in compressed_key_hex:
    x_hex = val[2:66]
    x = int(x_hex, 16)
    prefix = val[0:2]

    y_square = (pow(x, 3, p) + 7) % p
    y_square_square_root = pow(y_square, (p+1)//4, p)
    if prefix == "02":
        y = (-y_square_square_root) % p
    else:
        y = y_square_square_root

    computed_y_hex = hex(y)[2:66]
    computed_y_hex = computed_y_hex.zfill(64)
    computed_uncompressed_key = "04" + x_hex + computed_y_hex
    computed_uncompressed_key_list.append(computed_uncompressed_key)
with open('result.txt', 'w') as f:
    f.write('\n'.join(computed_uncompressed_key_list))
</code>```

text.txt file:

```<code>0200e7c810f4553fe1722522f8dcfc8e810757ef427efefef79bdf08ddf3700fd5
0216b3e68fed004b2fea2119cdbb8ab2393dfe8fc99398da18e40b6e949e9e1278
022bbf0fcde9bcba6e1038b78bd6906ed00be95d1a6f912a7352f5aca2d7bb6bbc
021060631ef4a610aebc3c9e24f5b0e33dcd0eb422b8223dbd75c1e6edfd21dd72
0218cbb66d6a417890aea6bf5f8a83a4d181a89c5aba8121e20def5b42c311514e
025d8ea956802ed00ebec42b480c0eb77c6ada6ed3fceb40e5fff9aed0fa31c6b4
02264a8c56551abeb68d6112863249857a4360c38528d02b9313988ba062e6efed
</code>```

result.txt file:

```<code>0400e7c810f4553fe1722522f8dcfc8e810757ef427efefef79bdf08ddf3700fd5c9b034d2aa9ee1ef7b2346e8fc9c0245a8746a92bfdbb472fc98397477551ced
0416b3e68fed004b2fea2119cdbb8ab2393dfe8fc99398da18e40b6e949e9e12780126dfa95d2d9ab8fc055ce158f1d2ef51c2a012413b3f88a6365f375cf903f8
042bbf0fcde9bcba6e1038b78bd6906ed00be95d1a6f912a7352f5aca2d7bb6bbcf4a39790075ce43dc08fbf0ecc9cc732415e6b066c3b8b8d960b8548e8a612b7
041060631ef4a610aebc3c9e24f5b0e33dcd0eb422b8223dbd75c1e6edfd21dd723f873c976d071939edf8450124da64c3d9a1b35fb070761b01a5bace7d741588
0418cbb66d6a417890aea6bf5f8a83a4d181a89c5aba8121e20def5b42c311514efb4f8645c503e7a39954e977f7af8e802a5ec44ce3084cb6fb4e133a79733e77
045d8ea956802ed00ebec42b480c0eb77c6ada6ed3fceb40e5fff9aed0fa31c6b4e7c279c9d2c3e731803a4dde91a0d9409e49b1cbec3c7ac536a3783d9518d737
04264a8c56551abeb68d6112863249857a4360c38528d02b9313988ba062e6efeddbd8a97a8762f6a1add1ea6f549b61316fe675fc703d49f597a91ad620f7627a
</code>```

Body:
Not very good at programming. Need to change the script code. It is necessary to read the contents of the file and split it into separate keys, and then save them in a file. Thank you in advance for your help!!!

'text.txt'

File:

0200e7c810f4553fe1722522f8dcfc8e810757ef427efefef79bdf08ddf3700fd5
0216b3e68fed004b2fea2119cdbb8ab2393dfe8fc99398da18e40b6e949e9e1278
022bbf0fcde9bcba6e1038b78bd6906ed00be95d1a6f912a7352f5aca2d7bb6bbc
021060631ef4a610aebc3c9e24f5b0e33dcd0eb422b8223dbd75c1e6edfd21dd72
0218cbb66d6a417890aea6bf5f8a83a4d181a89c5aba8121e20def5b42c311514e
025d8ea956802ed00ebec42b480c0eb77c6ada6ed3fceb40e5fff9aed0fa31c6b4
02264a8c56551abeb68d6112863249857a4360c38528d02b9313988ba062e6efed

import binascii

with open('text.txt') as f:
    text = f.read()
compressed_key_hex = text.split('\n')

computed_uncompressed_key = []

p_hex = 'FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEFFFFFC2F'
p = int(p_hex, 16)
x_hex = compressed_key_hex[2:66]
x = int(x_hex, 16)
prefix = compressed_key_hex[0:2]

y_square = (pow(x, 3, p)  + 7) % p
y_square_square_root = pow(y_square, (p+1)//4, p)
if prefix == "02":
    y = (-y_square_square_root) % p
else:
    y = y_square_square_root

computed_y_hex = hex(y)[2:66]
computed_uncompressed_key = "04" + x_hex + computed_y_hex

with open('result.txt', 'w') as f:
    f.write('\n'.join(computed_uncompressed_key))

I get the error:

===================== RESTART: D:\detailALL\03\Bit06.py =====================
Traceback (most recent call last):
  File "D:\detailALL\03\Bit06.py", line 12, in <module>
    x = int(x_hex, 16)
TypeError: int() can't convert non-string with explicit base
>>>

Body:
You are passing a list rather than a str. In the following code x_hex is a list.

x_hex = compressed_key_hex[2:66]

So you need to convert the list to str, you can do that using the following:

x_hex = ''.join(compressed_key_hex[2:66])

I guess the following might be your required solution:

import binascii

with open('text.txt') as f:
    text = f.read()
compressed_key_hex = text.split('\n')
print(compressed_key_hex)
computed_uncompressed_key_list = []
p_hex = 'FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEFFFFFC2F'
p = int(p_hex, 16)
for val in compressed_key_hex:
    x_hex = val[2:66]
    x = int(x_hex, 16)
    prefix = val[0:2]

    y_square = (pow(x, 3, p) + 7) % p
    y_square_square_root = pow(y_square, (p+1)//4, p)
    if prefix == "02":
        y = (-y_square_square_root) % p
    else:
        y = y_square_square_root

    computed_y_hex = hex(y)[2:66]
    computed_y_hex = computed_y_hex.zfill(64)
    computed_uncompressed_key = "04" + x_hex + computed_y_hex
    computed_uncompressed_key_list.append(computed_uncompressed_key)
with open('result.txt', 'w') as f:
    f.write('\n'.join(computed_uncompressed_key_list))

text.txt file:

0200e7c810f4553fe1722522f8dcfc8e810757ef427efefef79bdf08ddf3700fd5
0216b3e68fed004b2fea2119cdbb8ab2393dfe8fc99398da18e40b6e949e9e1278
022bbf0fcde9bcba6e1038b78bd6906ed00be95d1a6f912a7352f5aca2d7bb6bbc
021060631ef4a610aebc3c9e24f5b0e33dcd0eb422b8223dbd75c1e6edfd21dd72
0218cbb66d6a417890aea6bf5f8a83a4d181a89c5aba8121e20def5b42c311514e
025d8ea956802ed00ebec42b480c0eb77c6ada6ed3fceb40e5fff9aed0fa31c6b4
02264a8c56551abeb68d6112863249857a4360c38528d02b9313988ba062e6efed

result.txt file:

0400e7c810f4553fe1722522f8dcfc8e810757ef427efefef79bdf08ddf3700fd5c9b034d2aa9ee1ef7b2346e8fc9c0245a8746a92bfdbb472fc98397477551ced
0416b3e68fed004b2fea2119cdbb8ab2393dfe8fc99398da18e40b6e949e9e12780126dfa95d2d9ab8fc055ce158f1d2ef51c2a012413b3f88a6365f375cf903f8
042bbf0fcde9bcba6e1038b78bd6906ed00be95d1a6f912a7352f5aca2d7bb6bbcf4a39790075ce43dc08fbf0ecc9cc732415e6b066c3b8b8d960b8548e8a612b7
041060631ef4a610aebc3c9e24f5b0e33dcd0eb422b8223dbd75c1e6edfd21dd723f873c976d071939edf8450124da64c3d9a1b35fb070761b01a5bace7d741588
0418cbb66d6a417890aea6bf5f8a83a4d181a89c5aba8121e20def5b42c311514efb4f8645c503e7a39954e977f7af8e802a5ec44ce3084cb6fb4e133a79733e77
045d8ea956802ed00ebec42b480c0eb77c6ada6ed3fceb40e5fff9aed0fa31c6b4e7c279c9d2c3e731803a4dde91a0d9409e49b1cbec3c7ac536a3783d9518d737
04264a8c56551abeb68d6112863249857a4360c38528d02b9313988ba062e6efeddbd8a97a8762f6a1add1ea6f549b61316fe675fc703d49f597a91ad620f7627a


问:
Select a Generic Grouping (not static) of Cells
I have a current Excel Macro below which works great for one dataset:

```<code>Sub test_macro()
    Rows("1:1").Select
    Selection.Delete Shift:=xlUp
    Columns("A:A").Select
    Selection.TextToColumns Destination:=Range("A1"), DataType:=xlDelimited, _
        TextQualifier:=xlDoubleQuote, ConsecutiveDelimiter:=True, Tab:=False, _
        Semicolon:=False, Comma:=True, Space:=False, Other:=False, FieldInfo _
        :=Array(Array(1, 1), Array(2, 1), Array(3, 1), Array(4, 1), Array(5, 1), Array(6, 1), _
        Array(7, 1), Array(8, 1), Array(9, 1), Array(10, 1), Array(11, 1)), _
        TrailingMinusNumbers:=True
    Range("A1").Select
    Range(Selection, Selection.End(xlToRight)).Select
    Selection.Cut Destination:=Range("B1:K1")
    Columns("A:A").Select
    Selection.Delete Shift:=xlToLeft
End Sub
</code>```

The goal is to take a dataset that looks like this:

And transform it to this:

```<code>| COL1 | COL2 | COL3 | COL4 | COL5 | COL6 | COL7 | COL8 | COL9 | COL10 |
|------|------|------|------|------|------|------|------|------|-------|
| Foo1 | Foo2 | Foo3 | Foo4 | Foo5 | Foo6 | Foo7 | Foo8 | Foo9 | Foo10 |
</code>```

And this works great as is. However, the number of columns I have can change. Sometimes it is only 2 columns, sometimes it is up to 250 columns. Therefore, I am worried about the Range(Selection, Selection.End(xlToRight)).Select
    Selection.Cut Destination:=Range("B1:K1") portion of my macro, since it specifies the paste range to be B1:K1.

Therefore, How can I make that destination range generic? (I am simply shifting over row 1 by 1 to the right for every filled in cell in row 1).

答:
You should have a read on how to avoid using .Select... Otherwise I`m not sure if the number of the ",," commas can vary between your columns (in which case a better replace management needed), but as a working example based on your sample, the below should work on any number of columns/rows. See comments in code for some more details:

Option Explicit
Sub splitColumns()

With Application
    .ScreenUpdating = False
    .DisplayAlerts = False
End With

Dim databook As Workbook
Set databook = Application.Open("dummy_wip.xlsx") 'Can allocate directly to the variable on .Open

Dim ws As Worksheet: Set ws = databook.Worksheets("SheetName") 'Best to declare the worksheet objects too
Dim lRow As Long: lRow = ws.Cells(ws.Rows.Count, 1).End(xlUp).Row 'get the last row
Dim arrSplit() As String, strToSplit As String
Dim R As Long

With ws
    For R = 2 To lRow   'loop through all values
        strToSplit = Replace(.Cells(R, 1), ",,", ",") 'Replace 2 commas with 1... if you might have more than 2 at once, you will need a better replace
        If Left(strToSplit, 1) = "," Then strToSplit = Right(strToSplit, Len(strToSplit) - 1) 'Get rid of leading comma if any

        arrSplit = Split(strToSplit, ",") 'split the values at comma
        .Range(.Cells(R, 2), .Cells(R, UBound(arrSplit) + 2)) = arrSplit    'Allocate the values back to the spreadsheet in column B
    Next R
End With

With Application
    .ScreenUpdating = True
    .DisplayAlerts = True
End With

End Sub
```

Body:
I have a current Excel Macro below which works great for one dataset:

Sub test_macro()
    Rows("1:1").Select
    Selection.Delete Shift:=xlUp
    Columns("A:A").Select
    Selection.TextToColumns Destination:=Range("A1"), DataType:=xlDelimited, _
        TextQualifier:=xlDoubleQuote, ConsecutiveDelimiter:=True, Tab:=False, _
        Semicolon:=False, Comma:=True, Space:=False, Other:=False, FieldInfo _
        :=Array(Array(1, 1), Array(2, 1), Array(3, 1), Array(4, 1), Array(5, 1), Array(6, 1), _
        Array(7, 1), Array(8, 1), Array(9, 1), Array(10, 1), Array(11, 1)), _
        TrailingMinusNumbers:=True
    Range("A1").Select
    Range(Selection, Selection.End(xlToRight)).Select
    Selection.Cut Destination:=Range("B1:K1")
    Columns("A:A").Select
    Selection.Delete Shift:=xlToLeft
End Sub

The goal is to take a dataset that looks like this:

And transform it to this:

| COL1 | COL2 | COL3 | COL4 | COL5 | COL6 | COL7 | COL8 | COL9 | COL10 |
|------|------|------|------|------|------|------|------|------|-------|
| Foo1 | Foo2 | Foo3 | Foo4 | Foo5 | Foo6 | Foo7 | Foo8 | Foo9 | Foo10 |

And this works great as is. However, the number of columns I have can change. Sometimes it is only 2 columns, sometimes it is up to 250 columns. Therefore, I am worried about the Range(Selection, Selection.End(xlToRight)).Select
    Selection.Cut Destination:=Range("B1:K1") portion of my macro, since it specifies the paste range to be B1:K1.

Therefore, How can I make that destination range generic? (I am simply shifting over row 1 by 1 to the right for every filled in cell in row 1).


问:
Retrieving value using a nested variables in JMeter
I am writing a data driven test in JMeter, which has a JDBC request querying some book information.
I need to to randaomly pick 2 books of the list and inputs those items into a subsequent PUT request.

eg:
Book_1 and Book_10.

I have writing the following code in JSR223 PostProcessor:

```<code> log.info("Book count  : "+${IDs_#}); // COming from the JDBC Request from a
 DB

 upper = ${IDs_#};
 lower = 0;

 Random a = new Random();

 for (i=0;i<2;i++){
    //generating a random number between upper and lower

randNum =Math.abs( new Random().nextInt() % (upper - lower) ) + lower;

var ="Book_"+randNum;

    log.info("${var}");
</code>```

Var value would be "Book_10". I need to get ${Book_10}.
However when I enter log.info("${var}") it is considering it as String and not resolving the value of the variable.

I want it to resolve the value of ${Book_10}.

答: Please check if the below helps with your requirement:-

Body:
I am writing a data driven test in JMeter, which has a JDBC request querying some book information.
I need to to randaomly pick 2 books of the list and inputs those items into a subsequent PUT request.

eg:
Book_1 and Book_10.

I have writing the following code in JSR223 PostProcessor:

 log.info("Book count  : "+${IDs_#}); // COming from the JDBC Request from a
 DB

 upper = ${IDs_#};
 lower = 0;

 Random a = new Random();

 for (i=0;i<2;i++){
    //generating a random number between upper and lower

randNum =Math.abs( new Random().nextInt() % (upper - lower) ) + lower;

var ="Book_"+randNum;

    log.info("${var}");

Var value would be "Book_10". I need to get ${Book_10}.
However when I enter log.info("${var}") it is considering it as String and not resolving the value of the variable.

I want it to resolve the value of ${Book_10}.