问:
VBA | Regex | Matching fraction characters (e.g. 1/8, 3/8) in string
I have the following VBA regex code snippet, want to add ⅜ and ⅝ to the pattern but VBA editor does not recognize them (Showing "?" when I copy and paste).

Is there a way I can incorporate them? I imagine using Chr function might help but not sure how to put that in in a regex context.

```<code>Dim Reg As Object
Set Reg = = CreateObject("VBScript.RegExp")
Reg.Pattern = "([a-zA-Z0-9¾½]+)"
</code>```

Thanks!

答:
It is easy with hex representation of these symbols.

If you paste these ¾½ symbols into a Unicode char converter, you will get \u00BE\u00BD in the JavaScript field. Use them instead of the literal symbols.

You'd just use

```<code>"[a-zA-Z0-9\u00BE\u00BD]+"
</code>```

Note there is no need wrapping the whole pattern with a capturing group.

Another way is to use the values from the Decimal pane inthe ChrW$(i) function, but you will need to concat the strings:

```<code>"[a-zA-Z0-9" & ChrW$(190) & ChrW$(189) & "]+"
</code>```

Body:
I have the following VBA regex code snippet, want to add ⅜ and ⅝ to the pattern but VBA editor does not recognize them (Showing "?" when I copy and paste).

Is there a way I can incorporate them? I imagine using Chr function might help but not sure how to put that in in a regex context.

Dim Reg As Object
Set Reg = = CreateObject("VBScript.RegExp")
Reg.Pattern = "([a-zA-Z0-9¾½]+)"

Thanks!

Body:
It is easy with hex representation of these symbols.

If you paste these ¾½ symbols into a Unicode char converter, you will get \u00BE\u00BD in the JavaScript field. Use them instead of the literal symbols.

You'd just use

"[a-zA-Z0-9\u00BE\u00BD]+"

Note there is no need wrapping the whole pattern with a capturing group.

Another way is to use the values from the Decimal pane inthe ChrW$(i) function, but you will need to concat the strings:

"[a-zA-Z0-9" & ChrW$(190) & ChrW$(189) & "]+"


来源: stackexchange

问:
why do I get "Invalid appsecret_proof provided in the API argument"
Since the latest change on Facebook, regarding the appsecret_proof: https://developers.facebook.com/docs/reference/api/securing-graph-api/, we are still unable to download performance reports even after enabling/disabling features from Advanced Settings in our app, or apply the code as described in their document.

We are constantly getting this error:

{"error":{"message":"Invalid appsecret_proof provided in the API argument","type":"GraphMethodException","code":100}}

and I've open a confidential bug but no one returns to me with an answer.

I really don't know what more could we try?

答:
This is error is because of in correct token. It may be because you are using different account for configuring web app and mobile app for Facebook configuration. Both accounts should be same.

The app ID must be the same for your mobile app and your web app.

ContentLicense: CC BY-SA 3.0


问:
rxJs & angular 4 & restangular: stack errorInterceptors
In my angular 4 app I'm using ngx-restangular to handle all server calls. It returns observable as result, and this module has hooks to handle errors (like 401 etc).

But from documentation, i can handle 403 (401) so:

```<code>  RestangularProvider.addErrorInterceptor((response, subject, responseHandler) => {
    if (response.status === 403) {

      refreshAccesstoken()
      .switchMap(refreshAccesstokenResponse => {
        //If you want to change request or make with it some actions and give the request to the repeatRequest func.
        //Or you can live it empty and request will be the same.

        // update Authorization header
        response.request.headers.set('Authorization', 'Bearer ' + refreshAccesstokenResponse)

        return response.repeatRequest(response.request);
      })
      .subscribe(
        res => responseHandler(res),
        err => subject.error(err)
      );

      return false; // error handled
    }
    return true; // error not handled
  });
</code>```

and this is good for one request, which has broken with 403 error.
how can i stack this calls using rxJs? Becouse now, for example, i have 3 requests, which have 403 and for each this broken request I'm refreshing token - this is not so good, i have to update my token and then repeat all my broken requests. How can I achive this using Observables?

In angular 1 it was pretty easy:

```<code>Restangular.setErrorInterceptor(function (response, deferred, responseHandler) {
  if (response.status == 403) {
    // send only one request if multiple errors exist
    if (!refreshingIsInProgress) {
      refreshingIsInProgress = AppApi.refreshAccessToken(); // Returns promise
    }

    $q.when(refreshingIsInProgress, function () {
      refreshingIsInProgress = null;

      setHeaders(response.config.headers);

      // repeat request with error
      $http(response.config).then(responseHandler, deferred);
    }, function () {
      refreshingIsInProgress = null;

      $state.go('auth');
    });

    return false; // stop the promise chain
  }

  return true;
});
</code>```

And all was working like a charm. But I'm new to rxJs & angular 4 and I don't have any idea how to achive this with observables and angular 4. Maybe somebody have an idea?

upd!
here is my refreshAccesstoken method

```<code>const refreshAccesstoken = function () {
  const refreshToken = http.post(environment.apiURL + `/token/refresh`,
    {refreshToken: 'someToken'});
  return refreshToken;
};
</code>```

答:
One way I can see of doing this using ngx-restangular is to use the share operator. This way you don't have to implement complicated queueing logic. The idea is that if you have 3 requests all of the with a 403 response, they will all hit your interceptor and call your observable. If you share that observable, you will have only one token request for the 3 requests with a broken token.

You just have to use the share operator in your code like so:

```<code>refreshAccesstoken()
  .share()
  .switchMap(refreshAccesstokenResponse => {
    //If you want to change request or make with it some actions and give the request to the repeatRequest func.
    //Or you can live it empty and request will be the same.

    // update Authorization header
    response.request.headers.set('Authorization', 'Bearer ' + refreshAccesstokenResponse)

    return response.repeatRequest(response.request);
  })
  .subscribe(
    res => responseHandler(res),
    err => subject.error(err)
  );
</code>```

I haven't checked that the code actually works but I have used this approach before for the same use case, but instead of interceptors, I was using the angular HTTP service.

EDIT to change refreshAccessToken:

You need to wrap your refreshAccessToken method in a deferred Observable and share it. This way you will reuse the same observable every time.

In the constructor:

```<code>this.source = Observable.defer(() => {
        return this.refreshAccesstoken();
    }).share();
</code>```

Create another method that will invoke that observable:

```<code>refreshToken(): Observable<any> {
    return this.source
        .do((data) => {
            this.resolved(data);
        }, error => {
            this.resolved(error);
        });
}
</code>```

EDIT2

I have created a git repository which uses angular2 with restangular.
The scenario is the following:

In my app.component I'm making 3 concurrent requests to get a list of orders. When the request has finished, I will log "Orders received".

The orders endpoint requires an auth token. If one isn't provided it will return a 401.

In my app.module I set the base URL to my API only. Because I am not setting the authorization token as well, all of my requests will fail with a 401.

When the interceptor code is executed it will set the refresh token, which in my case is hard coded on the request and repeated the request.

The observable that returns the token logs "Getting token" each time it is executed.

Here is what I can see in my console:

If I remove the share operator I will get the following logs:

meaning that the observable will be created every time.

In order for this to work, it is important that the source is declared and created in the RestangularConfigFactory. It will essentially become a singleton object and that's what allows the Share operator to work.

NOTE:

I created a simple web API hosted locally for this project just because it was faster for me.

EDIT3:Update to include code to refresh the token:

@Injectable()
export class TokenRefreshService {
    source: Observable<any>;
    pausedObservable: Observable<any>;
    constructor(
        private authenthicationStore: AuthenticationStore,
        private router: Router,
        private authenticationDataService: AuthenticationDataService,
        private http: ObservableHttpService) {
        this.source = Observable.defer(() => {
            return this.postRequest();
        }).share();
    }

    refreshToken(): Observable<any> {
        return this.source
            .do((data) => {
                this.resolved(data);
            }, error => {
                this.resolved(error);
            });
    }

    public shouldRefresh(): boolean {
        if (this.getTime() < 0) {
            return true;
        }
        return false;
    }

    private postRequest(): Observable<any> {
        let authData = this.authenticationDataService.getAuthenticationData();
        if (authData == null) {
            return Observable.empty();
        }
        let data: URLSearchParams = new URLSearchParams();
        data.append('grant_type', 'refresh_token');

        let obs = this.http.postWithHeaders(
            'token', data, { 'Content-Type': 'application/x-www-form-urlencoded' })
            .map((response) => {
                return this.parseResult(true, response, 'authenticateUserResult');
            })
            .catch((error) => {
                let errorMessage = this.rejected(error);
                return Observable.throw(errorMessage);
            });
        return obs;
    }

    private rejected(failure) {
        let authenticateUserResult;
        let response = failure;
        let data = response.json();

        if (response &&
            response.status === 400 &&
            data &&
            data.error &&
            data.error === 'invalid_grant') {

            authenticateUserResult = this.parseResult(false, data, 'error_description');

            return authenticateUserResult;
        } else {
            return failure;
        }
    }

    private parseResult(success, data, resultPropertyName) {

        let authenticateResultParts = data[resultPropertyName].split(':');

        data.result = {
            success: success,
            id: authenticateResultParts[0],
            serverDescription: authenticateResultParts[1]
        };

        return data;
    }

    private resolved(data): void {
        let authenticationResult = data.result;
        if (authenticationResult && authenticationResult.success) {
            let authenticationData = this.createAuthenticationData(data);
            this.authenthicationStore.setUserData(authenticationData);
        } else {
            this.authenthicationStore.clearAll();
            this.router.navigate(['/authenticate/login']);
        }
    }

    private createAuthenticationData(data: any): AuthenticationData {
        let authenticationData = new AuthenticationData();
        authenticationData.access_token = data.access_token;
        authenticationData.token_type = data.token_type;
        authenticationData.username = data.username;
        authenticationData.friendlyName = data.friendlyName;

        return authenticationData;
    }

    private getTime(): number {
        return this.getNumberOfSecondsBeforeTokenExpires(this.getTicksUntilExpiration());
    }

    private getTicksUntilExpiration(): number {
        let authData = this.authenticationDataService.getAuthenticationData();
        if (authData) {
            return authData.expire_time;
        }
        return 0;
    }

