问:
GridFSDownloadStream can not read all data
I try to download file from mongodb . the size of uploaded file is 2106 bytes,and chunkSize=2048 bytes, so GridFS divides the file into 2 chunks. when I excute the codes of downloadStream.read(bytesToWriteTo), only read data of the first chunk, and can not read the  data of  second chunk. How can I read all of the data?

```<code>public class OpenDownloadStreamDemo {

          public static void main(String[] args) {
            MongoClient mongoClient = new MongoClient("127.0.0.1", 27017);
            MongoDatabase mongoDatabase = mongoClient.getDatabase("demo");
            GridFSBucket gridFSBucket = GridFSBuckets[enter image description here][1].create(mongoDatabase);
            ObjectId fileId = new ObjectId("56f25a8b163b4598987b666b");
            GridFSDownloadStream downloadStream = gridFSBucket.openDownloadStream(fileId);
            int fileLength = (int) downloadStream.getGridFSFile().getLength();
            byte[] bytesToWriteTo = new byte[fileLength];
            downloadStream.read(bytesToWriteTo);
            downloadStream.close();
            System.out.println(new String(bytesToWriteTo, StandardCharsets.UTF_8));
        }
    }
</code>```

The files Collection

The chunks Collection

答:
You can directly use the inputstream. The open download stream is enough to get all the chunks </p>

```<code>GridFSDownloadStream downloadStream = mongo.getGridFSBucket().openDownloadStream(fileId);
//int fileLength = (int) downloadStream.getGridFSFile().getLength();
//byte[] bytesToWriteTo = new byte[(fileLength];
//downloadStream.read(bytesToWriteTo);
return downloadStream;
</code>```

Body:
I try to download file from mongodb . the size of uploaded file is 2106 bytes,and chunkSize=2048 bytes, so GridFS divides the file into 2 chunks. when I excute the codes of downloadStream.read(bytesToWriteTo), only read data of the first chunk, and can not read the  data of  second chunk. How can I read all of the data?

public class OpenDownloadStreamDemo {

          public static void main(String[] args) {
            MongoClient mongoClient = new MongoClient("127.0.0.1", 27017);
            MongoDatabase mongoDatabase = mongoClient.getDatabase("demo");
            GridFSBucket gridFSBucket = GridFSBuckets[enter image description here][1].create(mongoDatabase);
            ObjectId fileId = new ObjectId("56f25a8b163b4598987b666b");
            GridFSDownloadStream downloadStream = gridFSBucket.openDownloadStream(fileId);
            int fileLength = (int) downloadStream.getGridFSFile().getLength();
            byte[] bytesToWriteTo = new byte[fileLength];
            downloadStream.read(bytesToWriteTo);
            downloadStream.close();
            System.out.println(new String(bytesToWriteTo, StandardCharsets.UTF_8));
        }
    }

The files Collection

The chunks Collection

Body:
You can directly use the inputstream. The open download stream is enough to get all the chunks

GridFSDownloadStream downloadStream = mongo.getGridFSBucket().openDownloadStream(fileId);
//int fileLength = (int) downloadStream.getGridFSFile().getLength();
//byte[] bytesToWriteTo = new byte[(fileLength];
//downloadStream.read(bytesToWriteTo);
return downloadStream;


来源: stackexchange

问:
Batch script to convert, youtube-dl webm file to mp3 with ffmpeg
I'm using youtube-dl to extract the best possible audio quality from youtube videos. However the best quality audio usually turns out to be the webm format, which isn't useful. I would like to write a batch script that converts the webm file to an mp3 with ffmpeg. I've already tried using this guide on reddit to do it, but it doesn't seem to work. It appears to create an empty mp3 file that displays an error when i try to play it and the meta data is also completly blank.

Here is the batch script:

```<code>for %%a in ("Downloaded\*.*") do %CD%\ffmpeg\bin\ffmpeg.exe -i "%%a" -vn -ar 44100 -ac 2 -ab 192k -f mp3 "Converted\%%~na.mp3" pause
</code>```

I'll also give an explanation of how the whole thing should work.

The idea is, is that you use youtube-dl to extract the best possible audio, then put that file into the Downloaded folder (see pic below) and then you run the mp3 script (which uses commands from ffmpeg) to convert the webm file in the Downloaded folder to a mp3 file, and place it in the Converted folder. The mp3 script is the code above. But it doesn't seem to work properly.

I'm not very familiar with batch scripting, nor with ffmpeg so any help would be appreicated.

Here is the picture to complement the explanation part.

答:
youtube-dl already contains this functionality - just specify that you want mp3:

```<code>youtube-dl -x --audio-format mp3 https://www.youtube.com/watch?v=BaW_jenozKc
</code>```

Replace https://www.youtube.com/watch?v=BaW_jenozKc with your actual URL.

ContentLicense: CC BY-SA 3.0

Body:
I'm using youtube-dl to extract the best possible audio quality from youtube videos. However the best quality audio usually turns out to be the webm format, which isn't useful. I would like to write a batch script that converts the webm file to an mp3 with ffmpeg. I've already tried using this guide on reddit to do it, but it doesn't seem to work. It appears to create an empty mp3 file that displays an error when i try to play it and the meta data is also completly blank.

Here is the batch script:

for %%a in ("Downloaded\*.*") do %CD%\ffmpeg\bin\ffmpeg.exe -i "%%a" -vn -ar 44100 -ac 2 -ab 192k -f mp3 "Converted\%%~na.mp3" pause

I'll also give an explanation of how the whole thing should work.

The idea is, is that you use youtube-dl to extract the best possible audio, then put that file into the Downloaded folder (see pic below) and then you run the mp3 script (which uses commands from ffmpeg) to convert the webm file in the Downloaded folder to a mp3 file, and place it in the Converted folder. The mp3 script is the code above. But it doesn't seem to work properly.

I'm not very familiar with batch scripting, nor with ffmpeg so any help would be appreicated.

Here is the picture to complement the explanation part.

Body:
youtube-dl already contains this functionality - just specify that you want mp3:

youtube-dl -x --audio-format mp3 https://www.youtube.com/watch?v=BaW_jenozKc

Replace https://www.youtube.com/watch?v=BaW_jenozKc with your actual URL.

OwnerDisplayName: anon


问:
Previous data is lost because of new data
I am creating some html tag and assigning data as below.

```<code>MyCombo = function(args) {
    var dataUrl = args.url;
    var divID = args.divID;
    var div = document.getElementById(divID);

    var myTable = '<input type="text" id="myInput"  list="myUL" onclick = "MyList()" onkeyup="MyList()" style="width:100% " >' +
        '<ul id="myUL" hidden=false>' + '<li>' + '<a href="#" ></a>' + '</li>' + '</ul>';
    div.innerHTML = myTable;

    function getData(callback) {
        var httpRequest = new XMLHttpRequest();
        httpRequest.open('GET', dataUrl, true);
        httpRequest.onreadystatechange = function() {
            if (httpRequest.readyState === XMLHttpRequest.DONE && httpRequest.status === 200) {
                callback(httpRequest.responseText);
            }
        };
        httpRequest.send();
    }

    getData(function(data) {
        var jsonc = JSON.parse(data);
        var new_opt = "";
        for (i = 0; i < jsonc.length; i++) {
            new_opt += '<li><a href="#">' + jsonc[i]['VALUE'] + '</a></li>';
        }
        document.getElementById('myUL').innerHTML = new_opt;
    });
}
</code>```

Now when I pass my second div, previous data is getting lost. And for first div I am getting second data.

This how I am calling the class :

For the first instance

```<code>var myCombo = new liveSearch({
    "url": "data1.json",
    "divID": "ID1",
});
</code>```

For the second instance

```<code>var myCombo2 = new liveSearch({
    "url": "data2.json",
    "divID": "ID2",
});
</code>```

Any idea how to overcome this?

答:
In getData you call

```<code>        document.getElementById('myUL').innerHTML = new_opt;
</code>```

which writes to the element called myUL everytime it is called.

Body:
I am creating some html tag and assigning data as below.

MyCombo = function(args) {
    var dataUrl = args.url;
    var divID = args.divID;
    var div = document.getElementById(divID);

    var myTable = '<input type="text" id="myInput"  list="myUL" onclick = "MyList()" onkeyup="MyList()" style="width:100% " >' +
        '
' + '
' + '' + '
' + '
';
    div.innerHTML = myTable;

    function getData(callback) {
        var httpRequest = new XMLHttpRequest();
        httpRequest.open('GET', dataUrl, true);
        httpRequest.onreadystatechange = function() {
            if (httpRequest.readyState === XMLHttpRequest.DONE && httpRequest.status === 200) {
                callback(httpRequest.responseText);
            }
        };
        httpRequest.send();
    }

    getData(function(data) {
        var jsonc = JSON.parse(data);
        var new_opt = "";
        for (i = 0; i < jsonc.length; i++) {
            new_opt += '
' + jsonc[i]['VALUE'] + '
';
        }
        document.getElementById('myUL').innerHTML = new_opt;
    });
}

Now when I pass my second div, previous data is getting lost. And for first div I am getting second data.

This how I am calling the class :

For the first instance

var myCombo = new liveSearch({
    "url": "data1.json",
    "divID": "ID1",
});

For the second instance

var myCombo2 = new liveSearch({
    "url": "data2.json",
    "divID": "ID2",
});

Any idea how to overcome this?

Body:
In getData you call

        document.getElementById('myUL').innerHTML = new_opt;

which writes to the element called myUL everytime it is called.


问:
Calling compose on React components with imported functions
I am trying to call several functions on a React component I have created, specifically the graphql() function from react-apollo

I use the pattern:

```<code>import someFunction from "../somewhere";

const withData = compose(
  graphql(gqlDocument, { name: "Name" }),
  graphql(anotherDocument, { name: "Name2" }),
  someFunction()
  ...
)
const ComponentWithData = withData(Component);
export default ComponentWithData
</code>```

This works fine, unless I try to use a function that I have defined in another file and imported. despite literally being of the exact same form, i.e. graphql(document, { name: "Name" }) I get the error: Uncaught TypeError: Cannot read property 'apply' of undefined. If I simply copy and paste the function from the external module and put it inside the compose block, it works perfectly, so the issue has to be with how react is dealing apply inside this function composition.

When the function works, it ComponetWithData should have a prop called "Name" that represents the graphql document passed to the graphql() function. This is particularly perplexing because react-apollo's implementation of subscriptions has you passing a React component to a function that alters its props, and yet I can define subscription functions externally with no hassle. here is the pattern for reference:

```<code>const COMMENTS_SUBSCRIPTION = gql`
    subscription onCommentAdded($repoFullName: String!){
      commentAdded(repoFullName: $repoFullName){
        id
        content
      }
    }
`;
const withData = graphql(COMMENT_QUERY, {
    name: 'comments',
    options: ({ params }) => ({
        variables: {
            repoName: `${params.org}/${params.repoName}`
        },
    }),
    props: props => {
        return {
            subscribeToNewComments: params => {
                return props.comments.subscribeToMore({
                    document: COMMENTS_SUBSCRIPTION,
                    variables: {
                        repoName: params.repoFullName,
                    },
                    updateQuery: (prev, {subscriptionData}) => {
                        if (!subscriptionData.data) {
                            return prev;
                        }
                        const newFeedItem = subscriptionData.data.commentAdded;
                        return Object.assign({}, prev, {
                            entry: {
                                comments: [newFeedItem, ...prev.entry.comments]
                            }
                        });
                    }
                });
            }
        };
    },
});
</code>```

