问:
XMLHttpRequest cannot load https://www.facebook.com/dialog/oauth?response_type=code&redirect_uri=
I am trying to integrate facebook login for my app in nodejs, angularjs using passport-facebook module.

I can intergrate facebook authentication without angularjs, but when i use angular http.get('/auth/facebook')
i am getting below error

```<code>XMLHttpRequest cannot load https://www.facebook.com/dialog/oauth?response_type=code&redirect_uri=http%…%2Flocalhost%3A1439%2Fauth%2Ffacebook%2Fcallback&client_id=xxxxxxxx. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost:1439' is therefore not allowed access.
app.js:153 err
</code>```

Below is my angular code

```<code>var headers = {
                'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8',
                'Content-Type': 'text/html'
            };
    $scope.fblogin=function(){
        // $window.location.href='/auth/facebook';
        $http({
         url:'/auth/facebook',
        method:'GET',
       headers: headers
        }).success(function(data){
            console.log(data);
        }).error(function(){
            console.log('err');
        });
    };

pp.config(['$routeProvider','$httpProvider',
  function($routeProvider,$httpProvider) {
        $httpProvider.defaults.useXDomain = true;
        $httpProvider.defaults.headers.common = 'Content-Type: application/json';
        delete $httpProvider.defaults.headers.common['X-Requested-With'];
</code>```

NodeJs

```<code>app.use(function(req, res, next) {
  res.header("Access-Control-Allow-Origin", "*");
  res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept");
  next();
});
</code>```

**Note:**I have tried changing multiple header changes for $http.get()

答:
This is what I have done to avoid Angular to call facebook auth dialogue API as AJAX request.

Use 'window.location="http://localhost:3000/auth/facebook"'; in your Angular Controller Function from where you send the request to your Express Server which contains passport.authenticate stuff.

Example:

```<code>$scope.authFacebook = function() { window.location="http://localhost:3000/facebook" }
</code>```

Body:
I am trying to integrate facebook login for my app in nodejs, angularjs using passport-facebook module.

I can intergrate facebook authentication without angularjs, but when i use angular http.get('/auth/facebook')
i am getting below error

XMLHttpRequest cannot load https://www.facebook.com/dialog/oauth?response_type=code&redirect_uri=http%…%2Flocalhost%3A1439%2Fauth%2Ffacebook%2Fcallback&client_id=xxxxxxxx. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost:1439' is therefore not allowed access.
app.js:153 err

Below is my angular code

var headers = {
                'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8',
                'Content-Type': 'text/html'
            };
    $scope.fblogin=function(){
        // $window.location.href='/auth/facebook';
        $http({
         url:'/auth/facebook',
        method:'GET',
       headers: headers
        }).success(function(data){
            console.log(data);
        }).error(function(){
            console.log('err');
        });
    };