    private getNumberOfSecondsBeforeTokenExpires(ticksWhenTokenExpires: number): number {
        let a;
        if (ticksWhenTokenExpires === 0) {
            a = new Date(new Date().getTime() + 1 * 60000);
        } else {
            a = new Date((ticksWhenTokenExpires) * 1000);
        }

        let b = new Date();
        let utc1 = Date.UTC(a.getFullYear(), a.getMonth(), a.getDate(), a.getHours(), a.getMinutes(), a.getSeconds());
        let utc2 = Date.UTC(b.getFullYear(), b.getMonth(), b.getDate(), b.getHours(), b.getMinutes(), b.getSeconds());

        let timeInSeconds = Math.floor((utc1 - utc2) / 1000);
        return timeInSeconds - 5;
    }
}```

Body:
In my angular 4 app I'm using ngx-restangular to handle all server calls. It returns observable as result, and this module has hooks to handle errors (like 401 etc).

But from documentation, i can handle 403 (401) so:

  RestangularProvider.addErrorInterceptor((response, subject, responseHandler) => {
    if (response.status === 403) {

      refreshAccesstoken()
      .switchMap(refreshAccesstokenResponse => {
        //If you want to change request or make with it some actions and give the request to the repeatRequest func.
        //Or you can live it empty and request will be the same.

        // update Authorization header
        response.request.headers.set('Authorization', 'Bearer ' + refreshAccesstokenResponse)

        return response.repeatRequest(response.request);
      })
      .subscribe(
        res => responseHandler(res),
        err => subject.error(err)
      );

      return false; // error handled
    }
    return true; // error not handled
  });

and this is good for one request, which has broken with 403 error.
how can i stack this calls using rxJs? Becouse now, for example, i have 3 requests, which have 403 and for each this broken request I'm refreshing token - this is not so good, i have to update my token and then repeat all my broken requests. How can I achive this using Observables?

In angular 1 it was pretty easy:

Restangular.setErrorInterceptor(function (response, deferred, responseHandler) {
  if (response.status == 403) {
    // send only one request if multiple errors exist
    if (!refreshingIsInProgress) {
      refreshingIsInProgress = AppApi.refreshAccessToken(); // Returns promise
    }

    $q.when(refreshingIsInProgress, function () {
      refreshingIsInProgress = null;

      setHeaders(response.config.headers);

      // repeat request with error
      $http(response.config).then(responseHandler, deferred);
    }, function () {
      refreshingIsInProgress = null;

      $state.go('auth');
    });

    return false; // stop the promise chain
  }

  return true;
});

And all was working like a charm. But I'm new to rxJs & angular 4 and I don't have any idea how to achive this with observables and angular 4. Maybe somebody have an idea?

upd!
here is my refreshAccesstoken method

const refreshAccesstoken = function () {
  const refreshToken = http.post(environment.apiURL + `/token/refresh`,
    {refreshToken: 'someToken'});
  return refreshToken;
};

Body:
One way I can see of doing this using ngx-restangular is to use the share operator. This way you don't have to implement complicated queueing logic. The idea is that if you have 3 requests all of the with a 403 response, they will all hit your interceptor and call your observable. If you share that observable, you will have only one token request for the 3 requests with a broken token.

You just have to use the share operator in your code like so:

refreshAccesstoken()
  .share()
  .switchMap(refreshAccesstokenResponse => {
    //If you want to change request or make with it some actions and give the request to the repeatRequest func.
    //Or you can live it empty and request will be the same.

    // update Authorization header
    response.request.headers.set('Authorization', 'Bearer ' + refreshAccesstokenResponse)

    return response.repeatRequest(response.request);
  })
  .subscribe(
    res => responseHandler(res),
    err => subject.error(err)
  );

I haven't checked that the code actually works but I have used this approach before for the same use case, but instead of interceptors, I was using the angular HTTP service.

EDIT to change refreshAccessToken:

You need to wrap your refreshAccessToken method in a deferred Observable and share it. This way you will reuse the same observable every time.

In the constructor:

this.source = Observable.defer(() => {
        return this.refreshAccesstoken();
    }).share();

Create another method that will invoke that observable:

refreshToken(): Observable<any> {
    return this.source
        .do((data) => {
            this.resolved(data);
        }, error => {
            this.resolved(error);
        });
}

EDIT2

I have created a git repository which uses angular2 with restangular.
The scenario is the following:

In my app.component I'm making 3 concurrent requests to get a list of orders. When the request has finished, I will log "Orders received".

The orders endpoint requires an auth token. If one isn't provided it will return a 401.

In my app.module I set the base URL to my API only. Because I am not setting the authorization token as well, all of my requests will fail with a 401.

When the interceptor code is executed it will set the refresh token, which in my case is hard coded on the request and repeated the request.

The observable that returns the token logs "Getting token" each time it is executed.

Here is what I can see in my console:

If I remove the share operator I will get the following logs:

meaning that the observable will be created every time.

In order for this to work, it is important that the source is declared and created in the RestangularConfigFactory. It will essentially become a singleton object and that's what allows the Share operator to work.

NOTE:

I created a simple web API hosted locally for this project just because it was faster for me.

EDIT3:Update to include code to refresh the token:

@Injectable()
export class TokenRefreshService {
    source: Observable<any>;
    pausedObservable: Observable<any>;
    constructor(
        private authenthicationStore: AuthenticationStore,
        private router: Router,
        private authenticationDataService: AuthenticationDataService,
        private http: ObservableHttpService) {
        this.source = Observable.defer(() => {
            return this.postRequest();
        }).share();
    }

    refreshToken(): Observable<any> {
        return this.source
            .do((data) => {
                this.resolved(data);
            }, error => {
                this.resolved(error);
            });
    }

    public shouldRefresh(): boolean {
        if (this.getTime() < 0) {
            return true;
        }
        return false;
    }

    private postRequest(): Observable<any> {
        let authData = this.authenticationDataService.getAuthenticationData();
        if (authData == null) {
            return Observable.empty();
        }
        let data: URLSearchParams = new URLSearchParams();
        data.append('grant_type', 'refresh_token');

        let obs = this.http.postWithHeaders(
            'token', data, { 'Content-Type': 'application/x-www-form-urlencoded' })
            .map((response) => {
                return this.parseResult(true, response, 'authenticateUserResult');
            })
            .catch((error) => {
                let errorMessage = this.rejected(error);
                return Observable.throw(errorMessage);
            });
        return obs;
    }

    private rejected(failure) {
        let authenticateUserResult;
        let response = failure;
        let data = response.json();

        if (response &&
            response.status === 400 &&
            data &&
            data.error &&
            data.error === 'invalid_grant') {

            authenticateUserResult = this.parseResult(false, data, 'error_description');

            return authenticateUserResult;
        } else {
            return failure;
        }
    }

    private parseResult(success, data, resultPropertyName) {

        let authenticateResultParts = data[resultPropertyName].split(':');

        data.result = {
            success: success,
            id: authenticateResultParts[0],
            serverDescription: authenticateResultParts[1]
        };

        return data;
    }

    private resolved(data): void {
        let authenticationResult = data.result;
        if (authenticationResult && authenticationResult.success) {
            let authenticationData = this.createAuthenticationData(data);
            this.authenthicationStore.setUserData(authenticationData);
        } else {
            this.authenthicationStore.clearAll();
            this.router.navigate(['/authenticate/login']);
        }
    }

    private createAuthenticationData(data: any): AuthenticationData {
        let authenticationData = new AuthenticationData();
        authenticationData.access_token = data.access_token;
        authenticationData.token_type = data.token_type;
        authenticationData.username = data.username;
        authenticationData.friendlyName = data.friendlyName;

        return authenticationData;
    }

    private getTime(): number {
        return this.getNumberOfSecondsBeforeTokenExpires(this.getTicksUntilExpiration());
    }

    private getTicksUntilExpiration(): number {
        let authData = this.authenticationDataService.getAuthenticationData();
        if (authData) {
            return authData.expire_time;
        }
        return 0;
    }

    private getNumberOfSecondsBeforeTokenExpires(ticksWhenTokenExpires: number): number {
        let a;
        if (ticksWhenTokenExpires === 0) {
            a = new Date(new Date().getTime() + 1 * 60000);
        } else {
            a = new Date((ticksWhenTokenExpires) * 1000);
        }

        let b = new Date();
        let utc1 = Date.UTC(a.getFullYear(), a.getMonth(), a.getDate(), a.getHours(), a.getMinutes(), a.getSeconds());
        let utc2 = Date.UTC(b.getFullYear(), b.getMonth(), b.getDate(), b.getHours(), b.getMinutes(), b.getSeconds());

        let timeInSeconds = Math.floor((utc1 - utc2) / 1000);
        return timeInSeconds - 5;
    }
}


问:
MYSQL need to remove random values and add values in sequence
i have this table and i have column called order it has random values like
1
2
5
7
8
12
11
9

i want to remove that and get values in a sequence
1
2
3
4
5
6
7
8

is there a way to do that?

答:
If i understood your question, you want to have identity column and remove existing ID column.

Try ALTER TABLE tbl1 ADD id INT PRIMARY KEY AUTO_INCREMENT FIRST;

Then drop the existing identity by

```<code>ALTER TABLE tbl1 DROP COLUMN yourColumn;
</code>```

If I am guessing it right, you have 1 2 5 7 8 12 11 9 because you have deleted rows with id 3 4 6 10 etc

Body:
If i understood your question, you want to have identity column and remove existing ID column.

Try ALTER TABLE tbl1 ADD id INT PRIMARY KEY AUTO_INCREMENT FIRST;

Then drop the existing identity by

ALTER TABLE tbl1 DROP COLUMN yourColumn;

If I am guessing it right, you have 1 2 5 7 8 12 11 9 because you have deleted rows with id 3 4 6 10 etc


问:
Get the names of data frames from a list
Say I have the following:

```<code>df1 <- data.frame()
df2 <- data.frame()
mylist = list(df1, df2)
</code>```

Is there a function that will return me the names of these two data frames, i.e. returns me 'df1' 'df2'? I know that names(mylist) will just return me NULL.

答:
If we create the list with mget, we can get the names

```<code>lst1 <- mget(paste0("df", 1:2))
names(lst1)
#[1] "df1" "df2"
</code>```

Body:
Say I have the following:

df1 <- data.frame()
df2 <- data.frame()
mylist = list(df1, df2)

Is there a function that will return me the names of these two data frames, i.e. returns me 'df1' 'df2'? I know that names(mylist) will just return me NULL.

Body:
If we create the list with mget, we can get the names

lst1 <- mget(paste0("df", 1:2))
names(lst1)
#[1] "df1" "df2"


问:
sed not working within $()
I'm trying to replace part of the filename with sed during a move.  What I want is to make evident that certain file goes from "READY" to "SENT" just after a transfer operation:

Assuming two files (at least), that for test purposes I'm generating with touch:

```<code>>touch READY01_file_to_process.txt
>touch READY02_file_to_process.txt
</code>```

Then I'm trying to do this:

```<code>>ls READY* | xargs -I% mv "%" $(echo "%" | sed 's/READY/SENT/')
</code>```

But it doesn't work as expected.  Just to debug it I changed 'mv' into 'echo' like this:

```<code>>ls READY* | xargs -I% echo "%" $(echo "%" | sed 's/READY/SENT/')
</code>```

I'm expecting to see this output:

```<code>READY01_file_to_process.txt SENT01_file_to_process.txt
READY02_file_to_process.txt SENT02_file_to_process.txt
</code>```

But it gives the following instead (no substitution at all):

```<code>READY01_file_to_process.txt READY01_file_to_process.txt
READY02_file_to_process.txt READY02_file_to_process.txt
</code>```

I'm pretty sure it's something stupid I just can't spot...
Thanks in advance.

答:
Do not parse ls and there are other ways to rename files

1) If you have rename command not based on perl, something like this: http://man7.org/linux/man-pages/man1/rename.1.html

```<code>$ touch READY0{1,2}_file_to_process.txt
$ # -v is for verbose output
$ # note how same glob is used as what you used with ls
$ rename -v READY SENT READY*
`READY01_file_to_process.txt' -> `SENT01_file_to_process.txt'
`READY02_file_to_process.txt' -> `SENT02_file_to_process.txt'
</code>```

2) If you have perl based rename

```<code>$ # -n is for dry run, remove and run cmd again after it looks okay
$ rename -n 's/READY/SENT/' READY*
rename(READY01_file_to_process.txt, SENT01_file_to_process.txt)
rename(READY02_file_to_process.txt, SENT02_file_to_process.txt)
</code>```

3) for-loop and http://mywiki.wooledge.org/BashGuide/Parameters#Parameter_Expansion

```<code>$ # remove echo once it looks okay
$ for f in READY*; do echo mv "$f" "${f/READY/SENT}"; done
mv READY01_file_to_process.txt SENT01_file_to_process.txt
mv READY02_file_to_process.txt SENT02_file_to_process.txt
</code>```

Title: sed not working within $()

Body:
I'm trying to replace part of the filename with sed during a move.  What I want is to make evident that certain file goes from "READY" to "SENT" just after a transfer operation:

Assuming two files (at least), that for test purposes I'm generating with touch:

>touch READY01_file_to_process.txt
>touch READY02_file_to_process.txt

Then I'm trying to do this:

>ls READY* | xargs -I% mv "%" $(echo "%" | sed 's/READY/SENT/')

But it doesn't work as expected.  Just to debug it I changed 'mv' into 'echo' like this:

>ls READY* | xargs -I% echo "%" $(echo "%" | sed 's/READY/SENT/')

I'm expecting to see this output:

READY01_file_to_process.txt SENT01_file_to_process.txt
READY02_file_to_process.txt SENT02_file_to_process.txt

But it gives the following instead (no substitution at all):

READY01_file_to_process.txt READY01_file_to_process.txt
READY02_file_to_process.txt READY02_file_to_process.txt

I'm pretty sure it's something stupid I just can't spot...
Thanks in advance.

Body:
Do not parse ls and there are other ways to rename files

1) If you have rename command not based on perl, something like this: http://man7.org/linux/man-pages/man1/rename.1.html

$ touch READY0{1,2}_file_to_process.txt
$ # -v is for verbose output
$ # note how same glob is used as what you used with ls
$ rename -v READY SENT READY*
`READY01_file_to_process.txt' -> `SENT01_file_to_process.txt'
`READY02_file_to_process.txt' -> `SENT02_file_to_process.txt'

