问:
Angular's link function vs Angular 2's constructor
Being new to Angular2, and its component architecture, I could understand that, Components are enhanced version of Angular's directives.

And when I look at the constructor which pertains to a particular I component that I tend to write, It more or less does the same work which the link function use to perform in Angular 1.x since the link function gets executed for each instance of directive so that each instance gets it’s own business-logic without affecting others.

Is my understanding correct?

答:
While the constructor function of an Angular 2 Component and the link function of an AngularJS directive are called at similar times (During creation) I would not go as far as to say that they are conceptually the same.  A notable difference would be that within a link function of an AngularJS directive the HTML Element represented by the directive has already been created while in the constructor function of an Angular 2 component it has not.

As @Venomy has explained, ngOnInit is a better analogy to a link function as both are features of the framework.


来源: stackexchange

问:
argument of type "x" is incompatible with parameter of type x
There is a union:

```<code>typedef union {
    RF_CmdHandle ch;
    uint16_t     availRatCh;
    bool         bRadioState;
    void         *pScheduleMap;
} RF_InfoVal;
</code>```

which is used by a function:

```<code>RF_Stat RF_getInfo(RF_Handle h, RF_InfoType type, RF_InfoVal *pValue)
</code>```

My variables are as following:

```<code>RF_handle handle;
RF_InfoType infoType = 0;
RF_InfoVal info;
</code>```

when I use the function like this:

```<code>RF_Stat status =  RF_getInfo(handle, infoType, info);
</code>```

I get the following error:

```<code>argument of type "RF_InfoVal" is incompatible with parameter of type RF_InfoVal.
</code>```

I would be very happy about an explanation what I'm doing wrong here.

答:
What you're doing wrong is that you aren't paying attention to what you're reading. Punctuation matters. RF_InfoVal and RF_InfoVal* are not the same thing. The first is a union, the second is a pointer to a union.

The error message that you retranscribed had a *. That * is important.

Here we can figure out that you made a mistake when retranscribing the error message — but that's because the mistake you made there is the same mistake that you made in your code. You should never retranscribe an error message. Always copy-paste. The same goes for your code: always copy-paste a full piece of code that reproduces the problem.

ContentLicense: CC BY-SA 3.0

Body:
There is a union:

typedef union {
    RF_CmdHandle ch;
    uint16_t     availRatCh;
    bool         bRadioState;
    void         *pScheduleMap;
} RF_InfoVal;

which is used by a function:

RF_Stat RF_getInfo(RF_Handle h, RF_InfoType type, RF_InfoVal *pValue)

My variables are as following:

RF_handle handle;
RF_InfoType infoType = 0;
RF_InfoVal info;

when I use the function like this:

RF_Stat status =  RF_getInfo(handle, infoType, info);

I get the following error:

argument of type "RF_InfoVal" is incompatible with parameter of type RF_InfoVal.

I would be very happy about an explanation what I'm doing wrong here.


问:
Electron : Wrote new app to release-builds : Is this successful ? What happens next?
I apologize for my ignorance, but not sure how I execute my packaged project.

Here is outcome:

```<code>harry@debian:/usr/lib/node_modules$ electron-packager --electron-version=1.7.9 . /home/harry/sound/SickBayScanner --overwrite  --platform=linux --arch=x64 --DEBUG=* --icon=assets/icons/png/1024x1024.png --prune=true --out=release-builds
</code>```

Packaging app for platform linux x64 using electron v1.7.9

Wrote new app to release-builds/-home-harry-sound-SickBayScanner-linux-x64

How do you execute the build ?

答:
If you go to the release-builds/-home-harry-sound-SickBayScanner-linux-x64 folder you will see lots of files one of which is an executable that you can run.

It's annoying to have to give the whole folder to everyone who uses it but I haven't found a good way to compress it into one file, I've tried things like electron-installer-debian and it would generate a .deb file but it wouldn't install.

Body:
I apologize for my ignorance, but not sure how I execute my packaged project.

Here is outcome:

harry@debian:/usr/lib/node_modules$ electron-packager --electron-version=1.7.9 . /home/harry/sound/SickBayScanner --overwrite  --platform=linux --arch=x64 --DEBUG=* --icon=assets/icons/png/1024x1024.png --prune=true --out=release-builds

Packaging app for platform linux x64 using electron v1.7.9

Wrote new app to release-builds/-home-harry-sound-SickBayScanner-linux-x64

How do you execute the build ?


问:
want to separate frontend and backend user in yii2
as there is only user table in yii2 advanced. so user can login to both frontend and backend with same credential . we want saperate it out.

so I created frontuser table ,with same structure as of user table.
then created its model using gii model generator

made it as common model/user.

here is frontend/model/frontuser

```<code><?php

namespace frontend\models;

use Yii;
use yii\base\NotSupportedException;
use yii\behaviors\TimestampBehavior;
use yii\db\ActiveRecord;
use yii\web\IdentityInterface;

/**
 * This is the model class for table "frontuser".
 *
 * @property integer $id
 * @property string $username
 * @property string $auth_key
 * @property string $password_hash
 * @property string $password_reset_token
 * @property string $email
 * @property integer $status
 * @property integer $created_at
 * @property integer $updated_at
 */
//class Frontuser extends \yii\db\ActiveRecord
class Frontuser extends ActiveRecord implements IdentityInterface
{
    /**
     * @inheritdoc
     */
    const STATUS_DELETED = 0;
    const STATUS_ACTIVE = 10;
    public static function tableName()
    {
       return '{{%frontuser}}';
    }

    /**
     * @inheritdoc
     */
    public function rules()
    {
       return [
            ['status', 'default', 'value' => self::STATUS_ACTIVE],
            ['status', 'in', 'range' => [self::STATUS_ACTIVE, self::STATUS_DELETED]],
        ];
    }

    /**
     *  inheritdoc
     */
    public static function findIdentity($id)
    {
        return static::findOne(['id' => $id, 'status' => self::STATUS_ACTIVE]);
    }

    /**
     * @inheritdoc
     */
    public static function findIdentityByAccessToken($token, $type = null)
    {
        throw new NotSupportedException('"findIdentityByAccessToken" is not implemented.');
    }

    /**
     * Finds user by username
     *
     * @param string $username
     * @return static|null
     */
    public static function findByUsername($username)
    {
        return static::findOne(['username' => $username, 'status' => self::STATUS_ACTIVE]);
    }

    /**
     * Finds user by password reset token
     *
     * @param string $token password reset token
     * @return static|null
     */
    public static function findByPasswordResetToken($token)
    {
        if (!static::isPasswordResetTokenValid($token)) {
            return null;
        }

        return static::findOne([
            'password_reset_token' => $token,
            'status' => self::STATUS_ACTIVE,
        ]);
    }

    /**
     * Finds out if password reset token is valid
     *
     * @param string $token password reset token
     * @return bool
     */
    public static function isPasswordResetTokenValid($token)
    {
        if (empty($token)) {
            return false;
        }

        $timestamp = (int) substr($token, strrpos($token, '_') + 1);
        $expire = Yii::$app->params['user.passwordResetTokenExpire'];
        return $timestamp + $expire >= time();
    }

    /**
     * @inheritdoc
     */
    public function getId()
    {
        return $this->getPrimaryKey();
    }

    /**
     * @inheritdoc
     */
    public function getAuthKey()
    {
        return $this->auth_key;
    }

    /**
     * @inheritdoc
     */
    public function validateAuthKey($authKey)
    {
        return $this->getAuthKey() === $authKey;
    }

    /**
     * Validates password
     *
     * @param string $password password to validate
     * @return bool if password provided is valid for current user
     */
    public function validatePassword($password)
    {
        return Yii::$app->security->validatePassword($password, $this->password_hash);
    }

    /**
     * Generates password hash from password and sets it to the model
     *
     * @param string $password
     */
    public function setPassword($password)
    {
        $this->password_hash = Yii::$app->security->generatePasswordHash($password);
    }

    /**
     * Generates "remember me" authentication key
     */
    public function generateAuthKey()
    {
        $this->auth_key = Yii::$app->security->generateRandomString();
    }

    /**
     * Generates new password reset token
     */
    public function generatePasswordResetToken()
    {
        $this->password_reset_token = Yii::$app->security->generateRandomString() . '_' . time();
    }

    /**
     * Removes password reset token
     */
    public function removePasswordResetToken()
    {
        $this->password_reset_token = null;
    }
}
</code>```

and in frontend/config/main.php

```<code><?php
$params = array_merge(
    require(__DIR__ . '/../../common/config/params.php'),
    require(__DIR__ . '/../../common/config/params-local.php'),
    require(__DIR__ . '/params.php'),
    require(__DIR__ . '/params-local.php')
);

return [
    'id' => 'app-frontend',
    'basePath' => dirname(__DIR__),
    'bootstrap' => ['log'],
    'controllerNamespace' => 'frontend\controllers',
    'components' => [
        'request' => [
            'csrfParam' => '_csrf-frontend',
        ],
        // 'user' => [
        //     'identityClass' => 'common\models\User',
        //     'enableAutoLogin' => true,
        //     'identityCookie' => ['name' => '_identity-frontend', 'httpOnly' => true],
        // ],
        'user' => [
                'class' => 'yii\web\User', // basic class
                'identityClass' => 'frontend\models\Frontuser', // your admin model
                'enableAutoLogin' => true,
                'loginUrl' => '/admin/frontend/login',
            ],
        'session' => [
            // this is the name of the session cookie used for login on the frontend
            'name' => 'advanced-frontend',
        ],
        'log' => [
            'traceLevel' => YII_DEBUG ? 3 : 0,
            'targets' => [
                [
                    'class' => 'yii\log\FileTarget',
                    'levels' => ['error', 'warning'],
                ],
            ],
        ],
        'authManager' => [
            'class' => 'yii\rbac\DbManager', // or use 'yii\rbac\DbManager'
            'defaultRoles'=> ['guest'],
            ],
        'errorHandler' => [
            'errorAction' => 'site/error',
        ],
        /*
        'urlManager' => [
            'enablePrettyUrl' => true,
            'showScriptName' => false,
            'rules' => [
            ],
        ],
        */
    ],
    'params' => $params,
];
</code>```

but still ,I sign up ,entry goes in user table ..
I want to use user table for backend user
and frontuser table for frontend user
how to do it?

答:
you can put below code in forntend/config/main.php under components

```<code>'user' => [
                        'identityClass' => 'common\models\User',
                        'enableAutoLogin' => true ,
                        'identityCookie' => [
                                'name' => '_frontendUser', // unique for frontend
                                'path'=>'/frontend/web'  // correct path for the frontend app.
                        ]
                ],
</code>```

you can put below code in backend/config/main.php under components

```<code> 'admin' => [
            'identityClass' => 'app\models\adminUsers',
            'enableAutoLogin' => true,
                'identityCookie' => [
                        'name' => '_backendUser', // unique for backend
                        'path' => '/advanced/backend/web' // correct path for backend app.
                ]
        ],
</code>```

you can copy common user identityClass and change that name to adminUsers and paste this file in backend models.

you can get user session data for frontend LIKE Yii::$app->user->identity->id
you can get user session data for frontend LIKE Yii::$app->admin->identity->id

Body:
as there is only user table in yii2 advanced. so user can login to both frontend and backend with same credential . we want saperate it out.

so I created frontuser table ,with same structure as of user table.
then created its model using gii model generator