pp.config(['$routeProvider','$httpProvider',
  function($routeProvider,$httpProvider) {
        $httpProvider.defaults.useXDomain = true;
        $httpProvider.defaults.headers.common = 'Content-Type: application/json';
        delete $httpProvider.defaults.headers.common['X-Requested-With'];

NodeJs

app.use(function(req, res, next) {
  res.header("Access-Control-Allow-Origin", "*");
  res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept");
  next();
});

**Note:**I have tried changing multiple header changes for $http.get()

Body:
This is what I have done to avoid Angular to call facebook auth dialogue API as AJAX request.

Use 'window.location="http://localhost:3000/auth/facebook"'; in your Angular Controller Function from where you send the request to your Express Server which contains passport.authenticate stuff.

Example:

$scope.authFacebook = function() { window.location="http://localhost:3000/facebook" }


来源: stackexchange

问:
What is the meaning of 'mean_test_score' in cv_result?
Hello I'm doing a GridSearchCV and I'm printing the result with the .cv_results_ function from scikit learn.

My problem is that when I'm evaluating by hand the mean on all the test score splits I obtain a different number compared to what it is written in 'mean_test_score'. Which is different from the standard np.mean()?

I attach here the code with the result:

```<code>n_estimators = [100]
max_depth = [3]
learning_rate = [0.1]

param_grid = dict(max_depth=max_depth, n_estimators=n_estimators, learning_rate=learning_rate)

gkf = GroupKFold(n_splits=7)

grid_search = GridSearchCV(model, param_grid, scoring=score_auc, cv=gkf)
grid_result = grid_search.fit(X, Y, groups=patients)

grid_result.cv_results_
</code>```

The result of this operation is:

```<code>{'mean_fit_time': array([ 8.92773601]),
 'mean_score_time': array([ 0.04288721]),
 'mean_test_score': array([ 0.83490629]),
 'mean_train_score': array([ 0.95167036]),
 'param_learning_rate': masked_array(data = [0.1],
              mask = [False],
        fill_value = ?),
 'param_max_depth': masked_array(data = [3],
              mask = [False],
        fill_value = ?),
 'param_n_estimators': masked_array(data = [100],
              mask = [False],
        fill_value = ?),
 'params': ({'learning_rate': 0.1, 'max_depth': 3, 'n_estimators': 100},),
 'rank_test_score': array([1]),
 'split0_test_score': array([ 0.74821666]),
 'split0_train_score': array([ 0.97564995]),
 'split1_test_score': array([ 0.80089016]),
 'split1_train_score': array([ 0.95361201]),
 'split2_test_score': array([ 0.92876979]),
 'split2_train_score': array([ 0.93935856]),
 'split3_test_score': array([ 0.95540287]),
 'split3_train_score': array([ 0.94718634]),
 'split4_test_score': array([ 0.89083901]),
 'split4_train_score': array([ 0.94787374]),
 'split5_test_score': array([ 0.90926355]),
 'split5_train_score': array([ 0.94829775]),
 'split6_test_score': array([ 0.82520379]),
 'split6_train_score': array([ 0.94971417]),
 'std_fit_time': array([ 1.79167576]),
 'std_score_time': array([ 0.02970254]),
 'std_test_score': array([ 0.0809713]),
 'std_train_score': array([ 0.0105566])}
</code>```

As you can see, doing the np.mean of all the test_score it gives you a value approximately of 0.8655122606479532 while the 'mean_test_score' is 0.83490629

Thanks for you help,
Leonardo.

答:
I suppose the reason for the different means are different weighting factors in the mean calculation.

The mean_test_score that sklearn returns is the mean calculated on all samples where each sample has the same weight.

If you calculate the mean by taking the mean of the folds (splits), then you only get the same results if the folds are all of equal size. If they are not, then all samples of larger folds will automatically have a smaller impact on the mean of the folds than smaller folds, and the other way around.

Small numeric example:

```<code>mean([2,3,5,8,9]) = 5.4 # mean over all samples ('mean_test_score')

mean([2,3,5]) = 3.333 # mean of fold 1
mean([8,9]) = 8.5 # mean of fold 2

mean(3.333, 8.5) = 5.91 # mean of means of folds

5.4 != 5.91
</code>```

ContentLicense: CC BY-SA 3.0

Body:
Hello I'm doing a GridSearchCV and I'm printing the result with the .cv_results_ function from scikit learn.

My problem is that when I'm evaluating by hand the mean on all the test score splits I obtain a different number compared to what it is written in 'mean_test_score'. Which is different from the standard np.mean()?

I attach here the code with the result:

n_estimators = [100]
max_depth = [3]
learning_rate = [0.1]

param_grid = dict(max_depth=max_depth, n_estimators=n_estimators, learning_rate=learning_rate)

gkf = GroupKFold(n_splits=7)

grid_search = GridSearchCV(model, param_grid, scoring=score_auc, cv=gkf)
grid_result = grid_search.fit(X, Y, groups=patients)

grid_result.cv_results_

The result of this operation is:

{'mean_fit_time': array([ 8.92773601]),
 'mean_score_time': array([ 0.04288721]),
 'mean_test_score': array([ 0.83490629]),
 'mean_train_score': array([ 0.95167036]),
 'param_learning_rate': masked_array(data = [0.1],
              mask = [False],
        fill_value = ?),
 'param_max_depth': masked_array(data = [3],
              mask = [False],
        fill_value = ?),
 'param_n_estimators': masked_array(data = [100],
              mask = [False],
        fill_value = ?),
 'params': ({'learning_rate': 0.1, 'max_depth': 3, 'n_estimators': 100},),
 'rank_test_score': array([1]),
 'split0_test_score': array([ 0.74821666]),
 'split0_train_score': array([ 0.97564995]),
 'split1_test_score': array([ 0.80089016]),
 'split1_train_score': array([ 0.95361201]),
 'split2_test_score': array([ 0.92876979]),
 'split2_train_score': array([ 0.93935856]),
 'split3_test_score': array([ 0.95540287]),
 'split3_train_score': array([ 0.94718634]),
 'split4_test_score': array([ 0.89083901]),
 'split4_train_score': array([ 0.94787374]),
 'split5_test_score': array([ 0.90926355]),
 'split5_train_score': array([ 0.94829775]),
 'split6_test_score': array([ 0.82520379]),
 'split6_train_score': array([ 0.94971417]),
 'std_fit_time': array([ 1.79167576]),
 'std_score_time': array([ 0.02970254]),
 'std_test_score': array([ 0.0809713]),
 'std_train_score': array([ 0.0105566])}

As you can see, doing the np.mean of all the test_score it gives you a value approximately of 0.8655122606479532 while the 'mean_test_score' is 0.83490629

Thanks for you help,
Leonardo.

Body:
I suppose the reason for the different means are different weighting factors in the mean calculation.

The mean_test_score that sklearn returns is the mean calculated on all samples where each sample has the same weight.

If you calculate the mean by taking the mean of the folds (splits), then you only get the same results if the folds are all of equal size. If they are not, then all samples of larger folds will automatically have a smaller impact on the mean of the folds than smaller folds, and the other way around.

Small numeric example:

mean([2,3,5,8,9]) = 5.4 # mean over all samples ('mean_test_score')

mean([2,3,5]) = 3.333 # mean of fold 1
mean([8,9]) = 8.5 # mean of fold 2

mean(3.333, 8.5) = 5.91 # mean of means of folds

5.4 != 5.91


问:
Correct syntax in php
I'am tryig to print an id this way

```<code><form action="upload.php" method="post" enctype="multipart/form-data" <?php isset($_REQUEST['code'])?echo'id="csv-form"':echo 'id="edit-form"'; ?> >
</code>```

But I get this error syntax error, unexpected 'echo'

How is the correct syntax?

答:
The ternary operator has the form condition ? expression : expression while you wrote in your code condition ? statement : statement.

You should write it like this:

```<code>echo isset($_REQUEST['code']) ? 'id="csv-form"' : 'id="edit-form"'
</code>```

Title: Correct syntax in php

Body:
I'am tryig to print an id this way

<form action="upload.php" method="post" enctype="multipart/form-data" <?php isset($_REQUEST['code'])?echo'id="csv-form"':echo 'id="edit-form"'; ?> >

But I get this error syntax error, unexpected 'echo'

How is the correct syntax?

Body:
The ternary operator has the form condition ? expression : expression while you wrote in your code condition ? statement : statement.

You should write it like this:

echo isset($_REQUEST['code']) ? 'id="csv-form"' : 'id="edit-form"'


问:
Does an NServiceBus endpoint with SQL Server transport and Windows authentication need to be installed as the user running the service?
I'm installing an NServiceBus 4.x endpoint which uses SQL Server transport.  While running the installer (via Octopus Deploy, which runs as Local System by default)...

.\NServiceBus.Host.exe /install NServiceBus.Production /serviceName=$name /username:"$username" /password:"$password

... I get an error:

Failed to execute installers: System.Data.SqlClient.SqlException (0x80131904): Login failed for user 'DOMAIN\MACHINENAME$'.

This is the expected behavior if the installer connects to SQL Server when it's run: Local System becomes the computer account when it leaves the box and the computer account does not have access to the transport database.

However, I do not intend to run the endpoint as Local System.  Instead, I intend to use a domain service account which does have access to the transport database, so...

Is it possible to install an NServiceBus endpoint using SQL Server transport as a user who does not have access to the transport database?

Bonus question: Has this behavior been changed in versions of NServiceBus later than 4.x?

答:
The problem here is that the NServiceBus.Host.exe is executed with the credentials of as you say Octopus Deploy and /install runs the NServiceBus installers.

Some alternatives:

Run Octopus Deploy Agent with permissions that also allows doing schema changes on the database during this deployment phase.

Instead of executing the host directly, launch a shell with different credentials so that the host is run with credentials that have appropriate permissions.

Do not use the host, but use self-hosting. Register that service via sc.exe to register the windows service with the right credentials, and use endpointConfiguration.EnableInstallers() to control if installers must be run.

https://docs.particular.net/nservicebus/operations/installers

https://docs.particular.net/samples/hosting/windows-service/

https://docs.particular.net/nservicebus/hosting/windows-service#installation

Use self-hosting as in (3), don't use endpointConfiguration.EnableInstallers() but script all tasks and let these run independently of the 'windows service' registration task. Alternatively, you can instead use  sc.exe to register the NServiceBus.Host.exe so that the /install will not be run.

That means generating most scripts yourself. Some components have script generators but our docs have a lot of guidance on scripting

https://docs.particular.net/search?q=script

I would advise NOT to just always run endpointConfiguration.EnableInstallers() on an endpoint. You should distinguish between a deployment and runtime. During deployment you would create tables, schemas etc. but at runtime, that account should not have the permissions to create or drop tables and run least privilege.


问:
my php script enters blank info into mysql db!
When I try to enter data from a form I have made it adds a new entry as i can see from phpmyadmin but does not transfer other details across

I am using a simple form that collects 9 fileds post is to update.php. Here is what I have in update.php

```<code><?php
$realname = $_POST['realname'];
$age = $_POST['age'];
$country = $_POST['country'];
$gamename = $_POST['gamename'];
$gamelevel = $_POST['gamelevel'];
$itemlevel = $_POST['itemlevel'];
$class = $_POST['class'];
$played = $_POST['played'];
$support = $_POST['support'];

mysql_connect ("localhost", "mydb_userid", "MYPASSWORD") or die ('Error: ' . mysql_error());
mysql_select_db ("mydb_recruitment");

$query="INSERT INTO applicants (ID, realname, age, country, gamename, gamelevel, itemlevel, class, played, support)VALUES ('NULL','".$realname."','".$age."','".$country."','".$gamename."','".$gamelevel."','".$itemlevel."','".$class."','".$played."','".$support."')";

mysql_query($query) or die ('Error updating DB');

echo "You have sucessfully sent an application. Your details will be reviewed and someone will get back to you";

?>
</code>```

Hope someone can help, searching the net seems to sugest something about global variables - but i dont know if i have control of that as its an hosted site.

this is the signup form:

```<code><!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Candidate Registration</title>
</head>

<body>

<form medthod="post" action="update.php">

Real Name:<br />
<input type="text" name="realname" size="50" /><br />

Age:<br />
<input type="text" name="age" size="10" /><br />

Country:<br />
<input type="text" name="country" size="20" /><br />

In Game Name:<br />
<input type="text" name="gamename" size="30" /><br />

In Game Level:<br />
<input type="text" name="gamelevel" size="10" /><br />

In Game Item Level:<br />
<input type="text" name="itemlevel" size="10" /><br />

Class Played:<br />
<input type="text" name="class" size="30" /><br />

How long have you played wow?:<br />
<input type="text" name="played" size="10" /><br />

Please enter a brief statement of why you want to join:<br />
<input type="text" name="support" size="5000" /><br />
<br />
<input type="submit" value="Update DB" />

</form>
</body>
</html>
</code>```

this is the update.php form

```<code><?php
$realname = $_POST['realname'];
$age = $_POST['age'];
$country = $_POST['country'];
$gamename = $_POST['gamename'];
$gamelevel = $_POST['gamelevel'];
$itemlevel = $_POST['itemlevel'];
$class = $_POST['class'];
$played = $_POST['played'];
$support = $_POST['support'];

mysql_connect ("localhost", "mydb_daniel", "mypwd") or die ('Error: ' . mysql_error());
mysql_select_db ("mydb_recruitment");

$query="INSERT INTO applicants (ID, realname, age, country, gamename, gamelevel, itemlevel, class, played, support)VALUES ('NULL','".$realname."','".$age."','".$country."','".$gamename."','".$gamelevel."','".$itemlevel."','".$class."','".$played."','".$support."')";

mysql_query($query) or die ('Error updating DB');

echo "You have sucessfully sent an application. Your details will be reviewed and someone will get back to you";

?>
</code>```

I understand peoples concerns about sercurity, but please understand this only for me to mess around with and produce a basic signup form for my guild, i wont be requesting credit card details :)

答:
Whoa, slow down. You've not even escaped this data!

```<code>$realname = mysql_real_escape_string($_POST['realname']);
</code>```

Or to escape it all:

```<code>$_POST = array_map('mysql_real_escape_string', $_POST);
</code>```

Note the second solution isn't entirely reliable. Can produce some strange results. It is generally better to run these inputs through a function/class for validation and cleansing.

On your ghost issue, try this and note response after form submit (put right at top):

```<code>var_dump($_POST);
exit;
</code>```

You spelled method attribute wrong in your query, that is why it isn't working.

ContentLicense: CC BY-SA 2.5

Body:
When I try to enter data from a form I have made it adds a new entry as i can see from phpmyadmin but does not transfer other details across

I am using a simple form that collects 9 fileds post is to update.php. Here is what I have in update.php

<?php
$realname = $_POST['realname'];
$age = $_POST['age'];
$country = $_POST['country'];
$gamename = $_POST['gamename'];
$gamelevel = $_POST['gamelevel'];
$itemlevel = $_POST['itemlevel'];
$class = $_POST['class'];
$played = $_POST['played'];
$support = $_POST['support'];

mysql_connect ("localhost", "mydb_userid", "MYPASSWORD") or die ('Error: ' . mysql_error());
mysql_select_db ("mydb_recruitment");

$query="INSERT INTO applicants (ID, realname, age, country, gamename, gamelevel, itemlevel, class, played, support)VALUES ('NULL','".$realname."','".$age."','".$country."','".$gamename."','".$gamelevel."','".$itemlevel."','".$class."','".$played."','".$support."')";

mysql_query($query) or die ('Error updating DB');

echo "You have sucessfully sent an application. Your details will be reviewed and someone will get back to you";

?>

Hope someone can help, searching the net seems to sugest something about global variables - but i dont know if i have control of that as its an hosted site.

this is the signup form:

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Candidate Registration</title>

<form medthod="post" action="update.php">

Real Name:

<input type="text" name="realname" size="50" />

Age:

<input type="text" name="age" size="10" />

Country:

<input type="text" name="country" size="20" />

In Game Name:

<input type="text" name="gamename" size="30" />

In Game Level:

<input type="text" name="gamelevel" size="10" />

In Game Item Level:

<input type="text" name="itemlevel" size="10" />

Class Played:

<input type="text" name="class" size="30" />

How long have you played wow?:

<input type="text" name="played" size="10" />

Please enter a brief statement of why you want to join:

<input type="text" name="support" size="5000" />

<input type="submit" value="Update DB" />

</form>

this is the update.php form

<?php
$realname = $_POST['realname'];
$age = $_POST['age'];
$country = $_POST['country'];
$gamename = $_POST['gamename'];
$gamelevel = $_POST['gamelevel'];
$itemlevel = $_POST['itemlevel'];
$class = $_POST['class'];
$played = $_POST['played'];
$support = $_POST['support'];

mysql_connect ("localhost", "mydb_daniel", "mypwd") or die ('Error: ' . mysql_error());
mysql_select_db ("mydb_recruitment");

$query="INSERT INTO applicants (ID, realname, age, country, gamename, gamelevel, itemlevel, class, played, support)VALUES ('NULL','".$realname."','".$age."','".$country."','".$gamename."','".$gamelevel."','".$itemlevel."','".$class."','".$played."','".$support."')";

mysql_query($query) or die ('Error updating DB');

echo "You have sucessfully sent an application. Your details will be reviewed and someone will get back to you";

?>

I understand peoples concerns about sercurity, but please understand this only for me to mess around with and produce a basic signup form for my guild, i wont be requesting credit card details :)

Body:
Whoa, slow down. You've not even escaped this data!

$realname = mysql_real_escape_string($_POST['realname']);

Or to escape it all:

$_POST = array_map('mysql_real_escape_string', $_POST);

Note the second solution isn't entirely reliable. Can produce some strange results. It is generally better to run these inputs through a function/class for validation and cleansing.

On your ghost issue, try this and note response after form submit (put right at top):

var_dump($_POST);
exit;

You spelled method attribute wrong in your query, that is why it isn't working.


问:
How to make a movie out of images in python
I currently try to make a movie out of images, but i could not find anything helpful .

Here is my code so far:

```<code>import time

from PIL import  ImageGrab

x =0

while True:
    try:
        x+= 1
        ImageGrab().grab().save('img{}.png'.format(str(x))
    except:
        movie = #Idontknow
        for _ in range(x):
            movie.save("img{}.png".format(str(_)))

movie.save()
</code>```

答:
You could consider using an external tool like ffmpeg to merge the images into a movie (see answer here) or you could try to use OpenCv to combine the images into a movie like the example here.

I'm attaching below a code snipped I used to combine all png files from a folder called "images" into a video.

```<code>import cv2
import os

image_folder = 'images'
video_name = 'video.avi'

images = [img for img in os.listdir(image_folder) if img.endswith(".png")]
frame = cv2.imread(os.path.join(image_folder, images[0]))
height, width, layers = frame.shape

video = cv2.VideoWriter(video_name, 0, 1, (width,height))

for image in images:
    video.write(cv2.imread(os.path.join(image_folder, image)))

cv2.destroyAllWindows()
video.release()
</code>```

It seems that the most commented section of this answer is the use of VideoWriter. You can look up it's documentation in the link of this answer (static) or you can do a bit of digging of your own. The first parameter is the filename, followed by an integer (fourcc in the documentation, the codec used), the FPS count and a tuple of the dimensions of the frame. If you really like digging in that can of worms, here's the fourcc video codecs list.

Body:
I currently try to make a movie out of images, but i could not find anything helpful .

Here is my code so far:

import time

from PIL import  ImageGrab

x =0

while True:
    try:
        x+= 1
        ImageGrab().grab().save('img{}.png'.format(str(x))
    except:
        movie = #Idontknow
        for _ in range(x):
            movie.save("img{}.png".format(str(_)))

movie.save()

Body:
You could consider using an external tool like ffmpeg to merge the images into a movie (see answer here) or you could try to use OpenCv to combine the images into a movie like the example here.

I'm attaching below a code snipped I used to combine all png files from a folder called "images" into a video.

import cv2
import os

image_folder = 'images'
video_name = 'video.avi'

images = [img for img in os.listdir(image_folder) if img.endswith(".png")]
frame = cv2.imread(os.path.join(image_folder, images[0]))
height, width, layers = frame.shape

video = cv2.VideoWriter(video_name, 0, 1, (width,height))

for image in images:
    video.write(cv2.imread(os.path.join(image_folder, image)))

cv2.destroyAllWindows()
video.release()

It seems that the most commented section of this answer is the use of VideoWriter. You can look up it's documentation in the link of this answer (static) or you can do a bit of digging of your own. The first parameter is the filename, followed by an integer (fourcc in the documentation, the codec used), the FPS count and a tuple of the dimensions of the frame. If you really like digging in that can of worms, here's the fourcc video codecs list.

ContentLicense: CC BY-SA 4.0


问:
Inserting developerPayload to getBuyIntent() method
I try to make Google Play Billing Service via com.android.billingclient:billing-dp1 library. I try starting the billing process by calling:

```<code>billingClient.launchBillingFlow(activity, params);
</code>```

So the question is how to pass "developerPayload" argument to this flow? Both launchBillingFlow and it's params argument don't contain such a field.

答:
You cannot, if you look at the sources of BillingClientImpl you'll see this:

```<code>buyIntentBundle =
        mService.getBuyIntent(3, mContext.getPackageName(), newSku, skuType, null);
</code>```

The Last null is the developerPayload:

```<code>Bundle getBuyIntent(int apiVersion, String packageName, String sku, String type,
    String developerPayload);
</code>```

So, no implementation for developerPayload yet.

Body:
I try to make Google Play Billing Service via com.android.billingclient:billing-dp1 library. I try starting the billing process by calling:

billingClient.launchBillingFlow(activity, params);

So the question is how to pass "developerPayload" argument to this flow? Both launchBillingFlow and it's params argument don't contain such a field.

Body:
You cannot, if you look at the sources of BillingClientImpl you'll see this:

buyIntentBundle =
        mService.getBuyIntent(3, mContext.getPackageName(), newSku, skuType, null);

The Last null is the developerPayload:

Bundle getBuyIntent(int apiVersion, String packageName, String sku, String type,
    String developerPayload);

So, no implementation for developerPayload yet.


问:
disable past date in datepicker wpf?
How can i disable past date in date picker?I am using ModernUI for my desktop application  </p>

```<code><DatePicker Grid.Column="0" Name="datepicker"  SelectedDate="{x:Static sys:DateTime.Now}" />
</code>```

答:
at codebehind you can define display date like this  </p>

```<code>datepicker.DisplayDateStart = DateTime.Now;
</code>```

Title: disable past date in datepicker wpf?

Body:
How can i disable past date in date picker?I am using ModernUI for my desktop application

<DatePicker Grid.Column="0" Name="datepicker"  SelectedDate="{x:Static sys:DateTime.Now}" />

Body:
at codebehind you can define display date like this

datepicker.DisplayDateStart = DateTime.Now;


问:
How to write http url based web service in netbeans?
How can I write a web service where I can query in the URL with some parameters and display the result in the JSON format.

For example, There is a table AppInfo in my database which has two columns named AppID and Status

Now, what I want is to write a web service like that

```<code>http://10.11.201.84?q=Select+*+from+AppInfo+where+AppID='21212'&format=json
</code>```

So, from a user, I will take the application id and get the status using this web service. I might have to use get method for using the HTTP URL request.

Which web service I have to use in this case and how?

答:
It's pretty simple (assuming you're having curent NB version)

Create a new project Java Web -> Web Application

In the project: New -> Web Service -> RESTful service

you have multiple options.. you have an empty one, from database, etc..

Body:
How can I write a web service where I can query in the URL with some parameters and display the result in the JSON format.

For example, There is a table AppInfo in my database which has two columns named AppID and Status

Now, what I want is to write a web service like that

http://10.11.201.84?q=Select+*+from+AppInfo+where+AppID='21212'&format=json

So, from a user, I will take the application id and get the status using this web service. I might have to use get method for using the HTTP URL request.

Which web service I have to use in this case and how?


问:
Get Permanent CWnd from HWnd
We run into a problem with temporary handles.

As I read here: What is the lifetime of a CWnd obtained from CWnd::FromHandle?
CWnd::FromHandle() will create a temporary handle. Our plan was to store the handle for later use, but this won't work.

We also tried CWnd::FromHandlePermanent() but this somehow returns a null pointer .

And also mpWnd->Attach(mhWnd); threw an Access violation exception.

If possible we would like to store the CWnd rather than the HWnd and call FromHandle() everytime the CWnd is required.
Does anybody know a solution for this?

答:
You get only a permanent CWnd object if you subclass an existing window, or you create a CWnd with one of the CWnd::Create functions.

You should not use Attach in this situation. Attach is used by SubclassWindow and by the internal Create hooks. If you use Attach without subclassing, the window will not be removed from the handle map upon destruction.

So when you get an error with the Attach function then either the mpwnd object isn't valid, or the CWnd object is already subclassed.

Also, it doesn't make sense to me why you want to store a CWnd pointer. Use a handle and if needed use FromHandle. The drawback of subclassing windows always is: that if your program later tries to subclass the window finally this fails, because it is already subclassed.

Also your question doesn't give information WHY you want to do this.

Title: Get Permanent CWnd from HWnd


问:
Get List from a Child Model
I created my list from model FolderModel to Add something like this:

```<code>var folders = new List<FolderModel>();
using (var command = new NpgsqlCommand())
            {
                ...
                        try
                        {
                            folders.Add(
                                new FolderModel()

                                {
                                    Id = (int)reader["id"],
                                    Name = (string)reader["foldername"]
                                }
                            );
                        }
 ...
</code>```

So I have my List in the folders variable and can add it with folders.Add and the new FolderModel().

Now I have the problem, that a Parent model is over the folder model and i need to use it. And my problem is, I cannot get the FolderModel List again.

Parentmodel:

```<code>public class ParentModel
    {
        public FolderModel FolderModel { get; set; }
    }
</code>```

Foldermodel:

```<code>public class FolderModel
    {
        public int Id { get; set; }
        public string Name{ get; set; }

    }
}
</code>```

How can I achieve the List when I start from the ParentModel?

```<code>ParentModel pm = new ParentModel();
var folders = List<pm.FolderModel>();
</code>```

Does not work for example. How can I achieve my Parentmodel.FolderModel list and what do I have to write instead of the new FolderModel() line?

答:
Update the ParentModel

```<code>public class ParentModel {
    public List<FolderModel> FolderModels { get; set; }
}
</code>```

Then you can assign the list to the parent

```<code>var folders = new List<FolderModel>();
//...execute command and populate folders
ParentModel pm = new ParentModel();
pm.FolderModels = folders;
</code>```

Title: Get List from a Child Model

Body:
I created my list from model FolderModel to Add something like this:

var folders = new List<FolderModel>();
using (var command = new NpgsqlCommand())
            {
                ...
                        try
                        {
                            folders.Add(
                                new FolderModel()

                                {
                                    Id = (int)reader["id"],
                                    Name = (string)reader["foldername"]
                                }
                            );
                        }
 ...

So I have my List in the folders variable and can add it with folders.Add and the new FolderModel().

Now I have the problem, that a Parent model is over the folder model and i need to use it. And my problem is, I cannot get the FolderModel List again.

Parentmodel:

public class ParentModel
    {
        public FolderModel FolderModel { get; set; }
    }

Foldermodel:

public class FolderModel
    {
        public int Id { get; set; }
        public string Name{ get; set; }

    }
}

How can I achieve the List when I start from the ParentModel?

ParentModel pm = new ParentModel();
var folders = List<pm.FolderModel>();

Does not work for example. How can I achieve my Parentmodel.FolderModel list and what do I have to write instead of the new FolderModel() line?

Body:
Update the ParentModel

public class ParentModel {
    public List<FolderModel> FolderModels { get; set; }
}

Then you can assign the list to the parent

var folders = new List<FolderModel>();
//...execute command and populate folders
ParentModel pm = new ParentModel();
pm.FolderModels = folders;


问:
Externalizing Tomcat webapp config from .war file
I am having trouble with configuring a webapp in Tomcat 7. In my WAR file, there is a properties file myApp/WEB-INF/classes/myProps.props, and it contains environment-specific properites. I am trying to override that configuration file on the server, so that the same WAR file will deploy to multiple environments.

I heard there was a way to do this using replacement config files in tomcat/conf/Catalina/myApp. This is the method I am having trouble figuring out.

Also, myApp.war is one of many running on the same Tomcat server, and it does not run as localhost. I want to be able to solve this problem for several of the webapps.

```<code>Server version: Apache Tomcat/7.0.23
Server built:   Nov 20 2011 07:36:25
Server number:  7.0.23.0
OS Name:        Linux
</code>```

答:
I just added a setenv.bat or setenv.sh script in the bin folder of tomcat. Set the classpath variable like

```<code>set CLASSPATH=my-propery-folder
</code>```

Body:
I am having trouble with configuring a webapp in Tomcat 7. In my WAR file, there is a properties file myApp/WEB-INF/classes/myProps.props, and it contains environment-specific properites. I am trying to override that configuration file on the server, so that the same WAR file will deploy to multiple environments.

I heard there was a way to do this using replacement config files in tomcat/conf/Catalina/myApp. This is the method I am having trouble figuring out.

Also, myApp.war is one of many running on the same Tomcat server, and it does not run as localhost. I want to be able to solve this problem for several of the webapps.

Server version: Apache Tomcat/7.0.23
Server built:   Nov 20 2011 07:36:25
Server number:  7.0.23.0
OS Name:        Linux

Body:
I just added a setenv.bat or setenv.sh script in the bin folder of tomcat. Set the classpath variable like

set CLASSPATH=my-propery-folder


问:
Insert space between arguments to concat function
When I concat($name, $surname), is there a way of putting a space in between the $name $surname using my sql not php so when i get the result it formats a little cleaner?

答:
You can concatenate string literals along with your fields, so you can add a space character in a string between the fields you're concatenating.

Use this:

```<code> CONCAT(name, " ", surname)
</code>```

This functionality is documented quite clearly on the MySQL manual page for the CONCAT() function.

There is also the CONCAT_WS function which allows you to specify a separator to be used between each of the other fields passed to the function. If you're concatenating more than two fields in the same way, this function might be considered cleaner than repeating the separator between each field.

For example, if you wanted to add a middle name field, you could use this function to specify the separator only once:

```<code>CONCAT_WS(" ", first_name, middle_name, surname)
</code>```

Body:
You can concatenate string literals along with your fields, so you can add a space character in a string between the fields you're concatenating.

Use this:

 CONCAT(name, " ", surname)

This functionality is documented quite clearly on the MySQL manual page for the CONCAT() function.

There is also the CONCAT_WS function which allows you to specify a separator to be used between each of the other fields passed to the function. If you're concatenating more than two fields in the same way, this function might be considered cleaner than repeating the separator between each field.

For example, if you wanted to add a middle name field, you could use this function to specify the separator only once:

CONCAT_WS(" ", first_name, middle_name, surname)


问:
CoreData/Entity error does not disappear even though there is no more entity
I am facing a CoreData related issue, and keep getting this error message:

```<code>Command /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/bin/swiftc failed with exit code 1
</code>```

More precisely, before the message above is displayed, I can see these details:

```<code><unknown>:0: error: filename "NiceEntity+CoreDataProperties.swift" used twice: '../Library/Developer/Xcode/DerivedData/NiceApp-bactemnueukiynkkjghppujjxzyht/Build/Intermediates/NiceApp.build/Debug-iphonesimulator/NiceApp.build/DerivedSources/CoreDataGenerated/BWP/NiceEntity+CoreDataProperties.swift' and '../Library/Developer/Xcode/DerivedData/NiceApp-bactemnueukiynkkjghppujjxzyht/Build/Intermediates/NiceApp.build/Debug-iphonesimulator/NiceApp.build/DerivedSources/CoreDataGenerated/BWP/NiceEntity+CoreDataProperties.swift'
<unknown>:0: note: filenames are used to distinguish private declarations with the same name
</code>```

I know I made some wrong manipulations when first setting up the entity NiceEntity, but I have removed everything that I could see related to this entity. That is I removed the entity NiceEntity from the data model and I erased the DerivedData/NiceApp-bactemnueukiynkkjghppujjxzyht folder. And yet the error has not disappeared.

Anyone has an idea on how to solve that?

In case this may be useful, I am using Xcode Version 8.3.2.

答:
Here is what worked for me at the end.

I removed all the entities that I had added recently, that is those in some ways related to my issue. I then rebuilt them one by one (I was lucky that there were not too many), and the problem magically disappeared. Who knows what dirty things I had been doing before?

Body:
I am facing a CoreData related issue, and keep getting this error message:

Command /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/bin/swiftc failed with exit code 1

More precisely, before the message above is displayed, I can see these details:

<unknown>:0: error: filename "NiceEntity+CoreDataProperties.swift" used twice: '../Library/Developer/Xcode/DerivedData/NiceApp-bactemnueukiynkkjghppujjxzyht/Build/Intermediates/NiceApp.build/Debug-iphonesimulator/NiceApp.build/DerivedSources/CoreDataGenerated/BWP/NiceEntity+CoreDataProperties.swift' and '../Library/Developer/Xcode/DerivedData/NiceApp-bactemnueukiynkkjghppujjxzyht/Build/Intermediates/NiceApp.build/Debug-iphonesimulator/NiceApp.build/DerivedSources/CoreDataGenerated/BWP/NiceEntity+CoreDataProperties.swift'
<unknown>:0: note: filenames are used to distinguish private declarations with the same name

I know I made some wrong manipulations when first setting up the entity NiceEntity, but I have removed everything that I could see related to this entity. That is I removed the entity NiceEntity from the data model and I erased the DerivedData/NiceApp-bactemnueukiynkkjghppujjxzyht folder. And yet the error has not disappeared.

Anyone has an idea on how to solve that?

In case this may be useful, I am using Xcode Version 8.3.2.


问:
How can I return the matched value from env::var?
If the environment variable SOMEVALUE is found, it should be bound to k:

```<code>let k = match env::var(SOMEVALUE) {
    Ok(val) => {return val},
    Err(e) => println!("could not find {}: {}", SOMEVALUE, e),
};
</code>```

Compiling this code gives the following error

   |
11 |         Ok(val) => {return val},
   |                            ^^^ expected (), found struct `std::string::String`
   |
   = note: expected type `()`
              found type `std::string::String`
```

答:
In Rust, everything is an expression, there are only a few statements. Each expression returns a value and if the expression does not return anything explicitly, it returns a () (unit) value implicitly.

Your match expression returns different types from 2 branches - a std::String from Ok branch and () from Err branch.

To fix this, you must return something from the second branch too:

```<code>let k = match env::var(SOMEVALUE) {
    Ok(val) => {return val},
    Err(e) => {
        println!("could not find {}: {}", SOMEVALUE, e);

        String::default()
    },
};
</code>```

This returns a value of the same type - std::String.

Body:
If the environment variable SOMEVALUE is found, it should be bound to k:

let k = match env::var(SOMEVALUE) {
    Ok(val) => {return val},
    Err(e) => println!("could not find {}: {}", SOMEVALUE, e),
};

Compiling this code gives the following error

   |
11 |         Ok(val) => {return val},
   |                            ^^^ expected (), found struct `std::string::String`
   |
   = note: expected type `()`
              found type `std::string::String`

Body:
In Rust, everything is an expression, there are only a few statements. Each expression returns a value and if the expression does not return anything explicitly, it returns a () (unit) value implicitly.

Your match expression returns different types from 2 branches - a std::String from Ok branch and () from Err branch.

To fix this, you must return something from the second branch too:

let k = match env::var(SOMEVALUE) {
    Ok(val) => {return val},
    Err(e) => {
        println!("could not find {}: {}", SOMEVALUE, e);

        String::default()
    },
};

This returns a value of the same type - std::String.


问:
How to dismiss a Twitter Bootstrap popover by clicking outside?
Can we get popovers to be dismissable in the same way as modals, ie. make them close when user clicks somewhere outside of them?

Unfortunately I can't just use real modal instead of popover, because modal means position:fixed and that would be no popover anymore. :(

答:
simply add this attribute with the element</p>

```<code>data-trigger="focus"
</code>```

Body:
simply add this attribute with the element

data-trigger="focus"


问:
Call index functions inside a component
I've an angular 4 app, in the index.html file, I've a lot of html elements before and after the ng app, since it's just an widget/component for the website.

In the head section of index file, it loads some css and js libraries, such as jquery, bootstrap, etc..

In order to style the select and option tags I'm using the bootstrap-select.

The issue is: the select boxes that are hard coded in the index file, works fine, but the ones that are inside the angular app, only work at the beginning.

If I use the *ngIf directive to hide and show the element, when it's added again, it doesn't call the 2 functions that are in the index file.

index.html

```<code><script>
    $(document).ready(function(){
        if ($('.select_box').length > 0){initializeSelectPicker();}
    });

    $(window).load(function(){
        if ($('.select_box').length > 0){adjustSelectPicker();}
    });

    $(window).resize(function(){
        if ($('.select_box').length > 0){adjustSelectPicker();}
    });

    function initializeSelectPicker(){
        $('.select_box').selectpicker({});
    }

    function adjustSelectPicker(){

        $(this).find(".btn-group.bootstrap-select.select_box.show-tick .btn.dropdown-toggle.selectpicker.btn-default .filter-option.pull-left").css("width", "0");

        $(this).each(function(){
            var maxWidthBox = $(this).find(".btn-group.bootstrap-select.select_box.show-tick .btn.dropdown-toggle.selectpicker.btn-default").width() - 20;
            $(this).find(".btn-group.bootstrap-select.select_box.show-tick .btn.dropdown-toggle.selectpicker.btn-default .filter-option.pull-left").css("width", maxWidthBox + "px");
        });
    }
</script>
</code>```

There is any way to call them in the ngOnChanges of a component?

答:
I dont recommend this approach, but this can be solved with emitting an event and listen to the desired eventname in your index file.

index file:

```<code>window.addEventListener('ngFix', function(e) {
// call either one of the methods you wish to run.
});
</code>```

Somewhere in your component you'd have to emit the event, presumably where the input value for the if directive is changed.

```<code>window.dispatchEvent(new CustomEvent('ngFix'));
</code>```

Title: Call index functions inside a component

Body:
I've an angular 4 app, in the index.html file, I've a lot of html elements before and after the ng app, since it's just an widget/component for the website.

In the head section of index file, it loads some css and js libraries, such as jquery, bootstrap, etc..

In order to style the select and option tags I'm using the bootstrap-select.

The issue is: the select boxes that are hard coded in the index file, works fine, but the ones that are inside the angular app, only work at the beginning.

If I use the *ngIf directive to hide and show the element, when it's added again, it doesn't call the 2 functions that are in the index file.

index.html

There is any way to call them in the ngOnChanges of a component?

Body:
I dont recommend this approach, but this can be solved with emitting an event and listen to the desired eventname in your index file.

index file:

window.addEventListener('ngFix', function(e) {
// call either one of the methods you wish to run.
});

Somewhere in your component you'd have to emit the event, presumably where the input value for the if directive is changed.

window.dispatchEvent(new CustomEvent('ngFix'));


问:
Apple Mach-O Linker Error - Xcode (Swift)
I'm trying to use a cocoapod with my Xcode project (Swift).

When I try to Build the project it fails with:

Apple Mach-O Linker Error Group
 -   "_OBJC_CLASS_$_FSCalendar", referenced from:
 - clang: error: linker command failed with exit code 1 (use -v to see invocation)

Errors

Any ideas what could be causing this?

(The cocoapod I am using is: https://github.com/WenchaoD/FSCalendar

UPDATE

I have added the frameworks and now I am just getting "clang: error: linker command failed with exit code 1 (use -v to see invocation)"

UPDATE

Full error:

ld: warning: directory not found for option '-F/Users/me/Documents/APP/build/Debug-iphoneos/FSCalendar'
ld: warning: directory not found for option '-F/Users/me/Documents/APP/build/Debug-iphoneos'
ld: framework not found FSCalendar
clang: error: linker command failed with exit code 1 (use -v to see invocation)

答:
After I ran pod install on the new name I changed my project to, I had this error cause the pod framework was not linking to NEW project name and was still looking for OLD name.

I resolved by going into my projects 'Linked Frameworks and Libraries' in the Targets section and removing the OLD framework that has the OLD project name.

Targets > General > Linked Frameworks and Libraries > -(Pods_OLD_PROJECT_NAME.framework)


问:
split a large file into small file based on pattern that can occur randomly Python
I have this large file with following content:

```<code>Column1 column2 column3
 345     367    Ramesh
 456     469    Ramesh
 300     301    Ramesh
 298     390    Naresh
 123     125    Suresh
 394     305    Suresh
 ......
 .....
</code>```

Now, I want to split this file into small files based on the name in column3. Like this:

File1: Ramesh.txt

```<code>column1 column2 column3
345     367      Ramesh
456     469      Ramesh
300     301      Ramesh
</code>```

File2: Naresh.txt

```<code>column1 column2 column3
298     390     Naresh
</code>```

File3: Suresh.txt

```<code>Column1 column2 column3
123     125      suresh
394     305      suresh
</code>```

and likewise.
I wrote the following python codes and it worked:

```<code>def split_file(file1):
source=open(file1)
l=[]
header=0
header_line=""
file_count=0
for line in source:
    line=line.rstrip()
    a=line.split()
    if header==0:
        header_line=line
        header+=1
    else:
        if a[-1] not in l:
            l.append(a[-1])
            file_count+=1
            if file_count>1:
                dest.close()
            else:
                pass
            dest=open(a[-1],'a')
            dest.write(header_line+"\n"+line+"\n")
        else:
            dest.write(line+"\n")
source.close()
dest.close()
</code>```

Now, my query is how can I modify these codes to work even if column3 is not sorted. For example:

```<code>Column1 column2 column3
345     367    Ramesh
123     125    Suresh
456     469    Ramesh
298     390    Naresh
300     301    Ramesh
394     305    Suresh
</code>```

Shall I generate random variable as values (to handle the output file) with the name in column3 as keys. And then use this dictionary to open the file everytime script encounters the key? Any suggestion will be appreciated.

答:
```<code>def split_file(filename):
    dest = {}
    with open(filename) as source:
        header_line = next(source)
        for line in source:
            name = line.rstrip().split()[-1]
            if name not in dest:
                dest[name] = open(name + '.txt', 'w')
                dest[name].write(header_line)
            dest[name].write(line)
    for d in dest.values():
        d.close()
</code>```

Body:
I have this large file with following content:

Column1 column2 column3
 345     367    Ramesh
 456     469    Ramesh
 300     301    Ramesh
 298     390    Naresh
 123     125    Suresh
 394     305    Suresh
 ......
 .....

Now, I want to split this file into small files based on the name in column3. Like this:

File1: Ramesh.txt

column1 column2 column3
345     367      Ramesh
456     469      Ramesh
300     301      Ramesh

File2: Naresh.txt

column1 column2 column3
298     390     Naresh

File3: Suresh.txt

Column1 column2 column3
123     125      suresh
394     305      suresh

and likewise.
I wrote the following python codes and it worked:

def split_file(file1):
source=open(file1)
l=[]
header=0
header_line=""
file_count=0
for line in source:
    line=line.rstrip()
    a=line.split()
    if header==0:
        header_line=line
        header+=1
    else:
        if a[-1] not in l:
            l.append(a[-1])
            file_count+=1
            if file_count>1:
                dest.close()
            else:
                pass
            dest=open(a[-1],'a')
            dest.write(header_line+"\n"+line+"\n")
        else:
            dest.write(line+"\n")
source.close()
dest.close()

Now, my query is how can I modify these codes to work even if column3 is not sorted. For example:

Column1 column2 column3
345     367    Ramesh
123     125    Suresh
456     469    Ramesh
298     390    Naresh
300     301    Ramesh
394     305    Suresh

Shall I generate random variable as values (to handle the output file) with the name in column3 as keys. And then use this dictionary to open the file everytime script encounters the key? Any suggestion will be appreciated.


问:
Vue.js app no errors but white page
I'm trying to learn Vue.
I read this tutorial and I'm trying to split it in single file components using the standard vue-cli webpack template. I don't have any error in console but the page is white, and I cannot understand why.

This is my main.js file

```<code>import Vue from 'vue'
import App from './App'

Vue.config.productionTip = false
window.axios = require('axios');

const NYTBaseUrl = "https://api.nytimes.com/svc/topstories/v2/";
const ApiKey = "18e1540d187c4b46bae767782750f9fd";
const SECTIONS = "home, arts, automobiles, books, business, fashion, food, health, insider, magazine, movies, national, nyregion, obituaries, opinion, politics, realestate, science, sports, sundayreview, technology, theater, tmagazine, travel, upshot, world";

function buildUrl (url) {
  return NYTBaseUrl + url + ".json?api-key=" + ApiKey
}

const vm = new Vue({
  el: '#app',
  data: {
    results: [],
    sections: SECTIONS.split(', '), // create an array of the sections
    section: 'home', // set default section to 'home'
    loading: true,
    title: ''
  },
  mounted () {
    this.getPosts('home');
  },
  methods: {
    getPosts(section) {
      let url = buildUrl(section);
      axios.get(url).then((response) => {
        this.loading = false;
        this.results = response.data.results;
        let title = this.section !== 'home' ? "Top stories in '"+ this.section + "' today" : "Top stories today";
        this.title = title + "(" + response.data.num_results+ ")";
      }).catch((error) => { console.log(error); });
    }
  }
});
</code>```

And this is the App.vue file

```<code><template>
  <div id="app">
    <h1>Test</h1>
    <product-list></product-list>
  </div>
</template>

<script>
import Products from './components/Products'

export default {
  name: 'app',
  components: {
    Products
  }
}
</script>

<style lang="sass" >
  @import '~bulma/sass/utilities/initial-variables.sass'
  @import "~bulma/sass/utilities/_all"
  @import "~bulma/sass/base/_all"
  @import "~bulma/sass/grid/columns"
  @import "~bulma/sass/components/_all"
</style>
</code>```

I also create a Products.vue file in the components folder

```<code><template id="product-list">
  <section>
    <div class="row" v-for="posts in processedPosts">
      <div class="columns large-3 medium-6" v-for="post in posts">
        <div class="card">
        <div class="card-divider">
        {{ post.title }}
        </div>
        <a :href="post.url" target="_blank"><img :src="post.image_url"></a>
        <div class="card-section">
          <p>{{ post.abstract }}</p>
        </div>
      </div>
      </div>
    </div>
  </section>

</template>

Vue.component('Products', {
  props: ['results'],
  template: "#product-list",
  computed: {
    processedPosts() {
      let posts = this.results;

      // Add image_url attribute
      posts.map(post => {
        let imgObj = post.multimedia.find(media => media.format === "superJumbo");
        post.image_url = imgObj ? imgObj.url : "http://placehold.it/300x200?text=N/A";
      });

      // Put Array into Chunks
      let i, j, chunkedArray = [],
        chunk = 4;
      for (i = 0, j = 0; i < posts.length; i += chunk, j++) {
        chunkedArray[j] = posts.slice(i, i + chunk);
      }
      return chunkedArray;
    }
  }
});
</code>```

Everything looks fine for me (except for the window.axios = require('axios'); that I don't understand why is not present in the original tutorial) but the page is blank and also the  tag I add for debug is not present in the DOM.

Edit

Looks like the code is not compiled.

My page source code is

```<code><body>
    <div id="app"></div>
    <!-- built files will be auto injected -->
  <script type="text/javascript" src="/app.js"></script>

</body>
</code>```

** Edit 2 **

I understand the problem. This is my index.html.

答:
There are several issues with your codes. First you have to wrap JavaScript in a script tag on your Products.vue file. Also on your Products.vue file you could just export the component files instead of creating the way you did, also you haven't imported Vue on Products.vue file but you are using it Vue.component('Products', {}). You should create Products.vue file this way

Products.vue

```<code><template>
  <section>
    <div class="container" v-for="posts in processedPosts">
      <div class="columns" v-for="post in posts">
        <div class="column is-6 is-offset-3">
           <div class="card">
           <header class="card-header">
             <p class="card-header-title">
            {{ post.title }}
            </p>
           </header>
           <div class="card-image">
           <a :href="post.url" target="_blank">
             <figure class="image">
               <img :src="post.image_url">
             </figure>
           </a>
           </div>

        <div class="card-content">
          <div class="content">
            <p>{{ post.abstract }}</p>
          </div>
        </div>
      </div>
        </div>
      </div>
    </div>
  </section>

</template>
<script>
export default{
  props: ['results'],
  computed: {
    processedPosts() {
      let posts = this.results;
      // Add image_url attribute
      posts.map(post => {
        let imgObj = post.multimedia.find(media => media.format === "superJumbo");
        post.image_url = imgObj ? imgObj.url : "http://placehold.it/300x200?text=N/A";
      });

      // Put Array into Chunks
      let i, j, chunkedArray = [],
        chunk = 4;
      for (i = 0, j = 0; i < posts.length; i += chunk, j++) {
        chunkedArray[j] = posts.slice(i, i + chunk);
      }
      return chunkedArray;
    }
  }
}
</script>
</code>```

On your main.js file you forgot to mount <App /> template.

```<code>new Vue({
  el: '#app',
  template: '<App/>',
  components: { App },
})
</code>```

You should also move code for network request, components to App.vue file.

main.js

```<code>import Vue from 'vue'
import App from './App'

Vue.config.productionTip = false
window.axios = require('axios');

new Vue({
  el: '#app',
  template: '<App/>',
  components: { App },
})
</code>```

Have to use the component we are importing, on your code you imported Products but using <product-list></product-list>.

App.vue

```<code><template>
  <div id="app">
    <products :results="results"></products>
  </div>
</template>

<script>
import Products from './components/Products'

const NYTBaseUrl = "https://api.nytimes.com/svc/topstories/v2/";
const ApiKey = "18e1540d187c4b46bae767782750f9fd";
const SECTIONS = "home, arts, automobiles, books, business, fashion, food, health, insider, magazine, movies, national, nyregion, obituaries, opinion, politics, realestate, science, sports, sundayreview, technology, theater, tmagazine, travel, upshot, world";

function buildUrl (url) {
  return NYTBaseUrl + url + ".json?api-key=" + ApiKey
}

export default {
  name: 'app',
  data: function(){
    return {
    results: [],
    sections: SECTIONS.split(', '), // create an array of the sections
    section: 'home', // set default section to 'home'
    loading: true,
    title: ''
    }
  },
  components: {
    Products
  },
  mounted(){
    this.getPosts('home');
  },
  methods:{
    getPosts(section) {
      let url = buildUrl(section);
      axios.get(url).then((response) => {
        this.loading = false;
        this.results = response.data.results;
        let title = this.section !== 'home' ? "Top stories in '"+ this.section + "' today" : "Top stories today";
        this.title = title + "(" + response.data.num_results+ ")";
      }).catch((error) => { console.log(error); });
    }
  }
}
</script>
</code>```

I tested this out, and uploaded code to github https://github.com/azs06/vuejs-news, you can clone it and check it out. Here it is deployed http://noisy-coach.surge.sh/

Note: I am using the api key temporarily will remove it, as soon as you test it out.

Title: Vue.js app no errors but white page

Body:
I'm trying to learn Vue.
I read this tutorial and I'm trying to split it in single file components using the standard vue-cli webpack template. I don't have any error in console but the page is white, and I cannot understand why.

This is my main.js file

import Vue from 'vue'
import App from './App'

Vue.config.productionTip = false
window.axios = require('axios');

const NYTBaseUrl = "https://api.nytimes.com/svc/topstories/v2/";
const ApiKey = "18e1540d187c4b46bae767782750f9fd";
const SECTIONS = "home, arts, automobiles, books, business, fashion, food, health, insider, magazine, movies, national, nyregion, obituaries, opinion, politics, realestate, science, sports, sundayreview, technology, theater, tmagazine, travel, upshot, world";

function buildUrl (url) {
  return NYTBaseUrl + url + ".json?api-key=" + ApiKey
}

const vm = new Vue({
  el: '#app',
  data: {
    results: [],
    sections: SECTIONS.split(', '), // create an array of the sections
    section: 'home', // set default section to 'home'
    loading: true,
    title: ''
  },
  mounted () {
    this.getPosts('home');
  },
  methods: {
    getPosts(section) {
      let url = buildUrl(section);
      axios.get(url).then((response) => {
        this.loading = false;
        this.results = response.data.results;
        let title = this.section !== 'home' ? "Top stories in '"+ this.section + "' today" : "Top stories today";
        this.title = title + "(" + response.data.num_results+ ")";
      }).catch((error) => { console.log(error); });
    }
  }
});

And this is the App.vue file

<template>

Test

    <product-list></product-list>

</template>

I also create a Products.vue file in the components folder

<template id="product-list">

        {{ post.title }}

{{ post.abstract }}

</template>

Vue.component('Products', {
  props: ['results'],
  template: "#product-list",
  computed: {
    processedPosts() {
      let posts = this.results;

      // Add image_url attribute
      posts.map(post => {
        let imgObj = post.multimedia.find(media => media.format === "superJumbo");
        post.image_url = imgObj ? imgObj.url : "http://placehold.it/300x200?text=N/A";
      });

      // Put Array into Chunks
      let i, j, chunkedArray = [],
        chunk = 4;
      for (i = 0, j = 0; i < posts.length; i += chunk, j++) {
        chunkedArray[j] = posts.slice(i, i + chunk);
      }
      return chunkedArray;
    }
  }
});

Everything looks fine for me (except for the window.axios = require('axios'); that I don't understand why is not present in the original tutorial) but the page is blank and also the  tag I add for debug is not present in the DOM.

Edit

Looks like the code is not compiled.

My page source code is

** Edit 2 **

I understand the problem. This is my index.html.

Body:
There are several issues with your codes. First you have to wrap JavaScript in a script tag on your Products.vue file. Also on your Products.vue file you could just export the component files instead of creating the way you did, also you haven't imported Vue on Products.vue file but you are using it Vue.component('Products', {}). You should create Products.vue file this way

Products.vue

<template>
  <section>
    <div class="container" v-for="posts in processedPosts">
      <div class="columns" v-for="post in posts">
        <div class="column is-6 is-offset-3">
           <div class="card">
           <header class="card-header">
             <p class="card-header-title">
            {{ post.title }}
            </p>
           </header>
           <div class="card-image">
           <a :href="post.url" target="_blank">
             <figure class="image">
               <img :src="post.image_url">
             </figure>
           </a>
           </div>

        <div class="card-content">
          <div class="content">
            <p>{{ post.abstract }}</p>
          </div>
        </div>
      </div>
        </div>
      </div>
    </div>
  </section>

</template>
<script>
export default{
  props: ['results'],
  computed: {
    processedPosts() {
      let posts = this.results;
      // Add image_url attribute
      posts.map(post => {
        let imgObj = post.multimedia.find(media => media.format === "superJumbo");
        post.image_url = imgObj ? imgObj.url : "http://placehold.it/300x200?text=N/A";
      });

      // Put Array into Chunks
      let i, j, chunkedArray = [],
        chunk = 4;
      for (i = 0, j = 0; i < posts.length; i += chunk, j++) {
        chunkedArray[j] = posts.slice(i, i + chunk);
      }
      return chunkedArray;
    }
  }
}
</script>

On your main.js file you forgot to mount <App /> template.

new Vue({
  el: '#app',
  template: '<App/>',
  components: { App },
})

You should also move code for network request, components to App.vue file.

main.js

import Vue from 'vue'
import App from './App'

Vue.config.productionTip = false
window.axios = require('axios');

new Vue({
  el: '#app',
  template: '<App/>',
  components: { App },
})

Have to use the component we are importing, on your code you imported Products but using <product-list></product-list>.

App.vue

<template>
  <div id="app">
    <products :results="results"></products>
  </div>
</template>

<script>
import Products from './components/Products'

const NYTBaseUrl = "https://api.nytimes.com/svc/topstories/v2/";
const ApiKey = "18e1540d187c4b46bae767782750f9fd";
const SECTIONS = "home, arts, automobiles, books, business, fashion, food, health, insider, magazine, movies, national, nyregion, obituaries, opinion, politics, realestate, science, sports, sundayreview, technology, theater, tmagazine, travel, upshot, world";

function buildUrl (url) {
  return NYTBaseUrl + url + ".json?api-key=" + ApiKey
}

export default {
  name: 'app',
  data: function(){
    return {
    results: [],
    sections: SECTIONS.split(', '), // create an array of the sections
    section: 'home', // set default section to 'home'
    loading: true,
    title: ''
    }
  },
  components: {
    Products
  },
  mounted(){
    this.getPosts('home');
  },
  methods:{
    getPosts(section) {
      let url = buildUrl(section);
      axios.get(url).then((response) => {
        this.loading = false;
        this.results = response.data.results;
        let title = this.section !== 'home' ? "Top stories in '"+ this.section + "' today" : "Top stories today";
        this.title = title + "(" + response.data.num_results+ ")";
      }).catch((error) => { console.log(error); });
    }
  }
}
</script>

I tested this out, and uploaded code to github https://github.com/azs06/vuejs-news, you can clone it and check it out. Here it is deployed http://noisy-coach.surge.sh/

Note: I am using the api key temporarily will remove it, as soon as you test it out.


问:
Creating EditText with button
I must create EditText with button inside and assign functions which will run after pressing the button. Then I would like to make it reusable - somehow add it as an element to my Activity. I was wondering about extending EditTextView and adding button and creating functions inside of it.
Any suggestions/ tutorials?</p>

答:
You can extend LinearLayout or RelativeLayout and add both Button and EditText in the constructor. However, you need to use a getter method to get the EditText or Button. Here is an example. I haven't tested it, but it should give you an idea. Just remember that, if you want to use xml attributes of Button or EditText, you should define them in attr.xml and then get them with TypedArray. Since the object is a LinearLayout, you cannot use EditText or Button attributes without defining them in attr.xml.</p>

```<code>public class CustomEditText extends LinearLayout {

private AppCompatButton mButton;
private AppCompatEditText mEditText;

public CustomEditText(Context context) {
    this(context, null, 0);
}

public CustomEditText(Context context, AttributeSet attrs) {
    this(context, attrs, 0);
}

public CustomEditText(Context context, AttributeSet attrs, int defStyleAttr) {
    super(context, attrs, defStyleAttr);

    setOrientation(HORIZONTAL);

    /** Get Attributes **/

    TypedArray typedArray = context.obtainStyledAttributes(attrs, R.styleable.CustomEditText);

    int lines = typedArray.getInt(R.styleable.CustomEditText_android_lines, 1);
    int gravity = typedArray.getInt(R.styleable.CustomEditText_android_gravity, Gravity.CENTER_VERTICAL);
    int inputType = typedArray.getInt(R.styleable.CustomEditText_android_inputType, InputType.TYPE_CLASS_TEXT);
    int imeOptions = typedArray.getInt(R.styleable.CustomEditText_android_imeOptions, EditorInfo.IME_ACTION_DONE);
    String hint = typedArray.getString(R.styleable.CustomEditText_hint);

    typedArray.recycle();

    /** Construct Button **/

    mButton = new AppCompatButton(context);
    addView(mButton);

    /** Construct EditText **/

    mEditText = new AppCompatEditText(context);
    mEditText.setGravity(gravity);
    mEditText.setHint(hint);
    mEditText.setImeOptions(imeOptions | EditorInfo.IME_FLAG_NO_EXTRACT_UI);
    mEditText.setInputType(inputType | InputType.TYPE_TEXT_FLAG_NO_SUGGESTIONS);
    if (!((inputType & InputType.TYPE_TEXT_FLAG_MULTI_LINE) == InputType.TYPE_TEXT_FLAG_MULTI_LINE
            && lines == 1)) mEditText.setLines(lines);
    addView(mEditText);
}

public AppCompatEditText getEditText() {
    return mEditText;
}

public AppCompatButton getButton() {
    return mButton;
}
}
</code>```

Title: Creating EditText with button

Body:
You can extend LinearLayout or RelativeLayout and add both Button and EditText in the constructor. However, you need to use a getter method to get the EditText or Button. Here is an example. I haven't tested it, but it should give you an idea. Just remember that, if you want to use xml attributes of Button or EditText, you should define them in attr.xml and then get them with TypedArray. Since the object is a LinearLayout, you cannot use EditText or Button attributes without defining them in attr.xml.

public class CustomEditText extends LinearLayout {

private AppCompatButton mButton;
private AppCompatEditText mEditText;

public CustomEditText(Context context) {
    this(context, null, 0);
}

public CustomEditText(Context context, AttributeSet attrs) {
    this(context, attrs, 0);
}

public CustomEditText(Context context, AttributeSet attrs, int defStyleAttr) {
    super(context, attrs, defStyleAttr);

    setOrientation(HORIZONTAL);

    /** Get Attributes **/

    TypedArray typedArray = context.obtainStyledAttributes(attrs, R.styleable.CustomEditText);

    int lines = typedArray.getInt(R.styleable.CustomEditText_android_lines, 1);
    int gravity = typedArray.getInt(R.styleable.CustomEditText_android_gravity, Gravity.CENTER_VERTICAL);
    int inputType = typedArray.getInt(R.styleable.CustomEditText_android_inputType, InputType.TYPE_CLASS_TEXT);
    int imeOptions = typedArray.getInt(R.styleable.CustomEditText_android_imeOptions, EditorInfo.IME_ACTION_DONE);
    String hint = typedArray.getString(R.styleable.CustomEditText_hint);

    typedArray.recycle();

    /** Construct Button **/

    mButton = new AppCompatButton(context);
    addView(mButton);

    /** Construct EditText **/

    mEditText = new AppCompatEditText(context);
    mEditText.setGravity(gravity);
    mEditText.setHint(hint);
    mEditText.setImeOptions(imeOptions | EditorInfo.IME_FLAG_NO_EXTRACT_UI);
    mEditText.setInputType(inputType | InputType.TYPE_TEXT_FLAG_NO_SUGGESTIONS);
    if (!((inputType & InputType.TYPE_TEXT_FLAG_MULTI_LINE) == InputType.TYPE_TEXT_FLAG_MULTI_LINE
            && lines == 1)) mEditText.setLines(lines);
    addView(mEditText);
}

public AppCompatEditText getEditText() {
    return mEditText;
}

public AppCompatButton getButton() {
    return mButton;
}
}


问:
Yii2 postgres error - fe_sendauth: no password supplied
I use Yii2, db connection

```<code>'db' => [
    'class' => 'yii\db\Connection',
    'dsn' => 'pgsql:host=localhost;dbname=data-storage',
    'username' => 'data-storage',
    'password' => '',
    'charset' => 'utf8',
]
</code>```

My database does not have a password. I got an error: SQLSTATE[08006] [7] fe_sendauth: no password supplied.
If I use some password (just fake, as I mentioned I don't have it) I'm getting: password authentication failed for user "data-storage"

In pg_hba.conf I have a record for my domain:

 host all all 172.28.3.70/32 trust

Which works fine for PgAdmin.

答:
try this

```<code>return [
        'class' => 'yii\db\Connection',
        'dsn' => 'pgsql:host=localhost;dbname=db_name',
        'username' => 'db_username',
        'password' => NULL,
        'charset' => 'utf8',
        'schemaMap' => [
          'pgsql'=> [
            'class'=>'yii\db\pgsql\Schema',
            'defaultSchema' => 'public' //specify your schema here
          ]
        ], // PostgreSQL
    ];
</code>```

or remove password.

Body:
I use Yii2, db connection

'db' => [
    'class' => 'yii\db\Connection',
    'dsn' => 'pgsql:host=localhost;dbname=data-storage',
    'username' => 'data-storage',
    'password' => '',
    'charset' => 'utf8',
]

My database does not have a password. I got an error: SQLSTATE[08006] [7] fe_sendauth: no password supplied.
If I use some password (just fake, as I mentioned I don't have it) I'm getting: password authentication failed for user "data-storage"

In pg_hba.conf I have a record for my domain:

 host all all 172.28.3.70/32 trust

Which works fine for PgAdmin.

Body:
try this

return [
        'class' => 'yii\db\Connection',
        'dsn' => 'pgsql:host=localhost;dbname=db_name',
        'username' => 'db_username',
        'password' => NULL,
        'charset' => 'utf8',
        'schemaMap' => [
          'pgsql'=> [
            'class'=>'yii\db\pgsql\Schema',
            'defaultSchema' => 'public' //specify your schema here
          ]
        ], // PostgreSQL
    ];

or remove password.


问:
Getting unique values from excel table
I'm trying to apply these
Getting unique values in Excel by using formulas only

to my table, but as a result i get only 0's

Can anyone help?

Thanks!

答:
This should work:

Place =G1 in L1

Place {=INDEX($G$1:$G$999,MATCH(0,INDEX(COUNTIF($H$1:H1,$G$1:$G$999),0,0),0))} in L2 and copy it down.

Title: Getting unique values from excel table


问:
Center buttons in middle of image
I try to make buttons that will be in the middle of the picture, but the problem is that either those buttons are in the middle of the page or under the picture. Any suggestions how to fix it and what I do wrong? https://jsfiddle.net/m5g16vt7/

* {
  box-sizing: border-box
}

body {
  font-family: Verdana, sans-serif;
  margin: 0
}

imageSlide-container {
  max-width: 1000px;
  position: relative;
  margin: auto;
}

.prev,
.next {
  cursor: pointer;
  position: absolute;
  top: 50%;
  width: auto;
  padding: 16px;
  margin-top: -22px;
  color: pink;
  font-weight: bold;
  font-size: 18px;
  transition: 0.6s ease;
  border-radius: 0 3px 3px 0;
}

.next {
  right: 0;
  border-radius: 3px 0 0 3px;
}

.prev:hover,
.next:hover {
  background-color: rgba(0, 0, 0, 0.8)
}

@media only screen and (max-width: 300px) {
  .prev,
  .next,
  .text {
    font-size: 11px
  }
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="imageSlide-container">
  <img class="imageSlide" src="img_nature_wide.jpg" style="width: 100%">

  ❮
  ❯
</div></code>```

答:
You missed a dot in the css:</p>

```<code>.imageSlide-container {
     max-width: 1000px;
     position: relative;
     margin: auto;
 }
</code>```

Title: Center buttons in middle of image

Body:
I try to make buttons that will be in the middle of the picture, but the problem is that either those buttons are in the middle of the page or under the picture. Any suggestions how to fix it and what I do wrong? https://jsfiddle.net/m5g16vt7/

* {
  box-sizing: border-box
}

body {
  font-family: Verdana, sans-serif;
  margin: 0
}

imageSlide-container {
  max-width: 1000px;
  position: relative;
  margin: auto;
}

.prev,
.next {
  cursor: pointer;
  position: absolute;
  top: 50%;
  width: auto;
  padding: 16px;
  margin-top: -22px;
  color: pink;
  font-weight: bold;
  font-size: 18px;
  transition: 0.6s ease;
  border-radius: 0 3px 3px 0;
}

.next {
  right: 0;
  border-radius: 3px 0 0 3px;
}

.prev:hover,
.next:hover {
  background-color: rgba(0, 0, 0, 0.8)
}

@media only screen and (max-width: 300px) {
  .prev,
  .next,
  .text {
    font-size: 11px
  }
}

  ❮
  ❯

Body:
You missed a dot in the css:

.imageSlide-container {
     max-width: 1000px;
     position: relative;
     margin: auto;
 }


问:
How to invoke method from one component to another component in Angular 2?
I have two different component - one component has click event method for the list users & I want to inherit(invoke) that click event method on detail page(another component) )

