问:
Contact Form Sending Error
I'm screwing around with a template and just trying to get my contact form to work (in attempt to see how it works, sends messages, etc.). When filling out my contact form and then hitting submit, instead of it going through successfully, one of the errors pops up:

Email could not be sent due to some Unexpected Error. Please Try Again later.

Reason:
Could not instantiate mail function.

http://prntscr.com/fh5cct

Here's my contact form in HTML:

```<code><div class="col_half col_last">

    <div class="fancy-title title-dotted-border test-john">
        <h3>Send us an Email</h3>
    </div>

    <div class="contact-widget">

        <div class="contact-form-result"></div>

        <form class="nobottommargin" id="template-contactform" name="template-contactform" action="include/sendemail.php" method="post">

        <div class="form-process"></div>

        <div class="col_one_third">
            <label for="template-contactform-name">Name <small>*</small></label>
            <input type="text" id="template-contactform-name" name="template-contactform-name" value="" class="sm-form-control required" />
        </div>

        <div class="col_one_third">
            <label for="template-contactform-email">Email <small>*</small></label>
            <input type="email" id="template-contactform-email" name="template-contactform-email" value="" class="required email sm-form-control" />
        </div>

        <div class="col_one_third col_last">
            <label for="template-contactform-phone">Phone</label>
            <input type="text" id="template-contactform-phone" name="template-contactform-phone" value="" class="sm-form-control" />
        </div>

        <div class="clear"></div>

        <div class="col_full">
            <label for="template-contactform-subject">Subject <small>*</small></label>
            <input type="text" id="template-contactform-subject" name="template-contactform-subject" value="" class="required sm-form-control" />
        </div>

        <div class="clear"></div>

        <div class="col_full">
            <label for="template-contactform-message">Message <small>*</small></label>
            <textarea class="required sm-form-control" id="template-contactform-message" name="template-contactform-message" rows="6" cols="30"></textarea>
        </div>

        <div class="col_full hidden">
            <input type="text" id="template-contactform-botcheck" name="template-contactform-botcheck" value="" class="sm-form-control" />
        </div>

        <div class="col_full">
            <button name="submit" type="submit" id="submit-button" tabindex="5" value="Submit" class="button button-3d nomargin">Submit Comment</button>
        </div>

        </form>
    </div>

</div>
</code>```

Then I have the sendemail.php file:

```<code><?php

require_once('phpmailer/PHPMailerAutoload.php');

$toemails = array();

$toemails[] = array(
                'email' => 'myEmail@yahoo.com', // Your Email Address
                'name' => 'My Name' // Your Name
            );

// Form Processing Messages
$message_success = 'We have <strong>successfully</strong> received your Message and will get Back to you as soon as possible.';

// Add this only if you use reCaptcha with your Contact Forms
$recaptcha_secret = 'your-recaptcha-secret-key'; // Your reCaptcha Secret

$mail = new PHPMailer();

// If you intend you use SMTP, add your SMTP Code after this Line

if( $_SERVER['REQUEST_METHOD'] == 'POST' ) {
    if( $_POST['template-contactform-email'] != '' ) {

        $name = isset( $_POST['template-contactform-name'] ) ? $_POST['template-contactform-name'] : '';
        $email = isset( $_POST['template-contactform-email'] ) ? $_POST['template-contactform-email'] : '';
        $phone = isset( $_POST['template-contactform-phone'] ) ? $_POST['template-contactform-phone'] : '';
        $service = isset( $_POST['template-contactform-service'] ) ? $_POST['template-contactform-service'] : '';
        $subject = isset( $_POST['template-contactform-subject'] ) ? $_POST['template-contactform-subject'] : '';
        $message = isset( $_POST['template-contactform-message'] ) ? $_POST['template-contactform-message'] : '';

        $subject = isset($subject) ? $subject : 'New Message From Contact Form';

        $botcheck = $_POST['template-contactform-botcheck'];

        if( $botcheck == '' ) {

            $mail->SetFrom( $email , $name );
            $mail->AddReplyTo( $email , $name );
            foreach( $toemails as $toemail ) {
                $mail->AddAddress( $toemail['email'] , $toemail['name'] );
            }
            $mail->Subject = $subject;

            $name = isset($name) ? "Name: $name<br><br>" : '';
            $email = isset($email) ? "Email: $email<br><br>" : '';
            $phone = isset($phone) ? "Phone: $phone<br><br>" : '';
            $service = isset($service) ? "Service: $service<br><br>" : '';
            $message = isset($message) ? "Message: $message<br><br>" : '';

            $referrer = $_SERVER['HTTP_REFERER'] ? '<br><br><br>This Form was submitted from: ' . $_SERVER['HTTP_REFERER'] : '';

            $body = "$name $email $phone $service $message $referrer";

            // Runs only when File Field is present in the Contact Form
            if ( isset( $_FILES['template-contactform-file'] ) && $_FILES['template-contactform-file']['error'] == UPLOAD_ERR_OK ) {
                $mail->IsHTML(true);
                $mail->AddAttachment( $_FILES['template-contactform-file']['tmp_name'], $_FILES['template-contactform-file']['name'] );
            }

            // Runs only when reCaptcha is present in the Contact Form
            if( isset( $_POST['g-recaptcha-response'] ) ) {
                $recaptcha_response = $_POST['g-recaptcha-response'];
                $response = file_get_contents( "https://www.google.com/recaptcha/api/siteverify?secret=" . $recaptcha_secret . "&response=" . $recaptcha_response );

                $g_response = json_decode( $response );

                if ( $g_response->success !== true ) {
                    echo '{ "alert": "error", "message": "Captcha not Validated! Please Try Again." }';
                    die;
                }
            }

            $mail->MsgHTML( $body );
            $sendEmail = $mail->Send();

            if( $sendEmail == true ):
                echo '{ "alert": "success", "message": "' . $message_success . '" }';
            else:
                echo '{ "alert": "error", "message": "Email <strong>could not</strong> be sent due to some Unexpected Error. Please Try Again later.<br /><br /><strong>Reason:</strong><br />' . $mail->ErrorInfo . '" }';
            endif;
        } else {
            echo '{ "alert": "error", "message": "Bot <strong>Detected</strong>.! Clean yourself Botster.!" }';
        }
    } else {
        echo '{ "alert": "error", "message": "Please <strong>Fill up</strong> all the Fields and Try Again." }';
    }
} else {
    echo '{ "alert": "error", "message": "An <strong>unexpected error</strong> occured. Please Try Again later." }';
}

?>
</code>```

Which requires this autoload.php file:

```<code><?php
/**
 * PHPMailer SPL autoloader.
 * PHP Version 5
 * @package PHPMailer
 * @link https://github.com/PHPMailer/PHPMailer/ The PHPMailer GitHub project
 * @author Marcus Bointon (Synchro/coolbru) <phpmailer@synchromedia.co.uk>
 * @author Jim Jagielski (jimjag) <jimjag@gmail.com>
 * @author Andy Prevost (codeworxtech) <codeworxtech@users.sourceforge.net>
 * @author Brent R. Matzelle (original founder)
 * @copyright 2012 - 2014 Marcus Bointon
 * @copyright 2010 - 2012 Jim Jagielski
 * @copyright 2004 - 2009 Andy Prevost
 * @license http://www.gnu.org/copyleft/lesser.html GNU Lesser General Public License
 * @note This program is distributed in the hope that it will be useful - WITHOUT
 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
 * FITNESS FOR A PARTICULAR PURPOSE.
 */

/**
 * PHPMailer SPL autoloader.
 * @param string $classname The name of the class to load
 */
function PHPMailerAutoload($classname)
{
    //Can't use __DIR__ as it's only in PHP 5.3+
    $filename = dirname(__FILE__).DIRECTORY_SEPARATOR.'class.'.strtolower($classname).'.php';
    if (is_readable($filename)) {
        require $filename;
    }
}

if (version_compare(PHP_VERSION, '5.1.2', '>=')) {
    //SPL autoloading was introduced in PHP 5.1.2
    if (version_compare(PHP_VERSION, '5.3.0', '>=')) {
        spl_autoload_register('PHPMailerAutoload', true, true);
    } else {
        spl_autoload_register('PHPMailerAutoload');
    }
} else {
    /**
     * Fall back to traditional autoload for old PHP versions
     * @param string $classname The name of the class to load
     */
    function __autoload($classname)
    {
        PHPMailerAutoload($classname);
    }
}
</code>```

Edit: Looks like I must edit/change a few lines of code here and input more data.

If you are not receiving Emails from your Forms then chances are that your Server Configuration doesn't support PHP mail() function. But you can use SMTP Authentication.

So I can add the following under $mail = new PHPMailer();:

```<code>$mail->IsSMTP();
$mail->Host = "mail.yourdomain.com";
$mail->SMTPDebug = 0;
$mail->SMTPAuth = true;
$mail->Port = 26;
$mail->Username = "yourname@yourdomain.com";
$mail->Password = "yourpassword";
</code>```

This gives me a few more questions now. What's the mail in mail.yourdomain.com ? Is the User/Pass for cPanel, my Email, what?

答:
Here's how I set it up on Bluehost:</p>

```<code>function mailerExpressBlueHost(array $mailInputs){

         require_once '../includes/phpmailer/PHPMailerAutoload.php';

         $mail = new PHPMailer();
         $mail->IsMail();

         $mail->SetFrom('skipper@yourdomain.com'); // make sure this is an andress
                                                 // on your domain
         $mail->IsHTML(true);
         $mail->addAddress($mailInputs['addAddress']);
         $body = $mailInputs['body'] ;
         $mail->isHTML(true);
         $mail->Subject = $mailInputs['subject'] ;
         $mail->Body    = $body;

         if(!$mail->send()) {
            return 'Message could not be sent.' . 'Mailer Error: ' . $mail->ErrorInfo;
         } else {
            return 'Message has been sent';
         }

          $mail->ClearAddresses();
}
</code>```

Title: Contact Form Sending Error

Body:
I'm screwing around with a template and just trying to get my contact form to work (in attempt to see how it works, sends messages, etc.). When filling out my contact form and then hitting submit, instead of it going through successfully, one of the errors pops up:

Email could not be sent due to some Unexpected Error. Please Try Again later.

Reason:
Could not instantiate mail function.

http://prntscr.com/fh5cct

Here's my contact form in HTML:

Send us an Email

        <form class="nobottommargin" id="template-contactform" name="template-contactform" action="include/sendemail.php" method="post">

            Name *
            <input type="text" id="template-contactform-name" name="template-contactform-name" value="" class="sm-form-control required" />

            Email *
            <input type="email" id="template-contactform-email" name="template-contactform-email" value="" class="required email sm-form-control" />

            Phone
            <input type="text" id="template-contactform-phone" name="template-contactform-phone" value="" class="sm-form-control" />

            Subject *
            <input type="text" id="template-contactform-subject" name="template-contactform-subject" value="" class="required sm-form-control" />

            Message *
            <textarea class="required sm-form-control" id="template-contactform-message" name="template-contactform-message" rows="6" cols="30"></textarea>

            <input type="text" id="template-contactform-botcheck" name="template-contactform-botcheck" value="" class="sm-form-control" />

            <button name="submit" type="submit" id="submit-button" tabindex="5" value="Submit" class="button button-3d nomargin">Submit Comment</button>

        </form>

