问:
Bower dependicies with postinstall on Docker
It is possible to install bower dependicies using postinstall in package.json on docker with docker-compose?

package.json file:

```<code>   {
      "name": "mongocrud",
      "version": "0.0.0",
      "private": true,
      "scripts": {
        "start": "node ./config/server.js",
        "postinstall": "node ./node_modules/bower/bin/bower install",
        "test": "mocha"
      },
      "dependencies": {
        //dependicies
      }
    }
</code>```

Dockerfile:

```<code>FROM node:7.7.2-alpine

WORKDIR /application

COPY package.json .

COPY bower.json .

COPY .bowerrc .

RUN npm install -g bower

RUN npm install

COPY . .

EXPOSE 3000

CMD ["npm", "start"]
</code>```

docker-compose.yml:

```<code>version: '3'

services:
    mongodb:
        image: mongo:3.4.4
        command: mongod
        container_name: mongo-container
        ports:
            - 27017:27017

    express:
         build: .
         container_name: express-container
         ports:
            - 3000:3000
         working_dir: /application

         links:
            - mongodb
         command: npm start
</code>```

And after use docker-compose up application works fine but missing bower dependicies, can I fix that?

P.S

This I found in console after docker-compose up:

```<code>npm WARN lifecycle mongocrud@0.0.0~postinstall: cannot run in wd %s %s (wd=%s) mongocrud@0.0.0 node ./node_modules/bower/bin/bower install /application
</code>```

Thanks

答:
Change node ./node_modules/bower/bin/bower install to bower install --allow-root in postinstall script. The --allow-root is to prevent you from permission errors.

Or you can remove the postinstall script and add RUN bower install --allow-root after RUN npm install in the Dockerfile.

And bower requires git to work, you have to install git first in your Dockerfile.

Body:
It is possible to install bower dependicies using postinstall in package.json on docker with docker-compose?

package.json file:

   {
      "name": "mongocrud",
      "version": "0.0.0",
      "private": true,
      "scripts": {
        "start": "node ./config/server.js",
        "postinstall": "node ./node_modules/bower/bin/bower install",
        "test": "mocha"
      },
      "dependencies": {
        //dependicies
      }
    }

Dockerfile:

FROM node:7.7.2-alpine

WORKDIR /application

COPY package.json .

COPY bower.json .

COPY .bowerrc .

RUN npm install -g bower

RUN npm install

COPY . .

EXPOSE 3000

CMD ["npm", "start"]

docker-compose.yml:

version: '3'

services:
    mongodb:
        image: mongo:3.4.4
        command: mongod
        container_name: mongo-container
        ports:
            - 27017:27017

    express:
         build: .
         container_name: express-container
         ports:
            - 3000:3000
         working_dir: /application

         links:
            - mongodb
         command: npm start

And after use docker-compose up application works fine but missing bower dependicies, can I fix that?

P.S

This I found in console after docker-compose up:

npm WARN lifecycle mongocrud@0.0.0~postinstall: cannot run in wd %s %s (wd=%s) mongocrud@0.0.0 node ./node_modules/bower/bin/bower install /application

Thanks


来源: stackexchange

问:
Displaying unique values in loop
I have in my database a table of product requests.

I am now making a summary of user's request. Which displays all the user's request without duplicating the product names (should be unique), and get the total quantity and amount.

This is my code and what I have tried so far. I tried using unique array.

```<code>$all_product_name = array();

foreach ( $rows as $row ) {

    $all_product_name[] = $row;
    $allproduct = array_unique( $all_product_name );
}

 foreach ($allproduct as $product) {

    print_r($product);

 }
</code>```

This gives me all the products and not the unique product names.

What I would like to do is to is to show only unique product names, and the sum of the quantity and amount of all products.

I am stuck, any help and ideas?

答:
Solution 1: Use a query, like in mysql it would be -
    select sum(prod_quantity), sum(prod_amount) group by prod_name

Solution 2: Iterate over the rows to create associative array of prod_name

```<code>foreach($rows as $row) {
    $prod_name = $row['prod_name'];
    $prod[$prod_name]['amount'] = $prod[$prod_name]['amount'] + $row['prod_amount'];
    $prod[$prod_name]['quantity'] = $prod[$prod_name]['quantity'] + $row['prod_quantity'];
}
</code>```

Output will be like:

```<code>Array
(
    [Product1] => Array
    (
        [amount] => 2600 //sum of prod_amount
        [quantity] => 6  //sum of prod_quantity
    )

[Product2] => Array
    (
        [amount] => 6600
        [quantity] => 5
    )
)
</code>```

ContentLicense: CC BY-SA 3.0

Title: Displaying unique values in loop

Body:
I have in my database a table of product requests.

I am now making a summary of user's request. Which displays all the user's request without duplicating the product names (should be unique), and get the total quantity and amount.

This is my code and what I have tried so far. I tried using unique array.

$all_product_name = array();

foreach ( $rows as $row ) {

    $all_product_name[] = $row;
    $allproduct = array_unique( $all_product_name );
}

 foreach ($allproduct as $product) {

    print_r($product);

 }

This gives me all the products and not the unique product names.

What I would like to do is to is to show only unique product names, and the sum of the quantity and amount of all products.

I am stuck, any help and ideas?

Body:
Solution 1: Use a query, like in mysql it would be -
    select sum(prod_quantity), sum(prod_amount) group by prod_name

Solution 2: Iterate over the rows to create associative array of prod_name

foreach($rows as $row) {
    $prod_name = $row['prod_name'];
    $prod[$prod_name]['amount'] = $prod[$prod_name]['amount'] + $row['prod_amount'];
    $prod[$prod_name]['quantity'] = $prod[$prod_name]['quantity'] + $row['prod_quantity'];
}

Output will be like:

Array
(
    [Product1] => Array
    (
        [amount] => 2600 //sum of prod_amount
        [quantity] => 6  //sum of prod_quantity
    )

[Product2] => Array
    (
        [amount] => 6600
        [quantity] => 5
    )
)


问:
Javascript object property not multiline
I am using a object in Javascript to store recipes and cannot get the "process" property to show as multiline. This has to be easy but not working. I am rendering the data as a
 tag in react.js.

```<code>let recipes = [

            {
                id:1,
                dish: "Chicken and Rice",
                ingredients: "Left over chicken",
                process: "1)Chop up chicken in bite sized chunks\n 2)Heat 1 Tablespoon olive oil in your favorite pan\n3) Dice any veggies in your pantry and add these and chicken to pan and heat through.\n optional: Mix with fresh rice or quinoa to make more filling."
            },
            {
                id:2,
                dish: "Beef and Rice",
                ingredients: "Left over beef",
                process: "1)Chop up chicken in bite sized chunks <br> 2)Heat 1 Tablespoon olive oil in your favorite pan 3) Dice any veggies in your pantry and add these and chicken to pan and heat through optional: Mix with fresh rice or quinoa to make more filling."
            },

            {
                id:3,
                dish: "Rice and Rice",
                ingredients: "Left over beef",

            }

]
</code>```

export default recipes;

答:
You can split up the string on \n and map each line to an element.

```<code>render: function() {
    let process = "1)Chop up chicken in bite sized chunks\n 2)Heat 1 Tablespoon olive oil in your favorite pan\n3) Dice any veggies in your pantry and add these and chicken to pan and heat through.\n optional: Mix with fresh rice or quinoa to make more filling.";
    let lines = process.split("\n");
    let mappedLines = lines.map((line)=>{
        return <p>{line}</p>
    });

    return <div>{mappedLines}</div>;
}
</code>```

https://jsfiddle.net/69z2wepo/82459/

Body:
I am using a object in Javascript to store recipes and cannot get the "process" property to show as multiline. This has to be easy but not working. I am rendering the data as a
 tag in react.js.

let recipes = [

            {
                id:1,
                dish: "Chicken and Rice",
                ingredients: "Left over chicken",
                process: "1)Chop up chicken in bite sized chunks\n 2)Heat 1 Tablespoon olive oil in your favorite pan\n3) Dice any veggies in your pantry and add these and chicken to pan and heat through.\n optional: Mix with fresh rice or quinoa to make more filling."
            },
            {
                id:2,
                dish: "Beef and Rice",
                ingredients: "Left over beef",
                process: "1)Chop up chicken in bite sized chunks
 2)Heat 1 Tablespoon olive oil in your favorite pan 3) Dice any veggies in your pantry and add these and chicken to pan and heat through optional: Mix with fresh rice or quinoa to make more filling."
            },

            {
                id:3,
                dish: "Rice and Rice",
                ingredients: "Left over beef",

            }

]

export default recipes;

Body:
You can split up the string on \n and map each line to an element.

render: function() {
    let process = "1)Chop up chicken in bite sized chunks\n 2)Heat 1 Tablespoon olive oil in your favorite pan\n3) Dice any veggies in your pantry and add these and chicken to pan and heat through.\n optional: Mix with fresh rice or quinoa to make more filling.";
    let lines = process.split("\n");
    let mappedLines = lines.map((line)=>{
        return <p>{line}</p>
    });

    return <div>{mappedLines}</div>;
}

https://jsfiddle.net/69z2wepo/82459/


问:
Get a list of elements that have attribute names that start with a specific string using XPath
I'm trying to get an array of elements that have attribute names that start with "temp" (not the attribute value, or I'd use querySelectorAll).

However, it seems that I can't quite get the xpath expression correct. Here is what seems to be the closest I've come up with:

let els = Array.from(document.evaluate(
  `//*/@*[starts-with(name(.), 'temp')]`,
  document,
  null,
  XPathResult.FIRST_ORDERED_NODE_TYPE,
  null
).singleNodeValue);

console.log(els);```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div temp-callback="1" temp-post-callback="4"></div>
<div temp-callback="2"></div>
<div></div>
<div temp-callback="8" temp-post-callback="7"></div></code>```

I would assume that would give me the 3 divs that contains at least 1 attribute with "temp."

What am I missing?

答:
I think you are looking for matching the elements with your XPath while applying the attribute name check as a filtering condition:

```<code>//*[@*[starts-with(name(), 'temp')]]
</code>```

var result = document.evaluate("//*[@*[starts-with(name(), 'temp')]]", document, null, XPathResult.ANY_TYPE, null);

var node = result.iterateNext();
var nodes = [];
while (node) {
  nodes.push(node);
  node = result.iterateNext();
}
console.log(nodes);```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div temp-callback="1" temp-post-callback="4"></div>
<div temp-callback="2"></div>
<div></div>
<div temp-callback="8" temp-post-callback="7"></div></code>```

Body:
I'm trying to get an array of elements that have attribute names that start with "temp" (not the attribute value, or I'd use querySelectorAll).

However, it seems that I can't quite get the xpath expression correct. Here is what seems to be the closest I've come up with:

let els = Array.from(document.evaluate(
  `//*/@*[starts-with(name(.), 'temp')]`,
  document,
  null,
  XPathResult.FIRST_ORDERED_NODE_TYPE,
  null
).singleNodeValue);

console.log(els);

I would assume that would give me the 3 divs that contains at least 1 attribute with "temp."

What am I missing?

Body:
I think you are looking for matching the elements with your XPath while applying the attribute name check as a filtering condition:

//*[@*[starts-with(name(), 'temp')]]

var result = document.evaluate("//*[@*[starts-with(name(), 'temp')]]", document, null, XPathResult.ANY_TYPE, null);

var node = result.iterateNext();
var nodes = [];
while (node) {
  nodes.push(node);
  node = result.iterateNext();
}
console.log(nodes);

<div temp-callback="1" temp-post-callback="4"></div>
<div temp-callback="2"></div>
<div></div>
<div temp-callback="8" temp-post-callback="7"></div>


问:
How do I display my database in table form using PHP html?
How do I display my database in table form. Here my code:

```<code><?php

$link=mysqli_connect("localhost","root","");
mysqli_select_db($link,"order");
$res=mysqli_query($link,"select * from ordersum");
while($row=mysqli_fetch_array($res))
{

echo $row["name"]." ".$row["email"]." ".$row["content"]." ".$row["date"]." ".$row["amount"];
echo "<br>";

}

?>
</code>```

答:
Your code should look like this:

```<code><table>
    <thead>
        <tr>
            <th>Name</th>
            <th>Email</th>
            <th>Content</th>
            <th>Date</th>
            <th>Amount</th>
        </tr>
    </thead>
    <tbody>
        <tr>
<?php
// your connection code here
while($row=mysqli_fetch_array($res)) { ?>
            <td><?php echo $row["name"];?></td>
            <td><?php echo $row["email"];?></td>
            <td><?php echo $row["content"];?></td>
            <td><?php echo $row["date"];?></td>
            <td><?php echo $row["amount"];?></td>
<?php } ?>
        </tr>
    </tbody>
</table>
</code>```

Try to NOT echo HTML tags, this is not a good practice, instead, close php, render html, echo your PHP values and make sure to close your loop (while, for, foreach) at the end of it.

Body:
How do I display my database in table form. Here my code:

<?php

$link=mysqli_connect("localhost","root","");
mysqli_select_db($link,"order");
$res=mysqli_query($link,"select * from ordersum");
while($row=mysqli_fetch_array($res))
{

echo $row["name"]." ".$row["email"]." ".$row["content"]." ".$row["date"]." ".$row["amount"];
echo "
";

}

?>

Body:
Your code should look like this:

<table>
    <thead>
        <tr>
            <th>Name</th>
            <th>Email</th>
            <th>Content</th>
            <th>Date</th>
            <th>Amount</th>
        </tr>
    </thead>
    <tbody>
        <tr>
<?php
// your connection code here
while($row=mysqli_fetch_array($res)) { ?>
            <td><?php echo $row["name"];?></td>
            <td><?php echo $row["email"];?></td>
            <td><?php echo $row["content"];?></td>
            <td><?php echo $row["date"];?></td>
            <td><?php echo $row["amount"];?></td>
<?php } ?>
        </tr>
    </tbody>
</table>

Try to NOT echo HTML tags, this is not a good practice, instead, close php, render html, echo your PHP values and make sure to close your loop (while, for, foreach) at the end of it.


问:
SQL Server simple Insert statement times out
I have a simple table with 6 columns. Most of the time any insert statements to it works just fine, but once in a while I'm getting a DB Timeout exception:
Timeout expired. The timeout period elapsed prior to completion of the operation or the server is not responding. The statement has been terminated.

Timeout is set to 10 seconds.

I should mention that I'm using NHibernate and that the statement also include a "select SCOPE_IDENTITY()" right after the insert itself.

My thought was that the table was locked or something, but there were no other statements running on that table at that time.

All the inserts are very simple, everything looks normal in sql profiler, the table has no indices but the PK (Page fullness: 98.57 %).

Any ideas on what should I look for?

Thanks.

答:
I think your most likely culprit is a blocking lock from another transaction (or maybe from a trigger or something else behind the scenes).

The easiest way to tell is to kick off the INSERT, and while it's hung, run EXEC SP_WHO2 in another window on the same server. This will list all of the current database activity, and has a column called BLK that will show you if any processes are currently blocked. Check the SPID of your hung connection to see if it has anything in the BLK column, and if it does, that's the process that's blocking you.

Even if you don't think there are any other statements running, the only way to know for sure is to list the current transactions using an SP like that one.

OwnerDisplayName: Meidan Alon

ContentLicense: CC BY-SA 2.5

LastEditorDisplayName: Ishmaeel

OwnerDisplayName: rwmnau


问:
How to use Jquery to check checkbox states and do something based on conditions?
Here is my setup.

```<code><input type="checkbox" name="item1" value="100" class="100" />
<input type="checkbox" name="item2" value="200" class="200" />
<input type="checkbox" name="item3" value="300" class="300" />

<p>$0.00</p>
</code>```

The criteria I need is:
change P tag to the amount selected in the checkbox
if more than 1 checkbox is checked, add the amount together and display in P tag
if 1 or more checkbox is unchecked, subtract the amount and display in P tag
if none is selected or all of them are unchecked, display ZERO in the P tag.

I only have this so far but obviously it only displays the price of that selected box and doesn't add nor does it remove when I uncheck the box.

```<code>$("input[type=checkbox]").click(function() {
var amount = $(this).attr("class");
$("p").html("$"+amount);
});
</code>```

Any help appreciated!

答:
simple try...

```<code>$("input[type=checkbox]").change(function() {
    var amount = 0;
    $("input[type=checkbox]:checked").each(function(){
        amount += parseFloat(this.value,10);
    });
    $("p").html("$"+amount);
});
</code>```

Crazy demo

Body:
Here is my setup.

<input type="checkbox" name="item1" value="100" class="100" />
<input type="checkbox" name="item2" value="200" class="200" />
<input type="checkbox" name="item3" value="300" class="300" />

$0.00

The criteria I need is:
change P tag to the amount selected in the checkbox
if more than 1 checkbox is checked, add the amount together and display in P tag
if 1 or more checkbox is unchecked, subtract the amount and display in P tag
if none is selected or all of them are unchecked, display ZERO in the P tag.

I only have this so far but obviously it only displays the price of that selected box and doesn't add nor does it remove when I uncheck the box.

$("input[type=checkbox]").click(function() {
var amount = $(this).attr("class");
$("p").html("$"+amount);
});

Any help appreciated!

Body:
simple try...

$("input[type=checkbox]").change(function() {
    var amount = 0;
    $("input[type=checkbox]:checked").each(function(){
        amount += parseFloat(this.value,10);
    });
    $("p").html("$"+amount);
});

Crazy demo


问:
SoapUI 5.3.0 Mac hangs on any use after installation
SoapUI 5.3.0 (latest open source version) Mac hangs on clean-install on MacOS 10.12.3 - with all presets suggested by the installer.

I tried rebooting & installing again - every time when you load the app it's just an eternal beach ball with no menus clickable - and requires a force quit - even after 5 minutes of just leaving it.

I've found nothing on Google about this

How can I fix this?!

答:
This is what you need to add in Info.plist</p>

```<code><key>soapui.jxbrowser.disable</key>
<true/>
</code>```

Body:
This is what you need to add in Info.plist

<key>soapui.jxbrowser.disable</key>
<true/>


问:
Move an icon to the right
I have an issue when changing a theme direction to RTL.

I have the following HTML code :

```<code><div class="header_top_right">
<div class="email">email :<a href="#"> megnor@gmail.com</a></div>
<div class="phone">Phone :<a href="#">01234567890</a></div></div>
</div>
</code>```

And the CSS :

```<code>.header_top_right .email {
background: url(../images/sprite.png) no-repeat scroll -220px -355px;
margin: 5px 0px;
}
.header_top_right .phone {
background: url(../images/sprite.png) no-repeat scroll -220px -313px;
margin: 5px 0px;
}
.header_top_right .email, .header_top_right .phone {
padding-right: 40px;
float: left;
color: #42474b;
}
</code>```

