问:
Sending data from one view controller to another not working
I am trying to send some data from one view controller to another. But I can't seem to get this code to work! It should change a label to a variable that was passed to it but it doesn't change anything.

ViewController.swift

```<code>override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
    if segue.identifier == "SVCSegue" {
        let controller = segue.destination as! SecondViewController
        if let user = FIRAuth.auth()?.currentUser {
            controller.email = user.email
        }
    }
}
</code>```

SecondViewController.swift

```<code>@IBOutlet weak var usernameLabel: UILabel!

    var email:String!

    override func viewDidLoad() {
        super.viewDidLoad()

        // Do any additional setup after loading the view.

        self.usernameLabel.text = self.email

    }
</code>```

EDIT I also have this code AFTER override func prepare

```<code>@IBAction func loginAction(_ sender: Any) {

        if self.emailField.text == "" || self.passwordField.text == "" {
            let alertController = UIAlertController(title: "Oops!", message: "Please put in an email and password.", preferredStyle: .alert)
            let defaultAction = UIAlertAction(title: "Ok", style: .cancel, handler: nil)

            alertController.addAction(defaultAction)

            self.present(alertController, animated: true, completion: nil)
        } else {
            FIRAuth.auth()?.signIn(withEmail: self.emailField.text!, password: self.passwordField.text!, completion: { (user, error) in
                if error == nil {
                    self.emailField.text = ""
                    self.passwordField.text = ""
                } else {
                    let alertController = UIAlertController(title: "Oops!", message: error?.localizedDescription, preferredStyle: .alert)
                    let defaultAction = UIAlertAction(title: "Ok", style: .cancel, handler: nil)

                    alertController.addAction(defaultAction)
                }
            })
        }
    }
</code>```

答:
```<code>@IBAction func loginAction(_ sender: Any) {

        if self.emailField.text == "" || self.passwordField.text == "" {
            let alertController = UIAlertController(title: "Oops!", message: "Please put in an email and password.", preferredStyle: .alert)
            let defaultAction = UIAlertAction(title: "Ok", style: .cancel, handler: nil)

            alertController.addAction(defaultAction)

            self.present(alertController, animated: true, completion: nil)
        } else {
            FIRAuth.auth()?.signIn(withEmail: self.emailField.text!, password: self.passwordField.text!, completion: { (user, error) in
                if error == nil {
               let sb = UIStoryboard(name: "StoryBoardName", bundle: nil)
    let secVC = sb.instantiateViewController(withIdentifier: "ViewControllerIdentifier") as! SecondViewController
                 if let userValue = FIRAuth.auth()?.currentUser {
                        secVC.email = userValue.email!
                    }
       self.navigationController?.pushViewController(secVC, animated: true)
                } else {
                    let alertController = UIAlertController(title: "Oops!", message: error?.localizedDescription, preferredStyle: .alert)
                    let defaultAction = UIAlertAction(title: "Ok", style: .cancel, handler: nil)

                    alertController.addAction(defaultAction)
                }
            })
        }
    }

I have made change in loginAction() that is navigate to SecondViewController and pass data of user

Try above code , Hope this help you and solved your issue.
</code>```

Body:
I am trying to send some data from one view controller to another. But I can't seem to get this code to work! It should change a label to a variable that was passed to it but it doesn't change anything.

ViewController.swift

override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
    if segue.identifier == "SVCSegue" {
        let controller = segue.destination as! SecondViewController
        if let user = FIRAuth.auth()?.currentUser {
            controller.email = user.email
        }
    }
}

SecondViewController.swift

@IBOutlet weak var usernameLabel: UILabel!

    var email:String!

    override func viewDidLoad() {
        super.viewDidLoad()

        // Do any additional setup after loading the view.

        self.usernameLabel.text = self.email

    }

EDIT I also have this code AFTER override func prepare

@IBAction func loginAction(_ sender: Any) {

        if self.emailField.text == "" || self.passwordField.text == "" {
            let alertController = UIAlertController(title: "Oops!", message: "Please put in an email and password.", preferredStyle: .alert)
            let defaultAction = UIAlertAction(title: "Ok", style: .cancel, handler: nil)

            alertController.addAction(defaultAction)

            self.present(alertController, animated: true, completion: nil)
        } else {
            FIRAuth.auth()?.signIn(withEmail: self.emailField.text!, password: self.passwordField.text!, completion: { (user, error) in
                if error == nil {
                    self.emailField.text = ""
                    self.passwordField.text = ""
                } else {
                    let alertController = UIAlertController(title: "Oops!", message: error?.localizedDescription, preferredStyle: .alert)
                    let defaultAction = UIAlertAction(title: "Ok", style: .cancel, handler: nil)

                    alertController.addAction(defaultAction)
                }
            })
        }
    }


来源: stackexchange

问:
my stylesheet says to output as xml but instead its text
my stylesheet says to output as xml but instead its text

Any insight?

答:
The output is indeed XML. To verify this, right click in the browser and select "View source...".

But unfortunately most browsers choose to display the transformed XML by only showing its text content.

ContentLicense: CC BY-SA 3.0


问:
Silverlight PrtScr some controls
I need to programmatically PrtScr my controls in silverlight.(Save to bitmap)
How can i do this?</p>

答:
It also looks as though you can use this method in WriteableBitmap, although I have never tried it.

http://msdn.microsoft.com/en-us/library/system.windows.media.imaging.writeablebitmap.render(v=VS.95).aspx

ContentLicense: CC BY-SA 2.5

Title: Silverlight PrtScr some controls


问:
Maintaining a Min heap on deletion c++
Test case:

8,7,5,2,3,6,9 (NOT min heap) (this is element A* for buildHeap function)

2,3,5,7,8,6,9 (min heap after calling build heap)

3,5,6,7,8,9 (after calling deleteMin) THIS IS INCORRECT

it should be this 3,7,5,9,8,6

I can't seem to find the problem with deleteMin i know my heapify is working but idk maybe im not seeing something.

```<code> Element Heap::deleteMin(Heap& heap){
    Element deleted = heap.H[0];
    heap.H[0] = heap.H[heap.size-1];
    heap.size--;
    cout<<deleted.getKey()<<" has been deleted from heap"<<endl;
    for(int i=heap.capacity/2-1;i>=0;--i)
       heapify(heap,i);
    return deleted;
}

void Heap::heapify(Heap& heap,int index){
    int smallest = 0;
    int left = 2*index;
    int right = 2*index+1;

    if(left < heap.size && heap.H[left].getKey() < heap.H[index].getKey())
        smallest=left;
    else
       smallest=index;
    if(right < heap.size && heap.H[right].getKey() < heap.H[smallest].getKey())
        smallest=right;
    if(smallest != index){
        int swapKey = heap.H[index].getKey();
        heap.H[index].setKey(heap.H[smallest].getKey());
        heap.H[smallest].setKey(swapKey);
        heapify(heap,smallest);
    }
}

void Heap::buildHeap(Heap& heap, Element* A){
        for(int j=0;j<heap.capacity;++j){
                heap.insert(heap,A[j]);
                for(int i=heap.capacity/2-1;i>=0;--i)
                        heapify(heap,i);
        }
}
</code>```

答:
The first problem is that your calculations for child indexes are wrong. If you're using H[0] as the root of the heap, then

```<code>left = (2*index)+1
right = (2*index)+2
</code>```

The calculations you have assume that the root is at H[1].

The other problem is that you're doing too much work in your deleteMin function:

```<code>Element Heap::deleteMin(Heap& heap){
    Element deleted = heap.H[0];
    heap.H[0] = heap.H[heap.size-1];
    heap.size--;
    cout<<deleted.getKey()<<" has been deleted from heap"<<endl;
    for(int i=heap.capacity/2-1;i>=0;--i)
        heapify(heap,i);
    return deleted;
}
</code>```

After you delete the minimum item and put the last item in the heap at the root, you just need to call heapify(heap, 0); There's no reason to re-build the entire heap in that loop.

So your function becomes:

```<code>Element Heap::deleteMin(Heap& heap){
    Element deleted = heap.H[0];
    heap.H[0] = heap.H[heap.size-1];
    heap.size--;
    cout<<deleted.getKey()<<" has been deleted from heap"<<endl;
    heapify(heap, 0);
    return deleted;
}
</code>```

Your buildHeap method is similarly doing too much work.

You might be interested in a refresher on heaps. My blog article at http://blog.mischel.com/2013/09/29/a-better-way-to-do-it-the-heap/ explains their operation in very simple terms, and my simple heap of integers shows a bare-bones implementation. It's in C# rather than C++, but the code is very similar. You should be able to understand it without trouble.

Title: Maintaining a Min heap on deletion c++

Body:
Test case:

8,7,5,2,3,6,9 (NOT min heap) (this is element A* for buildHeap function)

2,3,5,7,8,6,9 (min heap after calling build heap)

3,5,6,7,8,9 (after calling deleteMin) THIS IS INCORRECT

it should be this 3,7,5,9,8,6

I can't seem to find the problem with deleteMin i know my heapify is working but idk maybe im not seeing something.

 Element Heap::deleteMin(Heap& heap){
    Element deleted = heap.H[0];
    heap.H[0] = heap.H[heap.size-1];
    heap.size--;
    cout<<deleted.getKey()<<" has been deleted from heap"<<endl;
    for(int i=heap.capacity/2-1;i>=0;--i)
       heapify(heap,i);
    return deleted;
}

void Heap::heapify(Heap& heap,int index){
    int smallest = 0;
    int left = 2*index;
    int right = 2*index+1;

    if(left < heap.size && heap.H[left].getKey() < heap.H[index].getKey())
        smallest=left;
    else
       smallest=index;
    if(right < heap.size && heap.H[right].getKey() < heap.H[smallest].getKey())
        smallest=right;
    if(smallest != index){
        int swapKey = heap.H[index].getKey();
        heap.H[index].setKey(heap.H[smallest].getKey());
        heap.H[smallest].setKey(swapKey);
        heapify(heap,smallest);
    }
}

void Heap::buildHeap(Heap& heap, Element* A){
        for(int j=0;j<heap.capacity;++j){
                heap.insert(heap,A[j]);
                for(int i=heap.capacity/2-1;i>=0;--i)
                        heapify(heap,i);
        }
}

Body:
The first problem is that your calculations for child indexes are wrong. If you're using H[0] as the root of the heap, then

left = (2*index)+1
right = (2*index)+2

The calculations you have assume that the root is at H[1].

The other problem is that you're doing too much work in your deleteMin function:

Element Heap::deleteMin(Heap& heap){
    Element deleted = heap.H[0];
    heap.H[0] = heap.H[heap.size-1];
    heap.size--;
    cout<<deleted.getKey()<<" has been deleted from heap"<<endl;
    for(int i=heap.capacity/2-1;i>=0;--i)
        heapify(heap,i);
    return deleted;
}

After you delete the minimum item and put the last item in the heap at the root, you just need to call heapify(heap, 0); There's no reason to re-build the entire heap in that loop.

So your function becomes:

Element Heap::deleteMin(Heap& heap){
    Element deleted = heap.H[0];
    heap.H[0] = heap.H[heap.size-1];
    heap.size--;
    cout<<deleted.getKey()<<" has been deleted from heap"<<endl;
    heapify(heap, 0);
    return deleted;
}

Your buildHeap method is similarly doing too much work.

You might be interested in a refresher on heaps. My blog article at http://blog.mischel.com/2013/09/29/a-better-way-to-do-it-the-heap/ explains their operation in very simple terms, and my simple heap of integers shows a bare-bones implementation. It's in C# rather than C++, but the code is very similar. You should be able to understand it without trouble.


问:
Does SSL_CTX_use_certificate copy used certificate bytes?
Does function SSL_CTX_use_certificate copy a certificate bytes?
Can I free the certificate memory by call X509_free(cert); after the function call?

```<code>    BIO *cbio = BIO_new_mem_buf((void*)cert_iter, first_cert_length);
    X509 *cert = PEM_read_bio_X509(cbio, NULL, 0, NULL);
    BIO_free(cbio);
    assert(cert != NULL);
    SSL_CTX_use_certificate(mSslServerRoleCtx.native_handle(), cert);
</code>```

答: According to OpenSSL on GitHub function ssl_set_cert uses X509_up_ref on the certificate. So I assume I can call X509_free(cert);

ContentLicense: CC BY-SA 4.0

Body:
Does function SSL_CTX_use_certificate copy a certificate bytes?
Can I free the certificate memory by call X509_free(cert); after the function call?

    BIO *cbio = BIO_new_mem_buf((void*)cert_iter, first_cert_length);
    X509 *cert = PEM_read_bio_X509(cbio, NULL, 0, NULL);
    BIO_free(cbio);
    assert(cert != NULL);
    SSL_CTX_use_certificate(mSslServerRoleCtx.native_handle(), cert);


问:
Some wired behavior for display inline block
Update
it's a question of whether inline-block elements contains something or not, You can search for it and find a better solution.

The page contains three div(gray rectangle) and the first div(parent) contains three blue child-div. Parent divs are inline-block, child-divs are also the same. Why the first parent-div is moved downwards? I'm supposed that they should be aligned in a line.

```<code><body>
    <section>
        <div class = "container">
            <div class = "load_1"></div>
            <div class = "load_1"></div>
            <div class = "load_1"></div>
        </div>
        <div class = "container">

        </div>
        <div class = "container">

        </div>
    </section>
</body>
</code>```

css

```<code>           section{
                width:100%;
                height:100vh;
                background-color: rgba(236, 240, 241,1.0);
            }
            div.container{
                display: inline-block;
                width:150px;
                height:150px;
                margin:10px;
                background-color: rgba(189, 195, 199,1.0);
                border-radius: 5px;
            }
            div.container:first-child{
                margin-left: 20px;
            }
            div.container .load_1{
                width:20px;
                height:20px;
                display: inline-block;
                background-color: rgba(52, 152, 219,1.0);
            }
</code>```

Please check here in JSfiddle.

答:
just put float:left on the div.container

check the code below:

    section {
        width: 100%;
        height: 100vh;
        background-color: rgba(236, 240, 241, 1.0);
    }

    div.container {
    /* display: inline-block; */
        width: 150px;
        height: 150px;
        margin: 10px;
        background-color: rgba(189, 195, 199, 1.0);
        border-radius: 5px;
        float: left;
    }

    div.container:first-child {
        margin-left: 20px;
    }

    div.container .load_1 {
        width: 20px;
        height: 20px;
        display: inline-block;
        background-color: rgba(52, 152, 219, 1.0);
    }```
<pre class="snippet-code-html lang-html prettyprint-override"><code><section>
    <div class="container">
        <div class="load_1"></div>
        <div class="load_1"></div>
        <div class="load_1"></div>
    </div>
    <div class="container">

    </div>
    <div class="container">

    </div>
</section></code>```

Body:
Update
it's a question of whether inline-block elements contains something or not, You can search for it and find a better solution.

The page contains three div(gray rectangle) and the first div(parent) contains three blue child-div. Parent divs are inline-block, child-divs are also the same. Why the first parent-div is moved downwards? I'm supposed that they should be aligned in a line.

css

           section{
                width:100%;
                height:100vh;
                background-color: rgba(236, 240, 241,1.0);
            }
            div.container{
                display: inline-block;
                width:150px;
                height:150px;
                margin:10px;
                background-color: rgba(189, 195, 199,1.0);
                border-radius: 5px;
            }
            div.container:first-child{
                margin-left: 20px;
            }
            div.container .load_1{
                width:20px;
                height:20px;
                display: inline-block;
                background-color: rgba(52, 152, 219,1.0);
            }

Please check here in JSfiddle.

Body:
just put float:left on the div.container

check the code below:

    section {
        width: 100%;
        height: 100vh;
        background-color: rgba(236, 240, 241, 1.0);
    }

    div.container {
    /* display: inline-block; */
        width: 150px;
        height: 150px;
        margin: 10px;
        background-color: rgba(189, 195, 199, 1.0);
        border-radius: 5px;
        float: left;
    }

    div.container:first-child {
        margin-left: 20px;
    }

    div.container .load_1 {
        width: 20px;
        height: 20px;
        display: inline-block;
        background-color: rgba(52, 152, 219, 1.0);
    }

<section>
    <div class="container">
        <div class="load_1"></div>
        <div class="load_1"></div>
        <div class="load_1"></div>
    </div>
    <div class="container">

    </div>
    <div class="container">

    </div>
</section>


问:
Html5 elements in .md file
I have a static html file with animations and different html5 tags. Is it possible to include this file (will all resources, images, js) in a jekyl blog post/page. More specifically, from .md file can I use include tag to use my static html5 file. I am very new to both jekyl, markdown. thnx</p>

答:
An HTML file can be included in Jekyll like this:

```<code>{% include note.html %}
</code>```

And it will load the file located at _includes/note.html. Or you can use relative directories to the one that is calling the include, for example, consider having index.md and we want to include another html file inside it called note.html:

Folder structure:

```<code>.
├── note.html
└── index.md
</code>```

Then in index.md:

```<code>---
title: example
---

{% include_relative note.html %}
</code>```

And when you access index.md it will display the content of note.html.

Title: Html5 elements in .md file

Body:
An HTML file can be included in Jekyll like this:

{% include note.html %}

And it will load the file located at _includes/note.html. Or you can use relative directories to the one that is calling the include, for example, consider having index.md and we want to include another html file inside it called note.html:

Folder structure:

.
├── note.html
└── index.md

Then in index.md:

---
title: example
---

{% include_relative note.html %}

And when you access index.md it will display the content of note.html.


问:
How to order user by registration date using WP_User_Query
I've to modify a query used in a Wordpress Theme because it's not orders users by their registration date.
I need to shown last subscribed users.
This query uses like ordering arg:

```<code>$args['orderby'] = 'rand'
</code>```

What's it means?

I sobstituite this code row with

```<code>$args['orderby'] = 'user_registered'
</code>```

but users shown aren't last subscribed users.

Can you help me, please?
Thank's!

答:
```<code>$args['orderby'] = 'registered'
</code>```

<p>try this </p>

Body:
I've to modify a query used in a Wordpress Theme because it's not orders users by their registration date.
I need to shown last subscribed users.
This query uses like ordering arg:

$args['orderby'] = 'rand'

What's it means?

I sobstituite this code row with

$args['orderby'] = 'user_registered'

but users shown aren't last subscribed users.

Can you help me, please?
Thank's!

Body:
$args['orderby'] = 'registered'

try this


问:
How to get the count of repeated value of some perticular attribute in array of object and store in Object
Suppose I have an array of Object.

code :

```<code>var arrayMap = [{continent: "Asia", Country: "China"},
{continent:"NAmerica", Country: "USA"},
{continent:"Asia", Country:"India"},
{continent:"Australia", Country:"Australia"},
{continent:"Asia", Country:"Japan"},
{continent:"Europe", Country:"UK"},
{continent:"SAmerica", Country:"Brazil"},
{continent:"Europe", Country:"Germany"},
{continent:"Asia", Country:"Rassia"},
{continent:"NAmerica", Country:"Canada"}]
</code>```

Now I have two attribute continent and Country in arrayMap in Obj. I want to the counts of country in all continent.
like :

```<code> Obj{Asia: 4, NAmerica:2, Australia:1, Europe:2, SAmerica:1}
</code>```

Can anybody help me how to get this.

答:
You can use reduce method to get the count.Doc for reduce method. Reduce

reduce() method used for reduce element of array into single value.

Code Example :

```<code>    var arrayMap = [{continent: "Asia", Country: "China"},{continent:"NAmerica", Country: "USA"},{continent:"Asia", Country:"India"},{continent:"Australia", Country:"Australia"},{continent:"Asia", Country:"Japan"},{continent:"Europe", Country:"UK"},{continent:"SAmerica", Country:"Brazil"},{continent:"Europe", Country:"Germany"},{continent:"Asia", Country:"Rassia"},{continent:"NAmerica", Country:"Canada"}];
    var answer = arrayMap.reduce(function(continent,Country){
        return continent[Country.continent] = (continent[Country.continent] || 0) + 1, continent }, {});
    console.log(answer);
</code>```

Body:
Suppose I have an array of Object.

code :

var arrayMap = [{continent: "Asia", Country: "China"},
{continent:"NAmerica", Country: "USA"},
{continent:"Asia", Country:"India"},
{continent:"Australia", Country:"Australia"},
{continent:"Asia", Country:"Japan"},
{continent:"Europe", Country:"UK"},
{continent:"SAmerica", Country:"Brazil"},
{continent:"Europe", Country:"Germany"},
{continent:"Asia", Country:"Rassia"},
{continent:"NAmerica", Country:"Canada"}]

Now I have two attribute continent and Country in arrayMap in Obj. I want to the counts of country in all continent.
like :

 Obj{Asia: 4, NAmerica:2, Australia:1, Europe:2, SAmerica:1}

Can anybody help me how to get this.

