问:
PHP resize image before save to mysql database?
After I got the post, how to resize to a smaller width (maximum width is 80, min also 80) and what should I check for security purposes?

My current code:

```<code>if(!empty($_FILES)) {
# Resize Image function
$return=true;
function resizeImage($originalImage,$toWidth,$toHeight){
    // Get the original geometry and calculate scales
    list($width, $height) = getimagesize($originalImage);
    $xscale=$width/$toWidth;
    $yscale=$height/$toHeight;

    // Recalculate new size with default ratio
    if ($yscale>$xscale){
        $new_width = round($width * (1/$yscale));
        $new_height = round($height * (1/$yscale));
    }
    else {
        $new_width = round($width * (1/$xscale));
        $new_height = round($height * (1/$xscale));
    }

    // Resize the original image
    $imageResized = imagecreatetruecolor($new_width, $new_height);
    $imageTmp     = imagecreatefromjpeg ($originalImage);
    imagecopyresampled($imageResized, $imageTmp, 0, 0, 0, 0, $new_width, $new_height, $width, $height);

    return $imageResized;
}

// Get the file information
$userfile_name = $_FILES['profile_picture']['name'];
$userfile_tmp  = $_FILES['profile_picture']['tmp_name'];
$userfile_size = $_FILES['profile_picture']['size'];
$userfile_type = $_FILES['profile_picture']['type'];
$filename = basename($_FILES['profile_picture']['name']);
$file_ext = strtolower(substr($filename, strrpos($filename, '.') + 1));

//Only process if the file is a JPG and below the allowed limit
if((!empty($_FILES["profile_picture"])) && ($_FILES['profile_picture']['error'] == 0)) {
    $allowed_image_types = array('image/pjpeg'=>"jpg",'image/jpeg'=>"jpg",'image/jpg'=>"jpg",'image/png'=>"png",'image/x-png'=>"png",'image/gif'=>"gif");
    $allowed_image_ext = array_unique($allowed_image_types); // Do not change this
    foreach ($allowed_image_types as $mime_type => $ext) {
        if($file_ext==$ext ){
            $return=false;
            break;
        } else {
            $return=true;
        }
    }

    if ($userfile_size > (7*1048576)) { # 7 means 7 mb
        $return=false;
    }
} else {
    $return=false;
}

//Everything is ok, so we can upload the image.
if (strlen($return)==0){
    $widthAndHeight = getimagesize($userfile_tmp . "." . $file_ext); //EDITED QUESTION
    $width  = $widthAndHeight[0];
    $height = $widthAndHeight[1];

    if ($width > 80){
        $scale = 80/$width;
        $height = $height * $scale;
        $data = resizeImage($userfile_name,80,$height,$scale);
        $data = mysql_real_escape_string($data);
    } else {
        $data = mysql_real_escape_string($userfile_name);
    }

    $update = mysql_query("UPDATE `avatar` set image = '{$data}' WHERE userid = '" .  $_SESSION['userid'] . " . '");
} else {
    $return=false;
}
</code>```

The datatype in mysql database is MediumBlob since it only store small file

Sorry for not mention my problem, the code its not working. The error is:

```<code>Warning: getimagesize(C:\wamp\tmp\php991B.tmp.png) [function.getimagesize]: failed to open stream: No such file or directory in C:\wamp\www\XXX\avatar.php on line 82**strong text**
</code>```

答:
If you don't really need to write your own code for this, you can try out some of the solutions that are already out there.

This is an excellent script
http://phpthumb.gxdlabs.com/

I am not sure if you can save image data to a database using it, but worst case scenario is

you resize the image and save it to a local folder
use file_get_contents to read the image and save to db
delete temp image on server.

But I agree with those who say you should store the images in the filesystem, not the database.

Body:
After I got the post, how to resize to a smaller width (maximum width is 80, min also 80) and what should I check for security purposes?

My current code:

if(!empty($_FILES)) {
# Resize Image function
$return=true;
function resizeImage($originalImage,$toWidth,$toHeight){
    // Get the original geometry and calculate scales
    list($width, $height) = getimagesize($originalImage);
    $xscale=$width/$toWidth;
    $yscale=$height/$toHeight;

    // Recalculate new size with default ratio
    if ($yscale>$xscale){
        $new_width = round($width * (1/$yscale));
        $new_height = round($height * (1/$yscale));
    }
    else {
        $new_width = round($width * (1/$xscale));
        $new_height = round($height * (1/$xscale));
    }

    // Resize the original image
    $imageResized = imagecreatetruecolor($new_width, $new_height);
    $imageTmp     = imagecreatefromjpeg ($originalImage);
    imagecopyresampled($imageResized, $imageTmp, 0, 0, 0, 0, $new_width, $new_height, $width, $height);

    return $imageResized;
}

// Get the file information
$userfile_name = $_FILES['profile_picture']['name'];
$userfile_tmp  = $_FILES['profile_picture']['tmp_name'];
$userfile_size = $_FILES['profile_picture']['size'];
$userfile_type = $_FILES['profile_picture']['type'];
$filename = basename($_FILES['profile_picture']['name']);
$file_ext = strtolower(substr($filename, strrpos($filename, '.') + 1));

//Only process if the file is a JPG and below the allowed limit
if((!empty($_FILES["profile_picture"])) && ($_FILES['profile_picture']['error'] == 0)) {
    $allowed_image_types = array('image/pjpeg'=>"jpg",'image/jpeg'=>"jpg",'image/jpg'=>"jpg",'image/png'=>"png",'image/x-png'=>"png",'image/gif'=>"gif");
    $allowed_image_ext = array_unique($allowed_image_types); // Do not change this
    foreach ($allowed_image_types as $mime_type => $ext) {
        if($file_ext==$ext ){
            $return=false;
            break;
        } else {
            $return=true;
        }
    }

    if ($userfile_size > (7*1048576)) { # 7 means 7 mb
        $return=false;
    }
} else {
    $return=false;
}

//Everything is ok, so we can upload the image.
if (strlen($return)==0){
    $widthAndHeight = getimagesize($userfile_tmp . "." . $file_ext); //EDITED QUESTION
    $width  = $widthAndHeight[0];
    $height = $widthAndHeight[1];

    if ($width > 80){
        $scale = 80/$width;
        $height = $height * $scale;
        $data = resizeImage($userfile_name,80,$height,$scale);
        $data = mysql_real_escape_string($data);
    } else {
        $data = mysql_real_escape_string($userfile_name);
    }

    $update = mysql_query("UPDATE `avatar` set image = '{$data}' WHERE userid = '" .  $_SESSION['userid'] . " . '");
} else {
    $return=false;
}

The datatype in mysql database is MediumBlob since it only store small file

Sorry for not mention my problem, the code its not working. The error is:

Warning: getimagesize(C:\wamp\tmp\php991B.tmp.png) [function.getimagesize]: failed to open stream: No such file or directory in C:\wamp\www\XXX\avatar.php on line 82**strong text**


来源: stackexchange

问:
Facebook API for PHP: how to get user albums and photos?
Hello I'm using Facebook API for PHP (latest version) and I'm trying to get all albums with photos of an user.

I wrote this code:

```<code><?php
require_once "common.php";

if( !isset( $_SESSION['facebook_access_token'] ) ){
    header("Location: index.php");
    exit;
}

$token= $_SESSION['facebook_access_token'];

try {
    // Returns a `Facebook\FacebookResponse` object
    $response= $fb->get('/me?fields=id,name,first_name,last_name,gender,link,birthday,location,picture', $token);
} catch(Facebook\Exceptions\FacebookResponseException $e) {
    echo 'Graph returned an error: ' . $e->getMessage();
    exit;
} catch(Facebook\Exceptions\FacebookSDKException $e) {
    echo 'Facebook SDK returned an error: ' . $e->getMessage();
    exit;
}

$user= $response->getGraphUser();

$albums = $fb->get('/me/albums', $token);

$action = ( isset($_REQUEST['action']) ) ? $_REQUEST['action'] : null;

$album_id = '';
if($action=='viewalbum'){
    $album_id = $_REQUEST['album_id'];
    $photos = $fb->get("/{$album_id}/photos", $token);
    ?>
    <div class="slideshow">
        <?php
        foreach($photos['data'] as $photo)
        {
            echo "<img src='{$photo['source']}' />";
        }
        ?>
    </div>
<?php
}

$pageURL = 'http://'.$_SERVER["SERVER_NAME"].$_SERVER["REQUEST_URI"];
echo '<div class="alb">';
if(strstr($pageURL,'.php?')){
    $and = '&';
}else{
    $and = '?';
}

echo '<p class="hd">My Albums</p>';
foreach($albums['data'] as $album)
{
    if($album_id == $album['id']){
        $name = '<b><u>'.$album['name'].'</u></b>';
    }else{
        $name = $album['name'];
    }
    echo '<p>'."<a href=".$pageURL.$and."action=viewalbum&album_id=".$album['id'].">".$name.'</a></p>';
}
echo '</div>';
</code>```

I've found this example here: Get all images from specific Facebook album with Graph API PHP SDK
But is says: Cannot use object of type Facebook\FacebookResponse as array on line 53 (I've changed but don't work at all because API function doesn't exist!)

I've also tried to follow the documentation: https://developers.facebook.com/docs/graph-api/reference/user/photos/

But execute function doesn't exist! What shall I do?

答:
Here to attach the code retrieve varies size of photo instead of only 100px images from album.</p>

```<code>$photos = $fb->get("/{--album_id--}/photos?fields=images&width", $accessToken->getValue())->getGraphEdge()->asArray();

    //var_dump($photos);
    foreach($photos as $photo){
        echo "<br><img src='{$photo['images'][0]['source']}' />";//Get largest by 0 index
        //foreach($photo['images'] as $photosize){
        //    echo "<br><img src='{$photosize['source']}'/>";
        //}
    }
</code>```

ContentLicense: CC BY-SA 3.0

Body:
Hello I'm using Facebook API for PHP (latest version) and I'm trying to get all albums with photos of an user.

I wrote this code:

<?php
require_once "common.php";

if( !isset( $_SESSION['facebook_access_token'] ) ){
    header("Location: index.php");
    exit;
}

$token= $_SESSION['facebook_access_token'];

try {
    // Returns a `Facebook\FacebookResponse` object
    $response= $fb->get('/me?fields=id,name,first_name,last_name,gender,link,birthday,location,picture', $token);
} catch(Facebook\Exceptions\FacebookResponseException $e) {
    echo 'Graph returned an error: ' . $e->getMessage();
    exit;
} catch(Facebook\Exceptions\FacebookSDKException $e) {
    echo 'Facebook SDK returned an error: ' . $e->getMessage();
    exit;
}

$user= $response->getGraphUser();

$albums = $fb->get('/me/albums', $token);

$action = ( isset($_REQUEST['action']) ) ? $_REQUEST['action'] : null;

$album_id = '';
if($action=='viewalbum'){
    $album_id = $_REQUEST['album_id'];
    $photos = $fb->get("/{$album_id}/photos", $token);
    ?>

        <?php
        foreach($photos['data'] as $photo)
        {
            echo "";
        }
        ?>

<?php
}

$pageURL = 'http://'.$_SERVER["SERVER_NAME"].$_SERVER["REQUEST_URI"];
echo '
';
if(strstr($pageURL,'.php?')){
    $and = '&';
}else{
    $and = '?';
}

echo '
My Albums
';
foreach($albums['data'] as $album)
{
    if($album_id == $album['id']){
        $name = ''.$album['name'].'';
    }else{
        $name = $album['name'];
    }
    echo '
'."".$name.'
';
}
echo '
';

I've found this example here: Get all images from specific Facebook album with Graph API PHP SDK
But is says: Cannot use object of type Facebook\FacebookResponse as array on line 53 (I've changed but don't work at all because API function doesn't exist!)

I've also tried to follow the documentation: https://developers.facebook.com/docs/graph-api/reference/user/photos/

But execute function doesn't exist! What shall I do?

Body:
Here to attach the code retrieve varies size of photo instead of only 100px images from album.

$photos = $fb->get("/{--album_id--}/photos?fields=images&width", $accessToken->getValue())->getGraphEdge()->asArray();

    //var_dump($photos);
    foreach($photos as $photo){
        echo "<br><img src='{$photo['images'][0]['source']}' />";//Get largest by 0 index
        //foreach($photo['images'] as $photosize){
        //    echo "<br><img src='{$photosize['source']}'/>";
        //}
    }


问:
httpkit-fake does not intercept url build with passed parameters
How can I have with-fake-http intercept an http/get request containing :query-params. The following code produces an exception

```<code> (require
            '[org.httpkit.client :as http]
            '[org.httpkit.fake :refer :all]
            )

(with-fake-http ["localhost?q=hello" "hello param"]
  (println @(http/get "localhost" :query-params {:q "hello"})))
</code>```

CompilerException java.lang.IllegalArgumentException: Attempted to perform GET on unregistered URL localhost and real HTTP requests are disabled., compiling:(web/db_test.clj:57:1)

Thanks for your help.

答:
Instead of the String "localhost?q=hello", you can provide a map with the keys :url and :query-params

```<code>(with-fake-http
    [{:query-params {:q "hello"}, :url "localhost"} "hello param"]
    (println @(http/get "localhost" {:query-params {:q "hello"}})))
</code>```

Body:
How can I have with-fake-http intercept an http/get request containing :query-params. The following code produces an exception

 (require
            '[org.httpkit.client :as http]
            '[org.httpkit.fake :refer :all]
            )

(with-fake-http ["localhost?q=hello" "hello param"]
  (println @(http/get "localhost" :query-params {:q "hello"})))

CompilerException java.lang.IllegalArgumentException: Attempted to perform GET on unregistered URL localhost and real HTTP requests are disabled., compiling:(web/db_test.clj:57:1)

Thanks for your help.

Body:
Instead of the String "localhost?q=hello", you can provide a map with the keys :url and :query-params

(with-fake-http
    [{:query-params {:q "hello"}, :url "localhost"} "hello param"]
    (println @(http/get "localhost" {:query-params {:q "hello"}})))


问:
Proper placement of q.all inside array.map with _.forEach
I have the following code which searches my mongodb using find() using values extracted using array.map. Said search returns an object, which I then used a _.forEach to extract the values.

I used this article as basis, however the difference between his examples and mine was he used only one loop. I'm using two. In this case, where should I put my q.all()?

Here's my code. Please note that is server-side:

```<code>'use strict';
var q = require('q');

exports.downloadEmployee = function (req, res) {
    var tempCtr = [];

    if (req.params.hasdr === "yes") {
        return queries.generateDirectReportsCSV(req.params.id).then(function (directReports) {
            return directReports;
        }).then(function (directReports) {
            var empIDcoll = _.pluck(directReports.Data, "employeenumber");
            return empIDcoll;
        }).then(function (empIDcoll) {
            var promises = [];

            empIDcoll.map(function (id) {

                return EmployeeInfo.find({ employeeID: id }, function (err, results) {
                    if (err) { return err; }

                    _.forEach(results, function (item) {
                        if (item) {
                            tempCtr.push({
                                employeeID: item.employeeID,
                                employeeName: item.employeeName
                            });
                            promises.push(tempCtr);
                        }
                    });
                });

                q.all(promises).then(function (results) {
                    return res.json(results);
                });
            });
        });
    }
</code>```

When I run this, I don't get any result back.

Any answers will be greatly appreciated.

Thank you.

UPDATE: I've decided to revise my code and replaced array.map with the usual for loop:

```<code>.then(function (empIDcoll) {

    for (var i = 0; i <= empIDcoll.length - 1; i++) {
        var promise = EmployeeInfo.find({ employeeID: empIDcoll[i] }, function (err, results) {
            if (err) { return err; }

            _.forEach(results, function (item) {
                if (item) {
                    tempCtr.push({
                        employeeID: item.employeeID,
                        employeeName: item.employeeName,
                        currentShift: item.currentShift,
                        isOpenToIntlAssignment: item.isOpenToIntlAssignment,
                        desiredRole1: item.desiredRole1,
                        desiredRole2: item.desiredRole2,
                        desiredRole3: item.desiredRole3,
                        desiredRoleOther: item.desiredRoleOther,
                        passportInfo: item.passportInfo,
                        visaInfo: item.visaInfo,
                        yrsInIT: item.yrsInIT,
                        yrsAsCustomerPM: item.yrsAsCustomerPM,
                        yrsAsCustomerProgM: item.yrsAsCustomerProgM,
                        primaryDomain: item.primaryDomain,
                        primaryDomainOther: item.primaryDomainOther,
                        primaryIndustry: item.primaryIndustry,
                        primaryIndustryOther: item.primaryIndustryOther,
                        isPMPCertified: item.isPMPCertified,
                        pmpCertExpiryDate: item.pmpCertExpiryDate,
                        isPGMPCertified: item.isPGMPCertified,
                        pgmpCertExpiryDate: item.pgmpCertExpiryDate,
                        isScrumCertified: item.isScrumCertified,
                        scrumCertExpiryDate: item.scrumCertExpiryDate,
                        biggestProjectTCV: item.biggestProjectTCV,
                        biggestTeamSizeManaged: item.biggestTeamSizeManaged,
                        avgTeamSizeManaged: item.avgTeamSizeManaged,
                        biggestBilledFTE: item.biggestBilledFTE,
                        avgBilledFTE: item.avgBilledFTE
                    });
                }
            });
        });
        promises.push(promise);
    }

    return q.all(promises).then(function(data){
        return res.json(data);
    });

});
</code>```

...but it's still not returning anything. What am I doing wrong?

答:
I'm posting my working solution here for the benefit of those who might encounter the same problem in the future. Thank you to SinDeus for the simple and concise solution. :)</p>

```<code>.then(function (empIDcoll) {

        // push user's employee number in first row
        empIDcoll.unshift(req.params.id);

        // return resolved promises from EmployeeInfo.find()
        // this will return user's direct reports' information (if any)
        var promises = empIDcoll.map(function (id) {
            return EmployeeInfo.find({ employeeID: id }).exec();
        });

        // Take resolved promises from above statement and iterate to get final results.
        q.all(promises).then(function (results) {
            _.forEach(results, function (item) {
                var len = item.length - 1;
                if (len >= 0) {
                    tempCtr.push({
                        employeeID: item[0].employeeID,
                        employeeName: item[0].employeeName
                        // ... other fields here ...
                    });
                }
            });
            return res.json(tempCtr);
        });
    });
}
</code>```

Body:
I have the following code which searches my mongodb using find() using values extracted using array.map. Said search returns an object, which I then used a _.forEach to extract the values.

I used this article as basis, however the difference between his examples and mine was he used only one loop. I'm using two. In this case, where should I put my q.all()?

Here's my code. Please note that is server-side:

'use strict';
var q = require('q');

exports.downloadEmployee = function (req, res) {
    var tempCtr = [];

    if (req.params.hasdr === "yes") {
        return queries.generateDirectReportsCSV(req.params.id).then(function (directReports) {
            return directReports;
        }).then(function (directReports) {
            var empIDcoll = _.pluck(directReports.Data, "employeenumber");
            return empIDcoll;
        }).then(function (empIDcoll) {
            var promises = [];

            empIDcoll.map(function (id) {

                return EmployeeInfo.find({ employeeID: id }, function (err, results) {
                    if (err) { return err; }

                    _.forEach(results, function (item) {
                        if (item) {
                            tempCtr.push({
                                employeeID: item.employeeID,
                                employeeName: item.employeeName
                            });
                            promises.push(tempCtr);
                        }
                    });
                });

                q.all(promises).then(function (results) {
                    return res.json(results);
                });
            });
        });
    }

When I run this, I don't get any result back.

Any answers will be greatly appreciated.

Thank you.

UPDATE: I've decided to revise my code and replaced array.map with the usual for loop:

.then(function (empIDcoll) {

    for (var i = 0; i <= empIDcoll.length - 1; i++) {
        var promise = EmployeeInfo.find({ employeeID: empIDcoll[i] }, function (err, results) {
            if (err) { return err; }

            _.forEach(results, function (item) {
                if (item) {
                    tempCtr.push({
                        employeeID: item.employeeID,
                        employeeName: item.employeeName,
                        currentShift: item.currentShift,
                        isOpenToIntlAssignment: item.isOpenToIntlAssignment,
                        desiredRole1: item.desiredRole1,
                        desiredRole2: item.desiredRole2,
                        desiredRole3: item.desiredRole3,
                        desiredRoleOther: item.desiredRoleOther,
                        passportInfo: item.passportInfo,
                        visaInfo: item.visaInfo,
                        yrsInIT: item.yrsInIT,
                        yrsAsCustomerPM: item.yrsAsCustomerPM,
                        yrsAsCustomerProgM: item.yrsAsCustomerProgM,
                        primaryDomain: item.primaryDomain,
                        primaryDomainOther: item.primaryDomainOther,
                        primaryIndustry: item.primaryIndustry,
                        primaryIndustryOther: item.primaryIndustryOther,
                        isPMPCertified: item.isPMPCertified,
                        pmpCertExpiryDate: item.pmpCertExpiryDate,
                        isPGMPCertified: item.isPGMPCertified,
                        pgmpCertExpiryDate: item.pgmpCertExpiryDate,
                        isScrumCertified: item.isScrumCertified,
                        scrumCertExpiryDate: item.scrumCertExpiryDate,
                        biggestProjectTCV: item.biggestProjectTCV,
                        biggestTeamSizeManaged: item.biggestTeamSizeManaged,
                        avgTeamSizeManaged: item.avgTeamSizeManaged,
                        biggestBilledFTE: item.biggestBilledFTE,
                        avgBilledFTE: item.avgBilledFTE
                    });
                }
            });
        });
        promises.push(promise);
    }

    return q.all(promises).then(function(data){
        return res.json(data);
    });

});

...but it's still not returning anything. What am I doing wrong?

Body:
I'm posting my working solution here for the benefit of those who might encounter the same problem in the future. Thank you to SinDeus for the simple and concise solution. :)

.then(function (empIDcoll) {

        // push user's employee number in first row
        empIDcoll.unshift(req.params.id);

        // return resolved promises from EmployeeInfo.find()
        // this will return user's direct reports' information (if any)
        var promises = empIDcoll.map(function (id) {
            return EmployeeInfo.find({ employeeID: id }).exec();
        });

        // Take resolved promises from above statement and iterate to get final results.
        q.all(promises).then(function (results) {
            _.forEach(results, function (item) {
                var len = item.length - 1;
                if (len >= 0) {
                    tempCtr.push({
                        employeeID: item[0].employeeID,
                        employeeName: item[0].employeeName
                        // ... other fields here ...
                    });
                }
            });
            return res.json(tempCtr);
        });
    });
}


问:
symfony2 download file The Response content must be a string
i want download my pdf file where he's saved in my phpmyadmin 'blob'

i try this code:

```<code>public function downloadAction()
{
    $ma_base_de_donne = new myprojectdbEntity();

    $item = $this->getDoctrine()->getRepository('myprojectBundle:myprojectdbEntity')->find(5);
    if (!$item) {
        throw $this->createNotFoundException("File with ID 5 does not exist!");
    }
    $pdfFile = $item->getFichier(); //returns pdf file stored as mysql blob
    //$headers = array('Content-Type' => 'application/pdf', 'Content-Disposition' => "attachment; filename=" . urlencode($pdfFile));
    $response = new Response($pdfFile, 200, array('Content-Type' => 'application/pdf'));
    //return $response;
    var_dump($response); die();
}
</code>```

and i get this error :

The Response content must be a string or object implementing
  __toString(), "resource" given.

help me please

thanks first

答:
Define a __toString() method in your entity object($pdfFile):

```<code>public function __toString() {
    return $name;
}
</code>```

Or send directly the string in your response:

```<code>$response = new Response($pdfFile->getName(), 200, array('Content-Type' => 'application/pdf'));
</code>```

Body:
i want download my pdf file where he's saved in my phpmyadmin 'blob'

i try this code:

public function downloadAction()
{
    $ma_base_de_donne = new myprojectdbEntity();

    $item = $this->getDoctrine()->getRepository('myprojectBundle:myprojectdbEntity')->find(5);
    if (!$item) {
        throw $this->createNotFoundException("File with ID 5 does not exist!");
    }
    $pdfFile = $item->getFichier(); //returns pdf file stored as mysql blob
    //$headers = array('Content-Type' => 'application/pdf', 'Content-Disposition' => "attachment; filename=" . urlencode($pdfFile));
    $response = new Response($pdfFile, 200, array('Content-Type' => 'application/pdf'));
    //return $response;
    var_dump($response); die();
}

and i get this error :

The Response content must be a string or object implementing
  __toString(), "resource" given.

help me please

thanks first

Body:
Define a __toString() method in your entity object($pdfFile):

public function __toString() {
    return $name;
}

Or send directly the string in your response:

$response = new Response($pdfFile->getName(), 200, array('Content-Type' => 'application/pdf'));


问:
Dagger 2 LocalDataSource cannot be provided without @Provides annotated method
I'm trying to follow the same example as in here by creating a Repository pattern with DI.
The problem is that I get the following error:

"Error:(16, 20) error: @mvp.model.di.scope.Local
  mvp.model.repository.local.GameLocalDataSource cannot be provided
  without an @Provides-annotated method. @mvp.model.di.scope.Local
  mvp.model.repository.local.GameLocalDataSource is injected at
  mvp.model.repository.GameRepository.(gameLocalDataSource, …)
  mvp.model.repository.GameRepository is provided at
  mvp.model.di.component.RepositoryComponent.getGameRepository()"

Here's the code related to the app:

```<code>public class GameApplication extends Application {
private RepositoryComponent repositoryComponent;

@Override
public void onCreate() {
    super.onCreate();
    if (LeakCanary.isInAnalyzerProcess(this)) {
        // This process is dedicated to LeakCanary for heap analysis.
        // You should not init your app in this process.
        return;
    }
    LeakCanary.install(this);
    // Normal app init code...
    repositoryComponent = DaggerRepositoryComponent.builder()
            .applicationModule(new ApplicationModule((getApplicationContext())))
            .build();
}

public RepositoryComponent getRepositoryComponent() {
    return repositoryComponent;
}
}
</code>```

This is my RepositoryComponent:

```<code>@Singleton
@Component(modules = {RepositoryModule.class, ApplicationModule.class})
public interface RepositoryComponent {
    GameRepository getGameRepository();
}
</code>```

Here's the RepositoryModule:

```<code>    @Module
public class RepositoryModule {
    @Singleton
    @Provides
    @Local
    GameDataSource provideLocalDataSource(Context context) {
        return new GameLocalDataSource(context);
    }

    @Singleton
    @Provides
    @Remote
    GameDataSource provideRemoteDataSource() {
        return new GameRemoteDataSource();
    }
}
</code>```

And finally, the ApplicationModule:

```<code>    @Module
public final class ApplicationModule {
    private Context context;

    public ApplicationModule(Context context) {
        this.context = context;
    }

    @Provides
    Context providesContext() {
        return context;
    }
}
</code>```

Here's most of my GameRepository class:

```<code>@Singleton
public class GameRepository implements GameDataSource {
    private GameDataSource remoteDataSource;
    private GameDataSource localDataSource;

    @Inject
    public GameRepository(@Local GameLocalDataSource gameLocalDataSource, @Remote GameRemoteDataSource gameRemoteDataSource) {
        remoteDataSource = gameRemoteDataSource;
        localDataSource = gameLocalDataSource;
    }
</code>```

Also, as in the mentioned example, I created a couple of scopes, @Local and @Remote since my two data sources have the same type and Dagger needs to differentiate them.

```<code>@Qualifier
@Documented
@Retention(RetentionPolicy.RUNTIME)
public @interface Local {

}
</code>```

The rest of the code I have related to dagger, is just the @Inject in the constructors where I want to inject my dependencies.
Also, the DaggerRepositoryComponent is never generated in the GameApplication class.

Thanks a lot for the help in advance!

答:
GameLocalDataSource cannot be provided without an @Provides-annotated method

Somewhere in the code you are trying to @Inject GameLocalDataSource, but you have specified in your module how to provide GameDataSource, not GameLocalDataSource.

```<code>...
GameDataSource provideLocalDataSource(Context context) {
    return new GameLocalDataSource(context);
}
...
</code>```

Either ask Dagger to inject GameDataSource, or describe Dagger how to provide GameLocalDataSource.

```<code>...
GameLocalDataSource provideLocalDataSource(Context context) {
    return new GameLocalDataSource(context);
}
...
</code>```

Body:
I'm trying to follow the same example as in here by creating a Repository pattern with DI.
The problem is that I get the following error:

"Error:(16, 20) error: @mvp.model.di.scope.Local
  mvp.model.repository.local.GameLocalDataSource cannot be provided
  without an @Provides-annotated method. @mvp.model.di.scope.Local
  mvp.model.repository.local.GameLocalDataSource is injected at
  mvp.model.repository.GameRepository.(gameLocalDataSource, …)
  mvp.model.repository.GameRepository is provided at
  mvp.model.di.component.RepositoryComponent.getGameRepository()"

Here's the code related to the app:

public class GameApplication extends Application {
private RepositoryComponent repositoryComponent;

@Override
public void onCreate() {
    super.onCreate();
    if (LeakCanary.isInAnalyzerProcess(this)) {
        // This process is dedicated to LeakCanary for heap analysis.
        // You should not init your app in this process.
        return;
    }
    LeakCanary.install(this);
    // Normal app init code...
    repositoryComponent = DaggerRepositoryComponent.builder()
            .applicationModule(new ApplicationModule((getApplicationContext())))
            .build();
}

public RepositoryComponent getRepositoryComponent() {
    return repositoryComponent;
}
}

This is my RepositoryComponent:

@Singleton
@Component(modules = {RepositoryModule.class, ApplicationModule.class})
public interface RepositoryComponent {
    GameRepository getGameRepository();
}

Here's the RepositoryModule:

    @Module
public class RepositoryModule {
    @Singleton
    @Provides
    @Local
    GameDataSource provideLocalDataSource(Context context) {
        return new GameLocalDataSource(context);
    }

    @Singleton
    @Provides
    @Remote
    GameDataSource provideRemoteDataSource() {
        return new GameRemoteDataSource();
    }
}

And finally, the ApplicationModule:

    @Module
public final class ApplicationModule {
    private Context context;

    public ApplicationModule(Context context) {
        this.context = context;
    }

    @Provides
    Context providesContext() {
        return context;
    }
}

Here's most of my GameRepository class:

@Singleton
public class GameRepository implements GameDataSource {
    private GameDataSource remoteDataSource;
    private GameDataSource localDataSource;

    @Inject
    public GameRepository(@Local GameLocalDataSource gameLocalDataSource, @Remote GameRemoteDataSource gameRemoteDataSource) {
        remoteDataSource = gameRemoteDataSource;
        localDataSource = gameLocalDataSource;
    }

Also, as in the mentioned example, I created a couple of scopes, @Local and @Remote since my two data sources have the same type and Dagger needs to differentiate them.

@Qualifier
@Documented
@Retention(RetentionPolicy.RUNTIME)
public @interface Local {

}

The rest of the code I have related to dagger, is just the @Inject in the constructors where I want to inject my dependencies.
Also, the DaggerRepositoryComponent is never generated in the GameApplication class.

Thanks a lot for the help in advance!

Body:
GameLocalDataSource cannot be provided without an @Provides-annotated method

Somewhere in the code you are trying to @Inject GameLocalDataSource, but you have specified in your module how to provide GameDataSource, not GameLocalDataSource.

...
GameDataSource provideLocalDataSource(Context context) {
    return new GameLocalDataSource(context);
}
...

Either ask Dagger to inject GameDataSource, or describe Dagger how to provide GameLocalDataSource.

...
GameLocalDataSource provideLocalDataSource(Context context) {
    return new GameLocalDataSource(context);
}
...


问:
Lua - understanding setmetatable
I am trying to build a CNN using Torch 7. I am very new to Lua. I was trying to follow this link. I encountered something called setmetatable in the following code block:

```<code>setmetatable(train_set,
{
  __index = function(t, i)
    return {t.data[i], t.label[i]}
  end
});
</code>```

I understand that the second argument acts as the metatable for the table train_set.

1) Is t the metatable or is t just another name for train_set?

2) Whenever a function is used against __index, does the interpreter assume the first argument (t) to be a table (or metatable, depending on answer to first question)? And is the second argument always the key or index?

3) My understanding is that if I use train_set.data[1], it will invoke the __index. The answer here says that __index is invoked when key does not exist in the table. But is t.data[1] same as train_set.data[1]? If so, how does the interpreter know that?

答:
First, two important links:

metatables in Programming in Lua;

metatable events in the Lua wiki.

Now the answers:

t, the first parameter of the __index method in a metatable, refers to the table that has the metatable, here train_set. This parameter allows to reuse the same metatable for several tables.

__index is a special function inside metatables (look at the metatable events), that is called whenever a field in the metatabled table is accessed but missing. For instance, if train_set does not contain the key k and you read train_set.k, there will be a call to __index (train_set, "k") in its metatable.

From what i can infer from the code, the usage pattern in your example looks like local x = train_set [1] that will return a table containing { train_set.data[i], train_set.label[i] }.

Title: Lua - understanding setmetatable

Body:
I am trying to build a CNN using Torch 7. I am very new to Lua. I was trying to follow this link. I encountered something called setmetatable in the following code block:

setmetatable(train_set,
{
  __index = function(t, i)
    return {t.data[i], t.label[i]}
  end
});

I understand that the second argument acts as the metatable for the table train_set.

1) Is t the metatable or is t just another name for train_set?