How to do that, Please help me...

ANSWER UPDATE

Thanks For your Answers.

I have got the solution by Using extend Class & using super() in constructor.

First Class

```<code>export class TeamsView {
   constructor(private test:TestService){
   }
   ...
}
</code>```

Second Class

```<code>export class TeamsForm extends TeamsView {
   constructor(private test:TestService, private router: Router){
     super(test)
   }
   ...
}
</code>```

答:
1. Invoking method from one component to another component (if they are not parent and child), can only be possible using services.

```<code>    //FirstComponent

    import {Component} from '@angular/core';
    import {CommonService} from './common.service';

    @Component({
      selector: '<first-component></first-component>',
      template: 'some html here',
      providers: [CommonService]
    })

    export class FirstComponent {
      constructor(private _service: CommonService) {
       this._service.callMethodOfSecondComponent();
      }

    }

    //CommonService

    import {Subject} from 'rxjs/Subject';

    @Injectable()
    export class CommonService {
      invokeEvent: Subject<any> = new Subject();

      callMethodOfSecondComponent() {
        this.invokeEvent.next(someValue)
      }
    }

     //SecondComponent

    import {Component, OnInit} from '@angular/core';
    import {CommonService} from './common.service';

    @Component({
      selector: '<second-component></second-component>',
      template: 'some html here',
      providers: [CommonService]
    })

    export class SecondComponent {
      constructor(private _service: CommonService) {
       this._service.invokeEvent.subscribe(value => {
        if(value === 'someVal'){
         this.callMyMethod();
       }
      });
      }

      callMyMethod(){
      //code block to run
      }
    }
</code>```

  2. Invoking method of parent component from child component