2) If you have perl based rename

$ # -n is for dry run, remove and run cmd again after it looks okay
$ rename -n 's/READY/SENT/' READY*
rename(READY01_file_to_process.txt, SENT01_file_to_process.txt)
rename(READY02_file_to_process.txt, SENT02_file_to_process.txt)

3) for-loop and http://mywiki.wooledge.org/BashGuide/Parameters#Parameter_Expansion

$ # remove echo once it looks okay
$ for f in READY*; do echo mv "$f" "${f/READY/SENT}"; done
mv READY01_file_to_process.txt SENT01_file_to_process.txt
mv READY02_file_to_process.txt SENT02_file_to_process.txt


问:
Consecutive use of std::list causes crash
I have code which is meant to do memory management, but it keeps crashing at a certain point where I remove an object from the 'live' list and place it onto the 'dead' one:

```<code>class MemoryObject {
private:
    static std::list <MemoryObject *> alive, dead;
    long references;
public:
    MemoryObject() {
        alive.push_back(this);
        references = 0;
    }

    static void deepClean() {
        clean();
        std::list<MemoryObject *>::iterator iterator;
        for(iterator = alive.begin(); iterator != alive.end(); iterator ++) {
            MemoryObject *object = *iterator;
            Log::instance().write(DEBUG_LOG, "\nObject still active at the end of the program, check for memory leaks."
                    "\nSize: %d",
                    alive.size());
            delete object;
        }
        alive.clear();
    }

    void reference() {
        references ++;
    }

    void release() {
        references --;
        if(references <= 0) {
            dead.push_back(this);
            alive.remove(this);
        }
    }

    static void clean() {
        std::list<MemoryObject *>::iterator iterator;
        for(iterator = dead.begin(); iterator != dead.end(); iterator ++)
            delete(&iterator);
        dead.clear();
    }

    ~MemoryObject() {
        clean();
    }
};

std::list <MemoryObject *> MemoryObject::alive, MemoryObject::dead;
</code>```

Eclipse debug shows it failing under release(), always at the second list-related spot - I've tried putting them (alive.remove(this) and dead.push_back(this)) in a different order, which changes nothing. Interestingly however, if I place something in-between them, like a printf() statement, it doesn't crash...

Here's where I'm calling it from:

```<code>#include <stdlib.h>
#include <stdio.h>

#include "log/log.hpp"
#include "memory/object.hpp"

int main(int argc, char *argv[]) {
    MemoryObject foo;
    foo.release();
    MemoryObject::deepClean();
    return 0;
}
</code>```

答:
You delete only what is allocated through new.

```<code>MemoryObject foo;
foo.release();
</code>```

And inside clean

```<code>for(iterator = dead.begin(); iterator != dead.end(); iterator ++)
        delete(*iterator);  //I am assuming you have * instead of &(which is incorrect as mentioned in another answer).
</code>```

So you are calling delete() on something which was not allocated through newTry this.

```<code>MemoryObject *foo=new MemoryObject();
foo->release();
</code>```

EDIT: This will still not work for the below reason.

Inside clean() you are deleting element of dead which is this of the current object.So in short you are doing something like this

```<code>class A
{
    void delete_this()
    {
        delete(this);
        //At this point "this" is a dangling pointer and you should not use it.
    }
};
</code>```

Body:
I have code which is meant to do memory management, but it keeps crashing at a certain point where I remove an object from the 'live' list and place it onto the 'dead' one:

class MemoryObject {
private:
    static std::list <MemoryObject *> alive, dead;
    long references;
public:
    MemoryObject() {
        alive.push_back(this);
        references = 0;
    }

    static void deepClean() {
        clean();
        std::list<MemoryObject *>::iterator iterator;
        for(iterator = alive.begin(); iterator != alive.end(); iterator ++) {
            MemoryObject *object = *iterator;
            Log::instance().write(DEBUG_LOG, "\nObject still active at the end of the program, check for memory leaks."
                    "\nSize: %d",
                    alive.size());
            delete object;
        }
        alive.clear();
    }

    void reference() {
        references ++;
    }

    void release() {
        references --;
        if(references <= 0) {
            dead.push_back(this);
            alive.remove(this);
        }
    }

    static void clean() {
        std::list<MemoryObject *>::iterator iterator;
        for(iterator = dead.begin(); iterator != dead.end(); iterator ++)
            delete(&iterator);
        dead.clear();
    }

    ~MemoryObject() {
        clean();
    }
};

std::list <MemoryObject *> MemoryObject::alive, MemoryObject::dead;

Eclipse debug shows it failing under release(), always at the second list-related spot - I've tried putting them (alive.remove(this) and dead.push_back(this)) in a different order, which changes nothing. Interestingly however, if I place something in-between them, like a printf() statement, it doesn't crash...

Here's where I'm calling it from:

#include <stdlib.h>
#include <stdio.h>

#include "log/log.hpp"
#include "memory/object.hpp"

int main(int argc, char *argv[]) {
    MemoryObject foo;
    foo.release();
    MemoryObject::deepClean();
    return 0;
}

Body:
You delete only what is allocated through new.

MemoryObject foo;
foo.release();

And inside clean

for(iterator = dead.begin(); iterator != dead.end(); iterator ++)
        delete(*iterator);  //I am assuming you have * instead of &(which is incorrect as mentioned in another answer).

So you are calling delete() on something which was not allocated through newTry this.

MemoryObject *foo=new MemoryObject();
foo->release();

EDIT: This will still not work for the below reason.

Inside clean() you are deleting element of dead which is this of the current object.So in short you are doing something like this

class A
{
    void delete_this()
    {
        delete(this);
        //At this point "this" is a dangling pointer and you should not use it.
    }
};


问:
Python checking if string in list to list
I am having a hard time trying to understand how the "for" function works.

I want to make a script that only outputs the strings in list2 that are not inside list1. For example:

```<code>list1 = ["link1.com", "link2.com", "link3.com"]
list2 = ["link2.com", "link123.com"]

for list2 in list1:
    print(list2)
</code>```

{My intention was that the code printed:

link123.com

But instead it printed the strings from list1}

I can't get it to work. Help would be much appreciated. I am using python 3 by the way.

答:
For loops

For loops allow you to repeat a piece of code multiple times. You could easily just write a conditional and a print statement multiple times for each item in the list. A for loops allows you to write that piece of code once and have it repeated for each item in the list.

You can iterate over item in list2 by doing the following

```<code>for item in list2:
    print(item)
</code>```

item is an arbitrary variable name that holds the value of the current item we are on, what follows in is the list that we want to iterate over. print(item) is the piece of code we want to repeat for each element in the list.

What this does is goes through every item in list2 and prints them but that is not what we want. We want to check to make sure that item is not in list1. This can be achieved through a conditional statement.

```<code>if item not in list1:
    print(item)
</code>```

Now we can join the two piece of code together.

```<code>for item in list2:
    if item not in list1:
        print(item)
</code>```

Sets

Are a collection of items in no order where every item is unique. These sets are the same ones we encounter in mathematics, therefore we can perform mathematical set operations on them.

To go from a list of items to a set we use sList1 = set(list1) sList1 is now of type set and stores the elements in list1. The same can be done for list2.

Now that we have sList1 and sList2 we want to eliminate any duplicates in the two for that we can take the difference of sList1 and sList2 and print them out as follows print(sList2-sList1).

We can do all of this in one step.
print( set(list2) - set(list1) )

Body:
I am having a hard time trying to understand how the "for" function works.

I want to make a script that only outputs the strings in list2 that are not inside list1. For example:

list1 = ["link1.com", "link2.com", "link3.com"]
list2 = ["link2.com", "link123.com"]

for list2 in list1:
    print(list2)

{My intention was that the code printed:

link123.com

But instead it printed the strings from list1}

I can't get it to work. Help would be much appreciated. I am using python 3 by the way.

Body:
For loops

For loops allow you to repeat a piece of code multiple times. You could easily just write a conditional and a print statement multiple times for each item in the list. A for loops allows you to write that piece of code once and have it repeated for each item in the list.

You can iterate over item in list2 by doing the following

for item in list2:
    print(item)

item is an arbitrary variable name that holds the value of the current item we are on, what follows in is the list that we want to iterate over. print(item) is the piece of code we want to repeat for each element in the list.

What this does is goes through every item in list2 and prints them but that is not what we want. We want to check to make sure that item is not in list1. This can be achieved through a conditional statement.

if item not in list1:
    print(item)

Now we can join the two piece of code together.

for item in list2:
    if item not in list1:
        print(item)

Sets

Are a collection of items in no order where every item is unique. These sets are the same ones we encounter in mathematics, therefore we can perform mathematical set operations on them.

To go from a list of items to a set we use sList1 = set(list1) sList1 is now of type set and stores the elements in list1. The same can be done for list2.

Now that we have sList1 and sList2 we want to eliminate any duplicates in the two for that we can take the difference of sList1 and sList2 and print them out as follows print(sList2-sList1).

We can do all of this in one step.
print( set(list2) - set(list1) )


