问:
Access denied for user 'root'@'localhost' (using password: YES) in Visual Studio
Kindly bear with me. I am a Microsoft SQL Server person with loads of Visual Studio experience, but I need to get something done using a MySQL database.

I am trying to create a little tool here that will allow our developers to quickly update database records, and I am using Visual Studio to create a small Windows Form to do this.

In a Microsoft SQL Server connection string, I could write something like this:

```<code>Server=myServerAddress;Database=myDataBase;User Id=username;Password=password;
</code>```

In a MySQL connection string, there appear to be multiple other options, but the first one looks basically the same:

```<code>Server=myServerAddress;Database=myDataBase;Uid=username;Pwd=password;
</code>```

When I attempt to open the MySQL connection from my PC, I get the exception listed in the title (actually, it shows the Uid value and the IP Address of my PC instead of localhost, but I am hoping more people will recognize the error easier this way):

```<code>public static void MySQLi_Connect() {
  m_err = null;
  var str = Properties.Settings.Default.ConnStr;
  try {
    m_conn = new MySqlConnection(Properties.Settings.Default.ConnStr);
    m_conn.Open();
  } catch (MySqlException err) {
    ErrorLog("MySQLi_Connect", err);
  }
}
</code>```

I did a search, and it seems that the Uid on MySQL needs to be granted access from the specific IP Address that the connection is being made from.

Further, I found this on the mysql.com doc pages:

If you do not know the IP address or host name of the machine from which you are connecting, you should put a row with '%' as the Host column value in the user table. After trying to connect from the client machine, use a SELECT USER() query to see how you really did connect. Then change the '%' in the user table row to the actual host name that shows up in the log. Otherwise, your system is left insecure because it permits connections from any host for the given user name.

A few things:

It looks like I can connect to MySQL by using a % setting in the Uid jp2code, but MySQL says I need to change that back right away to remove system vulnerability.

Microsoft SQL Server did not seem to require this - or, if it did, I simply never was slapped in the face with this vulnerability issue like MySQL is doing.

Now, I ask:

If this is going to be a tool used by different developers on different PCs, is it common practice to turn the blind eye to this horrendous system vulnerability?

Is this not really as big of a concern as MySQL is making it appear?

What is the best way to continue with a Windows Forms application that needs to connect from various locations? Obviously, I do not want to continuously be adding more entries for a particular application every time another developer wants to use the tool or someone tries to run it from a different PC.

答:
Like OP says you can wildcard the hostname portion. I used this on our dev-server (not recommended for production servers):

```<code>update mysql.user set host = '%' where host='localhost';
</code>```

Then I had to restart the server to make MySQL use it (propably I could just have restarted the MySQL service).

Body:
Kindly bear with me. I am a Microsoft SQL Server person with loads of Visual Studio experience, but I need to get something done using a MySQL database.

I am trying to create a little tool here that will allow our developers to quickly update database records, and I am using Visual Studio to create a small Windows Form to do this.

In a Microsoft SQL Server connection string, I could write something like this:

Server=myServerAddress;Database=myDataBase;User Id=username;Password=password;

In a MySQL connection string, there appear to be multiple other options, but the first one looks basically the same:

Server=myServerAddress;Database=myDataBase;Uid=username;Pwd=password;

When I attempt to open the MySQL connection from my PC, I get the exception listed in the title (actually, it shows the Uid value and the IP Address of my PC instead of localhost, but I am hoping more people will recognize the error easier this way):

public static void MySQLi_Connect() {
  m_err = null;
  var str = Properties.Settings.Default.ConnStr;
  try {
    m_conn = new MySqlConnection(Properties.Settings.Default.ConnStr);
    m_conn.Open();
  } catch (MySqlException err) {
    ErrorLog("MySQLi_Connect", err);
  }
}

I did a search, and it seems that the Uid on MySQL needs to be granted access from the specific IP Address that the connection is being made from.

Further, I found this on the mysql.com doc pages:

If you do not know the IP address or host name of the machine from which you are connecting, you should put a row with '%' as the Host column value in the user table. After trying to connect from the client machine, use a SELECT USER() query to see how you really did connect. Then change the '%' in the user table row to the actual host name that shows up in the log. Otherwise, your system is left insecure because it permits connections from any host for the given user name.

A few things:

It looks like I can connect to MySQL by using a % setting in the Uid jp2code, but MySQL says I need to change that back right away to remove system vulnerability.

Microsoft SQL Server did not seem to require this - or, if it did, I simply never was slapped in the face with this vulnerability issue like MySQL is doing.

Now, I ask:

If this is going to be a tool used by different developers on different PCs, is it common practice to turn the blind eye to this horrendous system vulnerability?

Is this not really as big of a concern as MySQL is making it appear?

What is the best way to continue with a Windows Forms application that needs to connect from various locations? Obviously, I do not want to continuously be adding more entries for a particular application every time another developer wants to use the tool or someone tries to run it from a different PC.

Body:
Like OP says you can wildcard the hostname portion. I used this on our dev-server (not recommended for production servers):

update mysql.user set host = '%' where host='localhost';

Then I had to restart the server to make MySQL use it (propably I could just have restarted the MySQL service).


来源: stackexchange

问:
Spliting line to array of words
I'm finding the longest and shortest word in the txt.file.
But I always take result

```<code>File Path: there it's ok.
The longest word: *empty*
The shortest word: *empty*
Task complete...
</code>```

Code:

```<code>        List<String> lines = Files.readAllLines(Paths.get(fileName), StandardCharsets.UTF_8);
        String max = "", min = "BlaBlaBlaBlaBlaBlaBla";
        // We take a single line
        for(String line: lines){
            // Break the next line through the regular to an array of words
            List<String> words = Arrays.asList(line.split("\\P{Punct}\\P{Space}"));
            String tempMax = Collections.max(words);
            max = max.length() < tempMax.length() ? tempMax : max;
            String tempMin = Collections.min(words);
            min = min.length() > tempMin.length() ? tempMin : min;
        }

        textArea.setText(String.format(
                "File Path: %s\n" +
                        "The longest word: %s\n" +
                        "The shortest word: %s\n" +
                        "Task complete...", fileName, max, min));
</code>```

Give a hint)

答:
Regex pattern used is not correct and also use Comparator to get the result</p>

```<code>List<String> lines = Files.readAllLines(Paths.get(fileName), StandardCharsets.UTF_8);
String max = "", min = "";
List<String> words = new ArrayList<String>();
// We take a single line
for(String line: lines){
    // Break the next line through the regular to an array of words
    words.addAll(Arrays.asList(line.split("[\\p{Punct}\\s]+")));
}

Comparator<String> stringComparator = new Comparator<String>() {
    @Override
    public int compare(String o1, String o2) {
        return Integer.valueOf(o1.length()).compareTo(Integer.valueOf(o2.length()));
    }
};

max = Collections.max(words,stringComparator);
min = Collections.min(words,stringComparator);

textArea.setText(String.format("File Path: %s\n" +"The longest word: %s\n" +"The shortest word: %s\n" +"Task complete...", fileName, max, min));
</code>```

ContentLicense: CC BY-SA 3.0

Title: Spliting line to array of words

Body:
I'm finding the longest and shortest word in the txt.file.
But I always take result

File Path: there it's ok.
The longest word: *empty*
The shortest word: *empty*
Task complete...

Code:

        List<String> lines = Files.readAllLines(Paths.get(fileName), StandardCharsets.UTF_8);
        String max = "", min = "BlaBlaBlaBlaBlaBlaBla";
        // We take a single line
        for(String line: lines){
            // Break the next line through the regular to an array of words
            List<String> words = Arrays.asList(line.split("\\P{Punct}\\P{Space}"));
            String tempMax = Collections.max(words);
            max = max.length() < tempMax.length() ? tempMax : max;
            String tempMin = Collections.min(words);
            min = min.length() > tempMin.length() ? tempMin : min;
        }

        textArea.setText(String.format(
                "File Path: %s\n" +
                        "The longest word: %s\n" +
                        "The shortest word: %s\n" +
                        "Task complete...", fileName, max, min));

Give a hint)

Body:
Regex pattern used is not correct and also use Comparator to get the result

List<String> lines = Files.readAllLines(Paths.get(fileName), StandardCharsets.UTF_8);
String max = "", min = "";
List<String> words = new ArrayList<String>();
// We take a single line
for(String line: lines){
    // Break the next line through the regular to an array of words
    words.addAll(Arrays.asList(line.split("[\\p{Punct}\\s]+")));
}

Comparator<String> stringComparator = new Comparator<String>() {
    @Override
    public int compare(String o1, String o2) {
        return Integer.valueOf(o1.length()).compareTo(Integer.valueOf(o2.length()));
    }
};

max = Collections.max(words,stringComparator);
min = Collections.min(words,stringComparator);

textArea.setText(String.format("File Path: %s\n" +"The longest word: %s\n" +"The shortest word: %s\n" +"Task complete...", fileName, max, min));


问:
How (if at all) could rounding Decimals improve performance?
I am curious when I am doing any sort of math on a a bunch of decimals in my Spark program does it make any difference to round numbers beforehand? For instance does:

3.000009481 * 10.90001001010

Calculate the same time as something like:

3.000 * 10.900

Does it differ for multiplication, division, and more advanced things like power and square root etc?

I am wondering because lets say its a fraction of a millisecond when you are doing it on millions of numbers does it make sense to round? Or will you always get the same calculation times with decimals?

I have a large aggregateByKey function that is doing a lot of computation. The cluster I am on consistently provides inconsistent performance metrics.

答:
Spark SQL's Optimizer uses DecimalAggregates logical optimization that replaces Decimal-based calculations with optimized operators when the precision is smaller than:

9 for sum aggregate function, e.g. "SELECT sum(cast(id AS DECIMAL(5,0))) FROM range(1)"

12 for avg aggregate function, e.g. "SELECT avg(cast(id AS DECIMAL(10,0))) FROM range(1)"

See functions object for sum and avg.

So, in case of structured queries in Spark SQL, it does make sense to round if you can (explicitly or by using a schema with correct types).


问:
Managing video stream buffering in Android
I have an issue with streaming video file via HTTP. VideoView is used.

And I have noticed that buffer percentage decrease when seeking back. Also I have noticed that video start downloading once again if it is replaying.

Is it possible to provide some kind of cache for video buffer. And how to do this?

答: You can download/stream large file into small chunk of files. Play these chunk files one by one. In this case you should make proper use of MediaPlayer. - thanks</p>

ContentLicense: CC BY-SA 2.5


问:
Compatibility issues between typedefs
I am using BOOST_STRONG_TYPEDEF to prevent misuses of different string-based ID types. I am however running into compatibility problems between the original type and its typedef.

I have an std::string which contains a list of IDs, separated by commas. I need to store them into a set. The code would look like:

```<code>#include <boost/algorithm/string/split.hpp>
#include <boost/serialization/strong_typedef.hpp>
#include <boost/algorithm/string/classification.hpp>

#include <set>
#include <vector>

BOOST_STRONG_TYPEDEF(std::string, MY_ID)

int main()
{
    std::string line("ID1,ID2,ID3");

    // Use boost::split to get all the strings into a vector
    std::vector<std::string> id_vec;
    boost::split(id_vec, line, boost::is_any_of(","));

    // Generate a set of MY_ID. Do not use range constructor since the compiler
    // error is clearer this way
    std::set<MY_ID> ids;
    for (auto const & id : id_vec)
    {
        ids.insert(id);
    }
}
</code>```

This doesn't compile, since std::string cannot be inserted into a std::set<MY_ID>. However, if I declared the vector to be of type std::vector<MY_ID> it would not work with boost::split.

I have found a work around by adding a temporal variable when inserting:

```<code>for (auto const & id : id_vec)
{
    MY_ID tmp(id);
    ids.insert(tmp);
}
</code>```

This works but seems hacky. Is there a more concise way?

答:
The whole point of strong typedefs is to require an explicit conversion when creating the strong typedef out of its underlying type. So use an explicit conversion syntax:

```<code>for (auto const & id : id_vec)
{
    ids.insert(MY_ID{id});
}
</code>```

Alternative ways to do the conversion are static_cast<MY_ID>(id) and MY_ID(id) (note that the latter is equivalent to the C-style cast (MY_ID)id and is thus best avoided).

Title: Compatibility issues between typedefs

Body:
I am using BOOST_STRONG_TYPEDEF to prevent misuses of different string-based ID types. I am however running into compatibility problems between the original type and its typedef.

I have an std::string which contains a list of IDs, separated by commas. I need to store them into a set. The code would look like:

#include <boost/algorithm/string/split.hpp>
#include <boost/serialization/strong_typedef.hpp>
#include <boost/algorithm/string/classification.hpp>

#include <set>
#include <vector>

BOOST_STRONG_TYPEDEF(std::string, MY_ID)

int main()
{
    std::string line("ID1,ID2,ID3");

    // Use boost::split to get all the strings into a vector
    std::vector<std::string> id_vec;
    boost::split(id_vec, line, boost::is_any_of(","));

    // Generate a set of MY_ID. Do not use range constructor since the compiler
    // error is clearer this way
    std::set<MY_ID> ids;
    for (auto const & id : id_vec)
    {
        ids.insert(id);
    }
}

This doesn't compile, since std::string cannot be inserted into a std::set<MY_ID>. However, if I declared the vector to be of type std::vector<MY_ID> it would not work with boost::split.

I have found a work around by adding a temporal variable when inserting:

for (auto const & id : id_vec)
{
    MY_ID tmp(id);
    ids.insert(tmp);
}

This works but seems hacky. Is there a more concise way?

Body:
The whole point of strong typedefs is to require an explicit conversion when creating the strong typedef out of its underlying type. So use an explicit conversion syntax:

for (auto const & id : id_vec)
{
    ids.insert(MY_ID{id});
}

Alternative ways to do the conversion are static_cast<MY_ID>(id) and MY_ID(id) (note that the latter is equivalent to the C-style cast (MY_ID)id and is thus best avoided).


问:
Find existing object into an array in nodejs
Hi this is my collection i just want to look userId into subcriber array if both userId exist into the subcriber array than not create new collection return same channelId. If both userId not exist into subcriber array then create new document how can i search userids in an array.
this is my collection.

```<code>{
"_id" : ObjectId("58dd1013e973fc0004743443"),
"createdAt" : ISODate("2017-03-30T14:02:59.175Z"),
"updatedAt" : ISODate("2017-03-30T14:02:59.175Z"),
"timestamp" : "2017-03-30",
"channelId" : "CH-EU7D",
"createdById" : "58dcc3cd9a7a301308b62857",
"message" : "",
"subcriber" : [
    {
        "userId" : "58dcc3cd9a7a301308b62857",
        "channelId" : "CH-EU7D",
        "_id" : ObjectId("58dd1013e973fc0004743444"),
        "status" : "accepted"
    },
    {
        "userId" : "58dcc3ec9a7a301308b62859",
        "channelId" : "CH-EU7D",
        "_id" : ObjectId("58dd1013e973fc0004743445"),
        "status" : "pending"
    }
],
"__v" : 0
</code>```

}

I have tried this but not working.

```<code>Channel.find({ 'subcriber.userId': b.userId }, { $and: [{ 'subcriber.userId': b.friendId }] }
</code>```

答:
In nodejs you can use JavaScript Array.prototype.some() method with your json array to test if there's any matching useId, you will need to write something like:

```<code>function checkUserId(array, userId) {
  return array.some(function(element) {
    return userId === element.userId;
  });
}
</code>```

This is a Demo snippet:

function checkUserId(array, userId) {
  return array.some(function(element) {
    return userId === element.userId;
  });
}

var json = {
  "_id": "58dd1013e973fc0004743443",
  "createdAt": "2017-03-30T14:02:59.175Z",
  "updatedAt": "2017-03-30T14:02:59.175Z",
  "timestamp": "2017-03-30",
  "channelId": "CH-EU7D",
  "createdById": "58dcc3cd9a7a301308b62857",
  "message": "",
  "subcriber": [{
      "userId": "58dcc3cd9a7a301308b62857",
      "channelId": "CH-EU7D",
      "_id": "58dd1013e973fc0004743444",
      "status": "accepted"
    },
    {
      "userId": "58dcc3ec9a7a301308b62859",
      "channelId": "CH-EU7D",
      "_id": "58dd1013e973fc0004743445",
      "status": "pending"
    }
  ]
};

//Check an existing userId
console.log(checkUserId(json.subcriber, "58dcc3ec9a7a301308b62859"));

//Check a non existing userId
console.log(checkUserId(json.subcriber, "58dcc3ec9a7a3000000000859"));```

Body:
Hi this is my collection i just want to look userId into subcriber array if both userId exist into the subcriber array than not create new collection return same channelId. If both userId not exist into subcriber array then create new document how can i search userids in an array.
this is my collection.

{
"_id" : ObjectId("58dd1013e973fc0004743443"),
"createdAt" : ISODate("2017-03-30T14:02:59.175Z"),
"updatedAt" : ISODate("2017-03-30T14:02:59.175Z"),
"timestamp" : "2017-03-30",
"channelId" : "CH-EU7D",
"createdById" : "58dcc3cd9a7a301308b62857",
"message" : "",
"subcriber" : [
    {
        "userId" : "58dcc3cd9a7a301308b62857",
        "channelId" : "CH-EU7D",
        "_id" : ObjectId("58dd1013e973fc0004743444"),
        "status" : "accepted"
    },
    {
        "userId" : "58dcc3ec9a7a301308b62859",
        "channelId" : "CH-EU7D",
        "_id" : ObjectId("58dd1013e973fc0004743445"),
        "status" : "pending"
    }
],
"__v" : 0

}

I have tried this but not working.

Channel.find({ 'subcriber.userId': b.userId }, { $and: [{ 'subcriber.userId': b.friendId }] }

Body:
In nodejs you can use JavaScript Array.prototype.some() method with your json array to test if there's any matching useId, you will need to write something like:

function checkUserId(array, userId) {
  return array.some(function(element) {
    return userId === element.userId;
  });
}

This is a Demo snippet:

function checkUserId(array, userId) {
  return array.some(function(element) {
    return userId === element.userId;
  });
}

var json = {
  "_id": "58dd1013e973fc0004743443",
  "createdAt": "2017-03-30T14:02:59.175Z",
  "updatedAt": "2017-03-30T14:02:59.175Z",
  "timestamp": "2017-03-30",
  "channelId": "CH-EU7D",
  "createdById": "58dcc3cd9a7a301308b62857",
  "message": "",
  "subcriber": [{
      "userId": "58dcc3cd9a7a301308b62857",
      "channelId": "CH-EU7D",
      "_id": "58dd1013e973fc0004743444",
      "status": "accepted"
    },
    {
      "userId": "58dcc3ec9a7a301308b62859",
      "channelId": "CH-EU7D",
      "_id": "58dd1013e973fc0004743445",
      "status": "pending"
    }
  ]
};

//Check an existing userId
console.log(checkUserId(json.subcriber, "58dcc3ec9a7a301308b62859"));

//Check a non existing userId
console.log(checkUserId(json.subcriber, "58dcc3ec9a7a3000000000859"));


问:
Is it possible to train the ranker of Watson's Retrieve and Rank model on other features?
Can I get personalized results from the R&R service? i.e. train the model using demographics and user features instead of Q&A pairs</p>

答:
Yes, you can use custom features.

Exactly how to do that is too complex to sensibly fit into an answer here, but there is a detailed explanation (with links to sample code) at https://medium.com/machine-learning-with-ibm-watson/developing-with-ibm-watson-retrieve-and-rank-part-3-custom-features-826fe88a5c63

Hope that helps!


问:
Difference between struct static func vs class static func in swift?
I am not able to find any difference between class static function to struct static function. As I know class static function can not be inherited and struct does not have an option for inheritance.

Please do not get confused by static func and class func in class.

```<code>class a {
    static func myMethod1() {
    }
}
</code>```

vs

```<code>struct a {
    static func myMethod1() {
    }
}
</code>```

答:
These link may help you to understand the functions. As @mipadi says (emphasis mine):

static and class both associate a method with a class, rather than an
  instance of a class. The difference is that subclasses can override
  class methods; they cannot override static methods.

class properties will theoretically function in the same way
  (subclasses can override them), but they're not possible in Swift yet.

What is the difference between static func and class func in Swift?

Static vs class functions/variables in Swift classes?

Body:
I am not able to find any difference between class static function to struct static function. As I know class static function can not be inherited and struct does not have an option for inheritance.

Please do not get confused by static func and class func in class.

class a {
    static func myMethod1() {
    }
}

vs

struct a {
    static func myMethod1() {
    }
}


问:
Java Web Start application gets unrestricted access but still asks for permission
I have a Java Web Start (Java 8u121) application that should  run with full access on the users system.

All requirements to run with full access have been taken, basically we are using webstart-maven-plugin to sign the full application (all jars) with an official certificate. The JNLP requests 'all-permissions'. This also sets several properties to the MANIFEST.MF in each jar.

When I start the application (see image) it requests 'unrestricted access'.

When running the application, it tries to download a few images from another webserver, this always causes the following dialog:

The stacktrace of the thread showing the dialog is as follows:

```<code>  java.lang.Thread.State: WAITING (on object monitor)
    at java.lang.Object.wait(Native Method)
    at java.lang.Object.wait(Unknown Source)
    at com.sun.javaws.ui.JavawsSysRun.delegate(Unknown Source)
    - locked <0x0000000081e16908> (a java.lang.Object)
    at com.sun.deploy.util.DeploySysRun.execute(Unknown Source)
    at com.sun.deploy.util.DeploySysRun$1.run(Unknown Source)
    at java.security.AccessController.doPrivileged(Native Method)
    at com.sun.deploy.util.DeploySysRun.executePrivileged(Unknown Source)
    at com.sun.deploy.ui.UIFactory.showApiDialog(Unknown Source)
    at com.sun.deploy.uitoolkit.impl.awt.ui.UIFactoryImpl.showMessageDialog(Unknown Source)
    at com.sun.deploy.uitoolkit.impl.awt.ui.UIFactoryImpl.showMessageDialog(Unknown Source)
    at com.sun.jnlp.ApiDialog.askUser(Unknown Source)
    at com.sun.jnlp.ApiDialog.askUser(Unknown Source)
    at com.sun.jnlp.ApiDialog.askConnect(Unknown Source)
    at com.sun.javaws.security.JavaWebStartSecurity.checkURLPermissionHelper(Unknown Source)
    at com.sun.javaws.security.JavaWebStartSecurity.checkPermission(Unknown Source)
    at sun.net.www.protocol.http.HttpURLConnection.URLtoSocketPermission(Unknown Source)

