问:
Spamassassin Bayes Not Working
I'm getting no bayes score on any email and there appears to be no bayes filtering despite my best efforts. I am not a linux and spamassassin guru, so I'm asking for some help.

I have built up these settings in local.cf in attempts to get bayes working:

```<code>use_bayes 1
bayes_auto_learn 1
bayes_min_ham_num 100
bayes_auto_learn_threshold_nonspam -0.001
bayes_auto_learn_threshold_spam 6.0
allow_user_rules 0
add_header all Status _YESNO_, score=_SCORE_ required=_REQD_ tests=_TESTS_ autolearn=_AUTOLEARN_ version=_VERSION_
</code>```

The spamassassin log file shows one error consistently:

```<code>Fri Mar  3 12:36:27 2017 [10104] info: spamd: creating default_prefs: /root/.spamassassin/user_prefs
Fri Mar  3 12:36:27 2017 [10104] info: spamd: failed to create readable default_prefs: /root/.spamassassin/user_prefs
</code>```

and one error sporadically:

```<code>warn: plugin: eval failed: bayes: (in learn) locker: safe_lock: cannot create tmp lockfile /root/.spamassassin/bayes.lock.[mydomain.com].27903 for /root/.spamassassin/bayes.lock: Permission denied
</code>```

/root/.spamassassin/user_prefs does exist, and I've given everyone permissions to it to attempt to resolve this problem, with no effect:

```<code>-rwxrwxrwx 1 root root    1273 Mar  1 14:46 user_prefs*
</code>```

My spamd launch command explicitly sets the user as spamd, but the main service is still running as root while children appear to be spawning properly. Here's ps output:

```<code>root     10093  0.0  1.5 145988 66952 ?        Ss   02:25   0:05 /usr/sbin/spamd --create-prefs --max-children=5 --username=spamd --helper-home-dir=/var/log/spamassassin/ --syslog=/var/log/spamassassin/spam .log -d --pidfile=/var/run/spamd.pid
spamd    10104  0.0  1.8 155348 75544 ?        S    02:25   0:22 spamd child
spamd    23753  0.0  1.7 151732 72000 ?        S    10:30   0:02 spamd child
</code>```

My bayes database exists for root:

```<code>sa-learn --dump magic
0.000          0          3          0  non-token data: bayes db version
0.000          0       1727          0  non-token data: nspam
0.000          0        111          0  non-token data: nham
0.000          0     103812          0  non-token data: ntokens
0.000          0 1484629200          0  non-token data: oldest atime
0.000          0 1488559525          0  non-token data: newest atime
0.000          0 1488323169          0  non-token data: last journal sync atime
0.000          0          0          0  non-token data: last expiry atime
0.000          0          0          0  non-token data: last expire atime delta
0.000          0          0          0  non-token data: last expire reduction count
</code>```

All of my email headers have either of these, despite me forcing autolearn on with the thresholds shown above:

```<code>autolearn=unavailable autolearn_force=no
</code>```

or

```<code>autolearn=no autolearn_force=no
</code>```

Lastly, here's a full snippet of the spamassassin log showing it identifying spam, but not applying any bayes processing, while apparently working as root:

```<code>Fri Mar  3 12:55:11 2017 [10104] info: spamd: connection from localhost [::1]:54673 to port 783, fd 6
Fri Mar  3 12:55:11 2017 [10104] info: spamd: creating default_prefs: /root/.spamassassin/user_prefs
Fri Mar  3 12:55:11 2017 [10104] info: spamd: failed to create readable default_prefs: /root/.spamassassin/user_prefs
Fri Mar  3 12:55:11 2017 [10104] info: spamd: processing message <5323541152335322929654419@lo.nbvc12345.xyz> for root:1010
Fri Mar  3 12:55:11 2017 [10104] info: spamd: identified spam (10.5/3.0) for root:1010 in 0.2 seconds, 8433 bytes.
Fri Mar  3 12:55:11 2017 [10104] info: spamd: result: Y 10 - HTML_FONT_LOW_CONTRAST,HTML_MESSAGE,MPART_ALT_DIFF,RCVD_IN_BRBL_LASTEXT,RCVD_IN_SBL_CSS,RDNS_NONE,T_REMOTE_IMAGE,URIBL_BLOCKED,URIBL_DBL_SPAM,URIBL_SBL,URIBL_SBL_A scantime=0.2,size=8433,user=root,uid=1010,required_score=3.0,rhost=localhost,raddr=::1,rport=54673,mid=<5323541152335322929654419@lo.nbvc12345.xyz>,autolearn=no autolearn_force=no
Fri Mar  3 12:55:11 2017 [10093] info: prefork: child states: II
</code>```

and here's a full snippet of it missing spam, because of no bayes filtering:

```<code>Fri Mar  3 13:01:31 2017 [10104] info: spamd: connection from localhost [::1]:56926 to port 783, fd 6
Fri Mar  3 13:01:31 2017 [10104] info: spamd: creating default_prefs: /root/.spamassassin/user_prefs
Fri Mar  3 13:01:31 2017 [10104] info: spamd: failed to create readable default_prefs: /root/.spamassassin/user_prefs
Fri Mar  3 13:01:31 2017 [10104] info: spamd: processing message <sie819-8bh73y10780523sdgw_ds7fid385303272d2g-8h723se@email.searchresultsnewinfo.com> for root:1010
Fri Mar  3 13:01:31 2017 [10104] info: spamd: clean message (1.3/3.0) for root:1010 in 0.3 seconds, 8104 bytes.
Fri Mar  3 13:01:31 2017 [10104] info: spamd: result: . 1 - RDNS_NONE,URIBL_BLOCKED scantime=0.3,size=8104,user=root,uid=1010,required_score=3.0,rhost=localhost,raddr=::1,rport=56926,mid=<sie819-8bh73y10780523sdgw_ds7fid385303272d2g-8h723se@email.searchresultsnewinfo.com>,autolearn=no autolearn_force=no
Fri Mar  3 13:01:31 2017 [10093] info: prefork: child states: II
</code>```

Is the problem that the bayes database is in /root/.spamassassin and the child processes can't access it? Where should it be, or is it something else? At my limited knowledge's end on this. Any help appreciated.

答:
The problem is related to spamd running as root and the spamd children (spamc) running under the user "spamd", with insufficient permissions to access the bayes database in /root/.spamassassin.

To have spamassassin properly look at the bayes database, it must be in a location accessible to the children, and I had to tell spamassassin where to find it by adding this line to local.cf

```<code>bayes_path /var/spamassassin/bayesdb/bayes
</code>```

I then needed to create /var/spamassassin/bayesdb (not /var/spamassassin/bayesdb/bayes as the trailing "bayes" is the prefix for the filenames that will be in the bayesdb folder) and make user "spamd" the owner:

```<code>cd /var
chown -R spamd:some_group spamassassin
</code>```

I then moved the existing bayes database files from /root/.spamassassin to /var/spamassassin/bayesdb, performed the same ownership operation as above on the files, and the bayes filtering started working properly.

I did not resolve the issue with the children attempting to create user_prefs in /root/.spamassassin, as it's the same issue with permissions, but doesn't seem to affect bayes working, which was all I was after.

Title: Spamassassin Bayes Not Working

Body:
I'm getting no bayes score on any email and there appears to be no bayes filtering despite my best efforts. I am not a linux and spamassassin guru, so I'm asking for some help.

I have built up these settings in local.cf in attempts to get bayes working:

use_bayes 1
bayes_auto_learn 1
bayes_min_ham_num 100
bayes_auto_learn_threshold_nonspam -0.001
bayes_auto_learn_threshold_spam 6.0
allow_user_rules 0
add_header all Status _YESNO_, score=_SCORE_ required=_REQD_ tests=_TESTS_ autolearn=_AUTOLEARN_ version=_VERSION_

The spamassassin log file shows one error consistently:

Fri Mar  3 12:36:27 2017 [10104] info: spamd: creating default_prefs: /root/.spamassassin/user_prefs
Fri Mar  3 12:36:27 2017 [10104] info: spamd: failed to create readable default_prefs: /root/.spamassassin/user_prefs

and one error sporadically:

warn: plugin: eval failed: bayes: (in learn) locker: safe_lock: cannot create tmp lockfile /root/.spamassassin/bayes.lock.[mydomain.com].27903 for /root/.spamassassin/bayes.lock: Permission denied

/root/.spamassassin/user_prefs does exist, and I've given everyone permissions to it to attempt to resolve this problem, with no effect:

-rwxrwxrwx 1 root root    1273 Mar  1 14:46 user_prefs*

My spamd launch command explicitly sets the user as spamd, but the main service is still running as root while children appear to be spawning properly. Here's ps output:

root     10093  0.0  1.5 145988 66952 ?        Ss   02:25   0:05 /usr/sbin/spamd --create-prefs --max-children=5 --username=spamd --helper-home-dir=/var/log/spamassassin/ --syslog=/var/log/spamassassin/spam .log -d --pidfile=/var/run/spamd.pid
spamd    10104  0.0  1.8 155348 75544 ?        S    02:25   0:22 spamd child
spamd    23753  0.0  1.7 151732 72000 ?        S    10:30   0:02 spamd child

My bayes database exists for root:

sa-learn --dump magic
0.000          0          3          0  non-token data: bayes db version
0.000          0       1727          0  non-token data: nspam
0.000          0        111          0  non-token data: nham
0.000          0     103812          0  non-token data: ntokens
0.000          0 1484629200          0  non-token data: oldest atime
0.000          0 1488559525          0  non-token data: newest atime
0.000          0 1488323169          0  non-token data: last journal sync atime
0.000          0          0          0  non-token data: last expiry atime
0.000          0          0          0  non-token data: last expire atime delta
0.000          0          0          0  non-token data: last expire reduction count

All of my email headers have either of these, despite me forcing autolearn on with the thresholds shown above:

autolearn=unavailable autolearn_force=no

or

autolearn=no autolearn_force=no

Lastly, here's a full snippet of the spamassassin log showing it identifying spam, but not applying any bayes processing, while apparently working as root:

Fri Mar  3 12:55:11 2017 [10104] info: spamd: connection from localhost [::1]:54673 to port 783, fd 6
Fri Mar  3 12:55:11 2017 [10104] info: spamd: creating default_prefs: /root/.spamassassin/user_prefs
Fri Mar  3 12:55:11 2017 [10104] info: spamd: failed to create readable default_prefs: /root/.spamassassin/user_prefs
Fri Mar  3 12:55:11 2017 [10104] info: spamd: processing message <5323541152335322929654419@lo.nbvc12345.xyz> for root:1010
Fri Mar  3 12:55:11 2017 [10104] info: spamd: identified spam (10.5/3.0) for root:1010 in 0.2 seconds, 8433 bytes.
Fri Mar  3 12:55:11 2017 [10104] info: spamd: result: Y 10 - HTML_FONT_LOW_CONTRAST,HTML_MESSAGE,MPART_ALT_DIFF,RCVD_IN_BRBL_LASTEXT,RCVD_IN_SBL_CSS,RDNS_NONE,T_REMOTE_IMAGE,URIBL_BLOCKED,URIBL_DBL_SPAM,URIBL_SBL,URIBL_SBL_A scantime=0.2,size=8433,user=root,uid=1010,required_score=3.0,rhost=localhost,raddr=::1,rport=54673,mid=<5323541152335322929654419@lo.nbvc12345.xyz>,autolearn=no autolearn_force=no
Fri Mar  3 12:55:11 2017 [10093] info: prefork: child states: II

