source_id
int64
1
74.7M
question
stringlengths
0
40.2k
response
stringlengths
0
111k
metadata
dict
2,770
When working on ASP.NET 1.1 projects I always used the Global.asax to catch all errors. I'm looking for a similar way to catch all exceptions in a Windows Forms user control, which ends up being a hosted IE control. What is the proper way to go about doing something like this?
You need to handle the System.Windows.Forms.Application.ThreadException event for Windows Forms. This article really helped me: http://bytes.com/forum/thread236199.html .
{ "score": 6, "source": [ "https://Stackoverflow.com/questions/2770", "https://Stackoverflow.com", "https://Stackoverflow.com/users/447/" ] }
2,775
Here's what I use: SELECT CAST(FLOOR(CAST(getdate() as FLOAT)) as DATETIME) I'm thinking there may be a better and more elegant way. Requirements: It has to be as fast as possible (the less casting, the better). The final result has to be a datetime type, not a string.
SQL Server 2008 and up In SQL Server 2008 and up, of course the fastest way is Convert(date, @date) . This can be cast back to a datetime or datetime2 if necessary. What Is Really Best In SQL Server 2005 and Older? I've seen inconsistent claims about what's fastest for truncating the time from a date in SQL Server, and some people even said they did testing, but my experience has been different. So let's do some more stringent testing and let everyone have the script so if I make any mistakes people can correct me. Float Conversions Are Not Accurate First, I would stay away from converting datetime to float , because it does not convert correctly. You may get away with doing the time-removal thing accurately, but I think it's a bad idea to use it because it implicitly communicates to developers that this is a safe operation and it is not . Take a look: declare @d datetime;set @d = '2010-09-12 00:00:00.003';select Convert(datetime, Convert(float, @d));-- result: 2010-09-12 00:00:00.000 -- oops This is not something we should be teaching people in our code or in our examples online. Also, it is not even the fastest way! Proof – Performance Testing If you want to perform some tests yourself to see how the different methods really do stack up, then you'll need this setup script to run the tests farther down: create table AllDay (Tm datetime NOT NULL CONSTRAINT PK_AllDay PRIMARY KEY CLUSTERED);declare @d datetime;set @d = DateDiff(Day, 0, GetDate());insert AllDay select @d;while @@ROWCOUNT != 0 insert AllDay select * from ( select Tm = DateAdd(ms, (select Max(DateDiff(ms, @d, Tm)) from AllDay) + 3, Tm) from AllDay ) X where Tm < DateAdd(Day, 1, @d);exec sp_spaceused AllDay; -- 25,920,000 rows Please note that this creates a 427.57 MB table in your database and will take something like 15-30 minutes to run. If your database is small and set to 10% growth it will take longer than if you size big enough first. Now for the actual performance testing script. Please note that it's purposeful to not return rows back to the client as this is crazy expensive on 26 million rows and would hide the performance differences between the methods. Performance Results set statistics time on;-- (All queries are the same on io: logical reads 54712)GOdeclare @dd date, @d datetime, @di int, @df float, @dv varchar(10);-- Round trip back to datetimeselect @d = CONVERT(date, Tm) from AllDay; -- CPU time = 21234 ms, elapsed time = 22301 ms.select @d = CAST(Tm - 0.50000004 AS int) from AllDay; -- CPU = 23031 ms, elapsed = 24091 ms.select @d = DATEDIFF(DAY, 0, Tm) from AllDay; -- CPU = 23782 ms, elapsed = 24818 ms.select @d = FLOOR(CAST(Tm as float)) from AllDay; -- CPU = 36891 ms, elapsed = 38414 ms.select @d = CONVERT(VARCHAR(8), Tm, 112) from AllDay; -- CPU = 102984 ms, elapsed = 109897 ms.select @d = CONVERT(CHAR(8), Tm, 112) from AllDay; -- CPU = 103390 ms, elapsed = 108236 ms.select @d = CONVERT(VARCHAR(10), Tm, 101) from AllDay; -- CPU = 123375 ms, elapsed = 135179 ms.-- Only to another type but not backselect @dd = Tm from AllDay; -- CPU time = 19891 ms, elapsed time = 20937 ms.select @di = CAST(Tm - 0.50000004 AS int) from AllDay; -- CPU = 21453 ms, elapsed = 23079 ms.select @di = DATEDIFF(DAY, 0, Tm) from AllDay; -- CPU = 23218 ms, elapsed = 24700 msselect @df = FLOOR(CAST(Tm as float)) from AllDay; -- CPU = 29312 ms, elapsed = 31101 ms.select @dv = CONVERT(VARCHAR(8), Tm, 112) from AllDay; -- CPU = 64016 ms, elapsed = 67815 ms.select @dv = CONVERT(CHAR(8), Tm, 112) from AllDay; -- CPU = 64297 ms, elapsed = 67987 ms.select @dv = CONVERT(VARCHAR(10), Tm, 101) from AllDay; -- CPU = 65609 ms, elapsed = 68173 ms.GOset statistics time off; Some Rambling Analysis Some notes about this. First of all, if just performing a GROUP BY or a comparison, there's no need to convert back to datetime . So you can save some CPU by avoiding that, unless you need the final value for display purposes. You can even GROUP BY the unconverted value and put the conversion only in the SELECT clause: select Convert(datetime, DateDiff(dd, 0, Tm))from (select '2010-09-12 00:00:00.003') X (Tm)group by DateDiff(dd, 0, Tm) Also, see how the numeric conversions only take slightly more time to convert back to datetime , but the varchar conversion almost doubles? This reveals the portion of the CPU that is devoted to date calculation in the queries. There are parts of the CPU usage that don't involve date calculation, and this appears to be something close to 19875 ms in the above queries. Then the conversion takes some additional amount, so if there are two conversions, that amount is used up approximately twice. More examination reveals that compared to Convert(, 112) , the Convert(, 101) query has some additional CPU expense (since it uses a longer varchar ?), because the second conversion back to date doesn't cost as much as the initial conversion to varchar , but with Convert(, 112) it is closer to the same 20000 ms CPU base cost. Here are those calculations on the CPU time that I used for the above analysis: method round single base----------- ------ ------ ----- date 21324 19891 18458 int 23031 21453 19875 datediff 23782 23218 22654 float 36891 29312 21733varchar-112 102984 64016 25048varchar-101 123375 65609 7843 round is the CPU time for a round trip back to datetime . single is CPU time for a single conversion to the alternate data type (the one that has the side effect of removing the time portion). base is the calculation of subtracting from single the difference between the two invocations: single - (round - single) . It's a ballpark figure that assumes the conversion to and from that data type and datetime is approximately the same in either direction. It appears this assumption is not perfect but is close because the values are all close to 20000 ms with only one exception. One more interesting thing is that the base cost is nearly equal to the single Convert(date) method (which has to be almost 0 cost, as the server can internally extract the integer day portion right out of the first four bytes of the datetime data type). Conclusion So what it looks like is that the single-direction varchar conversion method takes about 1.8 μs and the single-direction DateDiff method takes about 0.18 μs. I'm basing this on the most conservative "base CPU" time in my testing of 18458 ms total for 25,920,000 rows, so 23218 ms / 25920000 = 0.18 μs. The apparent 10x improvement seems like a lot, but it is frankly pretty small until you are dealing with hundreds of thousands of rows (617k rows = 1 second savings). Even given this small absolute improvement, in my opinion, the DateAdd method wins because it is the best combination of performance and clarity. The answer that requires a "magic number" of 0.50000004 is going to bite someone some day (five zeroes or six???), plus it's harder to understand. Additional Notes When I get some time I'm going to change 0.50000004 to '12:00:00.003' and see how it does. It is converted to the same datetime value and I find it much easier to remember. For those interested, the above tests were run on a server where @@Version returns the following: Microsoft SQL Server 2008 (RTM) - 10.0.1600.22 (Intel X86) Jul 9 2008 14:43:34 Copyright (c) 1988-2008 Microsoft Corporation Standard Edition on Windows NT 5.2 (Build 3790: Service Pack 2)
{ "score": 8, "source": [ "https://Stackoverflow.com/questions/2775", "https://Stackoverflow.com", "https://Stackoverflow.com/users/434/" ] }
2,780
Let's say that we have an ARGB color: Color argb = Color.FromARGB(127, 69, 12, 255); //Light Urple. When this is painted on top of an existing color, the colors will blend. So when it is blended with white, the resulting color is Color.FromARGB(255, 162, 133, 255); The solution should work like this: Color blend = Color.White; Color argb = Color.FromARGB(127, 69, 12, 255); //Light Urple. Color rgb = ToRGB(argb, blend); //Same as Color.FromARGB(255, 162, 133, 255); What is ToRGB 's implementation?
It's called alpha blending . In psuedocode, assuming the background color (blend) always has 255 alpha. Also assumes alpha is 0-255. alpha=argb.alpha()r = (alpha/255)*argb.r() + (1 - alpha/255)*blend.r()g = (alpha/255)*argb.g() + (1 - alpha/255)*blend.g()b = (alpha/255)*argb.b() + (1 - alpha/255)*blend.b() note: you probably need to be a bit (more) careful about floating-point/int math and rounding issues, depending on language. Cast intermediates accordingly Edited to add: If you don't have a background color with an alpha of 255, the algebra gets alot more complicated. I've done it before and it's a fun exercise left to the reader (if you really need to know, ask another question :). In other words, what color C blends into some background the same as blending A, then blending B. This is sort of like calculating A+B (which isn't the same as B+A).
{ "score": 5, "source": [ "https://Stackoverflow.com/questions/2780", "https://Stackoverflow.com", "https://Stackoverflow.com/users/45/" ] }
2,785
Should you set all the objects to null ( Nothing in VB.NET) once you have finished with them? I understand that in .NET it is essential to dispose of any instances of objects that implement the IDisposable interface to release some resources although the object can still be something after it is disposed (hence the isDisposed property in forms), so I assume it can still reside in memory or at least in part? I also know that when an object goes out of scope it is then marked for collection ready for the next pass of the garbage collector (although this may take time). So with this in mind will setting it to null speed up the system releasing the memory as it does not have to work out that it is no longer in scope and are they any bad side effects? MSDN articles never do this in examples and currently I do this as I cannot see the harm. However I have come across a mixture of opinions so any comments are useful.
Karl is absolutely correct, there is no need to set objects to null after use. If an object implements IDisposable , just make sure you call IDisposable.Dispose() when you're done with that object (wrapped in a try .. finally , or, a using() block). But even if you don't remember to call Dispose() , the finaliser method on the object should be calling Dispose() for you. I thought this was a good treatment: Digging into IDisposable and this Understanding IDisposable There isn't any point in trying to second guess the GC and its management strategies because it's self tuning and opaque. There was a good discussion about the inner workings with Jeffrey Richter on Dot Net Rocks here: Jeffrey Richter on the Windows Memory Model andRichters book CLR via C# chapter 20 has a great treatment:
{ "score": 7, "source": [ "https://Stackoverflow.com/questions/2785", "https://Stackoverflow.com", "https://Stackoverflow.com/users/33/" ] }
2,786
I started trying to play with Mono, mostly for fun at the moment. I first tried to use the Visual Studio plugin that will convert a csproj into a makefile, but there seemed to be no version available for Visual Studio 2005. I also read about the MonoDevelop IDE, which sounded nice. Unfortunately, there's no pre-fab Windows package for it. I tried to follow some instructions to build it by combining dependencies from other semi-related installs. It didn't work, but that's probably because I'm a Windows-oriented guy and can barely spell "makefile". So, my question is this: What's the lowest-energy way to get up and running to try some Mono-based development on Windows?
I'd recommend getting VMWare Player and using the free Mono development platform image that is provided on the website. Download Mono Setup time for this will be minimal, and it will also allow you to get your code working in .NET and then focus on porting issues without a massive hassle of switching machines and the like. the VMWare Player tools will allow you to simply drag and drop the files over to copy them. I'm looking to take a couple of my .NET apps and make them Mono compliant, and this is the path I'm going to take here shortly.
{ "score": 5, "source": [ "https://Stackoverflow.com/questions/2786", "https://Stackoverflow.com", "https://Stackoverflow.com/users/404/" ] }
2,798
I've always been intrigued by Map Routing, but I've never found any good introductory (or even advanced!) level tutorials on it. Does anybody have any pointers, hints, etc? Update: I'm primarily looking for pointers as to how a map system is implemented (data structures, algorithms, etc).
Take a look at the open street map project to see how this sort of thing is being tackled in a truely free software project using only user supplied and licensed data and have a wiki containing stuff you might find interesting . A few years back the guys involved where pretty easy going and answered lots of questions I had so I see no reason why they still aren't a nice bunch.
{ "score": 5, "source": [ "https://Stackoverflow.com/questions/2798", "https://Stackoverflow.com", "https://Stackoverflow.com/users/116/" ] }
2,840
How do I page results in SQL Server 2005? I tried it in SQL Server 2000, but there was no reliable way to do this. I'm now wondering if SQL Server 2005 has any built in method? What I mean by paging is, for example, if I list users by their username, I want to be able to only return the first 10 records, then the next 10 records and so on. Any help would be much appreciated.
You can use the Row_Number() function.Its used as follows: SELECT Row_Number() OVER(ORDER BY UserName) As RowID, UserFirstName, UserLastNameFROM Users From which it will yield a result set with a RowID field which you can use to page between. SELECT * FROM ( SELECT Row_Number() OVER(ORDER BY UserName) As RowID, UserFirstName, UserLastName FROM Users ) As RowResultsWHERE RowID Between 5 AND 10 etc
{ "score": 6, "source": [ "https://Stackoverflow.com/questions/2840", "https://Stackoverflow.com", "https://Stackoverflow.com/users/383/" ] }
2,844
#include <stdio.h>int main() { unsigned long long int num = 285212672; //FYI: fits in 29 bits int normalInt = 5; printf("My number is %d bytes wide and its value is %ul. A normal number is %d.\n", sizeof(num), num, normalInt); return 0;} Output: My number is 8 bytes wide and its value is 285212672l. A normal number is 0. I assume this unexpected result is from printing the unsigned long long int . How do you printf() an unsigned long long int ?
Use the ll (el-el) long-long modifier with the u (unsigned) conversion. (Works in windows, GNU). printf("%llu", 285212672);
{ "score": 10, "source": [ "https://Stackoverflow.com/questions/2844", "https://Stackoverflow.com", "https://Stackoverflow.com/users/432/" ] }
2,871
What would be the best way to fill a C# struct from a byte[] array where the data was from a C/C++ struct? The C struct would look something like this (my C is very rusty): typedef OldStuff { CHAR Name[8]; UInt32 User; CHAR Location[8]; UInt32 TimeStamp; UInt32 Sequence; CHAR Tracking[16]; CHAR Filler[12];} And would fill something like this: [StructLayout(LayoutKind.Explicit, Size = 56, Pack = 1)]public struct NewStuff{ [MarshalAs(UnmanagedType.ByValTStr, SizeConst = 8)] [FieldOffset(0)] public string Name; [MarshalAs(UnmanagedType.U4)] [FieldOffset(8)] public uint User; [MarshalAs(UnmanagedType.ByValTStr, SizeConst = 8)] [FieldOffset(12)] public string Location; [MarshalAs(UnmanagedType.U4)] [FieldOffset(20)] public uint TimeStamp; [MarshalAs(UnmanagedType.U4)] [FieldOffset(24)] public uint Sequence; [MarshalAs(UnmanagedType.ByValTStr, SizeConst = 16)] [FieldOffset(28)] public string Tracking;} What is best way to copy OldStuff to NewStuff , if OldStuff was passed as byte[] array? I'm currently doing something like the following, but it feels kind of clunky. GCHandle handle;NewStuff MyStuff;int BufferSize = Marshal.SizeOf(typeof(NewStuff));byte[] buff = new byte[BufferSize];Array.Copy(SomeByteArray, 0, buff, 0, BufferSize);handle = GCHandle.Alloc(buff, GCHandleType.Pinned);MyStuff = (NewStuff)Marshal.PtrToStructure(handle.AddrOfPinnedObject(), typeof(NewStuff));handle.Free(); Is there better way to accomplish this? Would using the BinaryReader class offer any performance gains over pinning the memory and using Marshal.PtrStructure ?
From what I can see in that context, you don't need to copy SomeByteArray into a buffer. You simply need to get the handle from SomeByteArray , pin it, copy the IntPtr data using PtrToStructure and then release. No need for a copy. That would be: NewStuff ByteArrayToNewStuff(byte[] bytes){ GCHandle handle = GCHandle.Alloc(bytes, GCHandleType.Pinned); try { NewStuff stuff = (NewStuff)Marshal.PtrToStructure(handle.AddrOfPinnedObject(), typeof(NewStuff)); } finally { handle.Free(); } return stuff;} Generic version: T ByteArrayToStructure<T>(byte[] bytes) where T: struct { T stuff; GCHandle handle = GCHandle.Alloc(bytes, GCHandleType.Pinned); try { stuff = (T)Marshal.PtrToStructure(handle.AddrOfPinnedObject(), typeof(T)); } finally { handle.Free(); } return stuff;} Simpler version (requires unsafe switch): unsafe T ByteArrayToStructure<T>(byte[] bytes) where T : struct{ fixed (byte* ptr = &bytes[0]) { return (T)Marshal.PtrToStructure((IntPtr)ptr, typeof(T)); }}
{ "score": 8, "source": [ "https://Stackoverflow.com/questions/2871", "https://Stackoverflow.com", "https://Stackoverflow.com/users/206/" ] }
2,872
My Goal I would like to have a main processing thread (non GUI), and be able to spin off GUIs in their own background threads as needed, and having my main non GUI thread keep working. Put another way, I want my main non GUI-thread to be the owner of the GUI-thread and not vice versa. I'm not sure this is even possible with Windows Forms(?) Background I have a component based system in which a controller dynamically load assemblies and instantiates and run classes implementing a common IComponent interface with a single method DoStuff() . Which components that gets loaded is configured via a xml configuration file and by adding new assemblies containing different implementations of IComponent . The components provides utility functions to the main application. While the main program is doing it's thing, e.g. controlling a nuclear plant, the components might be performing utility tasks (in their own threads), e.g. cleaning the database, sending emails, printing funny jokes on the printer, what have you. What I would like, is to have one of these components be able to display a GUI, e.g. with status information for the said email sending component. The lifetime of the complete system looks like this Application starts. Check configuration file for components to load. Load them. For each component, run DoStuff() to initialize it and make it live its own life in their own threads. Continue to do main application-thingy king of work, forever. I have not yet been able to successfully perform point 3 if the component fires up a GUI in DoStuff() . It simply just halts until the GUI is closed. And not until the GUI is closed does the program progress to point 4. It would be great if these components were allowed to start up their own Windows Forms GUIs. Problem When a component tries to fire up a GUI in DoStuff() (the exact line of code is when the component runs Application.Run(theForm) ), the component and hence our system "hangs" at the Application.Run() line until the GUI is closed. Well, the just fired up GUI works fine, as expected. Example of components. One hasn't nothing to do with GUI, whilst the second fires up a cute windows with pink fluffy bunnies in them. public class MyComponent1: IComponent{ public string DoStuff(...) { // write something to the database }}public class MyComponent2: IComponent{ public void DoStuff() { Application.EnableVisualStyles(); Application.SetCompatibleTextRenderingDefault(false); Application.Run(new Form()); // I want the thread to immediately return after the GUI // is fired up, so that my main thread can continue to work. }} I have tried this with no luck. Even when I try to fire up the GUI in it's own thread, the execution halts until the GUI as closed. public void DoStuff(){ new Thread(ThreadedInitialize).Start()}private void ThreadedInitialize(){ Application.EnableVisualStyles(); Application.SetCompatibleTextRenderingDefault(false); Application.Run(new Form());} Is it possible to spin off a GUI and return after Application.Run() ?
Application.Run method displays one (or more) forms and initiates the standard message loop which runs until all the forms are closed. You cannot force a return from that method except by closing all your forms or forcing an application shutdown. You can, however, pass an ApplicationContext (instad of a new Form()) to Application.Run method and ApplicationContext can be used to launch several forms at once. Your application will only end when all of those are closed. See here: http://msdn.microsoft.com/en-us/library/system.windows.forms.application.run.aspx Also, any forms that you Show non-modally will continue to run alongside your main form, which will enable you to have more than one windows that do not block each other. I believe this is actually what you are trying to accomplish.
{ "score": 5, "source": [ "https://Stackoverflow.com/questions/2872", "https://Stackoverflow.com", "https://Stackoverflow.com/users/446/" ] }
2,873
I'm working on a project where I'm coding in C in a UNIX environment. I've been using the lint tool to check my source code. Lint has been around a long time (since 1979), can anyone suggest a more recent code analysis tool I could use ? Preferably a tool that is free.
Don't overlook the compiler itself. Read the compiler's documentation and find all the warnings and errors it can provide, and then enable as many as make sense for you. Also make sure to tell your compiler to treat warnings like errors so you're forced to fix them right away ( -Werror on gcc).By the way, don't be fooled -Wall on gcc does not enable all warnings. You may want to check valgrind (free!) — it "automatically detect[s] many memory management and threading bugs, and profile[s] your programs in detail." It isn't a static checker, but it's a great tool!
{ "score": 6, "source": [ "https://Stackoverflow.com/questions/2873", "https://Stackoverflow.com", "https://Stackoverflow.com/users/381/" ] }
2,898
Let me preface this question by saying I use TextMate on Mac OSX for my text needs and I am in love with it. Anything comparable on the Linux platform? I'll mostly use it for coding python/ruby. Doing a google search yielded outdated answers. Edit: Since there has been some concern about the 'merit' of this question. I am about to start a new Ruby Programming Project in Linux and before I got started I wanted to make sure I had the right tools to do the job. Edit #2: I use VIM on a daily basis -- all . the . time. I enjoy using it. I was just looking for some alternatives.
http://xkcd.com/378/
{ "score": 7, "source": [ "https://Stackoverflow.com/questions/2898", "https://Stackoverflow.com", "https://Stackoverflow.com/users/25/" ] }
2,900
I am getting the following error: Access denied for user 'apache'@'localhost' (using password: NO) When using the following code: <?phpinclude("../includes/connect.php");$query = "SELECT * from story";$result = mysql_query($query) or die(mysql_error());echo "<h1>Delete Story</h1>";if (mysql_num_rows($result) > 0) { while($row = mysql_fetch_row($result)){ echo '<b>'.$row[1].'</b><span align="right"><a href="../process/delete_story.php?id='.$row[0].'">Delete</a></span>'; echo '<br /><i>'.$row[2].'</i>'; }}else { echo "No stories available.";}?> The connect.php file contains my MySQL connect calls that are working fine with my INSERT queries in another portion of the software. If I comment out the $result = mysql_query line, then it goes through to the else statement. So, it is that line or the content in the if. I have been searching the net for any solutions, and most seem to be related to too many MySQL connections or that the user I am logging into MySQL as does not have permission. I have checked both. I can still perform my other queries elsewhere in the software, and I have verified that the account has the correct permissions.
And if it matters at all, apache@localhost is not the name of the user account that I use to get into the database. I don't have any user accounts with the name apache in them at all for that matter. If it is saying 'apache@localhost' the username is not getting passed correctly to the MySQL connection. 'apache' is normally the user that runs the httpd process (at least on Redhat-based systems) and if no username is passed during the connection MySQL uses whomever is calling for the connection. If you do the connection right in your script, not in a called file, do you get the same error?
{ "score": 5, "source": [ "https://Stackoverflow.com/questions/2900", "https://Stackoverflow.com", "https://Stackoverflow.com/users/454/" ] }
2,914
Occasionally, I've come across a webpage that tries to pop open a new window (for user input, or something important), but the popup blocker prevents this from happening. What methods can the calling window use to make sure the new window launched properly?
If you use JavaScript to open the popup, you can use something like this: var newWin = window.open(url); if(!newWin || newWin.closed || typeof newWin.closed=='undefined') { //POPUP BLOCKED}
{ "score": 9, "source": [ "https://Stackoverflow.com/questions/2914", "https://Stackoverflow.com", "https://Stackoverflow.com/users/434/" ] }
2,933
Python works on multiple platforms and can be used for desktop and web applications, thus I conclude that there is some way to compile it into an executable for Mac, Windows and Linux. The problem being I have no idea where to start or how to write a GUI with it, can anybody shed some light on this and point me in the right direction please?
First you will need some GUI library with Python bindings and then (if you want) some program that will convert your python scripts into standalone executables. Cross-platform GUI libraries with Python bindings (Windows, Linux, Mac) Of course, there are many, but the most popular that I've seen in wild are: Tkinter - based on Tk GUI toolkit (de-facto standard GUI library for python, free for commercial projects) WxPython - based on WxWidgets (popular, free for commercial projects) Qt using the PyQt bindings or Qt for Python . The former is not free for commercial projects. The latter is less mature, but can be used for free. Complete list is at http://wiki.python.org/moin/GuiProgramming Single executable (all platforms) PyInstaller - the most active(Could also be used with PyQt ) fbs - if you chose Qt above Single executable (Windows) py2exe - used to be the most popular Single executable (Linux) Freeze - works the same way like py2exe but targets Linux platform Single executable (Mac) py2app - again, works like py2exe but targets Mac OS
{ "score": 9, "source": [ "https://Stackoverflow.com/questions/2933", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1384652/" ] }
2,968
For parsing player commands, I've most often used the split method to split a string by delimiters and then to then just figure out the rest by a series of if s or switch es. What are some different ways of parsing strings in Java?
I assume you're trying to make the command interface as forgiving as possible. If this is the case, I suggest you use an algorithm similar to this: Read in the string Split the string into tokens Use a dictionary to convert synonyms to a common form For example, convert "hit", "punch", "strike", and "kick" all to "hit" Perform actions on an unordered, inclusive base Unordered - "punch the monkey in the face" is the same thing as "the face in the monkey punch" Inclusive - If the command is supposed to be "punch the monkey in the face" and they supply "punch monkey", you should check how many commands this matches. If only one command, do this action. It might even be a good idea to have command priorities, and even if there were even matches, it would perform the top action.
{ "score": 5, "source": [ "https://Stackoverflow.com/questions/2968", "https://Stackoverflow.com", "https://Stackoverflow.com/users/362/" ] }
2,970
My dad called me today and said people going to his website were getting 168 viruses trying to download to their computers. He isn't technical at all, and built the whole thing with a WYSIWYG editor. I popped his site open and viewed the source, and there was a line of Javascript includes at the bottom of the source right before the closing HTML tag. They included this file (among many others): http://www.98hs.ru/js.js <-- TURN OFF JAVASCRIPT BEFORE YOU GO TO THAT URL. So I commented it out for now. It turns out his FTP password was a plain dictionary word six letters long, so we think that's how it got hacked. We've changed his password to an 8+ digit non-word string (he wouldn't go for a passphrase since he is a hunt-n-peck typer). I did a whois on 98hs.ru and found it is hosted from a server in Chile. There is actually an e-mail address associated with it too, but I seriously doubt this person is the culprit. Probably just some other site that got hacked... I have no idea what to do at this point though as I've never dealt with this sort of thing before. Anyone have any suggestions? He was using plain jane un-secured ftp through webhost4life.com. I don't even see a way to do sftp on their site. I'm thinking his username and password got intercepted? So, to make this more relevant to the community, what are the steps you should take/best practices you should follow to protect your website from getting hacked? For the record, here is the line of code that "magically" got added to his file (and isn't in his file on his computer -- I've left it commented out just to make absolute sure it won't do anything on this page, although I'm sure Jeff would guard against this): <!--script src=http://www.98hs.ru/js.js></script><script src=http://www.98hs.ru/js.js></script><script src=http://www.98hs.ru/js.js></script><script src=http://www.98hs.ru/js.js></script><script src=http://www.98hs.ru/js.js></script><script src=http://www.98hs.ru/js.js></script><script src=http://www.porv.ru/js.js></script><script src=http://www.98hs.ru/js.js></script><script src=http://www.porv.ru/js.js></script><script src=http://www.98hs.ru/js.js></script><script src=http://www.porv.ru/js.js></script><script src=http://www.uhwc.ru/js.js></script><script src=http://www.98hs.ru/js.js></script><script src=http://www.porv.ru/js.js></script><script src=http://www.98hs.ru/js.js></script><script src=http://www.uhwc.ru/js.js></script><script src=http://www.98hs.ru/js.js></script><script src=http://www.uhwc.ru/js.js></script><script src=http://www.uhwc.ru/js.js></script><script src=http://www.uhwc.ru/js.js></script><script src=http://www.uhwc.ru/js.js></script><script src=http://www.porv.ru/js.js></script><script src=http://www.uhwc.ru/js.js></script><script src=http://www.porv.ru/js.js></script><script src=http://www.uhwc.ru/js.js></script><script src=http://www.uhwc.ru/js.js></script><script src=http://www.uhwc.ru/js.js></script><script src=http://www.uhwc.ru/js.js></script><script src=http://www.uhwc.ru/js.js></script><script src=http://www.uhwc.ru/js.js></script><script src=http://www.porv.ru/js.js></script><script src=http://www.uhwc.ru/js.js></script><script src=http://www.porv.ru/js.js></script><script src=http://www.uhwc.ru/js.js></script><script src=http://www.porv.ru/js.js></script><script src=http://www.uhwc.ru/js.js></script><script src=http://www.uhwc.ru/js.js></script><script src=http://www.porv.ru/js.js></script><script src=http://www.uhwc.ru/js.js></script><script src=http://www.porv.ru/js.js></script><script src=http://www.uhwc.ru/js.js></script><script src=http://www.porv.ru/js.js></script><script src=http://www.uhwc.ru/js.js></script><script src=http://www.porv.ru/js.js></script><script src=http://www.uhwc.ru/js.js></script><script src=http://www.porv.ru/js.js></script><script src=http://www.uhwc.ru/js.js></script><script src=http://www.uhwc.ru/js.js></script><script src=http://www.porv.ru/js.js></script><script src=http://www.uhwc.ru/js.js></script><script src=http://www.porv.ru/js.js></script><script src=http://www.uhwc.ru/js.js></script><script src=http://www.porv.ru/js.js></script><script src=http://www.uhwc.ru/js.js></script><script src=http://www.porv.ru/js.js></script><script src=http://www.uhwc.ru/js.js></script><script src=http://www.porv.ru/js.js></script><script src=http://www.uhwc.ru/js.js></script><script src=http://www.porv.ru/js.js></script><script src=http://www.uhwc.ru/js.js></script><script src=http://www.uhwc.ru/js.js></script><script src=http://www.uhwc.ru/js.js></script><script src=http://www.uhwc.ru/js.js></script><script src=http://www.uhwc.ru/js.js></script><script src=http://www.uhwc.ru/js.js></script><script src=http://www.uhwc.ru/js.js></script><script src=http://www.uhwc.ru/js.js></script><script src=http://www.uhwc.ru/js.js></script><script src=http://www.uhwc.ru/js.js></script><script src=http://www.uhwc.ru/js.js></script><script src=http://www.uhwc.ru/js.js></script><script src=http://www.uhwc.ru/js.js></script><script src=http://www.uhwc.ru/js.js></script><script src=http://www.uhwc.ru/js.js></script><script src=http://www.uhwc.ru/js.js></script><script src=http://www.uhwc.ru/js.js></script><script src=http://www.uhwc.ru/js.js></script><script src=http://www.uhwc.ru/js.js></script-->
Try and gather as much information as you can. See if the host can give you a log showing all the FTP connections that were made to your account. You can use those to see if it was even an FTP connection that was used to make the change and possibly get an IP address. If you're using a prepacked software like Wordpress, Drupal, or anything else that you didn't code there may be vulnerabilities in upload code that allows for this sort of modification. If it is custom built, double check any places where you allow users to upload files or modify existing files. The second thing would be to take a dump of the site as-is and check everything for other modifications. It may just be one single modification they made, but if they got in via FTP who knows what else is up there. Revert your site back to a known good status and, if need be, upgrade to the latest version. There is a level of return you have to take into account too. Is the damage worth trying to track the person down or is this something where you just live and learn and use stronger passwords?
{ "score": 5, "source": [ "https://Stackoverflow.com/questions/2970", "https://Stackoverflow.com", "https://Stackoverflow.com/users/58/" ] }
2,987
I am writing an application that needs to bring window of an external app to the foreground, and not necessarily steal focus (there is a setting the user can toggle to steal/not steal focus). What is the best way to go about this using the win32 API? I have tried SetForeground() but it always steals focus and does not consistenly work. What is the best way to go about this? Any thoughts?
SetForegroundWindow is supposed to steal focus and there are certain cases where it will fail. The SetForegroundWindow function puts the thread that created the specified window into the foreground and activates the window. Keyboard input is directed to the window Try capturing the focus with SetCapture prior to making the call. Also look into different ways of bringing the window to the front: SetForeGroundWindow, SetActiveWindow, even simulating a mouse click can do this.
{ "score": 5, "source": [ "https://Stackoverflow.com/questions/2987", "https://Stackoverflow.com", "https://Stackoverflow.com/users/324/" ] }
2,988
What are the most common problems that can be solved with both these data structures? It would be good for me to have also recommendations on books that: Implement the structures Implement and explain the reasoning of the algorithms that use them
The first thing I think about when I read this question is: what types of things use graphs/trees? and then I think backwards to how I could use them. For example, take two common uses of a tree: The DOM File systems The DOM, and XML for that matter, resemble tree structures. It makes sense, too. It makes sense because of how this data needs to be arranged . A file system, too. On a UNIX system there's a root node, and branching down below. When you mount a new device, you're attaching it onto the tree. You should also be asking yourself: does the data fall into this type of structure? Create data structures that make sense to the problem and the rest will follow. As far as being easier, I think thats relative. Are you good with recursive functions to traverse a tree/graph? What if you need to balance the tree? Think about a program that solves a word search puzzle. You could map out all the letters of the word search into a graph and check surrounding nodes to see if that string is matching any of the words. But couldn't you just do the same with with a single array? All you really need to do is move an index to check letters to the left and right, and by the width to check above and below letters. Solving this problem with a graph isn't difficult, but it can create a lot of extra work and difficulty if you're not comfortable with using them - of course that shouldn't discourage you from doing it, especially if you are learning about them. I hope that helps you think about these structures. As for a book recommendation, I'd have to go with Introduction to Algorithms .
{ "score": 5, "source": [ "https://Stackoverflow.com/questions/2988", "https://Stackoverflow.com", "https://Stackoverflow.com/users/861/" ] }
2,993
I'm in an environment with a lot of computers that haven't beenproperly inventoried. Basically, no one knows which IP goes with whichmac address and which hostname. So I wrote the following: # This script goes down the entire IP range and attempts to# retrieve the Hostname and mac address and outputs them# into a file. Yay!require "socket"TwoOctets = "10.26"def computer_exists?(computerip) system("ping -c 1 -W 1 #{computerip}")enddef append_to_file(line) file = File.open("output.txt", "a") file.puts(line) file.closeenddef getInfo(current_ip) begin if computer_exists?(current_ip) arp_output = `arp -v #{current_ip}` mac_addr = arp_output.to_s.match(/..:..:..:..:..:../) host_name = Socket.gethostbyname(current_ip) append_to_file("#{host_name[0]} - #{current_ip} - #{mac_addr}\n") end rescue SocketError => mySocketError append_to_file("unknown - #{current_ip} - #{mac_addr}") endend(6..8).each do |i| case i when 6 for j in (1..190) current_ip = "#{TwoOctets}.#{i}.#{j}" getInfo(current_ip) end when 7 for j in (1..255) current_ip = "#{TwoOctets}.#{i}.#{j}" getInfo(current_ip) end when 8 for j in (1..52) current_ip = "#{TwoOctets}.#{i}.#{j}" getInfo(current_ip) end endend Everything works except it does not find a Reverse DNS. Sample output that I'm getting is this: 10.26.6.12 - 10.26.6.12 - 00:11:11:9B:13:9F10.26.6.17 - 10.26.6.17 - 08:00:69:9A:97:C310.26.6.18 - 10.26.6.18 - 08:00:69:93:2C:E2 If I do nslookup 10.26.6.12 then I get the correct reverse DNS sothat shows that my machine is seeing the DNS server. I have tried Socket.gethostbyname , gethostbyaddr , but it doesn't work. Any guidance will be much appreciated.
Today I also needed reverse DNS lookup and I've found very simple standard solution: require 'resolv'host_name = Resolv.getname(ip_address_here) It seems it uses timeout which helps in rough cases.
{ "score": 6, "source": [ "https://Stackoverflow.com/questions/2993", "https://Stackoverflow.com", "https://Stackoverflow.com/users/155/" ] }
3,017
By "generate", I mean auto-generation of the code necessary for a particular selected (set of) variable(s). But any more explicit explication or comment on good practice is welcome.
Rather than using Ctrl + K , X you can also just type prop and then hit Tab twice.
{ "score": 9, "source": [ "https://Stackoverflow.com/questions/3017", "https://Stackoverflow.com", "https://Stackoverflow.com/users/391/" ] }
3,021
One of the topics that seems to come up regularly on mailing lists and online discussions is the merits (or lack thereof) of doing a Computer Science Degree. An argument that seems to come up time and again for the negative party is that they have been coding for some number of years and they have never used recursion. So the question is: What is recursion? When would I use recursion? Why don't people use recursion?
There are a number of good explanations of recursion in this thread, this answer is about why you shouldn't use it in most languages.* In the majority of major imperative language implementations (i.e. every major implementation of C, C++, Basic, Python, Ruby,Java, and C#) iteration is vastly preferable to recursion. To see why, walk through the steps that the above languages use to call a function: space is carved out on the stack for the function's arguments and local variables the function's arguments are copied into this new space control jumps to the function the function's code runs the function's result is copied into a return value the stack is rewound to its previous position control jumps back to where the function was called Doing all of these steps takes time, usually a little bit more than it takes to iterate through a loop. However, the real problem is in step #1. When many programs start, they allocate a single chunk of memory for their stack, and when they run out of that memory (often, but not always due to recursion), the program crashes due to a stack overflow . So in these languages recursion is slower and it makes you vulnerable to crashing. There are still some arguments for using it though. In general, code written recursively is shorter and a bit more elegant, once you know how to read it. There is a technique that language implementers can use called tail call optimization which can eliminate some classes of stack overflow. Put succinctly: if a function's return expression is simply the result of a function call, then you don't need to add a new level onto the stack, you can reuse the current one for the function being called. Regrettably, few imperative language-implementations have tail-call optimization built in. * I love recursion. My favorite static language doesn't use loops at all, recursion is the only way to do something repeatedly. I just don't think that recursion is generally a good idea in languages that aren't tuned for it. ** By the way Mario, the typical name for your ArrangeString function is "join", and I'd be surprised if your language of choice doesn't already have an implementation of it.
{ "score": 6, "source": [ "https://Stackoverflow.com/questions/3021", "https://Stackoverflow.com", "https://Stackoverflow.com/users/358/" ] }
3,033
If I have a Perl hash with a bunch of (key, value) pairs, what is the preferred method of iterating through all the keys? I have heard that using each may in some way have unintended side effects. So, is that true, and is one of the two following methods best, or is there a better way? # Method 1while (my ($key, $value) = each(%hash)) { # Something}# Method 2foreach my $key (keys(%hash)) { # Something}
The rule of thumb is to use the function most suited to your needs. If you just want the keys and do not plan to ever read any of the values, use keys(): foreach my $key (keys %hash) { ... } If you just want the values, use values(): foreach my $val (values %hash) { ... } If you need the keys and the values, use each(): keys %hash; # reset the internal iterator so a prior each() doesn't affect the loopwhile(my($k, $v) = each %hash) { ... } If you plan to change the keys of the hash in any way except for deleting the current key during the iteration, then you must not use each(). For example, this code to create a new set of uppercase keys with doubled values works fine using keys(): %h = (a => 1, b => 2);foreach my $k (keys %h){ $h{uc $k} = $h{$k} * 2;} producing the expected resulting hash: (a => 1, A => 2, b => 2, B => 4) But using each() to do the same thing: %h = (a => 1, b => 2);keys %h;while(my($k, $v) = each %h){ $h{uc $k} = $h{$k} * 2; # BAD IDEA!} produces incorrect results in hard-to-predict ways. For example: (a => 1, A => 2, b => 2, B => 8) This, however, is safe: keys %h;while(my($k, $v) = each %h){ if(...) { delete $h{$k}; # This is safe }} All of this is described in the perl documentation: % perldoc -f keys% perldoc -f each
{ "score": 9, "source": [ "https://Stackoverflow.com/questions/3033", "https://Stackoverflow.com", "https://Stackoverflow.com/users/219/" ] }
3,049
I need to send and receive data over serial connections (RS-232 and RS-422). How do I set up and communicate with such a connection? How do I figure out what the configuration settings (e.g. baud rate) should be and how do I set them? In particular I am looking to do this in Java, C/C++, or one of the major Unix shells but I also have some interest in serial programming using Windows/Hyperterminal.
Build a time machine and go back to 1987? Ho ho. Ok, no more snarky comments. How do I figure out what the configuration settings (e.g. baud rate) should be... Read the datasheet? Ok, ok. Seriously, last one. If you don't know the baud rate of the device you are trying to communicate with, you have two choices. Start guessing, or possibly bust out an o-scope. If you need a good starting point, let me suggest 9600-8-N-1. My suspicion is you can get there with brute force relatively quickly. There's a third option of having an old-school ninja who can tell just by the LOOK of the garbled characters at some standard baud rate what actual baud rate is. An impressive party trick to be sure. Hopefully though you have access to this information. In unix/linux, you can get ahold of minicom to play with the serial port directly. This should make it fairly quick to get the configuration figured out. one of the major Unix shells In Unix the serial port(s) is/are file-mapped into the /dev/ subdir. ttyS0, for example. If you setup the correct baud rate and whatnot using minicom, you can even cat stuff to that file to send stuff out there. On to the meat of the question, you can access it programmatically through the POSIX headers. termios.h is the big one. See: http://www.easysw.com/~mike/serial/serial.html#3_1 (NOT AVAILABLE ANYMORE) but I also have some interest in serial programming using Windows/Hyperterminal. Hyperterminal and minicom are basically the same program. As for how Windows let's you get access to the serial port, I'll leave that question for someone else. I haven't done that in Windows since the Win95 days.
{ "score": 6, "source": [ "https://Stackoverflow.com/questions/3049", "https://Stackoverflow.com", "https://Stackoverflow.com/users/462/" ] }
3,057
In interpreted programming languages, such as PHP and JavaScript, what are the repercussions of going with an Object Oriented approach over a Procedural approach? Specifically what I am looking for is a checklist of things to consider when creating a web application and choosing between Procedural and Object Oriented approaches, to optimize not only for speed, but maintainability as well. Cited research and test cases would be helpful as well if you know of any articles exploring this further. Bottom line: how big (if any) is the performance hit really, when going with OO vs. Procedural in an interpreted language?
Maybe I'm crazy but worrying about speed in cases like this using an interpretive language is like trying to figure out what color to paint the shed. Let's not even get into the idea that this kind of optimization is entirely pre-mature. You hit the nail on the head when you said 'maintainability'. I'd choose the approach that is the most productive and most maintainable. If you need speed later, it ain't gonna come from switching between procedural versus object oriented coding paradigms inside an interpreted language.
{ "score": 5, "source": [ "https://Stackoverflow.com/questions/3057", "https://Stackoverflow.com", "https://Stackoverflow.com/users/58/" ] }
3,058
Inversion of Control (IoC) can be quite confusing when it is first encountered. What is it? Which problem does it solve? When is it appropriate to use and when not?
The Inversion-of-Control (IoC) pattern, is about providing any kind of callback (which controls reaction), instead of acting ourself directly (in other words, inversion and/or redirecting control to external handler/controller). The Dependency-Injection (DI) pattern is a more specific version of IoC pattern, and is all about removing dependencies from your code. Every DI implementation can be considered IoC , but one should not call it IoC , because implementing Dependency-Injection is harder than callback (Don't lower your product's worth by using general term "IoC" instead). For DI example, say your application has a text-editor component, and you want to provide spell checking. Your standard code would look something like this: public class TextEditor { private SpellChecker checker; public TextEditor() { this.checker = new SpellChecker(); }} What we've done here creates a dependency between the TextEditor and the SpellChecker .In an IoC scenario we would instead do something like this: public class TextEditor { private IocSpellChecker checker; public TextEditor(IocSpellChecker checker) { this.checker = checker; }} In the first code example we are instantiating SpellChecker ( this.checker = new SpellChecker(); ), which means the TextEditor class directly depends on the SpellChecker class. In the second code example we are creating an abstraction by having the SpellChecker dependency class in TextEditor 's constructor signature (not initializing dependency in class). This allows us to call the dependency then pass it to the TextEditor class like so: SpellChecker sc = new SpellChecker(); // dependencyTextEditor textEditor = new TextEditor(sc); Now the client creating the TextEditor class has control over which SpellChecker implementation to use because we're injecting the dependency into the TextEditor signature.
{ "score": 12, "source": [ "https://Stackoverflow.com/questions/3058", "https://Stackoverflow.com", "https://Stackoverflow.com/users/358/" ] }
3,061
How do I call a function, using a string with the function's name? For example: import foofunc_name = "bar"call(foo, func_name) # calls foo.bar()
Given a module foo with method bar : import foobar = getattr(foo, 'bar')result = bar() getattr can similarly be used on class instance bound methods, module-level methods, class methods... the list goes on.
{ "score": 12, "source": [ "https://Stackoverflow.com/questions/3061", "https://Stackoverflow.com", "https://Stackoverflow.com/users/121/" ] }
3,067
If you've ever used Eclipse, you've probably noticed the great keyboard shortcuts that let you hit a shortcut key combination, then just type the first few characters of a function, class, filename, etc. It's even smart enough to put open files first in the list. I'm looking for a similar functionality for Visual Studio 2008. I know there's a findfiles plugin on codeproject, but that one is buggy and a little weird, and doesn't give me access to functions or classes.
Vs11 (maybe 2010 had it too) has the Navigate To... functionality which (on my machine) has the Ctrl + , shortcut. By the way it understands capitals as camelcase-shortucts (eclipse does so too). For instance type HH to get HtmlHelper.
{ "score": 5, "source": [ "https://Stackoverflow.com/questions/3067", "https://Stackoverflow.com", "https://Stackoverflow.com/users/291/" ] }
3,088
Original Question I am currently engaged in teaching my brother to program. He is a total beginner, but very smart. (And he actually wants to learn). I've noticed that some of our sessions have gotten bogged down in minor details, and I don't feel I've been very organized. ( But the answers to this post have helped a lot. ) What can I do better to teach him effectively? Is there a logical order that I can use to run through concept by concept? Are there complexities I should avoid till later? The language we are working with is Python , but advice in any language is welcome. How to Help If you have good ones please add the following in your answer: Beginner Exercises and Project Ideas Resources for teaching beginners Screencasts / blog posts / free e-books Print books that are good for beginners Please describe the resource with a link to it so I can take a look. I want everyone to know that I have definitely been using some of these ideas. Your submissions will be aggregated in this post. Online Resources for teaching beginners: A Gentle Introduction to Programming Using Python How to Think Like a Computer Scientist Alice: a 3d program for beginners Scratch (A system to develop programming skills) How To Design Programs Structure and Interpretation of Computer Programs Learn To Program Robert Read's How To Be a Programmer Microsoft XNA Spawning the Next Generation of Hackers COMP1917 Higher Computing lectures by Richard Buckland (requires iTunes) Dive into Python Python Wikibook Project Euler - sample problems (mostly mathematical) pygame - an easy python library for creating games Invent Your Own Computer Games With Python Foundations of Programming for a next step beyond basics. Squeak by Example Snake Wrangling For Kids (It's not just for kids!) Recommended Print Books for teaching beginners Accelerated C++ Python Programming for the Absolute Beginner Code by Charles Petzold Python Programming: An Introduction to Computer Science 2nd Edition
I've had to work with several beginner (never wrote a line of code) programmers, and I'll be doing an after school workshop with high school students this fall. This is the closest thing I've got to documentation. It's still a work in progress, but I hope it helps. 1) FizzBuzz. Start with command line programs. You can write some fun games, or tools, very quickly, and you learn all of the language features very quickly without having to learn the GUI tools first. These early apps should be simple enough that you won't need to use any real debugging tools to make them work. If nothing else things like FizzBuzz are good projects. Your first few apps should not have to deal with DBs, file system, configuration, ect. These are concepts which just confuse most people, and when you're just learning the syntax and basic framework features you really don't need more complexity. Some projects: Hello World! Take the year of my birth, and calculate my age (just (now - then) no month corrections). (simple math, input, output) Ask for a direction(Up, down, left, right), then tell the user their fate (fall in a hole, find a cake, ect). (Boolean logic) FizzBuzz, but count once every second. (Loops, timers, and more logic) Depending on their age some really like an app which calls the users a random insult at some interval. (Loops, arrays, timers, and random if you make the interval random) 2) Simple Project Once they have a good grasp of language features, you can start a project(simple, fun games work good.). You should try to have the first project be able to be completed within 6-12 hours. Don't spend time to architect it early. Let them design it even if it sucks. If it falls apart, talk about what happened and why it failed, then pick another topic and start again. This is where you start introducing the debugging capabilities of your tools. Even if you can see the problem by reading the code you should teach them how to use the tools, and then show them how you could see it. That serves the dual purpose of teaching the debugging tools and teaching how to ID errors without tools. Once, or if, the project gets functional you can use it to introduce refactoring tools. Its good if you can then expand the project with some simple features which you never planned for. This usually means refactoring and significant debugging, since very few people write even half decent code their first time. Some projects: Hangman game Experimenting with robotics( Vex and Mindstorms are options) 3) Real Project Start a real project which may take some time. Use proper source control, and make a point to have a schedule. Run this project like a real project, if nothing else its good experience having to deal with the tools. Obviously you need to adjust this for each person. The most important thing I've found is to make even the first simple apps apply to what the person is interested in. Some projects: Tetris Text file based blog engine More advanced robotics work
{ "score": 7, "source": [ "https://Stackoverflow.com/questions/3088", "https://Stackoverflow.com", "https://Stackoverflow.com/users/92/" ] }
3,112
I have a perl variable $results that gets returned from a service. The value is supposed to be an array, and $results should be an array reference. However, when the array has only one item in it, $results will be set to that value, and not a referenced array that contains that one item. I want to do a foreach loop on the expected array. Without checking ref($results) eq 'ARRAY' , is there any way to have something equivalent to the following: foreach my $result (@$results) { # Process $result} That particular code sample will work for the reference, but will complain for the simple scalar. EDIT: I should clarify that there is no way for me to change what is returned from the service. The problem is that the value will be a scalar when there is only one value and it will be an array reference when there is more than one value.
im not sure there's any other way than: $result = [ $result ] if ref($result) ne 'ARRAY'; foreach .....
{ "score": 6, "source": [ "https://Stackoverflow.com/questions/3112", "https://Stackoverflow.com", "https://Stackoverflow.com/users/219/" ] }
3,150
I'm having trouble figuring out how to get the testing framework set up and usable in Visual Studio 2008 for C++ presumably with the built-in unit testing suite. Any links or tutorials would be appreciated.
This page may help, it reviews quite a few C++ unit test frameworks: CppUnit Boost.Test CppUnitLite NanoCppUnit Unit++ CxxTest Check out CPPUnitLite or CPPUnitLite2 . CPPUnitLite was created by Michael Feathers, who originally ported Java's JUnit to C++ as CPPUnit (CPPUnit tries mimic the development model of JUnit - but C++ lacks Java's features [e.g. reflection] to make it easy to use). CPPUnitLite attempts to make a true C++-style testing framework, not a Java one ported to C++. (I'm paraphrasing from Feather's Working Effectively with Legacy Code book). CPPUnitLite2 seems to be another rewrite, with more features and bug fixes. I also just stumbled across UnitTest++ which includes stuff from CPPUnitLite2 and some other framework. Microsoft has released WinUnit . Also checkout Catch or Doctest
{ "score": 7, "source": [ "https://Stackoverflow.com/questions/3150", "https://Stackoverflow.com", "https://Stackoverflow.com/users/370/" ] }
3,163
I have been trying to find a really fast way to parse yyyy-mm-dd [hh:mm:ss] into a Date object. Here are the 3 ways I have tried doing it and the times it takes each method to parse 50,000 date time strings. Does anyone know any faster ways of doing this or tips to speed up the methods? castMethod1 takes 3673 ms castMethod2 takes 3812 ms castMethod3 takes 3931 ms Code: private function castMethod1(dateString:String):Date { if ( dateString == null ) { return null; } var year:int = int(dateString.substr(0,4)); var month:int = int(dateString.substr(5,2))-1; var day:int = int(dateString.substr(8,2)); if ( year == 0 && month == 0 && day == 0 ) { return null; } if ( dateString.length == 10 ) { return new Date(year, month, day); } var hour:int = int(dateString.substr(11,2)); var minute:int = int(dateString.substr(14,2)); var second:int = int(dateString.substr(17,2)); return new Date(year, month, day, hour, minute, second);} - private function castMethod2(dateString:String):Date { if ( dateString == null ) { return null; } if ( dateString.indexOf("0000-00-00") != -1 ) { return null; } dateString = dateString.split("-").join("/"); return new Date(Date.parse( dateString ));} - private function castMethod3(dateString:String):Date { if ( dateString == null ) { return null; } var mainParts:Array = dateString.split(" "); var dateParts:Array = mainParts[0].split("-"); if ( Number(dateParts[0])+Number(dateParts[1])+Number(dateParts[2]) == 0 ) { return null; } return new Date( Date.parse( dateParts.join("/")+(mainParts[1]?" "+mainParts[1]:" ") ) );} No, Date.parse will not handle dashes by default. And I need to return null for date time strings like "0000-00-00" .
I've been using the following snipplet to parse UTC date strings: private function parseUTCDate( str : String ) : Date { var matches : Array = str.match(/(\d\d\d\d)-(\d\d)-(\d\d) (\d\d):(\d\d):(\d\d)Z/); var d : Date = new Date(); d.setUTCFullYear(int(matches[1]), int(matches[2]) - 1, int(matches[3])); d.setUTCHours(int(matches[4]), int(matches[5]), int(matches[6]), 0); return d;} Just remove the time part and it should work fine for your needs: private function parseDate( str : String ) : Date { var matches : Array = str.match(/(\d\d\d\d)-(\d\d)-(\d\d)/); var d : Date = new Date(); d.setUTCFullYear(int(matches[1]), int(matches[2]) - 1, int(matches[3])); return d;} No idea about the speed, I haven't been worried about that in my applications. 50K iterations in significantly less than a second on my machine.
{ "score": 5, "source": [ "https://Stackoverflow.com/questions/3163", "https://Stackoverflow.com", "https://Stackoverflow.com/users/22/" ] }
3,164
If I have managed to locate and verify the existence of a file using Server.MapPath and I now want to send the user directly to that file, what is the fastest way to convert that absolute path back into a relative web path?
Perhaps this might work: String RelativePath = AbsolutePath.Replace(Request.ServerVariables["APPL_PHYSICAL_PATH"], String.Empty); I'm using c# but could be adapted to vb.
{ "score": 7, "source": [ "https://Stackoverflow.com/questions/3164", "https://Stackoverflow.com", "https://Stackoverflow.com/users/192/" ] }
3,180
Is there anyone working solo and using fogbugz out there? I'm interested in personal experience/overhead versus paper. I am involved in several projects and get pretty hammered with lots of details to keep track of... Any experience welcome. (Yes I know Mr. Joel is on the stackoverflow team... I still want good answers :)
I use it, especially since the hosted Version of FugBugz is free for up to 2 people . I found it a lot nicer than paper as I'm working on multiple projects, and my paper tends to get rather messy once you start making annotations or if you want to re-organize and shuffle tasks around, mark them as complete only to see that they are not complete after all... Plus, the Visual Studio integration is really neat, something paper just cannot compete with. Also, if you lay the project to rest for 6 months and come back, all your tasks and notes are still there, whereas with paper you may need to search all the old documents and notes again, if you did not discard it. But that is just the point of view from someone who is not really good at staying organized :-) If you are a really tidy and organized person, paper may work better for you than it does for me. Bonus suggestion: Run Fogbugz on a second PC (or a small Laptop like the eeePC) so that you always have it at your fingertips. The main problem with Task tracking programs - be it FogBugz, Outlook, Excel or just notepad - is that they take up screen space, and my two monitors are usually full with Visual Studio, e-Mail, Web Browsers, some Notepads etc.
{ "score": 6, "source": [ "https://Stackoverflow.com/questions/3180", "https://Stackoverflow.com", "https://Stackoverflow.com/users/479/" ] }
3,196
If I have data like this: Key Name 1 Dan 2 Tom 3 Jon 4 Tom 5 Sam 6 Dan What is the SQL query to bring back the records where Name is repeated 2 or more times? So the result I would want is Tom Dan
Couldn't be simpler... Select Name, Count(Name) As Count From Table Group By Name Having Count(Name) > 1 Order By Count(Name) Desc This could also be extended to delete duplicates: Delete From TableWhere Key In ( Select Max(Key) From Table Group By Name Having Count(Name) > 1 )
{ "score": 6, "source": [ "https://Stackoverflow.com/questions/3196", "https://Stackoverflow.com", "https://Stackoverflow.com/users/230/" ] }
3,213
Is there an efficient method of converting an integer into the written numbers, for example: string Written = IntegerToWritten(21); would return "Twenty One". Is there any way of doing this that doesn't involve a massive look-up table?
This should work reasonably well: public static class HumanFriendlyInteger{ static string[] ones = new string[] { "", "One", "Two", "Three", "Four", "Five", "Six", "Seven", "Eight", "Nine" }; static string[] teens = new string[] { "Ten", "Eleven", "Twelve", "Thirteen", "Fourteen", "Fifteen", "Sixteen", "Seventeen", "Eighteen", "Nineteen" }; static string[] tens = new string[] { "Twenty", "Thirty", "Forty", "Fifty", "Sixty", "Seventy", "Eighty", "Ninety" }; static string[] thousandsGroups = { "", " Thousand", " Million", " Billion" }; private static string FriendlyInteger(int n, string leftDigits, int thousands) { if (n == 0) { return leftDigits; } string friendlyInt = leftDigits; if (friendlyInt.Length > 0) { friendlyInt += " "; } if (n < 10) { friendlyInt += ones[n]; } else if (n < 20) { friendlyInt += teens[n - 10]; } else if (n < 100) { friendlyInt += FriendlyInteger(n % 10, tens[n / 10 - 2], 0); } else if (n < 1000) { friendlyInt += FriendlyInteger(n % 100, (ones[n / 100] + " Hundred"), 0); } else { friendlyInt += FriendlyInteger(n % 1000, FriendlyInteger(n / 1000, "", thousands+1), 0); if (n % 1000 == 0) { return friendlyInt; } } return friendlyInt + thousandsGroups[thousands]; } public static string IntegerToWritten(int n) { if (n == 0) { return "Zero"; } else if (n < 0) { return "Negative " + IntegerToWritten(-n); } return FriendlyInteger(n, "", 0); }} (Edited to fix a bug w/ million, billion, etc.)
{ "score": 7, "source": [ "https://Stackoverflow.com/questions/3213", "https://Stackoverflow.com", "https://Stackoverflow.com/users/383/" ] }
3,224
CSS and Javascript files don't change very often, so I want them to be cached by the web browser. But I also want the web browser to see changes made to these files without requiring the user to clear their browser cache. Also want a solution that works well with a version control system such as Subversion. Some solutions I have seen involve adding a version number to the end of the file in the form of a query string. Could use the SVN revision number to automate this for you: ASP.NET Display SVN Revision Number Can you specify how you include the Revision variable of another file? That is in the HTML file I can include the Revision number in the URL to the CSS or Javascript file. In the Subversion book it says about Revision: "This keyword describes the last known revision in which this file changed in the repository". Firefox also allows pressing CTRL + R to reload everything on a particular page. To clarify I am looking for solutions that don't require the user to do anything on their part.
I found that if you append the last modified timestamp of the file onto the end of the URL the browser will request the files when it is modified. For example in PHP: function urlmtime($url) { $parsed_url = parse_url($url); $path = $parsed_url['path']; if ($path[0] == "/") { $filename = $_SERVER['DOCUMENT_ROOT'] . "/" . $path; } else { $filename = $path; } if (!file_exists($filename)) { // If not a file then use the current time $lastModified = date('YmdHis'); } else { $lastModified = date('YmdHis', filemtime($filename)); } if (strpos($url, '?') === false) { $url .= '?ts=' . $lastModified; } else { $url .= '&ts=' . $lastModified; } return $url;}function include_css($css_url, $media='all') { // According to Yahoo, using link allows for progressive // rendering in IE where as @import url($css_url) does not echo '<link rel="stylesheet" type="text/css" media="' . $media . '" href="' . urlmtime($css_url) . '">'."\n";}function include_javascript($javascript_url) { echo '<script type="text/javascript" src="' . urlmtime($javascript_url) . '"></script>'."\n";}
{ "score": 6, "source": [ "https://Stackoverflow.com/questions/3224", "https://Stackoverflow.com", "https://Stackoverflow.com/users/486/" ] }
3,230
I'm wondering how to make a release build that includes all necessary dll files into the .exe so the program can be run on a non-development machine without it having to install the microsoft redistributable on the target machine. Without doing this you get the error message that the application configuration is not correct and to reinstall.
Choose Project -> Properties Select Configuration -> General In the box for how you should link MFC, choose to statically link it. Choose Linker -> Input. Under Additional Dependencies , add any libraries you need your app to statically link in.
{ "score": 5, "source": [ "https://Stackoverflow.com/questions/3230", "https://Stackoverflow.com", "https://Stackoverflow.com/users/370/" ] }
3,231
I want to write C/C++ programs that take input from a MIDI device. The MIDI device connects to my PC using a USB connector. I'm looking for a (C/C++ implemented) library that I can use to read the MIDI signals from the MIDI device through the USB port. I'm happy manipulating the MIDI data once I get it, I just don't want to have to implement the code for its capture. I'm planning on writing my code using the Bloodshed Dev-C++ IDE on Windows XP.
PortMidi is another open source cross-platform MIDI I/O library worth checking out. On the other hand, if you are working on a sysex type of app, then direct Win32 works easily enough. Just came across another open source cross-platform framework that includes MIDI support: Juce . Also, I should note that there isn't anything special about a USB connected MIDI device. It will still be presented as a MIDI device in Windows and you will use standard MIDI APIs (mmsystem) to communicate with it. [July 2014] I just came across RtMidi that looks to be a nice, compact, open source cross-platform C++ library.
{ "score": 5, "source": [ "https://Stackoverflow.com/questions/3231", "https://Stackoverflow.com", "https://Stackoverflow.com/users/381/" ] }
3,255
Most people with a degree in CS will certainly know what Big O stands for .It helps us to measure how well an algorithm scales. But I'm curious, how do you calculate or approximate the complexity of your algorithms?
I'll do my best to explain it here on simple terms, but be warned that this topic takes my students a couple of months to finally grasp. You can find more information on the Chapter 2 of the Data Structures and Algorithms in Java book. There is no mechanical procedure that can be used to get the BigOh. As a "cookbook", to obtain the BigOh from a piece of code you first need to realize that you are creating a math formula to count how many steps of computations get executed given an input of some size. The purpose is simple: to compare algorithms from a theoretical point of view, without the need to execute the code. The lesser the number of steps, the faster the algorithm. For example, let's say you have this piece of code: int sum(int* data, int N) { int result = 0; // 1 for (int i = 0; i < N; i++) { // 2 result += data[i]; // 3 } return result; // 4} This function returns the sum of all the elements of the array, and we want to create a formula to count the computational complexity of that function: Number_Of_Steps = f(N) So we have f(N) , a function to count the number of computational steps. The input of the function is the size of the structure to process. It means that this function is called such as: Number_Of_Steps = f(data.length) The parameter N takes the data.length value. Now we need the actual definition of the function f() . This is done from the source code, in which each interesting line is numbered from 1 to 4. There are many ways to calculate the BigOh. From this point forward we are going to assume that every sentence that doesn't depend on the size of the input data takes a constant C number computational steps. We are going to add the individual number of steps of the function, and neither the local variable declaration nor the return statement depends on the size of the data array. That means that lines 1 and 4 takes C amount of steps each, and the function is somewhat like this: f(N) = C + ??? + C The next part is to define the value of the for statement. Remember that we are counting the number of computational steps, meaning that the body of the for statement gets executed N times. That's the same as adding C , N times: f(N) = C + (C + C + ... + C) + C = C + N * C + C There is no mechanical rule to count how many times the body of the for gets executed, you need to count it by looking at what does the code do. To simplify the calculations, we are ignoring the variable initialization, condition and increment parts of the for statement. To get the actual BigOh we need the Asymptotic analysis of the function. This is roughly done like this: Take away all the constants C . From f() get the polynomium in its standard form . Divide the terms of the polynomium and sort them by the rate of growth. Keep the one that grows bigger when N approaches infinity . Our f() has two terms: f(N) = 2 * C * N ^ 0 + 1 * C * N ^ 1 Taking away all the C constants and redundant parts: f(N) = 1 + N ^ 1 Since the last term is the one which grows bigger when f() approaches infinity (think on limits ) this is the BigOh argument, and the sum() function has a BigOh of: O(N) There are a few tricks to solve some tricky ones: use summations whenever you can. As an example, this code can be easily solved using summations: for (i = 0; i < 2*n; i += 2) { // 1 for (j=n; j > i; j--) { // 2 foo(); // 3 }} The first thing you needed to be asked is the order of execution of foo() . While the usual is to be O(1) , you need to ask your professors about it. O(1) means (almost, mostly) constant C , independent of the size N . The for statement on the sentence number one is tricky. While the index ends at 2 * N , the increment is done by two. That means that the first for gets executed only N steps, and we need to divide the count by two. f(N) = Summation(i from 1 to 2 * N / 2)( ... ) = = Summation(i from 1 to N)( ... ) The sentence number two is even trickier since it depends on the value of i . Take a look: the index i takes the values: 0, 2, 4, 6, 8, ..., 2 * N, and the second for get executed: N times the first one, N - 2 the second, N - 4 the third... up to the N / 2 stage, on which the second for never gets executed. On formula, that means: f(N) = Summation(i from 1 to N)( Summation(j = ???)( ) ) Again, we are counting the number of steps . And by definition, every summation should always start at one, and end at a number bigger-or-equal than one. f(N) = Summation(i from 1 to N)( Summation(j = 1 to (N - (i - 1) * 2)( C ) ) (We are assuming that foo() is O(1) and takes C steps.) We have a problem here: when i takes the value N / 2 + 1 upwards, the inner Summation ends at a negative number! That's impossible and wrong. We need to split the summation in two, being the pivotal point the moment i takes N / 2 + 1 . f(N) = Summation(i from 1 to N / 2)( Summation(j = 1 to (N - (i - 1) * 2)) * ( C ) ) + Summation(i from 1 to N / 2) * ( C ) Since the pivotal moment i > N / 2 , the inner for won't get executed, and we are assuming a constant C execution complexity on its body. Now the summations can be simplified using some identity rules: Summation(w from 1 to N)( C ) = N * C Summation(w from 1 to N)( A (+/-) B ) = Summation(w from 1 to N)( A ) (+/-) Summation(w from 1 to N)( B ) Summation(w from 1 to N)( w * C ) = C * Summation(w from 1 to N)( w ) (C is a constant, independent of w ) Summation(w from 1 to N)( w ) = (N * (N + 1)) / 2 Applying some algebra: f(N) = Summation(i from 1 to N / 2)( (N - (i - 1) * 2) * ( C ) ) + (N / 2)( C )f(N) = C * Summation(i from 1 to N / 2)( (N - (i - 1) * 2)) + (N / 2)( C )f(N) = C * (Summation(i from 1 to N / 2)( N ) - Summation(i from 1 to N / 2)( (i - 1) * 2)) + (N / 2)( C )f(N) = C * (( N ^ 2 / 2 ) - 2 * Summation(i from 1 to N / 2)( i - 1 )) + (N / 2)( C )=> Summation(i from 1 to N / 2)( i - 1 ) = Summation(i from 1 to N / 2 - 1)( i )f(N) = C * (( N ^ 2 / 2 ) - 2 * Summation(i from 1 to N / 2 - 1)( i )) + (N / 2)( C )f(N) = C * (( N ^ 2 / 2 ) - 2 * ( (N / 2 - 1) * (N / 2 - 1 + 1) / 2) ) + (N / 2)( C )=> (N / 2 - 1) * (N / 2 - 1 + 1) / 2 = (N / 2 - 1) * (N / 2) / 2 = ((N ^ 2 / 4) - (N / 2)) / 2 = (N ^ 2 / 8) - (N / 4)f(N) = C * (( N ^ 2 / 2 ) - 2 * ( (N ^ 2 / 8) - (N / 4) )) + (N / 2)( C )f(N) = C * (( N ^ 2 / 2 ) - ( (N ^ 2 / 4) - (N / 2) )) + (N / 2)( C )f(N) = C * (( N ^ 2 / 2 ) - (N ^ 2 / 4) + (N / 2)) + (N / 2)( C )f(N) = C * ( N ^ 2 / 4 ) + C * (N / 2) + C * (N / 2)f(N) = C * ( N ^ 2 / 4 ) + 2 * C * (N / 2)f(N) = C * ( N ^ 2 / 4 ) + C * Nf(N) = C * 1/4 * N ^ 2 + C * N And the BigOh is: O(N²)
{ "score": 12, "source": [ "https://Stackoverflow.com/questions/3255", "https://Stackoverflow.com", "https://Stackoverflow.com/users/46/" ] }
3,260
We use a data acquisition card to take readings from a device that increases its signal to a peak and then falls back to near the original value. To find the peak value we currently search the array for the highest reading and use the index to determine the timing of the peak value which is used in our calculations. This works well if the highest value is the peak we are looking for but if the device is not working correctly we can see a second peak which can be higher than the initial peak. We take 10 readings a second from 16 devices over a 90 second period. My initial thoughts are to cycle through the readings checking to see if the previous and next points are less than the current to find a peak and construct an array of peaks. Maybe we should be looking at a average of a number of points either side of the current position to allow for noise in the system. Is this the best way to proceed or are there better techniques? We do use LabVIEW and I have checked the LAVA forums and there are a number of interesting examples. This is part of our test software and we are trying to avoid using too many non-standard VI libraries so I was hoping for feedback on the process/algorithms involved rather than specific code.
There are lots and lots of classic peak detection methods, any of which might work. You'll have to see what, in particular, bounds the quality of your data. Here are basic descriptions: Between any two points in your data, (x(0), y(0)) and (x(n), y(n)) , add up y(i + 1) - y(i) for 0 <= i < n and call this T ("travel") and set R ("rise") to y(n) - y(0) + k for suitably small k . T/R > 1 indicates a peak. This works OK if large travel due to noise is unlikely or if noise distributes symmetrically around a base curve shape. For your application, accept the earliest peak with a score above a given threshold, or analyze the curve of travel per rise values for more interesting properties. Use matched filters to score similarity to a standard peak shape (essentially, use a normalized dot-product against some shape to get a cosine-metric of similarity) Deconvolve against a standard peak shape and check for high values (though I often find 2 to be less sensitive to noise for simple instrumentation output). Smooth the data and check for triplets of equally spaced points where, if x0 < x1 < x2, y1 > 0.5 * (y0 + y2) , or check Euclidean distances like this: D((x0, y0), (x1, y1)) + D((x1, y1), (x2, y2)) > D((x0, y0),(x2, y2)) , which relies on the triangle inequality. Using simple ratios will again provide you a scoring mechanism. Fit a very simple 2-gaussian mixture model to your data (for example, Numerical Recipes has a nice ready-made chunk of code). Take the earlier peak. This will deal correctly with overlapping peaks. Find the best match in the data to a simple Gaussian, Cauchy, Poisson, or what-have-you curve. Evaluate this curve over a broad range and subtract it from a copy of the data after noting it's peak location. Repeat. Take the earliest peak whose model parameters (standard deviation probably, but some applications might care about kurtosis or other features) meet some criterion. Watch out for artifacts left behind when peaks are subtracted from the data.Best match might be determined by the kind of match scoring suggested in #2 above. I've done what you're doing before: finding peaks in DNA sequence data, finding peaks in derivatives estimated from measured curves, and finding peaks in histograms. I encourage you to attend carefully to proper baselining. Wiener filtering or other filtering or simple histogram analysis is often an easy way to baseline in the presence of noise. Finally, if your data is typically noisy and you're getting data off the card as unreferenced single-ended output (or even referenced, just not differential), and if you're averaging lots of observations into each data point, try sorting those observations and throwing away the first and last quartile and averaging what remains. There are a host of such outlier elimination tactics that can be really useful.
{ "score": 6, "source": [ "https://Stackoverflow.com/questions/3260", "https://Stackoverflow.com", "https://Stackoverflow.com/users/186/" ] }
3,281
I'm wondering if there's a way to do what I can do below with Python, in Ruby: sum = reduce(lambda x, y: x + y, map(lambda x, y: x * y, weights, data)) I have two arrays of equal sizes with the weights and data but I can't seem to find a function similar to map in Ruby, reduce I have working.
@Michiel de Mare Your Ruby 1.9 example can be shortened a bit further: weights.zip(data).map(:*).reduce(:+) Also note that in Ruby 1.8, if you require ActiveSupport (from Rails) you can use: weights.zip(data).map(&:*).reduce(&:+)
{ "score": 5, "source": [ "https://Stackoverflow.com/questions/3281", "https://Stackoverflow.com", "https://Stackoverflow.com/users/484/" ] }
3,284
I've been working with providers a fair bit lately, and I came across an interesting situation where I wanted to have an abstract class that had an abstract static method. I read a few posts on the topic, and it sort of made sense, but is there a nice clear explanation?
Static methods are not instantiated as such, they're just available without an object reference. A call to a static method is done through the class name, not through an object reference, and the Intermediate Language (IL) code to call it will call the abstract method through the name of the class that defined it, not necessarily the name of the class you used. Let me show an example. With the following code: public class A{ public static void Test() { }}public class B : A{} If you call B.Test, like this: class Program{ static void Main(string[] args) { B.Test(); }} Then the actual code inside the Main method is as follows: .entrypoint.maxstack 8L0000: nop L0001: call void ConsoleApplication1.A::Test()L0006: nop L0007: ret As you can see, the call is made to A.Test, because it was the A class that defined it, and not to B.Test, even though you can write the code that way. If you had class types , like in Delphi, where you can make a variable referring to a type and not an object, you would have more use for virtual and thus abstract static methods (and also constructors), but they aren't available and thus static calls are non-virtual in .NET. I realize that the IL designers could allow the code to be compiled to call B.Test, and resolve the call at runtime, but it still wouldn't be virtual, as you would still have to write some kind of class name there. Virtual methods, and thus abstract ones, are only useful when you're using a variable which, at runtime, can contain many different types of objects, and you thus want to call the right method for the current object you have in the variable. With static methods you need to go through a class name anyway, so the exact method to call is known at compile time because it can't and won't change. Thus, virtual/abstract static methods are not available in .NET.
{ "score": 8, "source": [ "https://Stackoverflow.com/questions/3284", "https://Stackoverflow.com", "https://Stackoverflow.com/users/493/" ] }
3,315
I need to set the height of every textbox on my form, some of which are nested within other controls. I thought I could do something like this: private static IEnumerator<TextBox> FindTextBoxes(Control rootControl){ foreach (Control control in rootControl.Controls) { if (control.Controls.Count > 0) { // Recursively search for any TextBoxes within each child control foreach (TextBox textBox in FindTextBoxes(control)) { yield return textBox; } } TextBox textBox2 = control as TextBox; if (textBox2 != null) { yield return textBox2; } }} Using it like this: foreach(TextBox textBox in FindTextBoxes(this)){ textBox.Height = height;} But of course the compiler spits its dummy, because foreach expects an IEnumerable rather than an IEnumerator . Is there a way to do this without having to create a separate class with a GetEnumerator() method?
As the compiler is telling you, you need to change your return type to IEnumerable. That is how the yield return syntax works.
{ "score": 5, "source": [ "https://Stackoverflow.com/questions/3315", "https://Stackoverflow.com", "https://Stackoverflow.com/users/503/" ] }
3,319
How can I set the background color of an HTML element using css in JavaScript?
In general, CSS properties are converted to JavaScript by making them camelCase without any dashes. So background-color becomes backgroundColor . function setColor(element, color){ element.style.backgroundColor = color;}// where el is the concerned elementvar el = document.getElementById('elementId');setColor(el, 'green');
{ "score": 8, "source": [ "https://Stackoverflow.com/questions/3319", "https://Stackoverflow.com", "https://Stackoverflow.com/users/383/" ] }
3,362
I would like to be able to use the Tab key within a text box to tab over four spaces. The way it is now, the Tab key jumps my cursor to the next input. Is there some JavaScript that will capture the Tab key in the text box before it bubbles up to the UI? I understand some browsers (i.e. FireFox) may not allow this. How about a custom key-combo like Shift + Tab , or Ctrl + Q ?
Even if you capture the keydown / keyup event, those are the only events that the tab key fires, you still need some way to prevent the default action, moving to the next item in the tab order, from occurring. In Firefox you can call the preventDefault() method on the event object passed to your event handler. In IE, you have to return false from the event handle. The JQuery library provides a preventDefault method on its event object that works in IE and FF. <body><input type="text" id="myInput"><script type="text/javascript"> var myInput = document.getElementById("myInput"); if(myInput.addEventListener ) { myInput.addEventListener('keydown',this.keyHandler,false); } else if(myInput.attachEvent ) { myInput.attachEvent('onkeydown',this.keyHandler); /* damn IE hack */ } function keyHandler(e) { var TABKEY = 9; if(e.keyCode == TABKEY) { this.value += " "; if(e.preventDefault) { e.preventDefault(); } return false; } }</script></body>
{ "score": 8, "source": [ "https://Stackoverflow.com/questions/3362", "https://Stackoverflow.com", "https://Stackoverflow.com/users/357/" ] }
3,385
I know that we can get the MAC address of a user via IE (ActiveX objects). Is there a way to obtain a user's MAC address using JavaScript?
I concur with all the previous answers that it would be a privacy/security vulnerability if you would be able to do this directly from Javascript. There are two things I can think of: Using Java (with a signed applet) Using signed Javascript, which in FF (and Mozilla in general) gets higher privileges than normal JS (but it is fairly complicated to set up)
{ "score": 7, "source": [ "https://Stackoverflow.com/questions/3385", "https://Stackoverflow.com", "https://Stackoverflow.com/users/384/" ] }
3,400
Note: I am using SQL's Full-text search capabilities, CONTAINS clauses and all - the * is the wildcard in full-text, % is for LIKE clauses only. I've read in several places now that "leading wildcard" searches (e.g. using "*overflow" to match "stackoverflow") is not supported in MS SQL. I'm considering using a CLR function to add regex matching , but I'm curious to see what other solutions people might have. More Info : You can add the asterisk only at the end of the word or phrase. - along with my empirical experience: When matching "myvalue", "my*" works, but "(asterisk)value" returns no match, when doing a query as simple as: SELECT * FROM TABLENAME WHERE CONTAINS(TextColumn, '"*searchterm"'); Thus, my need for a workaround. I'm only using search in my site on an actual search page - so it needs to work basically the same way that Google works (in the eyes on a Joe Sixpack-type user). Not nearly as complicated, but this sort of match really shouldn't fail.
Workaround only for leading wildcard: store the text reversed in a different field (or in materialised view) create a full text index on this column find the reversed text with an * SELECT * FROM TABLENAME WHERE CONTAINS(TextColumnREV, '"mrethcraes*"'); Of course there are many drawbacks, just for quick workaround... Not to mention CONTAINSTABLE...
{ "score": 5, "source": [ "https://Stackoverflow.com/questions/3400", "https://Stackoverflow.com", "https://Stackoverflow.com/users/35/" ] }
3,404
I use Firebug and the Mozilla JS console heavily, but every now and then I run into an IE-only JavaScript bug, which is really hard to locate (ex: error on line 724 , when the source HTML only has 200 lines). I would love to have a lightweight JS tool ( a la firebug) for Internet Explorer, something I can install in seconds on a client's PC if I run into an error and then uninstall. Some Microsoft tools take some serious download and configuration time. Any ideas?
You might find Firebug Lite useful for that. Its bookmarklet should be especially useful when debugging on a user's machine.
{ "score": 6, "source": [ "https://Stackoverflow.com/questions/3404", "https://Stackoverflow.com", "https://Stackoverflow.com/users/547/" ] }
3,408
What do you think is the best set-up for RoR in a Win Vista environment? I've tried the radrails eclipse plug-in, and it just seemed too bulky for me, I've also started to just use Textpad and the command line, but I'm used to having somewhat of an IDE to work with.
I don't know about "best", because that's a subjective question, but I can tell you what setup I use and recommend: Editor : E Text Editor TextMate seems to be the editor of choice for Rails on Mac. E Text Editor is essentially TextMate for Windows. Its bundles are broadly compatible with TextMate's including the Rails 2 bundle which is included with the basic install. Alternatively, if you're into the whole Visual Studio ecosystem, then Ruby in Steel PE might be a better bet. It's a really nice all-in-one package that actually comes with (a stripped-down version of) Visual Studio now. Environment : VirtualBox running Ubuntu Server Deploying a Rails app can be a pain at the best of times; deploying a Rails app from a Windows environment onto a *nix server is even worse. Plus, running Rails apps on Windows is slow . Running your tests is slow. So I use VirtualBox to host a VM on my Windows machine that mirrors my target deployment environment as closely as possible. In my case I run Ubuntu Server because there are a really nice set of step-by-step tutorials for getting up-and-running with a full Ubuntu-based Rails stack on the SliceHost wiki . Here are the benefits of developing using a VM: I map a network drive to the VM so that I can edit the code on it directly from Windows using E Text Editor. The VM acts and feels just like a command line window. So you don't feel like you're in a completely alien environment. It runs Rails and other Ruby scripts (like tests) faster than running it natively in Windows Everything is contained and snapshottable , so I can experiment and generally play around without worrying about breaking anything. If something does break, I just roll back to a previous good state. It uses hardly any RAM. It will typically use less that 100MB (it's currently using ~43MB, but I don't have a Rails app spun-up). Contrast this with, say, Firefox which will typically be hogging >200MB and you realize that running a Linux-based VM like this is amazingly efficient. I can move my environment between machines I have much more robust deployment workflow I can limit the VM to have exactly the same amount of RAM as the server I'll be hosting on. E.g., if I'm to be using a SliceHost 256MB slice, I would limit the RAM to 256MB. I can build a seperate environment for different hosts. If I wanted to host on Joyent, for example, I could build an Open Solaris VM Gems and other binaries won't need recompiling for your target environment It's "a good thing"™ to get to grips with the environment your Rails app is likely to be running on. Seeing as most, if not all, commercial Rails hosts run some sort of *nix derivative, you're going to want to be comfortable with the *nix environment.
{ "score": 5, "source": [ "https://Stackoverflow.com/questions/3408", "https://Stackoverflow.com", "https://Stackoverflow.com/users/514/" ] }
3,432
I know that you can insert multiple rows at once, is there a way to update multiple rows at once (as in, in one query) in MySQL? Edit:For example I have the following Name id Col1 Col2Row1 1 6 1Row2 2 2 3Row3 3 9 5Row4 4 16 8 I want to combine all the following Updates into one query UPDATE table SET Col1 = 1 WHERE id = 1;UPDATE table SET Col1 = 2 WHERE id = 2;UPDATE table SET Col2 = 3 WHERE id = 3;UPDATE table SET Col1 = 10 WHERE id = 4;UPDATE table SET Col2 = 12 WHERE id = 4;
Yes, that's possible - you can use INSERT ... ON DUPLICATE KEY UPDATE. Using your example: INSERT INTO table (id,Col1,Col2) VALUES (1,1,1),(2,2,3),(3,9,3),(4,10,12)ON DUPLICATE KEY UPDATE Col1=VALUES(Col1),Col2=VALUES(Col2);
{ "score": 10, "source": [ "https://Stackoverflow.com/questions/3432", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1384652/" ] }
3,437
We recently discovered that the Google Maps API does not play nicely with SSL. Fair enough, but what are some options for overcoming this that others have used effectively? Will the Maps API work over SSL (HTTPS)? At this time, the Maps API is not available over a secure (SSL) connection. If you are running the Maps API on a secure site, the browser may warn the user about non-secure objects on the screen. We have considered the following options Splitting the page so that credit card collection (the requirement for SSL) is not on the same page as the Google Map. Switching to another map provider, such as Virtual Earth. Rumor has it that they support SSL. Playing tricks with IFRAMEs. Sounds kludgy. Proxying the calls to Google. Sounds like a lot of overhead. Are there other options, or does anyone have insight into the options that we have considered?
I'd agree with the previous two answers that in this instance it may be better from a usability perspective to split the two functions into separate screens. You really want your users to be focussed on entering complete and accurate credit card information, and having a map on the same screen may be distracting. For the record though, Virtual Earth certainly does fully support SSL. To enable it you simple need to change the script reference from http:// to https:// and append &s=1 to the URL, e.g. <script src="http://dev.virtualearth.net/mapcontrol/mapcontrol.ashx?v=6.1" type="text/javascript"></script> becomes <script src="https://dev.virtualearth.net/mapcontrol/mapcontrol.ashx?v=6.1&s=1" type="text/javascript"></script>
{ "score": 5, "source": [ "https://Stackoverflow.com/questions/3437", "https://Stackoverflow.com", "https://Stackoverflow.com/users/308/" ] }
3,448
I've noticed a lot of sites, SO included, use XHTML as their mark-up language and then fail to adhere to the spec. Just browsing the source for SO there are missing closing tags for paragraphs, invalid elements, etc. So should tools (and developers) use the XHTML doctype if they are going to produce invalid mark up? And should browsers be more firm in their acceptance of poor mark-up? And before anyone shouts hypocrite, my blog has one piece of invalid mark-up involving the captha (or it did the last time I checked) which involves styling the noscript tag.
There are many reasons to use valid markup. My favorite is that it allows you to use validation as a form of regression testing, preventing the markup equivalent of "delta rot" from leading to real rendering problems once the errors reach some critical mass. And really, it's just plain sloppy to allow "lazy" errors like typos and mis-nested/unclosed tags to accumulate. Valid markup is one way to identify passionate programmers . There's also the issue of debugging: valid markup also gives you a stable baseline from which to work on the inevitable cross-browser compatibility woes. No web developer who values his time should begin debugging browser compatibility problems without first ensuring that the markup is at least syntactically valid—and any other invalid markup should have a good reason for being there. (Incidentally, stackoverflow.com fails both these tests, and suggestions to fix the problems were declined .) All of that said, to answer your specific question, it's probably not worthwhile to use one of the XHTML doctypes unless you plan to produce valid (or at least well-formed) markup. XHTML's primary advantages are derived from the fact that XHTML is XML, allowing it to be processed and transformed by tools and technologies that work with XML. If you don't plan to make your XHTML well-formed XML, then there's little point in choosing that doctype. The latest HTML 4 spec will probably do everything you need, and it's much more forgiving.
{ "score": 5, "source": [ "https://Stackoverflow.com/questions/3448", "https://Stackoverflow.com", "https://Stackoverflow.com/users/342/" ] }
3,452
How can I connect to a remote SQL server using Mac OS X? I don't really need a GUI, but it would be nice to have for the color coding and resultset grid. I'd rather not have to use a VM. Is there a SQL client for Mac OS X that works with MS SQL Server?
Let's work together on a canonical answer. Native Apps SQLPro for MSSQL Navicat Valentina Studio TablePlus Java-Based Oracle SQL Developer (free) SQuirrel SQL (free, open source) Razor SQL DB Visualizer DBeaver (free, open source) SQL Workbench/J (free, open source) JetBrains DataGrip Metabase (free, open source) Netbeans (free, open source, full development environment) Electron-Based Visual Studio Code with mssql extension Azure Data Studio SQLectron (TODO: Add others mentioned below)
{ "score": 9, "source": [ "https://Stackoverflow.com/questions/3452", "https://Stackoverflow.com", "https://Stackoverflow.com/users/437/" ] }
3,510
What is BODMAS and why is it useful in programming?
http://www.easymaths.com/What_on_earth_is_Bodmas.htm : What do you think the answer to 2 + 3 x 5 is? Is it (2 + 3) x 5 = 5 x 5 = 25 ? or 2 + (3 x 5) = 2 + 15 = 17 ? BODMAS can come to the rescue and give us rules to follow so that we always get the right answer: (B)rackets (O)rder (D)ivision (M)ultiplication (A)ddition (S)ubtraction According to BODMAS, multiplication should always be done before addition, therefore 17 is actually the correct answer according to BODMAS and will also be the answer which your calculator will give if you type in 2 + 3 x 5 . Why it is useful in programming? No idea, but i assume it's because you can get rid of some brackets? I am a quite defensive programmer, so my lines can look like this: result = (((i + 4) - (a + b)) * MAGIC_NUMBER) - ANOTHER_MAGIC_NUMBER; with BODMAS you can make this a bit clearer: result = (i + 4 - (a + b)) * MAGIC_NUMBER - ANOTHER_MAGIC_NUMBER; I think i'd still use the first variant - more brackets, but that way i do not have to learn yet another rule and i run into less risk of forgetting it and causing those weird hard to debug errors? Just guessing at that part though. Mike Stone EDIT: Fixed math as Gaius points out
{ "score": 5, "source": [ "https://Stackoverflow.com/questions/3510", "https://Stackoverflow.com", "https://Stackoverflow.com/users/383/" ] }
3,530
I have a Rakefile with a Rake task that I would normally call from the command line: rake blog:post Title I'd like to write a Ruby script that calls that Rake task multiple times, but the only solution I see is shelling out using `` (backticks) or system . What's the right way to do this?
from timocracy.com : require 'rake'def capture_stdout s = StringIO.new oldstdout = $stdout $stdout = s yield s.stringensure $stdout = oldstdoutendRake.application.rake_require 'metric_fetcher', ['../../lib/tasks']results = capture_stdout {Rake.application['metric_fetcher'].invoke}
{ "score": 7, "source": [ "https://Stackoverflow.com/questions/3530", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1388162/" ] }
3,585
I want to create my Rails application with MySQL, because I like it so much. How can I do that in the latest version of Rails instead of the default SQLite?
Normally, you would create a new Rails app using rails ProjectName To use MySQL, use rails new ProjectName -d mysql
{ "score": 8, "source": [ "https://Stackoverflow.com/questions/3585", "https://Stackoverflow.com", "https://Stackoverflow.com/users/124/" ] }
3,589
I need to create a backup of a SQL Server 2005 Database that's only the structure...no records, just the schema. Is there any way to do this? EDIT: I'm trying to create a backup file to use with old processes, so a script wouldn't work for my purposes, sorry
Use a 3 step process: Generate a script from the working database Create a new database from that script Create a backup of the new database
{ "score": 5, "source": [ "https://Stackoverflow.com/questions/3589", "https://Stackoverflow.com", "https://Stackoverflow.com/users/44/" ] }
3,607
I've got TotroiseSVN installed and have a majority of my repositories checking in and out from C:\subversion\ and a couple checking in and out from a network share (I forgot about this when I originally posted this question) . This means that I don't have a "subversion" server per-se. How do I integrate TortoiseSVN and Fogbugz? Edit: inserted italics
I've been investigating this issue and have managed to get it working. There are a couple of minor problems but they can be worked-around. There are 3 distinct parts to this problem, as follows: The TortoiseSVN part - getting TortoiseSVN to insert the Bugid and hyperlink in the svn log The FogBugz part - getting FogBugz to insert the SVN info and corresponding links The WebSVN part - ensuring the links from FogBugz actually work Instructions for part 1 are in another answer, although it actually does more than required. The stuff about the hooks is actually for part 2, and as is pointed out - it doesn't work "out of the box" Just to confirm, we are looking at using TortoiseSVN WITHOUT an SVN server (ie. file-based repositories) I'm accessing the repositories using UNC paths, but it also works for local drives or mapped drives. All of this works with TortoiseSVN v1.5.3 and SVN Server v1.5.2 (You need to install SVN Server because part 2 needs svnlook.exe which is in the server package. You don't actually configure it to work as an SVN Server) It may even be possible to just copy svnlook.exe from another computer and put it somewhere in your path. Part 1 - TortoiseSVN Creating the TortoiseSVN properties is all that is required in order to get the links in the SVN log. Previous instructions work fine, I'll quote them here for convenience: Configure the Properties Right click on the root directory of the checked out project you want to work with. Select "TortoiseSVN -> Properties" Add five property value pairs by clicking "New..." and inserting the following in "Property Name" and "Property Value" respectively: (make sure you tick "Apply property recursively" for each one) bugtraq:label BugzID:bugtraq:message BugzID: %BUGID%bugtraq:number truebugtraq:url http://[your fogbugz URL here]/default.asp?%BUGID%bugtraq:warnifnoissue false Click "OK" As Jeff says, you'll need to do that for each working copy, so follow his instructions for migrating the properties. That's it. TortoiseSVN will now add a link to the corresponding FogBugz bugID when you commit. If that's all you want, you can stop here. Part 2 - FogBugz For this to work we need to set up the hook scripts. Basically the batch file is called after each commit, and this in turn calls the VBS script which does the submission to FogBugz. The VBS script actually works fine in this situation so we don't need to modify it. The problem is that the batch file is written to work as a server hook, but we need a client hook. SVN server calls the post-commit hook with these parameters: <repository-path> <revision> TortoiseSVN calls the post-commit hook with these parameters: <affected-files> <depth> <messagefile> <revision> <error> <working-copy-path> So that's why it doesn't work - the parameters are wrong. We need to amend the batch file so it passes the correct parameters to the VBS script. You'll notice that TSVN doesn't pass the repository path, which is a problem, but it does work in the following circumstances: The repository name and working copy name are the same You do the commit at the root of the working copy, not a subfolder. I'm going to see if I can fix this problem and will post back here if I do. Here's my amended batch file which does work (please excuse the excessive comments...) You'll need to set the hook and repository directories to match your setup. rem @echo offrem SubVersion -> FogBugz post-commit hook filerem Put this into the Hooks directory in your subversion repositoryrem along with the logBugDataSVN.vbs filerem TSVN calls this with args <PATH> <DEPTH> <MESSAGEFILE> <REVISION> <ERROR> <CWD>rem The ones we're interested in are <REVISION> and <CWD> which are %4 and %6rem YOU NEED TO EDIT THE LINE WHICH SETS RepoRoot TO POINT AT THE DIRECTORY rem THAT CONTAINS YOUR REPOSITORIES AND ALSO YOU MUST SET THE HOOKS DIRECTORYsetlocalrem debuggingrem echo %1 %2 %3 %4 %5 %6 > c:\temp\test.txtrem Set Hooks directory location (no trailing slash)set HooksDir=\\myserver\svn\hooksrem Set Repo Root location (ie. the directory containing all the repos)rem (no trailing slash)set RepoRoot=\\myserver\svnrem Build full repo locationset Repo=%RepoRoot%\%~n6rem debuggingrem echo %Repo% >> c:\temp\test.txtrem Grab the last two digits of the revision numberrem and append them to the log of svn changesrem to avoid simultaneous commit scenarios causing overwritesset ChangeFileSuffix=%~4set LogSvnChangeFile=svn%ChangeFileSuffix:~-2,2%.txtset LogBugDataScript=logBugDataSVN.vbsset ScriptCommand=cscriptrem Could remove the need for svnlook on the client since TSVN rem provides as parameters the info we need to call the script.rem However, it's in a slightly different format than the script is expectingrem for parsing, therefore we would have to amend the script too, so I won't bother.rem @echo onsvnlook changed -r %4 %Repo% > %temp%\%LogSvnChangeFile%svnlook log -r %4 %Repo% | %ScriptCommand% %HooksDir%\%LogBugDataScript% %4 %temp%\%LogSvnChangeFile% %~n6del %temp%\%LogSvnChangeFile%endlocal I'm going to assume the repositories are at \\myserver\svn\ and working copies are all under `C:\Projects\ Go into your FogBugz account and click Extras -> Configure Source Control Integration Download the VBScript file for Subversion (don't bother with the batch file) Create a folder to store the hook scripts. I put it in the same folder as my repositories. eg. \\myserver\svn\hooks\ Rename VBscript to remove the .safe at the end of the filename. Save my version of the batch file in your hooks directory, as post-commit-tsvn.bat Right click on any directory. Select "TortoiseSVN > Settings" (in the right click menu from the last step) Select "Hook Scripts" Click "Add" and set the properties as follows: Hook Type: Post-Commit Hook Working Copy Path: C:\Projects (or whatever your root directory for all of your projects is.) Command Line To Execute: \\myserver\svn\hooks\post-commit-tsvn.bat (this needs to point to wherever you put your hooks directory in step 3) Tick "Wait for the script to finish" Click OK twice. Next time you commit and enter a Bugid, it will be submitted to FogBugz. The links won't work but at least the revision info is there and you can manually look up the log in TortoiseSVN. NOTE: You'll notice that the repository root is hard-coded into the batch file. As a result, if you check out from repositories that don't have the same root (eg. one on local drive and one on network) then you'll need to use 2 batch files and 2 corresponding entries under Hook Scripts in the TSVN settings. The way to do this would be to have 2 separate Working Copy trees - one for each repository root. Part 3 - WebSVN Errr, I haven't done this :-) From reading the WebSVN docs, it seems that WebSVN doesn't actually integrate with the SVN server, it just behaves like any other SVN client but presents a web interface. In theory then it should work fine with a file-based repository. I haven't tried it though.
{ "score": 5, "source": [ "https://Stackoverflow.com/questions/3607", "https://Stackoverflow.com", "https://Stackoverflow.com/users/58/" ] }
3,654
When developing a new web based application which version of html should you aim for? EDIT: cool I was just attempting to get a feel from others I tend to use XHTML 1.0 Strict in my own work and Transitional when others are involved in the content creation. I marked the first XHTML 1.0 Transitional post as the 'correct answer' but believe strongly that all the answers given at that point where equally valid.
HTML 4.01. There is absolutely no reason to use XHTML for anything but experimental or academic problems that you only want to run on the 'obscure' web browsers. XHTML Transitional is completely pointless even to those browsers, so I'm not sure why anyone would aim for that. It's actually pretty alarming that a number of people would recommend that. I'd say aiming for HTML 4.01 is the most predictable, but Teifion is right really, "anything that renders your page will do". in response to Michael Stum : XHTML is XML based, so it allows easier parsing and you can also use the XML Components of most IDEs to programatically query and insert stuff. This is certainly not true. A lot of XHTML on the web (if not most) does not conform to XML validity (and it needn't - it's not being sent as XML). Trying to treat this like XML when dealing with it is just going to earn you a lot of headaches. This page on Stack Overflow, for instance, will generate errors with many unforgiving XML tools for having invalid mark-up.
{ "score": 5, "source": [ "https://Stackoverflow.com/questions/3654", "https://Stackoverflow.com", "https://Stackoverflow.com/users/269/" ] }
3,667
We are currently using a somewhat complicated deployment setup that involves a remote SVN server, 3 SVN branches for DEV, STAGE, and PROD, promoting code between them through patches, etc. I wonder what do you use for deployment in a small dev team situation?
trunk for development, and a branch (production) for the production stuff. On my local machine, I have a VirtualHost that points to the trunk branch, to test my changes. Any commit to trunk triggers a commit hook that does an svn export and sync to the online server's dev URL - so if the site is stackoverflow.com then this hook automatically updates dev.stackoverflow.com Then I use svnmerge to merge selected patches from trunk to production in my local checkouts. I have a VirtualHost again on my local machine pointing to the production branch. When I commit the merged changes to the production branch, again an SVN export hook updates the production (live) export and the site is live!
{ "score": 5, "source": [ "https://Stackoverflow.com/questions/3667", "https://Stackoverflow.com", "https://Stackoverflow.com/users/556/" ] }
3,713
I'm writing a web page in ASP.NET. I have some JavaScript code, and I have a submit button with a click event. Is it possible to call a method I created in ASP with JavaScript's click event?
Well, if you don't want to do it using Ajax or any other way and just want a normal ASP.NET postback to happen, here is how you do it (without using any other libraries): It is a little tricky though... :) i. In your code file (assuming you are using C# and .NET 2.0 or later) add the following Interface to your Page class to make it look like public partial class Default : System.Web.UI.Page, IPostBackEventHandler{} ii. This should add (using Tab - Tab ) this function to your code file: public void RaisePostBackEvent(string eventArgument) { } iii. In your onclick event in JavaScript, write the following code: var pageId = '<%= Page.ClientID %>';__doPostBack(pageId, argumentString); This will call the 'RaisePostBackEvent' method in your code file with the 'eventArgument' as the 'argumentString' you passed from the JavaScript. Now, you can call any other event you like. P.S: That is 'underscore-underscore-doPostBack' ... And, there should be no space in that sequence... Somehow the WMD does not allow me to write to underscores followed by a character!
{ "score": 8, "source": [ "https://Stackoverflow.com/questions/3713", "https://Stackoverflow.com", "https://Stackoverflow.com/users/557/" ] }
3,725
I'm writing an application that is basically just a preferences dialog, much like the tree-view preferences dialog that Visual Studio itself uses. The function of the application is simply a pass-through for data from a serial device to a file. It performs many, many transformations on the data before writing it to the file, so the GUI for the application is simply all the settings that dictate what those transformations should be. What's the best way to go about designing/coding a tree-view preferences dialog? The way I've been going about it is building the main window with a docked tree control on the left. Then I have been creating container controls that correspond to each node of the tree. When a node is selected, the app brings that node's corresponding container control to the front, moves it to the right position, and maximizes it in the main window. This seems really, really clunky while designing it. It basically means I have tons of container controls beyond the edge of the main window during design time that I have to keep scrolling the main window over to in order to work with them. I don't know if this totally makes sense the way I'm writing this, but maybe this visual for what I'm talking about will make more sense: Basically I have to work with this huge form, with container controls all over the place, and then do a bunch of run-time reformatting to make it all work. This seems like a lot of extra work. Am I doing this in a totally stupid way? Is there some "obvious" easier way of doing this that I'm missing?
A tidier way is to create separate forms for each 'pane' and, in each form constructor, set this.TopLevel = false;this.FormBorderStyle = FormBorderStyle.None;this.Dock = DockStyle.Fill; That way, each of these forms can be laid out in its own designer, instantiated one or more times at runtime, and added to the empty area like a normal control. Perhaps the main form could use a SplitContainer with a static TreeView in one panel, and space to add these forms in the other. Once they are added, they could be flipped through using Hide/Show or BringToFront/SendToBack methods. SeparateForm f = new SeparateForm(); MainFormSplitContainer.Panel2.Controls.Add(f); f.Show();
{ "score": 5, "source": [ "https://Stackoverflow.com/questions/3725", "https://Stackoverflow.com", "https://Stackoverflow.com/users/551/" ] }
3,748
So I'm using an app that stores images heavily in the DB. What's your outlook on this? I'm more of a type to store the location in the filesystem, than store it directly in the DB. What do you think are the pros/cons?
I'm in charge of some applications that manage many TB of images. We've found that storing file paths in the database to be best. There are a couple of issues: database storage is usually more expensive than file system storage you can super-accelerate file system access with standard off the shelf products for example, many web servers use the operating system's sendfile() system call to asynchronously send a file directly from the file system to the network interface. Images stored in a database don't benefit from this optimization. things like web servers, etc, need no special coding or processing to access images in the file system databases win out where transactional integrity between the image and metadata are important. it is more complex to manage integrity between db metadata and file system data it is difficult (within the context of a web application) to guarantee data has been flushed to disk on the filesystem
{ "score": 8, "source": [ "https://Stackoverflow.com/questions/3748", "https://Stackoverflow.com", "https://Stackoverflow.com/users/514/" ] }
3,781
When prototyping initial GUI functionality with a customer is it better to use a pen/paper drawing or to mock something up using a tool and show them that ? The argument against a tool generated design being that the customer can sometimes focus on the low-level specifics of the mock-up rather than taking a higher level functional view of the GUI overall.
Always start with paper or paper-like mock-ups first. You do not want to fall into a trap of giving the impression of completeness when the back-end is completely hollow. A polished prototype or pixel-perfect example puts too much emphasis on the design. With an obvious sketch, you have a better shot of discussing desired functionality and content rather than colors, photos, and other stylistic matters. There will be time for that discussion later in the project. Jeff discusses paper prototyping in his Coding Horror article UI-First Software Development Click the "Watch a video!" link at twitter.com to see an interesting take on the idea from Common Craft .
{ "score": 5, "source": [ "https://Stackoverflow.com/questions/3781", "https://Stackoverflow.com", "https://Stackoverflow.com/users/381/" ] }
3,793
What's the best way to get the contents of the mixed body element in the code below? The element might contain either XHTML or text, but I just want its contents in string form. The XmlElement type has the InnerXml property which is exactly what I'm after. The code as written almost does what I want, but includes the surrounding <body> ... </body> element, which I don't want. XDocument doc = XDocument.Load(new StreamReader(s));var templates = from t in doc.Descendants("template") where t.Attribute("name").Value == templateName select new { Subject = t.Element("subject").Value, Body = t.Element("body").ToString() };
I wanted to see which of these suggested solutions performed best, so I ran some comparative tests. Out of interest, I also compared the LINQ methods to the plain old System.Xml method suggested by Greg. The variation was interesting and not what I expected, with the slowest methods being more than 3 times slower than the fastest . The results ordered by fastest to slowest: CreateReader - Instance Hunter (0.113 seconds) Plain old System.Xml - Greg Hurlman (0.134 seconds) Aggregate with string concatenation - Mike Powell (0.324 seconds) StringBuilder - Vin (0.333 seconds) String.Join on array - Terry (0.360 seconds) String.Concat on array - Marcin Kosieradzki (0.364) Method I used a single XML document with 20 identical nodes (called 'hint'): <hint> <strong>Thinking of using a fake address?</strong> <br /> Please don't. If we can't verify your address we might just have to reject your application.</hint> The numbers shown as seconds above are the result of extracting the "inner XML" of the 20 nodes, 1000 times in a row, and taking the average (mean) of 5 runs. I didn't include the time it took to load and parse the XML into an XmlDocument (for the System.Xml method) or XDocument (for all the others). The LINQ algorithms I used were: (C# - all take an XElement "parent" and return the inner XML string) CreateReader: var reader = parent.CreateReader();reader.MoveToContent();return reader.ReadInnerXml(); Aggregate with string concatenation: return parent.Nodes().Aggregate("", (b, node) => b += node.ToString()); StringBuilder: StringBuilder sb = new StringBuilder();foreach(var node in parent.Nodes()) { sb.Append(node.ToString());}return sb.ToString(); String.Join on array: return String.Join("", parent.Nodes().Select(x => x.ToString()).ToArray()); String.Concat on array: return String.Concat(parent.Nodes().Select(x => x.ToString()).ToArray()); I haven't shown the "Plain old System.Xml" algorithm here as it's just calling .InnerXml on nodes. Conclusion If performance is important (e.g. lots of XML, parsed frequently), I'd use Daniel's CreateReader method every time . If you're just doing a few queries, you might want to use Mike's more concise Aggregate method. If you're using XML on large elements with lots of nodes (maybe 100's), you'd probably start to see the benefit of using StringBuilder over the Aggregate method, but not over CreateReader . I don't think the Join and Concat methods would ever be more efficient in these conditions because of the penalty of converting a large list to a large array (even obvious here with smaller lists).
{ "score": 9, "source": [ "https://Stackoverflow.com/questions/3793", "https://Stackoverflow.com", "https://Stackoverflow.com/users/205/" ] }
3,801
The discussion of Dual vs. Quadcore is as old as the Quadcores itself and the answer is usually "it depends on your scenario". So here the scenario is a Web Server (Windows 2003 (not sure if x32 or x64), 4 GB RAM, IIS, ASP.net 3.0). My impression is that the CPU in a Webserver does not need to be THAT fast because requests are usually rather lightweight, so having more (slower) cores should be a better choice as we got many small requests. But since I do not have much experience with IIS load balancing and since I don't want to spend a lot of money only to find out I've made the wrong choice, can someone who has a bit more experience comment on whether or not More Slower or Fewer Faster cores is better?
For something like a webserver, dividing up the tasks of handling each connection is (relatively) easy. I say it's safe to say that web servers is one of the most common (and ironed out) uses of parallel code. And since you are able to split up much of the processing into multiple discrete threads, more cores actually does benefit you. This is one of the big reasons why shared hosting is even possible. If server software like IIS and Apache couldn't run requests in parallel it would mean that every page request would have to be dished out in a queue fashion...likely making load times unbearably slow. This also why high end server Operating Systems like Windows 2008 Server Enterprise support something like 64 cores and 2TB of RAM. These are applications that can actually take advantage of that many cores. Also, since each request is likely has low CPU load, you can probably (for some applications) get away with more slower cores. But obviously having each core faster can mean being able to get each task done quicker and, in theory, handle more tasks and more server requests.
{ "score": 5, "source": [ "https://Stackoverflow.com/questions/3801", "https://Stackoverflow.com", "https://Stackoverflow.com/users/91/" ] }
3,823
One simple method I've used in the past is basically just creating a second table whose structure mirrors the one I want to audit, and then create an update/delete trigger on the main table. Before a record is updated/deleted, the current state is saved to the audit table via the trigger. While effective, the data in the audit table is not the most useful or simple to report off of. I'm wondering if anyone has a better method for auditing data changes? There shouldn't be too many updates of these records, but it is highly sensitive information, so it is important to the customer that all changes are audited and easily reported on.
How much writing vs. reading of this table(s) do you expect? I've used a single audit table, with columns for Table, Column, OldValue, NewValue, User, and ChangeDateTime - generic enough to work with any other changes in the DB, and while a LOT of data got written to that table, reports on that data were sparse enough that they could be run at low-use periods of the day. Added: If the amount of data vs. reporting is a concern, the audit table could be replicated to a read-only database server, allowing you to run reports whenever necessary without bogging down the master server from doing their work.
{ "score": 5, "source": [ "https://Stackoverflow.com/questions/3823", "https://Stackoverflow.com", "https://Stackoverflow.com/users/423/" ] }
3,839
I'm trying out the following query: SELECT A,B,C FROM table WHERE field LIKE 'query%'UNIONSELECT A,B,C FROM table WHERE field LIKE '%query'UNIONSELECT A,B,C FROM table WHERE field LIKE '%query%'GROUP BY B ORDER BY B ASC LIMIT 5 That's three queries stuck together, kinda sorta. However, the result set that comes back reflects results from query #3 before the results from query #1 which is undesired. Is there any way to prioritize these so that results come as all for query #1, then all for query #2 then all for query #3? I don't want to do this in PHP just yet (not to mention having to control for results that showed up in the first query not to show in the second and so forth).
Maybe you should try including a fourth column, stating the table it came from, and then order and group by it: SELECT A,B,C, "query 1" as origin FROM table WHERE field LIKE 'query%'UNIONSELECT A,B,C, "query 2" as origin FROM table WHERE field LIKE '%query'UNIONSELECT A,B,C, "query 3" as origin FROM table WHERE field LIKE '%query%'GROUP BY origin, B ORDER BY origin, B ASC LIMIT 5
{ "score": 5, "source": [ "https://Stackoverflow.com/questions/3839", "https://Stackoverflow.com", "https://Stackoverflow.com/users/547/" ] }
3,856
I wrote a component that displays a filename, a thumbnail and has a button to load/play the file. The component is databound to a repeater. How can I make it so that the button event fires to the main application and tells it which file to play?
Maybe you should try including a fourth column, stating the table it came from, and then order and group by it: SELECT A,B,C, "query 1" as origin FROM table WHERE field LIKE 'query%'UNIONSELECT A,B,C, "query 2" as origin FROM table WHERE field LIKE '%query'UNIONSELECT A,B,C, "query 3" as origin FROM table WHERE field LIKE '%query%'GROUP BY origin, B ORDER BY origin, B ASC LIMIT 5
{ "score": 5, "source": [ "https://Stackoverflow.com/questions/3856", "https://Stackoverflow.com", "https://Stackoverflow.com/users/26/" ] }
3,859
After being told by at least 10 people on SO that version control was a good thing even if it's just me I now have a followup question. What is the difference between all the different types of version control and is there a guide that anybody knows of for version control that's very simple and easy to understand?
Eric Sink has a good overview of source control . There are also some existing questions here on SO.
{ "score": 5, "source": [ "https://Stackoverflow.com/questions/3859", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1384652/" ] }
3,881
I have a simple setter method for a property and null is not appropriate for this particular property. I have always been torn in this situation: should I throw an IllegalArgumentException , or a NullPointerException ? From the javadocs, both seem appropriate. Is there some kind of an understood standard? Or is this just one of those things that you should do whatever you prefer and both are really correct?
It seems like an IllegalArgumentException is called for if you don't want null to be an allowed value, and the NullPointerException would be thrown if you were trying to use a variable that turns out to be null .
{ "score": 9, "source": [ "https://Stackoverflow.com/questions/3881", "https://Stackoverflow.com", "https://Stackoverflow.com/users/122/" ] }
3,927
What profilers have you used when working with .net programs, and which would you particularly recommend?
I have used JetBrains dotTrace and Redgate ANTS extensively. They are fairly similar in features and price. They both offer useful performance profiling and quite basic memory profiling. dotTrace integrates with Resharper, which is really convenient, as you can profile the performance of a unit test with one click from the IDE. However, dotTrace often seems to give spurious results (e.g. saying that a method took several years to run) I prefer the way that ANTS presents the profiling results. It shows you the source code and to the left of each line tells you how long it took to run. dotTrace just has a tree view. EQATEC profiler is quite basic and requires you to compile special instrumented versions of your assemblies which can then be run in the EQATEC profiler. It is, however, free. Overall I prefer ANTS for performance profiling, although if you use Resharper then the integration of dotTrace is a killer feature and means it beats ANTS in usability. The free Microsoft CLR Profiler ( .Net framework 2.0 / .Net Framework 4.0 ) is all you need for .NET memory profiling. 2011 Update: The Scitech memory profiler has quite a basic UI but lots of useful information, including some information on unmanaged memory which dotTrace and ANTS lack - you might find it useful if you are doing COM interop, but I have yet to find any profiler that makes COM memory issues easy to diagnose - you usually have to break out windbg.exe . The ANTS profiler has come on in leaps and bounds in the last few years, and its memory profiler has some truly useful features which now pushed it ahead of dotTrace as a package in my estimation. I'm lucky enough to have licenses for both, but if you are going to buy one .Net profiler for both performance and memory, make it ANTS.
{ "score": 9, "source": [ "https://Stackoverflow.com/questions/3927", "https://Stackoverflow.com", "https://Stackoverflow.com/users/121/" ] }
3,978
In a language such as (since I'm working in it now) PHP, which supports procedural and object-oriented paradigms. Is there a good rule of thumb for determining which paradigm best suits a new project? If not, how can you make the decision?
It all depends on the problem you're trying to solve. Obviously you can solve any problem in either style (procedural or OO), but you usually can figure out in the planning stages before you start writing code which style suits you better. Some people like to write up use cases and if they see a lot of the same nouns showing up over and over again (e.g., a person withdraws money from the bank), then they go the OO route and use the nouns as their objects. Conversely, if you don't see a lot of nouns and there's really more verbs going on, then procedural or functional may be the way to go. Steve Yegge has a great but long post as usual that touches on this from a different perspective that you may find helpful as well.
{ "score": 5, "source": [ "https://Stackoverflow.com/questions/3978", "https://Stackoverflow.com", "https://Stackoverflow.com/users/572/" ] }
4,034
What is the best way to support multiple languages for the interface in an ASP.NET MVC application? I've seen people use resource files for other applications. Is this still the best way?
If you're using the default view engines, then local resources work in the views. However, if you need to grab resource strings within a controller action, you can't get local resources, and have to use global resources. This makes sense when you think about it because local resources are local to an aspx page and in the controller, you haven't even selected your view.
{ "score": 6, "source": [ "https://Stackoverflow.com/questions/4034", "https://Stackoverflow.com", "https://Stackoverflow.com/users/571/" ] }
4,046
I'm trying to convince my providers to use ANT instead of Rational Application Development so anyone can recompile, recheck, redeploy the solution anyplace, anytime, anyhow. :P I started a build.xml for a project that generates a JAR file but stopped there and I need real examples to compare notes. My good friends! I don't have anyone close to chat about this! This is my build.xml so far. (*) I edited my question based in the suggestion of to use pastebin.ca
My Environment: Fedora 8; WAS 6.1 (as installed with Rational Application Developer 7) The documentation is very poor in this area and there is a dearth of practical examples. Using the WebSphere Application Server (WAS) Ant tasks To run as described here, you need to run them from your server profile bin directory using the ws_ant.sh or ws_ant.bat commands. <?xml version="1.0"?><project name="project" default="wasListApps" basedir="."> <description> Script for listing installed apps. Example run from: /opt/IBM/SDP70/runtimes/base_v61/profiles/AppSrv01/bin </description> <property name="was_home" value="/opt/IBM/SDP70/runtimes/base_v61/"> </property> <path id="was.runtime"> <fileset dir="${was_home}/lib"> <include name="**/*.jar" /> </fileset> <fileset dir="${was_home}/plugins"> <include name="**/*.jar" /> </fileset> </path> <property name="was_cp" value="${toString:was.runtime}"></property> <property environment="env"></property> <target name="wasListApps"> <taskdef name="wsListApp" classname="com.ibm.websphere.ant.tasks.ListApplications" classpath="${was_cp}"> </taskdef> <wsListApp wasHome="${was_home}" /> </target></project> Command: ./ws_ant.sh -buildfile ~/IBM/rationalsdp7.0/workspace/mywebappDeploy/applist.xml A Deployment Script <?xml version="1.0"?><project name="project" default="default" basedir="."><description>Build/Deploy an EAR to WebSphere Application Server 6.1</description> <property name="was_home" value="/opt/IBM/SDP70/runtimes/base_v61/" /> <path id="was.runtime"> <fileset dir="${was_home}/lib"> <include name="**/*.jar" /> </fileset> <fileset dir="${was_home}/plugins"> <include name="**/*.jar" /> </fileset> </path> <property name="was_cp" value="${toString:was.runtime}" /> <property environment="env" /> <property name="ear" value="${env.HOME}/IBM/rationalsdp7.0/workspace/mywebappDeploy/mywebappEAR.ear" /> <target name="default" depends="deployEar"> </target> <target name="generateWar" depends="compileWarClasses"> <jar destfile="mywebapp.war"> <fileset dir="../mywebapp/WebContent"> </fileset> </jar> </target> <target name="compileWarClasses"> <echo message="was_cp=${was_cp}" /> <javac srcdir="../mywebapp/src" destdir="../mywebapp/WebContent/WEB-INF/classes" classpath="${was_cp}"> </javac> </target> <target name="generateEar" depends="generateWar"> <mkdir dir="./earbin/META-INF"/> <move file="mywebapp.war" todir="./earbin" /> <copy file="../mywebappEAR/META-INF/application.xml" todir="./earbin/META-INF" /> <jar destfile="${ear}"> <fileset dir="./earbin" /> </jar> </target> <!-- http://publib.boulder.ibm.com/infocenter/wasinfo/v6r1/index.jsp?topic=/com.ibm.websphere.javadoc.doc/public_html/api/com/ibm/websphere/ant/tasks/package-summary.html --> <target name="deployEar" depends="generateEar"> <taskdef name="wsInstallApp" classname="com.ibm.websphere.ant.tasks.InstallApplication" classpath="${was_cp}"/> <wsInstallApp ear="${ear}" failonerror="true" debug="true" taskname="" washome="${was_home}" /> </target></project> Notes: You can only run this once! You cannot install if the app name is in use - see other tasks like wsUninstallApp It probably won't start the app either You need to run this on the server and the script is quite fragile Alternatives I would probably use Java Management Extensions (JMX). You could write a file-upload servlet that accepts an EAR and uses the deployment MBeans to deploy the EAR on the server. You would just POST the file over HTTP. This would avoid any WAS API dependencies on your dev/build machine and could be independent of any one project.
{ "score": 5, "source": [ "https://Stackoverflow.com/questions/4046", "https://Stackoverflow.com", "https://Stackoverflow.com/users/527/" ] }
4,051
In C can I pass a multidimensional array to a function as a single argument when I don't know what the dimensions of the array are going to be? Besides, my multidimensional array may contain types other than strings.
You can do this with any data type. Simply make it a pointer-to-pointer: typedef struct { int myint; char* mystring;} data;data** array; But don't forget you still have to malloc the variable, and it does get a bit complex: //initializeint x,y,w,h;w = 10; //width of arrayh = 20; //height of array//malloc the 'y' dimensionarray = malloc(sizeof(data*) * h);//iterate over 'y' dimensionfor(y=0;y<h;y++){ //malloc the 'x' dimension array[y] = malloc(sizeof(data) * w); //iterate over the 'x' dimension for(x=0;x<w;x++){ //malloc the string in the data structure array[y][x].mystring = malloc(50); //50 chars //initialize array[y][x].myint = 6; strcpy(array[y][x].mystring, "w00t"); }} The code to deallocate the structure looks similar - don't forget to call free() on everything you malloced! (Also, in robust applications you should check the return of malloc() .) Now let's say you want to pass this to a function. You can still use the double pointer, because you probably want to do manipulations on the data structure, not the pointer to pointers of data structures: int whatsMyInt(data** arrayPtr, int x, int y){ return arrayPtr[y][x].myint;} Call this function with: printf("My int is %d.\n", whatsMyInt(array, 2, 4)); Output: My int is 6.
{ "score": 6, "source": [ "https://Stackoverflow.com/questions/4051", "https://Stackoverflow.com", "https://Stackoverflow.com/users/381/" ] }
4,052
I am trying to enable Full-text indexing in SQL Server 2005 Express. I am running this on my laptop with Vista Ultimate. I understand that the standard version of SQL Server Express does not have full-text indexing. I have already downloaded and installed "Microsoft SQL Server 2005 Express Edition with Advanced Services Service Pack 2" ( download ). I have also ensured that both the "SQL Server (instance)" and "SQL Server FullText Search (instance)" services are running on the same account which is "Network Service". I have also selected the option to "Use full-text indexing" in the Database Properties > Files area. I can run the sql query "SELECT fulltextserviceproperty('IsFulltextInstalled');" and return 1. The problem I am having is that when I have my table open in design view and select "Manage FullText Index"; the full-text index window displays the message... "Creation of the full-text index is not available. Check that you have the correct permissions or that full-text catalogs are defined." Any ideas on what to check or where to go next?
sp_fulltext_database 'enable'CREATE FULLTEXT CATALOG [myFullText]WITH ACCENT_SENSITIVITY = ONCREATE FULLTEXT INDEX ON [dbo].[tblName] KEY INDEX [PK_something] ON [myFullText] WITH CHANGE_TRACKING AUTOALTER FULLTEXT INDEX ON [dbo].[otherTable] ADD ([Text])ALTER FULLTEXT INDEX ON [dbo].[teyOtherTable] ENABLE
{ "score": 5, "source": [ "https://Stackoverflow.com/questions/4052", "https://Stackoverflow.com", "https://Stackoverflow.com/users/576/" ] }
4,080
What code analysis tools do you use on your Java projects? I am interested in all kinds static code analysis tools (FindBugs, PMD, and any others) code coverage tools (Cobertura, Emma, and any others) any other instrumentation-based tools anything else, if I'm missing something If applicable, also state what build tools you use and how well these tools integrate with both your IDEs and build tools. If a tool is only available a specific way (as an IDE plugin, or, say, a build tool plugin) that information is also worth noting.
For static analysis tools I often use CPD, PMD , FindBugs , and Checkstyle . CPD is the PMD "Copy/Paste Detector" tool. I was using PMD for a little while before I noticed the "Finding Duplicated Code" link on the PMD web page . I'd like to point out that these tools can sometimes be extended beyond their "out-of-the-box" set of rules. And not just because they're open source so that you can rewrite them. Some of these tools come with applications or "hooks" that allow them to be extended. For example, PMD comes with the "designer" tool that allows you to create new rules. Also, Checkstyle has the DescendantToken check that has properties that allow for substantial customization. I integrate these tools with an Ant-based build . You can follow the link to see my commented configuration. In addition to the simple integration into the build, I find it helpful to configure the tools to be somewhat "integrated" in a couple of other ways. Namely, report generation and warning suppression uniformity. I'd like to add these aspects to this discussion (which should probably have the "static-analysis" tag also): how are folks configuring these tools to create a "unified" solution? (I've asked this question separately here ) First, for warning reports, I transform the output so that each warning has the simple format: /absolute-path/filename:line-number:column-number: warning(tool-name): message This is often called the "Emacs format," but even if you aren't using Emacs, it's a reasonable format for homogenizing reports. For example: /project/src/com/example/Foo.java:425:9: warning(Checkstyle):Missing a Javadoc comment. My warning format transformations are done by my Ant script with Ant filterchains . The second "integration" that I do is for warning suppression. By default, each tool supports comments or an annotation (or both) that you can place in your code to silence a warning that you want to ignore. But these various warning suppression requests do not have a consistent look which seems somewhat silly. When you're suppressing a warning, you're suppressing a warning, so why not always write " SuppressWarning ?" For example, PMD's default configuration suppresses warning generation on lines of code with the string " NOPMD " in a comment. Also, PMD supports Java's @SuppressWarnings annotation. I configure PMD to use comments containing " SuppressWarning(PMD. " instead of NOPMD so that PMD suppressions look alike. I fill in the particular rule that is violated when using the comment style suppression: // SuppressWarnings(PMD.PreserveStackTrace) justification: (false positive) exceptions are chained Only the " SuppressWarnings(PMD. " part is significant for a comment, but it is consistent with PMD's support for the @SuppressWarning annotation which does recognize individual rule violations by name: @SuppressWarnings("PMD.CompareObjectsWithEquals") // justification: identity comparision intended Similarly, Checkstyle suppresses warning generation between pairs of comments (no annotation support is provided). By default, comments to turn Checkstyle off and on contain the strings CHECKSTYLE:OFF and CHECKSTYLE:ON , respectively. Changing this configuration (with Checkstyle's "SuppressionCommentFilter") to use the strings " BEGIN SuppressWarnings(CheckStyle. " and " END SuppressWarnings(CheckStyle. " makes the controls look more like PMD: // BEGIN SuppressWarnings(Checkstyle.HiddenField) justification: "Effective Java," 2nd ed., Bloch, Item 2 // END SuppressWarnings(Checkstyle.HiddenField) With Checkstyle comments, the particular check violation ( HiddenField ) is significant because each check has its own " BEGIN/END " comment pair. FindBugs also supports warning generation suppression with a @SuppressWarnings annotation, so no further configuration is required to achieve some level of uniformity with other tools. Unfortunately, Findbugs has to support a custom @SuppressWarnings annotation because the built-in Java @SuppressWarnings annotation has a SOURCE retention policy which is not strong enough to retain the annotation in the class file where FindBugs needs it. I fully qualify FindBugs warnings suppressions to avoid clashing with Java's @SuppressWarnings annotation: @edu.umd.cs.findbugs.annotations.SuppressWarnings("UWF_FIELD_NOT_INITIALIZED_IN_CONSTRUCTOR") These techniques makes things look reasonably consistent across tools. Note that having each warning suppression contain the string " SuppressWarnings " makes it easy to run a simple search to find all instances for all tools over an entire code base.
{ "score": 7, "source": [ "https://Stackoverflow.com/questions/4080", "https://Stackoverflow.com", "https://Stackoverflow.com/users/235/" ] }
4,138
What is the best SVN Ignore Pattern should TortoiseSVN have for a VB.NET solution?
this is what I use for C# w/resharper, should work just the same with vb.net: build deploy */bin */bin/* obj *.dll *.pdb *.user *.suo _ReSharper* *.resharper* bin
{ "score": 5, "source": [ "https://Stackoverflow.com/questions/4138", "https://Stackoverflow.com", "https://Stackoverflow.com/users/83/" ] }
4,149
I have an application that writes information to file. This information is used post-execution to determine pass/failure/correctness of the application. I'd like to be able to read the file as it is being written so that I can do these pass/failure/correctness checks in real time. I assume it is possible to do this, but what are the gotcha's involved when using Java? If the reading catches up to the writing, will it just wait for more writes up until the file is closed, or will the read throw an exception at this point? If the latter, what do I do then? My intuition is currently pushing me towards BufferedStreams. Is this the way to go?
Could not get the example to work using FileChannel.read(ByteBuffer) because it isn't a blocking read. Did however get the code below to work: boolean running = true;BufferedInputStream reader = new BufferedInputStream(new FileInputStream( "out.txt" ) );public void run() { while( running ) { if( reader.available() > 0 ) { System.out.print( (char)reader.read() ); } else { try { sleep( 500 ); } catch( InterruptedException ex ) { running = false; } } }} Of course the same thing would work as a timer instead of a thread, but I leave that up to the programmer. I'm still looking for a better way, but this works for me for now. Oh, and I'll caveat this with: I'm using 1.4.2. Yes I know I'm in the stone ages still.
{ "score": 7, "source": [ "https://Stackoverflow.com/questions/4149", "https://Stackoverflow.com", "https://Stackoverflow.com/users/488/" ] }
4,168
I'm looking for a simple algorithm to 'serialize' a directed graph. In particular I've got a set of files with interdependencies on their execution order, and I want to find the correct order at compile time. I know it must be a fairly common thing to do - compilers do it all the time - but my google-fu has been weak today. What's the 'go-to' algorithm for this?
Topological Sort (From Wikipedia): In graph theory, a topological sort or topological ordering of a directed acyclic graph (DAG) is a linear ordering of its nodes in which each node comes before all nodes to which it has outbound edges. Every DAG has one or more topological sorts. Pseudo code: L ← Empty list where we put the sorted elementsQ ← Set of all nodes with no incoming edgeswhile Q is non-empty do remove a node n from Q insert n into L for each node m with an edge e from n to m do remove edge e from the graph if m has no other incoming edges then insert m into Qif graph has edges then output error message (graph has a cycle)else output message (proposed topologically sorted order: L)
{ "score": 7, "source": [ "https://Stackoverflow.com/questions/4168", "https://Stackoverflow.com", "https://Stackoverflow.com/users/588/" ] }
4,208
Is there a Windows equivalent of the Unix command, nice ? I'm specifically looking for something I can use at the command line, and not the "Set Priority" menu from the task manager. My attempts at finding this on Google have been thwarted by those who can't come up with better adjectives.
If you want to set priority when launching a process you could use the built-in START command: START ["title"] [/Dpath] [/I] [/MIN] [/MAX] [/SEPARATE | /SHARED] [/LOW | /NORMAL | /HIGH | /REALTIME | /ABOVENORMAL | /BELOWNORMAL] [/WAIT] [/B] [command/program] [parameters] Use the low through belownormal options to set priority of the launched command/program. Seems like the most straightforward solution. No downloads or script writing. The other solutions probably work on already running procs though.
{ "score": 7, "source": [ "https://Stackoverflow.com/questions/4208", "https://Stackoverflow.com", "https://Stackoverflow.com/users/55/" ] }
4,219
A few months back my team switched our source control over to Apache Subversion from Visual SourceSafe , and we haven't been happier. Recently I've been looking at Team Foundation Server , and at least on the surface, it seems very impressive. There is some great integration with Visual Studio, and lots of great tools for DBAs, testers, project managers, etc. The most obvious difference between these two products is price. It's hard to beat Apache Subversion (free). Team Foundation Server is quite expensive, so the extra features would really have to kick Subversion in the pants. Does anyone have practical experience with both? How do they compare? Is Team Foundation Server actually worth the expense?
I joined an Open Source project over at CodePlex, recently. They use TFS for their source control and I have to say that it's absolutely magnificent. I'm incredibly impressed with it, so far. I'm a huge fan of the IDE integration and how easy it is to branch and tag your code. Adding a solution to source control is something like two clicks, if you've already got everything configured properly. Now. Is it worth the hefty price tag? I don't think so. The benefit to working on projects at CodePlex is it lets me get the experience with TFS that I need, in the event that I have to use it somewhere later. If you want good IDE integration for your Source Control, go grab VisualSVN integration package. It's a much, much cheaper investment to get a lot of the same features (free on non-domain computers BTW).
{ "score": 7, "source": [ "https://Stackoverflow.com/questions/4219", "https://Stackoverflow.com", "https://Stackoverflow.com/users/423/" ] }
4,221
I'd like to use a LinqDataSource control on a page and limit the amount of records returned. I know if I use code behind I could do something like this: IEnumerable<int> values = Enumerable.Range(0, 10);IEnumerable<int> take3 = values.Take(3); Does anyone know if something like this is possible with a LinqDataSource control? [Update] I'm going to use the LinqDataSource with the ListView control, not a GridView or Repeater. The LinqDataSource wizard does not provide the ability to limit the number of records return. The Advanced options only allow you to enabled deletes, inserts, and updates.
I had this same issue. The way I got round this was to use the Selecting event on the LinqDataSource and return the result manually. e.g. protected void lnqRecentOrder_Selecting(object sender, LinqDataSourceSelectEventArgs e){ DataClassesDataContext dx = new DataClassesDataContext(); e.Result = (from o in dx.Orders where o.CustomerID == Int32.Parse(Request.QueryString["CustomerID"]) select o).Take(5);}
{ "score": 5, "source": [ "https://Stackoverflow.com/questions/4221", "https://Stackoverflow.com", "https://Stackoverflow.com/users/519/" ] }
4,227
I'm using a Dictionary<string, int> where the int is a count of the key. Now, I need to access the last-inserted Key inside the Dictionary, but I do not know the name of it. The obvious attempt: int LastCount = mydict[mydict.keys[mydict.keys.Count]]; does not work, because Dictionary.Keys does not implement a []-indexer. I just wonder if there is any similar class? I thought about using a Stack, but that only stores a string. I could now create my own struct and then use a Stack<MyStruct> , but I wonder if there is another alternative, essentially a Dictionary that implements an []-indexer on the Keys?
As @Falanwe points out in a comment, doing something like this is incorrect : int LastCount = mydict.Keys.ElementAt(mydict.Count -1); You should not depend on the order of keys in a Dictionary. If you need ordering, you should use an OrderedDictionary , as suggested in this answer . The other answers on this page are interesting as well.
{ "score": 9, "source": [ "https://Stackoverflow.com/questions/4227", "https://Stackoverflow.com", "https://Stackoverflow.com/users/91/" ] }
4,230
I've been doing ASP.NET development for a little while now, and I've used both the GridView and the DataGrid controls before for various things, but I never could find a really good reason to use one or the other. I'd like to know: What is the difference between these 2 ASP.NET controls? What are the advantages or disadvantages of both? Is one any faster? Newer? Easier to maintain? The intellisense summary for the controls doesn't seem to describe any difference between the two. They both can view, edit, and sort data and automatically generate columns at runtime. Edit: Visual Studio 2008 no longer lists DataGrid as an available control in the toolbox. It is still available (for legacy support I assume) if you type it in by hand though.
DataGrid was an ASP.NET 1.1 control, still supported. GridView arrived in 2.0, made certain tasks simpler added different databinding features: This link has a comparison of DataGrid and GridView features - https://msdn.microsoft.com/en-us/library/05yye6k9(v=vs.100).aspx
{ "score": 7, "source": [ "https://Stackoverflow.com/questions/4230", "https://Stackoverflow.com", "https://Stackoverflow.com/users/392/" ] }
4,242
I want to convert a primitive to a string, and I tried: myInt.toString(); This fails with the error: int cannot be dereferenced Now, I get that primitives are not reference types (ie, not an Object) and so cannot have methods. However, Java 5 introduced autoboxing and unboxing (a la C#... which I never liked in C#, but that's beside the point). So with autoboxing, I would expect the above to convert myInt to an Integer and then call toString() on that. Furthermore, I believe C# allows such a call, unless I remember incorrectly. Is this just an unfortunate shortcoming of Java's autoboxing/unboxing specification, or is there a good reason for this?
Java autoboxing/unboxing doesn't go to the extent to allow you to dereference a primitive, so your compiler prevents it. Your compiler still knows myInt as a primitive. There's a paper about this issue at jcp.org . Autoboxing is mainly useful during assignment or parameter passing -- allowing you to pass a primitive as an object (or vice versa), or assign a primitive to an object (or vice versa). So unfortunately, you would have to do it like this: (kudos Patrick, I switched to your way) Integer.toString(myInt);
{ "score": 7, "source": [ "https://Stackoverflow.com/questions/4242", "https://Stackoverflow.com", "https://Stackoverflow.com/users/122/" ] }
4,269
What is the best way to programmatically send an SMS text message? Are there any free Web Service based SMS gateways? I know that if I happen to know the user's carrier (Sprint, AT&T, etc), I can send an SMS by emailing an address based on phone number + carrier. I would like a good solution that does not require me to know the carrier. Barring that, is there an easy way to lookup carrier given a cell phone number? I understand that there are some services independent of the major mobile carriers that offer a per-message fee-based service, with API. What I would like to know is how such organizations tap into the SMS networks. Do they have contracts with mobile carriers to resell their services?
Use http://www.twilio.com/ They have a REST interface to send SMS's and even to establish phone calls or receive phone calls. You even get 30$ credits to try it out. Def. the cheapest solution you will find.
{ "score": 5, "source": [ "https://Stackoverflow.com/questions/4269", "https://Stackoverflow.com", "https://Stackoverflow.com/users/357/" ] }
4,287
I have a process in erlang that is supposed to do something immediately after spawn, then send the result back to the parent when it is finished. How do I figure out the PID of the process that spawned it?
You should pass self() to the child as one of the arguments to the entry function. spawn_link(?MODULE, child, [self()]).
{ "score": 5, "source": [ "https://Stackoverflow.com/questions/4287", "https://Stackoverflow.com", "https://Stackoverflow.com/users/121/" ] }
4,303
Lots of people talk about writing tests for their code before they start writing their code. This practice is generally known as Test Driven Development or TDD for short. What benefits do I gain from writing software this way? How do I get started with this practice?
There are a lot of benefits: You get immediate feedback on if your code is working, so you can find bugs faster By seeing the test go from red to green, you know that you have both a working regression test, and working code You gain confidence to refactor existing code, which means you can clean up code without worrying what it might break At the end you have a suite of regression tests that can be run during automated builds to give you greater confidence that your codebase is solid The best way to start is to just start. There is a great book by Kent Beck all about Test Driven Development. Just start with new code, don't worry about old code... whenever you feel you need to refactor some code, write a test for the existing functionality, then refactor it and make sure the tests stay green. Also, read this great article .
{ "score": 6, "source": [ "https://Stackoverflow.com/questions/4303", "https://Stackoverflow.com", "https://Stackoverflow.com/users/358/" ] }
4,306
I am working on a project that requires the manipulation of enormous matrices, specifically pyramidal summation for a copula calculation. In short, I need to keep track of a relatively small number of values (usually a value of 1, and in rare cases more than 1) in a sea of zeros in the matrix (multidimensional array). A sparse array allows the user to store a small number of values, and assume all undefined records to be a preset value. Since it is not physically possibly to store all values in memory, I need to store only the few non-zero elements. This could be several million entries. Speed is a huge priority, and I would also like to dynamically choose the number of variables in the class at runtime. I currently work on a system that uses a binary search tree (b-tree) to store entries. Does anyone know of a better system?
For C++, a map works well. Several million objects won't be a problem. 10 million items took about 4.4 seconds and about 57 meg on my computer. My test application is as follows: #include <stdio.h>#include <stdlib.h>#include <map>class triple {public: int x; int y; int z; bool operator<(const triple &other) const { if (x < other.x) return true; if (other.x < x) return false; if (y < other.y) return true; if (other.y < y) return false; return z < other.z; }};int main(int, char**){ std::map<triple,int> data; triple point; int i; for (i = 0; i < 10000000; ++i) { point.x = rand(); point.y = rand(); point.z = rand(); //printf("%d %d %d %d\n", i, point.x, point.y, point.z); data[point] = i; } return 0;} Now to dynamically choose the number of variables, the easiest solution is to represent index as a string , and then use string as a key for the map. For instance, an item located at [23][55] can be represented via "23,55" string. We can also extend this solution for higher dimensions; such as for three dimensions an arbitrary index will look like "34,45,56". A simple implementation of this technique is as follows: std::map data<string,int> data;char ix[100];sprintf(ix, "%d,%d", x, y); // 2 varsdata[ix] = i;sprintf(ix, "%d,%d,%d", x, y, z); // 3 varsdata[ix] = i;
{ "score": 6, "source": [ "https://Stackoverflow.com/questions/4306", "https://Stackoverflow.com", "https://Stackoverflow.com/users/522/" ] }
4,314
Many people use Mock Objects when they are writing unit tests. What is a Mock Object ? Why would I ever need one? Do I need a Mock Object Framework?
Object Mocking is used to keep dependencies out of your unit test.Sometimes you'll have a test like "SelectPerson" which will select a person from the database and return a Person object. To do this, you would normally need a dependency on the database, however with object mocking you can simulate the interaction with the database with a mock framework, so it might return a dataset which looks like one returned from the database and you can then test your code to ensure that it handles translating a dataset to a person object, rather than using it to test that a connection to the database exists.
{ "score": 6, "source": [ "https://Stackoverflow.com/questions/4314", "https://Stackoverflow.com", "https://Stackoverflow.com/users/358/" ] }
4,347
I have experience writing console and network client/server applications in C and C++, but I know next to nothing about using the win32 visual API, MFC, Qt, wxWidgets, etc. Where is a good place to start, and what method should I specialize in, so as to be future ready and robust?
This is a rather broad question, as programming GUI applications in Windows can be done in so many ways. There are two main parts to developing any GUI app: the language and the API/framework . Considering you're interested in learning to build Windows GUI apps, the language isn't really a point of focus for you. Hence, you should pick a language you already know and work with a framework or API that can be harnessed by your chosen language. If you want to use C you're pretty much restricted to dealing with the Win32 API yourself, in which case reading Petzold or Richter would be great places to start. The Win32 API can be quite daunting, but it's well worth the effort to learn (imho). There are plenty of tutorials on Win32 on the web, and there's always MSDN , with a complete reference/guide to the Win32 API. Make sure you cover not just the API, but other areas such as resources/dialogs as they are building blocks for your Win32 application. If you want to use C++ you have all of the options that you have when using C plus a few others. I'd recommend going with the Win32 API directly, and then moving on to a known framework such as MFC, Qt, wxWindows or GTK so that you can spend less time working with boilerplate code and instead focus on writing your application logic. The last 3 options I just listed have the added benefit of being cross-platform, so you don't have to worry too much about platform-specific issues. Given that you said you want to work with Windows, I'll assume you're keen to focus on that rather than cross-platform -- so go with MFC, but spend some time with the Win32 API first to get familiar with some of the concepts. When dealing with MFC and the Win32 API, it's a good idea to try and get a solid understanding of the terminology prior to writing code. For example, you need to understand what the message pump is, and how it works. You need to know about concepts such as " owner-drawn controls", and subclassing . When you understand these things (and more), you'll find it easier to work with MFC because it uses similar terminology in its class interfaces (eg. you need to know what "translate messages" means before you can understand how and when to use PreTranslateMessage ). You could also use Managed C++ to write .NET GUI applications, but I've read in a few places that Managed C++ wasn't really intended to be used in this manner. Instead it should be used as a gateway between native/unmanaged code and managed code. If you're using .NET it's best to use a .NET language such as VB.NET or C# to build your GUIs. So if you are going to use .NET, you currently have the choice of the WinForms library, or WPF . I personally feel that you'd be wasting time learning to build WinForms applications given that WPF is designed to replace it. Over time WPF will become more prevelant and Winforms will most likely die off. WPF has a much richer API set, and doesn't suffer from many of the limitations that Winforms does. If you do choose this route, however, you'll no doubt have to learn XAML , which is a markup language that drives WPF applications. This technology is coming of age, and there are many great places to learn about it. First, there are sites such as LearnWPF , and DrWPF which have some really great articles. Secondly, there are plenty of quality books on the topic . So, to sum up, once you've picked your language and tech, the path is actually quite easy. Just pick up a book or two, read some blogs, get into some code samples.. and most importantly ... write code. Keep writing, keep making mistakes, and keep learning from them. As a final note... In other words, Silverlight. If you don't want to go the MS route you might give Adobe's Flash/Flex a look see. Both Silverlight and Flash/Flex build RIA's. Which I think is where we are headed. They days of Office like apps are numbered I don't agree at all. Silverlight is not the same as WPF. Silverlight is web-specific, and only has a subset of WPF's features. Given that the question asks for Windows GUI apps, Flash/Flex Rich Internet Apps are not really a fitting suggestion. I also don't agree that the days of Rich Client Applications (such as office) are numbered at all. I hope that helps. Good luck :)
{ "score": 6, "source": [ "https://Stackoverflow.com/questions/4347", "https://Stackoverflow.com", "https://Stackoverflow.com/users/522/" ] }
4,363
Any suggestions? Using visual studio in C#. Are there any specific tools to use or methods to approach this? Update: Sorry, I should have been a little more specific. I am using ASP.Net 2.0 and was looking more for a tool like jUnit for Java. I took a look at NUnit and NUnitAsp and that looks very promising. And I didn't even know that Visual Studio Pro has a testing suite, so I'll look at all of these options (I've just started using Visual Studio/Asp.net/C# this summer).
Boy, that's a pretty general question. I'll do my best, but be prepared to see me miss by a mile. Assumptions You are using ASP.NET, not plain ASP You don't really want to test your web pages, but the logic behind them. Unit testing the actual .ASPX pages is rather painful, but there are frameworks out there to do it. NUnitAsp is one. The first thing to do is to organize (or plan) your code so that it can be tested. The two most popular design patterns for this at the time seem to be MVP and MVC. Both separate the logic of the application away from the view so that you can test the logic without the view (web pages) getting in your way. Either MVP or MVC will be effective. MVC has the advantage of having a Microsoft framework almost ready to go . Once you've selected a framework pattern that encourages testability, you need to use a unit testing tool. NUnit is a good starting point. Visual Studio Professional has a testing suite built it , but NUnit + TestDrive.NET also works in the IDE. That's sort of a shotgun blast of information. I hope some if it hits. The Pragmatic Bookshelf has a good book covering the topic .
{ "score": 6, "source": [ "https://Stackoverflow.com/questions/4363", "https://Stackoverflow.com", "https://Stackoverflow.com/users/396/" ] }
4,369
I have a directory structure like the following; script.php inc/include1.php inc/include2.php objects/object1.php objects/object2.php soap/soap.php Now, I use those objects in both script.php and /soap/soap.php , I could move them, but I want the directory structure like that for a specific reason. When executing script.php the include path is inc/include.php and when executing /soap/soap.php it's ../inc , absolute paths work, /mnt/webdev/[project name]/inc/include1.php... But it's an ugly solution if I ever want to move the directory to a different location. So is there a way to use relative paths, or a way to programmatically generate the "/mnt/webdev/[project name]/" ?
This should work $root = realpath($_SERVER["DOCUMENT_ROOT"]);include "$root/inc/include1.php"; Edit: added imporvement by aussieviking
{ "score": 8, "source": [ "https://Stackoverflow.com/questions/4369", "https://Stackoverflow.com", "https://Stackoverflow.com/users/264/" ] }
4,371
I lost my MySQL username and password. How do I retrieve it?
Stop the MySQL process. Start the MySQL process with the --skip-grant-tables option. Start the MySQL console client with the -u root option. List all the users; SELECT * FROM mysql.user; Reset password; UPDATE mysql.user SET Password=PASSWORD('[password]') WHERE User='[username]'; But DO NOT FORGET to Stop the MySQL process Start the MySQL Process normally (i.e. without the --skip-grant-tables option) when you are finished. Otherwise, your database's security could be compromised.
{ "score": 9, "source": [ "https://Stackoverflow.com/questions/4371", "https://Stackoverflow.com", "https://Stackoverflow.com/users/131/" ] }
4,393
How can I drop all tables whose names begin with a given string? I think this can be done with some dynamic SQL and the INFORMATION_SCHEMA tables.
You may need to modify the query to include the owner if there's more than one in the database. DECLARE @cmd varchar(4000)DECLARE cmds CURSOR FORSELECT 'drop table [' + Table_Name + ']'FROM INFORMATION_SCHEMA.TABLESWHERE Table_Name LIKE 'prefix%'OPEN cmdsWHILE 1 = 1BEGIN FETCH cmds INTO @cmd IF @@fetch_status != 0 BREAK EXEC(@cmd)ENDCLOSE cmds;DEALLOCATE cmds This is cleaner than using a two-step approach of generate script plus run. But one advantage of the script generation is that it gives you the chance to review the entirety of what's going to be run before it's actually run. I know that if I were going to do this against a production database, I'd be as careful as possible. Edit Code sample fixed.
{ "score": 8, "source": [ "https://Stackoverflow.com/questions/4393", "https://Stackoverflow.com", "https://Stackoverflow.com/users/369/" ] }
4,416
I am walking through the MS Press Windows Workflow Step-by-Step book and in chapter 8 it mentions a tool with the filename "wca.exe". This is supposed to be able to generate workflow communication helper classes based on an interface you provide it. I can't find that file. I thought it would be in the latest .NET 3.5 SDK, but I just downloaded and fully installed, and it's not there. Also, some MSDN forum posts had links posted that just go to 404s. So, where can I find wca.exe?
You may need to modify the query to include the owner if there's more than one in the database. DECLARE @cmd varchar(4000)DECLARE cmds CURSOR FORSELECT 'drop table [' + Table_Name + ']'FROM INFORMATION_SCHEMA.TABLESWHERE Table_Name LIKE 'prefix%'OPEN cmdsWHILE 1 = 1BEGIN FETCH cmds INTO @cmd IF @@fetch_status != 0 BREAK EXEC(@cmd)ENDCLOSE cmds;DEALLOCATE cmds This is cleaner than using a two-step approach of generate script plus run. But one advantage of the script generation is that it gives you the chance to review the entirety of what's going to be run before it's actually run. I know that if I were going to do this against a production database, I'd be as careful as possible. Edit Code sample fixed.
{ "score": 8, "source": [ "https://Stackoverflow.com/questions/4416", "https://Stackoverflow.com", "https://Stackoverflow.com/users/404/" ] }
4,418
The firewall I'm behind is running Microsoft ISA server in NTLM-only mode. Hash anyone have success getting their Ruby gems to install/update via Ruby SSPI gem or other method? ... or am I just being lazy? Note: rubysspi-1.2.4 does not work. This also works for "igem", part of the IronRuby project
I wasn't able to get mine working from the command-line switch but I have been able to do it just by setting my HTTP_PROXY environment variable. (Note that case seems to be important). I have a batch file that has a line like this in it: SET HTTP_PROXY=http://%USER%:%PASSWORD%@%SERVER%:%PORT% I set the four referenced variables before I get to this line obviously. As an example if my username is "wolfbyte", my password is "secret" and my proxy is called "pigsy" and operates on port 8080: SET HTTP_PROXY=http://wolfbyte:secret@pigsy:8080 You might want to be careful how you manage that because it stores your password in plain text in the machine's session but I don't think it should be too much of an issue.
{ "score": 9, "source": [ "https://Stackoverflow.com/questions/4418", "https://Stackoverflow.com", "https://Stackoverflow.com/users/307/" ] }