input
stringlengths
51
42.3k
output
stringlengths
18
55k
How are you generating tests from specifications? <p>I came across a printed <a href="http://www.eiffel.com/general/column/2008/02.html" rel="nofollow">article by Bertrand Meyer</a> where he states that tests can be generated from specifications. My development team does nothing like this, but it sounds like a good technique to consider. How are you generating tests from specifications? How would you describe the success your having in discovering program faults via this method?</p>
<p>This might be a reference to <a href="http://rspec.info/" rel="nofollow">RSpec</a>, which is a really clever way of developing tests as a series of requirements. I'm still getting used to it, but it's been very handy in both defining what I need to do and then ensuring I do it.</p>
SQL1159 Initialization error with DB2 .NET Data Provider, reason code 7, tokens 9.5.0.DEF.2, SOFTWARE\IBM\DB2\InstalledCopies <p>I am trying to get the DB2 data provider from a 32-bit .Net application to connect to DB2 running as a 32-bit application on Vista 64 (is that confusing enough yet)? Unfortunately, I am getting the following error:</p> <blockquote> <p>SQL1159 Initialization error with DB2 .NET Data Provider, reason code 7, tokens 9.5.0.DEF.2, SOFTWARE\IBM\DB2\InstalledCopies</p> </blockquote> <p>There are several <a href="http://www-128.ibm.com/developerworks/forums/thread.jspa?threadID=207638&amp;tstart=45" rel="nofollow">IBM forum posts</a> mentioning it, but little useful guidance. Has anyone experienced this before? Or do you have better ideas for fixing it?</p>
<p>Are you required to have it run as x86? I had similar issues with web apps under Visual Studio's dev web server (which is x86), but switching over to IIS (x64) worked for me. Since I was deploying to IIS x64, I called it a day at that point.</p> <p>I tried tracing with Filemon and Regmon, but didn't get any denied or missing keys errors. If I were to look again, I'd check HKLM\Software\WOW6432Node, guessing that the installer writes to the x64 HKLM\Software node, but not the x86 one.</p>
Stop the taskbar flashing <p>I know I can programatically make the taskbar item for a particular window start flashing when something changes, but is there any way I can stop it from flashing either programatically after a certain period of time or at least is there a keyboard shortcur I can give to my users to somehow stop the flashing?</p>
<p>The <a href="http://msdn.microsoft.com/en-us/library/ms679347%28VS.85%29.aspx" rel="nofollow">FlashWindowEx</a> function which controls the flashing takes a <a href="http://msdn.microsoft.com/en-us/library/ms679348%28VS.85%29.aspx" rel="nofollow">FLASHWINFO</a> struct which has a uCount field to control how many times it flashes. Also, a possible value for the dwFlags field is FLASHW_STOP to cause the flashing to stop.</p> <p>EDIT: Forgot was a C# tagged question ... so <a href="http://www.pinvoke.net/default.aspx/user32.FlashWindowEx" rel="nofollow">P/Invoke goodness found here</a>.</p>
Why is pagination so resource-expensive? <p>It's one of those things that seems to have an odd curve where the more I think about it, the more it makes sense. To a certain extent, of course. And then it doesn't make sense to me at all.</p> <p>Care to enlighten me?</p>
<p>Because in most cases you've got to sort your results first. For example, when you search on Google, <a href="http://www.google.com.au/search?hl=en&amp;safe=off&amp;q=google&amp;start=1000&amp;sa=N" rel="nofollow">you can view only up to 100 pages of results</a>. They don't bother sorting by page-rank beyond 1000 websites for given keyword (or combination of keywords).</p> <p><strong>Pagination is fast. Sorting is slow.</strong></p>
What is the best way to package and distribute an Excel application <p>I've writen an Excel-based, database reporting tool. Currentely, all the VBA code is associated with a single XLS file. The user generates the report by clicking a button on the toolbar. Unfortunately, unless the user has saved the file under another file name, all the reported data gets wiped-out.</p> <p>When I have created similar tools in Word, I can put all the code in a template (.dot) file and call it from there. If I put the template file in the Office startup folder, it will launch everytime I start Word. Is there a similar way, to package and distribute my code in Excel? I've tried using Add-ins, but I didn't find a way to call the code from the application window.</p>
<p>Simply move your code into an Excel Addin (XLA) - this gets loaded at startup (assuming it's in the %AppData%\Microsoft\Excel\XLSTART folder) but if it's a addin, not a workbook, then only your macros and defined startup functions will be loaded.</p> <p>If the functions depend on a spreadsheet itself, then you might want to use a combination of templates and addins.</p> <p>I'm distributing part of an application like this, we have addins for Word, Excel and Powerpoint (XLA, PPA, DOT) and also Office 2007 'ribbon' versions (DOTM, XLAM and PPAM)</p> <p>The addin startup code creates toolbar buttons if they're not found, this means in any workbook/document/etc they can simply hit the toolbar button to run our code (we have two action buttons and one button that displays a settings dialog)</p> <p>Templates aren't really the way to go for VBA code, Addins are definitely the way to go...</p> <p>So to load the toolbars on startup we're using something like.. (checking to see if toolbar exists though - code will run for each worksheet that is opened, but toolbars are persistent for the user session)</p> <pre><code>Public Sub Workbook_Open() ' startup code / add toolbar / load saved settings, etc. End Sub </code></pre> <p>hope that helps :)</p>
Suppress NTLM dialog box after unauthorized request <p>In a recent sharepoint project, I implemented an authentication webpart which should replace the NTLM authentication dialog box. It works fine as long as the user provides valid credentials. Whenever the user provides invalid credentials, the NTLM dialog box pops up in Internet Explorer.</p> <p>My Javascript code which does the authentication via XmlHttpRequest looks like this:</p> <pre><code>function Login() { var request = GetRequest(); // retrieves XmlHttpRequest request.onreadystatechange = function() { if (this.status == 401) { // unauthorized request -&gt; invalid credentials // do something to suppress NTLM dialog box... // already tried location.reload(); and window.location = &lt;url to authentication form&gt;; } } request.open("GET", "http://myServer", false, "domain\\username", "password"); request.send(null); } </code></pre> <p>I don't want the NTLM dialog box to be displayed when the user provides invalid credentials. Instead the postback by the login button in the authentication form should be executed. In other words, the browser should not find out about my unauthorized request.</p> <p>Is there any way to do this via Javascript?</p>
<p><a href="http://stackoverflow.com/users/2199/mark-brackett">Mark</a>'s comment is correct; The NTLM auth prompt is triggered by a 401 response code and the presence of NTLM as the first mechanism offered in the WWW-Authenticate header (Ref: <a href="http://curl.haxx.se/rfc/ntlm.html" rel="nofollow">The NTLM Authentication Protocol</a>).</p> <p>I'm not sure if I understand the question description correctly, but I think you are trying to wrap the NTLM authentication for SharePoint, which means you don't have control over the server-side authentication protocol, correct? If you're not able to manipulate the server side to avoid sending a 401 response on failed credentials, then you will not be able to avoid this problem, because it's part of the (client-side) spec:</p> <h3><a href="http://www.w3.org/TR/2006/WD-XMLHttpRequest-20060619/" rel="nofollow">The XMLHttpRequest Object</a></h3> <blockquote> <p>If the UA supports HTTP Authentication [RFC2617] it SHOULD consider requests originating from this object to be part of the protection space that includes the accessed URIs and send Authorization headers and handle 401 Unauthorised requests appropriately. if authentication fails, UAs should prompt the users for credentials.</p> </blockquote> <p>So the spec actually calls for the browser to prompt the user accordingly if any 401 response is received in an XMLHttpRequest, just as if the user had accessed the URL directly. As far as I can tell the only way to really avoid this would be for you to have control over the server side and cause 401 Unauthorized responses to be avoided, as Mark mentioned. </p> <p>One last thought is that you may be able to get around this using a proxy, such a separate server side script on another webserver. That script then takes a user and pass parameter and checks the authentication, so that the user's browser isn't what's making the original HTTP request and therefore isn't receiving the 401 response that's causing the prompt. If you do it this way you can find out from your "proxy" script if it failed, and if so then prompt the user again until it succeeds. On a successful authentication event, you can simply fetch the HTTP request as you are now, since everything works if the credentials are correctly specified.</p>
Can someone point me to some guides for WPF <p>I am having trouble finding good guides for WPF.<br /> I have experience in C# and .NET but I don't know anything about WPF except for the regular marketing-ish description of the technology as a whole.<br /> Can anyone point me to a good beginner's tutorial/guide on WPF.</p>
<p>Scott Hanselmann has blogged extensively about his experience in learning WPF by creating his 'BabySmash' windows application. All the source code is on codeplex and he has many blog articles describing his progress.</p> <p><a href="http://www.hanselman.com/blog/IntroducingBabySmashAWPFExperiment.aspx" rel="nofollow">Initial BabySmash article</a></p> <p><a href="http://www.codeplex.com/babysmash/SourceControl/ListDownloadableCommits.aspx" rel="nofollow">Codeplex source</a></p> <p><a href="http://www.hanselman.com/babysmash/" rel="nofollow">BabySmash website</a></p>
Stopping MSI from launching an EXE in the SYSTEM context <p>I've got a problem here with an MSI deployment that I'm working on (using <a href="http://en.wikipedia.org/wiki/InstallShield" rel="nofollow">InstallShield</a>). We have a program running in the background that needs to run per-user, and it needs to start automatically without user intervention.</p> <p>The problem is with <a href="http://en.wikipedia.org/wiki/Group_Policy#Operation" rel="nofollow">Group Policy Object</a>/<a href="http://en.wikipedia.org/wiki/Active_Directory" rel="nofollow">Active Directory</a> (GPO/AD) deployment the application is started in the SYSTEM context before anyone is logged in rather than as the user who is about to log in. The application can only run once per user, and it seems that the SYSTEM process prevents the USER process from starting. This means the PCs need to be rebooted twice before the software can be deployed to the users. How do we to stop this?</p> <p>Basically the current workflow is: </p> <ol> <li>Installation/upgrade runs... kill background application</li> <li>Install new files</li> <li>Startup background application</li> </ol> <p>This works for published applications and interactive <a href="http://en.wikipedia.org/wiki/Windows_Installer" rel="nofollow">MSI</a> installations - it's only 'assigned' applications that seem to have the problem. As step 3 happens in the SYSTEM context rather than the user context :(</p> <p>Ideally, I'd have the development team patch the EXE file to prevent launching in the SYSTEM context, but that's a release cycle away, and I'm looking for an installer-based solution for the interim.</p> <p>(I don't know Installscript... So I'm guessing <a href="http://en.wikipedia.org/wiki/VBScript" rel="nofollow">VBScript</a> is probably the way to go if there's no native InstallShield stuff I can use.)</p>
<p>You can use the LogonUser property of Windows Installer as a condition to the action launching the EXE.</p>
Is version control (ie. Subversion) applicable in document tracking? <p>I am in charge of about 100+ documents (word document, not source code) that needs revision by different people in my department. Currently all the documents are in a shared folder where they will retrieve, revise and save back into the folder. </p> <p>What I am doing now is looking up the "date modified" in the shared folder, opened up recent modified documents and use the "Track Change" function in MS Word to apply the changes. I find this a bit tedious.</p> <p>So will it be better and easier if I commit this in a version control database?</p> <p>Basically I want to keep different version of a file.</p> <p><hr> What have I learn from answers:</p> <ul> <li><p>Use Time Machine to save different version (or Shadow copy in Vista)</p></li> <li><p>There is a difference between text and binary documents when you use version control app. (I didn't know that)</p></li> <li><p>Diff won't work on binary files</p></li> <li><p>A notification system (ie email) for revision is great</p></li> <li><p>Google Docs revision feature.</p></li> </ul> <p><strong>Update</strong> : </p> <p>I played around with Google Docs revision feature and feel that it is almost right for me. Just a bit annoyed with the too frequent versioning (autosaving). </p> <p>But what feels right for me doesn't mean it feels right for my dept. Will they be okay with saving all these documents with Google? </p>
<p>I've worked with Word documents in SVN. With <a href="http://tortoisesvn.tigris.org/">TortoiseSVN</a>, you can easily diff Word documents (between working copy and repository, or between two repository revisions). It's really slick and definitely recommended.</p> <p>The other thing to do if you're using Word documents in SVN is to add the <a href="http://svnbook.red-bean.com/en/1.2/svn.advanced.locking.html">svn:needs-lock</a> property to the Word documents. This will prevent two people from trying to edit the same document at the same time, since unfortunately there's no good way to merge Word documents.</p> <p>With the above two things, handling revision controlled Word documents is at least tolerable. It certainly beats the alternative of using a shared folder and track-changes.</p>
Java return copy to hide future changes <p>In Java, say you have a class that wraps an <code>ArrayList</code> (or any collection) of objects. </p> <p>How would you return one of those objects such that the caller will not see any future changes to the object made in the ArrayList? </p> <p>i.e. you want to return a deep copy of the object, but you don't know if it is cloneable.</p>
<p>Turn that into a spec:<br /> -that objects need to implement an interface in order to be allowed into the collection Something like <code>ArrayList&lt;ICloneable&gt;()</code></p> <p>Then you can be assured that you always do a deep copy - the interface should have a method that is guaranteed to return a deep copy. </p> <p>I think that's the best you can do. </p>
How to bring in a web app <p>I run a game and the running is done by hand, I have a few scripts that help me but essentially it's me doing the work. I am at the moment working on web app that will allow the users to input directly some of their game actions and thus save me a lot of work.</p> <p>The problem is that I'm one man working on a moderately sized (upwards of 20 tables) project, the workload isn't the issue, it's that bugs will have slipped in even though I test as I write. So my question is thus two-fold.</p> <ol> <li>Beta testing, I love open beta's but would a closed beta be somehow more effective and give better results?</li> <li>How should I bring in the app? Should I one turn drop it in and declare it's being used or should I use it alongside the normal construct of the game?</li> </ol>
<p>This is my general approach to testing/launching. How you test/launch depends mostly on:</p> <ol> <li>What your application <strong>is</strong>.</li> <li>Who your users <strong>are</strong>.</li> </ol> <p>If you application is a technical application and is geared to the technically-minded, the word "beta" won't really scare them - but provide an opportunity to test the product before it goes 'live', and help to improve the system. This is the ideal circumstance in which to use either an open or closed beta. It's usually beneficial to start off 'closed' with a group of people you select and trust to bug-find quickly and reliably - after you're more confident that all the critical bugs are gone, open it up with an invite system (for example).</p> <p>If, however, your application is 'trivial' from a technical standpoint (i.e. it's something like Twitter, or Facebook, or Flickr - nothing that is inherently geared towards technical usage), then you're going to have to be more careful in how you plan your testing. Closed testing is most definitely your first port of call, and this should last for longer than a closed beta on a more 'technical' product. The reason? Your 'average Joe' doesn't necessarily know what the word "beta" means, and others may well be scared by it, or judge your service prematurely (not understanding the concept of this 'public testing' phase). Many won't want to be used as guinea pigs.</p>
How to get your own (local) IP-Address from an udp-socket (C/C++) <ol> <li>You have multiple network adapters.</li> <li>Bind a UDP socket to an local port, without specifying an address.</li> <li>Receive packets on one of the adapters.</li> </ol> <p>How do you get the local ip address of the adapter which received the packet?</p> <p>The question is, "What is the ip address from the receiver adapter?" not the address from the sender which we get in the </p> <pre><code>receive_from( ..., &amp;senderAddr, ... ); </code></pre> <p>call.</p>
<p>You could enumerate all the network adapters, get their IP addresses and compare the part covered by the subnet mask with the sender's address.</p> <p>Like:</p> <pre><code>IPAddress FindLocalIPAddressOfIncomingPacket( senderAddr ) { foreach( adapter in EnumAllNetworkAdapters() ) { adapterSubnet = adapter.subnetmask &amp; adapter.ipaddress; senderSubnet = adapter.subnetmask &amp; senderAddr; if( adapterSubnet == senderSubnet ) { return adapter.ipaddress; } } } </code></pre>
How should I test a method that populates a list from a DataReader? <p>So I'm working on some legacy code that's heavy on the manual database operations. I'm trying to maintain some semblance of quality here, so I'm going TDD as much as possible.</p> <p>The code I'm working on needs to populate, let's say a <code>List&lt;Foo&gt;</code> from a DataReader that returns all the fields required for a functioning Foo. However, if I want to verify that the code in fact returns one list item per one database row, I'm writing test code that looks something like this:</p> <pre><code>Expect.Call(reader.Read()).Return(true); Expect.Call(reader["foo_id"]).Return((long) 1); // .... Expect.Call(reader.Read()).Return(true); Expect.Call(reader["foo_id"]).Return((long) 2); // .... Expect.Call(reader.Read()).Return(false); </code></pre> <p>Which is rather tedious and rather easily broken, too. </p> <p>How should I be approaching this issue so that the result won't be a huge mess of brittle tests?</p> <p>Btw I'm currently using Rhino.Mocks for this, but I can change it if the result is convincing enough. Just as long as the alternative isn't TypeMock, because their EULA was a bit too scary for my tastes last I checked.</p> <p>Edit: I'm also currently limited to C# 2.</p>
<p>To make this less tedious, you will need to encapsulate/refactor the mapping between the DataReader and the Object you hold in the list. There is quite of few steps to encapsulate that logic out. If that is the road you want to take, I can post code for you. I am just not sure how practical it would be to post the code here on StackOverflow, but I can give it a shot to keep it concise and to the point. Otherwise, you are stuck with the tedious task of repeating each expectation on the index accessor for the reader. The encapsulation process will also get rid of the strings and make those strings more reusable through your tests.</p> <p>Also, I am not sure at this point how much you want to make the existing code more testable. Since this is legacy code that wasn't built with testing in mind.</p>
How to know if a line intersects a plane in C#? - Basic 2D geometry <p>my school maths are very rusty and I think this is a good opportunity to take advance of this community :D</p> <p>I have two points (a line) and a rectangle, I would like to know how to calculate if the line intersects the rectangle, my first approach had so many "if" statements that the compiler sent me a link to this site.</p> <p>Thanks for your time!</p>
<p>From my "Geometry" class:</p> <pre><code>public struct Line { public static Line Empty; private PointF p1; private PointF p2; public Line(PointF p1, PointF p2) { this.p1 = p1; this.p2 = p2; } public PointF P1 { get { return p1; } set { p1 = value; } } public PointF P2 { get { return p2; } set { p2 = value; } } public float X1 { get { return p1.X; } set { p1.X = value; } } public float X2 { get { return p2.X; } set { p2.X = value; } } public float Y1 { get { return p1.Y; } set { p1.Y = value; } } public float Y2 { get { return p2.Y; } set { p2.Y = value; } } } public struct Polygon: IEnumerable&lt;PointF&gt; { private PointF[] points; public Polygon(PointF[] points) { this.points = points; } public PointF[] Points { get { return points; } set { points = value; } } public int Length { get { return points.Length; } } public PointF this[int index] { get { return points[index]; } set { points[index] = value; } } public static implicit operator PointF[](Polygon polygon) { return polygon.points; } public static implicit operator Polygon(PointF[] points) { return new Polygon(points); } IEnumerator&lt;PointF&gt; IEnumerable&lt;PointF&gt;.GetEnumerator() { return (IEnumerator&lt;PointF&gt;)points.GetEnumerator(); } public IEnumerator GetEnumerator() { return points.GetEnumerator(); } } public enum Intersection { None, Tangent, Intersection, Containment } public static class Geometry { public static Intersection IntersectionOf(Line line, Polygon polygon) { if (polygon.Length == 0) { return Intersection.None; } if (polygon.Length == 1) { return IntersectionOf(polygon[0], line); } bool tangent = false; for (int index = 0; index &lt; polygon.Length; index++) { int index2 = (index + 1)%polygon.Length; Intersection intersection = IntersectionOf(line, new Line(polygon[index], polygon[index2])); if (intersection == Intersection.Intersection) { return intersection; } if (intersection == Intersection.Tangent) { tangent = true; } } return tangent ? Intersection.Tangent : IntersectionOf(line.P1, polygon); } public static Intersection IntersectionOf(PointF point, Polygon polygon) { switch (polygon.Length) { case 0: return Intersection.None; case 1: if (polygon[0].X == point.X &amp;&amp; polygon[0].Y == point.Y) { return Intersection.Tangent; } else { return Intersection.None; } case 2: return IntersectionOf(point, new Line(polygon[0], polygon[1])); } int counter = 0; int i; PointF p1; int n = polygon.Length; p1 = polygon[0]; if (point == p1) { return Intersection.Tangent; } for (i = 1; i &lt;= n; i++) { PointF p2 = polygon[i % n]; if (point == p2) { return Intersection.Tangent; } if (point.Y &gt; Math.Min(p1.Y, p2.Y)) { if (point.Y &lt;= Math.Max(p1.Y, p2.Y)) { if (point.X &lt;= Math.Max(p1.X, p2.X)) { if (p1.Y != p2.Y) { double xinters = (point.Y - p1.Y) * (p2.X - p1.X) / (p2.Y - p1.Y) + p1.X; if (p1.X == p2.X || point.X &lt;= xinters) counter++; } } } } p1 = p2; } return (counter % 2 == 1) ? Intersection.Containment : Intersection.None; } public static Intersection IntersectionOf(PointF point, Line line) { float bottomY = Math.Min(line.Y1, line.Y2); float topY = Math.Max(line.Y1, line.Y2); bool heightIsRight = point.Y &gt;= bottomY &amp;&amp; point.Y &lt;= topY; //Vertical line, slope is divideByZero error! if (line.X1 == line.X2) { if (point.X == line.X1 &amp;&amp; heightIsRight) { return Intersection.Tangent; } else { return Intersection.None; } } float slope = (line.X2 - line.X1)/(line.Y2 - line.Y1); bool onLine = (line.Y1 - point.Y) == (slope*(line.X1 - point.X)); if (onLine &amp;&amp; heightIsRight) { return Intersection.Tangent; } else { return Intersection.None; } } } </code></pre>
Is there a Java Console/Editor similar to the GroovyConsole? <p>I'm giving a presentation to a Java User's Group on Groovy and I'm going to be doing some coding during the presentation to show some side-by-side Java/Groovy. I really like the GroovyConsole as it's simple and I can resize the text easily. </p> <p>I'm wondering if there is anything similar for Java? I know I could just use Eclipse but I'd rather have a smaller app to use without having to customize a view. What's the community got?</p> <p>Screen shot of GroovyConsole:</p> <p><img src="http://i.stack.imgur.com/GiR7b.jpg" alt="enter image description here"></p>
<p><a href="http://www.drjava.org/" rel="nofollow">DrJava</a> is your best bet. It also has an <a href="http://www.drjava.org/eclipse.shtml" rel="nofollow">Eclipse plugin</a> to use the interactions pane like GroovyConsole.</p>
Avoiding repeated constants in CSS <p>Are there any useful techniques for reducing the repetition of constants in a CSS file?</p> <p>(For example, a bunch of different selectors which should all apply the same colour, or the same font size)?</p>
<p>Elements can belong to more than one class, so you can do something like this: </p> <pre><code>.DefaultBackColor { background-color: #123456; } .SomeOtherStyle { //other stuff here } .DefaultForeColor { color:#654321; } </code></pre> <p>And then in the content portion somewhere: </p> <pre><code>&lt;div class="DefaultBackColor SomeOtherStyle DefaultForeColor"&gt;Your content&lt;/div&gt; </code></pre> <p>The weaknesses here are that it gets pretty wordy in the body and you're unlikely to be able to get it down to listing a color only once. But you might be able to do it only two or three times and you can group those colors together, perhaps in their own sheet. Now when you want to change the color scheme they're all together and the change is pretty simple.</p> <p>But, yeah, my biggest complain with CSS is the inability to define your own constants.</p>
enter key to insert newline in asp.net multiline textbox control <p>I have some C# / asp.net code I inherited which has a textbox which I want to make multiline. I did so by adding textmode="multiline" but when I try to insert a newline, the enter key instead submits the form :P</p> <p>I googled around and it seems like the default behavior should be for enter (or control-enter) to insert a newline. Like I said I inherited the code so I'm not sure if there's javascript monkeying around or if there's just a simple asp.net thing I have to do.</p>
<p>It turns out this is a bug with Firefox + ASP.NET where the generated javascript for the defaultButton stuff doesn't work in Firefox. I had to put a replacement for the WebForm_FireDefatultButton function as described <a href="http://forums.asp.net/t/1294544.aspx" rel="nofollow">here</a>:</p> <pre><code>function WebForm_FireDefaultButton(event, target) { var element = event.target || event.srcElement; if (event.keyCode == 13 &amp;&amp; !(element &amp;&amp; element.tagName.toLowerCase() == "textarea")) { var defaultButton; if (__nonMSDOMBrowser) { defaultButton = document.getElementById(target); } else { defaultButton = document.all[target]; } if (defaultButton &amp;&amp; typeof defaultButton.click != "undefined") { defaultButton.click(); event.cancelBubble = true; if (event.stopPropagation) { event.stopPropagation(); } return false; } } return true; } </code></pre>
Asp.Net MVC: How do I enable dashes in my urls? <p>I'd like to have dashes separate words in my URLs. So instead of:</p> <pre><code>/MyController/MyAction </code></pre> <p>I'd like:</p> <pre><code>/My-Controller/My-Action </code></pre> <p>Is this possible?</p>
<p>You can use the ActionName attribute like so:</p> <pre><code>[ActionName("My-Action")] public ActionResult MyAction() { return View(); } </code></pre> <p>Note that you will then need to call your View file "My-Action.cshtml" (or appropriate extension). You will also need to reference "my-action" in any Html.ActionLink methods.</p> <p>There isn't such a simple solution for controllers.</p> <h2>Edit: Update for MVC5</h2> <p>Now with MVC5, Attribute Routing has been absorbed into the project. You can now use:</p> <pre><code>[Route("My-Action")] </code></pre> <p>On Action Methods. </p> <p>For controllers, you can apply a <code>RoutePrefix</code> attribute which will be applied to all action methods in that controller:</p> <pre><code>[RoutePrefix("my-controller")] </code></pre> <p>One of the benefits of using <code>RoutePrefix</code> is URL parameters will also be passed down to any action methods.</p> <pre><code>[RoutePrefix("clients/{clientId:int}")] public class ClientsController : Controller ..... </code></pre> <p>Snip..</p> <pre><code>[Route("edit-client")] public ActionResult Edit(int clientId) // will match /clients/123/edit-client </code></pre>
Moving from Visual Studio 2005 to 2008 and .NET 2.0 <p>I'm currently using VS2005 Profesional and .NET 2.0, and since our project is rather large (25 projects in the solution), I'd like to try VS 2008, since its theoretically faster with larger projects. </p> <p>Before doing such thing, i'd like to know if what I've read is true: can I use VS2008 in ".net 2.0" mode? I don't want my customers to install .net 3.0 or .3.5, I just want to install VS2008, open my solution and start working from there. </p> <p>Is this possible?</p> <p>P.D.: the solution is a c# Window Forms project.</p>
<p>Yes it's possible. In the project properties you can target different versions of the .Net Framework going back to .NET 2.0.</p> <p>Upgrading to VS 2008 will upgrade your Solution file and you won't be able to go back to VS 2005 unless you have backed up your solution</p>
What does this javascript error mean? Permission denied to call method to Location.toString <p>This error just started popping up all over our site.</p> <p><strong><em>Permission denied to call method to Location.toString</em></strong></p> <p>I'm seeing google posts that suggest that this is related to flash and our crossdomain.xml. What caused this to occur and how do you fix?</p>
<p>Are you using javascript to communicate between frames/iframes which point to different domains? This is not permitted by the JS "same origin/domain" security policy. Ie, if you have</p> <pre><code>&lt;iframe name="foo" src="foo.com/script.js"&gt; &lt;iframe name="bar" src="bar.com/script.js"&gt; </code></pre> <p>And the script on bar.com tries to access <code>window["foo"].Location.toString</code>, you will get this (or similar) exceptions. Please also note that the same origin policy can also kick in if you have content from different subdomains. <a href="http://www.mozilla.org/projects/security/components/same-origin.html" rel="nofollow">Here</a> you can find a short and to the point explanation of it with examples.</p>
MySQL Binary Log Replication: Can it be set to ignore errors? <p>I'm running a master-slave MySQL binary log replication system (phew!) that, for some data, is not in sync (meaning, the master holds more data than the slave). But the slave stops very frequently on the slightest MySQL error, can this be disabled? (perhaps a my.cnf setting for the replicating slave ignore-replicating-errors or some of the sort ;) )</p> <p>This is what happens, every now and then, when the slave tries to replicate an item that does not exist, the slave just dies. a quick check at <strong>SHOW SLAVE STATUS \G;</strong> gives</p> <pre><code> Slave-IO-Running: Yes Slave-SQL-Running: No Replicate-Do-DB: Last-Errno: 1062 Last-Error: Error 'Duplicate entry '15218' for key 1' on query. Default database: 'db'. Query: 'INSERT INTO db.table ( FIELDS ) VALUES ( VALUES )' </code></pre> <p>which I promptly fix (once I realize that the slave has been stopped) by doing the following:</p> <pre><code>STOP SLAVE; RESET SLAVE; START SLAVE; </code></pre> <p>... lately this has been getting kind of tiresome, and before I spit out some sort of PHP which does this for me, i was wondering if there's some my.cnf entry which will not kill the slave on the first error.</p> <p>Cheers,</p> <p>/mp</p>
<p>stop slave; set global sql_slave_skip_counter=1; start slave;</p> <p>You can ignore only the current error and continue the replication process.</p>
How to unit test an object with database queries <p>I've heard that unit testing is "totally awesome", "really cool" and "all manner of good things" but 70% or more of my files involve database access (some read and some write) and I'm not sure how to write a unit test for these files.</p> <p>I'm using PHP and Python but I think it's a question that applies to most/all languages that use database access.</p>
<p>I would suggest mocking out your calls to the database. Mocks are basically objects that look like the object you are trying to call a method on, in the sense that they have the same properties, methods, etc. available to caller. But instead of performing whatever action they are programmed to do when a particular method is called, it skips that altogether, and just returns a result. That result is typically defined by you ahead of time. </p> <p>In order to set up your objects for mocking, you probably need to use some sort of inversion of control/ dependency injection pattern, as in the following pseudo-code:</p> <pre><code>class Bar { private FooDataProvider _dataProvider; public instantiate(FooDataProvider dataProvider) { _dataProvider = dataProvider; } public getAllFoos() { // instead of calling Foo.GetAll() here, we are introducing an extra layer of abstraction return _dataProvider.GetAllFoos(); } } class FooDataProvider { public Foo[] GetAllFoos() { return Foo.GetAll(); } } </code></pre> <p>Now in your unit test, you create a mock of FooDataProvider, which allows you to call the method GetAllFoos without having to actually hit the database.</p> <pre><code>class BarTests { public TestGetAllFoos() { // here we set up our mock FooDataProvider mockRepository = MockingFramework.new() mockFooDataProvider = mockRepository.CreateMockOfType(FooDataProvider); // create a new array of Foo objects testFooArray = new Foo[] {Foo.new(), Foo.new(), Foo.new()} // the next statement will cause testFooArray to be returned every time we call FooDAtaProvider.GetAllFoos, // instead of calling to the database and returning whatever is in there // ExpectCallTo and Returns are methods provided by our imaginary mocking framework ExpectCallTo(mockFooDataProvider.GetAllFoos).Returns(testFooArray) // now begins our actual unit test testBar = new Bar(mockFooDataProvider) baz = testBar.GetAllFoos() // baz should now equal the testFooArray object we created earlier Assert.AreEqual(3, baz.length) } } </code></pre> <p>A common mocking scenario, in a nutshell. Of course you will still probably want to unit test your actual database calls too, for which you will need to hit the database.</p>
Update Panel inside of a UserControl inside of a Repeater inside of another UpdatePanel <p>Yes, it sounds crazy....It might be.</p> <p>The final updatepanel does not appear to trigger anything, it just refreshes the update panels and does not call back to the usercontrol hosting it.</p> <p>Any ideas?</p> <p>EDIT: I got it posting back, however the controls inside the final usercontrol have lost their data...I'm thinking its because the main repeater is rebinding on each postback...Not sure where to take this one now.</p>
<p>I would suggest you start by removing the UpdatePanels at first, and make sure your control orgy is working correctly with postbacks. Once you have that working, try adding the UpdatePanels back in from the bottom up.</p>
Is there a Way to use Linq to Oracle <p>I can connect with the DataContext to the Oracle database however I get errors in running the query against the oracle database. I looked at the SQL generated and it is for MSSQL and not Oracle PSQL. </p> <p>Does anybody know of a decent easy to use wrapper to use LINQ against an Oracle Database?</p>
<p>No, LINQ to SQL is very much MS SQL only - think of it as a client driver.</p> <p><a href="http://forums.microsoft.com/MSDN/ShowPost.aspx?PostID=1623471&amp;SiteID=1">Microsoft is/was helping Oracle and DataDirect develop providers for Oracle and other non-MS database servers.</a></p>
How can I authenticate using client credentials in WCF just once? <p>What is the best approach to make sure you only need to authenticate once when using an API built on WCF?</p> <p>My current bindings and behaviors are listed below</p> <pre><code> &lt;bindings&gt; &lt;wsHttpBinding&gt; &lt;binding name="wsHttp"&gt; &lt;security mode="TransportWithMessageCredential"&gt; &lt;transport/&gt; &lt;message clientCredentialType="UserName" negotiateServiceCredential="false" establishSecurityContext="true"/&gt; &lt;/security&gt; &lt;/binding&gt; &lt;/wsHttpBinding&gt; &lt;/bindings&gt; &lt;behaviors&gt; &lt;serviceBehaviors&gt; &lt;behavior name="NorthwindBehavior"&gt; &lt;serviceMetadata httpGetEnabled="true"/&gt; &lt;serviceAuthorization principalPermissionMode="UseAspNetRoles"/&gt; &lt;serviceCredentials&gt; &lt;userNameAuthentication userNamePasswordValidationMode="MembershipProvider"/&gt; &lt;/serviceCredentials&gt; &lt;/behavior&gt; &lt;/serviceBehaviors&gt; &lt;/behaviors&gt; </code></pre> <p><strong>Next is what I am using in my client app to authenticate (currently I must do this everytime I want to make a call into WCF)</strong></p> <pre><code>Dim client As ProductServiceClient = New ProductServiceClient("wsHttpProductService") client.ClientCredentials.UserName.UserName = "foo" client.ClientCredentials.UserName.Password = "bar" Dim ProductList As List(Of Product) = client.GetProducts() </code></pre> <p>What I would like to do is auth w/ the API once using these credentials, then get some type of token for the period of time my client application is using the web service project. I thought establishsecuritycontext=true did this for me?</p>
<p>If you're on an intranet, Windows authentication can be handled for "free" by configuration alone. </p> <p>If this isn't appropriate, token services work just fine, but for some situations they may be just too much.</p> <p>The application I'm working on needed bare-bones authentication. Our server and client run inside a (very secure) intranet, so we didn't care too much for the requirement to use an X.509 certificate to encrypt the communication, which is required if you're using username authentication.</p> <p>So we added a <a href="http://www.winterdom.com/weblog/2006/10/02/CustomWCFBehaviorsThroughAppConfig.aspx" rel="nofollow">custom behavior</a> to the client that adds the username and (encrypted) password to the message headers, and another custom behavior on the server that verifies them.</p> <p>All very simple, required no changes to the client side service access layer or the service contract implementation. And as it's all done by configuration, if and when we need to move to something a little stronger it'll be easy to migrate.</p>
How to handle error logging <p>Until recently I've been using <code>syslog</code> in my <code>System_Exception</code> exception handler to log important errors - a pretty useful concept I thought. However my host just cut me off, and it appears that loveable <code>syslog</code> has actually been sending my error reports to everyone on the server (it's a shared server). They weren't too pleased.</p> <p>I've now switched to using a log.txt (and will now have to secure this with chmod or something) - but does anyone have any other suggestions for me to try? This seems a bit rusty.</p> <p>Oh, and don't use <code>syslog</code> on anything except a dedicated server or somewhere that can handle it ;-)</p>
<p>Try <strong>log4php</strong>. I'm using <strong>log4net</strong> for my .NET project and it's just terrific. :)</p>
What control is this? ("Open" Button with Drop Down) <p>The "Open" button on the open file dialog used in certain windows applications includes a dropdown arrow with a list of additional options -- namely "Open with..". </p> <p>I haven't seen this in every windows application, so you may have to try a few to get it, but SQL Server Management Studio and Visual Studio 2005 will both show the button that way if you go to the menu and choose <em>File->Open->File...</em></p> <p>I want to use a button like this with a built-in list in one of my applications, but I can't find the control they're using anywhere in visual studio. I should clarify that I'm looking for that specific button, not the entire dialog. Any thoughts?</p>
<p>I used the draggable search in Spy++ (installed with VS) to look at the split open button on the file-open dialog of VS.</p> <p>This revealed that it's an ordinary windows button with a style which includes BS_DEFSPLITBUTTON. That's a magic keyword which gets you to some interesting places, including</p> <p><a href="http://www.codeplex.com/windowsformsaero/SourceControl/FileView.aspx?itemId=212902&amp;changeSetId=9930">http://www.codeplex.com/windowsformsaero/SourceControl/FileView.aspx?itemId=212902&amp;changeSetId=9930</a></p> <p>and here</p> <p><a href="http://msdn.microsoft.com/en-us/library/bb775949.aspx#using_splits">http://msdn.microsoft.com/en-us/library/bb775949.aspx#using_splits</a></p> <p>Hope this helps you. </p> <p>EDIT:</p> <p>I've actually just tried that code from CodePlex and it does create a split button - but you do have to make sure you've set the button's FlatStyle to 'System' rather than 'Standard' which is the default. I've not bothered to hook-up the event handling stuff for the drop-down, but that's covered in the MSDN link, I think.</p> <p>Of course, this is Vista-only (but doesn't need Aero enabled, despite the name on codeplex) - if you need earlier OS support, you'll be back to drawing it yourself.</p>
Accessing a Component on an inherited form from the base form <p>A number of forms in my project inherit from a base form. It is easy to get at the Controls collection of the derived forms, but I have not found a simple way to access the Components collection, since VS marks this as private. </p> <p>I assume this could be done with reflection, but I'm not really sure how best to go about it, not having worked with reflection before.</p> <p>Right now, I'm using a sort of clunky workaround, in which I override a function GetComponents and return an array of the components I'm interested in. This is obviously prone to errors, since it's easy to forget to implement the overridden function or update it when components are added.</p> <p>If anyone has any tips or can suggest a better way, I'd be glad to hear.</p>
<p>If you set the Modifiers property of your components to strict protected makes them accessible without the use of a components collection. </p> <p>Edit: Discoverability could be done using reflection to walk over each field. Although that might be suboptimal in your case.</p>
Outlook synchronization on multiple machines <p><i>This isn't much of a programming question, but I'm sure I'm not the only person here who has this issue.</i></p> <p>Currently I have two machines with Outlook 2007. They both sync e-mail from Google Apps. One of the machines publishes my calendar to a secure server, which my other machine is subscribed to. The problem with this setup is that I have read-only calendar access on one of my machines, which sucks. Also soon I'll be upgrading to a smart-phone, so anything I do will also have to support that scenario.</p> <ol> <li>Is there a better way to handle Outlook synchronization without setting up an exchange server in my basement?</li> <li>If I have to setup Exchange, is it possible to make it pull e-mail, via IMAP, from Google Apps?</li> </ol>
<p>Question 2: Yes. Use your Exchange server as you normally would then add your IMAP email account to Outlook. I have a client that has done this for his office staff and it's been working fine for years.</p>
Content Type for MHT files <p>What is the content type for MHT files?</p>
<p>Microsoft, who co-authored the spec for MHT, seem to think that it should be '<code>message/rfc822</code>' on <a href="http://support.microsoft.com/kb/937912">this support page</a>.</p> <p>No specific MIME type seems to be given in the spec though: <a href="http://tools.ietf.org/html/rfc2557">RFC2557: MIME Encapsulation of Aggregate Documents, such as HTML (MHTML)</a> </p>
Profile a rails controller action <p>What is the best way to profile a controller action in Ruby on Rails. Currently I am using the brute-force method of throwing in <code>puts Time.now</code> calls between what I think will be a bottleneck. But that feels really, really dirty. There has got to be a better way.</p>
<p>I picked up this technique a while back and have found it quite handy.</p> <p>When it's in place, you can add <code>?profile=true</code> to any URL that hits a controller. Your action will run as usual, but instead of delivering the rendered page to the browser, it'll send a detailed, nicely formatted ruby-prof page that shows where your action spent its time.</p> <p>First, add ruby-prof to your Gemfile, probably in the development group:</p> <pre><code>group :development do gem "ruby-prof" end </code></pre> <p>Then add an <a href="http://guides.rubyonrails.org/action_controller_overview.html#after-filters-and-around-filters">around filter</a> to your ApplicationController:</p> <pre><code>around_filter :profile if Rails.env == 'development' def profile if params[:profile] &amp;&amp; result = RubyProf.profile { yield } out = StringIO.new RubyProf::GraphHtmlPrinter.new(result).print out, :min_percent =&gt; 0 self.response_body = out.string else yield end end </code></pre> <p>Reading the ruby-prof output is a bit of an art, but I'll leave that as an exercise.</p> <p><strong>Additional note by ScottJShea:</strong> If you want to change the measurement type place this:</p> <p><code>RubyProf.measure_mode = RubyProf::GC_TIME #example</code></p> <p>Before the <code>if</code> in the profile method of the application controller. You can find a list of the available measurements at the <a href="https://github.com/rdp/ruby-prof#measurements">ruby-prof page</a>. As of this writing the <code>memory</code> and <code>allocations</code> data streams seem to be corrupted (<a href="https://github.com/rdp/ruby-prof/issues/86">see defect</a>).</p>
How do threads work in Python, and what are common Python-threading specific pitfalls? <p>I've been trying to wrap my head around how threads work in Python, and it's hard to find good information on how they operate. I may just be missing a link or something, but it seems like the official documentation isn't very thorough on the subject, and I haven't been able to find a good write-up.</p> <p>From what I can tell, only one thread can be running at once, and the active thread switches every 10 instructions or so?</p> <p>Where is there a good explanation, or can you provide one? It would also be very nice to be aware of common problems that you run into while using threads with Python.</p>
<p>Yes, because of the Global Interpreter Lock (GIL) there can only run one thread at a time. Here are some links with some insights about this:</p> <ul> <li><a href="http://www.artima.com/weblogs/viewpost.jsp?thread=214235">http://www.artima.com/weblogs/viewpost.jsp?thread=214235</a></li> <li><a href="http://smoothspan.wordpress.com/2007/09/14/guido-is-right-to-leave-the-gil-in-python-not-for-multicore-but-for-utility-computing/">http://smoothspan.wordpress.com/2007/09/14/guido-is-right-to-leave-the-gil-in-python-not-for-multicore-but-for-utility-computing/</a></li> </ul> <p>From the last link an interesting quote:</p> <blockquote> <p>Let me explain what all that means. Threads run inside the same virtual machine, and hence run on the same physical machine. Processes can run on the same physical machine or in another physical machine. If you architect your application around threads, you’ve done nothing to access multiple machines. So, you can scale to as many cores are on the single machine (which will be quite a few over time), but to really reach web scales, you’ll need to solve the multiple machine problem anyway.</p> </blockquote> <p>If you want to use multi core, <a href="http://www.python.org/dev/peps/pep-0371/">pyprocessing</a> defines an process based API to do real parallelization. The <a href="http://en.wikipedia.org/wiki/Python_Enhancement_Proposal#Development">PEP</a> also includes some interesting benchmarks.</p>
Is there a reason to use BufferedReader over InputStreamReader when reading all characters? <p>I currently use the following function to do a simple HTTP GET.</p> <pre><code>public static String download(String url) throws java.io.IOException { java.io.InputStream s = null; java.io.InputStreamReader r = null; //java.io.BufferedReader b = null; StringBuilder content = new StringBuilder(); try { s = (java.io.InputStream)new URL(url).getContent(); r = new java.io.InputStreamReader(s); //b = new java.io.BufferedReader(r); char[] buffer = new char[4*1024]; int n = 0; while (n &gt;= 0) { n = r.read(buffer, 0, buffer.length); if (n &gt; 0) { content.append(buffer, 0, n); } } } finally { //if (b != null) b.close(); if (r != null) r.close(); if (s != null) s.close(); } return content.toString(); } </code></pre> <p>I see no reason to use the <code>BufferedReader</code> since I am just going to download everything in sequence. Am I right in thinking there is no use for the <code>BufferedReader</code> in this case?</p>
<p>In this case, I would do as you are doing (use a byte array for buffering and not one of the stream buffers).</p> <p>There are exceptions, though. One place you see buffers (output this time) is in the servlet API. Data isn't written to the underlying stream until <em>flush()</em> is called, allowing you to buffer output but then dump the buffer if an error occurs and write an error page instead. You might buffer input if you needed to reset the stream for rereading using <em>mark(int)</em> and <em>reset()</em>. For example, maybe you'd inspect the file header before deciding on which content handler to pass the stream to.</p> <p>Unrelated, but I think you should rewrite your stream handling. This pattern works best to avoid resource leaks:</p> <pre><code> InputStream stream = new FileInputStream("in"); try { //no operations between open stream and try block //work } finally { //do nothing but close this one stream in the finally stream.close(); } </code></pre> <p>If you are opening multiple streams, nest try/finally blocks.</p> <p>Another thing your code is doing is making the assumption that the returned content is encoded in your VM's default character set (though that might be adequate, depending on the use case).</p>
Visual Studio 2008 debugging issue <p>I'm working in VS 2008 and have three projects in one solution. I'm debugging by attaching to a .net process invoked by a third party app (SalesLogix, a CRM app). </p> <p>Once it has attached to the process and I attempt to set a breakpoint in one of the projects, it doesn't set a breakpoint in that file. It actually switches the current tab to another file in another project and sets a breakpoint in that document. If the file isn't open, it even goes so far as to open it for me. I can't explain this. I've got no clue. Anyone seen such odd behavior? I wouldn't believe it if I wasn't seeing it myself.</p> <p>A little more info: if I set a breakpoint before attaching, it shows the "red dot" and says no symbols loaded...no problem...I expect that. When I attach and invoke my .net code from SalesLogix and switch back to VS, my breakpoint is completely gone (not even a warning that the source doesn't match the debug file). When I attempt to manually load the debug file, then I get a message that the symbol file does not match the module. The .pdb and the .dll are timestamped the same, so I'm stumped.</p> <p>Anyone have any ideas?</p> <p>Thx,</p> <p>Jeff</p>
<p>I saw this functionality in older versions of VS.Net (2003 I think). It may still exist in current versions, but I haven't encountered it. Seems that files with the same name, even in different directories confuse VS.Net, and it ends up setting a break point in a file with the same name. May only happen if the classes in the file both have the same name also. So much for namespaces I guess. </p> <p>You also may want to check your build configuration to make sure that all the projects are in fact building in debug mode. I know I've been caught a couple times when the configuration got changed somehow for the solution, and some projects weren't compiling in debug mode.</p>
How stable is WPF? <p>How stable is WPF not in terms of stability of a WPF program, but in terms of the 'stability' of the API itself. </p> <p>Let me explain: </p> <p>Microsoft is notorious for changing its whole methodology around with new technology. Like with the move from silverlight 1 to silverlight 2. With WPF, I know that MS changed a bunch of stuff with the release of the .NET service pack. I don't know how much they changed things around. So the bottom line is, in your opinion are they going to revamp the system again with the next release or do you think that it is stable enough now that they won't change the bulk of the system. I hate to have to unlearn stuff with every release. </p> <p>I hope that the question wasn't too long winded.</p>
<p>MS do have a history of "fire and movement" with regards to introducing new technology into their development stack, but they also have a strong history of maintaining support for the older stuff, and backwards-compatibility. WPF seems to be getting stuff added to it with each new release of the framework but the things you learn aren't being superceded or invalidated.</p> <p>The only breaking change I've seen in my own WPF applications with a new release of the framework was one recently in 3.5 SP1, and that was because we were unknowingly relying on a bug to get a certain behaviour from our code. We adjusted the XAML to be more correct and it started working fine.</p> <p>So yeah, I think WPF is pretty "stable" as a client-side development technology.</p>
Do indexes work with "IN" clause <p>If I have a query like:</p> <pre><code>Select EmployeeId From Employee Where EmployeeTypeId IN (1,2,3) </code></pre> <p>and I have an index on the <code>EmployeeTypeId</code> field, does SQL server still use that index?</p>
<p>Yeah, that's right. If your employee table has 10,000 records, and only 5 records have employeetypeID in (1,2,3), then it will most likely use the index to fetch the records. However, if it finds that 9,000 records have the employeeIDType in (1,2,3), then it would most likely just do a table scan to get the corresponding EmployeeIDs, as it's faster just to run through the whole table than to go to each branch of the index tree and look at the records individually. </p> <p>SQL Server does a lot of stuff to try and optimize how the queries run. However, sometimes it doesn't get the right answer. If you know that SQL Server isn't using the index, by looking at the execution plan in query analyzer, you can tell the query engine to use a specific index with the following change to your query.</p> <pre><code>Select EmployeeId From Employee WITH (Index(Index_EmployeeTypeId )) Where EmployeeTypeId IN (1,2,3) </code></pre> <p>Assuming the index you have on the EmployeeTypeId field is named Index_EmployeeTypeId. </p>
How many ServiceContracts can a WCF service have? <p>How many ServiceContracts can a WCF service have?</p> <p>Specifically, since a ServiceContract is an attribute to an interface, how many interfaces can I code into one WCF web service? Is it a one-to-one?</p> <p>Does it make sense to separate the contracts across multiple web services?</p>
<p>WCF services can have multiple endpoints, each of which can implement a different service contract.</p> <p>For example, you could have a service declared as follows:</p> <pre><code>[ServiceBehavior(Namespace = "DemoService")] public class DemoService : IDemoService, IDoNothingService </code></pre> <p>Which would have configuration along these lines:</p> <pre><code>&lt;service name="DemoService" behaviorConfiguration="Debugging"&gt; &lt;host&gt; &lt;baseAddresses&gt; &lt;add baseAddress = "http://localhost/DemoService.svc" /&gt; &lt;/baseAddresses&gt; &lt;/host&gt; &lt;endpoint address ="" binding="customBinding" bindingConfiguration="InsecureCustom" bindingNamespace="http://schemas.com/Demo" contract="IDemoService"/&gt; &lt;endpoint address ="" binding="customBinding" bindingConfiguration="InsecureCustom" bindingNamespace="http://schemas.com/Demo" contract="IDoNothingService"/&gt; &lt;/service&gt; </code></pre> <p>Hope that helps, but if you were after the theoretical maximum interfaces you can have for a service I suspect it's some crazily large multiple of 2.</p>
How to respond to an alternate URI in a RESTful web service <p>I'm building a RESTful web service which has multiple URIs for one of its resources, because there is more than one unique identifier. Should the server respond to a GET request for an alternate URI by returning the resource, or should I send an HTTP 3xx redirect to the canonical URI? Is <em>HTTP 303 (see also)</em> the most appropriate redirect?</p> <p>Clarification: the HTTP specification makes it clear that the choice of redirect depends on which URI future requests should use. In my application, the 'canonical' URI is the most stable of the alternatives; an alternative URI will always direct to same canonical URI, or become invalid.</p>
<p>I'd personally plump for returning the resource rather than faffing with a redirect, although I suspect that's only because my subcoscious is telling me redirects are slower.</p> <p>However, if you were to decide to use a redirect I'd think a 302 or 307 might be more appropiate than a 303, although the <a href="http://www.w3.org/Protocols/rfc2616/rfc2616-sec10.html" rel="nofollow">w3.org</a> has details of the different redirect codes you could use.</p>
Java Logging vs Log4J <p>Is it still worth to add the log4j library to a Java 5 project just to log let's say some exceptions to a file with some nice rollover settings. Or will the standard util.logging facility do the job as well?</p> <p>What do you think?</p>
<p>I'd say you're probably fine with util.logging for the needs you describe.</p> <p>For a good decision tree, have a look at <a href="http://java.sys-con.com/node/48541">Log4j vs java.util.logging</a></p> <blockquote> <p>Question One : Do you anticipate a need for any of the clever handlers that Log4j has that JUL does not have, such as the SMTPHandler, NTEventLogHandler, or any of the very convenient FileHandlers?</p> <p>Question Two : Do you see yourself wanting to frequently switch the format of your logging output? Will you need an easy, flexible way to do so? In other words, do you need Log4j's PatternLayout?</p> <p>Question Three : Do you anticipate a definite need for the ability to change complex logging configurations in your applications, after they are compiled and deployed in a production environment? Does your configuration sound something like, "Severe messages from this class get sent via e-mail to the support guy; severe messages from a subset of classes get logged to a syslog deamon on our server; warning messages from another subset of classes get logged to a file on network drive A; and then all messages from everywhere get logged to a file on network drive B"? And do you see yourself tweaking it every couple of days?</p> <p>If you can answer yes to any of the above questions, go with Log4j. If you answer a definite no to all of them, JUL will be more than adequate and it's conveniently already included in the SDK.</p> </blockquote> <p>That said, pretty much every project these days seems to wind up including log4j, if only because some other library uses it.</p>
using a html entity in xslt (e.g. &nbsp;) <p>What is the best way to include an html entity in XSLT?</p> <pre><code>&lt;xsl:template match="/a/node"&gt; &lt;xsl:value-of select="."/&gt; &lt;xsl:text&gt;&amp;nbsp;&lt;/xsl:text&gt; &lt;/xsl:template&gt; </code></pre> <p>this one returns a <strong>XsltParseError</strong></p>
<p>You can use CDATA section</p> <pre><code>&lt;xsl:text disable-output-escaping="yes"&gt;&lt;![CDATA[&amp;nbsp;]]&gt;&lt;/xsl:text&gt; </code></pre> <p>or you can describe &amp;nbsp in local DTD:</p> <pre><code>&lt;!DOCTYPE xsl:stylesheet [ &lt;!ENTITY nbsp "&amp;#160;"&gt; ]&gt; </code></pre> <p>or just use <code>&amp;#160;</code> instead of <code>&amp;nbsp;</code></p>
Sending e-mail from a Custom SQL Server Reporting Services Delivery Extension <p>I've developed my own delivery extension for Reporting Services 2005, to integrate this with our SaaS marketing solution.</p> <p>It takes the subscription, and takes a snapshot of the report with a custom set of parameters. It then renders the report, sends an e-mail with a link and the report attached as XLS.</p> <p>Everything works fine, until mail delivery...</p> <p>Here's my code for sending e-mail:</p> <pre><code> public static List&lt;string&gt; SendMail(SubscriptionData data, Stream reportStream, string reportName, string smptServerHostname, int smtpServerPort) { List&lt;string&gt; failedRecipients = new List&lt;string&gt;(); MailMessage emailMessage = new MailMessage(data.ReplyTo, data.To); emailMessage.Priority = data.Priority; emailMessage.Subject = data.Subject; emailMessage.IsBodyHtml = false; emailMessage.Body = data.Comment; if (reportStream != null) { Attachment reportAttachment = new Attachment(reportStream, reportName); emailMessage.Attachments.Add(reportAttachment); reportStream.Dispose(); } try { SmtpClient smtp = new SmtpClient(smptServerHostname, smtpServerPort); // Send the MailMessage smtp.Send(emailMessage); } catch (SmtpFailedRecipientsException ex) { // Delivery failed for the recipient. Add the e-mail address to the failedRecipients List failedRecipients.Add(ex.FailedRecipient); } catch (SmtpFailedRecipientException ex) { // Delivery failed for the recipient. Add the e-mail address to the failedRecipients List failedRecipients.Add(ex.FailedRecipient); } catch (SmtpException ex) { throw ex; } catch (Exception ex) { throw ex; } // Return the List of failed recipient e-mail addresses, so the client can maintain its list. return failedRecipients; } </code></pre> <p>Values for SmtpServerHostname is localhost, and port is 25.</p> <p>I veryfied that I can actually send mail, by using Telnet. And it works.</p> <p><strong>Here's the error message I get from SSRS:</strong></p> <p>ReportingServicesService!notification!4!08/28/2008-11:26:17:: Notification 6ab32b8d-296e-47a2-8d96-09e81222985c completed. Success: False, Status: Exception Message: Failure sending mail. Stacktrace: at MyDeliveryExtension.MailDelivery.SendMail(SubscriptionData data, Stream reportStream, String reportName, String smptServerHostname, Int32 smtpServerPort) in C:\inetpub\wwwroot\CustomReporting\MyDeliveryExtension\MailDelivery.cs:line 48 at MyDeliveryExtension.MyDelivery.Deliver(Notification notification) in C:\inetpub\wwwroot\CustomReporting\MyDeliveryExtension\MyDelivery.cs:line 153, DeliveryExtension: My Delivery, Report: Clicks Development, Attempt 1 ReportingServicesService!dbpolling!4!08/28/2008-11:26:17:: NotificationPolling finished processing item 6ab32b8d-296e-47a2-8d96-09e81222985c</p> <p><strong>Could this have something to do with Trust/Code Access Security?</strong></p> <p>My delivery extension is granted full trust in rssrvpolicy.config:</p> <pre><code> &lt;CodeGroup class="UnionCodeGroup" version="1" PermissionSetName="FullTrust" Name="MyDelivery_CodeGroup" Description="Code group for MyDelivery extension"&gt; &lt;IMembershipCondition class="UrlMembershipCondition" version="1" Url="C:\Program Files\Microsoft SQL Server\MSSQL.2\Reporting Services\ReportServer\bin\MyDeliveryExtension.dll" /&gt; &lt;/CodeGroup&gt; </code></pre> <p>Could trust be an issue here?</p> <p>Another theory: SQL Server and SSRS was installed in the security context of Local System. Am I right, or is this service account restricted access to any network resource? Even its own SMTP Server?</p> <p>I tried changing all SQL Server Services logons to Administrator - but still without any success.</p> <p>I also tried logging onto the SMTP server in my code, by proviiding: NetworkCredential("Administrator", "password") and also NetworkCredential("Administrator", "password", "MyRepServer")</p> <p>Can anyone help here, please?</p>
<p>What's at:</p> <pre><code>at MyDeliveryExtension.MailDelivery.SendMail(SubscriptionData data, Stream reportStream, String reportName, String smptServerHostname, Int32 smtpServerPort) in C:\inetpub\wwwroot\CustomReporting\MyDeliveryExtension\MailDelivery.cs:line 48 at MyDeliveryExtension.MyDelivery.Deliver(Notification notification) in C:\inetpub\wwwroot\CustomReporting\MyDeliveryExtension\MyDelivery.cs:line 153 </code></pre> <p>Also you seem to be disposing the report stream, but that should be done by whatever opened that stream, not your method (it won't be obvious that attaching a stream disposes it).</p> <p>You're losing part of your stack trace due to how you re-throw exceptions. Don't throw the ex variable, just throw is enough.</p> <p>Try this tweak:</p> <pre><code>public static List&lt;string&gt; SendMail(SubscriptionData data, Stream reportStream, string reportName, string smptServerHostname, int smtpServerPort) { List&lt;string&gt; failedRecipients = new List&lt;string&gt;(); MailMessage emailMessage = new MailMessage(data.ReplyTo, data.To) { Priority = data.Priority, Subject = data.Subject, IsBodyHtml = false, Body = data.Comment }; if (reportStream != null) emailMessage.Attachments.Add(new Attachment(reportStream, reportName)); try { SmtpClient smtp = new SmtpClient(smptServerHostname, smtpServerPort); // Send the MailMessage smtp.Send(emailMessage); } catch (SmtpFailedRecipientsException ex) { // Delivery failed for the recipient. Add the e-mail address to the failedRecipients List failedRecipients.Add(ex.FailedRecipient); //are you missing a loop here? only one failed address will ever be returned } catch (SmtpFailedRecipientException ex) { // Delivery failed for the recipient. Add the e-mail address to the failedRecipients List failedRecipients.Add(ex.FailedRecipient); } // Return the List of failed recipient e-mail addresses, so the client can maintain its list. return failedRecipients; } </code></pre>
C# - SQLClient - Simplest INSERT <p>I'm basically trying to figure out the simplest way to perform your basic insert operation in C#.NET using the SqlClient namespace. </p> <p>I'm using <code>SqlConnection</code> for my db link, I've already had success executing some reads, and I want to know the simplest way to insert data. I'm finding what seem to be pretty verbose methods when I google.</p>
<pre><code>using (var conn = new SqlConnection(yourConnectionString)) { var cmd = new SqlCommand("insert into Foo values (@bar)", conn); cmd.Parameters.AddWithValue("@bar", 17); conn.Open(); cmd.ExecuteNonQuery(); } </code></pre>
Is regex case insensitivity slower? <p><a href="http://twitter.com/codinghorror/statuses/901272685">Source</a></p> <blockquote> <p>RegexOptions.IgnoreCase is more expensive than I would have thought (eg, should be barely measurable)</p> </blockquote> <p>Assuming that this applies to PHP, Python, Perl, Ruby etc as well as C# (which is what I assume Jeff was using), how much of a slowdown is it and will I incur a similar penalty with "/[a-zA-z]/" as I will with "/[a-z]/i" ?</p>
<p>Yes, [A-Za-z] will be much faster than setting the <code>RegexOptions.IgnoreCase</code>, largely because of Unicode strings. But it's also much more limiting -- [A-Za-z] does <em>not</em> match accented international characters, it's literally the A-Za-z ASCII set and nothing more.</p> <p>I don't know if you saw Tim Bray's answer to my message, but it's a good one:</p> <blockquote> <p>One of the trickiest issues in internationalized search is upper and lower case. This notion of case is limited to languages written in the Latin, Greek, and Cyrillic character sets. English-speakers naturally expect search to be case-insensitive if only because they’re lazy: if Nadia Jones wants to look herself up on Google she’ll probably just type in nadia jones and expect the system to take care of it.</p> <p>So it’s fairly common for search systems to “normalize” words by converting them all to lower- or upper-case, both for indexing and queries.</p> <p>The trouble is that the mapping between cases is not always as straightforward as it is in English. For example, the German lower-case character “ß” becomes “SS” when upper-cased, and good old capital “I” when down-cased in Turkish becomes the dotless “ı” (yes, they have “i”, its upper-case version is “İ”). I have read (but not verified first-hand) that the rules for upcasing accented characters such “é” are different in France and Québec. One of the results of all this is that software such as java.String.toLowerCase() tends to run astonishingly slow as it tries to work around all these corner-cases.</p> </blockquote> <p><a href="http://www.tbray.org/ongoing/When/200x/2003/10/11/SearchI18n">http://www.tbray.org/ongoing/When/200x/2003/10/11/SearchI18n</a></p>
Is soapUI the best web services testing tool/client/framework? <p>I have been working on a web services related project for about the last year. Our team found <a href="http://www.soapui.org">soapUI</a> near the start of our project and we have been <em>mostly</em>(*) satisfied with it (the free version, that is).</p> <p>My question is: are there other tools/clients/frameworks that you have used/currently use for web services testing and would recommend?</p> <p>(*) There are some weird GUI glitches that appear once in a while. As is mentioned by some of the answers, we attributed this to a memory leak.</p>
<p>I use soapUI, and it's generally pretty good. Be aware that it seems to leak memory, and eventually it will no longer save your project, so save regularly!</p> <p>This is about the only hassle I have with it (other than the general ugliness that almost every Java application has!), and I can't live without it.</p>
What is the simplest SQL Query to find the second largest value? <p>What is the simplest SQL query to find the second largest integer value in a specific column? </p> <p>There are maybe duplicate values in the column.</p>
<pre><code>SELECT MAX( col ) FROM table WHERE col &lt; ( SELECT MAX( col ) FROM table ) </code></pre>
Sending email in .NET through Gmail <p>Instead of relying on my host to send email, I was thinking of sending the messages though my Gmail account. The emails are personalized emails to the bands I play on my show. Is it possible to do?</p>
<p>Be sure to use <code>System.Net.Mail</code>, not the deprecated <code>System.Web.Mail</code>. Doing SSL with <code>System.Web.Mail</code> is a gross mess of hacky extensions.</p> <pre><code>using System.Net; using System.Net.Mail; var fromAddress = new MailAddress("[email protected]", "From Name"); var toAddress = new MailAddress("[email protected]", "To Name"); const string fromPassword = "fromPassword"; const string subject = "Subject"; const string body = "Body"; var smtp = new SmtpClient { Host = "smtp.gmail.com", Port = 587, EnableSsl = true, DeliveryMethod = SmtpDeliveryMethod.Network, UseDefaultCredentials = false, Credentials = new NetworkCredential(fromAddress.Address, fromPassword) }; using (var message = new MailMessage(fromAddress, toAddress) { Subject = subject, Body = body }) { smtp.Send(message); } </code></pre>
Passing null to a method <p>I am in the middle of reading the excellent <a href="http://rads.stackoverflow.com/amzn/click/0132350882">Clean Code</a></p> <p>One discussion is regarding passing nulls into a method.</p> <pre><code>public class MetricsCalculator { public double xProjection(Point p1, Point p2) { return (p2.x - p1.x) * 1.5; } } ... calculator.xProjection(null, new Point(12,13)); </code></pre> <p>It represents different ways of handling this:</p> <pre><code>public double xProjection(Point p1, Point p2) { if (p1 == null || p2 == null) { throw new IllegalArgumentException("Invalid argument for xProjection"); } return (p2.x - p1.x) * 1.5; } public double xProjection(Point p1, Point p2) { assert p1 != null : "p1 should not be null"; assert p2 != null : "p2 should not be null"; return (p2.x - p1.x) * 1.5; } </code></pre> <p>I prefer the <a href="http://java.sun.com/j2se/1.4.2/docs/guide/lang/assert.html">assertions</a> approach, but I don't like the fact that assertions are turned off by default.</p> <p>The book finally states:</p> <blockquote> <p>In most programming languages there is no good way to deal with a null that is passed by a caller accidentally. Because this is the case, the rational approach is to forbid passing null by default.</p> </blockquote> <p>It doesn't really go into how you would enforce this restriction?</p> <p>Do any of you have strong opinions either way.</p>
<p>General rule is if your method doesn't expect null arguments then you should throw <a href="http://msdn.microsoft.com/en-us/library/system.argumentnullexception.aspx">System.ArgumentNullException</a>. Throwing proper exception not only protects you from resource corruption and other bad things but serves as a guide for users of your code saving time spent debugging your code.</p> <p>Also read an article on <a href="http://en.wikipedia.org/wiki/Defensive_programming">Defensive programming</a></p>
1:1 Foreign Key Constraints <p>How do you specify that a foreign key constraint should be a 1:1 relationship in transact sql? Is declaring the column UNIQUE enough? Below is my existing code.!</p> <pre><code>CREATE TABLE [dbo].MyTable( [MyTablekey] INT IDENTITY(1,1) NOT FOR REPLICATION NOT NULL, [OtherTableKey] INT NOT NULL UNIQUE CONSTRAINT [FK_MyTable_OtherTable] FOREIGN KEY REFERENCES [dbo].[OtherTable]([OtherTableKey]), ... CONSTRAINT [PK_MyTable] PRIMARY KEY CLUSTERED ( [MyTableKey] ASC ) WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY] ) ON [PRIMARY] GO </code></pre>
<p>A foreign key column with the UNIQUE and NOT NULL constraints that references a UNIQUE, NOT NULL column in another table creates a 1:(0|1) relationship, which is probably what you want.</p> <p>If there was a true 1:1 relationship, every record in the first table would have a corresponding record in the second table and vice-versa. In that case, you would probably just want to make one table (unless you needed some strange storage optimization).</p>
Get the DefaultView DataRowView from a DataRow <p>Here's the situation: I need to bind a WPF <code>FixedPage</code> against a <code>DataRow</code>. Bindings don't work against <code>DataRows</code>; they work against <code>DataRowViews</code>. I need to do this in the most generic way possible, as I know nothing about and have no control over what is in the <code>DataRow</code>. </p> <p>What I need is to be able to get a <code>DataRowView</code> for a given <code>DataRow</code>. I can't use the <code>Find()</code> method on the <code>DefaultView</code> because that takes a key, and there is no guarantee the table will have a primary key set.</p> <p>Does anybody have a suggestion as to the best way to go around this? </p>
<p>Not Exactly a sexy piece of code but their doesn't seem to be an automated way to find the row without just looping the table.</p> <pre><code> DataRowView newRowView = null; foreach (DataRowView tempRowView in myDataTable.DefaultView) { if (tempRowView.Row == rowToMatch) newRowView = tempRowView; } if (newRow != null) UseNewRowView(newRowView); else HandleRowNotFound(); </code></pre>
Alternative "architectural" approaches to javaScript client code? <p>How is your javaScript code organized? Does it follow patterns like MVC, or something else? </p> <p>I've been working on a side project for some time now, and the further I get, the more my webpage has turned into a full-featured application. Right now, I'm sticking with <a href="http://jquery.com">jQuery</a>, however, the logic on the page is growing to a point where some organization, or dare I say it, "architecture" is needed. My first approach is "MVC-ish":</p> <ul> <li>The 'model' is a JSON tree that gets extended with helpers</li> <li>The view is the DOM plus classes that tweak it</li> <li>The controller is the object where I connect events handling and kick off view or model manipulation</li> </ul> <p>I'm very interested, however, in how other people have built more substantial javaScript apps. I'm not interested in GWT, or other server-oriented approaches... just in the approach of "javaScript + &lt;generic web service-y thingy here&gt;"</p> <p>Note: earlier I said javaScript "is not really OO, not really functional". This, I think, distracted everyone. Let's put it this way, because javaScript is unique in many ways, and I'm coming from a strongly-typed background, I don't want to force paradigms I know but were developed in very different languages.</p>
<p>..but Javascript has many facets that <strong>are</strong> OO.</p> <p>Consider this:</p> <pre><code>var Vehicle = jQuery.Class.create({ init: function(name) { this.name = name; } }); var Car = Vehicle.extend({ fillGas: function(){ this.gas = 100; } }); </code></pre> <p>I've used this technique to create page-level javascript classes that have their own state, this helps keep it contained (and I often identify areas that I can reuse and put into other classes).</p> <p>This is also especially useful when you have components/server controls that have their own script to execute, but when you might have multiple instances on the same page. This keeps the state separate.</p>
Does ReadUncommitted imply NoLock <p>When writing a SQL statement in SQL Server 2005, does the READUNCOMMITTED query hint imply NOLOCK or do I have to specify it manually too?</p> <p>So is:</p> <pre><code>With (NoLock, ReadUnCommitted) </code></pre> <p>the same as:</p> <pre><code>With (ReadUnCommitted) </code></pre>
<p>According to Kalen Delaney...</p> <p>The NOLOCK hint has nothing to do with the index options. The hint tells SQL Server not to request locks when doing SELECT operations, so there will be no conflict with data that is already locked. The index options just tell SQL Server that this level of locking is allowed, when locking is going to occur. For example, if ALLOW_ROW_LOCKS was off, the only possible locks would be page or table locks. The index options don't force locks to be held, they just control the possible size of the locks.</p> <p>In answer to the question in your subject, the NOLOCK hint and the READUNCOMMITTED hint are equivalent.</p>
How to make 'pretty urls' work in php hosted in IIS? <p>Is there some way I can use urls like: </p> <p><em><a href="http://www.blog.com/team-spirit/" rel="nofollow">http://www.blog.com/team-spirit/</a></em></p> <p>instead of</p> <p><em><a href="http://www.blog.com/?p=122" rel="nofollow">http://www.blog.com/?p=122</a></em></p> <p>in a windows hosted PHP server?</p>
<p><a href="http://www.codeplex.com/IIRF" rel="nofollow">Isapi Rewrite Filter on CodePlex</a> - actively developed, free ("DonationWare"), open source.</p>
Mocking Asp.net-mvc Controller Context <p>So the controller context depends on some asp.net internals. What are some ways to cleanly mock these up for unit tests? Seems like its very easy to clog up tests with tons of setup when I only need, for example, Request.HttpMethod to return "GET".</p> <p>I've seen some examples/helpers out on the nets, but some are dated. Figured this would be a good place to keep the latest and greatest.</p> <p>I'm using latest version of rhino mocks</p>
<p>Using MoQ it looks something like this:</p> <pre><code>var request = new Mock&lt;HttpRequestBase&gt;(); request.Expect(r =&gt; r.HttpMethod).Returns("GET"); var mockHttpContext = new Mock&lt;HttpContextBase&gt;(); mockHttpContext.Expect(c =&gt; c.Request).Returns(request.Object); var controllerContext = new ControllerContext(mockHttpContext.Object , new RouteData(), new Mock&lt;ControllerBase&gt;().Object); </code></pre> <p>I think the Rhino Mocks syntax is similar.</p>
How can I take a byte array of a TIFF image and turn it into a System.Drawing.Image object? <p>I have a <code>byte[]</code> array, the contents of which represent a TIFF file (as in, if I write out these bytes directly to a file using the <code>BinaryWriter</code> object, it forms a perfectly valid TIFF file) and I'm trying to turn it into a System.Drawing.Image object so that I can use it for later manipulation (feeding into a multipage TIFF object)</p> <p>The problem I'm having is that the commonly accepted code for this task:</p> <pre><code> public Image byteArrayToImage(byte[] byteArrayIn) { MemoryStream ms = new MemoryStream(byteArrayIn); Image returnImage = Image.FromStream(ms, true); return returnImage; } </code></pre> <p>doesn't work for me. The second line of the above method where it calls the <code>Image.FromStream</code> method dies at runtime, saying</p> <pre><code>Parameter Not Valid </code></pre> <p>I believe that the method is choking on the fact that this is a TIFF file but I cannot figure out how to make the <code>FromStream</code> method accept this fact.</p> <p>How do I turn a byte array of a TIFF image into an Image object?</p> <p>Also, like I said the end goal of this is to have a byte array representing a multipage TIFF file, which contains the TIFF files for which I have byte array objects of right now. If there's a much better way to go about doing this, I'm all for it.</p>
<p><strong>Edit:</strong> The assumption below is not correct, I had a chance to fire up my IDE later and tested with and without Write and both populated the MemoryStream correctly.</p> <p>I think you need to write to your MemeoryStream first.</p> <p>As if my memory (no pun intended) serves me correctly this:</p> <pre><code>MemoryStream ms = new MemoryStream(byteArrayIn); </code></pre> <p>Creates a memory stream of that size.</p> <p>You then need to write your byte array contents to the memory stream:</p> <pre><code>ms.Write(byteArrayIn, 0, byteArrayIn.Length); </code></pre> <p>See if that fixes it.</p>
SQL Server 2003 internet connection <p>Recently we got a new server at the office purely for testing purposes. It is set up so that we can access it from any computer. </p> <p>However today our ip got blocked from one of our other sites saying that our ip has been suspected of having a virus that sends spam emails. we learned this from the cbl <a href="http://cbl.abuseat.org/" rel="nofollow">http://cbl.abuseat.org/</a> </p> <p>So of course we turned the server off to stop this. The problem is the server must be on to continue developing our application and to access the database that is installed on it. Our normal admin is on vacation and is unreachable, and the rest of us are idiots(me included) in this area. </p> <p>We believe that the best solution is to remove it from connecting to the internet but still access it on the lan. If that is a valid solution how would this be done or is there a better way? say blocking specified ports or whatever.</p>
<p>I assume that this server is behind a router? You should be able to block <code>WAN</code> connections to the server on the router and still leave it open to accepting <code>LAN</code> connection. Or you could restrict the <code>IPs</code> that can connect to the server to the development machines on the network.</p>
Alternatives to System.exit(1) <p>For various reasons calling <code>System.exit</code> is frowned upon when writing <strong>Java Applications</strong>, so how can I notify the calling process that not everything is going according to plan?</p> <p><strong>Edit:</strong> The 1 is a <code>standin</code> for any non-zero exit code.</p>
<p>The use of System.exit is frowned upon when the 'application' is really a sub-application (e.g. servlet, applet) of a larger Java application (server): in this case the System.exit could stop the JVM and hence also all other sub-applications. In this situation, throwing an appropriate exception, which could be caught and handled by the application framework/server is the best option.</p> <p>If the java application is really meant to be run as a standalone application, there is nothing wrong with using System.exit. in this case, setting an exit value is probably the easiest (and also most used) way of communicating failure or success to the parent process.</p>
What is a good dvd burning component for Windows or .Net? <p>I'd like to add dvd burning functionality to my .Net app (running on Windows Server 2003), are there any good components available? I've used the NeroCOM sdk that used to come with Nero but they no longer support the sdk in the latest versions of Nero. I learned that Microsoft has created an IMAPI2 upgrade for Windows XP/2003 and there is an <a href="http://www.codeproject.com/KB/miscctrl/imapi2.aspx" rel="nofollow">example project</a> at CodeProject but not having used it myself I can't say how easy/reliable it is to use.</p> <p>I'm not really worried about burning audio/video to DVD as this is for file backup purposes only.</p>
<p>I've used the code from the codeproject <a href="http://www.codeproject.com/KB/miscctrl/imapi2.aspx" rel="nofollow">article</a> and it works pretty well. It's a nice wrapper around the IMAPI2, so as longs as IMAPI2 supports what you need to do, the .NET wrapper will do it.</p>
Setting the height of a DIV dynamically <p>In a web application, I have a page that contains a DIV that has an auto-width depending on the width of the browser window.</p> <p>I need an auto-height for the object. The DIV starts about 300px from the top screen, and it's height should make it stretch to the bottom of the browser screen. I have a max height for the container DIV, so there would have to be minimum-height for the div. I believe I can just restrict that in CSS, and use Javascript to handle the resizing of the DIV.</p> <p>My javascript isn't nearly as good as it should be. Is there an easy script I could write that would do this for me?</p> <p>Edit: The DIV houses a control that does it's own overflow handling (implements its own scroll bar).</p>
<p>Try this simple, specific function:</p> <pre><code>function resizeElementHeight(element) { var height = 0; var body = window.document.body; if (window.innerHeight) { height = window.innerHeight; } else if (body.parentElement.clientHeight) { height = body.parentElement.clientHeight; } else if (body &amp;&amp; body.clientHeight) { height = body.clientHeight; } element.style.height = ((height - element.offsetTop) + "px"); } </code></pre> <p>It does not depend on the current distance from the top of the body being specified (in case your 300px changes).</p> <p><hr /></p> <p>EDIT: By the way, you would want to call this on that div every time the user changed the browser's size, so you would need to wire up the event handler for that, of course.</p>
How to pass method name to custom server control in asp.net? <p>I am working on a Customer Server Control that extends another control. There is no problem with attaching to other controls on the form.</p> <p>in vb.net: Parent.FindControl(TargetControlName)</p> <p>I would like to pass a method to the control in the ASPX markup. </p> <p>for example: &lt;c:MyCustomerControl runat=server InitializeStuffCallback="InitializeStuff"&gt;</p> <p>So, I tried using reflection to access the given method name from the Parent.</p> <p>Something like (in VB)</p> <pre><code>Dim pageType As Type = Page.GetType Dim CallbackMethodInfo As MethodInfo = pageType.GetMethod( "MethodName" ) 'Also tried sender.Parent.GetType.GetMethod("MethodName") sender.Parent.Parent.GetType.GetMethod("MethodName") </code></pre> <p>The method isn't found, because it just isn't apart of the Page. Where should I be looking? I'm fairly sure this is possible because I've seen other controls do similar.</p> <p><hr /></p> <p>I forgot to mention, my work-around is to give the control events and attaching to them in the Code-behind.</p>
<p>If you want to be able to pass a method in the ASPX markup, you need to use the <code>Browsable</code> attribute in your code on the event.</p> <p>VB.NET</p> <pre><code>&lt;Browsable(True)&gt; Public Event InitializeStuffCallback </code></pre> <p>C#</p> <pre><code>[Browsable(true)] public event EventHandler InitializeStuffCallback; </code></pre> <p>Reference: <a href="http://msdn.microsoft.com/en-us/library/tk67c2t8.aspx" rel="nofollow">Design-Time Attributes for Components</a> and <a href="http://msdn.microsoft.com/en-us/library/system.componentmodel.browsableattribute.aspx" rel="nofollow">BrowsableAttribute Class</a></p> <p>All the events, properties, or whatever need to be in the code-behind of the control with the browsable attribute to make it so you can change it in the tag code.</p>
Caching Active Directory Data <p>In one of my applications, I am querying active directory to get a list of all users below a given user (using the "Direct Reports" thing). So basically, given the name of the person, it is looked up in AD, then the Direct Reports are read. But then for every direct report, the tool needs to check the direct reports of the direct reports. Or, more abstract: The Tool will use a person as the root of the tree and then walk down the complete tree to get the names of all the leaves (can be several hundred)</p> <p>Now, my concern is obviously performance, as this needs to be done quite a few times. My idea is to manually cache that (essentially just put all the names in a long string and store that somewhere and update it once a day).</p> <p>But I just wonder if there is a more elegant way to first get the information and then cache it, possibly using something in the System.DirectoryServices Namespace?</p>
<p>In order to take control over the properties that you want to be cached you can call 'RefreshCache()' passing the properties that you want to hang around:</p> <pre class="lang-c# prettyprint-override"><code>System.DirectoryServices.DirectoryEntry entry = new System.DirectoryServices.DirectoryEntry(); // Push the property values from AD back to cache. entry.RefreshCache(new string[] {"cn", "www" }); </code></pre>
Best use pattern for a DataContext <p>What's the best lifetime model for a DataContext? Should I just create a new one whenever I need it (aka, function level), should I keep one available in each class that would use it (class level), or should I create a static class with a static DataContext (app-domain level)? Are there any considered best practices on this?</p>
<p>You pretty much need to keep the same data context available throughout the lifetime of the operations you want to perform if you're ever going to be storing changes which are to be .SubmitChanges()'d later, as otherwise you will lose those changes.</p> <p>If you're just querying stuff then it's fine to create them as needed, but then if later you want to .SubmitChanges() you'll have to refactor your code a lot, so you may as well adopt the pattern of effectively keeping the datacontext global throughout your app from the beginning.</p> <p>Note the data context is <em>disconnected</em>. The connection is only made when the query data is <em>enumerated</em> (not when you first run the query, it's a 'lazy' data type so only provides data when it's needed), and then closed immediately afterwards. On .SubmitChanges() the connection is opened to submit the changes then closed immediately afterwards. So don't think keeping the datacontext around keeps a connection open, it doesn't (you can hook the StateChange event of the connection to confirm this for yourself, that's how I'm sure).</p> <p>There is a great article over at <a href="http://www.west-wind.com/weblog/posts/246222.aspx" rel="nofollow">Rick Strahl's Blog</a> which covers this topic in depth, far more than my answer here provides!!</p>
What is the best approach to both modularity and platform independence? <p>I hope this question does not come off as broad as it may seem at first. I am designing a software application in my <code>&lt;sarcasm&gt;</code><em>voluminous</em><code>&lt;/sarcasm&gt;</code> spare time. I would like it to be both cross-platform and modular. At this point, because I am still in the planning phase, I can pick practically any language and toolset.</p> <p>This makes things harder, not easier, because there are seemingly so many ways of accomplishing both of the goals (modularity, platform agnosticism). </p> <p>My basic premise is that security, data storage, interaction with the operating system, and configuration should all be handled by a "container" application - but most of the other functionality will be supplied through plug-in modules. If I had to describe it at a high level (without completely giving away my idea), it would be a single application that can do many different jobs, all dedicated to the same goal (there are lots of disparate things to do, but all the data has to interact and be highly available).</p> <p>This is not a new idea, and not particularly exotic. Yet I find myself wrestling with not so much how to do it (I can think of lots of ways), but which method is best.</p> <p>For example, I know that Eclipse practically embodies what I am describing, but I find Java applications in general (and Eclipse is no exception) to be too large and slow for what I need. Ditto desktop apps written Python and Ruby (which are excellent languages!) </p> <p>I don't mind recompiling the code base for different platforms as native exectables. Yet, C and C++ have their own set of issues.</p> <p>As a C# developer, I have a preference for managed code. But I am not at all sold on Mono, yet (I could be convinced).</p> <p>Does anyone have any ideas/experiences/ specific favorite frameworks to share?</p>
<p>Are you planning a desktop or web application? </p> <p>Everyone around here seems to think that Mono is great, but I still do not think it is ready for industry use, I would equate mono to where wine is, great idea; when it works it works well, and when it doesn't...well your out of luck. mod_mono for Apache is extremely glitchy and is hard to get running correctly.</p> <p>If your aiming for the desktop, nothing beats the eclipse RCP (Rich Client Platform) framework: <a href="http://wiki.eclipse.org/index.php/Rich_Client_Platform" rel="nofollow">http://wiki.eclipse.org/index.php/Rich_Client_Platform</a>. </p> <p>You can build window, linux, mac all under the same code and all UI components are native to the OS. And RCP wins in modularity hands down, it has a plug-in architecture that is unrivaled (from what I have seen)</p> <p>I have worked with RCP for 1.5 years now and I dunno what else could replace it, it is #1 in it's niche.</p> <p>If your totally opposed to java I would look into wxWidgets with either python or C++ </p>
Best open-source Mathematica equivalent <p>What is the best open-source equivalent for Mathematica? My requirements are:</p> <ol> <li>(most important) Must be a real computer algebra system (CAS). Notably, I don't want Matlab clones -- I want something that can, at least, symbolically differentiate and integrate.</li> <li>Must be programmable. A functional-programming view of the world, like Mathematica's, would be awesome. The basic datatype of M'ica is the list, which is very convenient!</li> <li>(least important) Similar syntax would be nice.</li> </ol> <p>The ability to deal with objects such as groups or graphs would be a great bonus, but my primary emphasis is on the main things Mathematica and Maple do: algebra and calculus, both symbolic and numeric. Also, plotting is not high on my list of requirements, as I'm mostly a terminal and not GUI user.</p>
<p>SAGE is definitely one you should consider since it actually includes the full version of Maxima within it (along with interfaces to various other mathematical packages). To answer your questions:</p> <p>1) SAGE can symbolically <a href="http://www.sagemath.org/doc/tutorial/tour_algebra.html#differentiation-integration-etc">differentiate and integrate</a>.</p> <p>2) Programming in SAGE is done via Python.</p> <p>3) The syntax is rather different to Mathematica's (which is essentially LISP-like) but here is a blog post written by a heavy user of Mathematica so you can see what he thinks: <a href="http://www.walkingrandomly.com/?p=103">Walking Randomly: Interacting with SAGE</a></p>
Drawing a custom label on a pie chart in Yahoo's Flash Library ASTRA <p>Has anyone looked at <a href="http://developer.yahoo.com/flash/" rel="nofollow">Yahoo's ASTRA</a>? It's fairly nifty, but I had some issues creating a custom label for a pie chart. They have an example for a line chart, which overrides an axis's series's label renderer. My solution was to override the <code>myPieChart.dataTipFunction</code>. For data that looks like:</p> <pre><code>myPieChart.dataProvider = [ { category: "Groceries", cost: 50 }, { category: "Transportation", cost: 175} ] myPieChart.dataField = "cost"; myPieChart.categoryField = "category"; </code></pre> <p>I wrote a function like this:</p> <pre><code>import com.yahoo.astra.fl.charts.series.* myPieChart.dataTipFunction = function (obj:Object, index:int, series:ISeries):String { return obj.category + "\n$" + obj.cost; }; </code></pre> <p>There's ceil(2.718281828459045) problems with this:</p> <ol> <li><p>I'm directly calling the category and cost properties of the data provider. The names are actually configurable when setting up the chart, I'd like to maintain that flexibility.</p></li> <li><p>The default data tip would show the category, the cost (without a dollar sign), and the percentage it makes up in the pie chart. So here, I've lost the percentage. I just have no idea which property of what would hold that. It might be part of the series.</p></li> <li><p>I probably only need to override the <code>dataItemRenderer</code> for the cost part of the series, but I don't know how to access it. The documentation is a little ... lacking there.</p></li> </ol> <p>Normally I would just look at the default implementation of the <code>dataTipFunction</code> but it's all inside a compiled shm that's part of the components distributed from yahoo.</p> <p>Can anyone help me complete this overridden function with percentage information and the flexibility mentioned in point 1?</p>
<p>Okay... so no-one's tried Astra, or people just avoid Flash questions.</p> <p>After a lot of guess work it turns out I needed to cast the series to a PieSeries and then work with those member functions, as the ISeries was useless on it's own.</p> <pre><code>myPieChart.dataTipFunction = function (item:Object, index:int, series:ISeries):String { var oPieSeries:PieSeries = series as PieSeries; return oPieSeries.itemToCategory(item,index) + "\n$" + oPieSeries.itemToData(item) + "\n" + Number(oPieSeries.itemToPercentage(item)).toFixed(2) + "%"; }; </code></pre>
What's the maximum amount of RAM I can use in a Windows box? <p>Obviously, that's 64-bit windows.</p> <p>Also, what's the maximum amount of memory a single 64-bit process can use? I was kind of counting on using it all... (Yes, I know what I'm doing, please don't tell me that if I need that much RAM i must be doing something wrong)</p> <p>Also, is this the same for a .Net 2.0 process? Or is there a lower limit for .Net?</p>
<p>What version of windows? it differs from XP to vista and from home to business versions of vista, and I would guess again for server.</p> <p>see <a href="http://msdn.microsoft.com/en-us/library/aa366778.aspx" rel="nofollow">here for more info on maximum ram for diffrent windows versions</a></p> <p>for Windows Server 2008 Datacenter MS quote 2 TB of physical memory.</p>
Change templates in Xcode <p>How would I change the initial templates created by Xcode when creating a new Cocoa Class.</p> <p>I am referring to the comments and class name created when using Xcode's new class wizard.</p>
<p>You wouldn't change the existing templates. In other words, don't <em>modify</em> anything under the <code>/Developer</code> hierarchy (or wherever you installed your developer tools).</p> <p>Instead, clone the templates you want to have customized variants of. Then change their names and the information in them. Finally, put them in the appropriate location in your account's <code>Library/Application Support</code> folder, specifically:</p> <ul> <li>File templates: <code>~/Library/Application Support/Developer/Shared/Xcode/File Templates/</code></li> <li>Target templates: <code>~/Library/Application Support/Developer/Shared/Xcode/Target Templates/</code></li> <li>Project templates: <code>~/Library/Application Support/Developer/Shared/Xcode/Project Templates/</code></li> </ul> <p>That way they won't be overwritten when you install new developer tools, and you can tweak them to your heart's content.</p>
How can I use `scp` to deploy a website's `.htaccess` file? <p>I am currently using the following command to upload my site content:</p> <pre><code>scp -r web/* [email protected]:site.com/ </code></pre> <p>This works great except that the .htaccess file is not sent. Presumably, this is because it's hidden.</p> <p>I have tried adding a second line to send the file explicitely:</p> <pre><code>scp -r web/.htaccess [email protected]:site.com/.htaccess </code></pre> <p>This works great except now I have to enter my password twice.</p> <p>Any thoughts on how to make this deploy with only 1 or 0 entries of my password?</p>
<p>Just combine the two commands:</p> <pre><code>scp -r web/* web/.htaccess [email protected]:site.com/ </code></pre> <p>If you want 0 entries of your password you can set up <a href="http://sial.org/howto/openssh/publickey-auth/" rel="nofollow">public key authentication</a> for ssh/scp.</p>
Is it possible to call Javascript's onsubmit event programatically on a form? <p>In Ruby on Rails, I'm attempting to update the <code>innerHTML</code> of a div tag using the <code>form_remote_tag</code> helper. This update happens whenever an associated select tag receives an onchange event. The problem is, <code>&lt;select onchange="this.form.submit();"&gt;</code>; doesn't work. Nor does <code>document.forms[0].submit()</code>. The only way to get the onsubmit code generated in the form_remote_tag to execute is to create a hidden submit button, and invoke the click method on the button from the select tag. Here's a working ERb partial example.</p> <pre><code>&lt;% form_remote_tag :url =&gt; product_path, :update =&gt; 'content', :method =&gt; 'get' do -%&gt; &lt;% content_tag :div, :id =&gt; 'content' do -%&gt; &lt;%= select_tag :update, options_for_select([["foo", 1], ["bar", 2]]), :onchange =&gt; "this.form.commit.click" %&gt; &lt;%= submit_tag 'submit_button', :style =&gt; "display: none" %&gt; &lt;% end %&gt; &lt;% end %&gt; </code></pre> <p>What I want to do is something like this, but it doesn't work.</p> <pre><code>&lt;% form_remote_tag :url =&gt; product_path, :update =&gt; 'content', :method =&gt; 'get' do -%&gt; &lt;% content_tag :div, :id =&gt; 'content' do -%&gt; # the following line does not work &lt;%= select_tag :update, options_for_select([["foo", 1], ["bar", 2]]), :onchange =&gt; "this.form.onsubmit()" %&gt; &lt;% end %&gt; &lt;% end %&gt; </code></pre> <p>So, is there any way to remove the invisible submit button for this use case?</p> <p>There seems to be some confusion. So, let me explain. The basic problem is that <code>submit()</code> doesn't call the <code>onsubmit()</code> code rendered into the form.</p> <p>The actual HTML form that Rails renders from this ERb looks like this:</p> <pre><code>&lt;form action="/products/1" method="post" onsubmit="new Ajax.Updater('content', '/products/1', {asynchronous:true, evalScripts:true, method:'get', parameters:Form.serialize(this)}); return false;"&gt; &lt;div style="margin:0;padding:0"&gt; &lt;input name="authenticity_token" type="hidden" value="4eacf78eb87e9262a0b631a8a6e417e9a5957cab" /&gt; &lt;/div&gt; &lt;div id="content"&gt; &lt;select id="update" name="update" onchange="this.form.commit.click"&gt; &lt;option value="1"&gt;foo&lt;/option&gt; &lt;option value="2"&gt;bar&lt;/option&gt; &lt;/select&gt; &lt;input name="commit" style="display: none" type="submit" value="submit_button" /&gt; &lt;/div&gt; &lt;/form&gt; </code></pre> <p>I want to axe the invisible submit button, but using a straight form.submit appears to not work. So, I need some way to call the form's onsubmit event code.</p> <p>Update: Orion Edwards solution would work if there wasn't a <code>return(false);</code> generated by Rails. I'm not sure which is worse though, sending a phantom click to an invisible submit button or calling eval on the <code>getAttribute('onsubmit')</code> call after removing the return call with a javascript string replacement! </p>
<p>I realize this question is kind of old, but what the heck are you doing eval for?</p> <pre><code>document.getElementById('formId').onsubmit(); document.getElementById('formId').submit(); </code></pre> <p>or</p> <pre><code>document.formName.onsubmit(); document.formName.submit(); </code></pre> <p>When the DOM of a document is loaded, the events are not strings any more, they are functions.</p> <pre><code>alert(typeof document.formName.onsubmit); // function </code></pre> <p>So there's no reason to convert a function to a string just so you can eval it.</p>
How do you get the ethernet address using Java? <p>I would like to retrieve the ethernet address of the network interface that is used to access a particular website.</p> <p>How can this be done in Java?</p> <p><strong>Solution</strong> Note that the accepted solution of <code>getHardwareAddress</code> is only available in Java 6. There does not seem to be a solution for Java 5 aside from executing i(f|p)confing.</p>
<p><a href="http://java.sun.com/javase/6/docs/api/java/net/NetworkInterface.html#getHardwareAddress%28%29"> java.net.NetworkInterface.getHardwareAddress</a> (method added in Java 6)</p> <p>It has to be called on the machine you are interested in - the MAC is not transferred across network boundaries (i.e. LAN and WAN). If you want to make use of it on a website server to interrogate the clients, you'd have to run an applet that would report the result back to you.</p> <p>For Java 5 and older I found code <a href="http://forums.sun.com/thread.jspa?messageID=3424868#4204392">parsing output of command line tools on various systems</a>.</p>
Can't create a subversion repository with Eclipse 3.4.0, svn 1.5.1 <p>I'm working on mac OS x 10.4. I have a subversion repository stored on an external drive connected via USB. I created a new python project in Eclipse (using the PyDev plugin). When I use right click Team->Share Project to set up a new prject with subversion, I get the following error:</p> <p>Error while creating module: org.tigris.subversion.javahl.ClientException: Couldn't open a repository svn: Unable to open ra_local session to URL svn: Unable to open repository 'file:///Volumes/svn-repos/Palindrome/Palindrome'</p> <p>The subversion repository has the following permisions: drwxrwxrwx 9 cameronl cameronl 306 Aug 23 10:08 svn-repos</p> <p>The external drive is formatted as Mac OS extended.</p> <p>I'm completely stumped. Anybody have any suggestions?</p>
<p>Try adding the repository first using the "SVN Repository Exploring" perspective (Window > Open Perspective > Other... > SVN Repository Exploring).</p> <p>Make sure that the URL you are using points to the correct directory, which typically contains these default repository files:</p> <pre><code>conf/ dav/ db/ format hooks/ locks/ README.txt </code></pre> <p>Hope this helps.</p>
Are Python threads buggy? <p>A reliable coder friend told me that Python's current multi-threading implementation is seriously buggy - enough to avoid using altogether. What can said about this rumor?</p>
<p>Python threads are good for <strong>concurrent I/O programming</strong>. Threads are swapped out of the CPU as soon as they block waiting for input from file, network, etc. This allows other Python threads to use the CPU while others wait. This would allow you to write a multi-threaded web server or web crawler, for example.</p> <p>However, Python threads are serialized by the <a href="http://en.wikipedia.org/wiki/Global_Interpreter_Lock">GIL</a> when they enter interpreter core. This means that if two threads are crunching numbers, only one can run at any given moment. It also means that you can't take advantage of multi-core or multi-processor architectures.</p> <p>There are solutions like running multiple Python interpreters concurrently, using a C based threading library. This is not for the faint of heart and the benefits might not be worth the trouble. Let's hope for an all Python solution in a future release.</p>
HTML Scraping in Php <p>I've been doing some html scraping in PHP using regular expressions. This works, but the result is finicky and fragile. Has anyone used any packages that provide a more robust solution? A config driven solution would be ideal, but I'm not picky.</p>
<p>I would recomend <a href="https://sourceforge.net/projects/simplehtmldom/">PHP Simple HTML DOM Parser</a> after you have scraped the HTML from the page. It supports invalid HTML, and provides a very easy way to handle HTML elements. </p>
COMException "Library not registered." while using System.DirectoryServices <p>I have only just started received the following error in my windows forms application under dot net 2 framework on windows 2000 when using System.DirectoryServices.</p> <pre><code> {System.Runtime.InteropServices.COMException} System.Runtime.InteropServices.COMException: {"Library not registered."} _className: Nothing _COMPlusExceptionCode: -532459699 _data: Nothing _dynamicMethods: Nothing _exceptionMethod: Nothing _exceptionMethodString: Nothing _helpURL: Nothing _HResult: -2147319779 _innerException: Nothing _message: "Library not registered." _remoteStackIndex: 0 _remoteStackTraceString: Nothing _source: Nothing _stackTrace: {System.Array} _stackTraceString: Nothing _xcode: -532459699 _xptrs: 0 Source: "System.DirectoryServices" StackTrace: " at System.DirectoryServices.DirectoryEntry.Bind(Boolean throwIfFail) </code></pre> <p>at System.DirectoryServices.DirectoryEntry.Bind() at System.DirectoryServices.DirectoryEntry.get_AdsObject() at System.DirectoryServices.DirectorySearcher.FindAll(Boolean findMoreThanOne) at System.DirectoryServices.DirectorySearcher.FindAll()</p> <p>I have re-installed the framework and re-registered activeds.dll however this has not resolved the issue. I am guessing I need to find another dll and re-register it however it is not clear which dll this would be.</p>
<p>Having used <a href="http://www.red-gate.com/products/reflector/" rel="nofollow">Reflector</a> to have a quick peak at the Directory Services code, it looks like your Active Directory Service Interfaces installation might be kaput.</p> <p>You can download version 2.5 from <a href="http://technet.microsoft.com/en-us/library/cc749949.aspx" rel="nofollow">Technet</a> although I'm not sure if it's the latest version or if it works with Windows 2000.</p>
Has .NET made raw COM and DCOM programming redundant? <p>Has the introduction of the .net framework made raw programming in COM and DCOM redundant ? </p> <p>(Except for using some COM+ services, e.g. for transaction management through the System.EnterpriseServices namespace)</p>
<p>Not yet, because the OS is still unmanaged.</p> <p>If MS finally do what their labs have been talking about for years and produce a fully managed OS then it will.</p> <p>That OS won't be backwards compatible though. They would have to produce managed versions of Office, IE, etc first. They will have to produce a virtual machine to run unmanaged apps.</p> <p>The pain would be something similar to the move from Mac OS9 to OSX.</p>
How to make user controls know about css classes in ASP.NET <p>Since there are no header sections for user controls in asp.net, user controls have no way of knowing about stylesheet files. So css classes in the user controls are not recognized by visual studio and produces warnings. How can I make a user control know that it will relate to a css class, so if it is warning me about a non-existing css class, it means that the class really do not exist?</p> <p>Edit: Or should I go for a different design like exposing css classes as properties like "HeaderStyle-CssClass" of GridView?</p>
<p>Here's what I did:</p> <pre><code>&lt;link rel="Stylesheet" type="text/css" href="Stylesheet.css" id="style" runat="server" visible="false" /&gt; </code></pre> <p>It fools Visual Studio into thinking you've added a stylesheet to the page but it doesn't get rendered.</p> <p><hr /></p> <p>Here's an even more concise way to do this with multiple references;</p> <pre><code>&lt;% if (false) { %&gt; &lt;link rel="Stylesheet" type="text/css" href="Stylesheet.css" /&gt; &lt;script type="text/javascript" src="js/jquery-1.2.6.js" /&gt; &lt;% } %&gt; </code></pre> <p>As seen in <a href="http://haacked.com/archive/2008/11/21/combining-jquery-form-validation-and-ajax-submission-with-asp.net.aspx">this blog post</a> from Phil Haack.</p>
How do I create a SHA1 hash in ruby? <p><a href="http://en.wikipedia.org/wiki/SHA-1">SHA Hash functions</a></p>
<pre><code>require 'digest/sha1' Digest::SHA1.hexdigest 'foo' </code></pre>
What is a race condition? <p>When writing multi-threaded applications, one of the most common problems experienced are race conditions. </p> <p>My questions to the community are:</p> <p>What is a race condition? How do you detect them? How do you handle them? Finally, how do you prevent them from occurring?</p>
<p>A race condition occurs when two or more threads can access shared data and they try to change it at the same time. Because the thread scheduling algorithm can swap between threads at any time, you don't know the order in which the threads will attempt to access the shared data. Therefore, the result of the change in data is dependent on the thread scheduling algorithm, i.e. both threads are "racing" to access/change the data. </p> <p>Problems often occur when one thread does a "check-then-act" (e.g. "check" if the value is X, then "act" to do something that depends on the value being X) and another thread does something to the value in between the "check" and the "act". E.g:</p> <pre><code>if (x == 5) // The "Check" { y = x * 2; // The "Act" // If another thread changed x in between "if (x == 5)" and "y = x * 2" above, // y will not be equal to 10. } </code></pre> <p>The point being, y could be 10, or it could be anything, depending on whether another thread changed x in between the check and act. You have no real way of knowing.</p> <p>In order to prevent race conditions from occurring, you would typically put a lock around the shared data to ensure only one thread can access the data at a time. This would mean something like this:</p> <pre><code>// Obtain lock for x if (x == 5) { y = x * 2; // Now, nothing can change x until the lock is released. // Therefore y = 10 } // release lock for x </code></pre>
What is the best quick-read Python book out there? <p>I am taking a class that requires Python. We will review the language in class next week, and I am a quick study on new languages, but I was wondering if there are any really great Python books I can grab while I am struggling through the basics of setting up my IDE, server environment and all those other "gotchas" that come with a new programming language. Suggestions?</p>
<p>I loved <a href="http://www.diveintopython.net/toc/index.html" rel="nofollow">Dive Into Python</a>, especially if you're a quick study. The beginning basics are all covered (and may move slowly for you), but the latter few chapters are great learning tools.</p> <p>Plus, Pilgrim is a pretty good writer.</p>
Can you pair program remotely? <p>We have a team of about 7 engineers, whom I supervise. We do not have a formal office where we all work. Instead, a handful are located outside of our city, while the rest of us are scattered around the Bay Area.</p> <p>Quite frequently, I find myself attempting to teach concepts like TDD or refactoring to some of our more junior (or not) developers. The best technique I know is pair programming, where you both sit at the same computer and work on a problem together. Since we are not in the same place most of the time, the only option is to use some kind of screen sharing and Skype to have one of us "drive" while the other consults, and then switch.</p> <p>My question is has anyone tried this "virtual" pair programming, and did you find it at all useful?</p>
<p>I've done quite a lot of pair-programming not only cross-site but cross-timezone. I live in Israel and I work with people on the West Coast all the time. The best way I've found is to use shared VNC session and skype. You need some "good behavior" to ensure that only one of us types at a given time. The VNC server that we use gives us two different pointers so we can move our respective mice without getting in the way, so long as we don't actually click.<br /> The main problem is that the clipboard is shared, so if someone selects something it's automatically copied to the other's clipboard.<br /> As a general rule, pair programming cross site, while not ideal, is certainly workable, and most definitely useful.</p>
duplicating jQuery datepicker <p>The <code>datepicker</code> function only works on the first input box that is created.</p> <p>I'm trying to duplicate a datepicker by cloning the <code>div</code> that is containing it.</p> <pre><code>&lt;a href="#" id="dupMe"&gt;click&lt;/a&gt; &lt;div id="template"&gt; input-text &lt;input type="text" value="text1" id="txt" /&gt; date time picker &lt;input type="text" id="example" value="(add date)" /&gt; &lt;/div&gt; </code></pre> <p>To initialize the datepicker, according to the <a href="http://docs.jquery.com/UI/Datepicker" rel="nofollow">jQuery UI documentation</a> I only have to do <code>$('#example').datepicker();</code> and it does work, but only on the first datepicker that is created.</p> <p>The code to duplicate the <code>div</code> is the following:</p> <pre><code>$("a#dupMe").click(function(event){ event.preventDefault(); i++; var a = $("#template").clone(true).insertBefore("#template").hide().fadeIn(1000); a.find("input#txt").attr('value', i); a.find("input#example").datepicker(); }); </code></pre> <p>The strangest thing is that on the <code>document.ready</code> I have:</p> <pre><code>$('#template #example').datepicker(); $("#template #txt").click(function() { alert($(this).val()); }); </code></pre> <p>and if I click on the <code>#txt</code> it always works.</p>
<p>I use a CSS class instead:</p> <pre><code>&lt;input type="text" id="BeginDate" class="calendar" /&gt; &lt;input type="text" id="EndDate" class="calendar" /&gt; </code></pre> <p>Then, in your <code>document.ready</code> function:</p> <pre><code>$('.calendar').datepicker(); </code></pre> <p>Using it that way for multiple calendar fields works for me.</p>
How do I lock a file in Perl? <p>What is the best way to create a lock on a file in Perl?</p> <p>Is it best to flock on the file or to create a lock file to place a lock on and check for a lock on the lock file?</p>
<p>If you end up using flock, here's some code to do it:</p> <pre><code>use Fcntl ':flock'; # Import LOCK_* constants # We will use this file path in error messages and function calls. # Don't type it out more than once in your code. Use a variable. my $file = '/path/to/some/file'; # Open the file for appending. Note the file path is quoted # in the error message. This helps debug situations where you # have a stray space at the start or end of the path. open(my $fh, '&gt;&gt;', $file) or die "Could not open '$file' - $!"; # Get exclusive lock (will block until it does) flock($fh, LOCK_EX) or die "Could not lock '$file' - $!"; # Do something with the file here... # Do NOT use flock() to unlock the file if you wrote to the # file in the "do something" section above. This could create # a race condition. The close() call below will unlock the # file for you, but only after writing any buffered data. # In a world of buffered i/o, some or all of your data may not # be written until close() completes. Always, always, ALWAYS # check the return value of close() if you wrote to the file! close($fh) or die "Could not write '$file' - $!"; </code></pre> <p>Some useful links:</p> <ul> <li><a href="http://www.perlmonks.org/?node_id=7058">PerlMonks file locking tutorial</a> (somewhat old)</li> <li><a href="http://perldoc.perl.org/functions/flock.html"><code>flock()</code> documentation</a></li> </ul> <p>In response to your added question, I'd say either place the lock on the file or create a file that you call 'lock' whenever the file is locked and delete it when it is no longer locked (and then make sure your programs obey those semantics).</p>
Comparison of Javascript libraries <p>After the suggestion to use a library for <a href="http://stackoverflow.com/questions/34486/what-more-is-needed-for-ajax-than-this-function">my ajax needs</a> I am going to use one, the problem is that there are so many and I've no idea how to even begin telling them apart.</p> <p>Thus, can anybody <br /> A) Give a rundown of the differences or <br /> B) Point me (and others like me) somewhere that has such a list. <br /><br />Failing that plan C is to go with whichever gets mentioned the most here.</p>
<p>To answer B:</p> <p><a href="http://en.wikipedia.org/wiki/Comparison_of_JavaScript_frameworks"><strong>Comparison of JavaScript frameworks</strong></a></p> <p><hr /></p> <p><strong>EDIT:</strong> Although everyone and their mom is apparently riding the <a href="http://jquery.com/"><strong>jQuery</strong></a> bandwagon (I use <a href="http://www.mochikit.com"><strong>MochiKit</strong></a>), there are many libraries which provide the same functionality - the problem set which most libraries solve (async client-server communication, DOM manipulation, etc.) is the same, and there are few that don't have what you will need to get the job done. </p> <p>The important thing to determine for yourself is whether or not a library will fit your particular style and sensibilities. Wide-spread ignorance about how <a href="http://www.ecma-international.org/publications/standards/Ecma-262.htm"><strong>JavaScript</strong></a>, the language, actually works, coupled with the negative press resulting thereby, coupled with the now-immense popularity of jQuery leads most people down that road. Thankfully, it isn't a bad road to be on as there are a lot of travellers to keep you company when the abstractions leak and you need help. You probably can't go wrong choosing jQuery.</p>
programmatically merge .reg file into win32 registry <p>What's the best way to programmatically merge a .reg file into the registry? This is for unit testing; the .reg file is a test artifact which will be added then removed at the start and end of testing.</p> <p>Or, if there's a better way to unit test against the registry...</p>
<p>It is possible to remove registry keys using a .reg file, although I'm not sure how well it's documented. Here's how:</p> <pre><code>REGEDIT4 [-HKEY_CURRENT_USER\Software\&lt;otherpath&gt;] </code></pre> <p>The <code>-</code> in front of the key name tells <code>Regedit</code> that you want to remove the key.</p> <p>To run this silently, type:</p> <pre><code>regedit /s "myfile.reg" </code></pre>
Image processing in Silverlight 2 <p>Is it possible to do image processing in silverlight 2.0?</p> <p>What I want to do is take an image, crop it, and then send the new cropped image up to the server. I know I can fake it by clipping the image, but that only effects the rendering of the image. I want to create a new image.</p> <p>After further research I have answered my own question. Answer: <strong>No</strong>. Since all apis would be in <a href="http://msdn.microsoft.com/en-us/library/system.windows.media.imaging.aspx" rel="nofollow">System.Windows.Media.Imaging</a> and that namespace does not have the appropriate classes in Silverlight</p> <p>I'm going to use fjcore. <a href="http://code.google.com/p/fjcore/" rel="nofollow">http://code.google.com/p/fjcore/</a></p> <p>Thanks <a href="http://stackoverflow.com/users/585/jonas-folles" rel="nofollow">Jonas</a></p>
<p>Well, you can actually do local image processing in Silverlight 2... But there are no built in classes to help you. But you can load any image into a byte array, and start manipulating it, or implement your own image encoder.</p> <p>Joe Stegman got lots of great information about "editable images" in Silverlight over at <a href="http://blogs.msdn.com/jstegman/" rel="nofollow">http://blogs.msdn.com/jstegman/</a>. He does things like applying filters to images, generating mandlebrots and more.</p> <p>This blog discuss a JPEG Silverilght Encoder (FJCore) you can use to resize and recompress photos client size: <a href="http://fluxcapacity.net/2008/07/14/fjcore-to-the-rescue/" rel="nofollow">http://fluxcapacity.net/2008/07/14/fjcore-to-the-rescue/</a></p> <p>Another tool is "Fluxify" which lets you resize and upload photos using Silverilght 2. Can be found over at <a href="http://fluxtools.net/" rel="nofollow">http://fluxtools.net/</a></p> <p>So yes, client side image processing can definetly be done in Silverilght 2. Happy hacking!</p>
Verilog automatic task <p>What does it mean if a task is declared with the automatic keyword in Verilog?</p> <pre><code>task automatic do_things; input [31:0] number_of_things; reg [31:0] tmp_thing; begin // ... end endtask; </code></pre> <p>Note: This question is mostly because I'm curious if there are any hardware programmers on the site. :)</p>
<p>"automatic" does in fact mean "re-entrant". The term itself is stolen from software languages -- for example, C has the "auto" keyword for declaring variables as being allocated on the stack when the scope it's in is executed, and deallocated afterwards, so that multiple invocations of the same scope do not see persistent values of that variable. The reason you may not have heard of this keyword in C is that it is the default storage class for all types :-) The alternatives are "static", which means "allocate this variable statically (to a single global location in memory), and refer to this same memory location throughout the execution of the program, regardless of how many times the function is invoked", and "volatile", which means "this is a register elsewhere on my SoC or something on another device which I have no control over; compiler, please don't optimize reads to me away, even when you think you know my value from previous reads with no intermediate writes in the code".</p> <p>"automatic" is intended for recursive functions, but also for running the same function in different threads of execution concurrently. For instance, if you "fork" off N different blocks (using Verilog's fork->join statement), and have them all call the same function at the same time, the same problems arise as a function calling itself recursively.</p> <p>In many cases, your code will be just fine without declaring the task or function as "automatic", but it's good practice to put it in there unless you specifically need it to be otherwise.</p>
Retrieving HTTP status code from loaded iframe with Javascript <p>I used the jQuery Form plugin for asynchronous form submission. For forms that contain files, it copies the form to a hidden iframe, submits it, and copies back the iframe's contents. The problem is that I can't figure out how to find what HTTP status code was returned by the server. For example, if the server returns 404, the data from the iframe will be copied as normal and treated as a regular response.</p> <p>I've tried poking around in the iframe objects looking for some sort of <code>status_code</code> attribute, but haven't been able to find anything like that.</p> <p><hr /></p> <p>The <code>$.ajax()</code> function can't be used, because it does not support uploading files. The only way to asynchronously upload files that I know of is using the hidden <code>iframe</code> method.</p>
<p>You can't get page headers by JS, but you can distinguish error from success: Try something like this:</p> <pre><code>&lt;script type="text/javascript"&gt; var uploadStarted = false; function OnUploadStart(){ uploadStarted = true; } function OnUploadComplete(state,message){ if(state == 1) alert("Success: "+message); else if(state == 0 &amp;&amp; uploadStarted) alert("Error:"+( message ? message : "unknow" )); } &lt;/script&gt; &lt;iframe id="uploader" name="uploader" onload="OnUploadComplete(0)" style="width:0px;height:0px;border:none;"&gt;&lt;/iframe&gt; &lt;form id="sender" action="/upload.php" method="post" target="uploader" enctype="multipart/form-data" onsubmit="OnUploadStart()"&gt; &lt;input type="file" name="files[upload]"/&gt; &lt;input type="submit" value="Upload"/&gt; &lt;/form&gt; </code></pre> <p>On server side:</p> <pre><code>/* file: upload.php */ &lt;?php // do some stuff with file print '&lt;script type="text/javascript"&gt;'; if(success) print 'window.parent.OnUploadComplete(1,"File uploaded!");'; else print 'window.parent.OnUploadComplete(0, "File too large!");'; print '&lt;/script&gt;'; ?&gt; </code></pre>
How do you get the last record generated in a recursive CTE? <p>In the code below I am using a recursive CTE(Common Table Expression) in SQL Server 2005 to try and find the top level parent of a basic hierarchical structure. The rule of this hierarchy is that every CustID has a ParentID and if the CustID has no parent then the ParentID = CustID and it is the highest level.</p> <pre><code>DECLARE @LookupID int --Our test value SET @LookupID = 1 WITH cteLevelOne (ParentID, CustID) AS ( SELECT a.ParentID, a.CustID FROM tblCustomer AS a WHERE a.CustID = @LookupID UNION ALL SELECT a.ParentID, a.CustID FROM tblCustomer AS a INNER JOIN cteLevelOne AS c ON a.CustID = c.ParentID WHERE c.CustID &lt;&gt; a.CustomerID ) </code></pre> <p>So if tblCustomer looks like this: </p> <pre><code>ParentID CustID 5 5 1 8 5 4 4 1 </code></pre> <p>The result I get from the code above is: </p> <pre><code>ParentID CustID 4 1 5 4 5 5 </code></pre> <p>What I want is just the last row of that result: </p> <pre><code>ParentID CustID 5 5 </code></pre> <p>How do I just return the last record generated in the CTE (which would be highest level CustID)?</p> <p>Also note that there are multiple unrelated CustID hierarchies in this table so I can't just do a SELECT * FROM tblCustomer WHERE ParentID = CustID. I can't order by ParentID or CustID because the ID number is not related to where it is in the hierarchy.</p>
<p>If you just want want the highest recursion depth couldn't you do something like this?Then, when you actually query the CTE just look for the row with max(Depth)? Like so:</p> <pre><code>DECLARE @LookupID int --Our test value SET @LookupID = 1; WITH cteLevelOne (ParentID, CustID, Depth) AS ( SELECT a.ParentID, a.CustID, 1 FROM tblCustomer AS a WHERE a.CustID = @LookupID UNION ALL SELECT a.ParentID, a.CustID, c.Depth + 1 FROM tblCustomer AS a INNER JOIN cteLevelOne AS c ON a.CustID = c.ParentID WHERE c.CustID &lt;&gt; a.CustID ) select * from CTELevelone where Depth = (select max(Depth) from CTELevelone) </code></pre> <p>or, adapting what trevor suggests, this could be used with the same CTE: </p> <pre><code>select top 1 * from CTELevelone order by Depth desc </code></pre> <p>I don't think CustomerID was necessarily what you wanted to order by in the case you described, but I wasn't perfectly clear on the question either.</p>
Print Odd-Even numbers using signals <p>I need to to print natural nos. 1,2,...n such that the parent process prints all odd numbers and the child process prints all even numbers, and all of this needs to be done using POSIX signals. How would I go about accomplishing this?</p> <p>The output should be:</p> <p>Parent : 1<br> Child : 2<br> Parent : 3<br> ...</p>
<p>It would probably be more beneficial for you provide what you have so far and explain what doesn't work as expected but here is what I came up with:</p> <pre><code>#include &lt;stdio.h&gt; #include &lt;sys/types.h&gt; #include &lt;unistd.h&gt; #include &lt;signal.h&gt; #include &lt;stdlib.h&gt; #define READY_SIGNAL SIGUSR1 /* The ready flag is set when READY_SIGNAL is received. * It is needed so that when we wake up from sigsuspend * we know whether or not the signal received was READY_SIGNAL. */ volatile sig_atomic_t ready; void make_ready(int i) { ready = 1; } int main (int argc, char *argv[]) { pid_t cpid, ppid; /* pids of the child and parent */ /* Signal masks for sigprocmask and sigsuspend */ sigset_t block_mask, wait_mask; unsigned long c = 1; /* The counter */ unsigned long n = 100; /* The default max count value */ struct sigaction act; /* Override the default max count if provided */ if (argv[1]) n = strtoul(argv[1], NULL, 10); /* Prepare signal masks */ sigemptyset(&amp;wait_mask); sigemptyset(&amp;block_mask); sigaddset(&amp;block_mask, READY_SIGNAL); /* Set the signal mask for the parent to ignore READY_SIGNAL until * we are ready to receive it, the mask will be inherited by the child, * needed to avoid race conditions */ sigprocmask(SIG_BLOCK, &amp;block_mask, NULL); /* Register the signal handler, will be inherited by the child */ act.sa_flags = 0; act.sa_handler = make_ready; sigemptyset(&amp;act.sa_mask); sigaction(READY_SIGNAL, &amp;act, NULL); /* Get the parent's process id, needed for the child to send signals * to the parent process, could alternatively use getppid in the child */ ppid = getpid(); /* Call fork, storing the child's process id needed for the parent to * send signals to the child */ cpid = fork(); if (cpid &lt; 0) { perror("Fork failed"); exit(EXIT_FAILURE); } if (cpid == 0) { /* Child */ c = 2; /* Child's first number will always be 2 */ if (c &gt; n) exit(0); /* If c &gt; n we have nothing to do */ do { /* Suspend until we receive READY_SIGNAL */ while (!ready) sigsuspend(&amp;wait_mask); /* Print out number, flush for proper output sequencing when output is not a terminal. */ printf("Child: %lu\n", c); fflush(stdout); ready = 0; /* Reset ready flag */ c += 2; /* Increment counter */ /* Wake up parent process */ kill(ppid, READY_SIGNAL); } while (c &lt;= n); } else { /* Parent */ for (;;) { /* Print out number, flush for proper output sequencing when output is not a terminal. */ printf("Parent: %lu\n", c); fflush(stdout); c += 2; /* Increment counter */ kill(cpid, READY_SIGNAL); /* Wake up child process */ if (c &gt; n) break; /* Don't go back to sleep if we are done */ ready = 0; /* Reset ready flag */ /* Suspend until we receive READY_SIGNAL */ while (!ready) sigsuspend(&amp;wait_mask); }; wait4(cpid, NULL, 0); /* Don't exist before child finishes */ } return 0; } </code></pre> <p>This passes these basic tests:</p> <p><code>./print_with_signals 100000|sort -n -k 2 -c &amp;&amp; echo "Success"</code> <br/> <code>./print_with_signals 100001|sort -n -k 2 -c &amp;&amp; echo "Success"</code></p>
mysql software: any suggestions to oversee my mysql replication server? <p>I've had a tough time setting up my replication server. Is there any program (OS X, Win, Linux or php no problem) that lets me monitor and resolve replication issues? (btw, for those -uhm- following, ive been on this issue <a href="http://stackoverflow.com/questions/8166/mysql-replication-if-i-dont-specify-any-databases-will-logbin-log-everything" rel="nofollow">here</a>, <a href="http://stackoverflow.com/questions/3798/full-complete-mysql-db-replication-ideas-what-do-people-do" rel="nofollow">here</a>, <a href="http://stackoverflow.com/questions/8365/mysql-administrator-backups-compatibility-mode-what-exactly-is-this-doing" rel="nofollow">here</a> and <a href="http://stackoverflow.com/questions/30660/mysql-binary-log-replication-can-it-be-set-to-ignore-errors" rel="nofollow">here</a>. Either i'm going about this the wrong way or i must be immensely thick)</p> <p>My production database is several megs in size and growing. Every time the database replication stops and the databases inevitably begin to slide out of sync i cringe. My last resync from dump took almost 4 hours roundtrip!</p> <p>As always, even after sync, I run into this kind of show-stopping error":</p> <pre><code>Error 'Duplicate entry '252440' for key 1' on query. </code></pre> <p>I would love it if there was some way to closely monitor whats going on and perhaps let the software deal with it. I'm even all ears for service companies which may help me monitor my data better. Or an alternate way to mirror altogether.</p> <p><strong>Edit</strong>: going through my previous questions i found <a href="http://stackoverflow.com/questions/30660/mysql-binary-log-replication-can-it-be-set-to-ignore-errors#30889" rel="nofollow">this</a> which helps tremendously. I'm still all ears on the monitoring solution.</p> <p>cheers,</p> <p>/mp</p>
<p>To monitor the servers we use the free <a href="http://www.maatkit.org/tools.html" rel="nofollow">tools from Maatkit</a> ... simple, yet efficient.</p> <p>The binary replication is available in 5.1, so I guess you've got some balls. We still use 5.0 and it works OK, but of course we had our share of issues with it.</p> <p>We use a Master-Master replication with a MySql Proxy as a load-balancer in front, and to prevent it from having errors:</p> <ul> <li>we removed all unique indexes</li> <li>for the few cases where we really needed unique constraints we made sure we used REPLACE instead of INSERT (MySql Proxy can be used to guard for proper usage ... it can even rewrite your queries)</li> <li>scheduled scripts doing intensive reports are always accessing the same server (not the load-balancer) ... so that dangerous operations are replicated safely</li> </ul> <p>Yeah, I know it sounds simple and stupid, but it solved 95% of all the problems we had.</p>
Are there static analysis tools for Python? <p>I am starting to use Python (specifically because of Django) and I would like to remove the burden for exhaustive testing by performing some static analysis. What tools/parameters/etc. exist to detect issues at compile time that would otherwise show up during runtime? (type errors are probably the most obvious case of this, but undefined variables are another big one that could be avoided with an in-depth analysis of the AST.)</p> <p>Obviously testing is important, and I don't imply that tests can be obviated entirely; however, there are many runtime errors in python that are not possible in other languages that perform stricter run-time checking -- I'm hoping that there are tools to bring at least some of these capabilities to python as well.</p>
<p><a href="http://www.logilab.org/857">pylint</a> is the best such tool I've found. Due to Python's nature it's difficult to statically analyze it, but it will catch undefined variables, basic type errors, unused code, etc. You'll want to tweak the configuration file, as by default it outputs many warnings I consider useless or harmful.</p> <p>Here's part of my <code>.pylintrc</code> dealing with warning silencing:</p> <pre><code>[MESSAGES CONTROL] # Brain-dead errors regarding standard language features # W0142 = *args and **kwargs support # W0403 = Relative imports # Pointless whinging # R0201 = Method could be a function # W0212 = Accessing protected attribute of client class # W0613 = Unused argument # W0232 = Class has no __init__ method # R0903 = Too few public methods # C0301 = Line too long # R0913 = Too many arguments # C0103 = Invalid name # R0914 = Too many local variables # PyLint's module importation is unreliable # F0401 = Unable to import module # W0402 = Uses of a deprecated module # Already an error when wildcard imports are used # W0614 = Unused import from wildcard # Sometimes disabled depending on how bad a module is # C0111 = Missing docstring # Disable the message(s) with the given id(s). disable=W0142,W0403,R0201,W0212,W0613,W0232,R0903,W0614,C0111,C0301,R0913,C0103,F0401,W0402,R0914 </code></pre>
How can I clear Class::DBI's internal cache? <p>I'm currently working on a large implementation of Class::DBI for an existing database structure, and am running into a problem with clearing the cache from Class::DBI. This is a mod_perl implementation, so an instance of a class can be quite old between times that it is accessed. From the man pages I found two options:</p> <pre><code>Music::DBI-&gt;clear_object_index(); </code></pre> <p>And:</p> <pre><code>Music::Artist-&gt;purge_object_index_every(2000); </code></pre> <p>Now, when I add clear_object_index() to the DESTROY method, it seems to run, but doesn't actually empty the cache. I am able to manually change the database, re-run the request, and it is still the old version. purge_object_index_every says that it clears the index every n requests. Setting this to "1" or "0", seems to clear the index... sometimes. I'd expect one of those two to work, but for some reason it doesn't do it every time. More like 1 in 5 times.</p> <p>Any suggestions for clearing this out?</p>
<p>The "<a href="http://wiki.class-dbi.com/wiki/Common_problems" rel="nofollow">common problems</a>" page on the <a href="http://wiki.class-dbi.com/wiki" rel="nofollow">Class::DBI wiki</a> has a <a href="http://wiki.class-dbi.com/wiki/Common_problems#Old_data_due_to_object_index" rel="nofollow">section</a> on this subject. The simplest solution is to disable the live object index entirely using:</p> <pre><code>$Class::DBI::Weaken_Is_Available = 0; </code></pre>
Spread vs MPI vs zeromq? <p>In one of the answers to <a href="http://stackoverflow.com/questions/31572/broadcast-like-udp-with-the-reliability-of-tcp#31629">Broadcast like UDP with the Reliability of TCP</a>, a user mentions the <a href="http://spread.org">Spread</a> messaging API. I've also run across one called <a href="http://zeromq.org">ØMQ</a>. I also have some familiarity with <a href="http://www-unix.mcs.anl.gov/mpi/">MPI</a>. </p> <p>So, my main question is: why would I choose one over the other? More specifically, why would I choose to use Spread or ØMQ when there are mature implementations of MPI to be had?</p>
<p>MPI was deisgned tightly-coupled compute clusters with fast, reliable networks. Spread and ØMQ are designed for large distributed systems. If you're designing a parallel scientific application, go with MPI, but if you are designing a persistent distributed system that needs to be resilient to faults and network instability, use one of the others.</p> <p>MPI has very limited facilities for fault tolerance; the default error handling behavior in most implementations is a system-wide fail. Also, the semantics of MPI require that all messages sent eventually be consumed. This makes a lot of sense for simulations on a cluster, but not for a distributed application.</p>
What Are High-Pass and Low-Pass Filters? <p>Graphics and audio editing and processing software often contain functions called "High-Pass Filter" and "Low-Pass Filter". Exactly what do these do, and what are the algorithms for implementing them?</p>
<p>Here is how you implement a low-pass filter using convolution:</p> <pre class="lang-c prettyprint-override"><code>double[] signal = (some 1d signal); double[] filter = [0.25 0.25 0.25 0.25]; // box-car filter double[] result = new double[signal.Length + filter.Length + 1]; // Set result to zero: for (int i=0; i &lt; result.Length; i++) result[i] = 0; // Do convolution: for (int i=0; i &lt; signal.Length; i++) for (int j=0; j &lt; filter.Length; j++) result[i+j] = result[i+j] + signal[i] * filter[j]; </code></pre> <p>Note that the example is extremely simplified. It does not do range checks and does not handle the edges properly. The filter used (box-car) is a particularly bad lowpass filter, because it will cause a lot of artifacts (ringing). Read up on filter design.</p> <p>You can also implement the filters in the frequency domain. Here is how you implement a high-pass filter using FFT:</p> <pre class="lang-c prettyprint-override"><code>double[] signal = (some 1d signal); // Do FFT: double[] real; double[] imag; [real, imag] = fft(signal) // Set the first quarter of the real part to zero to attenuate the low frequencies for (int i=0; i &lt; real.Length / 4; i++) real[i] = 0; // Do inverse FFT: double[] highfrequencysignal = inversefft(real, imag); </code></pre> <p>Again, this is simplified, but you get the idea. The code does not look as complicated as the math.</p>
Lazy Loading with a WCF Service Domain Model? <p>I'm looking to push my domain model into a WCF Service API and wanted to get some thoughts on lazy loading techniques with this type of setup.</p> <p>Any suggestions when taking this approach?</p> <hr> <p>when I implemented this technique and step into my app, just before the server returns my list it hits the get of each property that is supposed to be lazy loaded ... Thus eager loading. Could you explain this issue or suggest a resolution?</p> <p>Edit: It <a href="http://benders-blog.blogspot.com/2007/01/lazy-loading-in-soa-world.html" rel="nofollow">appears</a> you can use the XMLIgnore attribute so it doesn’t get looked at during serialization .. still reading up on this though</p>
<p>Don't do lazy loading over a service interface. Define explicit DTO's and consume those as your data contracts in WCF.</p> <p>You can use NHibernate (or other ORMs) to properly fetch the objects you need to construct the DTOs.</p>
How do I begin using SVN? <p>I am ready to start using SVN, but I have NO (as in the money required for free beer) experience with source control. I have installed subversion on my server (that was easy, 'apt-get install subversion') but now I don't know what to do, how to configure it, or how to use it.<br /><br />What suggestions do you have, and where can I find good resources to learn to start using it?<br /><br /> Update:<br /> O.K. So the feedback has been great and I have read through a bit of it but I want to clarify my question by saying that I am looking for more information on how to actually go about setting my up my repositories, clients, server, etc. I know that I could do a quick Google search and find dozens (or more) resources but I'm hoping that someone whom has experience with subversion and a client(I have installed tortoise) could suggest a good reference that will be reliable, and have quality content.</p>
<p>Eric Sink has an <a href="http://www.ericsink.com/scm/source_control.html">excellent series</a> on source code control aimed at beginners. For Subversion specifics, including setting up and administering a server, the <a href="http://svnbook.red-bean.com/">Subversion book</a> is a great resource, and includes a section with examples of a typical session with Subversion (checkout, commit, merging and updating basics).</p> <p><strong>Update:</strong> I forgot to mention that for beginners, I'd also recommend messing around in a graphical client, which removes the command-line hassle from the learning experience. <a href="http://rapidsvn.tigris.org/">RapidSVN</a> is a reasonable cross-platform client. You'll also find that common IDEs either come with Subversion support, or have plugins which can be installed, which allow most version control operations to be performed within that environment.</p> <p><strong>@John Millikin:</strong> While setting up a Subversion server can be complicated, depending on one's general admin experience, don't forget that you don't need to do that just to mess about with a repository and get to grips with the basics - the client can interact with a repository in the local filesystem.</p>
Writing cross-platform apps in C <p>What things should be kept most in mind when writing cross-platform applications in C? Targeted platforms: 32-bit Intel based PC, Mac, and Linux. I'm especially looking for the type of versatility that Jungle Disk has in their USB desktop edition ( <a href="http://www.jungledisk.com/desktop/download.aspx">http://www.jungledisk.com/desktop/download.aspx</a> )</p> <p>What are tips and "gotchas" for this type of development?</p>
<p>I maintained for a number of years an ANSI C networking library that was ported to close to 30 different OS's and compilers. The library didn't have any GUI components, which made it easier. We ended up abstracting out into dedicated source files any routine that was not consistent across platforms, and used #defines where appropriate in those source files. This kept the code that was adjusted per platform isolated away from the main business logic of the library. We also made extensive use of typedefs and our own dedicated types so that we could easily change them per platform if needed. This made the port to 64-bit platforms fairly easy.</p> <p>If you are looking to have GUI components, I would suggest looking at GUI toolkits such as WxWindows or Qt (which are both C++ libraries).</p>
Getting started with SideShow Devices <p>Is there a recommendation for a hardware platform for developing/testing SideShow devices, or is the Emulator adequate?</p>
<p>I'm not really sure about sideshow in particular. But since sideshow uses the microframework I could give you my view on that. For just getting started the emulator is very good. You're going to use the emulator during development most of the time anyway so if you're just figuring things out it is fine to use just that. You can also tweak the emulator to emulate the specific hardware you want to use (add io ports etc.) so if you're not clear on what you want to do or what you need this is a good way to try stuff out.</p> <p>If you know exactly what you want to build it might be a good idea to think about what hardware you're going to need as soon as possible. There are some developer boards out there for the microframework that you might use for sideshow. Or if you've got specific needs you might end up developing your own hardware and porting the microframework to it. I don't really know what you need so I can't recommend a specific hardware platform. There are some examples on the microsoft microframework site that you might want to look at. <a href="http://msdn.microsoft.com/en-us/embedded/bb267253.aspx" rel="nofollow">http://msdn.microsoft.com/en-us/embedded/bb267253.aspx</a> look under the heading developer kits.</p> <p>I hope this is usefull for you.</p>
Comparison of Lat, Long Coordinates <p>I have a list of more than 15 thousand latitude and longitude coordinates. Given any X,Y coordinates, what is the fastest way to find the closest coordinates on the list?</p>
<p>I did this once for a web site. I.e. find the dealer within 50 miles of your zip code. I used the <a href="http://en.wikipedia.org/wiki/Great-circle_distance">great circle calculation</a> to find the coordinates that were 50 miles north, 50 miles east, 50 miles south, and 50 miles west. That gave me a min and max lat and a min and max long. From there then I did a database query: </p> <pre><code>select * from dealers where latitude &gt;= minlat and latitude &lt;= maxlat and longitude &gt;= minlong and longitude &lt;= maxlong </code></pre> <p>Since some of those results will still be more than 50 miles away, then I used the <a href="http://en.wikipedia.org/wiki/Great-circle_distance">great circle formula</a> once more on that small list of coordinates. Then I printed out the list along with the distance from the target.</p> <p>Of course, if you wanted to search for points near the international date line or the poles, than this won't work. But it works great for searches inside North America!</p>
Elegant Snippets of F# <p>I'm currently learning F# quite intensively. I really love it as a language, it just sort of 'feels' right and seems to allow you to produce some succint elegant code.</p> <p>I'm interested in finding some really nice 'wow factor' snippets of F# code which demonstate the elegence of the language, especially compared to C#. For example I really like:-</p> <pre> #light let ListProduct l = List.fold_left (*) 1 l </pre> <p>Which inputs a list of ints and multiplies each element in the list, i.e. obtains the product of the list (e.g. a list of 1,2,3 would be calculated as 1*2*3=6). The closest C# equivilent, using LINQ and functional concepts is as follows:-</p> <pre><code>using System; using System.Collections.Generic; using System.Linq; ... public static class ListHelper { public static int ListProduct(List&lt;int&gt; l) { return l.Aggregate(1, (i, j) =&gt; i * j); } } </code></pre> <p>Before LINQ that would have been:-</p> <pre><code>using System; using System.Collections.Generic; ... public static class ListHelper { public static int ListProduct(List&lt;int&gt; l) { int ret = 1; foreach (int i in l) ret *= i; return ret; } } </code></pre> <p>I'm certainly not trying to criticise C# here, I think it's a wonderful language, it's just nice to see how F# compares and to see how it can do some things more elegantly - does anyone have anything really nice?</p>
<p>My favorite is recursively listing all files under a folder in a four-line sequence expression:</p> <pre><code>open System.IO let rec filesUnderFolder basePath = seq { for file in Directory.GetFiles(basePath) do yield file for subDir in Directory.GetDirectories(basePath) do yield! filesUnderFolder subDir } </code></pre>
I don't understand std::tr1::unordered_map <p>I need an associative container that makes me index a certain object through a string, but that also keeps the order of insertion, so I can look for a specific object by its name or just iterate on it and retrieve objects in the same order I inserted them.</p> <p>I think this <a href="http://www.ddj.com/cpp/184406207" rel="nofollow">hybrid of linked list and hash map</a> should do the job, but before I tried to use <code>std::tr1::unordered_map</code> thinking that it was working in that way I described, but it wasn't. So could someone explain me the meaning and behavior of <code>unordered_map</code>?</p> <hr> <p>@wesc: I'm sure std::map is implemented by STL, while I'm sure std::hash_map is NOT in the STL (I think older version of Visual Studio put it in a namespace called stdext).</p> <p>@cristopher: so, if I get it right, the difference is in the implementation (and thus performances), not in the way it behaves externally.</p>
<p>You've asked for the canonical reason why Boost::MultiIndex was made: list insertion order with fast lookup by key. <a href="http://www.boost.org/doc/libs/1_36_0/libs/multi_index/doc/tutorial/basics.html#list_fast_lookup" rel="nofollow">Boost MultiIndex tutorial: list fast lookup</a></p>