source_id
int64 1
74.7M
| question
stringlengths 0
40.2k
| response
stringlengths 0
111k
| metadata
dict |
---|---|---|---|
115,121 | Does anyone know why there is no respond_to block for generated edit actions? Every other action in typical scaffold controllers has a respond_to block in order to output html and xml formats. Why is the edit action an exception? I'm using the latest version of Ruby on Rails (2.1.1). | Rails handles the 99% case: It's fairly unlikely you'd ever need to do any XML or JSON translations in your Edit action, because non-visually, the Edit action is pretty much just like the Show action. Nonvisual clients that want to update a model in your application can call the controller this way GET /my_models/[:id].xml (Show) Then, the client app can make any transformations or edits and post (or put) the results to PUT /my_models/[:id].xml (Update) When you call this, you usually are doing it to get an editable form of the Show action: GET /my_models/[:id]/edit And it is intended for human use. 99% of the time, that is. Since it's unusual to transform the data in the Edit action, Rails assumes you aren't going to, and DRYs up your code by leaving respond_to out of the scaffold. | {
"score": 5,
"source": [
"https://Stackoverflow.com/questions/115121",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20467/"
]
} |
115,124 | I am evaluating WF for use in line of business applications on the web, and I would love to hear some recent first-hand accounts of this technology. My main interest here is in improving the maintainability of projects and maybe in increasing developer productivity when working on complex processes that change frequently. I really like the idea of WF, however it seems to be relatively unknown and many older comments I've come across mention that it's overwhelmingly complex once you get into it. If it's overdesigned to the point that it's unusable (or a bad tradeoff) for a small to medium-sized project, that's something that I need to know. Of course, it has been out since late 2006, so perhaps it has matured. If that's the case, that's another piece of information that would be very helpful! Thanks in advance! | Windows Workflow Foundation is a very capable product but still very much in its 1st version :-( The main reasons for use include: Visually modeling business requirements. Separating your business logic from the business rules and externalizing rules as XML files. Seperating your business flow from you application by externalizing your workflows as XML files. Creating long running processes with the automatic ability to react if nothing has happened for some extended period of time. For example an invoice not being paid. Automatic persistence of long running workflows to keep resource usage down and allow a process and/or machine to restart. Automatic tracking of workflows helping with business requirements. WF comes as a library/framework so most of the time you need to write the host that instantiates the WF runtime. That said, using WCF hosted in IIS is a viable solution and saves a lot of work. However the WCF/WF coupling is less than perfect and needs some serious work. See here http://msmvps.com/blogs/theproblemsolver/archive/2008/08/06/using-a-transactionscopeactivity-with-a-wcf-receiveactivity.aspx for more details. Expect quite a few changes/enhancements in the next version. WF (and WCF) are pretty central to a lot of the new stuff coming out of Microsoft. You can expect some interesting announcements during the PDC. BTW keeping multiple versions of a workflow running takes a bit of work but that is mostly standard .NET. I just did a series of blog posts on the subject starting here: http://msmvps.com/blogs/theproblemsolver/archive/2008/09/10/versioning-long-running-workfows.aspx About visually modeling business requirements.In theory this works quite well with a separation of intent and implementation. However in practice you will drop quite a few extra activities on a workflow purely for technical reasons and that sort of defeats the purpose as You have to tell a business analyst to ignore half the shapes and lines. | {
"score": 6,
"source": [
"https://Stackoverflow.com/questions/115124",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/16082/"
]
} |
115,159 | I have been using ASP.NET for years, but I can never remember when using the # and = are appropriate. For example: <%= Grid.ClientID %> or <%# Eval("FullName")%> Can someone explain when each should be used so I can keep it straight in my mind? Is # only used in controls that support databinding? | <%= %> is the equivalent of doing Response.Write("") wherever you place it. <%# %> is for Databinding and can only be used where databinding is supported (you can use these on the page-level outside a control if you call Page.DataBind() in your codebehind) Databinding Expressions Overview | {
"score": 6,
"source": [
"https://Stackoverflow.com/questions/115159",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/417/"
]
} |
115,206 | I use Codesmith to create our code generation templates and have had success in learning how to use the tool by looking at example templates and the built in documentation. However I was wondering if there are any other resources (books, articles, tutorials, etc.) for getting a better grasp of Codesmith? | Have you checked the codesmith community site | {
"score": 5,
"source": [
"https://Stackoverflow.com/questions/115206",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3111/"
]
} |
115,210 | I'm processing some data files that are supposed to be valid UTF-8 but aren't, which causes the parser (not under my control) to fail. I'd like to add a stage of pre-validating the data for UTF-8 well-formedness, but I've not yet found a utility to help do this. There's a web service at W3C which appears to be dead, and I've found a Windows-only validation tool that reports invalid UTF-8 files but doesn't report which lines/characters to fix. I'd be happy with either a tool I can drop in and use (ideally cross-platform), or a ruby/perl script I can make part of my data loading process. | You can use GNU iconv: $ iconv -f UTF-8 your_file -o /dev/null; echo $? Or with older versions of iconv, such as on macOS: $ iconv -f UTF-8 your_file > /dev/null; echo $? The command will return 0 if the file could be converted successfully, and 1 if not. Additionally, it will print out the byte offset where the invalid byte sequence occurred. Edit : The output encoding doesn't have to be specified, it will be assumed to be UTF-8. | {
"score": 8,
"source": [
"https://Stackoverflow.com/questions/115210",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6716/"
]
} |
115,237 | I am using Visual Studio, developing a native application, I have a programmatical breakpoint (assert) in my code placed using __asm int 3 or __debugbreak. Sometimes when I hit it, I would like to disable it so that successive hits in the same debugging session no longer break into the debugger. How can I do this? | x86 / x64 Assuming you are writing x86/x64 application, write following in your watch window: x86: *(char *)eip,x x64: *(char *)rip,x You should see a value 0xcc, which is opcode for INT 3. Replace it with 0x90, which is opcode for NOP. You can also use the memory window with eip as an address. PPC Assuming you are writing PPC application (e.g. Xbox 360), write following in your watch window: *(int *)iar,x You should see a value 0xfeNNNNNN, which is opcode for trap (most often 0x0fe00016 = unconditional trap). Replace it with 0x60000000, which is opcode for NOP. | {
"score": 6,
"source": [
"https://Stackoverflow.com/questions/115237",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/16673/"
]
} |
115,269 | There's something very unsatisfactory about this code: /*Given a command string in which the first 8 characters are the command namepadded on the right with whitespace, construct the appropriate kind of Command object.*/public class CommandFactory { public Command getCommand(String cmd) { cmdName = cmd.subString(0,8).trim(); if(cmdName.equals("START")) { return new StartCommand(cmd); } if(cmdName.equals("END")) { return new EndCommand(cmd); } // ... more commands in more if blocks here // else it's a bad command. return new InvalidCommand(cmd); }} I'm unrepentant about the multiple exit points - the structure is clear. But I'm not happy about the series of near-identical if statements. I've considered making a Map of Strings to Commands: commandMap = new HashMap();commandMap.put("START",StartCommand.class);// ... etc. ... then using Reflection to make instances of the appropriate class looked up from the Map. However while conceptually elegant, this involves a fair amount of Reflection code that whoever inherits this code might not appreciate - although that cost might be offset by the benefits. All the lines hardcoding values into the commandMap smell almost as bad as the if block. Even better would be if the factory's constructor could scan the classpath for subclasses of Command, query them for String representations, and automatically add them them to its repertoire. So - how should I go about refactoring this? I guess some of the frameworks out there give me this kind of thing for free. Let's assume I'm not in a position to migrate this stuff into such a framework. | Your map of strings to commands I think is good. You could even factor out the string command name to the constructor (i.e. shouldn't StartCommand know that its command is "START"?) If you could do this, instantiation of your command objects is much simpler: Class c = commandMap.get(cmdName);if (c != null) return c.newInstance();else throw new IllegalArgumentException(cmdName + " is not as valid command"); Another option is to create an enum of all your commands with links to the classes (assume all your command objects implement CommandInterface ): public enum Command{ START(StartCommand.class), END(EndCommand.class); private Class<? extends CommandInterface> mappedClass; private Command(Class<? extends CommandInterface> c) { mappedClass = c; } public CommandInterface getInstance() { return mappedClass.newInstance(); }} since the toString of an enum is its name, you can use EnumSet to locate the right object and get the class from within. | {
"score": 5,
"source": [
"https://Stackoverflow.com/questions/115269",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7512/"
]
} |
115,316 | I want to use a WSDL SOAP based web service in Python. I have looked at the Dive Into Python code but the SOAPpy module does not work under Python 2.5. I have tried using suds which works partly, but breaks with certain types (suds.TypeNotFound: Type not found: 'item'). I have also looked at Client but this does not appear to support WSDL. And I have looked at ZSI but it looks very complex. Does anyone have any sample code for it? The WSDL is https://ws.pingdom.com/soap/PingdomAPI.wsdl and works fine with the PHP 5 SOAP client. | I would recommend that you have a look at SUDS "Suds is a lightweight SOAP python client for consuming Web Services." | {
"score": 6,
"source": [
"https://Stackoverflow.com/questions/115316",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2183/"
]
} |
115,319 | I'm using C# and connecting to a WebService via an auto-generated C# proxy object. The method I'm calling can be long running, and sometimes times out. I get different errors back, sometimes I get a System.Net.WebException or a System.Web.Services.Protocols.SoapException . These exceptions have properties I can interrogate to find the specific type of error from which I can display a human-friendly version of to the user. But sometimes I just get an InvalidOperationException , and it has the following Message. Is there any way I can interpret what this is without digging through the string for things I recognize, that feels very dirty, and isn't internationalization agnostic, the error message might come back in a different language. Client found response content type of 'text/html; charset=utf-8', but expected 'text/xml'.The request failed with the error message:--<html> <head> <title>Request timed out.</title> <style> body {font-family:"Verdana";font-weight:normal;font-size: .7em;color:black;} p {font-family:"Verdana";font-weight:normal;color:black;margin-top: -5px} b {font-family:"Verdana";font-weight:bold;color:black;margin-top: -5px} H1 { font-family:"Verdana";font-weight:normal;font-size:18pt;color:red } H2 { font-family:"Verdana";font-weight:normal;font-size:14pt;color:maroon } pre {font-family:"Lucida Console";font-size: .9em} .marker {font-weight: bold; color: black;text-decoration: none;} .version {color: gray;} .error {margin-bottom: 10px;} .expandable { text-decoration:underline; font-weight:bold; color:navy; cursor:hand; } </style> </head> <body bgcolor="white"> <span><H1>Server Error in '/PerformanceManager' Application.<hr width=100% size=1 color=silver></H1> <h2> <i>Request timed out.</i> </h2></span> <font face="Arial, Helvetica, Geneva, SunSans-Regular, sans-serif "> <b> Description: </b>An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code. <br><br> <b> Exception Details: </b>System.Web.HttpException: Request timed out.<br><br> <b>Source Error:</b> <br><br> <table width=100% bgcolor="#ffffcc"> <tr> <td> <code>An unhandled exception was generated during the execution of the current web request. Information regarding the origin and location of the exception can be identified using the exception stack trace below.</code> </td> </tr> </table> <br> <b>Stack Trace:</b> <br><br> <table width=100% bgcolor="#ffffcc"> <tr> <td> <code><pre>[HttpException (0x80004005): Request timed out.]</pre></code> </td> </tr> </table> <br> <hr width=100% size=1 color=silver> <b>Version Information:</b> Microsoft .NET Framework Version:2.0.50727.312; ASP.NET Version:2.0.50727.833 </font> </body></html><!-- [HttpException]: Request timed out.-->--. Edit:I have a try-catch around the method on the web-server. I have debugged it, and the web-server method returns (after a minute or so) without any exception. I also added an unhandled exception handler in the web service and a breakpoint there wasn't hit. As soon as the web-service returns, I get this error in the client instead of the result I expected. | This is happening because there is an unhandled exception in your Web service, and the .NET runtime is spitting out its HTML yellow screen of death server error/exception dump page, instead of XML. Since the consumer of your Web service was expecting a text/xml header and instead got text/html, it throws that error. You should address the cause of your timeouts (perhaps a lengthy SQL query?). Also, checkout this blog post on Jeff Atwood's blog that explains implementing a global unhandled exception handler and using SOAP exceptions. | {
"score": 6,
"source": [
"https://Stackoverflow.com/questions/115319",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11898/"
]
} |
115,328 | I have the following class public class Car{ public Name {get; set;}} and I want to bind this programmatically to a text box. How do I do that? Shooting in the dark: ...Car car = new Car();TextEdit editBox = new TextEdit();editBox.DataBinding.Add("Name", car, "Car - Name");... I get the following error "Cannot bind to the propery 'Name' on the target control. What am I doing wrong and how should I be doing this? I am finding the databinding concept a bit difficult to grasp coming from web-development. | You want editBox.DataBindings.Add("Text", car, "Name"); The first parameter is the name of the property on the control that you want to be databound, the second is the data source, the third parameter is the property on the data source that you want to bind to. | {
"score": 7,
"source": [
"https://Stackoverflow.com/questions/115328",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/15771/"
]
} |
115,369 | I feel that my shop has a hole because we don't have a solid process in place for versioning our database schema changes. We do a lot of backups so we're more or less covered, but it's bad practice to rely on your last line of defense in this way. Surprisingly, this seems to be a common thread. Many shops I have spoken to ignore this issue because their databases don't change often, and they basically just try to be meticulous. However, I know how that story goes. It's only a matter of time before things line up just wrong and something goes missing. Are there any best practices for this? What are some strategies that have worked for you? | Must read Get your database under version control . Check the series of posts by K. Scott Allen. When it comes to version control, the database is often a second or even third-class citizen. From what I've seen, teams that would never think of writing code without version control in a million years-- and rightly so-- can somehow be completely oblivious to the need for version control around the critical databases their applications rely on. I don't know how you can call yourself a software engineer and maintain a straight face when your database isn't under exactly the same rigorous level of source control as the rest of your code. Don't let this happen to you. Get your database under version control. | {
"score": 10,
"source": [
"https://Stackoverflow.com/questions/115369",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/16082/"
]
} |
115,399 | My credit card processor requires I send a two-digit year from the credit card expiration date. Here is how I am currently processing: I put a DropDownList of the 4-digit year on the page. I validate the expiration date in a DateTime field to be sure that the expiration date being passed to the CC processor isn't expired. I send a two-digit year to the CC processor (as required). I do this via a substring of the value from the year DDL. Is there a method out there to convert a four-digit year to a two-digit year. I am not seeing anything on the DateTime object. Or should I just keep processing it as I am? | If you're creating a DateTime object using the expiration dates (month/year), you can use ToString() on your DateTime variable like so: DateTime expirationDate = new DateTime(2008, 1, 31); // random datestring lastTwoDigitsOfYear = expirationDate.ToString("yy"); Edit: Be careful with your dates though if you use the DateTime object during validation. If somebody selects 05/2008 as their card's expiration date, it expires at the end of May, not on the first. | {
"score": 8,
"source": [
"https://Stackoverflow.com/questions/115399",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2535/"
]
} |
115,418 | How to get an instance's member's values? With propertyInfos there is a propertyInfo.GetValue(instance, index) , but no such thing exists in memberInfo. I searched the net, but it seems to stop at getting the member's name and type. | I think what you need is FieldInfo . | {
"score": 5,
"source": [
"https://Stackoverflow.com/questions/115418",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11333/"
]
} |
115,425 | Aside from trying perldoc <module name> individually for any CPAN module that takes my fancy or going through the file system and looking at the directories I have no idea what modules we have installed. What's the easiest way to just get a big list of every CPAN module installed? From the command line or otherwise. | This is answered in the Perl FAQ, the answer which can be quickly found with perldoc -q installed . In short, it comes down to using ExtUtils::Installed or using File::Find , variants of both of which have been covered previously in this thread. You can also find the FAQ entry "How do I find which modules are installed on my system?" in perlfaq3. You can see a list of all FAQ answers by looking in perlfaq | {
"score": 7,
"source": [
"https://Stackoverflow.com/questions/115425",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3404/"
]
} |
115,426 | I'm looking for an algorithm to detect if two rectangles intersect (one at an arbitrary angle, the other with only vertical/horizontal lines). Testing if a corner of one is in the other ALMOST works. It fails if the rectangles form a cross-like shape. It seems like a good idea to avoid using slopes of the lines, which would require special cases for vertical lines. | The standard method would be to do the separating axis test (do a google search on that). In short: Two objects don't intersect if you can find a line that separates the two objects. e.g. the objects / all points of an object are on different sides of the line. The fun thing is, that it's sufficient to just check all edges of the two rectangles. If the rectangles don't overlap one of the edges will be the separating axis. In 2D you can do this without using slopes. An edge is simply defined as the difference between two vertices, e.g. edge = v(n) - v(n-1) You can get a perpendicular to this by rotating it by 90°. In 2D this is easy as: rotated.x = -unrotated.y rotated.y = unrotated.x So no trigonometry or slopes involved. Normalizing the vector to unit-length is not required either. If you want to test if a point is on one or another side of the line you can just use the dot-product. the sign will tell you which side you're on: // rotated: your rotated edge // v(n-1) any point from the edge. // testpoint: the point you want to find out which side it's on. side = sign (rotated.x * (testpoint.x - v(n-1).x) + rotated.y * (testpoint.y - v(n-1).y); Now test all points of rectangle A against the edges of rectangle B and vice versa. If you find a separating edge the objects don't intersect (providing all other points in B are on the other side of the edge being tested for - see drawing below). If you find no separating edge either the rectangles are intersecting or one rectangle is contained in the other. The test works with any convex polygons btw.. Amendment: To identify a separating edge, it is not enough to test all points of one rectangle against each edge of the other. The candidate-edge E (below) would as such be identified as a separating edge, as all points in A are in the same half-plane of E. However, it isn't a separating edge because the vertices Vb1 and Vb2 of B are also in that half-plane. It would only have been a separating edge if that had not been the case http://www.iassess.com/collision.png | {
"score": 8,
"source": [
"https://Stackoverflow.com/questions/115426",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20493/"
]
} |
115,431 | Suppose I have some XAML like this: <Window.Resources> <v:MyClass x:Key="whatever" Text="foo\nbar" /></Window.Resources> Obviously I want a newline character in the MyClass.Text property, but the XAML parser constructs the object with the literal string "foo\nbar". Is there (a) a way to convince the parser to translate escape sequences, or (b) a .NET method to interpret a string in the way that the C# compiler would? I realize that I can go in there looking for \n sequences, but it would be nicer to have a generic way to do this. | You can use XML character escaping <TextBlock Text="Hello World!"/> | {
"score": 5,
"source": [
"https://Stackoverflow.com/questions/115431",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9591/"
]
} |
115,459 | I'm looking for an online tool that will let me create a gif or png like this one: Some kind of LaTex online service, with friendly examples? | I use Roger's Online Equation Editor . PNG, colors, transparent background and anti-aliasing are all included. | {
"score": 6,
"source": [
"https://Stackoverflow.com/questions/115459",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/19269/"
]
} |
115,462 | I'm having a little bit of a problem scaling my images to a properly predefined size. I was wondering - since it is purely mathematics, if there's some sort of common logical algorithm that works in every language (PHP, ActionScript, Javascript etc.) to scale images proportionally. I'm using this at the moment: var maxHeight = 300;var maxWidth = 300;var ratio:Number = height / width;if (height > maxHeight) { height = maxHeight; width = Math.round(height / ratio);} else if(width > maxWidth) { width = maxWidth; height = Math.round(width * ratio);} But it doesn't work properly. The images scales proportionately, sure enough, but the size isn't set at 300 (either in width or in height). It kind of makes sense, but I was wondering if there's a fool-proof, easy way to scale images proportionally. | ratio = MIN( maxWidth / width, maxHeight/ height );width = ratio * width;height = ratio * height; Make sure all divides are floating-point. | {
"score": 7,
"source": [
"https://Stackoverflow.com/questions/115462",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/17362/"
]
} |
115,472 | I'm working on a .NET 3.5 website, with three projects under one solution. I'm using jQuery in this project. I'd like to use the Visual Studio JavaScript debugger to step through my JavaScript code. If I set a breakpoint in any of the .js files I get a warning that says: The breakpoint will not currently be hit. No symbols have been loaded for this document. How do I fix this? I'm guessing that Visual Studio is having some trouble parsing through some of the jQuery code. I will try to replace the minimized version of jQuery.js with the expanded version, but I don't think that will fix it. | I was experiencing the same behavior in Visual Studio 2008, and after spending several minutes trying to get the symbols to load I ended up using a workaround - adding a line with the "debugger;" command in my JavaScript file. After adding debugger; when you then reload the script in Internet Explorer it'll let you bring up a new instance of the script debugger, and it'll stop on your debugger command let you debug from there. In this scenario I was already debugging the JavaScript in Firebug , but I wanted to debug against Internet Explorer as well. | {
"score": 5,
"source": [
"https://Stackoverflow.com/questions/115472",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/13800/"
]
} |
115,478 | The following code is in the /Courses/Detail action: [AcceptVerbs("GET")] public ActionResult Detail(int id) { ViewData["Title"] = "A View Title"; return View(tmdc.GetCourseById(id)); } The tmdc.GetCourseById(id) method returns an instance of type Course for the View. In the View I am using <%= HTML.TextBox("Title")%> to display the value of the Title property for the Course object. Instead the text box is displaying the string A View Title . Is this normal/expected behavior? What would be the best way to handle this? Update As a workaround, I've changed ViewData["Title"] to ViewData["VIEW_TITLE"] but would like a cleaner way to handle this collision or to know if this is an expected result. | I was experiencing the same behavior in Visual Studio 2008, and after spending several minutes trying to get the symbols to load I ended up using a workaround - adding a line with the "debugger;" command in my JavaScript file. After adding debugger; when you then reload the script in Internet Explorer it'll let you bring up a new instance of the script debugger, and it'll stop on your debugger command let you debug from there. In this scenario I was already debugging the JavaScript in Firebug , but I wanted to debug against Internet Explorer as well. | {
"score": 5,
"source": [
"https://Stackoverflow.com/questions/115478",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/19251/"
]
} |
115,488 | I am having difficulty reliably creating / removing event sources during the installation of my .Net Windows Service. Here is the code from my ProjectInstaller class: // Create Process InstallerServiceProcessInstaller spi = new ServiceProcessInstaller();spi.Account = ServiceAccount.LocalSystem;// Create ServiceServiceInstaller si = new ServiceInstaller();si.ServiceName = Facade.GetServiceName();si.Description = "Processes ...";si.DisplayName = "Auto Checkout";si.StartType = ServiceStartMode.Automatic;// Remove Event Source if already thereif (EventLog.SourceExists("AutoCheckout")) EventLog.DeleteEventSource("AutoCheckout");// Create Event Source and Event Log EventLogInstaller log = new EventLogInstaller();log.Source = "AutoCheckout";log.Log = "AutoCheckoutLog";Installers.AddRange(new Installer[] { spi, si, log }); The facade methods referenced just return the strings for the name of the log, service, etc. This code works most of the time, but recently after installing I started getting my log entries showing up in the Application Log instead of the custom log. And the following errors are in the log as well: The description for Event ID ( 0 ) in Source ( AutoCheckout ) cannot be found. The local computer may not have the necessary registry information or message DLL files to display messages from a remote computer. You may be able to use the /AUXSOURCE= flag to retrieve this description; see Help and Support for details. For some reason it either isn't properly removing the source during the uninstall or it isn't creating it during the install. Any help with best practices here is appreciated. Thanks! In addition, here is a sample of how I am writing exceptions to the log: // Write to LogEventLog.WriteEntry(Facade.GetEventLogSource(), errorDetails, EventLogEntryType.Error, 99); Regarding stephbu's answer: The recommended path is an installer script and installutil, or a Windows Setup routine. I am using a Setup Project, which performs the installation of the service and sets up the log. Whether I use the installutil.exe or the windows setup project I believe they both call the same ProjectInstaller class I show above. I see how the state of my test machine could be causing the error if the log isn't truly removed until rebooting. I will experiment more to see if that solves the issue. Edit: I'm interested in a sure fire way to register the source and the log name during the installation of the service. So if the service had previously been installed, it would remove the source, or reuse the source during subsequent installations. I haven't yet had an opportunity to learn WiX to try that route. | The ServiceInstaller class automatically creates an EventLogInstaller and puts it inside its own Installers collection. Try this code: ServiceProcessInstaller serviceProcessInstaller = new ServiceProcessInstaller();serviceProcessInstaller.Password = null;serviceProcessInstaller.Username = null;serviceProcessInstaller.Account = ServiceAccount.LocalSystem;// serviceInstallerServiceInstaller serviceInstaller = new ServiceInstaller();serviceInstaller.ServiceName = "MyService";serviceInstaller.DisplayName = "My Service";serviceInstaller.StartType = ServiceStartMode.Automatic;serviceInstaller.Description = "My Service Description";// kill the default event log installerserviceInstaller.Installers.Clear(); // Create Event Source and Event Log EventLogInstaller logInstaller = new EventLogInstaller();logInstaller.Source = "MyService"; // use same as ServiceNamelogInstaller.Log = "MyLog";// Add all installersthis.Installers.AddRange(new Installer[] { serviceProcessInstaller, serviceInstaller, logInstaller}); | {
"score": 5,
"source": [
"https://Stackoverflow.com/questions/115488",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/13368/"
]
} |
115,493 | My development team uses source safe at a very basic level. We're moving into some more advanced and extended development cycles and I can't help but think that not using branching and merging in order to manage changes is going to be biting us very soon. What arguments did you find most useful in order to convince your team to move to a better solution like SVN? What programs did you use to bridge the functionality gap so that the team wouldn't miss the ide sourcesafe integration? Or should I just accept sourcesafe and attempt to shoehorn better practices into it? | First, teach them how to use SourceSafe in an efficient way. If they are smart enough, they will begin to love the advantages of using a version-control system, and if so, they will soon reach the limits of SourceSafe. That's where they will be the more able to listen to your arguments for switching to a better VCS, could it be a CVCS or a DVCS, depending on what's the team is ready to achieve. If you try to force them to use another VCS when they use SourceSafe in a wrong way, like saving zip file of source code (don't laugh, that's how they were acting in my company two years ago), they will be completly reluctant to any argumentation, as good as it could be. | {
"score": 7,
"source": [
"https://Stackoverflow.com/questions/115493",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/15769/"
]
} |
115,501 | I am considering creating a GUI-based tool that I want to be cross-platform. I've dismissed Java, as I personally do not like Swing. I'm currently considering C# and using Mono to make it cross-platform. However I'm wondering whether new-fangled cross-platform languages like Ruby can offer me a decent GUI development environment. | The short answer: no (because you said cross-platform ). The long answer: cross-platform GUIs are an age-old problem. Qt, GTK, wxWindows, Java AWT, Java Swing, XUL -- they all suffer from the same problem: the resulting GUI doesn't look native on every platform. Worse still, every platform has a slightly different look and feel, so even if you were somehow able to get a toolkit that looked native on every platform, you'd have to somehow code your app to feel native on each platform. It comes down to a decision: do you want to minimise development effort and have a GUI that doesn't look and feel quite right on each platform, or do you want to maximise the user experience? If you choose the second option, you'll need to develop a common backend and a custom UI for each platform. ruby is not a bad choice for your common backend. | {
"score": 6,
"source": [
"https://Stackoverflow.com/questions/115501",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7122/"
]
} |
115,526 | I'm running an c# .net app in an iframe of an asp page on an older site. Accessing the Asp page's session information is somewhat difficult, so I'd like to make my .net app simply verify that it's being called from an approved page, or else immediately halt. Is there a way for a page to find out the url of it's parent document? | top.location.href But that will only work if both pages (the iframe and the main page) are being served from the same domain. | {
"score": 5,
"source": [
"https://Stackoverflow.com/questions/115526",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/12382/"
]
} |
115,548 | This code in JS gives me a popup saying "i think null is a number", which I find slightly disturbing. What am I missing? if (isNaN(null)) { alert("null is not a number");} else { alert("i think null is a number");} I'm using Firefox 3. Is that a browser bug? Other tests: console.log(null == NaN); // falseconsole.log(isNaN("text")); // trueconsole.log(NaN == "text"); // false So, the problem seems not to be an exact comparison with NaN? Edit: Now the question has been answered, I have cleaned up my post to have a better version for the archive. However, this renders some comments and even some answers a little incomprehensible. Don't blame their authors. Among the things I changed was: Removed a note saying that I had screwed up the headline in the first place by reverting its meaning Earlier answers showed that I didn't state clearly enough why I thought the behaviour was weird, so I added the examples that check a string and do a manual comparison. | I believe the code is trying to ask, "is x numeric?" with the specific case here of x = null . The function isNaN() can be used to answer this question, but semantically it's referring specifically to the value NaN . From Wikipedia for NaN : NaN ( N ot a N umber) is a value of the numeric data type representing an undefined or unrepresentable value, especially in floating-point calculations. In most cases we think the answer to "is null numeric?" should be no. However, isNaN(null) == false is semantically correct, because null is not NaN . Here's the algorithmic explanation: The function isNaN(x) attempts to convert the passed parameter to a number 1 (equivalent to Number(x) ) and then tests if the value is NaN . If the parameter can't be converted to a number, Number(x) will return NaN 2 . Therefore, if the conversion of parameter x to a number results in NaN , it returns true; otherwise, it returns false. So in the specific case x = null , null is converted to the number 0, (try evaluating Number(null) and see that it returns 0,) and isNaN(0) returns false. A string that is only digits can be converted to a number and isNaN also returns false. A string (e.g. 'abcd' ) that cannot be converted to a number will cause isNaN('abcd') to return true, specifically because Number('abcd') returns NaN . In addition to these apparent edge cases are the standard numerical reasons for returning NaN like 0/0. As for the seemingly inconsistent tests for equality shown in the question, the behavior of NaN is specified such that any comparison x == NaN is false, regardless of the other operand, including NaN itself 1 . | {
"score": 8,
"source": [
"https://Stackoverflow.com/questions/115548",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2077/"
]
} |
115,573 | I'm sure we all have received the wonderfully vague "Object reference not set to instance of an Object" exception at some time or another. Identifying the object that is the problem is often a tedious task of setting breakpoints and inspecting all members in each statement. Does anyone have any tricks to easily and efficiently identify the object that causes the exception, either via programmatical means or otherwise? --edit It seems I was vague like the exception =). The point is to _not have to debug the app to find the errant object. The compiler/runtime does know that the object has been allocated/declared, and that the object has not yet been instantiated. Is there a way to extract / identify those details in a caught exception @ W. Craig Trader Your explanation that it is a result of a design problem is probably the best answer I could get. I am fairly compulsive with defensive coding and have managed to get rid of most of these errors after fixing my habits over time. The remaining ones just tweak me to no end, and lead me to posting this question to the community. Thanks for everyone's suggestions. | At the point where the NRE is thrown, there is no target object -- that's the point of the exception. The most you can hope for is to trap the file and line number where the exception occurred. If you're having problems identifying which object reference is causing the problem, then you might want to rethink your coding standards, because it sounds like you're doing too much on one line of code. A better solution to this sort of problem is Design by Contract , either through builtin language constructs, or via a library. DbC would suggest pre-checking any incoming arguments for a method for out-of-range data (ie: Null) and throwing exceptions because the method won't work with bad data. [Edit to match question edit:] I think the NRE description is misleading you. The problem that the CLR is having is that it was asked to dereference an object reference, when the object reference is Null. Take this example program: public class NullPointerExample { public static void Main() { Object foo; System.Console.WriteLine( foo.ToString() ); }} When you run this, it's going to throw an NRE on line 5, when it tried to evaluate the ToString() method on foo. There are no objects to debug, only an uninitialized object reference (foo). There's a class and a method, but no object. Re: Chris Marasti-Georg's answer : You should never throw NRE yourself -- that's a system exception with a specific meaning: the CLR (or JVM) has attempted to evaluate an object reference that wasn't initialized. If you pre-check an object reference, then either throw some sort of invalid argument exception or an application-specific exception, but not NRE, because you'll only confuse the next programmer who has to maintain your app. | {
"score": 5,
"source": [
"https://Stackoverflow.com/questions/115573",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/16391/"
]
} |
115,643 | PowerShell is definitely in the category of dynamic languages, but would it be considered strongly typed? | There is a certain amount of confusion around the terminlogy. This article explains a useful taxonomy of type systems. PowerShell is dynamically, implicit typed: > $x=100> $x=dir No type errors - a variable can change its type at runtime. This is like Python , Perl , JavaScript but different from C++ , Java , C# , etc. However: > [int]$x = 100> $x = dirCannot convert "scripts-2.5" to "System.Int32". So it also supports explicit typing of variables if you want. However, the type checking is done at runtime rather than compile time, so it's not statically typed. I have seen some say that PowerShell uses type inference (because you don't have to declare the type of a variable), but I think that is the wrong words. Type inference is a feature of systems that does type-checking at compile time (like " var " in C#). PowerShell only checks types at runtime, so it can check the actual value rather than do inference. However, there is some amount of automatic type-conversion going on: > [int]$a = 1> [string]$b = $a> $b1> $b.GetType()IsPublic IsSerial Name BaseType-------- -------- ---- --------True True String System.Object So some types are converted on the fly. This will by most definitions make PowerShell a weakly typed language. It is certainly more weak than e.g. Python which (almost?) never convert types on the fly. But probably not at weak as Perl which will convert almost anything as needed. | {
"score": 5,
"source": [
"https://Stackoverflow.com/questions/115643",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3289/"
]
} |
115,665 | I'm using the cacheCounter in CakePHP , which increments a counter for related fields. Example, I have a Person table a Source table. Person.source_id maps to a row in the Source table. Each person has one Source, and each Source has none or many Person rows. cacheCounter is working great when I change the value of a source on a person. It increments Source.Person_Count . Cool. But when it increments, it adds it to the destination source for a person, but doesn't remove it from the old value. I tried updateCacheControl() in afterSave , but that didn't do anything. So then I wrote some code in my model for afterSave that would subtract the source source_id, but it always did this even when I wasn't even changing the source_id . (So the count went negative). My question: Is there a way to tell if a field was changed in the model in CakePHP ? | To monitor changes in a field, you can use this logic in your model with no changes elsewhere required: function beforeSave() { $this->recursive = -1; $this->old = $this->find(array($this->primaryKey => $this->id)); if ($this->old){ $changed_fields = array(); foreach ($this->data[$this->alias] as $key =>$value) { if ($this->old[$this->alias][$key] != $value) { $changed_fields[] = $key; } } } // $changed_fields is an array of fields that changed return true;} | {
"score": 5,
"source": [
"https://Stackoverflow.com/questions/115665",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/43/"
]
} |
115,681 | I have to restore a database that has been inadvertently DROPped in MySQL 5.0. From checking the backup files, I only seem to have .FRM files to hold the database data. Can anyone advise whether this is all I need to perform a database restore/import from the backup, or are there other files I should have to hand to complete this? | .frm files are not the data files, they just store the "data dictionary information" (see MySQL manual ). InnoDB stores its data in ib_logfile* files. That's what you need in order to do a backup/restore. For more details see here . | {
"score": 5,
"source": [
"https://Stackoverflow.com/questions/115681",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7703/"
]
} |
115,692 | For example I have such query: Query q = sess.createQuery("from Cat cat");List cats = q.list(); If I try to make something like this it shows the following warning Type safety: The expression of type List needs unchecked conversion to conform to List<Cat>List<Cat> cats = q.list(); Is there a way to avoid it? | Using @SuppressWarnings everywhere, as suggested, is a good way to do it, though it does involve a bit of finger typing each time you call q.list() . There are two other techniques I'd suggest: Write a cast-helper Simply refactor all your @SuppressWarnings into one place: List<Cat> cats = MyHibernateUtils.listAndCast(q);...public static <T> List<T> listAndCast(Query q) { @SuppressWarnings("unchecked") List list = q.list(); return list;} Prevent Eclipse from generating warnings for unavoidable problems In Eclipse, go to Window>Preferences>Java>Compiler>Errors/Warnings and under Generic type, select the checkbox Ignore unavoidable generic type problems due to raw APIs This will turn off unnecessary warnings for similar problems like the one described above which are unavoidable. Some comments: I chose to pass in the Query instead of the result of q.list() because that way this "cheating" method can only be used to cheat with Hibernate, and not for cheating any List in general. You could add similar methods for .iterate() etc. | {
"score": 8,
"source": [
"https://Stackoverflow.com/questions/115692",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20128/"
]
} |
115,694 | Anyone know how to turn off code folding in visual studio 2008? Some of my colleagues love it, but I personally always want to see all the code, and never want code folded out of sight. I'd like a setting that means my copy of Visual Studio never folds #regions or function bodies. | Edit: I recommend this other answer Go to the Tools->Options menu.Go to Text Editor->C#->Advanced. Uncheck "Enter outlining mode when files open". That will disable all outlining, including regions, for all c# code files. | {
"score": 8,
"source": [
"https://Stackoverflow.com/questions/115694",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6722/"
]
} |
115,703 | I have some template code that I would prefer to have stored in a CPP file instead of inline in the header. I know this can be done as long as you know which template types will be used. For example: .h file class foo{public: template <typename T> void do(const T& t);}; .cpp file template <typename T>void foo::do(const T& t){ // Do something with t}template void foo::do<int>(const int&);template void foo::do<std::string>(const std::string&); Note the last two lines - the foo::do template function is only used with ints and std::strings, so those definitions mean the app will link. My question is - is this a nasty hack or will this work with other compilers/linkers? I am only using this code with VS2008 at the moment but will be wanting to port to other environments. | The problem you describe can be solved by defining the template in the header, or via the approach you describe above. I recommend reading the following points from the C++ FAQ Lite : Why can’t I separate the definition of my templates class from its declaration and put it inside a .cpp file? How can I avoid linker errors with my template functions? How does the C++ keyword export help with template linker errors? They go into a lot of detail about these (and other) template issues. | {
"score": 9,
"source": [
"https://Stackoverflow.com/questions/115703",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9236/"
]
} |
115,705 | When uploading a file (jpeg) via a form in IE7 I am seeing a mime-type of "image/pjpeg" instead of "image/jpeg" (as I see in Firefox or similar). It's easy enough to work around this problem, but I'm just wondering why IE7 is behaving differently in this case? | I believe it's because the JPEG you're working with is a progressive JPEG, which has a different mime-type. | {
"score": 6,
"source": [
"https://Stackoverflow.com/questions/115705",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5868/"
]
} |
115,773 | I'm using python and CherryPy to create a simple internal website that about 2 people use. I use the built in webserver with CherryPy.quickstart and never messed with the config files. I recently changed machines so I installed the latest Python and cherrypy and when I run the site I can access it from localhost:8080 but not through the IP or the windows machine name. It could be a machine configuration difference or a newer version of CherryPy or Python. Any ideas how I can bind to the correct IP address? Edit: to make it clear, I currently don't have a config file at all. | That depends on how you are running the cherrypy init. If using cherrypy 3.1 syntax, that wold do it: cherrypy.server.socket_host = 'www.machinename.com'cherrypy.engine.start()cherrypy.engine.block() Of course you can have something more fancy, like subclassing the server class, or using config files. Those uses are covered in the documentation . But that should be enough. If not just tell us what you are doing and cherrypy version, and I will edit this answer. | {
"score": 5,
"source": [
"https://Stackoverflow.com/questions/115773",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/852/"
]
} |
115,809 | Many beginning programmers write code like this: sub copy_file ($$) { my $from = shift; my $to = shift; `cp $from $to`;} Is this bad, and why? Should backticks ever be used? If so, how? | A few people have already mentioned that you should only use backticks when: You need to capture (or supress) the output. There exists no built-in function or Perl module to do the same task, or you have a good reason not to use the module or built-in. You sanitise your input. You check the return value. Unfortunately, things like checking the return value properly can be quite challenging. Did it die to a signal? Did it run to completion, but return a funny exit status? The standard ways of trying to interpret $? are just awful. I'd recommend using the IPC::System::Simple module's capture() and system() functions rather than backticks. The capture() function works just like backticks, except that: It provides detailed diagnostics if the command doesn't start, is killed by a signal, or returns an unexpected exit value. It provides detailed diagnostics if passed tainted data. It provides an easy mechanism for specifying acceptable exit values. It allows you to call backticks without the shell, if you want to. It provides reliable mechanisms for avoiding the shell, even if you use a single argument. The commands also work consistently across operating systems and Perl versions, unlike Perl's built-in system() which may not check for tainted data when called with multiple arguments on older versions of Perl (eg, 5.6.0 with multiple arguments), or which may call the shell anyway under Windows. As an example, the following code snippet will save the results of a call to perldoc into a scalar, avoids the shell, and throws an exception if the page cannot be found (since perldoc returns 1). #!/usr/bin/perl -wuse strict;use IPC::System::Simple qw(capture);# Make sure we're called with command-line arguments.@ARGV or die "Usage: $0 arguments\n";my $documentation = capture('perldoc', @ARGV); IPC::System::Simple is pure Perl, works on 5.6.0 and above, and doesn't have any dependencies that wouldn't normally come with your Perl distribution. (On Windows it depends upon a Win32:: module that comes with both ActiveState and Strawberry Perl). Disclaimer: I'm the author of IPC::System::Simple , so I may show some bias. | {
"score": 6,
"source": [
"https://Stackoverflow.com/questions/115809",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7598/"
]
} |
115,813 | I have been trying to produce a statically linked "single binary" version of my game for windows. I want to link with sdl, sdl_image and sdl_mixer which in turn pull in a few support libraries. Unfortunately I haven't found a way to get them all to compile and link using cygwin/mingw/gcc. As far as I can tell all existing public versions are only shared libraries / dlls. Please note that I'm not talking about licencing here. The source will be open thus the GPL/LGPLness of sdl is not relevant. | When compiling your project, you need to make just a couple changes to your makefile. Instead of sdl-config --libs , use sdl-config --static-libs Surround the use of the above-mentioned sdl-config --static-libs with -Wl,-Bstatic and -Wl,-Bdynamic . This tells GCC to force static linking, but only for the libraries specified between them. If your makefile currently looks like: SDLLIBS=`sdl-config --libs` Change it to: SDLLIBS=-Wl,-Bstatic `sdl-config --static-libs` -Wl,-Bdynamic These are actually the same things you should do on Unix-like systems, but it usually doesn't cause as many errors on Unix-likes if you use the simpler -static flag to GCC, like it does on Windows. | {
"score": 6,
"source": [
"https://Stackoverflow.com/questions/115813",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20555/"
]
} |
115,818 | When doing small icons, header graphics and the like for websites, is it better to use GIFs or PNGs? Obviously if transparency effects are required, then PNGs are definitely the way to go, and for larger, more photographic images I'd use JPEGs - but for normal web "furniture", which would you recommend and why? It may just be the tools I'm using, but GIF files usually seem to be a bit smaller than a comparible PNG, but using them just seems so 1987. | As a general rule, PNG is never worse, and often better than GIF because of superior compression. There might be some edge cases where GIF is slightly better (because the PNG format may have a slightly larger overhead from metadata) but it's really not worth the worry. It may just be the tools I'm using, but GIF files usually seem to be a bit smaller than a comparible PNG That may indeed be due to the encoding tool you use. /EDIT: Wow, there seem to be a lot of misconceptions about PNG file size. To quote Matt: There's nothing wrong with GIFs for images with few colours, and as you have noticed they tend to be smaller. This is a typical encoding mistake and not inherent in the format. You can control the colour depth and make the PNG file as small. Please refer to the relevant section in the Wikipedia article. Also, lacking support in MSIE6 is blown out of proportion by Chrono: If you need transparency and can get by with GIFs, then I'd recommend them because IE6 supports them. IE6 doesn't do well with transparent PNGs. That's wrong. MSIE6 does support PNG transparency. It doesn't support the alpha channel (without a few hacks), though but this is a different matter since GIFs don't have it at all. The only technical reason to use GIFs instead of PNGs is when use need animation and don't want to rely on other formats. | {
"score": 7,
"source": [
"https://Stackoverflow.com/questions/115818",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4309/"
]
} |
115,844 | From PyPubSub : Pypubsub provides a simple way for your Python application to decouple its components: parts of your application can publish messages (with or without data) and other parts can subscribe/receive them. This allows message "senders" and message "listeners" to be unaware of each other: one doesn't need to import the other a sender doesn't need to know "who" gets the messages, what the listeners will do with the data, or even if any listener will get the message data. similarly, listeners don't need to worry about where messages come from. This is a great tool for implementing a Model-View-Controller architecture or any similar architecture that promotes decoupling of its components. There seem to be quite a few Python modules for publishing/subscribing floating around the web, from PyPubSub, to PyDispatcher to simple "home-cooked" classes. Are there specific advantages and disadvantages when comparing different different modules? Which sets of modules have been benchmarked and compared? Thanks in advance | PyDispatcher is used heavily in Django and it's working perfectly for me (and for whole Django community, I guess). As I remember, there are some performance issues: Arguments checking made by PyDispatcher is slow. Unused connections have unnecessary overhead. AFAIK it's very unlikely you will run into this issues in a small-to-medium sized application. So these issues may not concern you. If you think you need every pound of performance (premature optimization is the root of all evil!), you can look at modifications done to PyDispatcher in Django. Hope this helps. | {
"score": 5,
"source": [
"https://Stackoverflow.com/questions/115844",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/8206/"
]
} |
115,851 | I need to manipulate 100,000 - 200,000 records. I am thinking of using LINQ (to SQL) to do this. I know from experience that filtering dataviews is very slow. So how quick is LINQ? Can you please tell me your experiences and if it is worth using, or would I be better off using SQL stored procedures (heavy going and less flexible)? Within the thousands of records I need to find groups of data and then process them, each group has about 50 records. | LINQ to SQL translates your query expression into T-SQL, so your query performance should be exactly the same as if you sent that SQL query via ADO.NET. There is a little overhead I guess, to convert the expression tree for your query into the equivalent T-SQL, but my experience is that this is small compared with the actual query time. You can of course find out exactly what T-SQL is generated, and therefore make sure you have good supporting indexes. The primary difference from DataViews is that LINQ to SQL does not bring all the data into memory and filter it there. Rather it gets the database to do what it's good at and only brings the matching data into memory. | {
"score": 5,
"source": [
"https://Stackoverflow.com/questions/115851",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7050/"
]
} |
115,866 | Convert mysql timestamp to epoch time in python - is there an easy way to do this? | Why not let MySQL do the hard work? select unix_timestamp(fieldname) from tablename; | {
"score": 5,
"source": [
"https://Stackoverflow.com/questions/115866",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
]
} |
115,868 | I'd like to know how to grab the Window title of the current active window (i.e. the one that has focus) using C#. | See example on how you can do this with full source code here: http://www.csharphelp.com/2006/08/get-current-window-handle-and-caption-with-windows-api-in-c/ [DllImport("user32.dll")]static extern IntPtr GetForegroundWindow();[DllImport("user32.dll")]static extern int GetWindowText(IntPtr hWnd, StringBuilder text, int count);private string GetActiveWindowTitle(){ const int nChars = 256; StringBuilder Buff = new StringBuilder(nChars); IntPtr handle = GetForegroundWindow(); if (GetWindowText(handle, Buff, nChars) > 0) { return Buff.ToString(); } return null;} Edited with @Doug McClean comments for better correctness. | {
"score": 9,
"source": [
"https://Stackoverflow.com/questions/115868",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1039/"
]
} |
115,882 | A product that I am working on collects several thousand readings a day and stores them as 64k binary files on a NTFS partition (Windows XP). After a year in production there is over 300000 files in a single directory and the number keeps growing. This has made accessing the parent/ancestor directories from windows explorer very time consuming. I have tried turning off the indexing service but that made no difference. I have also contemplated moving the file content into a database/zip files/tarballs but it is beneficial for us to access the files individually; basically, the files are still needed for research purposes and the researchers are not willing to deal with anything else. Is there a way to optimize NTFS or Windows so that it can work with all these small files? | NTFS performance severely degrades after 10,000 files in a directory. What you do is create an additional level in the directory hierarchy, with each subdirectory having 10,000 files. For what it's worth, this is the approach that the SVN folks took in version 1.5 . They used 1,000 files as the default threshold. | {
"score": 6,
"source": [
"https://Stackoverflow.com/questions/115882",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/13054/"
]
} |
115,971 | I'm getting an error message when I try to build my project in eclipse: The type weblogic.utils.expressions.ExpressionMap cannot be resolved. It is indirectly referenced from required .class files I've looked online for a solution and cannot find one (except for those sites that make you pay for help). Anyone have any idea of a way to find out how to go about solving this problem? Any help is appreciated, thanks! | How are you adding your Weblogic classes to the classpath in Eclipse? Are you using WTP, and a server runtime? If so, is your server runtime associated with your project? If you right click on your project and choose build path->configure build path and then choose the libraries tab. You should see the weblogic libraries associated here. If you do not you can click Add Library->Server Runtime . If the library is not there, then you first need to configure it. Windows->Preferences->Server->Installed runtimes | {
"score": 6,
"source": [
"https://Stackoverflow.com/questions/115971",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1459442/"
]
} |
115,974 | What would be the simplest way to daemonize a python script in Linux ? I need that this works with every flavor of Linux, so it should only use python based tools. | See Stevens and also this lengthy thread on activestate which I found personally to be both mostly incorrect and much to verbose, and I came up with this: from os import fork, setsid, umask, dup2from sys import stdin, stdout, stderrif fork(): exit(0)umask(0) setsid() if fork(): exit(0)stdout.flush()stderr.flush()si = file('/dev/null', 'r')so = file('/dev/null', 'a+')se = file('/dev/null', 'a+', 0)dup2(si.fileno(), stdin.fileno())dup2(so.fileno(), stdout.fileno())dup2(se.fileno(), stderr.fileno()) If you need to stop that process again, it is required to know the pid, the usual solution to this is pidfiles. Do this if you need one from os import getpidoutfile = open(pid_file, 'w')outfile.write('%i' % getpid())outfile.close() For security reasons you might consider any of these after demonizing from os import setuid, setgid, chdirfrom pwd import getpwnamfrom grp import getgrnamsetuid(getpwnam('someuser').pw_uid)setgid(getgrnam('somegroup').gr_gid)chdir('/') You could also use nohup but that does not work well with python's subprocess module | {
"score": 5,
"source": [
"https://Stackoverflow.com/questions/115974",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/14262/"
]
} |
115,977 | I would very much like to integrate pylint into the build process formy python projects, but I have run into one show-stopper: One of theerror types that I find extremely useful--: E1101: *%s %r has no %rmember* --constantly reports errors when using common django fields,for example: E1101:125:get_user_tags: Class 'Tag' has no 'objects' member which is caused by this code: def get_user_tags(username): """ Gets all the tags that username has used. Returns a query set. """ return Tag.objects.filter( ## This line triggers the error. tagownership__users__username__exact=username).distinct()# Here is the Tag class, models.Model is provided by Django:class Tag(models.Model): """ Model for user-defined strings that help categorize Events on on a per-user basis. """ name = models.CharField(max_length=500, null=False, unique=True) def __unicode__(self): return self.name How can I tune Pylint to properly take fields such as objects into account? (I've also looked into the Django source, and I have been unable to find the implementation of objects , so I suspect it is not "just" a class field. On the other hand, I'm fairly new to python, so I may very well have overlooked something.) Edit: The only way I've found to tell pylint to not warn about these warnings is by blocking all errors of the type (E1101) which is not an acceptable solution, since that is (in my opinion) an extremely useful error. If there is another way, without augmenting the pylint source, please point me to specifics :) See here for a summary of the problems I've had with pychecker and pyflakes -- they've proven to be far to unstable for general use. (In pychecker's case, the crashes originated in the pychecker code -- not source it was loading/invoking.) | Do not disable or weaken Pylint functionality by adding ignores or generated-members . Use an actively developed Pylint plugin that understands Django. This Pylint plugin for Django works quite well: pip install pylint-django and when running pylint add the following flag to the command: --load-plugins pylint_django Detailed blog post here . | {
"score": 7,
"source": [
"https://Stackoverflow.com/questions/115977",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3446/"
]
} |
115,983 | How do I add an empty directory (that contains no files) to a Git repository? | Another way to make a directory stay (almost) empty (in the repository) is to create a .gitignore file inside that directory that contains these four lines: # Ignore everything in this directory*# Except this file!.gitignore Then you don't have to get the order right the way that you have to do in m104's solution . This also gives the benefit that files in that directory won't show up as "untracked" when you do a git status. Making @GreenAsJade 's comment persistent: I think it's worth noting that this solution does precisely what the question asked for, but is not perhaps what many people looking at this question will have been looking for. This solution guarantees that the directory remains empty. It says "I truly never want files checked in here". As opposed to "I don't have any files to check in here, yet, but I need the directory here, files may be coming later". | {
"score": 13,
"source": [
"https://Stackoverflow.com/questions/115983",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7473/"
]
} |
116,002 | We all know that RAW pointers need to be wrapped in some form of smart pointer to get Exception safe memory management. But when it comes to containers of pointers the issue becomes more thorny. The std containers insist on the contained object being copyable so this rules out the use of std::auto_ptr, though you can still use boost::shared_ptr etc. But there are also some boost containers designed explicitly to hold pointers safely: See Pointer Container Library The question is:Under what conditions should I prefer to use the ptr_containers over a container of smart_pointers? boost::ptr_vector<X>orstd::vector<boost::shared_ptr<X> > | Boost pointer containers have strict ownership over the resources they hold. A std::vector<boost::shared_ptr<X>> has shared ownership. There are reasons why that may be necessary, but in case it isn't, I would default to boost::ptr_vector<X>. YMMV. | {
"score": 5,
"source": [
"https://Stackoverflow.com/questions/116002",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/14065/"
]
} |
116,038 | How do I read a file into a std::string , i.e., read the whole file at once? Text or binary mode should be specified by the caller. The solution should be standard-compliant, portable and efficient. It should not needlessly copy the string's data, and it should avoid reallocations of memory while reading the string. One way to do this would be to stat the filesize, resize the std::string and fread() into the std::string 's const_cast<char*>() 'ed data() . This requires the std::string 's data to be contiguous which is not required by the standard, but it appears to be the case for all known implementations. What is worse, if the file is read in text mode, the std::string 's size may not equal the file's size. A fully correct, standard-compliant and portable solutions could be constructed using std::ifstream 's rdbuf() into a std::ostringstream and from there into a std::string . However, this could copy the string data and/or needlessly reallocate memory. Are all relevant standard library implementations smart enough to avoid all unnecessary overhead? Is there another way to do it? Did I miss some hidden Boost function that already provides the desired functionality? void slurp(std::string& data, bool is_binary) | One way is to flush the stream buffer into a separate memory stream, and then convert that to std::string (error handling omitted): std::string slurp(std::ifstream& in) { std::ostringstream sstr; sstr << in.rdbuf(); return sstr.str();} This is nicely concise. However, as noted in the question this performs a redundant copy and unfortunately there is fundamentally no way of eliding this copy. The only real solution that avoids redundant copies is to do the reading manually in a loop, unfortunately. Since C++ now has guaranteed contiguous strings, one could write the following (≥C++17, error handling included): auto read_file(std::string_view path) -> std::string { constexpr auto read_size = std::size_t(4096); auto stream = std::ifstream(path.data()); stream.exceptions(std::ios_base::badbit); auto out = std::string(); auto buf = std::string(read_size, '\0'); while (stream.read(& buf[0], read_size)) { out.append(buf, 0, stream.gcount()); } out.append(buf, 0, stream.gcount()); return out;} | {
"score": 7,
"source": [
"https://Stackoverflow.com/questions/116038",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
]
} |
116,050 | How do I programatically (Using C#) find out what the path is of my My Pictures folder? Does this work on XP and Vista? | The following will return a full-path to the location of the users picture folder (Username\My Documents\My Pictures on XP, Username\Pictures on Vista) Environment.GetFolderPath(Environment.SpecialFolder.MyPictures); | {
"score": 7,
"source": [
"https://Stackoverflow.com/questions/116050",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5147/"
]
} |
116,054 | I'm not asking about converting a LaTeX document to html. What I'd like to be able to do is have some way to use LaTeX math commands in an html document, and have it appear correctly in a browser. This could be done server or client side. | MediaWiki can do what you are looking for. It uses Texvc ( http://en.wikipedia.org/wiki/Texvc ) which "validates (AMS) LaTeX mathematical expressions and converts them to HTML, MathML, or PNG graphics." Sounds like what you are looking for. Check out Wikipedia's article on how they handle math equations here: http://en.wikipedia.org/wiki/Help:Formula . They also have an extensive reference on LaTeX and pros/cons of the different rendering types (PNG/MathML/HTML). MediaWiki uses a subset of TeX markup, including some extensions from LaTeX and AMS-LaTeX, for mathematical formulae. It generates either PNG images or simple HTML markup, depending on user preferences and the complexity of the expression. In the future, as more browsers are smarter, it will be able to generate enhanced HTML or even MathML in many cases. (See blahtex for information about current work on adding MathML support.) More precisely, MediaWiki filters the markup through Texvc, which in turn passes the commands to TeX for the actual rendering. Thus, only a limited part of the full TeX language is supported; see below for details. ... Pros of HTML In-line HTML formulae always align properly with the rest of the HTML text. The formula's background, font size and face match the rest of HTML contents and the appearance respects CSS and browser settings. Pages using HTML will load faster. Pros of TeX TeX is semantically superior to HTML. In TeX, "x" means "mathematical variable x", whereas in HTML "x" could mean anything. Information has been irrevocably lost. This has multiple benefits: TeX can be transformed into HTML, but not vice-versa. This means that on the server side we can always transform a formula, based on its complexity and location within the text, user preferences, type of browser, etc. Therefore, where possible, all the benefits of HTML can be retained, together with the benefits of TeX. It's true that the current situation is not ideal, but that's not a good reason to drop information/contents. It's more a reason to help improve the situation. TeX can be converted to MathML for browsers which support it, thus keeping its semantics and allowing it to be rendered as a vector. TeX has been specifically designed for typesetting formulae, so input is easier and more natural, and output is more aesthetically pleasing. When writing in TeX, editors need not worry about browser support, since it is rendered into an image by the server. HTML formulae, on the other hand, can end up being rendered inconsistent of editor's intentions (or not at all), by some browsers or older versions of a browser. | {
"score": 5,
"source": [
"https://Stackoverflow.com/questions/116054",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/16970/"
]
} |
116,074 | I just started using SVN, and I have a cache directory that I don't need under source control. How can I ignore the whole directory/folder with SVN? I am using Versions and TextMate on OS X and commandline. | Set the svn:ignore property of the parent directory: svn propset svn:ignore dirname . If you have multiple things to ignore, separate by newlines in the property value. In that case it's easier to edit the property value using an external editor: svn propedit svn:ignore . | {
"score": 11,
"source": [
"https://Stackoverflow.com/questions/116074",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6305/"
]
} |
116,090 | I have a scenario where I have to check whether user has already opened Microsoft Word. If he has, then I have to kill the winword.exe process and continue to execute my code. Does any one have any straight-forward code for killing a process using vb.net or c#? | You'll want to use the System.Diagnostics.Process.Kill method. You can obtain the process you want using System.Diagnostics.Proccess.GetProcessesByName . Examples have already been posted here, but I found that the non-.exe version worked better, so something like: foreach ( Process p in System.Diagnostics.Process.GetProcessesByName("winword") ){ try { p.Kill(); p.WaitForExit(); // possibly with a timeout } catch ( Win32Exception winException ) { // process was terminating or can't be terminated - deal with it } catch ( InvalidOperationException invalidException ) { // process has already exited - might be able to let this one go }} You probably don't have to deal with NotSupportedException , which suggests that the process is remote. | {
"score": 8,
"source": [
"https://Stackoverflow.com/questions/116090",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/13337/"
]
} |
116,121 | Should I keep project filesm like Eclipse's .project, .classpath, .settings, under version control (e.g. Subversion, GitHub, CVS, Mercurial, etc)? | You do want to keep in version control any portable setting files , meaning: Any file which has no absolute path in it. That includes: .project, .classpath ( if no absolute path used , which is possible with the use of IDE variables, or user environment variables) IDE settings (which is where i disagree strongly with the 'accepted' answer). Those settings often includes static code analysis rules which are vitally important to enforce consistently for any user loading this project into his/her workspace. IDE specific settings recommandations must be written in a big README file (and versionned as well of course). Rule of thumb for me: You must be able to load a project into a workspace and have in it everything you need to properly set it up in your IDE and get going in minutes. No additional documentation, wiki pages to read or what not. Load it up, set it up, go. | {
"score": 8,
"source": [
"https://Stackoverflow.com/questions/116121",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/18722/"
]
} |
116,139 | I'd like to search a Word 2007 file (.docx) for a text string, e.g., "some special phrase" that could/would be found from a search within Word. Is there a way from Python to see the text? I have no interest in formatting - I just want to classify documents as having or not having "some special phrase". | After reading your post above, I made a 100% native Python docx module to solve this specific problem. # Import the modulefrom docx import *# Open the .docx filedocument = opendocx('A document.docx')# Search returns true if found search(document,'your search string') The docx module is at https://python-docx.readthedocs.org/en/latest/ | {
"score": 7,
"source": [
"https://Stackoverflow.com/questions/116139",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/372664/"
]
} |
116,142 | I would like to know if there is any way to add custom behaviour to the auto property get/set methods. An obvious case I can think of is wanting every set property method to call on any PropertyChanged event handlers as part of a System.ComponentModel.INotifyPropertyChanged implementation. This would allow a class to have numerous properties that can be observed, where each property is defined using auto property syntax. Basically I'm wondering if there is anything similar to either a get/set template or post get/set hook with class scope. (I know the same end functionality can easily be achieved in slightly more verbose ways - I just hate duplication of a pattern) | No, you'll have to use "traditional" property definitions for custom behavior. | {
"score": 5,
"source": [
"https://Stackoverflow.com/questions/116142",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5427/"
]
} |
116,195 | Yes XML is human readable but so is comma delimited text and properties files. XML is bloated, hard to parse, hard to modify in code, plus a ton of other problems that I can think about with it. My questions is what are XML's most attractive qualities that has made it so popular???? | It was the late 90s and the internet was hot hot hot, but companies had systems that couldn't get anywhere near the internet. They had spent countless hours dealing with CORBA and were plotting using Enterprise JavaBeans to get these older systems communicating with their newer systems. Along comes SGML, which is the precursor to almost all markup languages (I'm skipping GML). SGML was already used to define how to define HTML, but HTML had particular tags that HAD to be used in order for Netscape to properly display a given webpage. But what if we had other data that needed to be explained? Ah ha! So given that XML is structured, and you can feel free to define that structure, it naturally allows you to build interfaces (in a non-OO point of view). It doesn't really do anything that other interface languages already do, but it gave people the ability to design their own definitions. Interface languages like X12 and HL7 existed for sure, but with XML people could tailor it to their individual AIX or AS/400 systems. And with the predominance of tag language because of HTML, well it was just natural that XML would get pushed to the forefront because of its ease of use. | {
"score": 5,
"source": [
"https://Stackoverflow.com/questions/116195",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6788/"
]
} |
116,289 | I have VB6 application , I want to put some good error handling finction in it which can tell me what was the error and exact place when it happened , can anyone suggest the good way to do this | First of all, go get MZTools for Visual Basic 6 , its free and invaluable. Second add a custom error handler on every function (yes, every function). The error handler we use looks something like this: On Error GoTo {PROCEDURE_NAME}_Error{PROCEDURE_BODY} On Error GoTo 0 Exit {PROCEDURE_TYPE}{PROCEDURE_NAME}_Error: LogError "Error " & Err.Number & " (" & Err.Description & ") in line " & Erl & _ ", in procedure {PROCEDURE_NAME} of {MODULE_TYPE} {MODULE_NAME}" Then create a LogError function that logs the error to disc. Next, before you release code add Line Numbers to every function (this is also built into MZTools). From now on you will know from the Error Logs everything that happens. If possible, also, upload the error logs and actually examine them live from the field. This is about the best you can do for unexpected global error handling in VB6 (one of its many defects), and really this should only be used to find unexpected errors. If you know that if there is the possibility of an error occurring in a certain situation, you should catch that particular error and handle for it. If you know that an error occurring in a certain section is going to cause instability (File IO, Memory Issues, etc) warn the user and know that you are in an "unknown state" and that "bad things" are probably going happen. Obviously use friendly terms to keep the user informed, but not frightened. | {
"score": 5,
"source": [
"https://Stackoverflow.com/questions/116289",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/14299/"
]
} |
116,292 | I'm a PHP developer and now I use Notepad++ for code editing, but lately I've been searching for an IDE to ease my work. I've looked into Eclipse , Aptana Studio and several others, but I'm not really decided, they all look nice enough but a bit complicated. I'm sure it'll all get easy once I get used to it, but I don't want to waste my time. This is what I'm looking for: FTP support Code highlight SVN support would be great Ruby and JavaScript would be great | NetBeans . Check out 7.0.1. It supports FTP/SFTP synchronization, integrates well with Subversion, CVS, Mercurial and even with Git (with plugin). Also, it supports HTML, CSS, JavaScript, popular frameworks and more . And its free. | {
"score": 6,
"source": [
"https://Stackoverflow.com/questions/116292",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20603/"
]
} |
116,343 | I've googled around and found most people advocating the use of kmalloc , as you're guaranteed to get contiguous physical blocks of memory. However, it also seems as though kmalloc can fail if a contiguous physical block that you want can't be found. What are the advantages of having a contiguous block of memory? Specifically, why would I need to have a contiguous physical block of memory in a system call ? Is there any reason I couldn't just use vmalloc ? Finally, if I were to allocate memory during the handling of a system call, should I specify GFP_ATOMIC ? Is a system call executed in an atomic context? GFP_ATOMIC The allocation is high-priority and does not sleep. This is the flag to use in interrupt handlers, bottom halves and other situations where you cannot sleep. GFP_KERNEL This is a normal allocation and might block. This is the flag to use in process context code when it is safe to sleep. | You only need to worry about using physically contiguous memory if the buffer will be accessed by a DMA device on a physically addressed bus (like PCI). The trouble is that many system calls have no way to know whether their buffer will eventually be passed to a DMA device: once you pass the buffer to another kernel subsystem, you really cannot know where it is going to go. Even if the kernel does not use the buffer for DMA today, a future development might do so. vmalloc is often slower than kmalloc, because it may have to remap the buffer space into a virtually contiguous range. kmalloc never remaps, though if not called with GFP_ATOMIC kmalloc can block. kmalloc is limited in the size of buffer it can provide: 128 KBytes *) . If you need a really big buffer, you have to use vmalloc or some other mechanism like reserving high memory at boot. *) This was true of earlier kernels. On recent kernels (I tested this on 2.6.33.2), max size of a single kmalloc is up to 4 MB! (I wrote a fairly detailed post on this .) — kaiwan For a system call you don't need to pass GFP_ATOMIC to kmalloc(), you can use GFP_KERNEL. You're not an interrupt handler: the application code enters the kernel context by means of a trap, it is not an interrupt. | {
"score": 8,
"source": [
"https://Stackoverflow.com/questions/116343",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2132/"
]
} |
116,368 | I'm fine working on Linux using gcc as my C compiler but would like a Windows solution. Any ideas? I've looked at Dev-C++ from Bloodshed but looking for more options. | You can use GCC on Windows by downloading MingW ( discontinued ) or its successor Mingw-w64 . | {
"score": 7,
"source": [
"https://Stackoverflow.com/questions/116368",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20618/"
]
} |
116,402 | I was given a task to display when a record in the database was added, however the previous developers never made a field for this, and I can't go back and make up dates for all the existing records. Is there an easy way to extract out a record Creation date from a SQL server 2000 query. SELECT RECORD_CREATED_DATE FROM tblSomething WHERE idField = 1 The RECORD_CREATED_DATE isn't a field in the existing table. Is there some sort of SQL Function to get this information ? | If it's not stored as a field, the info is lost after the transaction log recycles (typically daily), and maybe even sooner. | {
"score": 5,
"source": [
"https://Stackoverflow.com/questions/116402",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/18893/"
]
} |
116,403 | Let's say I have a string holding a mess of text and (x)HTML tags. I want to remove all instances of a given tag (and any attributes of that tag), leaving all other tags and text along. What's the best Regex to get this done? Edited to add: Oh, I appreciate that using a Regex for this particular issue is not the best solution. However, for the sake of discussion can we assume that that particular technical decision was made a few levels over my pay grade? ;) | Attempting to parse HTML with regular expressions is generally an extremely bad idea. Use a parser instead, there should be one available for your chosen language. You might be able to get away with something like this: </?tag[^>]*?> But it depends on exactly what you're doing. For example, that won't remove the tag's content, and it may leave your HTML in an invalid state, depending on which tag you're trying to remove. It also copes badly with invalid HTML (and there's a lot of that about). Use a parser instead :) | {
"score": 5,
"source": [
"https://Stackoverflow.com/questions/116403",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/19074/"
]
} |
116,423 | I've been reading a little about temporary tables in MySQL but I'm an admitted newbie when it comes to databases in general and MySQL in particular. I've looked at some examples and the MySQL documentation on how to create a temporary table, but I'm trying to determine just how temporary tables might benefit my applications and I guess secondly what sorts of issues I can run into. Granted, each situation is different, but I guess what I'm looking for is some general advice on the topic. I did a little googling but didn't find exactly what I was looking for on the topic. If you have any experience with this, I'd love to hear about it. Thanks,Matt | Temporary tables are often valuable when you have a fairly complicated SELECT you want to perform and then perform a bunch of queries on that... You can do something like: CREATE TEMPORARY TABLE myTopCustomers SELECT customers.*,count(*) num from customers join purchases using(customerID) join items using(itemID) GROUP BY customers.ID HAVING num > 10; And then do a bunch of queries against myTopCustomers without having to do the joins to purchases and items on each query. Then when your application no longer needs the database handle, no cleanup needs to be done. Almost always you'll see temporary tables used for derived tables that were expensive to create. | {
"score": 5,
"source": [
"https://Stackoverflow.com/questions/116423",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7862/"
]
} |
116,444 | By default netbeans stores it's settings in a directory called .netbeans under the user's home directory. Is it possible to change the location of this directory (especially under Windows)? Thanks to James Schek I now know the answer (change the path in netbeans.conf) but that leads me to another question: Is there a way to include the current username in the path to the netbeans setting directory? I want to do something like this: netbeans_default_userdir="D:\etc\${USERNAME}\.netbeans\6.5beta" but I can't figure out the name of the variable to use (if there's any).Of course I can achieve the same thing with the --userdir option, I'm just curious. | yes, edit the netbeans.conf file under %NETBEANS_HOME%\etc. Edit the line with:netbeans_default_userdir="${HOME}/.netbeans/6.0" If you need different "profiles"--i.e. want to run different copies of Netbeans with different home directories, you can pass a new home directory to the launcher. Run "netbeans.exe --userdir /path/to/dir" or "nb.exe --userdir /path/to/dir" | {
"score": 5,
"source": [
"https://Stackoverflow.com/questions/116444",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4497/"
]
} |
116,485 | I have 2 arrays of 16 elements (chars) that I need to "compare" and see how many elements are equal between the two. This routine is going to be used millions of times (a usual run is about 60 or 70 million times), so I need it to be as fast as possible. I'm working on C++ (C++Builder 2007, for the record) Right now, I have a simple: matches += array1[0] == array2[0]; repeated 16 times (as profiling it appears to be 30% faster than doing it with a for loop) Is there any other way that could work faster? Some data about the environment and the data itself: I'm using C++Builder, which doesn't have any speed optimizations to take into account. I will try eventually with another compiler, but right now I'm stuck with this one. The data will be different most of the times. 100% equal data is usually very very rare (maybe less than 1%) | UPDATE: This answer has been modified to make my comments match the source code provided below. There is an optimization available if you have the capability to use SSE2 and popcnt instructions. 16 bytes happens to fit nicely in an SSE register. Using c++ and assembly/intrinsics, load the two 16 byte arrays into xmm registers, and cmp them. This generates a bitmask representing the true/false condition of the compare. You then use a movmsk instruction to load a bit representation of the bitmask into an x86 register; this then becomes a bit field where you can count all the 1's to determine how many true values you had. A hardware popcnt instruction can be a fast way to count all the 1's in a register. This requires knowledge of assembly/intrinsics and SSE in particular. You should be able to find web resources for both. If you run this code on a machine that does not support either SSE2 or popcnt, you must then iterate through the arrays and count the differences with your unrolled loop approach. Good luck Edit:Since you indicated you did not know assembly, here's some sample code to illustrate my answer: #include "stdafx.h"#include <iostream>#include "intrin.h"inline unsigned cmpArray16( char (&arr1)[16], char (&arr2)[16] ){ __m128i first = _mm_loadu_si128( reinterpret_cast<__m128i*>( &arr1 ) ); __m128i second = _mm_loadu_si128( reinterpret_cast<__m128i*>( &arr2 ) ); return _mm_movemask_epi8( _mm_cmpeq_epi8( first, second ) );}int _tmain( int argc, _TCHAR* argv[] ){ unsigned count = 0; char arr1[16] = { 0, 0, 0, 1, 0, 0, 0, 1, 0, 0, 1, 0, 0, 0, 0, 0 }; char arr2[16] = { 1, 0, 0, 1, 0, 0, 0, 0, 0, 0, 1, 0, 0, 1, 0, 0 }; count = __popcnt( cmpArray16( arr1, arr2 ) ); std::cout << "The number of equivalent bytes = " << count << std::endl; return 0;} Some notes: This function uses SSE2 instructions and a popcnt instruction introduced in the Phenom processor (that's the machine that I use). I believe the most recent Intel processors with SSE4 also have popcnt. This function does not check for instruction support with CPUID; the function is undefined if used on a processor that does not have SSE2 or popcnt (you will probably get an invalid opcode instruction). That detection code is a separate thread. I have not timed this code; the reason I think it's faster is because it compares 16 bytes at a time, branchless. You should modify this to fit your environment, and time it yourself to see if it works for you. I wrote and tested this on VS2008 SP1. SSE prefers data that is aligned on a natural 16-byte boundary; if you can guarantee that then you should get additional speed improvements, and you can change the _mm_loadu_si128 instructions to _mm_load_si128, which requires alignment. | {
"score": 5,
"source": [
"https://Stackoverflow.com/questions/116485",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/16772/"
]
} |
116,506 | By default, emacs 22.1.1 only shows the top of the compilation buffer when you first issue the compile command. I would like it to scroll to the bottom automatically when I use the compile command in order to save keystrokes. This way I can easily get a status of the current compilation by just looking at the compile buffer and seeing which files are currently being compiled instead of having to switch windows and scroll to the bottom of the buffer. Any ideas? | From Info > emacs > Compilation: If you set the variable compilation-scroll-output to a non- nil value, then the compilation buffer always scrolls to follow output as it comes in. | {
"score": 5,
"source": [
"https://Stackoverflow.com/questions/116506",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/18415/"
]
} |
116,523 | In C# there are String objects and string objects. What is the difference between the two? What are the best practices regarding which to use? | There is no difference. string (lower case) is just an alias for System.String. | {
"score": 6,
"source": [
"https://Stackoverflow.com/questions/116523",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1632/"
]
} |
116,560 | I like to use Emacs' shell mode, but it has a few deficiencies. One of those is that it's not smart enough to open a new buffer when a shell command tries to invoke an editor. For example with the environment variable VISUAL set to vim I get the following from svn propedit : $ svn propedit svn:externals . "svn-prop.tmp" 2L, 149C[1;1H~ [4;1H~ [5;1H~ [6;1H~ [7;1H~ ... (It may be hard to tell from the representation, but it's a horrible, ugly mess.) With VISUAL set to "emacs -nw" , I get $ svn propedit svn:externals .emacs: Terminal type "dumb" is not powerful enough to run Emacs.It lacks the ability to position the cursor.If that is not the actual type of terminal you have,use the Bourne shell command `TERM=... export TERM' (C-shell:`setenv TERM ...') to specify the correct type. It may be necessaryto do `unset TERMINFO' (C-shell: `unsetenv TERMINFO') as well.svn: system('emacs -nw svn-prop.tmp') returned 256 (It works with VISUAL set to just emacs , but only from inside an Emacs X window, not inside a terminal session.) Is there a way to get shell mode to do the right thing here and open up a new buffer on behalf of the command line process? | You can attach to an Emacs session through emacsclient . First, start the emacs server with M-x server-start or add (server-start) to your .emacs . Then, export VISUAL=emacsclient Edit away. Note: The versions of emacs and emacsclient must agree. If you have multiple versions of Emacs installed, make sure you invoke the version of emacsclient corresponding to the version of Emacs running the server. If you start the server in multiple Emacs processes/frames (e.g., because (server-start) is in your .emacs ), the buffer will be created in the last frame to start the server. | {
"score": 5,
"source": [
"https://Stackoverflow.com/questions/116560",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1412/"
]
} |
116,574 | While googling, I see that using java.io.File#length() can be slow. FileChannel has a size() method that is available as well. Is there an efficient way in java to get the file size? | Well, I tried to measure it up with the code below: For runs = 1 and iterations = 1 the URL method is fastest most times followed by channel. I run this with some pause fresh about 10 times. So for one time access, using the URL is the fastest way I can think of: LENGTH sum: 10626, per Iteration: 10626.0CHANNEL sum: 5535, per Iteration: 5535.0URL sum: 660, per Iteration: 660.0 For runs = 5 and iterations = 50 the picture draws different. LENGTH sum: 39496, per Iteration: 157.984CHANNEL sum: 74261, per Iteration: 297.044URL sum: 95534, per Iteration: 382.136 File must be caching the calls to the filesystem, while channels and URL have some overhead. Code: import java.io.*;import java.net.*;import java.util.*;public enum FileSizeBench { LENGTH { @Override public long getResult() throws Exception { File me = new File(FileSizeBench.class.getResource( "FileSizeBench.class").getFile()); return me.length(); } }, CHANNEL { @Override public long getResult() throws Exception { FileInputStream fis = null; try { File me = new File(FileSizeBench.class.getResource( "FileSizeBench.class").getFile()); fis = new FileInputStream(me); return fis.getChannel().size(); } finally { fis.close(); } } }, URL { @Override public long getResult() throws Exception { InputStream stream = null; try { URL url = FileSizeBench.class .getResource("FileSizeBench.class"); stream = url.openStream(); return stream.available(); } finally { stream.close(); } } }; public abstract long getResult() throws Exception; public static void main(String[] args) throws Exception { int runs = 5; int iterations = 50; EnumMap<FileSizeBench, Long> durations = new EnumMap<FileSizeBench, Long>(FileSizeBench.class); for (int i = 0; i < runs; i++) { for (FileSizeBench test : values()) { if (!durations.containsKey(test)) { durations.put(test, 0l); } long duration = testNow(test, iterations); durations.put(test, durations.get(test) + duration); // System.out.println(test + " took: " + duration + ", per iteration: " + ((double)duration / (double)iterations)); } } for (Map.Entry<FileSizeBench, Long> entry : durations.entrySet()) { System.out.println(); System.out.println(entry.getKey() + " sum: " + entry.getValue() + ", per Iteration: " + ((double)entry.getValue() / (double)(runs * iterations))); } } private static long testNow(FileSizeBench test, int iterations) throws Exception { long result = -1; long before = System.nanoTime(); for (int i = 0; i < iterations; i++) { if (result == -1) { result = test.getResult(); //System.out.println(result); } else if ((result = test.getResult()) != result) { throw new Exception("variance detected!"); } } return (System.nanoTime() - before) / 1000; }} | {
"score": 8,
"source": [
"https://Stackoverflow.com/questions/116574",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20641/"
]
} |
116,576 | I have a Website that is really slow and "feels" really bad when using it. The server is fine, it's a clientside issue, I assume because too much JavaScript or Image Requests, but since it's not my own Website, I wonder if there is a way to show and profile the Page from within IE. In Firefox, I would use Firebug, Y!Slow and the Web Developer extention to see all JavaScript, CSS, Images and other Requests, AJAX Requests etc., but on IE I did not see any problem. I know I could use Firefox, but the page works better in FF than in IE, so i wonder if there is some Development Addon specifically in IE. Edit: Thanks for the many suggestions! Too many good answers to pick one as "accepted", but i'll have a look at the various tools suggested. | There is the Internet Explorer Web Developer Toolbar . It isn't as good as Firebug IMHO, but it works. IE8 will ship with one built-in, too. | {
"score": 5,
"source": [
"https://Stackoverflow.com/questions/116576",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/91/"
]
} |
116,587 | I need to determine if a Class object representing an interface extends another interface, ie: package a.b.c.d; public Interface IMyInterface extends a.b.d.c.ISomeOtherInterface{ } according to the spec Class.getSuperClass() will return null for an Interface. If this Class represents either the Object class, an interface, a primitive type, or void, then null is returned. Therefore the following won't work. Class interface = Class.ForName("a.b.c.d.IMyInterface")Class extendedInterface = interface.getSuperClass();if(extendedInterface.getName().equals("a.b.d.c.ISomeOtherInterface")){ //do whatever here} any ideas? | Use Class.getInterfaces such as: Class<?> c; // Your classfor(Class<?> i : c.getInterfaces()) { // test if i is your interface} Also the following code might be of help, it will give you a set with all super-classes and interfaces of a certain class: public static Set<Class<?>> getInheritance(Class<?> in){ LinkedHashSet<Class<?>> result = new LinkedHashSet<Class<?>>(); result.add(in); getInheritance(in, result); return result;}/** * Get inheritance of type. * * @param in * @param result */private static void getInheritance(Class<?> in, Set<Class<?>> result){ Class<?> superclass = getSuperclass(in); if(superclass != null) { result.add(superclass); getInheritance(superclass, result); } getInterfaceInheritance(in, result);}/** * Get interfaces that the type inherits from. * * @param in * @param result */private static void getInterfaceInheritance(Class<?> in, Set<Class<?>> result){ for(Class<?> c : in.getInterfaces()) { result.add(c); getInterfaceInheritance(c, result); }}/** * Get superclass of class. * * @param in * @return */private static Class<?> getSuperclass(Class<?> in){ if(in == null) { return null; } if(in.isArray() && in != Object[].class) { Class<?> type = in.getComponentType(); while(type.isArray()) { type = type.getComponentType(); } return type; } return in.getSuperclass();} Edit: Added some code to get all super-classes and interfaces of a certain class. | {
"score": 5,
"source": [
"https://Stackoverflow.com/questions/116587",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/292/"
]
} |
116,593 | How do you clear the IRB console screen? | On Mac OS X or Linux you can use Ctrl + L to clear the IRB screen. | {
"score": 9,
"source": [
"https://Stackoverflow.com/questions/116593",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1450/"
]
} |
116,626 | I'm trying to polish up my Ruby by re writing Kent Beck's xUnit Python example from "Test Driven Development: By Example". I've got quite far but now I get the following error when I run which I don't grok. C:\Documents and Settings\aharmel\My Documents\My Workspace\TDD_Book\TDDBook_xUnit_RubyVersion\lib\main.rb:21:in `test_running': wrong number of arguments (0 for 2) (ArgumentError) from C:\Documents and Settings\aharmel\My Documents\My Workspace\TDD_Book\TDDBook_xUnit_RubyVersion\lib\main.rb:21:in `run' from C:\Documents and Settings\aharmel\My Documents\My Workspace\TDD_Book\TDDBook_xUnit_RubyVersion\lib\main.rb:85 My code looks like this: class TestCase def initialize(name) puts "1. inside TestCase.initialise: @name: #{name}" @name = name end def set_up # No implementation (but present to be overridden in WasRun) end def run self.set_up self.send @name # <<<<<<<<<<<<<<<<<<<<<<<<<= ERROR HERE!!!!!! endendclass WasRun < TestCase attr_accessor :wasRun attr_accessor :wasSetUp def initialize(name) super(name) end def set_up @wasRun = false @wasSetUp = true end def test_method @wasRun = true endendclass TestCaseTest < TestCase def set_up @test = WasRun.new("test_method") end def test_running @test.run puts "test was run? (true expected): #{test.wasRun}" end def test_set_up @test.run puts "test was set up? (true expected): #{test.wasSetUp}" endendTestCaseTest.new("test_running").run Can anyone point out my obvious mistake? | It's your print statement: puts "test was run? (true expected): #{test.wasRun}" should be puts "test was run? (true expected): #{@test.wasRun}" without the '@' you are calling Kernel#test, which expects 2 variables. | {
"score": 5,
"source": [
"https://Stackoverflow.com/questions/116626",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2455/"
]
} |
116,650 | I am tasked with writing an authentication component for an open source JAVA app. We have an in-house authentication widget that uses https . I have some example php code that accesses the widget which uses cURL to handle the transfer. My question is whether or not there is a port of cURL to JAVA , or better yet, what base package will get me close enough to handle the task? Update : This is in a nutshell, the code I would like to replicate in JAVA: $cp = curl_init();$my_url = "https://" . AUTH_SERVER . "/auth/authenticate.asp?pt1=$uname&pt2=$pass&pt4=full";curl_setopt($cp, CURLOPT_URL, $my_url);curl_setopt($cp, CURLOPT_RETURNTRANSFER, 1);$result = curl_exec($cp);curl_close($cp); Heath , I think you're on the right track, I think I'm going to end up using HttpsURLConnection and then picking out what I need from the response. | Exception handling omitted: HttpURLConnection con = (HttpURLConnection) new URL("https://www.example.com").openConnection();con.setRequestMethod("POST");con.getOutputStream().write("LOGIN".getBytes("UTF-8"));con.getInputStream(); | {
"score": 7,
"source": [
"https://Stackoverflow.com/questions/116650",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/16253/"
]
} |
116,654 | C++ is probably the most popular language for static metaprogramming and Java doesn't support it . Are there any other languages besides C++ that support generative programming (programs that create programs)? | The alternative to template style meta-programming is Macro-style that you see in various Lisp implementations. I would suggest downloading Paul Graham's On Lisp and also taking a look at Clojure if you're interested in a Lisp with macros that runs on the JVM. Macros in Lisp are much more powerful than C/C++ style and constitute a language in their own right -- they are meant for meta-programming. | {
"score": 6,
"source": [
"https://Stackoverflow.com/questions/116654",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/10559/"
]
} |
116,682 | I have a URI here in which a simple document.cookie query through the console is resulting in three cookies being displayed. I verified this with trivial code such as the following as well: var cookies = document.cookie.split(';'); console.log(cookies.length); The variable cookies does indeed come out to the number 3. Web Developer on the other hand is indicating that a grand total of 8 cookies are in use. I'm slightly confused to believe which is inaccurate. I believe the best solution might involve just reiterating the code above without the influence of Firebug. However, I was wondering if someone might suggest a more clever alternative to decipher which tool is giving me the inaccurate information. | The alternative to template style meta-programming is Macro-style that you see in various Lisp implementations. I would suggest downloading Paul Graham's On Lisp and also taking a look at Clojure if you're interested in a Lisp with macros that runs on the JVM. Macros in Lisp are much more powerful than C/C++ style and constitute a language in their own right -- they are meant for meta-programming. | {
"score": 6,
"source": [
"https://Stackoverflow.com/questions/116682",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
]
} |
116,684 | Is there anything available that isn't trivially breakable? | This 2008 answer is now dangerously out of date. SHA (all variants) is now trivially breakable, and best practice is now (as of Jan 2013) to use a key-stretching hash (like PBKDF2) or ideally a RAM intensive one (like Bcrypt ) and to add a per-user salt too. Points 2, 3 and 4 are still worth paying attention to. See the IT Security SE site for more. Original 2008 answer: Use a proven algorithm. SHA-256 uses 64 characters in the database, but with an index on the column that isn't a problem, and it is a proven hash and more reliable than MD5 and SHA-1. It's also implemented in most languages as part of the standard security suite. However don't feel bad if you use SHA-1. Don't just hash the password, but put other information in it as well. You often use the hash of "username:password:salt" or similar, rather than just the password, but if you play with this then you make it even harder to run a dictionary attack. Security is a tough field, do not think you can invent your own algorithms and protocols. Don't write logs like "[AddUser] Hash of GeorgeBush:Rep4Lyfe:ASOIJNTY is xyz" | {
"score": 7,
"source": [
"https://Stackoverflow.com/questions/116684",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/16398/"
]
} |
116,687 | I want to call a few "static" methods of a CPP class defined in a different file but I'm having linking problems. I created a test-case that recreates my problem and the code for it is below. (I'm completely new to C++, I come from a Java background and I'm a little familiar with C.) // CppClass.cpp#include <iostream>#include <pthread.h>static pthread_t thread;static pthread_mutex_t mutex;static pthread_cond_t cond;static int shutdown;using namespace std;class CppClass{public: static void Start() { cout << "Testing start function." << endl; shutdown = 0; pthread_attr_t attr; pthread_attr_init(&attr); pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_JOINABLE); pthread_mutex_init(&mutex, NULL); pthread_cond_init(&cond, NULL); pthread_create(&thread, &attr, run_thread, NULL); } static void Stop() { pthread_mutex_lock(&mutex); shutdown = 1; pthread_cond_broadcast(&cond); pthread_mutex_unlock(&mutex); } static void Join() { pthread_join(thread, NULL); }private: static void *run_thread(void *pthread_args) { CppClass *obj = new CppClass(); pthread_mutex_lock(&mutex); while (shutdown == 0) { struct timespec ts; ts.tv_sec = time(NULL) + 3; pthread_cond_timedwait(&cond, &mutex, &ts); if (shutdown) { break; } obj->display(); } pthread_mutex_unlock(&mutex); pthread_mutex_destroy(&mutex); pthread_cond_destroy(&cond); pthread_exit(NULL); return NULL; } void display() { cout << " Inside display() " << endl; }};// main.cpp#include <iostream>/* * If I remove the comment below and delete the * the class declaration part, it works. */// #include "CppClass.cpp"using namespace std;class CppClass{public: static void Start(); static void Stop(); static void Join();};int main(){ CppClass::Start(); while (1) { int quit; cout << "Do you want to end?: (0 = stay, 1 = quit) "; cin >> quit; cout << "Input: " << quit << endl; if (quit) { CppClass::Stop(); cout << "Joining CppClass..." << endl; CppClass::Join(); break; } }} When I tried to compile, I get the following error: $ g++ -o go main.cpp CppClass.cpp -l pthread/tmp/cclhBttM.o(.text+0x119): In function `main':: undefined reference to `CppClass::Start()'/tmp/cclhBttM.o(.text+0x182): In function `main':: undefined reference to `CppClass::Stop()'/tmp/cclhBttM.o(.text+0x1ad): In function `main':: undefined reference to `CppClass::Join()'collect2: ld returned 1 exit status But if I remove the class declaration in main.cpp and replace it with #include "CppClass.cpp", it works fine. Basically, I want to put these declarations in a separate .h file and use it. Am I missing something? Thanks for the help. | It's obvious you come from a Java background because you haven't yet grasped the concept of header files. In Java the process of defining something is usually in one piece. You declare and define at the same time. In C/C++ it's a two-step process. Declaring something tells the compiler "something exists with this type, but I'll tell you later how it is actually implemented". Defining something is giving the compiler the actual implementation part. Header files are used mostly for declarations, .cpp files for definitions. Header files are there to describe the "API" of classes, but not their actual code. It is possible to include code in the header, that's called header-inlining. You have inlined everything in CppClass.cpp (not good, header-inlining should be the exception), and then you declare your class in main.cpp AGAIN which is a double declaration in C++. The inlining in the class body leads to code reduplication everytime you use a method (this only sounds insane. See the C++ faq section on inlining for details.) Including the double declaration in your code gives you a compiler error. Leaving the class code out compiles but gives you a linker error because now you only have the header-like class declaration in main.cpp. The linker sees no code that implements your class methods, that's why the errors appear. Different to Java, the C++ linker will NOT automatically search for object files it wants to use. If you use class XYZ and don't give it object code for XYZ, it will simply fail. Please have a look at Wikipedia's header file article and Header File Include Patterns (the link is also at the bottom of the Wikipedia article and contains more examples) In short: For each class, generate a NewClass.h and NewClass.cpp file. In the NewClass.h file, write: class NewClass {public: NewClass(); int methodA(); int methodB();}; <- don't forget the semicolon In the NewClass.cpp file, write: #include "NewClass.h"NewClass::NewClass() { // constructor goes here}int NewClass::methodA() { // methodA goes here return 0;}int NewClass::methodB() { // methodB goes here return 1;} In main.cpp, write: #include "NewClass.h"int main() { NewClass nc; // do something with nc} To link it all together, do a g++ -o NewClassExe NewClass.cpp main.cpp (just an example with gcc) | {
"score": 6,
"source": [
"https://Stackoverflow.com/questions/116687",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7205/"
]
} |
116,797 | I have an int array as a property of a Web User Control. I'd like to set that property inline if possible using the following syntax: <uc1:mycontrol runat="server" myintarray="1,2,3" /> This will fail at runtime because it will be expecting an actual int array, but a string is being passed instead. I can make myintarray a string and parse it in the setter, but I was wondering if there was a more elegant solution. | Implement a type converter, here is one, warning : quick&dirty, not for production use, etc : public class IntArrayConverter : System.ComponentModel.TypeConverter{ public override bool CanConvertFrom(System.ComponentModel.ITypeDescriptorContext context, Type sourceType) { return sourceType == typeof(string); } public override object ConvertFrom(System.ComponentModel.ITypeDescriptorContext context, System.Globalization.CultureInfo culture, object value) { string val = value as string; string[] vals = val.Split(','); System.Collections.Generic.List<int> ints = new System.Collections.Generic.List<int>(); foreach (string s in vals) ints.Add(Convert.ToInt32(s)); return ints.ToArray(); }} and tag the property of your control : private int[] ints;[TypeConverter(typeof(IntsConverter))]public int[] Ints{ get { return this.ints; } set { this.ints = value; }} | {
"score": 5,
"source": [
"https://Stackoverflow.com/questions/116797",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5609/"
]
} |
116,819 | I want an expression that will fail when it encounters words such as "boon.ini" and "http". The goal would be to take this expression and be able to construct for any set of keywords. | ^(?:(?!boon\.ini|http).)*$\r?\n? (taken from RegexBuddy 's library) will match any line that does not contain boon.ini and/or http. Is that what you wanted? | {
"score": 7,
"source": [
"https://Stackoverflow.com/questions/116819",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/19161/"
]
} |
116,824 | Whats the most efficient way of selecting total number of records from a large table? Currently, Im simply doing $result = mysql_query("SELECT id FROM table");$total = mysql_num_rows($result) I was told this was not very efficient or fast, if you have a lot of records in the table. | You were told correctly. mysql can do this count for you which is much more efficient. $result = mysql_query( "select count(id) as num_rows from table" );$row = mysql_fetch_object( $result );$total = $row->num_rows; | {
"score": 6,
"source": [
"https://Stackoverflow.com/questions/116824",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
]
} |
116,830 | In Java, one can declare a variable parameterised by an "unknown" generic type, which looks like this: Foo<?> x; Is there an equivalent construct to this question-mark, in C#? | The short answer is no. There isn't an equivalent feature in C#. A workaround, from C# from a Java developer's perspective by Dare Obasanjo: In certain cases, one may need create a method that can operate on data structures containing any type as opposed to those that contain a specific type (e.g. a method to print all the objects in a data structure) while still taking advantage of the benefits of strong typing in generics. The mechanism for specifying this in C# is via a feature called generic type inferencing while in Java this is done using wildcard types. The following code samples show how both approaches lead to the same result. C# Code using System;using System.Collections;using System.Collections.Generic; class Test{ //Prints the contents of any generic Stack by //using generic type inference public static void PrintStackContents<T>(Stack<T> s){ while(s.Count != 0){ Console.WriteLine(s.Pop()); } } public static void Main(String[] args){ Stack<int> s2 = new Stack<int>(); s2.Push(4); s2.Push(5); s2.Push(6); PrintStackContents(s2); Stack<string> s1 = new Stack<string>(); s1.Push("One"); s1.Push("Two"); s1.Push("Three"); PrintStackContents(s1); }} Java Code import java.util.*; class Test{ //Prints the contents of any generic Stack by //specifying wildcard type public static void PrintStackContents(Stack<?> s){ while(!s.empty()){ System.out.println(s.pop()); } } public static void main(String[] args){ Stack <Integer> s2 = new Stack <Integer>(); s2.push(4); s2.push(5); s2.push(6); PrintStackContents(s2); Stack<String> s1 = new Stack<String>(); s1.push("One"); s1.push("Two"); s1.push("Three"); PrintStackContents(s1); }} | {
"score": 6,
"source": [
"https://Stackoverflow.com/questions/116830",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/14113/"
]
} |
116,854 | I'm starting work on a project using Rails, but I'm waiting for the 3rd edition of the pragmatic rails book to come out before I purchase a book. Anyway, my question is a bit more pointed than how do I get started... What are some of the must have gems that everyone uses? I need basic authentication, so I have the restful authentication gem, but beyond that, I don't know what I don't know. Is there a run down of this information somewhere? Some basic setup that 99% of the people start with when starting a new rails application? Thanks in advance. | The gems and plugins that I tend to use on most of my projects are: Restful Authentication -- For authentication Will Paginate -- For pagination Attachment Fu -- For image and file attachments RedCloth -- For textile rendering Capistrano -- For deployment | {
"score": 5,
"source": [
"https://Stackoverflow.com/questions/116854",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9450/"
]
} |
116,865 | Does anybody know, if closures will be in Java 7? | At Devoxx 2008, Mark Reinhold made it clear that closures will not be included in Java 7. Wait! Closures will be included in Java 7. Mark Reinhold announced this reversal at Devoxx 2009. Belay that! Closures ( lambda expressions ) have been deferred until Java 8. Follow Project Lambda (JSR 335) for more information. | {
"score": 5,
"source": [
"https://Stackoverflow.com/questions/116865",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1961117/"
]
} |
116,876 | I'm trying to build a Windows installer using Nullsoft Install System that requires installation by an Administrator. The installer makes a "logs" directory. Since regular users can run this application, that directory needs to be writable by regular users. How do I specify that all users should have permission to have write access to that directory in the NSIS script language? I admit that this sounds a like a sort of bad idea, but the application is just an internal app used by only a few people on a private network. I just need the log files saved so that I can see why the app is broken if something bad happens. The users can't be made administrator. | Use the AccessControl plugin and then add this to the script, where the "logs" directory is in the install directory. AccessControl::GrantOnFile "$INSTDIR\logs" "(BU)" "FullAccess" That gives full access to the folder for all users. | {
"score": 6,
"source": [
"https://Stackoverflow.com/questions/116876",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5074/"
]
} |
116,896 | I would like Visual Studio to break when a handled exception happens (i.e. I don't just want to see a "First chance" message, I want to debug the actual exception). e.g. I want the debugger to break at the exception: try{ System.IO.File.Delete(someFilename);}catch (Exception){ //we really don't care at runtime if the file couldn't be deleted} I came across these notes for Visual Studio.NET: 1) In VS.NET go to the Debug Menu >> "Exceptions..." >> "Common Language Runtime Exceptions" >> "System" and select "System.NullReferenceException" 2) In the bottom of that dialog there is a "When the exception is thrown:" group box, select "Break into the debugger" 3) Run your scenario. When the exception is thrown, the debugger will stop and notify you with a dialog that says something like: "An exception of type "System.NullReferenceException" has been thrown. [Break] [Continue]" Hit [Break]. This will put you on the line of code that's causing the problem. But they do not apply to Visual Studio 2005 (there is no Exceptions option on the Debug menu). Does anyone know where the find this options dialog in Visual Studio that the " When the exception is thrown " group box, with the option to " Break into the debugger "? Update: The problem was that my Debug menu didn't have an Exceptions item. I customized the menu to manually add it. | With a solution open, go to the Debug - Windows - Exception Settings ( Ctrl + Alt + E ) menu option. From there you can choose to break on Thrown or User-unhandled exceptions. EDIT: My instance is set up with the C# "profile" perhaps it isn't there for other profiles? | {
"score": 9,
"source": [
"https://Stackoverflow.com/questions/116896",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/12597/"
]
} |
116,945 | When Mac OS X goes to sleep, due to closing a laptop or selecting "Sleep" from the Apple menu, how does it suspend an executing process? I suppose non-windowed processes are simply suspended at an arbitrary point of execution. Is that also true for Cocoa apps, or does the OS wait until control returns to the run loop dispatcher, and goes to sleep in a "known" location? Does any modern OS do that, or is it usually safe enough to simply suspend an app no matter what it is doing? I'm curious, because allowing sleep to occur at any moment means, from the app's perspective, the system clock could suddenly leap forward by a significant amount. That's a possibility I don't usually consider while coding. | Your app is interrupted exactly where it is that moment if the CPU is actually currently executing code of your app. Your app constantly gets execution time by the task scheduler, that decides which app gets CPU time, on which core, and for how long. Once the system really goes to sleep, the scheduler simply gives no time to your app any longer, thus it will stop execution wherever it is at that moment, which can happen pretty much everywhere. However, the kernel must be in a clean state. That means if you just made a call into the kernel (many libC functions do) and this call is not at some safe-point (e.g. sleeping, waiting for a condition to become true, etc.) or possibly holding critical kernel locks (e.g. funnels), the kernel may suspend sleep till this call returns back to user space or execution reaches such a safe-point before it finally cancels your app from the task scheduler. You can open a kernel port and register for sleep/wake-up events. In that case, your app will receive an event, when the system wants to go to sleep. You have several possibilities. One is to reply to it, that the system may progress. Another one is to suspend sleep; however, Apple says certain events can be suspended at most 30 seconds, after that, the system will just continue, whether your app likes it or not. And finally, you can cancel it; though not all events can be canceled. If the system already decided it will go to sleep, you can only suspend this by at most 30 seconds or allow it at once, you cannot cancel it. However, you can also listen to an event, where the system asks apps, if it is okay to go to sleep now and there you can reply "no", causing a sleep to be canceled. The difference between "Is it okay to sleep" and "I'm planing on going to sleep" is: The first one is sent if the power saving settings are applied, that is, if the user has not moved the mouse or typed anything for the time configured there. In that case the system will just ask, if sleep is okay. An app like Apple's DVD Player will say "no", because most likely the user watches a DVD and thus doesn't interact with the computer, still no reason to go to sleep. OTOH, if the user closes his Mac Book, apps are not asked, the system will go to sleep for sure and just informs apps, that have now up to 30 seconds to react to it. Wake-up events can also be quite interesting to catch. E.g. if your system wakes up, open files might be inaccessible (an external drive has been unplugged) or network sockets won't work any longer (network has changed). So you may re-init certain app parts before using them and running into errors that are more or less expected. Apple's page regarding catching these events. | {
"score": 6,
"source": [
"https://Stackoverflow.com/questions/116945",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/10947/"
]
} |
116,951 | I wanted to use fstream to read a txt file. I am using inFile >> characterToConvert , but the problem is that this omits any spaces and newline. I am writing an encryption program so I need to include the spaces and newlines. What would be the proper way to go about accomplishing this? | Probably the best way is to read the entire file's contents into a string, which can be done very easily using ifstream's rdbuf() method: std::ifstream in("myfile");std::stringstream buffer;buffer << in.rdbuf();std::string contents(buffer.str()); You can then use regular string manipulation now that you've got everything from the file. While Tomek was asking about reading a text file, the same approach will work for reading binary data, though the std::ios::binary flag needs to be provided when creating the input file stream. | {
"score": 6,
"source": [
"https://Stackoverflow.com/questions/116951",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
]
} |
116,957 | What java GUI layout manager does everyone use? Lately, I have been using MigLayout , which has some powerful component controls. Just wanted to see what other developers are using other than the standard JDK ones. | MiGLayout is the GUI layout manager which is widely used by Java Developers. | {
"score": 5,
"source": [
"https://Stackoverflow.com/questions/116957",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6186/"
]
} |
116,967 | Is it possible to call a JavaScript function from the IMG SRC tag to get an image url? Like this: <IMG SRC="GetImage()" /><script language="javascript"> function GetImage() {return "imageName/imagePath.jpg"}</script> This is using .NET 2.0. | Nope. It's not possible, at least not in all browsers. You can do something like this instead: <img src="blank.png" id="image" alt="just nothing"><script type="text/javascript"> document.getElementById('image').src = "yourpicture.png";</script> Your favourite JavaScript framework will provide nicer ways :) | {
"score": 5,
"source": [
"https://Stackoverflow.com/questions/116967",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20682/"
]
} |
116,968 | I have a database full of customer data. It's so big that it's really cumbersome to operate on, and I'd rather just slim it down to 10% of the customers, which is plenty for development. I have an awful lot of tables and I don't want to alter them all with "ON DELETE CASCADE", especially because this is a one-time deal. Can I do a delete operation that cascades through all my tables without setting them up first? If not, what is my best option? | Combining your advice and a script I found online, I made a procedure that will produce SQL you can run to perform a cascaded delete regardless of ON DELETE CASCADE . It was probably a big waste of time, but I had a good time writing it. An advantage of doing it this way is, you can put a GO statement between each line, and it doesn't have to be one big transaction. The original was a recursive procedure; this one unrolls the recursion into a stack table. create procedure usp_delete_cascade ( @base_table_name varchar(200), @base_criteria nvarchar(1000))as begin -- Adapted from http://www.sqlteam.com/article/performing-a-cascade-delete-in-sql-server-7 -- Expects the name of a table, and a conditional for selecting rows -- within that table that you want deleted. -- Produces SQL that, when run, deletes all table rows referencing the ones -- you initially selected, cascading into any number of tables, -- without the need for "ON DELETE CASCADE". -- Does not appear to work with self-referencing tables, but it will -- delete everything beneath them. -- To make it easy on the server, put a "GO" statement between each line. declare @to_delete table ( id int identity(1, 1) primary key not null, criteria nvarchar(1000) not null, table_name varchar(200) not null, processed bit not null, delete_sql varchar(1000) ) insert into @to_delete (criteria, table_name, processed) values (@base_criteria, @base_table_name, 0) declare @id int, @criteria nvarchar(1000), @table_name varchar(200) while exists(select 1 from @to_delete where processed = 0) begin select top 1 @id = id, @criteria = criteria, @table_name = table_name from @to_delete where processed = 0 order by id desc insert into @to_delete (criteria, table_name, processed) select referencing_column.name + ' in (select [' + referenced_column.name + '] from [' + @table_name +'] where ' + @criteria + ')', referencing_table.name, 0 from sys.foreign_key_columns fk inner join sys.columns referencing_column on fk.parent_object_id = referencing_column.object_id and fk.parent_column_id = referencing_column.column_id inner join sys.columns referenced_column on fk.referenced_object_id = referenced_column.object_id and fk.referenced_column_id = referenced_column.column_id inner join sys.objects referencing_table on fk.parent_object_id = referencing_table.object_id inner join sys.objects referenced_table on fk.referenced_object_id = referenced_table.object_id inner join sys.objects constraint_object on fk.constraint_object_id = constraint_object.object_id where referenced_table.name = @table_name and referencing_table.name != referenced_table.name update @to_delete set processed = 1 where id = @id end select 'print ''deleting from ' + table_name + '...''; delete from [' + table_name + '] where ' + criteria from @to_delete order by id descendexec usp_delete_cascade 'root_table_name', 'id = 123' | {
"score": 7,
"source": [
"https://Stackoverflow.com/questions/116968",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/10906/"
]
} |
116,978 | I'm trying to get started on what I'm hoping will be a relatively quick web application in Java, yet most of the frameworks I've tried (Apache Wicket, Liftweb) require so much set-up, configuration, and trying to wrap my head around Maven while getting the whole thing to play nice with Eclipse, that I spent the whole weekend just trying to get to the point where I write my first line of code! Can anyone recommend a simple Java webapp framework that doesn't involve Maven, hideously complicated directory structures, or countless XML files that must be manually edited? | Haven't tried it myself, but I think http://www.playframework.org/ has a lot of potential... coming from php and classic asp, it's the first java web framework that sounds promising to me.... Edit by original question asker - 2011-06-09 Just wanted to provide an update. I went with Play and it was exactly what I asked for. It requires very little configuration, and just works out of the box. It is unusual in that it eschews some common Java best-practices in favor of keeping things as simple as possible. In particular, it makes heavy use of static methods, and even does some introspection on the names of variables passed to methods, something not supported by the Java reflection API. Play's attitude is that its first goal is being a useful web framework, and sticking to common Java best-practices and idioms is secondary to that. This approach makes sense to me, but Java purists may not like it, and would be better-off with Apache Wicket . In summary, if you want to build a web-app with convenience and simplicity comparable to a framework like Ruby on Rails, but in Java and with the benefit of Java's tooling (eg. Eclipse), then Play Framework is a great choice. | {
"score": 7,
"source": [
"https://Stackoverflow.com/questions/116978",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/16050/"
]
} |
116,988 | I have a number of data classes representing various entities. Which is better: writing a generic class (say, to print or output XML) using generics and interfaces, or writing a separate class to deal with each data class? Is there a performance benefit or any other benefit (other than it saving me the time of writing separate classes)? | There's a significant performance benefit to using generics -- you do away with boxing and unboxing . Compared with developing your own classes, it's a coin toss (with one side of the coin weighted more than the other). Roll your own only if you think you can out-perform the authors of the framework. | {
"score": 7,
"source": [
"https://Stackoverflow.com/questions/116988",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5648/"
]
} |
117,007 | I have some WCF methods that are used to transmit information from a server application to a website frontend for use in binding. I'm sending the result as an XElement that is a root of an XML tree containing the data I want to bind against. I'd like to create some tests that examine the data and ensure it comes across as expected. My current thinking is this: Every method that returns an XElement tree has a corresponding schema (.XSD) file. This file is included within the assembly that contains my WCF classes as an embedded resource. Tests call the method on these methods and compares the result against these embedded schemas. Is this a good idea? If not, what other ways can I use to provide a "guarantee" of what kind of XML a method will return? If it is, how do you validate an XElement against a schema? And how can I get that schema from the assembly it's embedded in? | Id say validating xml with a xsd schema is a good idea. How to validate a XElement with the loaded schema:As you see in this example you need to validate the XDocument first to get populate the "post-schema-validation infoset" (There might be a solution to do this without using the Validate method on the XDOcument but Im yet to find one): String xsd =@"<xsd:schema xmlns:xsd='http://www.w3.org/2001/XMLSchema'> <xsd:element name='root'> <xsd:complexType> <xsd:sequence> <xsd:element name='child1' minOccurs='1' maxOccurs='1'> <xsd:complexType> <xsd:sequence> <xsd:element name='grandchild1' minOccurs='1' maxOccurs='1'/> <xsd:element name='grandchild2' minOccurs='1' maxOccurs='2'/> </xsd:sequence> </xsd:complexType> </xsd:element> </xsd:sequence> </xsd:complexType> </xsd:element> </xsd:schema>";String xml = @"<?xml version='1.0'?><root> <child1> <grandchild1>alpha</grandchild1> <grandchild2>beta</grandchild2> </child1></root>";XmlSchemaSet schemas = new XmlSchemaSet();schemas.Add("", XmlReader.Create(new StringReader(xsd)));XDocument doc = XDocument.Load(XmlReader.Create(new StringReader(xml)));Boolean errors = false;doc.Validate(schemas, (sender, e) =>{ Console.WriteLine(e.Message); errors = true;}, true);errors = false;XElement child = doc.Element("root").Element("child1");child.Validate(child.GetSchemaInfo().SchemaElement, schemas, (sender, e) =>{ Console.WriteLine(e.Message); errors = true;}); How to read the embedded schema from an assembly and add it to the XmlSchemaSet: Assembly assembly = Assembly.GetExecutingAssembly();// you can use reflector to get the full namespace of your embedded resource hereStream stream = assembly.GetManifestResourceStream("AssemblyRootNamespace.Resources.XMLSchema.xsd");XmlSchemaSet schemas = new XmlSchemaSet();schemas.Add(null, XmlReader.Create(stream)); | {
"score": 5,
"source": [
"https://Stackoverflow.com/questions/117007",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
]
} |
117,014 | How can I retrieve the name of the currently logged in user, using a python script? The function should work regardless of whether it is a domain/ad user or a local user. | Try this: import os;print os.environ.get( "USERNAME" ) That should do the job. | {
"score": 5,
"source": [
"https://Stackoverflow.com/questions/117014",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
]
} |
117,150 | I love vim and the speed it gives me. But sometimes, my fingers are too speedy and I find myself typing :WQ instead of :wq . (On a German keyboard, you have to press Shift to get the colon : .) Vim will then complain that WQ is Not an editor command . Is there some way to make W and Q editor commands? | Try :command WQ wq :command Wq wq :command W w :command Q q This way you can define your own commands. See :help command for more information. | {
"score": 7,
"source": [
"https://Stackoverflow.com/questions/117150",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7498/"
]
} |
117,171 | When programming by contract a function or method first checks whether its preconditions are fulfilled, before starting to work on its responsibilities, right? The two most prominent ways to do these checks are by assert and by exception . assert fails only in debug mode. To make sure it is crucial to (unit) test all separate contract preconditions to see whether they actually fail. exception fails in debug and release mode. This has the benefit that tested debug behavior is identical to release behavior, but it incurs a runtime performance penalty. Which one do you think is preferable? See releated question here | The rule of thumb is that you should use assertions when you are trying to catch your own errors, and exceptions when trying to catch other people's errors. In other words, you should use exceptions to check the preconditions for the public API functions, and whenever you get any data that are external to your system. You should use asserts for the functions or data that are internal to your system. | {
"score": 8,
"source": [
"https://Stackoverflow.com/questions/117171",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/19863/"
]
} |
117,173 | I do not currently have this issue , but you never know, and thought experiments are always fun. Ignoring the obvious problems that you would have to have with your architecture to even be attempting this , let's assume that you had some horribly-written code of someone else's design, and you needed to do a bunch of wide and varied operations in the same code block, e.g.: WidgetMaker.SetAlignment(57);contactForm["Title"] = txtTitle.Text;Casserole.Season(true, false);((RecordKeeper)Session["CasseroleTracker"]).Seasoned = true; Multiplied by a hundred. Some of these might work, others might go badly wrong. What you need is the C# equivalent of "on error resume next", otherwise you're going to end up copying and pasting try-catches around the many lines of code. How would you attempt to tackle this problem? | public delegate void VoidDelegate();public static class Utils{ public static void Try(VoidDelegate v) { try { v(); } catch {} }}Utils.Try( () => WidgetMaker.SetAlignment(57) );Utils.Try( () => contactForm["Title"] = txtTitle.Text );Utils.Try( () => Casserole.Season(true, false) );Utils.Try( () => ((RecordKeeper)Session["CasseroleTracker"]).Seasoned = true ); | {
"score": 6,
"source": [
"https://Stackoverflow.com/questions/117173",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/192/"
]
} |
117,240 | If there is a cookie set for a subdomain, metric.foo.com, is there a way for me to delete the metric.foo.com cookie on a request to www.foo.com? The browser (at least Firefox) seems to ignore a Set-Cookie with a domain of metric.foo.com. | Cookies are only readable by the domain that created them, so if the cookie was created at metric.foo.com, it will have to be deleted under the same domain as it was created. This includes sub-domains. If you are required to delete a cookie from metric.foo.com, but are currently running a page at www.foo.com, you will not be able to. In order to do this, you need to load the page from metric.foo.com, or create the cookie under foo.com so it can be accessable under any subdomain. OR use this: Response.cookies("mycookie").domain = ".foo.com" ...while creating it, AND before you delete it. ..untested - should work. | {
"score": 5,
"source": [
"https://Stackoverflow.com/questions/117240",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20072/"
]
} |
117,250 | For example, the standard division symbol '/' rounds to zero: >>> 4 / 1000 However, I want it to return 0.04. What do I use? | There are three options: >>> 4 / float(100)0.04>>> 4 / 100.00.04 which is the same behavior as the C, C++, Java etc, or >>> from __future__ import division>>> 4 / 1000.04 You can also activate this behavior by passing the argument -Qnew to the Python interpreter: $ python -Qnew>>> 4 / 1000.04 The second option will be the default in Python 3.0. If you want to have the old integer division, you have to use the // operator. Edit : added section about -Qnew , thanks to ΤΖΩΤΖΙΟΥ ! | {
"score": 8,
"source": [
"https://Stackoverflow.com/questions/117250",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4872/"
]
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.