答:
While I didn't ever get it to work inside the compose block, I did find an acceptable solution:

```<code>const myFunc = compose(
  // graphql stuff here
);
const updated = myImportedFunc(Component);
const CompWGraphql = myFunc(updated);
</code>```

There was just an issue with how graphql passes the object from one function to the other in the compose chain, and simply calling it outside the compose block and assigning the result to a new variable gave me the result I wanted.

Body:
I am trying to call several functions on a React component I have created, specifically the graphql() function from react-apollo

I use the pattern:

import someFunction from "../somewhere";

const withData = compose(
  graphql(gqlDocument, { name: "Name" }),
  graphql(anotherDocument, { name: "Name2" }),
  someFunction()
  ...
)
const ComponentWithData = withData(Component);
export default ComponentWithData

This works fine, unless I try to use a function that I have defined in another file and imported. despite literally being of the exact same form, i.e. graphql(document, { name: "Name" }) I get the error: Uncaught TypeError: Cannot read property 'apply' of undefined. If I simply copy and paste the function from the external module and put it inside the compose block, it works perfectly, so the issue has to be with how react is dealing apply inside this function composition.

When the function works, it ComponetWithData should have a prop called "Name" that represents the graphql document passed to the graphql() function. This is particularly perplexing because react-apollo's implementation of subscriptions has you passing a React component to a function that alters its props, and yet I can define subscription functions externally with no hassle. here is the pattern for reference:

const COMMENTS_SUBSCRIPTION = gql`
    subscription onCommentAdded($repoFullName: String!){
      commentAdded(repoFullName: $repoFullName){
        id
        content
      }
    }
`;
const withData = graphql(COMMENT_QUERY, {
    name: 'comments',
    options: ({ params }) => ({
        variables: {
            repoName: `${params.org}/${params.repoName}`
        },
    }),
    props: props => {
        return {
            subscribeToNewComments: params => {
                return props.comments.subscribeToMore({
                    document: COMMENTS_SUBSCRIPTION,
                    variables: {
                        repoName: params.repoFullName,
                    },
                    updateQuery: (prev, {subscriptionData}) => {
                        if (!subscriptionData.data) {
                            return prev;
                        }
                        const newFeedItem = subscriptionData.data.commentAdded;
                        return Object.assign({}, prev, {
                            entry: {
                                comments: [newFeedItem, ...prev.entry.comments]
                            }
                        });
                    }
                });
            }
        };
    },
});

Body:
While I didn't ever get it to work inside the compose block, I did find an acceptable solution:

const myFunc = compose(
  // graphql stuff here
);
const updated = myImportedFunc(Component);
const CompWGraphql = myFunc(updated);

There was just an issue with how graphql passes the object from one function to the other in the compose chain, and simply calling it outside the compose block and assigning the result to a new variable gave me the result I wanted.


问:
How do I run two while True statements in python?
I am trying to make a door swipe card system in Python for my Raspberry Pi. I broke the program into two: A Door Alarm and a Card Swipe Recording system. The two programs work individually but how do I combine the two programs into one python file? I've tried threading but it doesn't seem to work.

Below are the programs:
1.) Door Alarm: If door is left open for a certain duration, an led will blink, then an alarm will ring

```<code>import time
import RPi.GPIO as gpio

led = 37
buzzer = 11
door = 16

gpio.setmode(gpio.BOARD)
gpio.setwarnings(False)
gpio.setup(buzzer, gpio.OUT)
gpio.setup(led, gpio.OUT)
gpio.setup(door, gpio.IN, pull_up_down=gpio.PUD_UP)

def blink(buzzer):
    gpio.output(buzzer, True)
    time.sleep(0.1)
    gpio.output(buzzer, False)
    time.sleep(0.1)
    return

def blink(led):
    gpio.output(led, True)
    time.sleep(1)
    gpio.output(led, False)
    time.sleep(1)
    return

while True:
    if gpio.input(door):
        time.sleep(3)
        for i in range(0,5):
                blink(led)
        for i in range (0,5):
                blink(buzzer)
    else:
        gpio.output(buzzer, False)

gpio.cleanup()
</code>```

2.) Card Swipe Recording System: When someone swipes their card, the led blinks and a picture is taken

```<code>import datetime
import time
import os
import RPi.GPIO as gpio

led = 37
t = datetime.datetime.now()

gpio.setmode(gpio.BOARD)
gpio.setwarnings(False)
gpio.setup(led, gpio.OUT)

def blink(led):
    gpio.output(led, True)
    time.sleep(0.1)
    gpio.output(led, False)
    time.sleep(0.1)

while True:
    card = raw_input()
    f = open("Laptop Sign Out" + '.txt', 'a')
    f.write("OneCard Number: " + card[1:10] + " Time: " + t.strftime("%m-%d-%Y %H:%M:%S"))
    f.write('\n')
    f.write(';')
    f.write('\n')
    f.close()
    time.sleep(1)
    for i in range(0,3):
        blink(led)
    os.system('fswebcam ~/Desktop/Photos/%H%M%S.jpeg')
    time.sleep(3)

gpio.cleanup()
</code>```

(UPDATE) Also, below is my attempt at threading:

```<code>import time
import RPi.GPIO as gpio
import os
import datetime
from threading import Thread

led = 37
buzzer = 11
door = 16
t = datetime.datetime.now()

gpio.setmode(gpio.BOARD)
gpio.setwarnings(False)
gpio.setup(buzzer, gpio.OUT)
gpio.setup(led, gpio.OUT)
gpio.setup(door, gpio.IN, pull_up_down=gpio.PUD_UP)

def blink(buzzer):
    gpio.output(buzzer, True)
    time.sleep(0.1)
    gpio.output(buzzer, False)
    time.sleep(0.1)
    return

def blink(led):
    gpio.output(led, True)
    time.sleep(1)
    gpio.output(led, False)
    time.sleep(1)
    return

def doorsensor():
    while True:
        if gpio.input(door):
            time.sleep(3)
            for i in range(0,5):
                    blink(led)
            for i in range (0,5):
                    blink(buzzer)
        else:
            gpio.output(buzzer, False)

def cardreader():
    while True:
        card = raw_input()
        f = open("Laptop Sign Out" + '.txt', 'a')
        f.write("OneCard Number: " + card[1:10] + " Time: " + t.strftime("%m-%d-%Y %H:%M:%S"))
        f.write('\n')
        f.write(';')
        f.write('\n')
        f.close()
        time.sleep(1)
        for i in range(0,3):
            blink(led)
        os.system('fswebcam ~/Desktop/Photos/%H%M%S.jpeg')
        time.sleep(3)

f1 = Thread(target = doorsensor())
f2 = Thread(target = cardreader())

f2.start()
f1.start()

gpio.cleanup()
</code>```

答:
Regardless of any other mistake, you need to join one of your threads once they have been started.

```<code>f1 = Thread(target = doorsensor())
f2 = Thread(target = cardreader())

f2.start()
f1.start()

f1.join()
</code>```

What does f1.join() do?

Basically, it tells Python to wait until f1 has finished running.
If you don't do so, the program will start f1 and f2, then will exit.
Upon exiting, Python will release all the resources, including those two threads, whose execution will stop.

Body:
I am trying to make a door swipe card system in Python for my Raspberry Pi. I broke the program into two: A Door Alarm and a Card Swipe Recording system. The two programs work individually but how do I combine the two programs into one python file? I've tried threading but it doesn't seem to work.

Below are the programs:
1.) Door Alarm: If door is left open for a certain duration, an led will blink, then an alarm will ring

import time
import RPi.GPIO as gpio

led = 37
buzzer = 11
door = 16

gpio.setmode(gpio.BOARD)
gpio.setwarnings(False)
gpio.setup(buzzer, gpio.OUT)
gpio.setup(led, gpio.OUT)
gpio.setup(door, gpio.IN, pull_up_down=gpio.PUD_UP)

def blink(buzzer):
    gpio.output(buzzer, True)
    time.sleep(0.1)
    gpio.output(buzzer, False)
    time.sleep(0.1)
    return

def blink(led):
    gpio.output(led, True)
    time.sleep(1)
    gpio.output(led, False)
    time.sleep(1)
    return

while True:
    if gpio.input(door):
        time.sleep(3)
        for i in range(0,5):
                blink(led)
        for i in range (0,5):
                blink(buzzer)
    else:
        gpio.output(buzzer, False)

gpio.cleanup()

2.) Card Swipe Recording System: When someone swipes their card, the led blinks and a picture is taken

import datetime
import time
import os
import RPi.GPIO as gpio

led = 37
t = datetime.datetime.now()

gpio.setmode(gpio.BOARD)
gpio.setwarnings(False)
gpio.setup(led, gpio.OUT)

def blink(led):
    gpio.output(led, True)
    time.sleep(0.1)
    gpio.output(led, False)
    time.sleep(0.1)

while True:
    card = raw_input()
    f = open("Laptop Sign Out" + '.txt', 'a')
    f.write("OneCard Number: " + card[1:10] + " Time: " + t.strftime("%m-%d-%Y %H:%M:%S"))
    f.write('\n')
    f.write(';')
    f.write('\n')
    f.close()
    time.sleep(1)
    for i in range(0,3):
        blink(led)
    os.system('fswebcam ~/Desktop/Photos/%H%M%S.jpeg')
    time.sleep(3)

gpio.cleanup()

(UPDATE) Also, below is my attempt at threading:

import time
import RPi.GPIO as gpio
import os
import datetime
from threading import Thread

led = 37
buzzer = 11
door = 16
t = datetime.datetime.now()

gpio.setmode(gpio.BOARD)
gpio.setwarnings(False)
gpio.setup(buzzer, gpio.OUT)
gpio.setup(led, gpio.OUT)
gpio.setup(door, gpio.IN, pull_up_down=gpio.PUD_UP)

def blink(buzzer):
    gpio.output(buzzer, True)
    time.sleep(0.1)
    gpio.output(buzzer, False)
    time.sleep(0.1)
    return

def blink(led):
    gpio.output(led, True)
    time.sleep(1)
    gpio.output(led, False)
    time.sleep(1)
    return

def doorsensor():
    while True:
        if gpio.input(door):
            time.sleep(3)
            for i in range(0,5):
                    blink(led)
            for i in range (0,5):
                    blink(buzzer)
        else:
            gpio.output(buzzer, False)

def cardreader():
    while True:
        card = raw_input()
        f = open("Laptop Sign Out" + '.txt', 'a')
        f.write("OneCard Number: " + card[1:10] + " Time: " + t.strftime("%m-%d-%Y %H:%M:%S"))
        f.write('\n')
        f.write(';')
        f.write('\n')
        f.close()
        time.sleep(1)
        for i in range(0,3):
            blink(led)
        os.system('fswebcam ~/Desktop/Photos/%H%M%S.jpeg')
        time.sleep(3)

f1 = Thread(target = doorsensor())
f2 = Thread(target = cardreader())

f2.start()
f1.start()

gpio.cleanup()

Body:
Regardless of any other mistake, you need to join one of your threads once they have been started.

f1 = Thread(target = doorsensor())
f2 = Thread(target = cardreader())

f2.start()
f1.start()

f1.join()

What does f1.join() do?

Basically, it tells Python to wait until f1 has finished running.
If you don't do so, the program will start f1 and f2, then will exit.
Upon exiting, Python will release all the resources, including those two threads, whose execution will stop.


问:
Check if two dictionaries are disjoint
Is there an easier/faster way to find out if two dictionaries are disjoint than calculating their intersection?

For the intersection I found this answer, so the disjoint-test would look like this:

```<code>def dicts_disjoint(a, b):
    keys_a = set(a.keys())
    keys_b = set(b.keys())
    intersection = keys_a & keys_b
    return not len(intersection)
</code>```

However I think this is inefficient since it always calculates the whole intersection (no short-circuit quit).

Any better ideas?

答:
Are you looking for something like:

```<code>def dicts_disjoint(a, b):
    return not any(k in b for k in a)
</code>```

Or:

```<code>def dicts_disjoint(a, b):
    return all(k not in b for k in a)
</code>```

Both will short-circuit.

Title: Check if two dictionaries are disjoint

Body:
Is there an easier/faster way to find out if two dictionaries are disjoint than calculating their intersection?

For the intersection I found this answer, so the disjoint-test would look like this:

def dicts_disjoint(a, b):
    keys_a = set(a.keys())
    keys_b = set(b.keys())
    intersection = keys_a & keys_b
    return not len(intersection)

However I think this is inefficient since it always calculates the whole intersection (no short-circuit quit).

Any better ideas?

Body:
Are you looking for something like:

def dicts_disjoint(a, b):
    return not any(k in b for k in a)

Or:

def dicts_disjoint(a, b):
    return all(k not in b for k in a)

Both will short-circuit.


问:
using .not() with an exception is not working - JQuery
I am using toggle to show/hide two elements.
I am displaying a block with button link on toggle show.
I need to put an exception for toggle when the user clicks on button link.

My function with .not is not working.
I have tried with the code written below. Can you point me to where I went wrong.

```<code>  // On cache le block d'ajout au panier et l'image dans le block texte
  jQuery('.panier_block').hide();
  jQuery('.img_toggle').hide();

 // les cachés s'affichent et les affichés se cachent avec toggle.
  jQuery('.item').not('.btn-cart').click( function() {
      jQuery(this).find('.panier_block').toggle(275);
      jQuery(this).find('.product-image').toggle(275);
      jQuery(this).find('.product-image-subtext').toggle(275);
      jQuery(this).find('.product_info_sub_block_text').toggle(275);

  })
</code>```

My HTML:

```<code><li class="item<?php if(($i-1)%$_columnCount==0): ?> first<?php elseif($i%$_columnCount==0): ?> last<?php endif; ?>">
      <!-- <a href="#" title="<?php echo $this->stripTags($this->getImageLabel($_product, 'small_image'), null, true) ?>" class="product-image" id="product-switch-<?php echo $z; ?>"> -->
        <div class="product-image" id="product-switch-<?php echo $z; ?>">
            <?php $_imgSize = 398; ?>
            <img id="product-collection-image-<?php echo $_product->getId(); ?>"
                 src="<?php echo $this->helper('catalog/image')->init($_product, 'small_image')->resize($_imgSize); ?>"
                 alt="<?php echo $this->stripTags($this->getImageLabel($_product, 'small_image'), null, true) ?>" />
        </div>
      <!-- </a> -->

 <!-- Panier-->
  <div class="product_info_block panier_block">
    <div class="product_info_sub_block">

        <div class="product-info">
            <h2 class="product-name"><a href="<?php echo $_product->getProductUrl() ?>" title="<?php echo $this->stripTags($_product->getName(), null, true) ?>"><?php echo $_helper->productAttribute($_product, $_product->getName(), 'name') ?></a></h2>
            <?php
            // Provides extra blocks on which to hang some features for products in the list
            // Features providing UI elements targeting this block will display directly below the product name
            if ($this->getChild('name.after')) {
                $_nameAfterChildren = $this->getChild('name.after')->getSortedChildren();
                foreach ($_nameAfterChildren as $_nameAfterChildName) {
                    $_nameAfterChild = $this->getChild('name.after')->getChild($_nameAfterChildName);
                    $_nameAfterChild->setProduct($_product);
                    echo $_nameAfterChild->toHtml();
                }
            }
            ?>
            <!-- Affiche le poids-->
            <div class="block_weight_cat">

          <span class="weight_cat">
            <?php $_product = Mage::getModel('catalog/product')->load($_product->getId());
              $_weight = $this->htmlEscape($_product->getWeight());
                if ($_weight < 1)
                  $_weightstr = number_format($_weight*1000) . " mll";
                else
                  $_weightstr = number_format($_weight) . " cl";
              echo $_weightstr;
              ?>
          </span>
        </div>

            <?php echo $this->getPriceHtml($_product, true) ?>
            <?php if($_product->getRatingSummary()): ?>
            <?php echo $this->getReviewsSummaryHtml($_product, 'short') ?>
            <?php endif; ?>

            <div class="actions">
                <?php if(!$_product->canConfigure() && $_product->isSaleable()): ?>
                    <button type="button" title="<?php echo $this->quoteEscape($this->__('Add to Cart')) ?>" class="button btn-cart" onclick="setLocation('<?php echo $this->getAddToCartUrl($_product) ?>')"><span><span><?php echo $this->__('Add to Cart') ?></span></span></button>

                <?php elseif($_product->getStockItem() && $_product->getStockItem()->getIsInStock()): ?>
                    <a title="<?php echo $this->quoteEscape($this->__('View Details')) ?>" class="button" href="<?php echo $_product->getProductUrl() ?>"><?php echo $this->__('View Details') ?></a>
                <?php else: ?>
                    <p class="availability out-of-stock"><span><?php echo $this->__('Out of stock') ?></span></p>
                <?php endif; ?>
                <ul class="add-to-links">
                    <?php if ($this->helper('wishlist')->isAllow()) : ?>
                        <li><a href="<?php echo $this->helper('wishlist')->getAddUrl($_product) ?>" class="link-wishlist"><?php echo $this->__('Add to Wishlist') ?></a></li>
                    <?php endif; ?>
                    <?php if($_compareUrl=$this->getAddToCompareUrl($_product)): ?>
                        <li><span class="separator">|</span> <a href="<?php echo $_compareUrl ?>" class="link-compare"><?php echo $this->__('Add to Compare') ?></a></li>
                    <?php endif; ?>
                </ul>
            </div>
            <a class="discover"href="<?php echo $_product->getProductUrl() ?>" title="">En savoir plus</a> <span class="iconm-arrow_2">  </span>

        </div>
      </div>    <li class="item<?php if(($i-1)%$_columnCount==0): ?> first<?php elseif($i%$_columnCount==0): ?> last<?php endif; ?>">
  <!-- <a href="#" title="<?php echo $this->stripTags($this->getImageLabel($_product, 'small_image'), null, true) ?>" class="product-image" id="product-switch-<?php echo $z; ?>"> -->
  <div class="product-image" id="product-switch-<?php echo $z; ?>">
    <?php $_imgSize = 398; ?>
    <img id="product-collection-image-<?php echo $_product->getId(); ?>"
         src="<?php echo $this->helper('catalog/image')->init($_product, 'small_image')->resize($_imgSize); ?>"
         alt="<?php echo $this->stripTags($this->getImageLabel($_product, 'small_image'), null, true) ?>" />
  </div>
  <!-- </a> -->

  <!-- Panier-->
  <div class="product_info_block panier_block">
    <div class="product_info_sub_block">

      <div class="product-info">
        <h2 class="product-name"><a href="<?php echo $_product->getProductUrl() ?>" title="<?php echo $this->stripTags($_product->getName(), null, true) ?>"><?php echo $_helper->productAttribute($_product, $_product->getName(), 'name') ?></a></h2>
        <?php
// Provides extra blocks on which to hang some features for products in the list
// Features providing UI elements targeting this block will display directly below the product name
if ($this->getChild('name.after')) {
$_nameAfterChildren = $this->getChild('name.after')->getSortedChildren();
foreach ($_nameAfterChildren as $_nameAfterChildName) {
$_nameAfterChild = $this->getChild('name.after')->getChild($_nameAfterChildName);
$_nameAfterChild->setProduct($_product);
echo $_nameAfterChild->toHtml();
}
}
?>
        <!-- Affiche le poids-->
        <div class="block_weight_cat">

          <span class="weight_cat">
            <?php $_product = Mage::getModel('catalog/product')->load($_product->getId());
$_weight = $this->htmlEscape($_product->getWeight());
if ($_weight < 1)
$_weightstr = number_format($_weight*1000) . " mll";
else
$_weightstr = number_format($_weight) . " cl";
echo $_weightstr;
?>
          </span>
        </div>

        <?php echo $this->getPriceHtml($_product, true) ?>
        <?php if($_product->getRatingSummary()): ?>
        <?php echo $this->getReviewsSummaryHtml($_product, 'short') ?>
        <?php endif; ?>

        <div class="actions">
          <?php if(!$_product->canConfigure() && $_product->isSaleable()): ?>
          <button type="button" title="<?php echo $this->quoteEscape($this->__('Add to Cart')) ?>" class="button btn-cart" onclick="setLocation('<?php echo $this->getAddToCartUrl($_product) ?>')"><span><span><?php echo $this->__('Add to Cart') ?></span></span></button>

          <?php elseif($_product->getStockItem() && $_product->getStockItem()->getIsInStock()): ?>
          <a title="<?php echo $this->quoteEscape($this->__('View Details')) ?>" class="button" href="<?php echo $_product->getProductUrl() ?>"><?php echo $this->__('View Details') ?></a>
          <?php else: ?>
          <p class="availability out-of-stock"><span><?php echo $this->__('Out of stock') ?></span></p>
          <?php endif; ?>
          <ul class="add-to-links">
            <?php if ($this->helper('wishlist')->isAllow()) : ?>
            <li><a href="<?php echo $this->helper('wishlist')->getAddUrl($_product) ?>" class="link-wishlist"><?php echo $this->__('Add to Wishlist') ?></a></li>
            <?php endif; ?>
            <?php if($_compareUrl=$this->getAddToCompareUrl($_product)): ?>
            <li><span class="separator">|</span> <a href="<?php echo $_compareUrl ?>" class="link-compare"><?php echo $this->__('Add to Compare') ?></a></li>
            <?php endif; ?>
          </ul>
        </div>
        <a class="discover"href="<?php echo $_product->getProductUrl() ?>" title="">En savoir plus</a> <span class="iconm-arrow_2">  </span>

      </div>
    </div>
  </div>

  <!-- block de texte-->
  <div class="product_info_block bg_cat">

    <div class="product-image-subtext img_toggle" id="product-switch-<?php echo $z; ?>" >
      <?php $_imgSize = 398; ?>
      <img id="product-collection-image-<?php echo $_product->getId(); ?>"
           src="<?php echo $this->helper('catalog/image')->init($_product, 'small_image')->resize($_imgSize); ?>"
           alt="<?php echo $this->stripTags($this->getImageLabel($_product, 'small_image'), null, true) ?>" />
    </div>

    <div class="product_info_sub_block product_info_sub_block_text">

      <div class="product-info">
        <h2 class="product-name product-name-cat"><a href="<?php echo $_product->getProductUrl() ?>" title="<?php echo $this->stripTags($_product->getName(), null, true) ?>"><?php echo $_helper->productAttribute($_product, $_product->getName(), 'name') ?></a></h2>
        <?php
// Provides extra blocks on which to hang some features for products in the list
// Features providing UI elements targeting this block will display directly below the product name
if ($this->getChild('name.after')) {
$_nameAfterChildren = $this->getChild('name.after')->getSortedChildren();
foreach ($_nameAfterChildren as $_nameAfterChildName) {
$_nameAfterChild = $this->getChild('name.after')->getChild($_nameAfterChildName);
$_nameAfterChild->setProduct($_product);
echo $_nameAfterChild->toHtml();
}
}
?>
        <?php if($_product->getRatingSummary()): ?>
        <?php echo $this->getReviewsSummaryHtml($_product, 'short') ?>
        <?php endif; ?>
        <div class="text_describe_cat">
          <p>Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua
            . Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit
            in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.</p>
        </div>

      </div>
    </div>
  </div>

</li>
      </div>

      <!-- block de texte-->
      <div class="product_info_block bg_cat">

        <div class="product-image-subtext img_toggle" id="product-switch-<?php echo $z; ?>" >
            <?php $_imgSize = 398; ?>
            <img id="product-collection-image-<?php echo $_product->getId(); ?>"
                 src="<?php echo $this->helper('catalog/image')->init($_product, 'small_image')->resize($_imgSize); ?>"
                 alt="<?php echo $this->stripTags($this->getImageLabel($_product, 'small_image'), null, true) ?>" />
        </div>

        <div class="product_info_sub_block product_info_sub_block_text">

            <div class="product-info">
                <h2 class="product-name product-name-cat"><a href="<?php echo $_product->getProductUrl() ?>" title="<?php echo $this->stripTags($_product->getName(), null, true) ?>"><?php echo $_helper->productAttribute($_product, $_product->getName(), 'name') ?></a></h2>
                <?php
                // Provides extra blocks on which to hang some features for products in the list
                // Features providing UI elements targeting this block will display directly below the product name
                if ($this->getChild('name.after')) {
                    $_nameAfterChildren = $this->getChild('name.after')->getSortedChildren();
                    foreach ($_nameAfterChildren as $_nameAfterChildName) {
                        $_nameAfterChild = $this->getChild('name.after')->getChild($_nameAfterChildName);
                        $_nameAfterChild->setProduct($_product);
                        echo $_nameAfterChild->toHtml();
                    }
                }
                ?>
                <?php if($_product->getRatingSummary()): ?>
                <?php echo $this->getReviewsSummaryHtml($_product, 'short') ?>
                <?php endif; ?>
                <div class="text_describe_cat">
      <p>Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua
        . Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit
        in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.</p>
                </div>

            </div>
          </div>
          </div>

    </li>
</code>```

