问:
javascript - How to define a property within a function?
So I can define a property on a function from the outside such as: createNewPerson.hmm = 3; and I get the result 3 when I use the alert. However if I try to do the same but from within a function (as in define a property within a function) it doesn't work.. I tried all the commented lines below. Is there a different way to achieve this or is it simply not possible? If it's not possible, then how does javascript append the .hmm property to the function and later call it?

Full code:

```<code>function createNewPerson(name) {
//var hello = "hgfgh";
//hello: "hgfgh"
//hello = hgfgh;
//this.hello = hgfgh;

}
createNewPerson.hmm = 3;
alert(createNewPerson.hmm);
alert(createNewPerson.hello);
</code>```

答:
I think you are trying to create objects. In javascript, you do it this way:

```<code>function Test(){
  this.foo = "bar";
  this.func = function(){
    console.log(this.foo);
  }
}

const test = new Test();
test.foo = "baz";
test.func(); //Will print "baz".
</code>```

note the use of "new". This is what enables the mechanism of allowing code to modify properties of object. The modified values of the properties is then accessible by the object itself.

Body:
So I can define a property on a function from the outside such as: createNewPerson.hmm = 3; and I get the result 3 when I use the alert. However if I try to do the same but from within a function (as in define a property within a function) it doesn't work.. I tried all the commented lines below. Is there a different way to achieve this or is it simply not possible? If it's not possible, then how does javascript append the .hmm property to the function and later call it?

Full code:

function createNewPerson(name) {
//var hello = "hgfgh";
//hello: "hgfgh"
//hello = hgfgh;
//this.hello = hgfgh;

}
createNewPerson.hmm = 3;
alert(createNewPerson.hmm);
alert(createNewPerson.hello);

Body:
I think you are trying to create objects. In javascript, you do it this way:

function Test(){
  this.foo = "bar";
  this.func = function(){
    console.log(this.foo);
  }
}

const test = new Test();
test.foo = "baz";
test.func(); //Will print "baz".

note the use of "new". This is what enables the mechanism of allowing code to modify properties of object. The modified values of the properties is then accessible by the object itself.


来源: stackexchange

问:
How can i combine a case insensitive search with a case sensitive replace in regex?
For example, suppose I have the following text:

```<code>"Constants cons are CONTAGIOUS"
</code>```

I want all the "cons" replaced irrespective of case, but preserving case on the replace.

For example, suppose I want to put bold tags around them, I would want the output to be:

```<code>"<b>Con</b>stants <b>cons</b> are <b>CON</b>TAGIOUS"
</code>```

In JavaScript, I have tried:

```<code>var re = new RegExp("con", 'ig');
var newText = text.replace(re,"<b>" + "con" + "</b>");
</code>```

This does a case insensitive search but I lose the case on the replace. Is there a way to preserve case on the replace?

答:
You can wrap the input in a capturing group () and refer back to it in the replacement via $1:

var text = "Constants cons are CONTAGIOUS";

var regex = new RegExp("(con)", 'ig');
var newText = text.replace(regex, "$1");

console.log(newText); // "Constants cons are CONTAGIOUS"```
</div>
</div>
</p>

<hr>

<p><strong>Edit:</strong> Thanks @JordanRunning, you don't even need a capturing group in this case, since you are referring back to the complete match:</p>

<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>var text = "Constants cons are CONTAGIOUS";

var regex = new RegExp("con", 'ig');
var newText = text.replace(regex, "<b>$&</b>");

console.log(newText); // "<b>Con</b>stants <b>con</b>s are <b>CON</b>TAGIOUS"</code>```

ContentLicense: CC BY-SA 3.0

Body:
For example, suppose I have the following text:

"Constants cons are CONTAGIOUS"

I want all the "cons" replaced irrespective of case, but preserving case on the replace.

For example, suppose I want to put bold tags around them, I would want the output to be:

"Constants cons are CONTAGIOUS"

In JavaScript, I have tried:

var re = new RegExp("con", 'ig');
var newText = text.replace(re,"" + "con" + "");

This does a case insensitive search but I lose the case on the replace. Is there a way to preserve case on the replace?

Body:
You can wrap the input in a capturing group () and refer back to it in the replacement via $1:

var text = "Constants cons are CONTAGIOUS";

var regex = new RegExp("(con)", 'ig');
var newText = text.replace(regex, "<b>$1</b>");

console.log(newText); // "<b>Con</b>stants <b>con</b>s are <b>CON</b>TAGIOUS"

Edit: Thanks @JordanRunning, you don't even need a capturing group in this case, since you are referring back to the complete match:

var text = "Constants cons are CONTAGIOUS";

var regex = new RegExp("con", 'ig');
var newText = text.replace(regex, "<b>$&</b>");

console.log(newText); // "<b>Con</b>stants <b>con</b>s are <b>CON</b>TAGIOUS"


问:
Fast way to check if a list of IP is in a list of IP-ranges (CIDR notation)
I am looking for a fast way to check if IP addresses are part of a list of CIDR notated IP ranges. I've seen examples before use netaddr like:

```<code>from netaddr import IPNetwork, IPAddress

    for CIDR in CIDRLIST:
        if IPAddress(row[0]) in IPNetwork(CIDR):
            print('success')
</code>```

However this solution is way too slow for my problem (800 IP ranges in CIDR and 500.000 IP adresses).

What could be a way to do this faster? I've read about using pytries, but I am not certain this is the solution.

答:
Patricia/Radix tree/tries seem to be the answer.  I found them by searching for algorithms for looking up routing tables.

There is a python implementation here.

A little later:  I now have this working fine in Ruby:

```
require 'rpatricia'
require 'uoainfoblox'

ib = UoAIinfoblox.new ({'user' => 'xxxxx', 'password' => 'yyyy', 'host' => 'ipam.auckland.ac.nz'})

pt = Patricia.new

ib.get_networks('*roaming_network=true').each do |net, info |
  pt.add(net)
end

puts "'130.216.66.65 #{ pt.include?('130.216.66.65')}"
puts "130.216.5.128 #{pt.include?('130.216.5.128') }"

```

Infoblox is an IP Management system and UoAInfoblox is a wrapper around their web api.  So here I get a list of the roaming networks add them into a patricia tree and then check two IP addresses (that I know the status of).

Edit:  I have just found out from a friend who uses python and who teaches networking in our CS department that he used the python radix module in his research scripts. I know he was processing very large amounts of data from a /8 darkenet for CAIDA.

Body:
I am looking for a fast way to check if IP addresses are part of a list of CIDR notated IP ranges. I've seen examples before use netaddr like:

from netaddr import IPNetwork, IPAddress

    for CIDR in CIDRLIST:
        if IPAddress(row[0]) in IPNetwork(CIDR):
            print('success')

However this solution is way too slow for my problem (800 IP ranges in CIDR and 500.000 IP adresses).

What could be a way to do this faster? I've read about using pytries, but I am not certain this is the solution.

Body:
Patricia/Radix tree/tries seem to be the answer.  I found them by searching for algorithms for looking up routing tables.

There is a python implementation here.

A little later:  I now have this working fine in Ruby:

require 'rpatricia'
require 'uoainfoblox'

ib = UoAIinfoblox.new ({'user' => 'xxxxx', 'password' => 'yyyy', 'host' => 'ipam.auckland.ac.nz'})

pt = Patricia.new

ib.get_networks('*roaming_network=true').each do |net, info |
  pt.add(net)
end

puts "'130.216.66.65 #{ pt.include?('130.216.66.65')}"
puts "130.216.5.128 #{pt.include?('130.216.5.128') }"

Infoblox is an IP Management system and UoAInfoblox is a wrapper around their web api.  So here I get a list of the roaming networks add them into a patricia tree and then check two IP addresses (that I know the status of).

Edit:  I have just found out from a friend who uses python and who teaches networking in our CS department that he used the python radix module in his research scripts. I know he was processing very large amounts of data from a /8 darkenet for CAIDA.


问:
Cannot create dataproc cluster
When creating DataProc cluster using Web Console or gcloud, getting the same error:

```<code>gcloud dataproc --region us-west1 clusters create cluster-02eb --subnet default --zone us-west1-a --master-machine-type n1-standard-4 --master-boot-disk-size 500 --num-workers 2 --worker-machine-type n1-standard-4 --worker-boot-disk-size 500 --image-version 1.2 --scopes 'https://www.googleapis.com/auth/cloud-platform' --project projectxyz123 --initialization-actions 'gs://dataproc-initialization-actions/jupyter/jupyter.sh'

Waiting on operation [projects/projectxyz123/regions/us-west1/operations/53badbbc-41cc-4241-aedb-490981864bf9].
Waiting for cluster creation operation...done.
ERROR: (gcloud.dataproc.clusters.create) Operation [projects/projectxyz123/regions/us-west1/operations/53badbbc-41cc-4241-aedb-490981864bf9] failed: com.google.api.client.googleapis.json.GoogleJsonResponseException: 404 Not Found
Not Found.
</code>```

What does this error means ?

答: This is currently a known issue for zone us-west1-a. Using an alternative zone should work (e.g. us-west1-b).</p>

Title: Cannot create dataproc cluster

Body:
When creating DataProc cluster using Web Console or gcloud, getting the same error:

gcloud dataproc --region us-west1 clusters create cluster-02eb --subnet default --zone us-west1-a --master-machine-type n1-standard-4 --master-boot-disk-size 500 --num-workers 2 --worker-machine-type n1-standard-4 --worker-boot-disk-size 500 --image-version 1.2 --scopes 'https://www.googleapis.com/auth/cloud-platform' --project projectxyz123 --initialization-actions 'gs://dataproc-initialization-actions/jupyter/jupyter.sh'

Waiting on operation [projects/projectxyz123/regions/us-west1/operations/53badbbc-41cc-4241-aedb-490981864bf9].
Waiting for cluster creation operation...done.
ERROR: (gcloud.dataproc.clusters.create) Operation [projects/projectxyz123/regions/us-west1/operations/53badbbc-41cc-4241-aedb-490981864bf9] failed: com.google.api.client.googleapis.json.GoogleJsonResponseException: 404 Not Found
Not Found.

What does this error means ?


问:
spark.executor.cores can't take effect while using livy
I'm using livy-server-0.2 to run spark job, however, I can't change the default setting for spark.executor.cores, it can't take effect while the other settings can.

It always use 1 core to start an executor.

```<code>yarn     11893 11889  6 21:08 ?        00:00:01
/opt/jdk1.7.0_80/bin/java -server -XX:OnOutOfMemoryError=kill
%p -Xms1024m -Xmx1024m -Djava.io.tmpdir=/var/lib/hadoop-yarn/cache/yarn/nm-local-dir/usercache/root/appcache/application_1487813931557_0603/container_1487813931557_0603_01_000026/tmp
-Dspark.driver.port=51553
-Dspark.yarn.app.container.log.dir=/var/log/hadoop-yarn/containers/application_1487813931557_0603/container_1487813931557_0603_01_000026
-XX:MaxPermSize=256m org.apache.spark.executor.CoarseGrainedExecutorBackend
--driver-url spark://CoarseGrainedScheduler@10.1.1.81:51553 --executor-id 19
--hostname master01.yscredit.com --cores 1 --app-id application_1487813931557_0603
--user-class-path file:/var/lib/hadoop-yarn/cache/yarn/nm-local-dir/usercache/root/appcache/application_1487813931557_0603/container_1487813931557_0603_01_000026/__app__.jar
</code>```

Here is my spark-defaults.conf file in $SPARK_HOME/conf

```<code>spark.master=yarn
spark.submit.deployMode=cluster
spark.executor.instances=7
spark.executor.cores=6
spark.executor.memoryOverhead=1024
spark.yarn.executor.memoryOverhead=1400
spark.executor.memory=11264
spark.driver.memory=5g
spark.yarn.driver.memoryOverhead=600
spark.speculation=true
spark.yarn.executor.memoryOverhead=1400
</code>```

can anybody help me? thanks!

答:
There is a property in the yarn which limits the resource on the cluster.

```<code>sudo  vi /etc/hadoop/conf/capacity-scheduler.xml
</code>```

Change the property to the following

```<code>"yarn.scheduler.capacity.resource-calculator": "org.apache.hadoop.yarn.util.resource.DominantResourceCalculator"
</code>```

In order to make this property applicable you have to restart the yarn

```<code> sudo  hadoop-yarn-resourcemanager stop
</code>```

Restart the yarn

```<code>sudo  hadoop-yarn-resourcemanager start
</code>```

Body:
I'm using livy-server-0.2 to run spark job, however, I can't change the default setting for spark.executor.cores, it can't take effect while the other settings can.

It always use 1 core to start an executor.

yarn     11893 11889  6 21:08 ?        00:00:01
/opt/jdk1.7.0_80/bin/java -server -XX:OnOutOfMemoryError=kill
%p -Xms1024m -Xmx1024m -Djava.io.tmpdir=/var/lib/hadoop-yarn/cache/yarn/nm-local-dir/usercache/root/appcache/application_1487813931557_0603/container_1487813931557_0603_01_000026/tmp
-Dspark.driver.port=51553
-Dspark.yarn.app.container.log.dir=/var/log/hadoop-yarn/containers/application_1487813931557_0603/container_1487813931557_0603_01_000026
-XX:MaxPermSize=256m org.apache.spark.executor.CoarseGrainedExecutorBackend
--driver-url spark://CoarseGrainedScheduler@10.1.1.81:51553 --executor-id 19
--hostname master01.yscredit.com --cores 1 --app-id application_1487813931557_0603
--user-class-path file:/var/lib/hadoop-yarn/cache/yarn/nm-local-dir/usercache/root/appcache/application_1487813931557_0603/container_1487813931557_0603_01_000026/__app__.jar

Here is my spark-defaults.conf file in $SPARK_HOME/conf

spark.master=yarn
spark.submit.deployMode=cluster
spark.executor.instances=7
spark.executor.cores=6
spark.executor.memoryOverhead=1024
spark.yarn.executor.memoryOverhead=1400
spark.executor.memory=11264
spark.driver.memory=5g
spark.yarn.driver.memoryOverhead=600
spark.speculation=true
spark.yarn.executor.memoryOverhead=1400

can anybody help me? thanks!

Body:
There is a property in the yarn which limits the resource on the cluster.

sudo  vi /etc/hadoop/conf/capacity-scheduler.xml

Change the property to the following

"yarn.scheduler.capacity.resource-calculator": "org.apache.hadoop.yarn.util.resource.DominantResourceCalculator"

In order to make this property applicable you have to restart the yarn

 sudo  hadoop-yarn-resourcemanager stop

Restart the yarn

sudo  hadoop-yarn-resourcemanager start


问:
Do we need to use the Repository pattern when working in ASP.NET MVC with ORM solutions?
I am bit curious as to what experience other developers have of applying the Repository pattern when programming in ASP.NET MVC with Entity Framework or NHibernate. It seems to me that this pattern is already implemented in the ORM themselves. DbContext and DbSet<T> in the Entity Framework and by the ISession in NHibernate. Most of the concerns mentioned in the Repository pattern - as catalogued in POEE and DDD - are pretty adequately implemented by these ORMs. Namely these concerns are,

Persistence

OO View of the data

Data Access Logic Abstraction

Query Access Logic

In addition, most of the implemententations of the repository pattern that I have seen follow this implementation pattern - assuming that we are developing a blog application.

NHibernate implementation:

```<code>public class PostRepository : IPostRepository
{
    private ISession _session;

    public PostRepository(ISession session)
    {
        _session = session;
    }

    public void Add(Post post)
    {
        _session.Save(post);
    }

    // other crud methods.
}
</code>```

Entity Framework:

```<code>public class PostRepository : IPostRepository
{
    private DbContext _session;

    public PostRepository(DbContext session)
    {
        _session = session;
    }

    public void Add(Post post)
    {
        _session.Posts.Add(post);
        -session.SaveChanges();
    }

    // other crud methods.
}
</code>```

It seems to me that when we are using ORMs - such as Nhibernate or Entity Framework - creating these repository implementation are redundant. Furthermore since these pattern implementations does no more than what is already there in the ORMS, these act more as noise than helpful OO abstractions. It seems using the repository pattern in the situation mentioned above is nothing more than developer self aggrandizement and more pomp and ceremony without any realizable techical benefits. What are your thoughts ??

答:
You've only mentioned basic CRUD actions. Doing these directly does mean you have to be aware of transactions, flushing and other things that a repository can wrap up, but I guess the value of repositories becomes more apparent when you think about complex retrieval queries.

Imagine then that you do decide to use the NHibernate session directly in your application layer.

You will need to do the equivalent of WHERE clauses and ORDER BYs etc, using either HQL or NHibernate criteria. This means your code has to reference NHibernate, and contains ideas specific to NHibernate. This makes your application hard to test and harder for others unfamiliar with NH to follow. A call to repository.GetCompletedOrders is much more descriptive and reusable than one that includes something like "where IsComplete = true and IsDeleted = false..." etc.