Body:
You can use reduce method to get the count.Doc for reduce method. Reduce

reduce() method used for reduce element of array into single value.

Code Example :

    var arrayMap = [{continent: "Asia", Country: "China"},{continent:"NAmerica", Country: "USA"},{continent:"Asia", Country:"India"},{continent:"Australia", Country:"Australia"},{continent:"Asia", Country:"Japan"},{continent:"Europe", Country:"UK"},{continent:"SAmerica", Country:"Brazil"},{continent:"Europe", Country:"Germany"},{continent:"Asia", Country:"Rassia"},{continent:"NAmerica", Country:"Canada"}];
    var answer = arrayMap.reduce(function(continent,Country){
        return continent[Country.continent] = (continent[Country.continent] || 0) + 1, continent }, {});
    console.log(answer);


问:
Cannot append to textarea after clearing value
I have a dropdown select that appends to a text area on change.  I set a simple button to clear it out which works but afterwords I cannot re-append from the dropdown select.

Fiddle: https://jsfiddle.net/kreza/noy5gqfL/6/

jquery snippet:

```<code>$('#criteriaSelect').change(function () {
    $('#inputCriteria').append((this.value + ';' + '\n'));
});
$('#clearTextArea').click(function () {
    $('#inputCriteria').val('');
});
</code>```

What am I doing wrong?

答:
values in textareas are set with .val(). try this:</p>

```<code>$('#criteriaSelect').change(function () {
    $('#inputCriteria').val((this.value + ';' + '\n'));
});
$('#clearTextArea').click(function () {
    $('#inputCriteria').val('');
});
</code>```

Body:
I have a dropdown select that appends to a text area on change.  I set a simple button to clear it out which works but afterwords I cannot re-append from the dropdown select.

Fiddle: https://jsfiddle.net/kreza/noy5gqfL/6/

jquery snippet:

$('#criteriaSelect').change(function () {
    $('#inputCriteria').append((this.value + ';' + '\n'));
});
$('#clearTextArea').click(function () {
    $('#inputCriteria').val('');
});

What am I doing wrong?

Body:
values in textareas are set with .val(). try this:

$('#criteriaSelect').change(function () {
    $('#inputCriteria').val((this.value + ';' + '\n'));
});
$('#clearTextArea').click(function () {
    $('#inputCriteria').val('');
});


问:
jQuery click event works only after the mouse is moved, while CSS hover is on (works as intended when hover is off)
I am having the same problem as this:
jQuery click event only working after moving the mouse in Chrome, but only on mac, OS X (I checked Chrome, Firefox, and Safari). It works as intended on Windows (I ignored IE for this one).

Here's my fiddle, where cells go darker on hover and change color on click (intended), but the color change on mac happens only after you've moved the mouse (unintended): https://jsfiddle.net/martakule/gh8t2m6n/2/

Now, the moment I comment out the hover, it works fine -- the color changes right on click. So is the problem that CSS hover and jQuery click don't work together on mac? What is it?

```<code>td:not(.main):hover {
    background: #cccccc;
    background: linear-gradient(to bottom right, #cccccc, #a6a6a6);
}
</code>```

答:
Try to add "!important" in some of your css rules:

```<code>#yes, td.yes {
  background: green !important;
  background: linear-gradient(to top right, green, yellowgreen) !important;
}
</code>```

and:

```<code>#no, td.no {
  background: red !important;
  background: linear-gradient(to bottom right, red, maroon) !important;
}
</code>```

(good thing I had my mac handy!)

Fiddle here: https://jsfiddle.net/s8c7qm7g/

Hope this is what you were looking for.

Body:
I am having the same problem as this:
jQuery click event only working after moving the mouse in Chrome, but only on mac, OS X (I checked Chrome, Firefox, and Safari). It works as intended on Windows (I ignored IE for this one).

Here's my fiddle, where cells go darker on hover and change color on click (intended), but the color change on mac happens only after you've moved the mouse (unintended): https://jsfiddle.net/martakule/gh8t2m6n/2/

Now, the moment I comment out the hover, it works fine -- the color changes right on click. So is the problem that CSS hover and jQuery click don't work together on mac? What is it?

td:not(.main):hover {
    background: #cccccc;
    background: linear-gradient(to bottom right, #cccccc, #a6a6a6);
}

Body:
Try to add "!important" in some of your css rules:

#yes, td.yes {
  background: green !important;
  background: linear-gradient(to top right, green, yellowgreen) !important;
}

and:

#no, td.no {
  background: red !important;
  background: linear-gradient(to bottom right, red, maroon) !important;
}

(good thing I had my mac handy!)

Fiddle here: https://jsfiddle.net/s8c7qm7g/

Hope this is what you were looking for.


问:
Sending email with spring fails on service
I'am working on a project(using spring boot) in which i need to send real time email notification, the email service is invoked in other class not in controller.
I receive an error that my service mail is null but when i put it in controller(RestController) it's working.
Where is my mistake?
is it possible to call for mail service in other class(services)?
For the process using RestController i used this example and as i said it's working, here is the link:
http://therealdanvega.com/blog/2016/01/13/sending-async-emails-in-spring</p>

答:
I receive an error that my service mail is null but when i put it in controller(RestController) it's working

It means that Spring didn't inject instance of the service into the controller. It's hard to help you in this case because you didn't provide neither error message nor controller code. I suggest to check the following

class member with service annotated with @Autowired (or @Inject)

bean with the mail service is defined in the application context

See also: Why is my Spring @Autowired field null?


问:
How to get values of multiple textboxes generated dynamically?
I have a button called 'AddTextArea', on clicking, I get new text area, but how can I get the values that I have entered in the new text areas?

I tried like this-

```<code>var x= document.getElementById("div_quotes").value;
</code>```

but it's not working.
Please help, as I am new to JS, thanks in advance.

  <form method="post">

    <input type="button" value="Add Text Area" onClick="addTextArea();">
    <input type="submit" name="submitted">
  </form>

```

答:
```<code>var x= document.getElementById("div_quotes").value;
</code>```

Above code will not work as div_quotes is a div and div do not have value property.

You will have to search for textareas in this div.

Sample

function addTextArea() {
  var div = document.getElementById('div_quotes');
  div.innerHTML += "<textarea name='new_quote[]' />";
  div.innerHTML += "\n
";
}

function validate(){
  var tas = document.querySelectorAll('#div_quotes  textarea[name="new_quote[]"]')
  for(var i = 0; i< tas.length; i++){
    console.log(tas[i].value)
  }
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><form method="post">
  <!--<input type="text" name="text_new_author" /><br />-->
  <div id="div_quotes"></div>
  <input type="button" value="Add Text Area" onClick="addTextArea();">
  <input type="button" name="submitted" onclick="validate()" value="Validate">
</form></code>```

Version 2

Now if you notice in above sample, if you type and then add another textarea, it will flush value of previous  ones. This is because, you are setting .innerHTML += .... This will destroy and recreate all elements again. You should use document.createElement

function addTextArea() {
  var div = document.getElementById('div_quotes');
  var wrapper = document.createElement('div')
  var ta = document.createElement('textarea');
  ta.name = "new_quote[]"
  wrapper.append(ta);
  div.append(wrapper)
}

function validate(){
  var tas = document.querySelectorAll('#div_quotes  textarea[name="new_quote[]"]')
  for(var i = 0; i< tas.length; i++){
    console.log(tas[i].value)
  }
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><form method="post">
  <!--<input type="text" name="text_new_author" /><br />-->
  <div id="div_quotes"></div>
  <input type="button" value="Add Text Area" onClick="addTextArea();">
  <input type="button" name="submitted" onclick="validate()" value="Validate">
</form></code>```

Body:
I have a button called 'AddTextArea', on clicking, I get new text area, but how can I get the values that I have entered in the new text areas?

I tried like this-

var x= document.getElementById("div_quotes").value;

but it's not working.
Please help, as I am new to JS, thanks in advance.

  <form method="post">

    <input type="button" value="Add Text Area" onClick="addTextArea();">
    <input type="submit" name="submitted">
  </form>

Body:
var x= document.getElementById("div_quotes").value;

Above code will not work as div_quotes is a div and div do not have value property.

You will have to search for textareas in this div.

Sample

function addTextArea() {
  var div = document.getElementById('div_quotes');
  div.innerHTML += "<textarea name='new_quote[]' />";
  div.innerHTML += "\n<br />";
}

function validate(){
  var tas = document.querySelectorAll('#div_quotes  textarea[name="new_quote[]"]')
  for(var i = 0; i< tas.length; i++){
    console.log(tas[i].value)
  }
}

<form method="post">
  <!--<input type="text" name="text_new_author" /><br />-->
  <div id="div_quotes"></div>
  <input type="button" value="Add Text Area" onClick="addTextArea();">
  <input type="button" name="submitted" onclick="validate()" value="Validate">
</form>

Version 2

Now if you notice in above sample, if you type and then add another textarea, it will flush value of previous  ones. This is because, you are setting .innerHTML += .... This will destroy and recreate all elements again. You should use document.createElement

function addTextArea() {
  var div = document.getElementById('div_quotes');
  var wrapper = document.createElement('div')
  var ta = document.createElement('textarea');
  ta.name = "new_quote[]"
  wrapper.append(ta);
  div.append(wrapper)
}

function validate(){
  var tas = document.querySelectorAll('#div_quotes  textarea[name="new_quote[]"]')
  for(var i = 0; i< tas.length; i++){
    console.log(tas[i].value)
  }
}

<form method="post">
  <!--<input type="text" name="text_new_author" /><br />-->
  <div id="div_quotes"></div>
  <input type="button" value="Add Text Area" onClick="addTextArea();">
  <input type="button" name="submitted" onclick="validate()" value="Validate">
</form>


问:
File attachments in Blocks?
Whats the best way to have file attachments in blocks like you can with nodes? Is this possible with an existing module?</p>

答: If your attachments are CCK File fields, you can use CCK Blocks module for this purpose.</p>

Title: File attachments in Blocks?


问:
Selecting column names and data types of columns as a table
I want to select column names of Table1 as rows of column1 of Table2 and data types of Table1 columns as rows of column2 of Table2.

So if Table1 is like this.

```<code>Name    Age Graduation Date
John    21  11.11.2015
Hillary 23  7.09.2015
</code>```

I want to get this table by query.

```<code>Name    String
Age Long
Graduation Date Date
</code>```

What should be my SQL query?

(I'm gonna use this in an Windows form application which uses OLEDB connection to get data from an mdb file.)

答:
I'm gonna use this in an Windows form application which uses OLEDB
  connection to get data from an mdb file

You can get the informations you need via con.GetOleDbSchemaTable:

```<code>using (OleDbConnection connection = new OleDbConnection(connectionString))
{
    connection.Open();

    DataTable tableColumns = connection.GetOleDbSchemaTable(OleDbSchemaGuid.Columns, new object[] { null, null, "Table1", null }));
    foreach (DataRow row in tableColumns.Rows)
    {
        var columnNameColumn = row["COLUMN_NAME"];
        var dateTypeColumn = row["DATA_TYPE"];
        var ordinalPositionColumn = row["ORDINAL_POSITION"];
        ...
    }
}
</code>```

You will find column-names and types in this DataTable. Ref.

Body:
I want to select column names of Table1 as rows of column1 of Table2 and data types of Table1 columns as rows of column2 of Table2.

So if Table1 is like this.

Name    Age Graduation Date
John    21  11.11.2015
Hillary 23  7.09.2015

I want to get this table by query.

Name    String
Age Long
Graduation Date Date

What should be my SQL query?

(I'm gonna use this in an Windows form application which uses OLEDB connection to get data from an mdb file.)

Body:
I'm gonna use this in an Windows form application which uses OLEDB
  connection to get data from an mdb file

You can get the informations you need via con.GetOleDbSchemaTable:

using (OleDbConnection connection = new OleDbConnection(connectionString))
{
    connection.Open();

    DataTable tableColumns = connection.GetOleDbSchemaTable(OleDbSchemaGuid.Columns, new object[] { null, null, "Table1", null }));
    foreach (DataRow row in tableColumns.Rows)
    {
        var columnNameColumn = row["COLUMN_NAME"];
        var dateTypeColumn = row["DATA_TYPE"];
        var ordinalPositionColumn = row["ORDINAL_POSITION"];
        ...
    }
}

You will find column-names and types in this DataTable. Ref.


问:
Python script only writes partial results to file
I have a little python script that I wrote to populate my proxychains.conf file with valid public proxies. For each request, 10 proxies are retrieved and added to proxychains.conf, and this is done 3 times so that a total of 30 proxies are added.

When I was writing the script and having results return to stdout everything worked as expected = 30 proxies were retrieved and returned. However when I added the file operations part of the script only 10 proxies are written to the file. I'm still learning Python and I've tried to rearrange some things but it's not working out. I can't figure out if :

my counter is in the wrong place?

my file operations are in the wrong place?

Here is the code:

```<code>#!/usr/bin/env python3