made it as common model/user.

here is frontend/model/frontuser

<?php

namespace frontend\models;

use Yii;
use yii\base\NotSupportedException;
use yii\behaviors\TimestampBehavior;
use yii\db\ActiveRecord;
use yii\web\IdentityInterface;

/**
 * This is the model class for table "frontuser".
 *
 * @property integer $id
 * @property string $username
 * @property string $auth_key
 * @property string $password_hash
 * @property string $password_reset_token
 * @property string $email
 * @property integer $status
 * @property integer $created_at
 * @property integer $updated_at
 */
//class Frontuser extends \yii\db\ActiveRecord
class Frontuser extends ActiveRecord implements IdentityInterface
{
    /**
     * @inheritdoc
     */
    const STATUS_DELETED = 0;
    const STATUS_ACTIVE = 10;
    public static function tableName()
    {
       return '{{%frontuser}}';
    }

    /**
     * @inheritdoc
     */
    public function rules()
    {
       return [
            ['status', 'default', 'value' => self::STATUS_ACTIVE],
            ['status', 'in', 'range' => [self::STATUS_ACTIVE, self::STATUS_DELETED]],
        ];
    }

    /**
     *  inheritdoc
     */
    public static function findIdentity($id)
    {
        return static::findOne(['id' => $id, 'status' => self::STATUS_ACTIVE]);
    }

    /**
     * @inheritdoc
     */
    public static function findIdentityByAccessToken($token, $type = null)
    {
        throw new NotSupportedException('"findIdentityByAccessToken" is not implemented.');
    }

    /**
     * Finds user by username
     *
     * @param string $username
     * @return static|null
     */
    public static function findByUsername($username)
    {
        return static::findOne(['username' => $username, 'status' => self::STATUS_ACTIVE]);
    }

    /**
     * Finds user by password reset token
     *
     * @param string $token password reset token
     * @return static|null
     */
    public static function findByPasswordResetToken($token)
    {
        if (!static::isPasswordResetTokenValid($token)) {
            return null;
        }

        return static::findOne([
            'password_reset_token' => $token,
            'status' => self::STATUS_ACTIVE,
        ]);
    }

    /**
     * Finds out if password reset token is valid
     *
     * @param string $token password reset token
     * @return bool
     */
    public static function isPasswordResetTokenValid($token)
    {
        if (empty($token)) {
            return false;
        }

        $timestamp = (int) substr($token, strrpos($token, '_') + 1);
        $expire = Yii::$app->params['user.passwordResetTokenExpire'];
        return $timestamp + $expire >= time();
    }

    /**
     * @inheritdoc
     */
    public function getId()
    {
        return $this->getPrimaryKey();
    }

    /**
     * @inheritdoc
     */
    public function getAuthKey()
    {
        return $this->auth_key;
    }

    /**
     * @inheritdoc
     */
    public function validateAuthKey($authKey)
    {
        return $this->getAuthKey() === $authKey;
    }

    /**
     * Validates password
     *
     * @param string $password password to validate
     * @return bool if password provided is valid for current user
     */
    public function validatePassword($password)
    {
        return Yii::$app->security->validatePassword($password, $this->password_hash);
    }

    /**
     * Generates password hash from password and sets it to the model
     *
     * @param string $password
     */
    public function setPassword($password)
    {
        $this->password_hash = Yii::$app->security->generatePasswordHash($password);
    }

    /**
     * Generates "remember me" authentication key
     */
    public function generateAuthKey()
    {
        $this->auth_key = Yii::$app->security->generateRandomString();
    }

    /**
     * Generates new password reset token
     */
    public function generatePasswordResetToken()
    {
        $this->password_reset_token = Yii::$app->security->generateRandomString() . '_' . time();
    }

    /**
     * Removes password reset token
     */
    public function removePasswordResetToken()
    {
        $this->password_reset_token = null;
    }
}

and in frontend/config/main.php

<?php
$params = array_merge(
    require(__DIR__ . '/../../common/config/params.php'),
    require(__DIR__ . '/../../common/config/params-local.php'),
    require(__DIR__ . '/params.php'),
    require(__DIR__ . '/params-local.php')
);

return [
    'id' => 'app-frontend',
    'basePath' => dirname(__DIR__),
    'bootstrap' => ['log'],
    'controllerNamespace' => 'frontend\controllers',
    'components' => [
        'request' => [
            'csrfParam' => '_csrf-frontend',
        ],
        // 'user' => [
        //     'identityClass' => 'common\models\User',
        //     'enableAutoLogin' => true,
        //     'identityCookie' => ['name' => '_identity-frontend', 'httpOnly' => true],
        // ],
        'user' => [
                'class' => 'yii\web\User', // basic class
                'identityClass' => 'frontend\models\Frontuser', // your admin model
                'enableAutoLogin' => true,
                'loginUrl' => '/admin/frontend/login',
            ],
        'session' => [
            // this is the name of the session cookie used for login on the frontend
            'name' => 'advanced-frontend',
        ],
        'log' => [
            'traceLevel' => YII_DEBUG ? 3 : 0,
            'targets' => [
                [
                    'class' => 'yii\log\FileTarget',
                    'levels' => ['error', 'warning'],
                ],
            ],
        ],
        'authManager' => [
            'class' => 'yii\rbac\DbManager', // or use 'yii\rbac\DbManager'
            'defaultRoles'=> ['guest'],
            ],
        'errorHandler' => [
            'errorAction' => 'site/error',
        ],
        /*
        'urlManager' => [
            'enablePrettyUrl' => true,
            'showScriptName' => false,
            'rules' => [
            ],
        ],
        */
    ],
    'params' => $params,
];

but still ,I sign up ,entry goes in user table ..
I want to use user table for backend user
and frontuser table for frontend user
how to do it?

Body:
you can put below code in forntend/config/main.php under components

'user' => [
                        'identityClass' => 'common\models\User',
                        'enableAutoLogin' => true ,
                        'identityCookie' => [
                                'name' => '_frontendUser', // unique for frontend
                                'path'=>'/frontend/web'  // correct path for the frontend app.
                        ]
                ],

you can put below code in backend/config/main.php under components

 'admin' => [
            'identityClass' => 'app\models\adminUsers',
            'enableAutoLogin' => true,
                'identityCookie' => [
                        'name' => '_backendUser', // unique for backend
                        'path' => '/advanced/backend/web' // correct path for backend app.
                ]
        ],

you can copy common user identityClass and change that name to adminUsers and paste this file in backend models.

you can get user session data for frontend LIKE Yii::$app->user->identity->id
you can get user session data for frontend LIKE Yii::$app->admin->identity->id


问:
Using custom font for entire iOS app swift
I know that to set a custom font of an element on the screen I can simply dosomeLabel.font=UIFont(name: "Exo 2.0", size: 15).

I was wondering how one could set it for an entire app using swift. (A hack would be to do what I know for every single element of the app but that is just going to be a maintainability nightmare)

I see that this question has already been asked with an objective-C tag, How to set a custom font for entire iOS app without specifying size but I'm not familiar enough with objective-C enough to port the code to swift

答:
I found out a way to do same in Swift 4 with iOS 11

Only need to add @objc keyword before variable name.
So variable declaration will be like this

```<code>@objc public var substituteFontName : String {
    get {}
    set {}
}
</code>```

Hope this helps others who are facing this issue.

Body:
I found out a way to do same in Swift 4 with iOS 11

Only need to add @objc keyword before variable name.
So variable declaration will be like this

@objc public var substituteFontName : String {
    get {}
    set {}
}

Hope this helps others who are facing this issue.


问:
Video training program
I am looking to create a video training program which records videos - via webcam, user screen capture and captures sound. Now the main problem is that I need a cross-platform (mac and windows) solutions.

I know its possible to use flash to record webcam + audio. But its not possible to record the user's screen via flash.

So am wonder if I should use Java (which i believe will work on mac & windows). I do not want to develop to separate versions because of the cost involved in developing two versions.

Please guide me as I am new to this.

Thank you.

UPDATE

Hello again,

I had a look at the following site: www.screencast-o-matic.com or www.screentoaster.com. I see that they have developed a java applet which helps interact with Windows/Mac to record the screen.

I am wondering how to go about developing something like that and integrating it with Flash (for webcam and audio recording).

Is this a better idea?

答:
This is not an answer to your question, but I strongly recommend against using video for educational programmes.  Our company delivers university courses on-line, and we long ago learned that video feeds are only effective under particular scenarios.  In general, a talking head is a waste of bandwidth.  You're much better off to put together a well designed powerpoint presentation, record a voice-over (and edit it!) and then assemble the whole thing as a flash presentation.  This is a non-trivial amount of work, but it provides a much more interesting product for the student.

When to use video:
1) When you are demonstrating something dynamic - Mechanics or Chemistry for example.
2) When you are acting out a scenario or case as an illustration -- For example, threat de-escalation techniques for high school teachers.

When you solve the screen recording problem, seriously consider whether you need full motion or if you can get away with stills.  Often the motion is distracting, and a still with good voice over can be more effective.   (Hint: Replace mouse pointers with something HUGE before recording -- Like Fox did with hockey pucks)

OwnerDisplayName: Alec Smart

ContentLicense: CC BY-SA 2.5

Title: Video training program

LastEditorDisplayName: Alec Smart

OwnerDisplayName: chris


问:
Orchard How can I style the summary of list items different in a page versus a widget
I am new to the orchard project, and have not been able to track down how this could be done (assuming its possible).

I have a data list called "Events" in which I have attached a list of custom data type objects which are of type "Event".  I then have put a view of this list in a widget on my homepage - as well as displayed the list view page by adding it to my main menu.

I have found the information to update the summary of these list items by adding the proper view
for example adding the following view:

\Themes\PeaceCamp\Views\Items\Content-Event.Summary.cshtml

```<code><div class="event">
<b>@Model.Title</b><br />
</div>
</code>```

however this seems to update the view in the widget, as well as in the list view page.  Since pagination only affects the page view - I presume there is a way to summarize them different in the two different areas - hoping someone could explain or direct me to the proper location to do that - Thanks!

My solution is all local at this time, so I cannot provide links as examples - and the only thing not done in the CMS would be the view added above.

答:
You could add your own IShapeTableProvider (the stuff you describe comes from the Shapes class in Orchard.Core.Contents) that walks up the shape tree to find a parent zone and adds alternates accordingly.
This post might give you some ideas on how to do that:
http://weblogs.asp.net/bleroy/archive/2011/01/10/orchard-shapeshifting.aspx</p>

Body:
I am new to the orchard project, and have not been able to track down how this could be done (assuming its possible).

I have a data list called "Events" in which I have attached a list of custom data type objects which are of type "Event".  I then have put a view of this list in a widget on my homepage - as well as displayed the list view page by adding it to my main menu.

I have found the information to update the summary of these list items by adding the proper view
for example adding the following view:

\Themes\PeaceCamp\Views\Items\Content-Event.Summary.cshtml

@Model.Title

however this seems to update the view in the widget, as well as in the list view page.  Since pagination only affects the page view - I presume there is a way to summarize them different in the two different areas - hoping someone could explain or direct me to the proper location to do that - Thanks!

My solution is all local at this time, so I cannot provide links as examples - and the only thing not done in the CMS would be the view added above.


问:
how to get the first splited part of each index in an array
we have an array like below, length of the array is not constant(may increase/decrease).