The Icon now appear on the left of the text, I want it to be in the right.
I changed the background-position but it only change the icon not it's position.

Any solution?

*PS : I can't change the HTML code

答:
HTML (same as you because you said you can't change it)

```<code><div class="header_top_right">
<div class="email">Email :<a href="#"> megnor@gmail.com</a></div>
<div class="phone">Phone :<a href="#">01234567890</a></div>
</div>
</code>```

CSS

```<code>.header_top_right > .email {
  background-image: url(https://d30y9cdsu7xlg0.cloudfront.net/png/12633-200.png);
  background-size: 10px 10px;
  background-repeat: no-repeat;
  background-position: right;
}
.header_top_right > .phone {
  background-image: url(https://cdn4.iconfinder.com/data/icons/social-icons-6/40/phone-512.png);
  background-size: 10px 10px;
  background-repeat: no-repeat;
  background-position: right;
}
.header_top_right > .email, .header_top_right > .phone {
padding-right: 15px;
margin-right: 10px;
float: left;
color: #42474b;
}
</code>```

Fiddle : https://jsfiddle.net/vqzh52d2/3/

Title: Move an icon to the right

Body:
I have an issue when changing a theme direction to RTL.

I have the following HTML code :

email : megnor@gmail.com

Phone :01234567890

And the CSS :

.header_top_right .email {
background: url(../images/sprite.png) no-repeat scroll -220px -355px;
margin: 5px 0px;
}
.header_top_right .phone {
background: url(../images/sprite.png) no-repeat scroll -220px -313px;
margin: 5px 0px;
}
.header_top_right .email, .header_top_right .phone {
padding-right: 40px;
float: left;
color: #42474b;
}

The Icon now appear on the left of the text, I want it to be in the right.
I changed the background-position but it only change the icon not it's position.

Any solution?

*PS : I can't change the HTML code

Body:
HTML (same as you because you said you can't change it)

<div class="header_top_right">
<div class="email">Email :<a href="#"> megnor@gmail.com</a></div>
<div class="phone">Phone :<a href="#">01234567890</a></div>
</div>

CSS

.header_top_right > .email {
  background-image: url(https://d30y9cdsu7xlg0.cloudfront.net/png/12633-200.png);
  background-size: 10px 10px;
  background-repeat: no-repeat;
  background-position: right;
}
.header_top_right > .phone {
  background-image: url(https://cdn4.iconfinder.com/data/icons/social-icons-6/40/phone-512.png);
  background-size: 10px 10px;
  background-repeat: no-repeat;
  background-position: right;
}
.header_top_right > .email, .header_top_right > .phone {
padding-right: 15px;
margin-right: 10px;
float: left;
color: #42474b;
}

Fiddle : https://jsfiddle.net/vqzh52d2/3/


问:
SWT x64 with xulrunner 3.6.28 x86
is there any way to run xulrunner 3.6.28 (x86 there is no other) with swt x64?

I cant use the newer xulrunner 10.4esr becouse i have some issues with it. The old one runs like a charm, but there is no x64 of it.

If i try loading 3.6.28 i get some weird errors:

```<code>org.eclipse.swt.SWTError: XPCOM error 0x80004005
    at org.eclipse.swt.browser.Mozilla.error(Unknown Source)
    at org.eclipse.swt.browser.Mozilla.initXULRunner(Unknown Source)
    at org.eclipse.swt.browser.Mozilla.create(Unknown Source)
    at org.eclipse.swt.browser.Browser.<init>(Unknown Source)
    at GUI.TFSBrowser$1.run(TFSBrowser.java:54)
</code>```

Any suggestions?

Kind regards
David

答:
I realize that this question is old, but hopefully this will help someone else who stumbles across it.

With 64-bit 4.3 SWT I was able to fix this exception by using XULRunner version 1.9.2.25 runtimes. This may not be the exact solution you are (or were) looking for since it seems you were using later XULRunner versions, however the common denominator seems to be the 64-bit libraries being used.

Originally I found the download from here: https://osdn.net/projects/sfnet_runawfe/downloads/SRC%20and%20BIN%20files/extras/xulrunner-1.9.2.25-win64.zip/

However, I have also re-hosted it as xulrunner-1.9.2.25.en-US.win64.zip.

Full explanation posted in my answer here: https://stackoverflow.com/a/44848877/3300205

Related post: Creating a SWT.MOZILLA browser on Windows 64 bit and SWT 4.3

Title: SWT x64 with xulrunner 3.6.28 x86

Body:
is there any way to run xulrunner 3.6.28 (x86 there is no other) with swt x64?

I cant use the newer xulrunner 10.4esr becouse i have some issues with it. The old one runs like a charm, but there is no x64 of it.

If i try loading 3.6.28 i get some weird errors:

org.eclipse.swt.SWTError: XPCOM error 0x80004005
    at org.eclipse.swt.browser.Mozilla.error(Unknown Source)
    at org.eclipse.swt.browser.Mozilla.initXULRunner(Unknown Source)
    at org.eclipse.swt.browser.Mozilla.create(Unknown Source)
    at org.eclipse.swt.browser.Browser.<init>(Unknown Source)
    at GUI.TFSBrowser$1.run(TFSBrowser.java:54)

Any suggestions?

Kind regards
David


问:
Is File.Delete() atomic under .NET
Target OS: Win2003

As posted in other SO questions about file operation atomicity, Win32 was simply not designed for transactions. Still I wonder whether file deletion could be non-atomic. After all, it is either get deleted or not. Or can a file remain in any other intermediate state on NTFS file system caused by a system crash or something else during deletion?

答:
Old question, but if I could add to @Mehdrad's answer, from a slightly different standpoint...

On Windows, deleting a file often isn't even completely synchronous, and it isn't even a single operation.  In that sense it's definitely not atomic.

If you look at tools like process monitor or look at MSFT documentation for writing a filesystem driver, you'll notice that to delete a file on Windows is a multi-step process.  First you need a handle to the file.  Then you set its disposition to "deleted".  This puts the file in a state where it has a "delete pending".  The file won't even be removed from view until the last handle to it is closed.  When a file is in this state, new attempts to open the file will fail with STATUS_DELETE_PENDING.  This status is more of a runtime thing -- if you pulled the plug or did a reboot the files won't stay in that state.

So, it may or may not be relevant to the way you're using deletes, but it's important to keep in mind that on Windows a delete won't necessary take effect right away and under concurrent access may lock further requests out of getting to the file.

Title: Is File.Delete() atomic under .NET


问:
Highlight the search text - angular 2
A messenger displays the search results based on the input given by the user. Need to highlight the word that is been searched, while displaying the result.
These are the html and component that is been used.

Component.html

```<code> <div *ngFor = "let result of resultArray">
<div>Id : result.id </div>
<div>Summary : result.summary </div>
<div> Link : result.link </div>
</div>
</code>```

Component.ts

```<code>resultArray : any = [{"id":"1","summary":"These are the results for the searched text","link":"http://www.example.com"}]
</code>```

This resultArray is fetched from hitting the backend service by sending the search text as input. Based on the search text, the result is fetched. Need to highlight the searched text, similar to google search. Please find the screenshot,

If I search for the word "member", the occurence of the word "member" gets highlighted. How to achieve the same using angular 2. Please suggest an idea on this.

答:
You can do that by creating a pipe and applying that pipe to the summary part of array inside ngfor. Here is the code for Pipe:

```<code>import { Pipe, PipeTransform } from '@angular/core';

@Pipe({
    name: 'highlight'
})

export class HighlightSearch implements PipeTransform {

    transform(value: any, args: any): any {
        if (!args) {return value;}
        var re = new RegExp(args, 'gi'); //'gi' for case insensitive and can use 'g' if you want the search to be case sensitive.
        return value.replace(re, "<mark>$&</mark>");
    }
}
</code>```

and then in markup apply it on a string like this:

```<code><div innerHTML="{{ str | highlight : 'search'}}"></div>
</code>```

Replace 'search' with the word you want to highlight.

Hope this will help.

Title: Highlight the search text - angular 2

Body:
A messenger displays the search results based on the input given by the user. Need to highlight the word that is been searched, while displaying the result.
These are the html and component that is been used.

Component.html

Id : result.id

Summary : result.summary

 Link : result.link

Component.ts

resultArray : any = [{"id":"1","summary":"These are the results for the searched text","link":"http://www.example.com"}]

This resultArray is fetched from hitting the backend service by sending the search text as input. Based on the search text, the result is fetched. Need to highlight the searched text, similar to google search. Please find the screenshot,

If I search for the word "member", the occurence of the word "member" gets highlighted. How to achieve the same using angular 2. Please suggest an idea on this.

Body:
You can do that by creating a pipe and applying that pipe to the summary part of array inside ngfor. Here is the code for Pipe:

import { Pipe, PipeTransform } from '@angular/core';

@Pipe({
    name: 'highlight'
})

export class HighlightSearch implements PipeTransform {

    transform(value: any, args: any): any {
        if (!args) {return value;}
        var re = new RegExp(args, 'gi'); //'gi' for case insensitive and can use 'g' if you want the search to be case sensitive.
        return value.replace(re, "<mark>$&</mark>");
    }
}

and then in markup apply it on a string like this:

<div innerHTML="{{ str | highlight : 'search'}}"></div>

Replace 'search' with the word you want to highlight.

Hope this will help.

ContentLicense: CC BY-SA 4.0


问:
How to iterate through members of a class
This:

```<code>class Loan
    def initialize(amount, interest)
        @amount = amount
        @interest = interest
    end
end

loan1 = Loan.new(100, 0.1)

Loan.each do |amount, interest|
    debt = debt + amount + (amount*interest)
end
</code>```

won't work because it's attempting to iterate over a class rather than an array or hash. Is there a away to iterate over all of the instances of a class?

答:
You can do something like this: Add a few accessors for amount and interest then use the ObjectSpace object along with inject to sum up your debts.

```<code>class Loan
  attr_accessor :amount, :interest
    def initialize(amount, interest)
      @amount = amount
      @interest = interest
    end
end

loan1 = Loan.new(100, 0.1)
loan2 = Loan.new(200, 0.1)

debt = ObjectSpace.each_object(Loan).inject(0) { |sum, obj|
  sum + obj.amount + obj.amount * obj.interest
}

debt #=> 330.0
</code>```

Body:
This:

class Loan
    def initialize(amount, interest)
        @amount = amount
        @interest = interest
    end
end

loan1 = Loan.new(100, 0.1)

Loan.each do |amount, interest|
    debt = debt + amount + (amount*interest)
end

won't work because it's attempting to iterate over a class rather than an array or hash. Is there a away to iterate over all of the instances of a class?

Body:
You can do something like this: Add a few accessors for amount and interest then use the ObjectSpace object along with inject to sum up your debts.

class Loan
  attr_accessor :amount, :interest
    def initialize(amount, interest)
      @amount = amount
      @interest = interest
    end
end

loan1 = Loan.new(100, 0.1)
loan2 = Loan.new(200, 0.1)

debt = ObjectSpace.each_object(Loan).inject(0) { |sum, obj|
  sum + obj.amount + obj.amount * obj.interest
}

debt #=> 330.0


问:
ASP.NET MVC Populate DropDown thru ViewBag
I am a beginner to ASP.NET MVC technology.
   In my View page, I have a WebGrid that is bind to data that is passed from Controller. I also want to populate a dropdown list with the list of Tables in the database. I retrieve the tables List from a helper method. I am trying to send the List to the ViewBag and want to populate the dropdown; but can't get it. Some syntax error is only coming or the List is not accessible.

My Controller class :

```<code>        [Authorize]
    public ActionResult Index(int page = 1, string sort = "FirstName", string sortdir = "asc", string search = "")
    {
        int pageSize = 10;
        int totalRecord = 0;
        if (page < 1)
            page = 1;
        int skip = (page * pageSize) - pageSize;
        var data = GetUsers(search, sort, sortdir, skip, pageSize, out totalRecord);

        // Get Tables List
        ViewBag.TableList = DataFiller.GetTableNames();
        ViewBag.TotalRows = totalRecord;

        return View(data);
    }
</code>```

View file :

```<code>@model List<DataStudio.Models.User>

@{
ViewBag.Title = "Index";
Layout = "~/Views/Shared/_MemberLayout.cshtml";

<!-- data is used for grid -->
var grid = new WebGrid(canPage: true, rowsPerPage: 10);
grid.Bind(source: Model, rowCount: ViewBag.TotalRows, autoSortAndPage: false);
}

<!-- ERROR LINE   -->
@Html.DropDownList("tableName", @ViewBag.TableList, "Select Table")
</code>```

ERROR

```<code>Error   CS1973  'HtmlHelper<List<User>>' has no applicable method named 'DropDownList' but appears to have an extension method by that name. Extension methods cannot be dynamically dispatched. Consider casting the dynamic arguments or calling the extension method without the extension method syntax.    1_Views_Member_Index.cshtml Index.cshtml    82  Active
</code>```

The User model doesn't contain any List nor any DropDownList. The drop down is a totally separate combo box, that I want to fill with a List items; it just contains the list of table names from the database.

I am not able to get how do I bind or populate the drop down list with the SelectLiteItem items. I googled a lot, but could not get any example with this scenario. I don't wish to add my List with my model. And, I want to populate the Tables list drop down only once.

Can anyone please help me and guide me how do I achieve the goal. Any help is highly appreciated.

Thanks

Tom

UPDATE:
The DataFilter.GetTableNames() method

```<code>       public static List<SelectListItem> GetTableNames()
    {
        List<SelectListItem> tablesList = new List<SelectListItem>();

        string sql = "SELECT * FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_TYPE = 'BASE TABLE'";
        string conStr = System.Configuration.ConfigurationManager.ConnectionStrings["DMSDbConnectionString"].ToString();

        using (SqlConnection con = new SqlConnection(conStr))
        {
            using (SqlCommand com = new SqlCommand(sql, con)) {
                con.Open();
                using(SqlDataReader sdr = com.ExecuteReader() )
                {
                    while (sdr.Read())
                    {
                        tablesList.Add(new SelectListItem
                        {
                            Text = sdr["TABLE_NAME"].ToString(),
                            Value = sdr["TABLE_NAME"].ToString()
                        });
                    }
                }

                /*
                SqlDataAdapter da = new SqlDataAdapter(com);
                DataSet ds = new DataSet();
                da.Fill(ds);

                DataTable dt = ds.Tables[0];

                tablesList = (from DataRow dr in dt.Rows
                              select new TablesInfo()
                              {
                                  TableCatalog = dr["TABLE_CATALOG"].ToString(),
                                  TableName = dr["TABLE_NAME"].ToString(),
                                  TableSchema = dr["TABLE_SCHEMA"].ToString(),
                                  TableType = dr["TABLE_TYPE"].ToString(),
                              }).ToList();

                    */
                con.Close();
            }
        }
        return tablesList;
    }
</code>```

I had created a class also TablesInfo to populate data in it and use strong typed object. But, as couldn't find a way to populate it, so used SelectListItem.
And as it contains only list of tables, so I don't wish it to be populated on every refresh of the page.

答:
As Tetsuya stated, you should be using a strongly typed view model.

You can structure your model like this:

```<code> public class MyUserCollection
    {
        public List<MyUser> Users { get; set; }
        public SelectList TableList { get; set; }
        public int TotalRows { get; set; }

        public MyUserCollection(string search, string sort, string sortdir, int skip, int pageSize)
        {
            TableList = DataFiller.GetTableNames();

            Users = GetUsers(search, sort, sortdir, skip, pageSize, out totalRecord);
        }
    }
</code>```

Then to create your drop down:

```<code>@Html.DropDownListFor(model => model.tableName, Model.TableList as SelectList, "Select Table")
</code>```

Other wise you need to cast your object:

```<code>@Html.DropDownList("tableName", (SelectList)ViewBag.TableList, "Select Table")
</code>```

Body:
I am a beginner to ASP.NET MVC technology.
   In my View page, I have a WebGrid that is bind to data that is passed from Controller. I also want to populate a dropdown list with the list of Tables in the database. I retrieve the tables List from a helper method. I am trying to send the List to the ViewBag and want to populate the dropdown; but can't get it. Some syntax error is only coming or the List is not accessible.

My Controller class :

        [Authorize]
    public ActionResult Index(int page = 1, string sort = "FirstName", string sortdir = "asc", string search = "")
    {
        int pageSize = 10;
        int totalRecord = 0;
        if (page < 1)
            page = 1;
        int skip = (page * pageSize) - pageSize;
        var data = GetUsers(search, sort, sortdir, skip, pageSize, out totalRecord);

        // Get Tables List
        ViewBag.TableList = DataFiller.GetTableNames();
        ViewBag.TotalRows = totalRecord;

        return View(data);
    }

View file :

@model List<DataStudio.Models.User>

@{
ViewBag.Title = "Index";
Layout = "~/Views/Shared/_MemberLayout.cshtml";

var grid = new WebGrid(canPage: true, rowsPerPage: 10);
grid.Bind(source: Model, rowCount: ViewBag.TotalRows, autoSortAndPage: false);
}

@Html.DropDownList("tableName", @ViewBag.TableList, "Select Table")

ERROR

Error   CS1973  'HtmlHelper<List<User>>' has no applicable method named 'DropDownList' but appears to have an extension method by that name. Extension methods cannot be dynamically dispatched. Consider casting the dynamic arguments or calling the extension method without the extension method syntax.    1_Views_Member_Index.cshtml Index.cshtml    82  Active

The User model doesn't contain any List nor any DropDownList. The drop down is a totally separate combo box, that I want to fill with a List items; it just contains the list of table names from the database.

I am not able to get how do I bind or populate the drop down list with the SelectLiteItem items. I googled a lot, but could not get any example with this scenario. I don't wish to add my List with my model. And, I want to populate the Tables list drop down only once.

Can anyone please help me and guide me how do I achieve the goal. Any help is highly appreciated.

Thanks

Tom

UPDATE:
The DataFilter.GetTableNames() method

       public static List<SelectListItem> GetTableNames()
    {
        List<SelectListItem> tablesList = new List<SelectListItem>();

        string sql = "SELECT * FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_TYPE = 'BASE TABLE'";
        string conStr = System.Configuration.ConfigurationManager.ConnectionStrings["DMSDbConnectionString"].ToString();

        using (SqlConnection con = new SqlConnection(conStr))
        {
            using (SqlCommand com = new SqlCommand(sql, con)) {
                con.Open();
                using(SqlDataReader sdr = com.ExecuteReader() )
                {
                    while (sdr.Read())
                    {
                        tablesList.Add(new SelectListItem
                        {
                            Text = sdr["TABLE_NAME"].ToString(),
                            Value = sdr["TABLE_NAME"].ToString()
                        });
                    }
                }

                /*
                SqlDataAdapter da = new SqlDataAdapter(com);
                DataSet ds = new DataSet();
                da.Fill(ds);

                DataTable dt = ds.Tables[0];

                tablesList = (from DataRow dr in dt.Rows
                              select new TablesInfo()
                              {
                                  TableCatalog = dr["TABLE_CATALOG"].ToString(),
                                  TableName = dr["TABLE_NAME"].ToString(),
                                  TableSchema = dr["TABLE_SCHEMA"].ToString(),
                                  TableType = dr["TABLE_TYPE"].ToString(),
                              }).ToList();

                    */
                con.Close();
            }
        }
        return tablesList;
    }

I had created a class also TablesInfo to populate data in it and use strong typed object. But, as couldn't find a way to populate it, so used SelectListItem.
And as it contains only list of tables, so I don't wish it to be populated on every refresh of the page.

Body:
As Tetsuya stated, you should be using a strongly typed view model.

You can structure your model like this:

 public class MyUserCollection
    {
        public List<MyUser> Users { get; set; }
        public SelectList TableList { get; set; }
        public int TotalRows { get; set; }

        public MyUserCollection(string search, string sort, string sortdir, int skip, int pageSize)
        {
            TableList = DataFiller.GetTableNames();

            Users = GetUsers(search, sort, sortdir, skip, pageSize, out totalRecord);
        }
    }

Then to create your drop down:

@Html.DropDownListFor(model => model.tableName, Model.TableList as SelectList, "Select Table")

Other wise you need to cast your object:

@Html.DropDownList("tableName", (SelectList)ViewBag.TableList, "Select Table")


问:
How to remove extra comma when concatenating strings
```<code>$folders = Get-ChildItem | where {$_.Attributes -match 'Directory'}
foreach ($items in $folders)
{
$type = $items.name
$cat = $cat + "," + "$type/*.$type
}
$cat
</code>```

This is supposed to print text, text but instead it adds an extra comma I understand due to how the script is written it will cause it to add the extra comma. I am trying to figure out if there is another way to write this that removes the extra comma.

This is written with concatenation because of off the top of my head it seemed simpler because everything is under one variable and what is being passed to works well in this situation.

答:
If you're on a newer PowerShell:

```<code>(Get-ChildItem -Directory) -join ', '

(gci -dir) -join ', '
</code>```

Older / more serious:

```<code>(Get-ChildItem | Where-Object { $_.PsIsContainer } | Select-Object -ExpandProperty Name) -join ', '
</code>```

Because why not:

```<code>$OFS=', ';"$(gci -di)"
</code>```

Body:
$folders = Get-ChildItem | where {$_.Attributes -match 'Directory'}
foreach ($items in $folders)
{
$type = $items.name
$cat = $cat + "," + "$type/*.$type
}
$cat

This is supposed to print text, text but instead it adds an extra comma I understand due to how the script is written it will cause it to add the extra comma. I am trying to figure out if there is another way to write this that removes the extra comma.

This is written with concatenation because of off the top of my head it seemed simpler because everything is under one variable and what is being passed to works well in this situation.

Body:
If you're on a newer PowerShell:

(Get-ChildItem -Directory) -join ', '

(gci -dir) -join ', '

Older / more serious:

(Get-ChildItem | Where-Object { $_.PsIsContainer } | Select-Object -ExpandProperty Name) -join ', '

Because why not:

$OFS=', ';"$(gci -di)"


问:
Query to retrieve neighbors is too slow
I have a set of Django ORM models representing a directed graph, and I'm trying to retrieve all the adjacent vertices to a given vertex ignoring edge direction:

```<code>class Vertex(models.Model):
    pass

class Edge(models.Model):
    orig = models.ForeignKey(Vertex, related_name='%(class)s_orig', null=True, blank=True)
    dest = models.ForeignKey(Vertex, related_name='%(class)s_dest', null=True, blank=True)
    # ... other data about this edge ...
</code>```

The query Vertex.objects.filter(Q(edge_orig__dest=v) | Q(edge_dest__orig=v)).distinct() returns the correct result, but in my case it takes far too long to execute.

Typically for my application there will be around 50-100 vertices at any given time, and around a million edges. Even reducing it to only 20 vertices and 100000 edges, that query takes about a minute and a half to execute:

```<code>for i in range(20):
    Vertex().save()

vxs = list(Vertex.objects.all())
for i in tqdm.tqdm(range(100000)):
    Edge(orig = random.sample(vxs,1)[0], dest = random.sample(vxs,1)[0]).save()

v = vxs[0]
def f1():
    return list( Vertex.objects.filter(
        Q(edge_orig__dest=v) | Q(edge_dest__orig=v)).distinct() )

t1 = timeit.Timer(f1)

print( t1.timeit(number=1) ) # 84.21138522100227
</code>```

On the other hand, if I split the query up into two pieces I can get the exact same result in only a handful of milliseconds:

```<code>def f2():
    q1 = Vertex.objects.filter(edge_orig__dest=v).distinct()
    q2 = Vertex.objects.filter(edge_dest__orig=v).distinct()
    return list( {x for x in itertools.chain(q1, q2)} )

t2 = timeit.Timer(f2)
print( t2.timeit(number=100)/100 ) # 0.0109818680600074
</code>```

This second version has issues though:

It's not atomic. The list of edges is almost guaranteed to change between the two queries in my application, meaning the results won't represent a single point in time.

I can't perform additional processing and aggregation on the results without manually looping over it. (e.g. If I wanted Vertex.objects.filter(Q(edge_orig__dest=v) | Q(edge_dest__orig=v)).distinct().aggregate(avg=Avg('some_field')))

Why does the second version run so much faster than the first one?
How can I do this, and is there a way to get the first one to run fast enough for practical use?

I'm currently testing with Python 3.5.2, PostgreSQL 9.5.6, and Django 1.11, although if this is an issue with one of those I'm not stuck with them.

Here is the SQL generated by each query, as well as Postgres's explan:

The first one:

```<code>Vertex.objects.filter(Q(edge_orig__dest=v) | Q(edge_dest__orig=v))

SELECT DISTINCT "app_vertex"."id"
FROM "app_vertex"
LEFT OUTER JOIN "app_edge" ON ("app_vertex"."id" = "app_edge"."orig_id")
LEFT OUTER JOIN "app_edge" T4 ON ("app_vertex"."id" = T4."dest_id")
WHERE ("app_edge"."dest_id" = 1061
       OR T4."orig_id" = 1061)

HashAggregate  (cost=8275151.47..8275151.67 rows=20 width=4)
  Group Key: app_vertex.id
  ->  Hash Left Join  (cost=3183.45..8154147.45 rows=48401608 width=4)
        Hash Cond: (app_vertex.id = app_edge.orig_id)
        Filter: ((app_edge.dest_id = 1061) OR (t4.orig_id = 1061))
        ->  Hash Right Join  (cost=1.45..2917.45 rows=100000 width=8)
              Hash Cond: (t4.dest_id = app_vertex.id)
              ->  Seq Scan on app_edge t4  (cost=0.00..1541.00 rows=100000 width=8)
              ->  Hash  (cost=1.20..1.20 rows=20 width=4)
                    ->  Seq Scan on app_vertex  (cost=0.00..1.20 rows=20 width=4)
        ->  Hash  (cost=1541.00..1541.00 rows=100000 width=8)
              ->  Seq Scan on app_edge  (cost=0.00..1541.00 rows=100000 width=8)
</code>```

The second ones:

```<code>Vertex.objects.filter(edge_orig__dest=v).distinct()

SELECT DISTINCT "app_vertex"."id"
FROM "app_vertex"
INNER JOIN "app_edge" ON ("app_vertex"."id" = "app_edge"."orig_id")
WHERE "app_edge"."dest_id" = 1061

HashAggregate  (cost=1531.42..1531.62 rows=20 width=4)
  Group Key: app_vertex.id
  ->  Hash Join  (cost=848.11..1519.04 rows=4950 width=4)
        Hash Cond: (app_edge.orig_id = app_vertex.id)
        ->  Bitmap Heap Scan on app_edge  (cost=846.65..1449.53 rows=4950 width=4)
              Recheck Cond: (dest_id = 1061)
              ->  Bitmap Index Scan on app_edge_dest_id_4254b90f  (cost=0.00..845.42 rows=4950 width=0)
                    Index Cond: (dest_id = 1061)
        ->  Hash  (cost=1.20..1.20 rows=20 width=4)
              ->  Seq Scan on app_vertex  (cost=0.00..1.20 rows=20 width=4)
</code>```

@khampson's version also takes a minute-and-a-half to run, so it's also a no-go.

```<code>Vertex.objects.raw( ... )

SELECT DISTINCT "app_vertex"."id"
FROM "app_vertex"
JOIN "app_edge" ON ("app_vertex"."id" = "app_edge"."orig_id")
JOIN "app_edge" T4 ON ("app_vertex"."id" = T4."dest_id")
WHERE ("app_edge"."dest_id" = 1061
       OR T4."orig_id" = 1061);

HashAggregate  (cost=8275347.47..8275347.67 rows=20 width=4)
  Group Key: app_vertex.id
  ->  Hash Join  (cost=3183.45..8154343.45 rows=48401608 width=4)
        Hash Cond: (app_vertex.id = app_edge.orig_id)
        Join Filter: ((app_edge.dest_id = 1061) OR (t4.orig_id = 1061))
        ->  Hash Join  (cost=1.45..2917.45 rows=100000 width=12)
              Hash Cond: (t4.dest_id = app_vertex.id)
              ->  Seq Scan on app_edge t4  (cost=0.00..1541.00 rows=100000 width=8)
              ->  Hash  (cost=1.20..1.20 rows=20 width=4)
                    ->  Seq Scan on app_vertex  (cost=0.00..1.20 rows=20 width=4)
        ->  Hash  (cost=1541.00..1541.00 rows=100000 width=8)
              ->  Seq Scan on app_edge  (cost=0.00..1541.00 rows=100000 width=8)
</code>```

答:
I propose another query could be:

# Get edges which contain Vertex v, "only" optimizes fields returned
edges = Edge.objects.filter(Q(orig=v) | Q(dest=v)).only('orig_id', 'dest_id')
# Get set of vertex id's to discard duplicates
vertex_ids = {*edges.values_list('orig_id', flat=True), *edges_values_list('dest_id', flat=True)}
# Get list of vertices, excluding the original vertex
vertices = Vertex.objects.filter(pk__in=vertex_ids).exclude(pk=v.pk)
```

This shouldn't require any joins and shouldn't suffer from the race conditions you mention.

Title: Query to retrieve neighbors is too slow

Body:
I have a set of Django ORM models representing a directed graph, and I'm trying to retrieve all the adjacent vertices to a given vertex ignoring edge direction:

class Vertex(models.Model):
    pass

class Edge(models.Model):
    orig = models.ForeignKey(Vertex, related_name='%(class)s_orig', null=True, blank=True)
    dest = models.ForeignKey(Vertex, related_name='%(class)s_dest', null=True, blank=True)
    # ... other data about this edge ...

The query Vertex.objects.filter(Q(edge_orig__dest=v) | Q(edge_dest__orig=v)).distinct() returns the correct result, but in my case it takes far too long to execute.

Typically for my application there will be around 50-100 vertices at any given time, and around a million edges. Even reducing it to only 20 vertices and 100000 edges, that query takes about a minute and a half to execute:

for i in range(20):
    Vertex().save()

vxs = list(Vertex.objects.all())
for i in tqdm.tqdm(range(100000)):
    Edge(orig = random.sample(vxs,1)[0], dest = random.sample(vxs,1)[0]).save()

v = vxs[0]
def f1():
    return list( Vertex.objects.filter(
        Q(edge_orig__dest=v) | Q(edge_dest__orig=v)).distinct() )

t1 = timeit.Timer(f1)

print( t1.timeit(number=1) ) # 84.21138522100227

On the other hand, if I split the query up into two pieces I can get the exact same result in only a handful of milliseconds:

def f2():
    q1 = Vertex.objects.filter(edge_orig__dest=v).distinct()
    q2 = Vertex.objects.filter(edge_dest__orig=v).distinct()
    return list( {x for x in itertools.chain(q1, q2)} )

t2 = timeit.Timer(f2)
print( t2.timeit(number=100)/100 ) # 0.0109818680600074

This second version has issues though:

It's not atomic. The list of edges is almost guaranteed to change between the two queries in my application, meaning the results won't represent a single point in time.

I can't perform additional processing and aggregation on the results without manually looping over it. (e.g. If I wanted Vertex.objects.filter(Q(edge_orig__dest=v) | Q(edge_dest__orig=v)).distinct().aggregate(avg=Avg('some_field')))

Why does the second version run so much faster than the first one?
How can I do this, and is there a way to get the first one to run fast enough for practical use?

I'm currently testing with Python 3.5.2, PostgreSQL 9.5.6, and Django 1.11, although if this is an issue with one of those I'm not stuck with them.

Here is the SQL generated by each query, as well as Postgres's explan:

The first one:

Vertex.objects.filter(Q(edge_orig__dest=v) | Q(edge_dest__orig=v))

SELECT DISTINCT "app_vertex"."id"
FROM "app_vertex"
LEFT OUTER JOIN "app_edge" ON ("app_vertex"."id" = "app_edge"."orig_id")
LEFT OUTER JOIN "app_edge" T4 ON ("app_vertex"."id" = T4."dest_id")
WHERE ("app_edge"."dest_id" = 1061
       OR T4."orig_id" = 1061)

HashAggregate  (cost=8275151.47..8275151.67 rows=20 width=4)
  Group Key: app_vertex.id
  ->  Hash Left Join  (cost=3183.45..8154147.45 rows=48401608 width=4)
        Hash Cond: (app_vertex.id = app_edge.orig_id)
        Filter: ((app_edge.dest_id = 1061) OR (t4.orig_id = 1061))
        ->  Hash Right Join  (cost=1.45..2917.45 rows=100000 width=8)
              Hash Cond: (t4.dest_id = app_vertex.id)
              ->  Seq Scan on app_edge t4  (cost=0.00..1541.00 rows=100000 width=8)
              ->  Hash  (cost=1.20..1.20 rows=20 width=4)
                    ->  Seq Scan on app_vertex  (cost=0.00..1.20 rows=20 width=4)
        ->  Hash  (cost=1541.00..1541.00 rows=100000 width=8)
              ->  Seq Scan on app_edge  (cost=0.00..1541.00 rows=100000 width=8)

The second ones:

Vertex.objects.filter(edge_orig__dest=v).distinct()

SELECT DISTINCT "app_vertex"."id"
FROM "app_vertex"
INNER JOIN "app_edge" ON ("app_vertex"."id" = "app_edge"."orig_id")
WHERE "app_edge"."dest_id" = 1061

HashAggregate  (cost=1531.42..1531.62 rows=20 width=4)
  Group Key: app_vertex.id
  ->  Hash Join  (cost=848.11..1519.04 rows=4950 width=4)
        Hash Cond: (app_edge.orig_id = app_vertex.id)
        ->  Bitmap Heap Scan on app_edge  (cost=846.65..1449.53 rows=4950 width=4)
              Recheck Cond: (dest_id = 1061)
              ->  Bitmap Index Scan on app_edge_dest_id_4254b90f  (cost=0.00..845.42 rows=4950 width=0)
                    Index Cond: (dest_id = 1061)
        ->  Hash  (cost=1.20..1.20 rows=20 width=4)
              ->  Seq Scan on app_vertex  (cost=0.00..1.20 rows=20 width=4)

@khampson's version also takes a minute-and-a-half to run, so it's also a no-go.

Vertex.objects.raw( ... )

SELECT DISTINCT "app_vertex"."id"
FROM "app_vertex"
JOIN "app_edge" ON ("app_vertex"."id" = "app_edge"."orig_id")
JOIN "app_edge" T4 ON ("app_vertex"."id" = T4."dest_id")
WHERE ("app_edge"."dest_id" = 1061
       OR T4."orig_id" = 1061);

HashAggregate  (cost=8275347.47..8275347.67 rows=20 width=4)
  Group Key: app_vertex.id
  ->  Hash Join  (cost=3183.45..8154343.45 rows=48401608 width=4)
        Hash Cond: (app_vertex.id = app_edge.orig_id)
        Join Filter: ((app_edge.dest_id = 1061) OR (t4.orig_id = 1061))
        ->  Hash Join  (cost=1.45..2917.45 rows=100000 width=12)
              Hash Cond: (t4.dest_id = app_vertex.id)
              ->  Seq Scan on app_edge t4  (cost=0.00..1541.00 rows=100000 width=8)
              ->  Hash  (cost=1.20..1.20 rows=20 width=4)
                    ->  Seq Scan on app_vertex  (cost=0.00..1.20 rows=20 width=4)
        ->  Hash  (cost=1541.00..1541.00 rows=100000 width=8)
              ->  Seq Scan on app_edge  (cost=0.00..1541.00 rows=100000 width=8)

Body:
I propose another query could be:

# Get edges which contain Vertex v, "only" optimizes fields returned
edges = Edge.objects.filter(Q(orig=v) | Q(dest=v)).only('orig_id', 'dest_id')
# Get set of vertex id's to discard duplicates
vertex_ids = {*edges.values_list('orig_id', flat=True), *edges_values_list('dest_id', flat=True)}
# Get list of vertices, excluding the original vertex
vertices = Vertex.objects.filter(pk__in=vertex_ids).exclude(pk=v.pk)

This shouldn't require any joins and shouldn't suffer from the race conditions you mention.


问:
Using the 64bit XulRunner in Eclipse SWT under Windows
Is it possible to use the 64bit XulRunner for Windows (available from here) with the Eclipse browser widget? It works fine under 32bit Windows and the answer to this question explains how this works. But when I try this under 64bit Windows I get the following exception:

```<code> org.eclipse.swt.SWTError: No more handles (java.lang.UnsatisfiedLinkError: Could not
 load SWT library. Reasons:
   no swt-xulrunner-win32-3834 in java.library.path
   no swt-xulrunner-win32 in java.library.path
   Can't load library:
     C:\Users\...\.swt\lib\win32\x86_64\swt-xulrunner-win32- 3834.dll
     Can't load library: C:\Users\...\.swt\lib\win32\x86_64\swt-xulrunner-win32.dll
    at org.eclipse.swt.SWT.error(SWT.java:4387)
    at org.eclipse.swt.SWT.error(SWT.java:4276)
    at org.eclipse.swt.browser.Mozilla.initXULRunner(Mozilla.java:2594)
    at org.eclipse.swt.browser.Mozilla.create(Mozilla.java:684)
    at org.eclipse.swt.browser.Browser.<init>(Browser.java:99)
    at org.openlca.ui.BrowserFactory.createMozilla(BrowserFactory.java:52)
</code>```

Thanks for help,
Michael

Edit:
I found it in the Eclipse bug-tracker (link here):

swt's 64-bit Windows port does not have xulrunner support because mozilla.org does not provide a 64-bit xulrunner on Windows

But as the last comment on this bug says, there is a 64bit XulRunner available

答:
I realize that this question is old and already has an accepted answer, but in regards to the XPCOM error 0x80004005, I may be able to help.

With 64-bit 4.3 SWT I was able to fix this exception by using XULRunner version 1.9.2.25 runtimes. Originally I found the download from here: https://osdn.net/projects/sfnet_runawfe/downloads/SRC%20and%20BIN%20files/extras/xulrunner-1.9.2.25-win64.zip/

However, I have also re-hosted it as xulrunner-1.9.2.25.en-US.win64.zip.

Full explanation posted in my answer here: https://stackoverflow.com/a/44848877/3300205

Body:
Is it possible to use the 64bit XulRunner for Windows (available from here) with the Eclipse browser widget? It works fine under 32bit Windows and the answer to this question explains how this works. But when I try this under 64bit Windows I get the following exception:

 org.eclipse.swt.SWTError: No more handles (java.lang.UnsatisfiedLinkError: Could not
 load SWT library. Reasons:
   no swt-xulrunner-win32-3834 in java.library.path
   no swt-xulrunner-win32 in java.library.path
   Can't load library:
     C:\Users\...\.swt\lib\win32\x86_64\swt-xulrunner-win32- 3834.dll
     Can't load library: C:\Users\...\.swt\lib\win32\x86_64\swt-xulrunner-win32.dll
    at org.eclipse.swt.SWT.error(SWT.java:4387)
    at org.eclipse.swt.SWT.error(SWT.java:4276)
    at org.eclipse.swt.browser.Mozilla.initXULRunner(Mozilla.java:2594)
    at org.eclipse.swt.browser.Mozilla.create(Mozilla.java:684)
    at org.eclipse.swt.browser.Browser.<init>(Browser.java:99)
    at org.openlca.ui.BrowserFactory.createMozilla(BrowserFactory.java:52)

Thanks for help,
Michael

Edit:
I found it in the Eclipse bug-tracker (link here):

swt's 64-bit Windows port does not have xulrunner support because mozilla.org does not provide a 64-bit xulrunner on Windows

But as the last comment on this bug says, there is a 64bit XulRunner available


问:
JQuery Not Working in Chrome
This code works properly in Firefox but not in Chrome, If you need more of the code I would be glad to provide it, a button changes a background image:

```<code>$(document).ready(function() {
var bg = 1;
$("#changePic").click(function () {
    if (bg == 1)
    {
        $("#outerWrapper").css("background-image","url(images/background-lodge1.jpg");
        bg=2;
    }
    else if (bg == 2)
    {
        $("#outerWrapper").css("background-image","url(images/background-lodge2.jpg");
        bg=3;
    }
    else
    {
        $("#outerWrapper").css("background-image","url(images/background-lodge.jpg");
        bg=1;
    }
  });
});
</code>```

I'm not getting any errors in the Chrome Console. Thanks!

答: To see what javascript errors are there in chrome, press "ctrl+shift+I" and go to console tab. or "ctrl+shift+J" to go to Console tab directly.

Title: JQuery Not Working in Chrome

Body:
This code works properly in Firefox but not in Chrome, If you need more of the code I would be glad to provide it, a button changes a background image:

$(document).ready(function() {
var bg = 1;
$("#changePic").click(function () {
    if (bg == 1)
    {
        $("#outerWrapper").css("background-image","url(images/background-lodge1.jpg");
        bg=2;
    }
    else if (bg == 2)
    {
        $("#outerWrapper").css("background-image","url(images/background-lodge2.jpg");
        bg=3;
    }
    else
    {
        $("#outerWrapper").css("background-image","url(images/background-lodge.jpg");
        bg=1;
    }
  });
});

I'm not getting any errors in the Chrome Console. Thanks!


问:
How to build a Carthage framework from git branch
Alamofire has a bug that is fixed in a future release. The author has already fixed the bug and the solution is merged in the master branch. Is there any way for me to use carthage so I can create a framework file that includes this fix? Currently when I use carthage against AF repo it clones release v4.4 which still has the bug.

I would also be open to a solution, where in I can checkout the latest code from AF repo on my local machine and use carthage to create a framework locally. I just want the SessionDelegate.swift file to contain the latest code so I can move forward with my testing.

答:
In short, the branch can be referenced by name by using the following in your Cartfile:

github "Alamofire/Alamofire" "branch-name"

For a little bit more in-depth explanation of what this can accomplish, consult the documentation:

Carthage supports several kinds of version requirements:

>= 1.0 for “at least version 1.0”

~> 1.0 for “compatible with version 1.0”

== 1.0 for “exactly version 1.0”

"some-branch-or-tag-or-commit" for a specific Git object (anything allowed by git rev-parse)

I found the answer here, but felt the question was not a duplicate, despite the fact that the answer is.


问:
Capistrano 3.x running a task programatically from ruby
Im trying to run a capistrano 3.x task from a ruby script.

I dive into the docs and in older versions of capistrano (2.x) you have Capistrano::CLI interface to access and execute tasks.

In newer versions this module seems to be gone, i can't find anything similar.

I was trying with Capistrano::DSL without no luck.

To make it clear, im looking something like this:

```<code>require 'capistrano/all'

Capistrano::CLI.invoke(stage, task)
</code>```

Any clue ??

答:
Finally solved, this is what i did,

I used the Capistrano::Application.invoke({task}) method

For capistrano 3.8.2

```<code>require 'capistrano/all'
require 'capistrano/setup'
require 'capistrano/deploy'
require "capistrano/scm/git"
install_plugin Capistrano::SCM::Git

stages = "production"
set :application, 'my_app_name'
set :repo_url, 'git@github.com:capistrano/capistrano.git'
set :deploy_to, '/var/www/'
set :stage, :production
role :app, %w{www}
Dir.glob("lib/capistrano/tasks/*.rake").each { |r| import r }

Capistrano::Application.invoke("common:ntp")
</code>```

Hope it helps.

Body:
Im trying to run a capistrano 3.x task from a ruby script.

I dive into the docs and in older versions of capistrano (2.x) you have Capistrano::CLI interface to access and execute tasks.

In newer versions this module seems to be gone, i can't find anything similar.

I was trying with Capistrano::DSL without no luck.

To make it clear, im looking something like this:

require 'capistrano/all'

Capistrano::CLI.invoke(stage, task)

Any clue ??

Body:
Finally solved, this is what i did,

I used the Capistrano::Application.invoke({task}) method

For capistrano 3.8.2

require 'capistrano/all'
require 'capistrano/setup'
require 'capistrano/deploy'
require "capistrano/scm/git"
install_plugin Capistrano::SCM::Git

stages = "production"
set :application, 'my_app_name'
set :repo_url, 'git@github.com:capistrano/capistrano.git'
set :deploy_to, '/var/www/'
set :stage, :production
role :app, %w{www}
Dir.glob("lib/capistrano/tasks/*.rake").each { |r| import r }

Capistrano::Application.invoke("common:ntp")

Hope it helps.


问:
java.lang.IllegalArgumentException: Expected MultipartHttpServletRequest: is a MultipartResolver configured?
I am tryin to upload a .jpg file but I get this message:

```<code>org.springframework.web.util.NestedServletException: Request processing failed; nested exception is java.lang.IllegalArgumentException: Expected MultipartHttpServletRequest: is a MultipartResolver configured?
    org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:978)
    org.springframework.web.servlet.FrameworkServlet.doPost(FrameworkServlet.java:868)
    javax.servlet.http.HttpServlet.service(HttpServlet.java:644)
    org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:842)
    javax.servlet.http.HttpServlet.service(HttpServlet.java:725)
    org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52)
    org.netbeans.modules.web.monitor.server.MonitorFilter.doFilter(MonitorFilter.java:393)
    org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:330)
    org.springframework.security.web.access.intercept.FilterSecurityInterceptor.invoke(FilterSecurityInterceptor.java:118)
    org.springframework.security.web.access.intercept.FilterSecurityInterceptor.doFilter(FilterSecurityInterceptor.java:84)
    org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:342)
    org.springframework.security.web.access.ExceptionTranslationFilter.doFilter(ExceptionTranslationFilter.java:113)
    org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:342)
    org.springframework.security.web.session.SessionManagementFilter.doFilter(SessionManagementFilter.java:103)
    org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:342)
    org.springframework.security.web.authentication.AnonymousAuthenticationFilter.doFilter(AnonymousAuthenticationFilter.java:113)
    org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:342)
    org.springframework.security.web.servletapi.SecurityContextHolderAwareRequestFilter.doFilter(SecurityContextHolderAwareRequestFilter.java:154)
    org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:342)
    org.springframework.security.web.savedrequest.RequestCacheAwareFilter.doFilter(RequestCacheAwareFilter.java:45)
    org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:342)
    org.springframework.security.web.authentication.AbstractAuthenticationProcessingFilter.doFilter(AbstractAuthenticationProcessingFilter.java:199)
    org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:342)
    org.springframework.security.web.authentication.logout.LogoutFilter.doFilter(LogoutFilter.java:110)
    org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:342)
    org.springframework.security.web.header.HeaderWriterFilter.doFilterInternal(HeaderWriterFilter.java:57)
    org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107)
    org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:342)
    org.springframework.security.web.context.SecurityContextPersistenceFilter.doFilter(SecurityContextPersistenceFilter.java:87)
    org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:342)
    org.springframework.security.web.context.request.async.WebAsyncManagerIntegrationFilter.doFilterInternal(WebAsyncManagerIntegrationFilter.java:50)
    org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107)
    org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:342)
    org.springframework.security.web.FilterChainProxy.doFilterInternal(FilterChainProxy.java:192)
    org.springframework.security.web.FilterChainProxy.doFilter(FilterChainProxy.java:160)
    org.springframework.web.filter.DelegatingFilterProxy.invokeDelegate(DelegatingFilterProxy.java:344)
    org.springframework.web.filter.DelegatingFilterProxy.doFilter(DelegatingFilterProxy.java:261)
