问:
Using Font Awesome Pro with Google App Engine
How does one get Font Awesome Pro to work on Google's App Engine in the standard environment?

I've included the .npmrc file with the proper registry settings and authentication token:

```<code>@fortawesome:registry=https://npm.fontawesome.com/
//npm.fontawesome.com/:_authToken=XXXXXXXXXXXXXXXX
</code>```

However after I deploy the code, I get the following:

```<code>Step #1 - "builder": npm ERR! code E404
Step #1 - "builder": npm ERR! 404 Not Found - GET https://registry.npmjs.org/@fortawesome%2ffontawesome-pro - Not found
Step #1 - "builder": npm ERR! 404
Step #1 - "builder": npm ERR! 404  '@fortawesome/fontawesome-pro@^5.12.1' is not in the npm registry.
Step #1 - "builder": npm ERR! 404 You should bug the author to publish it (or use the name yourself!)
Step #1 - "builder": npm ERR! 404 It was specified as a dependency of 'workspace'
Step #1 - "builder": npm ERR! 404
Step #1 - "builder": npm ERR! 404 Note that you can also install from a
Step #1 - "builder": npm ERR! 404 tarball, folder, http url, or git url.
Step #1 - "builder":
Step #1 - "builder": npm ERR! A complete log of this run can be found in:
Step #1 - "builder": npm ERR!     /builder/home/.npm/_logs/2020-02-10T16_36_28_563Z-debug.log
Step #1 - "builder":
Step #1 - "builder": ERROR    error: `gen_package_lock` returned code: 1
Step #1 - "builder": INFO     gen_package_lock took 13 seconds
Step #1 - "builder": INFO     builder initialization took 13 seconds
Step #1 - "builder": INFO     full build took 13 seconds
Step #1 - "builder": ERROR    `gen_package_lock` had stderr output:
Step #1 - "builder": npm WARN deprecated core-js@2.6.11: core-js@<3 is no longer maintained and not recommended for usage due to the number of issues. Please, upgrade your dependencies to the actual version of core-js@3.
Step #1 - "builder": npm ERR! code E404
Step #1 - "builder": npm ERR! 404 Not Found - GET https://registry.npmjs.org/@fortawesome%2ffontawesome-pro - Not found
Step #1 - "builder": npm ERR! 404
Step #1 - "builder": npm ERR! 404  '@fortawesome/fontawesome-pro@^5.12.1' is not in the npm registry.
Step #1 - "builder": npm ERR! 404 You should bug the author to publish it (or use the name yourself!)
Step #1 - "builder": npm ERR! 404 It was specified as a dependency of 'workspace'
Step #1 - "builder": npm ERR! 404
Step #1 - "builder": npm ERR! 404 Note that you can also install from a
Step #1 - "builder": npm ERR! 404 tarball, folder, http url, or git url.
Step #1 - "builder":
</code>```

Apparently it's not recognizing the .npmrc as the URL endpoint still points to https://registry.npmjs.org. Any advice?

答: Discovered this was because of my .gcloudignore file. I need to exclude the .npmrc file being ignored.</p>

Body:
How does one get Font Awesome Pro to work on Google's App Engine in the standard environment?

I've included the .npmrc file with the proper registry settings and authentication token:

@fortawesome:registry=https://npm.fontawesome.com/
//npm.fontawesome.com/:_authToken=XXXXXXXXXXXXXXXX

However after I deploy the code, I get the following:

Step #1 - "builder": npm ERR! code E404
Step #1 - "builder": npm ERR! 404 Not Found - GET https://registry.npmjs.org/@fortawesome%2ffontawesome-pro - Not found
Step #1 - "builder": npm ERR! 404
Step #1 - "builder": npm ERR! 404  '@fortawesome/fontawesome-pro@^5.12.1' is not in the npm registry.
Step #1 - "builder": npm ERR! 404 You should bug the author to publish it (or use the name yourself!)
Step #1 - "builder": npm ERR! 404 It was specified as a dependency of 'workspace'
Step #1 - "builder": npm ERR! 404
Step #1 - "builder": npm ERR! 404 Note that you can also install from a
Step #1 - "builder": npm ERR! 404 tarball, folder, http url, or git url.
Step #1 - "builder":
Step #1 - "builder": npm ERR! A complete log of this run can be found in:
Step #1 - "builder": npm ERR!     /builder/home/.npm/_logs/2020-02-10T16_36_28_563Z-debug.log
Step #1 - "builder":
Step #1 - "builder": ERROR    error: `gen_package_lock` returned code: 1
Step #1 - "builder": INFO     gen_package_lock took 13 seconds
Step #1 - "builder": INFO     builder initialization took 13 seconds
Step #1 - "builder": INFO     full build took 13 seconds
Step #1 - "builder": ERROR    `gen_package_lock` had stderr output:
Step #1 - "builder": npm WARN deprecated core-js@2.6.11: core-js@<3 is no longer maintained and not recommended for usage due to the number of issues. Please, upgrade your dependencies to the actual version of core-js@3.
Step #1 - "builder": npm ERR! code E404
Step #1 - "builder": npm ERR! 404 Not Found - GET https://registry.npmjs.org/@fortawesome%2ffontawesome-pro - Not found
Step #1 - "builder": npm ERR! 404
Step #1 - "builder": npm ERR! 404  '@fortawesome/fontawesome-pro@^5.12.1' is not in the npm registry.
Step #1 - "builder": npm ERR! 404 You should bug the author to publish it (or use the name yourself!)
Step #1 - "builder": npm ERR! 404 It was specified as a dependency of 'workspace'
Step #1 - "builder": npm ERR! 404
Step #1 - "builder": npm ERR! 404 Note that you can also install from a
Step #1 - "builder": npm ERR! 404 tarball, folder, http url, or git url.
Step #1 - "builder":

Apparently it's not recognizing the .npmrc as the URL endpoint still points to https://registry.npmjs.org. Any advice?


来源: stackexchange

问:
Why writing the directive access_log on twice actually turn off log?
The following nginx.conf can show the peoblem

```<code>server {
    listen 80;
    access_log /var/log/nginx/access.log combined;
    access_log on;
    ...
    location / {
      access_log on;  # write it the second time actually turn off the log!
      ...
    }
    ...
 }
</code>```

So write access_log on; twice actually turn off the log. Why is that ? I can't help wondering is it a bug ?

Thanks

---- update ----

It turned that there is only access_log off directive, no access_log on (no idea why I got that in the first place :$) so when I wrote access_log on the log was wrote to a file called "on", not /var/log/nginx/access.log as I expected. So I thought why there is no log ?! :$

答:
This is the expected behavior. From NGINX blog:

Access Logs Are Not Inherited

Access log settings do not stack or inherit; an access_log directive in one context overrides (replaces) access logs declared in parent contexts.

So if you don't put access_log on; in location / { then you get two log files because the ones in server context will apply. Contrary, if you put access_log on; in location / { then the outer scope's access log configuration will not apply.

ContentLicense: CC BY-SA 4.0

Body:
The following nginx.conf can show the peoblem

server {
    listen 80;
    access_log /var/log/nginx/access.log combined;
    access_log on;
    ...
    location / {
      access_log on;  # write it the second time actually turn off the log!
      ...
    }
    ...
 }

So write access_log on; twice actually turn off the log. Why is that ? I can't help wondering is it a bug ?

Thanks

---- update ----

It turned that there is only access_log off directive, no access_log on (no idea why I got that in the first place :$) so when I wrote access_log on the log was wrote to a file called "on", not /var/log/nginx/access.log as I expected. So I thought why there is no log ?! :$


问:
Message "flutter run: No connected devices"
I am trying to create a sample application with Flutter (fresh installation). Android Studio is also installed (fresh installation).

Here is the output of flutter run

```<code>flutter run
No connected devices.
</code>```

The output of flutter doctor:

Doctor summary (to see all details, run flutter doctor -v):
[✓] Flutter (Channel beta, v0.1.5, on Linux, locale en_US.UTF-8)
[✓] Android toolchain - develop for Android devices (Android SDK 27.0.3)
[✓] Android Studio (version 3.0)
[!] VS Code (version 1.20.1)
[!] Connected devices
! No devices available

! Doctor found issues in 2 categories.
```

Is there a solution to this problem?

答:
I recently faced the same problem. I am using macOS and the iOS simulator. The flutter devices command shows No devices detected.

Then I run the flutter doctor command and it says my Xcode installation is incomplete,

But it's not true (I verify it by building native iOS app and it runs
well)!

I didn't reinstall/download Xcode again. I just ran those two commands according to their suggestions:

```<code>sudo xcode-select --switch /Applications/Xcode.app/Contacts/Developer
sudo xcodebuild -runFirstLaunch
</code>```

And it solves my problem. Here is the final flutter doctor command output.

Body:
I am trying to create a sample application with Flutter (fresh installation). Android Studio is also installed (fresh installation).

Here is the output of flutter run

flutter run
No connected devices.

The output of flutter doctor:

Doctor summary (to see all details, run flutter doctor -v):
[✓] Flutter (Channel beta, v0.1.5, on Linux, locale en_US.UTF-8)
[✓] Android toolchain - develop for Android devices (Android SDK 27.0.3)
[✓] Android Studio (version 3.0)
[!] VS Code (version 1.20.1)
[!] Connected devices
! No devices available

! Doctor found issues in 2 categories.

Is there a solution to this problem?

Body:
I recently faced the same problem. I am using macOS and the iOS simulator. The flutter devices command shows No devices detected.

Then I run the flutter doctor command and it says my Xcode installation is incomplete,

But it's not true (I verify it by building native iOS app and it runs
well)!

I didn't reinstall/download Xcode again. I just ran those two commands according to their suggestions:

sudo xcode-select --switch /Applications/Xcode.app/Contacts/Developer
sudo xcodebuild -runFirstLaunch

And it solves my problem. Here is the final flutter doctor command output.


问:
Laravel MySQL groupby created_at with date format without time
I have a table column named created_at type datetime.
and I want to use groupby for created_at with date only and without time.
Here's my existing code :

```<code>$data = BloodPressureHistory::where('user_id', $id)
    ->groupBy('created_at')
    ->orderBy('created_at', 'DESC')
    ->paginate(7);
</code>```

答:
```<code>  $data = BloodPressureHistory::where('user_id', $id)
        ->groupBy(function ($item){
            return \Illuminate\Support\Carbon::parse($item->created_at)->format('Y-m-d');
        })
        ->orderBy('created_at', 'DESC')
        ->paginate(7);
</code>```

Body:
I have a table column named created_at type datetime.
and I want to use groupby for created_at with date only and without time.
Here's my existing code :

$data = BloodPressureHistory::where('user_id', $id)
    ->groupBy('created_at')
    ->orderBy('created_at', 'DESC')
    ->paginate(7);


问:
creating s3 bucket and folders inside it using node js in aws lambda function
I am both new to Node js and AWS. I am trying to create a bucket in S3 using node js in lambda function. Consequently, I am trying to create folders inside this S3 bucket.

I followed all the questions answered before and tried different iterations of code, but none of them seem to be working. Following is my code which is executing without giving any issues, yet the bucket and the folders are not getting created.

```<code>const AWS = require('aws-sdk');

let s3Client = new AWS.S3({
  accessKeyId: '<access_key_id>',
  secretAccessKey: '<secret_access_key>'
});

var params = {
  Bucket : 'pshycology06'
};

exports.handler = async (event, context, callback) => {

// call spaces to create the bucket
    s3Client.createBucket(params, function(err, data) {
      if (err) {
        console.log("\r\n[ERROR] : ", err);
      } else {
        console.log("\r\n[SUCCESS] : data = ",data);
      }
    });
};
</code>```

The code for creating folders inside the Lambda function is as following --

```<code>var AWS = require('aws-sdk');
AWS.config.region = 'us-east-1';
var s3Client = new AWS.S3({apiVersion: '2006-03-01'});