Then I have the sendemail.php file:

<?php

require_once('phpmailer/PHPMailerAutoload.php');

$toemails = array();

$toemails[] = array(
                'email' => 'myEmail@yahoo.com', // Your Email Address
                'name' => 'My Name' // Your Name
            );

// Form Processing Messages
$message_success = 'We have successfully received your Message and will get Back to you as soon as possible.';

// Add this only if you use reCaptcha with your Contact Forms
$recaptcha_secret = 'your-recaptcha-secret-key'; // Your reCaptcha Secret

$mail = new PHPMailer();

// If you intend you use SMTP, add your SMTP Code after this Line

if( $_SERVER['REQUEST_METHOD'] == 'POST' ) {
    if( $_POST['template-contactform-email'] != '' ) {

        $name = isset( $_POST['template-contactform-name'] ) ? $_POST['template-contactform-name'] : '';
        $email = isset( $_POST['template-contactform-email'] ) ? $_POST['template-contactform-email'] : '';
        $phone = isset( $_POST['template-contactform-phone'] ) ? $_POST['template-contactform-phone'] : '';
        $service = isset( $_POST['template-contactform-service'] ) ? $_POST['template-contactform-service'] : '';
        $subject = isset( $_POST['template-contactform-subject'] ) ? $_POST['template-contactform-subject'] : '';
        $message = isset( $_POST['template-contactform-message'] ) ? $_POST['template-contactform-message'] : '';

        $subject = isset($subject) ? $subject : 'New Message From Contact Form';

        $botcheck = $_POST['template-contactform-botcheck'];

        if( $botcheck == '' ) {

            $mail->SetFrom( $email , $name );
            $mail->AddReplyTo( $email , $name );
            foreach( $toemails as $toemail ) {
                $mail->AddAddress( $toemail['email'] , $toemail['name'] );
            }
            $mail->Subject = $subject;

            $name = isset($name) ? "Name: $name

" : '';
            $email = isset($email) ? "Email: $email

" : '';
            $phone = isset($phone) ? "Phone: $phone

" : '';
            $service = isset($service) ? "Service: $service

" : '';
            $message = isset($message) ? "Message: $message

" : '';

            $referrer = $_SERVER['HTTP_REFERER'] ? '

This Form was submitted from: ' . $_SERVER['HTTP_REFERER'] : '';

            $body = "$name $email $phone $service $message $referrer";

            // Runs only when File Field is present in the Contact Form
            if ( isset( $_FILES['template-contactform-file'] ) && $_FILES['template-contactform-file']['error'] == UPLOAD_ERR_OK ) {
                $mail->IsHTML(true);
                $mail->AddAttachment( $_FILES['template-contactform-file']['tmp_name'], $_FILES['template-contactform-file']['name'] );
            }

            // Runs only when reCaptcha is present in the Contact Form
            if( isset( $_POST['g-recaptcha-response'] ) ) {
                $recaptcha_response = $_POST['g-recaptcha-response'];
                $response = file_get_contents( "https://www.google.com/recaptcha/api/siteverify?secret=" . $recaptcha_secret . "&response=" . $recaptcha_response );

                $g_response = json_decode( $response );

                if ( $g_response->success !== true ) {
                    echo '{ "alert": "error", "message": "Captcha not Validated! Please Try Again." }';
                    die;
                }
            }

            $mail->MsgHTML( $body );
            $sendEmail = $mail->Send();

            if( $sendEmail == true ):
                echo '{ "alert": "success", "message": "' . $message_success . '" }';
            else:
                echo '{ "alert": "error", "message": "Email could not be sent due to some Unexpected Error. Please Try Again later.

Reason:
' . $mail->ErrorInfo . '" }';
            endif;
        } else {
            echo '{ "alert": "error", "message": "Bot Detected.! Clean yourself Botster.!" }';
        }
    } else {
        echo '{ "alert": "error", "message": "Please Fill up all the Fields and Try Again." }';
    }
} else {
    echo '{ "alert": "error", "message": "An unexpected error occured. Please Try Again later." }';
}

?>

Which requires this autoload.php file:

<?php
/**
 * PHPMailer SPL autoloader.
 * PHP Version 5
 * @package PHPMailer
 * @link https://github.com/PHPMailer/PHPMailer/ The PHPMailer GitHub project
 * @author Marcus Bointon (Synchro/coolbru) <phpmailer@synchromedia.co.uk>
 * @author Jim Jagielski (jimjag) <jimjag@gmail.com>
 * @author Andy Prevost (codeworxtech) <codeworxtech@users.sourceforge.net>
 * @author Brent R. Matzelle (original founder)
 * @copyright 2012 - 2014 Marcus Bointon
 * @copyright 2010 - 2012 Jim Jagielski
 * @copyright 2004 - 2009 Andy Prevost
 * @license http://www.gnu.org/copyleft/lesser.html GNU Lesser General Public License
 * @note This program is distributed in the hope that it will be useful - WITHOUT
 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
 * FITNESS FOR A PARTICULAR PURPOSE.
 */

/**
 * PHPMailer SPL autoloader.
 * @param string $classname The name of the class to load
 */
function PHPMailerAutoload($classname)
{
    //Can't use __DIR__ as it's only in PHP 5.3+
    $filename = dirname(__FILE__).DIRECTORY_SEPARATOR.'class.'.strtolower($classname).'.php';
    if (is_readable($filename)) {
        require $filename;
    }
}

if (version_compare(PHP_VERSION, '5.1.2', '>=')) {
    //SPL autoloading was introduced in PHP 5.1.2
    if (version_compare(PHP_VERSION, '5.3.0', '>=')) {
        spl_autoload_register('PHPMailerAutoload', true, true);
    } else {
        spl_autoload_register('PHPMailerAutoload');
    }
} else {
    /**
     * Fall back to traditional autoload for old PHP versions
     * @param string $classname The name of the class to load
     */
    function __autoload($classname)
    {
        PHPMailerAutoload($classname);
    }
}

Edit: Looks like I must edit/change a few lines of code here and input more data.

If you are not receiving Emails from your Forms then chances are that your Server Configuration doesn't support PHP mail() function. But you can use SMTP Authentication.

So I can add the following under $mail = new PHPMailer();:

$mail->IsSMTP();
$mail->Host = "mail.yourdomain.com";
$mail->SMTPDebug = 0;
$mail->SMTPAuth = true;
$mail->Port = 26;
$mail->Username = "yourname@yourdomain.com";
$mail->Password = "yourpassword";

This gives me a few more questions now. What's the mail in mail.yourdomain.com ? Is the User/Pass for cPanel, my Email, what?

Body:
Here's how I set it up on Bluehost:

function mailerExpressBlueHost(array $mailInputs){

         require_once '../includes/phpmailer/PHPMailerAutoload.php';

         $mail = new PHPMailer();
         $mail->IsMail();

         $mail->SetFrom('skipper@yourdomain.com'); // make sure this is an andress
                                                 // on your domain
         $mail->IsHTML(true);
         $mail->addAddress($mailInputs['addAddress']);
         $body = $mailInputs['body'] ;
         $mail->isHTML(true);
         $mail->Subject = $mailInputs['subject'] ;
         $mail->Body    = $body;

         if(!$mail->send()) {
            return 'Message could not be sent.' . 'Mailer Error: ' . $mail->ErrorInfo;
         } else {
            return 'Message has been sent';
         }

          $mail->ClearAddresses();
}


来源: stackexchange

问:
Eclipse/Maven showing errors on project creation
I'm trying to learn something new by following a tutorial, but I can't even get started with project creation. I'm very new to Maven, so I don't know how to fix this. I'm using Eclipse Mars.2 Release (4.5.2) and I have Maven 3.2.5 installed on a windows 10 machine (also, JDK 1.8.0.131 is set).

The thing is, I can create a new Maven project by going to New > Other > Maven Project > Check "create simple project" > enter a Group ID, Artifact ID and click Finish. But thn I get presented with a "Setup Maven plugin connectors" dialog and the pom.xml file shows more errors.

I've read posts of other people having this problem but they were trying to import a project, or they were using other frameworks like spring. I'm just trying to create a plain, simple Maven project from scratch.

I've also read that Maven comes bundled with Eclipse now, so I went to  Window > Preferences > Maven > Installation and saw that I had "Embedded" selected and "Workspace" showing up as "not available". So I added (not sure if did it right) my maven home directory:

I deleted the project, restarted Eclipse, then started all over. Still, nothing changed.

I also tried selecting one of the options in the "Setup Maven plugin connectors" dialog from the "Action" column, and it installed some annotations and other stuff. Still, no good.

From pom.xml I get the suggestion to install connectors, but I have no clue as to what to install.

Anything else I can try? Thanks.

答: Well, apparently the problem was that I had a custom settings.xml file I had inherited from a previous installation (work-related) in my .m2 folder. I removed it so now I could use the general settings file. Then I updated and cleaned the project within Eclipse and it seems to be working now.</p>

ContentLicense: CC BY-SA 3.0


问:
Python crawl : select text from
I have a problem with learning python crawl as follow:

```<code>from bs4 import  BeautifulSoup
import requests

url = 'http://www.zhipin.com/job_detail/1411924978.html'

result = requests.get(url)
soup = BeautifulSoup(result.text,'lxml').select('#main > div.job-banner > div > div > div.info-company > p')

print(soup[1])

print(soup[1].get_text())
</code>```

the result is :

```<code><p>IT软件<em class="vline"></em>已上市<em class="vline"></em>10000人以上</p>

IT软件已上市10000人以上
</code>```

But what I want print(soup[1].get_text()) is like this :

IT软件 已上市 10000人以上

or

```<code>IT软件
已上市
10000人以上
</code>```

How can I to write the codes?

Thanks so much !

答:
You can try:

```<code>print soup[1].getText(separator=u' ') # space separator
print soup[1].getText(separator=u'\n') # newline separator
</code>```

The output is:

```<code>>>> print soup[1].getText(separator=u' ')
IT软件 已上市 10000人以上
>>> print soup[1].getText(separator=u'\n')
IT软件
已上市
10000人以上
</code>```

Source: another SO answer => Please research your problem before asking a question.

Title: Python crawl : select text from

Body:
I have a problem with learning python crawl as follow:

from bs4 import  BeautifulSoup
import requests

url = 'http://www.zhipin.com/job_detail/1411924978.html'

result = requests.get(url)
soup = BeautifulSoup(result.text,'lxml').select('#main > div.job-banner > div > div > div.info-company > p')

print(soup[1])

print(soup[1].get_text())

the result is :

IT软件已上市10000人以上

IT软件已上市10000人以上

But what I want print(soup[1].get_text()) is like this :

IT软件 已上市 10000人以上

or

IT软件
已上市
10000人以上

How can I to write the codes?

Thanks so much !

Body:
You can try:

print soup[1].getText(separator=u' ') # space separator
print soup[1].getText(separator=u'\n') # newline separator

The output is:

>>> print soup[1].getText(separator=u' ')
IT软件 已上市 10000人以上
>>> print soup[1].getText(separator=u'\n')
IT软件
已上市
10000人以上

