input
stringlengths
51
42.3k
output
stringlengths
18
55k
Localization for Winforms from designmode? <p>I need to bind labels or items in a toolstrip to variables in Design Mode. I don't use the buit-in resources not the settings, so the section Data is not useful. I am taking the values out from an XML that I map to a class.</p> <p>I know there are many programs like: <a href="http://www.jollans.com/tiki/tiki-index.php?page=MultilangVsNetQuickTourForms" rel="nofollow">http://www.jollans.com/tiki/tiki-index.php?page=MultilangVsNetQuickTourForms</a> but they work with compiled resx. I want to use not compiled XML.</p> <p>I know that programatically i can do it, i create a method (for example, UpdateUI()), and there I assign the new values like this: this.tsBtn.Text=Class.Texts.tsBtnText;</p> <p>I would like something i could do from Design Mode or a more optimized way than the current one. Is there any Custom Control out there or Extension?</p>
<p>Aleksandar's response is one way to accomplish this, but in the long run it's going to be very time consuming and won't really provide much benefit. The bigger question that should be asked is why do you not want to use the tools and features built-in to .NET and Visual Studio or at least use a commercial third-party tool? It sounds like you are spending (have spent?) a lot of time to solve a problem that has already been solved.</p>
Large file download in background, initiated from the browser <p>Is there any reasonable method to allow users of a webapp to download large files? I'm looking for something other than the browser's built-in download dialog - the requirements are that the user initiates the download from the browser and then some other application takes over, downloads the file in background and doesn't exit when the browser is closed. It might possibly work over http, ftp or even bittorrent. Platform independence would be a nice thing to have but I'm mostly concerned with Windows.</p>
<p>This might be a suitable use for BitTorrent. It works using a separate program (in most browsers), and will still run after the browser is closed. Not a perfect match, but meets most of your demands.</p>
Icon size of button in Flex <p>How to find the width of the icon which is embedded in a button?</p>
<p>Try this:</p> <pre><code>var icon:DisplayObject = button.getChildByName("upIcon"); trace("icon (width: " + icon.width + ", height: " + icon.height + ")"); </code></pre>
What interface should I implement to create step driven events for my class? <p>I want to create a similar behavior to the data reader class but for a bespoke emailer program so that I can do the follow</p> <pre><code>Dim sender As New EmailSender(emailTemplate) While sender.Send() Response.Write(sender("HTMLContent")) End While </code></pre> <p>Is there an advised interface or mustInherit class to utilize the stepping functionality so that sender.Send() command prepares the next email for sending and returns true if it exists?</p>
<p>no - all you have to do is implement the Send() method to prepare the next email for sending and returns true if it exists</p> <p>you're probably thinking of the IEnumerable interface used for iterators, but you don't need that for what you want</p>
SQL Profiler connection details <p>When you startup a standard trace the first settings you see will be the current database connections.</p> <p>In my case there is about 10 entries, all of whome are the same username, however some are dateformat dmy and some are mdy. The asp website seems to pick a connection from the pool and uses it, it appears to pick one of 3 and all are set to dmy however every connection should be mdy. Since they are all the same username and that user is set to us_english where else might the connection be getting the dateformat entry?</p> <p>Thanks</p>
<p>Some ideas:</p> <ul> <li>The application is issuing SET DATEFORMAT</li> <li>The app is using a DSN with/without translation</li> </ul> <p>By default, the connection default is defined by SQL Server default settings.</p>
Do you know eclipse plugin to change localised text into html entities? <p>I have resource bundle with my country characters - how to change them into html entities. I prefer plugin integrated with Eclipse to have all tools in one place.</p>
<p>You might try:</p> <p><a href="http://andrei.gmxhome.de/anyedit/" rel="nofollow">http://andrei.gmxhome.de/anyedit/</a></p> <p>Further down the page one of its features is:</p> <p><em>Convert Chars to Html entities Editors - Useful if working in bilingual team to convert é's, ô's, ä's etc between html and other sources ;)</em></p>
reference path re javascript intellisense <p>I am trying to get intellisense in VS2008 in a js file, foo.js, from another js library/file I've written but cannot figure out the reference path ?syntax?/?string?</p> <p>The library is in a file called common.js which is in the same folder as foo.js I'm working on.</p> <p>Here's the paths I've tried...</p> <pre><code>/// &lt;reference path="../../scripts/common.js"/&gt; /// &lt;reference path="/../scripts/common.js"/&gt; /// &lt;reference path="../scripts/common.js"/&gt; /// &lt;reference path="/scripts/common.js"/&gt; /// &lt;reference path="scripts/common.js"/&gt; /// &lt;reference path="/common.js"/&gt; /// &lt;reference path="../common.js"/&gt; /// &lt;reference path="/common.js"/&gt; /// &lt;reference path="common.js"/&gt; </code></pre> <p>What's the secret path syntax/string that I'm missing?</p> <p>FWIW the top path is what is set in the master page of this MVC app...like so </p> <p><code>&lt;script type="text/javascript" src="../../scripts/common.js"&gt;&lt;/script&gt;</code></p> <p>Thanks Greg</p>
<p>First, make sure "common.js" is in your web project. Then drag "common.js" from the solution explorer into the editor window for the file you want to reference it from.</p>
Scheduled run of stored procedure on SQL server <p>Is it possible to set up somehow Microsoft SQL Server to run a stored procedure on regular basis?</p>
<p>Yes, in MS SQL Server, you can create scheduled jobs. In SQL Management Studio, navigate to the server, then expand the SQL Server Agent item, and finally the Jobs folder to view, edit, add scheduled jobs.</p>
Setting up SSL in Active Directory how-to <p>I need to set up SSL over Active Directory. I googled a lot but could not found a decent write up about how to do this. Please if you know some good resources about this let me know. Thanks!</p>
<p>Sounds easy - but I ran into quite a few problems getting trusted connections with SSL working in our environment. The article was about ADAM but is just as applicable for AD. In our environment I couldn't install domain-related services like cert-server, nor act as domain-admin.</p> <p>I blogged about how I got this working a while back</p> <blockquote> <p><a href="http://stephbu.wordpress.com/2006/11/29/using-adam-with-asp-net-2-0-activedirectorymembershipprovider/" rel="nofollow">http://stephbu.wordpress.com/2006/11/29/using-adam-with-asp-net-2-0-activedirectorymembershipprovider/</a></p> </blockquote> <p>Dan and Erlend's postings were invaluable.</p> <p>Took some backflips to get it done.</p>
How do you change a hashed password using asp.net membership provider if you don't know the current password? <p>Problem, there's no method:</p> <pre><code>bool ChangePassword(string newPassword); </code></pre> <p>You have to know the current password (which is probably hashed and forgotten).</p>
<p>This is an easy one that I wasted too much time on. Hopefully this post saves someone else the pain of slapping their forehead as hard as I did.</p> <p>Solution, reset the password randomly and pass that into the change method.</p> <pre><code>MembershipUser u = Membership.GetUser(); u.ChangePassword(u.ResetPassword(), "myAwesomePassword"); </code></pre>
ASP/VBScript "Gotchas" <p>I'm supporting/enhancing a web application written in Classic ASP/VBScript. It has been about 10 years since I have used either in a day to day capacity. I just ran across an issue that I would consider a "gotcha" and was wondering if others had similar things that I should learn to be aware of.</p> <p>My issue:<br /> I had to convert a Column in a SQL Table from float to decimal. It turns out that decimal isn't a type that is really supported (or supported well) in vbscript. So the following code:</p> <pre><code>Dim var1, var2 var1 = rs("DecimalField1").Value var2 = rs("DecimalField2").Value If (var1 &lt;&gt; var2) Then 'Do Something' End If </code></pre> <p>Would blow up with a Type Mismatch error on the line:</p> <pre><code>If (var1 &lt;&gt; var2) Then </code></pre> <p>After much searching I found out that:</p> <pre><code>var1 = CDBL(rs("DecimalField1").Value) var2 = CDBL(rs("DecimalField2").Value) </code></pre> <p>resolves the issue. But that didn't seem like an obvious thing and it took me a while to figure out why the heck I was getting a Type Mismatch on that line.</p> <p>So my question to everyone is, what other little quirks like this have you run across? What are some things within ASP/vbscript that you would think of as "gotchas" that I should be on the lookout for?</p>
<p><strong>Repeat after me:</strong> All good VB programmers use <code>Option Explicit</code></p> <p>It will keep you from accidentally declaring a new variable and using it - thus throwing off whatever you are doing.</p> <p>Beyond that, it depends on what you're doing.</p>
How to test a remoting connection (check state) <p>I have an object created in a host application and can access it remotely using remoting, is there any way I can test the connection to ensure it is still "alive"? Maybe an event I can use that fires if the remoting connection gets disconnected, or some property that can tell me the state of the remoting connection. Is there something like this available?</p>
<p>I generally add another method to the remoting server MarshallByRef class, (I generally name it Ping(), as in: </p> <pre><code> public void Ping() {} </code></pre> <p>that does nothing, and returns nothing.. Then to "test" my connection, I call this method... If it throws a System.Net.Sockets.Exception, I have lost the connection.... </p>
Find out sql server hardware or speed test <p>I use an sql server regularly and have recently been getting frustrated by the performance. It would be difficult for me to get direct access to find out the hardware so:</p> <p>Is there a direct way in management studio to assess performance or find out the exact hardware.</p> <p>Alternatively does someone have a set of test sql procedures I could try and ideally compare to other results to get an idea of it's performance.</p> <p>So far I have setup a few quick queries on my local machines sql express server just as test these seem to run quicker than the sql server on the network which is meant to be high performance although no one knows when it was last upgraded I have a feeling it hasn't been for 6 or 7 years. Obviously these test don't account for the possibility of others querying at the same time or network transfers of results... Hopefully someone has a better solution.</p>
<p>You can't just ask your server guys? Seems like there's a fair bit of mistrust if you can't get hardware metrics. Count of CPUs, total memory, etc.</p> <p>If there's that amount of mistrust, even if you found the answer from the database server, rectifying it would be impossible. If you can't get the current parameters, how could you get a change of hardware passed the server guys?</p> <p>Start building rapport. The best line in the world to get someone on your side is, "I'm in trouble and I need your help..." You've elevated them and subjugated yourself, you've put them in a position to save you. You'd be amazed at how much you can get out of people that way.</p> <p>As far as standard queries. You could look at <a href="http://www.tpc.org" rel="nofollow">TPC</a> queries. </p>
query join question <p>I have a right outer join, that almost does what I want...</p> <pre><code>SELECT users_usr.firstname_usr, users_usr.lastname_usr, credit_acc.given_credit_acc, users_usr.created_usr, users_usr.sitenum_usr, users_usr.original_aff_usr, users_usr.id_usr FROM credit_acc right Outer Join users_usr ON credit_acc.uid_usr = users_usr.id_usr </code></pre> <p>The problem is, I want to add a </p> <pre><code>where credit_acc.type_acc = 'init' </code></pre> <p>But this gets rid of all users who don't have a row in credit_acc... which is WHY I need a right outer join.</p> <p>Is there a way to get this without having to do two queries and a union?</p>
<pre><code>SELECT users_usr.firstname_usr, users_usr.lastname_usr, credit_acc.given_credit_acc, users_usr.created_usr, users_usr.sitenum_usr, users_usr.original_aff_usr, users_usr.id_usr FROM credit_acc right Outer Join users_usr ON credit_acc.uid_usr = users_usr.id_usr WHERE credit_acc.type_acc = 'init' OR credit_acc.type_acc is NULL </code></pre> <p>Or, as @Tomalak pointed out:</p> <pre><code>WHERE COALESCE(credit_acc.type_acc, 'init') = 'init' </code></pre> <p>which <em>may</em> be faster (see comments).</p>
How do I pre-cache images for quick viewing with javascript? <p>I have a webpage where I want the user to see a new image when they put thier mouse over a certain part of the image. I used an image map.</p> <pre><code>&lt;img src="pic.jpg" usemap="#picmap" /&gt; &lt;map id="picmap" name="picmap"&gt;&lt;area shape="rect" coords ="10,20,30,40" onMouseOver="mouse_on_write('mouse is on spot')" onMouseOut="mouse_off('mouse is off spot')" href="http://www....html" target="_blank" /&gt; &lt;/map&gt; &lt;p id="desc"&gt;&lt;/p&gt; </code></pre> <p>Where in the header I defined these functions:</p> <pre><code> &lt;script type="text/javascript"&gt; function mouse_off(txt) { document.getElementById("desc").innerHTML=txt; document.p1.src="pic.jpg"; } function mouse_on_write(txt) { document.getElementById("desc").innerHTML=txt; document.p1.src="pic2.jpg"; &lt;/script&gt; </code></pre> <p>It works, but it is slow. When the mouse is put over the second image it takes some few seconds to appear; my temporary solution was to drastically reduce the size of the images because they were huge (at 2.5mb they switch fast now, but still not seamless). <strong>How can I make the image switching more seamless without reduction in picture quality?</strong> On second thought I realize that I could also just have both images displayed, at a small and a large scale, and <strong>on mouse over they would switch places; How would I do this?</strong> Would this reduce lag? </p>
<p>You don't need to create any page elements, it can all be preloaded using JavaScript:</p> <pre><code>tempImg = new Image() tempImg.src="pic2.jpg" </code></pre> <p>EDIT:</p> <p>If you have a lot of images, you can use the poor-man's multi-preloader:</p> <pre><code>preloads = "red.gif,green.gif,blue.gif".split(",") var tempImg = [] for(var x=0;x&lt;preloads.length;x++) { tempImg[x] = new Image() tempImg[x].src = preloads[x] } </code></pre>
Submit changes of only one entity <p>If I select many rows from one table with one instance of DataContext. And then do I some changes in properties in the rows, can I submit changes to database only for one of the selected rows?</p>
<p>Yes you can.</p> <p>First you need to isolate the entities you want to undo the changes. Then, you can use your DataContext class to Override those entities with the values from the Database.</p> <pre><code>MyEntity e1, e2, e3 // changed entities ... // keep the changes only for e3 List&lt;MyEntity&gt; undoList = new List&lt;MyEntity&gt;(); undoList.Add(e1); undoList.Add(e2); myDataContext.Refresh(RefreshMode.OverwriteCurrentValues, undoList); myDataContext.SubmitChanges(); </code></pre> <p><strong>EDIT:</strong></p> <p>You can track all the changed objects in the DataContext like this:</p> <pre><code>MyEntity changedEntityToSubmit; // first you need to know what is the entity you need to submit. List&lt;object&gt; allChangedEntities = new List&lt;object&gt;(myDataContext.GetChangeSet().Updates); allChangedEntities.Remove(changedEntityToSubmit); myDataContext.Refresh(RefreshMode.OverwriteCurrentValues, allChangedEntities); myDataContext.SubmitChanges(); </code></pre> <p>This code is only considering the Updates. You also might need to consider the changes in Inserts and Deletes. This is up to you.</p>
Is there a way to use RegEx in ASP/VBScript? <p>I have an ASP website which I need to add a RegEx match to. Is there any support for RegEx in ASP/VBScript?</p> <p>Thank you,</p> <p>Brett</p>
<p>Yes, as of VBScript 5 <a href="http://authors.aspalliance.com/brettb/VBScriptRegularExpressions.asp" rel="nofollow">http://authors.aspalliance.com/brettb/VBScriptRegularExpressions.asp</a></p> <p><a href="http://www.regular-expressions.info/vbscript.html" rel="nofollow">http://www.regular-expressions.info/vbscript.html</a></p>
Decoding chunked HTTP with Actionscript <p>I have successfully connected to an HTTP server with ActionScript 3 over sockets. The only problem is, the server is sending chunked HTTP. Is there a generic function in any other language I can look at that clearly shows how to decode the chunking? I'm pretty sure there are no ActionScript libraries around for this.</p>
<p>The <a href="http://www.greenbytes.de/tech/webdav/rfc2616.htm" rel="nofollow">HTTP 1.1 specification</a> (or from <a href="http://www.w3.org/Protocols/" rel="nofollow">W3C</a>) provides a pseudocode example of how to <a href="http://www.greenbytes.de/tech/webdav/rfc2616.html#rfc.section.19.4.6" rel="nofollow">decode chunked transfer-coding</a>: </p> <pre><code>length := 0 read chunk-size, chunk-extension (if any) and CRLF while (chunk-size &gt; 0) { read chunk-data and CRLF append chunk-data to entity-body length := length + chunk-size read chunk-size and CRLF } read entity-header while (entity-header not empty) { append entity-header to existing header fields read entity-header } Content-Length := length Remove "chunked" from Transfer-Encoding </code></pre>
How do I look over a javascript array without using indexes in YUI? <p>I know that jQuery and prototype have a $.each() function for iterating over each element in an array. Does YUI offer any help with this?</p>
<p>YAHOO.util.Dom has the batch function which has the following signature:</p> <blockquote> <p>Any | Array <strong>batch</strong>( el , method , o , override )</p> </blockquote> <p>Where <em>el</em> is a DOM element or an array of DOM elements, <em>method</em> is a function that that will be passed each element in the array as its first argument, <em>o</em> is an optional second argument, and <em>override</em> is a boolean value that determines if the scope should be window (false) or <em>o</em> (true)</p> <p>So you could call it like this:</p> <pre><code>function setDisplay(el, display) { el.style.display = display; } YAHOO.util.Dom.batch(document.getElementsByTagName('div'), setDisplay, 'none'); </code></pre> <p>Perhaps that would serve your needs.</p>
How does one - without inheritance - override a class method and call the original from within the new method? <p>I found one source which successfully overrode <code>Time.strftime</code> like this:</p> <pre><code>class Time alias :old_strftime :strftime def strftime #do something old_strftime end end </code></pre> <p>The trouble is, <code>strftime</code> is an instance method. I need to override <code>Time.now</code> - a class method - in such away that any caller gets my new method, while the new method still calls the original <code>.now</code> method. I've looked at <code>alias_method</code> and have met with no success.</p>
<p>This is kinda hard to get your head around sometimes, but you need to open the "eigenclass" which is the singleton associated with a specific class object. the syntax for this is class &lt;&lt; self do...end. </p> <pre><code>class Time alias :old_strftime :strftime def strftime puts "got here" old_strftime end end class Time class &lt;&lt; self alias :old_now :now def now puts "got here too" old_now end end end t = Time.now puts t.strftime </code></pre>
Using Windows Role authentication in the App.config with WCF <p>I am using a WCF service and a net.tcp endpoint with serviceAuthentication's principal PermissionMode set to UseWindowsGroups.</p> <p>Currently in the implementation of the service i am using the PrincipalPermission attribute to set the role requirements for each method. </p> <pre><code> [PrincipalPermission(SecurityAction.Demand, Role = "Administrators")] [OperationBehavior(Impersonation = ImpersonationOption.Required)] public string method1() </code></pre> <p>I am trying to do pretty much the same exact thing, except have the configuration for the role set in the app.config. Is there any way to do this and still be using windows groups authentication?</p> <p>Thanks</p>
<p>If you are hosting your WCF service in IIS, it will run in the ASP.NET worker process, which means you can configure authentication and authorization as you would do with ASMX web services:</p> <pre><code>&lt;system.Web&gt; &lt;authentication mode="Windows"/&gt; &lt;authorization&gt; &lt;allow roles=".\Administrators"/&gt; &lt;deny users="*"/&gt; &lt;/authorization&gt; &lt;/system.Web&gt; </code></pre> <p>Then you will have to disable anonymous access to your endpoint in IIS, and instead enable <strong>Windows Integrated Authentication</strong>.<br/>In the IIS management console you do that by bringing up the '<em>Properties</em>' dialog for your virtual directory. You will then find the security settings in the '<em>Directory Security</em>' tab.</p> <p>Of course, the only communication channel available will be HTTP. Clients will have to provide their Windows identity in the request at the <em>transport-level</em> with these settings:</p> <pre><code>&lt;system.serviceModel&gt; &lt;bindings&gt; &lt;wsHttpBinding&gt; &lt;binding name="WindowsSecurity"&gt; &lt;security mode="Transport"&gt; &lt;transport clientCredentialType="Windows" /&gt; &lt;/security&gt; &lt;/binding&gt; &lt;/wsHttpBinding&gt; &lt;/bindings&gt; &lt;client&gt; &lt;endpoint address="https://localhost/myservice" binding="wsHttpBinding" bindingConfiguration="WindowsSecurity" contract="IMyService" /&gt; &lt;/client&gt; &lt;/system.serviceModel&gt; </code></pre> <p>Note that if your service endpoint uses <strong>wsHttpBinding</strong> then you will also have to add SSL to your endpoint since that's a requirement enforced by WCF when you using transport-level security.<br/> If you instead go for the <strong>basicHttpBinding</strong>, you are then able to use a <em>less secure</em> authentication mode available in WCF called <strong>TransportCredentialOnly</strong>, where SSL is no longer required.</p> <p>For more detailed information, <a href="http://www.code-magazine.com/articleprint.aspx?quickid=0611051">here</a> is a good overview of the security infrastructure in WCF.</p>
TortoiseSVN - Ignoring files within a folder already in the repository <p>How do I ignore all files within a folder under source control?</p> <p><code>/project/published/</code> is a folder I want to keep</p> <p><code>/project/published/some_file(s)</code> are files/folders I don't want</p> <p>More Details: Currently when I go to commit changes for my project I see a lot of files that I don't want to. They are files that get published to a folder and I don't need them under source control. I won't ever know the names of these files as they are chosen by users.</p> <p>I tried to use the property <code>svn:ignore</code> with value <code>published/*</code> but that did not work. Any ideas?</p>
<p>You just right click on the <code>published/</code> folder, select TortoiseSVN -> Properties, click New -> Advanced with the following:</p> <ul> <li>Property name: <code>svn:ignore</code> </li> <li>Property value: <code>*</code></li> </ul> <p>Then it would work fine.</p>
Prime number calculation fun <p>We're having a bit of fun here at work. It all started with one of the guys setting up a Hackintosh and we were wondering whether it was faster than a Windows Box of (nearly) same specs that we have. So we decided to write a little test for it. Just a simple Prime number calculator. It's written in Java and tells us the time it takes to calculate the first n Prime numbers.</p> <p>Optimised version below - now takes ~6.6secs</p> <pre><code>public class Primes { public static void main(String[] args) { int topPrime = 150000; int current = 2; int count = 0; int lastPrime = 2; long start = System.currentTimeMillis(); while (count &lt; topPrime) { boolean prime = true; int top = (int)Math.sqrt(current) + 1; for (int i = 2; i &lt; top; i++) { if (current % i == 0) { prime = false; break; } } if (prime) { count++; lastPrime = current; } if (current == 2) { current++; } else { current = current + 2; } } System.out.println("Last prime = " + lastPrime); System.out.println("Total time = " + (double)(System.currentTimeMillis() - start) / 1000); } } </code></pre> <p>We've pretty much lost the plot of the whole Hackintosh vs PC thing and are just having some fun with optimising it. First attempt with no optimisations (the above code has a couple) ran around 52.6min to find the first 150000 prime numbers. This optimisation is running around 47.2mins.</p> <p>If you want to have a go and post your results, then stick em up.</p> <p>Specs for the PC I'm running it on are Pentium D 2.8GHz, 2GB RAM, running Ubuntu 8.04.</p> <p><strong>Best Optimisation so far has been the square root of current, first mentioned by Jason Z.</strong></p>
<p>That's a bit worse than my sieve did on a 8 Mhz 8088 in turbo pascal in 1986 or so. But that was after optimisations :)</p>
Why isn't MySQL using the index for this subquery? <p>I used to do this:</p> <pre><code>SELECT layerID FROM layers WHERE ownerID = ? AND collectionID = ? </code></pre> <p>Which would give me an array of layerID's, and then I'd loop and do this for each one:</p> <pre><code>SELECT DATA FROM drawings WHERE layerID = ? </code></pre> <p>And it all worked fine. So now I'm trying to do it in one step, so I try this:</p> <pre><code>SELECT DATA , layerID FROM drawings WHERE layerID = ANY ( SELECT layerID FROM layers WHERE ownerID = ? AND collectionID = ? ) </code></pre> <p>But for some reason, it doesn't use the index, for the main query, <code>SELECT DATA etc</code>! So this one combined query takes much much longer to complete, versus the separate queries I was doing before. (By theway, the subquery, <code>SELECT layerID etc</code> still uses the index).</p> <p>I've determined if it's using a query or not by using the 'EXPLAIN' statement.</p> <p>I have individual indexes on the <code>ownerID</code> and <code>collectionID</code> columns in the <code>layers</code> table, and on the <code>layerID</code> column in the <code>drawings</code> table.</p> <p>What am I doing wrong with my query?</p>
<p>Try a join. ANY ends up looking a lot like an unoptimizable UNION to the query optimizer.</p> <pre><code>SELECT d.DATA, d.layerID FROM drawings AS d INNER JOIN layers AS l ON d.layerID = l.layerID WHERE l.ownerID = ? AND l.collectionID = ? </code></pre>
SQL Server 2005 and iTunes Library <p>what's the easiest way to bulk load my iTunes library xml into an existing SQL Server database?</p>
<p>bcp with xml flag.</p> <p><a href="http://msdn.microsoft.com/en-us/library/ms162802.aspx" rel="nofollow">http://msdn.microsoft.com/en-us/library/ms162802.aspx</a></p> <p>It really depends how you want it in there and what you're purposes are, which you haven't explained.</p>
Application_End global.asax <p>Can anybody tell me when Application_End is triggered in a lifecycle of an application? When all sessions are ended, will Application_End be triggered automatically? + Are there any other reasons why Application_End could be triggered?</p>
<p>The <code>application_end</code> event primarily fires when the IIS pool is recycled or the application itself is unloaded. One other thing to note, that a change to a dependent file (say web.config) will cause the application to reload itself, which will in cause the application_end event to fire while it is closing itself off.</p> <p>To note, the only instance I found of the application end event firing when the last user session times out is in some old documentation dated 2001. I'm not sure if that criteria still applies.</p>
Guidelines for / differences between cache / pool / cache pool <p>I'm doing some design (initially for Java) (but may extend to .NET in the future?) and I'm getting confused between the terms "cache" and "pool".</p> <p>As far as I can see, the main point of difference is what is contained in them?</p> <p>Any guidelines as to which should be used when?</p> <p>And what then is a "cache pool" which is referred to in a number of articles?</p>
<p>Although they both refer to keeping objects around, they are quite different, and I wouldn't say they're interchangeable.</p> <p><strong>Cache</strong> - store frequently used values, typically because the lookup and/or creation is non-trivial. e.g. if a lookup table from a database is frequently used, or values are read from a file on disk, it's more efficient to keep it in memory and refresh it periodically. </p> <p>A cache only manages object lifetime in the cache, but does not impose semantics on what is held in the cache. A cache also doesn't create the items, but just stores objects.</p> <p><strong>Pool</strong> - term to describe a group of resources that are managed by the pool itself. e.g. (Database) Connection Pool - When a connection is needed it is obtained from the pool, and when finished with is returned to the pool. </p> <p>The pool itself handles creation and destruction of the pooled objects, and manages how many objects can be created at any one time.</p> <p><strong>Cache Pool</strong> - mostly seems to describe the number of (independent?) cache's that exist. E.g. an asp.net application has 1 cache per Application Domain (cache isn't shared between asp.net applications). Literally a pool of caches, although this term seems to be used rarely.</p>
How Can I put information in a outputstream from tapestry5? <p>How Can I put information in a outputstream from tapestry5 ?</p> <p>I need a page when a user enters it open a dialog for save or open the file with the outputstream information.</p> <p>I write the next code:</p> <p>public class Index {</p> <pre><code>@Inject private RequestGlobals requestGlobals; @OnEvent("activate") public void onActivate() { try { HttpServletResponse response = requestGlobals.getHTTPServletResponse(); response.setContentType("text/txt"); PrintWriter out = response.getWriter(); out.println("hellooooooo"); out.flush(); } catch (IOException ex) { Logger.getLogger(Index.class.getName()).log(Level.SEVERE, null, ex); } } </code></pre> <p>}</p> <p>I hope that the result is only "helloooooooo" but is ("helloooooooo" + my html raw page)</p>
<p>Your method should have a return type of StreamResponse. You return an implementation of the interface StreamResponse, which simply returns the data you want with the content type you want.</p> <p>Look it up here:</p> <p><a href="http://tapestry.apache.org/tapestry5/apidocs/" rel="nofollow">http://tapestry.apache.org/tapestry5/apidocs/</a></p> <p>more info here:</p> <p><a href="http://tapestry.formos.com/nightly/tapestry5/tapestry-core/guide/pagenav.html" rel="nofollow">http://tapestry.formos.com/nightly/tapestry5/tapestry-core/guide/pagenav.html</a></p>
SSH hangs on Mac Book Pro; AFS and Network Preferences? <p>I am having an issue with SSH hanging on my Mac Book Pro. This only happens to me once I get home from work after I have used SSH while at work. The three factors I have narrowed the issue down to are SSH, our work AFS network drive and the method of network connectivity.</p> <p>At work we use an AFS drive with Kerberos Authentication to do all of our software development work on. I authenticate with Kerberos in order to gain access to the AFS drive where all my source code lives, but I open a local editor (Eclipse) which references the files on the AFS drive. Whenever I need to compile my code, I SSH in to my development server (which is also authenticated to the AFS drive) and compile from there. (Sanity Note: I know that it is a super wacky setup, but I promise I had NOTHING to do with it. I'm just making do with what I've got.)</p> <p>For my Network Preferences, I use the Automatic location all the time. For that configuration I have Built-in Ethernet en1 configured to use DHCP and our company's DNS server for when I'm at work (there is no wireless available). When I go home I connect to my home network via wireless, again using DHCP.</p> <p>I have a hunch that the AFS connection/Ethernet configuration is somehow the culprit here. Restarting the SSH daemon doesn't correct the problem. The only way I have found to correct the issue is by restarting the computer each time I want to use SSH. Keep in mind that I have no other (known) networking issues while at home after I've had the laptop at work. </p> <p>I have a co-worker who has reported to me the same issue on his MBP.</p> <p>I'm truly stumped on this one. Please provide some guidance. Thanks! </p>
<p>Can you be more specific about "SSH hanging"?</p> <p>It sounds like your ssh <strong>client</strong> hangs after losing the connection and you are unable to do anything in the terminal. To get around this, you can use the ssh escape character (default: ‘~’) to begin an escape sequence, and use the the '.' to terminate the connection.</p> <p>You can get a list of other ssh escape sequences using ~?, here's the one for OpenSSH SSH client:</p> <pre><code>Supported escape sequences: ~. - terminate connection ~B - send a BREAK to the remote system ~C - open a command line ~R - Request rekey (SSH protocol 2 only) ~^Z - suspend ssh ~# - list forwarded connections ~&amp; - background ssh (when waiting for connections to terminate) ~? - this message ~~ - send the escape character by typing it twice (Note that escapes are only recognized immediately after newline.) </code></pre> <p>If typing ~. does not work, it could be that you have the escape character disabled, in which case you can put</p> <pre><code>EscapeChar ~ </code></pre> <p>inside <em>~/.ssh/config</em> or */etc/ssh_config*</p> <p>Even when the escape character is disabled, you can simply pull up another Terminal window and type</p> <pre><code>killall ssh </code></pre> <p>to end all running ssh processes, allowing you to connect out again.</p> <p>Restarting the SSH daemon would not correct this problem because sshd allows other clients to connect in to your machine, and does not affect your ssh clients connecting out to some other machine.</p>
C#: How do you tell which item index is selected in ListView? <p>C#: How do you tell which item index is selected in ListView?</p>
<pre><code>ListView mylistv = new ListView(); var index = mylistv.SelectedIndices(); </code></pre> <p>That should do it.</p>
Sidebar form <p>How can I create a Sidebar form in delphi.</p> <p>I try the ScreenSnap and Align properties but I need that the form stay visible even if the user maximize other forms, without been on top. Just like the windows sidebar do.</p> <p><strong>update</strong> from the comments: if a window is maximized it maximizes next too the window, not in front of or behind.</p> <p>Thanks </p>
<p>What you're looking for is called an <em>AppBar</em>. Begin your research with the <a href="http://msdn.microsoft.com/en-us/library/bb762108.aspx"><code>ShAppBarMessage</code></a> API function.</p>
Unpacking _WTS_CLIENT_ADDRESS.Address in vb.net (retreiving IP address from Terminal Services Client) <p>I have the following structure:</p> <pre><code> &lt;StructLayout(LayoutKind.Sequential)&gt; _ Public Structure _WTS_CLIENT_ADDRESS Public AddressFamily As Integer &lt;MarshalAs(UnmanagedType.ByValArray, SizeConst:=20)&gt; _ Public Address() As Byte End Structure </code></pre> <p>Which is populated by the following call:</p> <pre><code> Dim _ClientIPAddress As New _WTS_CLIENT_ADDRESS Dim rtnPtr As IntPtr Dim rtncount As Int32 NativeMethods.WTSQuerySessionInformation(CInt(NativeMethods.WTS_CURRENT_SERVER_HANDLE), NativeMethods.WTS_CURRENT_SESSION, NativeMethods.WTS_INFO_CLASS.WTSClientAddress, rtnPtr, rtncount) '_ClientIPAddress() _ClientIPAddress = _ CType(System.Runtime.InteropServices.Marshal.PtrToStructure(rtnPtr, GetType(_WTS_CLIENT_ADDRESS)), _WTS_CLIENT_ADDRESS) </code></pre> <p>The address byte array is being populated, but I have no idea how to convert it into a useful string or integer values. The MDSN documentation is sparse: <a href="http://msdn.microsoft.com/en-us/library/aa383857" rel="nofollow">http://msdn.microsoft.com/en-us/library/aa383857</a>(VS.85).aspx</p>
<p>You're almost there with your code. I agree with you, the MSDN is not quite explicit on what's inside that byte array, but here's what you can do :</p> <pre><code>IPAddress address = new IPAddress(_ClientIPAddress.Address.Skip(2).Take(4).ToArray()); </code></pre> <p>The first two bytes do not seem to be used, but in the case of AF_INET (which is IPv4, or 2) the next four bytes are the IPv4 address of the client.</p> <p>You might also want to make sure that your code will handle IPv6 (AF_INET6) properly, or handle the fact that AF_INET6 is a likely value. You'll probably need to read 16 bytes instead of 4 for this protocol.</p>
How do I specify in my ccnet config file how to do daily builds? <p>How do I specify in my ccnet config file how to do daily builds?</p>
<p>You set up a scheduleTrigger:</p> <pre><code>&lt;triggers&gt; &lt;scheduleTrigger time="23:30" /&gt; &lt;/triggers&gt; </code></pre> <p>would run that project every night at 11:30pm</p>
What GOOD tools are available for generating ERD from a SQL Server Database? <p>I am trying to generate an Entity Relationship Diagram from an existing MS SQLServer 2005 database. What tools are available? Specifically,I am not only interested in ERD's more directly I am looking for a tool to help quickly learning and analysing a medium size (schema wise not really row wise) database structure.</p>
<p>I can see that this post is quite old and <strong>MS SQL Server Management Studio</strong> might have not had this feature back then! Though as far as I know with <strong>SQL Server 2012</strong> you can generate the ER diagrams by taking a few simple steps listed below:</p> <ol> <li>MS SQL Server management Studio > File menu > "Connect Object Explorer"</li> <li>Choose your Database node and expand it. under this node you'll find a sub-node called "Database Diagrams"</li> <li>Right click on "<strong>Database Diagrams</strong>" > "<strong>New Database Diagram</strong>" > <strong>Add tables</strong> that you wish to see their columns, relationships, ...</li> </ol>
Why does this regular expression kill the Java regex engine? <p>I have this naive regex "&lt;([\s]|[^&lt;])+?>" (excluding the quotation marks). It seems so straightforward but it is indeed evil when it works against the below HTML text. It sends the Java regular expression engine to an infinite loop. </p> <p>I have another regex ("&lt;.+?>"), which does somewhat the same thing, but it doesn't kill anything. Do you know why this happens?</p> <pre><code>&lt;script language="JavaScript" type="text/javascript"&gt; var numDivs, layerName; layerName = "lnavLayer"; catLinkName = "category"; numDivs = 2; function toggleLayer(layerID){ if (!(navigator.appName == "Netscape" &amp;&amp; navigator.appVersion.substr(0, 1) &lt; 5)){ thisLayer = document.getElementById(layerName + layerID); categoryLink = document.getElementById(catLinkName + layerID); closeThem(); if (thisLayer.className == 'subnavDefault'){ thisLayer.className = 'subnavToggled'; categoryLink.className = 'leftnavLinkSelectedSection'; } } } function closeThem(){ for(x = 0; x &lt; numDivs; x++){ theLayer = document.getElementById(layerName + (x + 1)); thecategoryLink = document.getElementById(catLinkName + (x + 1)); theLayer.className = 'subnavDefault'; thecategoryLink.className = 'leftnavLink'; } } var flag = 0; var lastClicked = 0 //--&gt; &lt;/script&gt; </code></pre> <p>it even keeps looping with an online Java regex tool (such as <a href="http://www.fileformat.info/tool/regex.htm" rel="nofollow">www.fileformat.info/tool/regex.htm</a>) or a utility like <a href="http://www.regexbuddy.com/" rel="nofollow">RegexBuddy</a>.</p>
<p>The reason the Java regex engine crashes is that this part of your regex causes a stack overflow (indeed!):</p> <pre><code>[\s]|[^&lt;] </code></pre> <p>What happens here is that every character matched by \s can also be matched by [^&lt;]. That means there are two ways to match each whitespace character. If we represent the two character classes with A and B:</p> <pre><code>A|B </code></pre> <p>Then a string of three spaces could be matched as AAA, AAB, ABA, ABB, BAA, BAB, BBA, or BBB. In other words the complexity of this part of the regex is 2^N. This will kill any regex engine that doesn't have any safeguards against what I call <a href="http://www.regular-expressions.info/catastrophic.html">catastrophic backtracking</a>.</p> <p>When using alternation (vertical bar) in a regex, always make sure the alternatives are mutually exclusive. That is, at most one of the alternatives may be allowed to match any given bit of text.</p>
Get the subdomain from a URL <p>Getting the subdomain from a URL sounds easy at first.</p> <pre><code>http://www.domain.example </code></pre> <p>Scan for the first period then return whatever came after the "http://" ...</p> <p>Then you remember</p> <pre><code>http://super.duper.domain.example </code></pre> <p>Oh. So then you think, okay, find the last period, go back a word and get everything before! </p> <p>Then you remember</p> <pre><code>http://super.duper.domain.co.uk </code></pre> <p>And you're back to square one. Anyone have any great ideas besides storing a list of all TLDs?</p>
<blockquote> <p>Anyone have any great ideas besides storing a list of all TLDs?</p> </blockquote> <p>No, because each TLD differs on what counts as a subdomain, second level domain, etc.</p> <p>Keep in mind that there are top level domains, second level domains, and subdomains. Technically speaking, everything except the TLD is a subdomain.</p> <p>In the domain.com.uk example, domain is a subdomain, com is a second level domain, and uk is the tld.</p> <p>So the question remains more complex than at first blush, and it depends on how each TLD is managed. You'll need a database of all the TLDs that include their particular partitioning, and what counts as a second level domain and a subdomain. There aren't too many TLDs, though, so the list is reasonably manageable, but collecting all that information isn't trivial. There may already be such a list available.</p> <p>Looks like <a href="http://publicsuffix.org/">http://publicsuffix.org/</a> is one such list - all the common suffixes (.com, .co.uk, etc) in a list suitable for searching. It still won't be easy to parse it, but at least you don't have to maintain the list. </p> <blockquote> <p>A "public suffix" is one under which Internet users can directly register names. Some examples of public suffixes are ".com", ".co.uk" and "pvt.k12.wy.us". The Public Suffix List is a list of all known public suffixes.</p> <p>The Public Suffix List is an initiative of the Mozilla Foundation. It is available for use in any software, but was originally created to meet the needs of browser manufacturers. It allows browsers to, for example:</p> <ul> <li>Avoid privacy-damaging "supercookies" being set for high-level domain name suffixes</li> <li>Highlight the most important part of a domain name in the user interface</li> <li>Accurately sort history entries by site</li> </ul> </blockquote> <p><a href="http://mxr.mozilla.org/mozilla-central/source/netwerk/dns/effective_tld_names.dat?raw=1">Looking through the list</a>, you can see it's not a trivial problem. I think a list is the only correct way to accomplish this...</p> <p>-Adam</p>
How to return JSON from a 2.0 asmx web service <p>I am using .Net framework 2.0 / jQuery to make an Ajax call to a 2.0 web service. No matter what I set the contentType to in the ajax call, the service always returns XML. I want it to return Json!</p> <p>Here is the call:</p> <pre><code> $(document).ready(function() { $.ajax({ type: "POST", url: "DonationsService.asmx/GetDate", data: "{}", contentType: "application/json; charset=utf-8", dataType: "json", success: function(msg) { // Hide the fake progress indicator graphic. $('#RSSContent').removeClass('loading'); // Insert the returned HTML into the &lt;div&gt;. $('#RSSContent').html(msg.d); } }); }); </code></pre> <p>Here is what the request header looks like in Fiddler:</p> <pre><code>POST /DonationsService.asmx/GetDate HTTP/1.1 x-requested-with: XMLHttpRequest Accept-Language: en-us Referer: http://localhost:1238/text.htm Accept: application/json, text/javascript, */* Content-Type: application/json; charset=utf-8 Accept-Encoding: gzip, deflate User-Agent: Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; SV1; .NET CLR 1.1.4322; eMusic DLM/4; .NET CLR 2.0.50727) Host: localhost:1238 Content-Length: 2 Connection: Keep-Alive Pragma: no-cache </code></pre> <p>I have tried setting the contentType to 'text/json' and get the same results.</p> <p>Here is the web service method:</p> <pre><code>&lt;WebMethod()&gt; _ Public Function GetDate() As String 'just playing around with Newtonsoft.Json Dim sb As New StringBuilder Dim sw As New IO.StringWriter(sb) Dim strOut As String = String.Empty Using jw As New JsonTextWriter(sw) With jw .WriteStartObject() .WritePropertyName("DateTime") .WriteValue(DateTime.Now.ToString) .WriteEndObject() End With strOut = sw.ToString End Using Return strOut End Function </code></pre> <p>and here is what it returns:</p> <pre><code>&lt;?xml version="1.0" encoding="utf-8"?&gt; &lt;string xmlns="http://DMS.Webservices.org/"&gt;{"DateTime":"11/13/2008 6:04:22 PM"}&lt;/string&gt; </code></pre> <p>Does anyone know how to force the web service to return Json when I ask for Json?</p> <p>Please don't tell me to upgrade to .Net Framework 3.5 or anything like that (I'm not that stupid). I need a 2.0 solution.</p>
<p>It's no problem to <a href="http://encosia.com/2010/03/08/asmx-scriptservice-mistakes-installation-and-configuration/">return JSON from ASMX services in ASP.NET 2.0</a>. You just need the ASP.NET AJAX Extensions installed.</p> <p>Do be sure to add the [ScriptService] decoration to your web service. That's what instructs the server side portion of the ASP.NET AJAX framework to return JSON for a properly formed request.</p> <p>Also, you'll need to drop the ".d" from "msg.d" in my example, if you're using it with 2.0. <a href="http://encosia.com/2009/02/10/a-breaking-change-between-versions-of-aspnet-ajax/">The ".d" is a security feature that came with 3.5</a>.</p>
How can I convert a string to a number in Perl? <p>How would I convert a string holding a number into its numeric value in Perl?</p>
<p>You don't need to convert it at all:</p> <pre><code>% perl -e 'print "5.45" + 0.1;' 5.55 </code></pre>
C# List<> Sort by x then y <p>Similar to <a href="http://stackoverflow.com/questions/188141/c-list-orderby-alphabetical-order">List&lt;&gt; OrderBy Alphabetical Order</a>, we want to sort by one element, then another. we want to achieve the functional equivalent of </p> <pre><code>SELECT * from Table ORDER BY x, y </code></pre> <p>We have a class that contains a number of sorting functions, and we have no issues sorting by one element.<br> For example: </p> <pre><code>public class MyClass { public int x; public int y; } List&lt;MyClass&gt; MyList; public void SortList() { MyList.Sort( MySortingFunction ); } </code></pre> <p>And we have the following in the list: </p> <pre><code>Unsorted Sorted(x) Desired --------- --------- --------- ID x y ID x y ID x y [0] 0 1 [2] 0 2 [0] 0 1 [1] 1 1 [0] 0 1 [2] 0 2 [2] 0 2 [1] 1 1 [1] 1 1 [3] 1 2 [3] 1 2 [3] 1 2 </code></pre> <p>Stable sort would be preferable, but not required. Solution that works for .Net 2.0 is welcome.</p>
<p>For versions of .Net where you can use LINQ <code>OrderBy</code> and <a href="http://msdn.microsoft.com/en-us/library/vstudio/bb534743(v=vs.100).aspx"><code>ThenBy</code></a> (or <code>ThenByDescending</code> if needed):</p> <pre><code>using System.Linq; .... List&lt;SomeClass&gt;() a; List&lt;SomeClass&gt; b = a.OrderBy(x =&gt; x.x).ThenBy(x =&gt; x.y).ToList(); </code></pre> <hr> <p>Note: for .Net 2.0 (or if you can't use LINQ) see <a href="http://stackoverflow.com/a/289040/477420">Hans Passant answer</a> to this question.</p>
HTML hyperlink with mouse over image <p>I am having a Html hyperlink. I need to link this hyperlink to another page.When I place the mouse over the link. It should show the image. how to do this</p>
<p>That depends on where you need to display the image. If you are looking for something along the lines of an icon next to or behind the link, you could accomplish this through CSS using a background image on the hover state of the link:</p> <pre><code>a:link { background-image:none; } a:hover { background-image:url('images/icon.png'); background-repeat:no-repeat; background-position:right; padding-right:10px /*adjust based on icon size*/ } </code></pre> <p>I did this off the top of my head, so you may need to make some minor adjustments.</p> <p>If you wanted to show an image somewhere else on the page, you could accomplish that using javascript to hide/show the image on the link's mouseover event.</p> <p>If this doesn't solve your problem, maybe you could supply some additional information to help guide everybody to the right answer.</p>
How can I use Html.ValidationSummary with Ajax.BeginForm? <p>I have an AJAX form that I am creating in my MVC project. If the form is submitted using normal browser function and a page refresh occurs I get validation information rendered in the form (the built in MVC validation based on ViewData.ModelState).</p> <p>Is there a similiar validation mechanism for AJAX forms?</p> <pre><code>&lt;% using (Ajax.BeginForm("Create", "GraphAdministration", new AjaxOptions() { OnSuccess = "newGraphSuccess", OnFailure = "newGraphFailure", HttpMethod = "POST" })) { %&gt; &lt;!-- some form stuff in here !--&gt; &lt;% } //end form %&gt; </code></pre>
<p>It really depends on where you are getting the content from to display once the form has been posted. The Validation summary is performed created on the server so that is where you have to do the work.</p> <p>As an example I was using some partial content in an .ascx file to render a form. You get the form in the page the first time round by calling the action directly with <code>Html.RenderAction</code></p> <p>You would have your <code>Ajax.BeginForm</code> etc. in the .ascx file. Then call it directly in an action.</p> <p>When the Ajax call is made from the browser you get it to post to the same action. That way you can do all of the server side validation that you would normally. You should set up the Ajax call to replace the original form with the new html that is returned by the action.</p> <p>One thing that you have to be aware of is that the replace JavaScript will replace the <b>content</b> of an element not the element itself so remember to us the id of a surrounding element.</p> <p>Apologies if that is a little convoluted, if you want more details just comment and I'll flesh out the relevant bits.</p> <h3>Extra Detail:</h3> <p>All of this assumes that you are doing all of the validation on the server.</p> <p>You are going to have a View that has all of the page stuff in it and then some partial content in a .ascx file, this is where your ajax form lives, it needs to be set to replace content by id. Its easiest if it has the same name as the action your ajax is going to call.</p> <p>You can use <code>Html.RenderAction</code> to get it into the View. You can also pass in data with other versions of the same method. Your essentially calling it in the same way your ajax code will.</p> <p>You will need to wrap it all in a div with an id set. Use this id in the partial as the content to replace.</p> <p>When you render the page the html for the form and all of the ajax stuff will get put in.</p> <p>When the ajax action is called the partial content will be returned with any validation performed. It will replace the content of the div that you gave the id to.</p> <p>You can have different versions of the action by using <code>[AcceptVerbs(HttpVerbs.Get)]</code> and <code>[AcceptVerbs(HttpVerbs.Post)]</code> attributes</p> <p>The main problem with this method is that its not self contained, the div with the id is external to the partial.</p>
Why do requests and responses get lost? <p>Even on big-time sites such as Google, I sometimes make a request and the browser just sits there. The hourglass will turn indefinitely until I click again, after which I get a response instantly. So, the response or request is simply getting lost on the internet. </p> <p>As a developer of ASP.NET web applications, is there any way for me to mitigate this problem, so that users of the sites I develop do not experience this issue? If there is, it seems like Google would do it. Still, I'm hopeful there is a solution.</p> <p>Edit: I can verify, for our web applications, that every request actually reaching the server is served in a few seconds even in the absolute worst case (e.g. a complex report). I have an email notification sent out if a server ever takes more than 4 seconds to process a request, or if it fails to process a request, and have not received that email in 30 days.</p>
<p>It's possible that a request made from the client took a particular path which happened to not work at that particular moment. These are unavoidable - they're simply a result of the internet, which is built upon unstable components and which TCP manages to ensure a certain kind of guarantee for.</p> <p>Like someone else said - make sure when a request hits your server, you'll be ready to reply. Everything else is out of your hands.</p>
Updating an associative table in MySQL <p>Below is my (simplified) schema (in MySQL ver. 5.0.51b) and my strategy for updating it. There has got to be a better way. Inserting a new item requires 4 trips to the database and editing/updating an item takes up to <strong>7</strong>!</p> <p><strong>items</strong>: itemId, itemName <br /><strong>categories</strong>: catId, catName <br /><strong>map</strong>: mapId*, itemId, catId <br />* mapId (varchar) is concat of itemId + | + catId</p> <p>1) If inserting: insert item. Get itemId via MySQL API. <br />Else updating: just update the item table. We already have the itemId.</p> <p>2) Conditionally batch insert into <code>categories</code>.</p> <pre><code>INSERT IGNORE INTO categories (catName) VALUES ('each'), ('category'), ('name'); </code></pre> <p>3) Select IDs from <code>categories</code>.</p> <pre><code>SELECT catId FROM categories WHERE catName = 'each' OR catName = 'category' OR catName = 'name'; </code></pre> <p>4) Conditionally batch insert into <code>map</code>.</p> <pre><code>INSERT IGNORE INTO map (mapId, itemId, catId) VALUES ('1|1', 1, 1), ('1|2', 1, 2), ('1|3', 1, 3); </code></pre> <p>If inserting: we're done. Else updating: continue.</p> <p>5) It's possible that we no longer associate a category with this item that we did prior to the update. Delete old categories for this itemId.</p> <pre><code>DELETE FROM MAP WHERE itemId = 2 AND catID &lt;&gt; 2 AND catID &lt;&gt; 3 AND catID &lt;&gt; 5; </code></pre> <p>6) If we have disassociated ourselves from a category, it's possible that we left it orphaned. We do not want categories with no items. Therefore, if <code>affected rows &gt; 0</code>, kill orphaned categories. I haven't found a way to combine these in MySQL, so this is #6 &amp; #7.</p> <pre><code>SELECT categories.catId FROM categories LEFT JOIN map USING (catId) GROUP BY categories.catId HAVING COUNT(map.catId) &lt; 1; </code></pre> <p>7) Delete IDs found in step 6.</p> <pre><code>DELETE FROM categories WHERE catId = 9 AND catId = 10; </code></pre> <p>Please tell me there's a better way that I'm not seeing.</p>
<p>There are a number of things you can do to make a bit easier:</p> <ul> <li><p>Read about [<code>INSERT...ON DUPLICATE KEY UPDATE</code>][1]</p></li> <li><p>Delete old categories before you insert new categories. This may benefit from an index better.</p> <p><code>DELETE FROM map WHERE itemId=2</code>;</p></li> <li><p>You probably don't need <code>map.mapID</code>. Instead, declare a compound primary key over <code>(itemID, catID)</code>.</p></li> <li><p>As Peter says in his answer, use MySQL's multi-table delete:</p> <pre><code>DELETE categories.* FROM categories LEFT JOIN map USING (catId) WHERE map.catID IS NULL </code></pre> <p><a href="http://dev.mysql.com/doc/refman/5.0/en/insert-on-duplicate.html" rel="nofollow">http://dev.mysql.com/doc/refman/5.0/en/insert-on-duplicate.html</a></p></li> </ul>
How to identify which lines of code participated in a specific execution of a Java program? <p>Suppose that I have a Java program within an IDE (Eclipse in this case). Suppose now that I execute the program and at some point terminate it or it ends naturally.</p> <p>Is there a <strong>convenient</strong> way to determine which lines executed at least once and which ones did not (e.g., exception handling or conditions that weren't reached?)</p> <p>A manual way to collect this information would be to constantly step with the debugging and maintain a set of lines where we have passed at least once. However, is there some tool or profiler that already does that?</p> <p>Edit: Just for clarification: I need to be able to access this information programmatically and not necessarily from a JUnit test.</p>
<p><a href="http://www.eclemma.org/" rel="nofollow">eclemma</a> would be a good start: a code coverage tool would allow a coverage session to record the information you are looking for.</p> <p><img src="http://www.eclemma.org/images/smallscreen.gif" alt="alt text" /></p>
Problem dealloc'ing memory used by UIImageViews with fairly large image in an UIScrollView <p>I have a large UIScrollView into which I'm placing 3-4 rather large (320x1500 pixels or so) UIImageView image tiles. I'm adding these UIImageViews to the scroll view inside of my NIB files. I have one outlet on my controller, and that is to the UIScrollView. I'm using a property (nonatomic, retain) for this, and sythesizing it.</p> <p>My question is this: When I observe this in Memory Monitor, I can see that the memory used goes up quite a bit when the view with all these images is loaded (as expected). But when I leave the view, it and its controller are dealloc'd, but do not seem to give up anywhere near the memory they had taken up. When I cut one of these views (there are several in my app) down to just 1-3 images that were 320x460 and left everything else the same, it recaptures the memory just fine.</p> <p>Is there some issue with using images this large? Am I doing something wrong in this code (pasted below)?</p> <p>This is a snippet from the viewController that is causing problems.</p> <pre><code>- (CGFloat)findHeight { UIImageView *imageView = nil; NSArray *subviews = [self.scrollView subviews]; CGFloat maxYLoc = 0; for (imageView in subviews) { if ([imageView isKindOfClass:[UIImageView class]]) { CGRect frame = imageView.frame; if ((frame.origin.y + frame.size.height) &gt; maxYLoc) { maxYLoc = frame.origin.y; maxYLoc += frame.size.height; } } } return maxYLoc; } - (void)viewDidLoad { [super viewDidLoad]; [self.scrollView setContentSize:CGSizeMake(320, [self findHeight])]; [self.scrollView setCanCancelContentTouches:NO]; self.scrollView.indicatorStyle = UIScrollViewIndicatorStyleWhite; self.scrollView.clipsToBounds = YES; self.scrollView.scrollEnabled = YES; self.scrollView.pagingEnabled = NO; } - (void)dealloc { NSLog(@"DAY Controller Dealloc'd"); self.scrollView = nil; [super dealloc]; } </code></pre> <p>UPDATE: I've noticed another weird phenomenon. If I don't use the scroll on the view, it seems to be hanging on to the memory. But if I scroll around a bunch and ensure that all of the UIImageViews became visible at one point, it will free up and regain most of the memory it lost.</p> <p>UPDATE2: The reason I'm asking this is my app is actually crashing due to low memory. I wouldn't mind if it were just caching and using up extra memory, but it doesn't seem to ever release it - even in didReceiveMmoryWarning conditions</p>
<p>I've solved the mystery - and I'm pretty sure this is a bug on Apple's side.</p> <p>As Kendall suggested (thanks!), the problem lies in how InterfaceBuilder loads images from the NIB file. When you initFromNib, all UIImageViews will init with a UIImage using the imageNamed: method of UIImage. This call uses caching for the image. Normally, this is what you want. However, with very large images and additionally ones that scroll far off of the visible area, it does not seem to be obeying memory warnings and dumping this cache. This is what I believe to be a bug on Apple's side (please comment if you agree/disagree - I'd like to submit this if others agree). As I said above, the memory used by these images does seem to be released if a user scrolls around enough to make it all visible.</p> <p>The workaround that I've found (also Kendall's suggestion) is to leave the image name blank in the NIB file. So you lay out your UIImageView elements as normal, but don't select an image. Then in your viewDidLoad code, you go in and load an image using imageWithContentsOfFile: instead. This method does NOT cache the image, and therefore does not cause any memory issues with retaining large images.</p> <p>Of course, imageNamed: is a lot easier to use, because it defaults to anything in the bundle, rather than having to find the path. However, you can get the path to the bundle with the following:</p> <pre><code>NSString *fullpath = [[[NSBundle mainBundle] bundlePath]; </code></pre> <p>Putting that all together, here's what that looks like in code:</p> <pre><code>NSString *fullpath = [[[NSBundle mainBundle] bundlePath] stringByAppendingString:[NSString stringWithFormat:@"/%@-%d.png", self.nibName, imageView.tag]]; UIImage *loadImage = [UIImage imageWithContentsOfFile:fullpath]; imageView.image = loadImage; </code></pre> <p>So adding that to my code above, the full function looks like this: </p> <pre><code>- (CGFloat)findHeight { UIImageView *imageView = nil; NSArray *subviews = [self.scrollView subviews]; CGFloat maxYLoc = 0; for (imageView in subviews) { if ([imageView isKindOfClass:[UIImageView class]]) { CGRect frame = imageView.frame; if ((frame.origin.y + frame.size.height) &gt; maxYLoc) { maxYLoc = frame.origin.y; maxYLoc += frame.size.height; } NSString *fullpath = [[[NSBundle mainBundle] bundlePath] stringByAppendingString:[NSString stringWithFormat:@"/%@-%d.png", self.nibName, imageView.tag]]; NSLog(fullpath); UIImage *loadImage = [UIImage imageWithContentsOfFile:fullpath]; imageView.image = loadImage; } } return maxYLoc; } </code></pre>
Is there a fast language that supports portable continuations? <p>I'm looking for a fast language (ie. a language that can be compiled natively to achieve performance not more than 3 or 4 times slower than C), which supports portable continuations. By this I mean a continuation that can be serialized on one computer, and deserialized on another.</p> <p>I know that SISC can do this (a Scheme implementation in Java), but its slow. Ditto for Rhino (a Javascript implementation in Java).</p>
<p>Did you checked <strong>OCaml</strong> ? It can be compiled and should be marginally slower than C.</p> <p><a href="http://okmij.org/ftp/Computation/Continuations.html">Continuations and delimited control</a></p>
Need assistance with diagnosing SOAP packet problem with Amazon S3 <p>We are building an application which stores data in an S3 bucket. However, we are having problems with the <strong>PutObject</strong> method. Here is the xml packet we are sending out:</p> <pre><code>&lt;?xml version="1.0" encoding="utf-8"?&gt; &lt;soap:Envelope xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/"&gt; &lt;soap:Body&gt; &lt;PutObject xmlns="http://doc.s3.amazonaws.com/2006-03-01"&gt; &lt;Bucket&gt;lills&lt;/Bucket&gt; &lt;Key&gt;lills123&lt;/Key&gt; &lt;Metadata&gt; &lt;Name&gt;Content-Type&lt;/Name&gt; &lt;Value&gt;text/plain&lt;/Value&gt; &lt;/Metadata&gt; &lt;Metadata&gt; &lt;Name&gt;title&lt;/Name&gt; &lt;Value&gt;lills&lt;/Value&gt; &lt;/Metadata&gt; &lt;Data&gt;aGEtaGE=&lt;/Data&gt; &lt;ContentLength&gt;5&lt;/ContentLength&gt; &lt;AWSAccessKeyId&gt;key&lt;/AWSAccessKeyId&gt; &lt;Timestamp&gt;2008-11-12T06:23:17Z&lt;/Timestamp&gt; &lt;Signature&gt;signature&lt;/Signature&gt; &lt;/PutObject&gt; &lt;/soap:Body&gt; &lt;/soap:Envelope&gt; </code></pre> <p>And this is the response we are getting back from S3:</p> <pre><code>&lt;?xml version="1.0" encoding="utf-8"?&gt; &lt;soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"&gt; &lt;soapenv:Body&gt; &lt;soapenv:Fault&gt; &lt;faultcode&gt;soapenv:Client.badRequest&lt;/faultcode&gt; &lt;faultstring&gt;Malformed request&lt;/faultstring&gt; &lt;detail/&gt; &lt;/soapenv:Fault&gt; &lt;/soapenv:Body&gt; &lt;/soapenv:Envelope&gt; </code></pre> <p>Can anyone tell me what the problem with the SOAP packet is?</p> <p>Thanks in advance, Devan</p>
<p>If you want to send the data in the SOAP message itself, you need to use PutObjectInline, and not PutObject (which expects the data to be a DIME attachment).</p> <p>see <a href="http://docs.amazonwebservices.com/AmazonS3/latest/index.html?SOAPPutObjectInline.html" rel="nofollow">PutObjectInline</a> in the s3 docs.</p>
Cannot get regular expression work correctly with multiline <p>I have a quite big XML output from an application. I need to process it with my program and then feed it back to the original program. There are pieces in this XML which needs to be filled out our replaced. The interesting part looks like this:</p> <pre><code>&lt;sys:customtag sys:sid="1" sys:type="Processtart" /&gt; &lt;sys:tag&gt;value&lt;/sys:tag&gt; here are some other tags &lt;sys:tag&gt;value&lt;/sys.tag&gt; &lt;sys:customtag sys:sid="1" sys:type="Procesend" /&gt; </code></pre> <p>and the document contains several pieces like this.</p> <p>I need to get all XML pieces inside these tags to be able to make modifications on it. I wrote a regular expression to get those pieces but it does not work:</p> <pre><code>XmlDocument xmlDoc = new XmlDocument(); xmlDoc.Load(@"output.xml"); Regex regExp = new Regex(@"&lt;sys:customtag(.*?)Processtart(.*?)/&gt;(.*?)&lt;sys:customtag (.*?)Procesend(.*?)/&gt;", RegexOptions.Multiline &amp; RegexOptions.IgnorePatternWhitespace &amp; RegexOptions.CultureInvariant); MatchCollection matches = regExp.Matches(xmlDoc.InnerXml); </code></pre> <p>If I leave the whole stuff in one line and call this regexp without the multiline option, it does find every occurences. By leaving the file as it is and set the multiline option, it does not work. What is the problem, what should I change? Or is there any easier way to get the XML parts between these tags without regexp?</p>
<p>i believe the option to use is <code>RegexOptions.Singleline</code> instead of <code>RegexOptions.Multiline</code> (<a href="http://www.regular-expressions.info/dot.html">src</a>). allowing (.) to match newlines should work in your case.</p> <blockquote> <p>...the mode where the dot also matches newlines is called "single-line mode". This is a bit unfortunate, because it is easy to mix up this term with "multi-line mode". Multi-line mode only affects anchors, and single-line mode only affects the dot ... When using the regex classes of the .NET framework, you activate this mode by specifying RegexOptions.Singleline, such as in Regex.Match("string", "regex", RegexOptions.Singleline).</p> </blockquote>
File System indexing <p>I am creating an application were I need to scan a directory hive to find a certain file.</p> <p>I also want to better understand how indexing works.</p> <p>Can anyone point me to any resource preferably in C# that shows how I can create a basic index for file system searching?</p>
<p>So, it sounds like you need a library for doing searches.</p> <p>Lucene is a java search library, which has been <a href="http://incubator.apache.org/lucene.net/" rel="nofollow">ported to C#</a>. </p>
Difference between 2 dates in SQLite <p>How do I get the difference in days between 2 dates in SQLite? I have already tried something like this:</p> <pre><code>SELECT Date('now') - DateCreated FROM Payment </code></pre> <p>It returns 0 every time.</p>
<pre><code> SELECT julianday('now') - julianday(DateCreated) FROM Payment; </code></pre>
How can I make my image control's imageurl dynamic depending on host? <p>I am trying to convert my web application into a fully dynamic system. One thing I am trying to do is to load a different logo (set in the masterpage template) depending on the host.</p> <p>But, even though the code is hit (in page_init), there is no image displayed on any page inheriting the masterpage - no image, no red x's, nothing.</p> <p>My code looks like this (from masterpage, the path to the image is correct and pasted from Windows Explorer's property window path):</p> <pre><code>Protected Sub Page_Init(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Init If Request.Url.Host.Contains("localhost") Then Image1.ImageUrl = "C:\Users\firstname.lastname\Documents\Visual Studio 2008\WebSites\ecardsystem\images\ECard Platform.jpg." End If End Sub </code></pre> <p>I know that I can add the image on the fly using literal controls through codebehind, but this will mean I need to design the html too, by hand, when the design is all done and perfect. Thus this approach will create a bit more work.</p> <p>Thanks</p>
<p>Have you tried using a virtual path to the image relative to you website? Internet Explorer will generally not show images from a users local file system with the default security settings. Try putting the image in an images directory in your project and setting the URL to it's relative path:</p> <pre><code>Image1.ImageUrl = "~/images/Card Platform.jpg." </code></pre>
Automatically copying files from a Linux machine to a Windows machine <p>I need to automatically copy files from a linux machine to a windows one every day. </p> <p>I'm looking for something simple and secure like scp, rsync, sftp. Unfortunately, I'm at a loss of how to set this up on the Windows machine.</p> <p>Does anyone know how to do this?</p>
<p>You can try mounting the Windows drive as a mount point on the Linux machine, using smbfs; you would then be able to use normal Linux scripting and copying tools such as cron and scp/rsync to do the copying.</p>
What is best thing to call your namespace in .Net <p>In the past I've always gone and called my namespace for a particular project the same as the project (and principle class) e.g.:</p> <pre><code>namespace KeepAlive { public partial class KeepAlive : ServiceBase {... </code></pre> <p>Then from other projects whenever i've called that class its always been:</p> <pre><code>KeepAlive.KeepAlive()... </code></pre> <p>I'm now beginning to think that this might not be such a good idea, but I'm sort of stumped what to actually call my namespace. What do other people do? Do you just have one namespace for all your projects?</p>
<p>Having the name of a class being the same as the namespace is a bad idea - it makes it quite tricky to refer to the right thing in some cases, in my opinion.</p> <p>I usually call the project (and namespace) an appropriate name and then have "EntryPoint" or "Program" for the entry point where appropriate. In your example, I'd probably call the class "KeepAliveService".</p>
Where can I find the Maven installation directory in Eclipse 3.4 <p>I have installed m2eclipse plugin from <a href="http://m2eclipse.codehaus.org/" rel="nofollow">http://m2eclipse.codehaus.org/</a>. Now I want to use that as a standalone build tool but I am unable to find the installation directory. Can anyone help me in this?</p>
<p>I have both the plugin (with its embedded maven instance) and a full maven download. Both should end up using the same repository in something like <code>C:\Documents and Settings\user\.m2</code>. </p> <p>There are a few cases where you need a full maven download anyways. For example, trying to build a groovy maven plugin crashes with the embedded maven, but works fine for the full download.</p> <p>You can also specify from the preference pane in Eclipse, to use a differen maven installation than the embedded one. </p> <p>Hope this helps.</p>
Getting the current stack trace on Mac OS X <p>I'm trying to work out how to store and then print the current stack in my C++ apps on Mac OS X. The main problem seems to be getting dladdr to return the right symbol when given an address inside the main executable. I suspect that the issue is actually a compile option, but I'm not sure.</p> <p>I have tried the backtrace code from Darwin/Leopard but it calls dladdr and has the same issue as my own code calling dladdr.</p> <p>Original post: Currently I'm capturing the stack with this code:</p> <pre><code>int BackTrace(Addr *buffer, int max_frames) { void **frame = (void **)__builtin_frame_address(0); void **bp = ( void **)(*frame); void *ip = frame[1]; int i; for ( i = 0; bp &amp;&amp; ip &amp;&amp; i &lt; max_frames; i++ ) { *(buffer++) = ip; ip = bp[1]; bp = (void**)(bp[0]); } return i; } </code></pre> <p>Which seems to work ok. Then to print the stack I'm looking at using dladdr like this:</p> <pre><code>Dl_info dli; if (dladdr(Ip, &amp;dli)) { ptrdiff_t offset; int c = 0; if (dli.dli_fname &amp;&amp; dli.dli_fbase) { offset = (ptrdiff_t)Ip - (ptrdiff_t)dli.dli_fbase; c = snprintf(buf, buflen, "%s+0x%x", dli.dli_fname, offset ); } if (dli.dli_sname &amp;&amp; dli.dli_saddr) { offset = (ptrdiff_t)Ip - (ptrdiff_t)dli.dli_saddr; c += snprintf(buf+c, buflen-c, "(%s+0x%x)", dli.dli_sname, offset ); } if (c &gt; 0) snprintf(buf+c, buflen-c, " [%p]", Ip); </code></pre> <p>Which almost works, some example output:</p> <pre><code>/Users/matthew/Library/Frameworks/Lgi.framework/Versions/A/Lgi+0x2473d(LgiStackTrace+0x5d) [0x102c73d] /Users/matthew/Code/Lgi/LgiRes/build/Debug/LgiRes.app/Contents/MacOS/LgiRes+0x2a006(tart+0x28e72) [0x2b006] /Users/matthew/Code/Lgi/LgiRes/build/Debug/LgiRes.app/Contents/MacOS/LgiRes+0x2f438(tart+0x2e2a4) [0x30438] /Users/matthew/Code/Lgi/LgiRes/build/Debug/LgiRes.app/Contents/MacOS/LgiRes+0x35e9c(tart+0x34d08) [0x36e9c] /Users/matthew/Code/Lgi/LgiRes/build/Debug/LgiRes.app/Contents/MacOS/LgiRes+0x1296(tart+0x102) [0x2296] /Users/matthew/Code/Lgi/LgiRes/build/Debug/LgiRes.app/Contents/MacOS/LgiRes+0x11bd(tart+0x29) [0x21bd] </code></pre> <p>It's getting the method name right for the shared object but not for the main app. Those just map to "tart" (or "start" minus the first character).</p> <p>Ideally I'd like line numbers as well as the method name at that point. But I'll settle for the correct function/method name for starters. Maybe shoot for line numbers after that, on Linux I hear you have to write your own parser for a private ELF block that has it's own instruction set. Sounds scary.</p> <p>Anyway, can anyone sort this code out so it gets the method names right?</p>
<p>What releases of OS X are you targetting. If you are running on Mac OS X 10.5 and higher you can just use the backtrace() and backtrace_symbols() libraray calls. They are defined in execinfo.h, and there is a <a href="http://developer.apple.com/documentation/Darwin/Reference/ManPages/man3/backtrace.3.html">manpage</a> with some sample code. </p> <p>Edit:</p> <p>You mentioned in the comments that you need to run on Tiger. You can probably just include the implementation from Libc in your app. The source is available from Apple's opensource site. Here is a link to the relevent <a href="http://www.opensource.apple.com/darwinsource/10.5.5/Libc-498.1.1/gen/backtrace.c">file</a>.</p>
Auto Font Size For Text (GD via PHP) <p>There is a space of x*y for text to go on $im (GD Image Resource) how can I choose a font size (or write text such that) it does not overflow over that area?</p>
<p>I think you look for the <a href="http://fr.php.net/manual/en/function.imagettfbbox.php" rel="nofollow" title="imagettfbbox">imagettfbbox</a> function.</p> <p>I used that some years ago for a script generating localized buttons for a Web interface. I actually resized buttons if the text didn't fit in the template, to keep text size consistent, but you can try to reduce the text size until the text fits.</p> <p>If you are interested, I can paste some snippets of my code (or give it right away).</p> <p>[EDIT] OK, here is some extracts of my code, someday I will clean it up (make it independent of target app, give samples) and make it public as a whole.<br /> I hope the snippets make sense.</p> <pre><code>// Bounding boxes: ImageTTFBBox, ImageTTFText: // Bottom-Left: $bb[0], $bb[1] // Bottom-Right: $bb[2], $bb[3] // Top-Right: $bb[4]; $bb[5] // Top-Left: $bb[6], $bb[7] define('GDBB_TOP', 5); define('GDBB_LEFT', 0); define('GDBB_BOTTOM', 1); define('GDBB_RIGHT', 2); #[ In class constructor ]# // Get size in pixels, must convert to points for GD2. // Because GD2 assumes 96 pixels per inch and we use more "standard" 72. $this-&gt;textSize *= 72/96; $this-&gt;ComputeTextDimensions($this-&gt;textSize, FONT, $this-&gt;text); #[ Remainder of the class (extract) ] /** * Compute the dimensions of the text. */ function ComputeTextDimensions($textSize, $fontFile, $text) { $this-&gt;textAreaWidth = $this-&gt;imageHSize - $this-&gt;marginL - $this-&gt;marginR; $this-&gt;textAreaHeight = $this-&gt;imageVSize - $this-&gt;marginT - $this-&gt;marginB; // Handle text on several lines $this-&gt;lines = explode(NEWLINE_CHAR, $text); $this-&gt;lineNb = count($this-&gt;lines); if ($this-&gt;lineNb == 1) { $bb = ImageTTFBBox($textSize, 0, $fontFile, $text); $this-&gt;textWidth[0] = $bb[GDBB_RIGHT] - $bb[GDBB_LEFT]; $this-&gt;maxTextWidth = $this-&gt;textWidth[0]; $this-&gt;textHeight[0] = $bb[GDBB_BOTTOM] - $bb[GDBB_TOP]; } else { for ($i = 0; $i &lt; $this-&gt;lineNb; $i++) { $bb = ImageTTFBBox($textSize, 0, $fontFile, $this-&gt;lines[$i]); $this-&gt;textWidth[$i] = $bb[GDBB_RIGHT] - $bb[GDBB_LEFT]; $this-&gt;maxTextWidth = max($this-&gt;maxTextWidth, $this-&gt;textWidth[$i]); $this-&gt;textHeight[$i] = $bb[GDBB_BOTTOM] - $bb[GDBB_TOP]; } } // Is the given text area width too small for asked text? if ($this-&gt;maxTextWidth &gt; $this-&gt;textAreaWidth) { // Yes! Increase button size $this-&gt;textAreaWidth = $this-&gt;maxTextWidth; $this-&gt;imageHSize = $this-&gt;textAreaWidth + $this-&gt;marginL + $this-&gt;marginR; } // Now compute the text positions given the new (?) text area width if ($this-&gt;lineNb == 1) { $this-&gt;ComputeTextPosition(0, $textSize, $fontFile, $text, false); } else { for ($i = 0; $i &lt; $this-&gt;lineNb; $i++) { $this-&gt;ComputeTextPosition($i, $textSize, $fontFile, $this-&gt;lines[$i], false); } } } /** * Compute xText and yText (text position) for the given text. */ function ComputeTextPosition($index, $textSize, $fontFile, $text, $centerAscDesc) { switch ($this-&gt;textAlign) { case 'L': $this-&gt;xText[$index] = $this-&gt;marginL; break; case 'R': $this-&gt;xText[$index] = $this-&gt;marginL + $this-&gt;textAreaWidth - $this-&gt;textWidth[$index]; break; case 'C': default: $this-&gt;xText[$index] = $this-&gt;marginL + ($this-&gt;textAreaWidth - $this-&gt;textWidth[$index]) / 2; break; } if ($centerAscDesc) { // Must compute the difference between baseline and bottom of BB. // I have to use a temporary image, as ImageTTFBBox doesn't use coordinates // providing offset from the baseline. $tmpBaseline = 5; // Image size isn't important here, GD2 still computes correct BB $tmpImage = ImageCreate(5, 5); $bbt = ImageTTFText($tmpImage, $this-&gt;textSize, 0, 0, $tmpBaseline, $this-&gt;color, $fontFile, $text); // Bottom to Baseline $baselinePos = $bbt[GDBB_BOTTOM] - $tmpBaseline; ImageDestroy($tmpImage); $this-&gt;yText[$index] = $this-&gt;marginT + $this-&gt;textAreaHeight - ($this-&gt;textAreaHeight - $this-&gt;textHeight) / 2 - $baselinePos + 0.5; } else { // Actually, we want to center the x-height, ie. to keep the baseline at same pos. // whatever the text is really, ie. independantly of ascenders and descenders. // This provide better looking buttons, as they are more consistent. $bbt = ImageTTFBBox($textSize, 0, $fontFile, "moxun"); $tmpHeight = $bbt[GDBB_BOTTOM] - $bbt[GDBB_TOP]; $this-&gt;yText[$index] = $this-&gt;marginT + $this-&gt;textAreaHeight - ($this-&gt;textAreaHeight - $tmpHeight) / 2 + 0.5; } } /** * Add the text to the button. */ function DrawText() { for ($i = 0; $i &lt; $this-&gt;lineNb; $i++) { // Increase slightly line height $yText = $this-&gt;yText[$i] + $this-&gt;textHeight[$i] * 1.1 * ($i - ($this-&gt;lineNb - 1) / 2); ImageTTFText($this-&gt;image, $this-&gt;textSize, 0, $this-&gt;xText[$i], $yText, $this-&gt;color, FONT, $this-&gt;lines[$i]); } } </code></pre>
Why this union's size is 2 with bitfields? <p>I am working on turbo C on windows where char takes one byte.Now my problem is with the below union.</p> <pre><code>union a { unsigned char c:2; }b; void main() { printf("%d",sizeof(b)); \\or even sizeof(union a) } </code></pre> <p><p>This program is printing output as 2 where as union should be taking only 1 byte. Why is it so? <p>for struct it is fine giving 1 byte but this union is working inappropriately. <p><b>And one more </b>thing how to access these bit fields.</p> <pre><code>scanf("%d",&amp;b.c); //even scanf("%x",b.c); </code></pre> <p><p>is not working because we cannot have address for bits.So we have to use another variable like below</p> <pre><code>int x; scanf("%d",&amp;x); b.c=x; </code></pre> <p><p>cant we avoid it?? is there any other way???</p>
<p>Compilers are allowed to add padding to structs and unions and while, I admit, that it's a little surprising that yours does round up the union to a two byte size when you are able to get a one byte struct it is perfectly allowed.</p> <p>In answer to your second question: no it's not avoidable. Bit fields are a struct packing optimization and the performance and convenience penalty to pay is that bit field members are not individually addressable.</p>
Apple DMG files over FTP are getting corrupted why? <p>I am trying to FTP some apple DMG files, if we do it by hand through Safari or IE it ends up at the destination just fine and uncorrupted. However, if I use a freeware FTP client that we had been using with great success for zip's and exe's or if I use a Powershell script I finished off (adapted from another stackover flow's question's answer) then I lose about a 1/2 Mb on a 10.5 Mb file and the dmg is corrupted. Does anyone have anyclues what could be going wrong? Things I could do to prevent it? So far all I have tried is gzipping the dmg before sending and that accomplished nothing. Again, anything but a dmg gets transmitted just fine.</p> <p>FYI I am using binary mode transfers, so that is not it..thx though</p>
<p>Seems like your client treats dmg file as text file. set Binary transfer mode in your ftp client and it will ftp it as is.</p> <p>I always thought that ascii transfer mode in ftp is just plain stupid. It causes more trouble then it is worth.</p>
Is there a delegate available for properties in C#? <p>Given the following class: </p> <pre><code>class TestClass { public void SetValue(int value) { Value = value; } public int Value { get; set; } } </code></pre> <p>I can do </p> <pre><code>TestClass tc = new TestClass(); Action&lt;int&gt; setAction = tc.SetValue; setAction.Invoke(12); </code></pre> <p>which is all good. Is it possible to do the same thing using the property instead of the method? Preferably with something built in to .net. </p>
<p>You could create the delegate using reflection :</p> <pre><code>Action&lt;int&gt; valueSetter = (Action&lt;int&gt;)Delegate.CreateDelegate(typeof(Action&lt;int&gt;), tc, tc.GetType().GetProperty("Value").GetSetMethod()); </code></pre> <p>or create a delegate to an anonymous method which sets the property;</p> <pre><code>Action&lt;int&gt; valueSetter = v =&gt; tc.Value = v; </code></pre> <p>Edit: used wrong overload for CreateDelegate(), need to use the one that takes and object as target. Fixed.</p>
How can I get the X,Y position of a TWinControl (relative to the screen) <p>I'm trying to show a custom hint in a TWinControl but I can't figure out how to get it's position.</p> <p>Using position 0,0 shows the hint on the top of my screen (outside the window) so I guess it must be the position of the control on the screen.</p> <p><strong>Edit:</strong></p> <p>I've found the TControl Property ClientOrigin which returns what I've expected, is it correct to use ClientOrigin.X and ClientOrigin.Y?</p>
<p>TControl.ClientToScreen gives you the screen coordinates for a given point within the control.</p> <pre><code>lPoint := Panel1.ClientToScreen(Point(0,0)); Label1.Caption := Format('Screen: %d, %d', [lPoint.X, lPoint.Y]); </code></pre>
Toolbar and treeview Icons missing when displaying CHM file using HH API <p>Just encountered an interesting problem. I have a CHM file. If I display it using Process.Start it displays correctly.</p> <p>If however I launch it using the HH API it displays without any icons in the toolbar and treeview; the main content, including graphics, displays correctly. Here's what it looks like - with a few article titles scribbled out: <img src="http://img527.imageshack.us/img527/3430/problemhelpfilehl2.png" alt="alt text" /></p> <p>The same file works fine on a colleagues machine with the same setup.</p> <p>Any thoughts as to what's going on?</p>
<p>It seems that the problem was that I was giving HH API a relative path to the help file. Now that I'm using an absolute path the problem seems to have gone away.</p>
How to check if DLL is debug-compiled <blockquote> <p><strong>Possible Duplicate:</strong><br> <a href="http://stackoverflow.com/questions/194616/how-to-tell-if-net-app-was-compiled-in-debug-or-release-mode">How to tell if .net app was compiled in DEBUG or RELEASE mode?</a> </p> </blockquote> <p>Simple Question; Is there an easy way to check whether a .NET 1.1 assembly is debug-compiled or not?</p>
<p>It depends on how you want to check. If you want to check in code when you are actually running, if the code is in debug mode, you can use:</p> <pre><code>Debug.Assert(MyFunction()) </code></pre> <p>Using that code, MyFunction will only run when the dll it is located in is compiled in debug mode.</p>
jQuery droppables - Change element on drop <p>I'm a bit new to jQuery and hope somebody can help me out.</p> <p>I'm trying to change an element (li) to another element (div) after the (li) has been dropped.</p> <p>Sample code:</p> <pre><code>$("#inputEl&gt;li").draggable({ revert: true, opacity: 0.4, helper: "clone" }); $("#dropEl") .droppable({ accept: ".drag", hoverClass: "dropElhover", drop: function(ev, ui) { // change the li element to div here } }); </code></pre> <p>The problem is, when i use</p> <pre><code>drop: function(ev, ui) { $(ui.draggable).replaceWith("&lt;div&gt;Some content&lt;/div&gt;"); } </code></pre> <p>the original draggable elements will be disabled when the function above is triggered.</p> <p>I'm using the latest jQuery and jQuery UI stable versions.</p>
<p>So, what you want is to keep your original list intact and drop list items into dropEl? How about this:</p> <pre><code>drop: function(ev,ui) { $(this).append("&lt;div&gt;Some content&lt;/div&gt;"); } </code></pre> <p>Or, if you want to replace the list elements with a div element and also have the div element draggable, you could try this:</p> <pre><code>drop: function(ev, ui) { $(ui.draggable).replaceWith("&lt;div&gt;Some content&lt;/div&gt;"); $("#inputEl&gt;div").draggable({ revert: true, opacity: 0.4, helper: "clone" }); } </code></pre> <p>The original draggable call only makes items draggable at the time it is called. If you change or add elements and want them to be draggable, you will need to call the draggable() function again.</p>
Sliding Notification bar in java (a la Firefox) <p>I would like to implement a sliding notification bar as the one in Firefox or IE for my java application. But I don't want to reinvent the wheel and I'm sure someone out there has already done it and is willing to share. Do you know any open-source implementation of this in java/swing?</p>
<p>There's an example in <a href="http://rads.stackoverflow.com/amzn/click/0596009070" rel="nofollow">Swing Hacks</a> called "Slide Notes Out from the Taskbar" that seems pretty close to what you want (there's a <a href="http://books.google.com/books?id=oNbFfcyAtv4C&amp;pg=PA240&amp;dq=%22Swing+hacks%22+%22slide+notes+out+from+the+taskbar%22" rel="nofollow">preview</a> on Google's Book Search at the moment). </p> <p>The code is freely available from the <a href="http://oreilly.com/catalog/9780596009076/" rel="nofollow">official O'Reilly Swing Hacks page</a>, under "examples." Not sure what the license is, but it's worth a look (Chapter 6, hack 46). At any rate, Swing Hacks is a worthy purchase at ~$20.</p>
Internet Explorer serves up unknown file type <p>I have a web server on port 80 and port 81. IE can connect to the server on either port. This worked fine until I installed an application with a file type (.TPJ) that had a MIME type of text/xml on the client PC. At that point IE no longer opened the web site, but offered to download a file <em>serverName.TPJ</em>. The file contained the correct information from the web site.</p> <p>I changed the installer for the application so it didn't register the MIME type. Now IE on the client PC offers to download a file with unknown file type. Note that the application has never been installed on the server PC.</p> <p>The problem occurs with IE7. It doesn't occur with Firefox, Safari, or Chrome.</p> <p>Does anyone know how to work around this?</p>
<p>I found the answer. There is a left-over entry in the registry for the text/xml MIME type. It can be restored to the default value by re-registering the MSXML3.DLL.</p> <pre><code>regsvr32 msxml3.dll </code></pre>
SQL Server and the Guest Account - what is this for? <p>How is the guest account in SQL Server (2000, 2005, 2008) supposed to be used? What is it good for? I've tried enabling the account but I still can't get certain users to be able to refresh Excel 2007 PivotTables attached to views which I have given SELECT rights to GUEST.</p> <p>What am I missing? </p>
<p>Guest is mostly just for allowing access to the database, using the Public role. Don't think it's meant to be something that users actually log in as...</p> <p>When a database is created, the database includes the Guest user by default. Permissions granted to the Guest user are inherited by users that do not have a user account in the database.</p>
Can someone explain the Flickr API and how security is established? Why not use AES instead of md5? <p>Just trying to understand Flickr's API setup, and how secure it really is.</p> <p><a href="http://www.flickr.com/services/api/auth.howto.web.html" rel="nofollow">Flickr API</a></p> <p>Why do a MD5 hash and not something like AES?</p>
<p>The hash is strictly a signature, so a one-way hash like MD5 is good enough for their usage. If there's a collision (unlikely but possible) they'll just re-hash.</p> <p>No need to make it more complicated than it has to be.</p>
ListView Shows Repeated Elements When the Underlying Generic List Does Not Contain Repeated Elements <p>I am binding a generic List to an &lt;asp:ListView /&gt; control to display a tag cloud. The elements in the list are Tag objects, where Tag is basically just something like:</p> <pre><code>public class Tag { public string Name { get; set; } public int Total { get; set; } } </code></pre> <p>I create the List&lt;Tag&gt; object and then bind it to a ListView but when the HTML is rendered for the page certain Tag objects are repeated e.g. given the expected tag list of <strong>apple, banana, kiwi, orange, strawberry</strong> the HTML would actually output something like <strong><em>apple, banana, apple, apple, strawberry</em></strong>.</p> <p>I am writing out the contents of my underlying List&lt;Tag&gt; to the Trace.axd and that shows the elements to be in the correct order without duplicates.</p> <p>Has anyone ever come across something similar?</p>
<p>Could you put some more code up? Perhaps you are using some reference variables that are using the same memory location? It's hard to tell with the code you uploaded.</p>
Advice about forming Hackers Club <p>I'm thinking of forming a <a href="http://www.catb.org/~esr/jargon/html/H/hacker.html" rel="nofollow">Hacker</a>s Club at work. My idea is that we would meet monthly and at each meeting one member would present an interesting hack he had created. (The hacks presented wouldn't necessarily have to be software hacks; they could also be the sort of things you read about in <em>MAKE</em> magazine.) </p> <p>There would also be <a href="http://www.catb.org/~esr/jargon/html/A/ANSI-standard-pizza.html" rel="nofollow">ANSI standard pizza</a>, veggie pizza, and beer and pop available for socializing afterward. I'm even thinking of calling the club "<a href="http://www.catb.org/~esr/jargon/html/T/TMRC.html" rel="nofollow">TMRC</a>" even though it will have nothing to do with model railroads.</p> <p>Has anyone ever tried doing something like this or have any advice?</p>
<p>We do this at the office. I call it 'Developer Fight Club'</p> <p>Usually do challenges of varying difficulty and compete against one another.</p> <p>At the end of it, we go over our solutions, do code-reviews and discussions, and then use either benchmark results or other people as the deciding factor for who wins.</p> <p>Typically, the loser has to buy lunch for the winner :)</p> <p>For ideas of things to do, try stuff from <a href="http://www.topcoder.com/tc" rel="nofollow">Top Coder</a>, programming questions on Stack Overflow, or even simple "<a href="http://en.wikipedia.org/wiki/Crackme" rel="nofollow">crackme</a>" applications available on different programming sites.</p> <p>The main rules you'll need to adhere to are:</p> <ul> <li>Make It Fun</li> <li>Make It Educational Make</li> <li>Make It Fair</li> </ul> <p>Try to rotate the challenges, so either everyone is really good at the subject, equally bad, or at least mix it up often enough that it doesn't favor one person's skillset too much.</p>
control lost focus event when using keyboard shortcut <p>For both .NET Winforms and Windows Presentation Foundation, if I have a text box that the user has just entered text into, and a button, if the user clicks the button the "LostFocus" event fires before the button click event fires. However if the user uses a keyboard shortcut for the button (e.g. Button's text is "&amp;Button" or "_Button" and user performs Alt+B), then the "LostFocus" event fires after the button click event, which is less useful.</p> <p>Do you know of reasonable workarounds? We have various things that we want to occur in LostFocus before ButtonClick.</p>
<p>You could try tracking whether or not the lost focus logic has occured before firing the button logic. You shouldn't really have code directly in the handler anyway. You could do something like this:</p> <pre><code>public partial class Form1 : Form { private Boolean _didLostFocusLogic; public Form1() { InitializeComponent(); } private void textBox1_Leave(object sender, EventArgs e) { LostFocusLogic(); } private void button1_Click(object sender, EventArgs e) { ButtonClickLogic(); } private void LostFocusLogic() { /* Do stuff */ _didLostFocusLogic = true; } private void ButtonClickLogic() { if (!_didLostFocusLogic) LostFocusLogic(); _didLostFocusLogic = false; // Reset for next time. /* Do stuff */ } } </code></pre>
Updating sort keys after delete <p>I have a table which has a field <code>sort_id</code>. In this field there are numbers from 1 to n, that define the order of the data sets. Now I want to delete some elements and afterwards I want to reorder the table. Therefore I need a query that "finds" the gaps and changes the <code>sort_id</code> field according to the modifications.</p> <p>Sure, I could do something like this:</p> <pre><code>SELECT sort_id FROM table WHERE id = 5 </code></pre> <p>Then save the sort_id and afterwards:</p> <pre><code>DELETE FROM table WHERE id = 5 UPDATE table SET sort_id = sort_id - 1 WHERE sort_id &gt; {id from above} </code></pre> <p>But I'd like to do the reordering process in one step.</p>
<p>Mladen and Arvo have good ideas, but unfortunately in MySQL you can't <code>SELECT</code> and <code>UPDATE</code> the same table in the same statement (even in a subquery). This is a known limitation of MySQL.</p> <p>Here's a solution that uses MySQL user variables:</p> <pre><code>SET @i := 0; UPDATE mytable SET sort_id = (@i := @i + 1) ORDER BY sort_id; </code></pre> <p>For what it's worth, I wouldn't bother doing this anyway. If your <code>sort_id</code> is used only for sorting and not as a kind of "row number," then the rows are still in sorted order after you delete the row where <code>id=6</code>. The values don't necessarily have to be consecutive for sorting.</p>
DB-side encryption via NHibernate <p>We're looking to encrypt a field using DB-side encryption via NHibernate (most examples we've come across are app-side, which is not what we would like). The issue has been raised a couple of times, but no answers yet it seems. </p> <p>On SQL Server 2005, for instance, and forgetting key-related issues for now, this means INSERTing EncryptByKey(Key_GUID(MyKey), MyValueToEncrypt) and SELECTing DecryptByKey(MyEncryptedField). The property might be a string, whereas the field has to be a varbinary. </p> <p>We've vaguely got somewhere - using upper() and lower() instead of encryption functions - by combining paired properties, one mapped with a custom user type and the other with a formula attribute. </p> <p>However if anyone has any ideas on how to do this in a nicer way, we'd be most grateful for a few pointers :o) </p>
<p>Posted outline of nasty hack on the <a href="http://forum.hibernate.org/viewtopic.php?p=2400105#2400105" rel="nofollow">NHibernate forum</a></p>
How can you concatenate two huge files with very little spare disk space? <p>Suppose that you have two huge files (several GB) that you want to concatenate together, but that you have very little spare disk space (let's say a couple hundred MB). That is, given <code>file1</code> and <code>file2</code>, you want to end up with a single file which is the result of concatenating <code>file1</code> and <code>file2</code> together byte-for-byte, and delete the original files.</p> <p>You can't do the obvious <code>cat file2 &gt;&gt; file1; rm file2</code>, since in between the two operations, you'd run out of disk space.</p> <p>Solutions on any and all platforms with free or non-free tools are welcome; this is a hypothetical problem I thought up while I was downloading a Linux ISO the other day, and the download got interrupted partway through due to a wireless hiccup.</p>
<p>time spent figuring out clever solution involving disk-sector shuffling and file-chain manipulation: 2-4 hours</p> <p>time spent acquiring/writing software to do in-place copy and truncate: 2-20 hours</p> <p>times median $50/hr programmer rate: $400-$1200</p> <p>cost of 1TB USB drive: $100-$200</p> <p>ability to understand the phrase "opportunity cost": priceless</p>
Toolbar moves up when call finishes <p>While in a call, if the user wants to use my application, and if the call finishes, and the user is still in the application, the toolbar moves up, well all the view moves up, and so the toolbar now has a space in the bottom. Basically the height "Touch to return to call" has. I am using a toolbar and a navigation controller. The navigation controller moves fine, and everything in the view moves accordingly, the only problem is with the toolbar. So the question is, Is there an event, which is called after the call is finished, so I can set the frame again of my toolbar? I tried this delegate with no luck:</p> <pre><code>- (void)application:(UIApplication *)application willChangeStatusBarFrame:(CGRect)newStatusBarFrame </code></pre> <p>This one is called only when the toolbar is changing orientation.</p> <p><img src="http://is.hn/downloads/IMG_0008.PNG" alt="alt text" /> <img src="http://is.hn/downloads/IMG_0009.PNG" alt="alt text" /></p> <p>Thanks.</p>
<p>In general setting your auto resize masks properly should fix things. Could you update with a screenshot to show exactly where the resizing issues are happening?</p>
Array slicing / group_concat limiting in MySQL <p>Let's say I have a table:</p> <pre> i j --- a 1 a 2 a 3 a 4 b 5 b 6 b 7 b 8 b 9 </pre> <p>Obvoiusly <code>SELECT a, GROUP_CONCAT(b SEPARATOR ',') GROUP BY a</code> would give me</p> <pre> a 1,2,3,4 b 5,6,7,8,9 </pre> <p>But what if I want to get only a LIMITED number of results, like 2, for example:</p> <pre> a 1,2 b 5,6 </pre> <p>Any ideas?</p>
<p>Best way is to use <code>SUBSTRING_INDEX()</code> and <code>GROUP_CONCAT()</code>.</p> <pre><code>SELECT i, SUBSTRING_INDEX( GROUP_CONCAT(j), ',', 2) FROM mytable GROUP BY i; </code></pre> <p>You don't have to know the length of <code>j</code> field here.</p>
Sample web Page using Mono and XSP on windows box <p>I'm attempting to get my first ASP.NET web page working on windows using <a href="http://www.mono-project.com/Main_Page" rel="nofollow">Mono</a> and the XSP web server.</p> <p>I'm following this chaps <a href="http://www.codeproject.com/KB/cross-platform/introtomono2.aspx" rel="nofollow">example</a>. The <a href="http://www.codeproject.com/KB/cross-platform/introtomono1.aspx" rel="nofollow">first part</a> of his example works very well with the latest version of mono. however the web part seems to fall over with the following error</p> <blockquote> <p>'{Path Name}\Index.aspx.cs' is not a valid virtual path.</p> </blockquote> <p>Here's the full Stack Trace:</p> <pre><code>System.Web.HttpException: 'C:\Projects\Mono\ASPExample\simpleapp\index.aspx.cs' is not a valid virtual path. at System.Web.HttpRequest.MapPath (System.String virtualPath, System.String baseVirtualDir, Boolean allowCrossAppMapping) [0x00000] at System.Web.HttpRequest.MapPath (System.String virtualPath) [0x00000] at System.Web.Compilation.BuildManager.AddToCache (System.String virtualPath, System.Web.Compilation.BuildProvider bp) [0x00000] at System.Web.Compilation.BuildManager.BuildAssembly (System.Web.VirtualPath virtualPath) [0x00000] at System.Web.Compilation.BuildManager.GetCompiledType (System.String virtualPath) [0x00000] at System.Web.Compilation.BuildManager.CreateInstanceFromVirtualPath (System.String virtualPath, System.Type requiredBaseType) [0x00000] at System.Web.UI.PageParser.GetCompiledPageInstance (System.String virtualPath, System.String inputFile, System.Web.HttpContext context) [0x00000] at System.Web.UI.PageHandlerFactory.GetHandler (System.Web.HttpContext context, System.String requestType, System.String url, System.String path) [0x00000] at System.Web.HttpApplication.GetHandler (System.Web.HttpContext context, System.String url, Boolean ignoreContextHandler) [0x00000] at System.Web.HttpApplication.GetHandler (System.Web.HttpContext context, System.String url) [0x00000] at System.Web.HttpApplication+&lt;Pipeline&gt;c__Iterator5.MoveNext () [0x00000] </code></pre> <p>I was wondering if anyone knew what this error meant. I guess i'm looking for a mono expert, who's tried out the windows version.</p>
<p>Can you paste the command line you are using to start xsp? If you are just running a single webapp something like this isn't really needed, and could be the source of the problem:</p> <p>xsp --applications /SimpleWebApp:C:\Projects\Mono\ASPExample\ </p> <p>just cd to the ASPExample directory and run xsp with no parameters.</p>
Inconsistencies with viewstate/function/server vs development server <p>The code goes something like this:</p> <pre><code>protected bool IsOKToSend() { bool IsOK = true; lblErrorSending.Visible = false; if (txtUserName.Text == "" ) { lblErrorSending.Text = "Please enter your username before sending."; IsOK = false; } return IsOK; } protected void btnSubmit_Click(object sender, EventArgs e) { if (IsOKToSend()) { adsUser.Insert(); Response.Redirect("complete.aspx"); } else { lblErrorSending.Visible = true; } } </code></pre> <p>For some reason it doesn't work consistently on the live server. Keep in mind that it ALWAYS works on my local development machine and SOMETIMES (about 1 in 3 tries) works on the live machine. When it fails on the live server the page reloads and all viewstate are lost.</p> <p>I have a default error catch in my webconfig file and the page is never redirected to the error page.</p> <p>Consistent bug are easy to troubleshoot but something like this isn't.</p> <p>Any idea on what could make this page sometime works and sometime not and/or why the viewstate aren't kept when it fails to work? Why am I not getting the same problem on my local machine?</p> <p>I tried merging the two function to see if calling the external function was causing the issue but it didn't change anything unfortunately. Also, the value of IsOK does not seem to influence whether I'll get the bug or not.</p> <p>I removed all the code in the page load function to make sure to troubleshoot correctly but I'm still getting the same issue.</p> <p>Any idea will be appreciated.</p> <p>Edit: I was gonna send this as is but I decided to try the following:</p> <pre><code>protected void btnSubmit_Click(object sender, EventArgs e) { bool IsOK = true; lblErrorSending.Visible = false; if (txtUserName.Text == "" ) { lblErrorSending.Text = "Please enter your username before sending."; IsOK = false; } lblErrorSending.Visible = !IsOK; } </code></pre> <p>If I click a few times on the button the page does lose the viewstate value after a few tries but not always. So the main issue here appears to be a problem with the viewstate not working correctly all the time. Any idea?</p> <p>Thanks.</p>
<p>I will take a wild guess here and say you are not using sticky sessions in production and you have multiple web servers. But in development you have only one server. You are using load balancing and every so often you get kicked to a different server with a different machinekey in your maching.config. App goes boom. </p> <p>Or this isn't it at all. :)</p> <p>If it is the problem, you can turn off viewstate or sync the keys in your machine.config and the problem should go away.</p>
Determine whether browser allows focus on radios/checkboxes <p>Does anyone know if it's possible to determine, using JavaScript, whether the user's browser allows checkboxes and radio buttons to be focused? In other words, whether you can tab to select them.</p> <p>I can't just use browser detection to do this, because in at least one case (Safari), the user can turn the ability on and off.</p> <p>Also in Safari, the focus() function is defined even when this ability is turned off, and it doesn't throw an error. So checking that function won't work.</p>
<p>One approach is to try to set the focus and then detect if it was successful. Do this by assigning an onfocus event that set a variable to true, try to focus it and then check if the variable is true. </p>
Migrating from one DBMS to another <p>Does anyone have any experience migrating from one DBMS to another? If you have done this, why did you do it? Features? Cost? Corporate Directive?</p> <p>At times, I've worked with DBAs who insisted that we not use features specific to a DBMS (for example, CLR Stored Procedures in SQL Server.) The DBAs point is, if we use these features, it will make it more difficult to switch to another DBMS if we have to. But so far, I've never been asked to switch.</p>
<p>In my opinion its silly not to take advantage of all the features of the db your using. Changing DBMS regardless of how many features you use is going to be difficult. There are minute differences between the systems (like some record Date and some record date and time) that will cause a huge headache to change. There is no such thing of just switching to a new dbms. </p> <p>From a business perspective there is a lot of work to be done. Analysis on the new dbs to change to. Figuring out the impact of changing dbs on the new system. Having development change the existing systems, testing the changes etc. The list goes on and on. Making a switch like that on an enterprise system takes months if not years. The last place I worked had to change dbs, and it took us a solid 11 months to do it and about 2 million dollars for consultants, hardware, software, and employee salaries. It's a big deal. If someone is saying not to use features, because that "may" happen someday and it'll be easier to do, Most likely, that person is off their rocker. The extra amount of time and money it will take to convert those features is minuscule compared to everything else (most likely). IMO if it will save time and money now buy using those features, then that is the best course of action. </p> <p>We did it because the systems we had running on the old dbms were too big. There was too much data, and we needed something a lot more powerful. Plus, it wasn't supported anymore.</p>
Windows Forms Error: "A strongly-named assembly is required" <p>I have a Windows forms project (VS 2005, .net 2.0). The solution has references to 9 projects. Everything works and compiles fine on one of my computers. When I move it to a second computer, 8 out of the 9 project compile with no problem. When I try to compile the 9th project (the main project for the application - produces the .exe file to execute the application), I get the following error: </p> <pre><code>'Error 3: A strongly-named assembly is required. (Exception from HRESULT: 0x80131044)' </code></pre> <p>The file location for the error is is listed as "C:\PATH-TO-APP\LC". </p> <p>I have checked in the project properties and all of the projects are set to build in Debug mode, none of them are supposed to be signed. In the project that is failing, the only assembly that it references that is not in any of the other projects is Microsoft.VisualBasic (a .net 2.0 assembly). So I am at a loss to find what ids causing this error (the file referenced above in the error message - "LC" - does not exist. </p> <p>Anyone know how I can force the project to accept all unsigned assemblies, or to determine which assembly is the culprit?</p> <p>The only meaningful difference between the dev environments between the dev environment where this worked and the current one is that the first was XP and this is Vista64. However, a colleague of mine who is using XP is getting the same error.</p> <p><strong>Third-party assemblies being used:</strong></p> <ul> <li>ComponentFactory.Krypton.Toolkit</li> <li>ComponentFactory.Krypton.Navigator</li> <li>VistaDB.NET20</li> </ul> <p>All of these are referenced in other projects in the solution which build with no problems, so it doesn't look like these are the problem.</p> <p>So far I have tried deleting the suo file, Rebuild All, unloading and reloading projects from the solution, removing and readding referenced assemblies. Nothing has worked.<code> </code></p>
<p>I just got it to build by doing the following:</p> <p>There had been a licenses file in the Properties of the project in question. After deleting the file (it was no longer needed) the project was able to build successfully. So it looks like that was the culprit.</p>
Tree library for PHP using left & right ids <p>I'm looking for a library in PHP that can create a tree structure from a database (or array of values) with left and right ids. For the result when getting values I am only looking for an array so I can create any type of view. For adding and removing, it would be nice if the library did it all. Even if the library is within another library, I don't mind as I'll probably pull it out and integrate it with my own libraries.</p> <p>Anyone know of anything?</p> <p>I'm using PHP &amp; MySQL, so it'd be helpful if it used atleast PHP. If it's a different database I can probably convert it, although maybe the same with PHP if it doesn't use too much language specific functionality.</p>
<p><a href="http://ezcomponents.org/docs/tutorials/Tree#database-based-back-ends" rel="nofollow">ezComponents Tree</a> library has different backends (tie-ins), that you can choose between. The documentation is pretty good as well.</p>
invalid QName when transforming a .net XSLTransform <p>I have a piece of XML that is structured similar to this:</p> <pre><code> &lt;root&gt; &lt;score name="Exam 1"&gt;&lt;value&gt;76&lt;/value&gt;&lt;/score&gt; &lt;score name="Exam 2"&gt;&lt;value&gt;87&lt;/value&lt;/score&gt; &lt;/root&gt; </code></pre> <p>and I would like to transform it to look like this:</p> <pre><code>&lt;root&gt; &lt;Exam 1&gt;76&lt;/Exam 1&gt; &lt;Exam 2&gt;87&lt;/Exam 2&gt; &lt;/root&gt; </code></pre> <p>Following <a href="http://www.peachpit.com/articles/article.aspx?p=21846" rel="nofollow">this article</a> I am using this stylesheet:</p> <pre><code> &lt;stylesheet&gt; &lt;xsl:stylesheet version='1.0' xmlns:xsl='http://www.w3.org/1999/XSL/Transform'&gt; &lt;xsl:template match='@*|node()'&gt; &lt;xsl:copy&gt; &lt;xsl:apply-templates select='@*|node()'/&gt; &lt;/xsl:copy&gt; &lt;/xsl:template&gt; &lt;xsl:template match='score'&gt; &lt;xsl:element name='{@name}'&gt; &lt;xsl:apply-templates/&gt; &lt;/xsl:element&gt; &lt;/xsl:template&gt; &lt;/xsl:stylesheet&gt; &lt;/stylesheet&gt; </code></pre> <p>However, when I transform it and load it into a document, I receive this error:</p> <blockquote> <p>System.Xml.Xslt.XsltException: 'Exam 1' is an invalid QName</p> </blockquote> <p>It seems that many of the google results show people with this error have passed an empty string somehow, the error is "" is an invalid QName, but that's not the case here.</p> <p>What is the problem? Is there a better, alternative solution?</p>
<p>You cannot have a space in an element name.</p>
Does .NET 3.5 installer include 3.0 SP2? <p>We're trying to track down some .Net assembly dependency problems.</p> <p>On Windows XP, does the .Net 3.5 installer include 3.0 SP2 automatically?</p>
<p>.NET 3.5 contains .NET 3.0 SP1</p> <p>.NET 3.5 SP1 contains .NET 3.0 SP2</p>
Rails & Windows <p>Is Rails development really this hard on Windows? I'm a PHP developer looking forwards to using Rails (mainly because every single PHP framework I've tried has some quirk that I just hate).</p> <p>I downloaded Aptana Studio (w/ RadRails) as it seemed to be a good solution (and because I love anything Eclipse-based). But that's where the problems begin - upon creating a project (called "test", using sqlite3), the first problem I hit is some "sqlite3 is missing" error. So I Google around a bit and install sqlite3-ruby with gem. I still got some error - but somehow managed to fix it. So it seems to work, but is this really it? Some environment that barely seems to work and has a lot of problems (<a href="http://stackoverflow.com/questions/164896/limitations-in-running-rubyrails-on-windows">see this</a>)?</p> <p>In some other question, I saw the suggestion to run the project in a VM instead and edit it from Windows. Sounds like a good idea - but the two major Rails IDE's (RadRails, NetBeans, unless there's more) seem to want to run their own server in Windows. What would be the best setup for them/how would I set up a project in them if I'd run a Linux Rails stack in a VM instead?</p> <p>Note that I'd rather not work without an IDE - upon trying one for PHP, I instantly became completely dependent (sigh) on them - and since I've never really used Ruby (or Rails) before, having code completion would be a major help.</p> <p>So what are your suggestions? Run in Windows or Windows &amp; Linux stack in VM? Any other tips?</p> <p>Thanks!</p>
<p>My advice to get started is to purchase <a href="http://rads.stackoverflow.com/amzn/click/0977616630" rel="nofollow">Agile Web Development with Rails</a> and use it like a tutorial, just following along with the book. If you have a Windows machine just use that. Make sure you have a text editor that you like. This should get you going and from there you can make more informed decisions about IDEs and the like.</p>
Modifying WordPress's "post-new.php" File for Custom Blog Entries <p>Has anyone ever modified the "post-new.php" file in their WordPress installation? </p> <p>I want to modify the look of this page to include pieces that I standardly include in my blog posts, and I just don't know if it is do-able/easy/worth my time.</p> <p>Should I just find another CMS that allows more modifcation like Drupal?</p>
<p>No reason to modify the core files - you can add stuff via plugins. See, for example, <a href="http://wordpress.org/extend/plugins/more-fields/" rel="nofollow">the more fields plugin</a> - it adds to the new/edit post form without breaking your ability to upgrade the core installation.</p> <p>Drupal's great, but if you're focusing on blogging you may get better results tweaking WP via plugins. I use WordPress for blog sites, and Drupal for most others.</p>
Mark parameters as NOT nullable in C#/.NET? <p>Is there a simple attribute or data contract that I can assign to a function parameter that prevents <code>null</code> from being passed in C#/.NET? Ideally this would also check at compile time to make sure the literal <code>null</code> isn't being used anywhere for it and at run-time throw <code>ArgumentNullException</code>.</p> <p>Currently I write something like ...</p> <pre><code>if (null == arg) throw new ArgumentNullException("arg"); </code></pre> <p>... for every argument that I expect to not be <code>null</code>.</p> <p>On the same note, is there an opposite to <code>Nullable&lt;&gt;</code> whereby the following would fail:</p> <pre><code>NonNullable&lt;string&gt; s = null; // throw some kind of exception </code></pre>
<p>There's nothing available at compile-time, unfortunately.</p> <p>I have a bit of a <a href="https://web.archive.org/web/20081231232311/http://msmvps.com/blogs/jon_skeet/archive/2008/10/06/non-nullable-reference-types.aspx">hacky solution</a> which I posted on my blog recently, which uses a new struct and conversions.</p> <p>In .NET 4.0 with the <a href="http://research.microsoft.com/contracts/">Code Contracts</a> stuff, life will be a lot nicer. It would still be quite nice to have actual language syntax and support around non-nullability, but the code contracts will help a lot.</p> <p>I also have an extension method in <a href="http://pobox.com/~skeet/csharp/miscutil">MiscUtil</a> called ThrowIfNull which makes it a bit simpler.</p> <p>One final point - any reason for using "<code>if (null == arg)</code>" instead of "<code>if (arg == null)</code>"? I find the latter easier to read, and the problem the former solves in C doesn't apply to C#.</p>
What is needed to execute visual studio 2005 web tests? <p>Our test department has a series of web tests created using Visual Studio 2005 Team Tester Edition.</p> <p>I would like to be able to execute these tests against my local machine. I attempted to use the mstest command line tool to accomplish this as described in <a href="http://msdn.microsoft.com/en-us/library/ms182487(VS.80).aspx" rel="nofollow">this MSDN article</a>. But I get the following error:</p> <blockquote> <p>C:\WebTests\Participant>mstest /testcontainer:AE_ActivityDue_Touch.webtest Microsoft (R) Test Execution Command Line Tool Version 9.0.30729.1 Copyright (c) Microsoft Corporation. All rights reserved.</p> <p>Loading AE_ActivityDue_Touch.webtest... AE_ActivityDue_Touch.webtest File extension specified '.webtest' is not a valid test extension.</p> </blockquote> <p>Any hints on how I can get this to work? Eventually we want to work them into our CI process.</p>
<p>You need VSTS Test Edition. No bueno.</p> <p><a href="http://msdn.microsoft.com/en-us/vsts2008/test/default.aspx" rel="nofollow">http://msdn.microsoft.com/en-us/vsts2008/test/default.aspx</a></p>
another sound as with subtitles <p>is it possible to get other sounds to a divx as it is with getting subtitles? what is that format of that?</p>
<p>Yes, you can have multiple audio streams in your video file. <a href="http://www.doom9.org/index.html?/dual-audio.htm" rel="nofollow">Here</a>'s some more information (I'm guessing you're using AVI as your container format).</p>
How to assign Date parameters to Hibernate query for current timezone? <p>When you assign a date to a named SQL parameter Hibernate automatically converts it to GMT time. How do you make it use the current server timezone for all dates?</p> <p>Lets say you have a query:</p> <pre><code>Query q = session.createQuery("from Table where date_field &lt; :now"); q.setDate("now", new java.util.Date()); </code></pre> <p>"now" will be set to GMT time, while "new Date()" gets your current server time.</p> <p>Thanks.</p>
<p>As it turned out Hibernate doesn't convert dates to GMT automatically, it just cuts off time if you use <code>query.setDate()</code>, so if you pass "2009-01-16 12:13:14" it becomes "2009-01-16 00:00:00". </p> <p>To take time into consideration you need to use <code>query.setTimestamp("date", dateObj)</code> instead.</p>
How do I split a huge text file in python <p>I have a huge text file (~1GB) and sadly the text editor I use won't read such a large file. However, if I can just split it into two or three parts I'll be fine, so, as an exercise I wanted to write a program in python to do it. </p> <p>What I think I want the program to do is to find the size of a file, divide that number into parts, and for each part, read up to that point in chunks, writing to a <em>filename</em>.nnn output file, then read up-to the next line-break and write that, then close the output file, etc. Obviously the last output file just copies to the end of the input file.</p> <p>Can you help me with the key filesystem related parts: filesize, reading and writing in chunks and reading to a line-break?</p> <p>I'll be writing this code test-first, so there's no need to give me a complete answer, unless its a one-liner ;-)</p>
<p>linux has a split command</p> <p>split -l 100000 file.txt</p> <p>would split into files of equal 100,000 line size</p>
MVC and jQuery validation, where to 'weave' the javascript and how to embed into master page? <p>If my header/footer are in the master page, and my .js files are referenced in the master page, how can I add jQuery validation on my login page?</p> <p>If there is an error detected, how will I modify the .js file to display the appropriate error message?</p>
<p>Have you looked at the jquery <a href="http://bassistance.de/jquery-plugins/jquery-plugin-validation/" rel="nofollow">validation plugin</a>? The plugin handles a lot of different validation tasks automatically -- i.e., you might be able to get away with doing:</p> <pre><code>$(document).ready( function { $(form).validate(); } ); </code></pre> <p>an annotating your text fields with the appropriate class attributes. You should be able to just reference the validation library on your view page and add the document ready function there as well inside a script tag.</p> <pre><code>&lt;asp:Content runat="server" ID="viewcContent" ContentID="masterContent"&gt; &lt;script type="text/javascript" src="..path_to/jquery.validate.js"&gt; &lt;/script&gt; &lt;script type="text/javascript"&gt; $(document).ready( function { $(form).validate(); } ); &lt;/script&gt; &lt;% using (Html.BeginForm()) { %&gt; ... form implementation... &lt;input type="text" id="username" name="username" class="required" /&gt; &lt;% } %&gt; &lt;/asp:Content&gt; </code></pre>
New to functional programming <p>Hey, I'm really new to Haskell and have been using more classic programming languages my whole life. I have no idea what is going on here. I'm trying to make a very simple Viterbi algorithm implementation, but for only two states (honest and dishonest casino)</p> <p>I have a problem where I want to address my array, but I don't think I'm getting types right. That or I'm making a new array each time I try to address it - equally stupid. Look at myArray, te infix, and dynamicProgram especially, PLEASE. Pretty pretty please </p> <pre> Code <code> import Array import Char trans :: Int -> Int -> Double -> Double -> Double trans from x trans11 trans21 = if (from == 1) && (x == 1) then trans11 else if (from == 1) && (x == 2) then (1-trans11) else if (from == 2) && (x == 1) then trans21 else (1-trans21) em :: Char -> [Double] -> Double em c list = list!! a where a = digitToInt c intToChar :: Int -> Char intToChar n | n == 1 = '1' | n == 2 = '2' casino :: Char -> Int -> Int -> [Double] -> [Double] -> Double -> Double -> Double casino seqchar 1 y em1 em2 t1 t2= 0.5 * (em seqchar em1) casino seqchar 2 y em1 em2 t1 t2= 0.5 * (em seqchar em2) casino seqchar x y em1 em2 t1 t2= maximum[ (1 @@ y-1)*(em seqchar em1)*(trans 1 x t1 t2),(2 @@ y-1)*(em seqchar em2)*(trans 2 x t1 t2) ] dynamicProgram :: [Char] -> (Char -> Int -> Int -> [Double] -> [Double] -> Double -> Double -> Double) -> [Double] -> [Double] -> Double -> Double -> (Array a b) dynamicProgram string score list1 list2 trans11 trans21 = myArray 1 len [score (string!!y) x y list1 list2 trans11 trans21 | x Int -> [Double] -> Array a b myArray startIndex endIndex values = listArray (startIndex,startIndex) (endIndex,endIndex) values traceback :: [Char] -> Int -> Int -> [Double] -> [Double] -> Double -> Double -> [Char] traceback s 1 0 em1 em2 t1 t2 = [] traceback s 2 0 em1 em2 t1 t2 = [] traceback s x y em1 em2 t1 t2 | x@@y == (1 @@ y-1)*(em (s!!y) em1)*(trans 1 x t1 t2) = '1' : traceback s 1 (y-1) em1 em2 t1 t2 | x@@y == (2 @@ y-1)*(em (s!!y) em1)*(trans 2 x t1 t2) = '2' : traceback s 2 (y-1) em1 em2 t1 t2 answer :: [Char] -> [Double] -> [Double] -> Double -> Double -> [Char] answer string list1 list2 t1 t2 = reverse $ maxC : traceback string max end list1 list2 t1 t2 $ dynamicProgram casino string list1 list2 t1 t2 where end = (length string) + 1 max | maximum (1@@end) (2@@end) == 1@@end = 1 | maximum (1@@end) (2@@end) == 2@@end = 2 maxC = intToChar max infix 5 @@ (@@) i j = myArray ! (i, j) main = do putStrLn "What is the sequence to test?" seq state 1 transmission probability?" trp1 state 2 transmission probability is " ++ (1-trp1) putStrLn "What is the state 2 -> state 1 transmission probability?" trp2 state 2 transmission probability is " ++ (1-trp2) putStrLn "I assume that the prob of starting in either state is 1/2. Go!" answer seq st1 st2 trp1 trp2 </code></pre>
<p>I copied the code from the edit window (something in stackoverflow's parser is eating part of the code) and tried it on ghci, which found several errors. The first error was:</p> <pre><code>foo.hs:34:71: Couldn't match expected type `[e]' against inferred type `(a, b)' In the second argument of `listArray', namely `(endIndex, endIndex)' In the expression: listArray (startIndex, startIndex) (endIndex, endIndex) values In the definition of `myArray': myArray startIndex endIndex values = listArray (startIndex, startIndex) (endIndex, endIndex) values </code></pre> <p>The type of listArray is:</p> <pre><code>listArray :: (Ix i) =&gt; (i, i) -&gt; [e] -&gt; Array i e -- Defined in GHC.Arr </code></pre> <p>It takes a tuple with the lower and upper bounds and the list. So, the correct expression would probably be:</p> <pre><code>listArray (startIndex, endIndex) values </code></pre> <p>And the type of myArray is not <code>Array a b</code>, it is <code>Array Int Double</code>.</p> <p>The second error was:</p> <pre><code>foo.hs:43:44: Couldn't match expected type `a -&gt; b' against inferred type `[Char]' In the first argument of `($)', namely `maxC : (traceback string max end list1 list2 t1 t2)' In the second argument of `($)', namely `(maxC : (traceback string max end list1 list2 t1 t2)) $ (dynamicProgram casino string list1 list2 t1 t2)' In the expression: reverse $ ((maxC : (traceback string max end list1 list2 t1 t2)) $ (dynamicProgram casino string list1 list2 t1 t2)) </code></pre> <p><code>$</code> is right associative, so the rightmost <code>$</code> is looked at first. The first parameter to it must be a function, which it will call with its rightmost parameter as the argument. Here, however, it is a list.</p> <p>The third error was:</p> <pre><code>foo.hs:51:11: Couldn't match expected type `Array i e' against inferred type `Int -&gt; Int -&gt; [Double] -&gt; Array a b' In the first argument of `(!)', namely `myArray' In the expression: myArray ! (i, j) In the definition of `@@': @@ i j = myArray ! (i, j) </code></pre> <p><code>myArray</code> is not an array; it is a function which takes three parameters and constructs an array based on them.</p> <p>Here probably your being used to more traditional imperative languages is tripping you. In a traditional imperative language, it would be natural to have a global <code>myArray</code> variable which you then can access from the middle of your program. In Haskell however, absent more advanced trickery which you should not try while you are a beginner, a "global" variable is more like a constant value (which is lazily computed on first use, but which as far as you care could have been computed by the compiler while generating your executable). You cannot initialize it from values you read as input.</p> <p>Your best way around that is to pass the array through the program, which unfortunately will need several changes and negates the usefulness of your <code>@@</code> operator. You can hide the passing of the array in several more advanced ways, but while learning it is best to be more explicit.</p> <p>The last error was:</p> <pre><code>foo.hs:63:4: Couldn't match expected type `[a]' against inferred type `IO ()' In the first argument of `(++)', namely `putStrLn "I assume that the state 1 -&gt; state 2 transmission probability is "' In the expression: (putStrLn "I assume that the state 1 -&gt; state 2 transmission probability is ") ++ (1 - trp1) In a 'do' expression: (putStrLn "I assume that the state 1 -&gt; state 2 transmission probability is ") ++ (1 - trp1) </code></pre> <p>This has two errors: the one the compiler complained about is a precedence problem, as the compiler-added parenthesis readly show, and which can easily be fixed by correct application of either parenthesis or the <code>$</code> operator. The other error, which you will find after you fix this one, is that you cannot concatenate a string and a number; you have to convert the number to a string.</p> <p>This was all without looking at the algorithm or even most of the code, just looking at the compiler errors. If you want a two-dimensional array, for instance, the correct expression for the first error would be:</p> <pre><code>listArray ((startIndex, startIndex), (endIndex, endIndex)) values </code></pre> <p>Now both bounds are tuples, and its type is <code>Array (Int, Int) Double</code>.</p>
Groovy in Ant build.xml (with Java classes) <p>I have to include Groovy classes into existing Java apps, and include Groovy into Ant's <code>build.xml</code> file.</p> <p>What is the best way to configure Ant's <code>build.xml</code> for it? </p> <p>Update: Are there more specifics in combining Java and Groovy compilations? Sequence of tasks?</p>
<p>@VonC is correct about including Groovy scripting in your Ant build.</p> <p>To expand a bit:</p> <p>To compile <code>.groovy</code> and <code>.java</code> sources <em>together</em> for use in the same application, use the <a href="http://groovy.codehaus.org/The+groovyc+Ant+Task" rel="nofollow"><code>&lt;groovyc&gt;</code></a> Ant task.</p> <p>See <a href="http://groovy.codehaus.org/Ant+Integration+with+Groovy" rel="nofollow">Ant Integration with Groovy</a> for the reference.</p>
Do you just code, or just design, or some of both? <p>Since I hold the job of both coder and designer I wonder if a lot of others are in the same boat. What percentage of your time is each?</p> <p>For me it's as close to 50/50 as you can get and I think I do a pretty good job at each: <a href="http://rpmware.com" rel="nofollow">RPMWare</a>. That said, I know I'm neither the best coder or designer out there, but I can hold my own in each respect.</p> <p>Is the best team one with full-time designer and full-time coders, or a hodge-podge of guys (and gals) who wear both hats.</p>
<p>Chances are, a good generalist won't quite be able to do the same quality job a specialist in that given area could do. At the same time, having too many specialists on staff can be a problem, because a lack of common understanding on a given topic may not allow them to collaborate as fluidly as they'd like. A team should be a combination of generalists and specialists.</p> <p>That being said, I think people are too eager to draw the line between 'coding' and 'design.' They might use different tools, and take wildly different approaches to problem, but at the end of the day, they're both making decisions about how a program should work, and if a team can't realize the importance of how these two 'disciplines' interact, the end product won't be as strong.</p>
File Access from Excel COM object fails when run from NT Service on Vista <p>We use COM objects to access excel spreadsheets in an NT service (via the Windows Scripting Host). Prior to Vista, this worked beautifully, but starting with Vista, we receive this error:</p> <p>Microsoft Office Excel cannot access the file 'c:\myfiles\test.xls'. There are several possible reasons: • The file name or path does not exist. • The file is being used by another program. • The workbook you are trying to save has the same name as a currently open workbook.</p> <p>I have tried changing the NT service logon settings to use my own account, an admin account and local system. I've looked through the Local Security Policy and have not found anything. I've spent days searching through the Microsoft KB to no avail.</p> <p>If the script is executed from a console application, it works fine. The file opens and is processed with no problem. The error only occurs when executed from within the context of a service.</p> <p>If the service is running on Windows XP or Server 2003 SP1, it also works fine. Only on Vista does it fail (and we've now gotten reports of it failing in Server 2003 SP2)!</p> <p>The code, for what it is worth is exceptionally simple: dim xl_app Set xl_app = CreateObject("Excel.Application") xl_app.Workbooks.Open mypath,0,1</p> <p>I suspect that this person might be experiencing the same issue: <a href="http://bytes.com/forum/thread819740.html" rel="nofollow">http://bytes.com/forum/thread819740.html</a></p>
<p>just some further questions:</p> <ul> <li>Which version of Excel are you using? </li> <li>Have you tried running the service with elevated privileges?</li> </ul>
ASP.NET shared hosting provider that allows multiple websites (not just applications)? <p>Most ASP.NET hosts give you a single website in IIS. Then, they let you set subfolders as applications. Are there any shared ASP.NET 3.5 hosts that give you multiple websites with a single account?</p> <p>I have several low traffic websites that don't use much bandwidth.</p>
<p>WebHost4Life offers this, though there's a small charge per domain. ($15/year or so). I'm sure most hosts can do this, but fees vary.</p>
How wrong is it to have a unique and normal index on the same column? <p>I have the following table structure</p> <pre><code>CREATE TABLE `table` ( `id` int(11) NOT NULL auto_increment, `date_expired` datetime NOT NULL, `user_id` int(11) NOT NULL, `foreign_id` int(11) NOT NULL, PRIMARY KEY (`id`), UNIQUE KEY `date_expired` (`date_expired`,`user_id`,`foreign_id`), KEY `user_id` (`user_id`) ) ENGINE=MyISAM DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci; </code></pre> <p>As you'll notice, I have duplicate indexes on user_id: <code>date_expired</code> &amp; <code>user_id</code>. I of course want the unique index because I want to ensure the data is unique.</p> <p>The reason for the duplicate indexes is because without the <code>user_id</code> index, my main search query takes 4 seconds. With the extra index it takes 1 second. The query is joining the table on <code>user_id</code> and checking <code>date_expired</code>.</p> <p>The table only has 275 records.</p> <ul> <li>How bad is it to have a unique and normal index on the same field?</li> <li>How bad is it to have larger indexes than data when the table is purely ids?</li> </ul>
<p>I believe if you created your unique index as (<code>user_id</code>, <code>date_expired</code>, <code>foreign_id</code>), you'll get the same benefit of having a normal index on <code>user_id</code> with just the unique index. MySQL can use the first columns of any index to pare down the number of rows in the join in the same manner as an index on <code>user_id</code>. </p> <p>See <a href="http://dev.mysql.com/doc/refman/5.0/en/mysql-indexes.html#id3515520">MySQL's index documentation</a> for more information.</p> <p>Are you referring to the <code>id</code> auto_increment column elsewhere in your schema to save space? Since your unique index covers all of the other columns in your table, it is in essence a primary key itself and could be dropped if you're not.</p> <p>You can check what keys your query is using by prefixing it with EXPLAIN.</p>
Opening a VS 2003 C++ project in VS 2008 <p>Found some old code, circa VS 2003. Now I have just VS 2008 (SP1) installed. When I try opening the *.sln file, it tries converting the projects. The report notifies me it was done successfully, but the solution is empty, marked with "project file was unloaded". VS 2008 doesn't even include opening a *.vcproj file.</p> <p>Does anyone have any idea how I can convert my solution?</p> <p>PS: I found several conversion tools that convert from VS 2005 to 2008 and vice versa - no one looks back to 2003 :(</p> <p>As always, thanks for your assistance and time!</p>
<p>I suggest manually converting the project by creating a new proj. If you are having trouble now then there will be no way that you can be certain later by trying some other import method.</p> <p>On a side note- I am on vs2005 and I often get 2008 projects handed to me. I go into the sln and proj files and rename the version numbers and it works perfectly. Hope that works for you!</p>
How to discard everything after a certain string character in PHP? <p>I want to take a string in PHP and discard everything after a certain character. However, it needs to search for not just one character, but an array of them. As soon as it gets to one of the characters in the array, it should return the string before that point.</p> <p>For instance, if I have an array:</p> <pre><code>$chars = array("a", "b", "c"); </code></pre> <p>How would I go through the following string...</p> <pre><code>log dog hat bat </code></pre> <p>...and end up with:</p> <pre><code>log dog h </code></pre> <p>Any solutions would be very much appreciated. :)</p>
<p>The <a href="http://php.net/manual/en/function.strcspn.php">strcspn</a> function is what you are looking for.</p> <pre><code>&lt;?php $mask = "abc"; $string = "log dog hat bat"; $result = substr($string,0,strcspn($string,$mask)); var_dump($result); ?&gt; </code></pre>
Wrapping Visual C++ in C# <p>I need to do some process injection using C++ but I would prefer to use C# for everything other than the low level stuff. I have heard about "function wrapping" and "marshaling" and have done quite a bit of google searching and have found bits of information here and there but I am still really lacking. </p> <p>Things I have read in order of usefulness;<br /> <a href="http://msdn.microsoft.com/en-us/library/ms235281" rel="nofollow">http://msdn.microsoft.com/en-us/library/ms235281</a>(VS.80).aspx<br /> <a href="http://www.drdobbs.com/cpp/184401742" rel="nofollow">http://www.drdobbs.com/cpp/184401742</a><br /> <a href="http://geeklit.blogspot.com/2006/08/calling-c-lib-from-c.html" rel="nofollow">http://geeklit.blogspot.com/2006/08/calling-c-lib-from-c.html</a> </p> <p>How can I wrap all the lower level stuff (native C++) in C# so I can easily command those functions in a language I am more comfortable with, C#? </p> <p>Any information on the topic is much appreciated.</p>
<p>I think P/Invoke is really the most straightforward approach:</p> <ul> <li>Create a DLL in <em>unmanaged</em> C++, containing all the functionality you need to do the injection.</li> <li>In your C# code, declare some <code>static extern</code> methods, and use the <code>DllImport</code> attribute to point them to your C++ dll. For more details, see the link provided by <a href="http://stackoverflow.com/users/15409/arul">arul</a> in <a href="http://stackoverflow.com/questions/292450/wrapping-visual-c-in-c#292455">his answer</a>.</li> </ul> <p>Note that P/Invoke isn't limited to "windows API functions" &mdash; you can call functions exposed by any native DLL.</p> <p>A potential downside of P/Invoke is that you will have to provide the signatures for your C++ functions, possibly specifying some less-than-obvious marshalling. In that case, you could consider constructing a COM server instead of a "plain" DLL, and using <a href="http://msdn.microsoft.com/en-us/library/kew41ycz(VS.80).aspx">COM interop</a> to call your code from C#.</p>