问:
Why am I getting this javascript error when I'm doing my Django?
I have valid json according to jsonlint.com

In my javascript, I do this:

```<code>var params = JSON.parse('{{ all_params_in_json }}');
</code>```

And I get this error:

```<code>Uncaught SyntaxError: Unexpected token ILLEGAL
(anonymous function)
</code>```

Why? My json is valid.  I'm using the standard json2 library.

My json is this:

```{
    "browser_location": "Sausalito",
    "browser_distance": 5,
    "users_who_voted": [

    ],
    "author": {
        "username": "swnn",
        "bio": "I'm the CEO at Twitter.  Prior to Twitter, I cofounded FeedBurner (acquired by Google). I'm an investor and Advisor in a few start-ups including about.me.\r\n \r\nI used to perform with Chicago\u2019s Annoyance Theater and at various comedy festivals in Edinburgh, Montreal and other distant lands. I recently left the cold winters of Chicago for Marin County's sunshine.",
        "first_name": "feli",
        "last_name": "twan",
        "avatar_url": "http://s3.amazonaws.com/fabletest/937ypvlchrd2e5z1a0sq",
        "is_active": true,
        "is_superuser": false,
        "is_staff": false,
        "last_login": 1295410796.0,
        "location": "San Francisco",
        "fullname": "twan Chan",
        "id": 1,
        "date_joined": 1293678904.0
    },
    "total_views": 227,
    "comments": [
        {
            "body": "sdfasdf",
            "created_at": 1295317816.0,
            "user": {
                "username": "swnn",
                "bio": "I'm the CEO at Twitter.  Prior to Twitter, I cofounded FeedBurner (acquired by Google). I'm an investor and Advisor in a few start-ups including about.me.\r\n \r\nI used to perform with Chicago\u2019s Annoyance Theater and at various comedy festivals in Edinburgh, Montreal and other distant lands. I recently left the cold winters of Chicago for Marin County's sunshine.",
                "first_name": "feli",
                "last_name": "twan",
                "avatar_url": "http://s3.amazonaws.com/fabletest/937ypvlchrd2e5z1a0sq",
                "is_active": true,
                "is_superuser": false,
                "is_staff": false,
                "last_login": 1295410796.0,
                "location": "San Francisco",
                "fullname": "twan Chan",
                "id": 1,
                "date_joined": 1293678904.0
            }
        },
        {
            "body": "sdfasdfasd",
            "created_at": 1295317900.0,
            "user": {
                "username": "swnn",
                "bio": "I'm the CEO at Twitter.  Prior to Twitter, I cofounded FeedBurner (acquired by Google). I'm an investor and Advisor in a few start-ups including about.me.\r\n \r\nI used to perform with Chicago\u2019s Annoyance Theater and at various comedy festivals in Edinburgh, Montreal and other distant lands. I recently left the cold winters of Chicago for Marin County's sunshine.",
                "first_name": "feli",
                "last_name": "twan",
                "avatar_url": "http://s3.amazonaws.com/fabletest/937ypvlchrd2e5z1a0sq",
                "is_active": true,
                "is_superuser": false,
                "is_staff": false,
                "last_login": 1295410796.0,
                "location": "San Francisco",
                "fullname": "twan Chan",
                "id": 1,
                "date_joined": 1293678904.0
            }
        },
        {
            "body": "sdasdasD",
            "created_at": 1295323153.0,
            "user": {
                "username": "swnn",
                "bio": "I'm the CEO at Twitter.  Prior to Twitter, I cofounded FeedBurner (acquired by Google). I'm an investor and Advisor in a few start-ups including about.me.\r\n \r\nI used to perform with Chicago\u2019s Annoyance Theater and at various comedy festivals in Edinburgh, Montreal and other distant lands. I recently left the cold winters of Chicago for Marin County's sunshine.",
                "first_name": "feli",
                "last_name": "twan",
                "avatar_url": "http://s3.amazonaws.com/fabletest/937ypvlchrd2e5z1a0sq",
                "is_active": true,
                "is_superuser": false,
                "is_staff": false,
                "last_login": 1295410796.0,
                "location": "San Francisco",
                "fullname": "twan Chan",
                "id": 1,
                "date_joined": 1293678904.0
            }
        },
        {
            "body": "The picture in this submission is not accurate",
            "created_at": 1295325473.0,
            "user": {
                "username": "swnn",
                "bio": "I'm the CEO at Twitter.  Prior to Twitter, I cofounded FeedBurner (acquired by Google). I'm an investor and Advisor in a few start-ups including about.me.\r\n \r\nI used to perform with Chicago\u2019s Annoyance Theater and at various comedy festivals in Edinburgh, Montreal and other distant lands. I recently left the cold winters of Chicago for Marin County's sunshine.",
                "first_name": "feli",
                "last_name": "twan",
                "avatar_url": "http://s3.amazonaws.com/fabletest/937ypvlchrd2e5z1a0sq",
                "is_active": true,
                "is_superuser": false,
                "is_staff": false,
                "last_login": 1295410796.0,
                "location": "San Francisco",
                "fullname": "twan Chan",
                "id": 1,
                "date_joined": 1293678904.0
            }
        },
        {
            "body": "This submission is not useful to me.",
            "created_at": 1295325491.0,
            "user": {
                "username": "swnn",
                "bio": "I'm the CEO at Twitter.  Prior to Twitter, I cofounded FeedBurner (acquired by Google). I'm an investor and Advisor in a few start-ups including about.me.\r\n \r\nI used to perform with Chicago\u2019s Annoyance Theater and at various comedy festivals in Edinburgh, Montreal and other distant lands. I recently left the cold winters of Chicago for Marin County's sunshine.",
                "first_name": "feli",
                "last_name": "twan",
                "avatar_url": "http://s3.amazonaws.com/fabletest/937ypvlchrd2e5z1a0sq",
                "is_active": true,
                "is_superuser": false,
                "is_staff": false,
                "last_login": 1295410796.0,
                "location": "San Francisco",
                "fullname": "twan Chan",
                "id": 1,
                "date_joined": 1293678904.0
            }
        },
        {
            "body": "lcokc",
            "created_at": 1295344958.0,
            "user": {
                "username": "swnn",
                "bio": "I'm the CEO at Twitter.  Prior to Twitter, I cofounded FeedBurner (acquired by Google). I'm an investor and Advisor in a few start-ups including about.me.\r\n \r\nI used to perform with Chicago\u2019s Annoyance Theater and at various comedy festivals in Edinburgh, Montreal and other distant lands. I recently left the cold winters of Chicago for Marin County's sunshine.",
                "first_name": "feli",
                "last_name": "twan",
                "avatar_url": "http://s3.amazonaws.com/fabletest/937ypvlchrd2e5z1a0sq",
                "is_active": true,
                "is_superuser": false,
                "is_staff": false,
                "last_login": 1295410796.0,
                "location": "San Francisco",
                "fullname": "twan Chan",
                "id": 1,
                "date_joined": 1293678904.0
            }
        },
        {
            "body": "gagaga",
            "created_at": 1295345040.0,
            "user": {
                "username": "swnn",
                "bio": "I'm the CEO at Twitter.  Prior to Twitter, I cofounded FeedBurner (acquired by Google). I'm an investor and Advisor in a few start-ups including about.me.\r\n \r\nI used to perform with Chicago\u2019s Annoyance Theater and at various comedy festivals in Edinburgh, Montreal and other distant lands. I recently left the cold winters of Chicago for Marin County's sunshine.",
                "first_name": "feli",
                "last_name": "twan",
                "avatar_url": "http://s3.amazonaws.com/fabletest/937ypvlchrd2e5z1a0sq",
                "is_active": true,
                "is_superuser": false,
                "is_staff": false,
                "last_login": 1295410796.0,
                "location": "San Francisco",
                "fullname": "twan Chan",
                "id": 1,
                "date_joined": 1293678904.0
            }
        },
        {
            "body": "wwwww",
            "created_at": 1295345084.0,
            "user": {
                "username": "swnn",
                "bio": "I'm the CEO at Twitter.  Prior to Twitter, I cofounded FeedBurner (acquired by Google). I'm an investor and Advisor in a few start-ups including about.me.\r\n \r\nI used to perform with Chicago\u2019s Annoyance Theater and at various comedy festivals in Edinburgh, Montreal and other distant lands. I recently left the cold winters of Chicago for Marin County's sunshine.",
                "first_name": "feli",
                "last_name": "twan",
                "avatar_url": "http://s3.amazonaws.com/fabletest/937ypvlchrd2e5z1a0sq",
                "is_active": true,
                "is_superuser": false,
                "is_staff": false,
                "last_login": 1295410796.0,
                "location": "San Francisco",
                "fullname": "twan Chan",
                "id": 1,
                "date_joined": 1293678904.0
            }
        },
        {
            "body": "sadfasdfasdf",
            "created_at": 1295345136.0,
            "user": {
                "username": "swnn",
                "bio": "I'm the CEO at Twitter.  Prior to Twitter, I cofounded FeedBurner (acquired by Google). I'm an investor and Advisor in a few start-ups including about.me.\r\n \r\nI used to perform with Chicago\u2019s Annoyance Theater and at various comedy festivals in Edinburgh, Montreal and other distant lands. I recently left the cold winters of Chicago for Marin County's sunshine.",
                "first_name": "feli",
                "last_name": "twan",
                "avatar_url": "http://s3.amazonaws.com/fabletest/937ypvlchrd2e5z1a0sq",
                "is_active": true,
                "is_superuser": false,
                "is_staff": false,
                "last_login": 1295410796.0,
                "location": "San Francisco",
                "fullname": "twan Chan",
                "id": 1,
                "date_joined": 1293678904.0
            }
        },
        {
            "body": "asdasdf",
            "created_at": 1295345253.0,
            "user": {
                "username": "swnn",
                "bio": "I'm the CEO at Twitter.  Prior to Twitter, I cofounded FeedBurner (acquired by Google). I'm an investor and Advisor in a few start-ups including about.me.\r\n \r\nI used to perform with Chicago\u2019s Annoyance Theater and at various comedy festivals in Edinburgh, Montreal and other distant lands. I recently left the cold winters of Chicago for Marin County's sunshine.",
                "first_name": "feli",
                "last_name": "twan",
                "avatar_url": "http://s3.amazonaws.com/fabletest/937ypvlchrd2e5z1a0sq",
                "is_active": true,
                "is_superuser": false,
                "is_staff": false,
                "last_login": 1295410796.0,
                "location": "San Francisco",
                "fullname": "twan Chan",
                "id": 1,
                "date_joined": 1293678904.0
            }
        },
        {
            "body": "sdfasdfasd",
            "created_at": 1295345279.0,
            "user": {
                "username": "swnn",
                "bio": "I'm the CEO at Twitter.  Prior to Twitter, I cofounded FeedBurner (acquired by Google). I'm an investor and Advisor in a few start-ups including about.me.\r\n \r\nI used to perform with Chicago\u2019s Annoyance Theater and at various comedy festivals in Edinburgh, Montreal and other distant lands. I recently left the cold winters of Chicago for Marin County's sunshine.",
                "first_name": "feli",
                "last_name": "twan",
                "avatar_url": "http://s3.amazonaws.com/fabletest/937ypvlchrd2e5z1a0sq",
                "is_active": true,
                "is_superuser": false,
                "is_staff": false,
                "last_login": 1295410796.0,
                "location": "San Francisco",
                "fullname": "twan Chan",
                "id": 1,
                "date_joined": 1293678904.0
            }
        },
        {
            "body": "asdfasdf",
            "created_at": 1295345358.0,
            "user": {
                "username": "swnn",
                "bio": "I'm the CEO at Twitter.  Prior to Twitter, I cofounded FeedBurner (acquired by Google). I'm an investor and Advisor in a few start-ups including about.me.\r\n \r\nI used to perform with Chicago\u2019s Annoyance Theater and at various comedy festivals in Edinburgh, Montreal and other distant lands. I recently left the cold winters of Chicago for Marin County's sunshine.",
                "first_name": "feli",
                "last_name": "twan",
                "avatar_url": "http://s3.amazonaws.com/fabletest/937ypvlchrd2e5z1a0sq",
                "is_active": true,
                "is_superuser": false,
                "is_staff": false,
                "last_login": 1295410796.0,
                "location": "San Francisco",
                "fullname": "twan Chan",
                "id": 1,
                "date_joined": 1293678904.0
            }
        },
        {
            "body": "foxed",
            "created_at": 1295345790.0,
            "user": {
                "username": "swnn",
                "bio": "I'm the CEO at Twitter.  Prior to Twitter, I cofounded FeedBurner (acquired by Google). I'm an investor and Advisor in a few start-ups including about.me.\r\n \r\nI used to perform with Chicago\u2019s Annoyance Theater and at various comedy festivals in Edinburgh, Montreal and other distant lands. I recently left the cold winters of Chicago for Marin County's sunshine.",
                "first_name": "feli",
                "last_name": "twan",
                "avatar_url": "http://s3.amazonaws.com/fabletest/937ypvlchrd2e5z1a0sq",
                "is_active": true,
                "is_superuser": false,
                "is_staff": false,
                "last_login": 1295410796.0,
                "location": "San Francisco",
                "fullname": "twan Chan",
                "id": 1,
                "date_joined": 1293678904.0
            }
        },
        {
            "body": "Is this really the right thing? I mean...after thinking about it. ist's just not very cool",
            "created_at": 1295345827.0,
            "user": {
                "username": "swnn",
                "bio": "I'm the CEO at Twitter.  Prior to Twitter, I cofounded FeedBurner (acquired by Google). I'm an investor and Advisor in a few start-ups including about.me.\r\n \r\nI used to perform with Chicago\u2019s Annoyance Theater and at various comedy festivals in Edinburgh, Montreal and other distant lands. I recently left the cold winters of Chicago for Marin County's sunshine.",
                "first_name": "feli",
                "last_name": "twan",
                "avatar_url": "http://s3.amazonaws.com/fabletest/937ypvlchrd2e5z1a0sq",
                "is_active": true,
                "is_superuser": false,
                "is_staff": false,
                "last_login": 1295410796.0,
                "location": "San Francisco",
                "fullname": "twan Chan",
                "id": 1,
                "date_joined": 1293678904.0
            }
        },
        {
            "body": "s this really the right thing? I mean...after thinking about it. ist's just not very cool",
            "created_at": 1295345871.0,
            "user": {
                "username": "swnn",
                "bio": "I'm the CEO at Twitter.  Prior to Twitter, I cofounded FeedBurner (acquired by Google). I'm an investor and Advisor in a few start-ups including about.me.\r\n \r\nI used to perform with Chicago\u2019s Annoyance Theater and at various comedy festivals in Edinburgh, Montreal and other distant lands. I recently left the cold winters of Chicago for Marin County's sunshine.",
                "first_name": "feli",
                "last_name": "twan",
                "avatar_url": "http://s3.amazonaws.com/fabletest/937ypvlchrd2e5z1a0sq",
                "is_active": true,
                "is_superuser": false,
                "is_staff": false,
                "last_login": 1295410796.0,
                "location": "San Francisco",
                "fullname": "twan Chan",
                "id": 1,
                "date_joined": 1293678904.0
            }
        },
        {
            "body": "his song really suck.s",
            "created_at": 1295346108.0,
            "user": {
                "username": "swnn",
                "bio": "I'm the CEO at Twitter.  Prior to Twitter, I cofounded FeedBurner (acquired by Google). I'm an investor and Advisor in a few start-ups including about.me.\r\n \r\nI used to perform with Chicago\u2019s Annoyance Theater and at various comedy festivals in Edinburgh, Montreal and other distant lands. I recently left the cold winters of Chicago for Marin County's sunshine.",
                "first_name": "feli",
                "last_name": "twan",
                "avatar_url": "http://s3.amazonaws.com/fabletest/937ypvlchrd2e5z1a0sq",
                "is_active": true,
                "is_superuser": false,
                "is_staff": false,
                "last_login": 1295410796.0,
                "location": "San Francisco",
                "fullname": "twan Chan",
                "id": 1,
                "date_joined": 1293678904.0
            }
        },
        {
            "body": "asdfasdf",
            "created_at": 1295383689.0,
            "user": {
                "username": "swnn",
                "bio": "I'm the CEO at Twitter.  Prior to Twitter, I cofounded FeedBurner (acquired by Google). I'm an investor and Advisor in a few start-ups including about.me.\r\n \r\nI used to perform with Chicago\u2019s Annoyance Theater and at various comedy festivals in Edinburgh, Montreal and other distant lands. I recently left the cold winters of Chicago for Marin County's sunshine.",
                "first_name": "feli",
                "last_name": "twan",
                "avatar_url": "http://s3.amazonaws.com/fabletest/937ypvlchrd2e5z1a0sq",
                "is_active": true,
                "is_superuser": false,
                "is_staff": false,
                "last_login": 1295410796.0,
                "location": "San Francisco",
                "fullname": "twan Chan",
                "id": 1,
                "date_joined": 1293678904.0
            }
        },
        {
            "body": "asdfasdf",
            "created_at": 1295410874.0,
            "user": {
                "username": "swnn",
                "bio": "I'm the CEO at Twitter.  Prior to Twitter, I cofounded FeedBurner (acquired by Google). I'm an investor and Advisor in a few start-ups including about.me.\r\n \r\nI used to perform with Chicago\u2019s Annoyance Theater and at various comedy festivals in Edinburgh, Montreal and other distant lands. I recently left the cold winters of Chicago for Marin County's sunshine.",
                "first_name": "feli",
                "last_name": "twan",
                "avatar_url": "http://s3.amazonaws.com/fabletest/937ypvlchrd2e5z1a0sq",
                "is_active": true,
                "is_superuser": false,
                "is_staff": false,
                "last_login": 1295410796.0,
                "location": "San Francisco",
                "fullname": "twan Chan",
                "id": 1,
                "date_joined": 1293678904.0
            }
        },
        {
            "body": "Is this all right?",
            "created_at": 1295411376.0,
            "user": {
                "username": "swnn",
                "bio": "I'm the CEO at Twitter.  Prior to Twitter, I cofounded FeedBurner (acquired by Google). I'm an investor and Advisor in a few start-ups including about.me.\r\n \r\nI used to perform with Chicago\u2019s Annoyance Theater and at various comedy festivals in Edinburgh, Montreal and other distant lands. I recently left the cold winters of Chicago for Marin County's sunshine.",
                "first_name": "feli",
                "last_name": "twan",
                "avatar_url": "http://s3.amazonaws.com/fabletest/937ypvlchrd2e5z1a0sq",
                "is_active": true,
                "is_superuser": false,
                "is_staff": false,
                "last_login": 1295410796.0,
                "location": "San Francisco",
                "fullname": "twan Chan",
                "id": 1,
                "date_joined": 1293678904.0
            }
        }
    ],
    "initial_vote": 0,
    "browser_lat": 37.848800659179688,
    "post": {
        "ip": "174.129.251.48",
        "thumb_500x500": {
            "url": "http://s3.amazonaws.com/fabletest/bv2814ghmd",
            "width": 500,
            "height": 351
        },
        "date": 1295154531.334044,
        "thumb_original": {
            "url": "http://farm6.static.flickr.com/5249/5336976806_481943d486_b.jpg",
            "width": 779,
            "height": 548
        },
        "total_views": 227,
        "thumb_230x480": {
            "url": "http://s3.amazonaws.com/fabletest/4e7h95rt3f",
            "width": 230,
            "height": 480
        },
        "test_set": "g2",
        "title": "Maybe. . .we were supposed to meet the wrong people before meeting the right one so that, when we finally meet the right person, we will know how to be grateful for that gift ...",
        "stamp": "bf305695ca51b5390dc0c2f34c074215",
        "pop_score": 241.59687499999995,
        "thumb_640x640": {
            "url": "http://s3.amazonaws.com/fabletest/4q15bsgmt2",
            "width": 640,
            "height": 450
        },
        "image_direction": "landscape",
        "author_username": "swnn",
        "thumb_230x230": {
            "url": "http://s3.amazonaws.com/fabletest/x0dq7gzb4f",
            "width": 230,
            "height": 230
        },
        "description": "sooc with Shana Rae overlay ....",
        "top_score": 0.90000000000000002,
        "active": true,
        "original_file": "http://farm6.static.flickr.com/5249/5336976806_481943d486_b.jpg",
        "loc_utm": [
            500000.0,
            6317527.4506855672
        ],
        "_id": {
            "$oid": "4d327d658aad6919be0000d5"
        },
        "sizes": [
            {
                "url": "http://farm6.static.flickr.com/5249/5336976806_481943d486_b.jpg",
                "width": 779,
                "height": 548
            },
            {
                "url": "http://s3.amazonaws.com/fabletest/4q15bsgmt2",
                "width": 640,
                "height": 450
            },
            {
                "url": "http://s3.amazonaws.com/fabletest/bv2814ghmd",
                "width": 500,
                "height": 351
            },
            {
                "url": "http://s3.amazonaws.com/fabletest/x0dq7gzb4f",
                "width": 230,
                "height": 230
            },
            {
                "url": "http://s3.amazonaws.com/fabletest/4e7h95rt3f",
                "width": 230,
                "height": 480
            },
            {
                "url": "http://s3.amazonaws.com/fabletest/g1pmqk7r6y",
                "width": 480,
                "height": 230
            }
        ],
        "loc_latlong": [
            57.0,
            -99.0
        ],
        "thumb_480x230": {
            "url": "http://s3.amazonaws.com/fabletest/g1pmqk7r6y",
            "width": 480,
            "height": 230
        },
        "processed": true,
        "author_id": 1,
        "content_id": 13259,
        "thumb_500x500_low": {
            "url": "http://s3.amazonaws.com/fabletest/oznumyqve7",
            "width": 500,
            "quality": 4,
            "height": 351
        }
    },
    "browser_long": -122.53489685058594,
    "pos_votes_count": 0
}
```