...

    at java.util.concurrent.CompletableFuture$AsyncSupply.run(Unknown Source)
    at java.util.concurrent.CompletableFuture$AsyncSupply.exec(Unknown Source)
    at java.util.concurrent.ForkJoinTask.doExec(Unknown Source)
    at java.util.concurrent.ForkJoinPool$WorkQueue.runTask(Unknown Source)
    at java.util.concurrent.ForkJoinPool.runWorker(Unknown Source)
    at java.util.concurrent.ForkJoinWorkerThread.run(Unknown Source)
</code>```

The biggest problem with this is that the dialog asking for permission often appears behind our main screen (but it will still block input to the main screen).

I have been able to trace this problem to the ForkJoinPool. Which apparently always runs with extra protection. See this post by Doug Lea.

What is the best way to disable this? I would prefer this to be an application wide solution.

答:
I see two solutions to this.

First of all you can use AccessController.doPriviledged() inside the task running on the ForkJoinPool.

Alternatively you can disable the SecurityManager for your full application by calling System.setSecurityManager(null) at the start of your application (outside the code running on the ForkJoinPool.

Body:
I have a Java Web Start (Java 8u121) application that should  run with full access on the users system.

All requirements to run with full access have been taken, basically we are using webstart-maven-plugin to sign the full application (all jars) with an official certificate. The JNLP requests 'all-permissions'. This also sets several properties to the MANIFEST.MF in each jar.

When I start the application (see image) it requests 'unrestricted access'.

When running the application, it tries to download a few images from another webserver, this always causes the following dialog:

The stacktrace of the thread showing the dialog is as follows:

  java.lang.Thread.State: WAITING (on object monitor)
    at java.lang.Object.wait(Native Method)
    at java.lang.Object.wait(Unknown Source)
    at com.sun.javaws.ui.JavawsSysRun.delegate(Unknown Source)
    - locked <0x0000000081e16908> (a java.lang.Object)
    at com.sun.deploy.util.DeploySysRun.execute(Unknown Source)
    at com.sun.deploy.util.DeploySysRun$1.run(Unknown Source)
    at java.security.AccessController.doPrivileged(Native Method)
    at com.sun.deploy.util.DeploySysRun.executePrivileged(Unknown Source)
    at com.sun.deploy.ui.UIFactory.showApiDialog(Unknown Source)
    at com.sun.deploy.uitoolkit.impl.awt.ui.UIFactoryImpl.showMessageDialog(Unknown Source)
    at com.sun.deploy.uitoolkit.impl.awt.ui.UIFactoryImpl.showMessageDialog(Unknown Source)
    at com.sun.jnlp.ApiDialog.askUser(Unknown Source)
    at com.sun.jnlp.ApiDialog.askUser(Unknown Source)
    at com.sun.jnlp.ApiDialog.askConnect(Unknown Source)
    at com.sun.javaws.security.JavaWebStartSecurity.checkURLPermissionHelper(Unknown Source)
    at com.sun.javaws.security.JavaWebStartSecurity.checkPermission(Unknown Source)
    at sun.net.www.protocol.http.HttpURLConnection.URLtoSocketPermission(Unknown Source)

...

    at java.util.concurrent.CompletableFuture$AsyncSupply.run(Unknown Source)
    at java.util.concurrent.CompletableFuture$AsyncSupply.exec(Unknown Source)
    at java.util.concurrent.ForkJoinTask.doExec(Unknown Source)
    at java.util.concurrent.ForkJoinPool$WorkQueue.runTask(Unknown Source)
    at java.util.concurrent.ForkJoinPool.runWorker(Unknown Source)
    at java.util.concurrent.ForkJoinWorkerThread.run(Unknown Source)

The biggest problem with this is that the dialog asking for permission often appears behind our main screen (but it will still block input to the main screen).

I have been able to trace this problem to the ForkJoinPool. Which apparently always runs with extra protection. See this post by Doug Lea.

What is the best way to disable this? I would prefer this to be an application wide solution.


问:
populate query does not show newly added referenced item
My schema is as follows:

items.js

```<code>var mongoose = require('mongoose');
var Schema = mongoose.Schema;

var ItemSchema = new Schema({
    no_of_times_ordered:Number,
    item_name:String,
    item_tag:String,
    item_category:String,
    item_illustrations:[String],
    item_stock:Number,   //0 available 1 last 5 items 2 not available
    item_quantity_ordered:{type:Number,default:0},
    item_discount_price:Number,
    item_price:Number,
    item_img:String,
    no_of_likes:{type:Number,default:0}
},{ versionKey: false });

module.exports = mongoose.model('items',ItemSchema);
</code>```

foodtruck.js

```<code>var mongoose = require('mongoose');
var Schema = mongoose.Schema;
var Items = require('./items.js');

var FoodTruckSchema = new Schema({
    foodtruck_name:String,
    foodtruck_location:String,
    foodtruck_rating:{type:Number,default:5},
    foodtruck_total_votes:{type:Number,default:0},
    foodtruck_tag:String,
    foodtruck_open_status:{type:Number,default:1},   //0 open 1 closed
    foodtruck_starting_timing:String,
    foodtruck_closing_timing:String,
    foodtruck_cusine:String,
    foodtruck_img:String,
    foodtruck_logo:String,
    item_list: [ {type : mongoose.Schema.ObjectId, ref : 'items'}]
},{ versionKey: false });

module.exports = mongoose.model('foodtruck',FoodTruckSchema);
</code>```

My query is as below:

```<code>var addItem = function(req, res) {
    var foodtruck_id = req.body.foodtruck_id;
    var newItem = new item();
    var itemList = [];
    newItem.item_name = req.body.item_name;
    newItem.item_tag = req.body.item_tag;
    newItem.item_category = req.body.item_category;

    for (var key in req.body) {
        if (req.body.hasOwnProperty(key)) {
            if (key == 'item_illustrations') {
                newItem.item_illustrations = req.body[key];
            }
        }
    }
    newItem.item_stock = req.body.item_status;
    newItem.item_price = req.body.item_price;

    if ((foodtruck_id) && (foodtruck_id.trim() != '')) {
        foodtruck.findById(foodtruck_id.trim(), function(err, foodtrucks) {
            if (err)
                res.json({
                    status: '500',
                    message: 'There is no data available'
                });

            newItem.save(function(err, savedItem) {
                if (!err) {
                   foodtrucks.item_list.push(savedItem._id);
                   foodtrucks.save();
                    foodtruck.find({
                        _id: foodtruck_id.trim()
                    }).populate('item_list').exec(function(err, foodtrucks) {
                        res.json({
                            status: '200',
                            message: 'New item added successfully',
                            data: foodtrucks
                        });
                    });
                } else {
                    res.json({
                        status: '500',
                        message: 'Error while saving new item'
                    });
                }
            });

        });

    }

}
</code>```

The main problem I am facing is that, I am able to create new item ,add its reference to the foodtruck schema, but somehow when I put populate query for the same foodtruck, the newly created item does not show. So,can you tell me how exactly I can show this item via populate query?

答:
I think you got to put the populate inside the save function to make the populate method happen after the save.

```<code>foodtrucks.save(function(err, doc) {
    //do population here
});
</code>```

using asynchronous methods.

Body:
My schema is as follows:

items.js

var mongoose = require('mongoose');
var Schema = mongoose.Schema;

var ItemSchema = new Schema({
    no_of_times_ordered:Number,
    item_name:String,
    item_tag:String,
    item_category:String,
    item_illustrations:[String],
    item_stock:Number,   //0 available 1 last 5 items 2 not available
    item_quantity_ordered:{type:Number,default:0},
    item_discount_price:Number,
    item_price:Number,
    item_img:String,
    no_of_likes:{type:Number,default:0}
},{ versionKey: false });

module.exports = mongoose.model('items',ItemSchema);

foodtruck.js

var mongoose = require('mongoose');
var Schema = mongoose.Schema;
var Items = require('./items.js');

var FoodTruckSchema = new Schema({
    foodtruck_name:String,
    foodtruck_location:String,
    foodtruck_rating:{type:Number,default:5},
    foodtruck_total_votes:{type:Number,default:0},
    foodtruck_tag:String,
    foodtruck_open_status:{type:Number,default:1},   //0 open 1 closed
    foodtruck_starting_timing:String,
    foodtruck_closing_timing:String,
    foodtruck_cusine:String,
    foodtruck_img:String,
    foodtruck_logo:String,
    item_list: [ {type : mongoose.Schema.ObjectId, ref : 'items'}]
},{ versionKey: false });

module.exports = mongoose.model('foodtruck',FoodTruckSchema);

My query is as below:

var addItem = function(req, res) {
    var foodtruck_id = req.body.foodtruck_id;
    var newItem = new item();
    var itemList = [];
    newItem.item_name = req.body.item_name;
    newItem.item_tag = req.body.item_tag;
    newItem.item_category = req.body.item_category;

    for (var key in req.body) {
        if (req.body.hasOwnProperty(key)) {
            if (key == 'item_illustrations') {
                newItem.item_illustrations = req.body[key];
            }
        }
    }
    newItem.item_stock = req.body.item_status;
    newItem.item_price = req.body.item_price;

    if ((foodtruck_id) && (foodtruck_id.trim() != '')) {
        foodtruck.findById(foodtruck_id.trim(), function(err, foodtrucks) {
            if (err)
                res.json({
                    status: '500',
                    message: 'There is no data available'
                });

            newItem.save(function(err, savedItem) {
                if (!err) {
                   foodtrucks.item_list.push(savedItem._id);
                   foodtrucks.save();
                    foodtruck.find({
                        _id: foodtruck_id.trim()
                    }).populate('item_list').exec(function(err, foodtrucks) {
                        res.json({
                            status: '200',
                            message: 'New item added successfully',
                            data: foodtrucks
                        });
                    });
                } else {
                    res.json({
                        status: '500',
                        message: 'Error while saving new item'
                    });
                }
            });

        });

    }

}

The main problem I am facing is that, I am able to create new item ,add its reference to the foodtruck schema, but somehow when I put populate query for the same foodtruck, the newly created item does not show. So,can you tell me how exactly I can show this item via populate query?

Body:
I think you got to put the populate inside the save function to make the populate method happen after the save.

foodtrucks.save(function(err, doc) {
    //do population here
});

using asynchronous methods.


问:
How to take screen shot for failed test cases using selenium webdriver in Java?
Can any one please help taking screen shots and saving on specific folder on Mac while running selenium webdriver automation scripts using java??

Note: I used static in my code so i cannot use below code

```<code>File scrFile = ((TakesScreenshot)driver).getScreenshotAs(OutputType.FILE);
FileUtils.copyFile(scrFile, new File("D:\\screenshot.jpg"));
</code>```

Thanks in advance !!

答:
If you're using JUnit 4, you can create a class that extends the TestWatcher class.

```<code>public class ScreenShotRule extends TestWatcher {

    private WebDriver webDriver;

    public ScreenShotRule(WebDriver webDriver) {
        this.webDriver = webDriver;
    }

    @Override
    protected void failed(Throwable e, Description description) {
        String methodName = description.getMethodName();
        String fileName = description.getTestClass().getSimpleName() + "-" + methodName + ".png";

        try {
            File destiny = new File(fileName);
            FileUtils.copyFile(((TakesScreenshot) webDriver).getScreenshotAs(OutputType.FILE), destiny);
        } catch (IOException ioe) {
            throw new RuntimeException(ioe);
        }
    }

    @Override
    protected void finished(Description description) {
        webDriver.quit();
    }
}
</code>```

In you're test, add a public field of this class and when the test fails, the rule will take the screenshot.

```<code>@Rule
public ScreenShotRule screenshotRule;
</code>```

Body:
Can any one please help taking screen shots and saving on specific folder on Mac while running selenium webdriver automation scripts using java??

Note: I used static in my code so i cannot use below code

File scrFile = ((TakesScreenshot)driver).getScreenshotAs(OutputType.FILE);
FileUtils.copyFile(scrFile, new File("D:\\screenshot.jpg"));

Thanks in advance !!

Body:
If you're using JUnit 4, you can create a class that extends the TestWatcher class.

public class ScreenShotRule extends TestWatcher {

    private WebDriver webDriver;

    public ScreenShotRule(WebDriver webDriver) {
        this.webDriver = webDriver;
    }

    @Override
    protected void failed(Throwable e, Description description) {
        String methodName = description.getMethodName();
        String fileName = description.getTestClass().getSimpleName() + "-" + methodName + ".png";

        try {
            File destiny = new File(fileName);
            FileUtils.copyFile(((TakesScreenshot) webDriver).getScreenshotAs(OutputType.FILE), destiny);
        } catch (IOException ioe) {
            throw new RuntimeException(ioe);
        }
    }

    @Override
    protected void finished(Description description) {
        webDriver.quit();
    }
}

In you're test, add a public field of this class and when the test fails, the rule will take the screenshot.

@Rule
public ScreenShotRule screenshotRule;


问:
Hide columns if cell has a given value
I would like to hide some columns if A1 changes but I am afraid that the function Worksheet_Change does not work.

I have the following code but if I change A1 nothing happens.

```<code>Private Sub Worksheet_Change(ByVal Target As Range)
    If Target.Address = "A1" Then

        Call hideColumns()
        '
        '
    End If