```<code>[255028AD_ABC_DE_2057,261830AD_ABC_FG_2876,.......]
</code>```

My aim is to achieve only the first part of each index like below.

```<code>[255028AD,261830AD,.........]
</code>```

Please help.

答:
You could match the first non underscore characters and return the first item of the matching result.

var array = ['255028AD_ABC_DE_2057', '261830AD_ABC_FG_2876'],
    result = array.map(s => s.match(/^[^_]+/)[0]);

console.log(result);```

Body:
we have an array like below, length of the array is not constant(may increase/decrease).

[255028AD_ABC_DE_2057,261830AD_ABC_FG_2876,.......]

My aim is to achieve only the first part of each index like below.

[255028AD,261830AD,.........]

Please help.


问:
PHP : Call to a member function execute() on boolean Error
this is my code :

```<code>    public function getTypeByID($typeId) {
    $stmt = $this->conn->prepare("SELECT type_id, description FROM type WHERE type_id = ? ");
    $stmt->bind_param("i", $typeId);
    if ($stmt->execute()) {
        $stmt->bind_result($id_type, $description);
        $stmt->fetch();
        $type = array();
        $type["type_id"] = $id_type;
        $type["description"] = $description;
        $stmt->close();
        return $type;
    } else {
        return NULL;
    }
}
</code>```

I got this error :

Fatal error: Call to a member function execute() on boolean.

I checked all topics that talk about it but nothing works for me.

I tried to execute the query on Mysql (PhpMyAdmin) and it works.

My type table structure :

Any idea.

答:
Maybe it's because type is a reserved word in MySQL.
See: https://dev.mysql.com/doc/refman/5.5/en/keywords.html
Try to change the table name to smth else.

Body:
this is my code :

    public function getTypeByID($typeId) {
    $stmt = $this->conn->prepare("SELECT type_id, description FROM type WHERE type_id = ? ");
    $stmt->bind_param("i", $typeId);
    if ($stmt->execute()) {
        $stmt->bind_result($id_type, $description);
        $stmt->fetch();
        $type = array();
        $type["type_id"] = $id_type;
        $type["description"] = $description;
        $stmt->close();
        return $type;
    } else {
        return NULL;
    }
}

I got this error :

Fatal error: Call to a member function execute() on boolean.

I checked all topics that talk about it but nothing works for me.

I tried to execute the query on Mysql (PhpMyAdmin) and it works.

My type table structure :

Any idea.


问:
XSLT - Remove child node while on appear in complete sentence
My Input XML is like as shown below:

```<code><thead>
  <tr>
    <td valign="top"><para><emph type="bold"><emph type="italic">Factor</emph></emph></para></td>
    <td valign="top"><para><emph type="bold"><emph type="italic">Important examples</emph></emph></para></td>
    <td valign="top"><para><emph type="italic">Content</emph></para></td>
    <td valign="top"><para><emph type="bold"><emph type="italic">Page</emph></emph></para></td>
    <td valign="top" colspan="2"><para><emph type="bold">Viral infection with</emph> <emph type="bold"><emph type="italic">Myxovirus influenzae</emph></emph></para></td>
  </tr>
</thead>
</code>```

Output should be

```<code><thead>
  <tr>
    <td valign="top"><para>Factor</para></td>
    <td valign="top"><para>Important examples</para></td>
    <td valign="top"><para>Content</para></td>
    <td valign="top"><para>Page</para></td>
    <td valign="top" colspan="2"><para><emph type="bold">Viral infection with</emph> <emph type="bold"><emph type="italic">Myxovirus influenzae</emph></emph></para></td>
  </tr>
</thead>
</code>```

My XSLT is as shown below.

```<code> <xsl:template match="emph">
    <xsl:choose>
        <xsl:when test="ancestor::thead/tr/td/para">
                <xsl:value-of select="."></xsl:value-of>
        </xsl:when>
        <xsl:otherwise>
            <xsl:copy>
                <xsl:apply-templates select="node() | @*"/>
            </xsl:copy>
        </xsl:otherwise>
    </xsl:choose>
</xsl:template>
</code>```

While running above XSLT, it's removing all emphasis from para whether it's partial emphasized or fully. But, we should remove only fully emphasized node within sentence. If the sentence is emphasized partially then we should not make any change.

答:
The following XSLT should work:</p>

```<code><xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform" version="1.0">

    <xsl:template match="@*|node()">
      <xsl:copy>
        <xsl:apply-templates select="@*|node()"/>
      </xsl:copy>
    </xsl:template>
    <xsl:template match="para[emph[emph]]">
      <para>
        <xsl:value-of select="."></xsl:value-of>
      </para>
    </xsl:template>
    <xsl:template match="para[emph]">
      <para>
        <xsl:value-of select="."></xsl:value-of>
      </para>
    </xsl:template>
    <xsl:template match="para[emph[2]]">
      <xsl:copy>
        <xsl:apply-templates select="@*|node()"/>
      </xsl:copy>
    </xsl:template>

</xsl:stylesheet>
</code>```

Body:
My Input XML is like as shown below:

    <para><emph type="bold"><emph type="italic">Factor</emph></emph></para>
    <para><emph type="bold"><emph type="italic">Important examples</emph></emph></para>
    <para><emph type="italic">Content</emph></para>
    <para><emph type="bold"><emph type="italic">Page</emph></emph></para>
    <para><emph type="bold">Viral infection with</emph> <emph type="bold"><emph type="italic">Myxovirus influenzae</emph></emph></para>

Output should be

    <para>Factor</para>
    <para>Important examples</para>
    <para>Content</para>
    <para>Page</para>
    <para><emph type="bold">Viral infection with</emph> <emph type="bold"><emph type="italic">Myxovirus influenzae</emph></emph></para>

My XSLT is as shown below.

 <xsl:template match="emph">
    <xsl:choose>
        <xsl:when test="ancestor::thead/tr/td/para">
                <xsl:value-of select="."></xsl:value-of>
        </xsl:when>
        <xsl:otherwise>
            <xsl:copy>
                <xsl:apply-templates select="node() | @*"/>
            </xsl:copy>
        </xsl:otherwise>
    </xsl:choose>
</xsl:template>

While running above XSLT, it's removing all emphasis from para whether it's partial emphasized or fully. But, we should remove only fully emphasized node within sentence. If the sentence is emphasized partially then we should not make any change.

Body:
The following XSLT should work:

<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform" version="1.0">

    <xsl:template match="@*|node()">
      <xsl:copy>
        <xsl:apply-templates select="@*|node()"/>
      </xsl:copy>
    </xsl:template>
    <xsl:template match="para[emph[emph]]">
      <para>
        <xsl:value-of select="."></xsl:value-of>
      </para>
    </xsl:template>
    <xsl:template match="para[emph]">
      <para>
        <xsl:value-of select="."></xsl:value-of>
      </para>
    </xsl:template>
    <xsl:template match="para[emph[2]]">
      <xsl:copy>
        <xsl:apply-templates select="@*|node()"/>
      </xsl:copy>
    </xsl:template>

</xsl:stylesheet>


问:
Destroy previous setInterval
I want a function to set an Ajax and a reload timer.  The code below doesn't destroy the previous function call timer, so each time I invoke it I get another timer.  How can I destroy the previous timer?</p>

```<code>function initNowPlayingMeta(station) {
    $('#cancion').children().remove();
    $('#cancion').load('sonando.php?emisora=' + station);
    var prevNowPlaying = setInterval(function () {
        $('#cancion').load('sonando.php?emisora=' + station);
    }, 5000);
}
</code>```

答:
clearInterval

clearInterval(prevNowPlaying);

you will also want to make the prevNowPlaying from previous calls in scope whereever you try to cancel

Title: Destroy previous setInterval

Body:
I want a function to set an Ajax and a reload timer.  The code below doesn't destroy the previous function call timer, so each time I invoke it I get another timer.  How can I destroy the previous timer?

function initNowPlayingMeta(station) {
    $('#cancion').children().remove();
    $('#cancion').load('sonando.php?emisora=' + station);
    var prevNowPlaying = setInterval(function () {
        $('#cancion').load('sonando.php?emisora=' + station);
    }, 5000);
}


问:
Decode JSON Swift 4
Can someone tell what is wrong with the code? I'm trying to parse the JSON from the server into variables to store the values. When i'm running the code, i'm not getting any errors. When i'm doing the print(users) after decoding the data, it's not returning anything. Can someone help me with this issue?

This is the code i'm using to retrieve the data from the server.

```<code>guard let url = URL(string: "my-url") else { return }
        let session = URLSession.shared
        let task = session.dataTask(with: url) { (data, _, _) in
            guard let data = data else { return }

            do {

                let user = try JSONDecoder().decode(User.self, from: data)
                print(user)

            } catch {}
        }
        task.resume()