2) Whenever a function is used against __index, does the interpreter assume the first argument (t) to be a table (or metatable, depending on answer to first question)? And is the second argument always the key or index?

3) My understanding is that if I use train_set.data[1], it will invoke the __index. The answer here says that __index is invoked when key does not exist in the table. But is t.data[1] same as train_set.data[1]? If so, how does the interpreter know that?


问:
Remove duplicate rows from joined table
I have following sql query

```<code>SELECT m.School, c.avgscore
FROM postswithratings c
join ZEntrycriteria on c.fk_postID= m.schoolcode
</code>```

Which provide following result

```<code>School| avgscore
xyz   |  5
xyz   |  5
xyz   |  5
abc   |  3
abc   |  3
kkk   |  1
</code>```

My question is how to remove those duplicates and get only following.

```<code> School| avgscore
    xyz   |  5
    abc   |  3
    kkk   |  1
</code>```

I tried with

```<code>   SELECT m.School, c.avgscore
   FROM postswithratings c
   join ZEntrycriteria on c.fk_postID= m.schoolcode
   group by m.School
</code>```

But it gives me following error

"Column 'postswithratings.avgscore' is invalid in the select list
  because it is not contained in either an aggregate function or the
  GROUP BY clause."

答:
you only use group by if you're using aggregated function, eg. max. sum, avg