End Sub
</code>```

答:
change to

```<code>If Target.Address = "$A$1" Then
</code>```

or maybe use (my favorite):

```<code>If Not Intersect(Target, Range("A1")) Is Nothing Then
</code>```

Title: Hide columns if cell has a given value

Body:
I would like to hide some columns if A1 changes but I am afraid that the function Worksheet_Change does not work.

I have the following code but if I change A1 nothing happens.

Private Sub Worksheet_Change(ByVal Target As Range)
    If Target.Address = "A1" Then

        Call hideColumns()
        '
        '
    End If
End Sub

Body:
change to

If Target.Address = "$A$1" Then

or maybe use (my favorite):

If Not Intersect(Target, Range("A1")) Is Nothing Then


问:
Keras, How to get the output of each layer?
I have trained a binary classification model with CNN, and here is my code

```<code>model = Sequential()
model.add(Convolution2D(nb_filters, kernel_size[0], kernel_size[1],
                        border_mode='valid',
                        input_shape=input_shape))
model.add(Activation('relu'))
model.add(Convolution2D(nb_filters, kernel_size[0], kernel_size[1]))
model.add(Activation('relu'))
model.add(MaxPooling2D(pool_size=pool_size))
# (16, 16, 32)
model.add(Convolution2D(nb_filters*2, kernel_size[0], kernel_size[1]))
model.add(Activation('relu'))
model.add(Convolution2D(nb_filters*2, kernel_size[0], kernel_size[1]))
model.add(Activation('relu'))
model.add(MaxPooling2D(pool_size=pool_size))
# (8, 8, 64) = (2048)
model.add(Flatten())
model.add(Dense(1024))
model.add(Activation('relu'))
model.add(Dropout(0.5))
model.add(Dense(2))  # define a binary classification problem
model.add(Activation('softmax'))

model.compile(loss='categorical_crossentropy',
              optimizer='adadelta',
              metrics=['accuracy'])
model.fit(x_train, y_train,
          batch_size=batch_size,
          nb_epoch=nb_epoch,
          verbose=1,
          validation_data=(x_test, y_test))
</code>```

And here, I wanna get the output of each layer just like TensorFlow, how can I do that?

答:
I wrote this function for myself (in Jupyter) and it was inspired by indraforyou's answer. It will plot all the layer outputs automatically. Your images must have a (x, y, 1) shape where 1 stands for 1 channel. You just call plot_layer_outputs(...) to plot.</p>

```<code>%matplotlib inline
import matplotlib.pyplot as plt
from keras import backend as K

def get_layer_outputs():
    test_image = YOUR IMAGE GOES HERE!!!
    outputs    = [layer.output for layer in model.layers]          # all layer outputs
    comp_graph = [K.function([model.input]+ [K.learning_phase()], [output]) for output in outputs]  # evaluation functions

    # Testing
    layer_outputs_list = [op([test_image, 1.]) for op in comp_graph]
    layer_outputs = []

    for layer_output in layer_outputs_list:
        print(layer_output[0][0].shape, end='\n-------------------\n')
        layer_outputs.append(layer_output[0][0])

    return layer_outputs

def plot_layer_outputs(layer_number):
    layer_outputs = get_layer_outputs()

    x_max = layer_outputs[layer_number].shape[0]
    y_max = layer_outputs[layer_number].shape[1]
    n     = layer_outputs[layer_number].shape[2]

    L = []
    for i in range(n):
        L.append(np.zeros((x_max, y_max)))

    for i in range(n):
        for x in range(x_max):
            for y in range(y_max):
                L[i][x][y] = layer_outputs[layer_number][x][y][i]

    for img in L:
        plt.figure()
        plt.imshow(img, interpolation='nearest')
</code>```

Body:
I have trained a binary classification model with CNN, and here is my code

model = Sequential()
model.add(Convolution2D(nb_filters, kernel_size[0], kernel_size[1],
                        border_mode='valid',
                        input_shape=input_shape))
model.add(Activation('relu'))
model.add(Convolution2D(nb_filters, kernel_size[0], kernel_size[1]))
model.add(Activation('relu'))
model.add(MaxPooling2D(pool_size=pool_size))
# (16, 16, 32)
model.add(Convolution2D(nb_filters*2, kernel_size[0], kernel_size[1]))
model.add(Activation('relu'))
model.add(Convolution2D(nb_filters*2, kernel_size[0], kernel_size[1]))
model.add(Activation('relu'))
model.add(MaxPooling2D(pool_size=pool_size))
# (8, 8, 64) = (2048)
model.add(Flatten())
model.add(Dense(1024))
model.add(Activation('relu'))
model.add(Dropout(0.5))
model.add(Dense(2))  # define a binary classification problem
model.add(Activation('softmax'))

model.compile(loss='categorical_crossentropy',
              optimizer='adadelta',
              metrics=['accuracy'])
model.fit(x_train, y_train,
          batch_size=batch_size,
          nb_epoch=nb_epoch,
          verbose=1,
          validation_data=(x_test, y_test))

And here, I wanna get the output of each layer just like TensorFlow, how can I do that?

Body:
I wrote this function for myself (in Jupyter) and it was inspired by indraforyou's answer. It will plot all the layer outputs automatically. Your images must have a (x, y, 1) shape where 1 stands for 1 channel. You just call plot_layer_outputs(...) to plot.

%matplotlib inline
import matplotlib.pyplot as plt
from keras import backend as K

def get_layer_outputs():
    test_image = YOUR IMAGE GOES HERE!!!
    outputs    = [layer.output for layer in model.layers]          # all layer outputs
    comp_graph = [K.function([model.input]+ [K.learning_phase()], [output]) for output in outputs]  # evaluation functions

    # Testing
    layer_outputs_list = [op([test_image, 1.]) for op in comp_graph]
    layer_outputs = []

    for layer_output in layer_outputs_list:
        print(layer_output[0][0].shape, end='\n-------------------\n')
        layer_outputs.append(layer_output[0][0])

    return layer_outputs

def plot_layer_outputs(layer_number):
    layer_outputs = get_layer_outputs()

    x_max = layer_outputs[layer_number].shape[0]
    y_max = layer_outputs[layer_number].shape[1]
    n     = layer_outputs[layer_number].shape[2]

    L = []
    for i in range(n):
        L.append(np.zeros((x_max, y_max)))

    for i in range(n):
        for x in range(x_max):
            for y in range(y_max):
                L[i][x][y] = layer_outputs[layer_number][x][y][i]

    for img in L:
        plt.figure()
        plt.imshow(img, interpolation='nearest')


问:
Delphi 7 GIF in picture Dialog
I am using Delphi 7 and the OpenPictureDialog to open / preview various images. This works fine when opening a bmp, jpg, etc.; however, if I try to do the same with a gif I get the following error. Anyone got any idea why or have a fix for it?

thanks

Colin

答:
Delphi 7 simply doesn't support GIF images. This has led to a number of third-party components for reading GIF files. However, as of Delphi 2006 (IIRC), the RTL/VCL can read GIF files as well. Just include GifImg in the uses clause. (In fact, as of Delphi 2009, the RTL/VCL can also read PNG files. And then there is really no need for GIF support, because the PNG file format is superior in almost every way. The only thing supported by GIF that is not supported by PNG is (low-quality(1)) animations.)

(1) GIF only supports 256 colours.

Title: Delphi 7 GIF in picture Dialog


问:
Is it more performant to add inferred keywords to Groovy
Groovy is an interpreted language. Right?
So I'm thinking: isn't it better to be verbose when we can to lessen the burden on the interpreter?

For example, in the following case:

```<code>def getStringy() {
   def result = ...
   ...

   result
}
</code>```

Groovy will know that we want to return result but isn't it more performant to write that explicitly?

Also, isn't it better to specify the type of the methods arguments when we can? Some people here disagree with me. For example:

```<code>void specialSort(list) {
     // do sorting of a list
}
</code>```

What about semi-colons? What about public keywords? Do these matters affect performance in any way?

答:
Groovy is a compiled language. Before being executed, your code is going to be compiled, to a normal JVM-compatible bytecode classes.

Write the code, so you and others can easily read and understand it. Leave the compilation work for the compiler.

The only exception is, when you explicitly leverage a possibility to have dynamic code, e.g. using GroovyShell, to execute custom code, passed to the program as a string. You can do it in runtime. It will still be a 2 step (compile, then execute) process, and compilation results may be easily cached, if you want to call them often.
In that particular case, you'll have more headache about how to make it secure, and safe, then how to speed-up compilation process.

Body:
Groovy is an interpreted language. Right?
So I'm thinking: isn't it better to be verbose when we can to lessen the burden on the interpreter?

For example, in the following case:

def getStringy() {
   def result = ...
   ...

   result
}

Groovy will know that we want to return result but isn't it more performant to write that explicitly?

Also, isn't it better to specify the type of the methods arguments when we can? Some people here disagree with me. For example:

void specialSort(list) {
     // do sorting of a list
}

What about semi-colons? What about public keywords? Do these matters affect performance in any way?


答:
Groovy is compiled to Java Bytecode and then is run on the JVM

So, your first statement is incorrect

Title: Is it more performant to add inferred keywords to Groovy


问:
How to compare values of two List Arrays in Java
I have two lists as shown:

```<code>//list one = {1,2,3,4}
listone.add(1);
listone.add(2);
listone.add(3);
listone.add(4);