import requests
import sys,os

proxy_file = '/etc/proxychains.conf'
base_url = 'http://proxy.tekbreak.com/10/json'
headers = {'user-agent':'Mozilla/5.0 (Windows NT x.y; Win64; x64; rv:10.0) Gecko/20'}

def fetchprox():
    pf = open(proxy_file, 'r')
    lines = pf.readlines()
    pf.close()
    with open (proxy_file, 'w') as f:
        del lines[69:]
        f.writelines([item for item in lines[:-1]])
        r = requests.get(base_url, headers=headers)
        n = 0
        while n < 10:
            ip = r.json()[n]['ip']
            port = r.json()[n]['port']
            p_type = r.json()[n]['type']

         #output to proxychains.conf
            f.writelines(str(p_type + " " + ip + " " + port + "\n"))
            n += 1

for i in range(0,3):
    fetchprox()
</code>```

Thanks for the help!

EDIT
I found a solution based off of Giordano's answer, however I believe it could be implemented better. It seems redundant to have to access this file 3 times to just to write some data. So here is the portion of the script that was changed:

```<code><--snip->
pf = open(proxy_file, 'r')
lines = pf.readlines()
pf.close()

f = open (proxy_file, 'w')
del lines[69:]
f.writelines([item for item in lines[:-2]])
f.close()

def fetchprox():
    with open (proxy_file, 'a') as f:
        r = requests.get(base_url, headers=headers)
        n = 0
        while n < 10:
<--snip-->
</code>```

so is there a more efficient way to accomplish this?

答:
Your script is correct, but as I mentioned in a comment, you overwrite your file each loop.

More in detail, the wrong line is the following:

```<code>with open (proxy_file, 'w') as f:
</code>```

With w, you write a file, but if it is not empty, you overwrite the content.

To fix it you can use append mode in this way:

```<code>with open (proxy_file, 'a') as f:
</code>```

append does not overwrite the content of the file but adds new lines.

Answer after edit

First of all you can use with to open a file, and so i've removed also .close() because with handle closure automatically.
I also changed the while loop with a for loop in this way:

```<code>lines = None
with open(proxy_file, 'r') as pf:
    lines = pf.readlines()

with open (proxy_file, 'w') as f:
    del lines[69:]
    f.writelines([item for item in lines[:-2]])

def fetchprox():
    with open (proxy_file, 'a') as f:
        data = requests.get(base_url, headers=headers).json()
        for element in data:
            ip = element['ip']
            port = element['port']
            p_type = element['type']

            #output to proxychains.conf
            f.writelines(str(p_type + " " + ip + " " + port + "\n"))

for i in range(0,3):
    fetchprox()
</code>```

Second edit

If you want remove one access to the file, you can use r+ mode in this way:

```<code>lines = None
with open(proxy_file, 'r+') as pf:
    lines = pf.readlines()
    del lines[69:]
    pf.writelines([item for item in lines[:-2]])
...
</code>```

With r+ you can read and write, opening one time the file.

Body:
I have a little python script that I wrote to populate my proxychains.conf file with valid public proxies. For each request, 10 proxies are retrieved and added to proxychains.conf, and this is done 3 times so that a total of 30 proxies are added.

When I was writing the script and having results return to stdout everything worked as expected = 30 proxies were retrieved and returned. However when I added the file operations part of the script only 10 proxies are written to the file. I'm still learning Python and I've tried to rearrange some things but it's not working out. I can't figure out if :

my counter is in the wrong place?

my file operations are in the wrong place?

Here is the code:

#!/usr/bin/env python3

import requests
import sys,os

proxy_file = '/etc/proxychains.conf'
base_url = 'http://proxy.tekbreak.com/10/json'
headers = {'user-agent':'Mozilla/5.0 (Windows NT x.y; Win64; x64; rv:10.0) Gecko/20'}

def fetchprox():
    pf = open(proxy_file, 'r')
    lines = pf.readlines()
    pf.close()
    with open (proxy_file, 'w') as f:
        del lines[69:]
        f.writelines([item for item in lines[:-1]])
        r = requests.get(base_url, headers=headers)
        n = 0
        while n < 10:
            ip = r.json()[n]['ip']
            port = r.json()[n]['port']
            p_type = r.json()[n]['type']

         #output to proxychains.conf
            f.writelines(str(p_type + " " + ip + " " + port + "\n"))
            n += 1

for i in range(0,3):
    fetchprox()

Thanks for the help!

EDIT
I found a solution based off of Giordano's answer, however I believe it could be implemented better. It seems redundant to have to access this file 3 times to just to write some data. So here is the portion of the script that was changed:

<--snip->
pf = open(proxy_file, 'r')
lines = pf.readlines()
pf.close()

f = open (proxy_file, 'w')
del lines[69:]
f.writelines([item for item in lines[:-2]])
f.close()

def fetchprox():
    with open (proxy_file, 'a') as f:
        r = requests.get(base_url, headers=headers)
        n = 0
        while n < 10:
<--snip-->

so is there a more efficient way to accomplish this?

Body:
Your script is correct, but as I mentioned in a comment, you overwrite your file each loop.

More in detail, the wrong line is the following:

with open (proxy_file, 'w') as f:

With w, you write a file, but if it is not empty, you overwrite the content.

To fix it you can use append mode in this way:

with open (proxy_file, 'a') as f:

append does not overwrite the content of the file but adds new lines.

Answer after edit

First of all you can use with to open a file, and so i've removed also .close() because with handle closure automatically.
I also changed the while loop with a for loop in this way:

lines = None
with open(proxy_file, 'r') as pf:
    lines = pf.readlines()

with open (proxy_file, 'w') as f:
    del lines[69:]
    f.writelines([item for item in lines[:-2]])

def fetchprox():
    with open (proxy_file, 'a') as f:
        data = requests.get(base_url, headers=headers).json()
        for element in data:
            ip = element['ip']
            port = element['port']
            p_type = element['type']

            #output to proxychains.conf
            f.writelines(str(p_type + " " + ip + " " + port + "\n"))

for i in range(0,3):
    fetchprox()

Second edit

If you want remove one access to the file, you can use r+ mode in this way:

lines = None
with open(proxy_file, 'r+') as pf:
    lines = pf.readlines()
    del lines[69:]
    pf.writelines([item for item in lines[:-2]])
...

With r+ you can read and write, opening one time the file.


问:
.NET Core how to test with net461 and xunit
dotnet new xunit ->
dotnet restore ->
dotnet test

Total tests: 1. Passed: 1. Failed: 0. Skipped: 0.
Test Run Successful.
Test execution time: 1,7148 Seconds.

.csproj; change target framework to net461:

```<code>  <PropertyGroup>
    <TargetFramework>net461</TargetFramework>
  </PropertyGroup>

  <ItemGroup>
    <PackageReference Include="Microsoft.NET.Test.Sdk" Version="15.0.0" />
    <PackageReference Include="xunit" Version="2.2.0" />
    <PackageReference Include="xunit.runner.visualstudio" Version="2.2.0" />
  </ItemGroup>

</Project>
</code>```

then
dotnet restore ->
dotnet test

```<code>Starting test execution, please wait...
No test is available in C:\Projects\testing\bin\Debug\net461\testing.dll. Make sure that installed test discoverers & executors, platform & framework version sett
ings are appropriate and try again.
</code>```

How am I supposed to test net461-projects with xunit?
I already have a big project I've upgraded from .NET Core 1.0, and testing worked fine before the upgrade, so changing test framework would require some work.

Update

As it turns out, this is probably not related to xunit and testing - ASP.NET Core projects targeting net461 won't run at all on my machine anymore, neither through VS or from cmd.

The project I am trying to run is an new empty web project from the VS template. The csproj looks like this:

```<code><Project Sdk="Microsoft.NET.Sdk.Web">

  <PropertyGroup>
    <TargetFramework>net461</TargetFramework>
    <RuntimeIdentifier>win7-x86</RuntimeIdentifier>
  </PropertyGroup>

  <ItemGroup>
    <Folder Include="wwwroot\" />
  </ItemGroup>
  <ItemGroup>
    <PackageReference Include="Microsoft.ApplicationInsights.AspNetCore" Version="2.0.0" />
    <PackageReference Include="Microsoft.AspNetCore" Version="1.1.1" />
  </ItemGroup>