in that case,

```<code>SELECT Distinct(m.School), c.avgscore
FROM postswithratings c
join ZEntrycriteria on c.fk_postID= m.schoolcode
</code>```

Title: Remove duplicate rows from joined table

Body:
I have following sql query

SELECT m.School, c.avgscore
FROM postswithratings c
join ZEntrycriteria on c.fk_postID= m.schoolcode

Which provide following result

School| avgscore
xyz   |  5
xyz   |  5
xyz   |  5
abc   |  3
abc   |  3
kkk   |  1

My question is how to remove those duplicates and get only following.

 School| avgscore
    xyz   |  5
    abc   |  3
    kkk   |  1

I tried with

   SELECT m.School, c.avgscore
   FROM postswithratings c
   join ZEntrycriteria on c.fk_postID= m.schoolcode
   group by m.School

But it gives me following error

"Column 'postswithratings.avgscore' is invalid in the select list
  because it is not contained in either an aggregate function or the
  GROUP BY clause."

Body:
you only use group by if you're using aggregated function, eg. max. sum, avg

in that case,

SELECT Distinct(m.School), c.avgscore
FROM postswithratings c
join ZEntrycriteria on c.fk_postID= m.schoolcode


问:
Data view don't show the index of DataFrame neither rows numbers from numpy array
I am using Pycharm Community Edition 2017.1 and when I try to see a DataFrame or a numpy array, the "data view" does not show the rows index neither the rows numbers, respectively. See attached an example with DataFrame. What am I missing?

The code:

```<code>import numpy as np
import pandas as pd
var = np.arange(3*2).reshape((3,2))
fr = pd.DataFrame(var, columns=['a','b'], index=range(np.shape(var)[0]))
fr
Out[6]:
   a  b
0  0  1
1  2  3
2  4  5
</code>```

I really appreciate help.

Alexandre

答:
I suppose showing the row numbers or index is a feature which is supported in Linux and Mac platform, it works well on my MacBook.

From Viewing as Array or DataFrame and Pandas Dataframes Viewer , I suppose this feature has not been supported in Windows yet.

Update

PyCharm 2017.1.3 (May 4, 2017)  RC fix this issue,
See
PyCharm 171.4249.61 Release Notes.

Body:
I am using Pycharm Community Edition 2017.1 and when I try to see a DataFrame or a numpy array, the "data view" does not show the rows index neither the rows numbers, respectively. See attached an example with DataFrame. What am I missing?

The code:

import numpy as np
import pandas as pd
var = np.arange(3*2).reshape((3,2))
fr = pd.DataFrame(var, columns=['a','b'], index=range(np.shape(var)[0]))
fr
Out[6]:
   a  b
0  0  1
1  2  3
2  4  5

I really appreciate help.

Alexandre


问:
Using the text replaced in the replace text
I'm using the version 7.3.3 of Notepad++.

I have this list of numbers to 1.000.000.

```<code>1
2
3
4
5
6
7
8
9
10
11
12
13
14
</code>```

I want to add XML tags to these numbers like this:

```<code><SerialNumber>
    <SN>1</SN>
</SerialNumber>
<SerialNumber>
    <SN>2</SN>
</SerialNumber>
<SerialNumber>
    <SN>3</SN>
</SerialNumber>
<SerialNumber>
    <SN>4</SN>
</SerialNumber>
</code>```

So I need a regular expression to find a number ended with a \n\r, and use the number I've found with the regular expression in the text that I'm going to add.

Do you know to do that in Notepad++?

I have tried with \d{*} but it is not a valid regular expression.

答:
if we take your [1.... n] numbers in string called strData then :

```<code>var nums = strData.split("\r\n").map(function(item) {
    return parseInt(item, 10);
});
var strXmlOut = nums.map(function(n) {
   return "<SerialNumber><SN>" + n + "</SN></SerialNumber>";
}).join("\r\n");
</code>```

and the one call version would be :

```<code>var xmlOut = strData.split("\r\n")
.map(function(item) {return parseInt(item, 10);})
.map(function(n) {return "<SerialNumber><SN>" + n + "</SN></SerialNumber>";})
.join("\r\n");
</code>```

Body:
I'm using the version 7.3.3 of Notepad++.

I have this list of numbers to 1.000.000.

1
2
3
4
5
6
7
8
9
10
11
12
13
14

I want to add XML tags to these numbers like this:

<SerialNumber>
    <SN>1</SN>
</SerialNumber>
<SerialNumber>
    <SN>2</SN>
</SerialNumber>
<SerialNumber>
    <SN>3</SN>
</SerialNumber>
<SerialNumber>
    <SN>4</SN>
</SerialNumber>

So I need a regular expression to find a number ended with a \n\r, and use the number I've found with the regular expression in the text that I'm going to add.

Do you know to do that in Notepad++?

I have tried with \d{*} but it is not a valid regular expression.

Body:
if we take your [1.... n] numbers in string called strData then :

var nums = strData.split("\r\n").map(function(item) {
    return parseInt(item, 10);
});
var strXmlOut = nums.map(function(n) {
   return "<SerialNumber><SN>" + n + "</SN></SerialNumber>";
}).join("\r\n");

and the one call version would be :

var xmlOut = strData.split("\r\n")
.map(function(item) {return parseInt(item, 10);})
.map(function(n) {return "<SerialNumber><SN>" + n + "</SN></SerialNumber>";})
.join("\r\n");