// list two = {3.0,4}
listtwo.add(3.0);
listtwo.add(4);
</code>```

I tried comparing 3 in listone to 3.0 in listtwo, but no matter what I do they don't seem to be equal. I was wondering, how can I detect that they are equal?

Also if I try to see they are a subset of each other:

```<code>Collections.indexOfSubList(listone,listtwo);
</code>```

Apparently this doesn't detect 3.0 as equal to 3.

So my question is, how do I test that 3 is equal to 3.0?

答:
Convert untyped lists to double lists:</p>

```<code>    Stream<Double> s1 = listone.stream().map(o->((Number)o).doubleValue());
    List<Double> dblListone = s1.collect(Collectors.toList());

    Stream<Double> s2 = listtwo.stream().map(o->((Number)o).doubleValue());
    List<Double> dblListtwo = s2.collect(Collectors.toList());
</code>```

Body:
I have two lists as shown:

//list one = {1,2,3,4}
listone.add(1);
listone.add(2);
listone.add(3);
listone.add(4);

// list two = {3.0,4}
listtwo.add(3.0);
listtwo.add(4);

I tried comparing 3 in listone to 3.0 in listtwo, but no matter what I do they don't seem to be equal. I was wondering, how can I detect that they are equal?

Also if I try to see they are a subset of each other:

Collections.indexOfSubList(listone,listtwo);

Apparently this doesn't detect 3.0 as equal to 3.

So my question is, how do I test that 3 is equal to 3.0?

Body:
Convert untyped lists to double lists:

    Stream<Double> s1 = listone.stream().map(o->((Number)o).doubleValue());
    List<Double> dblListone = s1.collect(Collectors.toList());

    Stream<Double> s2 = listtwo.stream().map(o->((Number)o).doubleValue());
    List<Double> dblListtwo = s2.collect(Collectors.toList());


问:
Recursive call to a duplicated Bash script, making it unable to access the assets
Edit : This post is now addressed in a new, as the problem as to be presented slightly differently. It's here : How can I efficiently run XSLT transformations for a large number of files in parallel?

I'm stuck in my attempts of parallelizing a process, and after some decent time spent on it I'd like to request some help ...

Basically, I have a lots of XML files to transform with a specific XSLT sheet. But the sheet uses a call to an (very slow) API to fetch additional data, and taking the whole batch of XMLs in 1 go will take (very) long.

Therefore I splitted all the files from the original "input" folder into subfolder containing each around 5000 XML files, and I copied the following Bash script inside each subfolder too:

```<code>for f in *.xml
do
  java -jar ../../saxon9he.jar -xsl:../../some-xslt-sheet.xsl -s:$f
done
</code>```

And I call each process, for each folder, from the "root" folder containing altogether the "input" folder, the Saxon library and the XSLT sheet :

```<code>find input -type d -exec sh {}/script.sh \;
</code>```

But I get this error:

```<code>Unable to access jarfile ../../saxon9he.jar
</code>```

I suppose it comes form the fact that I'm operating from the "root" folder, when the scripts being called are lower in the directories. I could solver the problem (if I'm correct) by copying all the assets in each subfolder, but I found the solution making my current approach even clumsier.

Thanks to anyone who might have an idea and make me understand this !

答:
Firstly, you really don't want to initialize a new Java VM to run each transformation: this is typically going to take much longer than running the actual transformation. To put this in perspective, for "typical" transformations you will often see Java initialization time 3 seconds, stylesheet compilation time 300ms, transformation time 10ms. So if you can find a way to do it that only initializes Java and compiles the stylesheet once, your total time for 10K documents is going to be 2 minutes rather than 10 hours.

There are various ways to achieve this but they all involve using something other than a shell-script to control the process. The simplest, in my view, is to control it from XSLT itself, by using the collection() function to access all the files in the directory. This has an added bonus, if you're using Saxon-EE, that the files will be processed (parsed) in parallel using all the cores on your machine, which can speed things up by another factor of 4 or so. You just need to add an entry point to the stylesheet something like:

```<code><xsl:template name="main">
  <xsl:for-each select="collection('file:///my/dir?select=*.xml;recurse=yes')!saxon:discard-document(.)">
    <xsl:result-document href="....">
      <xsl:apply-templates/>
    </xsl:result-document>
  </xsl:for-each>
</xsl:template>
</code>```

The saxon:discard-document call is optional, but because it makes documents eligible for garbage collection, means that you are less likely to run out of memory.

Another approach to writing the control loop is to use a specialized shell such as xmlsh.

Body:
Edit : This post is now addressed in a new, as the problem as to be presented slightly differently. It's here : How can I efficiently run XSLT transformations for a large number of files in parallel?

I'm stuck in my attempts of parallelizing a process, and after some decent time spent on it I'd like to request some help ...

Basically, I have a lots of XML files to transform with a specific XSLT sheet. But the sheet uses a call to an (very slow) API to fetch additional data, and taking the whole batch of XMLs in 1 go will take (very) long.

Therefore I splitted all the files from the original "input" folder into subfolder containing each around 5000 XML files, and I copied the following Bash script inside each subfolder too:

for f in *.xml
do
  java -jar ../../saxon9he.jar -xsl:../../some-xslt-sheet.xsl -s:$f
done

And I call each process, for each folder, from the "root" folder containing altogether the "input" folder, the Saxon library and the XSLT sheet :

find input -type d -exec sh {}/script.sh \;

But I get this error:

Unable to access jarfile ../../saxon9he.jar

I suppose it comes form the fact that I'm operating from the "root" folder, when the scripts being called are lower in the directories. I could solver the problem (if I'm correct) by copying all the assets in each subfolder, but I found the solution making my current approach even clumsier.

Thanks to anyone who might have an idea and make me understand this !

Body:
Firstly, you really don't want to initialize a new Java VM to run each transformation: this is typically going to take much longer than running the actual transformation. To put this in perspective, for "typical" transformations you will often see Java initialization time 3 seconds, stylesheet compilation time 300ms, transformation time 10ms. So if you can find a way to do it that only initializes Java and compiles the stylesheet once, your total time for 10K documents is going to be 2 minutes rather than 10 hours.

There are various ways to achieve this but they all involve using something other than a shell-script to control the process. The simplest, in my view, is to control it from XSLT itself, by using the collection() function to access all the files in the directory. This has an added bonus, if you're using Saxon-EE, that the files will be processed (parsed) in parallel using all the cores on your machine, which can speed things up by another factor of 4 or so. You just need to add an entry point to the stylesheet something like:

<xsl:template name="main">
  <xsl:for-each select="collection('file:///my/dir?select=*.xml;recurse=yes')!saxon:discard-document(.)">
    <xsl:result-document href="....">
      <xsl:apply-templates/>
    </xsl:result-document>
  </xsl:for-each>
</xsl:template>

The saxon:discard-document call is optional, but because it makes documents eligible for garbage collection, means that you are less likely to run out of memory.

Another approach to writing the control loop is to use a specialized shell such as xmlsh.


问:
Can Visual Studio 2010 Test Runner run XUnit?
Is it possible to use the integrated Visual Studio 2010 test runner to run other frameworks (Xunit, NUnit etc.) besides MSTest?

Does anyone know?

答:
Adam Salvo made the start of an XUnit test runner based on the NUnit one:
see http://blog.salvoz.com/2010/02/22/TransformXUnitToMSTest.aspx</p>


问:
flask-mail gmail: connection refused
I'm getting the following error when I attempt to use flask-mail to send an email through my gmail account.

error: [Errno 10061] No connection could be made because the target machine actively refused it

I've tried configuring flask-mail in various ways, but so far I always get this error.

Here are some sample configurations I've tried:

```<code>app = Flask(__name__)
mail = Mail(app)

app.config.update(dict(
    DEBUG = True,
    MAIL_SERVER = 'smtp.gmail.com',
    MAIL_PORT = 465,
    MAIL_USE_TLS = False,
    MAIL_USE_SSL = True,
    MAIL_USERNAME = 'my_username@gmail.com',
    MAIL_PASSWORD = 'my_password',
))
</code>```

```<code>app = Flask(__name__)
mail = Mail(app)

app.config.update(dict(
    DEBUG = True,
    MAIL_SERVER = 'smtp.gmail.com',
    MAIL_PORT = 587,
    MAIL_USE_TLS = True,
    MAIL_USE_SSL = False,
    MAIL_USERNAME = 'my_username@gmail.com',
    MAIL_PASSWORD = 'my_password',
))
</code>```

This configuration is from the flask mega-tutorial (http://blog.miguelgrinberg.com/post/the-flask-mega-tutorial-part-xi-email-support)

```<code>app = Flask(__name__)
mail = Mail(app)

