问:
Javascript - why is this undefined?
The alert at the start shows "undefined", why?

The alerts come in this order:

"success!"

"Data" (what it should be)

"undefined"

I read through multiple threads, the problem was always that ajax was asynchronous, so the data was not defined when it was accessed, but in my case the data is there, the alert in my function shows the data BEFORE the other alert where it is undefined!

Very grateful for any help!

I got this code

```<code>var data = getData("");
alert(data);            <<<<<<< UNDEFINED

function getData(fileName) {

    $.ajax({
        async:false,
        type: "GET",
        url: "breastCancer.csv",
        dataType: "text",
        success: function (data) {
            var arrData = processData(data);
            alert("success!");
            alert(arrData);      <<<<< WORKS GREAT
            return arrData;
        },
    });

}

function processData(data) {

    var arrData = CSVToArray(data);

    dimensions = arrData[0];
    var objects = [];

    objects[0] = dimensions;

    for (var i = 1; i < arrData.length; i++){
        objects[i] = new Object();

        for (var j = 0; j < dimensions.length; j++){
            objects[i][dimensions[j]] = arrData[i][j];
        }
    }

    return objects;
}
</code>```

To clarify, I know asynchronous is the way to go for user experience, but this page just has to show data from this call, so its okay for me to wait for it.

答: Your getData function doesn't return anything.

Title: Javascript - why is this undefined?

Body:
The alert at the start shows "undefined", why?

The alerts come in this order:

"success!"

"Data" (what it should be)

"undefined"

I read through multiple threads, the problem was always that ajax was asynchronous, so the data was not defined when it was accessed, but in my case the data is there, the alert in my function shows the data BEFORE the other alert where it is undefined!

Very grateful for any help!

I got this code

var data = getData("");
alert(data);            <<<<<<< UNDEFINED

function getData(fileName) {

    $.ajax({
        async:false,
        type: "GET",
        url: "breastCancer.csv",
        dataType: "text",
        success: function (data) {
            var arrData = processData(data);
            alert("success!");
            alert(arrData);      <<<<< WORKS GREAT
            return arrData;
        },
    });

}

function processData(data) {

    var arrData = CSVToArray(data);

    dimensions = arrData[0];
    var objects = [];

    objects[0] = dimensions;

    for (var i = 1; i < arrData.length; i++){
        objects[i] = new Object();

        for (var j = 0; j < dimensions.length; j++){
            objects[i][dimensions[j]] = arrData[i][j];
        }
    }

    return objects;
}

To clarify, I know asynchronous is the way to go for user experience, but this page just has to show data from this call, so its okay for me to wait for it.


来源: stackexchange

问:
ajax - can't retrieve data (same domain)
EDIT: Cavid Kərimov's answer does work. Setting the form as below does also work.

```<code><form onsubmit="return false;"></form>
</code>```

I'm trying to retrieve a simple string of text from a PHP file using jQuery and AJAX as shown below:

index.html

```<code>$.get("echo.php", function(data, status) {
    console.log("success: " + data);
}).fail(function(jqXHR, textStatus, error) {
    console.log("failed: " + JSON.stringify(jqXHR));
});
</code>```

echo.php

```<code><?php

    echo "echoed from php successfully";

?>
</code>```

But I'm getting the following error:

```<code>failed: {"readyState":0,"status":0,"statusText":"error"}
</code>```

I googled around for a bit and apparently this happens because of the Same-origin Policy, however I'm sure that isn't the case here because the HTML and PHP file are stored in the exact same folder on the server.

答:
Use this and tell us what happened:</p>

```<code>         $("#go").click(function() {
                console.log("clicked");

                var $id = $("#id").val();
                console.log("id: " + $id);

                $.get("echo.php", function(data) {
                    console.log("success: " + data);
                }).fail(function(data) {
                    console.log("failed: " + data);
                });

             return false;
            });
</code>```

ContentLicense: CC BY-SA 3.0

Body:
EDIT: Cavid Kərimov's answer does work. Setting the form as below does also work.

<form onsubmit="return false;"></form>

I'm trying to retrieve a simple string of text from a PHP file using jQuery and AJAX as shown below:

index.html

$.get("echo.php", function(data, status) {
    console.log("success: " + data);
}).fail(function(jqXHR, textStatus, error) {
    console.log("failed: " + JSON.stringify(jqXHR));
});

echo.php

<?php

    echo "echoed from php successfully";

?>

But I'm getting the following error:

failed: {"readyState":0,"status":0,"statusText":"error"}

I googled around for a bit and apparently this happens because of the Same-origin Policy, however I'm sure that isn't the case here because the HTML and PHP file are stored in the exact same folder on the server.

Body:
Use this and tell us what happened:

         $("#go").click(function() {
                console.log("clicked");

                var $id = $("#id").val();
                console.log("id: " + $id);

                $.get("echo.php", function(data) {
                    console.log("success: " + data);
                }).fail(function(data) {
                    console.log("failed: " + data);
                });

             return false;
            });


问:
Usage of 2nd level cache entity with hibernate 5.2
I recently upgraded my java application from hibernate 4.1 to hibernate 5.2 and I noticed (by looking at the SQL traces) a difference in the 2nd level entity cache usage. The cache does not get used as often as with the previous version.

To make things simple, let's say I have a very basic model: a CHILD entity with a many to one relation to its PARENT. The PARENT class is annotated with an @Cache(usage = CacheConcurrencyStrategy.READ_WRITE). The many to one relation in the CHILD is annotated with @Fetch(FetchMode.SELECT). This should let an opportunity for the 2nd level cache to store the PARENT when fetching CHILD.

When I a load a single CHILD instance (with a query like from CHILD where id=:id), I see that the PARENT cache is used. If I execute the query again, the PARENT secondary select is not repeated to the database.

However, when I load multiple CHILDs at once (with a query like from CHILD), the PARENT cache is not used. If I execute the query again, the secondary PARENT select is repeated.

This is a big loss of performances. Has anybody encountered the same problem? Am I missing some configuration part?

Thanks for your help.

答:
After I spending more time on this problem, I discovered that it is caused by a native query executed before the read many CHILDs. This native query sets a parameter in the database session (SET LOCAL TIME ZONE '<TIMEZONEID>') which is used to do some computation on dates in the user timezone.

The read CHILDs method is annotated with @Transactional(readOnly = true) but setting the time zone parameter in the session requires a call to query.executeUpdate() although it does not change entities. This seems to be what is causing the cache to stop storing entities.

I am still looking for a workaround, but I know that it is not related to a specific hibernate version nor reading one vs multiple CHILDs at once.


问:
show custom dialog only once with onclick Button
i'm trying to show my custom dialog only once ; firstly i have a custom dialog contains one button OK when i click ok button and re open app i want to hide the custom dialog for that i tried to use SharedPreference

```<code>   SharedPreferences.Editor editor;
    SharedPreferences pref;
    @SuppressLint("CommitPrefEdits")
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        pref = getApplicationContext().getSharedPreferences("MyPref", 0);
        editor = pref.edit();
        editor.putBoolean("key_name", false);

/**/

 if (pref.getBoolean("key_name", true)) {
                users();
  }

private void users() {
        final Dialog myDialog = new Dialog(MainActivity.this);
        myDialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
        assert myDialog.getWindow() != null;
        myDialog.getWindow().setBackgroundDrawable(new ColorDrawable(Color.TRANSPARENT));
        myDialog.setCancelable(false);
        myDialog.setContentView(R.layout.users_artwork_dialog);
        Button okbtn = myDialog.findViewById(R.id.okbtn);

        okbtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                SharedPreferences pref = getApplicationContext().getSharedPreferences("MyPref", 0);
                @SuppressLint("CommitPrefEdits") SharedPreferences.Editor editor = pref.edit();
                editor.putBoolean("key_name", false);
                myDialog.dismiss();
            }
        });
        myDialog.show();
    }
</code>```

答: You should do editor.commit() or editor.apply() to save the changes to SharedPreference in users() method. That should solve the problem.

Body:
i'm trying to show my custom dialog only once ; firstly i have a custom dialog contains one button OK when i click ok button and re open app i want to hide the custom dialog for that i tried to use SharedPreference

   SharedPreferences.Editor editor;
    SharedPreferences pref;
    @SuppressLint("CommitPrefEdits")
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        pref = getApplicationContext().getSharedPreferences("MyPref", 0);
        editor = pref.edit();
        editor.putBoolean("key_name", false);

/**/

 if (pref.getBoolean("key_name", true)) {
                users();
  }

private void users() {
        final Dialog myDialog = new Dialog(MainActivity.this);
        myDialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
        assert myDialog.getWindow() != null;
        myDialog.getWindow().setBackgroundDrawable(new ColorDrawable(Color.TRANSPARENT));
        myDialog.setCancelable(false);
        myDialog.setContentView(R.layout.users_artwork_dialog);
        Button okbtn = myDialog.findViewById(R.id.okbtn);

        okbtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                SharedPreferences pref = getApplicationContext().getSharedPreferences("MyPref", 0);
                @SuppressLint("CommitPrefEdits") SharedPreferences.Editor editor = pref.edit();
                editor.putBoolean("key_name", false);
                myDialog.dismiss();
            }
        });
        myDialog.show();
    }


