input
stringlengths
51
42.3k
output
stringlengths
18
55k
Can you create collapsible #Region like scopes in C++ within VS 2008? <p>I miss it so much (used it a lot in C#). can you do it in C++?</p>
<p>Yes, you can. See <a href="http://msdn.microsoft.com/en-us/library/b6xkz944(VS.80).aspx">here</a>.</p> <pre><code>#pragma region Region_Name //Your content. #pragma endregion Region_Name </code></pre>
How to get WCF statistics from inside an application that uses it? <p>Is it possible to gather performance statistics programmatically from inside a WCF application? For example, the number of connections open or requests received.</p>
<p>Look into <a href="http://msdn.microsoft.com/en-us/library/ms735098.aspx" rel="nofollow">WCF Performance Counters</a>. You can query performance counters using the respective <a href="http://msdn.microsoft.com/en-us/library/system.diagnostics.performancecounter.aspx" rel="nofollow">.NET Framework Classes</a>.</p> <p>Also, you could enable WMI for your WCF Services and query this information from inside your application.</p> <p>Probably depends on the kind of information you need to get.</p>
How can I plot data with a non-numeric X-axis? <p>I have a series of performance tests I would like to show as a graph. I have a set of tests (about 10) which I run on a set of components (currently 3), and get throughput results.</p> <p>The Y-axis would be the throughput result from the test, and the X-axis should have an abbreviated name of the test, with the results from the various components I'm testing. So, for each X label (eg. retrieve20Items, store20Items) there would be 3 different results above it, one for each of the three components I'm testing, each colour-coded and referenced in the legend.</p> <p>Is this non-numeric x-axis something that I can do with gnuplot? This is being done on a linux platform, so Windows-only tools won't work for me.</p>
<p>See <a href="http://lowrank.net/gnuplot/tics-e.html" rel="nofollow">this very helpful page</a>. Essentially you create a number-label mapping using</p> <pre><code>set xtics ("lbl1" 1, "lbl2" 2, "lbl3" 3, "lbl4" 4) </code></pre> <p>Then plot as normal.</p>
How do I peek at the first two bytes in an InputStream? <p>Should be pretty simple: I have an InputStream where I want to peek at (not read) the first two bytes, i.e. I want the "current position" of the InputStream to stil be at 0 after my peeking. What is the best and safest way to do this?</p> <p><strong>Answer</strong> - As I had suspected, the solution was to wrap it in a BufferedInputStream which offers markability. Thanks Rasmus.</p>
<p>For a general InputStream, I would wrap it in a BufferedInputStream and do something like this:</p> <pre><code>BufferedInputStream bis = new BufferedInputStream(inputStream); bis.mark(2); int byte1 = bis.read(); int byte2 = bis.read(); bis.reset(); // note: you must continue using the BufferedInputStream instead of the inputStream </code></pre>
SQL2005 Express slow from remote VB6 application <p>I have a legacy VB6 application that was built using MSDE.</p> <p>As many client's database grow towards the MSDE 2 GB limit they are upgraded to SQL 2005 Express.</p> <p>This has proven very successful until today.</p> <p>I have spent the entire day troubleshooting a client's network on which our application runs unacceptably slowly, when connecting the a SQL 2005 Express named instance across the "network". </p> <p>I say "network" because it is only two XP SP2 machines - there is no dedicated server here. No AD.</p> <p>In trying to isolate this problem I have installed SQL 2005 Express on both machines and placed copies of our database on both machines. I have even completely reinstalled our application using the SQL2005 Express install routine we now have. It makes no difference whether I restore an old MSDE database or use a newly created SQL 2005 Express one.</p> <p>When running our application and connecting to either machine's local server performance is fine. Once you connect our application on either PC to the server on the other PC, it is unworkably slow. (Regardless of the combination).</p> <p>Now, I have rebuilt statistics (exec sp_updatestats), rebuilt ALL indexes, disabled (temporarily) firewalls and virus software and clutched and countless other straws.</p> <p>I have resorted to running FileMon and ProcessMon on both machines and have even written a little test application to simply connect and query a table in the database. It too runs slowly - (takes about 5 - 6 seconds to connect).</p> <p>The monitors (File and Process) show delays when SQL Server is writing to a log file (c:\program files\microsoft sql server\mssql.1\log files\log_12.trc).</p> <p>Other tools though, like SQL Management Studio Express and even SSEUtil (a SQL Server Express Diagnostic Utility I found) run perfectly when connecting from the client to the server. Queries (even large ones) run as you would expect.</p> <p>I feel sure this problem is environmental as we have so many sites running what would appear to be the same setup, with no such problems.</p> <p>Can someone tell me what I should be doing to isolate this problem or even offer any clues or suggestions that could help solve this?</p>
<p>This might be due to a cached query plan which is not representative of the data, even thought you have rebuilt indexes and refreshed statistics. The symptom you describe (namely that a query runs fine from SSMS but not from an application) is often caused by a wrongly cached query plan. SSMS emits a "WITH RECOMPILE" under the covers. If you are calling a stored procedure, temporarily add 'WITH RECOMPILE' to its definition and check the results.</p>
how to register url handler for apache commons httpclient <p>I want to be able to access custom URLs with apache httpclient. Something like this:</p> <pre><code>HttpClient client = new HttpClient(); HttpMethod method = new GetMethod("media:///squishy.jpg"); int statusCode = client.executeMethod(method); </code></pre> <p>Can I somehow register a custom URL handler? Or should I just register one with Java, using</p> <pre><code>URL.setURLStreamHandlerFactory(...) </code></pre> <p>Regards.</p>
<p>We do it like this:</p> <pre><code> org.apache.commons.httpclient.protocol.Protocol.registerProtocol("ss-https", new Protocol("ss-https", (ProtocolSocketFactory)new EasySSLProtocolSocketFactory(), 443)); </code></pre>
Entlib versus ACA.Net - Does ACA.Net provide any advantage? <p>My understanding is that Entlib has picked-up and included concepts from ACA.Net. Is there any point to using ACA.Net on a new .net project?</p>
<p>We are actively using ACA.NET 4.1 where I work. ACA.NET actually uses EntLib at its core, and over the years Avanade have "retired" parts of their framework as EntLib functionality catches up.</p> <p>One thing which EntLib doesn't do, which ACA.NET does well is its use of Aspects over a machine boundary. I know EntLib has policy injection, but this works by manipulating the instantiation of a local object (i.e. the service). If you want to protect your remote service with an Authorization Aspect, then an ACA.NET Aspect declared as a ReceiversOnly container will ensure the service is protected where the service runs. If you are across physical layers on any of these service calls, ACA.NET will do the job, EntLib doesn't cut it just yet.</p> <p>If your application doesn't need to be deployed to multiple physical tiers, then this advantage of ACA.NET disappears and you can fall back to use EntLib only.</p>
NoClassDefFoundError with a long classname on Tomcat with java 1.4.2_07-b05 <p>I have a java class:</p> <blockquote> <p>it.eng.ancona.view.RuoliView$TabElaborazioneFattureValidazione$ElencoDettaglioElaborazioneFattureValidazione$RigaElencoDettaglioElaborazioneFattureValidazione</p> </blockquote> <p>It's so long for multiple inner class.</p> <p>If I use 1.4.2_07-b05 on Eclipse and I call this class, all goes fine.</p> <p>If I use 1.4.2_07-b05 on Tomcat 5.0 it throws <code>NoClassDefFoundError</code>.</p> <p>I try to cut the class name, and after this all works fine.</p> <p>I've searched the internet and I've found that the max length for a class name is 65000, so the length should be ok. And on eclipse all works.</p> <p>The OS is Vista.</p> <p>Someone know if it's a bug or anything else?</p>
<p>This could be caused by the maximum path length of Windows. Try moving your Tomcat server to something like C:\TC to see if you still have a problem. Also check if the jar that this class should be in, actually does have it.</p>
Creating my own Iterators <p>I'm trying to learn C++ so forgive me if this question demonstrates a lack of basic knowledge, you see, the fact is, I have a lack of basic knowledge.</p> <p>I want some help working out how to create an iterator for a class I have created.</p> <p>I have a class 'Shape' which has a container of Points. I have a class 'Piece' which references a Shape and defines a position for the Shape. Piece does not have a Shape it just references a Shape.</p> <p>I want it to seem like Piece is a container of Points which are the same as those of the Shape it references but with the offset of the Piece's position added.</p> <p>I want to be able to iterate through the Piece's Points just as if Piece was a container itself. I've done a little reading around and haven't found anything which has helped me. I would be very grateful for any pointers.</p>
<p>/EDIT: I see, an own iterator is actually necessary here (I misread the question first). Still, I'm letting the code below stand because it can be useful in similar circumstances.</p> <p><hr /></p> <p>Is an own iterator actually necessary here? Perhaps it's sufficient to forward all required definitions to the container holding the actual Points:</p> <pre><code>// Your class `Piece` class Piece { private: Shape m_shape; public: typedef std::vector&lt;Point&gt;::iterator iterator; typedef std::vector&lt;Point&gt;::const_iterator const_iterator; iterator begin() { return m_shape.container.begin(); } const_iterator begin() const { return m_shape.container.begin(); } iterator end() { return m_shape.container.end(); } const_iterator end() const { return m_shape.const_container.end(); } } </code></pre> <p>This is assuming you're using a <code>vector</code> internally but the type can easily be adapted.</p>
Using pre-compiled headers with CMake <p>I have seen a few (old) posts on the 'net about hacking together some support for pre-compiled headers in CMake. They all seem a bit all-over the place and everyone has their own way of doing it. What is the best way of doing it currently?</p>
<p>There is a <a href="https://github.com/sakra/cotire">third party CMake module</a> which automates the use of precompiled headers for CMake based build systems and also supports unity builds.</p>
Why is the fact that Microsoft decided to support jQuery such a big deal? <p>I don't see what all this fuss is about Microsoft's decision to support JQuery within ASP.NET MVC.</p> <p>There were signs that open-minded people are starting to have some say in the matters of marketing for a while now. And even the way MS does business has started to change. But at it's core it's still acting in response to customers' requests.</p> <p>I for one don't know what to make of it, except that it brings back to Microsoft's sphere of influence a very visible product.</p>
<p>Its the first time MS is shipping an open source component <em>they didn't write</em> with one of their products. This doesn't seem like a big deal, but its almost nuclear in its implications.</p> <p>Think about it... They are saying "we support this." In an OSS product, MS has no control over the code. So, they are putting their livelihood (in some small way) into the hands of people who don't work for MS.</p> <p>I think jQuery's popularity, the fact that it's not mission critical code, and that the codebase is so small all came together to make for favorable circumstances for MS to dip their toe in the water.</p>
What is the impact of having namespaces in multiple DLLs? <p>I've inherited a VB.net project that generates 2 DLLS: one for the web app, and another for the "business layer". This is for a sub-app of a larger web site. (Using VS2005).</p> <p>The problem is that that something doesn't smell right with the DLL &amp; namespace structure, and I'd like to know if there are any performance impacts.</p> <p>The main web app is "Foo", and generates Foo.dll. Foo.dll contains namespace App.Foo, which contains the classes for all the pages, user controls, etc.</p> <p>There's also a project "FooLib" that generates FooLib.dll. FooLib.dll also contains an App.Foo namespace, which contains a bunch of class definitions. There are a few other namespaces like App.Foo.Data, App.Foo.Logic, etc.</p> <p>Is there anything wrong with this? How does the runtime find a class across multiple DLLs?</p>
<p>There's nothing wrong with this, the only possible issues may be that 1) developers seeing "App.Foo.Something" may not know which assembly to look in 2) if the same name is used in both, apps compiling against (in c# at least) will get errors about ambiguous type names.</p> <p>As for the runtime, types are specified by assembly and name - the namespace is just part of the typename. So the runtime will have no issue finding the type - when you compile the information about what assembly to find it in is compiled in.</p>
Is there a way to define which fields in the model are editable in the admin app? <p>Assume the following:</p> <p><em>models.py</em></p> <pre><code>class Entry(models.Model): title = models.CharField(max_length=50) slug = models.CharField(max_length=50, unique=True) body = models.CharField(max_length=200) </code></pre> <p><em>admin.py</em></p> <pre><code>class EntryAdmin(admin.ModelAdmin): prepopulated_fields = {'slug':('title',)} </code></pre> <p>I want the slug to be pre-populated by the title, but I dont want the user to be able to edit it from the admin. I assumed that adding the fields=[] to the admin object and not including the slug would have worked, but it didnt. I also tried setting editable=False in the model, but that also didnt work (infact, stops the page from rendering).</p> <p>Thoughts? </p>
<p>For this particular case you can override your save method to slugify (it's built-in method, look at django source) the title and store it in slug field. Also from there you can easily check if this slug is indeed unique and change it somehow if it's not.</p> <p>Consider this example:</p> <pre><code>def save(self): from django.template.defaultfilters import slugify if not self.slug: self.slug = slugify(self.title) super(Your_Model_Name,self).save() </code></pre>
What are your favorite Ruby on Rails books and why? <p>I'm looking to pick up a few books on RoR to help teach myself how to build a scalable RoR app. I have read the RailsSpace book, and am starting the Rails Way book tonight. </p> <p>Some topics of interest are:</p> <ul> <li>REST - considering using Amazon's SimpleDB</li> <li>Using RSpec effectively</li> <li>memcached - server architecture and code implementation</li> <li>mongrel - server architecture</li> <li>MySQL</li> </ul>
<p><a href="http://www.pragmaticprogrammer.com/news/second-edition-agile-web-development-with-rails-now-shipping" rel="nofollow">Agile Web Development With Rails</a> is always a good starting point for Rails newcomers.</p> <p>I really liked this book because of it's example driven approach to teaching you the framework. They walk through building an application step by step which I think really helps you get your head around the gist of the Rails framework.</p>
Request.UrlReferrer null? <p>In an aspx C#.NET page (I am running framework v3.5), I need to know where the user came from since they cannot view pages without logging in. If I have page <code>A</code> (the page the user wants to view) redirect to page <code>B</code> (the login page), the Request.UrlReferrer object is null. </p> <p>Background: If a user isn't logged in, I redirect to the Login page (<code>B</code> in this scenario). After login, I would like to return them to the page they were requesting before they were forced to log in.</p> <p><strong>UPDATE:</strong> <br />A nice quick solution seems to be: <br /><code>//if user not logged in Response.Redirect("..MyLoginPage.aspx?returnUrl=" + Request.ServerVariables["SCRIPT_NAME"]);</code> <br />Then, just look at QueryString on login page you forced them to and put the user where they were after successful login.</p>
<p>UrlReferrer is based off the <a href="http://en.wikipedia.org/wiki/Referer" rel="nofollow">HTTP_REFERER</a> header that a browser <em>should</em> send. But, as with all things left up to the client, it's variable.</p> <p>I know some "security" suites (like Norton's Internet Security) will strip that header, in the belief that it aids tracking user behavior. Also, I'm sure there's some Firefox extensions to do the same thing.</p> <p>Bottom line is that you shouldn't trust it. Just append the url to the GET string and redirect based off that.</p> <p>UPDATE: As mentioned in the comments, it is probably a good idea to restrict the redirect from the GET parameter to only work for domain-less relative links, refuse directory patterns (../), etc. So still sanity check the redirect; if you follow the standard "don't use any user-supplied input blindly" rule you should be safe.</p>
Can we create an application with its own Web.config and Forms Authentication section inside another application using Forms Authentication? <p>I have an application that uses Forms Authentication to authenticate one type of user. There is a section in this application that needs to be authenticated for another type of user using a different table in the database. The problem happens if the second type of user's session times out, she is taken to the login page defined in the Forms Authentication section of the main Web.Config instead of the login page for the second type of user. I am looking for solutions to this problem. One idea is to create an application in IIS for the section and create a Web.Config for the folder and add another Forms Authentication section. In my experiments, it seems this doesn't work. Am I missing something obvious? Any insights? </p>
<p>IIRC, the authentication works per folder. So you should be able to do it if all of the pages that require the 2nd type of authentication live in a specific sub-folder with it's own config.</p> <p>Not 100% sure on this, though, so if someone more knowledgeable can contradict me I'll just delete the response.</p>
AVI Animations for GUI <p>I need to get some AVI animations for use with the Borland VCL TAnimate component, to display during operations such as 'online update', 'burning cd' and a few others.</p> <p>I have only come across the <a href="http://www.glyfx.com/shop/detail/animationpack/" rel="nofollow">glyFX Animation Pack</a> so far.</p> <p>Can anybody recomend other places to get nice avi animations?</p>
<p>You could consider using GIF animations instead of AVIs. There are a lots of them on the Web. There are also some free Delphi components working with animated GIFs, look <a href="http://melander.dk/delphi/gifimage/" rel="nofollow">TGIFImage for Delphi</a> for example.</p>
Prevent Text Wrap in DataGrid <p>I have a problem with a data-bound DataGrid control, in that despite each column having its Wrap property set to false, the text still wraps. It seems to only do this on IE, and not FF.</p>
<p>It appears that Microsoft is aware of this issue and they have <a href="http://connect.microsoft.com/VisualStudio/feedback/ViewFeedback.aspx?FeedbackID=104081" rel="nofollow">provided a workaround</a>...</p> <p>I don't know if this was addressed in IE8 B2... you might try it and see. Good luck!</p>
Dynamic Sorting within SQL Stored Procedures <p>This is an issue that I've spent hours researching in the past. It seems to me to be something that should have been addressed by modern <a href="http://en.wikipedia.org/wiki/Relational%5Fdatabase%5Fmanagement%5Fsystem">RDBMS</a> solutions but as yet I have not found anything that really addresses what I see to be an incredibly common need in any Web or Windows application with a database back-end.</p> <p>I speak of dynamic sorting. In my fantasy world, it should be as simple as something like:</p> <pre><code>ORDER BY @sortCol1, @sortCol2 </code></pre> <p>This is the canonical example given by newbie SQL and <a href="http://en.wikipedia.org/wiki/Stored%5Fprocedure">Stored Procedure</a> developers all over forums across the Internet. "Why isn't this possible?" they ask. Invariably, somebody eventually comes along to lecture them about the compiled nature of stored procedures, of execution plans in general, and all sorts of other reasons why it isn't possible to put a parameter directly into an <code>ORDER BY</code> clause.</p> <hr> <p>I know what some of you are already thinking: "Let the client do the sorting, then." Naturally, this offloads the work from your database. In our case though, our database servers aren't even breaking a sweat 99% of the time and they aren't even multi-core yet or any of the other myriad improvements to system architecture that happen every 6 months. For this reason alone, having our databases handle sorting wouldn't be a problem. Additionally, databases are <em>very</em> good at sorting. They are optimized for it and have had years to get it right, the language for doing it is incredibly flexible, intuitive, and simple and above all any beginner SQL writer knows how to do it and even more importantly they know how to edit it, make changes, do maintenance, etc. When your databases are far from being taxed and you just want to simplify (and shorten!) development time this seems like an obvious choice.</p> <p>Then there's the web issue. I've played around with JavaScript that will do client-side sorting of HTML tables, but they inevitably aren't flexible enough for my needs and, again, since my databases aren't overly taxed and can do sorting really <em>really</em> easily, I have a hard time justifying the time it would take to re-write or roll-my-own JavaScript sorter. The same generally goes for server-side sorting, though it is already probably much preferred over JavaScript. I'm not one that particularly likes the overhead of DataSets, so sue me.</p> <p>But this brings back the point that it isn't possible &mdash; or rather, not easily. I've done, with prior systems, an incredibly hack way of getting dynamic sorting. It wasn't pretty, nor intuitive, simple, or flexible and a beginner SQL writer would be lost within seconds. Already this is looking to be not so much a "solution" but a "complication."</p> <hr> <p>The following examples are not meant to expose any sort of best practices or good coding style or anything, nor are they indicative of my abilities as a T-SQL programmer. They are what they are and I fully admit they are confusing, bad form, and just plain hack.</p> <p>We pass an integer value as a parameter to a stored procedure (let's call the parameter just "sort") and from that we determine a bunch of other variables. For example... let's say sort is 1 (or the default):</p> <pre><code>DECLARE @sortCol1 AS varchar(20) DECLARE @sortCol2 AS varchar(20) DECLARE @dir1 AS varchar(20) DECLARE @dir2 AS varchar(20) DECLARE @col1 AS varchar(20) DECLARE @col2 AS varchar(20) SET @col1 = 'storagedatetime'; SET @col2 = 'vehicleid'; IF @sort = 1 -- Default sort. BEGIN SET @sortCol1 = @col1; SET @dir1 = 'asc'; SET @sortCol2 = @col2; SET @dir2 = 'asc'; END ELSE IF @sort = 2 -- Reversed order default sort. BEGIN SET @sortCol1 = @col1; SET @dir1 = 'desc'; SET @sortCol2 = @col2; SET @dir2 = 'desc'; END </code></pre> <p>You can already see how if I declared more @colX variables to define other columns I could really get creative with the columns to sort on based on the value of "sort"... to use it, it usually ends up looking like the following incredibly messy clause:</p> <pre><code>ORDER BY CASE @dir1 WHEN 'desc' THEN CASE @sortCol1 WHEN @col1 THEN [storagedatetime] WHEN @col2 THEN [vehicleid] END END DESC, CASE @dir1 WHEN 'asc' THEN CASE @sortCol1 WHEN @col1 THEN [storagedatetime] WHEN @col2 THEN [vehicleid] END END, CASE @dir2 WHEN 'desc' THEN CASE @sortCol2 WHEN @col1 THEN [storagedatetime] WHEN @col2 THEN [vehicleid] END END DESC, CASE @dir2 WHEN 'asc' THEN CASE @sortCol2 WHEN @col1 THEN [storagedatetime] WHEN @col2 THEN [vehicleid] END END </code></pre> <p>Obviously this is a very stripped down example. The real stuff, since we usually have four or five columns to support sorting on, each with possible secondary or even a third column to sort on in addition to that (for example date descending then sorted secondarily by name ascending) and each supporting bi-directional sorting which effectively doubles the number of cases. Yeah... it gets hairy really quick.</p> <p>The idea is that one could "easily" change the sort cases such that vehicleid gets sorted before the storagedatetime... but the pseudo-flexibility, at least in this simple example, really ends there. Essentially, each case that fails a test (because our sort method doesn't apply to it this time around) renders a NULL value. And thus you end up with a clause that functions like the following:</p> <pre><code>ORDER BY NULL DESC, NULL, [storagedatetime] DESC, blah blah </code></pre> <p>You get the idea. It works because SQL Server effectively ignores null values in order by clauses. This is incredibly hard to maintain, as anyone with any basic working knowledge of SQL can probably see. If I've lost any of you, don't feel bad. It took us a long time to get it working and we still get confused trying to edit it or create new ones like it. Thankfully it doesn't need changing often, otherwise it would quickly become "not worth the trouble."</p> <p>Yet it <em>did</em> work.</p> <hr> <p>My question is then: <strong>is there a better way?</strong></p> <p>I'm okay with solutions other than Stored Procedure ones, as I realize it may just not be the way to go. Preferably, I'd like to know if anyone can do it better within the Stored Procedure, but if not, how do you all handle letting the user dynamically sort tables of data (bi-directionally, too) with ASP.NET?</p> <p>And thank you for reading (or at least skimming) such a long question!</p> <p>PS: Be glad I didn't show my example of a stored procedure that supports dynamic sorting, dynamic filtering/text-searching of columns, pagination via ROWNUMBER() OVER, <em>AND</em> try...catch with transaction rollbacking on errors... "behemoth-sized" doesn't even begin to describe them.</p> <hr> <p><strong>Update:</strong></p> <ul> <li>I would like to <strong>avoid dynamic SQL</strong>. Parsing a string together and running an EXEC on it defeats a lot of the purpose of having a stored procedure in the first place. Sometimes I wonder though if the cons of doing such a thing wouldn't be worth it, at least in these special dynamic sorting cases. Still, I always feel dirty whenever I do dynamic SQL strings like that &mdash; like I'm still living in the Classic ASP world.</li> <li>A lot of the reason we want stored procedures in the first place is for <strong>security</strong>. I don't get to make the call on security concerns, only suggest solutions. With SQL Server 2005 we can set permissions (on a per-user basis if need be) at the schema level on individual stored procedures and then deny any queries against the tables directly. Critiquing the pros and cons of this approach is perhaps for another question, but again it's not my decision. I'm just the lead code monkey. :)</li> </ul>
<p>Yeah, it's a pain, and the way you're doing it looks similar to what I do:</p> <pre><code>order by case when @SortExpr = 'CustomerName' and @SortDir = 'ASC' then CustomerName end asc, case when @SortExpr = 'CustomerName' and @SortDir = 'DESC' then CustomerName end desc, ... </code></pre> <p>This, to me, is still much better than building dynamic SQL from code, which turns into a scalability and maintenance nightmare for DBAs.</p> <p>What I do from code is refactor the paging and sorting so I at least don't have a lot of repetition there with populating values for @SortExpr and @SortDir.</p> <p>As far as the SQL is concerned, keep the design and formatting the same between different stored procedures, so it's at least neat and recognizable when you go in to make changes.</p>
Customizing Visual Studio's Intellisense <p>A recent project had me working with C# again, and I noticed something I hadn't before -- C#'s Intellisense shows possible exceptions that can be thrown when calling a method</p> <p><img src="http://i38.tinypic.com/2vl4ldg.png"></p> <p>Since I work mostly with VB.NET applications, it'd be really nice to have this feature in those applications as well, but it's unfortunately absent from VB's Intellisense</p> <p><img src="http://i33.tinypic.com/2v1lxf9.png"></p> <p>Is there any quick and easy way I can customize Visual Studio's Intellisense to show exceptions (as well as other members from the XML comments)? Or am I looking at a full modification using the SDK?</p> <p>Update: 29-Sep-2008 1:49 PM -- I figure this will be more complicated than simply changing a configuration setting. Since the comments are XML-based, I was hoping for an XSLT file somewhere buried in the Visual Studio directory, but nothing has turned up so far. Looks like I'm going to have to dig into the Visual Studio SDK.</p>
<p>Try going to Tool -> Options...<br /> Then Text Editor -> Basic<br /> and make sure both options "Auto list members" and "hide advanced members" are unchecked.<br /> Also check "Parameter information".</p> <p>I cannot validate this information because my current Visual Studio installation is C# standalone.</p> <p>Regards, Luís</p>
What does the comma operator do? <p>What does the following code do in C/C++?</p> <pre><code>if (blah(), 5) { //do something } </code></pre>
<p>Comma operator is applied and the value 5 is used to determine the conditional's true/false.</p> <p>It will execute blah() and get something back (presumably), then the comma operator is employed and 5 will be the only thing that is used to determine the true/false value for the expression.</p> <p><hr /></p> <p>Note that the , operator could be overloaded for the return type of the blah() function (which wasn't specified), making the result non-obvious.</p>
"Submit" button works in Firefox 3 but not in IE7 (ASP 1.1) <p>I have code from an old website that I needed to modify. There are two pages that I modified some form code in. I modified the max length of a textbox and I modified slightly a line or two of code in a function. The "btnSubmit_Click" function as it happens.</p> <p>With the new code FTPed up on the webserver, when I click on the "Submit" button using Firefox 3, the button does what it is supposed to do. With IE7, nothing happens. No page load, no refresh, no error, no nothing. IE isn't busy, it doesn't time out, it does nada.</p> <p>On my development laptop however, when I run the project, the submit button works in IE7 as it is supposed to do. </p> <p>Any thoughts?</p> <p><strong>Response to Mecki:</strong> It is method=POST, but it is a JavaScript postback thing alright. Also I checked the outputted HTML and the Submit button has a JS "onclick" event:<br /> onclick="if (typeof(Page_ClientValidate) == 'function') Page_ClientValidate(); "</p> <p>Absolutely though all the required fields have what they need. The validation also works as when I test it by leaving out info from a required field IE7 asks me to fill in the data. Strange one.</p>
<p>The question was not complete, I left out a detail which in hindsight is very important: I also was moving the site from one host to another. </p> <p>The issue seems to have been differing versions of the Validating JavaScript code. I fixed the issue by copying the <strong>aspnet_client\systemweb\1_1_4322\*.*</strong> directory from the root of IIS to the root of the website. The website I had transferred, already had code in this directory and it must have been a different Build version or something from the ASP running on the new server.</p> <p>Apologies Mecki, if I was any good with JavaScript your answer would have lead me in the right direction, I'd say. Simon, it was while investigating your idea that I noticed the javascript includes for <strong>aspnet_client</strong>. End of the day the issue was fixed with trial and error on my part so I don't absolutely know what caused my problem. Thanks for helping.</p>
Continuations in Ruby <p>Has anyone ever done work to get Ruby to do continuations (like Seaside on Smalltalk)?</p>
<p>Yes, in most cases. MRI (1.8) have supported them as far as my memory reaches, Ruby 1.9 (YARV) <a href="http://svn.ruby-lang.org/cgi-bin/viewvc.cgi?view=rev&amp;revision=12380">does it, too</a>, so does Rubinius. JRuby and IronRuby don't have continuations, and it's quite unlikely they will get them (JVM and CLR use stack-instrospection for security)</p> <p>Ruby as a language supports continuations via <code>callcc</code> keyword. They're used, for example, to implement <code>Generator</code> class from standard library. </p> <p><b><a href="http://www.ruby-doc.org/docs/ProgrammingRuby/html/ref_c_continuation.html">continuations on ruby-doc</a></b></p> <p>Continuation-based web frameworks (like seaside, or one from Arc's std. library) seem less popular. I've found <a href="http://rubyforge.org/projects/wee/">wee</a> that claim to let you do optional continuations, but I've never used it.</p>
Php code formatter / beautifier and php beautification in general <p>Do you know any good tools for nicely formatting messy php code? Preferably a script for Aptana/Eclipse, but a standalone tool will do too.</p>
<p>Well here is my very basic and rough script:</p> <pre><code>#!/usr/bin/php &lt;?php class Token { public $type; public $contents; public function __construct($rawToken) { if (is_array($rawToken)) { $this-&gt;type = $rawToken[0]; $this-&gt;contents = $rawToken[1]; } else { $this-&gt;type = -1; $this-&gt;contents = $rawToken; } } } $file = $argv[1]; $code = file_get_contents($file); $rawTokens = token_get_all($code); $tokens = array(); foreach ($rawTokens as $rawToken) { $tokens[] = new Token($rawToken); } function skipWhitespace(&amp;$tokens, &amp;$i) { global $lineNo; $i++; $token = $tokens[$i]; while ($token-&gt;type == T_WHITESPACE) { $lineNo += substr($token-&gt;contents, "\n"); $i++; $token = $tokens[$i]; } } function nextToken(&amp;$j) { global $tokens, $i; $j = $i; do { $j++; $token = $tokens[$j]; } while ($token-&gt;type == T_WHITESPACE); return $token; } $OPERATORS = array('=', '.', '+', '-', '*', '/', '%', '||', '&amp;&amp;', '+=', '-=', '*=', '/=', '.=', '%=', '==', '!=', '&lt;=', '&gt;=', '&lt;', '&gt;', '===', '!=='); $IMPORT_STATEMENTS = array(T_REQUIRE, T_REQUIRE_ONCE, T_INCLUDE, T_INCLUDE_ONCE); $CONTROL_STRUCTURES = array(T_IF, T_ELSEIF, T_FOREACH, T_FOR, T_WHILE, T_SWITCH, T_ELSE); $WHITESPACE_BEFORE = array('?', '{', '=&gt;'); $WHITESPACE_AFTER = array(',', '?', '=&gt;'); foreach ($OPERATORS as $op) { $WHITESPACE_BEFORE[] = $op; $WHITESPACE_AFTER[] = $op; } $matchingTernary = false; // First pass - filter out unwanted tokens $filteredTokens = array(); for ($i = 0, $n = count($tokens); $i &lt; $n; $i++) { $token = $tokens[$i]; if ($token-&gt;contents == '?') { $matchingTernary = true; } if (in_array($token-&gt;type, $IMPORT_STATEMENTS) &amp;&amp; nextToken($j)-&gt;contents == '(') { $filteredTokens[] = $token; if ($tokens[$i + 1]-&gt;type != T_WHITESPACE) { $filteredTokens[] = new Token(array(T_WHITESPACE, ' ')); } $i = $j; do { $i++; $token = $tokens[$i]; if ($token-&gt;contents != ')') { $filteredTokens[] = $token; } } while ($token-&gt;contents != ')'); } elseif ($token-&gt;type == T_ELSE &amp;&amp; nextToken($j)-&gt;type == T_IF) { $i = $j; $filteredTokens[] = new Token(array(T_ELSEIF, 'elseif')); } elseif ($token-&gt;contents == ':') { if ($matchingTernary) { $matchingTernary = false; } elseif ($tokens[$i - 1]-&gt;type == T_WHITESPACE) { array_pop($filteredTokens); // Remove whitespace before } $filteredTokens[] = $token; } else { $filteredTokens[] = $token; } } $tokens = $filteredTokens; function isAssocArrayVariable($offset = 0) { global $tokens, $i; $j = $i + $offset; return $tokens[$j]-&gt;type == T_VARIABLE &amp;&amp; $tokens[$j + 1]-&gt;contents == '[' &amp;&amp; $tokens[$j + 2]-&gt;type == T_STRING &amp;&amp; preg_match('/[a-z_]+/', $tokens[$j + 2]-&gt;contents) &amp;&amp; $tokens[$j + 3]-&gt;contents == ']'; } // Second pass - add whitespace $matchingTernary = false; $doubleQuote = false; for ($i = 0, $n = count($tokens); $i &lt; $n; $i++) { $token = $tokens[$i]; if ($token-&gt;contents == '?') { $matchingTernary = true; } if ($token-&gt;contents == '"' &amp;&amp; isAssocArrayVariable(1) &amp;&amp; $tokens[$i + 5]-&gt;contents == '"') { /* * Handle case where the only thing quoted is the assoc array variable. * Eg. "$value[key]" */ $quote = $tokens[$i++]-&gt;contents; $var = $tokens[$i++]-&gt;contents; $openSquareBracket = $tokens[$i++]-&gt;contents; $str = $tokens[$i++]-&gt;contents; $closeSquareBracket = $tokens[$i++]-&gt;contents; $quote = $tokens[$i]-&gt;contents; echo $var . "['" . $str . "']"; $doubleQuote = false; continue; } if ($token-&gt;contents == '"') { $doubleQuote = !$doubleQuote; } if ($doubleQuote &amp;&amp; $token-&gt;contents == '"' &amp;&amp; isAssocArrayVariable(1)) { // don't echo " } elseif ($doubleQuote &amp;&amp; isAssocArrayVariable()) { if ($tokens[$i - 1]-&gt;contents != '"') { echo '" . '; } $var = $token-&gt;contents; $openSquareBracket = $tokens[++$i]-&gt;contents; $str = $tokens[++$i]-&gt;contents; $closeSquareBracket = $tokens[++$i]-&gt;contents; echo $var . "['" . $str . "']"; if ($tokens[$i + 1]-&gt;contents != '"') { echo ' . "'; } else { $i++; // process " $doubleQuote = false; } } elseif ($token-&gt;type == T_STRING &amp;&amp; $tokens[$i - 1]-&gt;contents == '[' &amp;&amp; $tokens[$i + 1]-&gt;contents == ']') { if (preg_match('/[a-z_]+/', $token-&gt;contents)) { echo "'" . $token-&gt;contents . "'"; } else { echo $token-&gt;contents; } } elseif ($token-&gt;type == T_ENCAPSED_AND_WHITESPACE || $token-&gt;type == T_STRING) { echo $token-&gt;contents; } elseif ($token-&gt;contents == '-' &amp;&amp; in_array($tokens[$i + 1]-&gt;type, array(T_LNUMBER, T_DNUMBER))) { echo '-'; } elseif (in_array($token-&gt;type, $CONTROL_STRUCTURES)) { echo $token-&gt;contents; if ($tokens[$i + 1]-&gt;type != T_WHITESPACE) { echo ' '; } } elseif ($token-&gt;contents == '}' &amp;&amp; in_array($tokens[$i + 1]-&gt;type, $CONTROL_STRUCTURES)) { echo '} '; } elseif ($token-&gt;contents == '=' &amp;&amp; $tokens[$i + 1]-&gt;contents == '&amp;') { if ($tokens[$i - 1]-&gt;type != T_WHITESPACE) { echo ' '; } $i++; // match &amp; echo '=&amp;'; if ($tokens[$i + 1]-&gt;type != T_WHITESPACE) { echo ' '; } } elseif ($token-&gt;contents == ':' &amp;&amp; $matchingTernary) { $matchingTernary = false; if ($tokens[$i - 1]-&gt;type != T_WHITESPACE) { echo ' '; } echo ':'; if ($tokens[$i + 1]-&gt;type != T_WHITESPACE) { echo ' '; } } elseif (in_array($token-&gt;contents, $WHITESPACE_BEFORE) &amp;&amp; $tokens[$i - 1]-&gt;type != T_WHITESPACE &amp;&amp; in_array($token-&gt;contents, $WHITESPACE_AFTER) &amp;&amp; $tokens[$i + 1]-&gt;type != T_WHITESPACE) { echo ' ' . $token-&gt;contents . ' '; } elseif (in_array($token-&gt;contents, $WHITESPACE_BEFORE) &amp;&amp; $tokens[$i - 1]-&gt;type != T_WHITESPACE) { echo ' ' . $token-&gt;contents; } elseif (in_array($token-&gt;contents, $WHITESPACE_AFTER) &amp;&amp; $tokens[$i + 1]-&gt;type != T_WHITESPACE) { echo $token-&gt;contents . ' '; } else { echo $token-&gt;contents; } } </code></pre>
Search for text between delimiters in MySQL <p>I am trying to extract a certain part of a column that is between delimiters.</p> <p>e.g. find foo in the following</p> <p>test 'esf :foo: bar</p> <p>So in the above I'd want to return foo, but all the regexp functions only return true|false, is there a way to do this in MySQL</p>
<p>Here ya go, bud:</p> <pre><code>SELECT SUBSTR(column, LOCATE(':',column)+1, (CHAR_LENGTH(column) - LOCATE(':',REVERSE(column)) - LOCATE(':',column))) FROM table </code></pre> <p>Yea, no clue why you're doing this, but this will do the trick.</p> <p>By performing a LOCATE, we can find the first ':'. To find the last ':', there's no reverse LOCATE, so we have to do it manually by performing a LOCATE(':', REVERSE(column)).</p> <p>With the index of the first ':', the number of chars from the last ':' to the end of the string, and the CHAR_LENGTH (<em>don't use LENGTH() for this</em>), we can use a little math to discover the length of the string between the two instances of ':'.</p> <p>This way we can peform a SUBSTR and dynamically pluck out the characters between the two ':'.</p> <p>Again, it's gross, but to each his own.</p>
Interlocked equivalent on Linux <p>In a C++ Linux app, what is the simplest way to get the functionality that the <a href="http://msdn.microsoft.com/en-us/library/system.threading.interlocked.aspx">Interlocked</a> functions on Win32 provide? Specifically, a lightweight way to atomically increment or add 32 or 64 bit integers? </p>
<p>Intel's open-source <a href="http://www.threadingbuildingblocks.org/">ThreadBuildingBlocks</a> has a template, Atomic, that offers the same functionality as .NET's Interlocked class.</p> <p>Unlike gcc's Atomic built-ins, it's cross platform and doesn't depend on a particular compiler. As Nemanja Trifunovic correctly points out above, it does depend on the <a href="http://en.wikipedia.org/wiki/Compare_and_swap">compare-and-swap</a> CPU instruction provided by x86 and Itanium chips. I guess you wouldn't expect anything else from an Intel library : )</p>
Multi-line label in RadioButton component (AS3) <p>I'm making a small quiz-application in Flash (and ActionScript 3). Decided to use the RadioButton-component for radiobuttons, but I'm having some problems getting the word-wrapping to work.</p> <p>The code for creating the button can be found below.</p> <pre><code>_button = new RadioButton(); _button.setStyle("textFormat", _format); _button.label = _config.toString(); _button.width = Number(_defaults.@alen); _button.textField.width = Number(_defaults.@alen); _button.textField.multiline = true; _button.textField.wordWrap = true; _button.value = _config.@value; _button.group = _group; _button.x = _config.@x; _button.y = _config.@y; </code></pre> <p>_config is a piece of XML, and _defaults is a piece of XML containing size-information and font-setup</p> <p>When I set _button.textField.wordWrap to true, the text gets split into multiple lines, but it's not split at _defaults.@alen, which I want, but looks like it happens pretty much after each word.</p> <p>Also, it sometimes splits it into several lines, but doesn't display it all until the mouse hovers over it.</p>
<p>Two possibilities: width should be in pixels, not in characters. In addition, don't forget that the button itself uses up some of the width.</p> <p>If you can't get it to work, instead of banging your head on it, might want to just create the label separately, either a simple TextField, or using a Label component. Slightly more code, but might be worth it to spend an extra 10 minutes writing code versus two hours getting the component to work how you want.</p>
how to prevent fgets blocks when file stream has no new data <p>I have a popen() function which executes "tail -f sometextfile". Aslong as there is data in the filestream obviously i can get the data through fgets(). Now, if no new data comes from tail, fgets() hangs. I tried ferror() and feof() to no avail. How can i make sure fgets() doesn't try to read data when nothing new is in the file stream? </p> <p>One of the suggestion was select(). Since this is for Windows Platform select doesn't seem to work as anonymous pipes do not seem to work for it (see <a href="http://stackoverflow.com/questions/152807/what-is-wrong-with-this-popen-select-example" rel="nofollow" title="this post">this post</a>).</p>
<p>In Linux (or any Unix-y OS), you can mark the underlying file descriptor used by popen() to be non-blocking. </p> <pre><code>#include &lt;fcntl.h&gt; FILE *proc = popen("tail -f /tmp/test.txt", "r"); int fd = fileno(proc); int flags; flags = fcntl(fd, F_GETFL, 0); flags |= O_NONBLOCK; fcntl(fd, F_SETFL, flags); </code></pre> <p>If there is no input available, fgets will return NULL with errno set to EWOULDBLOCK.</p>
How do I persist a ByRef variable into .net winforms dialog form? <p>I am creating a "department picker" form that is going to serve as a modal popup form with many of my "primary" forms of a Winforms application. Ideally the user is going to click on an icon next to a text box that will pop up the form, they will select the department they need, and when they click OK, the dialog will close and I will have the value selected for me to update the textbox with.</p> <p>I've already done the route with passing the owner of the dialog box into the dialog form and having the OK button click event do the proper update, but this forces me to do a DirectCast to the form type and I can then only reuse the picker on the current form.</p> <p>I have been able to use a ByRef variable in the constructor and successfully update a value, but it works only in the constructor. If I attempt to assign the ByRef value to some internal variable in the Department Picker class, I lose the reference aspect of it. This is my basic code attached to my form:</p> <pre class="lang-vb prettyprint-override"><code>Public Class DeptPicker Private m_TargetResult As String Public Sub New(ByRef TargetResult As String) InitializeComponent() ' This works just fine, my "parent" form has the reference value properly updated. TargetResult = "Booyah!" ' Once I leave the constructor, m_TargetResult is a simple string value that won't update the parent m_TargetResult = TargetResult End Sub Private Sub btnOK_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnOK.Click DialogResult = Windows.Forms.DialogResult.OK ' I get no love here. m_TargetResult is just a string and doesn't push the value back to the referenced variable I want. m_TargetResult = "That department I selected." Me.Close() End Sub Private Sub btnCancel_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnCancel.Click DialogResult = Windows.Forms.DialogResult.Cancel Me.Close() End Sub End Class </code></pre> <p>Can somebody tell me what I'm missing here or a different approach to make this happen?</p> <p><em>Note: Code sample is in VB.NET, but I'll take any C# answers too. 8^D</em></p>
<p>In such cases, I usually either</p> <ul> <li>Write a ShowDialog function that does what I want (e.g. return the value) or</li> <li>Just let the result be a property in the dialog. This is how the common file dialogs do it in the BCL. The caller must then read the property to get the result. That's fine in my opinion.</li> </ul> <p>You can also combine these methods, by making the result value a property in the dialog and creating a ShowDialog method that returns that property value, either as ByRef as you want or as a return value, depending on your needs.</p> <p>I'll add this as a usage instruction, for example (sorry, no VB over here, and you said C# is welcome):</p> <pre><code>using (var dlg = new DeptPicker()) { if (dlg.ShowDialog() == DialogResult.OK) { myTextBoxOrWhatEver.Text = dlg.TargetResult; } } </code></pre> <p>In the dialog itself, just do this:</p> <pre><code>void okButton_Click(object sender, EventArgs e) { TargetResult = whatever; // can also do this when the selection changes DialogResult = DialogResult.OK; Close(); } </code></pre> <p>I didn't use the new ShowDialog implementation in this sample though.</p>
What needs checking in for a Grails app? <p>What parts of a Grails application need to be stored in source-control? Some obvious parts that are needed:</p> <ul> <li>grails-app directory</li> <li>test directory</li> <li>web-app directory</li> </ul> <p>Now we reach questions like:</p> <ul> <li>If we use a Grails plug-in (like gldapo), do we need to check in that plugin? </li> <li>Do Grails plugins install in the Grails directory, or your project?</li> </ul> <p>I'm not looking to start a religious war about .project, so please ignore that, but are there any "hidden" project files I need to worry about, along with the plugin issues?</p> <p>Converted to a community wiki, as new versions of Grails have changed some of these solutions, especially as regards plugins.</p>
<ul> <li>You do not want ./plugins/core (Core Grails plugins) under SVN</li> <li>You do not want anything under ./web-app/WEB-INF/ under SVN. You should not usually need to put files in here. Files from ./conf are copied to WEB-INF/classes so they are on the classpath, if you need to supply anything.</li> </ul> <p>Here's a <a href="http://docs.codehaus.org/display/GRAILS/Checking+Projects+into+SVN">link</a> to the docs describing in more detail.</p>
How do I share a menu definition between a context menu and a regular menu in WPF <p>I have a defined MenuItem that I would like to share between two different menus on one page. The menu contains functionallity that is the same between both menus and I do not want two copies of it. Is there anyway to define a MenuItem in the Page.Resources and reference it in the ContextMenu XAML below?</p> <pre><code>&lt;Page.Resources&gt; &lt;MenuItem x:Key="123"/&gt; &lt;/Page.Resources&gt; &lt;ContextMenu&gt; &lt;MenuItem&gt;Something hardcoded&lt;/MenuItem&gt; &lt;!-- include shared menu here --&gt; &lt;/ContextMenu&gt; </code></pre>
<p>I've done this by setting x:Shared="False" on the menu item itself. Resources are shared between each place that uses them by default (meaning one instance across all uses), so turning that off means that a new "copy" of the resource is made each time.</p> <p>So:</p> <pre><code>&lt;MenuItem x:Key="myMenuItem" x:Shared="False" /&gt; </code></pre> <p>You'll still get a "copy" of it, but you only need to define it in one place. See if that helps. You use it like this within your menu definition:</p> <pre><code>&lt;StaticResource ResourceKey="myMenuItem" /&gt; </code></pre>
While-clause in T-SQL that loops forever <p>I was recently tasked with debugging a strange problem within an e-commerce application. After an application upgrade the site started to hang from time to time and I was sent in to debug. After checking the event log I found that the SQL-server wrote ~200 000 events in a couple of minutes with the message saying that a constraint had failed. After much debugging and some tracing I found the culprit. I've removed some unnecessary code and cleaned it up a bit but essentially this is it</p> <pre><code>WHILE EXISTS (SELECT * FROM ShoppingCartItem WHERE ShoppingCartItem.PurchID = @PurchID) BEGIN SELECT TOP 1 @TmpGFSID = ShoppingCartItem.GFSID, @TmpQuantity = ShoppingCartItem.Quantity, @TmpShoppingCartItemID = ShoppingCartItem.ShoppingCartItemID, FROM ShoppingCartItem INNER JOIN GoodsForSale on ShoppingCartItem.GFSID = GoodsForSale.GFSID WHERE ShoppingCartItem.PurchID = @PurchID EXEC @ErrorCode = spGoodsForSale_ReverseReservations @TmpGFSID, @TmpQuantity IF @ErrorCode &lt;&gt; 0 BEGIN Goto Cleanup END DELETE FROM ShoppingCartItem WHERE ShoppingCartItem.ShoppingCartItemID = @TmpShoppingCartItemID -- @@ROWCOUNT is 1 after this END </code></pre> <p>Facts:</p> <ol> <li>There's only one or two records matching the first select-clause</li> <li>RowCount from the DELETE statement indicates that it has been removed</li> <li>The WHILE-clause will loop forever</li> </ol> <p>The procedure has been rewritten to select the rows that should be deleted into a temporary in-memory table instead so the immediate problem is solved but this really sparked my curiosity.</p> <p>Why does it loop forever?</p> <p><strong>Clarification</strong>: The delete doesn't fail (@@rowcount is 1 after the delete stmt when debugged) <strong>Clarification 2</strong>: It shouldn't matter whether or not the SELECT TOP ... clause is ordered by any specific field since the record with the returned id will be deleted so in the next loop it should get another record.</p> <p><strong>Update</strong>: After checking the subversion logs I found the culprit commit that made this stored procedure to go haywire. The only real difference that I can find is that there previously was no join in the SELECT TOP 1 statement i.e. without that join it worked without any transaction statements surrounding the delete. It appears to be the introduction of the join that made SQL server more picky.</p> <p><strong>Update clarification</strong>: <a href="http://stackoverflow.com/questions/150250/while-clause-in-t-sql-that-loops-forever#150400">brien</a> pointed out that there's no need for the join but we actually do use some fields from the GoodsForSale table but I've removed them to keep the code simply so that we can concentrate on the problem at hand</p>
<p>Are you operating in explicit or implicit <a href="http://doc.ddart.net/mssql/sql70/ta-tz_8.htm" rel="nofollow">transaction mode</a>?</p> <p>Since you're in explicit mode, I think you need to surround the DELETE operation with BEGIN TRANSACTION and COMMIT TRANSACTION statements.</p> <pre><code>WHILE EXISTS (SELECT * FROM ShoppingCartItem WHERE ShoppingCartItem.PurchID = @PurchID) BEGIN SELECT TOP 1 @TmpGFSID = ShoppingCartItem.GFSID, @TmpQuantity = ShoppingCartItem.Quantity, @TmpShoppingCartItemID = ShoppingCartItem.ShoppingCartItemID, FROM ShoppingCartItem INNER JOIN GoodsForSale on ShoppingCartItem.GFSID = GoodsForSale.GFSID WHERE ShoppingCartItem.PurchID = @PurchID EXEC @ErrorCode = spGoodsForSale_ReverseReservations @TmpGFSID, @TmpQuantity IF @ErrorCode &lt;&gt; 0 BEGIN Goto Cleanup END BEGIN TRANSACTION delete DELETE FROM ShoppingCartItem WHERE ShoppingCartItem.ShoppingCartItemID = @TmpShoppingCartItemID -- @@ROWCOUNT is 1 after this COMMIT TRANSACTION delete END </code></pre> <p><strong>Clarification:</strong> The reason you'd need to use transactions is that the delete doesn't actually happen in the database until you do a COMMIT operation. This is generally used when you have multiple write operations in an atomic transaction. Basically, you only want the changes to happen to the DB if all of the operations are successful.</p> <p>In your case, there's only 1 operation, but since you're in explicit transaction mode, you need to tell SQL Server to <strong>really</strong> make the changes.</p>
Generating 'neighbours' for users based on rating <p>I'm looking for techniques to generate 'neighbours' (people with similar taste) for users on a site I am working on; something similar to the way last.fm works.</p> <p>Currently, I have a compatibilty function for users which could come into play. It ranks users on having 1) rated similar items 2) rated the item similarly. The function weighs point 2 heigher and this would be the most important if I had to use only one of these factors when generating 'neighbours'.</p> <p>One idea I had would be to just calculate the compatibilty of every combination of users and selecting the highest rated users to be the neighbours for the user. The downside of this is that as the number of users go up then this process couls take a very long time. For just a 1000 users, it needs 1000C2 (0.5 * 1000 * 999 = = 499 500) calls to the compatibility function which could be very heavy on the server also.</p> <p>So I am looking for any advice, links to articles etc on how best to achieve a system like this.</p>
<p>In the book Programming Collective Intelligence<br> <a href="http://oreilly.com/catalog/9780596529321" rel="nofollow">http://oreilly.com/catalog/9780596529321</a><br></p> <p>Chapter 2 "Making Recommendations" does a really good job of outlining methods of recommending items to people based on similarities between users. You could use the similarity algorithms to find the 'neighbours' you are looking for. The chapter is available on google book search here: <br> <a href="http://books.google.com/books?id=fEsZ3Ey-Hq4C&amp;printsec=frontcover" rel="nofollow">http://books.google.com/books?id=fEsZ3Ey-Hq4C&amp;printsec=frontcover</a></p>
Whats the best way to start using Mylyn? <p>I've heard a lot of good things about using Mylyn in eclipse.</p> <p>How could I set it up to give me a taste of how I could use it?</p> <p>Thanks</p>
<p>The <strong>seminal Developerworks article</strong> from the 2.0 release is a great introduction to Mylyn, and still relevant. Written by the Mik Kirsten who is the Mylyn project lead, it is a very clear explanation of something quite unique. Lots of pretty pictures showing it in action too.</p> <ul> <li><a href="http://www.tasktop.com/mylyn/tutorial" rel="nofollow">Mylyn Part one - Integrated Task Management</a></li> <li><a href="http://www.tasktop.com/mylyn/tutorial-part-2" rel="nofollow">Mylyn Part two - Automated Context Management</a></li> </ul>
Selecting unique rows in a set of two possibilities <p>The problem itself is simple, but I can't figure out a solution that does it in one query, and here's my "abstraction" of the problem to allow for a simpler explanation:</p> <p><strong>I will let my original explenation stand, but here's a set of sample data and the result i expect:</strong></p> <p>Ok, so here's some sample data, i separated pairs by a blank line</p> <pre><code>------------- | Key | Col | (Together they from a Unique Pair) -------------- | 1 Foo | | 1 Bar | | | | 2 Foo | | | | 3 Bar | | | | 4 Foo | | 4 Bar | -------------- </code></pre> <p>And the result I would expect, <strong>after running the query once</strong>, it need to be able to select this result set in one query:</p> <pre><code>1 - Foo 2 - Foo 3 - Bar 4 - Foo </code></pre> <p><em>Original explenation:</em></p> <p>I have a table, call it <code>TABLE</code> where I have a two columns say <code>ID</code> and <code>NAME</code> which together form the primary key of the table. Now I want to select something where <code>ID=1</code> and then first checks if it can find a row where <code>NAME</code> has the value "John", if "John" does not exist it should look for a row where <code>NAME</code> is "Bruce" - but only return "John" if both "Bruce" and "John" exists or only "John" exists of course.</p> <p>Also note that it should be able to return several rows per query that match the above criteria but with different ID/Name-combinations of course, and that the above explanation is just a simplification of the real problem.</p> <p>I could be completely blinded by my own code and line of thought but I just can't figure this out. </p>
<p>This is fairly similar to what you wrote, but should be fairly speedy as NOT EXISTS is more efficient, in this case, than NOT IN...</p> <pre><code>mysql&gt; select * from foo; +----+-----+ | id | col | +----+-----+ | 1 | Bar | | 1 | Foo | | 2 | Foo | | 3 | Bar | | 4 | Bar | | 4 | Foo | +----+-----+ SELECT id , col FROM foo f1 WHERE col = 'Foo' OR ( col = 'Bar' AND NOT EXISTS( SELECT * FROM foo f2 WHERE f1.id = f2.id AND f2.col = 'Foo' ) ); +----+-----+ | id | col | +----+-----+ | 1 | Foo | | 2 | Foo | | 3 | Bar | | 4 | Foo | +----+-----+ </code></pre>
Find the prefix substring which gives best compression <p><strong>Problem:</strong></p> <p>Given a list of strings, find the substring which, if subtracted from the beginning of all strings where it matches and replaced by an escape byte, gives the shortest total length.</p> <p><strong>Example:</strong></p> <p><code>"foo"</code>, <code>"fool"</code>, <code>"bar"</code></p> <p>The result is: "foo" as the base string with the strings <code>"\0"</code>, <code>"\0l"</code>, <code>"bar"</code> and a total length of 9 bytes. <code>"\0"</code> is the escape byte. The sum of the length of the original strings is 10, so in this case we only saved one byte.</p> <p><strong>A naive algorithm would look like:</strong></p> <pre><code>for string in list for i = 1, i &lt; length of string calculate total length based on prefix of string[0..i] if better than last best, save it return the best prefix </code></pre> <p>That will give us the answer, but it's something like O((n*m)^2), which is too expensive.</p>
<p>Use a forest of prefix trees (trie)...</p> <pre><code> f_2 b_1 / | o_2 a_1 | | o_2 r_1 | l_1 </code></pre> <p>then, we can find the best result, and guarantee it, by maximizing <code>(depth * frequency)</code> which will be replaced with your escape character. You can optimize the search by doing a branch and bound depth first search for the maximum.</p> <p>On the complexity: O(C), as mentioned in comment, for building it, and for finding the optimal, it depends. If you order the first elements frequency (O(A) --where A is the size of the languages alphabet), then you'll be able to cut out more branches, and have a good chance of getting sub-linear time.</p> <p>I think this is clear, I am not going to write it up --what is this a homework assignment? ;)</p>
HashSet vs. List performance <p>It's clear that a search performance of the generic <code>HashSet&lt;T&gt;</code> class is higher than of the generic <code>List&lt;T&gt;</code> class. Just compare the hash-based key with the linear approach in the <code>List&lt;T&gt;</code> class.</p> <p>However calculating a hash key may itself take some CPU cycles, so for a small amount of items the linear search can be a real alternative to the <code>HashSet&lt;T&gt;</code>.</p> <p>My question: where is the break-even?</p> <p>To simplify the scenario (and to be fair) let's assume that the <code>List&lt;T&gt;</code> class uses the element's <code>Equals()</code> method to identify an item.</p>
<p>A lot of people are saying that once you get to the size where speed is actually a concern that <code>HashSet&lt;T&gt;</code> will always beat <code>List&lt;T&gt;</code>, but that depends on what you are doing.</p> <p>Let's say you have a <code>List&lt;T&gt;</code> that will only ever have on average 5 items in it. Over a large number of cycles, if a single item is added or removed each cycle, you may well be better off using a <code>List&lt;T&gt;</code>.</p> <p>I did a test for this on my machine, and, well, it has to be very very small to get an advantage from <code>List&lt;T&gt;</code>. For a list of short strings, the advantage went away after size 5, for objects after size 20.</p> <pre><code>1 item LIST strs time: 617ms 1 item HASHSET strs time: 1332ms 2 item LIST strs time: 781ms 2 item HASHSET strs time: 1354ms 3 item LIST strs time: 950ms 3 item HASHSET strs time: 1405ms 4 item LIST strs time: 1126ms 4 item HASHSET strs time: 1441ms 5 item LIST strs time: 1370ms 5 item HASHSET strs time: 1452ms 6 item LIST strs time: 1481ms 6 item HASHSET strs time: 1418ms 7 item LIST strs time: 1581ms 7 item HASHSET strs time: 1464ms 8 item LIST strs time: 1726ms 8 item HASHSET strs time: 1398ms 9 item LIST strs time: 1901ms 9 item HASHSET strs time: 1433ms 1 item LIST objs time: 614ms 1 item HASHSET objs time: 1993ms 4 item LIST objs time: 837ms 4 item HASHSET objs time: 1914ms 7 item LIST objs time: 1070ms 7 item HASHSET objs time: 1900ms 10 item LIST objs time: 1267ms 10 item HASHSET objs time: 1904ms 13 item LIST objs time: 1494ms 13 item HASHSET objs time: 1893ms 16 item LIST objs time: 1695ms 16 item HASHSET objs time: 1879ms 19 item LIST objs time: 1902ms 19 item HASHSET objs time: 1950ms 22 item LIST objs time: 2136ms 22 item HASHSET objs time: 1893ms 25 item LIST objs time: 2357ms 25 item HASHSET objs time: 1826ms 28 item LIST objs time: 2555ms 28 item HASHSET objs time: 1865ms 31 item LIST objs time: 2755ms 31 item HASHSET objs time: 1963ms 34 item LIST objs time: 3025ms 34 item HASHSET objs time: 1874ms 37 item LIST objs time: 3195ms 37 item HASHSET objs time: 1958ms 40 item LIST objs time: 3401ms 40 item HASHSET objs time: 1855ms 43 item LIST objs time: 3618ms 43 item HASHSET objs time: 1869ms 46 item LIST objs time: 3883ms 46 item HASHSET objs time: 2046ms 49 item LIST objs time: 4218ms 49 item HASHSET objs time: 1873ms </code></pre> <p>Here is that data displayed as a graph:</p> <p><img src="http://i.stack.imgur.com/O4ly9.png" alt="enter image description here"></p> <p>Here's the code:</p> <pre><code>static void Main(string[] args) { int times = 10000000; for (int listSize = 1; listSize &lt; 10; listSize++) { List&lt;string&gt; list = new List&lt;string&gt;(); HashSet&lt;string&gt; hashset = new HashSet&lt;string&gt;(); for (int i = 0; i &lt; listSize; i++) { list.Add("string" + i.ToString()); hashset.Add("string" + i.ToString()); } Stopwatch timer = new Stopwatch(); timer.Start(); for (int i = 0; i &lt; times; i++) { list.Remove("string0"); list.Add("string0"); } timer.Stop(); Console.WriteLine(listSize.ToString() + " item LIST strs time: " + timer.ElapsedMilliseconds.ToString() + "ms"); timer = new Stopwatch(); timer.Start(); for (int i = 0; i &lt; times; i++) { hashset.Remove("string0"); hashset.Add("string0"); } timer.Stop(); Console.WriteLine(listSize.ToString() + " item HASHSET strs time: " + timer.ElapsedMilliseconds.ToString() + "ms"); Console.WriteLine(); } for (int listSize = 1; listSize &lt; 50; listSize+=3) { List&lt;object&gt; list = new List&lt;object&gt;(); HashSet&lt;object&gt; hashset = new HashSet&lt;object&gt;(); for (int i = 0; i &lt; listSize; i++) { list.Add(new object()); hashset.Add(new object()); } object objToAddRem = list[0]; Stopwatch timer = new Stopwatch(); timer.Start(); for (int i = 0; i &lt; times; i++) { list.Remove(objToAddRem); list.Add(objToAddRem); } timer.Stop(); Console.WriteLine(listSize.ToString() + " item LIST objs time: " + timer.ElapsedMilliseconds.ToString() + "ms"); timer = new Stopwatch(); timer.Start(); for (int i = 0; i &lt; times; i++) { hashset.Remove(objToAddRem); hashset.Add(objToAddRem); } timer.Stop(); Console.WriteLine(listSize.ToString() + " item HASHSET objs time: " + timer.ElapsedMilliseconds.ToString() + "ms"); Console.WriteLine(); } Console.ReadLine(); } </code></pre>
How to remove duplicate rows from flat file using SSIS? <p>Let me first say that being able to take 17 million records from a flat file, pushing to a DB on a remote box and having it take 7 minutes is amazing. SSIS truly is fantastic. But now that I have that data up there, how do I remove duplicates?</p> <p>Better yet, I want to take the flat file, remove the duplicates from the flat file and put them back into another flat file.</p> <p>I am thinking about a:</p> <p><strong><code>Data Flow Task</code></strong></p> <ul> <li>File source (with an associated file connection)</li> <li>A for loop container</li> <li>A script container that contains some logic to tell if another row exists</li> </ul> <p>Thak you, and everyone on this site is incredibly knowledgeable.</p> <p><strong><code>Update:</code></strong> <a href="http://rafael-salas.blogspot.com/2007/04/remove-duplicates-using-t-sql-rank.html">I have found this link, might help in answering this question</a></p>
<p>Use the Sort Component.</p> <p>Simply choose which fields you wish to sort your loaded rows by and in the bottom left corner you'll see a check box to remove duplicates. This box removes any rows which are duplicates based on the sort criteria only so in the example below the rows would be considered duplicate if we only sorted on the first field:</p> <pre><code>1 | sample A | 1 | sample B | </code></pre>
Strategies for Data Loading and DB Initialization for Integration Tests <p>I'm developing an integration testing framework for a data intensive J2EE enterprise application and I'm trying to decide upon a strategy for initializing and populating the database. We have a fairly complex model.</p> <p>The system will have to:</p> <ol> <li>Initialize the system itself </li> <li>Load users </li> <li>Load application test data</li> </ol> <p>The test data won't be as complex as the system will handle, load and stress testing is the domain of a specialized test team. We're interested in how well the UI's display what is in the system and that functions integration correctly from top to bottom.</p>
<p><a href="http://www.dbunit.org/" rel="nofollow" title="DBUnit">DBUnit</a> is a pretty good framework for loading data into a test database.</p>
Windows Forms UserControl overrides not being called <p>I am creating a Windows Forms control derived from UserControl to be embedded in a WPF app. I have generally followed the procedures given in <a href="http://www.codeproject.com/KB/WPF/WPFOpenGL.aspx?display=Print" rel="nofollow">this link</a>.</p> <pre><code>public ref class CTiledImgViewControl : public UserControl { ... virtual void OnPaint( PaintEventArgs^ e ) override; ... }; </code></pre> <p>And in my CPP file:</p> <pre><code>void CTiledImgViewControl::OnPaint( PaintEventArgs^ e ) { UserControl::OnPaint(e); // do something interesting... } </code></pre> <p>Everything compiles and runs, however the OnPaint method is never getting called.</p> <p>Any ideas of things to look for? I've done a lot with C++, but am pretty new to WinForms and WPF, so it could well be something obvious...</p>
<p>The <code>OnPaint</code> won't normally get called in a <code>UserControl</code> unless you set the appropriate style when it is constructed using the <code>SetStyle</code> method. You need to set the <code>UserPaint</code> style to true for the <code>OnPaint</code> to get called.</p> <pre><code>SetStyle(ControlStyles::UserPaint, true); </code></pre> <p><br/></p> <h3>Update</h3> <p>I recently encountered this issue myself and went digging for an answer. I wanted to perform some calculations during a paint (to leverage the unique handling of paint messages) but I wasn't always getting a call to <code>OnPaint</code>.</p> <p>After digging around with Reflector, I discovered that <code>OnPaint</code> is only called if the clipping rectangle of the corresponding <code>WM_PAINT</code> message is not empty. My <code>UserControl</code> instance had a child control that filled its entire client region and therefore, clipped it all. This meant that the clipping rectangle was empty and so no <code>OnPaint</code> call.</p> <p>I worked around this by overriding <code>WndProc</code> and adding a handler for <code>WM_PAINT</code> directly as I couldn't find another way to achieve what I wanted.</p>
Finalizers and Dispose <p>I've got a class named <code>BackgroundWorker</code> that has a thread constantly running. To turn this thread off, an instance variable named <code>stop</code> to needs to be <code>true</code>. </p> <p>To make sure the thread is freed when the class is done being used, I've added <code>IDisposable</code> and a finalizer that invokes <code>Dispose()</code>. Assuming that <code>stop = true</code> does indeed cause this thread to exit, is this sippet correct? It's fine to invoke <code>Dispose</code> from a finalizer, right?</p> <p>Finalizers should always call <code>Dispose</code> if the <code>object</code> inherits <code>IDisposable</code>, right?</p> <pre><code>/// &lt;summary&gt; /// Force the background thread to exit. /// &lt;/summary&gt; public void Dispose() { lock (this.locker) { this.stop = true; } } ~BackgroundWorker() { this.Dispose(); } </code></pre>
<p>First off, a <strong>severe warning</strong>. Don't use a finalizer like you are. You are setting yourself up for some very bad effects if you take locks within a finalizer. Short story is don't do it. Now to the original question.</p> <pre><code>public void Dispose() { Dispose(true); GC.SuppressFinalize(this); } /// &lt;summary&gt; /// Force the background thread to exit. /// &lt;/summary&gt; protected virtual void Dispose(bool disposing) { if (disposing) { lock (this.locker) { this.stop = true; } } } ~BackgroundWorker() { Dispose(false); } </code></pre> <p>The only reason to have a finalizer at all is to allow sub-classes to extend and release <strong>unmanaged resources</strong>. If you don't have subclasses then seal your class and drop the finalizer completely.</p>
How do I call controller/view methods from the console in Rails? <p>When I load <code>script/console</code>, some times I want play with the output of a controller or a view helper method.</p> <p>Are there ways to:</p> <ul> <li>simulate a request?</li> <li>call methods from a controller instance on said request?</li> <li>test helper methods, either via said controller instance or another way?</li> </ul>
<p>To call <strong>helpers</strong>, use the <code>helper</code> …hmm… helper.</p> <pre><code>$ ./script/console &gt;&gt; helper.number_to_currency('123.45') =&gt; "R$ 123,45" </code></pre> <p>If you want to use a helper that's not included by default (say, because you removed <code>helper :all</code> from <code>ApplicationController</code>), just include the helper.</p> <pre><code>&gt;&gt; include BogusHelper &gt;&gt; helper.bogus =&gt; "bogus output" </code></pre> <p>As for dealing with <strong>controllers</strong>, I quote <a href="http://stackoverflow.com/questions/151030/how-do-i-call-controller-view-methods-from-the-console-in-rails/1436342#1436342">Nick's</a> answer:</p> <blockquote> <pre><code>&gt; app.get '/posts/1' &gt; response = app.response # you now have a rails response object much like the integration tests &gt; response.body # get you the HTML &gt; response.cookies # hash of the cookies # etc, etc </code></pre> </blockquote>
How can I serve an image to the browser using Struts 2 + Hibernate 3? <p>I am developing a web application using Struts 2.1.2 and Hibernate 3.2.6.GA. I have an entity, <code>User</code>, which I have mapped to a table <code>USERS</code> in the DB using Hibernate. I want to have an image associated with this entity, which I plan to store as a <code>BLOB</code> in the DB. I also want to display the image on a webpage along with other attributes of the <code>User</code>.</p> <p>The solution I could think of was to have a table <code>IMAGES(ID, IMAGE)</code> where <code>IMAGE</code> is a <code>BLOB</code> column. <code>USERS</code> will have an <code>FK</code> column called <code>IMAGEID</code>, which points to the <code>IMAGES</code> table. I will then map a property on <code>User</code> entity, called <code>imageId</code> mapped to this <code>IMAGEID</code> as a Long. When rendering the page with a JSP, I would add images as <code>&lt;img src="images.action?id=1"/&gt;</code> etc, and have an Action which reads the image and streams the content to the browser, with the headers set to cache the image for a long time.</p> <p>Will this work? Is there a better approach for rendering images stored in a DB? Is storing such images in the DB the right approach in the first place?</p>
<p>Yes your suggested solution will work. Given that you are working in a Java environment storing the images in the database is the best way to go. If you are running in a single server environment with an application server that will let you deploy in an exploded format technically you could store the images on disk but that wouldn't be the best practice. One suggestion would be to use a servlet instead of a JSP. To get good browser behavior you want the browser to think that the file type that it is displaying matches the file type that it is expecting. Despite the existence of mime type headers the file extension is still really important. So you want a link that looks like this:</p> <pre><code>&lt;a href="foo.jsp"&gt;&lt;img src="imageservlet/123456789.png"&gt;&lt;/a&gt; </code></pre> <p>Where 123456789 is the primary key of your image in the database. Your servlet mapping would look like this:</p> <pre><code>&lt;servlet&gt; &lt;servlet-name&gt;ImageServlet&lt;/servlet-name&gt; &lt;servlet-class&gt;com.example.ImageServlet&lt;/servlet-class&gt; &lt;/servlet&gt; &lt;servlet-mapping&gt; &lt;servlet-name&gt;ImageServlet&lt;/servlet-name&gt; &lt;url-pattern&gt;/imageservlet/*&lt;/url-pattern&gt; &lt;/servlet-mapping&gt; </code></pre> <p>Then in your servlet simply parse the request URL for the image ID rather than using the query string as the query string will confuse some browsers. Using the query string won't break browsers outright but you'll get odd behavior with regards to caching and some browsers may report the content as unsafe.</p>
pl/sql dollar operator? <p>I encountered the following ddl in a pl/sql script this morning:</p> <p>create index genuser.idx$$_0bdd0011 ...</p> <p>My initial thought was that the index name was generated by a tool...but I'm also not a pl/sql superstar so I could very well be incorrect. Does the double dollar sign have any special significance in this statement? </p>
<p>No special meaning or significance.</p> <pre><code>SQL&gt; create table t (col number) 2 / Table created. SQL&gt; create index idx$$_0bdd0011 on t(col) 2 / Index created. </code></pre> <p>Note: CREATE INDEX is a DDL statement which is usually executed in a SQL script, not in PL/SQL.</p>
Are these interview questions too challenging for beginners? <p>So I just interviewed two people today, and gave them "tests" to see what their skills were like. Both are entry level applicants, one of which is actually still in college. Neither applicant saw anything wrong with the following code.</p> <p>I do, obviously or I wouldn't have picked those examples. <strong>Do you think these questions are too harsh for newbie programmers?</strong></p> <p>I guess I should also note neither of them had much experience with C#... but I don't think the issues with these are language dependent. </p> <pre><code>//For the following functions, evaluate the code for quality and discuss. E.g. //E.g. could it be done more efficiently? could it cause bugs? public void Question1() { int active = 0; CheckBox chkactive = (CheckBox)item.FindControl("chkactive"); if (chkactive.Checked == true) { active = 1; } dmxdevice.Active = Convert.ToBoolean(active); } public void Question2(bool IsPostBack) { if (!IsPostBack) { BindlistviewNotification(); } if (lsvnotificationList.Items.Count == 0) { BindlistviewNotification(); } } //Question 3 protected void lsvnotificationList_ItemUpdating(object sender, ListViewUpdateEventArgs e) { ListViewDataItem item = lsvnotificationList.Items[e.ItemIndex]; string Email = ((TextBox)item.FindControl("txtEmailAddress")).Text; int id = Convert.ToInt32(((HiddenField)item.FindControl("hfID")).Value); ESLinq.ESLinqDataContext db = new ESLinq.ESLinqDataContext(); var compare = from N in db.NotificationLists where N.ID == id select N; if (compare.Count() &gt; 0) { lblmessage.Text = "Record Already Exists"; } else { ESLinq.NotificationList Notice = db.NotificationLists.Where(N =&gt; N.ID == id).Single(); Notice.EmailAddress = Email; db.SubmitChanges(); } lsvnotificationList.EditIndex = -1; BindlistviewNotification(); } </code></pre>
<p>I don't typically throw code at someone interviewing for a position and say "what's wrong?", mainly because I'm not convinced it really finds me the best candidate. Interviews are sometimes stressful and a bit overwhelming and coders aren't always on their A-game.</p> <p>Regarding the questions, honestly I think that if I didn't know C#, I'd have a hard time with question 3. Question #2 is a bit funky too. Yes, I get what you're going for there but what if the idea was that BindlistviewNotification() was supposed to be called twice? It isn't clear and one could argue there isn't enough info. Question 1 is easy enough to clean up, but I'm not convinced even it proves anything for an entry-level developer without a background in C#.</p> <p>I think I'd rather have something talk me through how they'd attack a problem (in pseudo-code or whatever language they are comfortable with) and assess them from that. Just a personal opinion, though.</p>
How do I embed a File Version in an MSI file with Visual Studio? <p>I have a setup project for my C# program, and this setup project has a Version in its properties. I'd like for the MSI file that is generated to have this Version embedded in it, so I can mouse over it in explorer and see what version the file is.</p> <p>I'm using VS2008. How can I do this?</p>
<p>If you simply add the "Version: 1.5.0" text into the Description property of the Setup Project, the version number also shows on the MSI file like so: </p> <p><a href="http://screencast.com/t/A499i6jS" rel="nofollow">http://screencast.com/t/A499i6jS</a></p>
What combination do you use for your polyglot solution? <p>Those of us who use multiple languages to solve problems can combine them in a lot of ways. Personally I use PL/SQL, XSLT, JavaScript, and Java plus the pseudo languages HTML, XML, CSS, Ant, and Bash. What do you use? </p>
<p>Paraphrasing one of my favorite quotes:</p> <blockquote> <p>Always write your code as if it were going to be maintained by a homicidal maniac that knows your home address.</p> </blockquote>
IDE's for C# development on Linux? <p>What are my options? I tried MonoDevelop over a year ago but it was extremely buggy. Is the latest version a stable development environment?</p>
<p>MonoDevelop 2.0 has been released, it now has a decent GUI debugger, code completion, intellisense c# 3.0 support (including linq), and a descent GTK# Visual Designer.</p> <p>In short, since the 2.0 release I have started using mono develop again and am very happy with it so far.</p> <p>Check out the <a href="http://monodevelop.com/">MonoDevelop website</a> for more info.</p>
Should I provide a deep clone when implementing ICloneable? <p>It is unclear to me from the <a href="http://msdn.microsoft.com/en-us/library/system.icloneable.aspx" rel="nofollow">MSDN documentation</a> if I should provide a deep or a shallow clone when implementing ICloneable. What is the preferred option?</p>
<p>Short answer: Yes.</p> <p>Long Answer: Don't use ICloneable. That is because .Clone isn't defined as being a shallow or a deep clone. You should implement your own IClone interface, and describe how the clone should work.</p>
How to detect a remote side socket close? <p>How do you detect if <code>Socket#close()</code> has been called on a socket on the remote side?</p>
<p>The <code>isConnected</code> method won't help, it will return <code>true</code> even if the remote side has closed the socket. Try this: </p> <pre><code>public class MyServer { public static final int PORT = 12345; public static void main(String[] args) throws IOException, InterruptedException { ServerSocket ss = ServerSocketFactory.getDefault().createServerSocket(PORT); Socket s = ss.accept(); Thread.sleep(5000); ss.close(); s.close(); } } public class MyClient { public static void main(String[] args) throws IOException, InterruptedException { Socket s = SocketFactory.getDefault().createSocket("localhost", MyServer.PORT); System.out.println(" connected: " + s.isConnected()); Thread.sleep(10000); System.out.println(" connected: " + s.isConnected()); } } </code></pre> <p>Start the server, start the client. You'll see that it prints "connected: true" twice, even though the socket is closed the second time.</p> <p>The only way to really find out is by reading (you'll get -1 as return value) or writing (an <code>IOException</code> (broken pipe) will be thrown) on the associated Input/OutputStreams.</p>
Can I trust PHP __destruct() method to be called? <p>In PHP5, is the __destruct() method guaranteed to be called for each object instance? Can exceptions in the program prevent this from happening?</p>
<p>It's also worth mentioning that, in the case of a subclass that has its own destructor, the parent destructor is <strong>not</strong> called automatically.</p> <p>You have to explicitly call <strong>parent::__destruct()</strong> from the subclass <strong>__destruct()</strong> method if the parent class does any required cleanup.</p>
WPF Commands and Parameters <p>I'm finding the WPF command parameters to be a limitation. Perhaps that's a sign that I'm using them for the wrong purpose, but I'm still giving it a try before I scrap and take a different tack.</p> <p>I put together a system for <a href="http://stackoverflow.com/questions/151686/asynchrnonous-wpf-commands">executing commands asynchronously</a>, but it's hard to use anything that requires data input. I know one common pattern with WPF commands is to pass in <code>this</code>. But <code>this</code> will not work at all for asynchronous commands because all the dependency properties are then inaccessible.</p> <p>I end up with code like this:</p> <pre><code>&lt;Button Command="{Binding ElementName=servicePage, Path=InstallServiceCommand}"&gt; &lt;Button.CommandParameter&gt; &lt;MultiBinding Converter="{StaticResource InstallServiceParameterConverter}"&gt; &lt;MultiBinding.Bindings&gt; &lt;Binding ElementName="servicePage" Path="IsInstalled"/&gt; &lt;Binding ElementName="localURI" Path="Text"/&gt; &lt;Binding ElementName="meshURI" Path="Text"/&gt; &lt;Binding ElementName="registerWithMesh" Path="IsChecked"/&gt; &lt;/MultiBinding.Bindings&gt; &lt;/MultiBinding&gt; &lt;/Button.CommandParameter&gt; &lt;/Button&gt; </code></pre> <p>and also need the InstallServiceParametersConverter class (plus InstallServiceParameters).</p> <p>Anyone see an obvious way to improve upon this?</p>
<p>Let me point you to my open source project Caliburn. You can find it at <a href="http://caliburn.codeplex.com/" rel="nofollow">here</a>. The feature that would most help solve your problem is documented briefly <a href="http://caliburn.codeplex.com/Wiki/View.aspx?title=Action%20Basics&amp;referringTitle=Table%20Of%20Contents." rel="nofollow">here</a> </p>
Custom Sorting of a DataSet Column <p>I have a DataSet that contains a few columns. One of these columns is a number - most of the time. Because it's occasionally a string, in the database it's a varchar(10) column.</p> <p>However, when you sort a varchar column, it sorts it like a string. What I want to do instead is to try and override this somehow so that it sorts the integers like integers; this isn't all that hard, and I've already got a function that does this elsewhere in my code. However, I don't think it's possible to give a typed DataSet like I have a custom type with its own sorting implementation, and from what I can see BindingSource doesn't think about columns at all, which makes it awful hard to sort on them. I can easily do it using the ListView/DataGridView sorting functionality -- but I'd like the display to be in virtual mode because of the quantity of data I have, and for that I need to provide my own sorting anyway.</p> <p>Is there any way to do what I want to do?</p>
<p>I think your best bet is to add a new calculated column which converts the varchar(10) to an int, and sort on that.</p> <pre><code>myDataTable.Columns.Add("Sorter", typeof(System.Int32), "Convert(TextColumn, 'System.Int32')"); </code></pre> <p>This will throw exceptions when the string in your varchar column (which I've referred to as "TextColumn" in the code above), but you may be able to work around that using an Iif() function call in the expression.</p>
Sqlite update field if it contains <p>Given a database field named "widget_ids", containing data like "67/797/124/" or "45/", where the numbers are slash separated widget_ids... how would you make an update statement with SQL that would say: "if the widget_ids of the row with id X contains the text "somenumber/" do nothing, otherwise append "somenumber/" to it's current value"</p> <p>Can you do something like that with SQL, or more specifically, sqlite? Is that something that is better done in the program for some reason or is there support for "if-then" like syntax in SQL?</p>
<p>Updates are kind of like if-thens themselves, and there is also if-then support of some sort in most SQL implementations. A simple solution might be:</p> <pre><code>update &lt;tablename&gt; set widget_id = widget_id + "somenumber/" where row_id = X and widget_id not like "%/somenumber/%" and widget_id not like "somenumber/%"; </code></pre>
Why would you use an assignment in a condition? <p>In many languages assignments are legal in conditions. I never understood the reason behind this. Why would you write:</p> <pre><code>if (var1 = var2) { ... } </code></pre> <p>instead of:</p> <pre><code>var1 = var2; if (var1) { ... } </code></pre>
<p>It's more useful for loops than if statements.</p> <pre><code>while( var = GetNext() ) { ...do something with var } </code></pre> <p>Which would otherwise have to be written</p> <pre><code>var = GetNext(); while( var ) { ...do something var = GetNext(); } </code></pre>
root folder equivalent in windows <p>Is C drive treated as the root folder in windows when one says \folder1\folder2\ in linux and windows C:\folder1\folder2.</p>
<p>In Windows it's relative to what drive your current working directory is at the time. If your current directory is in the C drive then C:\ would be the root. If the current directory is the D drive then D:\ would be the root. There is no absolute root.</p>
saslpasswd2: generic failure on Windows <p>I get a generic failure when I try to run:</p> <pre><code>saslpasswd2 username </code></pre> <p>This was installed by Collanet's Subversion 1.5.2.</p>
<p>The problem that I had was that the sasl executables are trying to access the sasldb file at:</p> <pre><code>C:\CMU\sasldb2 </code></pre> <p>Make sure that you create the directory C:\CMU</p>
Are there any open source projects using DDD (Domain Driven Design)? <p>I'm trying to understand the concepts behind DDD, but I find it hard to understand just by reading books as they tend to discuss the topic in a rather abstract way. I would like to see some good implementations of DDD in code, preferably in C#.</p> <p>Are there any good examples of projects practicing DDD in the open source world?</p>
<p>Eric Evans and a Swedish consulting company have released a sample application based on the shipping example that Eric uses throughout the book. It's in Java, but the concepts are well documented on the project page.</p> <p><a href="http://dddsample.sourceforge.net/" rel="nofollow">http://dddsample.sourceforge.net/</a></p> <p>However, be warned that DDD is more about the journey than the destination. Understand that the sample code you are looking took many forms before it became what you see now. You did not see the awkward models that were used initially and you're missing the steps taken to refactor the model based on insight gained along the way. While the building blocks are important in DDD, Eric belives they are over-emphasized, so take all samples with a grain of salt.</p>
Setup wxWidget in Netbeans 6.1 C++ On MS Windows? <p>Im running Netbeans 6.1 with C++ Plugin and cygwin (gcc compiler) how do I setup wxWidget to work with it?</p>
<p><a href="http://www.daltonfilho.com/2008/02/23/wxwidgets-on-windows-using-netbeans-60-with-mingw-msys/" rel="nofollow">http://www.daltonfilho.com/2008/02/23/wxwidgets-on-windows-using-netbeans-60-with-mingw-msys/</a> seams to work.</p>
Using noweb on a large Java project <p>Has anyone used the <a href="http://www.cs.tufts.edu/~nr/noweb/" rel="nofollow">noweb</a> literate programming tool on a large Java project, where several source code files must be generated in different subdirectories? How did you manage this with noweb? Are there any resources and/or best practices out there?</p>
<p>Noweb will dump out files relative to the current working directory, or at the absolute path you specify. Just don't use * at the end of your filename (to avoid inserting the # preprocessor directives). I would recommend using %def with @ to show where you define and use names.</p> <pre><code>&lt;&lt;/path/to/file.java&gt;&gt;= reallyImportantVariable += 1; @ %def reallyImportantVariable </code></pre> <p>noweb lets you reorder and (the real win) reuse snippets of code, which I don't think javac would understand.</p> <p>I'd agree that since most people expect that you'll use javadoc, you're probably swimming against the stream to use noweb.</p>
Java: StringBuffer & Concatenation <p>I'm using StringBuffer in Java to concat strings together, like so:</p> <pre><code>StringBuffer str = new StringBuffer(); str.append("string value"); </code></pre> <p>I would like to know if there's a method (although I didn't find anything from a quick glance at the documentation) or some other way to add "padding".</p> <p>Let me explain; every time I append something to the string, I want to add a space in the end, like so:</p> <pre><code>String foo = "string value"; str.append(foo + " "); </code></pre> <p>and I have several calls to append.. and every time, I want to add a space. Is there a way to set the object so that it will add a space automatically after each append?</p> <p>EDIT --</p> <pre><code>String input StringBuffer query = new StringBuffer(); Scanner scanner = new Scanner(System.in); scanner.UseDelimiter("\n"); do { System.out.println("sql&gt; "); input = scanner.next(); if (!empty(input)) query.append(input); if (query.toString().trim().endsWith(";")) { //run query } } while (!input.equalsIgnoreCase("exit"); </code></pre> <p>I'll use StringBuilder though as grom suggested, but that's how the code looks right now</p>
<p>I think this is handled easier either with a helper method (untested code):</p> <pre><code>public String myMethod() { StringBuilder sb = new StringBuilder(); addToBuffer(sb, "Hello").addToBuffer("there,"); addToBuffer(sb, "it").addToBuffer(sb, "works"); } private StringBuilder addToBuffer(StringBuilder sb, String what) { return sb.append(what).append(' '); // char is even faster here! ;) } </code></pre> <p>Or even using a Builder pattern with a fluent interface (also untested code):</p> <pre><code>public String myMethod() { SBBuilder builder = new SBBuilder() .add("Hello").add("there") .add("it", "works", "just", "fine!"); for (int i = 0; i &lt; 10; i++) { builder.add("adding").add(String.valueOf(i)); } System.out.println(builder.build()); } public static class SBBuilder { private StringBuilder sb = new StringBuilder(); public SBBuilder add(String... parts) { for (String p : parts) { sb.append(p).append(' '); // char is even faster here! ;) } return this; } public String build() { return sb.toString(); } } </code></pre> <p>Here's an <a href="http://java.dzone.com/news/factories-builders-and-fluent-">article</a> on the subject.</p> <p>Hope it helps! :)</p>
Ruby on rails (based on Mephisto) - Unable to contact server <p>I am completely new to ruby and I inherited a ruby system for a product catalogue. Most of my users are able to view everything as they should but overseas users (specifically Mexico) cannot contact the server once logged in. They are an active user. I'm sorry I cannot be more specific, and the system is private so I cannot grant access. Has anyone had any issues similar to this before? Is it a user-end issue or a system error?</p>
<p>Speaking as somebody who <em>regularly</em> ends up on your user's side of the fence, the number one culprit for this symptom is "Clueless administrator". There are many, many sites which generically block either large blocks of IP space or which geolocate and carve out big portions of the world. </p> <p>For example, a surprising number of American blogs block Asian countries (including Japan) out of a misplaced effort to avoid DDOS attacks (which actually probably originated in Russia or China but, hey, this species of administrator isn't very good on fine tuning solutions). I have to hop over to my American proxy server to access those sites.</p> <p>So the first thing I'd do to diagnose your problems is to see whether your Mexican users are making it to the server at all, or whether they're being blocked somewhere earlier (router? firewall? etc). Then, to determine whether the problem is on your end or their end, I'd try to replicate the issue with you proxying your connection through a Mexican proxy and repeating the actions they took to cause the issue. </p> <p>The fact that they get blocked after logging in could indicate that you have https issues , for example with an HTTPS accelerator installed [1], or it could be that your frontend server is properly serving up the static content but doing the checking on dynamic requests only.</p> <p>[1] We've seen some <strong>really</strong> weird bugs at work caused by a malfunctioning HTTPS accelerator.</p>
Get class property name <p>I have my winform application gathering data using databinding. Everything looks fine except that I have to link the <strong>property</strong> with the <strong>textedit</strong> using a string:</p> <blockquote> <p>Me.TextEdit4.DataBindings.Add(New System.Windows.Forms.Binding("EditValue", Me.MyClassBindingSource, "MyClassProperty", True))</p> </blockquote> <p>This works fine but if I change the class' property name, the compiler obviously will not warn me . </p> <p>I would like to be able to get the property name by reflection but I don't know how to specify the name of the property I want (I only know how to iterate among all the properties of the class) </p> <p>Any idea?</p>
<p>If you are using C# 3.0, there is a way to get the name of the property dynamically, without hard coded it.</p> <pre><code>private string GetPropertyName&lt;TValue&gt;(Expression&lt;Func&lt;BindingSourceType, TValue&gt;&gt; propertySelector) { var memberExpression = propertySelector.Body as MemberExpression; return memberExpression != null ? memberExpression.Member.Name : string.empty; } </code></pre> <p>Where <code>BindingSourceType</code> is the class name of your datasource object instance.</p> <p>Then, you could use a lambda expression to select the property you want to bind, in a strongly typed manner :</p> <pre><code>this.textBox.DataBindings.Add(GetPropertyName(o =&gt; o.MyClassProperty), this.myDataSourceObject, "Text"); </code></pre> <p>It will allow you to refactor your code safely, without braking all your databinding stuff. But using expression trees is the same as using reflection, in terms of performance.</p> <p><strong>The previous code is quite ugly and unchecked, but you get the idea.</strong></p>
What's the canonical way to check for type in python? <p>What is the best way to check whether a given object is of a given type? How about checking whether the object inherits from a given type?</p> <p>Let's say I have an object <code>o</code>. How do I check whether it's a <code>str</code>?</p>
<p>To check if the type of <code>o</code> is exactly <code>str</code>:</p> <pre><code>type(o) is str </code></pre> <p>To check if <code>o</code> is an instance of <code>str</code> or any subclass of <code>str</code> (this would be the "canonical" way):</p> <pre><code>isinstance(o, str) </code></pre> <p>The following also works, and can be useful in some cases:</p> <pre><code>issubclass(type(o), str) type(o) in ([str] + str.__subclasses__()) </code></pre> <p>See <a href="http://docs.python.org/2/library/functions.html">Built-in Functions</a> in the Python Library Reference for relevant information.</p> <p>One more note: in this case, you may actually want to use:</p> <pre><code>isinstance(o, basestring) </code></pre> <p>because this will also catch Unicode strings (<code>unicode</code> is not a subclass of <code>str</code>; both <code>str</code> and <code>unicode</code> are subclasses of <code>basestring</code>).</p> <p>Alternatively, <code>isinstance</code> accepts a tuple of classes. This will return True if x is an instance of any subclass of any of (str, unicode):</p> <pre><code>isinstance(o, (str, unicode)) </code></pre>
How to stop the Access 2007 Configuration Progress when switching versions <p>Like many developers I need to run more than 1 version of MS Access. I have just installed Access 2007. If I open Access 2003 and then open Access 2007 I have to wait 3mins for the 'Configuring Microsoft Office Enterprise 2007..." dialog. Then if I open Access 2003 again it takes another 30secs or so to configure that. </p> <p>PLEASE NOTE: I am using shortcuts to open the files that include the full path to Access. Eg to open Access 2007:</p> <pre><code> "C:\program files\microsoft office 12\office12\msaccess.exe" "C:\test.accdb" </code></pre> <p>and for 2003:</p> <pre><code> "C:\program files\microsoft office 11\office11\msaccess.exe" "C:\test.mdb" </code></pre> <p>Does anyone have a solution to avoid this? </p>
<p>This is caused by Windows Installer, which is used by both installers. Advertised shortcuts as used by both Office 2003 and Office 2007 invoke Windows Installer to check that the entire feature is installed properly; the installer detects that something else (in this case the other product) has registered the file extensions used by Access (possibly the ProgIds as well) and decides that a repair is necessary, so it invokes the 'Configuring Office' dialog and proceeds to reinstall various components.</p> <p>To avoid this, run Access from Program Files directly; create shortcuts if you'll be doing this frequently.</p>
Transpose a set of rows as columns in SQL Server 2000 <p>Is there any facility of transposing rows to columns in SQL Server (it is possible in MS-Access)? I was befuddled because this facility is available in MS-Access but not in SQL Server. Is it by design that this feature has not been included in SQL Server?</p>
<p>The example at <a href="http://jdixon.dotnetdevelopersjournal.com/pivot_table_data_in_sql_server_2000_and_2005.htm" rel="nofollow">http://jdixon.dotnetdevelopersjournal.com/pivot_table_data_in_sql_server_2000_and_2005.htm</a> only works if you know in advance what the row values can be. For example, let's say you have an entity with custom attributes and the custom attributes are implemented as rows in a child table, where the child table is basically variable/value pairs, and those variable/value pairs are configurable. </p> <pre><code>color red size big city Chicago </code></pre> <p>I'm going to describe a technique that works. I've used it. I'm NOT promoting it, but it works.</p> <p>To pivot the data where you don't know what the values can be in advance, create a temp table on the fly with no columns. Then use a cursor to loop through your rows, issuing a dynamically built "alter table" for each variable, so that in the end your temp table has the columns, color, size, city.</p> <p>Then you insert one row in your temp table, update it via another cursor through the variable, value pairs, and then select it, usually joined with its parent entity, in effect making it seem like those custom variable/value pairs were like built-in columns in the original parent entity.</p>
.NET XmlDocument LoadXML and Entities <p>When loading XML into an XmlDocument, i.e.</p> <pre> XmlDocument document = new XmlDocument(); document.LoadXml(xmlData); </pre> <p>is there any way to stop the process from replacing entities? I've got a strange problem where I've got a TM symbol (stored as the entity #8482) in the xml being converted into the TM character. As far as I'm concerned this shouldn't happen as the XML document has the encoding ISO-8859-1 (which doesn't have the TM symbol)</p> <p>Thanks</p>
<p>What are you writing it to? A TextWriter? a Stream? what?</p> <p>The following keeps the entity (well, it replaces it with the hex equivalent) - but if you do the same with a StringWriter it detects the unicode and uses that instead:</p> <pre><code> XmlDocument doc = new XmlDocument(); doc.LoadXml(@"&lt;xml&gt;&amp;#8482;&lt;/xml&gt;"); using (MemoryStream ms = new MemoryStream()) { XmlWriterSettings settings = new XmlWriterSettings(); settings.Encoding = Encoding.GetEncoding("ISO-8859-1"); XmlWriter xw = XmlWriter.Create(ms, settings); doc.Save(xw); xw.Close(); Console.WriteLine(Encoding.UTF8.GetString(ms.ToArray())); } </code></pre> <p>Outputs:</p> <pre><code> &lt;?xml version="1.0" encoding="iso-8859-1"?&gt;&lt;xml&gt;&amp;#x2122;&lt;/xml&gt; </code></pre>
Are there any good free .Net network libraries? (FTP, SFTP, SSH, etc.) <p>I'm a bit surprised I haven't found a good open source library for performing common network tasks. There are a few very good commercial libraries, but they're too expensive to use on an open source project. </p> <p>Anyone know of any?</p>
<p>SSH.NET Library - <a href="http://sshnet.codeplex.com/">http://sshnet.codeplex.com/</a></p> <p>Inspired by Sharp.SSH, this library is complete rewrite using .NET 4.0, without any third party dependencies and utilizes parallelism as much as possible to allow best performance.</p> <p>It's been a solid C# implementation of client side SSH.</p>
Manage Scrum Software <p>What software do you use to manage Scrum software development ? </p> <p>We've tried Tackle and VersionOne (both free) so far and they are good except for the fact that it's difficult to track work in progress. For example, if I have a task that I estimate will take me 8 hours to complete, I've done 4 hours of work with 4 hours remaining, the task is always reported as 8 hours remaining until it is marked complete, at which time it falls to zero. </p> <p>I'd like to use a tool that will allow me to take an accurate work at the teams WIP at the end of each week and see how much impact that work has had towards a deadline along with completed tasks. </p> <p>Thanks for your input!</p>
<p>I recommend a white board and excel spreadsheets. The whiteboard has story cards (index cards) , where the work in progress is tracked. The story card starts out with say 8 hours, and as the work progresses decrement the number on the card. At the end of the day, put the numbers in the cards to a spreadsheet.</p> <p>The whiteboard is visible all the time, and gives the whole team visibility on how the work is progressing.</p>
Has anyone used lucene.net with Linq-to-Entities? <p>If anyone has done this, please let me know. I don't know anything about lucene.net. I have never used it, but I heard about it. I was wondering how something like that would integrate with the Linq entity framework?</p>
<p>Check out <a href="http://www.codeplex.com/linqtolucene" rel="nofollow">Linq to Lucene</a> project.</p>
What are good resources on compilation? <p>Summary for the impatient: I'm searching for good references on generating code for common language constructs but not parsing.</p> <p>I am interested in programming languages and try to read the literature as much as possible. But most of them covers the topic in a functional and theoretical perspective that, I find them hard to understand let alone implement the ideas.</p> <p>So the question is; Which resources do you suggest about programming language implementations that covers the topic in a more imperative and practical fashion?</p> <p>For example, I find "<em>The Implementation of Lua 5.0</em>" paper very instructive.</p> <p>Note that, I am not seeking articles about parsing or tokenizing.</p>
<p>Here are a bunch of good textbooks:</p> <p>Modern Compiler Implementation in Java (Tiger book) A.W. Appel Cambridge University Press, 1998 ISBN 0-52158-388-8 A textbook tutorial on compiler implementation, including techniques for many language features</p> <p>Compilers: Principles, Techniques and Tools (Dragon book) Aho, Lam, Sethi and Ullman Addison-Wesley, 2006 ISBN 0321486811 The classic compilers textbook, although its front-end emphasis reflects its age.</p> <p>Advanced Compiler Design and Implementation (Whale book) Steven Muchnick Morgan Kaufman Publishers, 1997 ISBN 1-55860-320-4 Essentially a recipe book of optimizations; very complete and suited for industrial practitioners and researchers.</p> <p>Engineering a Compiler (Ark book) Keith D. Cooper, Linda Torczon Morgan Kaufman Publishers, 2003 ISBN 1-55860-698-X A modern classroom textbook, with increased emphasis on the back-end and implementation techniques.</p> <p>Optimizing Compilers for Modern Architectures Randy Allen and Ken Kennedy Morgan Kaufman Publishers, 2001 ISBN 1-55860-286-0 A modern textbook that focuses on optimizations including parallelization and memory hierarchy optimizations.</p> <p>Programming Languages Pragmatics Michael L. Scott Morgan Kaufmann Publishers, 2005 ISBN 0126339511</p>
Is it feasible to create a REST client with Flex? <p>I'm starting a project using a Restful architecture implemented in Java (using the new JAX-RS standard)</p> <p>We are planning to develop the GUI with a Flex application. I have already found some problems with this implementation using the HTTPService component (the response error codes, headers access...).</p> <p>Any of you guys have some experience in a similar project. Is it feasible?</p>
<p>The problem here is that a lot of the web discussions around this issue are a year or more old. I'm working through this same research right now, and this is what I've learned today.</p> <p>This <a href="http://www.ibm.com/developerworks/websphere/library/techarticles/0808_rasillo/0808_rasillo.html">IBM Developer Works article from August 2008</a> by Jorge Rasillo and Mike Burr shows how to do a Flex front-end / RESTful back-end app (examples in PHP and Groovy). Nice article. Anyway, here's the take away:</p> <ul> <li>Their PHP/Groovy code <em>uses and expects</em> PUT and DELETE.</li> <li>But the Flex code has to use POST, but sets the HTTP header X-Method-Override to DELETE (you can do the same for PUT I presume).</li> <li>Note that this is <em>not</em> the Proxy method discussed above.</li> </ul> <p><code><pre> // Flex doesn't know how to generate an HTTP DELETE. // Fortunately, sMash/Zero will interpret an HTTP POST with // an X-Method-Override: DELETE header as a DELETE. deleteTodoHS.headers['X-Method-Override'] = 'DELETE';</pre></code></p> <p>What's happening here? the IBM web server intercepts and interprets the "POST with DELETE" as a DELETE.</p> <p>So, I dug further and found this <a href="http://www.pluralsight.com/community/blogs/dbox/archive/2007/01/16/45725.aspx">post and discussion with Don Box</a> (one of the original SOAP guys). Apparently this is a fairly standard behavior since some browsers, etc. do not support PUT and DELETE, and is a work-around that has been around a while. Here's a snippet, but there's much more discussion.</p> <blockquote> <p>"If I were building a GData client, I honestly wonder why I'd bother using DELETE and PUT methods at all given that X-HTTP-Method-Override is going to work in more cases/deployments."</p> </blockquote> <p>My take away from this is that if your web side supports this X-Method-Override header, then you can use this approach. The Don Box comments make me think it's fairly well supported, but I've not confirmed that yet.</p> <p>Another issue arises around being able to read the HTTP response headers. Again, from <a href="http://www.atnan.com/2007/6/11/can-as3-do-rest-or-not">a blog post in 2007 by Nathan de Vries</a>, we see this discussed. He followed up that blog post and discussion with his own comment:</p> <blockquote> <p>"The only change on the web front is that newer versions of the Flash Player (certainly those supplied with the Flex 3 beta) now support the responseHeaders property on instances of HTTPStatusEvent."</p> </blockquote> <p>I'm hoping that means it is a non-issue now.</p>
Add to right click application menu in taskbar in .NET <p>Most applications only have "Restore, Move, Size, Minimize, Maximize and Close", however <i>MS SQL</i> offers extra options "Help, Customize view". Along those lines, is it possible to add to the right click menu of an application in the task bar? </p> <p>Note: I'm <b>not</b> referring to an icon in the notification area next to the clock.</p>
<p><a href="http://pietschsoft.com/post/2008/03/Add-System-Menu-Items-to-a-Form-using-Windows-API.aspx">This article</a> gives you a walk through in C#!</p>
What is the best designed form you have ever seen? <p>I am looking for awesome forms that are easy and intuitive to use even though they may be overly complex. Multi-page is cool too. Screen shots of the forms would be way cool.</p>
<p><a href="http://www.google.com/" rel="nofollow">http://www.google.com/</a></p> <p>You want some screen shots? <a href="http://stuffthathappens.com/blog/2008/03/05/simplicity/" rel="nofollow">http://stuffthathappens.com/blog/2008/03/05/simplicity/</a></p>
How can you get the "real" HttpContext within an ASP.NET MVC application? <p>Unfortunately, I need to do this. I'm using ELMAH for my error log. Before I route to my error.aspx view, I have to grab the default ELMAH error log so I can log the exception. You used to be able to use </p> <pre><code>Elmah.ErrorLog.Default </code></pre> <p>However, this is now marked as obsolete. The compiler directs me to use the method</p> <pre><code>Elmah.ErrorLog.GetDefault(HttpContext context) </code></pre> <p>MVC's context is of type HttpContextBase, which enables us to mock it (YAY!). How can we deal with MVC-unaware libraries that require the old style HttpContext?</p>
<p>Try <code>System.Web.HttpContext.Current</code>. It should do the trick.</p> <p>Gets HTTP-specific information about an individual HTTP request.</p> <p><a href="https://msdn.microsoft.com/en-us/library/system.web.httpcontext.current%28v=vs.110%29.aspx">MSDN</a></p>
Printing leading 0's in C? <p>I'm trying to find a good way to print leading 0's, such as 01001 for a zipcode. While the number would be stored as 1001, what is a good way to do it?</p> <p>I thought of using either case statements/if then to figure out how many digits the number is and then convert it to an char array with extra 0's for printing but I can't help but think there may be a way to do this with the printf format syntax that is eluding me. </p>
<pre><code>printf("%05d", zipCode); </code></pre> <p></p>
php + unixODBC + DB2 + DESCRIBE = token not valid? <p>Code I am trying to run:</p> <pre><code>$query = "DESCRIBE TABLE TABLENAME"; $result = odbc_exec($h, $query); </code></pre> <p>The result:</p> <blockquote> <p>PHP Warning: odbc_exec(): SQL error: [unixODBC][IBM][iSeries Access ODBC Driver][DB2 UDB]SQL0104 - Token TABLENAME was not valid. Valid tokens: INTO., SQL state 37000 in SQLExecDirect in ...</p> </blockquote> <p>There were no other problems with SELECT, INSERT, UPDATE or DELETE queries on the same connection. Is this a syntax error?</p>
<p>The iSeries flavor of DB2 does not support the SQL DESCRIBE statement. Instead, you have to query the system table:</p> <pre><code>select * from qsys2.columns where table_schema = 'my_schema' and table_name = 'my_table' </code></pre>
Overriding namespaces in gSOAP <p>I am using <a href="http://gsoap2.sourceforge.net" rel="nofollow"><code>gSOAP</code></a> as a Web Service toolkit and have generated the stub and proxy classes through <code>soapcpp2</code> from multiple <code>WSDL</code>s all at once. Thus all the namespace bindings are in a single <code>.nsmap</code> file. </p> <p>Now the problem is that all the namespace bindings are being sent with all the method calls I make. The <code>HTTP POST</code> packet is unusually large and ugly. </p> <p>Is there a way to programatically override the namespace bindings ?</p>
<p>Check <code>soapcpp2</code> and its <code>-q</code> flag, it will help you.</p> <p>Other than that, the <code>-penv</code> flag will pack basic gSOAP-related methods within the executable, not including any service objects.</p> <p>Therefore the files generated with <code>-penv</code> can be shared across multiple namespaces, pertaining to different generated gSOAP Web Services.</p>
How does NUnit (and MSTest) handle tests that change static/shared variables? <p>I have some code that uses the shared gateway pattern to implement an inversion of control container. I have several hundred NUnit unit tests that exercises the code that uses this IOC. They all work (on my machine!) but I am concerned that these tests might fail under load. I seem to remember that NUnit (and MSTest) attempts to run tests in parallel on multiple threads (which would definitely trigger race conditions on the static/shared gateway) but I cannot find any documentation that says what actually happens. My experience is that NUnit seems to be running the tests sequencially. My question is, does NUnit (or MSTest) ever run unit tests in parallel? If so, under what conditions? And, can I turn this off via some sort of configuration option?</p>
<p><strong>Update:</strong></p> <p>Visual Studio 2010 introduced the ability to run tests in parallel.</p> <p>Here is a <a href="http://blogs.msdn.com/b/vstsqualitytools/archive/2009/12/01/executing-unit-tests-in-parallel-on-a-multi-cpu-core-machine.aspx" rel="nofollow">step by step article</a> about how to enable this.</p> <p><strong>MsTest:</strong><br> So according to David Williamson, from Microsoft Visual Studio Team System, on <a href="http://forums.microsoft.com/msdn/ShowPost.aspx?PostID=3894574&amp;SiteID=1" rel="nofollow">this post</a> in the MSDN forums:</p> <blockquote> <p>Tests absolutely do NOT run in parallel when run in VS or via mstest.exe. If they are run in a Load Test through VS then that is a different story. Basic execution, however, is always serial.</p> </blockquote> <p>Also, tests run using MsTest are each run using a different thread in order to ensure that you have a clean slate for each test. There is no way to disable this behavior.</p> <p><strong>NUnit:</strong><br> NUnit runs all tests on the same thread.</p>
Running many virtual machines on a single host <p>I have a need to run a relatively large number of virtual machines on a relatively small number of physical hosts. Each virtual machine isn't doing to much - each only needs to run essentially one basic network service - think SMTP or the like. Furthermore, the load on each is going to be extremely light. </p> <p>Unfortunately, the numbers are something like 100 virtual machines on 5 physical hosts. Each host is decent enough - core 2 with 2 gigs of ram and a 1tb disk. However, I know just taking a vmware image of ubuntu and throwing on that machine wont get me anywhere near 100 instances and would be something closer to 20.</p> <p>So, is there any hope for this ratio of images to hosts? Also, which implementation of virtual machine would be best suited for this purpose - ie has efficient overall usage of resources? We mostly use vmware here, but if there is a significant performance advantage that could be gained by switching to Xen or the like, I am sure we would consider it.</p> <p>Thank you in advance for your insights :)</p> <p>Note: We ended up using OpenVZ and it worked rather well. The default parameters for an ubuntu template let us run about 40 instances per machine.</p>
<p>there are three main fronts to make those fit:</p> <ol> <li><p>lower overhead. OpenVZ, Vserver, chroot, would be ideal if applicable. if you really need each instance be a real VM with it's own kernel, try KVM/Xen instead of VMWare. may be less mature, but you'll have a lot more flexibility.</p></li> <li><p>smaller guests. try Ubuntu JeOS, or roll your own with busybox</p></li> <li><p>share as much as possible between guests. try sharing a single R/O image with all the OS, and mount a small R/W image for each guest on /var, /home, /etc, etc</p></li> </ol>
Stuff in Windows Form Move When Maximized - C# <p>It's been a while since I've programmed a GUI program, so this may end up being super simple, but I can't find the solution anywhere online. </p> <p>Basically my problem is that when I maximize my program, all the things inside of the window (buttons, textboxes, etc.) stay in the same position in the window, which results in a large blank area near the bottom and right side. </p> <p>Is there a way of making the the elements in the program to stretch to scale?</p>
<p>You want to check and properly set the Anchor and Dock properties on each control in the Form. The Anchor property on a control tells which sides of the form (top, bottom, left, right) the control is 'anchored' to. When the form is resized, the distance between the control and its anchors will stay the same. This lets you make a control stay in the bottom right corner for example.</p> <p>The Dock property instructs the control to fill the entire parent form or to fill one side of it (again top, bottom, left or right).</p>
php Access violation <p>I am trying to install Php on Vista (IIS 7). The installation and configuration seems to be fine. Pretty much followed everything mentioned in <a href="http://blogs.iis.net/bills/archive/2006/09/19/How-to-install-PHP-on-IIS7-_2800_RC1_2900_.aspx" rel="nofollow">http://blogs.iis.net/bills/archive/2006/09/19/How-to-install-PHP-on-IIS7-_2800_RC1_2900_.aspx</a></p> <p>I can even bring up a test.php which is basically and can also connect to mysql db through code. But when I try to bring up some other php page like drupal's index page or phpmyadmin index page, it brings up a Php access violation message. </p> <p>Any clue whats happening? Also is there some tracing/diagnositic tool for php to trace whats happenign on the webserver. </p>
<p>In your PHP.INI file, try to comment all the extensions lines and restart IIS. Take note that MySql will no longer work. Do some tests.</p> <p>If it's successfull, uncomment back the mySql line. Do some tests.</p> <p>If it's unsucessfull, them I can't help you more. I suspect that's a loaded extension causing the error. You have to find which one...</p> <p>Hope this helps.</p> <p>vIceBerg</p>
XML Parsing Error: SYSTEM or PUBLIC, the URI is missing <p>I am parsing an RSS feed from the following URL:</p> <p><a href="http://rss.sciam.com/ScientificAmerican-Global?format=xml" rel="nofollow">http://rss.sciam.com/ScientificAmerican-Global?format=xml</a></p> <pre><code>// $xml_text is filled with the contents read from the URL $xml_parser = xml_parser_create(); $res = xml_parse($xml_parser, $xml_text); if (!$res) { $error = xml_error_string(xml_get_error_code($xml_parser)). " at line ". xml_get_current_line_number($xml_parser); } // $error contains: "SYSTEM or PUBLIC, the URI is missing at line 1" </code></pre> <p><a href="http://FeedValidator.org" rel="nofollow">FeedValidator.org</a> says this is a good feed.</p> <p>How can I get PHP's XML parser to work around this error?</p> <p><strong>EDIT</strong>: It looks like they are redirecting this feed to another location based on the user-agent. My PHP script is not getting the correct feed.</p>
<p>The code works for me, you must be getting the text wrong.</p>
Persistent storage of encrypted data using .Net <p>I need to store encrypted data (few small strings) between application runs. I do not want the user to provide a passphrase every time (s)he launches the application. I.e. after all it goes down to storing securely the encryption key(s).</p> <p>I was looking into RSACryptoServiceProvider and using PersistentKeyInCsp, but I'm not sure how it works. Is the key container persistent between application runs or machine restarts? If yes, is it user specific, or machine specific. I.e. if I store my encrypted data in user's roaming profile, can I decrypt the data if the user logs on a different machine?</p> <p>If the above does not work, what are my options (I need to deal with roaming profiles).</p>
<p>The Data Protection API (DPAPI) does exactly what you want. It provides symmetric encryption of arbitrary data, using the credentials of the machine or (better) the user, as the encryption key. You don't have to worry about managing the keys; Windows takes care of that for you. If the user changes his password, Windows will re-encrypt the data using the user's new password.</p> <p>DPAPI is exposed in .NET with the System.Security.Cryptography.ProtectedData class:</p> <pre><code>byte[] plaintextBytes = GetDataToProtect(); byte[] encodedBytes = ProtectedData.Protect(plaintextBytes, null, DataProtectionScope.CurrentUser); </code></pre> <p>The second parameter of the Protect method is an optional entropy byte array, which can be used as an additional application-specific "secret".</p> <p>To decrypt, use the ProtectedData.Unprotect call:</p> <pre><code>byte[] encodedBytes = GetDataToUnprotect(); byte[] plaintextBytes = ProtectedData.Unprotect(encodedBytes, null, DataProtectionScope.CurrentUser); </code></pre> <p>DPAPI works correctly with roaming profiles (as described <a href="http://support.microsoft.com/kb/309408">here</a>), though you'll need to store the encrypted data in a place (network share, IsolatedStorage with <a href="http://msdn.microsoft.com/en-us/library/zzdt0e7f%28VS.71%29.aspx">IsolatedStorageScope.Roaming</a>, etc.) that your various machines can access.</p> <p>See the ProtectedData class in MSDN for more information. There's a DPAPI white paper <a href="http://msdn.microsoft.com/en-us/library/ms995355.aspx">here</a>, with more information than you'd ever want.</p>
Recommended gcc warning options for C <p>Other than -Wall what other warnings have people found useful?</p> <p><a href="http://gcc.gnu.org/onlinedocs/gcc-4.3.2/gcc/Warning-Options.html">http://gcc.gnu.org/onlinedocs/gcc-4.3.2/gcc/Warning-Options.html</a></p>
<p>I routinely use:</p> <pre><code> gcc -m64 -std=c99 -pedantic -Wall -Wshadow -Wpointer-arith -Wcast-qual \ -Wstrict-prototypes -Wmissing-prototypes </code></pre> <p>This set catches a lot for people unused to it (people whose code I get to compile with those flags for the first time); it seldom gives me a problem (though -Wcast-qual is occasionally a nuisance).</p>
LINQ query with multiple aggregates <p>How would I create the equivalent Linq To Objects query?</p> <pre><code>SELECT MIN(CASE WHEN p.type = "In" THEN p.PunchTime ELSE NULL END ) AS EarliestIn, MAX(CASE WHEN p.type = "Out" THEN p.PunchTime ELSE NULL END ) AS LatestOUt FROM Punches p </code></pre>
<p>Single enumeration yielding both min and max (and any other aggregate you want to throw in there). This is much easier in vb.net.</p> <p>I know this doesn't handle the empty case. That's pretty easy to add.</p> <pre><code> List&lt;int&gt; myInts = new List&lt;int&gt;() { 1, 4, 2, 0, 3 }; var y = myInts.Aggregate( new { Min = int.MaxValue, Max = int.MinValue }, (a, i) =&gt; new { Min = (i &lt; a.Min) ? i : a.Min, Max = (a.Max &lt; i) ? i : a.Max }); Console.WriteLine("{0} {1}", y.Min, y.Max); </code></pre>
Capturing video out of an OpenGL window in Windows <p>I am supposed to provide my users a really simple way of capturing video clips out of my OpenGL application's main window. I am thinking of adding buttons and/or keyboard shortcuts for starting and stopping the capture; when starting, I could ask for a filename and other options, if any. It has to run in Windows (XP/Vista), but I also wouldn't like to close the Linux door which I've so far been able to keep open.</p> <p>The application uses OpenGL fragment and shader programs, the effects due to which I absolutely need to have in the eventual videos.</p> <p>It looks to me like there might be even several different approaches that could potentially fulfill my requirements (but I don't really know where I should start):</p> <ul> <li><p>An encoding library with functions like startRecording(filename), stopRecording, and captureFrame. I could call captureFrame() after every frame rendered (or every second/third/whatever). If doing so makes my program run slower, it's not really a problem.</p></li> <li><p>A standalone external program that can be programmatically controlled from my application. After all, a standalone program that can <em>not</em> be controlled almost does what I need... But as said, it should be really simple for the users to operate, and I would appreciate seamlessness as well; my application typically runs full-screen. Additionally, it should be possible to distribute as part of the installation package for my application, which I currently prepare using NSIS.</p></li> <li><p>Use the Windows API to capture screenshots frame-by-frame, then employ (for example) one of the <a href="http://stackoverflow.com/questions/93954/how-to-programatically-create-videos">libraries mentioned here</a>. It seems to be easy enough to find examples of how to capture screenshots in Windows; however, I would love a solution which doesn't really force me to get my hands super-dirty on the WinAPI level.</p></li> <li><p>Use OpenGL to render into an offscreen target, then use a library to produce the video. I don't know if this is even possible, and I'm afraid it might not be the path of least pain anyway. In particular, I would not like the actual rendering to take a different execution path depending on whether video is being captured or not. Additionally, I would avoid anything that might decrease the frame rate in the normal, non-capture mode.</p></li> </ul> <p>If the solution were free in either sense of the word, then that would be great, but it's not really an absolute requirement. In general, the less bloat there is, the better. On the other hand, for reasons beyond this question, I cannot link in any GPL-only code, unfortunately.</p> <p>Regarding the file format, I cannot expect my users to start googling for any codecs, but as long as also <em>displaying</em> the videos is easy enough for a basic-level Windows user, I don't really care what the format is. However, it would be great if it were possible to control the compression quality of the output.</p> <p>Just to clarify: I <em>don't</em> need to capture video from an external device like camcorder, nor am I really interested in mouse movements, even though getting them does not harm either. There are no requirements regarding audio; the application makes no noise whatsoever.</p> <p>I write C++ using Visual Studio 2008, for this very application also taking benefit of GLUT and GLUI. I have a solid understanding regarding C++ and linking in libraries and that sort of stuff, but on the other hand OpenGL is quite new for me: so far, I've really only learnt the necessary bits to actually get my job done.</p> <p>I don't need a solution super-urgently, so feel free to take your time :)</p>
<p>There are two different questions here - how to grab frames from an OpenGL application, and how to turn them into a movie file.</p> <p>The first question is easy enough; you just grab each frame with glReadPixels() (via a PBO if you need the performance).</p> <p>The second question is a little harder since the cross-platform solutions (ffmpeg) tend to be GPL'd or LGPL'd. Is LGPL acceptable for your project? The Windows way of doing this (DirectShow) is a bit of a headache to use.</p> <p><strong>Edit:</strong> Since LGPL is ok and you can use ffmpeg, see <a href="http://www.irisa.fr/texmex/people/dufouil/ffmpegdoxy/apiexample_8c-source.html#l00190" rel="nofollow">here</a> for an example of how to encode video.</p>
Is there a way to handle a variable number of parameters in a template class? <p>I have a set of callback classes that I use for handling callbacks with variable numbers of parameters. Right now I have about 6 different instances of it to handle differing numbers of arguments. Is there a way to make one instance than can handle a variable number of arguments?? Ultimately I would love to have each parameter be a POD type or a class pointer, or a struct pointer. Any ideas?</p> <pre><code>template &lt;class T&gt; class kGUICallBackPtr { public: kGUICallBackPtr() {m_obj=0;m_func=0;} void Set(void *o,void (*f)(void *,T *)); inline void Call(T *i) {if(m_func) m_func(m_obj,i);} inline bool IsValid(void) {return (m_func!=0);} private: void *m_obj; void (*m_func)(void *,T *); }; template &lt;class T,class U&gt; class kGUICallBackPtrPtr { public: kGUICallBackPtrPtr() {m_obj=0;m_func=0;} void Set(void *o,void (*f)(void *,T *,U *)); inline void Call(T *i, U *j) {if(m_func) m_func(m_obj,i,j);} inline bool IsValid(void) {return (m_func!=0);} private: void *m_obj; void (*m_func)(void *,T *,U *j); }; </code></pre>
<p>Not yet in the language itself but C++0x will have support for <a href="http://en.wikipedia.org/wiki/C%2B%2B0x#Variadic_templates" rel="nofollow">variadic templates</a>.</p>
How to tell when an MXML component has totally finished creation? <p>An MXML component can be quite complex, containing many nested controls, including asynchronously loaded content such as Image/SWFLoader.</p> <p>Is there one event I can watch for on my component that will only be raised when every control and sub-component has loaded, including SWFs and Images?</p>
<p>CreationComplete will NOT do the trick if you are talking about loading swf content or anything really external like that. CreationComplete gets fired when the MXML components have been laid out as defined in MXML (IE nested components, buttons, boxes, canvasses, etc.), so content that needs to get loaded externally (an image, a swf) does not count.</p> <p>What you need to do is keep track of everything that you're waiting for and fire off a custom event once all of those elements have loaded.</p> <p>One possible hackish way to do it would be to listen for whatever load complete event is relevant for each element, then have them call back to the same function that increments a value equal to the number of components you're waiting for. This means you have to pay more attention if you're modifying it, but it also means you don't have to check a boolean for every element that needs to load (IE "if (image1Loaded &amp;&amp; image2Loaded &amp;&amp; swfLoaded)" etc.)</p>
What does `$hash{$key} |= {}` do in Perl? <p>I was wrestling with some Perl that uses hash references.</p> <p>In the end it turned out that my problem was the line:</p> <pre><code>$myhash{$key} |= {}; </code></pre> <p>That is, "assign $myhash{$key} a reference to an empty hash, unless it already has a value".</p> <p>Dereferencing this and trying to use it as a hash reference, however, resulted in interpreter errors about using a string as a hash reference.</p> <p>Changing it to:</p> <pre><code>if( ! exists $myhash{$key}) { $myhash{$key} = {}; } </code></pre> <p>... made things work.</p> <p>So I don't have a <em>problem</em>. But I'm curious about what was going on.</p> <p>Can anyone explain?</p>
<p>Perl has shorthand assignment operators. The <code>||=</code> operator is often used to set default values for variables due to Perl's feature of having logical operators return the last value evaluated. The problem is that you used <code>|=</code> which is a <em>bitwise</em> or instead of <code>||=</code> which is a <em>logical</em> or.</p> <p>As of Perl 5.10 it's better to use <code>//=</code> instead. <code>//</code> is the logical defined-or operator and doesn't fail in the corner case where the current value is defined but false.</p>
How do I fix connection manager error that causes the package to fail in production? <p>I have created an SSIS package and it works great on my dev machine. But, when I try to run it on the production server, it errors out on me.</p> <p>Here is the error:</p> <pre><code>Error: The AcquireConection method call to the connection manager "DestinationConnectionOLEDB" failed with error code 0xC0202009. </code></pre> <p>I have figured out the cause, but am not sure how to get it fixed. The password isn't in the connection string. But I have set the password in the SSIS project. For some reason though, when I deploy and run this on the production server, it won't run since the password isn't part of the connection string.</p> <p>Is there some setting in the SSIS project that I need to change in order to get this to work right?</p> <p>Thanks.</p>
<p>Disable the password by setting the ProtectionLevel in the package properties to DontSaveSensitive.</p> <p>I also recommend moving the connection string to a package variable and make an expression on the connection. Enable package configurations.</p> <p>Then you are free to change the connection and to use integrated security or not without changing the package. You can either put the connection string in the configuration or then provide it on the command line.</p>
Novell client and windows SSO <p>Does the novell gina install a specific security provider that can be used via SSPI? Does it have to called out specifically or is SPNEGO good enough? Will that support single sign on if the novell gina is installed on the remote server?</p>
<p>I do not know SSPI or the low level things, but I think the way the Novell GINA works, is less about Single Sign On, and more about passing through the credentails. </p> <p>That is, when a physical user (as opposed to a programmatic user) logs in, the Novell Gina uses the credentials and passes them on to the Windows Gina, and any other Gina in line to receive them, until all are done, and everything is logged in.</p>
Separator attribute not working in SolPartMenu on DotNetNuke skin.ascx <p>I can get rootmenuitemlefthtml and rootmenuitemrighthtml to emit but not separator. Tried CDATA wrapping and setting SeparatorCssClass. I just want pipes between root menu items.</p> <pre><code>&lt;dnn:SOLPARTMENU runat="server" id="dnnSOLPARTMENU" Separator="&lt;![CDATA[|]]&gt;" SeparatorCssClass="MainMenu_SeparatorCSS" usearrows="false" userootbreadcrumbarrow="false" usesubmenubreadcrumbarrow="false" rootmenuitemlefthtml="&amp;nbsp;&amp;lt;span&amp;gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;" rootmenuitemrighthtml="&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;lt;/span&amp;gt;" rootmenuitemcssclass="rootmenuitem" rootmenuitemselectedcssclass="rootmenuitemselected" rootmenuitembreadcrumbcssclass="rootmenuitembreadcrumb" submenucssclass="submenu" submenuitemselectedcssclass="submenuitemselected" submenuitembreadcrumbcssclass="submenuitembreadcrumb" CSSNodeSelectedRoot="rootmenuitembreadcrumb" CSSNodeSelectedSub="submenuitembreadcrumb" MouseOverAction="False" MouseOutHideDelay="0" delaysubmenuload="true" level="Root" /&gt; </code></pre>
<p>While not a direct answer - you might want to shift to the DotNetNuke menu rather than using SolPart. SolPart is no longer officially supported and development work on this menu ceased almost two years ago. Jon Henning, the author of SolPart, wrote the DotNetNuke menu from the ground up and tried to address many of the shortcomings in the original SolPart menu.</p>
Dynamic SQL - Search Query - Variable Number of Keywords <p>We are trying to update our classic asp search engine to protect it from SQL injection. We have a VB 6 function which builds a query dynamically by concatenating a query together based on the various search parameters. We have converted this to a stored procedure using dynamic sql for all parameters except for the keywords.</p> <p>The problem with keywords is that there are a variable number words supplied by the user and we want to search several columns for each keyword. Since we cannot create a separate parameter for each keyword, how can we build a safe query?</p> <p>Example</p> <p>@CustomerId AS INT @Keywords AS NVARCHAR(MAX)</p> <p>@sql = 'SELECT event_name FROM calendar WHERE customer_id = @CustomerId '</p> <p>--(loop through each keyword passed in and concatenate)</p> <p>@sql = @sql + 'AND (event_name LIKE ''%' + @Keywords + '%'' OR event_details LIKE ''%' + @Keywords + '%'')'</p> <p>EXEC sp_executesql @sql N'@CustomerId INT, @CustomerId = @CustomerId</p> <p>What is the best way to handle this and maintaining protection from SQL injection? </p>
<p>You may not like to hear this, but it might be better for you to go back to dynamically constructing your SQL query in code before issuing against the database. If you use parameter placeholders in the SQL string you get the protection against SQL injection attacks.</p> <p>Example:</p> <pre><code>string sql = "SELECT Name, Title FROM Staff WHERE UserName=@UserId"; using (SqlCommand cmd = new SqlCommand(sql)) { cmd.Parameters.Add("@UserId", SqlType.VarChar).Value = "smithj"; </code></pre> <p>You can build the SQL string depending on the set of columns you need to query and then add the parameter values once the string is complete. This is a bit of a pain to do, but I think it is much easier than having really complicated TSQL which unpicks lots of possible permutations of possible inputs.</p>
Help me understand how QA works in Scrum <p>Apparently we use the Scrum development methodology. Here's generally how it goes: </p> <p>Developers thrash around trying to accomplish their tasks. Generally the tasks take most of the sprint to complete. QA pesters Dev to release something they can test, Dev finally throws some buggy code out to QA a day or two before the sprint ends and spends the rest of the time fixing bugs that QA is finding. QA can never complete the tasks on time, sprints are rarely releasable on time, and Dev and QA have a miserable few days at the end of the sprint.</p> <p>How is scrum supposed to work when releasable Dev tasks take up most of the sprint? </p> <p>Thank you everyone for your part in the discussion. As it's a pretty open-ended question, it doesn't seem like there is one "answer" - there are many good suggestions below. I'll attempt to summarize some of my "take home" points and make some clarifications.</p> <p>(BTW - Is this the best place to put this or should I have put it in an 'answer'?)</p> <p>Points to ponder / act on:</p> <ul> <li>Need to ensure that developer tasks are as small (granular) as possible.</li> <li>Sprint length should be appropriately based on average task length (e.g. sprint with 1 week tasks should be at least 4 weeks long)</li> <li>Team (including QA) needs to work on becoming more accurate at estimating.</li> <li>Consider doing a separate QA sprint in parallel but off-set if that works best for the team</li> <li>Unit testing!</li> </ul>
<p>My opinion is that you have an estimation problem. It seems that the time to test each feature is missing, and only the building part is being considered when planning the sprint. </p> <p>I'm not saying it is an easy problem to solve, because it is more common than anything. But things that could help are:</p> <ul> <li><p>Consider QA as members of the dev team, and include them in the sprint planning and estimating more closely.</p></li> <li><p>'Releasable Dev tasks' should not take up most of the sprint. Complete working features should. Try to gather metrics about dev time vs QA time for each kind of task and use those metrics when estimating future sprints.</p></li> <li><p>You might need to review your backlog to see if you have very coarse grained features. Try to divide them in smaller tasks that could be easily estimated and tested.</p></li> </ul> <p>In summary, it seems that your team hasn't found what its real velocity is because there are tasks that are not being considered when doing the estimation and planning for the sprint.</p> <p>But in the end, estimation inaccuracy is a tough project management issue that you find in agile-based or waterfall-based projects. Good luck.</p>
What is the "< >" syntax within C# <p>I have been learning about the basics of C# but haven't come across a good explanation of what this is:</p> <pre><code>var l = new List&lt;string&gt;(); </code></pre> <p>I don't know what the <code>&lt;string&gt;</code> is doing or if it's the <code>List</code> that is doing the magic. I have also seen objects been thrown within the <code>&lt; &gt;</code> tags.</p> <p>Can someone explain this to me with examples, please?</p>
<p>That is the generic syntax for C#.</p> <p>The basic concept is that it allows you to use a Type placeholder and substitute the actual real type in at compile time.</p> <p>For example, the old way:</p> <pre><code>ArrayList foos = new Arraylist(); foos.Add("Test"); </code></pre> <p>worked by making ArrayList store a list of System.Objects (The base type for all things .NET).</p> <p>So, when adding or retrieving an object from the list, The CLR would have to cast it to object, basically what really happens is this:</p> <pre><code>foos.Add("Test" as System.Object); string s = foos[1] as String. </code></pre> <p>This causes a performance penalty from the casting, and its also unsafe because I can do this:</p> <pre><code>ArrayList listOfStrings = new ArrayList(); listOfStrings.Add(1); listOfStrings.Add("Test"); </code></pre> <p>This will compile just fine, even though I put an integer in listOfStrings.</p> <p>Generics changed all of this, now using Generics I can declare what Type my collection expects:</p> <pre><code>List&lt;int&gt; listOfIntegers = new List&lt;int&gt;(); List&lt;String&gt; listOfStrings = new List&lt;String&gt;(); listOfIntegers.add(1); // Compile time error. listOfIntegers.add("test"); </code></pre> <p>This provides compile-time type safety, as well as avoids expensive casting operations.</p> <p>The way you leverage this is pretty simple, though there are some advanced edge cases. The basic concept is to make your class type agnostic by using a type placeholder, for example, if I wanted to create a generic "Add Two Things" class.</p> <pre><code>public class Adder&lt;T&gt; { public T AddTwoThings(T t1, T t2) { return t1 + t2; } } Adder&lt;String&gt; stringAdder = new Adder&lt;String&gt;(); Console.Writeline(stringAdder.AddTwoThings("Test,"123")); Adder&lt;int&gt; intAdder = new Adder&lt;int&gt;(); Console.Writeline(intAdder.AddTwoThings(2,2)); </code></pre> <p>For a much more detailed explanation of generics, I can't recommend enough the book CLR via C#.</p>
FIPS compliant password encryption for .NET <p>I've working on a WinForms in VB.NET (3.5) application that requires the user to enter domain administrator credentials. To make things easier on the user, they should only have to enter the user name and password once, and then just rely on my app to save these credentials. I'd like to save these credentials with the other user settings, but for security reasons, the password needs to be encrypted.</p> <p>What's an easy way to encrypt and decrypt this password? I'm wanting the encryption method to be FIPS compatible. The methods I've tried so far result in this exception:</p> <blockquote> <p>System.InvalidOperationException: This implementation is not part of the Windows Platform FIPS validated cryptographic algorithms.</p> </blockquote>
<p>Look into the Data Protection API (DPAPI), which is FIPS compliant (as far as I can tell; you can review the evaluation <a href="http://technet.microsoft.com/en-us/library/cc750357.aspx" rel="nofollow">here</a>).</p> <p>DPAPI is exposed in .NET 2.0 and greater with the System.Security.Cryptography.ProtectedData class. It uses the user's current credentials as the encryption key. See my more complete answer <a href="http://stackoverflow.com/questions/154430/persistent-storage-of-encrypted-data-using-net">here</a>.</p>
LINQ Submit Changes not submitting changes <p>I'm using LINQ to SQL and C#. I have two LINQ classes: User and Network. </p> <p>User has UserID (primary key) and NetworkID</p> <p>Network has NetworkID (primary key) and an AdminID (a UserID)</p> <p>The following code works fine:</p> <pre><code>user.Network.AdminID = 0; db.SubmitChanges(); </code></pre> <p>However, if I access the AdminID before making the change, the change never happens to the DB. So the following doesn't work:</p> <pre><code>if(user.Network.AdminID == user.UserID) { user.Network.AdminID = 0; db.SubmitChanges(); } </code></pre> <p>It is making it into the if statement and calling submit changes. For some reason, the changes to AdminID never make it to the DB. No error thrown, the change just never 'takes'.</p> <p>Any idea what could be causing this?</p> <p>Thanks.</p>
<p>I just ran a quick test and it works fine for me. </p> <p>I hate to ask this, but are you sure the if statement ever returns true? It could be you're just not hitting the code which changes the value.</p> <p>Other than that we might need more info. What are the properties of that member? Have you traced into the set statement to ensure the value is getting set before calling SubmitChanges? Does the Linq entity have the new value after SubmitChanges? Or do both the database AND the Linq entity fail to take the new value?</p> <p>In short, that code should work... so something else somewhere is probably wrong.</p>
OS-independent API to monitor file system? <p>I would like to experiment with ideas about distributed file synchronization/replication. To make it efficient when the user is working, I would like to implement some kind of daemon to monitor changes in some directory (e.g. /home/user/dirToBeMonitored or c:\docs and setts\user\dirToBeMonitored). So, I could be able to know which filename was added/changed/deleted at every time (or within a reasonable interval).</p> <p>Is this possible with any high-medium level language?. Do you know some API (and in which language?) to do this?</p> <p>Thanks.</p>
<p>The APIs are totally different for <a href="http://msdn.microsoft.com/en-us/library/aa365261(VS.85).aspx">Windows</a>, <a href="http://en.wikipedia.org/wiki/Inotify">Linux</a>, <a href="http://en.wikipedia.org/wiki/FSEvents">Mac OS X</a>, and any other <a href="http://en.wikipedia.org/wiki/File_Alteration_Monitor">Unix</a> you can name, it seems. I don't know of any cross-platform library that handles this in a consistent way.</p>
How can I tell when .Net System.Diagnostics.Process ran sucessfully or failed? <p>I'm writing a scheduler or sorts. It's basically a table with a list of exes (like "C:\a.exe") and a console app that looks at the records in the table every minute or so and runs the tasks that haven't been run yet.</p> <p>I run the tasks like this:</p> <pre><code>System.Diagnostics.Process p = new System.Diagnostics.Process(); p.StartInfo.UseShellExecute = false; p.StartInfo.FileName = someExe; // like "a.exe" p.Start(); </code></pre> <p>How can I tell if a particular task failed? For example what if a.exe throws an unhandled exception? I'd like the above code to know when this happens and update the tasks table with something like "the particular task failed" etc.</p> <p>How can I do this?</p> <p>p.s. I'm not using the Sql Agent or the Windows Scheduler because someone else told me not to. He has more "experience" so I'm basically just following orders. Feel free to suggest alternatives.</p> <p>Thanks!</p>
<p>You can catch the <a href="http://msdn.microsoft.com/en-us/library/system.componentmodel.win32exception.aspx">Win32Exception</a> to check if <a href="http://msdn.microsoft.com/en-us/library/e8zac0ca.aspx">Process.Start()</a> failed due to the file not existing or execute access is denied.</p> <p>But you can not catch exceptions thrown by the processes that you create using this class. In the first place, the application might not be written in .NET so there might not be a concept of exception at all.</p> <p>What you can do is check on the <a href="http://msdn.microsoft.com/en-us/library/system.diagnostics.process.exitcode.aspx">ExitCode</a> of the application or read the <a href="http://msdn.microsoft.com/en-us/library/system.diagnostics.process.standardoutput.aspx">StandardOutput</a> and <a href="http://msdn.microsoft.com/en-us/library/system.diagnostics.process.standarderror.aspx">StandardError</a> streams to check whether error messages are being posted.</p>