Source: another SO answer => Please research your problem before asking a question.


问:
Find frequency of vector elements in a matrix
I have a matrix in R, here is a small example:

```<code>set.seed(1)
n.columns<-6
mat <- matrix(, nrow = 5, ncol = n.columns)
for(column in 1:n.columns){
  mat[, column] <- sample(1:10,5)
}
mat
</code>```

The matrix looks like this:

```<code>     [,1] [,2] [,3] [,4] [,5] [,6]
[1,]    3    9    3    5   10    4
[2,]    4   10    2    7    2    1
[3,]    5    6    6    8    6   10
[4,]    7    5   10    3    1    7
[5,]    2    1    5   10    9    3
</code>```

I also have a vector v of integers, v<-c(1,3,6), whose elements could theoretically appear in the matrix mat above.

What I am looking for is an overview of the number of times that each element in v appears in mat per column. For the current example this overview is

```<code>1: 0 1 0 0 1 1
3: 1 0 1 1 0 1
6: 0 1 1 0 1 0
</code>```

It is fairly straightforward to do this using for-loops and if-statements, but this solution is not very pretty.

Is there a professional way to do this?

Body:
I have a matrix in R, here is a small example:

set.seed(1)
n.columns<-6
mat <- matrix(, nrow = 5, ncol = n.columns)
for(column in 1:n.columns){
  mat[, column] <- sample(1:10,5)
}
mat

The matrix looks like this:

     [,1] [,2] [,3] [,4] [,5] [,6]
[1,]    3    9    3    5   10    4
[2,]    4   10    2    7    2    1
[3,]    5    6    6    8    6   10
[4,]    7    5   10    3    1    7
[5,]    2    1    5   10    9    3

I also have a vector v of integers, v<-c(1,3,6), whose elements could theoretically appear in the matrix mat above.

What I am looking for is an overview of the number of times that each element in v appears in mat per column. For the current example this overview is

1: 0 1 0 0 1 1
3: 1 0 1 1 0 1
6: 0 1 1 0 1 0

It is fairly straightforward to do this using for-loops and if-statements, but this solution is not very pretty.

Is there a professional way to do this?

Body:
One option using sapply:

t(sapply(v, function(a) colSums(mat==a)))

#     [,1] [,2] [,3] [,4] [,5] [,6]
#[1,]    0    1    0    0    1    1
#[2,]    1    0    1    1    0    1
#[3,]    0    1    1    0    1    0


问:
how to force break words that exceed width of parent div
i am running into an issue that i do not think is possible with css. i have a text output dynamically showing in a label that only has the following html

label {
width:94px;
}

i am trying to come up with a solution that will dynamically take any mutliple word that exceeds the width of the div, and force break that word. if a word is to be split but could fit on its own line without breaking within the text, then wrap it to the next line

an example of this working fine as is would be the following screenshot:

here is the current scenario where a letter inside a word is pushed to the next line:

here is what i would like to happen in this scenario:

any help would be greatly appreciated. i am very curious if this is even possible with css without a lot of hacks and cross-browser issues...

答: you can try word-wrap:break-word; or  word-break:break-all;


问:
variable as Post_type in wp_query - Wordpress
I have a question regarding Wordpress and selective post type selection.

I am building a template but I am trying to make a function with ACF that when someone makes a page they can select which post type they want to show on this page.

I made a variable with the following in it:

```<code>$p = the_field('post_typer');
</code>```

This variable is getting his value when a user is making a page and selects which post type he wants to show.

```<code> $p = the_field('post_typer');

    // WP_Query arguments
    $args = array(
        'post_type' =>  $p,
);
</code>```

I am wondering why this is not working:

```<code>'post_type' =>  $p,
</code>```

Please help

答:
Depending on the type of field you have, you should be doing get_field

```<code>$p = get_field('post_typer');

// WP_Query arguments
$args = array(
    'post_type' =>  $p,
);
</code>```

https://www.advancedcustomfields.com/resources/get_field/

Body:
I have a question regarding Wordpress and selective post type selection.

I am building a template but I am trying to make a function with ACF that when someone makes a page they can select which post type they want to show on this page.

I made a variable with the following in it:

$p = the_field('post_typer');

This variable is getting his value when a user is making a page and selects which post type he wants to show.

 $p = the_field('post_typer');

    // WP_Query arguments
    $args = array(
        'post_type' =>  $p,
);

I am wondering why this is not working:

'post_type' =>  $p,

Please help

Body:
Depending on the type of field you have, you should be doing get_field

$p = get_field('post_typer');

// WP_Query arguments
$args = array(
    'post_type' =>  $p,
);

https://www.advancedcustomfields.com/resources/get_field/


问:
Find the Key from multiple values array in PHP
I am trying to find the key of which one of the children items exists in. I have this array

```<code>$stdCurl    = array(
    'homepage'  => array('', '/', 'index.php', 'home', 'arxiki'),
    'blog'      => array('αρθρα', 'blog'),
    'post'      => array('αρθρο', '*post'),
    'products'  => array('προιοντα', 'products'),
    'product'   => array('προιον', 'product'),
    'portfolio' => array('portfolio', 'έργα'),
    'project'   => array('project', 'έργο')
);
</code>```

User have selected the "post" value (marked with *). Now i want to find to which key "post" belongs to. I tried array_search, array_keys but can't make it work..I don't wont to loop, i was wondering if there is any built-in function for arrays for this..

Edited__

Basically i found the answer for my code, i just did not posted it because i wanted to know if there is really any way for this..
The reason i want this is because i parse the url and want to see if any of the keywords "index.php", "home", "product" etc exists in the url and if they exists i wanted to get the section these keywords belong to.

Let's say url is http://domain.gr/gear-s3-samsung/product.  I parse the url and explode it on "/", now i want to know if a keyword exists and if a keyword exists, return me the key that the keyword exists in from $stdCurl array.

```<code>foreach($this->stdCurl as $key => $value):
    foreach($value as $definedSection):
        if(in_array($definedSection, $this->urlStructure)):
            $this->pageKey = $key;
            $this->pageSection = $definedSection;
        else:
            continue;
        endif;
    endforeach;
endforeach;
</code>```

Now i get they $key and shows me the section the keyword exists..But i wanted to know if i give you the value "αρθρο" how can i get the "post" key?

答:
What I understood is: To find "key" for the inner array search.

Code:

```<code><?php

$stdCurl    = array(
  'homepage'  => array('', '/', 'index.php', 'home', 'arxiki'),
  'blog'      => array('αρθρα', 'blog'),
  'post'      => array('αρθρο', '*post'),
  'products'  => array('προιοντα', 'products'),
  'product'   => array('προιον', 'product'),
  'portfolio' => array('portfolio', 'έργα'),
  'project'   => array('project', 'έργο')
);

function array_search_key ($array, $val) {
  if (!is_array($array)){
    return false;
  }

  foreach ($array as $key => $inner_array) {
    if(in_array($val, $inner_array)){
      return $key;
    }
  }
  return false;
}

$key = array_search_key($stdCurl, 'προιον');

echo $key; //product

?>
</code>```

Quick Look:

Get key of multidimensional array?

Body:
I am trying to find the key of which one of the children items exists in. I have this array

$stdCurl    = array(
    'homepage'  => array('', '/', 'index.php', 'home', 'arxiki'),
    'blog'      => array('αρθρα', 'blog'),
    'post'      => array('αρθρο', '*post'),
    'products'  => array('προιοντα', 'products'),
    'product'   => array('προιον', 'product'),
    'portfolio' => array('portfolio', 'έργα'),
    'project'   => array('project', 'έργο')
);

User have selected the "post" value (marked with *). Now i want to find to which key "post" belongs to. I tried array_search, array_keys but can't make it work..I don't wont to loop, i was wondering if there is any built-in function for arrays for this..

Edited__

Basically i found the answer for my code, i just did not posted it because i wanted to know if there is really any way for this..
The reason i want this is because i parse the url and want to see if any of the keywords "index.php", "home", "product" etc exists in the url and if they exists i wanted to get the section these keywords belong to.

Let's say url is http://domain.gr/gear-s3-samsung/product.  I parse the url and explode it on "/", now i want to know if a keyword exists and if a keyword exists, return me the key that the keyword exists in from $stdCurl array.

foreach($this->stdCurl as $key => $value):
    foreach($value as $definedSection):
        if(in_array($definedSection, $this->urlStructure)):
            $this->pageKey = $key;
            $this->pageSection = $definedSection;
        else:
            continue;
        endif;
    endforeach;
endforeach;

Now i get they $key and shows me the section the keyword exists..But i wanted to know if i give you the value "αρθρο" how can i get the "post" key?

Body:
What I understood is: To find "key" for the inner array search.

Code:

<?php

$stdCurl    = array(
  'homepage'  => array('', '/', 'index.php', 'home', 'arxiki'),
  'blog'      => array('αρθρα', 'blog'),
  'post'      => array('αρθρο', '*post'),
  'products'  => array('προιοντα', 'products'),
  'product'   => array('προιον', 'product'),
  'portfolio' => array('portfolio', 'έργα'),
  'project'   => array('project', 'έργο')
);

function array_search_key ($array, $val) {
  if (!is_array($array)){
    return false;
  }

  foreach ($array as $key => $inner_array) {
    if(in_array($val, $inner_array)){
      return $key;
    }
  }
  return false;
}

$key = array_search_key($stdCurl, 'προιον');

echo $key; //product

?>

Quick Look:

Get key of multidimensional array?


问:
HTTP Request processing in IIS
To understand how IIS processes a request, I have used the diagram here: https://blogs.iis.net/tomwoolums/iis-7-0-http-request-processing

My questions:

Is step 1 until 5 executed for every request or only for the very first request?

Who is actually sending the request to the application pool? WAS? Or does WAS only create/map the worker process for the request and HTTP.sys sends the actual request to the worker process? If WAS sends the actual request, why would we need to configure the HTTP.sys if the request is passed to WAS, which already knows the configuration?

Am I right if I say: The application pool passes the response directly to the HTTP.sys?

答:
Step 1-5 is generally speaking executed once for multiple requests. When you change certain settings in IIS configuration, then a new request will trigger step 1-5 again.

Requests only go through http.sys and worker processes. WAS only manages worker process lifecycle, and that's why it is called Windows Process Activation Service.

Correct.

Title: HTTP Request processing in IIS


问:
Visual Studio: How can I see the same file in two separate tab groups?
I want to be able to edit one method while looking at another method in the same file, as reference.
Can this be done?</p>

答: Only vertically that I'm aware.  When looking at the code, right above the vertical scroll bar is a small rectangle, drag it down to get a split view of the file.</p>

OwnerDisplayName: Ofer

ContentLicense: CC BY-SA 2.5

OwnerDisplayName: ctacke


问:
How to handle unknown UILabel height and its effect on labels underneath in Interface Builder?
I have two UILabels in a XIB file, one on top of the other, the contents of which are loaded from a JSON source file on the net.

Given that I'm unsure of the number of lines the labels will take up, and hence the height, how best should I position these relative to each other.

I know in some Java GUI frameworks, one can use various container elements, and in HTML this flow of layout would be the default, but I can't find anything that would seem to do the trick.