问:
Use virtual property to access nested document in Mongoose model
Im trying to create a virtual item in one of my schemas, that will need access to data thats referenced by an item thats referenced in this schema (Yes, thats 2 references deep, connecting 3 schemas/models)

I've tried to simulate the code as close as I can here, using Model/Schema A/B/C..

This would be the schema for the ModelA, which contains the virtual item which depends on the references:

// models/modela.js

// SchemaA for ModelA
const SchemaA = new Schema({
    _foo: {
        // References ModelB
        type: Schema.Types.ObjectId,
        ref: 'ModelB'
    }
})

// Virtual `Modela.something`, which needs the data from ModelC.baz
SchemaA.virtual('something').get(function () {
    // How can I access ModelC.baz
    return 'Value from ModelC'
});
```

<p>Then heres the schema for <strong>ModelB</strong>:</p>

<pre class="lang-js prettyprint-override"><code>// models/modelb.js

// SchemaB for ModelB
const SchemaB = new Schema({
    _bar: [{
        // References ModelC.baz
        type: Schema.Types.ObjectId,
        ref: 'ModelC'
    }]
})
</code>```

And the schema for ModelC:

// models/modelc.js

// SchemaC for ModelC
const SchemaC = new Schema({
    baz: Schema.Types.String
})
```

<p>As you can see above, what I need to do, is access <strong>Modelc.haz</strong> from within the virtual <code>something</code> item in <strong>ModelA</strong></p>

<p>I thought that if I did both of the populations via the query itself, then maybe this would work, So I tried something like:</p>

<pre class="lang-js prettyprint-override"><code>this.find()
    .populate( '_foo' )
    .populate( '_foo._bar' )
</code>```

Which didn't work (which I actually didn't really expect it to, but oh well)

答:
You can find more information about this at this github issue. You can use query hooks.

I had similar issue, so I used it to populate reference models to use in a virtual function. Here is a sample.

```<code>const tutorialSchema = new mongoose.Schema({
    title: {
        type: String,
        required: true
    },
    videos: [
        {
            type: mongoose.Schema.Types.ObjectId,
            ref: 'Video'
        }
    ]
});

tutorialSchema.pre('findOne', function (next) {
    this.populate('videos');  // now can be accessed using this.videos
    next();
});

tutorialSchema.virtual('totalTime').get(function () {
    let times = [];
    times = this.videos.map((v) => {
        return v.duration;
    });
    if(times.length === 0) return 0;
    let totalTime; // find total time of videos and then return
    return totalTime;
});
</code>```

Body:
Im trying to create a virtual item in one of my schemas, that will need access to data thats referenced by an item thats referenced in this schema (Yes, thats 2 references deep, connecting 3 schemas/models)

I've tried to simulate the code as close as I can here, using Model/Schema A/B/C..

This would be the schema for the ModelA, which contains the virtual item which depends on the references:

// models/modela.js

// SchemaA for ModelA
const SchemaA = new Schema({
    _foo: {
        // References ModelB
        type: Schema.Types.ObjectId,
        ref: 'ModelB'
    }
})

// Virtual `Modela.something`, which needs the data from ModelC.baz
SchemaA.virtual('something').get(function () {
    // How can I access ModelC.baz
    return 'Value from ModelC'
});

Then heres the schema for ModelB:

// models/modelb.js

// SchemaB for ModelB
const SchemaB = new Schema({
    _bar: [{
        // References ModelC.baz
        type: Schema.Types.ObjectId,
        ref: 'ModelC'
    }]
})

And the schema for ModelC:

// models/modelc.js

// SchemaC for ModelC
const SchemaC = new Schema({
    baz: Schema.Types.String
})

As you can see above, what I need to do, is access Modelc.haz from within the virtual something item in ModelA

I thought that if I did both of the populations via the query itself, then maybe this would work, So I tried something like:

this.find()
    .populate( '_foo' )
    .populate( '_foo._bar' )

Which didn't work (which I actually didn't really expect it to, but oh well)

Body:
You can find more information about this at this github issue. You can use query hooks.

I had similar issue, so I used it to populate reference models to use in a virtual function. Here is a sample.

const tutorialSchema = new mongoose.Schema({
    title: {
        type: String,
        required: true
    },
    videos: [
        {
            type: mongoose.Schema.Types.ObjectId,
            ref: 'Video'
        }
    ]
});

tutorialSchema.pre('findOne', function (next) {
    this.populate('videos');  // now can be accessed using this.videos
    next();
});

tutorialSchema.virtual('totalTime').get(function () {
    let times = [];
    times = this.videos.map((v) => {
        return v.duration;
    });
    if(times.length === 0) return 0;
    let totalTime; // find total time of videos and then return
    return totalTime;
});


问:
BeanDeserializer Warnings: How to get rid of them?
I have a Java application which is using the a SOAP API of a software (Polarion) and I get warnings of BeanDeserializer (whatever that is)
which I want to suppress because they flood my logfile but have no known impact.

So I get warnings like

[WARN] BeanDeserializer - Invalid element in
  com.polarion.alm.ws.client.types.tracker.WorkItem -
  linkedOslcResources

but I can't figure out what this means.

Based on the provided info in another thread I concluded that these Warning occur due to an outdated axis library (I currently use axis-1.4.jar). I used an updated version from this source, imported the .jar and removed the former one but the suddenly there errors all over the place so I restored my lib folder to having only the axis-1.4.jar.

The apache page does not provide a download of a .JAR of a newer axis version and the maven repo says 1.4 is the latest one.

And now I am out of ideas.

答: Set the log level for that package/class to OFF to get rid of the messages but I would suggest using ERROR so you can still identify errors if they occur</p>


问:
Categorizing data based on the data's signature
Let us say I have some large collection of rows of data, where each element in the row is a (key, value) pair:

```<code>1)    [(bird, "eagle"), (fish, "cod"),      ... , (soda, "coke")]
2)    [(bird, "lark"),  (fish, "bass"),     ...,  (soda, "pepsi")]
n)    ....
n+1)  [(bird, "robin"), (fish, "flounder"), ...,  (soda, "fanta")]
</code>```

I would like the ability to run some computation that would allow me to determine for a new row, what is the row that is "most similar" to this row?

The most direct way I could think of finding the "most similar" row for any particular row is to directly compare said row against all other rows. This is obviously computationally very expensive.

I am looking for a solution of the following form.

A function that can take a row, and generate some derivative integer for that row. This returned integer would be a sort of "signature" of the row. The important property of this signature is that if two rows are very "similar" they would generate very close integers, if rows are very "different", they would generate distant integers. Obviously, if they are identical rows they would generate the same signature.

I could then takes these generated signatures, with the index of the row they point to, and sort them all by their signatures. This data structure I would keep so that I can do fast lookups. Call it database B.

When I have a new row, I wish to know which existent row in database B is most similar, I would:

Generate a signature for the new row

Binary search through the sorted list of (signature,index) in database B for the closet match

Return the closest matching (could be a perfect match) row in database B.

I know their is a lot of hand waving in this question. My problem is that I do not actually know what the function would be that would generate this signature. I see Levenshtein distances, but those represent the transformation cost, not so much the signature. I see that I could try lossy compressions, two things might be "bucketable" as they compress to the same thing. I am looking for other ideas on how to do this.

Thank you.

答:
EDIT: This is my original answer, which we will call Case 1, where there is no precedence to the keys

You cannot do it as a sorted integer because that is one dimensional and your data is multi-dimensional.  So "nearness" in that sense cannot be established on a line.

Your example shows bird, fish and soda for all 3 lines.  Are the keys fixed and known?  If they are not, then your first step is to hash the keys of a row to establish rows that have the same keys.

For the values, consider this as a poor man's Saturday Night similarity trick.  Hash the values, any two rows that match on that hash are an exact match and represent the same "spot", zero distance.

If N is the number of key/value pairs:

The closest non-exact "nearness" would mean matching N-1 out of N values.  So you generate N more hashes, each one dropping out one of the values.  Any two rows that match on those hashes have N-1 out of N values in common.

The next closest non-exact "nearness" would mean matching N-2 out of N values.  So you generate more than N more hashes (I can't figure the binary this late), this time each hash leaves out a combination of two values.  Any two rows that match on those hashes have N-2 out of N values in common.

So you can see where this is going.  At the logical extreme you end up with 2^N hashes, not very savory, but I'm assuming you would not go that far because you reach a point where too few matching values would be considered to "far" to be worth considering.

EDIT: To see how we cannot escape dimensionality, consider just two keys, with values 1-9.  Plot all possible values on a graph.  We see see that {1,1} is close to {2,2}, but also that {5,6} is close to {6,7}.  So we get a brainstorm, we say, Aha! I'll calculate each point's distance from the origin using Pythagorean theorem!  This will make both {1,1} and {2,2} easy to detect.  But then the two points {1,10} and {10,1} will get the same number, even though they are as far apart as they can be on the graph.  So we say, ok, I need to add the angle for each.  Two points at the same distance are distinguished by their angle, two points at the same angle are distinguished by their distance.  But of course now we've plotted them on two dimensions.

EDIT:  Case 2 would be when there is precedence to the keys, when key 1 is more significant than key 2, which is more significant than key 3, etc.  In this case, if the allowed values were A-Z, you would string the values together as if they were digits to get a sortable value.  ABC  is very close to ABD, but very far from BBD.

ContentLicense: CC BY-SA 2.5

Body:
Let us say I have some large collection of rows of data, where each element in the row is a (key, value) pair:

1)    [(bird, "eagle"), (fish, "cod"),      ... , (soda, "coke")]
2)    [(bird, "lark"),  (fish, "bass"),     ...,  (soda, "pepsi")]
n)    ....
n+1)  [(bird, "robin"), (fish, "flounder"), ...,  (soda, "fanta")]