答:
You have to do:

```<code>var params = JSON.parse('{{ all_params_in_json|escapejs }}');
</code>```

Otherwise e.g ' char inside all_params_in_json variable terminates string and all hell breaks loose.

Body:
I have valid json according to jsonlint.com

In my javascript, I do this:

var params = JSON.parse('{{ all_params_in_json }}');

And I get this error:

Uncaught SyntaxError: Unexpected token ILLEGAL
(anonymous function)

Why? My json is valid.  I'm using the standard json2 library.

My json is this:

{
    "browser_location": "Sausalito",
    "browser_distance": 5,
    "users_who_voted": [

    ],
    "author": {
        "username": "swnn",
        "bio": "I'm the CEO at Twitter.  Prior to Twitter, I cofounded FeedBurner (acquired by Google). I'm an investor and Advisor in a few start-ups including about.me.\r\n \r\nI used to perform with Chicago\u2019s Annoyance Theater and at various comedy festivals in Edinburgh, Montreal and other distant lands. I recently left the cold winters of Chicago for Marin County's sunshine.",
        "first_name": "feli",
        "last_name": "twan",
        "avatar_url": "http://s3.amazonaws.com/fabletest/937ypvlchrd2e5z1a0sq",
        "is_active": true,
        "is_superuser": false,
        "is_staff": false,
        "last_login": 1295410796.0,
        "location": "San Francisco",
        "fullname": "twan Chan",
        "id": 1,
        "date_joined": 1293678904.0
    },
    "total_views": 227,
    "comments": [
        {
            "body": "sdfasdf",
            "created_at": 1295317816.0,
            "user": {
                "username": "swnn",
                "bio": "I'm the CEO at Twitter.  Prior to Twitter, I cofounded FeedBurner (acquired by Google). I'm an investor and Advisor in a few start-ups including about.me.\r\n \r\nI used to perform with Chicago\u2019s Annoyance Theater and at various comedy festivals in Edinburgh, Montreal and other distant lands. I recently left the cold winters of Chicago for Marin County's sunshine.",
                "first_name": "feli",
                "last_name": "twan",
                "avatar_url": "http://s3.amazonaws.com/fabletest/937ypvlchrd2e5z1a0sq",
                "is_active": true,
                "is_superuser": false,
                "is_staff": false,
                "last_login": 1295410796.0,
                "location": "San Francisco",
                "fullname": "twan Chan",
                "id": 1,
                "date_joined": 1293678904.0
            }
        },
        {
            "body": "sdfasdfasd",
            "created_at": 1295317900.0,
            "user": {
                "username": "swnn",
                "bio": "I'm the CEO at Twitter.  Prior to Twitter, I cofounded FeedBurner (acquired by Google). I'm an investor and Advisor in a few start-ups including about.me.\r\n \r\nI used to perform with Chicago\u2019s Annoyance Theater and at various comedy festivals in Edinburgh, Montreal and other distant lands. I recently left the cold winters of Chicago for Marin County's sunshine.",
                "first_name": "feli",
                "last_name": "twan",
                "avatar_url": "http://s3.amazonaws.com/fabletest/937ypvlchrd2e5z1a0sq",
                "is_active": true,
                "is_superuser": false,
                "is_staff": false,
                "last_login": 1295410796.0,
                "location": "San Francisco",
                "fullname": "twan Chan",
                "id": 1,
                "date_joined": 1293678904.0
            }
        },
        {
            "body": "sdasdasD",
            "created_at": 1295323153.0,
            "user": {
                "username": "swnn",
                "bio": "I'm the CEO at Twitter.  Prior to Twitter, I cofounded FeedBurner (acquired by Google). I'm an investor and Advisor in a few start-ups including about.me.\r\n \r\nI used to perform with Chicago\u2019s Annoyance Theater and at various comedy festivals in Edinburgh, Montreal and other distant lands. I recently left the cold winters of Chicago for Marin County's sunshine.",
                "first_name": "feli",
                "last_name": "twan",
                "avatar_url": "http://s3.amazonaws.com/fabletest/937ypvlchrd2e5z1a0sq",
                "is_active": true,
                "is_superuser": false,
                "is_staff": false,
                "last_login": 1295410796.0,
                "location": "San Francisco",
                "fullname": "twan Chan",
                "id": 1,
                "date_joined": 1293678904.0
            }
        },
        {
            "body": "The picture in this submission is not accurate",
            "created_at": 1295325473.0,
            "user": {
                "username": "swnn",
                "bio": "I'm the CEO at Twitter.  Prior to Twitter, I cofounded FeedBurner (acquired by Google). I'm an investor and Advisor in a few start-ups including about.me.\r\n \r\nI used to perform with Chicago\u2019s Annoyance Theater and at various comedy festivals in Edinburgh, Montreal and other distant lands. I recently left the cold winters of Chicago for Marin County's sunshine.",
                "first_name": "feli",
                "last_name": "twan",
                "avatar_url": "http://s3.amazonaws.com/fabletest/937ypvlchrd2e5z1a0sq",
                "is_active": true,
                "is_superuser": false,
                "is_staff": false,
                "last_login": 1295410796.0,
                "location": "San Francisco",
                "fullname": "twan Chan",
                "id": 1,
                "date_joined": 1293678904.0
            }
        },
        {
            "body": "This submission is not useful to me.",
            "created_at": 1295325491.0,
            "user": {
                "username": "swnn",
                "bio": "I'm the CEO at Twitter.  Prior to Twitter, I cofounded FeedBurner (acquired by Google). I'm an investor and Advisor in a few start-ups including about.me.\r\n \r\nI used to perform with Chicago\u2019s Annoyance Theater and at various comedy festivals in Edinburgh, Montreal and other distant lands. I recently left the cold winters of Chicago for Marin County's sunshine.",
                "first_name": "feli",
                "last_name": "twan",
                "avatar_url": "http://s3.amazonaws.com/fabletest/937ypvlchrd2e5z1a0sq",
                "is_active": true,
                "is_superuser": false,
                "is_staff": false,
                "last_login": 1295410796.0,
                "location": "San Francisco",
                "fullname": "twan Chan",
                "id": 1,
                "date_joined": 1293678904.0
            }
        },
        {
            "body": "lcokc",
            "created_at": 1295344958.0,
            "user": {
                "username": "swnn",
                "bio": "I'm the CEO at Twitter.  Prior to Twitter, I cofounded FeedBurner (acquired by Google). I'm an investor and Advisor in a few start-ups including about.me.\r\n \r\nI used to perform with Chicago\u2019s Annoyance Theater and at various comedy festivals in Edinburgh, Montreal and other distant lands. I recently left the cold winters of Chicago for Marin County's sunshine.",
                "first_name": "feli",
                "last_name": "twan",
                "avatar_url": "http://s3.amazonaws.com/fabletest/937ypvlchrd2e5z1a0sq",
                "is_active": true,
                "is_superuser": false,
                "is_staff": false,
                "last_login": 1295410796.0,
                "location": "San Francisco",
                "fullname": "twan Chan",
                "id": 1,
                "date_joined": 1293678904.0
            }
        },
        {
            "body": "gagaga",
            "created_at": 1295345040.0,
            "user": {
                "username": "swnn",
                "bio": "I'm the CEO at Twitter.  Prior to Twitter, I cofounded FeedBurner (acquired by Google). I'm an investor and Advisor in a few start-ups including about.me.\r\n \r\nI used to perform with Chicago\u2019s Annoyance Theater and at various comedy festivals in Edinburgh, Montreal and other distant lands. I recently left the cold winters of Chicago for Marin County's sunshine.",
                "first_name": "feli",
                "last_name": "twan",
                "avatar_url": "http://s3.amazonaws.com/fabletest/937ypvlchrd2e5z1a0sq",
                "is_active": true,
                "is_superuser": false,
                "is_staff": false,
                "last_login": 1295410796.0,
                "location": "San Francisco",
                "fullname": "twan Chan",
                "id": 1,
                "date_joined": 1293678904.0
            }
        },
        {
            "body": "wwwww",
            "created_at": 1295345084.0,
            "user": {
                "username": "swnn",
                "bio": "I'm the CEO at Twitter.  Prior to Twitter, I cofounded FeedBurner (acquired by Google). I'm an investor and Advisor in a few start-ups including about.me.\r\n \r\nI used to perform with Chicago\u2019s Annoyance Theater and at various comedy festivals in Edinburgh, Montreal and other distant lands. I recently left the cold winters of Chicago for Marin County's sunshine.",
                "first_name": "feli",
                "last_name": "twan",
                "avatar_url": "http://s3.amazonaws.com/fabletest/937ypvlchrd2e5z1a0sq",
                "is_active": true,
                "is_superuser": false,
                "is_staff": false,
                "last_login": 1295410796.0,
                "location": "San Francisco",
                "fullname": "twan Chan",
                "id": 1,
                "date_joined": 1293678904.0
            }
        },
        {
            "body": "sadfasdfasdf",
            "created_at": 1295345136.0,
            "user": {
                "username": "swnn",
                "bio": "I'm the CEO at Twitter.  Prior to Twitter, I cofounded FeedBurner (acquired by Google). I'm an investor and Advisor in a few start-ups including about.me.\r\n \r\nI used to perform with Chicago\u2019s Annoyance Theater and at various comedy festivals in Edinburgh, Montreal and other distant lands. I recently left the cold winters of Chicago for Marin County's sunshine.",
                "first_name": "feli",
                "last_name": "twan",
                "avatar_url": "http://s3.amazonaws.com/fabletest/937ypvlchrd2e5z1a0sq",
                "is_active": true,
                "is_superuser": false,
                "is_staff": false,
                "last_login": 1295410796.0,
                "location": "San Francisco",
                "fullname": "twan Chan",
                "id": 1,
                "date_joined": 1293678904.0
            }
        },
        {
            "body": "asdasdf",
            "created_at": 1295345253.0,
            "user": {
                "username": "swnn",
                "bio": "I'm the CEO at Twitter.  Prior to Twitter, I cofounded FeedBurner (acquired by Google). I'm an investor and Advisor in a few start-ups including about.me.\r\n \r\nI used to perform with Chicago\u2019s Annoyance Theater and at various comedy festivals in Edinburgh, Montreal and other distant lands. I recently left the cold winters of Chicago for Marin County's sunshine.",
                "first_name": "feli",
                "last_name": "twan",
                "avatar_url": "http://s3.amazonaws.com/fabletest/937ypvlchrd2e5z1a0sq",
                "is_active": true,
                "is_superuser": false,
                "is_staff": false,
                "last_login": 1295410796.0,
                "location": "San Francisco",
                "fullname": "twan Chan",
                "id": 1,
                "date_joined": 1293678904.0
            }
        },
        {
            "body": "sdfasdfasd",
            "created_at": 1295345279.0,
            "user": {
                "username": "swnn",
                "bio": "I'm the CEO at Twitter.  Prior to Twitter, I cofounded FeedBurner (acquired by Google). I'm an investor and Advisor in a few start-ups including about.me.\r\n \r\nI used to perform with Chicago\u2019s Annoyance Theater and at various comedy festivals in Edinburgh, Montreal and other distant lands. I recently left the cold winters of Chicago for Marin County's sunshine.",
                "first_name": "feli",
                "last_name": "twan",
                "avatar_url": "http://s3.amazonaws.com/fabletest/937ypvlchrd2e5z1a0sq",
                "is_active": true,
                "is_superuser": false,
                "is_staff": false,
                "last_login": 1295410796.0,
                "location": "San Francisco",
                "fullname": "twan Chan",
                "id": 1,
                "date_joined": 1293678904.0
            }
        },
        {
            "body": "asdfasdf",
            "created_at": 1295345358.0,
            "user": {
                "username": "swnn",
                "bio": "I'm the CEO at Twitter.  Prior to Twitter, I cofounded FeedBurner (acquired by Google). I'm an investor and Advisor in a few start-ups including about.me.\r\n \r\nI used to perform with Chicago\u2019s Annoyance Theater and at various comedy festivals in Edinburgh, Montreal and other distant lands. I recently left the cold winters of Chicago for Marin County's sunshine.",
                "first_name": "feli",
                "last_name": "twan",
                "avatar_url": "http://s3.amazonaws.com/fabletest/937ypvlchrd2e5z1a0sq",
                "is_active": true,
                "is_superuser": false,
                "is_staff": false,
                "last_login": 1295410796.0,
                "location": "San Francisco",
                "fullname": "twan Chan",
                "id": 1,
                "date_joined": 1293678904.0
            }
        },
        {
            "body": "foxed",
            "created_at": 1295345790.0,
            "user": {
                "username": "swnn",
                "bio": "I'm the CEO at Twitter.  Prior to Twitter, I cofounded FeedBurner (acquired by Google). I'm an investor and Advisor in a few start-ups including about.me.\r\n \r\nI used to perform with Chicago\u2019s Annoyance Theater and at various comedy festivals in Edinburgh, Montreal and other distant lands. I recently left the cold winters of Chicago for Marin County's sunshine.",
                "first_name": "feli",
                "last_name": "twan",
                "avatar_url": "http://s3.amazonaws.com/fabletest/937ypvlchrd2e5z1a0sq",
                "is_active": true,
                "is_superuser": false,
                "is_staff": false,
                "last_login": 1295410796.0,
                "location": "San Francisco",
                "fullname": "twan Chan",
                "id": 1,
                "date_joined": 1293678904.0
            }
        },
        {
            "body": "Is this really the right thing? I mean...after thinking about it. ist's just not very cool",
            "created_at": 1295345827.0,
            "user": {
                "username": "swnn",
                "bio": "I'm the CEO at Twitter.  Prior to Twitter, I cofounded FeedBurner (acquired by Google). I'm an investor and Advisor in a few start-ups including about.me.\r\n \r\nI used to perform with Chicago\u2019s Annoyance Theater and at various comedy festivals in Edinburgh, Montreal and other distant lands. I recently left the cold winters of Chicago for Marin County's sunshine.",
                "first_name": "feli",
                "last_name": "twan",
                "avatar_url": "http://s3.amazonaws.com/fabletest/937ypvlchrd2e5z1a0sq",
                "is_active": true,
                "is_superuser": false,
                "is_staff": false,
                "last_login": 1295410796.0,
                "location": "San Francisco",
                "fullname": "twan Chan",
                "id": 1,
                "date_joined": 1293678904.0
            }
        },
        {
            "body": "s this really the right thing? I mean...after thinking about it. ist's just not very cool",
            "created_at": 1295345871.0,
            "user": {
                "username": "swnn",
                "bio": "I'm the CEO at Twitter.  Prior to Twitter, I cofounded FeedBurner (acquired by Google). I'm an investor and Advisor in a few start-ups including about.me.\r\n \r\nI used to perform with Chicago\u2019s Annoyance Theater and at various comedy festivals in Edinburgh, Montreal and other distant lands. I recently left the cold winters of Chicago for Marin County's sunshine.",
                "first_name": "feli",
                "last_name": "twan",
                "avatar_url": "http://s3.amazonaws.com/fabletest/937ypvlchrd2e5z1a0sq",
                "is_active": true,
                "is_superuser": false,
                "is_staff": false,
                "last_login": 1295410796.0,
                "location": "San Francisco",
                "fullname": "twan Chan",
                "id": 1,
                "date_joined": 1293678904.0
            }
        },
        {
            "body": "his song really suck.s",
            "created_at": 1295346108.0,
            "user": {
                "username": "swnn",
                "bio": "I'm the CEO at Twitter.  Prior to Twitter, I cofounded FeedBurner (acquired by Google). I'm an investor and Advisor in a few start-ups including about.me.\r\n \r\nI used to perform with Chicago\u2019s Annoyance Theater and at various comedy festivals in Edinburgh, Montreal and other distant lands. I recently left the cold winters of Chicago for Marin County's sunshine.",
                "first_name": "feli",
                "last_name": "twan",
                "avatar_url": "http://s3.amazonaws.com/fabletest/937ypvlchrd2e5z1a0sq",
                "is_active": true,
                "is_superuser": false,
                "is_staff": false,
                "last_login": 1295410796.0,
                "location": "San Francisco",
                "fullname": "twan Chan",
                "id": 1,
                "date_joined": 1293678904.0
            }
        },
        {
            "body": "asdfasdf",
            "created_at": 1295383689.0,
            "user": {
                "username": "swnn",
                "bio": "I'm the CEO at Twitter.  Prior to Twitter, I cofounded FeedBurner (acquired by Google). I'm an investor and Advisor in a few start-ups including about.me.\r\n \r\nI used to perform with Chicago\u2019s Annoyance Theater and at various comedy festivals in Edinburgh, Montreal and other distant lands. I recently left the cold winters of Chicago for Marin County's sunshine.",
                "first_name": "feli",
                "last_name": "twan",
                "avatar_url": "http://s3.amazonaws.com/fabletest/937ypvlchrd2e5z1a0sq",
                "is_active": true,
                "is_superuser": false,
                "is_staff": false,
                "last_login": 1295410796.0,
                "location": "San Francisco",
                "fullname": "twan Chan",
                "id": 1,
                "date_joined": 1293678904.0
            }
        },
        {
            "body": "asdfasdf",
            "created_at": 1295410874.0,
            "user": {
                "username": "swnn",
                "bio": "I'm the CEO at Twitter.  Prior to Twitter, I cofounded FeedBurner (acquired by Google). I'm an investor and Advisor in a few start-ups including about.me.\r\n \r\nI used to perform with Chicago\u2019s Annoyance Theater and at various comedy festivals in Edinburgh, Montreal and other distant lands. I recently left the cold winters of Chicago for Marin County's sunshine.",
                "first_name": "feli",
                "last_name": "twan",
                "avatar_url": "http://s3.amazonaws.com/fabletest/937ypvlchrd2e5z1a0sq",
                "is_active": true,
                "is_superuser": false,
                "is_staff": false,
                "last_login": 1295410796.0,
                "location": "San Francisco",
                "fullname": "twan Chan",
                "id": 1,
                "date_joined": 1293678904.0
            }
        },
        {
            "body": "Is this all right?",
            "created_at": 1295411376.0,
            "user": {
                "username": "swnn",
                "bio": "I'm the CEO at Twitter.  Prior to Twitter, I cofounded FeedBurner (acquired by Google). I'm an investor and Advisor in a few start-ups including about.me.\r\n \r\nI used to perform with Chicago\u2019s Annoyance Theater and at various comedy festivals in Edinburgh, Montreal and other distant lands. I recently left the cold winters of Chicago for Marin County's sunshine.",
                "first_name": "feli",
                "last_name": "twan",
                "avatar_url": "http://s3.amazonaws.com/fabletest/937ypvlchrd2e5z1a0sq",
                "is_active": true,
                "is_superuser": false,
                "is_staff": false,
                "last_login": 1295410796.0,
                "location": "San Francisco",
                "fullname": "twan Chan",
                "id": 1,
                "date_joined": 1293678904.0
            }
        }
    ],
    "initial_vote": 0,
    "browser_lat": 37.848800659179688,
    "post": {
        "ip": "174.129.251.48",
        "thumb_500x500": {
            "url": "http://s3.amazonaws.com/fabletest/bv2814ghmd",
            "width": 500,
            "height": 351
        },
        "date": 1295154531.334044,
        "thumb_original": {
            "url": "http://farm6.static.flickr.com/5249/5336976806_481943d486_b.jpg",
            "width": 779,
            "height": 548
        },
        "total_views": 227,
        "thumb_230x480": {
            "url": "http://s3.amazonaws.com/fabletest/4e7h95rt3f",
            "width": 230,
            "height": 480
        },
        "test_set": "g2",
        "title": "Maybe. . .we were supposed to meet the wrong people before meeting the right one so that, when we finally meet the right person, we will know how to be grateful for that gift ...",
        "stamp": "bf305695ca51b5390dc0c2f34c074215",
        "pop_score": 241.59687499999995,
        "thumb_640x640": {
            "url": "http://s3.amazonaws.com/fabletest/4q15bsgmt2",
            "width": 640,
            "height": 450
        },
        "image_direction": "landscape",
        "author_username": "swnn",
        "thumb_230x230": {
            "url": "http://s3.amazonaws.com/fabletest/x0dq7gzb4f",
            "width": 230,
            "height": 230
        },
        "description": "sooc with Shana Rae overlay ....",
        "top_score": 0.90000000000000002,
        "active": true,
        "original_file": "http://farm6.static.flickr.com/5249/5336976806_481943d486_b.jpg",
        "loc_utm": [
            500000.0,
            6317527.4506855672
        ],
        "_id": {
            "$oid": "4d327d658aad6919be0000d5"
        },
        "sizes": [
            {
                "url": "http://farm6.static.flickr.com/5249/5336976806_481943d486_b.jpg",
                "width": 779,
                "height": 548
            },
            {
                "url": "http://s3.amazonaws.com/fabletest/4q15bsgmt2",
                "width": 640,
                "height": 450
            },
            {
                "url": "http://s3.amazonaws.com/fabletest/bv2814ghmd",
                "width": 500,
                "height": 351
            },
            {
                "url": "http://s3.amazonaws.com/fabletest/x0dq7gzb4f",
                "width": 230,
                "height": 230
            },
            {
                "url": "http://s3.amazonaws.com/fabletest/4e7h95rt3f",
                "width": 230,
                "height": 480
            },
            {
                "url": "http://s3.amazonaws.com/fabletest/g1pmqk7r6y",
                "width": 480,
                "height": 230
            }
        ],
        "loc_latlong": [
            57.0,
            -99.0
        ],
        "thumb_480x230": {
            "url": "http://s3.amazonaws.com/fabletest/g1pmqk7r6y",
            "width": 480,
            "height": 230
        },
        "processed": true,
        "author_id": 1,
        "content_id": 13259,
        "thumb_500x500_low": {
            "url": "http://s3.amazonaws.com/fabletest/oznumyqve7",
            "width": 500,
            "quality": 4,
            "height": 351
        }
    },
    "browser_long": -122.53489685058594,
    "pos_votes_count": 0
}