```<code>    //Child Component

    import {Component} from '@angular/core';
    @Component({
      selector: '<child-component></child-component>',
      template: 'some html here',
    })

    export class ChildComponent {
      @Output()
      emitFunctionOfParent: EventEmitter<any> = new EventEmitter<any>();
      constructor() {
      }

      someMethodOfChildComponent(){
       this.emitFunctionOfParent.emit(someValue);
      }

    }

    //ParentComponent

    import {Component} from '@angular/core';
    @Component({
      selector: '<parent-component></parent-component>',
      template: `some html
                <child-component
                (emitFunctionOfParent)="myMethod($event)">
                 </child-component>
                 some html
                `,
    })

    export class ParentComponent {
      constructor() {
      }

      myMethod(someValue){
      // i am called
      }

    }
</code>```

  3. Invoking method of child component from parent component

```<code>//Child Component

    import {Component} from '@angular/core';
    @Component({
      selector: '<child-component></child-component>',
      template: 'some html here',
    })

    export class ChildComponent {

      constructor() {
      }

      someMethodOfChildComponentToBeCalled(){
       // i am called
      }

    }

//Parent Component

    import {Component, OnInit} from '@angular/core';
    import {ChildComponent} from './child.component';
    @Component({
      selector: '<parent-component></parent-component>',
       template: `some html
                <child-component>
                 </child-component>
                 some html
                `
    })

    export class ParentComponent implements OnInit {
      @ViewChild(ChildComponent) private _child:
      ChildComponent;

      ngOnInit() {
      this._child.someMethodOfChildComponentToBeCalled();
      }

    }
</code>```