</code>```

JSON result from the server

```<code>{
"UserId": "55844ef7-3f05-4560-8b37-216df422ffb8",
"ContactsDto": [
    {
        "Id": null,
        "UserId": null,
        "FriendUserId": "e61d09f8-9aec-4035-b0be-c36abea2d82b",
        "FirstName": null,
        "LastName": null,
        "Email": "",
        "PhonePrefix": null,
        "Phone": "54943597",
        "InviteStatus": "pending",
        "UserStatus": null,
        "ErrorCode": 0,
        "ErrorMessage": null
    },
    {
        "Id": null,
        "UserId": null,
        "FriendUserId": "b2e0d6d7-d97c-475e-a2ab-71cb8091a7a0",
        "FirstName": null,
        "LastName": null,
        "Email": "",
        "PhonePrefix": null,
        "Phone": "207-7575",
        "InviteStatus": "pending",
        "UserStatus": null,
        "ErrorCode": 0,
        "ErrorMessage": null
    },
    {
        "Id": null,
        "UserId": null,
        "FriendUserId": "8f8d6061-3a69-4641-ac40-329a824ff4e1",
        "FirstName": null,
        "LastName": null,
        "Email": "",
        "PhonePrefix": null,
        "Phone": "58511968",
        "InviteStatus": "pending",
        "UserStatus": null,
        "ErrorCode": 0,
        "ErrorMessage": null
    },
    {
        "Id": null,
        "UserId": null,
        "FriendUserId": "40c1e461-eb98-4e18-9363-13cfa460fe7e",
        "FirstName": null,
        "LastName": null,
        "Email": "",
        "PhonePrefix": null,
        "Phone": "57864550",
        "InviteStatus": "accepted",
        "UserStatus": null,
        "ErrorCode": 0,
        "ErrorMessage": null
    }
],
"ErrorCode": 0,
"ErrorMessage": null
</code>```

}

My Structure

```<code>struct User: Decodable {

let UserId: String?
let ContactsDto: [ContactsDto]?
let ErrorCode: Int?
let ErrorMessage: String?
</code>```

}

```<code>struct ContactsDto : Decodable {

let Id : String?
let UserId : String?
let FriendUserId : String?
let FirstName : String?
let LastName : String?
let Email : String?
let PhonePrefix : String?
let Phone : String?
let InviteStatus : String?
let UserStatus : String?
let ErrorCode : String?
let ErrorMessage : String?
</code>```

}

答:
From looking at your code, the way you are trying to decode the JSON isn't correct.

You aren't returning an array of User, but a single User Object.

As such you could try the following:

```<code>let user = try! JSONDecoder().decode(User.self, from: data)
</code>```

Title: Decode JSON Swift 4

Body:
Can someone tell what is wrong with the code? I'm trying to parse the JSON from the server into variables to store the values. When i'm running the code, i'm not getting any errors. When i'm doing the print(users) after decoding the data, it's not returning anything. Can someone help me with this issue?

This is the code i'm using to retrieve the data from the server.

guard let url = URL(string: "my-url") else { return }
        let session = URLSession.shared
        let task = session.dataTask(with: url) { (data, _, _) in
            guard let data = data else { return }

            do {

                let user = try JSONDecoder().decode(User.self, from: data)
                print(user)

            } catch {}
        }
        task.resume()

JSON result from the server

{
"UserId": "55844ef7-3f05-4560-8b37-216df422ffb8",
"ContactsDto": [
    {
        "Id": null,
        "UserId": null,
        "FriendUserId": "e61d09f8-9aec-4035-b0be-c36abea2d82b",
        "FirstName": null,
        "LastName": null,
        "Email": "",
        "PhonePrefix": null,
        "Phone": "54943597",
        "InviteStatus": "pending",
        "UserStatus": null,
        "ErrorCode": 0,
        "ErrorMessage": null
    },
    {
        "Id": null,
        "UserId": null,
        "FriendUserId": "b2e0d6d7-d97c-475e-a2ab-71cb8091a7a0",
        "FirstName": null,
        "LastName": null,
        "Email": "",
        "PhonePrefix": null,
        "Phone": "207-7575",
        "InviteStatus": "pending",
        "UserStatus": null,
        "ErrorCode": 0,
        "ErrorMessage": null
    },
    {
        "Id": null,
        "UserId": null,
        "FriendUserId": "8f8d6061-3a69-4641-ac40-329a824ff4e1",
        "FirstName": null,
        "LastName": null,
        "Email": "",
        "PhonePrefix": null,
        "Phone": "58511968",
        "InviteStatus": "pending",
        "UserStatus": null,
        "ErrorCode": 0,
        "ErrorMessage": null
    },
    {
        "Id": null,
        "UserId": null,
        "FriendUserId": "40c1e461-eb98-4e18-9363-13cfa460fe7e",
        "FirstName": null,
        "LastName": null,
        "Email": "",
        "PhonePrefix": null,
        "Phone": "57864550",
        "InviteStatus": "accepted",
        "UserStatus": null,
        "ErrorCode": 0,
        "ErrorMessage": null
    }
],
"ErrorCode": 0,
"ErrorMessage": null

}

My Structure

struct User: Decodable {

let UserId: String?
let ContactsDto: [ContactsDto]?
let ErrorCode: Int?
let ErrorMessage: String?

}

struct ContactsDto : Decodable {

let Id : String?
let UserId : String?
let FriendUserId : String?
let FirstName : String?
let LastName : String?
let Email : String?
let PhonePrefix : String?
let Phone : String?
let InviteStatus : String?
let UserStatus : String?
let ErrorCode : String?
let ErrorMessage : String?

}

Body:
From looking at your code, the way you are trying to decode the JSON isn't correct.

You aren't returning an array of User, but a single User Object.

As such you could try the following:

let user = try! JSONDecoder().decode(User.self, from: data)


问:
JMeter JSON Extractor to get value by condition
I get a JSON string like this:

```<code>[{"id":123,"name":"XX","default":false,"type":"other"},{"id":789,"name":"ZZ","default":false,"type":"first"}]
</code>```

I would like to get id, where name is ZZ, so extracted value should be 789.
I tried with this JSON expression:

$.id[?(@.name=='ZZ')]

I tried with regular expression too:

{"id":(.+?),"name":"ZZ","default":false,

My regular expression solution isn't working, because there are similar name values, like ZZ and ZZ (XYZ).

答:
You were close, with JSON extractor you need to find ZZ and then get the id of the object return, use the following expression:</p>

```<code>[?(@.name == 'ZZ')].id
</code>```

Body:
I get a JSON string like this:

[{"id":123,"name":"XX","default":false,"type":"other"},{"id":789,"name":"ZZ","default":false,"type":"first"}]

I would like to get id, where name is ZZ, so extracted value should be 789.
I tried with this JSON expression:

$.id[?(@.name=='ZZ')]

I tried with regular expression too:

{"id":(.+?),"name":"ZZ","default":false,

My regular expression solution isn't working, because there are similar name values, like ZZ and ZZ (XYZ).

Body:
You were close, with JSON extractor you need to find ZZ and then get the id of the object return, use the following expression:

[?(@.name == 'ZZ')].id


问:
Javascript function with dynamic parameters list and parameters array
I need to call a function in javaScript

```<code>service.call(row.operation, args.arg1, args.arg2, args.arg3,...,argN )
</code>```

And I have array of the parameters of random length. How to pass this array to a function as a parameter list?

UPDATE

I can't change call method signature. 'Call' method is custom, not standard.

答:
You can use the spread operator, it is perfectly suited for a varying number of parameters. Please have a look at this detailed description:

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Spread_operator

Body:
I need to call a function in javaScript

service.call(row.operation, args.arg1, args.arg2, args.arg3,...,argN )

And I have array of the parameters of random length. How to pass this array to a function as a parameter list?

UPDATE

I can't change call method signature. 'Call' method is custom, not standard.


问:
javax.net.ssl.SSLPeerUnverifiedException: SSL peer failed hostname validation for name: null
We set up Salesforce as IDP and our application is SP by using Spring SAML extension. But we got error 'SSL peer failed hostname validation for name: null'

```<code>2016-02-24 11:51:18 [localhost-startStop-1    ] ERROR o.s.s.s.t.MetadataCredentialResolver                                  : 111 - PKIX path construction failed for untrusted credential: [subjectName='CN=*.my.salesforce.com,OU=Applications,O=Salesforce.com\, Inc,L=San Francisco,ST=California,C=US']: unable to find valid certification path to requested target
2016-02-24 11:51:18 [localhost-startStop-1    ] INFO  o.a.c.h.HttpMethodDirector                                            : 439 - I/O exception (javax.net.ssl.SSLPeerUnverifiedException) caught when processing request: SSL peer failed hostname validation for name: null
2016-02-24 11:51:18 [localhost-startStop-1    ] INFO  o.a.c.h.HttpMethodDirector                                            : 445 - Retrying request
2016-02-24 11:51:18 [localhost-startStop-1    ] ERROR o.s.s.s.t.MetadataCredentialResolver                                  : 111 - PKIX path construction failed for untrusted credential: [subjectName='CN=*.my.salesforce.com,OU=Applications,O=Salesforce.com\, Inc,L=San Francisco,ST=California,C=US']: unable to find valid certification path to requested target
2016-02-24 11:51:18 [localhost-startStop-1    ] INFO  o.a.c.h.HttpMethodDirector                                            : 439 - I/O exception (javax.net.ssl.SSLPeerUnverifiedException) caught when processing request: SSL peer failed hostname validation for name: null
2016-02-24 11:51:18 [localhost-startStop-1    ] INFO  o.a.c.h.HttpMethodDirector                                            : 445 - Retrying request
2016-02-24 11:51:19 [localhost-startStop-1    ] ERROR o.s.s.s.t.MetadataCredentialResolver                                  : 111 - PKIX path construction failed for untrusted credential: [subjectName='CN=*.my.salesforce.com,OU=Applications,O=Salesforce.com\, Inc,L=San Francisco,ST=California,C=US']: unable to find valid certification path to requested target
2016-02-24 11:51:19 [localhost-startStop-1    ] INFO  o.a.c.h.HttpMethodDirector                                            : 439 - I/O exception (javax.net.ssl.SSLPeerUnverifiedException) caught when processing request: SSL peer failed hostname validation for name: null
2016-02-24 11:51:19 [localhost-startStop-1    ] INFO  o.a.c.h.HttpMethodDirector                                            : 445 - Retrying request
2016-02-24 11:51:19 [localhost-startStop-1    ] ERROR o.s.s.s.t.MetadataCredentialResolver                                  : 111 - PKIX path construction failed for untrusted credential: [subjectName='CN=*.my.salesforce.com,OU=Applications,O=Salesforce.com\, Inc,L=San Francisco,ST=California,C=US']: unable to find valid certification path to requested target
2016-02-24 11:51:19 [localhost-startStop-1    ] ERROR o.o.s.m.p.HTTPMetadataProvider                                        : 273 - Error retrieving metadata from https://flexsaml-dev-ed.my.salesforce.com/.well-known/samlidp/RevitasCCSpring.xml
javax.net.ssl.SSLPeerUnverifiedException: SSL peer failed hostname validation for name: null
</code>```

Here is our SAML configuration class.

```<code>@Autowired
private SAMLUserDetailsServiceImpl samlUserDetailsServiceImpl;

@Autowired
private ResourceLoader resourceLoader;

@Autowired
private Environment env;

@Autowired
private AuthenticationUtilService authenticationUtilService;

// Initialization of the velocity engine
@Bean
public VelocityEngine velocityEngine() {
    return VelocityFactory.getEngine();
}

// XML parser pool needed for OpenSAML parsing
@Bean(initMethod = "initialize")
public StaticBasicParserPool parserPool() {
    return new StaticBasicParserPool();
}

@Bean(name = "parserPoolHolder")
public ParserPoolHolder parserPoolHolder() {
    return new ParserPoolHolder();
}

// Bindings, encoders and decoders used for creating and parsing messages
@Bean
public MultiThreadedHttpConnectionManager multiThreadedHttpConnectionManager() {
    return new MultiThreadedHttpConnectionManager();
}

@Bean
public HttpClient httpClient() {
    return new HttpClient(multiThreadedHttpConnectionManager());
}

// SAML Authentication Provider responsible for validating of received SAML
// messages
@Bean
public SAMLAuthenticationProvider samlAuthenticationProvider() {
    SAMLAuthenticationProvider samlAuthenticationProvider = new SAMLAuthenticationProvider();
    samlAuthenticationProvider.setUserDetails(samlUserDetailsServiceImpl);
    samlAuthenticationProvider.setForcePrincipalAsString(false);
    return samlAuthenticationProvider;
}

// Provider of default SAML Context
@Bean
public SAMLContextProviderImpl contextProvider() {
    return new SAMLContextProviderImpl();
}

// Initialization of OpenSAML library
@Bean
public static SAMLBootstrap sAMLBootstrap() {
    return new SAMLBootstrap();
}

// Logger for SAML messages and events
@Bean
public SAMLDefaultLogger samlLogger() {
    return new SAMLDefaultLogger();
}

// SAML 2.0 WebSSO Assertion Consumer
@Bean
public WebSSOProfileConsumer webSSOprofileConsumer() {
    WebSSOProfileConsumerImpl webSSOProfileConsumer = new WebSSOProfileConsumerImpl();
    webSSOProfileConsumer.setResponseSkew(6000000);
    return webSSOProfileConsumer;
}

// SAML 2.0 Holder-of-Key WebSSO Assertion Consumer
@Bean
public WebSSOProfileConsumerHoKImpl hokWebSSOprofileConsumer() {
    return new WebSSOProfileConsumerHoKImpl();
}

// SAML 2.0 Web SSO profile
@Bean
public WebSSOProfile webSSOprofile() {
    return new WebSSOProfileImpl();
}

// SAML 2.0 Holder-of-Key Web SSO profile
@Bean
public WebSSOProfileConsumerHoKImpl hokWebSSOProfile() {
    return new WebSSOProfileConsumerHoKImpl();
}

// SAML 2.0 ECP profile
@Bean
public WebSSOProfileECPImpl ecpprofile() {
    return new WebSSOProfileECPImpl();
}

@Bean
public SingleLogoutProfile logoutprofile() {
    SingleLogoutProfileImpl singleLogoutProfile = new SingleLogoutProfileImpl();
    singleLogoutProfile.setResponseSkew(6000000);
    return singleLogoutProfile;
}

// Central storage of cryptographic keys
@Bean
public KeyManager keyManager() {
    Resource storeFile = null;
    if (StringUtils.isEmpty(env.getProperty("saml.keystore.file"))) {
        storeFile = resourceLoader
                .getResource("file:" + env.getProperty("saml.keystore.file"));
    } else {
        storeFile = resourceLoader.getResource("classpath:/saml/samlKeystore.jks");
    }
    String storePass = "nalle123";
    Map<String, String> passwords = new HashMap<String, String>();
    passwords.put("apollo", "nalle123");
    String defaultKey = "apollo";
    return new JKSKeyManager(storeFile, storePass, passwords, defaultKey);
}

// Setup TLS Socket Factory
@Bean
public TLSProtocolConfigurer tlsProtocolConfigurer() {
    TLSProtocolConfigurer tlsProtocolConfigurer = new TLSProtocolConfigurer();
    tlsProtocolConfigurer.setSslHostnameVerification("allowAll");
    return tlsProtocolConfigurer;
}

@Bean
public ProtocolSocketFactory socketFactory() {
    return new TLSProtocolSocketFactory(keyManager(), null, "default");
}

@Bean
public Protocol socketFactoryProtocol() {
    return new Protocol("https", socketFactory(), 443);
}

@Bean
public MethodInvokingFactoryBean socketFactoryInitialization() {
    MethodInvokingFactoryBean methodInvokingFactoryBean = new MethodInvokingFactoryBean();
    methodInvokingFactoryBean.setTargetClass(Protocol.class);
    methodInvokingFactoryBean.setTargetMethod("registerProtocol");
    Object[] args = {"https", socketFactoryProtocol()};
    methodInvokingFactoryBean.setArguments(args);
    return methodInvokingFactoryBean;
}

@Bean
public WebSSOProfileOptions defaultWebSSOProfileOptions() {
    WebSSOProfileOptions webSSOProfileOptions = new WebSSOProfileOptions();
    webSSOProfileOptions.setIncludeScoping(false);
    return webSSOProfileOptions;
}

// Entry point to initialize authentication, default values taken from
// properties file
@Bean
public SAMLEntryPoint samlEntryPoint() {
    SAMLEntryPoint samlEntryPoint = new SAMLEntryPoint();
    samlEntryPoint.setDefaultProfileOptions(defaultWebSSOProfileOptions());
    return samlEntryPoint;
}

// Setup advanced info about metadata
@Bean
public ExtendedMetadata extendedMetadata() {
    ExtendedMetadata extendedMetadata = new ExtendedMetadata();
    extendedMetadata.setIdpDiscoveryEnabled(true);
    extendedMetadata.setSignMetadata(false);
    return extendedMetadata;
}

// IDP Discovery Service
@Bean
public SAMLDiscovery samlIDPDiscovery() {
    SAMLDiscovery idpDiscovery = new SAMLDiscovery();
    idpDiscovery.setIdpSelectionPath("/saml/idpSelection");
    return idpDiscovery;
}

@Bean
@Qualifier("idp-local")
public ExtendedMetadataDelegate localIdpExtendedMetadataProvider()
        throws MetadataProviderException {
    File file = null;
    try {
        file = resourceLoader.getResource("classpath:/saml/metadata/idp.xml").getFile();
    } catch (IOException e) {
        theLogger.error("File doesn't exist...");
        return null;
    }

    Timer backgroundTaskTimer = new Timer(true);
    FilesystemMetadataProvider filesystemMetadataProvider = new FilesystemMetadataProvider(
            backgroundTaskTimer, file);
    filesystemMetadataProvider.setParserPool(parserPool());
    ExtendedMetadataDelegate extendedMetadataDelegate =
            new ExtendedMetadataDelegate(filesystemMetadataProvider, extendedMetadata());
    extendedMetadataDelegate.setMetadataTrustCheck(true);
    extendedMetadataDelegate.setMetadataRequireSignature(false);
    return extendedMetadataDelegate;
}

@Bean
@Qualifier("idp-sfdcHttp")
public ExtendedMetadataDelegate sfdcHttpExtendedMetadataProvider()
        throws MetadataProviderException {
    String sfdcMetadaURL = "https://flexsaml-dev-ed.my.salesforce.com/.well-known/samlidp/RevitasCCSpring.xml";
    Timer backgroundTaskTimer = new Timer(true);
    HTTPMetadataProvider httpMetadataProvider = new HTTPMetadataProvider(
            backgroundTaskTimer, httpClient(), sfdcMetadaURL);
    httpMetadataProvider.setParserPool(parserPool());
    ExtendedMetadataDelegate extendedMetadataDelegate =
            new ExtendedMetadataDelegate(httpMetadataProvider, extendedMetadata());
    extendedMetadataDelegate.setMetadataTrustCheck(false);
    extendedMetadataDelegate.setMetadataRequireSignature(false);
    return extendedMetadataDelegate;
}

// IDP Metadata configuration - paths to metadata of IDPs in circle of trust
// is here
// Do no forget to call iniitalize method on providers
@Bean
@Qualifier("metadata")
public CachingMetadataManager metadata() throws MetadataProviderException {
    List<MetadataProvider> providers = new ArrayList<MetadataProvider>();
    providers.add(localIdpExtendedMetadataProvider());
    providers.add(sfdcHttpExtendedMetadataProvider());
    return new CachingMetadataManager(providers);
}

// Filter automatically generates default SP metadata
@Bean
public MetadataGenerator metadataGenerator() {
    MetadataGenerator metadataGenerator = new MetadataGenerator();
    metadataGenerator.setEntityId("com:revitas:saml:sp");
    metadataGenerator.setExtendedMetadata(extendedMetadata());
    metadataGenerator.setIncludeDiscoveryExtension(false);
    metadataGenerator.setKeyManager(keyManager());
    return metadataGenerator;
}

// The filter is waiting for connections on URL suffixed with filterSuffix
// and presents SP metadata there
@Bean
public MetadataDisplayFilter metadataDisplayFilter() {
    return new MetadataDisplayFilter();
}

// Handler deciding where to redirect user after successful login
@Bean
public SAMLSuccessRedirectHandler successRedirectHandler() {
    SAMLSuccessRedirectHandler successRedirectHandler =
            new SAMLSuccessRedirectHandler();
    return successRedirectHandler;
}

// Handler deciding where to redirect user after failed login
@Bean
public SimpleUrlAuthenticationFailureHandler authenticationFailureHandler() {
    SimpleUrlAuthenticationFailureHandler failureHandler =
            new SimpleUrlAuthenticationFailureHandler();
    failureHandler.setUseForward(true);
    failureHandler.setDefaultFailureUrl("/error");
    return failureHandler;
}

@Bean
public SAMLWebSSOHoKProcessingFilter samlWebSSOHoKProcessingFilter() throws Exception {
    SAMLWebSSOHoKProcessingFilter samlWebSSOHoKProcessingFilter = new SAMLWebSSOHoKProcessingFilter();
    samlWebSSOHoKProcessingFilter.setAuthenticationSuccessHandler(successRedirectHandler());
    samlWebSSOHoKProcessingFilter.setAuthenticationManager(authenticationUtilService.getAuthenticationManager());
    samlWebSSOHoKProcessingFilter.setAuthenticationFailureHandler(authenticationFailureHandler());
    return samlWebSSOHoKProcessingFilter;
}

// Processing filter for WebSSO profile messages
@Bean
public SAMLProcessingFilter samlWebSSOProcessingFilter() throws Exception {
    SAMLProcessingFilter samlWebSSOProcessingFilter = new SAMLProcessingFilter();
    samlWebSSOProcessingFilter.setAuthenticationManager(authenticationUtilService.getAuthenticationManager());
    samlWebSSOProcessingFilter.setAuthenticationSuccessHandler(successRedirectHandler());
    samlWebSSOProcessingFilter.setAuthenticationFailureHandler(authenticationFailureHandler());
    return samlWebSSOProcessingFilter;
}

@Bean
public MetadataGeneratorFilter metadataGeneratorFilter() {
    return new MetadataGeneratorFilter(metadataGenerator());
}

// Handler for successful logout
@Bean
public SimpleUrlLogoutSuccessHandler successLogoutHandler() {
    SimpleUrlLogoutSuccessHandler successLogoutHandler = new SimpleUrlLogoutSuccessHandler();
    successLogoutHandler.setDefaultTargetUrl("/");
    return successLogoutHandler;
}

// Logout handler terminating local session
@Bean
public SecurityContextLogoutHandler logoutHandler() {
    SecurityContextLogoutHandler logoutHandler =
            new SecurityContextLogoutHandler();
    logoutHandler.setInvalidateHttpSession(true);
    logoutHandler.setClearAuthentication(true);
    return logoutHandler;
}

// Filter processing incoming logout messages
// First argument determines URL user will be redirected to after successful
// global logout
@Bean
public SAMLLogoutProcessingFilter samlLogoutProcessingFilter() {
    return new SAMLLogoutProcessingFilter(successLogoutHandler(),
            logoutHandler());
}

// Overrides default logout processing filter with the one processing SAML
// messages
@Bean
public SAMLLogoutFilter samlLogoutFilter() {
    return new SAMLLogoutFilter(successLogoutHandler(),
            new LogoutHandler[]{logoutHandler()},
            new LogoutHandler[]{logoutHandler()});
}

// Bindings
private ArtifactResolutionProfile artifactResolutionProfile() {
    final ArtifactResolutionProfileImpl artifactResolutionProfile =
            new ArtifactResolutionProfileImpl(httpClient());
    artifactResolutionProfile.setProcessor(new SAMLProcessorImpl(soapBinding()));
    return artifactResolutionProfile;
}

@Bean
public HTTPArtifactBinding artifactBinding(ParserPool parserPool, VelocityEngine velocityEngine) {
    return new HTTPArtifactBinding(parserPool, velocityEngine, artifactResolutionProfile());
}

@Bean
public HTTPSOAP11Binding soapBinding() {
    return new HTTPSOAP11Binding(parserPool());
}

@Bean
public HTTPPostBinding httpPostBinding() {
    return new HTTPPostBinding(parserPool(), velocityEngine());
}

@Bean
public HTTPRedirectDeflateBinding httpRedirectDeflateBinding() {
    return new HTTPRedirectDeflateBinding(parserPool());
}

@Bean
public HTTPSOAP11Binding httpSOAP11Binding() {
    return new HTTPSOAP11Binding(parserPool());
}

@Bean
public HTTPPAOS11Binding httpPAOS11Binding() {
    return new HTTPPAOS11Binding(parserPool());
}

// Processor
@Bean
public SAMLProcessorImpl processor() {
    Collection<SAMLBinding> bindings = new ArrayList<SAMLBinding>();
    bindings.add(httpRedirectDeflateBinding());
    bindings.add(httpPostBinding());
    bindings.add(artifactBinding(parserPool(), velocityEngine()));
    bindings.add(httpSOAP11Binding());
    bindings.add(httpPAOS11Binding());
    return new SAMLProcessorImpl(bindings);
}

/**
 * Define the security filter chain in order to support SSO Auth by using SAML 2.0
 *
 * @return Filter chain proxy
 * @throws Exception
 */
@Bean
public FilterChainProxy samlFilter() throws Exception {
    List<SecurityFilterChain> chains = new ArrayList<SecurityFilterChain>();
    chains.add(new DefaultSecurityFilterChain(new AntPathRequestMatcher("/saml/login/**"),
            samlEntryPoint()));
    chains.add(new DefaultSecurityFilterChain(new AntPathRequestMatcher("/saml/logout/**"),
            samlLogoutFilter()));
    chains.add(new DefaultSecurityFilterChain(new AntPathRequestMatcher("/saml/metadata/**"),
            metadataDisplayFilter()));
    chains.add(new DefaultSecurityFilterChain(new AntPathRequestMatcher("/saml/SSO/**"),
            samlWebSSOProcessingFilter()));
    chains.add(new DefaultSecurityFilterChain(new AntPathRequestMatcher("/saml/SSOHoK/**"),
            samlWebSSOHoKProcessingFilter()));
    chains.add(new DefaultSecurityFilterChain(new AntPathRequestMatcher("/saml/SingleLogout/**"),
            samlLogoutProcessingFilter()));
    chains.add(new DefaultSecurityFilterChain(new AntPathRequestMatcher("/saml/discovery/**"),
            samlIDPDiscovery()));
    return new FilterChainProxy(chains);
}
</code>```

We tried the suggestion from link 'Spring Security SAML + HTTPS to another page', which 1) disable host name verify or 2) commented out the Bean 'TLSProtocolConfigurer' and import Salesforce certificate into JDK cacerts, but none of them work and got the same error message.

What else approaches we can try?

答:
1) Setting the MetadataTrustCheck to false (extendedMetadataDelegate.setMetadataTrustCheck(false); every time you add metadata of IdP (the IdP signature is not verified in this case) and

2) delete of tlsProtocolConfigurer Bean

should solve your issue.

Body:
We set up Salesforce as IDP and our application is SP by using Spring SAML extension. But we got error 'SSL peer failed hostname validation for name: null'

2016-02-24 11:51:18 [localhost-startStop-1    ] ERROR o.s.s.s.t.MetadataCredentialResolver                                  : 111 - PKIX path construction failed for untrusted credential: [subjectName='CN=*.my.salesforce.com,OU=Applications,O=Salesforce.com\, Inc,L=San Francisco,ST=California,C=US']: unable to find valid certification path to requested target
2016-02-24 11:51:18 [localhost-startStop-1    ] INFO  o.a.c.h.HttpMethodDirector                                            : 439 - I/O exception (javax.net.ssl.SSLPeerUnverifiedException) caught when processing request: SSL peer failed hostname validation for name: null
2016-02-24 11:51:18 [localhost-startStop-1    ] INFO  o.a.c.h.HttpMethodDirector                                            : 445 - Retrying request
2016-02-24 11:51:18 [localhost-startStop-1    ] ERROR o.s.s.s.t.MetadataCredentialResolver                                  : 111 - PKIX path construction failed for untrusted credential: [subjectName='CN=*.my.salesforce.com,OU=Applications,O=Salesforce.com\, Inc,L=San Francisco,ST=California,C=US']: unable to find valid certification path to requested target
2016-02-24 11:51:18 [localhost-startStop-1    ] INFO  o.a.c.h.HttpMethodDirector                                            : 439 - I/O exception (javax.net.ssl.SSLPeerUnverifiedException) caught when processing request: SSL peer failed hostname validation for name: null
2016-02-24 11:51:18 [localhost-startStop-1    ] INFO  o.a.c.h.HttpMethodDirector                                            : 445 - Retrying request
2016-02-24 11:51:19 [localhost-startStop-1    ] ERROR o.s.s.s.t.MetadataCredentialResolver                                  : 111 - PKIX path construction failed for untrusted credential: [subjectName='CN=*.my.salesforce.com,OU=Applications,O=Salesforce.com\, Inc,L=San Francisco,ST=California,C=US']: unable to find valid certification path to requested target
2016-02-24 11:51:19 [localhost-startStop-1    ] INFO  o.a.c.h.HttpMethodDirector                                            : 439 - I/O exception (javax.net.ssl.SSLPeerUnverifiedException) caught when processing request: SSL peer failed hostname validation for name: null
2016-02-24 11:51:19 [localhost-startStop-1    ] INFO  o.a.c.h.HttpMethodDirector                                            : 445 - Retrying request
2016-02-24 11:51:19 [localhost-startStop-1    ] ERROR o.s.s.s.t.MetadataCredentialResolver                                  : 111 - PKIX path construction failed for untrusted credential: [subjectName='CN=*.my.salesforce.com,OU=Applications,O=Salesforce.com\, Inc,L=San Francisco,ST=California,C=US']: unable to find valid certification path to requested target
2016-02-24 11:51:19 [localhost-startStop-1    ] ERROR o.o.s.m.p.HTTPMetadataProvider                                        : 273 - Error retrieving metadata from https://flexsaml-dev-ed.my.salesforce.com/.well-known/samlidp/RevitasCCSpring.xml
javax.net.ssl.SSLPeerUnverifiedException: SSL peer failed hostname validation for name: null

Here is our SAML configuration class.

@Autowired
private SAMLUserDetailsServiceImpl samlUserDetailsServiceImpl;

@Autowired
private ResourceLoader resourceLoader;

@Autowired
private Environment env;

@Autowired
private AuthenticationUtilService authenticationUtilService;

// Initialization of the velocity engine
@Bean
public VelocityEngine velocityEngine() {
    return VelocityFactory.getEngine();
}

// XML parser pool needed for OpenSAML parsing
@Bean(initMethod = "initialize")
public StaticBasicParserPool parserPool() {
    return new StaticBasicParserPool();
}

@Bean(name = "parserPoolHolder")
public ParserPoolHolder parserPoolHolder() {
    return new ParserPoolHolder();
}

// Bindings, encoders and decoders used for creating and parsing messages
@Bean
public MultiThreadedHttpConnectionManager multiThreadedHttpConnectionManager() {
    return new MultiThreadedHttpConnectionManager();
}

@Bean
public HttpClient httpClient() {
    return new HttpClient(multiThreadedHttpConnectionManager());
}

// SAML Authentication Provider responsible for validating of received SAML
// messages
@Bean
public SAMLAuthenticationProvider samlAuthenticationProvider() {
    SAMLAuthenticationProvider samlAuthenticationProvider = new SAMLAuthenticationProvider();
    samlAuthenticationProvider.setUserDetails(samlUserDetailsServiceImpl);
    samlAuthenticationProvider.setForcePrincipalAsString(false);
    return samlAuthenticationProvider;
}

// Provider of default SAML Context
@Bean
public SAMLContextProviderImpl contextProvider() {
    return new SAMLContextProviderImpl();
}

// Initialization of OpenSAML library
@Bean
public static SAMLBootstrap sAMLBootstrap() {
    return new SAMLBootstrap();
}

// Logger for SAML messages and events
@Bean
public SAMLDefaultLogger samlLogger() {
    return new SAMLDefaultLogger();
}

// SAML 2.0 WebSSO Assertion Consumer
@Bean
public WebSSOProfileConsumer webSSOprofileConsumer() {
    WebSSOProfileConsumerImpl webSSOProfileConsumer = new WebSSOProfileConsumerImpl();
    webSSOProfileConsumer.setResponseSkew(6000000);
    return webSSOProfileConsumer;
}

// SAML 2.0 Holder-of-Key WebSSO Assertion Consumer
@Bean
public WebSSOProfileConsumerHoKImpl hokWebSSOprofileConsumer() {
    return new WebSSOProfileConsumerHoKImpl();
}

// SAML 2.0 Web SSO profile
@Bean
public WebSSOProfile webSSOprofile() {
    return new WebSSOProfileImpl();
}

// SAML 2.0 Holder-of-Key Web SSO profile
@Bean
public WebSSOProfileConsumerHoKImpl hokWebSSOProfile() {
    return new WebSSOProfileConsumerHoKImpl();
}

// SAML 2.0 ECP profile
@Bean
public WebSSOProfileECPImpl ecpprofile() {
    return new WebSSOProfileECPImpl();
}

@Bean
public SingleLogoutProfile logoutprofile() {
    SingleLogoutProfileImpl singleLogoutProfile = new SingleLogoutProfileImpl();
    singleLogoutProfile.setResponseSkew(6000000);
    return singleLogoutProfile;
}

// Central storage of cryptographic keys
@Bean
public KeyManager keyManager() {
    Resource storeFile = null;
    if (StringUtils.isEmpty(env.getProperty("saml.keystore.file"))) {
        storeFile = resourceLoader
                .getResource("file:" + env.getProperty("saml.keystore.file"));
    } else {
        storeFile = resourceLoader.getResource("classpath:/saml/samlKeystore.jks");
    }
    String storePass = "nalle123";
    Map<String, String> passwords = new HashMap<String, String>();
    passwords.put("apollo", "nalle123");
    String defaultKey = "apollo";
    return new JKSKeyManager(storeFile, storePass, passwords, defaultKey);
}

// Setup TLS Socket Factory
@Bean
public TLSProtocolConfigurer tlsProtocolConfigurer() {
    TLSProtocolConfigurer tlsProtocolConfigurer = new TLSProtocolConfigurer();
    tlsProtocolConfigurer.setSslHostnameVerification("allowAll");
    return tlsProtocolConfigurer;
}

@Bean
public ProtocolSocketFactory socketFactory() {
    return new TLSProtocolSocketFactory(keyManager(), null, "default");
}

@Bean
public Protocol socketFactoryProtocol() {
    return new Protocol("https", socketFactory(), 443);
}

@Bean
public MethodInvokingFactoryBean socketFactoryInitialization() {
    MethodInvokingFactoryBean methodInvokingFactoryBean = new MethodInvokingFactoryBean();
    methodInvokingFactoryBean.setTargetClass(Protocol.class);
    methodInvokingFactoryBean.setTargetMethod("registerProtocol");
    Object[] args = {"https", socketFactoryProtocol()};
    methodInvokingFactoryBean.setArguments(args);
    return methodInvokingFactoryBean;
}

@Bean
public WebSSOProfileOptions defaultWebSSOProfileOptions() {
    WebSSOProfileOptions webSSOProfileOptions = new WebSSOProfileOptions();
    webSSOProfileOptions.setIncludeScoping(false);
    return webSSOProfileOptions;
}

// Entry point to initialize authentication, default values taken from
// properties file
@Bean
public SAMLEntryPoint samlEntryPoint() {
    SAMLEntryPoint samlEntryPoint = new SAMLEntryPoint();
    samlEntryPoint.setDefaultProfileOptions(defaultWebSSOProfileOptions());
    return samlEntryPoint;
}

// Setup advanced info about metadata
@Bean
public ExtendedMetadata extendedMetadata() {
    ExtendedMetadata extendedMetadata = new ExtendedMetadata();
    extendedMetadata.setIdpDiscoveryEnabled(true);
    extendedMetadata.setSignMetadata(false);
    return extendedMetadata;
}

// IDP Discovery Service
@Bean
public SAMLDiscovery samlIDPDiscovery() {
    SAMLDiscovery idpDiscovery = new SAMLDiscovery();
    idpDiscovery.setIdpSelectionPath("/saml/idpSelection");
    return idpDiscovery;
}

@Bean
@Qualifier("idp-local")
public ExtendedMetadataDelegate localIdpExtendedMetadataProvider()
        throws MetadataProviderException {
    File file = null;
    try {
        file = resourceLoader.getResource("classpath:/saml/metadata/idp.xml").getFile();
    } catch (IOException e) {
        theLogger.error("File doesn't exist...");
        return null;
    }

    Timer backgroundTaskTimer = new Timer(true);
    FilesystemMetadataProvider filesystemMetadataProvider = new FilesystemMetadataProvider(
            backgroundTaskTimer, file);
    filesystemMetadataProvider.setParserPool(parserPool());
    ExtendedMetadataDelegate extendedMetadataDelegate =
            new ExtendedMetadataDelegate(filesystemMetadataProvider, extendedMetadata());
    extendedMetadataDelegate.setMetadataTrustCheck(true);
    extendedMetadataDelegate.setMetadataRequireSignature(false);
    return extendedMetadataDelegate;
}

@Bean
@Qualifier("idp-sfdcHttp")
public ExtendedMetadataDelegate sfdcHttpExtendedMetadataProvider()
        throws MetadataProviderException {
    String sfdcMetadaURL = "https://flexsaml-dev-ed.my.salesforce.com/.well-known/samlidp/RevitasCCSpring.xml";
    Timer backgroundTaskTimer = new Timer(true);
    HTTPMetadataProvider httpMetadataProvider = new HTTPMetadataProvider(
            backgroundTaskTimer, httpClient(), sfdcMetadaURL);
    httpMetadataProvider.setParserPool(parserPool());
    ExtendedMetadataDelegate extendedMetadataDelegate =
            new ExtendedMetadataDelegate(httpMetadataProvider, extendedMetadata());
    extendedMetadataDelegate.setMetadataTrustCheck(false);
    extendedMetadataDelegate.setMetadataRequireSignature(false);
    return extendedMetadataDelegate;
}

// IDP Metadata configuration - paths to metadata of IDPs in circle of trust
// is here
// Do no forget to call iniitalize method on providers
@Bean
@Qualifier("metadata")
public CachingMetadataManager metadata() throws MetadataProviderException {
    List<MetadataProvider> providers = new ArrayList<MetadataProvider>();
    providers.add(localIdpExtendedMetadataProvider());
    providers.add(sfdcHttpExtendedMetadataProvider());
    return new CachingMetadataManager(providers);
}

// Filter automatically generates default SP metadata
@Bean
public MetadataGenerator metadataGenerator() {
    MetadataGenerator metadataGenerator = new MetadataGenerator();
    metadataGenerator.setEntityId("com:revitas:saml:sp");
    metadataGenerator.setExtendedMetadata(extendedMetadata());
    metadataGenerator.setIncludeDiscoveryExtension(false);
    metadataGenerator.setKeyManager(keyManager());
    return metadataGenerator;
}

// The filter is waiting for connections on URL suffixed with filterSuffix
// and presents SP metadata there
@Bean
public MetadataDisplayFilter metadataDisplayFilter() {
    return new MetadataDisplayFilter();
}

// Handler deciding where to redirect user after successful login
@Bean
public SAMLSuccessRedirectHandler successRedirectHandler() {
    SAMLSuccessRedirectHandler successRedirectHandler =
            new SAMLSuccessRedirectHandler();
    return successRedirectHandler;
}

// Handler deciding where to redirect user after failed login
@Bean
public SimpleUrlAuthenticationFailureHandler authenticationFailureHandler() {
    SimpleUrlAuthenticationFailureHandler failureHandler =
            new SimpleUrlAuthenticationFailureHandler();
    failureHandler.setUseForward(true);
    failureHandler.setDefaultFailureUrl("/error");
    return failureHandler;
}

@Bean
public SAMLWebSSOHoKProcessingFilter samlWebSSOHoKProcessingFilter() throws Exception {
    SAMLWebSSOHoKProcessingFilter samlWebSSOHoKProcessingFilter = new SAMLWebSSOHoKProcessingFilter();
    samlWebSSOHoKProcessingFilter.setAuthenticationSuccessHandler(successRedirectHandler());
    samlWebSSOHoKProcessingFilter.setAuthenticationManager(authenticationUtilService.getAuthenticationManager());
    samlWebSSOHoKProcessingFilter.setAuthenticationFailureHandler(authenticationFailureHandler());
    return samlWebSSOHoKProcessingFilter;
}

// Processing filter for WebSSO profile messages
@Bean
public SAMLProcessingFilter samlWebSSOProcessingFilter() throws Exception {
    SAMLProcessingFilter samlWebSSOProcessingFilter = new SAMLProcessingFilter();
    samlWebSSOProcessingFilter.setAuthenticationManager(authenticationUtilService.getAuthenticationManager());
    samlWebSSOProcessingFilter.setAuthenticationSuccessHandler(successRedirectHandler());
    samlWebSSOProcessingFilter.setAuthenticationFailureHandler(authenticationFailureHandler());
    return samlWebSSOProcessingFilter;
}

@Bean
public MetadataGeneratorFilter metadataGeneratorFilter() {
    return new MetadataGeneratorFilter(metadataGenerator());
}

// Handler for successful logout
@Bean
public SimpleUrlLogoutSuccessHandler successLogoutHandler() {
    SimpleUrlLogoutSuccessHandler successLogoutHandler = new SimpleUrlLogoutSuccessHandler();
    successLogoutHandler.setDefaultTargetUrl("/");
    return successLogoutHandler;
}

// Logout handler terminating local session
@Bean
public SecurityContextLogoutHandler logoutHandler() {
    SecurityContextLogoutHandler logoutHandler =
            new SecurityContextLogoutHandler();
    logoutHandler.setInvalidateHttpSession(true);
    logoutHandler.setClearAuthentication(true);
    return logoutHandler;
}

// Filter processing incoming logout messages
// First argument determines URL user will be redirected to after successful
// global logout
@Bean
public SAMLLogoutProcessingFilter samlLogoutProcessingFilter() {
    return new SAMLLogoutProcessingFilter(successLogoutHandler(),
            logoutHandler());
}

// Overrides default logout processing filter with the one processing SAML
// messages
@Bean
public SAMLLogoutFilter samlLogoutFilter() {
    return new SAMLLogoutFilter(successLogoutHandler(),
            new LogoutHandler[]{logoutHandler()},
            new LogoutHandler[]{logoutHandler()});
}

// Bindings
private ArtifactResolutionProfile artifactResolutionProfile() {
    final ArtifactResolutionProfileImpl artifactResolutionProfile =
            new ArtifactResolutionProfileImpl(httpClient());
    artifactResolutionProfile.setProcessor(new SAMLProcessorImpl(soapBinding()));
    return artifactResolutionProfile;
}

@Bean
public HTTPArtifactBinding artifactBinding(ParserPool parserPool, VelocityEngine velocityEngine) {
    return new HTTPArtifactBinding(parserPool, velocityEngine, artifactResolutionProfile());
}

@Bean
public HTTPSOAP11Binding soapBinding() {
    return new HTTPSOAP11Binding(parserPool());
}

@Bean
public HTTPPostBinding httpPostBinding() {
    return new HTTPPostBinding(parserPool(), velocityEngine());
}

@Bean
public HTTPRedirectDeflateBinding httpRedirectDeflateBinding() {
    return new HTTPRedirectDeflateBinding(parserPool());
}

@Bean
public HTTPSOAP11Binding httpSOAP11Binding() {
    return new HTTPSOAP11Binding(parserPool());
}

@Bean
public HTTPPAOS11Binding httpPAOS11Binding() {
    return new HTTPPAOS11Binding(parserPool());
}

// Processor
@Bean
public SAMLProcessorImpl processor() {
    Collection<SAMLBinding> bindings = new ArrayList<SAMLBinding>();
    bindings.add(httpRedirectDeflateBinding());
    bindings.add(httpPostBinding());
    bindings.add(artifactBinding(parserPool(), velocityEngine()));
    bindings.add(httpSOAP11Binding());
    bindings.add(httpPAOS11Binding());
    return new SAMLProcessorImpl(bindings);
}

/**
 * Define the security filter chain in order to support SSO Auth by using SAML 2.0
 *
 * @return Filter chain proxy
 * @throws Exception
 */
@Bean
public FilterChainProxy samlFilter() throws Exception {
    List<SecurityFilterChain> chains = new ArrayList<SecurityFilterChain>();
    chains.add(new DefaultSecurityFilterChain(new AntPathRequestMatcher("/saml/login/**"),
            samlEntryPoint()));
    chains.add(new DefaultSecurityFilterChain(new AntPathRequestMatcher("/saml/logout/**"),
            samlLogoutFilter()));
    chains.add(new DefaultSecurityFilterChain(new AntPathRequestMatcher("/saml/metadata/**"),
            metadataDisplayFilter()));
    chains.add(new DefaultSecurityFilterChain(new AntPathRequestMatcher("/saml/SSO/**"),
            samlWebSSOProcessingFilter()));
    chains.add(new DefaultSecurityFilterChain(new AntPathRequestMatcher("/saml/SSOHoK/**"),
            samlWebSSOHoKProcessingFilter()));
    chains.add(new DefaultSecurityFilterChain(new AntPathRequestMatcher("/saml/SingleLogout/**"),
            samlLogoutProcessingFilter()));
    chains.add(new DefaultSecurityFilterChain(new AntPathRequestMatcher("/saml/discovery/**"),
            samlIDPDiscovery()));
    return new FilterChainProxy(chains);
}

We tried the suggestion from link 'Spring Security SAML + HTTPS to another page', which 1) disable host name verify or 2) commented out the Bean 'TLSProtocolConfigurer' and import Salesforce certificate into JDK cacerts, but none of them work and got the same error message.

What else approaches we can try?


答:
With Array.map() and String.substr() functions:

var arr = ['255028AD_ABC_DE_2057', '261830AD_ABC_FG_2876' ],
    result = arr.map(v => v.substr(0, v.indexOf('_')));
console.log(result);```

v.indexOf('_') - to find the 1st position of _ char

v.substr(0, v.indexOf('_')) - extracting the substring starting from the position 0 to the 1st position of _ char (getting slice)

Title: how to get the first splited part of each index in an array

Body:
With Array.map() and String.substr() functions:

var arr = ['255028AD_ABC_DE_2057', '261830AD_ABC_FG_2876' ],
    result = arr.map(v => v.substr(0, v.indexOf('_')));
console.log(result);

v.indexOf('_') - to find the 1st position of _ char

v.substr(0, v.indexOf('_')) - extracting the substring starting from the position 0 to the 1st position of _ char (getting slice)


问:
Get list of script references that are registered with the asp:ScriptManager
My asp.net ScriptManager is outputting lots of AXD script references in my html:

```<code><script src="/ScriptResource.axd?d=B073McDWctL8Kxw1sTGlGNcf...
<script src="/ScriptResource.axd?d=2WiTJxV_YZ2N4lJaAfSKnBVu...
<script src="/ScriptResource.axd?d=jSiywqe6yJ5PAsxeca407Xxb...
...about 4 more ...
</code>```

Now i realise that those encrypted querystrings represent script references, eg assembly and name. I want to get at that list of registered scripts, so i can add them to my composite script like so:

```<code><asp:ScriptManager runat="server">
  <CompositeScript>
    <Scripts>
        <asp:ScriptReference Name="Something.js" Assembly="System.Something" />
    </Scripts>
  </CompositeScript>
</asp:ScriptManager>
</code>```

I've tried the following code to get at the list of registered scripts but it always returns zero scripts for some reason, what am i doing wrong?

```<code>protected override void Render(HtmlTextWriter output)
{
  var sm = ScriptManager.GetCurrent(this);
  foreach (ScriptReference s in sm.Scripts)
  {
    string debug = s.Assembly + ">" + s.Name + ";" + s.Path;
  }

  base.Render(output);
}
</code>```

答:
Ok i wrote this code, inspired by ( http://aspnet.codeplex.com/releases/view/13356 ), which does the trick and outputs the list of script references i need to add to my scriptmanager:

```<code>protected override void OnInit(EventArgs e)
{
  base.OnInit(e);
  ScriptManager.GetCurrent(this)
    .ResolveScriptReference += new EventHandler<ScriptReferenceEventArgs>(ResolveScriptReferenceHandler);
}

List<string> ScriptRefs = new List<string>();
private void ResolveScriptReferenceHandler(object sender, ScriptReferenceEventArgs e)
{
  ScriptRefs.Add("<asp:ScriptReference Name=\"" + e.Script.Name + "\" Assembly=\"" + e.Script.Assembly + "\" />");
}

protected override void Render(HtmlTextWriter output)
{
  base.Render(output);
  string debug = string.Join("\r\n", ScriptRefs.Distinct());
}
</code>```

Simply put that code in your Page class and set a breakpoint on the 'string debug=...' line to check which scripts are needed.
Sweet.

Body:
My asp.net ScriptManager is outputting lots of AXD script references in my html:

  </CompositeScript>
</asp:ScriptManager>

I've tried the following code to get at the list of registered scripts but it always returns zero scripts for some reason, what am i doing wrong?

protected override void Render(HtmlTextWriter output)
{
  var sm = ScriptManager.GetCurrent(this);
  foreach (ScriptReference s in sm.Scripts)
  {
    string debug = s.Assembly + ">" + s.Name + ";" + s.Path;
  }

  base.Render(output);
}

Body:
Ok i wrote this code, inspired by ( http://aspnet.codeplex.com/releases/view/13356 ), which does the trick and outputs the list of script references i need to add to my scriptmanager:

protected override void OnInit(EventArgs e)
{
  base.OnInit(e);
  ScriptManager.GetCurrent(this)
    .ResolveScriptReference += new EventHandler<ScriptReferenceEventArgs>(ResolveScriptReferenceHandler);
}

List<string> ScriptRefs = new List<string>();
private void ResolveScriptReferenceHandler(object sender, ScriptReferenceEventArgs e)
{
  ScriptRefs.Add("<asp:ScriptReference Name=\"" + e.Script.Name + "\" Assembly=\"" + e.Script.Assembly + "\" />");
}

protected override void Render(HtmlTextWriter output)
{
  base.Render(output);
  string debug = string.Join("\r\n", ScriptRefs.Distinct());
}

Simply put that code in your Page class and set a breakpoint on the 'string debug=...' line to check which scripts are needed.
Sweet.


问:
create dynamically dataframes
I have a set of csv files in a folder, and I would like to create dynamically dataframes having the same name as the csv file

for instance I have the following files : AC201703.csv AC201703.csv AC201704.csv
I would like to load those file an put in dataframes having the same name e.g. AC201703 AC201704
I try to use exec like the following

```<code>for file in glob.glob("*.csv"):
   df = pd.read_csv(file,encoding = 'ISO-8859-1' )
   exec("%s = %s" % (file[:7],df))
</code>```

but it didn't work, i get the following error

```<code>  File "<ipython-input-31-2d670638b427>", line 4, in <module>
    exec("%s = %s" % (file[:7],df))

  File "<string>", line 1
    A201610 =        A201610_fb_act_n_n_buy cust_key  A201610_fb_act_n_n LCELGST  \
                                                   ^
SyntaxError: invalid syntax
</code>```

it seems to assign to the variable A201610 the name of csv columns

答:
I think better is use dict of DataFrames:

```<code>d = {file[:7] : pd.read_csv(file, encoding = 'ISO-8859-1') for file in glob.glob("*.csv")}
</code>```

and then select DataFrame by keys - first 7 letters of filenames:

```<code>print (d['AC20170'])
</code>```

But if dont want use dicts:

```<code>for file in glob.glob("*.csv"):
    globals()[file[:7]] = pd.read_csv(file,encoding = 'ISO-8859-1')

print (AC20170)
</code>```

Title: create dynamically dataframes

Body:
I have a set of csv files in a folder, and I would like to create dynamically dataframes having the same name as the csv file

for instance I have the following files : AC201703.csv AC201703.csv AC201704.csv
I would like to load those file an put in dataframes having the same name e.g. AC201703 AC201704
I try to use exec like the following

for file in glob.glob("*.csv"):
   df = pd.read_csv(file,encoding = 'ISO-8859-1' )
   exec("%s = %s" % (file[:7],df))

but it didn't work, i get the following error

  File "<ipython-input-31-2d670638b427>", line 4, in <module>
    exec("%s = %s" % (file[:7],df))

  File "<string>", line 1
    A201610 =        A201610_fb_act_n_n_buy cust_key  A201610_fb_act_n_n LCELGST  \
                                                   ^
SyntaxError: invalid syntax

it seems to assign to the variable A201610 the name of csv columns

Body:
I think better is use dict of DataFrames:

d = {file[:7] : pd.read_csv(file, encoding = 'ISO-8859-1') for file in glob.glob("*.csv")}

and then select DataFrame by keys - first 7 letters of filenames:

print (d['AC20170'])

But if dont want use dicts:

for file in glob.glob("*.csv"):
    globals()[file[:7]] = pd.read_csv(file,encoding = 'ISO-8859-1')

print (AC20170)


问:
Issue to resize element content properly
The text of second h5 element doesnt resize properly and get out over the background color, I also tested put the h5 inside a div and apply css to the div but it didnt work, what am I missing?

Here is the relevant code (I had to remove other elements and css properties):

.container {
    position: relative;
    display: inline-block;
    margin-top: 50px;
}
.card .front {
    color: white;
    text-align: center;
    font-weight: bold;
    position: absolute;
}
.card .front h5 {
    background-color: #5E92F2;
    padding: 10px 0 10px 0;
    margin-top: 98%;
    width: 198px;
    height: 44px;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><head>
  <title>Bootstrap Example</title>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-beta.2/css/bootstrap.min.css">
  <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
  <script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.12.6/umd/popper.min.js"></script>
  <script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-beta.2/js/bootstrap.min.js"></script>
</head>
<body>
<section class="container">
            <div class="card">
                <div class="front" style="background-image: url('image.jpg');">
                    <h5>Image 1</h5>
                </div>
                <div class="back">Abc</div>
            </div>
</section>

<section class="container">
            <div class="card">
                <div class="front" style="background-image: url('image.jpg');">
                    <h5>Image 1 With more text</h5>
                </div>
                <div class="back">Abc</div>
            </div>
</section></code>```

答:
try this : </p>

```<code>h5{
    font-size: 100%;
}
</code>```

Body:
The text of second h5 element doesnt resize properly and get out over the background color, I also tested put the h5 inside a div and apply css to the div but it didnt work, what am I missing?

Here is the relevant code (I had to remove other elements and css properties):

.container {
    position: relative;
    display: inline-block;
    margin-top: 50px;
}
.card .front {
    color: white;
    text-align: center;
    font-weight: bold;
    position: absolute;
}
.card .front h5 {
    background-color: #5E92F2;
    padding: 10px 0 10px 0;
    margin-top: 98%;
    width: 198px;
    height: 44px;
}

  <title>Bootstrap Example</title>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-beta.2/css/bootstrap.min.css">

Image 1

Abc

Image 1 With more text

Abc

Body:
try this :

h5{
    font-size: 100%;
}


问:
Internet Explorer javascript scroll function issue
My code is as follows:

```<code>var lastScrollTop = 0;
window.addEventListener("scroll", function(){
var st = window.pageYOffset || document.documentElement.scrollTop;
if (st > lastScrollTop){
   $('.sticky').addClass('insight');
} else {
  $('.sticky').removeClass('insight');
}
lastScrollTop = st;
}, false);
</code>```

Expected results appear in Chrome, FF, Edge: When the page is scrolled down, the class "insight" is added to elements with class "sticky" and it remains there until user scrolls upwards on the page.

In explorer, the "insight" is added as well on scroll down, but it's immediately removed when the downward scrolling motion stops. What could be causing this?

It's like Explorer has an extra scroll event when scrolling is complete?

答:
In Internet Explorer I didn't understand why on scroll down it is going to else condition as well.

I changed the condition for scroll up so it is working fine.

```<code>var lastScrollTop = 0;
 window.addEventListener("scroll", function(){
 var st = window.pageYOffset || document.documentElement.scrollTop;
if (st > lastScrollTop){
  $('.sticky').addClass('insight');
} else if (st < lastScrollTop) {
  $('.sticky').removeClass('insight');
}
lastScrollTop = st;
}, false);
</code>```

Body:
My code is as follows:

var lastScrollTop = 0;
window.addEventListener("scroll", function(){
var st = window.pageYOffset || document.documentElement.scrollTop;
if (st > lastScrollTop){
   $('.sticky').addClass('insight');
} else {
  $('.sticky').removeClass('insight');
}
lastScrollTop = st;
}, false);

Expected results appear in Chrome, FF, Edge: When the page is scrolled down, the class "insight" is added to elements with class "sticky" and it remains there until user scrolls upwards on the page.

In explorer, the "insight" is added as well on scroll down, but it's immediately removed when the downward scrolling motion stops. What could be causing this?

It's like Explorer has an extra scroll event when scrolling is complete?

Body:
In Internet Explorer I didn't understand why on scroll down it is going to else condition as well.

I changed the condition for scroll up so it is working fine.

var lastScrollTop = 0;
 window.addEventListener("scroll", function(){
 var st = window.pageYOffset || document.documentElement.scrollTop;
if (st > lastScrollTop){
  $('.sticky').addClass('insight');
} else if (st < lastScrollTop) {
  $('.sticky').removeClass('insight');
}
lastScrollTop = st;
}, false);

ContentLicense: CC BY-SA 4.0


答:
You need to explicitly clear the timer.</p>

```<code>var prevNowPlaying;
function initNowPlayingMeta(station) {
    $('#cancion').children().remove();
    $('#cancion').load('sonando.php?emisora=' + station);
    if (prevNowPlaying === undefined) clearInterval(prevNowPlaying);
    prevNowPlaying = setInterval(function () {
        $('#cancion').load('sonando.php?emisora=' + station);
    }, 5000);
}
</code>```

Title: Destroy previous setInterval

Body:
You need to explicitly clear the timer.

var prevNowPlaying;
function initNowPlayingMeta(station) {
    $('#cancion').children().remove();
    $('#cancion').load('sonando.php?emisora=' + station);
    if (prevNowPlaying === undefined) clearInterval(prevNowPlaying);
    prevNowPlaying = setInterval(function () {
        $('#cancion').load('sonando.php?emisora=' + station);
    }, 5000);
}