</code>```

But I have a multipartresolver:

```<code><bean id="multipartResolver"    class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
        <property name="maxUploadSize" value="1000000" />
    </bean>
</code>```

Now is my question how I can fix this, here is some more code:

UploadController:

```<code>@Controller
@RequestMapping(value = "/upload")
public class UploadController {
private static final Logger LOGGER = LoggerFactory.getLogger(UploadController.class);

private String folderToUpload = "/resources/img";

@RequestMapping(value = "/form", method = RequestMethod.GET)
public ModelAndView formUpload(){
    ModelAndView mv = new ModelAndView("upload/form");

    return mv;
}

@RequestMapping(value = "/form", method = RequestMethod.POST)
public ModelAndView procesFormUpload(HttpSession session, @RequestParam("photofile") MultipartFile file) {
    ModelAndView mv = new ModelAndView("upload/list");

    String uploadLocation = Upload(session).getAbsolutePath();
    LOGGER.debug("Name File: [{}]", file.getOriginalFilename());
    LOGGER.debug("Size File: [{}]", file.getSize());
    LOGGER.debug("Type File: [{}]", file.getContentType());

    File photo = new File(uploadLocation + File.separator + file.getOriginalFilename());
    try {
        file.transferTo(photo);
        LOGGER.debug("File [{}]", photo.getAbsolutePath());
    } catch (Exception ex) {
        LOGGER.error("Kan file niet uploaden");
        LOGGER.error("stacktrace: {}", ex.getMessage());
    }
    return mv;
}
private File Upload(HttpSession session) {
    String locationFullPath = session.getServletContext().getRealPath(folderToUpload);
    LOGGER.debug("location full path: [{}]", locationFullPath);
    File test = new File(locationFullPath);

    if(!test.exists()){
        LOGGER.debug("wtf");
        test.mkdirs();
    }
    return test;
}
}
</code>```

form.jsp:

```<code><%@page contentType="text/html" pageEncoding="UTF-8"%>
<%@taglib prefix="t" tagdir="/WEB-INF/tags" %>
<%@taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<%@taglib prefix="form" uri="http://www.springframework.org/tags/form"  %>
<%--
Document   : form
Created on : 16-nov-2014, 13:44:37
Author     : Nicky
--%>