问:
Pyparsing: How can I parse data and then edit a specific value in a .txt file?
my data is located in a .txt file (no, I can't change it to a different format) and it looks like this:

varaiablename = value

something = thisvalue

youget = the_idea

Here is my code so far (taken from the examples in Pyparsing):

```<code>from pyparsing import Word, alphas, alphanums, Literal, restOfLine, OneOrMore, \
empty, Suppress, replaceWith

input = open("text.txt", "r")
src = input.read()

# simple grammar to match #define's
ident = Word(alphas + alphanums + "_")
macroDef = ident.setResultsName("name") + "= " + ident.setResultsName("value") + Literal("#") + restOfLine.setResultsName("desc")
for t,s,e in macroDef.scanString(src):
print t.name,"=", t.value
</code>```

So how can I tell my script to edit a specific value for a specific variable?

Example:

I want to change the value of variablename, from value to new_value.
So essentially variable = (the data we want to edit).

I probably should make it clear that I don't want to go directly into the file and change the value by changing value to new_value but I want to parse the data, find the variable and then give it a new value.

答:
ConfigParser

```<code>import ConfigParser

config = ConfigParser.RawConfigParser()
config.read('example.txt')

variablename = config.get('variablename', 'float')
</code>```

It'll yell at you if you don't have a [section] header, though, but it's ok, you can fake one.

ContentLicense: CC BY-SA 2.5

Body:
my data is located in a .txt file (no, I can't change it to a different format) and it looks like this:

varaiablename = value

something = thisvalue

youget = the_idea

Here is my code so far (taken from the examples in Pyparsing):

from pyparsing import Word, alphas, alphanums, Literal, restOfLine, OneOrMore, \
empty, Suppress, replaceWith

input = open("text.txt", "r")
src = input.read()

# simple grammar to match #define's
ident = Word(alphas + alphanums + "_")
macroDef = ident.setResultsName("name") + "= " + ident.setResultsName("value") + Literal("#") + restOfLine.setResultsName("desc")
for t,s,e in macroDef.scanString(src):
print t.name,"=", t.value

So how can I tell my script to edit a specific value for a specific variable?

Example:

I want to change the value of variablename, from value to new_value.
So essentially variable = (the data we want to edit).

I probably should make it clear that I don't want to go directly into the file and change the value by changing value to new_value but I want to parse the data, find the variable and then give it a new value.

Body:
ConfigParser

import ConfigParser

config = ConfigParser.RawConfigParser()
config.read('example.txt')

variablename = config.get('variablename', 'float')

It'll yell at you if you don't have a [section] header, though, but it's ok, you can fake one.


问:
Java polymorphism: finding the right design pattern
Disclaimer: I know there are a lot of questions about polymorphism out there, but I couldn't find a suitable answer for my problem. If your Google-fu is better than mine, please forgive the dupe.

I have a model using inheritance, such as in the example below.

```<code>public abstract class Base {
// ...
}

public class ConcreteA extends Base {
    private String someString;
// ...
}

public class ConcreteB extends Base {
    private boolean someBool;
// ...
}
</code>```

And I also have a List<Base>, which is composed of objects that are either ConcreteAs or ConcreteBs.

I need to generate a graphical view for each object in the list, but the resulting element is not the same for ConcreteAs and ConcreteBs. From the example above, the view for ConcreteA would be a text field, while the view for a ConcreteB would be a check box.

How can I achieve this using OO principles?

答:
The problem that you have is that you somewhere return a List<Base> when the caller must know the concrete type.

Usually this is caused because one tried to make a method more generic. E.g. if someone has this service methods

```<code>public List<ConcreteA> doSomethingA(){ ... }
public List<ConcreteB> doSomethingB(){ ... }
</code>```

he might think it is a better idea to introduce a superclass, Base so that both methods can be substituted by

```<code>public List<Base> doSomething(){ ... }
</code>```

This is a good idea if the caller is only interessted in a Base object. This means that ConcreateA and ConcreteB have some common behavior that the caller only depends on.

But in your case it seems that the caller needs the concrete type information that is not available anymore, because of the more generic method.

So you either must preserve or reconstruct the type information.

Preserve the type by using a custom return type instead of making the method generic

```<code> public class Result {
     private List<ConcreteA> concreteA;
     private List<ConcreteB> concreteA;
 }

 public Result doSomething();
</code>```

Recunstruct the type information using instanceof

Reconstruct the type information by introcucing a visitor pattern.

Body:
Disclaimer: I know there are a lot of questions about polymorphism out there, but I couldn't find a suitable answer for my problem. If your Google-fu is better than mine, please forgive the dupe.

I have a model using inheritance, such as in the example below.

public abstract class Base {
// ...
}

public class ConcreteA extends Base {
    private String someString;
// ...
}

public class ConcreteB extends Base {
    private boolean someBool;
// ...
}

And I also have a List<Base>, which is composed of objects that are either ConcreteAs or ConcreteBs.

I need to generate a graphical view for each object in the list, but the resulting element is not the same for ConcreteAs and ConcreteBs. From the example above, the view for ConcreteA would be a text field, while the view for a ConcreteB would be a check box.

How can I achieve this using OO principles?

Body:
The problem that you have is that you somewhere return a List<Base> when the caller must know the concrete type.

Usually this is caused because one tried to make a method more generic. E.g. if someone has this service methods

public List<ConcreteA> doSomethingA(){ ... }
public List<ConcreteB> doSomethingB(){ ... }

he might think it is a better idea to introduce a superclass, Base so that both methods can be substituted by

public List<Base> doSomething(){ ... }

This is a good idea if the caller is only interessted in a Base object. This means that ConcreateA and ConcreteB have some common behavior that the caller only depends on.

But in your case it seems that the caller needs the concrete type information that is not available anymore, because of the more generic method.

So you either must preserve or reconstruct the type information.

Preserve the type by using a custom return type instead of making the method generic

 public class Result {
     private List<ConcreteA> concreteA;
     private List<ConcreteB> concreteA;
 }

 public Result doSomething();

Recunstruct the type information using instanceof

Reconstruct the type information by introcucing a visitor pattern.


问:
Configuring IPv6 network
I need to test my application on IPv6 network on iPhone. As far as I have learned, I have several options:

Share IPv6 Internet via iMac as described in this tutorial; though when I tried to follow the steps there on an MacBook Air connected by bluetooth to an iPhone with turned on 3G there was no "Create NAT64 Network" checkbox for step 7 - do I nessesarely need to be connected via cabel or I need a stationary iMac?

Configurate IPv6 wi-fi on a router; though as far as I have learned to do this I need some special router that supports IPv6 and my Internet provider should be able to give me IPv6 connection. Is this correct?

Are there other, maybe easier ways to simulate IPv6 on an iPhone? How do I tell router that supports IPv6 from the one that does not?

答: I know its a bit late, yet it might help someone. You can create an ipV6 network via step 1 described. The trick is, at the time of clicking on BluetoothPAN option, you should press the option(ALT) key in the keyboard. Then Create NAT64 Network checkbox will be displayed at the bottom. This is the same case for WIFI & Ethernet too

Title: Configuring IPv6 network


问:
How can I get amount of rows in Excel file via xlwt
How can I get amount of rows in Excel file via xlwt? Is it unable and I should open this file for read via xlrd just for get this info?</p>

答:
I know this topic is a bit old but it's the first google result when lookink for this issue. I'm using python 3.6 with xlwt 1.2.0 and to get worksheet length I use this:</p>

```<code>len(ws._Worksheet__rows) #care the simple then double underscore
</code>```

Body:
I know this topic is a bit old but it's the first google result when lookink for this issue. I'm using python 3.6 with xlwt 1.2.0 and to get worksheet length I use this:

len(ws._Worksheet__rows) #care the simple then double underscore


问:
Getting value of input field using variable as name in javascript

var count='0';
var value= document.getElementsByName('test['+count+']').value;
alert('test['+count+']');```
<pre class="snippet-code-html lang-html prettyprint-override"><code><input type="hidden" value="4" name="test[0]"></code>```

var count='0';
var value= document.getElementsByName('test['+count+']').value;
alert(value);```
<pre class="snippet-code-html lang-html prettyprint-override"><code><input type="hidden" value="4" name="test[0]"></code>```

Can't get the value of the field in javascript..By checking the above u get the difference..I am passing the name correctly..eventhough it shows undefined value..Just a beginner in javascript..help me solving this...

答:
getElementsByName returns list of matching name elements. you need to specify index of element you want to access.
like this document.getElementsByName('test['+count+']')[0].value;

var count='0';
var value= document.getElementsByName('test['+count+']')[0].value;
alert(value);```
<pre class="snippet-code-html lang-html prettyprint-override"><code><input type="hidden" value="4" name="test[0]"></code>```

Body:
var count='0';
var value= document.getElementsByName('test['+count+']').value;
alert('test['+count+']');

<input type="hidden" value="4" name="test[0]">

var count='0';
var value= document.getElementsByName('test['+count+']').value;
alert(value);

<input type="hidden" value="4" name="test[0]">

Can't get the value of the field in javascript..By checking the above u get the difference..I am passing the name correctly..eventhough it shows undefined value..Just a beginner in javascript..help me solving this...

Body:
getElementsByName returns list of matching name elements. you need to specify index of element you want to access.
like this document.getElementsByName('test['+count+']')[0].value;

var count='0';
var value= document.getElementsByName('test['+count+']')[0].value;
alert(value);

<input type="hidden" value="4" name="test[0]">


问:
In Mysql,How can select new data from last select data
Use PHP.
then in mysql hava this table

```<code>Id     where    name    sex
1      CN       X.ming  boy
2      US       Tom     boy
3      US       jom     boy
4      US       Kim     girl
</code>```

=====================

first i need get where select * from table where=US

then need get boy select * from (last select) where sex=boy

i find get code is

```<code>SELECT * FROM (SELECT * FROM table WHERE where=US) AS a WHERE sex=boy；
</code>```

but this not good and not fast.

case:

//
my English is no good,so i reply is slow... sorry!!

答:
First of all you cannot use reserve words in table column name (recommended). where is a reserve word, so change it to location or something else. And the query is like:

```<code>SELECT * FROM TABLENAME WHERE location = 'US' AND sex = 'boy';
</code>```

Body:
Use PHP.
then in mysql hava this table

Id     where    name    sex
1      CN       X.ming  boy
2      US       Tom     boy
3      US       jom     boy
4      US       Kim     girl

=====================

first i need get where select * from table where=US

then need get boy select * from (last select) where sex=boy

i find get code is

SELECT * FROM (SELECT * FROM table WHERE where=US) AS a WHERE sex=boy；

but this not good and not fast.

case:

//
my English is no good,so i reply is slow... sorry!!

Body:
First of all you cannot use reserve words in table column name (recommended). where is a reserve word, so change it to location or something else. And the query is like:

SELECT * FROM TABLENAME WHERE location = 'US' AND sex = 'boy';


问:
node.js mysql insert ER_PARSE ERROR near HANDLER RESOLVED
I have an API running in AWS Lambda written on Node.JS (6.10.3), using the npm package mysql (2.13.0).  This is deployed and managed using Serverless.

I am Inserting a single row into a table on a MariaDB RDS instance using the following code:

```<code>var mysql = require('mysql');

var connection = mysql.createConnection({
  "host": process.env.CONFIG_HOST,
  "user": process.env.CONFIG_WRITE_USER,
  "password": process.env.CONFIG_WRITE_PW,
  "database": process.env.CONFIG_DB,
  "connectionLimit": 1
});

module.exports.post = (event, context, callback) => {
  var body = JSON.parse(event.body);
  var params = event.someParameter;
  var sql = getSql(body.name);

  console.log(sql);
  connection.query(sql, onQueryComplete(params, callback));
}

const onQueryComplete = function(params, callback) {
  return function(error, result) {
    if (error) {
      console.log(error);
      callback(null, 'some error response');
    }

    // do something else...
  }
}

function getSql(name) {
  return `
    INSERT INTO lds_config.test_table
    (
      name,
      name_hash
    )
    VALUES
    (
      '${name}',
      MD5('${name}')
    );`;
}
</code>```

If I check the table, I can see that the insert has completed successfully and the new row has been added, however error is being set - meaning something has gone wrong somewhere (possibly after the insert).

The error returned by mysql (in console.log) is:

```<code>{
  Error: ER_PARSE_ERROR: You have an error in your SQL syntax; check the manual that corresponds to your MariaDB server version for the right syntax to use near 'HANDLER RESOLVED _____');
   // Timeout clearing if needed
       ' at line 2
    at Query.Sequence._packetToError (...\node_modules\mysql\lib\protocol\sequences\Sequence.js:52:14)
    at Query.ErrorPacket <<stack trace continues>>)
  code: 'ER_PARSE_ERROR',
  errno: 1064,
  sqlState: '42000',
  index: 0
}
</code>```

This is followed by a second error, stating that callback is not a function:

```<code>Debug: internal, implementation, error
TypeError: Uncaught error: callback is not a function
</code>```

Similar code is working elsewhere in the API for selects.  Thanks!

Further notes:
The table is:

```<code>CREATE TABLE lds_config.test_table(id INT PRIMARY KEY AUTO_INCREMENT, name VARCHAR(500), name_hash CHAR(32));
</code>```

The result from console.log(sql); is:

```<code>INSERT INTO lds_config.test_table
(
  name,
  name_hash
)
VALUES
(
  'test01',
  MD5('test01')
);
</code>```

Which works when I run it directly in mysql workbench.

答:
Include the query also since the first error is regarding MySQL syntax. About callback is not a function it is not passed as a parameter in below code as far as I see.

```<code>const onQueryComplete = function(params) {
  return function(error, result, callback) {
    if (error) {
     console.log(error);
     callback(null, 'some error response');
    }
    // do something else...
  }
}
</code>```

Above is the corrected one.

Body:
I have an API running in AWS Lambda written on Node.JS (6.10.3), using the npm package mysql (2.13.0).  This is deployed and managed using Serverless.

I am Inserting a single row into a table on a MariaDB RDS instance using the following code:

var mysql = require('mysql');

var connection = mysql.createConnection({
  "host": process.env.CONFIG_HOST,
  "user": process.env.CONFIG_WRITE_USER,
  "password": process.env.CONFIG_WRITE_PW,
  "database": process.env.CONFIG_DB,
  "connectionLimit": 1
});

module.exports.post = (event, context, callback) => {
  var body = JSON.parse(event.body);
  var params = event.someParameter;
  var sql = getSql(body.name);

  console.log(sql);
  connection.query(sql, onQueryComplete(params, callback));
}

const onQueryComplete = function(params, callback) {
  return function(error, result) {
    if (error) {
      console.log(error);
      callback(null, 'some error response');
    }

    // do something else...
  }
}

function getSql(name) {
  return `
    INSERT INTO lds_config.test_table
    (
      name,
      name_hash
    )
    VALUES
    (
      '${name}',
      MD5('${name}')
    );`;
}

If I check the table, I can see that the insert has completed successfully and the new row has been added, however error is being set - meaning something has gone wrong somewhere (possibly after the insert).

The error returned by mysql (in console.log) is:

{
  Error: ER_PARSE_ERROR: You have an error in your SQL syntax; check the manual that corresponds to your MariaDB server version for the right syntax to use near 'HANDLER RESOLVED _____');
   // Timeout clearing if needed
       ' at line 2
    at Query.Sequence._packetToError (...\node_modules\mysql\lib\protocol\sequences\Sequence.js:52:14)
    at Query.ErrorPacket <<stack trace continues>>)
  code: 'ER_PARSE_ERROR',
  errno: 1064,
  sqlState: '42000',
  index: 0
}

