问:
Why doesn't my code append a new row to the table element?
My purpose is to append a new row to the table button element, but nothing happens when I click the button element.

I've tried checking to see if I was selecting wrong elements, but everything seems to be sentactially entacted.When I try to debug my code in the console, I couldn't find any errors to fix. Any inpuy or help would be greatly appreciated, Thank you.

<!DOCTYPE html>

  <title>Table project</title>

        #
        First
        Last
        Handle

        1
        Mark
        Otto
        @mdo

        2
        Jacob
        Thornton
        @fat

        3
        Larry
        the Bird
        @twitter

  <button id="btn"> Enter Row </button>

```

答:
You can use $("#tbody2") to select the body. Use $("#tbody2 > tr").length to get the count of the

<!DOCTYPE html>

  <title>Table project</title>

        #
        First
        Last
        Handle

        1
        Mark
        Otto
        @mdo

        2
        Jacob
        Thornton
        @fat

        3
        Larry
        the Bird
        @twitter

  <button id="btn"> Enter Row </button>

```

Body:
You can use $("#tbody2") to select the body. Use $("#tbody2 > tr").length to get the count of the <tr>

<!DOCTYPE html>
<html>

<head>
  <title>Table project</title>
  <style>
    table {
      background-color: #00FFFF;
    }
  </style>
</head>

<body>
  <table id="x" border="1">
    <thead>
      <tr id="row0">
        <th scope="col">#</th>
        <th scope="col">First</th>
        <th scope="col">Last</th>
        <th scope="col">Handle</th>
      </tr>
    </thead>
    <tbody id="tbody2">
      <tr id="row1">
        <td scope="row">1</td>
        <td>Mark</td>
        <td>Otto</td>
        <td>@mdo</td>
      </tr>
      <tr id="row2">
        <td scope="row">2</td>
        <td>Jacob</td>
        <td>Thornton</td>
        <td>@fat</td>
      </tr>
      <tr id="row3">
        <td scope="row">3</td>
        <td>Larry</td>
        <td>the Bird</td>
        <td>@twitter</td>
      </tr>
    </tbody>
  </table>

  <button id="btn"> Enter Row </button>

  <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js" type="text/javascript"></script>

  <script type="text/javascript">
    $(document).ready(function() {
      $('#btn').click(function() {

        var count = $("#tbody2 > tr").length + 1;

        $("#tbody2").append(
          "<tr id='row" + count + "'>" +
          "<td scope='row'>" + count + "</td>" +
          "<td>Shit</td>" +
          "<td>All over</td>" +
          "<td>Myself</td>" +
          "</tr>"
        );

      })
    })
  </script>
</body>

</html>


来源: stackexchange

问:
Jasmine throwing error: Timeout - Async callback was not invoked within timeout specified by jasmine.DEFAULT_TIMEOUT_INTERVAL
I am trying to automate instagram following. I go to a profile and click on the followers link. It opens a modal type div and there are all the followers.
It first finds all the follow buttons present in the DOM and clickson them. After that it scrolls down and finds more follow buttons in the DOM and clicks on them. But after scrolling 2-3 times the automation stops and gives this error.

!Scrollable Div Image: https://imgur.com/6s3nGJs

Attaching the code below for collecting the follow buttons and clicking on them:

```<code>element(by.xpath("//div[@role='dialog']")).element(by.tagName("ul")).all(by.buttonText("Follow")).then(links => {
            console.log("Links Length" + links.length);
            if (links.length == 0) {
                this.ScrollDown();
            }
            else {
                for (let i = 0; i < links.length; i++) {
                    if (i >= links.length - 2) {
                        console.log("Scrolling Down");
                        browser.actions().sendKeys(protractor.Key.PAGE_DOWN).perform().then(function(){
                            console.log("Scrolled");
                            browser.sleep(3000);
                        });
                        break;
                    }
                    else {
                        browser.actions().mouseMove(links[i]).click().perform().then(function () {
                            console.log("Clicked on link " + (i + 1));
                            browser.sleep(3000);
                        });
                    }
                }
                this.followProfiles();
            }
        });
</code>```

ScrollDown:

```<code>console.log("Scrolling Down");
        browser.wait(browser.actions().sendKeys(protractor.Key.PAGE_DOWN).perform().then(function () {
            console.log("Scrolled down");
        }), 90000);
        browser.sleep(5000);
        this.followProfiles();
</code>```