问:
TableView crashes while making search using search bar during fast typing

I have used fetchedResultsController(FRC) to fetch and list a tableview using fetchedObjects. And the items are listed fine.

I am also having a search bar. On typing any string will update the FRC as shown below & perfomFetch() and reload the tableView.

fetchedResultsController.fetchRequest.predicate = NSPredicate(format: "title CONTAINS[c] %@, text)

Everything is working fine, except when I search faster on searchBar. The crash is happening in cellForRowAtIndexPath & numberOfSections saying that the fetchedObjects is 'Empty'

How to resolve the crash due to fast search ?

答:
If you have used FetchedResultsController's fetchedObjects count property specify the number of rows in section, sometimes your FetchedResultsController's fetchedObject might be nil in such cases app crashes.

try

```<code>override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return self.fetchedResultsController.fetchedObjects?.count ?? 0
    }
</code>```

Body:
If you have used FetchedResultsController's fetchedObjects count property specify the number of rows in section, sometimes your FetchedResultsController's fetchedObject might be nil in such cases app crashes.

try

override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return self.fetchedResultsController.fetchedObjects?.count ?? 0
    }


问:
Parsing string AngularJS $http to .NET Core controller
I'm trying out AngularJS in combination with NET Core. Currently trying to parse a "string username", "string password" and "bool rememberMe", but both strings are null no matter what I do. I've even tried parsing a constant value as seen below, the parameter "test", but even that doesn't work. I've confirmed in Fiddler that the script is in fact parsing the value, so the controller basically just can't "fetch it".

Below is my AngularJS loginController code.

```<code>var login = angular.module('login', []);
login.controller('LoginController',
    [
        '$scope', '$http', '$window', function ($scope, $http, $window) {
            $scope.submit = function () {
                var data = { test: ':D' };
                $http({
                    method: 'POST',
                    url: '/admin',
                    data: data
                }).then(function success(response) {
                    alert(response.data.test);
                });
            }
        }
    ]);
</code>```

Below is the code for my ActionResult meant to fetch the value being posted to it.

```<code>[HttpPost]
        public IActionResult Index(string test)
        {
            return Json(new
            {
                test,
                bla = "BLA"
            });
            //if (!string.IsNullOrEmpty(username) && !string.IsNullOrEmpty(password))
            //{
            //    if (UserSystem.Login(username, password, rememberMe, HttpContext))
            //    {
            //        HttpContext.Response.StatusCode = (int)HttpStatusCode.Accepted;
            //        return Json(new
            //        {
            //            returnUrl = "/admin/dashboard"
            //        });
            //    }
            //}
            //HttpContext.Response.StatusCode = (int)HttpStatusCode.InternalServerError;
            //return Json(new
            //{
            //    error = "Username and/or password do not match"
            //});
        }
</code>```

I've also tried specifying the Content-Type, but also without luck. Either way, in Fiddler the request always seems to per default be application/json.

I hope someone can help me. Thanks!

答:
The solution was to request an object in the controller, rather than "string username", "string password" and "bool rememberMe".

The controller now looks like this:

```<code>    public class LoginModel
    {
        public string Username { get; set; }
        public string Password { get; set; }
        public bool RememberMe { get; set; }
    }
    [HttpPost]
    public IActionResult Index([FromBody]LoginModel model)
    {
        if (!string.IsNullOrEmpty(model.Username) && !string.IsNullOrEmpty(model.Password))
        {
            if (UserSystem.Login(model.Username, model.Password, model.RememberMe, HttpContext))
            {
                HttpContext.Response.StatusCode = (int)HttpStatusCode.Accepted;
                return Json(new
                {
                    returnUrl = "/admin/dashboard"
                });
            }
        }
        HttpContext.Response.StatusCode = (int)HttpStatusCode.InternalServerError;
        return Json(new
        {
            error = "Username and/or password do not match"
        });
    }
</code>```

And the AngularJS controller now looks like this:

```<code>var login = angular.module('login', []);
login.controller('LoginController',
    [
        '$scope', '$http', '$window', function ($scope, $http, $window) {
            $scope.submit = function () {
                var data = {
                    username: $scope.username,
                    password: $scope.password,
                    rememberMe: $scope.rememberMe
                };
                $http({
                    method: 'POST',
                    url: '/admin',
                    data: data
                }).then(function success(response) {
                    $window.location.href = response.data.returnUrl;
                }, function fail(response) {
                    swal('Error!', response.data.error, 'error');
                });
            }
        }
    ]);
</code>```

Body:
I'm trying out AngularJS in combination with NET Core. Currently trying to parse a "string username", "string password" and "bool rememberMe", but both strings are null no matter what I do. I've even tried parsing a constant value as seen below, the parameter "test", but even that doesn't work. I've confirmed in Fiddler that the script is in fact parsing the value, so the controller basically just can't "fetch it".

Below is my AngularJS loginController code.

var login = angular.module('login', []);
login.controller('LoginController',
    [
        '$scope', '$http', '$window', function ($scope, $http, $window) {
            $scope.submit = function () {
                var data = { test: ':D' };
                $http({
                    method: 'POST',
                    url: '/admin',
                    data: data
                }).then(function success(response) {
                    alert(response.data.test);
                });
            }
        }
    ]);

Below is the code for my ActionResult meant to fetch the value being posted to it.

[HttpPost]
        public IActionResult Index(string test)
        {
            return Json(new
            {
                test,
                bla = "BLA"
            });
            //if (!string.IsNullOrEmpty(username) && !string.IsNullOrEmpty(password))
            //{
            //    if (UserSystem.Login(username, password, rememberMe, HttpContext))
            //    {
            //        HttpContext.Response.StatusCode = (int)HttpStatusCode.Accepted;
            //        return Json(new
            //        {
            //            returnUrl = "/admin/dashboard"
            //        });
            //    }
            //}
            //HttpContext.Response.StatusCode = (int)HttpStatusCode.InternalServerError;
            //return Json(new
            //{
            //    error = "Username and/or password do not match"
            //});
        }

I've also tried specifying the Content-Type, but also without luck. Either way, in Fiddler the request always seems to per default be application/json.

I hope someone can help me. Thanks!

Body:
The solution was to request an object in the controller, rather than "string username", "string password" and "bool rememberMe".

The controller now looks like this:

    public class LoginModel
    {
        public string Username { get; set; }
        public string Password { get; set; }
        public bool RememberMe { get; set; }
    }
    [HttpPost]
    public IActionResult Index([FromBody]LoginModel model)
    {
        if (!string.IsNullOrEmpty(model.Username) && !string.IsNullOrEmpty(model.Password))
        {
            if (UserSystem.Login(model.Username, model.Password, model.RememberMe, HttpContext))
            {
                HttpContext.Response.StatusCode = (int)HttpStatusCode.Accepted;
                return Json(new
                {
                    returnUrl = "/admin/dashboard"
                });
            }
        }
        HttpContext.Response.StatusCode = (int)HttpStatusCode.InternalServerError;
        return Json(new
        {
            error = "Username and/or password do not match"
        });
    }

And the AngularJS controller now looks like this:

var login = angular.module('login', []);
login.controller('LoginController',
    [
        '$scope', '$http', '$window', function ($scope, $http, $window) {
            $scope.submit = function () {
                var data = {
                    username: $scope.username,
                    password: $scope.password,
                    rememberMe: $scope.rememberMe
                };
                $http({
                    method: 'POST',
                    url: '/admin',
                    data: data
                }).then(function success(response) {
                    $window.location.href = response.data.returnUrl;
                }, function fail(response) {
                    swal('Error!', response.data.error, 'error');
                });
            }
        }
    ]);


问:
Jackson ObjectMapper() constructor throws NoSuchMethod
I'm using Jackson sample code to deserialize a POJO:

```<code>ObjectMapper m = new ObjectMapper();
</code>```

This line throws a NoSuchMethodError:

```<code>Exception in thread "main" java.lang.NoSuchMethodError: org.codehaus.jackson.type.JavaType.<init>(Ljava/lang/Class;)V
    at org.codehaus.jackson.map.type.TypeBase.<init>(TypeBase.java:15)
    at org.codehaus.jackson.map.type.SimpleType.<init>(SimpleType.java:45)
    at org.codehaus.jackson.map.type.SimpleType.<init>(SimpleType.java:40)
    at org.codehaus.jackson.map.type.TypeBindings.<clinit>(TypeBindings.java:18)
    at org.codehaus.jackson.map.type.TypeFactory._fromType(TypeFactory.java:525)
    at org.codehaus.jackson.map.type.TypeFactory.type(TypeFactory.java:61)
    at org.codehaus.jackson.map.ObjectMapper.<clinit>(ObjectMapper.java:179)
    at com.me.util.ctrl.BillingJobStatus.fromJson(BillingJobStatus.java:37)
</code>```

I don't get it