This is followed by a second error, stating that callback is not a function:

Debug: internal, implementation, error
TypeError: Uncaught error: callback is not a function

Similar code is working elsewhere in the API for selects.  Thanks!

Further notes:
The table is:

CREATE TABLE lds_config.test_table(id INT PRIMARY KEY AUTO_INCREMENT, name VARCHAR(500), name_hash CHAR(32));

The result from console.log(sql); is:

INSERT INTO lds_config.test_table
(
  name,
  name_hash
)
VALUES
(
  'test01',
  MD5('test01')
);

Which works when I run it directly in mysql workbench.

Body:
Include the query also since the first error is regarding MySQL syntax. About callback is not a function it is not passed as a parameter in below code as far as I see.

const onQueryComplete = function(params) {
  return function(error, result, callback) {
    if (error) {
     console.log(error);
     callback(null, 'some error response');
    }
    // do something else...
  }
}

Above is the corrected one.


答:
IIUC, you want the average mean of each participant across all questions:

```<code>df.where(df != 1).mean(axis=1).mean(level=0)
</code>```

Let's get rid of correlations with same question with where, then get the mean for all questions by participant_id with direction of axis=1, then get the participant_id mean level=0.

Output:

```<code>participant_id
11.0    0.086416
14.0   -0.031493
17.0    0.130800
18.0    0.105896
dtype: float64
</code>```

Edit: I used mean instead of median, we can so do the same logic with median.

```<code>df.where(df != 1).median(axis=1).median(level=0)
</code>```

Title: Applying function to Pandas with GroupBy along direction of the grouping variable

Body:
I have a cohort of N people and I computed a correlation matrix of some quantities (q1_score,...q5_score)

    df.groupby('participant_id').corr()
    Out[130]:
                                q1_score    q2_score   q3_score  q4_score   q5_score
    participant_id
    11.0           q1_score     1.000000   -0.748887  -0.546893  -0.213635  -0.231169
                   q2_score    -0.748887    1.000000   0.639649   0.324976   0.335596
                   q3_score    -0.546893    0.639649   1.000000   0.154539   0.151233
                   q4_score    -0.213635    0.324976   0.154539   1.000000   0.998752
                   q5_score    -0.231169    0.335596   0.151233   0.998752   1.000000
    14.0           q1_score     1.000000   -0.668781  -0.124614  -0.352075  -0.244251
                   q2_score    -0.668781    1.000000  -0.175432   0.360183   0.184585
                   q3_score    -0.124614   -0.175432   1.000000  -0.137993  -0.125115
                   q4_score    -0.352075    0.360183  -0.137993   1.000000   0.968564
                   q5_score    -0.244251    0.184585  -0.125115   0.968564   1.000000
    17.0           q1_score     1.000000   -0.799223  -0.814424  -0.790587  -0.777318
                   q2_score    -0.799223    1.000000   0.787238   0.658524   0.640786
                   q3_score    -0.814424    0.787238   1.000000   0.702570   0.701440
                   q4_score    -0.790587    0.658524   0.702570   1.000000   0.998996
                   q5_score    -0.777318    0.640786   0.701440   0.998996   1.000000
    18.0           q1_score     1.000000   -0.595545  -0.617691  -0.472409  -0.477523
                   q2_score    -0.595545    1.000000   0.386705   0.148761   0.115068
                   q3_score    -0.617691    0.386705   1.000000   0.806637   0.782345
                   q4_score    -0.472409    0.148761   0.806637   1.000000   0.982617
                   q5_score    -0.477523    0.115068   0.782345   0.982617   1.000000

I need to compute the median values of the correlations of all participants? What I mean: I need to take corr. between the item J and item K for all participants and find their median value.

I am sure it is a one line of code, but I'm struggling to realise (still learning pandas by examples).

Body:
IIUC, you want the average mean of each participant across all questions:

df.where(df != 1).mean(axis=1).mean(level=0)

Let's get rid of correlations with same question with where, then get the mean for all questions by participant_id with direction of axis=1, then get the participant_id mean level=0.

Output:

participant_id
11.0    0.086416
14.0   -0.031493
17.0    0.130800
18.0    0.105896
dtype: float64

Edit: I used mean instead of median, we can so do the same logic with median.

df.where(df != 1).median(axis=1).median(level=0)


问:
How to use Memcpy() function
I want to use the memcpy in the end, instead of

```<code>block_orig_left[i1][j1]=block_orig[i1][j1];
pred_orig_left [i1][j1]=block_pred[i1][j1];
</code>```

I have an error using memcpy

src/coder.c:909: error: invalid operands to binary * (have ‘unsigned int’ and ‘int **’)

  src/coder.c:910: error: invalid operands to binary * (have ‘unsigned int’ and ‘int **’)

```<code>int **block_orig_left=NULL;

block_orig_left=intmatrix(BSIZE_Y_LEVEL[levelv], BSIZE_X_LEVEL[levelv]);
pred_orig_left=intmatrix(BSIZE_Y_LEVEL[levelv], BSIZE_X_LEVEL[levelv]);

for(i1=0; i1<BSIZE_Y_LEVEL[levelv]; i1++)
for(j1=0; j1<BSIZE_X_LEVEL[levelv]; j1++)
{
    block_orig_left[i1][j1]=block_orig[i1][j1];
    pred_orig_left[i1][j1]=block_pred[i1][j1];
    Average_block_orig_left+=block_orig[i1][j1];
}
memcpy(block_orig_left, block_orig, sizeof(int **)*block_orig);

memcpy(pred_orig_left, block_pred,  sizeof(int **)*block_pred);
</code>```

How do I use the memcpy correctly?

答:
You are multiplying the size of an int** by an int**, which doesn't make sense. In other words, if you wanted to know the weight of all the cars on a truck, you can't multiply "weight of 1 car" by "truck". You have to multiply the weight of 1 car by the number of cars on the truck.

The third parameter to memcpy is the number of bytes you want to copy. You are correctly getting the size of an int*, but then you want to multiply that by the number of int* in the structure. So, if I'm understanding your code correctly, you would want to use

```<code>sizeof(int**) * BSIZE_Y_LEVEL[levelv] * BSIZE_X_LEVEL[levelv]
</code>```

since the structures you are copying seem to contain that many int double pointers.

EDIT: Looking at David Yaw's answer, I realize that he is correct. I failed to address the fact that the inner pointers were likely not all allocated at once, but rather in a for loop or something, so they would need to be copied in like manner. My way above would copy the right amount of memory, but it would not necessarily be the correct memory.

Title: How to use Memcpy() function

Body:
I want to use the memcpy in the end, instead of

block_orig_left[i1][j1]=block_orig[i1][j1];
pred_orig_left [i1][j1]=block_pred[i1][j1];

I have an error using memcpy

src/coder.c:909: error: invalid operands to binary * (have ‘unsigned int’ and ‘int **’)

  src/coder.c:910: error: invalid operands to binary * (have ‘unsigned int’ and ‘int **’)

int **block_orig_left=NULL;

block_orig_left=intmatrix(BSIZE_Y_LEVEL[levelv], BSIZE_X_LEVEL[levelv]);
pred_orig_left=intmatrix(BSIZE_Y_LEVEL[levelv], BSIZE_X_LEVEL[levelv]);

for(i1=0; i1<BSIZE_Y_LEVEL[levelv]; i1++)
for(j1=0; j1<BSIZE_X_LEVEL[levelv]; j1++)
{
    block_orig_left[i1][j1]=block_orig[i1][j1];
    pred_orig_left[i1][j1]=block_pred[i1][j1];
    Average_block_orig_left+=block_orig[i1][j1];
}
memcpy(block_orig_left, block_orig, sizeof(int **)*block_orig);