答:
The .not() method is used to "filter out" some elements from a collection.

The collection gathered by jQuery('.item') does not have any elements also having the class btn-cart...

That is why it looks like not working.

ContentLicense: CC BY-SA 4.0

Body:
I am using toggle to show/hide two elements.
I am displaying a block with button link on toggle show.
I need to put an exception for toggle when the user clicks on button link.

My function with .not is not working.
I have tried with the code written below. Can you point me to where I went wrong.

  // On cache le block d'ajout au panier et l'image dans le block texte
  jQuery('.panier_block').hide();
  jQuery('.img_toggle').hide();

 // les cachés s'affichent et les affichés se cachent avec toggle.
  jQuery('.item').not('.btn-cart').click( function() {
      jQuery(this).find('.panier_block').toggle(275);
      jQuery(this).find('.product-image').toggle(275);
      jQuery(this).find('.product-image-subtext').toggle(275);
      jQuery(this).find('.product_info_sub_block_text').toggle(275);

  })

My HTML:

<li class="item<?php if(($i-1)%$_columnCount==0): ?> first<?php elseif($i%$_columnCount==0): ?> last<?php endif; ?>">

        <div class="product-image" id="product-switch-<?php echo $z; ?>">
            <?php $_imgSize = 398; ?>
            <img id="product-collection-image-<?php echo $_product->getId(); ?>"
                 src="<?php echo $this->helper('catalog/image')->init($_product, 'small_image')->resize($_imgSize); ?>"
                 alt="<?php echo $this->stripTags($this->getImageLabel($_product, 'small_image'), null, true) ?>" />

<a href="<?php echo $_product->getProductUrl() ?>" title="<?php echo $this->stripTags($_product->getName(), null, true) ?>"><?php echo $_helper->productAttribute($_product, $_product->getName(), 'name') ?>

            <?php
            // Provides extra blocks on which to hang some features for products in the list
            // Features providing UI elements targeting this block will display directly below the product name
            if ($this->getChild('name.after')) {
                $_nameAfterChildren = $this->getChild('name.after')->getSortedChildren();
                foreach ($_nameAfterChildren as $_nameAfterChildName) {
                    $_nameAfterChild = $this->getChild('name.after')->getChild($_nameAfterChildName);
                    $_nameAfterChild->setProduct($_product);
                    echo $_nameAfterChild->toHtml();
                }
            }
            ?>

            <?php $_product = Mage::getModel('catalog/product')->load($_product->getId());
              $_weight = $this->htmlEscape($_product->getWeight());
                if ($_weight < 1)
                  $_weightstr = number_format($_weight*1000) . " mll";
                else
                  $_weightstr = number_format($_weight) . " cl";
              echo $_weightstr;
              ?>

            <?php echo $this->getPriceHtml($_product, true) ?>
            <?php if($_product->getRatingSummary()): ?>
            <?php echo $this->getReviewsSummaryHtml($_product, 'short') ?>
            <?php endif; ?>

                <?php if(!$_product->canConfigure() && $_product->isSaleable()): ?>
                    <button type="button" title="<?php echo $this->quoteEscape($this->__('Add to Cart')) ?>" class="button btn-cart" onclick="setLocation('<?php echo $this->getAddToCartUrl($_product) ?>')"><?php echo $this->__('Add to Cart') ?></button>

                <?php elseif($_product->getStockItem() && $_product->getStockItem()->getIsInStock()): ?>
                    <a title="<?php echo $this->quoteEscape($this->__('View Details')) ?>" class="button" href="<?php echo $_product->getProductUrl() ?>"><?php echo $this->__('View Details') ?>
                <?php else: ?>

<?php echo $this->__('Out of stock') ?>

                <?php endif; ?>

                    <?php if ($this->helper('wishlist')->isAllow()) : ?>

<a href="<?php echo $this->helper('wishlist')->getAddUrl($_product) ?>" class="link-wishlist"><?php echo $this->__('Add to Wishlist') ?>

                    <?php endif; ?>
                    <?php if($_compareUrl=$this->getAddToCompareUrl($_product)): ?>

| <a href="<?php echo $_compareUrl ?>" class="link-compare"><?php echo $this->__('Add to Compare') ?>

                    <?php endif; ?>

            <a class="discover"href="<?php echo $_product->getProductUrl() ?>" title="">En savoir plus

    <li class="item<?php if(($i-1)%$_columnCount==0): ?> first<?php elseif($i%$_columnCount==0): ?> last<?php endif; ?>">

  <div class="product-image" id="product-switch-<?php echo $z; ?>">
    <?php $_imgSize = 398; ?>
    <img id="product-collection-image-<?php echo $_product->getId(); ?>"
         src="<?php echo $this->helper('catalog/image')->init($_product, 'small_image')->resize($_imgSize); ?>"
         alt="<?php echo $this->stripTags($this->getImageLabel($_product, 'small_image'), null, true) ?>" />

<a href="<?php echo $_product->getProductUrl() ?>" title="<?php echo $this->stripTags($_product->getName(), null, true) ?>"><?php echo $_helper->productAttribute($_product, $_product->getName(), 'name') ?>

        <?php
// Provides extra blocks on which to hang some features for products in the list
// Features providing UI elements targeting this block will display directly below the product name
if ($this->getChild('name.after')) {
$_nameAfterChildren = $this->getChild('name.after')->getSortedChildren();
foreach ($_nameAfterChildren as $_nameAfterChildName) {
$_nameAfterChild = $this->getChild('name.after')->getChild($_nameAfterChildName);
$_nameAfterChild->setProduct($_product);
echo $_nameAfterChild->toHtml();
}
}
?>

            <?php $_product = Mage::getModel('catalog/product')->load($_product->getId());
$_weight = $this->htmlEscape($_product->getWeight());
if ($_weight < 1)
$_weightstr = number_format($_weight*1000) . " mll";
else
$_weightstr = number_format($_weight) . " cl";
echo $_weightstr;
?>

        <?php echo $this->getPriceHtml($_product, true) ?>
        <?php if($_product->getRatingSummary()): ?>
        <?php echo $this->getReviewsSummaryHtml($_product, 'short') ?>
        <?php endif; ?>

          <?php if(!$_product->canConfigure() && $_product->isSaleable()): ?>
          <button type="button" title="<?php echo $this->quoteEscape($this->__('Add to Cart')) ?>" class="button btn-cart" onclick="setLocation('<?php echo $this->getAddToCartUrl($_product) ?>')"><?php echo $this->__('Add to Cart') ?></button>

          <?php elseif($_product->getStockItem() && $_product->getStockItem()->getIsInStock()): ?>
          <a title="<?php echo $this->quoteEscape($this->__('View Details')) ?>" class="button" href="<?php echo $_product->getProductUrl() ?>"><?php echo $this->__('View Details') ?>
          <?php else: ?>

<?php echo $this->__('Out of stock') ?>

          <?php endif; ?>

            <?php if ($this->helper('wishlist')->isAllow()) : ?>

<a href="<?php echo $this->helper('wishlist')->getAddUrl($_product) ?>" class="link-wishlist"><?php echo $this->__('Add to Wishlist') ?>

            <?php endif; ?>
            <?php if($_compareUrl=$this->getAddToCompareUrl($_product)): ?>

| <a href="<?php echo $_compareUrl ?>" class="link-compare"><?php echo $this->__('Add to Compare') ?>

            <?php endif; ?>

        <a class="discover"href="<?php echo $_product->getProductUrl() ?>" title="">En savoir plus

    <div class="product-image-subtext img_toggle" id="product-switch-<?php echo $z; ?>" >
      <?php $_imgSize = 398; ?>
      <img id="product-collection-image-<?php echo $_product->getId(); ?>"
           src="<?php echo $this->helper('catalog/image')->init($_product, 'small_image')->resize($_imgSize); ?>"
           alt="<?php echo $this->stripTags($this->getImageLabel($_product, 'small_image'), null, true) ?>" />

<a href="<?php echo $_product->getProductUrl() ?>" title="<?php echo $this->stripTags($_product->getName(), null, true) ?>"><?php echo $_helper->productAttribute($_product, $_product->getName(), 'name') ?>

        <?php
// Provides extra blocks on which to hang some features for products in the list
// Features providing UI elements targeting this block will display directly below the product name
if ($this->getChild('name.after')) {
$_nameAfterChildren = $this->getChild('name.after')->getSortedChildren();
foreach ($_nameAfterChildren as $_nameAfterChildName) {
$_nameAfterChild = $this->getChild('name.after')->getChild($_nameAfterChildName);
$_nameAfterChild->setProduct($_product);
echo $_nameAfterChild->toHtml();
}
}
?>
        <?php if($_product->getRatingSummary()): ?>
        <?php echo $this->getReviewsSummaryHtml($_product, 'short') ?>
        <?php endif; ?>

Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua
            . Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit
            in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.

        <div class="product-image-subtext img_toggle" id="product-switch-<?php echo $z; ?>" >
            <?php $_imgSize = 398; ?>
            <img id="product-collection-image-<?php echo $_product->getId(); ?>"
                 src="<?php echo $this->helper('catalog/image')->init($_product, 'small_image')->resize($_imgSize); ?>"
                 alt="<?php echo $this->stripTags($this->getImageLabel($_product, 'small_image'), null, true) ?>" />