You could use Linq to NHibernate instead, but now you have the situation where you can easily forget that you're working on an IQueryable. You could end up chaining Linq expressions which generate enormous queries when they execute, without realising it (I speak from experience)! Mike Hadlow sparked a conversation on essentially this topic in his post Should my repository expose IQueryable.

N.b. If you don't like having lots of methods on custom repositories for different queries (like GetCompletedOrders), you can use specification parameters (like Get(specification)), which allow you to specify filters, orderings etc. without using data access language.

Going back to the list of benefits of repository that you gave:

Persistence

OO View of the data

Data Access Logic Abstraction

Query Access Logic

You can see that points 3 and 4 are not provided for by using the persistence framework classes directly, especially in real world retrieval scenarios.

Body:
I am bit curious as to what experience other developers have of applying the Repository pattern when programming in ASP.NET MVC with Entity Framework or NHibernate. It seems to me that this pattern is already implemented in the ORM themselves. DbContext and DbSet<T> in the Entity Framework and by the ISession in NHibernate. Most of the concerns mentioned in the Repository pattern - as catalogued in POEE and DDD - are pretty adequately implemented by these ORMs. Namely these concerns are,

Persistence

OO View of the data

Data Access Logic Abstraction

Query Access Logic

In addition, most of the implemententations of the repository pattern that I have seen follow this implementation pattern - assuming that we are developing a blog application.

NHibernate implementation:

public class PostRepository : IPostRepository
{
    private ISession _session;

    public PostRepository(ISession session)
    {
        _session = session;
    }

    public void Add(Post post)
    {
        _session.Save(post);
    }

    // other crud methods.
}

Entity Framework:

public class PostRepository : IPostRepository
{
    private DbContext _session;

    public PostRepository(DbContext session)
    {
        _session = session;
    }

    public void Add(Post post)
    {
        _session.Posts.Add(post);
        -session.SaveChanges();
    }

    // other crud methods.
}

It seems to me that when we are using ORMs - such as Nhibernate or Entity Framework - creating these repository implementation are redundant. Furthermore since these pattern implementations does no more than what is already there in the ORMS, these act more as noise than helpful OO abstractions. It seems using the repository pattern in the situation mentioned above is nothing more than developer self aggrandizement and more pomp and ceremony without any realizable techical benefits. What are your thoughts ??

ContentLicense: CC BY-SA 2.5


问:
Conversion from a shape drawn with quads, to a shape drawn with triangles
I am a student, for a legacy openGL assignment a few weeks ago we were asked to program 3D shapes using openGL commands such as GL_DRAW_QUADS, I had been using quads for essentially everything up until that point (since it was admittedly easier)

I've ran into a hurdle. I have multiple shapes that can be rendered with quads, such as a sphere and torus, and these currently work as intended when rendered directly with GL_QUADS

However, when storing a shape to be rendered later via the vertex buffers, which is the much better way of doing things, My model renderer will only work with shapes which are composed of triangles. and although a quad is technically two triangles, simply changing my methods to work with GL_TRIANGLES, or GL_TRIANGLE_FAN or GL_TRIANGLE_STRIP doesn't solve my issues.

I'm wondering what is the best way to convert shapes that have been drawn in quads to triangles without having to completely rewrite methods for rendering these shapes.

答:
Assuming you have a set of vertices {v1,v2,v3,v4,v5,...} and assuming you are passing a list of indices {i1,i2,i3,i4,i5,...} to the draw command, you simply need to pass a different index list.

Where you would have passed {i1,i2,i3,i4} before, you can now pass {i1,i2,i4,i4,i2,i3} to get two triangles covering the same quad. It gets more complicated if you want fans. You do the same process every four indices.

```
1 -- 2           1 -- 2
|    |  becomes  |  / |
|    |           | /  |
4 -- 3           4 -- 3
```

Body:
Assuming you have a set of vertices {v1,v2,v3,v4,v5,...} and assuming you are passing a list of indices {i1,i2,i3,i4,i5,...} to the draw command, you simply need to pass a different index list.

Where you would have passed {i1,i2,i3,i4} before, you can now pass {i1,i2,i4,i4,i2,i3} to get two triangles covering the same quad. It gets more complicated if you want fans. You do the same process every four indices.

1 -- 2           1 -- 2
|    |  becomes  |  / |
|    |           | /  |
4 -- 3           4 -- 3


问:
Basic festival program has undefined reference errors
I am currently trying to compile this basic festival program

```<code>#include <iostream>
#include <festival/festival.h>

#define HEAP_SIZE 210000
#define LOAD_INIT_FILES 1

using namespace std;

int main()
{
    festival_initialize(LOAD_INIT_FILES, HEAP_SIZE);

    festival_say_text("Hello World");

    festival_wait_for_spooler();

    return 0;
}
</code>```

When I try to build the program with g++, I get these errors:

```<code>speech_tools/lib/libestools.a $USER/Downloads/festival/speech_tools/lib/libeststring.a
$USER/Downloads/festival/speech_tools/lib/libestools.a(EST_PST.o): In function `EST_PredictionSuffixTree::test(EST_String)':
EST_PST.cc:(.text+0x2d30): undefined reference to `confusion(EST_TKVL<EST_String, EST_String>&, EST_TList<EST_String>&)'
EST_PST.cc:(.text+0x2d40): undefined reference to `print_confusion(EST_FMatrix const&, EST_TKVL<EST_String, EST_String>&, EST_TList<EST_String>&)'
$USER/Downloads/festival/speech_tools/lib/libestools.a(wfst_ops.o): In function `EST_WFST::determinize(EST_WFST const&)':
wfst_ops.cc:(.text+0x1136): undefined reference to `EST_THash<int, int>::EST_THash(int, unsigned int (*)(int const&, unsigned int))'
wfst_ops.cc:(.text+0x1206): undefined reference to `EST_THash<int, int>::val(int const&, int&) const'
wfst_ops.cc:(.text+0x122f): undefined reference to `EST_THash<int, int>::add_item(int const&, int const&, int)'
wfst_ops.cc:(.text+0x1568): undefined reference to `EST_THash<int, int>::~EST_THash()'
wfst_ops.cc:(.text+0x17d8): undefined reference to `EST_THash<int, int>::~EST_THash()'
$USER/Downloads/festival/speech_tools/lib/libestools.a(editline.o): In function `readline':
editline.c:(.text+0x7d2a): undefined reference to `tgetent'
editline.c:(.text+0x7d85): undefined reference to `tgetstr'
editline.c:(.text+0x7d9d): undefined reference to `tgetstr'
editline.c:(.text+0x7db5): undefined reference to `tgetstr'
editline.c:(.text+0x7dcd): undefined reference to `tgetstr'
editline.c:(.text+0x7e65): undefined reference to `tgetstr'
editline.c:(.text+0x7e87): undefined reference to `tgetnum'
editline.c:(.text+0x7e99): undefined reference to `tgetnum'
editline.c:(.text+0x7f21): undefined reference to `tgetstr'
collect2: error: ld returned 1 exit status
</code>```

As per http://festvox.org/docs/manual-2.4.0/festival_28.html#C_002fC_002b_002b-API, I added festival/src/include and speech_tools/include to the search path, in addition to linking with festival/src/lib/libFestival.a, speech_tools/lib/libestools.a, speech_tools/lib/libestbase.a, and speech_tools/lib/libeststring.a.

I am trying to build this on Arch Linux with g++ and festival 2.4.0.

EDIT:
Build command I'm using is

```<code>g++ -o bin/Debug/festival_test obj/Debug/main.o /usr/lib/libcurl.so /home/joshua/Downloads/festival/festival/src/lib/libFestival.a /home/joshua/Downloads/festival/speech_tools/lib/libestbase.a /home/joshua/Downloads/festival/speech_tools/lib/libestools.a /home/joshua/Downloads/festival/speech_tools/lib/libeststring.a
</code>```

I am using CodeBlocks so this is the default build command

EDIT 2:
Adding -lncurses to the build command eliminated the undefined reference errors relating to readline, but the other errors still persist

```<code>/home/joshua/Downloads/festival/speech_tools/lib/libestools.a(EST_PST.o): In function `EST_PredictionSuffixTree::test(EST_String)':
EST_PST.cc:(.text+0x2d30): undefined reference to `confusion(EST_TKVL<EST_String, EST_String>&, EST_TList<EST_String>&)'
EST_PST.cc:(.text+0x2d40): undefined reference to `print_confusion(EST_FMatrix const&, EST_TKVL<EST_String, EST_String>&, EST_TList<EST_String>&)'
/home/joshua/Downloads/festival/speech_tools/lib/libestools.a(wfst_ops.o): In function `EST_WFST::determinize(EST_WFST const&)':
wfst_ops.cc:(.text+0x1136): undefined reference to `EST_THash<int, int>::EST_THash(int, unsigned int (*)(int const&, unsigned int))'
wfst_ops.cc:(.text+0x1206): undefined reference to `EST_THash<int, int>::val(int const&, int&) const'
wfst_ops.cc:(.text+0x122f): undefined reference to `EST_THash<int, int>::add_item(int const&, int const&, int)'
wfst_ops.cc:(.text+0x1568): undefined reference to `EST_THash<int, int>::~EST_THash()'
wfst_ops.cc:(.text+0x17d8): undefined reference to `EST_THash<int, int>::~EST_THash()'
</code>```