答:
I have faced this problem when migrating my WebApp from Tomcat 6 to Tomcat 8.
On Tomcat6 and Tomcat7 my WebApp would start just fine, but on Tomcat8 I would get this exception(seems that T6 and T7 loads classes alphabeticaly but T8 doesn't - https://stackoverflow.com/a/26642798/1864614).

The problem was that I was having 2 versions of the class ```org.codehaus.jackson.map.ObjectMapper```
As answered by @wild_nothing I have checked dependency the tree to list all dependencies on org.codehaus.jackson

In my case the problem was that I had several versions of libraries that provided this class:

org.codehaus.jackson:jackson-mapper-lgpl:jar:1.5.0

org.codehaus.jackson:jackson-core-lgpl:jar:1.5.0

org.codehaus.jackson:jackson-mapper-asl:jar:1.8.2

org.codehaus.jackson:jackson-core-asl:jar:1.8.2

My solution was to exclude the older versions(1.5.0) and only leave the 1.8.2 version

```<code><dependency>
        <groupId>cfm.foo</groupId>
        <artifactId>jive</artifactId>
        <exclusions>
            <exclusion>
                <groupId>org.codehaus.jackson</groupId>
                <artifactId>jackson-core-lgpl</artifactId>
            </exclusion>
            <exclusion>
                <groupId>org.codehaus.jackson</groupId>
                <artifactId>jackson-mapper-lgpl</artifactId>
            </exclusion>
        </exclusions>
    </dependency>
</code>```

in this case jive was depending on older 1.5.0 version

ContentLicense: CC BY-SA 2.5

Body:
I'm using Jackson sample code to deserialize a POJO:

ObjectMapper m = new ObjectMapper();

This line throws a NoSuchMethodError:

Exception in thread "main" java.lang.NoSuchMethodError: org.codehaus.jackson.type.JavaType.<init>(Ljava/lang/Class;)V
    at org.codehaus.jackson.map.type.TypeBase.<init>(TypeBase.java:15)
    at org.codehaus.jackson.map.type.SimpleType.<init>(SimpleType.java:45)
    at org.codehaus.jackson.map.type.SimpleType.<init>(SimpleType.java:40)
    at org.codehaus.jackson.map.type.TypeBindings.<clinit>(TypeBindings.java:18)
    at org.codehaus.jackson.map.type.TypeFactory._fromType(TypeFactory.java:525)
    at org.codehaus.jackson.map.type.TypeFactory.type(TypeFactory.java:61)
    at org.codehaus.jackson.map.ObjectMapper.<clinit>(ObjectMapper.java:179)
    at com.me.util.ctrl.BillingJobStatus.fromJson(BillingJobStatus.java:37)

I don't get it

Body:
I have faced this problem when migrating my WebApp from Tomcat 6 to Tomcat 8.
On Tomcat6 and Tomcat7 my WebApp would start just fine, but on Tomcat8 I would get this exception(seems that T6 and T7 loads classes alphabeticaly but T8 doesn't - https://stackoverflow.com/a/26642798/1864614).

The problem was that I was having 2 versions of the class
org.codehaus.jackson.map.ObjectMapper

As answered by @wild_nothing I have checked dependency the tree to list all dependencies on org.codehaus.jackson

In my case the problem was that I had several versions of libraries that provided this class:

org.codehaus.jackson:jackson-mapper-lgpl:jar:1.5.0

org.codehaus.jackson:jackson-core-lgpl:jar:1.5.0

org.codehaus.jackson:jackson-mapper-asl:jar:1.8.2

org.codehaus.jackson:jackson-core-asl:jar:1.8.2

My solution was to exclude the older versions(1.5.0) and only leave the 1.8.2 version

<dependency>
        <groupId>cfm.foo</groupId>
        <artifactId>jive</artifactId>
        <exclusions>
            <exclusion>
                <groupId>org.codehaus.jackson</groupId>
                <artifactId>jackson-core-lgpl</artifactId>
            </exclusion>
            <exclusion>
                <groupId>org.codehaus.jackson</groupId>
                <artifactId>jackson-mapper-lgpl</artifactId>
            </exclusion>
        </exclusions>
    </dependency>

in this case jive was depending on older 1.5.0 version


问:
What is "this" in javascript when calling a method on a calculated object?
I know this is probably the second most asked-about thing in javascript, right after floating point arithmetic.

I generally know how this works, and how it's affected by arrow functions, .call(), .apply(), and .bind().  I thought I understood everything about it.  But I do not.

In a web browser, document.createElement("div").classList.add("c") yields undefined as expected.  However, this expression surprisingly is an error.

```<code>(true && document.createElement("div").classList.add)("c")
</code>```

I expected it to be the same, but it's

```<code>Uncaught TypeError: Illegal invocation
    at <anonymous>:1:54
</code>```

答:
This will work, as it is returning this as classlist context

```<code>(document.createElement("div").classList.add)("c")
</code>```

(true && document.createElement("div").classList.add) will not work as add is getting evaluated  with && expression and after this its returning context of the expression (true && document.createElement("div").classList.add) which is add() { [native code] } and not classList and here we are trying to call add on add function.

When you are trying pass class name ("c") to add then this is not classlist any more hence Illegal invocation

Body:
I know this is probably the second most asked-about thing in javascript, right after floating point arithmetic.

I generally know how this works, and how it's affected by arrow functions, .call(), .apply(), and .bind().  I thought I understood everything about it.  But I do not.

In a web browser, document.createElement("div").classList.add("c") yields undefined as expected.  However, this expression surprisingly is an error.

(true && document.createElement("div").classList.add)("c")

I expected it to be the same, but it's

Uncaught TypeError: Illegal invocation
    at <anonymous>:1:54

Body:
This will work, as it is returning this as classlist context

(document.createElement("div").classList.add)("c")

(true && document.createElement("div").classList.add) will not work as add is getting evaluated  with && expression and after this its returning context of the expression (true && document.createElement("div").classList.add) which is add() { [native code] } and not classList and here we are trying to call add on add function.

When you are trying pass class name ("c") to add then this is not classlist any more hence Illegal invocation


问:
After Maven build jar changes do not show
I made some changes to an old Java project and built a new jar out of it successfully using

```<code>mvn clean eclipse:clean eclipse:eclipse install -DskipTests
</code>```

and saved it in my local directory.

However, when I specify its file path (the local directory location) in another project and run it, the changes don't show in the output. Analyzing the produced jar shoewed, that the new changes were not included.

To be clear: I made changes to the pom.xml; specifically, I added maven-toolchains as a plugin dependency.

Any solutions?

答:
There are two things I don't really understand.

Why install?

Why eclipse:clean eclipse:eclipse?

If you only need the generated jar to be but in a non maven managed application, package would suffice, your newly packaged jar would be in target dir, non need to install it into local repository.

If you are just packaging your project to put it in the classpath of another project eclipse:clean eclipse:eclipse does nothing useful , it will fix the eclipse project settings,but wont change anything in the build.

My advice is just mvn package your project get the file from the target directory and copy it into the target project classpath.

If (instead) you have changed also dependency in the project you want to export, maybe just using the artifact is not enough (if you did change something in the POM) there are good chances that you need to do something more then just copying a jar.

Body:
I made some changes to an old Java project and built a new jar out of it successfully using

mvn clean eclipse:clean eclipse:eclipse install -DskipTests

and saved it in my local directory.

However, when I specify its file path (the local directory location) in another project and run it, the changes don't show in the output. Analyzing the produced jar shoewed, that the new changes were not included.

To be clear: I made changes to the pom.xml; specifically, I added maven-toolchains as a plugin dependency.

Any solutions?


问:
Testing a map contained in a mocked class
I am trying to test a ExampleController class which works kind of like a facade for my POJO Example class.

I started to write a InstrumentedTest for the ExampleController because it works with Greenrobots EventBus, and got a NullPointerException when I tried to retrieve values which are stored in a Map in my Example class.

I use Mockito v2.7.19, Espresso 2.2.2 and  JUnit 4.12.

I recreated my problem in a Unit test with the following example setup:

```<code>class Example {
    private HashMap<Integer, String> map;
    Example(){ map = new HashMap<>(); }
    //getter and setter for map
}

class ExampleController {
    private Example example;
    ExampleController(Example example){ this.example = example; }

    public HashMap<Integer, String> getMap(){ return example.getMap(); }
}
</code>```

Test class:

```<code>class ExampleControllerTest {
    ExampleController exampleController;

    @Before
    public void setUp() throws Exception {
        Example example = mock(Example.class);
        exampleController = new ExampleController(example);
    }

    @Test
    public void testPutThingsInMap() throws Exception {
        HashMap<Integer, String> map = exampleController.getMap();
        map.put(1, "Test");
        exampleController.getMap().putAll(map);

        assertEquals(1, exampleController.getMap().size());
    }
}
</code>```

When I run the test class I get the following output:

```<code>java.lang.AssertionError:
Expected :1
Actual   :0
</code>```

As I am relatively new to testing, I don't know where I went wrong. When I search for unit testing lists, I only find tests for lists that are not contained in an object.

答:
You can't use the "getMap" method like that, because you mocked the Example class in the ExampleController.
You could fix this by adding the following in the before-method:

```<code>HashMap<Integer, String> mapInMock = new HashMap<>();
when(example.getMap()).thenReturn(mapInMock);
</code>```

This way you're telling the mocked Example to return that hashMap when the getter is called.

I can't find it immediately in the javadoc, but debugging the test shows that the map a new map is returned after each call to exampleController.getMap(). That explains why you can't get anything in the map and retrieve it afterwards with your exampleController.

Besides this being the solution you can wonder if you actually need to mock the Example class. You could also just instantiate it, unless you actually want to mock some parts of it.

Body:
I am trying to test a ExampleController class which works kind of like a facade for my POJO Example class.

I started to write a InstrumentedTest for the ExampleController because it works with Greenrobots EventBus, and got a NullPointerException when I tried to retrieve values which are stored in a Map in my Example class.

I use Mockito v2.7.19, Espresso 2.2.2 and  JUnit 4.12.

I recreated my problem in a Unit test with the following example setup:

class Example {
    private HashMap<Integer, String> map;
    Example(){ map = new HashMap<>(); }
    //getter and setter for map
}

class ExampleController {
    private Example example;
    ExampleController(Example example){ this.example = example; }

    public HashMap<Integer, String> getMap(){ return example.getMap(); }
}

Test class:

class ExampleControllerTest {
    ExampleController exampleController;

    @Before
    public void setUp() throws Exception {
        Example example = mock(Example.class);
        exampleController = new ExampleController(example);
    }

    @Test
    public void testPutThingsInMap() throws Exception {
        HashMap<Integer, String> map = exampleController.getMap();
        map.put(1, "Test");
        exampleController.getMap().putAll(map);

        assertEquals(1, exampleController.getMap().size());
    }
}

When I run the test class I get the following output:

java.lang.AssertionError:
Expected :1
Actual   :0

As I am relatively new to testing, I don't know where I went wrong. When I search for unit testing lists, I only find tests for lists that are not contained in an object.

Body:
You can't use the "getMap" method like that, because you mocked the Example class in the ExampleController.
You could fix this by adding the following in the before-method:

HashMap<Integer, String> mapInMock = new HashMap<>();
when(example.getMap()).thenReturn(mapInMock);

This way you're telling the mocked Example to return that hashMap when the getter is called.

I can't find it immediately in the javadoc, but debugging the test shows that the map a new map is returned after each call to exampleController.getMap(). That explains why you can't get anything in the map and retrieve it afterwards with your exampleController.

Besides this being the solution you can wonder if you actually need to mock the Example class. You could also just instantiate it, unless you actually want to mock some parts of it.


问:
Using LINQ to return average of distinct values
I don't have much experience with LINQ and I'm having difficulties using LINQ to extract the average, mode and median for a column of a ListView based on distinct values in a different column.

For example, consider this data:

```<code>ReportID  TAT  Col3  Col4  etc...
--------  ---  ----  ----  -------
80424     9    1     7     ...
80424     9    2     3     ...
80424     9    2     2     ...
80423     5    1     5     ...
80425     4    1     5     ...
80423     7    1     4     ...
82541     7    1     5     ...
</code>```

To extract the count of distinct reports that have a TAT (turnaround time) greater than 5 days, I use the following:

```<code>int countDistinctReports = (from ListViewItem itm in lvList.Items
                            where itm.SubItems[1].Text) > 5
                            select itm.SubItems[0].Text
                           ).Distinct().Count();
</code>```

The value of countDistinctReports is 3.

To extract the minimum TAT for these reports I use this:

```<code>string minVal = (from ListViewItem itm in lvList.Items
             where itm.SubItems[1].Text) > 5
             select itm.SubItems[1].Text
            ).Min();
</code>```

The value of minVal is 7.

However, I don't know how to write LINQ expressions to calculate the average, mode and median TAT of distinct reports that have their TAT greater than 5. In the above example, the average should be (9+7+7)/3 = 7.67. The mode should be 7.

Can someone please help? Many thanks.

答:
You should use the GroupBy method.

```<code>var groups = myList.GroupBy(e=>e.Key);//here key is your TAT
</code>```

Then if you want to count the number of groups:

```<code>var count = groups.Count();
</code>```

If you want to get the minimum of all groups:

```<code>var mins = groups.Select(g=>g.Min());
</code>```

If you want to get and keep the key information:

```<code>var keyedMins = groups.Select(g=>new{K=g.Key,Min=g.Min()};
</code>```

Same for average and other :)

Body:
I don't have much experience with LINQ and I'm having difficulties using LINQ to extract the average, mode and median for a column of a ListView based on distinct values in a different column.

For example, consider this data:

ReportID  TAT  Col3  Col4  etc...
--------  ---  ----  ----  -------
80424     9    1     7     ...
80424     9    2     3     ...
80424     9    2     2     ...
80423     5    1     5     ...
80425     4    1     5     ...
80423     7    1     4     ...
82541     7    1     5     ...

To extract the count of distinct reports that have a TAT (turnaround time) greater than 5 days, I use the following:

int countDistinctReports = (from ListViewItem itm in lvList.Items
                            where itm.SubItems[1].Text) > 5
                            select itm.SubItems[0].Text
                           ).Distinct().Count();