and here's a full snippet of it missing spam, because of no bayes filtering:

Fri Mar  3 13:01:31 2017 [10104] info: spamd: connection from localhost [::1]:56926 to port 783, fd 6
Fri Mar  3 13:01:31 2017 [10104] info: spamd: creating default_prefs: /root/.spamassassin/user_prefs
Fri Mar  3 13:01:31 2017 [10104] info: spamd: failed to create readable default_prefs: /root/.spamassassin/user_prefs
Fri Mar  3 13:01:31 2017 [10104] info: spamd: processing message <sie819-8bh73y10780523sdgw_ds7fid385303272d2g-8h723se@email.searchresultsnewinfo.com> for root:1010
Fri Mar  3 13:01:31 2017 [10104] info: spamd: clean message (1.3/3.0) for root:1010 in 0.3 seconds, 8104 bytes.
Fri Mar  3 13:01:31 2017 [10104] info: spamd: result: . 1 - RDNS_NONE,URIBL_BLOCKED scantime=0.3,size=8104,user=root,uid=1010,required_score=3.0,rhost=localhost,raddr=::1,rport=56926,mid=<sie819-8bh73y10780523sdgw_ds7fid385303272d2g-8h723se@email.searchresultsnewinfo.com>,autolearn=no autolearn_force=no
Fri Mar  3 13:01:31 2017 [10093] info: prefork: child states: II

Is the problem that the bayes database is in /root/.spamassassin and the child processes can't access it? Where should it be, or is it something else? At my limited knowledge's end on this. Any help appreciated.

Body:
The problem is related to spamd running as root and the spamd children (spamc) running under the user "spamd", with insufficient permissions to access the bayes database in /root/.spamassassin.

To have spamassassin properly look at the bayes database, it must be in a location accessible to the children, and I had to tell spamassassin where to find it by adding this line to local.cf

bayes_path /var/spamassassin/bayesdb/bayes

I then needed to create /var/spamassassin/bayesdb (not /var/spamassassin/bayesdb/bayes as the trailing "bayes" is the prefix for the filenames that will be in the bayesdb folder) and make user "spamd" the owner:

cd /var
chown -R spamd:some_group spamassassin

I then moved the existing bayes database files from /root/.spamassassin to /var/spamassassin/bayesdb, performed the same ownership operation as above on the files, and the bayes filtering started working properly.

I did not resolve the issue with the children attempting to create user_prefs in /root/.spamassassin, as it's the same issue with permissions, but doesn't seem to affect bayes working, which was all I was after.


来源: stackexchange

问:
multiple IN conditions in JPQL
How can I express the following SQL in JPQL:

```<code>select * from table where
( ( table.col1 , table.col2) in
   (col1val1, col2val1),
   (col1val2, col2val2),
   (col1val3, col2val3)
)
</code>```

BTW: The above is valid Oracle SQL syntax

答:
My JPQL is terrible, but how about something like:

```<code>select tableDto from TableDto tableDto
where (tableDto.col1 = col1val1 and tableDto.col2 = col2val1)
or (tableDto.col1 = col1val2 and tableDto.col2 = col2val2)
or (tableDto.col1 = col1val3 and tableDto.col2 = col2val3)
</code>```

It's not pretty.

ContentLicense: CC BY-SA 2.5

Title: multiple IN conditions in JPQL

Body:
How can I express the following SQL in JPQL:

select * from table where
( ( table.col1 , table.col2) in
   (col1val1, col2val1),
   (col1val2, col2val2),
   (col1val3, col2val3)
)

BTW: The above is valid Oracle SQL syntax

Body:
My JPQL is terrible, but how about something like:

select tableDto from TableDto tableDto
where (tableDto.col1 = col1val1 and tableDto.col2 = col2val1)
or (tableDto.col1 = col1val2 and tableDto.col2 = col2val2)
or (tableDto.col1 = col1val3 and tableDto.col2 = col2val3)

It's not pretty.


问:
How do I skip a txt file when iterating over a directory?
Alright, so I'm trying to write a simple shell script to check for updates or just update all packages, including homebrew itself. I am trying to echo the executable filenames into a txt file, and source the txt file at the end. The problem is that in my script, no matter what I do, it always includes the name of the text file in the text file it creates. How do I either skip over the text file, or remove the entire line containing pkg.txt? Keep in mind that it won't be as simple as just removing the last line, because the packages are listed alphabetically and if I ever install any package starting with a letter that's greater than p, it will delete that line instead.

Here's my code so far.

```<code>for FILE in $HOME/.brew/bin/* ; do
  TRIM=$(basename $FILE)
  if [ "$FILE" != "*.txt" ] ; then
    echo "brew upgrade \c" >>  pkg.txt ; echo $TRIM >> pkg.txt
  fi
done
</code>```

Not sure if it matters, but I'm currently running zsh in iTerm2.

答:
It fails because [ "$FILE" != "*.txt" ] is a literal string comparison.