EDIT 3:
Setting libestbase to link last fixed the error.

答:
It may be related to this bug report:
https://bugzilla.redhat.com/show_bug.cgi?id=499837

It suggests that you explicitly link in the ncurses library for the readline library that seems to be included by another of your libraries. So you would add:

```<code>-lncurses
</code>```

to your command.

Body:
I am currently trying to compile this basic festival program

#include <iostream>
#include <festival/festival.h>

#define HEAP_SIZE 210000
#define LOAD_INIT_FILES 1

using namespace std;

int main()
{
    festival_initialize(LOAD_INIT_FILES, HEAP_SIZE);

    festival_say_text("Hello World");

    festival_wait_for_spooler();

    return 0;
}

When I try to build the program with g++, I get these errors:

speech_tools/lib/libestools.a $USER/Downloads/festival/speech_tools/lib/libeststring.a
$USER/Downloads/festival/speech_tools/lib/libestools.a(EST_PST.o): In function `EST_PredictionSuffixTree::test(EST_String)':
EST_PST.cc:(.text+0x2d30): undefined reference to `confusion(EST_TKVL<EST_String, EST_String>&, EST_TList<EST_String>&)'
EST_PST.cc:(.text+0x2d40): undefined reference to `print_confusion(EST_FMatrix const&, EST_TKVL<EST_String, EST_String>&, EST_TList<EST_String>&)'
$USER/Downloads/festival/speech_tools/lib/libestools.a(wfst_ops.o): In function `EST_WFST::determinize(EST_WFST const&)':
wfst_ops.cc:(.text+0x1136): undefined reference to `EST_THash<int, int>::EST_THash(int, unsigned int (*)(int const&, unsigned int))'
wfst_ops.cc:(.text+0x1206): undefined reference to `EST_THash<int, int>::val(int const&, int&) const'
wfst_ops.cc:(.text+0x122f): undefined reference to `EST_THash<int, int>::add_item(int const&, int const&, int)'
wfst_ops.cc:(.text+0x1568): undefined reference to `EST_THash<int, int>::~EST_THash()'
wfst_ops.cc:(.text+0x17d8): undefined reference to `EST_THash<int, int>::~EST_THash()'
$USER/Downloads/festival/speech_tools/lib/libestools.a(editline.o): In function `readline':
editline.c:(.text+0x7d2a): undefined reference to `tgetent'
editline.c:(.text+0x7d85): undefined reference to `tgetstr'
editline.c:(.text+0x7d9d): undefined reference to `tgetstr'
editline.c:(.text+0x7db5): undefined reference to `tgetstr'
editline.c:(.text+0x7dcd): undefined reference to `tgetstr'
editline.c:(.text+0x7e65): undefined reference to `tgetstr'
editline.c:(.text+0x7e87): undefined reference to `tgetnum'
editline.c:(.text+0x7e99): undefined reference to `tgetnum'
editline.c:(.text+0x7f21): undefined reference to `tgetstr'
collect2: error: ld returned 1 exit status

As per http://festvox.org/docs/manual-2.4.0/festival_28.html#C_002fC_002b_002b-API, I added festival/src/include and speech_tools/include to the search path, in addition to linking with festival/src/lib/libFestival.a, speech_tools/lib/libestools.a, speech_tools/lib/libestbase.a, and speech_tools/lib/libeststring.a.

I am trying to build this on Arch Linux with g++ and festival 2.4.0.

EDIT:
Build command I'm using is

g++ -o bin/Debug/festival_test obj/Debug/main.o /usr/lib/libcurl.so /home/joshua/Downloads/festival/festival/src/lib/libFestival.a /home/joshua/Downloads/festival/speech_tools/lib/libestbase.a /home/joshua/Downloads/festival/speech_tools/lib/libestools.a /home/joshua/Downloads/festival/speech_tools/lib/libeststring.a

I am using CodeBlocks so this is the default build command

EDIT 2:
Adding -lncurses to the build command eliminated the undefined reference errors relating to readline, but the other errors still persist

/home/joshua/Downloads/festival/speech_tools/lib/libestools.a(EST_PST.o): In function `EST_PredictionSuffixTree::test(EST_String)':
EST_PST.cc:(.text+0x2d30): undefined reference to `confusion(EST_TKVL<EST_String, EST_String>&, EST_TList<EST_String>&)'
EST_PST.cc:(.text+0x2d40): undefined reference to `print_confusion(EST_FMatrix const&, EST_TKVL<EST_String, EST_String>&, EST_TList<EST_String>&)'
/home/joshua/Downloads/festival/speech_tools/lib/libestools.a(wfst_ops.o): In function `EST_WFST::determinize(EST_WFST const&)':
wfst_ops.cc:(.text+0x1136): undefined reference to `EST_THash<int, int>::EST_THash(int, unsigned int (*)(int const&, unsigned int))'
wfst_ops.cc:(.text+0x1206): undefined reference to `EST_THash<int, int>::val(int const&, int&) const'
wfst_ops.cc:(.text+0x122f): undefined reference to `EST_THash<int, int>::add_item(int const&, int const&, int)'
wfst_ops.cc:(.text+0x1568): undefined reference to `EST_THash<int, int>::~EST_THash()'
wfst_ops.cc:(.text+0x17d8): undefined reference to `EST_THash<int, int>::~EST_THash()'

EDIT 3:
Setting libestbase to link last fixed the error.

Body:
It may be related to this bug report:
https://bugzilla.redhat.com/show_bug.cgi?id=499837

It suggests that you explicitly link in the ncurses library for the readline library that seems to be included by another of your libraries. So you would add:

-lncurses

to your command.


问:
Play Framework and Docker production configuration
I use PlayFramework 2.6 with Docker. I build and publish image with sbt:dockerPublish and then deploy it with Ansible to Amazon EC2 Instance.
I want to get powerful instance for production and my question is:

Do I need to change configuration for docker and play to achieve best performance?

I want instance with 4 CPU cores and 16 GB RAM. I had issues before running Play on plain Ubuntu with 1GB RAM without swap, would I run into same memory issues with Docker even there will be 16GB?

答:
I'm not familiar with PlayFramework outside of the quick web search I just did to see it's a Java MVC thing, but a Docker container by default will use up as much memory and compute as your instance has. Which seems like it would be a good thing in this instance, you're worried about Docker being conservative and not utilizing a bigger EC2 instance.

You can place hard or soft limits on container memory usage: https://docs.docker.com/engine/admin/resource_constraints/#limit-a-containers-access-to-memory

Once you get the container running on your instance ssh in and run docker stats, and you can track the resource usage of the container.


问:
Is it 'safe' to permanently trust the Fiddler root certificate?
I'm looking to inspect HTTP traffic sent and received by a WFC client using Fiddler. To do this I've added the Fiddler Root Certificate to the Windows certificate store.

My question: is there are any risk of leaving this certificate in the Windows store ready for when I may need to test again? Could an attacker take advantage of the fact that it's there? Should I remove it once I've finished testing?

答: Corporate usage instructions I have seen at more than one client include the Cert removal step after Fiddler has been used. So the answer would definitely be a "Yes, do remove the certificate after use."</p>

ContentLicense: CC BY-SA 4.0


问:
Get second child using jQuery
```<code>$(t).html()
</code>```

returns

```<code><td>test1</td><td>test2</td>
</code>```

I want to retrieve the second td from the $(t) object. I searched for a solution but nothing worked for me. Any idea how to get the second element?

答:
In addition to using jQuery methods, you can use the native cells collection that the
 gives you.