The value of countDistinctReports is 3.

To extract the minimum TAT for these reports I use this:

string minVal = (from ListViewItem itm in lvList.Items
             where itm.SubItems[1].Text) > 5
             select itm.SubItems[1].Text
            ).Min();

The value of minVal is 7.

However, I don't know how to write LINQ expressions to calculate the average, mode and median TAT of distinct reports that have their TAT greater than 5. In the above example, the average should be (9+7+7)/3 = 7.67. The mode should be 7.

Can someone please help? Many thanks.

Body:
You should use the GroupBy method.

var groups = myList.GroupBy(e=>e.Key);//here key is your TAT

Then if you want to count the number of groups:

var count = groups.Count();

If you want to get the minimum of all groups:

var mins = groups.Select(g=>g.Min());

If you want to get and keep the key information:

var keyedMins = groups.Select(g=>new{K=g.Key,Min=g.Min()};

Same for average and other :)


问:
Setting Jenkins build name from package.json version value
I want to include the value of the "version" parameter in package.json as part of the Jenkins build name.

I'm using the Jenkins Build Name Setter plugin - https://wiki.jenkins-ci.org/display/JENKINS/Build+Name+Setter+Plugin

So far I've tried to use PROPFILE syntax in the "Build name macro template" step:

```<code>${PROPFILE,file="./mainline/projectDirectory/package.json",property="\"version\""}
</code>```

This successfully creates a build, but includes the quotes and comma surrounding the value of the version property in package.json, for example:

```<code>"0.0.1",
</code>```

I want just the value inside returned, so it reads

```<code>0.0.1
</code>```

How can I do this? Is there a different plugin that would work better for parsing package.json and getting it into the template, or should I resort to some sort of regex for removing the characters I don't want?

UPDATE:

I tried using token transforms based on reading the Token Macro Plugin documentation, but it's not working:

```<code>${PROPFILE%\"\,#\",file="./mainline/projectDirectory/package.json",property="\"version\""}
</code>```

still just returns

However, using only one escaped character and only one of # or % works. No other combinations I tried work.

```<code>${PROPFILE%\,,file="./mainline/projectDirectory/package.json",property="\"version\""}
</code>```

which returns "0.0.1" (comma removed)

```<code>${PROPFILE#\"%\"\,,file="./mainline/projectDirectory/package.json",property="\"version\""}
</code>```

which returns "0.0.1", (no characters removed)

UPDATE:
Tried to use the new Jenkins Token Macro plugin's JSON macro with no luck.

Jenkins Build Name Setter set to update the build name with Macro:

```<code>${JSON,file="./mainline/pathToFiles/package.json",path="version"}-${P4_CHANGELIST}
</code>```

Jenkins build logs for this job show:

```<code>10:57:55 Evaluated macro: 'Error processing tokens: Error while parsing action 'Text/ZeroOrMore/FirstOf/Token/DelimitedToken/DelimitedToken_Action3' at input position (line 1, pos 74):
10:57:55 ${JSON,file="./mainline/pathToFiles/package.json",path="version"}-334319
10:57:55                                                                          ^
10:57:55
10:57:55 java.io.IOException: Unable to serialize org.jenkinsci.plugins.tokenmacro.impl.JsonFileMacro$ReadJSON@2707de37'
</code>```

答:
Try the token transformations # and % (see Token-Makro-Plugin):