答:
you can use clicking function of js to click what you want. if element is present and have width and height (element can't be displayed) , you can use this function to click directly htlm element.
click() : this function is protractor function, action of this function is same as clicking of left mouse, so element have just been present and displayed.
But clicking function of js can click html element when element have just been present although element can't be displayed.
clicking funtion of js :

browser.executeScript("arguments[0].click();",geocoding_switcher.getWebElement());

And, protractor usually run fast, so you should use clicking js function to click all "Follow" button in list, it make test run perfectly, don't need scroll to the element.
In js, there are many scrolling function. such as :

browser.executeScript("arguments[0].scrollIntoView();", category_label.getWebElement());

ContentLicense: CC BY-SA 4.0

Body:
I am trying to automate instagram following. I go to a profile and click on the followers link. It opens a modal type div and there are all the followers.
It first finds all the follow buttons present in the DOM and clickson them. After that it scrolls down and finds more follow buttons in the DOM and clicks on them. But after scrolling 2-3 times the automation stops and gives this error.

!Scrollable Div Image: https://imgur.com/6s3nGJs

Attaching the code below for collecting the follow buttons and clicking on them:

element(by.xpath("//div[@role='dialog']")).element(by.tagName("ul")).all(by.buttonText("Follow")).then(links => {
            console.log("Links Length" + links.length);
            if (links.length == 0) {
                this.ScrollDown();
            }
            else {
                for (let i = 0; i < links.length; i++) {
                    if (i >= links.length - 2) {
                        console.log("Scrolling Down");
                        browser.actions().sendKeys(protractor.Key.PAGE_DOWN).perform().then(function(){
                            console.log("Scrolled");
                            browser.sleep(3000);
                        });
                        break;
                    }
                    else {
                        browser.actions().mouseMove(links[i]).click().perform().then(function () {
                            console.log("Clicked on link " + (i + 1));
                            browser.sleep(3000);
                        });
                    }
                }
                this.followProfiles();
            }
        });

ScrollDown:

console.log("Scrolling Down");
        browser.wait(browser.actions().sendKeys(protractor.Key.PAGE_DOWN).perform().then(function () {
            console.log("Scrolled down");
        }), 90000);
        browser.sleep(5000);
        this.followProfiles();


问:
How to get each student's highest Score, in order
I have Student class and the initialized list of students to the Program class in my project.
Now I want to get the highest score of each student, in order

How to get that using Max()?

```<code>public class Student
{
    public string First { get; set; }

    public string Last { get; set; }

    public int ID { get; set; }

    public List<int> Scores;
}

// Create a data source by using a collection initializer.

static List<Student> students = new List<Student>
{
   new Student {First="Svetlana", Last="Omelchenko", ID=111, Scores= new List<int> {97, 92, 81, 60}},
   new Student {First="Claire", Last="O’Donnell", ID=112, Scores= new List<int> {75, 84, 91, 39}},
   new Student {First="Sven", Last="Mortensen", ID=113, Scores= new List<int> {88, 94, 65, 91}},
   new Student {First="Cesar", Last="Garcia", ID=114, Scores= new List<int> {97, 89, 85, 82}},
   new Student {First="Debra", Last="Garcia", ID=115, Scores= new List<int> {35, 72, 91, 70}},
   new Student {First="Fadi", Last="Fakhouri", ID=116, Scores= new List<int> {99, 86, 90, 94}},
   new Student {First="Hanying", Last="Feng", ID=117, Scores= new List<int> {93, 92, 80, 87}},
   new Student {First="Hugo", Last="Garcia", ID=118, Scores= new List<int> {92, 90, 83, 78}},
   new Student {First="Lance", Last="Tucker", ID=119, Scores= new List<int> {68, 79, 88, 92}},
   new Student {First="Terry", Last="Adams", ID=120, Scores= new List<int> {99, 82, 81, 79}},
   new Student {First="Eugene", Last="Zabokritski", ID=121, Scores= new List<int> {96, 85, 91, 60}},
   new Student {First="Michael", Last="Tucker", ID=122, Scores= new List<int> {94, 92, 91, 91} }
};
</code>```

答:
Something like this:

```<code>var studScores=students.Select(x=>new
            {
                student=x,
                highestscore=x.Scores.DefaultIfEmpty(0).Max()
            }).OrderByDescending(m=>m.highestscore);

            foreach(var score in studScores)
            {
                Console.WriteLine(score.highestscore+" "+score.student.First);
            }
</code>```

Output

```<code>99 Fadi
99 Terry
97 Svetlana
97 Cesar
96 Eugene
94 Sven
94 Hichael
93 Hanying
92 Hugo
92 Lance
91 Claire
91 Debra
</code>```

Body:
I have Student class and the initialized list of students to the Program class in my project.
Now I want to get the highest score of each student, in order

How to get that using Max()?

public class Student
{
    public string First { get; set; }

    public string Last { get; set; }

    public int ID { get; set; }

    public List<int> Scores;
}

// Create a data source by using a collection initializer.

static List<Student> students = new List<Student>
{
   new Student {First="Svetlana", Last="Omelchenko", ID=111, Scores= new List<int> {97, 92, 81, 60}},
   new Student {First="Claire", Last="O’Donnell", ID=112, Scores= new List<int> {75, 84, 91, 39}},
   new Student {First="Sven", Last="Mortensen", ID=113, Scores= new List<int> {88, 94, 65, 91}},
   new Student {First="Cesar", Last="Garcia", ID=114, Scores= new List<int> {97, 89, 85, 82}},
   new Student {First="Debra", Last="Garcia", ID=115, Scores= new List<int> {35, 72, 91, 70}},
   new Student {First="Fadi", Last="Fakhouri", ID=116, Scores= new List<int> {99, 86, 90, 94}},
   new Student {First="Hanying", Last="Feng", ID=117, Scores= new List<int> {93, 92, 80, 87}},
   new Student {First="Hugo", Last="Garcia", ID=118, Scores= new List<int> {92, 90, 83, 78}},
   new Student {First="Lance", Last="Tucker", ID=119, Scores= new List<int> {68, 79, 88, 92}},
   new Student {First="Terry", Last="Adams", ID=120, Scores= new List<int> {99, 82, 81, 79}},
   new Student {First="Eugene", Last="Zabokritski", ID=121, Scores= new List<int> {96, 85, 91, 60}},
   new Student {First="Michael", Last="Tucker", ID=122, Scores= new List<int> {94, 92, 91, 91} }
};

Body:
Something like this:

var studScores=students.Select(x=>new
            {
                student=x,
                highestscore=x.Scores.DefaultIfEmpty(0).Max()
            }).OrderByDescending(m=>m.highestscore);

            foreach(var score in studScores)
            {
                Console.WriteLine(score.highestscore+" "+score.student.First);
            }

Output

99 Fadi
99 Terry
97 Svetlana
97 Cesar
96 Eugene
94 Sven
94 Hichael
93 Hanying
92 Hugo
92 Lance
91 Claire
91 Debra


问:
A PHP function that adds # hashtag to an array of words
I'm trying to write a function that adds the sign # to an array of words in a string

Given I can use the str_replace for each one of them but my array is getting bigger and it's not efficient.

$needles = array('a', 'c', 'd');
$haystack = 'a b c d e f g';
    foreach($needles as $what) {
        if(strpos($haystack, $what)!==false) {
     $haystack = str_replace($needles, '#'.$what.'-', $haystack);
    }
    }
echo $haystack;
```

The array here is needles a c d in a haystack of  a b c d e f g
I'm trying to make them #a #b #c so that the result would be  #a b #c #d e f g

答:
I'm not sure if this is any faster you would have to benchmark it, but this solution works. Regex is slow, but iterating through a string once should be faster than looking through it N times. </p>

```<code><?php
$needles = array('a', 'c', 'd');
$haystack = 'a b c d e f g';
$reg = '~(['.implode($needles).'])~';

echo preg_replace ( $reg, '#$1' , $haystack );
</code>```

<p>Output </p>

```<code>#a b #c #d e f g
</code>```

Body:
I'm trying to write a function that adds the sign # to an array of words in a string

Given I can use the str_replace for each one of them but my array is getting bigger and it's not efficient.

$needles = array('a', 'c', 'd');
$haystack = 'a b c d e f g';
    foreach($needles as $what) {
        if(strpos($haystack, $what)!==false) {
     $haystack = str_replace($needles, '#'.$what.'-', $haystack);
    }
    }
echo $haystack;

The array here is needles a c d in a haystack of  a b c d e f g
I'm trying to make them #a #b #c so that the result would be  #a b #c #d e f g

Body:
I'm not sure if this is any faster you would have to benchmark it, but this solution works. Regex is slow, but iterating through a string once should be faster than looking through it N times.

<?php
$needles = array('a', 'c', 'd');
$haystack = 'a b c d e f g';
$reg = '~(['.implode($needles).'])~';

echo preg_replace ( $reg, '#$1' , $haystack );

Output

#a b #c #d e f g


问:
How to create a tuple of corresponding elements of a 2D numpy array in an efficient way
I have two 2D numpy arrays, one for latitude, another for longitude.

```<code>a = [ [1, 2, 3, 4],                  b = [ [a, b, c, d],
      [1, 2, 3, 4],                        [a, b, c, d],
      [1, 2, 3, 4],                        [a, b, c, d],
      [1, 2, 3, 4] ]                       [a, b, c, d] ]
</code>```

I want the following 2 kinds of outputs (a list and a 2D array of tuples)

```<code>output1 = [ (1,a), (2,a), (3,a), (4,a), (1,b), (2,b), (3,b), (4,b), . . . (3,d), (4,d) ]

output2 = [ [(1,a), (2,a), (3,a), (4,a)],
            [(1,b), (2,b), (3,b), (4,b)],
            [(1,c), (2,c), (3,c), (4,c)],
            [(1,d), (2,d), (3,d), (4,d)] ]
</code>```

How should I do it efficiently without loops?

This is the code for a and b generation:

```<code>aa = np.array([1,2,3,4])
bb = np.array(['a','b','c','d'])
a, b = np.meshgrid(aa,bb)
</code>```

Body:
I have two 2D numpy arrays, one for latitude, another for longitude.

a = [ [1, 2, 3, 4],                  b = [ [a, b, c, d],
      [1, 2, 3, 4],                        [a, b, c, d],
      [1, 2, 3, 4],                        [a, b, c, d],
      [1, 2, 3, 4] ]                       [a, b, c, d] ]

I want the following 2 kinds of outputs (a list and a 2D array of tuples)

output1 = [ (1,a), (2,a), (3,a), (4,a), (1,b), (2,b), (3,b), (4,b), . . . (3,d), (4,d) ]

output2 = [ [(1,a), (2,a), (3,a), (4,a)],
            [(1,b), (2,b), (3,b), (4,b)],
            [(1,c), (2,c), (3,c), (4,c)],
            [(1,d), (2,d), (3,d), (4,d)] ]

How should I do it efficiently without loops?

This is the code for a and b generation:

aa = np.array([1,2,3,4])
bb = np.array(['a','b','c','d'])
a, b = np.meshgrid(aa,bb)

Body:
A vectorized approach using numpy and tolist:

a = np.array([[1,2,3,4],
              [1,2,3,4],
              [1,2,3,4],
              [1,2,3,4]])
b = np.array([[10,20,30,40],
              [10,20,30,40],
              [10,20,30,40],
              [10,20,30,40]])

x = np.stack((a,b), axis=-1)

x.reshape(4,4,2).tolist()
[[[1, 10], [2, 10], [3, 10], [4, 10]],
 [[1, 20], [2, 20], [3, 20], [4, 20]],
 [[1, 30], [2, 30], [3, 30], [4, 30]],
 [[1, 40], [2, 40], [3, 40], [4, 40]]]

x.reshape(16,2).tolist()
[[1, 10], [2, 10], [3, 10], [4, 10], [1, 20], [2, 20], [3, 20], [4, 20], [1, 30], [2, 30], [3, 30], [4, 30], [1, 40], [2, 40], [3, 40], [4, 40]]


问:
Iphone get coords in background
Can I make iphone app that get coords from gps in 2 seconds and save them in file. In the end of the day I should send via mail?</p>

答: You can never have GPS location in 2 seconds, only the coordinates from triangulation of wifi signals.</p>

ContentLicense: CC BY-SA 3.0

Title: Iphone get coords in background


问:
Do Azure WebJobs run concurrently on the same host
If I have two distinct WebJobs, both triggered with TimerTrigger and at the same moment in time, can they ever run concurrently on the same host or will one wait for the other to complete?

In other words can a single host run two distinct webjobs in parallel which are triggered via TimerTrigger?

The main reason I am asking is because this project is heavily using both entity framework (DbContext) and also dependency injection and I want to be informed when planning my DI strategy. The solution for me may be challenging if two TimerTrigger webjobs can run concurrently on the same host (because services in this project receive an injected DbContext expecting a unit-of-work lifetime). In this case I might have to synchronize execution of the webjobs (within the same host) myself...

答: Yes, you can have many webjobs running at the time time. As long as they aren't configured to trigger based on a queue based trigger where an incoming message might cause conflict. You should be fine with a TimerTrigger.</p>


问:
How to parse a POINT object sent as string in JSON?
I'm fetching some data from an API and the response includes the user location in longitude and latitude.

This is to render an icon on a map according to the user's coordinates

That's the JSON object:

```<code>{
  ...
  "lonlat": "POINT (-42.796763 -5.077056)",
}
</code>```

I want to be able to parse this POINT object and get the value of latitude and longitude.

答:
You can replace all values other then space, digits and - and decimal and then trim leading and trailing whitespace and then split on space

```<code>[^\d .-]
</code>```

[^\d .-] - Match anything except digit, space, . and -

const data = {
  "lonlat": "POINT (-42.796763 -5.077056)"
};

let [lat,lng] = data.lonlat.replace(/[^\d .-]/g,'').trim().split(/\s+/)
console.log(lat);
console.log(lng);```

Body:
I'm fetching some data from an API and the response includes the user location in longitude and latitude.

This is to render an icon on a map according to the user's coordinates

That's the JSON object:

{
  ...
  "lonlat": "POINT (-42.796763 -5.077056)",
}

I want to be able to parse this POINT object and get the value of latitude and longitude.

Body:
You can replace all values other then space, digits and - and decimal and then trim leading and trailing whitespace and then split on space

[^\d .-]

[^\d .-] - Match anything except digit, space, . and -

const data = {
  "lonlat": "POINT (-42.796763 -5.077056)"
};

let [lat,lng] = data.lonlat.replace(/[^\d .-]/g,'').trim().split(/\s+/)
console.log(lat);
console.log(lng);


问:
last day/time of month
How do I get the last day of the month to be 11:59:59 pm? Right now it is showing 05/31/2019 12:00 AM. If I just do sysdate it just shows the time I ran it. Thanks. </p>

```<code>LAST_DAY(TRUNC(SYSDATE,'MM'))
</code>```

答:
Try adding one day to the last day of the current month, then subtracting one minute:

```<code>SELECT
    LAST_DAY(TRUNC(SYSDATE,'MM')) + INTERVAL '1' DAY - INTERVAL '1' SECOND
FROM dual;
</code>```

Or, if you want to also see the time component, use CURRENT_TIMESTAMP in place of SYSDATE:

```<code>SELECT
    LAST_DAY(TRUNC(CURRENT_TIMESTAMP,'MM')) + INTERVAL '1' DAY - INTERVAL '1' SECOND
FROM dual;
</code>```

This outputted:

```<code>30.06.2019 23:59:59
</code>```

Title: last day/time of month

Body:
How do I get the last day of the month to be 11:59:59 pm? Right now it is showing 05/31/2019 12:00 AM. If I just do sysdate it just shows the time I ran it. Thanks.

LAST_DAY(TRUNC(SYSDATE,'MM'))

Body:
Try adding one day to the last day of the current month, then subtracting one minute:

SELECT
    LAST_DAY(TRUNC(SYSDATE,'MM')) + INTERVAL '1' DAY - INTERVAL '1' SECOND
FROM dual;

Or, if you want to also see the time component, use CURRENT_TIMESTAMP in place of SYSDATE:

SELECT
    LAST_DAY(TRUNC(CURRENT_TIMESTAMP,'MM')) + INTERVAL '1' DAY - INTERVAL '1' SECOND
FROM dual;

This outputted:

30.06.2019 23:59:59


问:
Problem when create order On Paypal Javascript
I have a problem when the script call a create a order in the page HTML/javascript.

In the console, I have an error "Expected a promise for a string order id to be passed to createOrder".

I give my code HTMl/javascript

```<code><html >
<body>
<div id="bouton-paypal"></div>
<script src="https://www.paypal.com/sdk/js?client-id=monid"></script>
<script>
paypal.Buttons({
  // Set up the transaction
  createOrder: function() {
      var SETEC_URL = 'http://localhost/paypalphp/paypalcreatepayment.php';

      return fetch(SETEC_URL, {
        method: 'post',
        headers: {
          'content-type': 'application/json'
        }
      }).then(function(res) {
        return res.json();
      }).then(function(data) {
        return data.token;
      });
    }
}).render('#bouton-paypal');
</code>```

答:
I assume that you are following the PayPal guide for Setting Up A Transaction on the Server and that you have tested that your server is returning a valid transaction.

The error that you are getting indicates that the line return data.token; is not returning a valid order id string (most likely returning undefined).

I have added console.log(data) to your code. Please run this so that we can inspect the JSON returned from your server.

```

Body:
I assume that you are following the PayPal guide for Setting Up A Transaction on the Server and that you have tested that your server is returning a valid transaction.

The error that you are getting indicates that the line return data.token; is not returning a valid order id string (most likely returning undefined).

I have added console.log(data) to your code. Please run this so that we can inspect the JSON returned from your server.

<html>
<body>
<div id="bouton-paypal"></div>
<script src="https://www.paypal.com/sdk/js?client-id=monid"></script>
<script>
  paypal.Buttons({
    // Set up the transaction
    createOrder: function() {
      var SETEC_URL = 'http://localhost/paypalphp/paypalcreatepayment.php';

      return fetch(SETEC_URL, {
        method: 'post',
        headers: {
          'content-type': 'application/json'
        }
      }).then(function(res) {
        return res.json();
      }).then(function(data) {
        console.log(data)
        return data.token;
      });
    }
  }).render('#bouton-paypal');
</script>


问:
Why I am getting different outputs with these 2 assignments, one in a function and other in main of a pointer?
"I was trying to assign NULL to a pointer root in a function. But it doesn't really get assigned by NULL using function. But when I tried to assign root = NULL in main it get assigned. I am not getting why it happens so?

```<code>#include<bits/stdc++.h>
using namespace std;
struct node{
    int key;
};
void deletion(struct node* root){
    root=NULL;
}
void print(struct node* temp){
    if(!temp)
    return;
    cout<<temp->key;
}
int main(){
    struct node* root = new struct node;
    root->key=10;
    cout<<"Initially : ";
    print(root);

    deletion(root);
    cout<<"\nAfter deletion() : ";
    print(root);

    root=NULL;
    cout<<"\nAfter assigning in main() : ";
    print(root);
}
</code>```

The output I am getting is :

```<code>Initially : 10

After deletion() : 10

After assigning in main() :
</code>```

答:
You're passing the pointer by value and modifying that value. To modify the value of a variable being passed, you can either pass it by reference (C++-style) or pass it by pointer(C-style). With C-style, remember to dereference the pointer to change its value for the caller.

C++-style:

```<code>void foo(const struct node*& n);
</code>```

C-style:

```<code> void foo(const struct node** n);
</code>```

Body:
"I was trying to assign NULL to a pointer root in a function. But it doesn't really get assigned by NULL using function. But when I tried to assign root = NULL in main it get assigned. I am not getting why it happens so?

#include<bits/stdc++.h>
using namespace std;
struct node{
    int key;
};
void deletion(struct node* root){
    root=NULL;
}
void print(struct node* temp){
    if(!temp)
    return;
    cout<<temp->key;
}
int main(){
    struct node* root = new struct node;
    root->key=10;
    cout<<"Initially : ";
    print(root);

    deletion(root);
    cout<<"\nAfter deletion() : ";
    print(root);

    root=NULL;
    cout<<"\nAfter assigning in main() : ";
    print(root);
}

The output I am getting is :

Initially : 10

After deletion() : 10

After assigning in main() :

Body:
You're passing the pointer by value and modifying that value. To modify the value of a variable being passed, you can either pass it by reference (C++-style) or pass it by pointer(C-style). With C-style, remember to dereference the pointer to change its value for the caller.

C++-style:

void foo(const struct node*& n);

C-style:

 void foo(const struct node** n);


问:
What does output_dim in Keras Dense mean?
I am a newbie in Deep Learning.By studding this article
link .

I cannot understand what does the output_dim=128 and output_dim=1 mean???

I would expect as output in final Dense the number of classes=2(Cat/Dog).

Besides from where is the 128???

答:
Output_dim is the dimension of the dense embedding.

The choice of 128 in

```<code>classifier.add(Dense(output_dim = 128, activation = 'relu'))
</code>```

is quite arbitrary , it just indicate the size of fully connected layer that you prefer. You can change it to another number.

The 1 in

```<code>classifier.add(Dense(output_dim = 1, activation = 'sigmoid'))
</code>```

is due to for a binary classification problem, we just require a probability to distinguish the 2 groups. If the probability is at least 0.5, we classify it as a dog, if it is less than 0.5, we classify it as a cat.

If you prefer, you can also set activation function to be softmax and output_dim to be 2 as the last layer though that would not improve the performance.

Body:
Output_dim is the dimension of the dense embedding.

The choice of 128 in

classifier.add(Dense(output_dim = 128, activation = 'relu'))

is quite arbitrary , it just indicate the size of fully connected layer that you prefer. You can change it to another number.

The 1 in

classifier.add(Dense(output_dim = 1, activation = 'sigmoid'))

is due to for a binary classification problem, we just require a probability to distinguish the 2 groups. If the probability is at least 0.5, we classify it as a dog, if it is less than 0.5, we classify it as a cat.

If you prefer, you can also set activation function to be softmax and output_dim to be 2 as the last layer though that would not improve the performance.


问:
How to get ProGuard mapping file of previous release build
I have an application in production, I have got some crash report stacktraces and they are from the previous release version. I don't know if I have the ProGuard mapping file for the previous build version. I have the current one. And as far as I know that the mapping file is different for different release builds.

My question is:

How do I get the mapping file for the previous build?

答:
If you created an app bundle (.aab) instead of an app package (.apk), you can extract the mapping file from there.

Download app bundle from Google Play Console

Rename file extension from .aab to .zip

Extract ZIP archive

Navigate to BUNDLE-METADATA/com.android.tools.build.obfuscation/proguard.map

Open proguard.map with file editor, it is the mapping file.


问:
How to save images with the same name to the different direction using PIL and os.path?
While trying to split the path to get a name, I get the traceback:
TypeError: expected str, bytes or os.PathLike object, not JpegImageFile . How can I solve it or is there other methods?

I try to save resized images with the same name to a different direction. For this reason, I use os.path.split() functions.

```<code>import glob
from PIL import Image
import os
images = glob.glob("/Users/marialavrovskaa/Desktop/6_1/*")
path = "/Users/marialavrovskaa/Desktop/2.2/"
quality_val=95
for image in images:
    image = Image.open(image)
    image.thumbnail((640, 428), Image.ANTIALIAS)
    image_path_and_name = os.path.split(image)
    image_name_and_ext = os.path.splitext(image[0])
    name = image_name_and_ext[0] + '.png'
    name = os.path.splitext(image)[0] + '.png'
    file_path = os.path.join(path, name)
    image.save(file_path, quality=quality_val)
</code>```

答:
firstly,
image_name_and_ext = os.path.splitext(image[0])

should be
image_name_and_ext = os.path.splitext(image_path_and_name[1])

because image is string so image[0] just get first character of image not useless in this case

secondly,

name = os.path.splitext(image)[0] + '.png' equal image

name = os.path.splitext(image)[0] should return path of image not include extention

to solve this problem, you can try:

```<code>for image in images:
    img = Image.open(image)
    img.thumbnail((640, 428), Image.ANTIALIAS)
    name = os.path.split(image)
    file_path = os.path.join(path, name[1])
    image.save(file_path, quality=quality_val)
</code>```

Body:
While trying to split the path to get a name, I get the traceback:
TypeError: expected str, bytes or os.PathLike object, not JpegImageFile . How can I solve it or is there other methods?

I try to save resized images with the same name to a different direction. For this reason, I use os.path.split() functions.

import glob
from PIL import Image
import os
images = glob.glob("/Users/marialavrovskaa/Desktop/6_1/*")
path = "/Users/marialavrovskaa/Desktop/2.2/"
quality_val=95
for image in images:
    image = Image.open(image)
    image.thumbnail((640, 428), Image.ANTIALIAS)
    image_path_and_name = os.path.split(image)
    image_name_and_ext = os.path.splitext(image[0])
    name = image_name_and_ext[0] + '.png'
    name = os.path.splitext(image)[0] + '.png'
    file_path = os.path.join(path, name)
    image.save(file_path, quality=quality_val)

Body:
firstly,
image_name_and_ext = os.path.splitext(image[0])

should be
image_name_and_ext = os.path.splitext(image_path_and_name[1])

because image is string so image[0] just get first character of image not useless in this case

secondly,

name = os.path.splitext(image)[0] + '.png' equal image

name = os.path.splitext(image)[0] should return path of image not include extention

to solve this problem, you can try:

for image in images:
    img = Image.open(image)
    img.thumbnail((640, 428), Image.ANTIALIAS)
    name = os.path.split(image)
    file_path = os.path.join(path, name[1])
    image.save(file_path, quality=quality_val)


问:
How to delete widgets from another page in kivy
I have a delete button that deletes widgets from another page. However, the button doesn't actually delete the widget. The button also should delete the json object that is attached to the widget but it doesn't do this either.

code:

```<code>    # displays the streak that was clicked on in screen two
    def display_streak(self, obj):
        self.third_screen()
        name = obj.id
        bottle = self.root.get_screen("three")
        can = self.root.get_screen('two')
        bottle.ids.del_space.add_widget(Button(id=name, text="Delete", size=(60,25), size_hint=(None,None),
                                    font_size=18, on_press=self.del_button)) # fix later
</code>```

```<code>def del_button(self, obj):
        bottle = self.root.get_screen("two")
        can = self.root.get_screen('three')
        name = obj.id

        with open("streak.json", "r+") as f:
            data = json.load(f)

        for child in self.root.screen_two.ids.streak_zone.children:
            if child.text == name:
                print("delete")
                bottle.screen_two.ids.streak_zone.remove_widget(child)

                for i in xrange(len(data)):
                    if data[i] == name:
                        data.pop(i)
                        break

                open("streak.json", "w").write(json.dump(data, sort_keys=True, indent=4))
</code>```

I was trying to compare the id of the Button in del_space to the text inside of the widgets in streak_zone inorder to delete but for some reason this isn't working. I even passed obj from on_press=self.del_button and it still does not work, how come?

EDIT

obj in display_streak() is passed from a conditional that binds the function to a button widget:

```<code>elif delay > time.time() > self.honey:  # on time (green)
                    child.background_normal = ''
                    child.background_color = [0, 1, 0, .95]
                    child.unbind(on_press=self.early_click)
                    child.bind(on_press=self.add_score)
                    child.bind(on_press=self.display_streak)
                    child.bind(on_press=self.draw_streak)
</code>```

EDIT

I'm not sure but I believe that the problem may be coming from my kivy code:

```<code><ScreenTwo>
    id: screen_two
    name: "two"
    on_leave: app.restart()
    on_enter: app.display_btn()
    ScrollView:
        GridLayout:
            cols: 2
            rows: 1
            ScrollView:
                BoxLayout:
                    id: streak_zone
                    orientation: 'vertical'
                    height: self.minimum_height
</code>```

When entering page two display_btn is activated

Python:

```<code>def display_btn(self):
        ...

            for value in data.values():
                if value['delta'] is not None:
                    print(f"action={value['action']}, delta={value['delta']}, grace={value['delay']}")
                    streak_button = StreakButton(id=(value['action']), text=value['action'],
                                                 color=(0,0,0,1), size=(400, 50),
                                                 size_hint=(None, None))
                    self.root.screen_two.ids.streak_zone.add_widget(streak_button)
...
</code>```

If this is the reason why the button won't be deleted, then how would I get around this problem?

答:
Since the kv file deletes the widgets upon leaving, I need to just delete the json element with the same id as the widget</p>

```<code>def del_button(self, object):
        name = object.id

        with open("streak.json", "r") as f:
            data = json.load(f)

        with open("streak.json", "r+") as file:
            data = json.load(file)
            data.pop(name, None)
            file.seek(0)
            json.dump(data, file, indent=4)
            file.truncate()

        self.change_screen()

</code>```

Body:
I have a delete button that deletes widgets from another page. However, the button doesn't actually delete the widget. The button also should delete the json object that is attached to the widget but it doesn't do this either.

code:

    # displays the streak that was clicked on in screen two
    def display_streak(self, obj):
        self.third_screen()
        name = obj.id
        bottle = self.root.get_screen("three")
        can = self.root.get_screen('two')
        bottle.ids.del_space.add_widget(Button(id=name, text="Delete", size=(60,25), size_hint=(None,None),
                                    font_size=18, on_press=self.del_button)) # fix later

def del_button(self, obj):
        bottle = self.root.get_screen("two")
        can = self.root.get_screen('three')
        name = obj.id

        with open("streak.json", "r+") as f:
            data = json.load(f)

        for child in self.root.screen_two.ids.streak_zone.children:
            if child.text == name:
                print("delete")
                bottle.screen_two.ids.streak_zone.remove_widget(child)

                for i in xrange(len(data)):
                    if data[i] == name:
                        data.pop(i)
                        break

                open("streak.json", "w").write(json.dump(data, sort_keys=True, indent=4))

I was trying to compare the id of the Button in del_space to the text inside of the widgets in streak_zone inorder to delete but for some reason this isn't working. I even passed obj from on_press=self.del_button and it still does not work, how come?

EDIT

obj in display_streak() is passed from a conditional that binds the function to a button widget:

elif delay > time.time() > self.honey:  # on time (green)
                    child.background_normal = ''
                    child.background_color = [0, 1, 0, .95]
                    child.unbind(on_press=self.early_click)
                    child.bind(on_press=self.add_score)
                    child.bind(on_press=self.display_streak)
                    child.bind(on_press=self.draw_streak)

EDIT

I'm not sure but I believe that the problem may be coming from my kivy code:

<ScreenTwo>
    id: screen_two
    name: "two"
    on_leave: app.restart()
    on_enter: app.display_btn()
    ScrollView:
        GridLayout:
            cols: 2
            rows: 1
            ScrollView:
                BoxLayout:
                    id: streak_zone
                    orientation: 'vertical'
                    height: self.minimum_height

When entering page two display_btn is activated

Python:

def display_btn(self):
        ...

            for value in data.values():
                if value['delta'] is not None:
                    print(f"action={value['action']}, delta={value['delta']}, grace={value['delay']}")
                    streak_button = StreakButton(id=(value['action']), text=value['action'],
                                                 color=(0,0,0,1), size=(400, 50),
                                                 size_hint=(None, None))
                    self.root.screen_two.ids.streak_zone.add_widget(streak_button)
...

If this is the reason why the button won't be deleted, then how would I get around this problem?

Body:
Since the kv file deletes the widgets upon leaving, I need to just delete the json element with the same id as the widget

def del_button(self, object):
        name = object.id

        with open("streak.json", "r") as f:
            data = json.load(f)

        with open("streak.json", "r+") as file:
            data = json.load(file)
            data.pop(name, None)
            file.seek(0)
            json.dump(data, file, indent=4)
            file.truncate()

        self.change_screen()


问:
AWS MediaConvert Rotate Aspect Ratio Changed
I am using the VOD (video on demand) template in AWS for media conversion. It creates a Lambda function that in turn pushes a Job into AWS MediaConvert. Recently, AWS added support for a Rotate property, which when set to AUTO reads the meta data from the source file and applies the appropriate rotation to the video during conversion. It is rotating the video, however, it appears to shrink the video in the process. See below.

You can see that rather than the overall video being rotated, it rotates it to fit inside a wide aspect ratio container. The source file is a .mov from an iPhone.

Looking for help on how to get MediaConvert to rotate the full video rather than trying to rotate it, and then shrink to fit inside the original source video dimensions.

答:
If you have a 1920x1080 video with a metadata of 90 degrees and you are using a job that specifies an output resolution of 1920x1080, then this results in the video being rotated first to a 1080x1920 video which is then pillar-boxed + scaled to form an output resolution of 1920x1080. This will look rotated, pillar-boxed, and somewhat shrunk in the vertical dimension - just like this picture. </p>

<p>In order to prevent this, it is best to leave the width and height of the output unspecified so that it follows the dimensions of the rotated source. </p>

Body:
If you have a 1920x1080 video with a metadata of 90 degrees and you are using a job that specifies an output resolution of 1920x1080, then this results in the video being rotated first to a 1080x1920 video which is then pillar-boxed + scaled to form an output resolution of 1920x1080. This will look rotated, pillar-boxed, and somewhat shrunk in the vertical dimension - just like this picture.

In order to prevent this, it is best to leave the width and height of the output unspecified so that it follows the dimensions of the rotated source.


问:
Solving CodingBat brick making puzzle in Python
I'm completing this CodingBat problem:

We want to make a row of bricks that is goal inches long. We have a number of small bricks (1 inch each) and big bricks (5 inches each). Return True if it is possible to make the goal by choosing from the given bricks. This is a little harder than it looks and can be done without any loops.

```<code>make_bricks(3, 1, 8) → True
make_bricks(3, 1, 9) → False
make_bricks(3, 2, 10) → True
</code>```

I wrote:

```<code>if small + big * 5 >= goal: return True
else: return False
</code>```

My errors are: make_bricks(3, 2, 9) → False (I put true because (2*5)+3=13 which is greater than 9.

```<code>make_bricks(2, 1000000, 100003) → False
make_bricks(1, 4, 12) → False
</code>```

I found this answer than passed those tests:

```<code>if goal > small + big * 5:
  return False
else:
  return goal % 5 <= small
</code>```

I dont really get why, can someone please explain?

答:
```<code>def make_bricks(small, big, goal):
   if (goal//5) <= big:
       if (goal%5) <= small:
         return True
       else:
         return False
   if (goal//5) >= big:
       if (goal - (big*5)) <= small:
         return True
       else:
         return False
</code>```

Body:
I'm completing this CodingBat problem:

We want to make a row of bricks that is goal inches long. We have a number of small bricks (1 inch each) and big bricks (5 inches each). Return True if it is possible to make the goal by choosing from the given bricks. This is a little harder than it looks and can be done without any loops.

make_bricks(3, 1, 8) → True
make_bricks(3, 1, 9) → False
make_bricks(3, 2, 10) → True

I wrote:

if small + big * 5 >= goal: return True
else: return False

My errors are: make_bricks(3, 2, 9) → False (I put true because (2*5)+3=13 which is greater than 9.

make_bricks(2, 1000000, 100003) → False
make_bricks(1, 4, 12) → False

I found this answer than passed those tests:

if goal > small + big * 5:
  return False
else:
  return goal % 5 <= small

I dont really get why, can someone please explain?


问:
C++ "Reference to overloaded function" error using namespace std
I am new to C++, and I keep getting an error saying:

Reference to overloaded function could not be resolved; did you mean to call it?

Below is the code that is causing this:

#include <stdio.h>
#include <string>

using namespace std;

int main() {
    string name;
    string age;
    cout << "Enter your name and age: ";
    cin >> name >> age;
    cout << "Hello, " << name << ", are you " << age << " years old?\n";
    return 0;
}
```

I am using Xcode on Mac OS X Mojave.

I also noticed that if I have only that code, then it works just fine, but when I have multiple files, all of them fail to work.

Can anyone tell me why this is and a solution for it?

答:
stdio.h does not define std::cin and std::cout. That header defines the C functions for input and output, like printf and scanf. So it is an I/O header, but it's not the one you need.

You need to include <iostream> to have std::cin and std::cout

Body:
I am new to C++, and I keep getting an error saying:

Reference to overloaded function could not be resolved; did you mean to call it?

Below is the code that is causing this:

#include <stdio.h>
#include <string>

using namespace std;

int main() {
    string name;
    string age;
    cout << "Enter your name and age: ";
    cin >> name >> age;
    cout << "Hello, " << name << ", are you " << age << " years old?\n";
    return 0;
}

I am using Xcode on Mac OS X Mojave.

I also noticed that if I have only that code, then it works just fine, but when I have multiple files, all of them fail to work.

Can anyone tell me why this is and a solution for it?


问:
Delay future returns Error(shutdown) when polled
I'm rewriting the Forward future from a Stream to a Sink adding a timeout on the reception of new items.
I'm using a Delay future inside the Forward struct to keep track of the timeout, but the result is always an Error(Shutdown).

From the timer::Error documentation I see that this should return only if the future is dropped but it should not be the case since it's still contained in the main struct.

This is a minimal test example from which I get the same result.

```<code>extern crate tokio; // 0.1.20

use std::thread::sleep;
use std::time::{Duration, Instant};
use tokio::prelude::*;
use tokio::timer::Delay;

fn main() {
    let mut delay = Delay::new(Instant::now() + Duration::from_millis(3000));

    sleep(Duration::from_millis(1000));

    match delay.poll() {
        Ok(Async::NotReady) => println!("Not ready"),
        Ok(Async::Ready(v)) => println!("Ready: {:?}", v),
        Err(e) => println!("{:?}", e),
    }
}
</code>```

You can see a running example here

I'm expecting to either receive an Async:Ready(v) where v is ().

答:
A Delay works together with a Timer and the error here indicates that it was unable to register with one. While the docs sometimes assume that you're working within a tokio context, they do mention this requirement:

These types must be used from within the context of the Runtime or a timer context must be setup explicitly. See the tokio-timer crate for more details on how to setup a timer context.

If you wanted to avoid the error, it would be enough to run it inside a task:

fn main() {
    tokio::run(futures::future::lazy(|| {
        let mut delay = Delay::new(Instant::now() + Duration::from_millis(3000));

        sleep(Duration::from_millis(1000));

        // "Not ready"
        match delay.poll() {
            Ok(Async::NotReady) => println!("Not ready"),
            Ok(Async::Ready(v)) => println!("Ready: {:?}", v),
            Err(e) => println!("{:?}", e),
        }

        Ok(())
    }))
}
```

<p>However this will not transition to ready even if you wait more than 3000 milliseconds. If you want to use the Runtime's Timer you'll have to spawn it as a task:</p>

<pre class="lang-rust prettyprint-override"><code>fn main() {
    // "Ready: ()"
    tokio::run(
        Delay::new(Instant::now() + Duration::from_millis(3000))
            .map(|v| println!("Ready: {:?}", v))
            .map_err(|e| println!("{:?}", e)),
    )
}
</code>```

Body:
I'm rewriting the Forward future from a Stream to a Sink adding a timeout on the reception of new items.
I'm using a Delay future inside the Forward struct to keep track of the timeout, but the result is always an Error(Shutdown).

From the timer::Error documentation I see that this should return only if the future is dropped but it should not be the case since it's still contained in the main struct.

This is a minimal test example from which I get the same result.

extern crate tokio; // 0.1.20

use std::thread::sleep;
use std::time::{Duration, Instant};
use tokio::prelude::*;
use tokio::timer::Delay;

fn main() {
    let mut delay = Delay::new(Instant::now() + Duration::from_millis(3000));

    sleep(Duration::from_millis(1000));

    match delay.poll() {
        Ok(Async::NotReady) => println!("Not ready"),
        Ok(Async::Ready(v)) => println!("Ready: {:?}", v),
        Err(e) => println!("{:?}", e),
    }
}

You can see a running example here

I'm expecting to either receive an Async:Ready(v) where v is ().

Body:
A Delay works together with a Timer and the error here indicates that it was unable to register with one. While the docs sometimes assume that you're working within a tokio context, they do mention this requirement:

These types must be used from within the context of the Runtime or a timer context must be setup explicitly. See the tokio-timer crate for more details on how to setup a timer context.

If you wanted to avoid the error, it would be enough to run it inside a task:

fn main() {
    tokio::run(futures::future::lazy(|| {
        let mut delay = Delay::new(Instant::now() + Duration::from_millis(3000));

        sleep(Duration::from_millis(1000));

        // "Not ready"
        match delay.poll() {
            Ok(Async::NotReady) => println!("Not ready"),
            Ok(Async::Ready(v)) => println!("Ready: {:?}", v),
            Err(e) => println!("{:?}", e),
        }

        Ok(())
    }))
}

However this will not transition to ready even if you wait more than 3000 milliseconds. If you want to use the Runtime's Timer you'll have to spawn it as a task:

fn main() {
    // "Ready: ()"
    tokio::run(
        Delay::new(Instant::now() + Duration::from_millis(3000))
            .map(|v| println!("Ready: {:?}", v))
            .map_err(|e| println!("{:?}", e)),
    )
}


问:
Check if request.resource.data is a list of strings in Firebase Firestore
How do I check if a field is of type string[] in firestore rules?

I have a tags field in a document, which should be a list of strings, and I want to enforce that. Normally, I can say request.resource.data is int if I want to see if the field is an int, but I can't find an equivalent for lists.

Thanks!

答:
There is no explicit type check in the rules language (at least as far as I know). So the best I can come up with is trying to find a way to distinguish between a List (the type of an array), and other types.

For example, a list has a join() method, which can be used to concatenate the values from the list into a single string. Since (as far as I can see) none of the other types have that operation, this check can detect an array:

```<code>allow write: if request.resource.data.categories.join(",") != "";
</code>```

Any non-empty array will pass this test, while empty arrays and other types will fail. In the simulator this gives a pretty ugly error message, but that translates to a normal, generic "permission denied" when exposed to clients.

For my own future reference: test code is here.

Body:
There is no explicit type check in the rules language (at least as far as I know). So the best I can come up with is trying to find a way to distinguish between a List (the type of an array), and other types.

For example, a list has a join() method, which can be used to concatenate the values from the list into a single string. Since (as far as I can see) none of the other types have that operation, this check can detect an array:

allow write: if request.resource.data.categories.join(",") != "";

Any non-empty array will pass this test, while empty arrays and other types will fail. In the simulator this gives a pretty ugly error message, but that translates to a normal, generic "permission denied" when exposed to clients.

For my own future reference: test code is here.


问:
Wonders whether there's some principled way to define classes with getter/setter with less boilerplate
In Python world, IIUC, you generally have two kinds of options, every attribute is constant and frozen, like namedtuple, vs every attribute is modifiable.

You can write lots of getter/setter with @property. However, it's lots of boilerplates.

I like approaches like class Child(namedtuple(...)), however, it has the following downsides:

If in the inheritance you set __slots__ = (), then you can't add additional attribute into the child class.

If you don't set __slots__, then you can add additional attribute, however, there's no protection on assigning wrong attribute child.some_non_exist = some_value

Moreover, there's no way to optionally allow some attribute to be accessible and some attribute not.

I can have the following proposal, however, I don't know whether there's existing library for this.

Thanks!!

(I know attrs but I think it's focusing another set of problems.)

```<code>### The following is a proposal

@attr_acl
class A(object):
   x = attr_acl.frozen()    # x must be specified in __init__
   y = attr_acl.frozen(default = 5)
   z = attr_acl.mutable(default = 5)
   zz = attr_acl.mutable_freezable()
   g = attr_acl.mutable(is_final=True)

@attr_acl
class AA(X):
   o = attr_acl.mutable()

aa = AA(x=1, zz=2, o=3)
attr_acl.freeze(obj.zz)

### The followings must raise error
aa.x = 5
aa.zz = 6
aa.some_non_exist = 7
</code>```

答:
Here's a rudimentary implementation of the proposal without any dependencies, in case we want to proceed with not using attrs or dataclasses. It's only tested with the sample code in the question.</p>

```<code>class UnsetDefaultAttributeValue(object):
    pass

class AclAttribute(object):
    def __init__(self, value):
        self._value = value

    def __str__(self):
        return self._value.__str__()

class FrozenAttribute(AclAttribute):
    def __init__(self, *args, **kwargs):
        self._init_value_set = False
        self._default_value = kwargs.get('default',
                                         UnsetDefaultAttributeValue())
        self._value = self._default_value

    def __get__(self, instance, owner):
        if self._value is UnsetDefaultAttributeValue and not self._init_value_set:
            raise AttributeError('Value must be specified')
        return self

    def __set__(self, instance, value):
        if (self._init_value_set):
            raise AttributeError('Attribute is frozen')
        self._value = value
        self._init_value_set = True

class MutableAttribute(AclAttribute):
    def __init__(self, *args, **kwargs):
        self._init_value_set = False
        self._default_value = kwargs.get('default', None)
        self._is_final = kwargs.get('is_final', False)
        self._value = self._default_value

    def __get__(self, instance, owner):
        return self

    def __set__(self, instance, value):
        if (self._is_final):
            raise AttributeError('Attribute is finalized')
        self._value = value
        self._init_value_set = True

class MutableFreezableAttribute(AclAttribute):
    def __init__(self, *args, **kwargs):
        self._init_value_set = False
        self._is_frozen = False
        self._default_value = kwargs.get('default',
                                         UnsetDefaultAttributeValue())
        self._value = self._default_value

    def __get__(self, instance, owner):
        return self

    def __set__(self, instance, value):
        if (self._is_frozen):
            raise AttributeError('Attribute is frozen')
        self._value = value
        self._init_value_set = True

    def freeze(self):
        self._is_frozen = True

class attr_acl(type):
    def __new__(self, class_definition, *args, **kwargs):
        def _init_class(self, *args, **kwargs):
            for key, value in kwargs.items():
                setattr(self, key, value)

        def _set_attr(self, key, value):
            if not hasattr(self, key):
                raise AttributeError('Attribute does not exist')
            attr = getattr(self, key)
            attr.__set__(self, value)

        class_definition.__init__ = _init_class
        class_definition.__setattr__ = _set_attr
        return class_definition

    @classmethod
    def frozen(*args, **kwargs):
        default_value = kwargs.get('default', None)
        return FrozenAttribute(*args, **kwargs)

    @classmethod
    def mutable(*args, **kwargs):
        default_value = kwargs.get('default', None)
        return MutableAttribute(*args, **kwargs)

    @classmethod
    def mutable_freezable(*args, **kwargs):
        default_value = kwargs.get('default', None)
        return MutableFreezableAttribute(*args, **kwargs)

    @classmethod
    def freeze(self, attribute):
        attribute.freeze()

### The following is a proposal

@attr_acl
class A(object):
    x = attr_acl.frozen()    # x must be specified in __init__
    y = attr_acl.frozen(default = 5)
    z = attr_acl.mutable(default = 5)
    zz = attr_acl.mutable_freezable()
    g = attr_acl.mutable(is_final=True)

@attr_acl
class AA(A):
   o = attr_acl.mutable()

aa = AA(x=1, zz=2, o=3)
attr_acl.freeze(aa.zz)

### The followings must raise error
aa.x = 5
aa.zz = 6
aa.some_non_exist = 7
</code>```

Body:
In Python world, IIUC, you generally have two kinds of options, every attribute is constant and frozen, like namedtuple, vs every attribute is modifiable.

You can write lots of getter/setter with @property. However, it's lots of boilerplates.

I like approaches like class Child(namedtuple(...)), however, it has the following downsides:

If in the inheritance you set __slots__ = (), then you can't add additional attribute into the child class.

If you don't set __slots__, then you can add additional attribute, however, there's no protection on assigning wrong attribute child.some_non_exist = some_value

Moreover, there's no way to optionally allow some attribute to be accessible and some attribute not.

I can have the following proposal, however, I don't know whether there's existing library for this.

Thanks!!

(I know attrs but I think it's focusing another set of problems.)

### The following is a proposal

@attr_acl
class A(object):
   x = attr_acl.frozen()    # x must be specified in __init__
   y = attr_acl.frozen(default = 5)
   z = attr_acl.mutable(default = 5)
   zz = attr_acl.mutable_freezable()
   g = attr_acl.mutable(is_final=True)

@attr_acl
class AA(X):
   o = attr_acl.mutable()

aa = AA(x=1, zz=2, o=3)
attr_acl.freeze(obj.zz)

### The followings must raise error
aa.x = 5
aa.zz = 6
aa.some_non_exist = 7

Body:
Here's a rudimentary implementation of the proposal without any dependencies, in case we want to proceed with not using attrs or dataclasses. It's only tested with the sample code in the question.

class UnsetDefaultAttributeValue(object):
    pass

class AclAttribute(object):
    def __init__(self, value):
        self._value = value

    def __str__(self):
        return self._value.__str__()

class FrozenAttribute(AclAttribute):
    def __init__(self, *args, **kwargs):
        self._init_value_set = False
        self._default_value = kwargs.get('default',
                                         UnsetDefaultAttributeValue())
        self._value = self._default_value

    def __get__(self, instance, owner):
        if self._value is UnsetDefaultAttributeValue and not self._init_value_set:
            raise AttributeError('Value must be specified')
        return self

    def __set__(self, instance, value):
        if (self._init_value_set):
            raise AttributeError('Attribute is frozen')
        self._value = value
        self._init_value_set = True

class MutableAttribute(AclAttribute):
    def __init__(self, *args, **kwargs):
        self._init_value_set = False
        self._default_value = kwargs.get('default', None)
        self._is_final = kwargs.get('is_final', False)
        self._value = self._default_value

    def __get__(self, instance, owner):
        return self

    def __set__(self, instance, value):
        if (self._is_final):
            raise AttributeError('Attribute is finalized')
        self._value = value
        self._init_value_set = True

class MutableFreezableAttribute(AclAttribute):
    def __init__(self, *args, **kwargs):
        self._init_value_set = False
        self._is_frozen = False
        self._default_value = kwargs.get('default',
                                         UnsetDefaultAttributeValue())
        self._value = self._default_value

    def __get__(self, instance, owner):
        return self

    def __set__(self, instance, value):
        if (self._is_frozen):
            raise AttributeError('Attribute is frozen')
        self._value = value
        self._init_value_set = True

    def freeze(self):
        self._is_frozen = True

class attr_acl(type):
    def __new__(self, class_definition, *args, **kwargs):
        def _init_class(self, *args, **kwargs):
            for key, value in kwargs.items():
                setattr(self, key, value)

        def _set_attr(self, key, value):
            if not hasattr(self, key):
                raise AttributeError('Attribute does not exist')
            attr = getattr(self, key)
            attr.__set__(self, value)

        class_definition.__init__ = _init_class
        class_definition.__setattr__ = _set_attr
        return class_definition

    @classmethod
    def frozen(*args, **kwargs):
        default_value = kwargs.get('default', None)
        return FrozenAttribute(*args, **kwargs)

    @classmethod
    def mutable(*args, **kwargs):
        default_value = kwargs.get('default', None)
        return MutableAttribute(*args, **kwargs)

    @classmethod
    def mutable_freezable(*args, **kwargs):
        default_value = kwargs.get('default', None)
        return MutableFreezableAttribute(*args, **kwargs)

    @classmethod
    def freeze(self, attribute):
        attribute.freeze()

### The following is a proposal

@attr_acl
class A(object):
    x = attr_acl.frozen()    # x must be specified in __init__
    y = attr_acl.frozen(default = 5)
    z = attr_acl.mutable(default = 5)
    zz = attr_acl.mutable_freezable()
    g = attr_acl.mutable(is_final=True)

@attr_acl
class AA(A):
   o = attr_acl.mutable()

aa = AA(x=1, zz=2, o=3)
attr_acl.freeze(aa.zz)

### The followings must raise error
aa.x = 5
aa.zz = 6
aa.some_non_exist = 7


问:
selecting whole partitions uses index - why?
I am selecting all the data from some partitions of a partitioned table (Oracle 11g - actually updating in the real case, but for the example a select shows the same behaviour that I would like to understand). Can you explain to me why Oracle decides to use the index instead of a full scan? In my understanding a full scan would be the smarter access method. Why does Oracle think an index range scan + table access by index rowid batched is smarter than a full scan of the partitions?

Test table:

```<code>CREATE TABLE t_test
    (ID                NUMBER                 NOT NULL ENABLE,
    PARTITION_NUMBER   NUMBER                 NOT NULL ENABLE,
    CREATION_TIMESTAMP DATE   DEFAULT SYSDATE NOT NULL ENABLE,
    CONSTRAINT PK_t_test PRIMARY KEY (PARTITION_NUMBER, ID) USING INDEX LOCAL
    )
PARTITION BY LIST (PARTITION_NUMBER)
    (
    PARTITION P1  VALUES (1) SEGMENT CREATION IMMEDIATE,
    PARTITION P2  VALUES (2) SEGMENT CREATION IMMEDIATE,
    PARTITION P3  VALUES (3) SEGMENT CREATION IMMEDIATE,
    PARTITION P4  VALUES (4) SEGMENT CREATION IMMEDIATE,
    PARTITION P5  VALUES (5) SEGMENT CREATION IMMEDIATE,
    PARTITION P6  VALUES (6) SEGMENT CREATION IMMEDIATE,
    PARTITION P7  VALUES (7) SEGMENT CREATION IMMEDIATE,
    PARTITION P8  VALUES (8) SEGMENT CREATION IMMEDIATE,
    PARTITION P9  VALUES (9) SEGMENT CREATION IMMEDIATE
    );
</code>```

Selecting the data from some partitions (nothing was inserted for this example, but behaviour is the same with data in the partitions):

```<code>explain plan for select * from t_test where PARTITION_NUMBER in (2,3,4,5,6,7);
SELECT * FROM TABLE(dbms_xplan.display);

Plan hash value: 3284178661

-------------------------------------------------------------------------------------------------------------------------
| Id  | Operation                                   | Name      | Rows  | Bytes | Cost (%CPU)| Time     | Pstart| Pstop |
-------------------------------------------------------------------------------------------------------------------------
|   0 | SELECT STATEMENT                            |           |     1 |    35 |     1   (0)| 00:00:01 |       |       |
|   1 |  INLIST ITERATOR                            |           |       |       |            |          |       |       |
|   2 |   PARTITION LIST ITERATOR                   |           |     1 |    35 |     1   (0)| 00:00:01 |KEY(I) |KEY(I) |
|   3 |    TABLE ACCESS BY LOCAL INDEX ROWID BATCHED| T_TEST    |     1 |    35 |     1   (0)| 00:00:01 |KEY(I) |KEY(I) |
|*  4 |     INDEX RANGE SCAN                        | PK_T_TEST |     1 |       |     2   (0)| 00:00:01 |KEY(I) |KEY(I) |
-------------------------------------------------------------------------------------------------------------------------

Predicate Information (identified by operation id):
---------------------------------------------------

   4 - access("PARTITION_NUMBER"=2 OR "PARTITION_NUMBER"=3 OR "PARTITION_NUMBER"=4 OR "PARTITION_NUMBER"=5 OR
              "PARTITION_NUMBER"=6 OR "PARTITION_NUMBER"=7)

Note
-----
   - dynamic statistics used: dynamic sampling (level=2)
</code>```

I don't understand why it does the range scan... Why not just like this (same query but with FULL-hint)? Why does it ever think using the index is the better approach here? (Even an ALL_ROWS hint does not change the behavior) :

```<code>explain plan for select /*+ full(t_test) */ * from t_test where PARTITION_NUMBER in (2,3,4,5,6,7);
SELECT * FROM TABLE(dbms_xplan.display);

Plan hash value: 3335595461

------------------------------------------------------------------------------------------------
| Id  | Operation             | Name   | Rows  | Bytes | Cost (%CPU)| Time     | Pstart| Pstop |
------------------------------------------------------------------------------------------------
|   0 | SELECT STATEMENT      |        |     1 |    35 |     2   (0)| 00:00:01 |       |       |
|   1 |  PARTITION LIST INLIST|        |     1 |    35 |     2   (0)| 00:00:01 |KEY(I) |KEY(I) |
|   2 |   TABLE ACCESS FULL   | T_TEST |     1 |    35 |     2   (0)| 00:00:01 |KEY(I) |KEY(I) |
------------------------------------------------------------------------------------------------

Note
-----
   - dynamic statistics used: dynamic sampling (level=2)
</code>```

答:
The example uses an index instead of a full table scan because of how the segment space is allocated.  By default, Oracle tends to allocate a non-trivial amount of space for table partitions.  For indexes, Oracle tends to allocate a much smaller amount of space for index partitions.

When I run your sample code, the empty table contains 72 megabytes but the empty index contains 0.5 megabytes:

```<code>select segment_name, sum(bytes)/1024/1024 mb
from user_segments
where segment_name in ('T_TEST', 'PK_T_TEST')
group by segment_name
order by 1 desc;

SEGMENT_NAME   MB
------------   -------
T_TEST         72
PK_T_TEST       0.5625
</code>```

Full table scans have to read the entire segment.  The index range scan still has to read from the table, but it can do so using the ROWIDs, and therefore reads less data from disk.

Oracle's automatic segment space allocation is almost always better than configuring it manually.  But with a trivial amount of data, it might make sense to optimize the segments.  If you change each of the 9 SEGMENT CREATION IMMEDIATE to STORAGE (INITIAL 64K NEXT 64K) then the table partitions will be smaller and the execution plan will use a full table scan.  But you probably don't want to do that.  This problem is likely only related to using an unrealistically small sample data set.

Oracle's space algorithms are understandably optimized for storing large amounts of data in partitions.

Unfortunately, this likely doesn't help you with your real problem.  You mentioned a 300 million row table, and that kind of size should work better with partitioning.

But the real problem might also be related to a segment space issue.  Perhaps the table used to have 3 billion rows, and was deleted, but never shrunk?  Or maybe the table was created with hundreds of partitions, most of which are empty.  Or maybe the table was created with some ridiculous manual space setting.

When dealing with large table performance we often have to think in terms of segments and bytes instead of the number of rows.

Body:
I am selecting all the data from some partitions of a partitioned table (Oracle 11g - actually updating in the real case, but for the example a select shows the same behaviour that I would like to understand). Can you explain to me why Oracle decides to use the index instead of a full scan? In my understanding a full scan would be the smarter access method. Why does Oracle think an index range scan + table access by index rowid batched is smarter than a full scan of the partitions?

Test table:

CREATE TABLE t_test
    (ID                NUMBER                 NOT NULL ENABLE,
    PARTITION_NUMBER   NUMBER                 NOT NULL ENABLE,
    CREATION_TIMESTAMP DATE   DEFAULT SYSDATE NOT NULL ENABLE,
    CONSTRAINT PK_t_test PRIMARY KEY (PARTITION_NUMBER, ID) USING INDEX LOCAL
    )
PARTITION BY LIST (PARTITION_NUMBER)
    (
    PARTITION P1  VALUES (1) SEGMENT CREATION IMMEDIATE,
    PARTITION P2  VALUES (2) SEGMENT CREATION IMMEDIATE,
    PARTITION P3  VALUES (3) SEGMENT CREATION IMMEDIATE,
    PARTITION P4  VALUES (4) SEGMENT CREATION IMMEDIATE,
    PARTITION P5  VALUES (5) SEGMENT CREATION IMMEDIATE,
    PARTITION P6  VALUES (6) SEGMENT CREATION IMMEDIATE,
    PARTITION P7  VALUES (7) SEGMENT CREATION IMMEDIATE,
    PARTITION P8  VALUES (8) SEGMENT CREATION IMMEDIATE,
    PARTITION P9  VALUES (9) SEGMENT CREATION IMMEDIATE
    );

Selecting the data from some partitions (nothing was inserted for this example, but behaviour is the same with data in the partitions):

explain plan for select * from t_test where PARTITION_NUMBER in (2,3,4,5,6,7);
SELECT * FROM TABLE(dbms_xplan.display);

Plan hash value: 3284178661

-------------------------------------------------------------------------------------------------------------------------
| Id  | Operation                                   | Name      | Rows  | Bytes | Cost (%CPU)| Time     | Pstart| Pstop |
-------------------------------------------------------------------------------------------------------------------------
|   0 | SELECT STATEMENT                            |           |     1 |    35 |     1   (0)| 00:00:01 |       |       |
|   1 |  INLIST ITERATOR                            |           |       |       |            |          |       |       |
|   2 |   PARTITION LIST ITERATOR                   |           |     1 |    35 |     1   (0)| 00:00:01 |KEY(I) |KEY(I) |
|   3 |    TABLE ACCESS BY LOCAL INDEX ROWID BATCHED| T_TEST    |     1 |    35 |     1   (0)| 00:00:01 |KEY(I) |KEY(I) |
|*  4 |     INDEX RANGE SCAN                        | PK_T_TEST |     1 |       |     2   (0)| 00:00:01 |KEY(I) |KEY(I) |
-------------------------------------------------------------------------------------------------------------------------

Predicate Information (identified by operation id):
---------------------------------------------------

   4 - access("PARTITION_NUMBER"=2 OR "PARTITION_NUMBER"=3 OR "PARTITION_NUMBER"=4 OR "PARTITION_NUMBER"=5 OR
              "PARTITION_NUMBER"=6 OR "PARTITION_NUMBER"=7)

Note
-----
   - dynamic statistics used: dynamic sampling (level=2)

I don't understand why it does the range scan... Why not just like this (same query but with FULL-hint)? Why does it ever think using the index is the better approach here? (Even an ALL_ROWS hint does not change the behavior) :

explain plan for select /*+ full(t_test) */ * from t_test where PARTITION_NUMBER in (2,3,4,5,6,7);
SELECT * FROM TABLE(dbms_xplan.display);

Plan hash value: 3335595461

------------------------------------------------------------------------------------------------
| Id  | Operation             | Name   | Rows  | Bytes | Cost (%CPU)| Time     | Pstart| Pstop |
------------------------------------------------------------------------------------------------
|   0 | SELECT STATEMENT      |        |     1 |    35 |     2   (0)| 00:00:01 |       |       |
|   1 |  PARTITION LIST INLIST|        |     1 |    35 |     2   (0)| 00:00:01 |KEY(I) |KEY(I) |
|   2 |   TABLE ACCESS FULL   | T_TEST |     1 |    35 |     2   (0)| 00:00:01 |KEY(I) |KEY(I) |
------------------------------------------------------------------------------------------------

Note
-----
   - dynamic statistics used: dynamic sampling (level=2)

Body:
The example uses an index instead of a full table scan because of how the segment space is allocated.  By default, Oracle tends to allocate a non-trivial amount of space for table partitions.  For indexes, Oracle tends to allocate a much smaller amount of space for index partitions.

When I run your sample code, the empty table contains 72 megabytes but the empty index contains 0.5 megabytes:

select segment_name, sum(bytes)/1024/1024 mb
from user_segments
where segment_name in ('T_TEST', 'PK_T_TEST')
group by segment_name
order by 1 desc;

SEGMENT_NAME   MB
------------   -------
T_TEST         72
PK_T_TEST       0.5625

Full table scans have to read the entire segment.  The index range scan still has to read from the table, but it can do so using the ROWIDs, and therefore reads less data from disk.

Oracle's automatic segment space allocation is almost always better than configuring it manually.  But with a trivial amount of data, it might make sense to optimize the segments.  If you change each of the 9 SEGMENT CREATION IMMEDIATE to STORAGE (INITIAL 64K NEXT 64K) then the table partitions will be smaller and the execution plan will use a full table scan.  But you probably don't want to do that.  This problem is likely only related to using an unrealistically small sample data set.

Oracle's space algorithms are understandably optimized for storing large amounts of data in partitions.

Unfortunately, this likely doesn't help you with your real problem.  You mentioned a 300 million row table, and that kind of size should work better with partitioning.

But the real problem might also be related to a segment space issue.  Perhaps the table used to have 3 billion rows, and was deleted, but never shrunk?  Or maybe the table was created with hundreds of partitions, most of which are empty.  Or maybe the table was created with some ridiculous manual space setting.

When dealing with large table performance we often have to think in terms of segments and bytes instead of the number of rows.


问:
How do i save some data from the UIWebView in an application for IPad
I am making an app for an IPad.
I have loaded a local html file in the UIWebView. I have now collected some data from the user. I want to save this locally so it can be used by the application for some other purpose.</p>

答: store the information in plist if it is not huge and use it whenever required.</p>


答:
You can try getting the characters between parenthesis first like the following way:

var obj = {
  "lonlat": "POINT (-42.796763 -5.077056)",
}
var regExp = /\((.*?)\)/;
var lonlat = obj.lonlat.match(regExp)[1].split(' ');
console.log(lonlat);```

Title: How to parse a POINT object sent as string in JSON?

Body:
I'm fetching some data from an API and the response includes the user location in longitude and latitude.

This is to render an icon on a map according to the user's coordinates

That's the JSON object:

{
  ...
  "lonlat": "POINT (-42.796763 -5.077056)",
}

I want to be able to parse this POINT object and get the value of latitude and longitude.


问:
Extract the value from the html input element before sending to the sql server
For now, I have a form that the user inputs the lat and long, and I use those information to create markers and send them to the mysql. However, I want to change to have the user input the address instead, and I tried to use the geocode from google api to get the lat and long from the address the user give me. However, it failed miserably. I think the form is sent to the server before I can catch the address value.  So I am not sure how to get the address out of the form before it is sent to the server? Anything would help. thanks

This is my html file

```<code><form id = "seenform" action="/submitseen" method="POST">

        <input placeholder="Latitude" name = "lat" id="lat">
        <br>
        <input placeholder="Longitude" name = "lngt">
        <br>
        <input id="address_seen" placeholder = "Address" name = "address"> (this is where I want to get the value out)
</form>

Javascript file

app.post('/submitseen', function(req,res){
    var dlat = req.body.lat;
    var dlngt = req.body.lngt;
    var daddress = req.body.address;
})

</code>```

答:
You can get the form values before submit. </p>

```<code>document.getElementById('seenform').onsubmit = function() {
    var address = document.getElementById('address_seen');
    console.log(address.value);
};
</code>```

Body:
For now, I have a form that the user inputs the lat and long, and I use those information to create markers and send them to the mysql. However, I want to change to have the user input the address instead, and I tried to use the geocode from google api to get the lat and long from the address the user give me. However, it failed miserably. I think the form is sent to the server before I can catch the address value.  So I am not sure how to get the address out of the form before it is sent to the server? Anything would help. thanks

This is my html file

<form id = "seenform" action="/submitseen" method="POST">

        <input placeholder="Latitude" name = "lat" id="lat">

        <input placeholder="Longitude" name = "lngt">

        <input id="address_seen" placeholder = "Address" name = "address"> (this is where I want to get the value out)
</form>

Javascript file

app.post('/submitseen', function(req,res){
    var dlat = req.body.lat;
    var dlngt = req.body.lngt;
    var daddress = req.body.address;
})

Body:
You can get the form values before submit.

document.getElementById('seenform').onsubmit = function() {
    var address = document.getElementById('address_seen');
    console.log(address.value);
};


问:
Why is autocomplete not sending a JSON request
I'm trying to use the Jquery-UI autocomple in my rails app. Inside of my application.js I have the line

$j('#autocomplete').autocomplete({
  source:'contexts/1.json'
});

From what I read on the documentation the function expects json data in return so inside of my context_controller Show method I have the following

```<code>def show
@context = Context.find(params[:id])
if params[:term]
  @tags = Tag.find(5, :conditions => ['name LIKE ? AND context_id = ?',params[:q], @context.id])
else
  @tags = Tag.find(:all, :conditions => ["context_id = ?",@context.id])
end
respond_to do |format|
  format.html
  format.json { render :json => @tags}
end
</code>```

end

The problem is that the server doesn't seem to be receiving the request when I begin typing in the input box that autocomplete is attached to. How can I make this work?

答:
After a lot of searching around the intrawebz I realized that I was making a few small critical errors.
The first thing I changed was to put the javascript into $j(document).ready(function(){ so that it now reads

```<code>$j(document).ready(function() {
  $j('#autocomplete').autocomplete({
    source: '/contexts/1'
  });
});
</code>```

Not really sure why this made a difference, maybe someone can tell me.

After I did that I saw that it was correctly sending the json request to the server and receiving something back but nothing was being put into the autocomplete menu. From this point I realized that jQuery UI autocomplete filled in the menu with the attribute of the serialized object called "value". My model didn't have this attribute. I fixed this by adding a method(virtual attribute) of "value" into my Tag.rb model file. and changed my controller so that it would return the "value" attribute along with the object.
format.json { render :json => @tags.to_json(:methods=>:value)}

Although I now had a serialized object with a 'value' attribute, it still was not working. The final step that I had to take was to have the .to_json() method not return the type of object as the root. This is found inside config/initializers/new_rails_defaults.rb

ActiveRecord::Base.include_root_in_json = false

After all of this I was able to get autocomplete to work in my rails project without chaining myself to a plugin that didn't have all of the features that I would have liked.

ContentLicense: CC BY-SA 2.5

Body:
I'm trying to use the Jquery-UI autocomple in my rails app. Inside of my application.js I have the line

$j('#autocomplete').autocomplete({
  source:'contexts/1.json'
});

From what I read on the documentation the function expects json data in return so inside of my context_controller Show method I have the following

def show
@context = Context.find(params[:id])
if params[:term]
  @tags = Tag.find(5, :conditions => ['name LIKE ? AND context_id = ?',params[:q], @context.id])
else
  @tags = Tag.find(:all, :conditions => ["context_id = ?",@context.id])
end
respond_to do |format|
  format.html
  format.json { render :json => @tags}
end

end

The problem is that the server doesn't seem to be receiving the request when I begin typing in the input box that autocomplete is attached to. How can I make this work?

Body:
After a lot of searching around the intrawebz I realized that I was making a few small critical errors.
The first thing I changed was to put the javascript into $j(document).ready(function(){ so that it now reads

$j(document).ready(function() {
  $j('#autocomplete').autocomplete({
    source: '/contexts/1'
  });
});

Not really sure why this made a difference, maybe someone can tell me.

After I did that I saw that it was correctly sending the json request to the server and receiving something back but nothing was being put into the autocomplete menu. From this point I realized that jQuery UI autocomplete filled in the menu with the attribute of the serialized object called "value". My model didn't have this attribute. I fixed this by adding a method(virtual attribute) of "value" into my Tag.rb model file. and changed my controller so that it would return the "value" attribute along with the object.
format.json { render :json => @tags.to_json(:methods=>:value)}

Although I now had a serialized object with a 'value' attribute, it still was not working. The final step that I had to take was to have the .to_json() method not return the type of object as the root. This is found inside config/initializers/new_rails_defaults.rb

ActiveRecord::Base.include_root_in_json = false

After all of this I was able to get autocomplete to work in my rails project without chaining myself to a plugin that didn't have all of the features that I would have liked.


问:
How to avoid sub entity curly braces in JSON response?
I have a java POJO I want the response be in a certain format

I have the code something like below

```<code>   public class LocationInfo {

     private String locationId;
     private String locationName;

     private State state;
   }
</code>```

This is how I get the response

```<code>  "localCompanies": {
    "locationId": "345",
    "locationName": "test_location",
    "stateInfo": {
       "city": "test_city",
       "county": "test_county
   }
 }
</code>```

What I really need is

```<code>  "localCompanies": {
     "locationId": "345",
     "locationName": "test_location",
     "city": "test_city",
     "county": "test_county
  }
</code>```

How to achieve this? thanks in advance.

答:
Jackson has introduced JsonUnwrapped annotation in 1.9.0. All you need to add annotation on target object.

```<code>public class LocationInfo {

  private String locationId;
  private String locationName;

  @JsonUnwrapped
  private State state;
}
</code>```

Body:
I have a java POJO I want the response be in a certain format

I have the code something like below

   public class LocationInfo {

     private String locationId;
     private String locationName;

     private State state;
   }

This is how I get the response

  "localCompanies": {
    "locationId": "345",
    "locationName": "test_location",
    "stateInfo": {
       "city": "test_city",
       "county": "test_county
   }
 }

What I really need is

  "localCompanies": {
     "locationId": "345",
     "locationName": "test_location",
     "city": "test_city",
     "county": "test_county
  }

How to achieve this? thanks in advance.

Body:
Jackson has introduced JsonUnwrapped annotation in 1.9.0. All you need to add annotation on target object.

public class LocationInfo {

  private String locationId;
  private String locationName;

  @JsonUnwrapped
  private State state;
}


问:
Why isnt my audio working on a webpage that im working on, which is not live yet
Im working on a webpage, and im trying to have an audio file play from soundcloud, but it doesnt seem to work. it works if the src is from my computer but not from the soundcloud website.

```<code><audio controls autoplay loop>

<source src="audio.mp3" type="audio/mp3">

<a href="https://soundcloud.com/grixis/peacetreaty-change-grixis">

</audio>
</code>```

ive also tried the following below:

```<code><audio controls autoplay loop>

<source src="https://soundcloud.com/grixis/peacetreaty-change-grixis" type="audio/mp3">

</audio>
</code>```

Failed to load resource: net::ERR_FILE_NOT_FOUND

答:
You are providing a soundcloud link, which is a HTML page. Try providing a mp3 link instead.
If you need the ability to play from soundcloud, try embedding their player.

https://soundcloud.com/pages/embed

Body:
Im working on a webpage, and im trying to have an audio file play from soundcloud, but it doesnt seem to work. it works if the src is from my computer but not from the soundcloud website.

<audio controls autoplay loop>

<source src="audio.mp3" type="audio/mp3">

</audio>

ive also tried the following below:

<audio controls autoplay loop>

<source src="https://soundcloud.com/grixis/peacetreaty-change-grixis" type="audio/mp3">

</audio>

Failed to load resource: net::ERR_FILE_NOT_FOUND


问:
How to create a tuple of corresponding elements of a 2D numpy array in an efficient way
I have two 2D numpy arrays, one for latitude, another for longitude.

```<code>a = [ [1, 2, 3, 4],                  b = [ [a, b, c, d],
      [1, 2, 3, 4],                        [a, b, c, d],
      [1, 2, 3, 4],                        [a, b, c, d],
      [1, 2, 3, 4] ]                       [a, b, c, d] ]
</code>```

I want the following 2 kinds of outputs (a list and a 2D array of tuples)

```<code>output1 = [ (1,a), (2,a), (3,a), (4,a), (1,b), (2,b), (3,b), (4,b), . . . (3,d), (4,d) ]

output2 = [ [(1,a), (2,a), (3,a), (4,a)],
            [(1,b), (2,b), (3,b), (4,b)],
            [(1,c), (2,c), (3,c), (4,c)],
            [(1,d), (2,d), (3,d), (4,d)] ]
</code>```

How should I do it efficiently without loops?

This is the code for a and b generation:

```<code>aa = np.array([1,2,3,4])
bb = np.array(['a','b','c','d'])
a, b = np.meshgrid(aa,bb)
</code>```

答:
solution without numpy</p>

```<code>from itertools import chain
output2 = [list(zip(i,j)) for i,j in zip(a,zip(*b))]
output1 = list(chain.from_iterable(output2))
</code>```

Body:
I have two 2D numpy arrays, one for latitude, another for longitude.

a = [ [1, 2, 3, 4],                  b = [ [a, b, c, d],
      [1, 2, 3, 4],                        [a, b, c, d],
      [1, 2, 3, 4],                        [a, b, c, d],
      [1, 2, 3, 4] ]                       [a, b, c, d] ]

I want the following 2 kinds of outputs (a list and a 2D array of tuples)

output1 = [ (1,a), (2,a), (3,a), (4,a), (1,b), (2,b), (3,b), (4,b), . . . (3,d), (4,d) ]

output2 = [ [(1,a), (2,a), (3,a), (4,a)],
            [(1,b), (2,b), (3,b), (4,b)],
            [(1,c), (2,c), (3,c), (4,c)],
            [(1,d), (2,d), (3,d), (4,d)] ]

How should I do it efficiently without loops?

This is the code for a and b generation:

aa = np.array([1,2,3,4])
bb = np.array(['a','b','c','d'])
a, b = np.meshgrid(aa,bb)

Body:
solution without numpy

from itertools import chain
output2 = [list(zip(i,j)) for i,j in zip(a,zip(*b))]
output1 = list(chain.from_iterable(output2))


问:
How to automatically login a user after registration in django
This is what I am currently using for registration:

```<code>def register(request):
    if request.method == 'POST':
        form = UserCreationForm(request.POST)
        if form.is_valid():
            new_user = form.save()
            messages.info(request, "Thanks for registering. Please login to continue.")
            return HttpResponseRedirect("/dashboard/")
    else:
        form = UserCreationForm()
    return render_to_response("accounts/register.html", {
        'form': form,
    }, context_instance=RequestContext(request))
</code>```

Is it possible not to require the user to login manually after creating an account, but rather simply to log them in automatically? Thanks.

edit: I had tried the login() function without success. I believe the problem is that AUTHENTICATION_BACKENDS was not set.

答:
You can subclass Django's UserCreationForm and override it's save method to log them in when commit=True.

forms.py

```<code>from django.contrib.auth.forms import UserCreationForm
from django.contrib.auth import login

class CustomUserCreationForm(UserCreationForm):
    """
    A ModelForm for creating a User and logging
    them in after commiting a save of the form.
    """

    def __init__(self, request, *args, **kwargs):
        super().__init__(*args, **kwargs)
        self.request = request

    class Meta(UserCreationForm.Meta):
        pass

    def save(self, commit=True):
        user = super().save(commit=commit)
        if commit:
            auth_user = authenticate(
                username=self.cleaned_data['username'],
                password=self.cleaned_data['password1']
            )
            login(self.request, auth_user)

        return user
</code>```

You just need to make sure you pass in a request object when you instantiate the form. You can do that by overriding the view's get_form_kwargs method.

views.py

```<code>def get_form_kwargs(self):
    form_kwargs = super().get_form_kwargs()
    form_kwargs['request'] = self.request
    return form_kwargs

</code>```

Or, make sure when you instantiate a form_class you do CustomUserCreationForm(data=request.POST, request=self.request).

Body:
This is what I am currently using for registration:

def register(request):
    if request.method == 'POST':
        form = UserCreationForm(request.POST)
        if form.is_valid():
            new_user = form.save()
            messages.info(request, "Thanks for registering. Please login to continue.")
            return HttpResponseRedirect("/dashboard/")
    else:
        form = UserCreationForm()
    return render_to_response("accounts/register.html", {
        'form': form,
    }, context_instance=RequestContext(request))

Is it possible not to require the user to login manually after creating an account, but rather simply to log them in automatically? Thanks.

edit: I had tried the login() function without success. I believe the problem is that AUTHENTICATION_BACKENDS was not set.

Body:
You can subclass Django's UserCreationForm and override it's save method to log them in when commit=True.

forms.py

from django.contrib.auth.forms import UserCreationForm
from django.contrib.auth import login

class CustomUserCreationForm(UserCreationForm):
    """
    A ModelForm for creating a User and logging
    them in after commiting a save of the form.
    """

    def __init__(self, request, *args, **kwargs):
        super().__init__(*args, **kwargs)
        self.request = request

    class Meta(UserCreationForm.Meta):
        pass

    def save(self, commit=True):
        user = super().save(commit=commit)
        if commit:
            auth_user = authenticate(
                username=self.cleaned_data['username'],
                password=self.cleaned_data['password1']
            )
            login(self.request, auth_user)

        return user

You just need to make sure you pass in a request object when you instantiate the form. You can do that by overriding the view's get_form_kwargs method.

views.py

def get_form_kwargs(self):
    form_kwargs = super().get_form_kwargs()
    form_kwargs['request'] = self.request
    return form_kwargs

Or, make sure when you instantiate a form_class you do CustomUserCreationForm(data=request.POST, request=self.request).


问:
auto_complete_for: prevent the first item from being auto-selected
The auto_complete_for dealio from script.aculo.us is great an all, but is there a way for me to selectively disable the fact that it always auto-selects the first item in the list?

The problem is that, if I want to type my own entry that is new, and novel, I don't want the first item in the list to be auto-selected. The reason is because when I TAB out of the field, it selects, and fills the text box with that first item.

I got around that, somewhat, by making the first item in the list the same as what I'm typing, but that's not perfect either, because the auto_complete list doesn't always update with every keystroke, depending on how fast I type. I've tried setting the list refresh rate to the lowest value (1 millisecond) but no go.

What I really want is an option in "auto_complete_for" that doesn't select that first item at all - the same way that Google Instant doesn't automatically select the first suggested search phrase - you have to arrow-down to select one.

Maybe I can do this via an HTML option that I'm missing?

答:
Looking at the source, there doesn't appear to be an option for that, but I bet if you changed line 284 of controls.js to this.index = -1; it would do what you want.

Otherwise, it might be time to look for a different autocomplete widget.


问:
Turn extraction list to csv file
I have uploaded a raster file and polyline shapefile into R and use the extract function to to extract the data from every pixel along the polyline. How do I turn the list output by extract into a CSV file?

Title: Turn extraction list to csv file

Body:
Here is a simple self-contained reproducible example (this one is taken from ?raster::extract)

library(raster)
r <- raster(ncol=36, nrow=18, vals=1:(18*36))
cds1 <- rbind(c(-50,0), c(0,60), c(40,5), c(15,-45), c(-10,-25))
cds2 <- rbind(c(80,20), c(140,60), c(160,0), c(140,-55))
lines <- spLines(cds1, cds2)
e <- extract(r, lines)

e is a list

> e
[[1]]
 [1] 126 127 161 162 163 164 196 197 200 201 231 232 237 266 267 273 274 302 310 311 338 346 381 382 414 417 450 451 452 453 487 488

[[2]]
 [1] 139 140 141 174 175 177 208 209 210 213 243 244 249 250 279 286 322 358 359 394 429 430 465 501 537

and you cannot directly write this to a csv because the list elements (vectors) have different lengths.

So first make them all the same length

x <- max(sapply(e, length))
ee <- sapply(e, `length<-`, x)

Let's see

head(ee)
#     [,1] [,2]
#[1,]  126  139
#[2,]  127  140
#[3,]  161  141
#[4,]  162  174
#[5,]  163  175
#[6,]  164  177
tail(ee)
#      [,1] [,2]
#[27,]  450   NA
#[28,]  451   NA
#[29,]  452   NA
#[30,]  453   NA
#[31,]  487   NA
#[32,]  488   NA

And now you can write to a csv file

write.csv(ee, "test.csv", row.names=FALSE)


问:
getting Error "Symfony\Component\HttpKernel\Exception\HttpException"
```<code>                     $.ajax({

                        method: 'post',
                        url: '{{url("admin/append-course-pricebox-div")}}',
                        data: {_token:{{csrf_token()}},count:boxCount,workshop_id:$("#workshop_id").val()},
                        cache : false,
                        contentType: false,
                        processData: false,
                        success: function (result) {
                            if (result.status == 'success') {
                                $('#success').html('Details are saved successfully.');
                                $('#success_popup .cd-popup').addClass('is-visible');
                            }else if(result.status =='blankTerm'){
                                $("#php-error_includes").show().html(result.message);
                            }
                            $('#preLoader').hide();
                        },
                        error: function (errors) {
                            $('#preLoader').hide();
                            var error = (JSON.parse(errors.responseText));
                            $.each(error.errors, function (key, val) {
                                $('#php-error_'+key).html(val);
                            });
                            $('.php-error').show();
                        }
                    });
</code>```

<p>when I post request it shows error and Google says it because of csrf error how I pass csrf_token to the controller </p>

答:
please follow this steps
1."_token": "{{ csrf_token() }}", pass csrf token in request
2.<meta name="csrf-token" content="{{ csrf_token() }}">
3.Detailed explaination can be found hereenter link description here

Body:
                     $.ajax({

                        method: 'post',
                        url: '{{url("admin/append-course-pricebox-div")}}',
                        data: {_token:{{csrf_token()}},count:boxCount,workshop_id:$("#workshop_id").val()},
                        cache : false,
                        contentType: false,
                        processData: false,
                        success: function (result) {
                            if (result.status == 'success') {
                                $('#success').html('Details are saved successfully.');
                                $('#success_popup .cd-popup').addClass('is-visible');
                            }else if(result.status =='blankTerm'){
                                $("#php-error_includes").show().html(result.message);
                            }
                            $('#preLoader').hide();
                        },
                        error: function (errors) {
                            $('#preLoader').hide();
                            var error = (JSON.parse(errors.responseText));
                            $.each(error.errors, function (key, val) {
                                $('#php-error_'+key).html(val);
                            });
                            $('.php-error').show();
                        }
                    });

when I post request it shows error and Google says it because of csrf error how I pass csrf_token to the controller