Can I do this in Interface Builder, or does this have to be done programmatically?

Thanks for your help..

Edit:

I now have the answer, although it may not be perfect. I have two labels, titleLabel above descLabel. This is how I achieved it:

```<code>titleLabel.text = [data objectForKey:@"title"];
descLabel.text  = [data objectForKey:@"description"];

CGSize s;
s.width = descLabel.frame.size.width;
s.height = 10000;

titleLabel.frame = CGRectMake(titleLabel.frame.origin.x,
                             titleLabel.frame.origin.y,
                             titleLabel.frame.size.width,
                             [[data objectForKey:@"title"] sizeWithFont:titleLabel.font constrainedToSize: s lineBreakMode:titleLabel.lineBreakMode].height
                             );

descLabel.frame = CGRectMake(descLabel.frame.origin.x,
                             titleLabel.frame.origin.y + [[data objectForKey:@"title"] sizeWithFont:titleLabel.font constrainedToSize: s lineBreakMode:titleLabel.lineBreakMode].height + 10,
                             descLabel.frame.size.width,
                             [[data objectForKey:@"description"] sizeWithFont:descLabel.font constrainedToSize: s lineBreakMode:descLabel.lineBreakMode].height
                             );
</code>```

weffew

答: You’ll have to do this programatically. The NSString method -sizeWithFont:constrainedToSize:lineBreakMode: (which is actually in a UIKit category) will be of particular use for this.

Body:
I have two UILabels in a XIB file, one on top of the other, the contents of which are loaded from a JSON source file on the net.

Given that I'm unsure of the number of lines the labels will take up, and hence the height, how best should I position these relative to each other.

I know in some Java GUI frameworks, one can use various container elements, and in HTML this flow of layout would be the default, but I can't find anything that would seem to do the trick.

Can I do this in Interface Builder, or does this have to be done programmatically?

Thanks for your help..

Edit:

I now have the answer, although it may not be perfect. I have two labels, titleLabel above descLabel. This is how I achieved it:

titleLabel.text = [data objectForKey:@"title"];
descLabel.text  = [data objectForKey:@"description"];

CGSize s;
s.width = descLabel.frame.size.width;
s.height = 10000;

titleLabel.frame = CGRectMake(titleLabel.frame.origin.x,
                             titleLabel.frame.origin.y,
                             titleLabel.frame.size.width,
                             [[data objectForKey:@"title"] sizeWithFont:titleLabel.font constrainedToSize: s lineBreakMode:titleLabel.lineBreakMode].height
                             );

descLabel.frame = CGRectMake(descLabel.frame.origin.x,
                             titleLabel.frame.origin.y + [[data objectForKey:@"title"] sizeWithFont:titleLabel.font constrainedToSize: s lineBreakMode:titleLabel.lineBreakMode].height + 10,
                             descLabel.frame.size.width,
                             [[data objectForKey:@"description"] sizeWithFont:descLabel.font constrainedToSize: s lineBreakMode:descLabel.lineBreakMode].height
                             );

weffew


问:
RxJava convert byte array to Bitmap
Sorry for my english. Now i learning rxJava 1 and try convert byte[] to Bitmap and set it to imageview. But it work slowly. Do i right work whith rxJava? ps: i chek and asynkTask work fater than rxJava, how it possible? </p>

```<code>Observable.just(data)
                .map(new Func1<byte[], Bitmap>() {
                    @Override
                    public Bitmap call(byte[] bytes) {
                        BitmapFactory.Options options = new BitmapFactory.Options();
                        options.inJustDecodeBounds = false;
                        options.inPreferredConfig = Bitmap.Config.RGB_565;
                        options.inDither = true;
                        options.inMutable = true;

                        Bitmap largeBitmap = BitmapFactory.decodeByteArray(data, 0, data.length, options);
                        Bitmap bitmap = Bitmap.createScaledBitmap(largeBitmap
                                , (int) ((float) largeBitmap.getWidth() / 10)
                                , (int) ((float) largeBitmap.getHeight() / 10)
                                , true);

                        if (bitmap.getWidth() > bitmap.getHeight()) {
                            Matrix matrix = new Matrix();
                            matrix.postRotate(90); // anti-clockwise by 90 degrees

                            bitmap = Bitmap.createBitmap(bitmap, 0, 0, bitmap.getWidth(), bitmap.getHeight(), matrix, true);
                        }

                        float k = (float) bitmap.getWidth() / (float) w_target;

                        if (w_target < bitmap.getWidth()) {
                            bitmap = Bitmap.createScaledBitmap(bitmap, w_target, (int) ((float) bitmap.getHeight() / k), true);
                        }

                        return createBlackAndWhite(bitmap);
                    }
                })
                .observeOn(Schedulers.io())
                .subscribeOn(AndroidSchedulers.mainThread())
                .subscribe(new Action1<Bitmap>() {
                    @Override
                    public void call(Bitmap bitmap) {
                        imageview.setImageBitmap(bitmap);
                    }
                });
</code>```

答:
invert the schedulers to

```<code>.observeOn(AndroidSchedulers.mainThread())
.subscribeOn(Schedulers.io())
</code>```

the thread you observe on is the one in which imageView.setBitmap() will be called, subscribeOn on the other hand will set the thread for the bitmap manipulation

Title: RxJava convert byte array to Bitmap

Body:
Sorry for my english. Now i learning rxJava 1 and try convert byte[] to Bitmap and set it to imageview. But it work slowly. Do i right work whith rxJava? ps: i chek and asynkTask work fater than rxJava, how it possible?

Observable.just(data)
                .map(new Func1<byte[], Bitmap>() {
                    @Override
                    public Bitmap call(byte[] bytes) {
                        BitmapFactory.Options options = new BitmapFactory.Options();
                        options.inJustDecodeBounds = false;
                        options.inPreferredConfig = Bitmap.Config.RGB_565;
                        options.inDither = true;
                        options.inMutable = true;

                        Bitmap largeBitmap = BitmapFactory.decodeByteArray(data, 0, data.length, options);
                        Bitmap bitmap = Bitmap.createScaledBitmap(largeBitmap
                                , (int) ((float) largeBitmap.getWidth() / 10)
                                , (int) ((float) largeBitmap.getHeight() / 10)
                                , true);

                        if (bitmap.getWidth() > bitmap.getHeight()) {
                            Matrix matrix = new Matrix();
                            matrix.postRotate(90); // anti-clockwise by 90 degrees

                            bitmap = Bitmap.createBitmap(bitmap, 0, 0, bitmap.getWidth(), bitmap.getHeight(), matrix, true);
                        }

                        float k = (float) bitmap.getWidth() / (float) w_target;

                        if (w_target < bitmap.getWidth()) {
                            bitmap = Bitmap.createScaledBitmap(bitmap, w_target, (int) ((float) bitmap.getHeight() / k), true);
                        }

                        return createBlackAndWhite(bitmap);
                    }
                })
                .observeOn(Schedulers.io())
                .subscribeOn(AndroidSchedulers.mainThread())
                .subscribe(new Action1<Bitmap>() {
                    @Override
                    public void call(Bitmap bitmap) {
                        imageview.setImageBitmap(bitmap);
                    }
                });

Body:
invert the schedulers to

.observeOn(AndroidSchedulers.mainThread())
.subscribeOn(Schedulers.io())

the thread you observe on is the one in which imageView.setBitmap() will be called, subscribeOn on the other hand will set the thread for the bitmap manipulation


问:
SonarQube says critical bug : provide an 'AssemblyVersion' attribute for this assembly 36 times
I am using SonarQube for the first time and a scan of my project revealed 38 bugs.
36 are the same bug:

Provide an 'AssemblyVersion' attribute for this assembly.

SonarQube says to resolve this bug I need to add

```<code>[assembly: AssemblyTitle("MyAssembly")]
[assembly: AssemblyVersionAttribute("1.2.125.0")]
</code>```

before the namespace in each of the 36 files...

However, when I add it to even one file (With the correct title and version number) I get these errors in Visual Studio:

I read this questions and its answers and am more confused than before.
I read this article about "The right way to version your assemblies" and moved my projects' AssemblyInfo.cs into a linked VersionInfo.cs file like the article suggested.

At this point I am at a loss, how do I fix these 36 bugs? What is the best practice for providing Assembly Version?

答:
The rule is checking the assembly-level attributes that are already compiled and you should be able to follow the pattern with a linked AssemblyInfo.cs.

I think you are experiencing a bug with the issue reporting on our side, we have an open ticket about it and we are aiming at providing a fix at the end of the next week. If that's the case, you should be seeing much less reported errors with SonarLint for Visual Studio.

Body:
I am using SonarQube for the first time and a scan of my project revealed 38 bugs.
36 are the same bug:

Provide an 'AssemblyVersion' attribute for this assembly.

SonarQube says to resolve this bug I need to add

[assembly: AssemblyTitle("MyAssembly")]
[assembly: AssemblyVersionAttribute("1.2.125.0")]

before the namespace in each of the 36 files...

However, when I add it to even one file (With the correct title and version number) I get these errors in Visual Studio:

I read this questions and its answers and am more confused than before.
I read this article about "The right way to version your assemblies" and moved my projects' AssemblyInfo.cs into a linked VersionInfo.cs file like the article suggested.

At this point I am at a loss, how do I fix these 36 bugs? What is the best practice for providing Assembly Version?


问:
Content Security Policy directive: "script-src 'none' Violation Error
I have just installed MAMP and created 2 files in the htdocs folder:

index.html

```<code><!doctype html>
<html>
    <body>Test Page</body>
    <script src="script.js"></script>
</html>
</code>```

script.js

```<code>console.log("works");
</code>```

MAMP is configured to the following ports:

Apache Port: 8888

Nginx port: 7888

MySQL port: 8889

Opening localhost:8888 gives the following error in console:

Refused to load the script 'http://localhost:8888/script.js' because it violates the following Content Security Policy directive: "script-src 'none'".

I have never encountered CSP before, so this has left me bewildered. What is causing this issue?

答: Turns out the cause of this problem was the browser ScriptSafe extension which was turned on. Disabling it solved the issue</p>

Body:
I have just installed MAMP and created 2 files in the htdocs folder:

index.html

<!doctype html>

    Test Page

script.js

console.log("works");

MAMP is configured to the following ports:

Apache Port: 8888

Nginx port: 7888

MySQL port: 8889

Opening localhost:8888 gives the following error in console:

Refused to load the script 'http://localhost:8888/script.js' because it violates the following Content Security Policy directive: "script-src 'none'".

I have never encountered CSP before, so this has left me bewildered. What is causing this issue?


问:
Does a foreign key reduce redundancy if all the columns are referenced?
I've read that one of the benefits of normalization is to reduce redundancy in the DB. But I'm wondering, if you end up referencing all the columns in the target table?

For example, if I have a Video table that references a Genre table, the Genre table might very likely have a single column with a dozen fairly static values like 'Horror' 'Sci-Fi' 'Romance' etc.

In a case like this, does it save any space to separate the two, or is the only benefit making it so you can update all referencing rows from one place?

答: Yes, it will save space if you have a surrogate key (int) which you use in the video table instead of the varchar(20) or whatever the genra would be. </p>


