input
stringlengths
51
42.3k
output
stringlengths
18
55k
Wildcard Subdomain Exceptions <p>I have a wildcard subdomain enabled and dynamically parse the URL by passing it as-is to my <code>index.php</code> (ex. <code>somecity.domain.com</code>). </p> <p>Now, I wish to create a few subdomains that are static where I can install different application and not co-mingle with my current one (ex. <code>blog.domain.com</code>).</p> <p>My <code>.htaccess</code> currently reads:</p> <pre><code>RewriteEngine On RewriteBase / RewriteCond %{REQUEST_FILENAME} !-f RewriteCond %{REQUEST_FILENAME} !-d RewriteRule . /index.php [L] </code></pre> <p>Can I manipulate this <code>.htaccess</code> to achieve what I need? Can it be done through Apache?</p>
<p>Your .htaccess does nothing useful, as Apache is probably configured with DirectoryIndex index.php. Well, it does move domain.com/a to domain.com/index.php, but I doubt that is what you want.</p> <p>Your wildcard virtualhost works because you probably have ServerAlias *.domain.com in your configuration, or a single virtualhost and DNS pointing to the address of your server. (When you have a single virtualhost, it shows up for any request, and the first listed virtualhost is the default one)</p> <p>You have to create new VirtualHosts for the static domains, leaving the default one as, well, the default one :)</p> <p>Check <a href="http://httpd.apache.org/docs/2.2/vhosts/examples.html" rel="nofollow">these</a> <a href="http://wiki.apache.org/httpd/ExampleVhosts" rel="nofollow">tutorials</a> that explain it all.</p>
ColdFusion: Is it safe to leave out the variables keyword in a CFC? <p>In a ColdFusion Component (CFC), is it necessary to use fully qualified names for variables-scoped variables?</p> <p>Am I going to get myself into trouble if I change this:</p> <pre><code>&lt;cfcomponent&gt; &lt;cfset variables.foo = "a private instance variable"&gt; &lt;cffunction name = "doSomething"&gt; &lt;cfset var bar = "a function local variable"&gt; &lt;cfreturn "I have #variables.foo# and #bar#."&gt; &lt;/cffunction&gt; &lt;/cfcomponent&gt; </code></pre> <p>to this?</p> <pre><code>&lt;cfcomponent&gt; &lt;cfset foo = "a private instance variable"&gt; &lt;cffunction name = "doSomething"&gt; &lt;cfset var bar = "a function local variable"&gt; &lt;cfreturn "I have #foo# and #bar#."&gt; &lt;/cffunction&gt; &lt;/cfcomponent&gt; </code></pre>
<p>It won't matter to specify "variables" when you create the variable, because foo will be placed in the variables scope by default; but it will matter when you access the variable.</p> <pre><code>&lt;cfcomponent&gt; &lt;cfset foo = "a private instance variable"&gt; &lt;cffunction name="doSomething"&gt; &lt;cfargument name="foo" required="yes"/&gt; &lt;cfset var bar = "a function local variable"&gt; &lt;cfreturn "I have #foo# and #bar#."&gt; &lt;/cffunction&gt; &lt;cffunction name="doAnotherThing"&gt; &lt;cfargument name="foo" required="yes"/&gt; &lt;cfset var bar = "a function local variable"&gt; &lt;cfreturn "I have #variables.foo# and #bar#."&gt; &lt;/cffunction&gt; &lt;/cfcomponent&gt; </code></pre> <p>doSomething("args") returns "I have <strong>args</strong> and a <strong>function local variable</strong>"</p> <p>doAnotherThing("args") returns "I have <strong>a private instance of a variable</strong> and a <strong>function local variable</strong>."</p>
Most effective form of CAPTCHA? <p>Of all the forms of CAPTCHA available, which one is the "least crackable" while remaining fairly human readable?</p>
<blockquote> <p>I believe that CAPTCHA is dying. If someone really wants to break it, it will be broken. I read (somewhere, don't remember where) about a site that gave you free porn in exchange for answering CAPTCHAs to they can be rendered obsolete by bots. So, why bother?</p> </blockquote> <p>Anyone who really wants to break this padlock can use a pair of bolt cutters, so why bother with the lock?<br /> Anyone who really wants to steal this car can drive up with a tow truck, so why bother locking my car?<br /> Anyone who really wants to open this safe can cut it open with an oxyacetylene torch, so why bother putting things in the safe?</p> <p>Because using the padlock, locking your car, putting valuables in a safe, and using a CAPTCHA weeds out a large spectrum of relatively unsophisticated or unmotivated attackers. The fact that it doesn't stop sophisticated, highly motivated attackers doesn't mean that it doesn't work at all. Using a CAPTCHA isn't going to stop all spammers, but it's going to tremendously reduce the amount that requires filtering or manual intervention. </p> <p>Heck look at the lame CAPTCHA that Jeff uses on <a href="http://www.codinghorror.com/blog/">his blog</a>. Even a wimpy barrier like that still provides a lot of protection.</p>
lock keyword in C# <p>I understand the main function of the lock key word from MSDN</p> <blockquote> <p>lock Statement (C# Reference)</p> <p>The lock keyword marks a statement block as a critical section by obtaining the mutual-exclusion lock for a given object, executing a statement, and then releasing the lock.</p> </blockquote> <p>When should the lock be used? </p> <p>For instance it makes sense with multi-threaded applications because it protects the data. But is it necessary when the application does not spin off any other threads?</p> <p>Is there performance issues with using lock?</p> <p>I have just inherited an application that is using lock everywhere, and it is single threaded and I want to know should I leave them in, are they even necessary?</p> <p>Please note this is more of a general knowledge question, the application speed is fine, I want to know if that is a good design pattern to follow in the future or should this be avoided unless absolutely needed.</p>
<blockquote> <p>When should the lock be used?</p> </blockquote> <p>A lock should be used to protect shared resources in multithreaded code. Not for anything else.</p> <blockquote> <p>But is it necessary when the application does not spin off any other threads?</p> </blockquote> <p>Absolutely not. It's just a time waster. However do be sure that you're not implicitly using system threads. For example if you use asynchronous I/O you may receive callbacks from a random thread, not your original thread.</p> <blockquote> <p>Is there performance issues with using lock?</p> </blockquote> <p>Yes. They're not very big in a single-threaded application, but why make calls you don't need?</p> <blockquote> <p>...if that is a good design pattern to follow in the future[?]</p> </blockquote> <p>Locking everything willy-nilly is a terrible design pattern. If your code is cluttered with random locking and then you do decide to use a background thread for some work, you're likely to run into deadlocks. Sharing a resource between multiple threads requires careful design, and the more you can isolate the tricky part, the better.</p>
How to get rid of `deprecated conversion from string constant to ‘char*’` warnings in GCC? <p>So I'm working on an exceedingly large codebase, and recently upgraded to gcc 4.3, which now triggers this warning:</p> <blockquote> <p>warning: deprecated conversion from string constant to ‘char*’</p> </blockquote> <p>Obviously, the correct way to fix this is to find every declaration like</p> <pre><code>char *s = "constant string"; </code></pre> <p>or function call like:</p> <pre><code>void foo(char *s); foo("constant string"); </code></pre> <p>and make them <code>const char</code> pointers. However, that would mean touching 564 files, minimum, which is not a task I wish to perform at this point in time. The problem right now is that I'm running with <code>-werror</code>, so I need some way to stifle these warnings. How can I do that?</p>
<p>Any functions into which you pass string literals <code>"I am a string literal"</code> should use <code>char const *</code> as the type instead of <code>char*</code>.</p> <p>If you're going to fix something, fix it right.</p>
In a LotusScript Agent how do you get the name of the current server? <p>In a LotusScript Agent that is being run via WebQueryOpen, how do you get the name of the current server?</p>
<pre><code>Set s = New NotesSession Set db = s.CurrentDatabase If db.Server &lt;&gt; "" Then Set sName = New NotesName(db.Server) Else Set sName = New NotesName(s.Username) End If </code></pre>
Best way to transfer an xml to SQL Server? <p>I have been hearing the podcast blog for a while, I hope I dont break this. The question is this: I have to insert an xml to a database. This will be for already defined tables and fields. So what is the best way to accomplish this? So far I am leaning toward programatic. I have been seeing varios options, one is Data Transfer Objects (DTO), in the SQL Server there is the sp_xml_preparedocument that is used to get transfer XMLs to an object and throught code. </p> <p>I am using CSharp and SQL Server 2005. The fields are not XML fields, they are the usual SQL datatypes. </p>
<p>In an attempt to try and help, we may need some clarification. Maybe by restating the problem you can let us know if this is what you're asking:</p> <p><strong>How can one import existing xml into a SQL 2005 database, without relying on the built-in xml type?</strong></p> <p>A fairly straight forward solution that you already mentioned is the <em>sp_xml_preparedocument</em>, combined with <em>openxml</em>. </p> <p>Hopefully the following example illustrates the correct usage. For a more complete example checkout the MSDN docs on <a href="http://msdn.microsoft.com/en-us/library/ms187897(SQL.90).aspx" rel="nofollow">Using OPENXML</a>.</p> <pre><code>declare @XmlDocumentHandle int declare @XmlDocument nvarchar(1000) set @XmlDocument = N'&lt;ROOT&gt; &lt;Customer&gt; &lt;FirstName&gt;Will&lt;/FirstName&gt; &lt;LastName&gt;Smith&lt;/LastName&gt; &lt;/Customer&gt; &lt;/ROOT&gt;' -- Create temp table to insert data into create table #Customer ( FirstName varchar(20), LastName varchar(20) ) -- Create an internal representation of the XML document. exec sp_xml_preparedocument @XmlDocumentHandle output, @XmlDocument -- Insert using openxml allows us to read the structure insert into #Customer select FirstName = XmlFirstName, LastName = XmlLastName from openxml ( @XmlDocumentHandle, '/ROOT/Customer',2 ) with ( XmlFirstName varchar(20) 'FirstName', XmlLastName varchar(20) 'LastName' ) where ( XmlFirstName = 'Will' and XmlLastName = 'Smith' ) -- Cleanup xml document exec sp_xml_removedocument @XmlDocumentHandle -- Show the data select * from #Customer -- Drop tmp table drop table #Customer </code></pre> <p>If you have an xml file and are using C#, then defining a stored procedure that does something like the above and then passing the entire xml file contents to the stored procedure as a <em>string</em> should give you a fairly straight forward way of importing xml into your existing table(s).</p>
bug in linq Contains statement - is there a fix or workaround? <p>I found a bug in the Contains statement in Linq (not sure if it is really in Linq or Linq to SQL) and want to know if anyone else has seen this and if there is a fix or workaround.</p> <p>If the querysource you do the contains with has more than 10 items in it, it does not pass the items correctly to the SQL query. It is hard to explain what it does, an example will show it best.</p> <p>If you look at the raw query, the parameters look like this:</p> <pre><code>@P0 = 'aaa' @P1 = 'bbb' @P2 = 'ccc' ... [@P3 through @P9] @P10 = '111' @P11 = '222' ... [@p12 through @P19] @P20 = 'sss' ... [@P21 through @P99] @P100 = 'qqq' </code></pre> <p>when the values are passed into the final query (all parameters resolved) it has resolved the parameters as if these were the values passed:</p> <pre><code>@P0 = 'aaa' @P1 = 'bbb' @P2 = 'ccc' ... @P10 = 'bbb'0 @P11 = 'bbb'1 ... @P20 = 'ccc'0 ... @P100 = 'bbb'00 </code></pre> <p>So it looks like the parameter resolving looks at the first digit only after the <code>@P</code> and resolves that, then adds on anything left at the end of the parameter name.</p> <p>At least that is what the Sql Server Query Visualizer plugin to Visual Studio shows the query doing.</p> <p>Really strange.</p> <p>So if any one has advice please share. Thanks!</p> <p><strong>Update:</strong><br> I have rewritten the original linq statement to where I now use a join instead of the Contains, but would still like to know if there is a way around this issue.</p>
<p>The more I look at it, and after running more tests, I'm thinking the bug may be in the Sql Server Query Visualizer plugin for Visual Studio, not actually in Linq to SQL itself. So it is not nearly as bad a situation as I thought - the query will return the right results, but you can't trust what the Visualizer is showing. Not great, but better than what I thought was going on.</p>
How do I create a spring bean for a Java double primitive? <p>I'd like to create a spring bean that holds the value of a double. Something like:</p> <pre><code>&lt;bean id="doubleValue" value="3.7"/&gt; </code></pre>
<p>Declare it like this</p> <pre><code>&lt;bean id="doubleValue" class="java.lang.Double"&gt; &lt;constructor-arg index="0" value="3.7"/&gt; &lt;/bean&gt; </code></pre> <p>And use like this</p> <pre><code>&lt;bean id="someOtherBean" ...&gt; &lt;property name="value" ref="doubleValue"/&gt; &lt;/bean&gt; </code></pre>
Are Stored Procedures more efficient, in general, than inline statements on modern RDBMS's? <p>Conventional wisdom states that stored procedures are always faster. So, since they're always faster, use them <strong>ALL THE TIME</strong>.</p> <p>I am pretty sure this is grounded in some historical context where this was once the case. Now, I'm not advocating that Stored Procs are not needed, but I want to know in what cases stored procs are necessary in modern databases such as MySql, SqlServer, Oracle, or . Is it overkill to have ALL access through stored procs?</p>
<blockquote> <p><strong>NOTE</strong> that this is a general look at stored procedures not regulated to a specific DBMS. Some DBMS (and even, different versions of the same DBMS!) may operate contrary to this, so you'll want to double-check with your target DBMS before assuming all of this still holds.</p> <p>I've been a Sybase ASE, MySQL, and SQL Server DBA on-and off since for almost a decade (along with application development in C, PHP, PL/SQL, C#.NET, and Ruby). So, I have no particular axe to grind in this (sometimes) holy war.</p> </blockquote> <p>The historical performance benefit of stored procs have generally been from the following (in no particular order):</p> <ul> <li>Pre-parsed SQL</li> <li>Pre-generated query execution plan</li> <li>Reduced network latency</li> <li>Potential cache benefits</li> </ul> <p><strong>Pre-parsed SQL</strong> -- similar benefits to compiled vs. interpreted code, except on a very micro level. </p> <p><em>Still an advantage?</em> Not very noticeable at all on the modern CPU, but if you are sending a single SQL statement that is VERY large eleventy-billion times a second, the parsing overhead can add up.</p> <p><strong>Pre-generated query execution plan</strong>. If you have many JOINs the permutations can grow quite unmanageable (modern optimizers have limits and cut-offs for performance reasons). It is not unknown for very complicated SQL to have distinct, measurable (I've seen a complicated query take 10+ seconds just to generate a plan, before we tweaked the DBMS) latencies due to the optimizer trying to figure out the "near best" execution plan. Stored procedures will, generally, store this in memory so you can avoid this overhead.</p> <p><em>Still an advantage?</em> Most DBMS' (the latest editions) will cache the query plans for INDIVIDUAL SQL statements, greatly reducing the performance differential between stored procs and ad hoc SQL. There are some caveats and cases in which this isn't the case, so you'll need to test on your target DBMS.</p> <p>Also, more and more DBMS allow you to provide optimizer path plans (abstract query plans) to significantly reduce optimization time (for both ad hoc and stored procedure SQL!!).</p> <blockquote> <p><strong>WARNING</strong> Cached query plans are not a performance panacea. Occasionally the query plan that is generated is sub-optimal. For example, if you send <code>SELECT * FROM table WHERE id BETWEEN 1 AND 99999999</code>, the DBMS may select a full-table scan instead of an index scan because you're grabbing every row in the table (so sayeth the statistics). If this is the cached version, then you can get poor performance when you later send <code>SELECT * FROM table WHERE id BETWEEN 1 AND 2</code>. The reasoning behind this is outside the scope of this posting, but for further reading see: <a href="http://www.microsoft.com/technet/prodtechnol/sql/2005/frcqupln.mspx">http://www.microsoft.com/technet/prodtechnol/sql/2005/frcqupln.mspx</a> and <a href="http://msdn.microsoft.com/en-us/library/ms181055.aspx">http://msdn.microsoft.com/en-us/library/ms181055.aspx</a> and <a href="http://www.simple-talk.com/sql/performance/execution-plan-basics/">http://www.simple-talk.com/sql/performance/execution-plan-basics/</a></p> <p>"In summary, they determined that supplying anything other than the common values when a compile or recompile was performed resulted in the optimizer compiling and caching the query plan for that particular value. Yet, when that query plan was reused for subsequent executions of the same query for the common values (‘M’, ‘R’, or ‘T’), it resulted in sub-optimal performance. This sub-optimal performance problem existed until the query was recompiled. At that point, based on the @P1 parameter value supplied, the query might or might not have a performance problem."</p> </blockquote> <p><strong>Reduced network latency</strong> A) If you are running the same SQL over and over -- and the SQL adds up to many KB of code -- replacing that with a simple "exec foobar" can really add up. B) Stored procs can be used to move procedural code into the DBMS. This saves shuffling large amounts of data off to the client only to have it send a trickle of info back (or none at all!). Analogous to doing a JOIN in the DBMS vs. in your code (everyone's favorite WTF!)</p> <p><em>Still an advantage?</em> A) Modern 1Gb (and 10Gb and up!) Ethernet really make this negligible. B) Depends on how saturated your network is -- why shove several megabytes of data back and forth for no good reason?</p> <p><strong>Potential cache benefits</strong> Performing server-side transforms of data can potentially be faster if you have sufficient memory on the DBMS and the data you need is in memory of the server.</p> <p><em>Still an advantage?</em> Unless your app has shared memory access to DBMS data, the edge will always be to stored procs.</p> <p>Of course, no discussion of Stored Procedure optimization would be complete without a discussion of parameterized and ad hoc SQL.</p> <p><strong>Parameterized / Prepared SQL</strong><br /> Kind of a cross between stored procedures and ad hoc SQL, they are embedded SQL statements in a host language that uses "parameters" for query values, e.g.:</p> <pre><code>SELECT .. FROM yourtable WHERE foo = ? AND bar = ? </code></pre> <p>These provide a more generalized version of a query that modern-day optimizers can use to cache (and re-use) the query execution plan, resulting in much of the performance benefit of stored procedures.</p> <p><strong>Ad Hoc SQL</strong> Just open a console window to your DBMS and type in a SQL statement. In the past, these were the "worst" performers (on average) since the DBMS had no way of pre-optimizing the queries as in the parameterized/stored proc method.</p> <p><em>Still a disadvantage?</em> Not necessarily. Most DBMS have the ability to "abstract" ad hoc SQL into parameterized versions -- thus more or less negating the difference between the two. Some do this implicitly or must be enabled with a command setting (SQL server: <a href="http://msdn.microsoft.com/en-us/library/ms175037.aspx">http://msdn.microsoft.com/en-us/library/ms175037.aspx</a> , Oracle: <a href="http://www.praetoriate.com/oracle_tips_cursor_sharing.htm">http://www.praetoriate.com/oracle_tips_cursor_sharing.htm</a>).</p> <p><strong>Lessons learned?</strong> Moore's law continues to march on and DBMS optimizers, with every release, get more sophisticated. Sure, you can place every single silly teeny SQL statement inside a stored proc, but just know that the programmers working on optimizers are very smart and are continually looking for ways to improve performance. Eventually (if it's not here already) ad hoc SQL performance will become indistinguishable (on average!) from stored procedure performance, so any sort of <em>massive</em> stored procedure use ** solely for "performance reasons"** sure sounds like premature optimization to me.</p> <p>Anyway, I think if you avoid the edge cases and have fairly vanilla SQL, you won't notice a difference between ad hoc and stored procedures.</p>
C++ inheritance and member function pointers <p>In C++, can member function pointers be used to point to derived (or even base) class members? </p> <p>EDIT: Perhaps an example will help. Suppose we have a hierarchy of three classes <code>X</code>, <code>Y</code>, <code>Z</code> in order of inheritance. <code>Y</code> therefore has a base class <code>X</code> and a derived class <code>Z</code>.</p> <p>Now we can define a member function pointer <code>p</code> for class <code>Y</code>. This is written as:</p> <pre><code>void (Y::*p)(); </code></pre> <p>(For simplicity, I'll assume we're only interested in functions with the signature <code>void f()</code> ) </p> <p>This pointer <code>p</code> can now be used to point to member functions of class <code>Y</code>.</p> <p>This question (two questions, really) is then:</p> <ol> <li>Can <code>p</code> be used to point to a function in the derived class <code>Z</code>?</li> <li>Can <code>p</code> be used to point to a function in the base class <code>X</code>?</li> </ol>
<p>C++03 std, <a href="http://www.open-std.org/jtc1/sc22/WG21/docs/wp/html/nov97-2/conv.html#conv.mem">§4.11 2 Pointer to member conversions</a>:</p> <blockquote> <p>An rvalue of type “pointer to member of B of type <i>cv</i> T,” where B is a class type, can be converted to an rvalue of type “pointer to member of D of type <i>cv</i> T,” where D is a derived class (clause 10) of B. If B is an inaccessible (clause 11), ambiguous (10.2) or virtual (10.1) base class of D, a program that necessitates this conversion is ill-formed. The result of the conversion refers to the same member as the pointer to member before the conversion took place, but it refers to the base class member as if it were a member of the derived class. The result refers to the member in D’s instance of B. Since the result has type “pointer to member of D of type <i>cv</i> T,” it can be dereferenced with a D object. The result is the same as if the pointer to member of B were dereferenced with the B sub-object of D. The null member pointer value is converted to the null member pointer value of the destination type. <sup>52)</sup></p> <p><sup>52)</sup>The rule for conversion of pointers to members (from pointer to member of base to pointer to member of derived) appears inverted compared to the rule for pointers to objects (from pointer to derived to pointer to base) (4.10, clause 10). This inversion is necessary to ensure type safety. Note that a pointer to member is not a pointer to object or a pointer to function and the rules for conversions of such pointers do not apply to pointers to members. In particular, a pointer to member cannot be converted to a void*.</p> </blockquote> <p>In short, you can convert a pointer to a member of an accessible, non-virtual base class to a pointer to a member of a derived class as long as the member isn't ambiguous. </p> <pre><code>class A { public: void foo(); }; class B : public A {}; class C { public: void bar(); }; class D { public: void baz(); }; class E : public A, public B, private C, public virtual D { public: typedef void (E::*member)(); }; class F:public E { public: void bam(); }; ... int main() { E::member mbr; mbr = &amp;A::foo; // invalid: ambiguous; E's A or B's A? mbr = &amp;C::bar; // invalid: C is private mbr = &amp;D::baz; // invalid: D is virtual mbr = &amp;F::bam; // invalid: conversion isn't defined by the standard ... </code></pre> <p>Conversion in the other direction (via <code>static_cast</code>) is governed by <a href="http://www.open-std.org/jtc1/sc22/WG21/docs/wp/html/nov97-2/expr.html#expr.static.cast">§ 5.2.9</a> 9:</p> <blockquote> <p>An rvalue of type "pointer to member of D of type <i>cv1</i> T" can be converted to an rvalue of type "pointer to member of B of type <i>cv2</i> T", where B is a base class (clause <a href="http://www.open-std.org/jtc1/sc22/WG21/docs/wp/html/nov97-2/derived.html#class.derived">10 class.derived</a>) of D, if a valid standard conversion from "pointer to member of B of type T" to "pointer to member of D of type T" exists (<a href="http://www.open-std.org/jtc1/sc22/WG21/docs/wp/html/nov97-2/conv.html#conv.mem">4.11 conv.mem</a>), and <i>cv2</i> is the same cv-qualification as, or greater cv-qualification than, <i>cv1</i>.<sup>11)</sup> The null member pointer value (<a href="http://www.open-std.org/jtc1/sc22/WG21/docs/wp/html/nov97-2/conv.html#conv.mem">4.11 conv.mem</a>) is converted to the null member pointer value of the destination type. If class B contains the original member, or is a base or derived class of the class containing the original member, the resulting pointer to member points to the original member. Otherwise, the result of the cast is undefined. [Note: although class B need not contain the original member, the dynamic type of the object on which the pointer to member is dereferenced must contain the original member; see <a href="http://www.open-std.org/jtc1/sc22/WG21/docs/wp/html/nov97-2/expr.html#expr.mptr.oper">5.5 expr.mptr.oper</a>.]</p> <p><sup>11)</sup> Function types (including those used in pointer to member function types) are never cv-qualified; see <a href="http://www.open-std.org/jtc1/sc22/WG21/docs/wp/html/nov97-2/decl.html#dcl.fct">8.3.5 dcl.fct</a>.</p> </blockquote> <p>In short, you can convert from a derived <code>D::*</code> to a base <code>B::*</code> if you can convert from a <code>B::*</code> to a <code>D::*</code>, though you can only use the <code>B::*</code> on objects that are of type D or are descended from D.</p>
How do you resize an IE browser window to 1024 x 768 <p>In Firefox you can enter the following into the awesome bar and hit enter:</p> <pre><code>javascript:self.resizeTo(1024,768); </code></pre> <p>How do you do the same thing in IE?</p>
<pre><code>javascript:resizeTo(1024,768); vbscript:resizeto(1024,768)</code></pre> <p>Will work in IE7, But consider using something like</p> <pre><code>javascript:moveTo(0,0);resizeTo(1024,768);</code></pre> <p>because IE7 doesn't allow the window to "resize" beyond the screen borders. If you work on a 1024,768 desktop, this is what happens...<ul><li>Firefox: 1024x768 Window, going behind the taskbar. If you drop the moveTo part, the top left corner of the window won't change position.(You still get a 1024x768 window)</li> <li>IE7: As close as possible to the requested size without obscuring the taskbar or allowing any part of the window to lie beyond the screen borders.</li> <li>safari: As close as possible to the requested size without obscuring the taskbar or allowing any part of the window to lie beyond the screen borders, but you can ommit the moveTo part. Safari will move the top left corner of the window for you.</li> <li>Opera: Nothing happens.</li> <li>Chrome: Nothing happens.</li></p> <p></ul></p>
Is there a child's PID? <p>I am currently in an operating systems class and my teacher spent half of the class period talking about PIDs. She mentioned, as many know, that processes know their parent's ID.</p> <p>My question is this:</p> <p>Does a process's PCB know its child's ID? If so, what is the way to go about it obtaining it?</p>
<p>As far as I know a process doesn't have an explicit list of its children's PIDs, but it can easily be built, since a process should know which child processes it spawns. For example the UNIX fork() call returns the child PID in the parent process and 0 in the child process, CreateProcess() on Windows returns (IIRC) the PID of the new process created.</p>
In C# (or any language) what is/are your favourite way of removing repetition? <p>I've just coded a 700 line class. Awful. I hang my head in shame. It's as opposite to DRY as a British summer.</p> <p>It's full of cut and paste with minor tweaks here and there. This makes it's a prime candidate for refactoring. Before I embark on this, I'd thought I'd ask when you have lots of repetition, what are the first refactoring opportunities you look for?</p> <p>For the record, mine are probably using:</p> <ol> <li>Generic classes and methods</li> <li>Method overloading/chaining.</li> </ol> <p>What are yours?</p>
<p>I like to start refactoring when I need to, rather than the first opportunity that I get. You might say this is somewhat of an agile approach to refactoring. When do I feel I need to? Usually when I feel that the ugly parts of my codes are starting to spread. I think ugliness is okay as long as they are contained, but the moment when they start having the urge to spread, that's when you need to take care of business. </p> <p>The techniques you use for refactoring should start with the simplest. I would strongly recommand Martin Fowler's book. Combining common code into functions, removing unneeded variables, and other simple techniques gets you a lot of mileage. For list operations, I prefer using functional programming idioms. That is to say, I use internal iterators, map, filter and reduce(in python speak, there are corresponding things in ruby, lisp and haskell) whenever I can, this makes code a lot shorter and more self-contained.</p>
How to escape text for regular expression in Java <p>Does Java have a built-in way to escape arbitrary text so that it can be included in a regular expression? For example, if my users enter "$5", I'd like to match that exactly rather than a "5" after the end of input.</p>
<p>Since <a href="http://download.oracle.com/javase/7/docs/api/java/util/regex/Pattern.html#quote%28java.lang.String%29">Java 1.5, yes</a>:</p> <pre><code>Pattern.quote("$5"); </code></pre>
My first Lisp macro; is it leaky? <p>I've been working through <a href="http://gigamonkeys.com/book" rel="nofollow">Practical Common Lisp</a> and as an exercise decided to write a macro to determine if a number is a multiple of another number:</p> <p><code>(defmacro multp (value factor)<br /> `(= (rem ,value ,factor) 0))</code></p> <p>so that : <code>(multp 40 10)</code> evaluates to true whilst <code>(multp 40 13)</code> does not </p> <p>The question is does this macro <a href="http://gigamonkeys.com/book/macros-defining-your-own.html#plugging-the-leaks" rel="nofollow">leak</a> in some way? Also is this "good" Lisp? Is there already an existing function/macro that I could have used?</p>
<p>Siebel gives an extensive rundown (for simple cases anyway) of possible sources of leaks, and there aren't any of those here. Both <code>value</code> and <code>factor</code> are evaluated only once and in order, and <code>rem</code> doesn't have any side effects.</p> <p>This is not good Lisp though, because there's no reason to use a macro in this case. A function</p> <pre><code>(defun multp (value factor) (zerop (rem value factor))) </code></pre> <p>is identical for all practical purposes. (Note the use of <code>zerop</code>. I think it makes things clearer in this case, but in cases where you need to highlight, that the value you're testing might still be meaningful if it's something other then zero, <code>(= ... 0)</code> might be better)</p>
Can I change the appearance of an html image during hover without a second image? <p>Is there a way to change the appearance of an icon (ie. contrast / luminosity) when I hover the cursor, without requiring a second image file (or without requiring a hidden portion of the image)?</p>
<p><a href="http://www.w3schools.com/css/css_image_transparency.asp" rel="nofollow">Here's some good information about image opacity and transparency with CSS</a>.</p> <p>So to make an image with opacity 50%, you'd do this:</p> <pre><code>&lt;img src="image.png" style="opacity: 0.5; filter: alpha(opacity=50)" /&gt; </code></pre> <p>The <strong>opacity:</strong> part is how Firefox does it, and it's a value between 0.0 and 1.0. <strong>filter:</strong> is how IE does it, and it's a value from 0 to 100.</p>
Here are fifteen characters <p>I will never understand why the SE network insists that every worthless question has to exist forever.</p>
<p>It's more of a browse assist than a search assist. If you see a large or bold tag in a tag cloud that interests you it my lead to some knowledge discovery that wouldn't have otherwise been sought out with a deliberate search. When I am browsing del.ico.us or stackoverflow I appreciate the tags as they sometimes lead me to discover related topics.</p> <p>Wikipedia has an interesting <a href="http://en.wikipedia.org/wiki/Tag_cloud" rel="nofollow">definition</a>:</p> <blockquote> <p>A tag cloud or word cloud (or weighted list in visual design) is a visual depiction of user-generated tags, or simply the word content of a site, used typically to describe the content of web sites. Tags are usually single words and are typically listed alphabetically, and the importance of a tag is shown with font size or color. [1] Thus both finding a tag by alphabet and by popularity is possible. The tags are usually hyperlinks that lead to a collection of items that are associated with a tag.</p> </blockquote>
What are the best strategies for using multiple AJAX libraries? <p>What experience can you share about using multiple AJAX libraries?</p> <p>There are useful features in Prototype, some in jQuery, the Yahoo library, etc. Is it possible to include all libraries and use what you want from each, do they generally all play nicely together with name spaces, etc. For the sake of speed is there a practical limit to the size/number of libraries to include or is this negligible? Are there pairs that work particularly well together (e.g. Prototype/Scriptaculous) or pairs that don't?</p>
<p>You could use all those libraries, but I highly recommend against it. Downloading and executing that much JavaScript will most likely choke the browser and slow down your user's experience. It would be much better from a user's perspective and a developer's to pick one. Less context/architecture switching and less code to maintain.</p> <p>Like other answers have said, most don't conflict. </p> <p>See Yahoo!'s <a href="http://developer.yahoo.com/performance/" rel="nofollow">Exceptional Performance</a> site for more info. </p>
loading Java classes from a signed applet <p>If I'm running a signed Java applet, can I load additional classes from remote sources (in the same domain, maybe even the same host) and run them?</p> <p>I'd like to do this without changing pages or even stopping the current applet. Of course, the total size of all classes is too large to load them all at once.</p> <p>Is there a way to do this? And is there a way to do this with signed applets and preserve their "confidence" status?</p>
<p>I think classes are lazy loaded in applets. being loaded on demand.</p> <p>Anyway, if the classes are outside of a jar you can simply use the applet classloader and load them by name. Ex:</p> <pre><code>ClassLoader loader = this.getClass().getClassLoader(); Class clazz = loader.loadClass("acme.AppletAddon"); </code></pre> <p>If you want to load classes from a jar I think you will need to create a new instance of URLClassLoader with the url(s) of the jar(s).</p> <pre><code>URL[] urls = new URL[]{new URL("http://localhost:8080/addon.jar")}; URLClassLoader loader = URLClassLoader.newInstance(urls,this.getClass().getClassLoader()); Class clazz = loader.loadClass("acme.AppletAddon"); </code></pre> <p>By default, applets are forbidden to create new classloaders. But if you sign your applet and include permission to create new classloaders you can do it.</p>
Why should the "PIMPL" idiom be used? <p>Backgrounder:</p> <p>The <a href="http://en.wikipedia.org/wiki/Opaque_pointer" rel="nofollow">PIMPL Idiom</a> (Pointer to IMPLementation) is a technique for implementation hiding in which a public class wraps a structure or class that cannot be seen outside the library the public class is part of.</p> <p>This hides internal implementation details and data from the user of the library.</p> <p>When implementing this idiom why would you place the public methods on the pimpl class and not the public class since the public classes method implementations would be compiled into the library and the user only has the header file?</p> <p>To illustrate, this code puts the <code>Purr()</code> implementation on the impl class and wraps it as well.</p> <p><strong>Why not implement Purr directly on the public class?</strong></p> <pre class="lang-c++ prettyprint-override"><code>// header file: class Cat { private: class CatImpl; // Not defined here CatImpl *cat_; // Handle public: Cat(); // Constructor ~Cat(); // Destructor // Other operations... Purr(); }; // CPP file: #include "cat.h" class Cat::CatImpl { Purr(); ... // The actual implementation can be anything }; Cat::Cat() { cat_ = new CatImpl; } Cat::~Cat() { delete cat_; } Cat::Purr(){ cat_-&gt;Purr(); } CatImpl::Purr(){ printf("purrrrrr"); } </code></pre>
<p>I think most people refer to this as the Handle Body idiom. See James Coplien's book Advanced C++ Programming Styles and Idioms (<a href="http://rads.stackoverflow.com/amzn/click/0201548550">Amazon link</a>). It's also known as the <a href="http://en.wikipedia.org/wiki/Cheshire_Cat">Cheshire Cat</a> because of Lewis Caroll's character that fades away until only the grin remains.</p> <p>The example code should be distributed across two sets of source files. Then only Cat.h is the file that is shipped with the product.</p> <p>CatImpl.h is included by Cat.cpp and CatImpl.cpp contains the implementation for CatImpl::Purr(). This won't be visible to the public using your product.</p> <p>Basically the idea is to hide as much as possible of the implementation fom prying eyes. This is most useful where you have a commercial product that is shipped as a series of libraries that are accessed via an API that the customer's code is compiled against and linked to.</p> <p>We did this with the rewrite of IONAs Orbix 3.3 product in 2000.</p> <p>As mentioned by others, using his technique completely decouples the implementation from the interface of the object. Then you won't have to recompile everything that uses Cat if you just want to change the implementation of Purr().</p> <p>This technique is used in a methodology called <a href="http://en.wikipedia.org/wiki/Design_by_contract">design by contract</a>.</p>
Best way to initiate a download? <p>On a PHP-based web site, I want to send users a download package after they have filled out a short form. The site-initiated download should be similar to sites like download.com, which say "your download will begin in a moment."</p> <p>A couple of <strong>possible approaches</strong> I know about, and browser compatibility (based on a quick test):</p> <p><strong>1) Do a <code>window.open</code> pointing to the new file.</strong> </p> <pre><code>- FireFox 3 blocks this. - IE6 blocks this. - IE7 blocks this. </code></pre> <p><strong>2) Create an iframe pointing to the new file.</strong> </p> <pre><code>- FireFox 3 seems to think this is OK. (Maybe it's because I already accepted it once?) - IE6 blocks this. - IE7 blocks this. How can I do this so that at least these three browsers will not object? </code></pre> <p>Bonus: is there a method that doesn't require browser-conditional statements? </p> <p>(I believe that download.com employs both methods conditionally, but I can't get either one to work.)</p> <p><strong>Responses and Clarifications:</strong></p> <pre><code>Q: "Why not point the current window to the file?" A: That might work, but in this particular case, I want to show them some other content while their download starts - for example, "would you like to donate to this project?" </code></pre> <p><strong>UPDATE: I have abandoned this approach. See my answer below for reasons.</strong></p>
<p>You can also do a meta refresh, which most browsers support. Download.com places one in a noscript tag.</p> <pre><code>&lt;meta http-equiv="refresh" content="5;url=/download.php?doc=123.zip"/&gt; </code></pre>
Getting started with Silverlight development <p>How does one start development in Silverlight?</p> <p>Does one need a new IDE? or Visual studio will support?</p>
<p>Yes there is tooling support for Visual Studio. It is still in Beta though.</p> <p><a href="http://silverlight.net/GetStarted/" rel="nofollow">Get Started Building Silverlight 2 Applications</a></p> <p>1) Install Visual Studio 2008 then Install Silverlight Tools Beta 2 for Visual Studio 2008 This add-on to Visual Studio 2008 allows you to use .NET to create Silverlight 2 Beta 2 Web sites. The Silverlight 2 Beta 2 Runtime and the Silverlight 2 Beta 2 SDK are installed as part of this install. For additional information read the overview and the Silverlight 2 Beta 2 Readme Notes. Note if you have Visual Studio 2008 Service Pack 1 Beta installed, please see this information for details on installing correctly. </p> <p>2) Install Expression Blend 2.5 June 2008 Preview This is a preview version of Expression Blend for designing Silverlight 2 experiences. </p> <p>3) Install Deep Zoom Composer This tool allows you to prepare your images for use with the Deep Zoom feature in Silverlight 2. </p> <p>One thing to watch out for is that Silverlight does not support Synchronous calls to the server. All calls are <a href="http://weblogs.asp.net/scottgu/pages/silverlight-tutorial-part-3-using-networking-to-retrieve-data-and-populate-a-datagrid.aspx" rel="nofollow">Asynchronous</a> as of <a href="http://petesbloggerama.blogspot.com/2008/07/omg-silverlight-asynchronous-is-evil.html" rel="nofollow">this Beta</a>.</p>
ASP.NET - Is it possible to trigger a postback from server code? <p>Is it possible to to programmatically trigger a postback from server code in ASP.NET? I know that it is possible to do a Response.Redirect or Server.Transfer to redirect to a page, but is there a way to trigger a postback to the same page in server code (<em>i.e.</em> without using javascript trickery to submit a form)?</p>
<p>Asp.net Postbacks are initiated from the client (typically form submission). I am not sure what you are trying to achieve. Some of the server side <a href="http://www.15seconds.com/issue/020102.htm">page lifecyle</a> events are already executed and what you are trying to do is raise the previous event handlers again.</p>
How do I write a python HTTP server to listen on multiple ports? <p>I'm writing a small web server in Python, using BaseHTTPServer and a custom subclass of BaseHTTPServer.BaseHTTPRequestHandler. Is it possible to make this listen on more than one port?</p> <p>What I'm doing now:</p> <pre><code>class MyRequestHandler(BaseHTTPServer.BaseHTTPRequestHandler): def doGET [...] class ThreadingHTTPServer(ThreadingMixIn, HTTPServer): pass server = ThreadingHTTPServer(('localhost', 80), MyRequestHandler) server.serve_forever() </code></pre>
<p>Sure; just start two different servers on two different ports in two different threads that each use the same handler. Here's a complete, working example that I just wrote and tested. If you run this code then you'll be able to get a Hello World webpage at both <a href="http://localhost:1111/">http://localhost:1111/</a> and <a href="http://localhost:2222/">http://localhost:2222/</a></p> <pre><code>from threading import Thread from SocketServer import ThreadingMixIn from BaseHTTPServer import HTTPServer, BaseHTTPRequestHandler class Handler(BaseHTTPRequestHandler): def do_GET(self): self.send_response(200) self.send_header("Content-type", "text/plain") self.end_headers() self.wfile.write("Hello World!") class ThreadingHTTPServer(ThreadingMixIn, HTTPServer): pass def serve_on_port(port): server = ThreadingHTTPServer(("localhost",port), Handler) server.serve_forever() Thread(target=serve_on_port, args=[1111]).start() serve_on_port(2222) </code></pre>
How to determine the value of a controller variable during execution in Ruby on Rails? <p>What is the best way for me to determine a controller variable's value during execution?</p> <p>For example, is there a way I can insert a break in the code, and cause the value of the variable to be output to the screen (or the log)?</p>
<p>Yes. The easiest way is to raise the value as a string. Like so: <code>raise @foo.to_s</code></p> <p>Or, you can install the debugger (<code>gem install ruby-debug</code>), and then start the development server with the <code>--debugger</code> flag. Then, in your code, call the <code>debugger</code> instruction.</p> <p>Inside the debugger prompt, you have many commands, including <code>p</code> to print the value of a variable.</p> <p><strong>Update:</strong> here's <a href="http://bashdb.sourceforge.net/ruby-debug.html">a bit more about ruby-debug</a>.</p>
Which jQuery plugin should be used to fix the IE6 PNG transparency issue? <p>Is there an IE6/PNG fix that is officially developed by the jQuery team?</p> <p>If not which of the available plugins should I use?</p>
<p>I'm using <a href="http://jquery.andreaseberhard.de/pngFix/" rel="nofollow">jquery.pngFix.js</a>. I don't know if it's officially sanctioned or not, I do know that it works. I chose it because it was the plugin included with FancyBox, no other reason. </p>
Installing Curl IDE/RTE on AMD processors <p>Trying to move my development environment to Linux. And new to Curl. Can't get it to install the IDE &amp; RTE packages on an AMD HP PC running Ubuntu x64. I tried to install the Debian package via the package installer and get "Error: Wrong architecture - i386". Tried using the --force-architecture switch but it errors out. </p> <p>I'm assuming Curl IDE will just run under Intel processors? Anyone have any luck with this issue and can advise?</p>
<p>It's been a while since I ran linux, but try looking for the x64 version. There are also x64 to x86 compatibility libraries available that should make 32 bit programs work for most situations. </p> <p>The <a href="http://ubuntuforums.org/" rel="nofollow">ubuntu forums</a> are a much better place for this question, however. </p>
Find out how much memory is being used by an object in C#? <p>Does anyone know of a way to find out how much memory an instance of an object is taking?</p> <p>For example, if I have an instance of the following object:</p> <p>TestClass tc = new TestClass();</p> <p>Is there a way to find out how much memory the instance "tc" is taking?</p> <p>The reason for asking, is that although C# has built in memory management, I often run into issues with not clearing an instance of an object (e.g. a List that keeps track of something).</p> <p>There are couple of reasonably good memory profilers (e.g. ANTS Profiler) but in a multi-threaded environment is pretty hard to figure out what belongs where, even with those tools. </p>
<p>If you are not trying to do it in code itself, which I'm assuming based on your ANTS reference, try taking a look at CLRProfiler (currently v2.0). It's free and if you don't mind the rather simplistic UI, it can provide valuable information. It will give you a in-depth overview of all kinds of stats. I used it a while back as one tool for finding a memory leek.</p> <p>Download here: <a href="http://www.microsoft.com/downloads/details.aspx?FamilyId=A362781C-3870-43BE-8926-862B40AA0CD0&amp;displaylang=en">http://www.microsoft.com/downloads/details.aspx?FamilyId=A362781C-3870-43BE-8926-862B40AA0CD0&amp;displaylang=en</a></p> <p>If you do want to do it in code, the CLR has profiling APIs you could use. If you find the information in CLRProfiler, since it uses those APIs, you should be able to do it in code too. More info here: <a href="http://msdn.microsoft.com/de-de/magazine/cc300553(en-us).aspx">http://msdn.microsoft.com/de-de/magazine/cc300553(en-us).aspx</a></p> <p>(It's not as cryptic as using WinDbg, but be prepared to do mighty deep into the CLR.)</p>
What is wrong with using inline functions? <p>While it would be very convenient to use inline functions at some situations,</p> <p>Are there any drawbacks with inline functions?</p> <p><strong>Conclusion</strong>:</p> <p>Apparently, There is nothing wrong with using inline functions.</p> <p>But it is worth noting the following points!</p> <ul> <li><p>Overuse of inlining can actually make programs slower. Depending on a function's size, inlining it can cause the code size to increase or decrease. Inlining a very small accessor function will usually decrease code size while inlining a very large function can dramatically increase code size. On modern processors smaller code usually runs faster due to better use of the instruction cache. <a href="http://google-styleguide.googlecode.com/svn/trunk/cppguide.xml#Inline_Functions">- Google Guidelines</a></p></li> <li><p>The speed benefits of inline functions tend to diminish as the function grows in size. At some point the overhead of the function call becomes small compared to the execution of the function body, and the benefit is lost <a href="http://www-rocq.inria.fr/who/Marc.Thiriet/Langages/tic0324.html">- Source</a></p></li> <li><p>There are few situations where an inline function may not work:</p> <ul> <li>For a function returning values; if a return statement exists.</li> <li>For a function not returning any values; if a loop, switch or goto statement exists. </li> <li>If a function is recursive. <a href="http://www-rocq.inria.fr/who/Marc.Thiriet/Langages/tic0324.html">-Source</a></li> </ul></li> <li><p>The <code>__inline</code> keyword causes a function to be inlined only if you specify the optimize option. If optimize is specified, whether or not <code>__inline</code> is honored depends on the setting of the inline optimizer option. By default, the inline option is in effect whenever the optimizer is run. If you specify optimize , you must also specify the noinline option if you want the <code>__inline</code> keyword to be ignored. <a href="http://support.sas.com/documentation/onlinedoc/sasc/doc750/html/clug/zcoptinl.htm">-Source</a></p></li> </ul>
<p>It worth pointing out that the inline keyword is actually just a hint to the compiler. The compiler may ignore the inline and simply generate code for the function someplace.</p> <p>The main drawback to inline functions is that it can <strong>increase the size of your executable</strong> (depending on the number of instantiations). This can be a problem on some platforms (eg. embedded systems), especially if the function itself is recursive.</p> <p>I'd also recommend making inline'd functions <strong>very small</strong> - The speed benefits of inline functions tend to diminish as the function grows in size. At some point the overhead of the function call becomes small compared to the execution of the function body, and the benefit is lost.</p>
Changing the font in Aquamacs? <p>I've recently had a need to do a bit of lisp editing and I found the nifty Ready Lisp package for OS X, which is great, except Aquamacs automatically uses a proportional font (which is idiotic, IMHO) and I want to change it to a monospace font. However, I'm not really much of an EMACS user, and the preferences menu in Aquamacs is less than clear on where and how one might make such a change. </p>
<p>In Aquamacs 2.1, you can set the font through Options->Appearance->Font for Text Mode... That brings up the standard font chooser window, choose the font you like. Then, when you exit out of emacs (C-x C-c) you'll be prompted to save options, hit "y".</p>
What is the best implementation for DB Audit Trail? <p>A DB Audit Trail captures the User Last Modified, Modified Date, and Created Date.</p> <p>There are several possible implementations:</p> <ul> <li>SQL Server Triggers</li> <li>Add UserModified, ModifiedDate, CreatedDate columns to the database and include logic in Stored Procedures or Insert, Update statements accordingly.</li> </ul> <p>It would be nice if you include implementation (or link to) in your answer. </p>
<p>Depending on what you're doing, you might want to move the audit out of the data layer into the data access layer. It give you more control.</p> <p>I asked a similar question wrt NHibernate and SqlServer <a href="http://stackoverflow.com/questions/15917/data-auditing-in-nhibernate-and-sqlserver" rel="nofollow">here</a>.</p>
Is there a better Windows Console Window? <p>I find working on the command line in Windows frustrating, primarily because the console window is wretched to use compared to terminal applications on linux and OS X such as "rxvt", "xterm", or "Terminal". Major complaints:</p> <ol> <li><p>No standard copy/paste. You have to turn on "mark" mode and it's only available from a multi-level popup triggered by the (small) left hand corner button. Then copy and paste need to be invoked from the same menu</p></li> <li><p>You can't arbitrarily resize the window by dragging, you need to set a preference (back to the multi-level popup) each time you want to resize a window</p></li> <li><p>You can only make the window so big before horizontal scroll bars enter the picture. Horizontal scroll bars suck.</p></li> <li><p>With the cmd.exe shell, you can't navigate to folders with \\netpath notation (UNC?), you need to map a network drive. This sucks when working on multiple machines that are going to have different drives mapped</p></li> </ol> <p>Are there any tricks or applications, (paid or otherwise), that address these issue?</p>
<p>Sorry for the self-promotion, I'm the author of another Console Emulator, not mentioned here.</p> <p><a href="http://www.fosshub.com/ConEmu.html">ConEmu</a> is opensource console emulator with tabs, which represents multiple consoles and simple GUI applications as one customizable GUI window.</p> <p>Initially, the program was designed to work with <a href="http://www.farmanager.com/">Far Manager</a> (my favorite shell replacement - file and archive management, command history and completion, powerful editor). But ConEmu can be used with any other console application or simple GUI tools (like PuTTY for example). ConEmu is a live project, open to suggestions.</p> <p>A brief excerpt from the long list of options:</p> <ul> <li>Latest versions of ConEmu may set up itself as <a href="http://superuser.com/a/509710/139371">default terminal for Windows</a></li> <li>Use any font installed in the system, or copied to a folder of the program (ttf, otf, fon, bdf)</li> <li>Run selected tabs as Administrator (Vista+) or as selected user</li> <li>Windows 7 Jump lists and Progress on taskbar</li> <li>Integration with <a href="http://www.dosbox.com/">DosBox</a> (useful in 64bit systems to run DOS applications)</li> <li>Smooth resize, maximized and fullscreen window modes</li> <li>Scrollbar initially hidden, may be revealed by mouseover or checkbox in settings</li> <li>Optional settings (e.g. pallette) for selected applications</li> <li>User friendly text and block selection (from keyboard or mouse), copy, paste, text search in console</li> <li>ANSI X3.64 and Xterm 256 color</li> </ul> <p>Far Manager users will acquire shell style drag-n-drop, thumbnails and tiles in panles, tabs for editors and viewers, true colors and font styles (italic/bold/underline).</p> <p>PS. Far Manager supports UNC paths (\\server\share\...)</p>
Development directory Structure <p>I am wondering what directory structure are commonly used in development projects. I mean with the idea of facilitating builds, deploys release, and etc.</p> <p>I recently used a <a href="http://maven.apache.org/guides/introduction/introduction-to-the-standard-directory-layout.html">Maven structure</a> for a java project, but I am not sure it's the best structure for a non-maven driven project.</p> <p>So, I have two questions: When you guys start new projects, what structure you use? And: What if you need to integrate two different languages, like for example java classes into a PHP application; PHP files are source files, web files, you you use a /src, /classes, webapps/php ? What are your choices in such scenarios. </p> <p>As a note: I am wondering also what are you choices for directories names. I like the 3-letters names (src, lib, bin, web, img, css, xml, cfg) but what are your opinions about descriptive names like libraris, sources or htdocs/public_html ?</p>
<p>After a couple years working with different structures I recently found a structure that hols most variations for me:</p> <pre><code>/project_name (everything goes here) /web (htdocs) /img /css /app (usually some framework or sensitive code) /lib (externa libs) /vendor_1 /vendor_2 /tmp /cache /sql (sql scripts usually with maybe diagrams) /scripts /doc (usually an empty directory) </code></pre>
How to save the output of a console application <p>I need advice on how to have my C# console application display text to the user through the standard output while still being able access it later on. The actual feature I would like to implement is to dump the entire output buffer to a text file at the end of program execution.</p> <p>The workaround I use while I don't find a cleaner approach is to subclass <code>TextWriter</code> overriding the writing methods so they would both write to a file and call the original stdout writer. Something like this:</p> <pre><code>public class DirtyWorkaround { private class DirtyWriter : TextWriter { private TextWriter stdoutWriter; private StreamWriter fileWriter; public DirtyWriter(string path, TextWriter stdoutWriter) { this.stdoutWriter = stdoutWriter; this.fileWriter = new StreamWriter(path); } override public void Write(string s) { stdoutWriter.Write(s); fileWriter.Write(s); fileWriter.Flush(); } // Same as above for WriteLine() and WriteLine(string), // plus whatever methods I need to override to inherit // from TextWriter (Encoding.Get I guess). } public static void Main(string[] args) { using (DirtyWriter dw = new DirtyWriter("path", Console.Out)) { Console.SetOut(dw); // Teh codez } } } </code></pre> <p>See that it writes to and flushes the file all the time. I'd love to do it only at the end of the execution, but I couldn't find any way to access to the output buffer.</p> <p>Also, excuse inaccuracies with the above code (had to write it <em>ad hoc</em>, sorry ;).</p>
<p>The perfect solution for this is to use <a href="http://logging.apache.org/log4net/">log4net</a> with a console appender and a file appender. There are many other appenders available as well. It also allows you to turn the different appenders off and on at runtime. </p>
Mocking Static Blocks in Java <p>My motto for Java is "just because Java has static blocks, it doesn't mean that you should be using them." Jokes aside, there are a lot of tricks in Java that make testing a nightmare. Two of the most I hate are Anonymous Classes and Static Blocks. We have a lot of legacy code that make use of Static Blocks and these are one of the annoying points in our push in writing unit tests. Our goal is to be able to write unit tests for classes that depend on this static initialization with minimal code changes. </p> <p>So far my suggestion to my colleagues is to move the body of the static block into a private static method and call it <code>staticInit</code>. This method can then be called from within the static block. For unit testing another class that depends on this class could easily mock <code>staticInit</code> with JMockit to not do anything. Let's see this in example.</p> <pre><code>public class ClassWithStaticInit { static { System.out.println("static initializer."); } } </code></pre> <p>Will be changed to</p> <pre><code>public class ClassWithStaticInit { static { staticInit(); } private static void staticInit() { System.out.println("static initialized."); } } </code></pre> <p>So that we can do the following in a JUnit.</p> <pre><code>public class DependentClassTest { public static class MockClassWithStaticInit { public static void staticInit() { } } @BeforeClass public static void setUpBeforeClass() { Mockit.redefineMethods(ClassWithStaticInit.class, MockClassWithStaticInit.class); } } </code></pre> <p>However this solution also comes with its own problems. You can't run <code>DependentClassTest</code> and <code>ClassWithStaticInitTest</code> on the same JVM since you actually want the static block to run for <code>ClassWithStaticInitTest</code>.</p> <p>What would be your way of accomplishing this task? Or any better, non-JMockit based solutions that you think would work cleaner?</p>
<p><a href="http://powermock.org">PowerMock</a> is another mock framework that extends EasyMock and Mockito. With PowerMock you can easily <a href="http://code.google.com/p/powermock/wiki/SuppressUnwantedBehavior">remove unwanted behavior</a> from a class, for example a static initializer. In your example you simply add the following annotations to your JUnit test case:</p> <pre><code>@RunWith(PowerMockRunner.class) @SuppressStaticInitializationFor("some.package.ClassWithStaticInit") </code></pre> <p>PowerMock does not use a Java agent and therefore does not require modification of the JVM startup parameters. You simple add the jar file and the above annotations. </p>
Web in a desktop application: Good web browser controls? <p>I've been utlising a "web browser control" in desktop based applications (in my case Windows Forms .NET) for a number of years. I mostly use it to create a familiar flow-based user interface that also allows a seamless transition to the internet where required.</p> <p>I'm really tired of the IE browser control because of the poor quality html it generates on output. Also, I guess that it is really just IE7 behind the scenes and so has many of that browser "issues". Despite this, it is quite a powerful control and provides rich interaction with your desktop app.</p> <p>So, what other alternatives to the IE browser control are there? I looked at a Mosaic equivalent a year ago but was disappointed with the number of unimplemented features, maybe this has improved recently?</p>
<p>hmm..Interestingly </p> <ol> <li><a href="http://www.iol.ie/~locka/mozilla/control.htm" rel="nofollow">Mozilla</a> seems to provide ActiveX control</li> <li><a href="http://kmeleon.sourceforge.net/" rel="nofollow">K-Melon</a> is another Gecko based browser control</li> </ol>
Is there a good, free WYSIWYG editor for creating HTML using a Django template? <p>I'm interested to get a free, WYSIWYG HTML editor that is compatible with Django template. Any ideas?</p> <blockquote> <p>Thanks LainMH.</p> <p>But I afraid fckeditor is used in web app, for the purpose of editing HTML. What I want is an editor that allows me to write HTML that is Django compatible. </p> <p>Hope this clarifies the issue.</p> </blockquote>
<p><a href="http://www.fckeditor.net/">http://www.fckeditor.net/</a> ?</p> <p>EDIT: Just found this: <a href="http://blog.newt.cz/blog/integration-fckeditor-django/">http://blog.newt.cz/blog/integration-fckeditor-django/</a></p>
DIV's vs. Tables or CSS vs. Being Stupid <p>I know that tables are for tabular data, but it's so tempting to use them for layout. I can handle DIV's to get a three column layout, but when you got 4 nested DIV's, it get tricky. </p> <p>Is there a tutorial/reference out there to persuade me to use DIV's for layout?</p> <p>I want to use DIV's, but I refuse to spend an hour to position my DIV/SPAN where I want it.</p> <p>@GaryF: <a href="http://www.blueprintcss.org/">Blueprint CSS</a> has to be the CSS's best kept secret.</p> <p>Great tool - <a href="http://kematzy.com/blueprint-generator/">Blueprint Grid CSS Generator</a>.</p>
<p>There's the <a href="http://developer.yahoo.com/yui/grids/">Yahoo Grid CSS</a> which can do all sorts of things. But remember: <strong>CSS IS NOT A RELIGION</strong>. If you save hours by using tables instead of css, do so. </p> <p>One of the corner cases I could never make my mind up about is forms. I'd love to do it in css, but it's just so much more complicated than tables. You could even argue that forms are tables, in that they have headers (labels) and data (input fields). </p>
What are the pros and cons of the SVN plugins for Eclipse, Subclipse and Subversive? <p>SVN in Eclipse is spread into 2 camps. The SVN people have developed a plugin called <a href="http://subclipse.tigris.org/">Subclipse</a>. The Eclipse people have a plugin called <a href="http://www.eclipse.org/subversive/">Subversive</a>. Broadly speaking they both do the same things. What are the advantages and disadvantages of each?</p>
<p>Both are very similar but Subversive is the "eclipse svn provider". I primarily use Subversive because of a few convenient features:</p> <p><strong>Grouping of history</strong></p> <p>When I'm browsing the history of a branch instead of just seeing a bunch of rows for every commit it can group commits by today, week, etc.</p> <p><strong>Mapping of trunk, branches, and tags</strong></p> <p>Subversive assumes the default svn layout: trunk, branches, tags (which you can change), so whenever you want to tag or branch it is one click and you provide the name of the tag or branch.</p> <p>Like I said these are minor differences that I just find convenient. Both work great with mylyn, but overall there really isn't a whole lot of differences with these two extensions.</p> <p>Merging with Subversive is a pain though (haven't tried Subclipse), I've never been able to successfully merge. The preview of the merge is great but it would never complete the merge or it will take way to long. Most of the time I complete merging through the command line without any issues.</p>
What Makes a Good Unit Test? <p>I'm sure most of you are writing lots of automated tests and that you also have run into some common pitfalls when unit testing. </p> <p>My question is do you follow any rules of conduct for writing tests in order to avoid problems in the future? To be more specific: What are the <strong>properties of good unit tests</strong> or how do you write your tests?</p> <p>Language agnostic suggestions are encouraged.</p>
<p>Let me begin by plugging sources - <a href="http://pragprog.com/titles/utj/pragmatic-unit-testing-in-java-with-junit" rel="nofollow">Pragmatic Unit Testing in Java with JUnit</a> (There's a version with C#-Nunit too.. but I have this one.. its agnostic for the most part. Recommended.)</p> <p>Good Tests should be A TRIP (The acronymn isn't sticky enough - I have a printout of the cheatsheet in the book that I had to pull out to make sure I got this right..)</p> <ul> <li><strong>Automatic</strong> : Invoking of tests as well as checking results for PASS/FAIL should be automatic</li> <li><strong>Thorough</strong>: Coverage; Although bugs tend to cluster around certain regions in the code, ensure that you test all key paths and scenarios.. Use tools if you must to know untested regions</li> <li><strong>Repeatable</strong>: Tests should produce the same results each time.. every time. Tests should not rely on uncontrollable params.</li> <li><strong>Independent</strong>: Very important. <ul> <li>Tests should <strong>test only one thing</strong> at a time. Multiple assertions are okay as long as they are all testing one feature/behavior. When a test fails, it should pinpoint the location of the problem.</li> <li>Tests <strong>should not rely on each other</strong> - Isolated. No assumptions about order of test execution. Ensure 'clean slate' before each test by using setup/teardown appropriately</li> </ul></li> <li><p><strong>Professional</strong>: In the long run you'll have as much test code as production (if not more), therefore follow the same standard of good-design for your test code. Well factored methods-classes with intention-revealing names, No duplication, tests with good names, etc. </p></li> <li><p>Good tests also run <strong>Fast</strong>. any test that takes over half a second to run.. needs to be worked upon. The longer the test suite takes for a run.. the less frequently it will be run. The more changes the dev will try to sneak between runs.. if anything breaks.. it will take longer to figure out which change was the culprit.</p></li> </ul> <p>Update 2010-08:</p> <ul> <li><strong>Readable</strong> : This can be considered part of Professional - however it can't be stressed enough. An acid test would be to find someone who isn't part of your team and asking him/her to figure out the behavior under test within a couple of minutes. Tests need to be maintained just like production code - so make it easy to read even if it takes more effort. Tests should be symmetric (follow a pattern) and concise (test one behavior at a time). Use a consistent naming convention (e.g. the TestDox style). Avoid cluttering the test with "incidental details".. become a minimalist.</li> </ul> <p>Apart from these, most of the others are guidelines that cut down on low-benefit work: e.g. 'Don't test code that you don't own' (e.g. third-party DLLs). Don't go about testing getters and setters. Keep an eye on cost-to-benefit ratio or defect probability.</p>
How can I access the backing variable of an auto-implemented property? <p>In the past we declared properties like this:</p> <pre><code>public class MyClass { private int _age; public int Age { get{ return _age; } set{ _age = value; } } } </code></pre> <p>Now we can do:</p> <pre><code>public class MyClass { public int Age {get; set;} } </code></pre> <p>My question is, how can I access the private variable that is created automatically using this notation? </p> <p>I would rather access the private variable and not the public accessor 'Age'. Is there a default notation to access the private variable, or it is just not possible?</p>
<p>The aim of the new automatic properties is to reduce the amount of boilerplate code you need to write when you just have a simple property that doesn't need any special logic in the get or the set. </p> <p>If you want to access the private member that these properties use, that's usually for a few reasons:</p> <ul> <li>You need to more than just a simple get/set - in this case, you should just avoid using automatic properties for this member.</li> <li>You want to avoid the performance hit of going through the get or set and just use the member directly - in this case, I'd be surprised if there really was a performance hit. The simple get/set members are very very easy to inline, and in my (admittedly limited) testing I haven't found a difference between using the automatic properties and accessing the member directly. </li> <li><p>You only want to have public read access (i.e. just a 'get') and the class write to the member directly - in this case, you can use a private set in your automatic property. i.e.</p> <pre><code>public class MyClass { public int Age {get; private set;} }</code></pre></li> </ul> <p>This usually covers most the reasons for wanting to directly get to the backing field used by the automatic properties.</p>
What are the pros and cons of object databases? <p>There is a lot of information out there on object-relational mappers and how to best avoid impedance mismatch, all of which seem to be moot points if one were to use an object database. My question is why isn't this used more frequently? Is it because of performance reasons or because object databases cause your data to become proprietary to your application or is it due to something else? </p>
<p>I've been using <a href="http://www.db4o.com">db4o</a> which is an OODB and it solves most of the cons listed:</p> <ul> <li>Familiarity - Programmers know their language better then SQL (see Native queries)</li> <li>Performance - this one is highly subjective but you can take a look at <a href="http://polepos.sourceforge.net/">PolePosition</a></li> <li>Vendor support and maturity - can change over time</li> <li>Cannot be used by programs that don't also use the same framework - There are OODB standards and you can use <a href="http://developer.db4o.com/forums/thread/51254.aspx">different frameworks</a></li> <li>Versioning is probably a bit of a bitch - Versioning is actually <a href="http://developer.db4o.com/forums/thread/22660.aspx">easier</a>!</li> </ul> <p>The pros I'm interested in are:</p> <ul> <li>Native queries - Db4o lets you write queries in your static typed language so you don't have to worry about mistyping a string and finding data missing at runtime,</li> <li>Ease of use - Defining buissiness logic in the domain layer, persistence layer (mapping) and finally the SQL database is certainly violation of DRY. With OODB you define your domain where it belongs.</li> </ul> <p>I agree - OODB have a long way to go but they are going. And there are domain problems out there that are better solved by OODB,</p>
How to work around a very large 2d array in C++ <p>I need to create a 2D int array of size 800x800. But doing so creates a stack overflow (ha ha).</p> <p>I'm new to C++, so should I do something like a vector of vectors? And just encapsulate the 2d array into a class?</p> <p>Specifically, this array is my zbuffer in a graphics program. I need to store a z value for every pixel on the screen (hence the large size of 800x800).</p> <p>Thanks!</p>
<p>You need about 2.5 megs, so just using the heap should be fine. You don't need a vector unless you need to resize it. See <a href="https://isocpp.org/wiki/faq/freestore-mgmt#multidim-arrays" rel="nofollow">C++ FAQ Lite</a> for an example of using a "2D" heap array.</p> <pre><code>int *array = new int[800*800]; </code></pre> <p>(Don't forget to <code>delete[]</code> it when you're done.)</p>
How to implement database engine independent paging? <p>Task: implement paging of database records suitable for different RDBMS. Method should work for mainstream engines - MSSQL2000+, Oracle, MySql, etc.</p> <p>Please don't post RDBMS specific solutions, I know how to implement this for most of the modern database engines. I'm looking for the universal solution. Only temporary tables based solutions come to my mind at the moment.</p> <p><strong>EDIT:</strong><br /> I'm looking for SQL solution, not 3rd party library.</p>
<p>There would have been a universal solution if SQL specifications had included paging as a standard. The requirement for any RDBMS language to be called an RDBMS language does not include paging support as well. </p> <p>Many database products support SQL with proprietary extensions to the standard language. Some of them support paging like MySQL with the limit clause, Rowid with Oracle; each handled differently. Other DBMS's will need to add a field called rowid or something like that.</p> <p>I dont think you can have a universal solution (anyone is free to prove me wrong here;open to debate) unless it is built into the database system itself or unless there is a company say ABC that uses Oracle, MySQL, SQL Server and they decide to have all the various database systems provide their own implementation of paging by their database developers providing a universal interface for the code that uses it. </p>
Browser WYSIWYG best practices <p>I am using a rich text editor on a web page. .NET has feature that prevent one from posting HTML tags, so I added a JavaScript snippet to change the angle brackets to and alias pair of characters before the post. The alias is replaced on the server with the necessary angle bracket and then stored in the database. With XSS aside, what are common ways of fixing this problem. (i.e. Is there a better way?)</p> <p>If you have comments on XSS(cross-site scripting), I'm sure that will help someone.</p>
<p>There's actually a way to turn that "feature" off. This will allow the user to post whichever characters they want, and there will be no need to convert characters to an alias using Javascript. See this article for <a href="http://mdid.org/mdidwiki/index.php?title=Disabling_Request_Validation" rel="nofollow">disabling request validation</a>. It means that you'll have to do your own validation, but from the sounds of your post, it seems that is what you are looking to do anyway. You can also disable it per page by following <a href="http://www.asp.net/learn/whitepapers/request-validation/" rel="nofollow">the instructions here</a>.</p>
Is there a way to asynchronously filter an IList? <p>Ok, so there has to be a way to do this... no? If not I'd love some ideas. </p> <p>I have two repeaters and an image inside an update panel along with some AJAX dropdowns with link buttons to the left. I want to update the data inside the update panel as fast as possible as values are selected from the dropdowns. </p> <p>What do you think would be the best way to update the data? The repeaters are populated by objects, so if I could just filter the objects by some properties I could end up with the correct data. No new data from the server is needed. </p> <p>Anyone have some ideas?</p>
<p>As far as I know, it is not easy to get just Data and data-bind the repeater on the client side. But, you might want to <a href="http://dotnetslackers.com/articles/ajax/ASPNETRepeater.aspx" rel="nofollow">check this out</a>.</p>
Sum of items in a collection <p>Using LINQ to SQL, I have an Order class with a collection of OrderDetails. The Order Details has a property called LineTotal which gets Qnty x ItemPrice. </p> <p>I know how to do a new LINQ query of the database to find the order total, but as I already have the collection of OrderDetails from the DB, is there a simple method to return the sum of the LineTotal directly from the collection?</p> <p>I'd like to add the order total as a property of my Order class. I imagine I could loop through the collection and calculate the sum with a for each Order.OrderDetail, but I'm guessing there is a better way.</p>
<p>You can do LINQ to Objects and the use LINQ to calculate the totals:</p> <pre><code>decimal sumLineTotal = (from od in orderdetailscollection select od.LineTotal).Sum(); </code></pre> <p>You can also use lambda-expressions to do this, which is a bit "cleaner".</p> <pre><code>decimal sumLineTotal = orderdetailscollection.Sum(od =&gt; od.LineTotal); </code></pre> <p>You can then hook this up to your Order-class like this if you want:</p> <pre><code>Public Partial Class Order { ... Public Decimal LineTotal { get { return orderdetailscollection.Sum(od =&gt; od.LineTotal); } } } </code></pre>
ADO.NET Entity Framework tutorials <p>Does anyone know of any good tutorials on ADO.NET Entity Framework?</p> <p>There are a few useful links here at <a href="http://stackoverflow.com/questions/42826/where-to-start-with-entity-framework">Stack OverFlow</a>, and I've found one tutorial at <a href="http://dotnet-architecture-jdo.blogspot.com/2008/08/adonet-entity-framework-part.html">Jason's DotNet Architecture Blog</a>, but can anyone recommend any other good tutorials? Any tutorials available from Microsoft, either online or as part of any conference/course material?</p>
<p>Microsoft offers <a href="http://www.microsoft.com/downloads/details.aspx?FamilyID=355c80e9-fde0-4812-98b5-8a03f5874e96&amp;displaylang=en">.NET 3.5 Enhancements Training Kit</a> it contains documentation and sample code for ADO.NET EF</p>
How to save jpg image to database and then load it in Delphi using FIBplus and TImage? <p>How do I save a jpg image to database and then load it in Delphi using FIBplus and TImage?</p>
<pre><code>var S : TMemoryStream; begin S := TMemoryStream.Create; try TBlobField(AdoQuery1.FieldByName('ImageField')).SaveToStream(S); S.Position := 0; Image1.Picture.Graphic.LoadFromStream(S); finally S.Free; end; end; </code></pre> <p>if you are using JPEG images, add JPG unit to <strong>uses</strong> clause of your unit file.</p>
Does pop_back() really invalidate *all* iterators on an std::vector? <pre><code>std::vector&lt;int&gt; ints; // ... fill ints with random values for(std::vector&lt;int&gt;::iterator it = ints.begin(); it != ints.end(); ) { if(*it &lt; 10) { *it = ints.back(); ints.pop_back(); continue; } it++; } </code></pre> <p>This code is not working because when <code>pop_back()</code> is called, <code>it</code> is invalidated. But I don't find any doc talking about invalidation of iterators in <code>std::vector::pop_back()</code>.</p> <p>Do you have some links about that?</p>
<p>Here is your answer, directly from The Holy Standard:</p> <blockquote> 23.2.4.2 A vector satisfies all of the requirements of a container and of a reversible container (given in two tables in 23.1) and of a sequence, including most of the optional sequence requirements (23.1.1). </blockquote> <blockquote> 23.1.1.12 Table 68 expressiona.pop_back() return typevoid operational semantics<strong>a.erase(--a.end())</strong> containervector, list, deque </blockquote> <p>Notice that a.pop_back is equivalent to a.erase(--a.end()). Looking at vector's specifics on erase:</p> <blockquote> 23.2.4.3.3 - iterator erase(iterator position) - effects - <strong>Invalidates all the iterators and references after the point of the erase</strong> </blockquote> <p>Therefore, once you call pop_back, any iterators to the previously final element (which now no longer exists) are invalidated.</p> <p>Looking at your code, the problem is that when you remove the final element and the list becomes empty, you still increment it and walk off the end of the list.</p>
Regular expression that rejects all input? <p>Is is possible to construct a regular expression that rejects all input strings?</p>
<p>Probably this:</p> <pre><code>[^\w\W] </code></pre> <p>\w - word character (letter, digit, etc)<br /> \W - opposite of \w</p> <p>[^\w\W] - should always fail, because any character should belong to one of the character classes - \w or \W</p> <p>Another snippets:</p> <pre><code>$.^ </code></pre> <p>$ - assert position at the end of the string<br /> ^ - assert position at the start of the line<br /> . - any char </p> <pre><code>(?#it's just a comment inside of empty regex) </code></pre> <p>Empty lookahead/behind should work:</p> <pre><code>(?&lt;!) </code></pre>
How can I get Axis 1.4 to not generate several prefixes for the same XML namespace? <p>I am receiving SOAP requests from a client that uses the Axis 1.4 libraries. The requests have the following form:</p> <pre><code>&lt;soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"&gt; &lt;soapenv:Body&gt; &lt;PlaceOrderRequest xmlns="http://example.com/schema/order/request"&gt; &lt;order&gt; &lt;ns1:requestParameter xmlns:ns1="http://example.com/schema/common/request"&gt; &lt;ns1:orderingSystemWithDomain&gt; &lt;ns1:orderingSystem&gt;Internet&lt;/ns1:orderingSystem&gt; &lt;ns1:domainSign&gt;2&lt;/ns1:domainSign&gt; &lt;/ns1:orderingSystemWithDomain&gt; &lt;/ns1:requestParameter&gt; &lt;ns2:directDeliveryAddress ns2:addressType="0" ns2:index="1" xmlns:ns2="http://example.com/schema/order/request"&gt; &lt;ns3:address xmlns:ns3="http://example.com/schema/common/request"&gt; &lt;ns4:zipcode xmlns:ns4="http://example.com/schema/common"&gt;12345&lt;/ns4:zipcode&gt; &lt;ns5:city xmlns:ns5="http://example.com/schema/common"&gt;City&lt;/ns5:city&gt; &lt;ns6:street xmlns:ns6="http://example.com/schema/common"&gt;Street&lt;/ns6:street&gt; &lt;ns7:houseNum xmlns:ns7="http://example.com/schema/common"&gt;1&lt;/ns7:houseNum&gt; &lt;ns8:country xmlns:ns8="http://example.com/schema/common"&gt;XX&lt;/ns8:country&gt; &lt;/ns3:address&gt; [...] </code></pre> <p>As you can see, several prefixes are defined for the same namespace, e.g. the namespace <a href="http://example.com/schema/common">http://example.com/schema/common</a> has the prefixes ns4, ns5, ns6, ns7 and ns8. Some long requests define several hundred prefixes for the same namespace.</p> <p>This causes a problem with the <a href="http://saxon.sourceforge.net/">Saxon</a> XSLT processor, that I use to transform the requests. Saxon limits the the number of different prefixes for the same namespace to 255 and throws an exception when you define more prefixes.</p> <p>Can Axis 1.4 be configured to define smarter prefixes, so that there is only one prefix for each namespace?</p>
<p>I have the same issue. For the moment, I've worked around it by writing a BasicHandler extension, and then walking the SOAPPart myself and moving the namespace reference up to a parent node. I don't <em>like</em> this solution, but it does seem to work.</p> <p>I really hope somebody comes along and tells us what we have to do.</p> <p><strong><em>EDIT</em></strong></p> <p>This is way too complicated, and like I said, I don't like it at all, but here we go. I actually broke the functionality into a few classes (This wasn't the only manipulation that we needed to do in that project, so there were other implementations) I really hope that somebody can fix this soon. This uses dom4j to process the XML passing through the SOAP process, so you'll need dom4j to make it work.</p> <pre><code>public class XMLManipulationHandler extends BasicHandler { private static Log log = LogFactory.getLog(XMLManipulationHandler.class); private static List processingHandlers; public static void setProcessingHandlers(List handlers) { processingHandlers = handlers; } protected Document process(Document doc) { if (processingHandlers == null) { processingHandlers = new ArrayList(); processingHandlers.add(new EmptyProcessingHandler()); } log.trace(processingHandlers); treeWalk(doc.getRootElement()); return doc; } protected void treeWalk(Element element) { for (int i = 0, size = element.nodeCount(); i &lt; size; i++) { Node node = element.node(i); for (int handlerIndex = 0; handlerIndex &lt; processingHandlers.size(); handlerIndex++) { ProcessingHandler handler = (ProcessingHandler) processingHandlers.get(handlerIndex); handler.process(node); } if (node instanceof Element) { treeWalk((Element) node); } } } public void invoke(MessageContext context) throws AxisFault { if (!context.getPastPivot()) { SOAPMessage message = context.getMessage(); SOAPPart soapPart = message.getSOAPPart(); ByteArrayOutputStream baos = new ByteArrayOutputStream(); try { message.writeTo(baos); baos.flush(); baos.close(); ByteArrayInputStream bais = new ByteArrayInputStream(baos.toByteArray()); SAXReader saxReader = new SAXReader(); Document doc = saxReader.read(bais); doc = process(doc); DocumentSource ds = new DocumentSource(doc); soapPart.setContent(ds); message.saveChanges(); } catch (Exception e) { throw new AxisFault("Error Caught processing document in XMLManipulationHandler", e); } } } } public interface ProcessingHandler { public Node process(Node node); } public class NamespaceRemovalHandler implements ProcessingHandler { private static Log log = LogFactory.getLog(NamespaceRemovalHandler.class); private Namespace namespace; private String targetElement; private Set ignoreElements; public NamespaceRemovalHandler() { ignoreElements = new HashSet(); } public Node process(Node node) { if (node instanceof Element) { Element element = (Element) node; if (element.isRootElement()) { // Evidently, we never actually see the root node when we're called from // SOAP... } else { if (element.getName().equals(targetElement)) { log.trace("Found the target Element. Adding requested namespace"); Namespace already = element.getNamespaceForURI(namespace.getURI()); if (already == null) { element.add(namespace); } } else if (!ignoreElements.contains(element.getName())) { Namespace target = element.getNamespaceForURI(namespace.getURI()); if (target != null) { element.remove(target); element.setQName(new QName(element.getName(), namespace)); } } Attribute type = element.attribute("type"); if (type != null) { log.trace("Replacing type information: " + type.getText()); String typeText = type.getText(); typeText = typeText.replaceAll("ns[0-9]+", namespace.getPrefix()); type.setText(typeText); } } } return node; } public Namespace getNamespace() { return namespace; } public void setNamespace(Namespace namespace) { this.namespace = namespace; } /** * @return the targetElement */ public String getTargetElement() { return targetElement; } /** * @param targetElement the targetElement to set */ public void setTargetElement(String targetElement) { this.targetElement = targetElement; } /** * @return the ignoreElements */ public Set getIgnoreElements() { return ignoreElements; } /** * @param ignoreElements the ignoreElements to set */ public void setIgnoreElements(Set ignoreElements) { this.ignoreElements = ignoreElements; } public void addIgnoreElement(String element) { this.ignoreElements.add(element); } } </code></pre> <p>No warranty, etc, etc.</p>
How to prevent IE6 from refetching already-fetched images added via DOM manipulation <p>If you add a image to your browser's DOM, IE6 will not check its cache to see if it already downloaded the image but will, instead, re-retrieve it from the server. I have not found any combination of HTTP response headers (of the ensuing image request) to convince IE6 that it can cache the image: Cache-control, Expires, Last-modified.</p> <p>Some suggest you can return a 304 of the subsequent image requests to tell IE6 "you already got it" but I want to avoid the whole round trip to the server in the first place.</p>
<p>Maybe <a href="http://www.mister-pixel.com/index.php?Content__state=is_that_simple" rel="nofollow">this</a> will work? (is the same behaviour like hovering on links with css background image)</p>
How do I move a file (or folder) from one folder to another in TortoiseSVN? <p>I would like to move a file or folder from one place to another within the same repository without having to use Repo Browser to do it, and without creating two independent add/delete operations. Using Repo Browser works fine except that your code will be hanging in a broken state until you get any supporting changes checked in afterwards (like the .csproj file for example).</p> <p>Update: People have suggested "move" from the command line. Is there a TortoiseSVN equivalent?</p>
<p>To move a file or set of files using <code>Tortoise SVN</code>, right-click-and-drag the target files to their destination and release the right mouse button. The popup menu will have a <code>SVN move versioned files here</code> option.</p> <p><strong>Note that the destination folder must have already been added to the repository for the <code>SVN move versioned files here</code> option to appear.</strong></p>
Saving Java Object Graphs as XML file <p>What's the simplest-to-use techonlogy available to save an arbitrary Java object graph as an XML file (and to be able to rehydrate the objects later)?</p>
<p>The easiest way here is to serialize the object graph. Java 1.4 has built in support for serialization as XML.</p> <p>A solution I have used successfully is XStream (<a href="http://x-stream.github.io/)-" rel="nofollow">http://x-stream.github.io/)-</a> it's a small library that will easily allow you to serialize and deserialize to and from XML.</p> <p>The downside is you can only very limited define the resulting XML; which might not be neccessary in your case.</p>
IIS crashes when serving an ASP.NET application under heavy load. How to troubleshoot it? <p>I am working on an ASP.NET web application, it seems to be working properly when I try to debug it in Visual Studio. However when I emulate heavy load, IIS crashes without any trace -- log entry in the system journal is very generic, "The World Wide Web Publishing service terminated unexpectedly. It has done this 4 time(s)." How is it possible to get more information from IIS to troubleshoot this problem?</p>
<p>Download Debugging tools for Windows: <a href="http://www.microsoft.com/whdc/DevTools/Debugging/default.mspx" rel="nofollow">http://www.microsoft.com/whdc/DevTools/Debugging/default.mspx</a></p> <p>Debugging Tools for Windows has has a script (ADPLUS) that allows you to create dumps when a process CRASHES: <a href="http://support.microsoft.com/kb/286350" rel="nofollow">http://support.microsoft.com/kb/286350</a></p> <p>The command should be something like (if you are using IIS6):</p> <pre><code>cscript adplus.vbs -crash -pn w3wp.exe </code></pre> <p>This command will attach the debugger to the worker process. When the crash occurs it will generate a dump (a *.DMP file).</p> <p>You can open it in WinDBG (also included in the Debugging Tools for Windows). File > Open Crash dump...</p> <p>By default, WinDBG will show you (next to the command line) the thread were the process crashed.</p> <p>The first thing you need to do in WinDBG is to load the .NET Framework extensions:</p> <pre><code>.loadby sos mscorwks </code></pre> <p>then, you will display the managed callstack:</p> <pre><code>!clrstack </code></pre> <p>if the thread was not running managed code, then you'll need to check the native stack:</p> <pre><code>kpn 200 </code></pre> <p>This should give you some ideas. To continue troubleshooting I recommend you read the following article:</p> <p><a href="http://msdn.microsoft.com/en-us/library/ms954594.aspx" rel="nofollow">http://msdn.microsoft.com/en-us/library/ms954594.aspx</a></p>
Exceptions not passed correctly thru RCF (using Boost.Serialization) <p>I use RCF with boost.serialization (why use RCF's copy when we already use the original?) It works OK, but when an exception is thrown in the server, it's not passed correctly to the client. Instead, I get an RCF::SerializationException quoting an <code>archive_exception</code> saying "class name too long". When I change the protocol to BsText, the exceptions is "unregistered class". When I change the protocol to SfBinary, it works. I've registered RemoteException on both server and client like this:</p> <pre><code>BOOST_CLASS_VERSION(RCF::RemoteException, 0) BOOST_CLASS_EXPORT(RCF::RemoteException) </code></pre> <p>I even tried serializing and deserializing a <code>boost::shared_ptr&lt;RCF::RemoteException&gt;</code> in the same test, and it works.</p> <p>So how can I make RCF pass exceptions correctly without resorting to SF?</p>
<p>Here's a patch given by Jarl at <a href="http://www.codeproject.com/KB/threads/Rcf_Ipc_For_Cpp.aspx?msg=2739150#xx2730536xx" rel="nofollow">CodeProject</a>:</p> <p>In RcfServer.cpp, before the line where RcfServer::handleSession() is defined (around line 792), insert the following code:</p> <pre><code>void serialize(SerializationProtocolOut &amp; out, const RemoteException &amp; e) { serialize(out, std::auto_ptr&lt;RemoteException&gt;(new RemoteException(e))); } </code></pre> <p>And in Marshal.cpp, around line 37, replace this line:</p> <pre><code>ar &amp; boost::serialization::make_nvp("Dummy", apt.get()); </code></pre> <p>, with</p> <pre><code>T *pt = apt.get(); ar &amp; boost::serialization::make_nvp("Dummy", pt); </code></pre>
using asynchbeans instead of native jdk threads <p>are there any performance limitations using IBM's asynchbeans? my apps jvm core dumps are showing numerous occurences of orphaned threads. Im currently using native jdk unmanaged threads. Is it worth changing over to managed threads?</p>
<p>In my perspective asynchbeans are a workaround to create threads inside Websphere J2EE server. So far so good, websphere lets you create pool of "worker" threads, controlling this way the maximum number of threads, typical J2EE scalability concern. </p> <p>I had some problems using asynchbeans inside websphere on "unmanaged" threads (hacked callbacks from JMS Listener via the "outlawed" setMessageListener). I was "asking for it" not using MDBs in the first place, but I have requisites that do not feet MDB way.</p>
How do I get an auto-scrolling text display on .NET forms - e.g. for credits <p>Need to show a credits screen where I want to acknowledge the many contributors to my application. </p> <p>Want it to be an automatically scrolling box, much like the credits roll at the end of the film.</p>
<p>A easy-to-use snippet would be to make a multiline textbox. With a timer you may insert line after line and scroll to the end after that:</p> <pre><code>textbox1.SelectionStart = textbox1.Text.Length; textbox1.ScrollToCaret(); textbox1.Refresh(); </code></pre> <p>Not the best method but it's simple and working. There are also some free controls available for exactly this auto-scrolling.</p>
BufferedImage in IKVM <p>What is the best and/or easiest way to replace the missing BufferedImage functionality for a Java project I am converting to .NET with IKVM?</p> <p>I'm basically getting "cli.System.NotImplementedException: BufferedImage" exceptions when running the application, which otherwise runs fine.</p>
<p>The AWT code in IKVM is fairly easy to read and edit. I'd recommend you look for the methods that you are using that throw that exception, and then implement them. I've done this several times before with IKVM's AWT implementation and found it easy to do for background/server related functions. Its much less usable if your app is a desktop app, however.</p>
Surrogate vs. natural/business keys <p>Here we go again, the old argument still arises... </p> <p>Would we better have a business key as a primary key, or would we rather have a surrogate id (i.e. an SQL Server identity) with a unique constraint on the business key field? </p> <p>Please, provide examples or proof to support your theory.</p>
<p>Just a few reasons for maintaining surrogate keys:</p> <ol> <li><p><strong>Stability</strong>: Changing a key because of a business or natural need will negatively affect related tables. Surrogate keys rarely, if ever, need to be changed because there is nothing tied to the value.</p></li> <li><p><strong>Convention</strong>: Allows you to have a standardized Primary Key column naming convention rather than having to think about how to join tables with various names for their PKs.</p></li> <li><p><strong>Speed</strong>: Depending on the PK value and type, a surrogate key of an integer may be smaller, faster to index and search.</p></li> </ol>
Scrum Process Management - Tips, Pitfalls, Ideas <p>I've been doing scrum with a team for a while, but things seem messy for some reasons. I've been thinking on how they could be changed and have a couple of questions that I would like to raise here. </p> <p>First, what should be the role of testers, designers and non-developers as a whole in the Scrum process? If they are equal to other team members a couple of issues arise. Designers and testers usually work on a task after development is done, so they cannot adequately plan for a sprint because of this dependency. </p> <p>Second, we have deadlines. These are strict and have a lot of impact on prioritization. The end result is backlog changes in the middle of a sprint because of deadline changes, or bad results in the end of the sprint. We also have a lot of non-technical work like customer support that has to be done in the meantime and cannot be planned as it varies a lot. So I'm thinking that the team structure, culture and practices are kind of not compatible with Scrum. Scrum for me is a process management tool for teams working on the development of a single software product. </p> <p>What do you guys think about applying it in more specific and complicated scenarios? Do you have any experience to share?</p>
<p>In general testers and documenters (and other non-developes) are all equal members of a scrum team. The idea behind that is to minimize risk. </p> <p>Requiring a definition of done, which includes a potentially shipable product that's fully tested and documented, forces the project to come together at the end of each sprint.</p> <p>If testing does not start until AFTER dev. is done, what happens is that a lot of bugs are discovered after the developers are done with a task. So now you have to fix those bugs, and that's very slow and expensive both because bugs interact and because the general rule is: "The expense of fixing a bug grows exponentially with time." Bugs you catch early are cheap and easy to fix, late bugs are a nightmare.</p> <p>That is why you want testing (and documentation) to move in step with development. And right now you should be asking, how! Testing is slow, how the heck can it move in step with dev? </p> <p>The answer is automation, that is SCRUM always sits on top of XP or Agile, both demand excellent unit test coverage and TDD. Here's another gotcha to watch out for. The features developers should be the ones writing both, unit and system test. All testing automation should be done by the feature dev. team. Some places split feature dev. from automation dev. and that's bad.</p> <p>OK, so now you have great automated testing and you run it AT LEAST once a day. And obviously you practice continuous integration right? This reduces the work load of the testers by a huge amount. And that's how testing can stay in step with dev. One more thing, the testers now work on the really hard and creative stuff that's impossible or very difficult to automate, every time they find a bug that way, what ever it took to expose the bug is automated and becomes part of the daily regression tests. Phew, that's a long answer!</p> <p>Now to the second part of your question. Scrum is about discipline. Sprints are short and backlog changes during a sprint should NOT happen. Non technical work should be branched of onto a customer support team and they can do Scrum around that. You're right when you say that is sounds like your culture and practices are incompatible with scrum.</p> <p>In my experience transitioning to Scrum/Agile is a very painful, stressful process and most attempts to transition fail. One of the key's to success is a champion for Scrum/Agile in the executive team. From your description it sounds like you don't have one. </p> <p>There are costs and benefits to Scrum, but you're doing it badly you might be incurring costs with little or no benefit. If you're doing Scrum wrong and badly, you might be better off not doing Scrum at all. </p>
Add Custom TextboxCell to a DataGridView control that contains a button to open the FileDialog <p>I would like to add a DataGridViewTextBoxCell cell to a DataGridViewCell control, but as well as being able to type in the text cell as normal it must also contain a '...' button that once clicks brings up the OpenFileDialog window to allow the user to select a file. Once selected, the text cell will be populated with the full file path.</p> <p>What is the best way to go about this?</p> <p>Thanks</p>
<p><a href="http://msdn.microsoft.com/en-au/library/7tas5c80.aspx" rel="nofollow">This</a> MSDN article explains how to add a custom control to a DataGridView</p> <p>You should be able to make a UserControl that has a textbox and button on it and embed that in the DataGridView.</p>
What's the best way to build a string of delimited items in Java? <p>While working in a Java app, I recently needed to assemble a comma-delimited list of values to pass to another web service without knowing how many elements there would be in advance. The best I could come up with off the top of my head was something like this:</p> <pre><code>public String appendWithDelimiter( String original, String addition, String delimiter ) { if ( original.equals( "" ) ) { return addition; } else { return original + delimiter + addition; } } String parameterString = ""; if ( condition ) parameterString = appendWithDelimiter( parameterString, "elementName", "," ); if ( anotherCondition ) parameterString = appendWithDelimiter( parameterString, "anotherElementName", "," ); </code></pre> <p>I realize this isn't particularly efficient, since there are strings being created all over the place, but I was going for clarity more than optimization.</p> <p>In Ruby, I can do something like this instead, which feels much more elegant:</p> <pre><code>parameterArray = []; parameterArray &lt;&lt; "elementName" if condition; parameterArray &lt;&lt; "anotherElementName" if anotherCondition; parameterString = parameterArray.join(","); </code></pre> <p>But since Java lacks a join command, I couldn't figure out anything equivalent.</p> <p>So, what's the best way to do this in Java?</p>
<h3>Pre Java 8:</h3> <p>Apache's commons lang is your friend here - it provides a join method very similar to the one you refer to in Ruby: </p> <p><a href="http://commons.apache.org/proper/commons-lang/apidocs/org/apache/commons/lang3/StringUtils.html#join(java.lang.Iterable,%20char)"><code>StringUtils.join(java.lang.Iterable,char)</code></a></p> <hr> <h3>Java 8:</h3> <p>Java 8 provides joining out of the box via <code>StringJoiner</code> and <code>String.join()</code>. The snippets below show how you can use them:</p> <p><a href="https://docs.oracle.com/javase/8/docs/api/java/util/StringJoiner.html"><code>StringJoiner</code></a></p> <pre><code>StringJoiner joiner = new StringJoiner(","); joiner.add("01").add("02").add("03"); String joinedString = joiner.toString(); // "01,02,03" </code></pre> <hr> <p><a href="https://docs.oracle.com/javase/8/docs/api/java/lang/String.html#join-java.lang.CharSequence-java.lang.CharSequence...-"><code>String.join(CharSequence delimiter, CharSequence... elements))</code></a></p> <pre><code>String joinedString = String.join(" - ", "04", "05", "06"); // "04 - 05 - 06" </code></pre> <hr> <p><a href="https://docs.oracle.com/javase/8/docs/api/java/lang/String.html#join-java.lang.CharSequence-java.lang.Iterable-"><code>String.join(CharSequence delimiter, Iterable&lt;? extends CharSequence&gt; elements)</code></a></p> <pre><code>List&lt;String&gt; strings = new LinkedList&lt;&gt;(); strings.add("Java");strings.add("is"); strings.add("cool"); String message = String.join(" ", strings); //message returned is: "Java is cool" </code></pre>
Is there a way to build a Flash 9 SWF from an FLA file without using the Flash IDE? <p>Two reasons this would be useful, in case there's some other way to achieve these goals: 1) Building in the Flash IDE is really slow; I was hoping a third-party compiler would be faster. 2) It would be nice to be able to build projects on machines that don't have the Flash IDE installed. I'm familiar with other AS3 compilers that are out there, but I don't know of any that take FLA files as input.</p>
<p>To answer the original question, there is no way to compile FLAs without using the Flash IDEs. </p> <p>The only partial solution to to use a command line script that automates opening Flash Authoring and compiling the FLA. You can find one such example here:</p> <p><a href="http://www.mikechambers.com/blog/2004/02/20/flashcommand-flash-command-line-compiler-for-os-x/">http://www.mikechambers.com/blog/2004/02/20/flashcommand-flash-command-line-compiler-for-os-x/</a></p> <p>If you just need to compile ActionScript code and assets, there are a number of options (some included in this thread), including the mxmlc compiler included in the Flex SDK (provided by Adobe).</p> <p><a href="http://www.adobe.com/products/flex/">http://www.adobe.com/products/flex/</a></p> <p>Hope that helps...</p> <p>mike chambers</p> <p>[email protected]</p>
How do you reliably get an IP address via DHCP? <p>I work with embedded Linux systems that sometimes want to get their IP address from a DHCP server. The DHCP Client client we use (<a href="http://www.phystech.com/download/dhcpcd.html" rel="nofollow" title="DHCPCD">dhcpcd</a>) has limited retry logic. If our device starts up without any DHCP server available and times out, dhcpcd will exit and the device will never get an IP address until it's rebooted with a DHCP server visible/connected. I can't be the only one that has this problem. The problem doesn't even seem to be specific to embedded systems (though it's worse there). How do you handle this? Is there a more robust client available? </p>
<p>The reference dhclient from the ISC should run forever in the default configuration, and it should acquire a lease later if it doesn't get one at startup.</p> <p>I am using the out of the box dhcp client on FreeBSD, which is derived from OpenBSD's and based on the ISC's dhclient, and this is the out of the box behavior.</p> <p>See <a href="http://www.isc.org/index.pl?/sw/dhcp/" rel="nofollow">http://www.isc.org/index.pl?/sw/dhcp/</a></p>
Does Vista do stricter checking of Interface Ids in DCOM calls? (the Stub received bad Data)? <p>I hope everyone will pardon the length, and narrative fashion, of this question. I decided to describe the situation in some detail in my blog. I later saw Joel's invitation to this site, and I thought I'd paste it here to see if anyone has any insight into the situation.</p> <p>I wrote, and now support, an application that consists of a Visual Basic thick client speaking DCOM to middle tier COM+ components written in C++ using ATL. It runs in all eight of our offices. Each office hosts a back-end server that contains the COM+ application (consisting of 18 separate components) and the SQLServer. The SQLServer is typically on the same back-end server, but need not be.</p> <p>We recently migrated the back-end server in our largest office -- New York -- from a MSC cluster to a new virtual machine hosted on VMWare's ESX technology. Since the location of the COM+ application had moved from the old server to a new one with a different name, I had to redirect all the clients so that they activated the COM+ application on the new server. The procedure was old hat as I had done essentially the same thing for several of my smaller offices that had gone through similar infrastructure upgrades.</p> <p>All seemed routine and on Monday morning the entire office -- about 1,000 Windows XP workstations -- were running without incident on the new server. But then the call came from my mobile group -- there was an attorney working from home with a VPN connection that was getting a strange error after being redirected to the new server:</p> <pre> Error on FillTreeView2 - The stub received bad data. </pre> <p>Huh? I had never seen this error message before. Was it the new server? But all the workstations in the office were working fine. I told the mobile group to switch the attorney back to the old sever (which was still up), and the error disappeared. So what was the difference? Turns out this attorney was running Vista at home.</p> <p>We don't run Vista in any of our offices, but we do have some attorneys that run Vista at home (certainly some in my New York office). I do as well and I've never seen this problem. To confirm that there was an issue, I fired up my Vista laptop, pointed it to the new server, and got the same error. I pointed it back to the old server, and it worked fine. Clearly there was some problem with Vista and the components on the new server -- a problem that did not seem to affect XP clients. What could it be?</p> <p>Next stop -- the application error log on my laptop. This yielded more information on the error:</p> <pre> Source: Microsoft-Windows-RPC-Events Date: 9/2/2008 11:56:07 AM Event ID: 10 Level: Error Computer: DevLaptop Description: Application has failed to complete a COM call because an incorrect interface ID was passed as a parameter. The expected Interface ID was 00000555-0000-0010-8000-00aa006d2ea4, The Interface ID returned was 00000556-0000-0010-8000-00aa006d2ea4. User Action - Contact the application vendor for updated version of the application. </pre> <p>The interface ids provided the clue I needed to unravel the mystery. The "expected" interface id identifies MDAC's Recordset interface -- specifically version 2.1 of that interface. The "returned" interface corresponds to a later version of Recordset (version 2.5 which differs from version 2.1 by the inclusion of one additional entry at the end of the vtable -- method Save).</p> <p>Indeed my component's interfaces expose many methods that pass Recordset as an output parameter. So were they suddenly returning a later version of Recordset -- with a different interface id? It certainly appeared to be the case. And then I thought, why should it matter. The vtable looks the same to clients of the older interface. Indeed, I suspect that if we were talking about in-process COM, and not DCOM, this apparently innocuous impedance mismatch would have been silently ignored and would have caused no issues.</p> <p>Of course, when process and machine boundaries come into play, there is a proxy and a stub between the client and the server. In this case, I was using type library marshaling with the free threaded marshaller. So there were two mysteries to solve:</p> <p>Why was I returning a different interface in the output parameters from methods on my new server?</p> <p>Why did this affect only Vista clients?</p> <p>As my server software was hosted on servers at each of my eight offices, I decided to try pointing my Vista client at all of them in sequence to see which had problems with Vista and which didn't. Illuminating test. Some of the older servers still worked with Vista but the newer ones did not. Although some of the older servers were still running Windows 2000 while the newer ones were at 2003, that did not seem to be the issue.</p> <p>After comparing the dates of the component DLLs it appeared that whenever the client pointed to servers with component DLLs dated before 2003 Vista was fine. But those that had DLLs with dates after 2003 were problematic. Believe it or nor, there were no (or at least no significant) changes to the code on the server components in many years. Apparently the differing dates were simply due to recompiles of my components on my development machine(s). And it appeared that one of those recompiles happened in 2003.</p> <p>The light bulb went on. When passing Recordsets back from server to client, my ATL C++ components refer to the interface as _Recordset. This symbol comes from the type library embedded within msado15.dll. This is the line I had in the C++ code:</p> <pre> #import "c:\Program Files\Common Files\System\ADO\msado15.dll" no_namespace rename ( "EOF", "adoEOF" ) </pre> <p>Don't be deceived by the 15 in msdad15.dll. Apparently this DLL has not changed name in the long series of MDAC versions.</p> <p>When I compiled the application back in the day, the version of MDAC was 2.1. So _Recordset compiled with the 2.1 interface id and that is the interface returned by the servers running those components.</p> <p>All the client's use the COM+ application proxy that was generated (I believe) back in 1999. The type library that defines my interfaces includes the line:</p> <pre> importlib("msado21.tlb"); </pre> <p>which explains why they expect version 2.1 of Recordset in my method's output parameters. Clearly the problem was with my 2003 recompile and the fact that at that time the _Recordset symbol no longer corresponded to version 2.1. Indeed _Recordset corresponded to the 2.5 version with its distinct interface id. The solution for me was to change all references from _Recordset to Recordset21 in my C++ code. I rebuilt the components and deployed them to the new server. Voila -- the clients seemed happy again.</p> <p>In conclusion, there are two nagging questions that remain for me.</p> <p>Why does the proxy/stub infrastructure seem to behave differently with Vista clients? It appears that Vista is making stricter checks of the interface ids coming back from method parameters than is XP.</p> <p>How should I have coded this differently back in 1999 so that this would not have happened? Interfaces are supposed to be immutable and when I recompiled under a newer version of MDAC, I inadvertently changed my interface because the methods now returned a different Recordset interface as an output parameter. As far as I know, the type library back then did not have a version-specific symbol -- that is, later versions of the MDAC type libraries define Recordset21, but that symbol was not available back in the 2.1 type library.</p>
<p>When Microsoft got the security religion, DCOM (and the underlying RPC) got a lot of attention, and there definitely were changes made to close security holes that resulted in stricter marshaling. I'm suprised you see this in Vista but not in XP, but its possible that additional checks were added for Vista. Alternatively, its possible that optional strictness in XP was made mandatory in Vista.</p> <p>While I don't know enough about MDAC to know if you could have prevented this, I do know that security is one of the few areas where Microsoft is pretty willing to sacrifice backward compatibility, so it is possible you could not have done anything "better" back in 1999.</p>
VS 2003 Reports "unable to get the project file from the web server" when opening a solution from VSS <p>When attempting to open a project from source control on a newly formatted pc, I receive an "unable to get the project file from the web server" after getting the sln file from VSS. If I attempt to open the sln file from explorer, I also receive the same error.</p> <p>Any pointers or ideas?</p> <p>Thanks!</p>
<p>This question is very old so you have probably solved the issue, but just in case: Does the project file use IIS? If so then it is probably trying to read the project file from IIS and the virtual directory does not exist on the newly formatted computer. Also, there should be more detail about the message in the Output window when you open the solution which should help you find the cause. With VS2003, you also need to add your user account to the "Debugger Users" and "VS Developers" and possibly the account that is running the AppPool (possibly Network Server, ASPNET, or IUSER_xxx). This may depend on the type of authentication you are using as well. Occasionally I had to add those group permissions the the virtual directory location as well. It's been a while since I have used VS2003 with web projects though.</p>
Does Java impose any further restrictions on filenames other than the underlying operating system? <p>Does Java impose any extra restrictions of its own. Windows (upto Vista) does not allow names to include</p> <pre><code>\ / &lt; &gt; ? * : </code></pre> <p>I know HOW to validate names (a regular expression).</p> <p>I need to validate filenames entered by users. </p> <p>My application does not need to run on any other platform, though, of course, I would prefer to be platform independent!</p>
<p>No, you can escape any character that Java doesn't allow in String literals but the filesystem allows.</p> <p>Also, if trying to port an Windows app to Mac or Unix it is best to use:</p> <pre><code>File.separator </code></pre> <p>To determine the correct file separator to use on each platform.</p>
Splitting a file and its lines under Linux/bash <p>I have a rather large file (150 million lines of 10 chars). I need to split it in 150 files of 2 million lines, with each output line being alternatively the first 5 characters or the last 5 characters of the source line. I could do this in Perl rather quickly, but I was wondering if there was an easy solution using bash. Any ideas?</p>
<p>Homework? :-)</p> <p>I would think that a simple pipe with sed (to split each line into two) and split (to split things up into multiple files) would be enough.</p> <p>The man command is your friend.</p> <p><hr /></p> <p>Added after confirmation that it is not homework:</p> <p>How about</p> <pre><code>sed 's/\(.....\)\(.....\)/\1\n\2/' input_file | split -l 2000000 - out-prefix- </code></pre> <p>?</p>
Best Way to Animate Sprites in Flex <p>Is there a preferred way to handle animation when using Flex -- For instance, if I want to render a ball and bounce it around the screen?</p>
<p>If you're building a Flex application, you should use Flex's native Effect classes. They're probably already compiled into your app, since the core components use them, and you won't increase your SWF size with duplicate functionality like you would if you used another library. For simple animations, either mx.effects.AnimateProperty or mx.effects.Tween should work well.</p> <p>If you're working on a regular ActionScript project (without the Flex framework), then I concur with the answer given by Marc Hughes. However, if that's the case, then please don't say you're using Flex because that implies that you're using the Flex framework and it can be very confusing. If you mean Flex Builder, then please use the full name to avoid potential misunderstandings.</p>
Struts 1.3: forward outside the application context? <p>Struts 1.3 application. Main website is NOT served by struts/Java. I need to forward the result of a struts action to a page in the website, that is outside of the struts context. Currently, I forward to a JSP in context and use a meta-refresh to forward to the real location. That seems kinda sucky. Is there a better way?</p>
<p>You can't "forward", in the strict sense. Just call sendRedirect() on the HttpServletResponse object in your Action class's execute() method. and, then 'return null'.</p> <p>alternately, either call setModule on the ActionForward object (that you are going to return) or set the path to an absolute URI</p>
Missing classes in WMI when non-admin <p>I'd like to be able to see <code>Win32_PhysicalMedia</code> information when logged in as a <em>Limited User</em> in Windows XP (no admin rights). It works ok when logged in as <em>Admin</em>, <code>WMIDiag</code> has just given a clean bill of health, and <code>Win32_DiskDrive</code> class produces information correctly, but <code>Win32_PhysicalMedia</code> produces a count of 0 for this code</p> <pre><code>set WMI = GetObject("WinMgtmts:/root/cimv2") set objs = WMI.InstancesOf("Win32_PhysicalMedia") wscript.echo objs.count </code></pre> <p>Alternatively, if the hard disk serial number as found on the <code>SerialNumber</code> property of the physical drives is available in another class which I can read as a limited user please let me know. I am not attempting to write to any property with WMI, but I can't read this when running as a <em>Limited User</em>. Interestingly, <code>DiskDrive</code> misses out the <code>Signature</code> property, which would do for my application when run as a <em>Limited User</em> but is present when run from an <em>Admin</em> account.</p>
<p>WMI does not give limited users this information.</p> <p>If you can access Win32 functions from your language, you can call <a href="http://msdn.microsoft.com/en-us/library/aa364993(VS.85).aspx" rel="nofollow">GetVolumeInformation</a>.</p>
How to make Emacs terminal colors the same as Emacs GUI colors? <p>I program with Emacs on Ubuntu (Hardy Heron at the moment), and I like the default text coloration in the Emacs GUI. However, the default text coloration when Emacs is run in the terminal is different and garish.</p> <p>How do I make the colors in the terminal match the colors in the GUI?</p>
<p>You don't have to be stuck to your terminal's default 16 (or fewer) colours. Modern terminals will support 256 colours (which will get you pretty close to your GUI look).</p> <p>Unfortunately, getting your terminal to support 256 colours is the tricky part, and varies from term to term. <a href="http://www.xvx.ca/~awg/emacs-colors-howto.txt">This page</a> helped me out a lot (but it <em>is</em> out of date; I've definitely gotten 256 colours working in gnome-terminal and xfce4-terminal; but you may have to build them from source.) </p> <p>Once you've got your terminal happily using 256 colours, the magic invocation is setting your terminal type to "xterm-256color" before you invoke emacs, e.g.:</p> <pre><code>env TERM=xterm-256color emacs -nw </code></pre> <p>Or, you can set TERM in your <code>.bashrc</code> file:</p> <pre><code>export TERM=xterm-256color </code></pre> <p>You can check if it's worked in emacs by doing <code>M-x list-colors-display</code>, which will show you either 16, or all 256 glorious colours.</p> <p>If it works, then look at <code>color-theme</code> like someone else suggested.</p> <p>(You'll probably get frustrated at some point; god knows I do every time I try to do something similar. But stick with it; it's worth it.)</p>
Game Programming and Event Handlers <p>I haven't programmed games for about 10 years (My last experience was DJGPP + Allegro), but I thought I'd check out XNA over the weekend to see how it was shaping up.</p> <p>I am fairly impressed, however as I continue to piece together a game engine, I have a (probably) basic question.</p> <p>How much should you rely on C#'s Delegates and Events to drive the game? As an application programmer, I use delegates and events heavily, but I don't know if there is a significant overhead to doing so.</p> <p>In my game engine, I have designed a "chase cam" of sorts, that can be attached to an object and then recalculates its position relative to the object. When the object moves, there are two ways to update the chase cam.</p> <ul> <li>Have an "UpdateCameras()" method in the main game loop.</li> <li>Use an event handler, and have the chase cam subscribe to object.OnMoved.</li> </ul> <p>I'm using the latter, because it allows me to chain events together and nicely automate large parts of the engine. Suddenly, what would be huge and complex get dropped down to a handful of 3-5 line event handlers...Its a beauty.</p> <p>However, if event handlers firing every nanosecond turn out to be a major slowdown, I'll remove it and go with the loop approach.</p> <p>Ideas?</p>
<p>If you were to think of an event as a subscriber list, in your code all you are doing is registering a subscriber. The number of instructions needed to achieve that is likely to be minimal at the CLR level.</p> <p>If you want your code to be generic or dynamic, then you're need to check if something is subscribed prior to calling an event. The event/delegate mechanism of C# and .NET provides this to you at very little cost (in terms of CPU).</p> <p>If you're really concerned about every clock cycle, you'd never write generic/dynamic game logic. It's a trade off between maintainable/configurable code and outright speed.</p> <p>Written well, I'd favour events/delegates until I could prove it is an issue.</p> <p>The only way you'll truly know if it is an issue for you is by profiling your code -- which you should do anyway for any game development!</p>
Draining Standard Error in Java <p>When launching a process from Java, both stderr and stdout can block on output if I don't read from the pipes. Currently I have a thread that pro-actively reads from one and the main thread blocks on the other.</p> <p>Is there an easy way to join the two streams or otherwise cause the subprocess to continue while not losing the data in stderr? </p>
<p>Set the redirectErrorStream property on ProcessBuilder to send stderr output to stdout:</p> <pre><code>ProcessBuilder builder = new ProcessBuilder(command); builder.redirectErrorStream(true); </code></pre> <p>You should then create a thread to deal with the process stream, something like the following:</p> <pre><code>Process p = builder.start(); InputHandler outHandler = new InputHandler(p.getInputStream()); </code></pre> <p>Where InputHandler is defined as:</p> <pre><code>private static class InputHandler extends Thread { private final InputStream is; private final ByteArrayOutputStream os; public InputHandler(InputStream input) { this.is = input; this.os = new ByteArrayOutputStream(); } public void run() { try { int c; while ((c = is.read()) != -1) { os.write(c); } } catch (Throwable t) { throw new IllegalStateException(t); } } public String getOutput() { try { os.flush(); } catch (Throwable t) { throw new IllegalStateException(t); } return os.toString(); } } </code></pre> <p>Alternatively, just create two InputHandlers for the InputStream and ErrorStream. Knowing that the program will block if you don't read them is 90% of the battle :)</p>
How does one record audio from a Javascript based webapp? <p>I'm trying to write a web-app that records WAV files (eg: from the user's microphone). I know Javascript alone can not do this, but I'm interested in the least proprietary method to augment my Javascript with. My targeted browsers are Firefox for PC and Mac (so no ActiveX). Please share your experiences with this. I gather it can be done with Flash (but not as a WAV formated file). I gather it can be done with Java (but not without code-signing). Are these the only options?</p> <p><a href="http://stackoverflow.com/questions/64010/how-does-one-record-audio-from-a-javascript-based-webapp#64159">@dominic-mazzoni</a> I'd like to record the file as a WAV because because the purpose of the webapp will be to assemble a library of <em>good</em> quality short soundbites. I estimate upload will be 50 MB, which is well worth it for the quality. The app will only be used on our intranet.</p> <p>UPDATE: There's now an alternate solution thanks to JetPack's upcoming Audio API: See <a href="https://wiki.mozilla.org/Labs/Jetpack/JEP/18">https://wiki.mozilla.org/Labs/Jetpack/JEP/18</a></p>
<p>This is an old thread, but the issue remains relevant. It should be noted that there is a way to record audio to the server in Flash without a proprietary back-end. Here's an example project to get you started:</p> <p><a href="https://code.google.com/p/wami-recorder/">https://code.google.com/p/wami-recorder/</a></p>
Is there good .sol editor for Flash Player 9 Local Shared Objects? Can we build one? <p>There's plenty of them out there but none of them do what I would like them to do.</p> <p>Most of them crash when opening a file or simply corrupt the data. Many don't run at all. It seems to me that most were written 3-4 years ago for AS2 .sols and no longer work with FP9/AS3 sols. I'd attempt to write my own using AIR but I can't find a new spec of the byte format.</p> <p>There's an explanation of the file format here: <a href="http://sourceforge.net/docman/display_doc.php?docid=27026&amp;group_id=131628">http://sourceforge.net/docman/display_doc.php?docid=27026&amp;group_id=131628</a></p> <p>and another here: <a href="http://sourceforge.net/docman/display_doc.php?docid=27026&amp;group_id=131628">http://sourceforge.net/docman/display_doc.php?docid=27026&amp;group_id=131628</a></p> <p>but it looks as though both of these docs are a good 4 years old (pre-FP9) and as I'm not skilled or experienced in file formats, writing a new one, especially without an updated spec, is seeming like less and less of a viable option. </p> <p>Ideally I'd like one that can not only read the .sol, but edit and save new values also.</p> <p>Thanks!</p>
<p>Use <a href="http://blog.coursevector.com/minerva">minerva</a>. I've tried it, it works with every .sol I open it with.</p>
How do I call MySQL stored procedures from Perl? <p>How do I call MySQL stored procedures from Perl? Stored procedure functionality is fairly new to MySQL and the MySQL modules for Perl don't seem to have caught up yet.</p>
<p>MySQL stored procedures that produce datasets need you to use Perl DBD::mysql 4.001 or later. (<a href="http://www.perlmonks.org/?node_id=609098" rel="nofollow">http://www.perlmonks.org/?node_id=609098</a>)</p> <p>Below is a test program that will work in the newer version:</p> <pre><code>mysql&gt; delimiter // mysql&gt; create procedure Foo(x int) -&gt; begin -&gt; select x*2; -&gt; end -&gt; // perl -e 'use DBI; DBI-&gt;connect("dbi:mysql:database=bonk", "root", "")-&gt;prepare("call Foo(?)")-&gt;execute(21)' </code></pre> <p>But if you have too old a version of DBD::mysql, you get results like this:</p> <pre><code>DBD::mysql::st execute failed: PROCEDURE bonk.Foo can't return a result set in the given context at -e line 1. </code></pre> <p>You can install the newest DBD using CPAN.</p>
How to copy text from Emacs to another application on Linux <p>When I yank text in Emacs 22.1.1 (in its own window on X, in KDE, on Kubuntu), I can't paste it anywhere else.</p>
<p>Let's be careful with our definitions here</p> <ul> <li>An <em>Emacs copy</em> is the command <code>kill-ring-save</code> (usually bound to <kbd>M-w</kbd>).</li> <li>A <em>system copy</em> is what you typically get from pressing <kbd>C-c</kbd> (or choosing "Edit->Copy" in a application window).</li> <li>An <em>X copy</em> is "physically" highlighting text with the mouse cursor.</li> <li>An <em>Emacs paste</em> is the command <code>yank</code> (usually bound to <kbd>C-y</kbd>).</li> <li>A <em>system paste</em> is what you typically get from pressing <kbd>C-v</kbd> (or choosing "Edit-Paste" in an application window).</li> <li>An <em>X paste</em> is pressing the "center mouse button" (simulated by pressing the left and right mouse buttons together).</li> </ul> <p>In my case (on GNOME):</p> <ul> <li>Both Emacs and system copy usually work with X paste.</li> <li>X copy usually works with Emacs paste.</li> <li><p>To make system copy work with Emacs paste and Emacs copy work with system paste, you need to add <code>(setq x-select-enable-clipboard t)</code> to your <code>.emacs</code>. Or try </p> <pre><code>META-X set-variable RET x-select-enable-clipboard RET t </code></pre></li> </ul> <p>I think this is pretty standard modern Unix behavior.</p> <p>It's also important to note (though you say you're using Emacs in a separate window) that when Emacs is running in a console, it is completely divorced from the system and X clipboards: cut and paste in that case is mediated by the terminal. For example, "Edit->Paste" in your terminal window should act exactly as if you typed the text from the clipboard into the Emacs buffer. </p>
Using Apache mod_rewrite to remove sub-directories from URL <p>I'm managing an instance of Wordpress where the URLs are in the following format:</p> <pre> http://www.example.com/example-category/blog-post-permalink/ </pre> <p>The blog author did an inconsistent job of adding categories to posts, so while some of them had legitimate categories in their URLS, at least half are "uncategorised".</p> <p>I can easily change Wordpress to render the URL without the category name (e.g., <a href="http://www.example.com/blog-post-permalink/" rel="nofollow">http://www.example.com/blog-post-permalink/</a>), but I'd like to create a mod_rewrite rule to automatically redirect any requests for the previous format to the new, cleaner one.</p> <p>How can I use a mod_rewrite recipe to handle this, taking into account that I want to honor requests for the real WordPress directories that are in my webroot?</p>
<p>Something as simple as:</p> <pre><code>RewriteRule ^/[^/]+/([^/]+)/?$ /$2 [R] </code></pre> <p>Perhaps would do it? </p> <p>That simple redirects <code>/foo/bar/</code> to <code>/bar</code>.</p>
Is there any AIM API for PHP that would allow a user to set their status from a website? <p>Some users on a site I have been working on have requested the ability to allow the server to set their aim status when they are listening to a song though our flash music player. I looked at the AIM developer pages, but didn't see any API for PHP.</p> <p>I would be more than willing to write my own, but first I want to make sure that it will be possible to update a user's status from a website, and secondly a library doesn't already exist.</p> <p>What would you suggest?</p>
<p>You probably want the <a href="http://dev.aol.com/aim/web/serverapi_reference" rel="nofollow">Web AIM Server API</a>; it looks like you can set the AIM status through authenticated HTTP calls, among many other things. Should be language-independent; in PHP you could use the cURL library, for instance. I've never used it personally, though.</p>
How can I write an iPhone app entirely in JavaScript without making it just a web app? <p>I don't want to take the time to learn Obj-C. I've spent 7+ years doing web application programming. Shouldn't there be a way to use the WebView and just write the whole app in javascript, pulling the files right from the resources of the project?</p>
<p>I found the answer after searching around. Here's what I have done:</p> <ol> <li><p>Create a new project in XCode. I think I used the view-based app.</p></li> <li><p>Drag a WebView object onto your interface and resize.</p></li> <li><p>Inside of your WebViewController.m (or similarly named file, depending on the name of your view), in the viewDidLoad method:</p> <pre>NSString *filePath = [[NSBundle mainBundle] pathForResource:@"index" ofType:@"html"]; NSData *htmlData = [NSData dataWithContentsOfFile:filePath]; if (htmlData) { NSBundle *bundle = [NSBundle mainBundle]; NSString *path = [bundle bundlePath]; NSString *fullPath = [NSBundle pathForResource:@"index" ofType:@"html" inDirectory:path]; [webView loadRequest:[NSURLRequest requestWithURL:[NSURL fileURLWithPath:fullPath]]]; }</pre></li> <li><p>Now any files you have added as resources to the project are available for use in your web app. I've got an index.html file including javascript and css and image files with no problems. The only limitation I've found so far is that I can't create new folders so all the files clutter up the resources folder.</p></li> <li><p>Trick: make sure you've added the file as a resource in XCode or the file won't be available. I've been adding an empty file in XCode, then dragging my file on top in the finder. That's been working for me.</p></li> </ol> <p>Note: I realize that Obj-C must not be that hard to learn. But since I already have this app existing in JS and I know it works in Safari this is a much faster dev cycle for me. Some day I'm sure I'll have to break down and learn Obj-C.</p> <p>A few other resources I found helpful:</p> <p>Calling Obj-C from javascript: <a href="http://tetontech.wordpress.com/2008/08/14/calling-objective-c-from-javascript-in-an-iphone-uiwebview/">calling objective-c from javascript</a></p> <p>Calling javascript from Obj-C: <a href="http://dominiek.com/articles/2008/7/19/iphone-app-development-for-web-hackers">iphone app development for web hackers</a></p> <p>Reading files from application bundle: <a href="http://iphoneincubator.com/blog/tag/uiwebview">uiwebview</a></p>
Explode that doesn't return empty strings? <p>PHP's explode function returns an array of strings split on some provided substring. It will return empty strings like this:</p> <pre><code>var_dump(explode('/', '1/2//3/')); array(5) { [0]=&gt; string(1) "1" [1]=&gt; string(1) "2" [2]=&gt; string(0) "" [3]=&gt; string(1) "3" [4]=&gt; string(0) "" } </code></pre> <p>Is there some different function or option or anything that would return everything <em>except</em> the empty strings?</p> <pre><code>var_dump(different_explode('/', '1/2//3/')); array(3) { [0]=&gt; string(1) "1" [1]=&gt; string(1) "2" [2]=&gt; string(1) "3" } </code></pre>
<p>Try <a href="http://php.net/preg_split">preg_split</a>.</p> <p><code>$exploded = preg_split('@/@', '1/2//3/', NULL, PREG_SPLIT_NO_EMPTY);</code></p>
Parsing exact dates in C# shouldn't force you to create an IFormatProvider <p>Someone please correct me if I'm wrong, but parsing a yyyy/MM/dd (or other specific formats) dates in C# <strong>should</strong> be as easy as </p> <pre><code>DateTime.ParseExact(theDate, "yyyy/MM/dd"); </code></pre> <p>but no, C# forces you to create an IFormatProvider.</p> <p>Is there an app.config friendly way of setting this so I don't need to do this each time?</p> <pre><code>DateTime.ParseExact(theDate, "yyyy/MM/dd", new CultureInfo("en-CA", true)); </code></pre>
<p>The IFormatProvider argument can be null.</p>
Should HTML co-exist with code? <p>In a web application, is it acceptable to use HTML in your code (non-scripted languages, Java, .NET)?</p> <p>There are two major sub questions:</p> <ol> <li>Should you use code to print HTML, or otherwise directly create HTML that is displayed?</li> <li>Should you mix code within your HTML pages?</li> </ol>
<p>Generally, it's better to keep presentation (HTML) separate from logic ("back-end" code). Your code is decoupled and easier to maintain this way.</p>
Why aren't my breakpoints working? <p>I have breakpoints set but Xcode appears to ignore them.</p>
<p>First of all, I agree 100% with the earlier folks that said turn <strong>OFF</strong> <code>Load Symbols Lazily</code>.</p> <p>I have two more things to add.</p> <p>(My first suggestion sounds obvious, but the first time someone suggested it to me, my reaction went along these lines: "come on, please, you really think I wouldn't know better...... oh.")</p> <ol> <li><p>Make sure you haven't accidentally set "Active Build Configuration" to "Release."</p></li> <li><p>Under "Targets" in the graphical tree display of your project, right click on your Target and do "Get Info." Look for a property named "Generate Debug Symbols" (or similar) and make sure this is CHECKED (aka ON). Also, you might try finding (also in Target >> Get Info) a property called "Debug Information Format" and setting it to "Dwarf with dsym file."</p></li> </ol> <p>There are a number of other properties under Target >> Get Info that might affect you. Look for things like optimizing or compressing code and turn that stuff OFF (I assume you are working in a debug mode, so that this is not bad advice). Also, look for things like stripping symbols and make sure that is also OFF. For example, "Strip Linked Product" should be set to "No" for the Debug target.</p>
how to implement shortcut key combination of CTRL or SHIFT + <letter> through javascript? <p>ASP.NET 2.0 web application, how to implement shortcut key combination of CTRL + , preferably through javascript, to make web application ergonomically better? How to capture multiple-key keyboard events through javascript?</p>
<p>The short answer is that you use Javascript to capture a <strong>keydown</strong> event and use that event to fire off a function. Relevant articles:</p> <ul> <li><a href="http://www.openjs.com/scripts/events/keyboard_shortcuts/">http://www.openjs.com/scripts/events/keyboard_shortcuts/</a></li> <li><a href="http://udayms.wordpress.com/2006/03/17/ajax-key-disabling-using-javascript/">http://udayms.wordpress.com/2006/03/17/ajax-key-disabling-using-javascript/</a></li> <li><a href="http://protocolsofmatrix.blogspot.com/2007/09/javascript-keycode-reference-table-for.html">http://protocolsofmatrix.blogspot.com/2007/09/javascript-keycode-reference-table-for.html</a></li> <li><a href="http://www.quirksmode.org/js/keys.html">http://www.quirksmode.org/js/keys.html</a></li> </ul> <p>If you're using the <a href="http://jquery.com/">jQuery library</a>, I'd suggest you look at the <a href="http://plugins.jquery.com/project/hotkeys">HotKeys plugin</a> for a cross-browser solution.</p> <blockquote> <blockquote> <p>I know this is not answering the orginal question, but here is my advice: Don't Use Key Combination Shortcuts In A Web Application!</p> <p>Why? Because it might break de the usability, instead of increasing it. While it's generally accepted that "one-key shortcut" are not used in common browsers (Opera remove it as default from its last major version), you cannot figure out what are, nor what will be, the key combination shortcuts used by various browser.</p> </blockquote> </blockquote> <p>Gizmo makes a good point. There's some information about commonly-used accesskey assignments at <a href="http://www.clagnut.com/blog/193/">http://www.clagnut.com/blog/193/</a>. </p> <p>If you do change the accesskeys, here are some articles with good suggestions for how to do it well:</p> <ul> <li><a href="http://www.alistapart.com/articles/accesskeys/">Accesskeys: Unlocking Hidden Navigation</a></li> <li><a href="http://www.cs.tut.fi/~jkorpela/forms/accesskey.html">Using accesskey attribute in HTML forms and links </a></li> </ul> <p>And you may find this page of <a href="http://www.accessfirefox.org/Firefox_Keyboard_and_Mouse_Shortcuts.html">Firefox's default Keyboard and Mouse Shortcuts</a> useful (<a href="http://lesliefranke.com/files/reference/firefoxcheatsheet.html">Another version</a> of same information). Keyboard shortcuts for <a href="http://www.keyxl.com/aaacd98/28/Microsoft-Internet-Explorer-7-Browser-keyboard-shortcuts.htm">Internet Explorer 7</a> and <a href="http://www.keyxl.com/aaa29c1/29/Microsoft-Internet-Explorer-6-Browser-keyboard-shortcuts.htm">Internet Explorer 6</a>. Keyboard shortcuts <a href="http://www.keyxl.com/aaade74/97/Opera-web-browser-keyboard-shortcuts.htm">for Opera</a> <a href="http://www.keyxl.com/aaa8ceb/93/Apple-Safari-web-browser-keyboard-shortcuts.htm">and Safari</a>.</p> <p>You're more likely to run into problems with <a href="http://www.keyxl.com/aaadc6c/406/jaws-keyboard-shortcuts.htm">JAWS</a> or other screen readers that add more keyboard shortcuts.</p>
Best way to convert text files between character sets? <p>What is the fastest, easiest tool or method to convert text files between character sets?</p> <p>Specifically, I need to convert from UTF-8 to ISO-8859-15 and vice versa.</p> <p>Everything goes: one-liners in your favorite scripting language, command-line tools or other utilities for OS, web sites, etc.</p> <h2>Best solutions so far:</h2> <p>On Linux/UNIX/OS X/cygwin:</p> <ul> <li><p>Gnu <a href="http://www.gnu.org/software/libiconv/documentation/libiconv/iconv.1.html">iconv</a> suggested by <a href="http://stackoverflow.com/questions/64860/best-way-to-convert-text-files-between-character-sets#64889">Troels Arvin</a> is best used <strong>as a filter</strong>. It seems to be universally available. Example:</p> <pre><code>$ iconv -f UTF-8 -t ISO-8859-15 in.txt &gt; out.txt </code></pre> <p>As pointed out by <a href="http://stackoverflow.com/questions/64860/best-way-to-convert-text-files-between-character-sets#64991">Ben</a>, there is an <a href="http://www.iconv.com/iconv.htm">online converter using iconv</a>.</p></li> <li><p>Gnu <a href="http://www.gnu.org/software/recode/recode.html">recode</a> (<a href="http://www.informatik.uni-hamburg.de/RZ/software/gnu/utilities/recode_toc.html">manual</a>) suggested by <a href="http://stackoverflow.com/questions/64860/best-way-to-convert-text-files-between-character-sets#64888">Cheekysoft</a> will convert <strong>one or several files in-place</strong>. Example:</p> <pre><code>$ recode UTF8..ISO-8859-15 in.txt </code></pre> <p>This one uses shorter aliases:</p> <pre><code>$ recode utf8..l9 in.txt </code></pre> <p>Recode also supports <em>surfaces</em> which can be used to convert between different line ending types and encodings:</p> <p>Convert newlines from LF (Unix) to CR-LF (DOS):</p> <pre><code>$ recode ../CR-LF in.txt </code></pre> <p>Base64 encode file:</p> <pre><code>$ recode ../Base64 in.txt </code></pre> <p>You can also combine them.</p> <p>Convert a Base64 encoded UTF8 file with Unix line endings to Base64 encoded Latin 1 file with Dos line endings:</p> <pre><code>$ recode utf8/Base64..l1/CR-LF/Base64 file.txt </code></pre></li> </ul> <p>On Windows with <a href="http://www.microsoft.com/windowsserver2003/technologies/management/powershell/default.mspx">Powershell</a> (<a href="http://stackoverflow.com/questions/64860/best-way-to-convert-text-files-between-character-sets#64937">Jay Bazuzi</a>): </p> <ul> <li><p><code>PS C:\&gt; gc -en utf8 in.txt | Out-File -en ascii out.txt</code></p> <p>(No ISO-8859-15 support though; it says that supported charsets are unicode, utf7, utf8, utf32, ascii, bigendianunicode, default, and oem.)</p></li> </ul> <h2>Edit</h2> <p>Do you mean iso-8859-1 support? Using "String" does this e.g. for vice versa</p> <pre><code>gc -en string in.txt | Out-File -en utf8 out.txt </code></pre> <p>Note: The possible enumeration values are "Unknown, String, Unicode, Byte, BigEndianUnicode, UTF8, UTF7, Ascii".</p> <ul> <li>CsCvt - <a href="http://www.cscvt.de">Kalytta's Character Set Converter</a> is another great command line based conversion tool for Windows.</li> </ul>
<p><a href="http://linux.die.net/man/1/iconv">Stand-alone utility</a> approach</p> <pre><code>iconv -f UTF-8 -t ISO-8859-1 in.txt &gt; out.txt </code></pre> <pre> -f ENCODING the encoding of the input -t ENCODING the encoding of the output </pre>
Is GCJ (GNU Compiler for Java) a viable tool for publishing a webapp? <p>Is it really viable to use GCJ to publish server-side applications? Webapps? </p> <p>My boss is convinced that compiling our (<strong><em>my</em></strong>) webapp into a binary executable is a brilliant idea. (Then again, he likes nice, small simple things with blinky lights that he can understand.) He instinctively sees no issues with this, while I only see an endless series of problems and degradations. Once I start talking to him about the complexity of our platform, and more in depth specifics of byte code, JVMs, libraries, differences between operating systems, processor architectures, etc...well...his eyes glaze over, he smiles and he has made it clear he thinks I'm being childishly resistive.</p> <p>Why does he want a single magic executable? He sees a couple of "benefits":</p> <ul> <li>If it is a binary executable, then it is hard to reverse engineer and circumvent any licensing. Management lives in constant fear that this is happening, even though we sell into larger corporates who generally do not do cheat with server software. </li> <li>There is that vision of downloading this magic executable, running it, and everything works. (No more sending me out to do customer installations, which is not that frequent.)</li> </ul> <p>So, I've done my obligatory 20 minutes of googling, and now I am here. </p> <p>A bit of background on my application: </p> <p><strong>What it is made from:</strong></p> <ul> <li>Java 6 (Sun's JVM)</li> <li>AspectJ 1.6</li> <li>Tomcat 6</li> <li>Hibernate 3</li> <li>Spring 2</li> <li>another two dozen supporting jar files</li> </ul> <p><strong>What it does</strong></p> <ul> <li>A streaming media CMS</li> <li>Performance sensitive</li> <li>Deployed on Linux, Solaris, Windows (and developed on a Mac)</li> </ul> <p>As you can probably gather, I'm highly skeptical of this <em>"compiling Java to native code"</em> thing. It sound like where Mono (VB on Linux) was back in 2000. But am I being overly pessimistic? Is it viable? Should I actually spend the time (days if not weeks) to try this out?</p> <p>There is one other similar thread (<a href="http://stackoverflow.com/questions/53845/java-compiler-options-to-produce-exe-files">Java Compiler Options to produce .exe files</a>) but it is a bit too simple, the links dated, and not really geared towards a server-side question.</p> <p>Your informed opinions will be highly cherished, my dear SOpedians! TIA!</p>
<p>I don't know about GCJ, but my company uses Excelsior JET with success. We haven't done it with a webapp (yet) but it should be able to handle anything that the Sun JRE can. In fact JET is a Sun-certified Java implementation.</p>
Is there a way to add global error handler in a visual basic 6.0 application? <p>VB 6.0 does not have any global handler.To catch runtime errors,we need to add a handler in each method where we feel an error can occur.But, still some places might be left out.So,we end up getting runtime errors.Adding error handler in all the methods of an application,the only way?</p>
<p>No there is no way to add a global error handler in VB6. However, you do not need to add an error handler in every method. You only really need to add an error handler in every event handler. E.g. Every click event,load event, etc</p>
NHibernate, Sum Query <p>If i have a simple named query defined, the preforms a count function, on one column:</p> <pre><code> &lt;query name="Activity.GetAllMiles"&gt; &lt;![CDATA[ select sum(Distance) from Activity ]]&gt; &lt;/query&gt; </code></pre> <p>How do I get the result of a sum or any query that dont return of one the mapped entities, with NHibernate using Either IQuery or ICriteria?</p> <p>Here is my attempt (im unable to test it right now), would this work?</p> <pre><code> public decimal Find(String namedQuery) { using (ISession session = NHibernateHelper.OpenSession()) { IQuery query = session.GetNamedQuery(namedQuery); return query.UniqueResult&lt;decimal&gt;(); } } </code></pre>
<p>As an indirect answer to your question, here is how I do it without a named query.</p> <pre><code> var session = GetSession(); var criteria = session.CreateCriteria(typeof(Order)) .Add(Restrictions.Eq("Product", product)) .SetProjection(Projections.CountDistinct("Price")); return (int) criteria.UniqueResult(); </code></pre>
Java Open Source Workflow Engines <p>What is the best open source java workflow framework (e.g. OSWorkflow, jBPM, XFlow etc.)?</p>
<p><a href="http://eprints.qut.edu.au/archive/00014320/" rel="nofollow">Here's an article</a> that compares kBPM, OpenWFE, and Enhydra Shark that looks like it has some good, thorough info.</p>
How to get name associated with open HANDLE <p>What's the easiest way to get the filename associated with an open HANDLE in Win32?</p>
<p>There is a correct (although undocumented) way to do this on Windows XP <strong>which also works with directories</strong> -- the same method <a href="http://msdn.microsoft.com/en-us/library/aa364962.aspx">GetFinalPathNameByHandle</a> uses on Windows Vista and later.</p> <p>Here are the eneded declarations. Some of these are already in <code>WInternl.h</code> and <code>MountMgr.h</code> but I just put them here anyway:</p> <pre><code>#include "stdafx.h" #include &lt;Windows.h&gt; #include &lt;assert.h&gt; enum OBJECT_INFORMATION_CLASS { ObjectNameInformation = 1 }; enum FILE_INFORMATION_CLASS { FileNameInformation = 9 }; struct FILE_NAME_INFORMATION { ULONG FileNameLength; WCHAR FileName[1]; }; struct IO_STATUS_BLOCK { PVOID Dummy; ULONG_PTR Information; }; struct UNICODE_STRING { USHORT Length; USHORT MaximumLength; PWSTR Buffer; }; struct MOUNTMGR_TARGET_NAME { USHORT DeviceNameLength; WCHAR DeviceName[1]; }; struct MOUNTMGR_VOLUME_PATHS { ULONG MultiSzLength; WCHAR MultiSz[1]; }; extern "C" NTSYSAPI NTSTATUS NTAPI NtQueryObject(IN HANDLE Handle OPTIONAL, IN OBJECT_INFORMATION_CLASS ObjectInformationClass, OUT PVOID ObjectInformation OPTIONAL, IN ULONG ObjectInformationLength, OUT PULONG ReturnLength OPTIONAL); extern "C" NTSYSAPI NTSTATUS NTAPI NtQueryInformationFile(IN HANDLE FileHandle, OUT PIO_STATUS_BLOCK IoStatusBlock, OUT PVOID FileInformation, IN ULONG Length, IN FILE_INFORMATION_CLASS FileInformationClass); #define MOUNTMGRCONTROLTYPE ((ULONG) 'm') #define IOCTL_MOUNTMGR_QUERY_DOS_VOLUME_PATH \ CTL_CODE(MOUNTMGRCONTROLTYPE, 12, METHOD_BUFFERED, FILE_ANY_ACCESS) union ANY_BUFFER { MOUNTMGR_TARGET_NAME TargetName; MOUNTMGR_VOLUME_PATHS TargetPaths; FILE_NAME_INFORMATION NameInfo; UNICODE_STRING UnicodeString; WCHAR Buffer[USHRT_MAX]; }; </code></pre> <p>Here's the core function:</p> <pre><code>LPWSTR GetFilePath(HANDLE hFile) { static ANY_BUFFER nameFull, nameRel, nameMnt; ULONG returnedLength; IO_STATUS_BLOCK iosb; NTSTATUS status; status = NtQueryObject(hFile, ObjectNameInformation, nameFull.Buffer, sizeof(nameFull.Buffer), &amp;returnedLength); assert(status == 0); status = NtQueryInformationFile(hFile, &amp;iosb, nameRel.Buffer, sizeof(nameRel.Buffer), FileNameInformation); assert(status == 0); //I'm not sure how this works with network paths... assert(nameFull.UnicodeString.Length &gt;= nameRel.NameInfo.FileNameLength); nameMnt.TargetName.DeviceNameLength = (USHORT)( nameFull.UnicodeString.Length - nameRel.NameInfo.FileNameLength); wcsncpy(nameMnt.TargetName.DeviceName, nameFull.UnicodeString.Buffer, nameMnt.TargetName.DeviceNameLength / sizeof(WCHAR)); HANDLE hMountPointMgr = CreateFile(_T("\\\\.\\MountPointManager"), 0, FILE_SHARE_READ | FILE_SHARE_WRITE | FILE_SHARE_DELETE, NULL, OPEN_EXISTING, 0, NULL); __try { DWORD bytesReturned; BOOL success = DeviceIoControl(hMountPointMgr, IOCTL_MOUNTMGR_QUERY_DOS_VOLUME_PATH, &amp;nameMnt, sizeof(nameMnt), &amp;nameMnt, sizeof(nameMnt), &amp;bytesReturned, NULL); assert(success &amp;&amp; nameMnt.TargetPaths.MultiSzLength &gt; 0); wcsncat(nameMnt.TargetPaths.MultiSz, nameRel.NameInfo.FileName, nameRel.NameInfo.FileNameLength / sizeof(WCHAR)); return nameMnt.TargetPaths.MultiSz; } __finally { CloseHandle(hMountPointMgr); } } </code></pre> <p>and here's an example usage:</p> <pre><code>int _tmain(int argc, _TCHAR* argv[]) { HANDLE hFile = CreateFile(_T("\\\\.\\C:\\Windows\\Notepad.exe"), 0, FILE_SHARE_READ | FILE_SHARE_WRITE, NULL, OPEN_EXISTING, 0, NULL); assert(hFile != NULL &amp;&amp; hFile != INVALID_HANDLE_VALUE); __try { wprintf(L"%s\n", GetFilePath(hFile)); // Prints: // C:\Windows\notepad.exe } __finally { CloseHandle(hFile); } return 0; } </code></pre>
How do you crash a JVM? <p>I was reading a book on programming skills wherein the author asks the interviewee, "How do you crash a JVM?" I thought that you could do so by writing an infinite for-loop that would eventually use up all the memory.</p> <p>Anybody has any idea?</p>
<p>I wouldn't call throwing an OutOfMemoryError or StackOverflowError a crash. These are just normal exceptions. To really crash a VM there are 3 ways:</p> <ol> <li>Use JNI and crash in the native code.</li> <li>If no security manager is installed you can use reflection to crash the VM. This is VM specific, but normally a VM stores a bunch of pointers to native resources in private fields (e.g. a pointer to the native thread object is stored in a long field in <strong>java.lang.Thread</strong>). Just change them via reflection and the VM will crash sooner or later.</li> <li>All VMs have bugs, so you just have to trigger one.</li> </ol> <p>For the last method I have a short example, which will crash a Sun Hotspot VM quiet nicely:</p> <pre><code>public class Crash { public static void main(String[] args) { Object[] o = null; while (true) { o = new Object[] {o}; } } } </code></pre> <p>This leads to a stack overflow in the GC so you will get no StackOverflowError but a real crash including a hs_err* file.</p>
Convert a .doc or .pdf to an image and display a thumbnail in Ruby? <p>Convert a .doc or .pdf to an image and display a thumbnail in Ruby?<br> Does anyone know how to generate document thumbnails in Ruby (or C, python...)</p>
<p>A simple RMagick example to convert a PDF to a PNG would be:</p> <pre><code>require 'RMagick' pdf = Magick::ImageList.new("doc.pdf") thumb = pdf.scale(300, 300) thumb.write "doc.png" </code></pre> <p>To convert a MS Word document, it won't be as easy. Your best option may be to first convert it to a PDF before generating the thumbnail. Your options for generating the PDF depend heavily on the OS you're running on. One might be to use OpenOffice and the <a href="http://www.artofsolving.com/opensource/pyodconverter">Python Open Document Converter</a>. There are also online conversion services you could try, including <a href="http://Zamzar.com">http://Zamzar.com</a>.</p>
Apache Axis ConfigurationException <p>I am using Apache Axis to connect my Java app to a web server. I used wsdl2java to create the stubs for me, but when I try to use the stubs, I get the following exception:</p> <blockquote> <p>org.apache.axis.ConfigurationException: No service named <code>&lt;web service name&gt;</code> is available</p> </blockquote> <p>any idea?</p>
<p>According to the <a href="http://wiki.apache.org/ws/FrontPage/Axis/DealingWithCommonExceptions">documentation</a> linked to by @arnonym, this exception is somewhat misleading. In the first attempt to find the service a ConfigurationException is thrown and caught. It is logged at DEBUG level by the ConfigurationException class. Then another attempt is made using a different method to find the service that may then succeed. The workaround for this is to just change the log level on the ConfigurationException class to INFO in your log4j.properties:</p> <pre><code>log4j.logger.org.apache.axis.ConfigurationException = INFO </code></pre>
How to add method using metaclass <p>How do I add an instance method to a class using a metaclass (yes I do need to use a metaclass)? The following kind of works, but the func_name will still be "foo":</p> <pre><code>def bar(self): print "bar" class MetaFoo(type): def __new__(cls, name, bases, dict): dict["foobar"] = bar return type(name, bases, dict) class Foo(object): __metaclass__ = MetaFoo &gt;&gt;&gt; f = Foo() &gt;&gt;&gt; f.foobar() bar &gt;&gt;&gt; f.foobar.func_name 'bar' </code></pre> <p>My problem is that some library code actually uses the func_name and later fails to find the 'bar' method of the Foo instance. I could do:</p> <pre><code>dict["foobar"] = types.FunctionType(bar.func_code, {}, "foobar") </code></pre> <p>There is also types.MethodType, but I need an instance that does'nt exist yet to use that. Am I missing someting here?</p>
<p>Try dynamically extending the bases that way you can take advantage of the mro and the methods are actual methods:</p> <pre><code>class Parent(object): def bar(self): print "bar" class MetaFoo(type): def __new__(cls, name, bases, dict): return type(name, (Parent,) + bases, dict) class Foo(object): __metaclass__ = MetaFoo if __name__ == "__main__": f = Foo() f.bar() print f.bar.func_name </code></pre>
In Tomcat how can my servlet determine what connectors are configured? <p>In Tomcat 5.5 the server.xml can have many connectors, typically port only 8080, but for my application a user might configure their servlet.xml to also have other ports open (say 8081-8088). I would like for my servlet to figure out what socket connections ports will be vaild (During the Servlet.init() tomcat has not yet started the connectors.) </p> <p>I could find and parse the server.xml myself (grotty), I could look at the thread names (after tomcat starts up - but how would I know when a good time to do that is? ) But I would prefer a solution that can execute in my servlet.init() and determine what will be the valid port range. Any ideas? A solution can be tightly bound to Tomcat for my application that's ok.</p>
<p>In Tomcat 6.0 it should be something like:</p> <pre><code>org.apache.catalina.ServerFactory.getServer().getServices </code></pre> <p>to get the services. After that you might use </p> <pre><code>Service.findConnectors </code></pre> <p>which returns a Connector which finally has the method</p> <pre><code>Connector.getPort </code></pre> <p>See the <a href="http://tomcat.apache.org/tomcat-6.0-doc/api/org/apache/catalina/connector/Connector.html" rel="nofollow">JavaDocs</a> for the details.</p>