<!DOCTYPE html>
<t:masterpage>
  <jsp:body>
<meta http-equiv="Content-Type" content="text/html; charset=windows-1252">
    <title>Form upload</title>

    <h1>Form upload</h1>

    <form method="POST" enctype="multipart/form-data">

        <table border="0">
            <tbody>
                <tr>
                    <td>File</td>
                    <td>

                        <input type="file" name="photofile">

                    </td>
                </tr>
                <tr>
                    <td> </td>
                    <td>

                        <input type="submit" value="Upload">

                    </td>
                </tr>
            </tbody>
        </table>

    </form>
</jsp:body>
</code>```

I hope someone can help me!

答:
```<code>    @Configuration
public class FileConfig {

    @Bean(name = "multipartResolver")
    public CommonsMultipartResolver multipartResolver() {
        CommonsMultipartResolver multipartResolver = new CommonsMultipartResolver();
        multipartResolver.setMaxUploadSize(10485760);
        return multipartResolver;
    }
}
</code>```

Body:
I am tryin to upload a .jpg file but I get this message:

org.springframework.web.util.NestedServletException: Request processing failed; nested exception is java.lang.IllegalArgumentException: Expected MultipartHttpServletRequest: is a MultipartResolver configured?
    org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:978)
    org.springframework.web.servlet.FrameworkServlet.doPost(FrameworkServlet.java:868)
    javax.servlet.http.HttpServlet.service(HttpServlet.java:644)
    org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:842)
    javax.servlet.http.HttpServlet.service(HttpServlet.java:725)
    org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52)
    org.netbeans.modules.web.monitor.server.MonitorFilter.doFilter(MonitorFilter.java:393)
    org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:330)
    org.springframework.security.web.access.intercept.FilterSecurityInterceptor.invoke(FilterSecurityInterceptor.java:118)
    org.springframework.security.web.access.intercept.FilterSecurityInterceptor.doFilter(FilterSecurityInterceptor.java:84)
    org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:342)
    org.springframework.security.web.access.ExceptionTranslationFilter.doFilter(ExceptionTranslationFilter.java:113)
    org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:342)
    org.springframework.security.web.session.SessionManagementFilter.doFilter(SessionManagementFilter.java:103)
    org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:342)
    org.springframework.security.web.authentication.AnonymousAuthenticationFilter.doFilter(AnonymousAuthenticationFilter.java:113)
    org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:342)
    org.springframework.security.web.servletapi.SecurityContextHolderAwareRequestFilter.doFilter(SecurityContextHolderAwareRequestFilter.java:154)
    org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:342)
    org.springframework.security.web.savedrequest.RequestCacheAwareFilter.doFilter(RequestCacheAwareFilter.java:45)
    org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:342)
    org.springframework.security.web.authentication.AbstractAuthenticationProcessingFilter.doFilter(AbstractAuthenticationProcessingFilter.java:199)
    org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:342)
    org.springframework.security.web.authentication.logout.LogoutFilter.doFilter(LogoutFilter.java:110)
    org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:342)
    org.springframework.security.web.header.HeaderWriterFilter.doFilterInternal(HeaderWriterFilter.java:57)
    org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107)
    org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:342)
    org.springframework.security.web.context.SecurityContextPersistenceFilter.doFilter(SecurityContextPersistenceFilter.java:87)
    org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:342)
    org.springframework.security.web.context.request.async.WebAsyncManagerIntegrationFilter.doFilterInternal(WebAsyncManagerIntegrationFilter.java:50)
    org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107)
    org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:342)
    org.springframework.security.web.FilterChainProxy.doFilterInternal(FilterChainProxy.java:192)
    org.springframework.security.web.FilterChainProxy.doFilter(FilterChainProxy.java:160)
    org.springframework.web.filter.DelegatingFilterProxy.invokeDelegate(DelegatingFilterProxy.java:344)
    org.springframework.web.filter.DelegatingFilterProxy.doFilter(DelegatingFilterProxy.java:261)

But I have a multipartresolver:

<bean id="multipartResolver"    class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
        <property name="maxUploadSize" value="1000000" />
    </bean>

Now is my question how I can fix this, here is some more code:

UploadController:

@Controller
@RequestMapping(value = "/upload")
public class UploadController {
private static final Logger LOGGER = LoggerFactory.getLogger(UploadController.class);

private String folderToUpload = "/resources/img";

@RequestMapping(value = "/form", method = RequestMethod.GET)
public ModelAndView formUpload(){
    ModelAndView mv = new ModelAndView("upload/form");

    return mv;
}

@RequestMapping(value = "/form", method = RequestMethod.POST)
public ModelAndView procesFormUpload(HttpSession session, @RequestParam("photofile") MultipartFile file) {
    ModelAndView mv = new ModelAndView("upload/list");

    String uploadLocation = Upload(session).getAbsolutePath();
    LOGGER.debug("Name File: [{}]", file.getOriginalFilename());
    LOGGER.debug("Size File: [{}]", file.getSize());
    LOGGER.debug("Type File: [{}]", file.getContentType());

    File photo = new File(uploadLocation + File.separator + file.getOriginalFilename());
    try {
        file.transferTo(photo);
        LOGGER.debug("File [{}]", photo.getAbsolutePath());
    } catch (Exception ex) {
        LOGGER.error("Kan file niet uploaden");
        LOGGER.error("stacktrace: {}", ex.getMessage());
    }
    return mv;
}
private File Upload(HttpSession session) {
    String locationFullPath = session.getServletContext().getRealPath(folderToUpload);
    LOGGER.debug("location full path: [{}]", locationFullPath);
    File test = new File(locationFullPath);

    if(!test.exists()){
        LOGGER.debug("wtf");
        test.mkdirs();
    }
    return test;
}
}

form.jsp:

<%@page contentType="text/html" pageEncoding="UTF-8"%>
<%@taglib prefix="t" tagdir="/WEB-INF/tags" %>
<%@taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<%@taglib prefix="form" uri="http://www.springframework.org/tags/form"  %>
<%--
Document   : form
Created on : 16-nov-2014, 13:44:37
Author     : Nicky
--%>

<!DOCTYPE html>
<t:masterpage>
  <jsp:body>
<meta http-equiv="Content-Type" content="text/html; charset=windows-1252">
    <title>Form upload</title>

Form upload

    <form method="POST" enctype="multipart/form-data">

                    File

                        <input type="file" name="photofile">

                        <input type="submit" value="Upload">

    </form>
</jsp:body>

I hope someone can help me!