Body:
You have to do:

var params = JSON.parse('{{ all_params_in_json|escapejs }}');

Otherwise e.g ' char inside all_params_in_json variable terminates string and all hell breaks loose.


来源: stackexchange

问:
Using lambda to create a new variable in Pandas
if I want to do the following in Pandas, how do I do it using Lambda:

```<code>df['c'] = 0
df['c'][(df['a']==1) | (df['b'] ==1)] = 1
</code>```

Thanks

答:
I can't justify using a lambda

```<code>df.assign(c=df[['a', 'b']].eq(1).any(1).astype(int))
</code>```

But if you insist:

```<code>df.assign(c=lambda d: d[['a', 'b']].eq(1).any(1).astype(int))
</code>```

ContentLicense: CC BY-SA 3.0

Body:
if I want to do the following in Pandas, how do I do it using Lambda:

df['c'] = 0
df['c'][(df['a']==1) | (df['b'] ==1)] = 1

Thanks

Body:
I can't justify using a lambda

df.assign(c=df[['a', 'b']].eq(1).any(1).astype(int))

But if you insist:

df.assign(c=lambda d: d[['a', 'b']].eq(1).any(1).astype(int))


问:
android:gravity="top" doesn't align child view to top, but "center" aligns to center?
```<code><LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical" >

<LinearLayout
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_gravity="center"
    android:gravity="top"   <!--this line-->
    android:orientation="horizontal" >

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="0"
        android:textSize="56dp" />

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="0"
        android:textSize="36dp" />
</LinearLayout>
</code>```