```<code>$(t)[0].cells[1].innerHTML
</code>```

Assuming t is a DOM element, you could bypass the jQuery object creation.

```<code>t.cells[1].innerHTML
</code>```

Title: Get second child using jQuery

Body:
$(t).html()

returns

test1	test2

I want to retrieve the second td from the $(t) object. I searched for a solution but nothing worked for me. Any idea how to get the second element?

Body:
In addition to using jQuery methods, you can use the native cells collection that the <tr> gives you.

$(t)[0].cells[1].innerHTML

Assuming t is a DOM element, you could bypass the jQuery object creation.

t.cells[1].innerHTML


问:
Set SQL Server 'Maximum server memory in (MB)' using Powershell
I'm currently automating a VM and using a Powershell script to install SQL Server 2017.

I need to be able to script the Maximum server memory as well. Is this possible through the current configuration settings or will I need to create a custom script? If a custom script is required what would I need to do.

答:
You could use SQL (run from Powershell):

```<code>sp_configure 'show advanced options', 1;
RECONFIGURE;
sp_configure 'max server memory', 4096;
RECONFIGURE;
</code>```

or use PowerShell cmdlet from dbatools.io:

Set-DbaMaxMemory

explicitly set the max memory to 2048 MB on just one server, “sqlserver1”

```<code>Set-DbaMaxMemory -SqlServer sqlserver1 -MaxMb 2048
</code>```

Body:
You could use SQL (run from Powershell):

sp_configure 'show advanced options', 1;
RECONFIGURE;
sp_configure 'max server memory', 4096;
RECONFIGURE;

or use PowerShell cmdlet from dbatools.io:

Set-DbaMaxMemory

explicitly set the max memory to 2048 MB on just one server, “sqlserver1”

Set-DbaMaxMemory -SqlServer sqlserver1 -MaxMb 2048


问:
dividing all columns in pyspark SQL
I am new to Spark and this might be a straightforward problem.

I have a table in pyspark DF1, with a column name "A" and some other columns. The other column names might change in various cases. I want to generate a table DF2 by dividing the values of these "other" columns over A. The columns of DF2 would also be the "other" columns.

For example for

```<code>DF1 = sql_sc.createDataFrame([(1, 2,3), (2, 4,6), (3, 6,9), (4, 8,12), (5, 10,15)], ["A", "B","C"])
</code>```

The result would be a table as:

```<code> DF2 = sql_sc.createDataFrame([(2,3), (2,3), (2,3), (2,3), (2,3)], ["B","C"]
</code>```

How can I do this task in pyspark SQL ?

Thanks

答:
You can use DataFrame.columns to iterate over the columns and then just use the divide operator to perform your row-wise math. Like this:

```<code>from pyspark.sql.functions import col

DF1 = spark.createDataFrame([(1, 2,3), (2, 4,6), (3, 6,9), (4, 8,12), (5, 10,15)], ["A", "B","C"])
DF1.show()

df = DF1
for field in DF1.columns:
    if field != 'A':
        df = df.withColumn(field, col(field) / col("A"))

DF2 = df.drop('A')
DF2.show()
</code>```

Which outputs this:

```<code>+---+---+---+
|  A|  B|  C|
+---+---+---+
|  1|  2|  3|
|  2|  4|  6|
|  3|  6|  9|
|  4|  8| 12|
|  5| 10| 15|
+---+---+---+

+---+---+
|  B|  C|
+---+---+
|2.0|3.0|
|2.0|3.0|
|2.0|3.0|
|2.0|3.0|
|2.0|3.0|
+---+---+
</code>```

Title: dividing all columns in pyspark SQL

Body:
I am new to Spark and this might be a straightforward problem.

I have a table in pyspark DF1, with a column name "A" and some other columns. The other column names might change in various cases. I want to generate a table DF2 by dividing the values of these "other" columns over A. The columns of DF2 would also be the "other" columns.

For example for

DF1 = sql_sc.createDataFrame([(1, 2,3), (2, 4,6), (3, 6,9), (4, 8,12), (5, 10,15)], ["A", "B","C"])