问:
Create new Object Class in OpenDJ (LDAP) from JAVA
I have to create a custom Object Class in LDAP server from java JNDI. The object class should have 3 fields with values: Name, OID, Description. So far
I have managed to only define the environment.</p>

```<code>Properties properties = new Properties();

    properties.put(Context.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.ldap.LdapCtxFactory");
    properties.put(Context.PROVIDER_URL, ldapUrl);
    properties.put(Context.REFERRAL, "ignore");
    properties.put(Context.SECURITY_PRINCIPAL, dirManagerUser);
    properties.put(Context.SECURITY_CREDENTIALS, password);

    DirContext ctx = new InitialDirContext(properties);

    //NEW CUSTOM OBJECT CREATION SHOULD GO HERE

    ctx.close();
</code>```

答:
I found a solution:</p>

```<code>BasicAttribute attribute = new BasicAttribute("objectClasses");
        attribute.add(parameters);
        attributes.put(attribute);
        context.modifyAttributes("cn=schema",DirContext.ADD_ATTRIBUTE, attributes);
        context.close();
</code>```

Body:
I have to create a custom Object Class in LDAP server from java JNDI. The object class should have 3 fields with values: Name, OID, Description. So far
I have managed to only define the environment.

Properties properties = new Properties();

    properties.put(Context.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.ldap.LdapCtxFactory");
    properties.put(Context.PROVIDER_URL, ldapUrl);
    properties.put(Context.REFERRAL, "ignore");
    properties.put(Context.SECURITY_PRINCIPAL, dirManagerUser);
    properties.put(Context.SECURITY_CREDENTIALS, password);

    DirContext ctx = new InitialDirContext(properties);

    //NEW CUSTOM OBJECT CREATION SHOULD GO HERE

    ctx.close();

Body:
I found a solution:

BasicAttribute attribute = new BasicAttribute("objectClasses");
        attribute.add(parameters);
        attributes.put(attribute);
        context.modifyAttributes("cn=schema",DirContext.ADD_ATTRIBUTE, attributes);
        context.close();


问:
Joining 2 PDFs using Python join.py results in blank PDF
When I run join.py on computer A, I get a properly joined 2 page PDF. When running it on computers B and C, I get a one page blank PDF. All three computers are MacBook Pros running 10.10.1

Running the following command from Script Editor, no errors occur:

```<code>do shell script "python '/System/Library/Automator/Combine PDF Pages.action/Contents/Resources/join.py' -o '/Volumes/SSD/Users/username/Desktop/CD123AD9-77DB-4678-B301-9498CFD4E344/Welcome Packet.pdf' /Volumes/SSD/Users/username/Desktop/CD123AD9-77DB-4678-B301-9498CFD4E344/*.pdf"
</code>```

Any ideas on what is causing the joined PDF to come out as 1 page and blank?

答:
This is an old post, but i had the exact same problem. After a lot of different attempts, eventually i managed to solve it (with the help of SO users ofc - thanks Marcomdm) in the following way:

I created a string with the necessary command parameters laid out:

```<code>stringToCall = "%s %s %s%s" % ("./join.py -o", endPdf, pdfInputDir,"/*.pdf")
        os.chdir(/System/Library/Automator/Combine PDF Pages.action/Contents/Resources/)
        os.system(stringToCall)
</code>```

where endPdf is the final pdf name coming from
endPdf = os.path.join (pdfOutputDir, pdfName+".pdf")

Worked like a charm. Hope this helps.

Body:
When I run join.py on computer A, I get a properly joined 2 page PDF. When running it on computers B and C, I get a one page blank PDF. All three computers are MacBook Pros running 10.10.1

Running the following command from Script Editor, no errors occur:

do shell script "python '/System/Library/Automator/Combine PDF Pages.action/Contents/Resources/join.py' -o '/Volumes/SSD/Users/username/Desktop/CD123AD9-77DB-4678-B301-9498CFD4E344/Welcome Packet.pdf' /Volumes/SSD/Users/username/Desktop/CD123AD9-77DB-4678-B301-9498CFD4E344/*.pdf"

Any ideas on what is causing the joined PDF to come out as 1 page and blank?

Body:
This is an old post, but i had the exact same problem. After a lot of different attempts, eventually i managed to solve it (with the help of SO users ofc - thanks Marcomdm) in the following way:

I created a string with the necessary command parameters laid out:

stringToCall = "%s %s %s%s" % ("./join.py -o", endPdf, pdfInputDir,"/*.pdf")
        os.chdir(/System/Library/Automator/Combine PDF Pages.action/Contents/Resources/)
        os.system(stringToCall)

where endPdf is the final pdf name coming from
endPdf = os.path.join (pdfOutputDir, pdfName+".pdf")

Worked like a charm. Hope this helps.


问:
SpringBoot+Hibernate Relationship issues
I have an issue with the relationships of 3 entities. I was trying to have an inheritance heriarchy but within the child class I refer to a List of my Parent class objects as an attribute. So I would like my child class entity to be a mapper table, in which shows the association between it and it's parent. In doing this I was running into a bunch of relationship issues
I've created a sample project emulating the functionality.

Automobile.java

```<code>import java.io.Serializable;

import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.Inheritance;
import javax.persistence.InheritanceType;
import javax.persistence.OneToOne;

@Entity
@Inheritance(strategy=InheritanceType.JOINED)
public abstract class Automobile implements Serializable{

private static final long serialVersionUID = 1L;

@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private Long Id;

@OneToOne
private Manufacturer manufacturer;

@OneToOne
private AutomobileType autotype;

@OneToOne
private LoanerCar loanerCarID;

private String vin;

//Getters and Setters, Arg Constructors, No-Arg Constructor, toString
}
</code>```

LoanerCar.java

```<code>package com.example.demo.domains;

import java.sql.Timestamp;
import java.util.List;
import javax.persistence.Entity;
import javax.persistence.OneToMany;

@Entity
public class LoanerCar extends Automobile{

private static final long serialVersionUID = 1L;
private String name;
private Timestamp dateLoaned;
private Timestamp dateReceived;

@OneToMany
private List<Automobile> alist;

//Getters and Setters, Arg Constructors, No-Arg Constructor, toString
}
</code>```

TotaledCar.java

```<code>import java.util.List;
import javax.persistence.Entity;

@Entity
public class TotaledCar extends Automobile {

private static final long serialVersionUID = 1L;

private List<LoanerCar> eligibleLoaners;
</code>```

//Getters and Setters, Arg Constructors, No-Arg Constructor, toString
    }

AutomobileBaseRepository.java

```<code>import java.util.List;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.repository.NoRepositoryBean;
import com.example.demo.domains.Automobile;
import com.example.demo.domains.Manufacturer;

@NoRepositoryBean

public interface AutomobileBaseRepository<T extends Automobile> extends JpaRepository<T, Long> {
List<T> findByLoanerCarID(Long id);

List<T> findByVinAndManufacturerAndLoanerCarID(String vin, Manufacturer manfacturer, Long id);
}
</code>```

Automobile, TotaledCar, LoanerCar repositories extend the AutomobileBaseRespoistory, and has no methods.

LoaanerController.java

```<code>import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import com.example.demo.domains.LoanerCar;
import com.example.demo.domains.Manufacturer;
import com.example.demo.domains.TotaledCar;
import com.example.demo.repositories.LoanerCarRepository;
import com.example.demo.repositories.ManufacturerRepository;
import com.example.demo.repositories.TotaledCarRepository;

@RestController
public class LoanerController {

    @Autowired
    LoanerCarRepository loanerRepo;

    @Autowired
    TotaledCarRepository totaledCarRepo;

    @Autowired
    ManufacturerRepository manRepo;

    @RequestMapping(value="/loaner/all", method = RequestMethod.GET)
    public List<LoanerCar> loaners(){
        List<LoanerCar> list = loanerRepo.findAll();
        return list;
    }

    @RequestMapping(value="/loaner/{id}", method=RequestMethod.GET)
    public LoanerCar getLoaner(@PathVariable Long id){
        LoanerCar loanerCar= loanerRepo.findOne(id);
        return loanerCar;
    }

    @RequestMapping(value="/loaner", method=RequestMethod.GET)
    public String response(@RequestParam("vin") String vin, @RequestParam("manufacturer") Long manfuacturerId, @RequestParam("loanerId") Long loanerId){
        Manufacturer manObj = manRepo.findById(manfuacturerId);

        List<LoanerCar> loanerList = loanerRepo.findByLoanerCarID(loanerId);
        List<TotaledCar> tlist = totaledCarRepo.findByVinAndManufacturerAndLoanerCarID(vin, manObj, loanerId);

        for (TotaledCar junk : tlist){
            loanerList.addAll(junk.getEligibleLoaners());
        }

        String strlist = loanerList.toString();
        return strlist;
    }
}
</code>```

So the flow of this mapping is suppose to be from when I add an Automobile it will have an loanerId of null by default. And when I assign a value to the loanerId it is mapped to the LoanerCar table, in which has a AutomobileId from the parent class/table and a loanerId resides in the LoanerCar class/table. So in the LoanerCar table the loanerId is tied to a list of Automobiles in which are eligible for LoanerCars. So Automobile has one loanerId, and that loanerId can many automobiles.And my controller method will just get me a list of both totaled and loaner cars. I know it sounds confusing but I get this is what I'm trying to achieve.

Stack Trace