app.config.update(dict(
    DEBUG = True,
    # email server
    MAIL_SERVER = 'smtp.googlemail.com',
    MAIL_PORT = 465,
    MAIL_USE_TLS = False,
    MAIL_USE_SSL = True,
    MAIL_USERNAME = 'my_username',
    MAIL_PASSWORD = 'my_password',

    # administrator list
    ADMINS = ['my_username@gmail.com']
))
</code>```

Has anyone else experienced a similar problem?

答:
In addition to zero323's answer, adding the configuration before creating a Mail object should help, but if it gives an SMTPAuthentication error with a gmail server, then just for testing purpose one may allow less secure apps to login for a while -
https://myaccount.google.com/security#signin

Title: flask-mail gmail: connection refused

Body:
I'm getting the following error when I attempt to use flask-mail to send an email through my gmail account.

error: [Errno 10061] No connection could be made because the target machine actively refused it

I've tried configuring flask-mail in various ways, but so far I always get this error.

Here are some sample configurations I've tried:

app = Flask(__name__)
mail = Mail(app)

app.config.update(dict(
    DEBUG = True,
    MAIL_SERVER = 'smtp.gmail.com',
    MAIL_PORT = 465,
    MAIL_USE_TLS = False,
    MAIL_USE_SSL = True,
    MAIL_USERNAME = 'my_username@gmail.com',
    MAIL_PASSWORD = 'my_password',
))

app = Flask(__name__)
mail = Mail(app)

app.config.update(dict(
    DEBUG = True,
    MAIL_SERVER = 'smtp.gmail.com',
    MAIL_PORT = 587,
    MAIL_USE_TLS = True,
    MAIL_USE_SSL = False,
    MAIL_USERNAME = 'my_username@gmail.com',
    MAIL_PASSWORD = 'my_password',
))

This configuration is from the flask mega-tutorial (http://blog.miguelgrinberg.com/post/the-flask-mega-tutorial-part-xi-email-support)

app = Flask(__name__)
mail = Mail(app)

app.config.update(dict(
    DEBUG = True,
    # email server
    MAIL_SERVER = 'smtp.googlemail.com',
    MAIL_PORT = 465,
    MAIL_USE_TLS = False,
    MAIL_USE_SSL = True,
    MAIL_USERNAME = 'my_username',
    MAIL_PASSWORD = 'my_password',

    # administrator list
    ADMINS = ['my_username@gmail.com']
))

Has anyone else experienced a similar problem?


问:
Show a Bootstrap popup and then revert the eventDrop in FullCalendar based on user's choice
Currently I am using Javascript confirm box to ask whether the user wants to proceed or he wants to revert, but I need to warn the user using Bootstrap popup.
User needs to say 'Proceed/Cancel' in popup.

I used bootstrap modal popup. but the 'drop' doesn't wait for user's choice.
It executes the flow of code written inside 'eventDrop', before user clicks yes/no button of popup.

Current code snippet:

```<code>eventDrop: function(event, delta, revertFunc) {
        if (!confirm("Are you sure to re-book the ticket?"))
            revertFunc();
}
</code>```

Kindly suggest.

答:
Sometimes in eventDrop function if not work if { } not given. So, please follow my code below::

```<code>eventDrop: function(event, delta, revertFunc) {
    if (!confirm("Are you sure to re-book the ticket?")) {
      revertFunc();
    }
}
</code>```

But it will be better to use a confirmbox or bootstap cofirm modal because if any user checks prevent this page from additional dialogs , from next time that alert box will not show.

Working url:: https://jsfiddle.net/rekdp2wt/

Body:
Currently I am using Javascript confirm box to ask whether the user wants to proceed or he wants to revert, but I need to warn the user using Bootstrap popup.
User needs to say 'Proceed/Cancel' in popup.

I used bootstrap modal popup. but the 'drop' doesn't wait for user's choice.
It executes the flow of code written inside 'eventDrop', before user clicks yes/no button of popup.

Current code snippet:

eventDrop: function(event, delta, revertFunc) {
        if (!confirm("Are you sure to re-book the ticket?"))
            revertFunc();
}

Kindly suggest.

Body:
Sometimes in eventDrop function if not work if { } not given. So, please follow my code below::

eventDrop: function(event, delta, revertFunc) {
    if (!confirm("Are you sure to re-book the ticket?")) {
      revertFunc();
    }
}

But it will be better to use a confirmbox or bootstap cofirm modal because if any user checks prevent this page from additional dialogs , from next time that alert box will not show.

Working url:: https://jsfiddle.net/rekdp2wt/


问:
How to get the Hololens Locatable Camera view and projection matrices out of the WinRT Windows.Media API
The documentation for the Hololens gives an example of how to extract the Locatable Camera view and projection matrices using the Media Foundation API here: https://developer.microsoft.com/en-us/windows/mixed-reality/locatable_camera#locating_the_device_camera_in_the_world.

It claims that this is also possible with the WinRT API, and links to this documentation reference: https://learn.microsoft.com/en-us/uwp/api/Windows.Media.Devices.Core.CameraIntrinsics.

However, this class does not seem to have any API to retrieve the extended Hololens attributes, only the default Windows Phone ones like the distortion matrix and pinhole properties.

Is the Hololens documentation incorrect and is it simply not possible to retrieve the Locatable Camera metadata in the WinRT API? Or am I missing something?

The Spatial Coordinate System (3rd and last extended sample metadata attribute) does seem to be available as MediaFrameReference.CoordinateSystem (https://learn.microsoft.com/en-us/uwp/api/windows.media.capture.frames.mediaframereference), which makes this even more confusing...

答:
You can cast the captured CapturedPhoto object to IMFGetService interface. Then, you can call IMFGetService::GetService method with MF_WRAPPED_SAMPLE_SERVICE as the service GUID and that will give you the native IMFSample. From that, you can retrieve those 3 camera attributes (coordinate system, view transform and projection transform) as outlined in the documentation.

Now, you could try writing doing all that in C# by manually declaring those interfaces, but it would be way easier to do in C++.


问:
What is difference between Map and Set?
JavaScript Map and Set objects are both iterable objects. Both store object by [key, value] pair.

When to use which? What is the difference between them?

答:
```<code>var obj = {};
obj.name= "Anand Deep Singh";
console.log(obj.name); //logs "Anand Deep Singh"
</code>```

similarly in ES6, we can use regular object.

```<code>var map = new Map();
map.set("name","Anand Deep Singh");
console.log(map.get("name")); //logs "Anand Deep Singh"
</code>```

But noticeable thing is a Map isn’t created with the literal object syntax, and that one uses set and get methods to store and access data.

It has a has method to check whether the key exists in the object or not, delete method to delete the object and clear method to clear the entire object.

Set is a unique list of values.  It’s simply a unique list.

```<code>var set = new Set(["a", "a","e", "b", "c", "b", "b", "b", "d"]);
console.log(set); //logs Set {"a", "e", "b", "c", "d"}
</code>```

A Set can’t be accessed like an array, and it provides the same methods as a Map.

ContentLicense: CC BY-SA 4.0

Title: What is difference between Map and Set?

Body:
var obj = {};
obj.name= "Anand Deep Singh";
console.log(obj.name); //logs "Anand Deep Singh"

similarly in ES6, we can use regular object.

var map = new Map();
map.set("name","Anand Deep Singh");
console.log(map.get("name")); //logs "Anand Deep Singh"

But noticeable thing is a Map isn’t created with the literal object syntax, and that one uses set and get methods to store and access data.

It has a has method to check whether the key exists in the object or not, delete method to delete the object and clear method to clear the entire object.

Set is a unique list of values.  It’s simply a unique list.

var set = new Set(["a", "a","e", "b", "c", "b", "b", "b", "d"]);
console.log(set); //logs Set {"a", "e", "b", "c", "d"}

A Set can’t be accessed like an array, and it provides the same methods as a Map.


问:
MVC Error: model item of type 'System.Collections.Generic.IEnumerable`1 required
I'm doing some modifications to a system, and I've run into an exception that I was hoping someone could help with?? The error I'm getting is the following:

Exception Details:
  System.InvalidOperationException: The
  model item passed into the dictionary
  is of type
  'System.Collections.Generic.List1[System.String]',
  but this dictionary requires a model
  item of type
  'System.Collections.Generic.IEnumerable1[MyApp.Data.aspnet_Users]'.

Basically what I want to do is display a list of Inactive users. Here is the controller I've written for that:

```<code>public ActionResult InactiveUsers()
        {
            using (ModelContainer ctn = new ModelContainer())
            {
                aspnet_Users users = new aspnet_Users();

                DateTime duration = DateTime.Now.AddDays(-3);

                var inactive = from usrs in ctn.aspnet_Users
                    where usrs.LastActivityDate <= duration
                    orderby usrs.LastActivityDate ascending
                    select usrs.UserName;

                return View(inactive.ToList());
            }

        }
</code>```

From here then I added a partial view. Here is the code for it if anyone is interested. Just the usual Add View --> List.

```<code><%@ Control Language="C#" Inherits="System.Web.Mvc.ViewUserControl<IEnumerable<MyApp.Data.aspnet_Users>>" %>

    <table>
        <tr>
            <th></th>
            <th>
                ApplicationId
            </th>
            <th>
                UserId
            </th>
            <th>
                UserName
            </th>
            <th>
                LoweredUserName
            </th>
            <th>
                MobileAlias
            </th>
            <th>
                IsAnonymous
            </th>
            <th>
                LastActivityDate
            </th>
        </tr>

    <% foreach (var item in Model) { %>

        <tr>
            <td>
                <%: Html.ActionLink("Edit", "Edit", new { id=item.UserId }) %> |
                <%: Html.ActionLink("Details", "Details", new { id=item.UserId })%> |
                <%: Html.ActionLink("Delete", "Delete", new { id=item.UserId })%>
            </td>
            <td>
                <%: item.ApplicationId %>
            </td>
            <td>
                <%: item.UserId %>
            </td>
            <td>
                <%: item.UserName %>
            </td>
            <td>
                <%: item.LoweredUserName %>
            </td>
            <td>
                <%: item.MobileAlias %>
            </td>
            <td>
                <%: item.IsAnonymous %>
            </td>
            <td>
                <%: String.Format("{0:g}", item.LastActivityDate) %>
            </td>
        </tr>

    <% } %>

    </table>

    <p>
        <%: Html.ActionLink("Create New", "Create") %>
    </p>
</code>```

And for completeness here is the Index page where I render the partial:

```<code><%@ Page Title="" Language="C#" MasterPageFile="~/Views/Shared/Administrator.Master" Inherits="System.Web.Mvc.ViewPage<dynamic>" %>

<asp:Content ID="Content1" ContentPlaceHolderID="TitleContent" runat="server">
    Index
</asp:Content>

<asp:Content ID="Content2" ContentPlaceHolderID="MainContent" runat="server">

    <h2>Index</h2>

    <% Html.RenderAction("InactiveUsers"); %>

</asp:Content>

<asp:Content ID="Content3" ContentPlaceHolderID="Header" runat="server">
</asp:Content>
</code>```

If anyone has any advice I'd be very grateful :)

答:
Hi i think its because in your partial view type is System.Web.Mvc.ViewUserControl<IEnumerable<MyApp.Data.aspnet_Users>>
but you select user names

```<code>select usrs.UserName;

return View(inactive.ToList());
</code>```

Try change it to select usrs; but not usrs.UserName

Body:
I'm doing some modifications to a system, and I've run into an exception that I was hoping someone could help with?? The error I'm getting is the following:

Exception Details:
  System.InvalidOperationException: The
  model item passed into the dictionary
  is of type
  'System.Collections.Generic.List1[System.String]',
  but this dictionary requires a model
  item of type
  'System.Collections.Generic.IEnumerable1[MyApp.Data.aspnet_Users]'.

Basically what I want to do is display a list of Inactive users. Here is the controller I've written for that:

public ActionResult InactiveUsers()
        {
            using (ModelContainer ctn = new ModelContainer())
            {
                aspnet_Users users = new aspnet_Users();

                DateTime duration = DateTime.Now.AddDays(-3);

                var inactive = from usrs in ctn.aspnet_Users
                    where usrs.LastActivityDate <= duration
                    orderby usrs.LastActivityDate ascending
                    select usrs.UserName;

                return View(inactive.ToList());
            }

        }

From here then I added a partial view. Here is the code for it if anyone is interested. Just the usual Add View --> List.

<%@ Control Language="C#" Inherits="System.Web.Mvc.ViewUserControl<IEnumerable<MyApp.Data.aspnet_Users>>" %>

                ApplicationId

                UserId

                UserName

                LoweredUserName

                MobileAlias

                IsAnonymous

                LastActivityDate

    <% foreach (var item in Model) { %>

                <%: Html.ActionLink("Edit", "Edit", new { id=item.UserId }) %> |
                <%: Html.ActionLink("Details", "Details", new { id=item.UserId })%> |
                <%: Html.ActionLink("Delete", "Delete", new { id=item.UserId })%>

                <%: item.ApplicationId %>

                <%: item.UserId %>

                <%: item.UserName %>

                <%: item.LoweredUserName %>

                <%: item.MobileAlias %>

                <%: item.IsAnonymous %>

                <%: String.Format("{0:g}", item.LastActivityDate) %>

    <% } %>

        <%: Html.ActionLink("Create New", "Create") %>

And for completeness here is the Index page where I render the partial:

<%@ Page Title="" Language="C#" MasterPageFile="~/Views/Shared/Administrator.Master" Inherits="System.Web.Mvc.ViewPage<dynamic>" %>

<asp:Content ID="Content1" ContentPlaceHolderID="TitleContent" runat="server">
    Index
</asp:Content>

<asp:Content ID="Content2" ContentPlaceHolderID="MainContent" runat="server">

Index

    <% Html.RenderAction("InactiveUsers"); %>

</asp:Content>

<asp:Content ID="Content3" ContentPlaceHolderID="Header" runat="server">
</asp:Content>

If anyone has any advice I'd be very grateful :)

Body:
Hi i think its because in your partial view type is System.Web.Mvc.ViewUserControl<IEnumerable<MyApp.Data.aspnet_Users>>
but you select user names

select usrs.UserName;

return View(inactive.ToList());

Try change it to select usrs; but not usrs.UserName


问:
Why does this sort in Java not work?
I'm trying to implement a short sorting algorithm, but it simply doesn't work. Anyone with more experience in programming got any tips? The array is not sorted, several values are coming up multiple times in the end print. Why?</p>

```<code>public static void main(String[] args) {
    // Sort the data
    int[] array = {1,5,2,3,6,2,29,-2,23,3};

    for (int i = 0; i<array.length-1; i++) {

        if (array[i] > array[i+1]) {
            array[i+1] = array[i];
            array[i] = array[i+1];
        }
    }

    // Print the data.
    for (int i = 0; i<array.length; i++) {
        System.out.print(i+ ", ");
    }
}
</code>```

答:
1 if you want to swap two element please use temporary variable

```<code>public void swap(int[] nums,int i,int j)
{ int tmp=nums][i];
  nums[i]=nums[j];
   nums[j]=tmp;
}
</code>```

2 this way which you display can't sort the data, here is my way to sort data:

```<code>public void insertionSort(int nums[])
{
   int j;
   for(int i=1,i<nums.length-1;i++){
     int tmp=nums[i];
     for(j=i;j>0&&nums[j]<nums[j-1];j--)
         nums[j]=nums[j-1];
     nums[j]=tmp;
   }
 }
</code>```

Title: Why does this sort in Java not work?

Body:
I'm trying to implement a short sorting algorithm, but it simply doesn't work. Anyone with more experience in programming got any tips? The array is not sorted, several values are coming up multiple times in the end print. Why?

public static void main(String[] args) {
    // Sort the data
    int[] array = {1,5,2,3,6,2,29,-2,23,3};

    for (int i = 0; i<array.length-1; i++) {

        if (array[i] > array[i+1]) {
            array[i+1] = array[i];
            array[i] = array[i+1];
        }
    }

    // Print the data.
    for (int i = 0; i<array.length; i++) {
        System.out.print(i+ ", ");
    }
}

Body:
1 if you want to swap two element please use temporary variable

public void swap(int[] nums,int i,int j)
{ int tmp=nums][i];
  nums[i]=nums[j];
   nums[j]=tmp;
}

2 this way which you display can't sort the data, here is my way to sort data:

public void insertionSort(int nums[])
{
   int j;
   for(int i=1,i<nums.length-1;i++){
     int tmp=nums[i];
     for(j=i;j>0&&nums[j]<nums[j-1];j--)
         nums[j]=nums[j-1];
     nums[j]=tmp;
   }
 }


问:
Using object as property of another object
I want to use an object template as a property of another object. My template object is like below

```<code>var tableDataRow ={
    numberOfFiles:parseFloat(0),
    insurerIncurred :parseFloat(0),
    insuredIncurred :parseFloat(0),
    totalIncurred :parseFloat(0)
};
</code>```

I'm using this object like this

```<code>var tableData ={
    firm1 :tableDataRow,
    firm2:tableDataRow,
    firm3:tableDataRow,
    firm4:tableDataRow
};
</code>```

But when I want to change a property value in tableDataRow object, all values in tableData are changing.

```<code>tableData.firm1.numberOfFiles = 2;
tableData.firm2.insurerIncurred = 3;
tableData.firm3.insuredIncurred = 4;
tableData.firm4.totalIncurred = 5;
</code>```

I thought that I can use like object oriented languages but I supposed that this way I have only put a reference of tableDataRow in another object. How can I do this ?

https://jsfiddle.net/0ta0wkho/

答:
Objects are passed by reference, since the structure of yours is simple enough, you could get away with doing something like this JSON.parse(JSON.stringify(tableDataRow)) which would create a new object with the same structure as your original one, or you could have a function that returns that structure; if that makes it cleaner for you.

Here's a fork of your fiddle, if it makes it clearer

By having a function:

```<code>function cloneme(originalObject) {
  return JSON.parse(JSON.stringify(originalObject));
}
</code>```

And assigning like this:

```<code>var tableData = {
  firm1: cloneme(tableDataRow),
  firm2: cloneme(tableDataRow),
  firm3: cloneme(tableDataRow),
  firm4: cloneme(tableDataRow)
};
</code>```

We are working with new copies of the structure.

Body:
I want to use an object template as a property of another object. My template object is like below

var tableDataRow ={
    numberOfFiles:parseFloat(0),
    insurerIncurred :parseFloat(0),
    insuredIncurred :parseFloat(0),
    totalIncurred :parseFloat(0)
};

I'm using this object like this

var tableData ={
    firm1 :tableDataRow,
    firm2:tableDataRow,
    firm3:tableDataRow,
    firm4:tableDataRow
};

But when I want to change a property value in tableDataRow object, all values in tableData are changing.

tableData.firm1.numberOfFiles = 2;
tableData.firm2.insurerIncurred = 3;
tableData.firm3.insuredIncurred = 4;
tableData.firm4.totalIncurred = 5;

I thought that I can use like object oriented languages but I supposed that this way I have only put a reference of tableDataRow in another object. How can I do this ?

https://jsfiddle.net/0ta0wkho/

Body:
Objects are passed by reference, since the structure of yours is simple enough, you could get away with doing something like this JSON.parse(JSON.stringify(tableDataRow)) which would create a new object with the same structure as your original one, or you could have a function that returns that structure; if that makes it cleaner for you.

Here's a fork of your fiddle, if it makes it clearer

By having a function:

function cloneme(originalObject) {
  return JSON.parse(JSON.stringify(originalObject));
}

And assigning like this:

var tableData = {
  firm1: cloneme(tableDataRow),
  firm2: cloneme(tableDataRow),
  firm3: cloneme(tableDataRow),
  firm4: cloneme(tableDataRow)
};

We are working with new copies of the structure.


问:
Python - Transform List to List of Lists with each entry containing unique combinations
I have a list of lists as follows:

```<code>mylist=[[a,b],[a,c],[b,c],[c,d],[d,e],[e,c]]
</code>```

What I would like to do is iterate through mylist and produce a new list like this:

```<code>result=[ [ [a,b],[c,d] ] , [ [a,c],[d,e] ] , [ [b,c] ], [ [e,c] ] ]
</code>```

In other words, make a list of lists, where each list contains unique combinations of entries of the initial list, so that a letter is not present twice in each entry of result list. Also each time an entry is added to result, we abstract it's sub elements from the set of available combinations of the initial list. (I guess the given example makes it more clear than the explanation).

答:
This should work for you:

```<code>mylist=[['a','b'],['a','c'],['b','c'],['c','d'],['d','e'],['e','c']]
final_res=[]
while(len(mylist)>0):
    res=[list(mylist[0])]
    mylist.remove(res[0])
    for l in mylist:
        if len(set(l) & set().union(*res))==0:
            res.append(l)
            mylist.remove(l)
    final_res.append(res)
</code>```

output:

```<code>print final_res
>> [[['a', 'b'], ['c', 'd']], [['a', 'c'], ['d', 'e']], [['b', 'c']], [['e', 'c']]]
</code>```

Body:
I have a list of lists as follows:

mylist=[[a,b],[a,c],[b,c],[c,d],[d,e],[e,c]]

What I would like to do is iterate through mylist and produce a new list like this:

result=[ [ [a,b],[c,d] ] , [ [a,c],[d,e] ] , [ [b,c] ], [ [e,c] ] ]

In other words, make a list of lists, where each list contains unique combinations of entries of the initial list, so that a letter is not present twice in each entry of result list. Also each time an entry is added to result, we abstract it's sub elements from the set of available combinations of the initial list. (I guess the given example makes it more clear than the explanation).

Body:
This should work for you:

mylist=[['a','b'],['a','c'],['b','c'],['c','d'],['d','e'],['e','c']]
final_res=[]
while(len(mylist)>0):
    res=[list(mylist[0])]
    mylist.remove(res[0])
    for l in mylist:
        if len(set(l) & set().union(*res))==0:
            res.append(l)
            mylist.remove(l)
    final_res.append(res)

output:

print final_res
>> [[['a', 'b'], ['c', 'd']], [['a', 'c'], ['d', 'e']], [['b', 'c']], [['e', 'c']]]


问:
Why Android theme does not affect elements inside of fragment?
I have an Activity that hosts FrameLayout and dynamically displays custom fragments.

My goal is to have in styles.xml defined button style that applies to all buttons inside all fragments.

