问:
Error on sending mail with attachment using Amazon AWS and PHP
I have to send mail using Amazon AWS with PHP, I am able to send simple mail but got following Error, I used many codes get from Google but still I got the same error every time.

Fatal error: Cannot redeclare Aws\constantly() (previously declared
  in /path/vendor/aws/aws-sdk-php/src/functions.php:20) in
  phar:///opt/lampp/htdocs/path/amazon/aws.phar/Aws/functions.php on
  line 22

Code I used:-

```<code>require_once '/mypath/vendor/autoload.php';
include_once("SESUtils.php");

$subject_str = "Some Subject";
$body_str = "<strong>Some email body</strong>";
$attachment_str = file_get_contents("mypdf_file.pdf");

//send the email
 $params =
  array("to" => "to@xyz.com",
  "subject" => "Some subject",
  "message" => "<strong>Some email body</strong>",
  "from" => "from@xyz.com",
  "replyTo" => "reply_to@gmail.com",
  "files" =>
  array(
  "1" => array(
  "name" => "filename1",
  "filepath" => "/path/to/mypdf_file.pdf",
  "mime" => "application/pdf"
  ),
  )
  );

$res = SESUtils::sendMail($params);
</code>```

aws version:- 3.21.6
AND SESUtils.php

```<code>require_once('aws.phar');
use Aws\Ses\SesClient;
class SESUtils {
    const version = "1.0";
    const AWS_KEY = "AWS_KEY";
    const AWS_SEC = "AWS_SEC";
    const AWS_REGION = "us-east-1";
    const MAX_ATTACHMENT_NAME_LEN = 60;

    public static function sendMail($params) {
        $to = self::getParam($params, 'to', true);
        $subject = self::getParam($params, 'subject', true);
        $body = self::getParam($params, 'message', true);
        $from = self::getParam($params, 'from', true);
        $replyTo = self::getParam($params, 'replyTo');
        $files = self::getParam($params, 'files');

        $res = new ResultHelper();

        // get the client ready
        $client = SesClient::factory(array(
                    'key' => self::AWS_KEY,
                    'secret' => self::AWS_SEC,
                    'region' => self::AWS_REGION
        ));

        // build the message
        if (is_array($to)) {
            $to_str = rtrim(implode(',', $to), ',');
        } else {
            $to_str = $to;
        }

        $msg = "To: $to_str\n";
        $msg .= "From: $from\n";

        if ($replyTo) {
            $msg .= "Reply-To: $replyTo\n";
        }

        // in case you have funny characters in the subject
        $subject = mb_encode_mimeheader($subject, 'UTF-8');
        $msg .= "Subject: $subject\n";
        $msg .= "MIME-Version: 1.0\n";
        $msg .= "Content-Type: multipart/mixed;\n";
        $boundary = uniqid("_Part_".time(), true); //random unique string
        $boundary2 = uniqid("_Part2_".time(), true); //random unique string
        $msg .= " boundary=\"$boundary\"\n";
        $msg .= "\n";

        $msg .= "--$boundary\n";
        $msg .= "Content-Type: multipart/alternative;\n";
        $msg .= " boundary=\"$boundary2\"\n";
        $msg .= "\n";
        $msg .= "--$boundary2\n";

        $msg .= "Content-Type: text/plain; charset=utf-8\n";
        $msg .= "Content-Transfer-Encoding: 7bit\n";
        $msg .= "\n";
        $msg .= strip_tags($body); //remove any HTML tags
        $msg .= "\n";

        // now, the html text
        $msg .= "--$boundary2\n";
        $msg .= "Content-Type: text/html; charset=utf-8\n";
        $msg .= "Content-Transfer-Encoding: 7bit\n";
        $msg .= "\n";
        $msg .= $body;
        $msg .= "\n";
        $msg .= "--$boundary2--\n";

        // add attachments
        if (is_array($files)) {
            $count = count($files);
            foreach ($files as $file) {
                $msg .= "\n";
                $msg .= "--$boundary\n";
                $msg .= "Content-Transfer-Encoding: base64\n";
                $clean_filename = self::clean_filename($file["name"], self::MAX_ATTACHMENT_NAME_LEN);
                $msg .= "Content-Type: {$file['mime']}; name=$clean_filename;\n";
                $msg .= "Content-Disposition: attachment; filename=$clean_filename;\n";
                $msg .= "\n";
                $msg .= base64_encode(file_get_contents($file['filepath']));
                $msg .= "\n--$boundary";
            }
            // close email
            $msg .= "--\n";
        }

        // now send the email out
        try {
            $ses_result = $client->sendRawEmail(
                    array(
                'RawMessage' => array(
                    'Data' => base64_encode($msg)
                )
                    ), array(
                'Source' => $from,
                'Destinations' => $to_str
                    )
            );
            if ($ses_result) {
                $res->message_id = $ses_result->get('MessageId');
            } else {
                $res->success = false;
                $res->result_text = "Amazon SES did not return a MessageId";
            }
        } catch (Exception $e) {
            $res->success = false;
            $res->result_text = $e->getMessage().
                    " - To: $to_str, Sender: $from, Subject: $subject";
        }
        return $res;
    }

    private static function getParam($params, $param, $required = false) {
        $value = isset($params[$param]) ? $params[$param] : null;
        if ($required && empty($value)) {
            throw new Exception('"'.$param.'" parameter is required.');
        } else {
            return $value;
        }
    }

    /** Clean filename function - to be mail friendly **/
    public static function clean_filename($str, $limit = 0, $replace=array(), $delimiter='-') {
        if( !empty($replace) ) {
            $str = str_replace((array)$replace, ' ', $str);
        }

        $clean = iconv('UTF-8', 'ASCII//TRANSLIT', $str);
        $clean = preg_replace("/[^a-zA-Z0-9\.\/_| -]/", '', $clean);
        $clean = preg_replace("/[\/| -]+/", '-', $clean);

        if ($limit > 0) {
            //don't truncate file extension
            $arr = explode(".", $clean);
            $size = count($arr);
            $base = "";
            $ext = "";
            if ($size > 0) {
                for ($i = 0; $i < $size; $i++) {
                    if ($i < $size - 1) { //if it's not the last item, add to $bn
                        $base .= $arr[$i];
                        //if next one isn't last, add a dot
                        if ($i < $size - 2)
                            $base .= ".";
                    } else {
                        if ($i > 0)
                            $ext = ".";
                        $ext .= $arr[$i];
                    }
                }
            }
            $bn_size = mb_strlen($base);
            $ex_size = mb_strlen($ext);
            $bn_new = mb_substr($base, 0, $limit - $ex_size);
            // doing again in case extension is long
            $clean = mb_substr($bn_new.$ext, 0, $limit);
        }
        return $clean;
    }

}
class ResultHelper {
    public $success = true;
    public $result_text = "";
    public $message_id = "";
}
</code>```

答:
This is just namespacing. Look at the examples for reference - you need to either use the namespaced class or reference it absolutely, for example:</p>

```<code>use PHPMailer\PHPMailer\PHPMailer;
use PHPMailer\PHPMailer\Exception;

//Load composer's autoloader
require 'vendor/autoload.php';
</code>```

Body:
I have to send mail using Amazon AWS with PHP, I am able to send simple mail but got following Error, I used many codes get from Google but still I got the same error every time.

Fatal error: Cannot redeclare Aws\constantly() (previously declared
  in /path/vendor/aws/aws-sdk-php/src/functions.php:20) in
  phar:///opt/lampp/htdocs/path/amazon/aws.phar/Aws/functions.php on
  line 22

Code I used:-

require_once '/mypath/vendor/autoload.php';
include_once("SESUtils.php");

$subject_str = "Some Subject";
$body_str = "Some email body";
$attachment_str = file_get_contents("mypdf_file.pdf");

//send the email
 $params =
  array("to" => "to@xyz.com",
  "subject" => "Some subject",
  "message" => "Some email body",
  "from" => "from@xyz.com",
  "replyTo" => "reply_to@gmail.com",
  "files" =>
  array(
  "1" => array(
  "name" => "filename1",
  "filepath" => "/path/to/mypdf_file.pdf",
  "mime" => "application/pdf"
  ),
  )
  );

$res = SESUtils::sendMail($params);

aws version:- 3.21.6
AND SESUtils.php

require_once('aws.phar');
use Aws\Ses\SesClient;
class SESUtils {
    const version = "1.0";
    const AWS_KEY = "AWS_KEY";
    const AWS_SEC = "AWS_SEC";
    const AWS_REGION = "us-east-1";
    const MAX_ATTACHMENT_NAME_LEN = 60;

    public static function sendMail($params) {
        $to = self::getParam($params, 'to', true);
        $subject = self::getParam($params, 'subject', true);
        $body = self::getParam($params, 'message', true);
        $from = self::getParam($params, 'from', true);
        $replyTo = self::getParam($params, 'replyTo');
        $files = self::getParam($params, 'files');

        $res = new ResultHelper();

        // get the client ready
        $client = SesClient::factory(array(
                    'key' => self::AWS_KEY,
                    'secret' => self::AWS_SEC,
                    'region' => self::AWS_REGION
        ));

        // build the message
        if (is_array($to)) {
            $to_str = rtrim(implode(',', $to), ',');
        } else {
            $to_str = $to;
        }

        $msg = "To: $to_str\n";
        $msg .= "From: $from\n";

        if ($replyTo) {
            $msg .= "Reply-To: $replyTo\n";
        }

        // in case you have funny characters in the subject
        $subject = mb_encode_mimeheader($subject, 'UTF-8');
        $msg .= "Subject: $subject\n";
        $msg .= "MIME-Version: 1.0\n";
        $msg .= "Content-Type: multipart/mixed;\n";
        $boundary = uniqid("_Part_".time(), true); //random unique string
        $boundary2 = uniqid("_Part2_".time(), true); //random unique string
        $msg .= " boundary=\"$boundary\"\n";
        $msg .= "\n";

        $msg .= "--$boundary\n";
        $msg .= "Content-Type: multipart/alternative;\n";
        $msg .= " boundary=\"$boundary2\"\n";
        $msg .= "\n";
        $msg .= "--$boundary2\n";

        $msg .= "Content-Type: text/plain; charset=utf-8\n";
        $msg .= "Content-Transfer-Encoding: 7bit\n";
        $msg .= "\n";
        $msg .= strip_tags($body); //remove any HTML tags
        $msg .= "\n";

        // now, the html text
        $msg .= "--$boundary2\n";
        $msg .= "Content-Type: text/html; charset=utf-8\n";
        $msg .= "Content-Transfer-Encoding: 7bit\n";
        $msg .= "\n";
        $msg .= $body;
        $msg .= "\n";
        $msg .= "--$boundary2--\n";

        // add attachments
        if (is_array($files)) {
            $count = count($files);
            foreach ($files as $file) {
                $msg .= "\n";
                $msg .= "--$boundary\n";
                $msg .= "Content-Transfer-Encoding: base64\n";
                $clean_filename = self::clean_filename($file["name"], self::MAX_ATTACHMENT_NAME_LEN);
                $msg .= "Content-Type: {$file['mime']}; name=$clean_filename;\n";
                $msg .= "Content-Disposition: attachment; filename=$clean_filename;\n";
                $msg .= "\n";
                $msg .= base64_encode(file_get_contents($file['filepath']));
                $msg .= "\n--$boundary";
            }
            // close email
            $msg .= "--\n";
        }

        // now send the email out
        try {
            $ses_result = $client->sendRawEmail(
                    array(
                'RawMessage' => array(
                    'Data' => base64_encode($msg)
                )
                    ), array(
                'Source' => $from,
                'Destinations' => $to_str
                    )
            );
            if ($ses_result) {
                $res->message_id = $ses_result->get('MessageId');
            } else {
                $res->success = false;
                $res->result_text = "Amazon SES did not return a MessageId";
            }
        } catch (Exception $e) {
            $res->success = false;
            $res->result_text = $e->getMessage().
                    " - To: $to_str, Sender: $from, Subject: $subject";
        }
        return $res;
    }

