问:
Duplicated header icons in datatables when refreshing table
Im using jquery datatables to show data that i get from jsonresponse.
The initial display of table is ok, but when i hit refresh and use

```<code>$('#search-notable-authors').DataTable().destroy();
$('#search-notable-authors').DataTable(
</code>```

it reloads the table but duplicates header icons the number of times i hit refresh button.

Here is the full jq code

```<code><script type="text/javascript">
    var $jquery_1_11_3 = jQuery.noConflict(true);
    (function ($) {
        $(document).ready(function () {
            $("#refresh-btn").on("click",function(){
                showItemsTable1();
            });
            ajaxPaths = {
                allNotableAuthors:   "{{ path('json_getAllNotableAuthors') }}",
                allNotableAuthorsByJournal:   "{{ path('json_getAllNotableAuthorsByJournal') }}"
            },
                    itemsTable = null,
                    getItems = function () {

                        return $.Deferred(function () {
                            var that = this;
                            $.ajax({
                                type: "POST",
                                data: $('#articlesList').serialize(),
                                url: ajaxPaths.allNotableAuthors,
                                success: function (data) {
                                    console.log(data);
                                    that.resolve(data);
                                }
                            });
                        });
                    },
                    getItems1 = function () {
                        return $.Deferred(function () {
                            var that = this;
                            var journal = $("#search_authors_name_short").val();
                            $.ajax({
                                type: "POST",
                                data: { term : journal },
                                url: ajaxPaths.allNotableAuthorsByJournal,
                                success: function (data) {
                                    console.log(data);
                                    that.resolve(data);
                                }
                            });
                        });
                    },
                    showItemsTable = function () {
                        return $.Deferred(function () {
                            var that = this;
                            getItems().done(function (itemsData) {
                                $('#search-notable-authors').DataTable({
                                    aLengthMenu: [
                                        [25, 50, 100, 200, -1],
                                        [25, 50, 100, 200, "All"]
                                    ],
                                    iDisplayLength: -1,
                                    data: itemsData,
                                    columns: [
                                        {"data": 0},
                                        {"data": 1},
                                        {"data": 2},
                                        {"data": 3},
                                        {"data": 4}
                                    ]
                                });
                                that.resolve();

                            });
                        });
                    },
            showItemsTable1 = function () {
                return $.Deferred(function () {
                    var that = this;
                    getItems1().done(function (itemsData) {
                        $('#search-notable-authors').DataTable().destroy();
                        $('#search-notable-authors').DataTable({
                            aLengthMenu: [
                                [25, 50, 100, 200, -1],
                                [25, 50, 100, 200, "All"]
                            ],
                            iDisplayLength: -1,
                            data: itemsData,
                            columns: [
                                {"data": 0},
                                {"data": 1},
                                {"data": 2},
                                {"data": 3},
                                {"data": 4}
                            ]
                        });
                        that.resolve();
                    });
                });
            }
            showItemsTable();
        });//end of doc ready
    })($jquery_1_11_3);
</script>
</code>```

How can i fix this to work without duplicating header icons?

答:
I didn't find what was making the problem, so i didn't fix it, but i found a solution to bypass it. So this is with what im going until i find something better.

On the start of script i get the html from table header like this:

```<code>var hdr = $('#search-notable-authors').find('thead').html();
</code>```

Then in showItemsTable i destroy and empty the table

```<code>var tableId = $('#search-notable-authors');
itemsTable = $(tableId).DataTable();
itemsTable.destroy();
$(tableId).empty();
</code>```

and then replace html with thead of table

```<code>$('#search-notable-authors').find('thead').html(hdr);
</code>```

Here is the full showItemsTable code:

```<code>showItemsTable = function () {
                return $.Deferred(function () {
                    var that = this;
                    getItems().done(function (itemsData) {
                        var tableId = $('#search-notable-authors');
                        var header = $(tableId).find('thead').html();
                        itemsTable = $(tableId).DataTable();
                        itemsTable.destroy();
                        $(tableId).empty();

                        itemsTable = $(tableId).DataTable({

                            aLengthMenu: [
                                [25, 50, 100, 200, -1],
                                [25, 50, 100, 200, "All"]
                            ],
                            iDisplayLength: -1,
                            data: itemsData,
                            columns : [
                                DataTables.expandCol,
                                {"data": 'id'},
                                {"data": 'email'},
                                {"data": 'journal'},
                                {"data": 'title'},
                                {"data": 'citation_link'}
                            ]
                        });
                        $('#search-notable-authors').find('thead').html(hdr);
                        that.resolve();
                    });
                });
            },
</code>```

If someone comes up with a better solution, or fix of original problem please write

Body:
Im using jquery datatables to show data that i get from jsonresponse.
The initial display of table is ok, but when i hit refresh and use