<a href="<?php echo $_product->getProductUrl() ?>" title="<?php echo $this->stripTags($_product->getName(), null, true) ?>"><?php echo $_helper->productAttribute($_product, $_product->getName(), 'name') ?>

                <?php
                // Provides extra blocks on which to hang some features for products in the list
                // Features providing UI elements targeting this block will display directly below the product name
                if ($this->getChild('name.after')) {
                    $_nameAfterChildren = $this->getChild('name.after')->getSortedChildren();
                    foreach ($_nameAfterChildren as $_nameAfterChildName) {
                        $_nameAfterChild = $this->getChild('name.after')->getChild($_nameAfterChildName);
                        $_nameAfterChild->setProduct($_product);
                        echo $_nameAfterChild->toHtml();
                    }
                }
                ?>
                <?php if($_product->getRatingSummary()): ?>
                <?php echo $this->getReviewsSummaryHtml($_product, 'short') ?>
                <?php endif; ?>

Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua
        . Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit
        in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.


问:
SSL handshake problem? (was: Web page hangs, only clearing browser cache helps)
Please see at the end, as I constantly update with latest investigation data. Currently, I need help with server-side WireShark log.

I experience strange issues with ASP.NET MVC web application. Few users experience form post timeouts and hangs, so that after clicking submit it just lasts forever and does not advance to next page. The strange thing is, this is resolved by clearing browser's cache. I don't understand how these two things can be related. Also, a user reported that it happens in FireFox 3+, but does not happen in FireFox 1.5 and 2.0. Me and many users cannot reproduce this, on IE, any FireFox and both Linux/Windows.

How and why browser cache can affect form POST processing?

OK I checked with users and FireBug. I see the POST request, and it fails after long timeout. The server does not receive the request - at least, not the base controller's OnBeforeExecuting where I do logging, nor in the IIS log files. The response is empty. Also, once the request took long time but finally executed - and on the server I see that it takes very little time to execute.

As far as I see this happens on AJAX requests done with jQuery Form plugin. I tried setting cache: false in parameters, no success.

Actually, I tried without AJAX, plain submit - the same. I can also see that jQuery form plugin DOES call $.ajax() and returns. I see that it initiates POST request. But I don't see this request on the server in IIS logs, until, sometimes, in a minute later - and sometimes it gets aborted in FireBug .Net pane.

Funny thing, is that clearing FireFox cache/cookies/form&post data helps - for one attempt, next post also hangs.

Also, requests sends info about selected components in form of GUIDs. When components are not selected, it seems to work OK. Components are actually hidden checkboxes checked by JavaScript (not at the time of submit, earlier). This is the "selected" parameter in the POST data. Seems like when there're no components selected, it doesn't hang, though I only tried once, maybe will investigate more later.

Any thoughts with this additional info?

```<code>Request info:
User-Agent: Mozilla/5.0 (Windows; U; Windows NT 6.0; en-US; rv:1.9.2.8) Gecko/20100722 Firefox/3.6.8 ( .NET CLR 3.5.30729; .NET4.0C)
Accept: */*
Accept-Language: en-us,en;q=0.5
Accept-Encoding: gzip,deflate
Accept-Charset: ISO-8859-1,utf-8;q=0.7,*;q=0.7
Keep-Alive: 115
Connection: keep-alive
Content-Type: application/x-www-form-urlencoded; charset=UTF-8
X-Requested-With: XMLHttpRequest
Content-Length: 1288
Pragma: no-cache
Cache-Control: no-cache
</code>```

POST data

order=842f2988-abff-413c-a092-9dde00a8b9a8&selected=f98c9ad8-49e0-4a9f-9966-9d3d01203aa5_a1d659c0-b8ec-4f91-ba2f-9d3d01203a4c&selected=f98c9ad8-49e0-4a9f-9966-9d3d01203aa5_d6e1984e-227d-4bd0-b8d2-9d3d01203a4d&selected=f98c9ad8-49e0-4a9f-9966-9d3d01203aa5_0b7cbc1a-35f1-4db8-856b-9d3d01203a4c&selected=f98c9ad8-49e0-4a9f-9966-9d3d01203aa5_0cc7ef9b-085f-4b50-acdb-9d3d01203a4c&selected=f98c9ad8-49e0-4a9f-9966-9d3d01203aa5_ad273397-ed5d-49bb-b181-9d3d01203a4c&selected=f98c9ad8-49e0-4a9f-9966-9d3d01203aa5_b5fbf67f-202f-464b-a9e4-9d3d01203a4c&selected=f98c9ad8-49e0-4a9f-9966-9d3d01203aa5_ae275579-8163-4f6b-9d36-9d3d01203a4c&selected=f98c9ad8-49e0-4a9f-9966-9d3d01203aa5_73fa066c-0467-4bc6-aa91-9d3d01203a4c&selected=f98c9ad8-49e0-4a9f-9966-9d3d01203aa5_5020b52f-baa2-4aea-be10-9d3d01203a4d&selected=f98c9ad8-49e0-4a9f-9966-9d3d01203aa5_8b2cd95a-c014-4c83-9ec6-9d3d01203a4d&selected=f98c9ad8-49e0-4a9f-9966-9d3d01203aa5&submit=Add+To+Suite

Installed WireShark. It's hard to use without direct control (the remote user follows my commands) but I could see that immediately after clicking submit, a TCP request was send to the server IP address. So the browser does a request.

Asked remote user to collaborate with IT/network support to check if request goes from client / arrives to server.

And here is a VERY similar problem, unfortunately without any answer: https://stackoverflow.com/questions/3355000/my-iis-server-wont-serve-ssl-sites-to-some-browsers

Here's WireShark log from the server. Submit starts, then some SSL change cypher/handshake occurs (in 90 secs!), then after long time request finally fails.

```<code>No.     Time        Source                Destination           Protocol Info

  1 0.000000    11.22.33.44         192.168.1.9           TCP      [TCP segment of a reassembled PDU]

  2 0.000114    11.22.33.44         192.168.1.9           TLSv1    Application Data

  3 0.000394    192.168.1.9           11.22.33.44         TCP      https > 50950 [ACK] Seq=1 Ack=2305 Win=64690 Len=0

  4 97.611245   192.168.1.9           11.22.33.44         TCP      https > 50950 [RST, ACK] Seq=1 Ack=2305 Win=0 Len=0

  5 97.752530   11.22.33.44         192.168.1.9           TCP      50958 > https [SYN] Seq=0 Win=8192 Len=0 MSS=1459 WS=2 SACK_PERM=1

  6 97.752612   192.168.1.9           11.22.33.44         TCP      https > 50958 [SYN, ACK] Seq=0 Ack=1 Win=16384 Len=0 MSS=1460 WS=0 SACK_PERM=1

  7 97.778024   11.22.33.44         192.168.1.9           TCP      50958 > https [ACK] Seq=1 Ack=1 Win=17508 Len=0

  8 97.784462   11.22.33.44         192.168.1.9           TLSv1    Client Hello

  9 97.785107   192.168.1.9           11.22.33.44         TLSv1    Server Hello, Change Cipher Spec, Encrypted Handshake Message

 10 97.813970   11.22.33.44         192.168.1.9           TLSv1    Change Cipher Spec, Encrypted Handshake Message

 11 97.814082   11.22.33.44         192.168.1.9           TLSv1    Application Data

 12 97.814208   192.168.1.9           11.22.33.44         TCP      https > 50958 [ACK] Seq=123 Ack=2555 Win=64647 Len=0

 13 227.535270  192.168.1.9           11.22.33.44         TCP      https > 50958 [RST, ACK] Seq=123 Ack=2555 Win=0 Len=0
</code>```

答:
I had a similar issue where mac browsers were not loading an SSL page from an Win2k3 server running IIS 6.0. Updating the .net framework fixed the Firefox and Camino issues, but not the Safari problem. Disabling the AVG Online Scanner fixed my Safari issue, but the link scanner was not installed. Found this post and it fixed my issue.

thanks

ContentLicense: CC BY-SA 2.5

Body:
Please see at the end, as I constantly update with latest investigation data. Currently, I need help with server-side WireShark log.

I experience strange issues with ASP.NET MVC web application. Few users experience form post timeouts and hangs, so that after clicking submit it just lasts forever and does not advance to next page. The strange thing is, this is resolved by clearing browser's cache. I don't understand how these two things can be related. Also, a user reported that it happens in FireFox 3+, but does not happen in FireFox 1.5 and 2.0. Me and many users cannot reproduce this, on IE, any FireFox and both Linux/Windows.

How and why browser cache can affect form POST processing?

OK I checked with users and FireBug. I see the POST request, and it fails after long timeout. The server does not receive the request - at least, not the base controller's OnBeforeExecuting where I do logging, nor in the IIS log files. The response is empty. Also, once the request took long time but finally executed - and on the server I see that it takes very little time to execute.

As far as I see this happens on AJAX requests done with jQuery Form plugin. I tried setting cache: false in parameters, no success.

Actually, I tried without AJAX, plain submit - the same. I can also see that jQuery form plugin DOES call $.ajax() and returns. I see that it initiates POST request. But I don't see this request on the server in IIS logs, until, sometimes, in a minute later - and sometimes it gets aborted in FireBug .Net pane.

Funny thing, is that clearing FireFox cache/cookies/form&post data helps - for one attempt, next post also hangs.

Also, requests sends info about selected components in form of GUIDs. When components are not selected, it seems to work OK. Components are actually hidden checkboxes checked by JavaScript (not at the time of submit, earlier). This is the "selected" parameter in the POST data. Seems like when there're no components selected, it doesn't hang, though I only tried once, maybe will investigate more later.

Any thoughts with this additional info?