The result would be a table as:

 DF2 = sql_sc.createDataFrame([(2,3), (2,3), (2,3), (2,3), (2,3)], ["B","C"]

How can I do this task in pyspark SQL ?

Thanks

Body:
You can use DataFrame.columns to iterate over the columns and then just use the divide operator to perform your row-wise math. Like this:

from pyspark.sql.functions import col

DF1 = spark.createDataFrame([(1, 2,3), (2, 4,6), (3, 6,9), (4, 8,12), (5, 10,15)], ["A", "B","C"])
DF1.show()

df = DF1
for field in DF1.columns:
    if field != 'A':
        df = df.withColumn(field, col(field) / col("A"))

DF2 = df.drop('A')
DF2.show()

Which outputs this:

+---+---+---+
|  A|  B|  C|
+---+---+---+
|  1|  2|  3|
|  2|  4|  6|
|  3|  6|  9|
|  4|  8| 12|
|  5| 10| 15|
+---+---+---+

+---+---+
|  B|  C|
+---+---+
|2.0|3.0|
|2.0|3.0|
|2.0|3.0|
|2.0|3.0|
|2.0|3.0|
+---+---+


问:
how can i add h3 code from asp.net behind code?
I want show a html code from "else", how can i?

this is my code

```<code>    if (output == "1")
    {

        Session["user"] = textuser.Text;
        Response.Redirect("~/Default2.aspx");
    }
    else
    {

        // show html code <h4  id='error1' runat ='server'></h4>
    }
</code>```

答:
You could add that control to the page, but with Visible=false

```<code><h4 id="error1" runat="server" Visible="false"></h4>
</code>```

And then you can just set make it visible from the code beside:

```<code>error1.Visible = true;
error1.InnerText = "Some message";
</code>```

Body:
I want show a html code from "else", how can i?

this is my code

    if (output == "1")
    {

        Session["user"] = textuser.Text;
        Response.Redirect("~/Default2.aspx");
    }
    else
    {

        // show html code

    }

Body:
You could add that control to the page, but with Visible=false

<h4 id="error1" runat="server" Visible="false"></h4>

And then you can just set make it visible from the code beside:

error1.Visible = true;
error1.InnerText = "Some message";


问:
Set selection from a list of indexes in a QTreeView
In PySide, is there a way to selected a few hundred treeview items without having to manually go row by row and select them? The problem with this method is the UI updates each time a new row is selected causing the application to freeze up while it finishes the method. Is there a way I can just pass the selection-model a list of all the rows I want selected?

My treeview has hundres of rows and four columns, but the treeview is set to select entire rows, not cells.

```<code>model = self.uiFilesList.model()
rows = self.selectedFileItems.selectedRows()
self.uiFilesList.selectionModel().clear()
</code>```

I would expect this to work, but it doesn't.

```<code>selection = self.uiFilesList.selectionModel().selection()
self.uiFilesList.selectionModel().clear()
mode = QtGui.QItemSelectionModel.Select | QtGui.QItemSelectionModel.Rows
self.uiFilesList.selectionModel().select(selection, mode)
</code>```

Here is my sample project where the selection is not updating after i update the data in the mode. You'll see in my sample below, when you right-click and change the age or the jersey number the list must be repopulated in order to update the displayed data. However i attempt to store the selection before updating the list. Then i try to restore it after the list is repopulated but it doesn't appear to work.

```<code>import sys, os, random
from PySide import QtGui, QtCore

class Person(object):

    def __init__(self, name, age, hair, jersey):
        self.name = name
        self.age = age
        self.hair = hair
        self.jersey = jersey

class MainWindow(QtGui.QMainWindow):
    def __init__(self, parent=None):
        super(MainWindow, self).__init__(parent)
        self.resize(500, 320)

        self.people = [
            Person('Kevin', 10, 'Brown', 20),
            Person('Marsha', 32, 'Blonde', 00),
            Person('Leslie', 27, 'Black', 15),
            Person('Tim', 53, 'Red', 37),
            Person('Marie', 65, 'Brown', 101),
            Person('Bella', 8, 'Blonde', 1)
        ]

        self.treeview = QtGui.QTreeView()
        self.treeview.setAlternatingRowColors(True)
        self.treeview.setModel(QtGui.QStandardItemModel())
        self.treeview.setSortingEnabled(True)
        self.treeview.setRootIsDecorated(False)
        self.treeview.setEditTriggers(QtGui.QAbstractItemView.NoEditTriggers)
        self.treeview.setSelectionBehavior(QtGui.QAbstractItemView.SelectRows)
        self.treeview.setSelectionMode(QtGui.QAbstractItemView.ExtendedSelection)
        self.treeview.setContextMenuPolicy(QtCore.Qt.CustomContextMenu)
        self.treeview.customContextMenuRequested.connect(self.open_menu)
        self.selectedItems = self.treeview.selectionModel()
        self.setCentralWidget(self.treeview)
        self.populate_list()

        # actions
        self.actRandomizeAges = QtGui.QAction('Randomize Ages', self)
        self.actRandomizeJerseys = QtGui.QAction('Randomize Jersey Numbers', self)

        # menu
        self.cmenu = QtGui.QMenu()
        self.cmenu.addAction(self.actRandomizeAges)
        self.cmenu.addAction(self.actRandomizeJerseys)

        # connections
        self.actRandomizeAges.triggered.connect(self.randomize_ages)
        self.actRandomizeJerseys.triggered.connect(self.randomize_jerseys)

    def open_menu(self, position):
        self.cmenu.exec_(self.treeview.viewport().mapToGlobal(position))

    def randomize_ages(self):
        rows = self.selectedItems.selectedRows()
        for i, item in enumerate(rows):
            obj = item.data(role=QtCore.Qt.UserRole)
            obj.age = random.randint(0, 70)
        self.populate_list()

    def randomize_jerseys(self):
        rows = self.selectedItems.selectedRows()
        for i, item in enumerate(rows):
            obj = item.data(role=QtCore.Qt.UserRole)
            obj.jersey = random.randint(1, 100)
        self.populate_list()

    def populate_list(self):
        selection = self.treeview.selectionModel().selection()
        flags = QtGui.QItemSelectionModel.Select
        self.treeview.selectionModel().clear()

        model = self.treeview.model()
        model.clear()
        model.setHorizontalHeaderLabels(['Name','Age','Hair', 'Jersey'])

        for p in self.people:
            # column 1
            col1 = QtGui.QStandardItem()
            col1.setData(p.name, role=QtCore.Qt.DisplayRole)
            col1.setData(p, role=QtCore.Qt.UserRole)
            # column 2
            col2 = QtGui.QStandardItem()
            col2.setData(p.age, role=QtCore.Qt.DisplayRole)
            if p.age > 30:
                col2.setData(QtGui.QBrush(QtGui.QColor(255,0,0,255)), role=QtCore.Qt.ForegroundRole)
            # column 3
            col3 = QtGui.QStandardItem()
            col3.setData(p.hair, role=QtCore.Qt.DisplayRole)
            # column 4
            col4 = QtGui.QStandardItem()
            col4.setData(p.jersey, role=QtCore.Qt.DisplayRole)
            if p.jersey > 30:
                col4.setData(QtGui.QBrush(QtGui.QColor(0,0,255,255)), role=QtCore.Qt.ForegroundRole)

            model.appendRow([col1, col2, col3, col4])

        self.treeview.selectionModel().select(selection, flags)

if __name__ == '__main__':
    app = QtGui.QApplication(sys.argv)
    ex = MainWindow()
    ex.show()
    sys.exit(app.exec_())
</code>```

答:
Your example doesn't work because it uses the wrong selection-flags. If you use QItemSelectionModel.Select alone, it will work correctly (and will select whole rows).

To set the selection from a list of indexes, you can create a series of QItemSelection objects which cover contiguous ranges, and merge them all into one selection.

Here is a demo script which shows how to do that:

```<code>import sys
from PySide import QtCore, QtGui

class Window(QtGui.QWidget):
    def __init__(self):
        super(Window, self).__init__()
        self.button = QtGui.QPushButton('Select')
        self.button.clicked.connect(self.handleButton)
        self.tree = QtGui.QTreeView()
        layout = QtGui.QVBoxLayout(self)
        layout.addWidget(self.tree)
        layout.addWidget(self.button)
        columns = 'One Two Three Four'.split()
        mod = QtGui.QStandardItemModel(self)
        mod.setHorizontalHeaderLabels(columns)
        for row in range(1000):
            mod.appendRow((
                QtGui.QStandardItem('A%s' % row),
                QtGui.QStandardItem('B%s' % row),
                QtGui.QStandardItem('C%s' % row),
                QtGui.QStandardItem('D%s' % row),
                ))
        self.tree.setModel(mod)
        self.tree.setSelectionMode(
            QtGui.QAbstractItemView.ExtendedSelection)

    def handleButton(self):
        mod = self.tree.model()
        columns = mod.columnCount() - 1
        flags = QtGui.QItemSelectionModel.Select
        selection = QtGui.QItemSelection()
        for start, end in ((2, 15), (25, 260), (500, 996)):
            start, end = mod.index(start, 0), mod.index(end, columns)
            if selection.indexes():
                selection.merge(QtGui.QItemSelection(start, end), flags)
            else:
                selection.select(start, end)
        self.tree.selectionModel().clear()
        self.tree.selectionModel().select(selection, flags)

if __name__ == '__main__':

    app = QtGui.QApplication(sys.argv)
    window = Window()
    window.setGeometry(700, 50, 500, 600)
    window.show()
    sys.exit(app.exec_())
</code>```

UPDATE:

The example in your question doesn't work because your populate_list method clears the model, which will invalidate all the indexes in the selection. So you need a method to save the current selection as a list of row-numbers (rather than model-indexes). This can then be fed to the method I gave above to re-create the selection.

If you update your example as follows, it should work as expected:

```<code>def save_selection(self):
    selection = self.treeview.selectionModel().selectedRows()
    blocks = []
    for count, index in enumerate(sorted(selection)):
        row = index.row()
        if count > 0 and row == block[1] + 1:
            block[1] = row
        else:
            block = [row, row]
            blocks.append(block)
    return blocks

def create_selection(self, blocks):
    mod = self.treeview.model()
    columns = mod.columnCount() - 1
    flags = QtGui.QItemSelectionModel.Select
    selection = QtGui.QItemSelection()
    for start, end in blocks:
        start, end = mod.index(start, 0), mod.index(end, columns)
        if selection.indexes():
            selection.merge(QtGui.QItemSelection(start, end), flags)
        else:
            selection.select(start, end)
    self.treeview.selectionModel().clear()
    self.treeview.selectionModel().select(selection, flags)

def populate_list(self):
    selection = self.save_selection()

    ... # re-populate model

    self.create_selection(selection)
</code>```

Body:
In PySide, is there a way to selected a few hundred treeview items without having to manually go row by row and select them? The problem with this method is the UI updates each time a new row is selected causing the application to freeze up while it finishes the method. Is there a way I can just pass the selection-model a list of all the rows I want selected?

My treeview has hundres of rows and four columns, but the treeview is set to select entire rows, not cells.

model = self.uiFilesList.model()
rows = self.selectedFileItems.selectedRows()
self.uiFilesList.selectionModel().clear()

I would expect this to work, but it doesn't.

selection = self.uiFilesList.selectionModel().selection()
self.uiFilesList.selectionModel().clear()
mode = QtGui.QItemSelectionModel.Select | QtGui.QItemSelectionModel.Rows
self.uiFilesList.selectionModel().select(selection, mode)

Here is my sample project where the selection is not updating after i update the data in the mode. You'll see in my sample below, when you right-click and change the age or the jersey number the list must be repopulated in order to update the displayed data. However i attempt to store the selection before updating the list. Then i try to restore it after the list is repopulated but it doesn't appear to work.

import sys, os, random
from PySide import QtGui, QtCore

class Person(object):

    def __init__(self, name, age, hair, jersey):
        self.name = name
        self.age = age
        self.hair = hair
        self.jersey = jersey

class MainWindow(QtGui.QMainWindow):
    def __init__(self, parent=None):
        super(MainWindow, self).__init__(parent)
        self.resize(500, 320)

        self.people = [
            Person('Kevin', 10, 'Brown', 20),
            Person('Marsha', 32, 'Blonde', 00),
            Person('Leslie', 27, 'Black', 15),
            Person('Tim', 53, 'Red', 37),
            Person('Marie', 65, 'Brown', 101),
            Person('Bella', 8, 'Blonde', 1)
        ]

        self.treeview = QtGui.QTreeView()
        self.treeview.setAlternatingRowColors(True)
        self.treeview.setModel(QtGui.QStandardItemModel())
        self.treeview.setSortingEnabled(True)
        self.treeview.setRootIsDecorated(False)
        self.treeview.setEditTriggers(QtGui.QAbstractItemView.NoEditTriggers)
        self.treeview.setSelectionBehavior(QtGui.QAbstractItemView.SelectRows)
        self.treeview.setSelectionMode(QtGui.QAbstractItemView.ExtendedSelection)
        self.treeview.setContextMenuPolicy(QtCore.Qt.CustomContextMenu)
        self.treeview.customContextMenuRequested.connect(self.open_menu)
        self.selectedItems = self.treeview.selectionModel()
        self.setCentralWidget(self.treeview)
        self.populate_list()

        # actions
        self.actRandomizeAges = QtGui.QAction('Randomize Ages', self)
        self.actRandomizeJerseys = QtGui.QAction('Randomize Jersey Numbers', self)

        # menu
        self.cmenu = QtGui.QMenu()
        self.cmenu.addAction(self.actRandomizeAges)
        self.cmenu.addAction(self.actRandomizeJerseys)

        # connections
        self.actRandomizeAges.triggered.connect(self.randomize_ages)
        self.actRandomizeJerseys.triggered.connect(self.randomize_jerseys)

    def open_menu(self, position):
        self.cmenu.exec_(self.treeview.viewport().mapToGlobal(position))

    def randomize_ages(self):
        rows = self.selectedItems.selectedRows()
        for i, item in enumerate(rows):
            obj = item.data(role=QtCore.Qt.UserRole)
            obj.age = random.randint(0, 70)
        self.populate_list()

    def randomize_jerseys(self):
        rows = self.selectedItems.selectedRows()
        for i, item in enumerate(rows):
            obj = item.data(role=QtCore.Qt.UserRole)
            obj.jersey = random.randint(1, 100)
        self.populate_list()

    def populate_list(self):
        selection = self.treeview.selectionModel().selection()
        flags = QtGui.QItemSelectionModel.Select
        self.treeview.selectionModel().clear()

        model = self.treeview.model()
        model.clear()
        model.setHorizontalHeaderLabels(['Name','Age','Hair', 'Jersey'])

        for p in self.people:
            # column 1
            col1 = QtGui.QStandardItem()
            col1.setData(p.name, role=QtCore.Qt.DisplayRole)
            col1.setData(p, role=QtCore.Qt.UserRole)
            # column 2
            col2 = QtGui.QStandardItem()
            col2.setData(p.age, role=QtCore.Qt.DisplayRole)
            if p.age > 30:
                col2.setData(QtGui.QBrush(QtGui.QColor(255,0,0,255)), role=QtCore.Qt.ForegroundRole)
            # column 3
            col3 = QtGui.QStandardItem()
            col3.setData(p.hair, role=QtCore.Qt.DisplayRole)
            # column 4
            col4 = QtGui.QStandardItem()
            col4.setData(p.jersey, role=QtCore.Qt.DisplayRole)
            if p.jersey > 30:
                col4.setData(QtGui.QBrush(QtGui.QColor(0,0,255,255)), role=QtCore.Qt.ForegroundRole)

            model.appendRow([col1, col2, col3, col4])

        self.treeview.selectionModel().select(selection, flags)

if __name__ == '__main__':
    app = QtGui.QApplication(sys.argv)
    ex = MainWindow()
    ex.show()
    sys.exit(app.exec_())

Body:
Your example doesn't work because it uses the wrong selection-flags. If you use QItemSelectionModel.Select alone, it will work correctly (and will select whole rows).

To set the selection from a list of indexes, you can create a series of QItemSelection objects which cover contiguous ranges, and merge them all into one selection.

Here is a demo script which shows how to do that:

import sys
from PySide import QtCore, QtGui

class Window(QtGui.QWidget):
    def __init__(self):
        super(Window, self).__init__()
        self.button = QtGui.QPushButton('Select')
        self.button.clicked.connect(self.handleButton)
        self.tree = QtGui.QTreeView()
        layout = QtGui.QVBoxLayout(self)
        layout.addWidget(self.tree)
        layout.addWidget(self.button)
        columns = 'One Two Three Four'.split()
        mod = QtGui.QStandardItemModel(self)
        mod.setHorizontalHeaderLabels(columns)
        for row in range(1000):
            mod.appendRow((
                QtGui.QStandardItem('A%s' % row),
                QtGui.QStandardItem('B%s' % row),
                QtGui.QStandardItem('C%s' % row),
                QtGui.QStandardItem('D%s' % row),
                ))
        self.tree.setModel(mod)
        self.tree.setSelectionMode(
            QtGui.QAbstractItemView.ExtendedSelection)

    def handleButton(self):
        mod = self.tree.model()
        columns = mod.columnCount() - 1
        flags = QtGui.QItemSelectionModel.Select
        selection = QtGui.QItemSelection()
        for start, end in ((2, 15), (25, 260), (500, 996)):
            start, end = mod.index(start, 0), mod.index(end, columns)
            if selection.indexes():
                selection.merge(QtGui.QItemSelection(start, end), flags)
            else:
                selection.select(start, end)
        self.tree.selectionModel().clear()
        self.tree.selectionModel().select(selection, flags)

if __name__ == '__main__':

    app = QtGui.QApplication(sys.argv)
    window = Window()
    window.setGeometry(700, 50, 500, 600)
    window.show()
    sys.exit(app.exec_())

UPDATE:

The example in your question doesn't work because your populate_list method clears the model, which will invalidate all the indexes in the selection. So you need a method to save the current selection as a list of row-numbers (rather than model-indexes). This can then be fed to the method I gave above to re-create the selection.

If you update your example as follows, it should work as expected:

def save_selection(self):
    selection = self.treeview.selectionModel().selectedRows()
    blocks = []
    for count, index in enumerate(sorted(selection)):
        row = index.row()
        if count > 0 and row == block[1] + 1:
            block[1] = row
        else:
            block = [row, row]
            blocks.append(block)
    return blocks

def create_selection(self, blocks):
    mod = self.treeview.model()
    columns = mod.columnCount() - 1
    flags = QtGui.QItemSelectionModel.Select
    selection = QtGui.QItemSelection()
    for start, end in blocks:
        start, end = mod.index(start, 0), mod.index(end, columns)
        if selection.indexes():
            selection.merge(QtGui.QItemSelection(start, end), flags)
        else:
            selection.select(start, end)
    self.treeview.selectionModel().clear()
    self.treeview.selectionModel().select(selection, flags)

def populate_list(self):
    selection = self.save_selection()

    ... # re-populate model

    self.create_selection(selection)


问:
Get the last object returned
Occasionally I execute a PowerShell command and I forget to store its return values/objects in a variable. Does PowerShell store the returned object of the last command in a variable I could access to?</p>

```<code>PS C:\> Get-ChildItem
...
PS C:\> # Oh no, I forgot to assign the output to a variable
PS C:\> $a = Get-ChildItem
PS C:\>
</code>```

答:
Currently on WMF 5.1, it looks like Out-Default is in a different namespace.

```<code>function Out-Default {
    $Input | Tee-Object -Var Global:LastOutput |
        Microsoft.PowerShell.Core\Out-Default
}
</code>```

Title: Get the last object returned

Body:
Occasionally I execute a PowerShell command and I forget to store its return values/objects in a variable. Does PowerShell store the returned object of the last command in a variable I could access to?

PS C:\> Get-ChildItem
...
PS C:\> # Oh no, I forgot to assign the output to a variable
PS C:\> $a = Get-ChildItem
PS C:\>

Body:
Currently on WMF 5.1, it looks like Out-Default is in a different namespace.

function Out-Default {
    $Input | Tee-Object -Var Global:LastOutput |
        Microsoft.PowerShell.Core\Out-Default
}


问:
Referencing file to HTML link
I am trying to link a previously saved blog post to my new site and am having no luck getting them to show up. It says file not found. Could someone let me know if I am leaving something out? My prior blog entries are saved in a folder called _posts, which is under a folder for my project, and the project is in another folder called developer.

This is how I have it right now:

```<code><p><a href="/_posts/2017-05-26_blog.html></a></p>
</br>

<p><a href="/_posts/2017-06-09_blog.html></a></p>
</code>```

答:
If you're using absolute paths, those prefixed with /, then you'll need to use some kind of server configured to have a proper "web root". If you're looking at these HTML files in your browser directly off of disk these links won't work.

There's a number of web development tools that allow you to quickly and easily spin up a server locally for this purpose.

Title: Referencing file to HTML link


问:
Mysql Query Slow on large table
Trying to run the following query on a mysql table that has over 3 million rows. Its very slow to the point it pretty much hangs until the script times out. Below is the query and the explain from that query, any suggestions?

```<code>SELECT SQL_CALC_FOUND_ROWS
listing_track.listingid,
listing_track.commid,
listing.listingname,
listing_package.packagename,
listing.active,
community.commname,
SUM( listing_track.impression ) AS listing_impressions,
SUM( listing_track.view ) AS listing_views,
SUM( listing_track.phone ) AS listing_phones,
SUM( listing_track.forward ) AS listing_forward,
SUM( listing_track.coupon ) AS listing_coupons,
SUM( listing_track.email ) AS listing_emails
FROM listing_track
INNER JOIN listing ON listing_track.listingid = listing.id
INNER JOIN community ON listing_track.commid = community.id
INNER JOIN listing_package ON listing.packageid = listing_package.id
WHERE listing_track.commid =2
GROUP BY listing_track.commid, listing_track.listingid, listing_track.trackip
LIMIT 0 , 25
</code>```

Here is the explain:

答:
```<code>SELECT  listing_track.listingid,
        listing_track.commid,
        listing.listingname,
        listing_package.packagename,
        listing.active,
        community.commname
        SUM( listing_track.impression ) AS listing_impressions,
        SUM( listing_track.view ) AS listing_views,
        SUM( listing_track.phone ) AS listing_phones,
        SUM( listing_track.forward ) AS listing_forward,
        SUM( listing_track.coupon ) AS listing_coupons,
        SUM( listing_track.email ) AS listing_emails
FROM    (
        SELECT  *
        FROM    listing
        ORDER BY
                id
        LIMIT 25
        ) l
JOIN    listing_track lt
ON      lt.listingid = l.id
        AND lt.commid = 2
JOIN    community c
ON      c.id = lt.commid
JOIN    listing_package lp
ON      lp.packageid = l.packageid
GROUP BY
        l.id, lt.trackip
LIMIT 25
</code>```

Create a composite index on listing_track (listingid, commid)

This optimization only works without SQL_CALC_FOUND_ROWS, since the latter requires scanning all records (as if the query was run without LIMIT clause).

In your plan I see one more table, account, which is not used in the query. You need to post the whole query since even one extra table can change everything.

Title: Mysql Query Slow on large table

Body:
Trying to run the following query on a mysql table that has over 3 million rows. Its very slow to the point it pretty much hangs until the script times out. Below is the query and the explain from that query, any suggestions?

SELECT SQL_CALC_FOUND_ROWS
listing_track.listingid,
listing_track.commid,
listing.listingname,
listing_package.packagename,
listing.active,
community.commname,
SUM( listing_track.impression ) AS listing_impressions,
SUM( listing_track.view ) AS listing_views,
SUM( listing_track.phone ) AS listing_phones,
SUM( listing_track.forward ) AS listing_forward,
SUM( listing_track.coupon ) AS listing_coupons,
SUM( listing_track.email ) AS listing_emails
FROM listing_track
INNER JOIN listing ON listing_track.listingid = listing.id
INNER JOIN community ON listing_track.commid = community.id
INNER JOIN listing_package ON listing.packageid = listing_package.id
WHERE listing_track.commid =2
GROUP BY listing_track.commid, listing_track.listingid, listing_track.trackip
LIMIT 0 , 25

Here is the explain:

Body:
SELECT  listing_track.listingid,
        listing_track.commid,
        listing.listingname,
        listing_package.packagename,
        listing.active,
        community.commname
        SUM( listing_track.impression ) AS listing_impressions,
        SUM( listing_track.view ) AS listing_views,
        SUM( listing_track.phone ) AS listing_phones,
        SUM( listing_track.forward ) AS listing_forward,
        SUM( listing_track.coupon ) AS listing_coupons,
        SUM( listing_track.email ) AS listing_emails
FROM    (
        SELECT  *
        FROM    listing
        ORDER BY
                id
        LIMIT 25
        ) l
JOIN    listing_track lt
ON      lt.listingid = l.id
        AND lt.commid = 2
JOIN    community c
ON      c.id = lt.commid
JOIN    listing_package lp
ON      lp.packageid = l.packageid
GROUP BY
        l.id, lt.trackip
LIMIT 25

Create a composite index on listing_track (listingid, commid)

This optimization only works without SQL_CALC_FOUND_ROWS, since the latter requires scanning all records (as if the query was run without LIMIT clause).

In your plan I see one more table, account, which is not used in the query. You need to post the whole query since even one extra table can change everything.


问:
JSoup can not parse a website
I am trying to get some data from a website. I make copy paste from my old program. But its not working. My code is below.

```<code>import java.io.IOException;
import javax.swing.JOptionPane;
import org.jsoup.Jsoup;
import org.jsoup.Connection.Response;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;

public class Veri {

    public static void main(String[] args) {

        Veri();

    }

    public static void Veri() {

        try {

            String url = "https://www.isyatirim.com.tr/tr-tr/analiz/hisse/Sayfalar/default.aspx";

            Response res = Jsoup.connect(url).timeout(6000).execute();

            Document doc = res.parse();
            Element ele = doc.select("table[class=dataTable hover nowrap excelexport data-tables no-footer]").first();

            for (int i = 0; i < 100; i++) {

                System.out.println(ele.select("td").iterator().next().text());

            }

        } catch (IOException c) {

            JOptionPane.showMessageDialog(null, "Veriler Alınırken Bir Harta Oluştu!");
            c.printStackTrace();
        }

    }

}
</code>```

I got the below error

Exception in thread "main" java.lang.NullPointerException      at
  Veri.Veri(Veri.java:37)    at Veri.main(Veri.java:20)

答:
The page has probably changed a little bit since you last used your program.
Try this:

```<code>import org.jsoup.Jsoup;
import org.jsoup.Connection.Response;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;

public class Veri {

    public static void main(String[] args) {

        Veri();

    }

    public static void Veri() {

        try {

            String url = "https://www.isyatirim.com.tr/tr-tr/analiz/hisse/Sayfalar/default.aspx";

            Response res = Jsoup.connect(url).timeout(6000).execute();

            Document doc = res.parse();
            Element ele = doc.select("table[class=dataTable hover nowrap excelexport]").first();
            Elements lines = ele.select("tr");
            for (Element elt : lines) {
                System.out.println(elt.text());
                System.out.println("------------------------");
            }

        } catch (IOException c) {

            JOptionPane.showMessageDialog(null, "Veriler Alınırken Bir Harta Oluştu!");
            c.printStackTrace();
        }

    }

}
</code>```

I think you get all the information needed this way.

Title: JSoup can not parse a website

Body:
I am trying to get some data from a website. I make copy paste from my old program. But its not working. My code is below.

import java.io.IOException;
import javax.swing.JOptionPane;
import org.jsoup.Jsoup;
import org.jsoup.Connection.Response;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;

public class Veri {

    public static void main(String[] args) {

        Veri();

    }

    public static void Veri() {

        try {

            String url = "https://www.isyatirim.com.tr/tr-tr/analiz/hisse/Sayfalar/default.aspx";

            Response res = Jsoup.connect(url).timeout(6000).execute();

            Document doc = res.parse();
            Element ele = doc.select("table[class=dataTable hover nowrap excelexport data-tables no-footer]").first();

            for (int i = 0; i < 100; i++) {

                System.out.println(ele.select("td").iterator().next().text());

            }

        } catch (IOException c) {

            JOptionPane.showMessageDialog(null, "Veriler Alınırken Bir Harta Oluştu!");
            c.printStackTrace();
        }

    }

}

I got the below error

Exception in thread "main" java.lang.NullPointerException      at
  Veri.Veri(Veri.java:37)    at Veri.main(Veri.java:20)

Body:
The page has probably changed a little bit since you last used your program.
Try this:

import org.jsoup.Jsoup;
import org.jsoup.Connection.Response;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;

public class Veri {

    public static void main(String[] args) {

        Veri();

    }

    public static void Veri() {

        try {

            String url = "https://www.isyatirim.com.tr/tr-tr/analiz/hisse/Sayfalar/default.aspx";

            Response res = Jsoup.connect(url).timeout(6000).execute();

            Document doc = res.parse();
            Element ele = doc.select("table[class=dataTable hover nowrap excelexport]").first();
            Elements lines = ele.select("tr");
            for (Element elt : lines) {
                System.out.println(elt.text());
                System.out.println("------------------------");
            }

        } catch (IOException c) {

            JOptionPane.showMessageDialog(null, "Veriler Alınırken Bir Harta Oluştu!");
            c.printStackTrace();
        }

    }

}

I think you get all the information needed this way.