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
112,102
<p>Is there a secure way of logging into a Gmail account on a web browser, from an external Java program? I know the following works, but is there a safer alternative?</p> <pre><code>Desktop.getDesktop().browse(new URI( "https://www.google.com/accounts/ServiceLoginAuth?continue=http://mail.google.com/gmail" + "&amp;service=mail&amp;Email=LOGIN&amp;Passwd=PASSWORD&amp;null=Sign+in")); </code></pre> <p><strong>Clarification</strong>: The external Java program is <a href="http://gmailassistant.sourceforge.net/" rel="nofollow noreferrer">GmailAssistant</a>, a Gmail notifier that already uses the IMAP capabilities of JavaMail. I just need a way of allowing the user to access the account directly in a web browser.</p>
[ { "answer_id": 112108, "author": "Armin Ronacher", "author_id": 19990, "author_profile": "https://Stackoverflow.com/users/19990", "pm_score": 1, "selected": false, "text": "<p>If you are afraid that the link is visible in the Page, create a javascript document that sends a POST request t...
2008/09/21
[ "https://Stackoverflow.com/questions/112102", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20029/" ]
Is there a secure way of logging into a Gmail account on a web browser, from an external Java program? I know the following works, but is there a safer alternative? ``` Desktop.getDesktop().browse(new URI( "https://www.google.com/accounts/ServiceLoginAuth?continue=http://mail.google.com/gmail" + "&service=mail&Email=LOGIN&Passwd=PASSWORD&null=Sign+in")); ``` **Clarification**: The external Java program is [GmailAssistant](http://gmailassistant.sourceforge.net/), a Gmail notifier that already uses the IMAP capabilities of JavaMail. I just need a way of allowing the user to access the account directly in a web browser.
Depending of how much you want to integrate, you can check Google single sign-on (SSO) api. I'm studing how to use it and the best way to integrate it <http://code.google.com/apis/apps/sso/saml_reference_implementation.html> Victor UPDATED: As a better option, you should check this link as well <http://esoeproject.org/>
112,158
<p>On my team, we usually do string concatentation like this:</p> <pre><code>var url = // some dynamically generated URL var sb = new StringBuffer(); sb.append("&lt;a href='").append(url).append("'&gt;click here&lt;/a&gt;"); </code></pre> <p>Obviously the following is much more readable:</p> <pre><code>var url = // some dynamically generated URL var sb = "&lt;a href='" + url + "'&gt;click here&lt;/a&gt;"; </code></pre> <p>But the JS experts claim that the <code>+</code> operator is less performant than <code>StringBuffer.append()</code>. Is this really true?</p>
[ { "answer_id": 112164, "author": "Michael Haren", "author_id": 29, "author_profile": "https://Stackoverflow.com/users/29", "pm_score": 5, "selected": false, "text": "<p>Yes it's true but you shouldn't care. Go with the one that's easier to read. If you have to benchmark your app, then fo...
2008/09/21
[ "https://Stackoverflow.com/questions/112158", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2648/" ]
On my team, we usually do string concatentation like this: ``` var url = // some dynamically generated URL var sb = new StringBuffer(); sb.append("<a href='").append(url).append("'>click here</a>"); ``` Obviously the following is much more readable: ``` var url = // some dynamically generated URL var sb = "<a href='" + url + "'>click here</a>"; ``` But the JS experts claim that the `+` operator is less performant than `StringBuffer.append()`. Is this really true?
Internet Explorer is the only browser which really suffers from this in today's world. (Versions 5, 6, and 7 were dog slow. 8 does not show the same degradation.) What's more, IE gets slower and slower the longer your string is. If you have long strings to concatenate then definitely use an array.join technique. (Or some StringBuffer wrapper around this, for readability.) But if your strings are short don't bother.
112,169
<p>For years I've been using ShellExecute() API to launch the default web browser from within my applications. Like this:</p> <pre><code>ShellExecute( hwnd, _T("open"), _T("http://www.winability.com/home/"), NULL, NULL, SW_NORMAL ); </code></pre> <p>It's been working fine until a couple of weeks ago, when Google released its Chrome browser. Now, if Chrome is installed on the computer, the ShellExecute API no longer opens a web page.</p> <p>Has anyone figured out yet how to solve this problem? (Short of detecting Chrome and displaying a message telling the user it's Chrome's fault?)</p> <p>EDIT: the code provided by Sergey seems to work, so I've accepted it as "the" answer. Except that I don't like the call to WinExec: MSDN reads that WinExec is provided only for compatibility with 16-bit applications. IOW, it may stop working with any Service Pack. I did not try it, but I would not be surprised if it has already stopped working with Windows x64, since it does not support 16-bit applications at all. So, instead of WinExec, I'm going to use ShellExecute, with the path taken from the registry like Sergey's code does, and the URL as the argument. Thanks! </p>
[ { "answer_id": 112213, "author": "Sergey Kornilov", "author_id": 10969, "author_profile": "https://Stackoverflow.com/users/10969", "pm_score": 3, "selected": true, "text": "<p>Here is the code that works across all browsers. The trick is to call WinExec if ShellExecute fails.</p>\n\n<pre...
2008/09/21
[ "https://Stackoverflow.com/questions/112169", "https://Stackoverflow.com", "https://Stackoverflow.com/users/17037/" ]
For years I've been using ShellExecute() API to launch the default web browser from within my applications. Like this: ``` ShellExecute( hwnd, _T("open"), _T("http://www.winability.com/home/"), NULL, NULL, SW_NORMAL ); ``` It's been working fine until a couple of weeks ago, when Google released its Chrome browser. Now, if Chrome is installed on the computer, the ShellExecute API no longer opens a web page. Has anyone figured out yet how to solve this problem? (Short of detecting Chrome and displaying a message telling the user it's Chrome's fault?) EDIT: the code provided by Sergey seems to work, so I've accepted it as "the" answer. Except that I don't like the call to WinExec: MSDN reads that WinExec is provided only for compatibility with 16-bit applications. IOW, it may stop working with any Service Pack. I did not try it, but I would not be surprised if it has already stopped working with Windows x64, since it does not support 16-bit applications at all. So, instead of WinExec, I'm going to use ShellExecute, with the path taken from the registry like Sergey's code does, and the URL as the argument. Thanks!
Here is the code that works across all browsers. The trick is to call WinExec if ShellExecute fails. ``` HINSTANCE GotoURL(LPCTSTR url, int showcmd) { TCHAR key[MAX_PATH + MAX_PATH]; // First try ShellExecute() HINSTANCE result = 0; CString strURL = url; if ( strURL.Find(".htm") <0 && strURL.Find("http") <0 ) result = ShellExecute(NULL, _T("open"), url, NULL, NULL, showcmd); // If it failed, get the .htm regkey and lookup the program if ((UINT)result <= HINSTANCE_ERROR) { if (GetRegKey(HKEY_CLASSES_ROOT, _T(".htm"), key) == ERROR_SUCCESS) { lstrcat(key, _T("\\shell\\open\\command")); if (GetRegKey(HKEY_CLASSES_ROOT,key,key) == ERROR_SUCCESS) { TCHAR *pos; pos = _tcsstr(key, _T("\"%1\"")); if (pos == NULL) { // No quotes found pos = strstr(key, _T("%1")); // Check for %1, without quotes if (pos == NULL) // No parameter at all... pos = key+lstrlen(key)-1; else *pos = '\0'; // Remove the parameter } else *pos = '\0'; // Remove the parameter lstrcat(pos, _T(" \"")); lstrcat(pos, url); lstrcat(pos, _T("\"")); result = (HINSTANCE) WinExec(key,showcmd); } } } return result; } ```
112,197
<p>I want to create a hidden field and create a link in one helper and then output both to my erb.</p> <pre><code>&lt;%= my_cool_helper "something", form %&gt; </code></pre> <p>Should out put the results of</p> <pre><code>link_to "something", a_path form.hidden_field "something".tableize, :value =&gt; "something" </code></pre> <p>What would the definition of the helper look like? The details of what link_to and the form.hidden_field don't really matter. What matters is, how do I return the output from two different calls.</p>
[ { "answer_id": 112210, "author": "Sixty4Bit", "author_id": 1681, "author_profile": "https://Stackoverflow.com/users/1681", "pm_score": 4, "selected": false, "text": "<p>So far the best I have come up with is:</p>\n\n<pre><code>def my_cool_helper(name, form)\n out = capture { link_to nam...
2008/09/21
[ "https://Stackoverflow.com/questions/112197", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1681/" ]
I want to create a hidden field and create a link in one helper and then output both to my erb. ``` <%= my_cool_helper "something", form %> ``` Should out put the results of ``` link_to "something", a_path form.hidden_field "something".tableize, :value => "something" ``` What would the definition of the helper look like? The details of what link\_to and the form.hidden\_field don't really matter. What matters is, how do I return the output from two different calls.
There are several ways to do this. Remember that the existing rails helpers like `link_to`, etc, just output strings. You can concatenate the strings together and return that (which is what I do most of the time, if things are simple). EG: ``` link_to( "something", something_path ) + #NOTE THE PLUS FOR STRING CONCAT form.hidden_field('something'.tableize, :value=>'something') ``` If you're doing things which are more complicated, you could just put that code in a partial, and have your helper call `render :partial`. If you're doing more complicated stuff than even that, then you may want to look at errtheblog's [block\_to\_partial](http://errtheblog.com/posts/11-block-to-partial) helper, which is pretty cool
112,224
<p>I made a panel and set it to fill the screen, now I can see the windows under it but I want it to be click through, meaning they could click a file or see a tool tip of another object through the transparency.</p> <blockquote> <blockquote> <p>RE: This may be too obvious, but have you tried sending the panel to the back by right clicking and choosing "Send to Back"?</p> </blockquote> </blockquote> <p>I mean like the desktop or firefox, not something within my project.</p>
[ { "answer_id": 112593, "author": "Phil Wright", "author_id": 6276, "author_profile": "https://Stackoverflow.com/users/6276", "pm_score": 6, "selected": true, "text": "<p>Creating a top level form that is transparent is very easy. Just make it fill the screen, or required area, and define...
2008/09/21
[ "https://Stackoverflow.com/questions/112224", "https://Stackoverflow.com", "https://Stackoverflow.com/users/18309/" ]
I made a panel and set it to fill the screen, now I can see the windows under it but I want it to be click through, meaning they could click a file or see a tool tip of another object through the transparency. > > > > > > RE: This may be too obvious, but have you tried sending the panel to the back by right clicking and choosing "Send to Back"? > > > > > > > > > I mean like the desktop or firefox, not something within my project.
Creating a top level form that is transparent is very easy. Just make it fill the screen, or required area, and define it to have a TransparenyKey color and BackColor of the same value. Getting it to ignore the mouse is simple enough, you just need to override the WndProc and tell the WM\_HITTEST that all mouse positions are to be treated as transparent. Thus causing the mouse to interact with whatever happens to be underneath the window. Something like this... ``` protected override void WndProc(ref Message m) { if (m.Msg == (int)WM_NCHITTEST) m.Result = (IntPtr)HTTRANSPARENT; else base.WndProc(ref m); } ```
112,234
<p>Let's say that I have two arrays (in Java),</p> <p>int[] numbers; and int[] colors;</p> <p>Each ith element of numbers corresponds to its ith element in colors. Ex, numbers = {4,2,1} colors = {0x11, 0x24, 0x01}; Means that number 4 is color 0x11, number 2 is 0x24, etc.</p> <p>I want to sort the numbers array, but then still have it so each element matches up with its pair in colors.</p> <p>Ex. numbers = {1,2,4}; colors = {0x01,0x24,0x11};</p> <p>What's the cleanest, simplest way to do this? The arrays have a few thousand items, so being in place would be best, but not required. Would it make sense to do an Arrays.sort() and a custom comparator? Using library functions as much as possible is preferable.</p> <p><strong>Note: I know the "best" solution is to make a class for the two elements and use a custom comparator. This question is meant to ask people for the quickest way to code this. Imagine being at a programming competition, you wouldn't want to be making all these extra classes, anonymous classes for the comparator, etc. Better yet, forget Java; how would you code it in C?</strong></p>
[ { "answer_id": 112240, "author": "1800 INFORMATION", "author_id": 3146, "author_profile": "https://Stackoverflow.com/users/3146", "pm_score": 0, "selected": false, "text": "<p>You need to sort the colors array by its relative item in the numbers array. Specify a comparator that compares ...
2008/09/21
[ "https://Stackoverflow.com/questions/112234", "https://Stackoverflow.com", "https://Stackoverflow.com/users/16773/" ]
Let's say that I have two arrays (in Java), int[] numbers; and int[] colors; Each ith element of numbers corresponds to its ith element in colors. Ex, numbers = {4,2,1} colors = {0x11, 0x24, 0x01}; Means that number 4 is color 0x11, number 2 is 0x24, etc. I want to sort the numbers array, but then still have it so each element matches up with its pair in colors. Ex. numbers = {1,2,4}; colors = {0x01,0x24,0x11}; What's the cleanest, simplest way to do this? The arrays have a few thousand items, so being in place would be best, but not required. Would it make sense to do an Arrays.sort() and a custom comparator? Using library functions as much as possible is preferable. **Note: I know the "best" solution is to make a class for the two elements and use a custom comparator. This question is meant to ask people for the quickest way to code this. Imagine being at a programming competition, you wouldn't want to be making all these extra classes, anonymous classes for the comparator, etc. Better yet, forget Java; how would you code it in C?**
You could use sort() with a custom comparator if you kept a third array with the index, and sorted on that, leaving the data intact. Java code example: ``` Integer[] idx = new Integer[numbers.length]; for( int i = 0 ; i < idx.length; i++ ) idx[i] = i; Arrays.sort(idx, new Comparator<Integer>() { public int compare(Integer i1, Integer i2) { return Double.compare(numbers[i1], numbers[i2]); } }); // numbers[idx[i]] is the sorted number at index i // colors[idx[i]] is the sorted color at index i ``` Note that you have to use `Integer` instead of `int` or you can't use a custom comparator.
112,235
<p>There are certain Crystal Reports features that cannot be combined in the same report, for example SQL command objects and server side grouping. However, as far as I can find, the built-in help doesn't seem to clearly document these conflicts. For example, checking the help page for either of those features doesn't mention that it doesn't work with the other. I want to be able to find out about these conflicts when I decide to use a new feature, not later when I go to use some other feature and the option is greyed out. Is there any place that documents these conflicts?</p> <p>I am specifically working with Crystal Reports XI. Bonus points if the list of conflicts documents what range of versions each feature is available and conflicting in.</p> <p>I have now also checked the release notes (release.pdf on install CD), and it does not have any answers to this question.</p>
[ { "answer_id": 112240, "author": "1800 INFORMATION", "author_id": 3146, "author_profile": "https://Stackoverflow.com/users/3146", "pm_score": 0, "selected": false, "text": "<p>You need to sort the colors array by its relative item in the numbers array. Specify a comparator that compares ...
2008/09/21
[ "https://Stackoverflow.com/questions/112235", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20068/" ]
There are certain Crystal Reports features that cannot be combined in the same report, for example SQL command objects and server side grouping. However, as far as I can find, the built-in help doesn't seem to clearly document these conflicts. For example, checking the help page for either of those features doesn't mention that it doesn't work with the other. I want to be able to find out about these conflicts when I decide to use a new feature, not later when I go to use some other feature and the option is greyed out. Is there any place that documents these conflicts? I am specifically working with Crystal Reports XI. Bonus points if the list of conflicts documents what range of versions each feature is available and conflicting in. I have now also checked the release notes (release.pdf on install CD), and it does not have any answers to this question.
You could use sort() with a custom comparator if you kept a third array with the index, and sorted on that, leaving the data intact. Java code example: ``` Integer[] idx = new Integer[numbers.length]; for( int i = 0 ; i < idx.length; i++ ) idx[i] = i; Arrays.sort(idx, new Comparator<Integer>() { public int compare(Integer i1, Integer i2) { return Double.compare(numbers[i1], numbers[i2]); } }); // numbers[idx[i]] is the sorted number at index i // colors[idx[i]] is the sorted color at index i ``` Note that you have to use `Integer` instead of `int` or you can't use a custom comparator.
112,249
<p>I have a very large database table in PostgresQL and a column like "copied". Every new row starts uncopied and will later be replicated to another thing by a background programm. There is an partial index on that table "btree(ID) WHERE replicated=0". The background programm does a select for at most 2000 entries (LIMIT 2000), works on them and then commits the changes in one transaction using 2000 prepared sql-commands.</p> <p>Now the problem ist that I want to give the user an option to reset this replicated-value, make it all zero again.</p> <p>An update table set replicated=0;</p> <p>is not possible:</p> <ul> <li>It takes very much time</li> <li>It duplicates the size of the tabel because of MVCC</li> <li>It is done in one transaction: It either fails or goes through.</li> </ul> <p>I actually don't need transaction-features for this case: If the system goes down, it shall process only parts of it.</p> <p>Several other problems: Doing an </p> <pre><code>update set replicated=0 where id &gt;10000 and id&lt;20000 </code></pre> <p>is also bad: It does a sequential scan all over the whole table which is too slow. If it weren't doing that, it would still be slow because it would be too many seeks.</p> <p>What I really need is a way of going through all rows, changing them and not being bound to a giant transaction.</p> <p>Strangely, an</p> <pre><code>UPDATE table SET replicated=0 WHERE ID in (SELECT id from table WHERE replicated= LIMIT 10000) </code></pre> <p>is also slow, although it should be a good thing: Go through the table in DISK-order...</p> <p>(Note that in that case there was also an index that covered this)</p> <p>(An update LIMIT like Mysql is unavailable for PostgresQL)</p> <p>BTW: The real problem is more complicated and we're talking about an embedded system here that is already deployed, so remote schema changes are difficult, but possible It's PostgresQL 7.4 unfortunately.</p> <p>The amount of rows I'm talking about is e.g. 90000000. The size of the databse can be several dozend gigabytes.</p> <p>The database itself only contains 5 tables, one is a very large one. But that is not bad design, because these embedded boxes only operate with one kind of entity, it's not an ERP-system or something like that!</p> <p>Any ideas?</p>
[ { "answer_id": 112260, "author": "Dan", "author_id": 17121, "author_profile": "https://Stackoverflow.com/users/17121", "pm_score": 3, "selected": false, "text": "<p>How about adding a new table to store this replicated value (and a primary key to link each record to the main table). Then...
2008/09/21
[ "https://Stackoverflow.com/questions/112249", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20088/" ]
I have a very large database table in PostgresQL and a column like "copied". Every new row starts uncopied and will later be replicated to another thing by a background programm. There is an partial index on that table "btree(ID) WHERE replicated=0". The background programm does a select for at most 2000 entries (LIMIT 2000), works on them and then commits the changes in one transaction using 2000 prepared sql-commands. Now the problem ist that I want to give the user an option to reset this replicated-value, make it all zero again. An update table set replicated=0; is not possible: * It takes very much time * It duplicates the size of the tabel because of MVCC * It is done in one transaction: It either fails or goes through. I actually don't need transaction-features for this case: If the system goes down, it shall process only parts of it. Several other problems: Doing an ``` update set replicated=0 where id >10000 and id<20000 ``` is also bad: It does a sequential scan all over the whole table which is too slow. If it weren't doing that, it would still be slow because it would be too many seeks. What I really need is a way of going through all rows, changing them and not being bound to a giant transaction. Strangely, an ``` UPDATE table SET replicated=0 WHERE ID in (SELECT id from table WHERE replicated= LIMIT 10000) ``` is also slow, although it should be a good thing: Go through the table in DISK-order... (Note that in that case there was also an index that covered this) (An update LIMIT like Mysql is unavailable for PostgresQL) BTW: The real problem is more complicated and we're talking about an embedded system here that is already deployed, so remote schema changes are difficult, but possible It's PostgresQL 7.4 unfortunately. The amount of rows I'm talking about is e.g. 90000000. The size of the databse can be several dozend gigabytes. The database itself only contains 5 tables, one is a very large one. But that is not bad design, because these embedded boxes only operate with one kind of entity, it's not an ERP-system or something like that! Any ideas?
How about adding a new table to store this replicated value (and a primary key to link each record to the main table). Then you simply add a record for every replicated item, and delete records to remove the replicated flag. (Or maybe the other way around - a record for every non-replicated record, depending on which is the common case). That would also simplify the case when you want to set them all back to 0, as you can just truncate the table (which zeroes the table size on disk, you don't even have to vacuum to free up the space)
112,277
<p>Static metaprogramming (aka "template metaprogramming") is a great C++ technique that allows the execution of programs at compile-time. A light bulb went off in my head as soon as I read this canonical metaprogramming example:</p> <pre><code>#include &lt;iostream&gt; using namespace std; template&lt; int n &gt; struct factorial { enum { ret = factorial&lt; n - 1 &gt;::ret * n }; }; template&lt;&gt; struct factorial&lt; 0 &gt; { enum { ret = 1 }; }; int main() { cout &lt;&lt; "7! = " &lt;&lt; factorial&lt; 7 &gt;::ret &lt;&lt; endl; // 5040 return 0; } </code></pre> <p>If one wants to learn more about C++ static metaprogramming, what are the best sources (books, websites, on-line courseware, whatever)?</p>
[ { "answer_id": 112285, "author": "Maxim Ananyev", "author_id": 404206, "author_profile": "https://Stackoverflow.com/users/404206", "pm_score": 2, "selected": false, "text": "<p>google Alexandrescu, Modern C++ Design: Generic Programming and Design Patterns Applied</p>\n" }, { "an...
2008/09/21
[ "https://Stackoverflow.com/questions/112277", "https://Stackoverflow.com", "https://Stackoverflow.com/users/10559/" ]
Static metaprogramming (aka "template metaprogramming") is a great C++ technique that allows the execution of programs at compile-time. A light bulb went off in my head as soon as I read this canonical metaprogramming example: ``` #include <iostream> using namespace std; template< int n > struct factorial { enum { ret = factorial< n - 1 >::ret * n }; }; template<> struct factorial< 0 > { enum { ret = 1 }; }; int main() { cout << "7! = " << factorial< 7 >::ret << endl; // 5040 return 0; } ``` If one wants to learn more about C++ static metaprogramming, what are the best sources (books, websites, on-line courseware, whatever)?
*[Answering my own question]* The best introductions I've found so far are chapter 10, "Static Metaprogramming in C++" from *Generative Programming, Methods, Tools, and Applications* by Krzysztof Czarnecki and Ulrich W. Eisenecker, ISBN-13: 9780201309775; and chapter 17, "Metaprograms" of *C++ Templates: The Complete Guide* by David Vandevoorder and Nicolai M. Josuttis, ISBN-13: 9780201734843. ![alt text](https://i.stack.imgur.com/q79o3.gif) ![alt text](https://i.stack.imgur.com/FreHD.gif) ![alt text](https://i.stack.imgur.com/89bSK.gif) ![alt text](https://i.stack.imgur.com/oDM2G.gif) Todd Veldhuizen has an excellent tutorial [here](http://www.cs.rpi.edu/~musser/design/blitz/meta-art.html). A good resource for C++ programming in general is *Modern C++ Design* by Andrei Alexandrescu, ISBN-13: 9780201704310. This book mixes a bit of metaprogramming with other template techniques. For metaprogramming in particular, see sections 2.1 "Compile-Time Assertions", 2.4 "Mapping Integral Constants to Types", 2.6 "Type Selection", 2.7 "Detecting Convertibility and Inheritance at Compile Time", 2.9 "`NullType` and `EmptyType`" and 2.10 "Type Traits". The best intermediate/advanced resource I've found is *C++ Template Metaprogramming* by David Abrahams and Aleksey Gurtovoy, ISBN-13: 9780321227256 If you'd prefer just one book, get *C++ Templates: The Complete Guide* since it is also the definitive reference for templates in general.
112,372
<p>Is it possible to over interface? when designing an system now, I will start from interfaces and progressively write unit tests along with the interfaces until I have a pattern that works well.. I'll move onto writing some concrete classes and set the unit tests up against these..</p> <p>Now I'm someone who loves interfaces, I will generally end up only ever passing/returning primatives or interfaces around when I control the code.. so far I've found this to be ideal, you can easily adapt and enhance a system generally without impacting the dependent systems.</p> <p>I obviously don't need to sell the reasons for using interfaces, but im wondering if its overboard to interface everything, ps. I'm <strong>not</strong> talking about blank interfaces as in something crazy like:</p> <pre><code>interface IStringCollection : ICollection&lt;string&gt; { } </code></pre> <p>I'm talking more something like:</p> <pre><code>interface ISomethingProvider { ISomething Provide(ISomethingOptions options); } </code></pre> <p>Is this really over the top? my reasoning is that any type could gain from interfacing at some point.. and the only real problem I've had is that I've had to learn what I think is a better way to design classes, as you don't have daft interactions and 'hacks' going on.</p> <p>Would love your feedback about if this is a timebomb, and when you decide to interface vs not.. </p> <p>ps- this isn't really so much about how to write interfaces.</p>
[ { "answer_id": 112385, "author": "TonyOssa", "author_id": 3276, "author_profile": "https://Stackoverflow.com/users/3276", "pm_score": 0, "selected": false, "text": "<p>ISwissArmyKnife!</p>\n\n<p>Consult this:</p>\n\n<p><a href=\"http://thedailywtf.com/Articles/Classic-WTF-Implements-ISwi...
2008/09/21
[ "https://Stackoverflow.com/questions/112372", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
Is it possible to over interface? when designing an system now, I will start from interfaces and progressively write unit tests along with the interfaces until I have a pattern that works well.. I'll move onto writing some concrete classes and set the unit tests up against these.. Now I'm someone who loves interfaces, I will generally end up only ever passing/returning primatives or interfaces around when I control the code.. so far I've found this to be ideal, you can easily adapt and enhance a system generally without impacting the dependent systems. I obviously don't need to sell the reasons for using interfaces, but im wondering if its overboard to interface everything, ps. I'm **not** talking about blank interfaces as in something crazy like: ``` interface IStringCollection : ICollection<string> { } ``` I'm talking more something like: ``` interface ISomethingProvider { ISomething Provide(ISomethingOptions options); } ``` Is this really over the top? my reasoning is that any type could gain from interfacing at some point.. and the only real problem I've had is that I've had to learn what I think is a better way to design classes, as you don't have daft interactions and 'hacks' going on. Would love your feedback about if this is a timebomb, and when you decide to interface vs not.. ps- this isn't really so much about how to write interfaces.
Interfaces describe a contract for behavior. If you need to address some set of objects according to a behavioral pattern, interfaces are useful, not so much if you're simply describing the structure of objects. I think you need to have a good reason to use them, such as using a factory that creates behaviorally related objects or establishing a behavioral contract for part of a library. Using interfaces aimlessly can make a library difficult to read / understand / maintain.
112,396
<p>I set a passphrase when creating a new SSH key on my laptop. But, as I realise now, this is quite painful when you are trying to commit (<a href="http://en.wikipedia.org/wiki/Git_%28software%29" rel="noreferrer">Git</a> and <a href="http://en.wikipedia.org/wiki/Apache_Subversion" rel="noreferrer">SVN</a>) to a remote location over SSH many times in an hour.</p> <p>One way I can think of is, delete my SSH keys and create new. Is there a way to remove the passphrase, while still keeping the same keys?</p>
[ { "answer_id": 112409, "author": "Torsten Marek", "author_id": 9567, "author_profile": "https://Stackoverflow.com/users/9567", "pm_score": 12, "selected": true, "text": "<p>Short answer:</p>\n\n<pre><code>$ ssh-keygen -p\n</code></pre>\n\n<p>This will then prompt you to enter the keyfile...
2008/09/21
[ "https://Stackoverflow.com/questions/112396", "https://Stackoverflow.com", "https://Stackoverflow.com/users/14191/" ]
I set a passphrase when creating a new SSH key on my laptop. But, as I realise now, this is quite painful when you are trying to commit ([Git](http://en.wikipedia.org/wiki/Git_%28software%29) and [SVN](http://en.wikipedia.org/wiki/Apache_Subversion)) to a remote location over SSH many times in an hour. One way I can think of is, delete my SSH keys and create new. Is there a way to remove the passphrase, while still keeping the same keys?
Short answer: ``` $ ssh-keygen -p ``` This will then prompt you to enter the keyfile location, the old passphrase, and the new passphrase (which can be left blank to have no passphrase). --- If you would like to do it all on one line without prompts do: ``` $ ssh-keygen -p [-P old_passphrase] [-N new_passphrase] [-f keyfile] ``` **Important:** Beware that when executing commands they will typically be logged in your `~/.bash_history` file (or similar) in plain text including all arguments provided (i.e. the passphrases in this case). It is, therefore, is recommended that you use the first option unless you have a specific reason to do otherwise. Notice though that you can still use `-f keyfile` without having to specify `-P` nor `-N`, and that the keyfile defaults to `~/.ssh/id_rsa`, so in many cases, it's not even needed. You might want to consider using ssh-agent, which can cache the passphrase for a time. The latest versions of gpg-agent also support the protocol that is used by ssh-agent.
112,412
<p>I would like to use Visual Studio 2008 to the greatest extent possible while effectively compiling/linking/building/etc code as if all these build processes were being done by the tools provided with MASM 6.11. The exact version of MASM does not matter, so long as it's within the 6.x range, as that is what my college is using to teach 16-bit assembly.</p> <p>I have done some research on the subject and have come to the conclusion that there are several options:</p> <ol> <li>Reconfigure VS to call the MASM 6.11 executables with the same flags, etc as MASM 6.11 would natively do.</li> <li>Create intermediary batch file(s) to be called by VS to then invoke the proper commands for MASM's linker, etc.</li> <li>Reconfigure VS's built-in build tools/rules (assembler, linker, etc) to provide an environment identical to the one used by MASM 6.11.</li> </ol> <p>Option (2) was brought up when I realized that the options available in VS's "External Tools" interface may be insufficient to correctly invoke MASM's build tools, thus a batch file to interpret VS's strict method of passing arguments might be helpful, as a lot of my learning about how to get this working involved my manually calling ML.exe, LINK.exe, etc from the command prompt.</p> <p>Below are several links that may prove useful in answering my question. Please keep in mind that I have read them all and none are the actual solution. I can only hope my specifying MASM 6.11 doesn't prevent anyone from contributing a perhaps more generalized answer.</p> <p>Similar method used to Option (2), but users on the thread are not contactable:<br> <a href="http://www.codeguru.com/forum/archive/index.php/t-284051.html" rel="nofollow noreferrer">http://www.codeguru.com/forum/archive/index.php/t-284051.html</a><br> (also, I have my doubts about the necessity of an intermediary batch file)</p> <p>Out of date explanation to my question:<br> <a href="http://www.cs.fiu.edu/~downeyt/cop3402/masmaul.html" rel="nofollow noreferrer">http://www.cs.fiu.edu/~downeyt/cop3402/masmaul.html</a></p> <p>Probably the closest thing I've come to a definitive solution, but refers to a suite of tools from something besides MASM, also uses a batch file:<br> <a href="http://www.kipirvine.com/asm/gettingStarted/index.htm#16-bit" rel="nofollow noreferrer">http://www.kipirvine.com/asm/gettingStarted/index.htm#16-bit</a></p> <p>I apologize if my terminology for the tools used in each step of the code -> exe process is off, but since I'm trying to reproduce the entirety of steps in between completion of writing the code and generating an executable, I don't think it matters much.</p>
[ { "answer_id": 112600, "author": "shoosh", "author_id": 9611, "author_profile": "https://Stackoverflow.com/users/9611", "pm_score": 1, "selected": false, "text": "<p>instead of batch files, why not use the a custom build step defined on the file?</p>\n" }, { "answer_id": 192118, ...
2008/09/21
[ "https://Stackoverflow.com/questions/112412", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20110/" ]
I would like to use Visual Studio 2008 to the greatest extent possible while effectively compiling/linking/building/etc code as if all these build processes were being done by the tools provided with MASM 6.11. The exact version of MASM does not matter, so long as it's within the 6.x range, as that is what my college is using to teach 16-bit assembly. I have done some research on the subject and have come to the conclusion that there are several options: 1. Reconfigure VS to call the MASM 6.11 executables with the same flags, etc as MASM 6.11 would natively do. 2. Create intermediary batch file(s) to be called by VS to then invoke the proper commands for MASM's linker, etc. 3. Reconfigure VS's built-in build tools/rules (assembler, linker, etc) to provide an environment identical to the one used by MASM 6.11. Option (2) was brought up when I realized that the options available in VS's "External Tools" interface may be insufficient to correctly invoke MASM's build tools, thus a batch file to interpret VS's strict method of passing arguments might be helpful, as a lot of my learning about how to get this working involved my manually calling ML.exe, LINK.exe, etc from the command prompt. Below are several links that may prove useful in answering my question. Please keep in mind that I have read them all and none are the actual solution. I can only hope my specifying MASM 6.11 doesn't prevent anyone from contributing a perhaps more generalized answer. Similar method used to Option (2), but users on the thread are not contactable: <http://www.codeguru.com/forum/archive/index.php/t-284051.html> (also, I have my doubts about the necessity of an intermediary batch file) Out of date explanation to my question: <http://www.cs.fiu.edu/~downeyt/cop3402/masmaul.html> Probably the closest thing I've come to a definitive solution, but refers to a suite of tools from something besides MASM, also uses a batch file: <http://www.kipirvine.com/asm/gettingStarted/index.htm#16-bit> I apologize if my terminology for the tools used in each step of the code -> exe process is off, but since I'm trying to reproduce the entirety of steps in between completion of writing the code and generating an executable, I don't think it matters much.
There is a MASM rules file located at (32-bit system remove `(x86)`): ``` C:\Program Files (x86)\Microsoft Visual Studio 9.0\VC\VCProjectDefaults\masm.rules ``` Copy that file to your project directory, and add it to the Custom Build Rules for your project. Then "Modify Rule File...", select the MASM build rule and "Modify Build Rule...". Add a property: * User property type: **String** * Default value: **\*.inc** * Description: **Add additional MASM file dependencies.** * Display name: **Additional Dependencies** * Is read only: **False** * Name: **AdditionalDependencies** * Property page name: **General** * Switch: **[value]** Set the Additional Dependencies value to **[AdditionalDependencies]**. The build should now automatically detect changes to `*.inc`, and you can edit the properties for an individual asm file to specify others.
112,433
<p>In a C++ project I'm working on, I have a <em>flag</em> kind of value which can have four values. Those four flags can be combined. Flags describe the records in database and can be:</p> <ul> <li>new record</li> <li>deleted record</li> <li>modified record</li> <li>existing record</li> </ul> <p>Now, for each record I wish to keep this attribute, so I could use an enum:</p> <pre><code>enum { xNew, xDeleted, xModified, xExisting } </code></pre> <p>However, in other places in code, I need to select which records are to be visible to the user, so I'd like to be able to pass that as a single parameter, like: </p> <pre><code>showRecords(xNew | xDeleted); </code></pre> <p>So, it seems I have three possible appoaches:</p> <pre><code>#define X_NEW 0x01 #define X_DELETED 0x02 #define X_MODIFIED 0x04 #define X_EXISTING 0x08 </code></pre> <p>or</p> <pre><code>typedef enum { xNew = 1, xDeleted, xModified = 4, xExisting = 8 } RecordType; </code></pre> <p>or </p> <pre><code>namespace RecordType { static const uint8 xNew = 1; static const uint8 xDeleted = 2; static const uint8 xModified = 4; static const uint8 xExisting = 8; } </code></pre> <p>Space requirements are important (byte vs int) but not crucial. With defines I lose type safety, and with <code>enum</code> I lose some space (integers) and probably have to cast when I want to do a bitwise operation. With <code>const</code> I think I also lose type safety since a random <code>uint8</code> could get in by mistake.</p> <p>Is there some other cleaner way?</p> <p>If not, what would you use and why?</p> <p>P.S. The rest of the code is rather clean modern C++ without <code>#define</code>s, and I have used namespaces and templates in few spaces, so those aren't out of question either.</p>
[ { "answer_id": 112445, "author": "Jonathan Rupp", "author_id": 12502, "author_profile": "https://Stackoverflow.com/users/12502", "pm_score": 2, "selected": false, "text": "<p>Even if you have to use 4 byte to store an enum (I'm not that familiar with C++ -- I know you can specify the und...
2008/09/21
[ "https://Stackoverflow.com/questions/112433", "https://Stackoverflow.com", "https://Stackoverflow.com/users/14690/" ]
In a C++ project I'm working on, I have a *flag* kind of value which can have four values. Those four flags can be combined. Flags describe the records in database and can be: * new record * deleted record * modified record * existing record Now, for each record I wish to keep this attribute, so I could use an enum: ``` enum { xNew, xDeleted, xModified, xExisting } ``` However, in other places in code, I need to select which records are to be visible to the user, so I'd like to be able to pass that as a single parameter, like: ``` showRecords(xNew | xDeleted); ``` So, it seems I have three possible appoaches: ``` #define X_NEW 0x01 #define X_DELETED 0x02 #define X_MODIFIED 0x04 #define X_EXISTING 0x08 ``` or ``` typedef enum { xNew = 1, xDeleted, xModified = 4, xExisting = 8 } RecordType; ``` or ``` namespace RecordType { static const uint8 xNew = 1; static const uint8 xDeleted = 2; static const uint8 xModified = 4; static const uint8 xExisting = 8; } ``` Space requirements are important (byte vs int) but not crucial. With defines I lose type safety, and with `enum` I lose some space (integers) and probably have to cast when I want to do a bitwise operation. With `const` I think I also lose type safety since a random `uint8` could get in by mistake. Is there some other cleaner way? If not, what would you use and why? P.S. The rest of the code is rather clean modern C++ without `#define`s, and I have used namespaces and templates in few spaces, so those aren't out of question either.
Combine the strategies to reduce the disadvantages of a single approach. I work in embedded systems so the following solution is based on the fact that integer and bitwise operators are fast, low memory & low in flash usage. Place the enum in a namespace to prevent the constants from polluting the global namespace. ``` namespace RecordType { ``` An enum declares and defines a compile time checked typed. Always use compile time type checking to make sure arguments and variables are given the correct type. There is no need for the typedef in C++. ``` enum TRecordType { xNew = 1, xDeleted = 2, xModified = 4, xExisting = 8, ``` Create another member for an invalid state. This can be useful as error code; for example, when you want to return the state but the I/O operation fails. It is also useful for debugging; use it in initialisation lists and destructors to know if the variable's value should be used. ``` xInvalid = 16 }; ``` Consider that you have two purposes for this type. To track the current state of a record and to create a mask to select records in certain states. Create an inline function to test if the value of the type is valid for your purpose; as a state marker vs a state mask. This will catch bugs as the `typedef` is just an `int` and a value such as `0xDEADBEEF` may be in your variable through uninitialised or mispointed variables. ``` inline bool IsValidState( TRecordType v) { switch(v) { case xNew: case xDeleted: case xModified: case xExisting: return true; } return false; } inline bool IsValidMask( TRecordType v) { return v >= xNew && v < xInvalid ; } ``` Add a `using` directive if you want to use the type often. ``` using RecordType ::TRecordType ; ``` The value checking functions are useful in asserts to trap bad values as soon as they are used. The quicker you catch a bug when running, the less damage it can do. Here are some examples to put it all together. ``` void showRecords(TRecordType mask) { assert(RecordType::IsValidMask(mask)); // do stuff; } void wombleRecord(TRecord rec, TRecordType state) { assert(RecordType::IsValidState(state)); if (RecordType ::xNew) { // ... } in runtime TRecordType updateRecord(TRecord rec, TRecordType newstate) { assert(RecordType::IsValidState(newstate)); //... if (! access_was_successful) return RecordType ::xInvalid; return newstate; } ``` The only way to ensure correct value safety is to use a dedicated class with operator overloads and that is left as an exercise for another reader.
112,439
<p>If you had read my other <a href="https://stackoverflow.com/questions/111700/6502-cpu-emulation">question</a>, you'll know I've spent this weekend putting together a 6502 CPU emulator as a programming exercise.</p> <p>The CPU emulator is mostly complete, and seems to be fairly accurate from my limited testing, however it is running incredibly fast, and I want to throttle it down to the actual clock speed of the machine.</p> <p>My current test loop is this:</p> <pre><code> // Just loop infinitely. while (1 == 1) { CPU.ClockCyclesBeforeNext--; if (CPU.ClockCyclesBeforeNext &lt;= 0) { // Find out how many clock cycles this instruction will take CPU.ClockCyclesBeforeNext = CPU.OpcodeMapper.Map[CPU.Memory[CPU.PC]].CpuCycles; // Run the instruction CPU.ExecuteInstruction(CPU.Memory[CPU.PC]); // Debugging Info CPU.DumpDebug(); Console.WriteLine(CPU.OpcodeMapper.Map[CPU.Memory[CPU.PC]].ArgumentLength); // Move to next instruction CPU.PC += 1 + CPU.OpcodeMapper.Map[CPU.Memory[CPU.PC]].ArgumentLength; } } </code></pre> <p>As you can tell, each opcode takes a specific amount of time to complete, so I do not run the next instruction until I count down the CPU Cycle clock. This provides proper timing between opcodes, its just that the entire thing runs way to fast.</p> <p>The targeted CPU speed is 1.79mhz, however I'd like whatever solution to the clock issue to keep the speed at 1.79mhz even as I add complexity, so I don't have to adjust it up.</p> <p>Any ideas?</p>
[ { "answer_id": 112467, "author": "Lou Franco", "author_id": 3937, "author_profile": "https://Stackoverflow.com/users/3937", "pm_score": 2, "selected": false, "text": "<p>I would use the clock cycles to calculate time and them sleep the difference in time. Of course, to do this, you need...
2008/09/21
[ "https://Stackoverflow.com/questions/112439", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1965/" ]
If you had read my other [question](https://stackoverflow.com/questions/111700/6502-cpu-emulation), you'll know I've spent this weekend putting together a 6502 CPU emulator as a programming exercise. The CPU emulator is mostly complete, and seems to be fairly accurate from my limited testing, however it is running incredibly fast, and I want to throttle it down to the actual clock speed of the machine. My current test loop is this: ``` // Just loop infinitely. while (1 == 1) { CPU.ClockCyclesBeforeNext--; if (CPU.ClockCyclesBeforeNext <= 0) { // Find out how many clock cycles this instruction will take CPU.ClockCyclesBeforeNext = CPU.OpcodeMapper.Map[CPU.Memory[CPU.PC]].CpuCycles; // Run the instruction CPU.ExecuteInstruction(CPU.Memory[CPU.PC]); // Debugging Info CPU.DumpDebug(); Console.WriteLine(CPU.OpcodeMapper.Map[CPU.Memory[CPU.PC]].ArgumentLength); // Move to next instruction CPU.PC += 1 + CPU.OpcodeMapper.Map[CPU.Memory[CPU.PC]].ArgumentLength; } } ``` As you can tell, each opcode takes a specific amount of time to complete, so I do not run the next instruction until I count down the CPU Cycle clock. This provides proper timing between opcodes, its just that the entire thing runs way to fast. The targeted CPU speed is 1.79mhz, however I'd like whatever solution to the clock issue to keep the speed at 1.79mhz even as I add complexity, so I don't have to adjust it up. Any ideas?
I wrote a Z80 emulator many years ago, and to do cycle accurate execution, I divided the clock rate into a number of small blocks and had the core execute that many clock cycles. In my case, I tied it to the frame rate of the game system I was emulating. Each opcode knew how many cycles it took to execute and the core would keep running opcodes until the specified number of cycles had been executed. I had an outer run loop that would run the cpu core, and run other parts of the emulated system and then sleep until the start time of the next iteration. EDIT: Adding example of run loop. ``` int execute_run_loop( int cycles ) { int n = 0; while( n < cycles ) { /* Returns number of cycles executed */ n += execute_next_opcode(); } return n; } ``` Hope this helps.
112,440
<p>I'm getting a JS error on displaying a page: Nothing concrete is specified but the line where it seems to be thrown. When looking into the source code of the page, I see the error is thrown inside the following script, but I can't understand why! It's only about loading images!</p> <pre><code> &lt;SCRIPT language=JavaScript&gt; &lt;!-- function newImage(arg) { var rslt = new Image(); rslt.src = arg; return rslt; } function changeImages(a, b) { a.src = b; } newImage("\/_layouts\/images\/icon1.gif"); newImage("\/_layouts\/images\/icon2.gif"); // --&gt; &lt;/SCRIPT&gt; </code></pre> <p>The error I am getting is when clicking on a drop down context menu on a page, for this line:</p> <pre><code>newImage("\/_layouts\/images\/icon1.gif"); </code></pre> <blockquote> <p>The object doesn't accept this property or method Code: 0</p> </blockquote> <p>I really don't see what could happen... Any tips on what may be happening here?</p>
[ { "answer_id": 112449, "author": "Florian Bösch", "author_id": 19435, "author_profile": "https://Stackoverflow.com/users/19435", "pm_score": 1, "selected": false, "text": "<p>Write proper xml with the \" around attributes.</p>\n\n<pre><code>&lt;script type=\"text/javascript\"&gt;\nfuncti...
2008/09/21
[ "https://Stackoverflow.com/questions/112440", "https://Stackoverflow.com", "https://Stackoverflow.com/users/19159/" ]
I'm getting a JS error on displaying a page: Nothing concrete is specified but the line where it seems to be thrown. When looking into the source code of the page, I see the error is thrown inside the following script, but I can't understand why! It's only about loading images! ``` <SCRIPT language=JavaScript> <!-- function newImage(arg) { var rslt = new Image(); rslt.src = arg; return rslt; } function changeImages(a, b) { a.src = b; } newImage("\/_layouts\/images\/icon1.gif"); newImage("\/_layouts\/images\/icon2.gif"); // --> </SCRIPT> ``` The error I am getting is when clicking on a drop down context menu on a page, for this line: ``` newImage("\/_layouts\/images\/icon1.gif"); ``` > > The object doesn't accept this property or method > Code: 0 > > > I really don't see what could happen... Any tips on what may be happening here?
Have you tried loading your scripts into a JS debugger such as [Aptana](http://www.aptana.com/) or Firefox plugin like [Firebug](https://addons.mozilla.org/en-US/firefox/addon/1843)?
112,503
<p>Given an array of <strong>n</strong> Objects, let's say it is an <strong>array of strings</strong>, and it has the following values:</p> <pre><code>foo[0] = "a"; foo[1] = "cc"; foo[2] = "a"; foo[3] = "dd"; </code></pre> <p>What do I have to do to delete/remove all the strings/objects equal to <strong>"a"</strong> in the array?</p>
[ { "answer_id": 112507, "author": "Dustman", "author_id": 16398, "author_profile": "https://Stackoverflow.com/users/16398", "pm_score": 4, "selected": false, "text": "<p>Make a <code>List</code> out of the array with <code>Arrays.asList()</code>, and call <code>remove()</code> on all the ...
2008/09/21
[ "https://Stackoverflow.com/questions/112503", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4358/" ]
Given an array of **n** Objects, let's say it is an **array of strings**, and it has the following values: ``` foo[0] = "a"; foo[1] = "cc"; foo[2] = "a"; foo[3] = "dd"; ``` What do I have to do to delete/remove all the strings/objects equal to **"a"** in the array?
[If you want some ready-to-use code, please scroll to my "Edit3" (after the cut). The rest is here for posterity.] To flesh out [Dustman's idea](https://stackoverflow.com/a/112507/13): ``` List<String> list = new ArrayList<String>(Arrays.asList(array)); list.removeAll(Arrays.asList("a")); array = list.toArray(array); ``` Edit: I'm now using `Arrays.asList` instead of `Collections.singleton`: singleton is limited to one entry, whereas the `asList` approach allows you to add other strings to filter out later: `Arrays.asList("a", "b", "c")`. Edit2: The above approach retains the same array (so the array is still the same length); the element after the last is set to null. If you want a *new* array sized exactly as required, use this instead: ``` array = list.toArray(new String[0]); ``` --- Edit3: If you use this code on a frequent basis in the same class, you may wish to consider adding this to your class: ``` private static final String[] EMPTY_STRING_ARRAY = new String[0]; ``` Then the function becomes: ``` List<String> list = new ArrayList<>(); Collections.addAll(list, array); list.removeAll(Arrays.asList("a")); array = list.toArray(EMPTY_STRING_ARRAY); ``` This will then stop littering your heap with useless empty string arrays that would otherwise be `new`ed each time your function is called. cynicalman's suggestion (see comments) will also help with the heap littering, and for fairness I should mention it: ``` array = list.toArray(new String[list.size()]); ``` I prefer my approach, because it may be easier to get the explicit size wrong (e.g., calling `size()` on the wrong list).
112,517
<p>I have the following enum:</p> <pre><code>public enum Status implements StringEnum{ ONLINE("on"),OFFLINE("off"); private String status = null; private Status(String status) { this.status = status; } public String toString() { return this.status; } public static Status find(String value) { for(Status status : Status.values()) { if(status.toString().equals(value)) { return status; } } throw new IllegalArgumentException("Unknown value: " + value ); } } </code></pre> <p>Is it possible to build StringEnum interface to make sure every enum has find(), toString() and a constructor?</p> <p>Thanks.</p>
[ { "answer_id": 112553, "author": "Frank Pape", "author_id": 10367, "author_profile": "https://Stackoverflow.com/users/10367", "pm_score": 4, "selected": true, "text": "<p>It's not possible to specify either constructors or static methods in an interface. For a good, concise explanation, ...
2008/09/21
[ "https://Stackoverflow.com/questions/112517", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20128/" ]
I have the following enum: ``` public enum Status implements StringEnum{ ONLINE("on"),OFFLINE("off"); private String status = null; private Status(String status) { this.status = status; } public String toString() { return this.status; } public static Status find(String value) { for(Status status : Status.values()) { if(status.toString().equals(value)) { return status; } } throw new IllegalArgumentException("Unknown value: " + value ); } } ``` Is it possible to build StringEnum interface to make sure every enum has find(), toString() and a constructor? Thanks.
It's not possible to specify either constructors or static methods in an interface. For a good, concise explanation, check out this article: [No static methods in interfaces](http://zoom.z3950.org/bind/java/comment/static.html)
112,532
<p>How would a go about making a program where the user enters a string, and the program generates a list of words beginning with that string?</p> <p>Ex:<br /> User: "abd"<br /> Program:abdicate, abdomen, abduct...</p> <p>Thanks!</p> <hr> <p>Edit: I'm using python, but I assume that this is a fairly language-independent problem.</p>
[ { "answer_id": 112540, "author": "dimarzionist", "author_id": 10778, "author_profile": "https://Stackoverflow.com/users/10778", "pm_score": 1, "selected": false, "text": "<pre><code>var words = from word in dictionary\n where word.key.StartsWith(\"bla-bla-bla\");\n ...
2008/09/21
[ "https://Stackoverflow.com/questions/112532", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1615/" ]
How would a go about making a program where the user enters a string, and the program generates a list of words beginning with that string? Ex: User: "abd" Program:abdicate, abdomen, abduct... Thanks! --- Edit: I'm using python, but I assume that this is a fairly language-independent problem.
If you on a debian[-like] machine, ``` #!/bin/bash echo -n "Enter a word: " read input grep "^$input" /usr/share/dict/words ``` Takes all of 0.040s on my P200.
112,564
<p>I recently discovered the genshi.builder module. It reminds me of Divmod Nevow's Stan module. How would one use genshi.builder.tag to build an HTML document with a particular doctype? Or is this even a good thing to do? If not, what is the <em>right</em> way?</p>
[ { "answer_id": 112659, "author": "alif", "author_id": 12650, "author_profile": "https://Stackoverflow.com/users/12650", "pm_score": 2, "selected": false, "text": "<p>Genshi.builder is for \"programmatically generating markup streams\"[1]. I believe the purpose of it is as a backend for t...
2008/09/21
[ "https://Stackoverflow.com/questions/112564", "https://Stackoverflow.com", "https://Stackoverflow.com/users/18866/" ]
I recently discovered the genshi.builder module. It reminds me of Divmod Nevow's Stan module. How would one use genshi.builder.tag to build an HTML document with a particular doctype? Or is this even a good thing to do? If not, what is the *right* way?
It's not possible to build an entire page using just `genshi.builder.tag` -- you would need to perform some surgery on the resulting stream to insert the doctype. Besides, the resulting code would look horrific. The recommended way to use Genshi is to use a separate template file, generate a stream from it, and then render that stream to the output type you want. `genshi.builder.tag` is mostly useful for when you need to generate simple markup from within Python, such as when you're building a form or doing some sort of logic-heavy modification of the output. See documentation for: * [Creating and using templates](http://genshi.edgewall.org/wiki/Documentation/0.5.x/templates.html) * [The XML-based template language](http://genshi.edgewall.org/wiki/Documentation/0.5.x/xml-templates.html) * [`genshi.builder` API docs](http://genshi.edgewall.org/wiki/ApiDocs/0.5.x/genshi.builder) If you really want to generate a full document using only `builder.tag`, this (completely untested) code could be a good starting point: ``` from itertools import chain from genshi.core import DOCTYPE, Stream from genshi.output import DocType from genshi.builder import tag as t # Build the page using `genshi.builder.tag` page = t.html (t.head (t.title ("Hello world!")), t.body (t.div ("Body text"))) # Convert the page element into a stream stream = page.generate () # Chain the page stream with a stream containing only an HTML4 doctype declaration stream = Stream (chain ([(DOCTYPE, DocType.get ('html4'), None)], stream)) # Convert the stream to text using the "html" renderer (could also be xml, xhtml, text, etc) text = stream.render ('html') ``` The resulting page will have no whitespace in it -- it'll look normal, but you'll have a hard time reading the source code because it will be entirely on one line. Implementing appropriate filters to add whitespace is left as an exercise to the reader.
112,582
<p>I'm having a hard time understanding and therefore managing arrays and indexes manually in C. These are my two classic approaches but they doesn't seem to work as they keep looping when the condition is reached: </p> <pre><code>#include&lt;stdio.h&gt; #define MAX 255 int main(){ int arr[MAX]={0}; int idx=0; /* Approach #1 */ printf("Enter elements, -1 to finish:\n"); scanf("%d", &amp;arr[idx]); while(arr[idx-1] != -1 &amp;&amp; idx &lt; MAX){ printf("Enter elements, -1 to finish:\n"); scanf("%d", &amp;arr[idx]); idx++; } /* Approach #2 */ do{ printf("Enter elements, -1 to finish:\n"); scanf("%d", &amp;arr[idx]); idx++; }while(arr[idx-1] != -1 &amp;&amp; idx &lt; MAX); // Main func continues here. } </code></pre> <p>Any advice would be much appreciated!</p> <p><strong>Update:</strong></p> <p>Now it works! thanks MUCH <strong>all</strong> of you guys for such instant responses. This is definitely a great community, it's helping me a lot.</p>
[ { "answer_id": 112586, "author": "Sklivvz", "author_id": 7028, "author_profile": "https://Stackoverflow.com/users/7028", "pm_score": 2, "selected": false, "text": "<pre><code>arr[idx] &lt;= MAX\n</code></pre>\n\n<p>should be</p>\n\n<pre><code>idx &lt;= MAX\n</code></pre>\n" }, { ...
2008/09/21
[ "https://Stackoverflow.com/questions/112582", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6992/" ]
I'm having a hard time understanding and therefore managing arrays and indexes manually in C. These are my two classic approaches but they doesn't seem to work as they keep looping when the condition is reached: ``` #include<stdio.h> #define MAX 255 int main(){ int arr[MAX]={0}; int idx=0; /* Approach #1 */ printf("Enter elements, -1 to finish:\n"); scanf("%d", &arr[idx]); while(arr[idx-1] != -1 && idx < MAX){ printf("Enter elements, -1 to finish:\n"); scanf("%d", &arr[idx]); idx++; } /* Approach #2 */ do{ printf("Enter elements, -1 to finish:\n"); scanf("%d", &arr[idx]); idx++; }while(arr[idx-1] != -1 && idx < MAX); // Main func continues here. } ``` Any advice would be much appreciated! **Update:** Now it works! thanks MUCH **all** of you guys for such instant responses. This is definitely a great community, it's helping me a lot.
``` arr[idx] <= MAX ``` should be ``` idx < MAX ``` unless you are checking the item instead of the index. You are also always checking the "next" element for -1 (arr[idx] != -1) because you are incrementing idx prior to checking your added value. so if you had ``` arr[idx-1] != -1 ``` you would be fine.
112,601
<p>I want to select the topmost element in a document that has a given namespace (prefix).</p> <p>More specifically: I have XML documents that either start with /html/body (in the XHTML namespace) or with one of several elements in a particular namespace. I effectively want to strip out /html/body and just return the body contents OR the entire root namespaced element. </p>
[ { "answer_id": 112602, "author": "Craig Walker", "author_id": 3488, "author_profile": "https://Stackoverflow.com/users/3488", "pm_score": 2, "selected": false, "text": "<p>The XPath expression that I want is:</p>\n\n<pre><code>/html:html/html:body/node()|/foo:*\n</code></pre>\n\n<p>Where...
2008/09/21
[ "https://Stackoverflow.com/questions/112601", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3488/" ]
I want to select the topmost element in a document that has a given namespace (prefix). More specifically: I have XML documents that either start with /html/body (in the XHTML namespace) or with one of several elements in a particular namespace. I effectively want to strip out /html/body and just return the body contents OR the entire root namespaced element.
In XPath 2.0 and XQuery 1.0 you can test against the namespace prefix using the [in-scope-prefixes()](http://www.w3.org/TR/xquery-operators/#func-in-scope-prefixes) function in a predicate. e.g. ``` //*[in-scope-prefixes(.)='html'] ``` If you cant use v2, in XPath 1.0 you can use the [namespace-uri()](http://www.w3.org/TR/xpath#function-namespace-uri) function to test against the namespace itself. e.g. ``` //*[namespace-uri()='http://www.w3c.org/1999/xhtml'] ```
112,612
<p>I am hosting <a href="http://developer.mozilla.org/En/SpiderMonkey/JSAPI_Reference" rel="nofollow noreferrer">SpiderMonkey</a> in a current project and would like to have template functions generate some of the simple property get/set methods, eg:</p> <pre><code>template &lt;typename TClassImpl, int32 TClassImpl::*mem&gt; JSBool JS_DLL_CALLBACK WriteProp(JSContext* cx, JSObject* obj, jsval id, jsval* vp) { if (TClassImpl* pImpl = (TClassImpl*)::JS_GetInstancePrivate(cx, obj, &amp;TClassImpl::s_JsClass, NULL)) return ::JS_ValueToInt32(cx, *vp, &amp;(pImpl-&gt;*mem)); return JS_FALSE; } </code></pre> <p>Used:</p> <pre><code>::JSPropertySpec Vec2::s_JsProps[] = { {"x", 1, JSPROP_PERMANENT, &amp;JsWrap::ReadProp&lt;Vec2, &amp;Vec2::x&gt;, &amp;JsWrap::WriteProp&lt;Vec2, &amp;Vec2::x&gt;}, {"y", 2, JSPROP_PERMANENT, &amp;JsWrap::ReadProp&lt;Vec2, &amp;Vec2::y&gt;, &amp;JsWrap::WriteProp&lt;Vec2, &amp;Vec2::y&gt;}, {0} }; </code></pre> <p>This works fine, however, if I add another member type:</p> <pre><code>template &lt;typename TClassImpl, JSObject* TClassImpl::*mem&gt; JSBool JS_DLL_CALLBACK WriteProp(JSContext* cx, JSObject* obj, jsval id, jsval* vp) { if (TClassImpl* pImpl = (TClassImpl*)::JS_GetInstancePrivate(cx, obj, &amp;TClassImpl::s_JsClass, NULL)) return ::JS_ValueToObject(cx, *vp, &amp;(pImpl-&gt;*mem)); return JS_FALSE; } </code></pre> <p>Then Visual C++ 9 attempts to use the JSObject* wrapper for int32 members!</p> <pre><code>1&gt;d:\projects\testing\jswnd\src\main.cpp(93) : error C2440: 'specialization' : cannot convert from 'int32 JsGlobal::Vec2::* ' to 'JSObject *JsGlobal::Vec2::* const ' 1&gt; Types pointed to are unrelated; conversion requires reinterpret_cast, C-style cast or function-style cast 1&gt;d:\projects\testing\jswnd\src\main.cpp(93) : error C2973: 'JsWrap::ReadProp' : invalid template argument 'int32 JsGlobal::Vec2::* ' 1&gt; d:\projects\testing\jswnd\src\wrap_js.h(64) : see declaration of 'JsWrap::ReadProp' 1&gt;d:\projects\testing\jswnd\src\main.cpp(93) : error C2440: 'initializing' : cannot convert from 'overloaded-function' to 'JSPropertyOp' 1&gt; None of the functions with this name in scope match the target type </code></pre> <p>Surprisingly, parening JSObject* incurs a parse error! (unexpected '('). This is probably a VC++ error (can anyone test that "template void foo() {}" compiles in GCC?). Same error with "typedef JSObject* PObject; ..., PObject TClassImpl::<em>mem>", void</em>, struct Undefined*, and double. Since the function usage is fully instantiated: "&amp;ReadProp", there should be no normal function overload semantics coming into play, it is a defined function at that point and gets priority over template functions. It seems the template ordering is failing here.</p> <p>Vec2 is just:</p> <pre><code>class Vec2 { public: int32 x, y; Vec2(JSContext* cx, JSObject* obj, uintN argc, jsval* argv); static ::JSClass s_JsClass; static ::JSPropertySpec s_JsProps[]; }; </code></pre> <p>JSPropertySpec is described in JSAPI link in OP, taken from header:</p> <pre><code>typedef JSBool (* JS_DLL_CALLBACK JSPropertyOp)(JSContext *cx, JSObject *obj, jsval id, jsval *vp); ... struct JSPropertySpec { const char *name; int8 tinyid; uint8 flags; JSPropertyOp getter; JSPropertyOp setter; }; </code></pre>
[ { "answer_id": 112679, "author": "Lou Franco", "author_id": 3937, "author_profile": "https://Stackoverflow.com/users/3937", "pm_score": 0, "selected": false, "text": "<p>Try changing the JSObject * to another pointer type to see if that reproduces the error. Is JSObject defined at the ...
2008/09/22
[ "https://Stackoverflow.com/questions/112612", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20135/" ]
I am hosting [SpiderMonkey](http://developer.mozilla.org/En/SpiderMonkey/JSAPI_Reference) in a current project and would like to have template functions generate some of the simple property get/set methods, eg: ``` template <typename TClassImpl, int32 TClassImpl::*mem> JSBool JS_DLL_CALLBACK WriteProp(JSContext* cx, JSObject* obj, jsval id, jsval* vp) { if (TClassImpl* pImpl = (TClassImpl*)::JS_GetInstancePrivate(cx, obj, &TClassImpl::s_JsClass, NULL)) return ::JS_ValueToInt32(cx, *vp, &(pImpl->*mem)); return JS_FALSE; } ``` Used: ``` ::JSPropertySpec Vec2::s_JsProps[] = { {"x", 1, JSPROP_PERMANENT, &JsWrap::ReadProp<Vec2, &Vec2::x>, &JsWrap::WriteProp<Vec2, &Vec2::x>}, {"y", 2, JSPROP_PERMANENT, &JsWrap::ReadProp<Vec2, &Vec2::y>, &JsWrap::WriteProp<Vec2, &Vec2::y>}, {0} }; ``` This works fine, however, if I add another member type: ``` template <typename TClassImpl, JSObject* TClassImpl::*mem> JSBool JS_DLL_CALLBACK WriteProp(JSContext* cx, JSObject* obj, jsval id, jsval* vp) { if (TClassImpl* pImpl = (TClassImpl*)::JS_GetInstancePrivate(cx, obj, &TClassImpl::s_JsClass, NULL)) return ::JS_ValueToObject(cx, *vp, &(pImpl->*mem)); return JS_FALSE; } ``` Then Visual C++ 9 attempts to use the JSObject\* wrapper for int32 members! ``` 1>d:\projects\testing\jswnd\src\main.cpp(93) : error C2440: 'specialization' : cannot convert from 'int32 JsGlobal::Vec2::* ' to 'JSObject *JsGlobal::Vec2::* const ' 1> Types pointed to are unrelated; conversion requires reinterpret_cast, C-style cast or function-style cast 1>d:\projects\testing\jswnd\src\main.cpp(93) : error C2973: 'JsWrap::ReadProp' : invalid template argument 'int32 JsGlobal::Vec2::* ' 1> d:\projects\testing\jswnd\src\wrap_js.h(64) : see declaration of 'JsWrap::ReadProp' 1>d:\projects\testing\jswnd\src\main.cpp(93) : error C2440: 'initializing' : cannot convert from 'overloaded-function' to 'JSPropertyOp' 1> None of the functions with this name in scope match the target type ``` Surprisingly, parening JSObject\* incurs a parse error! (unexpected '('). This is probably a VC++ error (can anyone test that "template void foo() {}" compiles in GCC?). Same error with "typedef JSObject\* PObject; ..., PObject TClassImpl::*mem>", void*, struct Undefined\*, and double. Since the function usage is fully instantiated: "&ReadProp", there should be no normal function overload semantics coming into play, it is a defined function at that point and gets priority over template functions. It seems the template ordering is failing here. Vec2 is just: ``` class Vec2 { public: int32 x, y; Vec2(JSContext* cx, JSObject* obj, uintN argc, jsval* argv); static ::JSClass s_JsClass; static ::JSPropertySpec s_JsProps[]; }; ``` JSPropertySpec is described in JSAPI link in OP, taken from header: ``` typedef JSBool (* JS_DLL_CALLBACK JSPropertyOp)(JSContext *cx, JSObject *obj, jsval id, jsval *vp); ... struct JSPropertySpec { const char *name; int8 tinyid; uint8 flags; JSPropertyOp getter; JSPropertyOp setter; }; ```
Pretty sure VC++ has "issues" here. Comeau and g++ 4.2 are both happy with the following program: ``` struct X { int i; void* p; }; template<int X::*P> void foo(X* t) { t->*P = 0; } template<void* X::*P> void foo(X* t) { t->*P = 0; } int main() { X x; foo<&X::i>(&x); foo<&X::p>(&x); } ``` VC++ 2008SP1, however, is having none of it. I haven't the time to read through my standard to find out exactly what's what... but I think VC++ is in the wrong here.
112,643
<p>I know how to create a <code>SEL</code> at compile time using <code>@selector(MyMethodName:)</code> but what I want to do is create a selector dynamically from an <code>NSString</code>. Is this even possible?</p> <p>What I can do:</p> <pre><code>SEL selector = @selector(doWork:); [myobj respondsToSelector:selector]; </code></pre> <p>What I want to do: (pseudo code, this obviously doesn't work)</p> <pre><code>SEL selector = selectorFromString(@"doWork"); [myobj respondsToSelector:selector]; </code></pre> <p>I've been searching the Apple API docs, but haven't found a way that doesn't rely on the compile-time <code>@selector(myTarget:)</code> syntax.</p>
[ { "answer_id": 112668, "author": "Torsten Marek", "author_id": 9567, "author_profile": "https://Stackoverflow.com/users/9567", "pm_score": 8, "selected": true, "text": "<p>I'm not an Objective-C programmer, merely a sympathizer, but maybe <a href=\"https://developer.apple.com/documentati...
2008/09/22
[ "https://Stackoverflow.com/questions/112643", "https://Stackoverflow.com", "https://Stackoverflow.com/users/18590/" ]
I know how to create a `SEL` at compile time using `@selector(MyMethodName:)` but what I want to do is create a selector dynamically from an `NSString`. Is this even possible? What I can do: ``` SEL selector = @selector(doWork:); [myobj respondsToSelector:selector]; ``` What I want to do: (pseudo code, this obviously doesn't work) ``` SEL selector = selectorFromString(@"doWork"); [myobj respondsToSelector:selector]; ``` I've been searching the Apple API docs, but haven't found a way that doesn't rely on the compile-time `@selector(myTarget:)` syntax.
I'm not an Objective-C programmer, merely a sympathizer, but maybe [NSSelectorFromString](https://developer.apple.com/documentation/foundation/1395294-nsselectorfromstring?language=objc) is what you need. It's mentioned explicity in the [Runtime Reference](http://developer.apple.com/documentation/Cocoa/Conceptual/ObjectiveC/Articles/chapter_9_section_3.html) that you can use it to convert a string to a selector.
112,664
<p>I can connect to my SQL Server database via sqlcmd from a DOS command window, but not from a Cygwin window. From DOS:</p> <pre><code>F:\Cygnus&gt;sqlcmd -Q "select 'a test'" -S .\SQLEXPRESS </code></pre> <hr> <p>a test</p> <p>(1 rows affected)</p> <pre><code>F:\Cygnus&gt; </code></pre> <p>====================================================</p> <p>From Cygwin:</p> <pre><code>$ sqlcmd -Q "select 'a test'" -S .\SQLEXPRESS </code></pre> <blockquote> <p>HResult 0x35, Level 16, State 1<br> Named Pipes Provider: Could not open a connection to SQL Server [53]. Sqlcmd: Error: Microsoft SQL Native Client : An error has occurred while establishing a connection to the server. When connecting to SQL Server 2005, this failure may be caused by the fact that under the default settings SQL Server does not allow remote connections.. Sqlcmd: Error: Microsoft SQL Native Client : Login timeout expired.</p> </blockquote>
[ { "answer_id": 112688, "author": "PostMan", "author_id": 18405, "author_profile": "https://Stackoverflow.com/users/18405", "pm_score": 0, "selected": false, "text": "<p>You may have to allow remote connections for this, and give the full server name i.e SERVER\\SQLEXPRESS</p>\n" }, {...
2008/09/22
[ "https://Stackoverflow.com/questions/112664", "https://Stackoverflow.com", "https://Stackoverflow.com/users/8670/" ]
I can connect to my SQL Server database via sqlcmd from a DOS command window, but not from a Cygwin window. From DOS: ``` F:\Cygnus>sqlcmd -Q "select 'a test'" -S .\SQLEXPRESS ``` --- a test (1 rows affected) ``` F:\Cygnus> ``` ==================================================== From Cygwin: ``` $ sqlcmd -Q "select 'a test'" -S .\SQLEXPRESS ``` > > HResult 0x35, Level 16, State 1 > Named Pipes Provider: Could not > open a connection to SQL Server [53]. Sqlcmd: Error: Microsoft SQL > Native Client : An error has occurred while establishing a connection > to the server. When connecting to SQL Server 2005, this failure may be > caused by the fact that under the default settings SQL Server does not > allow remote connections.. Sqlcmd: Error: Microsoft SQL Native Client > : Login timeout expired. > > >
The backslash is being eaten by cygwin's bash shell. Try doubling it: ``` sqlcmd -Q "select 'a test'" -S .\\SQLEXPRESS ```
112,707
<p>Whenever I indent <code>HTML</code> in <code>PHP</code> mode, <code>emacs (22.1.1, basic install on Redaht Linux over Putty-SSH)</code> pops up a frame and tells me to get <code>MUMODE</code> or <code>somesuch</code> extra add-on. I installed <code>PHP</code> Mode without a big hassle, but I don't know how to get this multi-mode rolling.<br> <hr> I'd like to know 2 things</p> <pre><code>How to install and configure multi-mode How to disable pop-ups in Emacs </code></pre>
[ { "answer_id": 112906, "author": "bmdhacks", "author_id": 14032, "author_profile": "https://Stackoverflow.com/users/14032", "pm_score": 3, "selected": true, "text": "<p>If you're running emacs 22, you should just be able to run:</p>\n\n<pre><code>M-x nxhtml-mumamo\n</code></pre>\n\n<p>wh...
2008/09/22
[ "https://Stackoverflow.com/questions/112707", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1765/" ]
Whenever I indent `HTML` in `PHP` mode, `emacs (22.1.1, basic install on Redaht Linux over Putty-SSH)` pops up a frame and tells me to get `MUMODE` or `somesuch` extra add-on. I installed `PHP` Mode without a big hassle, but I don't know how to get this multi-mode rolling. --- I'd like to know 2 things ``` How to install and configure multi-mode How to disable pop-ups in Emacs ```
If you're running emacs 22, you should just be able to run: ``` M-x nxhtml-mumamo ``` when editing an html document. You might want to add it to your auto-mode-alist to get it to automatically load for html docs. See here for more info: <http://www.emacswiki.org/cgi-bin/wiki/MuMaMo> <http://www.emacswiki.org/cgi-bin/wiki/PhpMode>
112,721
<p>I've got the following situation</p> <ul> <li>A rails application that makes use of rjs / Scriptaculous to offer AJAX functionality</li> <li>Lot of nice javascript written using jQuery (for a separate application)</li> </ul> <p>I want to combine the two and use my jQuery based functionality in my Rails application, but I'm worried about jQuery and Scriptaculous clashing (they both define the $() function, etc). </p> <p>What is my easiest option to bring the two together? Thanks!</p>
[ { "answer_id": 112731, "author": "Jason Peacock", "author_id": 18381, "author_profile": "https://Stackoverflow.com/users/18381", "pm_score": 1, "selected": false, "text": "<p><a href=\"http://ennerchi.com/projects/jrails\" rel=\"nofollow noreferrer\">jRails</a> is a drop-in replacement f...
2008/09/22
[ "https://Stackoverflow.com/questions/112721", "https://Stackoverflow.com", "https://Stackoverflow.com/users/16779/" ]
I've got the following situation * A rails application that makes use of rjs / Scriptaculous to offer AJAX functionality * Lot of nice javascript written using jQuery (for a separate application) I want to combine the two and use my jQuery based functionality in my Rails application, but I'm worried about jQuery and Scriptaculous clashing (they both define the $() function, etc). What is my easiest option to bring the two together? Thanks!
``` jQuery.noConflict(); ``` Then use jQuery instead of $ to refer to jQuery. e.g., ``` jQuery('div.foo').doSomething() ``` If you need to adapt jQuery code that uses $, you can surround it with this: ``` (function($) { ...your code here... })(jQuery); ```
112,730
<p>I have a <code>n...n</code> structure for two tables, <strong><code>makes</code></strong> and <strong><code>models</code></strong>. So far no problem.</p> <p>In a third table (<strong><code>products</code></strong>) like:</p> <pre><code>id make_id model_id ... </code></pre> <p>My problem is creating a view for products of one specifi <strong><code>make</code></strong> inside my <code>ProductsController</code> containing just that's make models:</p> <p>I thought this could work:</p> <pre><code>var $uses = array('Make', 'Model'); $this-&gt;Make-&gt;id = 5; // My Make $this-&gt;Make-&gt;find(); // Returns only the make I want with it's Models (HABTM) $this-&gt;Model-&gt;find('list'); // Returns ALL models $this-&gt;Make-&gt;Model-&gt;find('list'); // Returns ALL models </code></pre> <p>So, If I want to use the <code>list</code> to pass to my view to create radio buttons I will have to do a <code>foreach()</code> in my <strong><code>make</code></strong> array to find all models titles and create a new array and send to the view via <code>$this-&gt;set()</code>.</p> <pre><code>$makeArray = $this-&gt;Make-&gt;find(); foreach ($makeArray['Model'] as $model) { $modelList[] = $model['title']; } $this-&gt;set('models', $models) </code></pre> <p>Is there any easier way to get that list without stressing the <strong><code>make</code></strong> Array. It will be a commom task to develops such scenarios in my application(s).</p> <p>Thanks in advance for any hint!</p>
[ { "answer_id": 112868, "author": "JayTee", "author_id": 20153, "author_profile": "https://Stackoverflow.com/users/20153", "pm_score": 1, "selected": false, "text": "<p>Here's my hint: Try getting your query written in regular SQL before trying to reconstruct using the Cake library. In ...
2008/09/22
[ "https://Stackoverflow.com/questions/112730", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2274/" ]
I have a `n...n` structure for two tables, **`makes`** and **`models`**. So far no problem. In a third table (**`products`**) like: ``` id make_id model_id ... ``` My problem is creating a view for products of one specifi **`make`** inside my `ProductsController` containing just that's make models: I thought this could work: ``` var $uses = array('Make', 'Model'); $this->Make->id = 5; // My Make $this->Make->find(); // Returns only the make I want with it's Models (HABTM) $this->Model->find('list'); // Returns ALL models $this->Make->Model->find('list'); // Returns ALL models ``` So, If I want to use the `list` to pass to my view to create radio buttons I will have to do a `foreach()` in my **`make`** array to find all models titles and create a new array and send to the view via `$this->set()`. ``` $makeArray = $this->Make->find(); foreach ($makeArray['Model'] as $model) { $modelList[] = $model['title']; } $this->set('models', $models) ``` Is there any easier way to get that list without stressing the **`make`** Array. It will be a commom task to develops such scenarios in my application(s). Thanks in advance for any hint!
The solution can be achieved with the use of the `with` operation in habtm array on the model. Using `with` you can define the "middle" table like: ``` $habtm = " ... 'with' => 'MakeModel', ... "; ``` And internally, in the Model or Controller, you can issue conditions to the `find` method. See: <http://www.cricava.com/blogs/index.php?blog=6&title=modelizing_habtm_join_tables_in_cakephp_&more=1&c=1&tb=1&pb=1>
112,738
<p>Without spending a long time reviewing the boost source code, could someone give me a quick rundown of how boost bind is implemented? </p>
[ { "answer_id": 112756, "author": "Lou Franco", "author_id": 3937, "author_profile": "https://Stackoverflow.com/users/3937", "pm_score": 0, "selected": false, "text": "<p>I think it's a template class that declares a member variable for the arguments you want to bind and overloads () for ...
2008/09/22
[ "https://Stackoverflow.com/questions/112738", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3153/" ]
Without spending a long time reviewing the boost source code, could someone give me a quick rundown of how boost bind is implemented?
I like this piece of the `bind` source: ``` template<class R, class F, class L> class bind_t { public: typedef bind_t this_type; bind_t(F f, L const & l): f_(f), l_(l) {} #define BOOST_BIND_RETURN return #include <boost/bind/bind_template.hpp> #undef BOOST_BIND_RETURN }; ``` Tells you almost all you need to know, really. The `bind_template` header expands to a list of inline `operator()` definitions. For example, the simplest: ``` result_type operator()() { list0 a; BOOST_BIND_RETURN l_(type<result_type>(), f_, a, 0); } ``` We can see the `BOOST_BIND_RETURN` macro expands to `return` at this point so the line is more like `return l_(type...)`. The one parameter version is here: ``` template<class A1> result_type operator()(A1 & a1) { list1<A1 &> a(a1); BOOST_BIND_RETURN l_(type<result_type>(), f_, a, 0); } ``` It's pretty similar. The `listN` classes are wrappers for the parameter lists. There is a lot of deep magic going on here that I don't really understand too much though. They have also overloaded `operator()` that calls the mysterious `unwrap` function. Ignoring some compiler specific overloads, it doesn't do a lot: ``` // unwrap template<class F> inline F & unwrap(F * f, long) { return *f; } template<class F> inline F & unwrap(reference_wrapper<F> * f, int) { return f->get(); } template<class F> inline F & unwrap(reference_wrapper<F> const * f, int) { return f->get(); } ``` The naming convention seems to be: `F` is the type of the function parameter to `bind`. `R` is the return type. `L` tends to be a list of parameter types. There are also a lot of complications because there are no less than nine overloads for different numbers of parameters. Best not to dwell on that too much.
112,768
<p>(ClientCookie is a module for (automatic) cookie-handling: <a href="http://wwwsearch.sourceforge.net/ClientCookie" rel="nofollow noreferrer">http://wwwsearch.sourceforge.net/ClientCookie</a>)</p> <pre><code># I encode the data I'll be sending: data = urllib.urlencode({'username': 'mandark', 'password': 'deedee'}) # And I send it and read the page: page = ClientCookie.urlopen('http://www.forum.com/ucp.php?mode=login', data) output = page.read() </code></pre> <p>The script doesn't log in, but rather seems to get redirected back to the same login page asking it for a username and password. What am I doing wrong?</p> <p>Any help would be greatly appreciated! Thanks!</p>
[ { "answer_id": 112819, "author": "Jonny Buchanan", "author_id": 6760, "author_profile": "https://Stackoverflow.com/users/6760", "pm_score": 3, "selected": true, "text": "<p>Have you tried fetching the login page first?</p>\n\n<p>I would suggest using <a href=\"https://addons.mozilla.org/...
2008/09/22
[ "https://Stackoverflow.com/questions/112768", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
(ClientCookie is a module for (automatic) cookie-handling: <http://wwwsearch.sourceforge.net/ClientCookie>) ``` # I encode the data I'll be sending: data = urllib.urlencode({'username': 'mandark', 'password': 'deedee'}) # And I send it and read the page: page = ClientCookie.urlopen('http://www.forum.com/ucp.php?mode=login', data) output = page.read() ``` The script doesn't log in, but rather seems to get redirected back to the same login page asking it for a username and password. What am I doing wrong? Any help would be greatly appreciated! Thanks!
Have you tried fetching the login page first? I would suggest using [Tamper Data](https://addons.mozilla.org/en-US/firefox/addon/966) to have a peek at exactly what's being sent when you request the login page and then log in normally using a web browser from a fresh start, with no initial cookies in place, so that your script can replicate it exactly. That's the approach I used when writing the following, extracted from a script which needs to login to an Invision Power Board forum, using cookielib and urllib2 - you may find it useful as a reference. ``` import cookielib import logging import sys import urllib import urllib2 cookies = cookielib.LWPCookieJar() opener = urllib2.build_opener(urllib2.HTTPCookieProcessor(cookies)) urllib2.install_opener(opener) headers = { 'User-Agent': 'Mozilla/5.0 (Windows; U; Windows NT 5.0; en-GB; rv:1.8.1.12) Gecko/20080201 Firefox/2.0.0.12', 'Accept': 'text/xml,application/xml,application/xhtml+xml,text/html;q=0.9,text/plain;q=0.8,image/png,*/*;q=0.5', 'Accept-Language': 'en-gb,en;q=0.5', 'Accept-Charset': 'ISO-8859-1,utf-8;q=0.7,*;q=0.7', } # Fetch the login page to set initial cookies urllib2.urlopen(urllib2.Request('http://www.rllmukforum.com/index.php?act=Login&CODE=00', None, headers)) # Login so we can access the Off Topic forum login_headers = headers.copy() login_headers.update({ 'Referer': 'http://www.rllmukforum.com/index.php?act=Login&CODE=00', 'Content-Type': 'application/x-www-form-urlencoded', }) html = urllib2.urlopen(urllib2.Request('http://www.rllmukforum.com/index.php?act=Login&CODE=01', urllib.urlencode({ 'referer': 'http://www.rllmukforum.com/index.php?', 'UserName': RLLMUK_USERNAME, 'PassWord': RLLMUK_PASSWORD, }), login_headers)).read() if 'The following errors were found' in html: logging.error('RLLMUK login failed') logging.info(html) sys.exit(1) ```
112,770
<p>Our subversion repository has been moved to a new host, and we have old applications that connect to that host. We CANNOT add an alias for the new server with the old name, how can we re-connect our checked out clients to the new repository?</p>
[ { "answer_id": 112773, "author": "Greg Hewgill", "author_id": 893, "author_profile": "https://Stackoverflow.com/users/893", "pm_score": 3, "selected": false, "text": "<p>Look up the <a href=\"http://svnbook.red-bean.com/en/1.0/re27.html\" rel=\"noreferrer\">svn switch</a> command. In par...
2008/09/22
[ "https://Stackoverflow.com/questions/112770", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20150/" ]
Our subversion repository has been moved to a new host, and we have old applications that connect to that host. We CANNOT add an alias for the new server with the old name, how can we re-connect our checked out clients to the new repository?
Example: ``` svn switch --relocate \ http://svn.example.com/path/to/repository/path/within/repository \ http://svnnew.example.com/new/repository/path/within/repository ``` One thing which is to remember, lets assume you checked out the project "path/within/repository" then you have to go to the **root of your working copy**, and execute the above command. it is **NOT** enough just to use the repository root (as in *svn switch --relocate <http://svn.example.com/path/to/repository/> <http://svnnew.example.com/new/repository/>*), because that wouldn't work.
112,775
<p>Is it possible to have a <code>MySQLi prepared statement</code> within the <code>fetch()</code> call of a previous statement? If not, what's the best way around it?</p> <p>Example code:</p> <pre><code>if($stmt = $link-&gt;prepare("SELECT item FROM data WHERE id = ?")) { $stmt-&gt;bind_param("i", $id); $stmt-&gt;execute(); $stmt-&gt;bind_result($item); while( $stmt-&gt;fetch() ) { /* Other code here */ $itemSummary = $item + $magic; if($stmt2 = $link-&gt;prepare("INSERT INTO summaries (itemID, summary) VALUES (?, ?)")) { $stmt2-&gt;bind_param("is", $itemID, $itemSummary); $stmt2-&gt;execute(); $stmt2-&gt;close(); } } } </code></pre>
[ { "answer_id": 112800, "author": "Kibbee", "author_id": 1862, "author_profile": "https://Stackoverflow.com/users/1862", "pm_score": 3, "selected": true, "text": "<p>You should be able to do that, although you make have to start a second connection. </p>\n" }, { "answer_id": 16753...
2008/09/22
[ "https://Stackoverflow.com/questions/112775", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6305/" ]
Is it possible to have a `MySQLi prepared statement` within the `fetch()` call of a previous statement? If not, what's the best way around it? Example code: ``` if($stmt = $link->prepare("SELECT item FROM data WHERE id = ?")) { $stmt->bind_param("i", $id); $stmt->execute(); $stmt->bind_result($item); while( $stmt->fetch() ) { /* Other code here */ $itemSummary = $item + $magic; if($stmt2 = $link->prepare("INSERT INTO summaries (itemID, summary) VALUES (?, ?)")) { $stmt2->bind_param("is", $itemID, $itemSummary); $stmt2->execute(); $stmt2->close(); } } } ```
You should be able to do that, although you make have to start a second connection.
112,796
<p>Is there a way to view the key/value pairs of a NSDictionary variable through the Xcode debugger? Here's the extent of information when it is fully expanded in the variable window:</p> <pre><code>Variable Value Summary jsonDict 0x45c540 4 key/value pairs NSObject {...} isa 0xa06e0720 </code></pre> <p>I was expecting it to show me each element of the dictionary (similar to an array variable). </p>
[ { "answer_id": 112808, "author": "craigb", "author_id": 18590, "author_profile": "https://Stackoverflow.com/users/18590", "pm_score": 8, "selected": true, "text": "<p>In the gdb window you can use <code>po</code> to inspect the object.</p>\n\n<p>given:</p>\n\n<pre><code>NSMutableDictiona...
2008/09/22
[ "https://Stackoverflow.com/questions/112796", "https://Stackoverflow.com", "https://Stackoverflow.com/users/11292/" ]
Is there a way to view the key/value pairs of a NSDictionary variable through the Xcode debugger? Here's the extent of information when it is fully expanded in the variable window: ``` Variable Value Summary jsonDict 0x45c540 4 key/value pairs NSObject {...} isa 0xa06e0720 ``` I was expecting it to show me each element of the dictionary (similar to an array variable).
In the gdb window you can use `po` to inspect the object. given: ``` NSMutableDictionary* dict = [[NSMutableDictionary alloc] init]; [dict setObject:@"foo" forKey:@"bar"]; [dict setObject:@"fiz" forKey:@"buz"]; ``` setting a breakpoint after the objects are added you can inspect what is in the dictionary ``` (gdb) po dict { bar = foo; buz = fiz; } ``` Of course these are `NSString` objects that print nicely. YMMV with other complex objects.
112,812
<p>How do I access parameters passed into an Oracle Form via a URL. Eg given the url:</p> <blockquote> <p><a href="http://example.com/forms90/f90servlet?config=cust&amp;form=" rel="nofollow noreferrer">http://example.com/forms90/f90servlet?config=cust&amp;form=</a>'a_form'&amp;p1=something&amp;p2=else</p> </blockquote> <p>This will launch the 'a_form' form, using the 'cust' configuration, but I can't work how (or even if it's possible) to access p1 (with value of 'something') p2 (with value of 'else')</p> <p>Does anyone know how I can do this? (Or even if it is/isn't possible?</p> <p>Thanks</p>
[ { "answer_id": 113990, "author": "Tony Andrews", "author_id": 18747, "author_profile": "https://Stackoverflow.com/users/18747", "pm_score": 2, "selected": true, "text": "<p>Within Forms you can refer to the parameters p1 an p2 as follows:</p>\n\n<ul>\n<li>:PARAMETER.p1</li>\n<li>:PARAMET...
2008/09/22
[ "https://Stackoverflow.com/questions/112812", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1505600/" ]
How do I access parameters passed into an Oracle Form via a URL. Eg given the url: > > <http://example.com/forms90/f90servlet?config=cust&form=>'a\_form'&p1=something&p2=else > > > This will launch the 'a\_form' form, using the 'cust' configuration, but I can't work how (or even if it's possible) to access p1 (with value of 'something') p2 (with value of 'else') Does anyone know how I can do this? (Or even if it is/isn't possible? Thanks
Within Forms you can refer to the parameters p1 an p2 as follows: * :PARAMETER.p1 * :PARAMETER.p2 e.g. ``` if :PARAMETER.p1 = 'something' then do_something; end if; ```
112,818
<p>I am creating a standalone asp.net page that needs to be embedded into a sharepoint site using the Page Viewer Web Part. The asp.net page is published to the same server on a different port, giving me the URL to embed.</p> <p>The requirement is that after a user is authenticated using Sharepoint authentication, they navigate to a page containing the asp.net web part for more options. </p> <p>What I need to do from this asp.net page is query Sharepoint for the currently authenticated username, then display this on the page from the asp.net code. </p> <p>This all works fine when I debug the application from VS, but when published and displayed though Sharepoint, I always get NULL as the user. </p> <p>Any suggestions on the best way to get this to work would be much appreciated.</p>
[ { "answer_id": 112828, "author": "Lou Franco", "author_id": 3937, "author_profile": "https://Stackoverflow.com/users/3937", "pm_score": 0, "selected": false, "text": "<p>When it works in debug, is that being used in SharePoint?</p>\n\n<p>Your page and the Sharepoint site might as well be...
2008/09/22
[ "https://Stackoverflow.com/questions/112818", "https://Stackoverflow.com", "https://Stackoverflow.com/users/11703/" ]
I am creating a standalone asp.net page that needs to be embedded into a sharepoint site using the Page Viewer Web Part. The asp.net page is published to the same server on a different port, giving me the URL to embed. The requirement is that after a user is authenticated using Sharepoint authentication, they navigate to a page containing the asp.net web part for more options. What I need to do from this asp.net page is query Sharepoint for the currently authenticated username, then display this on the page from the asp.net code. This all works fine when I debug the application from VS, but when published and displayed though Sharepoint, I always get NULL as the user. Any suggestions on the best way to get this to work would be much appreciated.
If you want to retrieve the currently authenticated user from the SharePoint context, you need to remain within the SharePoint context. This means hosting your custom web application within SharePoint (see [http://msdn.microsoft.com/en-us/library/cc297200.aspx](http://msdn.microsoft.com/en-us/library/cc297200.aspx "Deploying ASP.NET Web Applications in the Windows SharePoint Services 3.0 _layouts Folder")). Then from your custom application reference Microsoft.SharePoint and use the SPContext object to retrieve the user name. For example: ``` SPContext.Current.Web.CurrentUser.LoginName ``` You can still use the Page Viewer Web Part to reference the URL of the site, now located within the SharePoint context.
112,861
<p>According to the documentation the return value from a slot doesn't mean anything.<br> Yet in the generated moc code I see that if a slot returns a value this value is used for something. Any idea what does it do?</p> <hr> <p>Here's an example of what I'm talking about. this is taken from code generated by moc. 'message' is a slot that doesn't return anything and 'selectPart' is declared as returning int.</p> <pre><code>case 7: message((*reinterpret_cast&lt; const QString(*)&gt;(_a[1])),(*reinterpret_cast&lt; int(*)&gt;(_a[2]))); break; case 8: { int _r = selectPart((*reinterpret_cast&lt; AppObject*(*)&gt;(_a[1])),(*reinterpret_cast&lt; int(*)&gt;(_a[2]))); if (_a[0]) *reinterpret_cast&lt; int*&gt;(_a[0]) = _r; } break; </code></pre>
[ { "answer_id": 112960, "author": "David Dibben", "author_id": 5022, "author_profile": "https://Stackoverflow.com/users/5022", "pm_score": 4, "selected": false, "text": "<p>Looking through the Qt source it seems that when a slot is called from QMetaObject::invokeMethod the return type can...
2008/09/22
[ "https://Stackoverflow.com/questions/112861", "https://Stackoverflow.com", "https://Stackoverflow.com/users/9611/" ]
According to the documentation the return value from a slot doesn't mean anything. Yet in the generated moc code I see that if a slot returns a value this value is used for something. Any idea what does it do? --- Here's an example of what I'm talking about. this is taken from code generated by moc. 'message' is a slot that doesn't return anything and 'selectPart' is declared as returning int. ``` case 7: message((*reinterpret_cast< const QString(*)>(_a[1])),(*reinterpret_cast< int(*)>(_a[2]))); break; case 8: { int _r = selectPart((*reinterpret_cast< AppObject*(*)>(_a[1])),(*reinterpret_cast< int(*)>(_a[2]))); if (_a[0]) *reinterpret_cast< int*>(_a[0]) = _r; } break; ```
Looking through the Qt source it seems that when a slot is called from QMetaObject::invokeMethod the return type can be specified and the return value obtained. (Have a look at invokeMethod in the Qt help) I could not find many examples of this actually being used in the Qt source. One I found was ``` bool QAbstractItemDelegate::helpEvent ``` which is a slot with a return type and is called from ``` QAbstractItemView::viewportEvent ``` using invokeMethod. I think that the return value for a slot is only available when the function is called directly (when it is a normal C++ function) or when using invokeMethod. I think this is really meant for internal Qt functions rather than for normal use in programs using Qt. Edit: For the sample case: ``` case 8: { int _r = selectPart((*reinterpret_cast< AppObject*(*)>(_a[1])), *reinterpret_cast< int(*)>(_a[2]))); if (_a[0]) *reinterpret_cast< int*>(_a[0]) = _r; } break; ``` the vector \_a is a list of arguments that is passed to qt\_metacall. This is passed by QMetaObject::invokeMethod. So the return value in the moc generated code is saved and passed back to the caller. So for normal signal-slot interactions the return value is not used for anything at all. However, the mechanism exists so that return values from slots can be accessed if the slot is called via invokeMethod.
112,892
<p>How would retrieve all customer's birthdays for a given month in SQL? What about MySQL? I was thinking of using the following with SQL server.</p> <pre><code>select c.name from cust c where datename(m,c.birthdate) = datename(m,@suppliedDate) order by c.name </code></pre>
[ { "answer_id": 112894, "author": "rickripe", "author_id": 20169, "author_profile": "https://Stackoverflow.com/users/20169", "pm_score": 2, "selected": false, "text": "<p>Personally I would use DATEPART instead of DATENAME as DATENAME is open to interpretation depending on locale.</p>\n" ...
2008/09/22
[ "https://Stackoverflow.com/questions/112892", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5618/" ]
How would retrieve all customer's birthdays for a given month in SQL? What about MySQL? I was thinking of using the following with SQL server. ``` select c.name from cust c where datename(m,c.birthdate) = datename(m,@suppliedDate) order by c.name ```
don't forget the 29th February... ``` SELECT c.name FROM cust c WHERE ( MONTH(c.birthdate) = MONTH(@suppliedDate) AND DAY(c.birthdate) = DAY(@suppliedDate) ) OR ( MONTH(c.birthdate) = 2 AND DAY(c.birthdate) = 29 AND MONTH(@suppliedDate) = 3 AND DAY(@suppliedDate) = 1 AND (YEAR(@suppliedDate) % 4 = 0) AND ((YEAR(@suppliedDate) % 100 != 0) OR (YEAR(@suppliedDate) % 400 = 0)) ) ```
112,897
<p>The code currently does this and the fgetpos does handle files larger than 4GB but the seek returns an error, so any idea how to seek to the end of a <code>file &gt; 4GB</code>?</p> <pre><code>fpos_t currentpos; sok=fseek(fp,0,SEEK_END); assert(sok==0,"Seek error!"); fgetpos(fp,&amp;currentpos); m_filesize=currentpos; </code></pre>
[ { "answer_id": 112910, "author": "Captain Segfault", "author_id": 18408, "author_profile": "https://Stackoverflow.com/users/18408", "pm_score": 1, "selected": false, "text": "<p>On linux, at least, you could use lseek64 instead of fseek.</p>\n" }, { "answer_id": 112913, "auth...
2008/09/22
[ "https://Stackoverflow.com/questions/112897", "https://Stackoverflow.com", "https://Stackoverflow.com/users/13676/" ]
The code currently does this and the fgetpos does handle files larger than 4GB but the seek returns an error, so any idea how to seek to the end of a `file > 4GB`? ``` fpos_t currentpos; sok=fseek(fp,0,SEEK_END); assert(sok==0,"Seek error!"); fgetpos(fp,&currentpos); m_filesize=currentpos; ```
If you're in Windows, you want [GetFileSizeEx (MSDN)](http://msdn.microsoft.com/en-us/library/aa364957(VS.85).aspx). The return value is a 64bit int. On linux [stat64 (manpage)](http://www.manpagez.com/man/2/stat64/) is correct. fstat if you're working with a FILE\*.
112,964
<p>Ubuntu has 8 run levels (0-6 and S), I want to add the run level 7.</p> <p>I have done the following:</p> <p>1.- Created the folder <strong>/etc/rc7.d/</strong>, which contains some symbolic links to <strong>/etc/init.d/</strong></p> <p>2.- Created the file <strong>/etc/event.d/rc7</strong> This is its content:</p> <pre><code># rc7 - runlevel 7 compatibility # # This task runs the old sysv-rc runlevel 7 ("multi-user") scripts. It # is usually started by the telinit compatibility wrapper. start on runlevel 7 stop on runlevel [!7] console output script set $(runlevel --set 7 || true) if [ "$1" != "unknown" ]; then PREVLEVEL=$1 RUNLEVEL=$2 export PREVLEVEL RUNLEVEL fi exec /etc/init.d/rc 7 end script </code></pre> <p>I thought that would be enough, but <strong>telinit 7</strong> still throws this error: <em>telinit: illegal runlevel: 7</em></p>
[ { "answer_id": 113005, "author": "Zathrus", "author_id": 16220, "author_profile": "https://Stackoverflow.com/users/16220", "pm_score": 3, "selected": true, "text": "<p>You cannot; the runlevels are hardcoded into the utilities. But why do you need to? Runlevel 4 is essentially unused. An...
2008/09/22
[ "https://Stackoverflow.com/questions/112964", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7852/" ]
Ubuntu has 8 run levels (0-6 and S), I want to add the run level 7. I have done the following: 1.- Created the folder **/etc/rc7.d/**, which contains some symbolic links to **/etc/init.d/** 2.- Created the file **/etc/event.d/rc7** This is its content: ``` # rc7 - runlevel 7 compatibility # # This task runs the old sysv-rc runlevel 7 ("multi-user") scripts. It # is usually started by the telinit compatibility wrapper. start on runlevel 7 stop on runlevel [!7] console output script set $(runlevel --set 7 || true) if [ "$1" != "unknown" ]; then PREVLEVEL=$1 RUNLEVEL=$2 export PREVLEVEL RUNLEVEL fi exec /etc/init.d/rc 7 end script ``` I thought that would be enough, but **telinit 7** still throws this error: *telinit: illegal runlevel: 7*
You cannot; the runlevels are hardcoded into the utilities. But why do you need to? Runlevel 4 is essentially unused. And while it's not the best idea, you could repurpose either runlevel 3 or runlevel 5 depending on if you always/never use X. Note that some \*nix systems have support for more than 6 runlevels, but Linux is not one of them.
112,977
<p>I want to implement Generics in my Page Class like :</p> <pre><code>Public Class MyClass(Of TheClass) Inherits System.Web.UI.Page </code></pre> <p>But for this to work, I need to be able to instantiate the Class (with the correct Generic Class Type) and load the page, instead of a regular Response.Redirect. Is there a way to do this ?</p>
[ { "answer_id": 113080, "author": "Costo", "author_id": 1130, "author_profile": "https://Stackoverflow.com/users/1130", "pm_score": 2, "selected": false, "text": "<p>I'm not sure to fully understand what you want to do.\nIf you want something like a generic Page, you can use a generic Bas...
2008/09/22
[ "https://Stackoverflow.com/questions/112977", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
I want to implement Generics in my Page Class like : ``` Public Class MyClass(Of TheClass) Inherits System.Web.UI.Page ``` But for this to work, I need to be able to instantiate the Class (with the correct Generic Class Type) and load the page, instead of a regular Response.Redirect. Is there a way to do this ?
I'm not sure to fully understand what you want to do. If you want something like a generic Page, you can use a generic BasePage and put your generic methods into that BasePage: ``` Partial Public Class MyPage Inherits MyGenericBasePage(Of MyType) End Class Public Class MyGenericBasePage(Of T As New) Inherits System.Web.UI.Page Public Function MyGenericMethod() As T Return New T() End Function End Class Public Class MyType End Class ```
112,983
<p>I want to display data like the following:</p> <pre><code> Title Subject Summary Date </code></pre> <p>So my <code>HTML</code> looks like:</p> <pre><code>&lt;div class="title"&gt;&lt;/div&gt; &lt;div class="subject"&gt;&lt;/div&gt; &lt;div class="summary"&gt;&lt;/div&gt; &lt;div class="date"&gt;&lt;/div&gt; </code></pre> <p>The problem is, all the text doesn't appear on a single line. I tried adding <code>display="block"</code> but that doesn't seem to work.</p> <p>What am I doing wrong here?</p> <p><strong>Important:</strong> In this instance I dont want to use a <code>table</code> element but stick with <code>div</code> tags.</p>
[ { "answer_id": 112994, "author": "Andy Lester", "author_id": 8454, "author_profile": "https://Stackoverflow.com/users/8454", "pm_score": 5, "selected": false, "text": "<p>It looks like you're wanting to display a table, right? So go ahead and use the &lt;table&gt; tag.</p>\n" }, { ...
2008/09/22
[ "https://Stackoverflow.com/questions/112983", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1368/" ]
I want to display data like the following: ``` Title Subject Summary Date ``` So my `HTML` looks like: ``` <div class="title"></div> <div class="subject"></div> <div class="summary"></div> <div class="date"></div> ``` The problem is, all the text doesn't appear on a single line. I tried adding `display="block"` but that doesn't seem to work. What am I doing wrong here? **Important:** In this instance I dont want to use a `table` element but stick with `div` tags.
It looks like you're wanting to display a table, right? So go ahead and use the <table> tag.
113,033
<p>I have three (C++) classes: Player, Hand, and Card.</p> <p>Player has a member, hand, that holds a Hand. It also has a method, getHand(), that returns the contents of hand.</p> <pre><code>Hand Player::getHand() { return hand; } </code></pre> <p>Hand has a method, addCard(Card c), that adds a card to the hand.</p> <p>I want to do this:</p> <p>player1.getHand().addCard(c);</p> <p>but it doesn't work. It doesn't throw an error, so it's doing something. But if I examine the contents of player1's hand afterward, the card hasn't been added.</p> <p>How can I get this to work?</p>
[ { "answer_id": 113035, "author": "Adam Mitz", "author_id": 2574, "author_profile": "https://Stackoverflow.com/users/2574", "pm_score": 2, "selected": false, "text": "<p>If getHand() returns by-value you're modifying a copy of the hand and not the original.</p>\n" }, { "answer_id"...
2008/09/22
[ "https://Stackoverflow.com/questions/113033", "https://Stackoverflow.com", "https://Stackoverflow.com/users/18420/" ]
I have three (C++) classes: Player, Hand, and Card. Player has a member, hand, that holds a Hand. It also has a method, getHand(), that returns the contents of hand. ``` Hand Player::getHand() { return hand; } ``` Hand has a method, addCard(Card c), that adds a card to the hand. I want to do this: player1.getHand().addCard(c); but it doesn't work. It doesn't throw an error, so it's doing something. But if I examine the contents of player1's hand afterward, the card hasn't been added. How can I get this to work?
If getHand() is not returning a reference you will be in trouble.
113,045
<pre><code>SELECT GETDATE() </code></pre> <p>Returns: <code>2008-09-22 15:24:13.790</code></p> <p>I want that date part without the time part: <code>2008-09-22 00:00:00.000</code></p> <p>How can I get that?</p>
[ { "answer_id": 113051, "author": "Nescio", "author_id": 14484, "author_profile": "https://Stackoverflow.com/users/14484", "pm_score": 6, "selected": false, "text": "<p>Try this:</p>\n\n<pre><code>SELECT CONVERT(VARCHAR(10),GETDATE(),111)\n</code></pre>\n\n<p>The above statement converts ...
2008/09/22
[ "https://Stackoverflow.com/questions/113045", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5769/" ]
``` SELECT GETDATE() ``` Returns: `2008-09-22 15:24:13.790` I want that date part without the time part: `2008-09-22 00:00:00.000` How can I get that?
``` SELECT DATEADD(dd, 0, DATEDIFF(dd, 0, @your_date)) ``` for example ``` SELECT DATEADD(dd, 0, DATEDIFF(dd, 0, GETDATE())) ``` gives me ``` 2008-09-22 00:00:00.000 ``` Pros: * No varchar<->datetime conversions required * No need to think about locale
113,077
<p>I am creating a site in which different pages can look very different depending upon certain conditions (ie logged in or not, form filled out or not, etc). This makes it necessary to output diferent blocks of html at different times.</p> <p>Doing that, however, makes my php code look horrific... it really messes with the formatting and "shape" of the code. How should I get around this? Including custom "html dump" functions at the bottom of my scripts? The same thing, but with includes? Heredocs (don't look too good)?</p> <p>Thanks!</p>
[ { "answer_id": 113081, "author": "da5id", "author_id": 14979, "author_profile": "https://Stackoverflow.com/users/14979", "pm_score": 0, "selected": false, "text": "<p>In cases like that I write everything incrementally into a variable or sometimes an array and then echo the variable/arra...
2008/09/22
[ "https://Stackoverflow.com/questions/113077", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1615/" ]
I am creating a site in which different pages can look very different depending upon certain conditions (ie logged in or not, form filled out or not, etc). This makes it necessary to output diferent blocks of html at different times. Doing that, however, makes my php code look horrific... it really messes with the formatting and "shape" of the code. How should I get around this? Including custom "html dump" functions at the bottom of my scripts? The same thing, but with includes? Heredocs (don't look too good)? Thanks!
Don't panic, every fresh Web programmer face this problem. You HAVE TO separate your program logic from your display. First, try to make your own solution using two files for each Web page : * one with only PHP code (no HTML) that fills variables * another with HTML and very few PHP : this is your page design Then include where / when you need it. E.G : myPageLogic.php ``` <?php // pure PHP code, no HTML $name = htmlspecialchars($_GET['name']); $age = date('Y') - htmlspecialchars($_GET['age']); ?> ``` myPageView.php ``` // very few php code // just enought to print variables // and some if / else, or foreach to manage the data stream <h1>Hello, <?php $name ?> !</h1> <p>So your are <?php $age?>, hu ?</p> ``` (You may want to use the [alternative PHP syntax](http://php.mirror.camelnetwork.com/manual/en/control-structures.alternative-syntax.php) for this one. But don't try to hard to make it perfect the first time, really.) myPage.php ``` <?php require('myPageLogic.php'); require('myPageView.php'); ?> ``` *Don't bother about performance issues for now*. This is not your priority as a newbie. This solution is imperfect, but will help you to solve the problem with your programming level and will teach you the basics. Then, once your are comfortable with this concept, buy a book about the MVC pattern (or look for stack overflow entries about it). That what you want to do the *NEXT TIME*. Then you'll try some templating systems and frameworks, but *LATER*. For now, just code and learn from the beginning. You can perfectly code a project like that, as a rookie, it's fine.
113,103
<p>Can anyone explain the difference between the "name" property of a display object and the value found by <em>getChildByName("XXX")</em> function? They're the same 90% of the time, until they aren't, and things fall apart.</p> <p>For example, in the code below, I find an object by instance name only by directly examining the child's name property; <em>getChildByName()</em> fails. </p> <pre><code>var gfx:MovieClip = new a_Character(); //(a library object exported for Actionscript) var do1:DisplayObject = null; var do2:DisplayObject = null; for( var i:int = 0 ; i &lt; gfx.amSword.numChildren ; i++ ) { var child:DisplayObject = gfx.amSword.getChildAt(i); if( child.name == "amWeaponExchange" ) //An instance name set in the IDE { do2 = child; } } trace("do2:", do2 ); var do1:DisplayObject = gfx.amSword.getChildByName("amWeaponExchange"); </code></pre> <p>Generates the following output:</p> <pre><code>do2: [object MovieClip] ReferenceError: Error #1069: Property amWeaponExchange not found on builtin.as$0.MethodClosure and there is no default value. </code></pre> <p>Any ideas what Flash is thinking?</p>
[ { "answer_id": 113603, "author": "grapefrukt", "author_id": 914, "author_profile": "https://Stackoverflow.com/users/914", "pm_score": 0, "selected": false, "text": "<p>I haven't really managed to understand what it is you're doing. But one thing I've found is that accessing MovieClip's c...
2008/09/22
[ "https://Stackoverflow.com/questions/113103", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4969/" ]
Can anyone explain the difference between the "name" property of a display object and the value found by *getChildByName("XXX")* function? They're the same 90% of the time, until they aren't, and things fall apart. For example, in the code below, I find an object by instance name only by directly examining the child's name property; *getChildByName()* fails. ``` var gfx:MovieClip = new a_Character(); //(a library object exported for Actionscript) var do1:DisplayObject = null; var do2:DisplayObject = null; for( var i:int = 0 ; i < gfx.amSword.numChildren ; i++ ) { var child:DisplayObject = gfx.amSword.getChildAt(i); if( child.name == "amWeaponExchange" ) //An instance name set in the IDE { do2 = child; } } trace("do2:", do2 ); var do1:DisplayObject = gfx.amSword.getChildByName("amWeaponExchange"); ``` Generates the following output: ``` do2: [object MovieClip] ReferenceError: Error #1069: Property amWeaponExchange not found on builtin.as$0.MethodClosure and there is no default value. ``` Any ideas what Flash is thinking?
It seems you fixed it yourself! With: ``` var do1:DisplayObject = gfx.amSword.getChildByName["amWeaponExchange"]; ``` You get the error: ``` ReferenceError: Error #1069: Property amWeaponExchange not found on builtin.as$0.MethodClosure and there is no default value. ``` Because the compiler is looking for the property "amWeaponExchange" on the actual getChildByName **method**. When you change it to: ``` var do1:DisplayObject = gfx.amSword.getChildByName("amWeaponExchange"); ``` As you did in your edit, it successfully finds the child and compiles.
113,131
<p>What WPF Calendar control would you recommend? I am looking for something that will let me display a variable amount of weeks potentially spanning multiple months.</p>
[ { "answer_id": 113188, "author": "Dominic Hopton", "author_id": 9475, "author_profile": "https://Stackoverflow.com/users/9475", "pm_score": 0, "selected": false, "text": "<p>I would take a look at <a href=\"http://j832.com/BagOTricks/\" rel=\"nofollow noreferrer\">Kevin's Bag-o-tricks</a...
2008/09/22
[ "https://Stackoverflow.com/questions/113131", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5618/" ]
What WPF Calendar control would you recommend? I am looking for something that will let me display a variable amount of weeks potentially spanning multiple months.
Microsoft has now released a WPF calendar control. ``` <c:Calendar> <c:DatePicker.BlackoutDates> <c:CalendarDateRange Start="4/1/2008" End="4/6/2008"/> <c:CalendarDateRange Start="4/14/2008" End="4/17/2008"/> </c:DatePicker.BlackoutDates> </c:Calendar> <c:DatePicker> <c:DatePicker.BlackoutDates> <c:CalendarDateRange Start="4/1/2008" End="4/6/2008"/> <c:CalendarDateRange Start="4/14/2008" End="4/17/2008"/> </c:DatePicker.BlackoutDates> </c:DatePicker> ``` [![](https://i.stack.imgur.com/7WmdW.png)](https://i.stack.imgur.com/7WmdW.png) (source: [windowsclient.net](http://windowsclient.net/SiteFiles/1000/wpfsp1/wpf-35sp1-toolkit/110-1.png)) * <http://www.codeplex.com/wpf> * <http://windowsclient.net/wpf/wpf35/wpf-35sp1-toolkit-calendar-datepicker-walkthrough.aspx> Charles Petzold wrote a [good article about customising the WPF calendar control](http://msdn.microsoft.com/en-us/magazine/dd882520.aspx) too.
113,150
<p>I have the following situation:</p> <pre><code> class A { public: A(int whichFoo); int foo1(); int foo2(); int foo3(); int callFoo(); // cals one of the foo's depending on the value of whichFoo }; </code></pre> <p>In my current implementation I save the value of <code>whichFoo</code> in a data member in the constructor and use a <code>switch</code> in <code>callFoo()</code> to decide which of the foo's to call. Alternatively, I can use a <code>switch</code> in the constructor to save a pointer to the right <code>fooN()</code> to be called in <code>callFoo()</code>. </p> <p>My question is which way is more efficient if an object of class A is only constructed once, while <code>callFoo()</code> is called a very large number of times. So in the first case we have multiple executions of a switch statement, while in the second there is only one switch, and multiple calls of a member function using the pointer to it. I know that calling a member function using a pointer is slower than just calling it directly. Does anybody know if this overhead is more or less than the cost of a <code>switch</code>?</p> <p>Clarification: I realize that you never really know which approach gives better performance until you try it and time it. However, in this case I already have approach 1 implemented, and I wanted to find out if approach 2 can be more efficient at least in principle. It appears that it can be, and now it makes sense for me to bother to implement it and try it. </p> <p>Oh, and I also like approach 2 better for aesthetic reasons. I guess I am looking for a justification to implement it. :) </p>
[ { "answer_id": 113155, "author": "Greg Hewgill", "author_id": 893, "author_profile": "https://Stackoverflow.com/users/893", "pm_score": 5, "selected": true, "text": "<p>How sure are you that calling a member function via a pointer is slower than just calling it directly? Can you measure ...
2008/09/22
[ "https://Stackoverflow.com/questions/113150", "https://Stackoverflow.com", "https://Stackoverflow.com/users/13313/" ]
I have the following situation: ``` class A { public: A(int whichFoo); int foo1(); int foo2(); int foo3(); int callFoo(); // cals one of the foo's depending on the value of whichFoo }; ``` In my current implementation I save the value of `whichFoo` in a data member in the constructor and use a `switch` in `callFoo()` to decide which of the foo's to call. Alternatively, I can use a `switch` in the constructor to save a pointer to the right `fooN()` to be called in `callFoo()`. My question is which way is more efficient if an object of class A is only constructed once, while `callFoo()` is called a very large number of times. So in the first case we have multiple executions of a switch statement, while in the second there is only one switch, and multiple calls of a member function using the pointer to it. I know that calling a member function using a pointer is slower than just calling it directly. Does anybody know if this overhead is more or less than the cost of a `switch`? Clarification: I realize that you never really know which approach gives better performance until you try it and time it. However, in this case I already have approach 1 implemented, and I wanted to find out if approach 2 can be more efficient at least in principle. It appears that it can be, and now it makes sense for me to bother to implement it and try it. Oh, and I also like approach 2 better for aesthetic reasons. I guess I am looking for a justification to implement it. :)
How sure are you that calling a member function via a pointer is slower than just calling it directly? Can you measure the difference? In general, you should not rely on your intuition when making performance evaluations. Sit down with your compiler and a timing function, and actually *measure* the different choices. You may be surprised! More info: There is an excellent article [Member Function Pointers and the Fastest Possible C++ Delegates](http://www.codeproject.com/KB/cpp/FastDelegate.aspx) which goes into very deep detail about the implementation of member function pointers.
113,185
<p>I've installed <a href="http://www.owfs.org/" rel="nofollow noreferrer"><code>owfs</code></a> and am trying to read the data off a <a href="http://www.maxim-ic.com/quick_view2.cfm/qv_pk/4088" rel="nofollow noreferrer">iButton temperature logger</a>.</p> <p><code>owfs</code> lets me mount the iButton as a fuse filesystem and I can see all the data. I'm having trouble figuring out what is the best way to access the data though. I can get individual readings by <code>cat</code>ting the files, e.g. <code>cat onewire/{deviceid}/log/temperature.1</code>, but the <code>onewire/{deviceid}/log/temperature.ALL</code> file is "broken" (possible too large, as <code>histogram/temperature.ALL</code> work fine). </p> <p>A python script to read all files seems to work but takes a very long time. Is there a better way to do it? Does anyone have any examples?</p> <p>I'm using Ubuntu 8.04 and couldn't get the java "one wire viewer" app to run.</p> <p><strong>Update</strong>: Using <a href="http://owfs.sourceforge.net/owpython.html" rel="nofollow noreferrer"><code>owpython</code></a> (installed with owfs), I can get the current temperature but can't figure out how to get access to the recorded logs:</p> <pre><code>&gt;&gt;&gt; import ow &gt;&gt;&gt; ow.init("u") # initialize USB &gt;&gt;&gt; ow.Sensor("/").sensorList() [Sensor("/81.7FD921000000"), Sensor("/21.C4B912000000")] &gt;&gt;&gt; x = ow.Sensor("/21.C4B912000000") &gt;&gt;&gt; print x.type, x.temperature DS1921 22 </code></pre> <p><code>x.log</code> gives an <code>AttributeError</code>.</p>
[ { "answer_id": 117532, "author": "Armin Ronacher", "author_id": 19990, "author_profile": "https://Stackoverflow.com/users/19990", "pm_score": 2, "selected": false, "text": "<p>I don't think there is a clever way. owpython doesn't support that telling from the API documentation. I guess...
2008/09/22
[ "https://Stackoverflow.com/questions/113185", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3715/" ]
I've installed [`owfs`](http://www.owfs.org/) and am trying to read the data off a [iButton temperature logger](http://www.maxim-ic.com/quick_view2.cfm/qv_pk/4088). `owfs` lets me mount the iButton as a fuse filesystem and I can see all the data. I'm having trouble figuring out what is the best way to access the data though. I can get individual readings by `cat`ting the files, e.g. `cat onewire/{deviceid}/log/temperature.1`, but the `onewire/{deviceid}/log/temperature.ALL` file is "broken" (possible too large, as `histogram/temperature.ALL` work fine). A python script to read all files seems to work but takes a very long time. Is there a better way to do it? Does anyone have any examples? I'm using Ubuntu 8.04 and couldn't get the java "one wire viewer" app to run. **Update**: Using [`owpython`](http://owfs.sourceforge.net/owpython.html) (installed with owfs), I can get the current temperature but can't figure out how to get access to the recorded logs: ``` >>> import ow >>> ow.init("u") # initialize USB >>> ow.Sensor("/").sensorList() [Sensor("/81.7FD921000000"), Sensor("/21.C4B912000000")] >>> x = ow.Sensor("/21.C4B912000000") >>> print x.type, x.temperature DS1921 22 ``` `x.log` gives an `AttributeError`.
I don't think there is a clever way. owpython doesn't support that telling from the API documentation. I guess `/proc` is your safest bet. Maybe have a look at the source of the owpython module and check if you can find out how it works.
113,218
<p>I'm trying to build a web page with a number of drop-down select boxes that load their options asynchronously when the box is first opened. This works very well under Firefox, but not under Internet Explorer.</p> <p>Below is a small example of what I'm trying to achieve. Basically, there is a select box (with the id "selectBox"), which contains just one option ("Any"). Then there is an <code>onmousedown</code> handler that loads the other options when the box is clicked.</p> <pre><code>&lt;html&gt; &lt;head&gt; &lt;script type="text/javascript"&gt; function appendOption(select,option) { try { selectBox.add(option,null); // Standards compliant. } catch (e) { selectBox.add(option); // IE only version. } } function loadOptions() { // Simulate an AJAX request that will call the // loadOptionsCallback function after 500ms. setTimeout(loadOptionsCallback,500); } function loadOptionsCallback() { var selectBox = document.getElementById('selectBox'); var option = document.createElement('option'); option.text = 'new option'; appendOption(selectBox,option); } &lt;/script&gt; &lt;/head&gt; &lt;body&gt; &lt;select id="selectBox" onmousedown="loadOptions();"&gt; &lt;option&gt;Any&lt;/option&gt; &lt;/select&gt; &lt;/body&gt; &lt;/html&gt; </code></pre> <p>The desired behavior (which Firefox does) is:</p> <ol> <li>the user see's a closed select box containing "Any".</li> <li>the user clicks on the select box.</li> <li>the select box opens to reveal the one and only option ("Any").</li> <li>500ms later (or when the AJAX call has returned) the dropped-down list expands to include the new options (hard coded to 'new option' in this example).</li> </ol> <p>So that's exactly what Firefox does, which is great. However, in Internet Explorer, as soon as the new option is added in "4" the browser closes the select box. The select box does contain the correct options, but the box is closed, requiring the user to click to re-open it.</p> <p>So, does anyone have any suggestions for how I can load the select control's options asynchronously without IE closing the drop-down box?</p> <p>I know that I can load the list <em>before</em> the box is even clicked, but the real form I'm developing contains many such select boxes, which are all interrelated, so it will be <strong>much</strong> better for both the client and server if I can load each set of options only when needed.</p> <p>Also, if the results are loaded synchronously, before the select box's <code>onmousedown</code> handler completes, then IE will show the full list as expected - however, synchronous loading is a <strong>bad</strong> idea here, since it will completely "lock" the browser while the network requests are taking place.</p> <p>Finally, I've also tried using IE's <code>click()</code> method to open the select box once the new options have been added, but that does not re-open the select box.</p> <p>Any ideas or suggestions would be really appreciated!! :)</p> <p>Thanks!</p> <p>Paul.</p>
[ { "answer_id": 113211, "author": "Adam Pierce", "author_id": 5324, "author_profile": "https://Stackoverflow.com/users/5324", "pm_score": 2, "selected": false, "text": "<p>I like <a href=\"http://www.gtk.org/\" rel=\"nofollow noreferrer\">GTK+</a> personally but that or any of the ones yo...
2008/09/22
[ "https://Stackoverflow.com/questions/113218", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
I'm trying to build a web page with a number of drop-down select boxes that load their options asynchronously when the box is first opened. This works very well under Firefox, but not under Internet Explorer. Below is a small example of what I'm trying to achieve. Basically, there is a select box (with the id "selectBox"), which contains just one option ("Any"). Then there is an `onmousedown` handler that loads the other options when the box is clicked. ``` <html> <head> <script type="text/javascript"> function appendOption(select,option) { try { selectBox.add(option,null); // Standards compliant. } catch (e) { selectBox.add(option); // IE only version. } } function loadOptions() { // Simulate an AJAX request that will call the // loadOptionsCallback function after 500ms. setTimeout(loadOptionsCallback,500); } function loadOptionsCallback() { var selectBox = document.getElementById('selectBox'); var option = document.createElement('option'); option.text = 'new option'; appendOption(selectBox,option); } </script> </head> <body> <select id="selectBox" onmousedown="loadOptions();"> <option>Any</option> </select> </body> </html> ``` The desired behavior (which Firefox does) is: 1. the user see's a closed select box containing "Any". 2. the user clicks on the select box. 3. the select box opens to reveal the one and only option ("Any"). 4. 500ms later (or when the AJAX call has returned) the dropped-down list expands to include the new options (hard coded to 'new option' in this example). So that's exactly what Firefox does, which is great. However, in Internet Explorer, as soon as the new option is added in "4" the browser closes the select box. The select box does contain the correct options, but the box is closed, requiring the user to click to re-open it. So, does anyone have any suggestions for how I can load the select control's options asynchronously without IE closing the drop-down box? I know that I can load the list *before* the box is even clicked, but the real form I'm developing contains many such select boxes, which are all interrelated, so it will be **much** better for both the client and server if I can load each set of options only when needed. Also, if the results are loaded synchronously, before the select box's `onmousedown` handler completes, then IE will show the full list as expected - however, synchronous loading is a **bad** idea here, since it will completely "lock" the browser while the network requests are taking place. Finally, I've also tried using IE's `click()` method to open the select box once the new options have been added, but that does not re-open the select box. Any ideas or suggestions would be really appreciated!! :) Thanks! Paul.
I have both worked with PyQt and wxPython extensively. PyQt is better designed and comes with very good UI designer so that you can quickly assemble your UI wxPython has a very good demo and it can do pretty much anything which PyQT can do, I would anyday prefer PyQt but it may bot be free for commercial purpose but wxPython is free and is decent cross platform library.
113,253
<p>My web page sits in a DIV that is 960px wide, I center this DIV in the middle of the page by using the code: </p> <pre><code>html,body{background: url(images/INF_pageBg.gif) center top repeat-y #777777;text-align:center;} #container{background-color:#ffffff;width:960px;text-align:left;margin:0 auto 0 auto;} </code></pre> <p>I need the background image of the html/body to tile down the middle of the page, which it does, however if the viewable pane in the browser is an odd number of pixels width then the centered background and centered DIV don't align together.</p> <p>This is only happening in FF.</p> <p>Does anybody know of a workaround?</p>
[ { "answer_id": 113268, "author": "dimarzionist", "author_id": 10778, "author_profile": "https://Stackoverflow.com/users/10778", "pm_score": 3, "selected": true, "text": "<p>Yeah, it's known issue. Unfortunately you only can fix div and image width, or use script to dynamically change sty...
2008/09/22
[ "https://Stackoverflow.com/questions/113253", "https://Stackoverflow.com", "https://Stackoverflow.com/users/910/" ]
My web page sits in a DIV that is 960px wide, I center this DIV in the middle of the page by using the code: ``` html,body{background: url(images/INF_pageBg.gif) center top repeat-y #777777;text-align:center;} #container{background-color:#ffffff;width:960px;text-align:left;margin:0 auto 0 auto;} ``` I need the background image of the html/body to tile down the middle of the page, which it does, however if the viewable pane in the browser is an odd number of pixels width then the centered background and centered DIV don't align together. This is only happening in FF. Does anybody know of a workaround?
Yeah, it's known issue. Unfortunately you only can fix div and image width, or use script to dynamically change stye.backgroundPosition property. Another trick is to put expression to the CSS class definition.
113,275
<p>Here is what I have:</p> <pre><code> context "Create ingredient from string" do context "1 cups butter" do setup do @ingredient = Ingredient.create(:ingredient_string =&gt; "1 cups butter") end should "return unit" do assert_equal @ingredient.unit, 'cups' end should "return amount" do assert_equal @ingredient.amount, 1.0 end should "return name" do assert_equal @ingredient.name, 'butter' end end context "1 (18.25 ounce) package devil's food cake mix with pudding" do setup do @ingredient = Ingredient.create(:ingredient_string =&gt; "1 (18.25 ounce) package devil's food cake mix with pudding") end should "return unit" do assert_equal @ingredient.unit, '(18.25 ounce) package' end should "return amount" do assert_equal @ingredient.amount, 1.0 end should "return name" do assert_equal @ingredient.name, 'devil\'s food cake mix with pudding' end end end </code></pre> <p>Clearly there is a lot of duplication there. Any thoughts on how to remove it, if only at the very least the context and the string?</p>
[ { "answer_id": 113359, "author": "Andrew", "author_id": 17408, "author_profile": "https://Stackoverflow.com/users/17408", "pm_score": 0, "selected": false, "text": "<p>Personally for this test, I wouldn't use Shoulda.\nYou can easily remove duplication by using dynamic method creation as...
2008/09/22
[ "https://Stackoverflow.com/questions/113275", "https://Stackoverflow.com", "https://Stackoverflow.com/users/12448/" ]
Here is what I have: ``` context "Create ingredient from string" do context "1 cups butter" do setup do @ingredient = Ingredient.create(:ingredient_string => "1 cups butter") end should "return unit" do assert_equal @ingredient.unit, 'cups' end should "return amount" do assert_equal @ingredient.amount, 1.0 end should "return name" do assert_equal @ingredient.name, 'butter' end end context "1 (18.25 ounce) package devil's food cake mix with pudding" do setup do @ingredient = Ingredient.create(:ingredient_string => "1 (18.25 ounce) package devil's food cake mix with pudding") end should "return unit" do assert_equal @ingredient.unit, '(18.25 ounce) package' end should "return amount" do assert_equal @ingredient.amount, 1.0 end should "return name" do assert_equal @ingredient.name, 'devil\'s food cake mix with pudding' end end end ``` Clearly there is a lot of duplication there. Any thoughts on how to remove it, if only at the very least the context and the string?
Here's a solution to your specific problem. The idea is to create a class method (like Shoulda's context, setup and should). Encapsulate the repetition in a class method accepting all varying parts as arguments like this: ``` def self.should_get_unit_amount_and_name_from_string(unit, amount, name, string_to_analyze) context string_to_analyze do setup do @ingredient = Ingredient.create(:ingredient_string => string_to_analyze) end should "return unit" do assert_equal @ingredient.unit, unit end should "return amount" do assert_equal @ingredient.amount, amount end should "return name" do assert_equal @ingredient.name, name end end end ``` Now you can call all these encapsulated tests with one liners (5-liners here for readability ;-) ``` context "Create ingredient from string" do should_get_unit_amount_and_name_from_string( 'cups', 1.0, 'butter', "1 cups butter") should_get_unit_amount_and_name_from_string( '(18.25 ounce) package', 1.0, 'devil\'s food cake mix with pudding', "1 (18.25 ounce) package devil's food cake mix with pudding") end ``` In some cases, you may want to accept a block which could serve as your Shoulda setup.
113,341
<p>I'm trying to create a character generation wizard for a game. In one class I calculate the attributes of the character. In a different class, I'm displaying to the user which specialties are available based on the attributes of the character. However, I can't remember how to pass variables between different classes.</p> <p>Here is an example of what I have:</p> <pre><code>class BasicInfoPage(wx.wizard.WizardPageSimple): def __init__(self, parent, title): wiz.WizardPageSimple.__init__(self, parent) self.next = self.prev = None self.sizer = makePageTitle(self, title) &lt;---snip---&gt; self.intelligence = self.genAttribs() class MOS(wx.wizard.WizardPageSimple): def __init__(self, parent, title): wiz.WizardPageSimple.__init__(self, parent) self.next = self.prev = None self.sizer = makePageTitle(self, title) def eligibleMOS(self, event): if self.intelligence &gt;= 12: self.MOS_list.append("Analyst") </code></pre> <p>The problem is that I can't figure out how to use the "intelligence" variable from the BasicInfoPage class to the MOS class. I've tried several different things from around the Internet but nothing seems to work. What am I missing?</p> <p><strong>Edit</strong> I realized after I posted this that I didn't explain it that well. I'm trying to create a computer version of the Twilight 2000 RPG from the 1980s.</p> <p>I'm using wxPython to create a wizard; the parent class of my classes is the Wizard from wxPython. That wizard will walk a user through the creation of a character, so the Basic Information page (class BasicInfoPage) lets the user give the character's name and "roll" for the character's attributes. That's where the "self.intelligence" comes from.</p> <p>I'm trying to use the attributes created her for a page further on in the wizard, where the user selects the speciality of the character. The specialities that are available depend on the attributes the character has, e.g. if the intelligence is high enough, the character can be an Intel Anaylst.</p> <p>It's been several years since I've programmed, especially with OOP ideas. That's why I'm confused on how to create what's essentially a global variable with classes and methods. </p>
[ { "answer_id": 113374, "author": "Antti Rasinen", "author_id": 8570, "author_profile": "https://Stackoverflow.com/users/8570", "pm_score": 0, "selected": false, "text": "<p>If I understood you correctly, then the answer is: You can't.</p>\n\n<p>intelligence should be an attribute of Wiza...
2008/09/22
[ "https://Stackoverflow.com/questions/113341", "https://Stackoverflow.com", "https://Stackoverflow.com/users/18676/" ]
I'm trying to create a character generation wizard for a game. In one class I calculate the attributes of the character. In a different class, I'm displaying to the user which specialties are available based on the attributes of the character. However, I can't remember how to pass variables between different classes. Here is an example of what I have: ``` class BasicInfoPage(wx.wizard.WizardPageSimple): def __init__(self, parent, title): wiz.WizardPageSimple.__init__(self, parent) self.next = self.prev = None self.sizer = makePageTitle(self, title) <---snip---> self.intelligence = self.genAttribs() class MOS(wx.wizard.WizardPageSimple): def __init__(self, parent, title): wiz.WizardPageSimple.__init__(self, parent) self.next = self.prev = None self.sizer = makePageTitle(self, title) def eligibleMOS(self, event): if self.intelligence >= 12: self.MOS_list.append("Analyst") ``` The problem is that I can't figure out how to use the "intelligence" variable from the BasicInfoPage class to the MOS class. I've tried several different things from around the Internet but nothing seems to work. What am I missing? **Edit** I realized after I posted this that I didn't explain it that well. I'm trying to create a computer version of the Twilight 2000 RPG from the 1980s. I'm using wxPython to create a wizard; the parent class of my classes is the Wizard from wxPython. That wizard will walk a user through the creation of a character, so the Basic Information page (class BasicInfoPage) lets the user give the character's name and "roll" for the character's attributes. That's where the "self.intelligence" comes from. I'm trying to use the attributes created her for a page further on in the wizard, where the user selects the speciality of the character. The specialities that are available depend on the attributes the character has, e.g. if the intelligence is high enough, the character can be an Intel Anaylst. It's been several years since I've programmed, especially with OOP ideas. That's why I'm confused on how to create what's essentially a global variable with classes and methods.
You may have "Class" and "Instance" confused. It's not clear from your example, so I'll presume that you're using a lot of class definitions and don't have appropriate object instances of those classes. Classes don't really have usable attribute values. A class is just a common set of definitions for a collection of objects. You should think of of classes as definitions, not actual things. Instances of classes, "objects", are actual things that have actual attribute values and execute method functions. You don't pass variables among *classes*. You pass variables among *instances*. As a practical matter only instance variables matter. [Yes, there are class variables, but they're a fairly specialized and often confusing thing, best avoided.] When you create an object (an instance of a class) ``` b= BasicInfoPage(...) ``` Then `b.intelligence` is the value of intelligence for the `b` instance of `BasicInfoPage`. A really common thing is ``` class MOS( wx.wizard.PageSimple ): def __init__( self, parent, title, basicInfoPage ): <snip> self.basicInfo= basicInfoPage ``` Now, within MOS methods, you can say `self.basicInfo.intelligence` because MOS has an object that's a BasicInfoPage available to it. When you build MOS, you provide it with the instance of BasicInfoPage that it's supposed to use. ``` someBasicInfoPage= BasicInfoPage( ... ) m= MOS( ..., someBasicInfoPage ) ``` Now, the object `m` can examine `someBasicInfoPage.intelligence`
113,349
<p>I have an AdvancedDataGrid with a GroupingCollection and a SummaryRow. How do I display the summary row data in bold? Below is my code:</p> <pre><code>&lt;mx:AdvancedDataGrid width="100%" height="100%" id="adg" defaultLeafIcon="{null}" &gt; &lt;mx:dataProvider&gt; &lt;mx:GroupingCollection id="gc" source="{dataProvider}"&gt; &lt;mx:Grouping&gt; &lt;mx:GroupingField name="bankType"&gt; &lt;mx:summaries&gt; &lt;mx:SummaryRow summaryPlacement="group" id="summaryRow"&gt; &lt;mx:fields&gt; &lt;mx:SummaryField dataField="t0" label="t0" operation="SUM" /&gt; &lt;/mx:fields&gt; &lt;/mx:SummaryRow&gt; &lt;/mx:summaries&gt; &lt;/mx:GroupingField&gt; &lt;/mx:Grouping&gt; &lt;/mx:GroupingCollection&gt; &lt;/mx:dataProvider&gt; &lt;mx:columns&gt; &lt;mx:AdvancedDataGridColumn dataField="GroupLabel" headerText=""/&gt; &lt;mx:AdvancedDataGridColumn dataField="name" headerText="Bank" /&gt; &lt;mx:AdvancedDataGridColumn dataField="t0" headerText="Amount" formatter="{formatter}"/&gt; &lt;/mx:columns&gt; &lt;/mx:AdvancedDataGrid&gt; </code></pre>
[ { "answer_id": 114323, "author": "Swaroop C H", "author_id": 4869, "author_profile": "https://Stackoverflow.com/users/4869", "pm_score": 0, "selected": false, "text": "<p>If I've understood <a href=\"http://livedocs.adobe.com/flex/3/html/advdatagrid_10.html\" rel=\"nofollow noreferrer\">...
2008/09/22
[ "https://Stackoverflow.com/questions/113349", "https://Stackoverflow.com", "https://Stackoverflow.com/users/16534/" ]
I have an AdvancedDataGrid with a GroupingCollection and a SummaryRow. How do I display the summary row data in bold? Below is my code: ``` <mx:AdvancedDataGrid width="100%" height="100%" id="adg" defaultLeafIcon="{null}" > <mx:dataProvider> <mx:GroupingCollection id="gc" source="{dataProvider}"> <mx:Grouping> <mx:GroupingField name="bankType"> <mx:summaries> <mx:SummaryRow summaryPlacement="group" id="summaryRow"> <mx:fields> <mx:SummaryField dataField="t0" label="t0" operation="SUM" /> </mx:fields> </mx:SummaryRow> </mx:summaries> </mx:GroupingField> </mx:Grouping> </mx:GroupingCollection> </mx:dataProvider> <mx:columns> <mx:AdvancedDataGridColumn dataField="GroupLabel" headerText=""/> <mx:AdvancedDataGridColumn dataField="name" headerText="Bank" /> <mx:AdvancedDataGridColumn dataField="t0" headerText="Amount" formatter="{formatter}"/> </mx:columns> </mx:AdvancedDataGrid> ```
in the past when I have need to do this I had to put a condition in my style function to try and determine if it is a summary row or not. ``` public function dataGrid_styleFunction (data:Object, column:AdvancedDataGridColumn) : Object { var output:Object; if ( data.children != null ) { output = {color:0x081EA6, fontWeight:"bold", fontSize:14} } return output; } ``` if it has children, it should be a summary row. I am not sure this is the quote/unquote right way of doing this, but it does work, at least in my uses. HTH
113,376
<p>How do you impose a character limit on a text input in HTML?</p>
[ { "answer_id": 113379, "author": "cruizer", "author_id": 6441, "author_profile": "https://Stackoverflow.com/users/6441", "pm_score": 5, "selected": false, "text": "<p>there's a maxlength attribute</p>\n\n<pre><code>&lt;input type=\"text\" name=\"textboxname\" maxlength=\"100\" /&gt;\n</c...
2008/09/22
[ "https://Stackoverflow.com/questions/113376", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5509/" ]
How do you impose a character limit on a text input in HTML?
There are 2 main solutions: The pure HTML one: ``` <input type="text" id="Textbox" name="Textbox" maxlength="10" /> ``` The JavaScript one (attach it to a onKey Event): ``` function limitText(limitField, limitNum) { if (limitField.value.length > limitNum) { limitField.value = limitField.value.substring(0, limitNum); } } ``` But anyway, there is no good solution. You can not adapt to every client's bad HTML implementation, it's an impossible fight to win. That's why it's far better to check it on the server side, with a PHP / Python / whatever script.
113,384
<p>I have a marker interface defined as</p> <pre><code>public interface IExtender&lt;T&gt; { } </code></pre> <p>I have a class that implements IExtender</p> <pre><code>public class UserExtender : IExtender&lt;User&gt; </code></pre> <p>At runtime I recieve the UserExtender type as a parameter to my evaluating method</p> <pre><code>public Type Evaluate(Type type) // type == typeof(UserExtender) </code></pre> <p>How do I make my Evaluate method return </p> <pre><code>typeof(User) </code></pre> <p>based on the runtime evaluation. I am sure reflection is involved but I can't seem to crack it.</p> <p>(I was unsure how to word this question. I hope it is clear enough.)</p>
[ { "answer_id": 113379, "author": "cruizer", "author_id": 6441, "author_profile": "https://Stackoverflow.com/users/6441", "pm_score": 5, "selected": false, "text": "<p>there's a maxlength attribute</p>\n\n<pre><code>&lt;input type=\"text\" name=\"textboxname\" maxlength=\"100\" /&gt;\n</c...
2008/09/22
[ "https://Stackoverflow.com/questions/113384", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4884/" ]
I have a marker interface defined as ``` public interface IExtender<T> { } ``` I have a class that implements IExtender ``` public class UserExtender : IExtender<User> ``` At runtime I recieve the UserExtender type as a parameter to my evaluating method ``` public Type Evaluate(Type type) // type == typeof(UserExtender) ``` How do I make my Evaluate method return ``` typeof(User) ``` based on the runtime evaluation. I am sure reflection is involved but I can't seem to crack it. (I was unsure how to word this question. I hope it is clear enough.)
There are 2 main solutions: The pure HTML one: ``` <input type="text" id="Textbox" name="Textbox" maxlength="10" /> ``` The JavaScript one (attach it to a onKey Event): ``` function limitText(limitField, limitNum) { if (limitField.value.length > limitNum) { limitField.value = limitField.value.substring(0, limitNum); } } ``` But anyway, there is no good solution. You can not adapt to every client's bad HTML implementation, it's an impossible fight to win. That's why it's far better to check it on the server side, with a PHP / Python / whatever script.
113,385
<p>Is there anyway to declare an object of a class before the class is created in C++? I ask because I am trying to use two classes, the first needs to have an instance of the second class within it, but the second class also contains an instance of the first class. I realize that you may think I might get into an infinite loop, but I actually need to create and instance of the second class before the first class.</p>
[ { "answer_id": 113391, "author": "Adam Pierce", "author_id": 5324, "author_profile": "https://Stackoverflow.com/users/5324", "pm_score": 3, "selected": false, "text": "<p>You can't declare an instance of an undefined class but you can declare a <strong>pointer</strong> to one:</p>\n\n<pr...
2008/09/22
[ "https://Stackoverflow.com/questions/113385", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20229/" ]
Is there anyway to declare an object of a class before the class is created in C++? I ask because I am trying to use two classes, the first needs to have an instance of the second class within it, but the second class also contains an instance of the first class. I realize that you may think I might get into an infinite loop, but I actually need to create and instance of the second class before the first class.
You can't do something like this: ``` class A { B b; }; class B { A a; }; ``` The most obvious problem is the compiler doesn't know how to large it needs to make class A, because the size of B depends on the size of A! You can, however, do this: ``` class B; // this is a "forward declaration" class A { B *b; }; class B { A a; }; ``` Declaring class B as a forward declaration allows you to use pointers (and references) to that class without yet having the whole class definition.
113,392
<p>I'm trying to wrap my head around asp.net. I have a background as a long time php developer, but I'm now facing the task of learning asp.net and I'm having some trouble with it. It might very well be because I'm trying to force the framework into something it is not intended for - so I'd like to learn how to do it "the right way". :-)</p> <p>My problem is how to add controls to a page programmatically at runtime. As far as I can figure out you need to create the controls at page_init as they otherwise disappears at the next PostBack. But many times I'm facing the problem that I don't know which controls to add in page_init as it is dependent on values from at previous PostBack.</p> <p>A simple scenario could be a form with a dropdown control added in the designer. The dropdown is set to AutoPostBack. When the PostBack occur I need to render one or more controls denepending on the selected value from the dropdown control and preferably have those controls act as if they had been added by the design (as in "when posted back, behave "properly").</p> <p>Am I going down the wrong path here?</p>
[ { "answer_id": 113411, "author": "Jesper Blad Jensen", "author_id": 11559, "author_profile": "https://Stackoverflow.com/users/11559", "pm_score": 0, "selected": false, "text": "<p>Well. If you can get out of creating controls dynamicly, then do so - otherwise, what i whould do is to use ...
2008/09/22
[ "https://Stackoverflow.com/questions/113392", "https://Stackoverflow.com", "https://Stackoverflow.com/users/17700/" ]
I'm trying to wrap my head around asp.net. I have a background as a long time php developer, but I'm now facing the task of learning asp.net and I'm having some trouble with it. It might very well be because I'm trying to force the framework into something it is not intended for - so I'd like to learn how to do it "the right way". :-) My problem is how to add controls to a page programmatically at runtime. As far as I can figure out you need to create the controls at page\_init as they otherwise disappears at the next PostBack. But many times I'm facing the problem that I don't know which controls to add in page\_init as it is dependent on values from at previous PostBack. A simple scenario could be a form with a dropdown control added in the designer. The dropdown is set to AutoPostBack. When the PostBack occur I need to render one or more controls denepending on the selected value from the dropdown control and preferably have those controls act as if they had been added by the design (as in "when posted back, behave "properly"). Am I going down the wrong path here?
I agree with the other points made here "If you can get out of creating controls dynamically, then do so..." (by @[Jesper Blad Jenson aka](https://stackoverflow.com/users/11559/jesper-blad-jensen-aka-deldy)) but here is a trick I worked out with dynamically created controls in the past. The problem becomes chicken and the egg. You need your ViewState to create the control tree and you need your control tree created to get at your ViewState. Well, that's almost correct. There is a way to get at your ViewState values *just before* the rest of the tree is populated. That is by overriding [`LoadViewState(...)`](http://msdn.microsoft.com/en-us/library/system.web.ui.control.loadviewstate.aspx "MSDN - Control.LoadViewState Method") and [`SaveViewState(...)`](http://msdn.microsoft.com/en-us/library/system.web.ui.control.saveviewstate.aspx "MSDN - Control.SaveViewState Method"). In SaveViewState store the control you wish to create: ``` protected override object SaveViewState() { object[] myState = new object[2]; myState[0] = base.SaveViewState(); myState[1] = controlPickerDropDown.SelectedValue; return myState } ``` When the framework calls your "LoadViewState" override you'll get back the exact object you returned from "SaveViewState": ``` protected override void LoadViewState(object savedState) { object[] myState = (object[])savedState; // Here is the trick, use the value you saved here to create your control tree. CreateControlBasedOnDropDownValue(myState[1]); // Call the base method to ensure everything works correctly. base.LoadViewState(myState[0]); } ``` I've used this successfully to create ASP.Net pages where a DataSet was serialised to the ViewState to store changes to an entire grid of data allowing the user to make multiple edits with PostBacks and finally commit all their changes in a single "Save" operation.
113,395
<p>Visual Studio Test can check for expected exceptions using the ExpectedException attribute. You can pass in an exception like this:</p> <pre><code>[TestMethod] [ExpectedException(typeof(CriticalException))] public void GetOrganisation_MultipleOrganisations_ThrowsException() </code></pre> <p>You can also check for the message contained within the ExpectedException like this:</p> <pre><code>[TestMethod] [ExpectedException(typeof(CriticalException), "An error occured")] public void GetOrganisation_MultipleOrganisations_ThrowsException() </code></pre> <p>But when testing I18N applications I would use a resource file to get that error message (any may even decide to test the different localizations of the error message if I want to, but Visual Studio will not let me do this:</p> <pre><code>[TestMethod] [ExpectedException(typeof(CriticalException), MyRes.MultipleOrganisationsNotAllowed)] public void GetOrganisation_MultipleOrganisations_ThrowsException() </code></pre> <p>The compiler will give the following error:</p> <blockquote> <p>An attribute argument must be a constant expression, typeof expression or array creation expression of an attribute</p> </blockquote> <p>Does anybody know how to test for an exception that has a message from a resource file?</p> <hr> <p>One option I have considered is using custom exception classes, but based on often heard advice such as:</p> <blockquote> <p>"Do create and throw custom exceptions if you have an error condition that can be programmatically handled in a different way than any other existing exception. Otherwise, throw one of the existing exceptions." <a href="http://blogs.msdn.com/kcwalina/archive/2005/03/16/396787.aspx" rel="noreferrer">Source</a></p> </blockquote> <p>I'm not expecting to handle the exceptions differently in normal flow (it's a critical exception, so I'm going into panic mode anyway) and I don't think creating an exception for each test case is the right thing to do. Any opinions?</p>
[ { "answer_id": 113420, "author": "cruizer", "author_id": 6441, "author_profile": "https://Stackoverflow.com/users/6441", "pm_score": 2, "selected": false, "text": "<p>I think you can just do an explicit try-catch in your test code instead of relying on the ExpectedException attribute to ...
2008/09/22
[ "https://Stackoverflow.com/questions/113395", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5790/" ]
Visual Studio Test can check for expected exceptions using the ExpectedException attribute. You can pass in an exception like this: ``` [TestMethod] [ExpectedException(typeof(CriticalException))] public void GetOrganisation_MultipleOrganisations_ThrowsException() ``` You can also check for the message contained within the ExpectedException like this: ``` [TestMethod] [ExpectedException(typeof(CriticalException), "An error occured")] public void GetOrganisation_MultipleOrganisations_ThrowsException() ``` But when testing I18N applications I would use a resource file to get that error message (any may even decide to test the different localizations of the error message if I want to, but Visual Studio will not let me do this: ``` [TestMethod] [ExpectedException(typeof(CriticalException), MyRes.MultipleOrganisationsNotAllowed)] public void GetOrganisation_MultipleOrganisations_ThrowsException() ``` The compiler will give the following error: > > An attribute argument must be a > constant expression, typeof expression > or array creation expression of an > attribute > > > Does anybody know how to test for an exception that has a message from a resource file? --- One option I have considered is using custom exception classes, but based on often heard advice such as: > > "Do create and throw custom exceptions > if you have an error condition that > can be programmatically handled in a > different way than any other existing > exception. Otherwise, throw one of the > existing exceptions." [Source](http://blogs.msdn.com/kcwalina/archive/2005/03/16/396787.aspx) > > > I'm not expecting to handle the exceptions differently in normal flow (it's a critical exception, so I'm going into panic mode anyway) and I don't think creating an exception for each test case is the right thing to do. Any opinions?
*Just* an opinion, but I would say the error text: * is part of the test, in which case getting it from the resource would be 'wrong' (otherwise you could end up with a consistantly mangled resource), so just update the test when you change the resource (or the test fails) * is not part of the test, and you should only care that it throws the exception. Note that the first option should let you test multiple languages, given the ability to run with a locale. As for multiple exceptions, I'm from C++ land, where creating loads and loads of exceptions (to the point of one per 'throw' statement!) in big heirachies is acceptable (if not common), but .Net's metadata system probably doesn't like that, hence that advice.
113,504
<p>Is there a way to be sure we hold a useable reference to an object i.e. being sure it has not been already freed leaving that non nil reference dangling.</p>
[ { "answer_id": 113512, "author": "Lasse V. Karlsen", "author_id": 267, "author_profile": "https://Stackoverflow.com/users/267", "pm_score": 0, "selected": false, "text": "<p>Unfortunately there is no way to 100% guarantee that a pointer to anything is still valid, except by meticolously ...
2008/09/22
[ "https://Stackoverflow.com/questions/113504", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
Is there a way to be sure we hold a useable reference to an object i.e. being sure it has not been already freed leaving that non nil reference dangling.
If you're using FastMM4 as your Memory Manager, you can check that the class is not **TFreeObject**. Or, in a more standard case, use a routine that will verify that your object is what it says it is by **checking the class VMT**. There have been such ValidateObj functions hannging around for some time (by Ray Lischner and Hallvard Vassbotn: <http://hallvards.blogspot.com/2004/06/hack-6checking-for-valid-object.html>) Here's another: ``` function ValidateObj(Obj: TObject): Pointer; // see { Virtual method table entries } in System.pas begin Result := Obj; if Assigned(Result) then try if Pointer(PPointer(Obj)^) <> Pointer(Pointer(Cardinal(PPointer(Obj)^) + Cardinal(vmtSelfPtr))^) then // object not valid anymore Result := nil; except Result := nil; end; end; ``` Update: A bit of caution... The above function will ensure that the result is either nil or a valid non nil Object. It does not guarantee that the Obj is still what you think it is, in case where the Memory Manager has already reallocated that previously freed memory.
113,507
<p>I've written a control in C# that overrides the built-in DropDownList control. For this I need a javascript resource included, which I'm including as an embedded resource then adding the <code>WebResource</code> attribute, which works fine.</p> <p>However, I also need to reference a webservice, which I would normally include in the scriptmanager on the page like this</p> <pre><code>&lt;asp:scriptmanager id="scriptmanager" runat="server"&gt; &lt;Services&gt; &lt;asp:ServiceReference Path="~/Path/To/Service.asmx" /&gt; &lt;/Services&gt; &lt;/asp:scriptmanager&gt; </code></pre> <p>Is there any way to make the page include this reference in the code behind on the control I've created, similar to how it includes the embedded javascript file?</p>
[ { "answer_id": 113535, "author": "Dested", "author_id": 11137, "author_profile": "https://Stackoverflow.com/users/11137", "pm_score": 0, "selected": false, "text": "<p>If you know the page the usercontrol is in you can do a ((PageName)this.Page).scriptmanager.Services.Add() from the user...
2008/09/22
[ "https://Stackoverflow.com/questions/113507", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2975/" ]
I've written a control in C# that overrides the built-in DropDownList control. For this I need a javascript resource included, which I'm including as an embedded resource then adding the `WebResource` attribute, which works fine. However, I also need to reference a webservice, which I would normally include in the scriptmanager on the page like this ``` <asp:scriptmanager id="scriptmanager" runat="server"> <Services> <asp:ServiceReference Path="~/Path/To/Service.asmx" /> </Services> </asp:scriptmanager> ``` Is there any way to make the page include this reference in the code behind on the control I've created, similar to how it includes the embedded javascript file?
You can add a ScriptManagerProxy in the code or the markup of your control and add the service reference through it. The settings in the ScriptManagerProxy are merged with the "real" ScriptManager at compile time.
113,511
<p>How do we decide on the best implementation of <code>hashCode()</code> method for a collection (assuming that equals method has been overridden correctly) ?</p>
[ { "answer_id": 113530, "author": "Chris Carruthers", "author_id": 1119, "author_profile": "https://Stackoverflow.com/users/1119", "pm_score": -1, "selected": false, "text": "<p>For a simple class it is often easiest to implement hashCode() based on the class fields which are checked by t...
2008/09/22
[ "https://Stackoverflow.com/questions/113511", "https://Stackoverflow.com", "https://Stackoverflow.com/users/11193/" ]
How do we decide on the best implementation of `hashCode()` method for a collection (assuming that equals method has been overridden correctly) ?
The best implementation? That is a hard question because it depends on the usage pattern. A for nearly all cases reasonable good implementation was proposed in *Josh Bloch*'s ***Effective Java*** in Item 8 (second edition). The best thing is to look it up there because the author explains there why the approach is good. ### A short version 1. Create a `int result` and assign a **non-zero** value. 2. For *every field* `f` tested in the `equals()` method, calculate a hash code `c` by: * If the field f is a `boolean`: calculate `(f ? 0 : 1)`; * If the field f is a `byte`, `char`, `short` or `int`: calculate `(int)f`; * If the field f is a `long`: calculate `(int)(f ^ (f >>> 32))`; * If the field f is a `float`: calculate `Float.floatToIntBits(f)`; * If the field f is a `double`: calculate `Double.doubleToLongBits(f)` and handle the return value like every long value; * If the field f is an *object*: Use the result of the `hashCode()` method or 0 if `f == null`; * If the field f is an *array*: see every field as separate element and calculate the hash value in a *recursive fashion* and combine the values as described next. 3. Combine the hash value `c` with `result`: ``` result = 37 * result + c ``` 4. Return `result` This should result in a proper distribution of hash values for most use situations.
113,534
<p>Is there a function in Python to split a string without ignoring the spaces in the resulting list? </p> <p>E.g:</p> <pre><code>s="This is the string I want to split".split() </code></pre> <p>gives me</p> <pre><code>&gt;&gt;&gt; s ['This', 'is', 'the', 'string', 'I', 'want', 'to', 'split'] </code></pre> <p>I want something like</p> <pre><code>['This',' ','is',' ', 'the',' ','string', ' ', .....] </code></pre>
[ { "answer_id": 113554, "author": "rossp", "author_id": 612, "author_profile": "https://Stackoverflow.com/users/612", "pm_score": 1, "selected": false, "text": "<p>The hard part with what you're trying to do is that you aren't giving it a character to split on. split() explodes a string o...
2008/09/22
[ "https://Stackoverflow.com/questions/113534", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20211/" ]
Is there a function in Python to split a string without ignoring the spaces in the resulting list? E.g: ``` s="This is the string I want to split".split() ``` gives me ``` >>> s ['This', 'is', 'the', 'string', 'I', 'want', 'to', 'split'] ``` I want something like ``` ['This',' ','is',' ', 'the',' ','string', ' ', .....] ```
``` >>> import re >>> re.split(r"(\s+)", "This is the string I want to split") ['This', ' ', 'is', ' ', 'the', ' ', 'string', ' ', 'I', ' ', 'want', ' ', 'to', ' ', 'split'] ``` Using the capturing parentheses in re.split() causes the function to return the separators as well.
113,542
<p>Is there a simple way to hook into the standard '<strong>Add or Remove Programs</strong>' functionality using PowerShell to <strong>uninstall an existing application</strong>? Or to check if the application is installed?</p>
[ { "answer_id": 113584, "author": "Jeff Hillman", "author_id": 3950, "author_profile": "https://Stackoverflow.com/users/3950", "pm_score": 8, "selected": true, "text": "<pre class=\"lang-ps prettyprint-override\"><code>$app = Get-WmiObject -Class Win32_Product | Where-Object { \n $_.Na...
2008/09/22
[ "https://Stackoverflow.com/questions/113542", "https://Stackoverflow.com", "https://Stackoverflow.com/users/11571/" ]
Is there a simple way to hook into the standard '**Add or Remove Programs**' functionality using PowerShell to **uninstall an existing application**? Or to check if the application is installed?
```ps $app = Get-WmiObject -Class Win32_Product | Where-Object { $_.Name -match "Software Name" } $app.Uninstall() ``` **Edit:** Rob found another way to do it with the Filter parameter: ```ps $app = Get-WmiObject -Class Win32_Product ` -Filter "Name = 'Software Name'" ```
113,565
<p>I've seen the following code many times:</p> <pre><code>try { ... // some code } catch (Exception ex) { ... // Do something throw new CustomException(ex); // or // throw; // or // throw ex; } </code></pre> <p>Can you please explain the purpose of re-throwing an exception? Is it following a pattern/best practice in exception handling? (I've read somewhere that it's called "Caller Inform" pattern?)</p>
[ { "answer_id": 113568, "author": "johnc", "author_id": 5302, "author_profile": "https://Stackoverflow.com/users/5302", "pm_score": 0, "selected": false, "text": "<p>Until I started using the EntLib ExceptionBlock, I was using them to log errors before throwing them. Kind of nasty when yo...
2008/09/22
[ "https://Stackoverflow.com/questions/113565", "https://Stackoverflow.com", "https://Stackoverflow.com/users/14611/" ]
I've seen the following code many times: ``` try { ... // some code } catch (Exception ex) { ... // Do something throw new CustomException(ex); // or // throw; // or // throw ex; } ``` Can you please explain the purpose of re-throwing an exception? Is it following a pattern/best practice in exception handling? (I've read somewhere that it's called "Caller Inform" pattern?)
Rethrowing the same exception is useful if you want to, say, log the exception, but not handle it. Throwing a new exception that wraps the caught exception is good for abstraction. e.g., your library uses a third-party library that throws an exception that the clients of your library shouldn't know about. In that case, you wrap it into an exception type more native to your library, and throw that instead.
113,640
<p>I want to create a box like this with title:</p> <p><img src="https://i.stack.imgur.com/2rip1.gif" alt="CSS box with title"></p> <p>Can any one please let me know if there is a default CSS tag to do this? Or do I need to create my custom style?</p>
[ { "answer_id": 113656, "author": "Matthias Meid", "author_id": 17713, "author_profile": "https://Stackoverflow.com/users/17713", "pm_score": 2, "selected": false, "text": "<p>As far as I know (correct me if I'm wrong!), there isn't.</p>\n\n<p>I'd recommend you to use a div with a negativ...
2008/09/22
[ "https://Stackoverflow.com/questions/113640", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20165/" ]
I want to create a box like this with title: ![CSS box with title](https://i.stack.imgur.com/2rip1.gif) Can any one please let me know if there is a default CSS tag to do this? Or do I need to create my custom style?
I believe you are looking for the `fieldset` HTML tag, which you can then style with CSS. E.g., ```html <fieldset style="border: 1px black solid"> <legend style="border: 1px black solid;margin-left: 1em; padding: 0.2em 0.8em ">title</legend> Text within the box <br /> Etc </fieldset> ```
113,655
<p>Is there a function in python to split a word into a list of single letters? e.g:</p> <pre><code>s = &quot;Word to Split&quot; </code></pre> <p>to get</p> <pre><code>wordlist = ['W', 'o', 'r', 'd', ' ', 't', 'o', ' ', 'S', 'p', 'l', 'i', 't'] </code></pre>
[ { "answer_id": 113662, "author": "Greg Hewgill", "author_id": 893, "author_profile": "https://Stackoverflow.com/users/893", "pm_score": 9, "selected": true, "text": "<pre><code>&gt;&gt;&gt; list(\"Word to Split\")\n['W', 'o', 'r', 'd', ' ', 't', 'o', ' ', 'S', 'p', 'l', 'i', 't']\n</code...
2008/09/22
[ "https://Stackoverflow.com/questions/113655", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20211/" ]
Is there a function in python to split a word into a list of single letters? e.g: ``` s = "Word to Split" ``` to get ``` wordlist = ['W', 'o', 'r', 'd', ' ', 't', 'o', ' ', 'S', 'p', 'l', 'i', 't'] ```
``` >>> list("Word to Split") ['W', 'o', 'r', 'd', ' ', 't', 'o', ' ', 'S', 'p', 'l', 'i', 't'] ```
113,664
<p>I want to install PowerShell to 600 Window XP computers, and use it as the main processing shell. For example, for replacing batch scripts, VB scripts, and some other little programs. The installation process is not a problem. Some issues I think I'm going to come across are:</p> <ol> <li><p>Changing permissions to allow PowerShell to run scripts</p> </li> <li><p>The speed of PowerShell starting</p> </li> <li><p>Using PowerShell for logon/logoff scripts with GPO</p> </li> </ol> <p>Problem 2: There is a script that is supposed to speed up PowerShell, but it seems to need to be run as administrator (which of course isn't something that normal users do). Has anyone had any experience with using PowerShell in this way?</p>
[ { "answer_id": 114634, "author": "Tubs", "author_id": 11924, "author_profile": "https://Stackoverflow.com/users/11924", "pm_score": 0, "selected": false, "text": "<p>Changing permissions to allow Powershell scripts is possible to do via group policy. </p>\n\n<p>Microsoft provide ADM tem...
2008/09/22
[ "https://Stackoverflow.com/questions/113664", "https://Stackoverflow.com", "https://Stackoverflow.com/users/11924/" ]
I want to install PowerShell to 600 Window XP computers, and use it as the main processing shell. For example, for replacing batch scripts, VB scripts, and some other little programs. The installation process is not a problem. Some issues I think I'm going to come across are: 1. Changing permissions to allow PowerShell to run scripts 2. The speed of PowerShell starting 3. Using PowerShell for logon/logoff scripts with GPO Problem 2: There is a script that is supposed to speed up PowerShell, but it seems to need to be run as administrator (which of course isn't something that normal users do). Has anyone had any experience with using PowerShell in this way?
To speed up the start of PowerShell, Jeffrey Snover (the partner/architect responsible for PowerShell) provides an "Update-GAC" script [here](http://blogs.msdn.com/powershell/archive/2008/09/02/speeding-up-powershell-startup-updating-update-gac-ps1.aspx). Basically, it is just running through the assemblies that are loaded for PowerShell and NGen'ing (pre-compiling the IL to machine code) them. This does speed up the start of PowerShell. Another trick is to run PowerShell with the -nologo and -noprofile switches. This will skip the profile scripts and splash logo. There is a [product for using PowerShell for logon/logoff scripts](http://www.specopssoft.com/powershell/) from Special Operations Software. There are other ways to do it also. ``` %windir%\system32\WindowsPowerShell\v1.0\powershell.exe -nologo -noprofile ```
113,702
<p>How do I add a "last" class on the last <code>&lt;li&gt;</code> within a Views-generated list?</p>
[ { "answer_id": 113740, "author": "Tim C", "author_id": 7585, "author_profile": "https://Stackoverflow.com/users/7585", "pm_score": 4, "selected": true, "text": "<p>You could use the <strong>last-child</strong> pseudo-class on the li element to achieve this</p>\n\n<pre><code>&lt;html&gt;\...
2008/09/22
[ "https://Stackoverflow.com/questions/113702", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20273/" ]
How do I add a "last" class on the last `<li>` within a Views-generated list?
You could use the **last-child** pseudo-class on the li element to achieve this ``` <html> <head> <style type="text/css"> ul li:last-child { font-weight:bold } </style> </head> <body> <ul> <li>IE</li> <li>Firefox</li> <li>Safari</li> </ul> </body> </html> ``` There is also a first-child pseudo class available. I am not sure the last-child element works in IE though.
113,712
<p>Is there a way to combine a previous translation when extracting the csv file from an application? Or any other tool that could do this job for me? </p> <p>I can’t really see how could i use locbaml if i had to translate everything from scratch every time i add a new control in my application.</p>
[ { "answer_id": 113740, "author": "Tim C", "author_id": 7585, "author_profile": "https://Stackoverflow.com/users/7585", "pm_score": 4, "selected": true, "text": "<p>You could use the <strong>last-child</strong> pseudo-class on the li element to achieve this</p>\n\n<pre><code>&lt;html&gt;\...
2008/09/22
[ "https://Stackoverflow.com/questions/113712", "https://Stackoverflow.com", "https://Stackoverflow.com/users/15228/" ]
Is there a way to combine a previous translation when extracting the csv file from an application? Or any other tool that could do this job for me? I can’t really see how could i use locbaml if i had to translate everything from scratch every time i add a new control in my application.
You could use the **last-child** pseudo-class on the li element to achieve this ``` <html> <head> <style type="text/css"> ul li:last-child { font-weight:bold } </style> </head> <body> <ul> <li>IE</li> <li>Firefox</li> <li>Safari</li> </ul> </body> </html> ``` There is also a first-child pseudo class available. I am not sure the last-child element works in IE though.
113,728
<p>Basically I am trying to restart a service from a php web page.</p> <p>Here is the code:</p> <pre><code>&lt;?php exec ('/usr/bin/sudo /etc/init.d/portmap restart'); ?&gt; </code></pre> <p>But, in <code>/var/log/httpd/error_log</code>, I get </p> <blockquote> <p>unable to change to sudoers gid: Operation not permitted</p> </blockquote> <p>and in /var/log/messages, I get</p> <blockquote> <p>Sep 22 15:01:56 ri kernel: audit(1222063316.536:777): avc: denied { getattr } for pid=4851 comm="sh" name="var" dev=dm-0 ino=114241 scontext=root:system_r:httpd_sys_script_t tcontext=system_u:object_r:var_t tclass=dir<br> Sep 22 15:01:56 ri kernel: audit(1222063316.549:778): avc: denied { setrlimit } for pid=4851 comm="sudo" scontext=root:system_r:httpd_sys_script_t tcontext=root:system_r:httpd_sys_script_t tclass=process<br> Sep 22 15:01:56 ri kernel: audit(1222063316.565:779): avc: denied { read } for pid=4851 comm="sudo" name="shadow" dev=dm-0 ino=379669 scontext=root:system_r:httpd_sys_script_t tcontext=system_u:object_r:shadow_t tclass=file<br> Sep 22 15:01:56 ri kernel: audit(1222063316.568:780): avc: denied { read } for pid=4851 comm="sudo" name="shadow" dev=dm-0 ino=379669 scontext=root:system_r:httpd_sys_script_t tcontext=system_u:object_r:shadow_t tclass=file<br> Sep 22 15:01:56 ri kernel: audit(1222063316.571:781): avc: denied { setgid } for pid=4851 comm="sudo" capability=6 scontext=root:system_r:httpd_sys_script_t tcontext=root:system_r:httpd_sys_script_t tclass=capability<br> Sep 22 15:01:56 ri kernel: audit(1222063316.574:782): avc: denied { setuid } for pid=4851 comm="sudo" capability=7 scontext=root:system_r:httpd_sys_script_t tcontext=root:system_r:httpd_sys_script_t tclass=capability<br> Sep 22 15:01:56 ri kernel: audit(1222063316.577:783): avc: denied { setgid } for pid=4851 comm="sudo" capability=6 scontext=root:system_r:httpd_sys_script_t tcontext=root:system_r:httpd_sys_script_t tclass=capability</p> </blockquote> <p>In my visudo, I added those lines</p> <blockquote> <p>User_Alias WWW=apache </p> <p>WWW ALL=(ALL) NOPASSWD:ALL</p> </blockquote> <p>Can you please help me ? Am I doing something wrong ?</p> <p>Thanks for your help,</p> <p>tiBoun</p>
[ { "answer_id": 113764, "author": "Zoredache", "author_id": 20267, "author_profile": "https://Stackoverflow.com/users/20267", "pm_score": 3, "selected": false, "text": "<p>The error you are getting seems to be related to your SELinux configuration. You might try temporarily disabling tha...
2008/09/22
[ "https://Stackoverflow.com/questions/113728", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
Basically I am trying to restart a service from a php web page. Here is the code: ``` <?php exec ('/usr/bin/sudo /etc/init.d/portmap restart'); ?> ``` But, in `/var/log/httpd/error_log`, I get > > unable to change to sudoers gid: Operation not permitted > > > and in /var/log/messages, I get > > Sep 22 15:01:56 ri kernel: audit(1222063316.536:777): avc: denied { getattr } for pid=4851 comm="sh" name="var" dev=dm-0 ino=114241 scontext=root:system\_r:httpd\_sys\_script\_t tcontext=system\_u:object\_r:var\_t tclass=dir > > Sep 22 15:01:56 ri kernel: audit(1222063316.549:778): avc: denied { setrlimit } for pid=4851 comm="sudo" scontext=root:system\_r:httpd\_sys\_script\_t tcontext=root:system\_r:httpd\_sys\_script\_t tclass=process > > Sep 22 15:01:56 ri kernel: audit(1222063316.565:779): avc: denied { read } for pid=4851 comm="sudo" name="shadow" dev=dm-0 ino=379669 scontext=root:system\_r:httpd\_sys\_script\_t tcontext=system\_u:object\_r:shadow\_t tclass=file > > Sep 22 15:01:56 ri kernel: audit(1222063316.568:780): avc: denied { read } for pid=4851 comm="sudo" name="shadow" dev=dm-0 ino=379669 scontext=root:system\_r:httpd\_sys\_script\_t tcontext=system\_u:object\_r:shadow\_t tclass=file > > Sep 22 15:01:56 ri kernel: audit(1222063316.571:781): avc: denied { setgid } for pid=4851 comm="sudo" capability=6 scontext=root:system\_r:httpd\_sys\_script\_t tcontext=root:system\_r:httpd\_sys\_script\_t tclass=capability > > Sep 22 15:01:56 ri kernel: audit(1222063316.574:782): avc: denied { setuid } for pid=4851 comm="sudo" capability=7 scontext=root:system\_r:httpd\_sys\_script\_t tcontext=root:system\_r:httpd\_sys\_script\_t tclass=capability > > Sep 22 15:01:56 ri kernel: audit(1222063316.577:783): avc: denied { setgid } for pid=4851 comm="sudo" capability=6 scontext=root:system\_r:httpd\_sys\_script\_t tcontext=root:system\_r:httpd\_sys\_script\_t tclass=capability > > > In my visudo, I added those lines > > User\_Alias WWW=apache > > > WWW ALL=(ALL) NOPASSWD:ALL > > > Can you please help me ? Am I doing something wrong ? Thanks for your help, tiBoun
The problem is not with sudo at the moment, but with [SELinux](http://en.wikipedia.org/wiki/Selinux), which is (reasonably) set to deny the HTTPD from gaining root privileges. You will need to either explicitly allow this (you can use [audit2allow](http://fedoraproject.org/wiki/SELinux/audit2allow) for this), or set SELinux to be permissive instead. I'd suggest the former.
113,731
<p>We have CC.NET setup on our ASP.NET app. When we build the project, the ASP.NET app is pre-compiled and copied to a network share, from which a server runs the application.</p> <p>The server is a bit different from development box'es, and the next server in our staging environment differs even more. The difference is specific config files and so on - so I want to exclude some files - or delete them before the pre-compiled app is copied to a network share.</p> <p>My config file looks like this:</p> <pre><code> &lt;project name="Assembly.Web.project"&gt; &lt;triggers&gt; &lt;intervalTrigger seconds="3600" /&gt; &lt;/triggers&gt; &lt;sourcecontrol type="svn"&gt; &lt;trunkUrl&gt;svn://svn-server/MyApp/Web/Trunk&lt;/trunkUrl&gt; &lt;workingDirectory&gt;C:\build-server\Assembly\Web\TEST-HL&lt;/workingDirectory&gt; &lt;executable&gt;C:\Program Files (x86)\SVN 1.5 bin\svn.exe&lt;/executable&gt; &lt;username&gt;uid&lt;/username&gt; &lt;password&gt;pwd&lt;/password&gt; &lt;/sourcecontrol&gt; &lt;tasks&gt; &lt;msbuild&gt; &lt;executable&gt;C:\Windows\Microsoft.NET\Framework64\v3.5\MSBuild.exe&lt;/executable&gt; &lt;workingDirectory&gt;C:\build-server\Assembly\Web\TEST-HL&lt;/workingDirectory&gt; &lt;projectFile&gt;C:\build-server\Assembly\Web\TEST-HL\Web\Web.sln&lt;/projectFile&gt; &lt;buildArgs&gt;/noconsolelogger /p:Configuration=Debug /v:diag&lt;/buildArgs&gt; &lt;targets&gt;Build&lt;/targets&gt; &lt;timeout&gt;900&lt;/timeout&gt; &lt;logger&gt;C:\Program Files\CruiseControl.NET\server\ThoughtWorks.CruiseControl.MsBuild.dll&lt;/logger&gt; &lt;/msbuild&gt; &lt;/tasks&gt; &lt;publishers&gt; &lt;buildpublisher&gt; &lt;sourceDir&gt;C:\build-server\Assembly\Web\PrecompiledWeb&lt;/sourceDir&gt; &lt;publishDir&gt;\\test-web01\Web&lt;/publishDir&gt; &lt;useLabelSubDirectory&gt;false&lt;/useLabelSubDirectory&gt; &lt;alwaysPublish&gt;false&lt;/alwaysPublish&gt; &lt;/buildpublisher&gt; &lt;/publishers&gt; &lt;/project&gt; </code></pre> <p>As you can see, I use a buildPublisher to copy the pre-compiled files to the network share. What I want to do here, is either 1) delete certain files before they are copied or 2) replace those files after they have been copied.</p> <p>I DO NOT want to have some app running watching specific files for change, and then after that replace the files with other ones. I want something to be either done by CC.NET, or triggered by CC.NET.</p> <p>Can you launch a .bat file with CC.NET?</p>
[ { "answer_id": 113743, "author": "Sklivvz", "author_id": 7028, "author_profile": "https://Stackoverflow.com/users/7028", "pm_score": 2, "selected": false, "text": "<p>I use a <a href=\"http://nant.sourceforge.net/\" rel=\"nofollow noreferrer\">NAnt</a> <a href=\"http://www.cruisecontroln...
2008/09/22
[ "https://Stackoverflow.com/questions/113731", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2972/" ]
We have CC.NET setup on our ASP.NET app. When we build the project, the ASP.NET app is pre-compiled and copied to a network share, from which a server runs the application. The server is a bit different from development box'es, and the next server in our staging environment differs even more. The difference is specific config files and so on - so I want to exclude some files - or delete them before the pre-compiled app is copied to a network share. My config file looks like this: ``` <project name="Assembly.Web.project"> <triggers> <intervalTrigger seconds="3600" /> </triggers> <sourcecontrol type="svn"> <trunkUrl>svn://svn-server/MyApp/Web/Trunk</trunkUrl> <workingDirectory>C:\build-server\Assembly\Web\TEST-HL</workingDirectory> <executable>C:\Program Files (x86)\SVN 1.5 bin\svn.exe</executable> <username>uid</username> <password>pwd</password> </sourcecontrol> <tasks> <msbuild> <executable>C:\Windows\Microsoft.NET\Framework64\v3.5\MSBuild.exe</executable> <workingDirectory>C:\build-server\Assembly\Web\TEST-HL</workingDirectory> <projectFile>C:\build-server\Assembly\Web\TEST-HL\Web\Web.sln</projectFile> <buildArgs>/noconsolelogger /p:Configuration=Debug /v:diag</buildArgs> <targets>Build</targets> <timeout>900</timeout> <logger>C:\Program Files\CruiseControl.NET\server\ThoughtWorks.CruiseControl.MsBuild.dll</logger> </msbuild> </tasks> <publishers> <buildpublisher> <sourceDir>C:\build-server\Assembly\Web\PrecompiledWeb</sourceDir> <publishDir>\\test-web01\Web</publishDir> <useLabelSubDirectory>false</useLabelSubDirectory> <alwaysPublish>false</alwaysPublish> </buildpublisher> </publishers> </project> ``` As you can see, I use a buildPublisher to copy the pre-compiled files to the network share. What I want to do here, is either 1) delete certain files before they are copied or 2) replace those files after they have been copied. I DO NOT want to have some app running watching specific files for change, and then after that replace the files with other ones. I want something to be either done by CC.NET, or triggered by CC.NET. Can you launch a .bat file with CC.NET?
You have to use [NAnt](http://nant.sourceforge.net/) for those kind of stuff. Here is the [Task Reference of Nant](http://nant.sourceforge.net/release/latest/help/tasks/)..
113,737
<p>How do I use PowerShell to stop and start a "Generic Service" as seen in the Microsoft "Cluster Administrator" software?</p>
[ { "answer_id": 113797, "author": "Rob Paterson", "author_id": 11571, "author_profile": "https://Stackoverflow.com/users/11571", "pm_score": 2, "selected": false, "text": "<p>It turns out the answer is to simply use the command line tool CLUSTER.EXE to do this:</p>\n\n<p>cluster RES MyGen...
2008/09/22
[ "https://Stackoverflow.com/questions/113737", "https://Stackoverflow.com", "https://Stackoverflow.com/users/11571/" ]
How do I use PowerShell to stop and start a "Generic Service" as seen in the Microsoft "Cluster Administrator" software?
You can also use WMI. You can get all the Generic Services with: ``` $services = Get-WmiObject -Computer "Computer" -namespace 'root\mscluster' ` MSCluster_Resource | Where {$_.Type -eq "Generic Service"} ``` To stop and start a service: ``` $timeout = 15 $services[0].TakeOffline($timeout) $services[0].BringOnline($timeout) ```
113,750
<p>I'm trying to implement a pop-up menu based on a click-and-hold, positioned so that a (really) slow click will still trigger the default action, and with the delay set so that a text-selection gesture won't usually trigger the menu. </p> <p>What I can't seem to do is cancel the text-selection in a way that doesn't prevent text-selection in the first place: returning false from the event handler (or calling <code>$(this).preventDefault()</code>) prevents the user from selecting at all, and the obvious <code>$().trigger('mouseup')</code> doesn't doesn't do anything with the selection at all.</p> <ul> <li>This is in the general context of a page, not particular to a textarea or other text field.</li> <li><code>e.stopPropogation()</code> doesn't cancel text-selection.</li> <li>I'm not looking to <em>prevent</em> text selections, but rather to <em>veto</em> them after some short period of time, if certain conditions are met.</li> </ul>
[ { "answer_id": 113771, "author": "Craig Francis", "author_id": 6632, "author_profile": "https://Stackoverflow.com/users/6632", "pm_score": 3, "selected": false, "text": "<p>Try this:</p>\n\n<pre><code>var input = document.getElementById('myInputField');\nif (input) {\n input.onmousedo...
2008/09/22
[ "https://Stackoverflow.com/questions/113750", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
I'm trying to implement a pop-up menu based on a click-and-hold, positioned so that a (really) slow click will still trigger the default action, and with the delay set so that a text-selection gesture won't usually trigger the menu. What I can't seem to do is cancel the text-selection in a way that doesn't prevent text-selection in the first place: returning false from the event handler (or calling `$(this).preventDefault()`) prevents the user from selecting at all, and the obvious `$().trigger('mouseup')` doesn't doesn't do anything with the selection at all. * This is in the general context of a page, not particular to a textarea or other text field. * `e.stopPropogation()` doesn't cancel text-selection. * I'm not looking to *prevent* text selections, but rather to *veto* them after some short period of time, if certain conditions are met.
Try this: ``` var input = document.getElementById('myInputField'); if (input) { input.onmousedown = function(e) { if (!e) e = window.event; e.cancelBubble = true; if (e.stopPropagation) e.stopPropagation(); } } ``` And if not, have a read of: <http://www.quirksmode.org/js/introevents.html>
113,755
<p>I have an application that is installed and updated via ClickOnce. The application downloads files via FTP, and therefore needs to be added as an exception to the windows firewall. Because of the way that ClickOnce works, the path to the EXE changes with every update, so the exception needs to change also. What would be the best way to have the changes made to the firewall so that it's <em>invisible</em> to the end user?</p> <p>(The application is written in C#)</p>
[ { "answer_id": 113781, "author": "Michael Stum", "author_id": 91, "author_profile": "https://Stackoverflow.com/users/91", "pm_score": 4, "selected": false, "text": "<p>Not sure if this is the best way, but running <a href=\"https://learn.microsoft.com/en-us/previous-versions/windows/it-p...
2008/09/22
[ "https://Stackoverflow.com/questions/113755", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6389/" ]
I have an application that is installed and updated via ClickOnce. The application downloads files via FTP, and therefore needs to be added as an exception to the windows firewall. Because of the way that ClickOnce works, the path to the EXE changes with every update, so the exception needs to change also. What would be the best way to have the changes made to the firewall so that it's *invisible* to the end user? (The application is written in C#)
I found this article, which has a complete wrapper class included for manipulating the windows firewall. [Adding an Application to the Exception list on the Windows Firewall](http://web.archive.org/web/20070707110141/http://www.dot.net.nz/Default.aspx?tabid=42&mid=404&ctl=Details&ItemID=8) ```cs /// /// Allows basic access to the windows firewall API. /// This can be used to add an exception to the windows firewall /// exceptions list, so that our programs can continue to run merrily /// even when nasty windows firewall is running. /// /// Please note: It is not enforced here, but it might be a good idea /// to actually prompt the user before messing with their firewall settings, /// just as a matter of politeness. /// /// /// To allow the installers to authorize idiom products to work through /// the Windows Firewall. /// public class FirewallHelper { #region Variables /// /// Hooray! Singleton access. /// private static FirewallHelper instance = null; /// /// Interface to the firewall manager COM object /// private INetFwMgr fwMgr = null; #endregion #region Properties /// /// Singleton access to the firewallhelper object. /// Threadsafe. /// public static FirewallHelper Instance { get { lock (typeof(FirewallHelper)) { if (instance == null) instance = new FirewallHelper(); return instance; } } } #endregion #region Constructivat0r /// /// Private Constructor. If this fails, HasFirewall will return /// false; /// private FirewallHelper() { // Get the type of HNetCfg.FwMgr, or null if an error occurred Type fwMgrType = Type.GetTypeFromProgID("HNetCfg.FwMgr", false); // Assume failed. fwMgr = null; if (fwMgrType != null) { try { fwMgr = (INetFwMgr)Activator.CreateInstance(fwMgrType); } // In all other circumnstances, fwMgr is null. catch (ArgumentException) { } catch (NotSupportedException) { } catch (System.Reflection.TargetInvocationException) { } catch (MissingMethodException) { } catch (MethodAccessException) { } catch (MemberAccessException) { } catch (InvalidComObjectException) { } catch (COMException) { } catch (TypeLoadException) { } } } #endregion #region Helper Methods /// /// Gets whether or not the firewall is installed on this computer. /// /// public bool IsFirewallInstalled { get { if (fwMgr != null && fwMgr.LocalPolicy != null && fwMgr.LocalPolicy.CurrentProfile != null) return true; else return false; } } /// /// Returns whether or not the firewall is enabled. /// If the firewall is not installed, this returns false. /// public bool IsFirewallEnabled { get { if (IsFirewallInstalled && fwMgr.LocalPolicy.CurrentProfile.FirewallEnabled) return true; else return false; } } /// /// Returns whether or not the firewall allows Application "Exceptions". /// If the firewall is not installed, this returns false. /// /// /// Added to allow access to this metho /// public bool AppAuthorizationsAllowed { get { if (IsFirewallInstalled && !fwMgr.LocalPolicy.CurrentProfile.ExceptionsNotAllowed) return true; else return false; } } /// /// Adds an application to the list of authorized applications. /// If the application is already authorized, does nothing. /// /// /// The full path to the application executable. This cannot /// be blank, and cannot be a relative path. /// /// /// This is the name of the application, purely for display /// puposes in the Microsoft Security Center. /// /// /// When applicationFullPath is null OR /// When appName is null. /// /// /// When applicationFullPath is blank OR /// When appName is blank OR /// applicationFullPath contains invalid path characters OR /// applicationFullPath is not an absolute path /// /// /// If the firewall is not installed OR /// If the firewall does not allow specific application 'exceptions' OR /// Due to an exception in COM this method could not create the /// necessary COM types /// /// /// If no file exists at the given applicationFullPath /// public void GrantAuthorization(string applicationFullPath, string appName) { #region Parameter checking if (applicationFullPath == null) throw new ArgumentNullException("applicationFullPath"); if (appName == null) throw new ArgumentNullException("appName"); if (applicationFullPath.Trim().Length == 0) throw new ArgumentException("applicationFullPath must not be blank"); if (applicationFullPath.Trim().Length == 0) throw new ArgumentException("appName must not be blank"); if (applicationFullPath.IndexOfAny(Path.InvalidPathChars) >= 0) throw new ArgumentException("applicationFullPath must not contain invalid path characters"); if (!Path.IsPathRooted(applicationFullPath)) throw new ArgumentException("applicationFullPath is not an absolute path"); if (!File.Exists(applicationFullPath)) throw new FileNotFoundException("File does not exist", applicationFullPath); // State checking if (!IsFirewallInstalled) throw new FirewallHelperException("Cannot grant authorization: Firewall is not installed."); if (!AppAuthorizationsAllowed) throw new FirewallHelperException("Application exemptions are not allowed."); #endregion if (!HasAuthorization(applicationFullPath)) { // Get the type of HNetCfg.FwMgr, or null if an error occurred Type authAppType = Type.GetTypeFromProgID("HNetCfg.FwAuthorizedApplication", false); // Assume failed. INetFwAuthorizedApplication appInfo = null; if (authAppType != null) { try { appInfo = (INetFwAuthorizedApplication)Activator.CreateInstance(authAppType); } // In all other circumnstances, appInfo is null. catch (ArgumentException) { } catch (NotSupportedException) { } catch (System.Reflection.TargetInvocationException) { } catch (MissingMethodException) { } catch (MethodAccessException) { } catch (MemberAccessException) { } catch (InvalidComObjectException) { } catch (COMException) { } catch (TypeLoadException) { } } if (appInfo == null) throw new FirewallHelperException("Could not grant authorization: can't create INetFwAuthorizedApplication instance."); appInfo.Name = appName; appInfo.ProcessImageFileName = applicationFullPath; // ... // Use defaults for other properties of the AuthorizedApplication COM object // Authorize this application fwMgr.LocalPolicy.CurrentProfile.AuthorizedApplications.Add(appInfo); } // otherwise it already has authorization so do nothing } /// /// Removes an application to the list of authorized applications. /// Note that the specified application must exist or a FileNotFound /// exception will be thrown. /// If the specified application exists but does not current have /// authorization, this method will do nothing. /// /// /// The full path to the application executable. This cannot /// be blank, and cannot be a relative path. /// /// /// When applicationFullPath is null /// /// /// When applicationFullPath is blank OR /// applicationFullPath contains invalid path characters OR /// applicationFullPath is not an absolute path /// /// /// If the firewall is not installed. /// /// /// If the specified application does not exist. /// public void RemoveAuthorization(string applicationFullPath) { #region Parameter checking if (applicationFullPath == null) throw new ArgumentNullException("applicationFullPath"); if (applicationFullPath.Trim().Length == 0) throw new ArgumentException("applicationFullPath must not be blank"); if (applicationFullPath.IndexOfAny(Path.InvalidPathChars) >= 0) throw new ArgumentException("applicationFullPath must not contain invalid path characters"); if (!Path.IsPathRooted(applicationFullPath)) throw new ArgumentException("applicationFullPath is not an absolute path"); if (!File.Exists(applicationFullPath)) throw new FileNotFoundException("File does not exist", applicationFullPath); // State checking if (!IsFirewallInstalled) throw new FirewallHelperException("Cannot remove authorization: Firewall is not installed."); #endregion if (HasAuthorization(applicationFullPath)) { // Remove Authorization for this application fwMgr.LocalPolicy.CurrentProfile.AuthorizedApplications.Remove(applicationFullPath); } // otherwise it does not have authorization so do nothing } /// /// Returns whether an application is in the list of authorized applications. /// Note if the file does not exist, this throws a FileNotFound exception. /// /// /// The full path to the application executable. This cannot /// be blank, and cannot be a relative path. /// /// /// The full path to the application executable. This cannot /// be blank, and cannot be a relative path. /// /// /// When applicationFullPath is null /// /// /// When applicationFullPath is blank OR /// applicationFullPath contains invalid path characters OR /// applicationFullPath is not an absolute path /// /// /// If the firewall is not installed. /// /// /// If the specified application does not exist. /// public bool HasAuthorization(string applicationFullPath) { #region Parameter checking if (applicationFullPath == null) throw new ArgumentNullException("applicationFullPath"); if (applicationFullPath.Trim().Length == 0) throw new ArgumentException("applicationFullPath must not be blank"); if (applicationFullPath.IndexOfAny(Path.InvalidPathChars) >= 0) throw new ArgumentException("applicationFullPath must not contain invalid path characters"); if (!Path.IsPathRooted(applicationFullPath)) throw new ArgumentException("applicationFullPath is not an absolute path"); if (!File.Exists(applicationFullPath)) throw new FileNotFoundException("File does not exist.", applicationFullPath); // State checking if (!IsFirewallInstalled) throw new FirewallHelperException("Cannot remove authorization: Firewall is not installed."); #endregion // Locate Authorization for this application foreach (string appName in GetAuthorizedAppPaths()) { // Paths on windows file systems are not case sensitive. if (appName.ToLower() == applicationFullPath.ToLower()) return true; } // Failed to locate the given app. return false; } /// /// Retrieves a collection of paths to applications that are authorized. /// /// /// /// If the Firewall is not installed. /// public ICollection GetAuthorizedAppPaths() { // State checking if (!IsFirewallInstalled) throw new FirewallHelperException("Cannot remove authorization: Firewall is not installed."); ArrayList list = new ArrayList(); // Collect the paths of all authorized applications foreach (INetFwAuthorizedApplication app in fwMgr.LocalPolicy.CurrentProfile.AuthorizedApplications) list.Add(app.ProcessImageFileName); return list; } #endregion } /// /// Describes a FirewallHelperException. /// /// /// /// public class FirewallHelperException : System.Exception { /// /// Construct a new FirewallHelperException /// /// public FirewallHelperException(string message) : base(message) { } } ``` The ClickOnce sandbox did not present any problems.
113,780
<p>I don’t think I’ve grokked currying yet. I understand what it does, and how to do it. I just can’t think of a situation I would use it.</p> <p>Where are you using currying in JavaScript (or where are the main libraries using it)? DOM manipulation or general application development examples welcome.</p> <p><a href="https://stackoverflow.com/questions/113780/javascript-curry-what-are-the-practical-applications#113799">One of the answers</a> mentions animation. Functions like <code>slideUp</code>, <code>fadeIn</code> take an element as an arguments and are normally a curried function returning the high order function with the default “animation function” built-in. Why is that better than just applying the higher-up function with some defaults?</p> <p>Are there any drawbacks to using it?</p> <p>As requested here are some good resources on JavaScript currying:</p> <ul> <li><a href="http://www.dustindiaz.com/javascript-curry/" rel="noreferrer">http://www.dustindiaz.com/javascript-curry/</a></li> <li>Crockford, Douglas (2008) <em>JavaScript: The Good Parts</em></li> <li><a href="http://www.crockford.com/javascript/www_svendtofte_com/code/curried_javascript/index.html" rel="noreferrer">http://www.svendtofte.com/code/curried_javascript/</a> (Takes a detour into ML so skip the whole section from “A crash course in ML” and start again at “How to write curried JavaScript”)</li> <li><a href="http://web.archive.org/web/20111217011630/http://blog.morrisjohns.com:80/javascript_closures_for_dummies" rel="noreferrer">http://web.archive.org/web/20111217011630/http://blog.morrisjohns.com:80/javascript_closures_for_dummies</a></li> <li><a href="https://stackoverflow.com/questions/111102/how-does-a-javascript-closure-work">How do JavaScript closures work?</a></li> <li><strong><a href="http://ejohn.org/blog/partial-functions-in-javascript/" rel="noreferrer">http://ejohn.org/blog/partial-functions-in-javascript</a> (Mr. Resig on the money as per usual)</strong></li> <li><a href="http://benalman.com/news/2010/09/partial-application-in-javascript/" rel="noreferrer">http://benalman.com/news/2010/09/partial-application-in-javascript/</a></li> </ul> <p>I’ll add more as they crop up in the comments.</p> <hr> <p>So, according to the answers, currying and partial application in general are convenience techniques.</p> <p>If you are frequently “refining” a high-level function by calling it with same configuration, you can curry (or use Resig’s partial) the higher-level function to create simple, concise helper methods.</p>
[ { "answer_id": 113790, "author": "Hank Gay", "author_id": 4203, "author_profile": "https://Stackoverflow.com/users/4203", "pm_score": 1, "selected": false, "text": "<p>As for libraries using it, there's always <a href=\"http://osteele.com/sources/javascript/functional/\" rel=\"nofollow n...
2008/09/22
[ "https://Stackoverflow.com/questions/113780", "https://Stackoverflow.com", "https://Stackoverflow.com/users/9474/" ]
I don’t think I’ve grokked currying yet. I understand what it does, and how to do it. I just can’t think of a situation I would use it. Where are you using currying in JavaScript (or where are the main libraries using it)? DOM manipulation or general application development examples welcome. [One of the answers](https://stackoverflow.com/questions/113780/javascript-curry-what-are-the-practical-applications#113799) mentions animation. Functions like `slideUp`, `fadeIn` take an element as an arguments and are normally a curried function returning the high order function with the default “animation function” built-in. Why is that better than just applying the higher-up function with some defaults? Are there any drawbacks to using it? As requested here are some good resources on JavaScript currying: * <http://www.dustindiaz.com/javascript-curry/> * Crockford, Douglas (2008) *JavaScript: The Good Parts* * [http://www.svendtofte.com/code/curried\_javascript/](http://www.crockford.com/javascript/www_svendtofte_com/code/curried_javascript/index.html) (Takes a detour into ML so skip the whole section from “A crash course in ML” and start again at “How to write curried JavaScript”) * <http://web.archive.org/web/20111217011630/http://blog.morrisjohns.com:80/javascript_closures_for_dummies> * [How do JavaScript closures work?](https://stackoverflow.com/questions/111102/how-does-a-javascript-closure-work) * **[http://ejohn.org/blog/partial-functions-in-javascript](http://ejohn.org/blog/partial-functions-in-javascript/) (Mr. Resig on the money as per usual)** * <http://benalman.com/news/2010/09/partial-application-in-javascript/> I’ll add more as they crop up in the comments. --- So, according to the answers, currying and partial application in general are convenience techniques. If you are frequently “refining” a high-level function by calling it with same configuration, you can curry (or use Resig’s partial) the higher-level function to create simple, concise helper methods.
@Hank Gay In response to EmbiggensTheMind's comment: I can't think of an instance where [currying](http://en.wikipedia.org/wiki/Currying)—by itself—is useful in JavaScript; it is a technique for converting function calls with multiple arguments into chains of function calls with a single argument for each call, but JavaScript supports multiple arguments in a single function call. In JavaScript—and I assume most other actual languages (not lambda calculus)—it is commonly associated with partial application, though. John Resig [explains it better](http://ejohn.org/blog/partial-functions-in-javascript/#postcomment), but the gist is that have some logic that will be applied to two or more arguments, and you only know the value(s) for some of those arguments. You can use partial application/currying to fix those known values and return a function that only accepts the unknowns, to be invoked later when you actually have the values you wish to pass. This provides a nifty way to avoid repeating yourself when you would have been calling the same JavaScript built-ins over and over with all the same values but one. To steal John's example: ``` String.prototype.csv = String.prototype.split.partial(/,\s*/); var results = "John, Resig, Boston".csv(); alert( (results[1] == "Resig") + " The text values were split properly" ); ```
113,803
<p>If I have a table in MySQL which represents a base class, and I have a bunch of tables which represent the fields in the derived classes, each of which refers back to the base table with a foreign key, is there any way to get MySQL to enforce the one-to-one relationship between the derived table and the base table, or does this have to be done in code?</p> <p>Using the following quick 'n' dirty schema as an example, is there any way to get MySQL to ensure that rows in both product_cd and product_dvd cannot share the same product_id? Is there a better way to design the schema to allow the database to enforce this relationship, or is it simply not possible?</p> <pre><code>CREATE TABLE IF NOT EXISTS `product` ( `product_id` int(10) unsigned NOT NULL auto_increment, `product_name` varchar(50) NOT NULL, `description` text NOT NULL, PRIMARY KEY (`product_id`) ) ENGINE = InnoDB; CREATE TABLE `product_cd` ( `product_cd_id` INT UNSIGNED NOT NULL AUTO_INCREMENT , `product_id` INT UNSIGNED NOT NULL , `artist_name` VARCHAR( 50 ) NOT NULL , PRIMARY KEY ( `product_cd_id` ) , INDEX ( `product_id` ) ) ENGINE = InnoDB; ALTER TABLE `product_cd` ADD FOREIGN KEY ( `product_id` ) REFERENCES `product` (`product_id`) ON DELETE RESTRICT ON UPDATE RESTRICT ; CREATE TABLE `product_dvd` ( `product_dvd_id` INT UNSIGNED NOT NULL AUTO_INCREMENT , `product_id` INT UNSIGNED NOT NULL , `director` VARCHAR( 50 ) NOT NULL , PRIMARY KEY ( `product_dvd_id` ) , INDEX ( `product_id` ) ) ENGINE = InnoDB; ALTER TABLE `product_dvd` ADD FOREIGN KEY ( `product_id` ) REFERENCES `product` (`product_id`) ON DELETE RESTRICT ON UPDATE RESTRICT ; </code></pre> <p>@<a href="https://stackoverflow.com/questions/113803/mysql-foreign-keys-how-to-enforce-one-to-one-across-tables#113811">Skliwz</a>, can you please provide more detail about how triggers can be used to enforce this constraint with the schema provided?</p> <p>@<a href="https://stackoverflow.com/questions/113803/mysql-foreign-keys-how-to-enforce-one-to-one-across-tables#113858">boes</a>, that sounds great. How does it work in situations where you have a child of a child? For example, if we added product_movie and made product_dvd a child of product_movie? Would it be a maintainability nightmare to make the check constraint for product_dvd have to factor in all child types as well?</p>
[ { "answer_id": 113811, "author": "Sklivvz", "author_id": 7028, "author_profile": "https://Stackoverflow.com/users/7028", "pm_score": 1, "selected": false, "text": "<p>If you use MySQL 5.x you can use triggers for these kinds of constraints.</p>\n\n<p>Another (suboptimal) option would be ...
2008/09/22
[ "https://Stackoverflow.com/questions/113803", "https://Stackoverflow.com", "https://Stackoverflow.com/users/15004/" ]
If I have a table in MySQL which represents a base class, and I have a bunch of tables which represent the fields in the derived classes, each of which refers back to the base table with a foreign key, is there any way to get MySQL to enforce the one-to-one relationship between the derived table and the base table, or does this have to be done in code? Using the following quick 'n' dirty schema as an example, is there any way to get MySQL to ensure that rows in both product\_cd and product\_dvd cannot share the same product\_id? Is there a better way to design the schema to allow the database to enforce this relationship, or is it simply not possible? ``` CREATE TABLE IF NOT EXISTS `product` ( `product_id` int(10) unsigned NOT NULL auto_increment, `product_name` varchar(50) NOT NULL, `description` text NOT NULL, PRIMARY KEY (`product_id`) ) ENGINE = InnoDB; CREATE TABLE `product_cd` ( `product_cd_id` INT UNSIGNED NOT NULL AUTO_INCREMENT , `product_id` INT UNSIGNED NOT NULL , `artist_name` VARCHAR( 50 ) NOT NULL , PRIMARY KEY ( `product_cd_id` ) , INDEX ( `product_id` ) ) ENGINE = InnoDB; ALTER TABLE `product_cd` ADD FOREIGN KEY ( `product_id` ) REFERENCES `product` (`product_id`) ON DELETE RESTRICT ON UPDATE RESTRICT ; CREATE TABLE `product_dvd` ( `product_dvd_id` INT UNSIGNED NOT NULL AUTO_INCREMENT , `product_id` INT UNSIGNED NOT NULL , `director` VARCHAR( 50 ) NOT NULL , PRIMARY KEY ( `product_dvd_id` ) , INDEX ( `product_id` ) ) ENGINE = InnoDB; ALTER TABLE `product_dvd` ADD FOREIGN KEY ( `product_id` ) REFERENCES `product` (`product_id`) ON DELETE RESTRICT ON UPDATE RESTRICT ; ``` @[Skliwz](https://stackoverflow.com/questions/113803/mysql-foreign-keys-how-to-enforce-one-to-one-across-tables#113811), can you please provide more detail about how triggers can be used to enforce this constraint with the schema provided? @[boes](https://stackoverflow.com/questions/113803/mysql-foreign-keys-how-to-enforce-one-to-one-across-tables#113858), that sounds great. How does it work in situations where you have a child of a child? For example, if we added product\_movie and made product\_dvd a child of product\_movie? Would it be a maintainability nightmare to make the check constraint for product\_dvd have to factor in all child types as well?
To make sure that a product is or a cd or a dvd I would add a type column and make it part of the primary key. In the derived column you add a check constraint for the type. In the example I set cd to 1 and you could make dvd = 2 and so on for each derived table. ``` CREATE TABLE IF NOT EXISTS `product` ( `product_id` int(10) unsigned NOT NULL auto_increment, 'product_type' int not null, `product_name` varchar(50) NOT NULL, `description` text NOT NULL, PRIMARY KEY (`product_id`, 'product_type') ) ENGINE = InnoDB; CREATE TABLE `product_cd` ( `product_id` INT UNSIGNED NOT NULL , 'product_type' int not null default(1) check ('product_type' = 1) `artist_name` VARCHAR( 50 ) NOT NULL , PRIMARY KEY ( `product_id`, 'product_type' ) , ) ENGINE = InnoDB; ALTER TABLE `product_cd` ADD FOREIGN KEY ( `product_id`, 'product_type' ) REFERENCES `product` (`product_id`, 'product_type') ON DELETE RESTRICT ON UPDATE RESTRICT ; ```
113,824
<p>Is it possible to automount a TrueCrypt volume when logging in to Ubuntu 8.04? It's already storing the wireless network keys using the Seahorse password manager. Could TrueCrypt be made to fetch its volume password from the same keyring? Currently this would seem like the most convenient way to store my source code on the USB stick I carry around to boot from.</p>
[ { "answer_id": 114176, "author": "Zsolt Botykai", "author_id": 11621, "author_profile": "https://Stackoverflow.com/users/11621", "pm_score": 2, "selected": false, "text": "<p>Although I'm currently not a Gentoo user (on Ubuntu now), I used to be one, for years, and had learned, that it's...
2008/09/22
[ "https://Stackoverflow.com/questions/113824", "https://Stackoverflow.com", "https://Stackoverflow.com/users/16509/" ]
Is it possible to automount a TrueCrypt volume when logging in to Ubuntu 8.04? It's already storing the wireless network keys using the Seahorse password manager. Could TrueCrypt be made to fetch its volume password from the same keyring? Currently this would seem like the most convenient way to store my source code on the USB stick I carry around to boot from.
I can't really remember where I found this solution, but it was working for me on Ubuntu Karmic with gdm. You have to edit the `/etc/gdm/Init` file and add the following: ``` if !(echo `mount` | grep -q "/home/your_username type") then truecrypt /dev/sdaxxx /home/your_username fi ``` Unfortunately it doesn't work in the new Precious Penguin Ubuntu release, since it doesn't come with the gmd package. Does anybody know how to init truecrypt for this Ubuntu release?
113,829
<p>How do I get timestamp from e.g. <code>22-09-2008</code>?</p>
[ { "answer_id": 113836, "author": "Till", "author_id": 2859, "author_profile": "https://Stackoverflow.com/users/2859", "pm_score": 5, "selected": false, "text": "<p>Using <a href=\"http://php.net/mktime\" rel=\"noreferrer\">mktime</a>:</p>\n\n<pre><code>list($day, $month, $year) = explode...
2008/09/22
[ "https://Stackoverflow.com/questions/113829", "https://Stackoverflow.com", "https://Stackoverflow.com/users/205368/" ]
How do I get timestamp from e.g. `22-09-2008`?
*This method works on **both** Windows and Unix **and** is **time-zone** aware, which is probably what you want if you work with [dates](https://unix4lyfe.org/time/).* If you don't care about timezone, or want to use the time zone your server uses: ``` $d = DateTime::createFromFormat('d-m-Y H:i:s', '22-09-2008 00:00:00'); if ($d === false) { die("Incorrect date string"); } else { echo $d->getTimestamp(); } ``` **1222093324** (This will differ depending on your server time zone...) If you want to specify in which time zone, here EST. (Same as New York.) ``` $d = DateTime::createFromFormat( 'd-m-Y H:i:s', '22-09-2008 00:00:00', new DateTimeZone('EST') ); if ($d === false) { die("Incorrect date string"); } else { echo $d->getTimestamp(); } ``` **1222093305** Or if you want to use [UTC](https://en.wikipedia.org/wiki/Coordinated_Universal_Time). (Same as "[GMT](https://en.wikipedia.org/wiki/Greenwich_Mean_Time)".) ``` $d = DateTime::createFromFormat( 'd-m-Y H:i:s', '22-09-2008 00:00:00', new DateTimeZone('UTC') ); if ($d === false) { die("Incorrect date string"); } else { echo $d->getTimestamp(); } ``` **1222093289** Regardless, it's always a good starting point to be strict when parsing strings into structured data. It can save awkward debugging in the future. Therefore I recommend to always specify date format.
113,860
<p>How can I make sure that a certain OLEDB driver is installed when I start my application? I use ADO from Delphi and would like to display a descriptive error message if the driver is missing. The error that's returned from ADO isn't always that user-friendly.</p> <p>There are probably a nice little function that returns all installed drivers but I haven't found it.</p>
[ { "answer_id": 114072, "author": "Oli", "author_id": 12870, "author_profile": "https://Stackoverflow.com/users/12870", "pm_score": 1, "selected": false, "text": "<p>Wouldn't the easiest way just be trying to make a connection at start-up and catching the error?</p>\n\n<p>I mean you might...
2008/09/22
[ "https://Stackoverflow.com/questions/113860", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4101/" ]
How can I make sure that a certain OLEDB driver is installed when I start my application? I use ADO from Delphi and would like to display a descriptive error message if the driver is missing. The error that's returned from ADO isn't always that user-friendly. There are probably a nice little function that returns all installed drivers but I haven't found it.
Each provider has a GUID associated with its class. To find the guid, open regedit and search the registry for the provider name. For example, search for "Microsoft Jet 4.0 OLE DB Provider". When you find it, copy the key (the GUID value) and use that in a registry search in your application. ``` function OleDBExists : boolean; var reg : TRegistry; begin Result := false; // See if Advantage OLE DB Provider is on this PC reg := TRegistry.Create; try reg.RootKey := HKEY_LOCAL_MACHINE; Result := reg.OpenKeyReadOnly( '\SOFTWARE\Classes\CLSID\{C1637B2F-CA37-11D2-AE5C-00609791DC73}' ); finally reg.Free; end; end; ```
113,873
<p>I want to extend the basic <code>ControlCollection</code> in VB.NET so I can just add images and text to a self-made control, and then automaticly convert them to pictureboxes and lables.</p> <p>So I made a class that inherits from ControlCollection, overrided the add method, and added the functionality.</p> <p>But when I run the example, it gives a <code>NullReferenceException</code>.</p> <p>Here is the code:</p> <pre><code> Shadows Sub add(ByVal text As String) Dim LB As New Label LB.AutoSize = True LB.Text = text MyBase.Add(LB) 'Here it gives the exception. End Sub </code></pre> <p>I searched on Google, and someone said that the <code>CreateControlsInstance</code> method needs to be overriden. So I did that, but then it gives <code>InvalidOperationException</code> with an <code>innerException</code> message of <code>NullReferenceException</code>.</p> <p>How do I to implement this?</p>
[ { "answer_id": 113891, "author": "Nescio", "author_id": 14484, "author_profile": "https://Stackoverflow.com/users/14484", "pm_score": 3, "selected": true, "text": "<p>Why not inherit from <a href=\"http://msdn.microsoft.com/en-us/library/system.windows.forms.usercontrol.aspx\" rel=\"nofo...
2008/09/22
[ "https://Stackoverflow.com/questions/113873", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20261/" ]
I want to extend the basic `ControlCollection` in VB.NET so I can just add images and text to a self-made control, and then automaticly convert them to pictureboxes and lables. So I made a class that inherits from ControlCollection, overrided the add method, and added the functionality. But when I run the example, it gives a `NullReferenceException`. Here is the code: ``` Shadows Sub add(ByVal text As String) Dim LB As New Label LB.AutoSize = True LB.Text = text MyBase.Add(LB) 'Here it gives the exception. End Sub ``` I searched on Google, and someone said that the `CreateControlsInstance` method needs to be overriden. So I did that, but then it gives `InvalidOperationException` with an `innerException` message of `NullReferenceException`. How do I to implement this?
Why not inherit from [UserControl](http://msdn.microsoft.com/en-us/library/system.windows.forms.usercontrol.aspx) to define a custom control that has properties like Text and Image?
113,886
<p>I'm trying to ftp a folder using the command line ftp client, but so far I've only been able to use 'get' to get individual files. </p>
[ { "answer_id": 113892, "author": "Greg Hewgill", "author_id": 893, "author_profile": "https://Stackoverflow.com/users/893", "pm_score": 4, "selected": false, "text": "<p>If you can use <code>scp</code> instead of <code>ftp</code>, the <code>-r</code> option will do this for you. I would ...
2008/09/22
[ "https://Stackoverflow.com/questions/113886", "https://Stackoverflow.com", "https://Stackoverflow.com/users/11708/" ]
I'm trying to ftp a folder using the command line ftp client, but so far I've only been able to use 'get' to get individual files.
You could rely on wget which usually handles ftp get properly (at least in my own experience). For example: ``` wget -r ftp://user:pass@server.com/ ``` You can also use `-m` which is suitable for mirroring. It is currently equivalent to `-r -N -l inf`. If you've some special characters in the credential details, you can specify the `--user` and `--password` arguments to get it to work. Example with custom login with specific characters: ``` wget -r --user="user@login" --password="Pa$$wo|^D" ftp://server.com/ ``` As pointed out by @asmaier, watch out that even if `-r` is for recursion, it has a default max level of 5: > > > ``` > -r > --recursive > Turn on recursive retrieving. > > -l depth > --level=depth > Specify recursion maximum depth level depth. The default maximum depth is 5. > > ``` > > If you don't want to miss out subdirs, better use the mirroring option, `-m`: > > > ``` > -m > --mirror > Turn on options suitable for mirroring. This option turns on recursion and time-stamping, sets infinite > recursion depth and keeps FTP directory listings. It is currently equivalent to -r -N -l inf > --no-remove-listing. > > ``` > >
113,897
<p>I have a quick question. How do I get the image generated by a JComponent.paint or paintComponent?</p> <p>I have a JComponent which I use as a 'workspace' and where I have overwritten the paintComponent method to my own. The thing is that my workspace JComponent also has children which has their own paintComponent methods.</p> <p>So when Swing renders my workspace component, it renders the workspace graphics and then its childrens'.</p> <p>However, I want to get the image my workspace component generates (which includes the workspace graphics and the children's graphics).</p> <p>How do I do that?</p> <p>I tried to call the paintComponent/paint-method myself by using my own Graphics, but i just returned a black image. Here is what i tried;</p> <pre><code>public void paintComponent(Graphics g) { if (bufferedImage != null) { g.drawImage(bufferedImage, 0, 0, this); } else { g.setColor(Color.WHITE); g.fillRect(0, 0, bufferedImage.getWidth(), bufferedImage.getHeight()); } } public BufferedImage getImage() { BufferedImage hello = new BufferedImage(getWidth(), getHeight(), BufferedImage.TYPE_INT_ARGB); Graphics g = hello.getGraphics(); paintComponent( g ); return hello; } </code></pre> <p>Any thoughts or comments are welcome! :)</p>
[ { "answer_id": 113908, "author": "Martijn", "author_id": 17439, "author_profile": "https://Stackoverflow.com/users/17439", "pm_score": 2, "selected": false, "text": "<p>If you call getImage too early, your component will not have been displayed yet and will still have a 0 width and heigh...
2008/09/22
[ "https://Stackoverflow.com/questions/113897", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20298/" ]
I have a quick question. How do I get the image generated by a JComponent.paint or paintComponent? I have a JComponent which I use as a 'workspace' and where I have overwritten the paintComponent method to my own. The thing is that my workspace JComponent also has children which has their own paintComponent methods. So when Swing renders my workspace component, it renders the workspace graphics and then its childrens'. However, I want to get the image my workspace component generates (which includes the workspace graphics and the children's graphics). How do I do that? I tried to call the paintComponent/paint-method myself by using my own Graphics, but i just returned a black image. Here is what i tried; ``` public void paintComponent(Graphics g) { if (bufferedImage != null) { g.drawImage(bufferedImage, 0, 0, this); } else { g.setColor(Color.WHITE); g.fillRect(0, 0, bufferedImage.getWidth(), bufferedImage.getHeight()); } } public BufferedImage getImage() { BufferedImage hello = new BufferedImage(getWidth(), getHeight(), BufferedImage.TYPE_INT_ARGB); Graphics g = hello.getGraphics(); paintComponent( g ); return hello; } ``` Any thoughts or comments are welcome! :)
If you call getImage too early, your component will not have been displayed yet and will still have a 0 width and height. Have you made sure you're calling it at a sufficient late time? Try printing the component's size to stdout and see what its dimensions are.
113,899
<p>I want to create a c# application with multiple windows that are all transparent with some text on.</p> <p>The tricky part is making these forms sit on top of the desktop but under the desktop icons. Is this possible?</p>
[ { "answer_id": 113933, "author": "Jeff Hillman", "author_id": 3950, "author_profile": "https://Stackoverflow.com/users/3950", "pm_score": 3, "selected": true, "text": "<p>Just making the window transparent is very straight forward:</p>\n\n<pre><code>this.BackColor = Color.Fuchsia;\nthis....
2008/09/22
[ "https://Stackoverflow.com/questions/113899", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3585/" ]
I want to create a c# application with multiple windows that are all transparent with some text on. The tricky part is making these forms sit on top of the desktop but under the desktop icons. Is this possible?
Just making the window transparent is very straight forward: ``` this.BackColor = Color.Fuchsia; this.TransparencyKey = Color.Fuchsia; ``` You can do something like this to make it so you can still interact with the desktop or anything else under your window: ``` public const int WM_NCHITTEST = 0x84; public const int HTTRANSPARENT = -1; protected override void WndProc(ref Message message) { if ( message.Msg == (int)WM_NCHITTEST ) { message.Result = (IntPtr)HTTRANSPARENT; } else { base.WndProc( ref message ); } } ```
113,901
<p>In order to perform a case-sensitive search/replace on a table in a SQL Server 2000/2005 database, you must use the correct collation.</p> <p>How do you determine whether the default collation for a database is case-sensitive, and if it isn't, how to perform a case-sensitive search/replace?</p>
[ { "answer_id": 113909, "author": "blowdart", "author_id": 2525, "author_profile": "https://Stackoverflow.com/users/2525", "pm_score": 5, "selected": true, "text": "<pre><code>SELECT testColumn FROM testTable \n WHERE testColumn COLLATE Latin1_General_CS_AS = 'example' \n\nSELECT test...
2008/09/22
[ "https://Stackoverflow.com/questions/113901", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5152/" ]
In order to perform a case-sensitive search/replace on a table in a SQL Server 2000/2005 database, you must use the correct collation. How do you determine whether the default collation for a database is case-sensitive, and if it isn't, how to perform a case-sensitive search/replace?
``` SELECT testColumn FROM testTable WHERE testColumn COLLATE Latin1_General_CS_AS = 'example' SELECT testColumn FROM testTable WHERE testColumn COLLATE Latin1_General_CS_AS = 'EXAMPLE' SELECT testColumn FROM testTable WHERE testColumn COLLATE Latin1_General_CS_AS = 'eXaMpLe' ``` Don't assume the default collation will be case sensitive, just specify a case sensitive one every time (using the correct one for your language of course)
113,915
<p>I'm getting a random unreproducible Error when initializing a JSplitPane in with JDK 1.5.0_08. Note that this does not occur every time, but about 80% of the time:</p> <pre><code>Exception in thread "AWT-EventQueue-0" java.lang.ClassCastException: javax.swing.KeyStroke at java.util.TreeMap.compare(TreeMap.java:1093) at java.util.TreeMap.put(TreeMap.java:465) at java.util.TreeSet.add(TreeSet.java:210) at javax.swing.plaf.basic.BasicSplitPaneUI.installDefaults(BasicSplitPaneUI.java:364) at javax.swing.plaf.basic.BasicSplitPaneUI.installUI(BasicSplitPaneUI.java:300) at javax.swing.JComponent.setUI(JComponent.java:652) at javax.swing.JSplitPane.setUI(JSplitPane.java:350) at javax.swing.JSplitPane.updateUI(JSplitPane.java:378) at javax.swing.JSplitPane.&lt;init&gt;(JSplitPane.java:332) at javax.swing.JSplitPane.&lt;init&gt;(JSplitPane.java:287) ... </code></pre> <p>Thoughts? I've tried cleaning and rebuilding my project so as to minimize the probability of corrupted class files.</p> <p><strong>Edit #1</strong> See <a href="http://bugs.sun.com/bugdatabase/view_bug.do?bug_id=6434148" rel="nofollow noreferrer">http://bugs.sun.com/bugdatabase/view_bug.do?bug_id=6434148</a> - seems to be a JDK bug. Any known workarounds? None are listed on the bug entry page.</p>
[ { "answer_id": 113924, "author": "Epaga", "author_id": 6583, "author_profile": "https://Stackoverflow.com/users/6583", "pm_score": 3, "selected": true, "text": "<p>After doing some Googling on bugs.sun.com, this looks like this might be a JDK bug that was only fixed in JDK 6.</p>\n\n<p>S...
2008/09/22
[ "https://Stackoverflow.com/questions/113915", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6583/" ]
I'm getting a random unreproducible Error when initializing a JSplitPane in with JDK 1.5.0\_08. Note that this does not occur every time, but about 80% of the time: ``` Exception in thread "AWT-EventQueue-0" java.lang.ClassCastException: javax.swing.KeyStroke at java.util.TreeMap.compare(TreeMap.java:1093) at java.util.TreeMap.put(TreeMap.java:465) at java.util.TreeSet.add(TreeSet.java:210) at javax.swing.plaf.basic.BasicSplitPaneUI.installDefaults(BasicSplitPaneUI.java:364) at javax.swing.plaf.basic.BasicSplitPaneUI.installUI(BasicSplitPaneUI.java:300) at javax.swing.JComponent.setUI(JComponent.java:652) at javax.swing.JSplitPane.setUI(JSplitPane.java:350) at javax.swing.JSplitPane.updateUI(JSplitPane.java:378) at javax.swing.JSplitPane.<init>(JSplitPane.java:332) at javax.swing.JSplitPane.<init>(JSplitPane.java:287) ... ``` Thoughts? I've tried cleaning and rebuilding my project so as to minimize the probability of corrupted class files. **Edit #1** See <http://bugs.sun.com/bugdatabase/view_bug.do?bug_id=6434148> - seems to be a JDK bug. Any known workarounds? None are listed on the bug entry page.
After doing some Googling on bugs.sun.com, this looks like this might be a JDK bug that was only fixed in JDK 6. See <http://bugs.sun.com/bugdatabase/view_bug.do?bug_id=6434148>
113,916
<p>If I need to choose a collation mode to work with, how do I know what collations are available?</p>
[ { "answer_id": 113917, "author": "Andrew Myhre", "author_id": 5152, "author_profile": "https://Stackoverflow.com/users/5152", "pm_score": 3, "selected": false, "text": "<p>Use this query to list the available collation modes:</p>\n\n<p>SELECT *\nFROM fn_helpcollations()</p>\n" }, { ...
2008/09/22
[ "https://Stackoverflow.com/questions/113916", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5152/" ]
If I need to choose a collation mode to work with, how do I know what collations are available?
``` select distinct COLLATION_NAME from INFORMATION_SCHEMA.COLUMNS order by 1 ```
113,928
<p>When I enter an object into the DB with Linq-to-SQL can I get the id that I just inserted without making another db call? I am assuming this is pretty easy, I just don't know how. </p>
[ { "answer_id": 113948, "author": "Germstorm", "author_id": 18631, "author_profile": "https://Stackoverflow.com/users/18631", "pm_score": 9, "selected": true, "text": "<p>After you commit your object into the db the object receives a value in its ID field.</p>\n\n<p>So:</p>\n\n<pre><code>...
2008/09/22
[ "https://Stackoverflow.com/questions/113928", "https://Stackoverflow.com", "https://Stackoverflow.com/users/14777/" ]
When I enter an object into the DB with Linq-to-SQL can I get the id that I just inserted without making another db call? I am assuming this is pretty easy, I just don't know how.
After you commit your object into the db the object receives a value in its ID field. So: ``` myObject.Field1 = "value"; // Db is the datacontext db.MyObjects.InsertOnSubmit(myObject); db.SubmitChanges(); // You can retrieve the id from the object int id = myObject.ID; ```
113,951
<p>I am creating an appcation on Vista,which include a service and a Console application .Both running in same user account</p> <p>In service i am creating an event and waits for that event.In console application i am opening the same event (problem starts here) and calling <em>SetEvent</em> function. I can not open the event (getting error 5,Access is denied) in the console application.I searched in the net and saw something about integrity level (I am not sure that the problem is related to integrity level).Its telling that service and applicaation got differnt integrity levels.</p> <p>here is the part of the code,where IPC occures</p> <p><strong>service</strong> </p> <pre><code>DWORD WINAPI IpcThread(LPVOID lpParam) { HANDLE ghRequestEvent = NULL ; ghRequestEvent = CreateEvent(NULL, FALSE, FALSE, "Global\\Event1") ; //creating the event if(NULL == ghRequestEvent) { //error } while(1) { WaitForSingleObject(ghRequestEvent, INFINITE) //waiting for the event //here some action related to event } } </code></pre> <p><strong>Console Application</strong></p> <p>Here in application ,opening the event and seting the event</p> <pre><code>unsigned int event_notification() { HANDLE ghRequestEvent = NULL ; ghRequestEvent = OpenEvent(SYNCHRONIZE|EVENT_MODIFY_STATE, FALSE, "Global\\Event1") ; if(NULL == ghRequestEvent) { //error } SetEvent(ghRequestEvent) ; } </code></pre> <p>I am running both application (serivce and console application) with administrative privilege (i logged in as Administraor and running the console application by right clicking and using the option "run as administrator") .</p> <p>The error i am getting in console application (where i am opening the event) is error no 5(Access is denied. ) .</p> <p>So it will be very helpfull if you tell how to do the IPC between a service and an application in Vista</p> <p>Thanks in advance</p> <p>Navaneeth</p>
[ { "answer_id": 114009, "author": "1800 INFORMATION", "author_id": 3146, "author_profile": "https://Stackoverflow.com/users/3146", "pm_score": 2, "selected": false, "text": "<p>Are the service and the application running as the same user with different integrity levels, or are they runnin...
2008/09/22
[ "https://Stackoverflow.com/questions/113951", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20316/" ]
I am creating an appcation on Vista,which include a service and a Console application .Both running in same user account In service i am creating an event and waits for that event.In console application i am opening the same event (problem starts here) and calling *SetEvent* function. I can not open the event (getting error 5,Access is denied) in the console application.I searched in the net and saw something about integrity level (I am not sure that the problem is related to integrity level).Its telling that service and applicaation got differnt integrity levels. here is the part of the code,where IPC occures **service** ``` DWORD WINAPI IpcThread(LPVOID lpParam) { HANDLE ghRequestEvent = NULL ; ghRequestEvent = CreateEvent(NULL, FALSE, FALSE, "Global\\Event1") ; //creating the event if(NULL == ghRequestEvent) { //error } while(1) { WaitForSingleObject(ghRequestEvent, INFINITE) //waiting for the event //here some action related to event } } ``` **Console Application** Here in application ,opening the event and seting the event ``` unsigned int event_notification() { HANDLE ghRequestEvent = NULL ; ghRequestEvent = OpenEvent(SYNCHRONIZE|EVENT_MODIFY_STATE, FALSE, "Global\\Event1") ; if(NULL == ghRequestEvent) { //error } SetEvent(ghRequestEvent) ; } ``` I am running both application (serivce and console application) with administrative privilege (i logged in as Administraor and running the console application by right clicking and using the option "run as administrator") . The error i am getting in console application (where i am opening the event) is error no 5(Access is denied. ) . So it will be very helpfull if you tell how to do the IPC between a service and an application in Vista Thanks in advance Navaneeth
Are the service and the application running as the same user with different integrity levels, or are they running as different users? If it is the former, then this article from MSDN [which talks about integrity levels might help](http://msdn.microsoft.com/en-us/library/bb250462.aspx). They have some sample code for lowering the integrity level of a file. I'm not sure that this could be relevant for an event though. ``` #include <sddl.h> #include <AccCtrl.h> #include <Aclapi.h> void SetLowLabelToFile() { // The LABEL_SECURITY_INFORMATION SDDL SACL to be set for low integrity #define LOW_INTEGRITY_SDDL_SACL_W L"S:(ML;;NW;;;LW)" DWORD dwErr = ERROR_SUCCESS; PSECURITY_DESCRIPTOR pSD = NULL; PACL pSacl = NULL; // not allocated BOOL fSaclPresent = FALSE; BOOL fSaclDefaulted = FALSE; LPCWSTR pwszFileName = L"Sample.txt"; if (ConvertStringSecurityDescriptorToSecurityDescriptorW( LOW_INTEGRITY_SDDL_SACL_W, SDDL_REVISION_1, &pSD;, NULL)) { if (GetSecurityDescriptorSacl(pSD, &fSaclPresent;, &pSacl;, &fSaclDefaulted;)) { // Note that psidOwner, psidGroup, and pDacl are // all NULL and set the new LABEL_SECURITY_INFORMATION dwErr = SetNamedSecurityInfoW((LPWSTR) pwszFileName, SE_FILE_OBJECT, LABEL_SECURITY_INFORMATION, NULL, NULL, NULL, pSacl); } LocalFree(pSD); } } ``` If it is the latter you might look at this link which [suggests creating a NULL ACL](http://www.tech-archive.net/Archive/Development/microsoft.public.win32.programmer.kernel/2007-04/msg00086.html) and associating it with the object (in the example it is a named pipe, but the approach is similar for an event I'm sure: ``` BYTE sd[SECURITY_DESCRIPTOR_MIN_LENGTH]; SECURITY_ATTRIBUTES sa; sa.nLength = sizeof(sa); sa.bInheritHandle = TRUE; sa.lpSecurityDescriptor = &sd; InitializeSecurityDescriptor(&sd, SECURITY_DESCRIPTOR_REVISION); SetSecurityDescriptorDacl(&sd, TRUE, (PACL) 0, FALSE); CreateNamedPipe(..., &sa); ```
113,989
<p>Is there an easy way (in .Net) to test if a Font is installed on the current machine?</p>
[ { "answer_id": 113998, "author": "aku", "author_id": 1196, "author_profile": "https://Stackoverflow.com/users/1196", "pm_score": 5, "selected": false, "text": "<p><a href=\"https://stackoverflow.com/questions/89886/how-do-you-get-a-list-of-all-the-installed-fonts#89895\">How do you get a...
2008/09/22
[ "https://Stackoverflow.com/questions/113989", "https://Stackoverflow.com", "https://Stackoverflow.com/users/11492/" ]
Is there an easy way (in .Net) to test if a Font is installed on the current machine?
``` string fontName = "Consolas"; float fontSize = 12; using (Font fontTester = new Font( fontName, fontSize, FontStyle.Regular, GraphicsUnit.Pixel)) { if (fontTester.Name == fontName) { // Font exists } else { // Font doesn't exist } } ```
113,991
<p>A heap is a list where the following applies:</p> <pre><code>l[i] &lt;= l[2*i] &amp;&amp; l[i] &lt;= [2*i+1] </code></pre> <p>for <code>0 &lt;= i &lt; len(list)</code></p> <p>I'm looking for in-place sorting.</p>
[ { "answer_id": 114020, "author": "Antti Rasinen", "author_id": 8570, "author_profile": "https://Stackoverflow.com/users/8570", "pm_score": -1, "selected": false, "text": "<p>Read the items off the top of the heap one by one. Basically what you have then is heap sort.</p>\n" }, { ...
2008/09/22
[ "https://Stackoverflow.com/questions/113991", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6899/" ]
A heap is a list where the following applies: ``` l[i] <= l[2*i] && l[i] <= [2*i+1] ``` for `0 <= i < len(list)` I'm looking for in-place sorting.
Well you are half way through a Heap Sort already, by having your data in a heap. You just need to implement the second part of the heap sort algorithm. This should be faster than using quicksort on the heap array. If you are feeling brave you could have a go at implementing [smoothsort](http://www.cs.utexas.edu/users/EWD/ewd07xx/EWD796a.PDF), which is faster than heapsort for nearly-sorted data.
113,992
<p>In what order are the following parameters tested (in C++)?</p> <pre><code>if (a || b &amp;&amp; c) { } </code></pre> <p>I've just seen this code in our application and I hate it, I want to add some brackets to just clarify the ordering. But I don't want to add the brackets until I know I'm adding them in the right place.</p> <p><strong><em>Edit: Accepted Answer &amp; Follow Up</em></strong></p> <p>This link has more information, but it's not totally clear what it means. It seems || and &amp;&amp; are the same precedence, and in that case, they are evaluated left-to-right.</p> <p><a href="http://msdn.microsoft.com/en-us/library/126fe14k.aspx" rel="nofollow noreferrer">http://msdn.microsoft.com/en-us/library/126fe14k.aspx</a></p>
[ { "answer_id": 113995, "author": "tzot", "author_id": 6899, "author_profile": "https://Stackoverflow.com/users/6899", "pm_score": 3, "selected": true, "text": "<p>From <a href=\"http://www.difranco.net/compsci/C_Operator_Precedence_Table.htm\" rel=\"nofollow noreferrer\">here</a>:</p>\n\...
2008/09/22
[ "https://Stackoverflow.com/questions/113992", "https://Stackoverflow.com", "https://Stackoverflow.com/users/986/" ]
In what order are the following parameters tested (in C++)? ``` if (a || b && c) { } ``` I've just seen this code in our application and I hate it, I want to add some brackets to just clarify the ordering. But I don't want to add the brackets until I know I'm adding them in the right place. ***Edit: Accepted Answer & Follow Up*** This link has more information, but it's not totally clear what it means. It seems || and && are the same precedence, and in that case, they are evaluated left-to-right. <http://msdn.microsoft.com/en-us/library/126fe14k.aspx>
From [here](http://www.difranco.net/compsci/C_Operator_Precedence_Table.htm): ``` a || (b && c) ``` This is the default precedence.
114,010
<p>Is there any way to create C# 3.0 anonymous object via Reflection at runtime in .NET 3.5? I'd like to support them in my serialization scheme, so I need a way to manipulate them programmatically.</p> <p><em>edited later to clarify the use case</em></p> <p>An extra constraint is that I will be running all of it inside a Silverlight app, so extra runtimes are not an option, and not sure how generating code on the fly will work.</p>
[ { "answer_id": 114022, "author": "Serafina Brocious", "author_id": 4977, "author_profile": "https://Stackoverflow.com/users/4977", "pm_score": 1, "selected": false, "text": "<p>Use reflection to get the Type, use GetConstructor on the type, use Invoke on the constructor.</p>\n\n<p>Edit: ...
2008/09/22
[ "https://Stackoverflow.com/questions/114010", "https://Stackoverflow.com", "https://Stackoverflow.com/users/9777/" ]
Is there any way to create C# 3.0 anonymous object via Reflection at runtime in .NET 3.5? I'd like to support them in my serialization scheme, so I need a way to manipulate them programmatically. *edited later to clarify the use case* An extra constraint is that I will be running all of it inside a Silverlight app, so extra runtimes are not an option, and not sure how generating code on the fly will work.
Here is another way, seems more direct. ``` object anon = Activator.CreateInstance(existingObject.GetType()); ```
114,054
<p>Can you please clarify the folowing query? I am not sure if the way I am trying to code is correct. Kindly advise me if I am moving in the right/wrong direction.</p> <p>I am trying to develop an automation framework using <a href="http://en.wikipedia.org/wiki/HP_QuickTest_Professional" rel="nofollow noreferrer">QuickTest Professional</a>, a testing tool.</p> <ul> <li>There is an Excel sheet from which the data is being taken for execution based on the ID's stored in an array from another Excel sheet (The same ID is available in both Excel sheets).</li> <li>I'm trying to handle the exeptional cases through a function call. This function will capture the screenshot of the page error occured and then exit the entire loop.</li> <li>I need a scenario where execution continues for the next ID stored in the array, and this needs to be handled from the function call.</li> </ul>
[ { "answer_id": 114133, "author": "Rob Cooper", "author_id": 832, "author_profile": "https://Stackoverflow.com/users/832", "pm_score": 1, "selected": false, "text": "<p>Well, it sounds like you already have the answer.. You just need to handle the expection that occurs when reading in the...
2008/09/22
[ "https://Stackoverflow.com/questions/114054", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
Can you please clarify the folowing query? I am not sure if the way I am trying to code is correct. Kindly advise me if I am moving in the right/wrong direction. I am trying to develop an automation framework using [QuickTest Professional](http://en.wikipedia.org/wiki/HP_QuickTest_Professional), a testing tool. * There is an Excel sheet from which the data is being taken for execution based on the ID's stored in an array from another Excel sheet (The same ID is available in both Excel sheets). * I'm trying to handle the exeptional cases through a function call. This function will capture the screenshot of the page error occured and then exit the entire loop. * I need a scenario where execution continues for the next ID stored in the array, and this needs to be handled from the function call.
Well, it sounds like you already have the answer.. You just need to handle the expection that occurs when reading in the data within the main loop and make it stop there.. Now, I have not done VBScript for a LONG time so, to pseudo it: ``` While Not EndOfExcelSheet ReadDataFromExcel(); If errOccurred Then TakeScreenPrint(); 'NOTE: We have caught the error and requested the screen print 'is taken, but we have NOT bubbled the exception up! End While ```
114,149
<p>The point of const-correctness is to be able to provide a view of an instance that can't be altered or deleted by the user. The compiler supports this by pointing out when you break constness from within a const function, or try to use a non-const function of a const object. So without copying the const approach, is there a methodology I can use in C# that has the same ends? </p> <p>I'm aware of immutability, but that doesn't really carry over to container objects to name but one example.</p>
[ { "answer_id": 114155, "author": "aku", "author_id": 1196, "author_profile": "https://Stackoverflow.com/users/1196", "pm_score": 2, "selected": false, "text": "<p>C# doesn't have such feature. You can pass argument by value or by reference. Reference itself is immutable unless you specif...
2008/09/22
[ "https://Stackoverflow.com/questions/114149", "https://Stackoverflow.com", "https://Stackoverflow.com/users/11801/" ]
The point of const-correctness is to be able to provide a view of an instance that can't be altered or deleted by the user. The compiler supports this by pointing out when you break constness from within a const function, or try to use a non-const function of a const object. So without copying the const approach, is there a methodology I can use in C# that has the same ends? I'm aware of immutability, but that doesn't really carry over to container objects to name but one example.
I've come across this issue a lot of times too and ended up using interfaces. I think it's important to drop the idea that C# is any form, or even an evolution of C++. They're two different languages that share almost the same syntax. I usually express 'const correctness' in C# by defining a read-only view of a class: ``` public interface IReadOnlyCustomer { String Name { get; } int Age { get; } } public class Customer : IReadOnlyCustomer { private string m_name; private int m_age; public string Name { get { return m_name; } set { m_name = value; } } public int Age { get { return m_age; } set { m_age = value; } } } ```
114,154
<p>XAML allows you to specify an attribute value using a string that contains curly braces. Here is an example that creates a <em>Binding</em> instance and assigns it to the <em>Text</em> property of the <em>TextBox</em> element.</p> <pre><code>&lt;TextBox Text="{Binding ElementName=Foo, Path=Bar}"/&gt; </code></pre> <p>I want to extend XAML so that the developer could enter this as valid...</p> <pre><code>&lt;TextBox Text="{MyCustomObject Field1=Foo, Field2=Bar}"/&gt; </code></pre> <p>This would create an instance of my class and set the Field1/Field2 properties as appropriate. Is this possible? If so how do you do it?</p> <p>If this is possible I have a followup question. Can I take a string <em>"{Binding ElementName=Foo, Path=Bar}"</em> and ask the framework to process it and return the <em>Binding</em> instance it specified? This must be done somewhere already to make the above XAML work and so there must be a way to ask for the same thing to be processed.</p>
[ { "answer_id": 114175, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 2, "selected": true, "text": "<p>take a look at markupextensions\n<a href=\"http://blogs.msdn.com/wpfsdk/archive/2007/03/22/blogpost-text-creatingasimplecust...
2008/09/22
[ "https://Stackoverflow.com/questions/114154", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6276/" ]
XAML allows you to specify an attribute value using a string that contains curly braces. Here is an example that creates a *Binding* instance and assigns it to the *Text* property of the *TextBox* element. ``` <TextBox Text="{Binding ElementName=Foo, Path=Bar}"/> ``` I want to extend XAML so that the developer could enter this as valid... ``` <TextBox Text="{MyCustomObject Field1=Foo, Field2=Bar}"/> ``` This would create an instance of my class and set the Field1/Field2 properties as appropriate. Is this possible? If so how do you do it? If this is possible I have a followup question. Can I take a string *"{Binding ElementName=Foo, Path=Bar}"* and ask the framework to process it and return the *Binding* instance it specified? This must be done somewhere already to make the above XAML work and so there must be a way to ask for the same thing to be processed.
take a look at markupextensions <http://blogs.msdn.com/wpfsdk/archive/2007/03/22/blogpost-text-creatingasimplecustommarkupextension.aspx>
114,165
<p>At work we use <a href="http://en.wikipedia.org/wiki/WiX" rel="noreferrer">WiX</a> for building installation packages. We want that installation of product X would result in uninstall of the previous version of that product on that machine.</p> <p>I've read on several places on the Internet about a major upgrade but couldn't get it to work. Can anyone please specify the exact steps that I need to take to add uninstall previous version feature to WiX?</p>
[ { "answer_id": 114736, "author": "Dror Helper", "author_id": 11361, "author_profile": "https://Stackoverflow.com/users/11361", "pm_score": 8, "selected": false, "text": "<p>Finally I found a solution - I'm posting it here for other people who might have the same problem (all 5 of you):</...
2008/09/22
[ "https://Stackoverflow.com/questions/114165", "https://Stackoverflow.com", "https://Stackoverflow.com/users/11361/" ]
At work we use [WiX](http://en.wikipedia.org/wiki/WiX) for building installation packages. We want that installation of product X would result in uninstall of the previous version of that product on that machine. I've read on several places on the Internet about a major upgrade but couldn't get it to work. Can anyone please specify the exact steps that I need to take to add uninstall previous version feature to WiX?
In the newest versions (from the 3.5.1315.0 beta), you can use the [MajorUpgrade element](http://wixtoolset.org/documentation/manual/v3/xsd/wix/majorupgrade.html "Major upgrade") instead of using your own. For example, we use this code to do automatic upgrades. It prevents downgrades, giving a localised error message, and also prevents upgrading an already existing identical version (i.e. only lower versions are upgraded): ``` <MajorUpgrade AllowDowngrades="no" DowngradeErrorMessage="!(loc.NewerVersionInstalled)" AllowSameVersionUpgrades="no" /> ```
114,172
<p>I have a Windows executable (whoami) which is crashing every so often. It's called from another process to get details about the current user and domain. I'd like to know what parameters are passed when it fails.</p> <p>Does anyone know of an appropriate way to wrap the process and write it's command line arguments to log while still calling the process?</p> <p>Say the command is used like this: 'whoami.exe /all'</p> <p>I'd like a script to exist instead of the whoami.exe (with the same filename) which will write this invocation to log and then pass on the call to the actual process.</p>
[ { "answer_id": 114199, "author": "Milan Babuškov", "author_id": 14690, "author_profile": "https://Stackoverflow.com/users/14690", "pm_score": 1, "selected": false, "text": "<p>You didn't note which programming language. It is not doable from a .bat file if that's what you wanted, but you...
2008/09/22
[ "https://Stackoverflow.com/questions/114172", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2257098/" ]
I have a Windows executable (whoami) which is crashing every so often. It's called from another process to get details about the current user and domain. I'd like to know what parameters are passed when it fails. Does anyone know of an appropriate way to wrap the process and write it's command line arguments to log while still calling the process? Say the command is used like this: 'whoami.exe /all' I'd like a script to exist instead of the whoami.exe (with the same filename) which will write this invocation to log and then pass on the call to the actual process.
From a batch file: ``` echo Parameters: %* >> logfile.txt whoami.exe %* ``` With the caveat that you can have problems if the parameters contain spaces (and you passed the in escaping with "), because the command-line parser basically de-escapes them and they should be re-escaped before passed to an other executable.
114,179
<p>I got this síngleton cache object and it exposes an IEnumerable property which just returns a private IEnumerable variable.</p> <p>I have a static method on my singleton object that updates this member variable (that exists on the single 'Instance' instance of this cache object).</p> <p>Let's say some thread is currently iterating over this IEnumerable variable/property while my cache is updating. I made it so the cache is updating on a new local variable and finally setting the exposed private variable to point to this new local variable.</p> <p>I know i'm just updating a reference, leaving the other (old) object in memory waiting to be picked up by the GC but my problem is - i'm not 100% sure what happens once i set the new reference? Would the other thread suddenly be iterating over the new object or the old one it got passed through the IEnumerable interface? If it had been a normal reference i'd say 'no'. The calling thread would be operating on the old object, but i'm not sure if this is the case for IEnumerable as well?</p> <p>Here is the class stripped down:</p> <pre><code>internal sealed class SektionCache : CacheBase { public static readonly SektionCache Instance = new SektionCache(); private static readonly object lockObject = new object(); private static bool isUpdating; private IEnumerable&lt;Sektion&gt; sektioner; static SektionCache() { UpdateCache(); } public IEnumerable&lt;Sektion&gt; Sektioner { get { return sektioner; } } public static void UpdateCache() { // SNIP - getting data, locking etc. Instance.sektioner = newSektioner; // SNIP } } </code></pre>
[ { "answer_id": 114193, "author": "configurator", "author_id": 9536, "author_profile": "https://Stackoverflow.com/users/9536", "pm_score": 2, "selected": false, "text": "<p>Since the getter <code>{ return sektioner; }</code> is called before the new value is put in the field, the old valu...
2008/09/22
[ "https://Stackoverflow.com/questions/114179", "https://Stackoverflow.com", "https://Stackoverflow.com/users/11619/" ]
I got this síngleton cache object and it exposes an IEnumerable property which just returns a private IEnumerable variable. I have a static method on my singleton object that updates this member variable (that exists on the single 'Instance' instance of this cache object). Let's say some thread is currently iterating over this IEnumerable variable/property while my cache is updating. I made it so the cache is updating on a new local variable and finally setting the exposed private variable to point to this new local variable. I know i'm just updating a reference, leaving the other (old) object in memory waiting to be picked up by the GC but my problem is - i'm not 100% sure what happens once i set the new reference? Would the other thread suddenly be iterating over the new object or the old one it got passed through the IEnumerable interface? If it had been a normal reference i'd say 'no'. The calling thread would be operating on the old object, but i'm not sure if this is the case for IEnumerable as well? Here is the class stripped down: ``` internal sealed class SektionCache : CacheBase { public static readonly SektionCache Instance = new SektionCache(); private static readonly object lockObject = new object(); private static bool isUpdating; private IEnumerable<Sektion> sektioner; static SektionCache() { UpdateCache(); } public IEnumerable<Sektion> Sektioner { get { return sektioner; } } public static void UpdateCache() { // SNIP - getting data, locking etc. Instance.sektioner = newSektioner; // SNIP } } ```
The thread which is currently enumerating sektioner will continue to enumerate it even when you update the reference within the singleton. There is nothing special about objects which implement IEnumerable. You should perhaps add the [volatile](https://learn.microsoft.com/en-us/dotnet/csharp/language-reference/keywords/volatile) keyword to the sektioner field as you are not providing read-locking and multiple threads are reading/writing it.
114,180
<p>What would be better practice when giving a function the original variable to work with:</p> <pre><code>unsigned long x = 4; void func1(unsigned long&amp; val) { val = 5; } func1(x); </code></pre> <p>or:</p> <pre><code>void func2(unsigned long* val) { *val = 5; } func2(&amp;x); </code></pre> <p>IOW: Is there any reason to pick one over another?</p>
[ { "answer_id": 114189, "author": "Nils Pipenbrinck", "author_id": 15955, "author_profile": "https://Stackoverflow.com/users/15955", "pm_score": 9, "selected": true, "text": "<p>My rule of thumb is:</p>\n\n<p>Use pointers if you want to do pointer arithmetic with them (e.g. incrementing t...
2008/09/22
[ "https://Stackoverflow.com/questions/114180", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20349/" ]
What would be better practice when giving a function the original variable to work with: ``` unsigned long x = 4; void func1(unsigned long& val) { val = 5; } func1(x); ``` or: ``` void func2(unsigned long* val) { *val = 5; } func2(&x); ``` IOW: Is there any reason to pick one over another?
My rule of thumb is: Use pointers if you want to do pointer arithmetic with them (e.g. incrementing the pointer address to step through an array) or if you ever have to pass a NULL-pointer. Use references otherwise.
114,204
<p>I've set up DAV in apache2, which works great. The thing is, all read/write operations are done with the apache user's credentials. Instead I want to use the HTTP authenticated user's credentials. If I authenticate as "john", all read and write operations should use the system user john's credentials (from /etc/passwd). <a href="http://httpd.apache.org/docs/2.2/suexec.html" rel="nofollow noreferrer">suEXEC</a> seems like overkill since I am not executing anything, but I might be wrong...</p> <p>Here's the current configuration:</p> <pre><code>&lt;VirtualHost *:80&gt; DocumentRoot /var/www/webdav ServerName webdav.mydomain.com ServerAdmin webmaster@mydomain.com &lt;Location "/"&gt; DAV On AuthType Basic AuthName "WebDAV Restricted" AuthUserFile /etc/apache2/extra/webdav-passwords require valid-user Options +Indexes &lt;/Location&gt; DAVLockDB /var/lib/dav/lockdb ErrorLog /var/log/apache2/webdav-error.log TransferLog /var/log/apache2/webdav-access.log &lt;/VirtualHost&gt; </code></pre>
[ { "answer_id": 114275, "author": "niXar", "author_id": 19979, "author_profile": "https://Stackoverflow.com/users/19979", "pm_score": 2, "selected": false, "text": "<p>Shot answer, and as far as I know: you don't.</p>\n<p>Long answer: it is possible to implement such a feature with an app...
2008/09/22
[ "https://Stackoverflow.com/questions/114204", "https://Stackoverflow.com", "https://Stackoverflow.com/users/13365/" ]
I've set up DAV in apache2, which works great. The thing is, all read/write operations are done with the apache user's credentials. Instead I want to use the HTTP authenticated user's credentials. If I authenticate as "john", all read and write operations should use the system user john's credentials (from /etc/passwd). [suEXEC](http://httpd.apache.org/docs/2.2/suexec.html) seems like overkill since I am not executing anything, but I might be wrong... Here's the current configuration: ``` <VirtualHost *:80> DocumentRoot /var/www/webdav ServerName webdav.mydomain.com ServerAdmin webmaster@mydomain.com <Location "/"> DAV On AuthType Basic AuthName "WebDAV Restricted" AuthUserFile /etc/apache2/extra/webdav-passwords require valid-user Options +Indexes </Location> DAVLockDB /var/lib/dav/lockdb ErrorLog /var/log/apache2/webdav-error.log TransferLog /var/log/apache2/webdav-access.log </VirtualHost> ```
We have been using davenport (<http://davenport.sourceforge.net/>) for years to provide access to Windows/samba shares over webdav. Samba/Windows gives a lot of control over this sort of thing, and the Davenport just makes it usable over the web over SSL without a VPN
114,208
<p>Let me explain: this is path to this folder: > <code>www.my_site.com/images</code></p> <p>And images are created by <code>user_id</code>, and for example, images of <code>user_id = 27</code> are, <code>27_1.jpg</code>, <code>27_2.jpg</code>, <code>27_3.jpg</code>! How to list and print images which start with <code>27_%.jpg</code>? I hope You have understood me! PS. I am totally beginmer in ASP.NET (VB) and please give me detailed information</p> <p>Here starts my loop</p> <pre><code>while dbread.Read() 'and then id user_id dbread('user_id') </code></pre> <p>NEXT???</p> <hr> <p>I nedd to create XML, till now I created like this:</p> <p>act.WriteLine("") act.WriteLine("<a href="http://www.my_site.com/images/" rel="nofollow noreferrer">http://www.my_site.com/images/</a>"&amp;dbread("user_id")&amp;"_1.jpg") act.WriteLine("")</p> <p>But this is not answer because I need to create this nodes how many images of this user exist?</p> <p>In database doesn't exist list of this images so that is reason why I must count them in folder. (this is not my site exacly, but I need to create XMl on this site)</p> <p>Do you understand me?</p>
[ { "answer_id": 114231, "author": "Torsten Marek", "author_id": 9567, "author_profile": "https://Stackoverflow.com/users/9567", "pm_score": 4, "selected": true, "text": "<p>Environment variables are inherited by processes in Unix. The files in /etc/profile.d are only executed (in the curr...
2008/09/22
[ "https://Stackoverflow.com/questions/114208", "https://Stackoverflow.com", "https://Stackoverflow.com/users/205368/" ]
Let me explain: this is path to this folder: > `www.my_site.com/images` And images are created by `user_id`, and for example, images of `user_id = 27` are, `27_1.jpg`, `27_2.jpg`, `27_3.jpg`! How to list and print images which start with `27_%.jpg`? I hope You have understood me! PS. I am totally beginmer in ASP.NET (VB) and please give me detailed information Here starts my loop ``` while dbread.Read() 'and then id user_id dbread('user_id') ``` NEXT??? --- I nedd to create XML, till now I created like this: act.WriteLine("") act.WriteLine("<http://www.my_site.com/images/>"&dbread("user\_id")&"\_1.jpg") act.WriteLine("") But this is not answer because I need to create this nodes how many images of this user exist? In database doesn't exist list of this images so that is reason why I must count them in folder. (this is not my site exacly, but I need to create XMl on this site) Do you understand me?
Environment variables are inherited by processes in Unix. The files in /etc/profile.d are only executed (in the current shell, not in a subshell) when you log in. Just changing the value there and then restarting a process will not update the environment. Possible Fixes: * log out/log in, then start apache * source the file: `# . /etc/profile.d/foo.sh`, then restart apache * source the file in the apache init script You also need to make sure that `/etc/profile.d/` is sourced when Apache is started by `init` rather than yourself. The best fix might also depend on the distribution you are using, because they use different schemes for configuration.