There might be other ways for communication as well except these ones. :)

Body:
I have two different component - one component has click event method for the list users & I want to inherit(invoke) that click event method on detail page(another component) )

How to do that, Please help me...

ANSWER UPDATE

Thanks For your Answers.

I have got the solution by Using extend Class & using super() in constructor.

First Class

export class TeamsView {
   constructor(private test:TestService){
   }
   ...
}

Second Class

export class TeamsForm extends TeamsView {
   constructor(private test:TestService, private router: Router){
     super(test)
   }
   ...
}

Body:
1. Invoking method from one component to another component (if they are not parent and child), can only be possible using services.

    //FirstComponent

    import {Component} from '@angular/core';
    import {CommonService} from './common.service';

    @Component({
      selector: '<first-component></first-component>',
      template: 'some html here',
      providers: [CommonService]
    })

    export class FirstComponent {
      constructor(private _service: CommonService) {
       this._service.callMethodOfSecondComponent();
      }

    }

    //CommonService

    import {Subject} from 'rxjs/Subject';

    @Injectable()
    export class CommonService {
      invokeEvent: Subject<any> = new Subject();

      callMethodOfSecondComponent() {
        this.invokeEvent.next(someValue)
      }
    }

     //SecondComponent

    import {Component, OnInit} from '@angular/core';
    import {CommonService} from './common.service';

    @Component({
      selector: '<second-component></second-component>',
      template: 'some html here',
      providers: [CommonService]
    })

    export class SecondComponent {
      constructor(private _service: CommonService) {
       this._service.invokeEvent.subscribe(value => {
        if(value === 'someVal'){
         this.callMyMethod();
       }
      });
      }

      callMyMethod(){
      //code block to run
      }
    }

  2. Invoking method of parent component from child component

    //Child Component

    import {Component} from '@angular/core';
    @Component({
      selector: '<child-component></child-component>',
      template: 'some html here',
    })

    export class ChildComponent {
      @Output()
      emitFunctionOfParent: EventEmitter<any> = new EventEmitter<any>();
      constructor() {
      }

      someMethodOfChildComponent(){
       this.emitFunctionOfParent.emit(someValue);
      }

    }

    //ParentComponent

    import {Component} from '@angular/core';
    @Component({
      selector: '<parent-component></parent-component>',
      template: `some html
                <child-component
                (emitFunctionOfParent)="myMethod($event)">
                 </child-component>
                 some html
                `,
    })

    export class ParentComponent {
      constructor() {
      }

      myMethod(someValue){
      // i am called
      }

    }

  3. Invoking method of child component from parent component