```<code>org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'entityManagerFactory' defined in class path resource [org/springframework/boot/autoconfigure/orm/jpa/HibernateJpaAutoConfiguration.class]: Invocation of init method failed; nested exception is javax.persistence.PersistenceException: [PersistenceUnit: default] Unable to build Hibernate SessionFactory
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.initializeBean(AbstractAutowireCapableBeanFactory.java:1628) ~[spring-beans-4.3.8.RELEASE.jar:4.3.8.RELEASE]
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:555) ~[spring-beans-4.3.8.RELEASE.jar:4.3.8.RELEASE]
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:483) ~[spring-beans-4.3.8.RELEASE.jar:4.3.8.RELEASE]
    at org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:306) ~[spring-beans-4.3.8.RELEASE.jar:4.3.8.RELEASE]
    at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:230) ~[spring-beans-4.3.8.RELEASE.jar:4.3.8.RELEASE]
    at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:302) ~[spring-beans-4.3.8.RELEASE.jar:4.3.8.RELEASE]
    at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:197) ~[spring-beans-4.3.8.RELEASE.jar:4.3.8.RELEASE]
    at org.springframework.context.support.AbstractApplicationContext.getBean(AbstractApplicationContext.java:1081) ~[spring-context-4.3.8.RELEASE.jar:4.3.8.RELEASE]
    at org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:856) ~[spring-context-4.3.8.RELEASE.jar:4.3.8.RELEASE]
    at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:542) ~[spring-context-4.3.8.RELEASE.jar:4.3.8.RELEASE]
    at org.springframework.boot.context.embedded.EmbeddedWebApplicationContext.refresh(EmbeddedWebApplicationContext.java:122) ~[spring-boot-1.5.3.RELEASE.jar:1.5.3.RELEASE]
    at org.springframework.boot.SpringApplication.refresh(SpringApplication.java:737) [spring-boot-1.5.3.RELEASE.jar:1.5.3.RELEASE]
    at org.springframework.boot.SpringApplication.refreshContext(SpringApplication.java:370) [spring-boot-1.5.3.RELEASE.jar:1.5.3.RELEASE]
    at org.springframework.boot.SpringApplication.run(SpringApplication.java:314) [spring-boot-1.5.3.RELEASE.jar:1.5.3.RELEASE]
    at org.springframework.boot.SpringApplication.run(SpringApplication.java:1162) [spring-boot-1.5.3.RELEASE.jar:1.5.3.RELEASE]
    at org.springframework.boot.SpringApplication.run(SpringApplication.java:1151) [spring-boot-1.5.3.RELEASE.jar:1.5.3.RELEASE]
    at com.example.demo.SpringJpaInheritanceRelationshipsApplication.main(SpringJpaInheritanceRelationshipsApplication.java:10) [classes/:na]
Caused by: javax.persistence.PersistenceException: [PersistenceUnit: default] Unable to build Hibernate SessionFactory
    at org.hibernate.jpa.boot.internal.EntityManagerFactoryBuilderImpl.persistenceException(EntityManagerFactoryBuilderImpl.java:954) ~[hibernate-entitymanager-5.0.12.Final.jar:5.0.12.Final]
    at org.hibernate.jpa.boot.internal.EntityManagerFactoryBuilderImpl.build(EntityManagerFactoryBuilderImpl.java:882) ~[hibernate-entitymanager-5.0.12.Final.jar:5.0.12.Final]
    at org.springframework.orm.jpa.vendor.SpringHibernateJpaPersistenceProvider.createContainerEntityManagerFactory(SpringHibernateJpaPersistenceProvider.java:60) ~[spring-orm-4.3.8.RELEASE.jar:4.3.8.RELEASE]
    at org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean.createNativeEntityManagerFactory(LocalContainerEntityManagerFactoryBean.java:353) ~[spring-orm-4.3.8.RELEASE.jar:4.3.8.RELEASE]
    at org.springframework.orm.jpa.AbstractEntityManagerFactoryBean.buildNativeEntityManagerFactory(AbstractEntityManagerFactoryBean.java:370) ~[spring-orm-4.3.8.RELEASE.jar:4.3.8.RELEASE]
    at org.springframework.orm.jpa.AbstractEntityManagerFactoryBean.afterPropertiesSet(AbstractEntityManagerFactoryBean.java:359) ~[spring-orm-4.3.8.RELEASE.jar:4.3.8.RELEASE]
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.invokeInitMethods(AbstractAutowireCapableBeanFactory.java:1687) ~[spring-beans-4.3.8.RELEASE.jar:4.3.8.RELEASE]
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.initializeBean(AbstractAutowireCapableBeanFactory.java:1624) ~[spring-beans-4.3.8.RELEASE.jar:4.3.8.RELEASE]
    ... 16 common frames omitted
Caused by: org.hibernate.MappingException: Could not determine type for: java.util.List, at table: totaled_car, for columns: [org.hibernate.mapping.Column(eligible_loaners)]
    at org.hibernate.mapping.SimpleValue.getType(SimpleValue.java:431) ~[hibernate-core-5.0.12.Final.jar:5.0.12.Final]
    at org.hibernate.mapping.SimpleValue.isValid(SimpleValue.java:398) ~[hibernate-core-5.0.12.Final.jar:5.0.12.Final]
    at org.hibernate.mapping.Property.isValid(Property.java:225) ~[hibernate-core-5.0.12.Final.jar:5.0.12.Final]
    at org.hibernate.mapping.PersistentClass.validate(PersistentClass.java:595) ~[hibernate-core-5.0.12.Final.jar:5.0.12.Final]
    at org.hibernate.mapping.JoinedSubclass.validate(JoinedSubclass.java:44) ~[hibernate-core-5.0.12.Final.jar:5.0.12.Final]
    at org.hibernate.boot.internal.MetadataImpl.validate(MetadataImpl.java:329) ~[hibernate-core-5.0.12.Final.jar:5.0.12.Final]
    at org.hibernate.boot.internal.SessionFactoryBuilderImpl.build(SessionFactoryBuilderImpl.java:443) ~[hibernate-core-5.0.12.Final.jar:5.0.12.Final]
    at org.hibernate.jpa.boot.internal.EntityManagerFactoryBuilderImpl.build(EntityManagerFactoryBuilderImpl.java:879) ~[hibernate-entitymanager-5.0.12.Final.jar:5.0.12.Final]
    ... 22 common frames omitted
</code>```

答:
You are using field access strategy (determined by @Id annotation). Put any JPA related annotation right above

```<code>private List<LoanerCar> eligibleLoaners;
</code>```

see here

Body:
I have an issue with the relationships of 3 entities. I was trying to have an inheritance heriarchy but within the child class I refer to a List of my Parent class objects as an attribute. So I would like my child class entity to be a mapper table, in which shows the association between it and it's parent. In doing this I was running into a bunch of relationship issues
I've created a sample project emulating the functionality.

Automobile.java

import java.io.Serializable;

import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.Inheritance;
import javax.persistence.InheritanceType;
import javax.persistence.OneToOne;

@Entity
@Inheritance(strategy=InheritanceType.JOINED)
public abstract class Automobile implements Serializable{

private static final long serialVersionUID = 1L;

@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private Long Id;

@OneToOne
private Manufacturer manufacturer;

@OneToOne
private AutomobileType autotype;

@OneToOne
private LoanerCar loanerCarID;

private String vin;

//Getters and Setters, Arg Constructors, No-Arg Constructor, toString
}

LoanerCar.java

package com.example.demo.domains;

import java.sql.Timestamp;
import java.util.List;
import javax.persistence.Entity;
import javax.persistence.OneToMany;

@Entity
public class LoanerCar extends Automobile{

private static final long serialVersionUID = 1L;
private String name;
private Timestamp dateLoaned;
private Timestamp dateReceived;

@OneToMany
private List<Automobile> alist;

//Getters and Setters, Arg Constructors, No-Arg Constructor, toString
}

TotaledCar.java

import java.util.List;
import javax.persistence.Entity;

@Entity
public class TotaledCar extends Automobile {

private static final long serialVersionUID = 1L;

private List<LoanerCar> eligibleLoaners;

//Getters and Setters, Arg Constructors, No-Arg Constructor, toString
    }

AutomobileBaseRepository.java

import java.util.List;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.repository.NoRepositoryBean;
import com.example.demo.domains.Automobile;
import com.example.demo.domains.Manufacturer;

@NoRepositoryBean

public interface AutomobileBaseRepository<T extends Automobile> extends JpaRepository<T, Long> {
List<T> findByLoanerCarID(Long id);

List<T> findByVinAndManufacturerAndLoanerCarID(String vin, Manufacturer manfacturer, Long id);
}

Automobile, TotaledCar, LoanerCar repositories extend the AutomobileBaseRespoistory, and has no methods.

LoaanerController.java

import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import com.example.demo.domains.LoanerCar;
import com.example.demo.domains.Manufacturer;
import com.example.demo.domains.TotaledCar;
import com.example.demo.repositories.LoanerCarRepository;
import com.example.demo.repositories.ManufacturerRepository;
import com.example.demo.repositories.TotaledCarRepository;

@RestController
public class LoanerController {

    @Autowired
    LoanerCarRepository loanerRepo;

    @Autowired
    TotaledCarRepository totaledCarRepo;

    @Autowired
    ManufacturerRepository manRepo;

    @RequestMapping(value="/loaner/all", method = RequestMethod.GET)
    public List<LoanerCar> loaners(){
        List<LoanerCar> list = loanerRepo.findAll();
        return list;
    }

    @RequestMapping(value="/loaner/{id}", method=RequestMethod.GET)
    public LoanerCar getLoaner(@PathVariable Long id){
        LoanerCar loanerCar= loanerRepo.findOne(id);
        return loanerCar;
    }

    @RequestMapping(value="/loaner", method=RequestMethod.GET)
    public String response(@RequestParam("vin") String vin, @RequestParam("manufacturer") Long manfuacturerId, @RequestParam("loanerId") Long loanerId){
        Manufacturer manObj = manRepo.findById(manfuacturerId);

        List<LoanerCar> loanerList = loanerRepo.findByLoanerCarID(loanerId);
        List<TotaledCar> tlist = totaledCarRepo.findByVinAndManufacturerAndLoanerCarID(vin, manObj, loanerId);

        for (TotaledCar junk : tlist){
            loanerList.addAll(junk.getEligibleLoaners());
        }

        String strlist = loanerList.toString();
        return strlist;
    }
}

So the flow of this mapping is suppose to be from when I add an Automobile it will have an loanerId of null by default. And when I assign a value to the loanerId it is mapped to the LoanerCar table, in which has a AutomobileId from the parent class/table and a loanerId resides in the LoanerCar class/table. So in the LoanerCar table the loanerId is tied to a list of Automobiles in which are eligible for LoanerCars. So Automobile has one loanerId, and that loanerId can many automobiles.And my controller method will just get me a list of both totaled and loaner cars. I know it sounds confusing but I get this is what I'm trying to achieve.

Stack Trace

org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'entityManagerFactory' defined in class path resource [org/springframework/boot/autoconfigure/orm/jpa/HibernateJpaAutoConfiguration.class]: Invocation of init method failed; nested exception is javax.persistence.PersistenceException: [PersistenceUnit: default] Unable to build Hibernate SessionFactory
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.initializeBean(AbstractAutowireCapableBeanFactory.java:1628) ~[spring-beans-4.3.8.RELEASE.jar:4.3.8.RELEASE]
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:555) ~[spring-beans-4.3.8.RELEASE.jar:4.3.8.RELEASE]
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:483) ~[spring-beans-4.3.8.RELEASE.jar:4.3.8.RELEASE]
    at org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:306) ~[spring-beans-4.3.8.RELEASE.jar:4.3.8.RELEASE]
    at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:230) ~[spring-beans-4.3.8.RELEASE.jar:4.3.8.RELEASE]
    at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:302) ~[spring-beans-4.3.8.RELEASE.jar:4.3.8.RELEASE]
    at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:197) ~[spring-beans-4.3.8.RELEASE.jar:4.3.8.RELEASE]
    at org.springframework.context.support.AbstractApplicationContext.getBean(AbstractApplicationContext.java:1081) ~[spring-context-4.3.8.RELEASE.jar:4.3.8.RELEASE]
    at org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:856) ~[spring-context-4.3.8.RELEASE.jar:4.3.8.RELEASE]
    at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:542) ~[spring-context-4.3.8.RELEASE.jar:4.3.8.RELEASE]
    at org.springframework.boot.context.embedded.EmbeddedWebApplicationContext.refresh(EmbeddedWebApplicationContext.java:122) ~[spring-boot-1.5.3.RELEASE.jar:1.5.3.RELEASE]
    at org.springframework.boot.SpringApplication.refresh(SpringApplication.java:737) [spring-boot-1.5.3.RELEASE.jar:1.5.3.RELEASE]
    at org.springframework.boot.SpringApplication.refreshContext(SpringApplication.java:370) [spring-boot-1.5.3.RELEASE.jar:1.5.3.RELEASE]
    at org.springframework.boot.SpringApplication.run(SpringApplication.java:314) [spring-boot-1.5.3.RELEASE.jar:1.5.3.RELEASE]
    at org.springframework.boot.SpringApplication.run(SpringApplication.java:1162) [spring-boot-1.5.3.RELEASE.jar:1.5.3.RELEASE]
    at org.springframework.boot.SpringApplication.run(SpringApplication.java:1151) [spring-boot-1.5.3.RELEASE.jar:1.5.3.RELEASE]
    at com.example.demo.SpringJpaInheritanceRelationshipsApplication.main(SpringJpaInheritanceRelationshipsApplication.java:10) [classes/:na]