This is my styles.xml file:

```<code><!-- Base application theme. -->
<style name="AppThemeDark" parent="Theme.AppCompat.Light.DarkActionBar">
    <item name="android:buttonStyle">@style/bt</item>
</style>

<style name="bt" parent="@android:style/Widget.Button">
    <item name="android:background">#992323</item>
</style>
</code>```

activity_login.xml

```<code><?xml version="1.0" encoding="utf-8"?>
<LinearLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:fitsSystemWindows="true"
    tools:context="com.example.app.LoginActivity">

    <FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
        android:id="@+id/login_frame_layout"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:orientation="vertical"/>

</LinearLayout>
</code>```

and finally fragment.xml

```<code>    <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
        xmlns:tools="http://schemas.android.com/tools"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:paddingLeft="@dimen/activity_horizontal_margin"
        android:paddingRight="@dimen/activity_horizontal_margin"
        android:paddingTop="@dimen/activity_vertical_margin"
        android:paddingBottom="@dimen/activity_vertical_margin"
        tools:context="com.example.app.LoginBackupKeyFragment"
        android:orientation="vertical">

    <Button
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="Got it!"
        android:id="@+id/button"
        android:layout_gravity="center_horizontal"
        android:onClick="BackupKeyGotItButtonClicked"/>

</LinearLayout>
</code>```

But the style is not applied! Why?

EDIT 15.11.2015

After reading this question, I think I should mention that I use custom onCreateView function in my fragment and it looks like this:

```<code>@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {

    // create ContextThemeWrapper from the original Activity Context with the custom theme
    final Context contextThemeWrapper = new ContextThemeWrapper(getActivity(), R.style.AppThemeDark);

    // clone the inflater using the ContextThemeWrapper
    LayoutInflater localInflater = inflater.cloneInContext(contextThemeWrapper);

    View fragmentView = localInflater.inflate(R.layout.fragment_login_new, container, false);

    pass1 = (EditText)fragmentView.findViewById(R.id.login_new_pass1);

    return fragmentView;
}
</code>```

EDIT 2 15.11.2015
this is my manifest XML

```<code><?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.example.app" >

    <uses-permission android:name="android.permission.READ_SMS" />

    <application>

        <activity android:name=".StartUpActivity"
            android:theme="@style/AppTheme.NoActionBar"
            android:noHistory="true">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />
                <category android:name="android.intent.category.LAUNCHER" />

                <action android:name="android.intent.action.DEFAULT" />
            </intent-filter>
        </activity>

        <activity
            android:name=".LoginActivity"
            android:label="@string/title_activity_login"
            android:theme="@style/AppThemeDark"
            android:windowSoftInputMode="adjustResize">
        </activity>
    </application>

</manifest>
</code>```

EDIT 3 !!IMPORTANT!!

I have noticed this has to be related with

```<code><item name="android:buttonStyle">@style/bt</item>
</code>```

as e.g. adding this

```<code><item name="colorControlNormal">#f00</item>
<item name="colorControlActivated">#0f0</item>
<item name="colorControlHighlight">#00f</item>
</code>```

into AppThemeDark style works and shows ok in fragment. just android:buttonStyle and simmilaruly e.g. android.editTextStyle does not work.

答:
May be too late, but if I understand correctly you want to set different colorControlNormal, colorControlActivated and colorControlHighlight than specified globally in your theme and apply it just for a button. I had similar problem (I wanted white accent color for EditText) and I've resolved it like follows:

create style in values/styles:

add app:theme="@style/ColorOverwrite" (UPDATE app:theme="..." is now deprecated, we should use android:theme="") for certain control (EditText in my case)

<EditText
    android:id="@+id/id"
    android:textColor="@color/colorBlueLight"
    android:inputType="text"
    app:theme="@style/ColorOverwrite"
    android:layout_width="match_parent"
    android:layout_height="wrap_content" />

make sure you don't set at the same time style="@style/somestyle" for that control or you'll get an error.

Example image showing applied theme - EditText in red rectangle has my custom theme, EditText in yellow rectangle shows default color style from theme

Body:
I have an Activity that hosts FrameLayout and dynamically displays custom fragments.

My goal is to have in styles.xml defined button style that applies to all buttons inside all fragments.

This is my styles.xml file:

activity_login.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:fitsSystemWindows="true"
    tools:context="com.example.app.LoginActivity">

    <FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
        android:id="@+id/login_frame_layout"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:orientation="vertical"/>

</LinearLayout>

and finally fragment.xml

    <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
        xmlns:tools="http://schemas.android.com/tools"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:paddingLeft="@dimen/activity_horizontal_margin"
        android:paddingRight="@dimen/activity_horizontal_margin"
        android:paddingTop="@dimen/activity_vertical_margin"
        android:paddingBottom="@dimen/activity_vertical_margin"
        tools:context="com.example.app.LoginBackupKeyFragment"
        android:orientation="vertical">

    <Button
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="Got it!"
        android:id="@+id/button"
        android:layout_gravity="center_horizontal"
        android:onClick="BackupKeyGotItButtonClicked"/>

</LinearLayout>

But the style is not applied! Why?

EDIT 15.11.2015

After reading this question, I think I should mention that I use custom onCreateView function in my fragment and it looks like this:

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {

    // create ContextThemeWrapper from the original Activity Context with the custom theme
    final Context contextThemeWrapper = new ContextThemeWrapper(getActivity(), R.style.AppThemeDark);

    // clone the inflater using the ContextThemeWrapper
    LayoutInflater localInflater = inflater.cloneInContext(contextThemeWrapper);

    View fragmentView = localInflater.inflate(R.layout.fragment_login_new, container, false);

    pass1 = (EditText)fragmentView.findViewById(R.id.login_new_pass1);

    return fragmentView;
}

EDIT 2 15.11.2015
this is my manifest XML

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.example.app" >

    <uses-permission android:name="android.permission.READ_SMS" />

    <application>

        <activity android:name=".StartUpActivity"
            android:theme="@style/AppTheme.NoActionBar"
            android:noHistory="true">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />
                <category android:name="android.intent.category.LAUNCHER" />

                <action android:name="android.intent.action.DEFAULT" />
            </intent-filter>
        </activity>

        <activity
            android:name=".LoginActivity"
            android:label="@string/title_activity_login"
            android:theme="@style/AppThemeDark"
            android:windowSoftInputMode="adjustResize">
        </activity>
    </application>

</manifest>

EDIT 3 !!IMPORTANT!!

I have noticed this has to be related with

<item name="android:buttonStyle">@style/bt</item>

as e.g. adding this

<item name="colorControlNormal">#f00</item>
<item name="colorControlActivated">#0f0</item>
<item name="colorControlHighlight">#00f</item>

into AppThemeDark style works and shows ok in fragment. just android:buttonStyle and simmilaruly e.g. android.editTextStyle does not work.

Body:
May be too late, but if I understand correctly you want to set different colorControlNormal, colorControlActivated and colorControlHighlight than specified globally in your theme and apply it just for a button. I had similar problem (I wanted white accent color for EditText) and I've resolved it like follows:

create style in values/styles:

<style name="ColorOverwrite" parent="AppTheme">
    <item name="android:textColorHint">@color/white_54p</item>
    <item name="colorAccent">@color/colorWhite</item>
    <item name="colorControlNormal">@color/white_54p</item>
    <item name="colorControlActivated">@color/colorWhite</item>
</style>

add app:theme="@style/ColorOverwrite" (UPDATE app:theme="..." is now deprecated, we should use android:theme="") for certain control (EditText in my case)

<EditText
    android:id="@+id/id"
    android:textColor="@color/colorBlueLight"
    android:inputType="text"
    app:theme="@style/ColorOverwrite"
    android:layout_width="match_parent"
    android:layout_height="wrap_content" />

make sure you don't set at the same time style="@style/somestyle" for that control or you'll get an error.

Example image showing applied theme - EditText in red rectangle has my custom theme, EditText in yellow rectangle shows default color style from theme


问:
How to override insall directory with setup.py install
I am using python 2.7 on Mac OSX.

I am trying to install a package using the setup.py file which looks like:

```<code>from distutils.core import setup
setup(packages=['object_recognition_by_parts'], package_dir={'': 'python'})
</code>```

it fails an throws the following error:

```<code>running install
running build
running build_py
running install_lib
creating /usr/lib/python2.7/site-packages
error: could not create '/usr/lib/python2.7/site-packages': Permission denied
</code>```

But my site packages directory is /usr/local/lib/python2.7/site-packages and not /usr/lib/python2.7/site-packages. Can I override this?

If I install using pip, the packages are installed in /usr/local/lib/python2.7/site-packages

答:
You may define home path by command line parameter, e.g.

```<code>python setup.py install --home=/home/blah
</code>```

Or you may have to modify Python’s search path.

More details:

Alternate installation the home scheme

Modifying Python’s Search Path

Hope it will help.

Body:
I am using python 2.7 on Mac OSX.

I am trying to install a package using the setup.py file which looks like:

from distutils.core import setup
setup(packages=['object_recognition_by_parts'], package_dir={'': 'python'})

it fails an throws the following error:

running install
running build
running build_py
running install_lib
creating /usr/lib/python2.7/site-packages
error: could not create '/usr/lib/python2.7/site-packages': Permission denied

But my site packages directory is /usr/local/lib/python2.7/site-packages and not /usr/lib/python2.7/site-packages. Can I override this?

If I install using pip, the packages are installed in /usr/local/lib/python2.7/site-packages

Body:
You may define home path by command line parameter, e.g.

python setup.py install --home=/home/blah

Or you may have to modify Python’s search path.

More details:

Alternate installation the home scheme

Modifying Python’s Search Path

Hope it will help.


问:
How do I supply the message text when sending SMS using the sms schema?
How do I open SMS from my app and have the new message popped up and prepopulated?

Right now this is what I have

NSString *stringURL = @"sms:";

NSURL *url = [NSURL URLWithString:stringURL];

[[UIApplication sharedApplication] openURL:url];

That opens the SMS app but you have to click on new message etc.

Thanks,

Tee

答:
of course its supplied and supported by the public API.

here you go:

```<code>MFMessageComposeViewController *controller = [[[MFMessageComposeViewController alloc] init] autorelease];
if([MFMessageComposeViewController canSendText])
{
    controller.body = @"The text you want to populate in the SMS";
    controller.recipients = tempArrayForSMS;// any NSMutable Array holding numbers
    controller.messageComposeDelegate = self;
    [self presentModalViewController:controller animated:YES];
}
</code>```

Body:
of course its supplied and supported by the public API.

here you go:

MFMessageComposeViewController *controller = [[[MFMessageComposeViewController alloc] init] autorelease];
if([MFMessageComposeViewController canSendText])
{
    controller.body = @"The text you want to populate in the SMS";
    controller.recipients = tempArrayForSMS;// any NSMutable Array holding numbers
    controller.messageComposeDelegate = self;
    [self presentModalViewController:controller animated:YES];
}