I would like the ability to run some computation that would allow me to determine for a new row, what is the row that is "most similar" to this row?

The most direct way I could think of finding the "most similar" row for any particular row is to directly compare said row against all other rows. This is obviously computationally very expensive.

I am looking for a solution of the following form.

A function that can take a row, and generate some derivative integer for that row. This returned integer would be a sort of "signature" of the row. The important property of this signature is that if two rows are very "similar" they would generate very close integers, if rows are very "different", they would generate distant integers. Obviously, if they are identical rows they would generate the same signature.

I could then takes these generated signatures, with the index of the row they point to, and sort them all by their signatures. This data structure I would keep so that I can do fast lookups. Call it database B.

When I have a new row, I wish to know which existent row in database B is most similar, I would:

Generate a signature for the new row

Binary search through the sorted list of (signature,index) in database B for the closet match

Return the closest matching (could be a perfect match) row in database B.

I know their is a lot of hand waving in this question. My problem is that I do not actually know what the function would be that would generate this signature. I see Levenshtein distances, but those represent the transformation cost, not so much the signature. I see that I could try lossy compressions, two things might be "bucketable" as they compress to the same thing. I am looking for other ideas on how to do this.

Thank you.


答: data is undefined because the function getData doesn't return anything. You should have a look at promises.</p>

Title: Javascript - why is this undefined?


问:
Finding Highest, Middle and lowest value in a MySql using IF ELSE & Loop
I want to create php code that identifies and labels it if the result is top1, top2 or top3 using PHP Codes (If else and Loop). The scenario is I gathered data from the user. I allowed them to rate these three nominees ( clang, bes, tin, mark and yong);. But at the end of the calculation out of 5 nominees only 3 nominees will be collected and

here's my sql statement:

```<code>$res=mysqli_query($link,"select * from Award_Final_Calculation WHERE award_description = 'Sunshine Award' ORDER BY score DESC limit 3");`
</code>```

here's my php code:

```<code>while ($row = mysqli_fetch_array($res)) {
    echo $row['name']." "."got"." "$row['score']." "."Score";
}
</code>```

I want to label them if top1 top2 or top 3

This is my current output:

clang got 5 Score

mark got 2 Score

tin got 1 Score

答:
You can do this by using SQL and the GROUP BY clause.

```<code>$res=mysqli_query($link,"select name, COUNT(*) AS score from Award_Final_Calculation WHERE award_description = 'Sunshine Award' GROUP BY name ORDER BY score DESC limit 3");`
</code>```

The results from this query should work with the while loop you've got in your PHP.

Body:
I want to create php code that identifies and labels it if the result is top1, top2 or top3 using PHP Codes (If else and Loop). The scenario is I gathered data from the user. I allowed them to rate these three nominees ( clang, bes, tin, mark and yong);. But at the end of the calculation out of 5 nominees only 3 nominees will be collected and

here's my sql statement:

$res=mysqli_query($link,"select * from Award_Final_Calculation WHERE award_description = 'Sunshine Award' ORDER BY score DESC limit 3");`

here's my php code:

while ($row = mysqli_fetch_array($res)) {
    echo $row['name']." "."got"." "$row['score']." "."Score";
}

I want to label them if top1 top2 or top 3

This is my current output:

clang got 5 Score

mark got 2 Score

tin got 1 Score

Body:
You can do this by using SQL and the GROUP BY clause.

$res=mysqli_query($link,"select name, COUNT(*) AS score from Award_Final_Calculation WHERE award_description = 'Sunshine Award' GROUP BY name ORDER BY score DESC limit 3");`

The results from this query should work with the while loop you've got in your PHP.


问:
Scala fold on Option return type
I am very new to Scala and i would like to return a Some[String] or a None after doing some loging but it seems the types returned are not consistent for the fold to work.

```<code>(Option[String]).fold{
            logger.info("Message append failed")
            None
          }{stuff=>
            logger.info("Message appended")
            Some(stuff)
          }
</code>```

The returned compiler error is the following Expression of type Some[String] does not conform to expected type None.type

答:
I think, you use the wrong type signature. You have to call the fold method on some Option instance. For example:</p>

```<code>scala> val opt = Option("test")
scala> opt.fold[Option[String]] {
     | println("Message append failed.")
     | None
     | } { stuff =>
     | println("Message appended!")
     | Some(stuff)
     | }
Message appended!
res3: Option[String] = Some(test)
</code>```

Title: Scala fold on Option return type

Body:
I am very new to Scala and i would like to return a Some[String] or a None after doing some loging but it seems the types returned are not consistent for the fold to work.

(Option[String]).fold{
            logger.info("Message append failed")
            None
          }{stuff=>
            logger.info("Message appended")
            Some(stuff)
          }

The returned compiler error is the following Expression of type Some[String] does not conform to expected type None.type

Body:
I think, you use the wrong type signature. You have to call the fold method on some Option instance. For example:

scala> val opt = Option("test")
scala> opt.fold[Option[String]] {
     | println("Message append failed.")
     | None
     | } { stuff =>
     | println("Message appended!")
     | Some(stuff)
     | }
Message appended!
res3: Option[String] = Some(test)


问:
How to use lxml to find element text in XHTML document
I've been bashing my head at this for ages, I must be doing something stupid.

I am trying to retrieve all of the possible Wikipedia supported languages and output them to a text file by traversing the tables on List_of_Wikipedias.

Here is my python code so far, which is simply trying to retrieve one of the tables:

```<code>import httplib
from lxml import etree

def main():
    conn = httplib.HTTPConnection("meta.wikimedia.org")
    conn.request("GET","/wiki/List_of_Wikipedias")
    res = conn.getresponse()
    root = etree.fromstring(res.read())
    table = root.xpath('//table')
    print table

main()
</code>```

On my machine this only prints an empty list.  To increase speed I cached the page locally and used:

```<code>wikipage = open("wikipage.html")
root = lxml.parse(wikipage)
</code>```

but this makes no impact whatsoever (other than the obvious speedup).  I have also tried

```<code>lxml.find('table')
</code>```

and:

```<code>for element in root.iter():
    print("%s - %s" % (element.tag, element.text))
</code>```

which successfully prints out all of the elements, so I know the tree is being created.

What am I doing wrong?

Any help would be appreciated.
Thanks.

答:
```<code>I am trying to retrieve all of the possible Wikipedia supported languages and output them to a text file by traversing the tables on List_of_Wikipedias
</code>```

Your problem is that the element names in the document are in a default namespace. How to write XPath expressions that involve such element names is the most FAQ in XPath and has numerous good answer in the SO xpath tag. Just search for them.

Here is a complete solution:

Use:

```<code>(//x:table)[1]/x:tr[not(x:th)]/x:td[2]//text()
</code>```

where you have registered the XHTML namespace ("http://www.w3.org/1999/xhtml") bound to the prefix "x".

When I evaluated this XPath expression against the document obtained from: http://s23.org/wikistats/wikipedias_html

I needed to add the following at the start of the document, because I was working locally and didn't have the DTD for XHTML -- maybe you will not need these:

```<code><!DOCTYPE html [
<!ENTITY uarr "↑">
<!ENTITY darr "↓">
<!ENTITY ccedil "Ç">
<!ENTITY oslash "Ø">
<!ENTITY aacute "á">
<!ENTITY aring "å">
<!ENTITY agrave "À">
<!ENTITY egrave "è">
<!ENTITY ograve "Ò">
<!ENTITY ocirc "ô">
]>
</code>```

The result of applying the above XPath expression to this document is:

```<code>                    English

                    German

                    French

                    Polish

                    Italian

                    Japanese

                    Spanish

                    Portuguese

                    Dutch

                    Russian

                    Swedish

                    Chinese

                    Catalan

                    Norwegian (Bokmål)

                    Finnish

                    Ukrainian

                    Czech

                    Hungarian

                    Romanian

                    Korean

                    Turkish

                    Vietnamese

                    Indonesian

                    Danish

                    Arabic

                    Esperanto

                    Serbian

                    Lithuanian

                    Slovak

                    Volapük

                    Persian

                    Hebrew

                    Bulgarian

                    Slovenian

                    Malay

                    Waray-Waray

                    Croatian

                    Estonian

                    Newar / Nepal Bhasa

                    Simple English

                    Hindi

                    Galician

                    Thai

                    Basque

                    Norwegian (Nynorsk)

                    Aromanian

                    Greek

                    Haitian

                    Azerbaijani

                    Tagalog

                    Latin

                    Telugu

                    Georgian

                    Macedonian

                    Cebuano

                    Serbo-Croatian

                    Breton

                    Piedmontese

                    Marathi

                    Latvian

                    Luxembourgish

                    Javanese

                    Belarusian (Taraškievica)

                    Welsh

                    Icelandic

                    Bosnian

                    Albanian

                    Tamil

                    Belarusian

                    Bishnupriya Manipuri

                    Aragonese

                    Occitan

                    Bengali

                    Swahili

                    Ido

                    Lombard

                    West Frisian

                    Gujarati

                    Afrikaans

                    Low Saxon

                    Malayalam

                    Quechua

                    Sicilian

                    Urdu

                    Kurdish

                    Cantonese

                    Sundanese

                    Asturian

                    Neapolitan

                    Samogitian

                    Armenian

                    Yoruba

                    Irish

                    Chuvash

                    Walloon

                    Nepali

                    Ripuarian

                    Western Panjabi

                    Kannada

                    Tajik

                    Tarantino

                    Venetian

                    Yiddish

                    Scottish Gaelic

                    Tatar

                    Min Nan

                    Ossetian

                    Uzbek

                    Alemannic

                    Kapampangan

                    Sakha

                    Egyptian Arabic

                    Kazakh

                    Maori

                    Limburgian

                    Amharic

                    Nahuatl

                    Upper Sorbian

                    Gilaki

                    Corsican

                    Gan

                    Mongolian

                    Scots

                    Interlingua

                    Central_Bicolano

                    Burmese

                    Faroese

                    Võro

                    Dutch Low Saxon

                    Sinhalese

                    Turkmen

                    West Flemish

                    Sanskrit

                    Bavarian

                    Malagasy

                    Manx

                    Ilokano

                    Divehi

                    Norman

                    Pangasinan

                    Banyumasan

                    Sorani

                    Romansh

                    Northern Sami

                    Zazaki

                    Mazandarani

                    Wu

                    Friulian

                    Uyghur

                    Ligurian

                    Maltese

                    Bihari

                    Novial

                    Tibetan

                    Anglo-Saxon

                    Kashubian

                    Sardinian

                    Classical Chinese

                    Fiji Hindi

                    Khmer

                    Ladino

                    Zamboanga Chavacano

                    Pali

                    Franco-Provençal/Arpitan

                    Pashto

                    Hakka

                    Cornish

                    Punjabi

                    Navajo

                    Silesian

                    Kalmyk

                    Pennsylvania German

                    Hawaiian

                    Saterland Frisian

                    Interlingue

                    Somali

                    Komi

                    Karachay-Balkar

                    Crimean Tatar

                    Tongan

                    Acehnese

                    Meadow Mari

                    Picard

                    Erzya

                    Lingala

                    Kinyarwanda

                    Extremaduran

                    Guarani

                    Kirghiz

                    Emilian-Romagnol

                    Assyrian Neo-Aramaic

                    Papiamentu

                    Aymara

                    Chechen

                    Lojban

                    Wolof

                    Banjar

                    Bashkir

                    North Frisian

                    Greenlandic

                    Tok Pisin

                    Udmurt

                    Kabyle

                    Tahitian

                    Sranan

                    Zealandic

                    Hill Mari

                    Komi-Permyak

                    Lower Sorbian

                    Abkhazian

                    Gagauz

                    Igbo

                    Oriya

                    Lao

                    Kongo

                    Avar

                    Moksha

                    Mirandese

                    Romani

                    Old Church Slavonic

                    Karakalpak

                    Samoan

                    Moldovan

                    Tetum

                    Gothic

                    Kashmiri

                    Bambara

                    Inupiak

                    Sindhi

                    Bislama

                    Lak

                    Nauruan

                    Norfolk

                    Inuktitut

                    Pontic

                    Assamese

                    Cherokee

                    Min Dong

                    Swati

                    Palatinate German

                    Hausa

                    Ewe

                    Tigrinya

                    Oromo

                    Zulu

                    Zhuang

                    Venda

                    Tsonga

                    Kirundi

                    Dzongkha

                    Sango

                    Cree

                    Chamorro

                    Luganda

                    Buginese

                    Buryat (Russia)

                    Fijian

                    Chichewa

                    Akan

                    Sesotho

                    Xhosa

                    Fula

                    Tswana

                    Kikuyu

                    Tumbuka

                    Shona

                    Twi

                    Cheyenne

                    Ndonga

                    Sichuan Yi

                    Choctaw

                    Marshallese

                    Afar

                    Kuanyama

                    Hiri Motu

                    Muscogee

                    Kanuri

                    Herero
</code>```

Do note: Every second selected node is a white-space-only text node. If you don't want these selected, use:

```<code>(//x:table)[1]/x:tr[not(x:th)]/x:td[2]//text()[normalize-space()]
</code>```

Body:
I've been bashing my head at this for ages, I must be doing something stupid.

I am trying to retrieve all of the possible Wikipedia supported languages and output them to a text file by traversing the tables on List_of_Wikipedias.

Here is my python code so far, which is simply trying to retrieve one of the tables:

import httplib
from lxml import etree

def main():
    conn = httplib.HTTPConnection("meta.wikimedia.org")
    conn.request("GET","/wiki/List_of_Wikipedias")
    res = conn.getresponse()
    root = etree.fromstring(res.read())
    table = root.xpath('//table')
    print table

main()

On my machine this only prints an empty list.  To increase speed I cached the page locally and used:

wikipage = open("wikipage.html")
root = lxml.parse(wikipage)

but this makes no impact whatsoever (other than the obvious speedup).  I have also tried

lxml.find('table')

and:

for element in root.iter():
    print("%s - %s" % (element.tag, element.text))

which successfully prints out all of the elements, so I know the tree is being created.

What am I doing wrong?

Any help would be appreciated.
Thanks.

Body:
I am trying to retrieve all of the possible Wikipedia supported languages and output them to a text file by traversing the tables on List_of_Wikipedias

Your problem is that the element names in the document are in a default namespace. How to write XPath expressions that involve such element names is the most FAQ in XPath and has numerous good answer in the SO xpath tag. Just search for them.

Here is a complete solution:

Use:

(//x:table)[1]/x:tr[not(x:th)]/x:td[2]//text()

where you have registered the XHTML namespace ("http://www.w3.org/1999/xhtml") bound to the prefix "x".

When I evaluated this XPath expression against the document obtained from: http://s23.org/wikistats/wikipedias_html

I needed to add the following at the start of the document, because I was working locally and didn't have the DTD for XHTML -- maybe you will not need these:

<!DOCTYPE html [
<!ENTITY uarr "&#8593;">
<!ENTITY darr "&#8595;">
<!ENTITY ccedil "&#199;">
<!ENTITY oslash "&#216;">
<!ENTITY aacute "&#225;">
<!ENTITY aring "&#229;">
<!ENTITY agrave "&#192;">
<!ENTITY egrave "&#232;">
<!ENTITY ograve "&#210;">
<!ENTITY ocirc "&#244;">
]>

The result of applying the above XPath expression to this document is:

                    English

                    German

                    French

                    Polish

                    Italian

                    Japanese

                    Spanish

                    Portuguese

                    Dutch

                    Russian

                    Swedish

                    Chinese

                    Catalan

                    Norwegian (Bokmål)

                    Finnish

                    Ukrainian

                    Czech

                    Hungarian

                    Romanian

                    Korean

                    Turkish

                    Vietnamese

                    Indonesian

                    Danish

                    Arabic

                    Esperanto

                    Serbian

                    Lithuanian

                    Slovak

                    Volapük

                    Persian

                    Hebrew

                    Bulgarian

                    Slovenian

                    Malay

                    Waray-Waray

                    Croatian

                    Estonian

                    Newar / Nepal Bhasa

                    Simple English

                    Hindi

                    Galician

                    Thai

                    Basque

                    Norwegian (Nynorsk)

                    Aromanian

                    Greek

                    Haitian

                    Azerbaijani

                    Tagalog

                    Latin

                    Telugu

                    Georgian

                    Macedonian

                    Cebuano

                    Serbo-Croatian

                    Breton

                    Piedmontese

                    Marathi

                    Latvian

                    Luxembourgish

                    Javanese

                    Belarusian (Taraškievica)

                    Welsh

                    Icelandic

                    Bosnian

                    Albanian

                    Tamil

                    Belarusian

                    Bishnupriya Manipuri

                    Aragonese

                    Occitan

                    Bengali

                    Swahili

                    Ido

                    Lombard

                    West Frisian

                    Gujarati

                    Afrikaans

                    Low Saxon

                    Malayalam

                    Quechua

                    Sicilian

                    Urdu

                    Kurdish

                    Cantonese

                    Sundanese

                    Asturian

                    Neapolitan

                    Samogitian

                    Armenian

                    Yoruba

                    Irish

                    Chuvash

                    Walloon

                    Nepali

                    Ripuarian

                    Western Panjabi

                    Kannada

                    Tajik

                    Tarantino

                    Venetian

                    Yiddish

                    Scottish Gaelic

                    Tatar

                    Min Nan

                    Ossetian

                    Uzbek

                    Alemannic

                    Kapampangan

                    Sakha

                    Egyptian Arabic

                    Kazakh

                    Maori

                    Limburgian

                    Amharic

                    Nahuatl

                    Upper Sorbian

                    Gilaki

                    Corsican

                    Gan

                    Mongolian

                    Scots

                    Interlingua

                    Central_Bicolano

                    Burmese

                    Faroese

                    Võro

                    Dutch Low Saxon

                    Sinhalese

                    Turkmen

                    West Flemish

                    Sanskrit

                    Bavarian

                    Malagasy

                    Manx

                    Ilokano

                    Divehi

                    Norman

                    Pangasinan

                    Banyumasan

                    Sorani

                    Romansh

                    Northern Sami

                    Zazaki

                    Mazandarani

                    Wu

                    Friulian

                    Uyghur

                    Ligurian

                    Maltese

                    Bihari

                    Novial

                    Tibetan

                    Anglo-Saxon

                    Kashubian

                    Sardinian

                    Classical Chinese

                    Fiji Hindi

                    Khmer

                    Ladino

                    Zamboanga Chavacano

                    Pali

                    Franco-Provençal/Arpitan

                    Pashto

                    Hakka

                    Cornish

                    Punjabi

                    Navajo

                    Silesian

                    Kalmyk

                    Pennsylvania German

                    Hawaiian

                    Saterland Frisian

                    Interlingue

                    Somali

                    Komi

                    Karachay-Balkar

                    Crimean Tatar

                    Tongan

                    Acehnese

                    Meadow Mari

                    Picard

                    Erzya

                    Lingala

                    Kinyarwanda

                    Extremaduran

                    Guarani

                    Kirghiz

                    Emilian-Romagnol

                    Assyrian Neo-Aramaic

                    Papiamentu

                    Aymara

                    Chechen

                    Lojban

                    Wolof

                    Banjar

                    Bashkir

                    North Frisian

                    Greenlandic

                    Tok Pisin

                    Udmurt

                    Kabyle

                    Tahitian

                    Sranan

                    Zealandic

                    Hill Mari

                    Komi-Permyak

                    Lower Sorbian

                    Abkhazian

                    Gagauz

                    Igbo

                    Oriya

                    Lao

                    Kongo

                    Avar

                    Moksha

                    Mirandese

                    Romani

                    Old Church Slavonic

                    Karakalpak

                    Samoan

                    Moldovan

                    Tetum

                    Gothic

                    Kashmiri

                    Bambara

                    Inupiak

                    Sindhi

                    Bislama

                    Lak

                    Nauruan

                    Norfolk

                    Inuktitut

                    Pontic

                    Assamese

                    Cherokee

                    Min Dong

                    Swati

                    Palatinate German

                    Hausa

                    Ewe

                    Tigrinya

                    Oromo

                    Zulu

                    Zhuang

                    Venda

                    Tsonga

                    Kirundi

                    Dzongkha

                    Sango

                    Cree

                    Chamorro

                    Luganda

                    Buginese

                    Buryat (Russia)

                    Fijian

                    Chichewa

                    Akan

                    Sesotho

                    Xhosa

                    Fula

                    Tswana

                    Kikuyu

                    Tumbuka

                    Shona

                    Twi

                    Cheyenne

                    Ndonga

                    Sichuan Yi

                    Choctaw

                    Marshallese

                    Afar

                    Kuanyama

                    Hiri Motu

                    Muscogee

                    Kanuri

                    Herero

Do note: Every second selected node is a white-space-only text node. If you don't want these selected, use:

(//x:table)[1]/x:tr[not(x:th)]/x:td[2]//text()[normalize-space()]


问:
iPad Bluetooth keyboard returns keycode of 0 for any key with onKeyUp
Some clients have been reporting issues when using their iPad Bluetooth keyboards for entering text into one of our internal sites. Mainly pressing enter on a certain input would work fine when using desktop or the iPad on screen keyboard, but not when using a Bluetooth keyboard connected to the iPad.

Upon investigation it appears that any input to an onKeyUp returns 0 as the keycode when connected to a Bluetooth keyboard on the iPad. The demo works fine, however when using the onscreen keyboard it doesn't work because of the keycode returning 0. I created this jsFiddle to demonstrate. It was tested on both Chrome and Safari for iPad with the same results of working fine with onKeyPress but returning only 0 with onKeyUp.

$('#inputKeyUp').keyup(function (event){
 $("#outputKeyUp").text("Key Up Key: " + event.which);
});

$('#inputKeyPress').keypress(function (event){
 $("#outputKeyPress").text("Key Press Key: " + event.which);
});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<textarea id="inputKeyUp">keyup</textarea>
<div id="outputKeyUp">Key Up Key:</div>
<b/>
<textarea id="inputKeyPress">keypress</textarea>
<div id="outputKeyPress">Key Press Key:</div></code>```

EDIT: just reported the bug to Apple. We will see if anything comes of it.

答:
Testing study

I did some testing on this just now and discovered that on the keyUp event when using a Bluetooth keyboard on iOS Safari, the only keys that give any sort of proper feedback in terms of the properties e.key, e.charCode, e.keyCode and e.which are the following keys:

Escape

Up arrow

Left arrow

Right arrow

Down arrow

All other keys return the following:

```<code>{
    key: "Dead",
    charCode: 0,
    keyCode: 0,
    which: 0
}
</code>```

These special keys (escape and arrow keys) only return a different value on the e.key property according to the syntax UIKeyInput{PascalCasedKeyName}:

UIKeyInputEscape

UIKeyInputUpArrow

UIKeyInputLeftArrow

UIKeyInputRightArrow

UIKeyInputDownArrow

Summary

On iOS, the only keys you can identify on the keyUp event, based on my quick study, are Escape and the four Arrow keys, by matching their name on the e.key property. These values also appear on the keyDown event.

If you still need to wait until the keyUp event fires for your applications, and you need to match keys other than these special ones, the only solution I can come up with is to use a keyDown event for capturing the key, but then listen for the keyUp event inside that keyDown event like so:

```<code>el.addEventListener("keydown", e => {
    if (e.which === 13) // Enter key, or which ever key code you'd like
        el.addEventListener("keyup", function keyUp(e) {
            el.removeEventListener("keyup", keyUp, false) // Memory clean-up

            // Your code here
        }, false)
}, false)
</code>```

Furthermore

After a quick search for "UIKeyInput" I discovered that UIKeyInput is "a set of methods a subclass of UIResponder uses to implement simple text entry". (Apple's Developer Documentation) This would explain the special syntax of these key names.

Body:
Some clients have been reporting issues when using their iPad Bluetooth keyboards for entering text into one of our internal sites. Mainly pressing enter on a certain input would work fine when using desktop or the iPad on screen keyboard, but not when using a Bluetooth keyboard connected to the iPad.

Upon investigation it appears that any input to an onKeyUp returns 0 as the keycode when connected to a Bluetooth keyboard on the iPad. The demo works fine, however when using the onscreen keyboard it doesn't work because of the keycode returning 0. I created this jsFiddle to demonstrate. It was tested on both Chrome and Safari for iPad with the same results of working fine with onKeyPress but returning only 0 with onKeyUp.

$('#inputKeyUp').keyup(function (event){
 $("#outputKeyUp").text("Key Up Key: " + event.which);
});

$('#inputKeyPress').keypress(function (event){
 $("#outputKeyPress").text("Key Press Key: " + event.which);
});

<textarea id="inputKeyUp">keyup</textarea>

Key Up Key:

<textarea id="inputKeyPress">keypress</textarea>

Key Press Key:

EDIT: just reported the bug to Apple. We will see if anything comes of it.

Body:
Testing study

I did some testing on this just now and discovered that on the keyUp event when using a Bluetooth keyboard on iOS Safari, the only keys that give any sort of proper feedback in terms of the properties e.key, e.charCode, e.keyCode and e.which are the following keys:

Escape

Up arrow

Left arrow

Right arrow

Down arrow

All other keys return the following:

{
    key: "Dead",
    charCode: 0,
    keyCode: 0,
    which: 0
}

These special keys (escape and arrow keys) only return a different value on the e.key property according to the syntax UIKeyInput{PascalCasedKeyName}:

UIKeyInputEscape

UIKeyInputUpArrow

UIKeyInputLeftArrow

UIKeyInputRightArrow

UIKeyInputDownArrow

Summary

On iOS, the only keys you can identify on the keyUp event, based on my quick study, are Escape and the four Arrow keys, by matching their name on the e.key property. These values also appear on the keyDown event.

If you still need to wait until the keyUp event fires for your applications, and you need to match keys other than these special ones, the only solution I can come up with is to use a keyDown event for capturing the key, but then listen for the keyUp event inside that keyDown event like so:

el.addEventListener("keydown", e => {
    if (e.which === 13) // Enter key, or which ever key code you'd like
        el.addEventListener("keyup", function keyUp(e) {
            el.removeEventListener("keyup", keyUp, false) // Memory clean-up

            // Your code here
        }, false)
}, false)

Furthermore

After a quick search for "UIKeyInput" I discovered that UIKeyInput is "a set of methods a subclass of UIResponder uses to implement simple text entry". (Apple's Developer Documentation) This would explain the special syntax of these key names.


问:
Get data from selected checkboxes in yii2
I have a form rawmaterial and in that I've a Gridview with checkboxcolumn and some form fields. I want to get all the fields of the selected rows as array.
I've tried to solve as mentioned here - http://www.yiiframework.com/forum/index.php/topic/53777-gridview-get-selected-colum/. But getting Not Found error.
Code of index.php

```<code><?php

use yii\helpers\Html;
use kartik\grid\GridView;
use kartik\select2\Select2;
use yii\helpers\ArrayHelper;
use frontend\models\Rmtemplate;
use kartik\form\ActiveForm;

/* @var $this yii\web\View */
/* @var $searchModel frontend\modules\rmprod\models\RmtemplateSearch */
/* @var $dataProvider yii\data\ActiveDataProvider */

$this->title = 'Templates';
$this->params['breadcrumbs'][] = $this->title;
?>
<div class="rmtemplate-index">
    <?php $form = ActiveForm::begin([
        'id' => 'rmtemplate-index',
        'action' => ['/rmprod/Rmtemplate/processSelected',],
        'method' => 'get',
        'enableClientScript' => false,

    ]); ?>

    <h1><?= Html::encode($this->title) ?></h1>
    <?php // echo $this->render('_search', ['model' => $searchModel]); ?>

    <?= GridView::widget([
        'dataProvider' => $dataProvider,
        'filterModel' => $searchModel,
        'id'=>'mytable',
        'columns' => [
            ['class' => 'kartik\grid\CheckboxColumn'],

            //'id',
            //'productname',
            [
                'attribute'=>'productname',
                'filterType'=>GridView::FILTER_SELECT2,
                'filter'=>ArrayHelper::map(Rmtemplate::find()->orderBy(['productname' => SORT_ASC])->asArray()->all(), 'productname', 'productname'),
                'filterWidgetOptions'=>[
                'pluginOptions'=>['allowClear'=>true],
                                    ],
                'filterInputOptions'=>['placeholder'=>'Charge Name'],
            ],
            'rmname',
            'qty',
            // [
            //  'attribute' => 'unitcost',
            //  'value' => 'unitcost.unitcost',
            // ],
            'cost',

            //['class' => 'kartik\grid\ActionColumn'],
        ],
    ]); ?>
    <div class="form-group pull-right">
        <?= Html::submitButton('Next', ['class' => 'btn btn-primary search','id'=>'tabbutton',]) ?>
    </div>
</div>
<?php ActiveForm::end(); ?>

<?php
/* start getting the data */
$script = <<<EOD
$('tabbutton').one('click',function() {
    var keys = $('#w0').yiiGridView('getSelectedRows'); // returns an array of pkeys, and #grid is your grid element id
    $.post({
       url: '/rmtemplate/processSelected', // your controller action
       dataType: 'json',
       data: {keylist: keys},
       success: function(data) {
          if (data.status === 'success') {
              alert('I did it! Processed checked rows.');
          }
       },
    });
});
EOD;
$this->registerJs($script);
/*end getting the data */
?>
</code>```

Controller Action

```<code>public function actionProcessSelected() {
    if (isset($_POST['keylist'])) {
        $keys = \yii\helpers\Json::decode($_POST['keylist']);
        // you will have the array of pk ids to process in $keys
        // perform batch action on these keys and return status
        // back to ajax call above
        }
    }
</code>```

Console

Output

答:
There are two possible(Temporary) soutions you can try:
        Solution 1::

```<code>In Index.php=>
    //define action  ::
    $productupdate = '/rmprod/Rmtemplate/processSelected';
    In column add this........
    [
     'class' => 'kartik\grid\CheckboxColumn'
     'checkboxOptions' => function ($data) {
               return ['value' =>  $data['product_primary_key'], 'class' => 'class_checkbox'];  //primary_key=>product_primary_key
                        },
    ],
    Add Jquery code(To post data) ::::
        $('.class_checkbox').change(function()
        {
            var action_url = '<?= $productupdate; ?>';
            if (this.checked) {
                var product_data = $(this).attr('value'); //get product_primary_key
                $.ajax({
                    method: "post",
                    url: action_url,
                    data: {product_data:product_data,_csrf: csrfToken}
                }).done(function(data)
                {
                    $('#LoadingMSG').hide();
                    console.log(data);
                });
            }
            else
            {
                //you can apply another ajax to post data when checkbox unselect
            }
        });
    In Controller=>
    public function processSelected()
    {
    $getdata = Yii::$app->request->post(); //get posted data
    //apply query to play with database by $getdata (primary_key)
    }
</code>```

Solution 2

```<code>In Index.php.............
    [
     'class' => 'kartik\grid\CheckboxColumn'
     'checkboxOptions' => function ($data) {
               return ['value' =>  $value1.'+'.$value2.'+'.$value3.'+'.$value4, 'class' => 'class_checkbox'];
                        },
    ],
    Add Jquery code(To post data) ::::
        $('.class_checkbox').change(function()
        {
            var action_url = '<?= $productupdate; ?>';
            if (this.checked) {
                var all_flds_data = $(this).attr('value');
                $.ajax({
                    method: "post",
                    url: action_url,
                    data: {all_flds_data:all_flds_data,_csrf: csrfToken}
                }).done(function(data)
                {
                    $('#LoadingMSG').hide();
                    console.log(data);
                });
            }
            else
            {
                //you can apply another ajax to post data when checkbox unselect
            }
        });
In Controller=>
    public function processSelected()
    {
    $getdata = Yii::$app->request->post(); //get posted data
    //after json_deocode you will get all posted data from ajax
    }
</code>```

Body:
I have a form rawmaterial and in that I've a Gridview with checkboxcolumn and some form fields. I want to get all the fields of the selected rows as array.
I've tried to solve as mentioned here - http://www.yiiframework.com/forum/index.php/topic/53777-gridview-get-selected-colum/. But getting Not Found error.
Code of index.php

<?php

use yii\helpers\Html;
use kartik\grid\GridView;
use kartik\select2\Select2;
use yii\helpers\ArrayHelper;
use frontend\models\Rmtemplate;
use kartik\form\ActiveForm;

/* @var $this yii\web\View */
/* @var $searchModel frontend\modules\rmprod\models\RmtemplateSearch */
/* @var $dataProvider yii\data\ActiveDataProvider */

$this->title = 'Templates';
$this->params['breadcrumbs'][] = $this->title;
?>

    <?php $form = ActiveForm::begin([
        'id' => 'rmtemplate-index',
        'action' => ['/rmprod/Rmtemplate/processSelected',],
        'method' => 'get',
        'enableClientScript' => false,

    ]); ?>

<?= Html::encode($this->title) ?>

    <?php // echo $this->render('_search', ['model' => $searchModel]); ?>

    <?= GridView::widget([
        'dataProvider' => $dataProvider,
        'filterModel' => $searchModel,
        'id'=>'mytable',
        'columns' => [
            ['class' => 'kartik\grid\CheckboxColumn'],

            //'id',
            //'productname',
            [
                'attribute'=>'productname',
                'filterType'=>GridView::FILTER_SELECT2,
                'filter'=>ArrayHelper::map(Rmtemplate::find()->orderBy(['productname' => SORT_ASC])->asArray()->all(), 'productname', 'productname'),
                'filterWidgetOptions'=>[
                'pluginOptions'=>['allowClear'=>true],
                                    ],
                'filterInputOptions'=>['placeholder'=>'Charge Name'],
            ],
            'rmname',
            'qty',
            // [
            //  'attribute' => 'unitcost',
            //  'value' => 'unitcost.unitcost',
            // ],
            'cost',

            //['class' => 'kartik\grid\ActionColumn'],
        ],
    ]); ?>

        <?= Html::submitButton('Next', ['class' => 'btn btn-primary search','id'=>'tabbutton',]) ?>

<?php ActiveForm::end(); ?>

<?php
/* start getting the data */
$script = <<<EOD
$('tabbutton').one('click',function() {
    var keys = $('#w0').yiiGridView('getSelectedRows'); // returns an array of pkeys, and #grid is your grid element id
    $.post({
       url: '/rmtemplate/processSelected', // your controller action
       dataType: 'json',
       data: {keylist: keys},
       success: function(data) {
          if (data.status === 'success') {
              alert('I did it! Processed checked rows.');
          }
       },
    });
});
EOD;
$this->registerJs($script);
/*end getting the data */
?>

Controller Action

public function actionProcessSelected() {
    if (isset($_POST['keylist'])) {
        $keys = \yii\helpers\Json::decode($_POST['keylist']);
        // you will have the array of pk ids to process in $keys
        // perform batch action on these keys and return status
        // back to ajax call above
        }
    }

Console

Output

Body:
There are two possible(Temporary) soutions you can try:
        Solution 1::

In Index.php=>
    //define action  ::
    $productupdate = '/rmprod/Rmtemplate/processSelected';
    In column add this........
    [
     'class' => 'kartik\grid\CheckboxColumn'
     'checkboxOptions' => function ($data) {
               return ['value' =>  $data['product_primary_key'], 'class' => 'class_checkbox'];  //primary_key=>product_primary_key
                        },
    ],
    Add Jquery code(To post data) ::::
        $('.class_checkbox').change(function()
        {
            var action_url = '<?= $productupdate; ?>';
            if (this.checked) {
                var product_data = $(this).attr('value'); //get product_primary_key
                $.ajax({
                    method: "post",
                    url: action_url,
                    data: {product_data:product_data,_csrf: csrfToken}
                }).done(function(data)
                {
                    $('#LoadingMSG').hide();
                    console.log(data);
                });
            }
            else
            {
                //you can apply another ajax to post data when checkbox unselect
            }
        });
    In Controller=>
    public function processSelected()
    {
    $getdata = Yii::$app->request->post(); //get posted data
    //apply query to play with database by $getdata (primary_key)
    }

Solution 2

In Index.php.............
    [
     'class' => 'kartik\grid\CheckboxColumn'
     'checkboxOptions' => function ($data) {
               return ['value' =>  $value1.'+'.$value2.'+'.$value3.'+'.$value4, 'class' => 'class_checkbox'];
                        },
    ],
    Add Jquery code(To post data) ::::
        $('.class_checkbox').change(function()
        {
            var action_url = '<?= $productupdate; ?>';
            if (this.checked) {
                var all_flds_data = $(this).attr('value');
                $.ajax({
                    method: "post",
                    url: action_url,
                    data: {all_flds_data:all_flds_data,_csrf: csrfToken}
                }).done(function(data)
                {
                    $('#LoadingMSG').hide();
                    console.log(data);
                });
            }
            else
            {
                //you can apply another ajax to post data when checkbox unselect
            }
        });
In Controller=>
    public function processSelected()
    {
    $getdata = Yii::$app->request->post(); //get posted data
    //after json_deocode you will get all posted data from ajax
    }


问:
R loop through association rule mining (arules) with changing supports and item appearances
fairly new to R here. I am looking to mine association rules in R for specific items, but I want to vary the minimum support target for these rules by each item (i.e. 10% of the item's total frequency in the transaction list). Each item has a different amount of transactions so I believe there is value in varying the support.

I've calculated the support targets for each item in a separate spreadsheet using Excel.

I can do this manually writing the arules code and manually inputting support minimum and item appearances, but the process is slow, especially with many different items.

ex.

```<code>arules <- apriori(trans, parameter = list(sup = 0.001, conf = 0.25,target="rules"),
    appearance=list(rhs= c("Apples")))
arules2 <- apriori(trans, parameter = list(sup = 0.002, conf = 0.25,target="rules"),
    appearance=list(rhs= c("Oranges")))
combined <- c(arules,arules2)
</code>```

How can I do this using a for loop in R that will calculate the rules for each specified item at a specific support minimum, and also save those generated rules to a new variable each time the loop runs? I intend to later group these rules depending on their type.

Tried something like this which looped through too many times. I also couldn't figure out a way to save each loop to a new variable (i.e. arules1, arules2, arules3....)

```<code>min_supp <- c(0.001,0.002,0.003)
names <- c("Apples","Oranges","Grape")

for (inames in names) {
    for (supports in min_supp) {
        apriori(trans, parameter = list(sup = supports, conf = 0.25,target="rules"),
        appearance=list(rhs= inames))
        }}
</code>```

Thanks in advance!

答:
Consider Map (the simplified wrapper to mapply) that can iterate elementwise through same length vectors for a multiple apply method. Additionally, Map will output a list of the returned items which can be named with setNames. Lists are always preferred as you avoid separate, similarly structured objects flooding global environment.

```<code>min_supp <- c(0.001,0.002,0.003)
names <- c("Apples","Oranges","Grape")

arules_fun <- function(n, s) apriori(trans, parameter = list(sup = s, conf = 0.25, target="rules"),
                                     appearance=list(rhs= n))

# PROCESS FUNCTION ELEMENTWISE
arules_list <- Map(arules_fun, names, min_supp)
# NAME LIST ITEMS
arules_list <- setNames(arules_list, paste0("arules", 1:length(arules_list)))

arules_list$arules1
arules_list$arules2
arules_list$arules3
...
</code>```

Body:
fairly new to R here. I am looking to mine association rules in R for specific items, but I want to vary the minimum support target for these rules by each item (i.e. 10% of the item's total frequency in the transaction list). Each item has a different amount of transactions so I believe there is value in varying the support.

I've calculated the support targets for each item in a separate spreadsheet using Excel.

I can do this manually writing the arules code and manually inputting support minimum and item appearances, but the process is slow, especially with many different items.

ex.

arules <- apriori(trans, parameter = list(sup = 0.001, conf = 0.25,target="rules"),
    appearance=list(rhs= c("Apples")))
arules2 <- apriori(trans, parameter = list(sup = 0.002, conf = 0.25,target="rules"),
    appearance=list(rhs= c("Oranges")))
combined <- c(arules,arules2)

How can I do this using a for loop in R that will calculate the rules for each specified item at a specific support minimum, and also save those generated rules to a new variable each time the loop runs? I intend to later group these rules depending on their type.

Tried something like this which looped through too many times. I also couldn't figure out a way to save each loop to a new variable (i.e. arules1, arules2, arules3....)

min_supp <- c(0.001,0.002,0.003)
names <- c("Apples","Oranges","Grape")

for (inames in names) {
    for (supports in min_supp) {
        apriori(trans, parameter = list(sup = supports, conf = 0.25,target="rules"),
        appearance=list(rhs= inames))
        }}

Thanks in advance!

Body:
Consider Map (the simplified wrapper to mapply) that can iterate elementwise through same length vectors for a multiple apply method. Additionally, Map will output a list of the returned items which can be named with setNames. Lists are always preferred as you avoid separate, similarly structured objects flooding global environment.

min_supp <- c(0.001,0.002,0.003)
names <- c("Apples","Oranges","Grape")

arules_fun <- function(n, s) apriori(trans, parameter = list(sup = s, conf = 0.25, target="rules"),
                                     appearance=list(rhs= n))

# PROCESS FUNCTION ELEMENTWISE
arules_list <- Map(arules_fun, names, min_supp)
# NAME LIST ITEMS
arules_list <- setNames(arules_list, paste0("arules", 1:length(arules_list)))

arules_list$arules1
arules_list$arules2
arules_list$arules3
...


问:
JavaScript - Adding two numbers (which still strings) in one textbox
I'm currently making a bot for some reason, i wanted to add a command that will do math when some user typed <command> 1 + 2 and bot will answers 3. And when it's <command> 2 * 3, it will reply 6. (Let's just use textbox for this case, if I typed 1 + 2 in textbox, theres an alert that shows "3").

My question is, is it possible, by any chance to make this kind of command?
If so, I'd like to know how. Since I've learned a little about JavaScript RegEx and i think if i use it, it'll work out.

答: You could try to use eval function</p>

ContentLicense: CC BY-SA 4.0

Body: You could try to use eval function


问:
SDK Platform Android 8.1.0 - can't download
Android SDK manager fails with this message:

Downloading SDK Platform Android 8.1.0, API 27, revision 1 Download
  finished with wrong size. Expected 65606517 bytes, got 65738431 bytes.

Is there a workaround?

Edit: Download worked correctly from AndroidStudio.

答:
EDIT (For others):

Using the sdkmanager tool instead of the deprecated android tool prevents the validation error. It looks like someone at Google forgot to update the checksums of SDK Platform 8.1.0 for the android tool.

EDIT (For Travis CI):

Current recommended workaround is to add

```<code>before_install:
  - yes | sdkmanager "platforms;android-27"
</code>```

to your .travis.yml file to use the sdkmanager to download the API 27 platform.

I just encountered the same issue a few hours ago while using Travis CI, so I manually uninstalled and reinstalled my local android-27 package, expecting the reinstallation to fail with the same error. To my surprise though, it succeeded when I ran ./sdkmanager.bat "platforms;android-27" --verbose after uninstalling it.

The only difference I can tell is Travis CI using the deprecated android command instead of the modern sdkmanager command, but the deprecated android command correctly redirects to the sdkmanager command in my local SDK.

My exact error message, which is the same:
Download finished with wrong size. Expected 65606517 bytes, got 65738431 bytes.

There is now an issue on the Travis CI GitHub: https://github.com/travis-ci/travis-ci/issues/8874

Body:
EDIT (For others):

Using the sdkmanager tool instead of the deprecated android tool prevents the validation error. It looks like someone at Google forgot to update the checksums of SDK Platform 8.1.0 for the android tool.

EDIT (For Travis CI):

Current recommended workaround is to add

before_install:
  - yes | sdkmanager "platforms;android-27"

to your .travis.yml file to use the sdkmanager to download the API 27 platform.

I just encountered the same issue a few hours ago while using Travis CI, so I manually uninstalled and reinstalled my local android-27 package, expecting the reinstallation to fail with the same error. To my surprise though, it succeeded when I ran ./sdkmanager.bat "platforms;android-27" --verbose after uninstalling it.

The only difference I can tell is Travis CI using the deprecated android command instead of the modern sdkmanager command, but the deprecated android command correctly redirects to the sdkmanager command in my local SDK.

My exact error message, which is the same:
Download finished with wrong size. Expected 65606517 bytes, got 65738431 bytes.

There is now an issue on the Travis CI GitHub: https://github.com/travis-ci/travis-ci/issues/8874


问:
How do I calculate a running SUM?
How do I get a column that is the sum of the preceding values of another column?</p>

答:
Cross join solutions like Diomidis Spinellis suggested take O(N^2) time. A recursive CTE can work faster, if you can stomach the convoluted code.

This produces the same output as his.

```<code>WITH RECURSIVE running(id, name, gdppc, rt) AS (
    SELECT row1._rowid_, row1.name, row1.gdppc, COALESCE(row1.gdppc,0)
    FROM gdppc AS row1
    WHERE row1._rowid_ = (
        SELECT a._rowid_
        FROM gdppc AS a
        ORDER BY a.gdppc, a.name, a._rowid_
        LIMIT 1)
    UNION ALL
    SELECT row_n._rowid_, row_n.name, row_n.gdppc, COALESCE(row_n.gdppc,0)+running.rt
    FROM gdppc AS row_n INNER JOIN running
    ON row_n._rowid_ = (
        SELECT a._rowid_
        FROM gdppc AS a
        WHERE (a.gdppc, a.name, a._rowid_) > (running.gdppc, running.name, running.id)
        ORDER BY a.gdppc, a.name, a._rowid_
        LIMIT 1))
SELECT running.name, running.gdppc, running.rt
FROM running;
</code>```

Ordering and comparisons take care of duplicates, COALESCE is there to ignore NULLs.

If you have a good index, this should be O(N log N). Since SQLite doesn't support cursors, an O(N) solution probably doesn't exist without relying on an external application.

Title: How do I calculate a running SUM?

Body:
Cross join solutions like Diomidis Spinellis suggested take O(N^2) time. A recursive CTE can work faster, if you can stomach the convoluted code.

This produces the same output as his.

WITH RECURSIVE running(id, name, gdppc, rt) AS (
    SELECT row1._rowid_, row1.name, row1.gdppc, COALESCE(row1.gdppc,0)
    FROM gdppc AS row1
    WHERE row1._rowid_ = (
        SELECT a._rowid_
        FROM gdppc AS a
        ORDER BY a.gdppc, a.name, a._rowid_
        LIMIT 1)
    UNION ALL
    SELECT row_n._rowid_, row_n.name, row_n.gdppc, COALESCE(row_n.gdppc,0)+running.rt
    FROM gdppc AS row_n INNER JOIN running
    ON row_n._rowid_ = (
        SELECT a._rowid_
        FROM gdppc AS a
        WHERE (a.gdppc, a.name, a._rowid_) > (running.gdppc, running.name, running.id)
        ORDER BY a.gdppc, a.name, a._rowid_
        LIMIT 1))
SELECT running.name, running.gdppc, running.rt
FROM running;

Ordering and comparisons take care of duplicates, COALESCE is there to ignore NULLs.

If you have a good index, this should be O(N log N). Since SQLite doesn't support cursors, an O(N) solution probably doesn't exist without relying on an external application.


问:
Linking a ComboBox with an ObservableCollection
I am trying to link a combobox with my ObservableCollection, however this does not seem to work, I have looked around and tried other ways that the internet is saying, but I can't seem to get it to work

```<code>public class UserData
{
    public string Key { get; set; }
    public string UserName { get; set; }
    public string Password { get; set; }
    public string Application
    {
        get
        {
            return Text;
        }
    }
    public string Text { get; set; }
    public override string ToString()
    {
        return Text;
    }
}

private static ObservableCollection<UserData> _userdata = new ObservableCollection<UserData>();
    public static ObservableCollection<UserData> Userdata
    {
        get { return _userdata; }
        set { _userdata = value; }
    }
}
</code>```

XAML

```<code><ComboBox
   HorizontalAlignment="Left"
   Height="24"
   Margin="5,3,0,0"
   VerticalAlignment="Top"
   Width="112"
   x:Name="cbApplications"
   DropDownClosed="cbApplications_DropDownClosed"
   ItemsSource="{Binding Path=Userdata}"/>
</code>```

Would anyone be able to support me in this matter?

答:
You should have a view model class like this:

```<code>public class ViewModel : INotifyPropertyChanged
{
    public event PropertyChangedEventHandler PropertyChanged;

    public ObservableCollection<UserData> UserData { get; }
        = new ObservableCollection<UserData>();

    private UserData selectedUserData;

    public UserData SelectedUserData
    {
        get { return selectedUserData; }
        set
        {
            selectedUserData = value;
            PropertyChanged?.Invoke(this,
                new PropertyChangedEventArgs(nameof(SelectedUserData)));
        }
    }
}
</code>```

and bind to it like this:

```<code><ComboBox ItemsSource="{Binding UserData}"
          SelectedItem="{Binding SelectedUserData}"
          DisplayMemberPath="Text"/>
</code>```

In the constructor of your MainWindow (or some other appropriate place), initialize the view model and assign it to the DataContext property of the Window:

```<code>public MainWindow()
{
    InitializeComponent();

    var vm = new ViewModel();
    vm.UserData.Add(new UserData { Text = "User 1" });
    vm.UserData.Add(new UserData { Text = "User 2" });
    vm.UserData.Add(new UserData { Text = "User 3" });
    vm.SelectedUserData = vm.UserData[1];

    DataContext = vm;
}
</code>```

Note that since you can set the ComboBox's DisplayMemberPath property (or declare an ItemTemplate) it's not necessary to override the ToString method of the UserData class.

Body:
I am trying to link a combobox with my ObservableCollection, however this does not seem to work, I have looked around and tried other ways that the internet is saying, but I can't seem to get it to work

public class UserData
{
    public string Key { get; set; }
    public string UserName { get; set; }
    public string Password { get; set; }
    public string Application
    {
        get
        {
            return Text;
        }
    }
    public string Text { get; set; }
    public override string ToString()
    {
        return Text;
    }
}

private static ObservableCollection<UserData> _userdata = new ObservableCollection<UserData>();
    public static ObservableCollection<UserData> Userdata
    {
        get { return _userdata; }
        set { _userdata = value; }
    }
}

XAML

<ComboBox
   HorizontalAlignment="Left"
   Height="24"
   Margin="5,3,0,0"
   VerticalAlignment="Top"
   Width="112"
   x:Name="cbApplications"
   DropDownClosed="cbApplications_DropDownClosed"
   ItemsSource="{Binding Path=Userdata}"/>

Would anyone be able to support me in this matter?

Body:
You should have a view model class like this:

public class ViewModel : INotifyPropertyChanged
{
    public event PropertyChangedEventHandler PropertyChanged;

    public ObservableCollection<UserData> UserData { get; }
        = new ObservableCollection<UserData>();

    private UserData selectedUserData;

    public UserData SelectedUserData
    {
        get { return selectedUserData; }
        set
        {
            selectedUserData = value;
            PropertyChanged?.Invoke(this,
                new PropertyChangedEventArgs(nameof(SelectedUserData)));
        }
    }
}

and bind to it like this:

<ComboBox ItemsSource="{Binding UserData}"
          SelectedItem="{Binding SelectedUserData}"
          DisplayMemberPath="Text"/>

In the constructor of your MainWindow (or some other appropriate place), initialize the view model and assign it to the DataContext property of the Window:

public MainWindow()
{
    InitializeComponent();

    var vm = new ViewModel();
    vm.UserData.Add(new UserData { Text = "User 1" });
    vm.UserData.Add(new UserData { Text = "User 2" });
    vm.UserData.Add(new UserData { Text = "User 3" });
    vm.SelectedUserData = vm.UserData[1];

    DataContext = vm;
}

Note that since you can set the ComboBox's DisplayMemberPath property (or declare an ItemTemplate) it's not necessary to override the ToString method of the UserData class.


问:
SSRS "B" Parameter change to default after change in "A" parameter
I have SSRS report with several parameters (based on SSAS cube). All parameters has own default values. For example there are 3 parameters.

At first I change 1st and 3rd parameters to another value. After that I change value of the 2nd parameter. But after that the value of the 3rd parameter changes also - to its default. But the first parameter will stay the same. There is some dependency in order - if I change 2nd parameter, the 3rd parameter will reset itself to default.

Is there any chance to avoid this situation? I want keep the value of the 3rd parameter same as I defined.

There is no connection between those parameters

Thank you for your help

Ondra

答: On Parameter properties, in advance tab select option as to not refresh, check below screenshot