instruction
stringlengths
21
27.8k
chosen
stringlengths
18
28.2k
rejected
stringlengths
18
33.6k
__index_level_0__
int64
0
50k
<p>I want to call a c# function from my javascript function.</p> <p>I have a link button in my ascx (please see the code below). The problem is that if you press enter in firefox is not working however it is working fine in internet explorer.</p> <pre><code>&lt;li class="clearfix border_top"&gt; &lt;label for="title" class="first_column bold"&gt;Search For&lt;/label&gt; &lt;div class="contactUs_details"&gt; &lt;input type="text" id="advanced_txtBox1" name="advanced_txtBox1" class="searchbox" runat="server" style="width:300px;" /&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; &lt;asp:CheckBox ID="chkSearchBDJ" runat="server" Text="Search BDJ" CssClass="checkboxlistnoborder" /&gt; &lt;/div&gt; &lt;/li&gt; &lt;div class="img_SearchNow"&gt; &lt;asp:LinkButton ID="btnSearchNow" CausesValidation="true" runat="server" OnClick="btnSearchNow_Click"&gt;&lt;/asp:LinkButton&gt; &lt;/div&gt; </code></pre> <p>I have linkButton see above on which I have called on c# function on Click, But if you pree some text in above textbox and press "Enter" it should automatically call function "btnSearchNow_Click". It is working fine in IE but not working in Firefox.</p>
<p>This can't be done with the normal <code>printf</code> format specifiers. The closest you could get would be:</p> <pre><code>printf("%.6g", 359.013); // 359.013 printf("%.6g", 359.01); // 359.01 </code></pre> <p>but the ".6" is the <em>total</em> numeric width so</p> <pre><code>printf("%.6g", 3.01357); // 3.01357 </code></pre> <p>breaks it.</p> <p>What you <em>can</em> do is to <code>sprintf("%.20g")</code> the number to a string buffer then manipulate the string to only have N characters past the decimal point.</p> <p>Assuming your number is in the variable num, the following function will remove all but the first <code>N</code> decimals, then strip off the trailing zeros (and decimal point if they were all zeros).</p> <pre><code>char str[50]; sprintf (str,"%.20g",num); // Make the number. morphNumericString (str, 3); : : void morphNumericString (char *s, int n) { char *p; int count; p = strchr (s,'.'); // Find decimal point, if any. if (p != NULL) { count = n; // Adjust for more or less decimals. while (count &gt;= 0) { // Maximum decimals allowed. count--; if (*p == '\0') // If there's less than desired. break; p++; // Next character. } *p-- = '\0'; // Truncate string. while (*p == '0') // Remove trailing zeros. *p-- = '\0'; if (*p == '.') { // If all decimals were zeros, remove ".". *p = '\0'; } } } </code></pre> <hr> <p>If you're not happy with the truncation aspect (which would turn <code>0.12399</code> into <code>0.123</code> rather than rounding it to <code>0.124</code>), you can actually use the rounding facilities already provided by <code>printf</code>. You just need to analyse the number before-hand to dynamically create the widths, then use those to turn the number into a string:</p> <pre><code>#include &lt;stdio.h&gt; void nDecimals (char *s, double d, int n) { int sz; double d2; // Allow for negative. d2 = (d &gt;= 0) ? d : -d; sz = (d &gt;= 0) ? 0 : 1; // Add one for each whole digit (0.xx special case). if (d2 &lt; 1) sz++; while (d2 &gt;= 1) { d2 /= 10.0; sz++; } // Adjust for decimal point and fractionals. sz += 1 + n; // Create format string then use it. sprintf (s, "%*.*f", sz, n, d); } int main (void) { char str[50]; double num[] = { 40, 359.01335, -359.00999, 359.01, 3.01357, 0.111111111, 1.1223344 }; for (int i = 0; i &lt; sizeof(num)/sizeof(*num); i++) { nDecimals (str, num[i], 3); printf ("%30.20f -&gt; %s\n", num[i], str); } return 0; } </code></pre> <p>The whole point of <code>nDecimals()</code> in this case is to correctly work out the field widths, then format the number using a format string based on that. The test harness <code>main()</code> shows this in action:</p> <pre><code> 40.00000000000000000000 -&gt; 40.000 359.01335000000000263753 -&gt; 359.013 -359.00999000000001615263 -&gt; -359.010 359.00999999999999090505 -&gt; 359.010 3.01357000000000008200 -&gt; 3.014 0.11111111099999999852 -&gt; 0.111 1.12233439999999995429 -&gt; 1.122 </code></pre> <p>Once you have the correctly rounded value, you can once again pass that to <code>morphNumericString()</code> to remove trailing zeros by simply changing:</p> <pre><code>nDecimals (str, num[i], 3); </code></pre> <p>into:</p> <pre><code>nDecimals (str, num[i], 3); morphNumericString (str, 3); </code></pre> <p>(or calling <code>morphNumericString</code> at the end of <code>nDecimals</code> but, in that case, I'd probably just combine the two into one function), and you end up with:</p> <pre><code> 40.00000000000000000000 -&gt; 40 359.01335000000000263753 -&gt; 359.013 -359.00999000000001615263 -&gt; -359.01 359.00999999999999090505 -&gt; 359.01 3.01357000000000008200 -&gt; 3.014 0.11111111099999999852 -&gt; 0.111 1.12233439999999995429 -&gt; 1.122 </code></pre>
<p>Your code rounds to three decimal places due to the ".3" before the f</p> <pre><code>printf("%1.3f", 359.01335); printf("%1.3f", 359.00999); </code></pre> <p>Thus if you the second line rounded to two decimal places, you should change it to this:</p> <pre><code>printf("%1.3f", 359.01335); printf("%1.2f", 359.00999); </code></pre> <p>That code will output your desired results:</p> <pre><code>359.013 359.01 </code></pre> <p>*Note this is assuming you already have it printing on separate lines, if not then the following will prevent it from printing on the same line:</p> <pre><code>printf("%1.3f\n", 359.01335); printf("%1.2f\n", 359.00999); </code></pre> <p>The Following program source code was my test for this answer</p> <pre><code>#include &lt;cstdio&gt; int main() { printf("%1.3f\n", 359.01335); printf("%1.2f\n", 359.00999); while (true){} return 0; } </code></pre>
35,057
<p>I've been using MVC frameworks for a short while now and I really like how the concerns are separated out. I've got into a bad habit of letting the controllers do quite a bit of work. So I'm really looking for some advice.</p> <p>When I first started using MVC I quite often had the controller doing manipulation on the models after database work had been done. I knew this was bad so moved that work into the models. However I'm not happy with that as I want my models to be very learn.</p> <p>I've done a bit of reading and I see that people are keeping their controllers and models lean by having a service layer, which I like the look of. </p> <p>I'm just trying to understand how a service layer and repository should all work together. Here are my assumptions, can you please let me know if this is a good way of working?</p> <ol> <li>The controller can call the repository directly if no manipulation needs to be done on the data and as such a service layer does not need to get involved</li> <li>Once any work needs to be done to data (business logic) then this should be done in the service layer and the controller will make a simple call to the service layer as and when required</li> <li>Once a service has done it's business logic it will then use the repository as necessary (if data needs to be persisted).</li> <li>Models ideally should be kept lean, ideally actings as nothing more than DTOs</li> <li>Validation of data will be done within the models (using MonoRail validation attributes). I appreciate not even one likes polluting their models with lots of attributes, but that is a different discussion. I like the benefit of MonoRail's validation attributes for the automatic jQuery validation in the UI.</li> </ol> <p>I'm trying to turn all my code around to the single responsibility principle, hence trying to sort out my coding practices.</p> <p>Thanks</p>
<p>First, there is no set of rules that's going to work in every situation. How you model you're application depends a lot on the type and complexity of the project. Having said that, here are some ideas:</p> <ol> <li>Nothing wrong with calling the repository from a controller. Just make sure the controller does not contain business logic. </li> <li>The service takes care of (some) business logic and uses other services to do so. The repository is a type of service, there's nothing wrong with calling it from a service.</li> <li>The model <strong>should</strong> contain business logic, actually you should always try to put it in the model first. If you need external data to perform that business logic (from another model or from the repository) then you should create a service.</li> <li>Nothing wrong with validation in the models. Using attributes or not is a question of taste (if you like it then it's good). Move the validation outside of the model if it gets too complex (create a external set of rules).</li> </ol> <p>Most important, do what feels right (that's usually the right answer). </p>
<p>Ian Cooper has just written a blog post called <a href="http://codebetter.com/blogs/ian_cooper/archive/2008/12/03/the-fat-controller.aspx" rel="noreferrer">The Fat Controller</a> on just this subject.</p>
42,232
<p>When I am editing a cell in a <code>dataGrid</code>, the changes are not applied to the <code>dataProvider</code> until I finish editing. Is there a way that I can make the changes appear in the <code>dataProvider</code> whilst editing?</p> <p>I would assume that the way of doing this would be to subclass the editor I am using, in this case <code>NumericStepper</code>, but I don't know how I would go about it.</p> <p>Is there some sort of event that I need to trigger?</p>
<p>A few notes:</p> <ol> <li><p>You will save yourself a lot of trouble by just using a <code>&lt;table&gt;</code> for this data, which is tabular. </p></li> <li><p>Building this stuff via the DOM is insanely slow compared to letting the browser just render raw HTML. Just something to be aware of.</p></li> </ol> <p>Anyway, I'd immediately try floating the container div <code>.cssDivNino</code> left as well, explicitly setting top and bottom margins to 0, and keeping a close eye on <a href="http://www.positioniseverything.net/explorer/floatIndent.html" rel="nofollow noreferrer">IE6's suite of float/margin bugs.</a></p>
<p>I agree with Tpiptych but for arguments sake if I wanted to accomplish this I'd end up using different styles sheets for the defect browser (in this case IE6). </p> <p>Be aware, that you may not be able to get 100% of the same look and you may need to design a slightly different look for IE6. </p> <p>Even after I write this, I'd still endorse the &lt;table> solution. </p> <p>HTH!</p> <p>Regards,<br>Frank</p>
49,998
<p>The docs for <a href="http://msdn.microsoft.com/en-us/library/bb347013.aspx" rel="noreferrer">Dictionary.TryGetValue</a> say:</p> <blockquote> <p>When this method returns, [the value argument] contains the value associated with the specified key, if the key is found; otherwise, the <strong>default value for the type of the value parameter</strong>. This parameter is passed uninitialized.</p> </blockquote> <p>I need to mimic this in my class. <em>How do I find the default value for type T?</em></p> <hr> <p>How can this question be modified to make it show up in the search?</p> <p>Exact duplicate of <a href="https://stackoverflow.com/questions/367378/returning-a-default-value-c">Returning a default value. (C#)</a></p>
<p>You are looking for this:</p> <pre><code>default(T); </code></pre> <p>so:</p> <pre><code>public T Foo&lt;T&gt;(T Bar) { return default(T); } </code></pre>
<p>Using the <a href="http://msdn.microsoft.com/en-us/library/xwth0h0d(VS.80).aspx" rel="noreferrer">default</a> keyword:</p> <pre><code>T t = default(T) </code></pre>
48,330
<p>When I write an app, I use the System.Data interfaces (IDbConnection, IDbCommand, IDataReader, IDbDataParameter, etc...). I do this to reduce vendor dependencies. Unless, I'm doing a simple test app, it just seems like the ethical thing to do when consulting.</p> <p>However, it seems like all the code I see uses the System.Data.SqlClient namespace classes or other vendor specific classes. In magazines and books it's easy to chalk this up to Microsoft influence and their marketing spin to program only against SQLServer. But it seams like almost all the .NET code I see uses the SQLServer specific classes.</p> <p>I realize the vendor specific classes have more functionality, for example adding a parameter to a SqlCommand object is one method, where as adding it to an IDbCommand is an irritating 4+ lines of code. But then again; writing a little helper class for these limitations is pretty simple.</p> <p>I've also wondered if programming against the interfaces when SQLServer is the current target client is over-engineering since it is not required immediately. But I don't think it is since the cost of programming against the interfaces is so low, where as reducing vendor dependency provides such a huge benefit.</p> <p>Do you use vendor specific data classes or the interfaces?</p> <p>EDIT: To summarize some of the answers below, and throw in some thought's I had while reading them.</p> <p>Possible pitfalls to using interfaces for vendor neutrality:</p> <ul> <li>Vendor specific keywords embedded in your SELECT statements (all my ins, upd, &amp; del's are in procs, so that's not a problem) </li> <li>Binding directly the database would probably cause issues. </li> <li>Unless your connection instantiation is centralized, the vendor specific class will need to be called anyway.</li> </ul> <p>Positive reasons to use interfaces :</p> <ul> <li>In my experience the ability (even if not exercised) to move to a different vendor has always been appreciated by the customer.</li> <li>Use interfaces in reusable code libraries</li> </ul>
<p>There are differences to the SQL you're going to have to give the classes, depending on the type of database engine you're talking to, so even if you manage to write all your code to use the interfaces, you still need to write multiple sets of SQL.</p> <p>Or, you can do what we have done, write our own layer that takes care of all the syntax we use, which isn't all the syntax provided by the different engines, but enough to manage to write one SQL that gets properly rewritten before execution.</p> <p>Basically we've created a function syntax where we prefix the names of the functions with <code>SQL::</code>, which lets our code identify the special functions that needs to be rewritten. These are then parsed out, and rewritten properly, even so far as to swap around argument order if necessary.</p> <p>Small things like the name of the function that returns the current server date and time can be done, but also bigger things, like how to select the first N rows of a query.</p> <p>Additionally, parameters for SQL Server is written as @name, where OleDb uses positional (just add a ? where you want the parameter), and our code handles those differences as well.</p> <p>It pays off in the sense that we don't worry much about the SQL that needs to be written.</p>
<p>Take a look at Microsoft's Patterns and Practices group's Enterprise library. The data access code they have there shows some good implementations of provider independence.</p> <p><a href="http://msdn.microsoft.com/en-us/library/cc467894.aspx" rel="nofollow noreferrer">http://msdn.microsoft.com/en-us/library/cc467894.aspx</a></p>
45,632
<p>I am in charge of providing a theme functionality for a site using a big CSS file (thousands of elements) I've just inherited. Basically we want to allow the user to be able to change the colors on the screen.</p> <p>Every CSS element, besides color definition also have lots of other attributes - size, font, float, etc... As well a specific color appears in various CSS elements.</p> <p>If I use the Theme functionality of ASP.NET to have a different CSS file per theme, I have to duplicate my CSS file across all the themes, and it becomes a maintenance nightmare. </p> <p>Optimally I would like to have a single CSS file (for maintenance) and be able to change the color attributes only.</p> <p>What are the options here?</p>
<p>You only have to duplicate the color attributes so if you have </p> <pre><code>a:hover { text-decoration:none; color:Black; display:block } </code></pre> <p>in your css file in your theme you only need:</p> <pre><code>a:hover { color:Red; } </code></pre> <p>Now in your page you want to make sure you still reference the original css file, and the browser will merge all the styles.</p>
<p>Remember: elements can have multiple style classes. Since the layout remains static and will be separate from the coloring, you want to define classes for layout and color separately, in completely different files.</p> <p>So what you want to do for themes is define a few colors in a separate css file like this:</p> <pre><code>.DefaultBackgroundColor { background-color: white; } .PrimaryColor { background-color: #123456; } .PrimaryAsForeground { color: #123456; } .AccentColor { background-color: #654321; } .AccentAsForeground { color: #654321; } .ComplementColor { background-color: #333333; } .ComplementAsForeground { color: #333333; } .DefaultTextColor { color:black; } .HighlightTextColor { color:black; font-style:bold; } .ComplementTextColor { color:white; } </code></pre> <p>You can add more colors, but you get the idea. Then, in your HTML you add those classes to elements in addition to layout classes. For example, using these classes you might style the Nav buttons for StackOverflow like this:</p> <pre><code>&lt;div class="nav ComplementTextColor"&gt; &lt;ul class="primarynav"&gt; &lt;li class="PrimaryColor"&gt;&lt;a href="/questions"&gt;Questions&lt;/a&gt;&lt;/li&gt; &lt;!-- selected --&gt; &lt;li class="ComplementColor"&gt;&lt;a href="/tags"&gt;Tags&lt;/a&gt;&lt;/li&gt; &lt;li class="ComplementColor"&gt;&lt;a href="/users"&gt;Users&lt;/a&gt;&lt;/li&gt; &lt;li class="ComplementColor"&gt;&lt;a href="/badges"&gt;Badges&lt;/a&gt;&lt;/li&gt; &lt;li class="ComplementColor"&gt;&lt;a href="/unanswered"&gt;Unanswered&lt;/a&gt;&lt;/li&gt; &lt;/ul&gt; &lt;/div&gt; </code></pre> <p>Obviously those colors are made up and won't work together, but that's the beauty of this set up. This makes it real easy to play with and tweak your colors, since you don't have to define the same color all over the place. You set it up once and then only need to make a very small number of changes to completely re-color the site.</p> <p>The downside is you are limited. Using the html I posted, for example, you couldn't then go and make the buttons here a different color from everything else just by changing the css file, because we didn't set up 'hook' for it. But you could change that ugly orange color they user here across the board with one simple edit.</p>
46,612
<p>What is current state of the art for enabling OpenID login in Ruby on Rails applications? This is a community wiki with up-to-date answers to this question.</p> <h2>Authlogic</h2> <p>The most advanced authentication solution seems to be <a href="http://github.com/binarylogic/authlogic" rel="noreferrer">Authlogic</a>. It supports OpenID with <a href="http://github.com/binarylogic/authlogic_openid" rel="noreferrer">Authlogic OpenID plugin</a>. It supports Rails 4 and 3. Rails 2 is supported in the rails2 branch.</p> <p>You may want to watch <a href="http://railscasts.com/episodes/170-openid-with-authlogic" rel="noreferrer">&quot;OpenID with Authlogic&quot; railscast</a> (and the <a href="http://railscasts.com/episodes/160-authlogic" rel="noreferrer">&quot;Authlogic&quot; railscast</a>).</p> <p>There is a sample application called <a href="http://github.com/shripadk/authlogic_openid_selector_example" rel="noreferrer">Authlogic OpenID Selector Example</a>.</p> <h2>Devise</h2> <p>Devise is flexible authentication framework for Rails. It supports OpenID with <a href="https://github.com/nbudin/devise_openid_authenticatable" rel="noreferrer"><code>devise_openid_authenticatable</code></a>.</p> <h2>restful_authentication</h2> <p>Another authentication library of choice is <a href="http://github.com/technoweenie/restful-authentication" rel="noreferrer"><code>restful_authentication</code></a> Rails plugin. Seems like you also need to install <a href="http://github.com/rails/open_id_authentication" rel="noreferrer"><code>open_id_authentication</code></a> plugin.</p> <p>You may want to watch (old, circa 2007) <a href="http://railscasts.com/episodes/68-openid-authentication" rel="noreferrer">&quot;OpenID Authentication&quot; railscast</a>.</p> <h2>Ruby OpenID</h2> <p>Raw support for OpenID protocol is handled by <a href="http://github.com/openid/ruby-openid" rel="noreferrer">Ruby OpenID</a> library.</p>
<p>Check out this <a href="http://railscasts.com/episodes/68-openid-authentication" rel="nofollow noreferrer">Railscast on OpenId</a> for more info. I'm not sure if/how it might work alongside restful_authentication, but might be a good resource. (I haven't watched it yet)</p>
<p>Keep an eye on <a href="http://jimneath.org/2008/09/09/bort-base-rails-application/" rel="nofollow noreferrer">Bort</a>. It is a base rails application which already has restful_authentication setup among other things. The guy doing it is planning on adding OpenID.</p>
9,244
<p>I'd like to do some work with the nitty-gritties of computer imaging. I'm looking for a way to read single pixels of data, analyze them programatically, and change them. What is the best language to use for this (Python, c++, Java...)? What is the best fileformat?</p> <p>I don't want any super fancy software/APIs... I'm looking for the bare basics.</p>
<p>If you need speed (you'll probably always want speed with image processing) you definitely have to work with raw pixel data. Java has some real disadvantages as you cannot access memory directly which makes pixel access quite slow compared to accessing the memory directly. C++ is definitely the language of choice for production use image processing. But you can, for example, also use C# as it allows for unsafe code in specific areas. (Take a look at the scan0 pointer property of the bitmapdata class.) I've used C# successfully for image processing applications and they are definitely much faster than their java counterparts. I would not use any scripting language or java for such a purpose.</p>
<p>Short answer? I'd say C++, you have far more flexibility in manipulating raw chunks of memory than Python or Java.</p>
17,269
<p>How do you measure the memory usage of an application or process in Linux?</p> <p>From the blog article of <em><a href="http://virtualthreads.blogspot.com/2006/02/understanding-memory-usage-on-linux.html" rel="noreferrer">Understanding memory usage on Linux</a></em>, <code>ps</code> is not an accurate tool to use for this intent.</p> <blockquote> <p><strong>Why <code>ps</code> is &quot;wrong&quot;</strong></p> <p>Depending on how you look at it, <code>ps</code> is not reporting the real memory usage of processes. What it is really doing is showing how much real memory each process would take up <strong>if it were the only process running</strong>. Of course, a typical Linux machine has several dozen processes running at any given time, which means that the VSZ and RSS numbers reported by <code>ps</code> are almost definitely <em>wrong</em>.</p> </blockquote> <p><sub>(Note: This question is covered <a href="https://stackoverflow.com/q/63166/15161">here</a> in great detail.)</sub></p>
<p>With <code>ps</code> or similar tools you will only get the amount of memory pages allocated by that process. This number is correct, but:</p> <ul> <li><p>does not reflect the actual amount of memory used by the application, only the amount of memory reserved for it</p> </li> <li><p>can be misleading if pages are shared, for example by several threads or by using dynamically linked libraries</p> </li> </ul> <p>If you really want to know what amount of memory your application actually uses, you need to run it within a profiler. For example, <a href="https://en.wikipedia.org/wiki/Valgrind" rel="noreferrer">Valgrind</a> can give you insights about the amount of memory used, and, more importantly, about possible memory leaks in your program. The heap profiler tool of Valgrind is called 'massif':</p> <blockquote> </blockquote> <p>Massif is a heap profiler. It performs detailed heap profiling by taking regular snapshots of a program's heap. It produces a graph showing heap usage over time, including information about which parts of the program are responsible for the most memory allocations. The graph is supplemented by a text or HTML file that includes more information for determining where the most memory is being allocated. Massif runs programs about 20x slower than normal.</p> <p>As explained in the <a href="http://valgrind.org/docs/manual/ms-manual.html" rel="noreferrer">Valgrind documentation</a>, you need to run the program through Valgrind:</p> <pre><code>valgrind --tool=massif &lt;executable&gt; &lt;arguments&gt; </code></pre> <p>Massif writes a dump of memory usage snapshots (e.g. <code>massif.out.12345</code>). These provide, (1) a timeline of memory usage, (2) for each snapshot, a record of where in your program memory was allocated. A great graphical tool for analyzing these files is <a href="https://github.com/KDE/massif-visualizer" rel="noreferrer">massif-visualizer</a>. But I found <code>ms_print</code>, a simple text-based tool shipped with Valgrind, to be of great help already.</p> <p>To find memory leaks, use the (default) <code>memcheck</code> tool of valgrind.</p>
<p>Use the in-built <em>System Monitor</em> GUI tool available in Ubuntu.</p>
15,938
<p><strong>Duplicate of:</strong> <a href="https://stackoverflow.com/questions/203113/use-javascript-to-inject-script-references-as-needed">Use javascript to inject script references as needed?</a></p> <p>Javascript doesn't have any directive to "include" or "import" another js file. This means that if <code>script1.js</code> uses functions/objects defined in <code>script2.js</code>, then every html page that includes script1.js must include script2.js before it.</p> <p>This shouldn't be a big problem if you only have 2 js files in like 10 html pages. I mean, it's manageable then!</p> <p>But say suddenly you change <code>script1.js</code> and improve it by using functions/objects defined in a new file, <code>script3.js</code> <br> The problem is, you can't just tell <code>script1.js</code> to include <code>script3.js</code>, instead, you have to remember every html file that included <code>script1.js</code> and update it to include <code>script3.js</code> as well!</p> <p>This seems like rather stupid way of organizing code.</p> <p>Are there recommended strategies or practices to deal with this issue?</p> <p>Would it be acceptable to have a gigantic js file that holds all the functionality that you use across the website?</p>
<p>Use dynamic includes:</p> <p><a href="https://stackoverflow.com/questions/203113/use-javascript-to-inject-script-references-as-needed">Use javascript to inject script references as needed?</a></p>
<p>I guess you could use document.write in your JS files to make sure they include whatever dependencies they're dependent upon, though I wouldn't really recommend it...</p>
40,807
<p>It's rare that I hear someone using <a href="http://martinfowler.com/articles/injection.html" rel="nofollow noreferrer">Inversion of Control (Ioc)</a> principle with .Net. I have some friends that work with Java that use a lot more Ioc with Spring and PicoContainer.</p> <p>I understand the principle of removing dependencies from your code... but I have a doubt that it's so much better.</p> <p><strong>Why do .Net programmers not use (or use less) those types of frameworks? If you do, do you really find a positive effect in the long term?</strong></p>
<p>Lots of people use IOC in .NET, and there are several frameworks available to assist with using IoC. You may see it less in the WinForms side of things, because it's harder to just let the container wire everything together when you are designing forms in Visual Studio, but I can say that for server-side .NET applications, where I work at least, IoC is used very successfully.</p> <p>Why use it in .NET? For the same reason you use it everywhere else. The 2 biggest things I like are:</p> <ul> <li>Designing for IoC tends to enforce good coding practice - designing to interfaces, low coupling, high cohesion. This also leads to classes that are very easy to unit-test.</li> <li>System configuration can often be changed without recompiling.</li> </ul> <p>Some other posts discussing the different IoC/DI frameworks available for .NET:</p> <ul> <li><a href="https://stackoverflow.com/questions/21288/which-cnet-dependency-injection-frameworks-are-worth-looking-into">Which C#/.net Dependency Injection frameworks are worth looking into?</a></li> <li><a href="https://stackoverflow.com/questions/148908/which-dependency-injection-tool-should-i-use">Which Dependency Injection Tool Should I Use?</a></li> </ul>
<p>I use it to allow my Unit tests to substitute Mock Classes (simulating actual production classes) for upstream dependant objects so that my unit tests truly only execute and test the code in the one class.method they are written to test.</p>
31,162
<p>If I have the following string:</p> <pre><code>string s = "abcdefghab"; </code></pre> <p>Then how do I get a string (or char[]) that has just the characters that are repeated in the original string using C# and LINQ. In my example I want to end up with "ab".</p> <p>Although not necessary, I was trying to do this in a single line of LINQ and had so far come up with:</p> <pre><code>s.ToCharArray().OrderBy(a =&gt; a)... </code></pre>
<p>There isn't likely to be a foolproof method, as that's an intrusion into the privacy of the user. </p> <p>One thing that comes to mind is checking for a referrer. If the user arrived at your page without following a link, they a) typed the url, b) followed a bookmark, or c) have your page set as their homepage. But that's about the best I can do. </p>
<p>Simple solution, you shouldn't be checking if you or anyone else's site is set as the user's homepage. If they want it as their homepage, they'll make it so. </p> <p>However, if you've got some Javascript that will check their email and see if they've sent links to your site to their friends or colleagues, I'd be <strong>very</strong> interested in that functionality ;-)</p>
30,440
<p>On a page I want to dynamically list years and all the months in each year so an archive for each month can be viewed. I want to show the current year first but the current year may not be over yet so I only want to show the months that have passed, and the current month. Then I want all years and all months in the past since this year (i.e. 2008).</p> <p>The PHP code I have created that does the job is below. Is there a more efficient way of achieving this? I am running PHP 5.2.</p> <pre><code>$current_year = date('Y'); $months = array(1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12); // Loop through all the months and create an array up to and including the current month foreach ($months as $month) { if ($month &lt;= date('m')) { switch ($month) { case 1: $years[$current_year][] = 'January'; break; case 2: $years[$current_year][] = 'February'; break; case 3: $years[$current_year][] = 'March'; break; case 4: $years[$current_year][] = 'April'; break; case 5: $years[$current_year][] = 'May'; break; case 6: $years[$current_year][] = 'June'; break; case 7: $years[$current_year][] = 'July'; break; case 8: $years[$current_year][] = 'August'; break; case 9: $years[$current_year][] = 'September'; break; case 10: $years[$current_year][] = 'October'; break; case 11: $years[$current_year][] = 'November'; break; case 12: $years[$current_year][] = 'December'; break; } } } // Previous years $years_to_create = $current_year - 2008; if (!empty($years_to_create)) { for ($i = 1; $i &lt;= $years_to_create; $i++) { $years[$current_year - $i] = array('January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December'); } } </code></pre>
<pre><code>$current_year = date('Y'); $months = array(1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12); $month_names = array('January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December'); // Loop through all the months and create an array up to and including the current month for ($month=1;$month&lt;=date('m');$month++) { $years[$current_year][] = $month_names[$month-1]; } // Previous years $years_to_create = $current_year - 2008; if (!empty($years_to_create)) { for ($i = 1; $i &lt;= $years_to_create; $i++) { $years[$current_year - $i] = $month_names; } } </code></pre> <p>This seems a little simpler...is it any faster...?</p>
<p>PHP has a Date() function and an mktime function, you can use these to compare dates and to create dates out of strings etc. Without providing code, i can give you an instruction to somehow make an iteration:</p> <pre><code> -&gt; Get current Year -&gt; Loop the current year untill the current month is reached -&gt; Print Month </code></pre>
43,821
<p>I am reading a .NET book, and in one of the code examples there is a class definition with this field:</p> <pre><code>private DateTime? startdate </code></pre> <p>What does <code>DateTime?</code> mean?</p>
<p>Since <code>DateTime</code> is a <code>struct</code>, not a <code>class</code>, you get a <code>DateTime</code> <em>object</em>, not a <em>reference</em>, when you declare a field or variable of that type. </p> <p>And, in the same way as an <code>int</code> cannot be <code>null</code>, so this <code>DateTime</code> object can never be <code>null</code>, because it's not a reference.</p> <p>Adding the question mark turns it into a <a href="http://msdn.microsoft.com/en-us/library/1t3y8s4s%28v=vs.80%29.aspx" rel="noreferrer"><em>nullable type</em></a>, which means that <em>either</em> it is a <code>DateTime</code> object, <em>or</em> it is <code>null</code>.</p> <p><code>DateTime?</code> is syntactic sugar for <code>Nullable&lt;DateTime&gt;</code>, where <a href="http://msdn.microsoft.com/en-us/library/b3h38hb0%28v=vs.80%29.aspx" rel="noreferrer"><code>Nullable</code></a> is itself a <code>struct</code>.</p>
<pre><code>public class ReportsMapper : CommonMapper { public DateTime? cb_Bill_From_Date { get; set; } public DateTime? cb_Bill_To_Date { get; set; } public DateTime? tff_Bill_From_Date { get; set; } public DateTime? tff_Bill_To_Date { get; set; } } </code></pre> <p>If you declare DateTime As Null In Procedure Then You get an error stating DateTime Object Can never be Null so you need to add ? After DateTime that will say DateTime is Nullable too. </p> <p>Hope This Help!</p>
13,512
<p>An integer's max value in Java is 2147483647, since Java integers are signed, right?</p> <p>0xff000000 has a numeric value of 4278190080.</p> <p>Yet I see Java code like this:</p> <pre><code>int ALPHA_MASK = 0xff000000; </code></pre> <p>Can anyone enlighten me please?</p>
<p>The high bit is a sign bit. Setting it denotes a negative number: -16777216. </p> <p>Java, like most languages, stores signed numbers in <a href="http://en.wikipedia.org/wiki/Two%27s_complement" rel="noreferrer">2's complement</a> form. In this case, subtracting 2<sup>31</sup>, or 2147483648 from 0x7F000000, or 2130706432, yields -16777216.</p>
<p>ints are signed in Java.</p>
41,266
<p>With ASP.NET 3.5 I can easily bind to an XML file by using an <code>XmlDataSource</code>.</p> <p>How can I bind to an XML <em>string</em> instead of a <em>file</em>?</p>
<p>Use the <a href="http://msdn.microsoft.com/en-us/library/system.web.ui.webcontrols.xmldatasource.data.aspx" rel="nofollow noreferrer">XmlDataSource.Data</a> property.</p> <pre><code>XmlDataSource dataSource = new XmlDataSource(); dataSource.Data = "&lt;root&gt;&lt;element&gt;Item #1&lt;/element&gt;&lt;element&gt;Item #2&lt;/element&gt;&lt;/root&gt;"; dataSource.XPath = "root/element"; dataSource.DataBind(); </code></pre> <p>Alternately, you could specify the data declaratively:</p> <pre><code>&lt;asp:xmldatasource id="XmlDataSource1" runat="server" &gt; &lt;data&gt; &lt;Books&gt; &lt;LanguageBooks&gt; &lt;Book Title="Pure JavaScript" Author="Wyke, Gilliam, and Ting"/&gt; &lt;Book Title="Effective C++ Second Edition" Author="Scott Meyers"/&gt; &lt;Book Title="Assembly Language Step-By-Step" Author="Jeff Duntemann"/&gt; &lt;Book Title="Oracle PL/SQL" Author="Steven Feuerstein"/&gt; &lt;/LanguageBooks&gt; &lt;SecurityBooks&gt; &lt;Book Title="Counter Hack" Author="Ed Skoudis"/&gt; &lt;/SecurityBooks&gt; &lt;/Books&gt; &lt;/data&gt; &lt;/asp:xmldatasource&gt; </code></pre>
<p>From the XmlDataSource docs <a href="http://msdn.microsoft.com/en-us/library/system.web.ui.webcontrols.xmldatasource.aspx" rel="nofollow noreferrer">here:</a> </p> <blockquote> <p><em>XML data can also be stored directly by the data source control in string form using the Data property</em>.</p> </blockquote>
41,707
<p>I am adding a context menu using <code>QAction</code> for a widget. Now, there is some white space beside the text of the action. I assume this is the space where the <code>QIcon</code> association with the <code>QAction</code> should have been there. Now how do I hide this space. I tried doing:</p> <pre><code>action-&gt;setIcon(QIcon()); </code></pre> <p>but still does not seem to work.</p> <p>Kindly let me know if you have the way to remove that space before the text.</p>
<p>I don't know if there is a way specific to the action or the menu, but you could probably remove it using a style.</p>
<p>You didn't mention the version of Qt you are using but version 4.4.3's QAction allows you to hide the icon:<br> <a href="http://doc.trolltech.com/4.4/qaction.html#iconVisibleInMenu-prop" rel="nofollow noreferrer">http://doc.trolltech.com/4.4/qaction.html#iconVisibleInMenu-prop</a><br> <br> You can also try using the <code>QAction::QAction ( const QString &amp; text, QObject * parent )</code> constructor:<br> <a href="http://doc.trolltech.com/4.4/qaction.html#QAction-2" rel="nofollow noreferrer">http://doc.trolltech.com/4.4/qaction.html#QAction-2</a> (4.4.3)<br> <a href="http://doc.trolltech.com/4.0/qaction.html#QAction-2" rel="nofollow noreferrer">http://doc.trolltech.com/4.0/qaction.html#QAction-2</a> (4.0)<br> <a href="http://doc.trolltech.com/3.3/qaction.html#QAction-2" rel="nofollow noreferrer">http://doc.trolltech.com/3.3/qaction.html#QAction-2</a> (3.3)<br></p>
25,568
<p>I need to migrate a large project from StarTeam 5 to Subversion, and I'd like to keep snapshots of (at least) 5-10 of the major releases. I've considered the following:</p> <ul> <li>Manual or scripted export/import of each snapshot. Advantages: straightforward, easy to select labeled/dated versions. Disadvantages: time-consuming, does not preserve comments.</li> <li>Polarion offers what seems to be the perfect tool in svnimporter, but it requires a .jar file from StarTeam 8.0 that is not present in StarTeam 5. Advantages: automated, complete. Disadvantages: requires upgrade to StarTeam 8.0 for one-time use.</li> <li>Migrate via some intermediate repository (<em>e.g.</em> StarTeam -> CVS -> Subversion). I haven't yet found any intermediary that will cooperate with StarTeam.</li> <li>Migrate only the latest source. Advantages: simple, fast, encourages developers to invent new solutions rather than repeating history. Disadvantage: encourages developers to invent new solutions rather than repeating history. :-)</li> </ul> <p>I'd appreciate any experiences or suggestions you might offer. Thank you.</p>
<p>Having not used StarTeam I cannot speak to that -- but I think you've laid out some nice options. </p> <ol> <li>Scripted import seems like it could be time consuming, not really get you everything, but at the same time, be a reliable way to get into svn and still preserve your release history. </li> <li>What is the real downside of upgrading and throwing away the install after? Do you have to re-purchase the software? Is it a tedious upgrade? Barring that, it sounds like this may just be the best option.</li> <li>I would really stay away from this option. cvs -> svn import is pretty shaky (really, it's a one-off thing, probably not that many individual people work on it enough to really care about making it perfect). Going from another SCM system to cvs, and THEN to svn sounds like a recipe for useless history data and frustration. :) I've only done it a couple of times, and really, the best part is once you're done, you're in svn and never touch cvs again. </li> <li>This option does really suck. You lose all your history.. can no longer <em>blame</em> other dev's for screwing things up.. On the upside though, it will absolutely work, if all else fails.</li> </ol>
<p>I'm struggling to migrate StarTeam 8 to SVN using the Polarion kit. I'm getting:</p> <p>[main] DEBUG STProvider:80 - checkout ...relative/path/to/build.xml version:1.0 09:25:10,378</p> <p>[main] INFO historyLogger:84 - EXCEPTION CAUGHT: java.lang.UnsatisfiedLinkError: com.starbase.util.NativeFileAccess.setLastModifiedAsLong(Ljava/lang/String;J)V</p> <p>and the target file exists, but I suspect that it's unable to resolve the relative path. Do you know if there are properties (other than the ones in the config.properties file) that can be set to control this?</p>
27,159
<p>I am working on a web app that uses Perl and I need to look into speeding up portions of the app. </p> <p>I thought I'd start profiling the particular calls for the portion I wish to investigate. I've done some searching on profiling Perl code, but unfortunately most of what I find says that I should run my perl code with <code>-d:DProf myapp</code> from the command line. That doesn't quite work for me since my code is within a web app. I did find a way to get the profiling to work with apache, but unfortunately, the "most used" modules that came back from the profiler were all CPAN modules -- Class::xyz, etc etc etc. Not terribly helpful.</p> <p>Does anyone know of a good way besides me injecting "timer" code into the methods I wish to profile to target just these methods? I've thought of writing a test script and profiling that but due to the nature of the code I'm working on that would require a bit more work than I'm hoping to have to do. </p>
<p>Have you tried <A href="http://search.cpan.org/dist/Devel-NYTProf" rel="nofollow noreferrer">Devel::NYTProf</a> (much better than Devel::DProf), which can work under Apache? Which webserver are you using? Is this a vanilla CGI script, a mod_perl thing, or something else?</p> <p>If you're doing database stuff, the <a href="http://www.metacpan.org/module/DBI::Profile" rel="nofollow noreferrer">DBI::Profile</a> can benchmark your queries, which is work happening in another program.</p> <p>The real trick, however, is to organize the code so that you can do the full spectrum of testing and profiling without having to put it all together at the end to find out something is slow. That won't help you much in the short term to fight fires, but it does prevent things from becoming fires in the long run. There are also various ways to fake the webserver environment and so on, but that's a different question. :)</p>
<p>You can use the <a href="http://perldoc.perl.org/Benchmark.html" rel="nofollow noreferrer"><strong>Benchmark</strong></a> core module with the <strong>:hireswallclock</strong> option if you really want to time things internally. But really, you should be able to profile from the command line. You might have to write test scripts to emulate certain portions of a CGI request, but DProf can be <strong>extremely</strong> useful when looking for performance bottlenecks. </p> <p>In particular, look for where your code is calling the CPAN module code. You may be doing this in loops far more than necessary, so while the time is spent in the CPAN module, refactoring your code can fix the problem.</p>
16,472
<p>As an example in pseudocode:</p> <pre><code>if ((a mod 2) == 0) { isEven = true; } else { isEven = false; } </code></pre>
<p>Instead of the modulo operator, which has slightly different semantics, for non-negative integers, you can use the <em>remainder</em> operator <code>%</code>. For your exact example:</p> <pre><code>if ((a % 2) == 0) { isEven = true; } else { isEven = false; } </code></pre> <p>This can be simplified to a one-liner:</p> <pre><code>isEven = (a % 2) == 0; </code></pre>
<p>The modulo operator is % (percent sign). To test for evenness or generally do modulo for a power of 2, you can also use &amp; (the and operator) like isEven = !( a &amp; 1 ).</p>
11,565
<p>How do I setup a class that represents an interface? Is this just an abstract base class?</p>
<p>To expand on the answer by <a href="https://stackoverflow.com/questions/318064/how-do-you-declare-an-interface-in-c#318084">bradtgmurray</a>, you may want to make one exception to the pure virtual method list of your interface by adding a virtual destructor. This allows you to pass pointer ownership to another party without exposing the concrete derived class. The destructor doesn't have to do anything, because the interface doesn't have any concrete members. It might seem contradictory to define a function as both virtual and inline, but trust me - it isn't.</p> <pre><code>class IDemo { public: virtual ~IDemo() {} virtual void OverrideMe() = 0; }; class Parent { public: virtual ~Parent(); }; class Child : public Parent, public IDemo { public: virtual void OverrideMe() { //do stuff } }; </code></pre> <p>You don't have to include a body for the virtual destructor - it turns out some compilers have trouble optimizing an empty destructor and you're better off using the default. </p>
<pre><code>class Shape { public: // pure virtual function providing interface framework. virtual int getArea() = 0; void setWidth(int w) { width = w; } void setHeight(int h) { height = h; } protected: int width; int height; }; class Rectangle: public Shape { public: int getArea() { return (width * height); } }; class Triangle: public Shape { public: int getArea() { return (width * height)/2; } }; int main(void) { Rectangle Rect; Triangle Tri; Rect.setWidth(5); Rect.setHeight(7); cout &lt;&lt; "Rectangle area: " &lt;&lt; Rect.getArea() &lt;&lt; endl; Tri.setWidth(5); Tri.setHeight(7); cout &lt;&lt; "Triangle area: " &lt;&lt; Tri.getArea() &lt;&lt; endl; return 0; } </code></pre> <p>Result: Rectangle area: 35 Triangle area: 17</p> <p>We have seen how an abstract class defined an interface in terms of getArea() and two other classes implemented same function but with different algorithm to calculate the area specific to the shape.</p>
41,090
<p>Most developers and engineers that have experience writing software and deploying with the packaged Visual Studio Setup Project know about its many shortcomings. Usually in regards to installation customization, upgrade paths, etc. What are some good alternatives for software deployment? In particular I'm interested in features, .NET integration or scripting capabilities, easy of use, and price.</p>
<ul> <li><a href="http://wix.sourceforge.net/" rel="noreferrer">Windows Installer XML (Wix)</a></li> <li><a href="http://nsis.sourceforge.net/Main_Page" rel="noreferrer">NullSoft Installer</a></li> </ul>
<p>NullSoft Installer (NSIS) is good, but building the scripts is painful - even with HM NIS Edit. You basically have to learn a whole different language to be able to work with their scripts. Example:</p> <p>Plug-ins are necessary to do a lot of things as well, like check the .NET framework version or see if the application you are updating is already running. </p> <p>Aside from that though, once you get everything configured it is fast and works well. There's really not a better installer (for free) out there.</p>
22,663
<p>I've been trying to encode a relational algebra in Scala (which to my knowlege has one of the most advanced type systems) and just don't seem to find a way to get where I want.</p> <p>As I'm not that experienced with the academic field of programming language design I don't really know what feature to look for.</p> <p>So what language features would be needed, and what language has those features, to implement a statically verified relational algebra?</p> <p>Some of the requirements: A Tuple is a function mapping names from a statically defined set of valid names for the tuple in question to values of the type specified by the name. Lets call this name-type set the domain.</p> <p>A Relation is a Set of Tuples with the same domain such that the range of any tuple is uniqe in the Set</p> <p>So far the model can eaisly be modeled in Scala simply by</p> <pre><code>trait Tuple trait Relation[T&lt;Tuple] extends Set[T] </code></pre> <p>The vals, vars and defs in Tuple is the name-type set defined above. But there should'n be two defs in Tuple with the same name. Also vars and impure defs should probably be restricted too.</p> <p>Now for the tricky part:</p> <p>A join of two relations is a relation where the domain of the tuples is the union of the domains from the operands tuples. Such that only tuples having the same ranges for the intersection of their domains is kept.</p> <pre><code>def join(r1:Relation[T1],r2:Relation[T2]):Relation[T1 with T2] </code></pre> <p>should do the trick.</p> <p>A projection of a Relation is a Relation where the domain of the tuples is a subset of the operands tuples domain.</p> <pre><code>def project[T2](r:Relation[T],?1):Relation[T2&gt;:T] </code></pre> <p>This is where I'm not sure if it's even possible to find a sollution. What do you think? What language features are needed to define project?</p> <p>Implied above offcourse is that the API has to be usable. Layers and layers of boilerplate is not acceptable.</p>
<p>What your asking for is to be able to structurally define a type as the <em>difference</em> of two other types (the original relation and the projection definition). I honestly can't think of any language which would allow you to do that. Types can be structurally cumulative (<code>A with B</code>) since <code>A with B</code> is a structural sub-type of both <code>A</code> and <code>B</code>. However, if you think about it, a type operation <code>A less B</code> would actually be a <em>supertype</em> of <code>A</code>, rather than a sub-type. You're asking for an arbitrary, contravariant typing relation on naturally covariant types. It hasn't even been proven that sort of thing is sound with nominal existential types, much less structural declaration-point types.</p> <p>I've worked on this sort of modeling before, and the route I took was to constraint projections to one of three domains: <code>P</code> == <code>T</code>, <code>P</code> == <code>{F} where F in T</code>, <code>P</code> == <code>{$_1} where $_1 anonymous</code>. The first is where the projection is equivalent to the input type, meaning it is a no-op (<code>SELECT *</code>). The second is saying that the projection is a single field contained within the input type. The third is the tricky one. It is saying that you are allowing the declaration of some anonymous type <code>$_1</code> which has no <em>static</em> relationship to the input type. Presumably it will consist of fields which delegate to the input type, but we can't enforce that. This is roughly the strategy that LINQ takes.</p> <p>Sorry I couldn't be more helpful. I wish it were possible to do what you're asking, it would open up a lot of very neat possibilities.</p>
<p>I think I have settled on just using the normal facilities for mapping collection for the project part. The client just specify a function <code>[T&lt;:Tuple](t:T) =&gt; P</code></p> <p>With some java trickery to get to the class of P I should be able to use reflection to implement the query logic.</p> <p>For the join I'll probably use DynamicProxy to implement the mapping function.</p> <p>As a bonus I might be able to get the API to be usable with Scalas special for-syntax.</p>
20,573
<p>How do you clear the IRB console screen?</p>
<p>On <em>Mac OS X</em> or <em>Linux</em> you can use <kbd>Ctrl</kbd> + <kbd>L</kbd> to clear the <em>IRB</em> screen.</p>
<p>The backtick operator captures the output of the command and returns it</p> <pre><code>s = `cls` puts s </code></pre> <p>would work better, I guess.</p>
14,204
<p>I'd like a C library that can serialize my data structures to disk, and then load them again later. It should accept arbitrarily nested structures, possibly with circular references.</p> <p>I presume that this tool would need a configuration file describing my data structures. The library is allowed to use code generation, although I'm fairly sure it's possible to do this without it. </p> <p>Note I'm not interested in data portability. I'd like to use it as a cache, so I can rely on the environment not changing.</p> <p>Thanks.</p> <hr> <p><em>Results</em></p> <p>Someone suggested <a href="http://tpl.sourceforge.net/" rel="noreferrer">Tpl</a> which is an awesome library, but I believe that it does not do arbitrary object graphs, such as a tree of Nodes that each contain two other Nodes.</p> <p>Another candidate is <a href="http://www.enlightenment.org/p.php?p=about/efl/eet&amp;l=en" rel="noreferrer">Eet</a>, which is a project of the Enlightenment window manager. Looks interesting but, again, seems not to have the ability to serialize nested structures.</p>
<p>Check out <a href="http://troydhanson.github.io/tpl/" rel="nofollow noreferrer">tpl</a>. From the overview:</p> <blockquote> <p>Tpl is a library for serializing C data. The data is stored in its natural binary form. The API is small and tries to stay &quot;out of the way&quot;. Compared to using XML, tpl is faster and easier to use in C programs. Tpl can serialize many C data types, including structures.</p> </blockquote>
<p>In theory YAML should do what you want <a href="http://code.google.com/p/yaml-cpp/" rel="nofollow noreferrer">http://code.google.com/p/yaml-cpp/</a> </p> <p>Please let me know if it works for you.</p>
48,529
<p>I need to automate a process involving a website that is using a login form. I need to capture some data in the pages following the login page.</p> <p>I know how to screen-scrape normal pages, but not those behind a secure site.</p> <ol> <li>Can this be done with the .NET WebClient class? <ul> <li>How would I automatically login?</li> <li>How would I keep logged in for the other pages?</li> </ul></li> </ol>
<p>One way would be through automating a browser -- you mentioned WebClient, so I'm guessing you might be referring to WebClient in .NET.<p>Two main points:<ul><li>There's nothing special about https related to WebClient - it just works</li><li>Cookies are typically used to carry authentication -- you'll need to capture and replay them</li></ul></p> <p>Here's the steps I'd follow:<ol><li>GET the login form, capture the the cookie in the response.</li><li>Using Xpath and HtmlAgilityPack, find the "input type=hidden" field names and values.</li><li>POST to login form's action with user name, password, and hidden field values in the request body. Include the cookie in the request headers. Again, capture the cookie in the response.</li><li>GET the pages you want, again, with the cookie in the request headers.</li></ol></p> <p>On step 2, I mention a somewhat complicated method for automating the login. Usually, you can post with username and password directly to the known login form action without getting the initial form or relaying the hidden fields. Some sites have form validation (different from field validation) on their forms which makes this method not work.<p><a href="http://www.codeplex.com/htmlagilitypack" rel="nofollow noreferrer">HtmlAgilityPack</a> is a .NET library that allows you to turn ill-formed html into an XmlDocument so you can XPath over it. Quite useful.<p>Finally, you may run into a situation where the form relies on client script to alter the form values before submitting. You may need to simulate this behavior.<p>Using a tool to view the http traffic for this type of work is extremely helpful - I recommend <a href="http://www.blunck.se/iehttpheaders.html" rel="nofollow noreferrer">ieHttpHeaders</a>, <a href="http://www.fiddler2.com" rel="nofollow noreferrer">Fiddler</a>, or <a href="http://getfirebug.com/" rel="nofollow noreferrer">FireBug</a> (net tab).</p>
<p>Can you please clarify? Is the WebClient class you speak of the one in HTTPUnit/Java?</p> <p>If so, your session should be saved automatically.</p>
7,058
<p>I have a special url which I would want only few people to have access to. I have a list of super users stored as an array in the app.yml. How can I use this array in :requirements section of a specific route in the routes.rb file to allow only those super users access to this route? Thanks a lot.</p>
<p>A more direct analogue to <code>dict.get(key, default)</code> than <code>hasattr</code> is <code>getattr</code>.</p> <pre><code>val = getattr(obj, 'attr_to_check', default_value) </code></pre> <p>(Where <code>default_value</code> is optional, raising an exception on no attribute if not found.)</p> <p>For your example, you would pass <code>False</code>.</p>
<p>For checking if a key is in a dictionary you can use <code>in</code>: <code>'key' in dictionary</code>.</p> <p>For checking for attributes in object use the <code>hasattr()</code> function: <code>hasattr(obj, 'attribute')</code></p>
46,343
<p>HI All,</p> <p>We have a .Net 2.0 application which has a MySQL backend. We want to be able to deploy MySQl and the DB when we install the application and im trying to find the best solution. The current setup is to copy the required files to a folder on the local machine and then perform a "NET START" commands to install and start the mysql service. Then we restore a backup of the DB to this newly created mysql instance using bat files. Its not an ideal solution at all and im trying to come up with something more robust. </p> <p>The issues are User rights on Vista, and all sorts of small things around installing and starting the service. Its far too fragile to be reliable or at least it appears that way when i am testing it. This is a Client/Server type setup so we only need to install one Server per office but i want to make sure its as hassle free as possible and with as few screens as possible.</p> <p>How would you do it?</p>
<p>Not sure where you're at in the project, but if it's a simple and small database you might consider converting it to <a href="http://www.sqlite.org/" rel="noreferrer">SQLite</a>. It's not ideal for Client/Server operations, but if it's low volume/transactions it might work.</p>
<p>With a Client/Sever setup, you're allowed to require that whoever installs the server install it as an admin. That should solve most of your problems.</p> <p>Again- that's the server. The clients might be another story.</p>
7,190
<p>Is it possible to create a final route that catches all .. and bounces the user to a 404 view in ASP.NET MVC?</p> <p>NOTE: I don't want to set this up in my IIS settings.</p>
<p>Found the answer myself.</p> <p><a href="http://richarddingwall.name/2008/08/17/strategies-for-resource-based-404-errors-in-aspnet-mvc/" rel="noreferrer" title="Click to read Richard&#39;s MVC 404 strategies">Richard Dingwall</a> has an excellent post going through various strategies. I particularly like the FilterAttribute solution. I'm not a fan of throwing exceptions around willy nilly, so i'll see if i can improve on that :)</p> <p>For the global.asax, just add this code as your last route to register:</p> <pre><code>routes.MapRoute( "404-PageNotFound", "{*url}", new { controller = "StaticContent", action = "PageNotFound" } ); </code></pre>
<p>If the route cannot be resolved, then MVC framework will through 404 error.. Best approach is to use Exception Filters ... Create a custom exceptionfilter and make like this.. </p> <pre><code>public class RouteNotFoundAttribute : FilterAttribute, IExceptionFilter { public void OnException(ExceptionContext filterContext) { filterContext.Result = new RedirectResult("~/Content/RouteNotFound.html"); } } </code></pre>
40,017
<p>I'm probably doing this all wrong. I have a text file full of data and I want to match and replace patterns of "item" and "catalog number" that are in the file. But the order of each element in the file is very important, so I want to match/replace starting from the top of the file and then work my way down.</p> <p>The code snippet below actually works, but when I execute it, it replaces the third instance of the "SeaMonkey" &amp; "SMKY-1978" pattern and then it replaces the second instance of that pattern. What I'd like it to do is replace the first instance of the pattern and then the second.</p> <p>So I'd like the output to say "Found <strong>Kurt's</strong> SMKY-1978 SeaMonkeys" and then "Found <strong>Shane's</strong> SMKY-1978 SeaMonkeys" and then leave Mick's SMKY-1978 SeaMonkeys alone since I only want to find and replace the first 2 instances of the pattern. Right now it says "Found <strong>Shane's</strong> SMKY-1978 SeaMonkeys" and "Found <strong>Mick's</strong> SMKY-1978 SeaMonkeys" because it is matching the last pattern each time the for loop is executed.</p> <p>So am I missing a subtle little known regex character or am I just doing what I want to do completely and utterly wrong?</p> <p>Here is the working code:</p> <pre><code># my regexp matches from the bottom to the top but I'd like it to replace from the top down local $/=undef; my $DataToParse = &lt;DATA&gt;; my $item = "SeaMonkeys"; my $catNum = "SMKY-1978"; my $maxInstancesToReplace = 2; parseData(); exit(); sub parseData { for (my $counter = 0; $counter &lt; $maxInstancesToReplace; $counter++) { # Stick in a temporary text placeholder that I will replace later after more processing $DataToParse =~ s/(.+)\sELEMENT\s(.+?)\s\(Item := \"$item\".+?CatalogNumber := \"$catNum.+?END_ELEMENT(.+)/$1 ***** Found $2\'s $catNum $item. (counter: $counter) *****$3/s; } print("Here's the result:\n$DataToParse\n"); } __DATA__ ELEMENT Kurt (Item := "BrightLite", ItemID := 29, CatalogNumber := "BTLT-9274", Vendor := 100, END_ELEMENT ELEMENT Mick (Item := "PetRock", ItemID := 36, CatalogNumber := "PTRK-3475/A", Vendor := 82, END_ELEMENT ELEMENT Kurt (Item := "SeaMonkeys", ItemID := 12, CatalogNumber := "SMKY-1978/E", Vendor := 77, END_ELEMENT ELEMENT Joe (Item := "Pong", ItemID := 24, CatalogNumber := "PONG-1482", Vendor := 5, END_ELEMENT ELEMENT Shane (Item := "SeaMonkeys", ItemID := 1032, CatalogNumber := "SMKY-1978/E", Vendor := 77, END_ELEMENT ELEMENT Kurt (Item := "Battleship", ItemID := 99, CatalogNumber := "BTLS-5234", Vendor := 529, END_ELEMENT ELEMENT Mick (Item := "SeaMonkeys", ItemID := 8, CatalogNumber := "SMKY-1978/F", Vendor := 77, END_ELEMENT ELEMENT Frank (Item := "PetRock", ItemID := 42, CatalogNumber := "PTRK-3475/B", Vendor := 82, END_ELEMENT ELEMENT Joe (Item := "SeaMonkeys", ItemID := 8, CatalogNumber := "SMKY-1979/A", Vendor := 77, END_ELEMENT </code></pre> <p>And here is what it currently outputs:</p> <pre>Here's the result: ELEMENT Kurt (Item := "BrightLite", ItemID := 29, CatalogNumber := "BTLT-9274", Vendor := 100, END_ELEMENT ELEMENT Mick (Item := "PetRock", ItemID := 36, CatalogNumber := "PTRK-3475/A", Vendor := 82, END_ELEMENT ELEMENT Kurt (Item := "SeaMonkeys", ItemID := 12, CatalogNumber := "SMKY-1978/E", Vendor := 77, END_ELEMENT ELEMENT Joe (Item := "Pong", ItemID := 24, CatalogNumber := "PONG-1482", Vendor := 5, END_ELEMENT ***** Found Shane's SMKY-1978 SeaMonkeys. (counter: 1) ***** ELEMENT Kurt (Item := "Battleship", ItemID := 99, CatalogNumber := "BTLS-5234", Vendor := 529, END_ELEMENT ***** Found Mick's SMKY-1978 SeaMonkeys. (counter: 0) ***** ELEMENT Frank (Item := "PetRock", ItemID := 42, CatalogNumber := "PTRK-3475/B", Vendor := 82, END_ELEMENT ELEMENT Joe (Item := "SeaMonkeys", ItemID := 8, CatalogNumber := "SMKY-1979/A", Vendor := 77, END_ELEMENT</pre>
<p>.+ at start of your regex is "greedy". This means that it will match maximum chars.</p> <p>You regex is better written (it would be more readable and faster) as</p> <pre><code>my $re=qr/\sELEMENT\s(.+?)\s\(Item := "$item".+?CatalogNumber := "$catNum.+?END_ELEMENT/; </code></pre> <p>I think that you can simply repeat this match:</p> <pre><code>sub parseData { my $re=qr/\sELEMENT\s(.+?)\s\(Item := "$item".+?CatalogNumber := "$catNum.+?END_ELEMENT(.+)/; foreach my $counter (0..$maxInstancesToReplace) { # Stick in a temporary text placeholder that I will replace later after more processing $DataToParse =~ s/$re/ ***** Found $1\'s $catNum $item. (counter: $counter) *****$2/s; } print("Here's the result:\n$DataToParse\n"); } </code></pre> <p>If repeating is not possible, you should use /e regex modifier.</p>
<p>The best solution appears to be to grab each ELEMENT ... END_ELEMENT section from the data and regex only one section at a time rather than feeding the whole complete data set to a regular expression at once. Not exactly what I was trying to accomplish, but I rewrote my program to do this piecemeal processing and it works like a charm. </p>
29,121
<p>I'm working on a WinCE 6.0 system with a touchscreen that stores its calibration data (x-y location, offset, etc.) in the system registry (HKLM\HARDWARE\TOUCH). Right now, I'm placing the cal values into registry keys that get put into the OS image at build time. That works fine for the monitor that I get the original cal values from, but when I load this image into another system with a different monitor, the touchscreen pointer location is (understandably) off, because the two monitors do not have the same cal values.</p> <p>My problem is that I don't know how to properly store values into the registry so that they persist after a power cycle. See, I can recalibrate the screen on the second system, but the new values only exist in volatile memory. I suggested to my boss that we could just tell our customer to leave the power on the unit at all times -- that didn't go over well.</p> <p>I need advice on how to save the new constants into the registry, so that we can calibrate the monitors once before shipping them out to our customer, and not have to make separate OS images for each unit we build.</p> <p>A C# method that is known to work in CE6.0 would be helpful. Thanks.</p> <p>-Odbasta</p>
<p>I think what you're probably looking for is the Flush function of the RegistryKey class. This is normally not necessary (the registry is lazily-flushed by default), but if the power is turned off on the device before the system has a chance to do this, changes will be discarded:</p> <p><a href="http://msdn.microsoft.com/en-us/library/microsoft.win32.registrykey.flush.aspx" rel="nofollow noreferrer">http://msdn.microsoft.com/en-us/library/microsoft.win32.registrykey.flush.aspx</a></p> <p>This function is available in .NET Compact Framework version 2.0 and better.</p>
<p>As I understood you need to know how to set a value to the registry during runtime. I hope the codes bellow can help you.</p> <p>using Microsoft.Win32; </p> <pre><code> /// &lt;summary&gt; /// store a key value in registry. if it don't exist it will be created. /// &lt;/summary&gt; /// &lt;param name="mainKey"&gt;the main key of key path&lt;/param&gt; /// &lt;param name="subKey"&gt;the path below the main key&lt;/param&gt; /// &lt;param name="keyName"&gt;the key name&lt;/param&gt; /// &lt;param name="value"&gt;the value to be stored&lt;/param&gt; public static void SetRegistry(int mainKey, String subKey, String keyName, object value) { if (mainKey != CURRENT_USER &amp;&amp; mainKey != LOCAL_MACHINE) { throw new ArgumentOutOfRangeException("mainKey", "\'mainKey\' argument can only be AppUtils.CURRENT_USER or AppUtils.LOCAL_MACHINE values"); } if (subKey == null) { throw new ArgumentNullException("subKey", "\'subKey\' argument cannot be null"); } if (keyName == null) { throw new ArgumentNullException("keyName", "\'keyName\' argument cannot be null"); } const Boolean WRITABLE = true; RegistryKey key = null; if (mainKey == CURRENT_USER) { key = Registry.CurrentUser.OpenSubKey(subKey, WRITABLE); if (key == null) { key = Registry.CurrentUser.CreateSubKey(subKey); } } else if (mainKey == LOCAL_MACHINE) { key = Registry.LocalMachine.OpenSubKey(subKey, WRITABLE); if (key == null) { key = Registry.LocalMachine.CreateSubKey(subKey); } } key.SetValue(keyName, value); } /// &lt;summary&gt; /// find a key value in registry. if it don't exist the default value will be returned. /// &lt;/summary&gt; /// &lt;param name="mainKey"&gt;the main key of key path&lt;/param&gt; /// &lt;param name="subKey"&gt;the path below the main key&lt;/param&gt; /// &lt;param name="keyName"&gt;the key name&lt;/param&gt; /// &lt;param name="defaultValue"&gt;the value to be stored&lt;/param&gt; public static object GetRegistry(int mainKey, String subKey, String keyName, object defaultValue) { if (mainKey != CURRENT_USER &amp;&amp; mainKey != LOCAL_MACHINE) { throw new ArgumentOutOfRangeException("mainKey", "\'mainKey\' argument can only be AppUtils.CURRENT_USER or AppUtils.LOCAL_MACHINE values"); } if (subKey == null) { throw new ArgumentNullException("subKey", "\'subKey\' argument cannot be null"); } if (keyName == null) { throw new ArgumentNullException("keyName", "\'keyName\' argument cannot be null"); } RegistryKey key = Registry.CurrentUser.OpenSubKey(subKey); if (mainKey == CURRENT_USER) { key = Registry.CurrentUser.OpenSubKey(subKey); } else if (mainKey == LOCAL_MACHINE) { key = Registry.LocalMachine.OpenSubKey(subKey); } object result = defaultValue; if (key != null) { result = key.GetValue(keyName, defaultValue); } return result; } </code></pre>
8,195
<p>I have a script that has a part that looks like that:</p> <pre><code>for file in `ls *.tar.gz`; do echo encrypting $file gpg --passphrase-file /home/$USER/.gnupg/backup-passphrase \ --simple-sk-checksum -c $file done </code></pre> <p>For some reason if I run this script manually, works perfectly fine and all files are encrypted. If I run this as cron job, <code>echo $file</code> works fine (I see "encrypting &lt;file&gt;" in the log), but the file doesn't get encrypted and gpg silent fails with no stdout/stderr output.</p> <p>Any clues?</p>
<p>It turns out that the answer was easier than I expected. There is a <code>--batch</code> parameter missing, gpg tries to read from /dev/tty that doesn't exist for cron jobs. To debug that I have used <code>--exit-on-status-write-error</code> param. But to use that I was inspired by exit status 2, reported by echoing <code>$?</code> as Cd-Man suggested. </p>
<p>make sure the user that is running the cron job has the permissions needed to encrypt the file. </p>
6,102
<p>Is there a best way to turn an integer into its month name in .net?</p> <p>Obviously I can spin up a datetime to string it and parse the month name out of there. That just seems like a gigantic waste of time.</p>
<p>Try GetMonthName from DateTimeFormatInfo</p> <p><a href="http://msdn.microsoft.com/en-us/library/system.globalization.datetimeformatinfo.getmonthname.aspx" rel="noreferrer">http://msdn.microsoft.com/en-us/library/system.globalization.datetimeformatinfo.getmonthname.aspx</a></p> <p>You can do it by:</p> <pre><code>CultureInfo.CurrentCulture.DateTimeFormat.GetMonthName(1); </code></pre>
<p>To get abbreviated month value, you can use <code>Enum.Parse();</code></p> <pre><code>Enum.Parse(typeof(Month), "0"); </code></pre> <p>This will produce "Jan" as result.</p> <p>Remember this is zero-based index.</p>
26,941
<p>I have some flexible PLA filament (<a href="https://rads.stackoverflow.com/amzn/click/com/B00VKSSA4E" rel="noreferrer" rel="nofollow noreferrer">https://www.amazon.com/dp/B00VKSSA4E/</a>, presumably a mix of PLA with some platicizer) that's supposed to be easy to print with settings similar to regular PLA. I've seen recommendations to disable retraction, and indeed I get huge failures to extrude at all for a while after retraction if it's enabled. But with retraction disabled, I get stringing all over the place, and since the material isn't brittle, it's really difficult to remove.</p> <p>I'm using a bed temp of 60 and print temp of 220, increased from 210 for normal PLA since I had trouble getting it to adhere at lower temp. Printer is Creality Ender 3. Using CuraEngine for slicing. The extruder is feeding the material fine; there's no kinking going on or anything.</p> <p>Where should I start trying to improve this? Might retraction work with a really really slow print speed or greatly reduced retraction distance? Or are there other ways to avoid stringing?</p>
<p>You could enable <code>combing</code> in the slicer. Combing not only prevents retracts, it also uses already laid down paths for movement from one to the other location and as such reduces the amount of stringing.</p>
<p>The right path seems to be enabling retraction, but tuning the retraction and print speed settings. I started out by dropping all speed settings to 30. With retraction disabled, this turned the stringing into solid walls between paths, with only a tiny gap at the very start of the wall, right after the extruder stopped:</p> <p><a href="https://i.stack.imgur.com/StzqN.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/StzqN.jpg" alt="enter image description here"></a></p> <p>This suggested that the sudden drop in pressure at the nozzle is cutting off the string momentarily. Back to that thought in a bit.</p> <p>Independently of the pressure thought, I decided to turn retraction back on, but with <em>really</em> slow retraction speed. This helped a lot, but probably not the way I expected; I think what it did was give the nozzle time to ooze at the point where retraction happens, rather than in the travel path. I also turned off <code>infill_before_walls</code>, so that the retraction and potential oozing would happen in the infill region rather than walls, and increased the travel speed way up to 200 to take best advantage of the moment where oozing is interrupted.</p> <p>At this point, I'm getting almost-acceptable results with <code>retraction_retract_speed</code> set to 5 (vs default 25), default retraction amount, and <code>speed_travel</code> of 200:</p> <p><a href="https://i.stack.imgur.com/5MSpu.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/5MSpu.jpg" alt="enter image description here"></a></p> <p>Back to the pressure idea, I'm thinking that the right solution is probably to perform the retraction concurrently with the travel, keeping some negative pressure the whole time, and possibly jerking the extruder back further just before hitting the travel destination to prevent a string from forming there. Cura has no features to do anything like that, but it shouldn't be difficult as post-processing on the gcode. I might try prototyping it like that to see if it works.</p>
1,254
<p>I need audio playback with these features: good performance (for game), pitch control, and ability to layer the same sample multiple times at the same time (polyphony). What would be a quick way to get this on the iphone sdk?</p> <hr> <p>Here's what I found out so far:</p> <p>There's no available libraries or sample code that does this, please show me wrong.</p> <p>SoundEngine.cpp (from CrashLanding and TouchFighter code samples) uses OpenAL and allows to control pitch, but everytime a buffer is started, if that same buffer is playing, its playhead goes back to the start.</p> <p>One dirty solution to get polyphony with SoundEngine.cpp, without diving into its implementation (which is incomprehensible to me), is to load multiple buffers for the same sound file. Let's say I want a polyphony of maximum 4 voices per sound, then I load 4 buffers for the same file. I would just have to wrap it all up in a manager class. Is it safe to go down this path? And/or is there a way to hack the SoundEngine.cpp to be polyphonic?</p>
<p>FMOD (www.fmod.org) provides all these features. Check out their virtualvoices sample for polyphony and the pitch shift DSP effect in the docs.</p> <p>I'm just a customer, not otherwise affiliated with them.</p>
<p>The SoundEngine from CrashLanding is a mess, I’d stay away from it. Writing what you want around OpenAL is not hard, it’s a few hours of work. You can peek at <a href="http://github.com/zoul/Finch/" rel="nofollow noreferrer">Finch</a> or at the <a href="http://code.google.com/p/cocos2d-iphone/source/browse/trunk/experimental/sound-engine/" rel="nofollow noreferrer">Cocos 2D sound egine</a>.</p>
43,320
<p>I have to deal with text files in a motley selection of formats. Here's an example (Columns <strong>A</strong> and <strong>B</strong> are tab delimited):</p> <pre><code>A B a Name1=Val1, Name2=Val2, Name3=Val3 b Name1=Val4, Name3=Val5 c Name1=Val6, Name2=Val7, Name3=Val8 </code></pre> <p>The files could have headers or not, have mixed delimiting schemes, have columns with name/value pairs as above etc.<br> I often have the ad-hoc need to extract data from such files in various ways. For example from the above data I might want the value associated with Name2 where it is present. i.e.</p> <pre><code>A B a Val2 c Val7 </code></pre> <p>What tools/techniques are there for performing such manipulations as one line commands, using the above as an example but extensible to other cases?</p>
<p>I don't like sed too much, but it works for such things:</p> <pre><code>var="Name2";sed -n "1p;s/\([^ ]*\) .*$var=\([^ ,]*\).*/\1 \2/p" &lt; filename </code></pre> <p>Gives you:</p> <pre><code> A B a Val2 c Val7 </code></pre>
<p>From what I've seen I'd start with Awk for this sort of thing and then if you need something more complex, I'd progress to Python.</p>
10,796
<p>Ok, I have been working with Solaris for a 10+ years, and have never seen this...</p> <p>I have a directory listing which includes both a file and subdirectory with the same name:</p> <pre><code>-rw-r--r-- 1 root other 15922214 Nov 29 2006 msheehan drwxrwxrwx 12 msheehan sysadmin 2048 Mar 25 15:39 msheehan </code></pre> <p>I use file to discover contents of the file, and I get:</p> <pre><code>bash-2.03# file msheehan msheehan: directory bash-2.03# file msh* msheehan: ascii text msheehan: directory </code></pre> <p>I am not worried about the file, but I want to keep the directory, so I try rm:</p> <pre><code>bash-2.03# rm msheehan rm: msheehan is a directory </code></pre> <p>So here is my two part question:</p> <ol> <li>What's up with this?</li> <li>How do I carefully delete the file?</li> </ol> <p>Jonathan</p> <p>Edit: Thanks for the answers guys, both (so far) were helpful, but piping the listing to an editor did the trick, ala:</p> <pre><code>bash-2.03# ls -l &gt; jb.txt bash-2.03# vi jb.txt </code></pre> <p>Which contained:</p> <pre><code>-rw-r--r-- 1 root other 15922214 Nov 29 2006 msheehab^?n drwxrwxrwx 12 msheehan sysadmin 2048 Mar 25 15:39 msheehan </code></pre> <p>Always be careful with the backspace key!</p>
<p>I would guess that these are in fact two different filenames that "look" the same, as the command file was able to distinguish them when the shell passed the expanded versions of the name in. Try piping ls into od or another hex/octal dump utility to see if they really have the same name, or if there are non-printing characters involved.</p>
<p>And a quick answer to part 2 of my own question...</p> <p>I would imagine I could rename the directory, delete the file, and rename the directory back to it's original again. </p> <p>... I would still be interested to see what other people come up with.</p> <p>JB</p>
10,887
<p>I have a custom program which preprocesses a C# file and generates a new C# file as output. I would like to invoke this from msbuild on each of the C# files in the project, then compile the output files instead of the original C# files. How would I go about this?</p>
<p>I'm not sure if there is an easy way to perform it with default msbuild tasks. But you can create your own task to do whatever you want:</p> <p><a href="http://blogs.msdn.com/msbuild/archive/2006/01/21/515834.aspx" rel="nofollow noreferrer">How To: Implementing Custom Tasks - Part I</a></p> <p>Also you can search for suitable tasks at "<a href="https://github.com/loresoft/msbuildtasks" rel="nofollow noreferrer">MSBuild community tasks</a>" site.</p>
<p>If your custom program is an executable the easiest way would be to call the executable with Exec:</p> <pre><code>&lt;Exec Command="your executable" /&gt; </code></pre> <p>I would recommend writing a custom MSBuild task though. You can look at the <a href="http://www.codeplex.com/sdctasks" rel="nofollow noreferrer">SDC Tasks</a> for samples on how to do it.</p>
14,407
<p>So I'm teaching myself Python, and I'm having an issue with lists. I want to pass my function a list and pop items off it while retaining the original list. How do I make python "instance" the passed list rather that passing a pointer to the original one?</p> <p>Example:</p> <pre><code>def burninate(b): c = [] for i in range(3): c.append(b.pop()) return c a = range(6) d = burninate(a) print a, d </code></pre> <p>Output: [0, 1, 2] [5, 4, 3]<br> Desired output: [0, 1, 2, 3, 4, 5] [5, 4, 3]</p> <p>Thanks!</p>
<p>As other answers have suggested, you can provide your function with a copy of the list.</p> <p>As an alternative, your function could take a copy of the argument:</p> <pre><code>def burninate(b): c = [] b = list(b) for i in range(3): c.append(b.pop()) return c </code></pre> <p>Basically, you need to be clear in your mind (and in your documentation) whether your function will change its arguments. In my opinion, functions that return computed values should not change their arguments, and functions that change their arguments should not return anything. See python's [].sort(), [].extend(), {}.update(), etc. for examples. Obviously there are exceptions (like .pop()).</p> <p>Also, depending on your particular case, you could rewrite the function to avoid using pop() or other functions that modify the argument. e.g.</p> <pre><code>def burninante(b): return b[:-4:-1] # return the last three elements in reverse order </code></pre>
<pre><code>burninate = lambda x: x[:-4:-1]</code></pre>
28,195
<p>While we try to set up as many unit tests as time allows for our applications, I always find the amount of UI-level tests lacking. There are many options out there, but I'm not sure what would be a good place to start. </p> <p>What is your preferred unit testing tool for testing Swing applications? Why do you like it?</p>
<p>On our side, we use to test SWING GUI with <a href="http://code.google.com/p/fest/" rel="noreferrer">FEST</a>. This is an adapter on the classical swing robot, but it ease dramatically its use. </p> <p>Combined with TestNG, We found it an easy way to simulate "human" actions trough the GUI.</p>
<p>try pounder : <a href="http://pounder.sourceforge.net/" rel="nofollow noreferrer">http://pounder.sourceforge.net/</a></p>
10,529
<p>Is there a way to get more useful information on validation error? XmlSchemaException provides the line number and position of the error which makes little sense to me. Xml document after all is not about its transient textual representation. I'd like to get an enumerated error (or an error code) specifying what when wrong, node name (or an xpath) to locate the source of the problem so that perhaps I can try and fix it.</p> <p>Edit: I'm talking about valid xml documents - just not valid against a particular schema!</p>
<p>In my experience, you are lucky to get a line number and parse position.</p>
<p>personally I'm not sure how to get a more detailed error, typcially f you open the document and go to the location mentioned you can easily find the error.</p> <p>If the code isn't able to parse the file as valid XML, it is pretty hard for it to give an XPATH or other named XML detail.</p>
18,734
<p>I'm sorry I could not think of a better title.</p> <p>The problem is the following:</p> <p>For our customer we have created (as part of a larger application) a graphical designer which they can use to build "scenario's".</p> <p>These scenario's consist of "Composites" which in turn consist of "Commands". These command objects all derive from CommandBase and implement an interface called ICompilable.</p> <p>The scenario class also implements ICompilable. When Compile() is called on a command an array of bytes is returned which can then be send to the device for which they are intended (can't disclose to much info about that hardware, sorry)</p> <p>Just to give you an idea:</p> <pre><code>var scenario = new Scenario(); scenario.Add(new DelayCommand(1)); scenario.Add(new CountWithValueCommand(1,ActionEnum.Add,1)); scenario.Add(new DirectPowerCommand(23,false,150)); scenario.Add(new WaitCommand(3)); scenario.Add(new DirectPowerCommand(23,false,150)); scenario.Add(new SkipIfCommand(1,OperatorEnum.SmallerThan,10)); scenario.Add(new JumpCommand(2)); byte[] compiledData = scenario.Compile(); </code></pre> <p>The graphical designer abstracts all this from the user and allows him (or her) to simply drag en drop composites onto the designer surface. (Composites can group commands so we can provide building blocks for returning tasks)</p> <p>Recently our customer came to us and said, "well the designer is really cool, but we have some people who would rather have some kind of programming language, just something simple."</p> <p>(Simple to them of course)</p> <p>I would very much like to provide them with a simple language, that can call various commmands and also replace SkipIfCommand with a nicer structure, etc...</p> <p>I have no idea where to start or what my options are (without breaking what we have)</p> <p>I have heard about people embedding languages such as Python, people writing their own language an parsers, etc...</p> <p>Any suggestions?</p> <p>PS: Users only work with composites, never with commands. Composites are loaded dynamically at runtime (along with their graphical designer) and may be provided by third parties in seperate assemblies.</p>
<p>If you really just want a dirt simple language, you want a 'recursive descent parser'.</p> <p>For example, a language like this:</p> <pre><code>SCENARIO MyScenario DELAY 1 COUNT 1 ADD 1 DIRECT_POWER 23, False, 150 WAIT 3 ... END_SCENARIO </code></pre> <p>You might have a grammar like:</p> <pre><code>scenario :: 'SCENARIO' label newline _cmds END_SCENARIO cmds:: _delay or _count or _direct_power or... delay:: 'DELAY' number </code></pre> <p>Which gives code like:</p> <pre><code>def scenario(): match_word('SCENARIO') scenario_name = match_label() emit('var scenario = new Scenario();') cmds() match_word('END_SCENARIO') emit('byte[] ' + scenario_name + ' = scenario.Compile();') def delay(): match_word('DELAY') length = match_number() emit('scenario.Add(new DelayCommand('+ length +'))') def cmds(): word = peek_next_word() if word == 'DELAY': delay() elif ... </code></pre>
<p>While it might be great fun to create this mini-language and code it all up, the real questions you need to ask are:</p> <ol> <li>What is the business case for adding this feature / facility?</li> <li>Who is going to pay for this feature?</li> <li>Who is going to "sign off" on this feature if you build it?</li> </ol> <p>"Really neat" features have a way of getting built when the reality might indicate the true answer to such a request is "no".</p> <p>See if you have a stakeholder willing to sponsor this before proceeding. Then check with the end users to see what they really want before committing to the project.</p> <p>Cheers,</p> <p>-R</p>
32,997
<p>I've been writing PHP web applications for some time, and have come across very nice Javascript frameworks, such as JQuery, ExtJS, Scriptaculous, etc. I can't say the same about the PHP side - I always coded that part of the client-server dialog from scratch.</p> <p>I've used CodeIgniter (<a href="http://codeigniter.com/" rel="nofollow noreferrer">http://codeigniter.com/</a>) and it is nice, but doesn't deal with AJAX as a whole - rather providing input checking, image manipulation, and some output helpers.</p> <p>Is there a standard PHP library/class/framework out there that deals/integrates with Javascript frameworks? Something that can catch users' responses/requests, validate identity and input, provide progress status, keep track of sessions, be aware of asynchronous events, etc.</p>
<p>The <a href="http://framework.zend.com/" rel="nofollow noreferrer">Zend Framework</a> is integrated with <a href="http://dojotoolkit.org/" rel="nofollow noreferrer">Dojo Toolkit</a>. I haven't used the latest Zend Framework yet, but I do know that in the past, it has proven to be reliable.</p>
<p>Yes, PHP can output XML and JSON for Ajax but not all PHP frameworks support JSON/XML equally well.</p> <p>For example: I ran into an problem in Drupal (4.7) where the PHP sessions would be deleted after outputting a JSON response. (The HTML output code was explicitly closing the session, which was required or the session would be erased.)</p> <p>I would also love know about PHP frameworks that make it easier to manage to javascript code. Even something basic such as including jQuery only on the pages that require it. Or helping to manage minimizing/packing javascript code.</p>
20,638
<p>I'm attempting to install phpMyAdmin, but I constantly get errors.</p> <p>When I type this in the terminal:</p> <pre><code>sudo dpkg --configure -a </code></pre> <p>The following message appears:</p> <pre> Setting up mysql-server-5.0 (5.0.45-1ubuntu3) ... * Stopping MySQL database server mysqld [OK] * Starting MySQL database server mysqld [FAIL] invoke-rc.d: initscript mysql, action "start" failed. dpkg: error processing mysql-server-5.0 (--configure): subprocess post-installation script returned error exit status 1 dpkg: dependency problems prevent configuration of mysql-server: mysql-server depends on mysql-server-5.0; however: Package mysql-server 5.0 is not configured yet. dpkg: error processing mysql-server (--configure): dependency problems - leaving unconfigured Errors were encounter while processing: mysql-server-5.0 mysql-server </pre> <p>I also attempt to access MySQL through the console by typing: <code>mysql</code></p> <p>This error appears:</p> <pre><code>ERROR (HY000): Can't connect to local MySQL server through socket '/var/run/mysqld/mysqld.sock' (2) </code></pre> <p>This occurred ever I tried to install phpMyAdmin or accessing my <code>libapache</code>. Does anyone know how to resolve these problems?</p>
<p>The installer error is related to the <code>mysql-server-5.0</code> package. You probably should do an <code>apt-get purge mysql-server-5.0</code> and then try reinstalling it. Once that has been installed, try and install phpmyadmin.</p>
<p>You might also be able to get away with</p> <pre><code>dpkg --configure mysql-server-5.0 </code></pre> <p>since 'mysql-server' is a meta package. </p>
42,558
<p>I have an Asp.NET application (VS2008, Framework 2.0). When I try to set a property on one of the user controls like</p> <pre><code>myUserControl.SomeProperty = someValue; </code></pre> <p>I get a <code>NullReferenceException</code>. When I debug, I found out that <code>myUserControl</code> is null. How is it possible that a user control handle is null? How do I fix this or how do I find what causes this?</p>
<p>Where are you trying to access the property? If you are in onInit, the control may not be loaded yet.</p>
<p>If you created the UserControl during runtime (through ControlCollection.Add), you need to create it on postback too.</p> <p>Another case can be your UserControl does not match the designer.cs page</p>
5,015
<p>Does anyone know of a powershell cmdlet out there for automating task scheduler in XP/2003? If you've ever tried to work w/ schtasks you know it's pretty painful.</p>
<p>Ok, Pablo has sparked my interest in saying that the scheduler is accessible via COM.</p> <p>In PowerShell you can do this:</p> <pre><code>$svc = new-object -com Schedule.Service </code></pre> <p>... and that gives you a handle to the task scheduler. You can see what members it has using:</p> <pre><code>$svc | get-member </code></pre> <p>One of its methods is NewTask, so I'd start there.</p> <p>Edit: Some more info <a href="http://msdn.microsoft.com/en-us/library/aa446862.aspx" rel="nofollow noreferrer">here</a>. It's a VBScript example but it'll give you the gist.</p>
<p>@slipsec: I don't have access to a 2003 server to try, but googling "2003 server" SCHTASKS there are links related to questions about it. Perhaps you misspell the command? Like Matt says, you also can use AT, but in this case you don't have access to the scheduled tasks via the Control Panel, only via the AT command.</p>
5,388
<p>I'm having problems with Iterator.remove() called on a HashSet.</p> <p>I've a Set of time stamped objects. Before adding a new item to the Set, I loop through the set, identify an old version of that data object and remove it (before adding the new object). the timestamp is included in hashCode and equals(), but not equalsData().</p> <pre><code>for (Iterator&lt;DataResult&gt; i = allResults.iterator(); i.hasNext();) { DataResult oldData = i.next(); if (data.equalsData(oldData)) { i.remove(); break; } } allResults.add(data) </code></pre> <p>The odd thing is that i.remove() silently fails (no exception) for some of the items in the set. I've verified</p> <ul> <li><p>The line i.remove() is actually called. I can call it from the debugger directly at the breakpoint in Eclipse and it still fails to change the state of Set</p></li> <li><p>DataResult is an immutable object so it can't have changed after being added to the set originally.</p></li> <li><p>The equals and hashCode() methods use @Override to ensure they are the correct methods. Unit tests verify these work. </p></li> <li><p>This also fails if I just use a for statement and Set.remove instead. (e.g. loop through the items, find the item in the list, then call Set.remove(oldData) after the loop).</p></li> <li><p>I've tested in JDK 5 and JDK 6.</p></li> </ul> <p>I thought I must be missing something basic, but after spending some significant time on this my colleague and I are stumped. Any suggestions for things to check?</p> <p>EDIT:</p> <p>There have been questions - is DataResult truly immutable. Yes. There are no setters. And when the Date object is retrieved (which is a mutable object), it is done by creating a copy.</p> <pre><code>public Date getEntryTime() { return DateUtil.copyDate(entryTime); } public static Date copyDate(Date date) { return (date == null) ? null : new Date(date.getTime()); } </code></pre> <p>FURTHER EDIT (some time later): For the record -- DataResult was not immutable! It referenced an object which had a hashcode which changed when persisted to the database (bad practice, I know). It turned out that if a DataResult was created with a transient subobject, and the subobject was persisted, the DataResult hashcode was changed.</p> <p>Very subtle -- I looked at this many times and didn't notice the lack of immutability.</p>
<p>I was very curious about this one still, and wrote the following test:</p> <pre><code>import java.util.HashSet; import java.util.Iterator; import java.util.Random; import java.util.Set; public class HashCodeTest { private int hashCode = 0; @Override public int hashCode() { return hashCode ++; } public static void main(String[] args) { Set&lt;HashCodeTest&gt; set = new HashSet&lt;HashCodeTest&gt;(); set.add(new HashCodeTest()); System.out.println(set.size()); for (Iterator&lt;HashCodeTest&gt; iter = set.iterator(); iter.hasNext();) { iter.next(); iter.remove(); } System.out.println(set.size()); } } </code></pre> <p>which results in:</p> <pre><code>1 1 </code></pre> <p>If the hashCode() value of an object has changed since it was added to the HashSet, it seems to render the object unremovable.</p> <p>I'm not sure if that's the problem you're running into, but it's something to look into if you decide to re-visit this.</p>
<p>If there are two entries with the same data, only one of them is replaced... have you accounted for that? And just in case, have you tried another collection data structure that doesn't use a hashcode, say a List?</p>
31,742
<p>Wrote the following in PowersHell as a quick iTunes demonstration:</p> <pre><code>$iTunes = New-Object -ComObject iTunes.Application $LibrarySource = $iTunes.LibrarySource foreach ($PList in $LibrarySource.Playlists) { write-host $PList.name } </code></pre> <p>This works well and pulls back a list of playlist names. However on trying to close iTunes a warning appears</p> <blockquote> <p>One or more applications are using the iTunes scripting interface. Are you sure you want to quit?</p> </blockquote> <p>Obviously I can just ignore the message and press [Quit] or just wait the 20 seconds or so, but is there a clean way to tell iTunes that I've finished working with it?</p> <pre><code>Itunes 7.7.1, Windows XP </code></pre>
<p>Here is one thing that I did on my a Powershell script that adds podcasts to iTunes. I use Juice on a server to download all the podcasts that I listen to. The script uses .Net methods to release the COM objects. When I wrote my iTunes script I had read a couple of articles that stated you should release your COM objects using .NET.</p> <pre><code> [void][System.Runtime.InteropServices.Marshal]::ReleaseComObject([System.__ComObject]$LibrarySource) [void][System.Runtime.InteropServices.Marshal]::ReleaseComObject([System.__ComObject]$iTunes) </code></pre> <p>I also run my scripts the majority of time from a shortcut, not from the powershell prompt. </p> <p>Based on your comments, I did some testing and I determined that I would get the message when running against iTunes, if I ran my script in a way that leaves powershell running. iTunes seems to keep track of that. Running the script in a manner that exits it's process after running, eliminated the message.</p> <p>One method of running your script from powershell, is to prefix your script with powershell.</p> <pre><code>powershell .\scriptname.ps1</code></pre> <p>The above command will launch your script and then exit the process that was used to run it, but still leaving you at the powershell prompt.</p>
<p>You should be able to set $itunes to $null. Alternatively, $itunes should have a quit method you can call. $itunes.quit()</p>
7,551
<p>config file :</p> <pre><code>&lt;system.net&gt; &lt;mailSettings&gt; &lt;smtp from="YYYYY@xxxxxx.com"&gt; &lt;network host="mail.xxxxxx.com" port="25" password="password" userName="user@xxxxxx.com" defaultCredentials="false" /&gt; &lt;/smtp&gt; &lt;/mailSettings&gt; &lt;/system.net&gt; </code></pre> <p>I've already tried defaultCredentials="true" but i recieved following message:</p> <p>System.FormatException: Smtp server returned an invalid response.</p> <p>how to fix the problem?</p>
<p>Set the deliveryMethod property on the smtp element to 'network'. </p>
<p>Set the deliveryMethod property on the smtp element to 'network'. </p>
42,680
<p>This code</p> <pre><code>select.select([sys.stdin], [], [], 1.0) </code></pre> <p>does exactly what I want on Linux, but not in Windows.</p> <p>I've used <code>kbhit()</code> in <code>msvcrt</code> before to see if data is available on stdin for reading, but in this case it always returns <code>0</code>. Additionally <code>msvcrt.getch()</code> returns <code>'\xff'</code> whereas <code>sys.stdin.read(1)</code> returns <code>'\x01'</code>. It seems as if the msvcrt functions are not behaving properly.</p> <p>Unfortunately I can't use TCP sockets as I'm not in control of the application talking my Python program.</p>
<p>In some rare situations, you might care what stdin is connected to. Mostly, you don't care -- you just read stdin.</p> <p>In <code>someprocess | python myprogram.py</code>, stdin is connected to a pipe; in this case, the stdout of the previous process. You simply read from <code>sys.stdin</code> and you're reading from the other process. [Note that in Windows, however, there's still (potentially) a "CON" device with a keyboard. It just won't be <code>sys.stdin</code>.]</p> <p>In <code>python myprogram.py &lt;someFile</code>, stdin is connected to a file. You simply read from <code>sys.stdin</code> and you're reading from the file.</p> <p>In <code>python myprogram.py</code>, stdin is left connected to the console (<code>/dev/ttyxx</code> in *nix). You simple read from <code>sys.stdin</code> and you're reading from the keyboard.</p> <p>Note the common theme in the above three cases. You simply read from <code>sys.stdin</code> and your program's environment defines everything for you. You don't check "to see if data is available on stdin for reading". It's already available.</p> <p>Sometimes, you want a keyboard interrupt (or other shenanigans). Python, BTW, has a keyboard interrupt as a first-class feature of the I/O elements. Control-C raises an interrupt during I/O (it won't break into a tight loop, but it will signal a program that prints periodically.)</p> <p>Sometimes you need to find out what kind of file <code>stdin</code> is connected to.</p> <p>Something like <code>os.isatty( sys.stdin.fileno() )</code> If <code>sys.stdin</code> is a TTY, you're program was left connected to the windows "CON" (the keyboard). If <code>sys.stdin</code> is not a TTY, it's connected to a file or a pipe.</p> <hr> <p>Example</p> <pre><code>Microsoft Windows XP [Version 5.1.2600] (C) Copyright 1985-2001 Microsoft Corp. C:\Documents and Settings\slott&gt;python Python 2.5.2 (r252:60911, Feb 21 2008, 13:11:45) [MSC v.1310 32 bit (Intel)] on win32 Type "help", "copyright", "credits" or "license" for more information. &gt;&gt;&gt; import os &gt;&gt;&gt; import sys &gt;&gt;&gt; os.isatty( sys.stdin.fileno() ) True &gt;&gt;&gt; </code></pre> <p>The value of <code>True</code> tells me Python is running without a file or pipe attached. <code>sys.stdin</code> is the keyboard. Using windows <code>kbhit</code> is needless.</p> <p>A value of <code>False</code> tells me Python is running with a file or pipe attached. <code>sys.stdin</code> is NOT the keyboard. Checking <code>kbhit</code> might be meaningful. Also, I could open the <code>CON:</code> device and read the keyboard directly, separate from <code>sys.stdin</code>.</p> <hr> <p>I'm not sure why you need "to see if data is available on stdin for reading". It might help to update your question with additional details of what you're trying to accomplish.</p>
<p>I run a thread that reads from stdin, then forward the data to a socket. The socket is selectable, so, stdin is selectable too.</p> <blockquote> <p>In a recent project, I must continuously read from one network socket, forward to another socket, until the user inputs <code>q</code> from the console. One may think to use threading, but I don’t want to deal with multi-thread stuffs. Finally, I found a none-clear solution, and it worked.</p> <p>I create one thread – YES, thread, but no multi-thread concerns – this thread open a server socket listening on random port, then open a client socket connect to this server. The server socket accept the connection, then call <code>sys.stdin.read()</code> in a block way, all data read from stdin will write to that accepted connection. So client socket receive data reading from stdin. Now, the client socket is a <em>selectable</em> stdin, and it is thread-safe.</p> </blockquote> <p>Source code:</p> <pre><code># coding=UTF-8 &quot;&quot;&quot; === Windows stdio === @author ideawu@163.com @link http://www.ideawu.net/ File objects on Windows are not acceptable for select(), this module creates two sockets: stdio.s_in and stdio.s_out, as pseudo stdin and stdout. @example from stdio import stdio stdio.write('hello world') data = stdio.read() print stdio.STDIN_FILENO print stdio.STDOUT_FILENO &quot;&quot;&quot; import thread import sys, os import socket # socket read/write in multiple threads may cause unexpected behaviors # so use two separated sockets for stdin and stdout def __sock_stdio(): def stdin_thread(sock, console): &quot;&quot;&quot; read data from stdin, and write the data to sock &quot;&quot;&quot; try: fd = sys.stdin.fileno() while True: # DO NOT use sys.stdin.read(), it is buffered data = os.read(fd, 1024) #print 'stdin read: ' + repr(data) if not data: break while True: nleft = len(data) nleft -= sock.send(data) if nleft == 0: break except: pass #print 'stdin_thread exit' sock.close() def stdout_thread(sock, console): &quot;&quot;&quot; read data from sock, and write to stdout &quot;&quot;&quot; try: fd = sys.stdout.fileno() while True: data = sock.recv(1024) #print 'stdio_sock recv: ' + repr(data) if not data: break while True: nleft = len(data) nleft -= os.write(fd, data) if nleft == 0: break except: pass #print 'stdin_thread exit' sock.close() class Console: def __init__(self): self.serv = socket.socket(socket.AF_INET, socket.SOCK_STREAM) self.serv.bind(('127.0.0.1', 0)) self.serv.listen(5) port = self.serv.getsockname()[1] # data read from stdin will write to this socket self.stdin_sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) self.stdin_sock.connect(('127.0.0.1', port)) self.s_in, addr = self.serv.accept() self.STDIN_FILENO = self.s_in.fileno() thread.start_new_thread(stdin_thread, (self.stdin_sock, self)) # data read from this socket will write to stdout #self.stdout_sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) #self.stdout_sock.connect(('127.0.0.1', port)) #self.s_out, addr = self.serv.accept() #self.STDOUT_FILENO = self.s_out.fileno() #thread.start_new_thread(stdout_thread, (self.stdout_sock, self)) self.read_str = '' # read buffer for readline def close(self): self.s_in.close() self.s_out.close() self.stdin_sock.close() self.stdout_sock.close() self.serv.close() def write(self, data): try: return self.s_out.send(data) except: return -1 def read(self): try: data = self.s_in.recv(4096) except: return '' ret = self.read_str + data self.read_str = '' return ret def readline(self): while True: try: data = self.s_in.recv(4096) except: return '' if not data: return '' pos = data.find('\n') if pos == -1: self.read_str += data else: left = data[0 : pos + 1] right = data[pos + 1 : ] ret = self.read_str + left self.read_str = right return ret stdio = Console() return stdio def __os_stdio(): class Console: def __init__(self): self.STDIN_FILENO = sys.stdin.fileno() self.STDOUT_FILENO = sys.stdout.fileno() def close(self): pass def write(self, data): try: return os.write(self.STDOUT_FILENO, data) except: return -1 def read(self): try: return os.read(self.STDIN_FILENO, 4096) except: return '' def readline(self): try: return sys.stdin.readline() except: return '' stdio = Console() return stdio if os.name == 'posix': stdio = __os_stdio() else: stdio = __sock_stdio() </code></pre>
41,926
<p>I've written a IE Toolbar in C# and everything is working fine except that when I open a child Windows Form from my toolbar, the tab key doesn't work on the child form to allow me to move from field to field.</p> <p>The interesting part is that when I open my child form using form.showDialog() instead of form.show() the tabs work like normal.</p> <p>The toolbar I've created is based on this <a href="http://lamp.codeproject.com/KB/shell/dotnetbandobjects.aspx?fid=3788&amp;df=90&amp;mpp=25&amp;noise=3&amp;sort=Position&amp;view=Quick&amp;select=2766883&amp;fr=301#xx0xx" rel="nofollow noreferrer">article</a> and this <a href="https://secure.codeproject.com/KB/cs/Issuewithbandobjects.aspx" rel="nofollow noreferrer">article</a> </p> <p>I've implemented TranslateAcceleratorIO as mentioned in several articles, but still no luck.</p> <p>Here are my implmentations of TranslateAcceleratorIO() and HasFocusIO() (implemented in my toolband class)</p> <pre><code> [DllImport("user32.dll")] public static extern int TranslateMessage(ref MSG lpMsg); [DllImport("user32", EntryPoint = "DispatchMessage")] static extern bool DispatchMessage(ref MSG msg); public int HasFocusIO() { return this.ContainsFocus ? 0 : 1; //S_OK : S_FALSE; } public int TranslateAcceleratorIO(ref MSG msg) { if (msg.message == 0x100)//WM_KEYDOWN if (msg.wParam == (uint)Keys.Tab || msg.wParam ==(uint)Keys.F6) { if (SelectNextControl( ActiveControl, ModifierKeys == Keys.Shift ? false : true, true, true, false) ) { return 0;//S_OK } } else { TranslateMessage(ref msg); DispatchMessage(ref msg); return 0;//S_OK } return 1;//S_FALSE } </code></pre> <p>I've also tried having TranslateAccelerator like this with no luck:</p> <pre><code> public int TranslateAcceleratorIO(ref MSG msg) { TranslateMessage(ref msg); DispatchMessage(ref msg); return 0;//S_OK } </code></pre> <p>Has anybody else run into this issue?</p>
<p>Are you also implementing HasFocusIO? I believe your main toolbar class must also implement HasFocusIO and return true.</p> <p>These types of problems with IE toolbars were the bane of my existence for a while. I think what I eventually ended up doing was creating separate UI threads and making my dialogs modal in those threads, which eliminated a bunch of weird issues. But I think implementing HasFocusIO and TranslateAcceleratorIO should work for this particular one.</p>
<p>Where are you implementing these? It's hard to tell from what you have there, are you implementing them in your Form or are you implementing them in your deskband class? </p> <p>You need to implement them in your DeskBand implementation, and HasFocusIO needs to return true whenever one of your windows has focus (not just when the toolbar has focus). Then the messages for Tab, Delete, arrow keys, etc should be dispatched to the TranslateAcceleratorIO, also in your deskband, and from there you'll have to pass them along to your form. </p> <p>The IE plugin framework is incredibly hacky that way.</p>
27,068
<p>I'm looking for suggestions for a PHP:</p> <ol> <li>calendar control/widget that I can embed on a web page to enable users to select dates. A datepicker.</li> <li>calendar software that will provide weekly calendar view, similar to what Microsoft Outlook provides. It should display days of the week in columns and rows representing timeslots. Each cell would display events that occur on a day/timeslot <a href="https://i.stack.imgur.com/1QVT8.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/1QVT8.jpg" alt="alt text"></a><br> <sub>(source: <a href="https://www.microsoft.com/uk/atwork/images/office2007/outlook2007_todo.jpg" rel="nofollow noreferrer">microsoft.com</a>)</sub> </li> </ol> <p>I'm not looking for one piece of software that does both. It doesn't have to be fancy or full featured. I need something basic for a little project. It would be great if the software DIDN'T rely on a database or if it does, it can support Oracle.</p> <p>Thanks.</p>
<p>You can use the JQuery's datepicker:</p> <p>homepage: <a href="http://www.kelvinluck.com/assets/jquery/datePicker/" rel="nofollow noreferrer">http://www.kelvinluck.com/assets/jquery/datePicker/</a></p> <p>demos: <a href="http://www.kelvinluck.com/assets/jquery/datePicker/v2/demo/" rel="nofollow noreferrer">http://www.kelvinluck.com/assets/jquery/datePicker/v2/demo/</a></p> <p>As for a comprehensive calendar organizer unfortunately I don't know.</p>
<p>If you're willing to make a custom one take a look at the PHP <a href="http://docs.php.net/manual/en/book.calendar.php" rel="nofollow noreferrer">calendar book</a>. </p> <p>Unfortunately I haven't used any of these myself.</p>
32,059
<p>Using sql server 2000, I would like to take my production data and put it in my test database, but I don't want to overwrite the schema of the test database as there are fields in it that I haven't added to production yet. Can this be done? I should add that these databases are on different servers.</p>
<p>Use something like OmBelt's exportSQLServer to SQL tool. (ombelt.com)</p> <p>The inserts it makes specify fields so you should be okay. If not, mass-edit them.</p> <p>I find it greatly simplifies SQLServer to have SQL dumps like other databases.</p>
<p>If you use a tool to generate scripts that explicitly names columns (such as SSIS), it should work, as long as there aren't columns in your production database that don't exist in dev.</p>
12,435
<p>One of the things I like about coding "old skool" (web forms) is the AJAX Control Toolkit.</p> <p>I saw on the <a href="http://www.asp.net/learn/mvc-videos/video-373.aspx" rel="nofollow noreferrer">Microsoft Storefront video 14</a>, <a href="http://blog.wekeroad.com/mvc-storefront/mvcstore-part-14/" rel="nofollow noreferrer">Rob Conery uses the TextboxWatermark</a> control.</p> <p>When I <a href="http://www.codeplex.com/mvcsamples/SourceControl/changeset/view/9325" rel="nofollow noreferrer">downloaded the code</a> though, I couldn't find any reference to the Watermark control or any other control from the toolkit nor could I get it to work.</p> <p>So my question is, does the AJAX Control Toolkit even work in an MVC / AJAX / JQuery type world without viewstate. What do you use for "simple" controls such as Calendar &amp; Watermarks?</p>
<p><a href="http://ui.jquery.com/" rel="noreferrer">jQuery UI</a> has a calendar and other UI components. Also check out the vast number of <a href="http://plugins.jquery.com/" rel="noreferrer">jQuery plugins</a>.</p>
<p>Most of the AJAX Control Toolkit is available in MVC-friendly javascript form off the <a href="http://www.asp.net/ajaxlibrary/CDNACT40412.ashx" rel="nofollow noreferrer">MS AJAX CDN</a>. These can be used using a jquery plug-in syntax as well.</p>
48,053
<p>I've been developing a simple website using asp.net MVC and I'm starting to add some JQuery\JSON goodness. </p> <p>My problem is up until now all my 'Views' have been strongly typed and I've been building the view based on data from ViewData.Model.MyViewsData. Now once the view has been rendered and I do a Ajax style request I get new data back as JSON and I need to update my view. Now how can I update my view with the new data when I no longer have access to all the original ViewData?</p> <p>I'm guessing I need to one of two things, either: always fetch the data back using Jquery\JSON and forget about using ViewData or do some sort of partial rendering of my view?!</p> <p>Any tutorials or samples would be most appreciated.</p> <p>Many Thanks</p>
<p>I use jQuery and Monorail for an MVC framework - and we use both approaches.</p> <p><a href="https://remysharp.com/2007/01/20/auto-populating-select-boxes-using-jquery-ajax/" rel="nofollow noreferrer">Here's an example for the jquery approach</a> - ignore the fact it's php. The approach is the same, namely in the postback function in the JSON call, the JSON return object is accessed directly to populate front-end controls that are accessed via the css selector. </p> <p><a href="http://encosia.com/2008/03/27/using-jquery-to-consume-aspnet-json-web-services/" rel="nofollow noreferrer">The alternative is very similar</a> (archived <a href="https://web.archive.org/web/20101122205801/http://encosia.com/2008/03/27/using-jquery-to-consume-aspnet-json-web-services/" rel="nofollow noreferrer">here</a>) - instead of manually setting control contents, simply apply the html returned in the partial view (ensuring the layout is cancelled as you don't want menus etc just a html fragment).</p>
<p>If you use the Controller's JSON method to return data for your Ajax request, you can serialize your data to Json and then you have access to it from within your JavaScript. So as an example, If you had a comment form at the bottom of an Article/Blog Post page and you wanted to add the comment via a jQuery $.post call, you could create the comment object in your controller, return it using "return JSON(theNewComment);" and then in your return function in jQuery, you could access the properties of the comment object. You won't get intellisense, but if the object was properly created and returned, the data will be there.</p> <p>At that point, you need to use jQuery's DOM manipulation capabilities to plug the new values into your comment list (or whatever it is you are trying to update).</p> <p>Since it's an Ajax call, you shouldn't need all of your ViewData (since the page won't refresh), just the stuff that was created/updated.</p>
30,212
<p>In Java, say you have a class that wraps an <code>ArrayList</code> (or any collection) of objects. </p> <p>How would you return one of those objects such that the caller will not see any future changes to the object made in the ArrayList? </p> <p>i.e. you want to return a deep copy of the object, but you don't know if it is cloneable.</p>
<p>Turn that into a spec:<br> -that objects need to implement an interface in order to be allowed into the collection Something like <code>ArrayList&lt;ICloneable&gt;()</code></p> <p>Then you can be assured that you always do a deep copy - the interface should have a method that is guaranteed to return a deep copy. </p> <p>I think that's the best you can do. </p>
<p>I suppose it is an ovbious answer:</p> <p>Make a requisite for the classes stored in the collection to be cloneable. You could check that at insertion time or at retrieval time, whatever makes more sense, and throw an exception.</p> <p>Or if the item is not cloneable, just fail back to the return by reference option.</p>
4,962
<p>Are there any official naming conventions for tag names on Stack Exchange? And if not, how should tags be named?</p> <p>From what I understand, one typically adds a <em>dash</em> (-) where you normally would leave a <em>space</em>, but how about tags that derive from words that are <em><a href="https://3dprinting.meta.stackexchange.com/questions/150/tag-for-mattercontrol-app">CamelCased</a></em>, or somehow <em><a href="https://3dprinting.stackexchange.com/questions/tagged/postproduction">Prefixed</a></em>?</p> <p>Examples (which also shows some inconsistencies):</p> <pre><code>Topic | Existing tag | Alternative tag? ---------------------------------------------------------- MatterControl | matter-control | mattercontrol MakerBot | makerbot | maker-bot Post-production | postproduction | post-production Post-processing | post-processing | postprocessing Multi-material | multi-material | multimaterial </code></pre> <p>Which of the above tag alternatives should we go for?</p>
<p>Looking at other SE sites, the most common approach seems to make everything lowercase (including names and trademarks) and using hyphens whenever there would be a space or hyphen in normal usage.</p> <p>As such:</p> <ul> <li><p>MatterControl becomes mattercontrol</p></li> <li><p>Makerbot becomes makerbot</p></li> <li><p>Post-production becomes post-production</p></li> <li><p>Post-processing becomes post-processing</p></li> <li><p>Multi-material becomes multi-material</p></li> </ul>
<p>I would say we could use synonyms to stay with clear tag namespace.In this case we apply following pattern (especially for proper name (product name)):</p> <pre><code>Topic | Existing tag | Synonym? ---------------+-----------------+-------------- MatterControl | mattercontrol | matter-control </code></pre> <p>I think dash could be used to separate kinda branch for example:</p> <pre><code>app-cura, app-mattercontrol, app-meshmixer &lt;&lt; these could be also synonyms 3d-printer, 3d-models, 3d-design </code></pre> <p>of course we already have tags like</p> <pre><code>feature-request, switching-power-supply </code></pre> <p>but they are descriptive and would be unreadable written as one word, one may say these describe actions</p>
29
<p>What are the steps needed to successfully be able to remotely debug a stored procedure (SQL Server 2005) from within VS 2005? </p> <p>Both client and server machines are on the same domain. I have never done this so step by step instructions would greatly be appreciated.</p>
<p>Great Question! If I'm not mistaken I don't think debugging is possible inside of SQL Management Studio anymore (as it was back in the SQL Server 2000, Enterprise Studio days).</p> <h2>Instructions to Remote Debug MS SQL Stored Procedures within Visual Studio 2005</h2> <ol> <li>Launch Visual Studio (If you're running from Vista, <strong>Run As Administrator</strong>)</li> <li>Within Visual Studio 2005 click <strong>View-&gt;Server Explorer</strong>, which you'll notice brings up a panel with a <strong>Data Connections</strong> element.</li> <li>Right click on <strong>Data Connections</strong> and select <strong>Add Connection</strong></li> <li>Ensure the <strong>Data Source</strong> is set to <strong>SqlClient</strong>.</li> <li>Fill out the Server connection information, filling in the database name where the stored procedure that you wish to debug lives.</li> <li>Once a successful connection is made you'll notice the a tree for the database is populated that gives you the list of Tables, Views, Stored Procedures, Functions, etc.</li> <li>Expand <strong>Stored Procedures</strong>, finding the one you wish to debug and right click on it and select <strong>Step Into Stored Procedure</strong>.</li> <li>If the stored procedure has parameters a dialog will come up and you can specify what those parameters are.</li> <li>At this point, depending on your firewall settings and what not, you maybe be prompted to make modifications to your firewall to allow for the necessary ports to be opened up. However, Visual Studio seems to handle this for you.</li> <li>Once completed, Visual Studio should place you at the beginning of the stored procedure so you can starting the act of debugging!</li> </ol> <p>Happy Debugging!</p>
<p>SQL Specifically</p> <blockquote> <p><a href="http://msdn.microsoft.com/en-us/library/s4sszxst(VS.71).aspx" rel="nofollow noreferrer">http://msdn.microsoft.com/en-us/library/s4sszxst(VS.71).aspx</a></p> </blockquote> <p>VS2005 in general</p> <blockquote> <p><a href="http://msdn.microsoft.com/en-us/library/y7f5zaaa(VS.71).aspx" rel="nofollow noreferrer">http://msdn.microsoft.com/en-us/library/y7f5zaaa(VS.71).aspx</a></p> </blockquote>
17,205
<p>Ok, this is another one in the theory realm for the CS guys around.</p> <p>In the 90's I did fairly well in implementing BST's. The only thing I could never get my head around was the intricacy of the algorithm to balance a Binary Tree (AVL).</p> <p>Can you guys help me on this?</p>
<p>A scapegoat tree possibly has the simplest balance-determination algorithm to understand. If any insertion causes the new node to be too deep, it finds a node around which to rebalance, by looking at weight balance rather than height balance. The rule for whether to rebalance on delete is also simple. It doesn't store any arcane information in the nodes. It's trickier to prove that it's correct, but you don't need that to understand the algorithm...</p> <p>However, unlike an AVL it isn't height-balanced at all times. Like red-black its unbalance is bounded, but unlike red-black it's tunable with a parameter, so for most practical purposes it looks as balanced as you need it to be. I suspect that if you tune it too tightly, though, it ends up as bad or worse than AVL for worst-case insertions.</p> <p><strong>Response to question edit</strong></p> <p>I'll provide my personal path to understanding AVL trees.</p> <p>First you have to understand what a tree rotation is, so ignore everything else you've ever heard the AVL algorithms and understand that. Get straight in your head which is a right rotation and which is a left rotation, and what each does to the tree, or else the descriptions of the precise methods will just confuse you.</p> <p>Next, understand that the trick for balancing AVL trees is that each node records in it the difference between the height of its left and right subtrees. The definition of 'height balanced' is that this is between -1 and 1 inclusive for every node in the tree.</p> <p>Next, understand that if you have added or removed a node, you may have unbalanced the tree. But you can only have changed the balance of nodes which are ancestors of the node you added or removed. So, what you're going to do is work your way back up the tree, using rotations to balance any unbalanced nodes you find, and updating their balance score, until the tree is balanced again.</p> <p>The final part of understanding it is to look up in a decent reference the specific rotations used to rebalance each node you find: this is the "technique" of it as opposed to the high concept. You only have to remember the details while modifying AVL tree code or maybe during data structures exams. It's years since I last had AVL tree code so much as open in the debugger - implementations tend to get to a point where they work and then stay working. So I really do not remember. You can sort of work it out on a table using a few poker chips, but it's hard to be sure you've really got all the cases (there aren't many). Best just to look it up.</p> <p>Then there's the business of translating it all into code.</p> <p>I don't think that looking at code listings helps very much with any stage except the last, so ignore them. Even in the best case, where the code is clearly written, it will look like a textbook description of the process, but without the diagrams. In a more typical case it's a mess of C struct manipulation. So just stick to the books.</p>
<p>The AVL tree is inefficient because you have to do potentially many rotations per insertion/deletion.</p> <p>The Red-Black tree is probably a better alternative because insertions/deletions are much more efficient. This structure guarantees the longest path to a leaf is no more than twice the shortest path. So while less balanced than an AVL tree, the worst unbalanced cases are avoided.</p> <p>If your tree will be read many times, and won't be altered after it's created, it may be worth the extra overhead for a fully-balanced AVL tree. Also the Red-Black tree requires one extra bit of storage for each node, which give the node's "color".</p>
16,172
<p>Apparently, they're "confusing". Is that seriously the reason? Can you think of any others?</p>
<p>Have you seen how many developers don't really understand ref/out?</p> <p>I use them where they're really necessary, but not otherwise. They're usually only useful if you want to effectively return two or more values - in which case it's worth at least <em>thinking</em> about whether there's a way of making the method only do one thing instead. Sometimes using ref/out <em>is</em> the most appropriate approach - the various TryParse methods etc.</p>
<p>Isn't code complexity reason enough? Compare:</p> <pre><code>int myValue; ReadFromSomewhere(ref myValue); </code></pre> <p>To:</p> <pre><code>int myValue = ReadFromSomewhere(); </code></pre>
26,387
<p>I have a webapp development problem that I've developed one solution for, but am trying to find other ideas that might get around some performance issues I'm seeing.</p> <p>problem statement: </p> <ul> <li>a user enters several keywords/tokens</li> <li>the application searches for matches to the tokens</li> <li>need one result for each token <ul> <li>ie, if an entry has 3 tokens, i need the entry id 3 times</li> </ul></li> <li>rank the results <ul> <li>assign X points for token match</li> <li>sort the entry ids based on points</li> <li>if point values are the same, use date to sort results</li> </ul></li> </ul> <p>What I want to be able to do, but have not figured out, is to send 1 query that returns something akin to the results of an in(), but returns a duplicate entry id for each token matches for each entry id checked.</p> <p>Is there a better way to do this than what I'm doing, of using multiple, individual queries running one query per token? If so, what's the easiest way to implement those?</p> <p><strong>edit</strong><br> I've already tokenized the entries, so, for example, "see spot run" has an entry id of 1, and three tokens, 'see', 'spot', 'run', and those are in a separate token table, with entry ids relevant to them so the table might look like this:</p> <pre><code>'see', 1 'spot', 1 'run', 1 'run', 2 'spot', 3 </code></pre>
<p>you could achive this in one query using 'UNION ALL' in MySQL.</p> <p>Just loop through the tokens in PHP creating a UNION ALL for each token:</p> <p>e.g if the tokens are 'x', 'y' and 'z' your query may look something like this</p> <pre><code>SELECT * FROM `entries` WHERE token like "%x%" union all SELECT * FROM `entries` WHERE token like "%y%" union all SELECT * FROM `entries` WHERE token like "%z%" ORDER BY score ect... </code></pre> <p>The order clause should operate on the entire result set as one, which is what you need.</p> <p>In terms of performance it won't be all that fast (I'm guessing), however with databases the main overhead in terms of speed is often sending the query to the database engine from PHP and receiving the results. With this technique this only happens once instead of once per token, so performance will increase, I just don't know if it'll be enough.</p>
<p>You'll probably get much better performance if you used a data structure designed for search tasks rather than a database. For example, you might try looking at building an <a href="http://en.wikipedia.org/wiki/Inverted_index" rel="nofollow noreferrer">inverted index</a>. Rather than writing it youself, however, you might also want to look into something like <a href="http://en.wikipedia.org/wiki/Lucene" rel="nofollow noreferrer">Lucene</a> which does most of the work for you.</p>
7,002
<p>At work, we have one of those nasty communal urinals. There is no flush handle. Rather, it has a motion sensor that sometimes triggers when you stand in front of it and sometimes doesn't. When it triggers, a tank fills, which when full is used to flush the urinal.</p> <p>In my many trips before this nastraption, I have pondered both what the algorithm is the box uses to determine when to turn on and what would be the optimal algorithm, in terms of conserving water while still maintaining a relatively pleasant urinal experience.</p> <p>I'll share my answer once folks have had a chance to share their ideas.</p>
<pre><code>OnUserEnter() { if (UsersDetected == 0) { FirstDetectionTime = Now(); } UsersDetected++; CurrentlyInUse = true; } OnUserExit() { CurrentlyInUse = false; if (UsersDetected &gt;= MaxUsersBetweenFlushes || Now() - FirstDetectionTime &gt; StinkInterval) { Flush(); } } OnTimer() { if (!CurrentlyInUse &amp;&amp; UsersDetected &gt; 0 &amp;&amp; Now() - FirstDetectionTime &gt; StinkInterval) { Flush(); } } Flush() { FlushTheUrinal(); UsersDetected = 0; } </code></pre>
<p>At the risk of sounding Ludditish, I think the best solution is a handle. But that isn't the question. I would assume the mechanism is very simple. Someone moves in front of it, a count starts. When the count is fulfilled, the urinal is "primed". When the person moves away, the trigger is pulled, and the sensor turns off for an arbitrary amount of time (I don't think it has or needs any awareness of the act of flushing/tank-refilling). </p> <p>Am I overthinking this?</p>
29,365
<p>When I iterate over the values or keys are they going to correlate? Will the second key map to the second value?</p>
<p>No, not necessarily. You should really use the entrySet().iterator() for this purpose. With this iterator, you will be walking through all Map.Entry objects in the Map and can access each key and associated value.</p>
<p>The question confused me at first but @Matt cleared it up for me.</p> <p>Consider using the entrySet() method that returns a set with the key-value pairs on the Map.</p> <pre><code>Map&lt;Integer, Integer&gt; a = new HashMap&lt;Integer, Integer&gt;(2); a.put(1, 2); a.put(2, 3); for (Map.Entry&lt;Integer, Integer&gt; entry : a.entrySet()) { System.out.println(entry.getKey() + " =&gt; " + entry.getValue()); } </code></pre> <p>This outputs:</p> <pre><code>1 =&gt; 2 2 =&gt; 3 3 =&gt; 3 </code></pre>
15,577
<p>I have a problem with a string in C++ which has several words in Spanish. This means that I have a lot of words with accents and tildes. I want to replace them for their not accented counterparts. Example: I want to replace this word: "había" for habia. I tried replace it directly but with replace method of string class but I could not get that to work.</p> <p>I'm using this code:</p> <pre><code>for (it= dictionary.begin(); it != dictionary.end(); it++) { strMine=(it-&gt;first); found=toReplace.find_first_of(strMine); while (found!=std::string::npos) { strAux=(it-&gt;second); toReplace.erase(found,strMine.length()); toReplace.insert(found,strAux); found=toReplace.find_first_of(strMine,found+1); } } </code></pre> <p>Where <code>dictionary</code> is a map like this (with more entries):</p> <pre><code>dictionary.insert ( std::pair&lt;std::string,std::string&gt;("á","a") ); dictionary.insert ( std::pair&lt;std::string,std::string&gt;("é","e") ); dictionary.insert ( std::pair&lt;std::string,std::string&gt;("í","i") ); dictionary.insert ( std::pair&lt;std::string,std::string&gt;("ó","o") ); dictionary.insert ( std::pair&lt;std::string,std::string&gt;("ú","u") ); dictionary.insert ( std::pair&lt;std::string,std::string&gt;("ñ","n") ); </code></pre> <p>and <code>toReplace</code> strings is:</p> <pre><code>std::string toReplace="á-é-í-ó-ú-ñ-á-é-í-ó-ú-ñ"; </code></pre> <p>I obviously must be missing something. I can't figure it out. Is there any library I can use?.</p> <p>Thanks,</p>
<p>First, this is a really bad idea: you’re mangling somebody’s language by removing letters. Although the extra dots in words like “naïve” seem superfluous to people who only speak English, there are literally thousands of writing systems in the world in which such distinctions are very important. Writing software to mutilate someone’s speech puts you squarely on the wrong side of the tension between using computers as means to broaden the realm of human expression vs. tools of oppression.</p> <p>What is the reason you’re trying to do this? Is something further down the line choking on the accents? Many people would love to help you solve that.</p> <p>That said, libicu can do this for you. Open the <a href="http://www.icu-project.org/icu-bin/translit" rel="noreferrer">transform demo</a>; copy and paste your Spanish text into the “Input” box; enter</p> <pre><code>NFD; [:M:] remove; NFC </code></pre> <p>as “Compound 1” and click transform.</p> <p>(With help from slide 9 of <a href="http://macchiato.com/slides/icu_transforms.pdf" rel="noreferrer">Unicode Transforms in ICU</a>. Slides 29-30 show how to use the API.)</p>
<p>If you can (if you're running Unix), I suggest using the <a href="http://www.gnu.org/software/coreutils/manual/html_node/tr-invocation.html" rel="nofollow noreferrer"><code>tr</code></a> facility for this: it's custom-built for this purpose. Remember, no code == no buggy code. :-)</p> <p>Edit: Sorry, you're right, <code>tr</code> doesn't seem to work. How about <code>sed</code>? It's a pretty stupid script I've written, but it works for me.</p> <pre><code>#!/bin/sed -f s/á/a/g; s/é/e/g; s/í/i/g; s/ó/o/g; s/ú/u/g; s/ñ/n/g; </code></pre>
17,460
<p>I'm trying to decode a WBXML encoded SyncML message from a Nokia N95. My first attempt was to use the python pywbxml module which wraps calls to libwbxml. Decoding the message with this gave a lot of &lt;unknown&gt; tags and a big chunk of binary within a &lt;Collection&gt; tag. I tried running the contents of the &lt;Collection&gt; through by itself but it failed. Is there something I'm missing?</p> <p>Also, does anyone know of a pure python implementation of a wbxml parser? Failing that a command line or online tool to decode these messages would be useful -- it would make it a lot easier for me to write my own...</p>
<p>I ended up writing a python parser myself. I managed to do it by following the spec here: <a href="http://www.w3.org/TR/wbxml/" rel="nofollow noreferrer">http://www.w3.org/TR/wbxml/</a></p> <p>And then taking the code tables from the horde.org cvs.</p> <p>The open mobile alliance's site and documentation are terrible, this was a very trying project :(</p>
<p>I used <a href="https://github.com/diegows/pywbxml/" rel="nofollow noreferrer">pywbxml</a> , Just needed one patch in pywbxml.pyx:</p> <p><code>params.lang</code> in function <code>wbxml2xml</code> around <a href="https://github.com/diegows/pywbxml/blob/254030c8413ceab710838ff544c83bc343ddbd8c/0.1/src/pywbxml.pyx#L25" rel="nofollow noreferrer">line 25</a> set to:</p> <pre><code>params.lang = WBXML_LANG_UNKNOWN </code></pre> <p>works like charm. Also changing base class for WBXMLParseError to exception helps:</p> <pre><code>class WBXMLParseError(Exception): </code></pre>
27,971
<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>
<p>This is the single connection way:</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;store_result(); // &lt;-- this $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;store_result(); // &lt;-- this /*DO WHATEVER WITH STMT2*/ $stmt2-&gt;close(); } } } </code></pre>
<p>Or use <a href="http://php.net/manual/en/mysqli.store-result.php" rel="nofollow noreferrer"><code>store_result</code></a>.</p>
13,784
<p>I have a class hierarchy as such:</p> <pre><code> +-- VirtualNode | INode --+ +-- SiteNode | | +-- AbstractNode --+ | +-- SiteSubNode </code></pre> <p>And a corresponding <code>NodeCollection</code> class that is build on <code>INode</code>. In order to display a <code>NodeCollection</code> I need to know the final type of each member. So I need a function like this</p> <pre><code>foreach (INode n in myNodeCollection) { switch(n.GetType()) { case(typeof(SiteNode)): // Display n as SiteNode } } </code></pre> <p>Now, this is really not an object oriented way of doing it. <strong>Are there any patterns or recommended ways of doing the same thing, in your opinion?</strong></p> <p><strong>EDIT</strong><br> I already thought of adding a <code>Display</code> or <code>Render</code> method to the INode interface. That has the side effect of coupling the view to the model, which I would really like to avoid.</p>
<p>What you're after is the <a href="http://en.wikipedia.org/wiki/Visitor_pattern" rel="nofollow noreferrer">visitor pattern</a>, I think.</p>
<p>If you can change the INode interface - add a virtual method that returns the "view" and override it in the inherited classes.</p> <p>If you can't change the base interface - implement extension methods for each of the classes and have them return the "view" of for each particular class.</p>
22,593
<p>I have a subversion repository that contains a number so subfolders, corresponding to the various applications, configuration files, DLLs, etc (I'll call them 'modules') that make up my project. Now we are starting to "branch" into several related projects. That is, each high-level project will use a number of the modules, possibly slightly modified from project to project. The number of projects is smaller (~5) than the number of modules (~20)</p> <p>Now I'm trying to figure out how to organize the repo. Does it make sense to keep the top level subfolders on a module-by-module basis, with sub-subfolders for each project? Or should the top level be for each project, with each project having its own module subfolders:</p> <p>repo:</p> <pre><code>module 1 Project 1 Project 2 ... Project 5 module 2 Project 1 .... Project 5 .... module 20 Project 1 ... Project 5 </code></pre> <p>-or-</p> <p>repo:</p> <pre><code>Project 1 module 1 module 2 ... module 20 Project 2 module 1 module 2 ... module 20 ... Project 5 module 1 module 2 ... module 20 </code></pre>
<p>It would seem best to organize by <strong>Project</strong> at the top level, since you're going to want to checkout an entire branch and have a working copy for the project. If you organize by module, you'll have to do multiple checkouts (one for each module you're using) in order to build your project to a point where it's useable.</p> <p>It could make sense to keep both projects and modules separate, E.g.:</p> <pre><code>Projects Project 1 Project 2 ... Modules Module 1 Module 2 ... </code></pre> <p>If you use that in combination with svn <a href="http://svnbook.red-bean.com/en/1.0/ch07s03.html" rel="nofollow noreferrer"><strong>externals</strong></a> and/or <a href="http://svnbook.red-bean.com/en/1.1/ch07s05.html" rel="nofollow noreferrer"><strong>vendor branches</strong></a>, you could support different branches for your projects that need different module versions, but still benefit from the having a single module source when projects happen to share the same version of a module.</p>
<p>I think that your use of "high-level" to describe what a project is suggests that you should have a Projects/modules setup.</p> <p>However you could have a Modules and Projects set up - i.e., they are at the same level in the SVN repo. Your Projects can rely on Modules, and if possible the Projects can provide specific implementations of actions, turning the module into a base module with default but overrideable implementations.</p>
16,191
<p>I have some jQuery/JavaScript code that I want to run only when there is a hash (<code>#</code>) anchor link in a URL. How can you check for this character using JavaScript? I need a simple catch-all test that would detect URLs like these:</p> <ul> <li><code>example.com/page.html#anchor</code></li> <li><code>example.com/page.html#anotheranchor</code></li> </ul> <p>Basically something along the lines of:</p> <pre><code>if (thereIsAHashInTheUrl) { do this; } else { do this; } </code></pre>
<p>Simple use of <a href="https://developer.mozilla.org/en-US/docs/Web/API/Location/hash" rel="noreferrer">location hash</a>:</p> <pre><code>if(window.location.hash) { // Fragment exists } else { // Fragment doesn't exist } </code></pre>
<p>sometimes you get the full query string such as "#anchorlink?firstname=mark"</p> <p>this is my script to get the hash value:</p> <pre><code>var hashId = window.location.hash; hashId = hashId.match(/#[^?&\/]*/g); returns -> #anchorlink </code></pre>
38,212
<p>When would I implement IDispose on a class as opposed to a destructor? I read <a href="http://www.dotnetspider.com/resources/1382-Understanding-IDisposable-pattern.aspx" rel="noreferrer">this article</a>, but I'm still missing the point. </p> <p>My assumption is that if I implement IDispose on an object, I can explicitly 'destruct' it as opposed to waiting for the garbage collector to do it. Is this correct?</p> <p>Does that mean I should always explicitly call Dispose on an object? What are some common examples of this?</p>
<p>A finalizer (aka destructor) is part of garbage collection (GC) - it is indeterminate when (or even if) this happens, as GC mainly happens as a result of memory pressure (i.e. need more space). Finalizers are usually only used for cleaning up <em>unmanaged</em> resources, since managed resources will have their own collection/disposal.</p> <p>Hence <code>IDisposable</code> is used to <em>deterministically</em> clean up objects, i.e. now. It doesn't collect the object's memory (that still belongs to GC) - but is used for example to close files, database connections, etc.</p> <p>There are lots of previous topics on this:</p> <ul> <li><a href="https://stackoverflow.com/questions/188473/how-do-you-manage-deterministic-finalization-in-c">deterministic finalization</a></li> <li><a href="https://stackoverflow.com/questions/245856/when-should-i-dispose-my-objects-in-net">disposing objects</a></li> <li><a href="https://stackoverflow.com/questions/212198/what-is-the-c-using-block-and-why-should-i-use-it">using block</a></li> <li><a href="https://stackoverflow.com/questions/117135/resources-that-have-to-be-manually-cleaned-up-in-c">resources</a></li> </ul> <p>Finally, note that it is not uncommon for an <code>IDisposable</code> object to also have a finalizer; in this case, <code>Dispose()</code> usually calls <code>GC.SuppressFinalize(this)</code>, meaning that GC doesn't run the finalizer - it simply throws the memory away (much cheaper). The finalizer still runs if you forget to <code>Dispose()</code> the object.</p>
<p>Here is another fine article which clears up some of the mist surrounding IDisposable, the GC and dispose.</p> <p><a href="http://blogs.msdn.com/clyon/archive/2004/09/21/232445.aspx" rel="nofollow noreferrer">Chris Lyons WebLog Demystifying Dispose</a></p>
44,029
<p>Imagine we have a program trying to write to a particular file, but failing.</p> <p>On the Windows platform, what are the possible things which might be causing the file to be un-writable, and what steps could be suggested to an end user/administrator to fix it.</p> <hr /> <p>Please include steps which might require administrator permissions (obviously users may not be administrators, but for this question, let's assume they are (or can become) administrators.</p> <p>Also, I'm not really familiar with how permissions are calculated in windows. - Does the user need write access to each directory up the tree, or anything similar to that?</p>
<p>Some suggestions:</p> <ul> <li>No write permission (get permission through Security tab on file Properties window; you must be the file owner or an Administrator)</li> <li>File is locked (close any program that may have the file open, then reboot if that doesn't help)</li> <li>File has the read-only DOS attribute set (unset it from file Properties window, or with <code>attrib -r</code>; you must be the file owner or an Administrator)</li> </ul> <p>Edit 1: Only the second item (file is locked) has a possible solution that all users are likely to be able to do without help. For the first and third, you'll probably want to provide guidance (and hope the file wasn't made read-only intentionally!).</p> <p>Edit 2: Technically, the user does need write and execute (chdir) permissions on all directories up to the root. Windows may skip some of the recursive checks up the tree as a performance optimization, but you should not rely on this because admins can force on these so-called "traverse checks" for certain users.</p> <p>Edit 3: @RobM: Yes, you should check that there is no obvious reason that the user should not have the permissions she needs but does not have. I alluded to this in a less direct way in my first edit. However, in some cases users should have write permission to a file but do not because of filesystem corruption, a misbehaving program, or a mistake on their own part.</p>
<p>On Vista could it also be that it's "marked" as unsafe because it's been downloaded from the internet and you have to click the unblock button on it's explorer properties dialog?</p>
5,824
<p>I've read the several discussions about storing code snippets but I did't find the info that I'm looking for, so let's define it:</p> <ul> <li>At home, I have several side projects, most of them quite small, one large, and numerous little examples that demonstrate a specific language feature (for example, some template trick in C++).</li> <li>Since I think that these examples will be useful to be available when I'm at work for a reference instead of trying to remember the exact details of this or that particular snippet that was tried and worked at home, I want to have it available for example on a USB flash drive.</li> <li>The problem is that most of the snippets/small programs/examples are organized, written, compiled and tested in Visual Studio, it will be duplication if I have to put them in some code snippet organizer application. I can copy to the flash drive the source of the Visual Studio solution with all the examples, but it is not so convenient for searching compared with a dedicated snippet repository organizer. Or maybe I can change this if I write better comments and description of the examples, and that will do the job.</li> </ul> <p>Any ideas, best practices, solutions, and experience with similar stuff are appreciated.</p>
<p>I keep everything in a source control repository, indexed by language. As I learn new languages, I translate some of my old useful stuff into the new language to learn how to do things in the new language. </p>
<p>I work in Visual Studio at home and at work.</p> <p>I basically have all my code snippets in a folder that is synced to my <a href="https://www.mesh.com/Welcome/Default.aspx" rel="nofollow noreferrer">Live Mesh</a>. I then have each folder added to VS to enable it to auto-detect new snippets. Works like a charm for me :)</p> <p>So, I create a snippet in <a href="http://www.codeplex.com/snippy" rel="nofollow noreferrer">Snippy</a>, save it to my synced folder. Boom, works in VS with no additional configuration at all :)</p>
42,059
<p>I've decided to reimplement the datetime picker, as a standard datetime picker isn't nullable. The user wants to start with a blank field and type (not select) the date.</p> <p>I've created a user control to do just that, but if the user control is near the edge of the form, it will be cut off on the form boundry. The standard datetime picker doesn't suffer from this problem.</p> <p>Here is a picture showing the problem. My user control is on the left, the standard datetimepicker is on the right:</p> <p><a href="http://img50.imageshack.us/img50/9104/datetimepickervu6.jpg">alt text http://img50.imageshack.us/img50/9104/datetimepickervu6.jpg</a></p> <p>As you can see, the standard control will display over the form AND application boundry. How do I get the month picker in my control to do the same thing?</p> <p>Thanks!</p>
<p>The ToolStripDropDown control has this functionallity so by inheriting from it we can make a simple PopupWindow.</p> <pre><code>/// &lt;summary&gt; /// A simple popup window that can host any System.Windows.Forms.Control /// &lt;/summary&gt; public class PopupWindow : System.Windows.Forms.ToolStripDropDown { private System.Windows.Forms.Control _content; private System.Windows.Forms.ToolStripControlHost _host; public PopupWindow(System.Windows.Forms.Control content) { //Basic setup... this.AutoSize = false; this.DoubleBuffered = true; this.ResizeRedraw = true; this._content = content; this._host = new System.Windows.Forms.ToolStripControlHost(content); //Positioning and Sizing this.MinimumSize = content.MinimumSize; this.MaximumSize = content.Size; this.Size = content.Size; content.Location = Point.Empty; //Add the host to the list this.Items.Add(this._host); } } </code></pre> <p>Usage:</p> <pre><code>PopupWindow popup = new PopupWindow(MyControlToHost); popup.Show(new Point(100,100)); ... popup.Close(); </code></pre>
<p>The reason that your control gets chopped off is because it is a child control of the form that you reside on. Any control on the form must be contained by the form, hence it gets chopped off.</p> <p>I haven't done this in .Net, but had a similar problem in VB6. The solution then was to set the parent of the popup window (the calendar in your case) to be the desktop. This will allow it to extend beyond the boundaries of your form. You'll have to do some P/Invoke magic to find the hWnd of the popup, and another P/Invoke to set the parent.</p>
35,529
<p>I have code like this:</p> <pre><code>class RetInterface {...} class Ret1: public RetInterface {...} class AInterface { public: virtual boost::shared_ptr&lt;RetInterface&gt; get_r() const = 0; ... }; class A1: public AInterface { public: boost::shared_ptr&lt;Ret1&gt; get_r() const {...} ... }; </code></pre> <p><strong>This code does not compile.</strong></p> <p>In visual studio it raises</p> <blockquote> <p>C2555: overriding virtual function return type differs and is not covariant</p> </blockquote> <p>If I do not use <code>boost::shared_ptr</code> but return raw pointers, the code compiles (I understand this is due to <a href="http://en.wikipedia.org/wiki/Parameter_covariance#C.2B.2B" rel="noreferrer">covariant return types</a> in C++). I can see the problem is because <code>boost::shared_ptr</code> of <code>Ret1</code> is not derived from <code>boost::shared_ptr</code> of <code>RetInterface</code>. But I want to return <code>boost::shared_ptr</code> of <code>Ret1</code> for use in other classes, else I must cast the returned value after the return. </p> <ol> <li>Am I doing something wrong? </li> <li>If not, why is the language like this - it should be extensible to handle conversion between smart pointers in this scenario? Is there a desirable workaround?</li> </ol>
<p>Firstly, this is indeed how it works in C++: the return type of a virtual function in a derived class must be the same as in the base class. There is the special exception that a function that returns a reference/pointer to some class X can be overridden by a function that returns a reference/pointer to a class that derives from X, but as you note this doesn't allow for <em>smart</em> pointers (such as <code>shared_ptr</code>), just for plain pointers.</p> <p>If your interface <code>RetInterface</code> is sufficiently comprehensive, then you won't need to know the actual returned type in the calling code. In general it doesn't make sense anyway: the reason <code>get_r</code> is a <code>virtual</code> function in the first place is because you will be calling it through a pointer or reference to the base class <code>AInterface</code>, in which case you can't know what type the derived class would return. If you are calling this with an actual <code>A1</code> reference, you can just create a separate <code>get_r1</code> function in <code>A1</code> that does what you need.</p> <pre><code>class A1: public AInterface { public: boost::shared_ptr&lt;RetInterface&gt; get_r() const { return get_r1(); } boost::shared_ptr&lt;Ret1&gt; get_r1() const {...} ... }; </code></pre> <p>Alternatively, you can use the visitor pattern or something like my <a href="http://www.ddj.com/dept/cpp/184429055" rel="noreferrer">Dynamic Double Dispatch</a> technique to pass a callback in to the returned object which can then invoke the callback with the correct type.</p>
<p><a href="https://stackoverflow.com/questions/196733/smart-pointer-and-virtual#196744">Mr Fooz </a> answered part 1 of your question. Part 2, it works this way because the compiler doesn't know if it will be calling AInterface::get_r or A1::get_r at compile time - it needs to know what return value it's going to get, so it insists on both methods returning the same type. This is part of the C++ specification.</p> <p>For the workaround, if A1::get_r returns a pointer to RetInterface, the virtual methods in RetInterface will still work as expected, and the proper object will be deleted when the pointer is destroyed. There's no need for different return types.</p>
23,904
<p>I am trying to display object data members in a generic way. I started by using PropertyGrid, which satisfies my needs as far as simple properties are concerned. However, it doesn't let the user drill-down into data members. It allows browsing into collections, but the interface is a bit awkward.</p> <p>I'm basically looking for something with the features of QuickWatch. Does anybody know of any libraries that can do drill-down?</p>
<p>You can drill down into properties in the PropertyGrid of course. This is a vast subject, but maybe your properties simply need to have the ExpandableObjectConverter attached to them? Or if you are going more into details, the attached TypeConverter needs to override the GetPropertiesSupported and GetProperties methods.</p> <p>There is another way to tell the grid what properties to show underneath a property. You can implement ICustomTypeDescriptor and return your own PropertyDescriptors. But usually this is for more complex scenarios.</p> <p>Let me know if you need any specific detail on this.</p> <p><strong>Update:</strong> in the comments, you asked about displaying a Dictionary. If you want to see each entry of your dict as a subproperty, then this is the complex scenario mentioned above. Your TypeConverter or custom TypeDescriptor will have to generate a PropertyDescriptor for each entry. Its name will be the key and its value will be ... well ... the property value. If you are new to the PropertyGrid, I encourage you to read a lot about it because it can be quite complex and you will find a good list of resources to start here: <a href="http://www.propertygridresourcelist.com" rel="nofollow noreferrer">www.propertygridresourcelist.com</a></p>
<p>I would use a treeview control, styled to look like a 'grid'. Then as you drill down, you can dynamically load any child items that you need to.</p>
28,437
<p>I'm trying to write rules for detecting some errors in <em>annotated</em> multi-threaded java programs. As a toy example, I'd like to detect if any method annotated with @ThreadSafe calls a method without such an annotation, without synchronization. I'm looking for a tool that would allow me to write such a test. </p> <p>I've looked at source analyzers, like CheckStyle and PMD, and they don't really have cross-class analysis capabilities. Bytecode analysers, like FindBugs and JLint seem rather difficult to extend.</p> <p>I'd settle for a solution to something even simpler, but posing the same difficulty: writing a <em>custom</em> rule that checks whether each overriden method is annotated with @Override. </p>
<p>Have you tried <a href="http://findbugs.sourceforge.net/" rel="nofollow noreferrer">FindBugs</a>? It actually supports a set of <a href="http://www.javaconcurrencyinpractice.com/annotations/doc/net/jcip/annotations/package-summary.html" rel="nofollow noreferrer">annotations for thread safety</a> (the same as those used in <a href="http://www.javaconcurrencyinpractice.com" rel="nofollow noreferrer">Java Concurrency in Practice</a>). Also, you can write your own custom rules. I'm not sure whether you can do cross-class analysis, but I believe so. </p> <p><a href="http://pveentjer.wordpress.com" rel="nofollow noreferrer">Peter Ventjeer</a> has a <a href="http://pveentjer.wordpress.com/2008/05/26/the-concurrency-detector/" rel="nofollow noreferrer">concurrency checking tool</a> (that uses ASM) to detect stuff like this. I'm not sure if he's released it publicly but he might able to help you. </p> <p>And I believe <a href="http://www.coverity.com/" rel="nofollow noreferrer">Coverity's</a> static/dynamic analysis tools for thread safety do checking like this.</p>
<p>A simple tool to checkup on annotations is apt (<a href="http://java.sun.com/j2se/1.5.0/docs/guide/apt/" rel="nofollow noreferrer">http://java.sun.com/j2se/1.5.0/docs/guide/apt/</a> also part of Java 6 api in javax.annotation.processing) however this only has type information (ie I couldn't find a quick way to get at the inheritance hierarchy using the javax.lang.model api, however if you can load the class you can get that information using reflection).</p>
34,862
<p>In the following table structure:</p> <pre><code>Fruits ( fruit_id, fruitName ) Vegetables ( vegetable_id, vegetableName ) favoriteFoods ( food_id, foodName, type_id (References either a fruit or a vegetable) ) </code></pre> <p>I realize that I could forgo using a foreign key constraint on the favoriteFoods table and then simply add a type field to the favoriteFoods table to differentiate between fruits and vegetables. But how would you structure the tables so that you could actually create the necessary foreign key constraints? </p>
<p>I would only use 2 tables instead. Instead of having a separate Fruits and Vegetables table, why not have a table of Foods. Then have a foreign key constraint on fkfood_id to food_id. Then if for some reason you ever have to add meat, it would be much easier to maintain the application that uses this.</p> <pre><code>Food ( food_id, foodName, foodType ) favoriteFoods ( favoritefood_id, fkfood_id ) </code></pre>
<p>It depends on what you are going to do with the data.</p> <p>If for some reason normalization is important to you, the following works quite well.</p> <pre><code>Fruits ( fruit_id, food_id references favoritefoods.food_id, fruitName) Vegetables( vegetable_id, food_id references favoritefoods.food_id, vegetableName) favoriteFoods ( food_id, foodName) </code></pre> <p>The favoriteFoods table doesn't need to "know" what type of food it is, if any. Each fruit and each vegetable is bound to the corresponding favorite food.</p> <p>If you want to select all the fruits from favoriteFoods, just join the fruits table and the favoriteFoods table. You could even include a tomato as both a vegetable and a fruit, if that suits your fancy. </p> <p>The above is predicated on the assumption that joins are cheap. In many situations, joins really are cheap. Check it out before you alter your design to avoid joins. </p>
33,003
<p>How do I correct for floating point error in the following physical simulation:</p> <ul> <li>Original point (x, y, z),</li> <li>Desired point (x', y', z') after forces are applied.</li> <li>Two triangles (A, B, C) and (B, C, D), who share edge BC</li> </ul> <p>I am using this method for collision detection:</p> <pre><code>For each Triangle If the original point is in front of the current triangle, and the desired point is behind the desired triangle: Calculate the intersection point of the ray (original-desired) and the plane (triangle's normal). If the intersection point is inside the triangle edges (!) Respond to the collision. End If End If Next Triangle </code></pre> <p>The problem I am having is that sometimes the point falls into the grey area of floating point math where it is so close to the line BC that it fails to collide with either triangle, even though technically it should always collide with one or the other since they share an edge. When this happens the point passes right between the two edge sharing triangles. I have marked one line of the code with <strong>(!)</strong> because I believe that's where I should be making a change.</p> <p>One idea that works in very limited situations is to skip the edge testing. Effectively turning the triangles into planes. This only works when my meshes are convex hulls, but I plan to create convex shapes.</p> <p>I am specifically using the dot product and triangle normals for all of my front-back testing.</p>
<p>This is an inevitable problem when shooting a single ray against some geometry with edges and vertices. It's amazing how physical simulations seem to seek out the smallest of numerical inaccuracies!</p> <p>Some of the explanations and solutions proposed by other respondents will not work. In particular:</p> <ul> <li><p>Numerical inaccuracy really can cause a ray to "fall through the gap". The problem is that we intersect the ray with the plane ABC (getting the point P, say) before testing against line BC. Then we intersect the ray with plane BCD (getting the point Q, say) before testing against line BC. P and Q are both represented by the closest floating-point approximation; there's no reason to expect that these exactly lie on the planes that they are supposed to lie on, and so every possibility that you can have both P to the left of BC and Q to the right of BC.</p></li> <li><p>Using less-than-or-equal test won't help; it's inaccuracy in the intersection of the ray and the plane that's the trouble. </p></li> <li><p>Square roots are not the issue; you can do all of the necessary computations using dot products and floating-point division.</p></li> </ul> <p>Here are some genuine solutions:</p> <ul> <li><p>For convex meshes, you can just test against all the planes and ignore the edges and vertices, as you say (thus avoiding the issue entirely).</p></li> <li><p>Don't intersect the ray with each triangle in turn. Instead, use the <a href="http://realtimecollisiondetection.net/blog/?p=69" rel="noreferrer">scalar triple product</a>. (This method makes the exact same sequence of computations for the ray and the edge BC when considering each triangle, ensuring that any numerical inaccuracy is at least consistent between the two triangles.)</p></li> <li><p>For non-convex meshes, give the edges and vertices some width. That is, place a small sphere at each vertex in the mesh, and place a thin cylinder along each edge of the mesh. Intersect the ray with these spheres and cylinders as well as with the triangles. These additional geometric figures stop the ray passing through edges and vertices of the mesh.</p></li> </ul> <p>Let me strongly recommend the book <a href="http://realtimecollisiondetection.net/" rel="noreferrer">Real-Time Collision Detection</a> by Christer Ericson. There's a discussion of this exact problem on pages 446–448, and an explanation of the scalar triple product approach to intersecting a ray with a triangle on pages 184–188.</p>
<p>@Statement: I am indeed already using a "greater than or equal to" comparison in my code, thank you for the suggestion. +1</p> <p>My current solution is to add a small nudge amount to the edge test. Basically when each triangle is tested, its edges are pushed out by a very small amount to counteract the error in floating point. Sort of like testing if the result of a floating point calculation is less than 0.01 rather than testing for equality with zero.</p> <p>Is this a reasonable solution?</p>
12,475
<p>Looking for a <code>Linux application</code> <em>(or Firefox extension)</em> that will allow me to scrape an HTML mockup and keep the page's integrity.</p> <p>Firefox does an almost perfect job but doesn't grab images referenced in the CSS.</p> <p>The Scrapbook extension for Firefox gets everything, but flattens the directory structure. </p> <p>I wouldn't terribly mind if all folders became children of the <code>index</code> page.</p>
<p>See <a href="http://www.devarticles.com/c/a/Web-Services/Website-Mirroring-With-wget/1/" rel="noreferrer">Website Mirroring With wget</a></p> <pre><code>wget --mirror –w 2 –p --HTML-extension –-convert-links http://www.yourdomain.com </code></pre>
<p><a href="http://www.tenmax.com/teleport/pro/home.htm" rel="nofollow noreferrer">Teleport Pro</a> is great for this sort of thing. You can point it at complete websites and it will download a copy locally maintaining directory structure, and replacing absolute links with relative ones as necessary. You can also specify whether you want content from other third-party websites linked to from the original site.</p>
10,503
<p>Here is new C# future in version 4.0 known as dynamic. Show me the way i can use it in my code and how this future can help me?</p> <hr> <p>Related questions:</p> <ul> <li><a href="https://stackoverflow.com/questions/298277/does-the-new-dynamic-c-40-keyword-deprecate-the-var-keyword">Does the new ‘dynamic’ C# 4.0 keyword deprecate the ‘var’ keyword ?</a></li> <li><a href="https://stackoverflow.com/questions/244302/what-do-you-think-of-the-new-c-40-dynamic-keyword">What do you think of the new C# 4.0 ‘dynamic’ keyword?</a></li> </ul>
<p>One of the usages is interop between static and dynamic languages.</p> <p>Say you want to invoke a JavaScript function fron silverlight:</p> <pre><code>HtmlPage.Window.Invoke("HelloWorldFunction"); </code></pre> <p>If the window was dynamic (and properly implemented) you would be able to use it like this:</p> <pre><code>HtmlPage.Window.HelloWorldFunction(); </code></pre>
<p>One of the usages is interop between static and dynamic languages.</p> <p>Say you want to invoke a JavaScript function fron silverlight:</p> <pre><code>HtmlPage.Window.Invoke("HelloWorldFunction"); </code></pre> <p>If the window was dynamic (and properly implemented) you would be able to use it like this:</p> <pre><code>HtmlPage.Window.HelloWorldFunction(); </code></pre>
38,680
<p>How do I convert a string into the corresponding code in PLT Scheme (which does not contain the <code>string-&gt;input-port</code> method)? For example, I want to convert this string:</p> <pre><code>"(1 (0) 1 (0) 0)" </code></pre> <p>into this list:</p> <pre><code>'(1 (0) 1 (0) 0) </code></pre> <p>Is it possible to do this without opening a file?</p>
<p>Scheme has procedure <code>read</code> for reading s-expressions from input port and you can convert a string to input stream with <code>string-&gt;input-port</code>. So, you can read a Scheme object from a string with</p> <pre><code>(read (string-&gt;input-port "(1 (0) 1 (0) 0)")) </code></pre> <p>I don't have Scheme installed, so I only read it <a href="http://groups.csail.mit.edu/mac/projects/scheme/documentation/scheme.html" rel="noreferrer">from reference</a> and didn't actually test it.</p>
<p>Many schemes have <code>with-input-from-string str thunk</code> that executes <code>thunk</code> in a context where <code>str</code> is the standard input port. For example in gambit scheme:</p> <p><code>(with-input-from-string "(foo bar)" (lambda () (read)))</code></p> <p>evaluates to:</p> <p><code>(foo bar)</code></p> <p>The lambda is necessary because a <code>thunk</code> should be a procedure taking no arguments.</p>
41,236
<p>For example to create a hierarchy of categories you use a column 'parent_id', which points to another category in the same table.</p> <p>Should this be a foreign key? What would the dis/advantages be?</p>
<p>Yes. Ensures that you don't have an orphan (entry with no parent), and depending on usage, if you define a cascading delete, when a parent is deleted, all its children will also be deleted.</p> <p>Disadvantage would be a slight performance hit just like any other foreign key.</p>
<p>Yes, you should make it a foreign key.</p> <p>The benefits will be a better data model with less redundancy.</p>
30,593
<p>If I want to inject a globally scoped array variable into a page's client-side javascript during a full page postback, I can use:</p> <pre><code>this.Page.ClientScript.RegisterArrayDeclaration("WorkCalendar", "\"" + date.ToShortDateString() + "\""); </code></pre> <p>to declare and populate a client-side javascript array on the page. Nice and simple. </p> <p>But I want to do the same from a async postback from an UpdatePanel. </p> <p>The closest I can figure so far is to create a .js file that just contains the var declaration, update the file during the async postback, and then use a <code>ScriptManagerProxy.Scripts.Add</code> to add the .js file to the page's global scope. </p> <p>Is there anything simpler? r iz doin it wrong?</p>
<p>Use the static method System.Web.UI.ScriptManager.AddStartupScript()</p> <p>The script will run on all full and partial postbacks.</p>
<p>You could also update a hidden label inside the update panel which allows you to write out any javascript you like. I would suggest though using web services or even page methods to fetch the data you need instead of using update panels.</p> <p>Example: myLabel.Text = "...."; ... put your logic in this or you can add [WebMethod] to any public static page method and return data directly.</p>
12,061
<p>If I had a Canvas with n number of Visual objects of any shape or size, how would I highlight/outline a Visual object programmatically? </p> <p>Is there something built into WPF to help me? </p>
<p>Having read the comments in the other answer -- in which you state that you wish the outline to conform to the shape of the visual -- I can only suggest you take a look at the <code>BitmapEffects</code>. There is one for an Outer Glow effect.</p> <p>Duplicating the visuals themselves would probably be less efficient, and would probably produce a great number of complications due to other aspects of those items, such as any bindings.</p> <p><strong>Edit:</strong> In .NET 4.0, <code>BitmapEffects</code> property and the <code>BitmapEffect</code> class are obsolete. You'll get an exception thrown. Instead, you now have the <code>System.Windows.Media.Effects.Effect</code> class and its derived classes, along with properties such as <code>Visual.VisualEffect</code>.</p>
<p>If you wrap those Visual objects in a Border ... and make the Opacity 0 by default ... then you could programmatically turn the Opacity to 1 whenever you need to.</p> <p>Does that help?</p>
22,902
<p>I need to take a paragraph of text and extract from it a list of "tags". Most of this is quite straight forward. However I need some help now stemming the resulting word list to avoid duplicates. Example: Community / Communities</p> <p>I've used an implementation of Porter Stemmer algorithm (I'm writing in PHP by the way):</p> <p><a href="http://tartarus.org/~martin/PorterStemmer/php.txt" rel="noreferrer">http://tartarus.org/~martin/PorterStemmer/php.txt</a></p> <p>This works, up to a point, but doesn't return "real" words. The example above is stemmed to "commun".</p> <p>I've tried "Snowball" (suggested within another Stack Overflow thread).</p> <p><a href="http://snowball.tartarus.org/demo.php" rel="noreferrer">http://snowball.tartarus.org/demo.php</a></p> <p>For my example (community / communities), Snowball stems to "communiti".</p> <p><strong>Question</strong></p> <p>Are there any other stemming algorithms that will do this? Has anyone else solved this problem?</p> <p><em>My current thinking is that I could use a stemming algorithm to avoid duplicates and then pick the shortest word I encounter to be the actual word to display.</em></p>
<p>If I understand correctly, then what you need is not a stemmer but a lemmatizer. Lemmatizer is a tool with knowledge about endings like <em>-ies</em>, <em>-ed</em>, etc., and exceptional wordforms like <em>written</em>, etc. Lemmatizer maps the input wordform to its lemma, which is guaranteed to be a "real" word.</p> <p>There are many lemmatizers for English, I've only used <code>morpha</code> though. <em>Morpha</em> is just a big lex-file which you can compile into an executable. Usage example:</p> <pre><code>$ cat test.txt Community Communities $ cat test.txt | ./morpha -uc Community Community </code></pre> <p>You can get morpha from <a href="http://www.informatics.sussex.ac.uk/research/groups/nlp/carroll/morph.html" rel="noreferrer">http://www.informatics.sussex.ac.uk/research/groups/nlp/carroll/morph.html</a></p>
<p>Hey I don't know if that's perhaps too late, but there is only one PHP stemming script that produces real words: <a href="http://phpmorphy.sourceforge.net/">http://phpmorphy.sourceforge.net/</a> – it took me ages to find it. All other stemmers have to be compiled and even after that they only work according to Porter algorithm, which produces stems, not lemmas (i.e. community = communiti). PhpMorphy one works perfectly well, it's easy to install and initialize, and has English, Russian, German, Ukrainian and Estonian dictionaries. It also comes with a script that you can use to compile other dictionaries. The documentation is in Russian, but put it through Google translate and it should be easy.</p>
23,158
<p>I am displaying a texture that I want to manipulate without out affecting the image data. I want to be able to clamp the texel values so that anything below the lower value becomes 0, anything above the upper value becomes 0, and anything between is linearly mapped from 0 to 1. </p> <p>Originally, to display my image I was using glDrawPixels. And to solve the problem above I would create a color map using glPixelMap. This worked beautifully. However, for performance reasons I have begun using textures to display my image. The glPixelMap approach no longer seems to work. Well that approach may work but I was unable to get it working. </p> <p>I then tried using glPixelTransfer to set scales and bias'. This seemed to have some sort of effect (not necessarily the desired) on first pass, but when the upper and lower constraints were changed no effect was visible. </p> <p>I was then told that fragment shaders would work. But after a call to glGetString(GL_EXTENSIONS), I found that GL_ARB_fragment_shader was not supported. Plus, a call to glCreateShaderObjectARB cause a nullreferenceexception.</p> <p>So now I am at a loss. What should I do? Please Help.</p> <hr> <p>What ever might work I am willing to try. The vendor is Intel and the renderer is Intel 945G. I am unfortunately confined to a graphics card that is integrated on the motherboard, and only has gl 1.4.</p> <p>Thanks for your response thus far.</p>
<p>Unless you have a pretty old graphics-card, it's surprising that you don't have fragment-shader support. I'd suggest you try double-checking using <a href="http://www.realtech-vr.com/glview/" rel="nofollow noreferrer">this</a>.</p> <p>Also, are you sure you want anything above the max value to be 0? Perhaps you meant 1? If you did mean 1 and not 0 then are quite long-winded ways to do what you're asking. </p> <p>The condensed answer is that you use multiple rendering-passes. First you render the image at normal intensity. Then you use subtractive blending (look up glBlendEquation) to subtract your minimum value. Then you use additive blending to multiply everything up by 1/(max-min) (which may need multiple passes).</p> <p>If you really want to do this, please post back the <code>GL_VENDOR</code> and <code>GL_RENDERER</code> for your graphics-card.</p> <p><strong>Edit:</strong> Hmm. Intel 945G don't have <code>ARB_fragment_shader</code>, but it does have <code>ARB_fragment_program</code> which will also do the trick.</p> <p>Your fragment-code should look something like this (but it's been a while since I wrote any so it's probably bugged)</p> <pre><code>!!ARBfp1.0 ATTRIB tex = fragment.texcoord[0] PARAM cbias = program.local[0] PARAM cscale = program.local[1] OUTPUT cout = result.color TEMP tmp TXP tmp, tex, texture[0], 2D SUB tmp, tmp, cbias MUL cout, tmp, cscale END </code></pre> <p>You load this into OpenGL like so:</p> <pre><code>GLuint prog; glEnable(GL_FRAGMENT_PROGRAM_ARB); glGenProgramsARB(1, &amp;prog); glBindProgramARB(GL_FRAGMENT_PROGRAM_ARB, prog); glProgramStringARB(GL_FRAGMENT_PROGRAM_ARB, GL_PROGRAM_FORMAT_ASCII_ARB, strlen(src), src); glDisable(GL_FRAGMENT_PROGRAM_ARB); </code></pre> <p>Then, before rendering your geometry, you do this:</p> <pre><code>glEnable(GL_FRAGMENT_PROGRAM_ARB); glBindProgramARB(GL_FRAGMENT_PROGRAM_ARB, prog); colour4f cbias = cmin; colour4f cscale = 1.0f / (cmax-cmin); glProgramLocalParameter4fARB(GL_FRAGMENT_PROGRAM_ARB, 0, cbias.r, cbias.g, cbias.b, cbias.a); glProgramLocalParameter4fARB(GL_FRAGMENT_PROGRAM_ARB, 1, cscale.r, cscale.g, cscale.b, cscale.a); //Draw your textured geometry glDisable(GL_FRAGMENT_PROGRAM_ARB); </code></pre>
<p>It's really unfortunate that you're using such an ancient version of OpenGL. Can you upgrade with your card?</p> <p>For a more modern OGL 2.x, this is exactly the kind of program that GLSL is for. Great documentation can be found here:</p> <p><a href="http://opengl.org/documentation/" rel="nofollow noreferrer">OpenGL Documentation</a></p> <p><a href="http://opengl.org/documentation/glsl/" rel="nofollow noreferrer">OpenGL Shading Langauge</a></p>
29,009
<p>How can I put up a "File Open" dialog from some VBA running in Excel? </p> <p>I'm using Excel 2003. </p>
<p>You want the <code>Application.GetOpenFilename</code> function. Copying from VBA Object Browser:</p> <blockquote> <p>Function GetOpenFilename([FileFilter], [FilterIndex], [Title], [ButtonText], [MultiSelect])<br> Member of Excel.Application</p> </blockquote>
<p>Add a reference to ComDLG32.OCX and then something like...</p> <pre><code>Sub PromptForFile() Dim d As New MSComDlg.CommonDialog d.Filter = "xls" d.Filename = "*.xls" d.ShowOpen Excel.Workbooks.Open d.Filename Set d = Nothing End Sub </code></pre>
27,295
<p>The title speaks for itself... I've tried to find another question like it but must have missed it if it exists. I'm looking for anything, from a core library replacing GAPI to a .net wrapper... It's for building a nice UI so no 3D needed...</p>
<p>The System.Drawing classes in .NET are a lot more powerful than people realize. The only thing missing (which is actually really important in 2D graphics) is the ability to read and write individual pixels. This is technically possible using the GetPixel and SetPixel methods on the Bitmap object, but these methods are unimaginably slow.</p> <p>Fortunately, there is a super-fast alternative that you can implement by calling LockBits on a bitmap and then accessing the bitmap's byte data directly. I've used this to good effect. In fact, I've spent the last week creating a fisheye lens effect entirely in .NET (no libraries or PInvoke calls at all).</p> <p>This JPEG is kind of crappy, but it shows what's possible using just .NET: </p> <p><a href="http://www.freeimagehosting.net/uploads/5fdd250b21.jpg" rel="nofollow noreferrer">alt text http://www.freeimagehosting.net/uploads/5fdd250b21.jpg</a></p>
<p>IMO I would suggest getting hold of the frame buffer somehow and drawing to it directly if possible or using D3DM or use the drawing services provided by the Native Platform (GDI) through APIs like DrawGradient() etc from coredll.dll and since you are on WM you might be able to leverage aygshell.dll to draw widgets. </p> <p>Here are some links... </p> <p>1)<a href="http://msdn.microsoft.com/en-us/library/ms229655.aspx" rel="nofollow noreferrer">Using gradient fill from dot net</a><br> 2)<a href="http://msdn.microsoft.com/en-us/library/aa925212.aspx" rel="nofollow noreferrer">Using gradient fill directly</a><br> 3)<a href="http://msdn.microsoft.com/en-us/library/aa923590.aspx" rel="nofollow noreferrer">Other native GDI functions</a></p>
45,230
<pre><code>&lt;form id="frm_1" name="frm_1" target="_self" method="GET" action="local_page.php" &gt; &lt;/form&gt; &lt;form id="tgt_1" name="tgt_1" target="_blank" method="POST" action="http://stackoverflow.com/" &gt; &lt;/form&gt; &lt;a onclick="test(event, '1'); " href="#" &gt;Click Here&lt;/a&gt; &lt;script&gt; function test(event, id){ document.getElementById("frm_"+id).submit; document.getElementById("tgt_"+id).submit; } &lt;/script&gt; </code></pre> <p>Is it possible to open a new tab/window and change the current page ?</p>
<pre><code>&lt;form id="frm_1" name="frm_1" target="_self" method="POST" action="local_page.php" &gt; &lt;input type="hidden" name="vital_param" value="&lt;?= $something ?&gt;"&gt; &lt;/form&gt; &lt;form id="tgt_1" name="tgt_1" target="_blank" method="POST" action="http://stackoverflow.com/" &gt; &lt;/form&gt; &lt;button type="submit" onclick="test(event, '1'); " &gt;Click Here&lt;/button&gt; &lt;script&gt; function test(event, id){ window.open( document.getElementById("tgt_"+id).action, "_blank"); setTimeout('document.getElementById("frm_'+id+'").submit();', 1000); return true; } &lt;/script&gt; </code></pre> <p>tgt kept as source of target url, could be array or attribute. Without setyTimeout() browser stays on current page (FF/IE).</p>
<p>You should use the window.open to open the new page and then submit the tabchange e.g.</p> <pre><code>&lt;form id="frm_1" name="frm_1" target="_self" method="GET" action="local_page.php" &gt; &lt;/form&gt; &lt;a onclick="test(event, '1'); " href="#" &gt;Click Here&lt;/a&gt; &lt;script&gt; function test(event, id){ window.open("http://stackoverflow.com/", "_blank"); document.getElementById("tgt_"+id).submit(); } &lt;/script&gt; </code></pre>
33,692
<p>I need to communicate with an XML-RPC server from a .NET 2.0 client. Can you recommend any libraries?</p> <p>EDIT: Having tried XML-RPC.Net, I like the way it generates dynamic proxies, it is very neat. Unfortunately, as always, things are not so simple. I am accessing an XML-RPC service which uses the unorthodox technique of having object names in the names of the methods, like so:</p> <pre><code>object1.object2.someMethod(string1) </code></pre> <p>This means I can't use the attributes to set the names of my methods, as they are not known until run-time. If you start trying to get closer to the raw calls, XML-RPC.Net starts to get pretty messy.</p> <p>So, anyone know of a simple and straightforward XML-RPC library that'll just let me do (pseudocode):</p> <pre><code>x = new xmlrpc(host, port) x.makeCall("methodName", "arg1"); </code></pre> <p>I had a look at a thing by Michael somebody on Codeproject, but there are no unit tests and the code looks pretty dire.</p> <p>Unless someone has a better idea looks like I am going to have to start an open source project myself!</p>
<p>If the method name is all that is changing (i.e., the method signature is static) XML-RPC.NET can handle this for you. This is addressed <a href="http://xml-rpc.net/faq/xmlrpcnetfaq.html#2.23" rel="nofollow noreferrer">in the FAQ</a>, noting "However, there are some XML-RPC APIs which require the method name to be generated dynamically at runtime..." From the FAQ:</p> <pre><code>ISumAndDiff proxy = (ISumAndDiff)XmlRpcProxyGen.Create(typeof(ISumAndDiff)); proxy.XmlRpcMethod = "Id1234_SumAndDifference" proxy.SumAndDifference(3, 4); </code></pre> <p>This generates an XmlRpcProxy which implementes the specified interface. Setting the XmlRpcMethod attribute causes methodCalls to use the new method name.</p>
<p>I had also tried to run <a href="http://www.xml-rpc.net/" rel="nofollow noreferrer">www.xml-rpc.net </a> with <a href="http://www.mono-project.com/Main_Page" rel="nofollow noreferrer">Mono </a> on Windows XP and it worked in Mono .NET Runtime also properly. Just for information for everybody. </p>
12,657
<p>I have been asking myself this question for a long time now. Thought of posting it. C# doesn't support Multiple Inheritance(this is the fact). All classes created in C# derive out of 'Object' class(again a fact).</p> <p>So if C# does not support Multiple inheritance, then how are we able to extend a class even though it already extends Object class?</p> <p>Illustating with an example: </p> <ol> <li>class A : object - Class A created.</li> <li>class B : object - Class B created.</li> <li>class A : B - this again is supported. What happens to the earlier association to object.</li> </ol> <p>We are able to use object class methods in A after step 3. So is the turned to multi level inheritance. If that is the case, then</p> <ol> <li>class A : B</li> <li>class C : B</li> <li>class A : C - I must be able to access class B's methods in A. Which is not the case?</li> </ol> <p>Can anyone please explain?</p>
<p>Joel's answer is correct. There is a difference between multiple inheritance and an inhertance tree (or derivation chain). In your example, you actually show an inhertance tree: One object inherits (derives) from another object higher in the tree. Multiple inheritance allows one object to inherit from multiple base classes.</p> <p>Take, for example, the following tree:</p> <pre><code>public class BaseClass { } public class SpecialBaseClass : BaseClass {} public class SpecialtyDerivedClass : SpecialBaseClass {} </code></pre> <p>This is perfectly valid and says that SpecialtyDerivedClass inherits from SpecialBaseClass (SpecialtyDerivedClass' parent) which, in turn, derives from BaseClass (SpecialtyDerivedClass' grandparent).</p> <p>Under the idea of multiple inheritance, the example would look like this:</p> <pre><code>public class BaseClass { } public class SpecialBaseClass {} public class SpecialtyDerivedClass : BaseClass, SpecialBaseClass {} </code></pre> <p>This is not allowed in .NET, but it says that SpecialityDerivedClass inherits from both BaseClass and SpecialBaseClass (which are both parents).</p> <p>.NET does allow a form of multiple inheritance by allowing you to inherit from more than one interface. Changing the example above slightly:</p> <pre><code>public class BaseClass { } public interface ISpecialBase {} public interface ISpecialDerived {} public class SpecialtyDerivedClass : BaseClass, ISpecialBase, ISpecialDerived {} </code></pre> <p>This says that SpecialtyDerivedClass inherits from BaseClass (it's parent) and also ISpecialBase and ISpecialDerived (also parent's but more like step-parents as interfaces can't specify functionality).</p>
<p>Given below.</p> <pre><code>public class A : B { } public class B : C { public int BProperty { get; set; } } public class C { public int CProperty { get; set; } } public class Test { public void TestStuff() { A a = new A(); // These are valid. a.CProperty = 1; a.BProperty = 2; } } </code></pre> <p>This is valid. Object is a base for C in this case.</p>
23,246
<p>What are the benefits of having a member variable declared as read only? Is it just protecting against someone changing its value during the lifecycle of the class or does using this keyword result in any speed or efficiency improvements?</p>
<p>The <code>readonly</code> keyword is used to declare a member variable a constant, but allows the value to be calculated at runtime. This differs from a constant declared with the <code>const</code> modifier, which must have its value set at compile time. Using <code>readonly</code> you can set the value of the field either in the declaration, or in the constructor of the object that the field is a member of.</p> <p>Also use it if you don't want to have to recompile external DLLs that reference the constant (since it gets replaced at compile time).</p>
<p>There can be a performance benefit in WPF, as it removes the need for expensive DependencyProperties. This can be especially useful with collections</p>
34,946
<p>I was using jQuery plugins to create a rounded corner for my <code>&lt;li&gt;</code>, but it was not working on a lot of browsers and didn't support mouse over.</p> <p>I am wondering what is the best way to use two images (left corner and right corner) as the left and right side with using <code>&lt;li&gt;</code>.</p>
<p>The construct that I have seen used most for that is a span inside a link. </p> <p>so something like: </p> <pre><code>&lt;li&gt;&lt;a&gt;&lt;span&gt;Your text here&lt;/span&gt;&lt;/a&gt;&lt;/li&gt; </code></pre> <p>you can then target the span and the link using the hover state of the link: </p> <pre><code>a:hover{some rules here} a:hover span{some more rules here} </code></pre> <p>that keeps it kinda semantic, and doesn't add to much junk to the page.</p>
<p>You could put Divs inside your li's like so:</p> <pre><code>&lt;li&gt; &lt;div class="lefcorner"&gt;&lt;/div&gt; &lt;div class='liContent'&gt;Foo&lt;/div&gt; &lt;div class='rightcorner'&gt;&lt;/div&gt; &lt;/li&gt; </code></pre> <p>That way you will both keep your semantics and will also have the cross-browser support of styling DIVs.</p>
41,202
<p>We're planning a browser application (xbap) which is going to talk to WCF services. These WCF services get information from a SQL database. Each of our clients has his own database on this server. The clients need to get reports from SQL Reporting Services. A client can have multiple instances of this application running.</p> <p>How does this work with licensing? We thought of starting off with 1 server which has MSSQL and IIS running on windows server (although I might be smart separating these from the start). So that would be 1 license for Server 2008 and 1 for SQL2008? With an addition for each user? Then, is every client a user or every employee of our clients? Is this the same for the reporting services or is this a part of SQL2008? I'm confused...</p> <p><strong>Additional:</strong> I've heard from this company that got billed for about $100.000 because they were using reporting services with the wrong license. Their web application was described as a normal application because they used reporting services. We're trying to prevent that.</p>
<p>With the full SQL Server 2008 products (Enterprise, Standard, Workgroup and Web Server), licensing you get a bunch of choices:</p> <ul> <li>There is a Webserver version that basically takes care of using SQL server within a web application.</li> <li>Client Access Licenses (CALs) basically are not interesting if you get more than 25 users.</li> <li>Per-CPU license is the most expensive but allows the most flexibility.</li> </ul> <p>You need to be careful though: strictly speaking, for a web site, if you don't go with the special Web Server edition or a CPU license you must consider that each web client (web user out there) would need their own CAL.<br> If you just buy the cheapest 5 CAL version of SQL Server Standard (or Workgroup), you would not be compliant.</p> <p>Compliance is not enforced by software on SQL Server: it's up to you to make sure you have enough licenss to cover your needs in case of control.</p> <p>Depending on the functionalities you need, you'll have to get one of the <a href="http://www.microsoft.com/sqlserver/2008/en/us/editions.aspx" rel="noreferrer">available versions</a>:</p> <ul> <li>Enterprise - all the bells and whistles, very costly, unlimited CPU/RAM.</li> <li>Standard - very complete. 4 CPU/ No RAM limitation. Much cheaper than Enterprise edition but still fairly pricey.</li> <li>Workgroup - limited to 2 CPU, no RAM limitation. A bit cheaper than Standard.</li> <li>Express - free but limited to 1GB RAM, 1 CPU and a 4GB database.</li> </ul> <p>Not all <a href="http://msdn.microsoft.com/en-gb/library/cc645993.aspx" rel="noreferrer">functionalities are available for all versions</a>, but usually, if your initial needs are modest to start with, just download the free <em>Express Edition</em>, then move up to suit your actual needs.</p> <p>Sample prices and some licensing explanations are <a href="http://www.microsoft.com/sqlserver/2008/en/us/pricing.aspx" rel="noreferrer">available on the Microsoft SQL Server 2008 website</a>.</p>
<p>Per cpu licensing is probably your best best. But to answer your question, you can usually purchase "per device" or "per user" CALS for their software. This is just like it sounds. If you have one computer that will be accessing SQL Server with multiple users on that one comnputer, then "per device" CALS make sense. If however, generally you're going to have one user per computer, then it makes sense to purchase "per user" CALS.</p> <p>A per CPU license for SQL Server Std isn't really that expensive. We paid roughly $3000 for that license.</p>
47,685
<p>I am using running a simple find all and paginating with willpaginate, but I'd also like to have the query sorted by the user. The first solution that came to mind was just use a params[:sort]</p> <pre><code>http://localhost:3000/posts/?sort=created_at+DESC @posts = Post.paginate :page =&gt; params[:page], :order =&gt; params[:sort] </code></pre> <p>But the problem with his approach is that the query is defaulting as sorting by ID and I want it to be created_at. </p> <p>Is this a safe approach to sorting and is there a way to default to created_at?</p>
<p>I’d use a named scope for providing the default order (available since Rails 2.1).</p> <p>You’d add the scope in your Post model:</p> <pre><code>named_scope :ordered, lambda {|*args| {:order =&gt; (args.first || 'created_at DESC')} } </code></pre> <p>Then you can call:</p> <pre><code>@posts = Post.ordered.paginate :page =&gt; params[:page] </code></pre> <p>The example above will use the default order from the <code>named_scope</code> (<code>created_at DESC</code>), but you can also provide a different one:</p> <pre><code>@posts = Post.ordered('title ASC').paginate :page =&gt; params[:page] </code></pre> <p>You could use that with Romulo’s suggestion:</p> <pre><code>sort_params = { "by_date" =&gt; "created_at", "by_name" =&gt; "name" } @posts = Post.ordered(sort_params[params[:sort]]).paginate :page =&gt; params[:page] </code></pre> <p>If <code>params[:sort]</code> isn’t found in <code>sort_params</code> and returns <code>nil</code> then <code>named_scope</code> will fall back to using the default order.</p> <p><a href="http://railscasts.com/episodes/108-named-scope" rel="noreferrer">Railscasts</a> has some great info on named_scopes.</p>
<p>I prefer this idiom:</p> <pre><code>@posts = Post.paginate :page=&gt;page, :order=&gt;order ... def page params[:page] || 1 end def order params[:order] || 'created_at ASC' end </code></pre>
26,436
<p>I have a .NET 2.0 Windows Forms application. On this app there is a Form control with a Menu bar and a status bar. Also there's a ListView on this form.</p> <p>If I add a context menu to this form, the context menu will open when the user right clicks any part of the form, including the menu bar and the status bar. </p> <ol> <li><p>How can I prevent the context menu from opening when the click happened on the menu bar / status bar? I want it to open only when clicking the "gray area" of the form.</p></li> <li><p>If the click happened above a control on this form (for example, on the ListView), how can I identify this? I'd like to know if the user right clicked above the gray area or above the ListView, so I can enable/disable some menu items based on this.</p></li> </ol>
<p>After you've placed your Statusbar at the bottom and MenuStrip at the top, </p> <ol> <li>Set ContextMenuStrip on your form to <em>None</em> </li> <li>Place a standard Panel in the middle (between MenuStrip and StatusStrip) with the <em>Dock</em> property set to <em>Fill</em>. </li> <li>Set the ContextMenuStrip property on your <em>Panel</em> (instead of on the form).</li> </ol> <p>And place the ListView and all other controls that should go into the form in the <em>Panel</em></p> <p>Eg</p> <p>~~~~~~~~~~~~~</p> <p>menustrip</p> <p>~~~~~~~~~~~~~</p> <p>Panel. Dock=Fill. ContextMenuStrip=yourContextMenu.</p> <p>~~~~~~~~~~~~~</p> <p>StatusStrip</p> <p>~~~~~~~~~~~~~</p>
<p>I found the answer:</p> <pre><code>Point clientPos = this.PointToClient(Form.MousePosition); Control control = this.GetChildAtPoint(clientPos); </code></pre> <p>This should give the underlying control that was clicked on the Form, or null if the click was on the gray area. So we just need to test for the type of the control on the Opening event of the context menu. If it's MenuStrip, ToolStrip or StatusStrip, do e.Cancel = true;.</p>
13,453
<p>I am researching the feasibility of setting up a mapping tool for my alliance in an online game. The game is not based in the real world so I am not interested in the content of the map tools available, just the functionality. </p> <p>Minimally, I would like the map to display information about where allied cities are located in the world. Ideally, I'd like to be able to display information about desired trades, levels of development, and military actions. All this should be editable by the map users.</p> <p>I've been looking at the google maps API and it appears that I could use it to serve my ends by using my own map tiles with a custom defined map object and some custom overlays, but it looks like it would be a lot of work to set up. </p> <p>Is there another tool that would be better suited to this task?</p>
<p>A List Apart has an <a href="http://www.alistapart.com/articles/takecontrolofyourmaps" rel="nofollow noreferrer">article from the creators of EveryBlock.com</a>. They use a full open-source stack (client side library, tile cache, map generator) as an alternative to Google Maps. That sounds like it has exactly what you need.</p>
<p>Wouldn't defining your own overlay with a KMZ file in Google Maps work?</p>
23,680
<p>I have values stored as strings in a <code>DataTable</code> where each value could really represent an <code>int</code>, <code>double</code>, or <code>string</code> (they were all converted to strings during an import process from an external data source). I need to test and see what type each value really is.</p> <p>What is more efficient for the application (or is there no practical difference)?</p> <ol> <li>Try to convert to <code>int</code> (and then <code>double</code>). If conversion works, the return <code>true</code>. If an exception is thrown, return <code>false</code>.</li> <li>Regular expressions designed to match the pattern of an <code>int</code> or <code>double</code></li> <li>Some other method?</li> </ol>
<p>Would use double.TryParse, it has performance benefits.</p>
<p>I'd personally use int.tryparse, then double.tryparse. Performance on those methods is quite fast. They both return a Boolean. If both fail then you have a string, per how you defined your data.</p>
2,422
<p>Here are my thoughts: The purpose of using MVC is seperation of concerns and testability of gui logic. View should be able to work with different models and model should be able to work with different views. <p>I think controller class must implement an interface for mocking/testing reasons and view should call controller methods through this interface. But if we do so, then it becomes difficult to process view elements (textboxes, grids etc.) in controller. So these elements must be known by the controller somehow. <p>1. Do you expose these gui elements through the interface? Define controller classes as partial classes so that controller can directly process the gui elements (what about the interface then)? What do you do to solve this problem? <p>2. Basically, should controller implement more than one interface? One for view and another for model layer, to make view/model be able to work with different models/views via controllers? <p>3. Model layer also should implement an interface for mocking/testing?</p> <p>How can we achieve our testing, loosely coupling, SoC purposes best? Please share your experience/thoughts. </p>
<h2>My "short" answer:</h2> <hr> <p>You may have noticed this already, but just in case:</p> <p>First of all, even when you see that error, (assuming that you click past it and continue), then you should <strong>still be able to use 99% of the debugging features</strong> in Xcode. In other words, that error means that only a very small, specific portion of the debugger is "broken" for a given debugging session. It does <strong><em>not</em></strong> mean that debugging is completely down and/or impossible for the given program-execution.</p> <p>Given the above fact, if you simply want to get rid of the error and do not care whether Custom Data Formatters are working or not, then REMOVE the check-mark next to the following menu item:</p> <ul> <li>Run -> Variables View -> Enable Data Formatters</li> </ul> <h2>My "long" answer:</h2> <hr> <p>The developers in my office had been experiencing this very same Xcode error for quite a while until someone discovered that some third party libraries were the cause.</p> <p>In our case, this error was happening only for projects using wxWidgets. I am not meaning to imply that usage of wxWidgets is the only possible cause. I am only trying to put forth more information that might lead to the right solution for your case. </p> <p>Also of interest: we (in my office) were getting this error without any use or presence of any .gdbinit file whatsoever.</p> <p>It turns out that the "property" of wxWidgets that made it trigger this error was related to a "custom/generic" implementation of "dlopen." Prior to Mac OS X 10.3, dlopen was not provided within the operating system, so apparently some libraries coded their own versions. When such libraries are being used, then apparently the dlopen call that tries to open PBGDBIntrospectionSupport.A.dylib can fail.</p> <p><a href="http://sourceforge.net/tracker/index.php?func=detail&amp;aid=1896410&amp;group_id=9863&amp;atid=309863" rel="nofollow noreferrer">Read through the comments on this sourceforge patch submission to learn even further details about dlopen in 10.3 and beyond.</a></p> <p>Also, here is another related link:</p> <p><a href="http://lists.apple.com/archives/Xcode-users/2008/Mar/msg00240.html" rel="nofollow noreferrer">Message on the Xcode users mailing list about PBGDBIntrospectionSupport and Custom Data Formatters</a></p>
<p>Strange... Looking around my Mac, I see that library just fine, and it looks sane.</p> <p>Have you tried using dtrace to see what Xcode and GDB are trying to do when the error happens?</p>
17,570
<p>Is there a complete list of Google Gears enabled sites? I'm aware of rememberthemilk.com, google docs and google calendar</p>
<p>MySpace's message system is one of the <em>biggest</em> outside of Google. At least so I thought according to <a href="http://www.techcrunch.com/2008/05/28/myspace-shows-facebook-how-its-done-google-gears-to-power-messaging/" rel="noreferrer">this article</a>.</p> <p>Other sites are:</p> <ul> <li><a href="http://wordpress.com" rel="noreferrer">Wordpress</a></li> <li><a href="http://www.mindmeister.com/services/tools/offline" rel="noreferrer">MindMeister</a></li> <li><a href="http://www.passpack.com/" rel="noreferrer">PassPack</a></li> <li><a href="http://writer.zoho.com/" rel="noreferrer">ZohoWriter</a></li> <li><a href="http://buxfer.com/" rel="noreferrer">BuxFer</a></li> <li><a href="http://thn.gs/" rel="noreferrer">SomeThings</a></li> </ul>
<p><a href="http://rememberthemilk.com" rel="nofollow noreferrer">Remember The Milk</a></p>
24,684