memcpy(pred_orig_left, block_pred,  sizeof(int **)*block_pred);

How do I use the memcpy correctly?

Body:
You are multiplying the size of an int** by an int**, which doesn't make sense. In other words, if you wanted to know the weight of all the cars on a truck, you can't multiply "weight of 1 car" by "truck". You have to multiply the weight of 1 car by the number of cars on the truck.

The third parameter to memcpy is the number of bytes you want to copy. You are correctly getting the size of an int*, but then you want to multiply that by the number of int* in the structure. So, if I'm understanding your code correctly, you would want to use

sizeof(int**) * BSIZE_Y_LEVEL[levelv] * BSIZE_X_LEVEL[levelv]

since the structures you are copying seem to contain that many int double pointers.

EDIT: Looking at David Yaw's answer, I realize that he is correct. I failed to address the fact that the inner pointers were likely not all allocated at once, but rather in a for loop or something, so they would need to be copied in like manner. My way above would copy the right amount of memory, but it would not necessarily be the correct memory.


问:
getchar function to clear input buffer outside of while-condition?
I have learned that one can empty the input buffer like this:

```<code>while((ch = getchar()) != EOF && ch != '\n');
if (ch == EOF) {
    // oops
}
</code>```

Why then, can I not empty the buffer by one character with the line:

```<code>c = getchar();
</code>```

This line will cause the program to wait for user input. Context:

```<code>void strfuncs()
{
    char name[50] = {0};
    char lastname[50] = {0};
    char c;

    printf("Enter name...:");
    fgets(name, 50, stdin);
    printf("Enter last name...:");
    fgets(lastname, 50, stdin);

    c=getchar();
    printf("Enter a character...:");
    fgets(&c, 1, stdin);

    printf("c: %c",c);
}
</code>```

答:
This idiom for emptying the input stream only works if there are characters in the input stream to be read; otherwise getchar() will block, waiting for input. If there are characters in the input stream, getchar() will read one of them.

The fgets() function keeps the newline character, so it may seem that it is not necessary to clean the input stream after getting a line of input this way. But, if the buffer is not large enough, there will be characters left behind. One way to handle this is to check the input buffer for a newline character, and clean the input stream if it is not present. If the newline is found in the input buffer, it is often removed:

```<code>char buffer[1000];

puts("Enter a line:");
if (fgets(buffer, sizeof buffer, stdin) == NULL) {
    perror("Error in fgets()");
    exit(EXIT_FAILURE);
}

char *ch;
int c;
if ((ch = strchr(buffer, '\n')) == NULL) {
    while ((c = getchar()) != '\n' && c != EOF) {
        continue;
    }
} else {
    *ch = '\0';
}
</code>```

Note that an int variable should be used to recieve the value returned by getchar(), to ensure that EOF is correctly handled.

Body:
I have learned that one can empty the input buffer like this:

while((ch = getchar()) != EOF && ch != '\n');
if (ch == EOF) {
    // oops
}

Why then, can I not empty the buffer by one character with the line:

c = getchar();

This line will cause the program to wait for user input. Context:

void strfuncs()
{
    char name[50] = {0};
    char lastname[50] = {0};
    char c;

    printf("Enter name...:");
    fgets(name, 50, stdin);
    printf("Enter last name...:");
    fgets(lastname, 50, stdin);

    c=getchar();
    printf("Enter a character...:");
    fgets(&c, 1, stdin);

    printf("c: %c",c);
}

Body:
This idiom for emptying the input stream only works if there are characters in the input stream to be read; otherwise getchar() will block, waiting for input. If there are characters in the input stream, getchar() will read one of them.

The fgets() function keeps the newline character, so it may seem that it is not necessary to clean the input stream after getting a line of input this way. But, if the buffer is not large enough, there will be characters left behind. One way to handle this is to check the input buffer for a newline character, and clean the input stream if it is not present. If the newline is found in the input buffer, it is often removed:

char buffer[1000];

puts("Enter a line:");
if (fgets(buffer, sizeof buffer, stdin) == NULL) {
    perror("Error in fgets()");
    exit(EXIT_FAILURE);
}

char *ch;
int c;
if ((ch = strchr(buffer, '\n')) == NULL) {
    while ((c = getchar()) != '\n' && c != EOF) {
        continue;
    }
} else {
    *ch = '\0';
}

Note that an int variable should be used to recieve the value returned by getchar(), to ensure that EOF is correctly handled.


问:
Visual Studio 2017 can't find windows.h
Hell'o
I've just installed Visual Studio 2017 (enterprise).I opened my project whom I created in Visual Studio 2015. My project uses windows.h library but VS2017 cannot find this library. How to repair this?  </p>

答:
This happens when you have customized include/library paths in legacy projects. If you added your own additional paths in project properties, VisualStudio 2017 can't automatically figure out base paths when switching between platforms/toolsets - normally it automatically puts correct paths there, but if you added customizations, VS won't touch them.

This is legitimate problem which I ran into myself recently when migrating old project targeted for Windows XP into VS2017. None of the answers or comments listed/linked here so far are helpful. I have all legacy SDKs in VisualStudio 2017 installer, and none of that fixed VS not finding essential includes such as <windows.h>. In my case the project was using v120 toolset from VS2013, which is superseded by v140_xp in newer VS.

After setting correct platform and toolset understood by VS2017, I did the following to resolve the problem:

Open project properties, go to VC++ Directories, for 'Include Directories' and for 'Library Directories', choose <Inherit from parent or project defaults>. This will remove your additional paths.

Click 'Apply'. This will reset include path to something like $(VC_IncludePath_x86);$(WindowsSdk_71A_IncludePath_x86) (will vary for SDKs).

Re-add your extra paths here, or better yet - under C/C++/General -> Additional Include Directories and Linker/General -> Additional Library Directories.

Title: Visual Studio 2017 can't find windows.h


问:
Kendo DropDownList Conditional if else template
Currently my template looks like this:

```<code>template: '#:data.Name# (#:data.Code#)'
</code>```

What I would like to do is to check the data.Code parameter if it's empty.
If (data.Code == '') then

```<code>template: '#:data.Name#
</code>```

else the first template that contains both name and code.

I've been trying something like this but it doesn't seem to work.

```<code>template: "#if(#:data.Code#==''){ #:data.Name# (#:data.Code#)}else {#:data.Name#}#"
</code>```

Help would be very appreciated.

答:
Try this one

template: "#=data.Name# # if(data.Code != '') { # (#=data.Code#) # } #"

Body:
Currently my template looks like this:

template: '#:data.Name# (#:data.Code#)'

What I would like to do is to check the data.Code parameter if it's empty.
If (data.Code == '') then

template: '#:data.Name#

else the first template that contains both name and code.

I've been trying something like this but it doesn't seem to work.

template: "#if(#:data.Code#==''){ #:data.Name# (#:data.Code#)}else {#:data.Name#}#"

Help would be very appreciated.


问:
For vs. while in C programming?
There are three loops in C: for, while, and do-while. What's the difference between them?

For example, it seems nearly all while statements can be replaced by for statements, right? Then, what's the advantage using while?

答:
/*
while loop

5 bucks

1 chocolate = 1 bucks

```<code>while my money is greater than 1 bucks
  select chocolate
  pay 1 bucks to the shopkeeper
  money = money - 1
end
</code>```

come to home and cant go to while shop because my money = 0 bucks
*/

```<code>#include<stdio.h>
int main(){
  int money = 5;

  while( money >= 1){
    printf("inside the shopk and selecting chocolate\n");
    printf("after selecting chocolate paying 1 bucks\n");
    money = money - 1 ;
    printf("my remaining moeny = %d\n", money);
    printf("\n\n");
  }

  printf("dont have money cant go inside the shop, money = %d",  money);

  return 0;
}
</code>```

infinite money

```<code>while( codition ){ // condition will always true ....infinite loop
  statement(s)
}
</code>```

please visit this video for better understanding
https://www.youtube.com/watch?v=eqDv2wxDMJ8&t=25s

/*
for loop

5 bucks

```<code>for my money is greater than equal to 1 bucks   0      money >= 1
  select chocolate
  pay 1 bucks to the shopkeeper
  money = money - 1  1-1 => 0
end
</code>```

*/

```<code>#include<stdio.h>
int main(){

  int money = 5;
  for( ; money >= 1; ){     0>=1  false
    printf("select chocolate \n");
    printf("paying 1 bucks to the shopkeeper\n");
    money = money - 1;    1-1 = 0
    printf(" remaining money =%d\n", money);
    printf("\n\n");
  }

  return 0;
}
</code>```

For better understanding please visit https://www.youtube.com/watch?v=_vdvyzzp-R4&t=25s

Title: For vs. while in C programming?

Body:
/*
while loop

5 bucks

1 chocolate = 1 bucks

while my money is greater than 1 bucks
  select chocolate
  pay 1 bucks to the shopkeeper
  money = money - 1
end

come to home and cant go to while shop because my money = 0 bucks
*/

#include<stdio.h>
int main(){
  int money = 5;

  while( money >= 1){
    printf("inside the shopk and selecting chocolate\n");
    printf("after selecting chocolate paying 1 bucks\n");
    money = money - 1 ;
    printf("my remaining moeny = %d\n", money);
    printf("\n\n");
  }

  printf("dont have money cant go inside the shop, money = %d",  money);

  return 0;
}

infinite money

while( codition ){ // condition will always true ....infinite loop
  statement(s)
}

please visit this video for better understanding
https://www.youtube.com/watch?v=eqDv2wxDMJ8&t=25s

/*
for loop

5 bucks

for my money is greater than equal to 1 bucks   0      money >= 1
  select chocolate
  pay 1 bucks to the shopkeeper
  money = money - 1  1-1 => 0
end

*/

#include<stdio.h>
int main(){

  int money = 5;
  for( ; money >= 1; ){     0>=1  false
    printf("select chocolate \n");
    printf("paying 1 bucks to the shopkeeper\n");
    money = money - 1;    1-1 = 0
    printf(" remaining money =%d\n", money);
    printf("\n\n");
  }

  return 0;
}

For better understanding please visit https://www.youtube.com/watch?v=_vdvyzzp-R4&t=25s


答:
```<code>memcpy(block_orig_left, block_orig, sizeof(int **)*block_orig);
</code>```

sizeof(int **)*block_orig is the multiplication of a size with a pointer. I guess you know that multiplying a pointer doesn't make sense nor is it possible as you can see from the compiler error.

I don't know what block_orig or your other (btw did you hear about self-describing variable names?) variables mean, but memcpy takes the target, the source, and the size in bytes as arguments.

In your integer-matrix case, something like sizeof(int) * numberOfElementsToCopy would make sense, if the target memory is continuous (i.e. 2D array).

Title: How to use Memcpy() function

Body:
memcpy(block_orig_left, block_orig, sizeof(int **)*block_orig);

sizeof(int **)*block_orig is the multiplication of a size with a pointer. I guess you know that multiplying a pointer doesn't make sense nor is it possible as you can see from the compiler error.

I don't know what block_orig or your other (btw did you hear about self-describing variable names?) variables mean, but memcpy takes the target, the source, and the size in bytes as arguments.