    private static function getParam($params, $param, $required = false) {
        $value = isset($params[$param]) ? $params[$param] : null;
        if ($required && empty($value)) {
            throw new Exception('"'.$param.'" parameter is required.');
        } else {
            return $value;
        }
    }

    /** Clean filename function - to be mail friendly **/
    public static function clean_filename($str, $limit = 0, $replace=array(), $delimiter='-') {
        if( !empty($replace) ) {
            $str = str_replace((array)$replace, ' ', $str);
        }

        $clean = iconv('UTF-8', 'ASCII//TRANSLIT', $str);
        $clean = preg_replace("/[^a-zA-Z0-9\.\/_| -]/", '', $clean);
        $clean = preg_replace("/[\/| -]+/", '-', $clean);

        if ($limit > 0) {
            //don't truncate file extension
            $arr = explode(".", $clean);
            $size = count($arr);
            $base = "";
            $ext = "";
            if ($size > 0) {
                for ($i = 0; $i < $size; $i++) {
                    if ($i < $size - 1) { //if it's not the last item, add to $bn
                        $base .= $arr[$i];
                        //if next one isn't last, add a dot
                        if ($i < $size - 2)
                            $base .= ".";
                    } else {
                        if ($i > 0)
                            $ext = ".";
                        $ext .= $arr[$i];
                    }
                }
            }
            $bn_size = mb_strlen($base);
            $ex_size = mb_strlen($ext);
            $bn_new = mb_substr($base, 0, $limit - $ex_size);
            // doing again in case extension is long
            $clean = mb_substr($bn_new.$ext, 0, $limit);
        }
        return $clean;
    }

}
class ResultHelper {
    public $success = true;
    public $result_text = "";
    public $message_id = "";
}

Body:
This is just namespacing. Look at the examples for reference - you need to either use the namespaced class or reference it absolutely, for example:

use PHPMailer\PHPMailer\PHPMailer;
use PHPMailer\PHPMailer\Exception;

//Load composer's autoloader
require 'vendor/autoload.php';


来源: stackexchange

问:
React form using Axios post
I've been searching the internet for days and cannot seem to find anything related to submitting a form request through React and using Axios post to input the information to our REST API. Every time we submit our register form every value comes up undefined. Is this the best way to have React communicate with our REST API? Also we have tested the API using Postman and know it's working.</p>

```<code>var React = require('react');

var Access = React.createClass({
    getInitialState: function() {
        return {
            firstName: '',
            lastName: '',
            email: '',
            password1: ''
        }
    },

    handleSubmit: function(e) {
        var _this = this;
        this.serverRequest = axios
        console.log(_this.ref.firstName)
        .post("/api/Users", {
            userFirstName: _this.ref.firstName,
            userLastName: _this.ref.lastName,
            userEmail: _this.ref.email,
            userPassword: _this.ref.password1
        })
        .then(function(response) {
            console.log(response);
        }) .catch(function (error) {
            console.log(error);
        });
    },

    render: function() {
        return(
            <div>
                <section className="access">
                    <div className="row center-xs container">
                        <div className="col-xs-12 col-sm-4 sign-in">
                            <h1>Sign-In</h1>
                            <form action="/" method="get">
                                <label htmlFor="email">Email</label>
                                <input type="email" name="email" placeholder="Email"/>
                                <label htmlFor="password">Password</label>
                                <input type="password" name="password" placeholder="Password"/>
                                <input className="button pink" type="submit" value="Sign-In"/>
                                <br/>
                                <input type="checkbox" name="RememberMe"/>
                                <label htmlFor="RememberMe">Remember me</label>
                                <span> | <a href="/">Forgot password?</a></span>
                            </form>
                        </div>
                        <div className="col-xs-12 col-sm-4 register">
                            <h1>Register</h1>
                            <form onSubmit={this.onSubmit}>
                                <label htmlFor="firstName">First Name</label>
                                <input type="text" name="firstName" placeholder="First Name" ref="firstName"/>
                                <label htmlFor="lastName">Last Name</label>
                                <input type="text" name="lastName" placeholder="Last Name" ref="lastName"/>
                                <label htmlFor="email">Email</label>
                                <input type="email" name="email" placeholder="Email" ref="email"/>
                                <label htmlFor="password1">Password</label>
                                <input type="password" name="password1" placeholder="Password" ref="password1"/>
                                <label htmlFor="password2">Re-enter Password</label>
                                <input type="password" name="password2" placeholder="Password"/>
                                <input className="button gold" type="submit" value="Register"/>
                            </form>
                        </div>
                    </div>
                </section>
            </div>
        );
    }
});

module.exports = Access;
</code>```

答:
Not sure if I'm missing something, but in your form you say
   onSubmit={this.onSubmit} while your method is called handleSubmit.

ContentLicense: CC BY-SA 3.0

Title: React form using Axios post

Body:
I've been searching the internet for days and cannot seem to find anything related to submitting a form request through React and using Axios post to input the information to our REST API. Every time we submit our register form every value comes up undefined. Is this the best way to have React communicate with our REST API? Also we have tested the API using Postman and know it's working.

var React = require('react');

var Access = React.createClass({
    getInitialState: function() {
        return {
            firstName: '',
            lastName: '',
            email: '',
            password1: ''
        }
    },

    handleSubmit: function(e) {
        var _this = this;
        this.serverRequest = axios
        console.log(_this.ref.firstName)
        .post("/api/Users", {
            userFirstName: _this.ref.firstName,
            userLastName: _this.ref.lastName,
            userEmail: _this.ref.email,
            userPassword: _this.ref.password1
        })
        .then(function(response) {
            console.log(response);
        }) .catch(function (error) {
            console.log(error);
        });
    },

    render: function() {
        return(

Sign-In

                            <form action="/" method="get">
                                Email
                                <input type="email" name="email" placeholder="Email"/>
                                Password
                                <input type="password" name="password" placeholder="Password"/>
                                <input className="button pink" type="submit" value="Sign-In"/>

                                <input type="checkbox" name="RememberMe"/>
                                Remember me
                                 | Forgot password?
                            </form>

Register

                            <form onSubmit={this.onSubmit}>
                                First Name
                                <input type="text" name="firstName" placeholder="First Name" ref="firstName"/>
                                Last Name
                                <input type="text" name="lastName" placeholder="Last Name" ref="lastName"/>
                                Email
                                <input type="email" name="email" placeholder="Email" ref="email"/>
                                Password
                                <input type="password" name="password1" placeholder="Password" ref="password1"/>
                                Re-enter Password
                                <input type="password" name="password2" placeholder="Password"/>
                                <input className="button gold" type="submit" value="Register"/>
                            </form>

        );
    }
});

module.exports = Access;


问:
Convert the .txt file content into multidimensional array using it's current format
I have a text file with this format and I want to convert this into an array following the format.

Text File Content:

```<code>Header = "This is header"
Object class = "First"

min_size = 0
max_size = 727.555
content= true
size = 1
item []:
    item [1]:
        class = "Convert"
        name = "CONTENT"
        min_size = 0
        max_size = 727.555
        intervals: size = 474
        intervals [1]:
            min_size = 0
            max_size = 13.139997023062838
            type = ""
        intervals [2]:
            min_size = 13.139997023062838
            max_size = 14.763036269953904
            type = "this is a type"
        intervals [3]:
            min_size = 14.763036269953904
            max_size = 17.01
            type = ""
        intervals [4]:
            min_size = 17.01
            max_size = 18.193
            type = ""
</code>```

I want to convert this to an array something like this if possible:

```<code>Array
(
    [1] =>
        Array(
                ['min_size'] = 0,
                ['max_size'] = 13.139997023062838,
                ['type'] = ""
            )
    [2] =>
        Array(
                ['min_size'] = 13.139997023062838,
                ['max_size'] = 14.763036269953904,
                ['type'] = "this is a type"
            )
</code>```

I already tried something like this:

```<code>$file = "array.txt";// Your Temp Uploaded file
$cols = array();
ini_set('auto_detect_line_endings', true);

$fh = fopen($file, 'r');
$i = 0;

while (($line = fgetcsv($fh, 1000, "\t")) !== false) {
  $cols[] = $line;

  }

echo "```";
print_r($cols);
echo "```";
</code>```

But this only turned everything into a single array.

Is this possible?

I already looked into this: one two three

答:
Complex solution with preg_match_all, array_map and array_combine functions:

```<code>$data = file_get_contents('array.txt');
$pat = '/intervals \[\d+\]:\s+\Kmin_size = (?P<min_size>\d+(\.\d+)?) \
        \s+max_size = (?P<max_size>\d+(\.\d+)?)\s+type = "(?P<type>[^"]*)"/m';

preg_match_all($pat, $data, $m);
$result = array_map(function($a){
    return array_combine(['min_size', 'max_size', 'type'], $a);
}, array_map(null, $m['min_size'], $m['max_size'], $m['type']));