</Project>
</code>```

The error I get is this:

```<code>dotnet run

Unhandled Exception: System.IO.FileNotFoundException: Could not load file or assembly 'Microsoft.AspNetCore.Hosting, Version=1.1.1.0, Culture=neutral, PublicKeyTo
ken=adb9793829ddae60' or one of its dependencies. The system cannot find the file specified.
   at WebApplication2.Program.Main(String[] args)
</code>```

I have tried removing all traces of Visual Studio and .NET Core from my machine and reinstalling them, but the error is the same.

答:
Yeah, I've experienced the same issue. Not sure if Microsoft already has a fix available, but it seems that some packages of ASP.NET Core 1.1.x are targeting NetStandard Library 1.6.1, which is not compatible with .NET Framework... See the matrix on MS website here: https://learn.microsoft.com/en-us/dotnet/articles/standard/library#net-platforms-support

We've decided to stick to ASP.NET Core 1.0.x for now.

Body:
dotnet new xunit ->
dotnet restore ->
dotnet test

Total tests: 1. Passed: 1. Failed: 0. Skipped: 0.
Test Run Successful.
Test execution time: 1,7148 Seconds.

.csproj; change target framework to net461:

  <PropertyGroup>
    <TargetFramework>net461</TargetFramework>
  </PropertyGroup>

  <ItemGroup>
    <PackageReference Include="Microsoft.NET.Test.Sdk" Version="15.0.0" />
    <PackageReference Include="xunit" Version="2.2.0" />
    <PackageReference Include="xunit.runner.visualstudio" Version="2.2.0" />
  </ItemGroup>

</Project>

then
dotnet restore ->
dotnet test

Starting test execution, please wait...
No test is available in C:\Projects\testing\bin\Debug\net461\testing.dll. Make sure that installed test discoverers & executors, platform & framework version sett
ings are appropriate and try again.

How am I supposed to test net461-projects with xunit?
I already have a big project I've upgraded from .NET Core 1.0, and testing worked fine before the upgrade, so changing test framework would require some work.

Update

As it turns out, this is probably not related to xunit and testing - ASP.NET Core projects targeting net461 won't run at all on my machine anymore, neither through VS or from cmd.

The project I am trying to run is an new empty web project from the VS template. The csproj looks like this:

<Project Sdk="Microsoft.NET.Sdk.Web">

  <PropertyGroup>
    <TargetFramework>net461</TargetFramework>
    <RuntimeIdentifier>win7-x86</RuntimeIdentifier>
  </PropertyGroup>

  <ItemGroup>
    <Folder Include="wwwroot\" />
  </ItemGroup>
  <ItemGroup>
    <PackageReference Include="Microsoft.ApplicationInsights.AspNetCore" Version="2.0.0" />
    <PackageReference Include="Microsoft.AspNetCore" Version="1.1.1" />
  </ItemGroup>

</Project>

The error I get is this:

dotnet run

Unhandled Exception: System.IO.FileNotFoundException: Could not load file or assembly 'Microsoft.AspNetCore.Hosting, Version=1.1.1.0, Culture=neutral, PublicKeyTo
ken=adb9793829ddae60' or one of its dependencies. The system cannot find the file specified.
   at WebApplication2.Program.Main(String[] args)

I have tried removing all traces of Visual Studio and .NET Core from my machine and reinstalling them, but the error is the same.


问:
Convert value to as many decimal places in iOS?
I have string which has a double values as 2.344.Now i want to have as many decimal places for this number as i get from server.So i maxdecimalPlaces is 2 then i want to have number as 2.34 if maxdecimalplaces is 3 then i want to have number as 2.344.

I don't want to use [NSString StringwithFormat:@"%.2f",value];
because number of decimal places is dynamic.Please tell how can i resolve this issue,

答:
i maxdecimalPlaces is 2 then i want to have number as 2.34 if maxdecimalplaces is 3 then i want to have number as 2.344

use setMaximumFractionDigits: and pass the  maxdecimalPlaces

```<code>  float inputValue = 2.344;
 NSNumberFormatter *Formatter = [[NSNumberFormatter alloc] init];
 [Formatter setNumberStyle:NSNumberFormatterDecimalStyle];
 [Formatter setMaximumFractionDigits:maxdecimalPlaces];
 NSString *finalOutput = [Formatter stringFromNumber:[NSNumber numberWithFloat:inputValue]];
 NSLog(@"finalOutput: %@", finalOutput)
</code>```

Body:
i maxdecimalPlaces is 2 then i want to have number as 2.34 if maxdecimalplaces is 3 then i want to have number as 2.344

use setMaximumFractionDigits: and pass the  maxdecimalPlaces

  float inputValue = 2.344;
 NSNumberFormatter *Formatter = [[NSNumberFormatter alloc] init];
 [Formatter setNumberStyle:NSNumberFormatterDecimalStyle];
 [Formatter setMaximumFractionDigits:maxdecimalPlaces];
 NSString *finalOutput = [Formatter stringFromNumber:[NSNumber numberWithFloat:inputValue]];
 NSLog(@"finalOutput: %@", finalOutput)


问:
Deep copy an array in Angular 2 + TypeScript
I have an array of objects that is an input. Lets call it content.

When trying to deep copy it, it still has a reference to the previous array.

I need to duplicate that input array, and change one property of the duplicated part.

So long I've tried different methods that weren't successful.

ES6 way:

```<code>public duplicateArray() {
  arr = [...this.content]
  arr.map((x) => {x.status = DEFAULT});
  return this.content.concat(arr);
}
</code>```

The slice way:

```<code>public duplicateArray() {
  arr = this.content.slice(0);
  arr.map((x) => {x.status = DEFAULT});
  return this.content.concat(arr);
}
</code>```

In both of them all the objects inside the array have status: 'Default'.

What's the best approach to deep copy the array in Angular 2?

答:
Check this:</p>

```<code>  let cloned = source.map(x => Object.assign({}, x));
</code>```

Body:
I have an array of objects that is an input. Lets call it content.

When trying to deep copy it, it still has a reference to the previous array.

I need to duplicate that input array, and change one property of the duplicated part.

So long I've tried different methods that weren't successful.

ES6 way:

public duplicateArray() {
  arr = [...this.content]
  arr.map((x) => {x.status = DEFAULT});
  return this.content.concat(arr);
}

The slice way:

public duplicateArray() {
  arr = this.content.slice(0);
  arr.map((x) => {x.status = DEFAULT});
  return this.content.concat(arr);
}

In both of them all the objects inside the array have status: 'Default'.

What's the best approach to deep copy the array in Angular 2?

Body:
Check this:

  let cloned = source.map(x => Object.assign({}, x));


问:
Excel VBA Deleting rows based upon date
I have a question about the code in this thread

Excel VBA: Delete Old Records

In that thread, is this code

```<code>    Sub ClearOldData()
    Application.ScreenUpdating = False
    Dimi As Long

    With Sheets("Data")

        For i = 2 To LastRow Step -1
            If Int(Date - Cells(i, "F").Value) > 179 Then
                .Rows(i).Delete
            End If
        Next i

    End With
    Application.ScreenUpdating = True
End Sub
</code>```

The problem I am running into is that when I run this code, I receive the following error:

Compile error: Statement invalid outside Type block

Upon first look, the Dim looks to be incorrect as it is listed as Dimi and I can find no reference to VBA using something like that. I changed it to Dim and it still gives the error. This code appears to be correct in all I have researched on this, but I am scratching my head over where the hiccup is at. Anyone have an idea where it is going sideways at?

Thanks

答:
Try the code below, even with 1000 lines, it runs in less than 2 seconds (because you turn Application.ScreenUpdating = False)

Code

```<code>Option Explicit

Sub ClearOldData()

    Application.ScreenUpdating = False
    Dim i As Long
    Dim LastRow As Long

    With Sheets("Data")
        LastRow = .Cells(.Rows.Count, "F").End(xlUp).Row ' <-- get last row with data from column F

        For i = LastRow To 2 Step -1 ' always loop backwards when deleting cells/ranges/rows
            If DateDiff("d", .Range("F" & i).Value, Date) > 179 Then ' older than 179 days
                .Rows(i).Delete
            End If
        Next i
    End With
    Application.ScreenUpdating = True

End Sub
</code>```

Title: Excel VBA Deleting rows based upon date

Body:
I have a question about the code in this thread

Excel VBA: Delete Old Records

In that thread, is this code

    Sub ClearOldData()
    Application.ScreenUpdating = False
    Dimi As Long

    With Sheets("Data")

        For i = 2 To LastRow Step -1
            If Int(Date - Cells(i, "F").Value) > 179 Then
                .Rows(i).Delete
            End If
        Next i

    End With
    Application.ScreenUpdating = True
End Sub

The problem I am running into is that when I run this code, I receive the following error:

Compile error: Statement invalid outside Type block

Upon first look, the Dim looks to be incorrect as it is listed as Dimi and I can find no reference to VBA using something like that. I changed it to Dim and it still gives the error. This code appears to be correct in all I have researched on this, but I am scratching my head over where the hiccup is at. Anyone have an idea where it is going sideways at?

Thanks

Body:
Try the code below, even with 1000 lines, it runs in less than 2 seconds (because you turn Application.ScreenUpdating = False)

Code

Option Explicit

Sub ClearOldData()

    Application.ScreenUpdating = False
    Dim i As Long
    Dim LastRow As Long

    With Sheets("Data")
        LastRow = .Cells(.Rows.Count, "F").End(xlUp).Row ' <-- get last row with data from column F

        For i = LastRow To 2 Step -1 ' always loop backwards when deleting cells/ranges/rows
            If DateDiff("d", .Range("F" & i).Value, Date) > 179 Then ' older than 179 days
                .Rows(i).Delete
            End If
        Next i
    End With
    Application.ScreenUpdating = True

End Sub


问:
sails.js - change public folder to be different than .tmp/public
I reworked sails.js assets flow to fit my needs. I am storing my public assets in /assets/dist.

Is there any easy way to configurate sails app to use my own public folder instead of default "/.tmp/public"?

I know there is option to configure this via /config/local.js, but i want configure this elsewhere(if possible) so it will not be related just to current machine and it will be included in git repo.

答:
The previous answer clearly doesn't work on latest versions of sails.js. According this you cannot change paths unless you use the .sailsrc.

eg:

```<code>{
  "paths": {
        "tmp": "dist/assets",
        "public": "dist/assets"
    }
}
</code>```

Body:
The previous answer clearly doesn't work on latest versions of sails.js. According this you cannot change paths unless you use the .sailsrc.

eg:

{
  "paths": {
        "tmp": "dist/assets",
        "public": "dist/assets"
    }
}


问:
re-assign vim buffer number
I have vim buffers like this:

```<code>1 "file1.txt"
2 "file2.txt"
3 "file3.txt"
</code>```

and I want re-assign buffer numbers like this:

```<code>1 "file2.txt"
2 "file1.txt"
3 "file3.txt"
</code>```

How do I do this?

答:
From :help :ls:

Each buffer has a unique number.
  That number will not change,      so you
  can always go to a specific buffer
  with ":buffer N" or       "N CTRL-^",
  where N is the buffer number.

Why do you need to reassign those numbers? Maybe there is another thing to do to help you in your task?

Title: re-assign vim buffer number

Body:
I have vim buffers like this:

1 "file1.txt"
2 "file2.txt"
3 "file3.txt"

and I want re-assign buffer numbers like this:

1 "file2.txt"
2 "file1.txt"
3 "file3.txt"

How do I do this?


问:
Swift: Alamofire + Nutritionix API
I'm trying to use Alamofire 3.3 with the Nutritionix API.
I was able to get a few requests going however i'm having issues to get usda_fields.

```<code>var params = [
        "appId" : MY_APP_ID,
        "appKey" : MY_APP_KEY,
        "fields" : ["item_name", "brand_name", "keywords", "usda_fields"],
        "limit" : "50",
        "query" : searchString,
        "filters" : ["exists":["usda_fields": true]]
    ]