${PROPFILE#"%",file="./mainline/projectDirectory/package.json",property="\"version\""}

Body:
I want to include the value of the "version" parameter in package.json as part of the Jenkins build name.

I'm using the Jenkins Build Name Setter plugin - https://wiki.jenkins-ci.org/display/JENKINS/Build+Name+Setter+Plugin

So far I've tried to use PROPFILE syntax in the "Build name macro template" step:

${PROPFILE,file="./mainline/projectDirectory/package.json",property="\"version\""}

This successfully creates a build, but includes the quotes and comma surrounding the value of the version property in package.json, for example:

"0.0.1",

I want just the value inside returned, so it reads

0.0.1

How can I do this? Is there a different plugin that would work better for parsing package.json and getting it into the template, or should I resort to some sort of regex for removing the characters I don't want?

UPDATE:

I tried using token transforms based on reading the Token Macro Plugin documentation, but it's not working:

${PROPFILE%\"\,#\",file="./mainline/projectDirectory/package.json",property="\"version\""}

still just returns

However, using only one escaped character and only one of # or % works. No other combinations I tried work.

${PROPFILE%\,,file="./mainline/projectDirectory/package.json",property="\"version\""}

which returns "0.0.1" (comma removed)

${PROPFILE#\"%\"\,,file="./mainline/projectDirectory/package.json",property="\"version\""}

which returns "0.0.1", (no characters removed)

UPDATE:
Tried to use the new Jenkins Token Macro plugin's JSON macro with no luck.

Jenkins Build Name Setter set to update the build name with Macro:

${JSON,file="./mainline/pathToFiles/package.json",path="version"}-${P4_CHANGELIST}

Jenkins build logs for this job show:

10:57:55 Evaluated macro: 'Error processing tokens: Error while parsing action 'Text/ZeroOrMore/FirstOf/Token/DelimitedToken/DelimitedToken_Action3' at input position (line 1, pos 74):
10:57:55 ${JSON,file="./mainline/pathToFiles/package.json",path="version"}-334319
10:57:55                                                                          ^
10:57:55
10:57:55 java.io.IOException: Unable to serialize org.jenkinsci.plugins.tokenmacro.impl.JsonFileMacro$ReadJSON@2707de37'


问:
checkboxes are not appearing in browser
```<code><table class="table table-striped table-bordered table-hover" id="datatable_users">
    <thead>
        <tr role="row" class="heading">
            <th class="table-checkbox" align="center" style="padding-right:0px;">
                <input type="checkbox" class="group-checkable" data-set="#sample_1 .checkboxes" id="checkAll" />
            </th>
        </tr>
    </thead>
    <tbody>
        @foreach (var item in Model.NotificationRecord)
        {
            <tr>
                <td>
                    <input type="checkbox" class="checkboxes chk" value="@item.GCMRegistrationId" name="SelectedAdmissions"/>
                </td>
            </tr>
        }
    </tbody>
</table>
</code>```

jquery for above checkbox

```<code><script type="text/javascript" language="javascript">
    $('#checkAll').click(function (event) {
        if (this.checked) {
            $('.chk').each(function () {
                $('.checker span').addClass('checked');
                this.checked = true;
            });
        }
        else {
            $('.chk').each(function () {
                this.checked = false;
                $('.checker span').removeClass('checked');
            });
        }
    });
</script>
</code>```

When I am running my code in Chrome or in Mozilla, the checkboxes are not appearing but they are there: When I check in inspect element I can see that they are there but they are hidden.

How can I solve this?

答:
hm... if you want to check if checkbox is checked, you should do this:

```<code>$(this).is(':checked')
</code>```

if you want to change checkbox's value, you should do this:

```<code>$(this).prop(':checked', true)
</code>```

Title: checkboxes are not appearing in browser

Body:
                <input type="checkbox" class="group-checkable" data-set="#sample_1 .checkboxes" id="checkAll" />

        @foreach (var item in Model.NotificationRecord)
        {

                    <input type="checkbox" class="checkboxes chk" value="@item.GCMRegistrationId" name="SelectedAdmissions"/>

        }

jquery for above checkbox

When I am running my code in Chrome or in Mozilla, the checkboxes are not appearing but they are there: When I check in inspect element I can see that they are there but they are hidden.

How can I solve this?

Body:
hm... if you want to check if checkbox is checked, you should do this:

$(this).is(':checked')

if you want to change checkbox's value, you should do this:

$(this).prop(':checked', true)


问:
Can I combine values from C# variable and XML
I have a requirement where the email body should contain textbox inputted value. I have predefined contents in email body of xml format but inputted value from the textbox should append to the xml & with this inputted value whole email body should display in the placeholder.

```<code><?xml version="1.0" encoding="UTF-8"?>
<EMAIL>
  <ADDR To="abcd@abcd.com" Sub="Email body"></ADDR>
  <BODY>Data available at <br />**url<br /><br />Thanks</BODY>
</EMAIL>
</code>```

In C#,

```<code> public void EmailDefaultValue(string url)
    {
        XElement xmlMap = XElement.Load(HttpContext.Current.Server.MapPath("~/Config Files/EmailBody.xml"));
        txtToEmail.Value = (from item in xmlMap.Elements("ADDR")
                            select item.Attribute("To").Value).Single();
        txtSubject.Value = (from item in xmlMap.Elements("ADDR")
                            select item.Attribute("Sub").Value).Single();
        txtEmailBody.Text =string.Format((from item in xmlMap.Elements("BODY")
                             select item.Value).Single(),url);
    }
</code>```

in output:
a text **url displayed instead of reading the url variable value and appending.
where am i missing and what?

答:
Try with the below one.

```<code>[XmlRoot]
public class EMAIL
{
    [XmlElement("ADDR")]
    public ADDR ADDR { get; set; }
    [XmlElement("BODY")]
    public string BODY { get; set; }
}

public class ADDR
{
    [XmlAttribute("To")]
    public string To { get; set; }
    [XmlAttribute("Sub")]
    public string Sub { get; set; }
}

static void Main(string[] args)
{
        var fileName = @"your xml file here";
        var xmlResult = System.IO.File.ReadAllText(fileName);

        XmlSerializer serializer = new XmlSerializer(typeof(EMAIL));
        using (TextReader reader = new StringReader(xmlResult))
        {
            EMAIL result = (EMAIL)serializer.Deserialize(reader);
            Console.WriteLine(result.ADDR.Sub);
            Console.WriteLine(result.ADDR.To);
            Console.WriteLine(result.BODY);
        }

        Console.Read();
}
</code>```

And your output

Body:
I have a requirement where the email body should contain textbox inputted value. I have predefined contents in email body of xml format but inputted value from the textbox should append to the xml & with this inputted value whole email body should display in the placeholder.

<?xml version="1.0" encoding="UTF-8"?>
<EMAIL>
  <ADDR To="abcd@abcd.com" Sub="Email body"></ADDR>
  Data available at
**url

Thanks
</EMAIL>

In C#,

 public void EmailDefaultValue(string url)
    {
        XElement xmlMap = XElement.Load(HttpContext.Current.Server.MapPath("~/Config Files/EmailBody.xml"));
        txtToEmail.Value = (from item in xmlMap.Elements("ADDR")
                            select item.Attribute("To").Value).Single();
        txtSubject.Value = (from item in xmlMap.Elements("ADDR")
                            select item.Attribute("Sub").Value).Single();
        txtEmailBody.Text =string.Format((from item in xmlMap.Elements("BODY")
                             select item.Value).Single(),url);
    }

in output:
a text **url displayed instead of reading the url variable value and appending.
where am i missing and what?

Body:
Try with the below one.

[XmlRoot]
public class EMAIL
{
    [XmlElement("ADDR")]
    public ADDR ADDR { get; set; }
    [XmlElement("BODY")]
    public string BODY { get; set; }
}

public class ADDR
{
    [XmlAttribute("To")]
    public string To { get; set; }
    [XmlAttribute("Sub")]
    public string Sub { get; set; }
}

static void Main(string[] args)
{
        var fileName = @"your xml file here";
        var xmlResult = System.IO.File.ReadAllText(fileName);

        XmlSerializer serializer = new XmlSerializer(typeof(EMAIL));
        using (TextReader reader = new StringReader(xmlResult))
        {
            EMAIL result = (EMAIL)serializer.Deserialize(reader);
            Console.WriteLine(result.ADDR.Sub);
            Console.WriteLine(result.ADDR.To);
            Console.WriteLine(result.BODY);
        }

        Console.Read();
}

And your output


问:
Jquery ajax request not working in IE?
I'm experiencing a strange problem in IE with an ajax request. It works fine in FF and Chrome, but for some reason no data is added to the resultsPage, slideInResults is called, and the empty page appears. Inspecting it I can see there is nothing there. What can I do to fix this?</p>

```<code>$.ajax({
        type: "GET",
        url: "library/ajax/search.php",
        data: dataString,
        cache: false,
        dataType: "html",
        success: function(html){
            $('#resultsPage').html(html);
            slideInResults();
            }
        });
</code>```

答: Check all tag and case of variables. They creates problem in IE if not properly close or in different case. </p>

Title: Jquery ajax request not working in IE?

Body:
I'm experiencing a strange problem in IE with an ajax request. It works fine in FF and Chrome, but for some reason no data is added to the resultsPage, slideInResults is called, and the empty page appears. Inspecting it I can see there is nothing there. What can I do to fix this?

$.ajax({
        type: "GET",
        url: "library/ajax/search.php",
        data: dataString,
        cache: false,
        dataType: "html",
        success: function(html){
            $('#resultsPage').html(html);
            slideInResults();
            }
        });


问:
Sql timeout. Camel-context Bean fails for multiple files
I run an automatic route when files are dropped in a folder

```<code><route id ="automatic-route">
        <from uri="file:C:/pathToFolder?noop=true"/>
        <to uri="bean:automaticBean"/>
        <to uri="activemq:STARTFLOW.Q"/>
</route>
</code>```

I move the file in a subfolder called "done" with java methods in my Bean AutomaticBean.java.

Then I start another route to process the file.

```<code><route id ="process-route">
        <from uri="direct:process"/>
        <to uri="bean:processBean"/>
</route>
</code>```

When I move multiple files in the folder they are correctly moved to the subfolder (through my Bean. I use java method to move them). But then the second bean (file processing and SQL queries) has timeoutException because the files are moved and processed at the same time.

For example when I move 5 files 3 of them are correctly processed but then the last ones have a timeoutException. Is it possible to run the second route for each files one by one (schedule them or something like that)? And only start the second route for a file when the previous file is correctly processed?

I tried with noop=false;move=done and I have infinite loop problems and I cannot process the files because they moved. That's why I use noop=true. Furthermore my problem is about the second route (the files are all correctly moved).

Thanks.

答:
Actually adding a delay an set maxMessagePerPoll to 1 did the trick</p>

```<code><route id ="process-route">
    <from uri="file:C:/pathToFolder/noop=true&delay=10000&maxMessagesPerPoll=1"/>
    <to uri="bean:processBean"/>
</route>
</code>```

Body:
I run an automatic route when files are dropped in a folder

<route id ="automatic-route">
        <from uri="file:C:/pathToFolder?noop=true"/>
        <to uri="bean:automaticBean"/>
        <to uri="activemq:STARTFLOW.Q"/>
</route>

I move the file in a subfolder called "done" with java methods in my Bean AutomaticBean.java.

Then I start another route to process the file.

<route id ="process-route">
        <from uri="direct:process"/>
        <to uri="bean:processBean"/>
</route>

When I move multiple files in the folder they are correctly moved to the subfolder (through my Bean. I use java method to move them). But then the second bean (file processing and SQL queries) has timeoutException because the files are moved and processed at the same time.

For example when I move 5 files 3 of them are correctly processed but then the last ones have a timeoutException. Is it possible to run the second route for each files one by one (schedule them or something like that)? And only start the second route for a file when the previous file is correctly processed?

I tried with noop=false;move=done and I have infinite loop problems and I cannot process the files because they moved. That's why I use noop=true. Furthermore my problem is about the second route (the files are all correctly moved).

Thanks.

Body:
Actually adding a delay an set maxMessagePerPoll to 1 did the trick

<route id ="process-route">
    <from uri="file:C:/pathToFolder/noop=true&amp;delay=10000&amp;maxMessagesPerPoll=1"/>
    <to uri="bean:processBean"/>
</route>


问:
PLC Programmable Logic Controller Protocols
I'd like to integrate a PLC with a computer. Set outputs and read inputs. I've looked at Modbus and its simple although if I want to act on the change in a input I would need to poll the input to detect the change. Are there any open and common protocols used by PLC's that would push/update on sensor/input change rather than requiring polling?</p>

答:
The two previous answer's are decent.  As Nelson mentioned, you haven't specified which controller you are using.  You also haven't mentioned what on the computer you'd like to integrate with the PLC.  Beckhoff's TwinCAT PLCs can use MQTT, OPC-UA as well as a host of other protocols.  They also offer libraries to use their ADS protocol.

As part of ADS, you can either set up an ADS server on your machine (it's very easy) and have your PLC's write to the server.  The more typical way is to subscribe to variables/structure in the PLC using this ADS mechanism from within your program's runtime.  An event will be fired when the variable struct changes (you can specify how much it should have changed by, if an analog value).

The method you pick is probably dictated by your architecture.  If you have many PLCs, I would set up an ADS server in your computer, if you have a handful, subscribe from your program.  Of course, you can mix and match these approaches too.

Here is a page of examples: https://infosys.beckhoff.com/english.php?content=../content/1033/tc3_adssamples_net/html/tcsample_net_intro.htm&id=8269274592628480035


问:
How to set the animated view in centre of the parent in android?
I have total 5 image views in linear layout.first round it shows only 3 image views centre of the layout and second round first 3 image views are scale down or translate and visible the 4th image view and centre of the partent. and third round 4 views are scale down and visible the 5th image view in centre of the parent.

How to achive this in android using animations?

答:
Animations can be performed through either XML or android code. Here you get animation using xml.

http://www.androidhive.info/2013/06/android-working-with-xml-animations/

Hope it helps !