//Child Component

    import {Component} from '@angular/core';
    @Component({
      selector: '<child-component></child-component>',
      template: 'some html here',
    })

    export class ChildComponent {

      constructor() {
      }

      someMethodOfChildComponentToBeCalled(){
       // i am called
      }

    }

//Parent Component

    import {Component, OnInit} from '@angular/core';
    import {ChildComponent} from './child.component';
    @Component({
      selector: '<parent-component></parent-component>',
       template: `some html
                <child-component>
                 </child-component>
                 some html
                `
    })

    export class ParentComponent implements OnInit {
      @ViewChild(ChildComponent) private _child:
      ChildComponent;

      ngOnInit() {
      this._child.someMethodOfChildComponentToBeCalled();
      }

    }

There might be other ways for communication as well except these ones. :)


问:
Complete turn x angle values are mapped to half turn using asin function, how to mirror them back?
I have angles that form a complete turn in an array x, from -90 to 270 e.g. (it may be defined otherwise, like from 0 to 360 or -180 to 180) with step 1 or whatever.

asin function is valid only between -90 and +90.

Thus, angles < -90 or > 90 would be "mapped" between these values.

E.g. y = some_asin_func(over_sin(x)) will end up in an y value that is always between -90 and +90. So y is stuck between -90 and +90.