Alamofire.request(.GET, "https://api.nutritionix.com/v1_1/search/", parameters: params)
        .responseData { response in
            print(response.request)
            print(response.response)
            print(response.result)
}
</code>```

For some reason I realized that 'fields' shouldn't be in an array and just follow each others separated by a coma. Then the query return something however the filter doesn't seem to work.

Any help appreciated thanks!

答:
If you are still looking to solve this, I recommend trying the 2.0 version of our API instead of the 1.1 version.  Here are the details:
https://developer.nutritionix.com/docs/v2

Feel free to email us at api at nutritionix dot com if you have more questions about the API!

Title: Swift: Alamofire + Nutritionix API

Body:
I'm trying to use Alamofire 3.3 with the Nutritionix API.
I was able to get a few requests going however i'm having issues to get usda_fields.

var params = [
        "appId" : MY_APP_ID,
        "appKey" : MY_APP_KEY,
        "fields" : ["item_name", "brand_name", "keywords", "usda_fields"],
        "limit" : "50",
        "query" : searchString,
        "filters" : ["exists":["usda_fields": true]]
    ]

Alamofire.request(.GET, "https://api.nutritionix.com/v1_1/search/", parameters: params)
        .responseData { response in
            print(response.request)
            print(response.response)
            print(response.result)
}

For some reason I realized that 'fields' shouldn't be in an array and just follow each others separated by a coma. Then the query return something however the filter doesn't seem to work.

Any help appreciated thanks!


答:
Hello,

Check if this is what you need:

Code Example:

```<code>var obj = { };
for (var i = 0, j = arrayMap.length; i < j; i++) {
   obj[arrayMap[i].continent] = (obj[arrayMap[i].continent] || 0) + 1;
}
console.log(obj);
</code>```

Result:

```<code>Object {Asia: 4, NAmerica: 2, Australia: 1, Europe: 2, SAmerica: 1}
</code>```

I hope I have helped!

Title: How to get the count of repeated value of some perticular attribute in array of object and store in Object

Body:
Suppose I have an array of Object.

code :

var arrayMap = [{continent: "Asia", Country: "China"},
{continent:"NAmerica", Country: "USA"},
{continent:"Asia", Country:"India"},
{continent:"Australia", Country:"Australia"},
{continent:"Asia", Country:"Japan"},
{continent:"Europe", Country:"UK"},
{continent:"SAmerica", Country:"Brazil"},
{continent:"Europe", Country:"Germany"},
{continent:"Asia", Country:"Rassia"},
{continent:"NAmerica", Country:"Canada"}]

Now I have two attribute continent and Country in arrayMap in Obj. I want to the counts of country in all continent.
like :

 Obj{Asia: 4, NAmerica:2, Australia:1, Europe:2, SAmerica:1}

Can anybody help me how to get this.

Body:
Hello,

Check if this is what you need:

Code Example:

var obj = { };
for (var i = 0, j = arrayMap.length; i < j; i++) {
   obj[arrayMap[i].continent] = (obj[arrayMap[i].continent] || 0) + 1;
}
console.log(obj);

Result:

Object {Asia: 4, NAmerica: 2, Australia: 1, Europe: 2, SAmerica: 1}

I hope I have helped!


问:
how to open a particular folder using javascript,any possible to using the file handlers here
In PHP we used opendir and readdir tag for read the folders. But in javascript can I do it?

The below code uses the fopen statement to read the directory and fread tag is used to read the folder list of files from that given directory. I have tried in javascript but no responses.

```<code>var d = fopen(foldername);
var r = fread(d);
document.write(r);
</code>```

In google mostly seen fopen and fread for using the particular folders,but I cant get it to work. I want to open a particular directory I want to using the directory files like images

答:
Using ShellExecute function defined by Shell.application method ,you can open any folder

Here is the Simple sample code,

var open = new ActiveXObject("shell.application");

open.ShellExecute(""C:\\WINDOWS\system32\\", "", "", "open", 3);

Refer the following Link for more info :

https://msdn.microsoft.com/en-us/library/windows/desktop/gg537745(v=vs.85).aspx

Body:
In PHP we used opendir and readdir tag for read the folders. But in javascript can I do it?

The below code uses the fopen statement to read the directory and fread tag is used to read the folder list of files from that given directory. I have tried in javascript but no responses.

var d = fopen(foldername);
var r = fread(d);
document.write(r);

In google mostly seen fopen and fread for using the particular folders,but I cant get it to work. I want to open a particular directory I want to using the directory files like images


问:
Error inflating class android.support.v7.widget.Toolbar?
I am trying to get Material Design for my App by following this method.

Whenever I run the App it shows the following error:

Error inflating class android.support.v7.widget.Toolbar.

I checked whether I have added the appcompat properly. But it is all Correct to me. So please tell me what am I doing wrong ?

build.gradle

```<code>apply plugin: 'com.android.application'

android {
    compileSdkVersion 21
    buildToolsVersion '21.0.2'

    defaultConfig {
        applicationId "io.bxbxbai.feedlistviewdemo"
        minSdkVersion 14
        targetSdkVersion 21
        versionCode 1
        versionName "1.0"
    }
    buildTypes {
        release {
            runProguard false
            proguardFiles 'proguard-rules.pro'
        }
    }
}

configurations {
    all*.exclude group: 'com.android.support', module: 'support-v4'
}

dependencies {
    compile fileTree(include: ['*.jar'], dir: 'libs')
    compile project(':materialDesign')
    compile 'com.balysv.materialmenu:material-menu:1.4.0'
    compile 'com.android.support:appcompat-v7:21.+'
}
</code>```

Logcat

```<code>02:11.641  20583-20583/io.bxbxbai.feedlistviewdemo E/AndroidRuntime﹕ FATAL EXCEPTION: main
    Process: io.bxbxbai.feedlistviewdemo, PID: 20583
    java.lang.RuntimeException: Unable to start activity ComponentInfo{io.bxbxbai.feedlistviewdemo/io.bxbxbai.androiddemos.MainActivity}: android.view.InflateException: Binary XML file line #3: Error inflating class android.support.v7.widget.Toolbar
            at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2224)
            at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2283)
            at android.app.ActivityThread.access$800(ActivityThread.java:144)
            at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1205)
            at android.os.Handler.dispatchMessage(Handler.java:102)
            at android.os.Looper.loop(Looper.java:136)
            at android.app.ActivityThread.main(ActivityThread.java:5158)
            at java.lang.reflect.Method.invokeNative(Native Method)
            at java.lang.reflect.Method.invoke(Method.java:515)
            at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:796)
            at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:612)
            at dalvik.system.NativeStart.main(Native Method)
     Caused by: android.view.InflateException: Binary XML file line #3: Error inflating class android.support.v7.widget.Toolbar
            at android.view.LayoutInflater.createView(LayoutInflater.java:620)
            at android.view.LayoutInflater.createViewFromTag(LayoutInflater.java:696)
            at android.view.LayoutInflater.parseInclude(LayoutInflater.java:816)
            at android.view.LayoutInflater.rInflate(LayoutInflater.java:745)
            at android.view.LayoutInflater.inflate(LayoutInflater.java:492)
            at android.view.LayoutInflater.inflate(LayoutInflater.java:397)
            at android.view.LayoutInflater.inflate(LayoutInflater.java:353)
            at android.support.v7.app.ActionBarActivityDelegateBase.setContentView(ActionBarActivityDelegateBase.java:228)
            at android.support.v7.app.ActionBarActivity.setContentView(ActionBarActivity.java:102)
            at io.bxbxbai.androiddemos.MainActivity.onCreate(MainActivity.java:31)
            at android.app.Activity.performCreate(Activity.java:6144)
            at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1087)
            at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2181)
            at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2283)
            at android.app.ActivityThread.access$800(ActivityThread.java:144)
            at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1205)
            at android.os.Handler.dispatchMessage(Handler.java:102)
            at android.os.Looper.loop(Looper.java:136)
            at android.app.ActivityThread.main(ActivityThread.java:5158)
            at java.lang.reflect.Method.invokeNative(Native Method)
            at java.lang.reflect.Method.invoke(Method.java:515)
            at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:796)
            at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:612)
            at dalvik.system.NativeStart.main(Native Method)
     Caused by: java.lang.reflect.InvocationTargetException
            at java.lang.reflect.Constructor.constructNative(Native Method)
            at java.lang.reflect.Constructor.newInstance(Constructor.java:423)
            at android.view.LayoutInflater.createView(LayoutInflater.java:594)
            at android.view.LayoutInflater.createViewFromTag(LayoutInflater.java:696)
            at android.view.LayoutInflater.parseInclude(LayoutInflater.java:816)
            at android.view.LayoutInflater.rInflate(LayoutInflater.java:745)
            at android.view.LayoutInflater.inflate(LayoutInflater.java:492)
            at android.view.LayoutInflater.inflate(LayoutInflater.java:397)
            at android.view.LayoutInflater.inflate(LayoutInflater.java:353)
            at android.support.v7.app.ActionBarActivityDelegateBase.setContentView(ActionBarActivityDelegateBase.java:228)
            at android.support.v7.app.ActionBarActivity.setContentView(ActionBarActivity.java:102)
            at io.bxbxbai.androiddemos.MainActivity.onCreate(MainActivity.java:31)
            at android.app.Activity.performCreate(Activity.java:6144)
            at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1087)
            at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2181)
            at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2283)
            at android.app.ActivityThread.access$800(ActivityThread.java:144)
            at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1205)
            at android.os.Handler.dispatchMessage(Handler.java:102)
            at android.os.Looper.loop(Looper.java:136)
            at android.app.ActivityThread.main(ActivityThread.java:5158)
            at java.lang.reflect.Method.invokeNative(Native Method)
            at java.lang.reflect.Method.invoke(Method.java:515)
            at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:796)
            at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:612)
            at dalvik.system.NativeStart.main(Native Method)
     Caused by: java.lang.NoSuchMethodError: android.support.v4.content.ContextCompat.getDrawable
            at android.support.v7.internal.widget.TintManager.getDrawable(TintManager.java:133)
            at android.support.v7.internal.widget.TintTypedArray.getDrawable(TintTypedArray.java:62)
            at android.support.v7.widget.Toolbar.<init>(Toolbar.java:248)
            at android.support.v7.widget.Toolbar.<init>(Toolbar.java:190)
            at java.lang.reflect.Constructor.constructNative(Native Method)
            at java.lang.reflect.Constructor.newInstance(Constructor.java:423)
            at android.view.LayoutInflater.createView(LayoutInflater.java:594)
            at android.view.LayoutInflater.createViewFromTag(LayoutInflater.java:696)
            at android.view.LayoutInflater.parseInclude(LayoutInflater.java:816)
            at android.view.LayoutInflater.rInflate(LayoutInflater.java:745)
            at android.view.LayoutInflater.inflate(LayoutInflater.java:492)
            at android.view.LayoutInflater.inflate(LayoutInflater.java:397)
            at android.view.LayoutInflater.inflate(LayoutInflater.java:353)
            at android.support.v7.app.ActionBarActivityDelegateBase.setContentView(ActionBarActivityDelegateBase.java:228)
            at android.support.v7.app.ActionBarActivity.setContentView(ActionBarActivity.java:102)
            at io.bxbxbai.androiddemos.MainActivity.onCreate(MainActivity.java:31)
            at android.app.Activity.performCreate(Activity.java:6144)
            at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1087)
            at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2181)
            at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2283)
            at android.app.ActivityThread.access$800(ActivityThread.java:144)
            at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1205)
            at android.os.Handler.dispatchMessage(Handler.java:102)
            at android.os.Looper.loop(Looper.java:136)
            at android.app.ActivityThread.main(ActivityThread.java:5158)
            at java.lang.reflect.Method.invokeNative(Native Method)
            at java.lang.reflect.Method.invoke(Method.java:515)
            at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:796)
            at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:612)
            at dalvik.system.NativeStart.main(Native Method)