Shouldn't that make the smaller "0" t-view align to the top of the inner LinearLayout?
Since the other "0" is larger in height, it increases the overall height of the inner LinearLayout.

Alternatively, if you included this:

```<code>android:layout_gravity="top"
</code>```

within the t-view of the smaller 0, it also does nothing.
Why is this?
Does the wrap_content of the LinearLayout wrap each individual view independent of others?
If so, then why does setting gravity to "center" work? In the sense that the smaller zero is vertically centered to its parent.

I know you can just set the smaller 0's height to match parent and set its own gravity to top. I'm just trying to understand this. Thanks.

答: You can use android:layout_weight="10" and distribute on the other components.

Body:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical" >

<LinearLayout
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_gravity="center"
    android:gravity="top"
    android:orientation="horizontal" >

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="0"
        android:textSize="56dp" />

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="0"
        android:textSize="36dp" />
</LinearLayout>

Shouldn't that make the smaller "0" t-view align to the top of the inner LinearLayout?
Since the other "0" is larger in height, it increases the overall height of the inner LinearLayout.

Alternatively, if you included this:

android:layout_gravity="top"

within the t-view of the smaller 0, it also does nothing.
Why is this?
Does the wrap_content of the LinearLayout wrap each individual view independent of others?
If so, then why does setting gravity to "center" work? In the sense that the smaller zero is vertically centered to its parent.