I do need to retrieve to which x-input is y related, because it's ambiguous yet: for example, the function over (x) will give the same y values for x = 120 and x = 60, or x = -47 and x = 223. Which is not what I want.

Put an other way; I need y making a complete turn as x does, ranging from where x starts up to where x ends.

An image will be better:

Here, x ranges between -90 (left) to 270 (right of the graph).

The valid part of the curve is between x=-90 and x=+90 (left half of the graph).

All other values are like mirrored about y=90 or y=-90.

For x=180 for example, I got y=0 and it should be y=180.

For x=270, I have y=-90 but it should be y=270, thus +360.

Here's a code sample:

```<code>A   = 50 # you can make this value vary to have different curves like in the images, when A=0 -> shape is triangle-like, when A=90-> shape is square-like.
x   = np.linspace(-90,270,int(1e3))
u   = np.sin(math.pi*A/180)*np.cos(math.pi*x/180)
v   = 180*(np.arcsin(u))/math.pi
y   = 180*np.arcsin(np.sin(math.pi*x/180)/np.cos(math.pi*v/180))/math.pi
plt.plot(x,y)
plt.grid(True)
</code>```

Once again, first left half of the graph is completely correct.
The right half is also correct in its behavior, but in final, here, it must be mirrored about an horizontal axis at position y=+90 when x>90, like this:

