input
stringlengths
51
42.3k
output
stringlengths
18
55k
In C# what is the recommended way of passing data between 2 threads? <p>I have my main GUI thread, and a second thread running inside it's own ApplicationContext (to keep it alive, even when there is no work to be done). I want to call a method on my 2nd thread from my GUI thread, but if I just call thread.Method(); it seems to be running on my main GUI thread and causes my GUI to become unresponsive. What is the best way to call methods on different threads?</p> <p><strong>Update:</strong> What I'm really looking to do here is communicate between 2 threads, not communicate with a GUI. The GUI just happens to be one of the threads that will need to communicate with my 2nd thread.</p> <p><strong>Update #2:</strong> Ok, I must really be missing something. I created an event and a delegate and had my worker thread subscribe to the event. But when I call Invoke(MyEvent); from my GUI thread the work that the worker thread does ends up being on the GUI thread and hangs the GUI thread until it's done processing. Is what I'm trying to do even possible, without polling on a static object?</p>
<p>Wow, I can't believe how may people didn't bother reading the question.</p> <p>Anyways, this is what I do.</p> <ol> <li>Create you "message" classes. This stores all the information you want to share.</li> <li>Create a Queue&lt;T&gt; for each thread. Use a SyncLock (C# lock) to read/write to it.</li> <li>When you want to talk to a thread, send it a message object with a <strong>copy</strong> of all the information it needs by adding the message to the queue. </li> <li>The worker thread can then read from the queue, reading and processing each message in order. When there are no messages, simply sleep.</li> </ol> <p>Make sure that you don't share objects between the two threads. Once your GUI thread sticks a message in the Queue, the GUI thread no longer owns the message. It cannot hold a reference to the message, or you will get yourself into trouble.</p> <p>This won't give you the best possible performance, but it will be good enough for most applications. And more importantly, it will make it much harder to make a mistake.</p> <p>UPDATE: Don't use a SyncLock and Queue. Instead use a ConcurrentQueue, which will handle any locking automatically for you. You'll get better performance and are less likely to make a mistake.</p>
LINQ with FoxPro? <p>Is there a reasonable way to access FoxPro databases using LINQ?</p>
<p>I just finished working on implementation. <a href="http://linqtovfp.codeplex.com/">http://linqtovfp.codeplex.com/</a></p>
nHibernate slow performance on a hosted website <p>I have a webapp being hosted with a public hosting company, the site is not live yet, and I am still doing some testing with it. I am using nHibernate with Windsor Castle Container for dependency injection and the site seems to be responding very slow from time to time. I've contacted support but they said that it's my app not their servers. Has anyone had similar performance issues with ORM based sites when being hosted at the public hosting companies?</p> <p>Also, what hosting company would you recommend for hosting websites? I tried godaddy but couldn't use them 'cause they don't allow running website in full trust which is apparently required for nHibernate.</p> <hr> <p>I configured nHibernate using xml configuration files, opening sessions in the following way:</p> <pre><code>using (ISession session = _sessionManager.OpenSession()) { ICriteria crit = session.CreateCriteria(typeof(Content)); return crit.List(); } </code></pre> <p>Also in the <code>Application_Start</code> I have the following code:</p> <pre><code>private static WindsorContainer container; if (container == null) { container = new WindsorContainer(new XmlInterpreter(filePath)); Application[Constant.CastleWindsorAppKey] = container; } </code></pre>
<p>You don't know how slow your application is when you don't measure it. I'm using a <a href="http://haacked.com/archive/2008/07/02/httpmodule-for-timing-requests.aspx" rel="nofollow">timing http module</a> during development to notice big performance issues fast. When one of your pages loads slow, you should use a profiler to find the exact bottle neck. I'm using NHibernate for my current project and I don't have any performance issues with it. My most complex queries involve a complex object graph of 10 different classes and with their NHibernate mappings takes 0.082 seconds to execute. The main bottle-neck in that application is rendering the html aspx template to the response (that takes 0.5 seconds). Performance issues are often in dataaccess, but you can not be sure unless you measure it. </p>
Question: VB.net coding standard regarding declaring variable <p>I've seen some variable declare in VB.net in several way like:</p> <pre><code>print("dim _Foo as string"); </code></pre> <p>and print("dim m_Foo as string"); and print("dim foo as string");</p> <p>I will like to know what's the standard for VB.net coding.</p>
<p>It all depends on the scope. In the case of:</p> <pre><code>Private Dim m_Foo As String </code></pre> <p>That implies that m_Foo is a member of a class. This also implies the same thing:</p> <pre><code>Private Dim _Foo As String </code></pre> <p>It's a matter of preference.</p> <p>On the other hand, something like this:</p> <pre><code>Dim Foo As String </code></pre> <p>might refer to a variable local to a given method. Some might even prefix it with a "l_":</p> <pre><code>Dim l_Foo As String </code></pre> <p>Declaring like these examples helps in determining scope when scanning code. Putting it all together, here's a sample class showing a well-known naming convention (but not the only one):</p> <pre><code>Public Class Bar Private m_firstName As String Public Sub New(ByVal firstName As String) m_firstName = firstName End Sub Public Function SayGreeting() As String Dim l_Greeting As String l_Greeting = String.Format("{0}, {1}!", "Hello", m_firstName) Return l_Greeting End Function End Class </code></pre>
How do I restrict the number of records to be processed in an SSIS package? <p>I have a table with 7M records I want to trim down to 10k for dev. I tried a delete, but the whole world was nearly overpowered by the transaction log size, so I truncated the table.</p> <p>Now I wish to insert 10k records from the original table, into my dev table, but it has a identity column, and many, many other columns, so I'd thought I'd try SSIS (through the wizard), which handles the identity nicely, but gives me no place to edit a query. So I quickly made a view with a top clause, and changed the RowSet property of the source to the view. Now everything fails because nothing sees the view, although I copied and pasted the view name from my create view statement, which fails a second time because, lo, the view actually does exist. </p> <p>Does SSIS define which DB objects are used when a package is created, which would exclude the new view, and if so, how can I refresh that?</p>
<p>There's really no need to use SSIS to do this. You should be able to insert the records using SQL. First, you will need to set IDENTITY_INSERT to on. Then, you should be able to execute something like this:</p> <p>SET IDENTITY_INSERT db.schema.dev_table ON</p> <p>INSERT INTO dev_table SELECT TOP (10000) * FROM prod_table</p>
Showcasing Flex - Tour de Flex <p>I ran across <a href="http://flex.org/tour" rel="nofollow">Tour de Flex</a> a couple days ago. It's a demo that showcases all the Flex controls, with cross-references to source and references. It's a great way to get an idea of the resources available, and how to use them.</p> <p>Not a question, but a useful resource since I've seen a number of Flex/Actionscript questions here.</p> <p>(Note that I've preflagged all the no-credit tags I can think of already. Pile on more if you can think of any.)</p>
<p>Q: When is a question not a question?</p> <p><hr /></p> <p>A: When it is rhetorical.</p> <p>It think it would be best to make this question answerable rather than try to avoid taking credit. For instance, I would have asked something like:</p> <blockquote> <p>What are some good resources for understanding Flex controls?</p> </blockquote> <p>That would have set up the body of your "question" to be an acceptable answer.</p> <p>In addition, you might have found other people would have contributed other resources that they've found. As it stands, this question does not invite further answers and has the appearance of spam. Just so you know.</p>
iPhone designmode support <p>Anyone knows if Safari on the iPhone and iPod touch supports iFrame in design mode and if so, how I can enable it? I have tried following ways, but none work (but it works on my PC):</p> <pre><code>theIframe.contentWindow.document.body.contentEditable = true; theIframe.contentWindow.document.designMode = 'on'; theIframe.contentDocument.designMode = "on"; </code></pre> <p>Thanks!</p>
<p>According to [1], contenteditable, at least, should work:</p> <blockquote> <p>contenteditable</p> <p>If true, the element can be edited on the fly; if false, it cannot.></p> <p>Availability</p> <p>Available in Safari 1.2 and later. Available in iPhone OS 1.0 and later.</p> </blockquote> <p>.. but it didn't for me :-(</p> <p>[1] <a href="http://developer.apple.com/safari/library/documentation/AppleApplications/Reference/SafariHTMLRef/Articles/Attributes.html" rel="nofollow">http://developer.apple.com/safari/library/documentation/AppleApplications/Reference/SafariHTMLRef/Articles/Attributes.html</a></p>
Parsing XML with REGEX in Java <p>Given the below XML snippet I need to get a list of name/value pairs for each child under DataElements. XPath or an XML parser cannot be used for reasons beyond my control so I am using regex.</p> <pre><code>&lt;?xml version="1.0"?&gt; &lt;StandardDataObject xmlns="myns"&gt; &lt;DataElements&gt; &lt;EmpStatus&gt;2.0&lt;/EmpStatus&gt; &lt;Expenditure&gt;95465.00&lt;/Expenditure&gt; &lt;StaffType&gt;11.A&lt;/StaffType&gt; &lt;Industry&gt;13&lt;/Industry&gt; &lt;/DataElements&gt; &lt;InteractionElements&gt; &lt;TargetCenter&gt;92f4-MPA&lt;/TargetCenter&gt; &lt;Trace&gt;7.19879&lt;/Trace&gt; &lt;/InteractionElements&gt; &lt;/StandardDataObject&gt; </code></pre> <p>The output I need is: [{EmpStatus:2.0}, {Expenditure:95465.00}, {StaffType:11.A}, {Industry:13}] </p> <p>The tag names under DataElements are dynamic and so cannot be expressed literally in the regex. The tag names TargetCenter and Trace are static and could be in the regex but if there is a way to avoid hardcoding that would be preferable. </p> <pre><code>"&lt;([A-Za-z0-9]+?)&gt;([A-Za-z0-9.]*?)&lt;/" </code></pre> <p>This is the regex I have constructed and it has the problem that it erroneously includes {Trace:719879} in the results. Relying on new-lines within the XML or any other apparent formatting is not an option.</p> <p>Below is an approximation of the Java code I am using:</p> <pre><code>private static final Pattern PATTERN_1 = Pattern.compile(..REGEX..); private List&lt;DataElement&gt; listDataElements(CharSequence cs) { List&lt;DataElement&gt; list = new ArrayList&lt;DataElement&gt;(); Matcher matcher = PATTERN_1.matcher(cs); while (matcher.find()) { list.add(new DataElement(matcher.group(1), matcher.group(2))); } return list; } </code></pre> <p>How can I change my regex to only include data elements and ignore the rest?</p>
<p>XML is not a regular language. You <b>cannot</b> parse it using a regular expression. An expression you think will work will break when you get nested tags, then when you fix that it will break on XML comments, then CDATA sections, then processor directives, then namespaces, ... It cannot work, use an XML parser.</p>
Matching dashes in a URL regex <p>I have used the following regex to get the urls from text (e.g. <code>"this is text http://url.com/blabla possibly some more text"</code>).</p> <pre><code>'@(https?://([-\w\.]+)+(:\d+)?(/([\w/_\.]*(\?\S+)?)?)?)@' </code></pre> <p>This works for all URLs but I just found out it doesn't work for URLs shortened like: <code>"blabla bla http://ff.im/-bEnA blabla"</code> becomes <code>http://ff.im/</code> after the match.</p> <p>I suspect it has to do with the dash <code>-</code> after the slash <code>/</code>.</p>
<p>Short answer: <code>[\w/_\.]</code> doesn't match <code>-</code> so make it <code>[-\w/_\.]</code></p> <p>Long answer:</p> <pre><code>@ - delimiter ( - start of group https?:// - http:// or https:// ([-\w.]+)+ - capture 1 or more hyphens, word characters or dots, 1 or more times.. this seems odd - don't know what the second + is for (:\d+)? - optionally capture a : and some numbers (the port) ( - start of group / - leading slash ( - start of group [\w/_\.] - any word character, underscore or dot - you need to add hyphen to this list or just make it [^?\S] - any char except ? or whitespace (the path + filename) (\?\S+)? - optionally capture a ? followed by anything except whitespace (the querystring) )? - close group, make it optional )? - close group, make it optional ) - close group @ </code></pre>
Porting VB.NET Winforms Application to C# <p>Are there any 'good' resources for porting a VB.NET winforms application to C#? I'm sure there are is software that just translates the code, but I'm looking to refactor the code at the same time. Keeping it in its current form is problematic, since it uses some of the 'bad design' practices that VB.NET allows, and would further complicate future maintanence. Has anyone here gone through that process, and how did you go about doing it? Did you use a translate/refactor approach? Did you just use the end product to recreate functionality without looking at the current codebase for most of it? What would you (collectively) recommend?</p> <p><strong>Update</strong>:</p> <p>As I was telling Grauenwolf, keeping it in its current language presents the following issues:</p> <ul> <li>Not being able to readily add features. VB.NET isn't a language I'm rock solid in. I do appreciate the irony of learning the language to port it over -- but future maintenance will need to account for someone who doesn't know VB.NET.</li> <li>The rest of the application has been ported to C# (a long time ago, in fact); all features that we'd like to add depend on de-coupling the app (right now it's very tightly coupled). My choices are to either refactor it in a language I'm not too familiar with, or to refactor it in a language I understand. </li> </ul> <p>To anyone who voted the question down, I'm not really sure <em>why</em> you did; the concern isn't whether I should leave it in VB.NET; the concern is what is the future cost of not porting it over now. If I'm going to spare great expense in fixing it, why not go the extra step and make it maintainable for a future programmer?</p> <p><strong>Author's Note</strong>: I hadn't looked at this question in ages, there was a recent response, so I moved my 'answer' into the question and deleted the 'answer' (since it wasn't really an answer).</p>
<p>Based on my experience working with some large applications that mix VB and C# projects, I would recommend leaving it in VB.NET. If there are problems with the design, then fix them, but converting the whole thing to C# sounds like a messy, unnecessary distraction to me.</p> <p>The non-stylistic differences between the two languages are very minimal, so it is hard to see a functional need that would force a conversion. (There was an old bug in Visual Studio 2003 that ruled out certain chains of project references that mixed C# and VB projects in specific ways, but that is the only one I have ever run into as a practical obstacle.)</p> <p>Individual developers certainly tend to have a stylistic preference favoring one or the other, but a full conversion is a lot of work to do for something that amounts to a taste for a different flavor of syntactic sugar. </p>
ASP.NET Explicitly Post To Server From Checkbox Control OnCheckChanged Event <p>I have an asp:checkbox control, and I want to change the visibility of a Label when it is checked or unchecked. To do this I'm attempting to use the OnCheckChanged event, which apparently only fires after a post to the server. This means that my Label's visibility isn't changing immediately. How do I post to the server (and preserve the state of my form) so that when the checkbox is clicked the Label's visibility immediately toggles? </p>
<p>Well, do you need the checkbox control to post to the server when is clicked?</p> <p>if the answer is no, then you could use an html input control and use javascript to handle the onclick event. This way the action would be immediate and you save a post back to the server.</p>
Using boost::shared_ptr in a library's public interface <p>We have a C++ library that we provide to several different clients. Recently we made the switch from using raw pointers in the public interface to using boost::sharedptr instead. This has provided an enormous benefit, as you might guess, in that now the clients no longer have to worry about who needs to delete what and when. When we made the switch I believed it was the right thing to do, but it bothered me that we had to include something from a third-party library in our public interface - generally you avoid that kind of thing if you can. I rationalized it that boost was practically part of the C++ language now, and our use case requires that both the client code and the library hold pointers to the objects. However recently one of our clients has asked us if we could switch to using a neutral smart pointer class in the interface, because our library is essentially forcing them to a particular version of boost- a point which I certainly understand and appreciate. So now I am wondering what the best course of action might be. I have thought about it a little bit, and wondered about creating a simple smart pointer class that simply held a real boost smart pointer. But then the clients would probably immediately stuff one of those into their flavor of boost::sharedptr, and then we'd be three shared pointers deep - which might be a problem, or it might not. Anyway, I'd love to hear some opinions from the community about the best way to solve this problem.</p> <p>Edit: I originally said transfer of ownership, but I should have specified that code on both sides of the API boundary need to hold a pointer to the object.</p>
<p>One possible solution is to ship boost::shared_ptr with your project. As it all consists of headers, this would free your clients from having to install the boost libraries manually. You can use <a href="http://www.boost.org/doc/libs/1_37_0/tools/bcp/bcp.html">bcp</a> to get all files needed by a particular boost library, including the libraries itself. I did that when i worked for a company back then and needed <code>boost::shared_ptr</code> and it actually worked greatly.</p>
What is a debug working set (Eclipse)? <p>I'm using Eclipse IDE and notice an option in the Debug perspective in the Breakpoints view that allows me to chose/create a working set. I've found all kinds of help online that tells me how to make a working set or choose a working set, but nothing that explains what a working set is or why I'd want to use one.</p>
<p>A working set is a subset of other objects. You can create a breakpoint working set that contains only some of your breakpoints, or a project working set that contains only part of your project, and so on. You would use working sets to let you easily switch back and forth between different parts of a project or workspace.</p>
ASP.NET sites, hiring external design firms and standards <p>Hey. We're building a large ASP.NET website, and have hired an external firm to do the design (CSS + protoype pages). In fitting the design to the page, we've found a number of problems that indicate ASP.NET's workings were never considered. My question is - Is there a common standard (that should be) used by design firms creating what will become an ASP.NET site?</p> <p>We've found things like:</p> <ul> <li>Using IDs on HTML elements for CSS/JS to find, which doesn't work with server tags generating IDs.</li> <li>IDs with hyphens in them</li> <li>ValidatorSummary example built in a completely different style to ASP.NET's.</li> <li>Assumptions that all buttons will be &lt;input&gt; tags</li> <li>Margin styles on &lt;div&gt;s, interfering with our use of panels </li> </ul> <p>The first instance is a problem. The rest are inconvient misunderstandings. As usual, there are intense time constraints, so in this sea of <em>'we'll fix it / get our designer to look at it / work around it'</em>, I'm largely hoping there's some fundamental building block that would have stopped most of these problems from happening.</p> <p>The design firm is large, with a substantial body of large-site work behind them, so sadly the 'don't hire a one man shop' wisdom isn't the ticket in this case...</p> <p><strong>[Update]</strong></p> <p>If you're in the position of hiring an external web design firm, and have the luxury of early collaboration and wish to help bridge the gap of meeting ASP.NET's requirements, here's our current list of guidelines. Please comment below if you feel there's something that should be added:</p> <ul> <li>Please encapsulate each the page in a &lt;form&gt; tag (ie. place it directly after the &lt;body&gt; tag), and use no other <code>&lt;form&gt;</code> tags on the page</li> <li><p>To display a summary of page validation errors, please cater to rendering the following format example: </p> <p><code>&lt;div class="error_class"&gt;</code><br /> <code>&lt;h3&gt;</code>Please review the following fields<code>&lt;/h3&gt;</code><br /> <code>&lt;ul&gt;</code><br /> <code>&lt;li&gt;</code>Home phone number<code>&lt;/li&gt;</code><br /> <code>&lt;li&gt;</code>Surname<code>&lt;/li&gt;</code><br /> <code>&lt;/ul&gt;</code><br /> <code>&lt;/div&gt;</code></p></li> <li>Please avoid driving styles off the ID or name property.</li> <li>If there are HTML components that need to be turned on and off, these components should be encapsulated in a <code>&lt;div&gt;</code> element, so that the div's visibility can be set to 'false'.</li> <li>If styling buttons, please cater to both <code>&lt;input&gt;</code> tags and <code>&lt;a ... class="example_class"&gt;</code> <code>&lt;span&gt;</code>Button text<code>&lt;/span&gt;</code>` formats.</li> <li>Avoid setting attributes on class-less <code>&lt;div&gt;</code> and <code>&lt;span&gt;</code> tags.</li> <li>Thank you for bearing with us.</li> </ul>
<p>Any time I've worked with design firms building asp.net pages I've always just had them design what it should look like. Nothing to do with the markup or css. This leaves a lot of work to be done by the developers, but avoids all the mistakes you just mentioned. I've always had designers deliver a PSD file and chopped it up myself.</p> <p>If this doesn't suit your needs you can always try ASP.NET MVC. It gives you a lot more control over the markup you put on the page.</p>
A question about datasource objects in ASP.net <p>When using DataSources in ASP.net applications, paging and sorting along with GridView only works out of the box when using DataSet, DataTable, DataViews if you are using anything else you need to implement methods that perform paging as well as partial data retrieval from the datasource. I dont know many design nowadays that pass around DataSets accross layers. I am a big POCO fan and I like to keep things simple specially when working with DataContracts in WCF.</p> <p>Am I missing something or is it too much to expect paging and sorting working out of the box or is it guys at MS dont think its important??? Is the DataPager control the answer??</p> <p>Also,I would really appreciate if someone can give me a fully functional [gridview- object data source - Paging &amp; sorting] tutorial/link. The ones I saw online made me feel that you need to hack your way in order to make it work.</p>
<p>You may have already come across them, but I've found Scott Mitchell's <a href="http://www.asp.net/learn/data-access" rel="nofollow">data access tutorials</a> very helpful in the past. Tutorials #24-27 cover paging and sorting, and he uses the ObjectDataSource.</p>
Making Applications programmed in .NET languages work on older machines <p>Wondering if anyone knows how to see what parts of the .NET framework need to be installed to get cerftain functions working on older machines. Is there a way I can install them with my application without installing the entire .NET framework?</p>
<p>You could use <a href="http://mono-project.com" rel="nofollow">Mono</a>, the open source implementation of the .NET framework. The Mono installer is smaller than the .NET installer. Also, Mono works with Windows versions older than XP. </p> <p>With Mono you can use the <a href="http://www.mono-project.com/Linker" rel="nofollow">Linker</a> to bundle only a small subset of the .NET framework, the one you need, with your application.</p> <p>The downside is that Mono doesn't implement the entire .NET framework, at the moment is only compatible with the version 2.0 and parts of the 3.0. Anyway, there is a tool called <a href="http://www.mono-project.com/MoMA" rel="nofollow">MoMa</a> which tell you how compatible with Mono is your application.</p>
Is .NET MVC must learn technology? <p>Is it here to stay, or is this something just pushed out quickly as a "me too" offering, in response to the Rails community?</p> <p>Is it necessary to go through the learning curve, and will the Framework move to only working this way, without the Page behind model?</p> <p>If so where's the best place to pick up MVC essentials for .NET?</p>
<p>I personally prefer MVC, it's better structured and makes me a happy lad! I got to use MVC for a project at work, because it had to be finished quickly, and I believed that even though I knew no MVC, that I could learn it and finish the project quicker than I could do it using WebForms, and I was right! Learnt MVC and finished the project in a week, with a little help from Stack Overflow!</p> <p>When I finished it, I had to go back to maintain some WebForms projects, and extend them, I just want to go back to MVC now! </p> <p>My personal experience.</p>
How do you detect that monkey patching has occurred in Ruby? <p>How do you check that monkey patching has been done to a specific class in Ruby? If that is possible, is it also possible to get the previous implementation(s) of the attribute that's been patched?</p>
<p>There are the hooks <code>method_added</code> and <code>method_undefined</code>. Garry Dolley has written an I<a href="http://scie.nti.st/2008/9/17/making-methods-immutable-in-ruby" rel="nofollow">mmutable module</a> that prevents monkey patching.</p>
What techniques are available for memory optimizing in 8051 assembly language? <p>I need to optimize code to get room for some new code. I do not have the space for all the changes. I can not use code bank switching (80c31 with 64k). </p>
<p>You haven't really given a lot to go on here, but there are two main levels of optimizations you can consider:</p> <p><strong>Micro-Optimizations:</strong> eg. XOR A instead of MOV A,0 Adam has covered some of these nicely earlier.</p> <p><strong>Macro-Optimizations:</strong> Look at the structure of your program, the data structures and algorithms used, the tasks performed, and think VERY hard about how these could be rearranged or even removed. Are there whole chunks of code that actually aren't used? Is your code full of debug output statements that the user never sees? Are there functions specific to a single customer that you could leave out of a general release? </p> <p>To get a good handle on that, you'll need to work out WHERE your memory is being used up. The Linker map is a good place to start with this. Macro-optimizations are where the BIG wins can be made.</p> <p>As an aside, you could - seriously- try rewriting parts of your code with a good optimizing C compiler. You may be amazed at how tight the code can be. A true assembler hotshot may be able to improve on it, but it can easily be better than most coders. I used the <a href="http://www.iar.com/website1/1.0.1.0/244/1/index.php">IAR</a> one about 20 years ago, and it blew my socks off.</p>
Collision Detection between two images in Java <p>I have two characters displayed in a game I am writing, the player and the enemy. defined as such:</p> <pre><code>public void player(Graphics g) { g.drawImage(plimg, x, y, this); } public void enemy(Graphics g) { g.drawImage(enemy, 200, 200, this); } </code></pre> <p>Then called with:</p> <pre><code>player(g); enemy(g); </code></pre> <p>I am able to move player() around with the keyboard, but I am at a loss when trying to detect a collision between the two. A lot of people have said to use Rectangles, but being a beginner I cannot see how I would link this into my existing code. Can anyone offer some advice for me?</p>
<p>I think your problem is that you are not using good OO design for your player and enemies. Create two classes:</p> <pre><code>public class Player { int X; int Y; int Width; int Height; // Getters and Setters } public class Enemy { int X; int Y; int Width; int Height; // Getters and Setters } </code></pre> <p>Your Player should have X,Y,Width,and Height variables.</p> <p>Your enemies should as well.</p> <p>In your game loop, do something like this (C#):</p> <pre><code>foreach (Enemy e in EnemyCollection) { Rectangle r = new Rectangle(e.X,e.Y,e.Width,e.Height); Rectangle p = new Rectangle(player.X,player.Y,player.Width,player.Height); // Assuming there is an intersect method, otherwise just handcompare the values if (r.Intersects(p)) { // A Collision! // we know which enemy (e), so we can call e.DoCollision(); e.DoCollision(); } } </code></pre> <p>To speed things up, don't bother checking if the enemies coords are offscreen.</p>
Non-axis aligned scaling <p>Finding a good way to do this has stumped me for a while now: assume I have a selection box with a set of points in it. By dragging the corners you can scale the (distance between) points in the box. Now for an axis aligned box this is easy. Take a corner as an anchor point (subtract this corner from each point, scale it, then add it to the point again) and multiply each points x and y by the factor with which the box has gotten bigger.</p> <p>But now take a box that is not aligned with the x and y axis. How do you scale the points inside this box when you drag its corners?</p>
<p>Any box is contained inside a circle.<br /> You find the circle which binds the box, find its center and do exactly the same as you do with an axis aligned box.</p>
Create a Search Engine with SQL 2000 and ASP.NET C# <p>I am looking to create a search engine that will be based on 5 columns in a SQL 2000 DB. I have looked into Lucene.NET and read the documentation on it, but wondering if anyone has any previous experience with this?</p> <p>Thanks</p>
<p>IMHO it's not so much about performance, but about maintainability. In order to index your content using Lucene.NET you'll have to create some mechanism (service of triggered) which will add new rows (and remove deleted rows) from the Lucene index. </p> <p>From a beginner's perspective I think it's probably easier to use the SQL Server built-in full text search engine.</p>
What are the uses of svn copy? <p>Example: </p> <pre><code>$ svn copy foo.txt bar.txt A bar.txt </code></pre> <ul> <li>When would you use this technique, and why? </li> <li>Will this command (taken from svn's "red book") creates a copy of <code>&lt;foo.txt&gt;</code> while preserving the history of it to be shared with <code>&lt;bar.txt&gt;</code>? </li> <li>If I'm changing <code>&lt;bar.txt&gt;</code>, what will happen to <code>&lt;foo.txt&gt;</code>? </li> </ul> <p>What are the equivalents to this in other modern systems (Clearcase, Accurev, Perforce)? </p> <p>Let me emphasize the point I'm searching for:<br> Is this kind of branching out on a file level?<br> What happens if you use it in the same branch, i.e. create a copy of a file and than start changing that new file. all in the same branch?<br> I understand that it is also used for tagging but what is interesting me is what to expect when performing <code>&lt;svn copy&gt;</code> on the file level.</p>
<p>Aside from branching/tagging, you can also use it when you split a file in two. In this case both new files will have history and you'll be able to look at the code before the split.</p> <p>BTW: that's one of few features that SVN has, but Git doesn't (Git will try to guess origin of code after the fact, especially if you add <code>-C</code> to commands).</p>
What is the relative difference between in-proc, interprocess, and inter machine calls? <p>Ignoring payload size, what is relative difference in latency between an in-proc call (say in C++ or Java), a socket call to a process on the same machine, and a socket call to a process on another machine? This can be expressed as a minimum latency in ns/ms or in terms of relative orders of magnitude. </p> <p>I'm looking for something similar to this:</p> <p><a href="http://duartes.org/gustavo/blog/post/what-your-computer-does-while-you-wait" rel="nofollow">http://duartes.org/gustavo/blog/post/what-your-computer-does-while-you-wait</a></p> <p>... but extended to in-proc vs. network calls (assume fast intranet).</p>
<p>That is a good idea... not precise, but it gives the rough ratios:</p> <p>method call -- ~100s ns synchronized method call -- ~1000s ns reflective method call -- low ~10,000s ns</p> <p>machine loopback -- ~30,000-150,000 ns</p> <p>local sub-network -- 1-2 ms</p> <p>internet -- 30-100 ms</p>
Discarding the output of a function that needs an output iterator <p>Suppose there´s a template function in C++ that does some useful work but also outputs a sequence of values via an output iterator. Now suppose that that sequence of values sometimes is interesting, but at others is not useful. Is there a ready-to-use iterator class in the STL that can be instantiated and passed to the function and will ignore any values the function tries to assign to the output iterator? To put in another way, send all data to /dev/null?</p>
<p>The STL does not provide such an iterator. But you could code it yourself (tested that code):</p> <pre><code>struct null_output_iterator : std::iterator&lt; std::output_iterator_tag, null_output_iterator &gt; { /* no-op assignment */ template&lt;typename T&gt; void operator=(T const&amp;) { } null_output_iterator &amp; operator++() { return *this; } null_output_iterator operator++(int) { return *this; } null_output_iterator &amp; operator*() { return *this; } }; </code></pre> <p>It doesn't need any data by using itself as the result of <code>operator*</code>. The result of <code>*it = x;</code> is not used in the output iterator requirements, so we can give it a return type of <code>void</code>.</p> <hr> <p>Edit: Let's go into how this <code>operator*</code> works. The Standard says in <strong>24.1.2/1</strong> about the requirements of an output iterator that in both these cases:</p> <pre><code>*it = t; *it++ = t; </code></pre> <p>That the result of those expressions is not used. That's what makes this work:</p> <pre><code>null_output_iterator it; *it; // returns a null_output_iterator&amp; per definition of the `operator*`. *it = some_value; // returns void per definition of the templated `operator=`. </code></pre> <p>Now we don't need to have any data that we return in <code>operator*</code>: We just use the iterator itself. Note that the templated operator= does not overwrite the builtin copy assignment operator. It's still provided.</p>
Regex expression to split string into items <p>I've got text in a form of</p> <pre><code>[1/12/2008 2:32:11 p.m. - name] line 1 [1/12/2008 2:36:00 p.m. - name] - PRIVATE line 2 [some text] sd [1/12/2008 2:36:00 p.m. - name] line 3 </code></pre> <p>which i want to split into items so i have access to time, name and text of each item, </p> <pre><code>e.g.: (item 1) 1: 1/12/2008 2:32:11 p.m. 2: name 3: line 1 (item 2) 1: 1/12/2008 2:36:00 p.m. 2: name 3: - PRIVATE line 2 [some text] sd (item 3) 1: 1/12/2008 2:36:00 p.m. 2: name 3: line 3 </code></pre> <p>I was trying to come up with a single regex pattern to achieve this, but no luck:</p> <pre><code>\[([0-9\/ \:\.apm]+?) - ([a-z_\-0-9]+?)\](.*?\r\n.+?)(?:\[[0-9\/ \:\.apm]+? - [a-z_\-0-9]+?\]) </code></pre> <p>This pattern above only returns the first item.</p> <pre><code>\[([0-9\/ \:\.apm]+?) - ([a-z_\-0-9]+?)\](.*?\r\n.+?)(?!\[[0-9\/ \:\.apm]+? - [a-z_\-0-9]+?\]) </code></pre> <p>The pattern above returns all items, but only first character of the text (group 3)</p> <p>Any suggestions?</p>
<p>It looks like this gets you what you want.</p> <pre><code>\[([0-9\/ \:\.apm]+?) - ([a-z_\-0-9]+?)\](.*?\r\n.+.*?) </code></pre> <p>I tested it out on <a href="http://iowacomputergurus.com/free-products/regular-expression-tester.aspx" rel="nofollow">my RegEx tester</a> and it appears to get the proper format.</p>
What causes svn commit to fail and report a file/dir as obstructed? <p>I am pretty much the only person making check ins to the svn repo but for some reason over the past week Tortoise is reported that my WCF Service Reference directory is 'obstructed' and I cant commit my changes. If I have no even made any changes to the contents of that directory, why does svn report obstructed and what does that even mean?</p> <p>Thanks</p>
<p>You've probably deleted/moved some files / directories directly from the file system, and not through SVN commands. This can sometimes lead to a directory becoming obstructed if it can not work out the differences against the repository. </p> <p>Try performing a clean-up first, and if that fails, revert that directory and try use SVN commands for changing directory file structure (delete/move).</p>
Regular Expression for alphanumeric and underscores <p>I would like to have a regular expression that checks if a string contains only upper and lowercase letters, numbers, and underscores.</p>
<p>To match a string that contains <em>only</em> those characters (or an empty string), try</p> <pre><code>"^[a-zA-Z0-9_]*$" </code></pre> <p>This works for .NET regular expressions, and probably a lot of other languages as well.</p> <p>Breaking it down:</p> <pre><code>^ : start of string [ : beginning of character group a-z : any lowercase letter A-Z : any uppercase letter 0-9 : any digit _ : underscore ] : end of character group * : zero or more of the given characters $ : end of string </code></pre> <p>If you don't want to allow empty strings, use + instead of *.</p> <p><strong>EDIT</strong> As others have pointed out, some regex languages have a shorthand form for <code>[a-zA-Z0-9_]</code>. In the .NET regex language, you can turn on ECMAScript behavior and use <code>\w</code> as a shorthand (yielding <code>^\w*$</code> or <code>^\w+$</code>). Note that in other languages, and by default in .NET, <code>\w</code> is somewhat broader, and will match other sorts of unicode characters as well (thanks to Jan for pointing this out). So if you're really intending to match <strong>only</strong> those characters, using the explicit (longer) form is probably best.</p>
How to redirect to (or enforce) SSL connection? <p>I am using Zend Framework(MVC part of it), and need to either redirect user to SSL enabled page or to force SSL from controller somehow and don't quite see how to do that? Maybe someone can share the knowledge? </p> <p>Thanks!</p>
<p>It's easy to do at the web server level.</p> <p>In Apache, you'd do it like this:</p> <pre><code>RewriteEngine On RewriteRule (.*) https://%{HTTP_HOST}%{REQUEST_URI} </code></pre>
How can I enforce a maximum amount of forked children? <p>EDIT: I've tagged this C in a hope to get more response. It's more the theory I'm interested in than a specific language implementation. So if you're a C coder please treat the following PHP as pseudo-code and feel free to respond with an answer written in C.</p> <p>I am trying to speed up a PHP CLI script by having it execute its tasks in parallel instead of serial. The tasks are completely independent of each other so it doesn't matter which order they start/finish in.</p> <p>Here's the original script (note all these examples are stripped-back for clarity):</p> <pre><code>&lt;?php $items = range(0, 100); function do_stuff_with($item) { echo "$item\n"; } foreach ($items as $item) { do_stuff_with($item); } </code></pre> <p>I've managed to make it work on the <code>$items</code> in parallel with <a href="http://php.net/pcntl_fork" rel="nofollow"><code>pcntl_fork()</code></a> as shown below:</p> <pre><code>&lt;?php ini_set('max_execution_time', 0); ini_set('max_input_time', 0); set_time_limit(0); $items = range(0, 100); function do_stuff_with($item) { echo "$item\n"; } $pids = array(); foreach ($items as $item) { $pid = pcntl_fork(); if ($pid == -1) { die("couldn't fork()"); } elseif ($pid &gt; 0) { // parent $pids[] = $pid; } else { // child do_stuff_with($item); exit(0); } } foreach ($pids as $pid) { pcntl_waitpid($pid, $status); } </code></pre> <p>Now I want to extend this so there's a maximum of, say, 10 children active at once. What's the best way of handling this? I've tried a few things but haven't had much luck.</p>
<p>The best thing I can come up with is to add all the tasks to a queue, launch the maximum number of threads you want, and then have each thread requesting a task from the queue, execute the task and requesting the next one. Don't forget to have the threads terminate when there are no more tasks to do.</p>
I need help...........sample project <p>Can anybody give me one sample Asp.Net Project where all the Object oriented concept like class, abstraction, polymorphism, Inheritance and array list has been used for my practice purpose.</p> <p>I am new to this platform i know all the above mentioned concept but i don't know where and how to use those concept in web application.</p>
<p>Download from : <a href="http://www.dotnetspider.com/" rel="nofollow">http://www.dotnetspider.com/</a></p> <p>Available sample projects over there are :</p> <ol> <li>Course Finder - Search Colleges and Courses</li> <li>Library Management System</li> <li>Student Project - Personal Assistant</li> <li>Academic Project - Address Book</li> <li>School Management System </li> </ol>
Prerequisites Needed to Read Books on Neural Networks (and understand them) <p>I've been trying to learn about Neural Networks for a while now, and I can understand some basic tutorials online, and I've been able to get through portions of <a href="http://rads.stackoverflow.com/amzn/click/0852742622">Neural Computing - An Introduction</a> but even there, I'm glazing over a lot of the math, and it becomes completely over my head after the first few chapters. Even then its the least book "math-y" I can find. </p> <p>Its not that I'm afraid of the math or anything, its just I haven't learned what I need, and I'm not sure what I need exactly. I'm currently enrolled at my local university, working on catching up on classes I need to enter the MS in Comp. Sci program (my BA is in Business/Info. Sys.) and I haven't gotten very far. According to the university's little course descriptions, NN's are actually covered in a Electrical Engineering course on Pattern Recognition (seems odd to me that this course is EE), which has a few EE prereq's that I don't need to get into the MS Comp. Sci. Program.</p> <p>I'm extremely interested in this topic, and know I eventually want to learn a lot more about it, the problem is, I don't know what I need to know first. Here are topics I think I might need, but this is just speculation from ignorance:</p> <ul> <li>Single Variable Calculus (I've had Calc I and II, so I think I'm covered here, just listing for completeness)</li> <li>Multi Variable Calculus</li> <li>Linear Algebra (I've not taken this formally yet, but can actually understand many of the concepts from what I've managed to grok on Wikipedia and other sites)</li> <li>Discrete Mathematics (Another I've not taken formally, but learned a portion of on my own</li> <li>Graph Theory</li> <li>Probability Theory</li> <li>Bayesian Statistics</li> <li>Circuit Design</li> <li>Other maths?</li> <li>Other comp sci topics </li> </ul> <p>Obviously there is a neuroscience component here as well, but I actually haven't had any trouble understanding books when they talk about it as applied to NN's, largely because its conceptual</p> <p>In short, Can someone lay out a semi-clear path that one needs to really understand, read book on and eventually implement Neural Networks?</p>
<p>If you want a list of college courses that you'll need to understand the book, here it is:</p> <ul> <li>Calculus (I, II and III)</li> <li>Differential Equations</li> <li>Linear Algebra</li> <li>Statistics (or a good covering of Bayes)</li> </ul> <p>However, I did just fine in my NN classes without Diff. Eq. and just had to look up concepts I hadn't studied yet.</p> <p>You can take the black box approach as above, but if you really want to understand the math and implementation of the networks, you'll have to study. It's going to be a steep learning curve to fully grasp the more advanced networks no matter what you do. You can either take the above classes first, or you can start reading the book and look up everything you don't grasp on wikipedia, and then from those articles read whatever you have to read to understand them, etc. You will find that, either way, you'll eventually get past that initial peek and things will be easier.</p> <p>It would be good if you told us why you want to learn neural networks. I've not found a single use for them in my professional career, though I'm not a game developer or telecommunications developer.</p>
Somebody explain me Html.DropDown and it's dearest friend SelectList <p>If you check my earlier questions you may have noticed I just don't get the SelectList and Html.DropDown(). I find it intrigueing that I seem to be the only one in this. So maybe I should try to change my mindset or maybe there are things I don't know that will clear this all up. I really love the whole MVC framework, but SelectList just doesn't want to fit in my head. So here's my list:</p> <p><strong>SelectList</strong></p> <ul> <li>Why can't I set the selected value after instantiation</li> <li>Why can't I set selectedValue by index of items</li> <li>Why is the selectedvalue sometimes a string, sometimes the class I put into it and sometimes a ListItem</li> <li>Why are the items only accesible through GetItems()</li> <li>Why don't the types of selectedItem and the listItems match?</li> <li>Why are the items you put in the list converted to listItem and the selectedItem not?</li> <li>Why can't I get the count of the items without usint the GetItems() method</li> </ul> <p><strong>Html.DropDownList()</strong></p> <ul> <li>Why doesn't modelbinding work with it</li> <li>Why is there no behaviour for defaulting selection when there's only one option </li> <li>Why doesn't making an item SelectedValue in the source selectLIst make it the marked item</li> </ul> <p>Before ppl suggest me to write my own:<br /> Since this will be shipped with the MVC product, I would rather have the offical support for a basic controll then to roll my own and have all the troubles that come with it.</p>
<p>I feel your pain. Forgive the shameless plug, but you might look into <a href="http://lunaverse.wordpress.com/2008/11/24/mvcfluenthtml-fluent-html-interface-for-ms-mvc/" rel="nofollow">MvcFluentHtml</a>. You can still use SelectList and MultiSelectList, but you have several other choices. Should work fine with binders.</p>
Explicit script end tag always converted to self-closing <p>I'm using xslt to transform xml to an aspx file. In the xslt, I have a script tag to include a jquery.js file. To get it to work with IE, the script tag must have an explicit closing tag. For some reason, this doesn't work with xslt below.</p> <pre><code>&lt;?xml version="1.0" encoding="utf-8"?&gt; &lt;xsl:stylesheet version="1.0" xmlns="http://www.w3.org/1999/xhtml" xmlns:xsl="http://www.w3.org/1999/XSL/Transform" xmlns:msxsl="urn:schemas-microsoft-com:xslt" exclude-result-prefixes="msxsl" xmlns:asp="remove"&gt; &lt;xsl:output method="html"/&gt; &lt;xsl:template match="/"&gt; &lt;html xmlns="http://www.w3.org/1999/xhtml"&gt; &lt;head&gt; &lt;title&gt;TEST&lt;/title&gt; &lt;script type="text/javascript" src="jquery-1.2.6.js"&gt;&lt;/script&gt; </code></pre> <p>But if I change the script tag as shown below, it works. </p> <pre><code> &lt;script type="text/javascript" src="jquery-1.2.6.js"&gt; // &lt;![CDATA[ // ]]&gt; &lt;/script&gt; </code></pre> <p>I thought that the <code>&lt;xsl:output method="html" /&gt;</code> would do the trick, but it doesn't seem to work?</p> <p>/Jonas</p>
<p>If you're creating the XmlWriter yourself you need to pass the transform's OutputSettings to the XmlWriter, eg:</p> <pre><code>XmlDocument doc = new XmlDocument(); doc.LoadXml("&lt;book&gt;&lt;author&gt;Trudi Canavan&lt;/author&gt;&lt;title&gt;Voice of the Gods&lt;/title&gt;&lt;/book&gt;"); XslCompiledTransform transform = new XslCompiledTransform(); transform.Load("XSLTFile1.xslt"); StringBuilder output = new StringBuilder(); // Here we pass the output setting to the writer, otherwise the transform // may be set to Html, but the XmlWriter will be outputting Xml XmlWriter writer = XmlWriter.Create(output, transform.OutputSettings); transform.Transform(doc, writer); Console.WriteLine(output.ToString()); Console.ReadKey(); </code></pre>
Enable ListView multiselect by dragging <p>How do I enable multi-select in a WPF ListView by dragging? </p> <p>Setting the SelectionMode property to Extended does allow multi-select using Shift and Ctrl, but not by clicking and dragging. Setting the SelectionMode property to Multiple gives a sticky selection which isn't what I want.</p>
<p>You could extend <code>ListView</code> and <code>ListViewItem</code> to implement click and drag multi-select behavior.</p> <p>A very similar solution was posted <a href="http://stackoverflow.com/questions/6364029/drag-select-with-listbox/6728555#6728555">here</a>.</p>
ASP.NET: Custom client-side validator for "one of two fields must be filled"? <p>Can you tell me if there anybody has implemented a <strong>custom validator for checking that one of two (or N)</strong> input fields are filled?</p> <pre><code> "Insert phone number or email address" </code></pre> <p>I'm using ASP.NET (Ajax) 3.5, the ajaxToolkit:ValidatorCalloutExtender (and jQuery if it's necessary).</p>
<p>I just did this (requires jQuery):</p> <p>JS:</p> <pre><code>function validatePhoneOrEmail(source, args) { if ($("[id$='txtEmail']").val() == "" &amp;&amp; $("[id$='txtTel']").val() == "") args.IsValid = false; else args.IsValid = true; } </code></pre> <p>ASP.NET:</p> <pre><code>&lt;asp:CustomValidator runat="server" ClientValidationFunction="validatePhoneOrEmail" ErrorMessage="Please enter a telephone number or email address"&gt; &lt;/asp:CustomValidator&gt; </code></pre> <p>I don't have any server-side validation for this, but I'm assuming a similar function in the server would be pretty easy to create.</p>
Chaining containers with StructureMap <p>Is it possible to link containers together in StructureMap like it is in WindsorContainer.AddChildContainer()?</p> <p>I want to achieve having 3 container levels; - 1 page request level - 1 session level - 1 application level</p> <p>These would then be chained together so only one instance request would be made to the "base level" container.</p> <p>The levels of container are unimportant really, just whether there is the ability to link them together.</p>
<p>This seems to do the trick, not sure if there is a better way or what the implications are. So far looks ok...</p> <pre><code>childContainer.PluginGraph.Registries.ForEach( registry =&gt; parentContainer.Configure(expression =&gt; expression.AddRegistry(registry)) ); </code></pre> <p>where parentContainer &amp; childContainer are both StructureMap.Container</p>
How do you apply patches on a web project at production server? <p>We recently had a project where we released beta of a big web app on our client's server. Our client requested us to do bug fixes as they come, and we tried to do it same way. Normally while building an app on our prototype server is way easier, as I just have to issue simple 'svn up' command which takes a second. </p> <p>But on production environment, we do not have any version control tool available. Is it possible to automate the patching work, so that we need not to login to ftp and upload each a every file one by one? </p> <p>Its very difficult to work this way. As I'm having this problem, its for sure that some of you have already solved the problem. Please share your solutions.</p> <p>Looking forward to your replies... Thanks a lot for reading guys.</p>
<p>Depending on the tools available on the server, you could either do a <code>svn diff -r x:y</code> where x is the revision you last updated too and y the last revision you want to update to (probably the last revision on your repository) to generate a patch and then apply the patch with the <code>patch</code> command.</p> <p>If <code>rsync</code> is available on the production platform, and you can use it (though ssh for instance) you could set up a production ready tree, rsync it on the production server, and when an update comes in, svn update your production tree, and rsync it again.</p>
core dump at _dl_sysinfo_int80 () <p>I have created a TCP client that connects to a listening server. We implemeted TCP keep alive also. Some times the client crashes and core dumped. Below are the core dump traces.</p> <p>Problem is in linux kernel version Update 4, kernel 2.6.9-42.0.10.</p> <p>we had two core dumps.</p> <pre><code>(gdb) where #0 0x005e77a2 in _dl_sysinfo_int80 () from /ddisk/d303/dumps/mhx239131/ld- linux.so.2 #1 0x006c8bd1 in connect () from /ddisk/d303/dumps/mhx239131/libc.so.6 #2 0x08057863 in connect_to_host () #3 0x08052f38 in open_ldap_connection () #4 0x0805690a in new_connection () #5 0x08052cc9 in ldap_open () #6 0x080522cf in checkHosts () #7 0x08049b36 in pollLDEs () #8 0x0804d1cd in doOnChange () #9 0x0804a642 in main () (gdb) where #0 0x005e77a2 in _dl_sysinfo_int80 () from /ddisk/d303/dumps/mhx239131/ld- linux.so.2 #1 0x0068ab60 in __nanosleep_nocancel ( from /ddisk/d303/dumps/mhx239131/libc.so.6 #2 0x080520a2 in Sleep () #3 0x08049ac1 in pollLDEs () #4 0x0804d1cd in doOnChange () #5 0x0804a642 in main () </code></pre> <p>We have tried to reproduce the problem in our environment, but we could not.</p> <p>What would cause the core file?</p> <p>Please help me to avoid such situation.</p> <p>Thanks, Naga</p>
<p><code>_dl_sysinfo_int80</code> is just a function which does a system call into the kernel. So the core dump is happening on a system call (probably the one used by <code>connect</code> in the first example and <code>nanosleep</code> in the second example), probably because you are passing invalid pointers.</p> <p>The invalid pointers could be because the code which calls these functions being broken or because <em>somewhere else</em> in the program is broken and corrupting the program's memory.</p> <p>Take a look at two frames above (frame <code>#2</code>) in the core dump for both examples and check the parameters being passed. Unfortunately, it seems you did not compile with debug information, making it harder to see them.</p> <p>Additionally, I would suggest trying <code>valgrind</code> and seeing if it finds something.</p>
How to write your own .net obfuscator <p>I am very curious as to how people write their own obfuscator.</p> <p>How hard would it be to simply do the following:</p> <ol> <li>rename all public methods with GUID type names.</li> </ol> <p>Where would I start? How would I go about reading the .net dll assemby, pulling the public methods out and renaming them? </p>
<p>You can check those two projects that are using <a href="http://www.mono-project.com/Cecil" rel="nofollow" title="Cecil">Cecil</a> to write an open-source obfuscator:</p> <ul> <li><a href="http://code.google.com/p/obfuscar/" rel="nofollow">http://code.google.com/p/obfuscar/</a></li> <li><a href="http://www.codeplex.com/SharpObfuscator" rel="nofollow">http://www.codeplex.com/SharpObfuscator</a></li> </ul>
Why is Visual Studio's table adapter query not returning the same data as the stored procedure it represents? <p>I'm using a table adapter in Visual Studio to make a query to a stored procedure in my SQL Server 2005 database. When I make the call via my website application it returns nothing. When I make the same call via SQL Server Manager it returns the expected data.</p> <p>I put a breakpoint on the call to the adapter's <code>getData</code> method and looked at all the parameters and their values and matched them in a query from server management to make sure. I'm sending the following query:</p> <pre><code>getData(string, date, date, int, int?, int?, string, int?, string) </code></pre> <p>further</p> <pre><code>getData('0000-rtg', '1/1/2007', '3/12/2008', 0, null, null, null, null, null) </code></pre> <p>I guess I'm wondering if Visual Studio does something with the <code>null</code>'s before it tries to send the query to the SQL server. If not, how do I fix this problem?</p> <p>EDIT: All these values are passed by variables, I just typed what was in those variables at that break point. </p>
<p>Dates need to have quotes around them in SQL else they don't work. </p>
How do integrate Delphi with Active Directory? <p>We need to validate an user on Microsoft's Active Directory using Delphi 7, what is the best way to do that?</p> <p>We can have two scenarios: the user inputs its network username and password, where the username may include the domain, and we check on active directory if it is a valid, active user. Or we get the current logged user from Windows, and check on AD if it is still valid.</p> <p>The first scenario requires user validation, while the second one just a simple AD search and locate.</p> <p>Does anyone know of components or code that do one or both of the scenarios described above?</p>
<p>Here's a unit we wrote and use. Simple and gets the job done.</p> <pre><code>unit ADSI; interface uses SysUtils, Classes, ActiveX, Windows, ComCtrls, ExtCtrls, ActiveDs_TLB, adshlp, oleserver, Variants; type TPassword = record Expired: boolean; NeverExpires: boolean; CannotChange: boolean; end; type TADSIUserInfo = record UID: string; UserName: string; Description: string; Password: TPassword; Disabled: boolean; LockedOut: boolean; Groups: string; //CSV end; type TADSI = class(TComponent) private FUserName: string; FPassword: string; FCurrentUser: string; FCurrentDomain: string; function GetCurrentUserName: string; function GetCurrentDomain: string; protected { Protected declarations } public constructor Create(AOwner: TComponent); override; destructor Destroy; override; property CurrentUserName: string read FCurrentUser; property CurrentDomain: string read FCurrentDomain; function GetUser(Domain, UserName: string; var ADSIUser: TADSIUserInfo): boolean; function Authenticate(Domain, UserName, Group: string): boolean; published property LoginUserName: string read FUserName write FUserName; property LoginPassword: string read FPassword write FPassword; end; procedure Register; implementation function ContainsValComma(s1,s: string): boolean; var sub,str: string; begin Result:=false; if (s='') or (s1='') then exit; if SameText(s1,s) then begin Result:=true; exit; end; sub:=','+lowercase(trim(s1))+','; str:=','+lowercase(trim(s))+','; Result:=(pos(sub, str)&gt;0); end; procedure Register; begin RegisterComponents('ADSI', [TADSI]); end; constructor TADSI.Create(AOwner: TComponent); begin inherited Create(AOwner); FCurrentUser:=GetCurrentUserName; FCurrentDomain:=GetCurrentDomain; FUserName:=''; FPassword:=''; end; destructor TADSI.Destroy; begin inherited Destroy; end; function TADSI.GetCurrentUserName : string; const cnMaxUserNameLen = 254; var sUserName : string; dwUserNameLen : DWord; begin dwUserNameLen := cnMaxUserNameLen-1; SetLength(sUserName, cnMaxUserNameLen ); GetUserName(PChar(sUserName), dwUserNameLen ); SetLength(sUserName, dwUserNameLen); Result := sUserName; end; function TADSI.GetCurrentDomain: string; const DNLEN = 255; var sid : PSID; sidSize : DWORD; sidNameUse : DWORD; domainNameSize : DWORD; domainName : array[0..DNLEN] of char; begin sidSize := 65536; GetMem(sid, sidSize); domainNameSize := DNLEN + 1; sidNameUse := SidTypeUser; try if LookupAccountName(nil, PChar(FCurrentUser), sid, sidSize, domainName, domainNameSize, sidNameUse) then Result:=StrPas(domainName); finally FreeMem(sid); end; end; function TADSI.Authenticate(Domain, UserName, Group: string): boolean; var aUser: TADSIUserInfo; begin Result:=false; if GetUser(Domain,UserName,aUser) then begin if not aUser.Disabled and not aUser.LockedOut then begin if Group='' then Result:=true else Result:=ContainsValComma(Group, aUser.Groups); end; end; end; function TADSI.GetUser(Domain, UserName: string; var ADSIUser: TADSIUserInfo): boolean; var usr : IAdsUser; flags : integer; Enum : IEnumVariant; grps : IAdsMembers; grp : IAdsGroup; varGroup : OleVariant; Temp : LongWord; dom1, uid1: string; //ui: TADSIUserInfo; begin ADSIUser.UID:=''; ADSIUser.UserName:=''; ADSIUser.Description:=''; ADSIUser.Disabled:=true; ADSIUser.LockedOut:=true; ADSIUser.Groups:=''; Result:=false; if UserName='' then uid1:=FCurrentUser else uid1:=UserName; if Domain='' then dom1:=FCurrentDomain else dom1:=Domain; if uid1='' then exit; if dom1='' then exit; try if trim(FUserName)&lt;&gt;'' then ADsOpenObject('WinNT://' + dom1 + '/' + uid1, FUserName, FPassword, 1, IADsUser, usr) else ADsGetObject('WinNT://' + dom1 + '/' + uid1, IADsUser, usr); if usr=nil then exit; ADSIUser.UID:= UserName; ADSIUser.UserName := usr.FullName; ADSIUser.Description := usr.Description; flags := usr.Get('userFlags'); ADSIUser.Password.Expired := usr.Get('PasswordExpired'); ADSIUser.Password.CannotChange := (flags AND ADS_UF_PASSWD_CANT_CHANGE)&lt;&gt;0; ADSIUser.Password.NeverExpires := (flags and ADS_UF_DONT_EXPIRE_PASSWD)&lt;&gt;0; ADSIUser.Disabled := usr.AccountDisabled; ADSIUser.LockedOut := usr.IsAccountLocked; ADSIUser.Groups:=''; grps := usr.Groups; Enum := grps._NewEnum as IEnumVariant; if Enum &lt;&gt; nil then begin while (Enum.Next(1,varGroup, Temp) = S_OK) do begin grp := IDispatch(varGroup) as IAdsGroup; //sGroupType := GetGroupType(grp); if ADSIUser.Groups&lt;&gt;'' then ADSIUser.Groups:=ADSIUser.Groups+','; ADSIUser.Groups:=ADSIUser.Groups+grp.Name; VariantClear(varGroup); end; end; usr:=nil; Result:=true; except on e: exception do begin Result:=false; exit; end; end; end; end. </code></pre>
Javascript Marquee to replace <marquee> tags <p>I'm hopeless at Javascript. This is what I have:</p> <pre><code>&lt;script type="text/javascript"&gt; function beginrefresh(){ //set the id of the target object var marquee = document.getElementById("marquee_text"); if(marquee.scrollLeft &gt;= marquee.scrollWidth - parseInt(marquee.style.width)) { marquee.scrollLeft = 0; } marquee.scrollLeft += 1; // set the delay (ms), bigger delay, slower movement setTimeout("beginrefresh()", 10); } &lt;/script&gt; </code></pre> <p>It scrolls to the left but I need it to repeat relatively seamlessly. At the moment it just jumps back to the beginning. It might not be possible the way I've done it, if not, anyone have a better method?</p>
<p>Here is a jQuery plugin with a lot of features:</p> <p><a href="http://jscroller2.markusbordihn.de/example/image-scroller-windiv/">http://jscroller2.markusbordihn.de/example/image-scroller-windiv/</a></p> <p>And this one is "silky smooth"</p> <p><a href="http://remysharp.com/2008/09/10/the-silky-smooth-marquee/">http://remysharp.com/2008/09/10/the-silky-smooth-marquee/</a></p>
Is it worth it to code different functionality for users with javascript disabled? <p>I'm currently building a project and I would like to make use of some simple javascript - I know some people have it disabled to prevent XSS and other things. Should I...</p> <p>a) Use the simple javascript, those users with it disabled are missing out</p> <p>b) Don't use the simple javascript, users with it enabled have to click a little more</p> <p>c) Code both javascript-enabled and javascript-disabled functionality</p> <p>I'm not really sure as the web is always changing, what do you recommend?</p>
<p>Degrade gracefully - make sure the site works without JavaScript, then add bells and whistles for those with JavaScript enabled.</p>
How to Debug .NET Mobile Device Application using multiple instances of Device Emulator <p>I would like to Debug .NET Mobile Device Application using multiple instances of Device Emulator. If I right click the project and go to Debug -> Start new instance in Visual Studio 2008 when an instance is already running I get the error</p> <blockquote> <p>Unable to copy file "obj\Debug\MyMobileApp.exe" to "bin\Debug\MyMobileApp.exe". The process cannot access the file 'bin\Debug\MyMobileApp.exe' because it is being used by another process.</p> </blockquote> <p>Does anyone know if and how I can do this?</p>
<p>I just discovered a way you can (sort of) do this. You can't deploy from two instances of Visual Studio to two instances of the same type of emulator, but you <em>can</em> deploy to instances of two <em>different</em> types of emulator. Although not without a small trick.</p> <p>To see how this works, open two instances of Visual Studio, and open the same CF project in each. Next, you need to manually start two emulators. Find the file <strong>dvcemumanager.exe</strong> (it should be in <strong>C:\Program Files\Microsoft Device Emulator\1.0</strong>) and run it. To start an emulator, select it and then click Actions | Connect. For this example, start the regular emulator and the VGA emulator (and wait for them to fully come up, of course).</p> <p>Back in Visual Studio, set one instance's deployment target to the regular emulator, and the other instance's target to the VGA emulator, and start each. Each app will be deployed to the appropriate already-running instance of the emulator.</p> <p>You can't use this technique to run two versions of the same type of emulator, because there doesn't seem to be any way of doing that from the device manager interface. Also, you can't just start two instances of VS and set them to different emulators - I tried that and it doesn't work. For some reason the second one tries to deploy to the same emulator as the first, and you get the error you saw.</p>
Matrix Template Library matrix inversion <p>I'm trying to inverse a matrix with version Boost boost_1_37_0 and MTL mtl4-alpha-1-r6418. I can't seem to locate the matrix inversion code. I've googled for examples and they seem to reference lu.h that seems to be missing in the above release(s). Any hints?</p> <p><a href="http://stackoverflow.com/users/8643/matt-cruikshank">@Matt</a> suggested copying lu.h, but that seems to be from MTL2 rather than MTL4. I'm having trouble compiling with MTL2 with VS05 or higher. </p> <p>So, any idea how to do a matrix inversion in MTL4?</p> <p>Update: I think I understand Matt better and I'm heading down <a href="http://www.osl.iu.edu/research/itl/" rel="nofollow">this ITL path</a>.</p>
<p>Looks like you use <code>lu_factor</code>, and then <code>lu_inverse</code>. I don't remember what you have to do with the pivots, though. From the <a href="http://www.osl.iu.edu/research/mtl/reference/html/index.html" rel="nofollow">documentation</a>.</p> <p>And yeah, like you said, it looks like their documentations says you need lu.h, somehow:</p> <blockquote> <p><strong>How do I invert a matrix?</strong></p> <p>The first question you should ask yourself is whether you want to really compute the inverse of a matrix or if you really want to solve a linear system. For solving a linear system of equations, it is not necessary to explicitly compute the matrix inverse. Rather, it is more efficient to compute triangular factors of the matrix and then perform forward and backward triangular solves with the factors. More about solving linear systems is given below. If you really want to invert a matrix, there is a function <code>lu_inverse()</code> in mtl/lu.h.</p> </blockquote> <p>If nothing else, you can look at <a href="http://www.osl.iu.edu/research/mtl/mtl/lu.h" rel="nofollow">lu.h on their site</a>.</p>
Create an Array of the Last 30 Days Using PHP <p>I am trying to create an array starting with today and going back the last 30 days with PHP and I am having trouble. I can estimate but I don’t know a good way of doing it and taking into account the number of days in the previous month etc. Does anyone have a good solution? I can’t get close but I need to make sure it is 100% accurate.</p>
<p>Try this:</p> <pre><code>&lt;?php $d = array(); for($i = 0; $i &lt; 30; $i++) $d[] = date("d", strtotime('-'. $i .' days')); ?&gt; </code></pre>
Python subprocess.call() fails when using pythonw.exe <p>I have some Python code that works correctly when I use python.exe to run it, but fails if I use pythonw.exe.</p> <pre> def runStuff(commandLine): outputFileName = 'somefile.txt' outputFile = open(outputFileName, "w") try: result = subprocess.call(commandLine, shell=True, stdout=outputFile) except: print 'Exception thrown:', str(sys.exc_info()[1]) myThread = threading.Thread(None, target=runStuff, commandLine=['whatever...']) myThread.start() </pre> <p>The message I get is:</p> <pre> Exception thrown: [Error 6] The handle is invalid </pre> <p>However, if I don't specify the 'stdout' parameter, subprocess.call() starts okay.</p> <p>I can see that pythonw.exe might be redirecting output itself, but I can't see why I'm blocked from specifying stdout for a new thread.</p>
<p><code>sys.stdin</code> and <code>sys.stdout</code> handles are invalid because pythonw does not provide console support as it runs as a deamon, so default arguments of <code>subprocess.call()</code> are failing.</p> <p>Deamon programs close stdin/stdout/stderr purposedly and use logging instead, so that you have to manage this yourself: I would suggest to use subprocess.PIPE.</p> <p>If you <em>really</em> don't care about what the sub process says for errors and all, you could use <code>os.devnull</code> (I'm not really sure how portable it is?) but I wouldn't recommend that.</p>
SubSonic "Version" fails due to missing dependencies <p>I am using SubSonic 2.1 Final but having problems running "Version" with the SubCommander. I think this problem began when I installed SQL Server 2008 on my local machine and removed 2005.</p> <p>This is the error I get:</p> <pre><code>ERROR: Trying to execute Version Error Message: System.IO.FileNotFoundException: Could not load file or assembly 'Microsoft.SqlServer.SmoEnum, Version=9.0.242.0, Culture=neutral, PublicKeyToken=89845dcd8080cc91' or one of its dependencies. The system cannot find the file specified. File name: 'Microsoft.SqlServer.SmoEnum, Version=9.0.242.0, Culture=neutral, PublicKeyToken=89845dcd8080cc91' at Microsoft.SqlServer.Management.Smo.SqlSmoObject.GetDbCollation(String dbname) at Microsoft.SqlServer.Management.Smo.SqlSmoObject.GetDbComparer(Boolean inServer) at Microsoft.SqlServer.Management.Smo.SqlSmoObject.InitializeStringComparer() at Microsoft.SqlServer.Management.Smo.AbstractCollectionBase.get_StringComparer() at Microsoft.SqlServer.Management.Smo.SimpleObjectCollectionBase.InitInnerCollection() at Microsoft.SqlServer.Management.Smo.SmoCollectionBase.get_InternalStorage() at Microsoft.SqlServer.Management.Smo.SmoCollectionBase.GetObjectByKey(ObjectKeyBase key) at Microsoft.SqlServer.Management.Smo.DatabaseCollection.get_Item(String name) at SubSonic.SubCommander.DBScripter.ScriptSchema(String connectionString) in C:\svn\subsonicproject\trunk\SubCommander\DBScripter.cs:line 51 at SubSonic.SubCommander.Program.ScriptSchema() in C:\svn\subsonicproject\trunk\SubCommander\Program.cs:line 696 at SubSonic.SubCommander.Program.Main(String[] args) in C:\svn\subsonicproject\trunk\SubCommander\Program.cs:line 68 </code></pre> <p>Anybody knows how to make this work?</p>
<p>You probably have to compile SubCommander with the SqlServer 2008 version of Microsoft.SqlServer.Management.Smo dlls</p>
Avoiding a javascript race condition <p>Here's the scenario:</p> <p>My users are presented a grid, basically, a stripped down version of a spreadsheet. There are textboxes in each row in the grid. When they change a value in a textbox, I'm performing validation on their input, updating the collection that's driving the grid, and redrawing the subtotals on the page. This is all handled by the OnChange event of each textbox.</p> <p>When they click the "Save" button, I'm using the button's OnClick event to perform some final validation on the amounts, and then send their entire input to a web service, saving it.</p> <p>At least, that's what happens if they tab through the form to the Submit button.</p> <p>The problem is, if they enter a value, then immediately click the save button, SaveForm() starts executing before UserInputChanged() completes -- a race condition. My code does not use setTimeout, but I'm using it to simulate the sluggish UserInputChanged validation code:</p> <pre><code> &lt;!-- snip --&gt; &lt;script&gt; var amount = null; var currentControl = null; function UserInputChanged(control) { currentControl = control; // use setTimeout to simulate slow validation code (production code does not use setTimeout) setTimeout("ValidateAmount()", 100); } function SaveForm() { // call web service to save value document.getElementById("SavedAmount").innerHTML = amount; } function ValidateAmount() { // various validationey functions here amount = currentControl.value; // save value to collection document.getElementById("Subtotal").innerHTML = amount; // update subtotals } &lt;/script&gt; &lt;!-- snip --&gt; Amount: &lt;input type="text" id="UserInputValue" onchange="UserInputChanged(this);" /&gt; &lt;br /&gt; Subtotal: &lt;span id="Subtotal"&gt;&lt;/span&gt; &lt;br /&gt; &lt;input type="button" onclick="SaveForm();" value="Save" /&gt; &lt;br /&gt;&lt;br /&gt; Saved amount: &lt;span id="SavedAmount"&gt;&lt;/span&gt; &lt;!-- snip --&gt; </code></pre> <p>I don't think I can speed up the validation code -- it's pretty lightweight, but apparently, slow enough that code tries to call the web service before the validation is complete.</p> <p>On my machine, ~95ms is the magic number between whether the validation code executes before the save code begins. This may be higher or lower depending on the users' computer speed. </p> <p>Does anyone have any ideas how to handle this condition? A coworker suggested using a semaphore while the validation code is running and a busy loop in the save code to wait until the semaphore unlocks -- but I'd like to avoid using any sort of busy loop in my code.</p>
<p>Use the semaphore (let's call it StillNeedsValidating). if the SaveForm function sees the StillNeedsValidating semaphore is up, have it activate a second semaphore of its own (which I'll call FormNeedsSaving here) and return. When the validation function finishes, if the FormNeedsSaving semaphore is up, it calls the SaveForm function on its own.</p> <p>In jankcode;</p> <pre><code>function UserInputChanged(control) { StillNeedsValidating = true; // do validation StillNeedsValidating = false; if (FormNeedsSaving) saveForm(); } function SaveForm() { if (StillNeedsValidating) { FormNeedsSaving=true; return; } // call web service to save value FormNeedsSaving = false; } </code></pre>
Suggest a good PHP wiki engine <p>I am looking for a small wiki engine that is easy to embed into an existing PHP application. Or perhaps a set of libraries to handle all the typical wiki functions.</p> <p>Currently I am using <a href="http://erfurtwiki.sourceforge.net/">ErfurtWiki</a>, but it is starting to show its age. It hasn't been updated since 2005, and several of the pages on sourceforge appear to have been <a href="http://erfurtwiki.sourceforge.net/MailingList">hacked</a>.</p> <p>I will be including it with a GPLv2 application so a GPL compatible license is important.</p> <p>Edit:</p> <p>To update, mostly I am just looking for text formatting/parser functionality. I want to deal with the storage, security, rev history, etc on my own.</p>
<p>I highly recommend <a href="http://www.mediawiki.org/wiki/MediaWiki">MediaWiki</a>, the wiki engine that runs wikipedia.</p> <p>EDIT: As per your comment, MediaWiki is highly embeddable. I've integrated it in numerous projects over the years.</p>
Warnings using format strings with sprintf() in C++ <p>Compiling this lines</p> <pre><code> long int sz; char tmpret[128]; //take substring of c, translate in c string, convert to int, //and multiply with 1024 sz=atoi(c.substr(0,pos).c_str())*1024; snprintf(tmpret,128,"%l",sz); </code></pre> <p>I read two warning on snprintf line:</p> <pre><code> warning: conversion lacks type at end of format warning: too many arguments for format </code></pre> <p>Why? The type is specified (long int sz, and %l in snprintf) and the argument in snprintf is only one. Can anybody help me? Thanks.</p>
<p>Your format lacks type, because l is a "sizeof" modifier. Should be %ld </p>
Visual Studio 2008 sometimes won't open .aspx html markup <p>Every now and again I encounter a problem where Visual Studio Professional 2008 (SP1) refuses to open an aspx page. My site is in a Web Application Project. </p> <p>Double clicking on the aspx page in solution explorer just causes the tree view node with the code behind and .designer.cs to collapse and expand, it's almost as if VS thinks the file is already open, but it's definately not. </p> <p>I've also tried right-click + View Markup or View Designer but no joy. I also tried unloading/reloading the project in solution explorer but that doesn't solve the problem either, I actually have to close the whole solution then re-open again (which can take a while if there's lots of projects in the solution).</p> <p>This sometimes happens on just one or two files, others open without any problems. Anyone else seen this and know of any work arounds and cause?</p> <p>Cheers<br /> Kev</p>
<p>Yeah, I'm getting that with just one aspx file in a webproj. I can open it with notepad fine, no one else is having a problem with the file on their computer and it just started happening to me today. I am using SourceSafe if that matters. I tried closing and reopening VS.</p>
TimedRotatingFileHandler Changing File Name? <p>I am trying to implement the python logging handler called TimedRotatingFileHandler. </p> <p>When it rolls over to midnight it appends the current day in the form: "YYYY-MM-DD".</p> <pre><code>LOGGING_MSG_FORMAT = '%(name)-14s &gt; [%(levelname)s] [%(asctime)s] : %(message)s' LOGGING_DATE_FORMAT = '%Y-%m-%d %H:%M:%S' logging.basicConfig( level=logging.DEBUG, format=LOGGING_MSG_FORMAT, datefmt=LOGGING_DATE_FORMAT ) root_logger = logging.getLogger('') logger = logging.handlers.TimedRotatingFileHandler("C:\\logs\\Rotate_Test",'midnight',1) root_logger.addHandler(logger) while True: daemon_logger = logging.getLogger('TEST') daemon_logger.info("SDFKLDSKLFFJKLSDD") time.sleep(60) </code></pre> <p>The first log file created is called just "Rotate_Test" then once it rolls over to the next day it changes the file name to: "Rotate_Test.YYYY-MM-DD" Where YYYY-MM-DD is the current day.</p> <p>How can i change how it alters the filename? I googled and looked at the API and found pretty much nothing.</p>
<p>"How can i change how it alters the filename?"</p> <p>Since it isn't documented, I elected to read the source. This is what I concluded from reading the source of <code>logging/handlers.py</code></p> <pre><code>handler = logging.handlers.TimedRotatingFileHandler("C:\\isis_ops\\logs\\Rotate_Test",'midnight',1) handler.suffix = "%Y-%m-%d" # or anything else that strftime will allow root_logger.addHandler(handler) </code></pre> <p>The suffix is the formatting string.</p>
GUI App with Visual C++ Express Edition <p>What tool (preferably free) can be used with Visual C++ 2008 Express Edition to create Win32 GUI applications? As you know the Express Edition does not include a GUI resource editor.</p>
<p>It doesn't, but that doesn't stop you from creating a Win32 GUI app; you can still do this in code.</p> <p>If that's unappealing for you, just do a Google search for "win32 Resource Editor." There are a few available. Any tool that creates .rc files can be compiled into your C++ project.</p>
What is special about HashSet<T> in .NET 3.5? <p>Here's an interesting puzzle.</p> <p>I downloaded Snippet Compiler to try some stuff out, and wanted to write the following code:</p> <pre><code>using System; using System.Collections.Generic; public class MyClass { public static void RunSnippet() { HashSet&lt;int&gt; h = new HashSet&lt;int&gt;(); } } </code></pre> <p>But the above code doesn't compile. I get:</p> <blockquote> <p>"The type or namespace name 'HashSet' could not be found (are you missing a using directive or an assembly reference?)"</p> </blockquote> <p>Clearly I'm not. It seems it can't find HashSet, yet it finds other types in the Systems.Collections.Generic namespace (e.g. List, SortedDictionary).</p> <p>What's the explanation for this? Presumeably Snippet Compiler is just using the standard Framework compiler under the covers...</p> <p>I would be interested to know why this doesn't work.</p>
<p>is your reference use </p> <p>Namespace: System.Collections.Generic</p> <p>Assembly: System.Core (in System.Core.dll)</p> <p>version 3.5?</p>
How do I find the type of the object instance of the caller of the current function? <p>Currently I have the function CreateLog() for creating a a log4net Log with name after the constructing instance's class. Typically used as in:</p> <pre><code>class MessageReceiver { protected ILog Log = Util.CreateLog(); ... } </code></pre> <p>If we remove lots of error handling the implementation boils down to: [EDIT: Please read the longer version of CreateLog further on in this post.]</p> <pre><code>public ILog CreateLog() { System.Diagnostics.StackFrame stackFrame = new System.Diagnostics.StackFrame(1); System.Reflection.MethodBase method = stackFrame.GetMethod(); return CreateLogWithName(method.DeclaringType.FullName); } </code></pre> <p>Problem is that if we inheirit MessageReceiver into sub classes the log will still take its name from MessageReceiver since this is the declaring class of the method (constructor) which calls CreateLog.</p> <pre><code>class IMReceiver : MessageReceiver { ... } class EmailReceiver : MessageReceiver { ... } </code></pre> <p>Instances of both these classes would get Logs with name "MessageReceiver" while I would like them to be given names "IMReceiver" and "EmailReceiver".</p> <p>I know this can easily be done (and is done) by passing a reference to the object in creation when calling CreateLog since the GetType() method on object does what I want.</p> <p>There are some minor reasons to prefer not adding the parameter and personally I feel disturbed by not finding a solution with no extra argument.</p> <p>Is there anyone who can show me how to implement a zero argument CreateLog() that gets the name from the subclass and not the declaring class?</p> <p>EDIT:</p> <p>The CreateLog function does more than mentioned above. The reason for having one log per instance is to be able to differ between different instances in the logfile. This is enforced by the CreateLog/CreateLogWithName pair.</p> <p>Expanding on the functionality of CreateLog() to motivate its existence.</p> <pre><code>public ILog CreateLog() { System.Diagnostics.StackFrame stackFrame = new System.Diagnostics.StackFrame(1); System.Reflection.MethodBase method = stackFrame.GetMethod(); Type type = method.DeclaringType; if (method.IsStatic) { return CreateLogWithName(type.FullName); } else { return CreateLogWithName(type.FullName + "-" + GetAndInstanceCountFor(type)); } } </code></pre> <p>Also I prefer writing ILog Log = Util.CreateLog(); rather than copying in some long cryptic line from an other file whenever I write a new class. I am aware that the reflection used in Util.CreateLog is not guaranteed to work though - is System.Reflection.MethodBase.GetCurrentMethod() guaranteed to work?</p>
<p>Normally, <a href="http://msdn.microsoft.com/en-us/library/system.reflection.memberinfo.reflectedtype.aspx" rel="nofollow">MethodBase.ReflectedType</a> would have your info. But, according to MSDN <a href="http://msdn.microsoft.com/en-us/library/system.diagnostics.stackframe.getmethod.aspx" rel="nofollow">StackFrame.GetMethod</a>:</p> <blockquote>The method that is currently executing may be inherited from a base class, although it is called in a derived class. In this case, the ReflectedType property of the MethodBase object that is returned by GetMethod identifies the base class, not the derived class. </blockquote> <p>which means you're probably out of luck. </p>
Why use hashing to create pathnames for large collections of files? <p>I noticed a number of cases where an application or database stored collections of files/blobs using a has to determine the path and filename. I believe the intended outcome is a situation where the path never gets too deep, or the folders ever get too full - too many files (or folders) in a folder making for slower access. </p> <p>EDIT: Examples are often Digital libraries or repositories, though the simplest example I can think of (that can be installed in about 30s) is the <a href="http://zotero.org" rel="nofollow">Zotero document/citation database.</a> </p> <p>Why do this? </p> <p>EDIT: thanks Mat for the answer - does this technique of using a hash to create a file path have a name? Is it a <em>pattern</em>? I'd like to read more, but have failed to find anything in the <a href="http://portal.acm.org/portal.cfm" rel="nofollow">ACM Digital Library</a></p>
<h3>Hash/B:Tree</h3> <p>A hash has the advantage of being faster to look at when you're only going to use the "=" operator for searchs.</p> <p>If you're going to use things like "&lt;" or ">" or anything else than "=", you'll want to use a B:Tree because it will be able to do that kind of searchs.</p> <h3>Directory structure</h3> <p>If you have hundreds of thousands of files to store on a filesystem and you put them all in a single directory, you'll get to a point where the directory inode will grow so fat that it will takes minutes to add/remove a file from that directory, and you might even get to the point where the inode won't fit in memory, and you won't be able to add/remove or even touch the directory.</p> <p>You can be assured that for hashing method foo, foo("something") will always return the same thing, say, "grbezi". Now, you use part of that hash to store the file, say, in gr/be/something. Next time you need that file, you'll just have to compute the hash and it will be directly available. Plus, you gain the fact that with a good hash function, the distribution of hashes in the hash space is pretty good, and, for a large number of files, they will be evenly distributed inside the hierarchy, thus splitting the load.</p>
Simple protocol for remote process startup/shutdown <p>I'm looking for a simple protocol to control remote processes from one managing application. The remote processes will run on Windows and Linux (x86).</p> <p>Is there a simple protocol for managing remote processes, for which I could find daemons that run on both Windows and Linux?</p>
<p>I consider ssh to be the "Swiss-army knife" of remote administration. A custom script communicating over ssh can then do the process management. On Windows, I install ssh as part of <a href="http://www.cygwin.com/" rel="nofollow">Cygwin</a>.</p>
How to Create a Listener for WCF ServiceHost events when service is hosted under IIS? <p>I have a WCF service which will be hosted under IIS. Now I have some resources(Connections) that I create within service constructor. I need to free up those resources when IIS which is hosting the service shuts down or resets. These are not the resources that I will be clearing out every time client disconnects but they are application wide resources which will only free up when the service itself or IIS shuts down.</p> <p>I saw another post where someone mentioned that he has created a listener to capture the events of <code>ServiceHost</code>. Can someone help me with figuring out how to get a handle of the <code>ServiceHost</code> and capture the IIS reset or IIS shutdown event and free up my resources in WCF service?</p>
<p>You can use the IDisposable pattern with finalizer on the class that holds the resources.</p> <p>On unload of AppDomain, all objects are finalized and if the object that has reference to the resources (such connections) has a finalizer, the finalizer will be called and you can close / dispose the resources at that point.</p>
What is the Managed C++ equivalent to the C# using statement <p>How would one code the following C# code in Managed C++</p> <pre><code>void Foo() { using (SqlConnection con = new SqlConnection("connectionStringGoesHere")) { //do stuff } } </code></pre> <p><strong>Clarificaton:</strong> For managed objects.</p>
<p>Assuming you mean C++/CLI (not the old Managed C++), the following are your options:</p> <p>(1) Mimic a using-Block with using automatic / stackbased objects:</p> <pre><code>{ SqlConnection conn(connectionString); } </code></pre> <p>This will call the Destructor of the "conn" Object when the next enclosing block ends. Whether this is the enclosing function, or a block you manually add to limit scope doesn't matter.</p> <p>(2) Explicitly call "Dispose", i.e. destruct the object:</p> <pre><code>SqlConnection^ conn = nullptr; try { conn = gcnew SqlConnection(conntectionString); } finally { if (conn != nullptr) delete conn; } </code></pre> <p>The first one would be the direct replacement for "using". The second one is an option, typically you won't need to do unless you optionally pass the reference to somewhere else.</p>
How do I get rid of .. Replace(Replace(Replace(Replace(Replace( …? <p>I’m selecting data on an old database which has an abused status column. The status column has multiple pieces of information in it. Values are like ‘New Contact YYYY’, ‘Online YYYY’, ‘Updated YYYY’, ‘Withdrawn YYYY’, etc…. As you may have guessed, YYYY represents the year … which I need.</p> <p>In the past I’ve done something similar to </p> <pre><code>Rtrim( ltrim( Replace(Replace(Replace(Replace(Replace( … </code></pre> <p>Basically, replacing all text values with an empty string, so the only thing that still exists is the year. I can still do this, but I’m thinking this is ridiculous, and there’s got to be a better way.</p> <p>Does anybody know of a better way to do this?</p>
<p>If you simply want to extract a four digit year from the string, you could use PATINDEX</p> <pre><code>SELECT SUBSTRING(FieldName, PATINDEX('%[0-9][0-9][0-9][0-9]%', FieldName), 4) FROM TableName </code></pre>
xsl:for-each loop counter <p>How do I save the iterations that have occurred in an xsl:for-each? (variables in XSL are immutable)</p> <p>My goal is to find the MAX number of children for any node at a particular level.</p> <p>For example, I might want to print that there are no more than 2 Response nodes for any Question in this survey:</p> <pre><code>&lt;?xml version="1.0" encoding="ISO-8859-1"?&gt; &lt;?xml-stylesheet type="text/xsl" href="testing.xsl"?&gt; &lt;Survey&gt; &lt;Question&gt; &lt;Response text="Website" /&gt; &lt;Response text="Print Ad" /&gt; &lt;/Question&gt; &lt;Question&gt; &lt;Response text="Yes" /&gt; &lt;/Question&gt; &lt;/Survey&gt; &lt;xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform"&gt; &lt;xsl:output method="xml" version="1.0" encoding="UTF-8" indent="yes"/&gt; &lt;xsl:template match="/"&gt; &lt;html&gt; &lt;head&gt; &lt;/head&gt; &lt;body&gt; &lt;xsl:for-each select="Survey"&gt; The survey has &lt;xsl:value-of select="count(child::Question)"/&gt; questions. &lt;br /&gt; &lt;xsl:variable name="counter"&gt;0&lt;/xsl:variable&gt; &lt;xsl:for-each select="Question"&gt; &lt;!-- TODO: increment the counter ??????? --&gt; &lt;/xsl:for-each&gt; No more than &lt;xsl:value-of select="$counter"/&gt; responses were returned for any question. &lt;/xsl:for-each&gt; &lt;/body&gt; &lt;/html&gt; &lt;/xsl:template&gt; &lt;/xsl:stylesheet&gt; </code></pre>
<p>One doesn't "save the iterations that have occurred in an xsl:for-each" because <a href="http://conferences.idealliance.org/extreme/html/2006/Novatchev01/EML2006Novatchev01.html" rel="nofollow"><strong>XSLT is a functional language</strong></a> and variables are immutable.</p> <p><strong>The following transformation finds the wanted maximum:</strong></p> <pre> &lt;xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform"> &lt;xsl:output method="text"/> &lt;xsl:template match="/"> &lt;xsl:call-template name="maximum"> &lt;xsl:with-param name="pNodes" select="*/Question"/> &lt;/xsl:call-template> &lt;/xsl:template> &lt;xsl:template name="maximum"> &lt;xsl:param name="pNodes"/> &lt;xsl:variable name="vNumNodes" select="count($pNodes)"/> &lt;xsl:choose> &lt;xsl:when test="$vNumNodes = 1"> &lt;xsl:value-of select="count($pNodes[1]/Response)"/> &lt;/xsl:when> &lt;xsl:otherwise> &lt;xsl:variable name="vHalf" select="floor($vNumNodes div 2)"/> &lt;xsl:variable name="vMax1"> &lt;xsl:call-template name="maximum"> &lt;xsl:with-param name="pNodes" select="$pNodes[not(position() > $vHalf)]"/> &lt;/xsl:call-template> &lt;/xsl:variable> &lt;xsl:variable name="vMax2"> &lt;xsl:call-template name="maximum"> &lt;xsl:with-param name="pNodes" select="$pNodes[position() > $vHalf]"/> &lt;/xsl:call-template> &lt;/xsl:variable> &lt;xsl:value-of select= "$vMax1*($vMax1 >= $vMax2) + $vMax2*($vMax2 > $vMax1)"/> &lt;/xsl:otherwise> &lt;/xsl:choose> &lt;/xsl:template> &lt;/xsl:stylesheet> </pre> <p>When applied on the provided XML document:</p> <pre> &lt;Survey> &lt;Question> &lt;Response text="Website" /> &lt;Response text="Print Ad" /> &lt;/Question> &lt;Question> &lt;Response text="Yes" /> &lt;/Question> &lt;/Survey> </pre> <p>the wanted result is produced:</p> <p><strong>2</strong></p> <p><strong>Do note the following</strong>: <em>The template named</em> "<code>maximum</code>" calls itself recursively <em>and implements</em> the <a href="http://en.wikipedia.org/wiki/Divide_and_conquer_algorithm" rel="nofollow"><strong>DVC (Divide and Conquer principle)</strong></a> <em>to minimize the recursion stack depth</em>. The list of nodes is split into two, the maximums of the two lists are calculated (recursively) and the bigger of the two is returned.</p>
How do I render a partial of a different format in Rails? <p>I'm trying to generate a JSON response that includes some HTML. Thus, I have <code>/app/views/foo/bar.json.erb</code>:</p> <pre><code>{ someKey: 'some value', someHTML: "&lt;%= h render(:partial =&gt; '/foo/baz') -%&gt;" } </code></pre> <p>I want it to render <code>/app/views/foo/_baz.html.erb</code>, but it will only render <code>/app/views/foo/_baz.json.erb</code>. Passing <code>:format =&gt; 'html'</code> doesn't help.</p>
<p>Beginning with Rails 3.2.3, when calling render :partial use </p> <pre><code>:formats =&gt; [:html] </code></pre> <p>instead of</p> <pre><code>:format =&gt; 'html' </code></pre>
Extracting individual digits from a float <p>I have been banging my head on this one all day. The C++ project I am currently working on has a requirement to display an editable value. The currently selected digit displays the incremented value above and decremented value below for said digit. It is useful to be able to reference the editable value as both a number and collection of digits. What would be awesome is if there was some indexable form of a floating point number, but I have been unable to find such a solution. I am throwing this question out there to see if there is something obvious I am missing or if I should just roll my own.</p> <p><hr /></p> <p>Thanks for the advice! I was hoping for a solution that wouldn't convert from float -> string -> int, but I <em>think</em> that is the best way to get away from floating point quantization issues. I ended up going with boost::format and just referencing the individual characters of the string. I can't see that being a huge performance difference compared to using combinations of modf and fmod to attempt to get a digit out of a float (It probably does just that behind the scenes, only more robustly than my implementation). </p>
<p>Internal representation of the float point numbers aren't like was you see. You can only cast to a stirng.</p> <p>To cast, do this:</p> <pre><code>char string[99]; sprintf(string,"%f",floatValue); </code></pre> <p>Or see this : <a href="http://www.parashift.com/c++-faq-lite/misc-technical-issues.html#faq-39.1">http://www.parashift.com/c++-faq-lite/misc-technical-issues.html#faq-39.1</a></p> <p>The wikipedia article can explain more on the representation: <a href="http://en.wikipedia.org/wiki/Floating_point">http://en.wikipedia.org/wiki/Floating_point</a></p>
Unable to commit to Subversion <p>I have a client who had to rebuild his automated build server. He checked out his project folder from my subversion server but is now no longer able to commit - he gets this error:</p> <pre><code>Error: Commit failed (details follow): Error: Cannot write to the prototype revision file of transaction '551-1' because a Error: previous representation is currently being written by another process Finished!: </code></pre> <p>I have searched Google but although this error has been often reported there is no clear explanation - does anyone on StackOverflow have a solution?</p> <p>UPDATE: Nobody else commits to that repository, so it was not a transaction stuck (at least not from another user). In the end we found that permissions were not set correctly. Not that you would know it from this message, but that fixed the problem.</p>
<p>You can clear this error w/out a reboot:</p> <ol> <li><p>Identify (or create) a directory in the root SVN repository that was not a part of the failed commit.</p></li> <li><p>Create a new file in the directory from step 1.</p></li> <li><p>Commit the new file (and directory if created in step 1). Because the file is new, it doesn't conflict w/the previous commit and can update the revision # on the server. </p></li> <li><p>Commit the original files/directories.</p></li> <li><p>Delete the new file (and directory if created in step 1).</p></li> <li><p>Commit the entire tree.</p></li> </ol> <p>**Steps 5 &amp; 6 aren't required, but I like to keep my repository tidy... </p> <p>I get this error a lot b/c SVN frequently conks out in the middle of committing my large files, which in turn causes subsequent commits to try to write to the revision that was interrupted.</p>
MySQL/PHP - escaping characters that may slow my database down (or make it perform unexpectedly) <p>I run all my integers through a <code>(int)Integer</code> to make them safe to use in my query strings.</p> <p>I also run my strings through this function code:-</p> <pre><code>if(!get_magic_quotes_gpc()) { $string = mysql_real_escape_string($string); } $pattern = array("\\'", "\\\"", "\\\\", "\\0"); $replace = array("", "", "", ""); if(preg_match("/[\\\\'\"\\0]/", str_replace($pattern, $replace, $string))) $string = addslashes($string); $cleanedString = str_replace('%','',$string); </code></pre> <p>I obviously return the $cleanedString variable. Now I replace the % character because it is a wildcard to mySQL and it could potentially slow down my queries (or make them return incorrect data) if the user inserted them. Are there any other special characters for mySQL I should be concerned about? </p> <p>On a second note, is there anything wrong or redundant about my search and replace after the <code>mysql_real_escape_string</code>? I got it from a website when I was first starting out and (if I remember correctly) it said you had to use this search/replace in addition to the escape string. It looks like it's trying to remove any previously escaped injection characters?</p>
<p>Okay I have several comments:</p> <ul> <li><p>The magic quoting feature is <a href="http://php.net/manual/en/security.magicquotes.php" rel="nofollow">deprecated</a>, your PHP environment should never enable magic quotes. So checking for it should be unnecessary, unless you're designing code that may be be deployed into other customers' environments who have (inadvisedly) enabled magic quotes. </p></li> <li><p>The regular expression in your <code>preg_match()</code> is incorrect if you're searching for sequences of characters. A regular expression like <code>[xyz]</code> matches any <em>one</em> of the single characters x, y, or z. It does not match the string xy or yz. Anyway, this is academic because I don't think you need to search or replace special characters this way at all.</p></li> <li><p><code>mysql_real_escape_string()</code> is adequate to escape string literals that you intend to interpolate inside quotes in SQL strings. No need to do string substitution for other quotes, backslashes, etc.</p></li> <li><p><code>%</code> and <code>_</code> are wildcards in SQL <em>only</em> when using pattern-matching with <code>LIKE</code> expressions. These characters have no meaning if you're just comparing with equality or inequality operators or regexps. Even if you are using <code>LIKE</code> expressions, there's no need to escape these characters for the sake of defense against SQL injection. It's up to you if you want to treat them as literal characters (in which case escape them with a backslash) or wildcards in a <code>LIKE</code> expression (in which case just leave them in).</p></li> <li><p>All of the above applies when you're interpolating PHP variables into SQL expressions in place of literal string values. Escaping is not necessary at all if you use <a href="http://php.net/manual/en/mysqli-stmt.bind-param.php" rel="nofollow">bound query parameters</a> instead of interpolating. Bound parameters are not available in the plain "mysql" API, but only in the "mysqli" API.</p></li> <li><p>Another case is where you interpolate PHP variables in place of SQL table names, column names, or other SQL syntax. You can't use bound parameters in such cases; bound parameters <em>only</em> take the place of string literals. If you need to make the column name dynamic (for example to <code>ORDER BY</code> a column of the user's preference), you should <a href="http://stackoverflow.com/questions/214309/do-different-databases-use-different-name-quote#214344">delimit the column name</a> with back-quotes (in MySQL) or square brackets (Microsoft) or double-quotes (other standard SQL).</p></li> </ul> <p>So I would say your code could be reduced simply to the following:</p> <pre><code>$quotedString = mysql_real_escape_string($string); </code></pre> <p>That's <em>if</em> you are going to use the string for interpolation; if you're going to use it as a bound parameter value, it's even simpler:</p> <pre><code>$paramString = $string; </code></pre>
How Can I Create Rounded Rectangle Buttons in WM6? <p>Yes, like those pretty buttons on the iPhone. ;)</p> <p>I've been searching and reading for days now and everytime I find something that will get me close (like CreateRoundRectRgn), it blows up because Windows Mobile 6 GDI+ doesn't support it.</p> <p>I can do the whole owner draw thing and such. But how do I curve those hard corners and reshape a button? :/</p> <p>Note Tools available: Native Win32 only (no MFC)</p> <hr> <p>That thought has occured to me, but it leaves two issues:</p> <p>1) Won't the bitmap with rounded edges still leave the corners of the button visible.</p> <p>2) Bitmaps are great for fixed screen size. But having a variety of resolutions, my goal is to dynamically create the button bitmap in memory at run-time and use it that way.</p> <p>I've got it working with square buttons. Yet I have seen rounded edge buttons used by other software. There <strong><em>must</em></strong> be a way to reshape buttons.</p>
<p>Getting pretty buttons like that is typically done by doing a complete owner-drawn button and drawing an image that a graphic designer created to it rather than letting GDI do any of the control painting. You simply need an image for "up" and an image for "pressed". You can manually draw in the focus or use yet another image with a ROP mask to draw it on the button as well. To get the nice "rounded" effects, you simply create the image with a background color that you then use as a transparency color.</p> <p>Tee scaling issue is somewhat unique to WinMo, since iPhone really has only one resolution. If you need to target different resolution WinMo devices you can do one of 2 things (which you use depends on the images you're using). Eitehr just draw the image scaled, or include different size versions of the images and decide at runtime which to use based on screen resolution.</p>
Yet Another Divs vs Tables issue: Forms <p>[Meta-note:] I was browsing the question page, getting really tired of "DIVS vs Tables" "When to use tables vs DIVS" "Are Divs better than Tables" "Tables versus CSS" and all the questions that ask <em>THE SAME THING OMG PEOPLE</em> but I would like to see all the ways people tackle the translation of the canonical example of "why you should give up and use tables":</p> <pre><code>&lt;table&gt; &lt;tr&gt; &lt;td&gt; Name &lt;/td&gt; &lt;td&gt; &lt;input&gt; &lt;/td&gt; &lt;/tr&gt; &lt;tr&gt; &lt;td&gt; Social Security Number &lt;/td&gt; &lt;td&gt; &lt;input&gt; &lt;/td&gt; &lt;/tr&gt; &lt;/table&gt; </code></pre> <p><b> Question: </b> How to best (semantically, simply, robustly, fluidly, portably) implement the above without tables. For starters, I guess a naive implementation uses a fixed column width for the first column, but that can have iffy results for dynamically generated content. Including strengths/weaknesses of your approach in the answer would be nice.</p> <p>P.S. Another one I wonder about a lot is vertical centering but the hack for that is covered pretty well at <a href="http://www.jakpsatweb.cz/css/css-vertical-center-solution.html">jakpsatweb.cz</a></p> <p>EDIT: scunlife brings up a good example of why I didn't think out the problem that carefully. Tables can align multiple columns simultaneously. The Question still stands (I'd like to see different CSS techniques used for alignment/layout) - although solutions that can handle his? more involved example definitely are preferred.</p>
<p>What I usually do is :</p> <pre><code>&lt;form&gt; &lt;label for="param_1"&gt;Param 1&lt;/label&gt; &lt;input id="param_1" name="param_1"&gt;&lt;br /&gt; &lt;label for="param_2"&gt;Param 2&lt;/label&gt; &lt;input id="param_2" name="param_2"&gt;&lt;br /&gt; &lt;/form&gt; </code></pre> <p>and in a CSS :</p> <pre><code>label,input { display: block; float: left; margin-bottom: 1ex; } input { width: 20em; } label { text-align: right; width: 15em; padding-right: 2em; } br { clear: left; } </code></pre> <p>Of course, you'll have to define the width according to your actual data :-)</p> <ul> <li>First, give label and input <code>display: block</code>, so that it can be assigned a size and be lined up.</li> <li>They both get <code>float: left</code> because Explorer does things a bit differently</li> <li>Format the label nicely</li> <li>hack the <code>br</code> so that there's a <code>clear: left</code> somewhere, and I remember that putting it on the label didn't work on some browser.</li> </ul> <p>Plus, with the <code>br</code> you get a nice formatting even if the browser does not support CSS :-)</p>
Javascript form validation <p>I'm trying to figure out what would be the simplest way to validate required fields without having to do an if statement for each element's name. Perhaps just with a loop and verify its class.</p> <p>What I'm trying to accomplish is to check only the ones that have the class name as "required"</p> <pre><code>&lt;input name="a1" class="required" type="text" /&gt; &lt;input name="a2" class="" type="text" /&gt; &lt;input name="a3" class="required" type="text" /&gt; </code></pre> <p>Thanks</p>
<p>I'm not at all against the libraries suggested by others, but I thought that you may want some samples of how you could do it on your own, I hope it helps.</p> <p>This should work:</p> <pre><code>function validate() { var inputs = document.getElementsByTagName("input"); for (inputName in inputs) { if (inputs[inputName].className == 'required' &amp;&amp; inputs[inputName].value.length == 0) { inputs[inputName].focus(); return false; } } return true; } </code></pre> <p>Also lets say your inputs are in a form named "theForm":</p> <pre><code>function validate() { for (var i = 0; i &lt; theForm.elements.length; i++) { if (theForm.elements[i].className == "required" &amp;&amp; theForm.elements[i].value.length == 0) { theForm.elements[i].focus(); return false; } } return true; } </code></pre> <p>Of course you would trim the value and/or add the appropriate validation logic for the application, but I'm sure you can get the idea from the sample. </p> <p>You can also store arbitrary data on the input itself and read it using the <code>getAttribute()</code> method on the element. For example you could have this element in your html (regex requires a 3 digit number): </p> <pre><code>&lt;input name="a1" validate="true" regex="[0-9]{3}" type="text" /&gt; </code></pre> <p>you could use this method to run the regex in the validation routine.</p> <pre><code>function validate() { for (var i = 0; i &lt; theForm.elements.length; i++) { var elem = theForm.elements[i]; if (elem.getAttribute("validate") == "true") { if (!elem.value.match(elem.getAttribute("regex"))) { elem.select(); return false; } } } return true; } </code></pre> <p>Hope this helps.</p>
How can I add sessions to my Perl web app? <p>I want to maintain state in my Perl web app. How can I do this effectively? I looked at CGI::Session but it says that it doesn't work well with UTF-8 pages, which is a requirement. I'd also like to be able to pass some basic information to another Java application running on the Glassfish app server, so people aren't forced to login to both apps, for example. How can all this be managed?</p>
<p>The basics of sessions are that you need a place to hold the session data (the store) and a way to store and retrieve the session data. While some frameworks call that The State, it really boils down to having a session key (or session ID) and passing it back to your app via either a cookie or a URL parameter.</p> <p>Your store can be anything that can hold the data for you. Some examples are: a flat file, a dbm file, a DBMS,or an in-memory cache of some type.</p> <p>The most common implementation, which is used by CGI::session and Apache::Session is to have three fields in each record inside the store: session_id,session_data, expires_time.</p> <p>The session modules on the CPAN take care of loading your session at the beginning of the request, and storing it back at the end. </p>
How do I load arbitrary data from a url PHP? <p>This question is simple. What function would I use in a PHP script to load data from a URL into a string?</p>
<p>I think you are looking for</p> <pre><code>$url_data = file_get_contents("http://example.com/examplefile.txt"); </code></pre>
HTML over flash without stopping interaction with flash <p>I have a html div layered on top of an interactive flash movie, but when the mouse moves over the div, it can't interact with the flash (the view changes as the mouse moves or is clicked). Is there a way to have the flash recieve the mouse movements and clicks but leaving the html visible?</p> <p>I can't modify the flash SWF file.</p> <p><strong>Edit:</strong> To make it clearer, this is an layer of information sitting on top of Google Street View (flash), the trouble is that I can't move the street view around where the layer overlaps.</p>
<p>Try something like this:</p> <pre><code>&lt;object&gt; &lt;param name="wmode" value="transparent" /&gt; &lt;embed src="example.swf" wmode="transparent"&gt;&lt;/embed&gt; &lt;/object&gt; </code></pre> <p>The main things to note are the <code>&lt;param /&gt;</code> tag with the transparent attribute, and the <code>wmode="transparent"</code> in the embed tag. You'll also need to run the following javascript code to make this work across all browsers:</p> <pre><code>theObjects = document.getElementsByTagName("object"); for (var i = 0; i &lt; theObjects.length; i++) { theObjects[i].outerHTML = theObjects[i].outerHTML; } </code></pre> <p>This code should be run when the document is loaded. The site I got this code from claims that it must be run from an external file in order to work (although I haven't tested that).</p> <p>I got this answer from here, where you can get more detail and a working example:<br /> <a href="http://www.cssplay.co.uk/menus/flyout_flash.html" rel="nofollow">http://www.cssplay.co.uk/menus/flyout_flash.html</a></p>
T-SQL Query Optimization <p>I'm working on some upgrades to an internal web analytics system we provide for our clients (in the absence of a preferred vendor or Google Analytics), and I'm working on the following query:</p> <pre><code>select path as EntryPage, count(Path) as [Count] from ( /* Sub-query 1 */ select pv2.path from pageviews pv2 inner join ( /* Sub-query 2 */ select pv1.sessionid, min(pv1.created) as created from pageviews pv1 inner join Sessions s1 on pv1.SessionID = s1.SessionID inner join Visitors v1 on s1.VisitorID = v1.VisitorID where pv1.Domain = isnull(@Domain, pv1.Domain) and v1.Campaign = @Campaign group by pv1.sessionid ) t1 on pv2.sessionid = t1.sessionid and pv2.created = t1.created ) t2 group by Path; </code></pre> <p>I've tested this query with 2 million rows in the PageViews table and it takes about 20 seconds to run. I'm noticing a clustered index scan twice in the execution plan, both times it hits the PageViews table. There is a clustered index on the Created column in that table.</p> <p>The problem is that in both cases it appears to iterate over all 2 million rows, which I believe is the performance bottleneck. Is there anything I can do to prevent this, or am I pretty much maxed out as far as optimization goes?</p> <p>For reference, the purpose of the query is to find the first page view for each session.</p> <p><strong>EDIT:</strong> After much frustration, despite the help received here, I could not make this query work. Therefore, I decided to simply store a reference to the entry page (and now exit page) in the sessions table, which allows me to do the following:</p> <pre><code>select pv.Path, count(*) from PageViews pv inner join Sessions s on pv.SessionID = s.SessionID and pv.PageViewID = s.ExitPage inner join Visitors v on s.VisitorID = v.VisitorID where ( @Domain is null or pv.Domain = @Domain ) and v.Campaign = @Campaign group by pv.Path; </code></pre> <p>This query runs in 3 seconds or less. Now I either have to update the entry/exit page in real time as the page views are recorded (the optimal solution) or run a batch update at some interval. Either way, it solves the problem, but not like I'd intended. </p> <p>Edit Edit: Adding a missing index (after cleaning up from last night) reduced the query to mere milliseconds). Woo hoo!</p>
<p>For starters,</p> <pre><code> where pv1.Domain = isnull(@Domain, pv1.Domain) </code></pre> <p>won't SARG. You can't optimize a match on a function, as I remember.</p>
Does Javascript fire an event for unhandled/uncaught exceptions? <p>I'm looking to log unhandled javascript exceptions. Is there an event that fires when an exception isn't caught? I'm looking to catch the exceptions before they cause javascript errors in the browser, but I'd rather not run my entire application inside of a try/catch. Any help would be appreciated. Thanks!</p> <p>Update: tvanfosson pointed out onerror as a possibility. It is not part of a spec and is only available in IE or Gecko based browsers.</p> <p>For more information - <a href="http://books.google.com/books?id=tKszhx-XkzYC&amp;pg=PA386&amp;lpg=PA386&amp;dq=safari+onerror+javascript&amp;source=web&amp;ots=gQaGbpUnjG&amp;sig=iBCtOQs0aH_EAzSbWlGa9v5flyo#PPA387,M1">http://books.google.com/books?id=tKszhx-XkzYC&amp;pg=PA386&amp;lpg=PA386&amp;dq=safari+onerror+javascript&amp;source=web&amp;ots=gQaGbpUnjG&amp;sig=iBCtOQs0aH_EAzSbWlGa9v5flyo#PPA387,M1</a></p> <p>OnError Support Table - <a href="http://www.quirksmode.org/dom/events/error.html">http://www.quirksmode.org/dom/events/error.html</a></p> <p>Mozilla's documentation - <a href="https://developer.mozilla.org/en/DOM/window.onerror">https://developer.mozilla.org/en/DOM/window.onerror</a></p> <p>WebKit Bug Report - <a href="https://bugs.webkit.org/show_bug.cgi?id=8519">https://bugs.webkit.org/show_bug.cgi?id=8519</a></p>
<p>Check out this Fiddle:</p> <p><a href="http://jsfiddle.net/xYsRA/1/">http://jsfiddle.net/xYsRA/1/</a></p> <pre><code>window.onerror = function (msg, url, line) { console.log("Caught[via window.onerror]: '" + msg + "' from " + url + ":" + line); return true; // same as preventDefault }; window.addEventListener('error', function (evt) { console.log("Caught[via 'error' event]: '" + evt.message + "' from " + evt.filename + ":" + evt.lineno); console.log(evt); // has srcElement / target / etc evt.preventDefault(); }); throw new Error("Hewwo world. I crash you!!!"); throw new Error("Hewwo world. I can only crash you once... :("); </code></pre> <p>Which prints:</p> <pre>Caught[via window.onerror]: 'Uncaught Error: Hewwo world. I crash you!!!' from http://fiddle.jshell.net/xYsRA/1/show/:32 fiddle.jshell.net:21 Caught[via 'error' event]: 'Uncaught Error: Hewwo world. I crash you!!!' from http://fiddle.jshell.net/xYsRA/1/show/:32 fiddle.jshell.net:26 ErrorEvent {lineno: 32, filename: "http://fiddle.jshell.net/xYsRA/1/show/", message: "Uncaught Error: Hewwo world. I crash you!!!", clipboardData: undefined, cancelBubble: false…} fiddle.jshell.net:27\ </pre> <p>Notes:</p> <ul> <li><p>If you remove the "return true" / "evt.preventDefault()" lines, then after the error is logged, it will print on the JS console in the normal way.</p></li> <li><p>Contrary to statements made above, window.onerror worked in all the browsers I tested. However, the addEventListener method is probably better anyways and provides richer semantics.</p></li> </ul>
How do I remove minimize and maximize from a resizable window in WPF? <p>WPF doesn't provide the ability to have a window that allows resize but doesn't have maximize or minimize buttons. I'd like to able to make such a window so I can have resizable dialog boxes.</p> <p>I'm aware the solution will mean using pinvoke but I'm not sure what to call and how. A search of pinvoke.net didn't turn up any thing that jumped out at me as what I needed, mainly I'm sure because Windows Forms does provide the <code>CanMinimize</code> and <code>CanMaximize</code> properties on its windows.</p> <p>Could someone point me towards or provide code (C# preferred) on how to do this?</p>
<p>I've stolen some code I found on the MSDN forums and made an extension method on the Window class, like this:</p> <pre><code>internal static class WindowExtensions { // from winuser.h private const int GWL_STYLE = -16, WS_MAXIMIZEBOX = 0x10000, WS_MINIMIZEBOX = 0x20000; [DllImport("user32.dll")] extern private static int GetWindowLong(IntPtr hwnd, int index); [DllImport("user32.dll")] extern private static int SetWindowLong(IntPtr hwnd, int index, int value); internal static void HideMinimizeAndMaximizeButtons(this Window window) { IntPtr hwnd = new System.Windows.Interop.WindowInteropHelper(window).Handle; var currentStyle = GetWindowLong(hwnd, GWL_STYLE); SetWindowLong(hwnd, GWL_STYLE, (currentStyle &amp; ~WS_MAXIMIZEBOX &amp; ~WS_MINIMIZEBOX)); } } </code></pre> <p>The only other thing to remember is that for some reason this doesn't work from a window's constructor. I got around that by chucking this into the constructor:</p> <pre><code>this.SourceInitialized += (x, y) =&gt; { this.HideMinimizeAndMaximizeButtons(); }; </code></pre> <p>Hope this helps!</p>
What is the best approach for applying styles to massive amounts of items? <p>In my LOB apps I usually wind up with containers that contain a bunch of different textblocks and textboxes for users to enter data. Normally I need to apply a certain margin or vertical/horizontal alignment to each control.</p> <p>Let's say I have Grid on my form that looks like this (a lot of markup was eliminated for brevity):</p> <pre><code>&lt;Grid&gt; &lt;Grid.ColumnDefinitions.../&gt; &lt;Grid.RowDefinitions.../&gt; &lt;TextBlock Text="MyLabel" /&gt; &lt;TextBox Text={Binding ...}/&gt; . ' &lt;!-- Repated a bunch more times along with all of the Grid.Row, Grid.Column definitions --&gt; &lt;/Grid&gt; </code></pre> <p>Now let's say I need every single item contained in my grid to have Margin="3,1" VerticalContentAlignment="Left" VerticalAlignment="Center". There are several ways to achieve this:</p> <ol> <li>Set the properties directly on each control - BAD!! Does not allow for skinning or centralizing styles.</li> <li>Create a Style with an x:Key="MyStyleName" and apply the style to each control. Better...Makes centralizing styles and skinning more manageable but still requires a ton of markup, and can become unwieldy.</li> <li>Create a global style (i.e. don't specify an x:Key and set the TargetType={x:Type TextBox/TextBlock} - BAD!! The problem with this is that it affects ALL controls in the app that don't explicity override this style. This can be bad for things like menus, grids, and other controls that use textblocks and textboxes.</li> <li>Create a style that targets the Grid and explicitely sets the dependecy propety values like <code>&lt;Setter Property="Frameworkelement.Margin" Value="3,1" /&gt;</code> Not bad...it correctly applies the style to every element in it's content, but also applies it directly to the Grid itself...not exactly what I want.</li> </ol> <p>So what approach do you take and why? What works the best?</p>
<p>You can put a "global" style into the <code>Resources</code> section of the grid, thus confining its impact. To re-use "global" styles in different locations, put them into a non-default resource dictionary and include it as <code>MergedDictionary</code>:</p> <p>in <code>Styles.xaml</code>:</p> <pre><code>&lt;ResourceDictionary xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"&gt; &lt;Style x:Key="{x:Type ...}"&gt; ... &lt;/Style&gt; &lt;/ResourceDictionary&gt; </code></pre> <p>in the form:</p> <pre><code>&lt;Grid&gt; &lt;Grid.ColumnDefinitions.../&gt; &lt;Grid.RowDefinitions.../&gt; &lt;Grid.Resources&gt; &lt;ResourceDictionary&gt; &lt;ResourceDictionary.MergedDictionaries&gt; &lt;ResourceDictionary Source="Styles.xaml" /&gt; &lt;/ResourceDictionary.MergedDictionaries&gt; &lt;!-- other resources here --&gt; &lt;/ResourceDictionary&gt; &lt;/Grid.Resources&gt; ... &lt;/Grid&gt; </code></pre>
Looking for an example of using Lucene.net with ASP.NET <p>How do you implement the search capabilities of Lucene.net in asp.net? If possible, please include links or example code.</p>
<p>There is a excellent blog series here:</p> <ol> <li><a href="https://web.archive.org/web/20131229052210/http://www.devatwork.nl/articles/lucenenet" rel="nofollow">Lucene.NET</a></li> <li><a href="https://web.archive.org/web/20131031102410/http://www.devatwork.nl/articles/lucenenet/introduction-to-lucenenet-lucenenet/" rel="nofollow">Introduction to Lucene</a></li> <li><a href="https://web.archive.org/web/20131031102255/http://www.devatwork.nl/articles/lucenenet/indexing-basics-lucenenet/" rel="nofollow">Indexing basics</a></li> <li><a href="https://web.archive.org/web/20131031102439/http://www.devatwork.nl/articles/lucenenet/search-basics-lucenenet/" rel="nofollow">Search basics</a></li> <li><a href="https://web.archive.org/web/20131231031913/http://www.devatwork.nl/articles/lucenenet/alternatives-did-you-mean-lucenenet/" rel="nofollow">Alternatives ( did you mean …)</a></li> <li><a href="https://web.archive.org/web/20131031102405/http://www.devatwork.nl/articles/lucenenet/faceted-search-and-drill-down-lucenenet/" rel="nofollow">Faceted search / Drill down</a></li> <li><a href="https://web.archive.org/web/20131031102400/http://www.devatwork.nl/articles/lucenenet/class-reference-lucenenet/" rel="nofollow">Class reference</a></li> </ol> <p>I have also found another project called <a href="https://web.archive.org/web/20150428223648/http://blogs.planetcloud.co.uk/mygreatdiscovery/?tag=/lucenenet" rel="nofollow">SimpleLucene</a> which you can use to maintain your lucene indexes whenever you need to update or delete a document.</p>
Disadvantages of using void* pointers in C <p>There are many drawbacks to using <code>void *</code> in C (memory related, type related, efficiency wise ...). In spite of them we use them a lot for the flexibility they provide.</p> <p>List the disadvantages/drawbacks using <code>void *</code> (and preferred solution in C - if possible).</p> <p><strong>EDIT:</strong> please go through the follwoing link: <a href="http://attractivechaos.wordpress.com/2008/10/02/using-void-in-generic-c-programming-may-be-inefficient/" rel="nofollow">http://attractivechaos.wordpress.com/2008/10/02/using-void-in-generic-c-programming-may-be-inefficient/</a></p>
<p>There are no efficiency issues with void pointers. The only limitations with void pointers are:</p> <ul> <li>you cannot dereference void pointer for obvious reasons</li> <li><code>sizeof(void)</code> is illegal</li> <li>you cannot perform pointer arithmetics on void pointers</li> </ul> <p>However GCC assumes that <code>sizeof(void)</code> is 1 and allows pointer arithmetics on void pointers - <a href="http://gcc.gnu.org/onlinedocs/gcc-4.1.2/gcc/Pointer-Arith.html">see here</a></p>
Retrieve the uniqueidentifier key value for a record <p>in context of SQL Server 2005, I have a table for which the primary key is a uniqueidentifier (GUID), with a default value generated by the newid() function. I want to write a stored procedure that inserts a new record into the table. How do I get the record's PK value? for an identity-declared field, this is easy - I call scope_identity(). How should I proceed with guids?</p> <p>Thanks, Lucian</p>
<p><strong>Generating GUID before insertion introduces index fragmentation.</strong></p> <p>There is no need to declare the GUID prior insertion, </p> <p>I would recommend:</p> <ol> <li><p>Using NEWSEQUENTIALID default constraint to generate contiguous Guids. (this will eliminate index fragmentation - a well known issue with Guids as primary key).</p></li> <li><p>Use new OUTPUT clause (new in sql server 2005) which will enable you to get newly inserted GUID.</p></li> </ol> <p>Example below:</p> <pre><code>DECLARE @outputTblCustomer1 TABLE (CustomerID uniqueidentifier) -- Customer1 INSERT INTO dbo.Customer1 (CustomerNumber, LastName) OUTPUT INSERTED.CustomerID INTO @outputTblCustomer1 VALUES (-1, N'LastName') SELECT CustomerID FROM @outputTblCustomer1 -- Customer3 INSERT INTO dbo.Customer3 (CustomerNumber, LastName) VALUES (-1, N'LastName') SELECT SCOPE_IDENTITY() AS CustomerID </code></pre>
C# console applications all 16bit? <p>I was reading up about NTVDM.exe as I build a quick test console app and it crashed on a friends machine complaining about this EXE.</p> <p>As I understand it all DOS cmd windows (C# console apps included) run as 16bit not 32bit.</p> <p>Is this true? Does this mean all my works console app back office apps are running as 16bit rather than making the most of the 32bit available?</p> <p>What about Windows services? As I believe we wrote it as a console app then made it run as a windows service?</p> <p>Thanks</p>
<p>Any .NET app that is compiled for x86 will be 32-bit</p> <p>C# console apps aren't running in "real" dos - they run in a 32-bit or 64-bit environment - depending on your OS and .NET framework.</p>
MySQL - how to use index in WHERE x IN (<subquery>) <p>I'm using this query to get all employees of {clients with name starting with lowercase "a"}:</p> <pre><code>SELECT * FROM employees WHERE client_id IN (SELECT id FROM clients WHERE name LIKE 'a%') </code></pre> <p>Column <code>employees.client_id</code> is an int, with <code>INDEX client_id (index_id)</code>. The subquery should IMHO return a list of id-s, which is then used in the WHERE clause.</p> <p>When I <code>EXPLAIN</code> the query, the primary query uses no indexes (<code>type:ALL</code>). But when I <code>EXPLAIN</code> a list taken from the subquery (e.g. <code>SELECT ... WHERE client_id IN (121,184,501)</code>), the <code>EXPLAIN</code> switches to <code>type:range</code>, and this query gets faster by 50%.</p> <p>How can I make the query use the index for the data returned by subquery - or, is there a more efficient way of retrieving this data? (Retrieving the id-list to application server, joining it and sending a second query is even more expensive here).</p> <p>Thanks in advance.</p>
<pre><code>SELECT employees.* FROM employees, clients WHERE employees.client_id = clients.id AND clients.name LIKE 'a%'; </code></pre> <p>Should be more quicker, since the optimiser can choose the most efficient plan. In writing it your way with a sub-query, you're forcing it to do the steps in a certain order rather than letting it choose the optimal join order.</p> <p>As a general rule sub-queries should be avoided since they will typically be less performant than a join query (though there are certain circumstances where they are unavoidable)</p>
Firefox manipulation of saved form data <p>Is there a Firefox plugin for manipulating and deleting saved form data? In the browser there is only the option to delete all data.</p>
<p><a href="https://addons.mozilla.org/en-US/firefox/addon/12021" rel="nofollow">Form History Control</a> does what you want.</p>
Make C# algorithm more efficient <p>I have a C# method that projects the value of a number from an interval to a target interval.<br /> <strong>For example:</strong> we have an interval of -1000 and 9000 and a value of 5000; if we want to project this value to an interval of 0..100 we get 60.</p> <p>Here is the method: </p> <pre><code>/// &lt;summary&gt; /// Projects a value to an interval /// &lt;/summary&gt; /// &lt;param name="val"&gt;The value that needs to be projected&lt;/param&gt; /// &lt;param name="min"&gt;The minimum of the interval the value comes from&lt;/param&gt; /// &lt;param name="max"&gt;The maximum of the interval the value comes from&lt;/param&gt; /// &lt;param name="intervalTop"&gt;The minimum of the interval the value will /// be projected to&lt;/param&gt; /// &lt;param name="intervalBottom"&gt;The maximum of the interval the value will /// be projected to&lt;/param&gt; /// &lt;returns&gt;Projected value&lt;/returns&gt; public decimal ProjectValueToInterval(decimal val, decimal min, decimal max, decimal intervalBottom, decimal intervalTop) { decimal newMin = Math.Min(0, min); decimal valueIntervalSize = Math.Abs(max - newMin); decimal targetIntervalSize = Math.Abs(intervalTop - intervalBottom); decimal projectionUnit = targetIntervalSize / valueIntervalSize; return (val * projectionUnit) + Math.Abs((newMin * projectionUnit)); } </code></pre> <p>This method needs to be called for thousands of values.<br /> I was wondering if there is a more efficient way to do this in C#? If yes, what changes do you suggest?</p>
<p>Only thousands of values? Do you really need to optimise this further? I can't imagine it's actually a bottleneck at the moment. Have you profiled the app to check that this is really an issue?</p> <p>Given that the method is O(1), you're not going to make the most drastic kind of optimisation you normally aim at - improving the complexity.</p> <p>Having said that - when you call this thousands of times, do any of the values stay constant? For example, are you using the same min and max repeatedly? If so, you could create a class which takes those values in the constructors and precomputes what it can, then has a method taking the rest of the parameters. This will improve things slightly, but I go back to my original point - only worry about this if it's actually causing problems.</p>
What is the best method for formatting email when using System.Net.Mail <p>Hi I'm using <code>System.Net.Mail</code> to send some HTML formatted emails.</p> <p>What is the correct method for inserting css into the email message?</p> <p>I know I can apply formatting to each item, but I'ld rather use style sheets..</p> <p><strong>EDIT</strong> I should have mentioned that this is for an internal application, and I expect 99% of users to be using Outlook or other client, but never hotmail or gmail etc.</p>
<p>I've always found that strictly using <strong>HTML 3.0 compatible tags and formatting</strong> works best for all email readers and providers.</p> <p>nevertheless here is a <a href="http://www.alistapart.com/articles/cssemail" rel="nofollow"><strong>CSS in Email</strong> article</a> that may answer your question, you will find solutions to your css problems.</p>
Should I use decimal, float or double for this simple math result? <p>I'm doing some really simple math and saving the result to a MS SQL2008 DB.</p> <p>I'm <em>averaging</em> out the some numbers, which are byte values between 1&lt;->5. I wish to record probably 2 decimal places only. I don't care about rounding for the 2nd decimal place (eg. a 1.155 == 1.5 or 1.6 .. i'm not too phased).</p> <p>So .. should i store the average result as a float, decimal or double?</p> <p>When i check what LINQ returns, it can return all three values!</p> <p>Lastly, what would be the relevant SQL datatype field, also.</p> <p>cheers!</p>
<p>What you need is the DECIMAL datatype:</p> <pre><code>declare @val decimal(10,2) select @val = 10.155 select @val </code></pre> <p>When you input values, you can either rely on the built in rounding, or explicitly decide which rounding you want:</p> <pre><code>select val = round(10.155, 2, 0) -- rounded select val = round(10.155, 2, 1) -- truncated </code></pre> <p>Decimal (10,2) means that ten digits can be used, and that two of them are to be taken as being after the decimal point. i.e. The highest number that decimal(4,2) can contain is 99.99. Trying to set it to 100 will result in arithmetic overflow.</p>
import text file containing line breaks into excel <p>I have a plain text file looking like this:</p> <pre><code>"some text containing line breaks" </code></pre> <p>I'm trying to talk <code>excel 2004 (Mac, v.11.5)</code> into opening this file correctly. I'd expect to see only one cell (A1) containing all of the above (without the quotes)...</p> <p>But alas, I can't make it happen, because Excel seems to insist on using the CR's as row delimiters, even if I set the text qualifier to double quote. I was sort of hoping that Excel would understand that those line breaks are part of the value - they are embedded in double quotes which should qualify them as part of the value. So my Excel sheet has 5 rows, which is not what I want.</p> <p>I also tried this Applescript to no avail:</p> <pre><code>tell application "Microsoft Excel" activate open text file filename ¬ "Users:maximiliantyrtania:Desktop:linebreaks" data type delimited ¬ text qualifier text qualifier double quote ¬ field info {{1, text format}} ¬ origin Macintosh with tab end tell </code></pre> <p>If I could tell Excel to use a row delimiter other than CR (or LF), well, I'd be a happy camper, but excel seems to allow the change of the field delimiter only, not the row delimiter.</p> <p>Any pointers?</p> <p>Thanks,</p> <p>Max Excel's open</p>
<p>Looks like I just found the solution myself. I need to save the initial file as ".csv". Excel honors the line breaks properly with CSV files. Opening those via applescript works as well.</p> <p>Thanks again to those who responded.</p> <p>Max</p>
Can I create a dojox.data.XmlStore with a url pointing to a different port or server <p>In the following, I want to replace <code>/books.xml</code> with something like <code>http://server:port/books</code>. In essence the XmlStore to be served by some other server or port than the one serving this</p> <pre><code>&lt;div dojoType="dojox.data.XmlStore" url="/books.xml" jsId="fileStore_book" rootItem="book"&gt;&lt;/div&gt; &lt;div dojoType="dojox.grid.data.DojoData" jsId="model_fileStore_book" store="fileStore_book" query="{title:'*'}"&gt;&lt;/div&gt; &lt;div id="fileGrid_book" dojoType="dojox.Grid" model="model_fileStore_book" rowsPerPage="10" style="width: 400px; height: 300px;"&gt; &lt;script type="dojo/method"&gt;this.setStructure([{cells: [[{field: "isbn", name: "ISBN", width: 10}, {field: "author", name: "Author", width: 10}, {field: "title", name: "Title", width: 'auto'}]]}]);&lt;/script&gt; &lt;/div&gt; </code></pre>
<p>The data store is bound by "the same origin" restrictions like all data sources in web applications. You should either proxy the other server using your server, or consider alternative means of data access, e.g., JSONP, or the window-name transport.</p>
ASP.NET GridView "Client-Side Confirmation when Deleting" stopped working on ie - how come? <p>A few months ago, I have programmed an ASP.NET GridView with a custom "Delete" LinkButton and Client-Side JavaScript Confirmation according to this msdn article:</p> <p><a href="http://msdn.microsoft.com/en-us/library/bb428868.aspx" rel="nofollow">http://msdn.microsoft.com/en-us/library/bb428868.aspx</a> (published in April 2007)</p> <p>or e.g. <a href="http://stackoverflow.com/questions/218733/javascript-before-aspbuttonfield-click">http://stackoverflow.com/questions/218733/javascript-before-aspbuttonfield-click</a></p> <p>The code looks like this:</p> <pre><code>&lt;ItemTemplate&gt; &lt;asp:LinkButton ID="deleteLinkButton" runat="server" Text="Delete" OnCommand="deleteLinkButtonButton_Command" CommandName='&lt;%# Eval("id") %&gt;' OnClientClick='&lt;%# Eval("id", "return confirm(\"Delete Id {0}?\")") %&gt;' /&gt; &lt;/ItemTemplate&gt; </code></pre> <p>Surprisingly, "Cancel" doesn't work no more with my ie (Version: <code>6.0.2900.2180.xpsp_sp2_qfe.080814-1242</code>) - it always deletes the row. With Opera (Version 9.62) it still works as expeced and described in the msdn article. More surprisingly, on a fellow worker's machine with the same ie version, it still works ("Cancel" will not delete the row).</p> <p>The generated code looks like </p> <pre><code>&lt;a onclick="return confirm(...);" href="javascript:__doPostBack('...')"&gt; </code></pre> <p>As confirm(...) returns false on "Cancel", I expect the __doPostBack event in the href not to be fired. Are there any strange ie settings I accidentally might have changed? What else could be the cause of this weird behaviour? Or is this a "please reinstall WinXP" issue?</p>
<p>Try this :</p> <pre><code>&lt;asp:LinkButton ID="DeleteButton" runat="server" CausesValidation="False" CommandName="Delete" Text="Delete" OnClientClick="return confirm('Delete Id : '&lt;%# (string)Eval('id')%&gt;')" &gt; &lt;/asp:LinkButton&gt; </code></pre>
Is it possible to use GZIP compression on classic ASP pages? <p>We've got a classic ASP application that is putting out some very large reports, where the resulting HTML is several MBs. We've made a lot of progress in trimming this down by reducing extraneous HTML, but I'd like to know if there's any way to enable GZIP compression on these dynamic .asp pages. I'm sure compressing them would be an enormous benefit to the file size.</p> <p>All of the GZIP compression information I've seen only talks about supporting files or .aspx pages.</p> <p>Thanks.</p>
<p>Sure, that's just a matter of turning on compression in IIS. See this <a href="http://www.microsoft.com/technet/prodtechnol/WindowsServer2003/Library/IIS/25d2170b-09c0-45fd-8da4-898cf9a7d568.mspx?mfr=true" rel="nofollow">MSDN</a> page for example.</p>
Create empty C# event handlers automatically <p>It is not possible to fire an event in C# that has no handlers attached to it. So before each call it is necessary to check if the event is null.</p> <pre><code>if ( MyEvent != null ) { MyEvent( param1, param2 ); } </code></pre> <p>I would like to keep my code as clean as possible and get rid of those null checks. I don't think it will affect performance very much, at least not in my case.</p> <pre><code>MyEvent( param1, param2 ); </code></pre> <p>Right now I solve this by adding an empty inline handler to each event manually. This is error prone, since I need to remember to do that etc.</p> <pre><code>void Initialize() { MyEvent += new MyEvent( (p1,p2) =&gt; { } ); } </code></pre> <p>Is there a way to generate empty handlers for all events of a given class automatically using reflection and some CLR magic?</p>
<p>I saw this on another post and have shamelessly stolen it and used it in much of my code ever since:</p> <pre><code>public delegate void MyClickHandler(object sender, string myValue); public event MyClickHandler Click = delegate {}; // add empty delegate! //Let you do this: public void DoSomething() { Click(this, "foo"); } //Instead of this: public void DoSomething() { if (Click != null) // Unnecessary! Click(this, "foo"); } </code></pre> <p><strike>* If anyone knows the origin of this technique, please post it in the comments. I really do believe in the source getting due credit.</strike></p> <p>(<strong>Edit:</strong> I got it from this post <a href="http://stackoverflow.com/questions/9033/hidden-features-of-c#9282">Hidden Features of C#?</a>)</p>
How to delegate a method call to another thread? <p>I have the following problem: Multithreaded WPF application, Model View Presenter Implementation. Presenters and Views that belong together are created on a separate thread and get a separate Dispatcher. Now someone calls from another thread a method on the Presenter. I am intercepting the call, and now begins the problem: if the call comes from the same thread as the presenter, i want to proceed with the call, else invoke the call on the Dispatcherthread, so that i don't need to care about UI calls. I have already read about the use of SynchronizationContext, but that doesnt seem to work for me because if the calling thread is no UI thread i can't compare the 2 contexts. Whats a possible, working and elegant solution ?</p>
<pre><code>if( presenterDispatcherObject.CheckAccess() ) Doit(); else presenterDispatcherObject.BeginInvoke( DispatcherPriority.Normal, () =&gt; DoIt() ); </code></pre>
Java Cipher - AES Padding Problem <p>I am using a AES cipher with a 16 byte block size. </p> <p>If I try and encrypt a 16 byte string I have no problems, but any other length not a multiple of 16 is throwing an exception. </p> <p>I know with 3-DES you can specify a padding type as part of the algorithm and it's handled with no extra work (e.g. DES/CBC/PKCS5Padding), but is there a way to specify this with AES? </p> <p>Or do I need to pad the pytes manually to a multiple of 16, and then strip them when I decrypt? Here is an abbreviated code sample. </p> <pre><code>encrypt = Cipher.getInstance("AES", provider); encrypt.init(Cipher.ENCRYPT_MODE, key) ; byte[] encrypted = encrypt.doFinal(plainTxt.getBytes()) ; </code></pre> <p>Any and all replies appreciated! </p> <p>Thanks in advance, Ciarán</p>
<p>It should work exactly the same with AES, i.e. the padding mode has to be specified together with the cipher. Which padding modes are implemented depends on the provider and should be described in its documentation.</p> <p>According to the JCE documentation: <a href="http://java.sun.com/j2se/1.5.0/docs/guide/security/jce/JCERefGuide.html#AppA">http://java.sun.com/j2se/1.5.0/docs/guide/security/jce/JCERefGuide.html#AppA</a> standard padding modes like PKCS5Padding should be always supported (at least, that's how I interpret it).</p>
Python 3.0 - dict methods return views - why? <blockquote> <p>dict methods dict.keys(), dict.items() and dict.values() return “views” instead of lists. <a href="http://docs.python.org/dev/3.0/whatsnew//3.0.html">http://docs.python.org/dev/3.0/whatsnew//3.0.html</a></p> </blockquote> <p>First of all how is a view different from an iterator? Secondly, what is the benefit of this change? Is it just for performance reasons? </p> <p>It doesn't seem intuitive to me, i.e., I'm asking for a list of thing (give me all your keys) and I'm getting something else back. Will this confuse people?</p>
<p>You are effectively getting a list. It's just not a copy of the internal list, but something that acts as if it where a list but only represents the internal state.</p> <p>That's the same way it's implemented in Java (and probably many other languages/environments as well).</p> <p>The main reason is that for many use cases returning a completely detached list is unnecessary and wasteful. It would require copying the entire content (which may or many not be a lot).</p> <p>If you simply want to iterate over the keys then creating a new list is not necessary. And if you indeed need it as a separate list (as a copy) then you can easily create that list from the view.</p>
Unit Testing in web applications that use databases <p>I am building a web application that uses the database for Users, Security/roles, and to store content.</p> <p>It seems a little daunting to me to begin on the road of unit testing because I have to make sure my database has been initialized properly for my tests to run.</p> <p>What are common practices to help in this regard?</p> <p>i.e. while developing/testing, I might delete a user, but for my test to pass that user has to be in the database, along with his profile, security settings etc.</p> <p>I know I can create a setup script, something to recreat the databas etc. </p> <p><b>I don't want to end up spending my entire time maintaining my tests and ensuring my database is in sych</b></p> <p>Or is that the cost of Unit Testing/TDD?</p>
<p>The solution is Mocking. Mocks "replace" the connection. The unit under test will "connect" to the Mock and executes its statement. The Mock returns normal resultsets o.s.e.</p> <p>After the test, the mock can give you a list of all methods, that were called by the unit under test. <a href="http://www.easymock.org" rel="nofollow">Easymock.org</a></p> <p>As the other said: DB connection aren't a unit test. So drop it and do it local with Mocking objects</p>
Newbie: Visual Studio 2008 Standard Edition: How do I see more than "Reporting" project type? <p>I just bought a VS 2008 Standard license upgrade. (I was using the integrated shell for learning F# and express edition for c#. )</p> <p>I performed the install, re-booted, and when I click file->new->project ... all I get is the choice for "Reporting" project type under C#. IS there a way to expand the number of choices for the various project types?</p> <p>( I just uninstalled all things visual studio 2008 shell, express, etc... and the install went OK. )</p>
<p>You can install templates or save your project as a template.</p>
ASP.NET DropDownList AutoPostback Not Working - What Am I Missing? <p>I am attempting to get a DropDownList to AutoPostBack via an UpdatePanel when the selected item is changed. I'm going a little stir-crazy as to why this isn't working.</p> <p>Does anyone have any quick ideas?</p> <p>ASPX page:</p> <pre><code>&lt;asp:UpdatePanel ID="UpdatePanel1" runat="server" UpdateMode="Always" ChildrenAsTriggers="true" &gt; &lt;ContentTemplate&gt; &lt;asp:DropDownList ID="DropDownList1" runat="server" AutoPostBack="True" onselectedindexchanged="DropDownList1_SelectedIndexChanged"&gt; &lt;asp:ListItem&gt;item 1&lt;/asp:ListItem&gt; &lt;asp:ListItem&gt;item 2&lt;/asp:ListItem&gt; &lt;/asp:DropDownList&gt; &lt;/ContentTemplate&gt; &lt;/asp:UpdatePanel&gt; </code></pre> <p>Code-behind (I put a breakpoint on the string assignment to capture the postback):</p> <pre><code>protected void DropDownList1_SelectedIndexChanged(object sender, EventArgs e) { string s = ""; } </code></pre> <p><strong>Edit:</strong></p> <p><strong>OK, I have it working now. Very weird. All it took was a restart of Visual Studio. This is the kind of thing that frightens me as a developer ;) I think I've seen similar before, where VS gets "out of sync" wrt the assembly it's running.</strong></p> <p><strong>FYI I am running VS 2008 Web Developer Express.</strong></p> <p><strong>Thanks to those that answered.</strong></p>
<p>I was able to get it to work with what you posted. This is the code I used... Basically what you had but I am throwing an exception.</p> <pre><code> &lt;asp:ScriptManager ID="smMain" runat="server" /&gt; &lt;asp:UpdatePanel ID="UpdatePanel1" runat="server" UpdateMode="Always" ChildrenAsTriggers="true" &gt; &lt;ContentTemplate&gt; &lt;asp:DropDownList ID="DropDownList1" runat="server" AutoPostBack="True" onselectedindexchanged="DropDownList1_SelectedIndexChanged"&gt; &lt;asp:ListItem&gt;item 1&lt;/asp:ListItem&gt; &lt;asp:ListItem&gt;item 2&lt;/asp:ListItem&gt; &lt;/asp:DropDownList&gt; &lt;/ContentTemplate&gt; &lt;/asp:UpdatePanel&gt; protected void DropDownList1_SelectedIndexChanged(object sender, EventArgs e) { throw new NotImplementedException(); } </code></pre> <p>I tried a lot of variations to see if there was something off, but the exception was thrown every time. </p> <p>You might want to try the exception route to see if the postback is happening and this isn't a debugger issue. </p> <ul> <li><p>One issue might be with Vista and not running Visual Studios as administrator. I know that has a tendency to not allow debugging. </p></li> <li><p>Maybe the assembly you are running doesn't match the code? This might happen if you "View in Browswer" and then attach the debugger.</p></li> </ul>
Hide Comments in Code in Unix Environment <p>I work in a Unix environment with the typical Unix tools (emacs, vim, gvim, sunstudio, etc)</p> <p>My project has huge gross boilerplate comments on every method. It makes the files thousands of lines long, with a couple hundred lines of actual code. I may be exagerrating a bit but you get the idea. I am looking for a way when viewing these files to hide (not remove) all comments so I can quickly go through the code. C++ comments '//' only.</p>
<p>It all depends on which editor you use. In vim, you can enable folding with :</p> <pre><code>set foldenable </code></pre> <p>Then, you'll be able to use different of folding methods, for mainstream languages, you can set :</p> <pre><code>set foldmethod=syntax </code></pre> <p>which will enable syntax folding.</p> <p>There are half a dozen folding methods, I think the best would be to read</p> <pre><code>help folding </code></pre> <p>which should answer everything.</p>
How do I fix a .NET Webservice timeout causing a UnsupportedMediaException in a Java client? <p>I currently have a .net SOAP web service with a timeout on the request that I set using</p> <pre><code>Server.ScriptTimeout = TIME_OUT; </code></pre> <p>I then have java client calling said web service. However when the timeout is reached I get this exception:</p> <pre><code>Exception in thread "Thread-9" com.sun.xml.ws.server.UnsupportedMediaException: Unsupported Content-Type: text/html; charset=utf-8 Supported ones are: [text/xml] </code></pre> <p>What is happening is that the web service returns an html error page with the http timeout code (503 I think?), which my Java code (generated using WSDLimport) doesn't expect.</p> <p>Now I could catch the error UnsupportedMediaException on the client and attempt to translate it into something more meaningful, but I would prefer to send out a more specific timeout exception on the web service side. Is there anyway in a .net web service to send out a better exception when a timeout occurs, or any other way to handle this situation better?</p> <p><strong>EDIT:</strong><br> I am using the WSDLImport from the glassfish 2 distribution.</p>
<p>This is a <a href="https://jax-ws.dev.java.net/issues/show_bug.cgi?id=566" rel="nofollow">known issue</a> with Sun's JAX-WS stack.</p> <p>For reference, the HTTP 500 code actually means that the server had an Internal Server Error. I'm not sure why .NET sends that rather than HTTP 503 Service Unavailable.</p>
PNG image won't show in IE7 or Firefox but works in Opera <p>I got a webservice which creates a PNG-file and returns a link to it. Then this graphic is used by a website (ASP.NET).</p> <p>IE7 &amp; Firefox 3 can't show this image but in Opera 9.5 it works fine.</p> <p>Did anyone run across the same problem before?</p> <p>Edit: Content-type is set to image/png. The image is created with the library from a 3rd party vendor which is not available to the public.</p> <p>Any chance to check the png-file for compliance to the standard?</p>
<p>In principle, both IE7 and FF can display PNG images. As it seems your PNG is not fully compliant to the rendering engines of these browsers (or to the standard?).</p> <p>It is hard to tell where the problem lies exactly without knowing how the image was created. Which lib are you using? Do you have sample code?</p> <p>EDIT (After reading the comment by Yuval A): You could also check whether the HTTP response sent by your web server has the correct content type set for PNG images. This might be needed by browsers to display the image correctly.</p>