print_r($result);
</code>```

The output:

```<code>Array
(
    [0] => Array
        (
            [min_size] => 0
            [max_size] => 13.139997023062838
            [type] =>
        )

    [1] => Array
        (
            [min_size] => 13.139997023062838
            [max_size] => 14.763036269953904
            [type] => this is a type
        )

    [2] => Array
        (
            [min_size] => 14.763036269953904
            [max_size] => 17.01
            [type] =>
        )

    [3] => Array
        (
            [min_size] => 17.01
            [max_size] => 18.193
            [type] =>
        )
)
</code>```

Body:
I have a text file with this format and I want to convert this into an array following the format.

Text File Content:

Header = "This is header"
Object class = "First"

min_size = 0
max_size = 727.555
content= true
size = 1
item []:
    item [1]:
        class = "Convert"
        name = "CONTENT"
        min_size = 0
        max_size = 727.555
        intervals: size = 474
        intervals [1]:
            min_size = 0
            max_size = 13.139997023062838
            type = ""
        intervals [2]:
            min_size = 13.139997023062838
            max_size = 14.763036269953904
            type = "this is a type"
        intervals [3]:
            min_size = 14.763036269953904
            max_size = 17.01
            type = ""
        intervals [4]:
            min_size = 17.01
            max_size = 18.193
            type = ""

I want to convert this to an array something like this if possible:

Array
(
    [1] =>
        Array(
                ['min_size'] = 0,
                ['max_size'] = 13.139997023062838,
                ['type'] = ""
            )
    [2] =>
        Array(
                ['min_size'] = 13.139997023062838,
                ['max_size'] = 14.763036269953904,
                ['type'] = "this is a type"
            )

I already tried something like this:

$file = "array.txt";// Your Temp Uploaded file
$cols = array();
ini_set('auto_detect_line_endings', true);

$fh = fopen($file, 'r');
$i = 0;

while (($line = fgetcsv($fh, 1000, "\t")) !== false) {
  $cols[] = $line;

  }

echo "
";
print_r($cols);
echo "
";

But this only turned everything into a single array.

Is this possible?

I already looked into this: one two three

Body:
Complex solution with preg_match_all, array_map and array_combine functions:

$data = file_get_contents('array.txt');
$pat = '/intervals \[\d+\]:\s+\Kmin_size = (?P<min_size>\d+(\.\d+)?) \
        \s+max_size = (?P<max_size>\d+(\.\d+)?)\s+type = "(?P<type>[^"]*)"/m';

preg_match_all($pat, $data, $m);
$result = array_map(function($a){
    return array_combine(['min_size', 'max_size', 'type'], $a);
}, array_map(null, $m['min_size'], $m['max_size'], $m['type']));

print_r($result);

The output:

Array
(
    [0] => Array
        (
            [min_size] => 0
            [max_size] => 13.139997023062838
            [type] =>
        )

    [1] => Array
        (
            [min_size] => 13.139997023062838
            [max_size] => 14.763036269953904
            [type] => this is a type
        )

    [2] => Array
        (
            [min_size] => 14.763036269953904
            [max_size] => 17.01
            [type] =>
        )

    [3] => Array
        (
            [min_size] => 17.01
            [max_size] => 18.193
            [type] =>
        )
)


问:
How to remove new line characters until each line has a specific number of instances of a specific character?
I have a real mess of a pipe-delimited file, which I need to load to a database. The file has 35 fields, and thus 34 pipes. One of the fields is comprised of HTML code which, for some records, includes multiple line breaks. Unfortunately there's no patter as to where the line breaks fall.

The solution I've come up with is to count the number of pipes in each line and until that number reaches 34, remove the new line character from that line. I'm not incredibly well-versed in Perl, but I think I'm close to achieving what I'm looking to do. Any suggestions?

```<code>#!/usr/local/bin/perl

use strict;

open (FILE, 'test.txt');