Caused by: javax.persistence.PersistenceException: [PersistenceUnit: default] Unable to build Hibernate SessionFactory
    at org.hibernate.jpa.boot.internal.EntityManagerFactoryBuilderImpl.persistenceException(EntityManagerFactoryBuilderImpl.java:954) ~[hibernate-entitymanager-5.0.12.Final.jar:5.0.12.Final]
    at org.hibernate.jpa.boot.internal.EntityManagerFactoryBuilderImpl.build(EntityManagerFactoryBuilderImpl.java:882) ~[hibernate-entitymanager-5.0.12.Final.jar:5.0.12.Final]
    at org.springframework.orm.jpa.vendor.SpringHibernateJpaPersistenceProvider.createContainerEntityManagerFactory(SpringHibernateJpaPersistenceProvider.java:60) ~[spring-orm-4.3.8.RELEASE.jar:4.3.8.RELEASE]
    at org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean.createNativeEntityManagerFactory(LocalContainerEntityManagerFactoryBean.java:353) ~[spring-orm-4.3.8.RELEASE.jar:4.3.8.RELEASE]
    at org.springframework.orm.jpa.AbstractEntityManagerFactoryBean.buildNativeEntityManagerFactory(AbstractEntityManagerFactoryBean.java:370) ~[spring-orm-4.3.8.RELEASE.jar:4.3.8.RELEASE]
    at org.springframework.orm.jpa.AbstractEntityManagerFactoryBean.afterPropertiesSet(AbstractEntityManagerFactoryBean.java:359) ~[spring-orm-4.3.8.RELEASE.jar:4.3.8.RELEASE]
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.invokeInitMethods(AbstractAutowireCapableBeanFactory.java:1687) ~[spring-beans-4.3.8.RELEASE.jar:4.3.8.RELEASE]
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.initializeBean(AbstractAutowireCapableBeanFactory.java:1624) ~[spring-beans-4.3.8.RELEASE.jar:4.3.8.RELEASE]
    ... 16 common frames omitted
Caused by: org.hibernate.MappingException: Could not determine type for: java.util.List, at table: totaled_car, for columns: [org.hibernate.mapping.Column(eligible_loaners)]
    at org.hibernate.mapping.SimpleValue.getType(SimpleValue.java:431) ~[hibernate-core-5.0.12.Final.jar:5.0.12.Final]
    at org.hibernate.mapping.SimpleValue.isValid(SimpleValue.java:398) ~[hibernate-core-5.0.12.Final.jar:5.0.12.Final]
    at org.hibernate.mapping.Property.isValid(Property.java:225) ~[hibernate-core-5.0.12.Final.jar:5.0.12.Final]
    at org.hibernate.mapping.PersistentClass.validate(PersistentClass.java:595) ~[hibernate-core-5.0.12.Final.jar:5.0.12.Final]
    at org.hibernate.mapping.JoinedSubclass.validate(JoinedSubclass.java:44) ~[hibernate-core-5.0.12.Final.jar:5.0.12.Final]
    at org.hibernate.boot.internal.MetadataImpl.validate(MetadataImpl.java:329) ~[hibernate-core-5.0.12.Final.jar:5.0.12.Final]
    at org.hibernate.boot.internal.SessionFactoryBuilderImpl.build(SessionFactoryBuilderImpl.java:443) ~[hibernate-core-5.0.12.Final.jar:5.0.12.Final]
    at org.hibernate.jpa.boot.internal.EntityManagerFactoryBuilderImpl.build(EntityManagerFactoryBuilderImpl.java:879) ~[hibernate-entitymanager-5.0.12.Final.jar:5.0.12.Final]
    ... 22 common frames omitted

Body:
You are using field access strategy (determined by @Id annotation). Put any JPA related annotation right above

private List<LoanerCar> eligibleLoaners;

see here


问:
how to yammer feed filtering
We are integrating Yammer with our web application. One of our requirement it to display the my yammer feeds and the feeds of topics which I am following. We are using yammer widget in yam.connect.embedFeed() our pages. Is there any way to do the filtering?

Is there any modification possible in the below code to achieve this?

```<code>yam.connect.embedFeed({
  "feedType": "user",
  "feedId": 1530760345,
  "config": {
  "use_sso": false,
  "header": true,
  "footer": true,
  "showOpenGraphPreview": false,
  "defaultToCanonical": false,
  "hideNetworkName": false
},
"container": "#embedded-feed"
});
</code>```

答: You can change feedType to topic, and set the feedID to the topic ID. This will show all messages with a particular topic ID. More user-specific filtering is not supported.</p>

Title: how to yammer feed filtering

Body:
We are integrating Yammer with our web application. One of our requirement it to display the my yammer feeds and the feeds of topics which I am following. We are using yammer widget in yam.connect.embedFeed() our pages. Is there any way to do the filtering?

Is there any modification possible in the below code to achieve this?

yam.connect.embedFeed({
  "feedType": "user",
  "feedId": 1530760345,
  "config": {
  "use_sso": false,
  "header": true,
  "footer": true,
  "showOpenGraphPreview": false,
  "defaultToCanonical": false,
  "hideNetworkName": false
},
"container": "#embedded-feed"
});


问:
Sync code for Promise All
Hi everyone I'm having troubles with my code because of promises are being done in a async way and i need them to be sync. So I have this function to return the value of the two promises inside fullfilled

```<code> ServicesController.prototype.uci = function (device, config, path, section, property, value, apply, commit) {
    createLog('debug', __dirname, __filename.slice(__dirname.length + 1, -3), device.id, 'uci', 'inicio');

    createLog('debug', __dirname, __filename.slice(__dirname.length + 1, -3), device.id, 'uci', 'config', config);
    createLog('debug', __dirname, __filename.slice(__dirname.length + 1, -3), device.id, 'uci', 'path', path);
    createLog('debug', __dirname, __filename.slice(__dirname.length + 1, -3), device.id, 'uci', 'section', section);
    createLog('debug', __dirname, __filename.slice(__dirname.length + 1, -3), device.id, 'uci', 'option', property);
    createLog('debug', __dirname, __filename.slice(__dirname.length + 1, -3), device.id, 'uci', 'value', value);
    createLog('debug', __dirname, __filename.slice(__dirname.length + 1, -3), device.id, 'uci', 'apply', apply);
    createLog('debug', __dirname, __filename.slice(__dirname.length + 1, -3), device.id, 'uci', 'commit', commit);

    var values = {};
    values[property] = value;
    createLog('debug', __dirname, __filename.slice(__dirname.length + 1, -3), device.id, 'uci', 'values', values);

    return Controllers.Ubus.uciRequest('set', {"config": config, "section": section, values}, device)
            .then(function (uciData) {
                createLog('debug', __dirname, __filename.slice(__dirname.length + 1, -3), device.id, 'uci', 'uciData', uciData);
                var promises = [];

                if (uciData != null) {
                    createLog('info', __dirname, __filename.slice(__dirname.length + 1, -3), device.id, 'uci', 'depois do if do uciData');

                    if (commit) {
                        createLog('debug', __dirname, __filename.slice(__dirname.length + 1, -3), null, 'uci', 'commit');
                        var p1 = new Promise(function (resolve, reject) {
                            Controllers.Ubus.uciRequest('commit', {"config": config}, device)
                                .then(function (dataCommit) {
                                    if (dataCommit && dataCommit.hasOwnProperty('result') && dataCommit.result[0] == 0) {
                                        createLog('info', __dirname, __filename.slice(__dirname.length + 1, -3), null, 'uci', 'commit data', dataCommit);
                                        resolve(dataCommit.result[0]);
                                    } else {
                                        reject("no data");
                                    }
                                }).catch(function (err) {
                                    createLog('error', __dirname, __filename.slice(__dirname.length + 1, -3), null, 'uci', 'error promise commit', err);
                                });
                        });
                        promises.push(p1);
                    }

                    if (apply) {
                        createLog('debug', __dirname, __filename.slice(__dirname.length + 1, -3), null, 'uci', 'apply');
                        var p2 = new Promise(function (resolve, reject) {
                                Controllers.Ubus.fileExec(device.id, "exec", path, "restart")
                                .then(function (dataApply) {
                                    if (dataApply && dataApply.hasOwnProperty('result') && dataApply.result[0] == 0) {
                                        createLog('info', __dirname, __filename.slice(__dirname.length + 1, -3), null, 'uci', 'apply data', dataApply);
                                        resolve(dataApply.result[0]);
                                    } else {
                                        reject("no data");
                                    }
                                }).catch(function (err) {
                                    createLog('error', __dirname, __filename.slice(__dirname.length + 1, -3), null, 'uci', 'error promise apply', err);
                                });
                        });
                        promises.push(p2);
                    }
                    createLog('debug', __dirname, __filename.slice(__dirname.length + 1, -3), null, 'uci', 'promises ', promises);
                }
            }).then(function (promises) {
                createLog('debug', __dirname, __filename.slice(__dirname.length + 1, -3), null, 'uci', 'promises then', promises);
                Promise.all(promises).then(function (values) {
                    createLog('debug', __dirname, __filename.slice(__dirname.length + 1, -3), null, 'uci', 'promises all', values);
return(values);

                }).catch(function (err) {
                    createLog('error', __dirname, __filename.slice(__dirname.length + 1, -3), null, 'uci', 'error promise all', err);
                });
            }).catch(function (err) {
                createLog('error', __dirname, __filename.slice(__dirname.length + 1, -3), null, 'uci', 'error then 2', err);
            });
}
</code>```

By my logs I'm entering in the apply and commit if.

Right now i'm receiving this log:

```<code> [2017-06-08 15:37:39.621] - error: /opt/wscontroller/wscontroller-api/routes/services ServicesController NA uci error promise all {}
</code>```

Anyone can give me some help to solve this problem?

答: You must return the promises array in first then callback</p>

Title: Sync code for Promise All