exports.handler = async (event, context) => {

    let params1 = { Bucket: 'travasko', Key: '2/dir1/dir2', Body:'body does not matter' };

    s3Client.putObject(params1, function (err, data) {
        if (err) {
            console.log("Error creating the folder: ", err);
        } else {
            console.log("Successfully created a folder on S3");
        }
    });
</code>```

Both of them doesn't work. I read a lot of documents on this issue and answers previously asked, but none of them are working for me.

The lambda function has a timeout of 1 minute. It has following policies for the IAM role -
1. AmazonRDSFullAccess
2. AmazonS3FullAccess
3. AWSLambdaVPCExecutionRole

The VPC security group is the default one.

Also, when I am trying to create the same bucket using the following AWS CLI command, it creates the bucket.

```<code>aws s3api create-bucket --bucket psychology06 --region us-east-1

</code>```

I am not sure, where am i making a mistake.

答:
As you are new, always try aws cli(not recommended) and then search for search for equivalent sdk function while implementing.As it(your code) is async it won't wait until the call back function executes , so you can try something like below.(This is not actual solution , it just tells how to wait until the call back does it's work.)

```<code>    'use strict'

    var AWS = require('aws-sdk');
    AWS.config.region = 'us-east-1';
    var s3Client = new AWS.S3({ apiVersion: '2006-03-01' });

    exports.handler = async (event, context) => {
        let params1 = { Bucket: 'travasko', Key: '2/dir1/dir2', Body: 'body does not matter' };
        try {
            let obj = await something(params1);
            callback(null, obj);
        }
        catch (err) {
            callback('error', err)
        }
    }

    async function something(params1) {
        return new Promise(async (resolve, reject) => {
            await s3Client.putObject(params1, function (err, data) {
                if (err) {
                    console.log('Error creating the folder:', err);
                    reject('error during putObject');
                } else {
                    console.log('success' + JSON.stringify(data));
                    resolve('success');
                }
            });
        });
    }
</code>```

To your question in the comments :
Hi Vinit , let me give you little background , the question you have asked is very generic.  Firstly VPC is something which you create where you will have your organization private and public subnets that are used to run your ec2 or any hosted services (non-managed services by aws). But as lambda is managed service it runs in aws vpc , they usually take your code and lambda configurations and execute the code.Now coming to your question if we attach vpc in your lambda configurations ( only if your lambda needs to use services hosted in your vpc, else don't use it) then as we discussed lambda runs in aws vpc , so  during cold start it created an ENI(think of it as elastic IP) and tries to communicate with your VPC. Before Re-invent an ENI was created for each lambda that was the reason it takes time for the first time and lambda used to time out even though your execution takes lesser time. Now after re-invent EIP's are created per subnet per security group. So now coming to your question when u have attached vpc, if lambda execution is taking more time or not working as expected, then you have to see how your vpc(configs, routes, subnets) is set up and it's very hard to answer as so many parameters are involved unless we debug. So short answer do not attach vpc if your function(code) does not need to talk to any of your own managed instances in vpc (usually private subnet
) etc.

Body:
I am both new to Node js and AWS. I am trying to create a bucket in S3 using node js in lambda function. Consequently, I am trying to create folders inside this S3 bucket.

I followed all the questions answered before and tried different iterations of code, but none of them seem to be working. Following is my code which is executing without giving any issues, yet the bucket and the folders are not getting created.

const AWS = require('aws-sdk');

let s3Client = new AWS.S3({
  accessKeyId: '<access_key_id>',
  secretAccessKey: '<secret_access_key>'
});

var params = {
  Bucket : 'pshycology06'
};

exports.handler = async (event, context, callback) => {

// call spaces to create the bucket
    s3Client.createBucket(params, function(err, data) {
      if (err) {
        console.log("\r\n[ERROR] : ", err);
      } else {
        console.log("\r\n[SUCCESS] : data = ",data);
      }
    });
};

The code for creating folders inside the Lambda function is as following --

var AWS = require('aws-sdk');
AWS.config.region = 'us-east-1';
var s3Client = new AWS.S3({apiVersion: '2006-03-01'});

exports.handler = async (event, context) => {

    let params1 = { Bucket: 'travasko', Key: '2/dir1/dir2', Body:'body does not matter' };

    s3Client.putObject(params1, function (err, data) {
        if (err) {
            console.log("Error creating the folder: ", err);
        } else {
            console.log("Successfully created a folder on S3");
        }
    });

Both of them doesn't work. I read a lot of documents on this issue and answers previously asked, but none of them are working for me.

The lambda function has a timeout of 1 minute. It has following policies for the IAM role -
1. AmazonRDSFullAccess
2. AmazonS3FullAccess
3. AWSLambdaVPCExecutionRole

The VPC security group is the default one.

Also, when I am trying to create the same bucket using the following AWS CLI command, it creates the bucket.

aws s3api create-bucket --bucket psychology06 --region us-east-1

I am not sure, where am i making a mistake.

Body:
As you are new, always try aws cli(not recommended) and then search for search for equivalent sdk function while implementing.As it(your code) is async it won't wait until the call back function executes , so you can try something like below.(This is not actual solution , it just tells how to wait until the call back does it's work.)

    'use strict'

    var AWS = require('aws-sdk');
    AWS.config.region = 'us-east-1';
    var s3Client = new AWS.S3({ apiVersion: '2006-03-01' });

    exports.handler = async (event, context) => {
        let params1 = { Bucket: 'travasko', Key: '2/dir1/dir2', Body: 'body does not matter' };
        try {
            let obj = await something(params1);
            callback(null, obj);
        }
        catch (err) {
            callback('error', err)
        }
    }

    async function something(params1) {
        return new Promise(async (resolve, reject) => {
            await s3Client.putObject(params1, function (err, data) {
                if (err) {
                    console.log('Error creating the folder:', err);
                    reject('error during putObject');
                } else {
                    console.log('success' + JSON.stringify(data));
                    resolve('success');
                }
            });
        });
    }

To your question in the comments :
Hi Vinit , let me give you little background , the question you have asked is very generic.  Firstly VPC is something which you create where you will have your organization private and public subnets that are used to run your ec2 or any hosted services (non-managed services by aws). But as lambda is managed service it runs in aws vpc , they usually take your code and lambda configurations and execute the code.Now coming to your question if we attach vpc in your lambda configurations ( only if your lambda needs to use services hosted in your vpc, else don't use it) then as we discussed lambda runs in aws vpc , so  during cold start it created an ENI(think of it as elastic IP) and tries to communicate with your VPC. Before Re-invent an ENI was created for each lambda that was the reason it takes time for the first time and lambda used to time out even though your execution takes lesser time. Now after re-invent EIP's are created per subnet per security group. So now coming to your question when u have attached vpc, if lambda execution is taking more time or not working as expected, then you have to see how your vpc(configs, routes, subnets) is set up and it's very hard to answer as so many parameters are involved unless we debug. So short answer do not attach vpc if your function(code) does not need to talk to any of your own managed instances in vpc (usually private subnet
) etc.


问:
which is a better approach for fibonacci series generation
The two general approaches for Fibonacci series generation are:

The traditional approach, i.e., running through a for loop inside a function.

Recursion

I came across another solution

```<code>#include <iostream>

using namespace std;

void fibo() {
 static int y = 0;
 static int x = 1;
 cout << y << endl;
 y = x + y;
 x = y - x;
}

int main() {
 for (int i = 1; i <= 1; i++) {
  fibo();
 }
 return 0;
}
</code>```

This solution looks to be working fine in the initial runs, but when compared to the traditional and recursion approach, does this hold any significant disadvantages?

I am sure static variables would add to space complexity, but at least we are not building a function table stack using recursion, correct?

答:
I think this pointer approach would be more useful for you.</p>

```<code>void main()
{
    int i,p, *no,factorial,summ;

    int fib(int p);

    clrscr();

    printf("\n Enter The Number:");
    scanf("%d", no);
    printf("\n The Fibonnacci series: \n");

    for(i=0; i < *no; i++)
        printf("%d\n", fib(i));

    getch();
}

int fib(int p)
{
    if(p == 0)
        return(0);
    if(p >= 1 && p <= 2)
        return(1);
    else
        return(fib(p - 1) + fib(p - 2));
}
</code>```

ContentLicense: CC BY-SA 3.0

Body:
The two general approaches for Fibonacci series generation are:

The traditional approach, i.e., running through a for loop inside a function.

Recursion

I came across another solution

#include <iostream>

using namespace std;

void fibo() {
 static int y = 0;
 static int x = 1;
 cout << y << endl;
 y = x + y;
 x = y - x;
}

int main() {
 for (int i = 1; i <= 1; i++) {
  fibo();
 }
 return 0;
}

This solution looks to be working fine in the initial runs, but when compared to the traditional and recursion approach, does this hold any significant disadvantages?

I am sure static variables would add to space complexity, but at least we are not building a function table stack using recursion, correct?

Body:
I think this pointer approach would be more useful for you.

void main()
{
    int i,p, *no,factorial,summ;

    int fib(int p);

    clrscr();

    printf("\n Enter The Number:");
    scanf("%d", no);
    printf("\n The Fibonnacci series: \n");

    for(i=0; i < *no; i++)
        printf("%d\n", fib(i));

    getch();
}

int fib(int p)
{
    if(p == 0)
        return(0);
    if(p >= 1 && p <= 2)
        return(1);
    else
        return(fib(p - 1) + fib(p - 2));
}


问:
ios - sharing data between apps, but linked to AppleID
I'm developing 2 apps, which are already have done for Android, and trying not to confused with Apple's security frameworks.

Here is the Android apps scheme:

App1 create and save locally(as SQLite database) User's account

at App1 user can save/resume backup to/from filesystem (using SQLite3 and SHA256)

at App2 user can check, if is there any saved account, then use this saved data (for ex., token) for some http requests

so user account is linked to device

I've found, that at iOS I should better save data linked to AppleID, to protect it when AppleID is switched to another, so for my case (saving token at App1, then have access to it from App2) CloudKit, or maybe KeyChain, is good choice, right? At least better, than store it locally on the device, even hashed before.

So I need to save cloudly:

some Bool/String property to show if App1 is installed;

another Bool/String to show if is there saved account data;

some data as [String: Any]

And saving should be depending on AppleID - by the way, is it possible to detect, if User is login at the iCloud at this time?

So my question is - what scheme should I use to keep my data secure and share it between apps? Is iCloud with CloudKit a good decision? Or Keychain will be better?

答: Use keychain with app groups, so all your apps can access the secured data which will stored in keychain.</p>


问:
Maven Surefire Run Tests Command Line String Limitation (-Dtest=x.y.z#abc)
I'm using Maven Surefire to run a subset of my test cases via Jenkins on a Windows Server.

To specify the test cases to be run, I execute:

```<code>mvn surefire:test -DfailIfNoTests=false -Dtest=x.y.z#a,x.y.z#b
</code>```

The problem is that on Windows (CMD.exe) there is a Command Line String Limitation which does not allow for a very long list of tests to be executed (limit 8191 characters).

Does anybody have an idea whether I can maybe use a file as an input for the -Dtest parameter (i.e. -Dtest=testcases.txt) or any other ideas to solve this problem?

I know I could switch to Groovy scripts in the Jenkins rather than CMD.exe, but I want to avoid that.

UPDATE [21st Jan 2020]

Two things I must clarfiy:

I'm selecting the test cases dynamically in a Maven multi-module project, which means adjusting the pom.xml is generally an option, but I wanted to avoid it.

I already tried calling the command from a Python script rather than directly calling it in Window's cmd.exe:

import subprocess

command = 'mvn surefire:test -Dtest={} -DfailIfNoTests=false'.format(tests)
subprocess.call(command, shell=True)
```

<p>This doesn't work either, maybe Powershell is an option as @mark-bramnik suggested?</p>

<p><strong>UPDATE [17th Feb 2020]</strong></p>

<p>Powershell and/or <code>.bat</code> do not work either, nor does running it inside a <code>.sh</code> script from the Windows Git bash work.
When running it via the <code>.sh</code> script, I get an error related to the JDK:</p>

```/c/maven-3.6.1/bin/mvn: line 191: /c/Program Files/Java/jdk-11/bin/java: Argument list too long
/c/maven-3.6.1/bin/mvn: line 191: /c/Program Files/Java/jdk-11/bin/java: No error
```

Apparently, the limit to command length is inherently present on the Windows OS.

答: Found a solution using Maven Surefire's option -Dsurefire.includesFile which can apparently be used similarly to -Dtest, except that you can provide a file with the test names.

Body:
I'm using Maven Surefire to run a subset of my test cases via Jenkins on a Windows Server.

To specify the test cases to be run, I execute:

mvn surefire:test -DfailIfNoTests=false -Dtest=x.y.z#a,x.y.z#b

The problem is that on Windows (CMD.exe) there is a Command Line String Limitation which does not allow for a very long list of tests to be executed (limit 8191 characters).

Does anybody have an idea whether I can maybe use a file as an input for the -Dtest parameter (i.e. -Dtest=testcases.txt) or any other ideas to solve this problem?

I know I could switch to Groovy scripts in the Jenkins rather than CMD.exe, but I want to avoid that.

UPDATE [21st Jan 2020]

Two things I must clarfiy:

I'm selecting the test cases dynamically in a Maven multi-module project, which means adjusting the pom.xml is generally an option, but I wanted to avoid it.

I already tried calling the command from a Python script rather than directly calling it in Window's cmd.exe:

import subprocess

command = 'mvn surefire:test -Dtest={} -DfailIfNoTests=false'.format(tests)
subprocess.call(command, shell=True)

This doesn't work either, maybe Powershell is an option as @mark-bramnik suggested?

UPDATE [17th Feb 2020]

Powershell and/or .bat do not work either, nor does running it inside a .sh script from the Windows Git bash work.
When running it via the .sh script, I get an error related to the JDK:

/c/maven-3.6.1/bin/mvn: line 191: /c/Program Files/Java/jdk-11/bin/java: Argument list too long
/c/maven-3.6.1/bin/mvn: line 191: /c/Program Files/Java/jdk-11/bin/java: No error

Apparently, the limit to command length is inherently present on the Windows OS.


问:
Oracle ora_rowscn to get delta
ora_rowscn as definition from oracle,

You cannot use this pseudocolumn in a query to a view

so can I use the ora_rowscn column to get the delta and updated data from the oracle table in my ETL job?

答:
Unfortunately even if you use ROWDEPENDENCIES you can hardly rely on SCN - for replication purposes. There are situations where SCN can change or is generated at COMMIT time.

ORA_ROWSCN Pseudocolumn

For each row, ORA_ROWSCN returns the conservative upper bound system
  change number (SCN) of the most recent change to the row. This
  pseudocolumn is useful for determining approximately when a row was
  last updated. It is not absolutely precise, because Oracle tracks SCNs
  by transaction committed for the block in which the row resides.

Search for "delayed block clean out"

Title: Oracle ora_rowscn to get delta


问:
Google TTS <par> tags not working the way as expected
I was looking into Google TTS and found the following example with a par tag:

https://cloud.google.com/text-to-speech/docs/ssml#par

In the example, the audio is built properly. There are two sentences and some sounds in the background. However, if you actually use this with their API or the console, it doesn't work. You only get two sentences back and no audio is played. Link to the TTS console:

https://cloud.google.com/text-to-speech

This is the SSML that I was using:

```<code><par>
    <media xml:id="question" begin="0.5s">
      <speak>Who invented the Internet?</speak>
    </media>
    <media xml:id="answer" begin="question.end+2.0s">
      <speak>The Internet was invented by cats.</speak>
    </media>
    <media begin="answer.end-0.2s" soundLevel="-6dB">
      <audio
        src="https://actions.google.com/sounds/v1/cartoon/cartoon_boing.ogg"/>
    </media>
    <media repeatCount="3" soundLevel="+2.28dB"
      fadeInDur="2s" fadeOutDur="0.2s">
      <audio
        src="https://actions.google.com/sounds/v1/animals/cat_purr_close.ogg"/>
    </media>
  </par>
</code>```

What am I doing wrong? Or is there something wrong with the TTS service itself?

答:
There is certainly something strange about the TTS console, for starters. If you look at the JSON that it says should be used, you'll note that it has omitted the <par> tag. Inspecting the network traffic shows the same thing. I also noticed that the <speech> tag needed to be omitted.

If you try this as part of the Action Simulator Console, the output does work correctly. You can get to the Action Simulator by going to https://console.actions.google.com/, picking a project to work with, and going to the "Test" tab. In the simulator itself, you then select the "Audio" tab and can enter SSML (including the <speech> tag) into the editor and then press the "Update and Listen" button.

Body:
I was looking into Google TTS and found the following example with a par tag:

https://cloud.google.com/text-to-speech/docs/ssml#par

In the example, the audio is built properly. There are two sentences and some sounds in the background. However, if you actually use this with their API or the console, it doesn't work. You only get two sentences back and no audio is played. Link to the TTS console:

https://cloud.google.com/text-to-speech

This is the SSML that I was using:

<par>
    <media xml:id="question" begin="0.5s">
      <speak>Who invented the Internet?</speak>
    </media>
    <media xml:id="answer" begin="question.end+2.0s">
      <speak>The Internet was invented by cats.</speak>
    </media>
    <media begin="answer.end-0.2s" soundLevel="-6dB">
      <audio
        src="https://actions.google.com/sounds/v1/cartoon/cartoon_boing.ogg"/>
    </media>
    <media repeatCount="3" soundLevel="+2.28dB"
      fadeInDur="2s" fadeOutDur="0.2s">
      <audio
        src="https://actions.google.com/sounds/v1/animals/cat_purr_close.ogg"/>
    </media>
  </par>

What am I doing wrong? Or is there something wrong with the TTS service itself?


问:
How to delete a XML child node using SQL Server 2016
I have the following Xml example snippet taken from a larger file:

```<code><EntityAttributeValue>
  <Value />
  <Attribute>
    <Id>0</Id>
    <Name>Use 3</Name>
    <AttributeType>other</AttributeType>
  </Attribute>
  <AttributeValueId>999998</AttributeValueId>
  <ProductTypeId xsi:nil="true" />
</EntityAttributeValue>
</code>```

I am trying to remove the <ProductTypeId> node using SQL so that the above will look like this:

```<code><EntityAttributeValue>
  <Value />
  <Attribute>
    <Id>13</Id>
    <Name>Use 3</Name>
    <AttributeType>other</AttributeType>
  </Attribute>
  <AttributeValueId>999998</AttributeValueId>
</EntityAttributeValue>
</code>```

I have used the following to SQL query the XML and isolate the above snippet(first one)

```<code>select t.c.query('.') as Attributes
from @XMLData.nodes('/Item/ContentAttributeValues/EntityAttributeValue') t(c)
where t.c.value('(Attribute/Id)[1]','INT') = 0
</code>```

I have tried

```<code>SET @XMLData.modify('delete (/Item/ContentAttributeValues/EntityAttributeValue/ProductTypeId)')
</code>```

to remove all the product ids, but to no avail, any help would be greatly recieved.

Cheers

答:
From your code I take, that you are searching for the <ProductTypeId> of the EAV-element, where the <Attribute><Id> has the value 0.

Your question is not all clear, but I think you might be looking for this:

```<code>declare @tbl TABLE(ID INT IDENTITY, YourXml XML);
INSERT INTO @tbl VALUES
(N'<Item xmlns:xsi="blahblah">
  <ContentAttributeValues>
    <EntityAttributeValue>
      <Value />
      <Attribute>
        <Id>0</Id>                                     <!-- Id value = 0  -->
        <Name>Use 3</Name>
        <AttributeType>other</AttributeType>
      </Attribute>
      <AttributeValueId>999998</AttributeValueId>
      <ProductTypeId xsi:nil="true" />
    </EntityAttributeValue>
    <EntityAttributeValue>
      <Value />
      <Attribute>
        <Id>1</Id>                                      <!-- Other Id value!!!  -->
        <Name>Use 3</Name>
        <AttributeType>other</AttributeType>
      </Attribute>
      <AttributeValueId>999998</AttributeValueId>
      <ProductTypeId xsi:nil="true" />
    </EntityAttributeValue>
  </ContentAttributeValues>
</Item>');

UPDATE @tbl SET YourXml.modify(N'delete /Item
                                        /ContentAttributeValues
                                        /EntityAttributeValue[Attribute/Id = 0]
                                        /ProductTypeId');

SELECT * FROM @tbl;
</code>```

The XPath stands for: Dive into the EAV-element and filter for the element(s), which answer the predicate. Below this EAV-element find the <ProductTypeID> and delete it.

In the result you will find, that the node was deleted only for the first EAV-element, which has Id=0.

Body:
I have the following Xml example snippet taken from a larger file:

<EntityAttributeValue>
  <Value />
  <Attribute>
    <Id>0</Id>
    <Name>Use 3</Name>
    <AttributeType>other</AttributeType>
  </Attribute>
  <AttributeValueId>999998</AttributeValueId>
  <ProductTypeId xsi:nil="true" />
</EntityAttributeValue>

I am trying to remove the <ProductTypeId> node using SQL so that the above will look like this:

<EntityAttributeValue>
  <Value />
  <Attribute>
    <Id>13</Id>
    <Name>Use 3</Name>
    <AttributeType>other</AttributeType>
  </Attribute>
  <AttributeValueId>999998</AttributeValueId>
</EntityAttributeValue>

I have used the following to SQL query the XML and isolate the above snippet(first one)

select t.c.query('.') as Attributes
from @XMLData.nodes('/Item/ContentAttributeValues/EntityAttributeValue') t(c)
where t.c.value('(Attribute/Id)[1]','INT') = 0

I have tried

SET @XMLData.modify('delete (/Item/ContentAttributeValues/EntityAttributeValue/ProductTypeId)')

to remove all the product ids, but to no avail, any help would be greatly recieved.

Cheers

Body:
From your code I take, that you are searching for the <ProductTypeId> of the EAV-element, where the <Attribute><Id> has the value 0.

Your question is not all clear, but I think you might be looking for this:

declare @tbl TABLE(ID INT IDENTITY, YourXml XML);
INSERT INTO @tbl VALUES
(N'<Item xmlns:xsi="blahblah">
  <ContentAttributeValues>
    <EntityAttributeValue>
      <Value />
      <Attribute>
        <Id>0</Id>                                     <!-- Id value = 0  -->
        <Name>Use 3</Name>
        <AttributeType>other</AttributeType>
      </Attribute>
      <AttributeValueId>999998</AttributeValueId>
      <ProductTypeId xsi:nil="true" />
    </EntityAttributeValue>
    <EntityAttributeValue>
      <Value />
      <Attribute>
        <Id>1</Id>                                      <!-- Other Id value!!!  -->
        <Name>Use 3</Name>
        <AttributeType>other</AttributeType>
      </Attribute>
      <AttributeValueId>999998</AttributeValueId>
      <ProductTypeId xsi:nil="true" />
    </EntityAttributeValue>
  </ContentAttributeValues>
</Item>');

UPDATE @tbl SET YourXml.modify(N'delete /Item
                                        /ContentAttributeValues
                                        /EntityAttributeValue[Attribute/Id = 0]
                                        /ProductTypeId');

SELECT * FROM @tbl;

The XPath stands for: Dive into the EAV-element and filter for the element(s), which answer the predicate. Below this EAV-element find the <ProductTypeID> and delete it.

In the result you will find, that the node was deleted only for the first EAV-element, which has Id=0.


问:
C - charting a bar graph using 2D array - wont chart negative values
Hello everyone and thanks for taking your time to read this. I am doing an exercise where I'm given an array of integers and each integer represents the "height" of one bar in the chart. Negative values mean that the bar extends below the horizontal axis. So, if I am given an array of 4 integers, there would exactly be 4 bars in the chart.

I used a 2D array of characters to try to complete this exercise.

note: the text of the exercise says that there should be two spaces between each bar in the graph, so that's why I increment the j control variable by three in each pass.

I am having problems with the negative values. No matter what I do, the negative values won't print out on the screen.

What I have tried is the following: I determined the width of the graph by multiplying the array size by three. I then set all fields of the 2D array to spaces except for the horizontal line in the middle.

The outer, j loop iterates through the columns of the matrix. I have only one loop for this because, in every pass through the j loop we start in the 10th row.

the k loop actually does the plotting. The loop goes from zero to number-1, leaving a space for the asterisk at the top (or bottom).

I have two if statements checking if the number is <0 or >0, because in those two instances the bar is supposed to show up differently.

Here is my code:

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

int main()
{

    char mat[30][40];
    int i,j, size=0, m=20, n=40;

    int arr[7] = {1,2,-3,4,-5,6,-7};
    size=7;

    n=size*3; // n is the width of the graph

    for(i=0; i<m; i++) {          // I set all fields of the 2D array to spaces
        for(j=0; j<n; j++) {      // except for the horizontal line
            if(i==10) mat[i][j]='-';
            else mat[i][j]=' ';
        }
    }
    int k;
    int position=0; // position is the variable I use to iterate through the array
    int l;

    for(j=0; j<n; j+=3) {
        l=10;

        for( k = 0; k<arr[position]-1; k++) {
            if(arr[position]==0) {
                mat[10][j] = '*';    // if the height is zero, put an asterisk
            }

            else if((arr[position])<0) {

                l++;                    // if the number is negative,
                mat[l][j]='|';          // the bar extends below the horizontal line
            }

            else if(arr[position]>0) {

                l--;              // if the number is positive, the bar extends above the
                mat[l][j] = '|';  // horizontal line
            }

        }

        if(arr[position]>0) mat[l-1][j]='*';  //every bar ends with an asterisk
        else if(arr[position]<0) {
            mat[l+1][j]='*';
        }

        position++;  // jump to the next element in array

    }

    for(i=0; i<m; i++) {
        for(j=0; j<n; j++) {
            printf("%c",mat[i][j]);
        }
        printf("\n");
    }

    return 0;
}
</code>```

For negative numbers it just does not work. Furthermore I have made some tests and the condition else if((arr[position])<0)
is never fulfilled and I don't know why. What it does is it puts an asterisk below the horizontal line but that's about it.

Thank you for reading!

答:
The problem is this:

```<code>for( k = 0; k<arr[position]-1; k++)
</code>```

If the arr[position] is less than 2 than nothing will happen. Try this

```<code>        .
        .
        .
        l=10;
        int end = arr[position] < 0 ? -arr[position] : arr[position]; // added code

        for( k = 0; k < end - 1; k++) { // changed code
            if(arr[position]==0) {
                mat[10][j] = '*';    // if the height is zero, put an asterisk
            }
        .
        .
        .
</code>```

Output

```<code>               *
               |
         *     |
         |     |
   *     |     |
*  |     |     |
---------------------
      |     |     |
      |     |     |
      *     |     |
            |     |
            *     |
                  |
                  *
</code>```

Basically taking the absolute value of arr[position] and using that as an end condition.

EDIT:
To make astrix appear when the arr[position] is 0. Do the following:

```<code>        .
        .
        .
        int end = arr[position] < 0 ? -arr[position] : arr[position];

        if(arr[position]==0) {
            mat[10][j] = '*';    // if the height is zero, put an asterisk
        }
        for( k = 0; k < end - 1; k++) {
        .
        .
        .
</code>```

So moving out the if from the for loop since if arr[position] is 0 than the loop does not execute.

Body:
Hello everyone and thanks for taking your time to read this. I am doing an exercise where I'm given an array of integers and each integer represents the "height" of one bar in the chart. Negative values mean that the bar extends below the horizontal axis. So, if I am given an array of 4 integers, there would exactly be 4 bars in the chart.

I used a 2D array of characters to try to complete this exercise.

note: the text of the exercise says that there should be two spaces between each bar in the graph, so that's why I increment the j control variable by three in each pass.

I am having problems with the negative values. No matter what I do, the negative values won't print out on the screen.

What I have tried is the following: I determined the width of the graph by multiplying the array size by three. I then set all fields of the 2D array to spaces except for the horizontal line in the middle.

The outer, j loop iterates through the columns of the matrix. I have only one loop for this because, in every pass through the j loop we start in the 10th row.

the k loop actually does the plotting. The loop goes from zero to number-1, leaving a space for the asterisk at the top (or bottom).

I have two if statements checking if the number is <0 or >0, because in those two instances the bar is supposed to show up differently.

Here is my code:

#include <stdio.h>

int main()
{

    char mat[30][40];
    int i,j, size=0, m=20, n=40;

    int arr[7] = {1,2,-3,4,-5,6,-7};
    size=7;

    n=size*3; // n is the width of the graph

    for(i=0; i<m; i++) {          // I set all fields of the 2D array to spaces
        for(j=0; j<n; j++) {      // except for the horizontal line
            if(i==10) mat[i][j]='-';
            else mat[i][j]=' ';
        }
    }
    int k;
    int position=0; // position is the variable I use to iterate through the array
    int l;

    for(j=0; j<n; j+=3) {
        l=10;

        for( k = 0; k<arr[position]-1; k++) {
            if(arr[position]==0) {
                mat[10][j] = '*';    // if the height is zero, put an asterisk
            }

            else if((arr[position])<0) {

                l++;                    // if the number is negative,
                mat[l][j]='|';          // the bar extends below the horizontal line
            }

            else if(arr[position]>0) {

                l--;              // if the number is positive, the bar extends above the
                mat[l][j] = '|';  // horizontal line
            }

        }

        if(arr[position]>0) mat[l-1][j]='*';  //every bar ends with an asterisk
        else if(arr[position]<0) {
            mat[l+1][j]='*';
        }

        position++;  // jump to the next element in array

    }

    for(i=0; i<m; i++) {
        for(j=0; j<n; j++) {
            printf("%c",mat[i][j]);
        }
        printf("\n");
    }

    return 0;
}

For negative numbers it just does not work. Furthermore I have made some tests and the condition else if((arr[position])<0)
is never fulfilled and I don't know why. What it does is it puts an asterisk below the horizontal line but that's about it.

Thank you for reading!

Body:
The problem is this:

for( k = 0; k<arr[position]-1; k++)

If the arr[position] is less than 2 than nothing will happen. Try this

        .
        .
        .
        l=10;
        int end = arr[position] < 0 ? -arr[position] : arr[position]; // added code

        for( k = 0; k < end - 1; k++) { // changed code
            if(arr[position]==0) {
                mat[10][j] = '*';    // if the height is zero, put an asterisk
            }
        .
        .
        .

Output

               *
               |
         *     |
         |     |
   *     |     |
*  |     |     |
---------------------
      |     |     |
      |     |     |
      *     |     |
            |     |
            *     |
                  |
                  *

Basically taking the absolute value of arr[position] and using that as an end condition.

EDIT:
To make astrix appear when the arr[position] is 0. Do the following:

        .
        .
        .
        int end = arr[position] < 0 ? -arr[position] : arr[position];

        if(arr[position]==0) {
            mat[10][j] = '*';    // if the height is zero, put an asterisk
        }
        for( k = 0; k < end - 1; k++) {
        .
        .
        .

So moving out the if from the for loop since if arr[position] is 0 than the loop does not execute.


问:
Prompt asking for password then redirecting
I'm very new to PHP and JavaScript and I'm stuck. I spent a good 7 hours so far trying to figure this one out but I just do not know what or how to do it. So in my application, when you try to add a new row to my table, I have a html form to get the data. When you enter the data into the form, and press submit, it prompts for a password, and if the correct password is put in, it submits the form. It work just as I wanted it, here is what I have:

```<code><button onclick="password()" type="button">Create New Hero</button>
    <div>
        <a id="discl">*-Required Fields</a>
    </div>
    <script>
        function password(){
            var password = prompt("Please Enter the Admin Password");
            if(password != "shaun"){
                alert("Wrong Password");
            }
            else{
                if(validation()){
                document.getElementById("form_id").submit();
                }
                else{
                    alert("One or more required fields were left empty, or tried to use <script>");
                }
            }
        }
        function validation(){
            var f = document.getElementById("f_name").value;
            var l = document.getElementById("l_name").value;
            var d = document.getElementById("dob").value;
            var a = document.getElementById("alias").value;
            if(f == "" || l == "" || d == "" || f.includes("<script>") || l.includes("<script>") || a.includes("<script>")){
                return false;
            }
            else{
                return true;
            }
        }
    </script>
</code>```

Now I also have an edit and delete on my table. My problem is that with edit and delete, they are in  tags with an href, and they are not buttons. This is how they originally looked when it worked without asking for a password:

```<code>               echo "<a href='./edit.php?id={$row['id']}'>edit</a>";
</code>```

So based on which row of the table it was, where you clicked edit or delete, based on the row's id from the database, it would edit or delete that table. Now my problem is I don't know how to properly set up the function so it asks for the password and redirect to the right url. This is what I have right now:

```<code>           foreach($results as $row){
            echo "<tr>";
            echo "<td>{$row['first_name']}</td>";
            echo "<td>{$row['last_name']}</td>";
            echo "<td>{$row['date_of_birth']}</td>";
            echo "<td>{$row['alias']}</td>";
            echo "<td>{$row['active']}</td>";
            echo "<td>{$row['hero']}</td>";
            echo "<td>";
            echo "<a href='./edit.php?id={$row['id']}'>edit</a>";
            echo " | ";
            echo "<a  href='javascript: password()'>delete</a>";
            echo "</td>";
            echo "</tr>";
        }
        ?>
        <script type="text/javascript">
        function password(){
            var password = prompt("Please Enter the Admin Password");
            if(password != "shaun"){
                alert("Wrong Password");
            }
            else{
                window.location.replace("./delete.php?id=<?php echo $row['id']; ?>");
            }
        }
    </script>
</code>```

The problem with this is that no matter which delete I click on on my table, it always deletes the last one, because the ID it's getting out after the url is the last available ID from my database. I'm not sure if I'm just missing something small, or I'm completely on the wrong path but any help would be appreciated because I'm very lost. Thank you

答:
Ignoring the blatant security issue, I suggest this

```<code><a href='#' class='edit'   data-id='<?= $row['id'] ?>'>edit</a> |
<a href='#' class='delete' data-id='<?= $row['id'] ?>'>delete</a>
</code>```

using

```<code>window.addEventListerner('load',function() {
  document.querySelector('table').addEventListerner('click',function(e) {
    e.preventdefault(); // stop the link
    const tgt = e.target, id = tgt.getAttribute("id");
    if (tgt.classList.contains("edit") {
      location = '/edit.php?id='+encodeURIComponent(id);
    }
    else if (tgt.classList.contains("delete") {
      let password = prompt("Please Enter the Admin Password");
      if (password === "shaun") {
        location.replace('/delete.php?id='+encodeURIComponent(id)=;
      }
      else {
        alert("Wrong Password");
      }
    }
  })
})
</code>```

Body:
I'm very new to PHP and JavaScript and I'm stuck. I spent a good 7 hours so far trying to figure this one out but I just do not know what or how to do it. So in my application, when you try to add a new row to my table, I have a html form to get the data. When you enter the data into the form, and press submit, it prompts for a password, and if the correct password is put in, it submits the form. It work just as I wanted it, here is what I have:

<button onclick="password()" type="button">Create New Hero</button>

        *-Required Fields

Now I also have an edit and delete on my table. My problem is that with edit and delete, they are in  tags with an href, and they are not buttons. This is how they originally looked when it worked without asking for a password:

               echo "edit";

So based on which row of the table it was, where you clicked edit or delete, based on the row's id from the database, it would edit or delete that table. Now my problem is I don't know how to properly set up the function so it asks for the password and redirect to the right url. This is what I have right now:

           foreach($results as $row){
            echo "
";
            echo "{$row['first_name']}	";
            echo "{$row['last_name']}	";
            echo "{$row['date_of_birth']}	";
            echo "{$row['alias']}	";
            echo "{$row['active']}	";
            echo "{$row['hero']}	";
            echo "";
            echo "edit";
            echo " | ";
            echo "delete";
            echo "	";
            echo "
";
        }
        ?>

The problem with this is that no matter which delete I click on on my table, it always deletes the last one, because the ID it's getting out after the url is the last available ID from my database. I'm not sure if I'm just missing something small, or I'm completely on the wrong path but any help would be appreciated because I'm very lost. Thank you

Body:
Ignoring the blatant security issue, I suggest this

<a href='#' class='edit'   data-id='<?= $row['id'] ?>'>edit</a> |
<a href='#' class='delete' data-id='<?= $row['id'] ?>'>delete</a>

using

window.addEventListerner('load',function() {
  document.querySelector('table').addEventListerner('click',function(e) {
    e.preventdefault(); // stop the link
    const tgt = e.target, id = tgt.getAttribute("id");
    if (tgt.classList.contains("edit") {
      location = '/edit.php?id='+encodeURIComponent(id);
    }
    else if (tgt.classList.contains("delete") {
      let password = prompt("Please Enter the Admin Password");
      if (password === "shaun") {
        location.replace('/delete.php?id='+encodeURIComponent(id)=;
      }
      else {
        alert("Wrong Password");
      }
    }
  })
})


问:
Get instance of subtype of a model with Eloquent
I have an Animal model, based on the animal table.

This table contains a type field, that can contain values such as cat or dog.

I would like to be able to create objects such as :

```<code>class Animal extends Model { }
class Dog extends Animal { }
class Cat extends Animal { }
</code>```

Yet, being able to fetch an animal like this :

```<code>$animal = Animal::find($id);
</code>```

But where $animal would be an instance of Dog or Cat depending on the type field, that I can check using instance of or that will work with type hinted methods. The reason is that 90% of the code is shared, but one can bark, and the other can meow.

I know that I can do Dog::find($id), but it's not what I want : I can determine the type of the object only once it was fetched. I could also fetch the Animal, and then run find() on the right object, but this is doing two database calls, which I obviously don't want.

I tried to look for a way to "manually" instantiate an Eloquent model like Dog from Animal, but I could not find any method corresponding. Any idea or method I missed please ?

答:
If you really want to do this, you could use the following approach inside your Animal model.</p>

```<code><?php

namespace App;

use Illuminate\Database\Eloquent\Model;

class Animal extends Model
{

    // other code in animal model ....

    public static function __callStatic($method, $parameters)
    {
        if ($method == 'find') {
            $model = parent::find($parameters[0]);

            if ($model) {
                switch ($model->type) {
                    case 'dog':
                        return new \App\Dog($model->attributes);
                    case 'cat':
                        return new \App\Cat($model->attributes);
                }
                return $model;
            }
        }

        return parent::__callStatic($method, $parameters);
    }
}
</code>```

Body:
I have an Animal model, based on the animal table.

This table contains a type field, that can contain values such as cat or dog.

I would like to be able to create objects such as :

class Animal extends Model { }
class Dog extends Animal { }
class Cat extends Animal { }

Yet, being able to fetch an animal like this :

$animal = Animal::find($id);

But where $animal would be an instance of Dog or Cat depending on the type field, that I can check using instance of or that will work with type hinted methods. The reason is that 90% of the code is shared, but one can bark, and the other can meow.

I know that I can do Dog::find($id), but it's not what I want : I can determine the type of the object only once it was fetched. I could also fetch the Animal, and then run find() on the right object, but this is doing two database calls, which I obviously don't want.

I tried to look for a way to "manually" instantiate an Eloquent model like Dog from Animal, but I could not find any method corresponding. Any idea or method I missed please ?

Body:
If you really want to do this, you could use the following approach inside your Animal model.

<?php

namespace App;

use Illuminate\Database\Eloquent\Model;

class Animal extends Model
{

    // other code in animal model ....

    public static function __callStatic($method, $parameters)
    {
        if ($method == 'find') {
            $model = parent::find($parameters[0]);

            if ($model) {
                switch ($model->type) {
                    case 'dog':
                        return new \App\Dog($model->attributes);
                    case 'cat':
                        return new \App\Cat($model->attributes);
                }
                return $model;
            }
        }

        return parent::__callStatic($method, $parameters);
    }
}


问:
Randomly select number (without repetition) for each group in R
I have the following dataframe containing a variable "group" and a variable "number of elements per group"

```<code>group    elements
1        3
2        1
3        14
4        10
..       ..
..       ..
30       5
</code>```

then I have a bunch of numbers going from 1 to (let's say) 30

when summing "elements" I would get 900. what I want to obtain is to randomly select a number (from 0 to 30) from 1-30 and assign it to each group until I fill the number of elements for that group. Each of those should appear 30 times in total.

thus, for group 1, I want to randomly select 3 number from 0 to 30
for group 2, 1 number from 0 to 30 etc. until I filled all of the groups.

the final table should look like this:

```<code>group     number(randomly selected)
1           7
1           20
1           7
2           4
3           21
3           20
...
</code>```

any suggestions on how I can achieve this?

答:
I solved as follow:

```<code>random_sample <- rep(1:30, each=30)
random_sample <- sample(random_sample)
</code>```

then I create a df with this variable and a variable containing one group per row repeated by the number of elements in the group itself

Body:
I have the following dataframe containing a variable "group" and a variable "number of elements per group"

group    elements
1        3
2        1
3        14
4        10
..       ..
..       ..
30       5

then I have a bunch of numbers going from 1 to (let's say) 30

when summing "elements" I would get 900. what I want to obtain is to randomly select a number (from 0 to 30) from 1-30 and assign it to each group until I fill the number of elements for that group. Each of those should appear 30 times in total.

thus, for group 1, I want to randomly select 3 number from 0 to 30
for group 2, 1 number from 0 to 30 etc. until I filled all of the groups.

the final table should look like this:

group     number(randomly selected)
1           7
1           20
1           7
2           4
3           21
3           20
...

any suggestions on how I can achieve this?

Body:
I solved as follow:

random_sample <- rep(1:30, each=30)
random_sample <- sample(random_sample)

then I create a df with this variable and a variable containing one group per row repeated by the number of elements in the group itself


问:
CSS files are not working in server using yii2
I integrated the CSS and JS file in the asset file. On localhost it's working but when I uploaded my project files in cPanel, the UI is breaking.
I can't understand where I'm making the mistake, please help me fix these issues.

Inside the backend folder, I uploaded my AdminLTE-2 CSS and JS files in the web folder. In the asset layout file, I gave the path.

backend/assets/loginAsset.php

```<code>namespace backend\assets;

use yii\web\AssetBundle;

/**
 * Main backend application asset bundle.
 */
class loginAsset extends AssetBundle
{
    public $basePath = '@webroot';
    public $baseUrl = '@web';
    public $css = [
        'bower_components/bootstrap/dist/css/bootstrap.min.css',
        'bower_components/font-awesome/css/font-awesome.min.css',
        'bower_components/Ionicons/css/ionicons.min.css',
        'css/AdminLTE.min.css',
        'plugins/iCheck/square/blue.css',
        '//fonts.googleapis.com/css?family=Source+Sans+Pro:300,400,600,700,300italic,400italic,600italic',
        //'css/site.css',
    ];

    public $js = [
        '//oss.maxcdn.com/html5shiv/3.7.3/html5shiv.min.js',
        '//oss.maxcdn.com/respond/1.4.2/respond.min.js',
        'bower_components/jquery/dist/jquery.min.js',
        'bower_components/bootstrap/dist/js/bootstrap.min.js',
        'plugins/iCheck/icheck.min.js',
    ];
    public $depends = [
        //'yii\web\YiiAsset',
        //'yii\bootstrap\BootstrapAsset',
    ];
}
</code>```

答:
Depending on your code, the issue is usually one of these scenarios:

File doesn't exist in Asset_Management/backend/web/css/AdminLTE.min.css

File does not have a truth permission.

Maybe you need to add a truth server configuration to handling Asset_Management since by default it must be backend/web/css/AdminLTE.min.css nested of Asset_Management/backend/web/css/AdminLTE.min.css

File Name is wrong, spelling mistake.

Body:
I integrated the CSS and JS file in the asset file. On localhost it's working but when I uploaded my project files in cPanel, the UI is breaking.
I can't understand where I'm making the mistake, please help me fix these issues.

Inside the backend folder, I uploaded my AdminLTE-2 CSS and JS files in the web folder. In the asset layout file, I gave the path.

backend/assets/loginAsset.php

namespace backend\assets;

use yii\web\AssetBundle;

/**
 * Main backend application asset bundle.
 */
class loginAsset extends AssetBundle
{
    public $basePath = '@webroot';
    public $baseUrl = '@web';
    public $css = [
        'bower_components/bootstrap/dist/css/bootstrap.min.css',
        'bower_components/font-awesome/css/font-awesome.min.css',
        'bower_components/Ionicons/css/ionicons.min.css',
        'css/AdminLTE.min.css',
        'plugins/iCheck/square/blue.css',
        '//fonts.googleapis.com/css?family=Source+Sans+Pro:300,400,600,700,300italic,400italic,600italic',
        //'css/site.css',
    ];

    public $js = [
        '//oss.maxcdn.com/html5shiv/3.7.3/html5shiv.min.js',
        '//oss.maxcdn.com/respond/1.4.2/respond.min.js',
        'bower_components/jquery/dist/jquery.min.js',
        'bower_components/bootstrap/dist/js/bootstrap.min.js',
        'plugins/iCheck/icheck.min.js',
    ];
    public $depends = [
        //'yii\web\YiiAsset',
        //'yii\bootstrap\BootstrapAsset',
    ];
}


问:
How to generate a signature based on an XML file?
please help me to solve the following:
I have a code on Java
java code bellow:

```<code>StringBuilder fullText;
KeyStore p12 = KeyStore.getInstance("PKCS12");
p12.load(new FileInputStream("FileName.p12"), "1234".toCharArray());

Key key = (Key) p12.getKey("1", "1234".toCharArray());

//signing
Signature signer = Signature.getInstance("SHA1withRSA");

signer.initSign((PrivateKey) key);
signer.update(fullText.toString().getBytes());
b`yte[] digitalSignature = signer.sign();

String base64sign = new String(Base64.getEncoder().encode(digitalSignature));
</code>```

I tried to reproduce it on .Net platform.
I create a code on .NET 3.5 platform. The code on X++ below:

```<code>public static boolean Encrypt(str sXmlDoc)
{
    boolean bSuccess = false;

    System.Security.Cryptography.X509Certificates.X509Certificate2 p12;
    System.Security.Cryptography.AsymmetricAlgorithm key;

    str sBase64Cert;
    str sBase64Xml;
    str sBase64Sign;

    str sTmp;

    System.Byte[] byteArray;
    System.Security.Cryptography.Xml.Signature signer;
    System.Exception  ex;
    str sKeyPublic;
    System.Byte[] keyPublic;
    System.Int32 myInt32;
    int myInt;
    System.Byte[] byteTmp, byteTmp2;
    System.Text.ASCIIEncoding txtEncoder;
    System.Security.Cryptography.Xml.KeyInfo keyInfo;
    System.Security.Cryptography.Xml.SignedXml signedXml;
    System.Xml.XmlDocument xmlDocument;
    System.Xml.XmlElement xmlElement;
    System.Security.Cryptography.Xml.SignedInfo signedInfo;
    System.Security.Cryptography.Xml.Reference reference;
    System.Security.Cryptography.Xml.XmlDsigEnvelopedSignatureTransform env;

    System.Security.Cryptography.Xml.RSAKeyValue rsaKeyValue;
    System.Security.Cryptography.RSA rsaKey;

    try
    {

        p12 = new System.Security.Cryptography.X509Certificates.X509Certificate2("fileName.p12", "pass");
        if (p12)
        {
            //Signature

            //TEST
            if (p12.get_HasPrivateKey())
            {
                key = p12.get_PrivateKey();
                rsaKey = p12.get_PrivateKey();

                xmlDocument = new System.Xml.XmlDocument();
                xmlDocument.set_PreserveWhitespace(true); //Allow white spaces
                xmlDocument.LoadXml(sXmlDoc);
                signedXml = new System.Security.Cryptography.Xml.SignedXml(xmlDocument);
                signedXml.set_SigningKey(key);
                keyInfo = new System.Security.Cryptography.Xml.KeyInfo();
                rsaKeyValue = new System.Security.Cryptography.Xml.RSAKeyValue(rsaKey);
                keyInfo.AddClause(rsaKeyValue);
                signedXml.set_KeyInfo(keyInfo);
                // Create a reference to be signed.
                //System.Security.Cryptography.Xml.Reference reference;
                reference = new System.Security.Cryptography.Xml.Reference();
                reference.set_Uri("");
                // Add an enveloped transformation to the reference.
                env = new System.Security.Cryptography.Xml.XmlDsigEnvelopedSignatureTransform();
                reference.AddTransform(env);
                // Add the reference to the SignedXml object.
                signedXml.AddReference(reference);
                signedXml.set_KeyInfo(keyInfo);
                signedXml.ComputeSignature();
                xmlElement = signedXml.GetXml();
                signer = new System.Security.Cryptography.Xml.Signature();
                signer = signedXml.get_Signature();
                signedInfo = new System.Security.Cryptography.Xml.SignedInfo();
                signedInfo = signer.get_SignedInfo();
                byteTmp = signer.get_SignatureValue();
                sTmp = System.Convert::ToBase64String(byteTmp);
                sBase64Sign = "<signature>"+sTmp+"</signature>";
                info(sBase64Sign);
            }
        }

    }
    catch (Exception::CLRError)
    {
        ex = ClrInterop::getLastException();
        if (ex != null)
        {
           ex = ex.get_InnerException();
           if (ex != null)
           {
               error(ex.ToString());
           }
        }
    }

    return bSuccess;
}
</code>```

But the result differs than I got on java. I opened a p12 key. I signed an XML sting and got the signature for this XML, but got the wrong string. What did I do wrong?

答:
The best way to sign an XML on .NET is by using a Bouncy Castle library. I hope anybody in one day will solve it on .NET framework, without using an external library, but the solution has found via using BounsyCastle.
This code on C# used BouncyCastle.</p>

```<code>string item = string.Empty;

Pkcs12Store p12 = new Pkcs12Store();
p12.Load(_p12, _p12_psw.ToCharArray());

string alias = "";
foreach (string al in p12.Aliases)
{
    if (p12.IsKeyEntry(al) && p12.GetKey(al).Key.IsPrivate)
    {
        alias = al;
        break;
    }
}

//signature
var data = Encoding.UTF8.GetBytes(xmlDoc);
ISigner signer = SignerUtilities.GetSigner("SHA1withRSA");
signer.Init(true,p12.GetKey(alias).Key);
signer.BlockUpdate(data, 0, data.Length);

var sign = signer.GenerateSignature();

string base64Sign = Convert.ToBase64String(sign);
item = "<signature>"+base64Sign+"</signature>", base64Sign);
</code>```

Body:
please help me to solve the following:
I have a code on Java
java code bellow:

StringBuilder fullText;
KeyStore p12 = KeyStore.getInstance("PKCS12");
p12.load(new FileInputStream("FileName.p12"), "1234".toCharArray());

Key key = (Key) p12.getKey("1", "1234".toCharArray());

//signing
Signature signer = Signature.getInstance("SHA1withRSA");

signer.initSign((PrivateKey) key);
signer.update(fullText.toString().getBytes());
b`yte[] digitalSignature = signer.sign();

String base64sign = new String(Base64.getEncoder().encode(digitalSignature));

I tried to reproduce it on .Net platform.
I create a code on .NET 3.5 platform. The code on X++ below:

public static boolean Encrypt(str sXmlDoc)
{
    boolean bSuccess = false;

    System.Security.Cryptography.X509Certificates.X509Certificate2 p12;
    System.Security.Cryptography.AsymmetricAlgorithm key;

    str sBase64Cert;
    str sBase64Xml;
    str sBase64Sign;

    str sTmp;

    System.Byte[] byteArray;
    System.Security.Cryptography.Xml.Signature signer;
    System.Exception  ex;
    str sKeyPublic;
    System.Byte[] keyPublic;
    System.Int32 myInt32;
    int myInt;
    System.Byte[] byteTmp, byteTmp2;
    System.Text.ASCIIEncoding txtEncoder;
    System.Security.Cryptography.Xml.KeyInfo keyInfo;
    System.Security.Cryptography.Xml.SignedXml signedXml;
    System.Xml.XmlDocument xmlDocument;
    System.Xml.XmlElement xmlElement;
    System.Security.Cryptography.Xml.SignedInfo signedInfo;
    System.Security.Cryptography.Xml.Reference reference;
    System.Security.Cryptography.Xml.XmlDsigEnvelopedSignatureTransform env;

    System.Security.Cryptography.Xml.RSAKeyValue rsaKeyValue;
    System.Security.Cryptography.RSA rsaKey;

    try
    {

        p12 = new System.Security.Cryptography.X509Certificates.X509Certificate2("fileName.p12", "pass");
        if (p12)
        {
            //Signature

            //TEST
            if (p12.get_HasPrivateKey())
            {
                key = p12.get_PrivateKey();
                rsaKey = p12.get_PrivateKey();

                xmlDocument = new System.Xml.XmlDocument();
                xmlDocument.set_PreserveWhitespace(true); //Allow white spaces
                xmlDocument.LoadXml(sXmlDoc);
                signedXml = new System.Security.Cryptography.Xml.SignedXml(xmlDocument);
                signedXml.set_SigningKey(key);
                keyInfo = new System.Security.Cryptography.Xml.KeyInfo();
                rsaKeyValue = new System.Security.Cryptography.Xml.RSAKeyValue(rsaKey);
                keyInfo.AddClause(rsaKeyValue);
                signedXml.set_KeyInfo(keyInfo);
                // Create a reference to be signed.
                //System.Security.Cryptography.Xml.Reference reference;
                reference = new System.Security.Cryptography.Xml.Reference();
                reference.set_Uri("");
                // Add an enveloped transformation to the reference.
                env = new System.Security.Cryptography.Xml.XmlDsigEnvelopedSignatureTransform();
                reference.AddTransform(env);
                // Add the reference to the SignedXml object.
                signedXml.AddReference(reference);
                signedXml.set_KeyInfo(keyInfo);
                signedXml.ComputeSignature();
                xmlElement = signedXml.GetXml();
                signer = new System.Security.Cryptography.Xml.Signature();
                signer = signedXml.get_Signature();
                signedInfo = new System.Security.Cryptography.Xml.SignedInfo();
                signedInfo = signer.get_SignedInfo();
                byteTmp = signer.get_SignatureValue();
                sTmp = System.Convert::ToBase64String(byteTmp);
                sBase64Sign = "<signature>"+sTmp+"</signature>";
                info(sBase64Sign);
            }
        }

    }
    catch (Exception::CLRError)
    {
        ex = ClrInterop::getLastException();
        if (ex != null)
        {
           ex = ex.get_InnerException();
           if (ex != null)
           {
               error(ex.ToString());
           }
        }
    }

    return bSuccess;
}

But the result differs than I got on java. I opened a p12 key. I signed an XML sting and got the signature for this XML, but got the wrong string. What did I do wrong?

Body:
The best way to sign an XML on .NET is by using a Bouncy Castle library. I hope anybody in one day will solve it on .NET framework, without using an external library, but the solution has found via using BounsyCastle.
This code on C# used BouncyCastle.

string item = string.Empty;

Pkcs12Store p12 = new Pkcs12Store();
p12.Load(_p12, _p12_psw.ToCharArray());

string alias = "";
foreach (string al in p12.Aliases)
{
    if (p12.IsKeyEntry(al) && p12.GetKey(al).Key.IsPrivate)
    {
        alias = al;
        break;
    }
}

//signature
var data = Encoding.UTF8.GetBytes(xmlDoc);
ISigner signer = SignerUtilities.GetSigner("SHA1withRSA");
signer.Init(true,p12.GetKey(alias).Key);
signer.BlockUpdate(data, 0, data.Length);

var sign = signer.GenerateSignature();

string base64Sign = Convert.ToBase64String(sign);
item = "<signature>"+base64Sign+"</signature>", base64Sign);


问:
Spark dataFrame for-if loop taking a Long time
I have a Spark DF (df):

I have to convert below into something like this:

Basically it should detect a new sentence whenever it finds a full stop (".") and another row.

I have written a code for above:

```<code>val spark = SparkSession.builder.appName("elasticSpark").master("local[*]").config("spark.scheduler.mode", "FAIR").getOrCreate()
val count = df.count.toInt
var emptyDF = Seq.empty[(Int, Int, String)].toDF("start_time", "end_time", "Sentences")
var b = 0
for (a <- 1 to count){
if(d9.select("words").head(a)(a-1).toSeq.head == "." || a == (count-1))
{
val myList1 = d9.select("words").head(a).toArray.map(_.getString(0))
val myList = d9.select("words").head(a).toArray.map(_.getString(0)).splitAt(b)._2
val text = myList.mkString(" ")
val end_time = d9.select("end_time").head(a)(a-1).toSeq.head.toString.toInt
val start_time = d9.select("start_time").head(a)(b).toSeq.head.toString.toInt
val df1 = spark.sparkContext.parallelize(Seq(start_time)).toDF("start_time")
val df2 = spark.sparkContext.parallelize(Seq(end_time)).toDF("end_time")
val df3 = spark.sparkContext.parallelize(Seq(text)).toDF("Sentences")
val df4 = df1.crossJoin(df2).crossJoin(df3)
emptyDF = emptyDF.union(df4).toDF
b = a
}
}
</code>```

Though its giving the correct output but its taking ages to complete iteration and I have 117 other df's which I need to run.

Any other way to Tune this code or any other way to achieve above operation? Any help will be deeply appreciated.

答:
Here is my approach using udf without window function.</p>

```<code>val df=Seq((123,245,"Hi"),(123,245,"."),(123,245,"Hi"),(123,246,"I"),(123,245,".")).toDF("start","end","words")

  var count=0
  var flag=false
  val counterUdf=udf((dot:String) => {
    if(flag) {
      count+=1
    flag=false
    }
    if (dot == ".")
      flag=true
    count
  })

  val df1=df.withColumn("counter",counterUdf(col("words")))

  val df2=df1.groupBy("counter").agg(min("start").alias("start"), max("end").alias("end"), concat_ws(" ", collect_list("words")).alias("sentence")).drop("counter")

  df2.show()

+-----+---+--------+
|start|end|sentence|
+-----+---+--------+
|  123|246|  Hi I .|
|  123|245|    Hi .|
+-----+---+--------+
</code>```

Body:
I have a Spark DF (df):

I have to convert below into something like this:

Basically it should detect a new sentence whenever it finds a full stop (".") and another row.

I have written a code for above:

val spark = SparkSession.builder.appName("elasticSpark").master("local[*]").config("spark.scheduler.mode", "FAIR").getOrCreate()
val count = df.count.toInt
var emptyDF = Seq.empty[(Int, Int, String)].toDF("start_time", "end_time", "Sentences")
var b = 0
for (a <- 1 to count){
if(d9.select("words").head(a)(a-1).toSeq.head == "." || a == (count-1))
{
val myList1 = d9.select("words").head(a).toArray.map(_.getString(0))
val myList = d9.select("words").head(a).toArray.map(_.getString(0)).splitAt(b)._2
val text = myList.mkString(" ")
val end_time = d9.select("end_time").head(a)(a-1).toSeq.head.toString.toInt
val start_time = d9.select("start_time").head(a)(b).toSeq.head.toString.toInt
val df1 = spark.sparkContext.parallelize(Seq(start_time)).toDF("start_time")
val df2 = spark.sparkContext.parallelize(Seq(end_time)).toDF("end_time")
val df3 = spark.sparkContext.parallelize(Seq(text)).toDF("Sentences")
val df4 = df1.crossJoin(df2).crossJoin(df3)
emptyDF = emptyDF.union(df4).toDF
b = a
}
}

Though its giving the correct output but its taking ages to complete iteration and I have 117 other df's which I need to run.

Any other way to Tune this code or any other way to achieve above operation? Any help will be deeply appreciated.

Body:
Here is my approach using udf without window function.

val df=Seq((123,245,"Hi"),(123,245,"."),(123,245,"Hi"),(123,246,"I"),(123,245,".")).toDF("start","end","words")

  var count=0
  var flag=false
  val counterUdf=udf((dot:String) => {
    if(flag) {
      count+=1
    flag=false
    }
    if (dot == ".")
      flag=true
    count
  })

  val df1=df.withColumn("counter",counterUdf(col("words")))

  val df2=df1.groupBy("counter").agg(min("start").alias("start"), max("end").alias("end"), concat_ws(" ", collect_list("words")).alias("sentence")).drop("counter")

  df2.show()

+-----+---+--------+
|start|end|sentence|
+-----+---+--------+
|  123|246|  Hi I .|
|  123|245|    Hi .|
+-----+---+--------+


问:
iOS - How To Remove Previously Added Sublayers Of a UIView
I have a custom view which is a subclass of UIView. I added some sublayers to the custom view but now I want remove them.

I tried doing this:

```<code>self.layer.sublayers = nil;
</code>```

But this will remove everything including the initial sublayers of the view.

Is there any way to achieve this? Or do I have to reinitialise a new custom view every time?

Note: App runs in iOS 7 and above.

Thanks!

答:
keeping reference is not cool, in some cases you can use

```<code>resultImageView.layer.sublayers?.filter{ $0 is CAShapeLayer }.forEach{ $0.removeFromSuperlayer() }
</code>```

or to be more generic by using CALayer, which removes everything

Body:
I have a custom view which is a subclass of UIView. I added some sublayers to the custom view but now I want remove them.

I tried doing this:

self.layer.sublayers = nil;

But this will remove everything including the initial sublayers of the view.

Is there any way to achieve this? Or do I have to reinitialise a new custom view every time?

Note: App runs in iOS 7 and above.

Thanks!

Body:
keeping reference is not cool, in some cases you can use

resultImageView.layer.sublayers?.filter{ $0 is CAShapeLayer }.forEach{ $0.removeFromSuperlayer() }

or to be more generic by using CALayer, which removes everything


问:
Parent-child relation between two objects causes JSON StackOverflowError
I am trying to achieve a parent-child relation between some objects and I ran into a bit of trouble.

In my case, I am trying to store objects within other objects (e.g. container stores multiple items or other containers with items). The tricky part is that every object in the storage should be able to tell what it's outermost parent object is. While this seems to work in my in-memory database (using h2 at the moment), trying to get a JSON representation of all my storage items gives this (I return a List<StorageUnit> ):

Could not write JSON: Infinite recursion (StackOverflowError); nested exception is com.fasterxml.jackson.databind.JsonMappingException: Infinite recursion (StackOverflowError) (through reference chain: java.util.ArrayList[0]->com.warehousing.storage.FixedContentsCase["contents"]->java.util.ArrayList[0]->com.warehousing.storage.FixedContentsCase["contents"]->...

Here are the classes:

StorageUnit

```<code>@Entity
@Inheritance
public abstract class StorageUnit {

   @Id
   @GeneratedValue(strategy=GenerationType.IDENTITY)
   private Long id;
   @ManyToOne
   private Location location;
   protected Long parentContainerId;
   // <getters & setters>
   public abstract List<StorageUnit> getContents();
}
</code>```

FixedContentCase

```<code>
@Entity
public class FixedContentsCase extends StorageUnit {
    @OneToMany
    private List<Item> items;

    public FixedContentsCase() {
        super();
        items = new ArrayList<>();
    }
    // <getters & setters>
    @Override
    public List<StorageUnit> getContents() {
        // Return the case itself and its contents
        List<StorageUnit> contents = new ArrayList<>(Arrays.asList(this));
        for (StorageUnit item : items)
            contents.addAll(item.getContents());
        return contents;
    }
}
</code>```

Item

```<code>@Entity
public class Item extends StorageUnit {

    private String description;

    public Item() {
        super();
        this.description = "";
    }
    // <getters & setters>
    @Override
    public List<StorageUnit> getContents() {
        return Arrays.asList(this);
    }
}
</code>```

I have tried to annotate the StorageUnit class with @JsonIgnoreProperties("parentContainerId") but it didn't work. Annotating parentContainerId with  @JsonIgnore didn't help either. I also tried annotating the getters instead of the attributes themselves (as per following). Is there a way to work around this or is some kind of design change necessary? Thanks!

答:
Using Jackson this is definitely possible by annotations like @JsonIgnore or the DTO approach BugsForBreakfast mentioned.

I created a jackson MixIn handler to allow dynamic filtering which i use to avoid the boilerplate of DTOs

https://github.com/Antibrumm/jackson-antpathfilter

The examples in the readme should show how it works and if it‘s a possible solution for you.

Body:
I am trying to achieve a parent-child relation between some objects and I ran into a bit of trouble.

In my case, I am trying to store objects within other objects (e.g. container stores multiple items or other containers with items). The tricky part is that every object in the storage should be able to tell what it's outermost parent object is. While this seems to work in my in-memory database (using h2 at the moment), trying to get a JSON representation of all my storage items gives this (I return a List<StorageUnit> ):

Could not write JSON: Infinite recursion (StackOverflowError); nested exception is com.fasterxml.jackson.databind.JsonMappingException: Infinite recursion (StackOverflowError) (through reference chain: java.util.ArrayList[0]->com.warehousing.storage.FixedContentsCase["contents"]->java.util.ArrayList[0]->com.warehousing.storage.FixedContentsCase["contents"]->...

Here are the classes:

StorageUnit

@Entity
@Inheritance
public abstract class StorageUnit {

   @Id
   @GeneratedValue(strategy=GenerationType.IDENTITY)
   private Long id;
   @ManyToOne
   private Location location;
   protected Long parentContainerId;
   // <getters & setters>
   public abstract List<StorageUnit> getContents();
}

FixedContentCase

@Entity
public class FixedContentsCase extends StorageUnit {
    @OneToMany
    private List<Item> items;

    public FixedContentsCase() {
        super();
        items = new ArrayList<>();
    }
    // <getters & setters>
    @Override
    public List<StorageUnit> getContents() {
        // Return the case itself and its contents
        List<StorageUnit> contents = new ArrayList<>(Arrays.asList(this));
        for (StorageUnit item : items)
            contents.addAll(item.getContents());
        return contents;
    }
}

Item

@Entity
public class Item extends StorageUnit {

    private String description;

    public Item() {
        super();
        this.description = "";
    }
    // <getters & setters>
    @Override
    public List<StorageUnit> getContents() {
        return Arrays.asList(this);
    }
}

I have tried to annotate the StorageUnit class with @JsonIgnoreProperties("parentContainerId") but it didn't work. Annotating parentContainerId with  @JsonIgnore didn't help either. I also tried annotating the getters instead of the attributes themselves (as per following). Is there a way to work around this or is some kind of design change necessary? Thanks!


问:
How to map Enum in NHibernate using Mapping by Code
I am getting following exception while accessing data form database using fluent NHibernate

An exception of type 'NHibernate.HibernateException' occurred in NHibernate.dll but was not handled in user code

Additional information: Can't Parse 1 as State

I have Enum type in my employee entity.

Employee

```<code>public class Employee
{
    public virtual Guid Id { get; set; }
    public virtual string Name { get; set; }
    public virtual DateTime DateOfBirth { get; set; }
    public virtual string ContactNumber  { get; set; }
    //[JsonConverter(typeof(StringEnumConverter))]
    public virtual State Status { set; get; }
    public virtual DateTime LastModify  { get; set; }
}
</code>```

EmployeeMapping

```<code>public class EmployeeMap : ClassMapping<Employee>
{
    public EmployeeMap()

    {
        Table("Employee");

        Id(i => i.Id, m => m.Generator(Generators.GuidComb));

        Property(p => p.Name, m =>
        {
            m.NotNullable(false);
            m.Length(120);
        });

        Property(p => p.DateOfBirth, m => m.NotNullable(true));

        Property(p => p.ContactNumber, m =>
        {
            m.NotNullable(false);
            m.Length(12);
        });

        Property(p => p.Status, m => m.Column(y =>
        {
            y.NotNullable(true);
            y.Default(0);
        }));

        Version(v => v.LastModify, m =>
        {
            m.Column(y =>
            {
                y.NotNullable(true);
                y.Default("CURRENT_TIMESTAMP");
            });
            m.Type(NHibernateUtil.Timestamp);
            m.Generated(VersionGeneration.Never);
        });
    }
}
</code>```

State Enum

```<code>public enum State
{
    Probationer ,
    Permanent,
    Contractor
}
</code>```

Please suggest me how to remove the exception.

答:
When I tried using NHibernate Mapping by Code using the approach from Alexey or this:

```<code>Property(x => x.Command, o =>
{
  o.Type<CommandType>();
});
</code>```

I got a mapping error along the lines of 'must implement IUserType. The correct way to map an enum is:

```<code>Property(x => x.Command, o =>
{
  o.Type<EnumType<CommandType>>();
});
</code>```

Body:
I am getting following exception while accessing data form database using fluent NHibernate

An exception of type 'NHibernate.HibernateException' occurred in NHibernate.dll but was not handled in user code

Additional information: Can't Parse 1 as State

I have Enum type in my employee entity.

Employee

public class Employee
{
    public virtual Guid Id { get; set; }
    public virtual string Name { get; set; }
    public virtual DateTime DateOfBirth { get; set; }
    public virtual string ContactNumber  { get; set; }
    //[JsonConverter(typeof(StringEnumConverter))]
    public virtual State Status { set; get; }
    public virtual DateTime LastModify  { get; set; }
}

EmployeeMapping

public class EmployeeMap : ClassMapping<Employee>
{
    public EmployeeMap()

    {
        Table("Employee");

        Id(i => i.Id, m => m.Generator(Generators.GuidComb));

        Property(p => p.Name, m =>
        {
            m.NotNullable(false);
            m.Length(120);
        });

        Property(p => p.DateOfBirth, m => m.NotNullable(true));

        Property(p => p.ContactNumber, m =>
        {
            m.NotNullable(false);
            m.Length(12);
        });

        Property(p => p.Status, m => m.Column(y =>
        {
            y.NotNullable(true);
            y.Default(0);
        }));

        Version(v => v.LastModify, m =>
        {
            m.Column(y =>
            {
                y.NotNullable(true);
                y.Default("CURRENT_TIMESTAMP");
            });
            m.Type(NHibernateUtil.Timestamp);
            m.Generated(VersionGeneration.Never);
        });
    }
}

State Enum

public enum State
{
    Probationer ,
    Permanent,
    Contractor
}

Please suggest me how to remove the exception.

Body:
When I tried using NHibernate Mapping by Code using the approach from Alexey or this:

Property(x => x.Command, o =>
{
  o.Type<CommandType>();
});

I got a mapping error along the lines of 'must implement IUserType. The correct way to map an enum is:

Property(x => x.Command, o =>
{
  o.Type<EnumType<CommandType>>();
});


问:
GRAPH: Generate sum of squares between 1 and 10 for polynomial graph
In an attempt to write a query in Python that will generate the first one hundred sums of squares between one and ten, the following attempt is made:

```<code>for a in range(1, 10):
    for b in range(1,10):
        print(a**2+b**2)
</code>```

Format should look like this:

```<code>1   1   4   9   16  25  36  49  64  81  100
4   5   8   13  20  29  40  53  68  85  104
9   10  13  18  25  34  45  58  73  90  109
16  17  20  25  32  41  52  65  80  97  116
25  26  38  34  41  50  61  74  89  106 125
36  37  40  45  52  61  72  85  100 117 136
49  75  53  58  65  74  85  98  113 130 149
64  65  68  73  80  89  100 113 128 145 164
81  82  85  90  97  106 117 130 145 162 181
100 101 104 109 116 125 136 149 164 181 200
</code>```

After reading that the sum of two squares in a polynomial will always be positive, it occurred to me that it would make a good dataset to have all the numbers that could be generated by the sum of two squares.   Polynomial like (a+b)*(a-b)...

Seems to me there should be an answer that creates a couple of matrices multiplied together.

So tried this but format is wrong (Thank UnsignedFoo for the help)

```<code>df=pd.Dataframe=([])
for a in range(1, 10):
    val_row = " ".join([str(a**2+b**2) for b in range(1,10)])
    print("{}\n".format("["+val_row+"]"))
    df.append("{}\n".format("["+val_row+"]"))
</code>```

It can be hard coded a line a time:

```<code>df1 = pd.DataFrame([[1, 2,3,4,5,6,7,8,9,10], [2,5,10,17,26,37,50,65,82,101]], columns=list('ABCDEFGHIJ'))
df2 = pd.DataFrame([[5,8,13,20,29,40,53,68,85,104], [10,13,18,25,34,45,58,73,90,109]], columns=list('ABCDEFGHIJ'))
df3 = pd.DataFrame([[17,20,25,32,41,52,65,80,97,116], [26,38,34,41,50,61,74,89,106,125]], columns=list('ABCDEFGHIJ'))
df4 = pd.DataFrame([[37,40,45,52,61,72,85,100,117,136], [75,53,58,65,74,85,98,113,130,149]], columns=list('ABCDEFGHIJ'))
df5 = pd.DataFrame([[65,68,73,80,89,100,113,128,145,164], [82,85,90,97,106,117,130,145,162,181]], columns=list('ABCDEFGHIJ'))
df6 = pd.DataFrame([[101,104,109,116,125,136,149,164,181,200], [126,125,130,137,146,157,170,185,202,221]], columns=list('ABCDEFGHIJ'))
df1.append(df2)
df1.append(df3)
df1.append(df4)
df1.append(df5)
df1.append(df6)
</code>```

And at that point can be graphed and it would be great if the matrice could be built with less work - up to this point, Excel does everything but the Excel doesn't have the advanced matplot libraries:

```<code>import matplotlib.pyplot as plt
from matplotlib import cm
from mpl_toolkits.mplot3d import Axes3D
%matplotlib inline
%config InlineBackend.figure_format='retina'
from mpl_toolkits import mplot3d
fig=plt.figure(figsize=(8,6))
xs=df1['A']
ys=df1['B']
zs=df1['C']
ax=fig.add_subplot(111,projection='3d')
ax.scatter(xs,ys,zs,s=50,alpha=0.6,edgecolors='w')
ax.set_xlabel('A')
ax.set_ylabel('B')
ax.set_zlabel('C')
plt.show()
</code>```

A better example that is closer to where this should go is:

```<code>X = np.arange(1, 10, 1)
Y = np.arange(1, 10, 1)
X, Y = np.meshgrid(X, Y)
R = (X**2 + Y**2)# R = np.sqrt(X**2 + Y**2)
Z = np.sin(R)

fig = plt.figure()
ax = Axes3D(fig)
ax.plot_surface(X, Y, Z, rstride=1, cstride=1, cmap=cm.viridis)

plt.show()
</code>```

Still hoping someone can answer this question.  I'd like to delete and start again: the "answers" don't address the issue of graphing.

答:
The syntax error with your code is, that after a for loop a : followed by a newline is required:

This results in:

```<code>for b in range(1, 10):
  for a in range(1,b):
    print(a**2+b**2)
</code>```

Please note this still does not print your table, as print always generates a newline in python.

Body:
In an attempt to write a query in Python that will generate the first one hundred sums of squares between one and ten, the following attempt is made:

for a in range(1, 10):
    for b in range(1,10):
        print(a**2+b**2)

Format should look like this:

1   1   4   9   16  25  36  49  64  81  100
4   5   8   13  20  29  40  53  68  85  104
9   10  13  18  25  34  45  58  73  90  109
16  17  20  25  32  41  52  65  80  97  116
25  26  38  34  41  50  61  74  89  106 125
36  37  40  45  52  61  72  85  100 117 136
49  75  53  58  65  74  85  98  113 130 149
64  65  68  73  80  89  100 113 128 145 164
81  82  85  90  97  106 117 130 145 162 181
100 101 104 109 116 125 136 149 164 181 200

After reading that the sum of two squares in a polynomial will always be positive, it occurred to me that it would make a good dataset to have all the numbers that could be generated by the sum of two squares.   Polynomial like (a+b)*(a-b)...

Seems to me there should be an answer that creates a couple of matrices multiplied together.

So tried this but format is wrong (Thank UnsignedFoo for the help)

df=pd.Dataframe=([])
for a in range(1, 10):
    val_row = " ".join([str(a**2+b**2) for b in range(1,10)])
    print("{}\n".format("["+val_row+"]"))
    df.append("{}\n".format("["+val_row+"]"))

It can be hard coded a line a time:

df1 = pd.DataFrame([[1, 2,3,4,5,6,7,8,9,10], [2,5,10,17,26,37,50,65,82,101]], columns=list('ABCDEFGHIJ'))
df2 = pd.DataFrame([[5,8,13,20,29,40,53,68,85,104], [10,13,18,25,34,45,58,73,90,109]], columns=list('ABCDEFGHIJ'))
df3 = pd.DataFrame([[17,20,25,32,41,52,65,80,97,116], [26,38,34,41,50,61,74,89,106,125]], columns=list('ABCDEFGHIJ'))
df4 = pd.DataFrame([[37,40,45,52,61,72,85,100,117,136], [75,53,58,65,74,85,98,113,130,149]], columns=list('ABCDEFGHIJ'))
df5 = pd.DataFrame([[65,68,73,80,89,100,113,128,145,164], [82,85,90,97,106,117,130,145,162,181]], columns=list('ABCDEFGHIJ'))
df6 = pd.DataFrame([[101,104,109,116,125,136,149,164,181,200], [126,125,130,137,146,157,170,185,202,221]], columns=list('ABCDEFGHIJ'))
df1.append(df2)
df1.append(df3)
df1.append(df4)
df1.append(df5)
df1.append(df6)

And at that point can be graphed and it would be great if the matrice could be built with less work - up to this point, Excel does everything but the Excel doesn't have the advanced matplot libraries:

import matplotlib.pyplot as plt
from matplotlib import cm
from mpl_toolkits.mplot3d import Axes3D
%matplotlib inline
%config InlineBackend.figure_format='retina'
from mpl_toolkits import mplot3d
fig=plt.figure(figsize=(8,6))
xs=df1['A']
ys=df1['B']
zs=df1['C']
ax=fig.add_subplot(111,projection='3d')
ax.scatter(xs,ys,zs,s=50,alpha=0.6,edgecolors='w')
ax.set_xlabel('A')
ax.set_ylabel('B')
ax.set_zlabel('C')
plt.show()

A better example that is closer to where this should go is:

X = np.arange(1, 10, 1)
Y = np.arange(1, 10, 1)
X, Y = np.meshgrid(X, Y)
R = (X**2 + Y**2)# R = np.sqrt(X**2 + Y**2)
Z = np.sin(R)

fig = plt.figure()
ax = Axes3D(fig)
ax.plot_surface(X, Y, Z, rstride=1, cstride=1, cmap=cm.viridis)

plt.show()

Still hoping someone can answer this question.  I'd like to delete and start again: the "answers" don't address the issue of graphing.

Body:
The syntax error with your code is, that after a for loop a : followed by a newline is required:

This results in:

for b in range(1, 10):
  for a in range(1,b):
    print(a**2+b**2)

Please note this still does not print your table, as print always generates a newline in python.


问:
Analysis services project lifecycle
Is there a standard via which one should start an analysis services project? Out situation is that we work locally on our machines, and the relational DB is out of our domain - and the server that analysis services DB will eventually sit on is out of our domain. So, I have a bunch of questions:

Where do you set up the Star schema DB (as the source of the OLAP project)? Is it on a separate server somewhere? And then how do you have a dev star schema db, vs your production star schema DB?

When you create a new Anaylsis Project on your visual studio, where should it connect to (dev star schema? prod star schema?)

Analysis services only supports windows authentication, so how do you get around this if your local computer and the dev analysis services is not on the same server?

When doing ETL work (on SSIS) which DB do you connect to? (dev, I assume) - but then how do you deploy to production?

What about down the line if you need to make changes - how does that process work?

I apologise for haphazard questions, but I'm not really sure where to start, so if anyone has a process from start to finish that is a standard, please let me know.. thanks!

答:
It sounds like your main problem is that you don't have direct access to the production environment/domain and you're not sure how to deploy your SSAS and SSIS work.

In both cases you'll want to develop against the development database, which is hopefully a copy of the production database.

In SSIS, you will create Connection Managers that use connection strings pointing to your development environment. Add a package configuration file to give access to package properties, like the connection string. There are other ways to manage configuration information, but a config file is the mos straightforward. When you build the project with the Create Deployment Utility option enabled, the config file and a .manifest file will be created. Together with your package(s), these files can be run on the target server to install and configure the project outside the development environment.

Similarly, SSAS has a deployment utility. There are several ways to get an SSAS project deployed to a production environment. See: Deploying an Analysis Services Database into the Production Environment for one overview of the options. Note that data sources in your project can be manually modified by an administrator by connecting to the Analysis Server database in SSMS after deployment.

Changes in SSIS are generally handled by deploying updated packages. With SSAS, changes can be scripted or the entire database can be redeployed. The approach I would take would depend on the size and complexity of the SSAS database and what is changing.

Title: Analysis services project lifecycle