while (<FILE>) {
    chomp;
    my $line = $_;
    #remove null characters that are included in file
    $line =~ tr/\x00//;
    #count number of pipes
    my $count = ($line =~ tr/|//);
    #each line should have 34 pipes
    while ($count < 34) {
        #remove new lines until line has 34 pipes
        $line =~ tr/\r\n//;
        $count = ($line =~ tr/|//);
        print "$line\n";
    }
}
</code>```

答:
This should work I guess.</p>

```<code>#!/usr/bin/perl

use strict;

open (FILE, 'test.txt');

my $num_pipes = 0, my $line_num = 0;
my $tmp = "";
while (<FILE>)
{
    $line_num++;
    chomp;
    my $line = $_;
    $line =~ tr/\x00//; #remove null characters that are included in file
    $num_pipes += ($line =~ tr/|//); #count number of pipes
    if ($num_pipes == 34 && length($tmp))
    {
            $tmp .= $line;
            print "$tmp\n";
            # Reset values.
            $tmp = "";
            $num_pipes = 0;
    }
    elsif ($num_pipes == 34 && length($tmp) == 0)
    {
            print "$line\n";
            $num_pipes = 0;
    }
    elsif ($num_pipes < 34)
    {
            $tmp .= $line;
    }
    elsif ($num_pipes > 34)
    {
            print STDERR "Error before line $line_num. Too many pipes ($num_pipes)\n";
            $num_pipes = 0;
            $tmp = "";
    }
}
</code>```

ContentLicense: CC BY-SA 2.5

Body:
I have a real mess of a pipe-delimited file, which I need to load to a database. The file has 35 fields, and thus 34 pipes. One of the fields is comprised of HTML code which, for some records, includes multiple line breaks. Unfortunately there's no patter as to where the line breaks fall.

The solution I've come up with is to count the number of pipes in each line and until that number reaches 34, remove the new line character from that line. I'm not incredibly well-versed in Perl, but I think I'm close to achieving what I'm looking to do. Any suggestions?

#!/usr/local/bin/perl

use strict;

open (FILE, 'test.txt');

while (<FILE>) {
    chomp;
    my $line = $_;
    #remove null characters that are included in file
    $line =~ tr/\x00//;
    #count number of pipes
    my $count = ($line =~ tr/|//);
    #each line should have 34 pipes
    while ($count < 34) {
        #remove new lines until line has 34 pipes
        $line =~ tr/\r\n//;
        $count = ($line =~ tr/|//);
        print "$line\n";
    }
}

Body:
This should work I guess.

#!/usr/bin/perl

use strict;

open (FILE, 'test.txt');

my $num_pipes = 0, my $line_num = 0;
my $tmp = "";
while (<FILE>)
{
    $line_num++;
    chomp;
    my $line = $_;
    $line =~ tr/\x00//; #remove null characters that are included in file
    $num_pipes += ($line =~ tr/|//); #count number of pipes
    if ($num_pipes == 34 && length($tmp))
    {
            $tmp .= $line;
            print "$tmp\n";
            # Reset values.
            $tmp = "";
            $num_pipes = 0;
    }
    elsif ($num_pipes == 34 && length($tmp) == 0)
    {
            print "$line\n";
            $num_pipes = 0;
    }
    elsif ($num_pipes < 34)
    {
            $tmp .= $line;
    }
    elsif ($num_pipes > 34)
    {
            print STDERR "Error before line $line_num. Too many pipes ($num_pipes)\n";
            $num_pipes = 0;
            $tmp = "";
    }
}


问:
Read multi-line delimited sub-strings to bash array
I'd like to create array containing

```<code>Speed: 10500 Mbps
Size: 122400 MB
Load: 4544 Kg
Distance: 232680 miles
Acceleration: 11200 meters/s2
Deviation: 1100 Wierdos
</code>```

From the following code:

```<code>read -r -d '' TEST_STRING << EOM
Speed: 10500 Mbps; Size: 122400 MB
Load: 4544 Kg; Distance: 232680 miles
Acceleration: 11200 meters/s2; Deviation: 1100 Wierdos
EOM

STRINGS_ARRAY=()
RE_INTRALINEDELIMITER=";"

while IFS=$'\n' read -a LINE; do

    if [[ $LINE =~ $RE_INTRALINEDELIMITER ]]; then
        echo "(intraline): $LINE"
        while IFS=$';' read -a SUBSTR; do
            echo "(substr): $SUBSTR"
        done <<< "$LINE"

    fi

done <<< "$TEST_STRING"
</code>```

(echoes are added for debugging and as an empty operator). Then process lines with some functions and finally to assembly it back to the original string.

But for SUBSTR I get only first sub-string from every string (before semicolon). What I'm doing wrong?

答:
Use read twice; once get a line, and again to split that line.

```<code>test_string='Speed: 10500 Mbps; Size: 122400 MB
Load: 4544 Kg; Distance: 232680 miles
Acceleration: 11200 meters/s2; Deviation: 1100 Wierdos'

while IFS= read -r line; do
    IFS=";" read -r fields <<< "$line"
    strings_array+=("${fields[@]}")
done <<< "$test_string"
</code>```

Body:
I'd like to create array containing

Speed: 10500 Mbps
Size: 122400 MB
Load: 4544 Kg
Distance: 232680 miles
Acceleration: 11200 meters/s2
Deviation: 1100 Wierdos

From the following code:

read -r -d '' TEST_STRING << EOM
Speed: 10500 Mbps; Size: 122400 MB
Load: 4544 Kg; Distance: 232680 miles
Acceleration: 11200 meters/s2; Deviation: 1100 Wierdos
EOM

STRINGS_ARRAY=()
RE_INTRALINEDELIMITER=";"

while IFS=$'\n' read -a LINE; do

    if [[ $LINE =~ $RE_INTRALINEDELIMITER ]]; then
        echo "(intraline): $LINE"
        while IFS=$';' read -a SUBSTR; do
            echo "(substr): $SUBSTR"
        done <<< "$LINE"

    fi

done <<< "$TEST_STRING"

(echoes are added for debugging and as an empty operator). Then process lines with some functions and finally to assembly it back to the original string.

But for SUBSTR I get only first sub-string from every string (before semicolon). What I'm doing wrong?

Body:
Use read twice; once get a line, and again to split that line.

test_string='Speed: 10500 Mbps; Size: 122400 MB
Load: 4544 Kg; Distance: 232680 miles
Acceleration: 11200 meters/s2; Deviation: 1100 Wierdos'

while IFS= read -r line; do
    IFS=";" read -r fields <<< "$line"
    strings_array+=("${fields[@]}")
done <<< "$test_string"


问:
Wordpress htaccess to redict subdomain on sub folder

My public html folder has 2 subfolders: ./en and ./fr.

My main domain is .com domain, it currently lands in the root of public_html folder (I am using bluehost and the cPanel is opened with the mydomain.com as primary domain in this cPanel).

I have opened a subdomain fr.mydomain.com which I want my visitors to be redirect to the ./fr subfolder.

I am using wordpress in ./en folder and another wordpress in ./fr folder.

I want mydomain.com to fall into the ./en folder and fr.mydomain.com to fall into the ./fr folder.

How should I setup .htaccess of the public root folder ?

How should I setup .htaccess of the /en folder ?

How should I setup .htaccess of the /fr folder ?

答:
You need to rewrite based on the HTTP Host.

Try this:

```<code>RewriteEngine On
RewriteCond %{HTTP_HOST} en.example.com
RewriteRule ^(.*)$ http://example.com/en/$1 [L,NC,QSA]
RewriteCond %{HTTP_HOST} fr.example.com
RewriteRule ^(.*)$ http://example.com/fr/$1 [L,NC,QSA]
</code>```

Body:
You need to rewrite based on the HTTP Host.

Try this:

RewriteEngine On
RewriteCond %{HTTP_HOST} en.example.com
RewriteRule ^(.*)$ http://example.com/en/$1 [L,NC,QSA]
RewriteCond %{HTTP_HOST} fr.example.com
RewriteRule ^(.*)$ http://example.com/fr/$1 [L,NC,QSA]


问:
simple String example
i have the following piece of code but i could not detect why there is no output
when i debug it , the control flow is never goes inside for loop but i cannot figure out why </p>

<p>could anyone please help me ?
 here is my code </p>

```<code>public class DealWithStrings {
    ArrayList<String> container = new ArrayList<>();

    public void printDuplicate() {
        String string = "aaabed";
        String[] res = string.split("");

        for (int i = 1; i < string.length(); i++) {
            if (res[i] == res[i - 1]) {
                container.add(res[i]);
            }
        }

        for (String s : container) {
            System.out.println(s);
        }
    }

    public static void main(String[] args) {
        DealWithStrings d = new DealWithStrings();
        d.printDuplicate();
    }
}
</code>```

答:
Replace your code '==' operator with '.equals()' method, because ,
'==' equal operator compares the reference of the two characters in memory, whereas you need to check 'contents' at that reference.

And .equals method  is overridden to check the content for Strings.

```<code>for (int i = 1; i < string.length(); i++) {
        if (res[i].equals(res[i - 1])) {
            container.add(res[i]);
        }
    }
</code>```

Title: simple String example

Body:
i have the following piece of code but i could not detect why there is no output
when i debug it , the control flow is never goes inside for loop but i cannot figure out why

could anyone please help me ?
 here is my code

public class DealWithStrings {
    ArrayList<String> container = new ArrayList<>();

    public void printDuplicate() {
        String string = "aaabed";
        String[] res = string.split("");

        for (int i = 1; i < string.length(); i++) {
            if (res[i] == res[i - 1]) {
                container.add(res[i]);
            }
        }

        for (String s : container) {
            System.out.println(s);
        }
    }

    public static void main(String[] args) {
        DealWithStrings d = new DealWithStrings();
        d.printDuplicate();
    }
}

Body:
Replace your code '==' operator with '.equals()' method, because ,
'==' equal operator compares the reference of the two characters in memory, whereas you need to check 'contents' at that reference.

And .equals method  is overridden to check the content for Strings.

for (int i = 1; i < string.length(); i++) {
        if (res[i].equals(res[i - 1])) {
            container.add(res[i]);
        }
    }


问:
How to call mounted or created within a Vue plugin?
I am trying to create some plugins according to this article:

https://alligator.io/vuejs/creating-custom-plugins/

I have a plugin that needs to run something when the root Vue instance mounts or is created. So far I can only see a way to inject something into all components which is not what I would want.

I simply need to do something when the main Vue instance mounts. How can I do this with a plugin?

The install method from the plugin does not seem to do the trick because this seems to happen before the actual created method.

答:
It's possible to have multiple root Vue components. A "root component" is just a component created with the new syntax and no parent component, so you can detect this as follows:

Vue.mixin({
  created() {
    if (!this.$parent) {
      // This is either the root component or a component
      // created with `new` and no parent
    }
  }
})
```


问:
Pygame: objects moving one by one
I'm creating a tower defense game using pygame. And the functions to spawn and move enemy's work fine. However, the next enemy only moves when the first enemy is done moving. I assume this has something to do with the for or the while loop. Who can correct my code so that the objects move simultaneously.

This function is called in the main loop of the game:

```<code># creates and places all of the enemys
def begin_wave(self):
    # mark next waves as started
    self.wave += 1
    print("Wave number: ", self.wave)

    ### Draw Enemy ###
    for enemy in self.enemies:
        while enemy.waypoints_reached < len(config.WAYPOINTS):

            # Move enemy
            enemy.move()

            # Paint game + new enemy location
            self.paint(self.screen)

            # Update Screen
            pygame.display.update()

    # if done -> set state to BA_CLEAR
    print("Wave Completed!")
    self.waves_comp += 1
    self.state = config.BA_CLEAR
</code>```

The first function which is needed is the move enemy function which is this one:

```<code>def move(self):

    speed = config.DEFAULT_SPEED

    # Update enemy's location
    if self.get_position()[0] < self.trackNextWaypoint()[1]:
        if self.trackNextWaypoint()[1] - self.get_position()[0] >= speed:
            self.set_position((self.get_position()[0] + speed, self.get_position()[1]))
        else:
            self.set_position((self.get_position()[0] + (self.trackNextWaypoint()[1] - self.get_position()[0]),
                       self.get_position()[1]))

    if self.get_position()[0] > self.trackNextWaypoint()[1]:
        if self.get_position()[0] - self.trackNextWaypoint()[1] >= speed:
            self.set_position((self.get_position()[0] - speed, self.get_position()[1]))
        else:
            self.set_position((self.get_position()[0] - (self.get_position()[0] - self.trackNextWaypoint()[1]),
                       self.get_position()[1]))

    if self.get_position()[1] < self.trackNextWaypoint()[2]:
        if self.trackNextWaypoint()[2] - self.get_position()[1] >= speed:
            self.set_position((self.get_position()[0], self.get_position()[1] + speed))
        else:
            self.set_position((self.get_position()[0],
                       self.get_position()[1] + (self.trackNextWaypoint()[2] - self.get_position()[1])))

    if self.get_position()[1] > self.trackNextWaypoint()[2]:
        if self.get_position()[1] - self.trackNextWaypoint()[2] >= speed:
            self.set_position((self.get_position()[0], self.get_position()[1] - speed))
        else:
            self.set_position((self.get_position()[0], self.get_position()[1] - (self.get_position()[1] - self.trackNextWaypoint()[2])))

    # If enemy position is on waypoint
    if self.get_position()[0] == self.trackNextWaypoint()[1] and self.get_position()[1] == self.trackNextWaypoint()[2]:
        self.setWaypointsReached(1)
</code>```

Finally, these functions might also be needed for you understanding:

```<code>def trackNextWaypoint(self):
    for waypoint in config.WAYPOINTS:
        if waypoint[0] == self.waypoints_reached+1:
            return waypoint
            break

def setWaypointsReached(self, number):
    self.waypoints_reached += number

def get_position(self):
    return self.position

def set_position(self, position):
    self.position = position
</code>```

Update

And I've also got an screenshot for your visualisation

答:
Problem is because you use while inside for.

Object inside for should make only small step and external while should execute for many times.

You need some method to check if all objects are moved to destination and repeat again for loop.

I use how_many_moved to check if all enemies are in destination.

It could be something like this

```<code># value bigger than 0 to start `while` loop
how_many_moved = 1

while how_many_moved > 0:

    how_many_moved = 0

    ### every enemy makes only small step ###
    for enemy in self.enemies:
        if enemy.waypoints_reached < len(config.WAYPOINTS):
            # count how many was moved
            how_many_moved += 1

            # Move enemy
            enemy.move()

            # Paint game + new enemy location
            self.paint(self.screen)

    # Update Screen afer every enemy made small step
    pygame.display.update()
</code>```

Title: Pygame: objects moving one by one

Body:
I'm creating a tower defense game using pygame. And the functions to spawn and move enemy's work fine. However, the next enemy only moves when the first enemy is done moving. I assume this has something to do with the for or the while loop. Who can correct my code so that the objects move simultaneously.

This function is called in the main loop of the game:

# creates and places all of the enemys
def begin_wave(self):
    # mark next waves as started
    self.wave += 1
    print("Wave number: ", self.wave)

    ### Draw Enemy ###
    for enemy in self.enemies:
        while enemy.waypoints_reached < len(config.WAYPOINTS):

            # Move enemy
            enemy.move()

            # Paint game + new enemy location
            self.paint(self.screen)

            # Update Screen
            pygame.display.update()

    # if done -> set state to BA_CLEAR
    print("Wave Completed!")
    self.waves_comp += 1
    self.state = config.BA_CLEAR

The first function which is needed is the move enemy function which is this one:

def move(self):

    speed = config.DEFAULT_SPEED

    # Update enemy's location
    if self.get_position()[0] < self.trackNextWaypoint()[1]:
        if self.trackNextWaypoint()[1] - self.get_position()[0] >= speed:
            self.set_position((self.get_position()[0] + speed, self.get_position()[1]))
        else:
            self.set_position((self.get_position()[0] + (self.trackNextWaypoint()[1] - self.get_position()[0]),
                       self.get_position()[1]))

    if self.get_position()[0] > self.trackNextWaypoint()[1]:
        if self.get_position()[0] - self.trackNextWaypoint()[1] >= speed:
            self.set_position((self.get_position()[0] - speed, self.get_position()[1]))
        else:
            self.set_position((self.get_position()[0] - (self.get_position()[0] - self.trackNextWaypoint()[1]),
                       self.get_position()[1]))

    if self.get_position()[1] < self.trackNextWaypoint()[2]:
        if self.trackNextWaypoint()[2] - self.get_position()[1] >= speed:
            self.set_position((self.get_position()[0], self.get_position()[1] + speed))
        else:
            self.set_position((self.get_position()[0],
                       self.get_position()[1] + (self.trackNextWaypoint()[2] - self.get_position()[1])))

    if self.get_position()[1] > self.trackNextWaypoint()[2]:
        if self.get_position()[1] - self.trackNextWaypoint()[2] >= speed:
            self.set_position((self.get_position()[0], self.get_position()[1] - speed))
        else:
            self.set_position((self.get_position()[0], self.get_position()[1] - (self.get_position()[1] - self.trackNextWaypoint()[2])))

    # If enemy position is on waypoint
    if self.get_position()[0] == self.trackNextWaypoint()[1] and self.get_position()[1] == self.trackNextWaypoint()[2]:
        self.setWaypointsReached(1)

Finally, these functions might also be needed for you understanding:

def trackNextWaypoint(self):
    for waypoint in config.WAYPOINTS:
        if waypoint[0] == self.waypoints_reached+1:
            return waypoint
            break

def setWaypointsReached(self, number):
    self.waypoints_reached += number

def get_position(self):
    return self.position

def set_position(self, position):
    self.position = position

Update

And I've also got an screenshot for your visualisation

Body:
Problem is because you use while inside for.

Object inside for should make only small step and external while should execute for many times.

You need some method to check if all objects are moved to destination and repeat again for loop.

I use how_many_moved to check if all enemies are in destination.

It could be something like this

# value bigger than 0 to start `while` loop
how_many_moved = 1

while how_many_moved > 0:

    how_many_moved = 0

    ### every enemy makes only small step ###
    for enemy in self.enemies:
        if enemy.waypoints_reached < len(config.WAYPOINTS):
            # count how many was moved
            how_many_moved += 1

            # Move enemy
            enemy.move()

            # Paint game + new enemy location
            self.paint(self.screen)

    # Update Screen afer every enemy made small step
    pygame.display.update()


问:
Javascript document write
How do I get this javascript to populate the textarea?

```<code><body onload="form1.submit();"><div align="center">Loading...</div>
<script type="text/javascript" src="<%= g_page_site_actual %>/js/jquery-1.4.2.min.js"></script>
<script type="text/javascript" src="<%= g_page_site_actual %>/js/jquery.wordstats.js"></script> <!-- core code -->
<script type="text/javascript" src="<%= g_page_site_actual %>/js/jquery.wordstats.en.js"></script> <!-- English stop words -->
<script type="text/javascript">
        $(function() {
            var count = 20;
            $.extend($.wordStats.stopWords, {'retrieved': true, '2007': true});
            $.wordStats.computeTopWords(count);
            var msgcounttext1 = '<%=completehtml%>'
            for(var i = 0, j = $.wordStats.topWords.length; i < j && i <= count; i++) {
               msg += $.wordStats.topWords[i].substring(1) + ', ';
            }
            {
            document.form1.textarea.value = document.write(msgcounttext);
            }
            $.wordStats.clear();
        });
        </script>
<div id="content" class="hidden"><%=completehtml%>
    <form id="form1" name="form1" method="post" action="test.asp">
        <textarea name="textarea" id="textarea" cols="45" rows="5"></textarea>
    </form>
  </div>
</body>
</code>```

Thanks

答: Besides not having a variable named msgcounttext, get rid of the document.write call.

Title: Javascript document write

Body:
How do I get this javascript to populate the textarea?

Loading...

<%=completehtml%>
    <form id="form1" name="form1" method="post" action="test.asp">
        <textarea name="textarea" id="textarea" cols="45" rows="5"></textarea>
    </form>

Thanks


问:
Env file is not read when I use docker-compose -f in a different directory
I have a problem with my Docker .env file. When I'm in my Docker folder (where I have the docker-compose.yml and .env file), the environment variables are read from .env fine. However, when I run docker-compose -f ./docker/docker-compose.yml up --build -d in a higher-level directory I  get warnings like:

```<code>The MYSQL_ROOT_PASSWORD variable is not set. Defaulting to a blank string.
</code>```

Has anyone encountered this problem? I tried setting the env_file property in docker-compose.yml and using other file encodings (I found this solution in Google) and still nothing.

This is my config:

```<code>version: '2'

services:
    mysql:
        container_name: mysql
        image: mysql
        volumes:
            - "./.data/db:/var/lib/mysql"
        environment:
            MYSQL_ROOT_PASSWORD: ${MYSQL_ROOT_PASSWORD}
            MYSQL_DATABASE: ${MYSQL_DATABASE}
            MYSQL_USER: ${MYSQL_USER}
            MYSQL_PASSWORD: ${MYSQL_PASSWORD}
</code>```

.env file:

```<code># MySQL
MYSQL_ROOT_PASSWORD=test
MYSQL_DATABASE=test
MYSQL_USER=test
MYSQL_PASSWORD=test
</code>```

答:
As Tagc says, this is the documented behavior of docker-compose with a .env file, it must be in the directory where you are running docker-compose. You cannot use env_file for this because that's setting a different environment. The .env file sets the environment used by docker-compose to parse the yml file (and therefore could not be set from within the file, that would be a circular dependency), while the env_file injects environment variables into the running containers.

If you cannot cd into the folder or move your .env file for some reason, you can manually source the file with something like:

```<code>env $(cat docker/.env | grep -v ^# | xargs) \
  docker-compose -f docker/docker-compose.yml up --build -d
</code>```

Body:
I have a problem with my Docker .env file. When I'm in my Docker folder (where I have the docker-compose.yml and .env file), the environment variables are read from .env fine. However, when I run docker-compose -f ./docker/docker-compose.yml up --build -d in a higher-level directory I  get warnings like:

The MYSQL_ROOT_PASSWORD variable is not set. Defaulting to a blank string.

Has anyone encountered this problem? I tried setting the env_file property in docker-compose.yml and using other file encodings (I found this solution in Google) and still nothing.

This is my config:

version: '2'

services:
    mysql:
        container_name: mysql
        image: mysql
        volumes:
            - "./.data/db:/var/lib/mysql"
        environment:
            MYSQL_ROOT_PASSWORD: ${MYSQL_ROOT_PASSWORD}
            MYSQL_DATABASE: ${MYSQL_DATABASE}
            MYSQL_USER: ${MYSQL_USER}
            MYSQL_PASSWORD: ${MYSQL_PASSWORD}

.env file:

# MySQL
MYSQL_ROOT_PASSWORD=test
MYSQL_DATABASE=test
MYSQL_USER=test
MYSQL_PASSWORD=test

Body:
As Tagc says, this is the documented behavior of docker-compose with a .env file, it must be in the directory where you are running docker-compose. You cannot use env_file for this because that's setting a different environment. The .env file sets the environment used by docker-compose to parse the yml file (and therefore could not be set from within the file, that would be a circular dependency), while the env_file injects environment variables into the running containers.

If you cannot cd into the folder or move your .env file for some reason, you can manually source the file with something like:

env $(cat docker/.env | grep -v ^# | xargs) \
  docker-compose -f docker/docker-compose.yml up --build -d


问:
GUI Slowness in swing application, JFileChooser initialization waiting in java call
We are experiencing slowness in our Java swing application. By observing stack traces at the time of GUI slowness, AWT Thread is in waiting state. To be specific below is the stacktrace observed multiple times.

```<code>"AWT-EventQueue-2" prio=0 tid=30 nid=0 waiting on condition [on lock java.util.concurrent.FutureTask@3312ed4c]
java.lang.Thread.State: WAITING (parking)
at sun.misc.Unsafe.park(Native Method)
at java.util.concurrent.locks.LockSupport.park(Unknown Source)
at java.util.concurrent.FutureTask.awaitDone(Unknown Source)
at java.util.concurrent.FutureTask.get(Unknown Source)
at sun.awt.shell.Win32ShellFolderManager2$ComInvoker.invoke(Unknown Source)
at sun.awt.shell.ShellFolder.invoke(Unknown Source)
at sun.awt.shell.Win32ShellFolder2.listFiles(Unknown Source)
at sun.awt.shell.ShellFolder.listFiles(Unknown Source)
at sun.awt.shell.Win32ShellFolderManager2.get(Unknown Source)
at sun.awt.shell.ShellFolder.get(Unknown Source)
at javax.swing.plaf.metal.MetalFileChooserUI$DirectoryComboBoxModel.addItem(Unknown Source)
at javax.swing.plaf.metal.MetalFileChooserUI$DirectoryComboBoxModel.access$800(Unknown Source)
at javax.swing.plaf.metal.MetalFileChooserUI.doDirectoryChanged(Unknown Source)
at javax.swing.plaf.metal.MetalFileChooserUI.access$1100(Unknown Source)
at javax.swing.plaf.metal.MetalFileChooserUI$5.propertyChange(Unknown Source)
at java.beans.PropertyChangeSupport.fire(Unknown Source)
at java.beans.PropertyChangeSupport.firePropertyChange(Unknown Source)
at java.beans.PropertyChangeSupport.firePropertyChange(Unknown Source)
at java.awt.Component.firePropertyChange(Unknown Source)
at javax.swing.JFileChooser.setCurrentDirectory(Unknown Source)
at javax.swing.JFileChooser.<init>(Unknown Source)
at javax.swing.JFileChooser.<init>(Unknown Source)
.
.
.
.
at javax.swing.SwingWorker$5.run(Unknown Source)
at javax.swing.SwingWorker$DoSubmitAccumulativeRunnable.run(Unknown Source)
at sun.swing.AccumulativeRunnable.run(Unknown Source)
at javax.swing.SwingWorker$DoSubmitAccumulativeRunnable.actionPerformed(Unknown Source)
at javax.swing.Timer.fireActionPerformed(Unknown Source)
at javax.swing.Timer$DoPostEvent.run(Unknown Source)
at java.awt.event.InvocationEvent.dispatch(Unknown Source)
at java.awt.EventQueue.dispatchEventImpl(Unknown Source)
at java.awt.EventQueue.access$500(Unknown Source)
at java.awt.EventQueue$3.run(Unknown Source)
at java.awt.EventQueue$3.run(Unknown Source)
at java.security.AccessController.doPrivileged(Native Method)
at java.security.ProtectionDomain$JavaSecurityAccessImpl.doIntersectionPrivilege(Unknown Source)
at java.awt.EventQueue.dispatchEvent(Unknown Source)
at java.awt.EventDispatchThread.pumpOneEventForFilters(Unknown Source)
at java.awt.EventDispatchThread.pumpEventsForFilter(Unknown Source)
at java.awt.EventDispatchThread.pumpEventsForHierarchy(Unknown Source)
at java.awt.EventDispatchThread.pumpEvents(Unknown Source)
at java.awt.EventDispatchThread.pumpEvents(Unknown Source)
at java.awt.EventDispatchThread.run(Unknown Source)

Locked synchronizers: count = 0
</code>```

Java version : 1.8.0_121

Is this a of bug in Java ? Has anyone faced similar issue?

Could anyone please help.

Thanks in advance!

答:
I think we have hit exactly same the issue mentioned at
JFileChooser with disconnected network drives

Removed the disconnected network drive and the performance is imporved.

Body:
We are experiencing slowness in our Java swing application. By observing stack traces at the time of GUI slowness, AWT Thread is in waiting state. To be specific below is the stacktrace observed multiple times.

"AWT-EventQueue-2" prio=0 tid=30 nid=0 waiting on condition [on lock java.util.concurrent.FutureTask@3312ed4c]
java.lang.Thread.State: WAITING (parking)
at sun.misc.Unsafe.park(Native Method)
at java.util.concurrent.locks.LockSupport.park(Unknown Source)
at java.util.concurrent.FutureTask.awaitDone(Unknown Source)
at java.util.concurrent.FutureTask.get(Unknown Source)
at sun.awt.shell.Win32ShellFolderManager2$ComInvoker.invoke(Unknown Source)
at sun.awt.shell.ShellFolder.invoke(Unknown Source)
at sun.awt.shell.Win32ShellFolder2.listFiles(Unknown Source)
at sun.awt.shell.ShellFolder.listFiles(Unknown Source)
at sun.awt.shell.Win32ShellFolderManager2.get(Unknown Source)
at sun.awt.shell.ShellFolder.get(Unknown Source)
at javax.swing.plaf.metal.MetalFileChooserUI$DirectoryComboBoxModel.addItem(Unknown Source)
at javax.swing.plaf.metal.MetalFileChooserUI$DirectoryComboBoxModel.access$800(Unknown Source)
at javax.swing.plaf.metal.MetalFileChooserUI.doDirectoryChanged(Unknown Source)
at javax.swing.plaf.metal.MetalFileChooserUI.access$1100(Unknown Source)
at javax.swing.plaf.metal.MetalFileChooserUI$5.propertyChange(Unknown Source)
at java.beans.PropertyChangeSupport.fire(Unknown Source)
at java.beans.PropertyChangeSupport.firePropertyChange(Unknown Source)
at java.beans.PropertyChangeSupport.firePropertyChange(Unknown Source)
at java.awt.Component.firePropertyChange(Unknown Source)
at javax.swing.JFileChooser.setCurrentDirectory(Unknown Source)
at javax.swing.JFileChooser.<init>(Unknown Source)
at javax.swing.JFileChooser.<init>(Unknown Source)
.
.
.
.
at javax.swing.SwingWorker$5.run(Unknown Source)
at javax.swing.SwingWorker$DoSubmitAccumulativeRunnable.run(Unknown Source)
at sun.swing.AccumulativeRunnable.run(Unknown Source)
at javax.swing.SwingWorker$DoSubmitAccumulativeRunnable.actionPerformed(Unknown Source)
at javax.swing.Timer.fireActionPerformed(Unknown Source)
at javax.swing.Timer$DoPostEvent.run(Unknown Source)
at java.awt.event.InvocationEvent.dispatch(Unknown Source)
at java.awt.EventQueue.dispatchEventImpl(Unknown Source)
at java.awt.EventQueue.access$500(Unknown Source)
at java.awt.EventQueue$3.run(Unknown Source)
at java.awt.EventQueue$3.run(Unknown Source)
at java.security.AccessController.doPrivileged(Native Method)
at java.security.ProtectionDomain$JavaSecurityAccessImpl.doIntersectionPrivilege(Unknown Source)
at java.awt.EventQueue.dispatchEvent(Unknown Source)
at java.awt.EventDispatchThread.pumpOneEventForFilters(Unknown Source)
at java.awt.EventDispatchThread.pumpEventsForFilter(Unknown Source)
at java.awt.EventDispatchThread.pumpEventsForHierarchy(Unknown Source)
at java.awt.EventDispatchThread.pumpEvents(Unknown Source)
at java.awt.EventDispatchThread.pumpEvents(Unknown Source)
at java.awt.EventDispatchThread.run(Unknown Source)

Locked synchronizers: count = 0

Java version : 1.8.0_121

Is this a of bug in Java ? Has anyone faced similar issue?

Could anyone please help.

Thanks in advance!


问:
Subscript out of range on VBA
I am writing my first VBA. I have a sheet named Sheet1. That sheet has a column E; I would like to delete all rows which have an empty field on column E.

Therefore, I wrote this code:

```<code>Sub EmptyCells()
   Sheets("Sheet1").Columns("E:E").SpecialCells(xlBlanks).EntireRow.Delete
End Sub
</code>```

However, when I run it, I get this error:

Subscript out of range

Why is this error occurring? I am sure the column E exists in Sheet1. Are my references incorrect?

EDIT

If I try Columns("E") or Range("E:E"), instead of Columns("E:E") I get the same error

答:
Your code works if you have a sheet named/titled Sheet1.

```<code>Sub EmptyCells()
   Sheets("Sheet1").Columns("E:E").SpecialCells(xlBlanks).EntireRow.Delete
End Sub
</code>```

Note that there are different ways to call a sheet.

```<code>Sheets("Sheet1") 'means the visible name of the sheet is `Sheet1` (not the same as VBA name)
                 'the number doesn't tell anything about it's position, it's just a name.

Sheet1           'means the VBA name of the sheet.
                 'the number doesn't tell anything about it's position, it's just a name.

Worksheets(1)    'means the first worksheet (which ever is in the first position)

Sheets(1)        'means the first sheet (can also be a chart not only a worksheet)
                 'this has no relation to its name which could be "Sheet5"
                 '(If "Sheet5" is in first position).
</code>```

Title: Subscript out of range on VBA

Body:
I am writing my first VBA. I have a sheet named Sheet1. That sheet has a column E; I would like to delete all rows which have an empty field on column E.

Therefore, I wrote this code:

Sub EmptyCells()
   Sheets("Sheet1").Columns("E:E").SpecialCells(xlBlanks).EntireRow.Delete
End Sub

However, when I run it, I get this error:

Subscript out of range

Why is this error occurring? I am sure the column E exists in Sheet1. Are my references incorrect?

EDIT

If I try Columns("E") or Range("E:E"), instead of Columns("E:E") I get the same error

Body:
Your code works if you have a sheet named/titled Sheet1.

Sub EmptyCells()
   Sheets("Sheet1").Columns("E:E").SpecialCells(xlBlanks).EntireRow.Delete
End Sub

Note that there are different ways to call a sheet.

Sheets("Sheet1") 'means the visible name of the sheet is `Sheet1` (not the same as VBA name)
                 'the number doesn't tell anything about it's position, it's just a name.

Sheet1           'means the VBA name of the sheet.
                 'the number doesn't tell anything about it's position, it's just a name.

Worksheets(1)    'means the first worksheet (which ever is in the first position)

Sheets(1)        'means the first sheet (can also be a chart not only a worksheet)
                 'this has no relation to its name which could be "Sheet5"
                 '(If "Sheet5" is in first position).


问:
Observing properties of an array that is being observed in KnockoutJS
I'm working on an ASP.Net MVC application. My action is returning a view with a model that is an array of objects (a class with properties like Name, ID, IsViewable).

```<code>var model = @Model.ToJson(); // done via extension call
</code>```

I want to observe this array, so whenever it changes I can update a table that has been bound to a template.

```<code>var viewModel = {
    accounts = ko.observableArray(model)
}
</code>```

This works just fine for adding and deleting elements from the array. However, I also want the template to update when a property in one of the accounts changes (ie, Name or ID).

On the KnockoutJS website, it says: Of course, you can make those properties observable if you wish, but that’s an independent choice. This is what I cannot figure out how to do.

I tried something like this with no avail:

```<code>var viewModel = {
    accounts = ko.oservableArray([])
}

for(var i = 0; i < model.length; i++) {
    ko.observableArray(model[i]);
    viewModel.accounts.push(model[i]);
}
</code>```

I can post the template and the table if it's needed.

答:
I ended up getting this to work, so I thought I would share with anyone that might have having the same problem.

You need to wrap your array items in a JavaScript class. Then in the constructor, set each property to obserable:

```<code>var model = @Model.ToJson();

var viewModel = {
    accounts = ko.observableArray(ko.utils.arrayMap(model, function(account) {
        return new AccountWrapper(account);
    }))
};

function AccountWrapper(account) {
    this.Property1 = ko.observable(account.Propery1);
    this.Property2 = ko.observable(account.Propery2);
    this.Property3 = ko.observable(account.Propery3);
}

ko.applyBindings(viewModel);
</code>```

And if you want to modify one of the items directly to see the change, you could do something like:

```<code>viewModel.accounts()[3].Name('My Name Changed');
</code>```

And you can still get notified when items are added or remove:

```<code>viewModel.accounts.remove(viewModel.accounts()[4]);
</code>```

Body:
I'm working on an ASP.Net MVC application. My action is returning a view with a model that is an array of objects (a class with properties like Name, ID, IsViewable).

var model = @Model.ToJson(); // done via extension call

I want to observe this array, so whenever it changes I can update a table that has been bound to a template.

var viewModel = {
    accounts = ko.observableArray(model)
}

This works just fine for adding and deleting elements from the array. However, I also want the template to update when a property in one of the accounts changes (ie, Name or ID).

On the KnockoutJS website, it says: Of course, you can make those properties observable if you wish, but that’s an independent choice. This is what I cannot figure out how to do.

I tried something like this with no avail:

var viewModel = {
    accounts = ko.oservableArray([])
}

for(var i = 0; i < model.length; i++) {
    ko.observableArray(model[i]);
    viewModel.accounts.push(model[i]);
}

I can post the template and the table if it's needed.

Body:
I ended up getting this to work, so I thought I would share with anyone that might have having the same problem.

You need to wrap your array items in a JavaScript class. Then in the constructor, set each property to obserable:

var model = @Model.ToJson();

var viewModel = {
    accounts = ko.observableArray(ko.utils.arrayMap(model, function(account) {
        return new AccountWrapper(account);
    }))
};

function AccountWrapper(account) {
    this.Property1 = ko.observable(account.Propery1);
    this.Property2 = ko.observable(account.Propery2);
    this.Property3 = ko.observable(account.Propery3);
}

ko.applyBindings(viewModel);

And if you want to modify one of the items directly to see the change, you could do something like:

viewModel.accounts()[3].Name('My Name Changed');

And you can still get notified when items are added or remove:

viewModel.accounts.remove(viewModel.accounts()[4]);


问:
Create button OnClientClick asp net
I'm creating button from code c#:

```<code>        Button btnAddCalculation = new Button();
        btnAddCalculation.ID = "btnAddCalculation";
        btnAddCalculation.Text = "Add count";
        btnAddCalculation.SkinID = "middleButton";
        btnAddCalculation.Visible = true;

        string sPath = String.Format(
            "WindowCalculationArenda.aspx?{0}={1}&TempGuid={2}&IdDocument={3}",
            SessionViewstateConstants.CalculationType,
            CalcType.New,
            Guid.NewGuid(),
            oEditedDocument.Id.ToString()
        );
        //          btnAddCalculation.Attributes.Add("onclick", @"window.open('InformationAboutAddAddr.aspx', '_blank', 'location=yes,height=500,width=450,scrollbars=yes,status=yes');");
        btnAddCalculation.Click += new EventHandler(btnClick_cl);
        btnAddCalculation.OnClientClick = clsCommonHelper.sGetWindowOpen(sPath, 1100, 500) + "return false;";

    public static string sGetWindowOpen(string sLink, int iWidth, int iHeight)
    {
        return "javascript:setTimeout(function(){ WindowOpen('" + sLink + "', " + iWidth + ", " + iHeight + "); }, 100); ";
    }
</code>```

but in the client side the function OnClientClick does not work, when I click
nothing happens. What Did I do wrong???

Generated HTML:

```<code><input type="submit" name="ctl00$ctl00$Main$EditorMain$tabTabContainer$ctl00$Attr433$btnAddCalculation"
value="Add count"
id="ctl00_ctl00_Main_EditorMain_tabTabContainer_ctl00_Attr433_btnAddCalculation"
disabled="disabled" class="blue_button" />
</code>```

答:
The ASP.NET code you provided looks ok; so I suspect the problem is related to a script that is run on the clientside. Maybe the submit-button is disabled because the form contents are not valid yet. In this case your button might be disabled, depending on the selector that is used to identify the submit-button.

To avoid this, change the behavior of the button so that it is rendered as an input of type button instead of submit. You can use the UseSubmitBehavior-property to achieve this:

```<code>btnAddCalculation.UseSubmitBehavior = false;
</code>```

Title: Create button OnClientClick asp net

Body:
I'm creating button from code c#:

        Button btnAddCalculation = new Button();
        btnAddCalculation.ID = "btnAddCalculation";
        btnAddCalculation.Text = "Add count";
        btnAddCalculation.SkinID = "middleButton";
        btnAddCalculation.Visible = true;

        string sPath = String.Format(
            "WindowCalculationArenda.aspx?{0}={1}&TempGuid={2}&IdDocument={3}",
            SessionViewstateConstants.CalculationType,
            CalcType.New,
            Guid.NewGuid(),
            oEditedDocument.Id.ToString()
        );
        //          btnAddCalculation.Attributes.Add("onclick", @"window.open('InformationAboutAddAddr.aspx', '_blank', 'location=yes,height=500,width=450,scrollbars=yes,status=yes');");
        btnAddCalculation.Click += new EventHandler(btnClick_cl);
        btnAddCalculation.OnClientClick = clsCommonHelper.sGetWindowOpen(sPath, 1100, 500) + "return false;";

    public static string sGetWindowOpen(string sLink, int iWidth, int iHeight)
    {
        return "javascript:setTimeout(function(){ WindowOpen('" + sLink + "', " + iWidth + ", " + iHeight + "); }, 100); ";
    }

but in the client side the function OnClientClick does not work, when I click
nothing happens. What Did I do wrong???

Generated HTML:

<input type="submit" name="ctl00$ctl00$Main$EditorMain$tabTabContainer$ctl00$Attr433$btnAddCalculation"
value="Add count"
id="ctl00_ctl00_Main_EditorMain_tabTabContainer_ctl00_Attr433_btnAddCalculation"
disabled="disabled" class="blue_button" />

Body:
The ASP.NET code you provided looks ok; so I suspect the problem is related to a script that is run on the clientside. Maybe the submit-button is disabled because the form contents are not valid yet. In this case your button might be disabled, depending on the selector that is used to identify the submit-button.

To avoid this, change the behavior of the button so that it is rendered as an input of type button instead of submit. You can use the UseSubmitBehavior-property to achieve this:

btnAddCalculation.UseSubmitBehavior = false;


问:
RegEx for no whitespace at the beginning and end
I want to design an expression for not allowing whitespace at the beginning and at the end of a string, but allowing in the middle of the string.

The regex I've tried is this:

```<code>\^[^\s][a-z\sA-Z\s0-9\s-()][^\s$]\
</code>```

答:
pattern="^[^\s]+[-a-zA-Z\s]+([-a-zA-Z]+)*$"
This will help you accept only characters and wont allow spaces at the start nor whitespaces.</p>

ContentLicense: CC BY-SA 4.0

Body:
I want to design an expression for not allowing whitespace at the beginning and at the end of a string, but allowing in the middle of the string.

The regex I've tried is this:

\^[^\s][a-z\sA-Z\s0-9\s-()][^\s$]\


问:
Django : Is it impossible to static tag into block tag?
The code below makes error.. How could I resolve this problem?

```<code>{% block header %}
    <link rel="stylesheet" href="{% static 'shop/style.css' %}" />
{% endblock %}
</code>```

The error output:

TemplateSyntaxError : Invalid block tag: 'static', expected 'endblock'

答:
My solution is to include another page with {% load static %} and script with static reference. {% block xxx %} expects the first {% yyy %} not to be other than {% include %} and {% endblock %}(the only cases I have observed); so when we use "{% static 'xxx.js' %}" it breaks and complains. But including another page will put Django in calm.

For example, I have a page homepage which extends base.html and has some static js files which are not included in base.html.

base.html

```<code>{% block page %}

{% endblock %}
{% block script %}

{% endblock %}
</code>```

homepage.html:

```<code>{% extends 'base.html' %}
{% block page %}
...
{% endblock %}
{% block script %}
    {% include 'home_js.html'%}  <!-- don't use static links here because Django does not like it. -->
{% endblock %}
</code>```

home_js.html:

```<code>{% load static %}
<script src="{% static 'scripts/jquery.js' %}" ></script>
<script>
    function ...
</script>
</code>```

Now the scripts loads.

So, in a block we cannot use {% %} tags other than {% block xxx %} and {% endblock %}.

I am using Django 5.1.

EDIT:

I found {% verbatim %} tag to be our savior under such situation.

Body:
The code below makes error.. How could I resolve this problem?

{% block header %}
    <link rel="stylesheet" href="{% static 'shop/style.css' %}" />
{% endblock %}

The error output:

TemplateSyntaxError : Invalid block tag: 'static', expected 'endblock'

Body:
My solution is to include another page with {% load static %} and script with static reference. {% block xxx %} expects the first {% yyy %} not to be other than {% include %} and {% endblock %}(the only cases I have observed); so when we use "{% static 'xxx.js' %}" it breaks and complains. But including another page will put Django in calm.

For example, I have a page homepage which extends base.html and has some static js files which are not included in base.html.

base.html

{% block page %}

{% endblock %}
{% block script %}

{% endblock %}

homepage.html:

{% extends 'base.html' %}
{% block page %}
...
{% endblock %}
{% block script %}
    {% include 'home_js.html'%}  <!-- don't use static links here because Django does not like it. -->
{% endblock %}

home_js.html:

{% load static %}
<script src="{% static 'scripts/jquery.js' %}" ></script>
<script>
    function ...
</script>

Now the scripts loads.

So, in a block we cannot use {% %} tags other than {% block xxx %} and {% endblock %}.

I am using Django 5.1.

EDIT:

I found {% verbatim %} tag to be our savior under such situation.


问:
Magnolia 5.5.5 Custom Content Editor App (Stories) Custom CKEditor Config
I have got the following problem:

I want to add a customConfig to the ckeditor of the RichTextBlock.
Therefore I want to overwrite the content_editor_config.js which is a static final in TextBlockWidget.java. How can I do this?

答:
I can see two options:

Extend the class and change the references to the new one (don't forget to compile the widgetset since it's client side code)

Directly modify the content_editor_config.js file which seems to be the easier option if you want to modify all TextBlocks

Hope that helps,

Cheers,


问:
Sikuli selenium with eclipse
I would like to automate simple process to fill an internet form.
I use the Eclipse environment with Sikuli and Selenium for this purpose.
I follow the following tutorial. https://www.youtube.com/watch?v=8y41vKeGM9U
Still after writing the following code it do not seems to connect and open Google Chrome. With several problems: red cross on the class and project name icones, pattern cannot be resolved to a type. It seems to me that it cannot properly connect and perform while I think that I installed all the useful .jar files. I could be wrong on that. If you could help please. Thanks.

```<code>import org.sikuli.script.Screen;

public class FillForm {

    public static void main(String[] args) {
        // TODO Auto-generated method stub

        Screen screen = new Screen();
        Pattern pattern = new Pattern("C:\\Users\\mahfo\\Documents\\Sikuli project\\Pictures\\LoginShizugin.PNG");
        Pattern pattern1 = new Pattern("C:\\Users\\mahfo\\Documents\\Sikuli project\\Pictures\\LoginShizugin1.PNG");
        Pattern pattern2 = new Pattern("C:\\Users\\mahfo\\Documents\\Sikuli project\\Pictures\\LoginShizugin1.PNG");
        Pattern pattern3 = new Pattern("C:\\Users\\mahfo\\Documents\\Sikuli project\\Pictures\\LoginShizugin1.PNG");
        Pattern pattern4 = new Pattern("C:\\Users\\mahfo\\Documents\\Sikuli project\\Pictures\\LoginShizugin1.PNG");
        Pattern pattern5 = new Pattern("C:\\Users\\mahfo\\Documents\\Sikuli project\\Pictures\\LoginShizugin1.PNG");
        Pattern pattern6 = new Pattern("C:\\Users\\mahfo\\Documents\\Sikuli project\\Pictures\\LoginShizugin1.PNG");
        Pattern pattern7 = new Pattern("C:\\Users\\mahfo\\Documents\\Sikuli project\\Pictures\\LoginShizugin1.PNG");
        Pattern pattern8 = new Pattern("C:\\Users\\mahfo\\Documents\\Sikuli project\\Pictures\\LoginShizugin1.PNG");

        System.setProperty("webdriver.chrome.driver","C:\\Users\\mahfo\\Downloads\\chromedriver_win32.zip\\chromedriver.exe");
        WebDriver driver = new ChromeDriver();
        driver.get("https://www.******************.co.**/0149c/rblgi01/I1RBLGI01-S01.do");
        screen.wait(pattern, 5000);
        screen.type(pattern, "*****");
        screen.click(pattern1);
        screen.click(pattern2);
        screen.type(pattern3, "***********");
        screen.click(pattern4);
        screen.click(pattern5);
        screen.click(pattern6);
        screen.click(pattern7);
        screen.click(pattern8);
</code>```

答:
Below steps worked for me, please check whether you added this jar to your project build path

Download Sikulixsetup-1.1.0.jar from launchpad.net/sikuli/+download website

Click on that jar to setup. After installing that, add sikulixapi.jar as external jar in Buildpath.

or

You can try with maven dependency if it is configured as maven project. I didn't try with this dependency, just try this if you want:
mvnrepository.com/artifact/org.sikuli/sikuli-core/1.0.0, try this.

```<code><!-- https://mvnrepository.com/artifact/org.sikuli/sikuli-core -->
    <dependency>
    <groupId>org.sikuli</groupId>
    <artifactId>sikuli-core</artifactId>
    <version>1.0.0</version>
    </dependency>
</code>```

Title: Sikuli selenium with eclipse

Body:
I would like to automate simple process to fill an internet form.
I use the Eclipse environment with Sikuli and Selenium for this purpose.
I follow the following tutorial. https://www.youtube.com/watch?v=8y41vKeGM9U
Still after writing the following code it do not seems to connect and open Google Chrome. With several problems: red cross on the class and project name icones, pattern cannot be resolved to a type. It seems to me that it cannot properly connect and perform while I think that I installed all the useful .jar files. I could be wrong on that. If you could help please. Thanks.

import org.sikuli.script.Screen;

public class FillForm {

    public static void main(String[] args) {
        // TODO Auto-generated method stub

        Screen screen = new Screen();
        Pattern pattern = new Pattern("C:\\Users\\mahfo\\Documents\\Sikuli project\\Pictures\\LoginShizugin.PNG");
        Pattern pattern1 = new Pattern("C:\\Users\\mahfo\\Documents\\Sikuli project\\Pictures\\LoginShizugin1.PNG");
        Pattern pattern2 = new Pattern("C:\\Users\\mahfo\\Documents\\Sikuli project\\Pictures\\LoginShizugin1.PNG");
        Pattern pattern3 = new Pattern("C:\\Users\\mahfo\\Documents\\Sikuli project\\Pictures\\LoginShizugin1.PNG");
        Pattern pattern4 = new Pattern("C:\\Users\\mahfo\\Documents\\Sikuli project\\Pictures\\LoginShizugin1.PNG");
        Pattern pattern5 = new Pattern("C:\\Users\\mahfo\\Documents\\Sikuli project\\Pictures\\LoginShizugin1.PNG");
        Pattern pattern6 = new Pattern("C:\\Users\\mahfo\\Documents\\Sikuli project\\Pictures\\LoginShizugin1.PNG");
        Pattern pattern7 = new Pattern("C:\\Users\\mahfo\\Documents\\Sikuli project\\Pictures\\LoginShizugin1.PNG");
        Pattern pattern8 = new Pattern("C:\\Users\\mahfo\\Documents\\Sikuli project\\Pictures\\LoginShizugin1.PNG");

        System.setProperty("webdriver.chrome.driver","C:\\Users\\mahfo\\Downloads\\chromedriver_win32.zip\\chromedriver.exe");
        WebDriver driver = new ChromeDriver();
        driver.get("https://www.******************.co.**/0149c/rblgi01/I1RBLGI01-S01.do");
        screen.wait(pattern, 5000);
        screen.type(pattern, "*****");
        screen.click(pattern1);
        screen.click(pattern2);
        screen.type(pattern3, "***********");
        screen.click(pattern4);
        screen.click(pattern5);
        screen.click(pattern6);
        screen.click(pattern7);
        screen.click(pattern8);

Body:
Below steps worked for me, please check whether you added this jar to your project build path

Download Sikulixsetup-1.1.0.jar from launchpad.net/sikuli/+download website

Click on that jar to setup. After installing that, add sikulixapi.jar as external jar in Buildpath.

or

You can try with maven dependency if it is configured as maven project. I didn't try with this dependency, just try this if you want:
mvnrepository.com/artifact/org.sikuli/sikuli-core/1.0.0, try this.

<!-- https://mvnrepository.com/artifact/org.sikuli/sikuli-core -->
    <dependency>
    <groupId>org.sikuli</groupId>
    <artifactId>sikuli-core</artifactId>
    <version>1.0.0</version>
    </dependency>


问:
sql site or book with exercise queries more complicated than www3.schools.com
Hi
is there any online resource for practicing SQL queries more complicated ?
basically I had a db dev until now and I kind of forgot. I want to switch jobs and freshen up a little.
They should more complicated than 2 joins or something, as my level is medium or senior hopefully :)
Thank you</p>

答:
download SQL Server Express, it is free

Then pick out one of the zillion SQL Server books available at amazon or any local bookstore.  There should be lots for every level of experience.  Then, work through the examples in that book.


问:
How to re upload the same file twice using angular-file-upload (nervgh/angular-file-upload)
im using angular-file-upload module for uploading files in my angular application , but i have requirement like upload the same file again , but not able to upload again , as module checks the isUploaded property of item(file) before uploading .
is there any work around  </p>

答:
We can use the onAfterAddingFile call back which is getting fired after adding a file to queue, to store the copy of the original file. now we can upload the original and copied file separately using uploader1 and uploader2:

```<code>$scope.uploader1 = new FileUploader({
    url: url,
    queueLimit: 1
});

$scope.uploader2 = new FileUploader({
    url: url,
    queueLimit: 1
});

uploader1.onAfterAddingFile = function (fileItem1) {
    var fileItem2 = new FileUploader.FileItem($scope.uploaderOnSuccess,
    {
        lastModifiedDate: fileItem1.file.lastModifiedDate,
        size: fileItem1.file.size,
        type: fileItem1.file.type,
        name: fileItem1.file.name,
    });
    fileItem2._file = fileItem1._file;
    fileItem2.progress = 0;
    fileItem2.isUploaded = false;
    fileItem2.isSuccess = false;
    $scope.uploader2.queue.push(fileItem2);
};
</code>```

Body:
We can use the onAfterAddingFile call back which is getting fired after adding a file to queue, to store the copy of the original file. now we can upload the original and copied file separately using uploader1 and uploader2:

$scope.uploader1 = new FileUploader({
    url: url,
    queueLimit: 1
});

$scope.uploader2 = new FileUploader({
    url: url,
    queueLimit: 1
});

uploader1.onAfterAddingFile = function (fileItem1) {
    var fileItem2 = new FileUploader.FileItem($scope.uploaderOnSuccess,
    {
        lastModifiedDate: fileItem1.file.lastModifiedDate,
        size: fileItem1.file.size,
        type: fileItem1.file.type,
        name: fileItem1.file.name,
    });
    fileItem2._file = fileItem1._file;
    fileItem2.progress = 0;
    fileItem2.isUploaded = false;
    fileItem2.isSuccess = false;
    $scope.uploader2.queue.push(fileItem2);
};


问:
How to make express js and socket io listen to different ports
I have my socket io and Node express js server both listen to same ports now. Its hosted in AWS ElasticBeanStalk. Its working good.
Now due to security restrictions , have to move socket io to different port. Its a part of the same code base as of node js app.
Can I listen to a different port for socket io? Will that work ?What changes will I have to do in ElasticBeanStalk? Any new ports has to be opened Or is there any restriction in the port?</p>

答:
The docs give examples of connecting via Express or via standard Node HTTP. So technically you can just meld both of them together and listen on different ports.

```<code>var exApp = require('express')();
var exServer = require('http').Server(exApp);

var ioApp = require('http').createServer(handler);
var io = require('socket.io')(ioApp);

exServer.listen(80);
ioApp.listen(81);

function handler (req, res) {
  res.writeHead(200).end({});
}

app.get('/', function (req, res) {
  res.sendfile(__dirname + '/index.html');
});

// Then whatever you want to do with `io`, and `exApp`.
</code>```

If you go to localhost:80, you'll get the Express app served, and if you send socket.io requests to localhost:81, it should trigger the io.connection()

I haven't technically tested this, so let me know if I'm wildly off and I'll further think about it.

Body:
The docs give examples of connecting via Express or via standard Node HTTP. So technically you can just meld both of them together and listen on different ports.

var exApp = require('express')();
var exServer = require('http').Server(exApp);

var ioApp = require('http').createServer(handler);
var io = require('socket.io')(ioApp);

exServer.listen(80);
ioApp.listen(81);

function handler (req, res) {
  res.writeHead(200).end({});
}

app.get('/', function (req, res) {
  res.sendfile(__dirname + '/index.html');
});

// Then whatever you want to do with `io`, and `exApp`.

If you go to localhost:80, you'll get the Express app served, and if you send socket.io requests to localhost:81, it should trigger the io.connection()

I haven't technically tested this, so let me know if I'm wildly off and I'll further think about it.


问:
Aggregate and NA values
I've got a dataframe with 1000 observations.
 For each observation I got five variables. Now I'd like to create a new variable which is an aggregation from those 5 variables.
 I typed the following:

```<code>df$aggr_variable <- (1/5)*(var1+var2+var3+var4+var5)
</code>```

I then got the new aggregated variable, but also a problem. If let's say observation 839 got a missing value NA in var2, but still values for the other four variables, it gives me NA in the aggregated variable.

How can I leave the NA's of the five variables out without having to leave out the whole observation when one variable contains an NA?

答:
According to your aggregate equation, you are computing the average value of these five  variables for each sample(row).</p>

```<code>#some reproduciable data
df <- data.frame(var1=rnorm(20,10,5),var2=rnorm(20,5,1),var3=rnorm(20,30,1),
                 var4=rnorm(20,0,1),var5=rnorm(20,3,3))
#generates some NAs:
df[11,5] <- NA
df[8,3] <- NA
df[9,1] <- NA
df[17,2] <- NA
df[11,2] <- NA

#aggregate by mean
df$aggr_variable <- apply(df,1,function(x){mean(x,na.rm=T)})
</code>```

Title: Aggregate and NA values

Body:
I've got a dataframe with 1000 observations.
 For each observation I got five variables. Now I'd like to create a new variable which is an aggregation from those 5 variables.
 I typed the following:

df$aggr_variable <- (1/5)*(var1+var2+var3+var4+var5)

I then got the new aggregated variable, but also a problem. If let's say observation 839 got a missing value NA in var2, but still values for the other four variables, it gives me NA in the aggregated variable.

How can I leave the NA's of the five variables out without having to leave out the whole observation when one variable contains an NA?

Body:
According to your aggregate equation, you are computing the average value of these five  variables for each sample(row).

#some reproduciable data
df <- data.frame(var1=rnorm(20,10,5),var2=rnorm(20,5,1),var3=rnorm(20,30,1),
                 var4=rnorm(20,0,1),var5=rnorm(20,3,3))
#generates some NAs:
df[11,5] <- NA
df[8,3] <- NA
df[9,1] <- NA
df[17,2] <- NA
df[11,2] <- NA

#aggregate by mean
df$aggr_variable <- apply(df,1,function(x){mean(x,na.rm=T)})


问:
Is image pre-processing required (Google Mobile Vision Text Recognition API)?
In short: Is it needed or not to improve accuracy?

A bit longer: I was going through documentation and Internet and I did not find any references concerning Mobile Vision and if it is doing some sort of image pre-processing procedures by itself or not. I am talking about e.g. deskewing, binarisation or etc.

I know that e.g. you might improve tesseract-ocr accuracy by pre-processing images.

答:
The TextRecogniser does pretty well without any prosessering, but from my (very limited) experiments it does not seem to do any deskewing.
If you rotate the phone by >30 degrees the recognition breaks down and if have artifacts very close to the text then it also seems to break down.

Tested it with the lab from: https://codelabs.developers.google.com/codelabs/mobile-vision-ocr/


问:
What is a raw type and why shouldn't we use it?

Questions:

What are raw types in Java, and why do I often hear that they shouldn't be used in new code?

What is the alternative if we can't use raw types, and how is it better?

答:
Raw types are fine when they express what you want to express.

For example, a deserialisation function might return a List, but it doesn't know the list's element type. So List is the appropriate return type here.


问:
Good class to identify browser and OS
Is there any descent class that are capable to identify browser, its version and operating system?

I have tried default php function get_browser but results returned was wrong, it could not recognise non of my browsers (IE,Opera,Chrome,FF) except firefox but with wrong version.

答:
Take a look at phpbrowscap: https://github.com/garetjax/phpbrowscap

Use it like this:

```<code>$bc = new Browscap('/path/to/temp/dir');
$current_browser = $bc->getBrowser();

echo "```";
print_r($current_browser);
echo "```";
</code>```

Title: Good class to identify browser and OS

Body:
Take a look at phpbrowscap: https://github.com/garetjax/phpbrowscap

Use it like this:

$bc = new Browscap('/path/to/temp/dir');
$current_browser = $bc->getBrowser();

echo "<pre>";
print_r($current_browser);
echo "</pre>";