In your integer-matrix case, something like sizeof(int) * numberOfElementsToCopy would make sense, if the target memory is continuous (i.e. 2D array).


答:
Change where from table to location

```<code>  $servername = "localhost";
  $username = "username";
  $password = "password";
  $dbname = "yourDB";

  $conn = new mysqli($servername, $username, $password, $dbname);
  if ($conn->connect_error) {
      die("Connection failed: " . $conn->connect_error);
  }

  $result = $conn->query('SELECT * FROM table WHERE `location` = "US"');

  while($row = $result->fetch_assoc()) {
      if($row['sex']==boy) $data2[] = $row;
      $data1 = $row;
  }
</code>```

$data1 contains list of US and $data2 contain list of boy in US

Title: In Mysql,How can select new data from last select data

Body:
Change where from table to location

  $servername = "localhost";
  $username = "username";
  $password = "password";
  $dbname = "yourDB";

  $conn = new mysqli($servername, $username, $password, $dbname);
  if ($conn->connect_error) {
      die("Connection failed: " . $conn->connect_error);
  }

  $result = $conn->query('SELECT * FROM table WHERE `location` = "US"');

  while($row = $result->fetch_assoc()) {
      if($row['sex']==boy) $data2[] = $row;
      $data1 = $row;
  }

$data1 contains list of US and $data2 contain list of boy in US


问:
Bad Padding Exception while decryption
I am trying to implement a password based encryption algorithm, but I get this exception:

javax.crypto.BadPaddingException: Given final block not properly padded.

What might be the problem? (I am new to Java.) Here is my code:

```<code>import java.security.InvalidAlgorithmParameterException;
import java.security.InvalidKeyException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.security.spec.InvalidKeySpecException;
import java.security.spec.KeySpec;
import javax.crypto.BadPaddingException;
import javax.crypto.Cipher;
import javax.crypto.IllegalBlockSizeException;
import javax.crypto.NoSuchPaddingException;
import javax.crypto.SecretKey;
import javax.crypto.SecretKeyFactory;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.PBEKeySpec;
import javax.crypto.spec.SecretKeySpec;
import org.apache.commons.codec.binary.Base64;

public class EfiAdminPasswordHasher {
    /** SIZE variable.*/
    private static final int SIZE = 16;
    /** The serial number. */
    private static final long serialVersionUID = -7930024972049607076L;
    private static final String SECRET_KEY = "Dp29eInG$fch@ujO";
    private static final String SALT = "I@j2ts_@p$c29qTw";
    private SecretKey secretKey;

    public EfiAdminPasswordHasher() {
        generateSecretKey();
    }

    private void generateSecretKey() {
        try {

            SecretKeyFactory factory = SecretKeyFactory
                    .getInstance("PBKDF2WithHmacSHA1");
            KeySpec spec = new PBEKeySpec(SECRET_KEY.toCharArray(),
                    SALT.getBytes(), 65536, 256);
            SecretKey keySpec = factory.generateSecret(spec);
            final SecretKey secret = new SecretKeySpec(keySpec.getEncoded(),
                    "AES");
            System.out.println(secret+" "+"In SECRET kEY");
            secretKey = secret;
        } catch (NoSuchAlgorithmException | InvalidKeySpecException e) {
            throw new IllegalStateException(
                    "EfiAdminPasswordHasher::decryptPassword() - Unable to decrypt password.",
                    e);
        }
    }

public String encryptPassword(String password) {
        if (password == null || password.trim().length() == 0) {
            return password;
        }
        // Encoding password with SHA-256 algorithm
        try {

            MessageDigest md = MessageDigest.getInstance("SHA-256");
            md.update(password.getBytes());

            byte byteData[] = md.digest();
            //convert the byte to hex format method 1
            StringBuilder sb = new StringBuilder();
            for (int i = 0; i < byteData.length; i++) {
             sb.append(Integer.toString((byteData[i] & 0xff) + 0x100, 16).substring(1));
            }
            return sb.toString();

        } catch (NoSuchAlgorithmException | IllegalStateException e) {
            throw new IllegalStateException(
                    "EfiAdminPasswordHasher::encryptPassword() - Unable to encrypt password.",
                    e);
        }
    }

public String decryptPassword(String encryptedPassword) {

     // Cannot use StringUtils here, because this class to be serialized and
        // sent over to ACC
        if (encryptedPassword == null || encryptedPassword.trim().length() == 0) {
            return encryptedPassword;
        }
        // DECODE encryptedPwd String
        try {
            final byte[] encrypedPwdBytes = Base64.decodeBase64(encryptedPassword.getBytes());
            final Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");

            byte[] iv = new byte[SIZE];
            cipher.init(Cipher.DECRYPT_MODE, secretKey, new IvParameterSpec(iv));

            final byte[] plainTextPwdBytes = cipher.doFinal(encrypedPwdBytes);

            return new String(plainTextPwdBytes);
        } catch (IllegalBlockSizeException | NoSuchAlgorithmException | NoSuchPaddingException |
                        InvalidKeyException | IllegalStateException | BadPaddingException |
                        InvalidAlgorithmParameterException e) {
            throw new IllegalStateException(
                    "EfiAdminPasswordHasher::decryptPassword() - Unable to decrypt password.",
                    e);
        }
    }

public static void main(String[] args) {
        EfiAdminPasswordHasher hasher = new EfiAdminPasswordHasher();
        String encryptedPassword=hasher.encryptPassword("2");
        System.out.println("Encrypted password"+" "+encryptedPassword);

        String decryptedPassword=hasher.decryptPassword(encryptedPassword);
        System.out.println("Decrypted password"+" "+decryptedPassword);

    }
}
</code>```

答:
I found a solution in another post here, try to do this:</p>

```<code>final byte[] encrypedPwdBytes = fromHexString(encryptedPassword);
//...
public static byte[] fromHexString(String s) {
    int len = s.length();
    byte[] data = new byte[len / 2];
    for (int i = 0; i < len; i += 2) {
        data[i / 2] = (byte) ((Character.digit(s.charAt(i), 16) << 4)
                             + Character.digit(s.charAt(i+1), 16));
    }
    return data;
}
</code>```

Title: Bad Padding Exception while decryption

Body:
I am trying to implement a password based encryption algorithm, but I get this exception:

javax.crypto.BadPaddingException: Given final block not properly padded.

What might be the problem? (I am new to Java.) Here is my code:

import java.security.InvalidAlgorithmParameterException;
import java.security.InvalidKeyException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.security.spec.InvalidKeySpecException;
import java.security.spec.KeySpec;
import javax.crypto.BadPaddingException;
import javax.crypto.Cipher;
import javax.crypto.IllegalBlockSizeException;
import javax.crypto.NoSuchPaddingException;
import javax.crypto.SecretKey;
import javax.crypto.SecretKeyFactory;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.PBEKeySpec;
import javax.crypto.spec.SecretKeySpec;
import org.apache.commons.codec.binary.Base64;

public class EfiAdminPasswordHasher {
    /** SIZE variable.*/
    private static final int SIZE = 16;
    /** The serial number. */
    private static final long serialVersionUID = -7930024972049607076L;
    private static final String SECRET_KEY = "Dp29eInG$fch@ujO";
    private static final String SALT = "I@j2ts_@p$c29qTw";
    private SecretKey secretKey;

    public EfiAdminPasswordHasher() {
        generateSecretKey();
    }

    private void generateSecretKey() {
        try {

            SecretKeyFactory factory = SecretKeyFactory
                    .getInstance("PBKDF2WithHmacSHA1");
            KeySpec spec = new PBEKeySpec(SECRET_KEY.toCharArray(),
                    SALT.getBytes(), 65536, 256);
            SecretKey keySpec = factory.generateSecret(spec);
            final SecretKey secret = new SecretKeySpec(keySpec.getEncoded(),
                    "AES");
            System.out.println(secret+" "+"In SECRET kEY");
            secretKey = secret;
        } catch (NoSuchAlgorithmException | InvalidKeySpecException e) {
            throw new IllegalStateException(
                    "EfiAdminPasswordHasher::decryptPassword() - Unable to decrypt password.",
                    e);
        }
    }

public String encryptPassword(String password) {
        if (password == null || password.trim().length() == 0) {
            return password;
        }
        // Encoding password with SHA-256 algorithm
        try {

            MessageDigest md = MessageDigest.getInstance("SHA-256");
            md.update(password.getBytes());

            byte byteData[] = md.digest();
            //convert the byte to hex format method 1
            StringBuilder sb = new StringBuilder();
            for (int i = 0; i < byteData.length; i++) {
             sb.append(Integer.toString((byteData[i] & 0xff) + 0x100, 16).substring(1));
            }
            return sb.toString();

        } catch (NoSuchAlgorithmException | IllegalStateException e) {
            throw new IllegalStateException(
                    "EfiAdminPasswordHasher::encryptPassword() - Unable to encrypt password.",
                    e);
        }
    }

public String decryptPassword(String encryptedPassword) {

     // Cannot use StringUtils here, because this class to be serialized and
        // sent over to ACC
        if (encryptedPassword == null || encryptedPassword.trim().length() == 0) {
            return encryptedPassword;
        }
        // DECODE encryptedPwd String
        try {
            final byte[] encrypedPwdBytes = Base64.decodeBase64(encryptedPassword.getBytes());
            final Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");

            byte[] iv = new byte[SIZE];
            cipher.init(Cipher.DECRYPT_MODE, secretKey, new IvParameterSpec(iv));

            final byte[] plainTextPwdBytes = cipher.doFinal(encrypedPwdBytes);

            return new String(plainTextPwdBytes);
        } catch (IllegalBlockSizeException | NoSuchAlgorithmException | NoSuchPaddingException |
                        InvalidKeyException | IllegalStateException | BadPaddingException |
                        InvalidAlgorithmParameterException e) {
            throw new IllegalStateException(
                    "EfiAdminPasswordHasher::decryptPassword() - Unable to decrypt password.",
                    e);
        }
    }

public static void main(String[] args) {
        EfiAdminPasswordHasher hasher = new EfiAdminPasswordHasher();
        String encryptedPassword=hasher.encryptPassword("2");
        System.out.println("Encrypted password"+" "+encryptedPassword);

        String decryptedPassword=hasher.decryptPassword(encryptedPassword);
        System.out.println("Decrypted password"+" "+decryptedPassword);

    }
}

Body:
I found a solution in another post here, try to do this:

final byte[] encrypedPwdBytes = fromHexString(encryptedPassword);
//...
public static byte[] fromHexString(String s) {
    int len = s.length();
    byte[] data = new byte[len / 2];
    for (int i = 0; i < len; i += 2) {
        data[i / 2] = (byte) ((Character.digit(s.charAt(i), 16) << 4)
                             + Character.digit(s.charAt(i+1), 16));
    }
    return data;
}


问:
java.io.IOException: Server returned HTTP response code: 521 for URL:
I want to crawl the data of a URL "http://www.gc-zb.com/index/index.html"
but When I operate like this I got the error:

```<code>public class InvitedBids {

    public static void main(String[] args) throws IOException {

        InputStream inputStream=null;
        HttpURLConnection httpConn=null;
        InputStreamReader inputStreamReader=null;
        BufferedReader bufferedReader=null;
        StringBuilder contentBuf=null;
        String myURL="http://www.gc-zb.com/index/index.html";
        URL url= null;
        try {
            url = new URL(myURL);
            System.out.println(url);
            httpConn= (HttpURLConnection) url.openConnection();
            httpConn.setRequestMethod("GET");

            inputStream=httpConn.getInputStream();  //error occurs
            inputStreamReader=new InputStreamReader(inputStream,"utf-8");
            bufferedReader=new BufferedReader(inputStreamReader);
            String line="";
            contentBuf=new StringBuilder();
            while ((line = bufferedReader.readLine())!= null) {
                contentBuf.append(line);
            }
            String buf=contentBuf.toString();
            System.out.println(buf);
        } catch (Exception e) {
            e.printStackTrace();
        }finally {
           //close I/O and HTTP
        }

    }
}
</code>```

the console says:

```<code>http://www.gc-zb.com/index/index.html
java.io.IOException: Server returned HTTP response code: 521 for URL: http://www.gc-zb.com/index/index.html
    at sun.net.www.protocol.http.HttpURLConnection.getInputStream0(Unknown Source)
    at sun.net.www.protocol.http.HttpURLConnection.getInputStream(Unknown Source)
    at com.feilong.bid.InvitedBids.main(InvitedBids.java:43)
</code>```

Anybody who knows how to solve it .Thank you!

答:
Like Jon said earlier, error 521 means that the server is down. so don't worry and wait until the server is up. cloudflare docs

btw, if you want to crawl documents, I strongly suggest you to use JSOUP to get your data. we use it at my company and it rulz.

ex:

```<code>Document doc = Jsoup.connect("http://example.com/").get();
String title = doc.title();
</code>```

docs:
https://jsoup.org/cookbook/input/load-document-from-url

Body:
I want to crawl the data of a URL "http://www.gc-zb.com/index/index.html"
but When I operate like this I got the error:

public class InvitedBids {

    public static void main(String[] args) throws IOException {

        InputStream inputStream=null;
        HttpURLConnection httpConn=null;
        InputStreamReader inputStreamReader=null;
        BufferedReader bufferedReader=null;
        StringBuilder contentBuf=null;
        String myURL="http://www.gc-zb.com/index/index.html";
        URL url= null;
        try {
            url = new URL(myURL);
            System.out.println(url);
            httpConn= (HttpURLConnection) url.openConnection();
            httpConn.setRequestMethod("GET");

            inputStream=httpConn.getInputStream();  //error occurs
            inputStreamReader=new InputStreamReader(inputStream,"utf-8");
            bufferedReader=new BufferedReader(inputStreamReader);
            String line="";
            contentBuf=new StringBuilder();
            while ((line = bufferedReader.readLine())!= null) {
                contentBuf.append(line);
            }
            String buf=contentBuf.toString();
            System.out.println(buf);
        } catch (Exception e) {
            e.printStackTrace();
        }finally {
           //close I/O and HTTP
        }

    }
}

the console says:

http://www.gc-zb.com/index/index.html
java.io.IOException: Server returned HTTP response code: 521 for URL: http://www.gc-zb.com/index/index.html
    at sun.net.www.protocol.http.HttpURLConnection.getInputStream0(Unknown Source)
    at sun.net.www.protocol.http.HttpURLConnection.getInputStream(Unknown Source)
    at com.feilong.bid.InvitedBids.main(InvitedBids.java:43)

Anybody who knows how to solve it .Thank you!

Body:
Like Jon said earlier, error 521 means that the server is down. so don't worry and wait until the server is up. cloudflare docs

btw, if you want to crawl documents, I strongly suggest you to use JSOUP to get your data. we use it at my company and it rulz.

ex:

Document doc = Jsoup.connect("http://example.com/").get();
String title = doc.title();

docs:
https://jsoup.org/cookbook/input/load-document-from-url


答:
You are over complicating things, you can have more than one thing in the where clause

```<code>SELECT * FROM table WHERE `where`='US' AND sex='boy'；
</code>```

Note you also need quotes around text values, and backticks around reserved words, where is obviously a reserved word. It would be a better idea to think of another column name for that column.

Also sex is normally recorded as male or female or even M or F  rather than boy and girl.

Body:
Use PHP.
then in mysql hava this table

Id     where    name    sex
1      CN       X.ming  boy
2      US       Tom     boy
3      US       jom     boy
4      US       Kim     girl

=====================

first i need get where select * from table where=US

then need get boy select * from (last select) where sex=boy

i find get code is

SELECT * FROM (SELECT * FROM table WHERE where=US) AS a WHERE sex=boy；

but this not good and not fast.

case:

//
my English is no good,so i reply is slow... sorry!!

Body:
You are over complicating things, you can have more than one thing in the where clause

SELECT * FROM table WHERE `where`='US' AND sex='boy'；

Note you also need quotes around text values, and backticks around reserved words, where is obviously a reserved word. It would be a better idea to think of another column name for that column.

Also sex is normally recorded as male or female or even M or F  rather than boy and girl.


问:
Making use of sandy bridge's hardware true random number generator?
I was wondering if there is a way to make use of the new hardware based true number generator found in intel's sandy bridge CPU? I read that intel's MKL (Math Kernel Library) exposes this functionality, but this requires the MKL suite and an intel complier, ending up pretty expensive.

Is there another way to employ the hardware random number generator in my C++ code?
For example a nice, header only library?

答:
Here is the example code:

```<code>#include <immintrin.h>
#include <cstdint>
...
uint64_t val;
if(!_rdseed64_step(&val)) {
  printf("Error generating hardware random value\n");
}
// Now val contains 64-bit pseudo-random number

uint64_t val;
if(!_rdrand64_step(&val)) {
  printf("Error generating hardware random value\n");
}
// Now val contains 64-bit true random number
</code>```

Reference: Intel Intrinsics Guide

Body:
Here is the example code:

#include <immintrin.h>
#include <cstdint>
...
uint64_t val;
if(!_rdseed64_step(&val)) {
  printf("Error generating hardware random value\n");
}
// Now val contains 64-bit pseudo-random number

uint64_t val;
if(!_rdrand64_step(&val)) {
  printf("Error generating hardware random value\n");
}
// Now val contains 64-bit true random number

Reference: Intel Intrinsics Guide


问:
Manually running container exists with code 145
I am trying to manually run the image, that is created through Visual Studio 2017, using docker commands in powershell, with the following command

docker run -d -p 12345:80 webapplication1:dev

But the container exits immediately with Code 145.

```<code>PS C:\WINDOWS\system32> docker images
REPOSITORY         TAG        IMAGE ID            CREATED           SIZE
webapplication1    dev        b4f4585be3d1        6 minutes ago     305MB

PS C:\WINDOWS\system32> docker ps -a
CONTAINER ID  IMAGE                COMMAND                 CREATED        STATUS                        PORTS                   NAMES
41aa3e20e4be  webapplication1:dev  "dotnet WebApplica..."  11 minutes ago Exited (145) 11 minutes ago                           condescending_shaw
</code>```

Running docker logs condescending_shaw shows the following

```<code>PS C:\WINDOWS\system32> docker logs condescending_shaw
  Did you mean to run dotnet SDK commands? Please install dotnet SDK from:
  http://go.microsoft.com/fwlink/?LinkID=798306&clcid=0x409
</code>```

Currently I have  no clue what the Code 145 means and why I cannot run the image manually. So any help what I am doing wrong would be fine. Running the app via Visual Studio 2017 and Docker SupportTools is no problem. The application works just fine.

I also tried creating new images with the Dockerfile. But those containers also exit with 145.

Heres the Dockerfile for reference

```<code>FROM microsoft/aspnetcore:1.1
ARG source
WORKDIR /app
EXPOSE 80
COPY ${source:-publish} .
ENTRYPOINT ["dotnet", "WebApplication1.dll"]
</code>```

答:
Your application probably requieres the SDK and not just the .NET core runtime you are using. Try to use this image instead
https://hub.docker.com/r/microsoft/aspnetcore-build/.</p>

Body:
I am trying to manually run the image, that is created through Visual Studio 2017, using docker commands in powershell, with the following command

docker run -d -p 12345:80 webapplication1:dev

But the container exits immediately with Code 145.

PS C:\WINDOWS\system32> docker images
REPOSITORY         TAG        IMAGE ID            CREATED           SIZE
webapplication1    dev        b4f4585be3d1        6 minutes ago     305MB

PS C:\WINDOWS\system32> docker ps -a
CONTAINER ID  IMAGE                COMMAND                 CREATED        STATUS                        PORTS                   NAMES
41aa3e20e4be  webapplication1:dev  "dotnet WebApplica..."  11 minutes ago Exited (145) 11 minutes ago                           condescending_shaw

Running docker logs condescending_shaw shows the following

PS C:\WINDOWS\system32> docker logs condescending_shaw
  Did you mean to run dotnet SDK commands? Please install dotnet SDK from:
  http://go.microsoft.com/fwlink/?LinkID=798306&clcid=0x409

Currently I have  no clue what the Code 145 means and why I cannot run the image manually. So any help what I am doing wrong would be fine. Running the app via Visual Studio 2017 and Docker SupportTools is no problem. The application works just fine.

I also tried creating new images with the Dockerfile. But those containers also exit with 145.

Heres the Dockerfile for reference

FROM microsoft/aspnetcore:1.1
ARG source
WORKDIR /app
EXPOSE 80
COPY ${source:-publish} .
ENTRYPOINT ["dotnet", "WebApplication1.dll"]


答:
I'm assuming that block_orig, block_pred, block_orig_left, and pred_orig_left are all declared as int**. Only one of them is shown in your code.

The error that you're getting is in the parameter to memcpy, sizeof(int **)*block_orig. You're trying to multiply an integer (sizeof(int**)) with a variable of type int**. The compiler can't make sense of that multiplication.

You need to fix your length parameter to memcpy, but that still won't work as desired.

```<code>// Still won't work.
memcpy(block_orig_left, block_orig, sizeof(int) * BSIZE_Y_LEVEL[levelv] * BSIZE_X_LEVEL[levelv]);
</code>```

An int** is an array of pointers to arrays of integers. If you tried to memcpy the int**, you'll end up overwriting the outer array. Therefore, I think you need a loop and copy the inner arrays.

This should work.

```<code>for(int i = 0; i < BSIZE_Y_LEVEL[levelv]; i++)
{
    memcpy(block_orig_left[i], block_orig[i], sizeof(int) * BSIZE_X_LEVEL[levelv]);
}
</code>```

Title: How to use Memcpy() function

Body:
I'm assuming that block_orig, block_pred, block_orig_left, and pred_orig_left are all declared as int**. Only one of them is shown in your code.

The error that you're getting is in the parameter to memcpy, sizeof(int **)*block_orig. You're trying to multiply an integer (sizeof(int**)) with a variable of type int**. The compiler can't make sense of that multiplication.

You need to fix your length parameter to memcpy, but that still won't work as desired.

// Still won't work.
memcpy(block_orig_left, block_orig, sizeof(int) * BSIZE_Y_LEVEL[levelv] * BSIZE_X_LEVEL[levelv]);

An int** is an array of pointers to arrays of integers. If you tried to memcpy the int**, you'll end up overwriting the outer array. Therefore, I think you need a loop and copy the inner arrays.

This should work.

for(int i = 0; i < BSIZE_Y_LEVEL[levelv]; i++)
{
    memcpy(block_orig_left[i], block_orig[i], sizeof(int) * BSIZE_X_LEVEL[levelv]);
}