instruction
stringlengths
21
27.8k
chosen
stringlengths
18
28.2k
rejected
stringlengths
18
33.6k
__index_level_0__
int64
0
50k
<p>On my team, we usually do string concatentation like this:</p> <pre><code>var url = // some dynamically generated URL var sb = new StringBuffer(); sb.append("&lt;a href='").append(url).append("'&gt;click here&lt;/a&gt;"); </code></pre> <p>Obviously the following is much more readable:</p> <pre><code>var url = // some dynamically generated URL var sb = "&lt;a href='" + url + "'&gt;click here&lt;/a&gt;"; </code></pre> <p>But the JS experts claim that the <code>+</code> operator is less performant than <code>StringBuffer.append()</code>. Is this really true?</p>
<p>Your example is not a good one in that it is very unlikely that the performance will be signficantly different. In your example readability should trump performance because the performance gain of one vs the other is negligable. The benefits of an array (StringBuffer) are only apparent when you are doing many concatentations. Even then your mileage can very depending on your browser.</p> <p>Here is a detailed performance analysis that shows performance using all the different JavaScript concatenation methods across many different browsers; <a href="http://www.sitepen.com/blog/2008/05/09/string-performance-an-analysis/" rel="noreferrer">String Performance an Analysis</a></p> <p><img src="https://i.stack.imgur.com/FcI38.jpg" alt="join() once, concat() once, join() for, += for, concat() for"></p> <p>More:<br> <a href="http://ajaxian.com/archives/string-performance-in-ie-arrayjoin-vs-continued" rel="noreferrer">Ajaxian >> String Performance in IE: Array.join vs += continued</a></p>
<p>Yes, according to the usual benchmarks. E.G : <a href="http://mckoss.com/jscript/SpeedTrial.htm" rel="nofollow noreferrer">http://mckoss.com/jscript/SpeedTrial.htm</a>.</p> <p>But for the small strings, this is irrelevant. You will only care about performances on very large strings. What's more, in most JS script, the bottle neck is rarely on the string manipulations since there is not enough of it.</p> <p>You'd better watch the DOM manipulation.</p>
13,730
<p>Does MSTest have standalone GUI similar to nUnit that lets me use it and run test without visual studio? What is the official site for MSTest where I can learn more about how to use it?</p>
<p>It doesn't have a GUI (apart from Visual Studio) but there's a command line tool: <a href="http://msdn.microsoft.com/en-us/library/ms182489.aspx" rel="noreferrer">MSTest.exe</a></p> <p>Here is the official documentation on <a href="http://msdn.microsoft.com/en-us/library/ms182469.aspx" rel="noreferrer">running MSTest tests</a>.</p>
<p>Uset &quot;dotnet test&quot;, it is compatible with all versions, eg:</p> <pre><code>'dotnet test yourassembly.dll -l console -v detailed' </code></pre>
32,663
<p><strong>problem</strong></p> <p>how to best parse/access/extract "excel file" data stored as binary data in an SQL 2005 field?</p> <p>(so all the data can ultimately be stored in other fields of other tables.)</p> <p><strong>background</strong></p> <p>basically, our customer is requiring a large volume of verbose data from their users. unfortunately, our customer cannot require any kind of db export from their user. so our customer must supply some sort of UI for their user to enter the data. the UI our customer decided would be acceptable to all of their users was excel as it has a reasonably robust UI. so given all that, and our customer needs this data parsed and stored in their db automatically.</p> <p>we've tried to convince our customer that the users will do this exactly once and then insist on db export! but the customer can not <em>require</em> db export of their users.</p> <ul> <li>our customer is requiring us to parse an excel file</li> <li>the customer's users are using excel as the "best" user interface to enter all the required data</li> <li>the users are given blank excel templates that they must fill out <ul> <li>these templates have a fixed number of uniquely named tabs</li> <li>these templates have a number of fixed areas (cells) that must be completed</li> <li>these templates also have areas where the user will insert up to thousands of identically formatted rows</li> </ul></li> <li>when complete, the excel file is submitted from the user by standard html file upload</li> <li>our customer stores this file raw into their SQL database</li> </ul> <p><strong>given</strong></p> <ul> <li>a standard excel (".xls") file (native format, not comma or tab separated)</li> <li>file is stored raw in a <code>varbinary(max)</code> SQL 2005 field</li> <li>excel file data may not necessarily be "uniform" between rows -- i.e., we can't just assume one column is all the same data type (e.g., there may be row headers, column headers, empty cells, different "formats", ...)</li> </ul> <p><strong>requirements</strong></p> <ul> <li>code completely within SQL 2005 (stored procedures, SSIS?)</li> <li>be able to access values on any worksheet (tab)</li> <li>be able to access values in any cell (no formula data or dereferencing needed)</li> <li>cell values must not be assumed to be "uniform" between rows -- i.e., we can't just assume one column is all the same data type (e.g., there may be row headers, column headers, empty cells, formulas, different "formats", ...)</li> </ul> <p><strong>preferences</strong></p> <ul> <li>no filesystem access (no writing temporary .xls files)</li> <li>retrieve values in defined format (e.g., actual date value instead of a raw number like 39876)</li> </ul>
<p>My thought is that anything can be done, but there is a price to pay. In this particular case, the price seems to bee too high. </p> <p>I don't have a tested solution for you, but I can share how I would give my first try on a problem like that.</p> <p>My first approach would be to install excel on the SqlServer machine and code some assemblies to consume the file on your rows using excel API and then load them on Sql server as assembly procedures.</p> <p>As I said, This is just a idea, I don't have details, but I'm sure others here can complement or criticize my idea.</p> <p>But my real advice is to rethink the whole project. It makes no sense to read tabular data on binary files stored on a cell of a row of a table on database. </p>
<p>It sounds like you're trying to store an entire database table inside a spreadsheet and then inside a single table's field. Wouldn't it be simpler to store the data in a database table to begin with and then export it as an XLS when required?</p> <p>Without opening up an instance Excel and having Excel resolve worksheet references I'm not sure it's doable at all.</p>
10,500
<p>Currently I have two MediaWikis, one a slightly older version than the other. I want to merge the contents of both together, without eliminating duplicate pages. So far the best option I can think of is to use a bot (like pywikipedia) to go through all the pages of one wiki, and try inserting them into the other, renaming duplicate pages.</p> <p>This solution seems like it would take a while to accomplish though. Is there a more pleasant way to do this that I'm just unaware of? I haven't worked with the MediaWiki database directly very much, so I'm not very comfortable messing with it without knowing what I'm doing.</p>
<p>MediaWiki has <a href="http://meta.wikimedia.org/wiki/Help:Import" rel="noreferrer">import</a> and <a href="http://meta.wikimedia.org/wiki/Help:Export" rel="noreferrer">export</a> features, that you can use for moving the contents. It does merge histories of existing pages (see import link).</p> <p>However, it does not handle conlicts of two different pages with the same name, so you'll have to handle moving the pages by yourself. As far as I can see in description of MediaWiki <a href="http://www.mediawiki.org/wiki/Page_table" rel="noreferrer">page table</a>, you might be able to find and rename duplicate pages directly in SQL, but pywikipedia should work too (but you'll need to delete redirects that will result from "correct" page moves, otherwise they'll mess up with imported pages from the other wiki).</p>
<p>As a committer of <a href="https://github.com/WolfgangFahl/py-3rdparty-mediawiki" rel="nofollow noreferrer">https://github.com/WolfgangFahl/py-3rdparty-mediawiki</a> i recommend using the wikibackup/wikirestore feature of that tool - it will do the export/import in a way that allows to use standard unix tools while at it e.g. doing tree diffs of the backups to see what to do with the duplicats.</p>
37,804
<p>I'm generating some XML documents and when it comes to the address part I have fragments that look like this:</p> <pre><code>&lt;Address&gt;15 Sample St Example Bay Some Country&lt;/Address&gt; </code></pre> <p>The XSLT that I have for converting this to XHTML has some funky recursive template to convert newline characters within strings to &lt;br/&gt; tags.</p> <p>This is all working fine; but is it considered "bad practice" to rely on linebreaks within XML documents? If so, is it recommended that I do this instead?</p> <pre><code>&lt;Address&gt;&lt;Line&gt;15 Sample St&lt;/Line&gt; &lt;Line&gt;Example Bay&lt;/Line&gt; &lt;Line&gt;Some Country&lt;/Line&gt;&lt;/Address&gt; </code></pre> <p>Seems like it'd be really awkward to wrap every place where my text may be multiple lines with tags like that..</p>
<p>It's generally considered bad practice to rely on linebreaks, since it's a fragile way to differentiate data. While most XML processors will preserve any whitespace you put in your XML, it's not guaranteed. </p> <p>The real problem is that most applications that output your XML into a readable format consider all whitespace in an XML interchangable, and might collapse those linebreaks into a single space. That's why your XSLT has to jump through such hoops to render the data properly. Using a "br" tag would vastly simplify the transform.</p> <p>Another potential problem is that if you open up your XML document in an XML editor and pretty-print it, you're likely to lose those line breaks. </p> <p>If you do keep using linebreaks, make sure add an xml:space="preserve" attribute to "address." (You can do this in your DTD, if you're using one.)</p> <p><strong>Some suggested reading</strong></p> <ul> <li>An <a href="http://www.xml.com/pub/a/2001/11/07/whitespace.html" rel="noreferrer">article from XML.com</a> says the following:</li> </ul> <blockquote> <p>XML applications often seem to take a cavalier attitude toward whitespace because the rules about the places in an XML document where whitespace doesn't matter sometimes give these applications free rein to add or remove whitespace in certain places.</p> </blockquote> <ul> <li><a href="http://www.dpawson.co.uk/xsl/sect2/N8321.html" rel="noreferrer">A collection of XSL-list posts regarding whitespace</a>. </li> </ul>
<p>Yes, I think using a <a href="http://en.wikipedia.org/wiki/CDATA" rel="nofollow noreferrer">CDATA</a> block would protect the whitespace. Although some parser APIs allow you to preserve whitespace.</p>
2,892
<p>Is it safe to assume that event subscribers are called in order of subscription?<br> Example: </p> <pre><code>void One(object sender, EventArgs e) {} void Two(object sender, EventArgs e) {} event EventHandler foo; foo += One; foo += Two; </code></pre> <p>Is One() always called before Two() when the event is fired?</p> <p>Edit:<br> You should ofcourse not rely on it, I was just thinking. The idea was, that multicast delegates are similary to the COMMAND pattern. So I was just wondering. Ususally you would use a collection that keeps the order for COMMANDs so you can do undo/redo/whatever.</p>
<p>Given that implementation, yes, they will always be called in that order.</p> <p>If the event actually uses some weird and wonderful way of handling subscriptions, it could do different things - but "normal" implementations will do the right thing.</p> <p>To be clear, subscribing to an event handler just means invoking the appropriate "add" part of an event. If the event handles this by doing something like:</p> <pre><code>myHandler += value; </code></pre> <p>that gets translated into</p> <pre><code>myHandler = Delegate.Combine(myHandler, value); </code></pre> <p>and <a href="http://msdn.microsoft.com/en-us/library/30cyx32c.aspx" rel="noreferrer">Delegate.Combine</a> guarantees the ordering. However, if you had an event like this:</p> <pre><code>private LinkedList&lt;EventHandler&gt; eventHandlers = new LinkedList&lt;EventHandler&gt;; public event EventHandler Foo { add { eventHandlers.AddFirst(value); } remove { // do stuff here too } } </code></pre> <p>and then fired the event by doing something like:</p> <pre><code>foreach (EventHandler handler in eventHandlers) { handler(this, EventArgs.Empty); } </code></pre> <p>then the handlers would be called in the reverse order.</p> <p><strong>Summary</strong>: For all sane events, you can rely on the ordering. In theory, events can do what they like, but I've never seen an event which <em>doesn't</em> maintain the appropriate ordering.</p>
<p>In general, events subscribers are expected to behave independently from each other. It should make no difference whether they're invoked in order of subscription, reverse order of subscription, or in seemingly-random order which varies arbitrarily each time the event is raised. Subscribers shouldn't care about other subscribers that execute before them or after them.</p> <p>In some cases, however, events may be used in contexts where such ordering is important. Event handlers may be passed a mutable object, and be expected to make use of previous handler's mutations of that object. In such a case, if meaningful operation of the events would require that they be performed in a particular order, and provided that any documented requirements for subscribers have been complied with, one should expect that the events will be executed in the order given.</p>
48,959
<p>I'd sort of like to use SQLite from within C#.Net, but I can't seem to find an appropriate library. Is there one? An official one? Are there other ways to use SQLite than with a wrapper?</p>
<p>From <a href="https://system.data.sqlite.org/" rel="noreferrer">https://system.data.sqlite.org</a>:</p> <blockquote> <p>System.Data.SQLite is an ADO.NET adapter for SQLite.</p> <p>System.Data.SQLite was started by Robert Simpson. Robert still has commit privileges on this repository but is no longer an active contributor. Development and maintenance work is now mostly performed by the SQLite Development Team. The SQLite team is committed to supporting System.Data.SQLite long-term.</p> </blockquote> <p>"System.Data.SQLite is the original SQLite database engine and a complete ADO.NET 2.0 provider all rolled into a single mixed mode assembly. It is a complete drop-in replacement for the original sqlite3.dll (you can even rename it to sqlite3.dll). Unlike normal mixed assemblies, it has no linker dependency on the .NET runtime so it can be distributed independently of .NET."</p> <p>It even supports Mono.</p>
<p>Version 1.2 of Monotouch includes support for System.Data. You can find more details here: <a href="http://monotouch.net/Documentation/System.Data" rel="nofollow noreferrer">http://monotouch.net/Documentation/System.Data</a></p> <p>But basically it allows you to use the usual ADO .NET patterns with sqlite.</p>
11,922
<p>I've honestly <a href="https://stackoverflow.com/questions/35420/mysql-software-any-suggestions-to-oversee-my-mysql-replication-server">tried</a> <a href="https://stackoverflow.com/questions/8365/mysql-administrator-backups-compatibility-mode-what-exactly-is-this-doing">this</a> <a href="https://stackoverflow.com/questions/30660/mysql-binary-log-replication-can-it-be-set-to-ignore-errors">left</a> <a href="https://stackoverflow.com/questions/3798/full-complete-mysql-db-replication-ideas-what-do-people-do">and</a> <a href="https://stackoverflow.com/questions/8166/mysql-replication-if-i-dont-specify-any-databases-will-logbin-log-everything">right</a> and still find that my mirror server, set up as a replication slave still lags behind. My app's user base keeps growing and now Ive reached the point where I can't keep "shutting down" to "resync" databases (not even on weekends).</p> <p>Anyways, my question: Are there any plausible, <strong>affordable</strong>, alternatives to binlog replication? I have two servers so wouldn't consider buying a third for load balancing just yet, unless its the only option.</p> <p>Cheers,</p> <p>/mp</p>
<p>Your master executes in parallel and your slave executes in serial. If your master can process 1.5 hours of inserts/updates/executes in 1 real hour, your slave will fall behind.</p> <p>If you can't find ways to improve the write performance on your slave (more memory, faster disks, remove unnecessary indexes), you've hit a limitation in your applications architecture. Eventually you will hit a point that you can't execute the changes in real time as fast as your master can execute them in parallel.</p> <p>A lot of big sites shard their databases: consider splitting your master+slave into multiple master+slave clusters. Then split your customer base across these clusters. When a slave starts falling behind, it's time to add another cluster.</p> <p>It's not cheap, but unless you can find a way to make binlog replication execute statements in parallel you probably won't find a better way of doing it.</p> <p><strong>Update (2017)</strong>: MySQL now support <a href="https://dev.mysql.com/doc/refman/5.7/en/replication-options-slave.html#sysvar_slave_parallel_workers" rel="nofollow noreferrer">parallel slave worker threads</a>. There are still many variables that will cause a slave to fall behind, but slaves no longer need to write in serial order. Choosing to preserve the commit order of parallel slave threads is an important option to look at if the exact state of the slave at any point in time is critical.</p>
<p>Adding memory to the slave would probably help. We went from 32 to 128 megs and the lagging more or less went away. But its neither cheap nor will it be enough in all situations.</p> <p>Buying a third server will probably not help that much though, you will most likely just get another lagging slave.</p>
34,333
<p>With the help of the Stack Overflow community I've written a pretty basic-but fun physics simulator.</p> <p><img src="https://i.stack.imgur.com/EeqSP.png" alt="alt text" /></p> <p>You click and drag the mouse to launch a ball. It will bounce around and eventually stop on the &quot;floor&quot;.</p> <p>My next big feature I want to add in is ball to ball collision. The ball's movement is broken up into a x and y speed vector. I have gravity (small reduction of the y vector each step), I have friction (small reduction of both vectors each collision with a wall). The balls honestly move around in a surprisingly realistic way.</p> <p>I guess my question has two parts:</p> <ol> <li><strong>What is the best method to detect ball to ball collision?</strong><br /> Do I just have an O(n^2) loop that iterates over each ball and checks every other ball to see if it's radius overlaps?</li> <li><strong>What equations do I use to handle the ball to ball collisions? Physics 101</strong><br /> How does it effect the two balls speed x/y vectors? What is the resulting direction the two balls head off in? How do I apply this to each ball?</li> </ol> <p><img src="https://upload.wikimedia.org/wikipedia/commons/2/2c/Elastischer_sto%C3%9F_2D.gif" alt="alt text" /></p> <p>Handling the collision detection of the &quot;walls&quot; and the resulting vector changes were easy but I see more complications with ball-ball collisions. With walls I simply had to take the negative of the appropriate x or y vector and off it would go in the correct direction. With balls I don't think it is that way.</p> <p>Some quick clarifications: for simplicity I'm ok with a perfectly elastic collision for now, also all my balls have the same mass right now, but I might change that in the future.</p> <hr /> <p>Edit: Resources I have found useful</p> <p>2d Ball physics with vectors: <a href="https://www.vobarian.com/collisions/2dcollisions2.pdf" rel="nofollow noreferrer">2-Dimensional Collisions Without Trigonometry.pdf</a><br /> 2d Ball collision detection example: <a href="https://web.archive.org/web/20210125052930/http://geekswithblogs.net/robp/archive/2008/05/15/adding-collision-detection.aspx" rel="nofollow noreferrer">Adding Collision Detection</a></p> <hr /> <h2>Success!</h2> <p>I have the ball collision detection and response working great!</p> <p>Relevant code:</p> <p>Collision Detection:</p> <pre><code>for (int i = 0; i &lt; ballCount; i++) { for (int j = i + 1; j &lt; ballCount; j++) { if (balls[i].colliding(balls[j])) { balls[i].resolveCollision(balls[j]); } } } </code></pre> <p>This will check for collisions between every ball but skip redundant checks (if you have to check if ball 1 collides with ball 2 then you don't need to check if ball 2 collides with ball 1. Also, it skips checking for collisions with itself).</p> <p>Then, in my ball class I have my colliding() and resolveCollision() methods:</p> <pre><code>public boolean colliding(Ball ball) { float xd = position.getX() - ball.position.getX(); float yd = position.getY() - ball.position.getY(); float sumRadius = getRadius() + ball.getRadius(); float sqrRadius = sumRadius * sumRadius; float distSqr = (xd * xd) + (yd * yd); if (distSqr &lt;= sqrRadius) { return true; } return false; } public void resolveCollision(Ball ball) { // get the mtd Vector2d delta = (position.subtract(ball.position)); float d = delta.getLength(); // minimum translation distance to push balls apart after intersecting Vector2d mtd = delta.multiply(((getRadius() + ball.getRadius())-d)/d); // resolve intersection -- // inverse mass quantities float im1 = 1 / getMass(); float im2 = 1 / ball.getMass(); // push-pull them apart based off their mass position = position.add(mtd.multiply(im1 / (im1 + im2))); ball.position = ball.position.subtract(mtd.multiply(im2 / (im1 + im2))); // impact speed Vector2d v = (this.velocity.subtract(ball.velocity)); float vn = v.dot(mtd.normalize()); // sphere intersecting but moving away from each other already if (vn &gt; 0.0f) return; // collision impulse float i = (-(1.0f + Constants.restitution) * vn) / (im1 + im2); Vector2d impulse = mtd.normalize().multiply(i); // change in momentum this.velocity = this.velocity.add(impulse.multiply(im1)); ball.velocity = ball.velocity.subtract(impulse.multiply(im2)); } </code></pre> <p>Source Code: <a href="https://www.dropbox.com/s/1j4aiu2aahjc19p/ballbounce.zip?dl=0" rel="nofollow noreferrer">Complete source for ball to ball collider.</a></p> <p>If anyone has some suggestions for how to improve this basic physics simulator let me know! One thing I have yet to add is angular momentum so the balls will roll more realistically. Any other suggestions? Leave a comment!</p>
<p>To detect whether two balls collide, just check whether the distance between their centers is less than two times the radius. To do a perfectly elastic collision between the balls, you only need to worry about the component of the velocity that is in the direction of the collision. The other component (tangent to the collision) will stay the same for both balls. You can get the collision components by creating a unit vector pointing in the direction from one ball to the other, then taking the dot product with the velocity vectors of the balls. You can then plug these components into a 1D perfectly elastic collision equation. </p> <p>Wikipedia has a pretty good <a href="http://en.wikipedia.org/wiki/Elastic_collision" rel="noreferrer">summary of the whole process</a>. For balls of any mass, the new velocities can be calculated using the equations (where v1 and v2 are the velocities after the collision, and u1, u2 are from before):</p> <p><img src="https://upload.wikimedia.org/math/a/b/6/ab6645eaf09c6da1ba47b0f662615140.png" alt="v_{1} = \frac{u_{1}(m_{1}-m_{2})+2m_{2}u_{2}}{m_{1}+m_{2}}"> </p> <p><img src="https://upload.wikimedia.org/math/e/0/f/e0fa187fc3065bad45710620be5f7687.png" alt="v_{2} = \frac{u_{2}(m_{2}-m_{1})+2m_{1}u_{1}}{m_{1}+m_{2}}"></p> <p>If the balls have the same mass then the velocities are simply switched. Here's some code I wrote which does something similar:</p> <pre><code>void Simulation::collide(Storage::Iterator a, Storage::Iterator b) { // Check whether there actually was a collision if (a == b) return; Vector collision = a.position() - b.position(); double distance = collision.length(); if (distance == 0.0) { // hack to avoid div by zero collision = Vector(1.0, 0.0); distance = 1.0; } if (distance &gt; 1.0) return; // Get the components of the velocity vectors which are parallel to the collision. // The perpendicular component remains the same for both fish collision = collision / distance; double aci = a.velocity().dot(collision); double bci = b.velocity().dot(collision); // Solve for the new velocities using the 1-dimensional elastic collision equations. // Turns out it's really simple when the masses are the same. double acf = bci; double bcf = aci; // Replace the collision velocity components with the new ones a.velocity() += (acf - aci) * collision; b.velocity() += (bcf - bci) * collision; } </code></pre> <p>As for efficiency, Ryan Fox is right, you should consider dividing up the region into sections, then doing collision detection within each section. Keep in mind that balls can collide with other balls on the boundaries of a section, so this may make your code much more complicated. Efficiency probably won't matter until you have several hundred balls though. For bonus points, you can run each section on a different core, or split up the processing of collisions within each section.</p>
<p>I would consider using a quadtree if you have a large number of balls. For deciding the direction of bounce, just use simple conservation of energy formulas based on the collision normal. Elasticity, weight, and velocity would make it a bit more realistic.</p>
44,999
<p>Inside my code I'm generating hashes of URLs, (which are practically of unbounded length). I'm currently using sha1(), which I know has a tiny chance of a collision, but I have up to 255 bytes to store the hash in so feel that I might as well use that available space to lower the chance of collision even further.</p> <p>Is there either:</p> <ol> <li>Another PHP hash function with a longer or customisable hash length?</li> <li>A way of using a fixed-length hash function like sha1 with a variable length input to generate a longer hash?</li> </ol> <p>Or, is sha1's 20-byte hash good enough for anything and I should stop worrying about it?</p>
<blockquote> <p>Or, is sha1's 20-byte has good enough for anything and I should stop worrying about it?</p> </blockquote> <p>Exactly.</p> <p>Hashtables, Pigeonholes, and Birthdays<br> <a href="http://www.codinghorror.com/blog/archives/001014.html" rel="nofollow noreferrer">http://www.codinghorror.com/blog/archives/001014.html</a></p>
<p>You could always prepend/append a sequential ID (in decimal or hex) to your existing hash?</p> <p>Sure you wouldn't have a fixed length hash but you'd know the code was a) unique and b) non-guessable (even if someone noticed the sequential part they wouldn't know the way you were salting/hashing the rest of the code).</p> <p>Of course if you're not trying to hide these hashes from anyone then why not simply use a sequential ID in the first place?</p>
37,767
<p>Is there really that much of a difference between the performance of <code>Vector</code> and <code>ArrayList</code>? Is it good practice to use ArrayLists at all times when thread safety isn't an issue?</p>
<p>Vector originates back from the pre-Collections API days, and have been retrofitted since to be a part of it. From what I've read, the reason it is not deprecated is because the core API depends on it.</p> <p>ArrayList was written from scratch as a part of the Collections API and as such should be used unless you need to support Java versions down to 1.2.</p> <p>If you need a thread-safe ArrayList, you can use the static factory method <code>Collections.synchronizedList(new ArrayList&lt;type&gt;);</code> to generate your list.</p>
<p>If thread safety isn't an issue you should always use <code>ArrayList</code>. Vector has the overhead of synchronization and it has been shown that the performance differences between <code>ArrayList</code> and <code>Vector</code> are abysmal. You can google for a lot of performance benchmarks. </p> <p>Here's one <a href="http://www.particle.kth.se/~lindsey/JavaCourse/Book/Part1/Java/Chapter12/timing.html" rel="nofollow noreferrer">Timing &amp; Performance</a>.</p>
38,526
<p>You can use </p> <p>SelectFolder() to get a folder</p> <p>or </p> <p>GetOpenFolderitem(filter as string) to get files</p> <p>but can you select either a folder or file? ( or for that matter selecting multiple files )</p>
<p>The MonkeyBread plugin allows this in the OpenDialogMBS class.</p> <p><a href="http://www.monkeybreadsoftware.net/pluginhelp/navigation-opendialogmbs.shtml" rel="nofollow noreferrer">http://www.monkeybreadsoftware.net/pluginhelp/navigation-opendialogmbs.shtml</a></p> <pre><code>OpenDialogMBS.AllowFolderSelection as Boolean property, Navigation, MBS Util Plugin (OpenDialog), class OpenDialogMBS, Plugin version: 7.5, Mac OS X: Works, Windows: Does nothing, Linux x86: Does nothing, Feedback. Function: Whether folders can be selected. Example: dim o as OpenDialogMBS dim i,c as integer dim f as FolderItem o=new OpenDialogMBS o.ShowHiddenFiles=true o.PromptText="Select one or more files/folders:" o.MultipleSelection=false o.ActionButtonLabel="Open files/folders" o.CancelButtonLabel="no, thanks." o.WindowTitle="This is a window title." o.ClientName="Client Name?" o.AllowFolderSelection=true o.ShowDialog c=o.FileCount if c&gt;0 then for i=0 to c-1 f=o.Files(i) FileList.List.AddRow f.AbsolutePath next end if Notes: Default is false. Setting this to true on Windows or Linux has no effect there. (Read and Write property) </code></pre>
<p>Assuming you're using .Net I think you'll need to create your own control (or buy one). </p>
12,549
<p>I would like to print a custom version of something akin to this rugged case that was originally created using injection molding:</p> <p><a href="https://i.stack.imgur.com/oL8JW.jpg" rel="nofollow noreferrer" title="ea weather proofed tablet with over-molded rubber"><img src="https://i.stack.imgur.com/oL8JW.jpg" alt="ea weather proofed tablet with over-molded rubber" title="ea weather proofed tablet with over-molded rubber" /></a></p> <p>The outside consists of a material that is a bit softer than the main body.</p> <p>It is used to protect the electronics against drops when the case falls onto the floor.</p> <p>Unfortunately, I don't know which material this is, and I don't know which method I could use to measure its softness.</p> <p>I would therefore like to ask if anybody has experience with such a softer outer hull and can tell me which material could be used when I want to 3D print it.</p> <p>I would like to use this case in a hospital environment.</p>
<p>I do it a couple of ways.</p> <p>I use TPU which is pretty good for impacts and either make it thick or stiffen it with another filament as an inside or outside shell.</p> <p>But TPU is what you want for this project because it's flexible in the way you need it to be.</p>
<p>Case designers usually use TPU for flexibility and polycarbonate for stiffness</p>
2,201
<p>When I'm initializing a dialog, I'd like to select one of the radio buttons on the form. I don't see a way to associate a Control variable using the Class Wizard, like you would typically do with CButtons, CComboBoxes, etc...</p> <p>Further, it doesn't like a CRadioButton class even exists.</p> <p>How can I select one of the several radio buttons?</p>
<p>Radio buttons and check buttons are just buttons. Use a <code>CButton</code> control and use <code>GetCheck</code>/<code>SetCheck</code>.</p>
<pre><code>void CMyDlg::DoDataExchange(CDataExchange* pDX) { ... DDX_Radio(pDX, IDC_RADIO1, m_Radio); ... } </code></pre> <p>but it is the same thing Wizard generates</p>
9,919
<p>I have a business user who tried his hand at writing his own SQL query for a report of project statistics (e.g. number of tasks, milestones, etc.). The query starts off declaring a temp table of 80+ columns. There are then almost 70 UPDATE statements to the temp table over almost 500 lines of code that each contain their own little set of business rules. It finishes with a SELECT * from the temp table.</p> <p>Due to time constraints and 'other factors', this was rushed into production and now my team is stuck with supporting it. Performance is appalling, although thanks to some tidy up it's fairly easy to read and understand (although the code smell is nasty).</p> <p>What are some key areas we should be looking at to make this faster and follow good practice?</p>
<p>First off, if this is not causing a business problem, then leave it until it becomes a problem. Wait until it becomes a problem, then fix everything.</p> <p>When you do decide to fix it, check if there is one statement causing most of your speed issues ... issolate and fix it.</p> <p>If the speed issue is over all the statements, and you can combine it all into a single SELECT, this will probably save you time. I once converted a proc like this (not as many updates) to a SELECT and the time to run it went from over 3 minutes to under 3 seconds (no shit ... I couldn't believe it). By the way, don't attempt this if some of the data is coming from a linked server.</p> <p>If you don't want to or can't do that for whatever reason, then you might want to adjust the existing proc. Here are some of the things I would look at:</p> <ol> <li><p>If you are creating indexes on the temp table, wait until after your initial INSERT to populate it.</p></li> <li><p>Adjust your initial INSERT to insert as many of the columns as possible. There are probably some update's you can eliminate by doing this.</p></li> <li><p>Index the temp table before running your updates. Do not create indexes on any of the columns targetted by the update statements until after their updated.</p></li> <li><p>Group your updates if your table(s) and groupings allow for it. 70 updates is quite a few for only 80 columns, and sounds like there may be an opportunity to do this.</p></li> </ol> <p>Good luck</p>
<p>I would rewrite it from scratch.</p> <p>You say that you understand what it supposed to do so it should not be that difficult. And I bet that the requirements for that piece of code will keep changing so if you do not rewrite it now you may end up maintaining some ugly monster</p>
41,516
<p>I have to simultaneously load data into a table and run queries on it. Because of data nature, I can trade integrity for performance. How can I minimize the overhead of transactions?</p> <p>Unfortunately, alternatives like MySQL cannot be used (due to non-technical reasons). </p>
<p>Other than the general optimization practices that apply to all databases such as eliminating full table scans, removing unused or inefficient indexes, etc., etc., here are a few things you can do.</p> <ol> <li>Run in <a href="http://www.adp-gmbh.ch/ora/admin/backup_recovery/archive_vs_noarchive_log.html" rel="nofollow noreferrer"><code>No Archive Log</code></a> mode. This sacrifices recoverability for speed.</li> <li>For inserts use the <a href="http://www.psoug.org/reference/hints.html" rel="nofollow noreferrer"><code>/*+ APPEND */</code> hint</a>. This puts data into the table above the high water mark which does not create UNDO. The disadvantage is that existing free space is not used.</li> <li>On the hardware side, <a href="http://www.acnc.com/04_01_00.html" rel="nofollow noreferrer"><code>RAID 0</code></a> over a larger number of smaller disks will give you the best insert performance, but depending on your usage <a href="http://www.acnc.com/04_01_10.html" rel="nofollow noreferrer"><code>RAID 10</code></a> with its better read performance may provide a better fit.</li> </ol> <p>This said, I don't think you will gain much from any of these changes.</p>
<p>What kind of performance volumes are you looking at? Are inserts batched or numerous small ones?</p> <p>Before banging your head against the wall trying to think of clever ways to have good performance, did you create any simple prototypes which would give you a better picture of the out-of-the-box performance? It could easily turn out that you don't need to do anything special to meet the goals.</p>
32,485
<p>Given a jQuery result set, how do you convert that back into plain HTML?</p> <pre><code>&lt;div class="abc"&gt; foo &lt;strong&gt;FOO&lt;/strong&gt; &lt;/div&gt; &lt;div class="def"&gt; bar &lt;/div&gt; </code></pre> <p>--</p> <pre><code>var $mySet = $('div'); </code></pre> <p>Given <code>$mySet</code>, how would you go about returning to the plain HTML above?</p>
<p>i'd suggest creating a temporary container, then grabbing the <code>html()</code> of that new container:</p> <pre><code>var html = $('&lt;div&gt;').append( $('div').clone() ).html(); alert(html); // alerts: &lt;div class="abc"&gt; foo &lt;strong&gt;FOO&lt;/strong&gt; &lt;/div&gt;&lt;div class="def"&gt; bar &lt;/div&gt; </code></pre>
<pre><code>var $mySet = $('div'); var html = $mySet.html(); </code></pre> <p>If you want the element's HTML as well (untested):</p> <pre><code>var $mySet = $('div'); var html = $mySet.clone().wrap('&lt;div&gt;&lt;/div&gt;').html(); </code></pre> <p>By the way, here $ is part of the variable name. Javascript doesn't require a $ like in PHP for variable names, but it doesn't hurt to have it.</p>
42,092
<p>Is there a CIL instruction to exchange the first two elements in the stack?</p>
<p>There is no single instruction exchange. However, using <a href="http://msdn.microsoft.com/en-us/library/system.reflection.emit.opcodes.stloc.aspx" rel="noreferrer">stloc</a>, <a href="http://msdn.microsoft.com/en-us/library/system.reflection.emit.opcodes.pop.aspx" rel="noreferrer">pop</a>, and <a href="http://msdn.microsoft.com/en-us/library/system.reflection.emit.opcodes.ldloc.aspx" rel="noreferrer">ldloc</a>, you should be able to accomplish your exchange.</p>
<p>For future reference, you can create an assembly that does what you want to learn the IL for, then view the assembly in Reflector. You can select the language you wish the code to be in, and IL is one of the options. I did this when trying to figure out how to code a dynamic method...</p>
23,319
<p>I just started using CCNet, and in the process of getting my build projects set up I racked up a lot of build history from trial and error. I really don't want to keep that old stuff around, but I can't seem to see where/how to get rid of it. I'm sure this is a silly question, and I apologize if I'm overlooking something that should be obvious. I did <a href="http://confluence.public.thoughtworks.org/display/CCNET/Documentation" rel="noreferrer">RTM</a> and Google for about a half hour, and poked around my CCNet installation, but it's not jumping out at me. I deleted the state files for the projects (don't know if that has anything to do with it), but the old builds are still there if I drill into a project's stats from the dashboard. Any suggestions? Thanks.</p> <p><strong>Answered</strong>: I had explicitly set the artifacts directory to a location that was not under the CCNet server directory and consequently never looked in it again... went looking and, disco, there's the build histories.</p>
<p>Assuming you have a project called "Dev" and you've installed CCNet into the default location, you'll have a folder called:</p> <p>c:\Program Files\CruiseControl.NET\server\Dev </p> <p>and a Dev.state file in:</p> <p>c:\Program Files\CruiseControl.NET\server</p> <p>Just delete both the folder and the state file.</p>
<p>As mentioned above, use the Artifact Cleanup Publisher to keep the number of artifacts to a sensible level. </p> <p>If you have a lot of projects and need to do a retrospective cleanup, you could use the following Powershell script to remove old log files:</p> <pre><code>$limit = (Get-Date).AddDays(-60) get-childitem -Path D:\Builds -filter MatchMyProjects.* | %{ $projectPath=$_.FullName $logsPath=$projectPath + "\Logs" write-host Removing logs from folder $logsPath Get-ChildItem -Path $logsPath -Force -Filter *.xml | Where-Object { !$_.PSIsContainer -and $_.CreationTime -lt $limit } | Remove-Item -Force } </code></pre> <p>Thanks to this answer: <a href="https://stackoverflow.com/questions/17829785/delete-files-older-than-15-days-using-powershell">Delete files older than 15 days using PowerShell</a></p>
40,770
<p>Is there any way to access the Windows Event Log from a java class. Has anyone written any APIs for this, and would there be any way to access the data from a remote machine?</p> <p>The scenario is:</p> <p>I run a process on a remote machine, from a controlling Java process. This remote process logs stuff to the Event Log, which I want to be able to see in the controlling process.</p> <p>Thanks in advance.</p>
<p>On the Java side, you'll need a library that allows you to make native calls. Sun offers <a href="http://java.sun.com/javase/6/docs/technotes/guides/jni/index.html" rel="noreferrer">JNI</a>, but it sounds like sort of a pain. Also consider:</p> <ul> <li><a href="https://github.com/twall/jna/" rel="noreferrer">https://github.com/twall/jna/</a></li> <li><a href="http://johannburkard.de/software/nativecall/" rel="noreferrer">http://johannburkard.de/software/nativecall/</a></li> <li><a href="http://www.jinvoke.com/" rel="noreferrer">http://www.jinvoke.com/</a></li> </ul> <p>On the Windows side, the function you're after is <a href="http://msdn.microsoft.com/en-us/library/aa363672(VS.85).aspx" rel="noreferrer">OpenEventLog</a>. This should allow you to access a remote event log. See also <a href="http://msdn.microsoft.com/en-us/library/bb427356(VS.85).aspx" rel="noreferrer">Querying for Event Information</a>.</p> <p>If that doesn't sound right, I also found this for parsing the log files directly (not an approach I'd recommend but interesting nonetheless):</p> <ul> <li><a href="http://msdn.microsoft.com/en-us/library/bb309026.aspx" rel="noreferrer">http://msdn.microsoft.com/en-us/library/bb309026.aspx</a></li> <li><a href="http://objectmix.com/java/75154-regarding-windows-event-log-file-parser-java.html" rel="noreferrer">http://objectmix.com/java/75154-regarding-windows-event-log-file-parser-java.html</a></li> </ul>
<p>If you want true event log access from a remote machine, you will have to find a library which implements the <a href="http://msdn.microsoft.com/en-us/library/cc231215.aspx" rel="nofollow noreferrer">EventLog Remoting Protocol Specification</a>. Unfortunately, I have not yet found any such library in Java. However, much of the foundation for implementing this protocol has already been laid by the JCIFS and JARAPAC projects. The protocol itself (if I'm not mistaken) runs on top of the DCE/RPC protocol (implemented by JARAPAC) which itself runs on top of the SMB protocol (implemented by JCIFS).</p> <p>I have already been using JCIFS and JARAPAC to implement some of EventLog's cousin protocols, such as remote registry access. I may be blind, but documentation seemed a little scarce regarding JARAPAC. If you are interested in implementing this, I can share with you what I have learned when I get some spare time!</p> <p>Later!</p>
39,985
<p>I need to find out the <strong>external</strong> IP of the computer a C# application is running on. </p> <p>In the application I have a connection (via .NET remoting) to a server. Is there a good way to get the address of the client on the server side?</p> <p><em>(I have edited the question, to be a little more clear. I'm apologize to all kind people who did their best to respond to the question, when I perhaps was a little too vague)</em></p> <p><strong>Solution:</strong><br> I found a way that worked great for me. By implementing a custom IServerChannelSinkProvider and IServerChannelSink where I have access to CommonTransportKeys.IPAddress, it's easy to add the client ip on the CallContext.</p> <pre><code>public ServerProcessing ProcessMessage(IServerChannelSinkStack sinkStack, IMessage requestmessage, ITransportHeaders requestHeaders, System.IO.Stream requestStream, out IMessage responseMessage, out ITransportHeaders responseHeaders, out System.IO.Stream responseStream) { try { // Get the IP address and add it to the call context. IPAddress ipAddr = (IPAddress)requestHeaders[CommonTransportKeys.IPAddress]; CallContext.SetData("ClientIP", ipAddr); } catch (Exception) { } sinkStack.Push(this, null); ServerProcessing srvProc = _NextSink.ProcessMessage(sinkStack, requestmessage, requestHeaders, requestStream, out responseMessage, out responseHeaders, out responseStream); return srvProc; } </code></pre> <p>And then later (when I get a request from a client) just get the IP from the CallContext like this.</p> <pre><code>public string GetClientIP() { // Get the client IP from the call context. object data = CallContext.GetData("ClientIP"); // If the data is null or not a string, then return an empty string. if (data == null || !(data is IPAddress)) return string.Empty; // Return the data as a string. return ((IPAddress)data).ToString(); } </code></pre> <p>I can now send the IP back to the client.</p>
<p>This is one of those questions where you have to look deeper and maybe rethink the original problem; in this case, "Why do you need an external IP address?"</p> <p>The issue is that the computer may not have an external IP address. For example, my laptop has an internal IP address (192.168.x.y) assigned by the router. The router itself has an internal IP address, but its "external" IP address is also internal. It's only used to communicate with the DSL modem, which actually has the external, internet-facing IP address.</p> <p>So the real question becomes, "How do I get the Internet-facing IP address of a device 2 hops away?" And the answer is generally, you don't; at least not without using a service such as whatismyip.com that you have already dismissed, or doing a really massive hack involving hardcoding the DSL modem password into your application and querying the DSL modem and screen-scraping the admin page (and God help you if the modem is ever replaced).</p> <p>EDIT: Now to apply this towards the refactored question, "How do I get the IP address of my client from a server .NET component?" Like whatismyip.com, the best the server will be able to do is give you the IP address of your internet-facing device, which is unlikely to be the actual IP address of the computer running the application. Going back to my laptop, if my Internet-facing IP was 75.75.75.75 and the LAN IP was 192.168.0.112, the server would only be able to see the 75.75.75.75 IP address. That will get it as far as my DSL modem. If your server wanted to make a separate connection back to my laptop, I would first need to configure the DSL modem and any routers inbetween it and my laptop to recognize incoming connections from your server and route them appropriately. There's a few ways to do this, but it's outside the scope of this topic.</p> <p>If you are in fact trying to make a connection out from the server back to the client, rethink your design because you are delving into WTF territory (or at least, making your application that much harder to deploy).</p>
<p>You can basically parse the page returned by doing a WebRequest of <a href="http://whatismyipaddress.com" rel="nofollow noreferrer">http://whatismyipaddress.com</a></p> <p><a href="http://www.dreamincode.net/forums/showtopic24692.htm" rel="nofollow noreferrer">http://www.dreamincode.net/forums/showtopic24692.htm</a></p>
9,188
<p>I'm hoping that it isn't to pass each as a parameter to the controller post method..</p> <p>Have a grid of 52 text boxes representing weeks in a year, each will be containing a decimal value, need ALL of these passed back to the controller for mass updating of the database..</p> <p>edit: Adding more details.</p> <p>So my action Index(); returns a view with a list of 52 objects in it.</p> <p>so </p> <p>return View(dates);</p> <p>inside the view I do a foreach for all the objects of that type in the model, and put their values into textboxes, I then want to change them and hit submit.</p> <p><strong>is there any way to get the updated list into my POST controller without having to give it 52 parameters with the id's of the textboxes?</strong></p> <p>Thanks a lot in advance!</p> <p>edit: Maybe there is a way I can post the forum to the controller and iterate through the textbox controls and get out id/value, any idea how?</p>
<p>I would suggestion using a Model Binder:</p> <p><a href="http://www.singingeels.com/Articles/Model_Binders_in_ASPNET_MVC.aspx" rel="nofollow noreferrer">http://www.singingeels.com/Articles/Model_Binders_in_ASPNET_MVC.aspx</a></p> <p><a href="http://www.singingeels.com/Articles/Model_Binders_in_ASPNET_MVC__Part_2.aspx" rel="nofollow noreferrer">http://www.singingeels.com/Articles/Model_Binders_in_ASPNET_MVC__Part_2.aspx</a></p>
<p>Hey, I got the solution I wanted after a bit of messing about. I just passed in the parameter "FormCollection myForm" and after a bit of exploring within that object I found my 52 values! Thanks for the help.</p> <p>edit: I deleted this due to peer pressure probably over a year ago... but looking back on it I don't see what the problem was, aside from answering my own question..</p>
42,157
<p>I have a MySQL table that will only have one row. What should my statement be for the first time I insert to this row, and for subsequent updates? I tried an insert where the primary key equals 1, but this doesn't account for the first time around when no row exists yet.</p>
<pre><code>INSERT INTO table(col1,col2,col3) VALUES(val1,val2,val3) ON DUPLICATE KEY UPDATE col1 = val1, col2 = val2, col3 = val3; </code></pre>
<p>If your table will only ever have one row, you might consider preloading initial data into the row in your database creation script. Then your code will only ever need to issue an UPDATE statement. Also, you will not need a primary key column because there is only ever one row. You can then issue UPDATE statements without needing a WHERE clause, too.</p>
37,614
<p>What are the things to consider when choosing between ByRef and ByVal.</p> <p>I understand the difference between the two but I don't fully understand if ByRef saves resources or if we even need to worry about that in the .Net environment.</p> <p>How do you decide between the two if the functionality doesn't matter in a situation?</p>
<p>There's a lot of misinformation around about this. The main thing is that you understand the <a href="http://pobox.com/~skeet/csharp/references.html" rel="noreferrer">difference between value types and reference types</a>, and the <a href="http://pobox.com/~skeet/csharp/parameters.html" rel="noreferrer">difference between pass by value and pass by reference</a>.</p> <p>You almost always want to pass by value. Passing by reference is almost always for "I want to return more than one result, and not just by adding things to a list which is passed in." The classic example of a method using pass-by-reference is <a href="http://msdn.microsoft.com/en-us/library/f02979c7.aspx" rel="noreferrer">Int32.TryParse</a> where the return value is a success/failure, and the parsed value is "returned" by an out parameter.</p>
<p>Marking certain arguments as ByRef shows the user of your function that the <strong>variable</strong> allocated to that argument **will be modified.****</p> <p><strong>If you use ByRef</strong> for all args, there'll be no way to tell which variables are modified by the function, and which are just read by it. <em>(apart from peeking inside the function source!)</em></p>
36,981
<p>I would like to be a PHP/MySQL programmer </p> <p>What are the technologies that I must know?</p> <p>Like:</p> <ol> <li>Frameworks</li> <li>IDEs</li> <li>Template Engines</li> <li>Ajax and CSS Frameworks</li> </ol> <p>Please tell me the minimum requirements that I must know, and tell me your favourite things in the previous list?</p> <p>Thanks</p>
<p>First off, there is <em>no</em> must know about learning PHP and MySQL... You go into it not knowing anything, and you'll come out of it knowing a bunch. If there was a must know, then nobody would be able to get into PHP and MySQL development. I personally think you are at a slight advantage going into this without knowing everything about it. It'll give you a fresh perspective and a think outside of the box attitude :)</p> <p>As far as the object oriented stuff in this thread, it's true. But, as others have said, it's completely up to the programmer (you) to decide how to write your code. You can use object oriented practices, make a spaghetti code junction, or just right a bunch of functions, or whatever. Either way, as everyone else has been saying, it's up to you :) </p> <p><strong>IRC channel:</strong></p> <p>Don't really need this, but I find it helpful... See you in here :)</p> <p>irc.freenode.net #php</p> <p><strong>Manual:</strong></p> <p>The manual is your friend and probably the only thing you <em>should</em> know before diving in.</p> <p><a href="http://www.php.net/manual/en/" rel="nofollow noreferrer">http://www.php.net/manual/en/</a></p> <p><a href="http://dev.mysql.com/doc/refman/5.0/en/apis-php.html" rel="nofollow noreferrer">http://dev.mysql.com/doc/refman/5.0/en/apis-php.html</a></p> <p><strong>Frameworks:</strong></p> <p>Make sure it's an MVC framework :)</p> <p><a href="http://www.cakephp.org/" rel="nofollow noreferrer">http://www.cakephp.org/</a></p> <p><a href="http://www.phpmvc.net/" rel="nofollow noreferrer">http://www.phpmvc.net/</a></p> <p><a href="http://www.codeigniter.com/" rel="nofollow noreferrer">http://www.codeigniter.com/</a></p> <p><a href="http://www.symfony.com/" rel="nofollow noreferrer">http://www.symfony.com/</a></p> <p><a href="http://www.laravel.com/" rel="nofollow noreferrer">http://www.laravel.com</a></p> <p><a href="http://www.yiiframework.com/" rel="nofollow noreferrer">http://www.yiiframework.com/</a></p> <p><strong>IDE:</strong></p> <p>Whatever suits you best :)</p> <p><a href="http://www.eclipse.org/" rel="nofollow noreferrer">http://www.eclipse.org/</a></p> <p><a href="http://www.vim.org/" rel="nofollow noreferrer">http://www.vim.org/</a></p> <p><a href="http://www.zend.com/en/products/studio/" rel="nofollow noreferrer">http://www.zend.com/en/products/studio/</a></p> <p><a href="http://php.netbeans.org/" rel="nofollow noreferrer">http://php.netbeans.org/</a></p> <p><a href="https://www.jetbrains.com/phpstorm/" rel="nofollow noreferrer">https://www.jetbrains.com/phpstorm/</a></p> <p><strong>Template engines:</strong></p> <p>PHP is a good template engine</p> <p>Model view controller frameworks help with this</p> <p><a href="http://twig.sensiolabs.org/" rel="nofollow noreferrer">twig.sensiolabs.org</a></p> <p><a href="http://www.smarty.net/" rel="nofollow noreferrer">http://www.smarty.net/</a></p> <p><strong>Ajax:</strong></p> <p><a href="http://jquery.com/" rel="nofollow noreferrer">http://jquery.com/</a></p> <p><a href="http://www.mootools.net/" rel="nofollow noreferrer">http://www.mootools.net/</a></p> <p><a href="http://developer.yahoo.com/yui/" rel="nofollow noreferrer">http://developer.yahoo.com/yui/</a></p> <p><a href="http://www.prototypejs.org/" rel="nofollow noreferrer">http://www.prototypejs.org/</a></p> <p><a href="http://www.extjs.com/" rel="nofollow noreferrer">http://www.extjs.com/</a></p> <p><a href="http://code.google.com/webtoolkit/" rel="nofollow noreferrer">http://code.google.com/webtoolkit/</a></p> <p><a href="https://angularjs.org/" rel="nofollow noreferrer">https://angularjs.org/</a></p> <p><strong>CSS:</strong></p> <p><a href="http://www.yaml.de/en/home.html" rel="nofollow noreferrer">http://www.yaml.de/en/home.html</a></p> <p><a href="http://code.google.com/p/blueprintcss/" rel="nofollow noreferrer">http://code.google.com/p/blueprintcss/</a></p> <p><a href="http://developer.yahoo.com/yui/reset/" rel="nofollow noreferrer">http://developer.yahoo.com/yui/reset/</a></p> <p>Definitely not an exhaustive list, and things change constantly... But, it's a start :)</p> <p>Have fun!</p> <p>Chrelad</p>
<p>You should know how to use effectively at least one Debugger/IDE. It is amazing what you can learn from your code by stepping through it and watching it run. It both makes it much simpler to track down bugs, and improves the quality of your code. I believe you should never commit code to a project that you haven't seen execute. </p>
39,426
<p>I have an application that needs to hit the ActiveDirectory to get user permission/roles on startup of the app, and persist throughout. </p> <p>I don't want to hit AD on every form to recheck the user's permissions, so I'd like the user's role and possibly other data on the logged-in user to be globally available on any form within the application, so I can properly hide functionality, buttons, etc. where necessary.</p> <p>Something like:</p> <pre><code>if (UserProperties.Role == Roles.Admin) { btnDelete.Visible = false; } </code></pre> <p>What are the best practices for storing static user data in a windows app? Solutions such as a Singleton, or global variables may work, but I was trying to avoid these.</p> <p>Is a User object that gets passed around to each form's contructor just as bad?</p>
<p>Set <a href="http://msdn.microsoft.com/en-us/library/system.threading.thread.currentprincipal.aspx" rel="nofollow noreferrer">Thread.CurrentPrincipal</a> with either the <a href="http://msdn.microsoft.com/en-us/library/system.security.principal.windowsprincipal.aspx" rel="nofollow noreferrer">WindowsPrincipal</a>, a <a href="http://msdn.microsoft.com/en-us/library/system.security.principal.genericprincipal.aspx" rel="nofollow noreferrer">GenericPrincipal</a> or your custom principal. Then, you can just call <a href="http://msdn.microsoft.com/en-us/library/system.security.principal.iprincipal.isinrole.aspx" rel="nofollow noreferrer">IsInRole</a>:</p> <pre><code>if (Thread.CurrentPrincipal.IsInRole(Roles.Admin)) { btnDelete.Visible = false; } </code></pre>
<p>You can use the Profile provider from the asp.net in you Windows App. Check it out @ <a href="http://fredrik.nsquared2.com/viewpost.aspx?PostID=244&amp;showfeedback=true" rel="nofollow noreferrer">http://fredrik.nsquared2.com/viewpost.aspx?PostID=244&amp;showfeedback=true</a></p> <p>Hope it helps, Bruno Figueiredo <a href="http://www.brunofigueiredo.com" rel="nofollow noreferrer">http://www.brunofigueiredo.com</a></p>
34,391
<p>We want to maintain 3 webservices for the different steps of deployment, but how do we define in our application which service to use? Do we just maintain 3 web references and ifdef the uses of them somehow?</p>
<p>Don't maintain the differences in code, but rather through a configuration file. That way they're all running the same code, just with different configuration values (ie. port to bind to, hostname to answer to, etc.)</p>
<p>Put the service address and port into your application's configuration. It's probably a good idea to do the same thing in the service's config, at least for the port, so that your dev service listens on the right port. This way you don't have to modify your code just to change the server/port you're hitting.</p> <p>Using config rather than code for switching between dev, stage, and production is very valuable for testing. When you deploy to production you want to make sure you're deploying the same exact code that was tested, not something slightly different. All you should change between dev and production is the config.</p>
13,093
<p>I'm talking about <a href="http://en.wikipedia.org/wiki/Quality_of_service" rel="noreferrer">http://en.wikipedia.org/wiki/Quality_of_service</a>. With streaming stackoverflow podcasts and downloading the lastest updates to ubuntu, I would like to have QoS working so I can use stackoverflow without my http connections timing out or taking forever.</p> <p>I'm using an iConnect 624 ADSL modem which has QoS built-in but I can't seem to get it to work. Is it even possible to control the downstream (ie. from ISP to your modem)?</p>
<p>I don't know if this will help you, but I've never been a fan of using the ISP provided box directly. Personally I use a <a href="http://www.newegg.com/Product/ProductList.aspx?Submit=ENE&amp;DEPA=0&amp;Description=wrt54gl&amp;x=0&amp;y=0" rel="nofollow noreferrer">Linksys wrt54gl</a>, with <a href="http://www.dd-wrt.com" rel="nofollow noreferrer">DD-wrt</a>, behind(DMZ) my ISP provided box.</p> <p>DD-wrt has excellent QoS management.</p> <p>Sorry I can't be more help with your existing hardware. </p>
<p>You just need the <a href="http://www.arvanta.net/~mps/linux-tc.html" rel="nofollow noreferrer">tc command</a> to handle the QoS on Linux boxen. However I wouldn't expect that much from it because of the results I obtained and <a href="https://stackoverflow.com/questions/583532/software-router-traffic-monitoring/583987#583987">detailed here</a>.</p>
2,656
<p>I am writing multi-thread socket chat in C++Builder 2009.<br> It is almost complete in accordance with what I need to do but I have a little problem. I need to pass the TMemo* pointer into CreateThread WinAPI function which upcasts it to void*.</p> <p>I tryed this way:<br></p> <pre><code>HANDLE xxx = MemoChat-&gt;Handle; hNetThread = CreateThread(NULL, 0, NetThread, xxx, 0, &amp;dwNetThreadId); //... </code></pre> <p>and then, in NetThread function,</p> <pre><code>TMemo* MyMemo((HANDLE)lpParam); TMemo* MyMemo((TMemo*)lpParam); </code></pre> <p>but it didn`t work:(</p> <p>The question is how I can really downcast it correctly so I can use my Memo Component in this new thread?</p>
<p>Call:</p> <pre><code>TMemo* MemoChat = // You defined that somewhere I assume HANDLE hNetThread = CreateThread(NULL, 0, NetThread, MemoChat, 0, &amp;dwNetThreadId); </code></pre> <p>What is happening here is that any pointer you pass as the third parameter is being auto converted into a void pointer (or in WinTerms LPVOID). That's fine it does not change it it just loses the type information as the system does not know anything about your object. </p> <p>The new Thread Start point:</p> <pre><code>DWORD NetThread(LPVOID lpParameter) { TMemo* MemoChat = reinterpret_cast&lt;TMemo*&gt;(lpParameter); // Do your thread stuff here. } </code></pre> <p>Once your thread start method is called. Just convert the void pointer back into the correct type and you should be able to start using it again.</p> <p>Just to clear up other misconceptions.</p> <p>A <b>HANDLE is a pointer</b>.<br> And you could have passed it as the parameter to the NetThread().</p> <p>A HANDLE is a pointer to pointer under system control which points at the object you are using. So why the double indirection. It allows the system to move the object (and update its pointer) without finding all owners of the object. The owners all have handles that point at the pointer that was just updated.</p> <p>It is an old fashioned computer science concept that is used infrequently in modern computers because of the OS/Hardware ability to swap main memory into secondary storage. but for certain resource they are still useful. Nowadays when handles are required they are hidden inside objects away from the user. </p>
<p>This is more to try and clarify the handle vs. pointer thing, because I don't think Martin has it exactly right.</p> <p>A "pointer to a pointer" is indeed called a HANDLE, and is a common CS approach to allowing the operating system to physically move heap-allocated memory blocks around without the explicit knowledge of an application layer, which always accesses them via handles. Classic 68K Mac OS works in this way. OS'es that work in this way typically allow user code to allocate memory via handles as well as directly off the heap. This approach is used on machines that don't have proper memory-management hardware.</p> <p>However,there are other uses of the word HANDLE which borrow the some of the abstraction of the previous use, but with different implementations. Opaque pointers (pointers to datastructures of which the user has no knowledge - PIMPL idiom) are also commonly called HANDLES. </p> <p>Also, the term HANDLE can be used simply to denote a "reference" to an object - maybe an index into an array. Unix File Handles (= file descriptors) are a good example of this. stdin=0,stdout=1,...</p> <p>So, which of the above are Windows API HANDLES? I've seen conflicting reports. <a href="http://www.stanford.edu/class/cs193w/handouts/h04-naming.pdf" rel="nofollow noreferrer">This document</a> says:</p> <blockquote> <p>Handles in Win32 are numbers used to identify resources or windows. They are not pointers or pointers to pointers. Think of them as ID numbers.</p> </blockquote>
34,630
<p>I have a project that I'm currently working on but it currently only supports the .net framework 2.0. I love linq, but because of the framework version I can't use it. What I want isn't so much the ORM side of things, but the "queryability" (is that even a word?) of Linq. </p> <p>So far the closest is <a href="http://www.llblgen.com/defaultgeneric.aspx" rel="nofollow noreferrer">llblgen</a> but if there was something even lighter weight that could just do the querying for me that would be even better.</p> <p>I've also looked at <a href="http://www.hibernate.org/343.html" rel="nofollow noreferrer">NHibernate</a> which looks like it could go close to doing what I want, but it has a pretty steep learning curve and the mapping files don't get me overly excited.</p> <p>If anyone is aware of something that will give me a similar query interface to Linq (or even better, how to get Linq to work on the .net 2.0 framework) I'd really like to hear about it.</p>
<p>Have a look at this:</p> <p><a href="http://www.albahari.com/nutshell/linqbridge.html" rel="noreferrer">http://www.albahari.com/nutshell/linqbridge.html</a></p> <p>Linq is several different things, and I'm not 100% sure which bits you want, but the above might be useful in some way. If you don't already have a book on Linq (I guess you don't), then I found "Linq In Action" to be be good.</p>
<p>There's a way to reference LINQ in the .NET 2.0 Framework, but I have to warn you that it <em>might</em> be against the terms of use/EULA of the framework:</p> <p><a href="https://stackoverflow.com/questions/2138/linq-on-the-net-20-runtime#2146">LINQ on the .NET 2.0 Runtime</a></p>
2,921
<p>When writing a T-SQL script that I plan on re-running, often times I use temporary tables to store temporary data. Since the temp table is created on the fly, I'd like to be able to drop that table only if it exists (before I create it).</p> <p>I'll post the method that I use, but I'd like to see if there is a better way.</p>
<pre><code>IF Object_Id('TempDB..#TempTable') IS NOT NULL BEGIN DROP TABLE #TempTable END </code></pre>
<pre><code>SELECT name FROM sysobjects WHERE type = 'U' AND name = 'TempTable' </code></pre>
2,476
<p>I'm wondering if there is an easy way to load data from analysis services (SSAS) into SPSS.</p> <p>SPSS offers a product to put SPSS functionality on the analysis server, but to me this is backwards. I don't want to learn about SPSS or have the SPSS users in the office learn something else. </p> <p>I just want to give the analysis services data to the SPSS users in SPSS. </p>
<p>You would be better just to point SSPS at the relational datasource that SSAS is using. SSAS is not designed for doing bulk exporting of data. Evne if we did figure out a series of queries it would be many times slower than just querying the original source.</p>
<p>SSAS has actions. You can fire an action which calls VB.net or c# code to format and import data into SPSS.</p>
22,867
<p>I'm working on a web-based contest which is supposed to allow anonymous users to vote, but we want to prevent them from voting more than once. IP based limits can be bypassed with anonymous proxies, users can clear cookies, etc. It's possible to use a Silverlight application, which would have access to isolated storage, but users can still clear that.</p> <p>I don't think it's possible to do this without some joker voting himself up with a bot or something. Got an idea?</p>
<p>The short answer is: no. The longer answer is: but you can make it arbitrarily difficult. What I would do:</p> <ul> <li>Voting requires solving a captcha (to avoid as much as possible automated voting). To be even more effective I would recommend to have prepared multiple types of simple captchas (like "pick the photo with the cat", "what is 2+2", "type in the word", etc) and rotate them both by the time of the day and by IP, which should make automatic systems ineffective (ie if somebody using IP A creates a bot to solve the captcha, this will become useless the next day or if s/he distributes it onto other computers/uses proxies)</li> <li>When filtering by IP you should be careful to consider situations where multiple hosts are behind one public IP (AFAIK AOL proxies all of their customers through a few IPs - so such a limitation would effectively ban AOL users). Also, many proxies send along headers pointing to the original IP (like X-Forwarded-For), so you can take a look at that too.</li> <li>Finally, using something like FSO (Flash Shared Objects - "Flash cookies") is obscure enough for 99.99% of the people not to know about. Silverlight is even more obscure. To be even sneakier, you could buy an other domain and set the FSO from that domain (so, if the user is looking for FSO's set by your domain, they won't see any)</li> </ul> <p>None of these methods is 100%, but hopefully combined they give you the level of assurance you need. If you want to take this a level higher, you need to add some kind of user registration (which can be as simple as asking a valid e-mail address when the vote occurs and sending a confirmation link to the given address and not counting the votes for which the link wasn't clicked - so it doesn't need to be a full-fledged "create an account with username / password / firs name / last name / etc").</p>
<p>Nope, it's the user's computer and they're in control. Unfortunately the only solution is to bring it back on your court so to speak and require authentication.</p> <p>However, a CAPTCHA helps limit the votes to human users at least.</p> <p>Of course even with authentication you can't enforce single voting because then they teach the bots to register...</p>
7,965
<p>Based on the advice provided at <a href="http://www.tweakguides.com/VA_4.html" rel="nofollow noreferrer">http://www.tweakguides.com/VA_4.html</a> to prevent Windows Vista from "intelligently" rearranging column formats in Windows Explorer, I have written a script to automate the process a little.</p> <pre><code>Dim WshShell Set WshShell = WScript.CreateObject("WScript.Shell") 'Remove the "filthy" reg keys first. regKey = "HKCU\Software\Classes\Local Settings\Software\Microsoft\Windows\Shell\BagMRU\" WScript.Echo "Deleting " &amp; regKey &amp; VbCrLf WshShell.RegDelete regKey regKey = "HKCU\Software\Classes\Local Settings\Software\Microsoft\Windows\Shell\Bags\" WScript.Echo "Deleting " &amp; regKey &amp; VbCrLf WshShell.RegDelete regKey 'Then recreate a clean Bags key, with sub-keys and FolderType value. regKey = "HKCU\Software\Classes\Local Settings\Software\Microsoft\ Windows\Shell\Bags\AllFolders\Shell\FolderType" WScript.Echo "Creating " &amp; regKey &amp; " as 'NotSpecified' REG_SZ " &amp; VbCrLf WshShell.RegWrite regKey, "NotSpecified", "REG_SZ" WScript.Echo "Now define the columns of your preference in Windows Explorer," &amp; VbCrLf WScript.Echo "and click the Apply to Folders button in Folder Options." &amp; VbCrLf </code></pre> <p>But it is refusing to delete the registry key</p> <pre><code>E:\archive\settings\Windows Vista Explorer columns.vbs(9, 1) WshShell.RegDelete: Unable to remove registry key "HKCU\Software\Classes\Local Settings\Software\Mi crosoft\Windows\Shell\BagMRU\". </code></pre> <p>The suggestion is to put trailing "\" to indicate a key, which I did. Any ideas?</p>
<p>Does your registry setting have subkeys? I think you have to delete those before you can delete the key.</p>
<p>Disable UAC in Windows Vista, then this script will just work fine.</p>
39,076
<p>When using Google Reader and browsing RSS entries in the "Expanded" view, entries will automatically be marked as 'read' once a certain percentage of the div is visible on the screen (difficult to tell what percentage has to be visible in the case of Google Reader). So, as I scroll down line-by-line, the javascript code can determine that a) the entry is being rendered in the visible window and b) a certain amount is visible and when those conditions are met, the state is toggled to read.</p> <p>Does anyone have any idea how that feature is implemented? Specifically, does anyone here know how to tell if a div has scrolled into view an how much of the div is visible?</p> <p>As an aside, I'm using jQuery, so if anyone has any jQuery-specific examples, they would be much appreciated.</p>
<p>The real trick is to keep track of where the scrollbar is in the element containing your items. Here's some code I once whipped up to do it: <a href="http://pastebin.com/f4a329cd9" rel="nofollow noreferrer">http://pastebin.com/f4a329cd9</a></p> <p>You can see that as you scroll it changes focus. You just need to add more handler code to the function that handles each focus change. It works scrolling in both direction, and also by clicking right on the scrollbar, which simple mouse tracking won't give you (though in this case since the example elements are all the same size, with the same text, it's hard to tell that it has indeed scrolled). The other issue is what to do when the container bottoms out. The solution I have right now only works in FF. If you want to have it look nice in IE, you'll have to use a dummy element that blends into the background, like the one I have commented out in the code.</p>
<p>In my experience, Reader has only ever marked something as read if I have moused-over or clicked on it. Assuming that as you scroll your mouse is over the div (I tend to put my mouse to the right edge of the screen when I scroll) that might explain the appearance that it only gets marked off when a certain % has been shown. </p> <p>I could be (and likely am) wrong, though. I just know that the act of just scrolling through my items in reader does not mark them off. I have to make sure the mouse mouses over them as it scrolls to do it.</p>
46,128
<p>I'm running into a problem trying to anchor a textbox to a form on all 4 sides. I added a textbox to a form and set the Multiline property to True and the Anchor property to Left, Right, Up, and Down so that the textbox will expand and shrink with the form at run time. I also have a few other controls above and below the textbox. </p> <p>The anchoring works correctly in Visual Studio 2005 (i.e. I can resize the form and have the controls expand and shrink as expected), but when I run the project, the bottom of the textbox is extended to the bottom of the form, behind the other controls that would normally appear beneath it. This problem occurs when the form loads, before any resizing is attempted. The anchoring of the textbox is correct for the top, left, and right sides; only the bottom is malfunctioning. </p> <p>Has anybody heard of this and if so, were you able to find a solution?</p> <p>Thanks!</p> <p>UPDATE:</p> <p>Here is some of the designer code as per Greg D's request (I am only including the stuff that had to do with the textbox itself, not the other controls):</p> <pre><code>Friend WithEvents txtRecommendationText1 As System.Windows.Forms.TextBox &lt;System.Diagnostics.DebuggerStepThrough()&gt; _ Private Sub InitializeComponent() Me.txtRecommendationText1 = New System.Windows.Forms.TextBox ' ...snip... 'txtRecommendationText1 Me.txtRecommendationText1.Anchor = CType((((System.Windows.Forms.AnchorStyles.Top Or System.Windows.Forms.AnchorStyles.Bottom) _ Or System.Windows.Forms.AnchorStyles.Left) _ Or System.Windows.Forms.AnchorStyles.Right), System.Windows.Forms.AnchorStyles) Me.txtRecommendationText1.Location = New System.Drawing.Point(4, 127) Me.txtRecommendationText1.Multiline = True Me.txtRecommendationText1.Name = "txtRecommendationText1" Me.txtRecommendationText1.Size = New System.Drawing.Size(223, 149) Me.txtRecommendationText1.TabIndex = 10 End Sub </code></pre> <p>ANOTHER UPDATE:</p> <p>The textbox I originally posted about was not inherited from a baseclass form (although it was added to a custom User Control class; I probably should have mentioned that earlier), but I recently ran into the same problem on a totally unrelated set of controls that were inherited from a baseclass form. It's easy to blame these problems on possible bugs in the .NET framework, but it's really starting to look that way to me. </p>
<p>The textbox I originally posted about was not inherited from a baseclass form (although it was added to a custom User Control class; I probably should have mentioned that earlier), but I recently ran into the same problem on a totally unrelated set of controls that were inherited from a baseclass form. It's easy to blame these problems on possible bugs in the .NET framework, but it's really starting to look that way to me.</p>
<p>Does the form snap back to the expected layout when you resize it after it's been initialized weirdly? Also, have you set a Height or MinimumHeight/MaximumHeight property for the text box?</p> <p>If possible, a few snippets from the designer code might be useful. :)</p> <p>One possibility that I've run into in the past is DPI. If you're running/testing your code on a machine with a different DPI setting than the machine that you're developing on, you may observe some strange things.</p> <p>The anchor functionality essentially establishes a fixed distance between the edge of a control and the edge of the control's parent. Is your textbox embedded within another control (e.g., a panel) that doesn't have its anchors properly set? Right clicking on the text box in the designer should pop up a menu that lets you select any controls that exist underneath it, also.</p> <p>Does your program include any custom resize logic, or does it modify the size of the textbox programmatically outside of designer-generated code? That might also result in weird behavior. I've assumed maintenance for a number of pieces of software at my organization where the original developers spent a great deal of time implementing (buggy) resize logic that I had to tear out so that I could just let the designer-generated code do the work for me.</p>
41,184
<p>I set up my svn in assembla, and I code and test on my local machine that is set up identical to the production server. THen, I commit changes to assembla svn and also ftp upload to my production server.</p> <p>How can I improve my workflow? I would like to keep my svn on assembla because I can often move to another production server.</p> <p>Thank you very much!</p>
<p>Better way is to build nant or MSBuild script that will do all dirty work automated. Those scripts also can ftp upload.</p> <p>I've using on production server script to checkout last changes from svn, build and sync with production folder.</p>
<p>If you're working with interpreted languages like PHP, Python or Ruby for example, you can do a clean <a href="http://svnbook.red-bean.com/en/1.0/re10.html" rel="nofollow noreferrer">svn export</a> directly from your repository to the production server, instead of uploading by ftp the source files from your machine. </p> <p>You'll need shell access to your production server. </p>
47,638
<p>I can write a trivial script to do this but in my ongoing quest to get more familliar with unix I'd like to learn efficient methods using built in commands instead.</p> <p>I need to deal with very large files that have a variable number of header lines. the last header line consists of the text 'LastHeaderLine'. I wish to output everything after this line. (I'm not worried about false positive matches.)</p>
<p>Similar to the answer of <a href="https://stackoverflow.com/questions/197150/skip-file-lines-until-a-match-is-found-then-output-the-rest#197169">Avi</a>, but without including the line with "LastHeaderLine".</p> <pre><code>sed -e '1,/LastHeaderLine/d' </code></pre>
<p>Using sed:</p> <pre><code>sed -ne '/LastHeaderLine/,$p' &lt;inputfile </code></pre> <p>will match everything from the regex match to the end of the file. 'p' prints the lines that match.</p> <p>Edit:</p> <p>On second thought, you don't want to print the line matching LastHeaderLine. This is difficult to do with sed. In perl, you could do the following:</p> <pre><code>perl -ne 'if ($flag) {print;} if (/LastHeaderFile/) {$flag=1;}' &lt;inputfile </code></pre> <p>This would print only lines strictly following the regex match.</p>
23,975
<p>Does anyone have any suggestions as to how I can clean the body of incoming emails? I want to strip out disclaimers, images and maybe any previous email text that may be also be present so that I am left with just the body text content. My guess is it isn't going to be possible in any reliable way, but has anyone tried it? Are there any libraries geared towards this sort of thing?</p>
<p>In email, there is couple of agreed markings that mean something you wish to strip. You can look for these lines using <a href="http://www.regular-expressions.info/" rel="noreferrer">regular expressions</a>. I doubt you can't really well &quot;sanitize&quot; your emails, but some things you can look for:</p> <ol> <li>Line starting with &quot;&gt; &quot; (greater than then whitespace) marks a quote</li> <li>Line with &quot;-- &quot; (two hyphens then whitespace then linefeed) marks the beginning of a signature, see <a href="http://en.wikipedia.org/wiki/Signature_block" rel="noreferrer">Signature block on Wikipedia</a></li> <li>Multipart messages, boundaries start with <strong>--</strong>, beyond that you need to do some searching to separate the message body parts from unwanted parts (like base64 images)</li> </ol> <p>As for an actual C# implementation, I leave that for you or other SOers.</p>
<p>If you creating your own application i'd look into Regex, to find text and replace it. To make the application a little nice, i'd create a class Called Email and in that class i have a property called RAW and a property called Stripped.</p> <p>Just some hints, you'll gather the rest when you look into regex!</p>
47,875
<p>I'd like to use sqlmetal to generate dbml data contexts for my project, but the data context and all classes created are marked as <code>public</code>. As this is supposed to be an API layer I'd like to instead mark many of these classes or at least the context itself as <code>internal</code>. Is there a way to do this in sqlmetal or some other tool without having to go in and edit the dbml by hand?</p>
<p>I believe this is one of the options that you can't do directly at the command line. You may indeed have to edit the dbml. However, this isn't a tricky change, so you should be able to automate it with a basic command-line tool.</p>
<p>You could try using my <a href="http://damieng.com/blog/2008/09/14/linq-to-sql-template-for-visual-studio-2008" rel="nofollow noreferrer">LINQ to SQL template</a> that provides a drop-in replacement for the DBML to C#/VB.NET code generation process that you can completely customize.</p> <p>[)amien</p>
45,991
<p>I have always written regexes like this</p> <pre><code>&lt;A HREF="([^"]*)" TARGET="_blank"&gt;([^&lt;]*)&lt;/A&gt; </code></pre> <p>but I just learned about this <a href="http://www.regular-expressions.info/examples.html" rel="nofollow noreferrer">lazy thing</a> and that I can write it like this</p> <pre><code>&lt;A HREF="(.*?)" TARGET="_blank"&gt;(.*?)&lt;/A&gt; </code></pre> <p>is there any disadvantage to using this second approach? The regex is definitely more compact (even SO parses it better).</p> <p><strong>Edit</strong>: There are two best answers here, which point out two important differences between the expressions. ysth's answer points to a weakness in the non-greedy/lazy one, in which the hyperlink itself could possibly include other attributes of the A tag (definitely not good). Rob Kennedy points out a weakness in the greedy example, in that anchor texts cannot include other tags (definitely not okay, because it wouldn't grab all the anchor text either)... so the answer is that, regular expressions being what they are, lazy and non-lazy solutions that seem the same are probably not semantically equivalent.</p> <p><strong>Edit</strong>: Third best answer is by Alan M about relative speed of the expressions. For the time being, I'll mark his as best answer so people give him more points :) </p>
<p>Another thing to consider is how long the target text is, and how much of it is going to be matched by the quantified subexpression. For example, if you were trying to match the whole &lt;BODY> element in a large HTML document, you might be tempted to use this regex:</p> <pre><code>/&lt;BODY&gt;.*?&lt;\/BODY&gt;/is </code></pre> <p>But that's going to do a whole lot of unnecessary work, matching one character at a time while effectively doing a negative lookahead before each one. You know the &lt;/BODY> tag is going to be very near the end of the document, so the smart thing to do is to use a normal greedy quantitier; let it slurp up the whole rest of the document and then backtrack the few characters necessary to match the end tag.</p> <p>In most cases you won't notice any speed difference between greedy and reluctant quantifiers, but it's something to keep in mind. The main reason why you should be judicious in your use of reluctant quantifiers is the one that was pointed out by the others: they may do it reluctantly, but they will match more than you want them to if that's what it takes to achieve an overall match.</p>
<p>“lazy” is the wrong word here. You mean non-greedy as opposed to greedy. There's no disadvantage in using it, that I know of. But in your special case, neither should it be <em>more</em> efficient.</p>
47,874
<p>What's your preferred method of providing a search facility on a website? Currently I prefer to use <a href="http://incubator.apache.org/lucene.net/" rel="noreferrer" title="Lucene.net">Lucene.net</a> over Indexing Service / SQL Server full-text search (as there's nothing to set up server-side), but what other ways are being used out there?</p>
<p>We used both Lucene.net, Indexing Service and SQL Server full-text. For a project with large and heavy DB search functionality SQL search has an upper hand in terms of performance/resource hit. Otherwise Lucene is much better in all aspects.</p>
<p>you could use google, it's not going to be the fastest indexer but it does provide great results when you have no budget.</p>
14,716
<p>I'm having a hard time understanding some git/DCVS concepts. Here's what happened:</p> <ol> <li>I created a git project, and imported it from an SVN repo</li> <li>I made some commits</li> <li>I wanted to experiment something, so I created a branch called <strong>constants-update</strong></li> <li>I switched to <strong>constants-update</strong>branch, moved some files, deleted others and added many more</li> <li>I committed to this branch</li> <li>Now I'm trying to switch to my master branch using <code>git checkout master</code></li> <li>I got this error: <strong>error: You have local changes to 'src/groovy/Constants.groovy'; cannot switch branches.</strong></li> </ol> <p>My understanding of DCVS is that I can switch branches at will, even if some branch has more or less files than the others, as long as I commit my files. I've tried committing with <code>git commit -a</code> and switching to master branch, but I have the same error. </p> <p>As a side note, when I commit git warns me that LF will be replaced by CRLF and warns me about some trailing whitespaces also; after I commit I do a <code>git status</code> and a bunch of files always appear as <code>#modified ...</code>.</p> <p>Is this related to git/<strong>windows</strong>, or I do not understand correctly what it is supposed to happen? I just want to switch to my master branch <strong>without losing my changes</strong> in the other branch.</p>
<p>I solved the problem <a href="http://www.dont-panic.cc/capi/2007/07/13/git-on-windows-you-have-some-suspicious-patch-lines/" rel="nofollow noreferrer">hacking my pre-commit hook</a> (commenting these lines in <code>.git/hooks/pre-commit</code> with a <code>#</code>):</p> <pre><code># if (/\s$/) { # bad_line("trailing whitespace", $_); # } </code></pre>
<p>Lookup git-stash for changing branches while there are unsaved changes in the current branch.</p>
32,174
<p>I am porting an MFC application to .NET WinForms. In the MFC application, you can right click on a menu or on a context menu item and we show another context menu with diagnostic and configuration items. I am trying to port this functionality to .NET, but I am having trouble.</p> <p>I have been able to capture the right click, disable the click of the underlying menu and pop up a context menu at the right location, but the original menu disappears as soon as it loses focus.</p> <p>In MFC, we show the new context menu by calling <strong>TrackPopupMenuEx</strong> with the <strong>TPM_RECURSE</strong> flag.</p> <p><strong>ContextMenu</strong> and the newer <strong>ContextMenuStrip</strong> classes in .NET only have a <em>Show</em> method. Does anyone know how to do this in .NET?</p> <p><strong>EDIT</strong></p> <p>I have tried using <strong>TrackPopupMenuEx</strong> through a p/invoke, but that limits you to using a ContextMenu instead of a ContextMenuStrip which looks out of place in our application. It also still does not work correctly. It doesn't work with the new <strong>MenuStrip</strong> and <strong>ContextMenuStrip</strong>.</p> <p>I have also tried subclassing ToolStripMenuItem to see if I can add a context menu to it. That is working for <strong>MenuStrip</strong>, but <strong>ContextMenuStrip</strong> still allows the right click events to pass through as clicks.</p>
<p>Edit, due to a comment:</p> <p>In:</p> <pre><code>protected override void OnClick(EventArgs e) { if (SecondaryContextMenu == null || MouseButtons != MouseButtons.Right) { base.OnClick(e); } } </code></pre> <p>this part </p> <pre><code> MouseButtons != MouseButtons.Right </code></pre> <p>should and does compile as it is a call to Control.MouseButtons. Since the Form inherits Control class, it is sufficient to call MouseButtons property directly.</p> <p>Hope this helps: </p> <pre><code>public partial class Form1 : Form { class CustomToolStripMenuItem : ToolStripMenuItem { private ContextMenuStrip secondaryContextMenu; public ContextMenuStrip SecondaryContextMenu { get { return secondaryContextMenu; } set { secondaryContextMenu = value; } } public CustomToolStripMenuItem(string text) : base(text) { } protected override void Dispose(bool disposing) { if (disposing) { if (secondaryContextMenu != null) { secondaryContextMenu.Dispose(); secondaryContextMenu = null; } } base.Dispose(disposing); } protected override void OnClick(EventArgs e) { if (SecondaryContextMenu == null || MouseButtons != MouseButtons.Right) { base.OnClick(e); } } } class CustomContextMenuStrip : ContextMenuStrip { private bool secondaryContextMenuActive = false; private ContextMenuStrip lastShownSecondaryContextMenu = null; protected override void Dispose(bool disposing) { if (disposing) { if (lastShownSecondaryContextMenu != null) { lastShownSecondaryContextMenu.Close(); lastShownSecondaryContextMenu = null; } } base.Dispose(disposing); } protected override void OnControlAdded(ControlEventArgs e) { e.Control.MouseClick += new MouseEventHandler(Control_MouseClick); base.OnControlAdded(e); } protected override void OnControlRemoved(ControlEventArgs e) { e.Control.MouseClick -= new MouseEventHandler(Control_MouseClick); base.OnControlRemoved(e); } private void Control_MouseClick(object sender, MouseEventArgs e) { ShowSecondaryContextMenu(e); } protected override void OnMouseClick(MouseEventArgs e) { ShowSecondaryContextMenu(e); base.OnMouseClick(e); } private bool ShowSecondaryContextMenu(MouseEventArgs e) { CustomToolStripMenuItem ctsm = this.GetItemAt(e.Location) as CustomToolStripMenuItem; if (ctsm == null || ctsm.SecondaryContextMenu == null || e.Button != MouseButtons.Right) { return false; } lastShownSecondaryContextMenu = ctsm.SecondaryContextMenu; secondaryContextMenuActive = true; ctsm.SecondaryContextMenu.Closed += new ToolStripDropDownClosedEventHandler(SecondaryContextMenu_Closed); ctsm.SecondaryContextMenu.Show(Cursor.Position); return true; } void SecondaryContextMenu_Closed(object sender, ToolStripDropDownClosedEventArgs e) { ((ContextMenuStrip)sender).Closed -= new ToolStripDropDownClosedEventHandler(SecondaryContextMenu_Closed); lastShownSecondaryContextMenu = null; secondaryContextMenuActive = false; Focus(); } protected override void OnClosing(ToolStripDropDownClosingEventArgs e) { if (secondaryContextMenuActive) { e.Cancel = true; } base.OnClosing(e); } } public Form1() { InitializeComponent(); CustomToolStripMenuItem itemPrimary1 = new CustomToolStripMenuItem("item primary 1"); itemPrimary1.SecondaryContextMenu = new ContextMenuStrip(); itemPrimary1.SecondaryContextMenu.Items.AddRange(new ToolStripMenuItem[] { new ToolStripMenuItem("item primary 1.1"), new ToolStripMenuItem("item primary 1.2"), }); CustomToolStripMenuItem itemPrimary2 = new CustomToolStripMenuItem("item primary 2"); itemPrimary2.DropDownItems.Add("item primary 2, sub 1"); itemPrimary2.DropDownItems.Add("item primary 2, sub 2"); itemPrimary2.SecondaryContextMenu = new ContextMenuStrip(); itemPrimary2.SecondaryContextMenu.Items.AddRange(new ToolStripMenuItem[] { new ToolStripMenuItem("item primary 2.1"), new ToolStripMenuItem("item primary 2.2"), }); CustomContextMenuStrip primaryContextMenu = new CustomContextMenuStrip(); primaryContextMenu.Items.AddRange(new ToolStripItem[]{ itemPrimary1, itemPrimary2 }); this.ContextMenuStrip = primaryContextMenu; } } </code></pre>
<p>This shows how to use multiple ContextMenus as well as different ones with any combination of mouse clicks.</p> <p>More here: <a href="http://code.msdn.microsoft.com/TheNotifyIconExample" rel="nofollow noreferrer">http://code.msdn.microsoft.com/TheNotifyIconExample</a></p>
35,671
<p>I am about to build a piece of a project that will need to construct and post an XML document to a web service and I'd like to do it in Python, as a means to expand my skills in it. </p> <p>Unfortunately, whilst I know the XML model fairly well in .NET, I'm uncertain what the pros and cons are of the XML models in Python. </p> <p>Anyone have experience doing XML processing in Python? Where would you suggest I start? The XML files I'll be building will be fairly simple.</p>
<p>Personally, I've played with several of the built-in options on an XML-heavy project and have settled on <a href="http://docs.python.org/lib/module-xml.dom.pulldom.html" rel="noreferrer">pulldom</a> as the best choice for less complex documents.</p> <p>Especially for small simple stuff, I like the event-driven theory of parsing rather than setting up a whole slew of callbacks for a relatively simple structure. <a href="http://www.prescod.net/python/pulldom.html" rel="noreferrer">Here is a good quick discussion of how to use the API</a>.</p> <p>What I like: you can handle the parsing in a <code>for</code> loop rather than using callbacks. You also delay full parsing (the "pull" part) and only get additional detail when you call <code>expandNode()</code>. This satisfies my general requirement for "responsible" efficiency without sacrificing ease of use and simplicity.</p>
<p>I assume that the .NET way of processing XML builds on some version of MSXML and in that case I assume that using, for example, minidom would make you feel somewhat at home. However, if it is simple processing you are doing, any library will probably do.</p> <p>I also prefer working with ElementTree when dealing with XML in Python because it is a very neat library.</p>
2,284
<p>Does string immutability work by statement, or by strings within a statement? </p> <p>For example, I understand that the following code will allocate two strings on the heap.</p> <pre><code>string s = "hello "; s += "world!"; </code></pre> <p>"hello" will remain on the heap until garbage collected; and s now references "hello world!" on the heap. However, how many strings does the following line allocate on the heap...1 or 2? Also, is there a tool/way to verify the results?</p> <pre><code>string s = "goodbye " + "cruel world!"; </code></pre>
<p>The compiler has special treatment for string concatenation, which is why the second example is only ever <strong>one</strong> string. And "interning" means that even if you run this line 20000 times there is still only 1 string.</p> <p>Re testing the results... the easiest way (in this case) is probably to look in reflector: </p> <pre><code>.method private hidebysig static void Main() cil managed { .entrypoint .maxstack 1 .locals init ( [0] string s) L_0000: ldstr "goodbye cruel world!" L_0005: stloc.0 L_0006: ldloc.0 L_0007: call void [mscorlib]System.Console::WriteLine(string) L_000c: ret } </code></pre> <p>As you can see (<code>ldstr</code>), the compiler has done this for you already.</p>
<p>If the compiler is "intelligent", it will only be one string with "goodbye cruel world!"</p>
48,675
<p>Say I have a web service <a href="http://www.example.com/webservice.pl?q=google" rel="noreferrer">http://www.example.com/webservice.pl?q=google</a> which returns text "google.com". I need to call this web service (<a href="http://www.example.com/webservice.pl" rel="noreferrer">http://www.example.com/webservice.pl</a>) from a JavaScript module with a parameter (q=google) and then use the return value ("google.com") to do further processing.</p> <p>What's the simplest way to do this? I am a total JavaScript newbie, so any help is much appreciated.</p>
<p>Take a look at one of the many javascript libraries out there. I'd recommend <a href="http://www.jquery.com" rel="noreferrer">jQuery</a>, personally. Aside from all the fancy UI stuff they can do, it has really good <a href="http://docs.jquery.com/Ajax" rel="noreferrer">cross-browser AJAX libraries</a>.</p> <pre><code>$.get( "http://xyz.com/webservice.pl", { q : "google" }, function(data) { alert(data); // "google.com" } ); </code></pre>
<p><strong>EDIT:</strong> </p> <p>It has been a decade since I answered this question and we now have support for cross-domain XHR in the form of <a href="https://developer.mozilla.org/en-US/docs/Web/HTTP/CORS" rel="nofollow noreferrer">CORS</a>.</p> <p>For any modern app consider using <a href="https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API/Using_Fetch" rel="nofollow noreferrer">fetch</a> to make your requests. If you need support for older browsers you can add a <a href="https://github.com/github/fetch" rel="nofollow noreferrer">polyfill</a>.</p> <p><strong>Original answer:</strong></p> <p>Keep in mind that you cannot make requests across domains. For example, if your page is on yourexample.com and the web service is on myexample.com you cannot make a request to it directly.</p> <p>If you do need to make a request like this then you will need to set up a proxy on your server. You would make a request to that proxy page, and it will retrieve the data from the web service and return it to your page.</p>
14,435
<p>I'm writing a little desktop app that should be able to encrypt a data file and protect it with a password (i.e. one must enter the correct password to decrypt). I want the encrypted data file to be self-contained and portable, so the authentication has to be embedded in the file (or so I assume).</p> <p>I have a strategy that appears workable and seems logical based on what I know (which is probably just enough to be dangerous), but I have no idea if it's actually a good design or not. So tell me: is this crazy? Is there a better/best way to do it?</p> <ul> <li>Step 1: User enters plain-text password, e.g. "MyDifficultPassword" </li> <li>Step 2: App hashes the user-password and uses that value as the symmetric key to encrypt/decrypt the data file. e.g. "MyDifficultPassword" --> "HashedUserPwdAndKey". </li> <li>Step 3: App hashes the hashed value from step 2 and saves the new value in the data file header (i.e. the unencrypted part of the data file) and uses that value to validate the user's password. e.g. "HashedUserPwdAndKey" --> "HashedValueForAuthentication"</li> </ul> <p>Basically I'm extrapolating from the common way to implement web-site passwords (when you're not using OpenID, that is), which is to store the (salted) hash of the user's password in your DB and never save the actual password. But since I use the hashed user password for the symmetric encryption key, I can't use the same value for authentication. So I hash it again, basically treating it just like another password, and save the doubly-hashed value in the data file. That way, I can take the file to another PC and decrypt it by simply entering my password.</p> <p>So is this design reasonably secure, or hopelessly naive, or somewhere in between? Thanks!</p> <p>EDIT: clarification and follow-up question re: Salt.<br> I thought the salt had to be kept secret to be useful, but your answers and links imply this is not the case. For example, <a href="ftp://ftp.rsasecurity.com/pub/pkcs/pkcs-5v2/pkcs5v2-0.pdf" rel="noreferrer">this spec</a> linked by erickson (below) says: </p> <blockquote> <p>Thus, password-based key derivation as defined here is a function of a password, a salt, and an iteration count, where the latter two quantities need not be kept secret.</p> </blockquote> <p>Does this mean that I could store the salt value in the same place/file as the hashed key and still be more secure than if I used no salt at all when hashing? How does that work?</p> <p>A little more context: the encrypted file isn't meant to be shared with or decrypted by others, it's really single-user data. But I'd like to deploy it in a shared environment on computers I don't fully control (e.g. at work) and be able to migrate/move the data by simply copying the file (so I can use it at home, on different workstations, etc.).</p>
<h3>Key Generation</h3> <p>I would recommend using a recognized algorithm such as PBKDF2 defined in <a href="ftp://ftp.rsasecurity.com/pub/pkcs/pkcs-5v2/pkcs5v2-0.pdf" rel="nofollow noreferrer">PKCS #5 version 2.0</a> to generate a key from your password. It's similar to the algorithm you outline, but is capable of generating longer symmetric keys for use with AES. You should be able to find an open-source library that implements PBE key generators for different algorithms.</p> <h3>File Format</h3> <p>You might also consider using the <a href="http://www.ietf.org/rfc/rfc3852.txt" rel="nofollow noreferrer">Cryptographic Message Syntax</a> as a format for your file. This will require some study on your part, but again there are existing libraries to use, and it opens up the possibility of inter-operating more smoothly with other software, like S/MIME-enabled mail clients.</p> <h3>Password Validation</h3> <p>Regarding your desire to store a hash of the password, if you use PBKDF2 to generate the key, you could use a standard password hashing algorithm (big salt, a thousand rounds of hashing) for that, and get different values. </p> <p>Alternatively, you could compute a MAC on the content. A hash collision on a password is more likely to be useful to an attacker; a hash collision on the content is likely to be worthless. But it would serve to let a legitimate recipient know that the wrong password was used for decryption.</p> <h3>Cryptographic Salt</h3> <p><a href="http://en.wikipedia.org/wiki/Cryptographic_salt" rel="nofollow noreferrer">Salt</a> helps to thwart pre-computed dictionary attacks. </p> <p>Suppose an attacker has a list of likely passwords. He can hash each and compare it to the hash of his victim's password, and see if it matches. If the list is large, this could take a long time. He doesn't want spend that much time on his next target, so he records the result in a "dictionary" where a hash points to its corresponding input. If the list of passwords is very, very long, he can use techniques like a <a href="http://lasecwww.epfl.ch/~oechslin/projects/ophcrack/" rel="nofollow noreferrer">Rainbow Table</a> to save some space.</p> <p>However, suppose his next target salted their password. <em>Even if the attacker knows what the salt is, his precomputed table is worthless</em>&mdash;the salt changes the hash resulting from each password. He has to re-hash all of the passwords in his list, affixing the target's salt to the input. Every different salt requires a different dictionary, and if enough salts are used, the attacker won't have room to store dictionaries for them all. Trading space to save time is no longer an option; the attacker must fall back to hashing each password in his list for each target he wants to attack.</p> <p>So, it's not necessary to keep the salt secret. Ensuring that the attacker doesn't have a pre-computed dictionary corresponding to that particular salt is sufficient.</p>
<p>Is there really need to save the hashed password into the file. Can't you just use the password (or hashed password) with some salt and then encrypt the file with it. When decrypting just try to decrypt the file with the password + salt. If user gives wrong password the decrypted file isn't correct.</p> <p>Only drawbacks I can think is if the user accidentally enters wrong password and the decryption is slow, he has to wait to try again. And of course if password is forgotten there's no way to decrypt the file.</p>
7,971
<p>In Internet Explorer I can use the clipboardData object to access the clipboard. How can I do that in FireFox, Safari and/or Chrome?</p>
<p>For security reasons, Firefox doesn't allow you to place text on the clipboard. However, there is a workaround available using Flash.</p> <pre><code>function copyIntoClipboard(text) { var flashId = 'flashId-HKxmj5'; /* Replace this with your clipboard.swf location */ var clipboardSWF = 'http://appengine.bravo9.com/copy-into-clipboard/clipboard.swf'; if(!document.getElementById(flashId)) { var div = document.createElement('div'); div.id = flashId; document.body.appendChild(div); } document.getElementById(flashId).innerHTML = ''; var content = '&lt;embed src=&quot;' + clipboardSWF + '&quot; FlashVars=&quot;clipboard=' + encodeURIComponent(text) + '&quot; width=&quot;0&quot; height=&quot;0&quot; type=&quot;application/x-shockwave-flash&quot;&gt;&lt;/embed&gt;'; document.getElementById(flashId).innerHTML = content; } </code></pre> <p>The only disadvantage is that this requires Flash to be enabled.</p> <p>The source is currently dead: <a href="http://bravo9.com/journal/copying-text-into-the-clipboard-with-javascript-in-firefox-safari-ie-opera-292559a2-cc6c-4ebf-9724-d23e8bc5ad8a/" rel="nofollow noreferrer">http://bravo9.com/journal/copying-text-into-the-clipboard-with-javascript-in-firefox-safari-ie-opera-292559a2-cc6c-4ebf-9724-d23e8bc5ad8a/</a> (and so is its <a href="http://webcache.googleusercontent.com/search?q=cache:DaMt_LgPWUYJ:rokr-blargh.appspot.com/copying-text-into-the-clipboard-with-javascript-in-firefox-safari-ie-opera-292559a2cc6c4ebf9724d23e8bc5ad8a%20&amp;cd=1&amp;hl=en&amp;ct=clnk&amp;gl=us" rel="nofollow noreferrer">Google cache</a>)</p>
<p>A slight improvement on the Flash solution is to detect for Flash 10 using swfobject:</p> <p><a href="http://code.google.com/p/swfobject/" rel="nofollow noreferrer">http://code.google.com/p/swfobject/</a></p> <p>And then if it shows as Flash 10, try loading a Shockwave object using JavaScript. Shockwave can read/write to the clipboard (in all versions) as well using the copyToClipboard() command in <a href="https://en.wikipedia.org/wiki/Lingo_(programming_language)" rel="nofollow noreferrer">Lingo</a>.</p>
15,460
<p>I'm looking for a very specific USB device for debugging systems that may use USB but not with a regular computer (proprietary hardware). I want a device that has a USB host controller and two USB device connections. The device to be debugged is connected to the USB host controller and one of the device connections is connected to another device with it's own host controller on it. The the other device connection is connected to a pc. The point being that all USB data travelling through the device (from the device connected to the host controller to the device connected to the first device connection) is reported to the pc.</p> <p>I'll happily write software to do the logging (in fact I want to) but I can't seem to find a board like this anywhere. Can anyone help?</p>
<p>Sniffing the USB shouldn't be too hard if you have the right hardware. And that is the tricky question. I haven't seen anything that describes the USB breakout box that you want. However I can say that this is in the realm of the following two magazines:</p> <ol> <li><a href="http://www.nutsvolts.com" rel="nofollow noreferrer">Nuts and Volts</a></li> <li><a href="http://www.circuitcellar.com" rel="nofollow noreferrer">Circuit Cellar</a></li> </ol> <p>If they don't have a USB breakout box project in their archives, then at least they will have advertisements for small cheap single board computers that would have multiple USB ports that you can use for buffering the signals and reporting it back to your PC.</p> <p>Alternatively is it possible to just wire your PC up to the middle of your two devices and write a custom drive that echos data back and forth while sniffing off a stream for you?</p>
<p>Sorry for the long delay in my reply -- I checked out one of our USB developer's toolchain, and he uses a <a href="http://www.avrfreaks.net/index.php?module=Freaks%20Tools&amp;func=viewItem&amp;item_id=913" rel="nofollow noreferrer">Beagle USB Sniffer</a>. He seems happy with it.</p>
41,590
<p>Just to clarify, I'm running Sybase 12.5.3, but I am lead to believe that this holds true for SQL Server 2005 too. Basically, I'm trying to write a query that looks a little like this, I've simplified it as much as possible to highlight the problem:</p> <pre><code>DECLARE @a int, @b int, @c int SELECT @a = huzzah.a ,@b = huzzah.b ,@c = huzzah.c FROM ( SELECT 1 a ,2 b ,3 c ) huzzah </code></pre> <p>This query gives me the following error: <em>"Error:141 A SELECT statement that assigns a value to a variable must not be combined with data-retrieval operations."</em></p> <p>The only work around that I've got for this so far, is to insert the derived-table data into a temporary table and then select it right back out again. Which works fine, but the fact that this doesn't work irks me. Is there a better way to do this?</p>
<p>The error does appear as described in 12.5.3 esd 4 &amp; 7, it runs fine in 12.5.4 esd 4 &amp; 6.</p> <p>Looks like a bug that's been patched, your only options seem to be workaround or patch.</p> <p>Have found what appears to be the <a href="http://search.sybase.com/kbx/changerequests?bug_id=377625" rel="nofollow noreferrer">bug 377625</a></p>
<p>I've just ran your code against 12.5.3 and it parses fine...doesn't return anything but it does run. Have you maybe simplified the problem a bit too much because I'm not seeing any error messages at all.</p> <p>Just to be clear, the following runs and returns what you'd expect.</p> <pre><code>DECLARE @a int, @b int, @c int SELECT @a = huzzah.a ,@b = huzzah.b ,@c = huzzah.c FROM ( SELECT 1 a ,2 b ,3 c ) huzzah select @a select @b select @c </code></pre>
29,581
<p>I posted a <a href="https://stackoverflow.com/questions/81306/wcf-faults-exceptions-versus-messages">question</a> about using Messages versus Fault Exceptions to communicate business rules between services.</p> <p>I was under the impression it carried overhead to throw this exception over the wire, but considering it's just a message that get serialized and deserialized, they were in fact one and the same.</p> <p>But this got me thinking about throwing exceptions in general or more specifically throwing FaultExceptions.</p> <p>Now within my service, if i use</p> <pre><code>throw new FaultException </code></pre> <p>to communicate a simple business rule like "Your account has not been activated", What overhead does this now carry? Is it the same overhead as throwing regular exceptions in .NET? or does WCF service handle these more efficiently with the use of Fault Contracts.</p> <p>So in my user example, which is the optimal/preferred way to write my service method</p> <p>option a</p> <pre><code>public void AuthenticateUser() { throw new FaultException("Your account has not been activated"); } </code></pre> <p>option b</p> <pre><code>public AutheticateDto AutheticateUser() { return new AutheticateDto() { Success = false, Message = "Your account has not been activated"}; } </code></pre>
<p>Well... In general you shouldn't be throwing exceptions for expected conditions, or anything you <em>expect</em> to happen regularly. They are massively slower than doing normal methods. E.g., if you expect a file open to fail, don't throw a that exception up to your caller, pass the back a failure code, or provide a "CanOpenFile" method to do the test.</p> <p>True, the message text itself isn't much, but a real exception is thrown and handled (possibly more expensively because of IIS), and then real exception is again thrown on the client when the fault is deserialized. So, double hit.</p> <p>Honestly, if it is a low volume of calls, then you probably won't take any noticeable hit, but is not a good idea anyway. Who wants to put business logic in a catch block :)</p> <p><a href="http://msdn.microsoft.com/en-us/library/ms229009.aspx" rel="nofollow noreferrer">Microsoft : Exceptions And Performance, &amp; Alternatives</a></p> <p><a href="http://www.developerfusion.co.uk/show/5250/" rel="nofollow noreferrer">Developer Fusion: Performance, with example</a></p>
<p>It's just like a normal exception, and uses the same wrapping code as a normal exception would to marshal into a fault, including unwinding the stack.</p> <p>Like exceptions SOAP faults shouldn't, to my mind, be used for program flow, but to indicate errors.</p>
12,524
<p>Is there an openID implementation in Java? I would like to use this in a tomcat application.</p>
<p>The <a href="https://github.com/jbufu/openid4java" rel="nofollow noreferrer">openid4java</a> library seems to be the most popular.</p>
<p>If you don't mind using a service there is <a href="http://rpxnow.com" rel="nofollow noreferrer">RPX</a></p>
49,295
<p>I am trying to install VS2008 sp1 to my work machine - it has a pathetic 10Gb C drive. The SP1 bootstrapper doesn't give the option to install items to D, only C. It needs 3Gb free and the machine only has about 700Mb.</p> <p>VS allowed me to install to D originally why not the SP. The only thing I can think of that it requires system files installed in Windows etc, but I can't believe there are 3Gb worth of system files?</p>
<p>Worth a read:</p> <p><a href="http://blogs.msdn.com/heaths/archive/2008/07/24/why-windows-installer-may-require-so-much-disk-space.aspx" rel="nofollow noreferrer">http://blogs.msdn.com/heaths/archive/2008/07/24/why-windows-installer-may-require-so-much-disk-space.aspx</a></p>
<p>You could also download the full VS2008 SP1 ISO image from <a href="http://www.microsoft.com/downloads/details.aspx?FamilyID=27673c47-b3b5-4c67-bd99-84e525b5ce61&amp;displaylang=en" rel="nofollow noreferrer">here</a>.</p> <p>Then you can either burn it to DVD or use a tool such as <a href="http://download.microsoft.com/download/7/b/6/7b6abd84-7841-4978-96f5-bd58df02efa2/winxpvirtualcdcontrolpanel_21.exe" rel="nofollow noreferrer">Virtual CD-ROM Control Panel from Microsoft</a> to mount the ISO as another drive.</p> <p>After mounting the ISO as a virtual drive, you can run the SP1 install from there.</p>
3,016
<p>What's the fastest way to count the number of keys/properties of an object? Is it possible to do this without iterating over the object? I.e., without doing:</p> <pre><code>var count = 0; for (k in myobj) if (myobj.hasOwnProperty(k)) ++count; </code></pre> <p>(Firefox did provide a magic <code>__count__</code> property, but this was removed somewhere around version 4.)</p>
<p>To do this in any <em><a href="https://en.wikipedia.org/wiki/ECMAScript#5th_Edition" rel="noreferrer">ES5</a>-compatible environment</em>, such as <a href="http://nodejs.org" rel="noreferrer">Node.js</a>, Chrome, <a href="https://en.wikipedia.org/wiki/Internet_Explorer_9" rel="noreferrer">Internet Explorer 9+</a>, Firefox 4+, or Safari 5+:</p> <pre class="lang-js prettyprint-override"><code>Object.keys(obj).length </code></pre> <ul> <li><a href="http://kangax.github.com/es5-compat-table/" rel="noreferrer">Browser compatibility</a></li> <li><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/keys" rel="noreferrer">Object.keys documentation</a> (includes a method you can add to non-ES5 browsers)</li> </ul>
<p>If jQuery in previous answers does not work, then try</p> <pre><code>$(Object.Item).length </code></pre>
15,332
<p>I have a Stored procedure which schedules a job. This Job takes a lot of time to get completed (approx 30 to 40 min). I need to get to know the status of this Job. Below details would help me</p> <p>1) How to see the list of all jobs that have got scheduled for a future time and are yet to start</p> <p>2) How to see the the list of jobs running and the time span from when they are running</p> <p>3) How to see if the job has completed successfully or has stoped in between because of any error.</p>
<p>You could try using the system stored procedure sp_help_job. This returns information on the job, its steps, schedules and servers. For example</p> <pre><code>EXEC msdb.dbo.sp_help_job @Job_name = 'Your Job Name' </code></pre> <p><a href="http://msdn.microsoft.com/en-us/library/ms186722(SQL.90).aspx" rel="noreferrer">SQL Books Online</a> should contain lots of information about the records it returns.</p> <p>For returning information on multiple jobs, you could try querying the following system tables which hold the various bits of information on the job</p> <ul> <li>msdb.dbo.SysJobs</li> <li>msdb.dbo.SysJobSteps</li> <li>msdb.dbo.SysJobSchedules </li> <li>msdb.dbo.SysJobServers </li> <li>msdb.dbo.SysJobHistory</li> </ul> <p>Their names are fairly self-explanatory (apart from SysJobServers which hold information on when the job last run and the outcome).</p> <p>Again, information on the fields can be found at MSDN. For example, check out the page for <a href="http://msdn.microsoft.com/en-us/library/ms189817.aspx" rel="noreferrer">SysJobs</a></p>
<p>The most simple way I found was to create a stored procedure. Enter the 'JobName' and hit go.</p> <pre><code>/*----------------------------------------------------------------------------------------------------------- Document Title: usp_getJobStatus Purpose: Finds a Current Jobs Run Status Input Example: EXECUTE usp_getJobStatus 'MyJobName' -------------------------------------------------------------------------------------------------------------*/ IF OBJECT_ID ( 'usp_getJobStatus','P' ) IS NOT NULL DROP PROCEDURE usp_getJobStatus; GO CREATE PROCEDURE usp_getJobStatus @JobName NVARCHAR (1000) AS IF OBJECT_ID('TempDB..#JobResults','U') IS NOT NULL DROP TABLE #JobResults CREATE TABLE #JobResults ( Job_ID UNIQUEIDENTIFIER NOT NULL, Last_Run_Date INT NOT NULL, Last_Run_Time INT NOT NULL, Next_Run_date INT NOT NULL, Next_Run_Time INT NOT NULL, Next_Run_Schedule_ID INT NOT NULL, Requested_to_Run INT NOT NULL, Request_Source INT NOT NULL, Request_Source_id SYSNAME COLLATE Database_Default NULL, Running INT NOT NULL, Current_Step INT NOT NULL, Current_Retry_Attempt INT NOT NULL, Job_State INT NOT NULL ) INSERT #JobResults EXECUTE master.dbo.xp_sqlagent_enum_jobs 1, ''; SELECT job.name AS [Job_Name], ( SELECT MAX(CAST( STUFF(STUFF(CAST(jh.run_date AS VARCHAR),7,0,'-'),5,0,'-') + ' ' + STUFF(STUFF(REPLACE(STR(jh.run_time,6,0),' ','0'),5,0,':'),3,0,':') AS DATETIME)) FROM msdb.dbo.sysjobs AS j INNER JOIN msdb.dbo.sysjobhistory AS jh ON jh.job_id = j.job_id AND jh.step_id = 0 WHERE j.[name] LIKE '%' + @JobName + '%' GROUP BY j.[name] ) AS [Last_Completed_DateTime], ( SELECT TOP 1 start_execution_date FROM msdb.dbo.sysjobactivity WHERE job_id = r.job_id ORDER BY start_execution_date DESC ) AS [Job_Start_DateTime], CASE WHEN r.running = 0 THEN CASE WHEN jobInfo.lASt_run_outcome = 0 THEN 'Failed' WHEN jobInfo.lASt_run_outcome = 1 THEN 'Success' WHEN jobInfo.lASt_run_outcome = 3 THEN 'Canceled' ELSE 'Unknown' END WHEN r.job_state = 0 THEN 'Success' WHEN r.job_state = 4 THEN 'Success' WHEN r.job_state = 5 THEN 'Success' WHEN r.job_state = 1 THEN 'In Progress' WHEN r.job_state = 2 THEN 'In Progress' WHEN r.job_state = 3 THEN 'In Progress' WHEN r.job_state = 7 THEN 'In Progress' ELSE 'Unknown' END AS [Run_Status_Description] FROM #JobResults AS r LEFT OUTER JOIN msdb.dbo.sysjobservers AS jobInfo ON r.job_id = jobInfo.job_id INNER JOIN msdb.dbo.sysjobs AS job ON r.job_id = job.job_id WHERE job.[enabled] = 1 AND job.name LIKE '%' + @JobName + '%' </code></pre>
24,411
<p>Is it possible to reset the alternate buffer in a vim session to what it was previously?</p> <p>By alternate buffer, I mean the one that is referred to by #, i.e. the one that is displayed when you enter cntl-^.</p> <p>Say I've got two files open main.c and other.c and :ls gives me:</p> <pre><code> 1 %a "main.c" lines 27 2 # "other.c" lines 56 </code></pre> <p>Say I open another file, e.g. refer.c, :ls will now give me:</p> <pre><code> 1 %a "main.c" lines 27 2 "other.c" lines 56 3 # "refer.c" lines 125 </code></pre> <p>If I delete the buffer containing refer.c, :ls now shows:</p> <pre><code> 1 %a "main.c" lines 27 2 "other.c" lines 56 </code></pre> <p>But if I do a cntl-^, refer.c will be displayed again!</p> <p>Is there some way to get vim to reset the alternate buffer back to what it last was automatically? A "history" of alternate buffers?</p> <p>Or am I stuck with doing a :2 b to reload other.c into the alternate buffer?</p> <p>Or maybe there is a good reason for this behaviour?</p>
<p>In this case, "alternate" just means "previous". So, yes, :b2 (or 2 ctrl-6) is probably the easiest way to change which two buffers will be toggled by ctrl-6.</p> <p>Also, take a look at the :keepalt command.</p>
<p>As you'll come to expect with Vim, there is an excellent reason for this behaviour. <code>:bd</code> (mnemonic for buffer delete) does <em>not</em> delete the buffer, per se, it <em>deletes it from the main buffer list</em>!</p> <p>If you try <code>:ls!</code> or <code>:buffers!</code> you will see it is is still available but with a <code>u</code> adjacent to it's buffer number, indicating it is now "unlisted" (that is, unlisted unless you list it with an exclamation mark!).</p> <p>I'm making it sound as horrible as possible, but as with most of Vim it works once you understand it, and the use of exclamation mark / bang to force the command is consistent.</p> <p>To get rid of the buffer completely you need to <em>wipe</em> it using <code>:bw</code>. When you have done that you will still have the same problem, but this time, attempting to switch to the alternate buffer with <code>CTRL-^</code> will elicit <code>No alternate file</code> (because this time it <em>really</em> has gone).</p> <p>To switch to the file you want, yes, use the buffer number: <code>:b2</code>, or whatever the buffer number is of the file you want, and that will establish a new alternate buffer.</p> <p>I find it's easy to remember buffer numbers or look them up with <code>:buffers</code> or <code>:buffers!</code> really quickly, and of course changing to them is then quick, but of course there's a range of techniques in Vim for changing buffers, especially including <em>marks</em>.</p> <p>You've also discovered another great Vim feature here, the unlisted buffers. When you're dealing with a few extra files it's sometimes helpful to "delete" them from the <code>:buffers</code> list using <code>:bd</code>, just to get them out of sight, but although hidden they're not unavailable, and you can check which one you want with <code>:buffers!</code> and then <code>:b&lt;num&gt;</code> to pull it up, without having to undelete it or anything.</p>
19,227
<p>What's the best way for determining whether the user's browser can view PDF files? </p> <p>Ideally, it shouldn't matter on the browser or the operating system.</p> <p>Is there a specific way of doing it in ASP.NET, or would the answer be just JavaScript?</p>
<p>Neither, none, don't try.</p> <p>Re <a href="https://stackoverflow.com/questions/76179/how-to-determine-if-the-users-browser-can-view-pdf-files#76220">dawnerd</a>: Plug-in detection is not the right answer. I do not have a PDF plugin installed in my browser (Firefox on Ubuntu), yet I am able to view PDF files using the operating system's document viewer (which is not Acrobat Reader).</p> <p>Today, any operating system that can run a web browser can view PDF files out of the box.</p> <p>If a specific system does not have a PDF viewer installed and the browser configured to use it, that likely means that either it's a hand-made install of Windows, a very trimmed down alternate operating system, or something really retro.</p> <p>It is reasonable to assume that in any of those situation the user will know what a PDF file is and either deliberately choose not to be able to view them or know how to install the required software.</p> <p>If I am deluding myself, I would love to have it explained to me in which way I am wrong.</p>
<p>A quick google search <a href="http://www.oreillynet.com//cs/user/view/cs_msg/9920" rel="nofollow noreferrer">found this</a>. Useful for all kinds of plugins.</p>
10,175
<p>I say properly because everyone I have spoken to in the past said running Django on IIS was a hack. I had it working somewhat but it never did quite right and did feel like a hack. I like python but had to give it up because I could never make Django work with IIS and Django was my excuse to use Python in production web apps. But it was so messy that I could not in good conscience sell it to the group. So, I figured why fight it, just stick to asp.net, IIS, roll your own or use frameworks from MS. Just wondering if anything had changed. BTW, not knocking asp.net. I just wanted to use Python.</p> <p>Thank you.</p> <p>EDIT - Are there any new plans to officially support IIS yet?</p>
<p>Django is WSGI-based framework so as soon as IIS get proper WSGI handling there should be no problem in running Django under this environment. Anything that connects WSGI and IIS will do.</p> <p>Quick googling reveals <a href="http://code.google.com/p/isapi-wsgi/" rel="nofollow noreferrer">some project on Google Code</a>.</p>
<p>You should be able to use the FastCGI isapi developed by MS. It works on 6 but has better integration on 7. Disclaimer: I haven't tried it with Django.</p>
49,021
<p>Is there a way to emulate mixins or traits in java? basically, I need a way to do multiple inheritance so I can add common business logic to several classes</p>
<p>I would encapsulate all of the business logic into a new class <code>BusinessLogic</code> and have each class that needs <code>BusinessLogic</code> make calls to the class. If you need a single rooted heirarchy for your classes that make calls to <code>BusinessLogic</code>, you'll have to create an interface as well (<code>BusinessLogicInterface</code>?)</p> <p>In pseudo-code:</p> <pre><code>interface BusinessLogicInterace { void method1(); void method2(); } class BusinessLogic implements BusinessLogicInterface { void method1() { ... } void method2() { ... } } class User extends OtherClass implements BusinessLogicInterface { BusinessLogic logic = new BusinessLogic(); @Override void method1() { logic.method1(); } @Override void method2() { logic.method2(); } } </code></pre> <p>This isn't the prettiest implementation to work around a lack of multiple inheritance and it becomes quite cumbersome when the interface has a lot of methods. Most likely, you'll want to try and redesign your code to avoid needing mixins.</p>
<p>Implementing simple mixin/traits support in java using CGLib/javassit is quite easy. You can take a look for instance <a href="http://justonjava.blogspot.com/2011/10/mixins-aka-traits-implementation-in.html" rel="nofollow">here</a> for small example. More complete, ready to use solution might be found: <a href="http://insightfullogic.com/blog/2011/sep/16/multiple-inheritance/" rel="nofollow">here</a></p>
32,938
<p>I am building a FAQ module for my site and I want to be able to control single elements on the page even though they all have the same class. I believe this comes under siblings which I am not yet familiar with.</p> <p>Basically I want the user to be able to click the question div and then when they click it the answer div within the same div as the question div is set to show (if that makes sense!). Any help would be greatly appreciated.</p> <pre><code>&lt;div class="set"&gt; &lt;div class="question"&gt;What is the airspeed velocity of an unladen swallow?&lt;/div&gt; &lt;div class="answer"&gt;Although a definitive answer would of course require further measurements, published species-wide averages of wing length and body mass, initial Strouhal estimates based on those averages and cross-species comparisons, the Lund wind tunnel study of birds flying at a range of speeds, and revised Strouhal numbers based on that study all lead me to estimate that the average cruising airspeed velocity of an unladen European Swallow is roughly 11 meters per second, or 24 miles an hour. &lt;/div&gt; &lt;/div&gt; &lt;div class="set"&gt; &lt;div class="question"&gt;What is the airspeed velocity of an unladen swallow?&lt;/div&gt; &lt;div class="answer"&gt;Although a definitive answer would of course require further measurements, published species-wide averages of wing length and body mass, initial Strouhal estimates based on those averages and cross-species comparisons, the Lund wind tunnel study of birds flying at a range of speeds, and revised Strouhal numbers based on that study all lead me to estimate that the average cruising airspeed velocity of an unladen European Swallow is roughly 11 meters per second, or 24 miles an hour. &lt;/div&gt; &lt;/div&gt; &lt;div class="set"&gt; &lt;div class="question"&gt;What is the airspeed velocity of an unladen swallow?&lt;/div&gt; &lt;div class="answer"&gt;Although a definitive answer would of course require further measurements, published species-wide averages of wing length and body mass, initial Strouhal estimates based on those averages and cross-species comparisons, the Lund wind tunnel study of birds flying at a range of speeds, and revised Strouhal numbers based on that study all lead me to estimate that the average cruising airspeed velocity of an unladen European Swallow is roughly 11 meters per second, or 24 miles an hour. &lt;/div&gt; &lt;/div&gt; </code></pre>
<p>If I understand your question correctly, you should Start by setting all answers as hidden in the css: .answer {display:none;}</p> <p>Then you can use jquery to show the correct answer to the clicked questions : </p> <pre><code>$(document).ready ( function () { $('.question').click(function() { $(this).next('.answer').show(); }); }); </code></pre> <p>Edit: you can also use .toggle() instead of .show() to show/hide.</p>
<p>You should probably check out this <a href="https://stackoverflow.com/questions/233936/jquery-swapping-elements">question</a> where something similar is done.</p> <p>Basically, you first need to setup ID's for your elements so that you can identify single elements within the set classes.</p> <p>You could then add a click event handler which would set the selected item and show the appropriate answer.</p> <p>You can see the syntax for grabbing siblings in the <a href="http://docs.jquery.com/Traversing/siblings" rel="nofollow noreferrer">documentation here</a>.</p>
32,716
<p>I need to copy hundreds of gigs of random files around on my computer and am pretty leery of using the vanilla file copy built into Windows.</p> <p>I don't want it to hang on a "Are you sure?", "Are you really sure?", "Even zip files?", "Surely not read-only files too!" loop as soon as I step away.</p> <p>I don't want it to work for hours and then stop unexpectedly: "Someone once opened this file and so I won't copy it!" and then cancel the whole copy or just quit with no indication of what was done and what work remains.</p> <p>What file management programs do you have experience with? Which do you recommend?</p> <p>This question is related to my other question: <a href="https://stackoverflow.com/questions/225/how-can-i-use-an-old-pata-hard-disk-drive-on-my-newer-sata-only-computer">How can I use an old PATA hard disk drive on my newer SATA-only computer?</a></p>
<p>Use <a href="http://en.wikipedia.org/wiki/Robocopy" rel="noreferrer">Robocopy (Robust File Copy)</a>.</p> <p>NOTE:</p> <p>In Windows Vista and Server 2008 when you type:</p> <pre><code>xcopy /? </code></pre> <p>you get:</p> <blockquote> <p>NOTE: Xcopy is now deprecated, please use Robocopy.</p> </blockquote> <p>So start getting used to robocopy :)</p>
<p>Reboot into Linux, mount the drive, and use GNU <code>cp</code>.</p>
2,375
<p>What is the best way to store a large number of data points?</p> <p>For example temperature values which are measured every minute over lots of locations?</p> <p>SQL databases with one row per data points doesn't seem very efficient.</p>
<p>I would like to know why you reckon it to be "not efficient". Probably you need to explain your data model and schema to give a better context of the scenario.</p> <p>Storing multiple data points into a single row, when they are not related to each other, and should indeed stand on their own, is not a good approach. Meshing together will result in very counter-intuitive and quirky query statements to pull out the correct data points you need for a given scenario.</p> <p>We have done work in a power station before, collecting data from various systems and metering equipment a wide variety of gas and electrical parameters that need to be monitored and aggregated. They can come in every 3-5 minutes to 30-60 minutes depending on the type of parameters. These naturally results in millions of records per month.</p> <p>The key is indexing the tables properly so that their physical order is tied to sequence in which the records came in. (Clustered index) New pages and extents are created and filled sequentially by incoming data. This should prevent massive page splits and reshuffling.</p>
<p>Store them in a data table as rows and columns because the data table can later be partitioned by Year, Month, and Location for your temperatures for extraction speed using parallel processing.</p>
31,893
<p>Web parts seem to be used extensively in Sharepoint related development, but examples of using them in asp.net webforms applications are few and far between. I'm implementing a domain specific portal framework and like the "widgetlike" functionality in iGoogle or pageflakes and would like to get that kind of feature in my application. The real troubling issue from my perspective is that the drag &amp; drop layout features of web parts do not work in non-IE browsers unless you use the latest ASP.NET AJAX futures library. It seems to me if Microsoft meant this to be a foundation technology, they would have moved these features into the main product by now. </p> <p>Are web parts a dead-end technology? If so, are there any alternatives?</p>
<p>i think they are (dead), at least for developing the types of UI modern web-browsers are looking for. My recommendation ... ASP.NET MVC and a nice .js library. It's more work out of the gate, but with the proper planning and implementation it will serve you much better in the long run.</p>
<p>Webparts are a part of the .NET infrastructure and are a foundation technology. There are few interface technologies, to make webparts compatible with their J2EE counterparts.</p>
38,911
<p>How do I connect to Gmail and determine which messages have attachments? I then want to download each attachment, printing out the Subject: and From: for each message as I process it.</p>
<p>Hard one :-)</p> <pre><code>import email, getpass, imaplib, os detach_dir = '.' # directory where to save attachments (default: current) user = raw_input("Enter your GMail username:") pwd = getpass.getpass("Enter your password: ") # connecting to the gmail imap server m = imaplib.IMAP4_SSL("imap.gmail.com") m.login(user,pwd) m.select("[Gmail]/All Mail") # here you a can choose a mail box like INBOX instead # use m.list() to get all the mailboxes resp, items = m.search(None, "ALL") # you could filter using the IMAP rules here (check http://www.example-code.com/csharp/imap-search-critera.asp) items = items[0].split() # getting the mails id for emailid in items: resp, data = m.fetch(emailid, "(RFC822)") # fetching the mail, "`(RFC822)`" means "get the whole stuff", but you can ask for headers only, etc email_body = data[0][1] # getting the mail content mail = email.message_from_string(email_body) # parsing the mail content to get a mail object #Check if any attachments at all if mail.get_content_maintype() != 'multipart': continue print "["+mail["From"]+"] :" + mail["Subject"] # we use walk to create a generator so we can iterate on the parts and forget about the recursive headach for part in mail.walk(): # multipart are just containers, so we skip them if part.get_content_maintype() == 'multipart': continue # is this part an attachment ? if part.get('Content-Disposition') is None: continue filename = part.get_filename() counter = 1 # if there is no filename, we create one with a counter to avoid duplicates if not filename: filename = 'part-%03d%s' % (counter, 'bin') counter += 1 att_path = os.path.join(detach_dir, filename) #Check if its already there if not os.path.isfile(att_path) : # finally write the stuff fp = open(att_path, 'wb') fp.write(part.get_payload(decode=True)) fp.close() </code></pre> <p>Wowww! That was something. ;-) But try the same in Java, just for fun!</p> <p>By the way, I tested that in a shell, so some errors likely remain.</p> <p>Enjoy</p> <p><strong>EDIT:</strong></p> <p>Because mail-box names can change from one country to another, I recommend doing <code>m.list()</code> and picking an item in it before <code>m.select("the mailbox name")</code> to avoid this error:</p> <blockquote> <p>imaplib.error: command SEARCH illegal in state AUTH, only allowed in states SELECTED</p> </blockquote>
<p>Have you taken a look at the <a href="http://en.wikipedia.org/wiki/Gmail#Gmail_3rd_party_Add-Ins" rel="nofollow noreferrer">GMail 3rd party add-ons</a> at wikipedia?</p> <p>In particular, <a href="http://en.wikipedia.org/wiki/PhpGmailDrive" rel="nofollow noreferrer">PhpGmailDrive</a> is an open source add-on that you may be able to use as-is, or perhaps study for inspiration?</p>
45,358
<p>Please excuse the vague title. If anyone has a suggestion, please let me know! Also please retag with more appropriate tags!</p> <p><strong>The Problem</strong></p> <p>I want to have an instance of an imported class be able to view things in the scope (globals, locals) of the importer. Since I'm not sure of the exact mechanism at work here, I can describe it much better with snippets than words.</p> <pre><code>## File 1 def f1(): print "go f1!" class C1(object): def do_eval(self,x): # maybe this should be do_evil, given what happens print "evaling" eval(x) eval(x,globals(),locals()) </code></pre> <p>Then run this code from an iteractive session, there there will be lots of <code>NameErrors</code></p> <pre><code>## interactive class C2(object): def do_eval(self,x): # maybe this should be do_evil, given what happens print "evaling" eval(x) eval(x,globals(),locals()) def f2(): print "go f2!" from file1 import C1 import file1 C1().do_eval('file1.f1()') C1().do_eval('f1()') C1().do_eval('f2()') file1.C1().do_eval('file1.f1()') file1.C1().do_eval('f1()') file1.C1().do_eval('f2()') C2().do_eval('f2()') C2().do_eval('file1.f1()') C2().do_eval('f1()') </code></pre> <p>Is there a common idiom / pattern for this sort of task? Am I barking up the wrong tree entirely? </p>
<p>In this example, you can simply hand over functions as objects to the methods in <code>C1</code>:</p> <pre><code>&gt;&gt;&gt; class C1(object): &gt;&gt;&gt; def eval(self, x): &gt;&gt;&gt; x() &gt;&gt;&gt; &gt;&gt;&gt; def f2(): print "go f2" &gt;&gt;&gt; c = C1() &gt;&gt;&gt; c.eval(f2) go f2 </code></pre> <p>In Python, you can pass functions and classes to other methods and invoke/create them there.</p> <p>If you want to actually evaluate a code string, you have to specify the environment, as already mentioned by Thomas.</p> <p>Your module from above, slightly changed:</p> <pre><code>## File 1 def f1(): print "go f1!" class C1(object): def do_eval(self, x, e_globals = globals(), e_locals = locals()): eval(x, e_globals, e_locals) </code></pre> <p>Now, in the interactive interpreter:</p> <pre><code>&gt;&gt;&gt; def f2(): &gt;&gt;&gt; print "go f2!" &gt;&gt;&gt; from file1 import * # 1 &gt;&gt;&gt; C1().do_eval("f2()") # 2 NameError: name 'f2' is not defined &gt;&gt;&gt; C1().do_eval("f2()", globals(), locals()) #3 go f2! &gt;&gt;&gt; C1().do_eval("f1()", globals(), locals()) #4 go f1! </code></pre> <h2>Some annotations</h2> <ol> <li>Here, we insert all objects from <code>file1</code> into this module's namespace</li> <li><code>f2</code> is not in the namespace of <code>file1</code>, therefore we get a <code>NameError</code></li> <li>Now we pass the environment explictly, and the code can be evaluated</li> <li><code>f1</code> is in the namespace of this module, because we imported it</li> </ol> <p><strong>Edit</strong>: Added code sample on how to explicitly pass environment for <code>eval</code>.</p>
<p>Functions are always executed in the scope they are defined in, as are methods and class bodies. They are never executed in another scope. Because importing is just another assignment statement, and everything in Python is a reference, the functions, classes and modules don't even know where they are imported to.</p> <p>You can do two things: explicitly pass the 'environment' you want them to use, or use stack hackery to access their caller's namespace. The former is vastly preferred over the latter, as it's not as implementation-dependent and fragile as the latter.</p> <p>You may wish to look at the string.Template class, which tries to do something similar.</p>
14,267
<p>Ok, this is a weird one. The junk data isn't random either, it appears to be substrings of the executable itself.</p> <pre><code>private void Form1_Load(object sender, EventArgs e) { string s = GetValue(); // at this point, s == "400". Why isn't really relevant (dumbed down a test) if (s != "18446744073709551615") throw new Exception(); // When the exception is thrown though, the string is set to random // data from inside the executable. } </code></pre> <p>This seems dependant on certain seemingly insignificant implementation details in GetValue() such as calls to string.Format() being in different places.</p> <p>Has anyone ever run into something similar or have any ideas what might cause this?</p>
<p>"And I'm checking it in the "Locals" window in VS"</p> <p>That explains it. Contrary to popular belief, C# is allowed to do some amount of optimization. If you don't add a "KeepAlive" at the end of your function, the value doesn't really have to be stored.</p>
<p>If you're checking the variable after the exception has been thrown and is now out of scope, then it should be pointing to nothing more than garbage sitting in memory. Have you tried checking the value of this variable both before and after the exception has been thrown?</p>
21,867
<p>I have the following preprocessor divective:</p> <pre><code>#ifndef NDEBUG #define TRACE printf #else #define TRACE(...) #endif </code></pre> <p>and example of usage is:</p> <pre><code>TRACE("TRACE: some parameter = %i\n", param); </code></pre> <p>In C all works perfectly well when I build both debug and release versions, but in C++ compiler emits the following:</p> <p>warning: invalid character in macro parameter name</p> <p>error: badly punctuated parameter list in `#define'</p> <p>and points these warning and error to the 'TRACE(...)' directive.</p> <p>How to write this in C++ correctly?</p>
<p>You could do:</p> <pre><code>inline void TRACE(...) {} </code></pre>
<p>You could do:</p> <pre><code>inline void TRACE(...) {} </code></pre>
20,054
<p>I have C# wrapper of a C Library. It has a method that returns an sbyte that is supposed to represent a char. I can use Convert.ToChar but this is not CLS-compliant. What is the best practice for converting this sbyte to a char compliantly?</p>
<p>System.Buffer.BlockCopy can be used to convert sbyte arrays to byte arrays. Then, you can use the System.Text.ASCIIEncoding to do the conversion of the byte array to ASCII text. </p>
<p>System.Buffer.BlockCopy can be used to convert sbyte arrays to byte arrays. Then, you can use the System.Text.ASCIIEncoding to do the conversion of the byte array to ASCII text. </p>
27,454
<p>The controllers in my ASP.NET MVC web app are starting to get a bit bloated with business logic. The examples on the web all show simple controller actions that simply pull data out of a repository and pass it to the view. But what if you also need to support business logic on top of that? </p> <p>Say, for instance, an action that fulfills an order also needs to send an e-mail out. Do I stick this in the controller and copy/paste this logic to any other actions that also fulfill orders? My first intuition would be to create a service like OrderFulfillerService that would take care of all this logic and have the controller action call that. However, for simple operations like retrieving a list of users or orders from the database, I would like to interact directly with the repository instead of having that call wrapped by a service.</p> <p>Is this an acceptable design pattern? Controller actions call services when they need business logic and repositories when they just need data access?</p>
<p>Your controllers (in the MVC project) should be calling your objects in the Service project. The services project is where all the business logic is handled.</p> <p>A good example is this:</p> <pre><code>public ActionResult Index() { ProductServices productServices = new ProductServices(); // top 10 products, for example. IList&lt;Product&gt; productList = productServices.GetProducts(10); // Set this data into the custom viewdata. ViewData.Model = new ProductViewData { ProductList = productList; }; return View(); } </code></pre> <p>or with Dependency Injection (my fav)</p> <pre><code>// Field with the reference to all product services (aka. business logic) private readonly ProductServices _productServices; // 'Greedy' constructor, which Dependency Injection auto finds and therefore // will use. public ProductController(ProductServices productServices) { _productServices = productServices; } public ActionResult Index() { // top 10 products, for example. // NOTE: The services instance was automagically created by the DI // so i din't have to worry about it NOT being instansiated. IList&lt;Product&gt; productList = _productServices.GetProducts(10); // Set this data into the custom viewdata. ViewData.Model = new ProductViewData { ProductList = productList; }; return View(); } </code></pre> <p>Now .. what's the Service project (or what is ProductServices)? that's a class library with your business logic. For example.</p> <pre><code>public class ProductServices : IProductServices { private readonly ProductRepository _productRepository; public ProductServices(ProductRepository productRepository) { _productRepository = productRepository; } public IList&lt;Product&gt; GetProducts(int numberOfProducts) { // GetProducts() and OrderByMostRecent() are custom linq helpers... return _productRepository.GetProducts() .OrderByMostRecent() .Take(numberOfProducts) .ToList(); } } </code></pre> <p>but that might be all so hardcore and confusing... so a simple version of the ServiceProduct class could be (but i wouldn't really recommend) ...</p> <pre><code>public class ProductServices { public IList&lt;Product&gt; GetProducts(int numberOfProducts) { using (DB db = new Linq2SqlDb() ) { return (from p in db.Products orderby p.DateCreated ascending select p).Take(10).ToList(); } } } </code></pre> <p>So there you go. You can see that all the logic is in the Service projects, which means u can reuse that code in other places.</p> <p>Where did i learn this?</p> <p>From <a href="http://blog.wekeroad.com/" rel="nofollow noreferrer" title="Rob Conery&#39;s main blog">Rob Conery</a>'s <a href="http://www.codeplex.com/mvcsamples/Release/ProjectReleases.aspx?ReleaseId=18861" rel="nofollow noreferrer" title="Code is found here">MVC StoreFront</a> media and <a href="http://blog.wekeroad.com/mvc-storefront/" rel="nofollow noreferrer" title="Rob&#39;s blog, but filtered by MVC Storefront posts and tutorials">tutorials</a>. Best thing since sliced bread. His tutorials explain (what i did) in good detail with full solution code examples. He uses Dependency Injection which is SOO kewl now that i've seen how he uses it, in MVC.</p> <p>HTH.</p>
<p>Your business logic should be encapsulated in business objects - if you have an Order object (and you do, don't you?), and a business rule states that an email should be sent when the Order is fulfilled, then your Fulfill method (or, if more appropriate, the setter for IsFulfilled) should trigger that action. I would probably have configuration information that pointed the business object at an appropriate email service for the application, or more generally to a "notifier" service so that other notification types could be added when/if necessary.</p>
43,990
<p><strong>Here is the context</strong><br/> I've got an old car for which I have a small plastic piece who is broken. As it's an old car and a very specific piece, I can't find it anymore. So I was thinking about 3D printing it.</p> <p>My problem is this piece is on the carburetor, so close to the engine. This means, it can heat a lot, close to 90-100&nbsp;°C.</p> <p><strong>My question</strong><br/> Do the pieces created with the common 3D printing techniques melt at 100&nbsp;°C? If yes, what kind of other 3D printing technique can I use?</p> <p>Here is the piece I want to recreate (sorry for the bad quality), the scale is in cm. <a href="https://i.stack.imgur.com/XBZ6Q.jpg" rel="noreferrer"><img src="https://i.stack.imgur.com/XBZ6Q.jpg" alt="The piece"></a></p>
<p>The number you're looking for is the <a href="https://en.wikipedia.org/wiki/Glass_transition" rel="noreferrer">glass transition temperature</a> (the lowest temperature at which the material can flow or warp), not the melting point. This depends on what material you're using; approximate temperatures for common printable materials are:</p> <ul> <li>PLA: 60˚C</li> <li>PETG, high-temperature PLA: 95 ˚C</li> <li>ABS: 105˚C</li> <li>Nylon: typically 70˚C or above ("Nylon" is a large family of similar polymers)</li> <li>Polycarbonate: 145˚C</li> </ul> <p>Any plastic under your hood is probably either nylon (for its durability, impact resistance, and chemical resistance) or ABS (for its strength and heat resistance). These are both difficult materials to print: ABS emits toxic fumes while printing, and tends to warp if you're not using a heated enclosure, while nylon readily absorbs water from the air, causing the filament to bubble as it's printed. Further, many printers can't handle the high temperatures needed to work with these materials.</p> <p>If you're going to print this yourself, I recommend using PETG and inspecting the part after a few days of use to see if it's warping. PETG is reasonably easy to print and comes close to your target heat resistance.</p> <p>If you're going to get someone else to print it, I recommend using ABS. It's probably what the original part was made of, and anyone willing to print ABS for you will have the heated enclosure and ventilation system to deal with printing it.</p> <p>I'd avoid polycarbonate unless you know the original part was made of it. Although PC is strong and heat resistant, it's also somewhat brittle and vulnerable to scratching.</p> <p>High-temperature PLA is also brittle, and requires a heat-treating step that will change the dimensions of the part. It will likely take several tries to get something that comes out the right size, and even then, you risk having the part break when your car hits a bump.</p>
<p>Nylon is probably your best bet. It is resistant to some chemicals as well. Figure on printing it at around 250 °C.</p> <p>It might do the job.</p>
1,530
<p>I am using the <strong><a href="http://en.wikipedia.org/wiki/JQuery" rel="noreferrer">jQuery</a> validation plugin</strong>. Great stuff! I want to migrate my existing ASP.NET solution to use jQuery instead of the ASP.NET validators. I am missing a replacement for the <strong>regular expression</strong> validator. I want to be able to do something like this:</p> <pre><code>$("Textbox").rules("add", { regularExpression: "^[a-zA-Z'.\s]{1,40}$" }) </code></pre> <p>How do I <strong>add a custom rule</strong> to achieve this?</p>
<p>Thanks to the answer of redsquare I added a method like this:</p> <pre class="lang-js prettyprint-override"><code>$.validator.addMethod( &quot;regex&quot;, function(value, element, regexp) { var re = new RegExp(regexp); return this.optional(element) || re.test(value); }, &quot;Please check your input.&quot; ); </code></pre> <p>Now all you need to do to validate against any regex is this:</p> <pre class="lang-js prettyprint-override"><code>$(&quot;#Textbox&quot;).rules(&quot;add&quot;, { regex: &quot;^[a-zA-Z'.\\s]{1,40}$&quot; }) </code></pre> <p>Additionally, it looks like there is a file called <code>additional-methods.js</code> that contains the method &quot;pattern&quot;, which can be a <code>RegExp</code> when created using the method without quotes.</p> <hr /> <h2>Edit</h2> <p>The <code>pattern</code> function is now the preferred way to do this, making the example:</p> <pre class="lang-js prettyprint-override"><code>$(&quot;#Textbox&quot;).rules(&quot;add&quot;, { pattern: &quot;^[a-zA-Z'.\\s]{1,40}$&quot; }) </code></pre> <ul> <li><a href="https://cdnjs.com/libraries/jquery-validate" rel="noreferrer">https://cdnjs.com/libraries/jquery-validate</a> <ul> <li><a href="https://cdnjs.cloudflare.com/ajax/libs/jquery-validate/1.19.2/jquery.validate.min.js" rel="noreferrer">https://cdnjs.cloudflare.com/ajax/libs/jquery-validate/1.19.2/jquery.validate.min.js</a></li> <li><a href="https://cdnjs.cloudflare.com/ajax/libs/jquery-validate/1.19.2/additional-methods.min.js" rel="noreferrer">https://cdnjs.cloudflare.com/ajax/libs/jquery-validate/1.19.2/additional-methods.min.js</a></li> </ul> </li> </ul>
<p>Have you tried this??</p> <pre><code>$(&quot;Textbox&quot;).rules(&quot;add&quot;, { regex: &quot;^[a-zA-Z'.\\s]{1,40}$&quot;, messages: { regex: &quot;The text is invalid...&quot; } }) </code></pre> <p>Note: make sure to escape all the &quot;\&quot; of ur regex by adding another &quot;\&quot; in front of them else the regex wont work as expected.</p>
35,511
<p>What's the best way to use Bazaar (bzr) as the version control system in Visual Studio 2008?</p>
<p>The best I found is <a href="http://bazaar-vcs.org/TortoiseBzr" rel="noreferrer">TortoiseBZR</a> and the command-line - nothing integrated with VS.</p>
<p>Unified SCC has support for bzr. It is commercial but claims to be free for OSS projects.</p> <p><a href="http://aigenta.com/products/UnifiedScc.aspx" rel="nofollow" title="UnifiedSCC">UnifiedSCC</a></p>
43,977
<p>I have a scenario where I'm not really sure my approach is the best one, and I would appreciate feedback / suggestions.</p> <p>scenario: I have a bunch of flash based (swf) 'modules' which are hosted in my aspnet application. Each flash has it's own directory on the filesystem, which contains assets for the flash. Consider this simplified site structure:</p> <p><em>/webapp/index.aspx<br> /webapp/flash/flash1/flash.swf<br> /webapp/flash/flash1/someimage.jpg<br> /webapp/flash/flash1/someclip.mp3<br> /webapp/flash/flash2/flash.swf<br> /webapp/flash/flash2/someimage.jpg<br> /webapp/flash/flash2/someclip.mp3</em> </p> <p>etcetera</p> <p>where the naming convention is <em>/webapp/flash/flash[ID]/</em> </p> <p>I want to implement a security mechanism which checks whether the user should be allowed access* to the files in the subfolder '[ID]' and it's contents. </p> <p>**insert business logic based on information stored in a SQL database here*</p> <p>I was considering writing a HttpModule which does something like</p> <pre><code>ProcessRequest(){ if(Request.RawUrl.Contains("/webapp/flash") &amp;&amp; !userHasValidLicenseForModule(1)){ Redirect("login.aspx"); } } </code></pre> <p>But there's the drawback that HttpModule only works for file extension which are mapped to aspnet (in IIS6). That means I would have to map all possible extensions to that process (.mp3, .jpg etc) which is something I would rather avoid.</p> <p>I was also considering to use a HttpHandler instead, but the flash file needs to be able to link to it's resources using relative URLs. (so a proxy-like pattern like /webapp/getprotectedstuff.ashx?file=flash1234/flash.swf is not prefered)</p> <p>Perhaps it's wiser to store the flash files and assets outside of the web root completely. Perhaps there are other strategies I havent thought of. </p> <p>Use aspnet security and write a custom membership provider?</p> <p>Any thoughts?</p>
<p>Have you considered simply validating resource access through an HTTP request to the server after the swf loads?</p> <p>Where I work we provide online trainings to users through flash but rather than verify the HTTP request itself, we allow the swf's to load first and then make a request to the server to verify that the user should have access to the swf and that they are accessing the swf from within our site and not from another location.</p> <p>If any step of validation fails (either it fails to find an auth file in the necessary location or the user does not have a valid session or does not have access to the particular training) then they receive an error within flash and none of the important content ever loads.</p> <p>As another note, if you do decide that you want to strictly limit access to the files so that they can only be loaded by those who should have access, then I would probably suggest using your second option of storing the files in a separate, non-public location and then using a handler script to load the swf.</p>
<p>Why not go with an ISAPI filter?<br> Okay, dont answer that - plenty of reasons ;-). But seriously, if you have the dev power for it, you might want to consider that route.</p> <p>Otherwise, HTTP Module does seem the better route, IF you have a short, closed list of extensions you have to deal with (GIF, JPG, MP3). If its long, or open-ended, I would agree and forgo that. </p> <p>Another option you might want to look into, if applicable, is role-based NTFS access lists. If this fits, it is probably the easiest and cleanest way to do it.</p>
20,531
<p>Is there any reason for the use of 'T' in generics? Is it some kind of abbreviation? As far as I know, everything works. For example </p> <pre><code>public G Say&lt;G&gt;(){ ... } </code></pre> <p>or even</p> <pre><code>public Hello Say&lt;Hello&gt;(){ ... } </code></pre>
<p>T is for <strong>T</strong>ype. But it's really just a tradition and there is nothing to prevent you from using other names. For example, generic dictionaries use <code>&lt;TKey, TValue&gt;</code>.</p> <p>There is also a <a href="http://msdn.microsoft.com/lv-lv/library/ms229040(en-us).aspx" rel="noreferrer">Microsoft guideline</a> that recommends using the letter <strong>T</strong> if you have a single type parameter, and prefix descriptive parameter names with <strong>T</strong> if you have more than one. Doing so will provide a more consistent feel across your code.</p>
<blockquote> <p><em>T for Type</em></p> </blockquote> <p>Also, E is used for Element that's very common too. You're right G also works.</p>
48,906
<p>In a Delphi Form, I would like to replace one visual component with another. Example: I want to replace a Panel component with an ElPanel from a 3rd party package. </p> <p>I would like all identical properties and events of the first component to be transferred to the new one, and all the components that belong to the first component (e.g. Toolbars, memos,status bars, etc.) to end up placed on the new component exactly where they were on the first one.</p> <p>Is there a best/easiest way to do this other than adding the new component to the form and meticulously transferring every property, event and component to it one-by-one?</p>
<p>I do it as following:</p> <ol> <li>Right click on the form and choose (View as Text).</li> <li>Press Ctrl + F to search for the Component class name like TPanel and replace it with TElPanel</li> <li>Switch back to back to the form (View as form)</li> <li>In the interface section replace the TPanel with TElPanel.</li> </ol> <p>if you have many components using GExperts will be more feasible solutions.</p>
<p>In my project I had to convert few doezens forms from one set of components to another. I have created small perl script to convert components and its properties and do all neccesary mapings. The script is quick&amp;dirty solution but it is highly configurable. It scanns all dfm and pas files in project direcotory and convert dfm components definitions according to rules that you should provide in ObjectBeginFound, PropertyFound, ObjectEndFound procedures/events. </p> <p>DFM files should be in text mode. Tested on Delphi 5 files. I don't know if it will be compatible with newer versions. Please send posts if you find it out.</p> <p>USAGE: perl.exe cxdfm.pl > logfile.txt</p> <p>DOWNLOAD LINK <a href="http://dl.dropbox.com/u/15887789/cxdfm.pl" rel="nofollow">http://dl.dropbox.com/u/15887789/cxdfm.pl</a></p>
29,552
<p>Is it possible to set the cursor to 'wait' on the entire html page in a simple way? The idea is to show the user that something is going on while an ajax call is being completed. The code below shows a simplified version of what I tried and also demonstrate the problems I run into:</p> <ol> <li>if an element (#id1) has a cursor style set it will ignore the one set on body (obviously) </li> <li>some elements have a default cursor style (a) and will not show the wait cursor on hover </li> <li>the body element has a certain height depending on the content and if the page is short, the cursor will not show below the footer</li> </ol> <p>The test:</p> <pre><code>&lt;html&gt; &lt;head&gt; &lt;style type="text/css"&gt; #id1 { background-color: #06f; cursor: pointer; } #id2 { background-color: #f60; } &lt;/style&gt; &lt;/head&gt; &lt;body&gt; &lt;div id="id1"&gt;cursor: pointer&lt;/div&gt; &lt;div id="id2"&gt;no cursor&lt;/div&gt; &lt;a href="#" onclick="document.body.style.cursor = 'wait'; return false"&gt;Do something&lt;/a&gt; &lt;/body&gt; &lt;/html&gt; </code></pre> <p>Later edit...<br> It worked in firefox and IE with: </p> <pre><code>div#mask { display: none; cursor: wait; z-index: 9999; position: absolute; top: 0; left: 0; height: 100%; width: 100%; background-color: #fff; opacity: 0; filter: alpha(opacity = 0);} &lt;a href="#" onclick="document.getElementById('mask').style.display = 'block'; return false"&gt; Do something&lt;/a&gt; </code></pre> <p>The problem with (or feature of) this solution is that it will prevent clicks because of the overlapping div (thanks Kibbee)</p> <p>Later later edit...<br> A simpler solution from Dorward:</p> <pre><code>.wait, .wait * { cursor: wait !important; } </code></pre> <p>and then </p> <pre><code>&lt;a href="#" onclick="document.body.className = 'wait'; return false"&gt;Do something&lt;/a&gt; </code></pre> <p>This solution only shows the wait cursor but allows clicks.</p>
<p>If you use this slightly modified version of the CSS you posted from Dorward,</p> <pre><code>html.wait, html.wait * { cursor: wait !important; } </code></pre> <p>you can then add some really simple <a href="http://api.jquery.com/" rel="noreferrer">jQuery</a> to work for all ajax calls:</p> <pre><code>$(document).ready(function () { $(document).ajaxStart(function () { $("html").addClass("wait"); }); $(document).ajaxStop(function () { $("html").removeClass("wait"); }); }); </code></pre> <p>or, for older jQuery versions (before 1.9):</p> <pre><code>$(document).ready(function () { $("html").ajaxStart(function () { $(this).addClass("wait"); }); $("html").ajaxStop(function () { $(this).removeClass("wait"); }); }); </code></pre>
<p>Late to the party but simply give the Html tag an id by targeting</p> <p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false"> <div class="snippet-code"> <pre class="snippet-code-js lang-js prettyprint-override"><code>document.documentElement</code></pre> </div> </div> </p> <p>and in the CSS place at the top</p> <p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false"> <div class="snippet-code"> <pre class="snippet-code-css lang-css prettyprint-override"><code>html#wait * { cursor: wait !important; }</code></pre> </div> </div> </p> <p>and simply remove it when you want to stop this cursor.</p>
23,441
<p>I'm planning to write a javascript-based web application. I'm wondering what the best way to implement it in terms of file stucture is.</p> <p>There is one main page (main.html) containing a menu and a main div section. The way it works is simple: When the user clicks on one of the links in the menu (for example 'Page 1'), the content of the div section is refreshed with the content of the page1.html file. This is done using javascript (jquery). If the user clicks on 'Page 2', the content of the page2.html file is loaded into the div section, etc.</p> <p>Each page has its own javascript code and as I prefer to keep it separate I've implemented a sort of 'code behind' like in asp.net:</p> <p><b>page1.html</b>:<br> &lt; script type="text/javascript" src="<b>page1.js"</b> >&lt; /script> <br> &lt;... html code ...> <br><br> <b>page2.html</b>:<br> &lt; script type="text/javascript" src="<b>page2.js"</b> >&lt; /script > <br> &lt;... html code ...></p> <p>When the user clicks on 'Page 1', the content of the page1.html file is loaded into the main div section of main.html. As page1.html is referencing page1.js, the javascript code in page1.js is also loaded.</p> <p>This seems to work fine but I'm wondering if it is the best way to implement this. At some point I was thinking of referencing all the javascript files in main.html This would also work fine but it would mean all the javascript files would have to be loaded in memory even if they are not going to be used. With the 1st approach, a javascript file is only loaded in memory before being actually used.</p> <p>Any ideas? What are the 'best practises' for this? Keep in mind that this is a web application (as opposed to a website). It will be available over the internet but only to some users (and it will be password protected) so I don't care about SEO etc.</p>
<p>It might be of no consequence to you but you know that from an SEO perspective this is a terrible idea. Your site will be a Javascript version of a flash site. There will be only one page as far as the search engines are concerned.</p> <p>That's why sites based on frames, which were quite popular for a number of years, all but disappeared.</p>
<p>Loading of JavaScript files is synchronous, which negatively affects page loading time/perceived responsiveness.</p> <p>For that reason I think it's best to merge all scripts into one file, compress it with YUI compressor and send gzipped. You'll get best compression and least HTTP overhead this way, and cached JS won't pause loading of other pages.</p> <p>For page-specific, dynamic scripts use in-line <code>&lt;script&gt;…&lt;/script&gt;</code>.</p>
41,116
<p>I'm using repository pattern with LINQ, have IRepository.DeleteOnSubmit(T Entity). It works fine, but when my entity class has interface, like this: </p> <pre><code>public interface IEntity { int ID {get;set;} } public partial class MyEntity: IEntity { public int ID { get { return this.IDfield; } set { this.IDfield=value; } } } </code></pre> <p>and then trying to delete some entity like this: </p> <pre><code>IEntity ie=repository.GetByID(1); repoitory.DeleteOnSubmit(ie); </code></pre> <p>throws<br> The member 'IEntity.ID' has no supported translation to SQL. </p> <p>fetching data from DB works, but delete and insert doesn't. How to use interface against DataContext?</p> <hr> <p>Here it is:<br> Exception message: The member 'MMRI.DAL.ITag.idContent' has no supported translation to SQL. </p> <p>Code: </p> <pre><code>var d = repContent.GetAll().Where(x =&gt; x.idContent.Equals(idContent)); foreach (var tagConnect in d) &lt;- error line { repContet.DeleteOnSubmit(tagConnect); </code></pre> <p>(it gets all tags from DB, and deletes them)</p> <p>And stack trace: </p> <pre><code>[NotSupportedException: The member 'MMRI.DAL.ITag.idContent' has no supported translation to SQL.] System.Data.Linq.SqlClient.Visitor.VisitMember(SqlMember m) +621763 System.Data.Linq.SqlClient.SqlVisitor.Visit(SqlNode node) +541 System.Data.Linq.SqlClient.SqlVisitor.VisitExpression(SqlExpression exp) +8 System.Data.Linq.SqlClient.SqlVisitor.VisitBinaryOperator(SqlBinary bo) +18 System.Data.Linq.SqlClient.Visitor.VisitBinaryOperator(SqlBinary bo) +18 System.Data.Linq.SqlClient.SqlVisitor.Visit(SqlNode node) +196 System.Data.Linq.SqlClient.SqlVisitor.VisitExpression(SqlExpression exp) +8 System.Data.Linq.SqlClient.SqlVisitor.VisitSelectCore(SqlSelect select) +46 System.Data.Linq.SqlClient.Visitor.VisitSelect(SqlSelect select) +20 System.Data.Linq.SqlClient.SqlVisitor.Visit(SqlNode node) +1024 System.Data.Linq.SqlClient.SqlProvider.BuildQuery( ... </code></pre> <p>When I try do decorate partial class:</p> <pre><code>[Column(Storage = "_idEvent", DbType = "Int NOT NULL", IsPrimaryKey = true)] public int idContent { get { return this.idEvent; } set { this.idEvent=value; } } </code></pre> <p>it throws error "Invalid column name 'idContent'."</p>
<p>It appears Microsoft dropped support for <code>==</code> operator in interfaces when using linq-to-sql in MVC4 (or maybe it was never supported). You can however use <code>i.ID.Equals(someId)</code> in place of the <code>==</code> operator.</p> <p>Casting <code>IQueryable</code> to <code>IEnumerable</code> works but <strong>should not be used!</strong> The reason is: <code>IQueryable</code> has funky implementation of <code>IEnumerable</code>. Whatever linq method you'll use on a <code>IQueryable</code> through the <code>IEnumerable</code> interface will cause the query to be executed first, have all the results fetched to the memory from the DB and eventually running the method localy on the data (normally those methods would be translated to SQL and executed in the DB). Imagine trying to get a single row from a table containing billion rows, fetching all of them only to pick one (and it gets much worse with careless casting of <code>IQueryable</code> to <code>IEnumerable</code> and lazy loading related data).</p> <p>Apparently Linq has no problem using <code>==</code> operator with interfaces on local data (so only <code>IQueryable</code> is affected) and also with Entity Frameworks (or so I heard).</p>
<p>Try this:</p> <pre><code>using System.Data.Linq.Mapping; public partial class MyEntity: IEntity { [Column(Storage="IDfield", DbType="int not null", IsPrimaryKey=true)] public int ID { get { return this.IDfield; } set { this.IDfield=value; } } } </code></pre>
3,514
<p>I have a dev, that will get around our code coverage by writing tests that never fail.</p> <p>The code is just atrocious, but the tests never catch it because they assert(true).</p> <p>I code review, but I can't do everyones work for them, all the time. How do you get people like this motivated to make good software?</p> <p>Is there a build plugin for detecting tests that can't fail?</p> <p>C#, mbUnit tests.</p>
<p>Real motiviation comes from within. Some people will game the system every chance they get sometimes for no other reason than they can. Others do it simply because they are hacks.</p> <p>That said, assuming your the manager, have a "come to jesus" meeting with the dev. If that still doesn't work, there's always the door.</p> <p>If you're not the manager, then take it up the proper channels.</p>
<p>You should really specify the language / framework you're using.</p> <p>In the simplest case, I suppose it should be easy to detect <code>assert(true)</code> strings with simple <code>grep</code>-ping.</p>
13,084
<p>On the web side we are working on getting source control. Now, I want to see what can be done for the iSeries side. What is your favorite source control application for iSeries and why? I am looking for low-cost if possible.</p>
<p>The two most common source control packages for the iSeries are <a href="http://www.softlanding.com/turnover/index.htm" rel="nofollow noreferrer">Turnover</a> and <a href="http://www.aldon.com/products/lmi/" rel="nofollow noreferrer">Aldon</a>. Neither are low cost but integrate well with the iSeries.</p> <p>I prefer <strong>Turnover</strong>. It flawlessly handles production installs to both a local and remote iSeries.</p>
<p>If you're using the <strong>WebSphere Development Studio</strong> or <strong>Rational</strong> from a PC then any source control system that will play nicely with that is an option if you don't want to shell out for the native iSeries one.</p>
16,376
<p>Sometimes I have made some local changes and for whatever reason don't want to commit them to the source repository. In this case I like to zip up and save off my changes on my local file system until I am ready to commit them at a later date.</p> <p>I recall that in an earlier version of eclipse, there was a context sensitive action from the Synchronize view that would highlight in the Navigator view the same files that you have selected in the Synchronize view. Then from the Navigator view, you can choose to export the highlighted selection.</p> <p>I don't see where that option is still available from the Synchronize view anymore and manually selecting the files in the Navigator/Package Explorer view is tedious. Is there an easy way to export a selection of files within the Synchronize view?</p>
<p>It's not on the context menu, but going to the Navigate menu up top and selecting "Show In->Navigator" will apply that selection. Whether or not you can export just the selected files, I don't know.</p>
<p>This is how I do in eclipse 2019-06 (4.12.0)</p> <p>Suppose, I am working on an issue of Primeface Upgrade and a new issue came. I need to take a backup of the existing changes related to the PF upgrade to a specific changeset, say <em>upgrade</em> first. Following is the process</p> <ol> <li>Open Team Synchronizing perspective</li> <li>On the synchronize view, the very last button is the Change Sets button, turn that on</li> <li>Select all the files which should be part of the changeset <em>upgrade</em>. Right-click on a file listed and then Add To/Reassign Changes To -&gt; New Change Set -&gt; Give name as <em>upgrade</em> -&gt; Select &quot;Enter a Commit comment&quot; -&gt; Enter Commit comment -&gt; click Ok</li> <li>Add all the files which should be part of the changeset using the same method</li> <li>Right-click on the changeset <em>upgrade</em> -&gt; create path -&gt; Save In File System -&gt; Chose location and file -&gt; Choose Workspace -&gt; Finish</li> <li>Above step will create the patch file which we can reapply to get the effect of the changeset</li> <li>To reapply: right click on the version where the changeset will be applied -&gt; Team -&gt; Apply Patch -&gt; Choose File -&gt; Select the path file -&gt; Next -&gt; Check all the changes are imported -&gt; Finish.</li> <li>After my work each day, I take daily back up of this patch file only using step 5</li> </ol>
25,077
<p>When attempting to call functions in <code>math.h</code>, I'm getting link errors like the following </p> <pre><code>undefined reference to sqrt </code></pre> <p>But I'm doing a <code>#include &lt;math.h&gt;</code><br> I'm using gcc and compiling as follows:</p> <pre><code>gcc -Wall -D_GNU_SOURCE blah.c -o blah </code></pre> <p>Why can't the linker find the definition for <code>sqrt</code>?</p>
<p>Add -lm to the command when you call gcc:<br> gcc -Wall -D_GNU_SOURCE blah.c -o blah -lm</p> <p>This will tell the linker to link with the math library. Including math.h will tell the compiler that the math functions like sqrt() exist, but they are defined in a separate library, which the linker needs to pack with your executable.</p> <p>As FreeMemory pointed out the library is called libm.a . On Unix-like systems, the rule for naming libraries is lib[blah].a . Then if you want to link them to your executable you use -l[blah] .</p>
<p>You need to link the math library explicitly. Add <code>-lm</code> to the flags you're passing to gcc so that the linker knows to link <code>libm.a</code></p>
12,896
<p>I want to install a gem on all my application servers, but gem install requires sudo access - how can I enable sudo only for running this capistrano command? </p> <p>In other words, I don't wish to use sudo for all my deployment recipes, just when I invoke this command on the command line.</p>
<p>Found it - cap invoke COMMAND="<em>command that requires sudo</em>" SUDO=1</p>
<p>It would be best to use unix ACLs or similar permissions for this. Give the deploy user sudoer access, then you can call <code>run "sudo do_something"</code> and it will be sudo-level access only for that call.</p>
15,678
<p>I have worked on projects for embedded systems in the past where we have rearranged the order of declaration of stack variables to decrease the size of the resulting executable. For instance, if we had:</p> <pre><code>void func() { char c; int i; short s; ... } </code></pre> <p>We would reorder this to be:</p> <pre><code>void func() { int i; short s; char c; ... } </code></pre> <p>Because of alignment issues the first one resulted in 12 bytes of stack space being used and the second one resulted in only 8 bytes.</p> <p>Is this standard behavior for C compilers or just a shortcoming of the compiler we were using? </p> <p>It seems to me that a compiler should be able to reorder stack variables to favor smaller executable size if it wanted to. It has been suggested to me that some aspect of the C standard prevents this, but I haven't been able to find a reputable source either way.</p> <p>As a bonus question, does this also apply to C++ compilers?</p> <p><strong>Edit</strong></p> <p>If the answer is yes, C/C++ compilers can rearrange stack variables, can you give an example of a compiler that definitely does this? I'd like to see compiler documentation or something similar that backs this up.</p> <p><strong>Edit Again</strong></p> <p>Thanks everybody for your help. For documentation, the best thing I've been able to find is the paper <a href="http://mirror-fpt-telecom.fpt.net/gcc/summit/2003/Optimal%20Stack%20Slot%20Assignment.pdf" rel="noreferrer">Optimal Stack Slot Assignment in GCC</a>(pdf), by Naveen Sharma and Sanjiv Kumar Gupta, which was presented at the GCC summit proceedings in 2003.</p> <p>The project in question here was using the ADS compiler for ARM development. It is mentioned in the documentation for that compiler that ordering declarations like I've shown can improve performance, as well as stack size, because of how the ARM-Thumb architecture calculates addresses in the local stack frame. That compiler didn't automatically rearrange locals to take advantage of this. The paper linked here says that as of 2003 GCC also didn't rearrange the stack frame to improve locality of reference for ARM-Thumb processors, but it implies that you could.</p> <p>I can't find anything that definitely says this was ever implemented in GCC, but I think this paper counts as proof that you're all correct. Thanks again.</p>
<p>As there is nothing in the standard prohibiting that for C or C++ compilers, yes, the compiler can do that. </p> <p>It is different for aggregates (i.e. structs), where the relative order must be maintained, but still the compiler may insert pad bytes to achieve preferable alignment. </p> <p>IIRC newer MSVC compilers use that freedom in their fight against buffer overflows of locals.</p> <p>As a side note, in C++, the order of destruction must be reverse order of declaration, even if the compiler reorders the memory layout.</p> <p>(I can't quote chapter and verse, though, this is from memory.)</p>
<p>it is compiler specifics, one can make his own compiler that would do the inverse if he wanted it that way.</p>
29,487
<p>I'm trying to load test data into a test DB during a maven build for integration testing. persistence.xml is being copied to <code>target/test-classes/META-INF/</code> correctly, but I get this exception when the test is run.</p> <blockquote> <p>javax.persistence.PersistenceException: No Persistence provider for EntityManager named aimDatabase</p> </blockquote> <p>It looks like it's not finding or loading persistence.xml.</p>
<p>Just solved the same problem with a Maven/Eclipse based JPA project.</p> <p>I had my META-INF directory under <code>src/main/java</code> with the concequence that it was not copied to the target directory before the test phase.</p> <p>Moving this directory to <code>src/main/resources</code> solved the problem and ensured that the <code>META-INF/persistence.xml</code> file was present in <code>target/classes</code> when the tests were run.</p> <p>I <em>think</em> that the JPA facet put my <code>META-INF/persistence.xml</code> file in <code>src/main/java</code>, which turned out to be the root of my problem.</p>
<p>we got the same problem, does some tweaking on the project and finaly find following problem (more clear error description): at oracle.toplink.essentials.ejb.cmp3.persistence. PersistenceUnitProcessor.computePURootURL(PersistenceUnitProcessor.java:248)</p> <p>With that information we recalled a primary rule: NO WHITE SPACES IN PATH NAMES!!!</p> <p>Try this. Works for us <em>smile</em>. Maybe some day this will be fixed.</p> <p>Hope this works for you. Good luck.</p>
10,222
<p>How do you handle update refresh rate from your worker function to your UI ?</p> <p>Sending everything to the UI or maybe using a timer (from which side ? worker or UI ?)</p>
<p>Just for some clarification. In the early microprocessor days of the 1970's, CPUs had only a small number of registers and a very limited instruction set. Typically, the arithmetic unit could only operate on a single CPU register, often referred to as the "accumulator". The accumulator on the 8 bit 8080 &amp; Z80 processors was called "A". There were 6 other general purpose 8 bit registers: B, C, D, E, H &amp; L. These six registers could be paired up to form 3 16 bit registers: BC, DE &amp; HL. Internally, the accumulator was combined with the Flags register to form the AF 16 bit register.</p> <p>When Intel developed the 16 bit 8086 family they wanted to be able to port 8080 code, so they kept the same basic register structure:</p> <pre><code>8080/Z80 8086 A AX BC BX DE CX HL DX IX SI IY DI </code></pre> <p>Because of the need to port 8 bit code they needed to be able to refer to the individual 8 bit parts of AX, BX, CX &amp; DX. These are called AL, AH for the low &amp; high bytes of AX and so on for BL/BH, CL/CH &amp; DL/DH. IX &amp; IY on the Z80 were only ever used as 16 bit pointer registers so there was no need to access the two halves of SI &amp; DI.</p> <p>When the 80386 was released in the mid 1980s they created "extended" versions of all the registers. So, AX became EAX, BX became EBX etc. There was no need to access to top 16 bits of these new extended registers, so they didn't create an EAXH pseudo register.</p> <p>AMD applied the same trick when they produced the first 64 bit processors. The 64 bit version of the AX register is called RAX. So, now you have something that looks like this:</p> <pre><code>|63..32|31..16|15-8|7-0| |AH.|AL.| |AX.....| |EAX............| |RAX...................| </code></pre>
<p>In the old 8-bit days, there was the A register.</p> <p>In the 16-bit days, there was the 16 bit AX register, which was split into two 8 bit parts, AH and AL, for those times when you still wanted to work with 8 bit values.</p> <p>In the 32-bit days, the 32 bit EAX register was introduced, but the AX, AH, and AL registers were all kept. The designers did not feel it necessary to introduce a new 16 bit register that addressed bits 16 through 31 of EAX.</p>
28,241
<p>CSS and Javascript files don't change very often, so I want them to be cached by the web browser. But I also want the web browser to see changes made to these files without requiring the user to clear their browser cache. Also want a solution that works well with a version control system such as Subversion.</p> <hr /> <blockquote> <p>Some solutions I have seen involve adding a version number to the end of the file in the form of a query string.</p> <p>Could use the SVN revision number to automate this for you: <a href="https://stackoverflow.com/questions/2308/aspnet-display-svn-revision-number">ASP.NET Display SVN Revision Number</a></p> </blockquote> <p>Can you specify how you include the <a href="http://svnbook.red-bean.com/en/1.4/svn.advanced.props.special.keywords.html" rel="noreferrer">Revision</a> variable of another file? That is in the HTML file I can include the Revision number in the URL to the CSS or Javascript file.</p> <p>In the <a href="http://svnbook.red-bean.com" rel="noreferrer">Subversion book</a> it says about Revision: &quot;This keyword describes the last known revision in which this file changed in the repository&quot;.</p> <blockquote> <p>Firefox also allows pressing <kbd>CTRL</kbd>+<kbd>R</kbd> to reload everything on a particular page.</p> </blockquote> <p>To clarify I am looking for solutions that don't require the user to do anything on their part.</p>
<p>I found that if you append the last modified timestamp of the file onto the end of the URL the browser will request the files when it is modified. For example in PHP:</p> <pre><code>function urlmtime($url) { $parsed_url = parse_url($url); $path = $parsed_url['path']; if ($path[0] == "/") { $filename = $_SERVER['DOCUMENT_ROOT'] . "/" . $path; } else { $filename = $path; } if (!file_exists($filename)) { // If not a file then use the current time $lastModified = date('YmdHis'); } else { $lastModified = date('YmdHis', filemtime($filename)); } if (strpos($url, '?') === false) { $url .= '?ts=' . $lastModified; } else { $url .= '&amp;ts=' . $lastModified; } return $url; } function include_css($css_url, $media='all') { // According to Yahoo, using link allows for progressive // rendering in IE where as @import url($css_url) does not echo '&lt;link rel="stylesheet" type="text/css" media="' . $media . '" href="' . urlmtime($css_url) . '"&gt;'."\n"; } function include_javascript($javascript_url) { echo '&lt;script type="text/javascript" src="' . urlmtime($javascript_url) . '"&gt;&lt;/script&gt;'."\n"; } </code></pre>
<p>Some solutions I have seen involve adding a version number to the end of the file in the form of a query string.</p> <pre><code>&lt;script type="text/javascript" src="funkycode.js?v1"&gt; </code></pre> <p>You could use the SVN revision number to automate this <a href="https://stackoverflow.com/questions/2308/aspnet-display-svn-revision-number">for you</a> by including the word <strong>LastChangedRevision</strong> in your html file after where v1 appears above. You must also setup your repository to do this.</p> <p>I hope this further clarifies my answer?</p> <p>Firefox also allows pressing <kbd>CTRL</kbd> + <kbd>R</kbd> to reload everything on a particular page.</p>
2,539
<p>I have a series of text that contains mixed numbers (ie: a whole part and a fractional part). The problem is that the text is full of human-coded sloppiness:</p> <ol> <li>The whole part may or may not exist (ex: "10")</li> <li>The fractional part may or may not exist (ex: "1/3")</li> <li>The two parts may be separated by spaces and/or a hyphens (ex: "10 1/3", "10-1/3", "10 - 1/3").</li> <li>The fraction itself may or may not have spaces between the number and the slash (ex: "1 /3", "1/ 3", "1 / 3").</li> <li>There may be other text after the fraction that needs to be ignored</li> </ol> <p>I need a regex that can parse these elements so that I can create a proper number out of this mess.</p>
<p>Here's a regex that will handle all of the data I can throw at it:</p> <pre><code>(\d++(?! */))? *-? *(?:(\d+) */ *(\d+))?.*$ </code></pre> <p>This will put the digits into the following groups:</p> <ol> <li>The whole part of the mixed number, if it exists</li> <li>The numerator, if a fraction exits</li> <li>The denominator, if a fraction exists</li> </ol> <p>Also, here's the RegexBuddy explanation for the elements (which helped me immensely when constructing it):</p> <pre><code>Match the regular expression below and capture its match into backreference number 1 «(\d++(?! */))?» Between zero and one times, as many times as possible, giving back as needed (greedy) «?» Match a single digit 0..9 «\d++» Between one and unlimited times, as many times as possible, without giving back (possessive) «++» Assert that it is impossible to match the regex below starting at this position (negative lookahead) «(?! */)» Match the character “ ” literally « *» Between zero and unlimited times, as many times as possible, giving back as needed (greedy) «*» Match the character “/” literally «/» Match the character “ ” literally « *» Between zero and unlimited times, as many times as possible, giving back as needed (greedy) «*» Match the character “-” literally «-?» Between zero and one times, as many times as possible, giving back as needed (greedy) «?» Match the character “ ” literally « *» Between zero and unlimited times, as many times as possible, giving back as needed (greedy) «*» Match the regular expression below «(?:(\d+) */ *(\d+))?» Between zero and one times, as many times as possible, giving back as needed (greedy) «?» Match the regular expression below and capture its match into backreference number 2 «(\d+)» Match a single digit 0..9 «\d+» Between one and unlimited times, as many times as possible, giving back as needed (greedy) «+» Match the character “ ” literally « *» Between zero and unlimited times, as many times as possible, giving back as needed (greedy) «*» Match the character “/” literally «/» Match the character “ ” literally « *» Between zero and unlimited times, as many times as possible, giving back as needed (greedy) «*» Match the regular expression below and capture its match into backreference number 3 «(\d+)» Match a single digit 0..9 «\d+» Between one and unlimited times, as many times as possible, giving back as needed (greedy) «+» Match any single character that is not a line break character «.*» Between zero and unlimited times, as many times as possible, giving back as needed (greedy) «*» Assert position at the end of the string (or before the line break at the end of the string, if any) «$» </code></pre>
<p>If you are using <code>Perl 5.10</code>, this is how I would write it.</p> <pre> m{ ^ \s* # skip leading spaces (?'whole' \d++ (?! \s*[\/] ) # there should not be a slash immediately following a whole number ) \s* (?: # the rest should fail or succeed as a group -? # ignore possible neg sign \s* (?'numerator' \d+ ) \s* [\/] \s* (?'denominator' \d+ ) )? }x </pre> <p>Then you can access the values from the <code>%+</code> variable like this:</p> <pre><code>$+{whole}; $+{numerator}; $+{denominator}; </code></pre>
30,435
<p><strong>Concrete use case:</strong> In the Eclipse IDE, new 'plugins' can be added by copying a plugin's file(s) into the <code>$ECLIPSE_HOME/plugins</code> directory. However, I want to keep my original Eclipse installation 'clean' without additional plugins because I want to run this basic installation on its own at times. </p> <p>What is a way of avoiding having to copy the files (and hence therefore not being able to run a clean version) and instead logically 'overlaying' the contents of another directory so that it appears to be in the directory at runtime?</p> <p>e.g. something like:</p> <pre><code>gravelld@gravelld-laptop:~$ ls $ECLIPSE_HOME/plugins/ org.junit_3.8.2.v200706111738 org.junit4_4.3.1 org.junit.source_3.8.2.v200706111738 gravelld@gravelld-laptop:~$ ls myplugins/ org.dangravell.myplugin.jar gravelld@gravelld-laptop:~$ overlay myplugins/ $ECLIPSE_HOME/plugins gravelld@gravelld-laptop:~$ ls $ECLIPSE_HOME/plugins/ org.dangravell.myplugin.jar org.junit_3.8.2.v200706111738 org.junit4_4.3.1 org.junit.source_3.8.2.v200706111738 </code></pre> <p>Another use case may be around patching and so on...</p> <p>Can something be done with symbolic links or mnt for this?</p> <p>Thanks!</p>
<p>You could use an overlay filesystem for this. The three overlay filesystems that I know of in Linux are <a href="http://en.wikipedia.org/wiki/UnionFS" rel="nofollow noreferrer">unionfs</a>, <a href="http://aufs.sourceforge.net/" rel="nofollow noreferrer">aufs</a>, and <a href="http://www.denx.de/wiki/Know.MiniFOHome" rel="nofollow noreferrer">minifo</a>.</p> <p>Unionfs is included in recent Ubuntu kernels.</p>
<p>Have a look at <strong><a href="http://www.ibm.com/developerworks/library/os-ecl-manage/" rel="nofollow noreferrer">Manage your eclipse environment</a></strong> article, especially the Method 3</p> <blockquote> <p>Creating a links folder to manage product extensions</p> <p>If you have product extensions sitting on your file system, like the one we made in Method 1, you can create a few simple files in your Eclipse program directory to notify Eclipse that it needs to check these directories for plug-ins.</p> <p>First, create a directory inside your Eclipse installation folder (for example, /opt/eclipse) called links. Within this folder, you can create *.link files (for example, emfPlugins.link). Each link file points to a product extension location. Eclipse will scan this links folder on startup and find the plug-ins in each product extension pointed to by a link file.</p> </blockquote> <p>This is still supported in eclipse3.4 even though the new p2 provisioning system is quite different.</p> <hr /> <p>Now that the &quot;'links' directory mechanism&quot; is known, it means the difference between a vanilla eclipse and an eclipse with custom common plugins is just the presence of that 'links' directory.</p> <p>So, why not have a 'vanilla eclipse distribution' with a symbolic link inside, 'links', pointing to ../links ?</p> <p>Any user getting that vanilla eclipse would have at first no 'links' directory alongside it, so it will run as a vanilla distribution. But as soon the user creates a links directory or make another symbolic link to a common remote 'links' directory, that same distribution will pick up the common plugins remote directory...</p> <pre><code>/path/links -&gt; /remote/links/commonPlugins /eclipse/links -&gt; ../links </code></pre> <hr /> <p>Finally, if you create the &quot;/remote/links/commonPlugins&quot; with a given group &quot;aGroup&quot;, and protect it with a '750' mask, you have yourself <em>one</em> eclipse setup which will be:</p> <ul> <li>vanilla eclipse for any user whom 'id -a' does not include 'aGroup'</li> <li>eclipse with plugins for any user part of &quot;aGroup&quot;</li> </ul>
18,990
<p>I have a div tag styled through CSS. I set the padding to 10px (padding:10px), it works just as I wanted in Firefox and IE7, but in IE6 it adds additional padding at the bottom (about 2-3px I think). Anyone has idea about what's happening here?</p> <p>[update]</p> <p>I just noticed this, the div tag I'm talking about has a background-image. When I removed the background-image, the extra padding on the bottom disappears. Any ideas?</p> <p>[another update, code sample]</p> <p>Here's the CSS applied to my div tag:</p> <pre><code>.user-info{ margin-top: 20px; margin-right: 20px; padding: 10px; background-image: url("../img/user_panel_bg.png"); float:right; border: 1px #AAAAAA solid; font-size:12px; } </code></pre>
<p>Is there an image in your div? If there's an image, there's a bug in IE 6 that can cause white space within the div to create extra padding on the bottom</p> <p>Extra padding shows up with</p> <pre><code>&lt;div&gt; &lt;img src="myimage.jpg"&gt; &lt;/div&gt; </code></pre> <p>Extra padding doesn't show up when you change your HTML to</p> <pre><code>&lt;div&gt;&lt;img src="myimage.jpg"&gt;&lt;/div&gt; </code></pre>
<p>potentially 'margin' or 'border' properties?</p>
47,217
<p>I have an MFC legacy app that I help to maintain. I'm not quite sure how to identify the version of MFC and I don't think it would make a difference anyway. </p> <p>The app can take some parameters on the command line; I would like to be able to set an errorlevel on exiting the app to allow a bat/cmd file to check for failure and respond appropriately. </p> <p>I don't believe that exit() would work (hadn't tried it yet to be honest) because of the fact that this is an MFC app. Anyone know how to set the errorlevel returned by an MFC app? Can I just use exit()? </p>
<p>I can't take credit for this so please don't up this reply.</p> <p>CWinApp::ExitInstance(); return myExitCode;</p> <p>This will return the errorlevel to the calling batch file for you to then evaluate and act upon.</p>
<p>There are a couple of solutions listed <a href="http://social.msdn.microsoft.com/Forums/en-US/vcgeneral/thread/00d97998-f0b2-439a-9fa3-5dbcdd47cac4/" rel="nofollow noreferrer">here</a> I can't comment on which is better, but I'm sure at least one of them will get you there.</p>
33,782
<p>Do you still use session or entity EJBs in your project? Why?</p>
<p>EJB3 is a <strong>vast</strong> improvement over previous versions. It's still <em>technically</em> the standard server-side implementation toolset for JavaEE and since it now has none of the previous baggage (thanks to annotations and Java Persistence), is quite usable and being deployed as we speak. As one commenter noted, JBoss SEAM is based upon it.</p> <p>EJB 3 is a viable alternative to Spring, and the two technologies may become more tightly related. <a href="http://java.dzone.com/articles/end-spring-vs-ejb-wars-sight" rel="noreferrer">this</a> article details that Spring 3.0 will be compatible with EJB Lite (which I'm not sure what that is, exactly) and possibly be part of Java EE 6.</p> <p>EJB is not going anywhere.</p>
<p>I've just started back to work on an EJB project. I didn't remember how heavy and hard was to work with this technology. It was luck when Spring, Hibernate and Maven came. Since then everything was different and much easier.</p> <p>I always could see this technology was never used properly and was taken as a pattern that I never understood.</p> <p>It was supposed you needed two containers and if it was possible one server for each container. One for Business(EJBs) and another one for Views(MVC). I never saw that.</p> <p>Well, it's good to know that EBJ is upgrading.</p>
13,409
<p>Do you bother initialising java bean values? Say, for example:</p> <p>([g|s]etters omitted)</p> <pre><code>public class SomeClass { private String foo; private Date bar; private Baz someObject; } </code></pre> <p>(Yes, this is a POJO being used as a bean rather than a Java Bean in the strictest sense)</p> <p>In the empty constructor, do you initialise these members, or simply do nothing? Likewise, would Baz initialise it's members as well?</p> <p>Or do you just leave them as null?</p>
<p>It depends on the use case.</p> <p>If I use properties as service dependencies, they should be initialized to operate properly (btw, Spring DI has handy way to do it). </p> <p>If I use bean as part of domain model, it is usually illegal state to have some null property. It may not be initialized at startup, but I bother throwing IllegalStateException if some field is null during the business operation. </p>
<p>If at all possible, I initialize variables at declaration if they need to be initialized. These initialization statements actually wind up being called from the constructor.</p> <p>I do generally leave them as null if there's not a compelling reason to initialize them.</p>
27,752
<p>I need to be able to change a user's password from a cron task or from an ssh session. Is there an easy way to do that with a bash script? If not, what's the easiest way to do it in Cocoa?</p>
<p>Use the <code>passwd</code> shell command.</p>
<p>Use the <code>passwd</code> shell command.</p>
46,072
<p>I've read <a href="http://chriscavanagh.wordpress.com/2008/03/11/aspnet-routing-goodbye-url-rewriting/" rel="noreferrer">ASP.NET Routing… Goodbye URL rewriting?</a> and <a href="http://haacked.com/archive/2008/03/11/using-routing-with-webforms.aspx" rel="noreferrer">Using Routing With WebForms</a> which are great articles, but limited to simple, illustrative, "hello world"-complexity examples.</p> <p>Is anyone out there using ASP.NET routing with web forms in a non-trivial way? Any gotchas to be aware of? Performance issues? Further recommended reading I should look at before ploughing into an implementation of my own?</p> <p><strong>EDIT</strong> Found these additional useful URLs:</p> <ul> <li><a href="http://msdn.microsoft.com/en-us/library/cc668202.aspx" rel="noreferrer">How to: Use Routing with Web Forms (MSDN)</a></li> <li><a href="http://msdn.microsoft.com/en-us/library/cc668201.aspx" rel="noreferrer">ASP.NET Routing (MSDN)</a> </li> <li><a href="http://msdn.microsoft.com/en-us/library/cc668176.aspx" rel="noreferrer">How to: Construct a URL from a Route(MSDN)</a></li> </ul>
<p>A simple example of how to use routing in ASP.NET </p> <ol> <li>Create Empty Web Application</li> <li>Add first form - Default.aspx</li> <li>Add second form - Second.aspx</li> <li>Add third form - Third.aspx</li> <li><p>Add to default.aspx 3 buttons -</p> <pre><code>protected void Button1_Click(object sender, EventArgs e) { Response.Redirect("Second.aspx"); } protected void Button2_Click(object sender, EventArgs e) { Response.Redirect("Third.aspx?Name=Pants"); } protected void Button3_Click(object sender, EventArgs e) { Response.Redirect("Third.aspx?Name=Shoes"); } </code></pre></li> <li><p>Read query string on third page</p> <pre><code>protected void Page_Load(object sender, EventArgs e) { Response.Write(Request.QueryString["Name"]); } </code></pre></li> </ol> <p>Now if you run the program, you will be able to navigate to second and third form. This is how it used to be. Let's add routing.</p> <ol start="7"> <li><p>Add new item - Global.aspx using System.Web.Routing;</p> <pre><code>protected void Application_Start(object sender, EventArgs e) { RegisterRoutes(RouteTable.Routes); } void RegisterRoutes(RouteCollection routes) { routes.MapPageRoute( "HomeRoute", "Home", "~/Default.aspx" ); routes.MapPageRoute( "SecondRoute", "Second", "~/Second.aspx" ); routes.MapPageRoute( "ThirdRoute", "Third/{Name}", "~/Third.aspx" ); } </code></pre></li> <li><p>In default.aspx modify protected void Button1_Click(object sender, EventArgs e) { // Response.Redirect("Second.aspx"); Response.Redirect(GetRouteUrl("SecondRoute", null)); }</p> <pre><code>protected void Button2_Click(object sender, EventArgs e) { //Response.Redirect("Third.aspx?Name=Pants"); Response.Redirect(GetRouteUrl("ThirdRoute", new {Name = "Pants"})); } protected void Button3_Click(object sender, EventArgs e) { // Response.Redirect("Third.aspx?Name=Shoes"); Response.Redirect(GetRouteUrl("ThirdRoute", new { Name = "Shoes" })); } </code></pre></li> <li><p>Modify page load in third.aspx</p> <pre><code>protected void Page_Load(object sender, EventArgs e) { //Response.Write(Request.QueryString["Name"]); Response.Write(RouteData.Values["Name"]); } </code></pre></li> </ol> <p>Run the program, Please note that url looks much cleaner - there are not file extensions in it (Second.aspx becomes just Second)</p> <ol start="10"> <li><p>To pass more then one argument</p> <ul> <li><p>add new button to default.aspx with the following code:</p> <pre><code>protected void Button4_Click(object sender, EventArgs e) { Response.Redirect(GetRouteUrl("FourthRoute", new { Name = "Shoes" , Gender = "Male"})); } </code></pre></li> <li><p>add the following code to global.asax</p> <pre><code> routes.MapPageRoute( "FourthRoute", "Fourth/{Name}-{Gender}", "~/Fourth.aspx" ); </code></pre></li> <li><p>create Fourth.aspx page with the following page load:</p> <pre><code>protected void Page_Load(object sender, EventArgs e) { Response.Write("Name is: " + RouteData.Values["Name"] + " and Gender is " + RouteData.Values["Gender"]); } </code></pre></li> </ul></li> </ol>
<p>Mike Ormond's step-by-step guide to setting up URL routing with ASP.NET is excellent (<a href="http://blogs.msdn.com/mikeormond/archive/2008/11/06/getting-asp-net-routing-up-and-running-the-definitive-guide.aspx" rel="nofollow noreferrer">Getting ASP.NET Routing Up and Running - The Definitive Guide </a>) </p>
21,080
<p>I've got a Lua program that seems to be slower than it ought to be. I suspect the issue is that I'm adding values to an associative array one at a time and the table has to allocate new memory each time. </p> <p>There did seem to be a table.setn function, but it fails under Lua 5.1.3:</p> <pre><code>stdin:1: 'setn' is obsolete stack traceback: [C]: in function 'setn' stdin:1: in main chunk [C]: ? </code></pre> <p>I gather from the Google searching I've done that this function was depreciated in Lua 5.1, but I can't find what (if anything) replaced the functionality.</p> <p>Do you know how to pre-size a table in Lua?</p> <p>Alternatively, is there some other way to avoid memory allocation when you add an object to a table?</p>
<p>Let me focus more on your question:</p> <blockquote> <p>adding values to an associative array one at a time</p> </blockquote> <p>Tables in Lua are associative, but using them in an array form (1..N) is optimized. They have double faces, internally.</p> <p>So.. If you indeed are adding values associatively, follow the rules above.</p> <p>If you are using indices 1..N, you can force a one-time size readjust by setting t[100000]= something. This should work until the limit of optimized array size, specified within Lua sources (2^26 = 67108864). After that, everything is associative.</p> <p>p.s. The old 'setn' method handled the array part only, so it's no use for associative usage (ignore those answers).</p> <p>p.p.s. Have you studied general tips for keeping Lua performance high? i.e. know table creation and rather reuse a table than create a new one, use of 'local print=print' and such to avoid global accesses.</p>
<p>There is still an internal luaL_setn and you can compile Lua so that it is exposed as table.setn. But it looks like that it won't help because the code doesn't seem to do any pre-extending.</p> <p>(Also the setn as commented above the setn is related to the array part of a Lua table, and you said that your are using the table as an associative array)</p> <p>The good part is that even if you add the elements one by one, Lua does not increase the array that way. Instead it uses a more reasonable strategy. You still get multiple allocations for a larger array but the performance is better than getting a new allocation each time.</p>
15,146
<p>While creating a file synchronization program in C# I tried to make a method <code>copy</code> in <code>LocalFileItem</code> class that uses <code>System.IO.File.Copy(destination.Path, Path, true)</code> method where <code>Path</code> is a <code>string</code>.<br> After executing this code with destination. <code>Path = "C:\\Test2"</code> and <code>this.Path = "C:\\Test\\F1.txt"</code> I get an exception saying that I do not have the required file permissions to do this operation on <strong>C:\Test</strong>, but <strong>C:\Test</strong> is owned by myself <em>(the current user)</em>.<br> Does anybody knows what is going on, or how to get around this?</p> <p>Here is the original code complete.</p> <pre><code>using System; using System.Collections.Generic; using System.Text; using System.IO; namespace Diones.Util.IO { /// &lt;summary&gt; /// An object representation of a file or directory. /// &lt;/summary&gt; public abstract class FileItem : IComparable { protected String path; public String Path { set { this.path = value; } get { return this.path; } } protected bool isDirectory; public bool IsDirectory { set { this.isDirectory = value; } get { return this.isDirectory; } } /// &lt;summary&gt; /// Delete this fileItem. /// &lt;/summary&gt; public abstract void delete(); /// &lt;summary&gt; /// Delete this directory and all of its elements. /// &lt;/summary&gt; protected abstract void deleteRecursive(); /// &lt;summary&gt; /// Copy this fileItem to the destination directory. /// &lt;/summary&gt; public abstract void copy(FileItem fileD); /// &lt;summary&gt; /// Copy this directory and all of its elements /// to the destination directory. /// &lt;/summary&gt; protected abstract void copyRecursive(FileItem fileD); /// &lt;summary&gt; /// Creates a FileItem from a string path. /// &lt;/summary&gt; /// &lt;param name="path"&gt;&lt;/param&gt; public FileItem(String path) { Path = path; if (path.EndsWith("\\") || path.EndsWith("/")) IsDirectory = true; else IsDirectory = false; } /// &lt;summary&gt; /// Creates a FileItem from a FileSource directory. /// &lt;/summary&gt; /// &lt;param name="directory"&gt;&lt;/param&gt; public FileItem(FileSource directory) { Path = directory.Path; } public override String ToString() { return Path; } public abstract int CompareTo(object b); } /// &lt;summary&gt; /// A file or directory on the hard disk /// &lt;/summary&gt; public class LocalFileItem : FileItem { public override void delete() { if (!IsDirectory) File.Delete(this.Path); else deleteRecursive(); } protected override void deleteRecursive() { Directory.Delete(Path, true); } public override void copy(FileItem destination) { if (!IsDirectory) File.Copy(destination.Path, Path, true); else copyRecursive(destination); } protected override void copyRecursive(FileItem destination) { Microsoft.VisualBasic.FileIO.FileSystem.CopyDirectory( Path, destination.Path, true); } /// &lt;summary&gt; /// Create's a LocalFileItem from a string path /// &lt;/summary&gt; /// &lt;param name="path"&gt;&lt;/param&gt; public LocalFileItem(String path) : base(path) { } /// &lt;summary&gt; /// Creates a LocalFileItem from a FileSource path /// &lt;/summary&gt; /// &lt;param name="path"&gt;&lt;/param&gt; public LocalFileItem(FileSource path) : base(path) { } public override int CompareTo(object obj) { if (obj is FileItem) { FileItem fi = (FileItem)obj; if (File.GetCreationTime(this.Path).CompareTo (File.GetCreationTime(fi.Path)) &gt; 0) return 1; else if (File.GetCreationTime(this.Path).CompareTo (File.GetCreationTime(fi.Path)) &lt; 0) return -1; else { if (File.GetLastWriteTime(this.Path).CompareTo (File.GetLastWriteTime(fi.Path)) &lt; 0) return -1; else if (File.GetLastWriteTime(this.Path).CompareTo (File.GetLastWriteTime(fi.Path)) &gt; 0) return 1; else return 0; } } else throw new ArgumentException("obj isn't a FileItem"); } } } </code></pre>
<p>It seems you have misplaced the parameters in File.Copy(), it should be File.Copy(string source, string destination).</p> <p>Also is "C:\Test2" a directory? You can't copy file to a directory. Use something like that instead: <pre> File.Copy( sourceFile, Path.Combine(destinationDir,Path.GetFileName(sourceFile)) )</pre>;</p>
<p>I'm kinda guessing here, but could it be because:</p> <ul> <li>You are trying to perform file operations in C: root? (there may be protection on this by Vista if you are using it - not sure?)</li> <li>You are trying to copy to a non-existant directory?</li> <li>The file already exists and may be locked? (i.e you have not closed another application instance)?</li> </ul> <p>Sorry I cant be of more help, I have rarely experienced problems with File.Copy.</p>
4,399
<p>I'm using the <a href="http://libodbcxx.sourceforge.net/" rel="nofollow noreferrer">freeodbc++</a> library to access data on a MS SQL Server 2000 database (SP3? SP4?). In particular, I'm running a particularly long and nasty stored procedure. I can watch the procedure execute in SQL Profiler, however, it tends to stop processing at a certain point. No error codes or exceptions thrown. If I comment out the nested statement that is always the last statement, it just ends slightly before the comment. I haven't tried radically commenting out the whole darn thing... I'm setting the query timeout to 300 seconds. The callable statement usually returns in under 1 sec, without actually finishing the SP.</p> <p>Any ideas?</p> <p><strong>UPDATE0:</strong> If I run the SP via Query Analyzer or some other tool... it works. It's just via my ODBC connection that it fails.</p> <p><strong>UPDATE1:</strong> As I comment out code, the execution ends further into the SP. Makes me think there is a timeout or buffer limit that I'm running into.</p>
<p>In <a href="http://www.autoitscript.com/autoit3/" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/wOUx6.jpg" alt="" /> autoit</a>, you have a <a href="http://www.autoitscript.com/forum/index.php?showtopic=48585" rel="nofollow noreferrer">script</a> which does just that.</p> <p>It basically comes from this <a href="http://support.microsoft.com/?scid=kb%3Ben-us%3B165721&amp;x=18&amp;y=13" rel="nofollow noreferrer">Microsoft article</a> and uses kernel32.dll DeviceIoControl function</p> <p>Of course, this question appears to be a duplicate of <a href="https://stackoverflow.com/questions/85649/safe-remove-usb-drive-using-win32-api">Safe remove USB-Drive using Win32 API?</a>, which gives other solutions</p>
<p>You could spawn a process and use a <a href="http://quick.mixnmojo.com/readmes/USBDiskEjector.html" rel="nofollow noreferrer">command line tool</a>. This would also work from other languages such as java where calling the Win32 api is harder.</p>
25,270
<p>For development, I use a local LAMP stack, for production I'm using <a href="http://mediatemple.net/webhosting/gs/django.html" rel="noreferrer">MediaTemple's Django Container</a> (which I'm loving BTW). MT's container uses lighthttpd. Honestly I've never had any other experience with it. I've always used Apache. I've been doing some reading:</p> <ul> <li><a href="http://www.onlamp.com/pub/a/onlamp/2007/04/05/the-lighttpd-web-server.html" rel="noreferrer">Onlamp</a></li> <li><a href="http://weblog.textdrive.com/article/25/should-i-consider-lighttpd" rel="noreferrer">TextDrive</a></li> <li><a href="http://www.linux.com/feature/51673" rel="noreferrer">Linux.com</a></li> </ul> <p>Here's are questions:</p> <ul> <li>What strengths does one have over the other?</li> <li>Would it <em>benefit</em> me to use lighthttpd on my dev setup?</li> <li>What's up with using both? The Linux.com article talks about using lighttpd <em>with</em> Apache.</li> </ul>
<p>The way you interface between the web server and Django might have even a greater impact on performance than the choice of web server software. For instance, mod_python is known to be heavy on RAM.</p> <p><a href="https://stackoverflow.com/questions/26025/cleanest-fastest-server-setup-for-django">This question</a> and its answers discuss other web server options as well.</p> <p>I wouldn't be concerned on compatibility issues with client software (see <a href="https://stackoverflow.com/questions/172164/apache-or-lighttpd#173225">MarkR's comment</a>). I've had no such problems when serving Django using lighttpd and FastCGI. I'd like to see a diverse ecosystem of both server and client software. Having a good standard is better than a <em>de facto</em> product from a single vendor.</p>
<p>Use a standard web server. Apache is used by 50% of web sites (<a href="http://news.netcraft.com/archives/2008/09/30/september_2008_web_server_survey.html" rel="nofollow noreferrer">Netcraft</a>), therefore, if you use Apache, peoples' web browsers, spiders, proxies etc, are pretty much guaranteed to work with your site (its web server anyway).</p> <p>Lighthttpd is used by 1.5% of web sites (<a href="http://news.netcraft.com/archives/2008/09/30/september_2008_web_server_survey.html" rel="nofollow noreferrer">Netcraft</a>), so it's far less likely that people will test their apps with it.</p> <p>Any performance difference is likely not to matter in production; an Apache server can probably serve static requests at a much higher bandwidth than you have, on the slowest hardware you're likely to deploy in production.</p>
20,749