Request info:
User-Agent: Mozilla/5.0 (Windows; U; Windows NT 6.0; en-US; rv:1.9.2.8) Gecko/20100722 Firefox/3.6.8 ( .NET CLR 3.5.30729; .NET4.0C)
Accept: */*
Accept-Language: en-us,en;q=0.5
Accept-Encoding: gzip,deflate
Accept-Charset: ISO-8859-1,utf-8;q=0.7,*;q=0.7
Keep-Alive: 115
Connection: keep-alive
Content-Type: application/x-www-form-urlencoded; charset=UTF-8
X-Requested-With: XMLHttpRequest
Content-Length: 1288
Pragma: no-cache
Cache-Control: no-cache

POST data

order=842f2988-abff-413c-a092-9dde00a8b9a8&selected=f98c9ad8-49e0-4a9f-9966-9d3d01203aa5_a1d659c0-b8ec-4f91-ba2f-9d3d01203a4c&selected=f98c9ad8-49e0-4a9f-9966-9d3d01203aa5_d6e1984e-227d-4bd0-b8d2-9d3d01203a4d&selected=f98c9ad8-49e0-4a9f-9966-9d3d01203aa5_0b7cbc1a-35f1-4db8-856b-9d3d01203a4c&selected=f98c9ad8-49e0-4a9f-9966-9d3d01203aa5_0cc7ef9b-085f-4b50-acdb-9d3d01203a4c&selected=f98c9ad8-49e0-4a9f-9966-9d3d01203aa5_ad273397-ed5d-49bb-b181-9d3d01203a4c&selected=f98c9ad8-49e0-4a9f-9966-9d3d01203aa5_b5fbf67f-202f-464b-a9e4-9d3d01203a4c&selected=f98c9ad8-49e0-4a9f-9966-9d3d01203aa5_ae275579-8163-4f6b-9d36-9d3d01203a4c&selected=f98c9ad8-49e0-4a9f-9966-9d3d01203aa5_73fa066c-0467-4bc6-aa91-9d3d01203a4c&selected=f98c9ad8-49e0-4a9f-9966-9d3d01203aa5_5020b52f-baa2-4aea-be10-9d3d01203a4d&selected=f98c9ad8-49e0-4a9f-9966-9d3d01203aa5_8b2cd95a-c014-4c83-9ec6-9d3d01203a4d&selected=f98c9ad8-49e0-4a9f-9966-9d3d01203aa5&submit=Add+To+Suite

Installed WireShark. It's hard to use without direct control (the remote user follows my commands) but I could see that immediately after clicking submit, a TCP request was send to the server IP address. So the browser does a request.

Asked remote user to collaborate with IT/network support to check if request goes from client / arrives to server.

And here is a VERY similar problem, unfortunately without any answer: https://stackoverflow.com/questions/3355000/my-iis-server-wont-serve-ssl-sites-to-some-browsers

Here's WireShark log from the server. Submit starts, then some SSL change cypher/handshake occurs (in 90 secs!), then after long time request finally fails.

No.     Time        Source                Destination           Protocol Info

  1 0.000000    11.22.33.44         192.168.1.9           TCP      [TCP segment of a reassembled PDU]

  2 0.000114    11.22.33.44         192.168.1.9           TLSv1    Application Data

  3 0.000394    192.168.1.9           11.22.33.44         TCP      https > 50950 [ACK] Seq=1 Ack=2305 Win=64690 Len=0

  4 97.611245   192.168.1.9           11.22.33.44         TCP      https > 50950 [RST, ACK] Seq=1 Ack=2305 Win=0 Len=0

  5 97.752530   11.22.33.44         192.168.1.9           TCP      50958 > https [SYN] Seq=0 Win=8192 Len=0 MSS=1459 WS=2 SACK_PERM=1

  6 97.752612   192.168.1.9           11.22.33.44         TCP      https > 50958 [SYN, ACK] Seq=0 Ack=1 Win=16384 Len=0 MSS=1460 WS=0 SACK_PERM=1

  7 97.778024   11.22.33.44         192.168.1.9           TCP      50958 > https [ACK] Seq=1 Ack=1 Win=17508 Len=0

  8 97.784462   11.22.33.44         192.168.1.9           TLSv1    Client Hello

  9 97.785107   192.168.1.9           11.22.33.44         TLSv1    Server Hello, Change Cipher Spec, Encrypted Handshake Message

 10 97.813970   11.22.33.44         192.168.1.9           TLSv1    Change Cipher Spec, Encrypted Handshake Message

 11 97.814082   11.22.33.44         192.168.1.9           TLSv1    Application Data

 12 97.814208   192.168.1.9           11.22.33.44         TCP      https > 50958 [ACK] Seq=123 Ack=2555 Win=64647 Len=0

 13 227.535270  192.168.1.9           11.22.33.44         TCP      https > 50958 [RST, ACK] Seq=123 Ack=2555 Win=0 Len=0


问:
How to detect text in a photo
I am researching into the best way to detect test in a photo using open source libraries.

I think the standard way is as follows (note: steps 1 - 4 all use OpenCV):

1) detect outline of document

2) transform document so it's flat and cropped, using said outline

3) Make the background of document white, using a filter

4) Feed resulting image to Tesseract

Is this the optimum process, or is there a better way, or better tools?
Also, what happens for case if the photo doesn't have a document outline (It's possible that step 1 & 2 are redundant)?

Is there anyway to automatically detect document orientation (i.e. portrait / landscape)?

答:
Look up the uniform width transform.

What this does is detect edges which have more or less the same width with respect to their opposite edge. So things like drainpipes (which can be eliminated at a later pass) but also the majority of text. Whilst conceptually it's similar to a distance transform, the published method uses rather ad hoc normal projection methods and Canny edge detection.

Title: How to detect text in a photo


问:
published bot on skype but it's not working
I have a bot that I've created by merging LUIS and QnA together in a single project using Microsoft Bot Builder.
I published the bot to an EC2 instance from visual studio and I'm using the Bot Framework Emulator for testing and it works perfectly. (MUST use ngrok for tunneling).

Now I want to deploy the bot on Skype. I logged into the Bot Framework Portal and I registered my bot. Now comes the configuration part.
I'm not quite sure what to set as the HTTP endpoint here.

I found this in the Bot Framework documentation:

Complete the Configuration section of the form.

Provide your bot's HTTPS messaging endpoint. This is the endpoint
  where your bot will receive HTTP POST messages from Bot Connector. If
  you built your bot by using the Bot Builder SDK, the endpoint should
  end with /api/messages.

If you have already deployed your bot to the cloud, specify the endpoint generated from that deployment.

If you have not yet deployed your bot to the cloud, leave the endpoint blank for now. You will return to the Bot Framework Portal
  later and specify the endpoint after you've deployed your bot.

When I published from Visual Studio, from the Azure App Service Activity windows, I found this line:

Start Web Deploy Publish the Application/package to https://ec2-00-000-000-00.compute-1.amazonaws.com:PORT/msdeploy.axd?site=bots ...

I used that address for the Messaging Endpoint in the configuration and I published my app. However when I'm testing it on Skype, i'm not receiving any messages from the bot.

I don't know what the problem is exactly, does this have something to do with ngrok? Or am I missing a step here, is there something else I should be doing to deploy the bot on Skype? Maybe something to do with the appid/password that I need to use ... i really don't know

Would really appreciate an explanation of how this works exactly. I don't really understand how the whole deployment procedure works exactly, feels like i'm swimming in murky waters.

答:
Your endpoint is going to be the root of your deployed web application instance, plus the route that your bot is listening on.

For example, one of my bots is deployed to the free version of Azure Web Sites. The URL for a site such as this is https://APPLICATION_NAME.azurewebsites.net and the route that the bot listens on is the default /api/messages. This makes the endpoint https://APPLICATION_NAME.azurewebsites.net/api/messages.

If you connect directly to your app's endpoint, you should at least get a JSON dump with an error message. To make sure your site is getting deployed, drop an HTML file into the root of EC2 and see if you can access this.


问:
Cannot add series to plot
I need help making a really simple plot. It is merely a line graph with an accompanying line for a different set of prices (they are both time series, a line for each good. X = prices, Y = time). So I have a data set that follows the format:

```<code>#Date    prices1   prices2
</code>```

The dates all follow the format YYYY-MM-DD, and the two price columns are numbers. I have checked the class of all three columns to ensure that they are what they are supposed to be ("Date" , "numeric" and "numeric" respectively). Also a few things I feel I should mention:

The data was retrieved by a Quandl() call, and the lengths of the initial data frames were different. Thus, I had to join them using the full_join. I still checked the class() for each column in the final data frame and they are correct.

The price1 column has a length of 91, while price2 column has a length of 100. I initially thought this was the source of the problem. But after having set df$price2[92:100] = NA , I still have the same problem (I can plot each of the lines separately, but neither show up when I use the lines() function).

Furthermore, I made a separate script where I made a three column data frame where I have 100 columns and NA's for the first ten values of col1, NA's for 11th to 20th values of col2, etc.

Now, I did not make them a time-series object and tried graphic them simply as normal data frames. I can plot both of them on their own , but I cannot for the life of me plot one and use the lines() function for the other. What could I be missing? If NA's are the issue, then why am I unable to do the two-line plot with the Quandl data while my test data came out fine?

Due to the circumstances of the problem, I've decided to share the Quandl script and the test script.

```<code>#Original Script with issues
#Retrieving Data1
library(dplyr)
library(zoo)
library("Quandl")

data.1 = Quandl("JODI/OIL_TCPRKL_VEN")
#Putting data in chronological order

      #not in order
      print(data.1$Date[1])
      print(data.1$Date[length(data.1$Date)])

data.1 = data.frame(
  data.1$Date[length(data.1$Date):1],
  data.1$Value[length(data.1$Value):1]
)
names(data.1) = c("Date", "Value1")

      #Now in order
      print(data.1$Date[1])
      print(data.1$Date[length(data.1$Date)])

#Retrieving data2
data.2 = Quandl("JODI/OIL_TCPRKB_IRQ")

      #not in order
      print(data.2$Date[1])
      print(data.2$Date[length(data.2$Date)])

data.2 = data.frame(
  data.2$Date[length(data.2$Date):1],
  data.2$Value[length(data.2$Value):1]
)
names(data.2) = c("Date", "Value2")

      #now in order
      print(data.2$Date[1])
      print(data.2$Date[length(data.2$Date)])

#join the data
data.join = data.frame(full_join(data.1, data.2))

plot(data.join$Date, data.join$Value1,
     col = "blue",
     main = "Should have both lines",
     type = "l",
     sub = "only one of them shows up though. Why?",
     xlab = "Date",
     ylab = "Values")
lines(data.join$Value2)
#plot only has one line. Why??
</code>```

Here is also a test script I made where I do not seem to be having the issue.

```<code>library(dplyr)
library(zoo)

time.a = as.Date(c(10:30))
time.b = as.Date(c(20:40))
time.c = as.Date(c(30:50))

value.a = as.numeric(seq(10,30,1))
value.b = as.numeric(seq(20,60,2))
value.c = as.numeric(seq(20,30,.5))

    length(time.a)
    length(time.b)
    length(time.c)

    length(value.a)
    length(value.b)
    length(value.c)

    print(time.a)
    print(time.b)
    print(time.c)

    print(value.a)
    print(value.b)
    print(value.c)

data.a = data.frame(time.a, value.a)
data.b = data.frame(time.b, value.b)
data.c = data.frame(time.c, value.c)

names(data.a) = c("Date", "Value.a")
names(data.b) = c("Date", "Value.b")
names(data.c) = c("Date", "Value.c")

all.data = full_join(data.a, data.b)
all.data = full_join(all.data, data.c)

plot(all.data$Date, all.data$Value.a,
     type = "l",
     main = "plot",
     xlab = "Date",
     ylab = "Values")

lines(all.data$Date, all.data$Value.b,
      col = "blue")

lines(all.data$Date, all.data$Value.c,
      col = "red")
</code>```

I am really trying to understand why the first script doesn't work, while my second one does. Any help or hints would be greatly appreciated. Why doesn't it work?

答:
Your problem is the y ranges.

Using your sample data:

```<code>df = structure(list(Date = structure(c(14275, 14303, 14334, 14364, 14395,
 14425), class = "Date"), Value1 = c(14347.197, 12856.3706, 14623.1995,
 13998.8553, 14381.6974, 13688.8295), Value2 = c(68603, 62440, 73439,
 69930, 72850, 73500)), .Names = c("Date", "Value1", "Value2"), row.names =
 c(NA, 6L), class = "data.frame")
</code>```

We can see that that the ranges are nowhere close to overlapping, so you need to pre-define the limits of the plot:

```<code>df_range = range(c(df$Value1, df$Value2), na.rm = T)
plot(df$Date, df$Value1, type = "l", ylim = df_range))
lines(df$Date, df$Value2, col = "firebrick4")
</code>```

Title: Cannot add series to plot

Body:
I need help making a really simple plot. It is merely a line graph with an accompanying line for a different set of prices (they are both time series, a line for each good. X = prices, Y = time). So I have a data set that follows the format:

#Date    prices1   prices2

The dates all follow the format YYYY-MM-DD, and the two price columns are numbers. I have checked the class of all three columns to ensure that they are what they are supposed to be ("Date" , "numeric" and "numeric" respectively). Also a few things I feel I should mention:

The data was retrieved by a Quandl() call, and the lengths of the initial data frames were different. Thus, I had to join them using the full_join. I still checked the class() for each column in the final data frame and they are correct.

The price1 column has a length of 91, while price2 column has a length of 100. I initially thought this was the source of the problem. But after having set df$price2[92:100] = NA , I still have the same problem (I can plot each of the lines separately, but neither show up when I use the lines() function).

Furthermore, I made a separate script where I made a three column data frame where I have 100 columns and NA's for the first ten values of col1, NA's for 11th to 20th values of col2, etc.

Now, I did not make them a time-series object and tried graphic them simply as normal data frames. I can plot both of them on their own , but I cannot for the life of me plot one and use the lines() function for the other. What could I be missing? If NA's are the issue, then why am I unable to do the two-line plot with the Quandl data while my test data came out fine?

Due to the circumstances of the problem, I've decided to share the Quandl script and the test script.

#Original Script with issues
#Retrieving Data1
library(dplyr)
library(zoo)
library("Quandl")

data.1 = Quandl("JODI/OIL_TCPRKL_VEN")
#Putting data in chronological order

      #not in order
      print(data.1$Date[1])
      print(data.1$Date[length(data.1$Date)])

data.1 = data.frame(
  data.1$Date[length(data.1$Date):1],
  data.1$Value[length(data.1$Value):1]
)
names(data.1) = c("Date", "Value1")

      #Now in order
      print(data.1$Date[1])
      print(data.1$Date[length(data.1$Date)])

#Retrieving data2
data.2 = Quandl("JODI/OIL_TCPRKB_IRQ")

      #not in order
      print(data.2$Date[1])
      print(data.2$Date[length(data.2$Date)])

data.2 = data.frame(
  data.2$Date[length(data.2$Date):1],
  data.2$Value[length(data.2$Value):1]
)
names(data.2) = c("Date", "Value2")

      #now in order
      print(data.2$Date[1])
      print(data.2$Date[length(data.2$Date)])

#join the data
data.join = data.frame(full_join(data.1, data.2))

plot(data.join$Date, data.join$Value1,
     col = "blue",
     main = "Should have both lines",
     type = "l",
     sub = "only one of them shows up though. Why?",
     xlab = "Date",
     ylab = "Values")
lines(data.join$Value2)
#plot only has one line. Why??

Here is also a test script I made where I do not seem to be having the issue.

library(dplyr)
library(zoo)

time.a = as.Date(c(10:30))
time.b = as.Date(c(20:40))
time.c = as.Date(c(30:50))

value.a = as.numeric(seq(10,30,1))
value.b = as.numeric(seq(20,60,2))
value.c = as.numeric(seq(20,30,.5))

    length(time.a)
    length(time.b)
    length(time.c)

    length(value.a)
    length(value.b)
    length(value.c)

    print(time.a)
    print(time.b)
    print(time.c)

    print(value.a)
    print(value.b)
    print(value.c)

data.a = data.frame(time.a, value.a)
data.b = data.frame(time.b, value.b)
data.c = data.frame(time.c, value.c)

names(data.a) = c("Date", "Value.a")
names(data.b) = c("Date", "Value.b")
names(data.c) = c("Date", "Value.c")

all.data = full_join(data.a, data.b)
all.data = full_join(all.data, data.c)

plot(all.data$Date, all.data$Value.a,
     type = "l",
     main = "plot",
     xlab = "Date",
     ylab = "Values")

lines(all.data$Date, all.data$Value.b,
      col = "blue")

lines(all.data$Date, all.data$Value.c,
      col = "red")

I am really trying to understand why the first script doesn't work, while my second one does. Any help or hints would be greatly appreciated. Why doesn't it work?

Body:
Your problem is the y ranges.

Using your sample data:

df = structure(list(Date = structure(c(14275, 14303, 14334, 14364, 14395,
 14425), class = "Date"), Value1 = c(14347.197, 12856.3706, 14623.1995,
 13998.8553, 14381.6974, 13688.8295), Value2 = c(68603, 62440, 73439,
 69930, 72850, 73500)), .Names = c("Date", "Value1", "Value2"), row.names =
 c(NA, 6L), class = "data.frame")

We can see that that the ranges are nowhere close to overlapping, so you need to pre-define the limits of the plot:

df_range = range(c(df$Value1, df$Value2), na.rm = T)
plot(df$Date, df$Value1, type = "l", ylim = df_range))
lines(df$Date, df$Value2, col = "firebrick4")


问:
using SELECT inside an UPDATE query
I tried doing this query but it doesn't work... can any one help me

```<code>(SELECT (r.fare-r.fare*(t.discount/100)) FROM ccard AS c, downer AS d,
    typepolicy AS t,
rates AS r
WHERE c.cardno=Enter_card_no and d.deviceno=Enter_device_no and
    d.routeno=r.routeno and c.type=t.type );

UPDATE bank
SET amount = amount-[the_result of above select query]
WHERE accountno=(select c.accountno from ccard c where cardno=Enter_card_no);
</code>```

So i tried doing

```<code>UPDATE bank
SET amount = amount-(SELECT (r.fare-r.fare*(t.discount/100)) FROM ccard AS c,
    downer AS d, typepolicy AS t, rates AS r
WHERE c.cardno=Enter_card_no and d.deviceno=Enter_device_no and
    d.routeno=r.routeno and c.type=t.type )
WHERE accountno=(select c.accountno from ccard c where cardno=Enter_card_no);
</code>```

but it gives an error

"Operation must use an updateable query"

答:
First, on the subject of query updatability, if you join your tables using a WHERE clause, the query will not be updatable.  For example, rather than

```<code>FROM downer AS d, rates AS r
WHERE d.routeno=r.routeno
</code>```

you should use

```<code>FROM downer AS d INNER JOIN rates AS r ON d.routeno=r.routeno
</code>```

Second, is [bank] a one-row table?  Or do you really mean to set the amount column to the same value for all rows?

Third, without knowing how to join all the tables in your example, it's not possible to write an updatable query to do what you want.

Title: using SELECT inside an UPDATE query

Body:
I tried doing this query but it doesn't work... can any one help me

(SELECT (r.fare-r.fare*(t.discount/100)) FROM ccard AS c, downer AS d,
    typepolicy AS t,
rates AS r
WHERE c.cardno=Enter_card_no and d.deviceno=Enter_device_no and
    d.routeno=r.routeno and c.type=t.type );

UPDATE bank
SET amount = amount-[the_result of above select query]
WHERE accountno=(select c.accountno from ccard c where cardno=Enter_card_no);

So i tried doing

UPDATE bank
SET amount = amount-(SELECT (r.fare-r.fare*(t.discount/100)) FROM ccard AS c,
    downer AS d, typepolicy AS t, rates AS r
WHERE c.cardno=Enter_card_no and d.deviceno=Enter_device_no and
    d.routeno=r.routeno and c.type=t.type )
WHERE accountno=(select c.accountno from ccard c where cardno=Enter_card_no);

but it gives an error

"Operation must use an updateable query"

Body:
First, on the subject of query updatability, if you join your tables using a WHERE clause, the query will not be updatable.  For example, rather than

FROM downer AS d, rates AS r
WHERE d.routeno=r.routeno

you should use

FROM downer AS d INNER JOIN rates AS r ON d.routeno=r.routeno

Second, is [bank] a one-row table?  Or do you really mean to set the amount column to the same value for all rows?

Third, without knowing how to join all the tables in your example, it's not possible to write an updatable query to do what you want.


问:
Angular: Formatting numbers with commas
Title very much sums up my needs.

```<code>123456789 => 123,456,789
12345 => 12,345
</code>```

What's the best way to get this conversion ? Don't suggest currency pipe in Angular-2 as I don't need $ or currency symbol to be prepend to my output.

答:
Without using pipes, a simple way to answer your question with javascript:

```<code>var str = "The quick brown fox jumps over the lazy dogs.".replace(/(.{2})/g,"$1,");
</code>```

And this will output Th,e ,qu,ic,k ,br,ow,n ,fo,x ,ju,mp,s ,ov,er, t,he, l,az,y ,do,gs,.

But I think you formulated your question bad, so, If you want to parse numbers, you should use this function:

```<code>function numberWithCommas(x) {
    var parts = x.toString().split(".");
    parts[0] = parts[0].replace(/\B(?=(\d{3})+(?!\d))/g, ",");
    return parts.join(".");
}
</code>```

So

```<code>var num = numberWithCommas(1234567);
console.log(num);
</code>```

This will output 1,234,567

Title: Angular: Formatting numbers with commas

Body:
Title very much sums up my needs.

123456789 => 123,456,789
12345 => 12,345

What's the best way to get this conversion ? Don't suggest currency pipe in Angular-2 as I don't need $ or currency symbol to be prepend to my output.

Body:
Without using pipes, a simple way to answer your question with javascript:

var str = "The quick brown fox jumps over the lazy dogs.".replace(/(.{2})/g,"$1,");

And this will output Th,e ,qu,ic,k ,br,ow,n ,fo,x ,ju,mp,s ,ov,er, t,he, l,az,y ,do,gs,.

But I think you formulated your question bad, so, If you want to parse numbers, you should use this function:

function numberWithCommas(x) {
    var parts = x.toString().split(".");
    parts[0] = parts[0].replace(/\B(?=(\d{3})+(?!\d))/g, ",");
    return parts.join(".");
}

So

var num = numberWithCommas(1234567);
console.log(num);

This will output 1,234,567


问:
In Selenium with python, after choosing drop down option page refresh but giving values of previous page
When I choose the next page from the drop-down, the page refreshes when I choose values by python program it gives me the value of the previous page. Though the same query on firebug reaches the correct values but python program unable to fetch values in the new page.</p>

```<code><tr>
<td headers="SINCE">18-FEB-16</td>
<td headers="TOKEN">
<span style="font-family:mono,new courier;font-size:14;color:darkgreen;font- weight:bold">vavFeth3</span>
</td>
<td headers="STATUS">
</code>```

答:
First I fetched values of first page in fetched_passwd then went to next page and then tried to fetch values of next page in fetched_passwd1 but still previous values are being store.</p>

```<code>fetched_passwd=browser.find_elements_by_xpath("//*[@headers='TOKEN']//following::span[2]")
sum=0
for i in fetched_passwd :
    print(i.text)
    sum=sum+1
    if(sum==9):
        break

next_page=browser.find_element_by_xpath("//*[@id='X01_5011970802493527']//following::option[1]").click()

fetched_passwd1=browser.find_elements_by_xpath("//*[@headers='TOKEN']//following::span[2]")
sum=0
for j in fetched_passwd1 :
    print(j.text)
    sum=sum+1
    if(sum==10):
        break
</code>```

Body:
When I choose the next page from the drop-down, the page refreshes when I choose values by python program it gives me the value of the previous page. Though the same query on firebug reaches the correct values but python program unable to fetch values in the new page.

18-FEB-16

vavFeth3

Body:
First I fetched values of first page in fetched_passwd then went to next page and then tried to fetch values of next page in fetched_passwd1 but still previous values are being store.

fetched_passwd=browser.find_elements_by_xpath("//*[@headers='TOKEN']//following::span[2]")
sum=0
for i in fetched_passwd :
    print(i.text)
    sum=sum+1
    if(sum==9):
        break

next_page=browser.find_element_by_xpath("//*[@id='X01_5011970802493527']//following::option[1]").click()

fetched_passwd1=browser.find_elements_by_xpath("//*[@headers='TOKEN']//following::span[2]")
sum=0
for j in fetched_passwd1 :
    print(j.text)
    sum=sum+1
    if(sum==10):
        break


问:
Android Fragments are Duplicating/Recreating on Orientation Change
I'm trying to show two Fragments in a FrameLayout container. I only show one at a time and hide another one based on my application logic. I believe every time I change my device orientation, they recreate! I can see duplicates of fragments overlapping each other! How to fix it? Thanks in advance.

```<code>public class MainActivity extends AppCompatActivity {

   final Fragment oneFragment = oneFragment.newInstance();
   final Fragment twoFragment = twoFragment.newInstance();
   Fragment active = oneFragment;

   final FragmentManager fm = getSupportFragmentManager();

@Override
   protected void onCreate(Bundle savedInstanceState) {

       super.onCreate(savedInstanceState);

       // some other code

        fm.beginTransaction().add(R.id.container, oneFragment, "1").commit();
        fm.beginTransaction().add(R.id.container, twoFragment, "2").commit();

        // onclick listener
        if(condition) {
            fm.beginTransaction().hide(active)
            .show(oneFragment).commit();
        } else {
            fm.beginTransaction().hide(active)
            .show(twoFragment).commit();
        }

      // some other code
</code>```

答:
Fragments are always restored from a previous state automatically after Activity restart.

To avoid this behavior just check if savedInstanceState is null or not.
If it is null - we have a new activity instance, if not - activity was recreated (so, no need to add fragments again - they are already there).

```<code>protected void onCreate(Bundle savedInstanceState) {
   super.onCreate(savedInstanceState);
   if (savedInstanceState == null) {
      fm.beginTransaction().add(R.id.container, oneFragment, "1").commit();
      fm.beginTransaction().add(R.id.container, twoFragment, "2").commit();
   }
}
</code>```

Take a look at this article (section Add a Fragment to an Activity at Runtime) for additional info, it will help you with fragment magic :) https://developer.android.com/training/basics/fragments/fragment-ui.html

Body:
I'm trying to show two Fragments in a FrameLayout container. I only show one at a time and hide another one based on my application logic. I believe every time I change my device orientation, they recreate! I can see duplicates of fragments overlapping each other! How to fix it? Thanks in advance.

public class MainActivity extends AppCompatActivity {

   final Fragment oneFragment = oneFragment.newInstance();
   final Fragment twoFragment = twoFragment.newInstance();
   Fragment active = oneFragment;

   final FragmentManager fm = getSupportFragmentManager();

@Override
   protected void onCreate(Bundle savedInstanceState) {

       super.onCreate(savedInstanceState);

       // some other code

        fm.beginTransaction().add(R.id.container, oneFragment, "1").commit();
        fm.beginTransaction().add(R.id.container, twoFragment, "2").commit();

        // onclick listener
        if(condition) {
            fm.beginTransaction().hide(active)
            .show(oneFragment).commit();
        } else {
            fm.beginTransaction().hide(active)
            .show(twoFragment).commit();
        }

      // some other code

Body:
Fragments are always restored from a previous state automatically after Activity restart.

To avoid this behavior just check if savedInstanceState is null or not.
If it is null - we have a new activity instance, if not - activity was recreated (so, no need to add fragments again - they are already there).

protected void onCreate(Bundle savedInstanceState) {
   super.onCreate(savedInstanceState);
   if (savedInstanceState == null) {
      fm.beginTransaction().add(R.id.container, oneFragment, "1").commit();
      fm.beginTransaction().add(R.id.container, twoFragment, "2").commit();
   }
}

Take a look at this article (section Add a Fragment to an Activity at Runtime) for additional info, it will help you with fragment magic :) https://developer.android.com/training/basics/fragments/fragment-ui.html


问:
Expression resolves to an unused I Value
Here's my code:

```<code>import UIKit
import MessageUI
import UserNotifications

class TripDetailViewController: UIViewController, UIPickerViewDelegate, UIPickerViewDataSource, MFMessageComposeViewControllerDelegate {
    @IBOutlet weak var ScrollView: UIScrollView!
    @IBOutlet weak var tripImage: UIImageView!
    @IBOutlet weak var tripTitle: UILabel!
    @IBOutlet weak var datePickertxt: UITextField!
    @IBOutlet weak var numberOfPeopletxt: UITextField!
    @IBOutlet weak var meetingPoint: UILabel!
    @IBOutlet weak var maxNum: UILabel!
    @IBOutlet weak var tripTime: UILabel!
    @IBOutlet weak var spokenLanguage: UILabel!
    @IBOutlet weak var hostNumber: UILabel!
    @IBOutlet weak var tripLocation: UILabel!
    @IBOutlet weak var hostName: UILabel!
    @IBOutlet weak var tripDescription: UILabel!
    @IBOutlet weak var touristName: UITextField!

    let datePicker = UIDatePicker()
    var numbersOfPeoplePicker = ["1", "2", "3", "4", "5", "6", "7", "8", "9", "10"]
    let numberOfPeoplePicker = UIPickerView()
    var trip = Trip()

    @IBAction func bookButton(_ sender: Any)
    {
        let content = UNMutableNotificationContent()
        content.title = "DiscoverAround"
        content.subtitle = "Someone who booked up your trip!"
        content.body = touristName.text!; "Have booked your trip, and they are"; numberOfPeopletxt.text!; "people, in"; datePickertxt.text!;
        content.badge = 1
        let trigger = UNTimeIntervalNotificationTrigger(timeInterval: 5, repeats: false)
        let request = UNNotificationRequest(identifier: "timerDone", content: content, trigger: trigger)
        UNUserNotificationCenter.current().add(request, withCompletionHandler: nil)
    }
}
</code>```

and I'm getting this error:

"expression resolves to an unused I Value"

on this line:

```<code>content.body = touristName.text!; "Have booked your trip, and they are"; numberOfPeopletxt.text!; "people, in"; datePickertxt.text!;
</code>```

答:
You are not formatting the text correctly. If you want to concatenate strings, you should do it like this:

```<code>content.body = "\(touristName.text!) Have booked your trip, and they are \(numberOfPeopletxt.text!) people, in \(datePickertxt.text!)"
</code>```

If you are not sure that the field's values are nil or not, you should check it before or provide a default value to them:

```<code>if let tourist = touristName.text,
    let numberOfPeople = numberOfPeopletxt.text,
    let datePicker = datePickertxt.text {
    content.body = "\(tourist) Have booked your trip, and they are \(numberOfPeople) people, in \(datePicker)"
}
</code>```

or

```<code>content.body = "\(touristName.text ?? "Nobody") Have booked your trip, and they are \(numberOfPeopletxt.text ?? "0") people, in \(datePickertxt.text ?? "nowhere")"
</code>```

Body:
Here's my code:

import UIKit
import MessageUI
import UserNotifications

class TripDetailViewController: UIViewController, UIPickerViewDelegate, UIPickerViewDataSource, MFMessageComposeViewControllerDelegate {
    @IBOutlet weak var ScrollView: UIScrollView!
    @IBOutlet weak var tripImage: UIImageView!
    @IBOutlet weak var tripTitle: UILabel!
    @IBOutlet weak var datePickertxt: UITextField!
    @IBOutlet weak var numberOfPeopletxt: UITextField!
    @IBOutlet weak var meetingPoint: UILabel!
    @IBOutlet weak var maxNum: UILabel!
    @IBOutlet weak var tripTime: UILabel!
    @IBOutlet weak var spokenLanguage: UILabel!
    @IBOutlet weak var hostNumber: UILabel!
    @IBOutlet weak var tripLocation: UILabel!
    @IBOutlet weak var hostName: UILabel!
    @IBOutlet weak var tripDescription: UILabel!
    @IBOutlet weak var touristName: UITextField!

    let datePicker = UIDatePicker()
    var numbersOfPeoplePicker = ["1", "2", "3", "4", "5", "6", "7", "8", "9", "10"]
    let numberOfPeoplePicker = UIPickerView()
    var trip = Trip()

    @IBAction func bookButton(_ sender: Any)
    {
        let content = UNMutableNotificationContent()
        content.title = "DiscoverAround"
        content.subtitle = "Someone who booked up your trip!"
        content.body = touristName.text!; "Have booked your trip, and they are"; numberOfPeopletxt.text!; "people, in"; datePickertxt.text!;
        content.badge = 1
        let trigger = UNTimeIntervalNotificationTrigger(timeInterval: 5, repeats: false)
        let request = UNNotificationRequest(identifier: "timerDone", content: content, trigger: trigger)
        UNUserNotificationCenter.current().add(request, withCompletionHandler: nil)
    }
}

and I'm getting this error:

"expression resolves to an unused I Value"

on this line:

content.body = touristName.text!; "Have booked your trip, and they are"; numberOfPeopletxt.text!; "people, in"; datePickertxt.text!;

Body:
You are not formatting the text correctly. If you want to concatenate strings, you should do it like this:

content.body = "\(touristName.text!) Have booked your trip, and they are \(numberOfPeopletxt.text!) people, in \(datePickertxt.text!)"

If you are not sure that the field's values are nil or not, you should check it before or provide a default value to them:

if let tourist = touristName.text,
    let numberOfPeople = numberOfPeopletxt.text,
    let datePicker = datePickertxt.text {
    content.body = "\(tourist) Have booked your trip, and they are \(numberOfPeople) people, in \(datePicker)"
}

or

content.body = "\(touristName.text ?? "Nobody") Have booked your trip, and they are \(numberOfPeopletxt.text ?? "0") people, in \(datePickertxt.text ?? "nowhere")"


问:
Regular expression for "not in a list of values" without negative lookahead
I want to search for a string that doesn't exist in a list of strings by using regex. Is it possible to make a regex for that case without using negative lookahead?

答:
When you just search for a plain string in a list of strings you don't even need regex. you can just do string not in list_of_strings

For example if you have

```<code>list_of_string = ['string1', 'string2', 'string3']
string = 'string4'
</code>```

string not in list_of_strings would result in True

Body:
When you just search for a plain string in a list of strings you don't even need regex. you can just do string not in list_of_strings

For example if you have

list_of_string = ['string1', 'string2', 'string3']
string = 'string4'

string not in list_of_strings would result in True


问:
Vue js - source available to component
I have created a source in my main app.js file

```<code>let source = {
    selectedTalent: 0,
};

 var vm = new Vue({
 el: '#app',
 components:{
  Navigation:navigation,
</code>```

I want the source to be available in my navigation component. I aways get a not defined error.

How do I get this to work. Do I have to pass as a prop? I though this would be globally available as 'source'

My component is imported like this as I am using a custom webpack

```<code>import navigation from './components/nav.vue';
</code>```

This is the only difference I can see from the example in the docs.

答:
You should export and import that source object correctly, otherwise its scope is within the app.js script. That scoping is pretty much what Webpack does.

Example:

source.js

```<code>export default let source = {
    selectedTalent: 0,
};
</code>```

navigation.component.js

```<code>import source from '../path/to/source/'

/* your code for the component here */
</code>```

And then you could avoid declaring source in your app.js as you seem not to be using it in there.

Title: Vue js - source available to component

Body:
I have created a source in my main app.js file

let source = {
    selectedTalent: 0,
};

 var vm = new Vue({
 el: '#app',
 components:{
  Navigation:navigation,

I want the source to be available in my navigation component. I aways get a not defined error.

How do I get this to work. Do I have to pass as a prop? I though this would be globally available as 'source'

My component is imported like this as I am using a custom webpack

import navigation from './components/nav.vue';

This is the only difference I can see from the example in the docs.

Body:
You should export and import that source object correctly, otherwise its scope is within the app.js script. That scoping is pretty much what Webpack does.

Example:

source.js

export default let source = {
    selectedTalent: 0,
};

navigation.component.js

import source from '../path/to/source/'

/* your code for the component here */

And then you could avoid declaring source in your app.js as you seem not to be using it in there.