</code>```

EDIT

toolbar.xml

```<code><?xml version="1.0" encoding="utf-8"?>

<android.support.v7.widget.Toolbar
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/toolbar"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:background="?attr/colorPrimaryDark"/>
</code>```

activity_main.xml

```<code> <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
        xmlns:tools="http://schemas.android.com/tools"
        android:id="@+id/container"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:orientation="vertical"
        tools:context=".MainActivity"
        tools:ignore="MergeRootFrame">

        <include android:id="@+id/toolbar" layout="@layout/toolbar" />

        <Button
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:id="@+id/btn_feed_list_demo"
            android:text="@string/feed_list_demo"/>

    </RelativeLayout>
</code>```

答:
For me it worked after I did:

Cleaning solution.

Deleting the app from the phone I've debugged it    at.

Closing Visual Studio.

Deleting folders /bin/ and /obj/ in android projects.

Launching solution again.

Body:
I am trying to get Material Design for my App by following this method.

Whenever I run the App it shows the following error:

Error inflating class android.support.v7.widget.Toolbar.

I checked whether I have added the appcompat properly. But it is all Correct to me. So please tell me what am I doing wrong ?

build.gradle

apply plugin: 'com.android.application'

android {
    compileSdkVersion 21
    buildToolsVersion '21.0.2'

    defaultConfig {
        applicationId "io.bxbxbai.feedlistviewdemo"
        minSdkVersion 14
        targetSdkVersion 21
        versionCode 1
        versionName "1.0"
    }
    buildTypes {
        release {
            runProguard false
            proguardFiles 'proguard-rules.pro'
        }
    }
}

configurations {
    all*.exclude group: 'com.android.support', module: 'support-v4'
}

dependencies {
    compile fileTree(include: ['*.jar'], dir: 'libs')
    compile project(':materialDesign')
    compile 'com.balysv.materialmenu:material-menu:1.4.0'
    compile 'com.android.support:appcompat-v7:21.+'
}

Logcat

02:11.641  20583-20583/io.bxbxbai.feedlistviewdemo E/AndroidRuntime﹕ FATAL EXCEPTION: main
    Process: io.bxbxbai.feedlistviewdemo, PID: 20583
    java.lang.RuntimeException: Unable to start activity ComponentInfo{io.bxbxbai.feedlistviewdemo/io.bxbxbai.androiddemos.MainActivity}: android.view.InflateException: Binary XML file line #3: Error inflating class android.support.v7.widget.Toolbar
            at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2224)
            at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2283)
            at android.app.ActivityThread.access$800(ActivityThread.java:144)
            at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1205)
            at android.os.Handler.dispatchMessage(Handler.java:102)
            at android.os.Looper.loop(Looper.java:136)
            at android.app.ActivityThread.main(ActivityThread.java:5158)
            at java.lang.reflect.Method.invokeNative(Native Method)
            at java.lang.reflect.Method.invoke(Method.java:515)
            at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:796)
            at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:612)
            at dalvik.system.NativeStart.main(Native Method)
     Caused by: android.view.InflateException: Binary XML file line #3: Error inflating class android.support.v7.widget.Toolbar
            at android.view.LayoutInflater.createView(LayoutInflater.java:620)
            at android.view.LayoutInflater.createViewFromTag(LayoutInflater.java:696)
            at android.view.LayoutInflater.parseInclude(LayoutInflater.java:816)
            at android.view.LayoutInflater.rInflate(LayoutInflater.java:745)
            at android.view.LayoutInflater.inflate(LayoutInflater.java:492)
            at android.view.LayoutInflater.inflate(LayoutInflater.java:397)
            at android.view.LayoutInflater.inflate(LayoutInflater.java:353)
            at android.support.v7.app.ActionBarActivityDelegateBase.setContentView(ActionBarActivityDelegateBase.java:228)
            at android.support.v7.app.ActionBarActivity.setContentView(ActionBarActivity.java:102)
            at io.bxbxbai.androiddemos.MainActivity.onCreate(MainActivity.java:31)
            at android.app.Activity.performCreate(Activity.java:6144)
            at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1087)
            at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2181)
            at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2283)
            at android.app.ActivityThread.access$800(ActivityThread.java:144)
            at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1205)
            at android.os.Handler.dispatchMessage(Handler.java:102)
            at android.os.Looper.loop(Looper.java:136)
            at android.app.ActivityThread.main(ActivityThread.java:5158)
            at java.lang.reflect.Method.invokeNative(Native Method)
            at java.lang.reflect.Method.invoke(Method.java:515)
            at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:796)
            at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:612)
            at dalvik.system.NativeStart.main(Native Method)
     Caused by: java.lang.reflect.InvocationTargetException
            at java.lang.reflect.Constructor.constructNative(Native Method)
            at java.lang.reflect.Constructor.newInstance(Constructor.java:423)
            at android.view.LayoutInflater.createView(LayoutInflater.java:594)
            at android.view.LayoutInflater.createViewFromTag(LayoutInflater.java:696)
            at android.view.LayoutInflater.parseInclude(LayoutInflater.java:816)
            at android.view.LayoutInflater.rInflate(LayoutInflater.java:745)
            at android.view.LayoutInflater.inflate(LayoutInflater.java:492)
            at android.view.LayoutInflater.inflate(LayoutInflater.java:397)
            at android.view.LayoutInflater.inflate(LayoutInflater.java:353)
            at android.support.v7.app.ActionBarActivityDelegateBase.setContentView(ActionBarActivityDelegateBase.java:228)
            at android.support.v7.app.ActionBarActivity.setContentView(ActionBarActivity.java:102)
            at io.bxbxbai.androiddemos.MainActivity.onCreate(MainActivity.java:31)
            at android.app.Activity.performCreate(Activity.java:6144)
            at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1087)
            at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2181)
            at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2283)
            at android.app.ActivityThread.access$800(ActivityThread.java:144)
            at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1205)
            at android.os.Handler.dispatchMessage(Handler.java:102)
            at android.os.Looper.loop(Looper.java:136)
            at android.app.ActivityThread.main(ActivityThread.java:5158)
            at java.lang.reflect.Method.invokeNative(Native Method)
            at java.lang.reflect.Method.invoke(Method.java:515)
            at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:796)
            at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:612)
            at dalvik.system.NativeStart.main(Native Method)
     Caused by: java.lang.NoSuchMethodError: android.support.v4.content.ContextCompat.getDrawable
            at android.support.v7.internal.widget.TintManager.getDrawable(TintManager.java:133)
            at android.support.v7.internal.widget.TintTypedArray.getDrawable(TintTypedArray.java:62)
            at android.support.v7.widget.Toolbar.<init>(Toolbar.java:248)
            at android.support.v7.widget.Toolbar.<init>(Toolbar.java:190)
            at java.lang.reflect.Constructor.constructNative(Native Method)
            at java.lang.reflect.Constructor.newInstance(Constructor.java:423)
            at android.view.LayoutInflater.createView(LayoutInflater.java:594)
            at android.view.LayoutInflater.createViewFromTag(LayoutInflater.java:696)
            at android.view.LayoutInflater.parseInclude(LayoutInflater.java:816)
            at android.view.LayoutInflater.rInflate(LayoutInflater.java:745)
            at android.view.LayoutInflater.inflate(LayoutInflater.java:492)
            at android.view.LayoutInflater.inflate(LayoutInflater.java:397)
            at android.view.LayoutInflater.inflate(LayoutInflater.java:353)
            at android.support.v7.app.ActionBarActivityDelegateBase.setContentView(ActionBarActivityDelegateBase.java:228)
            at android.support.v7.app.ActionBarActivity.setContentView(ActionBarActivity.java:102)
            at io.bxbxbai.androiddemos.MainActivity.onCreate(MainActivity.java:31)
            at android.app.Activity.performCreate(Activity.java:6144)
            at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1087)
            at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2181)
            at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2283)
            at android.app.ActivityThread.access$800(ActivityThread.java:144)
            at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1205)
            at android.os.Handler.dispatchMessage(Handler.java:102)
            at android.os.Looper.loop(Looper.java:136)
            at android.app.ActivityThread.main(ActivityThread.java:5158)
            at java.lang.reflect.Method.invokeNative(Native Method)
            at java.lang.reflect.Method.invoke(Method.java:515)
            at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:796)
            at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:612)
            at dalvik.system.NativeStart.main(Native Method)

EDIT

toolbar.xml

<?xml version="1.0" encoding="utf-8"?>

<android.support.v7.widget.Toolbar
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/toolbar"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:background="?attr/colorPrimaryDark"/>

activity_main.xml

 <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
        xmlns:tools="http://schemas.android.com/tools"
        android:id="@+id/container"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:orientation="vertical"
        tools:context=".MainActivity"
        tools:ignore="MergeRootFrame">

        <include android:id="@+id/toolbar" layout="@layout/toolbar" />

        <Button
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:id="@+id/btn_feed_list_demo"
            android:text="@string/feed_list_demo"/>

    </RelativeLayout>


问:
Telerik RadGrid with conditional format
I have this Telerik RadGrid with a simple conditional format with jQuery.
Each time I make changes/page switch/filter... I lose my format.
Can I use some event in the grid to call this function and not lose the format?</p>

```<code>$('td').each(
                function () {
                    var myTD = $(this).text();
                    if (myTD.match("^Due")) {
                        $(this).addClass('trafic-green');
                    }
                    if (myTD.match("^Not yet due")) {
                        $(this).addClass('trafic-yellow');
                    }
                    if (myTD.match("^Overdue")) {
                        $(this).addClass('trafic-red');
                    }
                }
</code>```

答:
An other way is to use the Grid 'DataBound' event to get the GridDataItem.

In this exemple we are going to chance a cell BackgroundColor based on a CheckBoxState:

```<code>protected void Unnamed_DataBound(object sender, Telerik.Web.UI.GridItemEventArgs e)
{
    if (e.Item is GridDataItem)
    {
        GridDataItem item = (GridDataItem)e.Item;
        CheckBox chk = (CheckBox)item["BoolGood"].Controls[0];
        TableCell cell = (TableCell)item["BoolGood"];
        cell.BackColor = (chk.Checked ? Color.Green : Color.Red);
    }
}
</code>```

We can apply a CssClass to the cell directly:

```<code>cell.CssClass = "myClass";
</code>```

Title: Telerik RadGrid with conditional format

Body:
I have this Telerik RadGrid with a simple conditional format with jQuery.
Each time I make changes/page switch/filter... I lose my format.
Can I use some event in the grid to call this function and not lose the format?

$('td').each(
                function () {
                    var myTD = $(this).text();
                    if (myTD.match("^Due")) {
                        $(this).addClass('trafic-green');
                    }
                    if (myTD.match("^Not yet due")) {
                        $(this).addClass('trafic-yellow');
                    }
                    if (myTD.match("^Overdue")) {
                        $(this).addClass('trafic-red');
                    }
                }

Body:
An other way is to use the Grid 'DataBound' event to get the GridDataItem.

In this exemple we are going to chance a cell BackgroundColor based on a CheckBoxState:

protected void Unnamed_DataBound(object sender, Telerik.Web.UI.GridItemEventArgs e)
{
    if (e.Item is GridDataItem)
    {
        GridDataItem item = (GridDataItem)e.Item;
        CheckBox chk = (CheckBox)item["BoolGood"].Controls[0];
        TableCell cell = (TableCell)item["BoolGood"];
        cell.BackColor = (chk.Checked ? Color.Green : Color.Red);
    }
}

We can apply a CssClass to the cell directly:

cell.CssClass = "myClass";


问:
How to compile and link sqlite3 in a C++ program
I get the following response when I try to compile and link sqlite3 in a C++ program.
I use Eclipse Mars for C++

g++ "-LC:\Sqlite\sqlite3.h" -o Stryktips.exe "src\Stryktips.o" "-lC:\Sqlite\sqlite3.h"

  c:/mingw/bin/../lib/gcc/x86_64-w64-mingw32/4.9.2/../../.
  ./../x86_64-w64-mingw32/bin/ld.exe:

  cannot find -lC:\Sqlite\sqlite3.h

  collect2.exe: error: ld returned 1 exit status

答:
C:\Sqlite\sqlite3.h is a header file. And as such you should #include it, not link with it. You should link with a file ending with .lib or .a

And the -L option is to add a directory path, not a file.

So your linker command like should look something like this:

```<code>g++ -o Stryktips.exe "src\Stryktips.o" -LC:\Sqlite -lsqlite
</code>```

That will tell the linker that libraries can be found in the C:\Sqlite directory, and that it should link with the sqlite library.

Body:
C:\Sqlite\sqlite3.h is a header file. And as such you should #include it, not link with it. You should link with a file ending with .lib or .a

And the -L option is to add a directory path, not a file.

So your linker command like should look something like this:

g++ -o Stryktips.exe "src\Stryktips.o" -LC:\Sqlite -lsqlite

That will tell the linker that libraries can be found in the C:\Sqlite directory, and that it should link with the sqlite library.


问:
Get Element ID - JavaScript
I know the data-id from the li element, but now i want the id value of the li element. How can I get this? Tried:

```<code> var id = $('li[data-id="KnSubject[StId]"]').id;
 console.log(id); // UNDEFINED
</code>```

Html Code:

```<code><li role="treeitem" data-jstree="{"icon" : "glyphicon glyphicon-pencil"}" data-id="KnSubject[StId]" data-values="null" aria-selected="true" aria-level="3" aria-labelledby="j1_4_anchor" id="j1_4" class="jstree-node  jstree-leaf"><i class="jstree-icon jstree-ocl" role="presentation"></i><a class="jstree-anchor jstree-clicked" href="#" tabindex="-1" id="j1_4_anchor"><i class="jstree-icon jstree-themeicon glyphicon glyphicon-pencil jstree-themeicon-custom" role="presentation"></i>Type dossieritem (StId)</a></li>
</code>```

答:
```<code>var id = $('li[data-id="KnSubject[StId]"]').attr('id');
console.log(id);
</code>```

Title: Get Element ID - JavaScript

Body:
I know the data-id from the li element, but now i want the id value of the li element. How can I get this? Tried:

 var id = $('li[data-id="KnSubject[StId]"]').id;
 console.log(id); // UNDEFINED

Html Code:

Type dossieritem (StId)


问:
MemoryError on large merges with pandas in Python
I'm using pandas to do an outer merge on a set of about ~1000-2000 CSV files. Each CSV file has an identifier column id which is shared between all the CSV files, but each file has a unique set of columns of 3-5 columns. There are roughly 20,000 unique id rows in each file. All I want to do is merge these together, bringing all the new columns together and using the id column as the merge index.

I do it using a simple merge call:

```<code>merged_df = first_df # first csv file dataframe
for next_filename in filenames:
   # load up the next df
   # ...
   merged_df = merged_df.merge(next_df, on=["id"], how="outer")
</code>```

The problem is that with nearly 2000 CSV files, I get a MemoryError in the merge operation thrown by pandas. I'm not sure if this is a limitation due to a problem in the merge operation?

The final dataframe would have 20,000 rows and roughly (2000 x 3) = 6000 columns. This is large, but not large enough to consume all the memory on the computer I am using which has over 20 GB of RAM.  Is this size too much for pandas manipulation? Should I be using something like sqlite instead? Is there something I can change in the merge operation to make it work on this scale?

thanks.

答:
pd.concat seems to run out of memory for large dataframes as well, one option is to convert the dfs to matrixes and concat these.

```<code>def concat_df_by_np(df1,df2):
    """
    accepts two dataframes, converts each to a matrix, concats them horizontally and
    uses the index of the first dataframe. This is not a concat by index but simply by
    position, therefore the index of both dataframes should be the same
    """
    dfout = deepcopy(pd.DataFrame(np.concatenate( (df1.as_matrix(),df2.as_matrix()),axis=1),
                                  index   = df1.index,
                                  columns = np.concatenate([df1.columns,df2.columns])))
    if (df1.index!=df2.index).any():
       #logging.warning('Indices in concat_df_by_np are not the same')
       print ('Indices in concat_df_by_np are not the same')

    return dfout
</code>```

However, one needs to be careful as this function is not a join but rather a horizontal append while where the indices are ignored

Body:
I'm using pandas to do an outer merge on a set of about ~1000-2000 CSV files. Each CSV file has an identifier column id which is shared between all the CSV files, but each file has a unique set of columns of 3-5 columns. There are roughly 20,000 unique id rows in each file. All I want to do is merge these together, bringing all the new columns together and using the id column as the merge index.

I do it using a simple merge call:

merged_df = first_df # first csv file dataframe
for next_filename in filenames:
   # load up the next df
   # ...
   merged_df = merged_df.merge(next_df, on=["id"], how="outer")

The problem is that with nearly 2000 CSV files, I get a MemoryError in the merge operation thrown by pandas. I'm not sure if this is a limitation due to a problem in the merge operation?

The final dataframe would have 20,000 rows and roughly (2000 x 3) = 6000 columns. This is large, but not large enough to consume all the memory on the computer I am using which has over 20 GB of RAM.  Is this size too much for pandas manipulation? Should I be using something like sqlite instead? Is there something I can change in the merge operation to make it work on this scale?

thanks.

Body:
pd.concat seems to run out of memory for large dataframes as well, one option is to convert the dfs to matrixes and concat these.

def concat_df_by_np(df1,df2):
    """
    accepts two dataframes, converts each to a matrix, concats them horizontally and
    uses the index of the first dataframe. This is not a concat by index but simply by
    position, therefore the index of both dataframes should be the same
    """
    dfout = deepcopy(pd.DataFrame(np.concatenate( (df1.as_matrix(),df2.as_matrix()),axis=1),
                                  index   = df1.index,
                                  columns = np.concatenate([df1.columns,df2.columns])))
    if (df1.index!=df2.index).any():
       #logging.warning('Indices in concat_df_by_np are not the same')
       print ('Indices in concat_df_by_np are not the same')

    return dfout

However, one needs to be careful as this function is not a join but rather a horizontal append while where the indices are ignored