Zsh supports [[ "$FILE" != *.txt ]] to match against a pattern (also supported by bash and ksh. For dash and sh, use @Barmar's suggestion).

Here it is in your code:

```<code>#!/usr/bin/zsh
for FILE in $HOME/.brew/bin/* ; do
  TRIM=$(basename $FILE)
  if [[ "$FILE" != *.txt ]] ; then
    echo "brew upgrade \c" >>  pkg.txt ; echo $TRIM >> pkg.txt
  fi
done
</code>```

ContentLicense: CC BY-SA 3.0

Body:
Alright, so I'm trying to write a simple shell script to check for updates or just update all packages, including homebrew itself. I am trying to echo the executable filenames into a txt file, and source the txt file at the end. The problem is that in my script, no matter what I do, it always includes the name of the text file in the text file it creates. How do I either skip over the text file, or remove the entire line containing pkg.txt? Keep in mind that it won't be as simple as just removing the last line, because the packages are listed alphabetically and if I ever install any package starting with a letter that's greater than p, it will delete that line instead.

Here's my code so far.

for FILE in $HOME/.brew/bin/* ; do
  TRIM=$(basename $FILE)
  if [ "$FILE" != "*.txt" ] ; then
    echo "brew upgrade \c" >>  pkg.txt ; echo $TRIM >> pkg.txt
  fi
done

Not sure if it matters, but I'm currently running zsh in iTerm2.

Body:
It fails because [ "$FILE" != "*.txt" ] is a literal string comparison.

Zsh supports [[ "$FILE" != *.txt ]] to match against a pattern (also supported by bash and ksh. For dash and sh, use @Barmar's suggestion).

Here it is in your code:

#!/usr/bin/zsh
for FILE in $HOME/.brew/bin/* ; do
  TRIM=$(basename $FILE)
  if [[ "$FILE" != *.txt ]] ; then
    echo "brew upgrade \c" >>  pkg.txt ; echo $TRIM >> pkg.txt
  fi
done


问:
Discover that a filled-in grid has a circle; fill in the area

Hi, I'm currently in the middle of a project where a new grid is added on to a chain of blocks on the grid every timestep.  How would I be able to detect that a circle has been made in the grid?  Given that all I have are the coordinates (x,y) and the color of each cell.  By "circle" I mean an area that is sealed off, as shown in the picture.

Thanks in advance!  By the way, I'm not asking how to click on a cell and apply the flood-fill algorithm.

The aftermath of the algorithm should produce this:

答:
You need to split all of your white (unfilled) squares into sets of squares adjacent to each other. Start with any white square, add all of its unfilled adjacent squares to the set, and keep doing it until you've included all of the squares.

Once you have those sets, you will have a "circle" (as you named it) if there are non-empty sets that do not contain any border squares. Then to fill these sets you just change the color of each member to blue.

If you have the sets from the previous step, when you add another brick you just need to consider the set that included the affected square to see if it has been split into two sets and whether either of these new sets may be a "circle".


问:
How to store API data (array) into database with php
I am having error trying to store data into a database. I need help on how best to fix this my code, so that my array content can be stored in a my database. When I tried to echo the content, it worked not to store the data in my database is the problem.
Here is my code:

```<code>foreach ($data['players'] as $myp) {
//    echo $myp["name"]."<br>";
    $name = $myp['name'];
    $posi = $myp['position'];
    $nation = $myp['nationality'];
    $market = $myp['marketValue'];
}

//insert into mysql table
mysql_select_db($db, $conn); //database and connection

$date = date('Y-m-d H:m:s'); //date stamp formatting
//sql query that insert the user info into the database
$sql =  "INSERT INTO staffdb ( Name, Position, Nationality, Market, Created)
        VALUES($name, $posi, $nation, $market, $date)";
echo $name . "<br>";
//if the connection is sucessful, display regards message
if (mysql_query($sql, $conn)) {
    echo "Thank you <br/>";
} else {   //if the connection is not established
    die('Error: ' . mysql_error());
}
</code>```

Here is the error I was getting:
Error: You have an error in your SQL syntax; check the manual that corresponds to your MariaDB server version for the right syntax to use near 'Costa, Centre Forward, Spain, 45,000,000 €, 2017-03-31 23:03:04)' at line 2

In the error it printed the right value which i would like to be instead stored in the database.

Kindly correct my SQL part so that I can get my foreach data into my database.

Thanks alot!

答:
Just wrap values in query into quotes:

$sql = "INSERT INTO staffdb ( `Name`, `Position`, `Nationality`, `Market`, `Created`)
      VALUES('$name', '$posi', '$nation', '$market', '$date')";
```

Very recommend, how it's possible, move into new mysqli or PDO extension.

Body:
I am having error trying to store data into a database. I need help on how best to fix this my code, so that my array content can be stored in a my database. When I tried to echo the content, it worked not to store the data in my database is the problem.
Here is my code:

foreach ($data['players'] as $myp) {
//    echo $myp["name"]."
";
    $name = $myp['name'];
    $posi = $myp['position'];
    $nation = $myp['nationality'];
    $market = $myp['marketValue'];
}

//insert into mysql table
mysql_select_db($db, $conn); //database and connection

$date = date('Y-m-d H:m:s'); //date stamp formatting
//sql query that insert the user info into the database
$sql =  "INSERT INTO staffdb ( Name, Position, Nationality, Market, Created)
        VALUES($name, $posi, $nation, $market, $date)";
echo $name . "
";
//if the connection is sucessful, display regards message
if (mysql_query($sql, $conn)) {
    echo "Thank you
";
} else {   //if the connection is not established
    die('Error: ' . mysql_error());
}

Here is the error I was getting:
Error: You have an error in your SQL syntax; check the manual that corresponds to your MariaDB server version for the right syntax to use near 'Costa, Centre Forward, Spain, 45,000,000 €, 2017-03-31 23:03:04)' at line 2

In the error it printed the right value which i would like to be instead stored in the database.

Kindly correct my SQL part so that I can get my foreach data into my database.

Thanks alot!

Body:
Just wrap values in query into quotes:

$sql = "INSERT INTO staffdb ( `Name`, `Position`, `Nationality`, `Market`, `Created`)
      VALUES('$name', '$posi', '$nation', '$market', '$date')";

Very recommend, how it's possible, move into new mysqli or PDO extension.


问:
H2O Spark streaming 2.1 distribution
I have been intermittently getting distribution error when running a sample IRIS model in sparkling water.

Sparkling water: 2.1
Spark streaming kafka - 0.10.0.0
Running locally using spark submit - Only master

```<code>DistributedException from xxx:54321, caused by java.lang.NullPointerException
            at water.MRTask.getResult(MRTask.java:478)
            at water.MRTask.getResult(MRTask.java:486)
            at water.MRTask.doAll(MRTask.java:390)
            at water.MRTask.doAll(MRTask.java:396)
            at hex.Model.predictScoreImpl(Model.java:1103)
            at hex.Model.score(Model.java:964)
            at hex.Model.score(Model.java:932)
    ....
    Caused by: java.lang.NullPointerException
        at water.fvec.Vec.chunkForChunkIdx(Vec.java:1014)
        at water.fvec.CategoricalWrappedVec.chunkForChunkIdx(CategoricalWrappedVec.java:49)
        at water.MRTask.compute2(MRTask.java:618)
        at water.MRTask.compute2(MRTask.java:591)
        at water.MRTask.compute2(MRTask.java:591)
        at water.H2O$H2OCountedCompleter.compute1(H2O.java:1223)
        at hex.Model$BigScore$Icer.compute1(Model$BigScore$Icer.java)
        at water.H2O$H2OCountedCompleter.compute(H2O.java:1219)
        at jsr166y.CountedCompleter.exec(CountedCompleter.java:468)
        at jsr166y.ForkJoinTask.doExec(ForkJoinTask.java:263)
        at jsr166y.ForkJoinPool$WorkQueue.runTask(ForkJoinPool.java:974)
        at jsr166y.ForkJoinPool.runWorker(ForkJoinPool.java:1477)
        at jsr166y.ForkJoinWorkerThread.run(ForkJoinWorkerThread.java:104)
</code>```

答:
So the problem is that H2O model is not seeing the data and causing NPE. The main reasons could be that h2o dataframe is deleted either at the time of prediction or just before prediction call.

We are interested to know how you do process mini batch data i.e. how mini batch is transformed into h2o data frame.

It will also help if you explain "how h2o model is being called to make prediction".

Title: H2O Spark streaming 2.1 distribution

Body:
I have been intermittently getting distribution error when running a sample IRIS model in sparkling water.

Sparkling water: 2.1
Spark streaming kafka - 0.10.0.0
Running locally using spark submit - Only master

DistributedException from xxx:54321, caused by java.lang.NullPointerException
            at water.MRTask.getResult(MRTask.java:478)
            at water.MRTask.getResult(MRTask.java:486)
            at water.MRTask.doAll(MRTask.java:390)
            at water.MRTask.doAll(MRTask.java:396)
            at hex.Model.predictScoreImpl(Model.java:1103)
            at hex.Model.score(Model.java:964)
            at hex.Model.score(Model.java:932)
    ....
    Caused by: java.lang.NullPointerException
        at water.fvec.Vec.chunkForChunkIdx(Vec.java:1014)
        at water.fvec.CategoricalWrappedVec.chunkForChunkIdx(CategoricalWrappedVec.java:49)
        at water.MRTask.compute2(MRTask.java:618)
        at water.MRTask.compute2(MRTask.java:591)
        at water.MRTask.compute2(MRTask.java:591)
        at water.H2O$H2OCountedCompleter.compute1(H2O.java:1223)
        at hex.Model$BigScore$Icer.compute1(Model$BigScore$Icer.java)
        at water.H2O$H2OCountedCompleter.compute(H2O.java:1219)
        at jsr166y.CountedCompleter.exec(CountedCompleter.java:468)
        at jsr166y.ForkJoinTask.doExec(ForkJoinTask.java:263)
        at jsr166y.ForkJoinPool$WorkQueue.runTask(ForkJoinPool.java:974)
        at jsr166y.ForkJoinPool.runWorker(ForkJoinPool.java:1477)
        at jsr166y.ForkJoinWorkerThread.run(ForkJoinWorkerThread.java:104)


问:
Kotlin - Function's Invoke Operator Overloading
I am currently studying Kotlin - Operator Overloading

I am trying to understand (with an example) how does operator overloading work for a function's invoke() function

The pre-test

Kotlin's Extension Functions

```<code>fun exampleOfExtensionFunction() {
    fun Int.randomize(): Int {
        return Random(this.toLong()).nextInt()
    }

    val randomizedFive = 5.randomize()
    println("$randomizedFive")
}
</code>```

Prints :

-1157408321

In Kotlin, functions can be declared as variables with types

```<code>fun exampleOfFunctionType() {
    val printNumber: (number: Int) -> Unit
    printNumber = { number ->
        println("[$number = ${number.toString(16).toUpperCase()} = ${number.toString(2)}]")
    }

    printNumber(1023)
}
</code>```

Prints :

[1023 = 3FF = 1111111111]

Kotlin allows operator overloading with both extension and member functions

```<code>fun exampleOfOperatorOverloadingUsingExtensionFunction() {
    class MyType() {
        val strings: ArrayList<String> = ArrayList<String>()
        override fun toString(): String {
            val joiner: StringJoiner = StringJoiner(" , ", "{ ", " }")
            for (string in strings) {
                joiner.add("\"$string\"")
            }
            return joiner.toString()
        }
    }

    operator fun MyType.contains(stringToCheck: String): Boolean {
        for (stringElement in strings) {
            if (stringElement == stringToCheck) return true
        }
        return false
    }

    val myType = MyType()
    myType.strings.add("one")
    myType.strings.add("two")
    myType.strings.add("three")
    println("$myType")
    println("(myType.contains(\"four\")) = ${myType.contains("four")} , (\"three\" in myType) = ${"three" in myType}")
}
</code>```

Prints :

{ "one" , "two" , "three" }

  (myType.contains("four")) = false , ("three" in myType) = true

Test Attempt

Based on the above. I tried to create an example of a function's invoke() operator overloading using the type (Boolean, Boolean, Boolean) -> Boolean as a receiver type for an extension function invoke(flag1: Boolean, flag2: Boolean, flag3: Boolean). This however did not work as expected.

```<code>    fun attemptFunctionInvokeOperatorOverloading() {
        operator fun ((Boolean, Boolean, Boolean) -> Boolean).invoke(flag1: Boolean, flag2: Boolean, flag3: Boolean): Boolean {
            println("Overloaded invoke operator")
            return flag1 && flag2 && flag3
        }

        var func1: ((Boolean, Boolean, Boolean) -> Boolean) = { flag1, flag2, flag3 ->
            println("func1 body")
            flag1 && flag2 && flag3
        }

        fun func2(flag1: Boolean, flag2: Boolean, flag3: Boolean): Boolean {
            println("func2 body")
            return flag1 && flag2 && flag3
        }

        func1(true, true, false)
        func2(true, true, true)
    }
</code>```

Prints :

func1 body

  func2 body

Expected :

Overloaded invoke operator

  Overloaded invoke operator

Another question :

What exactly is this? (If it isn't operator overloading)

```<code>        operator fun ((Boolean, Boolean, Boolean) -> Boolean).invoke(flag1: Boolean, flag2: Boolean, flag3: Boolean): Boolean {
            println("Overloaded invoke operator")
            return flag1 && flag2 && flag3
        }
</code>```

答:
Your issue has to to with resolution precedence. According to the Kotlin docs:

If a class has a member function, and an extension function is defined which has the same receiver type, the same name and is applicable to given arguments, the member always wins.

So your operator fun ((Boolean, Boolean, Boolean) -> Boolean).invoke(...) extension function is never called because the member invoke takes precedence.

Another Answer

It is indeed operator overloading, but through an extension. Again, since (Boolean, Boolean, Boolean) -> Boolean already has a fun invoke(Boolean, Boolean, Boolean): Boolean defined, your extension loses.

Body:
I am currently studying Kotlin - Operator Overloading

I am trying to understand (with an example) how does operator overloading work for a function's invoke() function

The pre-test

Kotlin's Extension Functions

fun exampleOfExtensionFunction() {
    fun Int.randomize(): Int {
        return Random(this.toLong()).nextInt()
    }

    val randomizedFive = 5.randomize()
    println("$randomizedFive")
}

Prints :

-1157408321

In Kotlin, functions can be declared as variables with types

fun exampleOfFunctionType() {
    val printNumber: (number: Int) -> Unit
    printNumber = { number ->
        println("[$number = ${number.toString(16).toUpperCase()} = ${number.toString(2)}]")
    }

    printNumber(1023)
}

Prints :

[1023 = 3FF = 1111111111]

Kotlin allows operator overloading with both extension and member functions

fun exampleOfOperatorOverloadingUsingExtensionFunction() {
    class MyType() {
        val strings: ArrayList<String> = ArrayList<String>()
        override fun toString(): String {
            val joiner: StringJoiner = StringJoiner(" , ", "{ ", " }")
            for (string in strings) {
                joiner.add("\"$string\"")
            }
            return joiner.toString()
        }
    }

    operator fun MyType.contains(stringToCheck: String): Boolean {
        for (stringElement in strings) {
            if (stringElement == stringToCheck) return true
        }
        return false
    }

    val myType = MyType()
    myType.strings.add("one")
    myType.strings.add("two")
    myType.strings.add("three")
    println("$myType")
    println("(myType.contains(\"four\")) = ${myType.contains("four")} , (\"three\" in myType) = ${"three" in myType}")
}

Prints :

{ "one" , "two" , "three" }

  (myType.contains("four")) = false , ("three" in myType) = true

Test Attempt

Based on the above. I tried to create an example of a function's invoke() operator overloading using the type (Boolean, Boolean, Boolean) -> Boolean as a receiver type for an extension function invoke(flag1: Boolean, flag2: Boolean, flag3: Boolean). This however did not work as expected.

    fun attemptFunctionInvokeOperatorOverloading() {
        operator fun ((Boolean, Boolean, Boolean) -> Boolean).invoke(flag1: Boolean, flag2: Boolean, flag3: Boolean): Boolean {
            println("Overloaded invoke operator")
            return flag1 && flag2 && flag3
        }

        var func1: ((Boolean, Boolean, Boolean) -> Boolean) = { flag1, flag2, flag3 ->
            println("func1 body")
            flag1 && flag2 && flag3
        }

        fun func2(flag1: Boolean, flag2: Boolean, flag3: Boolean): Boolean {
            println("func2 body")
            return flag1 && flag2 && flag3
        }

        func1(true, true, false)
        func2(true, true, true)
    }

Prints :

func1 body

  func2 body

Expected :

Overloaded invoke operator

  Overloaded invoke operator

Another question :

What exactly is this? (If it isn't operator overloading)

        operator fun ((Boolean, Boolean, Boolean) -> Boolean).invoke(flag1: Boolean, flag2: Boolean, flag3: Boolean): Boolean {
            println("Overloaded invoke operator")
            return flag1 && flag2 && flag3
        }


问:
Reading integers from file into array?
Here is an attempt to read 10 white-space-separated integer values from a file into an array:

```<code>subroutine ReadFileIntoArray (filename, int_array)
    implicit none

    character(len = *), intent (in) :: filename
    integer, dimension(:), intent(in out) :: int_array

    integer :: current_index

    open (1, file = filename, status = 'old')

    do current_index = 1, 10, 1
        read(1, *) int_array(current_index)
    end do

    close (1)
end subroutine ReadFileIntoArray

! ---------------------------------------------------------------------- !

program ReadFileCalculateAverage
    implicit none

    integer, dimension(10) :: int_array
    character (len = 9) :: filename = 'makrs.txt'

    call ReadFileIntoArray(filename, int_array) ! <--- error line

end program ReadFileCalculateAverage
</code>```

The error I'm getting (using Code::Blocks 16.01 on Windows 10) is:

```<code>Error: explicit interface required for 'ReadFileIntoArray' : assumed-shape argument
</code>```

Having in mind my limited knowledge of Fortran, what is the way to correct the above code? Are there any other significant (still unobserved) errors that I should correct?

答:
You will eventually want a unit number other than 1 for the open and the read. Maybe 21 or use NEW UNIT.

For the FileName I usually use LEN=256 everywhere, and then on the open use

```<code>INTEGER :: LUN
...
OPEN(NEWUNIT=LUN, FileName(1:LEN_TRIM(FileName)) )
</code>```

Another option is to have FileName declared in a module with the subroutine, and don't pass it

```<code>MODULE AA
IMPLICIT NONE
CHARACTER(LEN=256), PUBLIC :: FileName
CONTAINS
subroutine readarray(array)
...
ENDMODULE AA
</code>```

Or give something for the *

```<code>SUBROUTINE readarray(FileName,array,lenF)
iNTEGER,INTENT(IN   )           :: LenF
CHARACTER(LEN=LenF), INTENT(IN) :: FileName
</code>```

Title: Reading integers from file into array?

Body:
Here is an attempt to read 10 white-space-separated integer values from a file into an array:

subroutine ReadFileIntoArray (filename, int_array)
    implicit none

    character(len = *), intent (in) :: filename
    integer, dimension(:), intent(in out) :: int_array

    integer :: current_index

    open (1, file = filename, status = 'old')

    do current_index = 1, 10, 1
        read(1, *) int_array(current_index)
    end do

    close (1)
end subroutine ReadFileIntoArray

! ---------------------------------------------------------------------- !

program ReadFileCalculateAverage
    implicit none

    integer, dimension(10) :: int_array
    character (len = 9) :: filename = 'makrs.txt'

    call ReadFileIntoArray(filename, int_array) ! <--- error line

end program ReadFileCalculateAverage

The error I'm getting (using Code::Blocks 16.01 on Windows 10) is:

Error: explicit interface required for 'ReadFileIntoArray' : assumed-shape argument

Having in mind my limited knowledge of Fortran, what is the way to correct the above code? Are there any other significant (still unobserved) errors that I should correct?

Body:
You will eventually want a unit number other than 1 for the open and the read. Maybe 21 or use NEW UNIT.

For the FileName I usually use LEN=256 everywhere, and then on the open use

INTEGER :: LUN
...
OPEN(NEWUNIT=LUN, FileName(1:LEN_TRIM(FileName)) )

Another option is to have FileName declared in a module with the subroutine, and don't pass it

MODULE AA
IMPLICIT NONE
CHARACTER(LEN=256), PUBLIC :: FileName
CONTAINS
subroutine readarray(array)
...
ENDMODULE AA

Or give something for the *

SUBROUTINE readarray(FileName,array,lenF)
iNTEGER,INTENT(IN   )           :: LenF
CHARACTER(LEN=LenF), INTENT(IN) :: FileName


问:
Where to get HELLO WORLD for .net with M2mQTT
Start working on MQTT with .net environment, as a novice stuck on some issues like failed to communicate between publisher and SUBSCRIBER. From eclipse.org I get the bellow syntax

```<code>// SUBSCRIBER
...

// create client instance
MqttClient client = new MqttClient(IPAddress.Parse(MQTT_BROKER_ADDRESS));

// register to message received
client.MqttMsgPublishReceived += client_MqttMsgPublishReceived;

string clientId = Guid.NewGuid().ToString();
client.Connect(clientId);

// subscribe to the topic "/home/temperature" with QoS 2
client.Subscribe(new string[] { "/home/temperature" }, new byte[] { MqttMsgBase.QOS_LEVEL_EXACTLY_ONCE });

...

static void client_MqttMsgPublishReceived(object sender, MqttMsgPublishEventArgs e)
{
// handle message received
}

// PUBLISHER
...

// create client instance
MqttClient client = new MqttClient(IPAddress.Parse(MQTT_BROKER_ADDRESS));

string clientId = Guid.NewGuid().ToString();
client.Connect(clientId);

string strValue = Convert.ToString(value);

// publish a message on "/home/temperature" topic with QoS 2
client.Publish("/home/temperature", Encoding.UTF8.GetBytes(strValue), MqttMsgBase.QOS_LEVEL_EXACTLY_ONCE);

...
</code>```

In the above syntax how I get the MQTT_BROKER_ADDRESS ,  so far I understood from other document like hivemq  I need to deploy it. Is there any broker available to use it? I need a HELLO WORLD type project on MQTT for .net.
Which have publisher,subscriber and broker.

答:
Just replace

```<code>MqttClient client = new MqttClient(IPAddress.Parse(MQTT_BROKER_ADDRESS));
</code>```

with

```<code>MqttClient client = new MqttClient("broker.mqtt-dashboard.com");
</code>```

where broker.mqtt-dashboard.com is the address of an MQTT broker provided by HiveMQ for testing purposes.

Body:
Start working on MQTT with .net environment, as a novice stuck on some issues like failed to communicate between publisher and SUBSCRIBER. From eclipse.org I get the bellow syntax

// SUBSCRIBER
...

// create client instance
MqttClient client = new MqttClient(IPAddress.Parse(MQTT_BROKER_ADDRESS));

// register to message received
client.MqttMsgPublishReceived += client_MqttMsgPublishReceived;

string clientId = Guid.NewGuid().ToString();
client.Connect(clientId);

// subscribe to the topic "/home/temperature" with QoS 2
client.Subscribe(new string[] { "/home/temperature" }, new byte[] { MqttMsgBase.QOS_LEVEL_EXACTLY_ONCE });

...

static void client_MqttMsgPublishReceived(object sender, MqttMsgPublishEventArgs e)
{
// handle message received
}

// PUBLISHER
...

// create client instance
MqttClient client = new MqttClient(IPAddress.Parse(MQTT_BROKER_ADDRESS));

string clientId = Guid.NewGuid().ToString();
client.Connect(clientId);

string strValue = Convert.ToString(value);

// publish a message on "/home/temperature" topic with QoS 2
client.Publish("/home/temperature", Encoding.UTF8.GetBytes(strValue), MqttMsgBase.QOS_LEVEL_EXACTLY_ONCE);

...

In the above syntax how I get the MQTT_BROKER_ADDRESS ,  so far I understood from other document like hivemq  I need to deploy it. Is there any broker available to use it? I need a HELLO WORLD type project on MQTT for .net.
Which have publisher,subscriber and broker.

Body:
Just replace

MqttClient client = new MqttClient(IPAddress.Parse(MQTT_BROKER_ADDRESS));

with

MqttClient client = new MqttClient("broker.mqtt-dashboard.com");

where broker.mqtt-dashboard.com is the address of an MQTT broker provided by HiveMQ for testing purposes.


问:
Efficiently handling python processes
So for my project I have to get a list of genes and clean it from synonyms ex. gene A might also be known as AA, so if in my original list there is AA and A I have to delete one of the two.

The list of genes is provided by the user, and I read the synonyms from a text file.

Both are stored in dictionaries.

The list is huuuuuge (Trump joke) and I will have to call this function, many times in my pipeline. So my question is: Can I multiprocess this to make it faster?

My initial approach was as follows:

```<code>for g in genes:
    process = multiprocessing.Process(target = fixReoccurences, args =  (g, genes, synonyms, replaced, ))
    my_processes.append(process)
    process.start()

# Wait for *ALL* the processes to finish.
for p in my_processes:
    p.join()
</code>```

But this approach quickly failed due to the fact that my script demanded 400 processes, that all of them are running a loop for ~40.000 iterations. It literally, froze my laptop.

So how can I tackle this issue by efficiently utilizing the multiple cores of my CPU to handle the processes?

答:
Use Pool.map.

You can have a function which takes a gene and returns it or None if it should be filtered:

```<code>def filter_gene_if_synonym(gene, synonyms):
    return None if gene in synonymns else gene
</code>```

You can bind an argument of a function using partial:

```<code>from functools import partial

filter_gene = partial(filter_gene_if_synonym,
                      synonyms=synonyms)
</code>```

Then the function can be called just with a gene.

You can map a function to a sequence of data using a pool of processes:

```<code>pool = Pool(processes=4)
filtered_genes = [gene for gene in pool.map(filter_gene, genes)
                  if gene is not None]
</code>```

The map function can also pass chunks of data to an appropriate function:

```<code>def filter_genes_of_synonyms(genes, synonyms):
    return [gene for gene in genes
            if gene not in synonymns]

filter_genes = partial(filter_genes, synonyms=synonyms)
</code>```

and:

```<code>filtered_chunks = pool.map(filter_genes, genes, chunksize=50)
filtered_genes = [gene for chunk in filtered_chunks
                  for gene in chunk]
</code>```

Title: Efficiently handling python processes

Body:
So for my project I have to get a list of genes and clean it from synonyms ex. gene A might also be known as AA, so if in my original list there is AA and A I have to delete one of the two.

The list of genes is provided by the user, and I read the synonyms from a text file.

Both are stored in dictionaries.

The list is huuuuuge (Trump joke) and I will have to call this function, many times in my pipeline. So my question is: Can I multiprocess this to make it faster?

My initial approach was as follows:

for g in genes:
    process = multiprocessing.Process(target = fixReoccurences, args =  (g, genes, synonyms, replaced, ))
    my_processes.append(process)
    process.start()

# Wait for *ALL* the processes to finish.
for p in my_processes:
    p.join()

But this approach quickly failed due to the fact that my script demanded 400 processes, that all of them are running a loop for ~40.000 iterations. It literally, froze my laptop.

So how can I tackle this issue by efficiently utilizing the multiple cores of my CPU to handle the processes?

Body:
Use Pool.map.

You can have a function which takes a gene and returns it or None if it should be filtered:

def filter_gene_if_synonym(gene, synonyms):
    return None if gene in synonymns else gene

You can bind an argument of a function using partial:

from functools import partial

filter_gene = partial(filter_gene_if_synonym,
                      synonyms=synonyms)

Then the function can be called just with a gene.

You can map a function to a sequence of data using a pool of processes:

pool = Pool(processes=4)
filtered_genes = [gene for gene in pool.map(filter_gene, genes)
                  if gene is not None]

The map function can also pass chunks of data to an appropriate function:

def filter_genes_of_synonyms(genes, synonyms):
    return [gene for gene in genes
            if gene not in synonymns]

filter_genes = partial(filter_genes, synonyms=synonyms)

and:

filtered_chunks = pool.map(filter_genes, genes, chunksize=50)
filtered_genes = [gene for chunk in filtered_chunks
                  for gene in chunk]


问:
Why does an equality check in Ruby behave this way with an OR expression?
I came across something like this in some specs at work today. A service was checking if a param was either "true" as a String or true as a TrueClass. It looked legit to me, but I found that it only evaluated to true when the supplied param value was the same as the first element in the OR.

A simplified example below:

5 == (5 || 6) evaluates to true

5 == (6 || 5) evaluates to false

Why?

答:
Because (6 || 5) returns 6 (|| returns the first true condition), not 5:

```<code>[2] pry(main)> (6 || 5)
# => 6
</code>```

So 5 == (6 || 5) is just the same as 5 == 6 which is, of course, false.

Body:
Because (6 || 5) returns 6 (|| returns the first true condition), not 5:

[2] pry(main)> (6 || 5)
# => 6

So 5 == (6 || 5) is just the same as 5 == 6 which is, of course, false.


问:
Conversion pdf document which includes tables to csv file using python or any other langaue
I tried to convert pdf document (includes tables) into csv file. Unfortunately I failed. I have used the following approaches:

Used pdfminer first converted the pdf to text but structure of text file was not same as of pdf file .

Used pypdf2 first converted the pdf to text but structure of text file was not same as of pdf file.

Used pdftotext first converted the pdf to text but structure of text file was not same as of pdf file.

Used slate first converted the pdf to text but structure of text file was not same as of pdf file.

Kindly tell me the appropriate way to convert pdf to csv file. Some people have recommended me to parse the document to xml file and then to csv file. Even then I did not got the solution.

The PDF document looks as follows:

Are there any better tools which can convert pdf document (includes complex tables) to csv file?

Solutions in Python language would be highly appreciated.

答: Might be worth giving PDFTables a try, they've got a Python library/API for PDF to CSV conversions, and you get free pages to try it out.</p>


问:
JSON Syntax: Transmitting an array
A valid JSON Syntax is something of the kind:

```<code>{
  "username": "admin",
  "password": "123"
}
</code>```

But what if I want to transmit an array of 'users' (given the example), instead of a single 'user' ?

Is the code below Valid JSON, according to the specifications?

```<code>[{
  "username": "admin",
  "password": "123"
}, {
  "username": "bbvb",
  "password": "sdfsdf"
}, {
  "username": "asd",
  "password": "222"
}]
</code>```

And if not, what is the best way to transmit an array of values across with JSON? (And with 'best way', I mean syntactically)

答:
What you wrote up there is already correct :)</p>

```<code>[{ "username" : "admin", "password" : "123" }, { "username" : "bbvb", "password" : "sdfsdf" }, { "username" : "asd", "password" : "222" }]
</code>```

OwnerDisplayName: Dreas Grech

Title: JSON Syntax: Transmitting an array

Body:
A valid JSON Syntax is something of the kind:

{
  "username": "admin",
  "password": "123"
}

But what if I want to transmit an array of 'users' (given the example), instead of a single 'user' ?

Is the code below Valid JSON, according to the specifications?

[{
  "username": "admin",
  "password": "123"
}, {
  "username": "bbvb",
  "password": "sdfsdf"
}, {
  "username": "asd",
  "password": "222"
}]

And if not, what is the best way to transmit an array of values across with JSON? (And with 'best way', I mean syntactically)

Body:
What you wrote up there is already correct :)

[{ "username" : "admin", "password" : "123" }, { "username" : "bbvb", "password" : "sdfsdf" }, { "username" : "asd", "password" : "222" }]

OwnerDisplayName: Sikachu


问:
sorting and load balancing
I read about parallel quicksort ( but no load balancing ).
who can give good algorithm for using on 2, 4, 8 cores?</p>

答:
Algorithms doesnt depend on hardware.

You can implement your program to use multiple core cpus, ie: multi threading, however, quick sort is quick sort. the algorithms (idea) is same.

What you can do is, for a dual core CPU, once you divide the input to two, you can assign each partition to one core and continue in the same way. at the end you can merge the results. This is becoming like a merge sort though, except that you use a pivot.

Title: sorting and load balancing


问:
Appending D3.js Elements to Shadow DOM of Polymer Element
I'm working on a Polymer (v1) project and one of my custom polymer elements needs to contain a D3 (v4) chart. D3 seems to operate pretty heavily on appending to the DOM. Unfortunately, Polymer seems pretty strict about how DOM manipulation is performed.

I have created a very simple version of the D3 chart I want to implement:

index.html

```<code><!DOCTYPE html>
<html>
<head>
    <script src="https://d3js.org/d3.v4.min.js"></script>
    <style>
        .bar {
            fill: #0198E1;
        }
    </style>
</head>
<body>

<svg></svg>

<script>
var data = [100, 120, 130, 110, 150, 90];

const CHART_WIDTH = 126;
const CHART_HEIGHT = 160;

svg = d3.select('svg')
    .attr("width", CHART_WIDTH)
    .attr("height", CHART_HEIGHT);

svg.selectAll('rect')
    .data(data).enter().append('rect')
        .attr("x", function(d, i) {return i * 21})
        .attr("y", function(d) {return CHART_HEIGHT - d})
        .attr("height", function(d) {return d})
        .attr("width", 20)
        .attr("class", "bar");
</script>
</body>
</html>
</code>```

I have attempted two solutions with the following files.

index.html

```<code><!DOCTYPE html>
<html>
<head>
    <link rel="import" href="../bower_components/polymer/polymer.html">
    <link rel="import" href="./d3-chart.html">
</head>
<body>
    <d3-chart></d3-chart>
</body>
</html>
</code>```

d3-lib.html

```<code><script src="https://d3js.org/d3.v4.min.js"></script>
</code>```

Attempted Solution 1

Use a combination of D3 and Polymer to select the target svg element and then perform d3 appends.

d3-chart.html

```<code><link rel="import" href="../bower_components/polymer/polymer.html">
<link rel="import" href="./d3-lib.html">

<dom-module id="d3-chart">
    <template>
        <style>
           .bar {
               fill: #0198E1;
           }
        </style>

        <svg id="svg"></svg>
    </template>

    <script>
        Polymer({
            is: 'd3-chart',
            properties: {
                data: {
                    Type: Array,
                    value: [100, 120, 130, 110, 150, 90]
                }
            },
            ready: function() {
                const CHART_WIDTH = 126;
                const CHART_HEIGHT = 160;

                var svg = d3.select(this.$.svg)
                    .attr("width", CHART_WIDTH)
                    .attr("height", CHART_HEIGHT);

                svg.selectAll('rect')
                    .data(this.data).enter().append('rect')
                        .attr("x", function(d, i) {return i * 21})
                        .attr("y", function(d) {return CHART_HEIGHT - d})
                        .attr("height", function(d) {return d})
                        .attr("width", 20)
                        .attr("class", "bar");
            }
        });
    </script>
</dom-module>
</code>```

This successfully displays the chart but the css style doesn't apply. I assume this is because Polymer doesn't 'know' about the new elements that have been appended.

Attempted Solution 2

Use D3 to select a new svg element (not in the DOM), perform D3 appends on the element, and use Polymer to append it to the DOM.

d3-chart.html

```<code><link rel="import" href="../bower_components/polymer/polymer.html">
<link rel="import" href="./d3-lib.html">

<dom-module id="d3-chart">
    <template>
        <style>
           .bar {
               fill: #0198E1;
           }
        </style>

    </template>

    <script>
        Polymer({
            is: 'd3-chart',
            properties: {
                data: {
                    Type: Array,
                    value: [100, 120, 130, 110, 150, 90]
                }
            },
            ready: function() {
                const CHART_WIDTH = 126;
                const CHART_HEIGHT = 160;

                var newSvgElement = document.createElement("svg");

                var svg = d3.select(newSvgElement)
                    .attr("width", CHART_WIDTH)
                    .attr("height", CHART_HEIGHT);

                svg.selectAll('rect')
                    .data(this.data).enter().append('rect')
                        .attr("x", function(d, i) {return i * 21})
                        .attr("y", function(d) {return CHART_HEIGHT - d})
                        .attr("height", function(d) {return d})
                        .attr("width", 20)
                        .attr("class", "bar");

                Polymer.dom(this.root).appendChild(newSvgElement);
            }
        });
    </script>
</dom-module>
</code>```

This code successfully appends all elements to the DOM but nothing is displayed.

What is the proper way to integrate Polymer with D3?

答:
I found a solution. I just had to add the following line to the beginning of the ready function in 'Attempted Solution 1'.

```<code>this.scopeSubtree(this.$.svg, true);
</code>```

For more information:
Why is my SVG rendered by D3 inside a Polymer component unstyled?

Body:
I'm working on a Polymer (v1) project and one of my custom polymer elements needs to contain a D3 (v4) chart. D3 seems to operate pretty heavily on appending to the DOM. Unfortunately, Polymer seems pretty strict about how DOM manipulation is performed.

I have created a very simple version of the D3 chart I want to implement:

index.html

<!DOCTYPE html>

<svg></svg>

I have attempted two solutions with the following files.

index.html

<!DOCTYPE html>

    <link rel="import" href="../bower_components/polymer/polymer.html">
    <link rel="import" href="./d3-chart.html">

    <d3-chart></d3-chart>

d3-lib.html

Attempted Solution 1

Use a combination of D3 and Polymer to select the target svg element and then perform d3 appends.

d3-chart.html

<link rel="import" href="../bower_components/polymer/polymer.html">
<link rel="import" href="./d3-lib.html">

<dom-module id="d3-chart">
    <template>

        <svg id="svg"></svg>
    </template>

</dom-module>

This successfully displays the chart but the css style doesn't apply. I assume this is because Polymer doesn't 'know' about the new elements that have been appended.

Attempted Solution 2

Use D3 to select a new svg element (not in the DOM), perform D3 appends on the element, and use Polymer to append it to the DOM.

d3-chart.html

<link rel="import" href="../bower_components/polymer/polymer.html">
<link rel="import" href="./d3-lib.html">

<dom-module id="d3-chart">
    <template>

    </template>

</dom-module>

This code successfully appends all elements to the DOM but nothing is displayed.

What is the proper way to integrate Polymer with D3?

Body:
I found a solution. I just had to add the following line to the beginning of the ready function in 'Attempted Solution 1'.

this.scopeSubtree(this.$.svg, true);

For more information:
Why is my SVG rendered by D3 inside a Polymer component unstyled?


问:
RESTful response code for bad preexisting data?
I have a case where sometimes the data in our database is insufficient to process a request (ie, we need an account number or something that hasn't been populated).

If the user's request contained invalid syntax, it'd be a 400.
If the database were down, or a service were failing, it'd be a 500, 502, or 503.

I'm considering 422, which basically means "the request was not malformed, but the semantics of your request have led to an error". The issue here is that it's not something inherent to the request itself, but rather to the state of our pre-existing data.

答:
I can see why you would use 422 and agree with that.

However, I was wondering if there is a graceful way to still accomplish the request without the data? Maybe the response takes place but the available features etc are degraded.
If not then can you prevent the feature from being exposed until the required data would be available?  Ie. the person is logged in and has a valid session ID for example.


问:
Limit Google Maps Autocomplete to European boundaries
I am using basic Google Maps autocomplete:

```<code>    function initAutocomplete() {
        autocomplete = new google.maps.places.Autocomplete(
                (document.getElementById('autocomplete_1')),
                {types: ['(cities)']});
        autocomplete.addListener('place_changed', fillInAddress);
    }
</code>```

It works totally fine, but I want to LIMIT the RESULTS to only European places. I could do it with the component Region filter but it limits me to 5 countries. Europe has 20+ countries. How to limit?

Edit: European including the UK :)

答:
Here is a wild guess I can do using the documentation :

function initialize() {
    var options = {
      bounds: myCustomEuropeBounds,
      strictBounds: true,
      types: ['(cities)']
     };

    new google.maps.places.Autocomplete(document.getElementById('autocomplete'), options);
}
```

The only thing left should be to define the bounds of Europe, which I let you find out by yourself :)

Hope it helped !

Body:
I am using basic Google Maps autocomplete:

    function initAutocomplete() {
        autocomplete = new google.maps.places.Autocomplete(
                (document.getElementById('autocomplete_1')),
                {types: ['(cities)']});
        autocomplete.addListener('place_changed', fillInAddress);
    }

It works totally fine, but I want to LIMIT the RESULTS to only European places. I could do it with the component Region filter but it limits me to 5 countries. Europe has 20+ countries. How to limit?

Edit: European including the UK :)

Body:
Here is a wild guess I can do using the documentation :

function initialize() {
    var options = {
      bounds: myCustomEuropeBounds,
      strictBounds: true,
      types: ['(cities)']
     };

    new google.maps.places.Autocomplete(document.getElementById('autocomplete'), options);
}

The only thing left should be to define the bounds of Europe, which I let you find out by yourself :)

Hope it helped !


问:
Redirection not happening in Php
I am using a special wrapper class around session_start() function to add protections on my sessions.

To log the user out, I have a button like this:

```<code> <a href="logout.php">
  <button data-toggle="modal" data-backdrop="false" href="" name="out" class="btn btn-primary navbar-btn" style="margin-right: 3px"><span class="glyphicon glyphicon-user"></span>Log Out</button></a>
</code>```

Here is the logout.php:

```<code><?php

error_reporting(0);
include('SessionManager.php');
$mySess = new SessionManager();
$session = $mySess -> sessionStart('InstallationName'); // create/start a new session or start the existent session

$mySess -> destroy(); //destroy the session

header('Location: page1bis.php');
exit();
?>
</code>```

Here is the destroy() function in my SessionManager Class:

```<code><?php
class SessionManager
{
          .
          .
          .
static protected function destroy()
{
    echo $_SESSION['cook'];echo "<br>";
    echo "hello !";
    session_destroy();
    echo $_SESSION['cook'];
}
}
?>
</code>```

But when one click on the logout button, it goes to the lougout.php page, but no redirection is made, also here is the output of the lougout.php page:

```<code>tfe0eccar02k3pgi5b7i8i2ek5
hello !
</code>```

p.s: The echos in the logout.php are just here to show that the session is effectively destroy (or there should to 2 tokens), also even if I remove them there is still the same problem

答: Turn on your PHP-errors. You should see something like Warning: Cannot modify header information - headers already sent by... which means that you're not allowed to echo/print anything prior to header-function.

Title: Redirection not happening in Php

Body:
I am using a special wrapper class around session_start() function to add protections on my sessions.

To log the user out, I have a button like this:

  <button data-toggle="modal" data-backdrop="false" href="" name="out" class="btn btn-primary navbar-btn" style="margin-right: 3px">Log Out</button>

Here is the logout.php:

<?php

error_reporting(0);
include('SessionManager.php');
$mySess = new SessionManager();
$session = $mySess -> sessionStart('InstallationName'); // create/start a new session or start the existent session

$mySess -> destroy(); //destroy the session

header('Location: page1bis.php');
exit();
?>

Here is the destroy() function in my SessionManager Class:

<?php
class SessionManager
{
          .
          .
          .
static protected function destroy()
{
    echo $_SESSION['cook'];echo "
";
    echo "hello !";
    session_destroy();
    echo $_SESSION['cook'];
}
}
?>

But when one click on the logout button, it goes to the lougout.php page, but no redirection is made, also here is the output of the lougout.php page:

tfe0eccar02k3pgi5b7i8i2ek5
hello !

p.s: The echos in the logout.php are just here to show that the session is effectively destroy (or there should to 2 tokens), also even if I remove them there is still the same problem


问:
get_categories order by last post
What is the best and shortest way in Wordpress to get_categories ordered by last posted article?

Means that categories with recent posts should appear first, is it available somehow?

答:
Try it:

```<code>function get_sorted_categories( $order_by = 'id', $args = array() ){
    global $wpdb;

    $category = get_categories( $args );

    $order = [
        'id' => 'post.ID',
        'date' => 'post.post_date',
        'modified' => 'post.post_modified',
    ];

    $order_by = $order[ $order_by ];

    $q = $wpdb->get_results("SELECT tax.term_id FROM `{$wpdb->prefix}term_taxonomy` tax
    INNER JOIN `{$wpdb->prefix}term_relationships` rel ON rel.term_taxonomy_id = tax.term_id
    INNER JOIN `{$wpdb->prefix}posts` post ON rel.object_id = post.ID WHERE tax.taxonomy = 'category' AND post.post_type = 'post' AND post.post_status = 'publish' ORDER BY {$order_by} DESC");

    $sort = array_flip( array_unique( wp_list_pluck( $q, 'term_id' ) ) );

    usort( $category, function( $a, $b ) use ( $sort, $category ) {
        if( isset( $sort[ $a->term_id ], $sort[ $b->term_id ] ) && $sort[ $a->term_id ] != $sort[ $b->term_id ] )
            $res = ($sort[ $a->term_id ] > $sort[ $b->term_id ]) ? 1 : -1;
        else if( !isset( $sort[ $a->term_id ] ) && isset( $sort[ $b->term_id ] ) )
            $res = 1;
        else if( isset( $sort[ $a->term_id ] ) && !isset( $sort[ $b->term_id ] ) )
            $res = -1;
        else
            $res = 0;

        return $res;
    } );

    return $category;
}

print_r( get_sorted_categories() );
print_r( get_sorted_categories('date') );
print_r( get_sorted_categories('modified') );
</code>```

Get categories order by (post ID | post date | post modified date). Without any loop and fast!

Title: get_categories order by last post

Body:
Try it:

function get_sorted_categories( $order_by = 'id', $args = array() ){
    global $wpdb;

    $category = get_categories( $args );

    $order = [
        'id' => 'post.ID',
        'date' => 'post.post_date',
        'modified' => 'post.post_modified',
    ];

    $order_by = $order[ $order_by ];

    $q = $wpdb->get_results("SELECT tax.term_id FROM `{$wpdb->prefix}term_taxonomy` tax
    INNER JOIN `{$wpdb->prefix}term_relationships` rel ON rel.term_taxonomy_id = tax.term_id
    INNER JOIN `{$wpdb->prefix}posts` post ON rel.object_id = post.ID WHERE tax.taxonomy = 'category' AND post.post_type = 'post' AND post.post_status = 'publish' ORDER BY {$order_by} DESC");

    $sort = array_flip( array_unique( wp_list_pluck( $q, 'term_id' ) ) );

    usort( $category, function( $a, $b ) use ( $sort, $category ) {
        if( isset( $sort[ $a->term_id ], $sort[ $b->term_id ] ) && $sort[ $a->term_id ] != $sort[ $b->term_id ] )
            $res = ($sort[ $a->term_id ] > $sort[ $b->term_id ]) ? 1 : -1;
        else if( !isset( $sort[ $a->term_id ] ) && isset( $sort[ $b->term_id ] ) )
            $res = 1;
        else if( isset( $sort[ $a->term_id ] ) && !isset( $sort[ $b->term_id ] ) )
            $res = -1;
        else
            $res = 0;

        return $res;
    } );

    return $category;
}

print_r( get_sorted_categories() );
print_r( get_sorted_categories('date') );
print_r( get_sorted_categories('modified') );

Get categories order by (post ID | post date | post modified date). Without any loop and fast!


问:
How do I return the smallest value using a for loop?
I am given a limit, and I have to return the smallest value for n to make it true: 1+2+3+4+...+n >= limit. I feel like there's one thing missing, but I can't tell.

```<code>public int whenToReachLimit(int limit) {
 int sum = 0;

 for (int i = 1; sum < limit; i++) {
   sum = sum + i;
  }
 return sum;
}
</code>```

The output would be:

1 : 1

4 : 3

10 : 4

答:
You don't want to return sum, you want to return n (smallest possible value satisfying the given requirement).

return i-1 instead of sum.

Body:
I am given a limit, and I have to return the smallest value for n to make it true: 1+2+3+4+...+n >= limit. I feel like there's one thing missing, but I can't tell.

public int whenToReachLimit(int limit) {
 int sum = 0;

 for (int i = 1; sum < limit; i++) {
   sum = sum + i;
  }
 return sum;
}

The output would be:

1 : 1

4 : 3

10 : 4


问:
Use lapply and show variable names
I am fairly new to R, though I've programmed in Python and Java a lot.  I have searched these questions about using a for loop to run through a list of variables and everyone keeps mentioning to use lapply.  I have done that, and my code works in the sense that it gives me the answers, but it doesn't work in the sense that the answers hide important details.  Here's my code and some of the output.

```<code>> bat <- read.csv(file="mlbTeam2016-B.csv", header=TRUE)
> varlist <- names(bat)[6:32]
> varlist
 [1] "AB.B"    "R.B"     "H.B"     "X2B.B"   "X3B.B"   "HR.B"    "RBI.B"
 [8] "BB.B"    "SO.B"    "SB.B"    "CS.B"    "AVG.B"   "OBP.B"   "SLG.B"
[15] "OPS.B"   "IBB.B"   "HBP.B"   "SAC.B"   "SF.B"    "TB.B"    "XBH.B"
[22] "GDP.B"   "GO.B"    "AO.B"    "GO_AO.B" "NP.B"    "PA.B"
> lapply(varlist, function(i){
+ var <- eval(parse(text=paste("bat$",i)))
+ cor.test(bat$W, var, alternative="two.sided", method="pearson")
+ })
[[1]]

        Pearson's product-moment correlation

data:  bat$W and var
t = 0.35067, df = 28, p-value = 0.7285
alternative hypothesis: true correlation is not equal to 0
95 percent confidence interval:
 -0.3013221  0.4164731
sample estimates:
       cor
0.06612551

etc
</code>```

The problem is that each output says data:  bat$W and var without telling me which variable it is testing in this step.  This is fine, except I have to go back and look up to see what variable this corresponds to.  That is better than typing this code in dozens of times, but not ideal.  I also know that using eval(parse( is bad, but I can't figure out another way to handle that line.

This is my desired output:

```<code>[[1]]

        Pearson's product-moment correlation

data:  bat$W and bat$AB.B
t = 0.35067, df = 28, p-value = 0.7285
alternative hypothesis: true correlation is not equal to 0
95 percent confidence interval:
 -0.3013221  0.4164731
sample estimates:
       cor
0.06612551
</code>```

答:
I would suggest  creating a correlation matrix rather than doing this using lapply.

This link will walk you through how to do that
http://www.sthda.com/english/wiki/correlation-matrix-a-quick-start-guide-to-analyze-format-and-visualize-a-correlation-matrix-using-r-software

You can select the variables you want using dplyr:

select(bat, one_of(varlist))

This should be a bit easier than the approach you are using.

Title: Use lapply and show variable names

Body:
I am fairly new to R, though I've programmed in Python and Java a lot.  I have searched these questions about using a for loop to run through a list of variables and everyone keeps mentioning to use lapply.  I have done that, and my code works in the sense that it gives me the answers, but it doesn't work in the sense that the answers hide important details.  Here's my code and some of the output.

> bat <- read.csv(file="mlbTeam2016-B.csv", header=TRUE)
> varlist <- names(bat)[6:32]
> varlist
 [1] "AB.B"    "R.B"     "H.B"     "X2B.B"   "X3B.B"   "HR.B"    "RBI.B"
 [8] "BB.B"    "SO.B"    "SB.B"    "CS.B"    "AVG.B"   "OBP.B"   "SLG.B"
[15] "OPS.B"   "IBB.B"   "HBP.B"   "SAC.B"   "SF.B"    "TB.B"    "XBH.B"
[22] "GDP.B"   "GO.B"    "AO.B"    "GO_AO.B" "NP.B"    "PA.B"
> lapply(varlist, function(i){
+ var <- eval(parse(text=paste("bat$",i)))
+ cor.test(bat$W, var, alternative="two.sided", method="pearson")
+ })
[[1]]

        Pearson's product-moment correlation

data:  bat$W and var
t = 0.35067, df = 28, p-value = 0.7285
alternative hypothesis: true correlation is not equal to 0
95 percent confidence interval:
 -0.3013221  0.4164731
sample estimates:
       cor
0.06612551

etc

The problem is that each output says data:  bat$W and var without telling me which variable it is testing in this step.  This is fine, except I have to go back and look up to see what variable this corresponds to.  That is better than typing this code in dozens of times, but not ideal.  I also know that using eval(parse( is bad, but I can't figure out another way to handle that line.

This is my desired output:

[[1]]

        Pearson's product-moment correlation

data:  bat$W and bat$AB.B
t = 0.35067, df = 28, p-value = 0.7285
alternative hypothesis: true correlation is not equal to 0
95 percent confidence interval:
 -0.3013221  0.4164731
sample estimates:
       cor
0.06612551


问:
Java - metode inside a metode syntax issues
Really don't know what it's called so I'm having a hard time searching for the answer.
Anyhow, I want to make a metode with metode inside (if that's even possible?).

```<code>public void log() {
    public makeLogElement() {
       //making a logelement to write inn
    }

    public write(String text) {
       logelement.setText(logelement.getText() + text);
    }
}
log myLog = new log();
myLog.makeLogElement();
myLog.write("This'll be written in the log");
</code>```

What is the right syntax for making something like this?

答: It's not possible. But you can create a class inside a method.</p>

Body:
Really don't know what it's called so I'm having a hard time searching for the answer.
Anyhow, I want to make a metode with metode inside (if that's even possible?).

public void log() {
    public makeLogElement() {
       //making a logelement to write inn
    }

    public write(String text) {
       logelement.setText(logelement.getText() + text);
    }
}
log myLog = new log();
myLog.makeLogElement();
myLog.write("This'll be written in the log");

What is the right syntax for making something like this?


问:
Trying to implement an alarm in my shell program. C Signal handling
I am building my own shell in C. I want to implement an builtin called alarm that takes in an integer argument for the number of seconds. The builtin just sends the user a message after i seconds (once) but the shell functionality should continue working in the meantime.

Heres what I have so far:

```<code>int seconds;

int main(int argc, char const *argv[], char* envp[]){
   ...
   signal(SIGALRM, alarmHandler);
   ...
}

void alarmHandler(int sig) {
    signal(sig, SIG_IGN);
    alarm(seconds);
    printf("%s\n", "message");
    signal(SIGALRM, alarmHandler);
}
void mainProgram(char* string, char* argument){
    ... //built ins that don't require forking
    pid_t processID = fork();

    if(processID==0){ //child
        if(strcmp(string, "alarm") == 0){
            seconds = atoi(argument);
            signal(SIGALRM, alarmHandler);
    }else{ // parent
        usleep(100000)
    }
</code>```

Clearly that doesn't work. I'm kinda lost. I've been trying this for the past couple of hours and I'm unsure of what to do.

答:
Perhaps you've got the wrong idea of what signal does...

The signal system call can be used for setting up handling of signals. Generally speaking, use the kill system call for sending signals.

OTOH, perhaps it's the difference between BSD signal handling semantics and System V signal handling semantics that's contributing to the confusion. System V signal handling semantics can necessitate calling signal (again) within the signal handler function. Newer linux systems at least stick with the BSD signal handling semantics which are reliable and don't require signal to be called again unless you wanted to change the handler that gets invoked.

As a side note, once you get past using signal correctly, I'd recommend using sigaction instead. You can read the 'Portability' section of the signal manual page that I linked to learn more about why you should use sigaction instead of signal.

But onwards...

There are other system calls that can be used to send signals in addition to the kill system call. Like in your case you may want to use alarm or setitimer.

Alternatively, if you wanted to implement something like what alarm does (without using alarm or setitimer), you could use a separate process (via a call to fork perhaps) that calls a sleep function followed by calling kill like this:

```<code>usleep(100000);
kill(pid, SIGALRM);
</code>```

In this example then, pid would be the process ID of the process that you wanted to send the SIGALRM signal to (which is the signal that alarm sends).

Hope this helps answer your question.

Body:
I am building my own shell in C. I want to implement an builtin called alarm that takes in an integer argument for the number of seconds. The builtin just sends the user a message after i seconds (once) but the shell functionality should continue working in the meantime.

Heres what I have so far:

int seconds;

int main(int argc, char const *argv[], char* envp[]){
   ...
   signal(SIGALRM, alarmHandler);
   ...
}

void alarmHandler(int sig) {
    signal(sig, SIG_IGN);
    alarm(seconds);
    printf("%s\n", "message");
    signal(SIGALRM, alarmHandler);
}
void mainProgram(char* string, char* argument){
    ... //built ins that don't require forking
    pid_t processID = fork();

    if(processID==0){ //child
        if(strcmp(string, "alarm") == 0){
            seconds = atoi(argument);
            signal(SIGALRM, alarmHandler);
    }else{ // parent
        usleep(100000)
    }

Clearly that doesn't work. I'm kinda lost. I've been trying this for the past couple of hours and I'm unsure of what to do.

Body:
Perhaps you've got the wrong idea of what signal does...

The signal system call can be used for setting up handling of signals. Generally speaking, use the kill system call for sending signals.

OTOH, perhaps it's the difference between BSD signal handling semantics and System V signal handling semantics that's contributing to the confusion. System V signal handling semantics can necessitate calling signal (again) within the signal handler function. Newer linux systems at least stick with the BSD signal handling semantics which are reliable and don't require signal to be called again unless you wanted to change the handler that gets invoked.

As a side note, once you get past using signal correctly, I'd recommend using sigaction instead. You can read the 'Portability' section of the signal manual page that I linked to learn more about why you should use sigaction instead of signal.

But onwards...

There are other system calls that can be used to send signals in addition to the kill system call. Like in your case you may want to use alarm or setitimer.

Alternatively, if you wanted to implement something like what alarm does (without using alarm or setitimer), you could use a separate process (via a call to fork perhaps) that calls a sleep function followed by calling kill like this:

usleep(100000);
kill(pid, SIGALRM);

In this example then, pid would be the process ID of the process that you wanted to send the SIGALRM signal to (which is the signal that alarm sends).

Hope this helps answer your question.


问:
How do I add an item to "Edit > Permute Lines" submenu?
According to this source the definition if Permute Lines submenu is following:

```<code>{
    "caption": "Permute Lines",
    "children": [...]
}
</code>```

And it doesn't contain an id. Is there a way to add items to this submenu?

Also this source is 5 years old and is probably for Sublime Text 2. Is there a more recent version of default menu file?

答:
To answer your second question first, you can always get at the most recent menu definition from your own copy of Sublime; it's stored in the file Default\Main.sublime-menu, which you can get to most easily using PackageResourceViewer to open it up.

That said, the part of the menu that you're referencing in your question is the same between Sublime Text 2 and Sublime Text 3 and neither of them has an id value directly within the Permute Lines sub-menu.

By creating a Main.sublime-menu in some other package (e.g. your User package) you could create entries that are adjacent to that sub menu, but in order to actually put new content directly inside of it you would need to create an Override.

You can do that via PackageResourceViewer; if you use it to open up the Default\Main.sublime-menu file, you can modify the file and when you save it, it will be saved as an override.

From this point forward your override becomes the new default menu; other packages that extend the menu can still do so, but they will be merged with your version and not the shipped version.

This is not without its risks in that if a future version of Sublime Text includes a modified version of the menu, your override will still take precedence and you won't be warned that it's happening, so you could potentially miss out on fixes.

This happened recently when the latest build of Sublime modified the base menu to include an install link for PackageControl, for example.

Also, this is only a viable solution if you want to edit the menu for your own purposes; if you're a package author, you can't use this method to distribute your own changes.

Body:
According to this source the definition if Permute Lines submenu is following:

{
    "caption": "Permute Lines",
    "children": [...]
}

And it doesn't contain an id. Is there a way to add items to this submenu?

Also this source is 5 years old and is probably for Sublime Text 2. Is there a more recent version of default menu file?


问:
Ifstream getting information from a textfile
At the moment I'm trying to get to create a race track that has all of the textures on the ground loaded via a textfile. An example is this:

0, 0, 1, 1, 1, 1, 0, 0

0, 1, 0, 0, 0, 0, 1, 0

0, 0, 1, 1, 1, 1, 0, 0

The ground itself is simply a grid.

At the moment the code I have to get information from text file is as follows:

```<code> string line;
 ifstream myfile ("track1.txt");
 if (myfile.is_open())
 {
  while ( !myfile.eof() )
  {
   getline( myfile, line, ',');
   if (line == '0')
   {
    const wstring textureFileName=TEXT("crate.jpg");
   }
   myfile>>line;
  }

  myfile.close();
 }
</code>```

When I build this code, how ever I get the following error:

binary '==' : no operator found which
  takes a right-hand operand of type

Then if I change the double equals sign to a single I get the following error:

error C2451: conditional expression
  of type 'std::basic_string<_Elem,_Traits,_Ax>'is illegal
  'char' (or there is no acceptable
  conversion)

Is there something I'm missing that is causing the error?

Sorry for my lack of proper detail.

Thank you chaosTechnician. Will the val work on multiple lines in the text file?
Like this

```<code>0 0 1 1 1 1 0 0
0 1 0 0 0 0 1 0
1 0 0 0 0 0 0 1
0 1 0 0 0 0 1 0
0 0 1 1 1 1 0 0
</code>```

I mean, is there anything else I need to type to get the computer to realise the line has ended?

答:
You're trying to compare a string to a char:

```<code>line == '0'
</code>```

instead, try:

```<code>line[0] == '0'
</code>```

or:

```<code>line == "0"
</code>```

Body:
At the moment I'm trying to get to create a race track that has all of the textures on the ground loaded via a textfile. An example is this:

0, 0, 1, 1, 1, 1, 0, 0

0, 1, 0, 0, 0, 0, 1, 0

0, 0, 1, 1, 1, 1, 0, 0

The ground itself is simply a grid.

At the moment the code I have to get information from text file is as follows:

 string line;
 ifstream myfile ("track1.txt");
 if (myfile.is_open())
 {
  while ( !myfile.eof() )
  {
   getline( myfile, line, ',');
   if (line == '0')
   {
    const wstring textureFileName=TEXT("crate.jpg");
   }
   myfile>>line;
  }

  myfile.close();
 }

When I build this code, how ever I get the following error:

binary '==' : no operator found which
  takes a right-hand operand of type

Then if I change the double equals sign to a single I get the following error:

error C2451: conditional expression
  of type 'std::basic_string<_Elem,_Traits,_Ax>'is illegal
  'char' (or there is no acceptable
  conversion)

Is there something I'm missing that is causing the error?

Sorry for my lack of proper detail.

Thank you chaosTechnician. Will the val work on multiple lines in the text file?
Like this

0 0 1 1 1 1 0 0
0 1 0 0 0 0 1 0
1 0 0 0 0 0 0 1
0 1 0 0 0 0 1 0
0 0 1 1 1 1 0 0

I mean, is there anything else I need to type to get the computer to realise the line has ended?

Body:
You're trying to compare a string to a char:

line == '0'

instead, try:

line[0] == '0'

or:

line == "0"


问:
Ajax saving array into global variables not working keep getting undefined
Trying to save an array retrieved from ajax into a global variable such that I may use it later on but keep getting undefined error</p>

```<code>   <script>
    var items = [];

    function add(value){
        items.push(value);
    }

    $(document).ready( function() {
    $.ajax({
        type: 'POST',
        url: 'xxxx.php',
        dataType: 'json',
        cache: false,
        success: function(result) {
            for(i=0; i < result.length; i++){
                add(result[i]);
            }
        },
    });
    });

    document.write(items[1])

    </script>
</code>```

答:
This is an asynchronous AJAX call. The call to add will be done at a later time than the execution of document.write(items[1]);

So this is the right way to do it:

```<code><script>
    var items = [];

    function add(value){
        items.push(value);
    }

$(document).ready( function() {
    $.ajax({
        type: 'POST',
        url: 'xxxx.php',
        dataType: 'json',
        cache: false,
        success: function(result) {
            for(i=0; i < result.length; i++){
                add(result[i]);
            }
            document.write(items[1])
        },
    });
});
</script>
</code>```

This way the function that uses the result, will be executed when the result function is executed.

Think it this way: you said: Here is this lemon basket. Then you asked someone to go somewhere and get the lemons and before he returned you tried to count the lemons. Got it ?

Body:
This is an asynchronous AJAX call. The call to add will be done at a later time than the execution of document.write(items[1]);

So this is the right way to do it:

<script>
    var items = [];

    function add(value){
        items.push(value);
    }

$(document).ready( function() {
    $.ajax({
        type: 'POST',
        url: 'xxxx.php',
        dataType: 'json',
        cache: false,
        success: function(result) {
            for(i=0; i < result.length; i++){
                add(result[i]);
            }
            document.write(items[1])
        },
    });
});
</script>

This way the function that uses the result, will be executed when the result function is executed.

Think it this way: you said: Here is this lemon basket. Then you asked someone to go somewhere and get the lemons and before he returned you tried to count the lemons. Got it ?


问:
Softlayer Got "Connection reset by peer" error when capturing a VM image
I use the Softlayer python API to automate create a VM and install some packages to the VM, then capture the VM image. The code worked for the last three years. The code runs in a VM inside Softlayer. But I kept getting "Connection reset by peer" during image capturing when running the same code since yesterday. Just wondering if anything has changed in Softlayer that causing it?

error: [Errno 104] Connection reset by peer

2017-03-31 14:37:03,096 - imaginator.cli-Status - ERROR - Failed |
  Unknown errors occurred during image building - see log for details.

2017-03-31 14:37:03,097 - SoftLayer.transports - INFO - POST
  https://api.service.softlayer.com/xmlrpc/v3/SoftLayer_Virtual_Guest

2017-03-31 14:37:03,097 - urllib3.connectionpool - INFO - Starting new
  HTTPS connection (1): api.service.softlayer.com

2017-03-31 14:37:05,719 - imaginator.provider.softlayer - INFO -
  Submitted request to destroy instance 30219065

The code I used to capture the image is:

```<code>transactionInfo = self.client['Virtual_Guest'].createArchiveTransaction(name, disks, groupName, id=server.id)
</code>```

答:
The code line you are using is correct. The method createArchiveTransaction() is working as expected, I was able to create an image template using the code example below.

Currently, there are some issues in Softlayer's API server related to “connection reset by peer” and SoftLayer is working to resolve them. Some users reported that this is temporal, I suggest to try it again after a while.

Code example:

```<code>"""
Create image template.

The script creates a standard image template, it makes a call to the SoftLayer_Virtual_Guest::createArchiveTransaction method
sending the IDs of the disks in the request.
For more information please see below.

Important manual pages:
https://sldn.softlayer.com/reference/services/SoftLayer_Virtual_Guest
https://sldn.softlayer.com/reference/services/SoftLayer_Virtual_Guest/createArchiveTransaction
https://sldn.softlayer.com/reference/datatypes/SoftLayer_Virtual_Guest_Block_Device

License: http://sldn.softlayer.com/article/License
Author: SoftLayer Technologies, Inc. <sldn@softlayer.com>
"""
import SoftLayer

# Your SoftLayer API username and key.
USERNAME = 'set me'
API_KEY = 'set me'

# The virtual guest ID you want to create a template
virtualGuestId = 29292929
# The name of the image template
groupName = 'my image name'
# An optional note for the image template
note = 'an optional note'

"""
Build a skeleton SoftLayer_Virtual_Guest_Block_Device object
containing the disks you want to the image.
In this case we are going take an image template of 2 disks
from the virtual machine.
"""
blockDevices = [
    {
        "id": 45009433,
        "complexType": "SoftLayer_Virtual_Guest_Block_Device"
    },
    {
        "id": 45009439,
        "complexType": "SoftLayer_Virtual_Guest_Block_Device"
    }
]

# Declare a new API service object
client = SoftLayer.create_client_from_env(username=USERNAME, api_key=API_KEY)

try:
    # Creating the transaction for the image template
   response = client['SoftLayer_Virtual_Guest'].createArchiveTransaction(groupName, blockDevices, note, id=virtualGuestId)
    print(response)
except SoftLayer.SoftLayerAPIError as e:
    """
    # If there was an error returned from the SoftLayer API then bomb out with the
    # error message.
    """
    print("Unable to create the image template. faultCode=%s, faultString=%s" % (e.faultCode, e.faultString))
</code>```

Regards,

Body:
I use the Softlayer python API to automate create a VM and install some packages to the VM, then capture the VM image. The code worked for the last three years. The code runs in a VM inside Softlayer. But I kept getting "Connection reset by peer" during image capturing when running the same code since yesterday. Just wondering if anything has changed in Softlayer that causing it?

error: [Errno 104] Connection reset by peer

2017-03-31 14:37:03,096 - imaginator.cli-Status - ERROR - Failed |
  Unknown errors occurred during image building - see log for details.

2017-03-31 14:37:03,097 - SoftLayer.transports - INFO - POST
  https://api.service.softlayer.com/xmlrpc/v3/SoftLayer_Virtual_Guest

2017-03-31 14:37:03,097 - urllib3.connectionpool - INFO - Starting new
  HTTPS connection (1): api.service.softlayer.com

2017-03-31 14:37:05,719 - imaginator.provider.softlayer - INFO -
  Submitted request to destroy instance 30219065

The code I used to capture the image is:

transactionInfo = self.client['Virtual_Guest'].createArchiveTransaction(name, disks, groupName, id=server.id)

Body:
The code line you are using is correct. The method createArchiveTransaction() is working as expected, I was able to create an image template using the code example below.

Currently, there are some issues in Softlayer's API server related to “connection reset by peer” and SoftLayer is working to resolve them. Some users reported that this is temporal, I suggest to try it again after a while.

Code example:

"""
Create image template.

The script creates a standard image template, it makes a call to the SoftLayer_Virtual_Guest::createArchiveTransaction method
sending the IDs of the disks in the request.
For more information please see below.

Important manual pages:
https://sldn.softlayer.com/reference/services/SoftLayer_Virtual_Guest
https://sldn.softlayer.com/reference/services/SoftLayer_Virtual_Guest/createArchiveTransaction
https://sldn.softlayer.com/reference/datatypes/SoftLayer_Virtual_Guest_Block_Device

License: http://sldn.softlayer.com/article/License
Author: SoftLayer Technologies, Inc. <sldn@softlayer.com>
"""
import SoftLayer

# Your SoftLayer API username and key.
USERNAME = 'set me'
API_KEY = 'set me'

# The virtual guest ID you want to create a template
virtualGuestId = 29292929
# The name of the image template
groupName = 'my image name'
# An optional note for the image template
note = 'an optional note'

"""
Build a skeleton SoftLayer_Virtual_Guest_Block_Device object
containing the disks you want to the image.
In this case we are going take an image template of 2 disks
from the virtual machine.
"""
blockDevices = [
    {
        "id": 45009433,
        "complexType": "SoftLayer_Virtual_Guest_Block_Device"
    },
    {
        "id": 45009439,
        "complexType": "SoftLayer_Virtual_Guest_Block_Device"
    }
]

# Declare a new API service object
client = SoftLayer.create_client_from_env(username=USERNAME, api_key=API_KEY)

try:
    # Creating the transaction for the image template
   response = client['SoftLayer_Virtual_Guest'].createArchiveTransaction(groupName, blockDevices, note, id=virtualGuestId)
    print(response)
except SoftLayer.SoftLayerAPIError as e:
    """
    # If there was an error returned from the SoftLayer API then bomb out with the
    # error message.
    """
    print("Unable to create the image template. faultCode=%s, faultString=%s" % (e.faultCode, e.faultString))

Regards,


问:
Cause of No component found with scheme: ftp
I am experimenting with Spring Boot and Camel.  I have a simple route:

```<code>@Component
public class MyRoute extends RouteBuilder {

    @Override
    public void configure() throws Exception {
        from("ftp://localhost/INBOUND?username=blah&password=foo")
                .to("file:/tmp/test");
    }
}
</code>```

My pom file has:

```<code><dependency>
    <groupId>org.apache.camel</groupId>
    <artifactId>camel-spring-boot-starter</artifactId>
    <version>2.18.3</version>
</dependency>
<dependency>
    <groupId>org.apache.camel</groupId>
    <artifactId>camel-ftp</artifactId>
    <version>2.18.3</version>
</dependency>
</code>```

On startup I get the following error:

Caused by: org.apache.camel.FailedToCreateRouteException: Failed to create route route2: Route(route2)[[From[ftp://localhost/INBOUND?username=blah... because of Failed to resolve endpoint: ftp://localhost/INBOUND?password=set42now&username=comcast due to: No component found with scheme: ftp

Any ideas?

答: You need the camel-ftp-starter dependency instead of camel-ftp.

Body:
I am experimenting with Spring Boot and Camel.  I have a simple route:

@Component
public class MyRoute extends RouteBuilder {

    @Override
    public void configure() throws Exception {
        from("ftp://localhost/INBOUND?username=blah&password=foo")
                .to("file:/tmp/test");
    }
}

My pom file has:

<dependency>
    <groupId>org.apache.camel</groupId>
    <artifactId>camel-spring-boot-starter</artifactId>
    <version>2.18.3</version>
</dependency>
<dependency>
    <groupId>org.apache.camel</groupId>
    <artifactId>camel-ftp</artifactId>
    <version>2.18.3</version>
</dependency>

On startup I get the following error:

Caused by: org.apache.camel.FailedToCreateRouteException: Failed to create route route2: Route(route2)[[From[ftp://localhost/INBOUND?username=blah... because of Failed to resolve endpoint: ftp://localhost/INBOUND?password=set42now&username=comcast due to: No component found with scheme: ftp

Any ideas?