I know you can just set the smaller 0's height to match parent and set its own gravity to top. I'm just trying to understand this. Thanks.


问:
How to predict input image using trained model in Keras?
I trained a model to classify images from 2 classes and saved it using model.save(). Here is the code I used:

```<code>from keras.preprocessing.image import ImageDataGenerator
from keras.models import Sequential
from keras.layers import Conv2D, MaxPooling2D
from keras.layers import Activation, Dropout, Flatten, Dense
from keras import backend as K

# dimensions of our images.
img_width, img_height = 320, 240

train_data_dir = 'data/train'
validation_data_dir = 'data/validation'
nb_train_samples = 200  #total
nb_validation_samples = 10  # total
epochs = 6
batch_size = 10

if K.image_data_format() == 'channels_first':
    input_shape = (3, img_width, img_height)
else:
    input_shape = (img_width, img_height, 3)

model = Sequential()
model.add(Conv2D(32, (3, 3), input_shape=input_shape))
model.add(Activation('relu'))
model.add(MaxPooling2D(pool_size=(2, 2)))

model.add(Conv2D(32, (3, 3)))
model.add(Activation('relu'))
model.add(MaxPooling2D(pool_size=(2, 2)))

model.add(Conv2D(64, (3, 3)))
model.add(Activation('relu'))
model.add(MaxPooling2D(pool_size=(2, 2)))

model.add(Flatten())
model.add(Dense(64))
model.add(Activation('relu'))
model.add(Dropout(0.5))
model.add(Dense(1))
model.add(Activation('sigmoid'))

model.compile(loss='binary_crossentropy',
              optimizer='rmsprop',
              metrics=['accuracy'])

# this is the augmentation configuration we will use for training
train_datagen = ImageDataGenerator(
    rescale=1. / 255,
    shear_range=0.2,
    zoom_range=0.2,
    horizontal_flip=True)

# this is the augmentation configuration we will use for testing:
# only rescaling
test_datagen = ImageDataGenerator(rescale=1. / 255)

train_generator = train_datagen.flow_from_directory(
    train_data_dir,
    target_size=(img_width, img_height),
    batch_size=batch_size,
    class_mode='binary')

validation_generator = test_datagen.flow_from_directory(
    validation_data_dir,
    target_size=(img_width, img_height),
    batch_size=batch_size,
    class_mode='binary')

model.fit_generator(
    train_generator,
    steps_per_epoch=nb_train_samples // batch_size,
    epochs=epochs,
    validation_data=validation_generator,
    validation_steps=5)

model.save('model.h5')
</code>```

It successfully trained with 0.98 accuracy which is pretty good. To load and test this model on new images, I used the below code:

```<code>from keras.models import load_model
import cv2
import numpy as np

model = load_model('model.h5')

model.compile(loss='binary_crossentropy',
              optimizer='rmsprop',
              metrics=['accuracy'])

img = cv2.imread('test.jpg')
img = cv2.resize(img,(320,240))
img = np.reshape(img,[1,320,240,3])

classes = model.predict_classes(img)

print classes
</code>```

It outputs:

[[0]]

Why wouldn't it give out the actual name of the class and why [[0]]?

答:
You can use model.predict() to predict the class of a single image as follows [doc]:

```<code># load_model_sample.py
from keras.models import load_model
from keras.preprocessing import image
import matplotlib.pyplot as plt
import numpy as np
import os

def load_image(img_path, show=False):

    img = image.load_img(img_path, target_size=(150, 150))
    img_tensor = image.img_to_array(img)                    # (height, width, channels)
    img_tensor = np.expand_dims(img_tensor, axis=0)         # (1, height, width, channels), add a dimension because the model expects this shape: (batch_size, height, width, channels)
    img_tensor /= 255.                                      # imshow expects values in the range [0, 1]

    if show:
        plt.imshow(img_tensor[0])
        plt.axis('off')
        plt.show()

    return img_tensor

if __name__ == "__main__":

    # load model
    model = load_model("model_aug.h5")

    # image path
    img_path = '/media/data/dogscats/test1/3867.jpg'    # dog
    #img_path = '/media/data/dogscats/test1/19.jpg'      # cat

    # load a single image
    new_image = load_image(img_path)

    # check prediction
    pred = model.predict(new_image)
</code>```

In this example, a image is loaded as a numpy array with shape (1, height, width, channels). Then, we load it into the model and predict its class, returned as a real value in the range [0, 1] (binary classification in this example).

ContentLicense: CC BY-SA 4.0

Body:
I trained a model to classify images from 2 classes and saved it using model.save(). Here is the code I used:

from keras.preprocessing.image import ImageDataGenerator
from keras.models import Sequential
from keras.layers import Conv2D, MaxPooling2D
from keras.layers import Activation, Dropout, Flatten, Dense
from keras import backend as K

# dimensions of our images.
img_width, img_height = 320, 240

train_data_dir = 'data/train'
validation_data_dir = 'data/validation'
nb_train_samples = 200  #total
nb_validation_samples = 10  # total
epochs = 6
batch_size = 10

if K.image_data_format() == 'channels_first':
    input_shape = (3, img_width, img_height)
else:
    input_shape = (img_width, img_height, 3)

model = Sequential()
model.add(Conv2D(32, (3, 3), input_shape=input_shape))
model.add(Activation('relu'))
model.add(MaxPooling2D(pool_size=(2, 2)))

model.add(Conv2D(32, (3, 3)))
model.add(Activation('relu'))
model.add(MaxPooling2D(pool_size=(2, 2)))

model.add(Conv2D(64, (3, 3)))
model.add(Activation('relu'))
model.add(MaxPooling2D(pool_size=(2, 2)))

model.add(Flatten())
model.add(Dense(64))
model.add(Activation('relu'))
model.add(Dropout(0.5))
model.add(Dense(1))
model.add(Activation('sigmoid'))

model.compile(loss='binary_crossentropy',
              optimizer='rmsprop',
              metrics=['accuracy'])

# this is the augmentation configuration we will use for training
train_datagen = ImageDataGenerator(
    rescale=1. / 255,
    shear_range=0.2,
    zoom_range=0.2,
    horizontal_flip=True)

# this is the augmentation configuration we will use for testing:
# only rescaling
test_datagen = ImageDataGenerator(rescale=1. / 255)

train_generator = train_datagen.flow_from_directory(
    train_data_dir,
    target_size=(img_width, img_height),
    batch_size=batch_size,
    class_mode='binary')

validation_generator = test_datagen.flow_from_directory(
    validation_data_dir,
    target_size=(img_width, img_height),
    batch_size=batch_size,
    class_mode='binary')

model.fit_generator(
    train_generator,
    steps_per_epoch=nb_train_samples // batch_size,
    epochs=epochs,
    validation_data=validation_generator,
    validation_steps=5)

model.save('model.h5')

It successfully trained with 0.98 accuracy which is pretty good. To load and test this model on new images, I used the below code:

from keras.models import load_model
import cv2
import numpy as np

model = load_model('model.h5')

model.compile(loss='binary_crossentropy',
              optimizer='rmsprop',
              metrics=['accuracy'])

img = cv2.imread('test.jpg')
img = cv2.resize(img,(320,240))
img = np.reshape(img,[1,320,240,3])

classes = model.predict_classes(img)

print classes

It outputs:

[[0]]

Why wouldn't it give out the actual name of the class and why [[0]]?

Body:
You can use model.predict() to predict the class of a single image as follows [doc]:

# load_model_sample.py
from keras.models import load_model
from keras.preprocessing import image
import matplotlib.pyplot as plt
import numpy as np
import os

def load_image(img_path, show=False):

    img = image.load_img(img_path, target_size=(150, 150))
    img_tensor = image.img_to_array(img)                    # (height, width, channels)
    img_tensor = np.expand_dims(img_tensor, axis=0)         # (1, height, width, channels), add a dimension because the model expects this shape: (batch_size, height, width, channels)
    img_tensor /= 255.                                      # imshow expects values in the range [0, 1]

    if show:
        plt.imshow(img_tensor[0])
        plt.axis('off')
        plt.show()

    return img_tensor

if __name__ == "__main__":

    # load model
    model = load_model("model_aug.h5")

    # image path
    img_path = '/media/data/dogscats/test1/3867.jpg'    # dog
    #img_path = '/media/data/dogscats/test1/19.jpg'      # cat

    # load a single image
    new_image = load_image(img_path)

    # check prediction
    pred = model.predict(new_image)

In this example, a image is loaded as a numpy array with shape (1, height, width, channels). Then, we load it into the model and predict its class, returned as a real value in the range [0, 1] (binary classification in this example).


问:
Importing python file into my pycharm that is in the same directory
Im trying to import a python file into my pycharm program.

The file is in the exact same folder as my pycharm project is.
I tried to use :

```<code>open("happy_histogram.py","r",encoding="utf-8")
</code>```

but it fails to work.

Appreciate your help!

答:
What are you importing the file for? If you're trying to use some functions and other variables in happy_histogram.py you maybe be better importing it using

from happy_histogram import *

But to make your code work, I was able to open a file by taking out the encoding. open("happy_histogram.py", "r")  hope that helps.

Body:
Im trying to import a python file into my pycharm program.

The file is in the exact same folder as my pycharm project is.
I tried to use :

open("happy_histogram.py","r",encoding="utf-8")

but it fails to work.

Appreciate your help!


问:
HTTP/2 results in 404 for images and fonts
What I did: I tweaked a Wordpress website so it will load within 2.3 seconds instead of the former 5 seconds. As a final step, I enabled HTTP/2 in the LAMP server (PHP7.0, Apache 2.4) and restarted Apache.

Issues: On doing this, the Time to First Byte jumped from 500ms to 9 seconds and the website PNG and JPEG images in the Speed Load Test (GTmetrix and Webpagetest.org) are now resulting in 404. Please, see screenshot here https://www.diigo.com/item/image/5pj5q/vt0g

Overall, the Speed Load Test is showing me that the website is loading at 20-30 seconds, instead of the former 2.3 seconds.

I am at a loss about how to solve those two issues caused by HTTP/2. Any advice is welcome.

答:
I may have found the answer. It has to do with SSL Certs. At least for my situation. I use WHM/CPanel and the SSL certs get shared. HTTP2 detects that and sends a 421 error.

From Apache : https://httpd.apache.org/docs/2.4/mod/mod_http2.html

Multiple Hosts and Misdirected Requests

Many sites use the same TLS certificate for multiple virtual hosts.
  The certificate either has a wildcard name, such as '*.example.org' or
  carries several alternate names. Browsers using HTTP/2 will recognize
  that and reuse an already opened connection for such hosts.

While this is great for performance, it comes at a price: such vhosts
  need more care in their configuration. The problem is that you will
  have multiple requests for multiple hosts on the same TLS connection.
  And that makes renegotiation impossible, in face the HTTP/2 standard
  forbids it.

So, if you have several virtual hosts using the same certificate and
  want to use HTTP/2 for them, you need to make sure that all vhosts
  have exactly the same SSL configuration. You need the same protocol,
  ciphers and settings for client verification.

If you mix things, Apache httpd will detect it and return a special
  response code, 421 Misdirected Request, to the client.

I disabled http2 and the 404/421 errors stopped.


问:
GStreamer and Swift
I'm trying to add GStreamer to an existing project written in Swift. I have downloaded the tutorials which are in Objective-C. I have added the file I need into the bridging header, matched all the header search paths, framework search paths,  and  and linked all of library binaries that are in the example project.

However, I am unable to locate or add the GStreamer.framework

The GStreamer code is included in the project when it compiles, I know this because it triggers an enormous amount syntax warnings.

However, the code in the one class I added from the tutorials throws the error:

```<code>Undefined symbols for architecture x86_64:
  "_gst_version_string", referenced from:
      -[GStreamerBackend getGStreamerVersion] in GStreamerBackend.o
  "_g_free", referenced from:
      -[GStreamerBackend getGStreamerVersion] in GStreamerBackend.o
ld: symbol(s) not found for architecture x86_64
clang: error: linker command failed with exit code 1 (use -v to see invocation)
</code>```

答: try to add as Embedded Binaries.</p>

Title: GStreamer and Swift

Body:
I'm trying to add GStreamer to an existing project written in Swift. I have downloaded the tutorials which are in Objective-C. I have added the file I need into the bridging header, matched all the header search paths, framework search paths,  and  and linked all of library binaries that are in the example project.

However, I am unable to locate or add the GStreamer.framework

The GStreamer code is included in the project when it compiles, I know this because it triggers an enormous amount syntax warnings.

However, the code in the one class I added from the tutorials throws the error:

Undefined symbols for architecture x86_64:
  "_gst_version_string", referenced from:
      -[GStreamerBackend getGStreamerVersion] in GStreamerBackend.o
  "_g_free", referenced from:
      -[GStreamerBackend getGStreamerVersion] in GStreamerBackend.o
ld: symbol(s) not found for architecture x86_64
clang: error: linker command failed with exit code 1 (use -v to see invocation)

Body: try to add as Embedded Binaries.


问:
Sorting array according to string dates in a complex filename
I have a set of strings:

20120160323001.z1.xml

     20120160324001.z1.xml

     20120160322001.z1.xml

# The file format is XXXYYYYMMDDVVV.z1.xml where XXX is a

     # medical code, YYYYMMDD is a date and VVV is a document

     # version number

I want to sort the strings according to the date in descending order. So, the above strings after sorting will be:

20120160324001.z1.xml

     20120160323001.z1.xml

     20120160322001.z1.xml

I know how to sort arrays in Perl but given the complex file name I'm confused how I can sort these strings by date? Is it possible?

```<code># The below sort function is not going to work for these filenames
sub rev_by_date  {
    $b->[9+1] <=> $a->[9+1]
}

my @sorted_files = sort rev_by_date @files;
</code>```

Edit I use this regular expression to find these files: (?^:^201.*.z1.xml) but its not that useful for the date sorting function. In the date sorting function I dont know if comparing date strings will even work?

答:
Try

```<code>sort { substr($b, 3) cmp substr($a, 3) } @files;
</code>```

This assumes @files contains strings. If it contains something else, you need to explain that.  It retains the document version at the end of the sort key, so this will break ties.

Body:
I have a set of strings:

20120160323001.z1.xml

     20120160324001.z1.xml

     20120160322001.z1.xml

# The file format is XXXYYYYMMDDVVV.z1.xml where XXX is a

     # medical code, YYYYMMDD is a date and VVV is a document

     # version number

I want to sort the strings according to the date in descending order. So, the above strings after sorting will be:

20120160324001.z1.xml

     20120160323001.z1.xml

     20120160322001.z1.xml

I know how to sort arrays in Perl but given the complex file name I'm confused how I can sort these strings by date? Is it possible?

# The below sort function is not going to work for these filenames
sub rev_by_date  {
    $b->[9+1] <=> $a->[9+1]
}

my @sorted_files = sort rev_by_date @files;

Edit I use this regular expression to find these files: (?^:^201.*.z1.xml) but its not that useful for the date sorting function. In the date sorting function I dont know if comparing date strings will even work?

Body:
Try

sort { substr($b, 3) cmp substr($a, 3) } @files;

This assumes @files contains strings. If it contains something else, you need to explain that.  It retains the document version at the end of the sort key, so this will break ties.


问:
Google Maps is grey
I am using google maps in a mobile application using html and javascript. When the I load the map I am only able to see 5% of the map in the upper left corner. 95% of the div container is grey.
When I want to check the div with Firebug the whole map is loaded suddenly.
What can that be?
I tried already several Stackoverflow threads but no solution worked for me.
Thank you.

Code:

```<code><link type="text/css" rel="stylesheet" href="jquery.mobile...>
<link type="text/css" rel="stylesheet" href="index.css">
<script type="text/javascript" src="jquery.mobile...></script>
<script type="text/javascript" src="jquery.mobile/jquery.mobile...></script>
<script type="text/javascript" charset="utf-8" src="cordova-2.1.0.js">       </script>
<script src="http://maps.google.com/maps/api/js?sensor=false" type="text/javascript"></script>
<script type="text/javascript" charset="utf-8" src="index.js"></script>

<div id="map" style="width: 700px; height: 700px;"></div>

var map = new google.maps.Map(document.getElementById('map'), {
       zoom: 10,
       center: new google.maps.LatLng(-33.92, 151.25),
       mapTypeId: google.maps.MapTypeId.ROADMAP
});
</code>```

index.js

```<code>$(document).ready(function() {
    $(window).resize(function() {
        google.maps.event.trigger(map, 'resize');
    });
});
</code>```

When I use div attributes measured in % or em it doesnt work at all.

答: In my case I had missed to provide the Longitude which came from an external API. Once the API was fixed to include Longitude, the issue was solved. </p>

Title: Google Maps is grey

Body:
I am using google maps in a mobile application using html and javascript. When the I load the map I am only able to see 5% of the map in the upper left corner. 95% of the div container is grey.
When I want to check the div with Firebug the whole map is loaded suddenly.
What can that be?
I tried already several Stackoverflow threads but no solution worked for me.
Thank you.

Code:

<link type="text/css" rel="stylesheet" href="jquery.mobile...>
<link type="text/css" rel="stylesheet" href="index.css">

var map = new google.maps.Map(document.getElementById('map'), {
       zoom: 10,
       center: new google.maps.LatLng(-33.92, 151.25),
       mapTypeId: google.maps.MapTypeId.ROADMAP
});

index.js

$(document).ready(function() {
    $(window).resize(function() {
        google.maps.event.trigger(map, 'resize');
    });
});

When I use div attributes measured in % or em it doesnt work at all.


问:
How to reduce log size for sqoop export
Is there a way to control the size of the logs created by sqoop export? Trying to export a series of parquet files from a hadoop cluster to microsoft sql server and finding that after a certain point in the mapper job, progress becomes very slow/freezes. Current theory from looking at the hadoop Resourcemanager is that the logs from the sqoop job are filling up to a size that causes the process to freeze.

New to hadoop and any advice would be appreciated. Thanks.

Update

Looking at the syslog output for one of the frozen map task jobs for the sqoop jar application from the resource manager web interface, the log output looks like:

```<code>2017-11-14 16:26:52,243 DEBUG [communication thread] org.apache.hadoop.yarn.util.ProcfsBasedProcessTree: [ 8758 8840 ]
2017-11-14 16:26:52,243 DEBUG [IPC Client (<ipc_client_num>) connection to /<myipaddress>:23716 from job_1502069985038_3490] org.apache.hadoop.security.SaslRpcClient: reading next wrapped RPC packet
2017-11-14 16:26:52,243 DEBUG [IPC Parameter Sending Thread #0] org.apache.hadoop.ipc.Client: IPC Client (<ipc_client_num>) connection to /<myipaddress>:23716 from job_1502069985038_3490 sending #280
2017-11-14 16:26:52,243 DEBUG [IPC Parameter Sending Thread #0] org.apache.hadoop.security.SaslRpcClient: wrapping token of length:751
2017-11-14 16:26:52,246 DEBUG [IPC Client (<ipc_client_num>) connection to /<myipaddress>:23716 from job_1502069985038_3490] org.apache.hadoop.security.SaslRpcClient: unwrapping token of length:62
2017-11-14 16:26:52,246 DEBUG [IPC Client (<ipc_client_num>) connection to /<myipaddress>:23716 from job_1502069985038_3490] org.apache.hadoop.ipc.Client: IPC Client (<ipc_client_num>) connection to /<myipaddress>:23716 from job_1502069985038_3490 got value #280
2017-11-14 16:26:52,246 DEBUG [communication thread] org.apache.hadoop.ipc.RPC: Call: statusUpdate 3
2017-11-14 16:26:55,252 DEBUG [communication thread] org.apache.hadoop.yarn.util.ProcfsBasedProcessTree: [ 8758 8840 ]
2017-11-14 16:26:55,252 DEBUG [IPC Client (<ipc_client_num>) connection to /<myipaddress>:23716 from job_1502069985038_3490] org.apache.hadoop.security.SaslRpcClient: reading next wrapped RPC packet
2017-11-14 16:26:55,252 DEBUG [IPC Parameter Sending Thread #0] org.apache.hadoop.ipc.Client: IPC Client (<ipc_client_num>) connection to /<myipaddress>:23716 from job_1502069985038_3490 sending #281
2017-11-14 16:26:55,252 DEBUG [IPC Parameter Sending Thread #0] org.apache.hadoop.security.SaslRpcClient: wrapping token of length:751
2017-11-14 16:26:55,254 DEBUG [IPC Client (<ipc_client_num>) connection to /<myipaddress>:23716 from job_1502069985038_3490] org.apache.hadoop.security.SaslRpcClient: unwrapping token of length:62
2017-11-14 16:26:55,255 DEBUG [IPC Client (<ipc_client_num>) connection to /<myipaddress>:23716 from job_1502069985038_3490] org.apache.hadoop.ipc.Client: IPC Client (<ipc_client_num>) connection to /<myipaddress>:23716 from job_1502069985038_3490 got value #281
2017-11-14 16:26:55,255 DEBUG [communication thread] org.apache.hadoop.ipc.RPC: Call: statusUpdate 3
</code>```

Furthermore, letting the process run throughout the day, it seems that the sqoop job does indeed finish, but takes a very long time (~4 hours for ~500MB of .tsv data).

答:
In response to the title of the posted question, the way to control the log output of the sqoop command is either by editing the log4j.properties file in the $HADOOP_HOME/etc/hadoop directory (since sqoop apparently uses this to inherit its log properties (though from what I can tell this may not be the case with sqoop2)) or by using generic arguments in the sqoop call with the -D prefix, eg:

```<code>sqoop export \
    -Dyarn.app.mapreduce.am.log.level=WARN\
    -Dmapreduce.map.log.level=WARN \
    -Dmapreduce.reduce.log.level=WARN \
    --connect "$connectionstring" \
    --driver com.microsoft.sqlserver.jdbc.SQLServerDriver \
    --table $tablename \
    --export-dir /tmp/${tablename^^}_export \
    --num-mappers 24 \
    --direct \
    --batch \
    --input-fields-terminated-by '\t'
</code>```

However, my initial theory from the body of the post, that the logs from the sqoop job were filling up to a size that caused the process to freeze, did not seem to hold up. The log sizes for the map tasks fell to 0 bytes in the resourcemanager ui, but the system still went through the flow of running well up to a certain percent then dropping to a very slow speed.

Title: How to reduce log size for sqoop export

Body:
Is there a way to control the size of the logs created by sqoop export? Trying to export a series of parquet files from a hadoop cluster to microsoft sql server and finding that after a certain point in the mapper job, progress becomes very slow/freezes. Current theory from looking at the hadoop Resourcemanager is that the logs from the sqoop job are filling up to a size that causes the process to freeze.

New to hadoop and any advice would be appreciated. Thanks.

Update

Looking at the syslog output for one of the frozen map task jobs for the sqoop jar application from the resource manager web interface, the log output looks like:

2017-11-14 16:26:52,243 DEBUG [communication thread] org.apache.hadoop.yarn.util.ProcfsBasedProcessTree: [ 8758 8840 ]
2017-11-14 16:26:52,243 DEBUG [IPC Client (<ipc_client_num>) connection to /<myipaddress>:23716 from job_1502069985038_3490] org.apache.hadoop.security.SaslRpcClient: reading next wrapped RPC packet
2017-11-14 16:26:52,243 DEBUG [IPC Parameter Sending Thread #0] org.apache.hadoop.ipc.Client: IPC Client (<ipc_client_num>) connection to /<myipaddress>:23716 from job_1502069985038_3490 sending #280
2017-11-14 16:26:52,243 DEBUG [IPC Parameter Sending Thread #0] org.apache.hadoop.security.SaslRpcClient: wrapping token of length:751
2017-11-14 16:26:52,246 DEBUG [IPC Client (<ipc_client_num>) connection to /<myipaddress>:23716 from job_1502069985038_3490] org.apache.hadoop.security.SaslRpcClient: unwrapping token of length:62
2017-11-14 16:26:52,246 DEBUG [IPC Client (<ipc_client_num>) connection to /<myipaddress>:23716 from job_1502069985038_3490] org.apache.hadoop.ipc.Client: IPC Client (<ipc_client_num>) connection to /<myipaddress>:23716 from job_1502069985038_3490 got value #280
2017-11-14 16:26:52,246 DEBUG [communication thread] org.apache.hadoop.ipc.RPC: Call: statusUpdate 3
2017-11-14 16:26:55,252 DEBUG [communication thread] org.apache.hadoop.yarn.util.ProcfsBasedProcessTree: [ 8758 8840 ]
2017-11-14 16:26:55,252 DEBUG [IPC Client (<ipc_client_num>) connection to /<myipaddress>:23716 from job_1502069985038_3490] org.apache.hadoop.security.SaslRpcClient: reading next wrapped RPC packet
2017-11-14 16:26:55,252 DEBUG [IPC Parameter Sending Thread #0] org.apache.hadoop.ipc.Client: IPC Client (<ipc_client_num>) connection to /<myipaddress>:23716 from job_1502069985038_3490 sending #281
2017-11-14 16:26:55,252 DEBUG [IPC Parameter Sending Thread #0] org.apache.hadoop.security.SaslRpcClient: wrapping token of length:751
2017-11-14 16:26:55,254 DEBUG [IPC Client (<ipc_client_num>) connection to /<myipaddress>:23716 from job_1502069985038_3490] org.apache.hadoop.security.SaslRpcClient: unwrapping token of length:62
2017-11-14 16:26:55,255 DEBUG [IPC Client (<ipc_client_num>) connection to /<myipaddress>:23716 from job_1502069985038_3490] org.apache.hadoop.ipc.Client: IPC Client (<ipc_client_num>) connection to /<myipaddress>:23716 from job_1502069985038_3490 got value #281
2017-11-14 16:26:55,255 DEBUG [communication thread] org.apache.hadoop.ipc.RPC: Call: statusUpdate 3

Furthermore, letting the process run throughout the day, it seems that the sqoop job does indeed finish, but takes a very long time (~4 hours for ~500MB of .tsv data).

Body:
In response to the title of the posted question, the way to control the log output of the sqoop command is either by editing the log4j.properties file in the $HADOOP_HOME/etc/hadoop directory (since sqoop apparently uses this to inherit its log properties (though from what I can tell this may not be the case with sqoop2)) or by using generic arguments in the sqoop call with the -D prefix, eg:

sqoop export \
    -Dyarn.app.mapreduce.am.log.level=WARN\
    -Dmapreduce.map.log.level=WARN \
    -Dmapreduce.reduce.log.level=WARN \
    --connect "$connectionstring" \
    --driver com.microsoft.sqlserver.jdbc.SQLServerDriver \
    --table $tablename \
    --export-dir /tmp/${tablename^^}_export \
    --num-mappers 24 \
    --direct \
    --batch \
    --input-fields-terminated-by '\t'

However, my initial theory from the body of the post, that the logs from the sqoop job were filling up to a size that caused the process to freeze, did not seem to hold up. The log sizes for the map tasks fell to 0 bytes in the resourcemanager ui, but the system still went through the flow of running well up to a certain percent then dropping to a very slow speed.


问:
scala observable unify observable with a sequence without intermediate datastructure update
I have a code which calls couchbase for getting some rows as following:

```<code>val gotValues: Observable[JsonDocument] = Observable.from(rowKeys).flatMap(id =>
      couchbaseBucket.async().get(id))
</code>```

If I have 1,2,3,4,5,6 as input row-keys and only rows 1,2,3 exist in the DB then the observable would get notified only about 1,2,3.

My requirement however is that I return a map with 1,2,3 true (exist in db) and 4,5,6 with false, (meaning not exist in DB).  I managed to do that with scala observable however i'm using an intermediate map data structure to return the total map which contains all ids.  Below is a sample code which simulates my problem..

```<code>object Main extends App {
  import rx.lang.scala.Observable

  val idsToFetch = Seq(1,2,3,4,5,6)

  println(isInDBOrNot()) // {1=true, 2=true, 3=true, 4=false, 5=false, 6=false}

  private def isInDBOrNot(): ConcurrentHashMap[Int, Boolean] = {
    val inAndNotInDB = new java.util.concurrent.ConcurrentHashMap[Int, Boolean]
    // - How can I avoid the additional data structure?
    // - In this case a map, so that the function will return
    //   a map with all numbers and for each if exist in DB?
    // - I mean I want the function to return a map I don't
    //   want to populate that map inside the observer,
    //   it's like a mini side effect I would rather simply
    //   manipulate the stream.

    Observable.from(idsToFetch)
      .filterNot(x => x == 4 || x == 5 || x == 6) // Simulate fetch from DB, 4,5,6 do not exist in DB, so not returned.
      .subscribe(
      x => inAndNotInDB.put(x, true),
      e => println(e),
      () => idsToFetch.filterNot(inAndNotInDB.containsKey)
        .foreach(inAndNotInDB.put(_, false)) // mark all non-found as false.
    )

    inAndNotInDB
  }

}
</code>```

Anyway to do that without the intermediate map (without populating an intermedia data structure, but only by manipulating the stream)? It does not look clean!! . Thanks.

答:
One way of doing this is the following:

(1) convert sequence of ids to Observable and map it with

```<code>id => (id, false)
</code>```

... so you'll get an observable of type Observable[(Int, Boolean)] (lets call this new observable first).

(2) fetch data from database and map every fetched row to from:

```<code>(some_id, true)
</code>```

... inside Observable[(Int, Boolean)] (lets call this observable last)

(3) concat first and last.

(4) toMap result of (3). Duplicate elements coming from first will be dropped in process. (this will be your resultObsrvable)

(5) (possibly) collect the first and only element of the observable (your map). You might not want to do this at all, but if you do, you should really understand implications of blocking to collect result at this point. In any case, this step really depends on your application specifics (how threading\scheduling\io is organized) but brute-force approach should look something like this (refer to this demo for more specifics):

```<code>Await.result(resultObsrvable.toBlocking.toFuture, 2 seconds)
</code>```

Body:
I have a code which calls couchbase for getting some rows as following:

val gotValues: Observable[JsonDocument] = Observable.from(rowKeys).flatMap(id =>
      couchbaseBucket.async().get(id))

If I have 1,2,3,4,5,6 as input row-keys and only rows 1,2,3 exist in the DB then the observable would get notified only about 1,2,3.

My requirement however is that I return a map with 1,2,3 true (exist in db) and 4,5,6 with false, (meaning not exist in DB).  I managed to do that with scala observable however i'm using an intermediate map data structure to return the total map which contains all ids.  Below is a sample code which simulates my problem..

object Main extends App {
  import rx.lang.scala.Observable

  val idsToFetch = Seq(1,2,3,4,5,6)

  println(isInDBOrNot()) // {1=true, 2=true, 3=true, 4=false, 5=false, 6=false}

  private def isInDBOrNot(): ConcurrentHashMap[Int, Boolean] = {
    val inAndNotInDB = new java.util.concurrent.ConcurrentHashMap[Int, Boolean]
    // - How can I avoid the additional data structure?
    // - In this case a map, so that the function will return
    //   a map with all numbers and for each if exist in DB?
    // - I mean I want the function to return a map I don't
    //   want to populate that map inside the observer,
    //   it's like a mini side effect I would rather simply
    //   manipulate the stream.

    Observable.from(idsToFetch)
      .filterNot(x => x == 4 || x == 5 || x == 6) // Simulate fetch from DB, 4,5,6 do not exist in DB, so not returned.
      .subscribe(
      x => inAndNotInDB.put(x, true),
      e => println(e),
      () => idsToFetch.filterNot(inAndNotInDB.containsKey)
        .foreach(inAndNotInDB.put(_, false)) // mark all non-found as false.
    )

    inAndNotInDB
  }

}

Anyway to do that without the intermediate map (without populating an intermedia data structure, but only by manipulating the stream)? It does not look clean!! . Thanks.

Body:
One way of doing this is the following:

(1) convert sequence of ids to Observable and map it with

id => (id, false)

... so you'll get an observable of type Observable[(Int, Boolean)] (lets call this new observable first).

(2) fetch data from database and map every fetched row to from:

(some_id, true)

... inside Observable[(Int, Boolean)] (lets call this observable last)

(3) concat first and last.

(4) toMap result of (3). Duplicate elements coming from first will be dropped in process. (this will be your resultObsrvable)

(5) (possibly) collect the first and only element of the observable (your map). You might not want to do this at all, but if you do, you should really understand implications of blocking to collect result at this point. In any case, this step really depends on your application specifics (how threading\scheduling\io is organized) but brute-force approach should look something like this (refer to this demo for more specifics):

Await.result(resultObsrvable.toBlocking.toFuture, 2 seconds)


问:
Python 3.5.1 IDLE keeps crashing on Mac OSX 10.11.4
I'm running IDLE with python 3.5.1 by python.org, but it keeps crashing.
The shell starts with
"WARNING: The version of Tcl/Tk (8.5.9) in use may be unstable.
Visit http://www.python.org/download/mac/tcltk/ for current information."
As recommended on that site I installed ActiveTcl 8.5.18.0, but that doesn't seem to have helped.
This message is relatively new, maybe since the OSX update to 10.11.4.

Any suggestions what might cause these crashes?
Thanks

@OSX 10.11.4 MacBook Air 13" 2013, i7, 8GB Ram

Update:

I called Idle via Terminal with python3 -m idlelib and then About Idle. It says Python and IDLE Version 3.5.1 an Tk Version 8.5.9.
I also noticed that when I click on README in the IDLE section, it prints an error on the terminal:

```<code>Exception in Tkinter callback
Traceback (most recent call last):
File"/Library/Frameworks/Python.framework/Versions/3.5/lib/python3.5/tkinter/__init__.py", line 1549, in __call__
return self.func(*args)
File  "/Library/Frameworks/Python.framework/Versions/3.5/lib/python3.5/idlelib/aboutDialog.py", line 127, in ShowIDLEAbout
self.display_file_text('About - Readme', 'README.txt')
File "/Library/Frameworks/Python.framework/Versions/3.5/lib/python3.5/idlelib/aboutDialog.py", line 139, in display_file_text
textView.view_file(self, title, fn, encoding)           File"/Library/Frameworks/Python.framework/Versions/3.5/lib/python3.5/idlelib/textView.py", line 74, in view_file
contents = file.read()
File "/Library/Frameworks/Python.framework/Versions/3.5/lib/python3.5/codecs.py", line 321, in decode
(result, consumed) = self._buffer_decode(data, self.errors, final)
UnicodeDecodeError: 'utf-8' codec can't decode byte 0x92 in position 72: invalid start byte
</code>```

答:
For me, 90% of IDLE crashes were caused by typing a left-parenthesis — very annoying.
In IDLE, you can fix it by:

```<code>Options Menu > Configure Extensions > CallTips > set to FALSE
</code>```

Then restart.

Body:
I'm running IDLE with python 3.5.1 by python.org, but it keeps crashing.
The shell starts with
"WARNING: The version of Tcl/Tk (8.5.9) in use may be unstable.
Visit http://www.python.org/download/mac/tcltk/ for current information."
As recommended on that site I installed ActiveTcl 8.5.18.0, but that doesn't seem to have helped.
This message is relatively new, maybe since the OSX update to 10.11.4.

Any suggestions what might cause these crashes?
Thanks

@OSX 10.11.4 MacBook Air 13" 2013, i7, 8GB Ram

Update:

I called Idle via Terminal with python3 -m idlelib and then About Idle. It says Python and IDLE Version 3.5.1 an Tk Version 8.5.9.
I also noticed that when I click on README in the IDLE section, it prints an error on the terminal:

Exception in Tkinter callback
Traceback (most recent call last):
File"/Library/Frameworks/Python.framework/Versions/3.5/lib/python3.5/tkinter/__init__.py", line 1549, in __call__
return self.func(*args)
File  "/Library/Frameworks/Python.framework/Versions/3.5/lib/python3.5/idlelib/aboutDialog.py", line 127, in ShowIDLEAbout
self.display_file_text('About - Readme', 'README.txt')
File "/Library/Frameworks/Python.framework/Versions/3.5/lib/python3.5/idlelib/aboutDialog.py", line 139, in display_file_text
textView.view_file(self, title, fn, encoding)           File"/Library/Frameworks/Python.framework/Versions/3.5/lib/python3.5/idlelib/textView.py", line 74, in view_file
contents = file.read()
File "/Library/Frameworks/Python.framework/Versions/3.5/lib/python3.5/codecs.py", line 321, in decode
(result, consumed) = self._buffer_decode(data, self.errors, final)
UnicodeDecodeError: 'utf-8' codec can't decode byte 0x92 in position 72: invalid start byte

Body:
For me, 90% of IDLE crashes were caused by typing a left-parenthesis — very annoying.
In IDLE, you can fix it by:

Options Menu > Configure Extensions > CallTips > set to FALSE

Then restart.


问:
Is there anyway to run iOS or Android code on a desktop application?
I would like to use an iOS or Android SDK (e.g. DJI Drone SDK), but instead of running it on a mobile device to connect to the hardware, is there a way to build a desktop application (e.g. Electron based) and be able to run their SDK to interact with the hardware?

答:
On Windows you can use Android Studio for run apps to Android .APK
Download it now https://developer.android.com/studio/index.html
Don't forget you need to know Java language to using Android Studio you can learn watch some tutorials on Youtube

On Mac you need to use Xcode
You can't run IOS Mac apps on Windows you can it with Virtual Machine like Vmware.
It's Xcode for download
https://developer.apple.com/xcode/
Don't forget you need to know Swift language to make an app on Mac for Mac and IOS


答:
You want to sort by the substrings matching the date part:

```<code>sub rev_by_date {
  substr($b, 3, 8) <=> substr($a, 3, 8);
}

my @sorted_files = sort rev_by_date @files;
</code>```

...as long as the filenames match the format that you've described.

Title: Sorting array according to string dates in a complex filename

Body:
You want to sort by the substrings matching the date part:

sub rev_by_date {
  substr($b, 3, 8) <=> substr($a, 3, 8);
}

my @sorted_files = sort rev_by_date @files;

...as long as the filenames match the format that you've described.


问:
Plotting Pandas dataframe subplots with different linestyles
I am plotting a figure with 6 sets of axes, each with a series of 3 lines from one of 2 Pandas dataframes (1 line per column).
I have been using matplotlib .plot:

```<code>import pandas as pd
import matplotlib.pyplot as plt

idx = pd.DatetimeIndex(start = '2013-01-01 00:00', periods =24,freq = 'H')
df1 = pd.DataFrame(index = idx, columns = ['line1','line2','line3'])
df1['line1']=  df1.index.hour
df1['line2'] = 24 - df1['line1']
df1['line3'] = df1['line1'].mean()
df2 = df1*2
df3= df1/2
df4= df2+df3

fig, ax = plt.subplots(2,2,squeeze=False,figsize = (10,10))
ax[0,0].plot(df1.index, df1,  marker='', linewidth=1, alpha=1)
ax[0,1].plot(df2.index, df2, marker='', linewidth=1, alpha=1)
ax[1,0].plot(df3.index, df3, marker='', linewidth=1, alpha=1)
ax[1,1].plot(df4.index, df4, marker='', linewidth=1, alpha=1)
fig.show()
</code>```

It's all good, and matplotlib automatically cycles through a different colour for each line, but uses the same colours for each plot, which is what i wanted.

However, now I want to specify more details for the lines: choosing specific colours for each line, and / or changing the linestyle for each line.
This link shows how to pass multiple linestyles to a Pandas plot. e.g. using

```<code> ax = df.plot(kind='line', style=['-', '--', '-.'])
</code>```

So I need to either:

pass lists of styles to my subplot command above, but style is not recognised and it doesn't accept a list for linestyle or color. Is there a way to do this?
or

Use df.plot:

fig, ax = plt.subplots(2,2,squeeze=False,figsize = (10,10))
ax[0,0] = df1.plot(style=['-','--','-.'], marker='', linewidth=1, alpha=1)
ax[0,1] = df2.plot(style=['-','--','-.'],marker='', linewidth=1, alpha=1)
ax[1,0] = df3.plot( style=['-','--','-.'],marker='', linewidth=1, alpha=1)
ax[1,1] = df4.plot(style=['-','--','-.'], marker='', linewidth=1, alpha=1)
fig.show()

...but then each plot is plotted as a seperate figure. I can't see how to put multiple Pandas plots on the same figure.

How can I make either of these approaches work?

答:
using matplotlib

Using matplotlib, you may define a cycler for the axes to loop over color and linestyle automatically. (See this answer).

```<code>import numpy as np; np.random.seed(1)
import pandas as pd
import matplotlib.pyplot as plt

f = lambda i: pd.DataFrame(np.cumsum(np.random.randn(20,3),0))
dic1= dict(zip(range(3), [f(i) for i in range(3)]))
dic2= dict(zip(range(3), [f(i) for i in range(3)]))
dics = [dic1,dic2]
rows = range(3)

def set_cycler(ax):
    ax.set_prop_cycle(plt.cycler('color', ['limegreen', '#bc15b0', 'indigo'])+
                      plt.cycler('linestyle', ["-","--","-."]))

fig, ax = plt.subplots(3,2,squeeze=False,figsize = (8,5))
for x in rows:
    for i,dic in enumerate(dics):
        set_cycler(ax[x,i])
        ax[x,i].plot(dic[x].index, dic[x],  marker='', linewidth=1, alpha=1)

plt.show()
</code>```

using pandas

Using pandas you can indeed supply a list of possible colors and linestyles to the df.plot() method. Additionally you need to tell it in which axes to plot (df.plot(ax=ax[i,j])).

```<code>import numpy as np; np.random.seed(1)
import pandas as pd
import matplotlib.pyplot as plt

f = lambda i: pd.DataFrame(np.cumsum(np.random.randn(20,3),0))
dic1= dict(zip(range(3), [f(i) for i in range(3)]))
dic2= dict(zip(range(3), [f(i) for i in range(3)]))
dics = [dic1,dic2]
rows = range(3)

color = ['limegreen', '#bc15b0', 'indigo']
linestyle = ["-","--","-."]

fig, ax = plt.subplots(3,2,squeeze=False,figsize = (8,5))
for x in rows:
    for i,dic in enumerate(dics):
        dic[x].plot(ax=ax[x,i], style=linestyle, color=color, legend=False)

plt.show()
</code>```

Body:
I am plotting a figure with 6 sets of axes, each with a series of 3 lines from one of 2 Pandas dataframes (1 line per column).
I have been using matplotlib .plot:

import pandas as pd
import matplotlib.pyplot as plt

idx = pd.DatetimeIndex(start = '2013-01-01 00:00', periods =24,freq = 'H')
df1 = pd.DataFrame(index = idx, columns = ['line1','line2','line3'])
df1['line1']=  df1.index.hour
df1['line2'] = 24 - df1['line1']
df1['line3'] = df1['line1'].mean()
df2 = df1*2
df3= df1/2
df4= df2+df3

fig, ax = plt.subplots(2,2,squeeze=False,figsize = (10,10))
ax[0,0].plot(df1.index, df1,  marker='', linewidth=1, alpha=1)
ax[0,1].plot(df2.index, df2, marker='', linewidth=1, alpha=1)
ax[1,0].plot(df3.index, df3, marker='', linewidth=1, alpha=1)
ax[1,1].plot(df4.index, df4, marker='', linewidth=1, alpha=1)
fig.show()

It's all good, and matplotlib automatically cycles through a different colour for each line, but uses the same colours for each plot, which is what i wanted.

However, now I want to specify more details for the lines: choosing specific colours for each line, and / or changing the linestyle for each line.
This link shows how to pass multiple linestyles to a Pandas plot. e.g. using

 ax = df.plot(kind='line', style=['-', '--', '-.'])

So I need to either:

pass lists of styles to my subplot command above, but style is not recognised and it doesn't accept a list for linestyle or color. Is there a way to do this?
or

Use df.plot:

fig, ax = plt.subplots(2,2,squeeze=False,figsize = (10,10))
ax[0,0] = df1.plot(style=['-','--','-.'], marker='', linewidth=1, alpha=1)
ax[0,1] = df2.plot(style=['-','--','-.'],marker='', linewidth=1, alpha=1)
ax[1,0] = df3.plot( style=['-','--','-.'],marker='', linewidth=1, alpha=1)
ax[1,1] = df4.plot(style=['-','--','-.'], marker='', linewidth=1, alpha=1)
fig.show()

...but then each plot is plotted as a seperate figure. I can't see how to put multiple Pandas plots on the same figure.

How can I make either of these approaches work?

Body:
using matplotlib

Using matplotlib, you may define a cycler for the axes to loop over color and linestyle automatically. (See this answer).

import numpy as np; np.random.seed(1)
import pandas as pd
import matplotlib.pyplot as plt

f = lambda i: pd.DataFrame(np.cumsum(np.random.randn(20,3),0))
dic1= dict(zip(range(3), [f(i) for i in range(3)]))
dic2= dict(zip(range(3), [f(i) for i in range(3)]))
dics = [dic1,dic2]
rows = range(3)

def set_cycler(ax):
    ax.set_prop_cycle(plt.cycler('color', ['limegreen', '#bc15b0', 'indigo'])+
                      plt.cycler('linestyle', ["-","--","-."]))

fig, ax = plt.subplots(3,2,squeeze=False,figsize = (8,5))
for x in rows:
    for i,dic in enumerate(dics):
        set_cycler(ax[x,i])
        ax[x,i].plot(dic[x].index, dic[x],  marker='', linewidth=1, alpha=1)

plt.show()

using pandas

Using pandas you can indeed supply a list of possible colors and linestyles to the df.plot() method. Additionally you need to tell it in which axes to plot (df.plot(ax=ax[i,j])).

import numpy as np; np.random.seed(1)
import pandas as pd
import matplotlib.pyplot as plt

f = lambda i: pd.DataFrame(np.cumsum(np.random.randn(20,3),0))
dic1= dict(zip(range(3), [f(i) for i in range(3)]))
dic2= dict(zip(range(3), [f(i) for i in range(3)]))
dics = [dic1,dic2]
rows = range(3)

color = ['limegreen', '#bc15b0', 'indigo']
linestyle = ["-","--","-."]

fig, ax = plt.subplots(3,2,squeeze=False,figsize = (8,5))
for x in rows:
    for i,dic in enumerate(dics):
        dic[x].plot(ax=ax[x,i], style=linestyle, color=color, legend=False)

plt.show()