qid
int64 4
8.14M
| question
stringlengths 20
48.3k
| answers
list | date
stringlengths 10
10
| metadata
list | input
stringlengths 12
45k
| output
stringlengths 2
31.8k
|
---|---|---|---|---|---|---|
279,572 |
<p>I have a database where one of the common queries is has a "where blobCol is null", I think that this is getting bad performance (as in a full table scan). I have no need to index the contents of the blobCol. </p>
<p>What indexes would improve this? Can an index be built on an expression (blobCol is not null) rather than just a column?</p>
|
[
{
"answer_id": 279578,
"author": "Robert Gamble",
"author_id": 25222,
"author_profile": "https://Stackoverflow.com/users/25222",
"pm_score": 1,
"selected": false,
"text": "<p>Some databases allow indexes on expressions but a plain index should reduce the running time of your query significantly.</p>\n"
},
{
"answer_id": 279580,
"author": "Vinko Vrsalovic",
"author_id": 5190,
"author_profile": "https://Stackoverflow.com/users/5190",
"pm_score": 3,
"selected": true,
"text": "<p>Yes, most DBMSs support it, for instance in <a href=\"http://www.postgresql.org/docs/8.2/static/sql-createindex.html\" rel=\"nofollow noreferrer\">PostgreSQL</a> it is</p>\n\n<pre><code>CREATE INDEX notNullblob ON myTable (blobCol is not NULL);\n</code></pre>\n\n<p>It seems that the best you could do on SQL Server though is to create a <a href=\"http://msdn.microsoft.com/en-us/library/ms189292.aspx\" rel=\"nofollow noreferrer\">computed column</a> that, for example, will contain 1 if blob is null and 0 otherwise and create an index over that.</p>\n"
}
] |
2008/11/10
|
[
"https://Stackoverflow.com/questions/279572",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1343/"
] |
I have a database where one of the common queries is has a "where blobCol is null", I think that this is getting bad performance (as in a full table scan). I have no need to index the contents of the blobCol.
What indexes would improve this? Can an index be built on an expression (blobCol is not null) rather than just a column?
|
Yes, most DBMSs support it, for instance in [PostgreSQL](http://www.postgresql.org/docs/8.2/static/sql-createindex.html) it is
```
CREATE INDEX notNullblob ON myTable (blobCol is not NULL);
```
It seems that the best you could do on SQL Server though is to create a [computed column](http://msdn.microsoft.com/en-us/library/ms189292.aspx) that, for example, will contain 1 if blob is null and 0 otherwise and create an index over that.
|
279,575 |
<p>HI All,</p>
<p>I have a piece of javaScript that removes commas from a provided string (in my case currency values)</p>
<p>It is:</p>
<pre><code> function replaceCommaInCurrency(myField, val)
{
var re = /,/g;
document.net1003Form.myField.value=val.replace(re, '');
}
</code></pre>
<p>'MyField' was my attempt to dynamically have this work on any field that I pass in, but it doesn't work, I get errors saying 'MyField' is not valid. I sort of get my, but I thought this was valid.</p>
<p>I am calling by using: onBlur="replaceCommaInCurrency(this.name, this.value);return false;"</p>
<p>this.name and this.value are passing in the right values...field name and its value.</p>
<p>How do I do this dynamically?</p>
<p>-Jason</p>
|
[
{
"answer_id": 279604,
"author": "flatline",
"author_id": 20846,
"author_profile": "https://Stackoverflow.com/users/20846",
"pm_score": 2,
"selected": false,
"text": "<p>If you code it right into the markup like that, e.g. onblur=\"replaceCommaInCurrency(this)\", the control originating the event gets passed as the parameter. Then you should be able to do something like:</p>\n\n<pre><code>myField.value = myField.value.replace(re, '');\n</code></pre>\n\n<p>with jQuery:</p>\n\n<pre><code>var jqField = $(myField);\njqField.val(jqField.val().replace(re, '')); \n</code></pre>\n"
},
{
"answer_id": 279607,
"author": "MrKurt",
"author_id": 35296,
"author_profile": "https://Stackoverflow.com/users/35296",
"pm_score": 3,
"selected": true,
"text": "<p>You can use eval to make your code snippet work:</p>\n\n<pre><code>eval(\"document.net1003Form.\" + myField + \".value=val.replace(re, '');\");\n</code></pre>\n\n<p>As mentioned below, the square brackets work (and don't suck like eval), stupid me for forgetting about those:</p>\n\n<pre><code>document.net1003Form[myField].value=val.replace(re, '');\n</code></pre>\n\n<p>Alternatively, try something like this:</p>\n\n<pre><code>function replaceCommaInCurrency(field){\n var re = /,/g;\n field.value = field.value.replace(re, '');\n}\n</code></pre>\n\n<p>Which gets called like so:</p>\n\n<pre><code>onBlur=\"replaceCommaInCurrency(this); return false\";\n</code></pre>\n\n<p>You should consider using a javascript toolkit for things like this. You could set a class like \"currency\" on each input, then use this snippet of jQuery based Javascript to handle everything:</p>\n\n<pre><code>$(function(){\n $(\"input.currency\").bind('blur', function(){\n this.value = $(this).val().replace(',', '');\n })\n});\n</code></pre>\n\n<p>This code would fire on document ready, attach an event handler to each input with currency as its class, and then do the replacements. Note that you don't need a regex for replacement as well.</p>\n"
},
{
"answer_id": 279614,
"author": "roenving",
"author_id": 23142,
"author_profile": "https://Stackoverflow.com/users/23142",
"pm_score": 0,
"selected": false,
"text": "<pre><code> function removeCommaInCurrency(myField)\n {\n var re = /,/g;\n\n myField.value=myField.value.replace(re, '');\n }\n</code></pre>\n\n<p>-- and then call it like this:</p>\n\n<pre><code><input type=\"text\" name=\"...\" onchange=\"removeCommaInCurrency(this);\">\n</code></pre>\n"
},
{
"answer_id": 279621,
"author": "FriendOfFuture",
"author_id": 1169746,
"author_profile": "https://Stackoverflow.com/users/1169746",
"pm_score": 1,
"selected": false,
"text": "<p>In general, you should be using a framework that will handle low level functionality like this, but the specific answer to your question is to use bracket notation for the field name:</p>\n\n<pre><code>function replaceCommaInCurrency( myField, val)\n{\n var re = /,/g;\n\n document.net1003Form[myField].value=val.replace(re, '');\n}\n</code></pre>\n"
},
{
"answer_id": 279760,
"author": "bobince",
"author_id": 18936,
"author_profile": "https://Stackoverflow.com/users/18936",
"pm_score": 0,
"selected": false,
"text": "<p>flatline and roenving's solution with ‘this’ is the cleaner approach, it also avoids the problems of ‘document.formname.fieldname’.</p>\n\n<p>(Use ‘document.forms.formname’ to access a form without possible clashing on forms having the same name as members of the document object, and ‘forms.elements.fieldname’ to do the same with fields. Like all JavaScript object, object[namevariable] can also be used. Or, better, add IDs and use the unambiguous document.getElementById method.)</p>\n\n<p>By moving binding into the script you can also remove the inline JavaScript of the onclick attribute, making the markup cleaner still:</p>\n\n<pre><code><input type=\"text\" class=\"number\" name=\"something\" />\n...\n<script type=\"text/javascript\"> // external script is best, linked after all forms\n function numberfield_bind() {\n var inputs= document.getElementsByTagName('input');\n for (var inputi= inputs.length; inputi-->0;)\n if (inputs[inputi].className=='number')\n inputs[inputi].onchange= numberfield_change;\n }\n function numberfield_change() {\n this.value= this.value.split(',').join('');\n }\n numberfield_bind();\n</script>\n</code></pre>\n"
}
] |
2008/11/10
|
[
"https://Stackoverflow.com/questions/279575",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] |
HI All,
I have a piece of javaScript that removes commas from a provided string (in my case currency values)
It is:
```
function replaceCommaInCurrency(myField, val)
{
var re = /,/g;
document.net1003Form.myField.value=val.replace(re, '');
}
```
'MyField' was my attempt to dynamically have this work on any field that I pass in, but it doesn't work, I get errors saying 'MyField' is not valid. I sort of get my, but I thought this was valid.
I am calling by using: onBlur="replaceCommaInCurrency(this.name, this.value);return false;"
this.name and this.value are passing in the right values...field name and its value.
How do I do this dynamically?
-Jason
|
You can use eval to make your code snippet work:
```
eval("document.net1003Form." + myField + ".value=val.replace(re, '');");
```
As mentioned below, the square brackets work (and don't suck like eval), stupid me for forgetting about those:
```
document.net1003Form[myField].value=val.replace(re, '');
```
Alternatively, try something like this:
```
function replaceCommaInCurrency(field){
var re = /,/g;
field.value = field.value.replace(re, '');
}
```
Which gets called like so:
```
onBlur="replaceCommaInCurrency(this); return false";
```
You should consider using a javascript toolkit for things like this. You could set a class like "currency" on each input, then use this snippet of jQuery based Javascript to handle everything:
```
$(function(){
$("input.currency").bind('blur', function(){
this.value = $(this).val().replace(',', '');
})
});
```
This code would fire on document ready, attach an event handler to each input with currency as its class, and then do the replacements. Note that you don't need a regex for replacement as well.
|
279,583 |
<p>I have a very basic app that I believe should change the width of an image, but it does nothing... can anyone tell me why, when I click on the image, nothing happens to the image? </p>
<p><em>(note, the image itself doesnt really matter, Im just trying to figure out how to shrink and grow and image in JavaFX)</em></p>
<pre><code>import javafx.application.Frame;
import javafx.application.Stage;
import javafx.scene.image.ImageView;
import javafx.scene.image.Image;
import javafx.input.MouseEvent;
var w:Number = 250;
Frame {
title: "Image View Sample"
width: 500
height: 500
closeAction: function() {
java.lang.System.exit( 0 );
}
visible: true
stage: Stage {
content: [
ImageView {
x: 200;
y: 200;
image: Image {
url: "{__DIR__}/c1.png"
width: bind w;
}
onMouseClicked: function( e: MouseEvent ):Void {
w = 100;
}
}
]
}
}
</code></pre>
<p>Thanks heaps!</p>
|
[
{
"answer_id": 279604,
"author": "flatline",
"author_id": 20846,
"author_profile": "https://Stackoverflow.com/users/20846",
"pm_score": 2,
"selected": false,
"text": "<p>If you code it right into the markup like that, e.g. onblur=\"replaceCommaInCurrency(this)\", the control originating the event gets passed as the parameter. Then you should be able to do something like:</p>\n\n<pre><code>myField.value = myField.value.replace(re, '');\n</code></pre>\n\n<p>with jQuery:</p>\n\n<pre><code>var jqField = $(myField);\njqField.val(jqField.val().replace(re, '')); \n</code></pre>\n"
},
{
"answer_id": 279607,
"author": "MrKurt",
"author_id": 35296,
"author_profile": "https://Stackoverflow.com/users/35296",
"pm_score": 3,
"selected": true,
"text": "<p>You can use eval to make your code snippet work:</p>\n\n<pre><code>eval(\"document.net1003Form.\" + myField + \".value=val.replace(re, '');\");\n</code></pre>\n\n<p>As mentioned below, the square brackets work (and don't suck like eval), stupid me for forgetting about those:</p>\n\n<pre><code>document.net1003Form[myField].value=val.replace(re, '');\n</code></pre>\n\n<p>Alternatively, try something like this:</p>\n\n<pre><code>function replaceCommaInCurrency(field){\n var re = /,/g;\n field.value = field.value.replace(re, '');\n}\n</code></pre>\n\n<p>Which gets called like so:</p>\n\n<pre><code>onBlur=\"replaceCommaInCurrency(this); return false\";\n</code></pre>\n\n<p>You should consider using a javascript toolkit for things like this. You could set a class like \"currency\" on each input, then use this snippet of jQuery based Javascript to handle everything:</p>\n\n<pre><code>$(function(){\n $(\"input.currency\").bind('blur', function(){\n this.value = $(this).val().replace(',', '');\n })\n});\n</code></pre>\n\n<p>This code would fire on document ready, attach an event handler to each input with currency as its class, and then do the replacements. Note that you don't need a regex for replacement as well.</p>\n"
},
{
"answer_id": 279614,
"author": "roenving",
"author_id": 23142,
"author_profile": "https://Stackoverflow.com/users/23142",
"pm_score": 0,
"selected": false,
"text": "<pre><code> function removeCommaInCurrency(myField)\n {\n var re = /,/g;\n\n myField.value=myField.value.replace(re, '');\n }\n</code></pre>\n\n<p>-- and then call it like this:</p>\n\n<pre><code><input type=\"text\" name=\"...\" onchange=\"removeCommaInCurrency(this);\">\n</code></pre>\n"
},
{
"answer_id": 279621,
"author": "FriendOfFuture",
"author_id": 1169746,
"author_profile": "https://Stackoverflow.com/users/1169746",
"pm_score": 1,
"selected": false,
"text": "<p>In general, you should be using a framework that will handle low level functionality like this, but the specific answer to your question is to use bracket notation for the field name:</p>\n\n<pre><code>function replaceCommaInCurrency( myField, val)\n{\n var re = /,/g;\n\n document.net1003Form[myField].value=val.replace(re, '');\n}\n</code></pre>\n"
},
{
"answer_id": 279760,
"author": "bobince",
"author_id": 18936,
"author_profile": "https://Stackoverflow.com/users/18936",
"pm_score": 0,
"selected": false,
"text": "<p>flatline and roenving's solution with ‘this’ is the cleaner approach, it also avoids the problems of ‘document.formname.fieldname’.</p>\n\n<p>(Use ‘document.forms.formname’ to access a form without possible clashing on forms having the same name as members of the document object, and ‘forms.elements.fieldname’ to do the same with fields. Like all JavaScript object, object[namevariable] can also be used. Or, better, add IDs and use the unambiguous document.getElementById method.)</p>\n\n<p>By moving binding into the script you can also remove the inline JavaScript of the onclick attribute, making the markup cleaner still:</p>\n\n<pre><code><input type=\"text\" class=\"number\" name=\"something\" />\n...\n<script type=\"text/javascript\"> // external script is best, linked after all forms\n function numberfield_bind() {\n var inputs= document.getElementsByTagName('input');\n for (var inputi= inputs.length; inputi-->0;)\n if (inputs[inputi].className=='number')\n inputs[inputi].onchange= numberfield_change;\n }\n function numberfield_change() {\n this.value= this.value.split(',').join('');\n }\n numberfield_bind();\n</script>\n</code></pre>\n"
}
] |
2008/11/10
|
[
"https://Stackoverflow.com/questions/279583",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/26310/"
] |
I have a very basic app that I believe should change the width of an image, but it does nothing... can anyone tell me why, when I click on the image, nothing happens to the image?
*(note, the image itself doesnt really matter, Im just trying to figure out how to shrink and grow and image in JavaFX)*
```
import javafx.application.Frame;
import javafx.application.Stage;
import javafx.scene.image.ImageView;
import javafx.scene.image.Image;
import javafx.input.MouseEvent;
var w:Number = 250;
Frame {
title: "Image View Sample"
width: 500
height: 500
closeAction: function() {
java.lang.System.exit( 0 );
}
visible: true
stage: Stage {
content: [
ImageView {
x: 200;
y: 200;
image: Image {
url: "{__DIR__}/c1.png"
width: bind w;
}
onMouseClicked: function( e: MouseEvent ):Void {
w = 100;
}
}
]
}
}
```
Thanks heaps!
|
You can use eval to make your code snippet work:
```
eval("document.net1003Form." + myField + ".value=val.replace(re, '');");
```
As mentioned below, the square brackets work (and don't suck like eval), stupid me for forgetting about those:
```
document.net1003Form[myField].value=val.replace(re, '');
```
Alternatively, try something like this:
```
function replaceCommaInCurrency(field){
var re = /,/g;
field.value = field.value.replace(re, '');
}
```
Which gets called like so:
```
onBlur="replaceCommaInCurrency(this); return false";
```
You should consider using a javascript toolkit for things like this. You could set a class like "currency" on each input, then use this snippet of jQuery based Javascript to handle everything:
```
$(function(){
$("input.currency").bind('blur', function(){
this.value = $(this).val().replace(',', '');
})
});
```
This code would fire on document ready, attach an event handler to each input with currency as its class, and then do the replacements. Note that you don't need a regex for replacement as well.
|
279,601 |
<p>I have a <code>vector</code> that I want to insert into a <code>set</code>. This is one of three different calls (the other two are more complex, involving <code>boost::lambda::if_()</code>), but solving this simple case will help me solve the others.</p>
<pre><code>std::vector<std::string> s_vector;
std::set<std::string> s_set;
std::for_each(s_vector.begin(), s_vector.end(), s_set.insert(boost::lambda::_1));
</code></pre>
<p>Unfortunately, this fails with a conversion error message (trying to convert <code>boost::lambda::placeholder1_type</code> to <code>std::string</code>).</p>
<p>So... what's wrong with this?</p>
|
[
{
"answer_id": 279649,
"author": "Ferruccio",
"author_id": 4086,
"author_profile": "https://Stackoverflow.com/users/4086",
"pm_score": 1,
"selected": false,
"text": "<p>I think part of the problem is that <code>for_each()</code> is expecting a functor and you're passing it the result of a function call. So your code would call <code>vector<string>::insert()</code> first and then pass the result of that call to <code>for_each()</code>. I'm not sure of the exact syntax, but I think you want to use bind in combination with lambda here. e.g.</p>\n\n<pre><code>for_each(s_vector.begin(), s_vector.end(),\n boost::bind(set<string>::insert, s_set, boost::lambda::_1));\n</code></pre>\n"
},
{
"answer_id": 279677,
"author": "Austin Ziegler",
"author_id": 36378,
"author_profile": "https://Stackoverflow.com/users/36378",
"pm_score": 0,
"selected": false,
"text": "<p>Unfortunately, this:</p>\n\n<pre><code>std::for_each(s_vector.begin(), s_vector.end(),\n lambda::bind(&std::set<std::string>::insert, s_set, lambda::_1));\n</code></pre>\n\n<p>doesn't work. (Note that I used set::insert, because that's what s_set is.) The error is really nasty, but boils down to the fact that it can't figure out which set::insert to use, since there's three overloads. The one that I'm trying to use is the set that will return pair::iterator, bool> (the value insert). Obviously, that's not working.</p>\n\n<p>I noticed you used boost::bind, not boost::lambda::bind -- was that intentional? (They appear to work a bit differently.)</p>\n\n<p>I think you're right about expecting a functor as opposed to a function call result; I'm sure this can be turned into a functor, but my brain is not seeing the answer right now.</p>\n\n<p>Thanks.</p>\n"
},
{
"answer_id": 279689,
"author": "Mic",
"author_id": 35656,
"author_profile": "https://Stackoverflow.com/users/35656",
"pm_score": 3,
"selected": true,
"text": "<blockquote>\n <p>The error is really nasty, but boils down to the fact that it can't figure out which set::insert to use, since there's three overloads.</p>\n</blockquote>\n\n<p>You can work around the ambiguity by giving bind a helpful hand, by specifying a pointer to the function you wish to use:</p>\n\n<pre><code>typedef std::set<std::string> s_type;\ntypedef std::pair<s_type::iterator, bool>(s_type::*insert_fp)(const s_type::value_type&);\nstd::for_each(s_vector.begin(), s_vector.end(), boost::bind(static_cast<insert_fp>(&s_type::insert), &s_set, _1));\n</code></pre>\n\n<p>It's not pretty, but it should work.</p>\n"
},
{
"answer_id": 279715,
"author": "user35978",
"author_id": 35978,
"author_profile": "https://Stackoverflow.com/users/35978",
"pm_score": 2,
"selected": false,
"text": "<p>I would use a for-loop :-D</p>\n"
},
{
"answer_id": 279850,
"author": "Alastair",
"author_id": 31038,
"author_profile": "https://Stackoverflow.com/users/31038",
"pm_score": 2,
"selected": false,
"text": "<p>To just copy the vector into the set, you could use std::copy and an insertion iterator. Something like:</p>\n\n<pre><code>std::copy(s_vector.begin(), s_vector.end(), std::inserter(s_set, s_set.end()));\n</code></pre>\n\n<p>Of course this doesn't use boost::lambda at all, so it probably doesn't help you generalise this into doing what you want. It would be better to know more about what you're trying to do here. I'm going to assume, based on your mention of lambda::_if, that your lambda is going to do some kind of filtering of the input vector before inserting into the set.</p>\n\n<p>The following (complete, tested) example shows how to copy only strings which are <= 4 characters from the vector into the set:</p>\n\n<pre><code>#include <boost/assign/list_of.hpp>\n#include <boost/lambda/lambda.hpp>\n#include <boost/lambda/bind.hpp>\n#include <boost/test/minimal.hpp>\n\n#include <set>\n#include <vector>\n#include <algorithm>\n\nusing namespace std;\nusing namespace boost::lambda;\nusing namespace boost::assign;\n\nint test_main(int argc, char* argv[])\n{\n vector<string> s_vector = list_of(\"red\")(\"orange\")(\"yellow\")(\"blue\")(\"indigo\")(\"violet\");\n set<string> s_set;\n\n // Copy only strings length<=4 into set:\n\n std::remove_copy_if(s_vector.begin(), s_vector.end(), std::inserter(s_set, s_set.end()),\n bind(&string::length, _1) > 4u);\n\n BOOST_CHECK(s_set.size() == 2);\n BOOST_CHECK(s_set.count(\"red\"));\n BOOST_CHECK(s_set.count(\"blue\"));\n\n return 0;\n}\n</code></pre>\n\n<p>Hopefully this gives you something to go on?</p>\n\n<p>Also let me reiterate the point made above that boost::bind and boost::lambda::bind are two different beasts. Conceptually they are similar, but they produce outputs of different types. Only the latter can be combined with other lambda operators.</p>\n"
}
] |
2008/11/10
|
[
"https://Stackoverflow.com/questions/279601",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/36378/"
] |
I have a `vector` that I want to insert into a `set`. This is one of three different calls (the other two are more complex, involving `boost::lambda::if_()`), but solving this simple case will help me solve the others.
```
std::vector<std::string> s_vector;
std::set<std::string> s_set;
std::for_each(s_vector.begin(), s_vector.end(), s_set.insert(boost::lambda::_1));
```
Unfortunately, this fails with a conversion error message (trying to convert `boost::lambda::placeholder1_type` to `std::string`).
So... what's wrong with this?
|
>
> The error is really nasty, but boils down to the fact that it can't figure out which set::insert to use, since there's three overloads.
>
>
>
You can work around the ambiguity by giving bind a helpful hand, by specifying a pointer to the function you wish to use:
```
typedef std::set<std::string> s_type;
typedef std::pair<s_type::iterator, bool>(s_type::*insert_fp)(const s_type::value_type&);
std::for_each(s_vector.begin(), s_vector.end(), boost::bind(static_cast<insert_fp>(&s_type::insert), &s_set, _1));
```
It's not pretty, but it should work.
|
279,610 |
<p>I want to create a history table to track field changes across a number of tables in DB2. </p>
<p>I know history is usually done with copying an entire table's structure and giving it a suffixed name (e.g. user --> user_history). Then you can use a pretty simple trigger to copy the old record into the history table on an UPDATE.</p>
<p>However, for my application this would use too much space. It doesn't seem like a good idea (to me at least) to copy an entire record to another table every time a field changes. So I thought I could have a generic 'history' table which would track individual field changes:</p>
<pre><code>CREATE TABLE history
(
history_id LONG GENERATED ALWAYS AS IDENTITY,
record_id INTEGER NOT NULL,
table_name VARCHAR(32) NOT NULL,
field_name VARCHAR(64) NOT NULL,
field_value VARCHAR(1024),
change_time TIMESTAMP,
PRIMARY KEY (history_id)
);
</code></pre>
<p>OK, so every table that I want to track has a single, auto-generated id field as the primary key, which would be put into the 'record_id' field. And the maximum VARCHAR size in the tables is 1024. Obviously if a non-VARCHAR field changes, it would have to be converted into a VARCHAR before inserting the record into the history table.</p>
<p>Now, this could be a completely retarded way to do things (hey, let me know why if it is), but I think it it's a good way of tracking changes that need to be pulled up rarely and need to be stored for a significant amount of time. </p>
<p>Anyway, I need help with writing the trigger to add records to the history table on an update. Let's for example take a hypothetical user table:</p>
<pre><code>CREATE TABLE user
(
user_id INTEGER GENERATED ALWAYS AS IDENTITY,
username VARCHAR(32) NOT NULL,
first_name VARCHAR(64) NOT NULL,
last_name VARCHAR(64) NOT NULL,
email_address VARCHAR(256) NOT NULL
PRIMARY KEY(user_id)
);
</code></pre>
<p>So, can anyone help me with a trigger on an update of the user table to insert the changes into the history table? My guess is that some procedural SQL will need to be used to loop through the fields in the old record, compare them with the fields in the new record and if they don't match, then add a new entry into the history table. </p>
<p>It'd be preferable to use the same trigger action SQL for every table, regardless of its fields, if it's possible.</p>
<p>Thanks!</p>
|
[
{
"answer_id": 279649,
"author": "Ferruccio",
"author_id": 4086,
"author_profile": "https://Stackoverflow.com/users/4086",
"pm_score": 1,
"selected": false,
"text": "<p>I think part of the problem is that <code>for_each()</code> is expecting a functor and you're passing it the result of a function call. So your code would call <code>vector<string>::insert()</code> first and then pass the result of that call to <code>for_each()</code>. I'm not sure of the exact syntax, but I think you want to use bind in combination with lambda here. e.g.</p>\n\n<pre><code>for_each(s_vector.begin(), s_vector.end(),\n boost::bind(set<string>::insert, s_set, boost::lambda::_1));\n</code></pre>\n"
},
{
"answer_id": 279677,
"author": "Austin Ziegler",
"author_id": 36378,
"author_profile": "https://Stackoverflow.com/users/36378",
"pm_score": 0,
"selected": false,
"text": "<p>Unfortunately, this:</p>\n\n<pre><code>std::for_each(s_vector.begin(), s_vector.end(),\n lambda::bind(&std::set<std::string>::insert, s_set, lambda::_1));\n</code></pre>\n\n<p>doesn't work. (Note that I used set::insert, because that's what s_set is.) The error is really nasty, but boils down to the fact that it can't figure out which set::insert to use, since there's three overloads. The one that I'm trying to use is the set that will return pair::iterator, bool> (the value insert). Obviously, that's not working.</p>\n\n<p>I noticed you used boost::bind, not boost::lambda::bind -- was that intentional? (They appear to work a bit differently.)</p>\n\n<p>I think you're right about expecting a functor as opposed to a function call result; I'm sure this can be turned into a functor, but my brain is not seeing the answer right now.</p>\n\n<p>Thanks.</p>\n"
},
{
"answer_id": 279689,
"author": "Mic",
"author_id": 35656,
"author_profile": "https://Stackoverflow.com/users/35656",
"pm_score": 3,
"selected": true,
"text": "<blockquote>\n <p>The error is really nasty, but boils down to the fact that it can't figure out which set::insert to use, since there's three overloads.</p>\n</blockquote>\n\n<p>You can work around the ambiguity by giving bind a helpful hand, by specifying a pointer to the function you wish to use:</p>\n\n<pre><code>typedef std::set<std::string> s_type;\ntypedef std::pair<s_type::iterator, bool>(s_type::*insert_fp)(const s_type::value_type&);\nstd::for_each(s_vector.begin(), s_vector.end(), boost::bind(static_cast<insert_fp>(&s_type::insert), &s_set, _1));\n</code></pre>\n\n<p>It's not pretty, but it should work.</p>\n"
},
{
"answer_id": 279715,
"author": "user35978",
"author_id": 35978,
"author_profile": "https://Stackoverflow.com/users/35978",
"pm_score": 2,
"selected": false,
"text": "<p>I would use a for-loop :-D</p>\n"
},
{
"answer_id": 279850,
"author": "Alastair",
"author_id": 31038,
"author_profile": "https://Stackoverflow.com/users/31038",
"pm_score": 2,
"selected": false,
"text": "<p>To just copy the vector into the set, you could use std::copy and an insertion iterator. Something like:</p>\n\n<pre><code>std::copy(s_vector.begin(), s_vector.end(), std::inserter(s_set, s_set.end()));\n</code></pre>\n\n<p>Of course this doesn't use boost::lambda at all, so it probably doesn't help you generalise this into doing what you want. It would be better to know more about what you're trying to do here. I'm going to assume, based on your mention of lambda::_if, that your lambda is going to do some kind of filtering of the input vector before inserting into the set.</p>\n\n<p>The following (complete, tested) example shows how to copy only strings which are <= 4 characters from the vector into the set:</p>\n\n<pre><code>#include <boost/assign/list_of.hpp>\n#include <boost/lambda/lambda.hpp>\n#include <boost/lambda/bind.hpp>\n#include <boost/test/minimal.hpp>\n\n#include <set>\n#include <vector>\n#include <algorithm>\n\nusing namespace std;\nusing namespace boost::lambda;\nusing namespace boost::assign;\n\nint test_main(int argc, char* argv[])\n{\n vector<string> s_vector = list_of(\"red\")(\"orange\")(\"yellow\")(\"blue\")(\"indigo\")(\"violet\");\n set<string> s_set;\n\n // Copy only strings length<=4 into set:\n\n std::remove_copy_if(s_vector.begin(), s_vector.end(), std::inserter(s_set, s_set.end()),\n bind(&string::length, _1) > 4u);\n\n BOOST_CHECK(s_set.size() == 2);\n BOOST_CHECK(s_set.count(\"red\"));\n BOOST_CHECK(s_set.count(\"blue\"));\n\n return 0;\n}\n</code></pre>\n\n<p>Hopefully this gives you something to go on?</p>\n\n<p>Also let me reiterate the point made above that boost::bind and boost::lambda::bind are two different beasts. Conceptually they are similar, but they produce outputs of different types. Only the latter can be combined with other lambda operators.</p>\n"
}
] |
2008/11/10
|
[
"https://Stackoverflow.com/questions/279610",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] |
I want to create a history table to track field changes across a number of tables in DB2.
I know history is usually done with copying an entire table's structure and giving it a suffixed name (e.g. user --> user\_history). Then you can use a pretty simple trigger to copy the old record into the history table on an UPDATE.
However, for my application this would use too much space. It doesn't seem like a good idea (to me at least) to copy an entire record to another table every time a field changes. So I thought I could have a generic 'history' table which would track individual field changes:
```
CREATE TABLE history
(
history_id LONG GENERATED ALWAYS AS IDENTITY,
record_id INTEGER NOT NULL,
table_name VARCHAR(32) NOT NULL,
field_name VARCHAR(64) NOT NULL,
field_value VARCHAR(1024),
change_time TIMESTAMP,
PRIMARY KEY (history_id)
);
```
OK, so every table that I want to track has a single, auto-generated id field as the primary key, which would be put into the 'record\_id' field. And the maximum VARCHAR size in the tables is 1024. Obviously if a non-VARCHAR field changes, it would have to be converted into a VARCHAR before inserting the record into the history table.
Now, this could be a completely retarded way to do things (hey, let me know why if it is), but I think it it's a good way of tracking changes that need to be pulled up rarely and need to be stored for a significant amount of time.
Anyway, I need help with writing the trigger to add records to the history table on an update. Let's for example take a hypothetical user table:
```
CREATE TABLE user
(
user_id INTEGER GENERATED ALWAYS AS IDENTITY,
username VARCHAR(32) NOT NULL,
first_name VARCHAR(64) NOT NULL,
last_name VARCHAR(64) NOT NULL,
email_address VARCHAR(256) NOT NULL
PRIMARY KEY(user_id)
);
```
So, can anyone help me with a trigger on an update of the user table to insert the changes into the history table? My guess is that some procedural SQL will need to be used to loop through the fields in the old record, compare them with the fields in the new record and if they don't match, then add a new entry into the history table.
It'd be preferable to use the same trigger action SQL for every table, regardless of its fields, if it's possible.
Thanks!
|
>
> The error is really nasty, but boils down to the fact that it can't figure out which set::insert to use, since there's three overloads.
>
>
>
You can work around the ambiguity by giving bind a helpful hand, by specifying a pointer to the function you wish to use:
```
typedef std::set<std::string> s_type;
typedef std::pair<s_type::iterator, bool>(s_type::*insert_fp)(const s_type::value_type&);
std::for_each(s_vector.begin(), s_vector.end(), boost::bind(static_cast<insert_fp>(&s_type::insert), &s_set, _1));
```
It's not pretty, but it should work.
|
279,631 |
<p>I'm trying to load an external swf movie then adding the ability to drag it around the stage, however whenever I try to do this I just hit a dead end. Are there any limitations on what you can set be draggable or clickable? An example of what I'm doing is below:</p>
<pre><code>public function loadSwf(url:String, swfUniqueName:String)
{
var ldr:Loader = new Loader();
var url:String = "Swfs/Label.swf";
var urlReq:URLRequest = new URLRequest(url);
ldr.load(urlReq);
ldr.contentLoaderInfo.addEventListener("complete", loadCompleteHandler);
}
private function loadCompleteHandler(event):void{
var ldr = event.currentTarget;
// These are only here because I can't seem to get the drag to work
ldr.content.doubleClickEnabled = true;
ldr.content.buttonMode = true;
ldr.content.useHandCursor = true;
ldr.content.mouseEnabled = true;
ldr.content.txtLabel.mouseEnabled = true;
this.addChild(ldr.content);
ldr.content.addEventListener(MouseEvent.MOUSE_DOWN, mouse_down);
}
mouse_down = function(event) {
trace(event.target);
}
</code></pre>
<p>Using the code above i can only get it to recognise a click on the movie itself if it is over a click on the textfield, but this really needs to work on any part of the movie. Any ideas?</p>
|
[
{
"answer_id": 281754,
"author": "mgbennet",
"author_id": 32139,
"author_profile": "https://Stackoverflow.com/users/32139",
"pm_score": 1,
"selected": false,
"text": "<p>Something of a shot in the dark, but could you make a transparent movie clip on top of the movie that's loaded that is dragged around, which moves the swf underneath?</p>\n"
},
{
"answer_id": 282050,
"author": "Iain",
"author_id": 11911,
"author_profile": "https://Stackoverflow.com/users/11911",
"pm_score": 2,
"selected": false,
"text": "<p>If there is empty space in your content, Flash will treat it like you have clicked THROUGH the clip to the stage below. Try adding a transparent square to the bottom layer of the content you're loading.</p>\n\n<p>Also try setting:</p>\n\n<p><code>ldr.content.mouseChildren = false;</code></p>\n"
}
] |
2008/11/11
|
[
"https://Stackoverflow.com/questions/279631",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/26081/"
] |
I'm trying to load an external swf movie then adding the ability to drag it around the stage, however whenever I try to do this I just hit a dead end. Are there any limitations on what you can set be draggable or clickable? An example of what I'm doing is below:
```
public function loadSwf(url:String, swfUniqueName:String)
{
var ldr:Loader = new Loader();
var url:String = "Swfs/Label.swf";
var urlReq:URLRequest = new URLRequest(url);
ldr.load(urlReq);
ldr.contentLoaderInfo.addEventListener("complete", loadCompleteHandler);
}
private function loadCompleteHandler(event):void{
var ldr = event.currentTarget;
// These are only here because I can't seem to get the drag to work
ldr.content.doubleClickEnabled = true;
ldr.content.buttonMode = true;
ldr.content.useHandCursor = true;
ldr.content.mouseEnabled = true;
ldr.content.txtLabel.mouseEnabled = true;
this.addChild(ldr.content);
ldr.content.addEventListener(MouseEvent.MOUSE_DOWN, mouse_down);
}
mouse_down = function(event) {
trace(event.target);
}
```
Using the code above i can only get it to recognise a click on the movie itself if it is over a click on the textfield, but this really needs to work on any part of the movie. Any ideas?
|
If there is empty space in your content, Flash will treat it like you have clicked THROUGH the clip to the stage below. Try adding a transparent square to the bottom layer of the content you're loading.
Also try setting:
`ldr.content.mouseChildren = false;`
|
279,634 |
<p>I have this piece of Javascript and it just won't work. I allready checked JSlint but that said everything works. Still doesn't work. The javascript is located not in the HTML but is linked in the <code><head></code></p>
<p>note: I am working with a local server, so pageload in instant.</p>
<pre><code>function changeVisibility() {
var a = document.getElementById('invisible');
a.style.display = 'block';
}
var changed = document.getElementById('click1');
changed.onchange = changeVisibility;
</code></pre>
<p>This here is the corresponding HTML</p>
<pre><code><input type="file" name="click[]" size="35" id="click1" />
<div id="invisible" style="display: none;">
<a href="javascript:addFileInput();">Attach another File</a>
</div>
</code></pre>
<p>So what happens is I click on the input, select a file and approve. Then then onchange event triggers and the style of my invisible div is set to block.</p>
<p>Problem is, I keep getting this error:</p>
<p>"changed is null:
changed.onchange = changeVisibility;"</p>
<p>i don't get it, I seriously don't get what I'm overlooking here.</p>
<hr>
<p>EDIT: question answered, thank you Mercutio for your help and everyone else too of course.
Final code: </p>
<pre><code>function loadEvents() {
var changed = document.getElementById('click1');
var a = document.getElementById('invisible');
document.getElementById('addField').onclick = addFileInput;
changed.onchange = function() {
a.style.display = 'block';
}
}
if (document.getElementById) window.onload = loadEvents;
</code></pre>
<p>This here is the corresponding HTML:</p>
<pre><code><input type="file" name="click[]" size="35" id="click1" />
<div id="invisible" style="display: none;">
<a href="#">Attach another File</a>
</div>
</code></pre>
<p>Also, thanks for the link to <a href="http://www.jsbin.com" rel="nofollow noreferrer">JSbin</a>, didn't know about that, looks nifty. </p>
|
[
{
"answer_id": 279637,
"author": "mercutio",
"author_id": 1951,
"author_profile": "https://Stackoverflow.com/users/1951",
"pm_score": 4,
"selected": true,
"text": "<p>This sounds like the DOM object doesn't exist at the time of referencing it. Perhaps change your code to execute once the document has fully loaded (or place the javascript at the bottom of your page)</p>\n\n<blockquote>\n <p>note: I am working with a local server, so pageload in instant.</p>\n</blockquote>\n\n<p>that's not the issue - the constituent parts of a document are loaded in order. It doesn't matter how fast they are loaded, some things happen before others :D</p>\n\n<blockquote>\n <p>The onlything I'd like to do now is remove the Javascript link from the ...</p>\n</blockquote>\n\n<p>Place an id on there, and inside your function do this:</p>\n\n<pre><code>document.getElementById('addField').onclick = addFileInput;\n</code></pre>\n\n<p>Or, as you already have the div as the variable 'a':</p>\n\n<pre><code>a.firstChild.onclick = addFileInput;\n</code></pre>\n\n<p>But this obviously leaves you with an invalid anchor tag. Best practice suggests that you should provide a way to do it without javascript, and override that functionality with your javascript-method if available.</p>\n"
},
{
"answer_id": 279650,
"author": "FriendOfFuture",
"author_id": 1169746,
"author_profile": "https://Stackoverflow.com/users/1169746",
"pm_score": 0,
"selected": false,
"text": "<p>You need to wrap your code in a window.onload event handler, a domReady event handler (available in most modern js frameworks and libraries) or place at the bottom of the page.</p>\n\n<p>Placing at the bottom of the page works fine, as you can see <a href=\"http://jsbin.com/azoke/edit\" rel=\"nofollow noreferrer\">here</a>.</p>\n\n<p>Decoupling event responder from your markup is covered under the topic of \"Unobtrusive JavaScript\" and can be handled in a variety of ways. In general, you want to declare event responders in a window.onload or document.ready event.</p>\n"
},
{
"answer_id": 279652,
"author": "FlySwat",
"author_id": 1965,
"author_profile": "https://Stackoverflow.com/users/1965",
"pm_score": 0,
"selected": false,
"text": "<p>I think its because you are trying to modify a file element.</p>\n\n<p>Browsers don't usually let you do that. If you want to show or hide them, place them inside of a div and show or hide that.</p>\n"
},
{
"answer_id": 279664,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 1,
"selected": false,
"text": "<p>mercutio is correct. If that code is executing in the HEAD, the call to \"document.getElementById('click1')\" will always return null since the body hasn't been parsed yet. Perhaps you should put that logic inside of an onload event handler.</p>\n"
},
{
"answer_id": 279676,
"author": "Vordreller",
"author_id": 11795,
"author_profile": "https://Stackoverflow.com/users/11795",
"pm_score": 0,
"selected": false,
"text": "<p>Right, I've modified things based on your collective sudgestions and it works now. Onlything bothering me is the direct reference to Javascript inside the anchor</p>\n"
}
] |
2008/11/11
|
[
"https://Stackoverflow.com/questions/279634",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11795/"
] |
I have this piece of Javascript and it just won't work. I allready checked JSlint but that said everything works. Still doesn't work. The javascript is located not in the HTML but is linked in the `<head>`
note: I am working with a local server, so pageload in instant.
```
function changeVisibility() {
var a = document.getElementById('invisible');
a.style.display = 'block';
}
var changed = document.getElementById('click1');
changed.onchange = changeVisibility;
```
This here is the corresponding HTML
```
<input type="file" name="click[]" size="35" id="click1" />
<div id="invisible" style="display: none;">
<a href="javascript:addFileInput();">Attach another File</a>
</div>
```
So what happens is I click on the input, select a file and approve. Then then onchange event triggers and the style of my invisible div is set to block.
Problem is, I keep getting this error:
"changed is null:
changed.onchange = changeVisibility;"
i don't get it, I seriously don't get what I'm overlooking here.
---
EDIT: question answered, thank you Mercutio for your help and everyone else too of course.
Final code:
```
function loadEvents() {
var changed = document.getElementById('click1');
var a = document.getElementById('invisible');
document.getElementById('addField').onclick = addFileInput;
changed.onchange = function() {
a.style.display = 'block';
}
}
if (document.getElementById) window.onload = loadEvents;
```
This here is the corresponding HTML:
```
<input type="file" name="click[]" size="35" id="click1" />
<div id="invisible" style="display: none;">
<a href="#">Attach another File</a>
</div>
```
Also, thanks for the link to [JSbin](http://www.jsbin.com), didn't know about that, looks nifty.
|
This sounds like the DOM object doesn't exist at the time of referencing it. Perhaps change your code to execute once the document has fully loaded (or place the javascript at the bottom of your page)
>
> note: I am working with a local server, so pageload in instant.
>
>
>
that's not the issue - the constituent parts of a document are loaded in order. It doesn't matter how fast they are loaded, some things happen before others :D
>
> The onlything I'd like to do now is remove the Javascript link from the ...
>
>
>
Place an id on there, and inside your function do this:
```
document.getElementById('addField').onclick = addFileInput;
```
Or, as you already have the div as the variable 'a':
```
a.firstChild.onclick = addFileInput;
```
But this obviously leaves you with an invalid anchor tag. Best practice suggests that you should provide a way to do it without javascript, and override that functionality with your javascript-method if available.
|
279,665 |
<p>How can I return the result of a different action or move the user to a different action if there is an error in my <code>ModelState</code> without losing my <code>ModelState</code> information?</p>
<p>The scenario is; <code>Delete</code> action accepts a POST from a DELETE form rendered by my <code>Index</code> Action/View. If there is an error in the <code>Delete</code> I want to move the user back to the <code>Index</code> Action/View and show the errors that are stored by the <code>Delete</code> action in the <code>ViewData.ModelState</code>. How can this be done in ASP.NET MVC?</p>
<pre><code>[AcceptVerbs(HttpVerbs.Post | HttpVerbs.Delete)]
public ActionResult Delete([ModelBinder(typeof(RdfUriBinder))] RdfUri graphUri)
{
if (!ModelState.IsValid)
return Index(); //this needs to be replaced with something that works :)
return RedirectToAction("Index");
}
</code></pre>
|
[
{
"answer_id": 279680,
"author": "Ty.",
"author_id": 16948,
"author_profile": "https://Stackoverflow.com/users/16948",
"pm_score": -1,
"selected": false,
"text": "<p>Maybe try</p>\n\n<pre><code>return View(\"Index\");\n</code></pre>\n\n<p>instead of</p>\n\n<pre><code>return Index();\n</code></pre>\n"
},
{
"answer_id": 279740,
"author": "tvanfosson",
"author_id": 12950,
"author_profile": "https://Stackoverflow.com/users/12950",
"pm_score": 8,
"selected": true,
"text": "<p>Store your view data in <code>TempData</code> and retrieve it from there in your <code>Index</code> action, if it exists.</p>\n<pre><code> ...\n if (!ModelState.IsValid)\n TempData["ViewData"] = ViewData;\n\n RedirectToAction( "Index" );\n}\n\n public ActionResult Index()\n {\n if (TempData["ViewData"] != null)\n {\n ViewData = (ViewDataDictionary)TempData["ViewData"];\n }\n\n ...\n }\n</code></pre>\n<p>[EDIT] I checked the on-line source for MVC and it appears that the <code>ViewData</code> in the Controller is settable, so it is probably easiest just to transfer all of the <code>ViewData</code>, including the <code>ModelState</code>, to the Index action.</p>\n"
},
{
"answer_id": 281939,
"author": "Eilon",
"author_id": 31668,
"author_profile": "https://Stackoverflow.com/users/31668",
"pm_score": 4,
"selected": false,
"text": "<p>Please note that tvanfosson's solution will not always work, though in most cases it should be just fine.</p>\n\n<p>The problem with that particular solution is that if you already have any ViewData or ModelState you end up overwriting it all with the previous request's state. For example, the new request might have some model state errors related to invalid parameters being passed to the action, but those would end up being hidden because they are overwritten.</p>\n\n<p>Another situation where it might not work as expected is if you had an Action Filter that initialized some ViewData or ModelState errors. Again, they would be overwritten by that code.</p>\n\n<p>We're looking at some solutions for ASP.NET MVC that would allow you to more easily merge the state from the two requests, so stay tuned for that.</p>\n\n<p>Thanks,\nEilon</p>\n"
},
{
"answer_id": 776117,
"author": "bob",
"author_id": 23805,
"author_profile": "https://Stackoverflow.com/users/23805",
"pm_score": 5,
"selected": false,
"text": "<p>Use Action Filters (PRG pattern) (as easy as using attributes)</p>\n\n<p>Mentioned <a href=\"https://stackoverflow.com/questions/658747/how-do-i-maintain-modelstate-errors-when-using-redirecttoaction\">here</a> and <a href=\"https://web.archive.org/web/20130702160308/http://weblogs.asp.net/rashid/archive/2009/04/01/asp-net-mvc-best-practices-part-1.aspx\" rel=\"noreferrer\">here</a>.</p>\n"
},
{
"answer_id": 18323394,
"author": "Matthew",
"author_id": 1803682,
"author_profile": "https://Stackoverflow.com/users/1803682",
"pm_score": 3,
"selected": false,
"text": "<p>In case this is useful to anyone I used @bob 's recommended solution using PRG: </p>\n\n<blockquote>\n <p>see item 13 -> <a href=\"http://weblogs.asp.net/rashid/archive/2009/04/01/asp-net-mvc-best-practices-part-1.aspx#prg\" rel=\"noreferrer\">link</a>.</p>\n</blockquote>\n\n<p>I had the additional issue of messages being passed in the VeiwBag to the View being written and checked / loaded manually from TempData in the controller actions when doing a <code>RedirectToAction(\"Action\")</code>. In an attempt to simplify (and also make it maintainable) I slightly extended this approach to check and store/load other data as well. My action methods looked something like:</p>\n\n<pre><code> [AcceptVerbs(HttpVerbs.Post)]\n [ExportModelStateToTempData]\n public ActionResult ChangePassword(ProfileViewModel pVM) {\n bool result = MyChangePasswordCode(pVM.ChangePasswordViewModel);\n if (result) {\n ViewBag.Message = \"Password change success\";\n else {\n ModelState.AddModelError(\"ChangePassword\", \"Some password error\");\n }\n return RedirectToAction(\"Index\");\n }\n</code></pre>\n\n<p>And my Index Action:</p>\n\n<pre><code>[ImportModelStateFromTempData]\npublic ActionResult Index() {\n ProfileViewModel pVM = new ProfileViewModel { //setup }\n return View(pVM);\n}\n</code></pre>\n\n<p>The code in the Action Filters:</p>\n\n<pre><code>// Following best practices as listed here for storing / restoring model data:\n// http://weblogs.asp.net/rashid/archive/2009/04/01/asp-net-mvc-best-practices-part-1.aspx#prg\npublic abstract class ModelStateTempDataTransfer : ActionFilterAttribute {\n protected static readonly string Key = typeof(ModelStateTempDataTransfer).FullName;\n}\n</code></pre>\n\n<p>:</p>\n\n<pre><code>public class ExportModelStateToTempData : ModelStateTempDataTransfer {\n public override void OnActionExecuted(ActionExecutedContext filterContext) {\n //Only export when ModelState is not valid\n if (!filterContext.Controller.ViewData.ModelState.IsValid) {\n //Export if we are redirecting\n if ((filterContext.Result is RedirectResult) || (filterContext.Result is RedirectToRouteResult)) {\n filterContext.Controller.TempData[Key] = filterContext.Controller.ViewData.ModelState;\n }\n }\n // Added to pull message from ViewBag\n if (!string.IsNullOrEmpty(filterContext.Controller.ViewBag.Message)) {\n filterContext.Controller.TempData[\"Message\"] = filterContext.Controller.ViewBag.Message;\n }\n\n base.OnActionExecuted(filterContext);\n }\n}\n</code></pre>\n\n<p>:</p>\n\n<pre><code>public class ImportModelStateFromTempData : ModelStateTempDataTransfer {\n public override void OnActionExecuted(ActionExecutedContext filterContext) {\n ModelStateDictionary modelState = filterContext.Controller.TempData[Key] as ModelStateDictionary;\n\n if (modelState != null) {\n //Only Import if we are viewing\n if (filterContext.Result is ViewResult) {\n filterContext.Controller.ViewData.ModelState.Merge(modelState);\n } else {\n //Otherwise remove it.\n filterContext.Controller.TempData.Remove(Key);\n }\n }\n // Restore Viewbag message\n if (!string.IsNullOrEmpty((string)filterContext.Controller.TempData[\"Message\"])) {\n filterContext.Controller.ViewBag.Message = filterContext.Controller.TempData[\"Message\"];\n }\n\n base.OnActionExecuted(filterContext);\n }\n}\n</code></pre>\n\n<p>I realize my changes here are a pretty obvious extension of what was already being done with the ModelState by the code @ the link provided by @bob - but I had to stumble on this thread before I even thought of handling it in this way.</p>\n"
},
{
"answer_id": 60775107,
"author": "Jess",
"author_id": 1804678,
"author_profile": "https://Stackoverflow.com/users/1804678",
"pm_score": 0,
"selected": false,
"text": "<p>Please don't skewer me for this answer. It is a legitimate suggestion.</p>\n\n<p><strong>Use AJAX</strong></p>\n\n<p>The code for managing ModelState is complicated and (probably?) indicative of other problems in your code.</p>\n\n<p>You can pretty easily roll your own AJAX javascript code. Here is a script I use:</p>\n\n<p><a href=\"https://gist.github.com/jesslilly/5f646ef29367ad2b0228e1fa76d6bdcc#file-ajaxform\" rel=\"nofollow noreferrer\">https://gist.github.com/jesslilly/5f646ef29367ad2b0228e1fa76d6bdcc#file-ajaxform</a></p>\n\n<pre><code>(function ($) {\n\n $(function () {\n\n // For forms marked with data-ajax=\"#container\",\n // on submit,\n // post the form data via AJAX\n // and if #container is specified, replace the #container with the response.\n var postAjaxForm = function (event) {\n\n event.preventDefault(); // Prevent the actual submit of the form.\n\n var $this = $(this);\n var containerId = $this.attr(\"data-ajax\");\n var $container = $(containerId);\n var url = $this.attr('action');\n\n console.log(\"Post ajax form to \" + url + \" and replace html in \" + containerId);\n\n $.ajax({\n type: \"POST\",\n url: url,\n data: $this.serialize()\n })\n .done(function (result) {\n if ($container) {\n $container.html(result);\n // re-apply this event since it would have been lost by the form getting recreated above.\n var $newForm = $container.find(\"[data-ajax]\");\n $newForm.submit(postAjaxForm);\n $newForm.trigger(\"data-ajax-done\");\n }\n })\n .fail(function (error) {\n alert(error);\n });\n };\n $(\"[data-ajax]\").submit(postAjaxForm);\n });\n\n})(jQuery);\n</code></pre>\n"
}
] |
2008/11/11
|
[
"https://Stackoverflow.com/questions/279665",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3957/"
] |
How can I return the result of a different action or move the user to a different action if there is an error in my `ModelState` without losing my `ModelState` information?
The scenario is; `Delete` action accepts a POST from a DELETE form rendered by my `Index` Action/View. If there is an error in the `Delete` I want to move the user back to the `Index` Action/View and show the errors that are stored by the `Delete` action in the `ViewData.ModelState`. How can this be done in ASP.NET MVC?
```
[AcceptVerbs(HttpVerbs.Post | HttpVerbs.Delete)]
public ActionResult Delete([ModelBinder(typeof(RdfUriBinder))] RdfUri graphUri)
{
if (!ModelState.IsValid)
return Index(); //this needs to be replaced with something that works :)
return RedirectToAction("Index");
}
```
|
Store your view data in `TempData` and retrieve it from there in your `Index` action, if it exists.
```
...
if (!ModelState.IsValid)
TempData["ViewData"] = ViewData;
RedirectToAction( "Index" );
}
public ActionResult Index()
{
if (TempData["ViewData"] != null)
{
ViewData = (ViewDataDictionary)TempData["ViewData"];
}
...
}
```
[EDIT] I checked the on-line source for MVC and it appears that the `ViewData` in the Controller is settable, so it is probably easiest just to transfer all of the `ViewData`, including the `ModelState`, to the Index action.
|
279,673 |
<p>I wonder if it's possible to save all files in a Visual Studio 2008 project into a specific character encoding. I got a solution with mixed encodings and I want to make them all the same (UTF-8 with signature).</p>
<p>I know how to save single files, but how about all files in a project?</p>
|
[
{
"answer_id": 279706,
"author": "MusiGenesis",
"author_id": 14606,
"author_profile": "https://Stackoverflow.com/users/14606",
"pm_score": -1,
"selected": false,
"text": "<p>I'm only offering this suggestion in case there's no way to automatically do this in Visual Studio (I'm not even sure this would work):</p>\n\n<ol>\n<li>Create a class in your project named <strong>足の不自由なハッキング</strong> (or some other unicode text that will force Visual Studio to encode as UTF-8).</li>\n<li>Add \"using MyProject.<strong>足の不自由なハッキング</strong>;\" to the top of each file. You should be able to do it on everything by doing a global replace of \"using System.Text;\" with \"using System.Text;using MyProject.<strong>足の不自由なハッキング</strong>;\".</li>\n<li>Save everything. You may get a long string of \"Do you want to save X.cs using UTF-8?\" messages or something.</li>\n</ol>\n"
},
{
"answer_id": 280325,
"author": "Martin v. Löwis",
"author_id": 33006,
"author_profile": "https://Stackoverflow.com/users/33006",
"pm_score": 3,
"selected": false,
"text": "<p>I would convert the files programmatically (outside VS), e.g. using a Python script:</p>\n\n<pre class=\"lang-py prettyprint-override\"><code>import glob, codecs\n\nfor f in glob.glob(\"*.py\"):\n data = open(\"f\", \"rb\").read()\n if data.startswith(codecs.BOM_UTF8):\n # Already UTF-8\n continue\n # else assume ANSI code page\n data = data.decode(\"mbcs\")\n data = codecs.BOM_UTF8 + data.encode(\"utf-8\")\n open(\"f\", \"wb\").write(data)\n</code></pre>\n\n<p>This assumes all files not in \"UTF-8 with signature\" are in the ANSI code page - this is the same what VS 2008 apparently also assumes. If you know that some files have yet different encodings, you would have to specify what these encodings are.</p>\n"
},
{
"answer_id": 850751,
"author": "Timwi",
"author_id": 33225,
"author_profile": "https://Stackoverflow.com/users/33225",
"pm_score": 7,
"selected": true,
"text": "<p>Since you're already in Visual Studio, why not just simply write the code?</p>\n\n<pre class=\"lang-cs prettyprint-override\"><code>foreach (var f in new DirectoryInfo(@\"...\").GetFiles(\"*.cs\", SearchOption.AllDirectories)) {\n string s = File.ReadAllText(f.FullName);\n File.WriteAllText (f.FullName, s, Encoding.UTF8);\n}\n</code></pre>\n\n<p>Only three lines of code! I'm sure you can write this in less than a minute :-)</p>\n"
},
{
"answer_id": 1326157,
"author": "rasx",
"author_id": 22944,
"author_profile": "https://Stackoverflow.com/users/22944",
"pm_score": 4,
"selected": false,
"text": "<p>In case you need to do this in PowerShell, here is my little move:</p>\n\n<pre><code>Function Write-Utf8([string] $path, [string] $filter='*.*')\n{\n [IO.SearchOption] $option = [IO.SearchOption]::AllDirectories;\n [String[]] $files = [IO.Directory]::GetFiles((Get-Item $path).FullName, $filter, $option);\n foreach($file in $files)\n {\n \"Writing $file...\";\n [String]$s = [IO.File]::ReadAllText($file);\n [IO.File]::WriteAllText($file, $s, [Text.Encoding]::UTF8);\n }\n}\n</code></pre>\n"
},
{
"answer_id": 2313200,
"author": "Ehsan",
"author_id": 278915,
"author_profile": "https://Stackoverflow.com/users/278915",
"pm_score": 1,
"selected": false,
"text": "<p>Thanks for your solutions, this code has worked for me : </p>\n\n<pre class=\"lang-vb prettyprint-override\"><code>Dim s As String = \"\"\nDim direc As DirectoryInfo = New DirectoryInfo(\"Your Directory path\")\n\nFor Each fi As FileInfo In direc.GetFiles(\"*.vb\", SearchOption.AllDirectories)\n s = File.ReadAllText(fi.FullName, System.Text.Encoding.Default)\n File.WriteAllText(fi.FullName, s, System.Text.Encoding.Unicode)\nNext\n</code></pre>\n"
},
{
"answer_id": 2633313,
"author": "Broam",
"author_id": 213880,
"author_profile": "https://Stackoverflow.com/users/213880",
"pm_score": 5,
"selected": false,
"text": "<p>This may be of some help.</p>\n\n<blockquote>\n <p>link removed due to original reference being defaced by spam site.</p>\n</blockquote>\n\n<p>Short version: edit one file, select File -> Advanced Save Options. Instead of changing UTF-8 to Ascii, change it to UTF-8. <em>Edit: Make sure you select the option that says no byte-order-marker (BOM)</em></p>\n\n<p>Set code page & hit ok. It seems to persist just past the current file.</p>\n"
},
{
"answer_id": 8799737,
"author": "podcast",
"author_id": 1140289,
"author_profile": "https://Stackoverflow.com/users/1140289",
"pm_score": 1,
"selected": false,
"text": "<p>I have created a function to change encoding files written in asp.net. \nI searched a lot. And I also used some ideas and codes from this page. Thank you.</p>\n\n<p>And here is the function.</p>\n\n<pre class=\"lang-vb prettyprint-override\"><code> Function ChangeFileEncoding(pPathFolder As String, pExtension As String, pDirOption As IO.SearchOption) As Integer\n\n Dim Counter As Integer\n Dim s As String\n Dim reader As IO.StreamReader\n Dim gEnc As Text.Encoding\n Dim direc As IO.DirectoryInfo = New IO.DirectoryInfo(pPathFolder)\n For Each fi As IO.FileInfo In direc.GetFiles(pExtension, pDirOption)\n s = \"\"\n reader = New IO.StreamReader(fi.FullName, Text.Encoding.Default, True)\n s = reader.ReadToEnd\n gEnc = reader.CurrentEncoding\n reader.Close()\n\n If (gEnc.EncodingName <> Text.Encoding.UTF8.EncodingName) Then\n s = IO.File.ReadAllText(fi.FullName, gEnc)\n IO.File.WriteAllText(fi.FullName, s, System.Text.Encoding.UTF8)\n Counter += 1\n Response.Write(\"<br>Saved #\" & Counter & \": \" & fi.FullName & \" - <i>Encoding was: \" & gEnc.EncodingName & \"</i>\")\n End If\n Next\n\n Return Counter\nEnd Function\n</code></pre>\n\n<p>It can placed in .aspx file and then called like:</p>\n\n<pre><code>ChangeFileEncoding(\"C:\\temp\\test\", \"*.ascx\", IO.SearchOption.TopDirectoryOnly)\n</code></pre>\n"
},
{
"answer_id": 18206763,
"author": "Mase",
"author_id": 2678184,
"author_profile": "https://Stackoverflow.com/users/2678184",
"pm_score": 1,
"selected": false,
"text": "<p>if you are using TFS with VS :\n<a href=\"http://msdn.microsoft.com/en-us/library/1yft8zkw(v=vs.100).aspx\" rel=\"nofollow\">http://msdn.microsoft.com/en-us/library/1yft8zkw(v=vs.100).aspx</a>\nExample : </p>\n\n<pre><code>tf checkout -r -type:utf-8 src/*.aspx\n</code></pre>\n"
},
{
"answer_id": 29138903,
"author": "Bruce",
"author_id": 1745885,
"author_profile": "https://Stackoverflow.com/users/1745885",
"pm_score": 3,
"selected": false,
"text": "<p>Using C#:<br>\n1) Create a new ConsoleApplication, then install <a href=\"https://nuget.org/packages/UDE.CSharp\" rel=\"nofollow\">Mozilla Universal Charset Detector</a><br>\n2) Run code:</p>\n\n<pre class=\"lang-cs prettyprint-override\"><code>static void Main(string[] args)\n{\n const string targetEncoding = \"utf-8\";\n foreach (var f in new DirectoryInfo(@\"<your project's path>\").GetFiles(\"*.cs\", SearchOption.AllDirectories))\n {\n var fileEnc = GetEncoding(f.FullName);\n if (fileEnc != null && !string.Equals(fileEnc, targetEncoding, StringComparison.OrdinalIgnoreCase))\n {\n var str = File.ReadAllText(f.FullName, Encoding.GetEncoding(fileEnc));\n File.WriteAllText(f.FullName, str, Encoding.GetEncoding(targetEncoding));\n }\n }\n Console.WriteLine(\"Done.\");\n Console.ReadKey();\n}\n\nprivate static string GetEncoding(string filename)\n{\n using (var fs = File.OpenRead(filename))\n {\n var cdet = new Ude.CharsetDetector();\n cdet.Feed(fs);\n cdet.DataEnd();\n if (cdet.Charset != null)\n Console.WriteLine(\"Charset: {0}, confidence: {1} : \" + filename, cdet.Charset, cdet.Confidence);\n else\n Console.WriteLine(\"Detection failed: \" + filename);\n return cdet.Charset;\n }\n}\n</code></pre>\n"
},
{
"answer_id": 32265184,
"author": "Janis Rudovskis",
"author_id": 1503576,
"author_profile": "https://Stackoverflow.com/users/1503576",
"pm_score": 0,
"selected": false,
"text": "<p>Experienced encoding problems after converting solution from VS2008 to VS2015. After conversion all project files was encoded in ANSI, but they contained UTF8 content and was recongnized as ANSI files in VS2015. Tried many conversion tactics, but worked only this solution.</p>\n\n<pre class=\"lang-cs prettyprint-override\"><code> Encoding encoding = Encoding.Default;\n String original = String.Empty;\n foreach (var f in new DirectoryInfo(path).GetFiles(\"*.cs\", SearchOption.AllDirectories))\n {\n using (StreamReader sr = new StreamReader(f.FullName, Encoding.Default))\n {\n original = sr.ReadToEnd();\n encoding = sr.CurrentEncoding;\n sr.Close();\n }\n if (encoding == Encoding.UTF8)\n continue;\n byte[] encBytes = encoding.GetBytes(original);\n byte[] utf8Bytes = Encoding.Convert(encoding, Encoding.UTF8, encBytes);\n var utf8Text = Encoding.UTF8.GetString(utf8Bytes);\n\n File.WriteAllText(f.FullName, utf8Text, Encoding.UTF8);\n }\n</code></pre>\n"
},
{
"answer_id": 42143222,
"author": "Maxime Esprit",
"author_id": 4965913,
"author_profile": "https://Stackoverflow.com/users/4965913",
"pm_score": 1,
"selected": false,
"text": "<p>If you want to avoid this type of error :</p>\n\n<p><a href=\"https://i.stack.imgur.com/NQmtD.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/NQmtD.png\" alt=\"enter image description here\"></a></p>\n\n<p>Use this following code :</p>\n\n<pre><code>foreach (var f in new DirectoryInfo(@\"....\").GetFiles(\"*.cs\", SearchOption.AllDirectories))\n {\n string s = File.ReadAllText(f.FullName, Encoding.GetEncoding(1252));\n File.WriteAllText(f.FullName, s, Encoding.UTF8);\n }\n</code></pre>\n\n<p>Encoding number 1252 is the default Windows encoding used by Visual Studio to save your files.</p>\n"
},
{
"answer_id": 53769947,
"author": "Yitzhak Weinberg",
"author_id": 4871015,
"author_profile": "https://Stackoverflow.com/users/4871015",
"pm_score": 0,
"selected": false,
"text": "<p>the item is removed from the menu in Visual Studio 2017\nYou can still access the functionality through File-> Save As -> then clicking the down arrow on the Save button and clicking \"Save With Encoding...\".</p>\n\n<p>You can also add it back to the File menu through Tools->Customize->Commands if you want to.</p>\n"
},
{
"answer_id": 58287056,
"author": "Bruno Zell",
"author_id": 5185376,
"author_profile": "https://Stackoverflow.com/users/5185376",
"pm_score": 1,
"selected": false,
"text": "<h1>Convert from UTF-8-BOM to UTF-8</h1>\n\n<p>Building on <a href=\"https://stackoverflow.com/a/1326157/5185376\">rasx's answer</a>, here is a PowerShell function that assumes your current files are already encoded in UTF-8 (but maybe with BOM) and converts them to UTF-8 without BOM, therefore preserving existing Unicode characters.</p>\n\n<pre><code>Function Write-Utf8([string] $path, [string] $filter='*')\n{\n [IO.SearchOption] $option = [IO.SearchOption]::AllDirectories;\n [String[]] $files = [IO.Directory]::GetFiles((Get-Item $path).FullName, $filter, $option);\n foreach($file in $files)\n {\n \"Writing $file...\";\n [String]$s = [IO.File]::ReadAllText($file, [Text.Encoding]::UTF8);\n [Text.Encoding]$e = New-Object -TypeName Text.UTF8Encoding -ArgumentList ($false);\n [IO.File]::WriteAllText($file, $s, $e);\n }\n}\n</code></pre>\n"
}
] |
2008/11/11
|
[
"https://Stackoverflow.com/questions/279673",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/33349/"
] |
I wonder if it's possible to save all files in a Visual Studio 2008 project into a specific character encoding. I got a solution with mixed encodings and I want to make them all the same (UTF-8 with signature).
I know how to save single files, but how about all files in a project?
|
Since you're already in Visual Studio, why not just simply write the code?
```cs
foreach (var f in new DirectoryInfo(@"...").GetFiles("*.cs", SearchOption.AllDirectories)) {
string s = File.ReadAllText(f.FullName);
File.WriteAllText (f.FullName, s, Encoding.UTF8);
}
```
Only three lines of code! I'm sure you can write this in less than a minute :-)
|
279,696 |
<p>Still struggling to understand what best practices are with respect to macros. I'm attempting to write a macro which defines packages on the fly.</p>
<pre><code>(defmacro def-dynamic-package (name)
`(defpackage ,(intern (string-upcase name) "KEYWORD")
(:use :common-lisp)))
</code></pre>
<p>This works fine only for expressions such as:</p>
<pre><code>(def-dynamic-package "helloworld")
</code></pre>
<p>But fails miserably for something like this:</p>
<pre><code>(defun make-package-from-path (path)
(def-dynamic-package (pathname-name path)))
</code></pre>
<p>or</p>
<pre><code>(defun make-package-from-path (path)
(let ((filename (pathname-path)))
(def-dynamic-package filename)))
</code></pre>
<p>I understand how most basic macros work but how to implement this one escapes me.</p>
|
[
{
"answer_id": 279725,
"author": "Nowhere man",
"author_id": 400277,
"author_profile": "https://Stackoverflow.com/users/400277",
"pm_score": 0,
"selected": false,
"text": "<p>Failure is to be expected here, because a macro is used when its argument should not be evaluated.</p>\n\n<p>In your first make-package-from-path, the def-dynamic-package will receive as argument a list that is EQUAL to the value of the following expression:</p>\n\n<pre><code>(list 'pathname-name 'path)\n</code></pre>\n\n<p>In your case, you only want a function:</p>\n\n<pre><code>(defun def-dynamic-package (name)\n (defpackage (string-upcase name)\n (:use :common-lisp)))\n</code></pre>\n\n<p>BTW, if you check the <a href=\"http://www.lispworks.com/documentation/HyperSpec/Front/index.htm\" rel=\"nofollow noreferrer\">CLHS</a>, you'll see that the first argument of <a href=\"http://www.lispworks.com/documentation/HyperSpec/Body/m_defpkg.htm\" rel=\"nofollow noreferrer\">defpackage</a> needn't be a symbol, but any <a href=\"http://www.lispworks.com/documentation/HyperSpec/Body/26_glo_s.htm#string_designator\" rel=\"nofollow noreferrer\">string designator</a>.</p>\n"
},
{
"answer_id": 280299,
"author": "Matthias Benkard",
"author_id": 15517,
"author_profile": "https://Stackoverflow.com/users/15517",
"pm_score": 4,
"selected": true,
"text": "<p><strong>defpackage</strong> is a macro. As such, it's expanded at compile-time, not run-time. What you want is something that is called at run-time in order to make a new package. Therefore, <strong>defpackage</strong> can't do anything for you.</p>\n\n<p>Fortunately, there's also <strong><a href=\"http://www.lispworks.com/documentation/HyperSpec/Body/f_mk_pkg.htm#make-package\" rel=\"noreferrer\">make-package</a></strong>, which provides <strong>defpackage</strong>'s features as a function. Use it instead of <strong>defpackage</strong>.</p>\n"
}
] |
2008/11/11
|
[
"https://Stackoverflow.com/questions/279696",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/32797/"
] |
Still struggling to understand what best practices are with respect to macros. I'm attempting to write a macro which defines packages on the fly.
```
(defmacro def-dynamic-package (name)
`(defpackage ,(intern (string-upcase name) "KEYWORD")
(:use :common-lisp)))
```
This works fine only for expressions such as:
```
(def-dynamic-package "helloworld")
```
But fails miserably for something like this:
```
(defun make-package-from-path (path)
(def-dynamic-package (pathname-name path)))
```
or
```
(defun make-package-from-path (path)
(let ((filename (pathname-path)))
(def-dynamic-package filename)))
```
I understand how most basic macros work but how to implement this one escapes me.
|
**defpackage** is a macro. As such, it's expanded at compile-time, not run-time. What you want is something that is called at run-time in order to make a new package. Therefore, **defpackage** can't do anything for you.
Fortunately, there's also **[make-package](http://www.lispworks.com/documentation/HyperSpec/Body/f_mk_pkg.htm#make-package)**, which provides **defpackage**'s features as a function. Use it instead of **defpackage**.
|
279,701 |
<p>I'm trying to get a handle on if there's a good time to use standard linq keywords or linq extension methods with lambda expressions. They seems to do the same thing, just are written differently. Is it purely a matter of style?</p>
<pre><code>var query = from p in Products
where p.Name.Contains("foo")
orderby c.Name
select p;
// or with extension methods:
var query = Products
.Where(p => p.Name.Contains("foo"))
.OrderBy(p => p.Name);
</code></pre>
<p>They're very similar with the second example being a bit more terse, but perhaps less expressive if you don't know what the => is doing.</p>
<p><strong>Other than writing terse code, are there other advantages to using the extension methods as opposed to the LINQ syntax?</strong></p>
|
[
{
"answer_id": 279719,
"author": "Mark Brackett",
"author_id": 2199,
"author_profile": "https://Stackoverflow.com/users/2199",
"pm_score": 3,
"selected": false,
"text": "<p>They compile the same, and are equivalent. Personally, I prefer the lambda (extension) methods for most things, only using the statements (standard) if I'm doing LINQ to SQL or otherwise trying to emulate SQL. I find that the lambda methods flow better with code, whereas the statements are visually distracting.</p>\n"
},
{
"answer_id": 279738,
"author": "Nathan W",
"author_id": 6335,
"author_profile": "https://Stackoverflow.com/users/6335",
"pm_score": 5,
"selected": false,
"text": "<p>One advantage to using LINQ extension methods (<em>method-based queries</em>) is that you can define custom extension methods and it will still read fine.</p>\n\n<p>On the other hand, when using a LINQ <em>query expression</em>, the custom extension method is not in the keywords list. It will look a bit strange mixed with the other keywords. </p>\n\n<h1>Example</h1>\n\n<p>I am using a custom extension method called <code>Into</code> which just takes a string:</p>\n\n<h2>Example with query</h2>\n\n<pre><code>var query = (from p in Products\n where p.Name.Contains(\"foo\")\n orderby c.Name\n select p).Into(\"MyTable\");\n</code></pre>\n\n<h2>Example with extension methods</h2>\n\n<pre><code>var query = Products\n .Where(p => p.Name.Contains(\"foo\"))\n .OrderBy(p => p.Name)\n .Into(\"MyTable\");\n</code></pre>\n\n<p>In my opinion the latter, using a <em>method-based query</em>, reads better when you have custom extension methods.</p>\n"
},
{
"answer_id": 284099,
"author": "Eric Minkes",
"author_id": 1172,
"author_profile": "https://Stackoverflow.com/users/1172",
"pm_score": 2,
"selected": false,
"text": "<p>I prefer the extension method syntax when I use Linq methods that have no query syntax equivalent, such as FirstOrDefault() or others like that.</p>\n"
},
{
"answer_id": 284313,
"author": "Programmin Tool",
"author_id": 21691,
"author_profile": "https://Stackoverflow.com/users/21691",
"pm_score": 6,
"selected": true,
"text": "<p>Honestly, sometimes it can be situational once you start using Funcs and Actions. Say you are using these three funcs:</p>\n\n<pre><code> Func<DataClasses.User, String> userName = user => user.UserName;\n Func<DataClasses.User, Boolean> userIDOverTen = user => user.UserID < 10;\n Func<DataClasses.User, Boolean> userIDUnderTen = user => user.UserID > 10;\n</code></pre>\n\n<p>As you can see the first one replaces the lamdba expression to get the user name, the second replaces a lamdba expression used to check if the ID is lower than 10, and let's face it, the third should be pretty easy to understand now.</p>\n\n<p>NOTE: This is a silly example but it works.</p>\n\n<pre><code> var userList = \n from user in userList\n where userIDOverTen(user)\n select userName;\n</code></pre>\n\n<p>Versus</p>\n\n<pre><code> var otherList =\n userList\n .Where(IDIsBelowNumber)\n .Select(userName)\n</code></pre>\n\n<p>In this example, the second is a little less verbose since the extension method can make full use of the Func, but he Linq expression can't since it is look just for a Boolean rather than a Func that returns boolean. However, this is where it might be better to use the expression language. Say you already had a method that takes in more than just a user:</p>\n\n<pre><code> private Boolean IDIsBelowNumber(DataClasses.User user, \n Int32 someNumber, Boolean doSomething)\n {\n return user.UserID < someNumber;\n }\n</code></pre>\n\n<p>Note: doSomething is just there because of the where extension method being ok with a method that takes in a user and integer and returns boolean. Kind of annoying for this example.</p>\n\n<p>Now if you look at the Linq query:</p>\n\n<pre><code> var completeList =\n from user in userList\n where IDIsBelowNumber(user, 10, true)\n select userName;\n</code></pre>\n\n<p>You're good for it. Now the Extension Method:</p>\n\n<pre><code> var otherList =\n userList\n .Where(IDIsBelowNumber????)\n .Select(userName)\n</code></pre>\n\n<p>Without a lambda expression, I really can't call that method. So now what I have to do is create a method that creates a Func based off the original method call.</p>\n\n<pre><code> private Func<DataClasses.User, Boolean> IDIsBelowNumberFunc(Int32 number)\n {\n return user => IDIsBelowNumber(user, number, true);\n }\n</code></pre>\n\n<p>And then plug it in:</p>\n\n<pre><code> var otherList =\n userList\n .Where(IDIsBelowNumberFunc(10))\n .Select(userName)\n</code></pre>\n\n<p>So you can see, sometimes it may just be easier to use the query approach at times.</p>\n"
},
{
"answer_id": 4322017,
"author": "Rodi",
"author_id": 526176,
"author_profile": "https://Stackoverflow.com/users/526176",
"pm_score": 4,
"selected": false,
"text": "<p>I think it's a good idea not to use them together and choose one and stick with it.</p>\n\n<p>Mostly it's personal taste, but in the query syntax (Comprehension method) not all operators are available as was said before.</p>\n\n<p>I find the Extension Methods syntax more in line with the rest of my code. I do my SQL in SQL. It's also very easy to build your expression just by adding everything on top of eachother with the extension methods.</p>\n\n<p>Just my two cents.</p>\n\n<p>As I cannot make comments yet I want to make one here to the answer of Programming Tool:\nWhy make a whole new method for the last example?? Can't you just use:</p>\n\n<p><code>\n.Where(user => IDIsBelowNumber(user, 10, true))\n</code></p>\n"
},
{
"answer_id": 22231539,
"author": "nawfal",
"author_id": 661933,
"author_profile": "https://Stackoverflow.com/users/661933",
"pm_score": -1,
"selected": false,
"text": "<p>I like to use the query syntax when its really a query, ie a lazy expression which evaluates on demand. </p>\n\n<p>A method that looks like regular method calls (method syntax or the lambda syntax) doesn't look lazy enough, so I use that as a convention. For eg,</p>\n\n<pre><code>var query = from p in Products\n where p.Name.Contains(\"foo\")\n orderby p.Name\n select p;\n\nvar result = query.ToList(); //extension method syntax\n</code></pre>\n\n<p>If it's a not a query, I like the fluent style which looks to me consistent with other eagerly executing calls.</p>\n\n<pre><code>var nonQuery = Products.Where(p => p.Name.Contains(\"foo\"))\n .OrderBy(p => p.Name)\n .ToList();\n</code></pre>\n\n<p>It helps me to differentiate the two styles of calls better. Of course there are situations where you will be forced to use method syntax anyway, so my convention is not very compelling enough. </p>\n"
},
{
"answer_id": 48172712,
"author": "bradley4",
"author_id": 770061,
"author_profile": "https://Stackoverflow.com/users/770061",
"pm_score": -1,
"selected": false,
"text": "<p>One advantage of extension methods/lynda expressions is the additional operators that is offered like Skip and Take. For example, if you are creating a pagination method, being able to skip the first 10 records and take the next 10 is easy to implement. </p>\n"
}
] |
2008/11/11
|
[
"https://Stackoverflow.com/questions/279701",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/26931/"
] |
I'm trying to get a handle on if there's a good time to use standard linq keywords or linq extension methods with lambda expressions. They seems to do the same thing, just are written differently. Is it purely a matter of style?
```
var query = from p in Products
where p.Name.Contains("foo")
orderby c.Name
select p;
// or with extension methods:
var query = Products
.Where(p => p.Name.Contains("foo"))
.OrderBy(p => p.Name);
```
They're very similar with the second example being a bit more terse, but perhaps less expressive if you don't know what the => is doing.
**Other than writing terse code, are there other advantages to using the extension methods as opposed to the LINQ syntax?**
|
Honestly, sometimes it can be situational once you start using Funcs and Actions. Say you are using these three funcs:
```
Func<DataClasses.User, String> userName = user => user.UserName;
Func<DataClasses.User, Boolean> userIDOverTen = user => user.UserID < 10;
Func<DataClasses.User, Boolean> userIDUnderTen = user => user.UserID > 10;
```
As you can see the first one replaces the lamdba expression to get the user name, the second replaces a lamdba expression used to check if the ID is lower than 10, and let's face it, the third should be pretty easy to understand now.
NOTE: This is a silly example but it works.
```
var userList =
from user in userList
where userIDOverTen(user)
select userName;
```
Versus
```
var otherList =
userList
.Where(IDIsBelowNumber)
.Select(userName)
```
In this example, the second is a little less verbose since the extension method can make full use of the Func, but he Linq expression can't since it is look just for a Boolean rather than a Func that returns boolean. However, this is where it might be better to use the expression language. Say you already had a method that takes in more than just a user:
```
private Boolean IDIsBelowNumber(DataClasses.User user,
Int32 someNumber, Boolean doSomething)
{
return user.UserID < someNumber;
}
```
Note: doSomething is just there because of the where extension method being ok with a method that takes in a user and integer and returns boolean. Kind of annoying for this example.
Now if you look at the Linq query:
```
var completeList =
from user in userList
where IDIsBelowNumber(user, 10, true)
select userName;
```
You're good for it. Now the Extension Method:
```
var otherList =
userList
.Where(IDIsBelowNumber????)
.Select(userName)
```
Without a lambda expression, I really can't call that method. So now what I have to do is create a method that creates a Func based off the original method call.
```
private Func<DataClasses.User, Boolean> IDIsBelowNumberFunc(Int32 number)
{
return user => IDIsBelowNumber(user, number, true);
}
```
And then plug it in:
```
var otherList =
userList
.Where(IDIsBelowNumberFunc(10))
.Select(userName)
```
So you can see, sometimes it may just be easier to use the query approach at times.
|
279,729 |
<p>I am forking a number of processes and I want to measure how long it takes to complete the whole task, that is when all processes forked are completed. Please advise how to make the parent process wait until all child processes are terminated? I want to make sure that I stop the timer at the right moment.</p>
<p>Here is as a code I use:</p>
<pre><code>#include <iostream>
#include <string>
#include <fstream>
#include <sys/time.h>
#include <sys/wait.h>
using namespace std;
struct timeval first, second, lapsed;
struct timezone tzp;
int main(int argc, char* argv[])// query, file, num. of processes.
{
int pCount = 5; // process count
gettimeofday (&first, &tzp); //start time
pid_t* pID = new pid_t[pCount];
for(int indexOfProcess=0; indexOfProcess<pCount; indexOfProcess++)
{
pID[indexOfProcess]= fork();
if (pID[indexOfProcess] == 0) // child
{
// code only executed by child process
// magic here
// The End
exit(0);
}
else if (pID[indexOfProcess] < 0) // failed to fork
{
cerr << "Failed to fork" << endl;
exit(1);
}
else // parent
{
// if(indexOfProcess==pCount-1) and a loop with waitpid??
gettimeofday (&second, &tzp); //stop time
if (first.tv_usec > second.tv_usec)
{
second.tv_usec += 1000000;
second.tv_sec--;
}
lapsed.tv_usec = second.tv_usec - first.tv_usec;
lapsed.tv_sec = second.tv_sec - first.tv_sec;
cout << "Job performed in " <<lapsed.tv_sec << " sec and " << lapsed.tv_usec << " usec"<< endl << endl;
}
}//for
}//main
</code></pre>
|
[
{
"answer_id": 279736,
"author": "SoapBox",
"author_id": 36384,
"author_profile": "https://Stackoverflow.com/users/36384",
"pm_score": 2,
"selected": false,
"text": "<p>I believe the <a href=\"http://linux.die.net/man/2/wait\" rel=\"nofollow noreferrer\">wait system call</a> will accomplish what you are looking for.</p>\n"
},
{
"answer_id": 279739,
"author": "Chris Morley",
"author_id": 36034,
"author_profile": "https://Stackoverflow.com/users/36034",
"pm_score": 2,
"selected": false,
"text": "<p>Call wait (or waitpid) in a loop until all children are accounted for.</p>\n\n<p>In this case, all processes are synchronizing anyway, but in general wait is preferred when more work can be done (eg worker process pool), since it will return when the first available process state changes.</p>\n"
},
{
"answer_id": 279744,
"author": "gnud",
"author_id": 27204,
"author_profile": "https://Stackoverflow.com/users/27204",
"pm_score": 4,
"selected": false,
"text": "<p>The simplest method is to do</p>\n\n<pre><code>while(wait() > 0) { /* no-op */ ; }\n</code></pre>\n\n<p>This will not work if <code>wait()</code> fails for some reason other than the fact that there are no children left. So with some error checking, this becomes</p>\n\n<pre><code>int status;\n[...]\ndo {\n status = wait();\n if(status == -1 && errno != ECHILD) {\n perror(\"Error during wait()\");\n abort();\n }\n} while (status > 0);\n</code></pre>\n\n<p>See also the manual page <code>wait(2)</code>.</p>\n"
},
{
"answer_id": 279745,
"author": "BCS",
"author_id": 1343,
"author_profile": "https://Stackoverflow.com/users/1343",
"pm_score": 0,
"selected": false,
"text": "<pre><code>for (int i = 0; i < pidCount; i++) {\n while (waitpid(pids[i], NULL, 0) > 0);\n}\n</code></pre>\n\n<p>It won't wait in the right order, but it will stop shortly after the last child dies.</p>\n"
},
{
"answer_id": 279761,
"author": "Steve Jessop",
"author_id": 13005,
"author_profile": "https://Stackoverflow.com/users/13005",
"pm_score": 6,
"selected": true,
"text": "<p>I'd move everything after the line \"else //parent\" down, outside the for loop. After the loop of forks, do another for loop with waitpid, then stop the clock and do the rest:</p>\n\n<pre><code>for (int i = 0; i < pidCount; ++i) {\n int status;\n while (-1 == waitpid(pids[i], &status, 0));\n if (!WIFEXITED(status) || WEXITSTATUS(status) != 0) {\n cerr << \"Process \" << i << \" (pid \" << pids[i] << \") failed\" << endl;\n exit(1);\n }\n}\n\ngettimeofday (&second, &tzp); //stop time\n</code></pre>\n\n<p>I've assumed that if the child process fails to exit normally with a status of 0, then it didn't complete its work, and therefore the test has failed to produce valid timing data. Obviously if the child processes are <em>supposed</em> to be killed by signals, or exit non-0 return statuses, then you'll have to change the error check accordingly.</p>\n\n<p>An alternative using wait:</p>\n\n<pre><code>while (true) {\n int status;\n pid_t done = wait(&status);\n if (done == -1) {\n if (errno == ECHILD) break; // no more child processes\n } else {\n if (!WIFEXITED(status) || WEXITSTATUS(status) != 0) {\n cerr << \"pid \" << done << \" failed\" << endl;\n exit(1);\n }\n }\n}\n</code></pre>\n\n<p>This one doesn't tell you which process in sequence failed, but if you care then you can add code to look it up in the pids array and get back the index.</p>\n"
}
] |
2008/11/11
|
[
"https://Stackoverflow.com/questions/279729",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3515/"
] |
I am forking a number of processes and I want to measure how long it takes to complete the whole task, that is when all processes forked are completed. Please advise how to make the parent process wait until all child processes are terminated? I want to make sure that I stop the timer at the right moment.
Here is as a code I use:
```
#include <iostream>
#include <string>
#include <fstream>
#include <sys/time.h>
#include <sys/wait.h>
using namespace std;
struct timeval first, second, lapsed;
struct timezone tzp;
int main(int argc, char* argv[])// query, file, num. of processes.
{
int pCount = 5; // process count
gettimeofday (&first, &tzp); //start time
pid_t* pID = new pid_t[pCount];
for(int indexOfProcess=0; indexOfProcess<pCount; indexOfProcess++)
{
pID[indexOfProcess]= fork();
if (pID[indexOfProcess] == 0) // child
{
// code only executed by child process
// magic here
// The End
exit(0);
}
else if (pID[indexOfProcess] < 0) // failed to fork
{
cerr << "Failed to fork" << endl;
exit(1);
}
else // parent
{
// if(indexOfProcess==pCount-1) and a loop with waitpid??
gettimeofday (&second, &tzp); //stop time
if (first.tv_usec > second.tv_usec)
{
second.tv_usec += 1000000;
second.tv_sec--;
}
lapsed.tv_usec = second.tv_usec - first.tv_usec;
lapsed.tv_sec = second.tv_sec - first.tv_sec;
cout << "Job performed in " <<lapsed.tv_sec << " sec and " << lapsed.tv_usec << " usec"<< endl << endl;
}
}//for
}//main
```
|
I'd move everything after the line "else //parent" down, outside the for loop. After the loop of forks, do another for loop with waitpid, then stop the clock and do the rest:
```
for (int i = 0; i < pidCount; ++i) {
int status;
while (-1 == waitpid(pids[i], &status, 0));
if (!WIFEXITED(status) || WEXITSTATUS(status) != 0) {
cerr << "Process " << i << " (pid " << pids[i] << ") failed" << endl;
exit(1);
}
}
gettimeofday (&second, &tzp); //stop time
```
I've assumed that if the child process fails to exit normally with a status of 0, then it didn't complete its work, and therefore the test has failed to produce valid timing data. Obviously if the child processes are *supposed* to be killed by signals, or exit non-0 return statuses, then you'll have to change the error check accordingly.
An alternative using wait:
```
while (true) {
int status;
pid_t done = wait(&status);
if (done == -1) {
if (errno == ECHILD) break; // no more child processes
} else {
if (!WIFEXITED(status) || WEXITSTATUS(status) != 0) {
cerr << "pid " << done << " failed" << endl;
exit(1);
}
}
}
```
This one doesn't tell you which process in sequence failed, but if you care then you can add code to look it up in the pids array and get back the index.
|
279,748 |
<p>I have some code like this:</p>
<pre><code>[AcceptVerbs(HttpVerbs.Post)]
public ActionResult Save([Bind(Prefix="")]Person person)
{
String s = person.property;
/* ... */
}
</code></pre>
<p>But it throws the error: "Cannot use local variable 'person' before it is declared".</p>
<p>What simple thing am I missing?</p>
|
[
{
"answer_id": 279829,
"author": "Matt Mitchell",
"author_id": 364,
"author_profile": "https://Stackoverflow.com/users/364",
"pm_score": 3,
"selected": true,
"text": "<p>Okay, this is just some really bizarre error - if the variable is named a particular name it does not work, for any other name it does work...</p>\n"
},
{
"answer_id": 438961,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 4,
"selected": false,
"text": "<p>It is most likely that you are receiving this error because the same variable is being declared later in the same code block. </p>\n\n<p>According to compiler rules, a variable reference will refer to default by a matching declaration withing the same block EVEN IF THE SAME DECLARATION EXISTS OUTSIDE OF THE BLOCK IN IN LOGICAL SCOPE FLOW.</p>\n\n<p>So in short, check to see if the variable isnt being declared later on(a couple of lines down) in the same application block.</p>\n"
},
{
"answer_id": 18253246,
"author": "Frankie Lee",
"author_id": 2685909,
"author_profile": "https://Stackoverflow.com/users/2685909",
"pm_score": 2,
"selected": false,
"text": "<p>I had the same problem with a declared variable named endingYear.</p>\n\n<p>Declared here:</p>\n\n<pre><code> public ChartData(MetricInfo metricInfo, MetricItem[] metricItems) : this()\n {\n int endingYear = 0;\n</code></pre>\n\n<p>Further along in the method this was not a problem:</p>\n\n<pre><code> endingYear = endingDate.Year;\n</code></pre>\n\n<p>But when I referenced the very same varable in a Case statement I got the \"Cannot use local variable before it is declared\" error even thou the variable was in intelesense:</p>\n\n<pre><code> case \"QRTR_LAST_FULL_QRTR\":\n if (metricInfo.CalendarType == \"CALENDAR\")\n {\n switch (endingDate.Month)\n {\n case 1:\n case 2:\n case 3:\n loopControl = 4;\n endingYear = endingDate.Year - 1;\n</code></pre>\n\n<p>Based on Matt's result I tried changing the variable name to endYear and the problem went away. Very strange and a waste of a half hour or so. If it was not for this thread of posts it probably would have been a bigger time loss.</p>\n"
}
] |
2008/11/11
|
[
"https://Stackoverflow.com/questions/279748",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/364/"
] |
I have some code like this:
```
[AcceptVerbs(HttpVerbs.Post)]
public ActionResult Save([Bind(Prefix="")]Person person)
{
String s = person.property;
/* ... */
}
```
But it throws the error: "Cannot use local variable 'person' before it is declared".
What simple thing am I missing?
|
Okay, this is just some really bizarre error - if the variable is named a particular name it does not work, for any other name it does work...
|
279,769 |
<p>How do you convert between a DateTime and a Time object in Ruby?</p>
|
[
{
"answer_id": 279785,
"author": "Gordon Wilson",
"author_id": 23071,
"author_profile": "https://Stackoverflow.com/users/23071",
"pm_score": 7,
"selected": true,
"text": "<p>You'll need two slightly different conversions.</p>\n\n<p>To convert from <code> Time </code> to <code> DateTime</code> you can amend the Time class as follows:</p>\n\n<pre><code>require 'date'\nclass Time\n def to_datetime\n # Convert seconds + microseconds into a fractional number of seconds\n seconds = sec + Rational(usec, 10**6)\n\n # Convert a UTC offset measured in minutes to one measured in a\n # fraction of a day.\n offset = Rational(utc_offset, 60 * 60 * 24)\n DateTime.new(year, month, day, hour, min, seconds, offset)\n end\nend\n</code></pre>\n\n<p>Similar adjustments to Date will let you convert <code> DateTime </code> to <code> Time </code>.</p>\n\n<pre><code>class Date\n def to_gm_time\n to_time(new_offset, :gm)\n end\n\n def to_local_time\n to_time(new_offset(DateTime.now.offset-offset), :local)\n end\n\n private\n def to_time(dest, method)\n #Convert a fraction of a day to a number of microseconds\n usec = (dest.sec_fraction * 60 * 60 * 24 * (10**6)).to_i\n Time.send(method, dest.year, dest.month, dest.day, dest.hour, dest.min,\n dest.sec, usec)\n end\nend\n</code></pre>\n\n<p>Note that you have to choose between local time and GM/UTC time.</p>\n\n<p>Both the above code snippets are taken from O'Reilly's <a href=\"http://safari.oreilly.com/0596523696\" rel=\"noreferrer\">Ruby Cookbook</a>. Their code reuse <a href=\"http://oreilly.com/pub/a/oreilly/ask_tim/2001/codepolicy.html\" rel=\"noreferrer\">policy</a> permits this.</p>\n"
},
{
"answer_id": 280464,
"author": "anshul",
"author_id": 17674,
"author_profile": "https://Stackoverflow.com/users/17674",
"pm_score": 8,
"selected": false,
"text": "<pre><code>require 'time'\nrequire 'date'\n\nt = Time.now\nd = DateTime.now\n\ndd = DateTime.parse(t.to_s)\ntt = Time.parse(d.to_s)\n</code></pre>\n"
},
{
"answer_id": 3513247,
"author": "Bernard",
"author_id": 1556338,
"author_profile": "https://Stackoverflow.com/users/1556338",
"pm_score": 4,
"selected": false,
"text": "<p>Unfortunately, the <code>DateTime.to_time, Time.to_datetime</code> and <code>Time.parse</code> functions don't retain the timezone info. Everything is converted to local timezone during conversion. Date arithmetics still work but you won't be able to display the dates with their original timezones. That context information is often important. For example, if I want to see transactions performed during business hours in New York I probably prefer to see them displayed in their original timezones, not my local timezone in Australia (which 12 hrs ahead of New York).</p>\n\n<p>The conversion methods below do keep that tz info.</p>\n\n<p>For Ruby 1.8, look at <a href=\"https://stackoverflow.com/questions/279769/convert-to-from-datetime-and-time-in-ruby/279785#279785\">Gordon Wilson's answer</a>. It's from the good old reliable Ruby Cookbook.</p>\n\n<p>For Ruby 1.9, it's slightly easier.</p>\n\n<pre><code>require 'date'\n\n# Create a date in some foreign time zone (middle of the Atlantic)\nd = DateTime.new(2010,01,01, 10,00,00, Rational(-2, 24))\nputs d\n\n# Convert DateTime to Time, keeping the original timezone\nt = Time.new(d.year, d.month, d.day, d.hour, d.min, d.sec, d.zone)\nputs t\n\n# Convert Time to DateTime, keeping the original timezone\nd = DateTime.new(t.year, t.month, t.day, t.hour, t.min, t.sec, Rational(t.gmt_offset / 3600, 24))\nputs d\n</code></pre>\n\n<p>This prints the following</p>\n\n<pre><code>2010-01-01T10:00:00-02:00\n2010-01-01 10:00:00 -0200\n2010-01-01T10:00:00-02:00\n</code></pre>\n\n<p>The full original DateTime info including timezone is kept.</p>\n"
},
{
"answer_id": 8511699,
"author": "the Tin Man",
"author_id": 128421,
"author_profile": "https://Stackoverflow.com/users/128421",
"pm_score": 6,
"selected": false,
"text": "<p>As an update to the state of the Ruby ecosystem, <code>Date</code>, <code>DateTime</code> and <code>Time</code> now have methods to convert between the various classes. Using Ruby 1.9.2+:</p>\n\n<pre><code>pry\n[1] pry(main)> ts = 'Jan 1, 2000 12:01:01'\n=> \"Jan 1, 2000 12:01:01\"\n[2] pry(main)> require 'time'\n=> true\n[3] pry(main)> require 'date'\n=> true\n[4] pry(main)> ds = Date.parse(ts)\n=> #<Date: 2000-01-01 (4903089/2,0,2299161)>\n[5] pry(main)> ds.to_date\n=> #<Date: 2000-01-01 (4903089/2,0,2299161)>\n[6] pry(main)> ds.to_datetime\n=> #<DateTime: 2000-01-01T00:00:00+00:00 (4903089/2,0,2299161)>\n[7] pry(main)> ds.to_time\n=> 2000-01-01 00:00:00 -0700\n[8] pry(main)> ds.to_time.class\n=> Time\n[9] pry(main)> ds.to_datetime.class\n=> DateTime\n[10] pry(main)> ts = Time.parse(ts)\n=> 2000-01-01 12:01:01 -0700\n[11] pry(main)> ts.class\n=> Time\n[12] pry(main)> ts.to_date\n=> #<Date: 2000-01-01 (4903089/2,0,2299161)>\n[13] pry(main)> ts.to_date.class\n=> Date\n[14] pry(main)> ts.to_datetime\n=> #<DateTime: 2000-01-01T12:01:01-07:00 (211813513261/86400,-7/24,2299161)>\n[15] pry(main)> ts.to_datetime.class\n=> DateTime\n</code></pre>\n"
},
{
"answer_id": 11138360,
"author": "Mildred",
"author_id": 174011,
"author_profile": "https://Stackoverflow.com/users/174011",
"pm_score": 1,
"selected": false,
"text": "<p>Improving on Gordon Wilson solution, here is my try:</p>\n\n<pre><code>def to_time\n #Convert a fraction of a day to a number of microseconds\n usec = (sec_fraction * 60 * 60 * 24 * (10**6)).to_i\n t = Time.gm(year, month, day, hour, min, sec, usec)\n t - offset.abs.div(SECONDS_IN_DAY)\nend\n</code></pre>\n\n<p>You'll get the same time in UTC, loosing the timezone (unfortunately)</p>\n\n<p>Also, if you have ruby 1.9, just try the <code>to_time</code> method</p>\n"
},
{
"answer_id": 62623498,
"author": "tomcat",
"author_id": 6926239,
"author_profile": "https://Stackoverflow.com/users/6926239",
"pm_score": 0,
"selected": false,
"text": "<p>While making such conversions one should take into consideration the behavior of timezones while converting from one object to the other. I found some good notes and examples in this stackoverflow <a href=\"https://stackoverflow.com/a/21075654\">post</a>.</p>\n"
},
{
"answer_id": 65582221,
"author": "Dorian",
"author_id": 12544391,
"author_profile": "https://Stackoverflow.com/users/12544391",
"pm_score": 0,
"selected": false,
"text": "<p>You can use <code>to_date</code>, e.g.</p>\n<pre class=\"lang-rb prettyprint-override\"><code>> Event.last.starts_at\n=> Wed, 13 Jan 2021 16:49:36.292979000 CET +01:00\n> Event.last.starts_at.to_date\n=> Wed, 13 Jan 2021\n</code></pre>\n"
}
] |
2008/11/11
|
[
"https://Stackoverflow.com/questions/279769",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4883/"
] |
How do you convert between a DateTime and a Time object in Ruby?
|
You'll need two slightly different conversions.
To convert from `Time` to `DateTime` you can amend the Time class as follows:
```
require 'date'
class Time
def to_datetime
# Convert seconds + microseconds into a fractional number of seconds
seconds = sec + Rational(usec, 10**6)
# Convert a UTC offset measured in minutes to one measured in a
# fraction of a day.
offset = Rational(utc_offset, 60 * 60 * 24)
DateTime.new(year, month, day, hour, min, seconds, offset)
end
end
```
Similar adjustments to Date will let you convert `DateTime` to `Time` .
```
class Date
def to_gm_time
to_time(new_offset, :gm)
end
def to_local_time
to_time(new_offset(DateTime.now.offset-offset), :local)
end
private
def to_time(dest, method)
#Convert a fraction of a day to a number of microseconds
usec = (dest.sec_fraction * 60 * 60 * 24 * (10**6)).to_i
Time.send(method, dest.year, dest.month, dest.day, dest.hour, dest.min,
dest.sec, usec)
end
end
```
Note that you have to choose between local time and GM/UTC time.
Both the above code snippets are taken from O'Reilly's [Ruby Cookbook](http://safari.oreilly.com/0596523696). Their code reuse [policy](http://oreilly.com/pub/a/oreilly/ask_tim/2001/codepolicy.html) permits this.
|
279,779 |
<p>I know in the MVC Framework, you have the Html Class to create URLs:</p>
<pre><code>Html.ActionLink("About us", "about", "home");
</code></pre>
<p>But what if you want to generate Urls in Webforms?</p>
<p>I haven't found a really good resource on the details on generating URLs with Webforms.</p>
<p>For example, if I'm generating routes like so:</p>
<pre><code>Route r = new Route("{country}/{lang}/articles/{id}/{title}",
new ArticleRouteHandler("~/Forms/Article.aspx"));
Route r2 = new Route("{country}/{lang}/articles/",
new ArticleRouteHandler("~/Forms/ArticlesList.aspx"));
Routes.Add(r);
Routes.Add(r2);
</code></pre>
<p>How would i generate URLs using the Routing table data.</p>
<h2>How do I generate URLS based on my routes?</h2>
<p>eg. /ca/en/articles/123/Article-Title without</p>
|
[
{
"answer_id": 279980,
"author": "tsilb",
"author_id": 11112,
"author_profile": "https://Stackoverflow.com/users/11112",
"pm_score": -1,
"selected": false,
"text": "<p>Hyperlink hl = new Hyperlink();\nhl.Text = \"click here\";\nhl.NavigateUrl=\"~/Forms/Article.aspx\";\nMostlyAnyControl.Controls.Add(hl);</p>\n\n<p>as for putting it in a list... either (1) loop / iterate, or (2) Linq to XML.</p>\n"
},
{
"answer_id": 281340,
"author": "MikeO",
"author_id": 36616,
"author_profile": "https://Stackoverflow.com/users/36616",
"pm_score": 3,
"selected": true,
"text": "<p>As you say, ASP.NET MVC offers you a set of helper methods to \"reverse lookup\" the RouteTable and generate a URL for you. I've not played with this much yet but as far as I can see you need to call the GetVirtualPath method on a RouteCollection (most likely RouteTable.Routes). So something like:</p>\n\n<pre><code>Dim routedurl = RouteTable.Routes.GetVirtualPath(context, rvd).VirtualPath\n</code></pre>\n\n<p>You need to pass the RequestContext and a RouteValueDictionary. The RouteValueDictionary contains the route parameters (so in your case something like county=\"UK\", lang=\"EN-GB\" etc. The tricky part is the RequestContext as this is not part of the normal HttpContext. You can push it into the HttpContext in your IRouteHandler:</p>\n\n<pre><code>requestContext.HttpContext.Items(\"RequestContext\") = requestContext\n</code></pre>\n\n<p>and then restore it again in your IHttpHandler (aspx page) when required:</p>\n\n<pre><code>Dim rvd = \n New RouteValueDictionary(New With {.country = \"UK\", .lang = \"EN-GB\"})\nDim routedurl = \n RouteTable.Routes.GetVirtualPath(context.Items(\"RequestContext\"), rvd).VirtualPath\n</code></pre>\n\n<p>Apologies for responding to a C# question in VB, it was just that the ASP.NET routing site I had to hand was in VB.NET.</p>\n"
},
{
"answer_id": 285882,
"author": "Armstrongest",
"author_id": 26931,
"author_profile": "https://Stackoverflow.com/users/26931",
"pm_score": 3,
"selected": false,
"text": "<p>Thanks for the answers. TO add to this, here is what I've done:</p>\n\n<h2>In Global.asax</h2>\n\n<pre><code>RouteValueDictionary rvdSiteDefaults \n = new RouteValueDictionary { { \"country\", \"ca\" }, { \"lang\", \"en\" } };\n\nRoute oneArticle \n = new Route(\"{country}/{lang}/articles/a{id}/{title}\",\n rvdSiteDefaults,\n rvdConstrainID,\n new ArticleRouteHandler(\"~/Articles/Details.aspx\"));\n\nRoutes.Add( \"Article\", oneArticle); \n</code></pre>\n\n<h2>Create Url from Article object</h2>\n\n<pre><code>public static string CreateUrl(Article a) {\n // Note, Article comes from Database, has properties of ArticleID, Title, etc.\n RouteValueDictionary parameters;\n\n string routeName = \"Article\"; // Set in Global.asax\n\n parameters \n = new RouteValueDictionary { \n { \"id\", a.ArticleID }, \n { \"title\", a.Title.CleanUrl() } \n }; \n</code></pre>\n\n<p>CleanUrl() <a href=\"https://stackoverflow.com/questions/266719/url-routing-handling-spaces-and-illegal-characters-when-creating-friendly-urls#271568\">returns a URL Friendly name</a>.</p>\n\n<pre><code> VirtualPathData vpd = RouteTable.Routes.GetVirtualPath(null, routeName, parameters);\n\n string url = vpd.VirtualPath; \n return url; // eg. /ca/en/1/The-Article-Title\n}\n</code></pre>\n\n<p>TaDa!</p>\n"
}
] |
2008/11/11
|
[
"https://Stackoverflow.com/questions/279779",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/26931/"
] |
I know in the MVC Framework, you have the Html Class to create URLs:
```
Html.ActionLink("About us", "about", "home");
```
But what if you want to generate Urls in Webforms?
I haven't found a really good resource on the details on generating URLs with Webforms.
For example, if I'm generating routes like so:
```
Route r = new Route("{country}/{lang}/articles/{id}/{title}",
new ArticleRouteHandler("~/Forms/Article.aspx"));
Route r2 = new Route("{country}/{lang}/articles/",
new ArticleRouteHandler("~/Forms/ArticlesList.aspx"));
Routes.Add(r);
Routes.Add(r2);
```
How would i generate URLs using the Routing table data.
How do I generate URLS based on my routes?
------------------------------------------
eg. /ca/en/articles/123/Article-Title without
|
As you say, ASP.NET MVC offers you a set of helper methods to "reverse lookup" the RouteTable and generate a URL for you. I've not played with this much yet but as far as I can see you need to call the GetVirtualPath method on a RouteCollection (most likely RouteTable.Routes). So something like:
```
Dim routedurl = RouteTable.Routes.GetVirtualPath(context, rvd).VirtualPath
```
You need to pass the RequestContext and a RouteValueDictionary. The RouteValueDictionary contains the route parameters (so in your case something like county="UK", lang="EN-GB" etc. The tricky part is the RequestContext as this is not part of the normal HttpContext. You can push it into the HttpContext in your IRouteHandler:
```
requestContext.HttpContext.Items("RequestContext") = requestContext
```
and then restore it again in your IHttpHandler (aspx page) when required:
```
Dim rvd =
New RouteValueDictionary(New With {.country = "UK", .lang = "EN-GB"})
Dim routedurl =
RouteTable.Routes.GetVirtualPath(context.Items("RequestContext"), rvd).VirtualPath
```
Apologies for responding to a C# question in VB, it was just that the ASP.NET routing site I had to hand was in VB.NET.
|
279,781 |
<p>Hey everyone, I am trying to run the following program, but am getting a NullPointerException. I am new to the Java swing library so I could be doing something very dumb. Either way here are my two classes I am just playing around for now and all i want to do is draw a damn circle (ill want to draw a gallow, with a hangman on it in the end).</p>
<pre><code>package hangman2;
import java.awt.*;
import javax.swing.*;
public class Hangman2 extends JFrame{
private GridLayout alphabetLayout = new GridLayout(2,2,5,5);
private Gallow gallow = new Gallow();
public Hangman2() {
setLayout(alphabetLayout);
setSize(1000,500);
setVisible( true );
}
public static void main( String args[] ) {
Hangman2 application = new Hangman2();
application.setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE );
}
}
package hangman2;
import java.awt.*;
import javax.swing.*;
public class Gallow extends JPanel {
private Graphics g;
public Gallow(){
g.fillOval(10, 20, 40, 25);
}
}
</code></pre>
<p>The NullPointerException comes in at the g.fillOval line.</p>
<p>Thanks in advance,</p>
<p>Tomek</p>
|
[
{
"answer_id": 279798,
"author": "sblundy",
"author_id": 4893,
"author_profile": "https://Stackoverflow.com/users/4893",
"pm_score": 3,
"selected": true,
"text": "<p>You're getting NPE because <code>g</code> is not set, therefore, it's <code>null</code>. Furthermore, you shouldn't be doing the drawing in the constructor. Overload <a href=\"http://java.sun.com/j2se/1.5.0/docs/api/javax/swing/JComponent.html#paintComponent(java.awt.Graphics)\" rel=\"nofollow noreferrer\"><code>paintComponent(Graphics g)</code></a> instead.</p>\n\n<pre><code>public class Gallow extends JPanel {\n public paintComponent(Graphics g){\n g.fillOval(10, 20, 40, 25); \n }\n}\n</code></pre>\n\n<p>I'd also look into <a href=\"http://java.sun.com/j2se/1.5.0/docs/api/java/awt/image/BufferedImage.html\" rel=\"nofollow noreferrer\">BufferedImage</a>.</p>\n"
},
{
"answer_id": 279851,
"author": "Vincent Ramdhanie",
"author_id": 27439,
"author_profile": "https://Stackoverflow.com/users/27439",
"pm_score": 0,
"selected": false,
"text": "<p>A couple of things: Don't forget to add the panel to the <code>JFrame</code>. And override the <code>paint()</code> method of <code>JPanel</code> for your custom painting. You do not need to declare a Graphics object since the <code>JPanel</code>'s paint method will have a reference to one in any case.</p>\n\n<pre><code>package hangman2;\n\nimport java.awt.*;\nimport javax.swing.*;\n\npublic class Hangman2 extends JFrame{\n private GridLayout alphabetLayout = new GridLayout(2,2,5,5);\n private Gallow gallow = new Gallow();\n\n public Hangman2() {\n\n setLayout(alphabetLayout);\n add(gallow, BorderLayout.CENTER);//here\n setSize(1000,500);\n setVisible( true );\n\n }\n\n public static void main( String args[] ) { \n Hangman2 application = new Hangman2();\n application.setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE );\n }\n}\n\n\npackage hangman2;\n\nimport java.awt.*;\nimport javax.swing.*;\n\npublic class Gallow extends JPanel {\n\n public Gallow(){\n super();\n }\n\n public void paint(Graphics g){\n g.fillOval(10, 20, 40, 25); \n }\n}\n</code></pre>\n"
}
] |
2008/11/11
|
[
"https://Stackoverflow.com/questions/279781",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/29326/"
] |
Hey everyone, I am trying to run the following program, but am getting a NullPointerException. I am new to the Java swing library so I could be doing something very dumb. Either way here are my two classes I am just playing around for now and all i want to do is draw a damn circle (ill want to draw a gallow, with a hangman on it in the end).
```
package hangman2;
import java.awt.*;
import javax.swing.*;
public class Hangman2 extends JFrame{
private GridLayout alphabetLayout = new GridLayout(2,2,5,5);
private Gallow gallow = new Gallow();
public Hangman2() {
setLayout(alphabetLayout);
setSize(1000,500);
setVisible( true );
}
public static void main( String args[] ) {
Hangman2 application = new Hangman2();
application.setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE );
}
}
package hangman2;
import java.awt.*;
import javax.swing.*;
public class Gallow extends JPanel {
private Graphics g;
public Gallow(){
g.fillOval(10, 20, 40, 25);
}
}
```
The NullPointerException comes in at the g.fillOval line.
Thanks in advance,
Tomek
|
You're getting NPE because `g` is not set, therefore, it's `null`. Furthermore, you shouldn't be doing the drawing in the constructor. Overload [`paintComponent(Graphics g)`](http://java.sun.com/j2se/1.5.0/docs/api/javax/swing/JComponent.html#paintComponent(java.awt.Graphics)) instead.
```
public class Gallow extends JPanel {
public paintComponent(Graphics g){
g.fillOval(10, 20, 40, 25);
}
}
```
I'd also look into [BufferedImage](http://java.sun.com/j2se/1.5.0/docs/api/java/awt/image/BufferedImage.html).
|
279,782 |
<p>Given:</p>
<pre><code>from django.db import models
class Food(models.Model):
"""Food, by name."""
name = models.CharField(max_length=25)
class Cat(models.Model):
"""A cat eats one type of food"""
food = models.ForeignKey(Food)
class Cow(models.Model):
"""A cow eats one type of food"""
food = models.ForeignKey(Food)
class Human(models.Model):
"""A human may eat lots of types of food"""
food = models.ManyToManyField(Food)
</code></pre>
<p>How can one, given only the class Food, get a set of all classes that it has "reverse relationships" to. I.e. given the class <strong>Food</strong>, how can one get the classes <strong>Cat</strong>, <strong>Cow</strong> and <strong>Human</strong>.</p>
<p>I would think it's possible because Food has the three "reverse relations": <em>Food.cat_set</em>, <em>Food.cow_set</em>, and <em>Food.human_set</em>.</p>
<p>Help's appreciated & thank you!</p>
|
[
{
"answer_id": 279809,
"author": "Brian M. Hunt",
"author_id": 19212,
"author_profile": "https://Stackoverflow.com/users/19212",
"pm_score": 4,
"selected": false,
"text": "<p>Some digging in the source code revealed:</p>\n\n<p>django/db/models/options.py:</p>\n\n<pre><code>def get_all_related_objects(self, local_only=False):\n\ndef get_all_related_many_to_many_objects(self, local_only=False)\n</code></pre>\n\n<p>And, using these functions on the models from above, you hypothetically get:</p>\n\n<pre><code>>>> Food._meta.get_all_related_objects()\n[<RelatedObject: app_label:cow related to food>,\n <RelatedObject: app_label:cat related to food>,]\n\n>>> Food._meta.get_all_related_many_to_many_objects()\n[<RelatedObject: app_label:human related to food>,]\n\n# and, per django/db/models/related.py\n# you can retrieve the model with\n>>> Food._meta.get_all_related_objects()[0].model\n<class 'app_label.models.Cow'>\n</code></pre>\n\n<p><em>Note</em>: I hear Model._meta is 'unstable', and perhaps ought not to be relied upon in the post Django-1.0 world.</p>\n\n<p>Thanks for reading. :)</p>\n"
},
{
"answer_id": 279952,
"author": "vincent",
"author_id": 34871,
"author_profile": "https://Stackoverflow.com/users/34871",
"pm_score": 4,
"selected": true,
"text": "<p>Either </p>\n\n<p>A) Use <a href=\"http://docs.djangoproject.com/en/dev/topics/db/models/#multi-table-inheritance\" rel=\"nofollow noreferrer\">multiple table inheritance</a> and create a \"Eater\" base class, that Cat, Cow and Human inherit from.</p>\n\n<p>B) Use a <a href=\"http://docs.djangoproject.com/en/dev/ref/contrib/contenttypes/#id1\" rel=\"nofollow noreferrer\">Generic Relation</a>, where Food could be linked to any other Model.</p>\n\n<p>Those are well-documented and officially supported features, you'd better stick to them to keep your own code clean, avoid workarounds and be sure it'll be still supported in the future.</p>\n\n<p>-- EDIT ( A.k.a. \"how to be a reputation whore\" )</p>\n\n<p>So, here is a recipe for that particular case.</p>\n\n<p>Let's assume you absolutely want separate models for Cat, Cow and Human. In a real-world application, you want to ask to yourself why a \"category\" field wouldn't do the job.</p>\n\n<p>It's easier to get to the \"real\" class through generic relations, so here is the implementation for B. We can't have that 'food' field in Person, Cat or Cow, or we'll run into the same problems. So we'll create an intermediary \"FoodConsumer\" model. We'll have to write additional validation tests if we don't want more than one food for an instance.</p>\n\n<pre><code>from django.db import models\nfrom django.contrib.contenttypes.models import ContentType\nfrom django.contrib.contenttypes import generic\n\nclass Food(models.Model):\n \"\"\"Food, by name.\"\"\"\n name = models.CharField(max_length=25)\n\n# ConsumedFood has a foreign key to Food, and a \"eaten_by\" generic relation\nclass ConsumedFood(models.Model):\n food = models.ForeignKey(Food, related_name=\"eaters\")\n content_type = models.ForeignKey(ContentType, null=True)\n object_id = models.PositiveIntegerField(null=True)\n eaten_by = generic.GenericForeignKey('content_type', 'object_id')\n\nclass Person(models.Model):\n first_name = models.CharField(max_length=50)\n last_name = models.CharField(max_length=50)\n birth_date = models.DateField()\n address = models.CharField(max_length=100)\n city = models.CharField(max_length=50)\n foods = generic.GenericRelation(ConsumedFood)\n\nclass Cat(models.Model):\n name = models.CharField(max_length=50)\n foods = generic.GenericRelation(ConsumedFood) \n\nclass Cow(models.Model):\n farmer = models.ForeignKey(Person)\n foods = generic.GenericRelation(ConsumedFood) \n</code></pre>\n\n<p>Now, to demonstrate it let's just write this working <a href=\"http://docs.djangoproject.com/en/dev/topics/testing/#writing-doctests\" rel=\"nofollow noreferrer\">doctest</a>:</p>\n\n<pre><code>\"\"\"\n>>> from models import *\n\nCreate some food records\n\n>>> weed = Food(name=\"weed\")\n>>> weed.save()\n\n>>> burger = Food(name=\"burger\")\n>>> burger.save()\n\n>>> pet_food = Food(name=\"Pet food\")\n>>> pet_food.save()\n\nJohn the farmer likes burgers\n\n>>> john = Person(first_name=\"John\", last_name=\"Farmer\", birth_date=\"1960-10-12\")\n>>> john.save()\n>>> john.foods.create(food=burger)\n<ConsumedFood: ConsumedFood object>\n\nWilma the cow eats weed\n\n>>> wilma = Cow(farmer=john)\n>>> wilma.save()\n>>> wilma.foods.create(food=weed)\n<ConsumedFood: ConsumedFood object>\n\nFelix the cat likes pet food\n\n>>> felix = Cat(name=\"felix\")\n>>> felix.save()\n>>> pet_food.eaters.create(eaten_by=felix)\n<ConsumedFood: ConsumedFood object>\n\nWhat food john likes again ?\n>>> john.foods.all()[0].food.name\nu'burger'\n\nWho's getting pet food ?\n>>> living_thing = pet_food.eaters.all()[0].eaten_by\n>>> isinstance(living_thing,Cow)\nFalse\n>>> isinstance(living_thing,Cat)\nTrue\n\nJohn's farm is in fire ! He looses his cow.\n>>> wilma.delete()\n\nJohn is a lot poorer right now\n>>> john.foods.clear()\n>>> john.foods.create(food=pet_food)\n<ConsumedFood: ConsumedFood object>\n\nWho's eating pet food now ?\n>>> for consumed_food in pet_food.eaters.all():\n... consumed_food.eaten_by\n<Cat: Cat object>\n<Person: Person object>\n\nGet the second pet food eater\n>>> living_thing = pet_food.eaters.all()[1].eaten_by\n\nTry to find if it's a person and reveal his name\n>>> if isinstance(living_thing,Person): living_thing.first_name\nu'John'\n\n\"\"\"\n</code></pre>\n"
}
] |
2008/11/11
|
[
"https://Stackoverflow.com/questions/279782",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/19212/"
] |
Given:
```
from django.db import models
class Food(models.Model):
"""Food, by name."""
name = models.CharField(max_length=25)
class Cat(models.Model):
"""A cat eats one type of food"""
food = models.ForeignKey(Food)
class Cow(models.Model):
"""A cow eats one type of food"""
food = models.ForeignKey(Food)
class Human(models.Model):
"""A human may eat lots of types of food"""
food = models.ManyToManyField(Food)
```
How can one, given only the class Food, get a set of all classes that it has "reverse relationships" to. I.e. given the class **Food**, how can one get the classes **Cat**, **Cow** and **Human**.
I would think it's possible because Food has the three "reverse relations": *Food.cat\_set*, *Food.cow\_set*, and *Food.human\_set*.
Help's appreciated & thank you!
|
Either
A) Use [multiple table inheritance](http://docs.djangoproject.com/en/dev/topics/db/models/#multi-table-inheritance) and create a "Eater" base class, that Cat, Cow and Human inherit from.
B) Use a [Generic Relation](http://docs.djangoproject.com/en/dev/ref/contrib/contenttypes/#id1), where Food could be linked to any other Model.
Those are well-documented and officially supported features, you'd better stick to them to keep your own code clean, avoid workarounds and be sure it'll be still supported in the future.
-- EDIT ( A.k.a. "how to be a reputation whore" )
So, here is a recipe for that particular case.
Let's assume you absolutely want separate models for Cat, Cow and Human. In a real-world application, you want to ask to yourself why a "category" field wouldn't do the job.
It's easier to get to the "real" class through generic relations, so here is the implementation for B. We can't have that 'food' field in Person, Cat or Cow, or we'll run into the same problems. So we'll create an intermediary "FoodConsumer" model. We'll have to write additional validation tests if we don't want more than one food for an instance.
```
from django.db import models
from django.contrib.contenttypes.models import ContentType
from django.contrib.contenttypes import generic
class Food(models.Model):
"""Food, by name."""
name = models.CharField(max_length=25)
# ConsumedFood has a foreign key to Food, and a "eaten_by" generic relation
class ConsumedFood(models.Model):
food = models.ForeignKey(Food, related_name="eaters")
content_type = models.ForeignKey(ContentType, null=True)
object_id = models.PositiveIntegerField(null=True)
eaten_by = generic.GenericForeignKey('content_type', 'object_id')
class Person(models.Model):
first_name = models.CharField(max_length=50)
last_name = models.CharField(max_length=50)
birth_date = models.DateField()
address = models.CharField(max_length=100)
city = models.CharField(max_length=50)
foods = generic.GenericRelation(ConsumedFood)
class Cat(models.Model):
name = models.CharField(max_length=50)
foods = generic.GenericRelation(ConsumedFood)
class Cow(models.Model):
farmer = models.ForeignKey(Person)
foods = generic.GenericRelation(ConsumedFood)
```
Now, to demonstrate it let's just write this working [doctest](http://docs.djangoproject.com/en/dev/topics/testing/#writing-doctests):
```
"""
>>> from models import *
Create some food records
>>> weed = Food(name="weed")
>>> weed.save()
>>> burger = Food(name="burger")
>>> burger.save()
>>> pet_food = Food(name="Pet food")
>>> pet_food.save()
John the farmer likes burgers
>>> john = Person(first_name="John", last_name="Farmer", birth_date="1960-10-12")
>>> john.save()
>>> john.foods.create(food=burger)
<ConsumedFood: ConsumedFood object>
Wilma the cow eats weed
>>> wilma = Cow(farmer=john)
>>> wilma.save()
>>> wilma.foods.create(food=weed)
<ConsumedFood: ConsumedFood object>
Felix the cat likes pet food
>>> felix = Cat(name="felix")
>>> felix.save()
>>> pet_food.eaters.create(eaten_by=felix)
<ConsumedFood: ConsumedFood object>
What food john likes again ?
>>> john.foods.all()[0].food.name
u'burger'
Who's getting pet food ?
>>> living_thing = pet_food.eaters.all()[0].eaten_by
>>> isinstance(living_thing,Cow)
False
>>> isinstance(living_thing,Cat)
True
John's farm is in fire ! He looses his cow.
>>> wilma.delete()
John is a lot poorer right now
>>> john.foods.clear()
>>> john.foods.create(food=pet_food)
<ConsumedFood: ConsumedFood object>
Who's eating pet food now ?
>>> for consumed_food in pet_food.eaters.all():
... consumed_food.eaten_by
<Cat: Cat object>
<Person: Person object>
Get the second pet food eater
>>> living_thing = pet_food.eaters.all()[1].eaten_by
Try to find if it's a person and reveal his name
>>> if isinstance(living_thing,Person): living_thing.first_name
u'John'
"""
```
|
279,791 |
<p>Suppose the following data schema:</p>
<pre><code>Usage
======
client_id
resource
type
amount
Billing
======
client_id
usage_resource
usage_type
rate
</code></pre>
<p>In this example, suppose I have multiple resources, each of which can be used in many ways. For example, one resource is a <code>widget</code>. <code>Widgets</code> can be <code>foo</code>ed and they can be <code>bar</code>ed. <code>Gizmo</code>s can also be <code>foo</code>ed and <code>bar</code>ed. These usage types are billed at different rates, possibly even different rates for different clients. Each occurence of a usage (of a resource) is recorded in the Usage table. Each billing rate (for client, resource, and type combination) is stored in the billing table.</p>
<p><em>(By the way, if this data schema is not the right way to approach this problem, please make suggestions.)</em></p>
<p>Is it possible, using Ruby on Rails and ActiveRecord, to create a <code>has_many</code> relationship from Billings to Usages so that I can get a list of usage instances for a given billing rate? Is there a syntax of the <code>has_many, :through</code> that I don't know?</p>
<p>Once again, I may be approaching this problem from the wrong angle, so if you can think of a better way, please speak up!</p>
|
[
{
"answer_id": 279838,
"author": "Bill Karwin",
"author_id": 20860,
"author_profile": "https://Stackoverflow.com/users/20860",
"pm_score": 4,
"selected": true,
"text": "<p>There is apparently an project at sourceforge to extend Rails' ActiveRecord with support for <a href=\"http://compositekeys.rubyforge.org/\" rel=\"nofollow noreferrer\">Composite Primary Keys</a>. I haven't used this extension, but it might help you. It's also a gem at rubyforge.</p>\n\n<p>Plain Ruby on Rails, as of version 2.0, does not support compound primary keys (cf. <a href=\"http://wiki.rubyonrails.org/rails/pages/howtouselegacyschemas\" rel=\"nofollow noreferrer\">HowToUseLegacySchemas</a>). Every table must have a single-column, auto-increment key named \"<code>id</code>\". </p>\n\n<p>The explanation I have seen is: \"You only need compound primary keys if you want to use a legacy database.\" This is of course a ridiculously ignorant view of data modeling.</p>\n\n<p>The solution I see would be:</p>\n\n<ul>\n<li>Usage.client_id -> Client.id</li>\n<li>Usage.type_id -> Usagetype.id</li>\n<li>Usage.resource_id -> Resource.id</li>\n<li>Billing.usage_id -> Usage.id</li>\n<li>Billing.client_id -> Client.id</li>\n<li>Billing.type_id -> Usagetype.id</li>\n<li>Billing.resource_id -> Resource.id</li>\n</ul>\n\n<p>The apparently redundant foreign keys in <code>Billing</code> attempt to enforce partial referential integrity. But it doesn't quite get there -- it does not prevent you from creating rows in <code>Billing</code> that reference a row in <code>Usage</code> with the wrong client/resource/usagetype combination, not matching those in the referencing row in the Billing table.</p>\n\n<p><strong>edit:</strong> @Yarik: yes, you're right. It makes more sense for <code>Usage</code> to reference <code>Billing</code>.</p>\n\n<ul>\n<li>Usage.billing_id -> Billing.id</li>\n</ul>\n\n<p>Hmm. I made an ER diagram but I'm having trouble inserting it as an image.</p>\n"
},
{
"answer_id": 1081092,
"author": "Michael Sofaer",
"author_id": 132613,
"author_profile": "https://Stackoverflow.com/users/132613",
"pm_score": 1,
"selected": false,
"text": "<p>You can create any constraint you want with the 'execute' command in a migration.</p>\n\n<p>You would probably want to add some error handling to .save to deal with cases when the constraint throws an error.</p>\n\n<p>You can't use AR's built-in method generators to generate the usages off the billing, but you can still have the method:</p>\n\n<pre><code>class Billing\n def usages\n Usage.find(:all, :conditions => [\"x = ? and y = ?\", self.x, self.y])\n end\nend\n</code></pre>\n"
}
] |
2008/11/11
|
[
"https://Stackoverflow.com/questions/279791",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4257/"
] |
Suppose the following data schema:
```
Usage
======
client_id
resource
type
amount
Billing
======
client_id
usage_resource
usage_type
rate
```
In this example, suppose I have multiple resources, each of which can be used in many ways. For example, one resource is a `widget`. `Widgets` can be `foo`ed and they can be `bar`ed. `Gizmo`s can also be `foo`ed and `bar`ed. These usage types are billed at different rates, possibly even different rates for different clients. Each occurence of a usage (of a resource) is recorded in the Usage table. Each billing rate (for client, resource, and type combination) is stored in the billing table.
*(By the way, if this data schema is not the right way to approach this problem, please make suggestions.)*
Is it possible, using Ruby on Rails and ActiveRecord, to create a `has_many` relationship from Billings to Usages so that I can get a list of usage instances for a given billing rate? Is there a syntax of the `has_many, :through` that I don't know?
Once again, I may be approaching this problem from the wrong angle, so if you can think of a better way, please speak up!
|
There is apparently an project at sourceforge to extend Rails' ActiveRecord with support for [Composite Primary Keys](http://compositekeys.rubyforge.org/). I haven't used this extension, but it might help you. It's also a gem at rubyforge.
Plain Ruby on Rails, as of version 2.0, does not support compound primary keys (cf. [HowToUseLegacySchemas](http://wiki.rubyonrails.org/rails/pages/howtouselegacyschemas)). Every table must have a single-column, auto-increment key named "`id`".
The explanation I have seen is: "You only need compound primary keys if you want to use a legacy database." This is of course a ridiculously ignorant view of data modeling.
The solution I see would be:
* Usage.client\_id -> Client.id
* Usage.type\_id -> Usagetype.id
* Usage.resource\_id -> Resource.id
* Billing.usage\_id -> Usage.id
* Billing.client\_id -> Client.id
* Billing.type\_id -> Usagetype.id
* Billing.resource\_id -> Resource.id
The apparently redundant foreign keys in `Billing` attempt to enforce partial referential integrity. But it doesn't quite get there -- it does not prevent you from creating rows in `Billing` that reference a row in `Usage` with the wrong client/resource/usagetype combination, not matching those in the referencing row in the Billing table.
**edit:** @Yarik: yes, you're right. It makes more sense for `Usage` to reference `Billing`.
* Usage.billing\_id -> Billing.id
Hmm. I made an ER diagram but I'm having trouble inserting it as an image.
|
279,822 |
<p>I'm looking for a (preferably free) component for Delphi for users to easily select about 100 different colours.</p>
<p>I've currently got one as part of DevExpress's editors, but it only has about 20 proper colours to choose, with a bunch of other 'Windows' colours like clHighlight, clBtnFace, etc.</p>
<p>It's for regular users, so would like to avoid requiring them to manually select RGB values. </p>
<p>Something similar to the colour picker in MS Paint might work, or something that lists X11/web colours:</p>
<p><a href="http://en.wikipedia.org/wiki/Web_Colors" rel="noreferrer">http://en.wikipedia.org/wiki/Web_Colors</a></p>
<p>So, please let me know if you got any recommendations.</p>
<p><strong>Thanks for the suggestions from everyone</strong></p>
<p>All of the suggestions were good, I didn't realise the MS Paint colour dialog can be called, that's all I needed and is the simplest solution. Thanks</p>
|
[
{
"answer_id": 279864,
"author": "moobaa",
"author_id": 3569,
"author_profile": "https://Stackoverflow.com/users/3569",
"pm_score": 4,
"selected": false,
"text": "<p>Delphi Gems' Color Picker control, maybe?</p>\n\n<p><a href=\"http://www.soft-gems.net/index.php/controls/color-picker-control\" rel=\"nofollow noreferrer\">http://www.soft-gems.net/index.php/controls/color-picker-control</a></p>\n"
},
{
"answer_id": 279879,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 3,
"selected": false,
"text": "<p>Give mbColor Lib from MXS a go. Perhaps the most comprehensive set of color picking components for Delphi. <a href=\"http://mxs.bergsoft.net/index.php?p=3\" rel=\"noreferrer\">MXS Components</a></p>\n"
},
{
"answer_id": 280103,
"author": "Francesca",
"author_id": 9842,
"author_profile": "https://Stackoverflow.com/users/9842",
"pm_score": 5,
"selected": true,
"text": "<p>What's wrong with the TColorDialog?<br>\nIt gives you the standard Windows color dialog, exactly the same as in MSPaint...<br>\nAdd these options to show it directly expanded and with all colors available. </p>\n\n<pre><code>object ColorDialog1: TColorDialog\n Options = [cdFullOpen, cdAnyColor]\nend\n</code></pre>\n"
},
{
"answer_id": 280779,
"author": "dcraggs",
"author_id": 4382,
"author_profile": "https://Stackoverflow.com/users/4382",
"pm_score": 2,
"selected": false,
"text": "<p>There was an article about creating a custom colour selection component in issue 3 of the blaise pascal magazine.</p>\n\n<p><a href=\"http://www.blaisepascal.eu/blaisepascal_3/color_selection_component_david_dirkse.php\" rel=\"nofollow noreferrer\">http://www.blaisepascal.eu/blaisepascal_3/color_selection_component_david_dirkse.php</a></p>\n"
}
] |
2008/11/11
|
[
"https://Stackoverflow.com/questions/279822",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/26305/"
] |
I'm looking for a (preferably free) component for Delphi for users to easily select about 100 different colours.
I've currently got one as part of DevExpress's editors, but it only has about 20 proper colours to choose, with a bunch of other 'Windows' colours like clHighlight, clBtnFace, etc.
It's for regular users, so would like to avoid requiring them to manually select RGB values.
Something similar to the colour picker in MS Paint might work, or something that lists X11/web colours:
<http://en.wikipedia.org/wiki/Web_Colors>
So, please let me know if you got any recommendations.
**Thanks for the suggestions from everyone**
All of the suggestions were good, I didn't realise the MS Paint colour dialog can be called, that's all I needed and is the simplest solution. Thanks
|
What's wrong with the TColorDialog?
It gives you the standard Windows color dialog, exactly the same as in MSPaint...
Add these options to show it directly expanded and with all colors available.
```
object ColorDialog1: TColorDialog
Options = [cdFullOpen, cdAnyColor]
end
```
|
279,833 |
<p>I am not looking for links to information on hashing.</p>
<p>I am not looking for the worlds greatest hash function.</p>
<p>I am interested in mini-stories describing</p>
<ul>
<li>The problem domain you were working in</li>
<li>The nature of the data you were working with</li>
<li>What your thought process was in designing a hash function for your data.</li>
<li>How happy were you with your result.</li>
<li>What you learned from the experience that might be of value to others.</li>
</ul>
|
[
{
"answer_id": 279877,
"author": "Adam Liss",
"author_id": 29157,
"author_profile": "https://Stackoverflow.com/users/29157",
"pm_score": 3,
"selected": false,
"text": "<p>The first issue I consider is whether an established algorithm will suit my requirements.</p>\n"
},
{
"answer_id": 279885,
"author": "Steven A. Lowe",
"author_id": 9345,
"author_profile": "https://Stackoverflow.com/users/9345",
"pm_score": 1,
"selected": false,
"text": "<p>i'll second what Adam said: don't reinvent the hashing wheel</p>\n\n<p>the only time i have ever needed a custom hashing function was to compare digraphs for equality; the hashing function let me tell very efficiently when two graphs were <em>not</em> equal (when the hash values matched i still had to do a node-by-node comparison to be certain)</p>\n"
},
{
"answer_id": 279893,
"author": "S.Lott",
"author_id": 10661,
"author_profile": "https://Stackoverflow.com/users/10661",
"pm_score": 3,
"selected": true,
"text": "<p>Doing data warehouse development. We had a dimension with about 9,000 rows. The queries that were being developed included some really ugly queries.</p>\n\n<p>So, I started analyzing the dimension rows. Dimension rows were clustered based on various combinations of columns. The clustering was a map from some key to a list of dimension rows that shared that key. The hash key, then, was a tuple of column values.</p>\n\n<p>The intermediate result, in Python, looked like this</p>\n\n<pre><code>{ \n ( (col1, col2), (col3, col4) ) : [ aRow, anotherRow, row3, ... ],\n ( (col1, col2), (col3, col4) ) : [ row1, row2, row3. row4, ... ],\n}\n</code></pre>\n\n<p>Technically, this is an inverted index.</p>\n\n<p>The hash key required some care in building a tuple of column values, partly because Python won't use mutable collections (i.e., lists). More important, the tuples weren't simple flat lists of column values. They were usually two-tuples that attempted to partition the dimension rows into disjoint subsets based on key combinations</p>\n\n<p>The hash algorithm, down deep, is the built-in Python hash. Choosing the keys, however, wasn't obvious or easy.</p>\n"
},
{
"answer_id": 280043,
"author": "Charles Graham",
"author_id": 7705,
"author_profile": "https://Stackoverflow.com/users/7705",
"pm_score": 1,
"selected": false,
"text": "<p>The first thing I think of is the best place to <code>steal</code> a hashing algorithm and its code. If and only if I find no algorithm appropriate, I use them as a starting point to create my own. To be fair, I have been in this industry for 7 years, and I have <em>never</em> created my own hashing algorithm since college.\nBut if I did create my own algorithm, minimizing collisions should be the biggest thing to think about. What are your likely values? Does this function accurately disperse those values so that hopefully there is a one to one relationship between the resulting value and the original value. Do the resulting values really disperse well. Meaning that say, they don’t all have common factors? This could cause collisions when you do modulus operations to make the value smaller and fit into your indexed collection.</p>\n"
},
{
"answer_id": 280085,
"author": "Michael Rutherfurd",
"author_id": 33889,
"author_profile": "https://Stackoverflow.com/users/33889",
"pm_score": 1,
"selected": false,
"text": "<p>Inventing a hashing algorithm is easy. Inventing a <em>working</em>, <em>efficient</em>, and <em>effective</em> hashing algorithm is not.</p>\n\n<p>You should ask yourself:</p>\n\n<ol>\n<li>Do I need to have a hash at all?</li>\n<li>Assuming I do then implement a standard cookbook recipe (e.g. Effective Java) including <em>all</em> related requirements (e.g. if a.equals(b) then a.hashCode() == b.hashCode()) </li>\n</ol>\n\n<p>If you have two instances of an object that need to be compared for equality, then you probably need to provide an implementation for equals().</p>\n\n<p>If you have multiple instances of an object that need to be sorted, then you probably need to provide an implementation for compareTo().</p>\n\n<p>If you have a custom object being used as the key of a Map, then you probably need to provide an implementation of hashCode().</p>\n"
},
{
"answer_id": 14053157,
"author": "nawfal",
"author_id": 661933,
"author_profile": "https://Stackoverflow.com/users/661933",
"pm_score": 1,
"selected": false,
"text": "<p>Not exactly my experience, but some of the conditions you have to consider:</p>\n\n<ol>\n<li><p>Most importantly hash function should be analogous to equality checking. Two equal objects should always always return the same hash (Two unequal objects can return same hash but that should be rare). </p></li>\n<li><p>Better go for existing hash functions since they most probably will have better balance between speed and distribution.</p></li>\n<li><p>Hashing function should be fast. Do not make it any bit slower/complex if the resulting hash wont yield in substantially better distribution of values. <em>So hashes of numeric types is always better</em> (agreed most frameworks have hashes of integer types, just saying).</p></li>\n<li><p>Hashes should have good distribution that chances of collision has to be very less. XOR is a bad choice mostly hence. <em>In other words finding a good balance between speed and distribution is the key</em>. Chances are likely to have a slower hash if distribution is better.</p></li>\n<li><p>Write the function knowing what size your output will be. If it is <code>int32</code> then ensure overflow doesn't happen.</p></li>\n<li><p>Hashing function should never give an error (other than for null reference which is valid). The main culprit will be integer overflows. Handle it.</p></li>\n<li><p>If you know before runtime itself what your possible inputs will be, then have a function to target that to speed up things.</p></li>\n<li><p>Most probably hashes need not be reversible, but if ever you need it (say get the two numbers back from a given hash), write it accordingly. This may not be a requirement in general cases (where hashes collide).</p></li>\n<li><p>If your hashes are just meant for quickly comparing two objects, then don't use it for security purposes. <em><a href=\"http://en.wikipedia.org/wiki/Cryptographic_hash_function\" rel=\"nofollow\">Cryptographic hashing</a> is entirely a different beast.</em></p></li>\n<li><p>If you have more than one hashing functions at hand, then run quick test to find which operates better for your inputs. Testing will be always better than theoretically analyzing.</p></li>\n</ol>\n\n<p>These are what I have off the top of my head. See <a href=\"http://blogs.msdn.com/b/ericlippert/archive/2011/02/28/guidelines-and-rules-for-gethashcode.aspx\" rel=\"nofollow\">Eric's blog additionally</a>.</p>\n"
}
] |
2008/11/11
|
[
"https://Stackoverflow.com/questions/279833",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7734/"
] |
I am not looking for links to information on hashing.
I am not looking for the worlds greatest hash function.
I am interested in mini-stories describing
* The problem domain you were working in
* The nature of the data you were working with
* What your thought process was in designing a hash function for your data.
* How happy were you with your result.
* What you learned from the experience that might be of value to others.
|
Doing data warehouse development. We had a dimension with about 9,000 rows. The queries that were being developed included some really ugly queries.
So, I started analyzing the dimension rows. Dimension rows were clustered based on various combinations of columns. The clustering was a map from some key to a list of dimension rows that shared that key. The hash key, then, was a tuple of column values.
The intermediate result, in Python, looked like this
```
{
( (col1, col2), (col3, col4) ) : [ aRow, anotherRow, row3, ... ],
( (col1, col2), (col3, col4) ) : [ row1, row2, row3. row4, ... ],
}
```
Technically, this is an inverted index.
The hash key required some care in building a tuple of column values, partly because Python won't use mutable collections (i.e., lists). More important, the tuples weren't simple flat lists of column values. They were usually two-tuples that attempted to partition the dimension rows into disjoint subsets based on key combinations
The hash algorithm, down deep, is the built-in Python hash. Choosing the keys, however, wasn't obvious or easy.
|
279,837 |
<p>It's kind of a C puzzle. You have to tell if the program finish its execution, if so, how much time it takes to run and what it returns to the OS.</p>
<pre><code>static unsigned char buffer[256];
int main(void)
{
unsigned char *p, *q;
q = (p = buffer) + sizeof(buffer);
while (q - p)
{
p = buffer;
while (!++*p++);
}
return p - q;
}
</code></pre>
<p>[EDIT]
I removed the interview-questions tag since that seems to be the primary thing people are objecting to. This is a great little puzzle but as everyone has already pointed out, not a great interview question.</p>
|
[
{
"answer_id": 279855,
"author": "Steven A. Lowe",
"author_id": 9345,
"author_profile": "https://Stackoverflow.com/users/9345",
"pm_score": 4,
"selected": false,
"text": "<p>this code is garbage, see comments</p>\n\n<pre><code>static unsigned char buffer[256];\nint main(void)\n{\n unsigned char *p, *q;\n q = (p = buffer) + sizeof(buffer); //p=buffer, q=buffer+256\n while (q - p) //q-p = 256 on first iteration\n { \n p = buffer; //p=buffer again\n while (!++*p++); //increment the value pointed at by p+1 and check for !0\n }\n return p - q; //will return zero if loop ever terminates\n}\n</code></pre>\n\n<p>it might terminate, it might not; the while loop is essentially scanning an uninitialized buffer so it might throw an access violation instead; i don't remember the binding precedence of ++*p++, nor do i care enough to look it up</p>\n\n<p>if this is really an interview question, my answer is \"if this is the kind of code you expect me to work with, i don't want the job\"</p>\n\n<p>EDIT: thanks to Robert Gamble for reminding me that static arrays are automatically initialized to zero, so the code is not complete garbage - but I still would not want to maintain it or work with the nutjob that wrote it ;-)</p>\n"
},
{
"answer_id": 279954,
"author": "Robert Gamble",
"author_id": 25222,
"author_profile": "https://Stackoverflow.com/users/25222",
"pm_score": 5,
"selected": true,
"text": "<p>Despite the fact that this is a horrible interview question, it is actually quite interesting:</p>\n\n<pre><code>static unsigned char buffer[256];\n\nint main(void)\n{\n unsigned char *p, *q;\n q = (p = buffer) + sizeof(buffer);\n /* This statement will set p to point to the beginning of buffer and will\n set q to point to one past the last element of buffer (this is legal) */\n while (q - p)\n /* q - p will start out being 256 and will decrease at an inversely \n exponential rate: */\n { \n p = buffer;\n while (!++*p++);\n /* This is where the interesting part comes in; the prefix increment,\n dereference, and logical negation operators all have the same\n precedence and are evaluated **right-to-left**. The postfix\n operator has a higher precedence. *p starts out at zero, is\n incremented to 1 by the prefix, and is negated by !.\n p is incremented by the postfix operator, the condition\n evaluates to false and the loop terminates with buffer[0] = 1.\n\n p is then set to point to buffer[0] again and the loop continues \n until buffer[0] = 255. This time, the loop succeeds when *p is\n incremented, becomes 0 and is negated. This causes the loop to\n run again immediately after p is incremented to point to buffer[1],\n which is increased to 1. The value 1 is of course negated,\n p is incremented which doesn't matter because the loop terminates\n and p is reset to point to buffer[0] again.\n\n This process will continue to increment buffer[0] every time,\n increasing buffer[1] every 256 runs. After 256*255 runs,\n buffer[0] and buffer[1] will both be 255, the loop will succeed\n *twice* and buffer[2] will be incremented once, etc.\n\n The loop will terminate after about 256^256 runs when all the values\n in the buffer array are 255 allowing p to be incremented to the end\n of the array. This will happen sometime after the universe ends,\n maybe a little sooner on the new Intels ;)\n */\n }\n return p - q;\n /* Returns 0 as p == q now */\n}\n</code></pre>\n\n<p>Essentially this is a base-256 (assuming 8-bit bytes) counter with 256 digits, the program will exit when the entire counter \"rolls over\".</p>\n\n<p>The reason this is interesting is because the code is actually completely legal C (no undefined or implementation defined behavior that you usually find in these types of questions) and there is actually a legitimate algorithm problem, albeit a little hidden, in the mix. The reason it is a horrible interview question is because I wouldn't expect anyone to remember the precedence and associativity of the operators involved in the while statement. But it does make for a fun and insightful little exercise.</p>\n"
},
{
"answer_id": 279955,
"author": "Franci Penov",
"author_id": 17028,
"author_profile": "https://Stackoverflow.com/users/17028",
"pm_score": 2,
"selected": false,
"text": "<p>The right answer to this question is:</p>\n\n<blockquote>\n <p>This code is unmaintainable, untestable, serves no purpose and should be removed or rewritten.</p>\n</blockquote>\n\n<p>Anything else means that the interviewee is not thinking as a software engineer.</p>\n\n<p>Than again, you might be not be interviewing for engineering position.</p>\n"
},
{
"answer_id": 280028,
"author": "Charles Graham",
"author_id": 7705,
"author_profile": "https://Stackoverflow.com/users/7705",
"pm_score": -1,
"selected": false,
"text": "<pre><code>unsigned char *p, *q;\n</code></pre>\n\n<p>Isn't this worng on many levels? First of all, is there such a thing as an unsigned char? Second, and I may be wrong here, so don't quote me, but doesn't char *p, <em>q produce funky results? It's either that, or it makes it easy to do char</em> p, q, which would be bad form.</p>\n\n<p>The following is much better:</p>\n\n<pre><code>char* p;\nchar* q;\n</code></pre>\n"
}
] |
2008/11/11
|
[
"https://Stackoverflow.com/questions/279837",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1876/"
] |
It's kind of a C puzzle. You have to tell if the program finish its execution, if so, how much time it takes to run and what it returns to the OS.
```
static unsigned char buffer[256];
int main(void)
{
unsigned char *p, *q;
q = (p = buffer) + sizeof(buffer);
while (q - p)
{
p = buffer;
while (!++*p++);
}
return p - q;
}
```
[EDIT]
I removed the interview-questions tag since that seems to be the primary thing people are objecting to. This is a great little puzzle but as everyone has already pointed out, not a great interview question.
|
Despite the fact that this is a horrible interview question, it is actually quite interesting:
```
static unsigned char buffer[256];
int main(void)
{
unsigned char *p, *q;
q = (p = buffer) + sizeof(buffer);
/* This statement will set p to point to the beginning of buffer and will
set q to point to one past the last element of buffer (this is legal) */
while (q - p)
/* q - p will start out being 256 and will decrease at an inversely
exponential rate: */
{
p = buffer;
while (!++*p++);
/* This is where the interesting part comes in; the prefix increment,
dereference, and logical negation operators all have the same
precedence and are evaluated **right-to-left**. The postfix
operator has a higher precedence. *p starts out at zero, is
incremented to 1 by the prefix, and is negated by !.
p is incremented by the postfix operator, the condition
evaluates to false and the loop terminates with buffer[0] = 1.
p is then set to point to buffer[0] again and the loop continues
until buffer[0] = 255. This time, the loop succeeds when *p is
incremented, becomes 0 and is negated. This causes the loop to
run again immediately after p is incremented to point to buffer[1],
which is increased to 1. The value 1 is of course negated,
p is incremented which doesn't matter because the loop terminates
and p is reset to point to buffer[0] again.
This process will continue to increment buffer[0] every time,
increasing buffer[1] every 256 runs. After 256*255 runs,
buffer[0] and buffer[1] will both be 255, the loop will succeed
*twice* and buffer[2] will be incremented once, etc.
The loop will terminate after about 256^256 runs when all the values
in the buffer array are 255 allowing p to be incremented to the end
of the array. This will happen sometime after the universe ends,
maybe a little sooner on the new Intels ;)
*/
}
return p - q;
/* Returns 0 as p == q now */
}
```
Essentially this is a base-256 (assuming 8-bit bytes) counter with 256 digits, the program will exit when the entire counter "rolls over".
The reason this is interesting is because the code is actually completely legal C (no undefined or implementation defined behavior that you usually find in these types of questions) and there is actually a legitimate algorithm problem, albeit a little hidden, in the mix. The reason it is a horrible interview question is because I wouldn't expect anyone to remember the precedence and associativity of the operators involved in the while statement. But it does make for a fun and insightful little exercise.
|
279,854 |
<p>If I have a vector of pairs:</p>
<pre><code>std::vector<std::pair<int, int> > vec;
</code></pre>
<p>Is there and easy way to sort the list in <strong>increasing</strong> order based on the second element of the pair?</p>
<p>I know I can write a little function object that will do the work, but is there a way to use existing parts of the <em>STL</em> and <code>std::less</code> to do the work directly?</p>
<p>EDIT: I understand that I can write a separate function or class to pass to the third argument to sort. The question is whether or not I can build it out of standard stuff. I'd really something that looks like:</p>
<pre><code>std::sort(vec.begin(), vec.end(), std::something_magic<int, int, std::less>());
</code></pre>
|
[
{
"answer_id": 279863,
"author": "Greg Rogers",
"author_id": 5963,
"author_profile": "https://Stackoverflow.com/users/5963",
"pm_score": 1,
"selected": false,
"text": "<p>You'd have to rely on a non standard <a href=\"http://www.sgi.com/tech/stl/select2nd.html\" rel=\"nofollow noreferrer\">select2nd</a></p>\n"
},
{
"answer_id": 279878,
"author": "Evan Teran",
"author_id": 13430,
"author_profile": "https://Stackoverflow.com/users/13430",
"pm_score": 9,
"selected": true,
"text": "<p><strong>EDIT</strong>: using c++14, the best solution is very easy to write thanks to lambdas that can now have parameters of type <code>auto</code>. <strong>This is my current favorite solution</strong></p>\n<pre><code>std::sort(v.begin(), v.end(), [](auto &left, auto &right) {\n return left.second < right.second;\n});\n</code></pre>\n<hr />\n<p><strong>ORIGINAL ANSWER</strong>:</p>\n<p>Just use a custom comparator (it's an optional 3rd argument to <code>std::sort</code>)</p>\n<pre><code>struct sort_pred {\n bool operator()(const std::pair<int,int> &left, const std::pair<int,int> &right) {\n return left.second < right.second;\n }\n};\n\nstd::sort(v.begin(), v.end(), sort_pred());\n</code></pre>\n<p>If you're using a C++11 compiler, you can write the same using lambdas:</p>\n<pre><code>std::sort(v.begin(), v.end(), [](const std::pair<int,int> &left, const std::pair<int,int> &right) {\n return left.second < right.second;\n});\n</code></pre>\n<p><strong>EDIT</strong>: in response to your edits to your question, here's some thoughts ...\nif you <strong>really</strong> wanna be creative and be able to reuse this concept a lot, just make a template:</p>\n<pre><code>template <class T1, class T2, class Pred = std::less<T2> >\nstruct sort_pair_second {\n bool operator()(const std::pair<T1,T2>&left, const std::pair<T1,T2>&right) {\n Pred p;\n return p(left.second, right.second);\n }\n};\n</code></pre>\n<p>then you can do this too:</p>\n<pre><code>std::sort(v.begin(), v.end(), sort_pair_second<int, int>());\n</code></pre>\n<p>or even</p>\n<pre><code>std::sort(v.begin(), v.end(), sort_pair_second<int, int, std::greater<int> >());\n</code></pre>\n<p>Though to be honest, this is all a bit overkill, just write the 3 line function and be done with it :-P</p>\n"
},
{
"answer_id": 280128,
"author": "Johannes Schaub - litb",
"author_id": 34509,
"author_profile": "https://Stackoverflow.com/users/34509",
"pm_score": 6,
"selected": false,
"text": "<p>You can use boost like this:</p>\n\n<pre><code>std::sort(a.begin(), a.end(), \n boost::bind(&std::pair<int, int>::second, _1) <\n boost::bind(&std::pair<int, int>::second, _2));\n</code></pre>\n\n<p>I don't know a standard way to do this equally short and concise, but you can grab <code>boost::bind</code> it's all consisting of headers.</p>\n"
},
{
"answer_id": 280662,
"author": "Leon Timmermans",
"author_id": 4727,
"author_profile": "https://Stackoverflow.com/users/4727",
"pm_score": 3,
"selected": false,
"text": "<p>For something reusable:</p>\n\n<pre><code>template<template <typename> class P = std::less >\nstruct compare_pair_second {\n template<class T1, class T2> bool operator()(const std::pair<T1, T2>& left, const std::pair<T1, T2>& right) {\n return P<T2>()(left.second, right.second);\n }\n};\n</code></pre>\n\n<p>You can use it as</p>\n\n<pre><code>std::sort(foo.begin(), foo.end(), compare_pair_second<>());\n</code></pre>\n\n<p>or</p>\n\n<pre><code>std::sort(foo.begin(), foo.end(), compare_pair_second<std::less>());\n</code></pre>\n"
},
{
"answer_id": 8002277,
"author": "Andreas Spindler",
"author_id": 887771,
"author_profile": "https://Stackoverflow.com/users/887771",
"pm_score": 5,
"selected": false,
"text": "<p>With C++0x we can use lambda functions:</p>\n\n<pre class=\"lang-cpp prettyprint-override\"><code>using namespace std;\nvector<pair<int, int>> v;\n .\n .\nsort(v.begin(), v.end(),\n [](const pair<int, int>& lhs, const pair<int, int>& rhs) {\n return lhs.second < rhs.second; } );\n</code></pre>\n\n<p>In this example the return type <code>bool</code> is implicitly deduced.</p>\n\n<p><strong>Lambda return types</strong></p>\n\n<p>When a lambda-function has a single statement, and this is a return-statement, the compiler can deduce the return type. From C++11, §5.1.2/4:</p>\n\n<blockquote>\n <p>...</p>\n \n <ul>\n <li>If the compound-statement is of the form <code>{ return expression ; }</code> the type of the returned expression after lvalue-to-rvalue conversion (4.1), array-to-pointer conversion (4.2), and function-to-pointer conversion (4.3);</li>\n <li>otherwise, <code>void</code>.</li>\n </ul>\n</blockquote>\n\n<p>To explicitly specify the return type use the form <code>[]() -> Type { }</code>, like in:</p>\n\n<pre class=\"lang-cpp prettyprint-override\"><code>sort(v.begin(), v.end(),\n [](const pair<int, int>& lhs, const pair<int, int>& rhs) -> bool {\n if (lhs.second == 0)\n return true;\n return lhs.second < rhs.second; } );\n</code></pre>\n"
},
{
"answer_id": 33649456,
"author": "Ezio",
"author_id": 3782306,
"author_profile": "https://Stackoverflow.com/users/3782306",
"pm_score": 5,
"selected": false,
"text": "<p>Its pretty simple\nyou use the sort function from algorithm and add your own compare function</p>\n\n<pre><code>vector< pair<int,int > > v;\nsort(v.begin(),v.end(),myComparison);\n</code></pre>\n\n<p>Now you have to make the comparison based on the second selection \nso declare you \"myComparison\" as</p>\n\n<pre><code>bool myComparison(const pair<int,int> &a,const pair<int,int> &b)\n{\n return a.second<b.second;\n}\n</code></pre>\n"
},
{
"answer_id": 41607852,
"author": "hadizadeh.ali",
"author_id": 5389810,
"author_profile": "https://Stackoverflow.com/users/5389810",
"pm_score": -1,
"selected": false,
"text": "<p>Try swapping the elements of the pairs so you can use <code>std::sort()</code> as normal.</p>\n"
}
] |
2008/11/11
|
[
"https://Stackoverflow.com/questions/279854",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/34502/"
] |
If I have a vector of pairs:
```
std::vector<std::pair<int, int> > vec;
```
Is there and easy way to sort the list in **increasing** order based on the second element of the pair?
I know I can write a little function object that will do the work, but is there a way to use existing parts of the *STL* and `std::less` to do the work directly?
EDIT: I understand that I can write a separate function or class to pass to the third argument to sort. The question is whether or not I can build it out of standard stuff. I'd really something that looks like:
```
std::sort(vec.begin(), vec.end(), std::something_magic<int, int, std::less>());
```
|
**EDIT**: using c++14, the best solution is very easy to write thanks to lambdas that can now have parameters of type `auto`. **This is my current favorite solution**
```
std::sort(v.begin(), v.end(), [](auto &left, auto &right) {
return left.second < right.second;
});
```
---
**ORIGINAL ANSWER**:
Just use a custom comparator (it's an optional 3rd argument to `std::sort`)
```
struct sort_pred {
bool operator()(const std::pair<int,int> &left, const std::pair<int,int> &right) {
return left.second < right.second;
}
};
std::sort(v.begin(), v.end(), sort_pred());
```
If you're using a C++11 compiler, you can write the same using lambdas:
```
std::sort(v.begin(), v.end(), [](const std::pair<int,int> &left, const std::pair<int,int> &right) {
return left.second < right.second;
});
```
**EDIT**: in response to your edits to your question, here's some thoughts ...
if you **really** wanna be creative and be able to reuse this concept a lot, just make a template:
```
template <class T1, class T2, class Pred = std::less<T2> >
struct sort_pair_second {
bool operator()(const std::pair<T1,T2>&left, const std::pair<T1,T2>&right) {
Pred p;
return p(left.second, right.second);
}
};
```
then you can do this too:
```
std::sort(v.begin(), v.end(), sort_pair_second<int, int>());
```
or even
```
std::sort(v.begin(), v.end(), sort_pair_second<int, int, std::greater<int> >());
```
Though to be honest, this is all a bit overkill, just write the 3 line function and be done with it :-P
|
279,860 |
<h2>Background</h2>
<p>I'm trying out Scons by setting up a basic C++ sample project that has two sub-projects: </p>
<ul>
<li>Prj1 is an EXE that depends on Prj2</li>
<li>Prj2 is a DLL that exports some functions</li>
</ul>
<p>The problem I'm running into is that the library builds its .obj, .pdb, .lib, .dll, etc. files in the same directory as it's SConscript file while the EXE builds its files in the same directory as its SConscript. The application successfully builds both the Prj2 dependency and itself. However, you cannot run the resulting EXE because it can't find the library it needs because it is in the other directory.</p>
<h2>Question</h2>
<p>How can I get multiple projects that have dependences to output their binaries and debug information into a common directory so that they can be executed and debugged?</p>
<h2>Potential Solutions</h2>
<p>This is what I have thought of so far:</p>
<ul>
<li>I tried using VariantDir (previously called BuildDir) however this doesn't seem to work. Perhaps I'm messing something up here.</li>
<li>I could potentially tell the compiler and the linker explicitly (via Fo/Fd for example) where to drop their files (is this the best or only solution???)</li>
<li>Execute a copy command on the resulting binaries (this seems like a hack and quite a pain to manage/maintain)</li>
</ul>
<h2>Update</h2>
<p>I updated the File Structure and file contents below to reflect the working solution in it's entirety. Thanks to grieve for his insight.</p>
<h2>Command</h2>
<p>With this configuration, you must unfortunately execute the build by cd'ing to the build directory and then running the command below. I need to get a properly working alias setup to get around this.</p>
<pre><code>
build> scons ../bin/project1.exe
</code></pre>
<h2>File Structure</h2>
<pre><code> /scons-sample
/bin
/release
/debug
/build
SConstruct
scons_helper.py
/prj1
SConscript
/include
/src
main.cpp
/prj2
SConscript
/include
functions.h
/src
functions.cpp
</code></pre>
<h2>SConstruct</h2>
<pre><code>
import os.path
BIN_DIR = '../bin'
OBJ_DIR = './obj'
#--------------------------------------
# CxxTest Options
#--------------------------------------
CXXTEST_DIR = '../extern/CxxTest/CxxTest-latest'
PERL = 'perl -w'
TESTS = '*.h'
TESTGEN = PERL + CXXTEST_DIR + '/cxxtestgen.pl'
CXXTESTGEN_FLAGS = '--runner=ParenPrinter \
--abort-on-fail \
--have-eh'
#--------------------------------------
# Options
#--------------------------------------
SetOption( 'implicit_cache', 1 )
# command line options
opts = Options()
opts.AddOptions(
EnumOption(
'debug',
'Debug version (useful for developers only)',
'no',
allowed_values = ('yes', 'no'),
map = { },
ignorecase = 1
)
)
#--------------------------------------
# Environment
#--------------------------------------
env = Environment(
options = opts,
#--------------------------------------
# Linker Options
#--------------------------------------
LIBPATH = [
'../extern/wxWidgets/wxWidgets-latest/lib/vc_dll'
],
LIBS = [
# 'wxmsw28d_core.lib',
# 'wxbase28d.lib',
# 'wxbase28d_odbc.lib',
# 'wxbase28d_net.lib',
'kernel32.lib',
'user32.lib',
'gdi32.lib',
'winspool.lib',
'comdlg32.lib',
'advapi32.lib',
'shell32.lib',
'ole32.lib',
'oleaut32.lib',
'uuid.lib',
'odbc32.lib',
'odbccp32.lib'
],
LINKFLAGS = '/nologo /subsystem:console /incremental:yes /debug /machine:I386',
#--------------------------------------
# Compiler Options
#--------------------------------------
CPPPATH = [
'./include/',
'../extern/wxWidgets/wxWidgets-latest/include',
'../extern/wxWidgets/wxWidgets-latest/vc_dll/mswd'
],
CPPDEFINES = [
'WIN32',
'_DEBUG',
'_CONSOLE',
'_MBCS',
'WXUSINGDLL',
'__WXDEBUG__'
],
CCFLAGS = '/W4 /EHsc /RTC1 /MDd /nologo /Zi /TP /errorReport:prompt'
)
env.Decider( 'MD5-timestamp' ) # For speed, use timestamps for change, followed by MD5
Export( 'env', 'BIN_DIR' ) # Export this environment for use by the SConscript files
#--------------------------------------
# Builders
#--------------------------------------
SConscript( '../prj1/SConscript' )
SConscript( '../prj2/SConscript' )
Default( 'prj1' )
</code></pre>
<h2>scons_helper.py</h2>
<pre><code>
import os.path
#--------------------------------------
# Functions
#--------------------------------------
# Prepends the full path information to the output directory so that the build
# files are dropped into the directory specified by trgt rather than in the
# same directory as the SConscript file.
#
# Parameters:
# env - The environment to assign the Program value for
# outdir - The relative path to the location you want the Program binary to be placed
# trgt - The target application name (without extension)
# srcs - The list of source files
# Ref:
# Credit grieve and his local SCons guru for this:
# http://stackoverflow.com/questions/279860/how-do-i-get-projects-to-place-their-build-output-into-the-same-directory-with
def PrefixProgram(env, outdir, trgt, srcs):
env.Program(target = os.path.join(outdir, trgt), source = srcs)
# Similar to PrefixProgram above, except for SharedLibrary
def PrefixSharedLibrary(env, outdir, trgt, srcs):
env.SharedLibrary(target = os.path.join(outdir, trgt), source = srcs)
def PrefixFilename(filename, extensions):
return [(filename + ext) for ext in extensions]
# Prefix the source files names with the source directory
def PrefixSources(srcdir, srcs):
return [os.path.join(srcdir, x) for x in srcs]
</code></pre>
<h2>SConscript for Prj1</h2>
<pre><code>
import os.path
import sys
sys.path.append( '../build' )
from scons_helper import *
Import( 'env', 'BIN_DIR' ) # Import the common environment
prj1_env = env.Clone() # Clone it so we don't make changes to the global one
#--------------------------------------
# Project Options
#--------------------------------------
PROG = 'project1'
#--------------------------------------
# Header Files
#--------------------------------------
INC_DIR = [
'../prj2/include'
]
HEADERS = [
''
]
#--------------------------------------
# Source Files
#--------------------------------------
SRC_DIR = './src'
SOURCES = [
'main.cpp'
]
# Prefix the source files names with the source directory
SOURCES = PrefixSources( SRC_DIR, SOURCES )
#--------------------------------------
# Compiler and Linker Overrides
#--------------------------------------
prj1_env.Append(
CPPPATH = INC_DIR,
LIBS = 'project2',
LIBPATH = BIN_DIR,
# Microsoft Visual Studio Specific
PDB = os.path.join( BIN_DIR, PROG + '.pdb' )
)
#--------------------------------------
# Builders
#--------------------------------------
PrefixProgram( prj1_env, BIN_DIR, PROG, SOURCES )
</code></pre>
<h2>SConscript for Prj2</h2>
<pre><code>
import os.path
import sys
sys.path.append( '../build' )
from scons_helper import *
Import( 'env', 'BIN_DIR' ) # Import the common environment
prj2_env = env.Clone() # Clone it so we don't make changes to the global one
#--------------------------------------
# Project Options
#--------------------------------------
PROG = 'project2'
#--------------------------------------
# Header Files
#--------------------------------------
INC_DIR = [
''
]
HEADERS = [
'functions.h'
]
#--------------------------------------
# Source Files
#--------------------------------------
SRC_DIR = './src/'
SOURCES = [
'functions.cpp'
]
# Prefix the source files names with the source directory
SOURCES = PrefixSources( SRC_DIR, SOURCES )
#--------------------------------------
# Compiler and Linker Overrides
#--------------------------------------
# Update the environment with the project specific information
prj2_env.Append(
CPPPATH = INC_DIR,
# Microsoft Visual Studio Specific
PDB = os.path.join( BIN_DIR, PROG + '.pdb' )
)
#--------------------------------------
# Builders
#--------------------------------------
PrefixSharedLibrary( prj2_env, BIN_DIR, PROG, SOURCES )
</code></pre>
|
[
{
"answer_id": 279883,
"author": "grieve",
"author_id": 34329,
"author_profile": "https://Stackoverflow.com/users/34329",
"pm_score": 2,
"selected": false,
"text": "<p>VariantDir is the way to do this. How does your Sconstruct call your Sconscript files? Also have you read this section of the documentation: <a href=\"http://www.scons.org/doc/1.1.0/HTML/scons-user/c3271.html\" rel=\"nofollow noreferrer\">http://www.scons.org/doc/1.1.0/HTML/scons-user/c3271.html</a> (I assume you have).</p>\n\n<hr>\n\n<p>The more I think about it the more I think you want to use a combination of <A href=\"http://www.scons.org/doc/1.1.0/HTML/scons-user/x2720.html#AEN2739\" rel=\"nofollow noreferrer\">Default</A> and <A href=\"http://www.scons.org/doc/1.1.0/HTML/scons-user/c2848.html\" rel=\"nofollow noreferrer\">Install</A></p>\n\n<p>In your SConscripts call</p>\n\n<pre><code>env.Install(\"../bin\", <your target exe or dll>)\n</code></pre>\n\n<p>then in your Sconstruct call </p>\n\n<pre><code>env.Alias('install', \"../bin\")\nDefault('install')\n</code></pre>\n\n<p>That should do the trick, and I think the links make it clear how it all works together.</p>\n"
},
{
"answer_id": 281103,
"author": "grieve",
"author_id": 34329,
"author_profile": "https://Stackoverflow.com/users/34329",
"pm_score": 4,
"selected": true,
"text": "<p>Ok Third try is a charm. I am just placing this in a new answer to keep it cleaner. I talked with my local scons guru, and he stated that the install method should work, but there is a much easier way.</p>\n\n<p>Simply define the full path where you want the executable (or dll) to go. So:</p>\n\n<pre><code>prj2_env.Program(target = os.path.join(BIN_DIR,PROG), source = SOURCES )\n</code></pre>\n\n<p>If you don't want to have to do this in all places you can make a global function:</p>\n\n<pre><code>def PrefixProgram(env, trgt, srcs):\n env.Program(target = os.path.join(env.[\"MY_OUTPUT_DIR\"], trgt), source = srcs)\n</code></pre>\n\n<p>Then in your SConscript, something like:</p>\n\n<pre><code>import ('PrefixProgram')\n# stuff ...\nPrefixProgram(prj2_env, PROG, SOURCES)\n</code></pre>\n\n<p>Note that you can add your own attribute to the environment, which is where the</p>\n\n<pre><code>env[\"MY_OUTPUT_DIR\"]\n</code></pre>\n\n<p>comes from. I wrote this off the cuff, so expect some minor syntax errors and what not. Obviously you can apply the same trick for shared and static libraries.</p>\n\n<p>In the interest of full disclosure I offered my local scons guru the chance to answer this himself, but he was scared he would become addicted to the site and declined. :)</p>\n"
}
] |
2008/11/11
|
[
"https://Stackoverflow.com/questions/279860",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2233/"
] |
Background
----------
I'm trying out Scons by setting up a basic C++ sample project that has two sub-projects:
* Prj1 is an EXE that depends on Prj2
* Prj2 is a DLL that exports some functions
The problem I'm running into is that the library builds its .obj, .pdb, .lib, .dll, etc. files in the same directory as it's SConscript file while the EXE builds its files in the same directory as its SConscript. The application successfully builds both the Prj2 dependency and itself. However, you cannot run the resulting EXE because it can't find the library it needs because it is in the other directory.
Question
--------
How can I get multiple projects that have dependences to output their binaries and debug information into a common directory so that they can be executed and debugged?
Potential Solutions
-------------------
This is what I have thought of so far:
* I tried using VariantDir (previously called BuildDir) however this doesn't seem to work. Perhaps I'm messing something up here.
* I could potentially tell the compiler and the linker explicitly (via Fo/Fd for example) where to drop their files (is this the best or only solution???)
* Execute a copy command on the resulting binaries (this seems like a hack and quite a pain to manage/maintain)
Update
------
I updated the File Structure and file contents below to reflect the working solution in it's entirety. Thanks to grieve for his insight.
Command
-------
With this configuration, you must unfortunately execute the build by cd'ing to the build directory and then running the command below. I need to get a properly working alias setup to get around this.
```
build> scons ../bin/project1.exe
```
File Structure
--------------
```
/scons-sample
/bin
/release
/debug
/build
SConstruct
scons_helper.py
/prj1
SConscript
/include
/src
main.cpp
/prj2
SConscript
/include
functions.h
/src
functions.cpp
```
SConstruct
----------
```
import os.path
BIN_DIR = '../bin'
OBJ_DIR = './obj'
#--------------------------------------
# CxxTest Options
#--------------------------------------
CXXTEST_DIR = '../extern/CxxTest/CxxTest-latest'
PERL = 'perl -w'
TESTS = '*.h'
TESTGEN = PERL + CXXTEST_DIR + '/cxxtestgen.pl'
CXXTESTGEN_FLAGS = '--runner=ParenPrinter \
--abort-on-fail \
--have-eh'
#--------------------------------------
# Options
#--------------------------------------
SetOption( 'implicit_cache', 1 )
# command line options
opts = Options()
opts.AddOptions(
EnumOption(
'debug',
'Debug version (useful for developers only)',
'no',
allowed_values = ('yes', 'no'),
map = { },
ignorecase = 1
)
)
#--------------------------------------
# Environment
#--------------------------------------
env = Environment(
options = opts,
#--------------------------------------
# Linker Options
#--------------------------------------
LIBPATH = [
'../extern/wxWidgets/wxWidgets-latest/lib/vc_dll'
],
LIBS = [
# 'wxmsw28d_core.lib',
# 'wxbase28d.lib',
# 'wxbase28d_odbc.lib',
# 'wxbase28d_net.lib',
'kernel32.lib',
'user32.lib',
'gdi32.lib',
'winspool.lib',
'comdlg32.lib',
'advapi32.lib',
'shell32.lib',
'ole32.lib',
'oleaut32.lib',
'uuid.lib',
'odbc32.lib',
'odbccp32.lib'
],
LINKFLAGS = '/nologo /subsystem:console /incremental:yes /debug /machine:I386',
#--------------------------------------
# Compiler Options
#--------------------------------------
CPPPATH = [
'./include/',
'../extern/wxWidgets/wxWidgets-latest/include',
'../extern/wxWidgets/wxWidgets-latest/vc_dll/mswd'
],
CPPDEFINES = [
'WIN32',
'_DEBUG',
'_CONSOLE',
'_MBCS',
'WXUSINGDLL',
'__WXDEBUG__'
],
CCFLAGS = '/W4 /EHsc /RTC1 /MDd /nologo /Zi /TP /errorReport:prompt'
)
env.Decider( 'MD5-timestamp' ) # For speed, use timestamps for change, followed by MD5
Export( 'env', 'BIN_DIR' ) # Export this environment for use by the SConscript files
#--------------------------------------
# Builders
#--------------------------------------
SConscript( '../prj1/SConscript' )
SConscript( '../prj2/SConscript' )
Default( 'prj1' )
```
scons\_helper.py
----------------
```
import os.path
#--------------------------------------
# Functions
#--------------------------------------
# Prepends the full path information to the output directory so that the build
# files are dropped into the directory specified by trgt rather than in the
# same directory as the SConscript file.
#
# Parameters:
# env - The environment to assign the Program value for
# outdir - The relative path to the location you want the Program binary to be placed
# trgt - The target application name (without extension)
# srcs - The list of source files
# Ref:
# Credit grieve and his local SCons guru for this:
# http://stackoverflow.com/questions/279860/how-do-i-get-projects-to-place-their-build-output-into-the-same-directory-with
def PrefixProgram(env, outdir, trgt, srcs):
env.Program(target = os.path.join(outdir, trgt), source = srcs)
# Similar to PrefixProgram above, except for SharedLibrary
def PrefixSharedLibrary(env, outdir, trgt, srcs):
env.SharedLibrary(target = os.path.join(outdir, trgt), source = srcs)
def PrefixFilename(filename, extensions):
return [(filename + ext) for ext in extensions]
# Prefix the source files names with the source directory
def PrefixSources(srcdir, srcs):
return [os.path.join(srcdir, x) for x in srcs]
```
SConscript for Prj1
-------------------
```
import os.path
import sys
sys.path.append( '../build' )
from scons_helper import *
Import( 'env', 'BIN_DIR' ) # Import the common environment
prj1_env = env.Clone() # Clone it so we don't make changes to the global one
#--------------------------------------
# Project Options
#--------------------------------------
PROG = 'project1'
#--------------------------------------
# Header Files
#--------------------------------------
INC_DIR = [
'../prj2/include'
]
HEADERS = [
''
]
#--------------------------------------
# Source Files
#--------------------------------------
SRC_DIR = './src'
SOURCES = [
'main.cpp'
]
# Prefix the source files names with the source directory
SOURCES = PrefixSources( SRC_DIR, SOURCES )
#--------------------------------------
# Compiler and Linker Overrides
#--------------------------------------
prj1_env.Append(
CPPPATH = INC_DIR,
LIBS = 'project2',
LIBPATH = BIN_DIR,
# Microsoft Visual Studio Specific
PDB = os.path.join( BIN_DIR, PROG + '.pdb' )
)
#--------------------------------------
# Builders
#--------------------------------------
PrefixProgram( prj1_env, BIN_DIR, PROG, SOURCES )
```
SConscript for Prj2
-------------------
```
import os.path
import sys
sys.path.append( '../build' )
from scons_helper import *
Import( 'env', 'BIN_DIR' ) # Import the common environment
prj2_env = env.Clone() # Clone it so we don't make changes to the global one
#--------------------------------------
# Project Options
#--------------------------------------
PROG = 'project2'
#--------------------------------------
# Header Files
#--------------------------------------
INC_DIR = [
''
]
HEADERS = [
'functions.h'
]
#--------------------------------------
# Source Files
#--------------------------------------
SRC_DIR = './src/'
SOURCES = [
'functions.cpp'
]
# Prefix the source files names with the source directory
SOURCES = PrefixSources( SRC_DIR, SOURCES )
#--------------------------------------
# Compiler and Linker Overrides
#--------------------------------------
# Update the environment with the project specific information
prj2_env.Append(
CPPPATH = INC_DIR,
# Microsoft Visual Studio Specific
PDB = os.path.join( BIN_DIR, PROG + '.pdb' )
)
#--------------------------------------
# Builders
#--------------------------------------
PrefixSharedLibrary( prj2_env, BIN_DIR, PROG, SOURCES )
```
|
Ok Third try is a charm. I am just placing this in a new answer to keep it cleaner. I talked with my local scons guru, and he stated that the install method should work, but there is a much easier way.
Simply define the full path where you want the executable (or dll) to go. So:
```
prj2_env.Program(target = os.path.join(BIN_DIR,PROG), source = SOURCES )
```
If you don't want to have to do this in all places you can make a global function:
```
def PrefixProgram(env, trgt, srcs):
env.Program(target = os.path.join(env.["MY_OUTPUT_DIR"], trgt), source = srcs)
```
Then in your SConscript, something like:
```
import ('PrefixProgram')
# stuff ...
PrefixProgram(prj2_env, PROG, SOURCES)
```
Note that you can add your own attribute to the environment, which is where the
```
env["MY_OUTPUT_DIR"]
```
comes from. I wrote this off the cuff, so expect some minor syntax errors and what not. Obviously you can apply the same trick for shared and static libraries.
In the interest of full disclosure I offered my local scons guru the chance to answer this himself, but he was scared he would become addicted to the site and declined. :)
|
279,907 |
<p>What is the best way to display a checkbox in a Crystal Report?</p>
<p>Example: My report has a box for "Male" and "Female", and one should be checked.</p>
<p>My current workaround is to draw a small graphical square, and line it up with a formula which goes like this:</p>
<pre><code>if {table.gender} = "M" then "X" else " "
</code></pre>
<p>This is a poor solution, because changing the font misaligns my "X" and the box around it, and it is absurdly tedious to squint at the screen and get a pixel-perfect alignment for every box (there are dozens).</p>
<p>Does anyone have a better solution? I've thought about using the old-style terminal characters, but I'm not sure if they display properly in Crystal.</p>
<p><em>Edit: I'm using Crystal XI.</em></p>
|
[
{
"answer_id": 279929,
"author": "Mark Bostleman",
"author_id": 22355,
"author_profile": "https://Stackoverflow.com/users/22355",
"pm_score": 3,
"selected": true,
"text": "<p>Try a pair of images with a conditional formula for visibility</p>\n"
},
{
"answer_id": 279932,
"author": "Hapkido",
"author_id": 27646,
"author_profile": "https://Stackoverflow.com/users/27646",
"pm_score": 1,
"selected": false,
"text": "<p>2 pictures<br>\n1 - Empty box<br>\n2 - Checked box</p>\n\n<p>Display the right picture with a formula</p>\n"
},
{
"answer_id": 281304,
"author": "jons911",
"author_id": 34375,
"author_profile": "https://Stackoverflow.com/users/34375",
"pm_score": 2,
"selected": false,
"text": "<p>An alternative to images could be to use the Wingdings font; Characters <code>0xFE</code> (checked) and <code>0xA8</code> (unchecked).</p>\n"
},
{
"answer_id": 322311,
"author": "dotjoe",
"author_id": 40822,
"author_profile": "https://Stackoverflow.com/users/40822",
"pm_score": 2,
"selected": false,
"text": "<p>I never use a box...I always use a textfield object with a full border, centered alignment and bold. Type an X inside to size it right. Erase the \"X\". Copy/paste as many as you need.</p>\n\n<p>Then I create all the formulas that return either \"X\" or \" \" (the space is important, otherwise border will not display on the text object). Then simply plop the formula fields into the right boxes.</p>\n\n<p>Also, if you want to align these bordered text objects you need to remove the border before aligning. That bug really annoys me!</p>\n"
},
{
"answer_id": 2891048,
"author": "hatem gamil",
"author_id": 298416,
"author_profile": "https://Stackoverflow.com/users/298416",
"pm_score": 3,
"selected": false,
"text": "<pre><code>If {Table.Field} = True Then\n\n'Display the checkbox of your choice here\n\nFormula = Chr(254)\n\nElse\n\n'Display empty checkbox\n\nFormula = Chr(168)\n\nEnd If\n</code></pre>\n"
},
{
"answer_id": 9060100,
"author": "am2",
"author_id": 1177465,
"author_profile": "https://Stackoverflow.com/users/1177465",
"pm_score": 2,
"selected": false,
"text": "<p>I need to mention here which is font need's to select here \"Wingdings\"</p>\n\n<pre><code>If {Table.Field} = True Then\n\n'Display the checkbox of your choice here\n\nFormula = Chr(254)\n\nElse\n\n'Display empty checkbox\n\nFormula = Chr(168)\n\nEnd If\n</code></pre>\n"
},
{
"answer_id": 40028863,
"author": "abi",
"author_id": 6780274,
"author_profile": "https://Stackoverflow.com/users/6780274",
"pm_score": 1,
"selected": false,
"text": "<ol>\n<li>Create a Formula Field and use the following formula</li>\n</ol>\n\n<p>if {Your Field} = true then \n Chr(254) \nelse\n Chr(168)</p>\n\n<ol start=\"2\">\n<li><p>Add the Formula field to the report where you want the checkbox to appear.</p></li>\n<li><p>Now change the font of the formula field to Wingdings.</p></li>\n</ol>\n"
}
] |
2008/11/11
|
[
"https://Stackoverflow.com/questions/279907",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/672/"
] |
What is the best way to display a checkbox in a Crystal Report?
Example: My report has a box for "Male" and "Female", and one should be checked.
My current workaround is to draw a small graphical square, and line it up with a formula which goes like this:
```
if {table.gender} = "M" then "X" else " "
```
This is a poor solution, because changing the font misaligns my "X" and the box around it, and it is absurdly tedious to squint at the screen and get a pixel-perfect alignment for every box (there are dozens).
Does anyone have a better solution? I've thought about using the old-style terminal characters, but I'm not sure if they display properly in Crystal.
*Edit: I'm using Crystal XI.*
|
Try a pair of images with a conditional formula for visibility
|
279,919 |
<p>Is there a C function call that can change the last modified date of a file or directory in Windows?</p>
|
[
{
"answer_id": 279930,
"author": "Rob Kennedy",
"author_id": 33732,
"author_profile": "https://Stackoverflow.com/users/33732",
"pm_score": 1,
"selected": false,
"text": "<p>Yes. You can use the <a href=\"http://msdn.microsoft.com/en-us/library/ms724933.aspx\" rel=\"nofollow noreferrer\">SetFileTime</a> API function.</p>\n"
},
{
"answer_id": 279931,
"author": "FlySwat",
"author_id": 1965,
"author_profile": "https://Stackoverflow.com/users/1965",
"pm_score": 2,
"selected": false,
"text": "<p>Use SetFileTime:</p>\n\n<pre><code>BOOL WINAPI SetFileTime(\n __in HANDLE hFile,\n __in_opt const FILETIME *lpCreationTime,\n __in_opt const FILETIME *lpLastAccessTime,\n __in_opt const FILETIME *lpLastWriteTime\n);\n</code></pre>\n\n<p>Its in winbase.h, so you just need to include windows.h</p>\n\n<p>EDIT: I pasted the wrong function.</p>\n"
},
{
"answer_id": 279944,
"author": "Christian C. Salvadó",
"author_id": 5445,
"author_profile": "https://Stackoverflow.com/users/5445",
"pm_score": 3,
"selected": false,
"text": "<p>You can use the <a href=\"http://msdn.microsoft.com/en-us/library/ms724933(VS.85).aspx\" rel=\"noreferrer\">SetFileTime</a> function, for the directories, you have to use the <a href=\"http://msdn.microsoft.com/en-us/library/aa363858(VS.85).aspx\" rel=\"noreferrer\">CreateFile</a> function with the FILE_FLAG_BACKUP_SEMANTICS flag to get the directory handle and use it as the file handle parameter of the SetFileTime like this:</p>\n\n<pre><code>hFolder = CreateFile(path, GENERIC_WRITE, FILE_SHARE_READ, NULL, OPEN_EXISTING,\nFILE_ATTRIBUTE_DIRECTORY | FILE_FLAG_BACKUP_SEMANTICS, NULL);\n</code></pre>\n"
}
] |
2008/11/11
|
[
"https://Stackoverflow.com/questions/279919",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] |
Is there a C function call that can change the last modified date of a file or directory in Windows?
|
You can use the [SetFileTime](http://msdn.microsoft.com/en-us/library/ms724933(VS.85).aspx) function, for the directories, you have to use the [CreateFile](http://msdn.microsoft.com/en-us/library/aa363858(VS.85).aspx) function with the FILE\_FLAG\_BACKUP\_SEMANTICS flag to get the directory handle and use it as the file handle parameter of the SetFileTime like this:
```
hFolder = CreateFile(path, GENERIC_WRITE, FILE_SHARE_READ, NULL, OPEN_EXISTING,
FILE_ATTRIBUTE_DIRECTORY | FILE_FLAG_BACKUP_SEMANTICS, NULL);
```
|
279,945 |
<p>I have a file <code>test.txt</code> that is inside a zip archive <code>test.zip</code>. The permissions on <code>test.txt</code> are out of my control when it's compressed, but now I want them to be group-writeable. I am extracting the file with Python, and don't want to escape out to the shell.</p>
<p><strong>EDIT:</strong>
Here's what I've got so far:</p>
<pre><code>import zipfile
z = zipfile.ZipFile('test.zip', 'w')
zi = zipfile.ZipInfo('test.txt')
zi.external_attr = 0777 << 16L
z.writestr(zi, 'FOO')
z.close()
z = zipfile.ZipFile('test.zip', 'r')
for name in z.namelist():
newFile = open(name, "wb")
newFile.write(z.read(name))
newFile.close()
z.close()
</code></pre>
<p>This works perfectly on OS X using 2.5.1, but it doesn't work on my home box (Debian, Python 2.4 & 2.5) or on RHEL 5 with Python 2.4. On anything but OS X it doesn't error, but doesn't change the permissions either. Any ideas why? Also, how does <code>writestr()</code> work? I know I'm using it incorrectly here.</p>
<p>Is there a way to do this without <code>os.chmod</code> (the user extracting the file doesn't have permissions to use <code>os.chmod</code> after it's extracted)? I have full write access to the zip file.</p>
<p>More info:</p>
<pre><code>> ls -l test.zip
-rwxrwxrwx 1 myuser mygroup 2008-11-11 13:24 test.zip
> unzip test.zip
Archive: test.zip
inflating: test.txt
> ls -l test.txt
-rw-r--r-- 1 myuser mygroup 2008-11-11 13:34 test.txt
</code></pre>
<p>The user extracting is not <code>myuser</code>, but is in <code>mygroup</code>.</p>
|
[
{
"answer_id": 279975,
"author": "Chris",
"author_id": 15578,
"author_profile": "https://Stackoverflow.com/users/15578",
"pm_score": 1,
"selected": false,
"text": "<p>Per the documentation, unzip sets the permissions to those stored, under unix. Also, the shell umask is not used. Your best bet is to make sure the perms are set before you zip the file.</p>\n\n<p>Since you can't do that, you will have to try and do what you were trying to do (and get it to work under Debian.)</p>\n\n<p>There have been a number of issues with Pythons zipfile library, including setting the mode of writestr to that of the file being written on some systems, or setting the zip systm to windows instead of unix. So your inconsistent results may mean that nothing has changed.</p>\n\n<p>So you may be completely out of luck.</p>\n"
},
{
"answer_id": 279985,
"author": "John Fouhy",
"author_id": 15154,
"author_profile": "https://Stackoverflow.com/users/15154",
"pm_score": 0,
"selected": false,
"text": "<p>Extract to stdout (unzip -p) and redirect to a file? If there's more than one file in the zip, you could list the zip contents, and then extract one at a time.</p>\n\n<pre><code>for n in `unzip -l test.zip | awk 'NR > 3 && NF == 4 { print $4 }'`; do unzip -p test.zip $n > $n; done\n</code></pre>\n\n<p>(yeah, I know you tagged this 'python' :-) )</p>\n"
},
{
"answer_id": 596455,
"author": "Petriborg",
"author_id": 2815,
"author_profile": "https://Stackoverflow.com/users/2815",
"pm_score": 3,
"selected": false,
"text": "<p>I had a similar problem to you, so here is the code spinet from my stuff, this I believe should help here.</p>\n\n<pre><code># extract all of the zip\nfor file in zf.filelist:\n name = file.filename\n perm = ((file.external_attr >> 16L) & 0777)\n if name.endswith('/'):\n outfile = os.path.join(dir, name)\n os.mkdir(outfile, perm)\n else:\n outfile = os.path.join(dir, name)\n fh = os.open(outfile, os.O_CREAT | os.O_WRONLY , perm)\n os.write(fh, zf.read(name))\n os.close(fh)\n print \"Extracting: \" + outfile\n</code></pre>\n\n<p>You might do something similar, but insert your own logic to calculate your perm value. I should note that I'm using Python 2.5 here, I'm aware of a few incompatibilities with some versions of Python's zipfile support.</p>\n"
},
{
"answer_id": 66880535,
"author": "Mike T",
"author_id": 327026,
"author_profile": "https://Stackoverflow.com/users/327026",
"pm_score": 1,
"selected": false,
"text": "<p>@Petriborg's answer is still relevant, but to work with Python 3, here is a version with the necessary fixes:</p>\n<pre><code>import os\nimport zipfile\n\nzip_file = "/path/to/archive.zip"\nout_dir = "/path/to/output"\n\nos.makedirs(out_dir, exist_ok=True)\n\nwith zipfile.ZipFile(zip_file, "r") as zf:\n for file in zf.filelist:\n name = file.filename\n perm = ((file.external_attr >> 16) & 0o777)\n print("Extracting: " + name)\n if name.endswith("/"):\n os.mkdir(os.path.join(out_dir, name), perm)\n else:\n outfile = os.path.join(out_dir, name)\n fh = os.open(outfile, os.O_CREAT | os.O_WRONLY, perm)\n os.write(fh, zf.read(name))\n os.close(fh)\n</code></pre>\n"
}
] |
2008/11/11
|
[
"https://Stackoverflow.com/questions/279945",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1057/"
] |
I have a file `test.txt` that is inside a zip archive `test.zip`. The permissions on `test.txt` are out of my control when it's compressed, but now I want them to be group-writeable. I am extracting the file with Python, and don't want to escape out to the shell.
**EDIT:**
Here's what I've got so far:
```
import zipfile
z = zipfile.ZipFile('test.zip', 'w')
zi = zipfile.ZipInfo('test.txt')
zi.external_attr = 0777 << 16L
z.writestr(zi, 'FOO')
z.close()
z = zipfile.ZipFile('test.zip', 'r')
for name in z.namelist():
newFile = open(name, "wb")
newFile.write(z.read(name))
newFile.close()
z.close()
```
This works perfectly on OS X using 2.5.1, but it doesn't work on my home box (Debian, Python 2.4 & 2.5) or on RHEL 5 with Python 2.4. On anything but OS X it doesn't error, but doesn't change the permissions either. Any ideas why? Also, how does `writestr()` work? I know I'm using it incorrectly here.
Is there a way to do this without `os.chmod` (the user extracting the file doesn't have permissions to use `os.chmod` after it's extracted)? I have full write access to the zip file.
More info:
```
> ls -l test.zip
-rwxrwxrwx 1 myuser mygroup 2008-11-11 13:24 test.zip
> unzip test.zip
Archive: test.zip
inflating: test.txt
> ls -l test.txt
-rw-r--r-- 1 myuser mygroup 2008-11-11 13:34 test.txt
```
The user extracting is not `myuser`, but is in `mygroup`.
|
I had a similar problem to you, so here is the code spinet from my stuff, this I believe should help here.
```
# extract all of the zip
for file in zf.filelist:
name = file.filename
perm = ((file.external_attr >> 16L) & 0777)
if name.endswith('/'):
outfile = os.path.join(dir, name)
os.mkdir(outfile, perm)
else:
outfile = os.path.join(dir, name)
fh = os.open(outfile, os.O_CREAT | os.O_WRONLY , perm)
os.write(fh, zf.read(name))
os.close(fh)
print "Extracting: " + outfile
```
You might do something similar, but insert your own logic to calculate your perm value. I should note that I'm using Python 2.5 here, I'm aware of a few incompatibilities with some versions of Python's zipfile support.
|
279,953 |
<p>I am using a service component through ASP.NET MVC.
I would like to send the email in a asynchronous way to let the user do other stuff without having to wait for the sending.</p>
<p>When I send a message without attachments it works fine.
When I send a message with at least one in-memory attachment it fails.</p>
<p>So, I would like to know if it is possible to use an async method with in-memory attachments.</p>
<p>Here is the sending method</p>
<pre><code>
public static void Send() {
MailMessage message = new MailMessage("[email protected]", "[email protected]");
using (MemoryStream stream = new MemoryStream(new byte[64000])) {
Attachment attachment = new Attachment(stream, "my attachment");
message.Attachments.Add(attachment);
message.Body = "This is an async test.";
SmtpClient smtp = new SmtpClient("localhost");
smtp.Credentials = new NetworkCredential("foo", "bar");
smtp.SendAsync(message, null);
}
}
</code></pre>
<p>Here is my current error</p>
<pre><code>
System.Net.Mail.SmtpException: Failure sending mail.
---> System.NotSupportedException: Stream does not support reading.
at System.Net.Mime.MimeBasePart.EndSend(IAsyncResult asyncResult)
at System.Net.Mail.Message.EndSend(IAsyncResult asyncResult)
at System.Net.Mail.SmtpClient.SendMessageCallback(IAsyncResult result)
--- End of inner exception stack trace ---
</code></pre>
<hr>
<p>Solution</p>
<pre><code> public static void Send()
{
MailMessage message = new MailMessage("[email protected]", "[email protected]");
MemoryStream stream = new MemoryStream(new byte[64000]);
Attachment attachment = new Attachment(stream, "my attachment");
message.Attachments.Add(attachment);
message.Body = "This is an async test.";
SmtpClient smtp = new SmtpClient("localhost");
//smtp.Credentials = new NetworkCredential("login", "password");
smtp.SendCompleted += delegate(object sender, System.ComponentModel.AsyncCompletedEventArgs e)
{
if (e.Error != null)
{
System.Diagnostics.Trace.TraceError(e.Error.ToString());
}
MailMessage userMessage = e.UserState as MailMessage;
if (userMessage != null)
{
userMessage.Dispose();
}
};
smtp.SendAsync(message, message);
}
</code></pre>
|
[
{
"answer_id": 280316,
"author": "Robert Vuković",
"author_id": 438025,
"author_profile": "https://Stackoverflow.com/users/438025",
"pm_score": 0,
"selected": false,
"text": "<p>I have tried your function and it works even for email with in memory attachments. But here are some remarks:</p>\n\n<ul>\n<li>What type of attachments did you try to send ? Exe ?</li>\n<li>Are both sender and receiver on the same email server ?</li>\n<li>You should “catch” exception and not just swallow it, than you will get more info about your problem.</li>\n<li><p>What does the exception says ?</p></li>\n<li><p>Does it work whan you use Send instead of SendAsync ? You are using 'using' clause and closing Stream before email is sent.</p></li>\n</ul>\n\n<p>Here is good text about this topic:</p>\n\n<p><a href=\"http://blogs.claritycon.com/blog/2006/01/sending-mail-in-net-2-0/\" rel=\"nofollow noreferrer\">Sending Mail in .NET 2.0</a></p>\n"
},
{
"answer_id": 283354,
"author": "liggett78",
"author_id": 19762,
"author_profile": "https://Stackoverflow.com/users/19762",
"pm_score": 6,
"selected": true,
"text": "<p>Don't use \"using\" here. You are destroying the memory stream immediately after calling SendAsync, e.g. probably before SMTP gets to read it (since it's async). Destroy your stream in the callback.</p>\n"
},
{
"answer_id": 41071322,
"author": "sweetfa",
"author_id": 490614,
"author_profile": "https://Stackoverflow.com/users/490614",
"pm_score": 0,
"selected": false,
"text": "<p>An extension to the Solution supplied in the original question also correctly cleans up an attachments that may also require disposal.</p>\n\n<pre><code> public event EventHandler EmailSendCancelled = delegate { };\n\n public event EventHandler EmailSendFailure = delegate { };\n\n public event EventHandler EmailSendSuccess = delegate { };\n ...\n\n MemoryStream mem = new MemoryStream();\n try\n {\n thisReport.ExportToPdf(mem);\n\n // Create a new attachment and put the PDF report into it.\n mem.Seek(0, System.IO.SeekOrigin.Begin);\n //Attachment att = new Attachment(mem, \"MyOutputFileName.pdf\", \"application/pdf\");\n Attachment messageAttachment = new Attachment(mem, thisReportName, \"application/pdf\");\n\n // Create a new message and attach the PDF report to it.\n MailMessage message = new MailMessage();\n message.Attachments.Add(messageAttachment);\n\n // Specify sender and recipient options for the e-mail message.\n message.From = new MailAddress(NOES.Properties.Settings.Default.FromEmailAddress, NOES.Properties.Settings.Default.FromEmailName);\n message.To.Add(new MailAddress(toEmailAddress, NOES.Properties.Settings.Default.ToEmailName));\n\n // Specify other e-mail options.\n //mail.Subject = thisReport.ExportOptions.Email.Subject;\n message.Subject = subject;\n message.Body = body;\n\n // Send the e-mail message via the specified SMTP server.\n SmtpClient smtp = new SmtpClient();\n smtp.SendCompleted += SmtpSendCompleted;\n smtp.SendAsync(message, message);\n }\n catch (Exception)\n {\n if (mem != null)\n {\n mem.Dispose();\n mem.Close();\n }\n throw;\n }\n }\n\n private void SmtpSendCompleted(object sender, AsyncCompletedEventArgs e)\n {\n var message = e.UserState as MailMessage;\n if (message != null)\n {\n foreach (var attachment in message.Attachments)\n {\n if (attachment != null)\n {\n attachment.Dispose();\n }\n }\n message.Dispose();\n }\n if (e.Cancelled)\n EmailSendCancelled?.Invoke(this, EventArgs.Empty);\n else if (e.Error != null)\n {\n EmailSendFailure?.Invoke(this, EventArgs.Empty);\n throw e.Error;\n }\n else\n EmailSendSuccess?.Invoke(this, EventArgs.Empty);\n }\n</code></pre>\n"
}
] |
2008/11/11
|
[
"https://Stackoverflow.com/questions/279953",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1195872/"
] |
I am using a service component through ASP.NET MVC.
I would like to send the email in a asynchronous way to let the user do other stuff without having to wait for the sending.
When I send a message without attachments it works fine.
When I send a message with at least one in-memory attachment it fails.
So, I would like to know if it is possible to use an async method with in-memory attachments.
Here is the sending method
```
public static void Send() {
MailMessage message = new MailMessage("[email protected]", "[email protected]");
using (MemoryStream stream = new MemoryStream(new byte[64000])) {
Attachment attachment = new Attachment(stream, "my attachment");
message.Attachments.Add(attachment);
message.Body = "This is an async test.";
SmtpClient smtp = new SmtpClient("localhost");
smtp.Credentials = new NetworkCredential("foo", "bar");
smtp.SendAsync(message, null);
}
}
```
Here is my current error
```
System.Net.Mail.SmtpException: Failure sending mail.
---> System.NotSupportedException: Stream does not support reading.
at System.Net.Mime.MimeBasePart.EndSend(IAsyncResult asyncResult)
at System.Net.Mail.Message.EndSend(IAsyncResult asyncResult)
at System.Net.Mail.SmtpClient.SendMessageCallback(IAsyncResult result)
--- End of inner exception stack trace ---
```
---
Solution
```
public static void Send()
{
MailMessage message = new MailMessage("[email protected]", "[email protected]");
MemoryStream stream = new MemoryStream(new byte[64000]);
Attachment attachment = new Attachment(stream, "my attachment");
message.Attachments.Add(attachment);
message.Body = "This is an async test.";
SmtpClient smtp = new SmtpClient("localhost");
//smtp.Credentials = new NetworkCredential("login", "password");
smtp.SendCompleted += delegate(object sender, System.ComponentModel.AsyncCompletedEventArgs e)
{
if (e.Error != null)
{
System.Diagnostics.Trace.TraceError(e.Error.ToString());
}
MailMessage userMessage = e.UserState as MailMessage;
if (userMessage != null)
{
userMessage.Dispose();
}
};
smtp.SendAsync(message, message);
}
```
|
Don't use "using" here. You are destroying the memory stream immediately after calling SendAsync, e.g. probably before SMTP gets to read it (since it's async). Destroy your stream in the callback.
|
279,959 |
<p>I have an entry in my .vimrc which makes it page down the viewport when I hit the spacebar. It looks like this:</p>
<pre><code>map <Space> <PageDown>
</code></pre>
<p>I want to create another key mapping which pages the viewport up when holding shift and hitting the spacebar. I have tried the following entries:</p>
<pre><code>map <Shift><Space> <PageUp>
map <S-Space> <PageUp>
</code></pre>
<p>Neither work. Anybody know how to achieve this functionality?</p>
|
[
{
"answer_id": 279973,
"author": "Christian C. Salvadó",
"author_id": 5445,
"author_profile": "https://Stackoverflow.com/users/5445",
"pm_score": 3,
"selected": false,
"text": "<p>Use this:</p>\n\n<pre><code>map <Space> ^D \" Pagedown when press Space\nmap <S-Space> ^U \" Page Up when press Shift Space\n</code></pre>\n\n<p>To get the ^D and ^U symbol correctly just press Control-V Control-D, and Control-V Control-U</p>\n"
},
{
"answer_id": 281484,
"author": "Zathrus",
"author_id": 16220,
"author_profile": "https://Stackoverflow.com/users/16220",
"pm_score": 6,
"selected": true,
"text": "<p>You cannot. CMS's solution will work for gVim, but not in vim because terminals cannot distinguish between <Space> and <S-Space> because curses sees them the same. It might be possible in the future if vim gains libtermkey support and your terminal supports the proper <CSI> sequences (xterm does if properly configured; nothing else does yet).</p>\n"
},
{
"answer_id": 7701779,
"author": "Steve McKinney",
"author_id": 139683,
"author_profile": "https://Stackoverflow.com/users/139683",
"pm_score": 2,
"selected": false,
"text": "<p>For OSX:</p>\n\n<pre><code>nnoremap <Space> <C-d>\nnnoremap <S-Space> <C-u>\n</code></pre>\n"
},
{
"answer_id": 18224694,
"author": "Bijou Trouvaille",
"author_id": 375570,
"author_profile": "https://Stackoverflow.com/users/375570",
"pm_score": 4,
"selected": false,
"text": "<p>If you are using vim inside iTerm2 you can map shift-space to ctrl+U by sending the hex key 15. Here's a screen shot:</p>\n\n<p><img src=\"https://i.stack.imgur.com/2GfWy.png\" alt=\"enter image description here\"></p>\n\n<p>To look up a hex code for a ctrl+letter combination, for example ctrl+u, you can do the following:</p>\n\n<ul>\n<li>In vim enter the insert mode</li>\n<li>Hit ctrl+v then ctrl+u then ctrl+c then ga</li>\n<li>various numerical representations will print at the bottom</li>\n</ul>\n\n<p>You can apply this idea to other terminal emulators that support key mapping. </p>\n"
},
{
"answer_id": 63084982,
"author": "ebk",
"author_id": 4710226,
"author_profile": "https://Stackoverflow.com/users/4710226",
"pm_score": 1,
"selected": false,
"text": "<p>Inspired by <a href=\"https://unix.stackexchange.com/a/320750/124200\">this answer</a>, I got the mapping done by:</p>\n<ul>\n<li>Using a terminal that supports key mapping</li>\n<li>Mapping <kbd>Shift</kbd>+<kbd>Space</kbd> to a sequence of characters that can be distinguished from <kbd>Space</kbd> by Vim, but still has a net effect of writting a space when you input text.</li>\n</ul>\n<h3>How-to:</h3>\n<ol>\n<li><p><strong>Choose one of those terminals that are capable of key mapping.</strong><br />\nFor example, Alacritty, xterm, urxvt, or Kitty.</p>\n</li>\n<li><p><strong>Choose the character sequence to which <kbd>Shift</kbd>+<kbd>Space</kbd> will be mapped.</strong><br />\n<kbd>SOME_KEY</kbd>,<kbd>Backspace</kbd>,<kbd>Space</kbd> should do the trick, where <kbd>SOME_KEY</kbd>:</p>\n<ul>\n<li>writes a character that can be canceled out by a <kbd>Backspace</kbd> when inputting text, e.g. a printable character or a tab.</li>\n<li>is also a key you rarely use in Vim normal mode and/or visual mode (depending on which mode you want to use <kbd>Shift</kbd>+<kbd>Space</kbd> in). If it has already been binded to some heavily-used command, you may experience some lag (see <code>:h timeout</code> for details) every time you use the command.</li>\n</ul>\n<p>I am using <kbd>\\</kbd> as <kbd>SOME_KEY</kbd> (<kbd>`</kbd> may also be a good option).</p>\n</li>\n<li><p><strong>Mapping in the terminal</strong><br />\nI'm using <a href=\"https://github.com/alacritty/alacritty\" rel=\"nofollow noreferrer\">Alacritty</a>, so here is an example of mapping <kbd>Shift</kbd>+<kbd>Space</kbd> to the character sequence in Alacritty. In the config file add the following line under the "key_bindings" item: <code>- { key: Space, mods: Shift, chars: "\\x5c\\x08 " }</code>.</p>\n<p>To confirm the mapping works, run <code>showkey -a</code> in the terminal and press <kbd>Shift</kbd>+<kbd>Space</kbd>, then the character sequence should be output. For the example above, the output is:</p>\n<pre><code> \\^H 92 0134 0x5c \n 8 0010 0x08 \n 32 0040 0x20\n</code></pre>\n</li>\n<li><p><strong>Mapping in Vim</strong><br />\nMap the character sequence to page up in Vim config. In my case (using <kbd>\\</kbd> as the first key), it will be <code>no <Bslash><C-h><Space> <C-b></code>. If you need the mapping in visual mode too, also add <code>vno <Bslash><C-h><Space> <C-b></code>.</p>\n</li>\n</ol>\n<p>I have used this settings for a while and it hasn't yet broken insert mode and replace mode of Vim as well as most\nprograms that accept text input on my system. But it's not a solution, but a workaround, which do have some flaws, e.g.:</p>\n<ul>\n<li>In Vim if you try to replace a character under the cursor (by <kbd>r</kbd> by default) with <kbd>Shift</kbd>+<kbd>Space</kbd>, you won't get a space.</li>\n<li>Some programs that interpret character sequences as commands like what Vim does may be affected.</li>\n</ul>\n"
}
] |
2008/11/11
|
[
"https://Stackoverflow.com/questions/279959",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2476/"
] |
I have an entry in my .vimrc which makes it page down the viewport when I hit the spacebar. It looks like this:
```
map <Space> <PageDown>
```
I want to create another key mapping which pages the viewport up when holding shift and hitting the spacebar. I have tried the following entries:
```
map <Shift><Space> <PageUp>
map <S-Space> <PageUp>
```
Neither work. Anybody know how to achieve this functionality?
|
You cannot. CMS's solution will work for gVim, but not in vim because terminals cannot distinguish between <Space> and <S-Space> because curses sees them the same. It might be possible in the future if vim gains libtermkey support and your terminal supports the proper <CSI> sequences (xterm does if properly configured; nothing else does yet).
|
279,966 |
<p>I am building a PHP application in CodeIgniter. CodeIgniter sends all requests to the main controller: <code>index.php</code>. However, I don't like to see <code>index.php</code> in the URI. For example, <code>http://www.example.com/faq/whatever</code> will route to <code>http://www.example.com/index.php/faq/whatever</code>. I need a reliable way for a script to know what it's address is, so it will know what to do with the navigation. I've used <code>mod_rewrite</code>, as per CodeIgniter documentation.</p>
<p>The rule is as follows:</p>
<pre><code>RewriteEngine on
RewriteCond $1 !^(images|inc|favicon\.ico|index\.php|robots\.txt)
RewriteRule ^(.*)$ /index.php/$1 [L]
</code></pre>
<p>Normally, I would just check <code>php_self</code>, but in this case it's always <code>index.php</code>. I can get it from <code>REQUEST_URI</code>, <code>PATH_INFO</code>, etc., but I'm trying to decide which will be most reliable. Does anyone know (or know where to find) the real difference between <code>PHP_SELF</code>, <code>PATH_INFO</code>, <code>SCRIPT_NAME</code>, and <code>REQUEST_URI</code>? Thanks for your help!</p>
<p><strong>Note</strong>: I've had to add spaces, as SO sees the underscore, and makes it italic for some reason. </p>
<p><strong>Updated</strong>: Fixed the spaces.</p>
|
[
{
"answer_id": 279986,
"author": "Xenph Yan",
"author_id": 264,
"author_profile": "https://Stackoverflow.com/users/264",
"pm_score": 2,
"selected": false,
"text": "<p>Personally I use the <code>$REQUEST_URI</code> as it references the URI entered and not the location on the server's disc.</p>\n"
},
{
"answer_id": 280068,
"author": "Adam",
"author_id": 13320,
"author_profile": "https://Stackoverflow.com/users/13320",
"pm_score": 3,
"selected": false,
"text": "<p>You may want to look into the <a href=\"http://codeigniter.com/user_guide/libraries/uri.html\" rel=\"noreferrer\">URI Class</a> and make use of $this->uri->uri_string()</p>\n\n<p>Returns a string with the complete URI. </p>\n\n<p>For example, if this is your full URL:</p>\n\n<pre><code>http://example.com/index.php/news/local/345\n</code></pre>\n\n<p>The function would return this:</p>\n\n<pre><code>/news/local/345\n</code></pre>\n\n<p>Or you could make use of the segments to drill down specific areas without having to come up with parsing/regex values</p>\n"
},
{
"answer_id": 280076,
"author": "Paige Ruten",
"author_id": 813,
"author_profile": "https://Stackoverflow.com/users/813",
"pm_score": 7,
"selected": true,
"text": "<p>The <a href=\"http://ca.php.net/manual/en/reserved.variables.server.php\" rel=\"noreferrer\">PHP documentation</a> can tell you the difference:</p>\n\n<blockquote>\n <p><i>'PHP_SELF'</i></p>\n \n <blockquote>\n <p>The filename of the currently executing script, relative to the document root. For instance, <i>$_SERVER['PHP_SELF']</i> in a script at the address <i><a href=\"http://example.com/test.php/foo.bar\" rel=\"noreferrer\">http://example.com/test.php/foo.bar</a></i> would be <i>/test.php/foo.bar</i>. The <a href=\"http://ca.php.net/manual/en/language.constants.predefined.php\" rel=\"noreferrer\">__FILE__</a> constant contains the full path and filename of the current (i.e. included) file. If PHP is running as a command-line processor this variable contains the script name since PHP 4.3.0. Previously it was not available. </p>\n </blockquote>\n \n <p><i>'SCRIPT_NAME'</i></p>\n \n <blockquote>\n <p>Contains the current script's path. This is useful for pages which need to point to themselves. The <a href=\"http://ca.php.net/manual/en/language.constants.predefined.php\" rel=\"noreferrer\">__FILE__</a> constant contains the full path and filename of the current (i.e. included) file.</p>\n </blockquote>\n \n <p><i>'REQUEST_URI'</i></p>\n \n <blockquote>\n <p>The URI which was given in order to access this page; for instance, <i>'/index.html'</i>.</p>\n </blockquote>\n</blockquote>\n\n<p>PATH_INFO doesn't seem to be documented...</p>\n"
},
{
"answer_id": 326331,
"author": "Odin",
"author_id": 41640,
"author_profile": "https://Stackoverflow.com/users/41640",
"pm_score": 8,
"selected": false,
"text": "<p>Some practical examples of the differences between these variables:<br>\nExample 1.\nPHP_SELF is different from SCRIPT_NAME <em>only</em> when requested url is in form:<br>\n<a href=\"http://example.com/test.php/foo/bar\" rel=\"noreferrer\">http://example.com/test.php/foo/bar</a></p>\n\n<pre><code>[PHP_SELF] => /test.php/foo/bar\n[SCRIPT_NAME] => /test.php\n</code></pre>\n\n<p>(this seems to be the only case when PATH_INFO contains sensible information [PATH_INFO] => /foo/bar)\nNote: this used to be different in some older PHP versions (<= 5.0 ?).</p>\n\n<p>Example 2.\nREQUEST_URI is different from SCRIPT_NAME when a non-empty query string is entered:<br>\n<a href=\"http://example.com/test.php?foo=bar\" rel=\"noreferrer\">http://example.com/test.php?foo=bar</a></p>\n\n<pre><code>[SCRIPT_NAME] => /test.php\n[REQUEST_URI] => /test.php?foo=bar\n</code></pre>\n\n<p>Example 3.\nREQUEST_URI is different from SCRIPT_NAME when server-side redirecton is in effect (for example mod_rewrite on apache):</p>\n\n<p><a href=\"http://example.com/test.php\" rel=\"noreferrer\">http://example.com/test.php</a></p>\n\n<pre><code>[REQUEST_URI] => /test.php\n[SCRIPT_NAME] => /test2.php\n</code></pre>\n\n<p>Example 4.\nREQUEST_URI is different from SCRIPT_NAME when handling HTTP errors with scripts.<br>\nUsing apache directive ErrorDocument 404 /404error.php<br>\n<a href=\"http://example.com/test.php\" rel=\"noreferrer\">http://example.com/test.php</a></p>\n\n<pre><code>[REQUEST_URI] => /test.php\n[SCRIPT_NAME] => /404error.php\n</code></pre>\n\n<p>On IIS server using custom error pages<br>\n<a href=\"http://example.com/test.php\" rel=\"noreferrer\">http://example.com/test.php</a></p>\n\n<pre><code>[SCRIPT_NAME] => /404error.php\n[REQUEST_URI] => /404error.php?404;http://example.com/test.php\n</code></pre>\n"
},
{
"answer_id": 395687,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": -1,
"selected": false,
"text": "<p>Backup a second, you've taken the wrong approach to begin with. Why not just do this</p>\n\n<pre><code>RewriteEngine on\nRewriteCond $1 !^(images|inc|favicon\\.ico|index\\.php|robots\\.txt)\nRewriteRule ^(.*)$ /index.php?url=$1 [L]\n</code></pre>\n\n<p>instead? Then grab it with <code>$_GET['url'];</code></p>\n"
},
{
"answer_id": 9600525,
"author": "Mike",
"author_id": 949747,
"author_profile": "https://Stackoverflow.com/users/949747",
"pm_score": 5,
"selected": false,
"text": "<p><code>PATH_INFO</code> is only available when using htaccess like this:</p>\n\n<h2>Example 1</h2>\n\n<pre><code>RewriteCond %{REQUEST_FILENAME} !-f\nRewriteCond %{REQUEST_FILENAME} !-d\nRewriteCond %{REQUEST_URI} !^(favicon\\.ico|robots\\.txt)\nRewriteRule ^(.*)$ index.php/$1 [L]\n</code></pre>\n\n<h3>Remains the same</h3>\n\n<pre><code>[SCRIPT_NAME] => /index.php\n</code></pre>\n\n<h3>Root</h3>\n\n<p><a href=\"http://domain.com/\">http://domain.com/</a></p>\n\n<pre><code>[PHP_SELF] => /index.php\n[PATH_INFO] IS NOT AVAILABLE (fallback to REQUEST_URI in your script)\n[REQUEST_URI] => /\n[QUERY_STRING] => \n</code></pre>\n\n<h3>Path</h3>\n\n<p><a href=\"http://domain.com/test\">http://domain.com/test</a></p>\n\n<pre><code>[PHP_SELF] => /index.php/test\n[PATH_INFO] => /test\n[REQUEST_URI] => /test\n[QUERY_STRING] => \n</code></pre>\n\n<h3>Query String</h3>\n\n<p><a href=\"http://domain.com/test?123\">http://domain.com/test?123</a></p>\n\n<pre><code>[PHP_SELF] => /index.php/test\n[PATH_INFO] => /test\n[REQUEST_URI] => /test?123\n[QUERY_STRING] => 123\n</code></pre>\n\n<h2>Example 2</h2>\n\n<pre><code>RewriteCond %{REQUEST_FILENAME} !-f\nRewriteCond %{REQUEST_FILENAME} !-d\nRewriteCond %{REQUEST_URI} !^(favicon\\.ico|robots\\.txt)\nRewriteRule ^(.*)$ index.php?url=$1 [L,QSA]\n</code></pre>\n\n<h3>Remains the same</h3>\n\n<pre><code>[SCRIPT_NAME] => /index.php\n[PHP_SELF] => /index.php\n[PATH_INFO] IS NOT AVAILABLE (fallback to REQUEST_URI in your script)\n</code></pre>\n\n<h3>Root</h3>\n\n<p><a href=\"http://domain.com/\">http://domain.com/</a></p>\n\n<pre><code>[REQUEST_URI] => /\n[QUERY_STRING] => \n</code></pre>\n\n<h3>Path</h3>\n\n<p><a href=\"http://domain.com/test\">http://domain.com/test</a></p>\n\n<pre><code>[REQUEST_URI] => /test\n[QUERY_STRING] => url=test\n</code></pre>\n\n<h3>Query String</h3>\n\n<p><a href=\"http://domain.com/test?123\">http://domain.com/test?123</a></p>\n\n<pre><code>[REQUEST_URI] => /test?123\n[QUERY_STRING] => url=test&123\n</code></pre>\n\n<h2>Example 3</h2>\n\n<pre><code>RewriteCond %{REQUEST_FILENAME} !-f\nRewriteCond %{REQUEST_FILENAME} !-d\nRewriteCond %{REQUEST_URI} !^(favicon\\.ico|robots\\.txt)\nRewriteRule ^(([a-z]{2})|(([a-z]{2})/)?(.*))$ index.php/$5 [NC,L,E=LANGUAGE:$2$4]\n</code></pre>\n\n<p>or</p>\n\n<pre><code>RewriteRule ^([a-z]{2})(/(.*))?$ $3 [NC,L,E=LANGUAGE:$1]\n\nRewriteCond %{REQUEST_FILENAME} !-f\nRewriteCond %{REQUEST_FILENAME} !-d\nRewriteCond %{REQUEST_URI} !^(favicon\\.ico|robots\\.txt)\nRewriteRule ^(.*)$ index.php/$1 [L]\n</code></pre>\n\n<h3>Remains the same</h3>\n\n<pre><code>[SCRIPT_NAME] => /index.php\n</code></pre>\n\n<h3>Root</h3>\n\n<p><a href=\"http://domain.com/\">http://domain.com/</a></p>\n\n<pre><code>[PHP_SELF] => /index.php\n[PATH_INFO] IS NOT AVAILABLE (fallback to REQUEST_URI in your script)\n[REQUEST_URI] => /\n[QUERY_STRING] => \n[REDIRECT_LANGUAGE] IS NOT AVAILABLE\n</code></pre>\n\n<h3>Path</h3>\n\n<p><a href=\"http://domain.com/test\">http://domain.com/test</a></p>\n\n<pre><code>[PHP_SELF] => /index.php/test\n[PATH_INFO] => /test\n[REQUEST_URI] => /test\n[QUERY_STRING] => \n[REDIRECT_LANGUAGE] => \n</code></pre>\n\n<h3>Language</h3>\n\n<p><a href=\"http://domain.com/en\">http://domain.com/en</a></p>\n\n<pre><code>[PHP_SELF] => /index.php/\n[PATH_INFO] => /\n[REQUEST_URI] => /en\n[QUERY_STRING] => \n[REDIRECT_LANGUAGE] => en\n</code></pre>\n\n<h3>Language path</h3>\n\n<p><a href=\"http://domain.com/en/test\">http://domain.com/en/test</a></p>\n\n<pre><code>[PHP_SELF] => /index.php/test\n[PATH_INFO] => /test\n[REQUEST_URI] => /en/test\n[REDIRECT_LANGUAGE] => en\n</code></pre>\n\n<h3>Language Query string</h3>\n\n<p><a href=\"http://domain.com/en/test?123\">http://domain.com/en/test?123</a></p>\n\n<pre><code>[PHP_SELF] => /index.php/test\n[PATH_INFO] => /test\n[REQUEST_URI] => /en/test?123\n[QUERY_STRING] => 123\n[REDIRECT_LANGUAGE] => en\n</code></pre>\n"
},
{
"answer_id": 29553868,
"author": "Beejor",
"author_id": 3672465,
"author_profile": "https://Stackoverflow.com/users/3672465",
"pm_score": 4,
"selected": false,
"text": "<h3>PHP Paths</h3>\n\n<p> <code> $_SERVER['REQUEST_URI'] </code> = Web path, requested URI<br/>\n <code> $_SERVER['PHP_SELF'] </code> = Web path, requested file + path info<br/>\n <code> $_SERVER['SCRIPT_NAME'] </code> = Web path, requested file<br/>\n <code> $_SERVER['SCRIPT_FILENAME'] </code> = File path, requested file<br/>\n <code> __FILE__ </code> = File path, current file<br/> </p>\n\n<h3>Where</h3>\n\n<ul>\n<li><strong>File path</strong> is a <em>system file path</em> like <code>/var/www/index.php</code>, after alias resolution</li>\n<li><strong>Web path</strong> is a <em>server document path</em> like <code>/index.php</code> from\n<code>http://foo.com/index.php</code>, and may not even match any file</li>\n<li><strong>Current file</strong> means <em>the included script file</em>, not any script that includes it</li>\n<li><strong>Requested file</strong> means <em>the includer script file</em>, not the included one</li>\n<li><strong>URI</strong> is the <em>HTTP request</em> like <code>/index.php?foo=bar</code>, before any URL rewriting</li>\n<li><strong>Path info</strong> is any extra Apache data located after the script name but before the query string</li>\n</ul>\n\n<h3>Order of Operation</h3>\n\n<ol>\n<li>Client sends server an <em>HTTP request</em> <code>REQUEST_URI</code></li>\n<li>Server performs any <em>URL rewriting</em> from .htaccess files, etc. to get <code>PHP_SELF</code></li>\n<li>Server separates <code>PHP_SELF</code> into <code>SCRIPT_FILENAME</code> + <code>PATH_INFO</code></li>\n<li>Server performs <em>alias resolution</em> and converts the entire <em>url path</em> to a <em>system file path</em> to get <code>SCRIPT_FILENAME</code></li>\n<li>Resulting script file may include others, where <code>__FILE__</code> refers to the path to the current file</li>\n</ol>\n"
},
{
"answer_id": 34303983,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 2,
"selected": false,
"text": "<p>There is very little to add to Odin's answer. I just felt to provide a complete example from the HTTP request to the actual file on the file system to illustrate the effects of URL rewriting and aliases. On the file system the script <code>/var/www/test/php/script.php</code> is</p>\n\n<pre><code><?php\ninclude (\"script_included.php\")\n?>\n</code></pre>\n\n<p>where <code>/var/www/test/php/script_included.php</code> is</p>\n\n<pre><code><?php\necho \"REQUEST_URI: \" . $_SERVER['REQUEST_URI'] . \"<br>\"; \necho \"PHP_SELF: \" . $_SERVER['PHP_SELF'] . \"<br>\";\necho \"QUERY_STRING: \" . $_SERVER['QUERY_STRING'] . \"<br>\";\necho \"SCRIPT_NAME: \" . $_SERVER['SCRIPT_NAME'] . \"<br>\";\necho \"PATH_INFO: \" . $_SERVER['PATH_INFO'] . \"<br>\";\necho \"SCRIPT_FILENAME: \" . $_SERVER['SCRIPT_FILENAME'] . \"<br>\";\necho \"__FILE__ : \" . __FILE__ . \"<br>\"; \n?>\n</code></pre>\n\n<p>and <code>/var/www/test/.htaccess</code> is</p>\n\n<pre><code>RewriteEngine On\nRewriteRule before_rewrite/script.php/path/(.*) after_rewrite/script.php/path/$1 \n</code></pre>\n\n<p>and the Apache configuration file includes the alias</p>\n\n<pre><code>Alias /test/after_rewrite/ /var/www/test/php/\n</code></pre>\n\n<p>and the http request is </p>\n\n<pre><code>www.example.com/test/before_rewrite/script.php/path/info?q=helloword\n</code></pre>\n\n<p>The output will be</p>\n\n<pre><code>REQUEST_URI: /test/before_rewrite/script.php/path/info?q=helloword\nPHP_SELF: /test/after_rewrite/script.php/path/info\nQUERY_STRING: q=helloword\nSCRIPT_NAME: /test/after_rewrite/script.php\nPATH_INFO: /path/info\nSCRIPT_FILENAME: /var/www/test/php/script.php\n__FILE__ : /var/www/test/php/script_included.php\n</code></pre>\n\n<p>The following always holds </p>\n\n<pre><code>PHP_SELF = SCRIPT_NAME + PATH_INFO = full url path between domain and query string. \n</code></pre>\n\n<p>If there is no mod_rewrite, mod_dir, ErrorDocument rewrite or any form of URL rewriting, we also have</p>\n\n<pre><code>REQUEST_URI = PHP_SELF + ? + QUERY_STRING \n</code></pre>\n\n<p>The aliases affect the system file paths <code>SCRIPT_FILENAME</code> and <code>__FILE__</code>, not the URL paths, which are defined before - see exceptions below. Aliases might use the entire URL path, including <code>PATH_INFO</code>. There could be no connection at all between <code>SCRIPT_NAME</code> and <code>SCRIPT_FILENAME</code> . </p>\n\n<p>It is not totally exact that aliases are not resolved at the time the URL path <code>[PHP_SELF] = [SCRIPT_NAME] + [PATH_INFO]</code> is defined, because aliases are considered to search the file system and we know from example 4 in Odin's answer that the file system is searched to determine if the file exists, but this is only relevant when the file is not found. Similarly, mod_dir calls mod_alias to search the file system, but this is only relevant if you have an alias such as <code>Alias \\index.php \\var\\www\\index.php</code> and the request uri is a directory. </p>\n"
},
{
"answer_id": 51481605,
"author": "AbsoluteƵERØ",
"author_id": 2145800,
"author_profile": "https://Stackoverflow.com/users/2145800",
"pm_score": 1,
"selected": false,
"text": "<p>If you ever forget which variables do what, you can write a little script that uses <a href=\"http://php.net/manual/en/function.phpinfo.php\" rel=\"nofollow noreferrer\">phpinfo()</a> and call it from a URL with a query string. Since server software installations present the variables that PHP returns it's always a good idea to check the machine's output in case rewrites at the server config file are causing different results than expected. Save it as something like <code>_inf0.php</code>:</p>\n\n<pre><code><?php\n $my_ip = '0.0.0.0';\n\n if($_SERVER['REMOTE_ADDR']==$my_ip){\n phpinfo();\n } else {\n //something\n }\n</code></pre>\n\n<p>Then you would call <code>/_inf0.php?q=500</code></p>\n"
}
] |
2008/11/11
|
[
"https://Stackoverflow.com/questions/279966",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/27580/"
] |
I am building a PHP application in CodeIgniter. CodeIgniter sends all requests to the main controller: `index.php`. However, I don't like to see `index.php` in the URI. For example, `http://www.example.com/faq/whatever` will route to `http://www.example.com/index.php/faq/whatever`. I need a reliable way for a script to know what it's address is, so it will know what to do with the navigation. I've used `mod_rewrite`, as per CodeIgniter documentation.
The rule is as follows:
```
RewriteEngine on
RewriteCond $1 !^(images|inc|favicon\.ico|index\.php|robots\.txt)
RewriteRule ^(.*)$ /index.php/$1 [L]
```
Normally, I would just check `php_self`, but in this case it's always `index.php`. I can get it from `REQUEST_URI`, `PATH_INFO`, etc., but I'm trying to decide which will be most reliable. Does anyone know (or know where to find) the real difference between `PHP_SELF`, `PATH_INFO`, `SCRIPT_NAME`, and `REQUEST_URI`? Thanks for your help!
**Note**: I've had to add spaces, as SO sees the underscore, and makes it italic for some reason.
**Updated**: Fixed the spaces.
|
The [PHP documentation](http://ca.php.net/manual/en/reserved.variables.server.php) can tell you the difference:
>
> *'PHP\_SELF'*
>
>
>
> >
> > The filename of the currently executing script, relative to the document root. For instance, *$\_SERVER['PHP\_SELF']* in a script at the address *<http://example.com/test.php/foo.bar>* would be */test.php/foo.bar*. The [\_\_FILE\_\_](http://ca.php.net/manual/en/language.constants.predefined.php) constant contains the full path and filename of the current (i.e. included) file. If PHP is running as a command-line processor this variable contains the script name since PHP 4.3.0. Previously it was not available.
> >
> >
> >
>
>
> *'SCRIPT\_NAME'*
>
>
>
> >
> > Contains the current script's path. This is useful for pages which need to point to themselves. The [\_\_FILE\_\_](http://ca.php.net/manual/en/language.constants.predefined.php) constant contains the full path and filename of the current (i.e. included) file.
> >
> >
> >
>
>
> *'REQUEST\_URI'*
>
>
>
> >
> > The URI which was given in order to access this page; for instance, *'/index.html'*.
> >
> >
> >
>
>
>
PATH\_INFO doesn't seem to be documented...
|
279,974 |
<p>I'm finding myself writing a bunch of related functions dealing with different nouns (clusters, sql servers, servers in general, files, etc.) and put each of these groups of functions in separate files (say cluster_utils.ps1, for example). I want to be able to "import" some of these libraries in my profile and others in my powershell session if I need them. I have written 2 functions that seem to solve the problem, but since I've only been using powershell for a month I thought I'd ask to see if there were any existing "best practice" type scripts I could be using instead.</p>
<p>To use these functions, I dot-source them (in my profile or my session)... for example,</p>
<pre><code># to load c:\powershellscripts\cluster_utils.ps1 if it isn't already loaded
. require cluster_utils
</code></pre>
<p>Here are the functions:</p>
<pre><code>$global:loaded_scripts=@{}
function require([string]$filename){
if (!$loaded_scripts[$filename]){
. c:\powershellscripts\$filename.ps1
$loaded_scripts[$filename]=get-date
}
}
function reload($filename){
. c:\powershellscripts\$filename.ps1
$loaded_scripts[$filename]=get-date
}
</code></pre>
<p>Any feedback would be helpful.</p>
|
[
{
"answer_id": 282098,
"author": "Steven Murawski",
"author_id": 1233,
"author_profile": "https://Stackoverflow.com/users/1233",
"pm_score": 2,
"selected": false,
"text": "<p>Mike, I think those scripts are awesome. Parceling out your functions into libraries is very useful, but I think your functions to load scripts is very convenient.</p>\n\n<p>The one change I would make would be to make the file location a parameter also. You could set a default value or even use a global variable for that. You don't need to add the \".ps1\"</p>\n\n<pre><code>$global:scriptdirectory= 'c:\\powershellscripts'\n$global:loaded_scripts=@{}\nfunction require(){\n param ([string]$filename, [string]$path=$scriptdirectory)\n if (!$loaded_scripts[$filename]){\n . (Join-Path $path $filename)\n $loaded_scripts[$filename]=get-date\n }\n}\n\nfunction reload(){\n param ([string]$filename, [string]$path=$scriptdirectory)\n . (Join-Path $path $filename)\n $loaded_scripts[$filename]=get-date\n}\n</code></pre>\n\n<p>Nice functions!</p>\n"
},
{
"answer_id": 293947,
"author": "Emperor XLII",
"author_id": 2495,
"author_profile": "https://Stackoverflow.com/users/2495",
"pm_score": 4,
"selected": true,
"text": "<p>Building on <a href=\"https://stackoverflow.com/questions/279974/importing-libraries-in-powershell#282098\">Steven's answer</a>, another improvement might be to allow loading multiple files at once:</p>\n\n<pre><code>$global:scriptdirectory = 'C:\\powershellscripts'\n$global:loaded_scripts = @{}\n\nfunction require {\n param(\n [string[]]$filenames=$(throw 'Please specify scripts to load'),\n [string]$path=$scriptdirectory\n )\n\n $unloadedFilenames = $filenames | where { -not $loaded_scripts[$_] }\n reload $unloadedFilenames $path\n}\n\nfunction reload {\n param(\n [string[]]$filenames=$(throw 'Please specify scripts to reload'),\n [string]$path=$scriptdirectory\n )\n\n foreach( $filename in $filenames ) {\n . (Join-Path $path $filename)\n $loaded_scripts[$filename] = Get-Date\n }\n}\n</code></pre>\n"
},
{
"answer_id": 315619,
"author": "Don Jones",
"author_id": 40405,
"author_profile": "https://Stackoverflow.com/users/40405",
"pm_score": 1,
"selected": false,
"text": "<p>I think you'll find the \"modules\" functionality of PowerShell v2 to be very satisfying. Basically takes care of this for you.</p>\n"
}
] |
2008/11/11
|
[
"https://Stackoverflow.com/questions/279974",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/36429/"
] |
I'm finding myself writing a bunch of related functions dealing with different nouns (clusters, sql servers, servers in general, files, etc.) and put each of these groups of functions in separate files (say cluster\_utils.ps1, for example). I want to be able to "import" some of these libraries in my profile and others in my powershell session if I need them. I have written 2 functions that seem to solve the problem, but since I've only been using powershell for a month I thought I'd ask to see if there were any existing "best practice" type scripts I could be using instead.
To use these functions, I dot-source them (in my profile or my session)... for example,
```
# to load c:\powershellscripts\cluster_utils.ps1 if it isn't already loaded
. require cluster_utils
```
Here are the functions:
```
$global:loaded_scripts=@{}
function require([string]$filename){
if (!$loaded_scripts[$filename]){
. c:\powershellscripts\$filename.ps1
$loaded_scripts[$filename]=get-date
}
}
function reload($filename){
. c:\powershellscripts\$filename.ps1
$loaded_scripts[$filename]=get-date
}
```
Any feedback would be helpful.
|
Building on [Steven's answer](https://stackoverflow.com/questions/279974/importing-libraries-in-powershell#282098), another improvement might be to allow loading multiple files at once:
```
$global:scriptdirectory = 'C:\powershellscripts'
$global:loaded_scripts = @{}
function require {
param(
[string[]]$filenames=$(throw 'Please specify scripts to load'),
[string]$path=$scriptdirectory
)
$unloadedFilenames = $filenames | where { -not $loaded_scripts[$_] }
reload $unloadedFilenames $path
}
function reload {
param(
[string[]]$filenames=$(throw 'Please specify scripts to reload'),
[string]$path=$scriptdirectory
)
foreach( $filename in $filenames ) {
. (Join-Path $path $filename)
$loaded_scripts[$filename] = Get-Date
}
}
```
|
280,014 |
<p>I have a script which logs on to a remote server and tries to rename files, using PHP.</p>
<p>The code currently looks something like this example from the php.net website:</p>
<pre><code>if (ftp_rename($conn_id, $old_file, $new_file)) {
echo "successfully renamed $old_file to $new_file\n";
} else {
echo "There was a problem while renaming $old_file to $new_file\n";
}
</code></pre>
<p>but ... what was the error? Permissions, no such directory, disk full?</p>
<p>How can I get PHP to return the FTP error? Something like this:</p>
<pre><code>echo "There was a problem while renaming $old_file to $new_file:
the server says $error_message\n";
</code></pre>
|
[
{
"answer_id": 280022,
"author": "FlySwat",
"author_id": 1965,
"author_profile": "https://Stackoverflow.com/users/1965",
"pm_score": 5,
"selected": true,
"text": "<p>Looking at the FTP API here:</p>\n\n<p><a href=\"http://us.php.net/manual/en/function.ftp-rename.php\" rel=\"noreferrer\">http://us.php.net/manual/en/function.ftp-rename.php</a></p>\n\n<p>There doesn't seem to be any way to get anything but true or false.</p>\n\n<p>However, you could use ftp_raw to send a raw RENAME command, and then parse the returned message.</p>\n"
},
{
"answer_id": 8847900,
"author": "Sascha Schmidt",
"author_id": 1147283,
"author_profile": "https://Stackoverflow.com/users/1147283",
"pm_score": 5,
"selected": false,
"text": "<p>You could use error_get_last() if return value is false.</p>\n"
},
{
"answer_id": 12910495,
"author": "Peter Hopfgartner",
"author_id": 1630567,
"author_profile": "https://Stackoverflow.com/users/1630567",
"pm_score": 4,
"selected": false,
"text": "<p>I'm doing something like:</p>\n\n<pre><code>$trackErrors = ini_get('track_errors');\nini_set('track_errors', 1);\nif (!@ftp_put($my_ftp_conn_id, $tmpRemoteFileName, $localFileName, FTP_BINARY)) {\n // error message is now in $php_errormsg\n $msg = $php_errormsg;\n ini_set('track_errors', $trackErrors);\n throw new Exception($msg);\n}\nini_set('track_errors', $trackErrors);\n</code></pre>\n\n<p>EDIT:</p>\n\n<p>Note that $php_errormsg is deprecated as of PHP 7.</p>\n\n<p>Use error_get_last() instead.</p>\n\n<p>See answer by @Sascha Schmidt</p>\n"
},
{
"answer_id": 56710674,
"author": "jsherk",
"author_id": 570759,
"author_profile": "https://Stackoverflow.com/users/570759",
"pm_score": 3,
"selected": false,
"text": "<p>Based on @Sascha Schmidt answer, you could do something like this:</p>\n\n<pre><code>if (ftp_rename($conn_id, $old_file, $new_file)) {\n echo \"successfully renamed $old_file to $new_file\\n\";\n} else {\n echo \"There was a problem while renaming $old_file to $new_file\\n\";\n print_r( error_get_last() ); // ADDED THIS LINE\n}\n</code></pre>\n\n<p>print_r will display the contents of the error_get_last() array so you can pinpoint the error.</p>\n"
}
] |
2008/11/11
|
[
"https://Stackoverflow.com/questions/280014",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/242241/"
] |
I have a script which logs on to a remote server and tries to rename files, using PHP.
The code currently looks something like this example from the php.net website:
```
if (ftp_rename($conn_id, $old_file, $new_file)) {
echo "successfully renamed $old_file to $new_file\n";
} else {
echo "There was a problem while renaming $old_file to $new_file\n";
}
```
but ... what was the error? Permissions, no such directory, disk full?
How can I get PHP to return the FTP error? Something like this:
```
echo "There was a problem while renaming $old_file to $new_file:
the server says $error_message\n";
```
|
Looking at the FTP API here:
<http://us.php.net/manual/en/function.ftp-rename.php>
There doesn't seem to be any way to get anything but true or false.
However, you could use ftp\_raw to send a raw RENAME command, and then parse the returned message.
|
280,017 |
<p>I'm trying to wrap my head around the roles of UIViews and UIViewControllers. If I'm creating and inserting subviews programmatically, is it typical to do this from the view or the controller?</p>
<p>I'm really just wondering if there's a convention/pattern for this. In my sample application, I'm loading 50 images at runtime, adding them as subviews to the main view, then letting the user drag them around the screen. I'm currently doing all the initialization in the view's initWithCoder:</p>
<pre><code>- (id)initWithCoder:(NSCoder*)coder
{
if (self = [super initWithCoder:coder]) {
// load UIImageViews and add them to the subview
}
return self;
}
</code></pre>
<p>The view also implements touchesBegan/touchesMoved to allow dragging. My problem comes when I try to access [self frame].size in initWithCoder, it doesn't seem to be initialized yet. This makes me think I may be loading the images in the wrong place...</p>
|
[
{
"answer_id": 280046,
"author": "Jim Puls",
"author_id": 6010,
"author_profile": "https://Stackoverflow.com/users/6010",
"pm_score": 4,
"selected": true,
"text": "<p>It depends on what you're doing. If the view represents something \"packaged\", then you create subviews from the view itself. If you're merely aggregating views together, then you should do it from the view controller.</p>\n\n<p>Think about traditional encapsulation. Is your subview conceptually \"part\" of its superview, or does it just live there in the drawing hierarchy?</p>\n"
},
{
"answer_id": 281250,
"author": "Alex",
"author_id": 35999,
"author_profile": "https://Stackoverflow.com/users/35999",
"pm_score": 2,
"selected": false,
"text": "<p>Suppose you're creating a view that contains some controls, like to edit a record with multiple fields or something. Since you're going to be using those text fields and their data in the view controller, they conceptually \"belong\" to the view controller, and the parent view exists just for grouping and layout purposes. This is probably the more common scenario.</p>\n\n<p>If you were creating a view subclass to behave like a new control, for example, then I would say you should create and manage the views entirely within the view class. I imagine this case will happen less frequently in practice.</p>\n"
},
{
"answer_id": 281788,
"author": "Bdebeez",
"author_id": 35516,
"author_profile": "https://Stackoverflow.com/users/35516",
"pm_score": 2,
"selected": false,
"text": "<p>It sounds like you may be adding them in the wrong place. If you moved the addition of the subviews into the ViewController, then you could do this work on viewDidLoad and you'd be guaranteed that the main view was already initialized and ready to access.</p>\n"
},
{
"answer_id": 6483410,
"author": "Matej Ukmar",
"author_id": 520491,
"author_profile": "https://Stackoverflow.com/users/520491",
"pm_score": 1,
"selected": false,
"text": "<p>Dummy explanation would be like this:</p>\n\n<p>Subclass UIViewController whenever you plan to display the view as modal (presentModalViewController) or inside UINavigationController (pushViewController)</p>\n\n<p>Subclass UIView whenever it is a small component inside main view... for example you wish to do custom button or ...</p>\n\n<p>More specifically in your example ... if you are initializing UIViewControllers you can set view's properties eg. like frame size only after your view is added to superview. Only \nat that point UIViewController loads and initializes its view.</p>\n\n<p>I think in your case you should use UIViews ... you can set frame size immediately after allocating&initializing them.</p>\n"
}
] |
2008/11/11
|
[
"https://Stackoverflow.com/questions/280017",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2773/"
] |
I'm trying to wrap my head around the roles of UIViews and UIViewControllers. If I'm creating and inserting subviews programmatically, is it typical to do this from the view or the controller?
I'm really just wondering if there's a convention/pattern for this. In my sample application, I'm loading 50 images at runtime, adding them as subviews to the main view, then letting the user drag them around the screen. I'm currently doing all the initialization in the view's initWithCoder:
```
- (id)initWithCoder:(NSCoder*)coder
{
if (self = [super initWithCoder:coder]) {
// load UIImageViews and add them to the subview
}
return self;
}
```
The view also implements touchesBegan/touchesMoved to allow dragging. My problem comes when I try to access [self frame].size in initWithCoder, it doesn't seem to be initialized yet. This makes me think I may be loading the images in the wrong place...
|
It depends on what you're doing. If the view represents something "packaged", then you create subviews from the view itself. If you're merely aggregating views together, then you should do it from the view controller.
Think about traditional encapsulation. Is your subview conceptually "part" of its superview, or does it just live there in the drawing hierarchy?
|
280,033 |
<p>I am new to C++ and I had a few general questions about code separation. I have currently built a small application, all in one file. What I want to do now is convert this into separate files such that they contain similar code or whatnot. My real question right now is, how do I know how to separate things? What is the invisible margin that code should be separated at? </p>
<p>Also, what's the point of header files? Is it to forward declare methods and classes so I can use them in my code before they are included by the linker during compilation? </p>
<p>Any insight into methods or best practises would be great, thanks!</p>
|
[
{
"answer_id": 280048,
"author": "Martin York",
"author_id": 14065,
"author_profile": "https://Stackoverflow.com/users/14065",
"pm_score": 5,
"selected": false,
"text": "<p>Header files should contain class and function declarations.</p>\n<p>Source files contain class and function definitions.</p>\n<p>It is standard practice (i.e. read easier) to have one declaration per header file and one definition per source file, though for small (read simpler helper) objects you sometimes group them with related more substantial objects.</p>\n<h3>Example: Class Menu</h3>\n<pre><code>Menu.h: Contains the Menu declaration.\nMenu.cpp: Contains the Menu definition.\n</code></pre>\n<p>The reason header files contain the declarations is so that you can include them from multiple source files and thus each source file has exactly the same definition of each class and function.</p>\n<p>Consider it this way:<br>\nIf you did not have header files then you would need to have the class and/or function declarations (without) definitions in every source file, this means a copy of the same declaration in every file. Thus if you modify a class you need to make the same modification in every file. By the use of a header file you have the declaration in one place and thus only one object to modify.</p>\n"
},
{
"answer_id": 280054,
"author": "David Dibben",
"author_id": 5022,
"author_profile": "https://Stackoverflow.com/users/5022",
"pm_score": 2,
"selected": false,
"text": "<p>Deciding how to separate your code into different classes/functions is one of main tasks of programing. There are many different guidelines on how to do this and I would recommend reading some tutorials on C++ and Object Oriented Design to get you started.</p>\n\n<p>Some basic guidelines will be</p>\n\n<ul>\n<li>Put things together which are used\ntogether </li>\n<li>Create classes for domain objects\n(eg files, collections etc)</li>\n</ul>\n\n<p>Header files allow you to declare a class or function and then use it in several different source files. For example, if you declare a class in a header file</p>\n\n<pre><code>// A.h\nclass A\n{\npublic:\n int fn();\n};\n</code></pre>\n\n<p>You can then use this class in several source files:</p>\n\n<pre><code>// A.cpp\n#include \"A.h\"\nint A::fn() {/* implementation of fn */}\n\n//B.cpp\n#include \"A.h\"\nvoid OtherFunction() {\n A a;\n a.fn();\n}\n</code></pre>\n\n<p>So header files enable you to separate the declaration from the implementation. If you were to put everything (declaration and implementation) in a source file (eg A.cpp) then try to include that in a second file, eg</p>\n\n<pre><code>// B.cpp\n#include \"A.cpp\" //DON'T do this!\n</code></pre>\n\n<p>Then you could compile B.cpp but when you try to link your program the linker will complain that you have multiply defined objects - this is because you have multiple copies of the implementation of A.</p>\n"
},
{
"answer_id": 280099,
"author": "Johannes Schaub - litb",
"author_id": 34509,
"author_profile": "https://Stackoverflow.com/users/34509",
"pm_score": 5,
"selected": false,
"text": "<p>First, you should not put anything into headers that is not needed to be visible by any other file, other than the one that needs it. Then, let's define something we need below.</p>\n\n<blockquote>\n <h3>Translation Unit</h3>\n \n <p>A Translation Unit is the current code being compiled, and all the code included \n by it, directly or indirectly. One Translation unit translates to one .o / .obj file.</p>\n \n <h3>Program</h3>\n \n <p>That's all your .o / .obj files linked together into one binary file that can be \n executed to form a process.</p>\n</blockquote>\n\n<p>What are the main points of having different translation units?</p>\n\n<ol>\n<li>Reduce dependencies, so that if you change one method of one class, you don't have to recompile all the code of your program, but only the affected translation unit. An</li>\n<li>Reduce possible name clashes by having translation unit local names, that are not visible by other translation unit when linking them together.</li>\n</ol>\n\n<p>Now, how can you split your code into different translation units? The answer is there is no \"so you do it!\", but you have to consider it on a case-by-case basis. It's often clear, since you have different classes, which can and should be put in different translation units:</p>\n\n<p><strong><code>foo.hpp:</code></strong></p>\n\n<pre><code>/* Only declaration of class foo we define below. Note that a declaration\n * is not a definition. But a definition is always also a declaration */\nclass foo;\n\n/* definition of a class foo. the same class definition can appear \n in multiple translation units provided that each definition is the same \n basicially, but only once per translation unit. This too is called the \n \"One Definition Rule\" (ODR). */\nclass foo {\n /* declaration of a member function doit */\n void doit();\n\n /* definition of an data-member age */\n int age;\n};\n</code></pre>\n\n<p>Declare some free functions and objects:</p>\n\n<pre><code>/* if you have translation unit non-local (with so-called extern linkage) \n names, you declare them here, so other translation units can include \n your file \"foo.hpp\" and use them. */\nvoid getTheAnswer();\n\n/* to avoid that the following is a definition of a object, you put \"extern\" \n in front of it. */\nextern int answerCheat;\n</code></pre>\n\n<p><strong><code>foo.cpp:</code></strong></p>\n\n<pre><code>/* include the header of it */\n#include \"foo.hpp\"\n\n/* definition of the member function doit */\nvoid foo::doit() {\n /* ... */\n}\n\n/* definition of a translation unit local name. preferred way in c++. */\nnamespace {\n void help() {\n /* ... */\n }\n}\n\nvoid getTheAnswer() {\n /* let's call our helper function */\n help();\n /* ... */\n}\n\n/* define answerCheat. non-const objects are translation unit nonlocal \n by default */\nint answerCheat = 42;\n</code></pre>\n\n<p><strong><code>bar.hpp:</code></strong></p>\n\n<pre><code>/* so, this is the same as above, just with other classes/files... */\nclass bar {\npublic:\n bar(); /* constructor */\n}; \n</code></pre>\n\n<p><strong><code>bar.cpp:</code></strong></p>\n\n<pre><code>/* we need the foo.hpp file, which declares getTheAnswer() */\n#include \"foo.hpp\"\n#include \"bar.hpp\"\n\nbar::bar() {\n /* make use of getTheAnswer() */\n getTheAnswer();\n}\n</code></pre>\n\n<p>Please note that names within an anonymous namespace (as above) do not clash since they appear to be translation unit local. in reality they are not, they just have unique names so that they do not clash. if you really want (there is little reason to) translation unit local names (for example because of compatibility with c so C code can call your function) you can do it like this:</p>\n\n<pre><code>static void help() { \n /* .... */\n}\n</code></pre>\n\n<p>The ODR also says that you cannot have more than one definition of any object or non-inline function in one program (classes are types, not objects, so it doesn't apply to them). So you have to watch out not to put non-inline functions into headers, or not putting objects like \"int foo;\" in headers. That will cause linker errors then when the linker tries to link the translation units including those headers together. </p>\n\n<p>I hope i could help you a bit. Now that was a long answer, there are indeed errors somewhere. I know that a translation unit strictly is defined another way (output of the pre-processor). But i think it would not add big value to include that into the above, and it would confuse the matter. Please feel free to slap me if you find real bugs :)</p>\n"
},
{
"answer_id": 561821,
"author": "Elroy",
"author_id": 56097,
"author_profile": "https://Stackoverflow.com/users/56097",
"pm_score": 0,
"selected": false,
"text": "<p>Suggestion:\n1. Have a design ready for your application now.\n2. Based on the design, create necessary objects that interact with each other.\n3. Refactor or completely change the existing code to suit the newly created design.</p>\n\n<p>Header files provide an interface to the other classes that might use it's functionality.</p>\n"
}
] |
2008/11/11
|
[
"https://Stackoverflow.com/questions/280033",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] |
I am new to C++ and I had a few general questions about code separation. I have currently built a small application, all in one file. What I want to do now is convert this into separate files such that they contain similar code or whatnot. My real question right now is, how do I know how to separate things? What is the invisible margin that code should be separated at?
Also, what's the point of header files? Is it to forward declare methods and classes so I can use them in my code before they are included by the linker during compilation?
Any insight into methods or best practises would be great, thanks!
|
Header files should contain class and function declarations.
Source files contain class and function definitions.
It is standard practice (i.e. read easier) to have one declaration per header file and one definition per source file, though for small (read simpler helper) objects you sometimes group them with related more substantial objects.
### Example: Class Menu
```
Menu.h: Contains the Menu declaration.
Menu.cpp: Contains the Menu definition.
```
The reason header files contain the declarations is so that you can include them from multiple source files and thus each source file has exactly the same definition of each class and function.
Consider it this way:
If you did not have header files then you would need to have the class and/or function declarations (without) definitions in every source file, this means a copy of the same declaration in every file. Thus if you modify a class you need to make the same modification in every file. By the use of a header file you have the declaration in one place and thus only one object to modify.
|
280,049 |
<p>I want to know when an image has finished loading. Is there a way to do it with a callback?</p>
<p>If not, is there a way to do it at all?</p>
|
[
{
"answer_id": 280087,
"author": "keparo",
"author_id": 19468,
"author_profile": "https://Stackoverflow.com/users/19468",
"pm_score": 6,
"selected": false,
"text": "<p><strong>Image.onload()</strong> will often work. </p>\n\n<p>To use it, you'll need to be sure to bind the event handler before you set the src attribute.</p>\n\n<p><strong>Related Links:</strong></p>\n\n<ul>\n<li><a href=\"https://developer.mozilla.org/en-US/docs/Web/API/GlobalEventHandlers/onload\" rel=\"noreferrer\"><strong>Mozilla on Image.onload()</strong></a></li>\n</ul>\n\n<p><strong>Example Usage:</strong></p>\n\n<p><div class=\"snippet\" data-lang=\"js\" data-hide=\"false\" data-console=\"true\" data-babel=\"false\">\r\n<div class=\"snippet-code\">\r\n<pre class=\"snippet-code-js lang-js prettyprint-override\"><code> window.onload = function () {\r\n\r\n var logo = document.getElementById('sologo');\r\n\r\n logo.onload = function () {\r\n alert (\"The image has loaded!\"); \r\n };\r\n\r\n setTimeout(function(){\r\n logo.src = 'https://edmullen.net/test/rc.jpg'; \r\n }, 5000);\r\n };</code></pre>\r\n<pre class=\"snippet-code-html lang-html prettyprint-override\"><code> <html>\r\n <head>\r\n <title>Image onload()</title>\r\n </head>\r\n <body>\r\n\r\n <img src=\"#\" alt=\"This image is going to load\" id=\"sologo\"/>\r\n\r\n <script type=\"text/javascript\">\r\n\r\n </script>\r\n </body>\r\n </html></code></pre>\r\n</div>\r\n</div>\r\n</p>\n"
},
{
"answer_id": 280142,
"author": "Jon DellOro",
"author_id": 36456,
"author_profile": "https://Stackoverflow.com/users/36456",
"pm_score": 4,
"selected": false,
"text": "<p>You can use the .complete property of the Javascript image class.</p>\n\n<p>I have an application where I store a number of Image objects in an array, that will be dynamically added to the screen, and as they're loading I write updates to another div on the page. Here's a code snippet:</p>\n\n<pre><code>var gAllImages = [];\n\nfunction makeThumbDivs(thumbnailsBegin, thumbnailsEnd)\n{\n gAllImages = [];\n\n for (var i = thumbnailsBegin; i < thumbnailsEnd; i++) \n {\n var theImage = new Image();\n theImage.src = \"thumbs/\" + getFilename(globals.gAllPageGUIDs[i]);\n gAllImages.push(theImage);\n\n setTimeout('checkForAllImagesLoaded()', 5);\n window.status=\"Creating thumbnail \"+(i+1)+\" of \" + thumbnailsEnd;\n\n // make a new div containing that image\n makeASingleThumbDiv(globals.gAllPageGUIDs[i]);\n }\n}\n\nfunction checkForAllImagesLoaded()\n{\n for (var i = 0; i < gAllImages.length; i++) {\n if (!gAllImages[i].complete) {\n var percentage = i * 100.0 / (gAllImages.length);\n percentage = percentage.toFixed(0).toString() + ' %';\n\n userMessagesController.setMessage(\"loading... \" + percentage);\n setTimeout('checkForAllImagesLoaded()', 20);\n return;\n }\n }\n\n userMessagesController.setMessage(globals.defaultTitle);\n}\n</code></pre>\n"
},
{
"answer_id": 4913155,
"author": "jimmystormig",
"author_id": 84236,
"author_profile": "https://Stackoverflow.com/users/84236",
"pm_score": 4,
"selected": false,
"text": "<p>You could use the load()-event in jQuery but it won't always fire if the image is loaded from the browser cache. This plugin <a href=\"https://github.com/peol/jquery.imgloaded/raw/master/ahpi.imgload.js\" rel=\"noreferrer\">https://github.com/peol/jquery.imgloaded/raw/master/ahpi.imgload.js</a> can be used to remedy that problem.</p>\n"
},
{
"answer_id": 13053752,
"author": "dave",
"author_id": 1771857,
"author_profile": "https://Stackoverflow.com/users/1771857",
"pm_score": 0,
"selected": false,
"text": "<p>these functions will solve the problem, you need to implement the <code>DrawThumbnails</code> function and have a global variable to store the images. I love to get this to work with a class object that has the <code>ThumbnailImageArray</code> as a member variable, but am struggling! </p>\n\n<p>called as in <code>addThumbnailImages(10);</code></p>\n\n<pre><code>var ThumbnailImageArray = [];\n\nfunction addThumbnailImages(MaxNumberOfImages)\n{\n var imgs = [];\n\n for (var i=1; i<MaxNumberOfImages; i++)\n {\n imgs.push(i+\".jpeg\");\n }\n\n preloadimages(imgs).done(function (images){\n var c=0;\n\n for(var i=0; i<images.length; i++)\n {\n if(images[i].width >0) \n {\n if(c != i)\n images[c] = images[i];\n c++;\n }\n }\n\n images.length = c;\n\n DrawThumbnails();\n });\n}\n\n\n\nfunction preloadimages(arr)\n{\n var loadedimages=0\n var postaction=function(){}\n var arr=(typeof arr!=\"object\")? [arr] : arr\n\n function imageloadpost()\n {\n loadedimages++;\n if (loadedimages==arr.length)\n {\n postaction(ThumbnailImageArray); //call postaction and pass in newimages array as parameter\n }\n };\n\n for (var i=0; i<arr.length; i++)\n {\n ThumbnailImageArray[i]=new Image();\n ThumbnailImageArray[i].src=arr[i];\n ThumbnailImageArray[i].onload=function(){ imageloadpost();};\n ThumbnailImageArray[i].onerror=function(){ imageloadpost();};\n }\n //return blank object with done() method \n //remember user defined callback functions to be called when images load\n return { done:function(f){ postaction=f || postaction } };\n}\n</code></pre>\n"
},
{
"answer_id": 24201249,
"author": "Ciro Santilli OurBigBook.com",
"author_id": 895245,
"author_profile": "https://Stackoverflow.com/users/895245",
"pm_score": 8,
"selected": false,
"text": "<p><strong><code>.complete</code> + callback</strong></p>\n\n<p>This is a standards compliant method without extra dependencies, and waits no longer than necessary:</p>\n\n<pre><code>var img = document.querySelector('img')\n\nfunction loaded() {\n alert('loaded')\n}\n\nif (img.complete) {\n loaded()\n} else {\n img.addEventListener('load', loaded)\n img.addEventListener('error', function() {\n alert('error')\n })\n}\n</code></pre>\n\n<p>Source: <a href=\"http://www.html5rocks.com/en/tutorials/es6/promises/\" rel=\"noreferrer\">http://www.html5rocks.com/en/tutorials/es6/promises/</a></p>\n"
},
{
"answer_id": 42946530,
"author": "Alexander Drobyshevsky",
"author_id": 1693748,
"author_profile": "https://Stackoverflow.com/users/1693748",
"pm_score": 2,
"selected": false,
"text": "<p>Here is jQuery equivalent:</p>\n\n<pre><code>var $img = $('img');\n\nif ($img.length > 0 && !$img.get(0).complete) {\n $img.on('load', triggerAction);\n}\n\nfunction triggerAction() {\n alert('img has been loaded');\n}\n</code></pre>\n"
},
{
"answer_id": 48208414,
"author": "Idan Beker",
"author_id": 7932878,
"author_profile": "https://Stackoverflow.com/users/7932878",
"pm_score": 4,
"selected": false,
"text": "<p>Life is too short for jquery.</p>\n\n<p><div class=\"snippet\" data-lang=\"js\" data-hide=\"false\" data-console=\"true\" data-babel=\"false\">\r\n<div class=\"snippet-code\">\r\n<pre class=\"snippet-code-js lang-js prettyprint-override\"><code>function waitForImageToLoad(imageElement){\r\n return new Promise(resolve=>{imageElement.onload = resolve})\r\n}\r\n\r\nvar myImage = document.getElementById('myImage');\r\nvar newImageSrc = \"https://pmchollywoodlife.files.wordpress.com/2011/12/justin-bieber-bio-photo1.jpg?w=620\"\r\n\r\nmyImage.src = newImageSrc;\r\nwaitForImageToLoad(myImage).then(()=>{\r\n // Image have loaded.\r\n console.log('Loaded lol')\r\n});</code></pre>\r\n<pre class=\"snippet-code-html lang-html prettyprint-override\"><code><img id=\"myImage\" src=\"\"></code></pre>\r\n</div>\r\n</div>\r\n</p>\n"
},
{
"answer_id": 50569577,
"author": "Mike",
"author_id": 232115,
"author_profile": "https://Stackoverflow.com/users/232115",
"pm_score": -1,
"selected": false,
"text": "<p>If you are using React.js, you could do this:</p>\n\n<pre><code>render() {\n</code></pre>\n\n<p>// ...</p>\n\n<pre><code><img \nonLoad={() => this.onImgLoad({ item })}\nonError={() => this.onImgLoad({ item })}\n\nsrc={item.src} key={item.key}\nref={item.key} />\n</code></pre>\n\n<p>// ...\n }</p>\n\n<p>Where:\n<li>- onLoad (...) now will called with something like this:\n{ src: \"<a href=\"https://......png\" rel=\"nofollow noreferrer\">https://......png</a>\", key:\"1\" }\nyou can use this as \"key\" to know which images is loaded correctly and which not.\n<li>- onError(...) it is the same but for errors.\n<li>- the object \"item\" is something like this { key:\"..\", src:\"..\"}\n you can use to store the images' URL and key in order to use in a list of images.</p>\n"
},
{
"answer_id": 60971078,
"author": "Sajad",
"author_id": 4205231,
"author_profile": "https://Stackoverflow.com/users/4205231",
"pm_score": 2,
"selected": false,
"text": "<p>If the goal is to style the img after browser has rendered image, you should:</p>\n\n<pre><code>const img = new Image();\nimg.src = 'path/to/img.jpg';\n\nimg.decode().then(() => {\n/* set styles */\n/* add img to DOM */ \n});\n</code></pre>\n\n<p>because the browser first <code>loads the compressed version of image</code>, then <code>decodes it</code>, finally <code>paints</code> it. since there is no event for <code>paint</code> you should run your logic after browser has <code>decoded</code> the img tag.</p>\n"
},
{
"answer_id": 62185013,
"author": "Hugh",
"author_id": 8930534,
"author_profile": "https://Stackoverflow.com/users/8930534",
"pm_score": 2,
"selected": false,
"text": "<p>Not suitable for 2008 when the question was asked, but these days this works well for me:</p>\n\n<pre class=\"lang-js prettyprint-override\"><code>async function newImageSrc(src) {\n // Get a reference to the image in whatever way suits.\n let image = document.getElementById('image-id');\n\n // Update the source.\n img.src = src;\n\n // Wait for it to load.\n await new Promise((resolve) => { image.onload = resolve; });\n\n // Done!\n console.log('image loaded! do something...');\n}\n</code></pre>\n"
}
] |
2008/11/11
|
[
"https://Stackoverflow.com/questions/280049",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] |
I want to know when an image has finished loading. Is there a way to do it with a callback?
If not, is there a way to do it at all?
|
**`.complete` + callback**
This is a standards compliant method without extra dependencies, and waits no longer than necessary:
```
var img = document.querySelector('img')
function loaded() {
alert('loaded')
}
if (img.complete) {
loaded()
} else {
img.addEventListener('load', loaded)
img.addEventListener('error', function() {
alert('error')
})
}
```
Source: <http://www.html5rocks.com/en/tutorials/es6/promises/>
|
280,053 |
<p>Please help! Have been staring at this for 12 hours; and have looked online and can't find solution.</p>
<p>In my application, I use 2 UIView controls in separate pages/controllers:</p>
<ul>
<li>UIImageView (retrieve data via
NSData dataWithContentsOfUrl)</li>
<li>UIWebView</li>
</ul>
<p>Just to isolate my code, and make it easier to explain, I created a new view based project called "MyTestApplication"</p>
<p>1 - I added a simple NSData dataWithContentsOfUrl in the delegate function.</p>
<pre><code>NSData *imageData = [NSData dataWithContentsOfURL:
[NSURL URLWithString:@"http://www.google.com/intl/en_ALL/images/logo.gif"]];
</code></pre>
<p>(Nothing to release here since it's all using convenience functions)</p>
<p><a href="http://img.skitch.com/20081110-j5tn5n7ixph95ys4rpchibaw5p.preview.jpg" rel="nofollow noreferrer">alt text http://img.skitch.com/20081110-j5tn5n7ixph95ys4rpchibaw5p.preview.jpg</a></p>
<p><a href="http://img.skitch.com/20081110-j5tn5n7ixph95ys4rpchibaw5p.jpg" rel="nofollow noreferrer">View Image</a></p>
<p>2 - Run it to verify no leaks (as expected)</p>
<p><a href="http://img.skitch.com/20081110-fy2qrkgy47hm4fe2f1aakd4muw.preview.jpg" rel="nofollow noreferrer">alt text http://img.skitch.com/20081110-fy2qrkgy47hm4fe2f1aakd4muw.preview.jpg</a></p>
<p><a href="http://img.skitch.com/20081110-fy2qrkgy47hm4fe2f1aakd4muw.jpg" rel="nofollow noreferrer">View Image</a></p>
<p>3 - Open the ViewController.xib and simply add a UIWebView from the library (no need to wire it up)</p>
<p><a href="http://img.skitch.com/20081110-d63c3yh1a1kqiciy73q8uyd68j.preview.jpg" rel="nofollow noreferrer">alt text http://img.skitch.com/20081110-d63c3yh1a1kqiciy73q8uyd68j.preview.jpg</a></p>
<p><a href="http://img.skitch.com/20081110-d63c3yh1a1kqiciy73q8uyd68j.jpg" rel="nofollow noreferrer">View Image</a></p>
<p>4 - Run it to verify there are leaks! (why???)</p>
<p><a href="http://img.skitch.com/20081110-qtxcfwntbcc3csabda3r6nfjg6.preview.jpg" rel="nofollow noreferrer">alt text http://img.skitch.com/20081110-qtxcfwntbcc3csabda3r6nfjg6.preview.jpg</a></p>
<p><a href="http://img.skitch.com/20081110-qtxcfwntbcc3csabda3r6nfjg6.jpg" rel="nofollow noreferrer">View Image</a></p>
<p>What am I doing wrong? Please help!</p>
<p>Why would NSData cause memory leak if I'm using UIWebView? I just don't get it.
Thanks. </p>
|
[
{
"answer_id": 280064,
"author": "Justin Weiss",
"author_id": 33821,
"author_profile": "https://Stackoverflow.com/users/33821",
"pm_score": 2,
"selected": false,
"text": "<p>I think this is what's happening: </p>\n\n<p>When ViewController.xib is loaded, an instance of UIWebView is allocated and initialized. Since you're not wiring it up anywhere, it's not getting released. I think you need to wire it up and release it in your backing View Controller's dealloc function. I remember having to manually release every object I created in a xib file. </p>\n"
},
{
"answer_id": 400526,
"author": "Genericrich",
"author_id": 39932,
"author_profile": "https://Stackoverflow.com/users/39932",
"pm_score": 1,
"selected": false,
"text": "<p>Are you running Leaks on the Simulator? If so, caveat coder. The Simulator will leak memory where the iPhone hardware won't. No simulator is ever a perfect match for the exact behavior of your code on the device.</p>\n\n<p>I would test on the device as well. I just did the same thing on a similar issue with UITableViewController which was leaking in the Sim but not on the phone.</p>\n"
},
{
"answer_id": 1442691,
"author": "Sam",
"author_id": 101750,
"author_profile": "https://Stackoverflow.com/users/101750",
"pm_score": 3,
"selected": false,
"text": "<p>I was also having trouble with leaks from NSData's <code>dataWithContentsOfURL:</code> in the iPhone simulator. I found that when I used the other convenience method (<code>dataWithContentsOfURL:options:error:</code>) I would not get the memory leak.</p>\n\n<p>My code looked something like this:</p>\n\n<pre><code>NSURL *url = [NSURL URLWithString:urlString];\nNSError *error = nil;\nNSData *data = [NSData dataWithContentsOfURL:url\n options:0\n error:&error];\n</code></pre>\n\n<p><a href=\"http://developer.apple.com/mac/library/documentation/Cocoa/Reference/Foundation/Classes/NSData_Class/Reference/Reference.html#//apple_ref/occ/clm/NSData/dataWithContentsOfURL:options:error:\" rel=\"nofollow noreferrer\">Link to documentation</a></p>\n"
},
{
"answer_id": 30437935,
"author": "palob",
"author_id": 395963,
"author_profile": "https://Stackoverflow.com/users/395963",
"pm_score": 0,
"selected": false,
"text": "<p><code>[NSData dataWithContentsOfURL:url options:0 error:&error]</code> did not help me on iOS8.</p>\n\n<p>But following works correctly:</p>\n\n<pre class=\"lang-objectivec prettyprint-override\"><code>NSURLRequest* request = [NSURLRequest requestWithURL:imageURL];\nNSData* imageData = [NSURLConnection sendSynchronousRequest:request returningResponse:nil error:nil];\n[[NSURLCache sharedURLCache] removeCachedResponseForRequest:request];\n</code></pre>\n\n<p>Production code would need also response and error parameters.</p>\n"
}
] |
2008/11/11
|
[
"https://Stackoverflow.com/questions/280053",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] |
Please help! Have been staring at this for 12 hours; and have looked online and can't find solution.
In my application, I use 2 UIView controls in separate pages/controllers:
* UIImageView (retrieve data via
NSData dataWithContentsOfUrl)
* UIWebView
Just to isolate my code, and make it easier to explain, I created a new view based project called "MyTestApplication"
1 - I added a simple NSData dataWithContentsOfUrl in the delegate function.
```
NSData *imageData = [NSData dataWithContentsOfURL:
[NSURL URLWithString:@"http://www.google.com/intl/en_ALL/images/logo.gif"]];
```
(Nothing to release here since it's all using convenience functions)
[alt text http://img.skitch.com/20081110-j5tn5n7ixph95ys4rpchibaw5p.preview.jpg](http://img.skitch.com/20081110-j5tn5n7ixph95ys4rpchibaw5p.preview.jpg)
[View Image](http://img.skitch.com/20081110-j5tn5n7ixph95ys4rpchibaw5p.jpg)
2 - Run it to verify no leaks (as expected)
[alt text http://img.skitch.com/20081110-fy2qrkgy47hm4fe2f1aakd4muw.preview.jpg](http://img.skitch.com/20081110-fy2qrkgy47hm4fe2f1aakd4muw.preview.jpg)
[View Image](http://img.skitch.com/20081110-fy2qrkgy47hm4fe2f1aakd4muw.jpg)
3 - Open the ViewController.xib and simply add a UIWebView from the library (no need to wire it up)
[alt text http://img.skitch.com/20081110-d63c3yh1a1kqiciy73q8uyd68j.preview.jpg](http://img.skitch.com/20081110-d63c3yh1a1kqiciy73q8uyd68j.preview.jpg)
[View Image](http://img.skitch.com/20081110-d63c3yh1a1kqiciy73q8uyd68j.jpg)
4 - Run it to verify there are leaks! (why???)
[alt text http://img.skitch.com/20081110-qtxcfwntbcc3csabda3r6nfjg6.preview.jpg](http://img.skitch.com/20081110-qtxcfwntbcc3csabda3r6nfjg6.preview.jpg)
[View Image](http://img.skitch.com/20081110-qtxcfwntbcc3csabda3r6nfjg6.jpg)
What am I doing wrong? Please help!
Why would NSData cause memory leak if I'm using UIWebView? I just don't get it.
Thanks.
|
I was also having trouble with leaks from NSData's `dataWithContentsOfURL:` in the iPhone simulator. I found that when I used the other convenience method (`dataWithContentsOfURL:options:error:`) I would not get the memory leak.
My code looked something like this:
```
NSURL *url = [NSURL URLWithString:urlString];
NSError *error = nil;
NSData *data = [NSData dataWithContentsOfURL:url
options:0
error:&error];
```
[Link to documentation](http://developer.apple.com/mac/library/documentation/Cocoa/Reference/Foundation/Classes/NSData_Class/Reference/Reference.html#//apple_ref/occ/clm/NSData/dataWithContentsOfURL:options:error:)
|
280,058 |
<p>Basically I need to insert a bunch of data to an Excel file. Creating an OleDB connection appears to be the fastest way but I've seen to have run into memory issues. The memory used by the process seems to keep growing as I execute INSERT queries. I've narrowed them down to only happen when I output to the Excel file (the memory holds steady without the output to Excel). I close and reopen the connection in between each worksheet, but this doesn't seem to have an effect on the memory usage (as so does Dispose()). The data is written successfully as I can verify with relatively small data sets. If anyone has insight, it would be appreciated.</p>
<p><em>initializeADOConn()</em> is called in the constructor</p>
<p><em>initADOConnInsertComm()</em> creates the insert parameterized insert query</p>
<p><em>writeRecord()</em> is called whenever a new record is written. New worksheets are created as needed.</p>
<pre><code>public bool initializeADOConn()
{
/* Set up the connection string and connect.*/
string connectionString = @"Provider=Microsoft.Jet.OLEDB.4.0;" +
"Data Source=" + this.destination + ";Extended Properties=\"Excel 8.0;HDR=YES;\"";
//DbProviderFactory factory =
//DbProviderFactories.GetFactory("System.Data.OleDb");
conn = new OleDbConnection(connectionString);
conn.ConnectionString = connectionString;
conn.Open();
/* Intialize the insert command. */
initADOConnInsertComm();
return true;
}
public override bool writeRecord(FileListerFileInfo file)
{
/* If all available sheets are full, make a new one. */
if (numWritten % EXCEL_MAX_ROWS == 0)
{
conn.Close();
conn.Open();
createNextSheet();
}
/* Count this record as written. */
numWritten++;
/* Get all of the properties of the FileListerFileInfo record and add
* them to the parameters of the insert query. */
PropertyInfo[] properties = typeof(FileListerFileInfo).GetProperties();
for (int i = 0; i < insertComm.Parameters.Count; i++)
insertComm.Parameters[i].Value = properties[i].GetValue(file, null);
/* Add the record. */
insertComm.ExecuteNonQuery();
return true;
}
</code></pre>
<p>EDIT:</p>
<p>No, I do not use Excel at all. I'm intentionally avoiding Interop.Excel due to its poor performance (at least from my dabbles with it).</p>
|
[
{
"answer_id": 280078,
"author": "Charles Graham",
"author_id": 7705,
"author_profile": "https://Stackoverflow.com/users/7705",
"pm_score": 0,
"selected": false,
"text": "<p>Instead of writing one record at a time, can you find a way to insert in a Bulk capacity? I try not to use crazy DataSet stuff, but isn't there a way to make all your inserts happen local first and then make them go up in one fell swoop?\nDoes this processes open up Excel in the background? Do these processes die afterwards?</p>\n"
},
{
"answer_id": 280131,
"author": "MusiGenesis",
"author_id": 14606,
"author_profile": "https://Stackoverflow.com/users/14606",
"pm_score": 3,
"selected": true,
"text": "<p>The answer is <strong>Yes</strong>, the formula you describe <em>does</em> equal a bad time.</p>\n\n<p>If you have a database handy (SQL Server or Access are good for this), you can do all of your inserts into a database table, and then export the table all at once into an Excel spreadsheet.</p>\n\n<p>Generally speaking, databases are good at handling lots of inserts, while spreadsheets aren't.</p>\n"
},
{
"answer_id": 280348,
"author": "onedaywhen",
"author_id": 15354,
"author_profile": "https://Stackoverflow.com/users/15354",
"pm_score": 1,
"selected": false,
"text": "<p>Here are a couple of ideas:</p>\n\n<p>Is the target workbook open? There is a bug (<a href=\"http://support.microsoft.com/kb/319998/en-us\" rel=\"nofollow noreferrer\">Memory leak occurs when you query an open Excel worksheet by using ActiveX Data Objects</a>) which IIRC is actually in the OLE DB provider for Jet (which you are using) although this isn't confirmed in the above article.</p>\n\n<p>Regardless, bulk insert would seem to be the way to go. </p>\n\n<p>You could use the same Jet OLE DB provider to do this: all you need is a one row table. You could even fabricate one on the fly. To create a new Excel workbook, execute <code>CREATE TABLE</code> DDL using a non-existent xls file in the connection string and the provider will create the workbook for you with a worksheet to represent the table. You have a connection to your Excel workbook so you could execute this:</p>\n\n<pre><code>CREATE TABLE [EXCEL 8.0;DATABASE=C:\\MyFabricatedWorkbook;HDR=YES].OneRowTable \n(\n x FLOAT\n);\n</code></pre>\n\n<p>(Even better IMO would be to fabricate a Jet database i.e. .mdb file). </p>\n\n<p>Use <code>INSERT</code> to create a dummy row:</p>\n\n<pre><code>INSERT INTO [EXCEL 8.0;DATABASE=C:\\MyFabricatedWorkbook;HDR=YES].OneRowTable (x) \n VALUES (0);\n</code></pre>\n\n<p>Then, still using your connection to your target workbook, you could use something similar to the following to create a derived table (DT1) of your values to <code>INSERT</code> in one hit:</p>\n\n<pre><code>INSERT INTO MyExcelTable (key_col, data_col)\nSELECT DT1.key_col, DT1.data_col\nFROM (\n SELECT 22 AS key_col, 'abc' AS data_col\n FROM [EXCEL 8.0;DATABASE=C:\\MyFabricatedWorkbook;HDR=YES].OneRowTable\n UNION ALL\n SELECT 55 AS key_col, 'xyz' AS data_col\n FROM [EXCEL 8.0;DATABASE=C:\\MyFabricatedWorkbook;HDR=YES].OneRowTable\n UNION ALL\n SELECT 99 AS key_col, 'efg' AS data_col\n FROM [EXCEL 8.0;DATABASE=C:\\MyFabricatedWorkbook;HDR=YES].OneRowTable\n) AS DT1;\n</code></pre>\n"
}
] |
2008/11/11
|
[
"https://Stackoverflow.com/questions/280058",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1469014/"
] |
Basically I need to insert a bunch of data to an Excel file. Creating an OleDB connection appears to be the fastest way but I've seen to have run into memory issues. The memory used by the process seems to keep growing as I execute INSERT queries. I've narrowed them down to only happen when I output to the Excel file (the memory holds steady without the output to Excel). I close and reopen the connection in between each worksheet, but this doesn't seem to have an effect on the memory usage (as so does Dispose()). The data is written successfully as I can verify with relatively small data sets. If anyone has insight, it would be appreciated.
*initializeADOConn()* is called in the constructor
*initADOConnInsertComm()* creates the insert parameterized insert query
*writeRecord()* is called whenever a new record is written. New worksheets are created as needed.
```
public bool initializeADOConn()
{
/* Set up the connection string and connect.*/
string connectionString = @"Provider=Microsoft.Jet.OLEDB.4.0;" +
"Data Source=" + this.destination + ";Extended Properties=\"Excel 8.0;HDR=YES;\"";
//DbProviderFactory factory =
//DbProviderFactories.GetFactory("System.Data.OleDb");
conn = new OleDbConnection(connectionString);
conn.ConnectionString = connectionString;
conn.Open();
/* Intialize the insert command. */
initADOConnInsertComm();
return true;
}
public override bool writeRecord(FileListerFileInfo file)
{
/* If all available sheets are full, make a new one. */
if (numWritten % EXCEL_MAX_ROWS == 0)
{
conn.Close();
conn.Open();
createNextSheet();
}
/* Count this record as written. */
numWritten++;
/* Get all of the properties of the FileListerFileInfo record and add
* them to the parameters of the insert query. */
PropertyInfo[] properties = typeof(FileListerFileInfo).GetProperties();
for (int i = 0; i < insertComm.Parameters.Count; i++)
insertComm.Parameters[i].Value = properties[i].GetValue(file, null);
/* Add the record. */
insertComm.ExecuteNonQuery();
return true;
}
```
EDIT:
No, I do not use Excel at all. I'm intentionally avoiding Interop.Excel due to its poor performance (at least from my dabbles with it).
|
The answer is **Yes**, the formula you describe *does* equal a bad time.
If you have a database handy (SQL Server or Access are good for this), you can do all of your inserts into a database table, and then export the table all at once into an Excel spreadsheet.
Generally speaking, databases are good at handling lots of inserts, while spreadsheets aren't.
|
280,069 |
<p>I'm writing a C++ program that doesn't work (I get a segmentation fault) when I compile it with optimizations (options -O1, -O2, -O3, etc.), but it works just fine when I compile it without optimizations.</p>
<p>Is there any chance that the error is in my code? or should I assume that this is a bug in GCC?</p>
<p>My GCC version is 3.4.6.</p>
<p>Is there any known workaround for this kind of problem?</p>
<p>There is a big difference in speed between the optimized and unoptimized version of my program, so I really need to use optimizations.</p>
<hr>
<p>This is my original functor. The one that works fine with no levels of optimizations and throws a segmentation fault with any level of optimization:</p>
<pre><code>struct distanceToPointSort{
indexedDocument* point ;
distanceToPointSort(indexedDocument* p): point(p) {}
bool operator() (indexedDocument* p1,indexedDocument* p2){
return distance(point,p1) < distance(point,p2) ;
}
} ;
</code></pre>
<p>And this one works flawlessly with any level of optimization:</p>
<pre><code>struct distanceToPointSort{
indexedDocument* point ;
distanceToPointSort(indexedDocument* p): point(p) {}
bool operator() (indexedDocument* p1,indexedDocument* p2){
float d1=distance(point,p1) ;
float d2=distance(point,p2) ;
std::cout << "" ; //without this line, I get a segmentation fault anyways
return d1 < d2 ;
}
} ;
</code></pre>
<p>Unfortunately, this problem is hard to reproduce because it happens with some specific values. I get the segmentation fault upon sorting just one out of more than a thousand vectors, so it really depends on the specific combination of values each vector has.</p>
|
[
{
"answer_id": 280079,
"author": "Patrick_O",
"author_id": 11084,
"author_profile": "https://Stackoverflow.com/users/11084",
"pm_score": 2,
"selected": false,
"text": "<p>You may be running into an aliasing problem (or it could be a million other things). Look up the -fstrict-aliasing option.</p>\n\n<p>This kind of question is impossible to answer properly without more information.</p>\n"
},
{
"answer_id": 280080,
"author": "Adam Rosenfield",
"author_id": 9530,
"author_profile": "https://Stackoverflow.com/users/9530",
"pm_score": 3,
"selected": false,
"text": "<p>The error is in your code. It's likely you're doing something that invokes undefined behavior according to the C standard which just happens to work with no optimizations, but when GCC makes certain assumptions for performing its optimizations, the code breaks when those assumptions aren't true. Make sure to compile with the <code>-Wall</code> option, and the <code>-Wextra</code> might also be a good idea, and see if you get any warnings. You could also try <code>-ansi</code> or <code>-pedantic</code>, but those are likely to result in false positives.</p>\n"
},
{
"answer_id": 280082,
"author": "Martin York",
"author_id": 14065,
"author_profile": "https://Stackoverflow.com/users/14065",
"pm_score": 3,
"selected": false,
"text": "<p>I would assume your code is wrong first.<br>\nThough it is hard to tell.</p>\n\n<p>Does your code compile with 0 warnings?</p>\n\n<pre><code> g++ -Wall -Wextra -pedantic -ansi\n</code></pre>\n"
},
{
"answer_id": 280089,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 2,
"selected": false,
"text": "<p>It's almost (<strong><em>almost</em></strong>) never the compiler.</p>\n\n<p>First, make sure you're compiling warning-free, with -Wall.</p>\n\n<p>If that didn't give you a \"eureka\" moment, attach a debugger to the least optimized version of your executable that crashes and see what it's doing and where it goes.</p>\n\n<p>5 will get you 10 that you've fixed the problem by this point.</p>\n"
},
{
"answer_id": 280100,
"author": "Robert Gould",
"author_id": 15124,
"author_profile": "https://Stackoverflow.com/users/15124",
"pm_score": 2,
"selected": false,
"text": "<p>Ran into the same problem a few days ago, in my case it was aliasing. And GCC does it differently, but not wrongly, when compared to other compilers. GCC has become what some might call a rules-lawyer of the C++ standard, and their implementation is correct, but you also have to be really correct in you C++, or it'll over optimize somethings, which is a pain. But you get speed, so can't complain.</p>\n"
},
{
"answer_id": 280118,
"author": "GetFree",
"author_id": 25700,
"author_profile": "https://Stackoverflow.com/users/25700",
"pm_score": 0,
"selected": false,
"text": "<p>Wow, I didn't expect answers so quicly, and so many...</p>\n\n<p>The error occurs upon sorting a std::vector of pointers using std::sort()</p>\n\n<p>I provide the strict-weak-ordering functor.</p>\n\n<p>But I know the functor I provide is correct because I've used it a lot and it works fine.</p>\n\n<p>Plus, the error cannot be some invalid pointer in the vector becasue the error occurs just when I sort the vector. If I iterate through the vector without applying std::sort first, the program works fine.</p>\n\n<p>I just used GDB to try to find out what's going on. The error occurs when std::sort invoke my functor. Aparently std::sort is passing an invalid pointer to my functor. (of course this happens with the optimized version only, any level of optimization -O, -O2, -O3)</p>\n"
},
{
"answer_id": 280169,
"author": "Jim Buck",
"author_id": 2666,
"author_profile": "https://Stackoverflow.com/users/2666",
"pm_score": 1,
"selected": false,
"text": "<p>I expect to get some downvotes here after reading some of the comments, but in the console game programming world, it's rather common knowledge that the higher optimization levels can sometimes generate incorrect code in weird edge cases. It might very well be that edge cases can be fixed with subtle changes to the code, though.</p>\n"
},
{
"answer_id": 280204,
"author": "JesperE",
"author_id": 13051,
"author_profile": "https://Stackoverflow.com/users/13051",
"pm_score": 2,
"selected": false,
"text": "<p>It is very seldom the compiler fault, but compiler do have bugs in them, and them often manifest themselves at different optimization levels (if there is a bug in an optimization pass, for example).</p>\n\n<p>In general when reporting programming problems: <strong>provide a minimal code sample to demonstrate the issue</strong>, such that people can just save the code to a file, compile and run it. Make it as <strong>easy as possible</strong> to reproduce your problem.</p>\n\n<p>Also, try different versions of GCC (compiling your own GCC is very easy, especially on Linux). If possible, try with another compiler. Intel C has a compiler which is more or less GCC compatible (and free for non-commercial use, I think). This will help pinpointing the problem.</p>\n"
},
{
"answer_id": 280219,
"author": "Artelius",
"author_id": 31945,
"author_profile": "https://Stackoverflow.com/users/31945",
"pm_score": 3,
"selected": false,
"text": "<p>Here's some code that <em>seems</em> to work, until you hit -O3...</p>\n\n<pre><code>#include <stdio.h>\n\nint main()\n{\n int i = 0, j = 1, k = 2;\n printf(\"%d %d %d\\n\", *(&j-1), *(&j), *(&j+1));\n return 0;\n}\n</code></pre>\n\n<p>Without optimisations, I get \"2 1 0\"; with optimisations I get \"40 1 2293680\". Why? Because i and k got optimised out!</p>\n\n<p>But I was taking the address of j and going out of the memory region allocated to j. That's not allowed by the standard. It's most likely that your problem is caused by a similar deviation from the standard.</p>\n\n<p>I find <a href=\"http://valgrind.org/\" rel=\"nofollow noreferrer\">valgrind</a> is often helpful at times like these.</p>\n\n<p>EDIT: Some commenters are under the impression that the standard allows arbitrary pointer arithmetic. <em>It does not.</em> Remember that some architectures have funny addressing schemes, alignment may be important, and you may get problems if you overflow certain registers!</p>\n\n<p>The words of the [draft] standard, on adding/subtracting an integer to/from a pointer (emphasis added):</p>\n\n<p>\"If both the pointer operand and the result point to elements of the same array object, or one past the last element of the array object, the <em>evaluation</em> shall not produce an overflow; <em>otherwise, the behavior is undefined.</em>\"</p>\n\n<p>Seeing as &j doesn't even point to an array object, &j-1 and &j+1 can hardly point to part of the same array object. So simply evaluating &j+1 (let alone dereferencing it) is undefined behaviour.</p>\n\n<p>On x86 we can be pretty confident that adding one to a pointer is fairly safe and just takes us to the next memory location. In the code above, the problem occurs when we make assumptions about what that memory contains, which of course the standard doesn't go near.</p>\n"
},
{
"answer_id": 280240,
"author": "starmole",
"author_id": 35706,
"author_profile": "https://Stackoverflow.com/users/35706",
"pm_score": 0,
"selected": false,
"text": "<p>as other have pointed out, probably strict aliasing. \nturn it of in o3 and try again. My guess is that you are doing some pointer tricks in your functor (fast float as int compare? object type in lower 2 bits?) that fail across inlining template functions. \nwarnings do not help to catch this case. \"if the compiler could detect all strict aliasing problems it could just as well avoid them\" just changing an unrelated line of code may make the problem appear or go away as it changes register allocation. </p>\n"
},
{
"answer_id": 280895,
"author": "MSalters",
"author_id": 15416,
"author_profile": "https://Stackoverflow.com/users/15416",
"pm_score": 0,
"selected": false,
"text": "<p>As the updated question will show ;) , the problem exists with a <code>std::vector<T*></code>. One common error with vectors is reserve()ing what should have been resize()d. As a result, you'd be writing outside array bounds. An optimizer may discard those writes.</p>\n"
},
{
"answer_id": 282455,
"author": "GetFree",
"author_id": 25700,
"author_profile": "https://Stackoverflow.com/users/25700",
"pm_score": 1,
"selected": false,
"text": "<p>Alright...\nThis is one of the weirdest problems I've ever had.<br>\nI dont think I have enough proof to state it's a GCC bug, but honestly... It really looks like one.</p>\n\n<p>This is my original functor. The one that works fine with no levels of optimizations and throws a segmentation fault with any level of optimization:</p>\n\n<pre><code>struct distanceToPointSort{\n indexedDocument* point ;\n distanceToPointSort(indexedDocument* p): point(p) {}\n bool operator() (indexedDocument* p1,indexedDocument* p2){\n return distance(point,p1) < distance(point,p2) ;\n }\n} ;\n</code></pre>\n\n<p>And this one works flawlessly with any level of optimization:</p>\n\n<pre><code>struct distanceToPointSort{\n indexedDocument* point ;\n distanceToPointSort(indexedDocument* p): point(p) {}\n bool operator() (indexedDocument* p1,indexedDocument* p2){\n\n float d1=distance(point,p1) ;\n float d2=distance(point,p2) ;\n\n std::cout << \"\" ; //without this line, I get a segmentation fault anyways\n\n return d1 < d2 ;\n }\n} ;\n</code></pre>\n\n<p>Unfortunately, this problem is hard to reproduce because it happens with some specific values. I get the segmentation fault upon sorting just one out of more than a thousand vectors, so it really depends on the specific combination of values each vector has.</p>\n"
},
{
"answer_id": 282508,
"author": "Windows programmer",
"author_id": 23705,
"author_profile": "https://Stackoverflow.com/users/23705",
"pm_score": 3,
"selected": false,
"text": "<p>As an experiment, try to see if this will force the compiler to round everything consistently.</p>\n\n<pre><code>volatile float d1=distance(point,p1) ;\nvolatile float d2=distance(point,p2) ;\nreturn d1 < d2 ;\n</code></pre>\n"
},
{
"answer_id": 283003,
"author": "starmole",
"author_id": 35706,
"author_profile": "https://Stackoverflow.com/users/35706",
"pm_score": 0,
"selected": false,
"text": "<p>post the code in distance! it probably does some pointer magic, see my previous post. doing an intermediate assignment just hides the bug in your code by changing register allocation. even more telling of this is the output changing things!</p>\n"
},
{
"answer_id": 283937,
"author": "CesarB",
"author_id": 28258,
"author_profile": "https://Stackoverflow.com/users/28258",
"pm_score": 4,
"selected": true,
"text": "<p>Now that you posted the code fragment and a working workaround was found (@Windows programmer's answer), I can say that perhaps what you are looking for is <code>-ffloat-store</code>.</p>\n\n<blockquote>\n <p>-ffloat-store</p>\n \n <p>Do not store floating point variables in registers, and inhibit other options that might change whether a floating point value is taken from a register or memory.</p>\n \n <p>This option prevents undesirable excess precision on machines such as the 68000 where the floating registers (of the 68881) keep more precision than a double is supposed to have. Similarly for the x86 architecture. For most programs, the excess precision does only good, but a few programs rely on the precise definition of IEEE floating point. Use -ffloat-store for such programs, after modifying them to store all pertinent intermediate computations into variables. </p>\n</blockquote>\n\n<p>Source: <a href=\"http://gcc.gnu.org/onlinedocs/gcc-3.4.6/gcc/Optimize-Options.html\" rel=\"noreferrer\">http://gcc.gnu.org/onlinedocs/gcc-3.4.6/gcc/Optimize-Options.html</a></p>\n"
},
{
"answer_id": 1426017,
"author": "Ringding",
"author_id": 135811,
"author_profile": "https://Stackoverflow.com/users/135811",
"pm_score": 0,
"selected": false,
"text": "<p>The true answer is hidden somewhere inside all the comments in this thread. First of all: it is not a bug in the compiler.</p>\n\n<p>The problem has to do with floating point precision. <code>distanceToPointSort</code> should be a function that should never return true for both the arguments (a,b) and (b,a), but that is exactly what can happen when the compiler decides to use higher precision for some data paths. The problem is especially likely on, but by no means limited to, x86 without <code>-mfpmath=sse</code>. If the comparator behaves that way, the <code>sort</code> function can become confused, and the segmentation fault is not surprising.</p>\n\n<p>I consider <code>-ffloat-store</code> the best solution here (already suggested by CesarB).</p>\n"
}
] |
2008/11/11
|
[
"https://Stackoverflow.com/questions/280069",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/25700/"
] |
I'm writing a C++ program that doesn't work (I get a segmentation fault) when I compile it with optimizations (options -O1, -O2, -O3, etc.), but it works just fine when I compile it without optimizations.
Is there any chance that the error is in my code? or should I assume that this is a bug in GCC?
My GCC version is 3.4.6.
Is there any known workaround for this kind of problem?
There is a big difference in speed between the optimized and unoptimized version of my program, so I really need to use optimizations.
---
This is my original functor. The one that works fine with no levels of optimizations and throws a segmentation fault with any level of optimization:
```
struct distanceToPointSort{
indexedDocument* point ;
distanceToPointSort(indexedDocument* p): point(p) {}
bool operator() (indexedDocument* p1,indexedDocument* p2){
return distance(point,p1) < distance(point,p2) ;
}
} ;
```
And this one works flawlessly with any level of optimization:
```
struct distanceToPointSort{
indexedDocument* point ;
distanceToPointSort(indexedDocument* p): point(p) {}
bool operator() (indexedDocument* p1,indexedDocument* p2){
float d1=distance(point,p1) ;
float d2=distance(point,p2) ;
std::cout << "" ; //without this line, I get a segmentation fault anyways
return d1 < d2 ;
}
} ;
```
Unfortunately, this problem is hard to reproduce because it happens with some specific values. I get the segmentation fault upon sorting just one out of more than a thousand vectors, so it really depends on the specific combination of values each vector has.
|
Now that you posted the code fragment and a working workaround was found (@Windows programmer's answer), I can say that perhaps what you are looking for is `-ffloat-store`.
>
> -ffloat-store
>
>
> Do not store floating point variables in registers, and inhibit other options that might change whether a floating point value is taken from a register or memory.
>
>
> This option prevents undesirable excess precision on machines such as the 68000 where the floating registers (of the 68881) keep more precision than a double is supposed to have. Similarly for the x86 architecture. For most programs, the excess precision does only good, but a few programs rely on the precise definition of IEEE floating point. Use -ffloat-store for such programs, after modifying them to store all pertinent intermediate computations into variables.
>
>
>
Source: <http://gcc.gnu.org/onlinedocs/gcc-3.4.6/gcc/Optimize-Options.html>
|
280,075 |
<p>I'm trying to implement (what I think is) a pretty simple data model for a counter:</p>
<pre><code>class VisitorDayTypeCounter(models.Model):
visitType = models.CharField(max_length=60)
visitDate = models.DateField('Visit Date')
counter = models.IntegerField()
</code></pre>
<p>When someone comes through, it will look for a row that matches the visitType and visitDate; if this row doesn't exist, it will be created with counter=0.</p>
<p>Then we increment the counter and save.</p>
<p>My concern is that this process is totally a race. Two requests could simultaneously check to see if the entity is there, and both of them could create it. Between reading the counter and saving the result, another request could come through and increment it (resulting in a lost count).</p>
<p>So far I haven't really found a good way around this, either in the Django documentation or in the tutorial (in fact, it looks like the tutorial has a race condition in the Vote part of it).</p>
<p>How do I do this safely?</p>
|
[
{
"answer_id": 280125,
"author": "Daniel Naab",
"author_id": 32638,
"author_profile": "https://Stackoverflow.com/users/32638",
"pm_score": 3,
"selected": false,
"text": "<p>Two suggestions:</p>\n\n<p>Add a unique_together to your model, and wrap the creation in an exception handler to catch duplicates:</p>\n\n<pre><code>class VisitorDayTypeCounter(models.Model):\n visitType = models.CharField(max_length=60)\n visitDate = models.DateField('Visit Date')\n counter = models.IntegerField()\n class Meta:\n unique_together = (('visitType', 'visitDate'))\n</code></pre>\n\n<p>After this, you could stlll have a minor race condition on the counter's update. If you get enough traffic to be concerned about that, I would suggest looking into transactions for finer grained database control. I don't think the ORM has direct support for locking/synchronization. The transaction documentation is available <a href=\"http://docs.djangoproject.com/en/dev/topics/db/transactions/\" rel=\"nofollow noreferrer\">here</a>. </p>\n"
},
{
"answer_id": 280152,
"author": "Roopinder",
"author_id": 31068,
"author_profile": "https://Stackoverflow.com/users/31068",
"pm_score": 1,
"selected": false,
"text": "<p>Why not use the database as the concurrency layer ? Add a primary key or unique constraint the table to visitType and visitDate. If I'm not mistaken, django does not exactly support this in their database Model class or at least I've not seen an example.</p>\n\n<p>Once you've added the constraint/key to the table, then all you have to do is:</p>\n\n<ol>\n<li>check if the row is there. if it is, fetch it.</li>\n<li>insert the row. if there's no error you're fine and can move on.</li>\n<li>if there's an error (i.e. race condition), re-fetch the row. if there's no row, then it's a genuine error. Otherwise, you're fine.</li>\n</ol>\n\n<p>It's nasty to do it this way, but it seems quick enough and would cover most situations.</p>\n"
},
{
"answer_id": 280585,
"author": "Ber",
"author_id": 11527,
"author_profile": "https://Stackoverflow.com/users/11527",
"pm_score": 0,
"selected": false,
"text": "<p>Your should use database transactions to avoid this kind of race condition. A transaction lets you perform the whole operation of creating, reading, incrementing and saving the counter on an \"all or nothing\" base. If anything goes wrong it will roll back the whole thing and you can try again.</p>\n\n<p>Check out the Django <a href=\"http://docs.djangoproject.com/en/dev/topics/db/transactions/?from=olddocs\" rel=\"nofollow noreferrer\">docs.</a> There is a transaction middle ware, or you can use decorators around views or methods to create transactions.</p>\n"
},
{
"answer_id": 281090,
"author": "Sam Corder",
"author_id": 2351,
"author_profile": "https://Stackoverflow.com/users/2351",
"pm_score": 4,
"selected": false,
"text": "<p>If you truly want the counter to be accurate you could use a transaction but the amount of concurrency required will really drag your application and database down under any significant load. Instead think of going with a more messaging style approach and just keep dumping count records into a table for each visit where you'd want to increment the counter. Then when you want the total number of visits do a count on the visits table. You could also have a background process that ran any number of times a day that would sum the visits and then store that in the parent table. To save on space it would also delete any records from the child visits table that it summed up. You'll cut down on your concurrency costs a huge amount if you don't have multiple agents vying for the same resources (the counter).</p>\n"
},
{
"answer_id": 282868,
"author": "iconoplast",
"author_id": 36683,
"author_profile": "https://Stackoverflow.com/users/36683",
"pm_score": 2,
"selected": true,
"text": "<p>This is a bit of a hack. The raw SQL will make your code less portable, but it'll get rid of the race condition on the counter increment. In theory, this should increment the counter any time you do a query. I haven't tested this, so you should make sure the list gets interpolated in the query properly.</p>\n\n<pre><code>class VisitorDayTypeCounterManager(models.Manager):\n def get_query_set(self):\n qs = super(VisitorDayTypeCounterManager, self).get_query_set()\n\n from django.db import connection\n cursor = connection.cursor()\n\n pk_list = qs.values_list('id', flat=True)\n cursor.execute('UPDATE table_name SET counter = counter + 1 WHERE id IN %s', [pk_list])\n\n return qs\n\nclass VisitorDayTypeCounter(models.Model):\n ...\n\n objects = VisitorDayTypeCounterManager()\n</code></pre>\n"
},
{
"answer_id": 370552,
"author": "kmmbvnr",
"author_id": 46548,
"author_profile": "https://Stackoverflow.com/users/46548",
"pm_score": 3,
"selected": false,
"text": "<p>You can use patch from <a href=\"http://code.djangoproject.com/ticket/2705\" rel=\"nofollow noreferrer\">http://code.djangoproject.com/ticket/2705</a> for support database level locking.</p>\n\n<p>With patch this code will be atomic:</p>\n\n<pre><code>visitors = VisitorDayTypeCounter.objects.get(day=curday).for_update()\nvisitors.counter += 1\nvisitors.save()\n</code></pre>\n"
},
{
"answer_id": 1955700,
"author": "bjunix",
"author_id": 80254,
"author_profile": "https://Stackoverflow.com/users/80254",
"pm_score": 5,
"selected": false,
"text": "<p>As of Django 1.1 you can use the ORM's F() expressions. </p>\n\n<pre><code>from django.db.models import F\nproduct = Product.objects.get(name='Venezuelan Beaver Cheese')\nproduct.number_sold = F('number_sold') + 1\nproduct.save()\n</code></pre>\n\n<p>For more details see the documentation:</p>\n\n<p><a href=\"https://docs.djangoproject.com/en/1.8/ref/models/instances/#updating-attributes-based-on-existing-fields\" rel=\"noreferrer\">https://docs.djangoproject.com/en/1.8/ref/models/instances/#updating-attributes-based-on-existing-fields</a></p>\n\n<p><a href=\"https://docs.djangoproject.com/en/1.8/ref/models/expressions/#django.db.models.F\" rel=\"noreferrer\">https://docs.djangoproject.com/en/1.8/ref/models/expressions/#django.db.models.F</a></p>\n"
}
] |
2008/11/11
|
[
"https://Stackoverflow.com/questions/280075",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/13868/"
] |
I'm trying to implement (what I think is) a pretty simple data model for a counter:
```
class VisitorDayTypeCounter(models.Model):
visitType = models.CharField(max_length=60)
visitDate = models.DateField('Visit Date')
counter = models.IntegerField()
```
When someone comes through, it will look for a row that matches the visitType and visitDate; if this row doesn't exist, it will be created with counter=0.
Then we increment the counter and save.
My concern is that this process is totally a race. Two requests could simultaneously check to see if the entity is there, and both of them could create it. Between reading the counter and saving the result, another request could come through and increment it (resulting in a lost count).
So far I haven't really found a good way around this, either in the Django documentation or in the tutorial (in fact, it looks like the tutorial has a race condition in the Vote part of it).
How do I do this safely?
|
This is a bit of a hack. The raw SQL will make your code less portable, but it'll get rid of the race condition on the counter increment. In theory, this should increment the counter any time you do a query. I haven't tested this, so you should make sure the list gets interpolated in the query properly.
```
class VisitorDayTypeCounterManager(models.Manager):
def get_query_set(self):
qs = super(VisitorDayTypeCounterManager, self).get_query_set()
from django.db import connection
cursor = connection.cursor()
pk_list = qs.values_list('id', flat=True)
cursor.execute('UPDATE table_name SET counter = counter + 1 WHERE id IN %s', [pk_list])
return qs
class VisitorDayTypeCounter(models.Model):
...
objects = VisitorDayTypeCounterManager()
```
|
280,106 |
<p>I am implementing a Comment box facility in my application which user can resize using mouse. This comment box contains a scrollpane which instead contains a <code>JEditorPane</code> in which user can insert comment. I have added the editor pane inside a scroll pane for the following reason:</p>
<p><a href="https://stackoverflow.com/questions/271881/auto-scolling-of-jeditorpane">auto scolling of jeditorpane</a></p>
<p>When the user resizes the comment box, I am setting the desired size for <code>JScrollPane</code> and the <code>JEditorPane</code>. When the user is increasing the size of the comment box, the size of these components are increasing as desired but when the size of the comment box is decreased, the size of the <code>JEditorPane</code> does not decrease even after setting the size. This leads to the scrollbars inside the scrollpane.</p>
<p>I tried using <code>setPreferrredSize</code>, <code>setSize</code>, <code>setMaximumSize</code> for <code>JEditorPane</code>. Still the size of the editor pane is not reducing. I tried calling <code>revalidate()</code> or <code>updateUI()</code> after the setting of size but no use. </p>
<p>I am using Java 1.4.2. </p>
<p>Please provide me some insight....</p>
|
[
{
"answer_id": 281769,
"author": "luiscubal",
"author_id": 32775,
"author_profile": "https://Stackoverflow.com/users/32775",
"pm_score": -1,
"selected": false,
"text": "<p>Decreasing the size of a JEditorPane in a JScrollPane and then reducing it, is not possible.\nYou may want to use a JTextArea instead.</p>\n"
},
{
"answer_id": 1525149,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 2,
"selected": false,
"text": "<p>Actually it is possible, luiscubal. Here is how,</p>\n\n<p>To the JScrollPane add a ComponentListener for resize events</p>\n\n<pre><code>public static void main(String...args) {\n //our test frame\n JFrame frame = new JFrame(\"JEditorPane inside JScrollPane resizing\");\n frame.setLayout(new BorderLayout());\n\n //our editing pane\n final JEditorPane editor = new JEditorPane();\n\n //our simple scroll pane\n final JScrollPane scroller = new JScrollPane(editor);\n\n //NOTE: this is the magic that is kind of a workaround\n // you can also implement your own type of JScrollPane\n // using the JScrollBar and a JViewport which is the \n // preferred method of doing something like this the \n // other option is to create a JEditorPane subclass that\n // implements the Scrollable interface.\n scroller.addComponentListener(new ComponentAdapter() {\n @Override\n public void componentResized(ComponentEvent e) {\n editor.setSize(new Dimension(\n scroller.getWidth()-20, \n scroller.getHeight()-20));\n }\n });\n\n //just use up the entire frame area.\n frame.add(scroller, BorderLayout.CENTER);\n\n //quick and dirty close event handler\n frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);\n frame.setSize(320, 240); //something not too big\n frame.setLocationRelativeTo(null); //centers window on screen\n frame.setVisible(true); // normally done in a SwingUtilities.invokeLater\n}\n</code></pre>\n\n<p>Look luiscubal it is possible. Don't be so quick to announce things in Java as not possible. The swing api is quiet flexible and can do a lot of the work for you. However, if you use JComponents in ways they weren't made to be used you will end up with problems and have two options. </p>\n\n<ol>\n<li>subclass subclass subclass basically create your own component. </li>\n<li>find a work around, like the above solution.</li>\n</ol>\n"
},
{
"answer_id": 7889617,
"author": "Mike B",
"author_id": 214756,
"author_profile": "https://Stackoverflow.com/users/214756",
"pm_score": 3,
"selected": false,
"text": "<p>I realise this is long since answered, but for future reference all you need to do is override the <code>getScrollableTracksViewportWidth()</code> to always return true, eg.</p>\n\n<pre><code>JEditorPane pane = new JEditorPane() {\n public boolean getScrollableTracksViewportWidth() {\n return true;\n }\n};\npanel.add(new JScrollPane(pane));\n</code></pre>\n"
}
] |
2008/11/11
|
[
"https://Stackoverflow.com/questions/280106",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/22550/"
] |
I am implementing a Comment box facility in my application which user can resize using mouse. This comment box contains a scrollpane which instead contains a `JEditorPane` in which user can insert comment. I have added the editor pane inside a scroll pane for the following reason:
[auto scolling of jeditorpane](https://stackoverflow.com/questions/271881/auto-scolling-of-jeditorpane)
When the user resizes the comment box, I am setting the desired size for `JScrollPane` and the `JEditorPane`. When the user is increasing the size of the comment box, the size of these components are increasing as desired but when the size of the comment box is decreased, the size of the `JEditorPane` does not decrease even after setting the size. This leads to the scrollbars inside the scrollpane.
I tried using `setPreferrredSize`, `setSize`, `setMaximumSize` for `JEditorPane`. Still the size of the editor pane is not reducing. I tried calling `revalidate()` or `updateUI()` after the setting of size but no use.
I am using Java 1.4.2.
Please provide me some insight....
|
I realise this is long since answered, but for future reference all you need to do is override the `getScrollableTracksViewportWidth()` to always return true, eg.
```
JEditorPane pane = new JEditorPane() {
public boolean getScrollableTracksViewportWidth() {
return true;
}
};
panel.add(new JScrollPane(pane));
```
|
280,114 |
<p>I'm new to C# and .Net in general so this may be a naive thing to ask. But anyway, consider this C# code:</p>
<pre><code>class A {
public int Data {get; set;}
}
class B {
public A Aval {get; set;}
}
</code></pre>
<p>The B.Aval property above is returning a reference to its internal A object. As a former C++ programmer, I find this dangerous because by exposing reference to an member object class B violates the principle of data hiding. Nonetheless, this seems to be the normal practice in the C# world.</p>
<p>My question is, if it is at all, why is such a design the usual approach as opposed to returning copies of internal members, which will be much safer in so many ways (including the case of thread safety)?</p>
<p>I understand that even in C++ sometimes good design demands that you do expose class members directly (a <strong>Car</strong> class with <strong>Engine</strong> and <strong>Stereo</strong> objects inside it comes to mind), but it is not the norm as seems to be in C#.</p>
|
[
{
"answer_id": 280133,
"author": "stephbu",
"author_id": 12702,
"author_profile": "https://Stackoverflow.com/users/12702",
"pm_score": 1,
"selected": false,
"text": "<p>This isn't encapsulation - it's an act of abstraction through object composition or aggregation depending on how the internal object lifetimes are created/managed. </p>\n\n<p>In composition patterns it is perfectly acceptable to access composite state e.g. the instance of A in the instance of B.</p>\n\n<blockquote>\n <p><a href=\"http://en.wikipedia.org/wiki/Object_composition\" rel=\"nofollow noreferrer\">http://en.wikipedia.org/wiki/Object_composition</a></p>\n</blockquote>\n\n<p>As you point out the semantics of encapsulation are <em>very different</em> - to completely hide the internal implementation of A e.g. by inheriting B from A.</p>\n"
},
{
"answer_id": 280139,
"author": "Brian",
"author_id": 19299,
"author_profile": "https://Stackoverflow.com/users/19299",
"pm_score": 1,
"selected": false,
"text": "<p>This is maybe related to the <a href=\"http://en.wikipedia.org/wiki/Law_of_Demeter\" rel=\"nofollow noreferrer\">Law of Demeter</a>... are you talking only about getters and setters that have no extra logic (and thus effectively directly expose the member), or any get-set pairs? In any case, if this portion of the outer object's state doesn't participate in meaninful invariants on the outer object, I don't think it's necessarily unreasonable to do this.</p>\n"
},
{
"answer_id": 280160,
"author": "Jon Skeet",
"author_id": 22656,
"author_profile": "https://Stackoverflow.com/users/22656",
"pm_score": 3,
"selected": true,
"text": "<p>You're absolutely right - you should only return objects from properties where either the object is immutable, or you're happy for the caller to modify it to whatever extent they can. A classic example of this is returning collections - often it's much better to return a read-only wrapper round a collection than to return the \"real\" collection directly.</p>\n\n<p>On the other hand, pragmatism sometimes calls for just documenting this as \"please don't change the returned object\" - particularly when it's an API which is only used within a company.</p>\n\n<p>Hopefully there'll be more support for immutability in future versions of C# and .NET, which will make this easier to cope with - but it's likely to remain a knotty problem in many cases.</p>\n"
}
] |
2008/11/11
|
[
"https://Stackoverflow.com/questions/280114",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/32688/"
] |
I'm new to C# and .Net in general so this may be a naive thing to ask. But anyway, consider this C# code:
```
class A {
public int Data {get; set;}
}
class B {
public A Aval {get; set;}
}
```
The B.Aval property above is returning a reference to its internal A object. As a former C++ programmer, I find this dangerous because by exposing reference to an member object class B violates the principle of data hiding. Nonetheless, this seems to be the normal practice in the C# world.
My question is, if it is at all, why is such a design the usual approach as opposed to returning copies of internal members, which will be much safer in so many ways (including the case of thread safety)?
I understand that even in C++ sometimes good design demands that you do expose class members directly (a **Car** class with **Engine** and **Stereo** objects inside it comes to mind), but it is not the norm as seems to be in C#.
|
You're absolutely right - you should only return objects from properties where either the object is immutable, or you're happy for the caller to modify it to whatever extent they can. A classic example of this is returning collections - often it's much better to return a read-only wrapper round a collection than to return the "real" collection directly.
On the other hand, pragmatism sometimes calls for just documenting this as "please don't change the returned object" - particularly when it's an API which is only used within a company.
Hopefully there'll be more support for immutability in future versions of C# and .NET, which will make this easier to cope with - but it's likely to remain a knotty problem in many cases.
|
280,115 |
<p>I am creating menus in WPF programatically using vb.net. Can someone show me how I can add separator bar to a menu in code? No xaml please.</p>
|
[
{
"answer_id": 280194,
"author": "Jeff Donnici",
"author_id": 821,
"author_profile": "https://Stackoverflow.com/users/821",
"pm_score": 7,
"selected": true,
"text": "<p>WPF has a <a href=\"http://msdn.microsoft.com/en-us/library/system.windows.controls.separator.aspx\" rel=\"noreferrer\">Separator</a> control for just that purpose and it also separates your menu items when the appear on a toolbar. From the MSDN docs:</p>\n\n<blockquote>\n <p>A Separator control draws a line,\n horizontal or vertical, between items\n in controls, such as ListBox, Menu,\n and ToolBar. Separator controls do not\n react to any keyboard, mouse, mouse\n wheel, or tablet input and cannot be\n enabled or selected.</p>\n</blockquote>\n\n<p>In code:</p>\n\n<pre><code>using System.Windows.Controls;\n\n//\n\nMenu myMenu = new Menu();\nmyMenu.Items.Add(new Separator());\n</code></pre>\n"
},
{
"answer_id": 13658089,
"author": "Adrian Toman",
"author_id": 651104,
"author_profile": "https://Stackoverflow.com/users/651104",
"pm_score": 5,
"selected": false,
"text": "<p>In xaml:</p>\n\n<pre><code><Menu>\n <MenuItem Header=\"Menu Item 1\" />\n <Separator />\n <MenuItem Header=\"Menu Item 1\" />\n<Menu>\n</code></pre>\n"
}
] |
2008/11/11
|
[
"https://Stackoverflow.com/questions/280115",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3566/"
] |
I am creating menus in WPF programatically using vb.net. Can someone show me how I can add separator bar to a menu in code? No xaml please.
|
WPF has a [Separator](http://msdn.microsoft.com/en-us/library/system.windows.controls.separator.aspx) control for just that purpose and it also separates your menu items when the appear on a toolbar. From the MSDN docs:
>
> A Separator control draws a line,
> horizontal or vertical, between items
> in controls, such as ListBox, Menu,
> and ToolBar. Separator controls do not
> react to any keyboard, mouse, mouse
> wheel, or tablet input and cannot be
> enabled or selected.
>
>
>
In code:
```
using System.Windows.Controls;
//
Menu myMenu = new Menu();
myMenu.Items.Add(new Separator());
```
|
280,127 |
<p>I'm bored with surrounding code with try catch like this..</p>
<pre><code>try
{
//some boring stuff
}
catch(Exception ex)
{
//something even more boring stuff
}
</code></pre>
<p>I would like something like</p>
<pre><code>SurroundWithTryCatch(MyMethod)
</code></pre>
<p>I know I can accomplish this behaviour by creating a delegate with the exact signature of the function, but creating a delegate for all the methods in my application it's just not an option.</p>
<p>I can also do this by injecting IL code but this is expensive in terms of performance as it creates an wrapper assembly around mine.</p>
<p>Any other valid ideeas?</p>
|
[
{
"answer_id": 280132,
"author": "stiduck",
"author_id": 35398,
"author_profile": "https://Stackoverflow.com/users/35398",
"pm_score": 2,
"selected": false,
"text": "<p>You can try to use some null validiation instead. I can take a LINQ to SQL example:</p>\n\n<pre><code>var user = db.Users.SingleOrDefault(u => u.Username == 3);\n\nif (user == null)\n throw new ArgumentNullException(\"User\", \"User cannot be null.\");\n\n// \"else\" continue your code...\n</code></pre>\n"
},
{
"answer_id": 280134,
"author": "Scott Weinstein",
"author_id": 25201,
"author_profile": "https://Stackoverflow.com/users/25201",
"pm_score": 2,
"selected": false,
"text": "<p>Perhaps you're treating exception handling as error codes via a different syntax? So don't try/catch. Let the exception propagate upwards. </p>\n"
},
{
"answer_id": 280165,
"author": "Roopinder",
"author_id": 31068,
"author_profile": "https://Stackoverflow.com/users/31068",
"pm_score": 0,
"selected": false,
"text": "<p>I'm not sure for C#, but in Java-land you could define and interface with all the methods, and then hide it under a proxy object. You could run away with writing even more code by defining something like:</p>\n\n<pre><code>ExceptionCatcher.catchAll(new Runnable() {\n public void run() {\n //run delegate here\n MyMethod();\n }\n});\n</code></pre>\n\n<p>and catchAll() will just call the runnable and wrapping a try-catch block around it.</p>\n\n<p>However, I think what you really want is a language that has got nice <a href=\"http://en.wikipedia.org/wiki/Closure_(computer_science)\" rel=\"nofollow noreferrer\">closure support</a>. Using closures, doing what you want is extremely easy.</p>\n"
},
{
"answer_id": 280167,
"author": "Jon Skeet",
"author_id": 22656,
"author_profile": "https://Stackoverflow.com/users/22656",
"pm_score": 6,
"selected": true,
"text": "<p>Firstly, it sounds like you may be using try/catch too often - particularly if you're catching <code>Exception</code>. try/catch blocks should be relatively rare; unless you can really \"handle\" the exception, you should just let it bubble up to the next layer of the stack.</p>\n\n<p>Now, assuming you really <em>do</em> want all of these try/catch blocks, why is it not an option to create a delegate? With anonymous methods and lambda expressions, as well as the Func/Action delegates in the <code>System</code> namespace, there's basically very little work to do. You write:</p>\n\n<pre><code>public void SurroundWithTryCatch(Action action)\n{\n try\n {\n action();\n }\n catch(Exception ex)\n {\n //something even more boring stuff\n } \n}\n</code></pre>\n\n<p>and then your <code>SurroundWithTryCatch(MyMethod)</code> will work fine, if it takes no paramaters.</p>\n\n<p>Alternatively, if you don't want to call a <em>different</em> method, just write:</p>\n\n<pre><code>public void MyMethod()\n{\n SurroundWithTryCatch(() => \n {\n // Logic here\n });\n}\n</code></pre>\n\n<p>If you need to return from the method, you can do:</p>\n\n<pre><code>public int MyMethod()\n{\n return SurroundWithTryCatch(() => \n {\n // Logic here\n return 5;\n });\n}\n</code></pre>\n\n<p>with a generic overload of <code>SurroundWithTryCatch</code> like this:</p>\n\n<pre><code>public T SurroundWithTryCatch<T>(Func<T> func)\n{ \n try\n {\n return func();\n }\n catch(Exception ex)\n {\n //something even more boring stuff\n } \n}\n</code></pre>\n\n<p>Most of this would be fine in C# 2 as well, but type inference won't help you quite as much and you'll have to use anonymous methods instead of lambda expressions.</p>\n\n<p>To go back to the start though: try to use try/catch less often. (try/finally should be much more frequent, although usually written as a using statement.)</p>\n"
},
{
"answer_id": 280258,
"author": "Martin Moser",
"author_id": 24756,
"author_profile": "https://Stackoverflow.com/users/24756",
"pm_score": 2,
"selected": false,
"text": "<p>For me I looks like you are asking for aspect oriented programming. I think you should take a look at PostSharp.</p>\n"
},
{
"answer_id": 280297,
"author": "Pablo Retyk",
"author_id": 30729,
"author_profile": "https://Stackoverflow.com/users/30729",
"pm_score": 2,
"selected": false,
"text": "<p>Aspect Oriented Programming could also help you, but this may require that you add libraries to your project, <a href=\"http://www.postsharp.org\" rel=\"nofollow noreferrer\">postsharp</a> would help you in this case.\nSee this link <a href=\"http://doc.postsharp.org/1.0/index.html#http://doc.postsharp.org/1.0/UserGuide/Laos/AspectKinds/OnExceptionAspect.html#idHelpTOCNode650988000\" rel=\"nofollow noreferrer\">http://doc.postsharp.org/1.0/index.html#http://doc.postsharp.org/1.0/UserGuide/Laos/AspectKinds/OnExceptionAspect.html#idHelpTOCNode650988000</a></p>\n"
},
{
"answer_id": 280448,
"author": "tunaranch",
"author_id": 27708,
"author_profile": "https://Stackoverflow.com/users/27708",
"pm_score": 0,
"selected": false,
"text": "<p>If you're using Java, you have RuntimeExceptions, which are exceptions that mean something has gone wrong that you can't be expected to recover from. Look it up. Start here: <a href=\"http://java.sun.com/docs/books/tutorial/essential/exceptions/runtime.html\" rel=\"nofollow noreferrer\">http://java.sun.com/docs/books/tutorial/essential/exceptions/runtime.html</a></p>\n\n<p>For example, Spring's Data Access bits throw various RuntimeExceptions when things go wrong. Dealing with them is optional.</p>\n"
}
] |
2008/11/11
|
[
"https://Stackoverflow.com/questions/280127",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/34296/"
] |
I'm bored with surrounding code with try catch like this..
```
try
{
//some boring stuff
}
catch(Exception ex)
{
//something even more boring stuff
}
```
I would like something like
```
SurroundWithTryCatch(MyMethod)
```
I know I can accomplish this behaviour by creating a delegate with the exact signature of the function, but creating a delegate for all the methods in my application it's just not an option.
I can also do this by injecting IL code but this is expensive in terms of performance as it creates an wrapper assembly around mine.
Any other valid ideeas?
|
Firstly, it sounds like you may be using try/catch too often - particularly if you're catching `Exception`. try/catch blocks should be relatively rare; unless you can really "handle" the exception, you should just let it bubble up to the next layer of the stack.
Now, assuming you really *do* want all of these try/catch blocks, why is it not an option to create a delegate? With anonymous methods and lambda expressions, as well as the Func/Action delegates in the `System` namespace, there's basically very little work to do. You write:
```
public void SurroundWithTryCatch(Action action)
{
try
{
action();
}
catch(Exception ex)
{
//something even more boring stuff
}
}
```
and then your `SurroundWithTryCatch(MyMethod)` will work fine, if it takes no paramaters.
Alternatively, if you don't want to call a *different* method, just write:
```
public void MyMethod()
{
SurroundWithTryCatch(() =>
{
// Logic here
});
}
```
If you need to return from the method, you can do:
```
public int MyMethod()
{
return SurroundWithTryCatch(() =>
{
// Logic here
return 5;
});
}
```
with a generic overload of `SurroundWithTryCatch` like this:
```
public T SurroundWithTryCatch<T>(Func<T> func)
{
try
{
return func();
}
catch(Exception ex)
{
//something even more boring stuff
}
}
```
Most of this would be fine in C# 2 as well, but type inference won't help you quite as much and you'll have to use anonymous methods instead of lambda expressions.
To go back to the start though: try to use try/catch less often. (try/finally should be much more frequent, although usually written as a using statement.)
|
280,143 |
<p>Well I would like to make a custom run dialog within my program so that the user can test commands without opening it themselves. The only problem is, msdn does not provide any coverage on this. If I cannot make my own custom run dialog and send the data to shell32.dll (where the run dialog is stored) I will settle for the code that can open the run dialog from a button. So far the only information I found is how to open it with VBScript, and I would like to know how to access shell objects within C/C++ directly.</p>
<p>Here is the VBScript if it helps (save as .vbs if you want to see)</p>
<pre><code><script language="VBScript">
function fnShellFileRunVB()
dim objShell
set objShell = CreateObject("Shell.Application")
objShell.FileRun
set objShell = nothing
end function
</script>
</code></pre>
|
[
{
"answer_id": 280447,
"author": "OJ.",
"author_id": 611,
"author_profile": "https://Stackoverflow.com/users/611",
"pm_score": 2,
"selected": true,
"text": "<p>VBScript's CreateObject() function just creates an instance of a COM object. You can do exactly the same thing in C++, you just need to read a <a href=\"http://progtutorials.tripod.com/COM.htm\" rel=\"nofollow noreferrer\">tutorial on how to access COM objects using C++</a> first.</p>\n"
},
{
"answer_id": 282424,
"author": "INS",
"author_id": 13136,
"author_profile": "https://Stackoverflow.com/users/13136",
"pm_score": 0,
"selected": false,
"text": "<p>Creating a simple RUn dialog is not a big problem (the user interface). The data entered by the user can be run via <a href=\"http://msdn.microsoft.com/en-us/library/bb762153(VS.85).aspx\" rel=\"nofollow noreferrer\">ShellExecute</a>. If you want to call the Run dialog then you should use COM.</p>\n"
}
] |
2008/11/11
|
[
"https://Stackoverflow.com/questions/280143",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/36457/"
] |
Well I would like to make a custom run dialog within my program so that the user can test commands without opening it themselves. The only problem is, msdn does not provide any coverage on this. If I cannot make my own custom run dialog and send the data to shell32.dll (where the run dialog is stored) I will settle for the code that can open the run dialog from a button. So far the only information I found is how to open it with VBScript, and I would like to know how to access shell objects within C/C++ directly.
Here is the VBScript if it helps (save as .vbs if you want to see)
```
<script language="VBScript">
function fnShellFileRunVB()
dim objShell
set objShell = CreateObject("Shell.Application")
objShell.FileRun
set objShell = nothing
end function
</script>
```
|
VBScript's CreateObject() function just creates an instance of a COM object. You can do exactly the same thing in C++, you just need to read a [tutorial on how to access COM objects using C++](http://progtutorials.tripod.com/COM.htm) first.
|
280,162 |
<p>I have some low level serialization code that is templated, and I need to know the system's endianness at compiletime obviously (because the templates specializes based on the system's endianness). </p>
<p>Right now I have a header with some platform defines, but I'd rather have someway to make assertions about endianness with some templated test (like a static_assert or boost_if). Reason being my code will need to be compiled and ran on a wide range of machines, of many specialized vendor, and probably devices that don't exist in 2008, so I can't really guess what might need to go into that header years down the road. And since the code-base has an expected lifetime of about 10 years. So I can't follow the code for-ever.</p>
<p>Hopefully this makes my situation clear.</p>
<p>So does anyone know of a compile-time test that can determine endianness, without relying on vendor specific defines?</p>
|
[
{
"answer_id": 280164,
"author": "Johannes Schaub - litb",
"author_id": 34509,
"author_profile": "https://Stackoverflow.com/users/34509",
"pm_score": 3,
"selected": false,
"text": "<p>Hmm, that's an interesting Question. My bet is that this is not possible. I think you have to continue using macros, and go with <code>BOOST_STATIC_ASSERT(!BIG_ENDIAN);</code>, or <code>static_assert</code> in c++0x. The reason i think this is because the endian'nes is a property if your execution environment. However, static_assert is considered at compile time. </p>\n\n<p>I suggest you look into the code of the new <em>GNU gold</em> ELF linker. Ian Lance Taylor, its author, used templates to select the right endianness at compile time, to ensure optimal performance at run time. He explicitely instantiates all possible endians, so that he still has separate compilation (not all templates in headers) of the template definition and declaration. His code is excellent.</p>\n"
},
{
"answer_id": 280174,
"author": "Robert Gamble",
"author_id": 25222,
"author_profile": "https://Stackoverflow.com/users/25222",
"pm_score": 4,
"selected": false,
"text": "<p>There is no portable way to do this at compile time, your best bet is probably to use the <a href=\"http://www.boost.org/\" rel=\"noreferrer\">Boost</a> <a href=\"http://www.boost.org/doc/libs/1_36_0/boost/detail/endian.hpp\" rel=\"noreferrer\">endian macros</a> or emulate the methods they use.</p>\n"
},
{
"answer_id": 280526,
"author": "Hasturkun",
"author_id": 20270,
"author_profile": "https://Stackoverflow.com/users/20270",
"pm_score": 5,
"selected": true,
"text": "<p>If you're using autoconf, you can use the <code>AC_C_BIGENDIAN</code> macro, which is fairly guaranteed to work (setting the <code>WORDS_BIGENDIAN</code> define by default)</p>\n\n<p>alternately, you could try something like the following (taken from autoconf) to get a test that will probably be optimized away (GCC, at least, removes the other branch)</p>\n\n<pre><code>int is_big_endian()\n{\n union {\n long int l;\n char c[sizeof (long int)];\n } u;\n\n u.l = 1;\n\n if (u.c[sizeof(long int)-1] == 1)\n {\n return 1;\n }\n else\n return 0;\n}\n</code></pre>\n"
},
{
"answer_id": 54175491,
"author": "Walter Whitman",
"author_id": 10904636,
"author_profile": "https://Stackoverflow.com/users/10904636",
"pm_score": -1,
"selected": false,
"text": "<p>This answer is based on the following specs (this is for clarity):</p>\n\n<blockquote>\n <p>Language: C++ v17, 64-Bit<br>\n Compilers: g++ v8 (The GNU Compiler Collection <a href=\"https://www.gnu.org/software/gcc/\" rel=\"nofollow noreferrer\">https://www.gnu.org/software/gcc/</a>) & MingW 8.1.0 toolchain (<a href=\"https://sourceforge.net/projects/mingw-w64/files/\" rel=\"nofollow noreferrer\">https://sourceforge.net/projects/mingw-w64/files/</a>)<br>\n OS's: Linux Mint & Windows</p>\n</blockquote>\n\n<p>The following two lines of code can be used to successfully detect a processor's endianness:</p>\n\n<pre><code>const uint8_t IsLittleEndian = char (0x0001);\n</code></pre>\n\n<p>or</p>\n\n<pre><code>#define IsLittleEndian char (0x0001)\n</code></pre>\n\n<p>These two little magical statement gems take advantage of how the processor stores a 16-Bit value in memory.</p>\n\n<p>On a \"Little Endian\" processor, like the Intel and AMD chipsets, a 16-Bit value is stored in a <code>[low order/least significant byte][high order/most significant byte]</code> fashion (the brackets represent a byte in memory).</p>\n\n<p>On a \"Big Endian\" processor, like the PowerPC, Sun Sparc, and IBM S/390 chipsets, a 16-Bit value is stored in a <code>[high order/most significant byte][low order/least significant byte]</code> fashion.</p>\n\n<p>For example, when we store a 16-Bit (two byte) value, let's say <code>0x1234</code>, into a C++ <code>uint16_t</code> (type defined in C++ v11, and later <a href=\"https://en.cppreference.com/w/cpp/types/integer\" rel=\"nofollow noreferrer\">https://en.cppreference.com/w/cpp/types/integer</a>) size variable on a \"Little Endian\" processor, then peer into the memory block the value is stored in, you will find the byte sequence, <code>[34][12]</code>.</p>\n\n<p>On a \"Big Endian processor\", the <code>0x1234</code> value is stored as <code>[12][34]</code>.</p>\n\n<p>Here is a little demo to help demonstrate how various size C++ integer variables are stored in memory on little and big endian processors:</p>\n\n<pre><code>#define __STDC_FORMAT_MACROS // Required for the MingW toolchain\n#include <iostream>\n#include <inttypes.h>\n\nconst uint8_t IsLittleEndian = char (0x0001);\n//#define IsLittleEndian char (0x0001)\n\nstd::string CurrentEndianMsg;\nstd::string OppositeEndianMsg;\n\ntemplate <typename IntegerType>\nvoid PrintIntegerDetails(IntegerType IntegerValue)\n{\n uint16_t SizeOfIntegerValue = sizeof(IntegerValue);\n int8_t i;\n\n std::cout << \"Integer size (in bytes): \" << SizeOfIntegerValue << \"\\n\";\n std::cout << \"Integer value (Decimal): \" << IntegerValue << \"\\n\";\n std::cout << \"Integer value (Hexidecimal): \";\n\n switch (SizeOfIntegerValue)\n {\n case 2: printf(\"0x%04X\\n\", (unsigned int) IntegerValue);\n break;\n case 4: printf(\"0x%08X\\n\", (unsigned int) IntegerValue);\n break;\n case 8: printf(\"0x%016\" PRIX64 \"\\n\", (uint64_t) IntegerValue);\n break;\n }\n\n std::cout << \"Integer stored in memory in byte order:\\n\";\n std::cout << \" \" << CurrentEndianMsg << \" processor [current]: \";\n\n for(i = 0; i < SizeOfIntegerValue; i++)https://stackoverflow.com/qhttps://stackoverflow.com/questions/280162/is-there-a-way-to-do-a-c-style-compile-time-assertion-to-determine-machines-e/54175491#54175491uestions/280162/is-there-a-way-to-do-a-c-style-compile-time-assertion-to-determine-machines-e/54175491#54175491\n {\n printf(\"%02X \", (((unsigned char*) &IntegerValue)[i]));\n }\n\n std::cout << \"\\n \" << OppositeEndianMsg << \" processor [simulated]: \";\n\n for(i = SizeOfIntegerValue - 1; i >= 0; i--)\n {\n printf(\"%02X \", (((unsigned char*) &IntegerValue)[i]));\n }\n\n std::cout << \"\\n\\n\";\n}\n\n\nint main()\n{\n uint16_t ValueUInt16a = 0x0001;\n uint16_t ValueUInt16b = 0x1234;\n uint32_t ValueUInt32a = 0x00000001;\n uint32_t ValueUInt32b = 0x12345678;\n uint64_t ValueUInt64a = 0x0000000000000001;\n uint64_t ValueUInt64b = 0x123456789ABCDEF0;\n\n std::cout << \"Current processor endianness: \";\n\n switch (IsLittleEndian) {\n case 0: CurrentEndianMsg = \"Big Endian\";\n OppositeEndianMsg = \"Little Endian\";\n break;\n case 1: CurrentEndianMsg = \"Little Endian\";\n OppositeEndianMsg = \"Big Endian\";\n break;\n }\n\n std::cout << CurrentEndianMsg << \"\\n\\n\";\n\n PrintIntegerDetails(ValueUInt16a);\n PrintIntegerDetails(ValueUInt16b);\n PrintIntegerDetails(ValueUInt32a);\n PrintIntegerDetails(ValueUInt32b);\n PrintIntegerDetails(ValueUInt64a);\n PrintIntegerDetails(ValueUInt64b);\n\n return 0;\n}\n\n</code></pre>\n\n<p>Here is the output of the demo on my machine:</p>\n\n<pre><code>Current processor endianness: Little Endian\n\nInteger size (in bytes): 2\nInteger value (Decinal): 1\nInteger value (Hexidecimal): 0x0001\nInteger stored in memory in byte order:\n Little Endian processor [current]: 01 00\n Big Endian processor [simulated]: 00 01\n\nInteger size (in bytes): 2\nInteger value (Decinal): 4660\nInteger value (Hexidecimal): 0x1234\nInteger stored in memory in byte order:\n Little Endian processor [current]: 34 12\n Big Endian processor [simulated]: 12 34\n\nInteger size (in bytes): 4\nInteger value (Decinal): 1\nInteger value (Hexidecimal): 0x00000001\nInteger stored in memory in byte order:\n Little Endian processor [current]: 01 00 00 00\n Big Endian processor [simulated]: 00 00 00 01\n\nInteger size (in bytes): 4\nInteger value (Decinal): 305419896\nInteger value (Hexidecimal): 0x12345678\nInteger stored in memory in byte order:\n Little Endian processor [current]: 78 56 34 12\n Big Endian processor [simulated]: 12 34 56 78\n\nInteger size (in bytes): 8\nInteger value (Decinal): 1\nInteger value (Hexidecimal): 0x0000000000000001\nInteger stored in memory in byte order:\n Little Endian processor [current]: 01 00 00 00 00 00 00 00\n Big Endian processor [simulated]: 00 00 00 00 00 00 00 01\n\nInteger size (in bytes): 8\nInteger value (Decinal): 13117684467463790320\nInteger value (Hexidecimal): 0x123456789ABCDEF0While the process\nInteger stored in memory in byte order:\n Little Endian processor [current]: F0 DE BC 9A 78 56 34 12\n Big Endian processor [simulated]: 12 34 56 78 9A BC DE F0\n\n</code></pre>\n\n<p>I wrote this demo with the GNU C++ toolchain in Linux Mint and don't have the means to test in other flavors of C++ like Visual Studio or the MingW toolchain, so I do not know what is required for this to compile in them, nor do I have access to Windows at the moment.</p>\n\n<p>However, a friend of mine tested the code with MingW, 64-Bit (x86_64-8.1.0-release-win32-seh-rt_v6-rev0) and it had errors. After a little bit of research, I discovered I needed to add the line <code>#define __STDC_FORMAT_MACROS</code> at the top of the code for it to compile with MingW.</p>\n\n<p>Now that we can visually see how a 16-Bit value is stored in memory, let's see how we can use that to our advantage to determine the endianness of a processor.</p>\n\n<p>To give a little extra help in visualizing the way that 16-Bit values are stored in memory, let's look at the following chart:</p>\n\n<pre><code>16-Bit Value (Hex): 0x1234\n\nMemory Offset: [00] [01]\n ---------\nMemory Byte Values: [34] [12] <Little Endian>\n [12] [34] <Big Endian>\n\n================================================\n\n16-Bit Value (Hex): 0x0001\n\nMemory Offset: [00] [01]\n ---------\nMemory Byte Values: [01] [00] <Little Endian>\n [00] [01] <Big Endian>\n</code></pre>\n\n<p>When we convert the 16-Bit value <code>0x0001</code> to a char (8-Bit) with the snippet <code>char (0x0001)</code>, the compiler uses the first memory offset of the 16-Bit value for the new value. Here is another chart that shows what happens on both the \"Little Endian\" and \"Big Endian\" processors:</p>\n\n<pre><code>Original 16-Bit Value: 0x0001\n\nStored in memory as: [01][00] <-- Little Endian\n [00][01] <-- Big Endian\n\nTruncate to char: [01][xx] <-- Little Endian\n [01] Final Result\n [00][xx] <-- Big Endian\n [00] Final Result\n</code></pre>\n\n<p>As you can see, we can easily determine the endianness of a processor.</p>\n\n<p><hr>\n<strong>UPDATE:</strong></p>\n\n<p>I am unable to test the demo above on a \"Big Endian\" processor, so I based the code on information I found on the web. Thanks to M.M for pointing out the obvious to me. </p>\n\n<p>I have updated the demo code (as seen below) to test for endianness or a processor correctly.</p>\n\n<pre><code>#define __STDC_FORMAT_MACROS // Required for the MingW toolchain\n#include <iostream>\n#include <inttypes.h>\n\nstd::string CurrentEndianMsg;\nstd::string OppositeEndianMsg;\n\ntemplate <typename IntegerType>\nvoid PrintIntegerDetails(IntegerType IntegerValue)\n{\n uint16_t SizeOfIntegerValue = sizeof(IntegerValue);\n int8_t i;\n\n std::cout << \"Integer size (in bytes): \" << SizeOfIntegerValue << \"\\n\";\n std::cout << \"Integer value (Decimal): \" << IntegerValue << \"\\n\";\n std::cout << \"Integer value (Hexidecimal): \";\n\n switch (SizeOfIntegerValue)\n {\n case 2: printf(\"0x%04X\\n\", (unsigned int) IntegerValue);\n break;\n case 4: printf(\"0x%08X\\n\", (unsigned int) IntegerValue);\n break;\n case 8: printf(\"0x%016\" PRIX64 \"\\n\", (uint64_t) IntegerValue);\n break;\n }\n\n std::cout << \"Integer stored in memory in byte order:\\n\";\n std::cout << \" \" << CurrentEndianMsg << \" processor [current]: \";\n\n for(i = 0; i < SizeOfIntegerValue; i++)\n {\n printf(\"%02X \", (((unsigned char*) &IntegerValue)[i]));\n }\n\n std::cout << \"\\n \" << OppositeEndianMsg << \" processor [simulated]: \";\n\n for(i = SizeOfIntegerValue - 1; i >= 0; i--)\n {\n printf(\"%02X \", (((unsigned char*) &IntegerValue)[i]));\n }\n\n std::cout << \"\\n\\n\";\n}\n\n\nint main()\n{\n uint16_t ValueUInt16a = 0x0001;\n uint16_t ValueUInt16b = 0x1234;\n uint32_t ValueUInt32a = 0x00000001;\n uint32_t ValueUInt32b = 0x12345678;\n uint64_t ValueUInt64a = 0x0000000000000001;\n uint64_t ValueUInt64b = 0x123456789ABCDEF0;\n\n uint16_t EndianTestValue = 0x0001;\n uint8_t IsLittleEndian = ((unsigned char*) &EndianTestValue)[0];\n\n std::cout << \"Current processor endianness: \";\n\n switch (IsLittleEndian) {\n case 0: CurrentEndianMsg = \"Big Endian\";\n OppositeEndianMsg = \"Little Endian\";\n break;\n case 1: CurrentEndianMsg = \"Little Endian\";\n OppositeEndianMsg = \"Big Endian\";\n break;\n }\n\n std::cout << CurrentEndianMsg << \"\\n\\n\";\n\n PrintIntegerDetails(ValueUInt16a);\n PrintIntegerDetails(ValueUInt16b);\n PrintIntegerDetails(ValueUInt32a);\n PrintIntegerDetails(ValueUInt32b);\n PrintIntegerDetails(ValueUInt64a);\n PrintIntegerDetails(ValueUInt64b);\n\n return 0;\n}\n\n</code></pre>\n\n<p>This updated demo creates a 16-Bit value <code>0x0001</code> and then reads the first byte in the variables memory. As seen in the output shown above, on the \"Little Endian\" processors, the value would be 0x01. On \"Big Endian\" processors, the value would be 0x00.</p>\n"
}
] |
2008/11/11
|
[
"https://Stackoverflow.com/questions/280162",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/15124/"
] |
I have some low level serialization code that is templated, and I need to know the system's endianness at compiletime obviously (because the templates specializes based on the system's endianness).
Right now I have a header with some platform defines, but I'd rather have someway to make assertions about endianness with some templated test (like a static\_assert or boost\_if). Reason being my code will need to be compiled and ran on a wide range of machines, of many specialized vendor, and probably devices that don't exist in 2008, so I can't really guess what might need to go into that header years down the road. And since the code-base has an expected lifetime of about 10 years. So I can't follow the code for-ever.
Hopefully this makes my situation clear.
So does anyone know of a compile-time test that can determine endianness, without relying on vendor specific defines?
|
If you're using autoconf, you can use the `AC_C_BIGENDIAN` macro, which is fairly guaranteed to work (setting the `WORDS_BIGENDIAN` define by default)
alternately, you could try something like the following (taken from autoconf) to get a test that will probably be optimized away (GCC, at least, removes the other branch)
```
int is_big_endian()
{
union {
long int l;
char c[sizeof (long int)];
} u;
u.l = 1;
if (u.c[sizeof(long int)-1] == 1)
{
return 1;
}
else
return 0;
}
```
|
280,201 |
<p>In a html page we use the head tag to add reference to our external .js files .. we can also include script tags in the body .. But how do we include our external .js file in a web user control?</p>
<p>After little googling I got this. It works but is this the only way?</p>
<pre><code>ScriptManager.RegisterStartupScript(this.Page, Page.GetType(), "MyUniquekey", @"<script src=""myJsFile.js"" type=""text/javascript""></script>", false);
</code></pre>
<p>-- Zuhaib</p>
|
[
{
"answer_id": 280338,
"author": "Phil Jenkins",
"author_id": 35496,
"author_profile": "https://Stackoverflow.com/users/35496",
"pm_score": 3,
"selected": true,
"text": "<p>You can also use</p>\n\n<pre><code>Page.ClientScript.RegisterClientScriptInclude(\"key\", \"path/to/script.js\");\n</code></pre>\n\n<p>That's the way I always do it anyway</p>\n"
},
{
"answer_id": 280459,
"author": "Phil Jenkins",
"author_id": 35496,
"author_profile": "https://Stackoverflow.com/users/35496",
"pm_score": 1,
"selected": false,
"text": "<blockquote>\n <p>Yes this works too .. but why does all\n the script gets dumped in the body and\n not in the head??</p>\n</blockquote>\n\n<p>There's a potential workaround for that <a href=\"http://www.codeproject.com/KB/aspnet/scriptregister.aspx\" rel=\"nofollow noreferrer\">here</a></p>\n"
},
{
"answer_id": 6748480,
"author": "Simon",
"author_id": 852145,
"author_profile": "https://Stackoverflow.com/users/852145",
"pm_score": 1,
"selected": false,
"text": "<p>That's kind of incorrect .. about needing the Javascript in the body.</p>\n\n<p>A Javascript function would sit in the head unexecuted and not at all affected by the fact that elements are still to load.</p>\n\n<p>Often there is a single call at the end of a page to start execution of scripts at the top.\n(Other methods available)</p>\n\n<p>The only reason that script gets dumped in the body, is because MS doesn't seem to give 2 hoots about JavaScript. \nShame, because forcing us all to use .NET proper, just makes the world full of sluggish pages that needlessly run back and forth to servers for the tiniest requirmenet.</p>\n"
}
] |
2008/11/11
|
[
"https://Stackoverflow.com/questions/280201",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/25138/"
] |
In a html page we use the head tag to add reference to our external .js files .. we can also include script tags in the body .. But how do we include our external .js file in a web user control?
After little googling I got this. It works but is this the only way?
```
ScriptManager.RegisterStartupScript(this.Page, Page.GetType(), "MyUniquekey", @"<script src=""myJsFile.js"" type=""text/javascript""></script>", false);
```
-- Zuhaib
|
You can also use
```
Page.ClientScript.RegisterClientScriptInclude("key", "path/to/script.js");
```
That's the way I always do it anyway
|
280,207 |
<p>I have an object.</p>
<pre><code> fp = open(self.currentEmailPath, "rb")
p = email.Parser.Parser()
self._currentEmailParsedInstance= p.parse(fp)
fp.close()
</code></pre>
<p>self.currentEmailParsedInstance, from this object I want to get the body of an email, text only no HTML....</p>
<p>How do I do it?</p>
<hr>
<p>something like this? </p>
<pre><code> newmsg=self._currentEmailParsedInstance.get_payload()
body=newmsg[0].get_content....?
</code></pre>
<p>then strip the html from body.
just what is that .... method to return the actual text... maybe I mis-understand you</p>
<pre><code> msg=self._currentEmailParsedInstance.get_payload()
print type(msg)
</code></pre>
<p>output = type 'list'</p>
<hr>
<p>the email </p>
<p>Return-Path: <br>
Received: from xx.xx.net (example) by mxx3.xx.net (xxx)<br>
id 485EF65F08EDX5E12 for [email protected]; Thu, 23 Oct 2008 06:07:51 +0200<br>
Received: from xxxxx2 (ccc) by example.net (ccc) (authenticated as [email protected])
id 48798D4001146189 for [email protected]; Thu, 23 Oct 2008 06:07:51 +0200<br>
From: "example" <br>
To: <br>
Subject: FW: example
Date: Thu, 23 Oct 2008 12:07:45 +0800<br>
Organization: example
Message-ID: <001601c934c4$xxxx30$a9ff460a@xxx><br>
MIME-Version: 1.0<br>
Content-Type: multipart/mixed;<br>
boundary="----=_NextPart_000_0017_01C93507.F6F64E30"<br>
X-Mailer: Microsoft Office Outlook 11<br>
X-MimeOLE: Produced By Microsoft MimeOLE V6.00.2900.3138<br>
Thread-Index: Ack0wLaumqgZo1oXSBuIpUCEg/wfOAABAFEA </p>
<p>This is a multi-part message in MIME format. </p>
<p>------=_NextPart_000_0017_01C93507.F6F64E30<br>
Content-Type: multipart/alternative;<br>
boundary="----=_NextPart_001_0018_01C93507.F6F64E30" </p>
<p>------=_NextPart_001_0018_01C93507.F6F64E30<br>
Content-Type: text/plain;<br>
charset="us-ascii"<br>
Content-Transfer-Encoding: 7bit </p>
<p>From: example.example[mailto:[email protected]]<br>
Sent: Thursday, October 23, 2008 11:37 AM<br>
To: [email protected]<br>
Subject: S/I for example(B/L<br>
No.:4357-0120-810.044) </p>
<p>Please find attached the example.doc), </p>
<p>Thanks. </p>
<p>B.rgds, </p>
<p>xxx xxx </p>
<p>------=_NextPart_001_0018_01C93507.F6F64E30<br>
Content-Type: text/html;<br>
charset="us-ascii"<br>
Content-Transfer-Encoding: quoted-printable </p>
<p>
xmlns:o=3D"urn:schemas-microsoft-com:office:office" =<br>
xmlns:w=3D"urn:schemas-microsoft-com:office:word" =<br>
xmlns:st1=3D"urn:schemas-microsoft-com:office:smarttags" =<br>
xmlns=3D"<a href="http://www.w3.org/TR/REC-html40" rel="nofollow noreferrer">http://www.w3.org/TR/REC-html40</a>"> </p>
<p>HTML STUFF till </p>
<p>------=_NextPart_001_0018_01C93507.F6F64E30-- </p>
<p>------=_NextPart_000_0017_01C93507.F6F64E30<br>
Content-Type: application/msword;<br>
name="xxxx.doc"<br>
Content-Transfer-Encoding: base64<br>
Content-Disposition: attachment;<br>
filename="xxxx.doc" </p>
<p>0M8R4KGxGuEAAAAAAAAAAAAAAAAAAAAAPgADAP7/CQAGAAAAAAAAAAAAAAABAAAAYAAAAAAAAAAA
EAAAYgAAAAEAAAD+////AAAAAF8AAAD/////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////s
pcEAI2AJBAAA+FK/AAAAAAAAEAAAAAAABgAAnEIAAA4AYmpiaqEVoRUAAAAAAAAAAAAAAAAAAAAA
AAAECBYAMlAAAMN/AADDfwAAQQ4AAAAAAAAPAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAD//w8AAAAA
AAAAAAD//w8AAAAAAAAAAAD//w8AAAAAAAAAAAAAAAAAAAAAAKQAAAAAAEYEAAAAAAAARgQAAEYE
AAAAAAAARgQAAAAAAABGBAAAAAAAAEYEAAAAAAAARgQAABQAAAAAAAAAAAAAAFoEAAAAAAAA4hsA
AAAAAADiGwAAAAAAAOIbAAA4AAAAGhwAAHwAAACWHAAARAAAAFoEAAAAAAAABzcAAEgBAADmHAAA
FgAAAPwcAAAAAAAA/BwAAAAAAAD8HAAAAAAAAPwcAAAAAAAA/BwAAAAAAAD8HAAAAAAAAPwcAAAA
AAAAMjYAAAIAAAA0NgAAAAAAADQ2AAAAAAAANDYAAAAAAAA0NgAAAAAAADQ2AAAAAAAANDYAACQA
AABPOAAAaAIAALc6AACOAAAAWDYAAGkAAAAAAAAAAAAAAAAAAAAAAAAARgQAAAAAAABHLAAAAAAA
AAAAAAAAAAAAAAAAAAAAAAD8HAAAAAAAAPwcAAAAAAAARywAAAAAAABHLAAAAAAAAFg2AAAAAAAA</p>
<p>------=_NextPart_000_0017_01C93507.F6F64E30-- </p>
<hr>
<p>I just want to get : </p>
<p>From: xxxx.xxxx [mailto:[email protected]]<br>
Sent: Thursday, October 23, 2008 11:37 AM<br>
To: [email protected]<br>
Subject: S/I for xxxxx (B/L<br>
No.:4357-0120-810.044) </p>
<p>Pls find attached the xxxx.doc), </p>
<p>Thanks. </p>
<p>B.rgds, </p>
<p>xxx xxx </p>
<hr>
<p>not sure if the mail is malformed!
seems if you get an html page you have to do this:</p>
<pre><code> parts=self._currentEmailParsedInstance.get_payload()
print parts[0].get_content_type()
..._multipart/alternative_
textParts=parts[0].get_payload()
print textParts[0].get_content_type()
..._text/plain_
body=textParts[0].get_payload()
print body
...get the text without a problem!!
</code></pre>
<p>thank you so much Vinko.</p>
<p>So its kinda like dealing with xml, recursive in nature.</p>
|
[
{
"answer_id": 280238,
"author": "Vinko Vrsalovic",
"author_id": 5190,
"author_profile": "https://Stackoverflow.com/users/5190",
"pm_score": 3,
"selected": true,
"text": "<p>This will get you the contents of the message</p>\n\n<pre><code>self.currentEmailParsedInstance.get_payload()\n</code></pre>\n\n<p>As for the text only part you will have to strip HTML on your own, for example using BeautifulSoup.</p>\n\n<p>Check <a href=\"http://www.python.org/doc/2.2.3/lib/module-email.Message.html\" rel=\"nofollow noreferrer\">this link</a> for more information about the Message class the Parser returns. If you mean getting the text part of messages containing both HTML and plain text version of themselves, you can specify an index to get_payload() to get the part you want.</p>\n\n<p>I tried with a different MIME email because what you pasted seems malformed, hopefully it got malformed when you edited it.</p>\n\n<pre><code>>>> parser = email.parser.Parser()\n>>> message = parser.parse(open('/home/vinko/jlm.txt','r'))\n>>> message.is_multipart()\nTrue\n>>> parts = message.get_payload()\n>>> len(parts)\n2\n>>> parts[0].get_content_type()\n'text/plain'\n>>> parts[1].get_content_type()\n'message/rfc822'\n>>> parts[0].get_payload()\n'Message Text'\n</code></pre>\n\n<p>parts will contain all parts of the multipart message, you can check their content types as shown and get only the text/plain ones, for instance.</p>\n\n<p>Good luck.</p>\n"
},
{
"answer_id": 280562,
"author": "Setori",
"author_id": 21537,
"author_profile": "https://Stackoverflow.com/users/21537",
"pm_score": 0,
"selected": false,
"text": "<p>ended up with this</p>\n\n<pre><code> parser = email.parser.Parser()\n self._email = parser.parse(open('/home/vinko/jlm.txt','r'))\n parts=self._email.get_payload()\n check=parts[0].get_content_type()\n if check == \"text/plain\":\n return parts[0].get_payload()\n elif check == \"multipart/alternative\":\n part=parts[0].get_payload()\n if part[0].get_content_type() == \"text/plain\":\n return part[0].get_payload()\n else:\n return \"cannot obtain the body of the email\"\n else:\n return \"cannot obtain the body of the email\"\n</code></pre>\n"
}
] |
2008/11/11
|
[
"https://Stackoverflow.com/questions/280207",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/21537/"
] |
I have an object.
```
fp = open(self.currentEmailPath, "rb")
p = email.Parser.Parser()
self._currentEmailParsedInstance= p.parse(fp)
fp.close()
```
self.currentEmailParsedInstance, from this object I want to get the body of an email, text only no HTML....
How do I do it?
---
something like this?
```
newmsg=self._currentEmailParsedInstance.get_payload()
body=newmsg[0].get_content....?
```
then strip the html from body.
just what is that .... method to return the actual text... maybe I mis-understand you
```
msg=self._currentEmailParsedInstance.get_payload()
print type(msg)
```
output = type 'list'
---
the email
Return-Path:
Received: from xx.xx.net (example) by mxx3.xx.net (xxx)
id 485EF65F08EDX5E12 for [email protected]; Thu, 23 Oct 2008 06:07:51 +0200
Received: from xxxxx2 (ccc) by example.net (ccc) (authenticated as [email protected])
id 48798D4001146189 for [email protected]; Thu, 23 Oct 2008 06:07:51 +0200
From: "example"
To:
Subject: FW: example
Date: Thu, 23 Oct 2008 12:07:45 +0800
Organization: example
Message-ID: <001601c934c4$xxxx30$a9ff460a@xxx>
MIME-Version: 1.0
Content-Type: multipart/mixed;
boundary="----=\_NextPart\_000\_0017\_01C93507.F6F64E30"
X-Mailer: Microsoft Office Outlook 11
X-MimeOLE: Produced By Microsoft MimeOLE V6.00.2900.3138
Thread-Index: Ack0wLaumqgZo1oXSBuIpUCEg/wfOAABAFEA
This is a multi-part message in MIME format.
------=\_NextPart\_000\_0017\_01C93507.F6F64E30
Content-Type: multipart/alternative;
boundary="----=\_NextPart\_001\_0018\_01C93507.F6F64E30"
------=\_NextPart\_001\_0018\_01C93507.F6F64E30
Content-Type: text/plain;
charset="us-ascii"
Content-Transfer-Encoding: 7bit
From: example.example[mailto:[email protected]]
Sent: Thursday, October 23, 2008 11:37 AM
To: [email protected]
Subject: S/I for example(B/L
No.:4357-0120-810.044)
Please find attached the example.doc),
Thanks.
B.rgds,
xxx xxx
------=\_NextPart\_001\_0018\_01C93507.F6F64E30
Content-Type: text/html;
charset="us-ascii"
Content-Transfer-Encoding: quoted-printable
xmlns:o=3D"urn:schemas-microsoft-com:office:office" =
xmlns:w=3D"urn:schemas-microsoft-com:office:word" =
xmlns:st1=3D"urn:schemas-microsoft-com:office:smarttags" =
xmlns=3D"<http://www.w3.org/TR/REC-html40>">
HTML STUFF till
------=\_NextPart\_001\_0018\_01C93507.F6F64E30--
------=\_NextPart\_000\_0017\_01C93507.F6F64E30
Content-Type: application/msword;
name="xxxx.doc"
Content-Transfer-Encoding: base64
Content-Disposition: attachment;
filename="xxxx.doc"
0M8R4KGxGuEAAAAAAAAAAAAAAAAAAAAAPgADAP7/CQAGAAAAAAAAAAAAAAABAAAAYAAAAAAAAAAA
EAAAYgAAAAEAAAD+////AAAAAF8AAAD/////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////s
pcEAI2AJBAAA+FK/AAAAAAAAEAAAAAAABgAAnEIAAA4AYmpiaqEVoRUAAAAAAAAAAAAAAAAAAAAA
AAAECBYAMlAAAMN/AADDfwAAQQ4AAAAAAAAPAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAD//w8AAAAA
AAAAAAD//w8AAAAAAAAAAAD//w8AAAAAAAAAAAAAAAAAAAAAAKQAAAAAAEYEAAAAAAAARgQAAEYE
AAAAAAAARgQAAAAAAABGBAAAAAAAAEYEAAAAAAAARgQAABQAAAAAAAAAAAAAAFoEAAAAAAAA4hsA
AAAAAADiGwAAAAAAAOIbAAA4AAAAGhwAAHwAAACWHAAARAAAAFoEAAAAAAAABzcAAEgBAADmHAAA
FgAAAPwcAAAAAAAA/BwAAAAAAAD8HAAAAAAAAPwcAAAAAAAA/BwAAAAAAAD8HAAAAAAAAPwcAAAA
AAAAMjYAAAIAAAA0NgAAAAAAADQ2AAAAAAAANDYAAAAAAAA0NgAAAAAAADQ2AAAAAAAANDYAACQA
AABPOAAAaAIAALc6AACOAAAAWDYAAGkAAAAAAAAAAAAAAAAAAAAAAAAARgQAAAAAAABHLAAAAAAA
AAAAAAAAAAAAAAAAAAAAAAD8HAAAAAAAAPwcAAAAAAAARywAAAAAAABHLAAAAAAAAFg2AAAAAAAA
------=\_NextPart\_000\_0017\_01C93507.F6F64E30--
---
I just want to get :
From: xxxx.xxxx [mailto:[email protected]]
Sent: Thursday, October 23, 2008 11:37 AM
To: [email protected]
Subject: S/I for xxxxx (B/L
No.:4357-0120-810.044)
Pls find attached the xxxx.doc),
Thanks.
B.rgds,
xxx xxx
---
not sure if the mail is malformed!
seems if you get an html page you have to do this:
```
parts=self._currentEmailParsedInstance.get_payload()
print parts[0].get_content_type()
..._multipart/alternative_
textParts=parts[0].get_payload()
print textParts[0].get_content_type()
..._text/plain_
body=textParts[0].get_payload()
print body
...get the text without a problem!!
```
thank you so much Vinko.
So its kinda like dealing with xml, recursive in nature.
|
This will get you the contents of the message
```
self.currentEmailParsedInstance.get_payload()
```
As for the text only part you will have to strip HTML on your own, for example using BeautifulSoup.
Check [this link](http://www.python.org/doc/2.2.3/lib/module-email.Message.html) for more information about the Message class the Parser returns. If you mean getting the text part of messages containing both HTML and plain text version of themselves, you can specify an index to get\_payload() to get the part you want.
I tried with a different MIME email because what you pasted seems malformed, hopefully it got malformed when you edited it.
```
>>> parser = email.parser.Parser()
>>> message = parser.parse(open('/home/vinko/jlm.txt','r'))
>>> message.is_multipart()
True
>>> parts = message.get_payload()
>>> len(parts)
2
>>> parts[0].get_content_type()
'text/plain'
>>> parts[1].get_content_type()
'message/rfc822'
>>> parts[0].get_payload()
'Message Text'
```
parts will contain all parts of the multipart message, you can check their content types as shown and get only the text/plain ones, for instance.
Good luck.
|
280,222 |
<p>I have input consisting of a list of nested lists like this:</p>
<pre><code>l = [[[[[39]]]], [1, 2, 3], [4, [5, 3], 1], [[[[8, 9], 10], 11], 12]]
</code></pre>
<p>I want to sort this list based on the sum of all the numbers in the nested lists... so, the values I want to sort by of l would look like this:</p>
<pre><code>[39, 6, 13, 50]
</code></pre>
<p>Then I want to sort based on these. So the output should be:</p>
<pre><code>[[1, 2, 3], [4, [5, 3], 1], [[[[39]]]], [[[[8, 9], 10], 11], 12]]
</code></pre>
<p>What's a nice pythonic way of doing this?</p>
|
[
{
"answer_id": 280224,
"author": "jfs",
"author_id": 4279,
"author_profile": "https://Stackoverflow.com/users/4279",
"pm_score": 3,
"selected": false,
"text": "<pre><code>l.sort(key=sum_nested)\n</code></pre>\n\n<p>Where <code>sum_nested()</code> is:</p>\n\n<pre><code>def sum_nested(astruct):\n try: return sum(map(sum_nested, astruct))\n except TypeError:\n return astruct\n\n\nassert sum_nested([[([8, 9], 10), 11], 12]) == 50\n</code></pre>\n"
},
{
"answer_id": 280226,
"author": "Greg Hewgill",
"author_id": 893,
"author_profile": "https://Stackoverflow.com/users/893",
"pm_score": 4,
"selected": false,
"text": "<p>A little recursive function would do it:</p>\n\n<pre><code>def asum(a):\n if isinstance(a, list):\n return sum(asum(x) for x in a)\n else:\n return a\n\nl = [[[[[39]]]], [1, 2, 3], [4, [5, 3], 1], [[[[8, 9], 10], 11], 12]]\nl.sort(key=asum)\nprint l\n</code></pre>\n"
},
{
"answer_id": 280865,
"author": "Alex Coventry",
"author_id": 1941213,
"author_profile": "https://Stackoverflow.com/users/1941213",
"pm_score": 5,
"selected": true,
"text": "<p>A slight simplification and generalization to the answers provided so far, using a recent addition to python's syntax:</p>\n\n<pre><code>>>> l = [[[[[39]]]], [1, 2, 3], [4, [5, 3], 1], [[[[8, 9], 10], 11], 12]]\n>>> def asum(t): return sum(map(asum, t)) if hasattr(t, '__iter__') else t\n...\n>>> sorted(l, key=asum)\n[[1, 2, 3], [4, [5, 3], 1], [[[[39]]]], [[[[8, 9], 10], 11], 12]]\n</code></pre>\n"
}
] |
2008/11/11
|
[
"https://Stackoverflow.com/questions/280222",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/15055/"
] |
I have input consisting of a list of nested lists like this:
```
l = [[[[[39]]]], [1, 2, 3], [4, [5, 3], 1], [[[[8, 9], 10], 11], 12]]
```
I want to sort this list based on the sum of all the numbers in the nested lists... so, the values I want to sort by of l would look like this:
```
[39, 6, 13, 50]
```
Then I want to sort based on these. So the output should be:
```
[[1, 2, 3], [4, [5, 3], 1], [[[[39]]]], [[[[8, 9], 10], 11], 12]]
```
What's a nice pythonic way of doing this?
|
A slight simplification and generalization to the answers provided so far, using a recent addition to python's syntax:
```
>>> l = [[[[[39]]]], [1, 2, 3], [4, [5, 3], 1], [[[[8, 9], 10], 11], 12]]
>>> def asum(t): return sum(map(asum, t)) if hasattr(t, '__iter__') else t
...
>>> sorted(l, key=asum)
[[1, 2, 3], [4, [5, 3], 1], [[[[39]]]], [[[[8, 9], 10], 11], 12]]
```
|
280,229 |
<p>I want to add an item to an ASP.Net combobox using Javascript. I can retrieve the ID (No Masterpage). How can I add values to the combobox from Javascript? My present code looks like this.</p>
<pre><code> //Fill the years (counting 100 from the first)
function fillvarYear() {
var dt = $('#txtBDate').val();
dt = dt.toString().substring(6);
var ye = parseInt(dt);
//Loop and add the next 100 years from the birth year to the combo
for (var j = 1; j <= 100; j++) {
ye += 1; //Add one year to the year count
var opt = document.createElement("OPTION");
opt.text = ye;
opt.value = ye;
document.form1.ddlYear.add(opt);
}
}
</code></pre>
|
[
{
"answer_id": 280241,
"author": "Cyril Gupta",
"author_id": 33052,
"author_profile": "https://Stackoverflow.com/users/33052",
"pm_score": 0,
"selected": false,
"text": "<p>I found a possible solution. I don't know why the earlier code didn't work for me, but the line below </p>\n\n<p>document.form1.ddlYear.appendChild(new Option(ye, ye));</p>\n"
},
{
"answer_id": 280329,
"author": "Rob Cooper",
"author_id": 832,
"author_profile": "https://Stackoverflow.com/users/832",
"pm_score": 1,
"selected": false,
"text": "<p>Always remember, ASP.NET controls are nothing \"fancy\" - they always end up at some point becoming standard HTML elements.</p>\n\n<p>Try checking out <a href=\"http://www.mredkj.com/tutorials/tutorial005.html\" rel=\"nofollow noreferrer\">this site</a>. It has a pretty nice demo and overview. Take note however that you are <strong>altering the data at the client side - this means you will need to do it on each and every request because the ViewState will not be updated.</strong></p>\n\n<p>TBH, you are probably better off just using a HTML control rather than ASP ComboBox..</p>\n\n<p>Can I ask why you are changing items via Javascript? (out of curiosity) :)</p>\n"
},
{
"answer_id": 280520,
"author": "FlySwat",
"author_id": 1965,
"author_profile": "https://Stackoverflow.com/users/1965",
"pm_score": 2,
"selected": true,
"text": "<p>To see the value on postback:</p>\n\n<pre><code>string selectedValue = Request.Params[combobox.UniqueId]\n</code></pre>\n\n<p>Remember, changing the values in a combobox with javascript will cause an Event Validation exception to be thrown, and is generally a bad idea, as you'll have to explicitly disabled event validation.</p>\n\n<p>I'd recommend placing the combobox in an update panel, so you can read txtBirthDate on the server and generate the appropriate data. You then won't have to manually preserve state either.</p>\n"
}
] |
2008/11/11
|
[
"https://Stackoverflow.com/questions/280229",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/33052/"
] |
I want to add an item to an ASP.Net combobox using Javascript. I can retrieve the ID (No Masterpage). How can I add values to the combobox from Javascript? My present code looks like this.
```
//Fill the years (counting 100 from the first)
function fillvarYear() {
var dt = $('#txtBDate').val();
dt = dt.toString().substring(6);
var ye = parseInt(dt);
//Loop and add the next 100 years from the birth year to the combo
for (var j = 1; j <= 100; j++) {
ye += 1; //Add one year to the year count
var opt = document.createElement("OPTION");
opt.text = ye;
opt.value = ye;
document.form1.ddlYear.add(opt);
}
}
```
|
To see the value on postback:
```
string selectedValue = Request.Params[combobox.UniqueId]
```
Remember, changing the values in a combobox with javascript will cause an Event Validation exception to be thrown, and is generally a bad idea, as you'll have to explicitly disabled event validation.
I'd recommend placing the combobox in an update panel, so you can read txtBirthDate on the server and generate the appropriate data. You then won't have to manually preserve state either.
|
280,243 |
<p>What's the easiest way to use a linked list in python? In scheme, a linked list is defined simply by <code>'(1 2 3 4 5)</code>. Python's lists, <code>[1, 2, 3, 4, 5]</code>, and tuples, <code>(1, 2, 3, 4, 5)</code>, are not, in fact, linked lists, and linked lists have some nice properties such as constant-time concatenation, and being able to reference separate parts of them. Make them immutable and they are really easy to work with!</p>
|
[
{
"answer_id": 280284,
"author": "Martin v. Löwis",
"author_id": 33006,
"author_profile": "https://Stackoverflow.com/users/33006",
"pm_score": 4,
"selected": false,
"text": "<p>Immutable lists are best represented through two-tuples, with None representing NIL. To allow simple formulation of such lists, you can use this function:</p>\n\n<pre><code>def mklist(*args):\n result = None\n for element in reversed(args):\n result = (element, result)\n return result\n</code></pre>\n\n<p>To work with such lists, I'd rather provide the whole collection of LISP functions (i.e. first, second, nth, etc), than introducing methods.</p>\n"
},
{
"answer_id": 280286,
"author": "Nick Stinemates",
"author_id": 4960,
"author_profile": "https://Stackoverflow.com/users/4960",
"pm_score": 6,
"selected": false,
"text": "<p>I wrote this up the other day</p>\n\n<pre><code>#! /usr/bin/env python\n\nclass Node(object):\n def __init__(self):\n self.data = None # contains the data\n self.next = None # contains the reference to the next node\n\n\nclass LinkedList:\n def __init__(self):\n self.cur_node = None\n\n def add_node(self, data):\n new_node = Node() # create a new node\n new_node.data = data\n new_node.next = self.cur_node # link the new node to the 'previous' node.\n self.cur_node = new_node # set the current node to the new one.\n\n def list_print(self):\n node = self.cur_node # cant point to ll!\n while node:\n print node.data\n node = node.next\n\n\n\nll = LinkedList()\nll.add_node(1)\nll.add_node(2)\nll.add_node(3)\n\nll.list_print()\n</code></pre>\n"
},
{
"answer_id": 280572,
"author": "Ber",
"author_id": 11527,
"author_profile": "https://Stackoverflow.com/users/11527",
"pm_score": 1,
"selected": false,
"text": "<p>When using immutable linked lists, consider using Python's tuple directly. </p>\n\n<pre><code>ls = (1, 2, 3, 4, 5)\n\ndef first(ls): return ls[0]\ndef rest(ls): return ls[1:]\n</code></pre>\n\n<p>Its really that ease, and you get to keep the additional funcitons like len(ls), x in ls, etc.</p>\n"
},
{
"answer_id": 281294,
"author": "Brian",
"author_id": 9493,
"author_profile": "https://Stackoverflow.com/users/9493",
"pm_score": 4,
"selected": false,
"text": "<p>Here's a slightly more complex version of a linked list class, with a similar interface to python's sequence types (ie. supports indexing, slicing, concatenation with arbitrary sequences etc). It should have O(1) prepend, doesn't copy data unless it needs to and can be used pretty interchangably with tuples.</p>\n\n<p>It won't be as space or time efficient as lisp cons cells, as python classes are obviously a bit more heavyweight (You could improve things slightly with \"<code>__slots__ = '_head','_tail'</code>\" to reduce memory usage). It will have the desired big O performance characteristics however.</p>\n\n<p>Example of usage:</p>\n\n<pre><code>>>> l = LinkedList([1,2,3,4])\n>>> l\nLinkedList([1, 2, 3, 4])\n>>> l.head, l.tail\n(1, LinkedList([2, 3, 4]))\n\n# Prepending is O(1) and can be done with:\nLinkedList.cons(0, l)\nLinkedList([0, 1, 2, 3, 4])\n# Or prepending arbitrary sequences (Still no copy of l performed):\n[-1,0] + l\nLinkedList([-1, 0, 1, 2, 3, 4])\n\n# Normal list indexing and slice operations can be performed.\n# Again, no copy is made unless needed.\n>>> l[1], l[-1], l[2:]\n(2, 4, LinkedList([3, 4]))\n>>> assert l[2:] is l.next.next\n\n# For cases where the slice stops before the end, or uses a\n# non-contiguous range, we do need to create a copy. However\n# this should be transparent to the user.\n>>> LinkedList(range(100))[-10::2]\nLinkedList([90, 92, 94, 96, 98])\n</code></pre>\n\n<p>Implementation:</p>\n\n<pre><code>import itertools\n\nclass LinkedList(object):\n \"\"\"Immutable linked list class.\"\"\"\n\n def __new__(cls, l=[]):\n if isinstance(l, LinkedList): return l # Immutable, so no copy needed.\n i = iter(l)\n try:\n head = i.next()\n except StopIteration:\n return cls.EmptyList # Return empty list singleton.\n\n tail = LinkedList(i)\n\n obj = super(LinkedList, cls).__new__(cls)\n obj._head = head\n obj._tail = tail\n return obj\n\n @classmethod\n def cons(cls, head, tail):\n ll = cls([head])\n if not isinstance(tail, cls):\n tail = cls(tail)\n ll._tail = tail\n return ll\n\n # head and tail are not modifiable\n @property \n def head(self): return self._head\n\n @property\n def tail(self): return self._tail\n\n def __nonzero__(self): return True\n\n def __len__(self):\n return sum(1 for _ in self)\n\n def __add__(self, other):\n other = LinkedList(other)\n\n if not self: return other # () + l = l\n start=l = LinkedList(iter(self)) # Create copy, as we'll mutate\n\n while l:\n if not l._tail: # Last element?\n l._tail = other\n break\n l = l._tail\n return start\n\n def __radd__(self, other):\n return LinkedList(other) + self\n\n def __iter__(self):\n x=self\n while x:\n yield x.head\n x=x.tail\n\n def __getitem__(self, idx):\n \"\"\"Get item at specified index\"\"\"\n if isinstance(idx, slice):\n # Special case: Avoid constructing a new list, or performing O(n) length \n # calculation for slices like l[3:]. Since we're immutable, just return\n # the appropriate node. This becomes O(start) rather than O(n).\n # We can't do this for more complicated slices however (eg [l:4]\n start = idx.start or 0\n if (start >= 0) and (idx.stop is None) and (idx.step is None or idx.step == 1):\n no_copy_needed=True\n else:\n length = len(self) # Need to calc length.\n start, stop, step = idx.indices(length)\n no_copy_needed = (stop == length) and (step == 1)\n\n if no_copy_needed:\n l = self\n for i in range(start): \n if not l: break # End of list.\n l=l.tail\n return l\n else:\n # We need to construct a new list.\n if step < 1: # Need to instantiate list to deal with -ve step\n return LinkedList(list(self)[start:stop:step])\n else:\n return LinkedList(itertools.islice(iter(self), start, stop, step))\n else: \n # Non-slice index.\n if idx < 0: idx = len(self)+idx\n if not self: raise IndexError(\"list index out of range\")\n if idx == 0: return self.head\n return self.tail[idx-1]\n\n def __mul__(self, n):\n if n <= 0: return Nil\n l=self\n for i in range(n-1): l += self\n return l\n def __rmul__(self, n): return self * n\n\n # Ideally we should compute the has ourselves rather than construct\n # a temporary tuple as below. I haven't impemented this here\n def __hash__(self): return hash(tuple(self))\n\n def __eq__(self, other): return self._cmp(other) == 0\n def __ne__(self, other): return not self == other\n def __lt__(self, other): return self._cmp(other) < 0\n def __gt__(self, other): return self._cmp(other) > 0\n def __le__(self, other): return self._cmp(other) <= 0\n def __ge__(self, other): return self._cmp(other) >= 0\n\n def _cmp(self, other):\n \"\"\"Acts as cmp(): -1 for self<other, 0 for equal, 1 for greater\"\"\"\n if not isinstance(other, LinkedList):\n return cmp(LinkedList,type(other)) # Arbitrary ordering.\n\n A, B = iter(self), iter(other)\n for a,b in itertools.izip(A,B):\n if a<b: return -1\n elif a > b: return 1\n\n try:\n A.next()\n return 1 # a has more items.\n except StopIteration: pass\n\n try:\n B.next()\n return -1 # b has more items.\n except StopIteration: pass\n\n return 0 # Lists are equal\n\n def __repr__(self):\n return \"LinkedList([%s])\" % ', '.join(map(repr,self))\n\nclass EmptyList(LinkedList):\n \"\"\"A singleton representing an empty list.\"\"\"\n def __new__(cls):\n return object.__new__(cls)\n\n def __iter__(self): return iter([])\n def __nonzero__(self): return False\n\n @property\n def head(self): raise IndexError(\"End of list\")\n\n @property\n def tail(self): raise IndexError(\"End of list\")\n\n# Create EmptyList singleton\nLinkedList.EmptyList = EmptyList()\ndel EmptyList\n</code></pre>\n"
},
{
"answer_id": 282238,
"author": "Ber",
"author_id": 11527,
"author_profile": "https://Stackoverflow.com/users/11527",
"pm_score": 7,
"selected": false,
"text": "<p>For some needs, a <a href=\"https://docs.python.org/library/collections.html#collections.deque\" rel=\"noreferrer\">deque</a> may also be useful. You can add and remove items on both ends of a deque at O(1) cost.</p>\n\n<pre><code>from collections import deque\nd = deque([1,2,3,4])\n\nprint d\nfor x in d:\n print x\nprint d.pop(), d\n</code></pre>\n"
},
{
"answer_id": 283630,
"author": "jfs",
"author_id": 4279,
"author_profile": "https://Stackoverflow.com/users/4279",
"pm_score": 7,
"selected": true,
"text": "<p>Here is some list functions based on <a href=\"https://stackoverflow.com/questions/280243/python-linked-list#280284\">Martin v. Löwis's representation</a>:</p>\n\n<pre><code>cons = lambda el, lst: (el, lst)\nmklist = lambda *args: reduce(lambda lst, el: cons(el, lst), reversed(args), None)\ncar = lambda lst: lst[0] if lst else lst\ncdr = lambda lst: lst[1] if lst else lst\nnth = lambda n, lst: nth(n-1, cdr(lst)) if n > 0 else car(lst)\nlength = lambda lst, count=0: length(cdr(lst), count+1) if lst else count\nbegin = lambda *args: args[-1]\ndisplay = lambda lst: begin(w(\"%s \" % car(lst)), display(cdr(lst))) if lst else w(\"nil\\n\")\n</code></pre>\n\n<p>where <code>w = sys.stdout.write</code></p>\n\n<p>Although doubly linked lists are famously used in Raymond Hettinger's <a href=\"http://code.activestate.com/recipes/576694-orderedset/\" rel=\"noreferrer\">ordered set recipe</a>, singly linked lists have no practical value in Python.</p>\n\n<p>I've <em>never</em> used a singly linked list in Python for any problem except educational. </p>\n\n<p>Thomas Watnedal <a href=\"https://stackoverflow.com/questions/280243/python-linked-list#280280\">suggested</a> a good educational resource <a href=\"http://greenteapress.com/thinkpython/html/chap17.html\" rel=\"noreferrer\">How to Think Like a Computer Scientist, Chapter 17: Linked lists</a>:</p>\n\n<p>A linked list is either: </p>\n\n<ul>\n<li>the empty list, represented by None, or </li>\n<li><p>a node that contains a cargo object and a reference to a linked list.</p>\n\n<pre><code>class Node: \n def __init__(self, cargo=None, next=None): \n self.car = cargo \n self.cdr = next \n def __str__(self): \n return str(self.car)\n\ndef display(lst):\n if lst:\n w(\"%s \" % lst)\n display(lst.cdr)\n else:\n w(\"nil\\n\")\n</code></pre></li>\n</ul>\n"
},
{
"answer_id": 3538133,
"author": "Chris Redford",
"author_id": 130427,
"author_profile": "https://Stackoverflow.com/users/130427",
"pm_score": 5,
"selected": false,
"text": "<p>The accepted answer is rather complicated. Here is a more standard design:</p>\n\n<pre><code>L = LinkedList()\nL.insert(1)\nL.insert(1)\nL.insert(2)\nL.insert(4)\nprint L\nL.clear()\nprint L\n</code></pre>\n\n<p>It is a simple <code>LinkedList</code> class based on the straightforward C++ design and <a href=\"http://greenteapress.com/thinkpython/html/chap17.html\" rel=\"noreferrer\">Chapter 17: Linked lists</a>, as recommended by <a href=\"https://stackoverflow.com/questions/280243/python-linked-list/280280#280280\">Thomas Watnedal</a>.</p>\n\n<pre><code>class Node:\n def __init__(self, value = None, next = None):\n self.value = value\n self.next = next\n\n def __str__(self):\n return 'Node ['+str(self.value)+']'\n\nclass LinkedList:\n def __init__(self):\n self.first = None\n self.last = None\n\n def insert(self, x):\n if self.first == None:\n self.first = Node(x, None)\n self.last = self.first\n elif self.last == self.first:\n self.last = Node(x, None)\n self.first.next = self.last\n else:\n current = Node(x, None)\n self.last.next = current\n self.last = current\n\n def __str__(self):\n if self.first != None:\n current = self.first\n out = 'LinkedList [\\n' +str(current.value) +'\\n'\n while current.next != None:\n current = current.next\n out += str(current.value) + '\\n'\n return out + ']'\n return 'LinkedList []'\n\n def clear(self):\n self.__init__()\n</code></pre>\n"
},
{
"answer_id": 6658636,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 2,
"selected": false,
"text": "<p>I based this additional function on <a href=\"https://stackoverflow.com/users/4960/nick-stinemates\">Nick Stinemates</a></p>\n\n<pre><code>def add_node_at_end(self, data):\n new_node = Node()\n node = self.curr_node\n while node:\n if node.next == None:\n node.next = new_node\n new_node.next = None\n new_node.data = data\n node = node.next\n</code></pre>\n\n<p>The method he has adds the new node at the beginning while I have seen a lot of implementations which usually add a new node at the end but whatever, it is fun to do.</p>\n"
},
{
"answer_id": 8367288,
"author": "Y Lan",
"author_id": 1078905,
"author_profile": "https://Stackoverflow.com/users/1078905",
"pm_score": 0,
"selected": false,
"text": "<p>I think the implementation below fill the bill quite gracefully.</p>\n\n<pre><code>'''singly linked lists, by Yingjie Lan, December 1st, 2011'''\n\nclass linkst:\n '''Singly linked list, with pythonic features.\nThe list has pointers to both the first and the last node.'''\n __slots__ = ['data', 'next'] #memory efficient\n def __init__(self, iterable=(), data=None, next=None):\n '''Provide an iterable to make a singly linked list.\nSet iterable to None to make a data node for internal use.'''\n if iterable is not None: \n self.data, self.next = self, None\n self.extend(iterable)\n else: #a common node\n self.data, self.next = data, next\n\n def empty(self):\n '''test if the list is empty'''\n return self.next is None\n\n def append(self, data):\n '''append to the end of list.'''\n last = self.data\n self.data = last.next = linkst(None, data)\n #self.data = last.next\n\n def insert(self, data, index=0):\n '''insert data before index.\nRaise IndexError if index is out of range'''\n curr, cat = self, 0\n while cat < index and curr:\n curr, cat = curr.next, cat+1\n if index<0 or not curr:\n raise IndexError(index)\n new = linkst(None, data, curr.next)\n if curr.next is None: self.data = new\n curr.next = new\n\n def reverse(self):\n '''reverse the order of list in place'''\n current, prev = self.next, None\n while current: #what if list is empty?\n next = current.next\n current.next = prev\n prev, current = current, next\n if self.next: self.data = self.next\n self.next = prev\n\n def delete(self, index=0):\n '''remvoe the item at index from the list'''\n curr, cat = self, 0\n while cat < index and curr.next:\n curr, cat = curr.next, cat+1\n if index<0 or not curr.next:\n raise IndexError(index)\n curr.next = curr.next.next\n if curr.next is None: #tail\n self.data = curr #current == self?\n\n def remove(self, data):\n '''remove first occurrence of data.\nRaises ValueError if the data is not present.'''\n current = self\n while current.next: #node to be examined\n if data == current.next.data: break\n current = current.next #move on\n else: raise ValueError(data)\n current.next = current.next.next\n if current.next is None: #tail\n self.data = current #current == self?\n\n def __contains__(self, data):\n '''membership test using keyword 'in'.'''\n current = self.next\n while current:\n if data == current.data:\n return True\n current = current.next\n return False\n\n def __iter__(self):\n '''iterate through list by for-statements.\nreturn an iterator that must define the __next__ method.'''\n itr = linkst()\n itr.next = self.next\n return itr #invariance: itr.data == itr\n\n def __next__(self):\n '''the for-statement depends on this method\nto provide items one by one in the list.\nreturn the next data, and move on.'''\n #the invariance is checked so that a linked list\n #will not be mistakenly iterated over\n if self.data is not self or self.next is None:\n raise StopIteration()\n next = self.next\n self.next = next.next\n return next.data\n\n def __repr__(self):\n '''string representation of the list'''\n return 'linkst(%r)'%list(self)\n\n def __str__(self):\n '''converting the list to a string'''\n return '->'.join(str(i) for i in self)\n\n #note: this is NOT the class lab! see file linked.py.\n def extend(self, iterable):\n '''takes an iterable, and append all items in the iterable\nto the end of the list self.'''\n last = self.data\n for i in iterable:\n last.next = linkst(None, i)\n last = last.next\n self.data = last\n\n def index(self, data):\n '''TODO: return first index of data in the list self.\n Raises ValueError if the value is not present.'''\n #must not convert self to a tuple or any other containers\n current, idx = self.next, 0\n while current:\n if current.data == data: return idx\n current, idx = current.next, idx+1\n raise ValueError(data)\n</code></pre>\n"
},
{
"answer_id": 15182629,
"author": "Brent O'Connor",
"author_id": 176611,
"author_profile": "https://Stackoverflow.com/users/176611",
"pm_score": 2,
"selected": false,
"text": "<p>The following is what I came up with. It's similer to <a href=\"https://stackoverflow.com/a/280286/176611\">Riccardo C.'s</a>, in this thread, except it prints the numbers in order instead of in reverse. I also made the LinkedList object a Python Iterator in order to print the list out like you would a normal Python list.</p>\n\n<pre><code>class Node:\n\n def __init__(self, data=None):\n self.data = data\n self.next = None\n\n def __str__(self):\n return str(self.data)\n\n\nclass LinkedList:\n\n def __init__(self):\n self.head = None\n self.curr = None\n self.tail = None\n\n def __iter__(self):\n return self\n\n def next(self):\n if self.head and not self.curr:\n self.curr = self.head\n return self.curr\n elif self.curr.next:\n self.curr = self.curr.next\n return self.curr\n else:\n raise StopIteration\n\n def append(self, data):\n n = Node(data)\n if not self.head:\n self.head = n\n self.tail = n\n else:\n self.tail.next = n\n self.tail = self.tail.next\n\n\n# Add 5 nodes\nll = LinkedList()\nfor i in range(1, 6):\n ll.append(i)\n\n# print out the list\nfor n in ll:\n print n\n\n\"\"\"\nExample output:\n$ python linked_list.py\n1\n2\n3\n4\n5\n\"\"\"\n</code></pre>\n"
},
{
"answer_id": 17850004,
"author": "bouzafr",
"author_id": 2617240,
"author_profile": "https://Stackoverflow.com/users/2617240",
"pm_score": 0,
"selected": false,
"text": "<pre><code>class LinkedList:\n def __init__(self, value):\n self.value = value\n self.next = None\n\n def insert(self, node):\n if not self.next:\n self.next = node\n else:\n self.next.insert(node)\n\n def __str__(self):\n if self.next:\n return '%s -> %s' % (self.value, str(self.next))\n else:\n return ' %s ' % self.value\n\nif __name__ == \"__main__\":\n items = ['a', 'b', 'c', 'd', 'e'] \n ll = None\n for item in items:\n if ll:\n next_ll = LinkedList(item)\n ll.insert(next_ll)\n else:\n ll = LinkedList(item)\n print('[ %s ]' % ll)\n</code></pre>\n"
},
{
"answer_id": 19008675,
"author": "Thomas Levine",
"author_id": 407226,
"author_profile": "https://Stackoverflow.com/users/407226",
"pm_score": 2,
"selected": false,
"text": "<p>I just did <a href=\"https://github.com/tlevine/cons.py/blob/master/cons.py\" rel=\"nofollow\">this</a> as a fun toy. It should be immutable as long as you don't touch the underscore-prefixed methods, and it implements a bunch of Python magic like indexing and <code>len</code>.</p>\n"
},
{
"answer_id": 20658095,
"author": "P. Luo",
"author_id": 962910,
"author_profile": "https://Stackoverflow.com/users/962910",
"pm_score": 0,
"selected": false,
"text": "<p>First of all, I assume you want linked lists. In practice, you can use <code>collections.deque</code>, whose current CPython implementation is a doubly linked list of blocks (each block contains an array of 62 cargo objects). It subsumes linked list's functionality. You can also search for a C extension called <code>llist</code> on pypi. If you want a pure-Python and easy-to-follow implementation of the linked list ADT, you can take a look at my following minimal implementation.</p>\n\n<pre><code>class Node (object):\n \"\"\" Node for a linked list. \"\"\"\n def __init__ (self, value, next=None):\n self.value = value\n self.next = next\n\nclass LinkedList (object):\n \"\"\" Linked list ADT implementation using class. \n A linked list is a wrapper of a head pointer\n that references either None, or a node that contains \n a reference to a linked list.\n \"\"\"\n def __init__ (self, iterable=()):\n self.head = None\n for x in iterable:\n self.head = Node(x, self.head)\n\n def __iter__ (self):\n p = self.head\n while p is not None:\n yield p.value\n p = p.next\n\n def prepend (self, x): # 'appendleft'\n self.head = Node(x, self.head)\n\n def reverse (self):\n \"\"\" In-place reversal. \"\"\"\n p = self.head\n self.head = None\n while p is not None:\n p0, p = p, p.next\n p0.next = self.head\n self.head = p0\n\nif __name__ == '__main__':\n ll = LinkedList([6,5,4])\n ll.prepend(3); ll.prepend(2)\n print list(ll)\n ll.reverse()\n print list(ll)\n</code></pre>\n"
},
{
"answer_id": 24342598,
"author": "user1244663",
"author_id": 1244663,
"author_profile": "https://Stackoverflow.com/users/1244663",
"pm_score": 1,
"selected": false,
"text": "<pre><code>class LL(object):\n def __init__(self,val):\n self.val = val\n self.next = None\n\n def pushNodeEnd(self,top,val):\n if top is None:\n top.val=val\n top.next=None\n else:\n tmp=top\n while (tmp.next != None):\n tmp=tmp.next \n newNode=LL(val)\n newNode.next=None\n tmp.next=newNode\n\n def pushNodeFront(self,top,val):\n if top is None:\n top.val=val\n top.next=None\n else:\n newNode=LL(val)\n newNode.next=top\n top=newNode\n\n def popNodeFront(self,top):\n if top is None:\n return\n else:\n sav=top\n top=top.next\n return sav\n\n def popNodeEnd(self,top):\n if top is None:\n return\n else:\n tmp=top\n while (tmp.next != None):\n prev=tmp\n tmp=tmp.next\n prev.next=None\n return tmp\n\ntop=LL(10)\ntop.pushNodeEnd(top, 20)\ntop.pushNodeEnd(top, 30)\npop=top.popNodeEnd(top)\nprint (pop.val)\n</code></pre>\n"
},
{
"answer_id": 24987486,
"author": "dstromberg",
"author_id": 1084684,
"author_profile": "https://Stackoverflow.com/users/1084684",
"pm_score": 1,
"selected": false,
"text": "<p>I've put a Python 2.x and 3.x singly-linked list class at <a href=\"https://pypi.python.org/pypi/linked_list_mod/\" rel=\"nofollow\">https://pypi.python.org/pypi/linked_list_mod/</a></p>\n\n<p>It's tested with CPython 2.7, CPython 3.4, Pypy 2.3.1, Pypy3 2.3.1, and Jython 2.7b2, and comes with a nice automated test suite.</p>\n\n<p>It also includes LIFO and FIFO classes.</p>\n\n<p>They aren't immutable though.</p>\n"
},
{
"answer_id": 26088052,
"author": "Adeel",
"author_id": 1827883,
"author_profile": "https://Stackoverflow.com/users/1827883",
"pm_score": -1,
"selected": false,
"text": "<p>My 2 cents </p>\n\n<pre><code>class Node:\n def __init__(self, value=None, next=None):\n self.value = value\n self.next = next\n\n def __str__(self):\n return str(self.value)\n\n\nclass LinkedList:\n def __init__(self):\n self.first = None\n self.last = None\n\n def add(self, x):\n current = Node(x, None)\n try:\n self.last.next = current\n except AttributeError:\n self.first = current\n self.last = current\n else:\n self.last = current\n\n def print_list(self):\n node = self.first\n while node:\n print node.value\n node = node.next\n\nll = LinkedList()\nll.add(\"1st\")\nll.add(\"2nd\")\nll.add(\"3rd\")\nll.add(\"4th\")\nll.add(\"5th\")\n\nll.print_list()\n\n# Result: \n# 1st\n# 2nd\n# 3rd\n# 4th\n# 5th\n</code></pre>\n"
},
{
"answer_id": 26658719,
"author": "Divesh Kumar",
"author_id": 4199342,
"author_profile": "https://Stackoverflow.com/users/4199342",
"pm_score": -1,
"selected": false,
"text": "<pre><code>enter code here\nenter code here\n\nclass node:\n def __init__(self):\n self.data = None\n self.next = None\nclass linked_list:\n def __init__(self):\n self.cur_node = None\n self.head = None\n def add_node(self,data):\n new_node = node()\n if self.head == None:\n self.head = new_node\n self.cur_node = new_node\n new_node.data = data\n new_node.next = None\n self.cur_node.next = new_node\n self.cur_node = new_node\n def list_print(self):\n node = self.head\n while node:\n print (node.data)\n node = node.next\n def delete(self):\n node = self.head\n next_node = node.next\n del(node)\n self.head = next_node\na = linked_list()\na.add_node(1)\na.add_node(2)\na.add_node(3)\na.add_node(4)\na.delete()\na.list_print()\n</code></pre>\n"
},
{
"answer_id": 26671637,
"author": "Ganesh Pujari",
"author_id": 4201899,
"author_profile": "https://Stackoverflow.com/users/4201899",
"pm_score": -1,
"selected": false,
"text": "<p>If you want to just create a simple liked list then refer this code</p>\n\n<p>l=[1,[2,[3,[4,[5,[6,[7,[8,[9,[10]]]]]]]]]]</p>\n\n<p>for visualize execution for this cod Visit <a href=\"http://www.pythontutor.com/visualize.html#mode=edit\" rel=\"nofollow\">http://www.pythontutor.com/visualize.html#mode=edit</a> </p>\n"
},
{
"answer_id": 40072598,
"author": "demosthenes",
"author_id": 1261030,
"author_profile": "https://Stackoverflow.com/users/1261030",
"pm_score": 1,
"selected": false,
"text": "<pre><code>class LinkedStack:\n'''LIFO Stack implementation using a singly linked list for storage.'''\n\n_ToList = []\n\n#---------- nested _Node class -----------------------------\nclass _Node:\n '''Lightweight, nonpublic class for storing a singly linked node.'''\n __slots__ = '_element', '_next' #streamline memory usage\n\n def __init__(self, element, next):\n self._element = element\n self._next = next\n\n#--------------- stack methods ---------------------------------\ndef __init__(self):\n '''Create an empty stack.'''\n self._head = None\n self._size = 0\n\ndef __len__(self):\n '''Return the number of elements in the stack.'''\n return self._size\n\ndef IsEmpty(self):\n '''Return True if the stack is empty'''\n return self._size == 0\n\ndef Push(self,e):\n '''Add element e to the top of the Stack.'''\n self._head = self._Node(e, self._head) #create and link a new node\n self._size +=1\n self._ToList.append(e)\n\ndef Top(self):\n '''Return (but do not remove) the element at the top of the stack.\n Raise exception if the stack is empty\n '''\n\n if self.IsEmpty():\n raise Exception('Stack is empty')\n return self._head._element #top of stack is at head of list\n\ndef Pop(self):\n '''Remove and return the element from the top of the stack (i.e. LIFO).\n Raise exception if the stack is empty\n '''\n if self.IsEmpty():\n raise Exception('Stack is empty')\n answer = self._head._element\n self._head = self._head._next #bypass the former top node\n self._size -=1\n self._ToList.remove(answer)\n return answer\n\ndef Count(self):\n '''Return how many nodes the stack has'''\n return self.__len__()\n\ndef Clear(self):\n '''Delete all nodes'''\n for i in range(self.Count()):\n self.Pop()\n\ndef ToList(self):\n return self._ToList\n</code></pre>\n"
},
{
"answer_id": 40889052,
"author": "Mina Gabriel",
"author_id": 1410185,
"author_profile": "https://Stackoverflow.com/users/1410185",
"pm_score": 1,
"selected": false,
"text": "<p><strong>Linked List Class</strong></p>\n\n<pre><code>class LinkedStack:\n# Nested Node Class\nclass Node:\n def __init__(self, element, next):\n self.__element = element\n self.__next = next\n\n def get_next(self):\n return self.__next\n\n def get_element(self):\n return self.__element\n\ndef __init__(self):\n self.head = None\n self.size = 0\n self.data = []\n\ndef __len__(self):\n return self.size\n\ndef __str__(self):\n return str(self.data)\n\ndef is_empty(self):\n return self.size == 0\n\ndef push(self, e):\n newest = self.Node(e, self.head)\n self.head = newest\n self.size += 1\n self.data.append(newest)\n\ndef top(self):\n if self.is_empty():\n raise Empty('Stack is empty')\n return self.head.__element\n\ndef pop(self):\n if self.is_empty():\n raise Empty('Stack is empty')\n answer = self.head.element\n self.head = self.head.next\n self.size -= 1\n return answer\n</code></pre>\n\n<p><strong>Usage</strong></p>\n\n<pre><code>from LinkedStack import LinkedStack\n\nx = LinkedStack()\n\nx.push(10)\nx.push(25)\nx.push(55)\n\n\nfor i in range(x.size - 1, -1, -1):\n\n print '|', x.data[i].get_element(), '|' ,\n #next object\n\n if x.data[i].get_next() == None:\n print '--> None'\n else:\n print x.data[i].get_next().get_element(), '-|----> ',\n</code></pre>\n\n<p><strong>Output</strong> </p>\n\n<pre><code>| 55 | 25 -|----> | 25 | 10 -|----> | 10 | --> None\n</code></pre>\n"
},
{
"answer_id": 41977119,
"author": "Sudhanshu Dev",
"author_id": 3875597,
"author_profile": "https://Stackoverflow.com/users/3875597",
"pm_score": 2,
"selected": false,
"text": "<pre><code>class Node(object):\n def __init__(self, data=None, next=None):\n self.data = data\n self.next = next\n\n def setData(self, data):\n self.data = data\n return self.data\n\n def setNext(self, next):\n self.next = next\n\n def getNext(self):\n return self.next\n\n def hasNext(self):\n return self.next != None\n\n\nclass singleLinkList(object):\n\n def __init__(self):\n self.head = None\n\n def isEmpty(self):\n return self.head == None\n\n def insertAtBeginning(self, data):\n newNode = Node()\n newNode.setData(data)\n\n if self.listLength() == 0:\n self.head = newNode\n else:\n newNode.setNext(self.head)\n self.head = newNode\n\n def insertAtEnd(self, data):\n newNode = Node()\n newNode.setData(data)\n\n current = self.head\n\n while current.getNext() != None:\n current = current.getNext()\n\n current.setNext(newNode)\n\n def listLength(self):\n current = self.head\n count = 0\n\n while current != None:\n count += 1\n current = current.getNext()\n return count\n\n def print_llist(self):\n current = self.head\n print(\"List Start.\")\n while current != None:\n print(current.getData())\n current = current.getNext()\n\n print(\"List End.\")\n\n\n\nif __name__ == '__main__':\n ll = singleLinkList()\n ll.insertAtBeginning(55)\n ll.insertAtEnd(56)\n ll.print_llist()\n print(ll.listLength())\n</code></pre>\n"
},
{
"answer_id": 42824275,
"author": "Arovit",
"author_id": 587088,
"author_profile": "https://Stackoverflow.com/users/587088",
"pm_score": 1,
"selected": false,
"text": "<p>Here is my simple implementation: </p>\n\n<pre><code>class Node:\n def __init__(self):\n self.data = None\n self.next = None\n def __str__(self):\n return \"Data %s: Next -> %s\"%(self.data, self.next)\n\nclass LinkedList:\n def __init__(self):\n self.head = Node()\n self.curNode = self.head\n def insertNode(self, data):\n node = Node()\n node.data = data\n node.next = None\n if self.head.data == None:\n self.head = node\n self.curNode = node\n else:\n self.curNode.next = node\n self.curNode = node\n def printList(self):\n print self.head\n\nl = LinkedList()\nl.insertNode(1)\nl.insertNode(2)\nl.insertNode(34)\n</code></pre>\n\n<p>Output:</p>\n\n<pre><code>Data 1: Next -> Data 2: Next -> Data 34: Next -> Data 4: Next -> None\n</code></pre>\n"
},
{
"answer_id": 42993060,
"author": "Farhad Maleki",
"author_id": 5064004,
"author_profile": "https://Stackoverflow.com/users/5064004",
"pm_score": 3,
"selected": false,
"text": "<h1>llist — Linked list datatypes for Python</h1>\n\n<p>llist module implements linked list data structures. It supports a doubly linked list, i.e. <code>dllist</code> and a singly linked data structure <code>sllist</code>.</p>\n\n<h2>dllist objects</h2>\n\n<p>This object represents a doubly linked list data structure. </p>\n\n<h3><code>first</code></h3>\n\n<p>First <code>dllistnode</code> object in the list. <code>None</code> if list is empty. </p>\n\n<h3><code>last</code></h3>\n\n<p>Last <code>dllistnode</code> object in the list. None if list is empty. </p>\n\n<p>dllist objects also support the following methods:</p>\n\n<h3><code>append(x)</code></h3>\n\n<p>Add <code>x</code> to the right side of the list and return inserted <code>dllistnode</code>.</p>\n\n<h3><code>appendleft(x)</code></h3>\n\n<p>Add <code>x</code> to the left side of the list and return inserted <code>dllistnode</code>.</p>\n\n<h3><code>appendright(x)</code></h3>\n\n<p>Add <code>x</code> to the right side of the list and return inserted <code>dllistnode</code>.</p>\n\n<h3><code>clear()</code></h3>\n\n<p>Remove all nodes from the list.</p>\n\n<h3><code>extend(iterable)</code></h3>\n\n<p>Append elements from <code>iterable</code> to the right side of the list.</p>\n\n<h3><code>extendleft(iterable)</code></h3>\n\n<p>Append elements from <code>iterable</code> to the left side of the list. </p>\n\n<h3><code>extendright(iterable)</code></h3>\n\n<p>Append elements from <code>iterable</code> to the right side of the list.</p>\n\n<h3><code>insert(x[, before])</code></h3>\n\n<p>Add <code>x</code> to the right side of the list if <code>before</code> is not specified, or insert <code>x</code> to the left side of <code>dllistnode before</code>. Return inserted <code>dllistnode</code>.</p>\n\n<h3><code>nodeat(index)</code></h3>\n\n<p>Return node (of type <code>dllistnode</code>) at <code>index</code>.</p>\n\n<h3><code>pop()</code></h3>\n\n<p>Remove and return an element’s value from the right side of the list.</p>\n\n<h3><code>popleft()</code></h3>\n\n<p>Remove and return an element’s value from the left side of the list.</p>\n\n<h3><code>popright()</code></h3>\n\n<p>Remove and return an element’s value from the right side of the list </p>\n\n<h3><code>remove(node)</code></h3>\n\n<p>Remove <code>node</code> from the list and return the element which was stored in it.</p>\n\n<h2><code>dllistnode</code> objects</h2>\n\n<h3>class <code>llist.dllistnode([value])</code></h3>\n\n<p>Return a new doubly linked list node, initialized (optionally) with <code>value</code>.</p>\n\n<h3><code>dllistnode</code> objects provide the following attributes:</h3>\n\n<h3><code>next</code></h3>\n\n<p>Next node in the list. This attribute is read-only.</p>\n\n<h3><code>prev</code></h3>\n\n<p>Previous node in the list. This attribute is read-only.</p>\n\n<h3><code>value</code></h3>\n\n<p>Value stored in this node.\n<a href=\"https://pythonhosted.org/llist/\" rel=\"noreferrer\">Compiled from this reference</a></p>\n\n<h1>sllist</h1>\n\n<p>class <code>llist.sllist([iterable])</code>\nReturn a new singly linked list initialized with elements from <code>iterable</code>. If iterable is not specified, the new <code>sllist</code> is empty.</p>\n\n<p>A similar set of attributes and operations are defined for this <code>sllist</code> object. <a href=\"https://pythonhosted.org/llist/#llist.sllist\" rel=\"noreferrer\">See this reference for more information.</a></p>\n"
},
{
"answer_id": 44469829,
"author": "Andre Araujo",
"author_id": 2452792,
"author_profile": "https://Stackoverflow.com/users/2452792",
"pm_score": 0,
"selected": false,
"text": "<p><strong>Sample of a <em>doubly</em> linked list</strong> (save as linkedlist.py): </p>\n\n<pre><code>class node:\n def __init__(self, before=None, cargo=None, next=None): \n self._previous = before\n self._cargo = cargo \n self._next = next \n\n def __str__(self):\n return str(self._cargo) or None \n\nclass linkedList:\n def __init__(self): \n self._head = None \n self._length = 0\n\n def add(self, cargo):\n n = node(None, cargo, self._head)\n if self._head:\n self._head._previous = n\n self._head = n\n self._length += 1\n\n def search(self,cargo):\n node = self._head\n while (node and node._cargo != cargo):\n node = node._next\n return node\n\n def delete(self,cargo):\n node = self.search(cargo)\n if node:\n prev = node._previous\n nx = node._next\n if prev:\n prev._next = node._next\n else:\n self._head = nx\n nx._previous = None\n if nx:\n nx._previous = prev \n else:\n prev._next = None\n self._length -= 1\n\n def __str__(self):\n print 'Size of linked list: ',self._length\n node = self._head\n while node:\n print node\n node = node._next\n</code></pre>\n\n<p><strong>Testing</strong> (save as test.py):</p>\n\n<pre><code>from linkedlist import node, linkedList\n\ndef test():\n\n print 'Testing Linked List'\n\n l = linkedList()\n\n l.add(10)\n l.add(20)\n l.add(30)\n l.add(40)\n l.add(50)\n l.add(60)\n\n print 'Linked List after insert nodes:'\n l.__str__()\n\n print 'Search some value, 30:'\n node = l.search(30)\n print node\n\n print 'Delete some value, 30:'\n node = l.delete(30)\n l.__str__()\n\n print 'Delete first element, 60:'\n node = l.delete(60)\n l.__str__()\n\n print 'Delete last element, 10:'\n node = l.delete(10)\n l.__str__()\n\n\nif __name__ == \"__main__\":\n test()\n</code></pre>\n\n<p><strong>Output</strong>:</p>\n\n<pre><code>Testing Linked List\nLinked List after insert nodes:\nSize of linked list: 6\n60\n50\n40\n30\n20\n10\nSearch some value, 30:\n30\nDelete some value, 30:\nSize of linked list: 5\n60\n50\n40\n20\n10\nDelete first element, 60:\nSize of linked list: 4\n50\n40\n20\n10\nDelete last element, 10:\nSize of linked list: 3\n50\n40\n20\n</code></pre>\n"
},
{
"answer_id": 45598670,
"author": "Abhinav Mehta",
"author_id": 8441618,
"author_profile": "https://Stackoverflow.com/users/8441618",
"pm_score": 2,
"selected": false,
"text": "<p>Here is my solution:</p>\n\n<p><strong>Implementation</strong></p>\n\n<pre><code>class Node:\n def __init__(self, initdata):\n self.data = initdata\n self.next = None\n\n def get_data(self):\n return self.data\n\n def set_data(self, data):\n self.data = data\n\n def get_next(self):\n return self.next\n\n def set_next(self, node):\n self.next = node\n\n\n# ------------------------ Link List class ------------------------------- #\nclass LinkList:\n\n def __init__(self):\n self.head = None\n\n def is_empty(self):\n return self.head == None\n\n def traversal(self, data=None):\n node = self.head\n index = 0\n found = False\n while node is not None and not found:\n if node.get_data() == data:\n found = True\n else:\n node = node.get_next()\n index += 1\n return (node, index)\n\n def size(self):\n _, count = self.traversal(None)\n return count\n\n def search(self, data):\n node, _ = self.traversal(data)\n return node\n\n def add(self, data):\n node = Node(data)\n node.set_next(self.head)\n self.head = node\n\n def remove(self, data):\n previous_node = None\n current_node = self.head\n found = False\n while current_node is not None and not found:\n if current_node.get_data() == data:\n found = True\n if previous_node:\n previous_node.set_next(current_node.get_next())\n else:\n self.head = current_node\n else:\n previous_node = current_node\n current_node = current_node.get_next()\n return found\n</code></pre>\n\n<p><strong>Usage</strong></p>\n\n<pre><code>link_list = LinkList()\nlink_list.add(10)\nlink_list.add(20)\nlink_list.add(30)\nlink_list.add(40)\nlink_list.add(50)\nlink_list.size()\nlink_list.search(30)\nlink_list.remove(20)\n</code></pre>\n\n<p><strong>Original Implementation Idea</strong></p>\n\n<blockquote>\n <p><a href=\"http://interactivepython.org/runestone/static/pythonds/BasicDS/ImplementinganUnorderedListLinkedLists.html\" rel=\"nofollow noreferrer\">http://interactivepython.org/runestone/static/pythonds/BasicDS/ImplementinganUnorderedListLinkedLists.html</a></p>\n</blockquote>\n"
},
{
"answer_id": 46755929,
"author": "Cold Tison",
"author_id": 8779792,
"author_profile": "https://Stackoverflow.com/users/8779792",
"pm_score": -1,
"selected": false,
"text": "<p>my double Linked List might be understandable to noobies. \nIf you are familiar with DS in C, this is quite readable.</p>\n\n<pre><code># LinkedList..\n\nclass node:\n def __init__(self): ##Cluster of Nodes' properties \n self.data=None\n self.next=None\n self.prev=None\n\nclass linkedList():\n def __init__(self):\n self.t = node() // for future use\n self.cur_node = node() // current node\n self.start=node()\n\n def add(self,data): // appending the LL\n\n self.new_node = node()\n self.new_node.data=data\n if self.cur_node.data is None: \n self.start=self.new_node //For the 1st node only\n\n self.cur_node.next=self.new_node\n self.new_node.prev=self.cur_node\n self.cur_node=self.new_node\n\n\n def backward_display(self): //Displays LL backwards\n self.t=self.cur_node\n while self.t.data is not None:\n print(self.t.data)\n self.t=self.t.prev\n\n def forward_display(self): //Displays LL Forward\n self.t=self.start\n while self.t.data is not None:\n print(self.t.data)\n self.t=self.t.next\n if self.t.next is None:\n print(self.t.data)\n break\n\n def main(self): //This is kind of the main \n function in C\n ch=0\n while ch is not 4: //Switch-case in C \n ch=int(input(\"Enter your choice:\"))\n if ch is 1:\n data=int(input(\"Enter data to be added:\"))\n ll.add(data)\n ll.main()\n elif ch is 2:\n ll.forward_display()\n ll.main()\n elif ch is 3:\n ll.backward_display()\n ll.main()\n else:\n print(\"Program ends!!\")\n return\n\n\nll=linkedList()\nll.main()\n</code></pre>\n\n<p>Though many more simplifications can be added to this code, I thought a raw implementation would me more grabbable.</p>\n"
},
{
"answer_id": 57751171,
"author": "Emma",
"author_id": 6553328,
"author_profile": "https://Stackoverflow.com/users/6553328",
"pm_score": 0,
"selected": false,
"text": "<p>I did also write a Single Linked List based on some tutorial, which has the basic two Node and Linked List classes, and some additional methods for insertion, delete, reverse, sorting, and such. </p>\n\n<p>It's not the best or easiest, works OK though.</p>\n\n<pre><code>\"\"\"\n\n\nSingle Linked List (SLL):\nA simple object-oriented implementation of Single Linked List (SLL) \nwith some associated methods, such as create list, count nodes, delete nodes, and such. \n\n\n\"\"\"\n\nclass Node:\n \"\"\"\n Instantiates a node\n \"\"\"\n def __init__(self, value):\n \"\"\"\n Node class constructor which sets the value and link of the node\n\n \"\"\"\n self.info = value\n self.link = None\n\nclass SingleLinkedList:\n \"\"\"\n Instantiates the SLL class\n \"\"\"\n def __init__(self):\n \"\"\"\n SLL class constructor which sets the value and link of the node\n\n \"\"\"\n self.start = None\n\n def create_single_linked_list(self):\n \"\"\"\n Reads values from stdin and appends them to this list and creates a SLL with integer nodes\n\n \"\"\"\n try:\n number_of_nodes = int(input(\" Enter a positive integer between 1-50 for the number of nodes you wish to have in the list: \"))\n if number_of_nodes <= 0 or number_of_nodes > 51:\n print(\" The number of nodes though must be an integer between 1 to 50!\")\n self.create_single_linked_list()\n\n except Exception as e:\n print(\" Error: \", e)\n self.create_single_linked_list()\n\n\n try:\n for _ in range(number_of_nodes):\n try:\n data = int(input(\" Enter an integer for the node to be inserted: \"))\n self.insert_node_at_end(data)\n except Exception as e:\n print(\" Error: \", e)\n except Exception as e:\n print(\" Error: \", e)\n\n def count_sll_nodes(self):\n \"\"\"\n Counts the nodes of the linked list\n\n \"\"\"\n try:\n p = self.start\n n = 0\n while p is not None:\n n += 1\n p = p.link\n\n if n >= 1:\n print(f\" The number of nodes in the linked list is {n}\")\n else:\n print(f\" The SLL does not have a node!\")\n except Exception as e: \n print(\" Error: \", e)\n\n def search_sll_nodes(self, x):\n \"\"\"\n Searches the x integer in the linked list\n \"\"\"\n try:\n position = 1\n p = self.start\n while p is not None:\n if p.info == x:\n print(f\" YAAAY! We found {x} at position {position}\")\n return True\n\n #Increment the position\n position += 1 \n #Assign the next node to the current node\n p = p.link\n else:\n print(f\" Sorry! We couldn't find {x} at any position. Maybe, you might want to use option 9 and try again later!\")\n return False\n except Exception as e:\n print(\" Error: \", e)\n\n def display_sll(self):\n \"\"\"\n Displays the list\n \"\"\"\n try:\n if self.start is None:\n print(\" Single linked list is empty!\")\n return\n\n display_sll = \" Single linked list nodes are: \"\n p = self.start\n while p is not None:\n display_sll += str(p.info) + \"\\t\"\n p = p.link\n\n print(display_sll)\n\n except Exception as e:\n print(\" Error: \", e) \n\n def insert_node_in_beginning(self, data):\n \"\"\"\n Inserts an integer in the beginning of the linked list\n\n \"\"\"\n try:\n temp = Node(data)\n temp.link = self.start\n self.start = temp\n except Exception as e:\n print(\" Error: \", e)\n\n def insert_node_at_end(self, data):\n \"\"\"\n Inserts an integer at the end of the linked list\n\n \"\"\"\n try: \n temp = Node(data)\n if self.start is None:\n self.start = temp\n return\n\n p = self.start \n while p.link is not None:\n p = p.link\n p.link = temp\n except Exception as e:\n print(\" Error: \", e)\n\n\n def insert_node_after_another(self, data, x):\n \"\"\"\n Inserts an integer after the x node\n\n \"\"\"\n try:\n p = self.start\n\n while p is not None:\n if p.info == x:\n break\n p = p.link\n\n if p is None:\n print(f\" Sorry! {x} is not in the list.\")\n else:\n temp = Node(data)\n temp.link = p.link\n p.link = temp\n except Exception as e: \n print(\" Error: \", e)\n\n\n def insert_node_before_another(self, data, x):\n \"\"\"\n Inserts an integer before the x node\n\n \"\"\"\n\n try:\n\n # If list is empty\n if self.start is None:\n print(\" Sorry! The list is empty.\")\n return \n # If x is the first node, and new node should be inserted before the first node\n if x == self.start.info:\n temp = Node(data)\n temp.link = p.link\n p.link = temp\n\n # Finding the reference to the prior node containing x\n p = self.start\n while p.link is not None:\n if p.link.info == x:\n break\n p = p.link\n\n if p.link is not None:\n print(f\" Sorry! {x} is not in the list.\")\n else:\n temp = Node(data)\n temp.link = p.link\n p.link = temp \n\n except Exception as e:\n print(\" Error: \", e)\n\n def insert_node_at_position(self, data, k):\n \"\"\"\n Inserts an integer in k position of the linked list\n\n \"\"\"\n try:\n # if we wish to insert at the first node\n if k == 1:\n temp = Node(data)\n temp.link = self.start\n self.start = temp\n return\n\n p = self.start\n i = 1\n\n while i < k-1 and p is not None:\n p = p.link\n i += 1\n\n if p is None:\n print(f\" The max position is {i}\") \n else: \n temp = Node(data)\n temp.link = self.start\n self.start = temp\n\n except Exception as e:\n print(\" Error: \", e)\n\n def delete_a_node(self, x):\n \"\"\"\n Deletes a node of a linked list\n\n \"\"\"\n try:\n # If list is empty\n if self.start is None:\n print(\" Sorry! The list is empty.\")\n return\n\n # If there is only one node\n if self.start.info == x:\n self.start = self.start.link\n\n # If more than one node exists\n p = self.start\n while p.link is not None:\n if p.link.info == x:\n break \n p = p.link\n\n if p.link is None:\n print(f\" Sorry! {x} is not in the list.\")\n else:\n p.link = p.link.link\n\n except Exception as e:\n print(\" Error: \", e)\n\n def delete_sll_first_node(self):\n \"\"\"\n Deletes the first node of a linked list\n\n \"\"\"\n try:\n if self.start is None:\n return\n self.start = self.start.link\n\n except Exception as e:\n print(\" Error: \", e)\n\n\n def delete_sll_last_node(self):\n \"\"\"\n Deletes the last node of a linked list\n\n \"\"\"\n try:\n\n # If the list is empty\n if self.start is None:\n return\n\n # If there is only one node\n if self.start.link is None:\n self.start = None\n return\n\n # If there is more than one node \n p = self.start\n\n # Increment until we find the node prior to the last node \n while p.link.link is not None:\n p = p.link\n\n p.link = None \n\n except Exception as e:\n print(\" Error: \", e)\n\n\n def reverse_sll(self):\n \"\"\"\n Reverses the linked list\n\n \"\"\"\n\n try:\n\n prev = None\n p = self.start\n while p is not None:\n next = p.link\n p.link = prev\n prev = p\n p = next\n self.start = prev\n\n except Exception as e:\n print(\" Error: \", e)\n\n\n def bubble_sort_sll_nodes_data(self):\n \"\"\"\n Bubble sorts the linked list on integer values\n\n \"\"\"\n\n try:\n\n # If the list is empty or there is only one node\n if self.start is None or self.start.link is None:\n print(\" The list has no or only one node and sorting is not required.\")\n end = None\n\n while end != self.start.link:\n p = self.start\n while p.link != end:\n q = p.link\n if p.info > q.info:\n p.info, q.info = q.info, p.info\n p = p.link\n end = p\n\n except Exception as e:\n print(\" Error: \", e)\n\n\n def bubble_sort_sll(self):\n \"\"\"\n Bubble sorts the linked list\n\n \"\"\"\n\n try:\n\n # If the list is empty or there is only one node\n if self.start is None or self.start.link is None:\n print(\" The list has no or only one node and sorting is not required.\")\n end = None\n\n while end != self.start.link:\n r = p = self.start\n while p.link != end:\n q = p.link\n if p.info > q.info:\n p.link = q.link\n q.link = p\n if p != self.start:\n r.link = q.link\n else:\n self.start = q\n p, q = q, p\n r = p\n p = p.link\n end = p\n\n except Exception as e:\n print(\" Error: \", e)\n\n\n def sll_has_cycle(self):\n \"\"\"\n Tests the list for cycles using Tortoise and Hare Algorithm (Floyd's cycle detection algorithm)\n \"\"\"\n\n try:\n\n if self.find_sll_cycle() is None:\n return False\n else:\n return True\n\n\n except Exception as e:\n print(\" Error: \", e)\n\n\n def find_sll_cycle(self):\n \"\"\"\n Finds cycles in the list, if any\n \"\"\"\n\n try:\n\n # If there is one node or none, there is no cycle\n if self.start is None or self.start.link is None:\n return None\n\n # Otherwise, \n slowR = self.start\n fastR = self.start\n\n while slowR is not None and fastR is not None:\n slowR = slowR.link\n fastR = fastR.link.link\n if slowR == fastR: \n return slowR\n\n return None\n\n except Exception as e:\n print(\" Error: \", e)\n\n\n def remove_cycle_from_sll(self):\n \"\"\"\n Removes the cycles\n \"\"\"\n\n try:\n\n c = self.find_sll_cycle()\n\n # If there is no cycle\n if c is None:\n return\n\n print(f\" There is a cycle at node: \", c.info)\n\n p = c\n q = c\n len_cycles = 0\n while True:\n len_cycles += 1\n q = q.link\n\n if p == q:\n break\n\n print(f\" The cycle length is {len_cycles}\")\n\n len_rem_list = 0\n p = self.start\n\n while p != q:\n len_rem_list += 1\n p = p.link\n q = q.link\n\n print(f\" The number of nodes not included in the cycle is {len_rem_list}\")\n\n length_list = len_rem_list + len_cycles\n\n print(f\" The SLL length is {length_list}\")\n\n # This for loop goes to the end of the SLL, and set the last node to None and the cycle is removed. \n p = self.start\n for _ in range(length_list-1):\n p = p.link\n p.link = None\n\n\n except Exception as e:\n print(\" Error: \", e)\n\n\n def insert_cycle_in_sll(self, x):\n \"\"\"\n Inserts a cycle at a node that contains x\n\n \"\"\"\n\n try:\n\n if self.start is None:\n return False\n\n p = self.start\n px = None\n prev = None\n\n\n while p is not None:\n if p.info == x:\n px = p\n prev = p\n p = p.link\n\n if px is not None:\n prev.link = px\n else:\n print(f\" Sorry! {x} is not in the list.\")\n\n\n except Exception as e:\n print(\" Error: \", e)\n\n\n def merge_using_new_list(self, list2):\n \"\"\"\n Merges two already sorted SLLs by creating new lists\n \"\"\"\n merge_list = SingleLinkedList()\n merge_list.start = self._merge_using_new_list(self.start, list2.start)\n return merge_list\n\n def _merge_using_new_list(self, p1, p2):\n \"\"\"\n Private method of merge_using_new_list\n \"\"\"\n if p1.info <= p2.info:\n Start_merge = Node(p1.info)\n p1 = p1.link\n else:\n Start_merge = Node(p2.info)\n p2 = p2.link \n pM = Start_merge\n\n while p1 is not None and p2 is not None:\n if p1.info <= p2.info:\n pM.link = Node(p1.info)\n p1 = p1.link\n else:\n pM.link = Node(p2.info)\n p2 = p2.link\n pM = pM.link\n\n #If the second list is finished, yet the first list has some nodes\n while p1 is not None:\n pM.link = Node(p1.info)\n p1 = p1.link\n pM = pM.link\n\n #If the second list is finished, yet the first list has some nodes\n while p2 is not None:\n pM.link = Node(p2.info)\n p2 = p2.link\n pM = pM.link\n\n return Start_merge\n\n def merge_inplace(self, list2):\n \"\"\"\n Merges two already sorted SLLs in place in O(1) of space\n \"\"\"\n merge_list = SingleLinkedList()\n merge_list.start = self._merge_inplace(self.start, list2.start)\n return merge_list\n\n def _merge_inplace(self, p1, p2):\n \"\"\"\n Merges two already sorted SLLs in place in O(1) of space\n \"\"\"\n if p1.info <= p2.info:\n Start_merge = p1\n p1 = p1.link\n else:\n Start_merge = p2\n p2 = p2.link\n pM = Start_merge\n\n while p1 is not None and p2 is not None:\n if p1.info <= p2.info:\n pM.link = p1\n pM = pM.link\n p1 = p1.link\n else:\n pM.link = p2\n pM = pM.link\n p2 = p2.link\n\n if p1 is None:\n pM.link = p2\n else:\n pM.link = p1\n\n return Start_merge\n\n def merge_sort_sll(self):\n \"\"\"\n Sorts the linked list using merge sort algorithm\n \"\"\"\n self.start = self._merge_sort_recursive(self.start)\n\n\n def _merge_sort_recursive(self, list_start):\n \"\"\"\n Recursively calls the merge sort algorithm for two divided lists\n \"\"\"\n\n # If the list is empty or has only one node\n if list_start is None or list_start.link is None:\n return list_start\n\n # If the list has two nodes or more\n start_one = list_start\n start_two = self._divide_list(self_start)\n start_one = self._merge_sort_recursive(start_one)\n start_two = self._merge_sort_recursive(start_two)\n start_merge = self._merge_inplace(start_one, start_two)\n\n return start_merge\n\n def _divide_list(self, p):\n \"\"\"\n Divides the linked list into two almost equally sized lists\n \"\"\"\n\n # Refers to the third nodes of the list\n q = p.link.link\n\n while q is not None and p is not None:\n # Increments p one node at the time\n p = p.link\n # Increments q two nodes at the time\n q = q.link.link\n\n start_two = p.link\n p.link = None\n\n return start_two\n\n def concat_second_list_to_sll(self, list2):\n \"\"\"\n Concatenates another SLL to an existing SLL\n \"\"\"\n\n # If the second SLL has no node\n if list2.start is None:\n return\n\n # If the original SLL has no node\n if self.start is None:\n self.start = list2.start\n return\n\n # Otherwise traverse the original SLL\n p = self.start\n while p.link is not None:\n p = p.link\n\n # Link the last node to the first node of the second SLL\n p.link = list2.start\n\n\n\n def test_merge_using_new_list_and_inplace(self):\n \"\"\"\n\n \"\"\"\n\n LIST_ONE = SingleLinkedList()\n LIST_TWO = SingleLinkedList()\n\n LIST_ONE.create_single_linked_list()\n LIST_TWO.create_single_linked_list()\n\n print(\"1️⃣ The unsorted first list is: \")\n LIST_ONE.display_sll()\n\n print(\"2️⃣ The unsorted second list is: \")\n LIST_TWO.display_sll()\n\n\n LIST_ONE.bubble_sort_sll_nodes_data()\n LIST_TWO.bubble_sort_sll_nodes_data()\n\n print(\"1️⃣ The sorted first list is: \")\n LIST_ONE.display_sll()\n\n print(\"2️⃣ The sorted second list is: \")\n LIST_TWO.display_sll()\n\n LIST_THREE = LIST_ONE.merge_using_new_list(LIST_TWO)\n\n print(\"The merged list by creating a new list is: \")\n LIST_THREE.display_sll()\n\n\n LIST_FOUR = LIST_ONE.merge_inplace(LIST_TWO)\n\n print(\"The in-place merged list is: \")\n LIST_FOUR.display_sll() \n\n\n def test_all_methods(self):\n \"\"\"\n Tests all methods of the SLL class\n \"\"\"\n\n OPTIONS_HELP = \"\"\"\n\n Select a method from 1-19: \n\n ℹ️ (1) Create a single liked list (SLL).\n ℹ️ (2) Display the SLL. \n ℹ️ (3) Count the nodes of SLL. \n ℹ️ (4) Search the SLL.\n ℹ️ (5) Insert a node at the beginning of the SLL.\n ℹ️ (6) Insert a node at the end of the SLL.\n ℹ️ (7) Insert a node after a specified node of the SLL.\n ℹ️ (8) Insert a node before a specified node of the SLL.\n ℹ️ (9) Delete the first node of SLL.\n ℹ️ (10) Delete the last node of the SLL.\n ℹ️ (11) Delete a node you wish to remove. \n ℹ️ (12) Reverse the SLL.\n ℹ️ (13) Bubble sort the SLL by only exchanging the integer values. \n ℹ️ (14) Bubble sort the SLL by exchanging links. \n ℹ️ (15) Merge sort the SLL.\n ℹ️ (16) Insert a cycle in the SLL.\n ℹ️ (17) Detect if the SLL has a cycle.\n ℹ️ (18) Remove cycle in the SLL.\n ℹ️ (19) Test merging two bubble-sorted SLLs.\n ℹ️ (20) Concatenate a second list to the SLL. \n ℹ️ (21) Exit.\n\n \"\"\"\n\n\n self.create_single_linked_list()\n\n while True:\n\n print(OPTIONS_HELP)\n\n UI_OPTION = int(input(\" Enter an integer for the method you wish to run using the above help: \"))\n\n if UI_OPTION == 1:\n data = int(input(\" Enter an integer to be inserted at the end of the list: \"))\n x = int(input(\" Enter an integer to be inserted after that: \"))\n self.insert_node_after_another(data, x)\n elif UI_OPTION == 2:\n self.display_sll()\n elif UI_OPTION == 3:\n self.count_sll_nodes()\n elif UI_OPTION == 4:\n data = int(input(\" Enter an integer to be searched: \"))\n self.search_sll_nodes(data)\n elif UI_OPTION == 5:\n data = int(input(\" Enter an integer to be inserted at the beginning: \"))\n self.insert_node_in_beginning(data)\n elif UI_OPTION == 6:\n data = int(input(\" Enter an integer to be inserted at the end: \"))\n self.insert_node_at_end(data)\n elif UI_OPTION == 7:\n data = int(input(\" Enter an integer to be inserted: \"))\n x = int(input(\" Enter an integer to be inserted before that: \"))\n self.insert_node_before_another(data, x)\n elif UI_OPTION == 8:\n data = int(input(\" Enter an integer for the node to be inserted: \"))\n k = int(input(\" Enter an integer for the position at which you wish to insert the node: \"))\n self.insert_node_before_another(data, k)\n elif UI_OPTION == 9:\n self.delete_sll_first_node()\n elif UI_OPTION == 10:\n self.delete_sll_last_node()\n elif UI_OPTION == 11:\n data = int(input(\" Enter an integer for the node you wish to remove: \"))\n self.delete_a_node(data)\n elif UI_OPTION == 12:\n self.reverse_sll()\n elif UI_OPTION == 13:\n self.bubble_sort_sll_nodes_data()\n elif UI_OPTION == 14:\n self.bubble_sort_sll()\n elif UI_OPTION == 15:\n self.merge_sort_sll()\n elif UI_OPTION == 16:\n data = int(input(\" Enter an integer at which a cycle has to be formed: \"))\n self.insert_cycle_in_sll(data)\n elif UI_OPTION == 17:\n if self.sll_has_cycle():\n print(\" The linked list has a cycle. \")\n else:\n print(\" YAAAY! The linked list does not have a cycle. \")\n elif UI_OPTION == 18:\n self.remove_cycle_from_sll()\n elif UI_OPTION == 19:\n self.test_merge_using_new_list_and_inplace()\n elif UI_OPTION == 20:\n list2 = self.create_single_linked_list()\n self.concat_second_list_to_sll(list2)\n elif UI_OPTION == 21:\n break\n else:\n print(\" Option must be an integer, between 1 to 21.\")\n\n print() \n\n\n\nif __name__ == '__main__':\n # Instantiates a new SLL object\n SLL_OBJECT = SingleLinkedList()\n SLL_OBJECT.test_all_methods()\n</code></pre>\n"
},
{
"answer_id": 58677862,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 0,
"selected": false,
"text": "<p>Expanding <a href=\"https://stackoverflow.com/a/280286\">Nick Stinemates's</a> answer</p>\n\n<pre><code>class Node(object):\n def __init__(self):\n self.data = None\n self.next = None\n\nclass LinkedList:\n def __init__(self):\n self.head = None\n\n def prepend_node(self, data):\n new_node = Node()\n new_node.data = data\n new_node.next = self.head\n self.head = new_node\n\n def append_node(self, data):\n new_node = Node()\n new_node.data = data\n current = self.head\n while current.next:\n current = current.next\n current.next = new_node\n\n def reverse(self):\n \"\"\" In-place reversal, modifies exiting list\"\"\"\n previous = None\n current_node = self.head\n\n while current_node:\n temp = current_node.next\n current_node.next = previous\n previous = current_node\n current_node = temp\n self.head = previous\n\n def search(self, data):\n current_node = self.head\n try:\n while current_node.data != data:\n current_node = current_node.next\n return True\n except:\n return False\n\n def display(self):\n if self.head is None:\n print(\"Linked list is empty\")\n else:\n current_node = self.head\n while current_node:\n print(current_node.data)\n current_node = current_node.next\n\n def list_length(self):\n list_length = 0\n current_node = self.head\n while current_node:\n list_length += 1\n current_node = current_node.next\n return list_length\n\n\ndef main():\n linked_list = LinkedList()\n\n linked_list.prepend_node(1)\n linked_list.prepend_node(2)\n linked_list.prepend_node(3)\n linked_list.append_node(24)\n linked_list.append_node(25)\n linked_list.display()\n linked_list.reverse()\n linked_list.display()\n print(linked_list.search(1))\n linked_list.reverse()\n linked_list.display()\n print(\"Lenght of singly linked list is: \" + str(linked_list.list_length()))\n\n\nif __name__ == \"__main__\":\n main()\n\n</code></pre>\n"
},
{
"answer_id": 68262495,
"author": "Farzad Hosseinali",
"author_id": 9477463,
"author_profile": "https://Stackoverflow.com/users/9477463",
"pm_score": -1,
"selected": false,
"text": "<p>Current Implementation of Linked List in Python requires for creation of a separate class, called Node, so that they can be connected using a main Linked List class. In the provided implementation, the Linked List is created without defining a separate class for a node. Using the proposed implementation, Linked Lists are easier to understand and can be simply visualized using the print function.</p>\n<pre><code>class Linkedlist:\n def __init__(self):\n self.outer = None\n\n def add_outermost(self, dt):\n self.outer = [dt, self.outer]\n\n def add_innermost(self, dt):\n p = self.outer\n if not p:\n self.outer = [dt, None]\n return\n while p[1]:\n p = p[1]\n p[1] = [dt, None]\n\n def visualize(self):\n p = self.outer\n l = 'Linkedlist: '\n while p:\n l += (str(p[0])+'->')\n p = p[1]\n print(l + 'None')\n\n ll = Linkedlist()\n ll.add_innermost(8)\n ll.add_outermost(3)\n ll.add_outermost(5)\n ll.add_outermost(2)\n ll.add_innermost(7)\n print(ll.outer)\n ll.visualize()\n</code></pre>\n"
}
] |
2008/11/11
|
[
"https://Stackoverflow.com/questions/280243",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/15055/"
] |
What's the easiest way to use a linked list in python? In scheme, a linked list is defined simply by `'(1 2 3 4 5)`. Python's lists, `[1, 2, 3, 4, 5]`, and tuples, `(1, 2, 3, 4, 5)`, are not, in fact, linked lists, and linked lists have some nice properties such as constant-time concatenation, and being able to reference separate parts of them. Make them immutable and they are really easy to work with!
|
Here is some list functions based on [Martin v. Löwis's representation](https://stackoverflow.com/questions/280243/python-linked-list#280284):
```
cons = lambda el, lst: (el, lst)
mklist = lambda *args: reduce(lambda lst, el: cons(el, lst), reversed(args), None)
car = lambda lst: lst[0] if lst else lst
cdr = lambda lst: lst[1] if lst else lst
nth = lambda n, lst: nth(n-1, cdr(lst)) if n > 0 else car(lst)
length = lambda lst, count=0: length(cdr(lst), count+1) if lst else count
begin = lambda *args: args[-1]
display = lambda lst: begin(w("%s " % car(lst)), display(cdr(lst))) if lst else w("nil\n")
```
where `w = sys.stdout.write`
Although doubly linked lists are famously used in Raymond Hettinger's [ordered set recipe](http://code.activestate.com/recipes/576694-orderedset/), singly linked lists have no practical value in Python.
I've *never* used a singly linked list in Python for any problem except educational.
Thomas Watnedal [suggested](https://stackoverflow.com/questions/280243/python-linked-list#280280) a good educational resource [How to Think Like a Computer Scientist, Chapter 17: Linked lists](http://greenteapress.com/thinkpython/html/chap17.html):
A linked list is either:
* the empty list, represented by None, or
* a node that contains a cargo object and a reference to a linked list.
```
class Node:
def __init__(self, cargo=None, next=None):
self.car = cargo
self.cdr = next
def __str__(self):
return str(self.car)
def display(lst):
if lst:
w("%s " % lst)
display(lst.cdr)
else:
w("nil\n")
```
|
280,247 |
<p>I've tried my best and cannot figure out what happened here. It worked fine in Delphi 4. After upgrading to Delphi 2009, I don't know if this is the way it is supposed to work, or if it's a problem:</p>
<p>This is what my program's menu looks like in Design Mode under Delphi 2009:</p>
<p><a href="https://i.stack.imgur.com/lg57M.gif" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/lg57M.gif" alt="enter image description here"></a></p>
<p>Notice that every word in the Main Menu and the File submenu have one letter underlined. It is supposed to be like this. This underlined letter is called the Accelerator Key and is standard in Windows applications so that you can use the Alt-key and that letter to quickly select the menu item and then submenu item with the keyboard rather than with your mouse.</p>
<p>You get them this way by using the "&" character as part of the caption of the item, for example: Save &As...</p>
<p>When I run my application, and use the mouse to open the File menu, it looks like this:</p>
<p><a href="https://i.stack.imgur.com/zpw14.gif" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/zpw14.gif" alt="enter image description here"></a></p>
<p>The characters are underlined in the main menu, but are not underlined in the File menu.</p>
<p>If instead, I use the Alt-F key to open up the File submenu, then it looks correct like this:</p>
<p><a href="https://i.stack.imgur.com/Hxwn0.gif" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/Hxwn0.gif" alt="enter image description here"></a></p>
<p>and all the Accelerator Key letters are properly underlined.</p>
<p>I've played with the AutoHotKeys option but that's not the problem.</p>
<p>Has someone encountered this problem before? Is the example in the 2nd image correct behavior that I don't know of? Or is there some option or coding mistake that I might have missed?</p>
<hr>
<p>Nov 2009 (one year later): mghie seems to have got to the root of this and figured out the problem. See his accepted answer below.</p>
|
[
{
"answer_id": 280275,
"author": "Francesca",
"author_id": 9842,
"author_profile": "https://Stackoverflow.com/users/9842",
"pm_score": 1,
"selected": false,
"text": "<p>I don't think it is a Delphi generated bug as you have the same behavior with Notepad on Vista. Also in Delphi itself BTW...<br>\nI must confess that I did not pay attention before your question. Thanks for pointing it out.</p>\n"
},
{
"answer_id": 280289,
"author": "mghie",
"author_id": 30568,
"author_profile": "https://Stackoverflow.com/users/30568",
"pm_score": 4,
"selected": true,
"text": "<p>There is a standard Windows setting (under display properties) to normally hide those accelerators unless the Alt key is held down. That would explain why opening the menu with Alt+F10 shows them for you. Maybe that's the cause?</p>\n\n<p>[EDIT]: No, it's not. I just tried, and a simple TForm with a menu item shows the accelerator, but as soon as I add a TImageList and set the ImageIndex of the single menu item, or simply set OwnerDraw to true, then the accelerator underline disappears. I guess that really is a bug in the VCL.</p>\n\n<p>BTW, this is on Windows XP.</p>\n\n<p><strong>Workaround:</strong></p>\n\n<p>I have debugged this using Delphi 2009 on Windows XP 64, and the root cause for the missing accelerators seems to be that Windows sends <code>WM_DRAWITEM</code> messages with the <code>ODS_NOACCEL</code> flag set, which it shouldn't if the system is set to show accelerators at all times. So you could say that it is not a VCL bug, but a Windows problem which the VCL does not work around.</p>\n\n<p>However, you can work around it in your own code, you just need to reset the flag before passing the message to the VCL. Override the window proc</p>\n\n<pre><code>protected\n procedure WndProc(var Message: TMessage); override;\n</code></pre>\n\n<p>like so:</p>\n\n<pre><code>procedure TYourForm.WndProc(var Message: TMessage);\nconst\n ODS_NOACCEL = $100;\nvar\n pDIS: PDrawItemStruct;\n ShowAccel: BOOL;\nbegin\n if (Message.Msg = WM_DRAWITEM) then begin\n pDIS := PDrawItemStruct(Message.LParam);\n if (pDIS^.CtlType = ODT_MENU)\n and SystemParametersInfo(SPI_GETKEYBOARDCUES, 0, @ShowAccel, 0)\n then begin\n if ShowAccel then\n pDIS^.itemState := pDIS^.itemState and not ODS_NOACCEL;\n end;\n end;\n inherited;\nend;\n</code></pre>\n\n<p>This is demonstration code only, you should not call <code>SystemParametersInfo()</code> every time a <code>WM_DRAWITEM</code> message is received, but once at program start, and then every time your program receives a <code>WM_SETTINGCHANGE</code> message. </p>\n"
},
{
"answer_id": 280294,
"author": "Jim McKeeth",
"author_id": 255,
"author_profile": "https://Stackoverflow.com/users/255",
"pm_score": 3,
"selected": false,
"text": "<p>It is a \"feature\" introduced with Windows 2000:</p>\n\n<p>The Old New Thing: <a href=\"http://blogs.msdn.com/oldnewthing/archive/2006/10/05/792913.aspx\" rel=\"nofollow noreferrer\">Why does Windows hide keyboard accelerators and focus rectangles by default?</a></p>\n\n<p>It would appear that Delphi 4 didn't support this Windows feature. </p>\n\n<p>To have 2000 and XP menus show accelerator keys, right-click an empty spot on the desktop, choose Properties, click the Appearance tab, and under Effects, uncheck <em>Hide Underlined Letters for Keyboard Navigation until I Press the Alt Key</em>. Click OK twice.</p>\n\n<p>Not sure how to do it in Vista.</p>\n"
},
{
"answer_id": 373451,
"author": "Step",
"author_id": 46036,
"author_profile": "https://Stackoverflow.com/users/46036",
"pm_score": 0,
"selected": false,
"text": "<p>As Jim McKeeth noted above (correctly), this is \"by design\" behavior. If the menus are triggered through keyboard action the accelerators should be shown, but if triggered by the mouse the accelerators are intentionally not shown. </p>\n\n<p>I have my XP configured to show accelerators at all times, but a quick test with that option changed confirms that the menus should not show underlines either (Visual Studio responded as I expected, no underlines when using the mouse). However, Microsoft Office ignores this setting and always shows the underlines. So it looks like a bug in how the menus are drawn in Delphi (I don't have any experience with Delphi myself). </p>\n\n<p>I found the option for Vista as well: <a href=\"http://www.vistax64.com/vista-general/42125-always-show-menu-underline-keyboard-accelerators.html\" rel=\"nofollow noreferrer\">http://www.vistax64.com/vista-general/42125-always-show-menu-underline-keyboard-accelerators.html</a></p>\n\n<blockquote>\n <p>You can turn this on in the new Ease of Access Center (go to Control\n Panel, click Ease of Access and then click Ease of Access Center). In\n the Ease of Access Center, click Make the keyboard easier to use, and\n at the very bottom select the Underline keyboard shortcuts and access\n keys check box.</p>\n</blockquote>\n\n<p>While doing further research I found this related bug on Delphi forums: <a href=\"http://qc.codegear.com/wc/qcmain.aspx?d=37403\" rel=\"nofollow noreferrer\">http://qc.codegear.com/wc/qcmain.aspx?d=37403</a> </p>\n\n<p>It looks like in your case the child windows (the drawn menus) aren't getting or aren't handling WM_UIUPDATESTATE message from their parent window, which is what causes the redraw with accelerators.</p>\n"
}
] |
2008/11/11
|
[
"https://Stackoverflow.com/questions/280247",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/30176/"
] |
I've tried my best and cannot figure out what happened here. It worked fine in Delphi 4. After upgrading to Delphi 2009, I don't know if this is the way it is supposed to work, or if it's a problem:
This is what my program's menu looks like in Design Mode under Delphi 2009:
[](https://i.stack.imgur.com/lg57M.gif)
Notice that every word in the Main Menu and the File submenu have one letter underlined. It is supposed to be like this. This underlined letter is called the Accelerator Key and is standard in Windows applications so that you can use the Alt-key and that letter to quickly select the menu item and then submenu item with the keyboard rather than with your mouse.
You get them this way by using the "&" character as part of the caption of the item, for example: Save &As...
When I run my application, and use the mouse to open the File menu, it looks like this:
[](https://i.stack.imgur.com/zpw14.gif)
The characters are underlined in the main menu, but are not underlined in the File menu.
If instead, I use the Alt-F key to open up the File submenu, then it looks correct like this:
[](https://i.stack.imgur.com/Hxwn0.gif)
and all the Accelerator Key letters are properly underlined.
I've played with the AutoHotKeys option but that's not the problem.
Has someone encountered this problem before? Is the example in the 2nd image correct behavior that I don't know of? Or is there some option or coding mistake that I might have missed?
---
Nov 2009 (one year later): mghie seems to have got to the root of this and figured out the problem. See his accepted answer below.
|
There is a standard Windows setting (under display properties) to normally hide those accelerators unless the Alt key is held down. That would explain why opening the menu with Alt+F10 shows them for you. Maybe that's the cause?
[EDIT]: No, it's not. I just tried, and a simple TForm with a menu item shows the accelerator, but as soon as I add a TImageList and set the ImageIndex of the single menu item, or simply set OwnerDraw to true, then the accelerator underline disappears. I guess that really is a bug in the VCL.
BTW, this is on Windows XP.
**Workaround:**
I have debugged this using Delphi 2009 on Windows XP 64, and the root cause for the missing accelerators seems to be that Windows sends `WM_DRAWITEM` messages with the `ODS_NOACCEL` flag set, which it shouldn't if the system is set to show accelerators at all times. So you could say that it is not a VCL bug, but a Windows problem which the VCL does not work around.
However, you can work around it in your own code, you just need to reset the flag before passing the message to the VCL. Override the window proc
```
protected
procedure WndProc(var Message: TMessage); override;
```
like so:
```
procedure TYourForm.WndProc(var Message: TMessage);
const
ODS_NOACCEL = $100;
var
pDIS: PDrawItemStruct;
ShowAccel: BOOL;
begin
if (Message.Msg = WM_DRAWITEM) then begin
pDIS := PDrawItemStruct(Message.LParam);
if (pDIS^.CtlType = ODT_MENU)
and SystemParametersInfo(SPI_GETKEYBOARDCUES, 0, @ShowAccel, 0)
then begin
if ShowAccel then
pDIS^.itemState := pDIS^.itemState and not ODS_NOACCEL;
end;
end;
inherited;
end;
```
This is demonstration code only, you should not call `SystemParametersInfo()` every time a `WM_DRAWITEM` message is received, but once at program start, and then every time your program receives a `WM_SETTINGCHANGE` message.
|
280,298 |
<p>A complicated-sounding term with no good explanations from a simple google search... are there any more academically-oriented folk who could explain this one?</p>
|
[
{
"answer_id": 280384,
"author": "Duncan",
"author_id": 7140,
"author_profile": "https://Stackoverflow.com/users/7140",
"pm_score": 1,
"selected": false,
"text": "<p>Okay, just going to hazard a COMPLETE guess here, based on this</p>\n\n<p><a href=\"http://ieeexplore.ieee.org/xpl/freeabs_all.jsp?arnumber=4276578\" rel=\"nofollow noreferrer\">http://ieeexplore.ieee.org/xpl/freeabs_all.jsp?arnumber=4276578</a></p>\n\n<p>I'd say it's a mathematical representation of parametric polymorphism (generics).</p>\n"
},
{
"answer_id": 286474,
"author": "Claudiu",
"author_id": 15055,
"author_profile": "https://Stackoverflow.com/users/15055",
"pm_score": 3,
"selected": true,
"text": "<p>Relational parametricity seems to be the property that a function abstracted over types (like a generic in Java) can have. If it has this property, it means it never inspects its type argument or deconstructs it / uses it in some special way. For example, the function \"id or inc\" here is not relationally parametric:</p>\n\n<pre><code>public class Hey<T>\n{\n public T idOrInc(T var)\n {\n if (var instanceof Integer)\n return (T)(new Integer(((Integer)var).intValue()+1));\n return var;\n }\n public static void main(String[] args) {\n Hey<Integer> h = new Hey<Integer>();\n System.out.println(h.idOrInc(new Integer(10)));\n Hey<Double> h2 = new Hey<Double>();\n System.out.println(h2.idOrInc(new Double(10)));\n }\n}\n</code></pre>\n\n<p>The output is:</p>\n\n<pre><code>$ java Hey\n11\n10.0\n</code></pre>\n"
},
{
"answer_id": 5369065,
"author": "Rasmus Lerchedahl Petersen",
"author_id": 668277,
"author_profile": "https://Stackoverflow.com/users/668277",
"pm_score": 3,
"selected": false,
"text": "<p>Both answers are mostly right. I would say that parametricity is a possible property of polymorphism. And polymorphism is parametric if polymorphic terms behave the same under all instantiations. To \"behave the same\" is a vague, intuitive term. Relational parametricity was introduced by John Reynolds as a mathematical formalization of this. It states that polymorphic terms preserve all relations, which intuitively forces it to behave the same:</p>\n\n<p>Consider f: a list -> a list.\n If we have the relation a~1, b~2, c~3, ..., then we can lift it to lists and hav e.g.\n [a, d, b, c] ~ [1, 4, 2, 3]</p>\n\n<p>Now, if f([a, d, b, c]) = [c, b, d, a] and f preserves relations,\n then f([1, 4, 2, 3]) = [3, 2, 4, 1].\n In other words, if f reverses list of strings, it also reverses lists of numbers.</p>\n\n<p>So relationally parametric polymorphic functions cannot \"inspect the type argument\", in that they cannot alter their behaviour based on the type.</p>\n"
}
] |
2008/11/11
|
[
"https://Stackoverflow.com/questions/280298",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/15055/"
] |
A complicated-sounding term with no good explanations from a simple google search... are there any more academically-oriented folk who could explain this one?
|
Relational parametricity seems to be the property that a function abstracted over types (like a generic in Java) can have. If it has this property, it means it never inspects its type argument or deconstructs it / uses it in some special way. For example, the function "id or inc" here is not relationally parametric:
```
public class Hey<T>
{
public T idOrInc(T var)
{
if (var instanceof Integer)
return (T)(new Integer(((Integer)var).intValue()+1));
return var;
}
public static void main(String[] args) {
Hey<Integer> h = new Hey<Integer>();
System.out.println(h.idOrInc(new Integer(10)));
Hey<Double> h2 = new Hey<Double>();
System.out.println(h2.idOrInc(new Double(10)));
}
}
```
The output is:
```
$ java Hey
11
10.0
```
|
280,313 |
<p>I am trying to merge several XML files in a single XDocument object.</p>
<p>Merge does not exist in XDocument object. I miss this.</p>
<p>Has anyone already implemented a Merge extension method for XDocument, or something similar ?</p>
|
[
{
"answer_id": 280319,
"author": "schnaader",
"author_id": 34065,
"author_profile": "https://Stackoverflow.com/users/34065",
"pm_score": 0,
"selected": false,
"text": "<p>As a workaround, you could use a XSL file to merge the XML files and then transform it to a XDocument object.</p>\n"
},
{
"answer_id": 280379,
"author": "Marc Gravell",
"author_id": 23354,
"author_profile": "https://Stackoverflow.com/users/23354",
"pm_score": 2,
"selected": false,
"text": "<p>Being pragmatic, <code>XDocument</code> vs <code>XmLDocument</code> isn't all-or-nothing (unless you are on Silverlight) - so if <code>XmlDoucument</code> does something you need, and <code>XDocument</code> doesn't, then perhaps use <code>XmlDocument</code> (with <code>ImportNode</code> etc).</p>\n\n<p>That said, even with <code>XDocument</code>, you could presumably use <code>XNode.ReadFrom</code> to import each, then simply <code>.Add</code> it to the main collection.</p>\n\n<p>Of course, if the files are big, <code>XmlReader/XmlWriter</code> might be more efficient... but more complex. Fortunately, <code>XmlWriter</code> has a <code>WriteNode</code> method that accepts an <code>XmlReader</code>, so you can navigate to the first child in the <code>XmlReader</code> and then just blitz it to the output file. Something like:</p>\n\n<pre><code> static void AppendChildren(this XmlWriter writer, string path)\n {\n using (XmlReader reader = XmlReader.Create(path))\n {\n reader.MoveToContent();\n int targetDepth = reader.Depth + 1;\n if(reader.Read()) {\n while (reader.Depth == targetDepth)\n {\n writer.WriteNode(reader, true);\n } \n }\n }\n }\n</code></pre>\n"
},
{
"answer_id": 280512,
"author": "Larry",
"author_id": 24472,
"author_profile": "https://Stackoverflow.com/users/24472",
"pm_score": 6,
"selected": true,
"text": "<p>I tried a bit myself :</p>\n\n<pre><code>var MyDoc = XDocument.Load(\"File1.xml\");\nMyDoc.Root.Add(XDocument.Load(\"File2.xml\").Root.Elements());\n</code></pre>\n\n<p>I dont know whether it is good or bad, but it works fine to me :-)</p>\n"
},
{
"answer_id": 27907730,
"author": "SV0505",
"author_id": 2227230,
"author_profile": "https://Stackoverflow.com/users/2227230",
"pm_score": 2,
"selected": false,
"text": "<p>Merge all xml files from dir to one XDocument</p>\n\n<pre><code>public static XDocument MergeDir(string xmlDir)\n{\n XDocument xdoc = XDocument.Parse(\"<root></root>\");\n System.IO.DirectoryInfo directory = new DirectoryInfo(xmlDir);\n if (directory.Exists)\n {\n foreach (System.IO.FileInfo file in directory.GetFiles())\n {\n if (file.Extension == \".xml\")\n {\n xdoc.Root.Add(XDocument.Load(file.FullName).Root.Elements());\n }\n }\n }\n\n return xdoc;\n}\n</code></pre>\n"
}
] |
2008/11/11
|
[
"https://Stackoverflow.com/questions/280313",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/24472/"
] |
I am trying to merge several XML files in a single XDocument object.
Merge does not exist in XDocument object. I miss this.
Has anyone already implemented a Merge extension method for XDocument, or something similar ?
|
I tried a bit myself :
```
var MyDoc = XDocument.Load("File1.xml");
MyDoc.Root.Add(XDocument.Load("File2.xml").Root.Elements());
```
I dont know whether it is good or bad, but it works fine to me :-)
|
280,324 |
<p>I have been using classes for only a short while and when I write a method, I make all variables reference self, e.g. self.foo.</p>
<p>However, I'm looking through the <em>wxPython in Action</em> book and notice that "self" isn't used all the time. For example:</p>
<pre><code> import wx
class TextFrame(wx.Frame):
def __init__(self):
wx.Frame.__init__(self, None, -1, 'Text Entry Example',
size=(300, 100))
panel = wx.Panel(self, -1)
basicLabel = wx.StaticText(panel, -1, "Basic Control:")
basicText = wx.TextCtrl(panel, -1, "I've entered some text!",
size=(175, -1))
basicText.SetInsertionPoint(0)
pwdLabel = wx.StaticText(panel, -1, "Password:")
pwdText = wx.TextCtrl(panel, -1, "password", size=(175, -1),
style=wx.TE_PASSWORD)
sizer = wx.FlexGridSizer(cols=2, hgap=6, vgap=6)
sizer.AddMany([basicLabel, basicText, pwdLabel, pwdText])
panel.SetSizer(sizer)
</code></pre>
<p>The one below does use "self".</p>
<pre><code>import wx
class ButtonFrame(wx.Frame):
def __init__(self):
wx.Frame.__init__(self, None, -1, 'Button Example',
size=(300, 100))
panel = wx.Panel(self, -1)
self.button = wx.Button(panel, -1, "Hello", pos=(50, 20))
self.Bind(wx.EVT_BUTTON, self.OnClick, self.button)
self.button.SetDefault()
def OnClick(self, event):
self.button.SetLabel("Clicked")
</code></pre>
<p>If I remember correctly, "self" is reference to a particular instance of the class, so when is it not necessary? Is there a general rule of thumb?</p>
|
[
{
"answer_id": 280332,
"author": "Greg Hewgill",
"author_id": 893,
"author_profile": "https://Stackoverflow.com/users/893",
"pm_score": 2,
"selected": false,
"text": "<p>In those instances, if you do not use <code>self</code> then you will create only a local variable of that name. In the first example, <code>panel</code> is created as a local variable and then referenced later in the function, but it won't be available outside that function. The act of passing <code>self</code> to the wx.Panel constructor associated it with the current object in some fashion, so it doesn't just disappear when the function returns.</p>\n"
},
{
"answer_id": 280336,
"author": "Martin v. Löwis",
"author_id": 33006,
"author_profile": "https://Stackoverflow.com/users/33006",
"pm_score": 0,
"selected": false,
"text": "<p>self is <strong>always</strong> required when referring to the instance itself, except when calling the base class constructor (wx.Frame.__init__). All the other variables that you see in the examples (panel, basicLabel, basicText, ...) are just local variables - not related to the current object at all. These names will be gone when the method returns - everything put into self.foo will survive the end of the method, and be available in the next method (e.g. self.button).</p>\n"
},
{
"answer_id": 280561,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 4,
"selected": true,
"text": "<p>You use <code>self.attribute</code> to reference an attribute of your current instance.</p>\n\n<p>You use <code>wx.Frame.__init__()</code> to reference a method of the parent class.</p>\n\n<p>You don't use <code>self</code> if you only reference a local name (variable) of the method (function) you are in.</p>\n\n<p>These are not \"rules of thumb,\" because there are no exceptions.</p>\n\n<hr>\n\n<p>What is probably confusing you in this particular example is that panel seems to be only a local name in the constructor, so it looks like the panel would disappear, once your constructor returns.</p>\n\n<p>If you look at the documentation to <code>wx.Panel</code>, though, you will see that <em>its</em> constructor attaches the panel to the parent window, so it will continue to exist, even after the constructor returns.</p>\n\n<p>Magic :)</p>\n"
}
] |
2008/11/11
|
[
"https://Stackoverflow.com/questions/280324",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/18676/"
] |
I have been using classes for only a short while and when I write a method, I make all variables reference self, e.g. self.foo.
However, I'm looking through the *wxPython in Action* book and notice that "self" isn't used all the time. For example:
```
import wx
class TextFrame(wx.Frame):
def __init__(self):
wx.Frame.__init__(self, None, -1, 'Text Entry Example',
size=(300, 100))
panel = wx.Panel(self, -1)
basicLabel = wx.StaticText(panel, -1, "Basic Control:")
basicText = wx.TextCtrl(panel, -1, "I've entered some text!",
size=(175, -1))
basicText.SetInsertionPoint(0)
pwdLabel = wx.StaticText(panel, -1, "Password:")
pwdText = wx.TextCtrl(panel, -1, "password", size=(175, -1),
style=wx.TE_PASSWORD)
sizer = wx.FlexGridSizer(cols=2, hgap=6, vgap=6)
sizer.AddMany([basicLabel, basicText, pwdLabel, pwdText])
panel.SetSizer(sizer)
```
The one below does use "self".
```
import wx
class ButtonFrame(wx.Frame):
def __init__(self):
wx.Frame.__init__(self, None, -1, 'Button Example',
size=(300, 100))
panel = wx.Panel(self, -1)
self.button = wx.Button(panel, -1, "Hello", pos=(50, 20))
self.Bind(wx.EVT_BUTTON, self.OnClick, self.button)
self.button.SetDefault()
def OnClick(self, event):
self.button.SetLabel("Clicked")
```
If I remember correctly, "self" is reference to a particular instance of the class, so when is it not necessary? Is there a general rule of thumb?
|
You use `self.attribute` to reference an attribute of your current instance.
You use `wx.Frame.__init__()` to reference a method of the parent class.
You don't use `self` if you only reference a local name (variable) of the method (function) you are in.
These are not "rules of thumb," because there are no exceptions.
---
What is probably confusing you in this particular example is that panel seems to be only a local name in the constructor, so it looks like the panel would disappear, once your constructor returns.
If you look at the documentation to `wx.Panel`, though, you will see that *its* constructor attaches the panel to the parent window, so it will continue to exist, even after the constructor returns.
Magic :)
|
280,331 |
<p>This seems like it should be easy but I'm stumped. In WPF, I'd like a TextBox that stretches to the width of it's parent, but only to a maximum width. The problem is that I want it to be left justified within its parent. To get it to stretch you have to use HorizontalAlignment="Stretch", but then the result is centered. I've experimented with HorizontalContentAlignment, but it doesn't seem to do anything.</p>
<p>How do I get this blue text box to grow with the size of the window, have a maximum width of 200 pixels, and be left justified?</p>
<pre><code><Page
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml">
<StackPanel>
<TextBox Background="Azure" Text="Hello" HorizontalAlignment="Stretch" MaxWidth="200" />
</StackPanel>
</Page>
</code></pre>
<p>What's the trick?</p>
|
[
{
"answer_id": 280402,
"author": "Kent Boogaart",
"author_id": 5380,
"author_profile": "https://Stackoverflow.com/users/5380",
"pm_score": 6,
"selected": false,
"text": "<pre><code><Grid>\n <Grid.ColumnDefinitions>\n <ColumnDefinition Width=\"*\" MaxWidth=\"200\"/>\n </Grid.ColumnDefinitions>\n\n <TextBox Background=\"Azure\" Text=\"Hello\" />\n</Grid>\n</code></pre>\n"
},
{
"answer_id": 280417,
"author": "Nir",
"author_id": 3509,
"author_profile": "https://Stackoverflow.com/users/3509",
"pm_score": 8,
"selected": true,
"text": "<p>You can set <code>HorizontalAlignment</code> to Left, set your <code>MaxWidth</code> and then bind <code>Width</code> to the <code>ActualWidth</code> of the parent element:</p>\n\n<pre><code><Page\n xmlns=\"http://schemas.microsoft.com/winfx/2006/xaml/presentation\"\n xmlns:x=\"http://schemas.microsoft.com/winfx/2006/xaml\">\n <StackPanel Name=\"Container\"> \n <TextBox Background=\"Azure\" \n Width=\"{Binding ElementName=Container,Path=ActualWidth}\"\n Text=\"Hello\" HorizontalAlignment=\"Left\" MaxWidth=\"200\" />\n </StackPanel>\n</Page>\n</code></pre>\n"
},
{
"answer_id": 280649,
"author": "Scott Bussinger",
"author_id": 9045,
"author_profile": "https://Stackoverflow.com/users/9045",
"pm_score": 3,
"selected": false,
"text": "<p>Both answers given worked for the problem I stated -- Thanks!</p>\n\n<p>In my real application though, I was trying to constrain a panel inside of a ScrollViewer and Kent's method didn't handle that very well for some reason I didn't bother to track down. Basically the controls could expand beyond the MaxWidth setting and defeated my intent.</p>\n\n<p>Nir's technique worked well and didn't have the problem with the ScrollViewer, though there is one minor thing to watch out for. You want to be sure the right and left margins on the TextBox are set to 0 or they'll get in the way. I also changed the binding to use ViewportWidth instead of ActualWidth to avoid issues when the vertical scrollbar appeared.</p>\n"
},
{
"answer_id": 3573316,
"author": "Filip Skakun",
"author_id": 41942,
"author_profile": "https://Stackoverflow.com/users/41942",
"pm_score": 3,
"selected": false,
"text": "<p>You can use this for the Width of your DataTemplate:</p>\n\n<pre><code>Width=\"{Binding ActualWidth,RelativeSource={RelativeSource FindAncestor, AncestorType={x:Type ScrollContentPresenter}}}\"\n</code></pre>\n\n<p>Make sure your DataTemplate root has Margin=\"0\" (you can use some panel as the root and set the Margin to the children of that root)</p>\n"
},
{
"answer_id": 46027269,
"author": "Patrick Cairns",
"author_id": 4204476,
"author_profile": "https://Stackoverflow.com/users/4204476",
"pm_score": 0,
"selected": false,
"text": "<p>I would use <code>SharedSizeGroup</code></p>\n\n<pre class=\"lang-xml prettyprint-override\"><code><Grid>\n <Grid.ColumnDefinition>\n <ColumnDefinition SharedSizeGroup=\"col1\"></ColumnDefinition> \n <ColumnDefinition SharedSizeGroup=\"col2\"></ColumnDefinition>\n </Grid.ColumnDefinition>\n <TextBox Background=\"Azure\" Text=\"Hello\" Grid.Column=\"1\" MaxWidth=\"200\" />\n</Grid>\n</code></pre>\n"
},
{
"answer_id": 50928803,
"author": "Y C",
"author_id": 1257577,
"author_profile": "https://Stackoverflow.com/users/1257577",
"pm_score": 2,
"selected": false,
"text": "<p>Maybe I can still help somebody out who bumps into this question, because this is a very old issue.</p>\n<p>I needed this as well and wrote a behavior to take care of this. So here is the behavior:</p>\n<pre class=\"lang-cs prettyprint-override\"><code>public class StretchMaxWidthBehavior : Behavior<FrameworkElement>\n{ \n protected override void OnAttached()\n {\n base.OnAttached();\n ((FrameworkElement)this.AssociatedObject.Parent).SizeChanged += this.OnSizeChanged;\n }\n\n protected override void OnDetaching()\n {\n base.OnDetaching();\n ((FrameworkElement)this.AssociatedObject.Parent).SizeChanged -= this.OnSizeChanged;\n }\n\n private void OnSizeChanged(object sender, SizeChangedEventArgs e)\n {\n this.SetAlignments();\n }\n\n private void SetAlignments()\n {\n var slot = LayoutInformation.GetLayoutSlot(this.AssociatedObject);\n var newWidth = slot.Width;\n var newHeight = slot.Height;\n\n if (!double.IsInfinity(this.AssociatedObject.MaxWidth))\n {\n if (this.AssociatedObject.MaxWidth < newWidth)\n {\n this.AssociatedObject.HorizontalAlignment = HorizontalAlignment.Left;\n this.AssociatedObject.Width = this.AssociatedObject.MaxWidth;\n }\n else\n {\n this.AssociatedObject.HorizontalAlignment = HorizontalAlignment.Stretch;\n this.AssociatedObject.Width = double.NaN;\n }\n }\n\n if (!double.IsInfinity(this.AssociatedObject.MaxHeight))\n {\n if (this.AssociatedObject.MaxHeight < newHeight)\n {\n this.AssociatedObject.VerticalAlignment = VerticalAlignment.Top;\n this.AssociatedObject.Height = this.AssociatedObject.MaxHeight;\n }\n else\n {\n this.AssociatedObject.VerticalAlignment = VerticalAlignment.Stretch;\n this.AssociatedObject.Height = double.NaN;\n }\n }\n }\n}\n</code></pre>\n<p>Then you can use it like so:</p>\n<pre><code><Grid>\n <Grid.ColumnDefinitions>\n <ColumnDefinition Width="Auto" />\n <ColumnDefinition />\n </Grid.ColumnDefinitions>\n\n <TextBlock Grid.Column="0" Text="Label" />\n <TextBox Grid.Column="1" MaxWidth="600">\n <i:Interaction.Behaviors> \n <cbh:StretchMaxWidthBehavior/>\n </i:Interaction.Behaviors>\n </TextBox>\n</Grid>\n</code></pre>\n<p>Note: don't forget to use the <code>System.Windows.Interactivity</code> namespace to use the behavior.</p>\n"
},
{
"answer_id": 58641460,
"author": "maxp",
"author_id": 35026,
"author_profile": "https://Stackoverflow.com/users/35026",
"pm_score": 2,
"selected": false,
"text": "<p>Functionally similar to the accepted answer, but doesn't require the parent element to be specified:</p>\n\n<pre><code><TextBox\n Width=\"{Binding ActualWidth, RelativeSource={RelativeSource Mode=FindAncestor, AncestorType={x:Type FrameworkElement}}}\"\n MaxWidth=\"500\"\n HorizontalAlignment=\"Left\" />\n</code></pre>\n"
},
{
"answer_id": 62392131,
"author": "sparedev",
"author_id": 11141718,
"author_profile": "https://Stackoverflow.com/users/11141718",
"pm_score": 0,
"selected": false,
"text": "<p>In my case I had to put textbox into a stack panel in order to stretch textbox on left side. \nThanks to previous post.\nJust for an example I did set a background color to see what’s happens when window size is changing.</p>\n\n<pre><code><StackPanel Name=\"JustContainer\" VerticalAlignment=\"Center\" HorizontalAlignment=\"Stretch\" Background=\"BlueViolet\" >\n <TextBox \n Name=\"Input\" Text=\"Hello World\" \n MaxWidth=\"300\"\n HorizontalAlignment=\"Right\"\n Width=\"{Binding ActualWidth, RelativeSource={RelativeSource Mode=FindAncestor, AncestorType={x:Type FrameworkElement}}}\">\n </TextBox>\n</StackPanel>\n</code></pre>\n"
},
{
"answer_id": 74678187,
"author": "mike",
"author_id": 4247806,
"author_profile": "https://Stackoverflow.com/users/4247806",
"pm_score": 0,
"selected": false,
"text": "<p>These answers didn't work for me, because I needed a <code>TextBox</code> to stretch (i.e. consume all available space) until it reaches it's <code>MaxWidth</code> and, if more space is available, align to the right.</p>\n<p>I created this simple control that works along the lines of Y C's answer, but doesn't require <code>System.Windows.Interactivity</code>:</p>\n<pre><code>public class StretchAlignmentPanel : ContentControl\n{\n public StretchAlignmentPanel()\n {\n this.SizeChanged += StretchAlignmentPanel_SizeChanged;\n }\n\n public static readonly DependencyProperty HorizontalFallbackAlignmentProperty = DependencyProperty.Register(\n nameof(HorizontalFallbackAlignment), typeof(HorizontalAlignment), typeof(StretchAlignmentPanel), new PropertyMetadata(HorizontalAlignment.Stretch));\n\n public HorizontalAlignment HorizontalFallbackAlignment\n {\n get { return (HorizontalAlignment)GetValue(HorizontalFallbackAlignmentProperty); }\n set { SetValue(HorizontalFallbackAlignmentProperty, value); }\n }\n\n public static readonly DependencyProperty VerticalFallbackAlignmentProperty = DependencyProperty.Register(\n nameof(VerticalFallbackAlignment), typeof(VerticalAlignment), typeof(StretchAlignmentPanel), new PropertyMetadata(VerticalAlignment.Stretch));\n\n public VerticalAlignment VerticalFallbackAlignment\n {\n get { return (VerticalAlignment)GetValue(VerticalFallbackAlignmentProperty); }\n set { SetValue(VerticalFallbackAlignmentProperty, value); }\n }\n\n private void StretchAlignmentPanel_SizeChanged(object sender, System.Windows.SizeChangedEventArgs e)\n {\n var fe = this.Content as FrameworkElement;\n if (fe == null) return;\n \n if(e.WidthChanged) applyHorizontalAlignment(fe);\n if(e.HeightChanged) applyVerticalAlignment(fe);\n }\n\n private void applyHorizontalAlignment(FrameworkElement fe)\n {\n if (HorizontalFallbackAlignment == HorizontalAlignment.Stretch) return;\n\n if (this.ActualWidth > fe.MaxWidth)\n {\n fe.HorizontalAlignment = HorizontalFallbackAlignment;\n fe.Width = fe.MaxWidth;\n }\n else\n {\n fe.HorizontalAlignment = HorizontalAlignment.Stretch;\n fe.Width = double.NaN;\n }\n }\n\n private void applyVerticalAlignment(FrameworkElement fe)\n {\n if (VerticalFallbackAlignment == VerticalAlignment.Stretch) return;\n\n if (this.ActualHeight > fe.MaxHeight)\n {\n fe.VerticalAlignment = VerticalFallbackAlignment;\n fe.Height= fe.MaxHeight;\n }\n else\n {\n fe.VerticalAlignment = VerticalAlignment.Stretch;\n fe.Height= double.NaN;\n }\n }\n}\n</code></pre>\n<p>It can be used like this:</p>\n<pre><code><controls:StretchAlignmentPanel HorizontalFallbackAlignment="Right">\n <TextBox MaxWidth="200" MinWidth="100" Text="Example"/>\n</controls:StretchAlignmentPanel>\n</code></pre>\n"
}
] |
2008/11/11
|
[
"https://Stackoverflow.com/questions/280331",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9045/"
] |
This seems like it should be easy but I'm stumped. In WPF, I'd like a TextBox that stretches to the width of it's parent, but only to a maximum width. The problem is that I want it to be left justified within its parent. To get it to stretch you have to use HorizontalAlignment="Stretch", but then the result is centered. I've experimented with HorizontalContentAlignment, but it doesn't seem to do anything.
How do I get this blue text box to grow with the size of the window, have a maximum width of 200 pixels, and be left justified?
```
<Page
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml">
<StackPanel>
<TextBox Background="Azure" Text="Hello" HorizontalAlignment="Stretch" MaxWidth="200" />
</StackPanel>
</Page>
```
What's the trick?
|
You can set `HorizontalAlignment` to Left, set your `MaxWidth` and then bind `Width` to the `ActualWidth` of the parent element:
```
<Page
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml">
<StackPanel Name="Container">
<TextBox Background="Azure"
Width="{Binding ElementName=Container,Path=ActualWidth}"
Text="Hello" HorizontalAlignment="Left" MaxWidth="200" />
</StackPanel>
</Page>
```
|
280,345 |
<p>I'm trying to start <code>iexplore.exe</code> let it run for 5 seconds and then close it again.</p>
<p><code>iexplore</code> opens just fine however it doesn't close when I call the PostThreadMessage.
Can anyone see what I'm doing wrong? Here is my code:</p>
<pre><code>CString IEPath = "C:\\Program Files\\Internet Explorer\\IEXPLORE.EXE";//GetIEPath();
//IEPath += ' ' + url;
std::string strCommand((LPCTSTR)IEPath);
PROCESS_INFORMATION procinfo;
STARTUPINFO startupinfo;
GetStartupInfo(&startupinfo);
CreateProcess(
NULL,
(char *)strCommand.c_str(),// name of executable module
NULL, // lpProcessAttributes
NULL, // lpThreadAttributes
false, // handle inheritance option
CREATE_SHARED_WOW_VDM, // creation flags
NULL, // new environment block
NULL, // current directory name
&startupinfo, // startup information
&procinfo // process information
);
Sleep(5000);
::PostThreadMessage(procinfo.dwThreadId, WM_QUIT, 0, 0); //<---Dosent Close internet explorer!
</code></pre>
<p>Anyone have an idea of what I'm doing wrong? Or is there better way what to do the trick?</p>
|
[
{
"answer_id": 280364,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 3,
"selected": true,
"text": "<p>if you can enumerate the windows on the desktop and send a WM_CLOSE to the IE window , it might work .. you can use the spy programme to get the window class of the IE window </p>\n"
},
{
"answer_id": 280371,
"author": "1800 INFORMATION",
"author_id": 3146,
"author_profile": "https://Stackoverflow.com/users/3146",
"pm_score": 1,
"selected": false,
"text": "<p>What is the return value from the PostThreadMessage call? That might give a clue.</p>\n"
},
{
"answer_id": 280377,
"author": "schnaader",
"author_id": 34065,
"author_profile": "https://Stackoverflow.com/users/34065",
"pm_score": 1,
"selected": false,
"text": "<p>For me, this works perfect:</p>\n\n<pre><code>TerminateProcess(procinfo.hProcess, 0);\n</code></pre>\n"
},
{
"answer_id": 280381,
"author": "Heng-Cheong Leong",
"author_id": 6904,
"author_profile": "https://Stackoverflow.com/users/6904",
"pm_score": 0,
"selected": false,
"text": "<p>I don't have an answer specifically why PostThreadMessage didn't work. But, perhaps if you elaborate on why you want to do this, there is a better solution?</p>\n\n<p>For example, if you just want to show a web page for 5 seconds, you can create and show your own window with an embedded Internet Explorer ActiveX control. You'll be also able to add a sink to detect when the web page is loaded in the ActiveX control, so that you start your 5-second counter only after the web page is loaded and displayed.</p>\n"
},
{
"answer_id": 280461,
"author": "MSalters",
"author_id": 15416,
"author_profile": "https://Stackoverflow.com/users/15416",
"pm_score": 1,
"selected": false,
"text": "<p>Try sending WM_CLOSE to the main (top-evel) window. That's equivalent to the normal Alt-F4 exit.</p>\n"
},
{
"answer_id": 280766,
"author": "CruelIO",
"author_id": 36476,
"author_profile": "https://Stackoverflow.com/users/36476",
"pm_score": 0,
"selected": false,
"text": "<p>I ended up doing an enumeration of the windows (As serval of you mentioned i should do)\nI was inspired of <a href=\"http://simplesamples.info/Windows/EnumWindows.php\" rel=\"nofollow noreferrer\">http://simplesamples.info/Windows/EnumWindows.php</a>.</p>\n"
},
{
"answer_id": 281155,
"author": "John Dibling",
"author_id": 241536,
"author_profile": "https://Stackoverflow.com/users/241536",
"pm_score": 0,
"selected": false,
"text": "<p>Don't use PostThreadMessage(), which sends a message to a specific thread in the target process instead of the process' Windows Message Pump. Use PostMessage() or SendMessage() instead, which place the message in the target process's Windows Message Pump -- which is exactly what you want.</p>\n"
},
{
"answer_id": 292410,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 0,
"selected": false,
"text": "<p>No, never use SendMessage() (basic win32 rule)\nDon't use EnmWindows() (horrible)</p>\n"
}
] |
2008/11/11
|
[
"https://Stackoverflow.com/questions/280345",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/36476/"
] |
I'm trying to start `iexplore.exe` let it run for 5 seconds and then close it again.
`iexplore` opens just fine however it doesn't close when I call the PostThreadMessage.
Can anyone see what I'm doing wrong? Here is my code:
```
CString IEPath = "C:\\Program Files\\Internet Explorer\\IEXPLORE.EXE";//GetIEPath();
//IEPath += ' ' + url;
std::string strCommand((LPCTSTR)IEPath);
PROCESS_INFORMATION procinfo;
STARTUPINFO startupinfo;
GetStartupInfo(&startupinfo);
CreateProcess(
NULL,
(char *)strCommand.c_str(),// name of executable module
NULL, // lpProcessAttributes
NULL, // lpThreadAttributes
false, // handle inheritance option
CREATE_SHARED_WOW_VDM, // creation flags
NULL, // new environment block
NULL, // current directory name
&startupinfo, // startup information
&procinfo // process information
);
Sleep(5000);
::PostThreadMessage(procinfo.dwThreadId, WM_QUIT, 0, 0); //<---Dosent Close internet explorer!
```
Anyone have an idea of what I'm doing wrong? Or is there better way what to do the trick?
|
if you can enumerate the windows on the desktop and send a WM\_CLOSE to the IE window , it might work .. you can use the spy programme to get the window class of the IE window
|
280,347 |
<p>How to convert Unicode string into a utf-8 or utf-16 string?
My VS2005 project is using Unicode char set, while sqlite in cpp provide </p>
<pre><code>int sqlite3_open(
const char *filename, /* Database filename (UTF-8) */
sqlite3 **ppDb /* OUT: SQLite db handle */
);
int sqlite3_open16(
const void *filename, /* Database filename (UTF-16) */
sqlite3 **ppDb /* OUT: SQLite db handle */
);
</code></pre>
<p>for opening a folder.
How can I convert string, CString, or wstring into UTF-8 or UTF-16 charset?</p>
<p>Thanks very much!</p>
|
[
{
"answer_id": 280358,
"author": "1800 INFORMATION",
"author_id": 3146,
"author_profile": "https://Stackoverflow.com/users/3146",
"pm_score": 3,
"selected": false,
"text": "<p>Use the <a href=\"http://msdn.microsoft.com/en-us/library/ms776420(VS.85).aspx\" rel=\"noreferrer\">WideCharToMultiByte</a> function. Specify <code>CP_UTF8</code> for the <code>CodePage</code> parameter.</p>\n\n<pre><code>CHAR buf[256]; // or whatever\nWideCharToMultiByte(\n CP_UTF8, \n 0, \n StringToConvert, // the string you have\n -1, // length of the string - set -1 to indicate it is null terminated\n buf, // output\n __countof(buf), // size of the buffer in bytes - if you leave it zero the return value is the length required for the output buffer\n NULL, \n NULL\n);\n</code></pre>\n\n<p>Also, the default encoding for unicode apps in windows is UTF-16LE, so you might not need to perform any translation and just use the second version <code>sqlite3_open16</code>.</p>\n"
},
{
"answer_id": 280360,
"author": "Johannes Schaub - litb",
"author_id": 34509,
"author_profile": "https://Stackoverflow.com/users/34509",
"pm_score": 0,
"selected": false,
"text": "<p>utf-8 and utf-16 are both \"unicode\" character encodings. What you probably talk about is utf-32 which is a fixed-size character encoding. Maybe searching for </p>\n\n<p><code>\"Convert utf-32 into utf-8 or utf-16\"</code></p>\n\n<p>provides you some results or other papers on this.</p>\n"
},
{
"answer_id": 280365,
"author": "jalf",
"author_id": 33213,
"author_profile": "https://Stackoverflow.com/users/33213",
"pm_score": 2,
"selected": false,
"text": "<p>All the C++ string types are charset neutral. They just settle on a character width, and make no further assumptions. A wstring uses 16-bit characters in Windows, corresponding roughly to utf-16, but it still depends on what you store in the thread. The wstring doesn't in any way enforce that the data you put in it must be valid utf16. Windows uses utf16 when UNICODE is defined though, so most likely your strings are already utf16, and you don't need to do anything.</p>\n\n<p>A few others have suggested using the WideCharToMultiByte function, which is (one of) the way(s) to go to convert utf16 to utf8. But since sqlite can handle utf16, that shouldn't be necessary.</p>\n"
},
{
"answer_id": 280443,
"author": "Serge Wautier",
"author_id": 12379,
"author_profile": "https://Stackoverflow.com/users/12379",
"pm_score": 4,
"selected": true,
"text": "<p>Short answer: </p>\n\n<p>No conversion required if you use Unicode strings such as CString or wstring. Use sqlite3_open16().\nYou will have to make sure you pass a WCHAR pointer (casted to <code>void *</code>. Seems lame! Even if this lib is cross platform, I guess they could have defined a wide char type that depends on the platform and is less unfriendly than a <code>void *</code>) to the API. Such as for a CString: <code>(void*)(LPCWSTR)strFilename</code></p>\n\n<p>The longer answer:</p>\n\n<p>You don't have a Unicode string that you want to convert to UTF8 or UTF16. You have a Unicode string represented in your program using a given encoding: Unicode is not a binary representation per se. Encodings say how the Unicode code points (numerical values) are represented in memory (binary layout of the number). UTF8 and UTF16 are the most widely used encodings. They are very different though.</p>\n\n<p>When a VS project says \"Unicode charset\", it actually means \"characters are encoded as UTF16\". Therefore, you can use sqlite3_open16() directly. No conversion required. Characters are stored in WCHAR type (as opposed to <code>char</code>) which takes 16 bits (Fallsback on standard C type <code>wchar_t</code>, which takes 16 bits on Win32. Might be different on other platforms. Thanks for the correction, Checkers).</p>\n\n<p>There's one more detail that you might want to pay attention to: UTF16 exists in 2 flavors: Big Endian and Little Endian. That's the byte ordering of these 16 bits. The function prototype you give for UTF16 doesn't say which ordering is used. But you're pretty safe assuming that sqlite uses the same endian-ness as Windows (Little Endian IIRC. I know the order but have always had problem with the names :-) ).</p>\n\n<p>EDIT: Answer to comment by Checkers:</p>\n\n<p>UTF16 uses 16 bits <em>code units</em>. Under Win32 (and <em>only</em> on Win32), <code>wchar_t</code> is used for such storage unit. The trick is that some Unicode characters require a sequence of 2 such 16-bits code units. They are called Surrogate Pairs. </p>\n\n<p>The same way an UTF8 represents 1 character using a 1 to 4 bytes sequence. Yet UTF8 are used with the <code>char</code> type.</p>\n"
},
{
"answer_id": 25456096,
"author": "Helstrom",
"author_id": 3739445,
"author_profile": "https://Stackoverflow.com/users/3739445",
"pm_score": 0,
"selected": false,
"text": "<p>The simplest way to do this is to use CStringA. The CString class is a typedef for either CStringA (ASCII version) or CStringW (wide char version). Both of these classes have constructors to convert string types. I typically use:</p>\n\n<pre><code>sqlite3_open(CStringA(L\"MyWideCharFileName\"), ...);\n</code></pre>\n"
}
] |
2008/11/11
|
[
"https://Stackoverflow.com/questions/280347",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/25749/"
] |
How to convert Unicode string into a utf-8 or utf-16 string?
My VS2005 project is using Unicode char set, while sqlite in cpp provide
```
int sqlite3_open(
const char *filename, /* Database filename (UTF-8) */
sqlite3 **ppDb /* OUT: SQLite db handle */
);
int sqlite3_open16(
const void *filename, /* Database filename (UTF-16) */
sqlite3 **ppDb /* OUT: SQLite db handle */
);
```
for opening a folder.
How can I convert string, CString, or wstring into UTF-8 or UTF-16 charset?
Thanks very much!
|
Short answer:
No conversion required if you use Unicode strings such as CString or wstring. Use sqlite3\_open16().
You will have to make sure you pass a WCHAR pointer (casted to `void *`. Seems lame! Even if this lib is cross platform, I guess they could have defined a wide char type that depends on the platform and is less unfriendly than a `void *`) to the API. Such as for a CString: `(void*)(LPCWSTR)strFilename`
The longer answer:
You don't have a Unicode string that you want to convert to UTF8 or UTF16. You have a Unicode string represented in your program using a given encoding: Unicode is not a binary representation per se. Encodings say how the Unicode code points (numerical values) are represented in memory (binary layout of the number). UTF8 and UTF16 are the most widely used encodings. They are very different though.
When a VS project says "Unicode charset", it actually means "characters are encoded as UTF16". Therefore, you can use sqlite3\_open16() directly. No conversion required. Characters are stored in WCHAR type (as opposed to `char`) which takes 16 bits (Fallsback on standard C type `wchar_t`, which takes 16 bits on Win32. Might be different on other platforms. Thanks for the correction, Checkers).
There's one more detail that you might want to pay attention to: UTF16 exists in 2 flavors: Big Endian and Little Endian. That's the byte ordering of these 16 bits. The function prototype you give for UTF16 doesn't say which ordering is used. But you're pretty safe assuming that sqlite uses the same endian-ness as Windows (Little Endian IIRC. I know the order but have always had problem with the names :-) ).
EDIT: Answer to comment by Checkers:
UTF16 uses 16 bits *code units*. Under Win32 (and *only* on Win32), `wchar_t` is used for such storage unit. The trick is that some Unicode characters require a sequence of 2 such 16-bits code units. They are called Surrogate Pairs.
The same way an UTF8 represents 1 character using a 1 to 4 bytes sequence. Yet UTF8 are used with the `char` type.
|
280,356 |
<p>In my webpage, I want the website to greet the user, but the username is surrounded by 'single quotations'. Since this isn't to prevent MySQL injection, i just want to remove quotes around my name on the display page.</p>
<p>Ex: Welcome 'user'!
I'm trying to find the way where i can strip the quotations around the user and have it display on the example below.</p>
<p>Ex: Welcome user!</p>
<p>The only line of code that I can think relating is this:</p>
<p>$login = $_SESSION['login'];</p>
<p>Does anyone know how to strip single lines quotes?</p>
|
[
{
"answer_id": 280366,
"author": "davil",
"author_id": 22592,
"author_profile": "https://Stackoverflow.com/users/22592",
"pm_score": 1,
"selected": false,
"text": "<p>I think the easiest way would be to use the trim() function. It usually trims whitespace characters, but you may pass it a string containing characters you want to be removed:</p>\n\n<pre><code>echo 'Welcome ' . trim($login, \"'\");\n</code></pre>\n\n<p>See <a href=\"http://php.net/trim\" rel=\"nofollow noreferrer\">http://php.net/trim</a></p>\n"
},
{
"answer_id": 280368,
"author": "Stefan Gehrig",
"author_id": 11354,
"author_profile": "https://Stackoverflow.com/users/11354",
"pm_score": 5,
"selected": true,
"text": "<p>If you're sure that the first and last characters of <code>$login</code> are always a <code>'</code> you can use <a href=\"http://de3.php.net/manual/en/function.substr.php\" rel=\"noreferrer\"><code>substr()</code></a> to do something like</p>\n\n<pre><code>$login = substr($_SESSION['login'], 1, -1); // example 1\n</code></pre>\n\n<p>You can strip all <code>'</code> from the string with <a href=\"http://de3.php.net/manual/en/function.str-replace.php\" rel=\"noreferrer\"><code>str_replace()</code></a></p>\n\n<pre><code>$login = str_replace(\"'\", '', $_SESSION['login']); // example 2\n</code></pre>\n\n<p>Or you can use the <a href=\"http://de3.php.net/manual/en/function.trim.php\" rel=\"noreferrer\"><code>trim()</code></a> function, which is in fact the same as example 1:</p>\n\n<pre><code>$login = trim($_SESSION['login'], \"'\"); // example 3\n</code></pre>\n\n<p>My personal favorite is example 3, because it can easily be extended to strip away both quote types: </p>\n\n<pre><code>$login = trim($_SESSION['login'], \"'\\\"\"); // example 4\n</code></pre>\n"
}
] |
2008/11/11
|
[
"https://Stackoverflow.com/questions/280356",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] |
In my webpage, I want the website to greet the user, but the username is surrounded by 'single quotations'. Since this isn't to prevent MySQL injection, i just want to remove quotes around my name on the display page.
Ex: Welcome 'user'!
I'm trying to find the way where i can strip the quotations around the user and have it display on the example below.
Ex: Welcome user!
The only line of code that I can think relating is this:
$login = $\_SESSION['login'];
Does anyone know how to strip single lines quotes?
|
If you're sure that the first and last characters of `$login` are always a `'` you can use [`substr()`](http://de3.php.net/manual/en/function.substr.php) to do something like
```
$login = substr($_SESSION['login'], 1, -1); // example 1
```
You can strip all `'` from the string with [`str_replace()`](http://de3.php.net/manual/en/function.str-replace.php)
```
$login = str_replace("'", '', $_SESSION['login']); // example 2
```
Or you can use the [`trim()`](http://de3.php.net/manual/en/function.trim.php) function, which is in fact the same as example 1:
```
$login = trim($_SESSION['login'], "'"); // example 3
```
My personal favorite is example 3, because it can easily be extended to strip away both quote types:
```
$login = trim($_SESSION['login'], "'\""); // example 4
```
|
280,378 |
<p>I read a little of the help for my advanced installer 6.5.1 and couldn't find a way to change the version string except by hand.</p>
|
[
{
"answer_id": 280458,
"author": "Rob Stevenson-Leggett",
"author_id": 4950,
"author_profile": "https://Stackoverflow.com/users/4950",
"pm_score": 1,
"selected": false,
"text": "<p>The files for creating an MSI are usually in XML format, we've created a little tool that runs as part of our build process that goes and changes the build number manually, try openning the advanced installer file in notepad and look for the \"ProductVersion\" string.</p>\n\n<p>Cheers,\nRob.</p>\n"
},
{
"answer_id": 2076057,
"author": "Fred",
"author_id": 251983,
"author_profile": "https://Stackoverflow.com/users/251983",
"pm_score": 3,
"selected": false,
"text": "<p>Here is a snippet from one of our push scripts. Rob, maybe you'll find this useful too- Advanced installer provides the ability to set the ProductVersion of your installation package based on an existing compiled EXE. We use a custom build task in TFS to increment our build number and set our AssemblyInfo.cs files, then with the resulting main app EXE, we can do this:</p>\n\n<pre><code>:COMPILE_AIP\n\nSET AIP_DIR=\"C:\\Program Files\\Caphyon\\Advanced Installer 7.1.3\"\n\nECHO Advanced Installer Directiry: %AIP_DIR%\n\nECHO.\nECHO //////////////////////////\nECHO //Compiling AIP Files...//\nECHO //////////////////////////\nECHO.\n\nECHO Setting version on all installers...\nECHO Setting version on all installers... >> %DESTINATION_APP_DIR%_push_script_output.txt\n%AIP_DIR%\\advancedinstaller /edit \"<pathtoaipfile>\\installproject.aip\" /SetVersion -fromfile <path to exe defining app version>\n IF NOT ERRORLEVEL 0 GOTO ERROR_HANDLER\n</code></pre>\n\n<p>Hope this helps-</p>\n"
},
{
"answer_id": 7360834,
"author": "EddieBytes",
"author_id": 911325,
"author_profile": "https://Stackoverflow.com/users/911325",
"pm_score": 3,
"selected": false,
"text": "<p>You can use the <a href=\"http://www.advancedinstaller.com/user-guide/set-version.html\" rel=\"noreferrer\">/SetVersion</a> switch to set the product version from the command line. Useful in automatic builds.</p>\n"
},
{
"answer_id": 19175123,
"author": "mteodor",
"author_id": 1437882,
"author_profile": "https://Stackoverflow.com/users/1437882",
"pm_score": 1,
"selected": false,
"text": "<p>Starting with Advanced Installer v9.8 it is much easier to retrieve the <em>Product Version</em> from a file: right-click in the edit box and select the “Set version from file...” menu item on the <a href=\"http://www.advancedinstaller.com/user-guide/product-details-tab.html\" rel=\"nofollow\">Product Details</a> tab. This will keep in sync the product version of the package with the version of the selected file, which can be for example your main application executable.</p>\n\n<p>Cheers</p>\n"
}
] |
2008/11/11
|
[
"https://Stackoverflow.com/questions/280378",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/30324/"
] |
I read a little of the help for my advanced installer 6.5.1 and couldn't find a way to change the version string except by hand.
|
Here is a snippet from one of our push scripts. Rob, maybe you'll find this useful too- Advanced installer provides the ability to set the ProductVersion of your installation package based on an existing compiled EXE. We use a custom build task in TFS to increment our build number and set our AssemblyInfo.cs files, then with the resulting main app EXE, we can do this:
```
:COMPILE_AIP
SET AIP_DIR="C:\Program Files\Caphyon\Advanced Installer 7.1.3"
ECHO Advanced Installer Directiry: %AIP_DIR%
ECHO.
ECHO //////////////////////////
ECHO //Compiling AIP Files...//
ECHO //////////////////////////
ECHO.
ECHO Setting version on all installers...
ECHO Setting version on all installers... >> %DESTINATION_APP_DIR%_push_script_output.txt
%AIP_DIR%\advancedinstaller /edit "<pathtoaipfile>\installproject.aip" /SetVersion -fromfile <path to exe defining app version>
IF NOT ERRORLEVEL 0 GOTO ERROR_HANDLER
```
Hope this helps-
|
280,385 |
<p>Let's say we have a method signature like </p>
<pre><code>public static function explodeDn($dn, array &$keys = null, array &$vals = null,
$caseFold = self::ATTR_CASEFOLD_NONE)
</code></pre>
<p>we can easily call the method by omitting all parameters after <code>$dn</code>:</p>
<pre><code>$dn=Zend_Ldap_Dn::explodeDn('CN=Alice Baker,CN=Users,DC=example,DC=com');
</code></pre>
<p>We can also call the method with 3 parameters:</p>
<pre><code>$dn=Zend_Ldap_Dn::explodeDn('CN=Alice Baker,CN=Users,DC=example,DC=com', $k, $v);
</code></pre>
<p>and with 4 parameters:</p>
<pre><code>$dn=Zend_Ldap_Dn::explodeDn('CN=Alice Baker,CN=Users,DC=example,DC=com', $k, $v,
Zend_Ldap_Dn::ATTR_CASEFOLD_UPPER);
</code></pre>
<p>But why is it impossible to call the method with the following parameter combination for example:</p>
<pre><code>$dn=Zend_Ldap_Dn::explodeDn('CN=Alice Baker,CN=Users,DC=example,DC=com', $k, null,
Zend_Ldap_Dn::ATTR_CASEFOLD_UPPER);
$dn=Zend_Ldap_Dn::explodeDn('CN=Alice Baker,CN=Users,DC=example,DC=com', null, $v);
</code></pre>
<p>What's the difference between passing <code>null</code> to the method and relying on the default value? Is this constraint written in the manual? Can it be circumvented?</p>
|
[
{
"answer_id": 280397,
"author": "Tomalak",
"author_id": 18771,
"author_profile": "https://Stackoverflow.com/users/18771",
"pm_score": 6,
"selected": true,
"text": "<p>It's because you can't have a reference to null.</p>\n\n<p>You can have a reference to a variable that contains null - that is exactly what the default value does. Or you can pass in null as a literal value - but since you want an out parameter this is not possible here.</p>\n"
},
{
"answer_id": 280404,
"author": "Stefan Gehrig",
"author_id": 11354,
"author_profile": "https://Stackoverflow.com/users/11354",
"pm_score": 1,
"selected": false,
"text": "<p>Just to confirm what <a href=\"https://stackoverflow.com/users/18771/tomalak\">Tomalak</a> stated <a href=\"https://stackoverflow.com/questions/280385/php-by-reference-parameters-and-default-null#280397\">here</a>:</p>\n\n<p>The following works:</p>\n\n<pre><code>$k=array();\n$v=null;\n$dn=Zend_Ldap_Dn::explodeDn('CN=Alice Baker,CN=Users,DC=example,DC=com', $k, $v, \n Zend_Ldap_Dn::ATTR_CASEFOLD_UPPER);\n</code></pre>\n\n<p>Not nice - but the explanation is clear and comprehensible.</p>\n"
},
{
"answer_id": 3632620,
"author": "josh",
"author_id": 438552,
"author_profile": "https://Stackoverflow.com/users/438552",
"pm_score": 2,
"selected": false,
"text": "<p>@ Tomalak</p>\n\n<p>Actually, the default value creates a variable without any reference involved. Which is something you simply cannot kick off when you pass something.</p>\n\n<p>What i find to illustrate the reasons is the following example (which i did not test):</p>\n\n<pre><code>function foo (&$ref = NULL) {\n $args = func_get_args();\n echo var_export($ref, TRUE).' - '.var_export($args, TRUE);\n}\n$bar = NULL;\nfoo(); // NULL - array()\nfoo($bar); // NULL - array(0 => NULL)\n</code></pre>\n\n<p>In my opinion, PHP should offer a way to NOT pass certain parameters, like with<br>\n<code>foo($p1, , , $p4);</code> or similar syntax instead of passing NULL.<br>\nBut it doesn't, so you have to use dummy variables.</p>\n"
},
{
"answer_id": 4233438,
"author": "Rafa",
"author_id": 279564,
"author_profile": "https://Stackoverflow.com/users/279564",
"pm_score": 3,
"selected": false,
"text": "<p>I just found out this myself, and I'm quite in shock o_O!</p>\n\n<p>This is what the <a href=\"http://www.php.net/manual/en/functions.arguments.php#functions.arguments.default\" rel=\"nofollow\">PHP documentation</a> says:</p>\n\n<pre><code>function makecoffee($type = \"cappuccino\")\n{\n return \"Making a cup of $type.\\n\";\n}\necho makecoffee(); // returns \"Making a cup of cappuccino.\"\necho makecoffee(null); // returns \"Making a cup of .\"\necho makecoffee(\"espresso\"); // returns \"Making a cup of espresso.\"\n</code></pre>\n\n<p>I would have expected <code>makecoffee(null)</code> to return \"Making a cup of cappuccino.\".\nOne work-around I have used is to check inside the function if the argument is null:</p>\n\n<pre><code>function makecoffee($type = null)\n{\n if (is_null($type)){ \n $type = \"capuccino\";\n }\n return \"Making a cup of $type.\\n\";\n}\n</code></pre>\n\n<p>Now <code>makecoffee(null)</code> returns \"Making a cup of cappuccino.\"</p>\n\n<p>(I realize this doesn't actually solve the Zend-related question, but it might be useful to some...)</p>\n"
},
{
"answer_id": 9716982,
"author": "Szczepan Hołyszewski",
"author_id": 1271158,
"author_profile": "https://Stackoverflow.com/users/1271158",
"pm_score": 4,
"selected": false,
"text": "<p>While you must create a dummy variable for by-ref arguments if you want to pass NULL explicitly, you don't have to create that variable on a separate line. You can use an assignment expression like $dummy=NULL directly as a function argument:</p>\n\n<pre><code>function foo (&$ref = NULL) {\n\n if (is_null($ref)) $ref=\"bar\";\n echo \"$ref\\n\"; \n}\n\nfoo($dummy = NULL); //this works!\n</code></pre>\n"
},
{
"answer_id": 28179870,
"author": "Chris Middleton",
"author_id": 2407870,
"author_profile": "https://Stackoverflow.com/users/2407870",
"pm_score": 1,
"selected": false,
"text": "<p>As @aschmecher pointed out in a comment on \n<a href=\"https://stackoverflow.com/a/9716982/2407870\">@Szczepan's answer here</a>, doing <code>func($var = null)</code> generates a strict standards notice.</p>\n\n<p><strong>One solution</strong></p>\n\n<p>Here's a method that does not generate any such warnings:</p>\n\n<pre class=\"lang-php prettyprint-override\"><code><?php\nerror_reporting(E_ALL | E_STRICT);\n\nfunction doIt(&$x = null) {\n if($x !== null) echo \"x not null: $x\\n\";\n $x = 2;\n}\n\nfunction &dummyRef() {\n $dummyRef = null;\n return $dummyRef;\n}\n\ndoIt(dummyRef());\n\ndoIt(dummyRef());\n</code></pre>\n\n<p><strong>Explanation</strong></p>\n\n<p>In place of passing in a variable, we pass in the result of a function returning a reference. The second call to <code>doIt(dummy())</code> is to verify that the reference <code>$dummy</code> value is not persisting between calls. This contrasts with creating a variable explicitly, where one needs to remember to clear any accumulated value:</p>\n\n<pre class=\"lang-php prettyprint-override\"><code>$dummyRef = null;\ndoIt($dummyRef);\ndoIt($dummyRef); // second call would print 'x not null: 2'\n</code></pre>\n\n<p><strong>Application</strong></p>\n\n<p>So in the OP's example, it would be:</p>\n\n<pre><code>$dn = Zend_Ldap_Dn::explodeDn(\n 'CN=Alice Baker,CN=Users,DC=example,DC=com',\n $k,\n dummyRef(),\n Zend_Ldap_Dn::ATTR_CASEFOLD_UPPER\n);\n</code></pre>\n\n<p><strong>Additional considerations</strong></p>\n\n<p>One thing I might worry is whether this method creates a memory leak. The following test shows that it doesn't:</p>\n\n<pre><code><?php\nfunction doItObj(&$x = null) {\n if(gettype($x) !== \"object\") echo \"x not null: $x\\n\";\n $x = 2;\n}\n\nfunction &dummyObjRef() {\n $dummyObjRef = new StdClass();\n return $dummyObjRef;\n}\n\necho \"memory before: \" . memory_get_usage(true) . \"\\n\";\n\nfor($i = 0; $i < 1000000; $i++) {\n doItObj(dummyObjRef());\n}\n\necho \"memory after: \" . memory_get_usage(true) . \"\\n\";\n\necho \"\\n$i\\n\";\n</code></pre>\n\n<p>On my system (using PHP 5.6.4), both calls to memory_get_usage showed ~ 262 KB.</p>\n"
}
] |
2008/11/11
|
[
"https://Stackoverflow.com/questions/280385",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11354/"
] |
Let's say we have a method signature like
```
public static function explodeDn($dn, array &$keys = null, array &$vals = null,
$caseFold = self::ATTR_CASEFOLD_NONE)
```
we can easily call the method by omitting all parameters after `$dn`:
```
$dn=Zend_Ldap_Dn::explodeDn('CN=Alice Baker,CN=Users,DC=example,DC=com');
```
We can also call the method with 3 parameters:
```
$dn=Zend_Ldap_Dn::explodeDn('CN=Alice Baker,CN=Users,DC=example,DC=com', $k, $v);
```
and with 4 parameters:
```
$dn=Zend_Ldap_Dn::explodeDn('CN=Alice Baker,CN=Users,DC=example,DC=com', $k, $v,
Zend_Ldap_Dn::ATTR_CASEFOLD_UPPER);
```
But why is it impossible to call the method with the following parameter combination for example:
```
$dn=Zend_Ldap_Dn::explodeDn('CN=Alice Baker,CN=Users,DC=example,DC=com', $k, null,
Zend_Ldap_Dn::ATTR_CASEFOLD_UPPER);
$dn=Zend_Ldap_Dn::explodeDn('CN=Alice Baker,CN=Users,DC=example,DC=com', null, $v);
```
What's the difference between passing `null` to the method and relying on the default value? Is this constraint written in the manual? Can it be circumvented?
|
It's because you can't have a reference to null.
You can have a reference to a variable that contains null - that is exactly what the default value does. Or you can pass in null as a literal value - but since you want an out parameter this is not possible here.
|
280,389 |
<pre><code>function main()
{
Hello();
}
function Hello()
{
// How do you find out the caller function is 'main'?
}
</code></pre>
<p>Is there a way to find out the call stack?</p>
|
[
{
"answer_id": 280396,
"author": "Greg Hewgill",
"author_id": 893,
"author_profile": "https://Stackoverflow.com/users/893",
"pm_score": 11,
"selected": true,
"text": "<p><strong>Note that this solution is deprecated and should no longer be used according to MDN documentation</strong></p>\n<p><a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function/caller\" rel=\"noreferrer\">https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function/caller</a></p>\n<hr />\n<pre><code>function Hello()\n{\n alert("caller is " + Hello.caller);\n}\n</code></pre>\n<p>Note that this feature is <strong>non-standard</strong>, from <a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function/caller\" rel=\"noreferrer\"><code>Function.caller</code></a>:</p>\n<blockquote>\n<p><strong>Non-standard</strong><br />\nThis feature is non-standard and is not on a standards track. Do not use it on production sites facing the Web: it will not work for every user. There may also be large incompatibilities between implementations and the behavior may change in the future.</p>\n</blockquote>\n<hr />\n<p>The following is the old answer from 2008, which is no longer supported in modern Javascript:</p>\n<pre><code>function Hello()\n{\n alert("caller is " + arguments.callee.caller.toString());\n}\n</code></pre>\n"
},
{
"answer_id": 280466,
"author": "Pablo Cabrera",
"author_id": 12540,
"author_profile": "https://Stackoverflow.com/users/12540",
"pm_score": 4,
"selected": false,
"text": "<p>It's safer to use <code>*arguments.callee.caller</code> since <code>arguments.caller</code> is <strong>deprecated</strong>...</p>\n"
},
{
"answer_id": 280510,
"author": "user15566",
"author_id": 15566,
"author_profile": "https://Stackoverflow.com/users/15566",
"pm_score": 4,
"selected": false,
"text": "<p>Try accessing this:</p>\n\n<pre><code>arguments.callee.caller.name\n</code></pre>\n"
},
{
"answer_id": 280598,
"author": "Shadow2531",
"author_id": 1697,
"author_profile": "https://Stackoverflow.com/users/1697",
"pm_score": 4,
"selected": false,
"text": "<pre><code>function Hello() {\n alert(Hello.caller);\n}\n</code></pre>\n"
},
{
"answer_id": 721516,
"author": "nourdine",
"author_id": 87624,
"author_profile": "https://Stackoverflow.com/users/87624",
"pm_score": 6,
"selected": false,
"text": "<p>To recap (and make it clearer) ...</p>\n\n<p>this code: </p>\n\n<pre><code>function Hello() {\n alert(\"caller is \" + arguments.callee.caller.toString());\n}\n</code></pre>\n\n<p>is equivalent to this: </p>\n\n<pre><code>function Hello() {\n alert(\"caller is \" + Hello.caller.toString());\n}\n</code></pre>\n\n<p>Clearly the first bit is more portable, since you can change the name of the function, say from \"Hello\" to \"Ciao\", and still get the whole thing to work.</p>\n\n<p>In the latter, in case you decide to refactor the name of the invoked function (Hello), you would have to change all its occurrences :( </p>\n"
},
{
"answer_id": 3789144,
"author": "Mariano Desanze",
"author_id": 146513,
"author_profile": "https://Stackoverflow.com/users/146513",
"pm_score": 7,
"selected": false,
"text": "<h2>StackTrace</h2>\n\n<p>You can find the entire stack trace using browser specific code. The good thing is <a href=\"http://eriwen.com/javascript/stacktrace-update/\" rel=\"noreferrer\">someone already made it</a>; here is the <a href=\"http://github.com/eriwen/javascript-stacktrace\" rel=\"noreferrer\">project code on GitHub</a>.</p>\n\n<p>But not all the news is good:</p>\n\n<ol>\n<li><p>It is really slow to get the stack trace so be careful (read <a href=\"http://webreflection.blogspot.com/2009/06/es5-arguments-and-callee-i-was-wrong.html\" rel=\"noreferrer\">this</a> for more).</p></li>\n<li><p>You will need to define function names for the stack trace to be legible. Because if you have code like this:</p>\n\n<pre><code>var Klass = function kls() {\n this.Hello = function() { alert(printStackTrace().join('\\n\\n')); };\n}\nnew Klass().Hello();\n</code></pre>\n\n<p>Google Chrome will alert <code>... kls.Hello ( ...</code> but most browsers will expect a function name just after the keyword <code>function</code> and will treat it as an anonymous function. An not even Chrome will be able to use the <code>Klass</code> name if you don't give the name <code>kls</code> to the function.</p>\n\n<p>And by the way, you can pass to the function printStackTrace the option <code>{guess: true}</code> but I didn't find any real improvement by doing that.</p></li>\n<li><p>Not all browsers give you the same information. That is, parameters, code column, etc.</p></li>\n</ol>\n\n<p><hr></p>\n\n<h2>Caller Function Name</h2>\n\n<p>By the way, if you only want the name of the caller function (in most browsers, but not IE) you can use:</p>\n\n<pre><code>arguments.callee.caller.name\n</code></pre>\n\n<p>But note that this name will be the one after the <code>function</code> keyword. I found no way (even on Google Chrome) to get more than that without getting the code of the whole function.</p>\n\n<p><hr></p>\n\n<h2>Caller Function Code</h2>\n\n<p>And summarizing the rest of the best answers (by Pablo Cabrera, nourdine, and Greg Hewgill). <strong>The only cross-browser and really safe thing you can use is:</strong></p>\n\n<pre><code>arguments.callee.caller.toString();\n</code></pre>\n\n<p>Which will show the <strong>code</strong> of the caller function. Sadly, that is not enough for me, and that is why I give you tips for the StackTrace and the caller function Name (although they are not cross-browser).</p>\n"
},
{
"answer_id": 4047670,
"author": "ale5000",
"author_id": 490687,
"author_profile": "https://Stackoverflow.com/users/490687",
"pm_score": 6,
"selected": false,
"text": "<p>You can get the full stacktrace:</p>\n\n<pre><code>arguments.callee.caller\narguments.callee.caller.caller\narguments.callee.caller.caller.caller\n</code></pre>\n\n<p>Until caller is <code>null</code>.</p>\n\n<p>Note: it cause an infinite loop on recursive functions.</p>\n"
},
{
"answer_id": 9713707,
"author": "JoolzCheat",
"author_id": 1270636,
"author_profile": "https://Stackoverflow.com/users/1270636",
"pm_score": 3,
"selected": false,
"text": "<p>If you just want the function name and not the code, and want a browser-independent solution, use the following:</p>\n\n<pre><code>var callerFunction = arguments.callee.caller.toString().match(/function ([^\\(]+)/)[1];\n</code></pre>\n\n<p>Note that the above will return an error if there is no caller function as there is no [1] element in the array. To work around, use the below:</p>\n\n<pre><code>var callerFunction = (arguments.callee.caller.toString().match(/function ([^\\(]+)/) === null) ? 'Document Object Model': arguments.callee.caller.toString().match(/function ([^\\(]+)/)[1], arguments.callee.toString().match(/function ([^\\(]+)/)[1]);\n</code></pre>\n"
},
{
"answer_id": 12321175,
"author": "bladnman",
"author_id": 473501,
"author_profile": "https://Stackoverflow.com/users/473501",
"pm_score": 3,
"selected": false,
"text": "<p>I wanted to add my fiddle here for this:</p>\n\n<p><a href=\"http://jsfiddle.net/bladnman/EhUm3/\" rel=\"noreferrer\">http://jsfiddle.net/bladnman/EhUm3/</a></p>\n\n<p>I tested this is chrome, safari and IE (10 and 8). Works fine. There is only 1 function that matters, so if you get scared by the big fiddle, read below.</p>\n\n<p>Note:\nThere is a fair amount of my own \"boilerplate\" in this fiddle. You can remove all of that and use split's if you like. It's just an ultra-safe\" set of functions I've come to rely on.</p>\n\n<p>There is also a \"JSFiddle\" template in there that I use for many fiddles to simply quick fiddling.</p>\n"
},
{
"answer_id": 12384187,
"author": "BrazFlat",
"author_id": 1665043,
"author_profile": "https://Stackoverflow.com/users/1665043",
"pm_score": 3,
"selected": false,
"text": "<p>Here, everything but the <code>functionname</code> is stripped from <code>caller.toString()</code>, with RegExp.</p>\n\n<pre><code><!DOCTYPE html>\n<meta charset=\"UTF-8\">\n<title>Show the callers name</title><!-- This validates as html5! -->\n<script>\nmain();\nfunction main() { Hello(); }\nfunction Hello(){\n var name = Hello.caller.toString().replace(/\\s\\([^#]+$|^[^\\s]+\\s/g,'');\n name = name.replace(/\\s/g,'');\n if ( typeof window[name] !== 'function' )\n alert (\"sorry, the type of \"+name+\" is \"+ typeof window[name]);\n else\n alert (\"The name of the \"+typeof window[name]+\" that called is \"+name);\n}\n</script>\n</code></pre>\n"
},
{
"answer_id": 17255041,
"author": "Diego Augusto Molina",
"author_id": 2512368,
"author_profile": "https://Stackoverflow.com/users/2512368",
"pm_score": 2,
"selected": false,
"text": "<p>Try the following code:</p>\n\n<pre><code>function getStackTrace(){\n var f = arguments.callee;\n var ret = [];\n var item = {};\n var iter = 0;\n\n while ( f = f.caller ){\n // Initialize\n item = {\n name: f.name || null,\n args: [], // Empty array = no arguments passed\n callback: f\n };\n\n // Function arguments\n if ( f.arguments ){\n for ( iter = 0; iter<f.arguments.length; iter++ ){\n item.args[iter] = f.arguments[iter];\n }\n } else {\n item.args = null; // null = argument listing not supported\n }\n\n ret.push( item );\n }\n return ret;\n}\n</code></pre>\n\n<p>Worked for me in Firefox-21 and Chromium-25.</p>\n"
},
{
"answer_id": 22165274,
"author": "QueueHammer",
"author_id": 46810,
"author_profile": "https://Stackoverflow.com/users/46810",
"pm_score": 5,
"selected": false,
"text": "<p>Looks like this is quite a solved question but I recently found out that <a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions_and_function_scope/arguments/callee\">callee is not allowed in 'strict mode'</a> so for my own use I wrote a class that will get the path from where it is called. It's <a href=\"https://github.com/QueueHammer/codecraftsman.js/blob/master/codecraftsman.js\">part of a small helper lib</a> and if you want to use the code standalone change the offset used to return the stack trace of the caller (use 1 instead of 2)</p>\n\n<pre><code>function ScriptPath() {\n var scriptPath = '';\n try {\n //Throw an error to generate a stack trace\n throw new Error();\n }\n catch(e) {\n //Split the stack trace into each line\n var stackLines = e.stack.split('\\n');\n var callerIndex = 0;\n //Now walk though each line until we find a path reference\n for(var i in stackLines){\n if(!stackLines[i].match(/http[s]?:\\/\\//)) continue;\n //We skipped all the lines with out an http so we now have a script reference\n //This one is the class constructor, the next is the getScriptPath() call\n //The one after that is the user code requesting the path info (so offset by 2)\n callerIndex = Number(i) + 2;\n break;\n }\n //Now parse the string for each section we want to return\n pathParts = stackLines[callerIndex].match(/((http[s]?:\\/\\/.+\\/)([^\\/]+\\.js)):/);\n }\n\n this.fullPath = function() {\n return pathParts[1];\n };\n\n this.path = function() {\n return pathParts[2];\n };\n\n this.file = function() {\n return pathParts[3];\n };\n\n this.fileNoExt = function() {\n var parts = this.file().split('.');\n parts.length = parts.length != 1 ? parts.length - 1 : 1;\n return parts.join('.');\n };\n}\n</code></pre>\n"
},
{
"answer_id": 22944747,
"author": "Pablo Armentano",
"author_id": 970375,
"author_profile": "https://Stackoverflow.com/users/970375",
"pm_score": 3,
"selected": false,
"text": "<p>Just want to let you know that on <strong>PhoneGap/Android</strong> the <code>name</code> doesnt seem to be working. But <code>arguments.callee.caller.toString()</code> will do the trick.</p>\n"
},
{
"answer_id": 28289354,
"author": "Phil",
"author_id": 2484523,
"author_profile": "https://Stackoverflow.com/users/2484523",
"pm_score": 6,
"selected": false,
"text": "<p>I know you mentioned \"in Javascript\", but if the purpose is debugging, I think it's easier to just use your browser's developer tools. This is how it looks in Chrome:\n<img src=\"https://i.stack.imgur.com/aBtUp.png\" alt=\"enter image description here\">\nJust drop the debugger where you want to investigate the stack.</p>\n"
},
{
"answer_id": 30103737,
"author": "heystewart",
"author_id": 4875359,
"author_profile": "https://Stackoverflow.com/users/4875359",
"pm_score": 6,
"selected": false,
"text": "<p>I usually use <code>(new Error()).stack</code> in Chrome. \nThe nice thing is that this also gives you the line numbers where the caller called the function. The downside is that it limits the length of the stack to 10, which is why I came to this page in the first place.</p>\n\n<p>(I'm using this to collect callstacks in a low-level constructor during execution, to view and debug later, so setting a breakpoint isn't of use since it will be hit thousands of times)</p>\n"
},
{
"answer_id": 30687518,
"author": "Greg",
"author_id": 410333,
"author_profile": "https://Stackoverflow.com/users/410333",
"pm_score": 5,
"selected": false,
"text": "<p>You can use Function.Caller to get the calling function. The old method using argument.caller is considered obsolete.</p>\n\n<p>The following code illustrates its use:</p>\n\n<pre><code>function Hello() { return Hello.caller;}\n\nHello2 = function NamedFunc() { return NamedFunc.caller; };\n\nfunction main()\n{\n Hello(); //both return main()\n Hello2();\n}\n</code></pre>\n\n<p>Notes about obsolete argument.caller: <a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions/arguments/caller\">https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions/arguments/caller</a></p>\n\n<p>Be aware Function.caller is non-standard: <a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function/caller\">https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function/caller</a></p>\n"
},
{
"answer_id": 33489922,
"author": "Mario PG",
"author_id": 5518040,
"author_profile": "https://Stackoverflow.com/users/5518040",
"pm_score": 0,
"selected": false,
"text": "<p>If you really need the functionality for some reason and want it to be cross-browser compatible and not worry for strict stuff and be forward compatible then pass a this reference:</p>\n\n<pre><code>function main()\n{\n Hello(this);\n}\n\nfunction Hello(caller)\n{\n // caller will be the object that called Hello. boom like that... \n // you can add an undefined check code if the function Hello \n // will be called without parameters from somewhere else\n}\n</code></pre>\n"
},
{
"answer_id": 34853024,
"author": "humkins",
"author_id": 1902296,
"author_profile": "https://Stackoverflow.com/users/1902296",
"pm_score": 6,
"selected": false,
"text": "<p>If you are not going to run it in IE < 11 then <a href=\"https://developer.mozilla.org/en-US/docs/Web/API/Console/trace\" rel=\"noreferrer\">console.trace()</a> would suit.</p>\n\n<pre><code>function main() {\n Hello();\n}\n\nfunction Hello() {\n console.trace()\n}\n\nmain()\n// Hello @ VM261:9\n// main @ VM261:4\n</code></pre>\n"
},
{
"answer_id": 35799799,
"author": "GrayedFox",
"author_id": 3249501,
"author_profile": "https://Stackoverflow.com/users/3249501",
"pm_score": 1,
"selected": false,
"text": "<p>Another way around this problem is to simply pass the name of the calling function as a parameter. </p>\n\n<p>For example:</p>\n\n<pre><code>function reformatString(string, callerName) {\n\n if (callerName === \"uid\") {\n string = string.toUpperCase();\n }\n\n return string;\n}\n</code></pre>\n\n<p>Now, you could call the function like this:</p>\n\n<pre><code>function uid(){\n var myString = \"apples\";\n\n reformatString(myString, function.name);\n}\n</code></pre>\n\n<p>My example uses a hard coded check of the function name, but you could easily use a switch statement or some other logic to do what you want there.</p>\n"
},
{
"answer_id": 36256573,
"author": "Abrar Jahin",
"author_id": 2193439,
"author_profile": "https://Stackoverflow.com/users/2193439",
"pm_score": 1,
"selected": false,
"text": "<p>As far as I know, we have 2 way for this from given sources like this-</p>\n\n<ol>\n<li><p><a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions/arguments/caller\" rel=\"nofollow\">arguments.caller</a></p>\n\n<pre><code>function whoCalled()\n{\n if (arguments.caller == null)\n console.log('I was called from the global scope.');\n else\n console.log(arguments.caller + ' called me!');\n}\n</code></pre></li>\n<li><p><a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function/caller\" rel=\"nofollow\">Function.caller</a></p>\n\n<pre><code>function myFunc()\n{\n if (myFunc.caller == null) {\n return 'The function was called from the top!';\n }\n else\n {\n return 'This function\\'s caller was ' + myFunc.caller;\n }\n}\n</code></pre></li>\n</ol>\n\n<p>Think u have your answer :).</p>\n"
},
{
"answer_id": 36277165,
"author": "autistic",
"author_id": 1989425,
"author_profile": "https://Stackoverflow.com/users/1989425",
"pm_score": 1,
"selected": false,
"text": "<p>I'm attempting to address both the question and the current bounty with this question.</p>\n\n<p>The bounty requires that the caller be obtained in <em>strict</em> mode, and the only way I can see this done is by referring to a function declared <em>outside</em> of strict mode.</p>\n\n<p>For example, the following is non-standard but has been tested with previous (29/03/2016) and current (1st August 2018) versions of Chrome, Edge and Firefox.</p>\n\n<p><div class=\"snippet\" data-lang=\"js\" data-hide=\"false\" data-console=\"true\" data-babel=\"false\">\r\n<div class=\"snippet-code\">\r\n<pre class=\"snippet-code-js lang-js prettyprint-override\"><code>function caller()\r\n{\r\n return caller.caller.caller;\r\n}\r\n\r\n'use strict';\r\nfunction main()\r\n{\r\n // Original question:\r\n Hello();\r\n // Bounty question:\r\n (function() { console.log('Anonymous function called by ' + caller().name); })();\r\n}\r\n\r\nfunction Hello()\r\n{\r\n // How do you find out the caller function is 'main'?\r\n console.log('Hello called by ' + caller().name);\r\n}\r\n\r\nmain();</code></pre>\r\n</div>\r\n</div>\r\n</p>\n"
},
{
"answer_id": 36596619,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 2,
"selected": false,
"text": "<p>here is a function to <a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function/caller\" rel=\"nofollow\">get full stacktrace</a>:</p>\n\n<pre><code>function stacktrace() {\nvar f = stacktrace;\nvar stack = 'Stack trace:';\nwhile (f) {\n stack += '\\n' + f.name;\n f = f.caller;\n}\nreturn stack;\n}\n</code></pre>\n"
},
{
"answer_id": 42096635,
"author": "Anonymous",
"author_id": 437393,
"author_profile": "https://Stackoverflow.com/users/437393",
"pm_score": 1,
"selected": false,
"text": "<p>Why all of the solutions above look like a rocket science. Meanwhile, it should not be more complicated than this snippet. All credits to this guy </p>\n\n<p><a href=\"https://stackoverflow.com/questions/280389/how-do-you-find-out-the-caller-function-in-javascript#answer-4047670\">How do you find out the caller function in JavaScript?</a></p>\n\n<pre><code>var stackTrace = function() {\n\n var calls = [];\n var caller = arguments.callee.caller;\n\n for (var k = 0; k < 10; k++) {\n if (caller) {\n calls.push(caller);\n caller = caller.caller;\n }\n }\n\n return calls;\n};\n\n// when I call this inside specific method I see list of references to source method, obviously, I can add toString() to each call to see only function's content\n// [function(), function(data), function(res), function(l), function(a, c), x(a, b, c, d), function(c, e)]\n</code></pre>\n"
},
{
"answer_id": 43674446,
"author": "吴家荣",
"author_id": 7387209,
"author_profile": "https://Stackoverflow.com/users/7387209",
"pm_score": 1,
"selected": false,
"text": "<p>I think the following code piece may be helpful:</p>\n\n<pre><code>window.fnPureLog = function(sStatement, anyVariable) {\n if (arguments.length < 1) { \n throw new Error('Arguments sStatement and anyVariable are expected'); \n }\n if (typeof sStatement !== 'string') { \n throw new Error('The type of sStatement is not match, please use string');\n }\n var oCallStackTrack = new Error();\n console.log(oCallStackTrack.stack.replace('Error', 'Call Stack:'), '\\n' + sStatement + ':', anyVariable);\n}\n</code></pre>\n\n<p>Execute the code:</p>\n\n<pre><code>window.fnPureLog = function(sStatement, anyVariable) {\n if (arguments.length < 1) { \n throw new Error('Arguments sStatement and anyVariable are expected'); \n }\n if (typeof sStatement !== 'string') { \n throw new Error('The type of sStatement is not match, please use string');\n }\n var oCallStackTrack = new Error();\n console.log(oCallStackTrack.stack.replace('Error', 'Call Stack:'), '\\n' + sStatement + ':', anyVariable);\n}\n\nfunction fnBsnCallStack1() {\n fnPureLog('Stock Count', 100)\n}\n\nfunction fnBsnCallStack2() {\n fnBsnCallStack1()\n}\n\nfnBsnCallStack2();\n</code></pre>\n\n<p>The log looks like this:</p>\n\n<pre><code>Call Stack:\n at window.fnPureLog (<anonymous>:8:27)\n at fnBsnCallStack1 (<anonymous>:13:5)\n at fnBsnCallStack2 (<anonymous>:17:5)\n at <anonymous>:20:1 \nStock Count: 100\n</code></pre>\n"
},
{
"answer_id": 45072174,
"author": "Stephen Quan",
"author_id": 881441,
"author_profile": "https://Stackoverflow.com/users/881441",
"pm_score": 5,
"selected": false,
"text": "<p><a href=\"https://stackoverflow.com/a/30103737/881441\">heystewart's answer</a> and <a href=\"https://stackoverflow.com/a/43674446/881441\">JiarongWu's answer</a> both mentioned that the <code>Error</code> object has access to the <code>stack</code>.</p>\n<p>Here's an example:</p>\n<p><div class=\"snippet\" data-lang=\"js\" data-hide=\"false\" data-console=\"true\" data-babel=\"false\">\r\n<div class=\"snippet-code\">\r\n<pre class=\"snippet-code-js lang-js prettyprint-override\"><code>function main() {\n Hello();\n}\n\nfunction Hello() {\n try {\n throw new Error();\n } catch (err) {\n let stack = err.stack;\n // N.B. stack === \"Error\\n at Hello ...\\n at main ... \\n....\"\n let m = stack.match(/.*?Hello.*?\\n(.*?)\\n/);\n if (m) {\n let caller_name = m[1];\n console.log(\"Caller is:\", caller_name);\n }\n }\n}\n\nmain();</code></pre>\r\n</div>\r\n</div>\r\n</p>\n<p>Different browsers shows the stack in different string formats:</p>\n<pre><code>Safari : Caller is: main@https://stacksnippets.net/js:14:8\nFirefox : Caller is: main@https://stacksnippets.net/js:14:3\nChrome : Caller is: at main (https://stacksnippets.net/js:14:3)\nIE Edge : Caller is: at main (https://stacksnippets.net/js:14:3)\nIE : Caller is: at main (https://stacksnippets.net/js:14:3)\n</code></pre>\n<p>Most browsers will set the stack with <code>var stack = (new Error()).stack</code>. In Internet Explorer the stack will be undefined - you have to throw a real exception to retrieve the stack.</p>\n<p>Conclusion: It's possible to determine "main" is the caller to "Hello" using the <code>stack</code> in the <code>Error</code> object. In fact it will work in cases where the <code>callee</code> / <code>caller</code> approach doesn't work. It will also show you context, i.e. source file and line number. However effort is required to make the solution cross platform.</p>\n"
},
{
"answer_id": 47340333,
"author": "inorganik",
"author_id": 591487,
"author_profile": "https://Stackoverflow.com/users/591487",
"pm_score": 5,
"selected": false,
"text": "<p>I would do this:</p>\n\n<pre><code>function Hello() {\n console.trace();\n}\n</code></pre>\n"
},
{
"answer_id": 48985787,
"author": "Rovanion",
"author_id": 501017,
"author_profile": "https://Stackoverflow.com/users/501017",
"pm_score": 4,
"selected": false,
"text": "<h1>2018 Update</h1>\n\n<p><a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function/caller\" rel=\"noreferrer\"><code>caller</code> is forbidden in strict mode</a>. Here is an alternative using the (non-standard) <a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Error/Stack\" rel=\"noreferrer\"><code>Error</code> stack</a>.</p>\n\n<p>The following function seems to do the job in Firefox 52 and Chrome 61-71 though its implementation makes a lot of assumptions about the logging format of the two browsers and should be used with caution, given that it throws an exception and possibly executes two regex matchings before being done.</p>\n\n<p><div class=\"snippet\" data-lang=\"js\" data-hide=\"false\" data-console=\"true\" data-babel=\"false\">\r\n<div class=\"snippet-code\">\r\n<pre class=\"snippet-code-js lang-js prettyprint-override\"><code>'use strict';\r\nconst fnNameMatcher = /([^(]+)@|at ([^(]+) \\(/;\r\n\r\nfunction fnName(str) {\r\n const regexResult = fnNameMatcher.exec(str);\r\n return regexResult[1] || regexResult[2];\r\n}\r\n\r\nfunction log(...messages) {\r\n const logLines = (new Error().stack).split('\\n');\r\n const callerName = fnName(logLines[1]);\r\n\r\n if (callerName !== null) {\r\n if (callerName !== 'log') {\r\n console.log(callerName, 'called log with:', ...messages);\r\n } else {\r\n console.log(fnName(logLines[2]), 'called log with:', ...messages);\r\n }\r\n } else {\r\n console.log(...messages);\r\n }\r\n}\r\n\r\nfunction foo() {\r\n log('hi', 'there');\r\n}\r\n\r\n(function main() {\r\n foo();\r\n}());</code></pre>\r\n</div>\r\n</div>\r\n</p>\n"
},
{
"answer_id": 49274444,
"author": "Prasanna",
"author_id": 4272651,
"author_profile": "https://Stackoverflow.com/users/4272651",
"pm_score": 4,
"selected": false,
"text": "<p>Just console log your error stack. You can then know how are you being called</p>\n\n<p><div class=\"snippet\" data-lang=\"js\" data-hide=\"false\" data-console=\"true\" data-babel=\"false\">\r\n<div class=\"snippet-code\">\r\n<pre class=\"snippet-code-js lang-js prettyprint-override\"><code>const hello = () => {\r\n console.log(new Error('I was called').stack)\r\n}\r\n\r\nconst sello = () => {\r\n hello()\r\n}\r\n\r\nsello()</code></pre>\r\n</div>\r\n</div>\r\n</p>\n"
},
{
"answer_id": 52925988,
"author": "pouyan",
"author_id": 2398444,
"author_profile": "https://Stackoverflow.com/users/2398444",
"pm_score": 1,
"selected": false,
"text": "<p>As none of previous answers works like what I was looking for(getting just the last function caller not a function as a string or callstack) I post my solution here for those who are like me and hope this will work for them:</p>\n\n<p><div class=\"snippet\" data-lang=\"js\" data-hide=\"false\" data-console=\"true\" data-babel=\"false\">\r\n<div class=\"snippet-code\">\r\n<pre class=\"snippet-code-js lang-js prettyprint-override\"><code>function getCallerName(func)\r\n{\r\n if (!func) return \"anonymous\";\r\n let caller = func.caller;\r\n if (!caller) return \"anonymous\";\r\n caller = caller.toString();\r\n if (!caller.trim().startsWith(\"function\")) return \"anonymous\";\r\n return caller.substring(0, caller.indexOf(\"(\")).replace(\"function\",\"\");\r\n}\r\n\r\n\r\n// Example of how to use \"getCallerName\" function\r\n\r\nfunction Hello(){\r\nconsole.log(\"ex1 => \" + getCallerName(Hello));\r\n}\r\n\r\nfunction Main(){\r\nHello();\r\n\r\n// another example\r\nconsole.log(\"ex3 => \" + getCallerName(Main));\r\n}\r\n\r\nMain();</code></pre>\r\n</div>\r\n</div>\r\n</p>\n"
},
{
"answer_id": 57023880,
"author": "VanagaS",
"author_id": 2546381,
"author_profile": "https://Stackoverflow.com/users/2546381",
"pm_score": 6,
"selected": false,
"text": "<p>In both ES6 and Strict mode, use the following to get the Caller function</p>\n<pre><code>console.log((new Error()).stack.split("\\n")[2].trim().split(" ")[1])\n</code></pre>\n<p>Please note that, the above line will throw an exception if there is no caller or no previous stack. Use accordingly.</p>\n<p>To get callee (the current function name), use:</p>\n<pre><code>console.log((new Error()).stack.split("\\n")[1].trim().split(" ")[1]) \n</code></pre>\n"
},
{
"answer_id": 60370866,
"author": "ns16",
"author_id": 7755085,
"author_profile": "https://Stackoverflow.com/users/7755085",
"pm_score": 2,
"selected": false,
"text": "<p>Note you can't use <a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function/caller\" rel=\"nofollow noreferrer\">Function.caller</a> in Node.js, use <a href=\"https://www.npmjs.com/package/caller-id\" rel=\"nofollow noreferrer\">caller-id</a> package instead. For example:</p>\n\n<pre><code>var callerId = require('caller-id');\n\nfunction foo() {\n bar();\n}\nfunction bar() {\n var caller = callerId.getData();\n /*\n caller = {\n typeName: 'Object',\n functionName: 'foo',\n filePath: '/path/of/this/file.js',\n lineNumber: 5,\n topLevelFlag: true,\n nativeFlag: false,\n evalFlag: false\n }\n */\n}\n</code></pre>\n"
},
{
"answer_id": 65168658,
"author": "Israel",
"author_id": 8244338,
"author_profile": "https://Stackoverflow.com/users/8244338",
"pm_score": 2,
"selected": false,
"text": "<p>Works great for me, and you can chose how much you want to go back in the functions:</p>\n<pre><code>function getCaller(functionBack= 0) {\n const back = functionBack * 2;\n const stack = new Error().stack.split('at ');\n const stackIndex = stack[3 + back].includes('C:') ? (3 + back) : (4 + back);\n const isAsync = stack[stackIndex].includes('async');\n let result;\n if (isAsync)\n result = stack[stackIndex].split(' ')[1].split(' ')[0];\n else\n result = stack[stackIndex].split(' ')[0];\n return result;\n}\n</code></pre>\n"
},
{
"answer_id": 69769143,
"author": "bbonch",
"author_id": 1513020,
"author_profile": "https://Stackoverflow.com/users/1513020",
"pm_score": 0,
"selected": false,
"text": "<pre><code>function main()\n{\n Hello();\n}\n\nfunction Hello()\n{\n new Error().stack\n}\n</code></pre>\n"
},
{
"answer_id": 69837438,
"author": "Anna Do",
"author_id": 9957129,
"author_profile": "https://Stackoverflow.com/users/9957129",
"pm_score": 2,
"selected": false,
"text": "<p>I could use these in 2021 and get the stack which starts from the caller function :</p>\n<pre><code>1. console.trace();\n2. console.log((new Error).stack)\n\n// do the same as #2 just with better view\n3. console.log((new Error).stack.split("\\n")) \n</code></pre>\n"
},
{
"answer_id": 70904900,
"author": "Mohamad amin Moslemi",
"author_id": 11738858,
"author_profile": "https://Stackoverflow.com/users/11738858",
"pm_score": 0,
"selected": false,
"text": "<p>You can use <code>debugger;</code> in function .\nopen inespect elements and watch call stack;</p>\n"
},
{
"answer_id": 72656754,
"author": "Putin - The Hero",
"author_id": 961631,
"author_profile": "https://Stackoverflow.com/users/961631",
"pm_score": 1,
"selected": false,
"text": "<p>With <code>Strict Mode On/Off</code> (JavaScript & TypeScript), if (!) the caller exist you can try this one</p>\n<pre><code>console.log(`caller:${(new Error()).stack?.split('\\n')[2].trim().split(' ')[1]}`)\n</code></pre>\n"
}
] |
2008/11/11
|
[
"https://Stackoverflow.com/questions/280389",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11413/"
] |
```
function main()
{
Hello();
}
function Hello()
{
// How do you find out the caller function is 'main'?
}
```
Is there a way to find out the call stack?
|
**Note that this solution is deprecated and should no longer be used according to MDN documentation**
<https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function/caller>
---
```
function Hello()
{
alert("caller is " + Hello.caller);
}
```
Note that this feature is **non-standard**, from [`Function.caller`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function/caller):
>
> **Non-standard**
>
> This feature is non-standard and is not on a standards track. Do not use it on production sites facing the Web: it will not work for every user. There may also be large incompatibilities between implementations and the behavior may change in the future.
>
>
>
---
The following is the old answer from 2008, which is no longer supported in modern Javascript:
```
function Hello()
{
alert("caller is " + arguments.callee.caller.toString());
}
```
|
280,399 |
<p>I have an sp with the following pseudo code... </p>
<pre><code> BEGIN TRANSACTION
set @errorLocation='Deleting Permissions'
DELETE [tblUsrPermissions]
WHERE
lngUserID = @lngUserID
if @@error>0
begin
goto roll_back
end
COMMIT TRANSACTION
set @errorLocation='' --clear error messages
select @errorLocation --return success
return
roll_back:
IF @@TRANCOUNT > 0
ROLLBACK TRANSACTION -- there were errors, rollback
select @errorLocation
</code></pre>
<p>I'm using .NET sqlclient sql datareader, and I am get an exeception in code when calling the ExecuteScalar function - an an error occurs during my delete operation in the sp.</p>
<p>I want to obtain my custom error message instead of the exception. What can I do?</p>
|
[
{
"answer_id": 280420,
"author": "Mladen Prajdic",
"author_id": 31345,
"author_profile": "https://Stackoverflow.com/users/31345",
"pm_score": 1,
"selected": false,
"text": "<p>use raiserror to thorw your error to the client.\nnote that depending on the severity of the erorr your raiserror message might never be hit.\nso for more complete answer provide the original error you get and where do you get it.</p>\n"
},
{
"answer_id": 280744,
"author": "kristof",
"author_id": 3241,
"author_profile": "https://Stackoverflow.com/users/3241",
"pm_score": 0,
"selected": false,
"text": "<p>If you are using SqlServer 2005 or greater put your code inside <a href=\"http://msdn.microsoft.com/en-us/library/ms175976.aspx\" rel=\"nofollow noreferrer\">TRY block</a> and then call <a href=\"http://msdn.microsoft.com/en-us/library/ms178592.aspx\" rel=\"nofollow noreferrer\">RAISERROR</a> in the catch block</p>\n"
}
] |
2008/11/11
|
[
"https://Stackoverflow.com/questions/280399",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/13370/"
] |
I have an sp with the following pseudo code...
```
BEGIN TRANSACTION
set @errorLocation='Deleting Permissions'
DELETE [tblUsrPermissions]
WHERE
lngUserID = @lngUserID
if @@error>0
begin
goto roll_back
end
COMMIT TRANSACTION
set @errorLocation='' --clear error messages
select @errorLocation --return success
return
roll_back:
IF @@TRANCOUNT > 0
ROLLBACK TRANSACTION -- there were errors, rollback
select @errorLocation
```
I'm using .NET sqlclient sql datareader, and I am get an exeception in code when calling the ExecuteScalar function - an an error occurs during my delete operation in the sp.
I want to obtain my custom error message instead of the exception. What can I do?
|
use raiserror to thorw your error to the client.
note that depending on the severity of the erorr your raiserror message might never be hit.
so for more complete answer provide the original error you get and where do you get it.
|
280,406 |
<p>I have problems with bringing a windows mobile 6 form to the front.
I tried things like this already</p>
<pre><code>Form1 testForm = new Form1();
testForm.Show();
testForm.BringToFront();
testForm.Focus();
</code></pre>
<p>But it's always behind the form that includes that code.
The only things that have worked for me are</p>
<pre><code>testForm.TopMost = true;
</code></pre>
<p>or Hide(); the old form and then show the new one, but i want to avoid hiding the other form. TopMost isn't very clean anyway with using multiple other forms.</p>
<p>The other thing that works is</p>
<pre><code>testForm.ShowDialog();
</code></pre>
<p>but I don't want to show the form modal.</p>
<p>To cut it short. I just want to show the new form in front of another form, and if I close it, I want to see the old form again.</p>
<p>Maybe someone can help me with this problem. Thank you.</p>
|
[
{
"answer_id": 280478,
"author": "kgiannakakis",
"author_id": 24054,
"author_profile": "https://Stackoverflow.com/users/24054",
"pm_score": 3,
"selected": true,
"text": "<p>I haven't tried it in WM6, but you can use some pinvoke to call Win32 functions:</p>\n\n<pre><code>[DllImport(\"coredll.dll\")]\nprivate static extern IntPtr FindWindow(string lpClassName, string lpWindowName);\n\n[DllImport(\"coredll.dll\", EntryPoint=\"SetForegroundWindow\")]\nprivate static extern int SetForegroundWindow(IntPtr hWnd);\n</code></pre>\n\n<p>Call FindWindow to get the handle and then call SetForegroundWindow. Other functions you may found useful:</p>\n\n<p>ShowWindow, BringWindowToTop, SetWindowPos</p>\n"
},
{
"answer_id": 390232,
"author": "MBoy",
"author_id": 15511,
"author_profile": "https://Stackoverflow.com/users/15511",
"pm_score": 0,
"selected": false,
"text": "<p>Try this:</p>\n\n<p>Put a timer on the form.<br>\nSet it's tick short say 100ms.<br>\nIn the timer_Tick event<br>\n- disable the timer (so it doesn't tick again) then<br>\n- load the child form.</p>\n\n<p>Also you might want to look at the <a href=\"http://msdn.microsoft.com/en-us/library/system.windows.forms.form.owner(VS.80).aspx\" rel=\"nofollow noreferrer\">form.owner</a> property:<br>\n\"<em>When a form is owned by another form, it is minimized and closed with the owner form. For example, if Form2 is owned by form Form1, if Form1 is closed or minimized, Form2 is also closed or minimized.</em> <strong><em>Owned forms are also never displayed behind their owner form</em></strong>.\"</p>\n"
}
] |
2008/11/11
|
[
"https://Stackoverflow.com/questions/280406",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/36481/"
] |
I have problems with bringing a windows mobile 6 form to the front.
I tried things like this already
```
Form1 testForm = new Form1();
testForm.Show();
testForm.BringToFront();
testForm.Focus();
```
But it's always behind the form that includes that code.
The only things that have worked for me are
```
testForm.TopMost = true;
```
or Hide(); the old form and then show the new one, but i want to avoid hiding the other form. TopMost isn't very clean anyway with using multiple other forms.
The other thing that works is
```
testForm.ShowDialog();
```
but I don't want to show the form modal.
To cut it short. I just want to show the new form in front of another form, and if I close it, I want to see the old form again.
Maybe someone can help me with this problem. Thank you.
|
I haven't tried it in WM6, but you can use some pinvoke to call Win32 functions:
```
[DllImport("coredll.dll")]
private static extern IntPtr FindWindow(string lpClassName, string lpWindowName);
[DllImport("coredll.dll", EntryPoint="SetForegroundWindow")]
private static extern int SetForegroundWindow(IntPtr hWnd);
```
Call FindWindow to get the handle and then call SetForegroundWindow. Other functions you may found useful:
ShowWindow, BringWindowToTop, SetWindowPos
|
280,413 |
<p><strong>Closed as exact duplicate of <a href="https://stackoverflow.com/questions/171970/how-can-i-find-the-method-that-called-the-current-method">"How can I find the method that called the current method?"</a></strong></p>
<p>Is <a href="https://stackoverflow.com/questions/280389/javascript-how-do-you-find-the-caller-function">this</a> possible with c#?</p>
<pre><code>void main()
{
Hello();
}
void Hello()
{
// how do you find out the caller is function 'main'?
}
</code></pre>
|
[
{
"answer_id": 280425,
"author": "Marc Gravell",
"author_id": 23354,
"author_profile": "https://Stackoverflow.com/users/23354",
"pm_score": 5,
"selected": true,
"text": "<pre><code>Console.WriteLine(new StackFrame(1).GetMethod().Name);\n</code></pre>\n\n<p>However, this is not robust, especially as optimisations (such as JIT inlining) can monkey with the perceived stack frames.</p>\n"
},
{
"answer_id": 280432,
"author": "schnaader",
"author_id": 34065,
"author_profile": "https://Stackoverflow.com/users/34065",
"pm_score": 2,
"selected": false,
"text": "<p>From <a href=\"http://bytes.com/forum/thread213910.html\" rel=\"nofollow noreferrer\">here</a>:</p>\n\n<pre><code>System.Diagnostics.StackTrace st = new System.Diagnostics.StackTrace(1);\nSystem.Diagnostics.StackFrame sf = st.GetFrame(0);\nstring msg = sf.GetMethod().DeclaringType.FullName + \".\" +\nsf.GetMethod().Name;\nMessageBox.Show( msg );\n</code></pre>\n\n<p>But there is also a remark that this could not work with multi-threading.</p>\n"
}
] |
2008/11/11
|
[
"https://Stackoverflow.com/questions/280413",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/31505/"
] |
**Closed as exact duplicate of ["How can I find the method that called the current method?"](https://stackoverflow.com/questions/171970/how-can-i-find-the-method-that-called-the-current-method)**
Is [this](https://stackoverflow.com/questions/280389/javascript-how-do-you-find-the-caller-function) possible with c#?
```
void main()
{
Hello();
}
void Hello()
{
// how do you find out the caller is function 'main'?
}
```
|
```
Console.WriteLine(new StackFrame(1).GetMethod().Name);
```
However, this is not robust, especially as optimisations (such as JIT inlining) can monkey with the perceived stack frames.
|
280,421 |
<p>It seems that when I have one mysql_real_query() function in a continuous while loop, the query will get executed OK.</p>
<p>However, if multiple mysql_real_query() are inside the while loop, one right after the other. Depending on the query, sometimes neither the first query nor second query will execute properly.</p>
<p>This seems like a threading issue to me. I'm wondering if the mysql c api has a way of dealing with this? Does anyone know how to deal with this? mysql_free_result() doesn't work since I am not even storing the results.</p>
<pre><code>//keep polling as long as stop character '-' is not read
while(szRxChar != '-')
{
// Check if a read is outstanding
if (HasOverlappedIoCompleted(&ovRead))
{
// Issue a serial port read
if (!ReadFile(hSerial,&szRxChar,1,
&dwBytesRead,&ovRead))
{
DWORD dwErr = GetLastError();
if (dwErr!=ERROR_IO_PENDING)
return dwErr;
}
}
// Wait 5 seconds for serial input
if (!(HasOverlappedIoCompleted(&ovRead)))
{
WaitForSingleObject(hReadEvent,RESET_TIME);
}
// Check if serial input has arrived
if (GetOverlappedResult(hSerial,&ovRead,
&dwBytesRead,FALSE))
{
// Wait for the write
GetOverlappedResult(hSerial,&ovWrite,
&dwBytesWritten,TRUE);
//load tagBuffer with byte stream
tagBuffer[i] = szRxChar;
i++;
tagBuffer[i] = 0; //char arrays are \0 terminated
//run query with tagBuffer
if( strlen(tagBuffer)==PACKET_LENGTH )
{
sprintf(query,"insert into scan (rfidnum) values ('");
strcat(query, tagBuffer);
strcat(query, "')");
mysql_real_query(&mysql,query,(unsigned int)strlen(query));
i=0;
}
mysql_real_query(&mysql,"insert into scan (rfidnum) values ('2nd query')",(unsigned int)strlen("insert into scan (rfid) values ('2nd query')"));
mysql_free_result(res);
}
}
</code></pre>
|
[
{
"answer_id": 280456,
"author": "Alnitak",
"author_id": 6782,
"author_profile": "https://Stackoverflow.com/users/6782",
"pm_score": 0,
"selected": false,
"text": "<p>OK, For test purposes, take your <code>tagBuffer</code> variable out of the first <code>mysql_real_query</code> call and replace it with a constant, like your second test query.</p>\n\n<p>At that point you'd just be repeatedly inserting two constant strings. That <strong>really</strong> should work.</p>\n\n<p>If that does work, then we have to figure out what is wrong with <code>tagBuffer</code>. Could it be receiving unusual characters that somehow is confusing MySQL but such that it wasn't spotted in the single query case?</p>\n"
},
{
"answer_id": 282302,
"author": "Bill Karwin",
"author_id": 20860,
"author_profile": "https://Stackoverflow.com/users/20860",
"pm_score": 1,
"selected": false,
"text": "<p>Always check the return value of an API call.</p>\n\n<p><a href=\"http://dev.mysql.com/doc/refman/5.0/en/mysql-real-query.html\" rel=\"nofollow noreferrer\"><code>mysql_real_query()</code></a> returns an integer. The value is zero if the call worked, and nonzero if there's an error.</p>\n\n<p>Check the return value and report it if it's nonzero:</p>\n\n<pre><code>if ((err = mysql_real_query(&mysql,\"insert into scan (rfidnum) values ('2nd query')\",\n (unsigned int)strlen(\"insert into scan (rfid) values ('2nd query')\"))) != 0)\n{\n // report err here, get additional information from these two API calls:\n errno = mysql_errno(&mysql);\n errmsg = mysql_error(&mysql);\n}\n</code></pre>\n\n<p><strong>update:</strong> If you get a nonzero result, you need to check <code>mysql_error()</code> to find out which error. Since you said you get an error if the second query is a <code>SELECT</code>, I would guess it's <code>CR_COMMANDS_OUT_OF_SYNC</code>, which means the API thinks there are some results pending (even if the result consists of zero rows). You can't start the next SQL query until you have finished fetching results of a <code>SELECT</code> (or calling a stored procedure), even if that query's result is empty.</p>\n\n<p>Here's a brief explanation in the MySQL docs: \"<a href=\"http://dev.mysql.com/doc/refman/5.0/en/commands-out-of-sync.html\" rel=\"nofollow noreferrer\">Commands out of sync</a>\"</p>\n\n<p>You need to use <a href=\"http://dev.mysql.com/doc/refman/5.0/en/mysql-free-result.html\" rel=\"nofollow noreferrer\"><code>mysql_free_result()</code></a> before you can run another query. And that means you need to use <a href=\"http://dev.mysql.com/doc/refman/5.0/en/mysql-use-result.html\" rel=\"nofollow noreferrer\"><code>mysql_use_result()</code></a> before you can free it.</p>\n\n<p>Here's an excerpt from <code>mysql_use_result()</code> doc:</p>\n\n<blockquote>\n <p>After invoking mysql_query() or\n mysql_real_query(), you must call\n mysql_store_result() or\n mysql_use_result() for every statement\n that successfully produces a result\n set (SELECT, SHOW, DESCRIBE, EXPLAIN,\n CHECK TABLE, and so forth). You must\n also call mysql_free_result() after\n you are done with the result set.</p>\n</blockquote>\n"
}
] |
2008/11/11
|
[
"https://Stackoverflow.com/questions/280421",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/28462/"
] |
It seems that when I have one mysql\_real\_query() function in a continuous while loop, the query will get executed OK.
However, if multiple mysql\_real\_query() are inside the while loop, one right after the other. Depending on the query, sometimes neither the first query nor second query will execute properly.
This seems like a threading issue to me. I'm wondering if the mysql c api has a way of dealing with this? Does anyone know how to deal with this? mysql\_free\_result() doesn't work since I am not even storing the results.
```
//keep polling as long as stop character '-' is not read
while(szRxChar != '-')
{
// Check if a read is outstanding
if (HasOverlappedIoCompleted(&ovRead))
{
// Issue a serial port read
if (!ReadFile(hSerial,&szRxChar,1,
&dwBytesRead,&ovRead))
{
DWORD dwErr = GetLastError();
if (dwErr!=ERROR_IO_PENDING)
return dwErr;
}
}
// Wait 5 seconds for serial input
if (!(HasOverlappedIoCompleted(&ovRead)))
{
WaitForSingleObject(hReadEvent,RESET_TIME);
}
// Check if serial input has arrived
if (GetOverlappedResult(hSerial,&ovRead,
&dwBytesRead,FALSE))
{
// Wait for the write
GetOverlappedResult(hSerial,&ovWrite,
&dwBytesWritten,TRUE);
//load tagBuffer with byte stream
tagBuffer[i] = szRxChar;
i++;
tagBuffer[i] = 0; //char arrays are \0 terminated
//run query with tagBuffer
if( strlen(tagBuffer)==PACKET_LENGTH )
{
sprintf(query,"insert into scan (rfidnum) values ('");
strcat(query, tagBuffer);
strcat(query, "')");
mysql_real_query(&mysql,query,(unsigned int)strlen(query));
i=0;
}
mysql_real_query(&mysql,"insert into scan (rfidnum) values ('2nd query')",(unsigned int)strlen("insert into scan (rfid) values ('2nd query')"));
mysql_free_result(res);
}
}
```
|
Always check the return value of an API call.
[`mysql_real_query()`](http://dev.mysql.com/doc/refman/5.0/en/mysql-real-query.html) returns an integer. The value is zero if the call worked, and nonzero if there's an error.
Check the return value and report it if it's nonzero:
```
if ((err = mysql_real_query(&mysql,"insert into scan (rfidnum) values ('2nd query')",
(unsigned int)strlen("insert into scan (rfid) values ('2nd query')"))) != 0)
{
// report err here, get additional information from these two API calls:
errno = mysql_errno(&mysql);
errmsg = mysql_error(&mysql);
}
```
**update:** If you get a nonzero result, you need to check `mysql_error()` to find out which error. Since you said you get an error if the second query is a `SELECT`, I would guess it's `CR_COMMANDS_OUT_OF_SYNC`, which means the API thinks there are some results pending (even if the result consists of zero rows). You can't start the next SQL query until you have finished fetching results of a `SELECT` (or calling a stored procedure), even if that query's result is empty.
Here's a brief explanation in the MySQL docs: "[Commands out of sync](http://dev.mysql.com/doc/refman/5.0/en/commands-out-of-sync.html)"
You need to use [`mysql_free_result()`](http://dev.mysql.com/doc/refman/5.0/en/mysql-free-result.html) before you can run another query. And that means you need to use [`mysql_use_result()`](http://dev.mysql.com/doc/refman/5.0/en/mysql-use-result.html) before you can free it.
Here's an excerpt from `mysql_use_result()` doc:
>
> After invoking mysql\_query() or
> mysql\_real\_query(), you must call
> mysql\_store\_result() or
> mysql\_use\_result() for every statement
> that successfully produces a result
> set (SELECT, SHOW, DESCRIBE, EXPLAIN,
> CHECK TABLE, and so forth). You must
> also call mysql\_free\_result() after
> you are done with the result set.
>
>
>
|
280,426 |
<p>We've got a fairly complex httphandler for handling images. Basically it streams any part of the image at any size that is requested. Some clients use this handler without any problems. But we've got one location that gives us problems, and now it also gives problems on my development environment.</p>
<p>What happens is that the client never receives anything on some requests. So request 1 and 2 are fine, but request 3 and 4 never end. </p>
<ul>
<li>While debugging I can see that the server is ready and has completed the request.</li>
<li>The client however is still waiting on a result (debugging with fiddler2 shows that there is no response received)</li>
</ul>
<p>The code that we use to stream an image is</p>
<pre><code> if (!context.Response.IsClientConnected)
{
imageStream.Close();
imageStream.Dispose();
return;
}
context.Response.BufferOutput = true;
context.Response.ContentType = "image/" + imageformat;
context.Response.AppendHeader("Content-Length", imageStream.Length.ToString());
if (imageStream != null && imageStream.Length > 0 && context.Response.IsClientConnected)
context.Response.BinaryWrite(imageStream.ToArray());
if (context.Response.IsClientConnected)
context.Response.Flush();
imageStream.Close();
imageStream.Dispose();
</code></pre>
<p>The imageStream is a MemoryStream with the contents of an image.</p>
<p>After the call to response.Flush() we do some more clean-up and writing summaries to the eventlog. </p>
<p>We also call GC.Collect() after every request, because the objects that we use in-memory become very large. I know that that is not a good practice, but could it give us trouble?</p>
<p>The problems with not returning requests happen at both IIS 5 (Win XP) and IIS 6 (Win 2003), we use .NET framework v2.</p>
|
[
{
"answer_id": 280436,
"author": "Marc Gravell",
"author_id": 23354,
"author_profile": "https://Stackoverflow.com/users/23354",
"pm_score": 2,
"selected": false,
"text": "<p>First off, there are better ways of dealing with streams that using an array for the entire thing (i.e. <code>MemoryStream</code> <em>might</em> be unnecessary here).</p>\n\n<p>I would envisage a loop:</p>\n\n<pre><code>const int BUFFER_SIZE = 4096; // pick your poison\nbute[] buffer = new byte[BUFFER_SIZE];\nint bytesRead;\n\nwhile((bytesRead = inStream.Read(buffer, 0, BUFFER_SIZE)) > 0)\n{\n outStream.Write(buffer, 0, bytesRead);\n}\n</code></pre>\n\n<p>You should also do this with buffering disabled (<code>.Response.BufferOutput = false</code>).</p>\n\n<p>Re the problem, my suspicion is that you haven't written enough data / closed the response (<code>.Response.Close()</code>).</p>\n"
},
{
"answer_id": 280438,
"author": "Jon Skeet",
"author_id": 22656,
"author_profile": "https://Stackoverflow.com/users/22656",
"pm_score": 2,
"selected": false,
"text": "<p>Garbage collection shouldn't be the problem. Why are you setting <code>BufferOutput</code> to true though? Given that you just want to write the data directly, I'd have thought it would be more appropriate to set it to false.</p>\n\n<p>I suggest you go one level lower in your diagnostics: use <a href=\"http://www.wireshark.org/\" rel=\"nofollow noreferrer\">Wireshark</a> to see exactly what's happening at the network level. Fiddler is great for the HTTP level, but sometimes you need even more detail.</p>\n"
},
{
"answer_id": 280696,
"author": "Michiel Overeem",
"author_id": 5043,
"author_profile": "https://Stackoverflow.com/users/5043",
"pm_score": 0,
"selected": false,
"text": "<p>We also used WebRequests to gather more information. Those were blocking the connections. Putting usings around the WebResponses did the trick.</p>\n\n<pre><code>using (HttpWebResponse test_resp = (HttpWebResponse)test_req.GetResponse())\n{\n}\n</code></pre>\n\n<p>I didn't know that those could block other request etc...</p>\n"
},
{
"answer_id": 281259,
"author": "AnthonyWJones",
"author_id": 17516,
"author_profile": "https://Stackoverflow.com/users/17516",
"pm_score": 3,
"selected": true,
"text": "<p>A client will limit the number of simultaneous requests it will make to any one server. Furthermore when requesting from a resource that requires session state (the default) other requests for resources requiring session state will block.</p>\n\n<p>When using <code>HttpWebResponse</code> you must dispose either that object or the stream returned by its <code>GetResponseStream</code> method to complete the connection.</p>\n\n<p>Your code was very confusing. You've turned buffering on, set a content-length and used a flush. This results in some strange HTTP headers. Ordinarily with buffering on you would leave the setting of the Content-Length header to ASP.NET to handle.</p>\n\n<p>When you use flush ASP.NET assumes that you may subsequently send more data. In this case it will use chunked transfer. Once the response is complete a final set of headers is sent for the final chunk, each chunk as its own length header and the total length of content is derived from these. The first chunk should <em>not</em> have a Content-Length header, however your code is adding that header.</p>\n\n<p>If you turn off buffering and pump the bytes into the output stream yourself <strong>then</strong> you should set the Content-Length header yourself because effectively buffer off means you are taking responsibility for exactly what gets sent to the client. Marc's code is a simple example of such a pump, although I would use a bigger buffer, or on a MemoryStream the WriteTo method would be more efficient.</p>\n"
}
] |
2008/11/11
|
[
"https://Stackoverflow.com/questions/280426",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5043/"
] |
We've got a fairly complex httphandler for handling images. Basically it streams any part of the image at any size that is requested. Some clients use this handler without any problems. But we've got one location that gives us problems, and now it also gives problems on my development environment.
What happens is that the client never receives anything on some requests. So request 1 and 2 are fine, but request 3 and 4 never end.
* While debugging I can see that the server is ready and has completed the request.
* The client however is still waiting on a result (debugging with fiddler2 shows that there is no response received)
The code that we use to stream an image is
```
if (!context.Response.IsClientConnected)
{
imageStream.Close();
imageStream.Dispose();
return;
}
context.Response.BufferOutput = true;
context.Response.ContentType = "image/" + imageformat;
context.Response.AppendHeader("Content-Length", imageStream.Length.ToString());
if (imageStream != null && imageStream.Length > 0 && context.Response.IsClientConnected)
context.Response.BinaryWrite(imageStream.ToArray());
if (context.Response.IsClientConnected)
context.Response.Flush();
imageStream.Close();
imageStream.Dispose();
```
The imageStream is a MemoryStream with the contents of an image.
After the call to response.Flush() we do some more clean-up and writing summaries to the eventlog.
We also call GC.Collect() after every request, because the objects that we use in-memory become very large. I know that that is not a good practice, but could it give us trouble?
The problems with not returning requests happen at both IIS 5 (Win XP) and IIS 6 (Win 2003), we use .NET framework v2.
|
A client will limit the number of simultaneous requests it will make to any one server. Furthermore when requesting from a resource that requires session state (the default) other requests for resources requiring session state will block.
When using `HttpWebResponse` you must dispose either that object or the stream returned by its `GetResponseStream` method to complete the connection.
Your code was very confusing. You've turned buffering on, set a content-length and used a flush. This results in some strange HTTP headers. Ordinarily with buffering on you would leave the setting of the Content-Length header to ASP.NET to handle.
When you use flush ASP.NET assumes that you may subsequently send more data. In this case it will use chunked transfer. Once the response is complete a final set of headers is sent for the final chunk, each chunk as its own length header and the total length of content is derived from these. The first chunk should *not* have a Content-Length header, however your code is adding that header.
If you turn off buffering and pump the bytes into the output stream yourself **then** you should set the Content-Length header yourself because effectively buffer off means you are taking responsibility for exactly what gets sent to the client. Marc's code is a simple example of such a pump, although I would use a bigger buffer, or on a MemoryStream the WriteTo method would be more efficient.
|
280,428 |
<p>I have one autocomplete search, in which by typing few characters it will show all the names, which matches the entered character. I am populating this data in the jsp using DIV tag, by using mouse I'm able to select the names. But I want to select the names in the DIV tag to be selected using the keyboard up and down arrow. Can anyone please help me out from this.</p>
|
[
{
"answer_id": 280450,
"author": "jishi",
"author_id": 33663,
"author_profile": "https://Stackoverflow.com/users/33663",
"pm_score": 0,
"selected": false,
"text": "<p>I assume that you have an input which handles the input. </p>\n\n<p>map onkeyup-eventhandler for that input in which you read out event.keyCode, and do stuff when it's the appropriate keycodes for up/down-arrow (38, 40), to keep a reference to which node (item in your div) you move the focus to.</p>\n\n<p>Then call the same handler when you hit enter (keyCode 13) as you do onclick.</p>\n\n<p>It's hard to give a coding-example because it highly depend on context, but a tip on how to navigate through your div is to make us of .nextSibling and .previousSibling, aswell as .firstChild and .childNodes.</p>\n"
},
{
"answer_id": 280455,
"author": "Shivasubramanian A",
"author_id": 9195,
"author_profile": "https://Stackoverflow.com/users/9195",
"pm_score": 0,
"selected": false,
"text": "<p>Long time since I did this, but I guess you can use <code>event.keyCode</code>.</p>\n\n<p>If the values returned are 38 and 40, then the user has pressed the up and down arrows respectively.</p>\n\n<p>You then have to select the row above or below your current position. How to select the row would depend on your particular situation.</p>\n"
},
{
"answer_id": 375426,
"author": "EndangeredMassa",
"author_id": 106,
"author_profile": "https://Stackoverflow.com/users/106",
"pm_score": 4,
"selected": false,
"text": "<p>Use the <code>onkeydown</code> and <code>onkeyup</code> events to check for key press events in your results div:</p>\n\n<pre><code>var UP = 38;\nvar DOWN = 40;\nvar ENTER = 13;\n\nvar getKey = function(e) {\n if(window.event) { return e.keyCode; } // IE\n else if(e.which) { return e.which; } // Netscape/Firefox/Opera\n};\n\n\nvar keynum = getKey(e);\n\nif(keynum === UP) {\n //Move selection up\n}\n\nif(keynum === DOWN) {\n //Move selection down\n}\n\nif(keynum === ENTER) {\n //Act on current selection\n}\n</code></pre>\n"
},
{
"answer_id": 477740,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 2,
"selected": false,
"text": "<p>copy and paste this piece of code and try..</p>\n\n<pre><code><style>\ndiv.active{ \n background: lightblue\n}\n</style>\n<center>\n<input type=\"text\" id=\"tb\">\n<div id=\"Parent\" style=\"position:absolute;display:block;left:428px; width:146px;top:38px; height:100px; border: 2px solid lightblue; overflow:auto;\"> \n<div id=\"childOne\">1 </div> \n<div id=\"childOne\">2 </div> \n<div id=\"childOne\">3 </div> \n<div id=\"childOne\">4 </div>\n<div id=\"childOne\">5 </div>\n<div id=\"childOne\">6 </div>\n<div id=\"childOne\">7 </div>\n<div id=\"childOne\">8 </div>\n<div id=\"childOne\">9 </div>\n<div id=\"childOne\">10 </div>\n</div>\n</center>\n<script type=\"text/javascript\">\n var scrolLength = 19;\n function autocomplete( textBoxId, containerDivId ) { \n var ac = this; \n this.textbox = document.getElementById(textBoxId); \n this.div = document.getElementById(containerDivId); \n this.list = this.div.getElementsByTagName('div'); \n this.pointer = null; \n this.textbox.onkeydown = function( e ) {\n e = e || window.event; \n switch( e.keyCode ) { \n case 38: //up \n ac.selectDiv(-1); \n break; \n case 40: //down \n ac.selectDiv(1); \n break; } \n } \n\n this.selectDiv = function( inc ) { \n if(this.pointer > 1){\n scrollDiv();\n }\n if(this.pointer == 0)\n document.getElementById(\"Parent\").scrollTop = 0; \n if( this.pointer !== null && this.pointer+inc >= 0 && this.pointer+inc < this.list.length ) { \n this.list[this.pointer].className = ''; \n this.pointer += inc; \n this.list[this.pointer].className = 'active'; \n this.textbox.value = this.list[this.pointer].innerHTML; \n }\n if( this.pointer === null ) { \n\n this.pointer = 0; \n scrolLength = 20;\n this.list[this.pointer].className = 'active'; \n this.textbox.value = this.list[this.pointer].innerHTML; \n } \n }\n function scrollDiv(){\n if(window.event.keyCode == 40){\n document.getElementById(\"Parent\").scrollTop = scrolLength;\n scrolLength = scrolLength + 19; \n } \n else if(window.event.keyCode == 38){\n\n scrolLength = scrolLength - 19; \n document.getElementById(\"Parent\").scrollTop = scrolLength;\n\n }\n }\n } \n new autocomplete( 'tb', 'Parent' );\n</script>\n</code></pre>\n"
}
] |
2008/11/11
|
[
"https://Stackoverflow.com/questions/280428",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] |
I have one autocomplete search, in which by typing few characters it will show all the names, which matches the entered character. I am populating this data in the jsp using DIV tag, by using mouse I'm able to select the names. But I want to select the names in the DIV tag to be selected using the keyboard up and down arrow. Can anyone please help me out from this.
|
Use the `onkeydown` and `onkeyup` events to check for key press events in your results div:
```
var UP = 38;
var DOWN = 40;
var ENTER = 13;
var getKey = function(e) {
if(window.event) { return e.keyCode; } // IE
else if(e.which) { return e.which; } // Netscape/Firefox/Opera
};
var keynum = getKey(e);
if(keynum === UP) {
//Move selection up
}
if(keynum === DOWN) {
//Move selection down
}
if(keynum === ENTER) {
//Act on current selection
}
```
|
280,435 |
<p>I want to use input from a user as a regex pattern for a search over some text. It works, but how I can handle cases where user puts characters that have meaning in regex?</p>
<p>For example, the user wants to search for Word <code>(s)</code>: regex engine will take the <code>(s)</code> as a group. I want it to treat it like a string <code>"(s)" </code>. I can run <code>replace</code> on user input and replace the <code>(</code> with <code>\(</code> and the <code>)</code> with <code>\)</code> but the problem is I will need to do replace for every possible regex symbol.</p>
<p>Do you know some better way ?</p>
|
[
{
"answer_id": 280441,
"author": "ddaa",
"author_id": 11549,
"author_profile": "https://Stackoverflow.com/users/11549",
"pm_score": 10,
"selected": true,
"text": "<p>Use the <code>re.escape()</code> function for this:</p>\n\n<p><a href=\"http://docs.python.org/library/re.html#re.escape\" rel=\"noreferrer\">4.2.3 <code>re</code> Module Contents</a></p>\n\n<blockquote>\n <p><strong>escape(string)</strong></p>\n \n <p>Return string with all non-alphanumerics backslashed; this is useful if you want to match an arbitrary literal string that may have regular expression metacharacters in it.</p>\n</blockquote>\n\n<p>A simplistic example, search any occurence of the provided string optionally followed by 's', and return the match object.</p>\n\n<pre><code>def simplistic_plural(word, text):\n word_or_plural = re.escape(word) + 's?'\n return re.match(word_or_plural, text)\n</code></pre>\n"
},
{
"answer_id": 280463,
"author": "gimel",
"author_id": 6491,
"author_profile": "https://Stackoverflow.com/users/6491",
"pm_score": 6,
"selected": false,
"text": "<p>You can use <a href=\"http://docs.python.org/library/re.html#re.escape\" rel=\"noreferrer\"><code>re.escape()</code></a>:</p>\n<blockquote>\n<p>re.escape(string)\nReturn string with all non-alphanumerics backslashed; this is useful if you want to match an arbitrary literal string that may have regular expression metacharacters in it.</p>\n</blockquote>\n<pre><code>>>> import re\n>>> re.escape('^a.*$')\n'\\\\^a\\\\.\\\\*\\\\$'\n</code></pre>\n<p>If you are using a Python version < 3.7, this will escape non-alphanumerics that are <em>not</em> part of regular expression syntax as well.</p>\n<p>If you are using a Python version < 3.7 but >= 3.3, this will escape non-alphanumerics that are <em>not</em> part of regular expression syntax, <em>except</em> for specifically underscore (<code>_</code>).</p>\n"
},
{
"answer_id": 42423081,
"author": "Owen",
"author_id": 371739,
"author_profile": "https://Stackoverflow.com/users/371739",
"pm_score": 3,
"selected": false,
"text": "<p>Unfortunately, <a href=\"https://docs.python.org/2/library/re.html#re.escape\" rel=\"noreferrer\"><code>re.escape()</code></a> is not suited for the replacement string:</p>\n\n<pre><code>>>> re.sub('a', re.escape('_'), 'aa')\n'\\\\_\\\\_'\n</code></pre>\n\n<p>A solution is to put the replacement in a lambda:</p>\n\n<pre><code>>>> re.sub('a', lambda _: '_', 'aa')\n'__'\n</code></pre>\n\n<p>because the return value of the lambda is treated by <a href=\"https://docs.python.org/2/library/re.html#re.sub\" rel=\"noreferrer\"><code>re.sub()</code></a> as a literal string.</p>\n"
},
{
"answer_id": 73068412,
"author": "Charlie Parker",
"author_id": 1601580,
"author_profile": "https://Stackoverflow.com/users/1601580",
"pm_score": -1,
"selected": false,
"text": "<p>Usually escaping the string that you feed into a regex is such that the regex considers those characters literally. Remember usually you type strings into your compuer and the computer insert the specific characters. When you see in your editor <code>\\n</code> it's not really a new line until the parser decides it is. It's two characters. Once you pass it through python's <code>print</code> will display it and thus parse it as a new a line but in the text you see in the editor it's likely just the char for backslash followed by n. If you do <code>\\r"\\n"</code> then python will always interpret it as the raw thing you typed in (as far as I understand). To complicate things further there is another syntax/grammar going on with regexes. The regex parser will interpret the strings it's receives differently than python's print would. I believe this is why we are recommended to pass raw strings like <code>r"(\\n+)</code> -- so that the regex receives what you actually typed. However, the regex will receive a parenthesis and won't match it as a literal parenthesis unless you tell it to explicitly using the <strong>regex's own syntax rules</strong>. For that you need <code>r"(\\fun \\( x : nat \\) :)"</code> here the first parens won't be matched since it's a capture group due to lack of backslashes but the second one will be matched as literal parens.</p>\n<p>Thus we usually do <code>re.escape(regex)</code> to escape things we want to be interpreted literally i.e. things that would be usually ignored by the regex paraser e.g. parens, spaces etc. will be escaped. e.g. code I have in my app:</p>\n<pre><code> # escapes non-alphanumeric to help match arbitrary literal string, I think the reason this is here is to help differentiate the things escaped from the regex we are inserting in the next line and the literal things we wanted escaped.\n __ppt = re.escape(_ppt) # used for e.g. parenthesis ( are not interpreted as was to group this but literally\n</code></pre>\n<p>e.g. see these strings:</p>\n<pre><code>_ppt\nOut[4]: '(let H : forall x : bool, negb (negb x) = x := fun x : bool =>HEREinHERE)'\n__ppt\nOut[5]: '\\\\(let\\\\ H\\\\ :\\\\ forall\\\\ x\\\\ :\\\\ bool,\\\\ negb\\\\ \\\\(negb\\\\ x\\\\)\\\\ =\\\\ x\\\\ :=\\\\ fun\\\\ x\\\\ :\\\\ bool\\\\ =>HEREinHERE\\\\)'\nprint(rf'{_ppt=}')\n_ppt='(let H : forall x : bool, negb (negb x) = x := fun x : bool =>HEREinHERE)'\nprint(rf'{__ppt=}')\n__ppt='\\\\(let\\\\ H\\\\ :\\\\ forall\\\\ x\\\\ :\\\\ bool,\\\\ negb\\\\ \\\\(negb\\\\ x\\\\)\\\\ =\\\\ x\\\\ :=\\\\ fun\\\\ x\\\\ :\\\\ bool\\\\ =>HEREinHERE\\\\)'\n</code></pre>\n<p>the double backslashes I believe are there so that the regex receives a literal backslash.</p>\n<hr />\n<p>btw, I am surprised it printed double backslashes instead of a single one. If anyone can comment on that it would be appreciated. I'm also curious how to match literal backslashes now in the regex. I assume it's 4 backslashes but I honestly expected only 2 would have been needed due to the raw string r construct.</p>\n"
}
] |
2008/11/11
|
[
"https://Stackoverflow.com/questions/280435",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/288629/"
] |
I want to use input from a user as a regex pattern for a search over some text. It works, but how I can handle cases where user puts characters that have meaning in regex?
For example, the user wants to search for Word `(s)`: regex engine will take the `(s)` as a group. I want it to treat it like a string `"(s)"` . I can run `replace` on user input and replace the `(` with `\(` and the `)` with `\)` but the problem is I will need to do replace for every possible regex symbol.
Do you know some better way ?
|
Use the `re.escape()` function for this:
[4.2.3 `re` Module Contents](http://docs.python.org/library/re.html#re.escape)
>
> **escape(string)**
>
>
> Return string with all non-alphanumerics backslashed; this is useful if you want to match an arbitrary literal string that may have regular expression metacharacters in it.
>
>
>
A simplistic example, search any occurence of the provided string optionally followed by 's', and return the match object.
```
def simplistic_plural(word, text):
word_or_plural = re.escape(word) + 's?'
return re.match(word_or_plural, text)
```
|
280,449 |
<p>I have a page on which I must load controls dynamically based on the user selection.
Let's say that I have something like this:</p>
<pre><code>public static readonly Dictionary<string, string> DynamicControls = new Dictionary<string, string>
{
{ "UserCtrl1", "~/Controls/UserCtrl1.ascx" },
{ "UserCtrl2", "~/Controls/UserCtrl2.ascx" },
{ "UserCtrl3", "~/Controls/UserCtrl3.ascx" },
{ "UserCtrl4", "~/Controls/UserCtrl4.ascx"}
};
</code></pre>
<p>Now let's say than on the page where the controls are loaded the code is something like this:</p>
<pre><code>protected void Page_Load(object sender, EventArgs e)
{
SomePanel.Controls.Add(GetControl());
}
private Control GetControl()
{
string dynamicCtrl = CurrentItem.DynamicControl;
string path = SomeClass.DynamicControls[dynamicCtrl];
Control ctrl = null;
//TODO: find a better way to load the controls
switch (dynamicCtrl)
{
case "UserCtrl1":
{
ctrl = (UserCtrl1)LoadControl(path);
}
break;
case "UserCtrl2":
{
ctrl = (UserCtrl2)LoadControl(path);
}
break;
case "UserCtrl3":
{
ctrl = (UserCtrl3)LoadControl(path);
}
break;
default:
{
throw new ApplicationException("Invalid dynamic control added.");
}
}
return ctrl;
}
</code></pre>
<p>The page has the required registered statements. Any idea how I can get rid of this ugly switch statement?</p>
|
[
{
"answer_id": 280460,
"author": "Will Dean",
"author_id": 987,
"author_profile": "https://Stackoverflow.com/users/987",
"pm_score": 0,
"selected": false,
"text": "<p>Can you not just use foreach on your dictionary and do your test and LoadControl in there?</p>\n"
},
{
"answer_id": 280469,
"author": "Adrian Magdas",
"author_id": 2099426,
"author_profile": "https://Stackoverflow.com/users/2099426",
"pm_score": 0,
"selected": false,
"text": "<p>That wont help because the switch is needed for casting to the right control type.</p>\n"
},
{
"answer_id": 280470,
"author": "Magnus",
"author_id": 4184,
"author_profile": "https://Stackoverflow.com/users/4184",
"pm_score": 4,
"selected": true,
"text": "<p>You don't need to cast the result from LoadControl.</p>\n\n<p>This should do:</p>\n\n<pre><code>private Control GetControl()\n{\n string dynamicCtrl = CurrentItem.DynamicControl;\n string path = SomeClass.DynamicControls[dynamicCtrl];\n\n Control ctrl = LoadControl(path); \n\n return ctrl;\n}\n</code></pre>\n"
},
{
"answer_id": 280481,
"author": "Adam Pope",
"author_id": 12226,
"author_profile": "https://Stackoverflow.com/users/12226",
"pm_score": 1,
"selected": false,
"text": "<p>You probably want something like this (pseudo-ish code): </p>\n\n<pre>\nforeach key in dictionary\n if key = dynamicControl then\n ctrl = (Type.GetType(key))LoadControl(dictionary.get(key))\n end if\nnext\n</pre>\n"
}
] |
2008/11/11
|
[
"https://Stackoverflow.com/questions/280449",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2099426/"
] |
I have a page on which I must load controls dynamically based on the user selection.
Let's say that I have something like this:
```
public static readonly Dictionary<string, string> DynamicControls = new Dictionary<string, string>
{
{ "UserCtrl1", "~/Controls/UserCtrl1.ascx" },
{ "UserCtrl2", "~/Controls/UserCtrl2.ascx" },
{ "UserCtrl3", "~/Controls/UserCtrl3.ascx" },
{ "UserCtrl4", "~/Controls/UserCtrl4.ascx"}
};
```
Now let's say than on the page where the controls are loaded the code is something like this:
```
protected void Page_Load(object sender, EventArgs e)
{
SomePanel.Controls.Add(GetControl());
}
private Control GetControl()
{
string dynamicCtrl = CurrentItem.DynamicControl;
string path = SomeClass.DynamicControls[dynamicCtrl];
Control ctrl = null;
//TODO: find a better way to load the controls
switch (dynamicCtrl)
{
case "UserCtrl1":
{
ctrl = (UserCtrl1)LoadControl(path);
}
break;
case "UserCtrl2":
{
ctrl = (UserCtrl2)LoadControl(path);
}
break;
case "UserCtrl3":
{
ctrl = (UserCtrl3)LoadControl(path);
}
break;
default:
{
throw new ApplicationException("Invalid dynamic control added.");
}
}
return ctrl;
}
```
The page has the required registered statements. Any idea how I can get rid of this ugly switch statement?
|
You don't need to cast the result from LoadControl.
This should do:
```
private Control GetControl()
{
string dynamicCtrl = CurrentItem.DynamicControl;
string path = SomeClass.DynamicControls[dynamicCtrl];
Control ctrl = LoadControl(path);
return ctrl;
}
```
|
280,480 |
<p>I have some code to enable/disable the Windows Aero service in Vista, and I would like to run it in a Windows Service. The code works in a standalone application, but when I run it from a Service, nothing happens. No errors or exceptions are thrown.</p>
<p>I realise that running code in a service is a different scope than running code in an application, but in this case, how would I enable/disable Aero from the service? Is this even possible? </p>
<p>Here is the code I am working with:</p>
<pre><code>public static readonly uint DWM_EC_DISABLECOMPOSITION = 0;
public static readonly uint DWM_EC_ENABLECOMPOSITION = 1;
[DllImport("dwmapi.dll", EntryPoint="DwmEnableComposition")]
protected static extern uint Win32DwmEnableComposition(uint uCompositionAction);
public static bool EnableAero()
{
Win32DwmEnableComposition(DWM_EC_ENABLECOMPOSITION);
}
</code></pre>
<p>Edit: </p>
<p>It turns out that the DwmEnableComposition call is returning HRESULT 0x80070018, or ERROR_BAD_LENGTH. Seems like a strange error, since the code works when not running as a service.</p>
<p>I also tried changing the entire thing to the following code, but got the same result. It sets the window station and desktop, and it seems to be correct, but the call to DwmEnableComposition results in the same error. I've not included the PInvoke declarations for brevity.</p>
<pre><code> protected override void OnStop()
{
IntPtr winStation = OpenWindowStation("winsta0", true, 0x10000000 /* GENERIC_ALL */);
if (winStation == null || winStation.ToInt32() == 0)
{
String err = new Win32Exception(Marshal.GetLastWin32Error()).Message;
}
if (!SetProcessWindowStation(winStation))
{
String err = new Win32Exception(Marshal.GetLastWin32Error()).Message;
}
uint thread = GetCurrentThreadId();
IntPtr hdesk = OpenInputDesktop(0, false, 0x10000000 /* GENERIC_ALL */);
if (hdesk == null || hdesk.ToInt32() == 0)
{
String err = new Win32Exception(Marshal.GetLastWin32Error()).Message;
}
if (!SetThreadDesktop(hdesk))
{
String err = new Win32Exception(Marshal.GetLastWin32Error()).Message;
}
uint result = Win32DwmEnableComposition(DWM_EC_DISABLECOMPOSITION);
if (result != 0)
{
String err = new Win32Exception(Marshal.GetLastWin32Error()).Message;
}
}
</code></pre>
|
[
{
"answer_id": 280498,
"author": "OJ.",
"author_id": 611,
"author_profile": "https://Stackoverflow.com/users/611",
"pm_score": 1,
"selected": false,
"text": "<p>I dont know for certain, but perhaps you need to associate your service's process with the current desktop before that will work?</p>\n\n<p>Make sure that your service can interact with the desktop. Then use <a href=\"http://msdn.microsoft.com/en-us/library/ms686250(VS.85).aspx\" rel=\"nofollow noreferrer\">SetThreadDesktop()</a> to set the desktop for the service thread passing in a handle to the desktop called \"Default\".</p>\n\n<p>I haven't tried it, and I can't guarantee it'll work. But it might be something to try?</p>\n\n<p>Good luck :)</p>\n"
},
{
"answer_id": 1211167,
"author": "Thies",
"author_id": 41639,
"author_profile": "https://Stackoverflow.com/users/41639",
"pm_score": 3,
"selected": true,
"text": "<p>I had the same error code, when creating WPF FlowDocuments through a service running under 64-bit Vista. After digging around I can accross <a href=\"https://connect.microsoft.com/VisualStudio/feedback/ViewFeedback.aspx?FeedbackID=361469\" rel=\"nofollow noreferrer\">this post on Microsoft Connect</a>, which points out that </p>\n\n<blockquote>\n <p>\"... The problem is caused by an interop problem with the DWM ...\"</p>\n</blockquote>\n\n<p>and</p>\n\n<blockquote>\n <p>\"... it will fix the WPF crash in all\n services including IIS7 ...\"</p>\n</blockquote>\n\n<p>Here is the direct link to the hot-fix downloads; <a href=\"http://support.microsoft.com/kb/959209\" rel=\"nofollow noreferrer\">KB 959209</a> </p>\n\n<p>This fixed our problems with running unit tests through CruiseControl.Net (CCNet) running 64-bit Vista. The tests where fine when not running through a service.</p>\n"
}
] |
2008/11/11
|
[
"https://Stackoverflow.com/questions/280480",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/21593/"
] |
I have some code to enable/disable the Windows Aero service in Vista, and I would like to run it in a Windows Service. The code works in a standalone application, but when I run it from a Service, nothing happens. No errors or exceptions are thrown.
I realise that running code in a service is a different scope than running code in an application, but in this case, how would I enable/disable Aero from the service? Is this even possible?
Here is the code I am working with:
```
public static readonly uint DWM_EC_DISABLECOMPOSITION = 0;
public static readonly uint DWM_EC_ENABLECOMPOSITION = 1;
[DllImport("dwmapi.dll", EntryPoint="DwmEnableComposition")]
protected static extern uint Win32DwmEnableComposition(uint uCompositionAction);
public static bool EnableAero()
{
Win32DwmEnableComposition(DWM_EC_ENABLECOMPOSITION);
}
```
Edit:
It turns out that the DwmEnableComposition call is returning HRESULT 0x80070018, or ERROR\_BAD\_LENGTH. Seems like a strange error, since the code works when not running as a service.
I also tried changing the entire thing to the following code, but got the same result. It sets the window station and desktop, and it seems to be correct, but the call to DwmEnableComposition results in the same error. I've not included the PInvoke declarations for brevity.
```
protected override void OnStop()
{
IntPtr winStation = OpenWindowStation("winsta0", true, 0x10000000 /* GENERIC_ALL */);
if (winStation == null || winStation.ToInt32() == 0)
{
String err = new Win32Exception(Marshal.GetLastWin32Error()).Message;
}
if (!SetProcessWindowStation(winStation))
{
String err = new Win32Exception(Marshal.GetLastWin32Error()).Message;
}
uint thread = GetCurrentThreadId();
IntPtr hdesk = OpenInputDesktop(0, false, 0x10000000 /* GENERIC_ALL */);
if (hdesk == null || hdesk.ToInt32() == 0)
{
String err = new Win32Exception(Marshal.GetLastWin32Error()).Message;
}
if (!SetThreadDesktop(hdesk))
{
String err = new Win32Exception(Marshal.GetLastWin32Error()).Message;
}
uint result = Win32DwmEnableComposition(DWM_EC_DISABLECOMPOSITION);
if (result != 0)
{
String err = new Win32Exception(Marshal.GetLastWin32Error()).Message;
}
}
```
|
I had the same error code, when creating WPF FlowDocuments through a service running under 64-bit Vista. After digging around I can accross [this post on Microsoft Connect](https://connect.microsoft.com/VisualStudio/feedback/ViewFeedback.aspx?FeedbackID=361469), which points out that
>
> "... The problem is caused by an interop problem with the DWM ..."
>
>
>
and
>
> "... it will fix the WPF crash in all
> services including IIS7 ..."
>
>
>
Here is the direct link to the hot-fix downloads; [KB 959209](http://support.microsoft.com/kb/959209)
This fixed our problems with running unit tests through CruiseControl.Net (CCNet) running 64-bit Vista. The tests where fine when not running through a service.
|
280,485 |
<p>We have a DLL which is produced in house, and for which we have the associated static LIB of stubs.</p>
<p>We also have an EXE which uses this DLL using the simple method of statically linking to the DLL's LIB file (ie, not manually using LoadLibrary).</p>
<p>When we deploy the EXE we'd like the DLL file name to be changed for obfuscation reasons (at customer's request).</p>
<p><strong>How can we do this so that our EXE still finds the DLL automagically?</strong></p>
<p>I have tried renaming the DLL and LIB files (after they were built to their normal name), then changing the EXE project settings to link with the renamed LIB. This fails at runtime, as I guess the name of the DLL is baked into the LIB file, and not simply guessed at by the linker replacing ".lib" with ".dll".</p>
<p>In general, we do not want to apply this obfuscation to all uses of the DLL, so we'd like to keep the current DLL project output files are they are.</p>
<p>I'm hoping that there will be a method whereby we can edit the DLL's LIB file, and replace the hardcoded name of the DLL file with something else. In which case this could be done entirely within the EXE project (perhaps as a pre-build step).</p>
<hr>
<p><strong>Update</strong>: I find that Delay Loading does not work, as my DLL contains exported C++ classes.
See <a href="http://www.tech-archive.net/Archive/VC/microsoft.public.vc.language/2004-09/0377.html" rel="noreferrer">this article</a>.</p>
<p>Are there any alternatives?</p>
|
[
{
"answer_id": 280522,
"author": "Mladen Prajdic",
"author_id": 31345,
"author_profile": "https://Stackoverflow.com/users/31345",
"pm_score": -1,
"selected": false,
"text": "<p>you'll have to use Assembly.Load and have the obfuscated assembly name saved in the app.config.</p>\n\n<p>either that or use the same approach that plug-ins use. have a class in your assembly implement an interface that you search for from your app in every assembly in a certain directory. if found loat it. you'll of course have to not obfuscate the Interface name.</p>\n"
},
{
"answer_id": 280567,
"author": "wimh",
"author_id": 33499,
"author_profile": "https://Stackoverflow.com/users/33499",
"pm_score": 4,
"selected": false,
"text": "<p>Using the LIB tool (included with visual studio) you can generate a lib file from a def file. Asuming your dll source does not include a def file, you have to create one first. You can use dumpbin to assist you. For example: <code>dumpbin /exports ws2_32.dll</code></p>\n\n<p>In the output you see the names of the functions exported. Now create a def file like this:</p>\n\n<pre><code>LIBRARY WS2_32\nEXPORTS\n accept @1\n bind @2\n closesocket @3\n connect @4\n</code></pre>\n\n<p>The @number is the ordinal in the dumpbin output</p>\n\n<p>Use <code>LIB /MACHINE:x86 /def:ws2_32.def</code> to generete the lib file.</p>\n\n<p>Now you can easily modify the def file, and generate a new libfile each time you rename your dll.</p>\n\n<p>you can verify the libfile using dumpbin: <code>dumpbin /exports ws2_32.lib</code>. You should get the same output as the original lib file.</p>\n"
},
{
"answer_id": 281011,
"author": "QAZ",
"author_id": 14260,
"author_profile": "https://Stackoverflow.com/users/14260",
"pm_score": 4,
"selected": false,
"text": "<p>Here is a nice alternative approach: <strong>delay loading</strong>.</p>\n\n<p>When building your application, link it all as you would with the original DLL name (but set the origional dll to be delay loaded).</p>\n\n<p>You then deploy the DLL renamed as per your customers request.</p>\n\n<p>Your EXE will attempt to locate the DLL using the original name and not the renamed version so will fail, however with delay loading you can intercept this fail and load the renamed version yourself and then have the native windows loader resolve everything as if nothing changed.</p>\n\n<p>Read the article <a href=\"https://learn.microsoft.com/en-us/cpp/build/reference/linker-support-for-delay-loaded-dlls\" rel=\"nofollow noreferrer\">Linker Support for Delay-Loaded DLLs</a> and see the <a href=\"https://learn.microsoft.com/en-us/cpp/build/reference/calling-conventions-parameters-and-return-type#sample\" rel=\"nofollow noreferrer\">Delay Hook example</a>.</p>\n\n<p>Your delay hook might be something like below:</p>\n\n<pre><code>FARPROC WINAPI delayHook( unsigned dliNotify, PDelayLoadInfo pdli )\n{\n switch( dliNotify )\n {\n case dliNotePreLoadLibrary:\n if( strcmp( pdli->szDll, \"origional.dll\" ) == 0 )\n return (FARPROC)LoadLibrary( \"renamed.dll\" );\n break;\n default:\n return NULL;\n }\n\n return NULL;\n}\n</code></pre>\n"
},
{
"answer_id": 285867,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 3,
"selected": false,
"text": "<p>Is your customer drunk? Of all the crazy requirements in all the world ...</p>\n\n<p>Back in my glory days as a syphilitic madman midnight C++ programmer I used to add my DLLs to my .exe file as resources. Then at startup I'd unpack them and write them to the exe's directory. Your program can decide on the DLL filename at this point. Really go for the obfuscation thing - start with a random number, concatenate some Edward Lear poetry and xor it with your favourite German double-barrelled noun; should do for starters anyway. Then load the DLL using LoadLibrary().</p>\n\n<pre><code>enum ukOverwrite {dontOverwriteAnything = 0, overwriteWhateverPresent = 1};\nvoid unpackResource (ukOverwrite param1, int resourceID, const char* basePath, \nconst char* endFilename)\n{\n char* lpName = 0;\n lpName += resourceID;\n HRSRC MrResource = FindResource (0, lpName, \"file\");\n\n if (MrResource)\n {\n HGLOBAL loadedResource = LoadResource (0, MrResource);\n if (loadedResource)\n {\n void* lockedResource = LockResource (loadedResource);\n if (lockedResource)\n {\n DWORD size = SizeofResource (0, MrResource);\n if (size)\n {\n unsigned long creationDisposition = CREATE_NEW;\n if (param1 == overwriteWhateverPresent)\n creationDisposition = CREATE_ALWAYS;\n\n char filepath [MAX_PATH];\n strcpy (filepath, basePath);\n strcat (filepath, endFilename);\n HANDLE rabbit = CreateFile (filepath, GENERIC_WRITE, 0, 0, \ncreationDisposition, 0, 0);\n if (rabbit != INVALID_HANDLE_VALUE)\n {\n DWORD numBytesWritten = 0;\n int wf = WriteFile (rabbit, lockedResource, size, &numBytesWritten, \n0);\n CloseHandle (rabbit);\n }\n }\n }\n FreeResource (loadedResource);\n }\n }\n}\n</code></pre>\n"
},
{
"answer_id": 2386595,
"author": "Woods",
"author_id": 287111,
"author_profile": "https://Stackoverflow.com/users/287111",
"pm_score": 0,
"selected": false,
"text": "<ol>\n<li>Use LoadLibrary (Read new name from registry) is one option.</li>\n<li>You can rename your visual studio project to have a generalised name (which your customer has no objection).</li>\n<li>The DLL itself needs to be renamed. But the lib still carries the old name? Did you cross verify using DUMPBIN /ALL *.lib > file. grep for the old DLL name. Is it still there?\nCheck *.def file in the project. Did you rename the LIBRARY \"OLDNAME\"</li>\n</ol>\n\n<p>Otherwise, there is no reason for the LIB to carry old DLL name.</p>\n"
},
{
"answer_id": 48969192,
"author": "Chris Berry",
"author_id": 2258710,
"author_profile": "https://Stackoverflow.com/users/2258710",
"pm_score": 3,
"selected": false,
"text": "<p>I created a little python script to rename native dlls properly. It generates a new lib file for you to use in project linking in MSVC.</p>\n\n<p><a href=\"https://github.com/cmberryau/rename_dll/blob/master/rename_dll.py\" rel=\"noreferrer\">https://github.com/cmberryau/rename_dll/blob/master/rename_dll.py</a>.</p>\n\n<p>You'll need to use the developer command prompt for it to work of course.</p>\n"
}
] |
2008/11/11
|
[
"https://Stackoverflow.com/questions/280485",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/755/"
] |
We have a DLL which is produced in house, and for which we have the associated static LIB of stubs.
We also have an EXE which uses this DLL using the simple method of statically linking to the DLL's LIB file (ie, not manually using LoadLibrary).
When we deploy the EXE we'd like the DLL file name to be changed for obfuscation reasons (at customer's request).
**How can we do this so that our EXE still finds the DLL automagically?**
I have tried renaming the DLL and LIB files (after they were built to their normal name), then changing the EXE project settings to link with the renamed LIB. This fails at runtime, as I guess the name of the DLL is baked into the LIB file, and not simply guessed at by the linker replacing ".lib" with ".dll".
In general, we do not want to apply this obfuscation to all uses of the DLL, so we'd like to keep the current DLL project output files are they are.
I'm hoping that there will be a method whereby we can edit the DLL's LIB file, and replace the hardcoded name of the DLL file with something else. In which case this could be done entirely within the EXE project (perhaps as a pre-build step).
---
**Update**: I find that Delay Loading does not work, as my DLL contains exported C++ classes.
See [this article](http://www.tech-archive.net/Archive/VC/microsoft.public.vc.language/2004-09/0377.html).
Are there any alternatives?
|
Using the LIB tool (included with visual studio) you can generate a lib file from a def file. Asuming your dll source does not include a def file, you have to create one first. You can use dumpbin to assist you. For example: `dumpbin /exports ws2_32.dll`
In the output you see the names of the functions exported. Now create a def file like this:
```
LIBRARY WS2_32
EXPORTS
accept @1
bind @2
closesocket @3
connect @4
```
The @number is the ordinal in the dumpbin output
Use `LIB /MACHINE:x86 /def:ws2_32.def` to generete the lib file.
Now you can easily modify the def file, and generate a new libfile each time you rename your dll.
you can verify the libfile using dumpbin: `dumpbin /exports ws2_32.lib`. You should get the same output as the original lib file.
|
280,488 |
<p>I'm looking to convert the following <code>mod_rewrite</code> rule to the <a href="http://wiki.codemongers.com/NginxHttpRewriteModule" rel="noreferrer">Nginx equivalent</a>:</p>
<pre><code>RewriteRule ^foo/(.*)$ /bar/index.php?title=$1 [PT,L,QSA]
RewriteRule ^foo/*$ /bar/index.php [L,QSA]
</code></pre>
<p>So far I have:</p>
<pre><code>rewrite ^foo/(.*)$ /bar/index.php?title=$1&$query_string last;
rewrite ^foo/?$ /bar/index.php?$query_string break;
</code></pre>
<p>The problem is (I think!) that the query string doesn't get appended. I haven't found a way to port the <code>QSA</code> argument to Nginx.</p>
|
[
{
"answer_id": 282437,
"author": "jumoel",
"author_id": 1555170,
"author_profile": "https://Stackoverflow.com/users/1555170",
"pm_score": 4,
"selected": true,
"text": "<p>These rewrite rules made the scripts work:</p>\n\n<pre><code>rewrite ^/foo/([^?]*)(?:\\?(.*))? /bar/index.php?title=$1&$2;\nrewrite ^/foo /bar/index.php;\n</code></pre>\n"
},
{
"answer_id": 410843,
"author": "Mikeage",
"author_id": 41308,
"author_profile": "https://Stackoverflow.com/users/41308",
"pm_score": 4,
"selected": false,
"text": "<p>QSA is automatic in NGINX. </p>\n\n<p>If you don't want it, add ? to the end of your new location</p>\n\n<p>rewrite ^/foo /bar/index.php? last;</p>\n"
}
] |
2008/11/11
|
[
"https://Stackoverflow.com/questions/280488",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1555170/"
] |
I'm looking to convert the following `mod_rewrite` rule to the [Nginx equivalent](http://wiki.codemongers.com/NginxHttpRewriteModule):
```
RewriteRule ^foo/(.*)$ /bar/index.php?title=$1 [PT,L,QSA]
RewriteRule ^foo/*$ /bar/index.php [L,QSA]
```
So far I have:
```
rewrite ^foo/(.*)$ /bar/index.php?title=$1&$query_string last;
rewrite ^foo/?$ /bar/index.php?$query_string break;
```
The problem is (I think!) that the query string doesn't get appended. I haven't found a way to port the `QSA` argument to Nginx.
|
These rewrite rules made the scripts work:
```
rewrite ^/foo/([^?]*)(?:\?(.*))? /bar/index.php?title=$1&$2;
rewrite ^/foo /bar/index.php;
```
|
280,494 |
<p>I have a group by clause in a sql statement and need to use an aggregate function to minus all the values in each group instead of adding like the Sum() function.</p>
<p>i.e. </p>
<pre><code>SELECT Sum(A)
FROM (
SELECT 2 AS A
UNION
SELECT 1) AS t1
</code></pre>
<p>..so will evaluate 2+1 and return 3.</p>
<p>I need some way of doing 2-1 to return 1.</p>
<p>Hope this makes sense. Only way I can think of doing this would be to use CLR integration to make my own aggregate function.</p>
<p>Any other ideas?</p>
|
[
{
"answer_id": 280496,
"author": "Unsliced",
"author_id": 2902,
"author_profile": "https://Stackoverflow.com/users/2902",
"pm_score": 2,
"selected": false,
"text": "<p>How will you identify the item to be subtracted from? </p>\n\n<p>Once that's been identified it's a <code>SUM()</code> multiplied by <code>-1</code> and then added to that value.</p>\n\n<p><strong>Edit:</strong> </p>\n\n<p>If it's the first value to be taken as the subtracted from then take that value, double it, then take away the sum of all the values. (Doubling it cancels out the effect of including it in the sum of all the values.) </p>\n\n<pre><code>select top 1 @var = [value]\nfrom myTable \norder by [some condition] \n\nselect @minused = (2 * @var) - sum([value]) \nfrom myTable \n</code></pre>\n"
},
{
"answer_id": 280499,
"author": "harriyott",
"author_id": 5744,
"author_profile": "https://Stackoverflow.com/users/5744",
"pm_score": 0,
"selected": false,
"text": "<p>SUM() works, as 2+1 == 1+2, whereas 2-1 != 1-2, so such a function would produce different results when the ORDER BY changes, if it were to exist.</p>\n"
},
{
"answer_id": 280503,
"author": "FlySwat",
"author_id": 1965,
"author_profile": "https://Stackoverflow.com/users/1965",
"pm_score": 0,
"selected": false,
"text": "<p>I'm not sure WHY you'd want this, but I'd just SUM the negative values of the data returned:</p>\n\n<pre><code>SELECT Sum(A) \nFROM ( \n SELECT (2 * -1) AS A\n UNION \n SELECT (1)) AS t1\n</code></pre>\n"
},
{
"answer_id": 280546,
"author": "Ben Dowling",
"author_id": 36191,
"author_profile": "https://Stackoverflow.com/users/36191",
"pm_score": 2,
"selected": false,
"text": "<p>From your question it isn't exactly clear what you want to do. If you want the sum of all the values as if they were negative then you can just perform a SUM(), and multiply by -1 to return a negative result.</p>\n\n<p>In your example it looks like you want to get the sum of the first row in the table, minus all the other values. So if you had the values 10, 15, 5, 20 you'd want: 10 - 15 - 5 - 20. This value is the same as 10 - (15 + 5 + 20). You can get the first row in a table using LIMIT. We'll also need the primary key for the next stage:</p>\n\n<pre><code>SELECT primary_key AS pk, field FROM table LIMIT 1;\n</code></pre>\n\n<p>We can get the sum of all the other rows by excluding the above one:</p>\n\n<pre><code>SELECT SUM(field) FROM table WHERE primary_key != pk;\n</code></pre>\n\n<p>You can then subtract the second value from the first.</p>\n"
},
{
"answer_id": 281080,
"author": "Steve Bosman",
"author_id": 4389,
"author_profile": "https://Stackoverflow.com/users/4389",
"pm_score": 2,
"selected": false,
"text": "<p>Reading your comments, I think you want something like this:</p>\n\n<pre><code>SELECT SUM(CASE WHEN ROWNUM=1 THEN 2*A ELSE -A END) \nFROM foo\n</code></pre>\n\n<p>Although to get reliable ordering you're probably going to need to use another select:</p>\n\n<pre><code>SELECT SUM(b) \nFROM (\n SELECT CASE WHEN ROWNUM=1 THEN 2*a ELSE -a END AS b\n FROM foo\n ORDER BY ???\n);\n</code></pre>\n"
}
] |
2008/11/11
|
[
"https://Stackoverflow.com/questions/280494",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11989/"
] |
I have a group by clause in a sql statement and need to use an aggregate function to minus all the values in each group instead of adding like the Sum() function.
i.e.
```
SELECT Sum(A)
FROM (
SELECT 2 AS A
UNION
SELECT 1) AS t1
```
..so will evaluate 2+1 and return 3.
I need some way of doing 2-1 to return 1.
Hope this makes sense. Only way I can think of doing this would be to use CLR integration to make my own aggregate function.
Any other ideas?
|
How will you identify the item to be subtracted from?
Once that's been identified it's a `SUM()` multiplied by `-1` and then added to that value.
**Edit:**
If it's the first value to be taken as the subtracted from then take that value, double it, then take away the sum of all the values. (Doubling it cancels out the effect of including it in the sum of all the values.)
```
select top 1 @var = [value]
from myTable
order by [some condition]
select @minused = (2 * @var) - sum([value])
from myTable
```
|
280,495 |
<p>When browsing ASP.NET MVC source code in <a href="http://www.codeplex.com/aspnet/SourceControl/FileView.aspx?itemId=266503&changeSetId=17272" rel="noreferrer">codeplex</a>, I found it is common to have a class explicitly implementing interface. The explicitly implemented method/property then invoke another "protected virtual" method/property with same name.</p>
<p>For example, </p>
<pre><code>public class MvcHandler : IHttpHandler, IRequiresSessionState
{
protected virtual bool IsReusable
{
get
{
return false;
}
}
bool IHttpHandler.IsReusable
{
get
{
return IsReusable;
}
}
}
</code></pre>
<p>I'm now sure what's the benefit of this kind of programming. For me, I prefer to just implicitly implement the interface IHttpHandler.</p>
<p>I guess the author just don't want <strong>MvcHandler</strong> has a public property <strong>IsResuable</strong>. The property <strong>IsReusable</strong> can only be used when instance of <strong>MvcHandler</strong> is treated as a <strong>IHttpHandler</strong>. Still, I'm not sure why the author what this way.</p>
<p>Anybody know more benefits about this style of interface implementation?</p>
|
[
{
"answer_id": 280505,
"author": "Marc Gravell",
"author_id": 23354,
"author_profile": "https://Stackoverflow.com/users/23354",
"pm_score": 5,
"selected": true,
"text": "<p>Well, not specific to MVC, but this approach allows you to <strong>keep the core public API clean</strong>. It is also useful if there is ever a risk of different interfaces / etc having the same name & signature, but different meaning. In reality this is rare.</p>\n\n<p>It also allows you to provide an implementation where you want the return type to change in subclasses:</p>\n\n<p>(<code>ICloneable</code> chosen for simplicity - don't get hung up on the fact that it is a poorly defined interface... a better example would have been things like <code>DbCommand</code> etc, which do this - but that is harder to show in a short example)</p>\n\n<pre><code>class Foo : ICloneable\n{\n public Foo Clone() { return CloneCore(); }\n object ICloneable.Clone() { return CloneCore(); }\n protected virtual Foo CloneCore() { ... }\n}\n\nclass Bar : Foo\n{\n protected override Foo CloneCore() { ... }\n public new Bar Clone() { return (Bar)CloneCore(); }\n}\n</code></pre>\n\n<p>If we had used a public virtual method, we wouldn't be able to <code>override</code> it <em>and</em> use <code>new</code> in the base-class, as you aren't allowed to do both:</p>\n\n<pre><code>class A\n{\n public virtual A SomeMethod() { ... }\n}\nclass B : A\n{\n public override A SomeMethod() { ... }\n //Error 1 Type 'B' already defines a member called 'SomeMethod' with the same parameter types\n public new B SomeMethod() { ... }\n}\n</code></pre>\n\n<p>Using the protected virtual approach, any usage:</p>\n\n<ul>\n<li>Foo.Clone()</li>\n<li>Bar.Clone()</li>\n<li>ICloneable.Clone()</li>\n</ul>\n\n<p>all use the correct <code>CloneCore()</code> implementation for the concrete type.</p>\n"
},
{
"answer_id": 12096386,
"author": "Mohammad Nikravan",
"author_id": 252229,
"author_profile": "https://Stackoverflow.com/users/252229",
"pm_score": 1,
"selected": false,
"text": "<ol>\n<li>When a member is explicitly implemented, it cannot be accessed through a class instance, but only through an instance of the interface. reference : <a href=\"http://msdn.microsoft.com/en-us/library/aa288461%28v=vs.71%29.aspx\" rel=\"nofollow\">Explicit Interface Implementation Tutorial</a></li>\n<li>As my experience if interface implementer explicitly implement an interface he will receive compiler error after you drop a method from interface while he will not notify if he/she implicitly implement it and the method will remain in the code.</li>\n</ol>\n\n<p>sample for reason 1:\n</p>\n\n<pre><code>public interface IFoo\n{\n void method1();\n void method2();\n}\n\npublic class Foo : IFoo\n{\n // you can't declare explicit implemented method as public\n void IFoo.method1() \n {\n }\n\n public void method2()\n {\n }\n\n private void test()\n {\n var foo = new Foo();\n foo.method1(); //ERROR: not accessible because foo is object instance\n method1(); //ERROR: not accessible because foo is object instance\n foo.method2(); //OK\n method2(); //OK\n\n IFoo ifoo = new Foo();\n ifoo.method1(); //OK, because ifoo declared as interface\n ifoo.method2(); //OK\n }\n}\n</code></pre>\n"
},
{
"answer_id": 14185580,
"author": "supercat",
"author_id": 363751,
"author_profile": "https://Stackoverflow.com/users/363751",
"pm_score": 2,
"selected": false,
"text": "<p>If a class implements <code>IFoo.Bar</code> explicitly, and a derived class needs <code>IFoo.Bar</code> to do something different, there will be no way for the derived class to call the base-class implementation of that method. A derived class which does not re-implement <code>IFoo.Bar</code> could call the base-class implementation via <code>((IFoo)this).Bar()</code>, but if the derived class re-implements <code>IFoo.Bar</code> (as it would have to in order to change its behavior) the aforementioned call would go to the derived-class re-implementation, rather than the base-class implementation. Even <code>((IFoo)(BaseType)this).bar</code> wouldn't help, since casting a reference to an interface type will discard any information about the type of the reference (as opposed to the type of the instance instance) that was cast.</p>\n\n<p>Having an explicit interface implementation do nothing but call a protected method avoids this problem, since a derived class can change the behavior of the interface method by overriding the virtual method, while retaining the ability to call the base implementation as it sees fit. IMHO, C# should have had an explicit interface implementation produce a virtual method with a CLS-compliant name, so someone writing in C# a derivative of a class that explicitly implemented <code>IFoo.Bar</code> could say <code>override void IFoo.Bar</code>, and someone writing in some other language could say, e.g. <code>Overrides Sub Explicit_IFoo_Bar()</code>; since any derived class can re-implement <code>IFoo.Bar</code>, and since any derived class which doesn't re-implement <code>IFoo.Bar</code> can call it on itself, I don't see that there's any useful purpose to having the explicit implementation be sealed.</p>\n\n<p>Incidentally, in vb.net, the normal pattern would simply be <code>Protected Overridable Sub IFoo_Bar() Implements IFoo.Bar</code>, without need for a separate virtual method.</p>\n"
}
] |
2008/11/11
|
[
"https://Stackoverflow.com/questions/280495",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/26349/"
] |
When browsing ASP.NET MVC source code in [codeplex](http://www.codeplex.com/aspnet/SourceControl/FileView.aspx?itemId=266503&changeSetId=17272), I found it is common to have a class explicitly implementing interface. The explicitly implemented method/property then invoke another "protected virtual" method/property with same name.
For example,
```
public class MvcHandler : IHttpHandler, IRequiresSessionState
{
protected virtual bool IsReusable
{
get
{
return false;
}
}
bool IHttpHandler.IsReusable
{
get
{
return IsReusable;
}
}
}
```
I'm now sure what's the benefit of this kind of programming. For me, I prefer to just implicitly implement the interface IHttpHandler.
I guess the author just don't want **MvcHandler** has a public property **IsResuable**. The property **IsReusable** can only be used when instance of **MvcHandler** is treated as a **IHttpHandler**. Still, I'm not sure why the author what this way.
Anybody know more benefits about this style of interface implementation?
|
Well, not specific to MVC, but this approach allows you to **keep the core public API clean**. It is also useful if there is ever a risk of different interfaces / etc having the same name & signature, but different meaning. In reality this is rare.
It also allows you to provide an implementation where you want the return type to change in subclasses:
(`ICloneable` chosen for simplicity - don't get hung up on the fact that it is a poorly defined interface... a better example would have been things like `DbCommand` etc, which do this - but that is harder to show in a short example)
```
class Foo : ICloneable
{
public Foo Clone() { return CloneCore(); }
object ICloneable.Clone() { return CloneCore(); }
protected virtual Foo CloneCore() { ... }
}
class Bar : Foo
{
protected override Foo CloneCore() { ... }
public new Bar Clone() { return (Bar)CloneCore(); }
}
```
If we had used a public virtual method, we wouldn't be able to `override` it *and* use `new` in the base-class, as you aren't allowed to do both:
```
class A
{
public virtual A SomeMethod() { ... }
}
class B : A
{
public override A SomeMethod() { ... }
//Error 1 Type 'B' already defines a member called 'SomeMethod' with the same parameter types
public new B SomeMethod() { ... }
}
```
Using the protected virtual approach, any usage:
* Foo.Clone()
* Bar.Clone()
* ICloneable.Clone()
all use the correct `CloneCore()` implementation for the concrete type.
|
280,497 |
<p>I am having a peculiar problem with the order in which FlowLayoutPanels are added in to the form's <strong>controls</strong> property. This is what I tried,</p>
<p>I added 7 FlowLayoutPanels in to a C# window application from left to right in vertical strips. Then I tagged the flow layouts as 1, 2, 3, ... 7 again from left to right. Now in the load handler of the form, I wrote the following snippet,</p>
<pre><code> foreach (FlowLayoutPanel aDaysControl in this.Controls)
{
MessageBox.Show(aDaysControl.Tag.ToString());
}
</code></pre>
<p>I expected messages to appear in the order of <strong>1, 2, ... 7</strong>. But I got it in the reverse order (7, 6, ...1). Could some one help me out with the mistake I did ??</p>
<p>Reason behind preserving the order,</p>
<blockquote>
<p>I am trying to make a calendar control
with each row representing a day. If a
month starts from Wednesday, then I
need to add a empty label to the
first(Monday) and the second(Tuesday)
row. So the order matters a bit</p>
</blockquote>
|
[
{
"answer_id": 280513,
"author": "Mladen Prajdic",
"author_id": 31345,
"author_profile": "https://Stackoverflow.com/users/31345",
"pm_score": 3,
"selected": true,
"text": "<p>look at the order in which they are added to the form in the yourForm.designer.cs</p>\n"
},
{
"answer_id": 280517,
"author": "Steve Morgan",
"author_id": 5806,
"author_profile": "https://Stackoverflow.com/users/5806",
"pm_score": 0,
"selected": false,
"text": "<p>Is it really a problem?</p>\n\n<p>As long as the UI operates correctly (in terms of tab order, for example), I'd recommend that you don't make any assumptions about the order in which they're enumerated.</p>\n\n<p>EDIT: Thanks for explaining your requirement in more detail. I think I'd still recommend against using the order that they're stored in the Controls collection. It's always best to consider these implementation details to be 'opaque'. You have a tag associated with each control, so you can use this to identify the correct control. In order to speed up the processing, you could build a 7-element array that references the controls by ordinal:</p>\n\n<pre><code>FlowLayoutPanel[] panels = new FlowLayoutPanel[7];\n\nforeach(FlowLayoutPanel panel in this.Controls)\n{\n panels[(int)panel.Tag] = panel;\n}\n\n// Now, you can reference the panels directly by subscript:\n\npanels[2].BackColor = Color.Aquamarine;\n</code></pre>\n\n<p>Though I'd put some type-checking in to make this code a bit more robust!</p>\n"
},
{
"answer_id": 280525,
"author": "Hath",
"author_id": 5186,
"author_profile": "https://Stackoverflow.com/users/5186",
"pm_score": 1,
"selected": false,
"text": "<p>if you look at the code generated by the designer Form1.designer.cs it will look something like this:</p>\n\n<pre><code> // \n // Form1\n // \n this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F);\n this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;\n this.ClientSize = new System.Drawing.Size(658, 160);\n this.Controls.Add(this.flowLayoutPanel7);\n this.Controls.Add(this.flowLayoutPanel6);\n this.Controls.Add(this.flowLayoutPanel5);\n this.Controls.Add(this.flowLayoutPanel4);\n this.Controls.Add(this.flowLayoutPanel3);\n this.Controls.Add(this.flowLayoutPanel2);\n this.Controls.Add(this.flowLayoutPanel1);\n this.Name = \"Form1\";\n this.Text = \"Form1\";\n this.ResumeLayout(false);\n</code></pre>\n\n<p>note how it was built up you added panel 1 first then 2 etc.\nbut as the code runs through it will add 7 first then 6.</p>\n\n<p>this code will be in the InitializeComponent() function generated by the designer.</p>\n\n<p>Why do you need them to run in a certain order?</p>\n\n<p>I wouldn't rely on the designer to keep the order you want.. i would sort the controls my self:</p>\n\n<pre><code> var flowpanelinOrder = from n in this.Controls.Cast<Control>()\n where n is FlowLayoutPanel\n orderby int.Parse(n.Tag.ToString())\n select n;\n\n /* non linq\n List<Control> flowpanelinOrder = new List<Control>();\n foreach (Control c in this.Controls)\n {\n if (c is FlowLayoutPanel) flowpanelinOrder.Add(c); \n }\n flowpanelinOrder.Sort();\n * */\n\n foreach (FlowLayoutPanel aDaysControl in flowpanelinOrder)\n {\n MessageBox.Show(aDaysControl.Tag.ToString());\n }\n</code></pre>\n"
},
{
"answer_id": 8157734,
"author": "ispiro",
"author_id": 939213,
"author_profile": "https://Stackoverflow.com/users/939213",
"pm_score": 4,
"selected": false,
"text": "<p>I know this is quite an old question, but...</p>\n\n<p>You might want to use <code>SetChildIndex</code>. e.g. <code>this.Controls.SetChildIndex(button1, 0);</code></p>\n"
},
{
"answer_id": 12167665,
"author": "nawfal",
"author_id": 661933,
"author_profile": "https://Stackoverflow.com/users/661933",
"pm_score": 1,
"selected": false,
"text": "<p>What if in future some other designer removed the controls, added back etc? Checking the designer always is a mess. What would be better is to sort the controls in the container control before you enumerate. I use this extension method (if you have Linq):</p>\n\n<pre><code>public static List<Control> ToControlsSorted(this Control panel)\n{\n var controls = panel.Controls.OfType<Control>().ToList();\n controls.Sort((c1, c2) => c1.TabIndex.CompareTo(c2.TabIndex));\n return controls;\n}\n</code></pre>\n\n<p>And you can: </p>\n\n<pre><code>foreach (FlowLayoutPanel aDaysControl in this.ToControlsSorted())\n{\n MessageBox.Show(aDaysControl.TabIndex.ToString());\n}\n</code></pre>\n\n<p>(Above is for <code>TabIndex</code>). Would be trivial to sort according to <code>Tag</code> from that.</p>\n"
}
] |
2008/11/11
|
[
"https://Stackoverflow.com/questions/280497",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] |
I am having a peculiar problem with the order in which FlowLayoutPanels are added in to the form's **controls** property. This is what I tried,
I added 7 FlowLayoutPanels in to a C# window application from left to right in vertical strips. Then I tagged the flow layouts as 1, 2, 3, ... 7 again from left to right. Now in the load handler of the form, I wrote the following snippet,
```
foreach (FlowLayoutPanel aDaysControl in this.Controls)
{
MessageBox.Show(aDaysControl.Tag.ToString());
}
```
I expected messages to appear in the order of **1, 2, ... 7**. But I got it in the reverse order (7, 6, ...1). Could some one help me out with the mistake I did ??
Reason behind preserving the order,
>
> I am trying to make a calendar control
> with each row representing a day. If a
> month starts from Wednesday, then I
> need to add a empty label to the
> first(Monday) and the second(Tuesday)
> row. So the order matters a bit
>
>
>
|
look at the order in which they are added to the form in the yourForm.designer.cs
|
280,542 |
<p>I'm regularly creating an XSD schema by transforming a proprietary data model of a legacy system. This works out pretty good. However, the legacy system only allows me to specify very basic attributes of a parameter, such as the data type (<code>int</code>, <code>string</code> etc.).</p>
<p>I would like to enhance the XSL transformation with a mechanism that allows me to add meta data in order to provide more details for the transformation. I thought of something like the Java properties notation to assign attributes to an XPath. </p>
<p>Imagine the following example:</p>
<p><strong>legacy system data model</strong> (actually that neat, but best suited for demonstration purposes)</p>
<pre><code><datamodel>
<customer>
<firstName type="string"/>
<lastName type="string"/>
<age type="int">
<customer>
</datamodel>
</code></pre>
<p><strong>meta data</strong></p>
<pre><code>customer/firstName/@nillable=false
customer/lastName/@nillable=false
customer/age/@nillable=true
customer/firstName/@minOccurs=1
customer/firstName/@maxOccurs=1
customer/lastName/@minOccurs=1
customer/lastName/@maxOccurs=1
</code></pre>
<p><strong>resulting XSD schema</strong></p>
<pre><code>...
<xs:complexType name="customerType">
<xs:sequence>
<xs:element name="firstName" type="xs:string" nillable="false" minOccurs="1" maxOccurs="1"/>
<xs:element name="lastName" type="xs:string" nillable="false" minOccurs="1" maxOccurs="1"/>
<xs:element name="age" type="xs:int" nillable="true"/>
</xs:sequence>
</xs:complexType>
...
</code></pre>
<p>What do you think of that? Is there a way to include meta data into an XSL stylesheet?</p>
|
[
{
"answer_id": 280728,
"author": "S.Lott",
"author_id": 10661,
"author_profile": "https://Stackoverflow.com/users/10661",
"pm_score": 1,
"selected": false,
"text": "<p>\"What do you think of that?\"</p>\n\n<p><strike>Two</strike>Three things.</p>\n\n<ol>\n<li><p>Fix the legacy metadata. It's XML. Add stuff to it. Add a namespace if you have to.</p></li>\n<li><p>If you can't fix the legacy metadata, who will maintaint he second set of metadata that isn't in XML notation? Who will do the double-entry of making a metadata change? What are the odds of anyone following through?</p></li>\n<li><p>Consider using XML for the additional metadata, not pseudo-XPath. Consistency will help those that come after you figure out what's going on.</p></li>\n</ol>\n"
},
{
"answer_id": 286272,
"author": "Dimitre Novatchev",
"author_id": 36305,
"author_profile": "https://Stackoverflow.com/users/36305",
"pm_score": 3,
"selected": true,
"text": "<p>The best solution would be to modify the legacy data by adding the missing metadata. </p>\n\n<p>An instance of the modified \"datamodel\" vocabulary may be something like this:</p>\n\n<pre><code><datamodel xmlns:nm=\"my:new.meta\">\n <customer>\n <firstName type=\"string\"\n nm:nillable=\"false\"\n nm:minOccurs=\"1\"\n nm:maxOccurs=\"1\"\n />\n <lastName type=\"string\"\n nm:nillable=\"false\"\n nm:minOccurs=\"1\"\n nm:maxOccurs=\"1\"\n />\n <age type=\"int\" nm:nillable=\"true\"/>\n </customer>\n</datamodel>\n</code></pre>\n\n<p>Putting the new properties in a separate namespace is a good way to easily distinguish them from the already supported properties. Usually using attributes in a namespace is not recommended, so if this is to be avoided, one could use sub-elements (belonging to the new namespace) instead of attributes. Making the new attributes belong to a different namespace may result in the legacy schema validation not to reject them.</p>\n\n<p>If due to some reasons it is not possible to modify the legacy data, I would recommend not to include the new properties in the XSLT stylesheet itself (this is perfectly possible, for example as defining this as the contents of a global <code><xsl:variable></code>), but to provide these new properties as a separate XML file or as a set of one ore more XML files.</p>\n\n<p>Any XML file may be accessed dynamically during an XSLT transformation using the XSLT document() function. An instance of the XML file with the new properties may look like this:</p>\n\n<pre><code><newProperties xmlns:nm=\"my:new.meta\">\n <customer>\n <firstName nm:nillable=\"false\"\n nm:minOccurs=\"1\"\n nm:maxOccurs=\"1\"\n />\n <lastName nm:nillable=\"false\"\n nm:minOccurs=\"1\"\n nm:maxOccurs=\"1\"\n />\n <age nm:nillable=\"true\"/>\n </customer>\n</newProperties>\n</code></pre>\n\n<p>Hope this helped.</p>\n\n<p>Cheers,</p>\n\n<p>Dimitre Novatchev</p>\n"
}
] |
2008/11/11
|
[
"https://Stackoverflow.com/questions/280542",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/25842/"
] |
I'm regularly creating an XSD schema by transforming a proprietary data model of a legacy system. This works out pretty good. However, the legacy system only allows me to specify very basic attributes of a parameter, such as the data type (`int`, `string` etc.).
I would like to enhance the XSL transformation with a mechanism that allows me to add meta data in order to provide more details for the transformation. I thought of something like the Java properties notation to assign attributes to an XPath.
Imagine the following example:
**legacy system data model** (actually that neat, but best suited for demonstration purposes)
```
<datamodel>
<customer>
<firstName type="string"/>
<lastName type="string"/>
<age type="int">
<customer>
</datamodel>
```
**meta data**
```
customer/firstName/@nillable=false
customer/lastName/@nillable=false
customer/age/@nillable=true
customer/firstName/@minOccurs=1
customer/firstName/@maxOccurs=1
customer/lastName/@minOccurs=1
customer/lastName/@maxOccurs=1
```
**resulting XSD schema**
```
...
<xs:complexType name="customerType">
<xs:sequence>
<xs:element name="firstName" type="xs:string" nillable="false" minOccurs="1" maxOccurs="1"/>
<xs:element name="lastName" type="xs:string" nillable="false" minOccurs="1" maxOccurs="1"/>
<xs:element name="age" type="xs:int" nillable="true"/>
</xs:sequence>
</xs:complexType>
...
```
What do you think of that? Is there a way to include meta data into an XSL stylesheet?
|
The best solution would be to modify the legacy data by adding the missing metadata.
An instance of the modified "datamodel" vocabulary may be something like this:
```
<datamodel xmlns:nm="my:new.meta">
<customer>
<firstName type="string"
nm:nillable="false"
nm:minOccurs="1"
nm:maxOccurs="1"
/>
<lastName type="string"
nm:nillable="false"
nm:minOccurs="1"
nm:maxOccurs="1"
/>
<age type="int" nm:nillable="true"/>
</customer>
</datamodel>
```
Putting the new properties in a separate namespace is a good way to easily distinguish them from the already supported properties. Usually using attributes in a namespace is not recommended, so if this is to be avoided, one could use sub-elements (belonging to the new namespace) instead of attributes. Making the new attributes belong to a different namespace may result in the legacy schema validation not to reject them.
If due to some reasons it is not possible to modify the legacy data, I would recommend not to include the new properties in the XSLT stylesheet itself (this is perfectly possible, for example as defining this as the contents of a global `<xsl:variable>`), but to provide these new properties as a separate XML file or as a set of one ore more XML files.
Any XML file may be accessed dynamically during an XSLT transformation using the XSLT document() function. An instance of the XML file with the new properties may look like this:
```
<newProperties xmlns:nm="my:new.meta">
<customer>
<firstName nm:nillable="false"
nm:minOccurs="1"
nm:maxOccurs="1"
/>
<lastName nm:nillable="false"
nm:minOccurs="1"
nm:maxOccurs="1"
/>
<age nm:nillable="true"/>
</customer>
</newProperties>
```
Hope this helped.
Cheers,
Dimitre Novatchev
|
280,551 |
<p>I try get the <a href="http://flash-mp3-player.net/players/js/" rel="nofollow noreferrer">mp3 flash player</a> to work with my javascript on all browsers. All went well for first, but fast realized that my code doesn't work on MSIE.</p>
<p>After trying to find out I found this in the reference code:</p>
<pre><code><!--[if IE]>
<script type="text/javascript" event="FSCommand(command,args)" for="myFlash">
eval(args);
</script>
<![endif]-->
</code></pre>
<p>How to turn this into a javascript or jquery clause that I could stuff it where it belongs to (in audio.js)?</p>
|
[
{
"answer_id": 281941,
"author": "Ben Combee",
"author_id": 1323,
"author_profile": "https://Stackoverflow.com/users/1323",
"pm_score": 3,
"selected": true,
"text": "<p>That syntax, with the <script> tag with the \"event\" and \"for\" attributes is an Internet Explorer-only way of setting up an event handler on an DOM object. Here, it adds a FSCommand event handler to the myFlash object. This is needed because code running inside the Flash object may want to run JavaScript in the browser. To do this, the Flash object will invoke the FSCommand event handler, passing the JavaScript to run as the arguments to the event.</p>\n\n<p>With this player, the name of a JS listener object is passed in the FlashVars param to the player. It then uses FSCommands from ActionScript to modify that listener object, with an occasional call to a method on that listener when it's other properties have been modified. I suppose that IE isn't able to run the JS code using this method until the FSCommand handler has been added to the Flash player object, which is why that code exists. Modify it to use the ID of your Flash object and you should be in good shape.</p>\n"
},
{
"answer_id": 4434557,
"author": "Troels",
"author_id": 541245,
"author_profile": "https://Stackoverflow.com/users/541245",
"pm_score": 1,
"selected": false,
"text": "<p>Maybe this is more about embedding flash dynamically.</p>\n\n<p>I got stuck on exactly the same thing with mp3 flash player. The thing is that IE doesn't care about the special script tag with 'event' and 'for' attribute, if it is added AFTER the page has loaded. My IE wouldn't event eat jquery's .html() when the page loaded, only document.write worked. But document.write can't really be used after the page has loaded, unless it is targeted in an iframe or some other devil worship mechanism.</p>\n\n<p>What's good tho, is that IE doesn't distinguish between assigning an event handler in this bastard script tag or programatically. This means that:</p>\n\n<pre><code><script type=\"text/javascript\" event=\"FSCommand(command,args)\" for=\"myFlash\">\n eval(args);\n</script>\n</code></pre>\n\n<p>in IE directly translates to:</p>\n\n<pre><code>function foo(command, args){\n eval(args);\n}\nvar ie_sucks = document.getElementById('myFlash');\nie_sucks.attachEvent(\"FSCommand\", foo);\n</code></pre>\n"
},
{
"answer_id": 6835723,
"author": "Eugene Bos",
"author_id": 792870,
"author_profile": "https://Stackoverflow.com/users/792870",
"pm_score": 1,
"selected": false,
"text": "<p>And... in the end we have that:</p>\n\n<pre><code>var ie_sucks = document.getElementById('comebacker_audio');\nie_sucks.attachEvent(\"FSCommand\", function(command, args) {eval(args);});\n</code></pre>\n\n<p>and if that not work for you, try to check your html for inserting object. Example here:\n<a href=\"http://kb2.adobe.com/cps/415/tn_4150.html\" rel=\"nofollow\">http://kb2.adobe.com/cps/415/tn_4150.html</a></p>\n\n<p>;)</p>\n"
},
{
"answer_id": 11035610,
"author": "Oliver Moran",
"author_id": 681800,
"author_profile": "https://Stackoverflow.com/users/681800",
"pm_score": 0,
"selected": false,
"text": "<p>Thanks everyone for the above. I'll just drop a few lines that were handy for me.</p>\n\n<p>To re-use code across browsers, do:</p>\n\n<pre><code><script type=\"text/javascript\">\n function mySwf_DoFSCommand(command, args) {\n // do stuff\n }\n</script>\n\n<!--[if IE]>\n<script type=\"text/javascript\" event=\"FSCommand(command,args)\" for=\"mySwf\">\n mySwf_DoFSCommand(command, args);\n</script>\n<![endif]-->\n</code></pre>\n"
}
] |
2008/11/11
|
[
"https://Stackoverflow.com/questions/280551",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/21711/"
] |
I try get the [mp3 flash player](http://flash-mp3-player.net/players/js/) to work with my javascript on all browsers. All went well for first, but fast realized that my code doesn't work on MSIE.
After trying to find out I found this in the reference code:
```
<!--[if IE]>
<script type="text/javascript" event="FSCommand(command,args)" for="myFlash">
eval(args);
</script>
<![endif]-->
```
How to turn this into a javascript or jquery clause that I could stuff it where it belongs to (in audio.js)?
|
That syntax, with the <script> tag with the "event" and "for" attributes is an Internet Explorer-only way of setting up an event handler on an DOM object. Here, it adds a FSCommand event handler to the myFlash object. This is needed because code running inside the Flash object may want to run JavaScript in the browser. To do this, the Flash object will invoke the FSCommand event handler, passing the JavaScript to run as the arguments to the event.
With this player, the name of a JS listener object is passed in the FlashVars param to the player. It then uses FSCommands from ActionScript to modify that listener object, with an occasional call to a method on that listener when it's other properties have been modified. I suppose that IE isn't able to run the JS code using this method until the FSCommand handler has been added to the Flash player object, which is why that code exists. Modify it to use the ID of your Flash object and you should be in good shape.
|
280,559 |
<p>This is probably easy but I am getting stuck: when I build a solution in Visual Studio - how do extract the exact cmd line for the current build command in order to be able to do the same build from VisualStudio console? </p>
<p>In the output window I can see the single projects in the solution build commands but not the one for the whole solution.</p>
<p>I am on VS2005.</p>
<p>Any help would be appreciated</p>
|
[
{
"answer_id": 280568,
"author": "Mendelt",
"author_id": 3320,
"author_profile": "https://Stackoverflow.com/users/3320",
"pm_score": 2,
"selected": false,
"text": "<p>You can start msbuild from the command line. msbuild understands .sln (solution) files. You can specify the .sln file and the build configuration (debug, release etc.) from the command line.</p>\n\n<p><a href=\"http://msdn.microsoft.com/en-us/library/ms164311.aspx\" rel=\"nofollow noreferrer\">http://msdn.microsoft.com/en-us/library/ms164311.aspx</a> <br>\nHere is the documentation on what you can do with msbuild. MSBuild.exe is installed with the .net framework, not with visual studio. You can find it in c:\\windows\\microsoft.net\\framework\\v3.5 (or v2.0.50727)</p>\n\n<p>I searched a bit and found that you can also do a command line build with visual studio using devenv.exe /build, more info here:<br>\n<a href=\"http://msdn.microsoft.com/en-us/library/xee0c8y7(VS.80).aspx\" rel=\"nofollow noreferrer\">http://msdn.microsoft.com/en-us/library/xee0c8y7(VS.80).aspx</a></p>\n"
},
{
"answer_id": 280584,
"author": "kenny",
"author_id": 3225,
"author_profile": "https://Stackoverflow.com/users/3225",
"pm_score": 5,
"selected": true,
"text": "<p>In addition to what @JohnIdol says correctly, I've found that you need to setup a number VS environment variables. I don't have the name of the batch file in front of me, but you can modify or 'I think' use it. It is in VS program files tree somewhere. Also, as I remember you don't want to be in a standard shell but a .NET setup shell for some paths and such. I'll add details later when I'm at a Windows PC with VS.</p>\n\n<p>EDIT: The batch file mentioned is a shortcut in ProgFiles menu. Here is the details of its properties. </p>\n\n<pre><code>%comspec% /k \"\"C:\\Program Files\\Microsoft Visual Studio 8\\VC\\vcvarsall.bat\"\"x86\"\n</code></pre>\n\n<p>Here is my batch file, using MSBuild to call the solution.</p>\n\n<pre><code>@echo off\n\n:: setup VS2005 command line build environment\nset VSINSTALLDIR=C:\\Program Files\\Microsoft Visual Studio 8\nset VCINSTALLDIR=C:\\Program Files\\Microsoft Visual Studio 8\\VC\nset FrameworkDir=C:\\WINDOWS\\Microsoft.NET\\Framework\nset FrameworkVersion=v2.0.50727\nset FrameworkSDKDir=C:\\Program Files\\Microsoft Visual Studio 8\\SDK\\v2.0\nset DevEnvDir=C:\\Program Files\\Microsoft Visual Studio 8\\Common7\\IDE\nset PATH=C:\\Program Files\\Microsoft Visual Studio 8\\Common7\\IDE;C:\\Program Files\\Microsoft Visual Studio 8\\VC\\BIN;C:\\Program Files\\Microsoft Visual Studio 8\\Com\nmon7\\Tools;C:\\Program Files\\Microsoft Visual Studio 8\\Common7\\Tools\\bin;C:\\Program Files\\Microsoft Visual Studio 8\\VC\\PlatformSDK\\bin;C:\\Program Files\\Microsoft\n Visual Studio 8\\SDK\\v2.0\\bin;C:\\WINDOWS\\Microsoft.NET\\Framework\\v2.0.50727;C:\\Program Files\\Microsoft Visual Studio 8\\VC\\VCPackages;%PATH%\nset INCLUDE=C:\\Program Files\\Microsoft Visual Studio 8\\VC\\ATLMFC\\INCLUDE;C:\\Program Files\\Microsoft Visual Studio 8\\VC\\INCLUDE;C:\\Program Files\\Microsoft Visual\n Studio 8\\VC\\PlatformSDK\\include;C:\\Program Files\\Microsoft Visual Studio 8\\SDK\\v2.0\\include;%INCLUDE%\nset LIB=C:\\Program Files\\Microsoft Visual Studio 8\\VC\\ATLMFC\\LIB;C:\\Program Files\\Microsoft Visual Studio 8\\VC\\LIB;C:\\Program Files\\Microsoft Visual Studio 8\\VC\n\\PlatformSDK\\lib;C:\\Program Files\\Microsoft Visual Studio 8\\SDK\\v2.0\\lib;%LIB%\nset LIBPATH=C:\\WINDOWS\\Microsoft.NET\\Framework\\v2.0.50727;C:\\Program Files\\Microsoft Visual Studio 8\\VC\\ATLMFC\\LIB\n\necho %0 %*\necho %0 %* >> %MrB-LOG%\ncd\nif not \"\"==\"%~dp1\" pushd %~dp1\ncd\nif exist %~nx1 (\n echo VS2005 build of '%~nx1'.\n echo VS2005 build of '%~nx1'. >> %MrB-LOG%\n set MrB-BUILDLOG=%MrB-BASE%\\%MrB-WORK%.%MrB-NICEDATE%.%MrB-NICETIME%.build-errors.log\n msbuild.exe %~nx1 /t:Rebuild /p:Configuration=Release > %MrB-BUILDLOG%\n findstr /r /c:\"[1-9][0-9]* Error(s)\" %MrB-BUILDLOG%\n if not errorlevel 1 (\n echo ERROR: sending notification email for build errors in '%~nx1'.\n echo ERROR: sending notification email for build errors in '%~nx1'. >> %MrB-LOG%\n call mrb-email \"Mr Build isn't happy about build errors in '%~nx1'\" %MrB-BUILDLOG%\n ) else (\n findstr /r /c:\"[1-9][0-9]* Warning(s)\" %MrB-BUILDLOG%\n if not errorlevel 1 (\n echo ERROR: sending notification email for build warnings in '%~nx1'.\n echo ERROR: sending notification email for build warnings in '%~nx1'. >> %MrB-LOG%\n call mrb-email \"Mr Build isn't happy about build warnings in '%~nx1'\" %MrB-BUILDLOG%\n ) else (\n echo Successful build of '%~nx1'.\n echo Successful build of '%~nx1'. >> %MrB-LOG%\n )\n )\n) else (\n echo ERROR '%1' doesn't exist.\n echo ERROR '%1' doesn't exist. >> %MrB-LOG%\n)\npopd\n</code></pre>\n"
},
{
"answer_id": 280907,
"author": "David Sykes",
"author_id": 259,
"author_profile": "https://Stackoverflow.com/users/259",
"pm_score": 3,
"selected": false,
"text": "<p>If you want to see the exact command line as provided by VS (rather than work it out) then you could try replacing the MSBuild.exe with your own console app that prints out all the parameters to a file.</p>\n\n<p>You could also write out all the environment variables supplied to check which ones VS provides in the background.</p>\n"
},
{
"answer_id": 281356,
"author": "icelava",
"author_id": 2663,
"author_profile": "https://Stackoverflow.com/users/2663",
"pm_score": 5,
"selected": false,
"text": "<p>Navigate to your Programs menu > Microsoft Visual Studio 2005 > Visual Studio Tools > <strong>Visual Studio 2005 Command Prompt</strong>.</p>\n\n<p>this command prompt has all the necessary .NET environment variables set for the the command line session. You can change directory to your solution directory (e.g. c:\\projects\\mySolution) and run</p>\n\n<pre><code>Msbuild.exe mySolution.sln\n</code></pre>\n\n<p>You can see the various options available using <strong>msbuild /?</strong></p>\n\n<p>Msbuild is located at C:\\Windows\\Microsoft.NET\\Framework\\v2.0.50727</p>\n\n<p>On top of msbuild /? quick-option check, you may reference the <a href=\"http://msdn.microsoft.com/en-us/library/ms164311.aspx\" rel=\"noreferrer\">MSBuild Command Line Reference</a> page for more explanations on its usage. And <a href=\"http://msdn.microsoft.com/en-us/library/ms171486(VS.80).aspx\" rel=\"noreferrer\">how to build specific targets in solutions</a>.</p>\n"
},
{
"answer_id": 355547,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 3,
"selected": false,
"text": "<p>For VS .NET 2003 you can use devenv.exe to build the solution/project from command line. </p>\n\n<pre><code>devenv solutionfile.sln /build solutionconfig\n</code></pre>\n\n<p>E.g. usage in batch file:</p>\n\n<pre><code>call \"C:\\Program Files\\Microsoft Visual Studio .NET 2003\\Common7\\Tools\\vsvars32.bat\"\n\ndevenv Tools.sln /build \"Release\"\n</code></pre>\n"
},
{
"answer_id": 14748432,
"author": "crash",
"author_id": 2050281,
"author_profile": "https://Stackoverflow.com/users/2050281",
"pm_score": 2,
"selected": false,
"text": "<p>I just want to thank the Bejoy on the example. I had big problems with solution rebuild on setup pre build event because they removed most of the macros and this helped me a lot.</p>\n\n<p>Here is my solution based on Bejoy's (considering that .bat file is located in setup root folder which is part of solution):</p>\n\n<pre><code>call \"%VS100COMNTOOLS%\\vsvars32.bat\"\n\ndevenv \"%CD%\\..\\soulutionfile.sln\" /build \"Release\"\n</code></pre>\n"
}
] |
2008/11/11
|
[
"https://Stackoverflow.com/questions/280559",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1311500/"
] |
This is probably easy but I am getting stuck: when I build a solution in Visual Studio - how do extract the exact cmd line for the current build command in order to be able to do the same build from VisualStudio console?
In the output window I can see the single projects in the solution build commands but not the one for the whole solution.
I am on VS2005.
Any help would be appreciated
|
In addition to what @JohnIdol says correctly, I've found that you need to setup a number VS environment variables. I don't have the name of the batch file in front of me, but you can modify or 'I think' use it. It is in VS program files tree somewhere. Also, as I remember you don't want to be in a standard shell but a .NET setup shell for some paths and such. I'll add details later when I'm at a Windows PC with VS.
EDIT: The batch file mentioned is a shortcut in ProgFiles menu. Here is the details of its properties.
```
%comspec% /k ""C:\Program Files\Microsoft Visual Studio 8\VC\vcvarsall.bat""x86"
```
Here is my batch file, using MSBuild to call the solution.
```
@echo off
:: setup VS2005 command line build environment
set VSINSTALLDIR=C:\Program Files\Microsoft Visual Studio 8
set VCINSTALLDIR=C:\Program Files\Microsoft Visual Studio 8\VC
set FrameworkDir=C:\WINDOWS\Microsoft.NET\Framework
set FrameworkVersion=v2.0.50727
set FrameworkSDKDir=C:\Program Files\Microsoft Visual Studio 8\SDK\v2.0
set DevEnvDir=C:\Program Files\Microsoft Visual Studio 8\Common7\IDE
set PATH=C:\Program Files\Microsoft Visual Studio 8\Common7\IDE;C:\Program Files\Microsoft Visual Studio 8\VC\BIN;C:\Program Files\Microsoft Visual Studio 8\Com
mon7\Tools;C:\Program Files\Microsoft Visual Studio 8\Common7\Tools\bin;C:\Program Files\Microsoft Visual Studio 8\VC\PlatformSDK\bin;C:\Program Files\Microsoft
Visual Studio 8\SDK\v2.0\bin;C:\WINDOWS\Microsoft.NET\Framework\v2.0.50727;C:\Program Files\Microsoft Visual Studio 8\VC\VCPackages;%PATH%
set INCLUDE=C:\Program Files\Microsoft Visual Studio 8\VC\ATLMFC\INCLUDE;C:\Program Files\Microsoft Visual Studio 8\VC\INCLUDE;C:\Program Files\Microsoft Visual
Studio 8\VC\PlatformSDK\include;C:\Program Files\Microsoft Visual Studio 8\SDK\v2.0\include;%INCLUDE%
set LIB=C:\Program Files\Microsoft Visual Studio 8\VC\ATLMFC\LIB;C:\Program Files\Microsoft Visual Studio 8\VC\LIB;C:\Program Files\Microsoft Visual Studio 8\VC
\PlatformSDK\lib;C:\Program Files\Microsoft Visual Studio 8\SDK\v2.0\lib;%LIB%
set LIBPATH=C:\WINDOWS\Microsoft.NET\Framework\v2.0.50727;C:\Program Files\Microsoft Visual Studio 8\VC\ATLMFC\LIB
echo %0 %*
echo %0 %* >> %MrB-LOG%
cd
if not ""=="%~dp1" pushd %~dp1
cd
if exist %~nx1 (
echo VS2005 build of '%~nx1'.
echo VS2005 build of '%~nx1'. >> %MrB-LOG%
set MrB-BUILDLOG=%MrB-BASE%\%MrB-WORK%.%MrB-NICEDATE%.%MrB-NICETIME%.build-errors.log
msbuild.exe %~nx1 /t:Rebuild /p:Configuration=Release > %MrB-BUILDLOG%
findstr /r /c:"[1-9][0-9]* Error(s)" %MrB-BUILDLOG%
if not errorlevel 1 (
echo ERROR: sending notification email for build errors in '%~nx1'.
echo ERROR: sending notification email for build errors in '%~nx1'. >> %MrB-LOG%
call mrb-email "Mr Build isn't happy about build errors in '%~nx1'" %MrB-BUILDLOG%
) else (
findstr /r /c:"[1-9][0-9]* Warning(s)" %MrB-BUILDLOG%
if not errorlevel 1 (
echo ERROR: sending notification email for build warnings in '%~nx1'.
echo ERROR: sending notification email for build warnings in '%~nx1'. >> %MrB-LOG%
call mrb-email "Mr Build isn't happy about build warnings in '%~nx1'" %MrB-BUILDLOG%
) else (
echo Successful build of '%~nx1'.
echo Successful build of '%~nx1'. >> %MrB-LOG%
)
)
) else (
echo ERROR '%1' doesn't exist.
echo ERROR '%1' doesn't exist. >> %MrB-LOG%
)
popd
```
|
280,563 |
<p>Has anybody got any real world stories build mobile web sites with NetBiscuits?</p>
<p>Someone told me it was the next big thing in mobile development (<a href="http://www.netbiscuits.com/home" rel="nofollow noreferrer">http://www.netbiscuits.com/home</a>) and it looks pretty good from their site. Just wondered if anybody (besides them) has actually used it.</p>
|
[
{
"answer_id": 280568,
"author": "Mendelt",
"author_id": 3320,
"author_profile": "https://Stackoverflow.com/users/3320",
"pm_score": 2,
"selected": false,
"text": "<p>You can start msbuild from the command line. msbuild understands .sln (solution) files. You can specify the .sln file and the build configuration (debug, release etc.) from the command line.</p>\n\n<p><a href=\"http://msdn.microsoft.com/en-us/library/ms164311.aspx\" rel=\"nofollow noreferrer\">http://msdn.microsoft.com/en-us/library/ms164311.aspx</a> <br>\nHere is the documentation on what you can do with msbuild. MSBuild.exe is installed with the .net framework, not with visual studio. You can find it in c:\\windows\\microsoft.net\\framework\\v3.5 (or v2.0.50727)</p>\n\n<p>I searched a bit and found that you can also do a command line build with visual studio using devenv.exe /build, more info here:<br>\n<a href=\"http://msdn.microsoft.com/en-us/library/xee0c8y7(VS.80).aspx\" rel=\"nofollow noreferrer\">http://msdn.microsoft.com/en-us/library/xee0c8y7(VS.80).aspx</a></p>\n"
},
{
"answer_id": 280584,
"author": "kenny",
"author_id": 3225,
"author_profile": "https://Stackoverflow.com/users/3225",
"pm_score": 5,
"selected": true,
"text": "<p>In addition to what @JohnIdol says correctly, I've found that you need to setup a number VS environment variables. I don't have the name of the batch file in front of me, but you can modify or 'I think' use it. It is in VS program files tree somewhere. Also, as I remember you don't want to be in a standard shell but a .NET setup shell for some paths and such. I'll add details later when I'm at a Windows PC with VS.</p>\n\n<p>EDIT: The batch file mentioned is a shortcut in ProgFiles menu. Here is the details of its properties. </p>\n\n<pre><code>%comspec% /k \"\"C:\\Program Files\\Microsoft Visual Studio 8\\VC\\vcvarsall.bat\"\"x86\"\n</code></pre>\n\n<p>Here is my batch file, using MSBuild to call the solution.</p>\n\n<pre><code>@echo off\n\n:: setup VS2005 command line build environment\nset VSINSTALLDIR=C:\\Program Files\\Microsoft Visual Studio 8\nset VCINSTALLDIR=C:\\Program Files\\Microsoft Visual Studio 8\\VC\nset FrameworkDir=C:\\WINDOWS\\Microsoft.NET\\Framework\nset FrameworkVersion=v2.0.50727\nset FrameworkSDKDir=C:\\Program Files\\Microsoft Visual Studio 8\\SDK\\v2.0\nset DevEnvDir=C:\\Program Files\\Microsoft Visual Studio 8\\Common7\\IDE\nset PATH=C:\\Program Files\\Microsoft Visual Studio 8\\Common7\\IDE;C:\\Program Files\\Microsoft Visual Studio 8\\VC\\BIN;C:\\Program Files\\Microsoft Visual Studio 8\\Com\nmon7\\Tools;C:\\Program Files\\Microsoft Visual Studio 8\\Common7\\Tools\\bin;C:\\Program Files\\Microsoft Visual Studio 8\\VC\\PlatformSDK\\bin;C:\\Program Files\\Microsoft\n Visual Studio 8\\SDK\\v2.0\\bin;C:\\WINDOWS\\Microsoft.NET\\Framework\\v2.0.50727;C:\\Program Files\\Microsoft Visual Studio 8\\VC\\VCPackages;%PATH%\nset INCLUDE=C:\\Program Files\\Microsoft Visual Studio 8\\VC\\ATLMFC\\INCLUDE;C:\\Program Files\\Microsoft Visual Studio 8\\VC\\INCLUDE;C:\\Program Files\\Microsoft Visual\n Studio 8\\VC\\PlatformSDK\\include;C:\\Program Files\\Microsoft Visual Studio 8\\SDK\\v2.0\\include;%INCLUDE%\nset LIB=C:\\Program Files\\Microsoft Visual Studio 8\\VC\\ATLMFC\\LIB;C:\\Program Files\\Microsoft Visual Studio 8\\VC\\LIB;C:\\Program Files\\Microsoft Visual Studio 8\\VC\n\\PlatformSDK\\lib;C:\\Program Files\\Microsoft Visual Studio 8\\SDK\\v2.0\\lib;%LIB%\nset LIBPATH=C:\\WINDOWS\\Microsoft.NET\\Framework\\v2.0.50727;C:\\Program Files\\Microsoft Visual Studio 8\\VC\\ATLMFC\\LIB\n\necho %0 %*\necho %0 %* >> %MrB-LOG%\ncd\nif not \"\"==\"%~dp1\" pushd %~dp1\ncd\nif exist %~nx1 (\n echo VS2005 build of '%~nx1'.\n echo VS2005 build of '%~nx1'. >> %MrB-LOG%\n set MrB-BUILDLOG=%MrB-BASE%\\%MrB-WORK%.%MrB-NICEDATE%.%MrB-NICETIME%.build-errors.log\n msbuild.exe %~nx1 /t:Rebuild /p:Configuration=Release > %MrB-BUILDLOG%\n findstr /r /c:\"[1-9][0-9]* Error(s)\" %MrB-BUILDLOG%\n if not errorlevel 1 (\n echo ERROR: sending notification email for build errors in '%~nx1'.\n echo ERROR: sending notification email for build errors in '%~nx1'. >> %MrB-LOG%\n call mrb-email \"Mr Build isn't happy about build errors in '%~nx1'\" %MrB-BUILDLOG%\n ) else (\n findstr /r /c:\"[1-9][0-9]* Warning(s)\" %MrB-BUILDLOG%\n if not errorlevel 1 (\n echo ERROR: sending notification email for build warnings in '%~nx1'.\n echo ERROR: sending notification email for build warnings in '%~nx1'. >> %MrB-LOG%\n call mrb-email \"Mr Build isn't happy about build warnings in '%~nx1'\" %MrB-BUILDLOG%\n ) else (\n echo Successful build of '%~nx1'.\n echo Successful build of '%~nx1'. >> %MrB-LOG%\n )\n )\n) else (\n echo ERROR '%1' doesn't exist.\n echo ERROR '%1' doesn't exist. >> %MrB-LOG%\n)\npopd\n</code></pre>\n"
},
{
"answer_id": 280907,
"author": "David Sykes",
"author_id": 259,
"author_profile": "https://Stackoverflow.com/users/259",
"pm_score": 3,
"selected": false,
"text": "<p>If you want to see the exact command line as provided by VS (rather than work it out) then you could try replacing the MSBuild.exe with your own console app that prints out all the parameters to a file.</p>\n\n<p>You could also write out all the environment variables supplied to check which ones VS provides in the background.</p>\n"
},
{
"answer_id": 281356,
"author": "icelava",
"author_id": 2663,
"author_profile": "https://Stackoverflow.com/users/2663",
"pm_score": 5,
"selected": false,
"text": "<p>Navigate to your Programs menu > Microsoft Visual Studio 2005 > Visual Studio Tools > <strong>Visual Studio 2005 Command Prompt</strong>.</p>\n\n<p>this command prompt has all the necessary .NET environment variables set for the the command line session. You can change directory to your solution directory (e.g. c:\\projects\\mySolution) and run</p>\n\n<pre><code>Msbuild.exe mySolution.sln\n</code></pre>\n\n<p>You can see the various options available using <strong>msbuild /?</strong></p>\n\n<p>Msbuild is located at C:\\Windows\\Microsoft.NET\\Framework\\v2.0.50727</p>\n\n<p>On top of msbuild /? quick-option check, you may reference the <a href=\"http://msdn.microsoft.com/en-us/library/ms164311.aspx\" rel=\"noreferrer\">MSBuild Command Line Reference</a> page for more explanations on its usage. And <a href=\"http://msdn.microsoft.com/en-us/library/ms171486(VS.80).aspx\" rel=\"noreferrer\">how to build specific targets in solutions</a>.</p>\n"
},
{
"answer_id": 355547,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 3,
"selected": false,
"text": "<p>For VS .NET 2003 you can use devenv.exe to build the solution/project from command line. </p>\n\n<pre><code>devenv solutionfile.sln /build solutionconfig\n</code></pre>\n\n<p>E.g. usage in batch file:</p>\n\n<pre><code>call \"C:\\Program Files\\Microsoft Visual Studio .NET 2003\\Common7\\Tools\\vsvars32.bat\"\n\ndevenv Tools.sln /build \"Release\"\n</code></pre>\n"
},
{
"answer_id": 14748432,
"author": "crash",
"author_id": 2050281,
"author_profile": "https://Stackoverflow.com/users/2050281",
"pm_score": 2,
"selected": false,
"text": "<p>I just want to thank the Bejoy on the example. I had big problems with solution rebuild on setup pre build event because they removed most of the macros and this helped me a lot.</p>\n\n<p>Here is my solution based on Bejoy's (considering that .bat file is located in setup root folder which is part of solution):</p>\n\n<pre><code>call \"%VS100COMNTOOLS%\\vsvars32.bat\"\n\ndevenv \"%CD%\\..\\soulutionfile.sln\" /build \"Release\"\n</code></pre>\n"
}
] |
2008/11/11
|
[
"https://Stackoverflow.com/questions/280563",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/36503/"
] |
Has anybody got any real world stories build mobile web sites with NetBiscuits?
Someone told me it was the next big thing in mobile development (<http://www.netbiscuits.com/home>) and it looks pretty good from their site. Just wondered if anybody (besides them) has actually used it.
|
In addition to what @JohnIdol says correctly, I've found that you need to setup a number VS environment variables. I don't have the name of the batch file in front of me, but you can modify or 'I think' use it. It is in VS program files tree somewhere. Also, as I remember you don't want to be in a standard shell but a .NET setup shell for some paths and such. I'll add details later when I'm at a Windows PC with VS.
EDIT: The batch file mentioned is a shortcut in ProgFiles menu. Here is the details of its properties.
```
%comspec% /k ""C:\Program Files\Microsoft Visual Studio 8\VC\vcvarsall.bat""x86"
```
Here is my batch file, using MSBuild to call the solution.
```
@echo off
:: setup VS2005 command line build environment
set VSINSTALLDIR=C:\Program Files\Microsoft Visual Studio 8
set VCINSTALLDIR=C:\Program Files\Microsoft Visual Studio 8\VC
set FrameworkDir=C:\WINDOWS\Microsoft.NET\Framework
set FrameworkVersion=v2.0.50727
set FrameworkSDKDir=C:\Program Files\Microsoft Visual Studio 8\SDK\v2.0
set DevEnvDir=C:\Program Files\Microsoft Visual Studio 8\Common7\IDE
set PATH=C:\Program Files\Microsoft Visual Studio 8\Common7\IDE;C:\Program Files\Microsoft Visual Studio 8\VC\BIN;C:\Program Files\Microsoft Visual Studio 8\Com
mon7\Tools;C:\Program Files\Microsoft Visual Studio 8\Common7\Tools\bin;C:\Program Files\Microsoft Visual Studio 8\VC\PlatformSDK\bin;C:\Program Files\Microsoft
Visual Studio 8\SDK\v2.0\bin;C:\WINDOWS\Microsoft.NET\Framework\v2.0.50727;C:\Program Files\Microsoft Visual Studio 8\VC\VCPackages;%PATH%
set INCLUDE=C:\Program Files\Microsoft Visual Studio 8\VC\ATLMFC\INCLUDE;C:\Program Files\Microsoft Visual Studio 8\VC\INCLUDE;C:\Program Files\Microsoft Visual
Studio 8\VC\PlatformSDK\include;C:\Program Files\Microsoft Visual Studio 8\SDK\v2.0\include;%INCLUDE%
set LIB=C:\Program Files\Microsoft Visual Studio 8\VC\ATLMFC\LIB;C:\Program Files\Microsoft Visual Studio 8\VC\LIB;C:\Program Files\Microsoft Visual Studio 8\VC
\PlatformSDK\lib;C:\Program Files\Microsoft Visual Studio 8\SDK\v2.0\lib;%LIB%
set LIBPATH=C:\WINDOWS\Microsoft.NET\Framework\v2.0.50727;C:\Program Files\Microsoft Visual Studio 8\VC\ATLMFC\LIB
echo %0 %*
echo %0 %* >> %MrB-LOG%
cd
if not ""=="%~dp1" pushd %~dp1
cd
if exist %~nx1 (
echo VS2005 build of '%~nx1'.
echo VS2005 build of '%~nx1'. >> %MrB-LOG%
set MrB-BUILDLOG=%MrB-BASE%\%MrB-WORK%.%MrB-NICEDATE%.%MrB-NICETIME%.build-errors.log
msbuild.exe %~nx1 /t:Rebuild /p:Configuration=Release > %MrB-BUILDLOG%
findstr /r /c:"[1-9][0-9]* Error(s)" %MrB-BUILDLOG%
if not errorlevel 1 (
echo ERROR: sending notification email for build errors in '%~nx1'.
echo ERROR: sending notification email for build errors in '%~nx1'. >> %MrB-LOG%
call mrb-email "Mr Build isn't happy about build errors in '%~nx1'" %MrB-BUILDLOG%
) else (
findstr /r /c:"[1-9][0-9]* Warning(s)" %MrB-BUILDLOG%
if not errorlevel 1 (
echo ERROR: sending notification email for build warnings in '%~nx1'.
echo ERROR: sending notification email for build warnings in '%~nx1'. >> %MrB-LOG%
call mrb-email "Mr Build isn't happy about build warnings in '%~nx1'" %MrB-BUILDLOG%
) else (
echo Successful build of '%~nx1'.
echo Successful build of '%~nx1'. >> %MrB-LOG%
)
)
) else (
echo ERROR '%1' doesn't exist.
echo ERROR '%1' doesn't exist. >> %MrB-LOG%
)
popd
```
|
280,571 |
<p>I am confused about how popen() redirects stdin, stdout and stderr of the child process in unix. The man page on popen() is not very clear in this regard. The call</p>
<pre><code>FILE *p = popen("/usr/bin/foo", "w");
</code></pre>
<p>forks a child process and executes a shell with arguments "-c", "/usr/bin/foo", and redirects stdin of this shell (which is redirected stdin of foo), stdout to p. But what happens with stderr? What is the general principle behind it?</p>
<p>I noticed that, if I open a file in foo (using fopen, socket, accept etc.), and the parent process has no stdout, it gets assigned the next available file number, which is 1 and so on. This delivers unexpected results from calls like fprintf(stderr, ...).</p>
<p>It can be avoided by writing</p>
<pre><code>FILE *p = popen("/usr/bin/foo 2>/dev/null", "w");
</code></pre>
<p>in the parent program, but are their better ways?</p>
|
[
{
"answer_id": 280587,
"author": "Johannes Schaub - litb",
"author_id": 34509,
"author_profile": "https://Stackoverflow.com/users/34509",
"pm_score": 3,
"selected": false,
"text": "<blockquote>\n <p>The return value from popen() is a normal standard I/O stream in all\n respects save that it must be closed with pclose() rather than\n fclose(3). Writing to such a stream writes to the standard input of\n the command; the command's standard output is the same as that of the\n process that called popen(), unless this is altered by the command\n itself. Conversely, reading from a \"popened\" stream reads the\n command's standard output, and the command's standard input is the\n same as that of the process that called popen().</p>\n</blockquote>\n\n<p>From its manpage, so it allows you to read the commands standard output or write into its standard input. It doesn't say anything about stderr. Thus that is not redirected. </p>\n\n<p>If you provide \"w\", you will send your stuff to the stdin of the shell that is executed. Thus, doing</p>\n\n<pre><code>FILE * file = popen(\"/bin/cat\", \"w\");\nfwrite(\"hello\", 5, file);\npclose(file);\n</code></pre>\n\n<p>Will make the shell execute /bin/cat, and pass it the string <code>\"hello\"</code> as its standard input stream. If you want to redirect, for example stderr to the file <code>\"foo\"</code> do this first, before you execute the code above:</p>\n\n<pre><code>FILE * error_file = fopen(\"foo\", \"w+\");\nif(error_file) {\n dup2(fileno(error_file), 2);\n fclose(error_file);\n}\n</code></pre>\n\n<p>It will open the file, and duplicate its file-descriptor to 2, closing the original file descriptor afterwards.</p>\n\n<p>Now, if you have your stdout closed in your parent, then if the child calls <code>open</code> it will get 1, since that's (if stdin is already opened) the next free file-descriptor. Only solution i see is to just use dup2 and duplicate something into that in the parent, like the above code. Note that if the child opens <code>stdout</code>, it will <em>not</em> make <code>stdout</code> open in the parent too. It stays closed there.</p>\n"
},
{
"answer_id": 280628,
"author": "Alnitak",
"author_id": 6782,
"author_profile": "https://Stackoverflow.com/users/6782",
"pm_score": 6,
"selected": true,
"text": "<p><code>popen(3)</code> is just a library function, which relies on <code>fork(2)</code> and <code>pipe(2)</code> to do the real work.</p>\n\n<p>However <code>pipe(2)</code> can only create unidirectional pipes. To send the child process input, and also capture the output, you need to open two pipes.</p>\n\n<p>If you want to capture the <code>stderr</code> too, that's possible, but then you'll need <strong>three</strong> pipes, and a <code>select</code> loop to arbitrate reads between the <code>stdout</code> and <code>stderr</code> streams.</p>\n\n<p>There's an example <a href=\"http://jineshkj.wordpress.com/2006/12/22/how-to-capture-stdin-stdout-and-stderr-of-child-program/\" rel=\"noreferrer\">here</a> for the two-pipe version.</p>\n"
},
{
"answer_id": 5552111,
"author": "martin",
"author_id": 692908,
"author_profile": "https://Stackoverflow.com/users/692908",
"pm_score": 5,
"selected": false,
"text": "<p>simple idea: why not add \"2>&1\" to the command string to force the bash to redirect stderr to stdout (OK, writing to stdin still is not possible but at least we get stderr and stdout into our C program).</p>\n"
},
{
"answer_id": 5766346,
"author": "neoneye",
"author_id": 78336,
"author_profile": "https://Stackoverflow.com/users/78336",
"pm_score": 3,
"selected": false,
"text": "<p>Check out <a href=\"https://github.com/sni/mod_gearman/blob/master/common/popenRWE.c\" rel=\"noreferrer\">popenRWE</a> by Bart Trojanowski. Clean way to do all 3 pipes.</p>\n"
},
{
"answer_id": 23234272,
"author": "kangear",
"author_id": 2193455,
"author_profile": "https://Stackoverflow.com/users/2193455",
"pm_score": 3,
"selected": false,
"text": "<p>if you just want to get STDERR, try this:</p>\n\n<pre><code>#include <stdio.h>\n#include <errno.h>\n#include <fcntl.h>\n#include <sys/wait.h>\n#include <malloc.h>\n#include <unistd.h>\n#include <string.h>\n#include <sys/types.h>\n\n/*\n * Pointer to array allocated at run-time.\n */\nstatic pid_t *childpid = NULL;\n\n/*\n * From our open_max(), {Prog openmax}.\n */\nstatic int maxfd;\n\nFILE *\nmypopen(const char *cmdstring, const char *type)\n{\n int i;\n int pfd[2];\n pid_t pid;\n FILE *fp;\n\n /* only allow \"r\" \"e\" or \"w\" */\n if ((type[0] != 'r' && type[0] != 'w' && type[0] != 'e') || type[1] != 0) {\n errno = EINVAL; /* required by POSIX */\n return(NULL);\n }\n\n if (childpid == NULL) { /* first time through */\n /* allocate zeroed out array for child pids */\n maxfd = 256;\n if ((childpid = calloc(maxfd, sizeof(pid_t))) == NULL)\n return(NULL);\n }\n\n if (pipe(pfd) < 0)\n return(NULL); /* errno set by pipe() */\n\n if ((pid = fork()) < 0) {\n return(NULL); /* errno set by fork() */\n } else if (pid == 0) { /* child */\n if (*type == 'e') {\n close(pfd[0]);\n if (pfd[1] != STDERR_FILENO) {\n dup2(pfd[1], STDERR_FILENO);\n close(pfd[1]);\n }\n } else if (*type == 'r') {\n close(pfd[0]);\n if (pfd[1] != STDOUT_FILENO) {\n dup2(pfd[1], STDOUT_FILENO);\n close(pfd[1]);\n }\n } else {\n close(pfd[1]);\n if (pfd[0] != STDIN_FILENO) {\n dup2(pfd[0], STDIN_FILENO);\n close(pfd[0]);\n }\n }\n\n /* close all descriptors in childpid[] */\n for (i = 0; i < maxfd; i++)\n if (childpid[i] > 0)\n close(i);\n\n execl(\"/bin/sh\", \"sh\", \"-c\", cmdstring, (char *)0);\n _exit(127);\n }\n\n /* parent continues... */\n if (*type == 'e') {\n close(pfd[1]);\n if ((fp = fdopen(pfd[0], \"r\")) == NULL)\n return(NULL);\n } else if (*type == 'r') {\n close(pfd[1]);\n if ((fp = fdopen(pfd[0], type)) == NULL)\n return(NULL);\n\n } else {\n close(pfd[0]);\n if ((fp = fdopen(pfd[1], type)) == NULL)\n return(NULL);\n }\n\n childpid[fileno(fp)] = pid; /* remember child pid for this fd */\n return(fp);\n}\n\nint\nmypclose(FILE *fp)\n{\n int fd, stat;\n pid_t pid;\n\n if (childpid == NULL) {\n errno = EINVAL;\n return(-1); /* popen() has never been called */\n }\n\n fd = fileno(fp);\n if ((pid = childpid[fd]) == 0) {\n errno = EINVAL;\n return(-1); /* fp wasn't opened by popen() */\n }\n\n childpid[fd] = 0;\n if (fclose(fp) == EOF)\n return(-1);\n\n while (waitpid(pid, &stat, 0) < 0)\n if (errno != EINTR)\n return(-1); /* error other than EINTR from waitpid() */\n\n return(stat); /* return child's termination status */\n}\n\nint shellcmd(char *cmd){\n FILE *fp;\n char buf[1024];\n fp = mypopen(cmd,\"e\");\n if (fp==NULL) return -1;\n\n while(fgets(buf,1024,fp)!=NULL)\n {\n printf(\"shellcmd:%s\", buf);\n }\n\n pclose(fp);\n return 0;\n}\n\nint main()\n{\n shellcmd(\"ls kangear\");\n}\n</code></pre>\n\n<p>and you will get this:</p>\n\n<pre><code>shellcmd:ls: cannot access kangear: No such file or directory\n</code></pre>\n"
}
] |
2008/11/11
|
[
"https://Stackoverflow.com/questions/280571",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/31330/"
] |
I am confused about how popen() redirects stdin, stdout and stderr of the child process in unix. The man page on popen() is not very clear in this regard. The call
```
FILE *p = popen("/usr/bin/foo", "w");
```
forks a child process and executes a shell with arguments "-c", "/usr/bin/foo", and redirects stdin of this shell (which is redirected stdin of foo), stdout to p. But what happens with stderr? What is the general principle behind it?
I noticed that, if I open a file in foo (using fopen, socket, accept etc.), and the parent process has no stdout, it gets assigned the next available file number, which is 1 and so on. This delivers unexpected results from calls like fprintf(stderr, ...).
It can be avoided by writing
```
FILE *p = popen("/usr/bin/foo 2>/dev/null", "w");
```
in the parent program, but are their better ways?
|
`popen(3)` is just a library function, which relies on `fork(2)` and `pipe(2)` to do the real work.
However `pipe(2)` can only create unidirectional pipes. To send the child process input, and also capture the output, you need to open two pipes.
If you want to capture the `stderr` too, that's possible, but then you'll need **three** pipes, and a `select` loop to arbitrate reads between the `stdout` and `stderr` streams.
There's an example [here](http://jineshkj.wordpress.com/2006/12/22/how-to-capture-stdin-stdout-and-stderr-of-child-program/) for the two-pipe version.
|
280,578 |
<p>I have got some code to load an assembly and get all types, which implement a certain interface, like this (assume asm is a valid and loaded assembly).</p>
<pre><code>var results = from type in asm.GetTypes()
where typeof(IServiceJob).IsAssignableFrom(type)
select type;
</code></pre>
<p>Now I'm stuck: I need to create instances of these objects and invoke methods and properties on the object. And I need to store the references to the created objects in an array for later usage.</p>
|
[
{
"answer_id": 280591,
"author": "Matt Hamilton",
"author_id": 615,
"author_profile": "https://Stackoverflow.com/users/615",
"pm_score": 5,
"selected": true,
"text": "<p>Oh wow - I only <a href=\"http://www.madprops.org/blog/linq-with-reflection-part-2/\" rel=\"noreferrer\">blogged about this</a> a few days ago. Here's my method to return instances of all the types that implement a given interface:</p>\n\n<pre><code>private static IEnumerable<T> InstancesOf<T>() where T : class\n{\n var type = typeof(T);\n return from t in type.Assembly.GetExportedTypes()\n where t.IsClass\n && type.IsAssignableFrom(t)\n && t.GetConstructor(new Type[0]) != null\n select (T)Activator.CreateInstance(t);\n}\n</code></pre>\n\n<p>If you refactor this to accept an assembly parameter rather than using the interface's assembly, it becomes flexible enough to suit your need.</p>\n"
},
{
"answer_id": 280610,
"author": "AnthonyWJones",
"author_id": 17516,
"author_profile": "https://Stackoverflow.com/users/17516",
"pm_score": 1,
"selected": false,
"text": "<p>You can create an instance of a type with the <code>Activator.CreateInstance</code> method:-</p>\n\n<pre><code>IServiceJob x = Activator.CreateInstance(type);\n</code></pre>\n\n<p>So your code becomes:-</p>\n\n<pre><code>IServiceJob[] results = (from type in asm.GetTypes()\n where typeof(IServiceJob).IsAssignableFrom(type)\n select (IServiceJob)Activator.CreateInstance(type)).ToArray();\n</code></pre>\n\n<p>(Note change var to IServiceJob[] to make it clear what is being created).</p>\n"
}
] |
2008/11/11
|
[
"https://Stackoverflow.com/questions/280578",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/16440/"
] |
I have got some code to load an assembly and get all types, which implement a certain interface, like this (assume asm is a valid and loaded assembly).
```
var results = from type in asm.GetTypes()
where typeof(IServiceJob).IsAssignableFrom(type)
select type;
```
Now I'm stuck: I need to create instances of these objects and invoke methods and properties on the object. And I need to store the references to the created objects in an array for later usage.
|
Oh wow - I only [blogged about this](http://www.madprops.org/blog/linq-with-reflection-part-2/) a few days ago. Here's my method to return instances of all the types that implement a given interface:
```
private static IEnumerable<T> InstancesOf<T>() where T : class
{
var type = typeof(T);
return from t in type.Assembly.GetExportedTypes()
where t.IsClass
&& type.IsAssignableFrom(t)
&& t.GetConstructor(new Type[0]) != null
select (T)Activator.CreateInstance(t);
}
```
If you refactor this to accept an assembly parameter rather than using the interface's assembly, it becomes flexible enough to suit your need.
|
280,579 |
<p>How do I pass a value from a child back to the parent form? I have a string that I would like to pass back to the parent.</p>
<p>I launched the child using:</p>
<pre><code>FormOptions formOptions = new FormOptions();
formOptions.ShowDialog();
</code></pre>
|
[
{
"answer_id": 280586,
"author": "Mitch Wheat",
"author_id": 16076,
"author_profile": "https://Stackoverflow.com/users/16076",
"pm_score": 6,
"selected": false,
"text": "<p>Create a property (or method) on <code>FormOptions</code>, say <code>GetMyResult</code>:</p>\n\n<pre><code>using (FormOptions formOptions = new FormOptions())\n{\n formOptions.ShowDialog();\n\n string result = formOptions.GetMyResult;\n\n // do what ever with result...\n}\n</code></pre>\n"
},
{
"answer_id": 280595,
"author": "kenny",
"author_id": 3225,
"author_profile": "https://Stackoverflow.com/users/3225",
"pm_score": 0,
"selected": false,
"text": "<p>Many ways to skin the cat here and <a href=\"https://stackoverflow.com/questions/280579/c-beginner-help-how-do-i-pass-a-value-from-a-child-back-to-the-parent-form#280586\">@Mitch's suggestion</a> is a good way. If you want the client form to have more 'control', you may want to pass the instance of the parent to the child when created and then you can call any public parent method on the child. </p>\n"
},
{
"answer_id": 280630,
"author": "stiduck",
"author_id": 35398,
"author_profile": "https://Stackoverflow.com/users/35398",
"pm_score": 5,
"selected": false,
"text": "<p>You can also create a public property.</p>\n\n<pre><code>// Using and namespace...\n\npublic partial class FormOptions : Form\n{\n private string _MyString; // Use this\n public string MyString { // in \n get { return _MyString; } // .NET\n } // 2.0\n\n public string MyString { get; } // In .NET 3.0 or newer\n\n // The rest of the form code\n}\n</code></pre>\n\n<p>Then you can get it with:</p>\n\n<pre><code>FormOptions formOptions = new FormOptions();\nformOptions.ShowDialog();\n\nstring myString = formOptions.MyString;\n</code></pre>\n"
},
{
"answer_id": 280685,
"author": "MusiGenesis",
"author_id": 14606,
"author_profile": "https://Stackoverflow.com/users/14606",
"pm_score": 5,
"selected": false,
"text": "<p><strong>If you're just using formOptions to pick a single value and then close, Mitch's suggestion is a good way to go</strong>. My example here would be used if you needed the child to communicate back to the parent while remaining open.</p>\n\n<p>In your parent form, add a public method that the child form will call, such as</p>\n\n<pre><code>public void NotifyMe(string s)\n{\n // Do whatever you need to do with the string\n}\n</code></pre>\n\n<p>Next, when you need to launch the child window from the parent, use this code:</p>\n\n<pre><code>using (FormOptions formOptions = new FormOptions())\n{\n // passing this in ShowDialog will set the .Owner \n // property of the child form\n formOptions.ShowDialog(this);\n}\n</code></pre>\n\n<p>In the child form, use this code to pass a value back to the parent:</p>\n\n<pre><code>ParentForm parent = (ParentForm)this.Owner;\nparent.NotifyMe(\"whatever\");\n</code></pre>\n\n<p>The code in this example would be better used for something like a toolbox window which is intended to float above the main form. In this case, you would open the child form (with .TopMost = true) using .Show() instead of .ShowDialog().</p>\n\n<p>A design like this means that the child form is tightly coupled to the parent form (since the child has to cast its owner as a ParentForm in order to call its NotifyMe method). However, this is not automatically a bad thing.</p>\n"
},
{
"answer_id": 280731,
"author": "Ali Ersöz",
"author_id": 4215,
"author_profile": "https://Stackoverflow.com/users/4215",
"pm_score": 3,
"selected": false,
"text": "<p>You can also create an overload of ShowDialog in your child class that gets an out parameter that returns you the result.</p>\n\n<pre><code>public partial class FormOptions : Form\n{\n public DialogResult ShowDialog(out string result)\n {\n DialogResult dialogResult = base.ShowDialog();\n\n result = m_Result;\n return dialogResult;\n }\n}\n</code></pre>\n"
},
{
"answer_id": 395035,
"author": "Ahmed",
"author_id": 42749,
"author_profile": "https://Stackoverflow.com/users/42749",
"pm_score": 0,
"selected": false,
"text": "<p>I think the easiest way is to use the Tag property\nin your FormOptions class set the Tag = value you need to pass\nand after the ShowDialog method read it as </p>\n\n<pre><code>myvalue x=(myvalue)formoptions.Tag;\n</code></pre>\n"
},
{
"answer_id": 395104,
"author": "abatishchev",
"author_id": 41956,
"author_profile": "https://Stackoverflow.com/users/41956",
"pm_score": 2,
"selected": false,
"text": "<p>Use public property of child form</p>\n\n<pre><code>frmOptions {\n public string Result; }\n\nfrmMain {\n frmOptions.ShowDialog(); string r = frmOptions.Result; }\n</code></pre>\n\n<p>Use events</p>\n\n<pre><code>frmMain {\n frmOptions.OnResult += new ResultEventHandler(frmMain.frmOptions_Resukt);\n frmOptions.ShowDialog(); }\n</code></pre>\n\n<p>Use public property of main form</p>\n\n<pre><code>frmOptions {\n public frmMain MainForm; MainForm.Result = \"result\"; }\n\nfrmMain {\n public string Result;\n frmOptions.MainForm = this;\n frmOptions.ShowDialog();\n string r = this.Result; }\n</code></pre>\n\n<p>Use object Control.Tag; This is common for all controls public property which can contains a System.Object. You can hold there string or MyClass or MainForm - anything!</p>\n\n<pre><code>frmOptions {\n this.Tag = \"result\": }\nfrmMain {\n frmOptions.ShowDialog();\n string r = frmOptions.Tag as string; }\n</code></pre>\n"
},
{
"answer_id": 11013409,
"author": "Odin",
"author_id": 1453458,
"author_profile": "https://Stackoverflow.com/users/1453458",
"pm_score": 0,
"selected": false,
"text": "<p>When you use the <code>ShowDialog()</code> or <code>Show()</code> method, and then close the form, the form object does not get completely destroyed (<em>closing != destruction</em>). It will remain alive, only it's in a \"closed\" state, and you can still do things to it.</p>\n"
},
{
"answer_id": 13625756,
"author": "Bravo Mike",
"author_id": 1863172,
"author_profile": "https://Stackoverflow.com/users/1863172",
"pm_score": 1,
"selected": false,
"text": "<p>For Picrofo EDY</p>\n\n<p>It depends, if you use the <code>ShowDialog()</code> as a way of showing your form and to close it you use the close button instead of <code>this.Close()</code>. The form will not be disposed or destroyed, it will only be hidden and changes can be made after is gone. In order to properly close it you will need the <code>Dispose()</code> or <code>Close()</code> method. In the other hand, if you use the <code>Show()</code> method and you close it, the form will be disposed and can not be modified after.</p>\n"
},
{
"answer_id": 21948683,
"author": "ghfarzad",
"author_id": 2988517,
"author_profile": "https://Stackoverflow.com/users/2988517",
"pm_score": 1,
"selected": false,
"text": "<p>If you are displaying child form as a modal dialog box, you can set DialogResult property of child form with a value from the DialogResult enumeration which in turn hides the modal dialog box, and returns control to the calling form. At this time parent can access child form's data to get the info that it need.</p>\n\n<p>For more info check this link:\n<a href=\"http://msdn.microsoft.com/en-us/library/system.windows.forms.form.dialogresult(v=vs.110).aspx\" rel=\"nofollow\">http://msdn.microsoft.com/en-us/library/system.windows.forms.form.dialogresult(v=vs.110).aspx</a></p>\n"
},
{
"answer_id": 30526895,
"author": "Chagbert",
"author_id": 1261930,
"author_profile": "https://Stackoverflow.com/users/1261930",
"pm_score": 2,
"selected": false,
"text": "<p>Well I have just come across the same problem here - maybe a bit different. However, I think this is how I solved it:</p>\n\n<ol>\n<li><p>in my parent form I declared the child form without instance e.g. <code>RefDateSelect myDateFrm;</code> So this is available to my other methods within this class/ form</p></li>\n<li><p>next, a method displays the child by new instance:</p>\n\n<pre><code>myDateFrm = new RefDateSelect();\nmyDateFrm.MdiParent = this;\nmyDateFrm.Show();\nmyDateFrm.Focus();\n</code></pre></li>\n<li><p>my third method (which wants the results from child) can come at any time & simply get results: </p>\n\n<pre><code>PDateEnd = myDateFrm.JustGetDateEnd();\npDateStart = myDateFrm.JustGetDateStart();`\n</code></pre>\n\n<p>Note: the child methods <code>JustGetDateStart()</code> are public within CHILD as:</p>\n\n<pre><code>public DateTime JustGetDateStart()\n{\n return DateTime.Parse(this.dtpStart.EditValue.ToString());\n}\n</code></pre></li>\n</ol>\n\n<p>I hope this helps.</p>\n"
},
{
"answer_id": 56788194,
"author": "user889030",
"author_id": 889030,
"author_profile": "https://Stackoverflow.com/users/889030",
"pm_score": 1,
"selected": false,
"text": "<p>i had same problem i solved it like that , here are newbies step by step instruction </p>\n\n<p>first create object of child form it top of your form class , then use that object for every operation of child form like showing child form and reading value from it.</p>\n\n<p>example</p>\n\n<pre><code>namespace ParentChild\n{\n // Parent Form Class\n public partial class ParentForm : Form\n {\n // Forms Objects\n ChildForm child_obj = new ChildForm();\n\n\n // Show Child Forrm\n private void ShowChildForm_Click(object sender, EventArgs e)\n {\n child_obj.ShowDialog();\n }\n\n // Read Data from Child Form \n private void ReadChildFormData_Click(object sender, EventArgs e)\n {\n int ChildData = child_obj.child_value; // it will have 12345\n }\n\n } // parent form class end point\n\n\n // Child Form Class\n public partial class ChildForm : Form\n {\n\n public int child_value = 0; // variable where we will store value to be read by parent form \n\n // save something into child_value variable and close child form \n private void SaveData_Click(object sender, EventArgs e)\n {\n child_value = 12345; // save 12345 value to variable\n this.Close(); // close child form\n }\n\n } // child form class end point\n\n\n} // name space end point\n</code></pre>\n"
},
{
"answer_id": 65976609,
"author": "mahdi yousefi",
"author_id": 3247491,
"author_profile": "https://Stackoverflow.com/users/3247491",
"pm_score": 0,
"selected": false,
"text": "<p>The fastest and more flexible way to do that is passing the parent to the children from the constructor as below:</p>\n<ol>\n<li><p>Declare a property in the parent form:</p>\n<p><code>public string MyProperty {get; set;}</code></p>\n</li>\n<li><p>Declare a property from the parent in child form:</p>\n<p><code>private ParentForm ParentProperty {get; set;}</code></p>\n</li>\n<li><p>Write the child's constructor like this:</p>\n<pre><code> public ChildForm(ParentForm parent){\n ParentProperty= parent;\n }\n</code></pre>\n</li>\n<li><p>Change the value of the parent property everywhere in the child form:</p>\n<p><code>ParentProperty.MyProperty = "New value";</code></p>\n</li>\n</ol>\n<p>It's done. the property <code>MyProperty</code> in the parent form is changed. With this solution, you can change multiple properties from the child form. So delicious, no?!</p>\n"
}
] |
2008/11/11
|
[
"https://Stackoverflow.com/questions/280579",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] |
How do I pass a value from a child back to the parent form? I have a string that I would like to pass back to the parent.
I launched the child using:
```
FormOptions formOptions = new FormOptions();
formOptions.ShowDialog();
```
|
Create a property (or method) on `FormOptions`, say `GetMyResult`:
```
using (FormOptions formOptions = new FormOptions())
{
formOptions.ShowDialog();
string result = formOptions.GetMyResult;
// do what ever with result...
}
```
|
280,600 |
<p>I have some code that effectively does this :</p>
<pre><code>File file = new File("C:\\Program Files (x86)\\Something\\fred.txt");
System.out.println("file.canWrite() = " + file.canWrite());
</code></pre>
<p>It prints true.
Now the odd thing is, I can create the file without any exceptions. Furthermore, another program can read the file I've created. The thing is, in Windows Explorer, the file doesn't show up at all!</p>
<p>Show hidden files you may be thinking, but no, I've got that option turned on.</p>
<p>I've also found out about 'super hidden files' in Vista, so I've turned that option on and I still can't see the file! Maybe I haven't edited my registry correctly - I can only assume the file is super hidden - where else could it be?</p>
<p>Now the problem is that I'm creating an html file and the when I fire up a browser, it can't see the html file because it's super hidden.</p>
<p>How can I prevent Java creating a super hidden file? This is running under JRE 6 update 6.</p>
|
[
{
"answer_id": 280609,
"author": "Michael Madsen",
"author_id": 27528,
"author_profile": "https://Stackoverflow.com/users/27528",
"pm_score": 4,
"selected": true,
"text": "<p>You are most likely a \"victim\" of folder redirection. When UAC is enabled, any writes to Program Files is redirected to somewhere else when you're not running the program as an administrator.</p>\n\n<p>You should find your file in C:\\Users\\<username>\\AppData\\Local\\VirtualStore\\<insert>\\<expected>\\<path>\\<here>.</p>\n\n<p>The proper fix, of course, is to not write to Program Files in the first place. Instead, use somewhere in the user's home directory (the exact location you should write to depends on the purpose of the app).</p>\n"
},
{
"answer_id": 280619,
"author": "jcoder",
"author_id": 417292,
"author_profile": "https://Stackoverflow.com/users/417292",
"pm_score": 0,
"selected": false,
"text": "<p>I believe that update 10 might have changed this behavour. I know the reimplemented a lot of the browser stuff to work better with vista. I'm not 100% certain though but I suggest you take a look.</p>\n"
}
] |
2008/11/11
|
[
"https://Stackoverflow.com/questions/280600",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/36510/"
] |
I have some code that effectively does this :
```
File file = new File("C:\\Program Files (x86)\\Something\\fred.txt");
System.out.println("file.canWrite() = " + file.canWrite());
```
It prints true.
Now the odd thing is, I can create the file without any exceptions. Furthermore, another program can read the file I've created. The thing is, in Windows Explorer, the file doesn't show up at all!
Show hidden files you may be thinking, but no, I've got that option turned on.
I've also found out about 'super hidden files' in Vista, so I've turned that option on and I still can't see the file! Maybe I haven't edited my registry correctly - I can only assume the file is super hidden - where else could it be?
Now the problem is that I'm creating an html file and the when I fire up a browser, it can't see the html file because it's super hidden.
How can I prevent Java creating a super hidden file? This is running under JRE 6 update 6.
|
You are most likely a "victim" of folder redirection. When UAC is enabled, any writes to Program Files is redirected to somewhere else when you're not running the program as an administrator.
You should find your file in C:\Users\<username>\AppData\Local\VirtualStore\<insert>\<expected>\<path>\<here>.
The proper fix, of course, is to not write to Program Files in the first place. Instead, use somewhere in the user's home directory (the exact location you should write to depends on the purpose of the app).
|
280,634 |
<p>How can I check if a string ends with a particular character in JavaScript?</p>
<p>Example: I have a string </p>
<pre><code>var str = "mystring#";
</code></pre>
<p>I want to know if that string is ending with <code>#</code>. How can I check it?</p>
<ol>
<li><p>Is there a <code>endsWith()</code> method in JavaScript?</p></li>
<li><p>One solution I have is take the length of the string and get the last character and check it.</p></li>
</ol>
<p>Is this the best way or there is any other way?</p>
|
[
{
"answer_id": 280644,
"author": "Phillip B Oldham",
"author_id": 30478,
"author_profile": "https://Stackoverflow.com/users/30478",
"pm_score": 7,
"selected": false,
"text": "<ol>\n<li>Unfortunately not.</li>\n<li><code>if( \"mystring#\".substr(-1) === \"#\" ) {}</code></li>\n</ol>\n"
},
{
"answer_id": 280651,
"author": "duckyflip",
"author_id": 7370,
"author_profile": "https://Stackoverflow.com/users/7370",
"pm_score": 4,
"selected": false,
"text": "<pre><code>if( (\"mystring#\").substr(-1,1) == '#' )\n</code></pre>\n\n<p>-- Or --</p>\n\n<pre><code>if( (\"mystring#\").match(/#$/) )\n</code></pre>\n"
},
{
"answer_id": 280704,
"author": "Phani Kumar Bhamidipati",
"author_id": 15177,
"author_profile": "https://Stackoverflow.com/users/15177",
"pm_score": 0,
"selected": false,
"text": "<p>all of them are very useful examples. Adding <code>String.prototype.endsWith = function(str)</code> will help us to simply call the method to check if our string ends with it or not, well regexp will also do it.</p>\n\n<p>I found a better solution than mine. Thanks every one.</p>\n"
},
{
"answer_id": 280708,
"author": "Jon Skeet",
"author_id": 22656,
"author_profile": "https://Stackoverflow.com/users/22656",
"pm_score": 6,
"selected": false,
"text": "<p>This version avoids creating a substring, and doesn't use regular expressions (some regex answers here will work; others are broken):</p>\n\n<pre><code>String.prototype.endsWith = function(str)\n{\n var lastIndex = this.lastIndexOf(str);\n return (lastIndex !== -1) && (lastIndex + str.length === this.length);\n}\n</code></pre>\n\n<p>If performance is important to you, it would be worth testing whether <code>lastIndexOf</code> is actually faster than creating a substring or not. (It may well depend on the JS engine you're using...) It may well be faster in the matching case, and when the string is small - but when the string is huge it needs to look back through the whole thing even though we don't really care :(</p>\n\n<p>For checking a single character, finding the length and then using <code>charAt</code> is probably the best way.</p>\n"
},
{
"answer_id": 611204,
"author": "user73745",
"author_id": 73745,
"author_profile": "https://Stackoverflow.com/users/73745",
"pm_score": 4,
"selected": false,
"text": "<pre><code>return this.lastIndexOf(str) + str.length == this.length;\n</code></pre>\n\n<p>does not work in the case where original string length is one less than search string length and the search string is not found:</p>\n\n<p>lastIndexOf returns -1, then you add search string length and you are left with the original string's length.</p>\n\n<p>A possible fix is</p>\n\n<pre><code>return this.length >= str.length && this.lastIndexOf(str) + str.length == this.length\n</code></pre>\n"
},
{
"answer_id": 679134,
"author": "Mike Samuel",
"author_id": 20394,
"author_profile": "https://Stackoverflow.com/users/20394",
"pm_score": 8,
"selected": false,
"text": "<pre><code>/#$/.test(str)\n</code></pre>\n\n<p>will work on all browsers, doesn't require monkey patching <code>String</code>, and doesn't require scanning the entire string as <code>lastIndexOf</code> does when there is no match.</p>\n\n<p>If you want to match a constant string that might contain regular expression special characters, such as <code>'$'</code>, then you can use the following:</p>\n\n<pre><code>function makeSuffixRegExp(suffix, caseInsensitive) {\n return new RegExp(\n String(suffix).replace(/[$%()*+.?\\[\\\\\\]{|}]/g, \"\\\\$&\") + \"$\",\n caseInsensitive ? \"i\" : \"\");\n}\n</code></pre>\n\n<p>and then you can use it like this</p>\n\n<pre><code>makeSuffixRegExp(\"a[complicated]*suffix*\").test(str)\n</code></pre>\n"
},
{
"answer_id": 1483107,
"author": "Oskar Liljeblad",
"author_id": 179703,
"author_profile": "https://Stackoverflow.com/users/179703",
"pm_score": 6,
"selected": false,
"text": "<p>Come on, this is the correct <code>endsWith</code> implementation:</p>\n\n<pre><code>String.prototype.endsWith = function (s) {\n return this.length >= s.length && this.substr(this.length - s.length) == s;\n}\n</code></pre>\n\n<p>using <code>lastIndexOf</code> just creates unnecessary CPU loops if there is no match.</p>\n"
},
{
"answer_id": 2548133,
"author": "chakrit",
"author_id": 3055,
"author_profile": "https://Stackoverflow.com/users/3055",
"pm_score": 12,
"selected": true,
"text": "<p><strong>UPDATE (Nov 24th, 2015):</strong></p>\n<p>This answer is originally posted in the year 2010 (SIX years back.) so please take note of these insightful comments:</p>\n<ul>\n<li><a href=\"https://stackoverflow.com/users/570040/shauna\">Shauna</a> -</li>\n</ul>\n<blockquote>\n<p>Update for Googlers - Looks like ECMA6 adds this function. The MDN article also shows a polyfill. <a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/endsWith\" rel=\"nofollow noreferrer\">https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/endsWith</a></p>\n</blockquote>\n<ul>\n<li><a href=\"https://stackoverflow.com/users/157247/t-j-crowder\">T.J. Crowder</a> -</li>\n</ul>\n<blockquote>\n<p>Creating substrings isn't expensive on modern browsers; it may well have been in 2010 when this answer was posted. These days, the simple <code>this.substr(-suffix.length) === suffix</code> approach is fastest on Chrome, the same on IE11 as indexOf, and only 4% slower (fergetaboutit territory) on Firefox: <a href=\"https://jsben.ch/OJzlM\" rel=\"nofollow noreferrer\">https://jsben.ch/OJzlM</a> And faster across the board when the result is false: <a href=\"http://jsperf.com/endswith-stackoverflow-when-false\" rel=\"nofollow noreferrer\">jsperf.com/endswith-stackoverflow-when-false</a> <strong>Of course, with ES6 adding endsWith, the point is moot. :-)</strong></p>\n</blockquote>\n<hr />\n<p><strong>ORIGINAL ANSWER:</strong></p>\n<p>I know this is a year old question... but I need this too and I need it to work cross-browser so... <strong>combining everyone's answer and comments</strong> and simplifying it a bit:</p>\n<pre><code>String.prototype.endsWith = function(suffix) {\n return this.indexOf(suffix, this.length - suffix.length) !== -1;\n};\n</code></pre>\n<ul>\n<li>Doesn't create a substring</li>\n<li>Uses native <code>indexOf</code> function for fastest results</li>\n<li>Skip unnecessary comparisons using the second parameter of <code>indexOf</code> to skip ahead</li>\n<li>Works in Internet Explorer</li>\n<li>NO Regex complications</li>\n</ul>\n<hr />\n<p>Also, if you don't like stuffing things in native data structure's prototypes, here's a standalone version:</p>\n<pre><code>function endsWith(str, suffix) {\n return str.indexOf(suffix, str.length - suffix.length) !== -1;\n}\n</code></pre>\n<hr />\n<p><strong>EDIT:</strong> As noted by @hamish in the comments, if you want to err on the safe side and check if an implementation has already been provided, you can just adds a <code>typeof</code> check like so:</p>\n<pre><code>if (typeof String.prototype.endsWith !== 'function') {\n String.prototype.endsWith = function(suffix) {\n return this.indexOf(suffix, this.length - suffix.length) !== -1;\n };\n}\n</code></pre>\n"
},
{
"answer_id": 3054087,
"author": "manish",
"author_id": 368321,
"author_profile": "https://Stackoverflow.com/users/368321",
"pm_score": 2,
"selected": false,
"text": "<pre><code>function check(str)\n{\n var lastIndex = str.lastIndexOf('/');\n return (lastIndex != -1) && (lastIndex == (str.length - 1));\n}\n</code></pre>\n"
},
{
"answer_id": 5854629,
"author": "user511941",
"author_id": 511941,
"author_profile": "https://Stackoverflow.com/users/511941",
"pm_score": 1,
"selected": false,
"text": "<p>if you dont want to use lasIndexOf or substr then why not just look at the string in its natural state (ie. an array)</p>\n\n<pre><code>String.prototype.endsWith = function(suffix) {\n if (this[this.length - 1] == suffix) return true;\n return false;\n}\n</code></pre>\n\n<p>or as a standalone function</p>\n\n<pre><code>function strEndsWith(str,suffix) {\n if (str[str.length - 1] == suffix) return true;\n return false;\n}\n</code></pre>\n"
},
{
"answer_id": 6739835,
"author": "Dan Doyon",
"author_id": 53635,
"author_profile": "https://Stackoverflow.com/users/53635",
"pm_score": 2,
"selected": false,
"text": "<p>A way to future proof and/or prevent overwriting of existing prototype would be test check to see if it has already been added to the String prototype. Here's my take on the non-regex highly rated version. </p>\n\n<pre><code>if (typeof String.endsWith !== 'function') {\n String.prototype.endsWith = function (suffix) {\n return this.indexOf(suffix, this.length - suffix.length) !== -1;\n };\n}\n</code></pre>\n"
},
{
"answer_id": 11158914,
"author": "Ebubekir Dirican",
"author_id": 869571,
"author_profile": "https://Stackoverflow.com/users/869571",
"pm_score": 1,
"selected": false,
"text": "<pre><code>String.prototype.endWith = function (a) {\n var isExp = a.constructor.name === \"RegExp\",\n val = this;\n if (isExp === false) {\n a = escape(a);\n val = escape(val);\n } else\n a = a.toString().replace(/(^\\/)|(\\/$)/g, \"\");\n return eval(\"/\" + a + \"$/.test(val)\");\n}\n\n// example\nvar str = \"Hello\";\nalert(str.endWith(\"lo\"));\nalert(str.endWith(/l(o|a)/));\n</code></pre>\n"
},
{
"answer_id": 12932780,
"author": "Mohammed Rafeeq",
"author_id": 1752917,
"author_profile": "https://Stackoverflow.com/users/1752917",
"pm_score": 3,
"selected": false,
"text": "<pre><code>String.prototype.endsWith = function(str) \n{return (this.match(str+\"$\")==str)}\n\nString.prototype.startsWith = function(str) \n{return (this.match(\"^\"+str)==str)}\n</code></pre>\n\n<p>I hope this helps</p>\n\n<pre><code>var myStr = “ Earth is a beautiful planet ”;\nvar myStr2 = myStr.trim(); \n//==“Earth is a beautiful planet”;\n\nif (myStr2.startsWith(“Earth”)) // returns TRUE\n\nif (myStr2.endsWith(“planet”)) // returns TRUE\n\nif (myStr.startsWith(“Earth”)) \n// returns FALSE due to the leading spaces…\n\nif (myStr.endsWith(“planet”)) \n// returns FALSE due to trailing spaces…\n</code></pre>\n\n<p>the traditional way </p>\n\n<pre><code>function strStartsWith(str, prefix) {\n return str.indexOf(prefix) === 0;\n}\n\nfunction strEndsWith(str, suffix) {\n return str.match(suffix+\"$\")==suffix;\n}\n</code></pre>\n"
},
{
"answer_id": 16333087,
"author": "Tici",
"author_id": 1651168,
"author_profile": "https://Stackoverflow.com/users/1651168",
"pm_score": 3,
"selected": false,
"text": "<p>I don't know about you, but:</p>\n\n<pre><code>var s = \"mystring#\";\ns.length >= 1 && s[s.length - 1] == '#'; // will do the thing!\n</code></pre>\n\n<p>Why regular expressions? Why messing with the prototype? substr? c'mon...</p>\n"
},
{
"answer_id": 17120898,
"author": "Matthew Brown",
"author_id": 515311,
"author_profile": "https://Stackoverflow.com/users/515311",
"pm_score": 0,
"selected": false,
"text": "<p>This builds on @charkit's accepted answer allowing either an Array of strings, or string to passed in as an argument.</p>\n\n<pre><code>if (typeof String.prototype.endsWith === 'undefined') {\n String.prototype.endsWith = function(suffix) {\n if (typeof suffix === 'String') {\n return this.indexOf(suffix, this.length - suffix.length) !== -1;\n }else if(suffix instanceof Array){\n return _.find(suffix, function(value){\n console.log(value, (this.indexOf(value, this.length - value.length) !== -1));\n return this.indexOf(value, this.length - value.length) !== -1;\n }, this);\n }\n };\n}\n</code></pre>\n\n<p>This requires underscorejs - but can probably be adjusted to remove the underscore dependency.</p>\n"
},
{
"answer_id": 17594966,
"author": "termi",
"author_id": 1587897,
"author_profile": "https://Stackoverflow.com/users/1587897",
"pm_score": 0,
"selected": false,
"text": "<pre><code>if(typeof String.prototype.endsWith !== \"function\") {\n /**\n * String.prototype.endsWith\n * Check if given string locate at the end of current string\n * @param {string} substring substring to locate in the current string.\n * @param {number=} position end the endsWith check at that position\n * @return {boolean}\n *\n * @edition ECMA-262 6th Edition, 15.5.4.23\n */\n String.prototype.endsWith = function(substring, position) {\n substring = String(substring);\n\n var subLen = substring.length | 0;\n\n if( !subLen )return true;//Empty string\n\n var strLen = this.length;\n\n if( position === void 0 )position = strLen;\n else position = position | 0;\n\n if( position < 1 )return false;\n\n var fromIndex = (strLen < position ? strLen : position) - subLen;\n\n return (fromIndex >= 0 || subLen === -fromIndex)\n && (\n position === 0\n // if position not at the and of the string, we can optimise search substring\n // by checking first symbol of substring exists in search position in current string\n || this.charCodeAt(fromIndex) === substring.charCodeAt(0)//fast false\n )\n && this.indexOf(substring, fromIndex) === fromIndex\n ;\n };\n}\n</code></pre>\n\n<p><strong>Benefits:</strong></p>\n\n<ul>\n<li>This version is not just re-using indexOf.</li>\n<li>Greatest performance on long strings. Here is a speed test <a href=\"http://jsperf.com/starts-ends-with/4\" rel=\"nofollow\">http://jsperf.com/starts-ends-with/4</a></li>\n<li>Fully compatible with ecmascript specification. It passes the <a href=\"https://github.com/monolithed/ECMAScript-6/blob/master/tests/String.js\" rel=\"nofollow\">tests</a></li>\n</ul>\n"
},
{
"answer_id": 20929168,
"author": "Daniel Nuriyev",
"author_id": 1299267,
"author_profile": "https://Stackoverflow.com/users/1299267",
"pm_score": 0,
"selected": false,
"text": "<p>Do not use regular expressions. They are slow even in fast languages. Just write a function that checks the end of a string. This library has nice examples: <a href=\"https://github.com/danielnuriyev/groundjs/blob/master/util.js\" rel=\"nofollow\">groundjs/util.js</a>.\nBe careful adding a function to String.prototype. This code has nice examples of how to do it: <a href=\"https://github.com/danielnuriyev/groundjs/blob/master/prototype.js\" rel=\"nofollow\">groundjs/prototype.js</a>\nIn general, this is a nice language-level library: <a href=\"https://github.com/danielnuriyev/groundjs/blob/master/ground.js\" rel=\"nofollow\">groundjs</a>\nYou can also take a look at lodash</p>\n"
},
{
"answer_id": 22201327,
"author": "Aniket Kulkarni",
"author_id": 1031945,
"author_profile": "https://Stackoverflow.com/users/1031945",
"pm_score": 4,
"selected": false,
"text": "<p>From developer.mozilla.org <a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/endsWith\" rel=\"noreferrer\">String.prototype.endsWith()</a></p>\n\n<h2>Summary</h2>\n\n<p>The <code>endsWith()</code> method determines whether a string ends with the characters of another string, returning true or false as appropriate.</p>\n\n<h2>Syntax</h2>\n\n<pre><code>str.endsWith(searchString [, position]);\n</code></pre>\n\n<h2>Parameters</h2>\n\n<ul>\n<li><p><strong>searchString</strong> :\nThe characters to be searched for at the end of this string.</p></li>\n<li><p><strong>position</strong> :\nSearch within this string as if this string were only this long; defaults to this string's actual length, clamped within the range established by this string's length.</p></li>\n</ul>\n\n<h2>Description</h2>\n\n<p>This method lets you determine whether or not a string ends with another string.</p>\n\n<h2>Examples</h2>\n\n<pre><code>var str = \"To be, or not to be, that is the question.\";\n\nalert( str.endsWith(\"question.\") ); // true\nalert( str.endsWith(\"to be\") ); // false\nalert( str.endsWith(\"to be\", 19) ); // true\n</code></pre>\n\n<h2>Specifications</h2>\n\n<p><a href=\"http://people.mozilla.org/~jorendorff/es6-draft.html#sec-string.prototype.endswith\" rel=\"noreferrer\">ECMAScript Language Specification 6th Edition (ECMA-262)</a></p>\n\n<h2>Browser compatibility</h2>\n\n<p><a href=\"https://i.stack.imgur.com/THZsd.jpg\" rel=\"noreferrer\"><img src=\"https://i.stack.imgur.com/THZsd.jpg\" alt=\"Browser compatibility\"></a></p>\n"
},
{
"answer_id": 23361885,
"author": "Ashley Davis",
"author_id": 25868,
"author_profile": "https://Stackoverflow.com/users/25868",
"pm_score": 3,
"selected": false,
"text": "<p>I just learned about this string library:</p>\n\n<p><a href=\"http://stringjs.com/\" rel=\"noreferrer\">http://stringjs.com/</a></p>\n\n<p>Include the js file and then use the <code>S</code> variable like this:</p>\n\n<pre><code>S('hi there').endsWith('hi there')\n</code></pre>\n\n<p>It can also be used in NodeJS by installing it:</p>\n\n<pre><code>npm install string\n</code></pre>\n\n<p>Then requiring it as the <code>S</code> variable:</p>\n\n<pre><code>var S = require('string');\n</code></pre>\n\n<p>The web page also has links to alternate string libraries, if this one doesn't take your fancy.</p>\n"
},
{
"answer_id": 23732394,
"author": "Tabish Usman",
"author_id": 3651315,
"author_profile": "https://Stackoverflow.com/users/3651315",
"pm_score": 2,
"selected": false,
"text": "<pre><code>function strEndsWith(str,suffix) {\n var reguex= new RegExp(suffix+'$');\n\n if (str.match(reguex)!=null)\n return true;\n\n return false;\n}\n</code></pre>\n"
},
{
"answer_id": 26525300,
"author": "Quanlong",
"author_id": 622662,
"author_profile": "https://Stackoverflow.com/users/622662",
"pm_score": 0,
"selected": false,
"text": "<p>For coffeescript</p>\n\n<pre><code>String::endsWith = (suffix) ->\n -1 != @indexOf suffix, @length - suffix.length\n</code></pre>\n"
},
{
"answer_id": 26990323,
"author": "LahiruBandara",
"author_id": 3175948,
"author_profile": "https://Stackoverflow.com/users/3175948",
"pm_score": 2,
"selected": false,
"text": "<p>So many things for such a small problem, just use this Regular Expression</p>\n\n<p><div class=\"snippet\" data-lang=\"js\" data-hide=\"false\">\r\n<div class=\"snippet-code\">\r\n<pre class=\"snippet-code-js lang-js prettyprint-override\"><code>var str = \"mystring#\";\r\nvar regex = /^.*#$/\r\n\r\nif (regex.test(str)){\r\n //if it has a trailing '#'\r\n}</code></pre>\r\n</div>\r\n</div>\r\n</p>\n"
},
{
"answer_id": 28330768,
"author": "rmehlinger",
"author_id": 1141842,
"author_profile": "https://Stackoverflow.com/users/1141842",
"pm_score": 2,
"selected": false,
"text": "<p>@chakrit's accepted answer is a solid way to do it yourself. If, however, you're looking for a packaged solution, I recommend taking a look at <a href=\"http://epeli.github.io/underscore.string/\" rel=\"nofollow\">underscore.string</a>, as @mlunoe pointed out. Using underscore.string, the code would be:</p>\n\n<pre><code>function endsWithHash(str) {\n return _.str.endsWith(str, '#');\n}\n</code></pre>\n"
},
{
"answer_id": 28807654,
"author": "Dheeraj Vepakomma",
"author_id": 165674,
"author_profile": "https://Stackoverflow.com/users/165674",
"pm_score": 3,
"selected": false,
"text": "<p>If you're using <a href=\"https://lodash.com/docs#endsWith\" rel=\"noreferrer\">lodash</a>:</p>\n\n<pre><code>_.endsWith('abc', 'c'); // true\n</code></pre>\n\n<p>If not using lodash, you can borrow from its <a href=\"https://github.com/lodash/lodash/blob/3.9.3/lodash.src.js#L10423\" rel=\"noreferrer\">source</a>.</p>\n"
},
{
"answer_id": 29960996,
"author": "ScrapCode",
"author_id": 3048967,
"author_profile": "https://Stackoverflow.com/users/3048967",
"pm_score": 2,
"selected": false,
"text": "<p>Its been many years for this question. Let me add an important update for the users who wants to use the most voted chakrit's answer.</p>\n\n<p>'endsWith' functions is already added to JavaScript as part of ECMAScript 6 (experimental technology)</p>\n\n<p>Refer it here: <a href=\"https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/String/endsWith\" rel=\"nofollow\">https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/String/endsWith</a></p>\n\n<p>Hence it is highly recommended to add check for the existence of native implementation as mentioned in the answer.</p>\n"
},
{
"answer_id": 30128677,
"author": "Vinicius",
"author_id": 528531,
"author_profile": "https://Stackoverflow.com/users/528531",
"pm_score": 3,
"selected": false,
"text": "<p>Just another quick alternative that worked like a charm for me, using regex:</p>\n\n<pre><code>// Would be equivalent to:\n// \"Hello World!\".endsWith(\"World!\")\n\"Hello World!\".match(\"World!$\") != null\n</code></pre>\n"
},
{
"answer_id": 30725350,
"author": "Nikita Koksharov",
"author_id": 764206,
"author_profile": "https://Stackoverflow.com/users/764206",
"pm_score": 5,
"selected": false,
"text": "<p>Didn't see apporach with <code>slice</code> method. So i'm just leave it here:</p>\n\n<pre><code>function endsWith(str, suffix) {\n return str.slice(-suffix.length) === suffix\n}\n</code></pre>\n"
},
{
"answer_id": 35460962,
"author": "faisalbhagat",
"author_id": 1851358,
"author_profile": "https://Stackoverflow.com/users/1851358",
"pm_score": -1,
"selected": false,
"text": "<p>7 years old post, but I was not able to understand top few posts, because they are complex. So, I wrote my own solution:</p>\n\n<pre><code>function strEndsWith(str, endwith)\n{\n var lastIndex = url.lastIndexOf(endsWith);\n var result = false;\n if (lastIndex > 0 && (lastIndex + \"registerc\".length) == url.length)\n {\n result = true;\n }\n return result;\n}\n</code></pre>\n"
},
{
"answer_id": 35681532,
"author": "immazharkhan",
"author_id": 4945514,
"author_profile": "https://Stackoverflow.com/users/4945514",
"pm_score": 2,
"selected": false,
"text": "<p>After all those long tally of answers, i found this piece of code simple and easy to understand!</p>\n\n<pre><code>function end(str, target) {\n return str.substr(-target.length) == target;\n}\n</code></pre>\n"
},
{
"answer_id": 50940299,
"author": "Singh123",
"author_id": 3526891,
"author_profile": "https://Stackoverflow.com/users/3526891",
"pm_score": 0,
"selected": false,
"text": "<p>This is the implementation of <code>endsWith</code>:</p>\n\n<pre class=\"lang-js prettyprint-override\"><code>String.prototype.endsWith = function (str) {\n return (this.length >= str.length) && (this.substr(this.length - str.length) === str);\n}\n</code></pre>\n"
}
] |
2008/11/11
|
[
"https://Stackoverflow.com/questions/280634",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/15177/"
] |
How can I check if a string ends with a particular character in JavaScript?
Example: I have a string
```
var str = "mystring#";
```
I want to know if that string is ending with `#`. How can I check it?
1. Is there a `endsWith()` method in JavaScript?
2. One solution I have is take the length of the string and get the last character and check it.
Is this the best way or there is any other way?
|
**UPDATE (Nov 24th, 2015):**
This answer is originally posted in the year 2010 (SIX years back.) so please take note of these insightful comments:
* [Shauna](https://stackoverflow.com/users/570040/shauna) -
>
> Update for Googlers - Looks like ECMA6 adds this function. The MDN article also shows a polyfill. <https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/endsWith>
>
>
>
* [T.J. Crowder](https://stackoverflow.com/users/157247/t-j-crowder) -
>
> Creating substrings isn't expensive on modern browsers; it may well have been in 2010 when this answer was posted. These days, the simple `this.substr(-suffix.length) === suffix` approach is fastest on Chrome, the same on IE11 as indexOf, and only 4% slower (fergetaboutit territory) on Firefox: <https://jsben.ch/OJzlM> And faster across the board when the result is false: [jsperf.com/endswith-stackoverflow-when-false](http://jsperf.com/endswith-stackoverflow-when-false) **Of course, with ES6 adding endsWith, the point is moot. :-)**
>
>
>
---
**ORIGINAL ANSWER:**
I know this is a year old question... but I need this too and I need it to work cross-browser so... **combining everyone's answer and comments** and simplifying it a bit:
```
String.prototype.endsWith = function(suffix) {
return this.indexOf(suffix, this.length - suffix.length) !== -1;
};
```
* Doesn't create a substring
* Uses native `indexOf` function for fastest results
* Skip unnecessary comparisons using the second parameter of `indexOf` to skip ahead
* Works in Internet Explorer
* NO Regex complications
---
Also, if you don't like stuffing things in native data structure's prototypes, here's a standalone version:
```
function endsWith(str, suffix) {
return str.indexOf(suffix, str.length - suffix.length) !== -1;
}
```
---
**EDIT:** As noted by @hamish in the comments, if you want to err on the safe side and check if an implementation has already been provided, you can just adds a `typeof` check like so:
```
if (typeof String.prototype.endsWith !== 'function') {
String.prototype.endsWith = function(suffix) {
return this.indexOf(suffix, this.length - suffix.length) !== -1;
};
}
```
|
280,672 |
<p>I have let's say two pc's.PC-a and PC-b which both have the same application installed with java db support.I want from time to time to copy the data from the database on PC-a to database to PC-b and vice-versa so the two PC's to have the same data all the time.
Is there an already implemented API in the database layer for this(i.e 1.export-backup database from PC-a 2.import-merge databases to PC-b) or i have to do this in the sql layer(manually)?</p>
|
[
{
"answer_id": 280717,
"author": "Chris Kimpton",
"author_id": 48310,
"author_profile": "https://Stackoverflow.com/users/48310",
"pm_score": 1,
"selected": false,
"text": "<p>I guess you are using <a href=\"http://developers.sun.com/javadb/\" rel=\"nofollow noreferrer\">Java DB (aka Derby)</a> - in which case, assuming you just can't use a single instance, you can do a <a href=\"http://db.apache.org/derby/docs/10.3/adminguide/\" rel=\"nofollow noreferrer\">backup/restore</a>.</p>\n"
},
{
"answer_id": 281427,
"author": "w-ll",
"author_id": 146637,
"author_profile": "https://Stackoverflow.com/users/146637",
"pm_score": 1,
"selected": false,
"text": "<p>Why dont you have the database on one pc. and have all other pc's request data from the host pc</p>\n"
},
{
"answer_id": 295505,
"author": "Chris Kimpton",
"author_id": 48310,
"author_profile": "https://Stackoverflow.com/users/48310",
"pm_score": 2,
"selected": false,
"text": "<p>As you mention in the comments that you want to \"merge\" the databases, this sounds like you need to write custom code to do this, as presumably there could be conficts - the same key in both, but with different details against it, for example.</p>\n"
},
{
"answer_id": 1235367,
"author": "Chris K",
"author_id": 51789,
"author_profile": "https://Stackoverflow.com/users/51789",
"pm_score": 2,
"selected": true,
"text": "<p>In short: You can't do this without some work on your side. SalesLogix fixed this problem by giving everything a site code, so here's how your table looked: </p>\n\n<pre><code>Customer: \n SiteCode varchar,\n CustomerID varchar, \n .... \n primary key(siteCode, CustomerID) \n</code></pre>\n\n<p>So now you would take your databases, and match up each record by primary key. Where there are conflicts you would have to provide a report to the end-user, on what data was different. </p>\n\n<p>Say machine1: </p>\n\n<pre><code> SiteCode|CustomerID|CustName |phone |email \n 1 XXX |0001 |Customer1 |555.555.1212 |[email protected]\n</code></pre>\n\n<p>and on machine2: </p>\n\n<pre><code> SiteCode|CustomerID|CustName |phone |email \n 2 XXY |0001 |customer2 |555.555.1213 |[email protected] \n 3 XXX |0001 |customer1 |555.555.1212 |[email protected]\n</code></pre>\n\n<p>When performing a resolution: </p>\n\n<ul>\n<li>Record 1 and 3 are in conflict, because the PK matches, but the data doesnt (email is different). </li>\n<li>Record 2 is unique, and can freely exist in both databases.</li>\n</ul>\n\n<p>There is <em>NO</em> way to do this automatically without error or data corruption or referential integrity issues.</p>\n"
}
] |
2008/11/11
|
[
"https://Stackoverflow.com/questions/280672",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/36525/"
] |
I have let's say two pc's.PC-a and PC-b which both have the same application installed with java db support.I want from time to time to copy the data from the database on PC-a to database to PC-b and vice-versa so the two PC's to have the same data all the time.
Is there an already implemented API in the database layer for this(i.e 1.export-backup database from PC-a 2.import-merge databases to PC-b) or i have to do this in the sql layer(manually)?
|
In short: You can't do this without some work on your side. SalesLogix fixed this problem by giving everything a site code, so here's how your table looked:
```
Customer:
SiteCode varchar,
CustomerID varchar,
....
primary key(siteCode, CustomerID)
```
So now you would take your databases, and match up each record by primary key. Where there are conflicts you would have to provide a report to the end-user, on what data was different.
Say machine1:
```
SiteCode|CustomerID|CustName |phone |email
1 XXX |0001 |Customer1 |555.555.1212 |[email protected]
```
and on machine2:
```
SiteCode|CustomerID|CustName |phone |email
2 XXY |0001 |customer2 |555.555.1213 |[email protected]
3 XXX |0001 |customer1 |555.555.1212 |[email protected]
```
When performing a resolution:
* Record 1 and 3 are in conflict, because the PK matches, but the data doesnt (email is different).
* Record 2 is unique, and can freely exist in both databases.
There is *NO* way to do this automatically without error or data corruption or referential integrity issues.
|
280,680 |
<pre><code>$images = array();
$images[0][0] = "boxes/blue.jpg";
$images[0][1] = "blah.html";
$images[1][0] = "boxes/green.jpg";
$images[1][1] = "blah.html";
$images[2][0] = "boxes/orange.jpg";
$images[2][1] = "blah.html";
$images[3][0] = "boxes/pink.jpg";
$images[3][1] = "blah.html";
$images[4][0] = "boxes/purple.jpg";
$images[4][1] = "blah.html";
$images[5][0] = "boxes/red.jpg";
$images[5][1] = "blah.html";
$images[6][0] = "boxes/yellow.jpg";
$images[6][1] = "blah.html";
$i = 0;
*echo "<a href='" . $images[0][1] . "'><img src='" . $images[0][0] . "' /></a>";
$boxes = array();
while($i<5)
{
$rand = rand(0,(sizeof($images)-1));
//echo $rand;
$slice = array_splice($images, $rand);
$boxes[$i] = $slice;
$i++;
}*
</code></pre>
<p>I am trying to get a random image picker to choose from a list of images provided by the $images array. However, I am unable to fill the $boxes array with anything other than "Array". Can anyone tell me why? Any help is much appreciated</p>
<p>UPDATE</p>
<p>I am now using the code below and it breaks whenever it comes across an empty element. Unless i am very much mistaken, shouldn't splice patch up holes like that?</p>
<pre><code>$rand = rand(0,(sizeof($images)));
array_splice($images, $rand);
$i = 0;
while($i<5)
{
echo "<a href='" . $images[$i][1] . "'><img src='" . $images[$i][0] . "' /></a>";
$i++;
}
</code></pre>
|
[
{
"answer_id": 280686,
"author": "Davide Gualano",
"author_id": 28582,
"author_profile": "https://Stackoverflow.com/users/28582",
"pm_score": 0,
"selected": false,
"text": "<p><a href=\"http://it.php.net/manual/en/function.array-splice.php\" rel=\"nofollow noreferrer\">array_splice()</a> returns an array.</p>\n\n<p>You can try something like this:</p>\n\n<pre><code>while($i<5)\n{\n $rand = rand(0,(sizeof($images)-1));\n $boxes[$i] = $images[$rand];\n $i++;\n}\n</code></pre>\n"
},
{
"answer_id": 280709,
"author": "Tom Haigh",
"author_id": 22224,
"author_profile": "https://Stackoverflow.com/users/22224",
"pm_score": 2,
"selected": false,
"text": "<p>This might be a nicer way of doing it:</p>\n\n<pre><code>foreach (array_rand($images, 5) as $key) {\n $boxes[] = $images[$key];\n}\n</code></pre>\n"
},
{
"answer_id": 280710,
"author": "ZombieSheep",
"author_id": 377,
"author_profile": "https://Stackoverflow.com/users/377",
"pm_score": 3,
"selected": true,
"text": "<p>Slightly off topic, but wouldn't it be easier in this case (picking 5 items from a list of 6) just to pick one element and discard it from the original array, and then use the original? This will also ensure you do not get duplicates in the resultant array.</p>\n\n<p>I realise that you may have more than 6 items in the original, and may want less than 5 from it, but I'm talking specifically about the example posted.</p>\n"
}
] |
2008/11/11
|
[
"https://Stackoverflow.com/questions/280680",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/31677/"
] |
```
$images = array();
$images[0][0] = "boxes/blue.jpg";
$images[0][1] = "blah.html";
$images[1][0] = "boxes/green.jpg";
$images[1][1] = "blah.html";
$images[2][0] = "boxes/orange.jpg";
$images[2][1] = "blah.html";
$images[3][0] = "boxes/pink.jpg";
$images[3][1] = "blah.html";
$images[4][0] = "boxes/purple.jpg";
$images[4][1] = "blah.html";
$images[5][0] = "boxes/red.jpg";
$images[5][1] = "blah.html";
$images[6][0] = "boxes/yellow.jpg";
$images[6][1] = "blah.html";
$i = 0;
*echo "<a href='" . $images[0][1] . "'><img src='" . $images[0][0] . "' /></a>";
$boxes = array();
while($i<5)
{
$rand = rand(0,(sizeof($images)-1));
//echo $rand;
$slice = array_splice($images, $rand);
$boxes[$i] = $slice;
$i++;
}*
```
I am trying to get a random image picker to choose from a list of images provided by the $images array. However, I am unable to fill the $boxes array with anything other than "Array". Can anyone tell me why? Any help is much appreciated
UPDATE
I am now using the code below and it breaks whenever it comes across an empty element. Unless i am very much mistaken, shouldn't splice patch up holes like that?
```
$rand = rand(0,(sizeof($images)));
array_splice($images, $rand);
$i = 0;
while($i<5)
{
echo "<a href='" . $images[$i][1] . "'><img src='" . $images[$i][0] . "' /></a>";
$i++;
}
```
|
Slightly off topic, but wouldn't it be easier in this case (picking 5 items from a list of 6) just to pick one element and discard it from the original array, and then use the original? This will also ensure you do not get duplicates in the resultant array.
I realise that you may have more than 6 items in the original, and may want less than 5 from it, but I'm talking specifically about the example posted.
|
280,687 |
<p>I am trying to change the rows output by PHP in a table to links. I have added the a href tags to the example below, however it results in an unexpected <code>T_VARIABLE</code>. I have tried it without the extra quotes, but this displays a blank table. I am not sure what the flaw in the logic is.</p>
<pre><code>while($row = mysql_fetch_row($result))
{
echo "<tr>";
// $row is array... foreach( .. ) puts every element
// of $row to $cell variable
foreach($row as $cell)
echo "<td><a href="$cell"</a></td>";
echo "</tr>\n";
}
</code></pre>
|
[
{
"answer_id": 280691,
"author": "Tom Haigh",
"author_id": 22224,
"author_profile": "https://Stackoverflow.com/users/22224",
"pm_score": 1,
"selected": false,
"text": "<ol>\n<li><p>I'm not sure, but you should not really trust anything sent in the header, as it could be faked by the user.</p></li>\n<li><p>It depends on how the server works. For example in PHP your script will not run until the file upload is complete, so this wouldn't be possible.</p></li>\n</ol>\n"
},
{
"answer_id": 280702,
"author": "Vladimir Dyuzhev",
"author_id": 1163802,
"author_profile": "https://Stackoverflow.com/users/1163802",
"pm_score": 5,
"selected": true,
"text": "<p><a href=\"http://www.faqs.org/rfcs/rfc1867.html\" rel=\"noreferrer\">http://www.faqs.org/rfcs/rfc1867.html</a></p>\n\n<p><em>HTTP clients are\n encouraged to supply content-length for overall file input so that a\n busy server could detect if the proposed file data is too large to be\n processed reasonably</em></p>\n\n<p>But the content-length is not required, so you cannot rely on it. Also, an attacker can forge a wrong content-length. </p>\n\n<p>To read the file content is the only reliable way. Having said that, if the content-lenght is present and is too big, to close the connection would be a reasonable thing to do.</p>\n\n<p>Also, the content is sent as multipart, so most of the modern frameworks decode it first. That means you won't get the file byte stream until the framework is done, which could mean \"until the whole file is uploaded\".</p>\n"
},
{
"answer_id": 280750,
"author": "vincent",
"author_id": 34871,
"author_profile": "https://Stackoverflow.com/users/34871",
"pm_score": 2,
"selected": false,
"text": "<p>EDIT : before going too far, you may want to check this other answer relying on apache configuration : <a href=\"https://stackoverflow.com/questions/307679/using-jquery-restricting-file-size-before-uploading#307861\">Using jQuery, Restricting File Size Before Uploading</a> . the description below is only useful if you really need even more custom feedback.</p>\n\n<p>Yes, you can get some information upfront, before allowing the upload of the whole file.</p>\n\n<p>Here's an example of header coming from a form with the <code>enctype=\"multipart/form-data\"</code> attribute :</p>\n\n<pre><code>POST / HTTP/1.1\nHost: 127.0.0.1:8000\nUser-Agent: Mozilla/5.0 (Macintosh; U; Intel Mac OS X 10.5; en-US; rv:1.9.0.3) Gecko/2008092414 Firefox/3.0.3\nAccept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8\nAccept-Language: en-us,en;q=0.7,fr-be;q=0.3\nAccept-Encoding: gzip,deflate\nAccept-Charset: ISO-8859-1,utf-8;q=0.7,*;q=0.7\nKeep-Alive: 300\nConnection: keep-alive\nContent-Type: multipart/form-data; boundary=---------------------------886261531333586100294758961\nContent-Length: 135361\n\n-----------------------------886261531333586100294758961\nContent-Disposition: form-data; name=\"\"; filename=\"IMG_1132.jpg\"\nContent-Type: image/jpeg\n\n(data starts here and ends with -----------------------------886261531333586100294758961 )\n</code></pre>\n\n<p>You have the Content-Length in the header, and additionally there is the Content-Type in the header of the file part ( each file has its own header, which is the purpose of multipart encoding ). Beware that it's the browser responsibility to set a relevant Content-Type by guessing the file type ; you can't guarantee it, but it should be fairly reliable for early rejection ( yet you'd better check the whole file when it's entirely available ).</p>\n\n<p>Now, there is a gotcha. I used to filter image files like that, not on the size, but on the content-type ; but as you want to stop the request as soon as possible, the same problem arises : <strong>the browser only gets your response once the whole request is sent, including form content and thus uploaded files</strong>.</p>\n\n<p>If you don't want the provided content and stop the upload, you have no choice but to brutally close the socket. The user will only see a confusing \"connection reset by peer\" message. And that sucks, but it's by design.</p>\n\n<p>So you only want to use this method in cases of background asynchronous checks ( using a timer that checks the file field ). So I had that hack :</p>\n\n<ul>\n<li>I use jquery to tell me if the file field has changed</li>\n<li>When a new file is chosen, <em>disable all other file fields on the same form</em> to get only that one.</li>\n<li>Send the file asynchronously ( jQuery can do it for you, it uses a hidden frame )</li>\n<li>Server-side, check the header ( content-length, content-type, ... ), cut the connection as soon as you got what you need.</li>\n<li>Set a session variable telling if that file was OK or not.</li>\n<li>Client-side, as the file is uploaded to a frame <strong>you don't even get any kind of feedback if the connection is closed</strong>. Your only alternative is a timer.</li>\n<li>Client-side, a timer polls the server to get a status for the uploaded file. Server side, you have that session variable set, send it back to the brower.</li>\n<li>The client has the status code ; render it to your form : error message, green checkmark/red X, whatever. Reset the file field or disable the form, you decide. Don't forget to re-enable other file fields.</li>\n</ul>\n\n<p>Quite messy, eh ? If any of you has a better alternative, I'm all ears.</p>\n"
}
] |
2008/11/11
|
[
"https://Stackoverflow.com/questions/280687",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1246613/"
] |
I am trying to change the rows output by PHP in a table to links. I have added the a href tags to the example below, however it results in an unexpected `T_VARIABLE`. I have tried it without the extra quotes, but this displays a blank table. I am not sure what the flaw in the logic is.
```
while($row = mysql_fetch_row($result))
{
echo "<tr>";
// $row is array... foreach( .. ) puts every element
// of $row to $cell variable
foreach($row as $cell)
echo "<td><a href="$cell"</a></td>";
echo "</tr>\n";
}
```
|
<http://www.faqs.org/rfcs/rfc1867.html>
*HTTP clients are
encouraged to supply content-length for overall file input so that a
busy server could detect if the proposed file data is too large to be
processed reasonably*
But the content-length is not required, so you cannot rely on it. Also, an attacker can forge a wrong content-length.
To read the file content is the only reliable way. Having said that, if the content-lenght is present and is too big, to close the connection would be a reasonable thing to do.
Also, the content is sent as multipart, so most of the modern frameworks decode it first. That means you won't get the file byte stream until the framework is done, which could mean "until the whole file is uploaded".
|
280,706 |
<p>I've been thinking of ways of providing syntactic sugar for a framework I have been working on. I want to deal with Immitable objects exclusively.</p>
<h3>Say I have an immutable object and wish to create a modified version of it. Would, in your view, a non-instantiable class with a single static factory method break OO principles ?</h3>
<br>
<blockquote>
<p>As an example using a String:</p>
<pre><code>public final class LOWERCASE {
private LOWERCASE() {}
public static String string( final String STRING ) {
return STRING.toLowerCase();
}
}
</code></pre>
<p>Therefore from this example I could write:</p>
<pre><code>String lowercaseString = LOWERCASE.string( targetString );
</code></pre>
<p>Which I find very readable.</p>
</blockquote>
<br>
<h3>Any provisos against such an approach?</h3>
|
[
{
"answer_id": 280718,
"author": "Erik Hesselink",
"author_id": 8071,
"author_profile": "https://Stackoverflow.com/users/8071",
"pm_score": 1,
"selected": false,
"text": "<p>Usually on immutable objects, I would have a method returning a modified version of the object. So if you have some immutable collection, it can have a sort() method, that returns a new collection that is sorted. However, in your String example this is not possible, since you cannot touch the String class.</p>\n\n<p>Your approach is quite readable, and I think for edge cases like this, is perfectly fine. For immutable objects you write yourself, I'd have the method on the object itself.</p>\n\n<p><a href=\"http://blogs.msdn.com/ericlippert/archive/tags/Immutability/default.aspx\" rel=\"nofollow noreferrer\">Eric Lippert's series on immutable objects in C#</a> is quite good, by the way.</p>\n"
},
{
"answer_id": 280727,
"author": "kgiannakakis",
"author_id": 24054,
"author_profile": "https://Stackoverflow.com/users/24054",
"pm_score": 3,
"selected": true,
"text": "<p>I don't think it's a good idea to create one class per method. You could instead create a static only methods class, named e.g StringUtils and implement the methods. This way you would call:</p>\n\n<p>String lowerCaseString = StringUtils.lowercase( targetString );</p>\n\n<p>This would also offer you intellisense help while you are typing. The list of your classes will go otherwise too big. Even for this simple example, you should implement more than one Lowercase classes, so that you could also cater for circumstances that the CulutureInfo must be taken into consideration.</p>\n\n<p>I don't think this breaks OO principles in any way or that is bad design. In other languages, Ruby for example, you could add your methods directly to String class. Methods that end with ! denote that the original object is modified. All other methods return a modified copy. Ruby on Rails framework adds some methods to the String class and there is some debate about whether this is a good technique or not. It is definitely handy though.</p>\n"
},
{
"answer_id": 280752,
"author": "bruno conde",
"author_id": 31136,
"author_profile": "https://Stackoverflow.com/users/31136",
"pm_score": 1,
"selected": false,
"text": "<p>In my opinion, the only point of such a factory class would be if the class provided different kinds of immutable objects.</p>\n\n<p>Ex:</p>\n\n<pre><code>public final class Lowercase {\n\n private Lowercase() {}\n\n public static String string( final String string ) {\n\n return new String( string.toLowerCase() );\n }\n\n public static Foo foo( final Foo f ) {\n boolean isLowerCase = true;\n return new Foo(f, isLowerCase );\n }\n}\n</code></pre>\n\n<p>Otherwise, you should implement your method in the immutable class itself like toLowerCase() in String Class.</p>\n\n<p>Either way, I don't think this breaks any OO principle.</p>\n"
},
{
"answer_id": 280754,
"author": "reallyinsane",
"author_id": 35407,
"author_profile": "https://Stackoverflow.com/users/35407",
"pm_score": 1,
"selected": false,
"text": "<p>I agree with Erik. Immutable objects should always have a method returning a modified version of the object rather than a static method. There are also examples in the JDK:</p>\n\n<ul>\n<li>String.subString(int)</li>\n<li>BigDecimal.movePointLeft(int)</li>\n</ul>\n\n<p>Doing it this way has the advantage that you don't need to pass the instance you want to modify as argument for a method. For classes like String or Integer I would prefer to use a wrapper class. Then you can control when such an object is created (by constructor of the wrapper class or one of the methods of the class). If you would use the class Integer it is much more complicated to control this as everyone can create an instance of it.</p>\n\n<p>On the other hand you're example is regarded to some utility classes like <a href=\"http://commons.apache.org/lang/api-release/org/apache/commons/lang/StringUtils.html\" rel=\"nofollow noreferrer\">StringUtils</a> of the apache commons-lang package. Just have a look at this as I think that you wanted to create something like this. (Don't reinvent the wheel)</p>\n"
},
{
"answer_id": 280863,
"author": "Ken Gentle",
"author_id": 8709,
"author_profile": "https://Stackoverflow.com/users/8709",
"pm_score": 1,
"selected": false,
"text": "<p><code>new String()</code> is a code smell - it is almost <em>always</em> unnecessary because of the <em>immutability</em> of <code>String</code>. Once a <code>String</code> instance has a value, that instance will never, ever have a different value.</p>\n\n<p>In the following method, <code>new String()</code> is redundant: </p>\n\n<pre><code>public static String string( final String string ) {\n return new String( string.toLowerCase() );\n}\n</code></pre>\n\n<p><code>toLowerCase()</code> returns a new (different) <code>String</code> instance - <code>new String()</code> doesn't do anything beneficial here other than cause another object creation having the exact value of the <code>String</code> instance returned by <code>toLowerCase()</code></p>\n\n<p>Here's a small Groovy script showing the concept (I hope - note, this is Java under the scripting language):</p>\n\n<pre><code>String a = 'CamelCase'\nString b = a.toLowerCase()\n\nprintln \"a='${a}'\"\nprintln \"b='${b}'\"\n</code></pre>\n\n<p>producing</p>\n\n<pre><code>a='CamelCase'\nb='camelcase'\n</code></pre>\n\n<p>Note that <code>a</code> <em>didn't change</em> - it is immutable; <code>b</code> is a new <code>String</code> value.</p>\n\n<p>The same is true for <code>BigDecimal.movePointLeft()</code> or any other method on <code>BigDecimal</code> that returns a <code>BigDecimal</code> - they're new instances, leaving the original instance unchanged.</p>\n\n<p>OK, now to answer your question:</p>\n\n<p>Having a set of operations for <code>Strings</code> that perform a useful purpose in your application is a fine idea. Using a factory probably isn't necessary for something like <code>String</code>, but might be for a different immutable class that takes some effort to construct.</p>\n\n<p>In the case where it is not possible to extend the base class, like <code>String</code>, a <code>static method</code>s class as @kgiannakakis described is fine.</p>\n\n<p>Otherwise, if the \"immutable\" class is part of the application, where you have access to the class declaration/definition, methods returning a new instance, in the model of <code>BigDecimal</code>, <code>String</code>, etc, would be preferable. This is in essence what @Erik Hesselink ,@Bruno Conde and @reallyinsane have said.</p>\n"
}
] |
2008/11/11
|
[
"https://Stackoverflow.com/questions/280706",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4857/"
] |
I've been thinking of ways of providing syntactic sugar for a framework I have been working on. I want to deal with Immitable objects exclusively.
### Say I have an immutable object and wish to create a modified version of it. Would, in your view, a non-instantiable class with a single static factory method break OO principles ?
>
> As an example using a String:
>
>
>
> ```
> public final class LOWERCASE {
>
> private LOWERCASE() {}
>
> public static String string( final String STRING ) {
>
> return STRING.toLowerCase();
> }
> }
>
> ```
>
> Therefore from this example I could write:
>
>
>
> ```
> String lowercaseString = LOWERCASE.string( targetString );
>
> ```
>
> Which I find very readable.
>
>
>
### Any provisos against such an approach?
|
I don't think it's a good idea to create one class per method. You could instead create a static only methods class, named e.g StringUtils and implement the methods. This way you would call:
String lowerCaseString = StringUtils.lowercase( targetString );
This would also offer you intellisense help while you are typing. The list of your classes will go otherwise too big. Even for this simple example, you should implement more than one Lowercase classes, so that you could also cater for circumstances that the CulutureInfo must be taken into consideration.
I don't think this breaks OO principles in any way or that is bad design. In other languages, Ruby for example, you could add your methods directly to String class. Methods that end with ! denote that the original object is modified. All other methods return a modified copy. Ruby on Rails framework adds some methods to the String class and there is some debate about whether this is a good technique or not. It is definitely handy though.
|
280,712 |
<p>There should be something akin to <code>\w</code> that can match any code-point in Letters or Marks category (not just the ASCII ones), and hopefully have filters like [[P*]] for punctuation, etc.</p>
|
[
{
"answer_id": 280762,
"author": "Tomalak",
"author_id": 18771,
"author_profile": "https://Stackoverflow.com/users/18771",
"pm_score": 8,
"selected": false,
"text": "<h2>Situation for ES 6</h2>\n<p>The ECMAScript language specification, edition 6 (also commonly known as ES2015), includes Unicode-aware regular expressions. Support must be enabled with the <code>u</code> modifier on the regex. See <a href=\"https://mathiasbynens.be/notes/es6-unicode-regex\" rel=\"nofollow noreferrer\"><em>Unicode-aware regular expressions in ES6</em></a> for a break-down of the feature and some caveats.</p>\n<p>ES6 is widely adopted in both browsers and stand-alone Javascript runtimes such as Node.js, so using this feature won't require extra effort in most cases. Full compatibility list: <a href=\"https://kangax.github.io/compat-table/es6/\" rel=\"nofollow noreferrer\">https://kangax.github.io/compat-table/es6/</a></p>\n<h2>Situation for ES 5 and below (legacy browsers)</h2>\n<p>There is <a href=\"http://mths.be/regexpu\" rel=\"nofollow noreferrer\">a transpiler named <em>regexpu</em></a> that translates ES6 Unicode regular expressions into equivalent ES5. It can be used as part of your build process. <a href=\"http://mothereff.in/regexpu\" rel=\"nofollow noreferrer\">Try it out online.</a>.</p>\n<p>Even though JavaScript operates on Unicode strings, it does not implement Unicode-aware character classes and has no concept of POSIX character classes or Unicode blocks/sub-ranges.</p>\n<ul>\n<li><p><a href=\"https://mathiasbynens.be/notes/javascript-unicode#regex\" rel=\"nofollow noreferrer\">Issues with Unicode in JavaScript regular expressions</a></p>\n</li>\n<li><p>Check your expectations here: <a href=\"http://hamstersoup.com/javascript/regexp_character_class_tester.html\" rel=\"nofollow noreferrer\">Javascript RegExp Unicode Character Class tester</a> (<em>Edit:</em> the original page is down, <a href=\"http://web.archive.org/web/20101104085449/http://hamstersoup.com/javascript/regexp_character_class_tester.html\" rel=\"nofollow noreferrer\">the Internet Archive still has a copy</a>.)</p>\n</li>\n<li><p>Flagrant Badassery has an article on <a href=\"http://blog.stevenlevithan.com/archives/javascript-regex-and-unicode\" rel=\"nofollow noreferrer\">JavaScript, Regex, and Unicode</a> that sheds some light on the matter.</p>\n</li>\n<li><p>Also read <a href=\"https://stackoverflow.com/questions/14389/\">Regex and Unicode</a> here on SO. Probably you have to build your own "punctuation character class".</p>\n</li>\n<li><p>Check out the <a href=\"http://kourge.net/projects/regexp-unicode-block\" rel=\"nofollow noreferrer\">Regular Expression: Match Unicode Block Range</a> builder (<a href=\"https://web.archive.org/web/20191219033259/http://kourge.net/projects/regexp-unicode-block\" rel=\"nofollow noreferrer\">archived copy</a>), which lets you build a JavaScript regular expression that matches characters that fall in any number of specified Unicode blocks.</p>\n<p>I just did it for the "General Punctuation" and "Supplemental Punctuation" sub-ranges, and the result is as simple and straight-forward as I would have expected it:</p>\n<pre><code> [\\u2000-\\u206F\\u2E00-\\u2E7F]\n</code></pre>\n</li>\n<li><p>There also is <a href=\"http://xregexp.com/\" rel=\"nofollow noreferrer\">XRegExp</a>, a project that brings <a href=\"http://xregexp.com/plugins/#unicode\" rel=\"nofollow noreferrer\">Unicode support to JavaScript</a> by offering an alternative regex engine with extended capabilities.</p>\n</li>\n<li><p>And of course, required reading: <a href=\"https://mathiasbynens.be/notes/javascript-unicode\" rel=\"nofollow noreferrer\">mathiasbynens.be - JavaScript has a Unicode problem</a>:</p>\n</li>\n</ul>\n"
},
{
"answer_id": 320254,
"author": "Jan Goyvaerts",
"author_id": 33358,
"author_profile": "https://Stackoverflow.com/users/33358",
"pm_score": 4,
"selected": false,
"text": "<p>In JavaScript, \\w and \\d are ASCII, while \\s is Unicode. Don't ask me why. JavaScript does support \\p with Unicode categories, which you can use to emulate a Unicode-aware \\w and \\d.</p>\n\n<p>For \\d use \\p{N} (numbers)</p>\n\n<p>For \\w use [\\p{L}\\p{N}\\p{Pc}\\p{M}] (letters, numbers, underscores, marks)</p>\n\n<p><strong>Update:</strong> Unfortunately, I was wrong about this. JavaScript does does not officially support \\p either, though some implementations may still support this. The only Unicode support in JavaScript regexes is matching specific code points with \\uFFFF. You can use those in ranges in character classes.</p>\n"
},
{
"answer_id": 4448502,
"author": "Tim Down",
"author_id": 96100,
"author_profile": "https://Stackoverflow.com/users/96100",
"pm_score": 5,
"selected": false,
"text": "<p>As mentioned in other answers, JavaScript regexes have no support for Unicode character classes. However, there is a library that does provide this: Steven Levithan's excellent <a href=\"http://xregexp.com/\" rel=\"noreferrer\">XRegExp</a> and its <a href=\"http://xregexp.com/plugins/\" rel=\"noreferrer\">Unicode plug-in</a>.</p>\n"
},
{
"answer_id": 8933546,
"author": "mgibsonbr",
"author_id": 520779,
"author_profile": "https://Stackoverflow.com/users/520779",
"pm_score": 6,
"selected": false,
"text": "<p>Having also not found a good solution, I wrote a small <a href=\"https://marcelogibson.com/stackoverflow/unicode_hack.js\" rel=\"noreferrer\">script</a> a long time ago, by downloading data from the unicode <a href=\"http://unicode.org/versions/Unicode5.0.0/\" rel=\"noreferrer\">specification</a> (v.5.0.0) and generating intervals for each unicode category and subcategory in the BMP (lately replaced by <a href=\"https://ideone.com/04llh4\" rel=\"noreferrer\">a small Java program</a> that uses its own native Unicode support).</p>\n\n<p>Basically it converts <code>\\p{...}</code> to a range of values, much like the output of the <a href=\"http://kourge.net/projects/regexp-unicode-block\" rel=\"noreferrer\">tool</a> mentioned by Tomalak, but the intervals can end up quite large (since it's not dealing with blocks, but with characters scattered through many different places).</p>\n\n<p>For instance, a Regex written like this:</p>\n\n<pre><code>var regex = unicode_hack(/\\p{L}(\\p{L}|\\p{Nd})*/g);\n</code></pre>\n\n<p>Will be converted to something like this:</p>\n\n<pre><code>/[\\u0041-\\u005a\\u0061-\\u007a...]([...]|[\\u0030-\\u0039\\u0660-\\u0669...])*/g\n</code></pre>\n\n<p>Haven't used it a lot in practice, but it seems to work fine from my tests, so I'm posting here in case someone find it useful. Despite the length of the resulting regexes (the example above has 3591 characters when expanded), the performance seems to be acceptable (see the <a href=\"http://jsfiddle.net/mgibsonbr/Waxkc/\" rel=\"noreferrer\">tests</a> at jsFiddle; thanks to @modiX and @Lwangaman for the improvements).</p>\n\n<p>Here's the <a href=\"http://difnet.com.br/opensource/unicode_hack.js\" rel=\"noreferrer\">source</a> (raw, 27.5KB; <a href=\"http://difnet.com.br/opensource/unicode_hack.js\" rel=\"noreferrer\">minified</a>, 24.9KB, not much better...). It <em>might</em> be made smaller by unescaping the unicode characters, but OTOH will run the risk of encoding issues, so I'm leaving as it is. Hopefully with ES6 this kind of thing won't be necessary anymore.</p>\n\n<p><strong>Update</strong>: this looks like the same strategy adopted in the <a href=\"http://xregexp.com/plugins/#unicode\" rel=\"noreferrer\">XRegExp Unicode plug-in</a> mentioned by Tim Down, except that in this case regular JavaScript regexes are being used.</p>\n"
},
{
"answer_id": 30058779,
"author": "fiatjaf",
"author_id": 973380,
"author_profile": "https://Stackoverflow.com/users/973380",
"pm_score": 3,
"selected": false,
"text": "<p>This will do it:</p>\n\n<pre><code>/[A-Za-z\\u00C0-\\u00FF ]+/.exec('hipopótamo maçã pólen ñ poção água língüa')\n</code></pre>\n\n<p>It explicitly selects a range of unicode characters.\nIt will work for latin characters, but other strange characters may be out of this range.</p>\n"
},
{
"answer_id": 30130489,
"author": "Daniel",
"author_id": 616974,
"author_profile": "https://Stackoverflow.com/users/616974",
"pm_score": 3,
"selected": false,
"text": "<p>If you are using <a href=\"https://babeljs.io/\" rel=\"nofollow noreferrer\">Babel</a> then <a href=\"https://github.com/babel/babel/blob/0f1f5e3565623721c96f234a869921a7568b564b/src/babel/transformation/transformers/es6/regex.unicode.js\" rel=\"nofollow noreferrer\">Unicode support</a> is already available.</p>\n\n<p>I also released a plugin which transforms your source code such that you can write regular expressions like <code>/^\\p{L}+$/</code>. These will then be transformed into something that browsers understand.</p>\n\n<p>Here is the project page of the plugin:</p>\n\n<p><em><a href=\"https://github.com/danielberndt/babel-plugin-utf-8-regex\" rel=\"nofollow noreferrer\">babel-plugin-utf-8-regex</a></em></p>\n"
},
{
"answer_id": 37668315,
"author": "Laurel",
"author_id": 6083675,
"author_profile": "https://Stackoverflow.com/users/6083675",
"pm_score": 6,
"selected": false,
"text": "<p>Personally, I would rather not install another library just to get this functionality. My answer does not require any external libraries, and it may also work with little modification for regex flavors besides JavaScript.</p>\n\n<p>Unicode's <a href=\"http://unicode.org/cldr/utility/list-unicodeset.jsp\">website</a> provides a way to translate Unicode categories into a set of code points. Since it's <em>Unicode</em>'s website, the information from it should be accurate.</p>\n\n<p>Note that you will need to exclude the high-end characters, as JavaScript can only handle characters less than <code>FFFF</code> (hex). I suggest checking the Abbreviate Collate, and Escape check boxes, which strike a balance between avoiding unprintable characters and minimizing the size of the regex.</p>\n\n<p>Here are some common expansions of different Unicode properties:</p>\n\n<p><code>\\p{L}</code> (Letters):</p>\n\n<pre><code>[A-Za-z\\u00AA\\u00B5\\u00BA\\u00C0-\\u00D6\\u00D8-\\u00F6\\u00F8-\\u02C1\\u02C6-\\u02D1\\u02E0-\\u02E4\\u02EC\\u02EE\\u0370-\\u0374\\u0376\\u0377\\u037A-\\u037D\\u037F\\u0386\\u0388-\\u038A\\u038C\\u038E-\\u03A1\\u03A3-\\u03F5\\u03F7-\\u0481\\u048A-\\u052F\\u0531-\\u0556\\u0559\\u0561-\\u0587\\u05D0-\\u05EA\\u05F0-\\u05F2\\u0620-\\u064A\\u066E\\u066F\\u0671-\\u06D3\\u06D5\\u06E5\\u06E6\\u06EE\\u06EF\\u06FA-\\u06FC\\u06FF\\u0710\\u0712-\\u072F\\u074D-\\u07A5\\u07B1\\u07CA-\\u07EA\\u07F4\\u07F5\\u07FA\\u0800-\\u0815\\u081A\\u0824\\u0828\\u0840-\\u0858\\u08A0-\\u08B4\\u0904-\\u0939\\u093D\\u0950\\u0958-\\u0961\\u0971-\\u0980\\u0985-\\u098C\\u098F\\u0990\\u0993-\\u09A8\\u09AA-\\u09B0\\u09B2\\u09B6-\\u09B9\\u09BD\\u09CE\\u09DC\\u09DD\\u09DF-\\u09E1\\u09F0\\u09F1\\u0A05-\\u0A0A\\u0A0F\\u0A10\\u0A13-\\u0A28\\u0A2A-\\u0A30\\u0A32\\u0A33\\u0A35\\u0A36\\u0A38\\u0A39\\u0A59-\\u0A5C\\u0A5E\\u0A72-\\u0A74\\u0A85-\\u0A8D\\u0A8F-\\u0A91\\u0A93-\\u0AA8\\u0AAA-\\u0AB0\\u0AB2\\u0AB3\\u0AB5-\\u0AB9\\u0ABD\\u0AD0\\u0AE0\\u0AE1\\u0AF9\\u0B05-\\u0B0C\\u0B0F\\u0B10\\u0B13-\\u0B28\\u0B2A-\\u0B30\\u0B32\\u0B33\\u0B35-\\u0B39\\u0B3D\\u0B5C\\u0B5D\\u0B5F-\\u0B61\\u0B71\\u0B83\\u0B85-\\u0B8A\\u0B8E-\\u0B90\\u0B92-\\u0B95\\u0B99\\u0B9A\\u0B9C\\u0B9E\\u0B9F\\u0BA3\\u0BA4\\u0BA8-\\u0BAA\\u0BAE-\\u0BB9\\u0BD0\\u0C05-\\u0C0C\\u0C0E-\\u0C10\\u0C12-\\u0C28\\u0C2A-\\u0C39\\u0C3D\\u0C58-\\u0C5A\\u0C60\\u0C61\\u0C85-\\u0C8C\\u0C8E-\\u0C90\\u0C92-\\u0CA8\\u0CAA-\\u0CB3\\u0CB5-\\u0CB9\\u0CBD\\u0CDE\\u0CE0\\u0CE1\\u0CF1\\u0CF2\\u0D05-\\u0D0C\\u0D0E-\\u0D10\\u0D12-\\u0D3A\\u0D3D\\u0D4E\\u0D5F-\\u0D61\\u0D7A-\\u0D7F\\u0D85-\\u0D96\\u0D9A-\\u0DB1\\u0DB3-\\u0DBB\\u0DBD\\u0DC0-\\u0DC6\\u0E01-\\u0E30\\u0E32\\u0E33\\u0E40-\\u0E46\\u0E81\\u0E82\\u0E84\\u0E87\\u0E88\\u0E8A\\u0E8D\\u0E94-\\u0E97\\u0E99-\\u0E9F\\u0EA1-\\u0EA3\\u0EA5\\u0EA7\\u0EAA\\u0EAB\\u0EAD-\\u0EB0\\u0EB2\\u0EB3\\u0EBD\\u0EC0-\\u0EC4\\u0EC6\\u0EDC-\\u0EDF\\u0F00\\u0F40-\\u0F47\\u0F49-\\u0F6C\\u0F88-\\u0F8C\\u1000-\\u102A\\u103F\\u1050-\\u1055\\u105A-\\u105D\\u1061\\u1065\\u1066\\u106E-\\u1070\\u1075-\\u1081\\u108E\\u10A0-\\u10C5\\u10C7\\u10CD\\u10D0-\\u10FA\\u10FC-\\u1248\\u124A-\\u124D\\u1250-\\u1256\\u1258\\u125A-\\u125D\\u1260-\\u1288\\u128A-\\u128D\\u1290-\\u12B0\\u12B2-\\u12B5\\u12B8-\\u12BE\\u12C0\\u12C2-\\u12C5\\u12C8-\\u12D6\\u12D8-\\u1310\\u1312-\\u1315\\u1318-\\u135A\\u1380-\\u138F\\u13A0-\\u13F5\\u13F8-\\u13FD\\u1401-\\u166C\\u166F-\\u167F\\u1681-\\u169A\\u16A0-\\u16EA\\u16F1-\\u16F8\\u1700-\\u170C\\u170E-\\u1711\\u1720-\\u1731\\u1740-\\u1751\\u1760-\\u176C\\u176E-\\u1770\\u1780-\\u17B3\\u17D7\\u17DC\\u1820-\\u1877\\u1880-\\u18A8\\u18AA\\u18B0-\\u18F5\\u1900-\\u191E\\u1950-\\u196D\\u1970-\\u1974\\u1980-\\u19AB\\u19B0-\\u19C9\\u1A00-\\u1A16\\u1A20-\\u1A54\\u1AA7\\u1B05-\\u1B33\\u1B45-\\u1B4B\\u1B83-\\u1BA0\\u1BAE\\u1BAF\\u1BBA-\\u1BE5\\u1C00-\\u1C23\\u1C4D-\\u1C4F\\u1C5A-\\u1C7D\\u1CE9-\\u1CEC\\u1CEE-\\u1CF1\\u1CF5\\u1CF6\\u1D00-\\u1DBF\\u1E00-\\u1F15\\u1F18-\\u1F1D\\u1F20-\\u1F45\\u1F48-\\u1F4D\\u1F50-\\u1F57\\u1F59\\u1F5B\\u1F5D\\u1F5F-\\u1F7D\\u1F80-\\u1FB4\\u1FB6-\\u1FBC\\u1FBE\\u1FC2-\\u1FC4\\u1FC6-\\u1FCC\\u1FD0-\\u1FD3\\u1FD6-\\u1FDB\\u1FE0-\\u1FEC\\u1FF2-\\u1FF4\\u1FF6-\\u1FFC\\u2071\\u207F\\u2090-\\u209C\\u2102\\u2107\\u210A-\\u2113\\u2115\\u2119-\\u211D\\u2124\\u2126\\u2128\\u212A-\\u212D\\u212F-\\u2139\\u213C-\\u213F\\u2145-\\u2149\\u214E\\u2183\\u2184\\u2C00-\\u2C2E\\u2C30-\\u2C5E\\u2C60-\\u2CE4\\u2CEB-\\u2CEE\\u2CF2\\u2CF3\\u2D00-\\u2D25\\u2D27\\u2D2D\\u2D30-\\u2D67\\u2D6F\\u2D80-\\u2D96\\u2DA0-\\u2DA6\\u2DA8-\\u2DAE\\u2DB0-\\u2DB6\\u2DB8-\\u2DBE\\u2DC0-\\u2DC6\\u2DC8-\\u2DCE\\u2DD0-\\u2DD6\\u2DD8-\\u2DDE\\u2E2F\\u3005\\u3006\\u3031-\\u3035\\u303B\\u303C\\u3041-\\u3096\\u309D-\\u309F\\u30A1-\\u30FA\\u30FC-\\u30FF\\u3105-\\u312D\\u3131-\\u318E\\u31A0-\\u31BA\\u31F0-\\u31FF\\u3400-\\u4DB5\\u4E00-\\u9FD5\\uA000-\\uA48C\\uA4D0-\\uA4FD\\uA500-\\uA60C\\uA610-\\uA61F\\uA62A\\uA62B\\uA640-\\uA66E\\uA67F-\\uA69D\\uA6A0-\\uA6E5\\uA717-\\uA71F\\uA722-\\uA788\\uA78B-\\uA7AD\\uA7B0-\\uA7B7\\uA7F7-\\uA801\\uA803-\\uA805\\uA807-\\uA80A\\uA80C-\\uA822\\uA840-\\uA873\\uA882-\\uA8B3\\uA8F2-\\uA8F7\\uA8FB\\uA8FD\\uA90A-\\uA925\\uA930-\\uA946\\uA960-\\uA97C\\uA984-\\uA9B2\\uA9CF\\uA9E0-\\uA9E4\\uA9E6-\\uA9EF\\uA9FA-\\uA9FE\\uAA00-\\uAA28\\uAA40-\\uAA42\\uAA44-\\uAA4B\\uAA60-\\uAA76\\uAA7A\\uAA7E-\\uAAAF\\uAAB1\\uAAB5\\uAAB6\\uAAB9-\\uAABD\\uAAC0\\uAAC2\\uAADB-\\uAADD\\uAAE0-\\uAAEA\\uAAF2-\\uAAF4\\uAB01-\\uAB06\\uAB09-\\uAB0E\\uAB11-\\uAB16\\uAB20-\\uAB26\\uAB28-\\uAB2E\\uAB30-\\uAB5A\\uAB5C-\\uAB65\\uAB70-\\uABE2\\uAC00-\\uD7A3\\uD7B0-\\uD7C6\\uD7CB-\\uD7FB\\uF900-\\uFA6D\\uFA70-\\uFAD9\\uFB00-\\uFB06\\uFB13-\\uFB17\\uFB1D\\uFB1F-\\uFB28\\uFB2A-\\uFB36\\uFB38-\\uFB3C\\uFB3E\\uFB40\\uFB41\\uFB43\\uFB44\\uFB46-\\uFBB1\\uFBD3-\\uFD3D\\uFD50-\\uFD8F\\uFD92-\\uFDC7\\uFDF0-\\uFDFB\\uFE70-\\uFE74\\uFE76-\\uFEFC\\uFF21-\\uFF3A\\uFF41-\\uFF5A\\uFF66-\\uFFBE\\uFFC2-\\uFFC7\\uFFCA-\\uFFCF\\uFFD2-\\uFFD7\\uFFDA-\\uFFDC]\n</code></pre>\n\n<p><code>\\p{Nd}</code> (Number decimal digits):</p>\n\n<pre><code>[0-9\\u0660-\\u0669\\u06F0-\\u06F9\\u07C0-\\u07C9\\u0966-\\u096F\\u09E6-\\u09EF\\u0A66-\\u0A6F\\u0AE6-\\u0AEF\\u0B66-\\u0B6F\\u0BE6-\\u0BEF\\u0C66-\\u0C6F\\u0CE6-\\u0CEF\\u0D66-\\u0D6F\\u0DE6-\\u0DEF\\u0E50-\\u0E59\\u0ED0-\\u0ED9\\u0F20-\\u0F29\\u1040-\\u1049\\u1090-\\u1099\\u17E0-\\u17E9\\u1810-\\u1819\\u1946-\\u194F\\u19D0-\\u19D9\\u1A80-\\u1A89\\u1A90-\\u1A99\\u1B50-\\u1B59\\u1BB0-\\u1BB9\\u1C40-\\u1C49\\u1C50-\\u1C59\\uA620-\\uA629\\uA8D0-\\uA8D9\\uA900-\\uA909\\uA9D0-\\uA9D9\\uA9F0-\\uA9F9\\uAA50-\\uAA59\\uABF0-\\uABF9\\uFF10-\\uFF19]\n</code></pre>\n\n<p><code>\\p{P}</code> (Punctuation):</p>\n\n<pre><code>[!-#%-*,-/\\:;?@\\[-\\]_\\{\\}\\u00A1\\u00A7\\u00AB\\u00B6\\u00B7\\u00BB\\u00BF\\u037E\\u0387\\u055A-\\u055F\\u0589\\u058A\\u05BE\\u05C0\\u05C3\\u05C6\\u05F3\\u05F4\\u0609\\u060A\\u060C\\u060D\\u061B\\u061E\\u061F\\u066A-\\u066D\\u06D4\\u0700-\\u070D\\u07F7-\\u07F9\\u0830-\\u083E\\u085E\\u0964\\u0965\\u0970\\u0AF0\\u0DF4\\u0E4F\\u0E5A\\u0E5B\\u0F04-\\u0F12\\u0F14\\u0F3A-\\u0F3D\\u0F85\\u0FD0-\\u0FD4\\u0FD9\\u0FDA\\u104A-\\u104F\\u10FB\\u1360-\\u1368\\u1400\\u166D\\u166E\\u169B\\u169C\\u16EB-\\u16ED\\u1735\\u1736\\u17D4-\\u17D6\\u17D8-\\u17DA\\u1800-\\u180A\\u1944\\u1945\\u1A1E\\u1A1F\\u1AA0-\\u1AA6\\u1AA8-\\u1AAD\\u1B5A-\\u1B60\\u1BFC-\\u1BFF\\u1C3B-\\u1C3F\\u1C7E\\u1C7F\\u1CC0-\\u1CC7\\u1CD3\\u2010-\\u2027\\u2030-\\u2043\\u2045-\\u2051\\u2053-\\u205E\\u207D\\u207E\\u208D\\u208E\\u2308-\\u230B\\u2329\\u232A\\u2768-\\u2775\\u27C5\\u27C6\\u27E6-\\u27EF\\u2983-\\u2998\\u29D8-\\u29DB\\u29FC\\u29FD\\u2CF9-\\u2CFC\\u2CFE\\u2CFF\\u2D70\\u2E00-\\u2E2E\\u2E30-\\u2E42\\u3001-\\u3003\\u3008-\\u3011\\u3014-\\u301F\\u3030\\u303D\\u30A0\\u30FB\\uA4FE\\uA4FF\\uA60D-\\uA60F\\uA673\\uA67E\\uA6F2-\\uA6F7\\uA874-\\uA877\\uA8CE\\uA8CF\\uA8F8-\\uA8FA\\uA8FC\\uA92E\\uA92F\\uA95F\\uA9C1-\\uA9CD\\uA9DE\\uA9DF\\uAA5C-\\uAA5F\\uAADE\\uAADF\\uAAF0\\uAAF1\\uABEB\\uFD3E\\uFD3F\\uFE10-\\uFE19\\uFE30-\\uFE52\\uFE54-\\uFE61\\uFE63\\uFE68\\uFE6A\\uFE6B\\uFF01-\\uFF03\\uFF05-\\uFF0A\\uFF0C-\\uFF0F\\uFF1A\\uFF1B\\uFF1F\\uFF20\\uFF3B-\\uFF3D\\uFF3F\\uFF5B\\uFF5D\\uFF5F-\\uFF65]\n</code></pre>\n\n<p>The page also recognizes a number of obscure character classes, such as <code>\\p{Hira}</code>, which is just the (Japanese) Hiragana characters:</p>\n\n<pre><code>[\\u3041-\\u3096\\u309D-\\u309F]\n</code></pre>\n\n<p>Lastly, it's possible to plug a char class with more than one Unicode property to get a shorter regex than you would get by just combining them (as long as certain settings are checked).</p>\n"
},
{
"answer_id": 46413244,
"author": "Hamid Hoseini",
"author_id": 4826188,
"author_profile": "https://Stackoverflow.com/users/4826188",
"pm_score": 5,
"selected": false,
"text": "<p><code>[^\\u0000-\\u007F]+</code> for any characters which is not included ASCII characters.</p>\n<p>For example:</p>\n<p><div class=\"snippet\" data-lang=\"js\" data-hide=\"false\" data-console=\"true\" data-babel=\"false\">\r\n<div class=\"snippet-code\">\r\n<pre class=\"snippet-code-js lang-js prettyprint-override\"><code>function isNonLatinCharacters(s) {\n return /[^\\u0000-\\u007F]/.test(s);\n}\n\nconsole.log(isNonLatinCharacters(\"身分\"));// Japanese\nconsole.log(isNonLatinCharacters(\"测试\"));// Chinese\nconsole.log(isNonLatinCharacters(\"حمید\"));// Persian\nconsole.log(isNonLatinCharacters(\"테스트\"));// Korean\nconsole.log(isNonLatinCharacters(\"परीक्षण\"));// Hindi\nconsole.log(isNonLatinCharacters(\"מִבְחָן\"));// Hebrew</code></pre>\r\n</div>\r\n</div>\r\n</p>\n<p>Here are some perfect references:</p>\n<p><a href=\"https://apps.timwhitlock.info/js/regex#\" rel=\"noreferrer\">Unicode range RegExp generator</a></p>\n<p><a href=\"https://www.regular-expressions.info/unicode.html\" rel=\"noreferrer\">Unicode Regular Expressions</a></p>\n<p><a href=\"http://www.unicode.org/charts/\" rel=\"noreferrer\">Unicode 10.0 Character Code Charts</a></p>\n<p><a href=\"http://kourge.net/projects/regexp-unicode-block\" rel=\"noreferrer\">Match Unicode Block Range</a></p>\n"
},
{
"answer_id": 52205643,
"author": "Kamil Kiełczewski",
"author_id": 860099,
"author_profile": "https://Stackoverflow.com/users/860099",
"pm_score": 5,
"selected": false,
"text": "<p><strong>September 2018 (updated February 2019)</strong> </p>\n\n<p>It seems that regexp <code>/\\p{L}/u</code> for match letters (as <a href=\"https://www.regular-expressions.info/unicode.html#category\" rel=\"noreferrer\">unicode categories</a>) </p>\n\n<ul>\n<li>works on <strong>Chrome</strong> 68.0.3440.106 and <strong>Safari</strong> 11.1.2 (13605.3.8) </li>\n<li>NOT working on Firefox 65.0 :(</li>\n</ul>\n\n<p>Here is a <a href=\"https://jsfiddle.net/Lamik/t71kahrp/2/\" rel=\"noreferrer\">working example</a></p>\n\n<p><div class=\"snippet\" data-lang=\"js\" data-hide=\"false\" data-console=\"true\" data-babel=\"false\">\r\n<div class=\"snippet-code\">\r\n<pre class=\"snippet-code-html lang-html prettyprint-override\"><code>In below field you should be able to to type letters but not numbers<br>\r\n<input type=\"text\" name=\"field\" onkeydown=\"return /\\p{L}/u.test(event.key)\" ></code></pre>\r\n</div>\r\n</div>\r\n</p>\n\n<p>I report this bug <a href=\"https://bugzilla.mozilla.org/show_bug.cgi?id=1500035\" rel=\"noreferrer\">here</a>.</p>\n\n<h2>Update</h2>\n\n<p>After over 2 years according to: <a href=\"https://bugzilla.mozilla.org/show_bug.cgi?id=1500035\" rel=\"noreferrer\">1500035</a> > <a href=\"https://bugzilla.mozilla.org/show_bug.cgi?id=1361876\" rel=\"noreferrer\">1361876</a> > <a href=\"https://bugzilla.mozilla.org/show_bug.cgi?id=1634135\" rel=\"noreferrer\">1634135</a> finally this bug is fixed and will be available in Firefox v.78+</p>\n"
},
{
"answer_id": 56795591,
"author": "Tapan Upadhyay",
"author_id": 1155396,
"author_profile": "https://Stackoverflow.com/users/1155396",
"pm_score": 2,
"selected": false,
"text": "<p>You can also use:</p>\n\n<pre><code>function myFunction() {\n var str = \"xq234\"; \n var allowChars = \"^[a-zA-ZÀ-ÿ]+$\";\n var res = str.match(allowChars);\n if(!str.match(allowChars)){\n res=\"true\";\n }\n else {\n res=\"false\";\n }\n document.getElementById(\"demo\").innerHTML = res;\n</code></pre>\n"
},
{
"answer_id": 58999494,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 2,
"selected": false,
"text": "<p>I'm answering this question<br>\n<a href=\"https://stackoverflow.com/questions/58995708/what-would-be-the-equivalent-for-plu-or-pll-in-regexp-for-js\">What would be the equivalent for \\p{Lu} or \\p{Ll} in regExp for js?</a><br>\nsince it was marked as an exact duplicate of the current old question.</p>\n\n<p>Querying the <a href=\"http://www.regexformat.com/scrn8/Ucustom.jpg\" rel=\"nofollow noreferrer\">UCD Database</a> of Unicode 12, \\p{Lu} generates 1,788 code points. </p>\n\n<p>Converting to UTF-16 yields the class construct equivalency.<br>\nIt's only a 4k character string and is easily doable in any regex engines. </p>\n\n<pre><code>(?:[\\u0041-\\u005A\\u00C0-\\u00D6\\u00D8-\\u00DE\\u0100\\u0102\\u0104\\u0106\\u0108\\u010A\\u010C\\u010E\\u0110\\u0112\\u0114\\u0116\\u0118\\u011A\\u011C\\u011E\\u0120\\u0122\\u0124\\u0126\\u0128\\u012A\\u012C\\u012E\\u0130\\u0132\\u0134\\u0136\\u0139\\u013B\\u013D\\u013F\\u0141\\u0143\\u0145\\u0147\\u014A\\u014C\\u014E\\u0150\\u0152\\u0154\\u0156\\u0158\\u015A\\u015C\\u015E\\u0160\\u0162\\u0164\\u0166\\u0168\\u016A\\u016C\\u016E\\u0170\\u0172\\u0174\\u0176\\u0178-\\u0179\\u017B\\u017D\\u0181-\\u0182\\u0184\\u0186-\\u0187\\u0189-\\u018B\\u018E-\\u0191\\u0193-\\u0194\\u0196-\\u0198\\u019C-\\u019D\\u019F-\\u01A0\\u01A2\\u01A4\\u01A6-\\u01A7\\u01A9\\u01AC\\u01AE-\\u01AF\\u01B1-\\u01B3\\u01B5\\u01B7-\\u01B8\\u01BC\\u01C4\\u01C7\\u01CA\\u01CD\\u01CF\\u01D1\\u01D3\\u01D5\\u01D7\\u01D9\\u01DB\\u01DE\\u01E0\\u01E2\\u01E4\\u01E6\\u01E8\\u01EA\\u01EC\\u01EE\\u01F1\\u01F4\\u01F6-\\u01F8\\u01FA\\u01FC\\u01FE\\u0200\\u0202\\u0204\\u0206\\u0208\\u020A\\u020C\\u020E\\u0210\\u0212\\u0214\\u0216\\u0218\\u021A\\u021C\\u021E\\u0220\\u0222\\u0224\\u0226\\u0228\\u022A\\u022C\\u022E\\u0230\\u0232\\u023A-\\u023B\\u023D-\\u023E\\u0241\\u0243-\\u0246\\u0248\\u024A\\u024C\\u024E\\u0370\\u0372\\u0376\\u037F\\u0386\\u0388-\\u038A\\u038C\\u038E-\\u038F\\u0391-\\u03A1\\u03A3-\\u03AB\\u03CF\\u03D2-\\u03D4\\u03D8\\u03DA\\u03DC\\u03DE\\u03E0\\u03E2\\u03E4\\u03E6\\u03E8\\u03EA\\u03EC\\u03EE\\u03F4\\u03F7\\u03F9-\\u03FA\\u03FD-\\u042F\\u0460\\u0462\\u0464\\u0466\\u0468\\u046A\\u046C\\u046E\\u0470\\u0472\\u0474\\u0476\\u0478\\u047A\\u047C\\u047E\\u0480\\u048A\\u048C\\u048E\\u0490\\u0492\\u0494\\u0496\\u0498\\u049A\\u049C\\u049E\\u04A0\\u04A2\\u04A4\\u04A6\\u04A8\\u04AA\\u04AC\\u04AE\\u04B0\\u04B2\\u04B4\\u04B6\\u04B8\\u04BA\\u04BC\\u04BE\\u04C0-\\u04C1\\u04C3\\u04C5\\u04C7\\u04C9\\u04CB\\u04CD\\u04D0\\u04D2\\u04D4\\u04D6\\u04D8\\u04DA\\u04DC\\u04DE\\u04E0\\u04E2\\u04E4\\u04E6\\u04E8\\u04EA\\u04EC\\u04EE\\u04F0\\u04F2\\u04F4\\u04F6\\u04F8\\u04FA\\u04FC\\u04FE\\u0500\\u0502\\u0504\\u0506\\u0508\\u050A\\u050C\\u050E\\u0510\\u0512\\u0514\\u0516\\u0518\\u051A\\u051C\\u051E\\u0520\\u0522\\u0524\\u0526\\u0528\\u052A\\u052C\\u052E\\u0531-\\u0556\\u10A0-\\u10C5\\u10C7\\u10CD\\u13A0-\\u13F5\\u1C90-\\u1CBA\\u1CBD-\\u1CBF\\u1E00\\u1E02\\u1E04\\u1E06\\u1E08\\u1E0A\\u1E0C\\u1E0E\\u1E10\\u1E12\\u1E14\\u1E16\\u1E18\\u1E1A\\u1E1C\\u1E1E\\u1E20\\u1E22\\u1E24\\u1E26\\u1E28\\u1E2A\\u1E2C\\u1E2E\\u1E30\\u1E32\\u1E34\\u1E36\\u1E38\\u1E3A\\u1E3C\\u1E3E\\u1E40\\u1E42\\u1E44\\u1E46\\u1E48\\u1E4A\\u1E4C\\u1E4E\\u1E50\\u1E52\\u1E54\\u1E56\\u1E58\\u1E5A\\u1E5C\\u1E5E\\u1E60\\u1E62\\u1E64\\u1E66\\u1E68\\u1E6A\\u1E6C\\u1E6E\\u1E70\\u1E72\\u1E74\\u1E76\\u1E78\\u1E7A\\u1E7C\\u1E7E\\u1E80\\u1E82\\u1E84\\u1E86\\u1E88\\u1E8A\\u1E8C\\u1E8E\\u1E90\\u1E92\\u1E94\\u1E9E\\u1EA0\\u1EA2\\u1EA4\\u1EA6\\u1EA8\\u1EAA\\u1EAC\\u1EAE\\u1EB0\\u1EB2\\u1EB4\\u1EB6\\u1EB8\\u1EBA\\u1EBC\\u1EBE\\u1EC0\\u1EC2\\u1EC4\\u1EC6\\u1EC8\\u1ECA\\u1ECC\\u1ECE\\u1ED0\\u1ED2\\u1ED4\\u1ED6\\u1ED8\\u1EDA\\u1EDC\\u1EDE\\u1EE0\\u1EE2\\u1EE4\\u1EE6\\u1EE8\\u1EEA\\u1EEC\\u1EEE\\u1EF0\\u1EF2\\u1EF4\\u1EF6\\u1EF8\\u1EFA\\u1EFC\\u1EFE\\u1F08-\\u1F0F\\u1F18-\\u1F1D\\u1F28-\\u1F2F\\u1F38-\\u1F3F\\u1F48-\\u1F4D\\u1F59\\u1F5B\\u1F5D\\u1F5F\\u1F68-\\u1F6F\\u1FB8-\\u1FBB\\u1FC8-\\u1FCB\\u1FD8-\\u1FDB\\u1FE8-\\u1FEC\\u1FF8-\\u1FFB\\u2102\\u2107\\u210B-\\u210D\\u2110-\\u2112\\u2115\\u2119-\\u211D\\u2124\\u2126\\u2128\\u212A-\\u212D\\u2130-\\u2133\\u213E-\\u213F\\u2145\\u2183\\u2C00-\\u2C2E\\u2C60\\u2C62-\\u2C64\\u2C67\\u2C69\\u2C6B\\u2C6D-\\u2C70\\u2C72\\u2C75\\u2C7E-\\u2C80\\u2C82\\u2C84\\u2C86\\u2C88\\u2C8A\\u2C8C\\u2C8E\\u2C90\\u2C92\\u2C94\\u2C96\\u2C98\\u2C9A\\u2C9C\\u2C9E\\u2CA0\\u2CA2\\u2CA4\\u2CA6\\u2CA8\\u2CAA\\u2CAC\\u2CAE\\u2CB0\\u2CB2\\u2CB4\\u2CB6\\u2CB8\\u2CBA\\u2CBC\\u2CBE\\u2CC0\\u2CC2\\u2CC4\\u2CC6\\u2CC8\\u2CCA\\u2CCC\\u2CCE\\u2CD0\\u2CD2\\u2CD4\\u2CD6\\u2CD8\\u2CDA\\u2CDC\\u2CDE\\u2CE0\\u2CE2\\u2CEB\\u2CED\\u2CF2\\uA640\\uA642\\uA644\\uA646\\uA648\\uA64A\\uA64C\\uA64E\\uA650\\uA652\\uA654\\uA656\\uA658\\uA65A\\uA65C\\uA65E\\uA660\\uA662\\uA664\\uA666\\uA668\\uA66A\\uA66C\\uA680\\uA682\\uA684\\uA686\\uA688\\uA68A\\uA68C\\uA68E\\uA690\\uA692\\uA694\\uA696\\uA698\\uA69A\\uA722\\uA724\\uA726\\uA728\\uA72A\\uA72C\\uA72E\\uA732\\uA734\\uA736\\uA738\\uA73A\\uA73C\\uA73E\\uA740\\uA742\\uA744\\uA746\\uA748\\uA74A\\uA74C\\uA74E\\uA750\\uA752\\uA754\\uA756\\uA758\\uA75A\\uA75C\\uA75E\\uA760\\uA762\\uA764\\uA766\\uA768\\uA76A\\uA76C\\uA76E\\uA779\\uA77B\\uA77D-\\uA77E\\uA780\\uA782\\uA784\\uA786\\uA78B\\uA78D\\uA790\\uA792\\uA796\\uA798\\uA79A\\uA79C\\uA79E\\uA7A0\\uA7A2\\uA7A4\\uA7A6\\uA7A8\\uA7AA-\\uA7AE\\uA7B0-\\uA7B4\\uA7B6\\uA7B8\\uA7BA\\uA7BC\\uA7BE\\uA7C2\\uA7C4-\\uA7C6\\uFF21-\\uFF3A]|(?:\\uD801[\\uDC00-\\uDC27\\uDCB0-\\uDCD3]|\\uD803[\\uDC80-\\uDCB2]|\\uD806[\\uDCA0-\\uDCBF]|\\uD81B[\\uDE40-\\uDE5F]|\\uD835[\\uDC00-\\uDC19\\uDC34-\\uDC4D\\uDC68-\\uDC81\\uDC9C\\uDC9E-\\uDC9F\\uDCA2\\uDCA5-\\uDCA6\\uDCA9-\\uDCAC\\uDCAE-\\uDCB5\\uDCD0-\\uDCE9\\uDD04-\\uDD05\\uDD07-\\uDD0A\\uDD0D-\\uDD14\\uDD16-\\uDD1C\\uDD38-\\uDD39\\uDD3B-\\uDD3E\\uDD40-\\uDD44\\uDD46\\uDD4A-\\uDD50\\uDD6C-\\uDD85\\uDDA0-\\uDDB9\\uDDD4-\\uDDED\\uDE08-\\uDE21\\uDE3C-\\uDE55\\uDE70-\\uDE89\\uDEA8-\\uDEC0\\uDEE2-\\uDEFA\\uDF1C-\\uDF34\\uDF56-\\uDF6E\\uDF90-\\uDFA8\\uDFCA]|\\uD83A[\\uDD00-\\uDD21]))\n</code></pre>\n\n<p>Querying the UCD database of Unicode 12, \\p{Ll} generates 2,151 code points. </p>\n\n<p>Converting to UTF-16 yields the class construct equivalency. </p>\n\n<pre><code>(?:[\\u0061-\\u007A\\u00B5\\u00DF-\\u00F6\\u00F8-\\u00FF\\u0101\\u0103\\u0105\\u0107\\u0109\\u010B\\u010D\\u010F\\u0111\\u0113\\u0115\\u0117\\u0119\\u011B\\u011D\\u011F\\u0121\\u0123\\u0125\\u0127\\u0129\\u012B\\u012D\\u012F\\u0131\\u0133\\u0135\\u0137-\\u0138\\u013A\\u013C\\u013E\\u0140\\u0142\\u0144\\u0146\\u0148-\\u0149\\u014B\\u014D\\u014F\\u0151\\u0153\\u0155\\u0157\\u0159\\u015B\\u015D\\u015F\\u0161\\u0163\\u0165\\u0167\\u0169\\u016B\\u016D\\u016F\\u0171\\u0173\\u0175\\u0177\\u017A\\u017C\\u017E-\\u0180\\u0183\\u0185\\u0188\\u018C-\\u018D\\u0192\\u0195\\u0199-\\u019B\\u019E\\u01A1\\u01A3\\u01A5\\u01A8\\u01AA-\\u01AB\\u01AD\\u01B0\\u01B4\\u01B6\\u01B9-\\u01BA\\u01BD-\\u01BF\\u01C6\\u01C9\\u01CC\\u01CE\\u01D0\\u01D2\\u01D4\\u01D6\\u01D8\\u01DA\\u01DC-\\u01DD\\u01DF\\u01E1\\u01E3\\u01E5\\u01E7\\u01E9\\u01EB\\u01ED\\u01EF-\\u01F0\\u01F3\\u01F5\\u01F9\\u01FB\\u01FD\\u01FF\\u0201\\u0203\\u0205\\u0207\\u0209\\u020B\\u020D\\u020F\\u0211\\u0213\\u0215\\u0217\\u0219\\u021B\\u021D\\u021F\\u0221\\u0223\\u0225\\u0227\\u0229\\u022B\\u022D\\u022F\\u0231\\u0233-\\u0239\\u023C\\u023F-\\u0240\\u0242\\u0247\\u0249\\u024B\\u024D\\u024F-\\u0293\\u0295-\\u02AF\\u0371\\u0373\\u0377\\u037B-\\u037D\\u0390\\u03AC-\\u03CE\\u03D0-\\u03D1\\u03D5-\\u03D7\\u03D9\\u03DB\\u03DD\\u03DF\\u03E1\\u03E3\\u03E5\\u03E7\\u03E9\\u03EB\\u03ED\\u03EF-\\u03F3\\u03F5\\u03F8\\u03FB-\\u03FC\\u0430-\\u045F\\u0461\\u0463\\u0465\\u0467\\u0469\\u046B\\u046D\\u046F\\u0471\\u0473\\u0475\\u0477\\u0479\\u047B\\u047D\\u047F\\u0481\\u048B\\u048D\\u048F\\u0491\\u0493\\u0495\\u0497\\u0499\\u049B\\u049D\\u049F\\u04A1\\u04A3\\u04A5\\u04A7\\u04A9\\u04AB\\u04AD\\u04AF\\u04B1\\u04B3\\u04B5\\u04B7\\u04B9\\u04BB\\u04BD\\u04BF\\u04C2\\u04C4\\u04C6\\u04C8\\u04CA\\u04CC\\u04CE-\\u04CF\\u04D1\\u04D3\\u04D5\\u04D7\\u04D9\\u04DB\\u04DD\\u04DF\\u04E1\\u04E3\\u04E5\\u04E7\\u04E9\\u04EB\\u04ED\\u04EF\\u04F1\\u04F3\\u04F5\\u04F7\\u04F9\\u04FB\\u04FD\\u04FF\\u0501\\u0503\\u0505\\u0507\\u0509\\u050B\\u050D\\u050F\\u0511\\u0513\\u0515\\u0517\\u0519\\u051B\\u051D\\u051F\\u0521\\u0523\\u0525\\u0527\\u0529\\u052B\\u052D\\u052F\\u0560-\\u0588\\u10D0-\\u10FA\\u10FD-\\u10FF\\u13F8-\\u13FD\\u1C80-\\u1C88\\u1D00-\\u1D2B\\u1D6B-\\u1D77\\u1D79-\\u1D9A\\u1E01\\u1E03\\u1E05\\u1E07\\u1E09\\u1E0B\\u1E0D\\u1E0F\\u1E11\\u1E13\\u1E15\\u1E17\\u1E19\\u1E1B\\u1E1D\\u1E1F\\u1E21\\u1E23\\u1E25\\u1E27\\u1E29\\u1E2B\\u1E2D\\u1E2F\\u1E31\\u1E33\\u1E35\\u1E37\\u1E39\\u1E3B\\u1E3D\\u1E3F\\u1E41\\u1E43\\u1E45\\u1E47\\u1E49\\u1E4B\\u1E4D\\u1E4F\\u1E51\\u1E53\\u1E55\\u1E57\\u1E59\\u1E5B\\u1E5D\\u1E5F\\u1E61\\u1E63\\u1E65\\u1E67\\u1E69\\u1E6B\\u1E6D\\u1E6F\\u1E71\\u1E73\\u1E75\\u1E77\\u1E79\\u1E7B\\u1E7D\\u1E7F\\u1E81\\u1E83\\u1E85\\u1E87\\u1E89\\u1E8B\\u1E8D\\u1E8F\\u1E91\\u1E93\\u1E95-\\u1E9D\\u1E9F\\u1EA1\\u1EA3\\u1EA5\\u1EA7\\u1EA9\\u1EAB\\u1EAD\\u1EAF\\u1EB1\\u1EB3\\u1EB5\\u1EB7\\u1EB9\\u1EBB\\u1EBD\\u1EBF\\u1EC1\\u1EC3\\u1EC5\\u1EC7\\u1EC9\\u1ECB\\u1ECD\\u1ECF\\u1ED1\\u1ED3\\u1ED5\\u1ED7\\u1ED9\\u1EDB\\u1EDD\\u1EDF\\u1EE1\\u1EE3\\u1EE5\\u1EE7\\u1EE9\\u1EEB\\u1EED\\u1EEF\\u1EF1\\u1EF3\\u1EF5\\u1EF7\\u1EF9\\u1EFB\\u1EFD\\u1EFF-\\u1F07\\u1F10-\\u1F15\\u1F20-\\u1F27\\u1F30-\\u1F37\\u1F40-\\u1F45\\u1F50-\\u1F57\\u1F60-\\u1F67\\u1F70-\\u1F7D\\u1F80-\\u1F87\\u1F90-\\u1F97\\u1FA0-\\u1FA7\\u1FB0-\\u1FB4\\u1FB6-\\u1FB7\\u1FBE\\u1FC2-\\u1FC4\\u1FC6-\\u1FC7\\u1FD0-\\u1FD3\\u1FD6-\\u1FD7\\u1FE0-\\u1FE7\\u1FF2-\\u1FF4\\u1FF6-\\u1FF7\\u210A\\u210E-\\u210F\\u2113\\u212F\\u2134\\u2139\\u213C-\\u213D\\u2146-\\u2149\\u214E\\u2184\\u2C30-\\u2C5E\\u2C61\\u2C65-\\u2C66\\u2C68\\u2C6A\\u2C6C\\u2C71\\u2C73-\\u2C74\\u2C76-\\u2C7B\\u2C81\\u2C83\\u2C85\\u2C87\\u2C89\\u2C8B\\u2C8D\\u2C8F\\u2C91\\u2C93\\u2C95\\u2C97\\u2C99\\u2C9B\\u2C9D\\u2C9F\\u2CA1\\u2CA3\\u2CA5\\u2CA7\\u2CA9\\u2CAB\\u2CAD\\u2CAF\\u2CB1\\u2CB3\\u2CB5\\u2CB7\\u2CB9\\u2CBB\\u2CBD\\u2CBF\\u2CC1\\u2CC3\\u2CC5\\u2CC7\\u2CC9\\u2CCB\\u2CCD\\u2CCF\\u2CD1\\u2CD3\\u2CD5\\u2CD7\\u2CD9\\u2CDB\\u2CDD\\u2CDF\\u2CE1\\u2CE3-\\u2CE4\\u2CEC\\u2CEE\\u2CF3\\u2D00-\\u2D25\\u2D27\\u2D2D\\uA641\\uA643\\uA645\\uA647\\uA649\\uA64B\\uA64D\\uA64F\\uA651\\uA653\\uA655\\uA657\\uA659\\uA65B\\uA65D\\uA65F\\uA661\\uA663\\uA665\\uA667\\uA669\\uA66B\\uA66D\\uA681\\uA683\\uA685\\uA687\\uA689\\uA68B\\uA68D\\uA68F\\uA691\\uA693\\uA695\\uA697\\uA699\\uA69B\\uA723\\uA725\\uA727\\uA729\\uA72B\\uA72D\\uA72F-\\uA731\\uA733\\uA735\\uA737\\uA739\\uA73B\\uA73D\\uA73F\\uA741\\uA743\\uA745\\uA747\\uA749\\uA74B\\uA74D\\uA74F\\uA751\\uA753\\uA755\\uA757\\uA759\\uA75B\\uA75D\\uA75F\\uA761\\uA763\\uA765\\uA767\\uA769\\uA76B\\uA76D\\uA76F\\uA771-\\uA778\\uA77A\\uA77C\\uA77F\\uA781\\uA783\\uA785\\uA787\\uA78C\\uA78E\\uA791\\uA793-\\uA795\\uA797\\uA799\\uA79B\\uA79D\\uA79F\\uA7A1\\uA7A3\\uA7A5\\uA7A7\\uA7A9\\uA7AF\\uA7B5\\uA7B7\\uA7B9\\uA7BB\\uA7BD\\uA7BF\\uA7C3\\uA7FA\\uAB30-\\uAB5A\\uAB60-\\uAB67\\uAB70-\\uABBF\\uFB00-\\uFB06\\uFB13-\\uFB17\\uFF41-\\uFF5A]|(?:\\uD801[\\uDC28-\\uDC4F\\uDCD8-\\uDCFB]|\\uD803[\\uDCC0-\\uDCF2]|\\uD806[\\uDCC0-\\uDCDF]|\\uD81B[\\uDE60-\\uDE7F]|\\uD835[\\uDC1A-\\uDC33\\uDC4E-\\uDC54\\uDC56-\\uDC67\\uDC82-\\uDC9B\\uDCB6-\\uDCB9\\uDCBB\\uDCBD-\\uDCC3\\uDCC5-\\uDCCF\\uDCEA-\\uDD03\\uDD1E-\\uDD37\\uDD52-\\uDD6B\\uDD86-\\uDD9F\\uDDBA-\\uDDD3\\uDDEE-\\uDE07\\uDE22-\\uDE3B\\uDE56-\\uDE6F\\uDE8A-\\uDEA5\\uDEC2-\\uDEDA\\uDEDC-\\uDEE1\\uDEFC-\\uDF14\\uDF16-\\uDF1B\\uDF36-\\uDF4E\\uDF50-\\uDF55\\uDF70-\\uDF88\\uDF8A-\\uDF8F\\uDFAA-\\uDFC2\\uDFC4-\\uDFC9\\uDFCB]|\\uD83A[\\uDD22-\\uDD43]))\n</code></pre>\n\n<p>Note that a regex implementation of \\p{Lu} or \\p{Pl} actually calls a<br>\nnon standard function to test the value. </p>\n\n<p>The character classes shown here are done differently and are linear, standard<br>\nand pretty slow, when jammed into mostly a single class. </p>\n\n<hr>\n\n<p><em><strong>Some insight on how a Regex engine (in general) implements Unicode Property Classes:</strong></em> </p>\n\n<p>Examine these performance characteristics between the property<br>\nand the class block (like above) </p>\n\n<pre><code>Regex1: LONG CLASS \n< none >\nCompleted iterations: 50 / 50 ( x 1 )\nMatches found per iteration: 1788\nElapsed Time: 0.73 s, 727.58 ms, 727584 µs\nMatches per sec: 122,872\n\n\nRegex2: \\p{Lu}\nOptions: < ICU - none >\nCompleted iterations: 50 / 50 ( x 1 )\nMatches found per iteration: 1788\nElapsed Time: 0.07 s, 65.32 ms, 65323 µs\nMatches per sec: 1,368,583\n</code></pre>\n\n<p>Wow what a difference !!</p>\n\n<p>Lets see how Properties might be implemented</p>\n\n<p>Array of Pointers [ 10FFFF ] where each index is is a Code Point </p>\n\n<ul>\n<li><p>Each pointer in the Array is to a structure of classification. </p>\n\n<ul>\n<li><p>A Classification structure contains fixed field elemets.<br>\nSome are NULL and do not pertain.<br>\nSome contain category classifications. </p>\n\n<p>Example : General Category<br>\nThis is a bitmapped element that uses 17 out of 64 bits.<br>\nWhatever this Code Point supports has bit(s) set as a mask. </p>\n\n<p>-Close_Punctuation<br>\n -Connector_Punctuation<br>\n -Control<br>\n -Currency_Symbol<br>\n -Dash_Punctuation<br>\n -Decimal_Number<br>\n -Enclosing_Mark<br>\n -Final_Punctuation<br>\n -Format<br>\n -Initial_Punctuation<br>\n -Letter_Number<br>\n -Line_Separator<br>\n -Lowercase_Letter<br>\n -Math_Symbol<br>\n -Modifier_Letter<br>\n -Modifier_Symbol<br>\n -Nonspacing_Mark<br>\n -Open_Punctuation<br>\n -Other_Letter<br>\n -Other_Number<br>\n -Other_Punctuation<br>\n -Other_Symbol<br>\n -Paragraph_Separator<br>\n -Private_Use<br>\n -Space_Separator<br>\n -Spacing_Mark<br>\n -Surrogate<br>\n -Titlecase_Letter<br>\n -Unassigned<br>\n -Uppercase_Letter </p></li>\n</ul></li>\n</ul>\n\n<p>When a regex is parsed with something like this \\p{Lu} it<br>\nis translated directly into </p>\n\n<ul>\n<li>Classification Structure element offset : General Category </li>\n<li>A check of that element for bit item : Uppercase_Letter </li>\n</ul>\n\n<p>Another example, when a regex is parsed with punctuation property \\p{P} it<br>\nis translated into </p>\n\n<ul>\n<li>Classification Structure element offset : General Category </li>\n<li><p>A check of that element for any of these items bits, which are joined into a mask : </p>\n\n<p>-Close_Punctuation<br>\n -Connector_Punctuation<br>\n -Dash_Punctuation<br>\n -Final_Punctuation<br>\n -Initial_Punctuation<br>\n -Open_Punctuation<br>\n -Other_Punctuation </p></li>\n</ul>\n\n<p>The offset and bit or bit(mask) are stored as a regex step for that property. </p>\n\n<p>The lookup table is created once for all Unicode Code Points using this array. </p>\n\n<p>When a character is checked, it is as simple as using the CP as an index into\nthis array and checking the Classification Structure's specific element for that bit(mask). </p>\n\n<p>This structure is expandable and indirect to provide much more complex look ups. This is just a simple example.</p>\n\n<hr>\n\n<p>Compare that direct lookup with a character class search : </p>\n\n<p>All classes are a linear list of items searched from left to right.<br>\nIn this comparison, given our target string contains only the complete\nUpper Case Unicode Letters only, the law of averages would predict that \nhalf of the items in the class would have to be ranged checked\nto find a match. </p>\n\n<p>This is a huge disadvantage in performance. </p>\n\n<p>However, if the lookup tables are not there or are not up to date\nwith the latest Unicode release (12 as of this date)<br>\nthen this would be the only way. </p>\n\n<p>In fact, it is mostly the only way to get the complete Emoji<br>\ncharacters as there is no specific property (or reasoning) to their assignment.</p>\n"
}
] |
2008/11/11
|
[
"https://Stackoverflow.com/questions/280712",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] |
There should be something akin to `\w` that can match any code-point in Letters or Marks category (not just the ASCII ones), and hopefully have filters like [[P\*]] for punctuation, etc.
|
Situation for ES 6
------------------
The ECMAScript language specification, edition 6 (also commonly known as ES2015), includes Unicode-aware regular expressions. Support must be enabled with the `u` modifier on the regex. See [*Unicode-aware regular expressions in ES6*](https://mathiasbynens.be/notes/es6-unicode-regex) for a break-down of the feature and some caveats.
ES6 is widely adopted in both browsers and stand-alone Javascript runtimes such as Node.js, so using this feature won't require extra effort in most cases. Full compatibility list: <https://kangax.github.io/compat-table/es6/>
Situation for ES 5 and below (legacy browsers)
----------------------------------------------
There is [a transpiler named *regexpu*](http://mths.be/regexpu) that translates ES6 Unicode regular expressions into equivalent ES5. It can be used as part of your build process. [Try it out online.](http://mothereff.in/regexpu).
Even though JavaScript operates on Unicode strings, it does not implement Unicode-aware character classes and has no concept of POSIX character classes or Unicode blocks/sub-ranges.
* [Issues with Unicode in JavaScript regular expressions](https://mathiasbynens.be/notes/javascript-unicode#regex)
* Check your expectations here: [Javascript RegExp Unicode Character Class tester](http://hamstersoup.com/javascript/regexp_character_class_tester.html) (*Edit:* the original page is down, [the Internet Archive still has a copy](http://web.archive.org/web/20101104085449/http://hamstersoup.com/javascript/regexp_character_class_tester.html).)
* Flagrant Badassery has an article on [JavaScript, Regex, and Unicode](http://blog.stevenlevithan.com/archives/javascript-regex-and-unicode) that sheds some light on the matter.
* Also read [Regex and Unicode](https://stackoverflow.com/questions/14389/) here on SO. Probably you have to build your own "punctuation character class".
* Check out the [Regular Expression: Match Unicode Block Range](http://kourge.net/projects/regexp-unicode-block) builder ([archived copy](https://web.archive.org/web/20191219033259/http://kourge.net/projects/regexp-unicode-block)), which lets you build a JavaScript regular expression that matches characters that fall in any number of specified Unicode blocks.
I just did it for the "General Punctuation" and "Supplemental Punctuation" sub-ranges, and the result is as simple and straight-forward as I would have expected it:
```
[\u2000-\u206F\u2E00-\u2E7F]
```
* There also is [XRegExp](http://xregexp.com/), a project that brings [Unicode support to JavaScript](http://xregexp.com/plugins/#unicode) by offering an alternative regex engine with extended capabilities.
* And of course, required reading: [mathiasbynens.be - JavaScript has a Unicode problem](https://mathiasbynens.be/notes/javascript-unicode):
|
280,713 |
<p>Does the "for…in" loop in Javascript loop through the hashtables/elements in the order they are declared? Is there a browser which doesn't do it in order?<br>
The object I wish to use will be declared <em>once</em> and will never be modified.</p>
<p>Suppose I have:</p>
<pre><code>var myObject = { A: "Hello", B: "World" };
</code></pre>
<p>And I further use them in:</p>
<pre><code>for (var item in myObject) alert(item + " : " + myObject[item]);
</code></pre>
<p>Can I expect 'A : "Hello"' to always come before 'B : "World"' in most decent browsers?</p>
|
[
{
"answer_id": 280733,
"author": "Adam Wright",
"author_id": 1200,
"author_profile": "https://Stackoverflow.com/users/1200",
"pm_score": 3,
"selected": false,
"text": "<p>The elements of an object that for/in enumerates are the properties that don't have the DontEnum flag set. The ECMAScript, aka Javascript, standard explicitly says that \"An Object is an unordered collection of properties\" (see <a href=\"http://www.mozilla.org/js/language/E262-3.pdf\" rel=\"noreferrer\">http://www.mozilla.org/js/language/E262-3.pdf</a> section 8.6).</p>\n\n<p>It's not going to be standards conformant (i.e. safe) to assume all Javascript implementations will enumerate in declaration order.</p>\n"
},
{
"answer_id": 280734,
"author": "Tomalak",
"author_id": 18771,
"author_profile": "https://Stackoverflow.com/users/18771",
"pm_score": 5,
"selected": false,
"text": "<p>From the <a href=\"http://www.ecma-international.org/publications/files/ECMA-ST/Ecma-262.pdf\" rel=\"noreferrer\">ECMAScript Language Specification</a>, section 12.6.4 (on the <code>for .. in</code> loop):</p>\n\n<blockquote>\n <p>The mechanics of enumerating the properties is implementation dependent. The order of enumeration is defined by the object.</p>\n</blockquote>\n\n<p>And section 4.3.3 (definition of \"Object\"):</p>\n\n<blockquote>\n <p>It is an unordered collection of properties each of which contains a primitive value, object, or function. A function stored in a property of an object is called a method.</p>\n</blockquote>\n\n<p>I guess that means you cant rely on the properties being enumerated in a consistent order across JavaScript implementations. (It would be bad style anyway to rely on implementation-specific details of a language.)</p>\n\n<p>If you want your order defined, you will need to implement something that defines it, like an array of keys that you sort before accessing the object with it.</p>\n"
},
{
"answer_id": 280861,
"author": "Borgar",
"author_id": 27388,
"author_profile": "https://Stackoverflow.com/users/27388",
"pm_score": 9,
"selected": true,
"text": "<p><a href=\"http://ejohn.org/blog/javascript-in-chrome/\" rel=\"noreferrer\">Quoting John Resig</a>:</p>\n<blockquote>\n<p>Currently all major browsers loop over the properties of an object in the order in\nwhich they were defined. Chrome does this as well, except for a couple cases. [...]\nThis behavior is explicitly left undefined by the ECMAScript specification.\nIn ECMA-262, section 12.6.4:</p>\n<blockquote>\n<p>The mechanics of enumerating the properties ... is implementation dependent.</p>\n</blockquote>\n<p>However, specification is quite different from implementation. All modern implementations\nof ECMAScript iterate through object properties in the order in which they were defined.\nBecause of this the Chrome team has deemed this to be a bug and will be fixing it.</p>\n</blockquote>\n<p>All browsers respect definition order <a href=\"https://code.google.com/p/v8/issues/detail?id=164\" rel=\"noreferrer\">with the exception of Chrome</a> and Opera which do for every non-numerical property name. In these two browsers the properties are pulled in-order ahead of the first non-numerical property (this is has to do with how they implement arrays). The order is the same for <code>Object.keys</code> as well.</p>\n<p>This example should make it clear what happens:</p>\n<pre><code>var obj = {\n "first":"first",\n "2":"2",\n "34":"34",\n "1":"1",\n "second":"second"\n};\nfor (var i in obj) { console.log(i); };\n// Order listed:\n// "1"\n// "2"\n// "34"\n// "first"\n// "second"\n</code></pre>\n<p>The technicalities of this are less important than the fact that this may change at any time. Do not rely on things staying this way.</p>\n<p>In short: <strong>Use an array if order is important to you.</strong></p>\n"
},
{
"answer_id": 350644,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 2,
"selected": false,
"text": "<p>in IE6, the order is not guaranteed. </p>\n"
},
{
"answer_id": 3567208,
"author": "Kouber Saparev",
"author_id": 83108,
"author_profile": "https://Stackoverflow.com/users/83108",
"pm_score": 2,
"selected": false,
"text": "<p>The order cannot be trusted. Both Opera and Chrome return the list of properties unordered.</p>\n\n<pre><code><script type=\"text/javascript\">\nvar username = {\"14719\":\"A\",\"648\":\"B\",\"15185\":\"C\"};\n\nfor (var i in username) {\n window.alert(i + ' => ' + username[i]);\n}\n</script>\n</code></pre>\n\n<p>The code above shows B, A, C in Opera and C, A, B in Chrome.</p>\n"
},
{
"answer_id": 4591510,
"author": "Brett Zamir",
"author_id": 271577,
"author_profile": "https://Stackoverflow.com/users/271577",
"pm_score": 3,
"selected": false,
"text": "<p>Iteration order is also confused with respect to deleting of properties, but in this case with IE only.</p>\n\n<pre><code>var obj = {};\nobj.a = 'a';\nobj.b = 'b';\nobj.c = 'c';\n\n// IE allows the value to be deleted...\ndelete obj.b;\n\n// ...but remembers the old position if it is added back later\nobj.b = 'bb';\nfor (var p in obj) {\n alert(obj[p]); // in IE, will be a, bb, then c;\n // not a, c, then bb as for FF/Chrome/Opera/Safari\n}\n</code></pre>\n\n<p>The desire for changing the spec to fix the iteration order seems to be quite a popular desire among developers if the discussion at <a href=\"http://code.google.com/p/v8/issues/detail?id=164\" rel=\"noreferrer\">http://code.google.com/p/v8/issues/detail?id=164</a> is any indication.</p>\n"
},
{
"answer_id": 8704349,
"author": "dvdrtrgn",
"author_id": 94778,
"author_profile": "https://Stackoverflow.com/users/94778",
"pm_score": 6,
"selected": false,
"text": "<p><em>Bumping this a year later...</em></p>\n\n<p>It is <strong>2012</strong> and the major browsers <strong>still</strong> differ:</p>\n\n<pre><code>function lineate(obj){\n var arr = [], i;\n for (i in obj) arr.push([i,obj[i]].join(':'));\n console.log(arr);\n}\nvar obj = { a:1, b:2, c:3, \"123\":'xyz' };\n/* log1 */ lineate(obj);\nobj.a = 4;\n/* log2 */ lineate(obj);\ndelete obj.a;\nobj.a = 4;\n/* log3 */ lineate(obj);\n</code></pre>\n\n<p><a href=\"https://gist.github.com/1551668\" rel=\"nofollow noreferrer\">gist</a> or <a href=\"https://rawgit.com/dvdrtrgn/460db3c214ade506fe7123500b1b4c8c/raw/36aaeb687bc34280e8f1cb5410359271c629e9b6/domlineate.html\" rel=\"nofollow noreferrer\">test in current browser</a></p>\n\n<p>Safari 5, Firefox 14</p>\n\n<pre><code>[\"a:1\", \"b:2\", \"c:3\", \"123:xyz\"]\n[\"a:4\", \"b:2\", \"c:3\", \"123:xyz\"]\n[\"b:2\", \"c:3\", \"123:xyz\", \"a:4\"]\n</code></pre>\n\n<p>Chrome 21, Opera 12, Node 0.6, Firefox 27</p>\n\n<pre><code>[\"123:xyz\", \"a:1\", \"b:2\", \"c:3\"]\n[\"123:xyz\", \"a:4\", \"b:2\", \"c:3\"]\n[\"123:xyz\", \"b:2\", \"c:3\", \"a:4\"]\n</code></pre>\n\n<p>IE9</p>\n\n<pre><code>[123:xyz,a:1,b:2,c:3] \n[123:xyz,a:4,b:2,c:3] \n[123:xyz,a:4,b:2,c:3] \n</code></pre>\n"
},
{
"answer_id": 50091737,
"author": "JDQ",
"author_id": 3662499,
"author_profile": "https://Stackoverflow.com/users/3662499",
"pm_score": 2,
"selected": false,
"text": "<p>This does not answer the question per se, but offers a solution to the basic problem.</p>\n<p>Assuming that you cannot rely on order to preserved, why not use an array of objects with key and value as properties?</p>\n<pre><code>var myArray = [\n {\n 'key' : 'key1'\n 'value' : 0\n },\n {\n 'key' : 'key2',\n 'value' : 1\n } // ...\n];\n</code></pre>\n<p>Now, it is up to you to ensure that the keys are unique (assuming that this is also important to you). As well, direct addressing changes, and <code>for (...in...)</code> now returns indices as 'keys'.</p>\n<pre><code>> console.log(myArray[0].key);\nkey1\n\n> for (let index in myArray) {console.log(myArray[index].value);}\n0\n1\n</code></pre>\nSee the Pen <a href=\"https://codepen.io/JDQ/pen/deNqKZ/\" rel=\"nofollow noreferrer\">for (...in...) addressing in order</a> by JDQ (<a href=\"https://codepen.io/JDQ\" rel=\"nofollow noreferrer\">@JDQ</a>) on <a href=\"https://codepen.io\" rel=\"nofollow noreferrer\">CodePen</a>.</p>\n\n"
},
{
"answer_id": 63355429,
"author": "Thierry J.",
"author_id": 1710784,
"author_profile": "https://Stackoverflow.com/users/1710784",
"pm_score": 2,
"selected": false,
"text": "<p>As stated by other answers, no, the order is not guaranteed.</p>\n<p>If you want to iterate in order, you can do something like:</p>\n<pre><code>let keys = Object.keys(myObject);\nfor (let key of keys.sort()) {\n let value = myObject[key];\n \n // Do what you want with key and value \n}\n</code></pre>\n<p>Note that performance-wise, this is not optimal, but that's the price when you want a nice alphabetical display.</p>\n"
},
{
"answer_id": 70925912,
"author": "Lukáš Řádek",
"author_id": 2468189,
"author_profile": "https://Stackoverflow.com/users/2468189",
"pm_score": 0,
"selected": false,
"text": "<p><strong>As of 2022</strong>,</p>\n<p>I have just found out (to my surprise), that Chrome does not respect the definition order. It rather sorts it alphabetically but <strong>not naturally</strong>. For example key "a12" comes BEFORE "a3". So be careful.</p>\n"
}
] |
2008/11/11
|
[
"https://Stackoverflow.com/questions/280713",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3055/"
] |
Does the "for…in" loop in Javascript loop through the hashtables/elements in the order they are declared? Is there a browser which doesn't do it in order?
The object I wish to use will be declared *once* and will never be modified.
Suppose I have:
```
var myObject = { A: "Hello", B: "World" };
```
And I further use them in:
```
for (var item in myObject) alert(item + " : " + myObject[item]);
```
Can I expect 'A : "Hello"' to always come before 'B : "World"' in most decent browsers?
|
[Quoting John Resig](http://ejohn.org/blog/javascript-in-chrome/):
>
> Currently all major browsers loop over the properties of an object in the order in
> which they were defined. Chrome does this as well, except for a couple cases. [...]
> This behavior is explicitly left undefined by the ECMAScript specification.
> In ECMA-262, section 12.6.4:
>
>
>
> >
> > The mechanics of enumerating the properties ... is implementation dependent.
> >
> >
> >
>
>
> However, specification is quite different from implementation. All modern implementations
> of ECMAScript iterate through object properties in the order in which they were defined.
> Because of this the Chrome team has deemed this to be a bug and will be fixing it.
>
>
>
All browsers respect definition order [with the exception of Chrome](https://code.google.com/p/v8/issues/detail?id=164) and Opera which do for every non-numerical property name. In these two browsers the properties are pulled in-order ahead of the first non-numerical property (this is has to do with how they implement arrays). The order is the same for `Object.keys` as well.
This example should make it clear what happens:
```
var obj = {
"first":"first",
"2":"2",
"34":"34",
"1":"1",
"second":"second"
};
for (var i in obj) { console.log(i); };
// Order listed:
// "1"
// "2"
// "34"
// "first"
// "second"
```
The technicalities of this are less important than the fact that this may change at any time. Do not rely on things staying this way.
In short: **Use an array if order is important to you.**
|
280,729 |
<p>I am trying to use the following code to write data into an excel file</p>
<pre><code> Dim objexcel As Excel.Application
Dim wbexcel As Excel.Workbook
Dim wbExists As Boolean
Set objexcel = CreateObject("excel.Application")
objexcel.Visible = True
On Error GoTo Openwb
wbExists = False
Set wbexcel = objexcel.Documents.Open("C:\Documents and Settings\TAYYAPP\Desktop\test folder\ERROR REPORT2.xls")
wbExists = True
Openwb:
On Error GoTo 0
If Not wbExists Then
Set wbexcel = objexcel.Workbook.Add
End If
</code></pre>
<p>but I'm getting an </p>
<blockquote>
<p>runtime error object doesn't support property or method</p>
</blockquote>
<p>in the line</p>
<pre><code>Set wbexcel = objexcel.Workbook.Add
</code></pre>
<p>I have referenced the Excel object library.</p>
|
[
{
"answer_id": 280758,
"author": "Fionnuala",
"author_id": 2548,
"author_profile": "https://Stackoverflow.com/users/2548",
"pm_score": 4,
"selected": true,
"text": "<p>You will need to change this line:</p>\n\n<pre><code> Set wbexcel = objexcel.WorkBooks.Open( _\n \"C:\\Documents and Settings\\TAYYAPP\\Desktop\\test folder\\ERROR REPORT2.xls\") \n</code></pre>\n\n<p>Note WorkBooks, not Documents </p>\n\n<p>As For this line Set wbexcel = objexcel.Workbook.Add, wbexcel is defined as a workbook, but the line is an action, so:</p>\n\n<pre><code>objexcel.Workbooks.Add\nSet wbexcel = objexcel.ActiveWorkbook\n</code></pre>\n\n<p>EDIT:\nAs an aside, DoCmd.Transferspreadsheet is probably the easiest way of transferring a set of data (query, table) from Access to Excel.</p>\n"
},
{
"answer_id": 286626,
"author": "tksy",
"author_id": 31132,
"author_profile": "https://Stackoverflow.com/users/31132",
"pm_score": 0,
"selected": false,
"text": "<p>I have got this code which works fine</p>\n\n<pre><code>Dim objexcel As Excel.Application\n Dim wbexcel As Excel.Workbook\n Dim wbExists As Boolean\n Dim objSht As Excel.Worksheet\n Dim objRange As Excel.Range\n\n\n Set objexcel = CreateObject(\"excel.Application\")\n objexcel.Visible = True\n On Error GoTo Openwb\n wbExists = False\n Set wbexcel = objexcel.Workbooks.Open(\"C:\\Documents and Settings\\TAYYAPP\\Desktop\\test folder\\reports\\ERROR REPORT2.xls\")\n Set objSht = wbexcel.Worksheets(\"Sheet1\")\n objSht.Activate\n wbExists = True\nOpenwb:\n\n On Error GoTo 0\n If Not wbExists Then\n objexcel.Workbooks.Add\n Set wbexcel = objexcel.ActiveWorkbook\n Set objSht = wbexcel.Worksheets(\"Sheet1\")\n\n End If\n</code></pre>\n\n<p>but I want to add one more check that if the file exists then I want to see if its is populated with values and if so then I want the next set of values to be populated from the end. As of now it is overwriting the existing values</p>\n"
}
] |
2008/11/11
|
[
"https://Stackoverflow.com/questions/280729",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/31132/"
] |
I am trying to use the following code to write data into an excel file
```
Dim objexcel As Excel.Application
Dim wbexcel As Excel.Workbook
Dim wbExists As Boolean
Set objexcel = CreateObject("excel.Application")
objexcel.Visible = True
On Error GoTo Openwb
wbExists = False
Set wbexcel = objexcel.Documents.Open("C:\Documents and Settings\TAYYAPP\Desktop\test folder\ERROR REPORT2.xls")
wbExists = True
Openwb:
On Error GoTo 0
If Not wbExists Then
Set wbexcel = objexcel.Workbook.Add
End If
```
but I'm getting an
>
> runtime error object doesn't support property or method
>
>
>
in the line
```
Set wbexcel = objexcel.Workbook.Add
```
I have referenced the Excel object library.
|
You will need to change this line:
```
Set wbexcel = objexcel.WorkBooks.Open( _
"C:\Documents and Settings\TAYYAPP\Desktop\test folder\ERROR REPORT2.xls")
```
Note WorkBooks, not Documents
As For this line Set wbexcel = objexcel.Workbook.Add, wbexcel is defined as a workbook, but the line is an action, so:
```
objexcel.Workbooks.Add
Set wbexcel = objexcel.ActiveWorkbook
```
EDIT:
As an aside, DoCmd.Transferspreadsheet is probably the easiest way of transferring a set of data (query, table) from Access to Excel.
|
280,749 |
<p>I have some directories that are bundled with my installer and I need to access them from within a custom action. I have done some research and seen that the SourceDir can be used to obtain the currently executing dir location. However I cannot find any examples of how to obtain this property? Or another way to obtain the current directory?</p>
<p>Can anyone advise or point me to anything other than the unhelpful Microsoft site?</p>
|
[
{
"answer_id": 282465,
"author": "w4g3n3r",
"author_id": 36745,
"author_profile": "https://Stackoverflow.com/users/36745",
"pm_score": 1,
"selected": false,
"text": "<p>I'm assuming you're using vbscript for the custom action. If so, properties can be accessed via the Session object. See below:</p>\n\n<pre><code>strSourceDir = Session.Property(\"SourceDir\")\n</code></pre>\n\n<p>Be aware that the SourceDir property is only available at <a href=\"http://msdn.microsoft.com/en-us/library/aa371857(VS.85).aspx\" rel=\"nofollow noreferrer\">specific times during the installation</a>.</p>\n"
},
{
"answer_id": 1004783,
"author": "Chris",
"author_id": 203114,
"author_profile": "https://Stackoverflow.com/users/203114",
"pm_score": 1,
"selected": false,
"text": "<p>For C#, you'll find that you can do something like this:</p>\n\n<pre><code>[CustomAction]\npublic static ActionResult MyCustomAction(Session session)\n{\n string sourceDir = session[\"SourceDir\"];\n string path = Path.Combine(sourceDir, \"yourfilename.txt\");\n ...\n</code></pre>\n\n<p>The <a href=\"http://msdn.microsoft.com/en-us/library/aa371681.aspx\" rel=\"nofollow noreferrer\">documentation on MSDN</a> is unfortunately lacking in making this clear.</p>\n\n<p>As w4g3n3r mentions in his answer, SourceDir is only available to you at certain times. In short, you will need to make sure your custom action is called <strong>after</strong> a call to the ResolveSource action, which can only be called after CostInitialize has run. </p>\n\n<p>Once SourceDir is set, it should be available for use for the remainder of the installation process.</p>\n"
},
{
"answer_id": 1004812,
"author": "William Leara",
"author_id": 116166,
"author_profile": "https://Stackoverflow.com/users/116166",
"pm_score": 0,
"selected": false,
"text": "<p>Are you using InstallShield? Here's an example for an InstallScript CA:</p>\n\n<pre><code>MsiGetProperty(hMSI, \"CustomActionData\", strDirectory, numBuffer);\n</code></pre>\n\n<p>... where you also used a Set Property \"Type 51\" custom action to setup CustomActionData for your function to the value SOURCEDIR.</p>\n"
}
] |
2008/11/11
|
[
"https://Stackoverflow.com/questions/280749",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] |
I have some directories that are bundled with my installer and I need to access them from within a custom action. I have done some research and seen that the SourceDir can be used to obtain the currently executing dir location. However I cannot find any examples of how to obtain this property? Or another way to obtain the current directory?
Can anyone advise or point me to anything other than the unhelpful Microsoft site?
|
I'm assuming you're using vbscript for the custom action. If so, properties can be accessed via the Session object. See below:
```
strSourceDir = Session.Property("SourceDir")
```
Be aware that the SourceDir property is only available at [specific times during the installation](http://msdn.microsoft.com/en-us/library/aa371857(VS.85).aspx).
|
280,751 |
<p>I have a large c# solution file (~100 projects), and I am trying to improve build times. I think that "Copy Local" is wasteful in many cases for us, but I am wondering about best practices.</p>
<p>In our .sln, we have application A depending on assembly B which depends on assembly C. In our case, there are dozens of "B" and a handful of "C". Since these are all included in the .sln, we're using project references. All assemblies currently build into $(SolutionDir)/Debug (or Release).</p>
<p>By default, Visual Studio marks these project references as "Copy Local", which results in every "C" being copied into $(SolutionDir)/Debug once for every "B" that builds. This seems wasteful. What can go wrong if I just turn "Copy Local" off? What do other people with large systems do?</p>
<p>FOLLOWUP:</p>
<p>Lots of responses suggest breaking up the build into smaller .sln files... In the example above, I would build the foundation classes "C" first, followed by the bulk of the modules "B", and then a few applications, "A". In this model, I need to have non-project references to C from B. The problem I run into there is that "Debug" or "Release" gets baked into the hint path and I wind up building my Release builds of "B" against debug builds of "C". </p>
<p>For those of you that split the build up into multiple .sln files, how do you manage this problem?</p>
|
[
{
"answer_id": 280770,
"author": "TcKs",
"author_id": 20382,
"author_profile": "https://Stackoverflow.com/users/20382",
"pm_score": 2,
"selected": false,
"text": "<p>our \"best practise\" is to avoid solutions with many projects.\nWe have a directory named \"matrix\" with current versions of assemblies, and all references are from this directory. If you change some project and you can say \"now the change is complete\" you can copy the assembly into the \"matrix\" directory. So all projects that depends on this assembly will have the current(=latest) version.</p>\n\n<p>If you have few projects in solution, the build process is much faster.</p>\n\n<p>You can automate the \"copy assembly to matrix directory\" step using visual studio macros or with \"menu -> tools -> external tools...\".</p>\n"
},
{
"answer_id": 280771,
"author": "kenny",
"author_id": 3225,
"author_profile": "https://Stackoverflow.com/users/3225",
"pm_score": 1,
"selected": false,
"text": "<p>I tend to build to a common directory (e.g. ..\\bin), so I can create small test solutions.</p>\n"
},
{
"answer_id": 280782,
"author": "Bruno Shine",
"author_id": 28294,
"author_profile": "https://Stackoverflow.com/users/28294",
"pm_score": 3,
"selected": false,
"text": "<p>In my opinion, having a solution with 100 projects is a BIG mistake. You could probably split your solution in valid logical small units, thus simplifying both maintenance and builds.</p>\n"
},
{
"answer_id": 280788,
"author": "CubanX",
"author_id": 27555,
"author_profile": "https://Stackoverflow.com/users/27555",
"pm_score": 0,
"selected": false,
"text": "<p>Usually, you only need to Copy Local if you want your project using the DLL that is in your Bin vs. what is somewhere else (the GAC, other projects, etc.)</p>\n\n<p>I would tend to agree with the other folks that you should also try, if at all possible, to break up that solution.</p>\n\n<p>You can also use Configuration Manager to make yourself different build configurations within that one solution that will only build given sets of projects.</p>\n\n<p>It would seem odd if all 100 projects relied on one another, so you should be able to either break it up or use Configuration Manager to help yourself out.</p>\n"
},
{
"answer_id": 280804,
"author": "Aleksandar",
"author_id": 29511,
"author_profile": "https://Stackoverflow.com/users/29511",
"pm_score": 1,
"selected": false,
"text": "<p>You can try to use a folder where all assemblies that are shared between projects will be copied, then make an DEVPATH environment variable and set <br/><br/> <code><developmentMode developerInstallation=\"true\" /></code> <br/><br/> in machine.config file on each developer's workstation. The only thing you need to do is to copy any new version in your folder where DEVPATH variable points.</p>\n\n<p>\nAlso divide your solution into few smaller solutions if possible.\n</p>\n"
},
{
"answer_id": 280988,
"author": "jyoung",
"author_id": 14841,
"author_profile": "https://Stackoverflow.com/users/14841",
"pm_score": 1,
"selected": false,
"text": "<p>This may not be best pratice, but this is how I work. </p>\n\n<p>I noticed that Managed C++ dumps all of its binaries into $(SolutionDir)/'DebugOrRelease'.\nSo I dumped all my C# projects there too. I also turned off the \"Copy Local\" of all references to projects in the solution. I had noticable build time improvement in my small 10 project solution. This solution is a mixture of C#, managed C++, native C++, C# webservice, and installer projects. </p>\n\n<p>Maybe something is broken, but since this is the only way I work, I do not notice it.</p>\n\n<p>It would be interesting to find out what I am breaking.</p>\n"
},
{
"answer_id": 283808,
"author": "Bruno Shine",
"author_id": 28294,
"author_profile": "https://Stackoverflow.com/users/28294",
"pm_score": 0,
"selected": false,
"text": "<p>You can have your projects references pointing to the debug versions of the dlls.\nThan on your msbuild script, you can set the <code>/p:Configuration=Release</code>, thus you will have a release version of your application and all satellite assemblies.</p>\n"
},
{
"answer_id": 649590,
"author": "Torbjörn Gyllebring",
"author_id": 21182,
"author_profile": "https://Stackoverflow.com/users/21182",
"pm_score": 3,
"selected": false,
"text": "<p>If you got the dependency structure defined via project references or via solution level dependencies it's safe to turn of \"Copy Local\" I would even say that it's a best practice todo so since that will let you use MSBuild 3.5 to run your build in parallel (via /maxcpucount) without diffrent processes tripping over each other when trying to copy referenced assemblies.</p>\n"
},
{
"answer_id": 649771,
"author": "Bas Bossink",
"author_id": 74198,
"author_profile": "https://Stackoverflow.com/users/74198",
"pm_score": 7,
"selected": true,
"text": "<p>In a previous project I worked with one big solution with project references and bumped into a performance problem as well. The solution was three fold:</p>\n\n<ol>\n<li><p>Always set the Copy Local property to false and enforce this via a custom msbuild step</p></li>\n<li><p>Set the output directory for each project to the same directory (preferably relative to $(SolutionDir)</p></li>\n<li><p>The default cs targets that get shipped with the framework calculate the set of references to be copied to the output directory of the project currently being built. Since this requires calculating a transitive closure under the 'References' relation this can become <strong>VERY</strong> costly. My workaround for this was to redefine the <code>GetCopyToOutputDirectoryItems</code> target in a common targets file (eg. <code>Common.targets</code> ) that's imported in every project after the import of the <code>Microsoft.CSharp.targets</code>. Resulting in every project file to look like the following: </p>\n\n<pre><code><Project DefaultTargets=\"Build\" xmlns=\"http://schemas.microsoft.com/developer/msbuild/2003\">\n <PropertyGroup>\n ... snip ...\n </ItemGroup>\n <Import Project=\"$(MSBuildBinPath)\\Microsoft.CSharp.targets\" />\n <Import Project=\"[relative path to Common.targets]\" />\n <!-- To modify your build process, add your task inside one of the targets below and uncomment it. \n Other similar extension points exist, see Microsoft.Common.targets.\n <Target Name=\"BeforeBuild\">\n </Target>\n <Target Name=\"AfterBuild\">\n </Target>\n -->\n</Project>\n</code></pre></li>\n</ol>\n\n<p>This reduced our build time at a given time from a couple of hours (mostly due to memory constraints), to a couple of minutes.</p>\n\n<p>The redefined <code>GetCopyToOutputDirectoryItems</code> can be created by copying the lines 2,438–2,450 and 2,474–2,524 from <code>C:\\WINDOWS\\Microsoft.NET\\Framework\\v2.0.50727\\Microsoft.Common.targets</code> into <code>Common.targets</code>.</p>\n\n<p>For completeness the resulting target definition then becomes:</p>\n\n<pre><code><!-- This is a modified version of the Microsoft.Common.targets\n version of this target it does not include transitively\n referenced projects. Since this leads to enormous memory\n consumption and is not needed since we use the single\n output directory strategy.\n============================================================\n GetCopyToOutputDirectoryItems\n\nGet all project items that may need to be transferred to the\noutput directory.\n============================================================ -->\n<Target\n Name=\"GetCopyToOutputDirectoryItems\"\n Outputs=\"@(AllItemsFullPathWithTargetPath)\"\n DependsOnTargets=\"AssignTargetPaths;_SplitProjectReferencesByFileExistence\">\n\n <!-- Get items from this project last so that they will be copied last. -->\n <CreateItem\n Include=\"@(ContentWithTargetPath->'%(FullPath)')\"\n Condition=\"'%(ContentWithTargetPath.CopyToOutputDirectory)'=='Always' or '%(ContentWithTargetPath.CopyToOutputDirectory)'=='PreserveNewest'\"\n >\n <Output TaskParameter=\"Include\" ItemName=\"AllItemsFullPathWithTargetPath\"/>\n <Output TaskParameter=\"Include\" ItemName=\"_SourceItemsToCopyToOutputDirectoryAlways\"\n Condition=\"'%(ContentWithTargetPath.CopyToOutputDirectory)'=='Always'\"/>\n <Output TaskParameter=\"Include\" ItemName=\"_SourceItemsToCopyToOutputDirectory\"\n Condition=\"'%(ContentWithTargetPath.CopyToOutputDirectory)'=='PreserveNewest'\"/>\n </CreateItem>\n\n <CreateItem\n Include=\"@(_EmbeddedResourceWithTargetPath->'%(FullPath)')\"\n Condition=\"'%(_EmbeddedResourceWithTargetPath.CopyToOutputDirectory)'=='Always' or '%(_EmbeddedResourceWithTargetPath.CopyToOutputDirectory)'=='PreserveNewest'\"\n >\n <Output TaskParameter=\"Include\" ItemName=\"AllItemsFullPathWithTargetPath\"/>\n <Output TaskParameter=\"Include\" ItemName=\"_SourceItemsToCopyToOutputDirectoryAlways\"\n Condition=\"'%(_EmbeddedResourceWithTargetPath.CopyToOutputDirectory)'=='Always'\"/>\n <Output TaskParameter=\"Include\" ItemName=\"_SourceItemsToCopyToOutputDirectory\"\n Condition=\"'%(_EmbeddedResourceWithTargetPath.CopyToOutputDirectory)'=='PreserveNewest'\"/>\n </CreateItem>\n\n <CreateItem\n Include=\"@(Compile->'%(FullPath)')\"\n Condition=\"'%(Compile.CopyToOutputDirectory)'=='Always' or '%(Compile.CopyToOutputDirectory)'=='PreserveNewest'\">\n <Output TaskParameter=\"Include\" ItemName=\"_CompileItemsToCopy\"/>\n </CreateItem>\n <AssignTargetPath Files=\"@(_CompileItemsToCopy)\" RootFolder=\"$(MSBuildProjectDirectory)\">\n <Output TaskParameter=\"AssignedFiles\" ItemName=\"_CompileItemsToCopyWithTargetPath\" />\n </AssignTargetPath>\n <CreateItem Include=\"@(_CompileItemsToCopyWithTargetPath)\">\n <Output TaskParameter=\"Include\" ItemName=\"AllItemsFullPathWithTargetPath\"/>\n <Output TaskParameter=\"Include\" ItemName=\"_SourceItemsToCopyToOutputDirectoryAlways\"\n Condition=\"'%(_CompileItemsToCopyWithTargetPath.CopyToOutputDirectory)'=='Always'\"/>\n <Output TaskParameter=\"Include\" ItemName=\"_SourceItemsToCopyToOutputDirectory\"\n Condition=\"'%(_CompileItemsToCopyWithTargetPath.CopyToOutputDirectory)'=='PreserveNewest'\"/>\n </CreateItem>\n\n <CreateItem\n Include=\"@(_NoneWithTargetPath->'%(FullPath)')\"\n Condition=\"'%(_NoneWithTargetPath.CopyToOutputDirectory)'=='Always' or '%(_NoneWithTargetPath.CopyToOutputDirectory)'=='PreserveNewest'\"\n >\n <Output TaskParameter=\"Include\" ItemName=\"AllItemsFullPathWithTargetPath\"/>\n <Output TaskParameter=\"Include\" ItemName=\"_SourceItemsToCopyToOutputDirectoryAlways\"\n Condition=\"'%(_NoneWithTargetPath.CopyToOutputDirectory)'=='Always'\"/>\n <Output TaskParameter=\"Include\" ItemName=\"_SourceItemsToCopyToOutputDirectory\"\n Condition=\"'%(_NoneWithTargetPath.CopyToOutputDirectory)'=='PreserveNewest'\"/>\n </CreateItem>\n</Target>\n</code></pre>\n\n<p>With this workaround in place I found it workable to have as much as > 120 projects in one solution, this has the main benefit that the build order of the projects can still be determined by VS instead of doing that by hand by splitting up your solution.</p>\n"
},
{
"answer_id": 649796,
"author": "Julien Hoarau",
"author_id": 12248,
"author_profile": "https://Stackoverflow.com/users/12248",
"pm_score": 5,
"selected": false,
"text": "<p>I'll suggest you to read Patric Smacchia's articles on that subject :</p>\n\n<ul>\n<li><a href=\"http://www.simple-talk.com/dotnet/.net-framework/partitioning-your-code-base-through-.net-assemblies-and-visual-studio-projects/\" rel=\"noreferrer\">Partitioning Your Code Base Through .NET Assemblies and Visual Studio Projects</a> --> <em>Should every Visual Studio project really be in its own assembly? And what does 'Copy Local=True' really mean?</em></li>\n<li><a href=\"http://codebetter.com/blogs/patricksmacchia/archive/2009/01/11/lessons-learned-from-the-nunit-code-base.aspx\" rel=\"noreferrer\">Lessons learned from the NUnit code base</a> --> <em>The VisualStudio Project Reference + Copy Local true option is evil!</em>)</li>\n<li><a href=\"http://codebetter.com/patricksmacchia/2009/03/15/analyzing-the-code-base-of-cruisecontrol-net/\" rel=\"noreferrer\">Analyzing the code base of CruiseControl.NET</a> --> <em>Bad usage of Copy Local Reference Assembly option set to True)</em></li>\n</ul>\n\n<blockquote>\n <p>CC.Net VS projects rely on the copy local reference assembly option set to true. [...]\n Not only this increase significantly the compilation time (x3 in the case of NUnit), but also it messes up your working environment. Last but not least, doing so introduces the risk for versioning potential problems. Btw, NDepend will emit a warning if it founds 2 assemblies in 2 different directories with the same name, but not the same content or version.</p>\n \n <p>The right thing to do is to define 2 directories $RootDir$\\bin\\Debug and $RootDir$\\bin\\Release, and configure your VisualStudio projects to emit assemblies in these directories. All project references should reference assemblies in the Debug directory.</p>\n</blockquote>\n\n<p>You could also read <a href=\"http://www.theserverside.net/tt/articles/showarticle.tss?id=ControllingDependencies\" rel=\"noreferrer\">this article</a> to help you reduce your projects number and improve your compilation time.</p>\n"
},
{
"answer_id": 2024003,
"author": "Sayed Ibrahim Hashimi",
"author_id": 105999,
"author_profile": "https://Stackoverflow.com/users/105999",
"pm_score": 3,
"selected": false,
"text": "<p>You are correct. CopyLocal will absolutely kill your build times. If you have a large source tree then you should disable CopyLocal. Unfortunately it not as easy as it should be to disable it cleanly. I have answered this exact question about disabling CopyLocal at <a href=\"https://stackoverflow.com/questions/1682096/how-do-i-override-copylocal-private-setting-for-references-in-net-from-msbuild\">How do I override CopyLocal (Private) setting for references in .NET from MSBUILD</a>. Check it out. As well as <a href=\"https://stackoverflow.com/questions/690033/best-practices-for-large-solutions-in-visual-studio-2008\">Best practices for large solutions in Visual Studio (2008).</a></p>\n\n<p>Here is some more info on CopyLocal as I see it.</p>\n\n<p>CopyLocal was implemented really to support local debugging. When you prepare your application for packaging and deployment you should build your projects to the same output folder and make sure you have all the references you need there.</p>\n\n<p>I have written about how to deal with building large source trees in the article <a href=\"http://msdn.microsoft.com/en-us/magazine/dd483291.aspx\" rel=\"nofollow noreferrer\">MSBuild: Best Practices For Creating Reliable Builds, Part 2</a>.</p>\n"
},
{
"answer_id": 2553187,
"author": "user306031",
"author_id": 306031,
"author_profile": "https://Stackoverflow.com/users/306031",
"pm_score": 0,
"selected": false,
"text": "<p>If you want to have a central place to reference a DLL using copy local false will fail without the GAC unless you do this.</p>\n\n<p><a href=\"http://nbaked.wordpress.com/2010/03/28/gac-alternative/\" rel=\"nofollow noreferrer\">http://nbaked.wordpress.com/2010/03/28/gac-alternative/</a></p>\n"
},
{
"answer_id": 6529461,
"author": "Aaron Stainback",
"author_id": 424430,
"author_profile": "https://Stackoverflow.com/users/424430",
"pm_score": 5,
"selected": false,
"text": "<p>I suggest having copy local = false for almost all projects except the one that is at the top of the dependency tree. And for all the references in the one at the top set copy local = true. I see many people suggesting sharing an output directory; I think this is a horrible idea based on experience. If your startup project holds references to a dll that any other project holds a reference to you will at some point experience an access\\sharing violation even if copy local = false on everything and your build will fail. This issue is very annoying and hard to track down. I completely suggest staying away from a shard output directory and instead of having the project at the top of the dependency chain write the needed assemblies to the corresponding folder. If you don't have a project at the \"top,\" then I would suggest a post-build copy to get everything in the right place. Also, I would try and keep in mind the ease of debugging. Any exe projects I still leave copy local=true so the F5 debugging experience will work.</p>\n"
},
{
"answer_id": 13784190,
"author": "Michael Freidgeim",
"author_id": 52277,
"author_profile": "https://Stackoverflow.com/users/52277",
"pm_score": 2,
"selected": false,
"text": "<p>Set CopyLocal=false will reduce build time, but can cause different issues during deployment.</p>\n\n<p>There are many scenarios, when you need to have Copy Local’ left to True, e.g. </p>\n\n<ul>\n<li>Top-level projects, </li>\n<li>Second-level dependencies, </li>\n<li>DLLs called by reflection</li>\n</ul>\n\n<p>The possible issues described in SO questions<br>\n\"<a href=\"https://stackoverflow.com/questions/602765/when-should-copy-local-be-set-to-true-and-when-should-it-not\">When should copy-local be set to true and when should it not?</a>\",<br>\n\"<a href=\"https://stackoverflow.com/questions/1091853/unable-to-load-one-or-more-of-the-requested-types-retrieve-the-loaderexceptions/6200173#6200173\">Error message 'Unable to load one or more of the requested types. Retrieve the LoaderExceptions property for more information.'</a>\"<br>\nand <a href=\"https://stackoverflow.com/users/424430/aaron-stainback\">aaron-stainback</a>'s <a href=\"https://stackoverflow.com/a/6200173/52277\">answer</a> for this question.</p>\n\n<p>My experience with setting CopyLocal=false was NOT successful. See my blog post <a href=\"http://geekswithblogs.net/mnf/archive/2012/12/09/do-not-change-copy-local-project-references-to-false-unless.aspx\" rel=\"nofollow noreferrer\">\"Do NOT Change \"Copy Local” project references to false, unless understand subsequences.\"</a></p>\n\n<p>The time to solve the issues overweight the benefits of setting copyLocal=false.</p>\n"
},
{
"answer_id": 29708236,
"author": "Matt Slagle",
"author_id": 1557745,
"author_profile": "https://Stackoverflow.com/users/1557745",
"pm_score": 3,
"selected": false,
"text": "<p>I am surprised no one has mentioned using hardlinks. Instead of copying the files, it creates a hardlink to the original file. This saves disk space as well as greatly speeding up build. This can enabled on the command line with the following properties: </p>\n\n<p>/p:CreateHardLinksForAdditionalFilesIfPossible=true;CreateHardLinksForCopyAdditionalFilesIfPossible=true;CreateHardLinksForCopyFilesToOutputDirectoryIfPossible=true;CreateHardLinksForCopyLocalIfPossible=true;CreateHardLinksForPublishFilesIfPossible=true</p>\n\n<p>You can also add this to a central import file so that all your projects can also get this benefit.</p>\n"
},
{
"answer_id": 30855833,
"author": "Sheen",
"author_id": 451875,
"author_profile": "https://Stackoverflow.com/users/451875",
"pm_score": 2,
"selected": false,
"text": "<p>You don't need to change CopyLocal values. All you need to do is predefine a common $(OutputPath) for all projects in the solution and preset $(UseCommonOutputDirectory) to true. See this:\n<a href=\"http://blogs.msdn.com/b/kirillosenkov/archive/2015/04/04/using-a-common-intermediate-and-output-directory-for-your-solution.aspx\" rel=\"nofollow\">http://blogs.msdn.com/b/kirillosenkov/archive/2015/04/04/using-a-common-intermediate-and-output-directory-for-your-solution.aspx</a></p>\n"
},
{
"answer_id": 31447843,
"author": "SharpGobi",
"author_id": 2824077,
"author_profile": "https://Stackoverflow.com/users/2824077",
"pm_score": 0,
"selected": false,
"text": "<p>If the reference is not contained within the GAC, we must set the Copy Local to true so that the application will work, if we are sure that the reference will be preinstalled in the GAC then it can be set to false.</p>\n"
},
{
"answer_id": 40787099,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 0,
"selected": false,
"text": "<p>Well, I certainly don't know how the problems works out, but i had contact with a build solution that helped itself in such that all created files where put on an <strong>ramdisk</strong> with the help of <strong>symbolic links</strong>. </p>\n\n<ul>\n<li>c:\\solution folder\\bin -> ramdisk r:\\solution folder\\bin\\</li>\n<li><p>c:\\solution folder\\obj -> ramdisk r:\\solution folder\\obj\\</p></li>\n<li><p>You can also tell additionally the visual studio which temp directory it can use for the build. </p></li>\n</ul>\n\n<p>Actually that wasn't all what it did. But it really hit my understanding of performance. <br>\n100% processor use and a huge project in under 3 Minute with all dependencies. </p>\n"
}
] |
2008/11/11
|
[
"https://Stackoverflow.com/questions/280751",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6996/"
] |
I have a large c# solution file (~100 projects), and I am trying to improve build times. I think that "Copy Local" is wasteful in many cases for us, but I am wondering about best practices.
In our .sln, we have application A depending on assembly B which depends on assembly C. In our case, there are dozens of "B" and a handful of "C". Since these are all included in the .sln, we're using project references. All assemblies currently build into $(SolutionDir)/Debug (or Release).
By default, Visual Studio marks these project references as "Copy Local", which results in every "C" being copied into $(SolutionDir)/Debug once for every "B" that builds. This seems wasteful. What can go wrong if I just turn "Copy Local" off? What do other people with large systems do?
FOLLOWUP:
Lots of responses suggest breaking up the build into smaller .sln files... In the example above, I would build the foundation classes "C" first, followed by the bulk of the modules "B", and then a few applications, "A". In this model, I need to have non-project references to C from B. The problem I run into there is that "Debug" or "Release" gets baked into the hint path and I wind up building my Release builds of "B" against debug builds of "C".
For those of you that split the build up into multiple .sln files, how do you manage this problem?
|
In a previous project I worked with one big solution with project references and bumped into a performance problem as well. The solution was three fold:
1. Always set the Copy Local property to false and enforce this via a custom msbuild step
2. Set the output directory for each project to the same directory (preferably relative to $(SolutionDir)
3. The default cs targets that get shipped with the framework calculate the set of references to be copied to the output directory of the project currently being built. Since this requires calculating a transitive closure under the 'References' relation this can become **VERY** costly. My workaround for this was to redefine the `GetCopyToOutputDirectoryItems` target in a common targets file (eg. `Common.targets` ) that's imported in every project after the import of the `Microsoft.CSharp.targets`. Resulting in every project file to look like the following:
```
<Project DefaultTargets="Build" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
<PropertyGroup>
... snip ...
</ItemGroup>
<Import Project="$(MSBuildBinPath)\Microsoft.CSharp.targets" />
<Import Project="[relative path to Common.targets]" />
<!-- To modify your build process, add your task inside one of the targets below and uncomment it.
Other similar extension points exist, see Microsoft.Common.targets.
<Target Name="BeforeBuild">
</Target>
<Target Name="AfterBuild">
</Target>
-->
</Project>
```
This reduced our build time at a given time from a couple of hours (mostly due to memory constraints), to a couple of minutes.
The redefined `GetCopyToOutputDirectoryItems` can be created by copying the lines 2,438–2,450 and 2,474–2,524 from `C:\WINDOWS\Microsoft.NET\Framework\v2.0.50727\Microsoft.Common.targets` into `Common.targets`.
For completeness the resulting target definition then becomes:
```
<!-- This is a modified version of the Microsoft.Common.targets
version of this target it does not include transitively
referenced projects. Since this leads to enormous memory
consumption and is not needed since we use the single
output directory strategy.
============================================================
GetCopyToOutputDirectoryItems
Get all project items that may need to be transferred to the
output directory.
============================================================ -->
<Target
Name="GetCopyToOutputDirectoryItems"
Outputs="@(AllItemsFullPathWithTargetPath)"
DependsOnTargets="AssignTargetPaths;_SplitProjectReferencesByFileExistence">
<!-- Get items from this project last so that they will be copied last. -->
<CreateItem
Include="@(ContentWithTargetPath->'%(FullPath)')"
Condition="'%(ContentWithTargetPath.CopyToOutputDirectory)'=='Always' or '%(ContentWithTargetPath.CopyToOutputDirectory)'=='PreserveNewest'"
>
<Output TaskParameter="Include" ItemName="AllItemsFullPathWithTargetPath"/>
<Output TaskParameter="Include" ItemName="_SourceItemsToCopyToOutputDirectoryAlways"
Condition="'%(ContentWithTargetPath.CopyToOutputDirectory)'=='Always'"/>
<Output TaskParameter="Include" ItemName="_SourceItemsToCopyToOutputDirectory"
Condition="'%(ContentWithTargetPath.CopyToOutputDirectory)'=='PreserveNewest'"/>
</CreateItem>
<CreateItem
Include="@(_EmbeddedResourceWithTargetPath->'%(FullPath)')"
Condition="'%(_EmbeddedResourceWithTargetPath.CopyToOutputDirectory)'=='Always' or '%(_EmbeddedResourceWithTargetPath.CopyToOutputDirectory)'=='PreserveNewest'"
>
<Output TaskParameter="Include" ItemName="AllItemsFullPathWithTargetPath"/>
<Output TaskParameter="Include" ItemName="_SourceItemsToCopyToOutputDirectoryAlways"
Condition="'%(_EmbeddedResourceWithTargetPath.CopyToOutputDirectory)'=='Always'"/>
<Output TaskParameter="Include" ItemName="_SourceItemsToCopyToOutputDirectory"
Condition="'%(_EmbeddedResourceWithTargetPath.CopyToOutputDirectory)'=='PreserveNewest'"/>
</CreateItem>
<CreateItem
Include="@(Compile->'%(FullPath)')"
Condition="'%(Compile.CopyToOutputDirectory)'=='Always' or '%(Compile.CopyToOutputDirectory)'=='PreserveNewest'">
<Output TaskParameter="Include" ItemName="_CompileItemsToCopy"/>
</CreateItem>
<AssignTargetPath Files="@(_CompileItemsToCopy)" RootFolder="$(MSBuildProjectDirectory)">
<Output TaskParameter="AssignedFiles" ItemName="_CompileItemsToCopyWithTargetPath" />
</AssignTargetPath>
<CreateItem Include="@(_CompileItemsToCopyWithTargetPath)">
<Output TaskParameter="Include" ItemName="AllItemsFullPathWithTargetPath"/>
<Output TaskParameter="Include" ItemName="_SourceItemsToCopyToOutputDirectoryAlways"
Condition="'%(_CompileItemsToCopyWithTargetPath.CopyToOutputDirectory)'=='Always'"/>
<Output TaskParameter="Include" ItemName="_SourceItemsToCopyToOutputDirectory"
Condition="'%(_CompileItemsToCopyWithTargetPath.CopyToOutputDirectory)'=='PreserveNewest'"/>
</CreateItem>
<CreateItem
Include="@(_NoneWithTargetPath->'%(FullPath)')"
Condition="'%(_NoneWithTargetPath.CopyToOutputDirectory)'=='Always' or '%(_NoneWithTargetPath.CopyToOutputDirectory)'=='PreserveNewest'"
>
<Output TaskParameter="Include" ItemName="AllItemsFullPathWithTargetPath"/>
<Output TaskParameter="Include" ItemName="_SourceItemsToCopyToOutputDirectoryAlways"
Condition="'%(_NoneWithTargetPath.CopyToOutputDirectory)'=='Always'"/>
<Output TaskParameter="Include" ItemName="_SourceItemsToCopyToOutputDirectory"
Condition="'%(_NoneWithTargetPath.CopyToOutputDirectory)'=='PreserveNewest'"/>
</CreateItem>
</Target>
```
With this workaround in place I found it workable to have as much as > 120 projects in one solution, this has the main benefit that the build order of the projects can still be determined by VS instead of doing that by hand by splitting up your solution.
|
280,759 |
<p>I am using the <strong><a href="http://en.wikipedia.org/wiki/JQuery" rel="noreferrer">jQuery</a> validation plugin</strong>. Great stuff! I want to migrate my existing ASP.NET solution to use jQuery instead of the ASP.NET validators. I am missing a replacement for the <strong>regular expression</strong> validator. I want to be able to do something like this:</p>
<pre><code>$("Textbox").rules("add", { regularExpression: "^[a-zA-Z'.\s]{1,40}$" })
</code></pre>
<p>How do I <strong>add a custom rule</strong> to achieve this?</p>
|
[
{
"answer_id": 280952,
"author": "redsquare",
"author_id": 6440,
"author_profile": "https://Stackoverflow.com/users/6440",
"pm_score": 6,
"selected": false,
"text": "<p>You can use the addMethod()</p>\n\n<p>e.g </p>\n\n<pre><code>$.validator.addMethod('postalCode', function (value) { \n return /^((\\d{5}-\\d{4})|(\\d{5})|([A-Z]\\d[A-Z]\\s\\d[A-Z]\\d))$/.test(value); \n}, 'Please enter a valid US or Canadian postal code.');\n</code></pre>\n\n<p>good article here <a href=\"https://web.archive.org/web/20130609222116/http://www.randallmorey.com/blog/2008/mar/16/extending-jquery-form-validation-plugin/\" rel=\"noreferrer\">https://web.archive.org/web/20130609222116/http://www.randallmorey.com/blog/2008/mar/16/extending-jquery-form-validation-plugin/</a></p>\n"
},
{
"answer_id": 709358,
"author": "PeterFromCologne",
"author_id": 36546,
"author_profile": "https://Stackoverflow.com/users/36546",
"pm_score": 9,
"selected": true,
"text": "<p>Thanks to the answer of redsquare I added a method like this:</p>\n<pre class=\"lang-js prettyprint-override\"><code>$.validator.addMethod(\n "regex",\n function(value, element, regexp) {\n var re = new RegExp(regexp);\n return this.optional(element) || re.test(value);\n },\n "Please check your input."\n);\n</code></pre>\n<p>Now all you need to do to validate against any regex is this:</p>\n<pre class=\"lang-js prettyprint-override\"><code>$("#Textbox").rules("add", { regex: "^[a-zA-Z'.\\\\s]{1,40}$" })\n</code></pre>\n<p>Additionally, it looks like there is a file called <code>additional-methods.js</code> that contains the method "pattern", which can be a <code>RegExp</code> when created using the method without quotes.</p>\n<hr />\n<h2>Edit</h2>\n<p>The <code>pattern</code> function is now the preferred way to do this, making the example:</p>\n<pre class=\"lang-js prettyprint-override\"><code>$("#Textbox").rules("add", { pattern: "^[a-zA-Z'.\\\\s]{1,40}$" })\n</code></pre>\n<ul>\n<li><a href=\"https://cdnjs.com/libraries/jquery-validate\" rel=\"noreferrer\">https://cdnjs.com/libraries/jquery-validate</a>\n<ul>\n<li><a href=\"https://cdnjs.cloudflare.com/ajax/libs/jquery-validate/1.19.2/jquery.validate.min.js\" rel=\"noreferrer\">https://cdnjs.cloudflare.com/ajax/libs/jquery-validate/1.19.2/jquery.validate.min.js</a></li>\n<li><a href=\"https://cdnjs.cloudflare.com/ajax/libs/jquery-validate/1.19.2/additional-methods.min.js\" rel=\"noreferrer\">https://cdnjs.cloudflare.com/ajax/libs/jquery-validate/1.19.2/additional-methods.min.js</a></li>\n</ul>\n</li>\n</ul>\n"
},
{
"answer_id": 843611,
"author": "Markus Jarderot",
"author_id": 22364,
"author_profile": "https://Stackoverflow.com/users/22364",
"pm_score": 5,
"selected": false,
"text": "<p>Extending PeterTheNiceGuy's answer a bit:</p>\n\n<pre><code>$.validator.addMethod(\n \"regex\",\n function(value, element, regexp) {\n if (regexp.constructor != RegExp)\n regexp = new RegExp(regexp);\n else if (regexp.global)\n regexp.lastIndex = 0;\n return this.optional(element) || regexp.test(value);\n },\n \"Please check your input.\"\n);\n</code></pre>\n\n<p>This would allow you to pass a regex object to the rule.</p>\n\n<pre><code>$(\"Textbox\").rules(\"add\", { regex: /^[a-zA-Z'.\\s]{1,40}$/ });\n</code></pre>\n\n<p>Resetting the <code>lastIndex</code> property is necessary when the <code>g</code>-flag is set on the <code>RegExp</code> object. Otherwise it would start validating from the position of the last match with that regex, even if the subject string is different.</p>\n\n<p>Some other ideas I had was be to enable you use arrays of regex's, and another rule for the negation of regex's:</p>\n\n<pre><code>$(\"password\").rules(\"add\", {\n regex: [\n /^[a-zA-Z'.\\s]{8,40}$/,\n /^.*[a-z].*$/,\n /^.*[A-Z].*$/,\n /^.*[0-9].*$/\n ],\n '!regex': /password|123/\n});\n</code></pre>\n\n<p>But implementing those would maybe be too much.</p>\n"
},
{
"answer_id": 862946,
"author": "Jörn Zaefferer",
"author_id": 2671,
"author_profile": "https://Stackoverflow.com/users/2671",
"pm_score": 4,
"selected": false,
"text": "<p>As mentioned on the <a href=\"http://docs.jquery.com/Plugins/Validation/Validator/addMethod\" rel=\"noreferrer\">addMethod documentation</a>:</p>\n\n<p>Please note: While the temptation is great to add a regex method that checks it's parameter against the value, it is much cleaner to encapsulate those regular expressions inside their own method. If you need lots of slightly different expressions, try to extract a common parameter. A library of regular expressions: <a href=\"http://regexlib.com/DisplayPatterns.aspx\" rel=\"noreferrer\">http://regexlib.com/DisplayPatterns.aspx</a></p>\n\n<p>So yes, you have to add a method for each regular expression. The overhead is minimal, while it allows you to give the regex a name (not to be underestimated), a default message (handy) and the ability to reuse it a various places, without duplicating the regex itself over and over.</p>\n"
},
{
"answer_id": 1217344,
"author": "bshack",
"author_id": 149057,
"author_profile": "https://Stackoverflow.com/users/149057",
"pm_score": 6,
"selected": false,
"text": "<p>I had some trouble putting together all the pieces for doing a jQuery regular expression validator, but I got it to work... Here is a complete working example. It uses the 'Validation' plugin which can be found in <em><a href=\"http://bassistance.de/jquery-plugins/jquery-plugin-validation/\" rel=\"noreferrer\">jQuery Validation Plugin</a></em></p>\n\n<pre><code><!DOCTYPE html PUBLIC \"-//W3C//DTD XHTML 1.0 Strict//EN\" \"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd\">\n<html xmlns=\"http://www.w3.org/1999/xhtml\">\n<head>\n <meta http-equiv=\"Content-Type\" content=\"text/html; charset=UTF-8\" />\n <script src=\"http://YOURJQUERYPATH/js/jquery.js\" type=\"text/javascript\"></script>\n <script src=\"http://YOURJQUERYPATH/js/jquery.validate.js\" type=\"text/javascript\"></script>\n <script type=\"text/javascript\">\n\n $().ready(function() {\n $.validator.addMethod(\"EMAIL\", function(value, element) {\n return this.optional(element) || /^[a-zA-Z0-9._-]+@[a-zA-Z0-9-]+\\.[a-zA-Z.]{2,5}$/i.test(value);\n }, \"Email Address is invalid: Please enter a valid email address.\");\n\n $.validator.addMethod(\"PASSWORD\",function(value,element){\n return this.optional(element) || /^(?=.*\\d)(?=.*[a-z])(?=.*[A-Z]).{8,16}$/i.test(value);\n },\"Passwords are 8-16 characters with uppercase letters, lowercase letters and at least one number.\");\n\n $.validator.addMethod(\"SUBMIT\",function(value,element){\n return this.optional(element) || /[^ ]/i.test(value);\n },\"You did not click the submit button.\");\n\n // Validate signup form on keyup and submit\n $(\"#LOGIN\").validate({\n rules: {\n EMAIL: \"required EMAIL\",\n PASSWORD: \"required PASSWORD\",\n SUBMIT: \"required SUBMIT\",\n },\n });\n });\n </script>\n</head>\n<body>\n <div id=\"LOGIN_FORM\" class=\"form\">\n <form id=\"LOGIN\" name=\"LOGIN\" method=\"post\" action=\"/index/secure/authentication?action=login\">\n <h1>Log In</h1>\n <div id=\"LOGIN_EMAIL\">\n <label for=\"EMAIL\">Email Address</label>\n <input id=\"EMAIL\" name=\"EMAIL\" type=\"text\" value=\"\" tabindex=\"1\" />\n </div>\n <div id=\"LOGIN_PASSWORD\">\n <label for=\"PASSWORD\">Password</label>\n <input id=\"PASSWORD\" name=\"PASSWORD\" type=\"password\" value=\"\" tabindex=\"2\" />\n </div>\n <div id=\"LOGIN_SUBMIT\">\n <input id=\"SUBMIT\" name=\"SUBMIT\" type=\"submit\" value=\"Submit\" tabindex=\"3\" />\n </div>\n </form>\n </div>\n</body>\n</html>\n</code></pre>\n"
},
{
"answer_id": 2040384,
"author": "Sam",
"author_id": 247853,
"author_profile": "https://Stackoverflow.com/users/247853",
"pm_score": 5,
"selected": false,
"text": "<p>No reason to define the regex as a string.</p>\n\n<pre><code>$.validator.addMethod(\n \"regex\",\n function(value, element, regexp) {\n var check = false;\n return this.optional(element) || regexp.test(value);\n },\n \"Please check your input.\"\n);\n</code></pre>\n\n<p>and</p>\n\n<pre><code>telephone: { required: true, regex : /^[\\d\\s]+$/, minlength: 5 },\n</code></pre>\n\n<p>tis better this way, no?</p>\n"
},
{
"answer_id": 4062771,
"author": "Kris Nobels",
"author_id": 492677,
"author_profile": "https://Stackoverflow.com/users/492677",
"pm_score": 4,
"selected": false,
"text": "<p>I got it to work like this:</p>\n\n<p></p>\n\n<pre><code>$.validator.addMethod(\n \"regex\",\n function(value, element, regexp) {\n return this.optional(element) || regexp.test(value);\n },\n \"Please check your input.\"\n);\n\n\n$(function () {\n $('#uiEmailAdress').focus();\n $('#NewsletterForm').validate({\n rules: {\n uiEmailAdress:{\n required: true,\n email: true,\n minlength: 5\n },\n uiConfirmEmailAdress:{\n required: true,\n email: true,\n equalTo: '#uiEmailAdress'\n },\n DDLanguage:{\n required: true\n },\n Testveld:{\n required: true,\n regex: /^[0-9]{3}$/\n }\n },\n messages: {\n uiEmailAdress:{\n required: 'Verplicht veld',\n email: 'Ongeldig emailadres',\n minlength: 'Minimum 5 charaters vereist'\n },\n uiConfirmEmailAdress:{\n required: 'Verplicht veld',\n email: 'Ongeldig emailadres',\n equalTo: 'Veld is niet gelijk aan E-mailadres'\n },\n DDLanguage:{\n required: 'Verplicht veld'\n },\n Testveld:{\n required: 'Verplicht veld',\n regex: '_REGEX'\n }\n }\n });\n});\n</code></pre>\n\n<p>Make sure that the regex is between <code>/</code> :-)</p>\n"
},
{
"answer_id": 22814773,
"author": "staabm",
"author_id": 1597388,
"author_profile": "https://Stackoverflow.com/users/1597388",
"pm_score": 2,
"selected": false,
"text": "<p>we mainly use the markup notation of jquery validation plugin and the posted samples did not work for us, when flags are present in the regex, e.g.</p>\n\n<pre><code><input type=\"text\" name=\"myfield\" regex=\"/^[0-9]{3}$/i\" />\n</code></pre>\n\n<p>therefore we use the following snippet</p>\n\n<pre><code>$.validator.addMethod(\n \"regex\",\n function(value, element, regstring) {\n // fast exit on empty optional\n if (this.optional(element)) {\n return true;\n }\n\n var regParts = regstring.match(/^\\/(.*?)\\/([gim]*)$/);\n if (regParts) {\n // the parsed pattern had delimiters and modifiers. handle them. \n var regexp = new RegExp(regParts[1], regParts[2]);\n } else {\n // we got pattern string without delimiters\n var regexp = new RegExp(regstring);\n }\n\n return regexp.test(value);\n },\n \"Please check your input.\"\n); \n</code></pre>\n\n<p>Of course now one could combine this code, with one of the above to also allow passing RegExp objects into the plugin, but since we didn't needed it we left this exercise for the reader ;-).</p>\n\n<p>PS: there is also bundled plugin for that, <a href=\"https://github.com/jzaefferer/jquery-validation/blob/master/src/additional/pattern.js\" rel=\"nofollow\">https://github.com/jzaefferer/jquery-validation/blob/master/src/additional/pattern.js</a></p>\n"
},
{
"answer_id": 36867078,
"author": "ArunDhwaj IIITH",
"author_id": 1509738,
"author_profile": "https://Stackoverflow.com/users/1509738",
"pm_score": 3,
"selected": false,
"text": "<p>This is working code.</p>\n\n<pre><code>function validateSignup()\n{ \n $.validator.addMethod(\n \"regex\",\n function(value, element, regexp) \n {\n if (regexp.constructor != RegExp)\n regexp = new RegExp(regexp);\n else if (regexp.global)\n regexp.lastIndex = 0;\n return this.optional(element) || regexp.test(value);\n },\n \"Please check your input.\"\n );\n\n $('#signupForm').validate(\n {\n\n onkeyup : false,\n errorClass: \"req_mess\",\n ignore: \":hidden\",\n validClass: \"signup_valid_class\",\n errorClass: \"signup_error_class\",\n\n rules:\n {\n\n email:\n {\n required: true,\n email: true,\n regex: /^[A-Za-z0-9_]+\\@[A-Za-z0-9_]+\\.[A-Za-z0-9_]+/,\n },\n\n userId:\n {\n required: true,\n minlength: 6,\n maxlength: 15,\n regex: /^[A-Za-z0-9_]{6,15}$/,\n },\n\n phoneNum:\n {\n required: true,\n regex: /^[+-]{1}[0-9]{1,3}\\-[0-9]{10}$/,\n },\n\n },\n messages: \n {\n email: \n {\n required: 'You must enter a email',\n regex: 'Please enter a valid email without spacial chars, ie, [email protected]'\n },\n\n userId:\n {\n required: 'Alphanumeric, _, min:6, max:15',\n regex: \"Please enter any alphaNumeric char of length between 6-15, ie, sbp_arun_2016\"\n },\n\n phoneNum: \n {\n required: \"Please enter your phone number\",\n regex: \"e.g. +91-1234567890\" \n },\n\n },\n\n submitHandler: function (form)\n {\n return true;\n }\n });\n}\n</code></pre>\n"
},
{
"answer_id": 37563111,
"author": "Bogdan Mates",
"author_id": 5068697,
"author_profile": "https://Stackoverflow.com/users/5068697",
"pm_score": 2,
"selected": false,
"text": "<p>This worked for me, being one of the validation rules:</p>\n\n<pre><code> Zip: {\n required: true,\n regex: /^\\d{5}(?:[-\\s]\\d{4})?$/\n }\n</code></pre>\n\n<p>Hope it helps</p>\n"
},
{
"answer_id": 47163549,
"author": "Wiktor Stribiżew",
"author_id": 3832970,
"author_profile": "https://Stackoverflow.com/users/3832970",
"pm_score": 4,
"selected": false,
"text": "<p>You may use <em><code>pattern</code></em> defined in the <em><code>additional-methods.js</code></em> file. Note that this additional-methods.js file must be included <em>after</em> jQuery Validate dependency, then you can just use</p>\n\n<p><div class=\"snippet\" data-lang=\"js\" data-hide=\"false\" data-console=\"true\" data-babel=\"false\">\r\n<div class=\"snippet-code\">\r\n<pre class=\"snippet-code-js lang-js prettyprint-override\"><code>$(\"#frm\").validate({\r\n rules: {\r\n Textbox: {\r\n pattern: /^[a-zA-Z'.\\s]{1,40}$/\r\n },\r\n },\r\n messages: {\r\n Textbox: {\r\n pattern: 'The Textbox string format is invalid'\r\n }\r\n }\r\n});</code></pre>\r\n<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>\r\n<script src=\"https://cdnjs.cloudflare.com/ajax/libs/jquery-validate/1.17.0/jquery.validate.js\"></script>\r\n<script src=\"https://cdnjs.cloudflare.com/ajax/libs/jquery-validate/1.17.0/additional-methods.min.js\"></script>\r\n<form id=\"frm\" method=\"get\" action=\"\">\r\n <fieldset>\r\n <p>\r\n <label for=\"fullname\">Textbox</label>\r\n <input id=\"Textbox\" name=\"Textbox\" type=\"text\">\r\n </p>\r\n </fieldset>\r\n</form></code></pre>\r\n</div>\r\n</div>\r\n</p>\n"
},
{
"answer_id": 63363750,
"author": "Amir Hosseinzadeh",
"author_id": 2858268,
"author_profile": "https://Stackoverflow.com/users/2858268",
"pm_score": 1,
"selected": false,
"text": "<pre><code> $.validator.methods.checkEmail = function( value, element ) {\n return this.optional( element ) || /[a-z]+@[a-z]+\\.[a-z]+/.test( value );\n }\n\n $("#myForm").validate({\n rules: {\n email: {\n required: true,\n checkEmail: true\n }\n },\n messages: {\n email: "incorrect email"\n }\n });\n</code></pre>\n"
},
{
"answer_id": 64769318,
"author": "Noob",
"author_id": 8604852,
"author_profile": "https://Stackoverflow.com/users/8604852",
"pm_score": 0,
"selected": false,
"text": "<p>Have you tried this??</p>\n<pre><code>$("Textbox").rules("add", { regex: "^[a-zA-Z'.\\\\s]{1,40}$", messages: { regex: "The text is invalid..." } })\n</code></pre>\n<p>Note: make sure to escape all the "\\" of ur regex by adding another "\\" in front of them else the regex wont work as expected.</p>\n"
}
] |
2008/11/11
|
[
"https://Stackoverflow.com/questions/280759",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/36546/"
] |
I am using the **[jQuery](http://en.wikipedia.org/wiki/JQuery) validation plugin**. Great stuff! I want to migrate my existing ASP.NET solution to use jQuery instead of the ASP.NET validators. I am missing a replacement for the **regular expression** validator. I want to be able to do something like this:
```
$("Textbox").rules("add", { regularExpression: "^[a-zA-Z'.\s]{1,40}$" })
```
How do I **add a custom rule** to achieve this?
|
Thanks to the answer of redsquare I added a method like this:
```js
$.validator.addMethod(
"regex",
function(value, element, regexp) {
var re = new RegExp(regexp);
return this.optional(element) || re.test(value);
},
"Please check your input."
);
```
Now all you need to do to validate against any regex is this:
```js
$("#Textbox").rules("add", { regex: "^[a-zA-Z'.\\s]{1,40}$" })
```
Additionally, it looks like there is a file called `additional-methods.js` that contains the method "pattern", which can be a `RegExp` when created using the method without quotes.
---
Edit
----
The `pattern` function is now the preferred way to do this, making the example:
```js
$("#Textbox").rules("add", { pattern: "^[a-zA-Z'.\\s]{1,40}$" })
```
* <https://cdnjs.com/libraries/jquery-validate>
+ <https://cdnjs.cloudflare.com/ajax/libs/jquery-validate/1.19.2/jquery.validate.min.js>
+ <https://cdnjs.cloudflare.com/ajax/libs/jquery-validate/1.19.2/additional-methods.min.js>
|
280,769 |
<blockquote>
<p><strong>Possible Duplicate:</strong><br>
<a href="https://stackoverflow.com/questions/2246772/whats-the-difference-between-not-exists-vs-not-in-vs-left-join-where-is-null">What's the difference between NOT EXISTS vs. NOT IN vs. LEFT JOIN WHERE IS NULL?</a> </p>
</blockquote>
<p>I need to wite a query that will retrieve the records from Table A , provided that the key in Table A does not exist in Table B.</p>
<p>Any help will be appreciated.</p>
<p>Thanks</p>
|
[
{
"answer_id": 280775,
"author": "Galwegian",
"author_id": 3201,
"author_profile": "https://Stackoverflow.com/users/3201",
"pm_score": 3,
"selected": true,
"text": "<pre><code>SELECT *\nFROM A\nWHERE ID NOT IN\n (SELECT ID FROM B)\n</code></pre>\n"
},
{
"answer_id": 280778,
"author": "CubanX",
"author_id": 27555,
"author_profile": "https://Stackoverflow.com/users/27555",
"pm_score": 0,
"selected": false,
"text": "<p>Assuming:\nTableA's Id = Id\nTableB's Id = Id</p>\n\n<pre><code>select * from TableA ta where ta.Id not in (select Id from TableB)\n</code></pre>\n"
},
{
"answer_id": 280780,
"author": "kristof",
"author_id": 3241,
"author_profile": "https://Stackoverflow.com/users/3241",
"pm_score": 3,
"selected": false,
"text": "<pre><code>select a.* \nfrom\n tableA a\n left join tableB b\n ON a.id = b.id\nwhere\n b.id is null\n</code></pre>\n"
},
{
"answer_id": 280792,
"author": "okoman",
"author_id": 35903,
"author_profile": "https://Stackoverflow.com/users/35903",
"pm_score": 2,
"selected": false,
"text": "<p>Use a left join. The DB tries to map datasets from TableB to TableA using the id fields. If there is no fitting data set available in TableB, the TableB data gets NULL. Now you just have to check for TableB.id to be NULL.</p>\n\n<pre><code>SELECT TableA.* FROM TableA LEFT JOIN TableB ON TableA.id = TableB.id WHERE TableB.id IS NULL\n</code></pre>\n"
},
{
"answer_id": 280858,
"author": "Kaniu",
"author_id": 3236,
"author_profile": "https://Stackoverflow.com/users/3236",
"pm_score": 0,
"selected": false,
"text": "<pre><code>SELECT * FROM TableA\nWHERE NOT Exists(SELECT * FROM TableB WHERE id=TableA.id)\n</code></pre>\n\n<p>also works and it's almost self documenting...</p>\n"
},
{
"answer_id": 1464339,
"author": "Rahul",
"author_id": 24424,
"author_profile": "https://Stackoverflow.com/users/24424",
"pm_score": 2,
"selected": false,
"text": "<p>None of the above solutions would work if the key comprises of multiple columns. </p>\n\n<p>If the tables have compound primary keys, you'll have to use a \"NOT EXISTS\" clause similar to the one below.</p>\n\n<pre><code>SELECT * \n FROM TableA AS a \n WHERE NOT EXISTS (\n SELECT * \n FROM TableB b \n WHERE b.id1 = a.id1 \n AND b.id2 = a.id2 \n AND b.id3 = a.id3\n );\n</code></pre>\n"
}
] |
2008/11/11
|
[
"https://Stackoverflow.com/questions/280769",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] |
>
> **Possible Duplicate:**
>
> [What's the difference between NOT EXISTS vs. NOT IN vs. LEFT JOIN WHERE IS NULL?](https://stackoverflow.com/questions/2246772/whats-the-difference-between-not-exists-vs-not-in-vs-left-join-where-is-null)
>
>
>
I need to wite a query that will retrieve the records from Table A , provided that the key in Table A does not exist in Table B.
Any help will be appreciated.
Thanks
|
```
SELECT *
FROM A
WHERE ID NOT IN
(SELECT ID FROM B)
```
|
280,793 |
<p>I need to highlight, case insensitively, given keywords in a JavaScript string.</p>
<p>For example:</p>
<ul>
<li><code>highlight("foobar Foo bar FOO", "foo")</code> should return <code>"<b>foo</b>bar <b>Foo</b> bar <b>FOO</b>"</code></li>
</ul>
<p>I need the code to work for any keyword, and therefore using a hardcoded regular expression like <code>/foo/i</code> is not a sufficient solution.</p>
<p>What is the easiest way to do this?</p>
<p>(This an instance of a more general problem detailed in the title, but I feel that it's best to tackle with a concrete, useful example.)</p>
|
[
{
"answer_id": 280805,
"author": "okoman",
"author_id": 35903,
"author_profile": "https://Stackoverflow.com/users/35903",
"pm_score": 7,
"selected": true,
"text": "<p>You <em>can</em> use regular expressions if you prepare the search string. In PHP e.g. there is a function preg_quote, which replaces all regex-chars in a string with their escaped versions.</p>\n\n<p>Here is such a function for javascript (<a href=\"https://locutus.io/php/pcre/preg_quote/\" rel=\"nofollow noreferrer\">source</a>):</p>\n\n<pre><code>function preg_quote (str, delimiter) {\n // discuss at: https://locutus.io/php/preg_quote/\n // original by: booeyOH\n // improved by: Ates Goral (https://magnetiq.com)\n // improved by: Kevin van Zonneveld (https://kvz.io)\n // improved by: Brett Zamir (https://brett-zamir.me)\n // bugfixed by: Onno Marsman (https://twitter.com/onnomarsman)\n // example 1: preg_quote(\"$40\")\n // returns 1: '\\\\$40'\n // example 2: preg_quote(\"*RRRING* Hello?\")\n // returns 2: '\\\\*RRRING\\\\* Hello\\\\?'\n // example 3: preg_quote(\"\\\\.+*?[^]$(){}=!<>|:\")\n // returns 3: '\\\\\\\\\\\\.\\\\+\\\\*\\\\?\\\\[\\\\^\\\\]\\\\$\\\\(\\\\)\\\\{\\\\}\\\\=\\\\!\\\\<\\\\>\\\\|\\\\:'\n\n return (str + '')\n .replace(new RegExp('[.\\\\\\\\+*?\\\\[\\\\^\\\\]$(){}=!<>|:\\\\' + (delimiter || '') + '-]', 'g'), '\\\\$&')\n}\n</code></pre>\n\n<p>So you could do the following:</p>\n\n<pre><code>function highlight(str, search) {\n return str.replace(new RegExp(\"(\" + preg_quote(search) + \")\", 'gi'), \"<b>$1</b>\");\n}\n</code></pre>\n"
},
{
"answer_id": 280811,
"author": "Erik Hesselink",
"author_id": 8071,
"author_profile": "https://Stackoverflow.com/users/8071",
"pm_score": 0,
"selected": false,
"text": "<p>Why not just create a new regex on each call to your function? You can use:</p>\n\n<pre><code>new Regex([pat], [flags])\n</code></pre>\n\n<p>where [pat] is a string for the pattern, and [flags] are the flags.</p>\n"
},
{
"answer_id": 280824,
"author": "tvanfosson",
"author_id": 12950,
"author_profile": "https://Stackoverflow.com/users/12950",
"pm_score": 6,
"selected": false,
"text": "<pre><code>function highlightWords( line, word )\n{\n var regex = new RegExp( '(' + word + ')', 'gi' );\n return line.replace( regex, \"<b>$1</b>\" );\n}\n</code></pre>\n"
},
{
"answer_id": 280837,
"author": "bobince",
"author_id": 18936,
"author_profile": "https://Stackoverflow.com/users/18936",
"pm_score": 3,
"selected": false,
"text": "<p>Regular expressions are fine as long as keywords are really words, you can just use a RegExp constructor instead of a literal to create one from a variable:</p>\n\n<pre><code>var re= new RegExp('('+word+')', 'gi');\nreturn s.replace(re, '<b>$1</b>');\n</code></pre>\n\n<p>The difficulty arises if ‘keywords’ can have punctuation in, as punctuation tends to have special meaning in regexps. Unfortunately unlike most other languages/libraries with regexp support, there is no standard function to escape punctation for regexps in JavaScript.</p>\n\n<p>And you can't be totally sure exactly what characters need escaping because not every browser's implementation of regexp is guaranteed to be exactly the same. (In particular, newer browsers may add new functionality.) And backslash-escaping characters that are not special is not guaranteed to still work, although in practice it does.</p>\n\n<p>So about the best you can do is one of:</p>\n\n<ul>\n<li>attempting to catch each special character in common browser use today [add: see Sebastian's recipe]</li>\n<li>backslash-escape all non-alphanumerics. care: \\W will also match non-ASCII Unicode characters, which you don't really want.</li>\n<li>just ensure that there are no non-alphanumerics in the keyword before searching</li>\n</ul>\n\n<p>If you are using this to highlight words in HTML which already has markup in, though, you've got trouble. Your ‘word’ might appear in an element name or attribute value, in which case attempting to wrap a < b> around it will cause brokenness. In more complicated scenarios possibly even an HTML-injection to XSS security hole. If you have to cope with markup you will need a more complicated approach, splitting out ‘< ... >’ markup before attempting to process each stretch of text on its own.</p>\n"
},
{
"answer_id": 280970,
"author": "Tomalak",
"author_id": 18771,
"author_profile": "https://Stackoverflow.com/users/18771",
"pm_score": 4,
"selected": false,
"text": "<p>You can enhance the RegExp object with a function that does special character escaping for you:</p>\n\n<pre><code>RegExp.escape = function(str) \n{\n var specials = /[.*+?|()\\[\\]{}\\\\$^]/g; // .*+?|()[]{}\\$^\n return str.replace(specials, \"\\\\$&\");\n}\n</code></pre>\n\n<p>Then you would be able to use what the others suggested without any worries:</p>\n\n<pre><code>function highlightWordsNoCase(line, word)\n{\n var regex = new RegExp(\"(\" + RegExp.escape(word) + \")\", \"gi\");\n return line.replace(regex, \"<b>$1</b>\");\n}\n</code></pre>\n"
},
{
"answer_id": 12431195,
"author": "GitCarter",
"author_id": 892598,
"author_profile": "https://Stackoverflow.com/users/892598",
"pm_score": 3,
"selected": false,
"text": "<p>What about something like this:</p>\n\n<pre><code>if(typeof String.prototype.highlight !== 'function') {\n String.prototype.highlight = function(match, spanClass) {\n var pattern = new RegExp( match, \"gi\" );\n replacement = \"<span class='\" + spanClass + \"'>$&</span>\";\n\n return this.replace(pattern, replacement);\n }\n}\n</code></pre>\n\n<p>This could then be called like so:</p>\n\n<pre><code>var result = \"The Quick Brown Fox Jumped Over The Lazy Brown Dog\".highlight(\"brown\",\"text-highlight\");\n</code></pre>\n"
},
{
"answer_id": 42215678,
"author": "exebook",
"author_id": 1968972,
"author_profile": "https://Stackoverflow.com/users/1968972",
"pm_score": 2,
"selected": false,
"text": "<p>For those poor with disregexia or regexophobia:</p>\n\n<p><div class=\"snippet\" data-lang=\"js\" data-hide=\"false\" data-console=\"true\" data-babel=\"false\">\r\n<div class=\"snippet-code\">\r\n<pre class=\"snippet-code-js lang-js prettyprint-override\"><code>function replacei(str, sub, f){\r\n let A = str.toLowerCase().split(sub.toLowerCase());\r\n let B = [];\r\n let x = 0;\r\n for (let i = 0; i < A.length; i++) {\r\n let n = A[i].length;\r\n B.push(str.substr(x, n));\r\n if (i < A.length-1)\r\n B.push(f(str.substr(x + n, sub.length)));\r\n x += n + sub.length;\r\n }\r\n return B.join('');\r\n}\r\n\r\ns = 'Foo and FOO (and foo) are all -- Foo.'\r\nt = replacei(s, 'Foo', sub=>'<'+sub+'>')\r\nconsole.log(t)</code></pre>\r\n</div>\r\n</div>\r\n</p>\n\n<p>Output:</p>\n\n<pre><code><Foo> and <FOO> (and <foo>) are all -- <Foo>.\n</code></pre>\n"
}
] |
2008/11/11
|
[
"https://Stackoverflow.com/questions/280793",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] |
I need to highlight, case insensitively, given keywords in a JavaScript string.
For example:
* `highlight("foobar Foo bar FOO", "foo")` should return `"<b>foo</b>bar <b>Foo</b> bar <b>FOO</b>"`
I need the code to work for any keyword, and therefore using a hardcoded regular expression like `/foo/i` is not a sufficient solution.
What is the easiest way to do this?
(This an instance of a more general problem detailed in the title, but I feel that it's best to tackle with a concrete, useful example.)
|
You *can* use regular expressions if you prepare the search string. In PHP e.g. there is a function preg\_quote, which replaces all regex-chars in a string with their escaped versions.
Here is such a function for javascript ([source](https://locutus.io/php/pcre/preg_quote/)):
```
function preg_quote (str, delimiter) {
// discuss at: https://locutus.io/php/preg_quote/
// original by: booeyOH
// improved by: Ates Goral (https://magnetiq.com)
// improved by: Kevin van Zonneveld (https://kvz.io)
// improved by: Brett Zamir (https://brett-zamir.me)
// bugfixed by: Onno Marsman (https://twitter.com/onnomarsman)
// example 1: preg_quote("$40")
// returns 1: '\\$40'
// example 2: preg_quote("*RRRING* Hello?")
// returns 2: '\\*RRRING\\* Hello\\?'
// example 3: preg_quote("\\.+*?[^]$(){}=!<>|:")
// returns 3: '\\\\\\.\\+\\*\\?\\[\\^\\]\\$\\(\\)\\{\\}\\=\\!\\<\\>\\|\\:'
return (str + '')
.replace(new RegExp('[.\\\\+*?\\[\\^\\]$(){}=!<>|:\\' + (delimiter || '') + '-]', 'g'), '\\$&')
}
```
So you could do the following:
```
function highlight(str, search) {
return str.replace(new RegExp("(" + preg_quote(search) + ")", 'gi'), "<b>$1</b>");
}
```
|
280,797 |
<p>When you use the POISSON function in Excel (or in OpenOffice Calc), it takes two arguments:</p>
<ul>
<li>an integer</li>
<li>an 'average' number</li>
</ul>
<p>and returns a float.</p>
<p>In Python (I tried RandomArray and NumPy) it returns an array of random poisson numbers.
What I really want is the percentage that this event will occur (it is a constant number and the array has every time different numbers - so is it an average?).</p>
<p>for example:</p>
<pre><code>print poisson(2.6,6)
</code></pre>
<p>returns <code>[1 3 3 0 1 3]</code> (and every time I run it, it's different).</p>
<p>The number I get from calc/excel is 3.19 (<code>POISSON(6,2.16,0)*100</code>).</p>
<p>Am I using the python's poisson wrong (no pun!) or am I missing something?</p>
|
[
{
"answer_id": 280831,
"author": "unwind",
"author_id": 28169,
"author_profile": "https://Stackoverflow.com/users/28169",
"pm_score": 1,
"selected": false,
"text": "<p><a href=\"http://numpy.sourceforge.net/numdoc/HTML/numdoc.htm#pgfId-305426\" rel=\"nofollow noreferrer\">This page</a> explains why you get an array, and the meaning of the numbers in it, at least.</p>\n"
},
{
"answer_id": 280843,
"author": "Alex Coventry",
"author_id": 1941213,
"author_profile": "https://Stackoverflow.com/users/1941213",
"pm_score": 5,
"selected": false,
"text": "<p><code>scipy</code> has what you want</p>\n\n<pre><code>>>> scipy.stats.distributions\n<module 'scipy.stats.distributions' from '/home/coventry/lib/python2.5/site-packages/scipy/stats/distributions.pyc'>\n>>> scipy.stats.distributions.poisson.pmf(6, 2.6)\narray(0.031867055625524499)\n</code></pre>\n\n<p>It's worth noting that it's pretty easy to calculate by hand, <a href=\"http://www.scipy.org/doc/api_docs/SciPy.stats.distributions.html#poisson\" rel=\"noreferrer\">too</a>.</p>\n"
},
{
"answer_id": 280862,
"author": "Ned Batchelder",
"author_id": 14343,
"author_profile": "https://Stackoverflow.com/users/14343",
"pm_score": 5,
"selected": true,
"text": "<p>It is easy to do by hand, but you can overflow doing it that way. You can do the exponent and factorial in a loop to avoid the overflow:</p>\n\n<pre><code>def poisson_probability(actual, mean):\n # naive: math.exp(-mean) * mean**actual / factorial(actual)\n\n # iterative, to keep the components from getting too large or small:\n p = math.exp(-mean)\n for i in xrange(actual):\n p *= mean\n p /= i+1\n return p\n</code></pre>\n"
}
] |
2008/11/11
|
[
"https://Stackoverflow.com/questions/280797",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] |
When you use the POISSON function in Excel (or in OpenOffice Calc), it takes two arguments:
* an integer
* an 'average' number
and returns a float.
In Python (I tried RandomArray and NumPy) it returns an array of random poisson numbers.
What I really want is the percentage that this event will occur (it is a constant number and the array has every time different numbers - so is it an average?).
for example:
```
print poisson(2.6,6)
```
returns `[1 3 3 0 1 3]` (and every time I run it, it's different).
The number I get from calc/excel is 3.19 (`POISSON(6,2.16,0)*100`).
Am I using the python's poisson wrong (no pun!) or am I missing something?
|
It is easy to do by hand, but you can overflow doing it that way. You can do the exponent and factorial in a loop to avoid the overflow:
```
def poisson_probability(actual, mean):
# naive: math.exp(-mean) * mean**actual / factorial(actual)
# iterative, to keep the components from getting too large or small:
p = math.exp(-mean)
for i in xrange(actual):
p *= mean
p /= i+1
return p
```
|
280,798 |
<p>I'm trying to make a class that will execute any one of a number of stored procedures with any amount of variables</p>
<p>Im using php and mysqli</p>
<ul>
<li>My class enumerates an array and constructs a string based on the number of elements if any</li>
<li>giving something like this <code>CALL spTestLogin(?,?)</code> for example</li>
<li><p>I now need to bind the input from my array using somethin like this:</p>
<p>$stmt->bind_param($this->paramTypes,$this->paramValues);//paramValues is my array</p></li>
</ul>
<p>Then if that works I can work on getting my results</p>
<p>Any ideas</p>
|
[
{
"answer_id": 280829,
"author": "Stefan Gehrig",
"author_id": 11354,
"author_profile": "https://Stackoverflow.com/users/11354",
"pm_score": 2,
"selected": false,
"text": "<p>You have to do something like this:</p>\n\n<pre><code>$params=array_merge(\n array($this->paramTypes), \n $this->paramValues\n);\ncall_user_func_array(array($stmt, 'bind_param'), $params);\n</code></pre>\n\n<p>given that <code>$this->paramTypes</code> is a string in the format required by <code>mysqli_stmt::bind_param</code> - if not, you have to create this <code>string</code> parameter first.</p>\n\n<p>I don't know if <code>out</code> or <code>inout</code> parameters do work in this case.</p>\n"
},
{
"answer_id": 280856,
"author": "Tom Haigh",
"author_id": 22224,
"author_profile": "https://Stackoverflow.com/users/22224",
"pm_score": 2,
"selected": false,
"text": "<p><code>mysqli_stmt::bind_param()</code> will take a variable number of arguments</p>\n\n<p>Assuming <code>$this->paramTypes</code> is also an array holding the correct type character for each variable (one of 'i', 'd', 's', 'b'), you could do something like</p>\n\n<pre><code>$params = $this->paramValues;\narray_unshift($params, implode($this->paramTypes));\ncall_user_func_array( array( $stmt, 'bind_param' ), $params);\n</code></pre>\n\n<p>Essentially you create an array of the parameters you would normally pass to bind_param(), and then make the call using <code>call_user_func_array()</code></p>\n\n<p>There may be a much better way of doing this</p>\n\n<p><strong>Edit</strong>: just realised I was beaten to it while writing this, I'll leave this answer here for now in case it is of interest</p>\n"
}
] |
2008/11/11
|
[
"https://Stackoverflow.com/questions/280798",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11394/"
] |
I'm trying to make a class that will execute any one of a number of stored procedures with any amount of variables
Im using php and mysqli
* My class enumerates an array and constructs a string based on the number of elements if any
* giving something like this `CALL spTestLogin(?,?)` for example
* I now need to bind the input from my array using somethin like this:
$stmt->bind\_param($this->paramTypes,$this->paramValues);//paramValues is my array
Then if that works I can work on getting my results
Any ideas
|
You have to do something like this:
```
$params=array_merge(
array($this->paramTypes),
$this->paramValues
);
call_user_func_array(array($stmt, 'bind_param'), $params);
```
given that `$this->paramTypes` is a string in the format required by `mysqli_stmt::bind_param` - if not, you have to create this `string` parameter first.
I don't know if `out` or `inout` parameters do work in this case.
|
280,801 |
<blockquote>
<p><strong>Possible Duplicate:</strong><br>
<a href="https://stackoverflow.com/questions/16991/what-ruby-ide-do-you-prefer">What Ruby IDE do you prefer?</a> </p>
</blockquote>
<p>I'm making a <strong>simple</strong> script using ruby on a Windows 2003 Server.
My questions are:</p>
<ul>
<li>How can I connect to a database through ODBC? I will be connecting to both <strong>Sybase on Solaris</strong> and <strong>MSSQL Server</strong>.</li>
<li>How can I send emails through an Exchange Server 2003?</li>
</ul>
<hr>
<h2>Update</h2>
<ul>
<li>What's the best simple IDE for Ruby scripting? I currently use SciTE (which comes with Ruby)</li>
</ul>
|
[
{
"answer_id": 280857,
"author": "Tomalak",
"author_id": 18771,
"author_profile": "https://Stackoverflow.com/users/18771",
"pm_score": 2,
"selected": false,
"text": "<p>There is an ODBC package for the <a href=\"http://ruby-dbi.rubyforge.org/\" rel=\"nofollow noreferrer\">Ruby DBI module</a> available, or you can try to use the <a href=\"http://www.ch-werner.de/rubyodbc/\" rel=\"nofollow noreferrer\">ODBC binding for Ruby</a>, which also includes a Win32 binary.</p>\n\n<p>Here an example that uses RDI (stolen from <a href=\"http://www.ruby-forum.com/topic/64065\" rel=\"nofollow noreferrer\">here</a>):</p>\n\n<pre><code>require 'DBI'\n\n# make an ODBC connection\nconn = DBI.connect('DBI:ODBC:datasource','your_username','your_password')\n\n# returns a list of the table names from your database\nconn.tables\n\n# returns an array with the resultset from your query\nrs = conn.select_all('SELECT * FROM TheTable')\n</code></pre>\n\n<p><em>(ODBC datasources can be defined using the ODBC Administrator available via Control Panel/Administrative Tools.)</em></p>\n\n<p>For e-mailing I would suggest you simply use the <a href=\"http://www.ruby-doc.org/stdlib/libdoc/net/smtp/rdoc/index.html\" rel=\"nofollow noreferrer\">standard mailing capabilities</a> of Ruby and connect to your Exchange Server through SMTP.</p>\n\n<p>I cannot recommend you a Ruby IDE, though, as I do my text-editing with VIM. :-) Other people might be able to give you a hint on that.</p>\n"
},
{
"answer_id": 280869,
"author": "epochwolf",
"author_id": 16204,
"author_profile": "https://Stackoverflow.com/users/16204",
"pm_score": 1,
"selected": false,
"text": "<p>For a Ruby IDE, try NetBeans. </p>\n"
},
{
"answer_id": 285092,
"author": "Jonke",
"author_id": 15638,
"author_profile": "https://Stackoverflow.com/users/15638",
"pm_score": 1,
"selected": false,
"text": "<p>For simple but powerful use <a href=\"http://rubyonwindows.blogspot.com/2007/03/ruby-ado-and-sqlserver.html\" rel=\"nofollow noreferrer\">ado and ruby on windows</a>.This is a really good example.</p>\n"
},
{
"answer_id": 285569,
"author": "Austin Ziegler",
"author_id": 36378,
"author_profile": "https://Stackoverflow.com/users/36378",
"pm_score": 1,
"selected": false,
"text": "<p>Be warned that the ODBC drivers included with the One-Click Installer for Ruby don't seem to be Unicode aware. (Accessing a SQL Server database from Unix, I used FreeTDS to convert UTF-16 to UTF-8 prior to getting it from UnixODBC.) I haven't been able to make a similar conversion in Windows.</p>\n"
}
] |
2008/11/11
|
[
"https://Stackoverflow.com/questions/280801",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/15884/"
] |
>
> **Possible Duplicate:**
>
> [What Ruby IDE do you prefer?](https://stackoverflow.com/questions/16991/what-ruby-ide-do-you-prefer)
>
>
>
I'm making a **simple** script using ruby on a Windows 2003 Server.
My questions are:
* How can I connect to a database through ODBC? I will be connecting to both **Sybase on Solaris** and **MSSQL Server**.
* How can I send emails through an Exchange Server 2003?
---
Update
------
* What's the best simple IDE for Ruby scripting? I currently use SciTE (which comes with Ruby)
|
There is an ODBC package for the [Ruby DBI module](http://ruby-dbi.rubyforge.org/) available, or you can try to use the [ODBC binding for Ruby](http://www.ch-werner.de/rubyodbc/), which also includes a Win32 binary.
Here an example that uses RDI (stolen from [here](http://www.ruby-forum.com/topic/64065)):
```
require 'DBI'
# make an ODBC connection
conn = DBI.connect('DBI:ODBC:datasource','your_username','your_password')
# returns a list of the table names from your database
conn.tables
# returns an array with the resultset from your query
rs = conn.select_all('SELECT * FROM TheTable')
```
*(ODBC datasources can be defined using the ODBC Administrator available via Control Panel/Administrative Tools.)*
For e-mailing I would suggest you simply use the [standard mailing capabilities](http://www.ruby-doc.org/stdlib/libdoc/net/smtp/rdoc/index.html) of Ruby and connect to your Exchange Server through SMTP.
I cannot recommend you a Ruby IDE, though, as I do my text-editing with VIM. :-) Other people might be able to give you a hint on that.
|
280,818 |
<p>I'm developing a small utility application that needs to detect whether another one has one of its MDI child windows open (it's an off-the-shelf Win32 business application over which I have neither source code nor control).
From my app, I would like to be able to poll or detect when a particular MDI Child window is open.</p>
<p>In .Net, it's easy to iterate over running processes, but I haven't found an easy way to iterate through the (sub)windows and controls of a given Win32 process from .Net.</p>
<p>Any ideas?</p>
<p><strong>Update</strong><br>
Thanks for the answers they got me on the right path.<br>
I found an <a href="http://www.vbaccelerator.com/home/NET/Code/Libraries/Windows/Enumerating_Windows/article.asp" rel="nofollow noreferrer">article with a test project</a> that uses both <code>EnumWindows</code>and <code>EnumChidWindows</code> and other API calls to get extended information on controls.</p>
|
[
{
"answer_id": 280866,
"author": "Juanma",
"author_id": 3730,
"author_profile": "https://Stackoverflow.com/users/3730",
"pm_score": 1,
"selected": false,
"text": "<p>You can use P/Invoke to access EnumWindows and EnumChidWindows to itereate through the subwindows/controls of any window.</p>\n"
},
{
"answer_id": 280878,
"author": "Robert Vuković",
"author_id": 438025,
"author_profile": "https://Stackoverflow.com/users/438025",
"pm_score": 4,
"selected": true,
"text": "<p>You must use native Win32 API.</p>\n\n<p><a href=\"http://www.pinvoke.net/default.aspx/user32/EnumChildWindows.html\" rel=\"noreferrer\">EnumChildWindows (user32)</a></p>\n\n<p><code></p>\n\n<pre><code>[DllImport(\"user32\")]\n\n[return: MarshalAs(UnmanagedType.Bool)]\npublic static extern bool EnumChildWindows(IntPtr window, EnumWindowProc callback, IntPtr i);\n\n/// <summary>\n/// Returns a list of child windows\n/// </summary>\n/// <param name=\"parent\">Parent of the windows to return</param>\n/// <returns>List of child windows</returns>\npublic static List<IntPtr> GetChildWindows(IntPtr parent)\n{\nList<IntPtr> result = new List<IntPtr>();\nGCHandle listHandle = GCHandle.Alloc(result);\ntry\n{\n EnumWindowProc childProc = new EnumWindowProc(EnumWindow);\n EnumChildWindows(parent, childProc, GCHandle.ToIntPtr(listHandle));\n}\nfinally\n{\n if (listHandle.IsAllocated)\n listHandle.Free();\n}\nreturn result;\n}\n\n/// <summary>\n/// Callback method to be used when enumerating windows.\n/// </summary>\n/// <param name=\"handle\">Handle of the next window</param>\n/// <param name=\"pointer\">Pointer to a GCHandle that holds a reference to the list to fill</param>\n/// <returns>True to continue the enumeration, false to bail</returns>\nprivate static bool EnumWindow(IntPtr handle, IntPtr pointer)\n{\nGCHandle gch = GCHandle.FromIntPtr(pointer);\nList<IntPtr> list = gch.Target as List<IntPtr>;\nif (list == null)\n{\n throw new InvalidCastException(\"GCHandle Target could not be cast as List<IntPtr>\");\n}\nlist.Add(handle);\n// You can modify this to check to see if you want to cancel the operation, then return a null here\nreturn true;\n}\n\n/// <summary>\n/// Delegate for the EnumChildWindows method\n/// </summary>\n/// <param name=\"hWnd\">Window handle</param>\n/// <param name=\"parameter\">Caller-defined variable; we use it for a pointer to our list</param>\n/// <returns>True to continue enumerating, false to bail.</returns>\npublic delegate bool EnumWindowProc(IntPtr hWnd, IntPtr parameter);\n</code></pre>\n\n<p></code></p>\n"
},
{
"answer_id": 43541456,
"author": "Peter Talbot",
"author_id": 7901147,
"author_profile": "https://Stackoverflow.com/users/7901147",
"pm_score": 2,
"selected": false,
"text": "<p>This is an old post, but a common problem. I have a similar situation where I'm trying to control the behaviour of an off-the-shelf software application. I mostly succeeded by using Kixstart, but came up against the limitations of using SETFOCUS and SENDKEYS because at certain points the off-the-shelf software is displaying windows where WindowTitle is blank. So I developed a little utility which identifies visible Windows by their ProcessName as well as WindowTitle (or lack thereof) and sends a message to close a window which matches.</p>\n\n<p>Most of the examples I've seen of EnumWindows callback functions ignore windows which aren't visible or which have blank titles, whereas this code enumerates all windows including invisible ones.</p>\n\n<p>This code is Visual Basic and uses a configuration file in the format</p>\n\n<pre><code>PRC=process name\nWIN=window title\n</code></pre>\n\n<p>Hope this is useful to somebody</p>\n\n<pre><code>Imports System\nImports System.IO\nImports System.Runtime.InteropServices\nImports System.Text\nModule Module1\n Dim hShellWindow As IntPtr = GetShellWindow()\n Dim dictWindows As New Dictionary(Of IntPtr, String)\n Dim dictChildWindows As New Dictionary(Of IntPtr, String)\n Dim currentProcessID As Integer = -1\n <DllImport(\"USER32.DLL\")>\n Function GetShellWindow() As IntPtr\n End Function\n <DllImport(\"USER32.DLL\")>\n Function GetForegroundWindow() As IntPtr\n End Function\n <DllImport(\"USER32.DLL\")>\n Function GetWindowText(ByVal hWnd As IntPtr, ByVal lpString As StringBuilder, ByVal nMaxCount As Integer) As Integer\n End Function\n <DllImport(\"USER32.DLL\")>\n Function GetWindowTextLength(ByVal hWnd As IntPtr) As Integer\n End Function\n <DllImport(\"user32.dll\", SetLastError:=True)>\n Function GetWindowThreadProcessId(ByVal hWnd As IntPtr, <Out()> ByRef lpdwProcessId As UInt32) As UInt32\n End Function\n <DllImport(\"USER32.DLL\")>\n Function IsWindowVisible(ByVal hWnd As IntPtr) As Boolean\n End Function\n Delegate Function EnumWindowsProc(ByVal hWnd As IntPtr, ByVal lParam As Integer) As Boolean\n <DllImport(\"USER32.DLL\")>\n Function EnumWindows(ByVal enumFunc As EnumWindowsProc, ByVal lParam As Integer) As Boolean\n End Function\n <DllImport(\"USER32.DLL\")>\n Function EnumChildWindows(ByVal hWndParent As System.IntPtr, ByVal lpEnumFunc As EnumWindowsProc, ByVal lParam As Integer) As Boolean\n End Function\n <DllImport(\"USER32.DLL\")>\n Function PostMessage(ByVal hwnd As Integer, ByVal message As UInteger, ByVal wParam As Integer, ByVal lParam As Integer) As Boolean\n End Function\n <DllImport(\"USER32.DLL\")>\n Function SendMessage(ByVal hWnd As IntPtr, ByVal Msg As UInteger, ByVal wParam As IntPtr, ByVal lParam As IntPtr) As IntPtr\n End Function\n\n Function enumWindowsInternal(ByVal hWnd As IntPtr, ByVal lParam As Integer) As Boolean\n Dim a As String = \"\"\n Dim length As Integer = GetWindowTextLength(hWnd)\n If (length > 0) Then\n Dim stringBuilder As New System.Text.StringBuilder(length)\n GetWindowText(hWnd, stringBuilder, (length + 1))\n a = stringBuilder.ToString\n End If\n dictWindows.Add(hWnd, a)\n EnumChildWindows(hWnd, AddressOf enumChildWindowsInternal, 0)\n Return True\n End Function\n Function enumChildWindowsInternal(ByVal hWnd As IntPtr, ByVal lParam As Integer) As Boolean\n Dim a As String = \"\"\n Dim length As Integer = GetWindowTextLength(hWnd)\n If (length > 0) Then\n Dim stringBuilder As New System.Text.StringBuilder(length)\n GetWindowText(hWnd, stringBuilder, (length + 1))\n a = stringBuilder.ToString\n End If\n dictChildWindows.Add(hWnd, a)\n Return True\n End Function\n Function cleanstring(ByVal a As String) As String\n Dim c As String = \"\"\n Dim b As String = \"\"\n Dim i As Integer\n Do While i < Len(a)\n i = i + 1\n c = Mid(a, i, 1)\n If Asc(c) > 31 And Asc(c) < 128 Then\n b = b & c\n End If\n Loop\n cleanstring = b\n End Function\n Sub Main()\n '\n '\n Dim a As String = \"\"\n Dim b As String = \"\"\n Dim c As String = \"\"\n Dim d As String = \"\"\n Dim f As String = \"C:\\FIS5\\WK.txt\"\n Dim a1 As String = \"\"\n Dim a2 As String = \"\"\n Dim p As Process\n Dim windows As IDictionary(Of IntPtr, String)\n Dim kvp As KeyValuePair(Of IntPtr, String)\n Dim windowPid As UInt32\n Dim hWnd As IntPtr\n Dim fhWnd As IntPtr\n Dim WM_CLOSE As UInteger = &H12\n Dim WM_SYSCOMMAND As UInteger = &H112\n Dim SC_CLOSE As UInteger = &HF060\n Dim x As Boolean = True\n Dim y As IntPtr\n Dim processes As Process() = Process.GetProcesses\n Dim params As String = File.ReadAllText(\"C:\\FIS5\\WindowKiller.txt\")\n Dim words As String() = params.Split(vbCrLf)\n Dim word As String\n Dim myprocname As String = \"\"\n Dim mywinname As String = \"\"\n Dim i As Integer = 0\n Dim v1 As Integer = 0\n For Each word In words\n word = Trim(cleanstring(word)).ToUpper\n i = InStr(word, \"=\", CompareMethod.Text)\n ' a = a & word & \" \" & i.ToString & vbCrLf\n If i = 4 And 4 < Len(word) Then\n If Left(word, 4) = \"PRC=\" Then\n myprocname = Mid(word, 5)\n End If\n If Left(word, 4) = \"WIN=\" Then\n mywinname = Mid(word, 5)\n End If\n End If\n Next\n a = a & params & vbCrLf & \"procname=\" & myprocname & \", winname=\" & mywinname & vbCrLf\n fhWnd = GetForegroundWindow()\n dictWindows.Clear()\n dictChildWindows.Clear()\n EnumWindows(AddressOf enumWindowsInternal, 0)\n windows = dictChildWindows\n For Each kvp In windows\n hWnd = kvp.Key\n GetWindowThreadProcessId(hWnd, windowPid)\n b = \"\"\n c = \"\"\n For Each p In processes\n If p.Id = windowPid Then\n b = p.ProcessName\n c = p.Id.ToString\n End If\n Next\n d = \"hidden\"\n If IsWindowVisible(hWnd) Then\n d = \"visible\"\n End If\n If hWnd = fhWnd Then\n d = d & \", foreground\"\n End If\n a = a & \"Child window=\" & hWnd.ToString & \", processname=\" & b & \", procid=\" & c & \", windowname=\" & kvp.Value & \", \" & d & vbCrLf\n Next\n windows = dictWindows\n For Each kvp In windows\n v1 = 0\n hWnd = kvp.Key\n GetWindowThreadProcessId(hWnd, windowPid)\n b = \"\"\n c = \"\"\n For Each p In processes\n If p.Id = windowPid Then\n b = p.ProcessName\n c = p.Id.ToString\n End If\n Next\n d = \"hidden\"\n If IsWindowVisible(hWnd) Then\n d = \"visible\"\n v1 = 1\n End If\n If hWnd = fhWnd Then\n d = d & \", foreground\"\n End If\n word = kvp.Value\n a = a & \"Window=\" & hWnd.ToString & \", processname=\" & b & \", procid=\" & c & \", windowname=\" & word & \", \" & d & vbCrLf\n If Trim(cleanstring(b).ToUpper) = myprocname Then\n a = a & \"procname match\" & vbCrLf\n If Trim(cleanstring(word)).ToUpper = mywinname And v1 <> 0 Then\n a = a & \"ATTEMPTING To CLOSE: \" & b & \" # \" & word & \" # \" & c & vbCrLf\n ' x = PostMessage(hWnd, WM_CLOSE, 0, 0)\n 'If x Then\n 'a = a & \"PostMessage returned True\" & vbCrLf\n 'Else\n 'a = a & \"PostMessage returned False\" & vbCrLf\n 'End If\n y = SendMessage(hWnd, WM_SYSCOMMAND, SC_CLOSE, 0)\n a = a & \"SendMessage returned \" & y.ToString & vbCrLf\n End If\n End If\n Next\n My.Computer.FileSystem.WriteAllText(f, a, False)\n End Sub\nEnd Module\n</code></pre>\n"
}
] |
2008/11/11
|
[
"https://Stackoverflow.com/questions/280818",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3811/"
] |
I'm developing a small utility application that needs to detect whether another one has one of its MDI child windows open (it's an off-the-shelf Win32 business application over which I have neither source code nor control).
From my app, I would like to be able to poll or detect when a particular MDI Child window is open.
In .Net, it's easy to iterate over running processes, but I haven't found an easy way to iterate through the (sub)windows and controls of a given Win32 process from .Net.
Any ideas?
**Update**
Thanks for the answers they got me on the right path.
I found an [article with a test project](http://www.vbaccelerator.com/home/NET/Code/Libraries/Windows/Enumerating_Windows/article.asp) that uses both `EnumWindows`and `EnumChidWindows` and other API calls to get extended information on controls.
|
You must use native Win32 API.
[EnumChildWindows (user32)](http://www.pinvoke.net/default.aspx/user32/EnumChildWindows.html)
```
[DllImport("user32")]
[return: MarshalAs(UnmanagedType.Bool)]
public static extern bool EnumChildWindows(IntPtr window, EnumWindowProc callback, IntPtr i);
/// <summary>
/// Returns a list of child windows
/// </summary>
/// <param name="parent">Parent of the windows to return</param>
/// <returns>List of child windows</returns>
public static List<IntPtr> GetChildWindows(IntPtr parent)
{
List<IntPtr> result = new List<IntPtr>();
GCHandle listHandle = GCHandle.Alloc(result);
try
{
EnumWindowProc childProc = new EnumWindowProc(EnumWindow);
EnumChildWindows(parent, childProc, GCHandle.ToIntPtr(listHandle));
}
finally
{
if (listHandle.IsAllocated)
listHandle.Free();
}
return result;
}
/// <summary>
/// Callback method to be used when enumerating windows.
/// </summary>
/// <param name="handle">Handle of the next window</param>
/// <param name="pointer">Pointer to a GCHandle that holds a reference to the list to fill</param>
/// <returns>True to continue the enumeration, false to bail</returns>
private static bool EnumWindow(IntPtr handle, IntPtr pointer)
{
GCHandle gch = GCHandle.FromIntPtr(pointer);
List<IntPtr> list = gch.Target as List<IntPtr>;
if (list == null)
{
throw new InvalidCastException("GCHandle Target could not be cast as List<IntPtr>");
}
list.Add(handle);
// You can modify this to check to see if you want to cancel the operation, then return a null here
return true;
}
/// <summary>
/// Delegate for the EnumChildWindows method
/// </summary>
/// <param name="hWnd">Window handle</param>
/// <param name="parameter">Caller-defined variable; we use it for a pointer to our list</param>
/// <returns>True to continue enumerating, false to bail.</returns>
public delegate bool EnumWindowProc(IntPtr hWnd, IntPtr parameter);
```
|
280,819 |
<p>My WCF service involves the sending of a dataset (in csv format) data between client and service. This dataset must be encrypted so that the data cannot be intercepted. I'm using wshttpbinding and trying to encrypt the message by using the following settings in web.config:</p>
<pre><code><wsHttpBinding>
<binding name="wsHttp">
<reliableSession enabled="true" />
<security mode="Message">
<message clientCredentialType="UserName" algorithmSuite="TripleDes" />
</security>
</binding>
</wsHttpBinding>
</code></pre>
<p>When I try and generate a client proxy I get a long error messagebox (which cannot be completely read because it goes off the bottom of the screen!). The error message does mention something about a "service certificate not being provided".</p>
<p>How do I encrypt a message? Do I need a certificate? I should mention that this service will be used over the internet from different domains so I'm not sure whether using "Username" security is the best option (?)</p>
<p>Basically I'm confused!</p>
|
[
{
"answer_id": 280890,
"author": "Martin",
"author_id": 1529,
"author_profile": "https://Stackoverflow.com/users/1529",
"pm_score": 3,
"selected": true,
"text": "<p>Yes, your service needs a certificate so that your encryption keys can be exchanged securely. You can create a test service authentication certificate with makecert.exe. See <a href=\"http://web.archive.org/web/20070306040207/http://martinparry.com/cs/blogs/mparry_software/archive/2006/10/30/97.aspx\" rel=\"nofollow noreferrer\">this entry in my blog</a> for the details of that.</p>\n\n<p>You also need to ensure that the account your service is running as is able to read the certificate's private key file. If you're on Windows Vista (or later) the Certificates MMC snap-in allows you to control permissions on that private-key, but for earlier versions of Windows it's a bit harder. I used to use a utility that came with WSE3, but someone else might be able to suggest a more direct way. Unless your service runs as an admin, you will most likely have to adjust these permissions.</p>\n\n<p>Update: like all good things, my blog came to an end. Thanks to makerofthings7 for reminding me. The makecert command you need to generate a service authentication certificate is something like this...</p>\n\n<pre><code>makecert -sr LocalMachine -ss My -pe -n CN=subject-name -eku 1.3.6.1.5.5.7.3.1 -sky exchange\n</code></pre>\n\n<p>...simply replace <em>subject-name</em> with any certificate name that makes sense for your service.</p>\n"
},
{
"answer_id": 280899,
"author": "Sixto Saez",
"author_id": 9711,
"author_profile": "https://Stackoverflow.com/users/9711",
"pm_score": 2,
"selected": false,
"text": "<p>@Martin is right, you need a certificate on the server. <a href=\"http://msdn.microsoft.com/en-us/library/ms731058.aspx\" rel=\"nofollow noreferrer\">This link</a> has a good overview of the communication flow for message based security and has sample code. <a href=\"http://weblogs.asp.net/cibrax/archive/2006/08/08/Creating-X509-Certificates-for-WSE-or-WCF.aspx\" rel=\"nofollow noreferrer\">This link</a> has a good overview of working with certificates.</p>\n\n<p>For your authenication requirements, <a href=\"http://blogs.msdn.com/pedram/archive/2007/10/05/wcf-authentication-custom-username-and-password-validator.aspx\" rel=\"nofollow noreferrer\">this link</a> reviews the various options available. If you're new to WCF, Learning WCF: A Hands-on Guide by Michele Bustamante is a good book and covers message based security.</p>\n"
},
{
"answer_id": 391765,
"author": "ThorDivDev",
"author_id": 12924,
"author_profile": "https://Stackoverflow.com/users/12924",
"pm_score": 1,
"selected": false,
"text": "<p>I am still trying to find the solution this problem. I have it too, but with signing an xml. Still to find the user IIS is running in WinXP Start > Right-Click My Computer > Manage > Services And Applications > Services > IIS Admin > Double click and in the Log on tab it will usually say Local System.</p>\n\n<p>EDIT</p>\n\n<p>OK, this is how I solved my problem. I had a ceritificate that I used this <a href=\"http://www.digwin.com/view/howto-use-makecert-for-trusted-root-certification-authority-and-ssl-certificate-issuance\" rel=\"nofollow noreferrer\">article</a>\nto make the cert. If the project is a ASPWebSite that is saved to your C Folder you may not have issues with this. But if its saved to IIS as an HTTP project then you will have issues. </p>\n\n<p>The way to solve it after weeks of investigationg is not that hard. Microsoft has something called the Web Services Enhancements you will download the lastest but I am using the second one with the lastest service pack. When I installed I enabled everything.</p>\n\n<p>Certificates can be in a physical file but they are usually in the Certificate Management Store to get to it use the tool X509 Certificate tool in WSE 2.0. Here open your certificate by looking for it in the diferent sections until you find it. Then open it and at the bottom there will be a View Private Key, in the security tab add LOCALHOST\\ASPNET . And this should enable your website to read the certificate.</p>\n\n<p>In short what happens is that when you create the public and private keys, althought you may see the private key just fine, it really its send to Timbuktu in the file system and you need to find it to add the ASPNET account for read access. I am reading than in Vista this is much easier but I am using XP.</p>\n"
}
] |
2008/11/11
|
[
"https://Stackoverflow.com/questions/280819",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/445/"
] |
My WCF service involves the sending of a dataset (in csv format) data between client and service. This dataset must be encrypted so that the data cannot be intercepted. I'm using wshttpbinding and trying to encrypt the message by using the following settings in web.config:
```
<wsHttpBinding>
<binding name="wsHttp">
<reliableSession enabled="true" />
<security mode="Message">
<message clientCredentialType="UserName" algorithmSuite="TripleDes" />
</security>
</binding>
</wsHttpBinding>
```
When I try and generate a client proxy I get a long error messagebox (which cannot be completely read because it goes off the bottom of the screen!). The error message does mention something about a "service certificate not being provided".
How do I encrypt a message? Do I need a certificate? I should mention that this service will be used over the internet from different domains so I'm not sure whether using "Username" security is the best option (?)
Basically I'm confused!
|
Yes, your service needs a certificate so that your encryption keys can be exchanged securely. You can create a test service authentication certificate with makecert.exe. See [this entry in my blog](http://web.archive.org/web/20070306040207/http://martinparry.com/cs/blogs/mparry_software/archive/2006/10/30/97.aspx) for the details of that.
You also need to ensure that the account your service is running as is able to read the certificate's private key file. If you're on Windows Vista (or later) the Certificates MMC snap-in allows you to control permissions on that private-key, but for earlier versions of Windows it's a bit harder. I used to use a utility that came with WSE3, but someone else might be able to suggest a more direct way. Unless your service runs as an admin, you will most likely have to adjust these permissions.
Update: like all good things, my blog came to an end. Thanks to makerofthings7 for reminding me. The makecert command you need to generate a service authentication certificate is something like this...
```
makecert -sr LocalMachine -ss My -pe -n CN=subject-name -eku 1.3.6.1.5.5.7.3.1 -sky exchange
```
...simply replace *subject-name* with any certificate name that makes sense for your service.
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.