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
125,094
<p>I have a 2D character array:<br> <code>char nm[MAX1][MAX2] = { "john", "bob", "david" };</code><br> I want to swap two of these elements (without <code>std::swap</code>) by simply writing<br> <code>swapPointers(nm[0], nm[1]);</code><br> where <code>swapPointers</code> looks like this </p> <pre><code>void swapPointers(char *&amp;a, char *&amp;b) { char *temp = a; a = b; b = a; } </code></pre> <p>However, this does not compile (and while adding casts makes it compile, the pointers end up pointing to wrong/weird locations). </p> <p>Can anybody help?<br> Thanks!</p>
[ { "answer_id": 125103, "author": "Ana Betts", "author_id": 5728, "author_profile": "https://Stackoverflow.com/users/5728", "pm_score": 0, "selected": false, "text": "<pre><code>void swapPointers(char** ppa, char** ppb)\n{\n char* ptemp = *ppa;\n *ppb = *ppa;\n *ppa = ptemp;\n}\n...
2008/09/24
[ "https://Stackoverflow.com/questions/125094", "https://Stackoverflow.com", "https://Stackoverflow.com/users/21475/" ]
I have a 2D character array: `char nm[MAX1][MAX2] = { "john", "bob", "david" };` I want to swap two of these elements (without `std::swap`) by simply writing `swapPointers(nm[0], nm[1]);` where `swapPointers` looks like this ``` void swapPointers(char *&a, char *&b) { char *temp = a; a = b; b = a; } ``` However, this does not compile (and while adding casts makes it compile, the pointers end up pointing to wrong/weird locations). Can anybody help? Thanks!
Zan is close, but his problem is that his 'swap' function can take any pointer to characters. This can cause problems if misused. Here is a safer version: ``` void swap(char (&x)[MAX2], char (&y)[MAX2]) { char temp[MAX2]; memcpy(temp, x, MAX2); memcpy(x, y, MAX2); memcpy(y, temp, MAX2); } ``` There is also a misunderstanding on the part of the poster: 'nm' is a 2-dimensional array of characters. There are no pointers. nm[0], nm[2], etc... are also not pointers either -- they are still (1-dimensional) arrays. The fact that 1-dimensional arrays are implicitly convertible to pointers causes this type of confusion among many C and C++ programmers. In order to swap the data in the 2-dimensional array, you have to swap blocks of memory of size MAX2 -- as indicated by both 'swap' functions Zan and I wrote.
125,096
<p>I have an app that has impersonation used throughout. But when a user is logged in as an admin, a few operation require them to write to the server itself. Now if these users do not have rights on the actual server (some don't) it will not let them write. </p> <p>What I want to do is turn off impersonation for just a couple commands.</p> <p>Is there a way to do something like this?</p> <pre><code>using(HostingEnvironment.Impersonate.Off()) //I know this isn't a command, but you get the idea? </code></pre> <p>Thank you.</p>
[ { "answer_id": 125219, "author": "jedatu", "author_id": 2582, "author_profile": "https://Stackoverflow.com/users/2582", "pm_score": 2, "selected": false, "text": "<p>I am not sure if this is the preferred approach but when I wanted to do this I new'd up an instance of a <a href=\"http://...
2008/09/24
[ "https://Stackoverflow.com/questions/125096", "https://Stackoverflow.com", "https://Stackoverflow.com/users/14777/" ]
I have an app that has impersonation used throughout. But when a user is logged in as an admin, a few operation require them to write to the server itself. Now if these users do not have rights on the actual server (some don't) it will not let them write. What I want to do is turn off impersonation for just a couple commands. Is there a way to do something like this? ``` using(HostingEnvironment.Impersonate.Off()) //I know this isn't a command, but you get the idea? ``` Thank you.
Make sure the Application Pool do have the proper rights that you need. Then, when you want to revert to the application pool identity... run the following: ``` private WindowsImpersonationContext context = null; public void RevertToAppPool() { try { if (!WindowsIdentity.GetCurrent().IsSystem) { context = WindowsIdentity.Impersonate(System.IntPtr.Zero); } } catch { } } public void UndoImpersonation() { try { if (context != null) { context.Undo(); } } catch { } } ```
125,099
<p>Anyone know the formula used to control the movement of a simple tank-like vehicle?</p> <p>To 'steer' it, you need to alter the force applied the left and right "wheels". Eg. 1 unit of force on both wheels makes it go forward. -1 units of force on both wheels makes it go backwards. Apply more force to one wheel than the other and it turns.</p> <p>How would you calculate the amount of force needed on both wheels to turn the tank a certain number of degrees either way?</p> <p>Or am I thinking about this in the wrong way?</p> <p>edit: As William Keller mentioned I missed out the speed of the tank. Assume 1 unit of force on both wheels moves the tank forward at 1 unit per second.</p> <p>For anyone who's interested, I just found this thread on gamedev.net: <a href="http://66.102.9.104/search?q=cache:wSn5t58ACJwJ:www.gamedev.net/community/forums/topic.asp%3Ftopic_id%3D407491+tank+track+radius+velocity&amp;hl=en&amp;ct=clnk&amp;cd=1&amp;gl=za&amp;client=firefox-a" rel="nofollow noreferrer">http://66.102.9.104/search?q=cache:wSn5t58ACJwJ:www.gamedev.net/community/forums/topic.asp%3Ftopic_id%3D407491+tank+track+radius+velocity&amp;hl=en&amp;ct=clnk&amp;cd=1&amp;gl=za&amp;client=firefox-a</a></p> <p>Another thread: <a href="http://www.physicsforums.com/showthread.php?t=220317" rel="nofollow noreferrer">http://www.physicsforums.com/showthread.php?t=220317</a></p> <p>It turns out the key to finding the formula was just knowing the correct terminology ("skid steer") :P</p>
[ { "answer_id": 125116, "author": "William Keller", "author_id": 17095, "author_profile": "https://Stackoverflow.com/users/17095", "pm_score": 1, "selected": false, "text": "<p>Well, keep in mind that you're also talking about duration here. You need to find out the forces taking in to ac...
2008/09/24
[ "https://Stackoverflow.com/questions/125099", "https://Stackoverflow.com", "https://Stackoverflow.com/users/9825/" ]
Anyone know the formula used to control the movement of a simple tank-like vehicle? To 'steer' it, you need to alter the force applied the left and right "wheels". Eg. 1 unit of force on both wheels makes it go forward. -1 units of force on both wheels makes it go backwards. Apply more force to one wheel than the other and it turns. How would you calculate the amount of force needed on both wheels to turn the tank a certain number of degrees either way? Or am I thinking about this in the wrong way? edit: As William Keller mentioned I missed out the speed of the tank. Assume 1 unit of force on both wheels moves the tank forward at 1 unit per second. For anyone who's interested, I just found this thread on gamedev.net: <http://66.102.9.104/search?q=cache:wSn5t58ACJwJ:www.gamedev.net/community/forums/topic.asp%3Ftopic_id%3D407491+tank+track+radius+velocity&hl=en&ct=clnk&cd=1&gl=za&client=firefox-a> Another thread: <http://www.physicsforums.com/showthread.php?t=220317> It turns out the key to finding the formula was just knowing the correct terminology ("skid steer") :P
For a skid steered vehicle that is required to turn in radius 'r' at a given speed 'Si' of the Inner Wheel/Track, the Outer track must be driven at speed 'So' : ``` So = Si * ((r+d)/r) ``` **Details:** In Skid Steering, a turn is performed by the outer wheels/track traveling further distance than the inner wheels/track. Furthermore, the extra distance traveled is completed in the same time as the inner track, meaning that the outer wheels/track must run faster. Circle circumference circumscribed by "Inner" track: ``` c1 = 2*PI*r 'r' is radius of circle origin to track/wheel ``` Circle circumference circumscribed by "Outer" track: ``` c2 = 2*PI*(r+d) 'r' is radius of circle origin to inner track/wheel 'd' is the distance between the Inner and Outer wheels/track. ``` Furthermore, c2 = X \* c1, which says that c2 is proportionally bigger than c1 ``` X = c2 / c1 X = 2*PI*(r+d) / 2*PI*r X = (r+d)/r ``` Therefore for a skid steered vehicle that is required to turn in radius 'r' at a given speed 's' of the Inner Wheel/Track, the Outer track must be driven at : ``` So = Si * ((r+d)/r) ``` Where: ``` 'So' = Speed of outer track 'Si' = Speed of inner track 'r' = turn radius from inner track 'd' = distance between vehicle tracks. ********* <---------------- Outer Track **** | **** ** |<--------**----------- 'd' Distance between tracks * *******<-------*---------- Inner Track * *** ^ *** * * * |<-----*------*-------- 'r' Radius of Turn * * | * * * * O * * * * * * * * * * * *** *** * * ******* * ** ** **** **** ********* ```
125,102
<p>Say I have the following string:</p> <pre><code>"I am the most foo h4ck3r ever!!" </code></pre> <p>I'm trying to write a makeSpecial(foo) function where the foo substring would be wrapped in a new span element, resulting in:</p> <pre><code>"I am the most &lt;span class="special"&gt;foo&gt;&lt;/span&gt; h4ck3r ever!!" </code></pre> <p>BeautifulSoup seemed like the way to go, but I haven't been able to make it work.</p> <p>I could also pass this to the browser and do it with javascript, but that doesn't seem like a great idea.</p> <p>Some advice for this would be really useful, especially in python. </p>
[ { "answer_id": 125122, "author": "fuentesjr", "author_id": 10708, "author_profile": "https://Stackoverflow.com/users/10708", "pm_score": 3, "selected": true, "text": "<p>How about this:</p>\n\n<pre><code>Python 2.5.1 (r251:54863, Apr 18 2007, 08:51:08) [MSC v.1310 32 bit (Intel)] on\nwin...
2008/09/24
[ "https://Stackoverflow.com/questions/125102", "https://Stackoverflow.com", "https://Stackoverflow.com/users/9106/" ]
Say I have the following string: ``` "I am the most foo h4ck3r ever!!" ``` I'm trying to write a makeSpecial(foo) function where the foo substring would be wrapped in a new span element, resulting in: ``` "I am the most <span class="special">foo></span> h4ck3r ever!!" ``` BeautifulSoup seemed like the way to go, but I haven't been able to make it work. I could also pass this to the browser and do it with javascript, but that doesn't seem like a great idea. Some advice for this would be really useful, especially in python.
How about this: ``` Python 2.5.1 (r251:54863, Apr 18 2007, 08:51:08) [MSC v.1310 32 bit (Intel)] on win32 Type "help", "copyright", "credits" or "license" for more information. >>> def makeSpecial(mystring, special_substr): ... return mystring.replace(special_substr, '<span class="special">%s</span> ' % special_substr) ... >>> makeSpecial("I am the most foo h4ck3r ever!!", "foo") 'I am the most <span class="special">foo</span> h4ck3r ever!!' >>> ```
125,109
<p>I'm trying to bind a <code>List&lt;T&gt;</code> to a DataGridView control, and I'm not having any luck creating custom bindings.</p> <p>I have tried:</p> <pre><code>gvProgramCode.DataBindings.Add(new Binding("Opcode",code,"Opcode")); </code></pre> <p>It throws an exception, saying that nothing was found by that property name.</p> <p>The name of the column in question is "Opcode". The name of the property in the <code>List&lt;T&gt;</code> is Opcode.</p> <p><strong>ANSWER EDIT</strong>: the problem was that I did not have the bindable fields in my class as properties, just public fields...Apparently it doesn't reflect on fields, just properties.</p>
[ { "answer_id": 125132, "author": "Quintin Robinson", "author_id": 12707, "author_profile": "https://Stackoverflow.com/users/12707", "pm_score": 4, "selected": false, "text": "<p>Is the property on the grid you are binding to Opcode as well?.. if you want to bind directly to List you woul...
2008/09/24
[ "https://Stackoverflow.com/questions/125109", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1965/" ]
I'm trying to bind a `List<T>` to a DataGridView control, and I'm not having any luck creating custom bindings. I have tried: ``` gvProgramCode.DataBindings.Add(new Binding("Opcode",code,"Opcode")); ``` It throws an exception, saying that nothing was found by that property name. The name of the column in question is "Opcode". The name of the property in the `List<T>` is Opcode. **ANSWER EDIT**: the problem was that I did not have the bindable fields in my class as properties, just public fields...Apparently it doesn't reflect on fields, just properties.
Is the property on the grid you are binding to Opcode as well?.. if you want to bind directly to List you would just DataSource = list. The databindings allows custom binding. are you trying to do something other than the datasource? You are getting a bunch of empty rows? do the auto generated columns have names? Have you verified data is in the object (not just string.empty) ? ``` class MyObject { public string Something { get; set; } public string Text { get; set; } public string Other { get; set; } } public Form1() { InitializeComponent(); List<MyObject> myList = new List<MyObject>(); for (int i = 0; i < 200; i++) { string num = i.ToString(); myList.Add(new MyObject { Something = "Something " + num , Text = "Some Row " + num , Other = "Other " + num }); } dataGridView1.DataSource = myList; } ``` this should work fine...
125,113
<p>What is the most efficient way to convert a MySQL query to CSV in PHP please?</p> <p>It would be best to avoid temp files as this reduces portability (dir paths and setting file-system permissions required).</p> <p>The CSV should also include one top line of field names.</p>
[ { "answer_id": 125118, "author": "Wayne", "author_id": 8236, "author_profile": "https://Stackoverflow.com/users/8236", "pm_score": 2, "selected": false, "text": "<pre><code>// Export to CSV\nif($_GET['action'] == 'export') {\n\n $rsSearchResults = mysql_query($sql, $db) or die(mysql_err...
2008/09/24
[ "https://Stackoverflow.com/questions/125113", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5165/" ]
What is the most efficient way to convert a MySQL query to CSV in PHP please? It would be best to avoid temp files as this reduces portability (dir paths and setting file-system permissions required). The CSV should also include one top line of field names.
``` SELECT * INTO OUTFILE "c:/mydata.csv" FIELDS TERMINATED BY ',' OPTIONALLY ENCLOSED BY '"' LINES TERMINATED BY "\n" FROM my_table; ``` (*the documentation for this is here: <http://dev.mysql.com/doc/refman/5.0/en/select.html>*) or: ``` $select = "SELECT * FROM table_name"; $export = mysql_query ( $select ) or die ( "Sql error : " . mysql_error( ) ); $fields = mysql_num_fields ( $export ); for ( $i = 0; $i < $fields; $i++ ) { $header .= mysql_field_name( $export , $i ) . "\t"; } while( $row = mysql_fetch_row( $export ) ) { $line = ''; foreach( $row as $value ) { if ( ( !isset( $value ) ) || ( $value == "" ) ) { $value = "\t"; } else { $value = str_replace( '"' , '""' , $value ); $value = '"' . $value . '"' . "\t"; } $line .= $value; } $data .= trim( $line ) . "\n"; } $data = str_replace( "\r" , "" , $data ); if ( $data == "" ) { $data = "\n(0) Records Found!\n"; } header("Content-type: application/octet-stream"); header("Content-Disposition: attachment; filename=your_desired_name.xls"); header("Pragma: no-cache"); header("Expires: 0"); print "$header\n$data"; ```
125,117
<p>I was looking at how some site implemented rounded corners, and the CSS had these odd tags that I've never really seen before.</p> <pre><code>-moz-border-radius-topright: 5px; -webkit-border-top-right-radius: 5px; -moz-border-radius-bottomright: 5px; -webkit-border-bottom-right-radius: 5px; </code></pre> <p>I googled it, and they seem to be Firefox specific tags? </p> <p><b>Update</b></p> <p>The site I was looking at was twitter, it's wierd how a site like that would alienate their IE users.</p>
[ { "answer_id": 125123, "author": "Joel Coehoorn", "author_id": 3043, "author_profile": "https://Stackoverflow.com/users/3043", "pm_score": 0, "selected": false, "text": "<p>I suggest browsing the site from IE or some other browser. I bet you get different markup.</p>\n" }, { "an...
2008/09/24
[ "https://Stackoverflow.com/questions/125117", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1368/" ]
I was looking at how some site implemented rounded corners, and the CSS had these odd tags that I've never really seen before. ``` -moz-border-radius-topright: 5px; -webkit-border-top-right-radius: 5px; -moz-border-radius-bottomright: 5px; -webkit-border-bottom-right-radius: 5px; ``` I googled it, and they seem to be Firefox specific tags? **Update** The site I was looking at was twitter, it's wierd how a site like that would alienate their IE users.
The `-moz-*` properties are Gecko-only (Firefox, Mozilla, Camino), the `-webkit-*` properties are WebKit-only (Chrome, Safari, Epiphany). Vendor-specific prefixes are common for implementing CSS capabilities that have not yet been standardized by the W3C. --- Twitter's not "alienating" their IE users. There's simply adding style for browsers that support it.
125,124
<p>How do you pass options to an executable? Is there an easier way than making the options boolean arguments?</p> <p>EDIT: The last two answers have suggested using arguments. I know I can code a workable solution like that, but I'd rather have them be options.</p> <p>EDIT2: Per requests for clarification, I'll use this simple example: It's fairly easy to handle arguments because they automatically get parsed into an array.</p> <pre><code>./printfile file.txt 1000 </code></pre> <p>If I want to know what the name of the file the user wants to print, I access it via argv[1].</p> <p>Now about how this situation:</p> <pre><code>./printfile file.txt 1000 --nolinebreaks </code></pre> <p>The user wants to print the file with no line breaks. This is not required for the program to be able to run (as the filename and number of lines to print are), but the user has the option of using if if s/he would like. Now I could do this using:</p> <pre><code>./printfile file.txt 1000 true </code></pre> <p>The usage prompt would inform the user that the third argument is used to determine whether to print the file with line breaks or not. However, this seems rather clumsy. </p>
[ { "answer_id": 125139, "author": "paxdiablo", "author_id": 14860, "author_profile": "https://Stackoverflow.com/users/14860", "pm_score": 2, "selected": false, "text": "<p>I use two methods for passing information:</p>\n\n<p>1/ The use of command line arguments, which are made easier to h...
2008/09/24
[ "https://Stackoverflow.com/questions/125124", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7545/" ]
How do you pass options to an executable? Is there an easier way than making the options boolean arguments? EDIT: The last two answers have suggested using arguments. I know I can code a workable solution like that, but I'd rather have them be options. EDIT2: Per requests for clarification, I'll use this simple example: It's fairly easy to handle arguments because they automatically get parsed into an array. ``` ./printfile file.txt 1000 ``` If I want to know what the name of the file the user wants to print, I access it via argv[1]. Now about how this situation: ``` ./printfile file.txt 1000 --nolinebreaks ``` The user wants to print the file with no line breaks. This is not required for the program to be able to run (as the filename and number of lines to print are), but the user has the option of using if if s/he would like. Now I could do this using: ``` ./printfile file.txt 1000 true ``` The usage prompt would inform the user that the third argument is used to determine whether to print the file with line breaks or not. However, this seems rather clumsy.
You seem to think that there is some fundamental difference between "options" that start with "`--`" and "arguments" that don't. The only difference is in how you parse them. It might be worth your time to look at GNU's `getopt()`/`getopt_long()` option parser. It supports passing arguments with options such as `--number-of-line-breaks 47`.
125,157
<p>Is it possible to specify a relative path reference in connectionstring, attachDbFileName property in a web.config?</p> <p>For example, In my database is located in the App_data folder, I can easily specify the AttachDBFilename as|DataDirectory|\mydb.mdf and the |Datadirectory| will automatically resolve to the correct path.</p> <p>Now, suppose that web.config file is located in A folder, but the database is located in B\App_data folder, where A and B folder is located in the same folder. Is there anyway to use relative path reference to resolve to the correct path?</p>
[ { "answer_id": 125236, "author": "Jared", "author_id": 7388, "author_profile": "https://Stackoverflow.com/users/7388", "pm_score": 3, "selected": false, "text": "<p>It depends on where your '|DataDirectory|' is located. If the resolved value of '|DataDirectory|' is in folder A (where th...
2008/09/24
[ "https://Stackoverflow.com/questions/125157", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3834/" ]
Is it possible to specify a relative path reference in connectionstring, attachDbFileName property in a web.config? For example, In my database is located in the App\_data folder, I can easily specify the AttachDBFilename as|DataDirectory|\mydb.mdf and the |Datadirectory| will automatically resolve to the correct path. Now, suppose that web.config file is located in A folder, but the database is located in B\App\_data folder, where A and B folder is located in the same folder. Is there anyway to use relative path reference to resolve to the correct path?
I had the same problem with the following scenario: I wanted to use the same database as the application from my integration tests. I went with the following workaround: In the App.config of my test-project I have: ``` <appSettings> <add key="DataDirectory" value="..\..\..\BookShop\App_Data\"/> </appSettings> ``` In the test-setup I execute the following code: ``` var dataDirectory = ConfigurationManager.AppSettings["DataDirectory"]; var absoluteDataDirectory = Path.GetFullPath(dataDirectory); AppDomain.CurrentDomain.SetData("DataDirectory", absoluteDataDirectory); ```
125,171
<p>I need to pass a regex substitution as a variable:</p> <pre><code>sub proc { my $pattern = shift; my $txt = &quot;foo baz&quot;; $txt =~ $pattern; } my $pattern = 's/foo/bar/'; proc($pattern); </code></pre> <p>This, of course, doesn't work. I tried eval'ing the substitution:</p> <pre><code>eval(&quot;$txt =~ $pattern;&quot;); </code></pre> <p>but that didn't work either. What horribly obvious thing am I missing here?</p>
[ { "answer_id": 125212, "author": "zigdon", "author_id": 4913, "author_profile": "https://Stackoverflow.com/users/4913", "pm_score": 3, "selected": false, "text": "<p>Well, you can precompile the regular expression using the <em>qr//</em> operator. But you can't pass an operator (s///).<...
2008/09/24
[ "https://Stackoverflow.com/questions/125171", "https://Stackoverflow.com", "https://Stackoverflow.com/users/8130/" ]
I need to pass a regex substitution as a variable: ``` sub proc { my $pattern = shift; my $txt = "foo baz"; $txt =~ $pattern; } my $pattern = 's/foo/bar/'; proc($pattern); ``` This, of course, doesn't work. I tried eval'ing the substitution: ``` eval("$txt =~ $pattern;"); ``` but that didn't work either. What horribly obvious thing am I missing here?
> > I need to pass a regex substitution as a variable > > > Do you? Why not pass a code reference? Example: ``` sub modify { my($text, $code) = @_; $code->($text); return $text; } my $new_text = modify('foo baz', sub { $_[0] =~ s/foo/bar/ }); ``` In general, when you want to pass "something that does something" to a subroutine ("a regex substitution" in the case of your question) the answer is to pass a reference to a piece of code. [Higher Order Perl](http://hop.perl.plover.com/) is a good book on the topic.
125,192
<p>A common pattern with STL containers is this:</p> <pre><code>map&lt;Key, Value&gt; map; for(map&lt;Key, Value&gt;::iterator iter = map.begin(); iter != map.end(); ++iter) { ... } </code></pre> <p>So in order to avoid writing the declaration of the template parameters we can do this somewhere:</p> <pre><code>typedef map&lt;Key, Value&gt; TNiceNameForAMap; </code></pre> <p>But if this map is only used in a single function or for a single iteration this is an annoying overhead.</p> <p>Is there any way around this typedef?</p>
[ { "answer_id": 125201, "author": "Steve Jessop", "author_id": 13005, "author_profile": "https://Stackoverflow.com/users/13005", "pm_score": 3, "selected": false, "text": "<p>Not sure what you mean by \"overhead\". If it simplifies the way you write your code, use it, otherwise stick with...
2008/09/24
[ "https://Stackoverflow.com/questions/125192", "https://Stackoverflow.com", "https://Stackoverflow.com/users/9611/" ]
A common pattern with STL containers is this: ``` map<Key, Value> map; for(map<Key, Value>::iterator iter = map.begin(); iter != map.end(); ++iter) { ... } ``` So in order to avoid writing the declaration of the template parameters we can do this somewhere: ``` typedef map<Key, Value> TNiceNameForAMap; ``` But if this map is only used in a single function or for a single iteration this is an annoying overhead. Is there any way around this typedef?
Not sure what you mean by "overhead". If it simplifies the way you write your code, use it, otherwise stick with the longhand. If it's only used in a restricted scope, put the typedef in that same scope. Then it doesn't need to be published, or documented, or appear on any UML diagrams. For example (and I don't claim this is the best code ever in other respects): ``` int totalSize() { typedef std::map<Key, Value> DeDuplicator; DeDuplicator everything; // Run around the universe finding everything. If we encounter a key // more than once it's only added once. // now compute the total int total = 0; for(DeDuplicator::iterator i = everything.begin(); i <= everything.end(); ++i) { total += i->second.size(); // yeah, yeah, overflow. Whatever. } return total; } ``` Combining with Ferruccio's suggestion (if you're using boost), the loop becomes: ``` BOOST_FOREACH(DeDuplicator::pair p, everything) { total += p.second.size(); } ``` And combining with bk1e's suggestion (if you're using C++0x or have features from it), and assuming that BOOST\_FOREACH interacts with auto in the way I think it should based on the fact that it can normally handle implicit casts to compatible types: ``` std::map<Key, Value> everything; // snipped code to run around... int total = 0; BOOST_FOREACH(auto p, everything) { total += p.second.size(); } ``` Not bad.
125,230
<p>What MySQL query will do a text search and replace in one particular field in a table?</p> <p>I.e. search for <code>foo</code> and replace with <code>bar</code> so a record with a field with the value <code>hello foo</code> becomes <code>hello bar</code>.</p>
[ { "answer_id": 125241, "author": "Wayne", "author_id": 8236, "author_profile": "https://Stackoverflow.com/users/8236", "pm_score": 1, "selected": false, "text": "<p>The <a href=\"http://dev.mysql.com/doc/refman/5.0/en/string-functions.html#function_replace\" rel=\"nofollow noreferrer\">R...
2008/09/24
[ "https://Stackoverflow.com/questions/125230", "https://Stackoverflow.com", "https://Stackoverflow.com/users/16536/" ]
What MySQL query will do a text search and replace in one particular field in a table? I.e. search for `foo` and replace with `bar` so a record with a field with the value `hello foo` becomes `hello bar`.
Change `table_name` and `field` to match your table name and field in question: ``` UPDATE table_name SET field = REPLACE(field, 'foo', 'bar') WHERE INSTR(field, 'foo') > 0; ``` * [REPLACE](https://dev.mysql.com/doc/refman/5.7/en/string-functions.html#function_replace) (string functions) * [INSTR](https://dev.mysql.com/doc/refman/5.7/en/string-functions.html#function_instr) (string functions)
125,265
<p>In reading about Perl 6, I see a feature being trumpeted about, where you no longer have to do:</p> <pre><code>return "0 but true"; </code></pre> <p>...but can instead do:</p> <pre><code>return 0 but True; </code></pre> <p>If that's the case, how does truth work in Perl 6? In Perl 5, it was pretty simple: 0, "", and undef are false, everything else is true.</p> <p>What are the rules in Perl 6 when it comes to boolean context?</p>
[ { "answer_id": 125303, "author": "Mark Cidade", "author_id": 1659, "author_profile": "https://Stackoverflow.com/users/1659", "pm_score": 3, "selected": false, "text": "<p>According to O'Reilly's <em><a href=\"http://books.google.com/books?id=NYgzEwH5tsQC&amp;pg=PA37&amp;lpg=PA36&amp;ots=...
2008/09/24
[ "https://Stackoverflow.com/questions/125265", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7598/" ]
In reading about Perl 6, I see a feature being trumpeted about, where you no longer have to do: ``` return "0 but true"; ``` ...but can instead do: ``` return 0 but True; ``` If that's the case, how does truth work in Perl 6? In Perl 5, it was pretty simple: 0, "", and undef are false, everything else is true. What are the rules in Perl 6 when it comes to boolean context?
So to combine what I think to be the best of everyone's answers: When you evaluate a variable in boolean context, its .true() method gets called. The default .true() method used by an object does a Perl 5-style <0, "", undef> check of the object's value, but when you say "but True" or "but False", this method is overridden with one that doesn't look at the value just returns a constant. One could conceivable write a true() method which, say, returned true when the value was even and false when it was odd.
125,268
<p>Is it possible to chain static methods together using a static class? Say I wanted to do something like this:</p> <pre><code>$value = TestClass::toValue(5)::add(3)::subtract(2)::add(8)::result(); </code></pre> <p>. . . and obviously I would want $value to be assigned the number 14. Is this possible?</p> <p><strong>Update</strong>: It doesn't work (you can't return "self" - it's not an instance!), but this is where my thoughts have taken me:</p> <pre><code>class TestClass { public static $currentValue; public static function toValue($value) { self::$currentValue = $value; } public static function add($value) { self::$currentValue = self::$currentValue + $value; return self; } public static function subtract($value) { self::$currentValue = self::$currentValue - $value; return self; } public static function result() { return self::$value; } } </code></pre> <p>After working that out, I think it would just make more sense to simply work with a class instance rather than trying to chain static function calls (which doesn't look possible, unless the above example could be tweaked somehow).</p>
[ { "answer_id": 125291, "author": "dirtside", "author_id": 20903, "author_profile": "https://Stackoverflow.com/users/20903", "pm_score": 1, "selected": false, "text": "<p>In a nutshell... no. :) The resolution operator (::) would work for the TetsClass::toValue(5) part, but everything af...
2008/09/24
[ "https://Stackoverflow.com/questions/125268", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5291/" ]
Is it possible to chain static methods together using a static class? Say I wanted to do something like this: ``` $value = TestClass::toValue(5)::add(3)::subtract(2)::add(8)::result(); ``` . . . and obviously I would want $value to be assigned the number 14. Is this possible? **Update**: It doesn't work (you can't return "self" - it's not an instance!), but this is where my thoughts have taken me: ``` class TestClass { public static $currentValue; public static function toValue($value) { self::$currentValue = $value; } public static function add($value) { self::$currentValue = self::$currentValue + $value; return self; } public static function subtract($value) { self::$currentValue = self::$currentValue - $value; return self; } public static function result() { return self::$value; } } ``` After working that out, I think it would just make more sense to simply work with a class instance rather than trying to chain static function calls (which doesn't look possible, unless the above example could be tweaked somehow).
I like the solution provided by Camilo above, essentially since all you're doing is altering the value of a static member, and since you do want chaining (even though it's only syntatic sugar), then instantiating TestClass is probably the best way to go. I'd suggest a Singleton pattern if you want to restrict instantiation of the class: ``` class TestClass { public static $currentValue; private static $_instance = null; private function __construct () { } public static function getInstance () { if (self::$_instance === null) { self::$_instance = new self; } return self::$_instance; } public function toValue($value) { self::$currentValue = $value; return $this; } public function add($value) { self::$currentValue = self::$currentValue + $value; return $this; } public function subtract($value) { self::$currentValue = self::$currentValue - $value; return $this; } public function result() { return self::$currentValue; } } // Example Usage: $result = TestClass::getInstance () ->toValue(5) ->add(3) ->subtract(2) ->add(8) ->result(); ```
125,272
<p>I'm relatively new to Mercurial and my team is trying it out right now as a replacement for Subversion. </p> <p>How can I commit and push a single file out to another repository while leaving other modifications in my working directory uncommitted (or at least not pushed to the other repository)?</p> <p>This happens for us with database migrations. We want to commit the migration to source control so a DBA can view and edit it while we're working on the code modifications to go along with that database migration. The changes aren't yet ready to go so we don't want to push all of them out.</p> <p>In subversion, I'd simply do:</p> <pre><code>svn add my_migration.sql # commit only the migration, but not the other files I'm working on svn commit -m "migration notes" my_mygration.sql </code></pre> <p>and continue working locally.</p> <p>This doesn't work with mercurial as when I'm pushing it out to the other repository, if there are changes to it that I haven't pulled down, it wants me to pull them down, merge them, and commit that merge to the repository. Commits after a merge don't allow you to omit files so it forces you to commit everything in your local repository.</p> <p>The easiest thing that I can figure out is to commit the file to my local repository, clone my local repository, fetch any new changes from the actual repository, merge them and commit that merge, and them push my changes out.</p> <pre><code>hg add my_migration.sql hg commit -m "migration notes" my_migration.sql cd .. hg clone project project-clone cd project-clone hg fetch http://hg/project hg push http://hg/project </code></pre> <p>This works, but it feels like I'm missing something easier, some way to tell mercurial to ignore the files already in my working directory, just do the merge and send the files along. I suspect mercurial queues can do this, but I don't fully grok mq yet.</p>
[ { "answer_id": 125301, "author": "Josh Matthews", "author_id": 3830, "author_profile": "https://Stackoverflow.com/users/3830", "pm_score": 6, "selected": true, "text": "<p>There's a Mercurial feature that implements shelve and unshelve commands, which give you an interactive way to speci...
2008/09/24
[ "https://Stackoverflow.com/questions/125272", "https://Stackoverflow.com", "https://Stackoverflow.com/users/8912/" ]
I'm relatively new to Mercurial and my team is trying it out right now as a replacement for Subversion. How can I commit and push a single file out to another repository while leaving other modifications in my working directory uncommitted (or at least not pushed to the other repository)? This happens for us with database migrations. We want to commit the migration to source control so a DBA can view and edit it while we're working on the code modifications to go along with that database migration. The changes aren't yet ready to go so we don't want to push all of them out. In subversion, I'd simply do: ``` svn add my_migration.sql # commit only the migration, but not the other files I'm working on svn commit -m "migration notes" my_mygration.sql ``` and continue working locally. This doesn't work with mercurial as when I'm pushing it out to the other repository, if there are changes to it that I haven't pulled down, it wants me to pull them down, merge them, and commit that merge to the repository. Commits after a merge don't allow you to omit files so it forces you to commit everything in your local repository. The easiest thing that I can figure out is to commit the file to my local repository, clone my local repository, fetch any new changes from the actual repository, merge them and commit that merge, and them push my changes out. ``` hg add my_migration.sql hg commit -m "migration notes" my_migration.sql cd .. hg clone project project-clone cd project-clone hg fetch http://hg/project hg push http://hg/project ``` This works, but it feels like I'm missing something easier, some way to tell mercurial to ignore the files already in my working directory, just do the merge and send the files along. I suspect mercurial queues can do this, but I don't fully grok mq yet.
There's a Mercurial feature that implements shelve and unshelve commands, which give you an interactive way to specify changes to store away until a later time: [Shelve](http://www.selenic.com/mercurial/wiki/index.cgi/ShelveExtension). Then you can `hg shelve` and `hg unshelve` to temporarily store changes away. It lets you work at the "patch hunk" level to pick and choose the items to shelve away. It didn't appear to shelve a file had listed for adding, only files already in the repo with modifications. It is included with Mercurial as an "extension" which just means you have to enable it in your hg config file. --- Notes for really old versions of Mercurial (before shelve was included -- this is no longer necessary): I didn't see any great install instructions with some googling, so here is the combined stuff I used to get it working: Get it with: ``` hg clone http://freehg.org/u/tksoh/hgshelve/ hgshelve ``` The only file (currently) in the project is the hgshelve.py file. Modify your ~/.hgrc to add the shelve extension, pointing to where you cloned the repo: ``` [extensions] hgshelve=/Users/ted/Documents/workspace/hgshelve/hgshelve.py ```
125,281
<p>Given a string file path such as <code>/foo/fizzbuzz.bar</code>, how would I use bash to extract just the <code>fizzbuzz</code> portion of said string?</p>
[ { "answer_id": 125287, "author": "zigdon", "author_id": 4913, "author_profile": "https://Stackoverflow.com/users/4913", "pm_score": 8, "selected": false, "text": "<p>look at the basename command:</p>\n<pre><code>NAME=&quot;$(basename /foo/fizzbuzz.bar .bar)&quot;\n</code></pre>\n<p>instr...
2008/09/24
[ "https://Stackoverflow.com/questions/125281", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1512/" ]
Given a string file path such as `/foo/fizzbuzz.bar`, how would I use bash to extract just the `fizzbuzz` portion of said string?
Here's how to do it with the # and % operators in Bash. ``` $ x="/foo/fizzbuzz.bar" $ y=${x%.bar} $ echo ${y##*/} fizzbuzz ``` `${x%.bar}` could also be `${x%.*}` to remove everything after a dot or `${x%%.*}` to remove everything after the first dot. Example: ``` $ x="/foo/fizzbuzz.bar.quux" $ y=${x%.*} $ echo $y /foo/fizzbuzz.bar $ y=${x%%.*} $ echo $y /foo/fizzbuzz ``` Documentation can be found in the [Bash manual](https://www.gnu.org/software/bash/manual/html_node/Shell-Parameter-Expansion.html#Shell-Parameter-Expansion). Look for `${parameter%word}` and `${parameter%%word}` trailing portion matching section.
125,306
<p>I'm writing an iPhone app that takes a photo and then uploads it to a server. How do I upload a photo to a server with Cocoa? I suppose I use NSUrl somewhere.</p> <p>Thanks!</p>
[ { "answer_id": 136452, "author": "user19087", "author_id": 19087, "author_profile": "https://Stackoverflow.com/users/19087", "pm_score": 2, "selected": false, "text": "<p>Create an NSURLRequest and then use NSURLConnection to send it off to your server.</p>\n" }, { "answer_id": 1...
2008/09/24
[ "https://Stackoverflow.com/questions/125306", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
I'm writing an iPhone app that takes a photo and then uploads it to a server. How do I upload a photo to a server with Cocoa? I suppose I use NSUrl somewhere. Thanks!
Header: ``` @interface EPUploader : NSObject { NSURL *serverURL; NSString *filePath; id delegate; SEL doneSelector; SEL errorSelector; BOOL uploadDidSucceed; } - (id)initWithURL: (NSURL *)serverURL filePath: (NSString *)filePath delegate: (id)delegate doneSelector: (SEL)doneSelector errorSelector: (SEL)errorSelector; - (NSString *)filePath; @end ``` Main: ``` #import "EPUploader.h" #import <zlib.h> static NSString * const BOUNDRY = @"0xKhTmLbOuNdArY"; static NSString * const FORM_FLE_INPUT = @"uploaded"; #define ASSERT(x) NSAssert(x, @"") @interface EPUploader (Private) - (void)upload; - (NSURLRequest *)postRequestWithURL: (NSURL *)url boundry: (NSString *)boundry data: (NSData *)data; - (NSData *)compress: (NSData *)data; - (void)uploadSucceeded: (BOOL)success; - (void)connectionDidFinishLoading:(NSURLConnection *)connection; @end @implementation EPUploader /* *----------------------------------------------------------------------------- * * -[Uploader initWithURL:filePath:delegate:doneSelector:errorSelector:] -- * * Initializer. Kicks off the upload. Note that upload will happen on a * separate thread. * * Results: * An instance of Uploader. * * Side effects: * None * *----------------------------------------------------------------------------- */ - (id)initWithURL: (NSURL *)aServerURL // IN filePath: (NSString *)aFilePath // IN delegate: (id)aDelegate // IN doneSelector: (SEL)aDoneSelector // IN errorSelector: (SEL)anErrorSelector // IN { if ((self = [super init])) { ASSERT(aServerURL); ASSERT(aFilePath); ASSERT(aDelegate); ASSERT(aDoneSelector); ASSERT(anErrorSelector); serverURL = [aServerURL retain]; filePath = [aFilePath retain]; delegate = [aDelegate retain]; doneSelector = aDoneSelector; errorSelector = anErrorSelector; [self upload]; } return self; } /* *----------------------------------------------------------------------------- * * -[Uploader dealloc] -- * * Destructor. * * Results: * None * * Side effects: * None * *----------------------------------------------------------------------------- */ - (void)dealloc { [serverURL release]; serverURL = nil; [filePath release]; filePath = nil; [delegate release]; delegate = nil; doneSelector = NULL; errorSelector = NULL; [super dealloc]; } /* *----------------------------------------------------------------------------- * * -[Uploader filePath] -- * * Gets the path of the file this object is uploading. * * Results: * Path to the upload file. * * Side effects: * None * *----------------------------------------------------------------------------- */ - (NSString *)filePath { return filePath; } @end // Uploader @implementation EPUploader (Private) /* *----------------------------------------------------------------------------- * * -[Uploader(Private) upload] -- * * Uploads the given file. The file is compressed before beign uploaded. * The data is uploaded using an HTTP POST command. * * Results: * None * * Side effects: * None * *----------------------------------------------------------------------------- */ - (void)upload { NSData *data = [NSData dataWithContentsOfFile:filePath]; ASSERT(data); if (!data) { [self uploadSucceeded:NO]; return; } if ([data length] == 0) { // There's no data, treat this the same as no file. [self uploadSucceeded:YES]; return; } // NSData *compressedData = [self compress:data]; // ASSERT(compressedData && [compressedData length] != 0); // if (!compressedData || [compressedData length] == 0) { // [self uploadSucceeded:NO]; // return; // } NSURLRequest *urlRequest = [self postRequestWithURL:serverURL boundry:BOUNDRY data:data]; if (!urlRequest) { [self uploadSucceeded:NO]; return; } NSURLConnection * connection = [[NSURLConnection alloc] initWithRequest:urlRequest delegate:self]; if (!connection) { [self uploadSucceeded:NO]; } // Now wait for the URL connection to call us back. } /* *----------------------------------------------------------------------------- * * -[Uploader(Private) postRequestWithURL:boundry:data:] -- * * Creates a HTML POST request. * * Results: * The HTML POST request. * * Side effects: * None * *----------------------------------------------------------------------------- */ - (NSURLRequest *)postRequestWithURL: (NSURL *)url // IN boundry: (NSString *)boundry // IN data: (NSData *)data // IN { // from http://www.cocoadev.com/index.pl?HTTPFileUpload NSMutableURLRequest *urlRequest = [NSMutableURLRequest requestWithURL:url]; [urlRequest setHTTPMethod:@"POST"]; [urlRequest setValue: [NSString stringWithFormat:@"multipart/form-data; boundary=%@", boundry] forHTTPHeaderField:@"Content-Type"]; NSMutableData *postData = [NSMutableData dataWithCapacity:[data length] + 512]; [postData appendData: [[NSString stringWithFormat:@"--%@\r\n", boundry] dataUsingEncoding:NSUTF8StringEncoding]]; [postData appendData: [[NSString stringWithFormat: @"Content-Disposition: form-data; name=\"%@\"; filename=\"file.bin\"\r\n\r\n", FORM_FLE_INPUT] dataUsingEncoding:NSUTF8StringEncoding]]; [postData appendData:data]; [postData appendData: [[NSString stringWithFormat:@"\r\n--%@--\r\n", boundry] dataUsingEncoding:NSUTF8StringEncoding]]; [urlRequest setHTTPBody:postData]; return urlRequest; } /* *----------------------------------------------------------------------------- * * -[Uploader(Private) compress:] -- * * Uses zlib to compress the given data. * * Results: * The compressed data as a NSData object. * * Side effects: * None * *----------------------------------------------------------------------------- */ - (NSData *)compress: (NSData *)data // IN { if (!data || [data length] == 0) return nil; // zlib compress doc says destSize must be 1% + 12 bytes greater than source. uLong destSize = [data length] * 1.001 + 12; NSMutableData *destData = [NSMutableData dataWithLength:destSize]; int error = compress([destData mutableBytes], &destSize, [data bytes], [data length]); if (error != Z_OK) { NSLog(@"%s: self:0x%p, zlib error on compress:%d\n",__func__, self, error); return nil; } [destData setLength:destSize]; return destData; } /* *----------------------------------------------------------------------------- * * -[Uploader(Private) uploadSucceeded:] -- * * Used to notify the delegate that the upload did or did not succeed. * * Results: * None * * Side effects: * None * *----------------------------------------------------------------------------- */ - (void)uploadSucceeded: (BOOL)success // IN { [delegate performSelector:success ? doneSelector : errorSelector withObject:self]; } /* *----------------------------------------------------------------------------- * * -[Uploader(Private) connectionDidFinishLoading:] -- * * Called when the upload is complete. We judge the success of the upload * based on the reply we get from the server. * * Results: * None * * Side effects: * None * *----------------------------------------------------------------------------- */ - (void)connectionDidFinishLoading:(NSURLConnection *)connection // IN { NSLog(@"%s: self:0x%p\n", __func__, self); [connection release]; [self uploadSucceeded:uploadDidSucceed]; } /* *----------------------------------------------------------------------------- * * -[Uploader(Private) connection:didFailWithError:] -- * * Called when the upload failed (probably due to a lack of network * connection). * * Results: * None * * Side effects: * None * *----------------------------------------------------------------------------- */ - (void)connection:(NSURLConnection *)connection // IN didFailWithError:(NSError *)error // IN { NSLog(@"%s: self:0x%p, connection error:%s\n", __func__, self, [[error description] UTF8String]); [connection release]; [self uploadSucceeded:NO]; } /* *----------------------------------------------------------------------------- * * -[Uploader(Private) connection:didReceiveResponse:] -- * * Called as we get responses from the server. * * Results: * None * * Side effects: * None * *----------------------------------------------------------------------------- */ -(void) connection:(NSURLConnection *)connection // IN didReceiveResponse:(NSURLResponse *)response // IN { NSLog(@"%s: self:0x%p\n", __func__, self); } /* *----------------------------------------------------------------------------- * * -[Uploader(Private) connection:didReceiveData:] -- * * Called when we have data from the server. We expect the server to reply * with a "YES" if the upload succeeded or "NO" if it did not. * * Results: * None * * Side effects: * None * *----------------------------------------------------------------------------- */ - (void)connection:(NSURLConnection *)connection // IN didReceiveData:(NSData *)data // IN { NSLog(@"%s: self:0x%p\n", __func__, self); NSString *reply = [[[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding] autorelease]; NSLog(@"%s: data: %s\n", __func__, [reply UTF8String]); if ([reply hasPrefix:@"YES"]) { uploadDidSucceed = YES; } } @end ``` Usage: ``` [[EPUploader alloc] initWithURL:[NSURL URLWithString:@"http://yourserver.com/uploadDB.php"] filePath:@"path/to/some/file" delegate:self doneSelector:@selector(onUploadDone:) errorSelector:@selector(onUploadError:)]; ```
125,313
<p>I'm running programs from Eclipse (on Windows) that eat a lot of CPU time. To avoid bogging down my whole machine, I set the priority to Low with the Task Manager. However, this is a cumbersome manual process. Is there a way Eclipse can set this priority automatically?</p> <p>EDIT: I realized that each particular launcher (Java, Python etc) has its own configuration method, so I will restrict this question to the Java domain, which is what I need most.</p>
[ { "answer_id": 125322, "author": "marcospereira", "author_id": 4600, "author_profile": "https://Stackoverflow.com/users/4600", "pm_score": 0, "selected": false, "text": "<p>A better alternative is configure the amount of memory that Eclipse will use: <a href=\"http://www.eclipsezone.com/...
2008/09/24
[ "https://Stackoverflow.com/questions/125313", "https://Stackoverflow.com", "https://Stackoverflow.com/users/9871/" ]
I'm running programs from Eclipse (on Windows) that eat a lot of CPU time. To avoid bogging down my whole machine, I set the priority to Low with the Task Manager. However, this is a cumbersome manual process. Is there a way Eclipse can set this priority automatically? EDIT: I realized that each particular launcher (Java, Python etc) has its own configuration method, so I will restrict this question to the Java domain, which is what I need most.
I have the same problem on Windows--- launching subprocesses that use all the CPUs (thread-parallel jobs), yet I want good responsiveness in my Windows development environment. **Solution**: after launching several jobs: DOS cmd>> `wmic process where name="javaw.exe" CALL setpriority "below normal"` No, this won't affect eclipse.exe process. **Java Solution**: Insert this code into your CPU-intense programs to lower their own Windows priority: ``` public static void lowerMyProcessPriority() throws IOException { String pid = ManagementFactory.getRuntimeMXBean().getName(); int p = pid.indexOf("@"); if (p > 0) pid = pid.substring(0,p); String cmd = "wmic process where processid=<pid> CALL setpriority".replace("<pid>", pid); List<String> ls = new ArrayList<>(Arrays.asList(cmd.split(" "))); ls.add("\"below normal\""); ProcessBuilder pb = new ProcessBuilder(ls); pb.start(); } ``` Yes, tested. Works on Win7.
125,314
<p>Selenium Remote Control has a method of "get_html_source", which returns the source of the current page as a string.</p> <p>AFAIK, this method works in all cases in Firefox and Safari. But when it's invoked in Internet Explorer, it returns an incorrect source.</p> <p>Does anyone know if this is a bug with Selenium or Internet Explorer, and if there's a fix?</p>
[ { "answer_id": 125361, "author": "Alan Storm", "author_id": 4668, "author_profile": "https://Stackoverflow.com/users/4668", "pm_score": 2, "selected": false, "text": "<p>I'm 99% sure get_html_source uses the browser's innerHTML property. InnerHTML returns the browser's internal represent...
2008/09/24
[ "https://Stackoverflow.com/questions/125314", "https://Stackoverflow.com", "https://Stackoverflow.com/users/21479/" ]
Selenium Remote Control has a method of "get\_html\_source", which returns the source of the current page as a string. AFAIK, this method works in all cases in Firefox and Safari. But when it's invoked in Internet Explorer, it returns an incorrect source. Does anyone know if this is a bug with Selenium or Internet Explorer, and if there's a fix?
I'm 99% sure get\_html\_source uses the browser's innerHTML property. InnerHTML returns the browser's internal representation of a document, and has always been inconsistent and "wonky" between platforms. You can test this by temporarily adding the following onload attribute to the body tag of your page. ``` onload="var oArea = document.createElement('textarea');oArea.rows=80;oArea.cols=80;oArea.value = document.getElementsByTagName('html')[0].innerHTML;document.getElementsByTagName('body')[0].appendChild(oArea)" ``` This will add a text area to the bottom of your page with the document's innerHTML. If you see the same "incorrect" HTML source you know IE's the culprit here. Possible workarounds would be running the source through HTML Tidy or some other cleaner if you're after valid markup. I don't know of anything that will give you a consistent rendering between browsers.
125,319
<p>I have been running <a href="http://en.wikipedia.org/wiki/StyleCop" rel="noreferrer">StyleCop</a> over some C# code, and it keeps reporting that my <code>using</code> directives should be inside the namespace.</p> <p>Is there a technical reason for putting the <code>using</code> directives inside instead of outside the namespace?</p>
[ { "answer_id": 125330, "author": "Mark Cidade", "author_id": 1659, "author_profile": "https://Stackoverflow.com/users/1659", "pm_score": 8, "selected": false, "text": "<p>Putting it inside the namespaces makes the declarations local to that namespace for the file (in case you have multip...
2008/09/24
[ "https://Stackoverflow.com/questions/125319", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4490/" ]
I have been running [StyleCop](http://en.wikipedia.org/wiki/StyleCop) over some C# code, and it keeps reporting that my `using` directives should be inside the namespace. Is there a technical reason for putting the `using` directives inside instead of outside the namespace?
There is actually a (subtle) difference between the two. Imagine you have the following code in File1.cs: ``` // File1.cs using System; namespace Outer.Inner { class Foo { static void Bar() { double d = Math.PI; } } } ``` Now imagine that someone adds another file (File2.cs) to the project that looks like this: ``` // File2.cs namespace Outer { class Math { } } ``` The compiler searches `Outer` before looking at those `using` directives outside the namespace, so it finds `Outer.Math` instead of `System.Math`. Unfortunately (or perhaps fortunately?), `Outer.Math` has no `PI` member, so File1 is now broken. This changes if you put the `using` inside your namespace declaration, as follows: ``` // File1b.cs namespace Outer.Inner { using System; class Foo { static void Bar() { double d = Math.PI; } } } ``` Now the compiler searches `System` before searching `Outer`, finds `System.Math`, and all is well. Some would argue that `Math` might be a bad name for a user-defined class, since there's already one in `System`; the point here is just that there *is* a difference, and it affects the maintainability of your code. It's also interesting to note what happens if `Foo` is in namespace `Outer`, rather than `Outer.Inner`. In that case, adding `Outer.Math` in File2 breaks File1 regardless of where the `using` goes. This implies that the compiler searches the innermost enclosing namespace before it looks at any `using` directive.
125,333
<p>I'm looking for the simplest, most straightforward way to implement the following:</p> <ul> <li>The main program instantiates worker threads to do a task.</li> <li>Only <code>n</code> tasks can be running at once.</li> <li>When <code>n</code> is reached, no more workers are started until the count of running threads drops back below <code>n</code>.</li> </ul>
[ { "answer_id": 125350, "author": "hazzen", "author_id": 5066, "author_profile": "https://Stackoverflow.com/users/5066", "pm_score": 2, "selected": false, "text": "<p>Use the Executor framework; namely <a href=\"http://docs.oracle.com/javase/8/docs/api/java/util/concurrent/Executors.html#...
2008/09/24
[ "https://Stackoverflow.com/questions/125333", "https://Stackoverflow.com", "https://Stackoverflow.com/users/292/" ]
I'm looking for the simplest, most straightforward way to implement the following: * The main program instantiates worker threads to do a task. * Only `n` tasks can be running at once. * When `n` is reached, no more workers are started until the count of running threads drops back below `n`.
I think that [Executors.newFixedThreadPool](http://docs.oracle.com/javase/8/docs/api/java/util/concurrent/Executors.html#newFixedThreadPool(int)) fits your requirements. There are a number of different ways to use the resulting ExecutorService, depending on whether you want a result returned to the main thread, or whether the task is totally self-contained, and whether you have a collection of tasks to perform up front, or whether tasks are queued in response to some event. ``` Collection<YourTask> tasks = new ArrayList<YourTask>(); YourTask yt1 = new YourTask(); ... tasks.add(yt1); ... ExecutorService exec = Executors.newFixedThreadPool(5); List<Future<YourResultType>> results = exec.invokeAll(tasks); ``` Alternatively, if you have a new asynchronous task to perform in response to some event, you probably just want to use the ExecutorService's simple `execute(Runnable)` method.
125,359
<p>In Java, web apps are bundled in to WARs. By default, many servlet containers will use the WAR name as the context name for the application.</p> <p>Thus myapp.war gets deployed to <a href="http://example.com/myapp" rel="noreferrer">http://example.com/myapp</a>.</p> <p>The problem is that the webapp considers its "root" to be, well, "root", or simply "/", whereas HTML would consider the root of your application to be "/myapp".</p> <p>The Servlet API and JSP have facilities to help manage this. For example, if, in a servlet, you do: response.sendRedirect("/mypage.jsp"), the container will prepend the context and create the url: <a href="http://example.com/myapp/mypage.jsp" rel="noreferrer">http://example.com/myapp/mypage.jsp</a>".</p> <p>However, you can't do that with, say, the IMG tag in HTML. If you do &lt;img src="/myimage.gif"/> you will likely get a 404, because what you really wanted was "/myapp/myimage.gif".</p> <p>Many frameworks have JSP tags that are context aware as well, and there are different ways of making correct URLs within JSP (none particularly elegantly).</p> <p>It's a nitty problem for coders to jump in an out of when to use an "App Relative" url, vs an absolute url.</p> <p>Finally, there's the issue of Javascript code that needs to create URLs on the fly, and embedded URLs within CSS (for background images and the like).</p> <p>I'm curious what techniques others use to mitigate and work around this issue. Many simply punt and hard code it, either to server root or to whatever context they happen to be using. I already know that answer, that's not what I'm looking for.</p> <p>What do you do?</p>
[ { "answer_id": 125420, "author": "Swati", "author_id": 12682, "author_profile": "https://Stackoverflow.com/users/12682", "pm_score": 0, "selected": false, "text": "<p>I by <em>no</em> means claim that the following is an elegant issue. In fact, in hindsight, I wouldn't recommend this iss...
2008/09/24
[ "https://Stackoverflow.com/questions/125359", "https://Stackoverflow.com", "https://Stackoverflow.com/users/13663/" ]
In Java, web apps are bundled in to WARs. By default, many servlet containers will use the WAR name as the context name for the application. Thus myapp.war gets deployed to <http://example.com/myapp>. The problem is that the webapp considers its "root" to be, well, "root", or simply "/", whereas HTML would consider the root of your application to be "/myapp". The Servlet API and JSP have facilities to help manage this. For example, if, in a servlet, you do: response.sendRedirect("/mypage.jsp"), the container will prepend the context and create the url: <http://example.com/myapp/mypage.jsp>". However, you can't do that with, say, the IMG tag in HTML. If you do <img src="/myimage.gif"/> you will likely get a 404, because what you really wanted was "/myapp/myimage.gif". Many frameworks have JSP tags that are context aware as well, and there are different ways of making correct URLs within JSP (none particularly elegantly). It's a nitty problem for coders to jump in an out of when to use an "App Relative" url, vs an absolute url. Finally, there's the issue of Javascript code that needs to create URLs on the fly, and embedded URLs within CSS (for background images and the like). I'm curious what techniques others use to mitigate and work around this issue. Many simply punt and hard code it, either to server root or to whatever context they happen to be using. I already know that answer, that's not what I'm looking for. What do you do?
You can use JSTL for creating urls. For example, `<c:url value="/images/header.jpg" />` will prefix the context root. With CSS, this usually isn't an issue for me. I have a web root structure like this: /css /images In the CSS file, you then just need to use relative URLs (../images/header.jpg) and it doesn't need to be aware of the context root. As for JavaScript, what works for me is including some common JavaScript in the page header like this: ``` <script type="text/javascript"> var CONTEXT_ROOT = '<%= request.getContextPath() %>'; </script> ``` Then you can use the context root in all your scripts (or, you can define a function to build paths - may be a bit more flexible). Obviously this all depends on your using JSPs and JSTL, but I use JSF with Facelets and the techniques involved are similar - the only real difference is getting the context root in a different way.
125,369
<p>I come across this problem when i am writing an event handler in SharePoint. My event handler has a web reference. When i create this web reference, the URL of the web service will be added in the .config file of the assembly. If i have to change the web reference URL i just have to change the link in the config file. </p> <p>Problem comes when I try to GAC the dll. When i GAC the DLL, the config file cannot be GACed along with the dll, and hence, there is no way for me to update the web reference. </p> <p>One workaround i have found is to modify the constructor method Reference.cs class which is autogenerated by visual studio when i add a reference, so that the constructor reads the web service url from some other location, say a registry or an XML file in some predetermined location. But this poses a problem sometimes, as when i update the web referenc using visual studio, this Reference.cs file gets regenerated, and all my modifications would be lost.</p> <p>Is there a better way to solve this problem?</p>
[ { "answer_id": 125375, "author": "Mark Cidade", "author_id": 1659, "author_profile": "https://Stackoverflow.com/users/1659", "pm_score": 2, "selected": true, "text": "<p>If you have Visual Studio 2008, use a Service Reference instead of a Web Reference, which will generate partial classe...
2008/09/24
[ "https://Stackoverflow.com/questions/125369", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1909/" ]
I come across this problem when i am writing an event handler in SharePoint. My event handler has a web reference. When i create this web reference, the URL of the web service will be added in the .config file of the assembly. If i have to change the web reference URL i just have to change the link in the config file. Problem comes when I try to GAC the dll. When i GAC the DLL, the config file cannot be GACed along with the dll, and hence, there is no way for me to update the web reference. One workaround i have found is to modify the constructor method Reference.cs class which is autogenerated by visual studio when i add a reference, so that the constructor reads the web service url from some other location, say a registry or an XML file in some predetermined location. But this poses a problem sometimes, as when i update the web referenc using visual studio, this Reference.cs file gets regenerated, and all my modifications would be lost. Is there a better way to solve this problem?
If you have Visual Studio 2008, use a Service Reference instead of a Web Reference, which will generate partial classes that you can use to override functionality without your code overwritten by the generator. For Visual Studio 2005, you could just add the *partial* keyword to the class in Reference.cs and keep a separate file with your own partial class: ``` public partial class WebServiceReference { public WebServiceReference(ExampleConfigurationClass config) { /* ... */ } } WebServiceReference svc = new WebServiceReference(myConfig); ```
125,377
<p>I've tried this, but get a ClassNotFoundException when calling:</p> <pre><code>Class.forName("com.AClass", false, mySpecialLoader) </code></pre>
[ { "answer_id": 125686, "author": "Brian Deterling", "author_id": 14619, "author_profile": "https://Stackoverflow.com/users/14619", "pm_score": 3, "selected": false, "text": "<p>The ClassLoader will have to call defineClass to get the Class. According to the JavaDoc for defineClass: </...
2008/09/24
[ "https://Stackoverflow.com/questions/125377", "https://Stackoverflow.com", "https://Stackoverflow.com/users/21364/" ]
I've tried this, but get a ClassNotFoundException when calling: ``` Class.forName("com.AClass", false, mySpecialLoader) ```
The ClassLoader will have to call defineClass to get the Class. According to the JavaDoc for defineClass: > > If name is not null, it must be equal > to the binary name of the class > specified by the byte array. > > > If the name is null, it will get it from the bytecode. So you can return any class you want as long as it's called com.AClass. In other words, you could have multiple versions of com.AClass. You could even use something like JavaAssist to create a class on the fly. But that doesn't explain the ClassNotFoundException - it sounds like your class loader isn't returning anything.
125,389
<p>I am writing a custom maven2 MOJO. I need to access the runtime configuration of another plugin, from this MOJO.</p> <p>What is the best way to do this?</p>
[ { "answer_id": 130171, "author": "Mike Deck", "author_id": 1247, "author_profile": "https://Stackoverflow.com/users/1247", "pm_score": 0, "selected": false, "text": "<p>I'm not sure how you would do that exactly, but it seems to me that this might not be the best design decision. If at ...
2008/09/24
[ "https://Stackoverflow.com/questions/125389", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2767300/" ]
I am writing a custom maven2 MOJO. I need to access the runtime configuration of another plugin, from this MOJO. What is the best way to do this?
Using properties is certainly one way to go, however not ideal. It still requires a user to define the ${propertyName} in multiple places throughout the pom. I want to allow my plugin to work with no modifications to the user's pom, other than the plugin definition itself. I don't see accessing the runtime properties of another MOJO as too tight coupling. If the other MOJO is defined anywhere in the build hierarchy, I want my MOJO to respect the same configuration. My current solution is: ``` private Plugin lookupPlugin(String key) { List plugins = getProject().getBuildPlugins(); for (Iterator iterator = plugins.iterator(); iterator.hasNext();) { Plugin plugin = (Plugin) iterator.next(); if(key.equalsIgnoreCase(plugin.getKey())) { return plugin; } } return null; } /** * Extracts nested values from the given config object into a List. * * @param childname the name of the first subelement that contains the list * @param config the actual config object */ private List extractNestedStrings(String childname, Xpp3Dom config) { final Xpp3Dom subelement = config.getChild(childname); if (subelement != null) { List result = new LinkedList(); final Xpp3Dom[] children = subelement.getChildren(); for (int i = 0; i < children.length; i++) { final Xpp3Dom child = children[i]; result.add(child.getValue()); } getLog().info("Extracted strings: " + result); return result; } return null; } ``` This has worked for the few small builds I've tested with. Including a multi-module build.
125,400
<p>Not sure if this is possible or if I'm expressing correctly what I'm looking for, but I have the following piece of code in my library repeatedly and would like to practice some DRY. I have set of SQL Server tables that I'm querying based on a simple user-supplied search field ala Google. I'm using LINQ to compose the final query based on what's in the search string. I'm looking for a way to use generics and passed in lambda functions to create a reusable routine out of this: </p> <pre><code>string[] arrayOfQueryTerms = getsTheArray(); var somequery = from q in dataContext.MyTable select q; if (arrayOfQueryTerms.Length == 1) { somequery = somequery.Where&lt;MyTableEntity&gt;( e =&gt; e.FieldName.StartsWith(arrayOfQueryTerms[0])); } else { foreach(string queryTerm in arrayOfQueryTerms) { if (!String.IsNullOrEmpty(queryTerm)) { somequery = somequery .Where&lt;MyTableEntity&gt;( e =&gt; e.FieldName.Contains(queryTerm)); } } } </code></pre> <p>I was hoping to create a generic method with signature that looks something like:</p> <pre><code>private IQueryable&lt;T&gt; getQuery( T MyTableEntity, string[] arrayOfQueryTerms, Func&lt;T, bool&gt; predicate) </code></pre> <p>I'm using the same search strategy across all my tables, so the only thing that really differs from usage to usage is the MyTable &amp; MyTableEntity searched and the FieldName searched. Does this make sense? Is there a way with LINQ to dynamically pass in the name of the field to query in the where clause? Or can I pass in this as a predicate lambda?</p> <pre><code>e =&gt; e.FieldName.Contains(queryTerm) </code></pre> <p>I realize there a million and a half ways to do this in SQL, probably easier, but I'd love to keep everything in the LINQ family for this one. Also, I feel that generics should be handy for a problem like this. Any ideas?</p>
[ { "answer_id": 125414, "author": "Quintin Robinson", "author_id": 12707, "author_profile": "https://Stackoverflow.com/users/12707", "pm_score": 3, "selected": false, "text": "<p>What it sounds like is you want basically a conditional predicate builder.. </p>\n\n<p>I hope you can mold thi...
2008/09/24
[ "https://Stackoverflow.com/questions/125400", "https://Stackoverflow.com", "https://Stackoverflow.com/users/17729/" ]
Not sure if this is possible or if I'm expressing correctly what I'm looking for, but I have the following piece of code in my library repeatedly and would like to practice some DRY. I have set of SQL Server tables that I'm querying based on a simple user-supplied search field ala Google. I'm using LINQ to compose the final query based on what's in the search string. I'm looking for a way to use generics and passed in lambda functions to create a reusable routine out of this: ``` string[] arrayOfQueryTerms = getsTheArray(); var somequery = from q in dataContext.MyTable select q; if (arrayOfQueryTerms.Length == 1) { somequery = somequery.Where<MyTableEntity>( e => e.FieldName.StartsWith(arrayOfQueryTerms[0])); } else { foreach(string queryTerm in arrayOfQueryTerms) { if (!String.IsNullOrEmpty(queryTerm)) { somequery = somequery .Where<MyTableEntity>( e => e.FieldName.Contains(queryTerm)); } } } ``` I was hoping to create a generic method with signature that looks something like: ``` private IQueryable<T> getQuery( T MyTableEntity, string[] arrayOfQueryTerms, Func<T, bool> predicate) ``` I'm using the same search strategy across all my tables, so the only thing that really differs from usage to usage is the MyTable & MyTableEntity searched and the FieldName searched. Does this make sense? Is there a way with LINQ to dynamically pass in the name of the field to query in the where clause? Or can I pass in this as a predicate lambda? ``` e => e.FieldName.Contains(queryTerm) ``` I realize there a million and a half ways to do this in SQL, probably easier, but I'd love to keep everything in the LINQ family for this one. Also, I feel that generics should be handy for a problem like this. Any ideas?
It sounds like you're looking for Dynamic Linq. Take a look [here](http://weblogs.asp.net/scottgu/archive/2008/01/07/dynamic-linq-part-1-using-the-linq-dynamic-query-library.aspx). This allows you to pass strings as arguments to the query methods, like: ``` var query = dataSource.Where("CategoryID == 2 && UnitPrice > 3") .OrderBy("SupplierID"); ``` Edit: Another set of posts on this subject, using C# 4's Dynamic support: [Part 1](http://weblogs.asp.net/davidfowler/archive/2010/08/04/dynamic-linq-a-little-more-dynamic.aspx) and [Part 2](http://weblogs.asp.net/davidfowler/archive/2010/08/19/dynamic-linq-part-2-evolution.aspx).
125,449
<p>I am using Excel where certain fields are allowed for user input and other cells are to be protected. I have used Tools Protect sheet, however after doing this I am not able to change the values in the VBA script. I need to restrict the sheet to stop user input, at the same time allow the VBA code to change the cell values based on certain computations.</p>
[ { "answer_id": 125505, "author": "Kevin Crumley", "author_id": 1818, "author_profile": "https://Stackoverflow.com/users/1818", "pm_score": 2, "selected": false, "text": "<p><strike>I don't think you can set any part of the sheet to be editable only by VBA</strike>, but you can do somethi...
2008/09/24
[ "https://Stackoverflow.com/questions/125449", "https://Stackoverflow.com", "https://Stackoverflow.com/users/17266/" ]
I am using Excel where certain fields are allowed for user input and other cells are to be protected. I have used Tools Protect sheet, however after doing this I am not able to change the values in the VBA script. I need to restrict the sheet to stop user input, at the same time allow the VBA code to change the cell values based on certain computations.
Try using ``` Worksheet.Protect "Password", UserInterfaceOnly := True ``` If the UserInterfaceOnly parameter is set to true, VBA code can modify protected cells.
125,457
<p>If I need to copy a stored procedure (SP) from one SQL Server to another I right click on the SP in SSMS and select Script Stored Procedure as > CREATE to > New Query Editor Window. I then change the connection by right clicking on that window and selecting Connection > Change Connection... and then selecting the new server and F5 to run the create on the new server.</p> <p>So my question is "What is the T-SQL syntax to connect to another SQL Server?" so that I can just paste that in the top of the create script and F5 to run it and it would switch to the new server and run the create script.</p> <p>While typing the question I realized that if I gave you the back ground to what I'm trying to do that you might come up with a faster and better way from me to accomplish this.</p>
[ { "answer_id": 125469, "author": "Wayne", "author_id": 8236, "author_profile": "https://Stackoverflow.com/users/8236", "pm_score": 2, "selected": false, "text": "<p>Try creating a linked server (which you can do with <a href=\"http://msdn.microsoft.com/en-us/library/ms190479.aspx\" rel=\...
2008/09/24
[ "https://Stackoverflow.com/questions/125457", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1463/" ]
If I need to copy a stored procedure (SP) from one SQL Server to another I right click on the SP in SSMS and select Script Stored Procedure as > CREATE to > New Query Editor Window. I then change the connection by right clicking on that window and selecting Connection > Change Connection... and then selecting the new server and F5 to run the create on the new server. So my question is "What is the T-SQL syntax to connect to another SQL Server?" so that I can just paste that in the top of the create script and F5 to run it and it would switch to the new server and run the create script. While typing the question I realized that if I gave you the back ground to what I'm trying to do that you might come up with a faster and better way from me to accomplish this.
Also, make sure when you write the query involving the linked server, you include brackets like this: ``` SELECT * FROM [LinkedServer].[RemoteDatabase].[User].[Table] ``` I've found that at least on 2000/2005 the [] brackets are necessary, at least around the server name.
125,468
<p>I have a repository of files which are unrelated to each other but are common to multiple projects. Each project might only need a subset of these files. For example:</p> <pre><code>/myRepo: /jquery.js /jquery.form.js /jquery.ui.js </code></pre> <p>Project A requires <code>jquery.js</code> and <code>jquery.form.js</code>, whereas Project B requires <code>jquery.js</code> and <code>jquery.ui.js</code></p> <p>I could just do a checkout of <code>myRepo</code> into both projects, but that'd add a lot of unnecessary files into both. What I'd like is some sort of way for each Project to only get the files it needs. One way I thought it might be possible is if I put just the required files into each project and then run an <code>svn update</code> on it, but somehow stop SVN from adding new files to each directory. They'd still get the modifications to the existing files, but no unnecessary files would be added.</p> <p>Is this possible at all?</p>
[ { "answer_id": 125478, "author": "Hector Sosa Jr", "author_id": 12829, "author_profile": "https://Stackoverflow.com/users/12829", "pm_score": 1, "selected": false, "text": "<p>If I understood your question correctly, you want to share code across projects? If so, look at the svn:external...
2008/09/24
[ "https://Stackoverflow.com/questions/125468", "https://Stackoverflow.com", "https://Stackoverflow.com/users/9021/" ]
I have a repository of files which are unrelated to each other but are common to multiple projects. Each project might only need a subset of these files. For example: ``` /myRepo: /jquery.js /jquery.form.js /jquery.ui.js ``` Project A requires `jquery.js` and `jquery.form.js`, whereas Project B requires `jquery.js` and `jquery.ui.js` I could just do a checkout of `myRepo` into both projects, but that'd add a lot of unnecessary files into both. What I'd like is some sort of way for each Project to only get the files it needs. One way I thought it might be possible is if I put just the required files into each project and then run an `svn update` on it, but somehow stop SVN from adding new files to each directory. They'd still get the modifications to the existing files, but no unnecessary files would be added. Is this possible at all?
Don't complicate yourself. Either pull out all files (what is the disadvatage of this ? a few more 100s of Ks of space ?), or divide the files into several directories, and only check out the needed directories (using the 'externals' property) in relevant projects.
125,470
<p>I need to create a configuration section, that is able to store key-value pairs in an app.config file and the key-value pairs can be added runtime regardless of their type. It is also important that the value keeps its original type. I need to extend the following interface </p> <pre><code>public interface IPreferencesBackend { bool TryGet&lt;T&gt;(string key, out T value); bool TrySet&lt;T&gt;(string key, T value); } </code></pre> <p>At runtime, I can say something like: </p> <pre><code>My.Foo.Data data = new My.Foo.Data("blabla"); Pref pref = new Preferences(); pref.TrySet("foo.data", data); pref.Save(); My.Foo.Data date = new My.Foo.Data(); pref.TryGet("foo.data", out data); </code></pre> <p>I tried with System.Configuration.Configuration.AppSettings, but the problem with that that it is storing the key-value pairs in a string array. </p> <p>What I need is to have an implementation of System.Configuration.ConfigurationSection, where I can control the how the individual setting is serialized. I noticed that the settings generated by Visual Studio kind of do this. It is using reflection to create all the setting keys. what I need is to do this runtime and dynamically. </p> <pre><code>[System.Configuration.UserScopedSettingAttribute()] [System.Diagnostics.DebuggerNonUserCodeAttribute()] [System.Configuration.DefaultSettingValueAttribute("2008-09-24")] public global::System.DateTime DateTime { get { return ((global::System.DateTime)(this["DateTime"])); } set { this["DateTime"] = value; } } </code></pre>
[ { "answer_id": 125479, "author": "Wayne", "author_id": 8236, "author_profile": "https://Stackoverflow.com/users/8236", "pm_score": 2, "selected": false, "text": "<p>Phil Haack has a great article on <a href=\"http://haacked.com/archive/2007/03/12/custom-configuration-sections-in-3-easy-s...
2008/09/24
[ "https://Stackoverflow.com/questions/125470", "https://Stackoverflow.com", "https://Stackoverflow.com/users/260/" ]
I need to create a configuration section, that is able to store key-value pairs in an app.config file and the key-value pairs can be added runtime regardless of their type. It is also important that the value keeps its original type. I need to extend the following interface ``` public interface IPreferencesBackend { bool TryGet<T>(string key, out T value); bool TrySet<T>(string key, T value); } ``` At runtime, I can say something like: ``` My.Foo.Data data = new My.Foo.Data("blabla"); Pref pref = new Preferences(); pref.TrySet("foo.data", data); pref.Save(); My.Foo.Data date = new My.Foo.Data(); pref.TryGet("foo.data", out data); ``` I tried with System.Configuration.Configuration.AppSettings, but the problem with that that it is storing the key-value pairs in a string array. What I need is to have an implementation of System.Configuration.ConfigurationSection, where I can control the how the individual setting is serialized. I noticed that the settings generated by Visual Studio kind of do this. It is using reflection to create all the setting keys. what I need is to do this runtime and dynamically. ``` [System.Configuration.UserScopedSettingAttribute()] [System.Diagnostics.DebuggerNonUserCodeAttribute()] [System.Configuration.DefaultSettingValueAttribute("2008-09-24")] public global::System.DateTime DateTime { get { return ((global::System.DateTime)(this["DateTime"])); } set { this["DateTime"] = value; } } ```
I found two great articles on codeproject.com that are explaining these issues in great detail. Unraveling the Mysteries of .NET 2.0 Configuration <http://www.codeproject.com/KB/dotnet/mysteriesofconfiguration.aspx> User Settings Applied <http://www.codeproject.com/KB/dotnet/user_settings.aspx?display=PrintAll&fid=1286606&df=90&mpp=25&noise=3&sort=Position&view=Quick&select=2647446&fr=26>
125,496
<p>On my rails app I have a list of items (like a task list) and for each item there is a couple of check box to set parameters.</p> <p>When I submit the form, the checked box are stored as zero and the unchecked as null on DB. </p> <p>the question is: Is there a way to configure it? To store the data on a more traditional 0 or 1, because I think that storing null as false and 0 as true is a bit confusing, specially if another app (like a C app) needs to read the data.</p>
[ { "answer_id": 125517, "author": "Dan Harper", "author_id": 14530, "author_profile": "https://Stackoverflow.com/users/14530", "pm_score": 2, "selected": false, "text": "<p>There are a number of potential reasons for this:</p>\n\n<ul>\n<li>Make sure that the column in the database is of t...
2008/09/24
[ "https://Stackoverflow.com/questions/125496", "https://Stackoverflow.com", "https://Stackoverflow.com/users/440867/" ]
On my rails app I have a list of items (like a task list) and for each item there is a couple of check box to set parameters. When I submit the form, the checked box are stored as zero and the unchecked as null on DB. the question is: Is there a way to configure it? To store the data on a more traditional 0 or 1, because I think that storing null as false and 0 as true is a bit confusing, specially if another app (like a C app) needs to read the data.
Let's assume that the attribute you are working with is `club_member` as in "are you a club\_member?". Note that in Ruby/Rails, the way it is working now, `if model.club_member` will return false if it is not checked (value is null or in Ruby, nil) and true if it is checked (value is 0). On the whole, I would strongly recommend that instead of letting other applications (like a C app) directly at your data, you should instead build an API in Ruby/Rails to expose the data from your application to external entities. In this manner, you will better encapsulate your application's internals and you won't have to worry about things like this. --- However, all that being said, here is your answer: Use: ``` value="1" ``` ...attribute in your checkbox HTML tags, and set the default value of the **boolean** attribute (in your migration) to 0.
125,523
<p>Is it possible to use an attribute of a child to group a query?</p> <pre><code>Post.find(:all, :include =&gt; [ :authors, :comments ], :group=&gt;'authors.city') </code></pre> <p>does not work. </p> <p>However, I am able to use <code>author.city</code> as part of the conditions.</p>
[ { "answer_id": 125537, "author": "Terry G Lorber", "author_id": 809, "author_profile": "https://Stackoverflow.com/users/809", "pm_score": 1, "selected": false, "text": "<p>If that's what you're using, then the syntax is wrong for the :group argument, it should be:</p>\n\n<pre><code>Post....
2008/09/24
[ "https://Stackoverflow.com/questions/125523", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1227001/" ]
Is it possible to use an attribute of a child to group a query? ``` Post.find(:all, :include => [ :authors, :comments ], :group=>'authors.city') ``` does not work. However, I am able to use `author.city` as part of the conditions.
The solution is to force the necessary join so that ActiveRecord can resolve "authors.city": ``` Post.find(:all, :include => [ :author, :comments ], :joins=>"INNER JOIN authors ON posts.author_id=authors.id", :group=>'authors.city') ```
125,532
<p>I decided to teach myself assembly language.</p> <p>I have realized that my program will not compile if I attempt to change the value of any segment register.</p> <p>Every article that I have found says that I can indeed change the value of at least 4 segment registers, so what gives? </p> <p>I am really only interested in the why at this point, I don't have any real purpose in changing these addresses.</p>
[ { "answer_id": 125565, "author": "Blorgbeard", "author_id": 369, "author_profile": "https://Stackoverflow.com/users/369", "pm_score": 2, "selected": false, "text": "<p>Are you writing windows executables?</p>\n\n<p>In protected-mode (Win32), segment registers are not used any more.</p>\n...
2008/09/24
[ "https://Stackoverflow.com/questions/125532", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1053/" ]
I decided to teach myself assembly language. I have realized that my program will not compile if I attempt to change the value of any segment register. Every article that I have found says that I can indeed change the value of at least 4 segment registers, so what gives? I am really only interested in the why at this point, I don't have any real purpose in changing these addresses.
You said you were interested in why, so: In real mode, a segment is a 64K "window" to physical memory and these windows are spaced 16 bytes apart. In protected mode, a segment is a window to either physical or virtual memory, whose size and location is determined by the OS, and it has many other properties, including what privilege level a process must have to access it. From here on, everything I say refers to protected mode. There is a table in memory called the global descriptor table (GDT), which is where the information about these window sizes and locations and other properties are kept. There may also be local descriptor tables on a per-process basis, and they work in a similar way, so I'll just focus on the GDT. The value you load into a segment register is known as a *segment selector*. It is an index into the GDT or LDT, with a bit of extra security information. Naturally if a program tries to load a descriptor which is outside the bounds of the GDT, an exception occurs. Also if the process does not have enough privilege to access the segment, or something else is invalid, an exception occurs. When an exception occurs, the kernel handles it. This sort of exception would probably be classed as a segmentation fault. So the OS kills your program. There's one final caveat: in the x86 instruction set, you can't load immediate values into segment registers. You must use an intermediate register or a memory operand or POP into the segment register. ``` MOV DS, 160 ;INVALID - won't assemble MOV AX, 160 ;VALID - assembles, but will probably result in an MOV DS, AX ;exception, and thus the death of your program ``` I think it should be pointed out that the architecture allows for heaps of segments. But AFAIK, when it comes to the mainstream x86 operating systems, segment registers serve only a few purposes: * Security mechanisms, such as keeping user space processes from harming each other or the OS * Dealing with multiple/multi-core processors * Thread-local storage: as an optimization, some operating systems (including Linux and Windows) use segment registers for thread-local storage (TLS). Since threads share the same address space, it is hard for a thread to "know" where its TLS region is without using a system call or wasting a register... but since segment registers are practically useless, there's no harm in "wasting" them for the sake of fast TLS. Note that when setting this up, an OS might skip the segment registers and write directly to descriptor cache registers, which are "hidden" registers used to cache the GDT/LDT lookups triggered by references to the segment registers, in which case if you try to read from the segment registers you won't see it. Apart from a segment per thread for TLS, really only a handful of segments (times the number of processors) are used, and only by the OS. Application programs can *completely* ignore the segment registers. This is due to OS design, not to any technical limitations. There may be embedded operating systems that require user-space programs to work with the segment registers, though I don't know of any.
125,536
<p>I want to add a constant value onto an incoming bound integer. In fact I have several places where I want to bind to the same source value but add different constants. So the ideal solution would be something like this...</p> <pre><code>&lt;TextBox Canvas.Top="{Binding ElementName=mySource, Path=myInt, Constant=5}"/&gt; &lt;TextBox Canvas.Top="{Binding ElementName=mySource, Path=myInt, Constant=8}"/&gt; &lt;TextBox Canvas.Top="{Binding ElementName=mySource, Path=myInt, Constant=24}"/&gt; </code></pre> <p>(NOTE: This is an example to show the idea, my actual binding scenario is not to the canvas property of a TextBox. But this shows the idea more clearly) </p> <p>At the moment the only solution I can think of is to expose many different source properties each of which adds on a different constant to the same internal value. So I could do something like this...</p> <pre><code>&lt;TextBox Canvas.Top="{Binding ElementName=mySource, Path=myIntPlus5}"/&gt; &lt;TextBox Canvas.Top="{Binding ElementName=mySource, Path=myIntPlus8}"/&gt; &lt;TextBox Canvas.Top="{Binding ElementName=mySource, Path=myIntPlus24}"/&gt; </code></pre> <p>But this is pretty grim because in the future I might need to keep adding new properties for new constants. Also if I need to change the value added I need to go an alter the source object which is pretty naff. </p> <p>There must be a more generic way than this? Any WPF experts got any ideas?</p>
[ { "answer_id": 125582, "author": "Steve Steiner", "author_id": 3892, "author_profile": "https://Stackoverflow.com/users/3892", "pm_score": 4, "selected": true, "text": "<p>I believe you can do this with a value converter. Here is a <a href=\"http://weblogs.asp.net/marianor/archive/2007/...
2008/09/24
[ "https://Stackoverflow.com/questions/125536", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6276/" ]
I want to add a constant value onto an incoming bound integer. In fact I have several places where I want to bind to the same source value but add different constants. So the ideal solution would be something like this... ``` <TextBox Canvas.Top="{Binding ElementName=mySource, Path=myInt, Constant=5}"/> <TextBox Canvas.Top="{Binding ElementName=mySource, Path=myInt, Constant=8}"/> <TextBox Canvas.Top="{Binding ElementName=mySource, Path=myInt, Constant=24}"/> ``` (NOTE: This is an example to show the idea, my actual binding scenario is not to the canvas property of a TextBox. But this shows the idea more clearly) At the moment the only solution I can think of is to expose many different source properties each of which adds on a different constant to the same internal value. So I could do something like this... ``` <TextBox Canvas.Top="{Binding ElementName=mySource, Path=myIntPlus5}"/> <TextBox Canvas.Top="{Binding ElementName=mySource, Path=myIntPlus8}"/> <TextBox Canvas.Top="{Binding ElementName=mySource, Path=myIntPlus24}"/> ``` But this is pretty grim because in the future I might need to keep adding new properties for new constants. Also if I need to change the value added I need to go an alter the source object which is pretty naff. There must be a more generic way than this? Any WPF experts got any ideas?
I believe you can do this with a value converter. Here is a [blog entry](http://weblogs.asp.net/marianor/archive/2007/09/18/using-ivalueconverter-to-format-binding-values-in-wpf.aspx) that addresses passing a parameter to the value converter in the xaml. And [this blog](http://blogs.msdn.com/bencon/archive/2006/05/10/594886.aspx) gives some details of implementing a value converter.
125,570
<p>I am actually working on SP in SQL 2005. Using SP i am creating a job and am scheduling it for a particular time. These jobs take atleast 5 to 10 min to complete as the database is very huge. But I am not aware of how to check the status of the Job. I want to know if it has got completed successfully or was there any error in execution. On exception i also return proper error code. But i am not aware of where i can check for this error code.</p>
[ { "answer_id": 125738, "author": "Philip Fourie", "author_id": 11123, "author_profile": "https://Stackoverflow.com/users/11123", "pm_score": 3, "selected": true, "text": "<p>This is what I could find, maybe it solves your problem:</p>\n\n<ol>\n<li>SP to get the current job activiity.</li...
2008/09/24
[ "https://Stackoverflow.com/questions/125570", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20951/" ]
I am actually working on SP in SQL 2005. Using SP i am creating a job and am scheduling it for a particular time. These jobs take atleast 5 to 10 min to complete as the database is very huge. But I am not aware of how to check the status of the Job. I want to know if it has got completed successfully or was there any error in execution. On exception i also return proper error code. But i am not aware of where i can check for this error code.
This is what I could find, maybe it solves your problem: 1. SP to get the current job activiity. > > > ``` > exec msdb.dbo.sp_help_jobactivity @job_id = (your job_id here) > > ``` > > You can execute this SP and place the result in a temp table and get the required result from there. Otherwise have a look at these tables: * msdb.dbo.sysjobactivity * msdb.dbo.sysjobhistory Run the following to see the association between these tables. > > exec sp\_helptext sp\_help\_jobactivity > > >
125,577
<p>I open a connection like this:</p> <pre><code>Using conn as New OdbcConnection(connectionString) conn.Open() //do stuff End Using </code></pre> <p>If connection pooling is enabled, the connection is not physically closed but released to the pool and will get reused. If it is disabled, it will be physically closed.</p> <p>Is there any way of knowing <strong>programmatically</strong> <em>if</em> connection pooling is enabled or not? and the number of used and unused connections currently open in the pool?</p> <p><strong>EDIT:</strong> I need to get this information from within the program, I can't go and check it manually on every single PC where the program will be deployed.</p>
[ { "answer_id": 125581, "author": "Rob Cooper", "author_id": 832, "author_profile": "https://Stackoverflow.com/users/832", "pm_score": 2, "selected": false, "text": "<p>MSDN as <a href=\"http://msdn.microsoft.com/en-us/library/ms810829.aspx\" rel=\"nofollow noreferrer\">in-depth guideline...
2008/09/24
[ "https://Stackoverflow.com/questions/125577", "https://Stackoverflow.com", "https://Stackoverflow.com/users/10786/" ]
I open a connection like this: ``` Using conn as New OdbcConnection(connectionString) conn.Open() //do stuff End Using ``` If connection pooling is enabled, the connection is not physically closed but released to the pool and will get reused. If it is disabled, it will be physically closed. Is there any way of knowing **programmatically** *if* connection pooling is enabled or not? and the number of used and unused connections currently open in the pool? **EDIT:** I need to get this information from within the program, I can't go and check it manually on every single PC where the program will be deployed.
Looks like you can just read this registry key: [HKEYLOCALMACHINE]\SOFTWARE\ODBC\ODBCINST.INI\SQL Server\CPTimeout (or some variant thereof, depending on your OS and user account). If the value is 0, then connection pooling is disabled. If it's any value above 0, it's enabled. See: <http://msdn.microsoft.com/en-us/library/ms810829.aspx> I'm not sure about getting the number of open connections. Just curious: why do you need to know the number?
125,606
<p>I'm working on a C#/ASP.NET web application, and I have a number of situations where I need to do locking. Ideally, I want the locks to act independently, since they have nothing to do with each other. I've been considering <code>[MethodImpl(MethodImplOptions.Synchronized)]</code> and a few ways of using <code>lock()</code>, but I have a few questions/concerns. </p> <p>It seems like MethodImplOptions.Synchronized<code>will essentially do</code>lock(this)`. If that's the case, it seems like a thread entering any synchronized method would block <em>all other</em> threads from entering <em>any</em> synchronized method. Is that right? If so, this isn't granular enough. At that point, it seems like I may as well use Application.Lock. (But please correct me if I'm wrong.)</p> <p>Concerning <code>lock()</code>, I'm trying to figure out what I should pass in. Should I create a set of objects solely for this purpose, and use each one for a different lock? Is there a better way?</p> <p>Thanks in advance!</p>
[ { "answer_id": 125614, "author": "cruizer", "author_id": 6441, "author_profile": "https://Stackoverflow.com/users/6441", "pm_score": 0, "selected": false, "text": "<p>You can expose some static reference or a singleton, and lock() that.</p>\n\n<p>Maybe you can care to explain why you nee...
2008/09/24
[ "https://Stackoverflow.com/questions/125606", "https://Stackoverflow.com", "https://Stackoverflow.com/users/13348/" ]
I'm working on a C#/ASP.NET web application, and I have a number of situations where I need to do locking. Ideally, I want the locks to act independently, since they have nothing to do with each other. I've been considering `[MethodImpl(MethodImplOptions.Synchronized)]` and a few ways of using `lock()`, but I have a few questions/concerns. It seems like MethodImplOptions.Synchronized`will essentially do`lock(this)`. If that's the case, it seems like a thread entering any synchronized method would block *all other* threads from entering *any* synchronized method. Is that right? If so, this isn't granular enough. At that point, it seems like I may as well use Application.Lock. (But please correct me if I'm wrong.) Concerning `lock()`, I'm trying to figure out what I should pass in. Should I create a set of objects solely for this purpose, and use each one for a different lock? Is there a better way? Thanks in advance!
My preference is to create an object specifically for the lock. ``` private object lockForSomeResource = new object(); ``` in the class that is managing the contentious resource. Jeff Richter posted an [article](http://msdn.microsoft.com/en-us/magazine/cc188793.aspx) I read some time ago that recommended this. You need to think carefully about designing these as a hierarchy if there is any code within a lock that needs another lock. Make sure you always request them in the same order.
125,612
<p>I have a menu running off of a sitemap which one of the SiteMapNode looks like this: </p> <pre><code>&lt;siteMapNode title="Gear" description="" url=""&gt; &lt;siteMapNode title="Armor" description="" url="~/Armor.aspx" /&gt; &lt;siteMapNode title="Weapons" description="" url="~/Weapons.aspx" /&gt; &lt;/siteMapNode&gt; </code></pre> <p>I also have a Skin applied to the asp:menu which uses the following css definition:</p> <pre><code>.nav-bar { z-index: 2; margin-top: -5%; position: absolute; top: 281px; font-family: Jokewood; font-style: italic; } </code></pre> <p>When I run the website and mouseOver the Gear link, the Jokewood font is not applied to those items, how can I apply the css to the Armor and Weapons titles?</p> <p><strong>Update</strong><br> I should of mentioned that the font is displayed correctly on all non-nested siteMapNodes.</p>
[ { "answer_id": 125629, "author": "Devin Ceartas", "author_id": 14897, "author_profile": "https://Stackoverflow.com/users/14897", "pm_score": 2, "selected": false, "text": "<p>you can nest CSS commands by listing them in sequence</p>\n\n<p>siteMapNode siteMapNode { .... css code ... } wou...
2008/09/24
[ "https://Stackoverflow.com/questions/125612", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4298/" ]
I have a menu running off of a sitemap which one of the SiteMapNode looks like this: ``` <siteMapNode title="Gear" description="" url=""> <siteMapNode title="Armor" description="" url="~/Armor.aspx" /> <siteMapNode title="Weapons" description="" url="~/Weapons.aspx" /> </siteMapNode> ``` I also have a Skin applied to the asp:menu which uses the following css definition: ``` .nav-bar { z-index: 2; margin-top: -5%; position: absolute; top: 281px; font-family: Jokewood; font-style: italic; } ``` When I run the website and mouseOver the Gear link, the Jokewood font is not applied to those items, how can I apply the css to the Armor and Weapons titles? **Update** I should of mentioned that the font is displayed correctly on all non-nested siteMapNodes.
You should bind styles like this (for both static and dynamic menu items): ``` <asp:Menu ID="Menu1" runat="server" > <StaticMenuStyle CssClass="nav-bar" /> <DynamicMenuStyle CssClass="nav-bar" /> </asp:Menu> ```
125,619
<p>I'm working on an app that requires no user input, but I don't want the iPhone to enter the power saving mode.</p> <p>Is it possible to disable power saving from an app?</p>
[ { "answer_id": 125645, "author": "lajos", "author_id": 3740, "author_profile": "https://Stackoverflow.com/users/3740", "pm_score": 9, "selected": true, "text": "<p><strong>Objective-C</strong></p>\n\n<pre><code>[[UIApplication sharedApplication] setIdleTimerDisabled:YES];\n</code></pre>\...
2008/09/24
[ "https://Stackoverflow.com/questions/125619", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3740/" ]
I'm working on an app that requires no user input, but I don't want the iPhone to enter the power saving mode. Is it possible to disable power saving from an app?
**Objective-C** ``` [[UIApplication sharedApplication] setIdleTimerDisabled:YES]; ``` **Swift** ``` UIApplication.shared.isIdleTimerDisabled = true ```
125,627
<p>I want to call a web service, but I won't know the url till runtime.</p> <p>Whats the best way to get the web reference in, without actually committing to a url.</p> <p>What about having 1 client hit the same web service on say 10 different domains?</p>
[ { "answer_id": 125637, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 4, "selected": true, "text": "<p>Create the web reference, and convert the web service to a dynamic web service. A dynamic web service allows you to modify t...
2008/09/24
[ "https://Stackoverflow.com/questions/125627", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1220/" ]
I want to call a web service, but I won't know the url till runtime. Whats the best way to get the web reference in, without actually committing to a url. What about having 1 client hit the same web service on say 10 different domains?
Create the web reference, and convert the web service to a dynamic web service. A dynamic web service allows you to modify the Url. You need to create the web reference now to ensure your application understands the interfaces available. By switching to a dynamic web service you can then modify the .Url property after you have initialised the web reference in your code. ``` service = new MyWebService.MyWebService(); service.Url = myWebServiceUrl; ```
125,632
<p>When providing a link to a PDF file on a website, is it possible to include information in the URL (request parameters) which will make the PDF browser plugin (if used) jump to a particular bookmark instead of just opening at the beginning?</p> <p>Something like: <a href="http://www.somehost.com/user-guide.pdf?bookmark=chapter3" rel="noreferrer">http://www.somehost.com/user-guide.pdf?bookmark=chapter3</a> ?</p> <p>If not a bookmark, would it be possible to go to a particular page?</p> <p>I'm assuming that if there is an answer it may be specific to Adobe's PDF reader plugin or something, and may have version limitations, but I'm mostly interested in whether the technique exists at all.</p>
[ { "answer_id": 125650, "author": "Wayne", "author_id": 8236, "author_profile": "https://Stackoverflow.com/users/8236", "pm_score": 7, "selected": true, "text": "<p>Yes, you can link to specific pages by number or named locations and that will always work <strong>if the user's browser use...
2008/09/24
[ "https://Stackoverflow.com/questions/125632", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1119/" ]
When providing a link to a PDF file on a website, is it possible to include information in the URL (request parameters) which will make the PDF browser plugin (if used) jump to a particular bookmark instead of just opening at the beginning? Something like: <http://www.somehost.com/user-guide.pdf?bookmark=chapter3> ? If not a bookmark, would it be possible to go to a particular page? I'm assuming that if there is an answer it may be specific to Adobe's PDF reader plugin or something, and may have version limitations, but I'm mostly interested in whether the technique exists at all.
Yes, you can link to specific pages by number or named locations and that will always work **if the user's browser uses Adobe Reader as plugin for viewing PDF files**. For a specific page by number: ``` <a href="http://www.domain.com/file.pdf#page=3">Link text</a> ``` For a named location (destination): ``` <a href="http://www.domain.com/file.pdf#nameddest=TOC">Link text</a> ``` To create destinations within a PDF with Acrobat: 1. Manually navigate through the PDF for the desired location 2. Go to View > Navigation Tabs > Destinations 3. Under Options, choose Scan Document 4. Once this is completed, select New Destination from the Options menu and enter an appropriate name
125,638
<p>At run time I want to dynamically build grid columns (or another display layout) in a WPF ListView. I do not know the number and names of the columns before hand.</p> <p>I want to be able to do:<br/> MyListView.ItemSource = MyDataset;<br/> MyListView.CreateColumns();</p>
[ { "answer_id": 125736, "author": "Jobi Joy", "author_id": 8091, "author_profile": "https://Stackoverflow.com/users/8091", "pm_score": 0, "selected": false, "text": "<p>Have a <strong>DataTemplateselector</strong> to select one of the predefined templates(Of same DataType) and apply the s...
2008/09/24
[ "https://Stackoverflow.com/questions/125638", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5189/" ]
At run time I want to dynamically build grid columns (or another display layout) in a WPF ListView. I do not know the number and names of the columns before hand. I want to be able to do: MyListView.ItemSource = MyDataset; MyListView.CreateColumns();
i'd try following approach: A) you need to have the list box display grid view - i believe this you've done already B) define a style for GridViewColumnHeader: ``` <Style TargetType="{x:Type GridViewColumnHeader}" x:Key="gridViewColumnStyle"> <EventSetter Event="Click" Handler="OnHeaderClicked"/> <EventSetter Event="Loaded" Handler="OnHeaderLoaded"/> </Style> ``` in my case, i had a whole bunch of other properties set, but in the basic scenario - you'd need Loaded event. Clicked - this is useful if you want to add sorting and filtering functionality. C) in your listview code, bind the template with your gridview: ``` public MyListView() { InitializeComponent(); GridView gridViewHeader = this.listView.View as GridView; System.Diagnostics.Debug.Assert(gridViewHeader != null, "Expected ListView.View should be GridView"); if (null != gridViewHeader) { gridViewHeader.ColumnHeaderContainerStyle = (Style)this.FindResource("gridViewColumnStyle"); } } ``` D) then in you OnHeaderLoaded handler, you can set a proper template based on the column's data ``` void OnHeaderLoaded(object sender, RoutedEventArgs e) { GridViewColumnHeader header = (GridViewColumnHeader)sender; GridViewColumn column = header.Column; ``` //select and apply your data template here. ``` e.Handled = true; } ``` E) I guess you'd need also to acquire ownership of ItemsSource dependency property and handle it's changed event. ``` ListView.ItemsSourceProperty.AddOwner(typeof(MyListView), new PropertyMetadata(OnItemsSourceChanged)); static void OnItemsSourceChanged(DependencyObject sender, DependencyPropertyChangedEventArgs e) { MyListView view = (MyListView)sender; //do reflection to get column names and types //and for each column, add it to your grid view: GridViewColumn column = new GridViewColumn(); //set column properties here... view.Columns.Add(column); } ``` the GridViewColumn class itself doesn't have much properties, so you might want to add some information there using attached properties - i.e. like unique column tag - header most likely will be used for localization, and you will not relay on this one. In general, this approach, even though quite complicated, will allow you to easily extend your list view functionality.
125,664
<p>How do I write a program that tells when my other program ends?</p>
[ { "answer_id": 125671, "author": "Viktor", "author_id": 17424, "author_profile": "https://Stackoverflow.com/users/17424", "pm_score": -1, "selected": false, "text": "<p>This is called the \"halting problem\" and is not solvable.\nSee <a href=\"http://en.wikipedia.org/wiki/Halting_problem...
2008/09/24
[ "https://Stackoverflow.com/questions/125664", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
How do I write a program that tells when my other program ends?
The only way to do a waitpid() or waitid() on a program that isn't spawned by yourself is to become its parent by ptrace'ing it. Here is an example of how to use ptrace on a posix operating system to temporarily become another processes parent, and then wait until that program exits. As a side effect you can also get the exit code, and the signal that caused that program to exit.: ``` #include <sys/ptrace.h> #include <errno.h> #include <stdio.h> #include <signal.h> #include <unistd.h> #include <sys/wait.h> int main(int argc, char** argv) { int pid = atoi(argv[1]); int status; siginfo_t si; switch (ptrace(PTRACE_ATTACH, pid, NULL)) { case 0: break; case -ESRCH: case -EPERM: return 0; default: fprintf(stderr, "Failed to attach child\n"); return 1; } if (pid != wait(&status)) { fprintf(stderr, "wrong wait signal\n"); return 1; } if (!WIFSTOPPED(status) || (WSTOPSIG(status) != SIGSTOP)) { /* The pid might not be running */ if (!kill(pid, 0)) { fprintf(stderr, "SIGSTOP didn't stop child\n"); return 1; } else { return 0; } } if (ptrace(PTRACE_CONT, pid, 0, 0)) { fprintf(stderr, "Failed to restart child\n"); return 1; } while (1) { if (waitid(P_PID, pid, &si, WSTOPPED | WEXITED)) { // an error occurred. if (errno == ECHILD) return 0; return 1; } errno = 0; if (si.si_code & (CLD_STOPPED | CLD_TRAPPED)) { /* If the child gets stopped, we have to PTRACE_CONT it * this will happen when the child has a child that exits. **/ if (ptrace(PTRACE_CONT, pid, 1, si.si_status)) { if (errno == ENOSYS) { /* Wow, we're stuffed. Stop and return */ return 0; } } continue; } if (si.si_code & (CLD_EXITED | CLD_KILLED | CLD_DUMPED)) { return si.si_status; } // Fall through to exiting. return 1; } } ```
125,677
<p>So I'm writing a framework on which I want to base a few apps that I'm working on (the framework is there so I have an environment to work with, and a system that will let me, for example, use a single sign-on)</p> <p>I want to make this framework, and the apps it has use a Resource Oriented Architecture.</p> <p>Now, I want to create a URL routing class that is expandable by APP writers (and possibly also by CMS App users, but that's WAYYYY ahead in the future) and I'm trying to figure out the best way to do it by looking at how other apps do it.</p>
[ { "answer_id": 125799, "author": "Mez", "author_id": 20010, "author_profile": "https://Stackoverflow.com/users/20010", "pm_score": 1, "selected": false, "text": "<p>Use a list of Regexs to match which object I should be using</p>\n\n<p>For example</p>\n\n<pre><code>^/users/[\\w-]+/bookma...
2008/09/24
[ "https://Stackoverflow.com/questions/125677", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20010/" ]
So I'm writing a framework on which I want to base a few apps that I'm working on (the framework is there so I have an environment to work with, and a system that will let me, for example, use a single sign-on) I want to make this framework, and the apps it has use a Resource Oriented Architecture. Now, I want to create a URL routing class that is expandable by APP writers (and possibly also by CMS App users, but that's WAYYYY ahead in the future) and I'm trying to figure out the best way to do it by looking at how other apps do it.
I prefer to use reg ex over making my own format since it is common knowledge. I wrote a small class that I use which allows me to nest these reg ex routing tables. I use to use something similar that was implemented by inheritance but it didn't need inheritance so I rewrote it. I do a reg ex on a key and map to my own control string. Take the below example. I visit `/api/related/joe` and my router class creates a new object `ApiController` and calls it's method `relatedDocuments(array('tags' => 'joe'));` ``` // the 12 strips the subdirectory my app is running in $index = urldecode(substr($_SERVER["REQUEST_URI"], 12)); Route::process($index, array( "#^api/related/(.*)$#Di" => "ApiController/relatedDocuments/tags", "#^thread/(.*)/post$#Di" => "ThreadController/post/title", "#^thread/(.*)/reply$#Di" => "ThreadController/reply/title", "#^thread/(.*)$#Di" => "ThreadController/thread/title", "#^ajax/tag/(.*)/(.*)$#Di" => "TagController/add/id/tags", "#^ajax/reply/(.*)/post$#Di"=> "ThreadController/ajaxPost/id", "#^ajax/reply/(.*)$#Di" => "ArticleController/newReply/id", "#^ajax/toggle/(.*)$#Di" => "ApiController/toggle/toggle", "#^$#Di" => "HomeController", )); ``` In order to keep errors down and simplicity up you can subdivide your table. This way you can put the routing table into the class that it controls. Taking the above example you can combine the three thread calls into a single one. ``` Route::process($index, array( "#^api/related/(.*)$#Di" => "ApiController/relatedDocuments/tags", "#^thread/(.*)$#Di" => "ThreadController/route/uri", "#^ajax/tag/(.*)/(.*)$#Di" => "TagController/add/id/tags", "#^ajax/reply/(.*)/post$#Di"=> "ThreadController/ajaxPost/id", "#^ajax/reply/(.*)$#Di" => "ArticleController/newReply/id", "#^ajax/toggle/(.*)$#Di" => "ApiController/toggle/toggle", "#^$#Di" => "HomeController", )); ``` Then you define ThreadController::route to be like this. ``` function route($args) { Route::process($args['uri'], array( "#^(.*)/post$#Di" => "ThreadController/post/title", "#^(.*)/reply$#Di" => "ThreadController/reply/title", "#^(.*)$#Di" => "ThreadController/thread/title", )); } ``` Also you can define whatever defaults you want for your routing string on the right. Just don't forget to document them or you will confuse people. I'm currently calling index if you don't include a function name on the right. [Here](http://pastie.org/278748) is my current code. You may want to change it to handle errors how you like and or default actions.
125,703
<p>I'm using Python, and would like to insert a string into a text file without deleting or copying the file. How can I do that?</p>
[ { "answer_id": 125713, "author": "Armin Ronacher", "author_id": 19990, "author_profile": "https://Stackoverflow.com/users/19990", "pm_score": 7, "selected": false, "text": "<p>Depends on what you want to do. To append you can open it with \"a\":</p>\n\n<pre><code> with open(\"foo.txt\",...
2008/09/24
[ "https://Stackoverflow.com/questions/125703", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
I'm using Python, and would like to insert a string into a text file without deleting or copying the file. How can I do that?
Depends on what you want to do. To append you can open it with "a": ``` with open("foo.txt", "a") as f: f.write("new line\n") ``` If you want to preprend something you have to read from the file first: ``` with open("foo.txt", "r+") as f: old = f.read() # read everything in the file f.seek(0) # rewind f.write("new line\n" + old) # write the new line before ```
125,730
<p>Why do I get following error when trying to start a ruby on rails application with <pre>mongrel_rails start</pre>?</p> <pre> C:\RailsTest\cookbook2>mongrel_rails start ** WARNING: Win32 does not support daemon mode. ** Daemonized, any open files are closed. Look at log/mongrel.pid and log/mongr el.log for info. ** Starting Mongrel listening at 0.0.0.0:3000 c:/ruby/lib/ruby/gems/1.8/gems/mongrel-1.1.5-x86-mswin32-60/bin/../lib/mongrel/t cphack.rb:12:in `initialize_without_backlog': Only one usage of each socket addr ess (protocol/network address/port) is normally permitted. - bind(2) (Errno::EAD DRINUSE) from c:/ruby/lib/ruby/gems/1.8/gems/mongrel-1.1.5-x86-mswin32-60/bin/../ lib/mongrel/tcphack.rb:12:in `initialize' from c:/ruby/lib/ruby/gems/1.8/gems/mongrel-1.1.5-x86-mswin32-60/bin/../ lib/mongrel.rb:93:in `new' from c:/ruby/lib/ruby/gems/1.8/gems/mongrel-1.1.5-x86-mswin32-60/bin/../ lib/mongrel.rb:93:in `initialize' from c:/ruby/lib/ruby/gems/1.8/gems/mongrel-1.1.5-x86-mswin32-60/bin/../ lib/mongrel/configurator.rb:139:in `new' from c:/ruby/lib/ruby/gems/1.8/gems/mongrel-1.1.5-x86-mswin32-60/bin/../ lib/mongrel/configurator.rb:139:in `listener' from c:/ruby/lib/ruby/gems/1.8/gems/mongrel-1.1.5-x86-mswin32-60/bin/mon grel_rails:99:in `cloaker_' from c:/ruby/lib/ruby/gems/1.8/gems/mongrel-1.1.5-x86-mswin32-60/bin/../ lib/mongrel/configurator.rb:50:in `call' from c:/ruby/lib/ruby/gems/1.8/gems/mongrel-1.1.5-x86-mswin32-60/bin/../ lib/mongrel/configurator.rb:50:in `initialize' from c:/ruby/lib/ruby/gems/1.8/gems/mongrel-1.1.5-x86-mswin32-60/bin/mon grel_rails:84:in `new' from c:/ruby/lib/ruby/gems/1.8/gems/mongrel-1.1.5-x86-mswin32-60/bin/mon grel_rails:84:in `run' from c:/ruby/lib/ruby/gems/1.8/gems/mongrel-1.1.5-x86-mswin32-60/bin/../ lib/mongrel/command.rb:212:in `run' from c:/ruby/lib/ruby/gems/1.8/gems/mongrel-1.1.5-x86-mswin32-60/bin/mon grel_rails:281 from c:/ruby/bin/mongrel_rails:19:in `load' from c:/ruby/bin/mongrel_rails:19 </pre>
[ { "answer_id": 125748, "author": "Armin Ronacher", "author_id": 19990, "author_profile": "https://Stackoverflow.com/users/19990", "pm_score": 2, "selected": false, "text": "<p>I don't use mongrel on windows myself, but I guess that error is the equivalent of Linux' \"port in use\" error....
2008/09/24
[ "https://Stackoverflow.com/questions/125730", "https://Stackoverflow.com", "https://Stackoverflow.com/users/14027/" ]
Why do I get following error when trying to start a ruby on rails application with ``` mongrel_rails start ``` ? ``` C:\RailsTest\cookbook2>mongrel_rails start ** WARNING: Win32 does not support daemon mode. ** Daemonized, any open files are closed. Look at log/mongrel.pid and log/mongr el.log for info. ** Starting Mongrel listening at 0.0.0.0:3000 c:/ruby/lib/ruby/gems/1.8/gems/mongrel-1.1.5-x86-mswin32-60/bin/../lib/mongrel/t cphack.rb:12:in `initialize_without_backlog': Only one usage of each socket addr ess (protocol/network address/port) is normally permitted. - bind(2) (Errno::EAD DRINUSE) from c:/ruby/lib/ruby/gems/1.8/gems/mongrel-1.1.5-x86-mswin32-60/bin/../ lib/mongrel/tcphack.rb:12:in `initialize' from c:/ruby/lib/ruby/gems/1.8/gems/mongrel-1.1.5-x86-mswin32-60/bin/../ lib/mongrel.rb:93:in `new' from c:/ruby/lib/ruby/gems/1.8/gems/mongrel-1.1.5-x86-mswin32-60/bin/../ lib/mongrel.rb:93:in `initialize' from c:/ruby/lib/ruby/gems/1.8/gems/mongrel-1.1.5-x86-mswin32-60/bin/../ lib/mongrel/configurator.rb:139:in `new' from c:/ruby/lib/ruby/gems/1.8/gems/mongrel-1.1.5-x86-mswin32-60/bin/../ lib/mongrel/configurator.rb:139:in `listener' from c:/ruby/lib/ruby/gems/1.8/gems/mongrel-1.1.5-x86-mswin32-60/bin/mon grel_rails:99:in `cloaker_' from c:/ruby/lib/ruby/gems/1.8/gems/mongrel-1.1.5-x86-mswin32-60/bin/../ lib/mongrel/configurator.rb:50:in `call' from c:/ruby/lib/ruby/gems/1.8/gems/mongrel-1.1.5-x86-mswin32-60/bin/../ lib/mongrel/configurator.rb:50:in `initialize' from c:/ruby/lib/ruby/gems/1.8/gems/mongrel-1.1.5-x86-mswin32-60/bin/mon grel_rails:84:in `new' from c:/ruby/lib/ruby/gems/1.8/gems/mongrel-1.1.5-x86-mswin32-60/bin/mon grel_rails:84:in `run' from c:/ruby/lib/ruby/gems/1.8/gems/mongrel-1.1.5-x86-mswin32-60/bin/../ lib/mongrel/command.rb:212:in `run' from c:/ruby/lib/ruby/gems/1.8/gems/mongrel-1.1.5-x86-mswin32-60/bin/mon grel_rails:281 from c:/ruby/bin/mongrel_rails:19:in `load' from c:/ruby/bin/mongrel_rails:19 ```
You already have a process listening on port 3000 (the default port for mongrel). Try: ``` mongrel_rails start -p 3001 ``` and see whether you get a similar error. If you're trying to install more than one Rails app, you need to assign each mongrel to a separate port and edit you apache conf accordingly. If you not trying to do that, the most direct way of killing all mongrels is to open windows task manager and kill all the 'ruby' processes. Note that if you have mongrel installed as a service that starts automatically ``` mongrel_rails install::service ... ``` ...the ruby process will regenerate automatically. In that case, you'll have to edit the process properties through the windows services panel. Let me know if you need more info.
125,735
<p>I'm using the following code for setting/getting deleting cookies:</p> <pre><code>function get_cookie(cookie_name) { var results = document.cookie.match('(^|;) ?' + cookie_name + '=([^;]*)(;|$)'); if (results) return ( decodeURI(results[2]) ); else return null; } function set_cookie(name, value, exp_y, exp_m, exp_d, path, domain, secure) { var cookie_string = name + "=" + encodeURI(value); if (exp_y) { var expires = new Date(exp_y, exp_m, exp_d); cookie_string += "; expires=" + expires.toGMTString(); } if (path) cookie_string += "; path=" + encodeURI(path); if (domain) cookie_string += "; domain=" + encodeURI(domain); if (secure) cookie_string += "; secure"; document.cookie = cookie_string; } function delete_cookie(cookie_name) { var cookie_date = new Date(); // current date &amp; time cookie_date.setTime(cookie_date.getTime() - 1); document.cookie = cookie_name += "=; expires=" + cookie_date.toGMTString(); } </code></pre> <p>but i am getting inconsistent results. for example, a cookie set on the startpage (www.example.com/start) , will not always show up on a subsequent page (www.example.com/foo/thing.jsp). i am setting a cookie "onUnload" of the page using </p> <pre><code>set_cookie("beginrequest", (new Date()).getTime(), null, null, null, "/"); </code></pre> <p>and retrieving + deleting it "onLoad" via </p> <pre><code>loadDur = (new Date()).getTime() - get_cookie("beginrequest"); delete_cookie("beginrequest"); </code></pre> <p>to measure the total amount of time the page took to load.</p> <p>when using firebug, i often see "leftover" beginrequest-cookies and multiple instances of beginrequest with past timestamps.</p> <p>how can i achieve to see just one beginrequest-cookie on every page?</p>
[ { "answer_id": 126115, "author": "amix", "author_id": 20081, "author_profile": "https://Stackoverflow.com/users/20081", "pm_score": 0, "selected": false, "text": "<p>Your code for set_cookie, get_cookie and delete_cookie seems to be correct. And your usage as well.</p>\n\n<p>I think you ...
2008/09/24
[ "https://Stackoverflow.com/questions/125735", "https://Stackoverflow.com", "https://Stackoverflow.com/users/16542/" ]
I'm using the following code for setting/getting deleting cookies: ``` function get_cookie(cookie_name) { var results = document.cookie.match('(^|;) ?' + cookie_name + '=([^;]*)(;|$)'); if (results) return ( decodeURI(results[2]) ); else return null; } function set_cookie(name, value, exp_y, exp_m, exp_d, path, domain, secure) { var cookie_string = name + "=" + encodeURI(value); if (exp_y) { var expires = new Date(exp_y, exp_m, exp_d); cookie_string += "; expires=" + expires.toGMTString(); } if (path) cookie_string += "; path=" + encodeURI(path); if (domain) cookie_string += "; domain=" + encodeURI(domain); if (secure) cookie_string += "; secure"; document.cookie = cookie_string; } function delete_cookie(cookie_name) { var cookie_date = new Date(); // current date & time cookie_date.setTime(cookie_date.getTime() - 1); document.cookie = cookie_name += "=; expires=" + cookie_date.toGMTString(); } ``` but i am getting inconsistent results. for example, a cookie set on the startpage (www.example.com/start) , will not always show up on a subsequent page (www.example.com/foo/thing.jsp). i am setting a cookie "onUnload" of the page using ``` set_cookie("beginrequest", (new Date()).getTime(), null, null, null, "/"); ``` and retrieving + deleting it "onLoad" via ``` loadDur = (new Date()).getTime() - get_cookie("beginrequest"); delete_cookie("beginrequest"); ``` to measure the total amount of time the page took to load. when using firebug, i often see "leftover" beginrequest-cookies and multiple instances of beginrequest with past timestamps. how can i achieve to see just one beginrequest-cookie on every page?
If you're getting old cookies that might be because your page contains a lot of content and onload isn't called before onunload (because the page doesn't finish loading). So delete the cookie by calling something like this from both onload and onunload: ``` var deleted_cookie = false; function delete_timestamp() { if(!deleted_cookie) delete_cookie("beginrequest"); deleted_cookie = true; } ``` You might also have a race condition if you're loading the next page quick enough that the 'delete\_cookie' cookie hasn't expired properly, and your get\_cookie implementation is picking that up. So try changing the regular expression in get\_cookie to only pick up cookies with a value: ``` var results = document.cookie.match('(^|;) ?' + cookie_name + '=([^;]+)(;|$)'); ``` Also, if you're viewing the site in more than one window (or tab), their cookies can get mixed up, so don't do that. But try using a global regular expression to pick up all the values, and only using the latest one.
125,756
<p>I'm looking for a way to set the default language for visitors comming to a site built in EPiServer for the first time. Not just administrators/editors in the backend, people comming to the public site.</p>
[ { "answer_id": 126318, "author": "user19264", "author_id": 19264, "author_profile": "https://Stackoverflow.com/users/19264", "pm_score": 3, "selected": true, "text": "<p>Depends on your setup.</p>\n\n<p>If the site languages is to change under different domains you can do this.\nAdd to c...
2008/09/24
[ "https://Stackoverflow.com/questions/125756", "https://Stackoverflow.com", "https://Stackoverflow.com/users/452521/" ]
I'm looking for a way to set the default language for visitors comming to a site built in EPiServer for the first time. Not just administrators/editors in the backend, people comming to the public site.
Depends on your setup. If the site languages is to change under different domains you can do this. Add to configuration -> configSections nodes in web.config: ``` <sectionGroup name="episerver"> <section name="domainLanguageMappings" allowDefinition="MachineToApplication" allowLocation="false" type="EPiServer.Util.DomainLanguageConfigurationHandler,EPiServer" /> ``` ..and add this to episerver node in web.config: ``` <domainLanguageMappings> <map domain="site.com" language="EN" /> <map domain="site.se" language="SV" /> </domainLanguageMappings> ``` Otherwhise you can do something like this. Add to appSettings in web.config: ``` <add name="EPsDefaultLanguageBranch" key="EN"/> ```
125,785
<p>I need a function written in Excel VBA that will hash passwords using a standard algorithm such as SHA-1. Something with a simple interface like:</p> <pre><code>Public Function CreateHash(Value As String) As String ... End Function </code></pre> <p>The function needs to work on an XP workstation with Excel 2003 installed, but otherwise must use no third party components. It can reference and use DLLs that are available with XP, such as CryptoAPI. </p> <p>Does anyone know of a sample to achieve this hashing functionality?</p>
[ { "answer_id": 482150, "author": "Chris", "author_id": 59198, "author_profile": "https://Stackoverflow.com/users/59198", "pm_score": 6, "selected": false, "text": "<p>Here's a module for calculating SHA1 hashes that is usable for Excel formulas eg. '=SHA1HASH(\"test\")'. To use it, make ...
2008/09/24
[ "https://Stackoverflow.com/questions/125785", "https://Stackoverflow.com", "https://Stackoverflow.com/users/13087/" ]
I need a function written in Excel VBA that will hash passwords using a standard algorithm such as SHA-1. Something with a simple interface like: ``` Public Function CreateHash(Value As String) As String ... End Function ``` The function needs to work on an XP workstation with Excel 2003 installed, but otherwise must use no third party components. It can reference and use DLLs that are available with XP, such as CryptoAPI. Does anyone know of a sample to achieve this hashing functionality?
Here's a module for calculating SHA1 hashes that is usable for Excel formulas eg. '=SHA1HASH("test")'. To use it, make a new module called 'module\_sha1' and copy and paste it all in. This is based on some VBA code from <http://vb.wikia.com/wiki/SHA-1.bas>, with changes to support passing it a string, and executable from formulas in Excel cells. ``` ' Based on: http://vb.wikia.com/wiki/SHA-1.bas Option Explicit Private Type FourBytes A As Byte B As Byte C As Byte D As Byte End Type Private Type OneLong L As Long End Type Function HexDefaultSHA1(Message() As Byte) As String Dim H1 As Long, H2 As Long, H3 As Long, H4 As Long, H5 As Long DefaultSHA1 Message, H1, H2, H3, H4, H5 HexDefaultSHA1 = DecToHex5(H1, H2, H3, H4, H5) End Function Function HexSHA1(Message() As Byte, ByVal Key1 As Long, ByVal Key2 As Long, ByVal Key3 As Long, ByVal Key4 As Long) As String Dim H1 As Long, H2 As Long, H3 As Long, H4 As Long, H5 As Long xSHA1 Message, Key1, Key2, Key3, Key4, H1, H2, H3, H4, H5 HexSHA1 = DecToHex5(H1, H2, H3, H4, H5) End Function Sub DefaultSHA1(Message() As Byte, H1 As Long, H2 As Long, H3 As Long, H4 As Long, H5 As Long) xSHA1 Message, &H5A827999, &H6ED9EBA1, &H8F1BBCDC, &HCA62C1D6, H1, H2, H3, H4, H5 End Sub Sub xSHA1(Message() As Byte, ByVal Key1 As Long, ByVal Key2 As Long, ByVal Key3 As Long, ByVal Key4 As Long, H1 As Long, H2 As Long, H3 As Long, H4 As Long, H5 As Long) 'CA62C1D68F1BBCDC6ED9EBA15A827999 + "abc" = "A9993E36 4706816A BA3E2571 7850C26C 9CD0D89D" '"abc" = "A9993E36 4706816A BA3E2571 7850C26C 9CD0D89D" Dim U As Long, P As Long Dim FB As FourBytes, OL As OneLong Dim i As Integer Dim W(80) As Long Dim A As Long, B As Long, C As Long, D As Long, E As Long Dim T As Long H1 = &H67452301: H2 = &HEFCDAB89: H3 = &H98BADCFE: H4 = &H10325476: H5 = &HC3D2E1F0 U = UBound(Message) + 1: OL.L = U32ShiftLeft3(U): A = U \ &H20000000: LSet FB = OL 'U32ShiftRight29(U) ReDim Preserve Message(0 To (U + 8 And -64) + 63) Message(U) = 128 U = UBound(Message) Message(U - 4) = A Message(U - 3) = FB.D Message(U - 2) = FB.C Message(U - 1) = FB.B Message(U) = FB.A While P < U For i = 0 To 15 FB.D = Message(P) FB.C = Message(P + 1) FB.B = Message(P + 2) FB.A = Message(P + 3) LSet OL = FB W(i) = OL.L P = P + 4 Next i For i = 16 To 79 W(i) = U32RotateLeft1(W(i - 3) Xor W(i - 8) Xor W(i - 14) Xor W(i - 16)) Next i A = H1: B = H2: C = H3: D = H4: E = H5 For i = 0 To 19 T = U32Add(U32Add(U32Add(U32Add(U32RotateLeft5(A), E), W(i)), Key1), ((B And C) Or ((Not B) And D))) E = D: D = C: C = U32RotateLeft30(B): B = A: A = T Next i For i = 20 To 39 T = U32Add(U32Add(U32Add(U32Add(U32RotateLeft5(A), E), W(i)), Key2), (B Xor C Xor D)) E = D: D = C: C = U32RotateLeft30(B): B = A: A = T Next i For i = 40 To 59 T = U32Add(U32Add(U32Add(U32Add(U32RotateLeft5(A), E), W(i)), Key3), ((B And C) Or (B And D) Or (C And D))) E = D: D = C: C = U32RotateLeft30(B): B = A: A = T Next i For i = 60 To 79 T = U32Add(U32Add(U32Add(U32Add(U32RotateLeft5(A), E), W(i)), Key4), (B Xor C Xor D)) E = D: D = C: C = U32RotateLeft30(B): B = A: A = T Next i H1 = U32Add(H1, A): H2 = U32Add(H2, B): H3 = U32Add(H3, C): H4 = U32Add(H4, D): H5 = U32Add(H5, E) Wend End Sub Function U32Add(ByVal A As Long, ByVal B As Long) As Long If (A Xor B) < 0 Then U32Add = A + B Else U32Add = (A Xor &H80000000) + B Xor &H80000000 End If End Function Function U32ShiftLeft3(ByVal A As Long) As Long U32ShiftLeft3 = (A And &HFFFFFFF) * 8 If A And &H10000000 Then U32ShiftLeft3 = U32ShiftLeft3 Or &H80000000 End Function Function U32ShiftRight29(ByVal A As Long) As Long U32ShiftRight29 = (A And &HE0000000) \ &H20000000 And 7 End Function Function U32RotateLeft1(ByVal A As Long) As Long U32RotateLeft1 = (A And &H3FFFFFFF) * 2 If A And &H40000000 Then U32RotateLeft1 = U32RotateLeft1 Or &H80000000 If A And &H80000000 Then U32RotateLeft1 = U32RotateLeft1 Or 1 End Function Function U32RotateLeft5(ByVal A As Long) As Long U32RotateLeft5 = (A And &H3FFFFFF) * 32 Or (A And &HF8000000) \ &H8000000 And 31 If A And &H4000000 Then U32RotateLeft5 = U32RotateLeft5 Or &H80000000 End Function Function U32RotateLeft30(ByVal A As Long) As Long U32RotateLeft30 = (A And 1) * &H40000000 Or (A And &HFFFC) \ 4 And &H3FFFFFFF If A And 2 Then U32RotateLeft30 = U32RotateLeft30 Or &H80000000 End Function Function DecToHex5(ByVal H1 As Long, ByVal H2 As Long, ByVal H3 As Long, ByVal H4 As Long, ByVal H5 As Long) As String Dim H As String, L As Long DecToHex5 = "00000000 00000000 00000000 00000000 00000000" H = Hex(H1): L = Len(H): Mid(DecToHex5, 9 - L, L) = H H = Hex(H2): L = Len(H): Mid(DecToHex5, 18 - L, L) = H H = Hex(H3): L = Len(H): Mid(DecToHex5, 27 - L, L) = H H = Hex(H4): L = Len(H): Mid(DecToHex5, 36 - L, L) = H H = Hex(H5): L = Len(H): Mid(DecToHex5, 45 - L, L) = H End Function ' Convert the string into bytes so we can use the above functions ' From Chris Hulbert: http://splinter.com.au/blog Public Function SHA1HASH(str) Dim i As Integer Dim arr() As Byte ReDim arr(0 To Len(str) - 1) As Byte For i = 0 To Len(str) - 1 arr(i) = Asc(Mid(str, i + 1, 1)) Next i SHA1HASH = Replace(LCase(HexDefaultSHA1(arr)), " ", "") End Function ```
125,806
<p>First, yes I know about <a href="https://stackoverflow.com/questions/50182/linuxx11-input-library-without-creating-a-window">this question</a>, but I'm looking for a bit more information that that. I have actually, a fairly similar problem, in that I need to be able to capture input for mouse/keyboard/joystick, and I'd also like to avoid SDL if at all possible. I was more or less wondering if anyone knows where I can get some decent primers on handling input from devices in Linux, perhaps even some tutorials. SDL works great for cross-platform input handling, but I'm not going to be using anything else at all from SDL, so I'd like to cut it out altogether. Suggestion, comments, and help are all appreciated. Thanks!</p> <p>Edit for clarity:</p> <p>The point is to capture mouse motion, keyboard press/release, mouse clicks, and potentially joystick handling for a game.</p>
[ { "answer_id": 125830, "author": "dsm", "author_id": 7780, "author_profile": "https://Stackoverflow.com/users/7780", "pm_score": 1, "selected": false, "text": "<p>You could start by reading <a href=\"http://tldp.org/LDP/khg/HyperNews/get/devices/devices.html\" rel=\"nofollow noreferrer\"...
2008/09/24
[ "https://Stackoverflow.com/questions/125806", "https://Stackoverflow.com", "https://Stackoverflow.com/users/14838/" ]
First, yes I know about [this question](https://stackoverflow.com/questions/50182/linuxx11-input-library-without-creating-a-window), but I'm looking for a bit more information that that. I have actually, a fairly similar problem, in that I need to be able to capture input for mouse/keyboard/joystick, and I'd also like to avoid SDL if at all possible. I was more or less wondering if anyone knows where I can get some decent primers on handling input from devices in Linux, perhaps even some tutorials. SDL works great for cross-platform input handling, but I'm not going to be using anything else at all from SDL, so I'd like to cut it out altogether. Suggestion, comments, and help are all appreciated. Thanks! Edit for clarity: The point is to capture mouse motion, keyboard press/release, mouse clicks, and potentially joystick handling for a game.
Using the link below look at the function void kGUISystemX::Loop(void) This is my main loop for getting input via keyboard and mouse using X Windows on Linux. <http://code.google.com/p/kgui/source/browse/trunk/kguilinux.cpp> Here is a snippet: ``` if(XPending(m_display)) { XNextEvent(m_display, &m_e); switch(m_e.type) { case MotionNotify: m_mousex=m_e.xmotion.x; m_mousey=m_e.xmotion.y; break; case ButtonPress: switch(m_e.xbutton.button) { case Button1: m_mouseleft=true; break; case Button3: m_mouseright=true; break; case Button4:/* middle mouse wheel moved */ m_mousewheel=1; break; case Button5:/* middle mouse wheel moved */ m_mousewheel=-1; break; } break; case ButtonRelease: switch(m_e.xbutton.button) { case Button1: m_mouseleft=false; break; case Button3: m_mouseright=false; break; } break; case KeyPress: { XKeyEvent *ke; int ks; int key; ke=&m_e.xkey; kGUI::SetKeyShift((ke->state&ShiftMask)!=0); kGUI::SetKeyControl((ke->state&ControlMask)!=0); ks=XLookupKeysym(ke,(ke->state&ShiftMask)?1:0); ...... ```
125,828
<p>I'm trying to start an external application through <code>system()</code> - for example, <code>system("ls")</code>. I would like to capture its output as it happens so I can send it to another function for further processing. What's the best way to do that in C/C++?</p>
[ { "answer_id": 125851, "author": "Blank", "author_id": 19521, "author_profile": "https://Stackoverflow.com/users/19521", "pm_score": 0, "selected": false, "text": "<p>I'm not entirely certain that its possible in standard C, as two different processes don't typically share memory space. ...
2008/09/24
[ "https://Stackoverflow.com/questions/125828", "https://Stackoverflow.com", "https://Stackoverflow.com/users/10010/" ]
I'm trying to start an external application through `system()` - for example, `system("ls")`. I would like to capture its output as it happens so I can send it to another function for further processing. What's the best way to do that in C/C++?
From the popen manual: ``` #include <stdio.h> FILE *popen(const char *command, const char *type); int pclose(FILE *stream); ```
125,850
<p>I have this RewriteRule that works too well :-)</p> <pre><code>RewriteRule ^([^/]*)/$ /script.html?id=$1 [L] </code></pre> <p>The bad thing about this rule is that it also matches physical directories which I don't want.</p> <p>How can I tell the <code>mod_rewrite</code> to ignore physical directories and apply the above rule only when the directory matched does not exist?</p>
[ { "answer_id": 125864, "author": "ctcherry", "author_id": 10322, "author_profile": "https://Stackoverflow.com/users/10322", "pm_score": 3, "selected": true, "text": "<p>Take a look at <a href=\"http://httpd.apache.org/docs/2.2/mod/mod_rewrite.html#rewritecond\" rel=\"nofollow noreferrer\...
2008/09/24
[ "https://Stackoverflow.com/questions/125850", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
I have this RewriteRule that works too well :-) ``` RewriteRule ^([^/]*)/$ /script.html?id=$1 [L] ``` The bad thing about this rule is that it also matches physical directories which I don't want. How can I tell the `mod_rewrite` to ignore physical directories and apply the above rule only when the directory matched does not exist?
Take a look at [RewriteCond](http://httpd.apache.org/docs/2.2/mod/mod_rewrite.html#rewritecond). Put the following before your rule to exempt out directories and files ``` RewriteCond %{REQUEST_FILENAME} !-d RewriteCond %{REQUEST_FILENAME} !-f ```
125,857
<p>Having a problem getting a TreeView control to display node images. The code below works sometimes but fails to show any image at other times.</p> <pre><code> private TreeNode AddNodeForCore(TreeNode root, Core c) { string key = GetImageKey(c); TreeNode t = root.Nodes.Add(c.Name, c.Name, key, key); t.Tag = c; return t; } </code></pre> <p>Note that when it fails, the TreeView fails to show any images for any node. The TreeView does have an ImageList assigned to it, and the image key is definitely in the images collection.</p> <p>Edit:<br> My google-fu is weak. Can't believe I didn't find that answer myself.</p>
[ { "answer_id": 125871, "author": "VVS", "author_id": 21038, "author_profile": "https://Stackoverflow.com/users/21038", "pm_score": 2, "selected": false, "text": "<p>A quick google search found this answer: <a href=\"http://forums.microsoft.com/MSDN/ShowPost.aspx?siteid=1&amp;PostID=96596...
2008/09/24
[ "https://Stackoverflow.com/questions/125857", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1389021/" ]
Having a problem getting a TreeView control to display node images. The code below works sometimes but fails to show any image at other times. ``` private TreeNode AddNodeForCore(TreeNode root, Core c) { string key = GetImageKey(c); TreeNode t = root.Nodes.Add(c.Name, c.Name, key, key); t.Tag = c; return t; } ``` Note that when it fails, the TreeView fails to show any images for any node. The TreeView does have an ImageList assigned to it, and the image key is definitely in the images collection. Edit: My google-fu is weak. Can't believe I didn't find that answer myself.
The helpful bit of the googled posts above is in fact: "This is a known bug in the Windows XP visual styles implementation. Certain controls, like ImageList, do not get properly initialized when they've been created before the app calls Application.EnableVisualStyles(). The normal Main() implementation in a C#'s Program.cs avoids this. Thanks for posting back!" So basically, guarantee that Application.EnableVisualStyles() is called before you initialise your imagelist.
125,875
<p>I need to change the credentials of an already existing Windows service using C#. I am aware of two different ways of doing this.</p> <ol> <li>ChangeServiceConfig, see <a href="http://www.pinvoke.net/default.aspx/advapi32.ChangeServiceConfig" rel="nofollow noreferrer">ChangeServiceConfig on pinvoke.net</a></li> <li>ManagementObject.InvokeMethod using Change as the method name.</li> </ol> <p>Neither seems a very "friendly" way of doing this and I was wondering if I am missing another and better way to do this.</p>
[ { "answer_id": 126549, "author": "Magnus Johansson", "author_id": 3584, "author_profile": "https://Stackoverflow.com/users/3584", "pm_score": 3, "selected": false, "text": "<p>Here is one quick and dirty method using the System.Management classes.</p>\n\n<pre><code>using System;\nusing S...
2008/09/24
[ "https://Stackoverflow.com/questions/125875", "https://Stackoverflow.com", "https://Stackoverflow.com/users/19676/" ]
I need to change the credentials of an already existing Windows service using C#. I am aware of two different ways of doing this. 1. ChangeServiceConfig, see [ChangeServiceConfig on pinvoke.net](http://www.pinvoke.net/default.aspx/advapi32.ChangeServiceConfig) 2. ManagementObject.InvokeMethod using Change as the method name. Neither seems a very "friendly" way of doing this and I was wondering if I am missing another and better way to do this.
Here is one quick and dirty method using the System.Management classes. ``` using System; using System.Collections.Generic; using System.Text; using System.Management; namespace ServiceTest { class Program { static void Main(string[] args) { string theServiceName = "My Windows Service"; string objectPath = string.Format("Win32_Service.Name='{0}'", theServiceName); using (ManagementObject mngService = new ManagementObject(new ManagementPath(objectPath))) { object[] wmiParameters = new object[11]; wmiParameters[6] = @"domain\username"; wmiParameters[7] = "password"; mngService.InvokeMethod("Change", wmiParameters); } } } } ```
125,878
<p>I am new to java so excuse my lame questions:)</p> <p>I am trying to build a web service in Java NetBeans 6.1 , but I have some troubles with configuration parameters ( like .settings in .net).</p> <p>What is the right way to save and access such settings in a java web service.</p> <p>Is there a way to read context parameters from web.xml in a web method?</p> <p>If no what are the alternatives for storing your configuration variables like pathnames ?</p> <p>Thank you</p>
[ { "answer_id": 125949, "author": "Lars Westergren", "author_id": 15627, "author_profile": "https://Stackoverflow.com/users/15627", "pm_score": 2, "selected": false, "text": "<p>If you are using servlets, you can configure parameters in web.xml:</p>\n\n<pre><code>&lt;servlet&gt;\n &lt;se...
2008/09/24
[ "https://Stackoverflow.com/questions/125878", "https://Stackoverflow.com", "https://Stackoverflow.com/users/18834/" ]
I am new to java so excuse my lame questions:) I am trying to build a web service in Java NetBeans 6.1 , but I have some troubles with configuration parameters ( like .settings in .net). What is the right way to save and access such settings in a java web service. Is there a way to read context parameters from web.xml in a web method? If no what are the alternatives for storing your configuration variables like pathnames ? Thank you
If you are using servlets, you can configure parameters in web.xml: ``` <servlet> <servlet-name>jsp</servlet-name> <servlet-class>org.apache.jasper.servlet.JspServlet</servlet-class> <init-param> <param-name>fork</param-name> <param-value>false</param-value> </init-param> </servlet> ``` These properties will be passed in a ServletConfig object to your servlet's "init" method. Another way is to read your system's environment variables with ``` System.getProperty(String name); ``` But this is not recommended for other than small programs and tests. There is also the Properties API if you want to use ".properties" files. <http://java.sun.com/javase/6/docs/api/java/util/Properties.html> Finally, I believe looking up configurations with JNDI is pretty common when developing modern web service applications, Netbeans and app containers have pretty good support for that. Google it.
125,885
<p>I'm working on a fairly complex project, a custom encryption routine if you will (just for fun) and I've run into this issue in designing my code layout.</p> <p>I have a number of functions that I want to be able to call by index. Specifically, I need to be able to call one randomly for the encrypt process, but then address that by a specific index in the decrypt process.</p> <p>I was considering a classic function array, but my main concern is that a function array would be tricky to maintain, and a little ugly. (The goal is to get each function pair in a separate file, to reduce compile times and make the code easier to manage.) Does anyone have a more elegant C++ solution as an alternative to a function array? Speed isn't really an issue, I'm more worried about maintainability.</p> <p>-Nicholas</p>
[ { "answer_id": 125906, "author": "Khoth", "author_id": 20686, "author_profile": "https://Stackoverflow.com/users/20686", "pm_score": 0, "selected": false, "text": "<p>An object with an operator() method defined can act a lot like a function but be generally nicer to work with.</p>\n" }...
2008/09/24
[ "https://Stackoverflow.com/questions/125885", "https://Stackoverflow.com", "https://Stackoverflow.com/users/19521/" ]
I'm working on a fairly complex project, a custom encryption routine if you will (just for fun) and I've run into this issue in designing my code layout. I have a number of functions that I want to be able to call by index. Specifically, I need to be able to call one randomly for the encrypt process, but then address that by a specific index in the decrypt process. I was considering a classic function array, but my main concern is that a function array would be tricky to maintain, and a little ugly. (The goal is to get each function pair in a separate file, to reduce compile times and make the code easier to manage.) Does anyone have a more elegant C++ solution as an alternative to a function array? Speed isn't really an issue, I'm more worried about maintainability. -Nicholas
You could write something like: ``` class EncryptionFunction { public: virtual Foo Run(Bar input) = 0; virtual ~MyFunction() {} }; class SomeSpecificEncryptionFunction : public EncryptionFunction { // override the Run function }; // ... std::vector<EncryptionFunction*> functions; // ... functions[2]->Run(data); ``` You could use `operator()` instead of `Run` as the function name, if you prefer.
125,921
<p>I'm trying to handle Winsock_Connect event (Actually I need it in Excel macro) using the following code:</p> <pre><code>Dim Winsock1 As Winsock 'Object type definition Sub Init() Set Winsock1 = CreateObject("MSWinsock.Winsock") 'Object initialization Winsock1.RemoteHost = "MyHost" Winsock1.RemotePort = "22" Winsock1.Connect Do While (Winsock1.State &lt;&gt; sckConnected) Sleep 200 Loop End Sub 'Callback handler Private Sub Winsock1_Connect() MsgBox "Winsock1::Connect" End Sub </code></pre> <p>But it never goes to Winsock1_Connect subroutine although Winsock1.State is "Connected". I want to use standard MS library because I don't have administrative rights on my PC and I'm not able to register some custom libraries. Can anybody tell me, where I'm wrong?</p>
[ { "answer_id": 125975, "author": "Nescio", "author_id": 14484, "author_profile": "https://Stackoverflow.com/users/14484", "pm_score": 3, "selected": true, "text": "<p>Are you stuck using MSWinsock?<br>\n<a href=\"http://www.ostrosoft.com/oswinsck/oswinsck_reference.aspx\" rel=\"nofollow ...
2008/09/24
[ "https://Stackoverflow.com/questions/125921", "https://Stackoverflow.com", "https://Stackoverflow.com/users/21530/" ]
I'm trying to handle Winsock\_Connect event (Actually I need it in Excel macro) using the following code: ``` Dim Winsock1 As Winsock 'Object type definition Sub Init() Set Winsock1 = CreateObject("MSWinsock.Winsock") 'Object initialization Winsock1.RemoteHost = "MyHost" Winsock1.RemotePort = "22" Winsock1.Connect Do While (Winsock1.State <> sckConnected) Sleep 200 Loop End Sub 'Callback handler Private Sub Winsock1_Connect() MsgBox "Winsock1::Connect" End Sub ``` But it never goes to Winsock1\_Connect subroutine although Winsock1.State is "Connected". I want to use standard MS library because I don't have administrative rights on my PC and I'm not able to register some custom libraries. Can anybody tell me, where I'm wrong?
Are you stuck using MSWinsock? [Here](http://www.ostrosoft.com/oswinsck/oswinsck_reference.aspx) is a site/tutorial using a custom winsock object. Also... You need to declare Winsock1 **WithEvents** within a "Class" module: ``` Private WithEvents Winsock1 As Winsock ``` And finally, make sure you reference the winsock ocx control. Tools -> References -> Browse -> %SYSEM%\MSWINSCK.OCX
125,934
<p>I'm writing an application to start and monitor other applications in C#. I'm using the System.Diagnostics.Process class to start applications and then monitor the applications using the Process.Responding property to poll the state of the application every 100 milisecs. I use Process.CloseMainWindow to stop the application or Process.Kill to kill it if it's not responding.</p> <p>I've noticed a weird behaviour where sometimes the process object gets into a state where the responding property always returns true even when the underlying process hangs in a loop and where it doesn't respond to CloseMainWindow.</p> <p>One way to reproduce it is to poll the Responding property right after starting the process instance. So for example</p> <pre><code>_process.Start(); bool responding = _process.Responding; </code></pre> <p>will reproduce the error state while</p> <pre><code>_process.Start(); Thread.Sleep(1000); bool responding = _process.Responding; </code></pre> <p>will work. Reducing the sleep period to 500 will introduce the error state again.</p> <p>Something in calling _process.Responding too fast after starting seems to prevent the object from getting the right windows message queue handler. I guess I need to wait for _process.Start to finish doing it's asynchronous work. Is there a better way to wait for this than calling Thread.Sleep ? I'm not too confident that the 1000 ms will always be enough.</p>
[ { "answer_id": 125961, "author": "Jarod Elliott", "author_id": 1061, "author_profile": "https://Stackoverflow.com/users/1061", "pm_score": 2, "selected": false, "text": "<p>I think it may be better to enhance the check for _process.Responding so that you only try to stop/kill the process...
2008/09/24
[ "https://Stackoverflow.com/questions/125934", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3320/" ]
I'm writing an application to start and monitor other applications in C#. I'm using the System.Diagnostics.Process class to start applications and then monitor the applications using the Process.Responding property to poll the state of the application every 100 milisecs. I use Process.CloseMainWindow to stop the application or Process.Kill to kill it if it's not responding. I've noticed a weird behaviour where sometimes the process object gets into a state where the responding property always returns true even when the underlying process hangs in a loop and where it doesn't respond to CloseMainWindow. One way to reproduce it is to poll the Responding property right after starting the process instance. So for example ``` _process.Start(); bool responding = _process.Responding; ``` will reproduce the error state while ``` _process.Start(); Thread.Sleep(1000); bool responding = _process.Responding; ``` will work. Reducing the sleep period to 500 will introduce the error state again. Something in calling \_process.Responding too fast after starting seems to prevent the object from getting the right windows message queue handler. I guess I need to wait for \_process.Start to finish doing it's asynchronous work. Is there a better way to wait for this than calling Thread.Sleep ? I'm not too confident that the 1000 ms will always be enough.
Now, I need to check this out later, but I am sure there is a method that tells the thread to wait until it is ready for input. Are you monitoring GUI processes only? Isn't [Process.WaitForInputIdle](http://msdn.microsoft.com/en-us/library/kcdbkyt4.aspx) of any help to you? Or am I missing the point? :) Update ------ Following a chit-chat on Twitter (or tweet-tweet?) with Mendelt I thought I should update my answer so the community is fully aware.. * `WaitForInputIdle` will only work on applications that have a GUI. * You specify the time to wait, and the method returns a bool if the process reaches an idle state within that time frame, you can obviously use this to loop if required, or handle as appropriate. Hope that helps :)
125,951
<p>What is a good command line tool to create screenshots of websites on Linux? I need to automatically generate screenshots of websites without human interaction. The only tool that I found was <a href="http://khtml2png.sourceforge.net/" rel="noreferrer">khtml2png</a>, but I wonder if there are others that aren't based on khtml (i.e. have good JavaScript support, ...).</p>
[ { "answer_id": 126000, "author": "Paul Whelan", "author_id": 3050, "author_profile": "https://Stackoverflow.com/users/3050", "pm_score": 2, "selected": false, "text": "<p>I know its not a command line tool but you could easily script up something to use <a href=\"http://browsershots.org/...
2008/09/24
[ "https://Stackoverflow.com/questions/125951", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4936/" ]
What is a good command line tool to create screenshots of websites on Linux? I need to automatically generate screenshots of websites without human interaction. The only tool that I found was [khtml2png](http://khtml2png.sourceforge.net/), but I wonder if there are others that aren't based on khtml (i.e. have good JavaScript support, ...).
A little more detail might be useful... Start a firefox (or other browser) in an X session, either on your console or using a vncserver. You can use the `--height` and `--width` options to set the size of the window to full screen. Another firefox command can be used to set the URL being displayed in the first firefox window. Now you can grab the screen image with one of several commands, such as the "import" command from the Imagemagick package, or using gimp, or fbgrab, or xv. ``` #!/bin/sh # start a server with a specific DISPLAY vncserver :11 -geometry 1024x768 # start firefox in this vnc session firefox --display :11 # read URLs from a data file in a loop count=1 while read url do # send URL to the firefox session firefox --display :11 $url # take a picture after waiting a bit for the load to finish sleep 5 import -window root image$count.jpg count=`expr $count + 1` done < url_list.txt # clean up when done vncserver -kill :11 ```
125,957
<p>I know this is not directly a programming question, but people on stackoverflow seems to be able to answer any question.</p> <p>I have a server running Centos 5.2 64 bit. Pretty powerful dual core 2 server with 4GB memory. It mostly serves static files, flash and pictures. When I use lighttpd it easily serves over 80 MB/sec, but when I test with nginx it drops down to less than 20 MB/sec.</p> <p>My setup is pretty straight forward, uses the default setup file, and I have added the following</p> <pre><code>user lighttpd; worker_processes 8; worker_rlimit_nofile 206011; #worker_rlimit_nofile 110240; error_log /var/log/nginx/error.log; #error_log /var/log/nginx/error.log notice; #error_log /var/log/nginx/error.log info; pid /var/run/nginx.pid; events { worker_connections 4096; } http { .... keepalive_timeout 2; .... } </code></pre> <p>And I thought nginx was supposed to be at least as powerful, so I must be not doing something.</p>
[ { "answer_id": 129855, "author": "Ross", "author_id": 14794, "author_profile": "https://Stackoverflow.com/users/14794", "pm_score": 2, "selected": false, "text": "<p>Perhaps lighttpd is using some kind of caching? There's a great article <a href=\"http://www.igvita.com/2008/02/11/nginx-...
2008/09/24
[ "https://Stackoverflow.com/questions/125957", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6801/" ]
I know this is not directly a programming question, but people on stackoverflow seems to be able to answer any question. I have a server running Centos 5.2 64 bit. Pretty powerful dual core 2 server with 4GB memory. It mostly serves static files, flash and pictures. When I use lighttpd it easily serves over 80 MB/sec, but when I test with nginx it drops down to less than 20 MB/sec. My setup is pretty straight forward, uses the default setup file, and I have added the following ``` user lighttpd; worker_processes 8; worker_rlimit_nofile 206011; #worker_rlimit_nofile 110240; error_log /var/log/nginx/error.log; #error_log /var/log/nginx/error.log notice; #error_log /var/log/nginx/error.log info; pid /var/run/nginx.pid; events { worker_connections 4096; } http { .... keepalive_timeout 2; .... } ``` And I thought nginx was supposed to be at least as powerful, so I must be not doing something.
When you reload your nginx (kiil -HUP) you'll get something like this in your error logs ``` 2008/10/01 03:57:26 [notice] 4563#0: signal 1 (SIGHUP) received, reconfiguring 2008/10/01 03:57:26 [notice] 4563#0: reconfiguring 2008/10/01 03:57:26 [notice] 4563#0: using the "epoll" event method 2008/10/01 03:57:26 [notice] 4563#0: start worker processes 2008/10/01 03:57:26 [notice] 4563#0: start worker process 3870 ``` What event method is your nginx compiled to use? Are you doing any access\_log'ing ? Consider adding buffer=32k, which will reduce the contention on the write lock for the log file. Consider reducing the number of workers, it sounds counter intuitive, but the workers need to synchronize with each other for sys calls like accept(). Try reducing the number of workers, ideally I would suggest 1. You might try explicitly setting the read and write socket buffers on the listening socket, see <http://wiki.codemongers.com/NginxHttpCoreModule#listen>
125,964
<p>Is there an easier way to step through the code than to start the service through the Windows Service Control Manager and then attaching the debugger to the thread? It's kind of cumbersome and I'm wondering if there is a more straightforward approach.</p>
[ { "answer_id": 125980, "author": "akauppi", "author_id": 14455, "author_profile": "https://Stackoverflow.com/users/14455", "pm_score": 3, "selected": false, "text": "<p>You can also start the service through the command prompt (sc.exe).</p>\n\n<p>Personally, I'd run the code as a stand-a...
2008/09/24
[ "https://Stackoverflow.com/questions/125964", "https://Stackoverflow.com", "https://Stackoverflow.com/users/16440/" ]
Is there an easier way to step through the code than to start the service through the Windows Service Control Manager and then attaching the debugger to the thread? It's kind of cumbersome and I'm wondering if there is a more straightforward approach.
If I want to quickly debug the service, I just drop in a `Debugger.Break()` in there. When that line is reached, it will drop me back to VS. Don't forget to remove that line when you are done. **UPDATE:** As an alternative to `#if DEBUG` pragmas, you can also use `Conditional("DEBUG_SERVICE")` attribute. ``` [Conditional("DEBUG_SERVICE")] private static void DebugMode() { Debugger.Break(); } ``` On your `OnStart`, just call this method: ``` public override void OnStart() { DebugMode(); /* ... do the rest */ } ``` There, the code will only be enabled during Debug builds. While you're at it, it might be useful to create a separate Build Configuration for service debugging.
125,997
<p>I'm a newbie in C# bu I'm experienced Delphi developer. In Delphi I can use same code for MenuItem and ToolButton using TAction.OnExecute event and I can disable/enable MenuItem and ToolButton together using TAction.OnUpdate event. Is there a similar way to do this in C# without using external libraries? Or more - How C# developers share code between different controls? </p> <hr> <p>Ok, may be I write my question in wrong way. I want to know not witch property to use (I know about Enabled property) but I want to know on witch event I should attach to if I want to enable/disable more than one control. In delphi TAction.OnUpdate event ocurs when Application is idle - is there similar event in C#?</p>
[ { "answer_id": 126008, "author": "VVS", "author_id": 21038, "author_profile": "https://Stackoverflow.com/users/21038", "pm_score": 0, "selected": false, "text": "<p>You can enable or disable a control and all its children by setting its <a href=\"http://msdn.microsoft.com/en-us/library/s...
2008/09/24
[ "https://Stackoverflow.com/questions/125997", "https://Stackoverflow.com", "https://Stackoverflow.com/users/21540/" ]
I'm a newbie in C# bu I'm experienced Delphi developer. In Delphi I can use same code for MenuItem and ToolButton using TAction.OnExecute event and I can disable/enable MenuItem and ToolButton together using TAction.OnUpdate event. Is there a similar way to do this in C# without using external libraries? Or more - How C# developers share code between different controls? --- Ok, may be I write my question in wrong way. I want to know not witch property to use (I know about Enabled property) but I want to know on witch event I should attach to if I want to enable/disable more than one control. In delphi TAction.OnUpdate event ocurs when Application is idle - is there similar event in C#?
Try the a modification of the command pattern: ``` public abstract class ToolStripItemCommand { private bool enabled = true; private bool visible = true; private readonly List<ToolStripItem> controls; protected ToolStripItemCommand() { controls = new List<ToolStripItem>(); } public void RegisterControl(ToolStripItem item, string eventName) { item.Click += delegate { Execute(); }; controls.Add(item); } public bool Enabled { get { return enabled; } set { enabled = value; foreach (ToolStripItem item in controls) item.Enabled = value; } } public bool Visible { get { return visible; } set { visible = value; foreach (ToolStripItem item in controls) item.Visible = value; } } protected abstract void Execute(); } ``` Your implementations of this command can be stateful in order to support your view's state. This also enables the ability to build "undo" into your form. Here's some toy code that consumes this: ``` private ToolStripItemCommand fooCommand; private void wireUpCommands() { fooCommand = new HelloWorldCommand(); fooCommand.RegisterControl(fooToolStripMenuItem, "Click"); fooCommand.RegisterControl(fooToolStripButton, "Click"); } private void toggleEnabledClicked(object sender, EventArgs e) { fooCommand.Enabled = !fooCommand.Enabled; } private void toggleVisibleClicked(object sender, EventArgs e) { fooCommand.Visible = !fooCommand.Visible; } ``` HelloWorldCommand: ``` public class HelloWorldCommand : ToolStripItemCommand { #region Overrides of ControlCommand protected override void Execute() { MessageBox.Show("Hello World"); } #endregion } ``` It's unfortunate that Control and ToolStripItem do not share a common interface since they both have "Enabled" and "Visible" properties. In order to support both types, you would have to composite a command for both, or use reflection. Both solutions infringe on the elegance afforded by simple inheritance.
126,005
<p>Specifically I have a PHP command-line script that at a certain point requires input from the user. I would like to be able to execute an external editor (such as vi), and wait for the editor to finish execution before resuming the script.</p> <p>My basic idea was to use a temporary file to do the editing in, and to retrieve the contents of the file afterwards. Something along the lines of:</p> <pre><code>$filename = '/tmp/script_' . time() . '.tmp'; get_user_input ($filename); $input = file_get_contents ($filename); unlink ($filename); </code></pre> <p>I suspect that this isn't possible from a PHP command-line script, however I'm hoping that there's some sort of shell scripting trick that can be employed to achieve the same effect.</p> <p>Suggestions for how this can be achieved in other scripting languages are also more than welcome.</p>
[ { "answer_id": 126031, "author": "lms", "author_id": 21359, "author_profile": "https://Stackoverflow.com/users/21359", "pm_score": 0, "selected": false, "text": "<pre><code>system('vi');\n</code></pre>\n\n<p><a href=\"http://www.php.net/system\" rel=\"nofollow noreferrer\">http://www.php...
2008/09/24
[ "https://Stackoverflow.com/questions/126005", "https://Stackoverflow.com", "https://Stackoverflow.com/users/10942/" ]
Specifically I have a PHP command-line script that at a certain point requires input from the user. I would like to be able to execute an external editor (such as vi), and wait for the editor to finish execution before resuming the script. My basic idea was to use a temporary file to do the editing in, and to retrieve the contents of the file afterwards. Something along the lines of: ``` $filename = '/tmp/script_' . time() . '.tmp'; get_user_input ($filename); $input = file_get_contents ($filename); unlink ($filename); ``` I suspect that this isn't possible from a PHP command-line script, however I'm hoping that there's some sort of shell scripting trick that can be employed to achieve the same effect. Suggestions for how this can be achieved in other scripting languages are also more than welcome.
You can redirect the editor's output to the terminal: ``` system("vim > `tty`"); ```
126,028
<p>We have a 3D viewer that uses OpenGL, but our clients sometimes complain about it "not working". We suspect that most of these issues stem from them trying to use, what is in effect a modern 3d realtime game, on a businiss laptop computer.</p> <p><strong>How can we, in the windows msi installer we use, check for support for openGL?</strong></p> <p>And as a side note, if you can answer "List of OpenGL supported graphic cards?", that would also be greate. Strange that google doesnt help here..</p>
[ { "answer_id": 126082, "author": "Nils Pipenbrinck", "author_id": 15955, "author_profile": "https://Stackoverflow.com/users/15955", "pm_score": 1, "selected": false, "text": "<p>OpenGL is part of Windows since Windows NT or Win95. It's unlikely that you'll ever find a windows system wher...
2008/09/24
[ "https://Stackoverflow.com/questions/126028", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4013/" ]
We have a 3D viewer that uses OpenGL, but our clients sometimes complain about it "not working". We suspect that most of these issues stem from them trying to use, what is in effect a modern 3d realtime game, on a businiss laptop computer. **How can we, in the windows msi installer we use, check for support for openGL?** And as a side note, if you can answer "List of OpenGL supported graphic cards?", that would also be greate. Strange that google doesnt help here..
Depends on what the customers mean by "not working". It could be one of: 1. it does not install/launch at all, because of lack of some OpenGL support. 2. it launches, but crashes further on. 3. it launches, does not crash, but rendering is corrupt. 4. it launches and renders everything correctly, but performance is abysmal. All Windows versions (since 95) have OpenGL support built-in. So it's unlikely to cause situation 1) above, unless you application *requires* higher OpenGL version. However, that default OpenGL implementation is OpenGL 1.1 with *software rendering*. If user did not manually install drivers that have OpenGL support (any driver downloaded from NVIDIA/AMD/Intel site will have OpenGL), they will default to this slow and old implementation. This is quite likely to cause situations 3) and 4) above. Even if OpenGL is available, on Windows OpenGL drivers are not very robust, to say mildly. Various bugs in the drivers are very likely to cause situation 2), where doing something valid causes a crash in the driver. Here's a C++/WinAPI code snippet that creates a dummy OpenGL context and retrieves info (GL version, graphics card name, extensions etc.): ``` // setup minimal required GL HWND wnd = CreateWindow( "STATIC", "GL", WS_OVERLAPPEDWINDOW | WS_CLIPSIBLINGS | WS_CLIPCHILDREN, 0, 0, 16, 16, NULL, NULL, AfxGetInstanceHandle(), NULL ); HDC dc = GetDC( wnd ); PIXELFORMATDESCRIPTOR pfd = { sizeof(PIXELFORMATDESCRIPTOR), 1, PFD_DRAW_TO_WINDOW | PFD_SUPPORT_OPENGL, PFD_TYPE_RGBA, 32, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 16, 0, 0, PFD_MAIN_PLANE, 0, 0, 0, 0 }; int fmt = ChoosePixelFormat( dc, &pfd ); SetPixelFormat( dc, fmt, &pfd ); HGLRC rc = wglCreateContext( dc ); wglMakeCurrent( dc, rc ); // get information const char* vendor = (const char*)glGetString(GL_VENDOR); const char* renderer = (const char*)glGetString(GL_RENDERER); const char* extensions = (const char*)glGetString(GL_EXTENSIONS); const char* version = (const char*)glGetString(GL_VERSION); // DO SOMETHING WITH THOSE STRINGS HERE! // cleanup wglDeleteContext( rc ); ReleaseDC( wnd, dc ); DestroyWindow( wnd ); ``` You could somehow plug that code into your installer or application and at least check GL version for being 1.1; this will detect "driver is not installed" situation. To work around actual OpenGL driver bugs, well, you have to figure them out and work around them. Lots of work.
126,036
<p>Is there a way to know and output the stack size needed by a function at compile time in C ? Here is what I would like to know :</p> <p>Let's take some function :</p> <pre><code>void foo(int a) { char c[5]; char * s; //do something return; } </code></pre> <p>When compiling this function, I would like to know how much stack space it will consume whent it is called. This might be useful to detect the on stack declaration of a structure hiding a big buffer.</p> <p>I am looking for something that would print something like this :</p> <p>file foo.c : function foo stack usage is <code>n</code> bytes</p> <p>Is there a way not to look at the generated assembly to know that ? Or a limit that can be set for the compiler ?</p> <p>Update : I am not trying to avoid runtime stack overflow for a given process, I am looking for a way to find before runtime, if a function stack usage, as determined by the compiler, is available as an output of the compilation process.</p> <p>Let's put it another way : is it possible to know the size of all the objects local to a function ? I guess compiler optimization won't be my friend, because some variable will disappear but a superior limit is fine.</p>
[ { "answer_id": 126047, "author": "1800 INFORMATION", "author_id": 3146, "author_profile": "https://Stackoverflow.com/users/3146", "pm_score": 1, "selected": false, "text": "<p>Only the compiler would really know, since it is the guy that puts all your stuff together. You'd have to look a...
2008/09/24
[ "https://Stackoverflow.com/questions/126036", "https://Stackoverflow.com", "https://Stackoverflow.com/users/11589/" ]
Is there a way to know and output the stack size needed by a function at compile time in C ? Here is what I would like to know : Let's take some function : ``` void foo(int a) { char c[5]; char * s; //do something return; } ``` When compiling this function, I would like to know how much stack space it will consume whent it is called. This might be useful to detect the on stack declaration of a structure hiding a big buffer. I am looking for something that would print something like this : file foo.c : function foo stack usage is `n` bytes Is there a way not to look at the generated assembly to know that ? Or a limit that can be set for the compiler ? Update : I am not trying to avoid runtime stack overflow for a given process, I am looking for a way to find before runtime, if a function stack usage, as determined by the compiler, is available as an output of the compilation process. Let's put it another way : is it possible to know the size of all the objects local to a function ? I guess compiler optimization won't be my friend, because some variable will disappear but a superior limit is fine.
Linux kernel code runs on a 4K stack on x86. Hence they care. What they use to check that, is a perl script they wrote, which you may find as scripts/checkstack.pl in a recent kernel tarball (2.6.25 has got it). It runs on the output of objdump, usage documentation is in the initial comment. I think I already used it for user-space binaries ages ago, and if you know a bit of perl programming, it's easy to fix that if it is broken. Anyway, what it basically does is to look automatically at GCC's output. And the fact that kernel hackers wrote such a tool means that there is no static way to do it with GCC (or maybe that it was added very recently, but I doubt so). Btw, with objdump from the mingw project and ActivePerl, or with Cygwin, you should be able to do that also on Windows and also on binaries obtained with other compilers.
126,048
<p>I have a problem where a Web Application needs to (after interaction from the user via Javascript)<br> &nbsp;&nbsp; 1) open a Windows Forms Application<br> &nbsp;&nbsp; 2) send a parameter to the app (e.g. an ID)</p> <p>Correspondingly, the Windows Forms Application should be able to<br> &nbsp;&nbsp; 1) send parameters back to the Web Application (updating the URL is ok)<br> &nbsp;&nbsp; 2) open the Web App in a new brower, if it does not exist<br> If many browser windows are open it's important that the correct one is updated.</p> <p>Windows Forms Application is in ASP.NET<br> Browser is IE6+<br> The applications are controlled and internal for a specific organisation so it's not a question of launching a custom app. </p> <p>Question A) Is this possible?<br> Question B) How do I send parameters to an open Windows Forms Application from a Web App?<br> Question C) If updating the Web App, how do I make sure the right browser is targeted? </p>
[ { "answer_id": 126057, "author": "Sklivvz", "author_id": 7028, "author_profile": "https://Stackoverflow.com/users/7028", "pm_score": 0, "selected": false, "text": "<p>No I don't think it's possible.<br>\nThink of viruses/trojans/spyware. If it were possible to launch an application from ...
2008/09/24
[ "https://Stackoverflow.com/questions/126048", "https://Stackoverflow.com", "https://Stackoverflow.com/users/21552/" ]
I have a problem where a Web Application needs to (after interaction from the user via Javascript)    1) open a Windows Forms Application    2) send a parameter to the app (e.g. an ID) Correspondingly, the Windows Forms Application should be able to    1) send parameters back to the Web Application (updating the URL is ok)    2) open the Web App in a new brower, if it does not exist If many browser windows are open it's important that the correct one is updated. Windows Forms Application is in ASP.NET Browser is IE6+ The applications are controlled and internal for a specific organisation so it's not a question of launching a custom app. Question A) Is this possible? Question B) How do I send parameters to an open Windows Forms Application from a Web App? Question C) If updating the Web App, how do I make sure the right browser is targeted?
What you're asking for is possible but seems awkward. Trying to call an application from a web page is not something you could do due to security considerations. You could however make a desktop application which would be associated with a certain type of files and then use content-type on the web page to make sure that your app is called when a URL with this type is opened. It would be similar to the way MS Office handles .doc or .xls documents or the Media Player opens the .mp3 or .wmv files. The second part (opening a particular web page from your application) is easier. As you should know the address of your web page create a URL string with the parameters you want and open it in default browser (there are plenty of examples on how to do that, a sample is below). ``` System.Diagnostics.Process.Start("http://example.com?key=value"); ``` If you want to update the page in the already opened browser or use a browser of your choice (i.e. always IE6 instead of Opera or Chrome) then you'll have to do some homework but it's still quite easy.
126,070
<p>I have an email subject of the form:</p> <pre><code>=?utf-8?B?T3.....?= </code></pre> <p>The body of the email is utf-8 base64 encoded - and has decoded fine. I am current using Perl's Email::MIME module to decode the email.</p> <p>What is the meaning of the =?utf-8 delimiter and how do I extract information from this string?</p>
[ { "answer_id": 126087, "author": "1800 INFORMATION", "author_id": 3146, "author_profile": "https://Stackoverflow.com/users/3146", "pm_score": 6, "selected": true, "text": "<p>The <a href=\"http://en.wikipedia.org/wiki/MIME#Encoded-Word\" rel=\"noreferrer\"><code>encoded-word</code></a> t...
2008/09/24
[ "https://Stackoverflow.com/questions/126070", "https://Stackoverflow.com", "https://Stackoverflow.com/users/21553/" ]
I have an email subject of the form: ``` =?utf-8?B?T3.....?= ``` The body of the email is utf-8 base64 encoded - and has decoded fine. I am current using Perl's Email::MIME module to decode the email. What is the meaning of the =?utf-8 delimiter and how do I extract information from this string?
The [`encoded-word`](http://en.wikipedia.org/wiki/MIME#Encoded-Word) tokens (as per [RFC 2047](http://www.faqs.org/rfcs/rfc2047.html)) can occur in values of some headers. They are parsed as follows: ``` =?<charset>?<encoding>?<data>?= ``` Charset is UTF-8 in this case, the encoding is `B` which means base64 (the other option is `Q` which means Quoted Printable). To read it, first decode the base64, then treat it as UTF-8 characters. Also read the various Internet Mail RFCs for more detail, mainly [RFC 2047](http://www.faqs.org/rfcs/rfc2047.html). Since you are using Perl, [Encode::MIME::Header](https://metacpan.org/pod/Encode::MIME::Header) could be of use: > > SYNOPSIS > > > > ``` > use Encode qw/encode decode/; > $utf8 = decode('MIME-Header', $header); > $header = encode('MIME-Header', $utf8); > > ``` > > ABSTRACT > > > This module implements RFC 2047 Mime > Header Encoding. There are 3 variant > encoding names; MIME-Header, MIME-B > and MIME-Q. The difference is > described below > > > > ``` > decode() encode() > MIME-Header Both B and Q =?UTF-8?B?....?= > MIME-B B only; Q croaks =?UTF-8?B?....?= > MIME-Q Q only; B croaks =?UTF-8?Q?....?= > > ``` > >
126,094
<p>Considering that the debug data file is available (PDB) and by using either <strong>System.Reflection</strong> or another similar framework such as <strong>Mono.Cecil</strong>, how to retrieve programmatically the source file name and the line number where a type or a member of a type is declared.</p> <p>For example, let's say you have compiled this file into an assembly:</p> <p><em>C:\MyProject\Foo.cs</em></p> <pre><code>1: public class Foo 2: { 3: public string SayHello() 4: { 5: return "Hello"; 6: } 7: } </code></pre> <p>How to do something like:</p> <pre><code>MethodInfo methodInfo = typeof(Foo).GetMethod("SayHello"); string sourceFileName = methodInfo.GetSourceFile(); // ?? Does not exist! int sourceLineNumber = methodInfo.GetLineNumber(); // ?? Does not exist! </code></pre> <p>sourceFileName would contain "C:\MyProject\Foo.cs" and sourceLineNumber be equal to 3.</p> <p><em>Update: <code>System.Diagnostics.StackFrame</code> is indeed able to get that information, but only in the scope of current executing call stack. It means that the method must be invoked first. I would like to get the same info, but without invoking the type member.</em></p>
[ { "answer_id": 126132, "author": "Richard", "author_id": 20038, "author_profile": "https://Stackoverflow.com/users/20038", "pm_score": -1, "selected": false, "text": "<p>you might find some help with these links:</p>\n\n<p><a href=\"http://www.busycode.com/news/index.php/article/news-abo...
2008/09/24
[ "https://Stackoverflow.com/questions/126094", "https://Stackoverflow.com", "https://Stackoverflow.com/users/563/" ]
Considering that the debug data file is available (PDB) and by using either **System.Reflection** or another similar framework such as **Mono.Cecil**, how to retrieve programmatically the source file name and the line number where a type or a member of a type is declared. For example, let's say you have compiled this file into an assembly: *C:\MyProject\Foo.cs* ``` 1: public class Foo 2: { 3: public string SayHello() 4: { 5: return "Hello"; 6: } 7: } ``` How to do something like: ``` MethodInfo methodInfo = typeof(Foo).GetMethod("SayHello"); string sourceFileName = methodInfo.GetSourceFile(); // ?? Does not exist! int sourceLineNumber = methodInfo.GetLineNumber(); // ?? Does not exist! ``` sourceFileName would contain "C:\MyProject\Foo.cs" and sourceLineNumber be equal to 3. *Update: `System.Diagnostics.StackFrame` is indeed able to get that information, but only in the scope of current executing call stack. It means that the method must be invoked first. I would like to get the same info, but without invoking the type member.*
Up to date method: ``` private static void Log(string text, [CallerFilePath] string file = "", [CallerMemberName] string member = "", [CallerLineNumber] int line = 0) { Console.WriteLine("{0}_{1}({2}): {3}", Path.GetFileName(file), member, line, text); } ``` New `Framework API` which populates arguments (marked with special attributes) at runtime, see more in [my answer to this SO question](https://stackoverflow.com/questions/6369184/print-the-source-filename-and-linenumber-in-c-sharp/16295702#16295702)
126,100
<p>What's the fastest way to count the number of keys/properties of an object? Is it possible to do this without iterating over the object? I.e., without doing:</p> <pre><code>var count = 0; for (k in myobj) if (myobj.hasOwnProperty(k)) ++count; </code></pre> <p>(Firefox did provide a magic <code>__count__</code> property, but this was removed somewhere around version 4.)</p>
[ { "answer_id": 126151, "author": "Confusion", "author_id": 16784, "author_profile": "https://Stackoverflow.com/users/16784", "pm_score": 5, "selected": false, "text": "<p>If you are actually running into a performance problem I would suggest wrapping the calls that add/remove properties ...
2008/09/24
[ "https://Stackoverflow.com/questions/126100", "https://Stackoverflow.com", "https://Stackoverflow.com/users/11543/" ]
What's the fastest way to count the number of keys/properties of an object? Is it possible to do this without iterating over the object? I.e., without doing: ``` var count = 0; for (k in myobj) if (myobj.hasOwnProperty(k)) ++count; ``` (Firefox did provide a magic `__count__` property, but this was removed somewhere around version 4.)
To do this in any *[ES5](https://en.wikipedia.org/wiki/ECMAScript#5th_Edition)-compatible environment*, such as [Node.js](http://nodejs.org), Chrome, [Internet Explorer 9+](https://en.wikipedia.org/wiki/Internet_Explorer_9), Firefox 4+, or Safari 5+: ```js Object.keys(obj).length ``` * [Browser compatibility](http://kangax.github.com/es5-compat-table/) * [Object.keys documentation](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/keys) (includes a method you can add to non-ES5 browsers)
126,109
<p>I defined a record named <code>log</code>. I want to create an mnesia table with name <code>log_table</code>. When I try to write a record to table, I get <code>bad_type</code> error as follows:</p> <pre><code>(node1@kitt)4&gt; mnesia:create_table(log_table, [{ram_copies, [node()]}, {attributes, record_info(fields, log)}]). {atomic,ok} (node1@kitt)5&gt; mnesia:dirty_write(log_table, #log{id="hebelek"}). ** exception exit: {aborted,{bad_type,#log{id = "hebelek"}}} in function mnesia:abort/1 </code></pre> <p>What am I missing?</p>
[ { "answer_id": 126185, "author": "JesperE", "author_id": 13051, "author_profile": "https://Stackoverflow.com/users/13051", "pm_score": 0, "selected": false, "text": "<p>How does your definition of the log-records look? Do you get the same error if you create a new table from scratch (i.e...
2008/09/24
[ "https://Stackoverflow.com/questions/126109", "https://Stackoverflow.com", "https://Stackoverflow.com/users/21000/" ]
I defined a record named `log`. I want to create an mnesia table with name `log_table`. When I try to write a record to table, I get `bad_type` error as follows: ``` (node1@kitt)4> mnesia:create_table(log_table, [{ram_copies, [node()]}, {attributes, record_info(fields, log)}]). {atomic,ok} (node1@kitt)5> mnesia:dirty_write(log_table, #log{id="hebelek"}). ** exception exit: {aborted,{bad_type,#log{id = "hebelek"}}} in function mnesia:abort/1 ``` What am I missing?
By default the record name is assumed to be the same as the table name. To fix this you should either name your table just `log` or append the option `{record_name, log}` in your table options (as you've done in your fix). It is usually good practice to let your record and table be named the same thing, it makes the code easier to read and debug. You can also then use the `mnesia:write/1` function with just your record as only argument. Mnesia then figures out which table to put the record in by looking at the name.
126,114
<p><strong>Problem</strong>. I need a way to find Starteam server time through Starteam Java SDK 8.0. Version of server is 8.0.172 so method <code>Server.getCurrentTime()</code> is not available since it was added only in server version 9.0.</p> <p><strong>Motivation</strong>. My application needs to use views at specific dates. So if there's some difference in system time between client (where the app is running) and server then obtained views are not accurate. In the worst case the client's requested date is in the future for server so the operation results in exception.</p>
[ { "answer_id": 126516, "author": "Ioannis", "author_id": 20428, "author_profile": "https://Stackoverflow.com/users/20428", "pm_score": -1, "selected": false, "text": "<p><code>&lt;stab_in_the_dark&gt;</code>\nI'm not familiar with that SDK but from looking at the API if the server is in ...
2008/09/24
[ "https://Stackoverflow.com/questions/126114", "https://Stackoverflow.com", "https://Stackoverflow.com/users/15647/" ]
**Problem**. I need a way to find Starteam server time through Starteam Java SDK 8.0. Version of server is 8.0.172 so method `Server.getCurrentTime()` is not available since it was added only in server version 9.0. **Motivation**. My application needs to use views at specific dates. So if there's some difference in system time between client (where the app is running) and server then obtained views are not accurate. In the worst case the client's requested date is in the future for server so the operation results in exception.
After some investigation I haven't found any cleaner solution than using a temporary item. My app requests the item's time of creation and compares it with local time. Here's the method I use to get server time: ``` public Date getCurrentServerTime() { Folder rootFolder = project.getDefaultView().getRootFolder(); Topic newItem = (Topic) Item.createItem(project.getTypeNames().TOPIC, rootFolder); newItem.update(); newItem.remove(); newItem.update(); return newItem.getCreatedTime().createDate(); } ```
126,116
<p>Is it possbile to execute linux commands with java? I am trying to create a web servlet to allow ftp users to change their passwords without ssh login access. I would like to execute the next commands: </p> <pre><code># adduser -s /sbin/nologin clientA -d /home/mainclient/clientA # passwd clientA # cd /home/mainclient; chgrp -R mainclient clientA # cd /home/mainclient/clientA; chmod 770 . </code></pre>
[ { "answer_id": 126121, "author": "Craig Day", "author_id": 5193, "author_profile": "https://Stackoverflow.com/users/5193", "pm_score": 4, "selected": true, "text": "<p>Check out <a href=\"http://java.sun.com/j2se/1.5.0/docs/api/java/lang/ProcessBuilder.html\" rel=\"nofollow noreferrer\">...
2008/09/24
[ "https://Stackoverflow.com/questions/126116", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2138/" ]
Is it possbile to execute linux commands with java? I am trying to create a web servlet to allow ftp users to change their passwords without ssh login access. I would like to execute the next commands: ``` # adduser -s /sbin/nologin clientA -d /home/mainclient/clientA # passwd clientA # cd /home/mainclient; chgrp -R mainclient clientA # cd /home/mainclient/clientA; chmod 770 . ```
Check out [this](http://java.sun.com/j2se/1.5.0/docs/api/java/lang/ProcessBuilder.html). However, doing what you are talking about is way outside spec, and I wouldnt reccommend it. To get it to work you are going to either run your app server as root, or use some other mechanism to give the user the app server is running as permission to execute these privileged commands. One small screw-up somewhere and you are "owned".
126,138
<p>I'm trying to run a process and do stuff with its input, output and error streams. The obvious way to do this is to use something like <code>select()</code>, but the only thing I can find in Java that does that is <code>Selector.select()</code>, which takes a <code>Channel</code>. It doesn't appear to be possible to get a <code>Channel</code> from an <code>InputStream</code> or <code>OutputStream</code> (<code>FileStream</code> has a <code>getChannel()</code> method but that doesn't help here)</p> <p>So, instead I wrote some code to poll all the streams:</p> <pre><code>while( !out_eof || !err_eof ) { while( out_str.available() ) { if( (bytes = out_str.read(buf)) != -1 ) { // Do something with output stream } else out_eof = true; } while( err_str.available() ) { if( (bytes = err_str.read(buf)) != -1 ) { // Do something with error stream } else err_eof = true; } sleep(100); } </code></pre> <p>which works, except that it never terminates. When one of the streams reaches end of file, <code>available()</code> returns zero so <code>read()</code> isn't called and we never get the -1 return that would indicate EOF.</p> <p>One solution would be a non-blocking way to detect EOF. I can't see one in the docs anywhere. Alternatively is there a better way of doing what I want to do?</p> <p>I see this question here: <a href="https://stackoverflow.com/questions/60302/starting-a-process-with-inherited-stdinstdoutstderr-in-java-6#60578" title="Processes with inherited stdin/stdout/stderr in Java">link text</a> and although it doesn't exactly do what I want, I can probably use that idea, of spawning separate threads for each stream, for the particular problem I have now. But surely that isn't the only way to do it? Surely there must be a way to read from multiple streams without using a thread for each?</p>
[ { "answer_id": 126366, "author": "Matt Quail", "author_id": 15790, "author_profile": "https://Stackoverflow.com/users/15790", "pm_score": 3, "selected": true, "text": "<p>As you said, the solution <a href=\"https://stackoverflow.com/questions/60302/starting-a-process-with-inherited-stdin...
2008/09/24
[ "https://Stackoverflow.com/questions/126138", "https://Stackoverflow.com", "https://Stackoverflow.com/users/11815/" ]
I'm trying to run a process and do stuff with its input, output and error streams. The obvious way to do this is to use something like `select()`, but the only thing I can find in Java that does that is `Selector.select()`, which takes a `Channel`. It doesn't appear to be possible to get a `Channel` from an `InputStream` or `OutputStream` (`FileStream` has a `getChannel()` method but that doesn't help here) So, instead I wrote some code to poll all the streams: ``` while( !out_eof || !err_eof ) { while( out_str.available() ) { if( (bytes = out_str.read(buf)) != -1 ) { // Do something with output stream } else out_eof = true; } while( err_str.available() ) { if( (bytes = err_str.read(buf)) != -1 ) { // Do something with error stream } else err_eof = true; } sleep(100); } ``` which works, except that it never terminates. When one of the streams reaches end of file, `available()` returns zero so `read()` isn't called and we never get the -1 return that would indicate EOF. One solution would be a non-blocking way to detect EOF. I can't see one in the docs anywhere. Alternatively is there a better way of doing what I want to do? I see this question here: [link text](https://stackoverflow.com/questions/60302/starting-a-process-with-inherited-stdinstdoutstderr-in-java-6#60578 "Processes with inherited stdin/stdout/stderr in Java") and although it doesn't exactly do what I want, I can probably use that idea, of spawning separate threads for each stream, for the particular problem I have now. But surely that isn't the only way to do it? Surely there must be a way to read from multiple streams without using a thread for each?
As you said, the solution [outlined in this Answer](https://stackoverflow.com/questions/60302/starting-a-process-with-inherited-stdinstdoutstderr-in-java-6#60578) is the traditional way of reading both stdout and stderr from a Process. A thread-per-stream is the way to go, even though it is slightly annoying.
126,141
<p>I need to determine which version of GTK+ is installed on Ubuntu</p> <p>Man does not seem to help</p>
[ { "answer_id": 126145, "author": "Torsten Marek", "author_id": 9567, "author_profile": "https://Stackoverflow.com/users/9567", "pm_score": 5, "selected": false, "text": "<p>You can use this command:</p>\n<pre><code>$ dpkg -s libgtk2.0-0|grep '^Version'\n</code></pre>\n" }, { "ans...
2008/09/24
[ "https://Stackoverflow.com/questions/126141", "https://Stackoverflow.com", "https://Stackoverflow.com/users/15352/" ]
I need to determine which version of GTK+ is installed on Ubuntu Man does not seem to help
[This suggestion](https://stackoverflow.com/a/126145/) will tell you which minor version of 2.0 is installed. Different major versions will have different package names because they can co-exist on the system (in order to support applications built with older versions). Even for development files, which normally would only let you have one version on the system, you can have a version of gtk 1.x and a version of gtk 2.0 on the same system (the include files are in directories called gtk-1.2 or gtk-2.0). So in short there isn't a simple answer to "what version of GTK is on the system". But... Try something like: ``` dpkg -l libgtk* | grep -e '^i' | grep -e 'libgtk-*[0-9]' ``` to list all the libgtk packages, including -dev ones, that are on your system. `dpkg -l` will list all the packages that dpkg knows about, including ones that aren't currently installed, so I've used grep to list only ones that are installed (line starts with i). Alternatively, and probably better if it's the version of the headers etc that you're interested in, use pkg-config: ``` pkg-config --modversion gtk+ ``` will tell you what version of GTK 1.x development files are installed, and ``` pkg-config --modversion gtk+-2.0 ``` will tell you what version of GTK 2.0. The old 1.x version also has its own gtk-config program that does the same thing. Similarly, for GTK+ 3: ``` pkg-config --modversion gtk+-3.0 ```
126,148
<p>How is the salt generated in HashProvider in Microsoft Enterprise Library when we set SaltEnabled?</p> <p>Is it random to new machines? Is it some magic number?</p> <p>(I know what is a salt, the question is what's the actual value of a/the salt in Enterprise Library HashProvider)</p>
[ { "answer_id": 128481, "author": "Corbin March", "author_id": 7625, "author_profile": "https://Stackoverflow.com/users/7625", "pm_score": 2, "selected": false, "text": "<p>Edit:</p>\n\n<p>See Microsoft.Practices.EnterpriseLibrary.Security.Cryptography.HashAlgorithmProvider for an example...
2008/09/24
[ "https://Stackoverflow.com/questions/126148", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
How is the salt generated in HashProvider in Microsoft Enterprise Library when we set SaltEnabled? Is it random to new machines? Is it some magic number? (I know what is a salt, the question is what's the actual value of a/the salt in Enterprise Library HashProvider)
Edit: See Microsoft.Practices.EnterpriseLibrary.Security.Cryptography.HashAlgorithmProvider for an example implementation. Hashing steps are: 1. If SaltEnabled, generate random bytes for the salt length using RNGCryptoServiceProvider. 2. Append the salt to the plaintext. 3. Hash the salted plaintext. 4. Then (this is the important step), append the salt again to the **hash**. To compare against hashed text, you must use: ``` public bool CompareHash(byte[] plaintext, byte[] hashedtext) ``` versus rehashing and comparing. If you rehash, a new random salt is generated and you're lost. CompareHash does the following: 1. Pulls the non-hashed salt off the hashtext. Remember, it was appended at step 4 above. 2. Uses that salt to compute a hash for the plaintext. 3. Compares the new hash with the hashedtext minus salt. If they're the same - true, else false. Original: "if salt is enabled on a HashProvider, the provider will generate a random sequence of bytes, that will be added to the hash. If you compare a hashed value with a unhashed value, the salt will be extracted from the hashed value and used to hash the unhashed value, prior to comparison." and "As for decoding as hash-value. this cannot be done. after creating a hash there should be no way to reverse this into the original value. However, what you can do is compare an unhashed-value with a hashed-value by putting it through the same algorithm and comparing the output." From <http://www.codeplex.com/entlib/Thread/View.aspx?ThreadId=10284>
126,154
<p>I am designing a page to Add/Edit users - I used a repeater control and a table to display users. In users view the individual columns of the table row have labels to display a record values and when users click on edit button, the labels are hidden and text boxes are displayed for users to edit values - The problem is - as soon as the text boxes are visible, the table size increases - the row height and cells size becomes large. Is there a way to display the text boxes so that they take the same size as the labels</p>
[ { "answer_id": 126254, "author": "Oli", "author_id": 12870, "author_profile": "https://Stackoverflow.com/users/12870", "pm_score": 0, "selected": false, "text": "<p>I'd use JS+CSS... You'll have to get your hands dirty for this one though. Visual Studio isn't going to help you much. </p>...
2008/09/24
[ "https://Stackoverflow.com/questions/126154", "https://Stackoverflow.com", "https://Stackoverflow.com/users/17296/" ]
I am designing a page to Add/Edit users - I used a repeater control and a table to display users. In users view the individual columns of the table row have labels to display a record values and when users click on edit button, the labels are hidden and text boxes are displayed for users to edit values - The problem is - as soon as the text boxes are visible, the table size increases - the row height and cells size becomes large. Is there a way to display the text boxes so that they take the same size as the labels
Dealing with tables, the question is: can your labels span on multiple text rows (ie: can you have long texts)? If yes, you may encounter layout problems any way. If no, a simple approach can be creating a CSS Class: ``` .CellContent { display:block; width: ...; height: ...; } ``` with your preferred cell width/height. Just stay a bit "large" with your height. Assign the class to both your label and textbox, and you should not get width/height changes when switching control (thanks to the display:block property). Again, if you have long texts, you will still encounter issues, and may want to use multilines. In that case, I would suggest ignoring height problems: just set the width to be consistent, and always show a 3-4 lines textbox for editing. Users will not be bothered to see a row height change, if they are ready to type long texts.
126,164
<p>Assume the following class:</p> <pre><code>public class MyEnum: IEnumerator { private List&lt;SomeObject&gt; _myList = new List&lt;SomeObject&gt;(); ... } </code></pre> <p>It is necessary to implement the IEnumerator methods in MyEnum. But is it possible to 'delegate' or redirect the implementation for IEnumerator directly to _myList without needing to implement the IEnumerator methods?</p>
[ { "answer_id": 126171, "author": "Paul van Brenk", "author_id": 1837197, "author_profile": "https://Stackoverflow.com/users/1837197", "pm_score": -1, "selected": false, "text": "<p>Not unless you derive from List&lt;T>.</p>\n\n<pre><code>public class MyEnum : List&lt;SomeObject&gt;, IEnu...
2008/09/24
[ "https://Stackoverflow.com/questions/126164", "https://Stackoverflow.com", "https://Stackoverflow.com/users/21568/" ]
Assume the following class: ``` public class MyEnum: IEnumerator { private List<SomeObject> _myList = new List<SomeObject>(); ... } ``` It is necessary to implement the IEnumerator methods in MyEnum. But is it possible to 'delegate' or redirect the implementation for IEnumerator directly to \_myList without needing to implement the IEnumerator methods?
**Method 1:** Continue to use encapsulation and forward calls to the List implementation. ``` class SomeObject { } class MyEnum : IEnumerable<SomeObject> { private List<SomeObject> _myList = new List<SomeObject>(); public void Add(SomeObject o) { _myList.Add(o); } public IEnumerator<SomeObject> GetEnumerator() { return _myList.GetEnumerator(); } IEnumerator IEnumerable.GetEnumerator() { return this.GetEnumerator(); } } class Program { static void Main(string[] args) { MyEnum a = new MyEnum(); a.Add(new SomeObject()); foreach (SomeObject o in a) { Console.WriteLine(o.GetType().ToString()); } Console.ReadLine(); } } ``` **Method 2:** Inherit from List implementation you get that behavior for free. ``` class SomeObject { } class MyEnum : List<SomeObject> { } class Program { static void Main(string[] args) { MyEnum a = new MyEnum(); a.Add(new SomeObject()); foreach (SomeObject o in a) { Console.WriteLine(o.GetType().ToString()); } Console.ReadLine(); } } ``` **Method 1** allows for better sandboxing as there is no method that will be called in List without MyEnum knowledge. For least effort **Method 2** is preferred.
126,167
<p>Application able to record error in OnError, but we are not able to do any redirect or so to show something meaningfull to user. Any ideas? I know that we can set maxRequestLength in web.config, but anyway user can exceed this limit and some normal error need to be displayed.</p>
[ { "answer_id": 126200, "author": "Adam Vigh", "author_id": 1613872, "author_profile": "https://Stackoverflow.com/users/1613872", "pm_score": -1, "selected": false, "text": "<p>You could check the length of the postedfile (FileUpload.PostedFile.ContentLength), to see if it's below the lim...
2008/09/24
[ "https://Stackoverflow.com/questions/126167", "https://Stackoverflow.com", "https://Stackoverflow.com/users/11768/" ]
Application able to record error in OnError, but we are not able to do any redirect or so to show something meaningfull to user. Any ideas? I know that we can set maxRequestLength in web.config, but anyway user can exceed this limit and some normal error need to be displayed.
As you say you can setup maxRequestLength in your web.config (overriding the default 4MB of your machine.config) and if this limits is exceeded you usually get a HTTP 401.1 error. In order to handle a generic HTTP error at application level you can setup a CustomError section in your web.config within the system.web section: ``` <system.web> <customErrors mode=On defaultRedirect=yourCustomErrorPage.aspx /> </system.web> ``` Everytime the error is showed the user will be redirected to your custom error page. If you want a specialized page for each error you can do something like: ``` <system.web> <customErrors mode="On" defaultRedirect="yourCustomErrorPage.aspx"> <error statusCode="404" redirect="PageNotFound.aspx" /> </customErrors> </system.web> ``` And so on. Alternatively you could edit the CustomErrors tab of your virtual directory properties from IIS to point to your error handling pages of choice. The above doesn't seem to work for 401.x errors - this code-project article explains a workaround for a what seems to be a very similar problem: [Redirecting to custom 401 page](http://www.codeproject.com/KB/aspnet/Custon401Page.aspx)
126,179
<p>If I have a query like, </p> <pre><code>DELETE FROM table WHERE datetime_field &lt; '2008-01-01 00:00:00' </code></pre> <p>does having the <code>datetime_field</code> column indexed help? i.e. is the index only useful when using equality (or inequality) testing, or is it useful when doing an ordered comparison as well?</p> <blockquote> <p>(Suggestions for better executing this query, without recreating the table, would also be ok!)</p> </blockquote>
[ { "answer_id": 126183, "author": "Matthias Winkelmann", "author_id": 4494, "author_profile": "https://Stackoverflow.com/users/4494", "pm_score": 1, "selected": false, "text": "<p>It does, check with a DESCRIBE SELECT FROM table ...</p>\n" }, { "answer_id": 126190, "author": "...
2008/09/24
[ "https://Stackoverflow.com/questions/126179", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4966/" ]
If I have a query like, ``` DELETE FROM table WHERE datetime_field < '2008-01-01 00:00:00' ``` does having the `datetime_field` column indexed help? i.e. is the index only useful when using equality (or inequality) testing, or is it useful when doing an ordered comparison as well? > > (Suggestions for better executing this query, without recreating the table, would also be ok!) > > >
Maybe. In general, if there is such an index, it will use a range scan on that index if there is no "better" index on the query. However, if the optimiser decides that the range would end up being too big (i.e. include more than, say 1/3 of the rows), it probably won't use the index at all, as a table scan would be likely to be faster. Use EXPLAIN (on a SELECT; you can't EXPLAIN a delete) to determine its decision in a specific case. This is likely to depend upon * How many rows there are in the table * What the range is that you're specifying * What else is specified in the WHERE clause. It won't use a range scan of one index if there is another index which "looks better".
126,238
<p>Imagine to have two RESTful controllers (UsersController, OffersController) and a PagesController (used for static content such as index, about and so on) in your application.</p> <p>You have the following routes defined:</p> <pre><code>map.with_options :controller =&gt; 'pages' do |pages| pages.root :action =&gt; 'index' # static home page pages.about :action =&gt; 'about' # static about page # maybe more static pages... end map.resources :users # RESTful UsersController map.resources :posts # RESTful PostsController </code></pre> <p>Your application layout looks like this:</p> <pre><code>&lt;html&gt; &lt;head&gt; &lt;title&gt;Demo Application&lt;/title&gt; &lt;/head&gt; &lt;body&gt; &lt;ul id="menu"&gt; &lt;li&gt; &lt;%= link_to 'Home', root_path %&gt; &lt;/li&gt; &lt;li&gt; &lt;%= link_to 'Offers', offers_path %&gt; &lt;ul id="submenu&gt; &lt;li&gt;&lt;%= link_to 'Search', 'path/to/search' %&gt;&lt;/li&gt; &lt;li&gt;maybe more links...&lt;/li&gt; &lt;/ul&gt; &lt;/li&gt; &lt;li&gt; &lt;%= link_to 'About', about_path %&gt; &lt;/li&gt; &lt;li&gt; &lt;%= link_to 'Admin', users_path %&gt; &lt;ul id="submenu"&gt; &lt;li&gt;&lt;%= link_to 'New User', new_user_path %&gt;&lt;/li&gt; &lt;li&gt;&lt;%= link_to 'New Offer', new_offer_path %&gt;&lt;/li&gt; &lt;li&gt;maybe more links&lt;/li&gt; &lt;/ul&gt; &lt;/li&gt; &lt;/li&gt; &lt;%= yield %&gt; &lt;/body&gt; &lt;/html&gt; </code></pre> <p>The problem with the layout is that I want only one <code>#submenu</code> to be visible at any time. All other submenus can be completely skipped (don't need to rendered at all).</p> <p>Take the Admin menu for example: This menu should be active for all RESTful paths in the application except for <code>offers_path</code>. Active means that the submenu is visible.</p> <p>The only solution I can think of to achieve this is to build a lot complicated if conditions and that sucks (really complicated to write and to maintain). I'm looking for an elegant solution?</p> <p>I hope someone understands my question - if there's something unclear just comment the question and I'm going to explain it in more detail.</p>
[ { "answer_id": 126849, "author": "Jeremiah Peschka", "author_id": 11780, "author_profile": "https://Stackoverflow.com/users/11780", "pm_score": 1, "selected": false, "text": "<p>Typically, I would abstract out the menuing functionality so that I have a helper method for rendering the Adm...
2008/09/24
[ "https://Stackoverflow.com/questions/126238", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20467/" ]
Imagine to have two RESTful controllers (UsersController, OffersController) and a PagesController (used for static content such as index, about and so on) in your application. You have the following routes defined: ``` map.with_options :controller => 'pages' do |pages| pages.root :action => 'index' # static home page pages.about :action => 'about' # static about page # maybe more static pages... end map.resources :users # RESTful UsersController map.resources :posts # RESTful PostsController ``` Your application layout looks like this: ``` <html> <head> <title>Demo Application</title> </head> <body> <ul id="menu"> <li> <%= link_to 'Home', root_path %> </li> <li> <%= link_to 'Offers', offers_path %> <ul id="submenu> <li><%= link_to 'Search', 'path/to/search' %></li> <li>maybe more links...</li> </ul> </li> <li> <%= link_to 'About', about_path %> </li> <li> <%= link_to 'Admin', users_path %> <ul id="submenu"> <li><%= link_to 'New User', new_user_path %></li> <li><%= link_to 'New Offer', new_offer_path %></li> <li>maybe more links</li> </ul> </li> </li> <%= yield %> </body> </html> ``` The problem with the layout is that I want only one `#submenu` to be visible at any time. All other submenus can be completely skipped (don't need to rendered at all). Take the Admin menu for example: This menu should be active for all RESTful paths in the application except for `offers_path`. Active means that the submenu is visible. The only solution I can think of to achieve this is to build a lot complicated if conditions and that sucks (really complicated to write and to maintain). I'm looking for an elegant solution? I hope someone understands my question - if there's something unclear just comment the question and I'm going to explain it in more detail.
One thing you could play with is yield and content\_for, used with a few partials for the menus. For example you could put each section of the menu in a partial and then modify your layout to something like: ``` <%= yield(:menu) %> ``` You then can then specify in your views content\_for and put whatever partials you want into the menu. If it's not specified it won't get rendered. ``` <% content_for(:menu) do %> <%= render :partial => 'layouts/menu' %> <%= render :partial => 'layouts/search_menu' %> etc... <% end %> ``` If you're using a lot of the same menus in most pages, specify a default in your layout if no yield(:menu) is found. ``` <%= yield(:menu) || render :partial => 'layouts/menu_default' %> ``` Saves you a lot of typing. :) I've found this to be a nice clean way of handling things.
126,242
<p>This is probably explained more easily with an example. I'm trying to find a way of turning a relative URL, e.g. "/Foo.aspx" or "~/Foo.aspx" into a full URL, e.g. <a href="http://localhost/Foo.aspx" rel="noreferrer">http://localhost/Foo.aspx</a>. That way when I deploy to test or stage, where the domain under which the site runs is different, I will get <a href="http://test/Foo.aspx" rel="noreferrer">http://test/Foo.aspx</a> and <a href="http://stage/Foo.aspx" rel="noreferrer">http://stage/Foo.aspx</a>.</p> <p>Any ideas?</p>
[ { "answer_id": 126258, "author": "Oli", "author_id": 12870, "author_profile": "https://Stackoverflow.com/users/12870", "pm_score": 7, "selected": true, "text": "<p>Have a play with this (modified <a href=\"http://web.archive.org/web/20130730034405/http://www.aspdotnetfaq.com/Faq/how-to-c...
2008/09/24
[ "https://Stackoverflow.com/questions/126242", "https://Stackoverflow.com", "https://Stackoverflow.com/users/12277/" ]
This is probably explained more easily with an example. I'm trying to find a way of turning a relative URL, e.g. "/Foo.aspx" or "~/Foo.aspx" into a full URL, e.g. <http://localhost/Foo.aspx>. That way when I deploy to test or stage, where the domain under which the site runs is different, I will get <http://test/Foo.aspx> and <http://stage/Foo.aspx>. Any ideas?
Have a play with this (modified [from here](http://web.archive.org/web/20130730034405/http://www.aspdotnetfaq.com/Faq/how-to-convert-relative-url-to-absolute-url-in-asp-net-page.aspx)) ``` public string ConvertRelativeUrlToAbsoluteUrl(string relativeUrl) { return string.Format("http{0}://{1}{2}", (Request.IsSecureConnection) ? "s" : "", Request.Url.Host, Page.ResolveUrl(relativeUrl) ); } ```
126,271
<p>Does someone have experience with storing key-value pairs in a database?</p> <p>I've been using this type of table:</p> <pre><code>CREATE TABLE key_value_pairs ( itemid varchar(32) NOT NULL, itemkey varchar(32) NOT NULL, itemvalue varchar(32) NOT NULL, CONSTRAINT ct_primarykey PRIMARY KEY(itemid,itemkey) ) </code></pre> <p>Then for example the following rows could exist:</p> <pre><code> itemid itemkey itemvalue ---------------- ------------- ------------ 123 Colour Red 123 Size Medium 123 Fabric Cotton </code></pre> <p>The trouble with this scheme is the SQL syntax required to extract data is quite complex. Would it be better to just create a series of key/value columns?</p> <pre><code>CREATE TABLE key_value_pairs ( itemid varchar(32) NOT NULL, itemkey1 varchar(32) NOT NULL, itemvalue1 varchar(32) NOT NULL, itemkey2 varchar(32) NOT NULL, itemvalue2 varchar(32) NOT NULL, . . .etc . . . ) </code></pre> <p>This will be easier and faster to query but lacks the extensibility of the first approach. Any advice?</p>
[ { "answer_id": 126282, "author": "Mladen", "author_id": 21404, "author_profile": "https://Stackoverflow.com/users/21404", "pm_score": 1, "selected": false, "text": "<p>the first method is quite ok. you can create a UDF that extracts the desired data and just call that.</p>\n" }, { ...
2008/09/24
[ "https://Stackoverflow.com/questions/126271", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2887/" ]
Does someone have experience with storing key-value pairs in a database? I've been using this type of table: ``` CREATE TABLE key_value_pairs ( itemid varchar(32) NOT NULL, itemkey varchar(32) NOT NULL, itemvalue varchar(32) NOT NULL, CONSTRAINT ct_primarykey PRIMARY KEY(itemid,itemkey) ) ``` Then for example the following rows could exist: ``` itemid itemkey itemvalue ---------------- ------------- ------------ 123 Colour Red 123 Size Medium 123 Fabric Cotton ``` The trouble with this scheme is the SQL syntax required to extract data is quite complex. Would it be better to just create a series of key/value columns? ``` CREATE TABLE key_value_pairs ( itemid varchar(32) NOT NULL, itemkey1 varchar(32) NOT NULL, itemvalue1 varchar(32) NOT NULL, itemkey2 varchar(32) NOT NULL, itemvalue2 varchar(32) NOT NULL, . . .etc . . . ) ``` This will be easier and faster to query but lacks the extensibility of the first approach. Any advice?
Before you continue on your approach, I would humbly suggest you step back and consider if you really want to store this data in a "Key-Value Pair"table. I don't know your application but my experience has shown that every time I have done what you are doing, later on I wish I had created a color table, a fabric table and a size table. Think about referential integrity constraints, if you take the key-value pair approach, the database can't tell you when you are trying to store a color id in a size field Think about the performance benefits of joining on a table with 10 values versus a generic value that may have thousands of values across multiple domains. How useful is an index on Key Value really going to be? Usually the reasoning behind doing what you are doing is because the domains need to be "user definable". If that is the case then even I am not going to push you towards creating tables on the fly (although that is a feasible approach). However, if your reasoning is because you think it will be easier to manage than multiple tables, or because you are envisioning a maintenance user interface that is generic for all domains, then stop and think really hard before you continue.
126,277
<p>Say you want to generate a matched list of identifiers and strings</p> <pre><code>enum { NAME_ONE, NAME_TWO, NAME_THREE }; myFunction(NAME_ONE, "NAME_ONE"); myFunction(NAME_TWO, "NAME_TWO"); myFunction(NAME_THREE, "NAME_THREE"); </code></pre> <p>..without repeating yourself, and without auto-generating the code, using C/C++ macros</p> <p><b>Initial guess:</b></p> <p>You could add an #include file containing</p> <pre><code>myDefine(NAME_ONE) myDefine(NAME_TWO) myDefine(NAME_THREE) </code></pre> <p>Then use it twice like:</p> <pre><code>#define myDefine(a) a, enum { #include "definitions" } #undef myDefine #define myDefine(a) myFunc(a, "a"); #include "definitions" #undef myDefine </code></pre> <p>but #define doesn't let you put parameters within a string?</p>
[ { "answer_id": 126291, "author": "Kristopher Johnson", "author_id": 1175, "author_profile": "https://Stackoverflow.com/users/1175", "pm_score": 6, "selected": true, "text": "<p>For your second #define, you need to use the # preprocessor operator, like this:</p>\n\n<pre><code>#define myDe...
2008/09/24
[ "https://Stackoverflow.com/questions/126277", "https://Stackoverflow.com", "https://Stackoverflow.com/users/46478/" ]
Say you want to generate a matched list of identifiers and strings ``` enum { NAME_ONE, NAME_TWO, NAME_THREE }; myFunction(NAME_ONE, "NAME_ONE"); myFunction(NAME_TWO, "NAME_TWO"); myFunction(NAME_THREE, "NAME_THREE"); ``` ..without repeating yourself, and without auto-generating the code, using C/C++ macros **Initial guess:** You could add an #include file containing ``` myDefine(NAME_ONE) myDefine(NAME_TWO) myDefine(NAME_THREE) ``` Then use it twice like: ``` #define myDefine(a) a, enum { #include "definitions" } #undef myDefine #define myDefine(a) myFunc(a, "a"); #include "definitions" #undef myDefine ``` but #define doesn't let you put parameters within a string?
For your second #define, you need to use the # preprocessor operator, like this: ``` #define myDefine(a) myFunc(a, #a); ``` That converts the argument to a string.
126,297
<p>After I <a href="https://stackoverflow.com/questions/121922/automatic-casts">messed up the description of my previous post</a> on this I have sat down and tried to convey my exact intent.</p> <p>I have a class called P which performs some distinct purpose. I also have PW which perform some distinct purpose on P. PW has no member variables, just member functions.</p> <p>From this description you would assume that the code would follow like this:</p> <pre><code>class P { public: void a( ); }; class PW { public: PW( const P&amp; p ) : p( p ) { } void b( ); P&amp; p; }; class C { public: P GetP( ) const { return p; } private: P p; }; // ... PW&amp; p = c.GetP( ); // valid // ... </code></pre> <p>However that brings up a problem. I can't call the functions of P without indirection everywhere.</p> <pre><code>// ... p-&gt;p-&gt;a( ) // ... </code></pre> <p><strong>What I would like to do is call p->a( ) and have it automatically determine that I would like to call the member function of P.</strong></p> <p>Also having a member of PW called <em>a</em> doesn't really scale - what if I add (or remove) another function to P - this will need to be added (or removed) to PW.</p>
[ { "answer_id": 126321, "author": "Rik", "author_id": 5409, "author_profile": "https://Stackoverflow.com/users/5409", "pm_score": 1, "selected": false, "text": "<p>If you make P a superclass to PW, like you did in your previous question, you could call p->a() and it would direct to class ...
2008/09/24
[ "https://Stackoverflow.com/questions/126297", "https://Stackoverflow.com", "https://Stackoverflow.com/users/342/" ]
After I [messed up the description of my previous post](https://stackoverflow.com/questions/121922/automatic-casts) on this I have sat down and tried to convey my exact intent. I have a class called P which performs some distinct purpose. I also have PW which perform some distinct purpose on P. PW has no member variables, just member functions. From this description you would assume that the code would follow like this: ``` class P { public: void a( ); }; class PW { public: PW( const P& p ) : p( p ) { } void b( ); P& p; }; class C { public: P GetP( ) const { return p; } private: P p; }; // ... PW& p = c.GetP( ); // valid // ... ``` However that brings up a problem. I can't call the functions of P without indirection everywhere. ``` // ... p->p->a( ) // ... ``` **What I would like to do is call p->a( ) and have it automatically determine that I would like to call the member function of P.** Also having a member of PW called *a* doesn't really scale - what if I add (or remove) another function to P - this will need to be added (or removed) to PW.
You could try overriding operator\* and operator-> to return access to the embedded p. Something like this might do the trick : ``` class P { public: void a( ) { std::cout << "a" << std::endl; } }; class PW { public: PW(P& p) : p(p) { } void b( ) { std::cout << "b" << std::endl; } P & operator*() { return p; } P * operator->() { return &p; } private: P & p; }; class C { public: P & getP() { return p; } private: P p; }; int main() { C c; PW pw(c.getP()); (*pw).a(); pw->a(); pw.b(); return EXIT_SUCCESS; } ``` This code prints ``` a a b ``` However, this method may confuse the user since the semantic of operator\* and operator-> becomes a little messed up.
126,320
<p>Suppose I have a set of commits in a repository folder...</p> <pre><code>123 (250 new files, 137 changed files, 14 deleted files) 122 (150 changed files) 121 (renamed folder) 120 (90 changed files) 119 (115 changed files, 14 deleted files, 12 added files) 118 (113 changed files) 117 (10 changed files) </code></pre> <p>I want to get a working copy that includes all changes from revision 117 onward but does NOT include the changes for revisions 118 and 120.</p> <p>EDIT: To perhaps make the problem clearer, I want to undo the changes that were made in 118 and 120 while retaining all other changes. The folder contains thousands of files in hundreds of subfolders.</p> <p>What is the best way to achieve this?</p> <p><strong>The answer</strong>, thanks to Bruno and Bert, is the command (in this case, for removing 120 after the full merge was performed)</p> <pre><code>svn merge -c -120 . </code></pre> <p>Note that the revision number must be specified with a leading minus. '-120' not '120'</p>
[ { "answer_id": 126357, "author": "Christian Davén", "author_id": 12534, "author_profile": "https://Stackoverflow.com/users/12534", "pm_score": -1, "selected": false, "text": "<p>I suppose you could create a branch from revision 117, then merge everything except 118 and 120.</p>\n\n<pre><...
2008/09/24
[ "https://Stackoverflow.com/questions/126320", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4200/" ]
Suppose I have a set of commits in a repository folder... ``` 123 (250 new files, 137 changed files, 14 deleted files) 122 (150 changed files) 121 (renamed folder) 120 (90 changed files) 119 (115 changed files, 14 deleted files, 12 added files) 118 (113 changed files) 117 (10 changed files) ``` I want to get a working copy that includes all changes from revision 117 onward but does NOT include the changes for revisions 118 and 120. EDIT: To perhaps make the problem clearer, I want to undo the changes that were made in 118 and 120 while retaining all other changes. The folder contains thousands of files in hundreds of subfolders. What is the best way to achieve this? **The answer**, thanks to Bruno and Bert, is the command (in this case, for removing 120 after the full merge was performed) ``` svn merge -c -120 . ``` Note that the revision number must be specified with a leading minus. '-120' not '120'
To undo revisions 118 and 120: ``` svn up -r HEAD # get latest revision svn merge -c -120 . # undo revision 120 svn merge -c -118 . # undo revision 118 svn commit # after solving problems (if any) ``` Also see the description in [Undoing changes](http://svnbook.red-bean.com/en/1.5/svn.branchmerge.basicmerging.html#svn.branchmerge.basicmerging.undo). Note the minus in the `-c -120` argument. The `-c` (or `--change`) switch is supported since Subversion 1.4, older versions can use `-r 120:119`.
126,332
<p>I'm wanting a method called same_url? that will return true if the passed in URLs are equal. The passed in URLs might be either params options hash or strings.</p> <pre><code>same_url?({:controller =&gt; :foo, :action =&gt; :bar}, "http://www.example.com/foo/bar") # =&gt; true </code></pre> <p>The Rails Framework helper <a href="http://api.rubyonrails.org/classes/ActionView/Helpers/UrlHelper.html#M001607" rel="nofollow noreferrer">current_page?</a> seems like a good starting point but I'd like to pass in an arbitrary number of URLs.</p> <p>As an added bonus It would be good if a hash of params to exclude from the comparison could be passed in. So a method call might look like:</p> <pre><code>same_url?(projects_path(:page =&gt; 2), "projects?page=3", :excluding =&gt; :page) # =&gt; true </code></pre>
[ { "answer_id": 126693, "author": "Codebeef", "author_id": 12037, "author_profile": "https://Stackoverflow.com/users/12037", "pm_score": 1, "selected": false, "text": "<p>Is this the sort of thing you're after?</p>\n\n<pre><code>def same_url?(one, two)\n url_for(one) == url_for(two)\nend...
2008/09/24
[ "https://Stackoverflow.com/questions/126332", "https://Stackoverflow.com", "https://Stackoverflow.com/users/19588/" ]
I'm wanting a method called same\_url? that will return true if the passed in URLs are equal. The passed in URLs might be either params options hash or strings. ``` same_url?({:controller => :foo, :action => :bar}, "http://www.example.com/foo/bar") # => true ``` The Rails Framework helper [current\_page?](http://api.rubyonrails.org/classes/ActionView/Helpers/UrlHelper.html#M001607) seems like a good starting point but I'd like to pass in an arbitrary number of URLs. As an added bonus It would be good if a hash of params to exclude from the comparison could be passed in. So a method call might look like: ``` same_url?(projects_path(:page => 2), "projects?page=3", :excluding => :page) # => true ```
Here's the method (bung it in /lib and require it in environment.rb): ``` def same_page?(a, b, params_to_exclude = {}) if a.respond_to?(:except) && b.respond_to?(:except) url_for(a.except(params_to_exclude)) == url_for(b.except(params_to_exclude)) else url_for(a) == url_for(b) end end ``` **If you are on Rails pre-2.0.1**, you also need to add the `except` helper method to Hash: ``` class Hash # Usage { :a => 1, :b => 2, :c => 3}.except(:a) -> { :b => 2, :c => 3} def except(*keys) self.reject { |k,v| keys.include? k.to_sym } end end ``` Later version of Rails (well, ActiveSupport) include `except` already (credit: [Brian Guthrie](https://stackoverflow.com/users/77859/brian-guthrie))
126,337
<p>I have a 2.4 MB XML file, an export from Microsoft Project (hey I'm the victim here!) from which I am requested to extract certain details for re-presentation. Ignoring the intelligence or otherwise of the request, which library should I try first from a Ruby perspective?</p> <p>I'm aware of the following (in no particular order):</p> <ul> <li><a href="http://www.germane-software.com/software/rexml/" rel="noreferrer">REXML</a></li> <li><a href="http://www.chilkatsoft.com/ruby-xml.asp" rel="noreferrer">Chilkat Ruby XML library</a></li> <li><a href="http://code.whytheluckystiff.net/hpricot/wiki/HpricotXML" rel="noreferrer">hpricot XML</a></li> <li><a href="http://libxml.rubyforge.org/" rel="noreferrer">libXML</a></li> </ul> <p>I'd prefer something packaged as a Ruby gem, which I suspect the Chilkat library is not.</p> <p>Performance isn't a major issue - I don't expect the thing to need to run more than once a day (once a week is more likely). I'm more interested in something that's as easy to use as anything XML-related is able to get.</p> <p>EDIT: I tried the gemified ones:</p> <p>hpricot is, by a country mile, easiest. For example, to extract the content of the SaveVersion tag in this XML (saved in a file called, say 'test.xml')</p> <pre><code>&lt;?xml version="1.0" encoding="UTF-8" standalone="yes"?&gt; &lt;Project xmlns="http://schemas.microsoft.com/project"&gt; &lt;SaveVersion&gt;12&lt;/SaveVersion&gt; &lt;/Project&gt; </code></pre> <p>takes something like this: </p> <pre><code>doc = Hpricot.XML(open('test.xml')) version = (doc/:Project/:SaveVersion).first.inner_html </code></pre> <p>hpricot seems to be relatively unconcerned with namespaces, which in this example is fine: there's only one, but would potentially be a problem with a complex document. Since hpricot is also very slow, I rather imagine this would be a problem that solves itself.</p> <p>libxml-ruby is an order of magnitude faster, understands namespaces (it took me a good couple of hours to figure this out) and is altogether much closer to the XML metal - XPath queries and all the other stuff are in there. This is not necessarily a Good Thing if, like me, you open up an XML document only under conditions of extreme duress. The helper module was mostly helpful in providing examples of how to handle a default namespace effectively. This is roughly what I ended up with (I'm not in any way asserting its beauty, correctness or other value, it's just where I am right now):</p> <pre><code>xml_parser = XML::Parser.new xml_parser.string = File.read(path) doc = xml_parser.parse @root = doc.root @scopes = { :in_node =&gt; '', :in_root =&gt; '/', :in_doc =&gt; '//' } @ns_prefix = 'p' @ns = "#{@ns_prefix}:#{@root.namespace[0].href}" version = @root.find_first(xpath_qry("Project/SaveVersion", :in_root), @ns).content.to_i def xpath_qry(tags, scope = :in_node) "#{@scopes[scope]}" + tags.split(/\//).collect{ |tag| "#{@ns_prefix}:#{tag}"}.join('/') end </code></pre> <p>I'm still debating the pros and cons: libxml for its extra rigour, hpricot for the sheer style of _why's code.</p> <p>EDIT again, somewhat later: I discovered HappyMapper ('gem install happymapper') which is hugely promising, if still at an early stage. It's declarative and mostly works, although I have spotted a couple of edge cases that I don't have fixes for yet. It lets you do stuff like this, which parses my Google Reader OPML:</p> <pre><code>module OPML class Outline include HappyMapper tag 'outline' attribute :title, String attribute :text, String attribute :type, String attribute :xmlUrl, String attribute :htmlUrl, String has_many :outlines, Outline end end xml_string = File.read("google-reader-subscriptions.xml") sections = OPML::Outline.parse(xml_string) </code></pre> <p>I already love it, even though it's not perfect yet.</p>
[ { "answer_id": 146733, "author": "dimus", "author_id": 23080, "author_profile": "https://Stackoverflow.com/users/23080", "pm_score": 3, "selected": true, "text": "<p><a href=\"http://code.whytheluckystiff.net/hpricot/wiki/HpricotBasics\" rel=\"nofollow noreferrer\">Hpricot</a> is probabl...
2008/09/24
[ "https://Stackoverflow.com/questions/126337", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1060/" ]
I have a 2.4 MB XML file, an export from Microsoft Project (hey I'm the victim here!) from which I am requested to extract certain details for re-presentation. Ignoring the intelligence or otherwise of the request, which library should I try first from a Ruby perspective? I'm aware of the following (in no particular order): * [REXML](http://www.germane-software.com/software/rexml/) * [Chilkat Ruby XML library](http://www.chilkatsoft.com/ruby-xml.asp) * [hpricot XML](http://code.whytheluckystiff.net/hpricot/wiki/HpricotXML) * [libXML](http://libxml.rubyforge.org/) I'd prefer something packaged as a Ruby gem, which I suspect the Chilkat library is not. Performance isn't a major issue - I don't expect the thing to need to run more than once a day (once a week is more likely). I'm more interested in something that's as easy to use as anything XML-related is able to get. EDIT: I tried the gemified ones: hpricot is, by a country mile, easiest. For example, to extract the content of the SaveVersion tag in this XML (saved in a file called, say 'test.xml') ``` <?xml version="1.0" encoding="UTF-8" standalone="yes"?> <Project xmlns="http://schemas.microsoft.com/project"> <SaveVersion>12</SaveVersion> </Project> ``` takes something like this: ``` doc = Hpricot.XML(open('test.xml')) version = (doc/:Project/:SaveVersion).first.inner_html ``` hpricot seems to be relatively unconcerned with namespaces, which in this example is fine: there's only one, but would potentially be a problem with a complex document. Since hpricot is also very slow, I rather imagine this would be a problem that solves itself. libxml-ruby is an order of magnitude faster, understands namespaces (it took me a good couple of hours to figure this out) and is altogether much closer to the XML metal - XPath queries and all the other stuff are in there. This is not necessarily a Good Thing if, like me, you open up an XML document only under conditions of extreme duress. The helper module was mostly helpful in providing examples of how to handle a default namespace effectively. This is roughly what I ended up with (I'm not in any way asserting its beauty, correctness or other value, it's just where I am right now): ``` xml_parser = XML::Parser.new xml_parser.string = File.read(path) doc = xml_parser.parse @root = doc.root @scopes = { :in_node => '', :in_root => '/', :in_doc => '//' } @ns_prefix = 'p' @ns = "#{@ns_prefix}:#{@root.namespace[0].href}" version = @root.find_first(xpath_qry("Project/SaveVersion", :in_root), @ns).content.to_i def xpath_qry(tags, scope = :in_node) "#{@scopes[scope]}" + tags.split(/\//).collect{ |tag| "#{@ns_prefix}:#{tag}"}.join('/') end ``` I'm still debating the pros and cons: libxml for its extra rigour, hpricot for the sheer style of \_why's code. EDIT again, somewhat later: I discovered HappyMapper ('gem install happymapper') which is hugely promising, if still at an early stage. It's declarative and mostly works, although I have spotted a couple of edge cases that I don't have fixes for yet. It lets you do stuff like this, which parses my Google Reader OPML: ``` module OPML class Outline include HappyMapper tag 'outline' attribute :title, String attribute :text, String attribute :type, String attribute :xmlUrl, String attribute :htmlUrl, String has_many :outlines, Outline end end xml_string = File.read("google-reader-subscriptions.xml") sections = OPML::Outline.parse(xml_string) ``` I already love it, even though it's not perfect yet.
[Hpricot](http://code.whytheluckystiff.net/hpricot/wiki/HpricotBasics) is probably the best tool for you -- it is easy to use and should handle 2mg file with no problem. Speedwise libxml should be the best. I used libxml2 binding for python few months ago (at that moment rb-libxml was stale). Streaming interface worked the best for me (LibXML::XML::Reader in ruby gem). It allows to process file while it is downloading, is a bit more userfriendly than SAX and allowed me to load data from 30mb xml file from internet to a MySQL database in a little more than a minute.
126,364
<p><strong>Intro</strong>: I'm trying to migrate our Trac SQLite to a PostgreSQL backend, to do that I need psycopg2. After clicking past the embarrassing rant on www.initd.org I downloaded the latest version and tried running <code>setup.py install</code>. This didn't work, telling me I needed mingw. So I downloaded and installed mingw.</p> <p><strong>Problem</strong>: I now get the following error when running <code>setup.py build_ext --compiler=mingw32 install</code>:</p> <pre><code>running build_ext building 'psycopg2._psycopg' extension writing build\temp.win32-2.4\Release\psycopg\_psycopg.def C:\mingw\bin\gcc.exe -mno-cygwin -shared -s build\temp.win32-2.4\Release\psycopg \psycopgmodule.o build\temp.win32-2.4\Release\psycopg\pqpath.o build\temp.win32- 2.4\Release\psycopg\typecast.o build\temp.win32-2.4\Release\psycopg\microprotoco ls.o build\temp.win32-2.4\Release\psycopg\microprotocols_proto.o build\temp.win3 2-2.4\Release\psycopg\connection_type.o build\temp.win32-2.4\Release\psycopg\con nection_int.o build\temp.win32-2.4\Release\psycopg\cursor_type.o build\temp.win3 2-2.4\Release\psycopg\cursor_int.o build\temp.win32-2.4\Release\psycopg\lobject_ type.o build\temp.win32-2.4\Release\psycopg\lobject_int.o build\temp.win32-2.4\R elease\psycopg\adapter_qstring.o build\temp.win32-2.4\Release\psycopg\adapter_pb oolean.o build\temp.win32-2.4\Release\psycopg\adapter_binary.o build\temp.win32- 2.4\Release\psycopg\adapter_asis.o build\temp.win32-2.4\Release\psycopg\adapter_ list.o build\temp.win32-2.4\Release\psycopg\adapter_datetime.o build\temp.win32- 2.4\Release\psycopg\_psycopg.def -LC:\Python24\libs -LC:\Python24\PCBuild -Lc:/P ROGRA~1/POSTGR~1/8.3/lib -lpython24 -lmsvcr71 -lpq -lmsvcr71 -lws2_32 -ladvapi32 -o build\lib.win32-2.4\psycopg2\_psycopg.pyd C:\mingw\bin\..\lib\gcc\mingw32\3.4.5\..\..\..\..\mingw32\bin\ld.exe: cannot fin d -lpq collect2: ld returned 1 exit status error: command 'gcc' failed with exit status 1 </code></pre> <p><strong>What I've tried</strong> - I noticed the forward slashes in the -L option, so I manually entered my PostgreSQL lib directory in the library_dirs option in the setup.cfg, to no avail (the call then had a -L option with backslashes, but the error message stayed the same).</p>
[ { "answer_id": 126494, "author": "Michael Twomey", "author_id": 995, "author_profile": "https://Stackoverflow.com/users/995", "pm_score": 3, "selected": true, "text": "<p>Have you tried the <a href=\"http://www.stickpeople.com/projects/python/win-psycopg/\" rel=\"nofollow noreferrer\">bi...
2008/09/24
[ "https://Stackoverflow.com/questions/126364", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6583/" ]
**Intro**: I'm trying to migrate our Trac SQLite to a PostgreSQL backend, to do that I need psycopg2. After clicking past the embarrassing rant on www.initd.org I downloaded the latest version and tried running `setup.py install`. This didn't work, telling me I needed mingw. So I downloaded and installed mingw. **Problem**: I now get the following error when running `setup.py build_ext --compiler=mingw32 install`: ``` running build_ext building 'psycopg2._psycopg' extension writing build\temp.win32-2.4\Release\psycopg\_psycopg.def C:\mingw\bin\gcc.exe -mno-cygwin -shared -s build\temp.win32-2.4\Release\psycopg \psycopgmodule.o build\temp.win32-2.4\Release\psycopg\pqpath.o build\temp.win32- 2.4\Release\psycopg\typecast.o build\temp.win32-2.4\Release\psycopg\microprotoco ls.o build\temp.win32-2.4\Release\psycopg\microprotocols_proto.o build\temp.win3 2-2.4\Release\psycopg\connection_type.o build\temp.win32-2.4\Release\psycopg\con nection_int.o build\temp.win32-2.4\Release\psycopg\cursor_type.o build\temp.win3 2-2.4\Release\psycopg\cursor_int.o build\temp.win32-2.4\Release\psycopg\lobject_ type.o build\temp.win32-2.4\Release\psycopg\lobject_int.o build\temp.win32-2.4\R elease\psycopg\adapter_qstring.o build\temp.win32-2.4\Release\psycopg\adapter_pb oolean.o build\temp.win32-2.4\Release\psycopg\adapter_binary.o build\temp.win32- 2.4\Release\psycopg\adapter_asis.o build\temp.win32-2.4\Release\psycopg\adapter_ list.o build\temp.win32-2.4\Release\psycopg\adapter_datetime.o build\temp.win32- 2.4\Release\psycopg\_psycopg.def -LC:\Python24\libs -LC:\Python24\PCBuild -Lc:/P ROGRA~1/POSTGR~1/8.3/lib -lpython24 -lmsvcr71 -lpq -lmsvcr71 -lws2_32 -ladvapi32 -o build\lib.win32-2.4\psycopg2\_psycopg.pyd C:\mingw\bin\..\lib\gcc\mingw32\3.4.5\..\..\..\..\mingw32\bin\ld.exe: cannot fin d -lpq collect2: ld returned 1 exit status error: command 'gcc' failed with exit status 1 ``` **What I've tried** - I noticed the forward slashes in the -L option, so I manually entered my PostgreSQL lib directory in the library\_dirs option in the setup.cfg, to no avail (the call then had a -L option with backslashes, but the error message stayed the same).
Have you tried the [binary build](http://www.stickpeople.com/projects/python/win-psycopg/) of psycopg2 for windows? If that works with your python then it mitigates the need to build by hand. I've seen random people ask this question on various lists and it seems one recommendation is to build postgresql by hand to work around this problem.
126,373
<p>I write a lot of dynamically generated content (developing under PHP) and I use jQuery to add extra flexibility and functionality to my projects.</p> <p>Thing is that it's rather hard to add JavaScript in an unobtrusive manner. Here's an example:</p> <p>You have to generate a random number of <code>div</code> elements each with different functionality triggered <code>onClick</code>. I can use the <code>onclick</code> attribute on my <code>div</code> elements to call a JS function with a parameter but that is just a bad solution. Also I could generate some jQuery code along with each div in my PHP <code>for</code> loop, but then again this won't be entirely unobtrusive.</p> <p>So what's the solution in situations like this?</p>
[ { "answer_id": 126398, "author": "roryf", "author_id": 270, "author_profile": "https://Stackoverflow.com/users/270", "pm_score": 3, "selected": false, "text": "<p>You need to add something to the divs that defines what type of behaviour they have, then use jQuery to select those divs and...
2008/09/24
[ "https://Stackoverflow.com/questions/126373", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20603/" ]
I write a lot of dynamically generated content (developing under PHP) and I use jQuery to add extra flexibility and functionality to my projects. Thing is that it's rather hard to add JavaScript in an unobtrusive manner. Here's an example: You have to generate a random number of `div` elements each with different functionality triggered `onClick`. I can use the `onclick` attribute on my `div` elements to call a JS function with a parameter but that is just a bad solution. Also I could generate some jQuery code along with each div in my PHP `for` loop, but then again this won't be entirely unobtrusive. So what's the solution in situations like this?
You need to add something to the divs that defines what type of behaviour they have, then use jQuery to select those divs and add the behaviour. One option is to use the class attribute, although arguably this should be used for presentation rather than behaviour. An alternative would be the rel attribute, but I usually find that you also want to specify different CSS for each behaviour, so class is probably ok in this instance. So for instance, lets assume you want odd and even behaviour: ``` <div class="odd">...</div> <div class="even">...</div> <div class="odd">...</div> <div class="even">...</div> ``` Then in jQuery: ``` $(document).load(function() { $('.odd').click(function(el) { // do stuff }); $('.even').click(function(el) { // dostuff }); }); ``` jQuery has a very powerful selector engine that can find based on any CSS based selector, and also support some XPath and its own selectors. Get to know them! <http://docs.jquery.com/Selectors>
126,401
<p>Debugging some finance-related SQL code found a strange issue with numeric(24,8) mathematics precision.</p> <p>Running the following query on your MSSQL you would get A + B * C expression result to be 0.123457</p> <p>SELECT A, B, C, A + B * C FROM ( SELECT CAST(0.12345678 AS NUMERIC(24,8)) AS A, CAST(0 AS NUMERIC(24,8)) AS B, CAST(500 AS NUMERIC(24,8)) AS C ) T</p> <p>So we have lost 2 significant symbols. Trying to get this fixed in different ways i got that conversion of the intermediate multiplication result (which is Zero!) to numeric (24,8) would work fine.</p> <p>And finally a have a solution. But still I hace a question - why MSSQL behaves in this way and which type conversions actually occured in my sample?</p>
[ { "answer_id": 126473, "author": "Eugene Yokota", "author_id": 3827, "author_profile": "https://Stackoverflow.com/users/3827", "pm_score": 4, "selected": true, "text": "<p>Just as addition of the float type is inaccurate, multiplication of the decimal types can be inaccurate (or cause in...
2008/09/24
[ "https://Stackoverflow.com/questions/126401", "https://Stackoverflow.com", "https://Stackoverflow.com/users/21603/" ]
Debugging some finance-related SQL code found a strange issue with numeric(24,8) mathematics precision. Running the following query on your MSSQL you would get A + B \* C expression result to be 0.123457 SELECT A, B, C, A + B \* C FROM ( SELECT CAST(0.12345678 AS NUMERIC(24,8)) AS A, CAST(0 AS NUMERIC(24,8)) AS B, CAST(500 AS NUMERIC(24,8)) AS C ) T So we have lost 2 significant symbols. Trying to get this fixed in different ways i got that conversion of the intermediate multiplication result (which is Zero!) to numeric (24,8) would work fine. And finally a have a solution. But still I hace a question - why MSSQL behaves in this way and which type conversions actually occured in my sample?
Just as addition of the float type is inaccurate, multiplication of the decimal types can be inaccurate (or cause inaccuracy) if you exceed the precision. See [Data Type Conversion](http://msdn.microsoft.com/en-us/library/ms191530%28SQL.90%29.aspx#_decimal) and [decimal and numeric](http://msdn.microsoft.com/en-us/library/ms187746%28SQL.90%29.aspx). Since you multiplied `NUMERIC(24,8)` and `NUMERIC(24,8)`, and SQL Server will only check the type not the content, it probably will try to save the potential 16 non-decimal digits (24 - 8) when it can't save all 48 digits of precision (max is 38). Combine two of them, you get 32 non-decimal digits, which leaves you with only 6 decimal digits (38 - 32). Thus the original query ``` SELECT A, B, C, A + B * C FROM ( SELECT CAST(0.12345678 AS NUMERIC(24,8)) AS A, CAST(0 AS NUMERIC(24,8)) AS B, CAST(500 AS NUMERIC(24,8)) AS C ) T ``` reduces to ``` SELECT A, B, C, A + D FROM ( SELECT CAST(0.12345678 AS NUMERIC(24,8)) AS A, CAST(0 AS NUMERIC(24,8)) AS B, CAST(500 AS NUMERIC(24,8)) AS C, CAST(0 AS NUMERIC(38,6)) AS D ) T ``` Again, between `NUMERIC(24,8)` and `NUMERIC(38,6)`, SQL Server will try to save the potential 32 digits of non-decimals, so `A + D` reduces to ``` SELECT CAST(0.12345678 AS NUMERIC(38,6)) ``` which gives you `0.123457` after rounding.
126,406
<p>I would like to change the database files location of MySQL administrator to another drive of my computer. (I run Windows XP SP2 and MySQL Administrator 1.2.8.)</p> <p>--Under the startup variable --> General Parameters --> I changed <code>Data directory:</code> from <code>C:/Program Files/MySQL/MySQL Server 5.0/data</code> to <code>D:/.....</code>, but after I stopped the service and restarted it, the following error appeared: </p> <pre><code>Could not re-connect to the MySQL Server. Server could not be started. Fatal error: Can't open and lock privilege tables: Table 'mysql.host' doesn't exist </code></pre> <p>Has anyone else had this problem? </p>
[ { "answer_id": 126420, "author": "Armin Ronacher", "author_id": 19990, "author_profile": "https://Stackoverflow.com/users/19990", "pm_score": 5, "selected": true, "text": "<p>Normally it works like this:</p>\n\n<ol>\n<li>shut down MySQL</li>\n<li>change the <code>[mysqld]</code> and <cod...
2008/09/24
[ "https://Stackoverflow.com/questions/126406", "https://Stackoverflow.com", "https://Stackoverflow.com/users/21608/" ]
I would like to change the database files location of MySQL administrator to another drive of my computer. (I run Windows XP SP2 and MySQL Administrator 1.2.8.) --Under the startup variable --> General Parameters --> I changed `Data directory:` from `C:/Program Files/MySQL/MySQL Server 5.0/data` to `D:/.....`, but after I stopped the service and restarted it, the following error appeared: ``` Could not re-connect to the MySQL Server. Server could not be started. Fatal error: Can't open and lock privilege tables: Table 'mysql.host' doesn't exist ``` Has anyone else had this problem?
Normally it works like this: 1. shut down MySQL 2. change the `[mysqld]` and `[mysqld_safe]` `datadir` variable in the MySQL configuration 3. change the `basedir` variable in the same section. 4. move the location over 5. restart MySQL If that doesn't work I have no idea. On linux you can try to move the socket to a new location too, but that shouldn't affect windows. Alternatively you can use a symbolic link on \*nix what most people do I guess.
126,409
<p>What are the ways to eliminate the use of switch in code?</p>
[ { "answer_id": 126415, "author": "Bernard", "author_id": 61, "author_profile": "https://Stackoverflow.com/users/61", "pm_score": 4, "selected": false, "text": "<p>Everybody loves HUGE <code>if else</code> blocks. So easy to read! I am curious as to why you would want to remove switch sta...
2008/09/24
[ "https://Stackoverflow.com/questions/126409", "https://Stackoverflow.com", "https://Stackoverflow.com/users/12514/" ]
What are the ways to eliminate the use of switch in code?
Switch-statements are not an antipattern per se, but if you're coding object oriented you should consider if the use of a switch is better solved with [polymorphism](http://en.wikipedia.org/wiki/Polymorphism_in_object-oriented_programming) instead of using a switch statement. With polymorphism, this: ``` foreach (var animal in zoo) { switch (typeof(animal)) { case "dog": echo animal.bark(); break; case "cat": echo animal.meow(); break; } } ``` becomes this: ``` foreach (var animal in zoo) { echo animal.speak(); } ```
126,430
<p>Is it possible to change the natural order of columns in Postgres 8.1?</p> <p>I know that you shouldn't rely on column order - it's not <em>essential</em> to what I am doing - I only need it to make some auto-generated stuff come out in a way that is more pleasing, so that the field order matches all the way from pgadmin through the back end and out to the front end.</p>
[ { "answer_id": 126432, "author": "Nick Johnson", "author_id": 12030, "author_profile": "https://Stackoverflow.com/users/12030", "pm_score": 0, "selected": false, "text": "<p>Unfortunately, no, it's not. Column order is entirely up to Postgres.</p>\n" }, { "answer_id": 126437, ...
2008/09/24
[ "https://Stackoverflow.com/questions/126430", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3408/" ]
Is it possible to change the natural order of columns in Postgres 8.1? I know that you shouldn't rely on column order - it's not *essential* to what I am doing - I only need it to make some auto-generated stuff come out in a way that is more pleasing, so that the field order matches all the way from pgadmin through the back end and out to the front end.
You can actually just straight up change the column order, but I'd hardly recommend it, and you should be very careful if you decide to do it. eg. ``` # CREATE TABLE test (a int, b int, c int); # INSERT INTO test VALUES (1,2,3); # SELECT * FROM test; a | b | c ---+---+--- 1 | 2 | 3 (1 row) ``` Now for the tricky bit, you need to connect to your database using the postgres user so you can modify the system tables. ``` # SELECT relname, relfilenode FROM pg_class WHERE relname='test'; relname | relfilenode ---------+------------- test_t | 27666 (1 row) # SELECT attrelid, attname, attnum FROM pg_attribute WHERE attrelid=27666; attrelid | attname | attnum ----------+----------+-------- 27666 | tableoid | -7 27666 | cmax | -6 27666 | xmax | -5 27666 | cmin | -4 27666 | xmin | -3 27666 | ctid | -1 27666 | b | 1 27666 | a | 2 27666 | c | 3 (9 rows) ``` attnum is a unique column, so you need to use a temporary value when you're modifying the column numbers as such: ``` # UPDATE pg_attribute SET attnum=4 WHERE attname='a' AND attrelid=27666; UPDATE 1 # UPDATE pg_attribute SET attnum=1 WHERE attname='b' AND attrelid=27666; UPDATE 1 # UPDATE pg_attribute SET attnum=2 WHERE attname='a' AND attrelid=27666; UPDATE 1 # SELECT * FROM test; b | a | c ---+---+--- 1 | 2 | 3 (1 row) ``` Again, because this is playing around with database system tables, use extreme caution if you feel you really need to do this. This is working as of postgres 8.3, with prior versions, your milage may vary.
126,445
<p>I am implementing a design that uses custom styled submit-buttons. They are quite simply light grey buttons with a slightly darker outer border:</p> <pre><code>input.button { background: #eee; border: 1px solid #ccc; } </code></pre> <p>This looks just right in Firefox, Safari and Opera. The problem is with Internet Explorer, both 6 and 7. </p> <p>Since the form is the first one on the page, it's counted as the main form - and thus active from the get go. The first submit button in the active form receives a solid black border in IE, to mark it as the main action.</p> <p>If I turn off borders, then the black extra border in IE goes away too. I am looking for a way to keep my normal borders, but remove the outline.</p>
[ { "answer_id": 126474, "author": "Oli", "author_id": 12870, "author_profile": "https://Stackoverflow.com/users/12870", "pm_score": 1, "selected": false, "text": "<p>Right, well here's an ugly fix for you to weigh up... Stick the button in a <code>&lt;span&gt;</code>, nuke the border on t...
2008/09/24
[ "https://Stackoverflow.com/questions/126445", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1123/" ]
I am implementing a design that uses custom styled submit-buttons. They are quite simply light grey buttons with a slightly darker outer border: ``` input.button { background: #eee; border: 1px solid #ccc; } ``` This looks just right in Firefox, Safari and Opera. The problem is with Internet Explorer, both 6 and 7. Since the form is the first one on the page, it's counted as the main form - and thus active from the get go. The first submit button in the active form receives a solid black border in IE, to mark it as the main action. If I turn off borders, then the black extra border in IE goes away too. I am looking for a way to keep my normal borders, but remove the outline.
Well this works here: ``` <html> <head> <style type="text/css"> span.button { background: #eee; border: 1px solid #ccc; } span.button input { background:none; border:0; margin:0; padding:0; } </style> </head> <body> <span class="button"><input type="button" name="..." value="Button"/></span> </body> </html> ```
126,513
<p>I am running following <code>PHP</code> code to interact with a MS Access database.</p> <pre><code>$odbc_con = new COM("ADODB.Connection"); $constr = "DRIVER={Microsoft Access Driver (*.mdb)}; DBQ=" . $db_path . ";"; $odbc_con -&gt; open($constr); $rs_select = $odbc_con -&gt; execute ("SELECT * FROM Main"); </code></pre> <p>Using <code>($rs_select -&gt; RecordCount)</code> gives -1 though the query is returning non-zero records.</p> <p>(a) What can be the reason? (b) Is there any way out?</p> <p>I have also tried using <code>count($rs_select -&gt; GetRows())</code>. This satisfies the need but looks inefficient as it will involve copying of all the records into an array first.</p>
[ { "answer_id": 126543, "author": "Oli", "author_id": 12870, "author_profile": "https://Stackoverflow.com/users/12870", "pm_score": 0, "selected": false, "text": "<p>Doesn't Access have its own COUNT operator? eg:</p>\n\n<pre><code>$rs_select = $odbc_con -&gt; execute (\"SELECT COUNT(*) F...
2008/09/24
[ "https://Stackoverflow.com/questions/126513", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6561/" ]
I am running following `PHP` code to interact with a MS Access database. ``` $odbc_con = new COM("ADODB.Connection"); $constr = "DRIVER={Microsoft Access Driver (*.mdb)}; DBQ=" . $db_path . ";"; $odbc_con -> open($constr); $rs_select = $odbc_con -> execute ("SELECT * FROM Main"); ``` Using `($rs_select -> RecordCount)` gives -1 though the query is returning non-zero records. (a) What can be the reason? (b) Is there any way out? I have also tried using `count($rs_select -> GetRows())`. This satisfies the need but looks inefficient as it will involve copying of all the records into an array first.
ADODB has its own rules for what recordcount is returned depending on the type of recordset you've defined. See: [MS Knowledge Base article 194973](http://support.microsoft.com/kb/194973) [W3C Schools article](http://www.w3schools.com/ADO/prop_rs_recordcount.asp) In the example above, the PHP COM() object is used to instantiate ADODB, a COM interface for generic database access. According to the [PHP documentation](http://us3.php.net/manual/en/class.com.php), the object reference produced is overloaded, so you can just use the same properties/methods that the native ADODB object would have. This means that you need to use the ADODB methods to set the recordset type to one that will give an accurate recordcount (if you must have it). The alternative, as others have mentioned, is to use a second query to get the COUNT() of the records returned by the SELECT statement. This is easier, but may be inappropriate in the particular environment. I'm not an ADO guru, so can't provide you with the exact commands for setting your recordset type, but from the articles cited above, it is clear that you need a static or keyset cursor. It appears to me that the proper method of setting the CursorType is to use a parameter in the command that opens the recordset. [This W3C Schools article on the CursorType property](http://www.w3schools.com/ADO/prop_rs_cursortype.asp) gives the appropriate arguments for that command. Hopefully, this information will help the original poster accomplish his task, one way or the other.
126,524
<p>I could swear I've seen the function (or method) that takes a list, like this <code>[3, 7, 19]</code> and makes it into iterable list of tuples, like so: <code>[(0,3), (1,7), (2,19)]</code> to use it instead of:</p> <pre><code>for i in range(len(name_of_list)): name_of_list[i] = something </code></pre> <p>but I can't remember the name and googling "iterate list" gets nothing.</p>
[ { "answer_id": 126533, "author": "Vinko Vrsalovic", "author_id": 5190, "author_profile": "https://Stackoverflow.com/users/5190", "pm_score": 10, "selected": true, "text": "<pre><code>&gt;&gt;&gt; a = [3,4,5,6]\n&gt;&gt;&gt; for i, val in enumerate(a):\n... print i, val\n...\n0 3\n1 4...
2008/09/24
[ "https://Stackoverflow.com/questions/126524", "https://Stackoverflow.com", "https://Stackoverflow.com/users/37141/" ]
I could swear I've seen the function (or method) that takes a list, like this `[3, 7, 19]` and makes it into iterable list of tuples, like so: `[(0,3), (1,7), (2,19)]` to use it instead of: ``` for i in range(len(name_of_list)): name_of_list[i] = something ``` but I can't remember the name and googling "iterate list" gets nothing.
``` >>> a = [3,4,5,6] >>> for i, val in enumerate(a): ... print i, val ... 0 3 1 4 2 5 3 6 >>> ```
126,526
<p>Has anyone got any suggestions for unit testing a Managed Application Add-In for Office? I'm using NUnit but I had the same issues with MSTest.</p> <p>The problem is that there is a .NET assembly loaded inside the Office application (in my case, Word) and I need a reference to that instance of the .NET assembly. I can't just instantiate the object because it wouldn't then have an instance of Word to do things to.</p> <p>Now, I can use the Application.COMAddIns("Name of addin").Object interface to get a reference, but that gets me a COM object that is returned through the RequestComAddInAutomationService. My solution so far is that for that object to have proxy methods for every method in the real .NET object that I want to test (all set under conditional-compilation so they disappear in the released version).</p> <p>The COM object (a VB.NET class) actually has a reference to the instance of the real add-in, but I tried just returning that to NUnit and I got a nice p/Invoke error:</p> <p>System.Runtime.Remoting.RemotingException : This remoting proxy has no channel sink which means either the server has no registered server channels that are listening, or this application has no suitable client channel to talk to the server. at System.Runtime.Remoting.Proxies.RemotingProxy.InternalInvoke(IMethodCallMessage reqMcmMsg, Boolean useDispatchMessage, Int32 callType) at System.Runtime.Remoting.Proxies.RemotingProxy.Invoke(IMessage reqMsg) at System.Runtime.Remoting.Proxies.RealProxy.PrivateInvoke(MessageData&amp; msgData, Int32 type) </p> <p>I tried making the main add-in COM visible and the error changes:</p> <p>System.InvalidOperationException : Operation is not valid due to the current state of the object. at System.RuntimeType.ForwardCallToInvokeMember(String memberName, BindingFlags flags, Object target, Int32[] aWrapperTypes, MessageData&amp; msgData) </p> <p>While I have a work-around, it's messy and puts lots of test code in the real project instead of the test project - which isn't really the way NUnit is meant to work.</p>
[ { "answer_id": 126560, "author": "Lou Franco", "author_id": 3937, "author_profile": "https://Stackoverflow.com/users/3937", "pm_score": 2, "selected": false, "text": "<p>Consider the various mocking frameworks <a href=\"http://www.nmock.org/\" rel=\"nofollow noreferrer\">NMock</a>, <a hr...
2008/09/24
[ "https://Stackoverflow.com/questions/126526", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20354/" ]
Has anyone got any suggestions for unit testing a Managed Application Add-In for Office? I'm using NUnit but I had the same issues with MSTest. The problem is that there is a .NET assembly loaded inside the Office application (in my case, Word) and I need a reference to that instance of the .NET assembly. I can't just instantiate the object because it wouldn't then have an instance of Word to do things to. Now, I can use the Application.COMAddIns("Name of addin").Object interface to get a reference, but that gets me a COM object that is returned through the RequestComAddInAutomationService. My solution so far is that for that object to have proxy methods for every method in the real .NET object that I want to test (all set under conditional-compilation so they disappear in the released version). The COM object (a VB.NET class) actually has a reference to the instance of the real add-in, but I tried just returning that to NUnit and I got a nice p/Invoke error: System.Runtime.Remoting.RemotingException : This remoting proxy has no channel sink which means either the server has no registered server channels that are listening, or this application has no suitable client channel to talk to the server. at System.Runtime.Remoting.Proxies.RemotingProxy.InternalInvoke(IMethodCallMessage reqMcmMsg, Boolean useDispatchMessage, Int32 callType) at System.Runtime.Remoting.Proxies.RemotingProxy.Invoke(IMessage reqMsg) at System.Runtime.Remoting.Proxies.RealProxy.PrivateInvoke(MessageData& msgData, Int32 type) I tried making the main add-in COM visible and the error changes: System.InvalidOperationException : Operation is not valid due to the current state of the object. at System.RuntimeType.ForwardCallToInvokeMember(String memberName, BindingFlags flags, Object target, Int32[] aWrapperTypes, MessageData& msgData) While I have a work-around, it's messy and puts lots of test code in the real project instead of the test project - which isn't really the way NUnit is meant to work.
This is how I resolved it. 1. Just about everything in my add-in runs from the Click method of a button in the UI. I have changed all those Click methods to consist only of a simple, parameterless call. 2. I then created a new file (Partial Class) called EntryPoint that had lots of very short Friend Subs, each of which was usually one or two calls to parameterised worker functions, so that all the Click methods just called into this file. So, for example, there's a function that opens a standard document and calls a "save as" into our DMS. The function takes a parameter of which document to open, and there are a couple of dozen standard documents that we use. So I have ``` Private Sub btnMemo_Click(ByVal Ctrl As Microsoft.Office.Core.CommandBarButton, ByRef CancelDefault As Boolean) Handles btnMemo.Click DocMemo() End Sub ``` in the ThisAddin and then ``` Friend Sub DocMemo() OpenDocByNumber("Prec", 8862, 1) End Sub ``` in my new EntryPoints file. 3. I add a new AddInUtilities file which has Public Interface IAddInUtilities `#If DEBUG Then` ``` Sub DocMemo() ``` `#End If` ``` End Interface Public Class AddInUtilities Implements IAddInUtilities Private Addin as ThisAddIn ``` `#If DEBUG Then` ``` Public Sub DocMemo() Implements IAddInUtilities.DocMemo Addin.DocMemo() End Sub ``` `#End If` ``` Friend Sub New(ByRef theAddin as ThisAddIn) Addin=theAddin End Sub End Class ``` 4. I go to the ThisAddIn file and add in Private utilities As AddInUtilities Protected Overrides Function RequestComAddInAutomationService() As Object If utilities Is Nothing Then utilities = New AddInUtilities(Me) End If Return utilities End Function And now it's possible to test the DocMemo() function in EntryPoints using NUnit, something like this: ``` <TestFixture()> Public Class Numbering Private appWord As Word.Application Private objMacros As Object <TestFixtureSetUp()> Public Sub LaunchWord() appWord = New Word.Application appWord.Visible = True Dim AddIn As COMAddIn = Nothing Dim AddInUtilities As IAddInUtilities For Each tempAddin As COMAddIn In appWord.COMAddIns If tempAddin.Description = "CobbettsMacrosVsto" Then AddIn = tempAddin End If Next AddInUtilities = AddIn.Object objMacros = AddInUtilities.TestObject End Sub <Test()> Public Sub DocMemo() objMacros.DocMemo() End Sub <TestFixtureTearDown()> Public Sub TearDown() appWord.Quit(False) End Sub End Class ``` The only thing you can't then unit test are the actual Click events, because you're calling into EntryPoints in a different way, ie through the RequestComAddInAutomationService interface rather than through the event handlers. But it works!
126,528
<p>On the safari browser, the standard &lt;asp:Menu&gt; doesn't render well at all. How can this be fixed?</p>
[ { "answer_id": 126709, "author": "Ben Scheirman", "author_id": 3381, "author_profile": "https://Stackoverflow.com/users/3381", "pm_score": 1, "selected": false, "text": "<p>You can use ControlAdapters to alter the rendering of server controls.</p>\n\n<p>Here's an example:\n<a href=\"http...
2008/09/24
[ "https://Stackoverflow.com/questions/126528", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20524/" ]
On the safari browser, the standard <asp:Menu> doesn't render well at all. How can this be fixed?
Thanks for the advice, it led me into the following solution; I created a file named "safari.browser" and placed it in the App\_Browsers directory. The content of this file is shown below; ``` <browsers> <browser refID="safari1plus"> <controlAdapters> <adapter controlType="System.Web.UI.WebControls.Menu" adapterType="" /> </controlAdapters> </browser> </browsers> ``` As I understand it, this tells ASP.NET not to use the adaptor it would normally use to render the control content and instead use uplevel rendering.
126,584
<p>I have a requirement to be be able to embed scanned tiff images into some SSRS reports.</p> <p>When I design a report in VS2005 and add an image control the tiff image displays perfectly however when I build it. I get the warning :</p> <p><code>Warning 2 [rsInvalidMIMEType] The value of the MIMEType property for the image ‘image1’ is “image/tiff”, which is not a valid MIMEType. c:\SSRSStuff\TestReport.rdl 0 0</code></p> <p>and instead of an image I get the little red x.</p> <p>Has anybody overcome this issue?</p>
[ { "answer_id": 130950, "author": "Peter Wone", "author_id": 1715673, "author_profile": "https://Stackoverflow.com/users/1715673", "pm_score": 3, "selected": true, "text": "<p>Assuming you're delivering the image file via IIS, use an ASP.NET page to change image formats and mime type to s...
2008/09/24
[ "https://Stackoverflow.com/questions/126584", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1116/" ]
I have a requirement to be be able to embed scanned tiff images into some SSRS reports. When I design a report in VS2005 and add an image control the tiff image displays perfectly however when I build it. I get the warning : `Warning 2 [rsInvalidMIMEType] The value of the MIMEType property for the image ‘image1’ is “image/tiff”, which is not a valid MIMEType. c:\SSRSStuff\TestReport.rdl 0 0` and instead of an image I get the little red x. Has anybody overcome this issue?
Assuming you're delivering the image file via IIS, use an ASP.NET page to change image formats and mime type to something that you *can* use. ``` Response.ContentType = "image/png"; Response.Clear(); using (Bitmap bmp = new Bitmap(tifFilepath)) bmp.Save(Response.OutputStream, ImageFormat.Png); Response.End(); ```
126,587
<p>I have an old server with a defunct evaluation version of SQL 2000 on it (from 2006), and two databases which were sitting on it.</p> <p>For some unknown reason, the LDF log files are missing. Presumed deleted.</p> <p>I have the mdf files (and in one case an ndf file too) for the databases which used to exist on that server, and I am trying to get them up and running on another SQL 2000 box I have sitting around.</p> <p><code>sp_attach_db</code> complains that the logfile is missing, and will not attach the database. Attempts to fool it by using a logfile from a database with the same name failed miserably. <code>sp_attach_single_file_db</code> will not work either. The mdf files have obviously not been cleanly detached.</p> <p>How do I get the databases attached and readable?</p>
[ { "answer_id": 126633, "author": "Jonathan", "author_id": 6910, "author_profile": "https://Stackoverflow.com/users/6910", "pm_score": 4, "selected": true, "text": "<p>I found this answer, which worked with my SQL 2000 machines:</p>\n\n<p><strong>How to attach a database with a non-cleanl...
2008/09/24
[ "https://Stackoverflow.com/questions/126587", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6910/" ]
I have an old server with a defunct evaluation version of SQL 2000 on it (from 2006), and two databases which were sitting on it. For some unknown reason, the LDF log files are missing. Presumed deleted. I have the mdf files (and in one case an ndf file too) for the databases which used to exist on that server, and I am trying to get them up and running on another SQL 2000 box I have sitting around. `sp_attach_db` complains that the logfile is missing, and will not attach the database. Attempts to fool it by using a logfile from a database with the same name failed miserably. `sp_attach_single_file_db` will not work either. The mdf files have obviously not been cleanly detached. How do I get the databases attached and readable?
I found this answer, which worked with my SQL 2000 machines: **How to attach a database with a non-cleanly detached MDF file.** **Step 1:** Make a new database with same name, and which uses the same files as the old one on the new server. **Step 2:** Stop SQL server, and move your mdf files (and any ndf files you have) over the top of the new ones you just created. Delete any log files. **Step 3:** Start SQL and run this to put the DB in emergency mode. ``` sp_configure 'allow updates', 1 go reconfigure with override GO update sysdatabases set status = 32768 where name = 'TestDB' go sp_configure 'allow updates', 0 go reconfigure with override GO ``` **Step 4:** Restart SQL server and observe that the DB is successfully in emergency mode. **Step 5:** Run this undocumented dbcc option to rebuild the log file (in the correct place) ``` DBCC REBUILD_LOG(TestDB,'D:\SQL_Log\TestDB_Log.LDF') ``` **Step 6:** You might need to reset the status. Even if you don't, it won't do any harm to do so. ``` exec sp_resetstatus TestDB ``` **Step 7:** Stop and start SQL to see your newly restored database.