Body:
Hi everyone I'm having troubles with my code because of promises are being done in a async way and i need them to be sync. So I have this function to return the value of the two promises inside fullfilled

 ServicesController.prototype.uci = function (device, config, path, section, property, value, apply, commit) {
    createLog('debug', __dirname, __filename.slice(__dirname.length + 1, -3), device.id, 'uci', 'inicio');

    createLog('debug', __dirname, __filename.slice(__dirname.length + 1, -3), device.id, 'uci', 'config', config);
    createLog('debug', __dirname, __filename.slice(__dirname.length + 1, -3), device.id, 'uci', 'path', path);
    createLog('debug', __dirname, __filename.slice(__dirname.length + 1, -3), device.id, 'uci', 'section', section);
    createLog('debug', __dirname, __filename.slice(__dirname.length + 1, -3), device.id, 'uci', 'option', property);
    createLog('debug', __dirname, __filename.slice(__dirname.length + 1, -3), device.id, 'uci', 'value', value);
    createLog('debug', __dirname, __filename.slice(__dirname.length + 1, -3), device.id, 'uci', 'apply', apply);
    createLog('debug', __dirname, __filename.slice(__dirname.length + 1, -3), device.id, 'uci', 'commit', commit);

    var values = {};
    values[property] = value;
    createLog('debug', __dirname, __filename.slice(__dirname.length + 1, -3), device.id, 'uci', 'values', values);

    return Controllers.Ubus.uciRequest('set', {"config": config, "section": section, values}, device)
            .then(function (uciData) {
                createLog('debug', __dirname, __filename.slice(__dirname.length + 1, -3), device.id, 'uci', 'uciData', uciData);
                var promises = [];

                if (uciData != null) {
                    createLog('info', __dirname, __filename.slice(__dirname.length + 1, -3), device.id, 'uci', 'depois do if do uciData');

                    if (commit) {
                        createLog('debug', __dirname, __filename.slice(__dirname.length + 1, -3), null, 'uci', 'commit');
                        var p1 = new Promise(function (resolve, reject) {
                            Controllers.Ubus.uciRequest('commit', {"config": config}, device)
                                .then(function (dataCommit) {
                                    if (dataCommit && dataCommit.hasOwnProperty('result') && dataCommit.result[0] == 0) {
                                        createLog('info', __dirname, __filename.slice(__dirname.length + 1, -3), null, 'uci', 'commit data', dataCommit);
                                        resolve(dataCommit.result[0]);
                                    } else {
                                        reject("no data");
                                    }
                                }).catch(function (err) {
                                    createLog('error', __dirname, __filename.slice(__dirname.length + 1, -3), null, 'uci', 'error promise commit', err);
                                });
                        });
                        promises.push(p1);
                    }

                    if (apply) {
                        createLog('debug', __dirname, __filename.slice(__dirname.length + 1, -3), null, 'uci', 'apply');
                        var p2 = new Promise(function (resolve, reject) {
                                Controllers.Ubus.fileExec(device.id, "exec", path, "restart")
                                .then(function (dataApply) {
                                    if (dataApply && dataApply.hasOwnProperty('result') && dataApply.result[0] == 0) {
                                        createLog('info', __dirname, __filename.slice(__dirname.length + 1, -3), null, 'uci', 'apply data', dataApply);
                                        resolve(dataApply.result[0]);
                                    } else {
                                        reject("no data");
                                    }
                                }).catch(function (err) {
                                    createLog('error', __dirname, __filename.slice(__dirname.length + 1, -3), null, 'uci', 'error promise apply', err);
                                });
                        });
                        promises.push(p2);
                    }
                    createLog('debug', __dirname, __filename.slice(__dirname.length + 1, -3), null, 'uci', 'promises ', promises);
                }
            }).then(function (promises) {
                createLog('debug', __dirname, __filename.slice(__dirname.length + 1, -3), null, 'uci', 'promises then', promises);
                Promise.all(promises).then(function (values) {
                    createLog('debug', __dirname, __filename.slice(__dirname.length + 1, -3), null, 'uci', 'promises all', values);
return(values);

                }).catch(function (err) {
                    createLog('error', __dirname, __filename.slice(__dirname.length + 1, -3), null, 'uci', 'error promise all', err);
                });
            }).catch(function (err) {
                createLog('error', __dirname, __filename.slice(__dirname.length + 1, -3), null, 'uci', 'error then 2', err);
            });
}

By my logs I'm entering in the apply and commit if.

Right now i'm receiving this log:

 [2017-06-08 15:37:39.621] - error: /opt/wscontroller/wscontroller-api/routes/services ServicesController NA uci error promise all {}

Anyone can give me some help to solve this problem?


问:
How to clear errors object in vee-validate?
I'd like to clear all the errors from vee-validate in a sign out method, following code seems not working, the errors in the form is still being shown, why?

```<code>sign_out: function (e) {
    console.log('sign me out')
    var self = this
    firebase.auth().signOut().then(function () {

      console.log('sign out!')
      self.info.email = ''
      self.errors.clear()  // clear errors object of vee-validate

    }, function (error) {

      console.log('sign out failed')

    })
  },
</code>```

here is a jsFiddle that describe the problem in code, when you type '123', a warning is shown, then when you click 'clear', the field is set to '', and errors.clear(), was expecting the warning in the form will go away, but it is not:

https://jsfiddle.net/8j3z82bv/1/

答:
Use the following:</p>

```<code>this.$validator.clean();
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I'd like to clear all the errors from vee-validate in a sign out method, following code seems not working, the errors in the form is still being shown, why?

sign_out: function (e) {
    console.log('sign me out')
    var self = this
    firebase.auth().signOut().then(function () {

      console.log('sign out!')
      self.info.email = ''
      self.errors.clear()  // clear errors object of vee-validate

    }, function (error) {

      console.log('sign out failed')

    })
  },

here is a jsFiddle that describe the problem in code, when you type '123', a warning is shown, then when you click 'clear', the field is set to '', and errors.clear(), was expecting the warning in the form will go away, but it is not:

https://jsfiddle.net/8j3z82bv/1/

Body:
Use the following:

this.$validator.clean();


问:
java.net.URLConnection.guessContentTypeFromStream and text/plain
All,

I am trying to identify plain text files with Mac line endings and, inside an InputStream, silently convert them to Windows or Linux line endings (the important part is the LF character, really). Specifically, I'm working with several APIs that take InputStreams and are hard-locked to looking for \n as newlines.

Sometimes, I get binary files. Obviously, a file that isn't text-like shouldn't have this substitution done, because the value that happens to correspond to \r obviously can't silently be followed by a \n without mangling things badly.

I am attempting to use java.net.URLConnection.guessContentTypeFromStream and only performing endline conversions if the type is text/plain. Unfortunately, "text/plain" doesn't seem to be in its gamut of return values; all I get is null for my flat text files, and it's possibly not safe to assume all unidentifiable files can be modified.

What better library (preferably in a public Maven repository and open-source) can I use to do this? Alternatively, how can I make guessContentTypeFromStream work for me? I know I'm describing an inherently hazardous application and no solution can be perfect, but should I just treat "null" as likely to be "text/plain" and I simply need to write more code myself to look for evidence that it isn't?

答:
It seems to me that what you're asking is to determine if a file is textual or not. Given that, there is a solution here that seems right:

Granted, he is talking about unix, bash and perl but the concept is the same:

Unless you inspect every byte of the
  file, you are not going to get this
  100%. And there is a big performance
  hit with inspecting every byte. But
  after some experiments, I settled on
  an algorithm that works for me. I
  examine the first line and declare the
  file to be binary if I encounter even
  one non-text byte. It seems a little
  slack, I know, but I seem to get away
  with it.

EDIT #1:

Expanding on this type of solution, it seems like a reasonable approach would be to ensure the file contains no non-ascii characters (unless you're dealing with files that are non-English...thats another solution). This could be done by checking if the file contents as a String does not match this:

```<code>// -- uses commons-io
String fileAsString = FileUtils.readFileToString( new File( "file-name-here" ) );
boolean isTextualFile = fileAsString.matches( ".*\\p{ASCII}+.*" );
</code>```

EDIT #2

You may want to try this as your regex, or something close to it. Though, I'll admit it could likely use some refining.

```<code>".*(?:\\p{Print}|\\p{Space})+.*"
</code>```

Body:
It seems to me that what you're asking is to determine if a file is textual or not. Given that, there is a solution here that seems right:

Granted, he is talking about unix, bash and perl but the concept is the same:

Unless you inspect every byte of the
  file, you are not going to get this
  100%. And there is a big performance
  hit with inspecting every byte. But
  after some experiments, I settled on
  an algorithm that works for me. I
  examine the first line and declare the
  file to be binary if I encounter even
  one non-text byte. It seems a little
  slack, I know, but I seem to get away
  with it.

EDIT #1:

Expanding on this type of solution, it seems like a reasonable approach would be to ensure the file contains no non-ascii characters (unless you're dealing with files that are non-English...thats another solution). This could be done by checking if the file contents as a String does not match this:

// -- uses commons-io
String fileAsString = FileUtils.readFileToString( new File( "file-name-here" ) );
boolean isTextualFile = fileAsString.matches( ".*\\p{ASCII}+.*" );

EDIT #2

You may want to try this as your regex, or something close to it. Though, I'll admit it could likely use some refining.

".*(?:\\p{Print}|\\p{Space})+.*"


问:
Using a collection and error handling to find new item numbers
I get monthly reports of inventory sales. There are items added to the system regularly, and I find these by their unique ID numbers. I have an excel file with a list of all the item numbers and descriptions and a few other attributes.

My goal - download an excel file with all the items sold last month. If there are new items, add those to the existing list.

I am using something Siddharth Rout has posted on a previous answer, the relevant code looks like this:

```<code>dim col as collection
Application.ScreenUpdating = False
With ItemList
    For x = 3 To lastrowIL
        On Error Resume Next
        col.Add .Range("A" & x).Value, CStr(.Range("A" & x).Value)
        On Error GoTo 0
    Next x
End With
With Monthly
.Range("AH3:AH" & lastrowM).Value = "New"
On Error Resume Next
    For y = 3 To lastrowM
        col.Add .Range("B" & y).Value, CStr(.Range("B" & y).Value)
        If Err.Number <> 0 Then .Range("AH" & y).Value = "Old"
        Err.Clear
    Next y
End With
Application.ScreenUpdating = True
</code>```

the concept is that if you enter the same item ID twice, the same key will be used and there will be an error message which will change "new" to "old"

The problem: All additions to the collection are causing errors, thereby changing all "New" to "Old"

答:
OK I figured out the problem by adding a watch to the err.number object.

I did not declare the collection as New collection
(or declare the collection and then set it as New collection)

fixed that and I fixed the "old" vs "new" indication.

Body:
I get monthly reports of inventory sales. There are items added to the system regularly, and I find these by their unique ID numbers. I have an excel file with a list of all the item numbers and descriptions and a few other attributes.

My goal - download an excel file with all the items sold last month. If there are new items, add those to the existing list.

I am using something Siddharth Rout has posted on a previous answer, the relevant code looks like this:

dim col as collection
Application.ScreenUpdating = False
With ItemList
    For x = 3 To lastrowIL
        On Error Resume Next
        col.Add .Range("A" & x).Value, CStr(.Range("A" & x).Value)
        On Error GoTo 0
    Next x
End With
With Monthly
.Range("AH3:AH" & lastrowM).Value = "New"
On Error Resume Next
    For y = 3 To lastrowM
        col.Add .Range("B" & y).Value, CStr(.Range("B" & y).Value)
        If Err.Number <> 0 Then .Range("AH" & y).Value = "Old"
        Err.Clear
    Next y
End With
Application.ScreenUpdating = True

the concept is that if you enter the same item ID twice, the same key will be used and there will be an error message which will change "new" to "old"

The problem: All additions to the collection are causing errors, thereby changing all "New" to "Old"