$('#search-notable-authors').DataTable().destroy();
$('#search-notable-authors').DataTable(

it reloads the table but duplicates header icons the number of times i hit refresh button.

Here is the full jq code

How can i fix this to work without duplicating header icons?

Body:
I didn't find what was making the problem, so i didn't fix it, but i found a solution to bypass it. So this is with what im going until i find something better.

On the start of script i get the html from table header like this:

var hdr = $('#search-notable-authors').find('thead').html();

Then in showItemsTable i destroy and empty the table

var tableId = $('#search-notable-authors');
itemsTable = $(tableId).DataTable();
itemsTable.destroy();
$(tableId).empty();

and then replace html with thead of table

$('#search-notable-authors').find('thead').html(hdr);

Here is the full showItemsTable code:

showItemsTable = function () {
                return $.Deferred(function () {
                    var that = this;
                    getItems().done(function (itemsData) {
                        var tableId = $('#search-notable-authors');
                        var header = $(tableId).find('thead').html();
                        itemsTable = $(tableId).DataTable();
                        itemsTable.destroy();
                        $(tableId).empty();

                        itemsTable = $(tableId).DataTable({

                            aLengthMenu: [
                                [25, 50, 100, 200, -1],
                                [25, 50, 100, 200, "All"]
                            ],
                            iDisplayLength: -1,
                            data: itemsData,
                            columns : [
                                DataTables.expandCol,
                                {"data": 'id'},
                                {"data": 'email'},
                                {"data": 'journal'},
                                {"data": 'title'},
                                {"data": 'citation_link'}
                            ]
                        });
                        $('#search-notable-authors').find('thead').html(hdr);
                        that.resolve();
                    });
                });
            },

If someone comes up with a better solution, or fix of original problem please write


来源: stackexchange

问:
Passing Array to model function query codeigniter
Here is my function I want to put array values in IN() clause but it is not working

    Here $ids is the array passing to it.

```<code>    function get_school_students_data($ids){
    $query=$this->db->query("SELECT * FROM screening_answers where uid
    IN(".implode(',',$ids).")");
    $result=$query->result_array();
     return $query->num_rows();
    }
</code>```

答:
Try this

```<code>$this->db->where_in('uid',$ids);
</code>```

So in model

```<code>function get_school_students_data($ids){
    $this->db->where_in('uid',$ids);//$ids should be an array like array('20','15','22','42','86')
    $query = $this->db->get("screening_answers");
    $result=$this->db->result_array();// no need of this in your scenario
    return $this->db->num_rows();
 }
</code>```

ContentLicense: CC BY-SA 3.0

Body:
Here is my function I want to put array values in IN() clause but it is not working

    Here $ids is the array passing to it.

    function get_school_students_data($ids){
    $query=$this->db->query("SELECT * FROM screening_answers where uid
    IN(".implode(',',$ids).")");
    $result=$query->result_array();
     return $query->num_rows();
    }

Body:
Try this

$this->db->where_in('uid',$ids);

So in model

function get_school_students_data($ids){
    $this->db->where_in('uid',$ids);//$ids should be an array like array('20','15','22','42','86')
    $query = $this->db->get("screening_answers");
    $result=$this->db->result_array();// no need of this in your scenario
    return $this->db->num_rows();
 }


问:
Convert xy dataset to array
I have a dataset of time/value e.g.

```<code>> df <- data.frame(time=c(1,4,5,6), speed=c(100, 500, 600, 800))
</code>```

I want to convert it to an array with one item per time tick:

```<code>> some_func(df, speed ~ time, step=1)
[1] 100 100 100 500 600 800
</code>```

notice that a values for time == 2 and 3 were added.

Then I can use it in the cross correlation function.

答:
This will return the values that you want.

```<code>df$speed[rep(seq_len(nrow(df)), c(diff(df$time), 1))]
[1] 100 100 100 500 600 800
</code>```

Here, we use rep along with a vector argument to the second argument to return the indices of the desired vector for df$speed. We achieve this with diff, which will calculate the time period gaps and append 1 at the end to return the final value.

Title: Convert xy dataset to array

Body:
I have a dataset of time/value e.g.

> df <- data.frame(time=c(1,4,5,6), speed=c(100, 500, 600, 800))

I want to convert it to an array with one item per time tick:

> some_func(df, speed ~ time, step=1)
[1] 100 100 100 500 600 800

notice that a values for time == 2 and 3 were added.

Then I can use it in the cross correlation function.

Body:
This will return the values that you want.

df$speed[rep(seq_len(nrow(df)), c(diff(df$time), 1))]
[1] 100 100 100 500 600 800

Here, we use rep along with a vector argument to the second argument to return the indices of the desired vector for df$speed. We achieve this with diff, which will calculate the time period gaps and append 1 at the end to return the final value.


问:
Splitting a project VB/C#, and References
I've inherited a project written mostly in VB. I'd like to maintain what I have in VB while slowly converting to C# when I can. The only way I've found to do this is to create a separate C# project. However, this causes problems because of dependencies and references. I can't have VBProject reference CSharpProject and vice versa because it creates a circular reference. This is a problem because I need both projects to be able to reference the other. Is there a better way to do this, or am I stuck writing in VB (or completely translating to C#)?

Also, these projects are in the same solution. Shouldn't I be able to import/use them without creating a reference or some other easier way?

答:
There's no getting around having to remove the circular references.

When I've faced a similar situation in the past, converting from language A to language B, I started by refactoring bits of the language A code so that they were independent of the majority of the code base.  Then I'd translate those isolated pieces to language B and integrate so that the main program was now depending on the new modules.  Eventually, all that was left was the main program.

It took time, but this bottom-up approach was very effective and I ended up with a much more modular program.

ContentLicense: CC BY-SA 2.5


问:
I can't convert a JSON format file into a python format file
I'm doing pythonAPI exercises, and this is my completed API address：

http://api.juheapi.com/japi/toh?key=10245c2b75fa03d527204967ef7291cb&v=1.0&month=07&day=05

If you use the browser to open, the correct JSON file is displayed.but i cant't get correct
result using the following codecode .

```<code>page = urllib.urlopen(url)
html = page.read()
dic_json = json.loads(html)
print dic_json
</code>```

答:
There is nothing error in the json. It successfully parse json to python dict. You should take a look on python unicode. When you try to print a unicode in python 2 you will find like this, but when open in browser it will be correct non-ASCII character.

Python2 store non-ASCII character into like this format.

To read this particular dict , you can do something like this.

```<code>for x,y in dic_json.items():
    print x,":", y
</code>```

Body:
I'm doing pythonAPI exercises, and this is my completed API address：

http://api.juheapi.com/japi/toh?key=10245c2b75fa03d527204967ef7291cb&v=1.0&month=07&day=05

If you use the browser to open, the correct JSON file is displayed.but i cant't get correct
result using the following codecode .

page = urllib.urlopen(url)
html = page.read()
dic_json = json.loads(html)
print dic_json

Body:
There is nothing error in the json. It successfully parse json to python dict. You should take a look on python unicode. When you try to print a unicode in python 2 you will find like this, but when open in browser it will be correct non-ASCII character.

Python2 store non-ASCII character into like this format.

To read this particular dict , you can do something like this.

for x,y in dic_json.items():
    print x,":", y


问:
Ordering of the messages

Does ZeroMQ guarantee the order of messages( FIFO ).

Is there an option for persistence.

Is it the best fit for IPC communications.

Does it allow prioritizing the messages.

Does it allow prioritizing the receivers.

Does it allow both synchronous as well asynchronous way of communication?

答:
https://lists.zeromq.org/pipermail/zeromq-dev/2015-January/027748.html

The author said:"Messages carried over TCP or IPC will be delivered in order if they pass through the same network paths. This is guaranteed and it's a TCP
guarantee, nothing to do with ZeroMQ. ZeroMQ does not reorder
messages, ever. However if you pass messages through two or more
paths, and then merge those flows again, you will in effect shuffle
the messages."

Title: Ordering of the messages


问:
create different InverseBindingAdapter for Short and Integer values on android:text of EditText
I create these methods for custom data binding

```<code>@BindingAdapter("android:text")
public static void setShortText(TextView view, short value) {
    view.setText(String.valueOf(value));
}

@InverseBindingAdapter(attribute = "android:text")
public static Short getShortText(TextView view) {
    try {
        return Short.parseShort(view.getText().toString());
    } catch (NumberFormatException e) {
        return null;
    }
}

@BindingAdapter("android:text")
public static void setIntText(TextView view, int value) {
    view.setText(String.valueOf(value));
}

@InverseBindingAdapter(attribute = "android:text")
public static Integer getIntText(TextView view) {
    try {
        return Integer.parseInt(view.getText().toString());
    } catch (NumberFormatException e) {
        return null;
    }
}
</code>```

and bind my Short and Integer variables to views. when I build my project, the auto generated java uses the first three methods and it's have no usage from the fourth one (getIntText), and the problem is here. it use getShortText for Integer fields and cause compile time casting error.

I'm surprised, data binder properly detect it should use setIntText for set Integer values to views but it can't recognize that for inverseBinding.

how can I fix the problem?

please note that I prefer not use from below technique because I want to have control on binding when data in null

```<code>android:text="@={`` + obj.field}
</code>```

答:
I find a solution, but really not satisfy myself.
I change getIntText return value from Integer to int and problem is solved.
if someone find other better solution please let me know.

```<code>@InverseBindingAdapter(attribute = "android:text")
public static int getIntText(TextView view) {
    try {
        return Integer.parseInt(view.getText().toString());
    } catch (NumberFormatException e) {
        return -1;
    }
}
</code>```

Body:
I create these methods for custom data binding

@BindingAdapter("android:text")
public static void setShortText(TextView view, short value) {
    view.setText(String.valueOf(value));
}

@InverseBindingAdapter(attribute = "android:text")
public static Short getShortText(TextView view) {
    try {
        return Short.parseShort(view.getText().toString());
    } catch (NumberFormatException e) {
        return null;
    }
}

@BindingAdapter("android:text")
public static void setIntText(TextView view, int value) {
    view.setText(String.valueOf(value));
}

@InverseBindingAdapter(attribute = "android:text")
public static Integer getIntText(TextView view) {
    try {
        return Integer.parseInt(view.getText().toString());
    } catch (NumberFormatException e) {
        return null;
    }
}

and bind my Short and Integer variables to views. when I build my project, the auto generated java uses the first three methods and it's have no usage from the fourth one (getIntText), and the problem is here. it use getShortText for Integer fields and cause compile time casting error.

I'm surprised, data binder properly detect it should use setIntText for set Integer values to views but it can't recognize that for inverseBinding.

how can I fix the problem?

please note that I prefer not use from below technique because I want to have control on binding when data in null

android:text="@={`` + obj.field}

Body:
I find a solution, but really not satisfy myself.
I change getIntText return value from Integer to int and problem is solved.
if someone find other better solution please let me know.

@InverseBindingAdapter(attribute = "android:text")
public static int getIntText(TextView view) {
    try {
        return Integer.parseInt(view.getText().toString());
    } catch (NumberFormatException e) {
        return -1;
    }
}


问:
Store X509AttributeCertificateHolder object, especially attrCert local and open it
There is an option to store the X509Certificate local with the class JcaPEMWriter from the Bouncy Castle API. After storing the X509Certificate I can open it with openssl with the following command:

```<code>openssl x509 -in certificate.pem -text
</code>```

I have the following code:

```<code>X509AttributeCertificateHolder att = acBuilder.build(new JcaContentSignerBuilder("SHA1WithRSA").setProvider("BC").build(caprivkey));
</code>```

Now I want to store the attrCert (the Attribute Certificate) local, which is contained in the att variable. How can I do this? And how can I open the attrCert, it is possible to open it with openssl or any other tool?

答:
To save your Attribute Certificate in a PEM file, you can use JcaPEMWriter as well:

// save the Attribute Certificate to attcert.pem file
JcaPEMWriter writer = new JcaPEMWriter(new FileWriter("attcert.pem"));
writer.writeObject(att);
writer.close();
```

<p>The file will contain a base64 content, like this:</p>

<pre class="lang-none prettyprint-override"><code>-----BEGIN ATTRIBUTE CERTIFICATE-----
MIIBvzCCASgCAQEwZ6BlMGCkXjBcMQswCQYDVQQGEwJBVTEoMCYGA1UECgwfVGhl
IExlZ2lvbiBvZiB0aGUgQm91bmN5IENhc3RsZTEjMCEGA1UECwwaQm91bmN5IFBy
aW1hcnkgQ2VydGlmaWNhdGUCAQKgYjBgpF4wXDELMAkGA1UEBhMCQVUxKDAmBgNV
BAoMH1RoZSBMZWdpb24gb2YgdGhlIEJvdW5jeSBDYXN0bGUxIzAhBgNVBAsMGkJv
dW5jeSBQcmltYXJ5IENlcnRpZmljYXRlMA0GCSqGSIb3DQEBBQUAAgF7MCIYDzIw
MTcwNzA2MTE1MDExWhgPMjAxNzA3MDYxMTUxNTFaMCAwHgYDVQRIMRcwFaEThhFp
ZDovL0RBVTEyMzQ1Njc4OTANBgkqhkiG9w0BAQUFAAOBgQBy3epbynwILi/H0DkQ
UXDgIWXXN5oRQem9DJ2AhYl6JHeKOk3ML87axq+ukWYjZoo3eP2rIxuDU6jWRak1
+n92KLsc/zSFaAdxxYjXQbjTpqEafvEea4QPd4PfPHA9nd4QNKox4H1lNhDeyqtP
B4iU+bkA1bKDo4dnhXVtJaAlkg==
-----END ATTRIBUTE CERTIFICATE-----
</code>```

Unfortunately, it seems that there's no specific command in openssl to check the Attribute Certificate (check this discussion and this message with no replies - there's an extended version of openssl that seems to support it, although I haven't tested it).

But you can check the ASN.1 structure using the asn1parse option:

```<code>openssl asn1parse -dump -i -in attcert.pem
</code>```

The output will be the ASN.1 structure, like this:

    0:d=0  hl=4 l= 447 cons: SEQUENCE
    4:d=1  hl=4 l= 296 cons:  SEQUENCE
    8:d=2  hl=2 l=   1 prim:   INTEGER           :01
   11:d=2  hl=2 l= 103 cons:   SEQUENCE
   13:d=3  hl=2 l= 101 cons:    cont [ 0 ]
   15:d=4  hl=2 l=  96 cons:     SEQUENCE
   17:d=5  hl=2 l=  94 cons:      cont [ 4 ]
   19:d=6  hl=2 l=  92 cons:       SEQUENCE
   21:d=7  hl=2 l=  11 cons:        SET
   23:d=8  hl=2 l=   9 cons:         SEQUENCE
   25:d=9  hl=2 l=   3 prim:          OBJECT            :countryName
   30:d=9  hl=2 l=   2 prim:          PRINTABLESTRING   :AU
   34:d=7  hl=2 l=  40 cons:        SET
   36:d=8  hl=2 l=  38 cons:         SEQUENCE
   38:d=9  hl=2 l=   3 prim:          OBJECT            :organizationName
   43:d=9  hl=2 l=  31 prim:          UTF8STRING        :The Legion of the Bouncy Castle
... and so on
```

<p>Or you can read the file using Bouncy Castle:</p>

<pre class="lang-java prettyprint-override"><code>import org.bouncycastle.cert.X509AttributeCertificateHolder;
import org.bouncycastle.util.encoders.Base64;

String pem = // read contents from PEM file
// Convert to AC object
byte[] data = Base64.decode(pem.getBytes());
X509AttributeCertificateHolder holder = new X509AttributeCertificateHolder(data);
</code>```

Body:
There is an option to store the X509Certificate local with the class JcaPEMWriter from the Bouncy Castle API. After storing the X509Certificate I can open it with openssl with the following command:

openssl x509 -in certificate.pem -text

I have the following code:

X509AttributeCertificateHolder att = acBuilder.build(new JcaContentSignerBuilder("SHA1WithRSA").setProvider("BC").build(caprivkey));

Now I want to store the attrCert (the Attribute Certificate) local, which is contained in the att variable. How can I do this? And how can I open the attrCert, it is possible to open it with openssl or any other tool?

Body:
To save your Attribute Certificate in a PEM file, you can use JcaPEMWriter as well:

// save the Attribute Certificate to attcert.pem file
JcaPEMWriter writer = new JcaPEMWriter(new FileWriter("attcert.pem"));
writer.writeObject(att);
writer.close();

The file will contain a base64 content, like this:

-----BEGIN ATTRIBUTE CERTIFICATE-----
MIIBvzCCASgCAQEwZ6BlMGCkXjBcMQswCQYDVQQGEwJBVTEoMCYGA1UECgwfVGhl
IExlZ2lvbiBvZiB0aGUgQm91bmN5IENhc3RsZTEjMCEGA1UECwwaQm91bmN5IFBy
aW1hcnkgQ2VydGlmaWNhdGUCAQKgYjBgpF4wXDELMAkGA1UEBhMCQVUxKDAmBgNV
BAoMH1RoZSBMZWdpb24gb2YgdGhlIEJvdW5jeSBDYXN0bGUxIzAhBgNVBAsMGkJv
dW5jeSBQcmltYXJ5IENlcnRpZmljYXRlMA0GCSqGSIb3DQEBBQUAAgF7MCIYDzIw
MTcwNzA2MTE1MDExWhgPMjAxNzA3MDYxMTUxNTFaMCAwHgYDVQRIMRcwFaEThhFp
ZDovL0RBVTEyMzQ1Njc4OTANBgkqhkiG9w0BAQUFAAOBgQBy3epbynwILi/H0DkQ
UXDgIWXXN5oRQem9DJ2AhYl6JHeKOk3ML87axq+ukWYjZoo3eP2rIxuDU6jWRak1
+n92KLsc/zSFaAdxxYjXQbjTpqEafvEea4QPd4PfPHA9nd4QNKox4H1lNhDeyqtP
B4iU+bkA1bKDo4dnhXVtJaAlkg==
-----END ATTRIBUTE CERTIFICATE-----

Unfortunately, it seems that there's no specific command in openssl to check the Attribute Certificate (check this discussion and this message with no replies - there's an extended version of openssl that seems to support it, although I haven't tested it).

But you can check the ASN.1 structure using the asn1parse option:

openssl asn1parse -dump -i -in attcert.pem

The output will be the ASN.1 structure, like this:

    0:d=0  hl=4 l= 447 cons: SEQUENCE
    4:d=1  hl=4 l= 296 cons:  SEQUENCE
    8:d=2  hl=2 l=   1 prim:   INTEGER           :01
   11:d=2  hl=2 l= 103 cons:   SEQUENCE
   13:d=3  hl=2 l= 101 cons:    cont [ 0 ]
   15:d=4  hl=2 l=  96 cons:     SEQUENCE
   17:d=5  hl=2 l=  94 cons:      cont [ 4 ]
   19:d=6  hl=2 l=  92 cons:       SEQUENCE
   21:d=7  hl=2 l=  11 cons:        SET
   23:d=8  hl=2 l=   9 cons:         SEQUENCE
   25:d=9  hl=2 l=   3 prim:          OBJECT            :countryName
   30:d=9  hl=2 l=   2 prim:          PRINTABLESTRING   :AU
   34:d=7  hl=2 l=  40 cons:        SET
   36:d=8  hl=2 l=  38 cons:         SEQUENCE
   38:d=9  hl=2 l=   3 prim:          OBJECT            :organizationName
   43:d=9  hl=2 l=  31 prim:          UTF8STRING        :The Legion of the Bouncy Castle
... and so on

Or you can read the file using Bouncy Castle:

import org.bouncycastle.cert.X509AttributeCertificateHolder;
import org.bouncycastle.util.encoders.Base64;

String pem = // read contents from PEM file
// Convert to AC object
byte[] data = Base64.decode(pem.getBytes());
X509AttributeCertificateHolder holder = new X509AttributeCertificateHolder(data);


问:
Loop through list and variable in Ansible
I'm going to grant privileges on two MySQL databases to user from to different IP's using Ansible. What I've got now:
Vars:

```<code>#users
root_user: 'root'
root_password: 'root'
prosody_user: 'prosody'
prosody_password: 'prosody'

#databases
oauth_db: "oauth"

#hosts
prosody_hosts: ['10.0.1.4', '10.0.1.5']
</code>```

Task:

```<code>- name: add or update mysql user prosody
  mysql_user:
   name: "{{ prosody_user }}"
   host: "{{ item.host }}"
   password: "{{ prosody_password }}"
   login_user: "{{ root_user }}"
   login_password: "{{ root_password }}"
   check_implicit_admin: yes
   append_privs: yes
   priv: "{{ item.database }}.*:ALL,GRANT"
  with_items:
  - { host: "{{ prosody_hosts[0] }}", database: "{{ oauth_db }}" }
  - { host: "{{ prosody_hosts[1] }}", database: "{{ oauth_db }}" }
  - { host: "{{ prosody_hosts[0] }}", database: "{{ prosody_db }}" }
  - { host: "{{ prosody_hosts[1] }}", database: "{{ prosody_db }}" }
</code>```

Direct calling of array elements doesn't look very nice. I just want loop through prosody_hosts array in with_item directive, сonsidering that database is not an array.

Goal is to to get something like this:

```<code>...
with_items
- { host: "{{ prosody_hosts }}", database: "{{ oauth_db }}" }
- { host: "{{ prosody_hosts }}", database: "{{ prosody_db }}" }
</code>```

Thanks in advance!

答:
What you need is nested loops.
See this Ansible documentation.

Basically you'd end up with something similar like this. Put your databases in a list called 'databases' like you did with hosts. This will execute the task for every host and every database.

 I haven't tested this but it should get pretty close.

```<code>- name: add or update mysql user prosody
  mysql_user:
   name: "{{ prosody_user }}"
   host: "{{ item[0] }}"
   password: "{{ prosody_password }}"
   login_user: "{{ root_user }}"
   login_password: "{{ root_password }}"
   check_implicit_admin: yes
   append_privs: yes
   priv: "{{ item[1] }}.*:ALL,GRANT"
  with_nested:
    - "{{ prosody_hosts }}"
    - "{{ databases }}"
</code>```

Body:
I'm going to grant privileges on two MySQL databases to user from to different IP's using Ansible. What I've got now:
Vars:

#users
root_user: 'root'
root_password: 'root'
prosody_user: 'prosody'
prosody_password: 'prosody'

#databases
oauth_db: "oauth"

#hosts
prosody_hosts: ['10.0.1.4', '10.0.1.5']

Task:

- name: add or update mysql user prosody
  mysql_user:
   name: "{{ prosody_user }}"
   host: "{{ item.host }}"
   password: "{{ prosody_password }}"
   login_user: "{{ root_user }}"
   login_password: "{{ root_password }}"
   check_implicit_admin: yes
   append_privs: yes
   priv: "{{ item.database }}.*:ALL,GRANT"
  with_items:
  - { host: "{{ prosody_hosts[0] }}", database: "{{ oauth_db }}" }
  - { host: "{{ prosody_hosts[1] }}", database: "{{ oauth_db }}" }
  - { host: "{{ prosody_hosts[0] }}", database: "{{ prosody_db }}" }
  - { host: "{{ prosody_hosts[1] }}", database: "{{ prosody_db }}" }

Direct calling of array elements doesn't look very nice. I just want loop through prosody_hosts array in with_item directive, сonsidering that database is not an array.

Goal is to to get something like this:

...
with_items
- { host: "{{ prosody_hosts }}", database: "{{ oauth_db }}" }
- { host: "{{ prosody_hosts }}", database: "{{ prosody_db }}" }

Thanks in advance!

Body:
What you need is nested loops.
See this Ansible documentation.

Basically you'd end up with something similar like this. Put your databases in a list called 'databases' like you did with hosts. This will execute the task for every host and every database.

 I haven't tested this but it should get pretty close.

- name: add or update mysql user prosody
  mysql_user:
   name: "{{ prosody_user }}"
   host: "{{ item[0] }}"
   password: "{{ prosody_password }}"
   login_user: "{{ root_user }}"
   login_password: "{{ root_password }}"
   check_implicit_admin: yes
   append_privs: yes
   priv: "{{ item[1] }}.*:ALL,GRANT"
  with_nested:
    - "{{ prosody_hosts }}"
    - "{{ databases }}"


问:
array group by iteration in scala
I have a array with data like this.

```<code>tagid,timestamp,listner,orgid,suborgid,rssi
[4,1496745915,718,4,3,0.30]
[2,1496745915,3878,4,3,0.20]
[4,1496745918,362,4,3,0.60]
[4,1496745913,362,4,3,0.60]
</code>```

I want to iterate this array and find the latest 10 seconds timestamp data for each tag & listner.This is my code.

```<code> override def inputSchema: StructType =
 StructType(StructField("time", StringType) :: StructField("tagid", StringType) :: StructField("listener", StringType) :: StructField("rssi", StringType) :: Nil)

   override def initialize(buffer: org.apache.spark.sql.expressions.MutableAggregationBuffer): Unit = {
buffer(0) = Array[String]();
}

override def update(buffer: MutableAggregationBuffer, input: Row): Unit =      {
buffer(0) = buffer.getAs[WrappedArray[String]](0) :+ (input.getAs[String](0)+";"+
  input.getAs[String](1)+";"+input.getAs[String](2));
}

override def merge(buffer1: MutableAggregationBuffer, buffer2: Row): Unit     =  {
buffer1(0) = buffer1.getAs[WrappedArray[String]](0) ++ buffer2.getAs[WrappedArray[String]](0)
}

override def evaluate(buffer: Row): Any = {
val in_array = buffer.getAs[WrappedArray[String]](0);
}
</code>```

The in_array contains all the data.I dont know how to proceed further .Any help will be appreciated.

答:
I see that you are trying to use udaf and for a beginner its a nightmare. By the way udaf will return you one row for each group and to get all the original rows from aggregated dataframe would be another nightmare.

I am assuming that you have a text file with data as

```<code>tagid,timestamp,listner,orgid,suborgid,rssi
4,1496745915,718,4,3,0.30
2,1496745915,3878,4,3,0.20
4,1496745918,362,4,3,0.60
4,1496745913,362,4,3,0.60
</code>```

If yes than reading the file to dataframe is quite easy as

```<code>val df = sqlContext.read.format("csv").option("header", true).load("path to the above file")
df.show(false)
</code>```

This should give you dataframe as

```<code>+-----+----------+-------+-----+--------+----+
|tagid|timestamp |listner|orgid|suborgid|rssi|
+-----+----------+-------+-----+--------+----+
|4    |1496745915|718    |4    |3       |0.30|
|2    |1496745915|3878   |4    |3       |0.20|
|4    |1496745918|362    |4    |3       |0.60|
|4    |1496745913|362    |4    |3       |0.60|
+-----+----------+-------+-----+--------+----+
</code>```

Now you are looking to filter in only the data that are within 10 seconds of latest timestamp for each tagid and listner. For this use following code

```<code>val windowSpec = Window
                    .orderBy($"timestamp".desc)  //latest to come first
                    .partitionBy("tagid", "listner")//grouping data
</code>```

You will have to put latest timestamp in each row for each groups created above so that you can find the time difference. For that do following

```<code>df.withColumn("firstValue", first("timestamp") over windowSpec)
</code>```

This will create a new column as

```<code>+-----+----------+-------+-----+--------+----+----------+
|tagid|timestamp |listner|orgid|suborgid|rssi|firstValue|
+-----+----------+-------+-----+--------+----+----------+
|2    |1496745915|3878   |4    |3       |0.20|1496745915|
|4    |1496745915|718    |4    |3       |0.30|1496745915|
|4    |1496745918|362    |4    |3       |0.60|1496745918|
|4    |1496745913|362    |4    |3       |0.60|1496745918|
+-----+----------+-------+-----+--------+----+----------+
</code>```

Next step would be simple just to check if the time difference is less than 10 or not and filter it

```<code>df.filter($"firstValue".cast("long")-$"timestamp".cast("long") < 10)
</code>```

Finally time to remove unwanted columns

```<code>df.drop("firstValue")
</code>```

I hope the answer is clear and understanding

Its more clear if you convert the timestamp to real timestamp as

```<code>+-----+-------------------+-------+-----+--------+----+-------------------+---------+
|tagid|timestamp          |listner|orgid|suborgid|rssi|firstValue         |differnce|
+-----+-------------------+-------+-----+--------+----+-------------------+---------+
|2    |2017-06-06 16:30:15|3878   |4    |3       |0.20|2017-06-06 16:30:15|0        |
|4    |2017-06-06 16:30:15|718    |4    |3       |0.30|2017-06-06 16:30:15|0        |
|4    |2017-06-06 16:30:18|362    |4    |3       |0.60|2017-06-06 16:30:18|0        |
|4    |2017-06-06 16:30:13|362    |4    |3       |0.60|2017-06-06 16:30:18|5        |
+-----+-------------------+-------+-----+--------+----+-------------------+---------+
</code>```

Title: array group by iteration in scala

Body:
I have a array with data like this.

tagid,timestamp,listner,orgid,suborgid,rssi
[4,1496745915,718,4,3,0.30]
[2,1496745915,3878,4,3,0.20]
[4,1496745918,362,4,3,0.60]
[4,1496745913,362,4,3,0.60]

I want to iterate this array and find the latest 10 seconds timestamp data for each tag & listner.This is my code.

 override def inputSchema: StructType =
 StructType(StructField("time", StringType) :: StructField("tagid", StringType) :: StructField("listener", StringType) :: StructField("rssi", StringType) :: Nil)

   override def initialize(buffer: org.apache.spark.sql.expressions.MutableAggregationBuffer): Unit = {
buffer(0) = Array[String]();
}

override def update(buffer: MutableAggregationBuffer, input: Row): Unit =      {
buffer(0) = buffer.getAs[WrappedArray[String]](0) :+ (input.getAs[String](0)+";"+
  input.getAs[String](1)+";"+input.getAs[String](2));
}

override def merge(buffer1: MutableAggregationBuffer, buffer2: Row): Unit     =  {
buffer1(0) = buffer1.getAs[WrappedArray[String]](0) ++ buffer2.getAs[WrappedArray[String]](0)
}

override def evaluate(buffer: Row): Any = {
val in_array = buffer.getAs[WrappedArray[String]](0);
}

The in_array contains all the data.I dont know how to proceed further .Any help will be appreciated.

Body:
I see that you are trying to use udaf and for a beginner its a nightmare. By the way udaf will return you one row for each group and to get all the original rows from aggregated dataframe would be another nightmare.

I am assuming that you have a text file with data as

tagid,timestamp,listner,orgid,suborgid,rssi
4,1496745915,718,4,3,0.30
2,1496745915,3878,4,3,0.20
4,1496745918,362,4,3,0.60
4,1496745913,362,4,3,0.60

If yes than reading the file to dataframe is quite easy as

val df = sqlContext.read.format("csv").option("header", true).load("path to the above file")
df.show(false)

This should give you dataframe as

+-----+----------+-------+-----+--------+----+
|tagid|timestamp |listner|orgid|suborgid|rssi|
+-----+----------+-------+-----+--------+----+
|4    |1496745915|718    |4    |3       |0.30|
|2    |1496745915|3878   |4    |3       |0.20|
|4    |1496745918|362    |4    |3       |0.60|
|4    |1496745913|362    |4    |3       |0.60|
+-----+----------+-------+-----+--------+----+

Now you are looking to filter in only the data that are within 10 seconds of latest timestamp for each tagid and listner. For this use following code

val windowSpec = Window
                    .orderBy($"timestamp".desc)  //latest to come first
                    .partitionBy("tagid", "listner")//grouping data

You will have to put latest timestamp in each row for each groups created above so that you can find the time difference. For that do following

df.withColumn("firstValue", first("timestamp") over windowSpec)

This will create a new column as

+-----+----------+-------+-----+--------+----+----------+
|tagid|timestamp |listner|orgid|suborgid|rssi|firstValue|
+-----+----------+-------+-----+--------+----+----------+
|2    |1496745915|3878   |4    |3       |0.20|1496745915|
|4    |1496745915|718    |4    |3       |0.30|1496745915|
|4    |1496745918|362    |4    |3       |0.60|1496745918|
|4    |1496745913|362    |4    |3       |0.60|1496745918|
+-----+----------+-------+-----+--------+----+----------+

Next step would be simple just to check if the time difference is less than 10 or not and filter it

df.filter($"firstValue".cast("long")-$"timestamp".cast("long") < 10)

Finally time to remove unwanted columns

df.drop("firstValue")

I hope the answer is clear and understanding

Its more clear if you convert the timestamp to real timestamp as

+-----+-------------------+-------+-----+--------+----+-------------------+---------+
|tagid|timestamp          |listner|orgid|suborgid|rssi|firstValue         |differnce|
+-----+-------------------+-------+-----+--------+----+-------------------+---------+
|2    |2017-06-06 16:30:15|3878   |4    |3       |0.20|2017-06-06 16:30:15|0        |
|4    |2017-06-06 16:30:15|718    |4    |3       |0.30|2017-06-06 16:30:15|0        |
|4    |2017-06-06 16:30:18|362    |4    |3       |0.60|2017-06-06 16:30:18|0        |
|4    |2017-06-06 16:30:13|362    |4    |3       |0.60|2017-06-06 16:30:18|5        |
+-----+-------------------+-------+-----+--------+----+-------------------+---------+


问:
Yii2: sort a relational count column in GridView
[EDITED 2]

I'm having hard time to sort by the 'topicCount' which is defined as a relational getter on a model 'Tag'.
A Topic can have a lots of Tag, and wish to sort the Tags by how many Topics containing that Tag.

In my models/Tag.php:

```<code>public function getTopicCount()
{
    return TopicTag::find()->where(['tag_id' => $this->id])->count();
}
</code>```

And in my views/tag/index.php:

```<code><?= GridView::widget([
    'dataProvider' => $dataProvider,
    'columns' => [
        'id',
        'name',
        [
             'attribute'=>'topicCount',
             'value' => 'topicCount',
        ],
        'created_at',

        ['class' => 'yii\grid\ActionColumn','template' => '{view}',],
    ],
]); ?>
</code>```

And in my controllers/TagController.php:

```<code>public function actionIndex()
{
    $dataProvider = new ActiveDataProvider([
        'query' => Tag::find(),
        'sort'=> [
            'defaultOrder' => ['id'=>SORT_DESC],
            'attributes' => ['id','topicCount'],
        ],
        'pagination' => [
            'pageSize' => 100,
        ],
    ]);

    return $this->render('index', [
        'dataProvider' => $dataProvider,
    ]);
}
</code>```

And in my models/TagSearch.php:

```<code><?php

namespace common\models;

use Yii;

/**
 * This is the model class for table "tags".
 *
 * @property integer $id
 * @property string $name
 * @property string $created_at
 * @property string $updated_at
 */
class TagSearch extends Tag
{

public $topicCount;

/**
 * @inheritdoc
 */
public function rules()
{
    return [
        [['topicCount'], 'safe']
    ];
}

public function search($params)
{
    // create ActiveQuery
    $query = Tag::find();
    $query->joinWith(['topicCount']);

    $dataProvider = new ActiveDataProvider([
        'query' => $query,
    ]);

    $dataProvider->sort->attributes['topicCount'] = [
        'asc' => ['topicCount' => SORT_ASC],
        'desc' => ['topicCount' => SORT_DESC],
    ];

    if (!($this->load($params) && $this->validate())) {
        return $dataProvider;
    }

    $query->andFilterWhere([
        //... other searched attributes here
    ])
    ->andFilterWhere(['=', 'topicCount', $this->topicCount]);

    return $dataProvider;
}

}
</code>```

And in the index view I can see the correct topicCount:

but on clicking the topicCount column I get the error:

exception 'PDOException' with message 'SQLSTATE[42703]: Undefined column: 7 ERROR:  column "topicCount" does not exist
LINE 1: SELECT * FROM "tags" ORDER BY "topicCount" LIMIT 100

Thanks for any guidance..!

[EDIT]

Following Lucas' advice, I've set my dataProvider query in my $dataProvider like this:

```<code>'query' => $query->select(['tags.*','(select count(topic_tags.id) from topic_tags where topic_tags.tag_id=tags.id) topicCount'])->groupBy('tags.id'),
</code>```

and I got error:

exception 'PDOException' with message 'SQLSTATE[42P01]: Undefined table: 7 ERROR:  missing FROM-clause entry for table "tags"

so I reformulated like this:

```<code>        'query' => $query->from('tags')->leftJoin('topic_tags','topic_tags.tag_id = tags.id')->select(['tags.*','(select count(topic_tags.id) from topic_tags where topic_tags.tag_id=tags.id) topicCount'])->groupBy('tags.id'),
</code>```

and now I get the result:

apparently the topicCount column is not set, so when I try to sort by it, it returns the error:

exception 'PDOException' with message 'SQLSTATE[42703]: Undefined column: 7 ERROR:  column "topicCount" does not exist

but when I try the SQL directly on the DB, it works fine:

so I suppose the problem is in the way Yii handles the alias 'topicCount'?

2nd EDIT

Still the same result without the topicCount set in the Grid view.
I show my TagSearch model, TagController and views/tag/index view file below:

TagSearch

```<code><?php

namespace common\models;

use Yii;
use yii\base\Model;
use yii\data\ActiveDataProvider;
use common\models\Tag;

/**
 * TagSearch represents the model behind the search form about `common\models\Tag`.
 */
class TagSearch extends Tag
{

    public $topicCount;

    /**
     * @inheritdoc
     */
    public function rules()
    {
        return [
            [['id', 'topicCount'], 'integer'],
            [['name', 'created_at', 'updated_at', 'topicCount'], 'safe'],
        ];
    }

    /**
     * @inheritdoc
     */
    public function scenarios()
    {
        // bypass scenarios() implementation in the parent class
        return Model::scenarios();
    }

    /**
     * Creates data provider instance with search query applied
     *
     * @param array $params
     *
     * @return ActiveDataProvider
     */
    public function search($params)
    {
        $query = Tag::find();

        $dataProvider = new ActiveDataProvider([
            'query' => $query->from("tags")->select(["tags.*","(select count(topic_tags.id) from topic_tags where topic_tags.tag_id=tags.id) topicCount"])->groupBy("tags.id"),
        ]);

        $this->load($params);

        if (!$this->validate()) {
            // uncomment the following line if you do not want to return any records when validation fails
            $query->where('0=1');
            return $dataProvider;
        }

        $query->andFilterWhere([
            'id' => $this->id,
            'topicCount' => $this->topicCount,
            'created_at' => $this->created_at,
            'updated_at' => $this->updated_at,
        ]);

        $query->andFilterWhere(['like', 'name', $this->name]);

        return $dataProvider;
    }
}
</code>```

Tag model

```<code><?php

namespace common\models;

use Yii;

/**
 * This is the model class for table "tags".
 *
 * @property integer $id
 * @property integer $topicCount
 * @property string $name
 * @property string $created_at
 * @property string $updated_at
 */
class Tag extends \yii\db\ActiveRecord
{

    public $topicCount;

    /**
     * @inheritdoc
     */
    public static function tableName()
    {
        return 'tags';
    }

    /**
     * @inheritdoc
     */
    public function rules()
    {
        return [
            [['topicCount'], 'integer'],
            [['name'], 'string'],
            [['created_at', 'updated_at'], 'required'],
            [['created_at', 'updated_at'], 'safe']
        ];
    }

    /**
     * @inheritdoc
     */
    public function attributeLabels()
    {
        return [
            'id' => 'ID',
            'name' => 'Name',
            'topicCount' => 'TC',
            'created_at' => 'Created At',
            'updated_at' => 'Updated At',
        ];
    }

}
</code>```

TagController

```<code>public function actionIndex()
{

    $searchModel = new TagSearch();
    $myModels = $searchModel->search([]);

    return $this->render('index', [
        'dataProvider' => $myModels,
    ]);
}
</code>```

tags/index

```<code><?= GridView::widget([
    'dataProvider' => $dataProvider,
    'columns' => [
        'id',
        'name',
        'topicCount',
        'created_at',
        'updated_at',
        ['class' => 'yii\grid\ActionColumn','template' => '{view}',],
    ],
]); ?>
</code>```

What am I missing?

答:
light solution is just reate view in PostgreSQL

and generate model via gii generator using as model and order & find work.

For update & delete use table model for search & index use view model.

For example

for actions update & delete use Tag model

for actions index & view  use TagView model.

Body:
[EDITED 2]

I'm having hard time to sort by the 'topicCount' which is defined as a relational getter on a model 'Tag'.
A Topic can have a lots of Tag, and wish to sort the Tags by how many Topics containing that Tag.

In my models/Tag.php:

public function getTopicCount()
{
    return TopicTag::find()->where(['tag_id' => $this->id])->count();
}

And in my views/tag/index.php:

<?= GridView::widget([
    'dataProvider' => $dataProvider,
    'columns' => [
        'id',
        'name',
        [
             'attribute'=>'topicCount',
             'value' => 'topicCount',
        ],
        'created_at',

        ['class' => 'yii\grid\ActionColumn','template' => '{view}',],
    ],
]); ?>

And in my controllers/TagController.php:

public function actionIndex()
{
    $dataProvider = new ActiveDataProvider([
        'query' => Tag::find(),
        'sort'=> [
            'defaultOrder' => ['id'=>SORT_DESC],
            'attributes' => ['id','topicCount'],
        ],
        'pagination' => [
            'pageSize' => 100,
        ],
    ]);

    return $this->render('index', [
        'dataProvider' => $dataProvider,
    ]);
}

And in my models/TagSearch.php:

<?php

namespace common\models;

use Yii;

/**
 * This is the model class for table "tags".
 *
 * @property integer $id
 * @property string $name
 * @property string $created_at
 * @property string $updated_at
 */
class TagSearch extends Tag
{

public $topicCount;

/**
 * @inheritdoc
 */
public function rules()
{
    return [
        [['topicCount'], 'safe']
    ];
}

public function search($params)
{
    // create ActiveQuery
    $query = Tag::find();
    $query->joinWith(['topicCount']);

    $dataProvider = new ActiveDataProvider([
        'query' => $query,
    ]);

    $dataProvider->sort->attributes['topicCount'] = [
        'asc' => ['topicCount' => SORT_ASC],
        'desc' => ['topicCount' => SORT_DESC],
    ];

    if (!($this->load($params) && $this->validate())) {
        return $dataProvider;
    }

    $query->andFilterWhere([
        //... other searched attributes here
    ])
    ->andFilterWhere(['=', 'topicCount', $this->topicCount]);

    return $dataProvider;
}

}

And in the index view I can see the correct topicCount:

but on clicking the topicCount column I get the error:

exception 'PDOException' with message 'SQLSTATE[42703]: Undefined column: 7 ERROR:  column "topicCount" does not exist
LINE 1: SELECT * FROM "tags" ORDER BY "topicCount" LIMIT 100

Thanks for any guidance..!

[EDIT]

Following Lucas' advice, I've set my dataProvider query in my $dataProvider like this:

'query' => $query->select(['tags.*','(select count(topic_tags.id) from topic_tags where topic_tags.tag_id=tags.id) topicCount'])->groupBy('tags.id'),

and I got error:

exception 'PDOException' with message 'SQLSTATE[42P01]: Undefined table: 7 ERROR:  missing FROM-clause entry for table "tags"

so I reformulated like this:

        'query' => $query->from('tags')->leftJoin('topic_tags','topic_tags.tag_id = tags.id')->select(['tags.*','(select count(topic_tags.id) from topic_tags where topic_tags.tag_id=tags.id) topicCount'])->groupBy('tags.id'),

and now I get the result:

apparently the topicCount column is not set, so when I try to sort by it, it returns the error:

exception 'PDOException' with message 'SQLSTATE[42703]: Undefined column: 7 ERROR:  column "topicCount" does not exist

but when I try the SQL directly on the DB, it works fine:

so I suppose the problem is in the way Yii handles the alias 'topicCount'?

2nd EDIT

Still the same result without the topicCount set in the Grid view.
I show my TagSearch model, TagController and views/tag/index view file below:

TagSearch

<?php

namespace common\models;

use Yii;
use yii\base\Model;
use yii\data\ActiveDataProvider;
use common\models\Tag;

/**
 * TagSearch represents the model behind the search form about `common\models\Tag`.
 */
class TagSearch extends Tag
{

    public $topicCount;

    /**
     * @inheritdoc
     */
    public function rules()
    {
        return [
            [['id', 'topicCount'], 'integer'],
            [['name', 'created_at', 'updated_at', 'topicCount'], 'safe'],
        ];
    }

    /**
     * @inheritdoc
     */
    public function scenarios()
    {
        // bypass scenarios() implementation in the parent class
        return Model::scenarios();
    }

    /**
     * Creates data provider instance with search query applied
     *
     * @param array $params
     *
     * @return ActiveDataProvider
     */
    public function search($params)
    {
        $query = Tag::find();

        $dataProvider = new ActiveDataProvider([
            'query' => $query->from("tags")->select(["tags.*","(select count(topic_tags.id) from topic_tags where topic_tags.tag_id=tags.id) topicCount"])->groupBy("tags.id"),
        ]);

        $this->load($params);

        if (!$this->validate()) {
            // uncomment the following line if you do not want to return any records when validation fails
            $query->where('0=1');
            return $dataProvider;
        }

        $query->andFilterWhere([
            'id' => $this->id,
            'topicCount' => $this->topicCount,
            'created_at' => $this->created_at,
            'updated_at' => $this->updated_at,
        ]);

        $query->andFilterWhere(['like', 'name', $this->name]);

        return $dataProvider;
    }
}

Tag model

<?php

namespace common\models;

use Yii;

/**
 * This is the model class for table "tags".
 *
 * @property integer $id
 * @property integer $topicCount
 * @property string $name
 * @property string $created_at
 * @property string $updated_at
 */
class Tag extends \yii\db\ActiveRecord
{

    public $topicCount;

    /**
     * @inheritdoc
     */
    public static function tableName()
    {
        return 'tags';
    }

    /**
     * @inheritdoc
     */
    public function rules()
    {
        return [
            [['topicCount'], 'integer'],
            [['name'], 'string'],
            [['created_at', 'updated_at'], 'required'],
            [['created_at', 'updated_at'], 'safe']
        ];
    }

    /**
     * @inheritdoc
     */
    public function attributeLabels()
    {
        return [
            'id' => 'ID',
            'name' => 'Name',
            'topicCount' => 'TC',
            'created_at' => 'Created At',
            'updated_at' => 'Updated At',
        ];
    }

}

TagController

public function actionIndex()
{

    $searchModel = new TagSearch();
    $myModels = $searchModel->search([]);

    return $this->render('index', [
        'dataProvider' => $myModels,
    ]);
}

tags/index

<?= GridView::widget([
    'dataProvider' => $dataProvider,
    'columns' => [
        'id',
        'name',
        'topicCount',
        'created_at',
        'updated_at',
        ['class' => 'yii\grid\ActionColumn','template' => '{view}',],
    ],
]); ?>

What am I missing?


问:
How do I get the standard file extension given a MIME type in Delphi?
Is there a built-in way to get the standard extension of a given MIME type in Delphi (XE7)?

I'm looking for the easiest and most general way to implement a function that would be called like this:

```<code>fileExt := GetExtension('text/xml');
</code>```

答:
It seems Indy has a built in function for that, on TIdThreadSafeMimeTable:

```<code>Uses
  IdCustomHTTPServer;

function GetMIMETypeDefaultExtension(const aMIMEType: String): String;
var
  mimetable: TIdThreadSafeMimeTable;
Begin
  if not(aMIMEType.Trim.IsEmpty) then
  Begin
    mimetable := TIdThreadSafeMimeTable.Create(true);
    try
      result := mimetable.GetDefaultFileExt(aMIMEType);
    finally
      mimetable.Free;
    end
  End
  else
      result := '';
End;
</code>```

Edit: function fixed to use TIdThreadSafeMimeTable directly without custom http server.

Body:
Is there a built-in way to get the standard extension of a given MIME type in Delphi (XE7)?

I'm looking for the easiest and most general way to implement a function that would be called like this:

fileExt := GetExtension('text/xml');

Body:
It seems Indy has a built in function for that, on TIdThreadSafeMimeTable:

Uses
  IdCustomHTTPServer;

function GetMIMETypeDefaultExtension(const aMIMEType: String): String;
var
  mimetable: TIdThreadSafeMimeTable;
Begin
  if not(aMIMEType.Trim.IsEmpty) then
  Begin
    mimetable := TIdThreadSafeMimeTable.Create(true);
    try
      result := mimetable.GetDefaultFileExt(aMIMEType);
    finally
      mimetable.Free;
    end
  End
  else
      result := '';
End;

Edit: function fixed to use TIdThreadSafeMimeTable directly without custom http server.


问:
Simple Mod_rewrite rule for a simple website (Classic) :(
I have been making my own little website with a small CMS. And i just can't get mod_rewrite to work for me, what i'm after seems simple and straightforward.
Right now my links look like this:
localhost/cms/?page=history,
localhost/cms/?news=galery-module
etc..
I want them to look like this:
localhost/cms/page/history

The code in my .htacess file right now is(but it does not seem to work although MOD_rewrite is on):

```<code>Options +FollowSymLinks
RewriteEngine on
RewriteCond %{SCRIPT_FILENAME} !-d
RewriteRule /cms1/([-A-z0-9]+) /cms1/?page=$1
</code>```

Thank you for your help!

答:
This should work:

```<code>Options +FollowSymLinks

RewriteEngine on

RewriteCond %{SCRIPT_FILENAME} !-d
RewriteCond %{SCRIPT_FILENAME} !-f

RewriteRule /cms1/([a-zA-Z0-9-]+)/?([a-zA-Z0-9-]*) /cms1/?$1=$2
</code>```

Also note that I wrote cms1 and not cms, it was in your rules but not in your urls, adjust accordingly.

Body:
I have been making my own little website with a small CMS. And i just can't get mod_rewrite to work for me, what i'm after seems simple and straightforward.
Right now my links look like this:
localhost/cms/?page=history,
localhost/cms/?news=galery-module
etc..
I want them to look like this:
localhost/cms/page/history

The code in my .htacess file right now is(but it does not seem to work although MOD_rewrite is on):

Options +FollowSymLinks
RewriteEngine on
RewriteCond %{SCRIPT_FILENAME} !-d
RewriteRule /cms1/([-A-z0-9]+) /cms1/?page=$1

Thank you for your help!

Body:
This should work:

Options +FollowSymLinks

RewriteEngine on

RewriteCond %{SCRIPT_FILENAME} !-d
RewriteCond %{SCRIPT_FILENAME} !-f

RewriteRule /cms1/([a-zA-Z0-9-]+)/?([a-zA-Z0-9-]*) /cms1/?$1=$2

Also note that I wrote cms1 and not cms, it was in your rules but not in your urls, adjust accordingly.


问:
Update a specific field in elastic search document
I am trying to update a document in elasticsearch,but instead the document gets deleted

```<code>POST /index/type/id/
{
   "id":1
   "field:"modified"
}
</code>```

What is the way to update a particular field in a document?The document contains an id field by which it is indexed.

答:
Do one thing.
Export your Elastic search in a file format using the below commands.

```<code>sudo npm install elasticsearch-tools -g

es-export-bulk --url http://localhost:9200 --file ~/Desktop/filename.json --index elastic_collection_name
</code>```

Then open that file and update all the data you want..
Then using the below command import it.

```<code>es-import-bulk --url http://localhost:9200 --file ~/Desktop/filename.json
</code>```

Try it.

Body:
I am trying to update a document in elasticsearch,but instead the document gets deleted

POST /index/type/id/
{
   "id":1
   "field:"modified"
}

What is the way to update a particular field in a document?The document contains an id field by which it is indexed.

Body:
Do one thing.
Export your Elastic search in a file format using the below commands.

sudo npm install elasticsearch-tools -g

es-export-bulk --url http://localhost:9200 --file ~/Desktop/filename.json --index elastic_collection_name

Then open that file and update all the data you want..
Then using the below command import it.

es-import-bulk --url http://localhost:9200 --file ~/Desktop/filename.json

Try it.


问:
Phonegap/Cordova: iOS not loading iframe content
I am trying to get iframes to work on iOS using Cordova CLI 6.2.0 and PhoneGap Desktop 0.3.3 . I have also asked for help at https://groups.google.com/forum/#!topic/phonegap/m1PPJuHtS8M

The iframes were working earlier in March, but have since stopped working. Due to attempts finding a solution, and other delays, I wasn't able to ask earlier and know the precise version numbers of when the error started.

To test possibilities, I made a simple app to test functionality. The parts I think are relevant include this of index.html here:

```<code>    <link rel="stylesheet" type="text/css" href="css/index.css" />
    <link rel="stylesheet" type="text/css" href="css/page.css" />
    <script type="text/javascript" src="js/jquery-1.12.3.min.js"></script>

    <title>Webpage Bring In Test</title>
</head>
<body>
    <div class="app">

        <p>First Paragraph</p>

        <iframe class="viewerStuff" src="http://www.uwsp.edu/library/Pages/default.aspx">
            <p>IFrame failed.</p>
        </iframe>

        <p>Second Paragraph</p>

        <object type="text/html" data="http://www.uwsp.edu/library/Pages/default.aspx" class="viewerStuff">
            <p>Object failed.</p>
        </object>

        <p>Third Paragraph</p>

        <p>-Update successfully loaded, though-</p>
    </div>
</code>```

and config.xml here:

```<code><feature name="IntentAndNavigationFilter">
<param name="ios-package" value="CDVIntentAndNavigationFilter"/>
<param name="onload" value="true"/>
</feature>
<access origin="*"/>
<allow-intent href="http://*/*"/>
<allow-intent href="https://*/*"/>
<gap:plugin name="org.apache.cordova.whitelist" source="npm" />
<plugin name="cordova-plugin-whitelist" version="1"/>
<allow-navigation href="*" />
<platform name="ios">
    <allow-intent href="itms:*"/>
    <allow-intent href="itms-apps:*"/>
</platform>
</code>```

There are other parts, but I don't think they are relevant.

Here's a picture of what it looks like on the Ipad being tested on.
https://lh3.googleusercontent.com/-NGwIXwKz5q0/V369CMFBzwI/AAAAAAAAAtE/EquMiMl0a1gDdkBFbp8kTTGiyRISF0YvwCLcB/s1600/Iframe%2BIOS%2BTests%2B4%2B07072016.jpg
I'm linking it as I don't have enough history on StackExchange to embed pictures.

Also, I can't use XCode for the solution. The place I am developing the app for doesn't want OS specific coding as part of their policy.

Let me know if you need more information or have any questions.

答:
try editing Content-Security-Policy in your index.html to:</p>

```<code><meta http-equiv="Content-Security-Policy" content="default-src 'self' data: gap: https://ssl.gstatic.com *; style-src 'self' 'unsafe-inline' 'unsafe-eval'; media-src *; img-src 'self' data: content:; script-src * 'self' 'unsafe-inline' 'unsafe-eval';">
</code>```

Body:
I am trying to get iframes to work on iOS using Cordova CLI 6.2.0 and PhoneGap Desktop 0.3.3 . I have also asked for help at https://groups.google.com/forum/#!topic/phonegap/m1PPJuHtS8M

The iframes were working earlier in March, but have since stopped working. Due to attempts finding a solution, and other delays, I wasn't able to ask earlier and know the precise version numbers of when the error started.

To test possibilities, I made a simple app to test functionality. The parts I think are relevant include this of index.html here:

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

    <title>Webpage Bring In Test</title>

First Paragraph

IFrame failed.

Second Paragraph

        <object type="text/html" data="http://www.uwsp.edu/library/Pages/default.aspx" class="viewerStuff">

Object failed.

        </object>

Third Paragraph

-Update successfully loaded, though-

and config.xml here:

<feature name="IntentAndNavigationFilter">
<param name="ios-package" value="CDVIntentAndNavigationFilter"/>
<param name="onload" value="true"/>
</feature>
<access origin="*"/>
<allow-intent href="http://*/*"/>
<allow-intent href="https://*/*"/>
<gap:plugin name="org.apache.cordova.whitelist" source="npm" />
<plugin name="cordova-plugin-whitelist" version="1"/>
<allow-navigation href="*" />
<platform name="ios">
    <allow-intent href="itms:*"/>
    <allow-intent href="itms-apps:*"/>
</platform>

There are other parts, but I don't think they are relevant.

Here's a picture of what it looks like on the Ipad being tested on.
https://lh3.googleusercontent.com/-NGwIXwKz5q0/V369CMFBzwI/AAAAAAAAAtE/EquMiMl0a1gDdkBFbp8kTTGiyRISF0YvwCLcB/s1600/Iframe%2BIOS%2BTests%2B4%2B07072016.jpg
I'm linking it as I don't have enough history on StackExchange to embed pictures.

Also, I can't use XCode for the solution. The place I am developing the app for doesn't want OS specific coding as part of their policy.

Let me know if you need more information or have any questions.

Body:
try editing Content-Security-Policy in your index.html to:

<meta http-equiv="Content-Security-Policy" content="default-src 'self' data: gap: https://ssl.gstatic.com *; style-src 'self' 'unsafe-inline' 'unsafe-eval'; media-src *; img-src 'self' data: content:; script-src * 'self' 'unsafe-inline' 'unsafe-eval';">


问:
Prevent popup login form from closing by validation error
a short version of my problem:
I have a Login form that popups by clicking 'Login'. Then the user can log in by enter email and password. After submitting the form and by success the user get redirecting to his profile.

What I want:
If there is an error in the validation like invalid email oder wrong password, then the login form should not be submitted but display a error message in the login popup instead. So by error the popup window should stay open.

The code:

Popup Login form:

```<code><div id="added_login">
    <div class="form_title">
        <h3>Anmelden</h3>
        <img id="form_close" src="images/close.png"/>
    </div>
    <form id="login_form" action="includes/login.inc.php" method="POST">
        <img src="images/or_line.png" />
        <p>Melde dich mit deiner E-Mail Adresse an</p>
        <input id="email" type="text" name="email" placeholder="E-Mail Adresse oder Benutzername">
        <input id="password" type="password" name="password" placeholder="Passwort eingeben">
        <div class="error_msg_container"></div>
        <input id="submit" class="button button_highlight" type="submit" name="submit_login" value="Anmelden">
        <div class="login_footer">
            <p class="forget_password">Passwort vergessen?</p>
            <p id="loginform_register" class="button_register">Registrieren</p>
        </div>
    </form>
</div>
</code>```

the jquery/ajax part for the popup form

```<code>$("#login_form").submit(function(e){
    e.preventDefault();
    var email = $("#email").val();
    var password = $("#password").val();
    var submit = $("#submit").val();
    $.ajax({
        type: "POST",
        url: "includes/login.inc.php",
        data: {
            email: email,
            password: password,
            submit_login: submit
        },
        success: function(data){
            $("#error_msg_container").html(data);
        },
        error: function(){
            alert("ERROR");
        }
    })
});
</code>```

the php part for the database:

```<code><?php

session_start();

//this function checks the user input
function IsEmail($email){
    if(filter_var($email, FILTER_VALIDATE_EMAIL)){
        //if user input is an email then return true
        return true;
    }else{
        //if user input isnt an email then return false
        return false;
    }
}

if (isset($_POST['submit_login'])) {
    include_once 'db_connect.inc.php';

    $loginid = mysqli_real_escape_string($conn, $_POST['email']);
    $password = mysqli_real_escape_string($conn, $_POST['password']);

    if(empty($loginid)){
        //Check for empty email
        echo "<p>E-Mail cannot be empty.</p>";
    }elseif(empty($password)){
        //Check for empty password
        echo "<p>Password cannot be empty.</p>";
    }else{
        $check_email = IsEmail($loginid);
        if($check_email){
            //is input an email
            $sql = "SELECT * FROM users WHERE email='$loginid'";
            $result = mysqli_query($conn, $sql);
        }else{
            //is email a username
            $sql = "SELECT * FROM users WHERE username='$loginid'";
            $result = mysqli_query($conn, $sql);
        }
        $resultCheck = mysqli_num_rows($result);
        //Check for user existing
        if($resultCheck < 1){
            echo "<p>No such a user found.</p>";
        }else{
            if($row = mysqli_fetch_assoc($result)){
                //Dehashing password
                $hashedPasswordCheck = password_verify($password, $row['password']);
                //Check for correct password
                if($hashedPasswordCheck == false){
                    header("Location: ../index.php?login=wrong_password");
                    exit();
                }elseif($hashedPasswordCheck == true){

                    if($row[active] == 0){
                        echo "<p>Your accent have to set on active</p>";
                    }else{
                        //Log in the user
                        $_SESSION[user_id] = $row[id];
                        $_SESSION[user_firstname] = $row[firstname];
                        $_SESSION[user_lastname] = $row[lastname];
                        $_SESSION[user_gender] = $row[gender];
                        $_SESSION[user_username] = $row[username];
                        $_SESSION[user_email] = $row[email];
                        $_SESSION[user_level] = $row[level];
                        $_SESSION[user_points] = $row[points];
                        $_SESSION[loggedIn] = true;

                        header("Location: ../index.php?login=success");
                        exit();
                    }
                }
            }
        }
    }

}else{
    header("Location: ../index.php");
    exit();
}
</code>```

The problem now is that nothing happen.. the popup login window stay open but the error message doesn't show up and even if the input are correct nothing happen..

Hope you guys can help me. Thx

答:
```<code>There is issue in your jquery code.
</code>```

<p>In ajax success function,you have mentioned div id 'error_msg_container' which is actually a class in html.
Code should be </p>

```<code>    success: function(data){
        $(".error_msg_container").html(data);
    }
</code>```

Body:
a short version of my problem:
I have a Login form that popups by clicking 'Login'. Then the user can log in by enter email and password. After submitting the form and by success the user get redirecting to his profile.

What I want:
If there is an error in the validation like invalid email oder wrong password, then the login form should not be submitted but display a error message in the login popup instead. So by error the popup window should stay open.

The code:

Popup Login form:

Anmelden

    <form id="login_form" action="includes/login.inc.php" method="POST">

Melde dich mit deiner E-Mail Adresse an

        <input id="email" type="text" name="email" placeholder="E-Mail Adresse oder Benutzername">
        <input id="password" type="password" name="password" placeholder="Passwort eingeben">

        <input id="submit" class="button button_highlight" type="submit" name="submit_login" value="Anmelden">

Passwort vergessen?

Registrieren

    </form>

the jquery/ajax part for the popup form

$("#login_form").submit(function(e){
    e.preventDefault();
    var email = $("#email").val();
    var password = $("#password").val();
    var submit = $("#submit").val();
    $.ajax({
        type: "POST",
        url: "includes/login.inc.php",
        data: {
            email: email,
            password: password,
            submit_login: submit
        },
        success: function(data){
            $("#error_msg_container").html(data);
        },
        error: function(){
            alert("ERROR");
        }
    })
});

the php part for the database:

<?php

session_start();

//this function checks the user input
function IsEmail($email){
    if(filter_var($email, FILTER_VALIDATE_EMAIL)){
        //if user input is an email then return true
        return true;
    }else{
        //if user input isnt an email then return false
        return false;
    }
}

if (isset($_POST['submit_login'])) {
    include_once 'db_connect.inc.php';

    $loginid = mysqli_real_escape_string($conn, $_POST['email']);
    $password = mysqli_real_escape_string($conn, $_POST['password']);

    if(empty($loginid)){
        //Check for empty email
        echo "
E-Mail cannot be empty.
";
    }elseif(empty($password)){
        //Check for empty password
        echo "
Password cannot be empty.
";
    }else{
        $check_email = IsEmail($loginid);
        if($check_email){
            //is input an email
            $sql = "SELECT * FROM users WHERE email='$loginid'";
            $result = mysqli_query($conn, $sql);
        }else{
            //is email a username
            $sql = "SELECT * FROM users WHERE username='$loginid'";
            $result = mysqli_query($conn, $sql);
        }
        $resultCheck = mysqli_num_rows($result);
        //Check for user existing
        if($resultCheck < 1){
            echo "
No such a user found.
";
        }else{
            if($row = mysqli_fetch_assoc($result)){
                //Dehashing password
                $hashedPasswordCheck = password_verify($password, $row['password']);
                //Check for correct password
                if($hashedPasswordCheck == false){
                    header("Location: ../index.php?login=wrong_password");
                    exit();
                }elseif($hashedPasswordCheck == true){

                    if($row[active] == 0){
                        echo "
Your accent have to set on active
";
                    }else{
                        //Log in the user
                        $_SESSION[user_id] = $row[id];
                        $_SESSION[user_firstname] = $row[firstname];
                        $_SESSION[user_lastname] = $row[lastname];
                        $_SESSION[user_gender] = $row[gender];
                        $_SESSION[user_username] = $row[username];
                        $_SESSION[user_email] = $row[email];
                        $_SESSION[user_level] = $row[level];
                        $_SESSION[user_points] = $row[points];
                        $_SESSION[loggedIn] = true;

                        header("Location: ../index.php?login=success");
                        exit();
                    }
                }
            }
        }
    }

}else{
    header("Location: ../index.php");
    exit();
}

The problem now is that nothing happen.. the popup login window stay open but the error message doesn't show up and even if the input are correct nothing happen..

Hope you guys can help me. Thx

Body:
There is issue in your jquery code.

In ajax success function,you have mentioned div id 'error_msg_container' which is actually a class in html.
Code should be

    success: function(data){
        $(".error_msg_container").html(data);
    }


问:
How can I display YouTube videos in a website built with materialize css?
I have the following html within my materializecss website. I referred to the documentation at http://materializecss.com/media-css.html).

```<code><div class = "col s12 m6">
    <div class="video-container">
        <iframe src="//www.youtube.com/embed/7yDXeEJEi0A?wmode=opaque" frameborder="0" allowfullscreen></iframe>
    </div>
</div>
</code>```

When I view this page, all I see is an error message. The video is working fine on YouTube itself (I tried other videos also, no luck).

Other elements on this page (images, text, dropdown) are working fine. Any help will be greatly appreciated.

`

答:
Try adding http:// before video URL
i have checked. it is working fine at my end, if i add http:// or https:// (https required SSL on your server/webpage) to play properly.

```<code><div class = "col s12 m6">
    <div class="video-container">
        <iframe src="http://www.youtube.com/embed/7yDXeEJEi0A?wmode=opaque" frameborder="0" allowfullscreen></iframe>
    </div>
</div>
</code>```

Body:
I have the following html within my materializecss website. I referred to the documentation at http://materializecss.com/media-css.html).

When I view this page, all I see is an error message. The video is working fine on YouTube itself (I tried other videos also, no luck).

Other elements on this page (images, text, dropdown) are working fine. Any help will be greatly appreciated.

`

Body:
Try adding http:// before video URL
i have checked. it is working fine at my end, if i add http:// or https:// (https required SSL on your server/webpage) to play properly.

<div class = "col s12 m6">
    <div class="video-container">
        <iframe src="http://www.youtube.com/embed/7yDXeEJEi0A?wmode=opaque" frameborder="0" allowfullscreen></iframe>
    </div>
</div>


问:
R_loading R data files in a loop and assigning a same variable name
Hi I have several RData files with the same file name and object name. For example one of the file names is int.5.RData where the dataframe int.5 is saved. I have several similar files with names int.5.RData, int.10.RData, and so on. Now I have to load them  and assign a same variable name (say new.int) to the data frames( int.5, int.10, etc) in a for loop. I can load them by using load(paste0("int",i,".RData")) in the for loop where i is c(5,10,...), But I am stuck with the next step where I have to assign the data frames (int.5, int.10,etc) the same name, int.new in the same loop as I can't use pastecommand for that operation. Can anybody help me here?

答:
<s> Look at assign.. </s>

Edit:

In that case look at get function:

```<code>> a <- 5
> get("a")
[1] 5
</code>```

Body:
<s> Look at assign.. </s>

Edit:

In that case look at get function:

> a <- 5
> get("a")
[1] 5


问:
Passing Array to model function query codeigniter
Here is my function I want to put array values in IN() clause but it is not working

    Here $ids is the array passing to it.

```<code>    function get_school_students_data($ids){
    $query=$this->db->query("SELECT * FROM screening_answers where uid
    IN(".implode(',',$ids).")");
    $result=$query->result_array();
     return $query->num_rows();
    }
</code>```

答:
It's best to use the active record of codeigniter

```<code>$this->db->query("SELECT * FROM screening_answers where uid
IN(".implode(',',$ids).")");
</code>```

become

```<code>$this->db->select();
$this->db->from('screening_answer');
$this->db->where_in('uid',$ids);
</code>```

Body:
Here is my function I want to put array values in IN() clause but it is not working

    Here $ids is the array passing to it.

    function get_school_students_data($ids){
    $query=$this->db->query("SELECT * FROM screening_answers where uid
    IN(".implode(',',$ids).")");
    $result=$query->result_array();
     return $query->num_rows();
    }

Body:
It's best to use the active record of codeigniter

$this->db->query("SELECT * FROM screening_answers where uid
IN(".implode(',',$ids).")");

become

$this->db->select();
$this->db->from('screening_answer');
$this->db->where_in('uid',$ids);


问:
Access-Control-Allow-Origin is not matched when server responds 304
I have an API server api.example.com and two websites a.example.com, b.example.com. To enable CORS, I set up CORS headers for them.

An XHR request from a.example.com will get the response headers from api.example.com

```
access-control-allow-credentials: true
access-control-allow-methods: GET, HEAD, POST, PUT, PATCH, DELETE, OPTIONS
access-control-allow-origin: https://a.example.com
access-control-max-age: 0
vary: origin
```

Similarly, an XHR request from b.example.com will get the response headers from api.example.com

```
access-control-allow-credentials: true
access-control-allow-methods: GET, HEAD, POST, PUT, PATCH, DELETE, OPTIONS
access-control-allow-origin: https://b.example.com
access-control-max-age: 0
vary: origin
```

When I fetches resource GET api.example.com/articles/1 in a.example.com and then go to b.example.com do the same action to fetch the resource. The browser will use if-none-match headers to get the resource and receives a 304 response code from server. Then it complains that Access-Control-Allow-Origin header has a value https://a.example.com that is not equal to the supplied origin. Origin https://b.example.com is therefore not allowed access.

I think browser uses its cache when 304 is responded and find out Access-Control-Allow-Origin is cached as a.example.com's resource therefore refuse to fulfill the request.

How can I mitigate the issue here? Any thought?

答:
Requests are cached, including its content and headers.

When you access a the first time. The response is generated and saved in the cache.

When you access b afterwards. The 304 response comes with no header and no content, all it does is instruct the browser to use the cache. The cached response has headers for the other site and it throws an access error.

These two requests should not be answered with a 304 since they are not equivalent.

If-None-Match means that pages are identified with en ETag. An arbitrary string generated by the application to identify a cachable version of a page.

You should modify the application to generate different ETag for different Origin.

Body:
I have an API server api.example.com and two websites a.example.com, b.example.com. To enable CORS, I set up CORS headers for them.

An XHR request from a.example.com will get the response headers from api.example.com

access-control-allow-credentials: true
access-control-allow-methods: GET, HEAD, POST, PUT, PATCH, DELETE, OPTIONS
access-control-allow-origin: https://a.example.com
access-control-max-age: 0
vary: origin

Similarly, an XHR request from b.example.com will get the response headers from api.example.com

access-control-allow-credentials: true
access-control-allow-methods: GET, HEAD, POST, PUT, PATCH, DELETE, OPTIONS
access-control-allow-origin: https://b.example.com
access-control-max-age: 0
vary: origin

When I fetches resource GET api.example.com/articles/1 in a.example.com and then go to b.example.com do the same action to fetch the resource. The browser will use if-none-match headers to get the resource and receives a 304 response code from server. Then it complains that Access-Control-Allow-Origin header has a value https://a.example.com that is not equal to the supplied origin. Origin https://b.example.com is therefore not allowed access.

I think browser uses its cache when 304 is responded and find out Access-Control-Allow-Origin is cached as a.example.com's resource therefore refuse to fulfill the request.

How can I mitigate the issue here? Any thought?


问:
Chrome Extension: Can Javascript intercept a file download and parse the data
I'm writing a Chrome Extension to automate one of my daily tasks, part of the task is downloading a .csv file and manipulating the data. As part of the automation I want to grab the file with Javascript and make the script manipulate it.

The problem is grabbing this file with an XMLHttpRequest would be a nightmare because they send heaps of unique IDs to verify the user and it'd be a nightmare to work out where they come from.

I can easily click the button using javascript which starts the file download, but is there a way that javascript can intercept this request and parse the CSV? I'm thinking if its not possible with plain javascript I might be able to do it with the HTML5 file API?

答:
You can do it by accessing the file's content with an AJAX request to file://{filepath} once the file has been downloaded. You just need to add the file://*permission to your manifest file.

To get the downloaded file's path in the local system, use chrome.downloads.search and get the filenameproperty.


问:
Segmentation error and free memory though no pointer used
I was trying a question to print nearest prime ASCII but no output is coming. What is the problem and how to solve it?

Code:

```<code>#include <iostream>
using namespace std;

bool isPrime(int p) {
    bool result = true;
    for (int i = 2; i <= p / 2; i++) {
        if (p%i == 0) {
            result = false;
            break;
        }
    }
    return result;
}

int goLeft(int l) {
    if (l != 65) {
        for (int i = l; i>65; i--) {
            if (isPrime(i))
                return i;
        }
        return 0;
    }
    else {
        return 0;
    }
}

int goRight(int r) {
    if (r != 122) {
        for (int i = r; i<122; i++) {
            if (isPrime(i))
                return i;
        }
        return 0;
    }
    else {
        return 0;
    }
}

int performAll(int l, int r, int p) {
    int diffLeft = 0, diffRight = 0;

    if (l == 0 && r != 0) {
        diffLeft = diffRight = r;
    }
    else if (l != 0 && r == 0) {
        diffRight = diffLeft = l;
    }
    else if (l == 0 && r == 0) {
        diffRight = diffLeft = 0;
    }
    else {
        diffLeft = p - l;
        diffRight = r - p;
    }

    if (diffLeft > diffRight) {
        return r;
    }
    else if (diffLeft < diffRight) {
        return l;
    }
    else {
        if (l<r) {
            if (l != 0) {
                return l;
            }
            else {
                return r;
            }
        }
        else if (l>r) {
            if (r != 0) {
                return r;
            }
            else {
                return l;
            }
        }
    }
return 0;
}

int main()
{
    int T, N;
    int left = 0, right = 0, ss = 0;
    cin >> T;
    string S, R;
    while (T>0) {
        cin >> N;
        cin >> S[j];

        for (int i = 0; i<N; i++) {
            cout << "i-" << i << endl;
            ss = S[i];
            if ((ss >= 65 && ss <= 90) || (ss >= 97 && ss <= 122)) {
                if (isPrime(ss)) {
                    R[i] = S[i];
                }
                else {
                    left = goLeft(ss);
                    right = goRight(ss);
                    R[i] = performAll(left, right, ss);
                }
            }
            else {
                if (ss<65) {
                    left = 0;
                    right = 67;
                }
                else if (ss>122) {
                    left = 113;
                    right = 0;
                }
                else {
                    left = goLeft(ss);
                    right = goRight(ss);
                }
                R[i] = performAll(left, right, ss);
            }
            cout << R[i];
        }
        T--;
    }

    return 0;
}
</code>```

Input:

```<code>1
</code>```

375
AvfmaLgLRpQadLyThsxVzkUqbFOdxfbLGdpBWOwmAnflENlYFbdhNHerHVtZkaPLgMtNQovVHpwGfHJdXXWAhYrhwXKPxtnpxCIsaXVAkcxTpVprFNeOVcnSEsgIvfqXPRSUASSDCvAGrFJCDbzGLFhrMYWALElChmurLrEeQttIWctyhQXzZUVAYuCIZecBJbXMxlMHFbZxJRTSZJmZAwCggGabVsovqBrdmmbCTaIHDfUunLFntfGzodKqoAKwCassKMDybethRaQgegsOawfNCNrIAkECEKpbwElhvWtlZBEZqJQpEkzpiSjrqZZIHbszUxwuWreXkxFKxSAiKoemIqETGVxcCjweKhbyXxhVKCbNTQBKgHD

```<code>Your Code's Output
</code>```

"Your code didn't print anything."

答:
cin>>S[j]; is accessing S out-of-bounds, because S is empty. You may want to replace it with e.g.:

```<code>char ch;
cin >> ch;
S += ch;
</code>```

or just read the whole string at once without entering the length first:

```<code>cin >> S;
</code>```

Also I get a compiler error "Control may reach end of non-void function" for performAll. I.e. it's missing a return statement.

Body:
I was trying a question to print nearest prime ASCII but no output is coming. What is the problem and how to solve it?

Code:

#include <iostream>
using namespace std;

bool isPrime(int p) {
    bool result = true;
    for (int i = 2; i <= p / 2; i++) {
        if (p%i == 0) {
            result = false;
            break;
        }
    }
    return result;
}

int goLeft(int l) {
    if (l != 65) {
        for (int i = l; i>65; i--) {
            if (isPrime(i))
                return i;
        }
        return 0;
    }
    else {
        return 0;
    }
}

int goRight(int r) {
    if (r != 122) {
        for (int i = r; i<122; i++) {
            if (isPrime(i))
                return i;
        }
        return 0;
    }
    else {
        return 0;
    }
}

int performAll(int l, int r, int p) {
    int diffLeft = 0, diffRight = 0;

    if (l == 0 && r != 0) {
        diffLeft = diffRight = r;
    }
    else if (l != 0 && r == 0) {
        diffRight = diffLeft = l;
    }
    else if (l == 0 && r == 0) {
        diffRight = diffLeft = 0;
    }
    else {
        diffLeft = p - l;
        diffRight = r - p;
    }

    if (diffLeft > diffRight) {
        return r;
    }
    else if (diffLeft < diffRight) {
        return l;
    }
    else {
        if (l<r) {
            if (l != 0) {
                return l;
            }
            else {
                return r;
            }
        }
        else if (l>r) {
            if (r != 0) {
                return r;
            }
            else {
                return l;
            }
        }
    }
return 0;
}

int main()
{
    int T, N;
    int left = 0, right = 0, ss = 0;
    cin >> T;
    string S, R;
    while (T>0) {
        cin >> N;
        cin >> S[j];

        for (int i = 0; i<N; i++) {
            cout << "i-" << i << endl;
            ss = S[i];
            if ((ss >= 65 && ss <= 90) || (ss >= 97 && ss <= 122)) {
                if (isPrime(ss)) {
                    R[i] = S[i];
                }
                else {
                    left = goLeft(ss);
                    right = goRight(ss);
                    R[i] = performAll(left, right, ss);
                }
            }
            else {
                if (ss<65) {
                    left = 0;
                    right = 67;
                }
                else if (ss>122) {
                    left = 113;
                    right = 0;
                }
                else {
                    left = goLeft(ss);
                    right = goRight(ss);
                }
                R[i] = performAll(left, right, ss);
            }
            cout << R[i];
        }
        T--;
    }

    return 0;
}

Input:

1

375
AvfmaLgLRpQadLyThsxVzkUqbFOdxfbLGdpBWOwmAnflENlYFbdhNHerHVtZkaPLgMtNQovVHpwGfHJdXXWAhYrhwXKPxtnpxCIsaXVAkcxTpVprFNeOVcnSEsgIvfqXPRSUASSDCvAGrFJCDbzGLFhrMYWALElChmurLrEeQttIWctyhQXzZUVAYuCIZecBJbXMxlMHFbZxJRTSZJmZAwCggGabVsovqBrdmmbCTaIHDfUunLFntfGzodKqoAKwCassKMDybethRaQgegsOawfNCNrIAkECEKpbwElhvWtlZBEZqJQpEkzpiSjrqZZIHbszUxwuWreXkxFKxSAiKoemIqETGVxcCjweKhbyXxhVKCbNTQBKgHD

Your Code's Output

"Your code didn't print anything."

Body:
cin>>S[j]; is accessing S out-of-bounds, because S is empty. You may want to replace it with e.g.:

char ch;
cin >> ch;
S += ch;

or just read the whole string at once without entering the length first:

cin >> S;

Also I get a compiler error "Control may reach end of non-void function" for performAll. I.e. it's missing a return statement.


问:
Can not get database generated value after saving
I'm using SpringBoot, Spring data and postgresql.

In postgres I created one table.

```<code>CREATE EXTENSION "uuid-ossp";
CREATE TABLE user (
    id serial PRIMARY KEY not null,
    user_id varchar(255) not null default uuid_generate_v4()
);
</code>```

Than create entity

```<code>@Entity
public class User implements Serializable {

  private static final long serialVersionUID = 9129894781337596497L;

  @Id
  @GeneratedValue(strategy = GenerationType.IDENTITY)
  @Column(columnDefinition = "serial")
  private Integer id;

  @Column(insertable = false)
  private String userId;

  public static User create(){
    User user = new User();
    return user;
  }

  public String getUserId(){
    return userId;
  }

}
</code>```

Than create jpa repository like this

```<code>@Repository
public interface UserRepository extends JpaRepository<User, Integer> {}
</code>```

When I save the user I need to get id and userId but I get null instead and in database is generated UUID.

```<code>User user = userRepository.save(User.create());
assertThat(user.getUserId()).isNotNull();
</code>```

How can I get those generated values from database?

答:
You have to re-read the inserted entity OR (since Hibernate 3.2?) you can specify @Generated(GenerationTime.INSERT) on the column ( https://docs.jboss.org/hibernate/orm/5.0/topical/html/generated/GeneratedValues.html#_legacy_support_in_database_generation ), which causes hibernate to re-read the attribute value after insert.

I've created a little demo:

http://peter.risko.hu/java_incubator/spring_data_postgres_uuid.zip

The User entity:

```<code>@Id
@SequenceGenerator(name="seq", sequenceName="seq")
@GeneratedValue(strategy = GenerationType.SEQUENCE, generator="seq")
@Column(columnDefinition = "serial")
private Integer id;

@Column(insertable = false, name="user_id")
private String userId;

public String getUserId(){
    return userId;
}

public static User create(){
    User user = new User();
    log.info("user created in memory: " + user);
    return user;
}

public Integer getId(){
    return id;
}

@Override
public String toString() {
    return "[id: " + id + ", userId: " + userId + "]";
}
</code>```

The test:

```<code>@Test
public void testInsert() {
    User u = userRepository.save(User.create());
    log.info("user after save: " + u);
    log.info("users queried from db: " + userRepository.findAll());
}
</code>```

The output:

```<code>tst.User - user created in memory: [id: null, userId: null]
tst.UserRepositoryTest - user after save: [id: 960, userId: null]
tst.UserRepositoryTest - users queried from db: [[id: 960, userId: dc7cdc53-984d-4051-a3f3-ecc7136d9fd8]]
</code>```

If I apply the @Generated(GenerationTime.INSERT):

```<code>@Column(insertable = false, name="user_id")
@Generated(GenerationTime.INSERT)
private String userId;
</code>```

Then the result is:

```<code>tst.User - user created in memory: [id: null, userId: null]
tst.UserRepositoryTest - user after save: [id: 961, userId: c68ea300-2f20-47ea-a76d-6e1aaf97a5ea]
tst.UserRepositoryTest - users queried from db: [[id: 960, userId: dc7cdc53-984d-4051-a3f3-ecc7136d9fd8], [id: 961, userId: c68ea300-2f20-47ea-a76d-6e1aaf97a5ea]]
</code>```

Body:
I'm using SpringBoot, Spring data and postgresql.

In postgres I created one table.

CREATE EXTENSION "uuid-ossp";
CREATE TABLE user (
    id serial PRIMARY KEY not null,
    user_id varchar(255) not null default uuid_generate_v4()
);

Than create entity

@Entity
public class User implements Serializable {

  private static final long serialVersionUID = 9129894781337596497L;

  @Id
  @GeneratedValue(strategy = GenerationType.IDENTITY)
  @Column(columnDefinition = "serial")
  private Integer id;

  @Column(insertable = false)
  private String userId;

  public static User create(){
    User user = new User();
    return user;
  }

  public String getUserId(){
    return userId;
  }

}

Than create jpa repository like this

@Repository
public interface UserRepository extends JpaRepository<User, Integer> {}

When I save the user I need to get id and userId but I get null instead and in database is generated UUID.

User user = userRepository.save(User.create());
assertThat(user.getUserId()).isNotNull();

How can I get those generated values from database?

Body:
You have to re-read the inserted entity OR (since Hibernate 3.2?) you can specify @Generated(GenerationTime.INSERT) on the column ( https://docs.jboss.org/hibernate/orm/5.0/topical/html/generated/GeneratedValues.html#_legacy_support_in_database_generation ), which causes hibernate to re-read the attribute value after insert.

I've created a little demo:

http://peter.risko.hu/java_incubator/spring_data_postgres_uuid.zip

The User entity:

@Id
@SequenceGenerator(name="seq", sequenceName="seq")
@GeneratedValue(strategy = GenerationType.SEQUENCE, generator="seq")
@Column(columnDefinition = "serial")
private Integer id;

@Column(insertable = false, name="user_id")
private String userId;

public String getUserId(){
    return userId;
}

public static User create(){
    User user = new User();
    log.info("user created in memory: " + user);
    return user;
}

public Integer getId(){
    return id;
}

@Override
public String toString() {
    return "[id: " + id + ", userId: " + userId + "]";
}

The test:

@Test
public void testInsert() {
    User u = userRepository.save(User.create());
    log.info("user after save: " + u);
    log.info("users queried from db: " + userRepository.findAll());
}

The output:

tst.User - user created in memory: [id: null, userId: null]
tst.UserRepositoryTest - user after save: [id: 960, userId: null]
tst.UserRepositoryTest - users queried from db: [[id: 960, userId: dc7cdc53-984d-4051-a3f3-ecc7136d9fd8]]

If I apply the @Generated(GenerationTime.INSERT):

@Column(insertable = false, name="user_id")
@Generated(GenerationTime.INSERT)
private String userId;

Then the result is:

tst.User - user created in memory: [id: null, userId: null]
tst.UserRepositoryTest - user after save: [id: 961, userId: c68ea300-2f20-47ea-a76d-6e1aaf97a5ea]
tst.UserRepositoryTest - users queried from db: [[id: 960, userId: dc7cdc53-984d-4051-a3f3-ecc7136d9fd8], [id: 961, userId: c68ea300-2f20-47ea-a76d-6e1aaf97a5ea]]