That is, it's like the function is mirrored about y=-90 and y=+90 for y where x is out of the range [-90,+90] and only where where x is out of the range [-90,+90].

I want to un-mirror it outside the valid [-90,+90] range:

 about y=-90 where y is lower than -90

 about y=+90 where y is greater than +90

And of course, modulo each complete turn.

Here an other example where x ranges from -180 to 180 and the desired behavior:

Yet:

Wanted:

I have first tested some simple thing up now:

```<code>A = 50
x = np.linspace(-180,180,int(1e3))
u = np.sin(math.pi*A/180)*np.cos(math.pi*x/180)
v = 180*(np.arcsin(u))/math.pi
y = 180*np.arcsin(np.sin(math.pi*x/180)/np.cos(math.pi*v/180))/math.pi
for i,j in np.ndenumerate(x):
    xval = (j-180)%180-180
    if (xval < -90):
        y[i] = y[i]-val
    elif (xval > 90):
        y[i] = y[i]+val

plt.plot(x,y);
plt.grid(True)
plt.show()
</code>```

which doesn't work at all but I think the background idea is there...

I guess it may be some kind of modulo trick but can't figure it out.

答:
Thank you @Thomas Kühn, it seems fine except I wanted to restrict the function in a single same turn in respect to y-values. Anyway, it's only aesthetics.

Here's what I found by my side. It's maybe not perfect but it works:

```<code>A = 50
u = np.sin(math.pi*A/180)*np.cos(math.pi*x/180)
v = 180*(np.arcsin(u))/math.pi
y = 180*np.arcsin(np.sin(math.pi*x/180)/np.cos(math.pi*v/180))/math.pi
for i,j in np.ndenumerate(x):
    val = (j-180)%360-180
    if (val < -90):
        y[i] = -180-y[i]
    elif (val > 90):
        y[i] = 180-y[i]
</code>```

Here are some expected results:

Range from -180 to +180

Range from 0 to +360

Range from -720 to +720

Range from -360 to +360 with some different A values.

Funny thing is that it reminds me some electronics diagrams as well.

Periodic phenomenons are everywhere!

Body:
I have angles that form a complete turn in an array x, from -90 to 270 e.g. (it may be defined otherwise, like from 0 to 360 or -180 to 180) with step 1 or whatever.

asin function is valid only between -90 and +90.

Thus, angles < -90 or > 90 would be "mapped" between these values.

E.g. y = some_asin_func(over_sin(x)) will end up in an y value that is always between -90 and +90. So y is stuck between -90 and +90.

I do need to retrieve to which x-input is y related, because it's ambiguous yet: for example, the function over (x) will give the same y values for x = 120 and x = 60, or x = -47 and x = 223. Which is not what I want.

Put an other way; I need y making a complete turn as x does, ranging from where x starts up to where x ends.

An image will be better:

Here, x ranges between -90 (left) to 270 (right of the graph).

The valid part of the curve is between x=-90 and x=+90 (left half of the graph).

All other values are like mirrored about y=90 or y=-90.

For x=180 for example, I got y=0 and it should be y=180.

For x=270, I have y=-90 but it should be y=270, thus +360.

Here's a code sample:

A   = 50 # you can make this value vary to have different curves like in the images, when A=0 -> shape is triangle-like, when A=90-> shape is square-like.
x   = np.linspace(-90,270,int(1e3))
u   = np.sin(math.pi*A/180)*np.cos(math.pi*x/180)
v   = 180*(np.arcsin(u))/math.pi
y   = 180*np.arcsin(np.sin(math.pi*x/180)/np.cos(math.pi*v/180))/math.pi
plt.plot(x,y)
plt.grid(True)

Once again, first left half of the graph is completely correct.
The right half is also correct in its behavior, but in final, here, it must be mirrored about an horizontal axis at position y=+90 when x>90, like this:

That is, it's like the function is mirrored about y=-90 and y=+90 for y where x is out of the range [-90,+90] and only where where x is out of the range [-90,+90].

I want to un-mirror it outside the valid [-90,+90] range:

 about y=-90 where y is lower than -90

 about y=+90 where y is greater than +90

And of course, modulo each complete turn.

Here an other example where x ranges from -180 to 180 and the desired behavior:

Yet:

Wanted:

I have first tested some simple thing up now:

A = 50
x = np.linspace(-180,180,int(1e3))
u = np.sin(math.pi*A/180)*np.cos(math.pi*x/180)
v = 180*(np.arcsin(u))/math.pi
y = 180*np.arcsin(np.sin(math.pi*x/180)/np.cos(math.pi*v/180))/math.pi
for i,j in np.ndenumerate(x):
    xval = (j-180)%180-180
    if (xval < -90):
        y[i] = y[i]-val
    elif (xval > 90):
        y[i] = y[i]+val

plt.plot(x,y);
plt.grid(True)
plt.show()

which doesn't work at all but I think the background idea is there...

I guess it may be some kind of modulo trick but can't figure it out.

Body:
Thank you @Thomas Kühn, it seems fine except I wanted to restrict the function in a single same turn in respect to y-values. Anyway, it's only aesthetics.

Here's what I found by my side. It's maybe not perfect but it works:

A = 50
u = np.sin(math.pi*A/180)*np.cos(math.pi*x/180)
v = 180*(np.arcsin(u))/math.pi
y = 180*np.arcsin(np.sin(math.pi*x/180)/np.cos(math.pi*v/180))/math.pi
for i,j in np.ndenumerate(x):
    val = (j-180)%360-180
    if (val < -90):
        y[i] = -180-y[i]
    elif (val > 90):
        y[i] = 180-y[i]

Here are some expected results:

Range from -180 to +180

Range from 0 to +360

Range from -720 to +720

Range from -360 to +360 with some different A values.

Funny thing is that it reminds me some electronics diagrams as well.

Periodic phenomenons are everywhere!


问:
Java Swing close ONLY one application
Hi all:
I have a Java Swing App. There is a button allow user to create open up a new window of the application. I use System.Exit(0) when user decides to close the application, however when I press "Close" button, both Application windows closed.

```<code>public static void main(String[] args)
{
 ghMain = new GreenHouseMain();
}
</code>```

Above is how I initialize the first application, then use the same code to create new GreenHouseMain Object to open second application window.

So my question is how do I close only one application window which the close button I pressed from?

Thanks all

答: read the javadocs for setDefaultCloseOperation. System.exit() is doing exactly what it's supposed to, so get rid of it.

Title: Java Swing close ONLY one application

Body:
Hi all:
I have a Java Swing App. There is a button allow user to create open up a new window of the application. I use System.Exit(0) when user decides to close the application, however when I press "Close" button, both Application windows closed.

public static void main(String[] args)
{
 ghMain = new GreenHouseMain();
}

Above is how I initialize the first application, then use the same code to create new GreenHouseMain Object to open second application window.

So my question is how do I close only one application window which the close button I pressed from?

Thanks all