source_id
int64 1
74.7M
| question
stringlengths 0
40.2k
| response
stringlengths 0
111k
| metadata
dict |
---|---|---|---|
33,409 | I am using SQL Server 2005. I have a table with a text column and I have many rows in the table where the value of this column is not null, but it is empty. Trying to compare against '' yields this response: The data types text and varchar are incompatible in the not equal to operator. Is there a special function to determine whether the value of a text column is not null but empty? | where datalength(mytextfield)=0 | {
"score": 9,
"source": [
"https://Stackoverflow.com/questions/33409",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1214/"
]
} |
33,412 | After reading Jeff's blog post on Protecting Your Cookies: HttpOnly . I'd like to implement HttpOnly cookies in my web application. How do you tell tomcat to use http only cookies for sessions? | httpOnly is supported as of Tomcat 6.0.19 and Tomcat 5.5.28. See the changelog entry for bug 44382. The last comment for bug 44382 states, "this has been applied to 5.5.x and will be included in 5.5.28 onwards." However, it does not appear that 5.5.28 has been released. The httpOnly functionality can be enabled for all webapps in conf/context.xml : <Context useHttpOnly="true">...</Context> My interpretation is that it also works for an individual context by setting it on the desired Context entry in conf/server.xml (in the same manner as above). | {
"score": 7,
"source": [
"https://Stackoverflow.com/questions/33412",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1310/"
]
} |
33,449 | Is there a way to call out from a TSQL stored procedure or function to a webservice? | Yes , you can create like this CREATE PROCEDURE CALLWEBSERVICE(@Para1 ,@Para2)ASBEGIN Declare @Object as Int; Declare @ResponseText as Varchar(8000); Exec sp_OACreate 'MSXML2.XMLHTTP', @Object OUT; Exec sp_OAMethod @Object, 'open', NULL, 'get', 'http://www.webservicex.com/stockquote.asmx/GetQuote?symbol=MSFT','false' Exec sp_OAMethod @Object, 'send' Exec sp_OAMethod @Object, 'responseText', @ResponseText OUTPUT Select @ResponseText Exec sp_OADestroy @ObjectEND | {
"score": 6,
"source": [
"https://Stackoverflow.com/questions/33449",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1874/"
]
} |
33,469 | So I just fixed a bug in a framework I'm developing. The pseudo-pseudocode looks like this: myoldObject = new MyObject { someValue = "old value" };cache.Insert("myObjectKey", myoldObject);myNewObject = cache.Get("myObjectKey");myNewObject.someValue = "new value";if(myObject.someValue != cache.Get("myObjectKey").someValue) myObject.SaveToDatabase(); So, essentially, I was getting an object from the cache, and then later on comparing the original object to the cached object to see if I need to save it to the database in case it's changed. The problem arose because the original object is a reference...so changing someValue also changed the referenced cached object, so it'd never save back to the database. I fixed it by cloning the object off of the cached version, severing the reference and allowing me to compare the new object against the cached one. My question is: is there a better way to do this, some pattern, that you could recommend? I can't be the only person that's done this before :) | Dirty tracking is the normal way to handle this, I think. Something like: class MyObject { public string SomeValue { get { return _someValue; } set { if (value != SomeValue) { IsDirty = true; _someValue = value; } } public bool IsDirty { get; private set; } void SaveToDatabase() { base.SaveToDatabase(); IsDirty = false; }}myoldObject = new MyObject { someValue = "old value" };cache.Insert("myObjectKey", myoldObject);myNewObject = cache.Get("myObjectKey");myNewObject.someValue = "new value";if(myNewObject.IsDirty) myNewObject.SaveToDatabase(); | {
"score": 6,
"source": [
"https://Stackoverflow.com/questions/33469",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1212/"
]
} |
33,476 | There are a couple of things that I am having a difficult time understanding with regards to developing custom components in JSF. For the purposes of these questions, you can assume that all of the custom controls are using valuebindings/expressions (not literal bindings), but I'm interested in explanations on them as well. Where do I set the value for the valuebinding? Is this supposed to happen in decode? Or should decode do something else and then have the value set in encodeBegin? Read from the Value Binding - When do I read data from the valuebinding vs. reading it from submittedvalue and putting it into the valuebinding? When are action listeners on forms called in relation to all of this? The JSF lifecycle pages all mention events happening at various steps, but its not completely clear to me when just a simple listener for a commandbutton is being called I've tried a few combinations, but always end up with hard to find bugs that I believe are coming from basic misunderstandings of the event lifecycle. | There is a pretty good diagram in the JSF specification that shows the request lifecycle - essential for understanding this stuff. The steps are: Restore View . The UIComponent tree is rebuilt. Apply Request Values . Editable components should implement EditableValueHolder. This phase walks the component tree and calls the processDecodes methods. If the component isn't something complex like a UIData, it won't do much except call its own decode method. The decode method doesn't do much except find its renderer and invokes its decode method, passing itself as an argument. It is the renderer's job to get any submitted value and set it via setSubmittedValue . Process Validations . This phase calls processValidators which will call validate . The validate method takes the submitted value, converts it with any converters, validates it with any validators and (assuming the data passes those tests) calls setValue . This will store the value as a local variable. While this local variable is not null, it will be returned and not the value from the value binding for any calls to getValue . Update Model Values . This phase calls processUpdates . In an input component, this will call updateModel which will get the ValueExpression and invoke it to set the value on the model. Invoke Application . Button event listeners and so on will be invoked here (as will navigation if memory serves). Render Response . The tree is rendered via the renderers and the state saved. If any of these phases fail (e.g. a value is invalid), the lifecycle skips to Render Response. Various events can be fired after most of these phases, invoking listeners as appropriate (like value change listeners after Process Validations). This is a somewhat simplified version of events. Refer to the specification for more details. I would question why you are writing your own UIComponent. This is a non-trivial task and a deep understanding of the JSF architecture is required to get it right. If you need a custom control, it is better to create a concrete control that extends an exisiting UIComponent (like HtmlInputText does) with an equivalent renderer. If contamination isn't an issue, there is an open-source JSF implementation in the form of Apache MyFaces. | {
"score": 5,
"source": [
"https://Stackoverflow.com/questions/33476",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1432/"
]
} |
33,485 | I'm starting a new web project and I am considering two presentation frameworks. I am thinking either about ASP.NET MVC or Silverlight. I would tend toward Silverlight since I'm quite experienced .NET developer while I have just a basic knowledge of ASP.NET controls. | It is mainly going to be an iternal product so browsers are not an issue. You still have not written a proper description about the nature of your application. It is difficult to assess which technology is a good fit without first knowing well enough the domain the application is being applied to, and the problems it is designed to solve. In general, Microsoft is positioning these array of presentation technologies on the " Reach vs Rich " continuum. You have "plain old" HTML and Javascript on one end, acceptable by the most number of client machines out there, and the ultimate full-blown WPF on the other side where limited number of machines can handle. You did mention this to be an internal app, so WPF via XBAP or ClickOnce are also possible. So the scale would align this way: (reach) ASP.NET, AJAX, Silverlight, WPF (rich). So the question is just how rich you want/need it to be for the users until it hurts the deployment base? Frankly if all you fetch are forms and tabular data and statistics then regular ASP.NET web forms are just fine. If you want on-the-fly resizable graphs and client-side interactive with back-end WCF web services Silverlight can do that. If you want even more powerful graphical rendering than WPF via the remote deployment options is your bet. | {
"score": 6,
"source": [
"https://Stackoverflow.com/questions/33485",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/223/"
]
} |
33,497 | Unchecked exceptions are alright if you want to handle every failure the same way, for example by logging it and skipping to the next request, displaying a message to the user and handling the next event, etc. If this is my use case, all I have to do is catch some general exception type at a high level in my system, and handle everything the same way. But I want to recover from specific problems, and I'm not sure the best way to approach it with unchecked exceptions. Here is a concrete example. Suppose I have a web application, built using Struts2 and Hibernate. If an exception bubbles up to my "action", I log it, and display a pretty apology to the user. But one of the functions of my web application is creating new user accounts, that require a unique user name. If a user picks a name that already exists, Hibernate throws an org.hibernate.exception.ConstraintViolationException (an unchecked exception) down in the guts of my system. I'd really like to recover from this particular problem by asking the user to choose another user name, rather than giving them the same "we logged your problem but for now you're hosed" message. Here are a few points to consider: There a lot of people creating accounts simultaneously. I don't want to lock the whole user table between a "SELECT" to see if the name exists and an "INSERT" if it doesn't. In the case of relational databases, there might be some tricks to work around this, but what I'm really interested in is the general case where pre-checking for an exception won't work because of a fundamental race condition. Same thing could apply to looking for a file on the file system, etc. Given my CTO's propensity for drive-by management induced by reading technology columns in "Inc.", I need a layer of indirection around the persistence mechanism so that I can throw out Hibernate and use Kodo, or whatever, without changing anything except the lowest layer of persistence code. As a matter of fact, there are several such layers of abstraction in my system. How can I prevent them from leaking in spite of unchecked exceptions? One of the declaimed weaknesses of checked exceptions is having to "handle" them in every call on the stack—either by declaring that a calling method throws them, or by catching them and handling them. Handling them often means wrapping them in another checked exception of a type appropriate to the level of abstraction. So, for example, in checked-exception land, a file-system–based implementation of my UserRegistry might catch IOException , while a database implementation would catch SQLException , but both would throw a UserNotFoundException that hides the underlying implementation. How do I take advantage of unchecked exceptions, sparing myself of the burden of this wrapping at each layer, without leaking implementation details? | IMO, wrapping exceptions (checked or otherwise) has several benefits that are worth the cost: 1) It encourages you to think about the failure modes for the code you write. Basically, you have to consider the exceptions that the code you call may throw, and in turn you'll consider the exceptions you'll throw for the code that calls yours. 2) It gives you the opportunity to add additional debugging information into the exception chain. For instance, if you have a method that throws an exception on a duplicate username, you might wrap that exception with one that includes additional information about the circumstances of the failure (for example, the IP of the request that provided the dupe username) that wasn't available to the lower-level code. The cookie trail of exceptions may help you debug a complex problem (it certainly has for me). 3) It lets you become implementation-independent from the lower level code. If you're wrapping exceptions and need to swap out Hibernate for some other ORM, you only have to change your Hibernate-handling code. All the other layers of code will still be successfully using the wrapped exceptions and will interpret them in the same way, even though the underlying circumstances have changed. Note that this applies even if Hibernate changes in some way (ex: they switch exceptions in a new version); it's not just for wholesale technology replacement. 4) It encourages you use different classes of exceptions to represent different situations. For example, you may have a DuplicateUsernameException when the user tries to reuse a username, and a DatabaseFailureException when you can't check for dupe usernames due to a broken DB connection. This, in turn, lets you answer your question ("how do I recover?") in flexible and powerful ways. If you get a DuplicateUsernameException, you may decide to suggest a different username to the user. If you get a DatabaseFailureException, you may let it bubble up to the point where it displays a "down for maintenance" page to the user and send off a notification email to you. Once you have custom exceptions, you have customizeable responses -- and that's a good thing. | {
"score": 5,
"source": [
"https://Stackoverflow.com/questions/33497",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3474/"
]
} |
33,529 | Inspired by this CodingHorror article, " Protecting Your Cookies: HttpOnly " How do you set this property? Somewhere in the web config? | If you're using ASP.NET 2.0 or greater, you can turn it on in the Web.config file. In the <system.web> section, add the following line: <httpCookies httpOnlyCookies="true"/> | {
"score": 7,
"source": [
"https://Stackoverflow.com/questions/33529",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1842/"
]
} |
33,534 | I'm trying to extend some "base" classes in Python: class xlist (list): def len(self): return len(self) def add(self, *args): self.extend(args) return Noneclass xint (int): def add(self, value): self += value return selfx = xlist([1,2,3])print x.len() ## >>> 3 okprint x ## >>> [1,2,3] okx.add (4, 5, 6)print x ## >>> [1,2,3,4,5,6] okx = xint(10)print x ## >>> 10 okx.add (2)print x ## >>> 10 # Not ok (#1)print type(x) ## >>> <class '__main__.xint'> okx += 5print type(x) ## >>> <type 'int'> # Not ok (#2) It works fine in the list case because the append method modifies the object "in place", without returning it. But in the int case, the add method doesn't modify the value of the external x variable. I suppose that's fine in the sense that self is a local variable in the add method of the class, but this is preventing me from modifying the initial value assigned to the instance of the class. Is it possible to extend a class this way or should I define a class property with the base type and map all the needed methods to this property? | Your two xint examples don't work for two different reasons. The first doesn't work because self += value is equivalent to self = self + value which just reassigns the local variable self to a different object (an integer) but doesn't change the original object. You can't really get this >>> x = xint(10)>>> x.add(2) to work with a subclass of int since integers are immutable . To get the second one to work you can define an __add__ method , like so: class xint(int): def __add__(self, value): return xint(int.__add__(self, value))>>> x = xint(10)>>> type(x)<class '__main__.xint'>>>> x += 3>>> x13>>> type(x)<class '__main__.xint'> | {
"score": 5,
"source": [
"https://Stackoverflow.com/questions/33534",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/394/"
]
} |
33,559 | I played with one of the early beta versions of PowerShell V1, but haven't used it since it went "gold". What is the best way to get started using PowerShell? Which version of PowerShell should I be using (V1.0 vs 2.0 CTP's)? What are you using PowerShell for? Are there any tools that make using PowerShell easier (that is, development environments)? | For learning PowerShell, there are a number of great resources Technet Virtual Labs ( Introduction to Windows PowerShell ) PowerShellCommunity.org - Forums, blogs, script repository powershell on irc.freenode.net PowerShell podcasts - PowerScripting.net and Get-Scripting.blogspot.com For IDE style environments, you have PowerShell Analyzer (free) and PowerGUI (free), PowerShell Plus (commercial), PrimalScript (commercial), and Admin Script Editor (commerical). I use PowerShell for everything that I can. Right now, I'm looking at Psake , a PowerShell based build script environment. I use if for managing my Active Directory, Hyper-V, Twitter, some keyboard automation (hosting PowerShell in a winforms app to grab keystrokes), and a ton of other stuff. Another cool project I have to check out is PSExpect for testing. I also use it for database access - monitoring changes made to rows in a database by applications. It is also integrated in to my network monitoring solution. I am also looking to use PowerShell as a scripting engine for a project I am working on. EDIT : If you are just learning PowerShell, I would focus on V1. As you get more comfortable, take a look at the CTP, but too much can change from the CTP to what is actually released as V2 to make that your learning tool. Version 2 is out and available from XP SP3, Server 2003, Vista, and Server 2008 and in the box for Win7 and Server 2008 R2. What you learned for V1 will still serve you well, but now I would concentrate on V2, as there is a superior feature set. Good luck! | {
"score": 7,
"source": [
"https://Stackoverflow.com/questions/33559",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/708/"
]
} |
33,577 | I want to check out all files in all subdirectories of a specified folder. (And it is painful to do this using the GUI, because there is no recursive checkout option). | Beware: ClearCase is File-centric, not repository centric (like SVN or CVS). That means it is rarely a good solution to checkout all files (and it can be fairly long with ClearCase ;) ) That being said, the question is perfectly legitimate and I would like to point out another way: open a cleartool session in the 'specified folder': c:\MyFolder> cleartoolcleartool> co -c "Reason for massive checkout" .../* does the trick too. But as the aku's answer, it does checkout everything : files and directories... and you may most not need to checkout directories! cleartool find somedir -type f -exec "cleartool checkout -c \"Reason for massive checkout\" \"%CLEARCASE_PN%\"" would only checkout files... Now the problem is to checkin everything that has changed. It is problematic since often not everything has changed, and CleaCase will trigger an error message when trying to check in an identical file. Meaning you will need 2 commands: ct lsco -r -cvi -fmt "ci -nc \"%n\"\n" | ctct lsco -r -cvi -fmt "unco -rm %n\n" | ct (with ' ct being ' cleartool ' : type ' doskey ct=cleartool $* ' on Windows to set that alias) Note that ct ci -nc will check-in with the comment used for the checkout stage. So it is not a checkin without a comment (like the -nc option -- or "no comment" -- could make believe). | {
"score": 6,
"source": [
"https://Stackoverflow.com/questions/33577",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/814/"
]
} |
33,637 | I assume it doesn't connect to anything (other than the satelite I guess), is this right? Or it does and has some kind of charge? | GPS, the Global Positioning System run by the United States Military, is free for civilian use, though the reality is that we're paying for it with tax dollars. However, GPS on cell phones is a bit more murky. In general, it won't cost you anything to turn on the GPS in your cell phone, but when you get a location it usually involves the cell phone company in order to get it quickly with little signal, as well as get a location when the satellites aren't visible (since the gov't requires a fix even if the satellites aren't visible for emergency 911 purposes). It uses up some cellular bandwidth. This also means that for phones without a regular GPS receiver, you cannot use the GPS at all if you don't have cell phone service. For this reason most cell phone companies have the GPS in the phone turned off except for emergency calls and for services they sell you (such as directions). This particular kind of GPS is called assisted GPS (AGPS), and there are several levels of assistance used. GPS A normal GPS receiver listens to a particular frequency for radio signals. Satellites send time coded messages at this frequency. Each satellite has an atomic clock, and sends the current exact time as well. The GPS receiver figures out which satellites it can hear, and then starts gathering those messages. The messages include time, current satellite positions, and a few other bits of information. The message stream is slow - this is to save power, and also because all the satellites transmit on the same frequency and they're easier to pick out if they go slow. Because of this, and the amount of information needed to operate well, it can take 30-60 seconds to get a location on a regular GPS. When it knows the position and time code of at least 3 satellites, a GPS receiver can assume it's on the earth's surface and get a good reading. 4 satellites are needed if you aren't on the ground and you want altitude as well. AGPS As you saw above, it can take a long time to get a position fix with a normal GPS. There are ways to speed this up, but unless you're carrying an atomic clock with you all the time, or leave the GPS on all the time, then there's always going to be a delay of between 5-60 seconds before you get a location. In order to save cost, most cell phones share the GPS receiver components with the cellular components, and you can't get a fix and talk at the same time. People don't like that (especially when there's an emergency) so the lowest form of GPS does the following: Get some information from the cell phone company to feed to the GPS receiver - some of this is gross positioning information based on what cellular towers can 'hear' your phone, so by this time they already phone your location to within a city block or so. Switch from cellular to GPS receiver for 0.1 second (or some small, practically unoticable period of time) and collect the raw GPS data (no processing on the phone). Switch back to the phone mode, and send the raw data to the phone company The phone company processes that data (acts as an offline GPS receiver) and send the location back to your phone. This saves a lot of money on the phone design, but it has a heavy load on cellular bandwidth, and with a lot of requests coming it requires a lot of fast servers. Still, overall it can be cheaper and faster to implement. They are reluctant, however, to release GPS based features on these phones due to this load - so you won't see turn by turn navigation here. More recent designs include a full GPS chip. They still get data from the phone company - such as current location based on tower positioning, and current satellite locations - this provides sub 1 second fix times. This information is only needed once, and the GPS can keep track of everything after that with very little power. If the cellular network is unavailable, then they can still get a fix after awhile. If the GPS satellites aren't visible to the receiver, then they can still get a rough fix from the cellular towers. But to completely answer your question - it's as free as the phone company lets it be, and so far they do not charge for it at all. I doubt that's going to change in the future. In the higher end phones with a full GPS receiver you may even be able to load your own software and access it, such as with mologogo on a motorola iDen phone - the J2ME development kit is free, and the phone is only $40 (prepaid phone with $5 credit). Unlimited internet is about $10 a month, so for $40 to start and $10 a month you can get an internet tracking system. (Prices circa August 2008) It's only going to get cheaper and more full featured from here on out... Re: Google maps and such Yes, Google maps and all other cell phone mapping systems require a data connection of some sort at varying times during usage. When you move far enough in one direction, for instance, it'll request new tiles from its server. Your average phone doesn't have enough storage to hold a map of the US, nor the processor power to render it nicely. iPhone would be able to if you wanted to use the storage space up with maps, but given that most iPhones have a full time unlimited data plan most users would rather use that space for other things. | {
"score": 7,
"source": [
"https://Stackoverflow.com/questions/33637",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1782/"
]
} |
33,664 | I've just started using Linq to SQL, and I'm wondering if anyone has any best practices they can share for managing dbml files. How do you keep them up to date with the database? Do you have a single dbml file for the entire database, or is it split into multiple logical units? How does managing this file work in a team environment? Any other tips and tricks welcome. | Have you looked at SqlMetal ? It's officially supported, although not promoted too much. You can use it to build dbmls from the commandline - we've used it as part of a db's continous integration updates (make sure you have really good code separation if you do this though - partial classes are a saviour - as the dbml will get overwritten). If I recall correctly it doesn't have quite the same features as the model designer in Visual Studio (I think it handles pluralisation differently). There a good post about it on Ben Hall's blog . | {
"score": 5,
"source": [
"https://Stackoverflow.com/questions/33664",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/637/"
]
} |
33,703 | I'm working on a visual studio 2005 vb.net windows forms project that's been around for several years. It's full of default textboxes, labels, dropdowns, datagrids, datetime pickers -- all the standard stuff. The end result is a very gray, old-looking project. What would be the best approach to making this project look fresh and snazzy? I'd rather not rewrite the entire solution with all brand new forms objects, but would that be avoidable? | I was actually just sprucing up a dialog today. A lot of it depends on what kind of application you have, and what OS it is running on. A couple of these tips will certainly go a long way to jazzing things up. Ensure adequate spacing between controls — don't cram them all together. Space is appealing. You might also trying flowing the controls a little differently when you have more space. Put in some new 3D and glossy images. You can put a big yellow exclamation mark on a custom warning dialog. Replace old toolbar buttons with new ones. Two libraries I have used and like are GlyFX and IconExperience . You can find free ones too. Ideally get a graphic artist to make some custom ones for the specific actions your application does to fill in between the common ones you use (make sure they all go together). That will go a long way to making it look fancy. Try a different font. Tahoma is a good one. Often times the default font is MS Sans Serif. You can do better. Avoid Times New Roman and Comic Sans though. Also avoid large blocks of bold — use it sparingly. Generally you want all your fonts the same, and only use different fonts sparingly to set certain bits of text apart. Add subdued colors to certain controls. This is a tricky one. You always want to use subdued colors, nothing bright or stark usually, but the colors should indicate something, or if you have a grid you can use it to show logical grouping. This is a slippery slope. Be aware that users might change their system colors, which will change how your colors look. Ideally give them a few color themes, or the ability to change colors. Instead of thinking eye-candy, think usability. Make the most common course of action obvious. Mark Miller of DevExpress has a great talk on the Science of User Interface Design. I actually have a video of it and might be able to post it online with a little clean-up. Invest in a few good quality 3rd party controls. Replacing all your controls could be a pain, but if you are using the default grids for example, you would really jazz it up with a good grid from DevExpress or some other component vendor. Be aware that different vendors have different philosophies for how their components are used, so swapping them out can be a bit of a pain. Start small to test the waters, and then try something really complicated before you commit to replacing all of them. The only thing worse then ugly grids is ugly grids mixed with pretty grids. Consistency is golden! You also might look at replacing your old tool bars and menus with a Ribbon Control like Microsoft did in Office 2007. Then everyone will think you are really uptown! Again only replacing key components and UI elements without thinking you need to revamp the whole UI. Of course pay attention to the basics like tab order, etc. Consistency, consistency, consistency. Some apps lend themselves to full blown skinning, while others don't. Generally you don't want anything flashy that gets used a lot. | {
"score": 6,
"source": [
"https://Stackoverflow.com/questions/33703",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3259/"
]
} |
33,708 | So I've got a JPanel implementing MouseListener and MouseMotionListener : import javax.swing.*;import java.awt.*;import java.awt.event.*;public class DisplayArea extends JPanel implements MouseListener, MouseMotionListener { public DisplayArea(Rectangle bounds, Display display) { setLayout(null); setBounds(bounds); setOpaque(false); setPreferredSize(new Dimension(bounds.width, bounds.height)); this.display = display; } public void paintComponent(Graphics g) { Graphics2D g2 = (Graphics2D)g; if (display.getControlPanel().Antialiasing()) { g2.addRenderingHints(new RenderingHints(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON)); } g2.setColor(Color.white); g2.fillRect(0, 0, getWidth(), getHeight()); } public void mousePressed(MouseEvent event) { System.out.println("mousePressed()"); mx1 = event.getX(); my1 = event.getY(); } public void mouseReleased(MouseEvent event) { System.out.println("mouseReleased()"); mx2 = event.getX(); my2 = event.getY(); int mode = display.getControlPanel().Mode(); switch (mode) { case ControlPanel.LINE: System.out.println("Line from " + mx1 + ", " + my1 + " to " + mx2 + ", " + my2 + "."); } } public void mouseEntered(MouseEvent event) { System.out.println("mouseEntered()"); } public void mouseExited(MouseEvent event) { System.out.println("mouseExited()"); } public void mouseClicked(MouseEvent event) { System.out.println("mouseClicked()"); } public void mouseMoved(MouseEvent event) { System.out.println("mouseMoved()"); } public void mouseDragged(MouseEvent event) { System.out.println("mouseDragged()"); } private Display display = null; private int mx1 = -1; private int my1 = -1; private int mx2 = -1; private int my2 = -1;} The trouble is, none of these mouse functions are ever called. DisplayArea is created like this: da = new DisplayArea(new Rectangle(CONTROL_WIDTH, 0, DISPLAY_WIDTH, DISPLAY_HEIGHT), this); I am not really a Java programmer (this is part of an assignment), but I can't see anything glaringly obvious. Can someone smarter than I see anything? | The implements mouselistener, mousemotionlistener just allows the displayArea class to listen to some, to be defined, Swing component's mouse events. You have to explicitly define what it should be listening at. So I suppose you could add something like this to the constructor: this.addMouseListener(this);this.addMouseMotionListener(this); | {
"score": 5,
"source": [
"https://Stackoverflow.com/questions/33708",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/61/"
]
} |
33,720 | How would I change the initial templates created by Xcode when creating a new Cocoa Class. I am referring to the comments and class name created when using Xcode's new class wizard. | You wouldn't change the existing templates. In other words, don't modify anything under the /Developer hierarchy (or wherever you installed your developer tools). Instead, clone the templates you want to have customized variants of. Then change their names and the information in them. Finally, put them in the appropriate location in your account's Library/Application Support folder, specifically: File templates: ~/Library/Application Support/Developer/Shared/Xcode/File Templates/ Target templates: ~/Library/Application Support/Developer/Shared/Xcode/Target Templates/ Project templates: ~/Library/Application Support/Developer/Shared/Xcode/Project Templates/ That way they won't be overwritten when you install new developer tools, and you can tweak them to your heart's content. Update For newer versions of Xcode the updated path will be: ~/Library/Developer/Xcode/Templates/File Templates/Source | {
"score": 8,
"source": [
"https://Stackoverflow.com/questions/33720",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3467/"
]
} |
33,728 | I'm going to build an API for a web app and I'm interested in what people can suggest as good practices. I'm already planning to make it versioned (version 1 can only control certain aspects of the system, version 2 could control more, but this may need a change in the way authentication is performed that would be incompatible with version 1), and the authentication will be distinct from the standard username/password people use to log in (if someone does use a malicious tool it won't open them up to full impersonation, just whatever the api allows). Does anyone have further ideas, or examples of sites with particularly good APIs you have used? | Read the RESTful Web Services book, which give you a good overview of how to use REST in practice, and get to up to speed quickly enough to get started now, with some confidence. This is more useful than just looking at an existing API, because it also discusses design choices and trade-offs. | {
"score": 5,
"source": [
"https://Stackoverflow.com/questions/33728",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1612/"
]
} |
33,739 | Does anyone know how to debug JSP in IntelliJ IDEA? When I set breakpoint in my JSP files, those breakpoints never seem to take effect. The debugger never hits them. IDEA seems to think that the breakpoints are valid. I do see a red dot placed to the left of the line where I place my breakpoint. I read in IntelliJ forum in this post that JSP files need to be under web-inf for debugging to work. But then I also read that JSP files placed under web-inf won't be directly accessible by the user. I am not sure who's really right. | For JSP debugging in Intellij there are some configurations that must be in order. The fact that Intellij always allows you to add a breakpoint on a JSP line does not necessarily imply that you’ve configured JSP debugging. In the following I refer to Intellij 8 configuration, w.r.t. previous versions you will need to do similar operations as the concepts are the same. In order to enable JSP debugging you must do two steps: set a web application configuration in your project and add a web application server configuration. Web application Configuration : in order to have JSP debugging, you must have a “web” facet in your project structure, pointing to the correct web.xml file. Depending on the kind of web application structure you are using, the facet may be detected automatically by Intellij (go anyway to check what it has done) or you may have to add it manually. Remember in the “Java EE build settings” tab to set as anable “Create web facet exploded directory”; if you don’t want duplications, a trick is just to enable it and point to your already existing directory. (Web) Application server : Go to “edit configurations”, there you have to add to configurations an application server, not launch the web server as an application like any other. In this way Intellij will be able to intercept JSP calls. In the list of application servers, you should have the default one, Tomcat. Be sure to have a local Tomcat installation before you do this, and point to that when adding the web application server. The last trick is going to the “Deployment” tab and selecting as “Deployment source” the same facet that you configured in the previous step. The same configuration works if you want to use another web application server, I tested it with the latest Caucho Resin releases and debugging works fine (it didn’t with the previous Intellij and Resin combinations). If you don’t see Tomcat in the list of available application servers to add, check the plugins in the general Intellij settings pane: in the latest releases, more and more functionality has become “pluggable”, and even very basic functions may be disabled; this plugin is called “Tomcat integration”. Finally, it is surely not true that JSP files need to be under WEB-INF to be under debugging. | {
"score": 5,
"source": [
"https://Stackoverflow.com/questions/33739",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
]
} |
33,746 | At work we are being asked to create XML files to pass data to another offline application that will then create a second XML file to pass back in order to update some of our data. During the process we have been discussing with the team of the other application about the structure of the XML file. The sample I came up with is essentially something like: <INVENTORY> <ITEM serialNumber="something" location="something" barcode="something"> <TYPE modelNumber="something" vendor="something"/> </ITEM></INVENTORY> The other team said that this was not industry standard and that attributes should only be used for meta data. They suggested: <INVENTORY> <ITEM> <SERIALNUMBER>something</SERIALNUMBER> <LOCATION>something</LOCATION> <BARCODE>something</BARCODE> <TYPE> <MODELNUMBER>something</MODELNUMBER> <VENDOR>something</VENDOR> </TYPE> </ITEM></INVENTORY> The reason I suggested the first is that the size of the file created is much smaller. There will be roughly 80000 items that will be in the file during transfer. Their suggestion in reality turns out to be three times larger than the one I suggested. I searched for the mysterious "Industry Standard" that was mentioned, but the closest I could find was that XML attributes should only be used for meta data, but said the debate was about what was actually meta data. After the long winded explanation (sorry) how do you determine what is meta data, and when designing the structure of an XML document how should you decide when to use an attribute or an element? | I use this rule of thumb: An Attribute is something that is self-contained, i.e., a color, an ID, a name. An Element is something that does or could have attributes of its own or contain other elements. So yours is close. I would have done something like: EDIT : Updated the original example based on feedback below. <ITEM serialNumber="something"> <BARCODE encoding="Code39">something</BARCODE> <LOCATION>XYX</LOCATION> <TYPE modelNumber="something"> <VENDOR>YYZ</VENDOR> </TYPE> </ITEM> | {
"score": 8,
"source": [
"https://Stackoverflow.com/questions/33746",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3340/"
]
} |
33,751 | I would like to add the following MIME type to a site run by Apache : <mime-mapping> <extension>jnlp</extension> <mime-type>application/x-java-jnlp-file</mime-type></mime-mapping> That is the Tomcat format. I'm on a shared host, so I can only create an .htaccess file. Would someone please specify the complete contents of such a file? | AddType application/x-java-jnlp-file .jnlp Note that you might not actually be allowed to do that. See also the documentation of the AddType directive and the .htaccess howto . | {
"score": 5,
"source": [
"https://Stackoverflow.com/questions/33751",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/338/"
]
} |
33,778 | One of my co-workers checked in a some files in SVN and one of the files has a password in it. The password has been removed from the file and a new version checked in but the password is obviously still in the repository if we look at the revision history and go to that revision. (We're using TortoiseSVN as the client.) So how do I securely delete that single file from the repository in SVN? | link to subversion FAQ entry on this | {
"score": 5,
"source": [
"https://Stackoverflow.com/questions/33778",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1463/"
]
} |
33,813 | I noticed that many people here use TextMate for coding on OS X. I've recently started using it, and although I like its minimalistic interface, it makes it harder to stumble upon cool features if you don't know what you're looking for. So, what feature have you found most helpful for coding (mainly in Python)? Are there any third-party bundles I should know about, besides what's included? | Don't neglect the 'mate' command line tool. You can use it to pipe output into TextMate, so if you do the following... diff file1.py file2.py | mate ...it will not only open in TextMate, but it is smart enough to know that you're looking at a diff and highlight lines on screen. TextMate's SVN integration is great; it also seems to have bundles for some other version control systems as well. Add GetBundle to browse the bundle repository. I found the jQuery bundle through it and it's very handy. As others have mentioned, rolling your own bundle for frequently used snippets is very helpful. If you have some snippets that are specific to a project or framework, you might want to prefix all of them with a common letter to keep the namespace tidy. | {
"score": 6,
"source": [
"https://Stackoverflow.com/questions/33813",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3002/"
]
} |
33,822 | Every time I turn on my company-owned development machine, I have to kill 10+ processes using the Task Manager or any other process management app just to get decent performance out of my IDE. Yes, these are processes from programs that my company installs on my machine for security and compliance. What I'd like to do is have a .bat file or script of some kind with which I can kill the processes in question. Does anybody know how to do this? | You can do this with ' taskkill '.With the /IM parameter, you can specify image names. Example: taskkill /im somecorporateprocess.exe You can also do this to ' force ' kill: Example: taskkill /f /im somecorporateprocess.exe Just add one line per process you want to kill, save it as a .bat file, and add in your startup directory. Problem solved! If this is a legacy system, PsKill will do the same. | {
"score": 9,
"source": [
"https://Stackoverflow.com/questions/33822",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3030/"
]
} |
33,901 | I'm looking for a library to handle iCalendar data in Java. Open source, well-documented implementations with a good object model are preferred. iCal parsing capabilities are less important to me, but still nice to have. Does anyone have any recommendations? | I had limited success with iCal4j ( intro ) on a project last year. It seems to be a fairly popular choice for ical work in the java community. If I remember correctly the API can be slightly confusing at first glance.However It's pretty solid in the long run. Good luck, Brian | {
"score": 7,
"source": [
"https://Stackoverflow.com/questions/33901",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2783/"
]
} |
33,923 | Whilst starting to learn lisp, I've come across the term tail-recursive . What does it mean exactly? | Consider a simple function that adds the first N natural numbers. (e.g. sum(5) = 0 + 1 + 2 + 3 + 4 + 5 = 15 ). Here is a simple JavaScript implementation that uses recursion: function recsum(x) { if (x === 0) { return 0; } else { return x + recsum(x - 1); }} If you called recsum(5) , this is what the JavaScript interpreter would evaluate: recsum(5)5 + recsum(4)5 + (4 + recsum(3))5 + (4 + (3 + recsum(2)))5 + (4 + (3 + (2 + recsum(1))))5 + (4 + (3 + (2 + (1 + recsum(0)))))5 + (4 + (3 + (2 + (1 + 0))))5 + (4 + (3 + (2 + 1)))5 + (4 + (3 + 3))5 + (4 + 6)5 + 1015 Note how every recursive call has to complete before the JavaScript interpreter begins to actually do the work of calculating the sum. Here's a tail-recursive version of the same function: function tailrecsum(x, running_total = 0) { if (x === 0) { return running_total; } else { return tailrecsum(x - 1, running_total + x); }} Here's the sequence of events that would occur if you called tailrecsum(5) , (which would effectively be tailrecsum(5, 0) , because of the default second argument). tailrecsum(5, 0)tailrecsum(4, 5)tailrecsum(3, 9)tailrecsum(2, 12)tailrecsum(1, 14)tailrecsum(0, 15)15 In the tail-recursive case, with each evaluation of the recursive call, the running_total is updated. Note: The original answer used examples from Python. These have been changed to JavaScript, since Python interpreters don't support tail call optimization . However, while tail call optimization is part of the ECMAScript 2015 spec , most JavaScript interpreters don't support it . | {
"score": 12,
"source": [
"https://Stackoverflow.com/questions/33923",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2045/"
]
} |
33,955 | Could someone tell me what the units the SetTimeout(int) method in the ICriteria interface uses? Is it milliseconds, seconds, minutes or other? | A little bit of poking around suggests that it could be seconds: Assuming that ICriteria is the same as the Criteria interface in Hibernate core, then the JavaDoc for org.hibernate.Criteria provides a hint - the "see also" link to java.sql.Statement.setQueryTimeout() . The latter refers to its timeout parameter as seconds. Assuming that the NHibernate implementation follows the implied contract of that method, then that should be fine. However, for peace of mind's sake, I went and looked for some NHibernate specific stuff. There are various references to CommandTimeout; for example, here , related to NHibernate. Sure enough, the documentation for CommandTimeout states that it's seconds. I almost didn't post the above, because I don't know the answer outright, and can't find any concrete documentation - but since there is so little on the issue, I figured it couldn't hurt to present these findings. | {
"score": 6,
"source": [
"https://Stackoverflow.com/questions/33955",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/493/"
]
} |
33,960 | I would like to retrieve the ethernet address of the network interface that is used to access a particular website. How can this be done in Java? Solution Note that the accepted solution of getHardwareAddress is only available in Java 6. There does not seem to be a solution for Java 5 aside from executing i(f|p)confing. | java.net.NetworkInterface.getHardwareAddress (method added in Java 6) It has to be called on the machine you are interested in - the MAC is not transferred across network boundaries (i.e. LAN and WAN). If you want to make use of it on a website server to interrogate the clients, you'd have to run an applet that would report the result back to you. For Java 5 and older I found code parsing output of command line tools on various systems . | {
"score": 5,
"source": [
"https://Stackoverflow.com/questions/33960",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/338/"
]
} |
33,969 | We're experimenting with various ways to throttle user actions in a given time period : Limit question/answer posts Limit edits Limit feed retrievals For the time being, we're using the Cache to simply insert a record of user activity - if that record exists if/when the user does the same activity, we throttle. Using the Cache automatically gives us stale data cleaning and sliding activity windows of users, but how it will scale could be a problem. What are some other ways of ensuring that requests/user actions can be effectively throttled (emphasis on stability)? | Here's a generic version of what we've been using on Stack Overflow for the past year: /// <summary>/// Decorates any MVC route that needs to have client requests limited by time./// </summary>/// <remarks>/// Uses the current System.Web.Caching.Cache to store each client request to the decorated route./// </remarks>[AttributeUsage(AttributeTargets.Method, AllowMultiple = false)]public class ThrottleAttribute : ActionFilterAttribute{ /// <summary> /// A unique name for this Throttle. /// </summary> /// <remarks> /// We'll be inserting a Cache record based on this name and client IP, e.g. "Name-192.168.0.1" /// </remarks> public string Name { get; set; } /// <summary> /// The number of seconds clients must wait before executing this decorated route again. /// </summary> public int Seconds { get; set; } /// <summary> /// A text message that will be sent to the client upon throttling. You can include the token {n} to /// show this.Seconds in the message, e.g. "Wait {n} seconds before trying again". /// </summary> public string Message { get; set; } public override void OnActionExecuting(ActionExecutingContext c) { var key = string.Concat(Name, "-", c.HttpContext.Request.UserHostAddress); var allowExecute = false; if (HttpRuntime.Cache[key] == null) { HttpRuntime.Cache.Add(key, true, // is this the smallest data we can have? null, // no dependencies DateTime.Now.AddSeconds(Seconds), // absolute expiration Cache.NoSlidingExpiration, CacheItemPriority.Low, null); // no callback allowExecute = true; } if (!allowExecute) { if (String.IsNullOrEmpty(Message)) Message = "You may only perform this action every {n} seconds."; c.Result = new ContentResult { Content = Message.Replace("{n}", Seconds.ToString()) }; // see 409 - http://www.w3.org/Protocols/rfc2616/rfc2616-sec10.html c.HttpContext.Response.StatusCode = (int)HttpStatusCode.Conflict; } }} Sample usage: [Throttle(Name="TestThrottle", Message = "You must wait {n} seconds before accessing this url again.", Seconds = 5)]public ActionResult TestThrottle(){ return Content("TestThrottle executed");} The ASP.NET Cache works like a champ here - by using it, you get automatic clean-up of your throttle entries. And with our growing traffic, we're not seeing that this is an issue on the server. Feel free to give feedback on this method; when we make Stack Overflow better, you get your Ewok fix even faster :) | {
"score": 9,
"source": [
"https://Stackoverflow.com/questions/33969",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3/"
]
} |
33,978 | How would you go about finding out how much memory is being used by an object? I know it is possible to find out how much is used by a block of code, but not by an instantiated object (anytime during its life), which is what I want. | There's no easy way to find out the memory size of a python object . One of the problems you may find is that Python objects - like lists and dicts - may have references to other python objects (in this case, what would your size be? The size containing the size of each object or not?). There are some pointers overhead and internal structures related to object types and garbage collection. Finally, some python objects have non-obvious behaviors. For instance, lists reserve space for more objects than they have, most of the time; dicts are even more complicated since they can operate in different ways (they have a different implementation for small number of keys and sometimes they over allocate entries). There is a big chunk of code (and an updated big chunk of code ) out there to try to best approximate the size of a python object in memory. You may also want to check some old description about PyObject (the internal C struct that represents virtually all python objects). | {
"score": 8,
"source": [
"https://Stackoverflow.com/questions/33978",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3119/"
]
} |
34,020 | A reliable coder friend told me that Python's current multi-threading implementation is seriously buggy - enough to avoid using altogether. What can said about this rumor? | Python threads are good for concurrent I/O programming . Threads are swapped out of the CPU as soon as they block waiting for input from file, network, etc. This allows other Python threads to use the CPU while others wait. This would allow you to write a multi-threaded web server or web crawler, for example. However, Python threads are serialized by the GIL when they enter interpreter core. This means that if two threads are crunching numbers, only one can run at any given moment. It also means that you can't take advantage of multi-core or multi-processor architectures. There are solutions like running multiple Python interpreters concurrently, using a C based threading library. This is not for the faint of heart and the benefits might not be worth the trouble. Let's hope for an all Python solution in a future release. | {
"score": 7,
"source": [
"https://Stackoverflow.com/questions/34020",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3561/"
]
} |
34,059 | What is the difference between Build Solution and Batch Build in Visual Studio 2008? | The key point which seems to be missed in both the existing answers is that batch build allows you to build multiple configurations of each project (e.g. you can build debug and release configurations with a single operation). With a normal build, you have to use the configuration manager to select just one configuration for each project. | {
"score": 6,
"source": [
"https://Stackoverflow.com/questions/34059",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/45603/"
]
} |
34,065 | Given the key for some registry value (e.g. HKEY_LOCAL_MACHINE\blah\blah\blah\foo) how can I: Safely determine that such a key exists. Programmatically (i.e. with code) get its value. I have absolutely no intention of writing anything back to the registry (for the duration of my career if I can help it). So we can skip the lecture about every molecule in my body exploding at the speed of light if I write to the registry incorrectly. Prefer answers in C++, but mostly just need to know what the special Windows API incantation to get at the value is. | Here is some pseudo-code to retrieve the following: If a registry key exists What the default value is for that registry key What a string value is What a DWORD value is Example code: Include the library dependency: Advapi32.lib HKEY hKey;LONG lRes = RegOpenKeyExW(HKEY_LOCAL_MACHINE, L"SOFTWARE\\Perl", 0, KEY_READ, &hKey);bool bExistsAndSuccess (lRes == ERROR_SUCCESS);bool bDoesNotExistsSpecifically (lRes == ERROR_FILE_NOT_FOUND);std::wstring strValueOfBinDir;std::wstring strKeyDefaultValue;GetStringRegKey(hKey, L"BinDir", strValueOfBinDir, L"bad");GetStringRegKey(hKey, L"", strKeyDefaultValue, L"bad");LONG GetDWORDRegKey(HKEY hKey, const std::wstring &strValueName, DWORD &nValue, DWORD nDefaultValue){ nValue = nDefaultValue; DWORD dwBufferSize(sizeof(DWORD)); DWORD nResult(0); LONG nError = ::RegQueryValueExW(hKey, strValueName.c_str(), 0, NULL, reinterpret_cast<LPBYTE>(&nResult), &dwBufferSize); if (ERROR_SUCCESS == nError) { nValue = nResult; } return nError;}LONG GetBoolRegKey(HKEY hKey, const std::wstring &strValueName, bool &bValue, bool bDefaultValue){ DWORD nDefValue((bDefaultValue) ? 1 : 0); DWORD nResult(nDefValue); LONG nError = GetDWORDRegKey(hKey, strValueName.c_str(), nResult, nDefValue); if (ERROR_SUCCESS == nError) { bValue = (nResult != 0) ? true : false; } return nError;}LONG GetStringRegKey(HKEY hKey, const std::wstring &strValueName, std::wstring &strValue, const std::wstring &strDefaultValue){ strValue = strDefaultValue; WCHAR szBuffer[512]; DWORD dwBufferSize = sizeof(szBuffer); ULONG nError; nError = RegQueryValueExW(hKey, strValueName.c_str(), 0, NULL, (LPBYTE)szBuffer, &dwBufferSize); if (ERROR_SUCCESS == nError) { strValue = szBuffer; } return nError;} | {
"score": 7,
"source": [
"https://Stackoverflow.com/questions/34065",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3551/"
]
} |
34,079 | What's the best way to specify a proxy with username and password for an http connection in python? | This works for me: import urllib2proxy = urllib2.ProxyHandler({'http': 'http://username:password@proxyurl:proxyport'})auth = urllib2.HTTPBasicAuthHandler()opener = urllib2.build_opener(proxy, auth, urllib2.HTTPHandler)urllib2.install_opener(opener)conn = urllib2.urlopen('http://python.org')return_str = conn.read() | {
"score": 6,
"source": [
"https://Stackoverflow.com/questions/34079",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3573/"
]
} |
34,093 | I want to apply an XSLT Stylesheet to an XML Document using C# and write the output to a File. | I found a possible answer here: http://web.archive.org/web/20130329123237/http://www.csharpfriends.com/Articles/getArticle.aspx?articleID=63 From the article: XPathDocument myXPathDoc = new XPathDocument(myXmlFile) ;XslTransform myXslTrans = new XslTransform() ;myXslTrans.Load(myStyleSheet);XmlTextWriter myWriter = new XmlTextWriter("result.html",null) ;myXslTrans.Transform(myXPathDoc,null,myWriter) ; Edit: But my trusty compiler says, XslTransform is obsolete: Use XslCompiledTransform instead: XPathDocument myXPathDoc = new XPathDocument(myXmlFile) ;XslCompiledTransform myXslTrans = new XslCompiledTransform();myXslTrans.Load(myStyleSheet);XmlTextWriter myWriter = new XmlTextWriter("result.html",null);myXslTrans.Transform(myXPathDoc,null,myWriter); | {
"score": 9,
"source": [
"https://Stackoverflow.com/questions/34093",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2260/"
]
} |
34,120 | I've been doing some HTML scraping in PHP using regular expressions. This works, but the result is finicky and fragile. Has anyone used any packages that provide a more robust solution? A config driven solution would be ideal, but I'm not picky. | I would recomend PHP Simple HTML DOM Parser after you have scraped the HTML from the page. It supports invalid HTML, and provides a very easy way to handle HTML elements. | {
"score": 6,
"source": [
"https://Stackoverflow.com/questions/34120",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3575/"
]
} |
34,125 | It seems to me that it would work perfectly well to do tail-recursion optimization in both C and C++, yet while debugging I never seem to see a frame stack that indicates this optimization. That is kind of good, because the stack tells me how deep the recursion is. However, the optimization would be kind of nice as well. Do any C++ compilers do this optimization? Why? Why not? How do I go about telling the compiler to do it? For MSVC: /O2 or /Ox For GCC: -O2 or -O3 How about checking if the compiler has done this in a certain case? For MSVC, enable PDB output to be able to trace the code, then inspect the code For GCC..? I'd still take suggestions for how to determine if a certain function is optimized like this by the compiler (even though I find it reassuring that Konrad tells me to assume it) It is always possible to check if the compiler does this at all by making an infinite recursion and checking if it results in an infinite loop or a stack overflow (I did this with GCC and found out that -O2 is sufficient), but I want to be able to check a certain function that I know will terminate anyway. I'd love to have an easy way of checking this :) After some testing, I discovered that destructors ruin the possibility of making this optimization. It can sometimes be worth it to change the scoping of certain variables and temporaries to make sure they go out of scope before the return-statement starts. If any destructor needs to be run after the tail-call, the tail-call optimization can not be done. | All current mainstream compilers perform tail call optimisation fairly well (and have done for more than a decade), even for mutually recursive calls such as: int bar(int, int);int foo(int n, int acc) { return (n == 0) ? acc : bar(n - 1, acc + 2);}int bar(int n, int acc) { return (n == 0) ? acc : foo(n - 1, acc + 1);} Letting the compiler do the optimisation is straightforward: Just switch on optimisation for speed: For MSVC, use /O2 or /Ox . For GCC, Clang and ICC, use -O3 An easy way to check if the compiler did the optimisation is to perform a call that would otherwise result in a stack overflow — or looking at the assembly output. As an interesting historical note, tail call optimisation for C was added to the GCC in the course of a diploma thesis by Mark Probst. The thesis describes some interesting caveats in the implementation. It's worth reading. | {
"score": 8,
"source": [
"https://Stackoverflow.com/questions/34125",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2971/"
]
} |
34,144 | I would like to know which dependency described in my pom.xml brings a transitive dependency in my target directory. To be more precise, I have the library "poi-2.5.1-final-20040804.jar" in my WEB-INF/lib directory and I would like to know which dependency in my pom.xml brings that. | To add to @David Crow, here's a dependency:tree example from the Maven site: mvn dependency:tree -Dincludes=velocity:velocity might output [INFO] [dependency:tree][INFO] org.apache.maven.plugins:maven-dependency-plugin:maven-plugin:2.0-alpha-5-SNAPSHOT[INFO] \- org.apache.maven.doxia:doxia-site-renderer:jar:1.0-alpha-8:compile[INFO] \- org.codehaus.plexus:plexus-velocity:jar:1.1.3:compile[INFO] \- velocity:velocity:jar:1.4:compile | {
"score": 8,
"source": [
"https://Stackoverflow.com/questions/34144",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3122/"
]
} |
34,155 | I'm trying to grasp the concept of continuations and I found several small teaching examples like this one from the Wikipedia article : (define the-continuation #f)(define (test) (let ((i 0)) ; call/cc calls its first function argument, passing ; a continuation variable representing this point in ; the program as the argument to that function. ; ; In this case, the function argument assigns that ; continuation to the variable the-continuation. ; (call/cc (lambda (k) (set! the-continuation k))) ; ; The next time the-continuation is called, we start here. (set! i (+ i 1)) i)) I understand what this little function does, but I can't see any obvious application of it. While I don't expect to use continuations all over my code anytime soon, I wish I knew a few cases where they can be appropriate. So I'm looking for more explicitely usefull code samples of what continuations can offer me as a programmer. Cheers! | In Algo & Data II we used these all the times to "exit" or "return" from a (long) function for example the BFS algorthm to traverse trees with was implemented like this: (define (BFS graph root-discovered node-discovered edge-discovered edge-bumped . nodes) (define visited (make-vector (graph.order graph) #f)) (define q (queue.new)) (define exit ()) (define (BFS-tree node) (if (node-discovered node) (exit node)) (graph.map-edges graph node (lambda (node2) (cond ((not (vector-ref visited node2)) (when (edge-discovered node node2) (vector-set! visited node2 #t) (queue.enqueue! q node2))) (else (edge-bumped node node2))))) (if (not (queue.empty? q)) (BFS-tree (queue.serve! q)))) (call-with-current-continuation (lambda (my-future) (set! exit my-future) (cond ((null? nodes) (graph.map-nodes graph (lambda (node) (when (not (vector-ref visited node)) (vector-set! visited node #t) (root-discovered node) (BFS-tree node))))) (else (let loop-nodes ((node-list (car nodes))) (vector-set! visited (car node-list) #t) (root-discovered (car node-list)) (BFS-tree (car node-list)) (if (not (null? (cdr node-list))) (loop-nodes (cdr node-list))))))))) As you can see the algorithm will exit when the node-discovered function returns true: (if (node-discovered node) (exit node)) the function will also give a "return value": 'node' why the function exits, is because of this statement: (call-with-current-continuation (lambda (my-future) (set! exit my-future) when we use exit, it will go back to the state before the execution, emptying the call-stack and return the value you gave it. So basically, call-cc is used (here) to jump out of a recursive function, instead of waiting for the entire recursion to end by itself (which can be quite expensive when doing lots of computational work) another smaller example doing the same with call-cc: (define (connected? g node1 node2) (define visited (make-vector (graph.order g) #f)) (define return ()) (define (connected-rec x y) (if (eq? x y) (return #t)) (vector-set! visited x #t) (graph.map-edges g x (lambda (t) (if (not (vector-ref visited t)) (connected-rec t y))))) (call-with-current-continuation (lambda (future) (set! return future) (connected-rec node1 node2) (return #f)))) | {
"score": 5,
"source": [
"https://Stackoverflow.com/questions/34155",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2797/"
]
} |
34,194 | Where can I find some good pointers on best practices for running ASP.NET MVC on IIS6? I haven't seen any realistic options for web-hosts who provide IIS7-hosting yet. Mostly because I don't live in the U.S. So I was wondering on how you best build applications in ASP.NET MVC and make it easily available to deploy on both IIS6 and IIS7. Keep in mind that this is for standard web-hosts, so there is no access to ISAPI-filters or special settings inside IIS6. Are there anything else one should think about when developing ASP.NET MVC-applications to target IIS6? Any functions that doesn't work? UPDATE: One of the bigger issues is the thing with routes. The pattern {controller}/{action} will work on IIS7, but not IIS6 which needs {controller}.mvc/{action}. So how do I make this transparent? Again, no ISAPI and no IIS-settings , please. | It took me a bit, but I figured out how to make the extensions work with IIS 6. First, you need to rework the base routing to include .aspx so that they will be routed through the ASP.NET ISAPI filter. routes.MapRoute( "Default", // Route name "{controller}.aspx/{action}/{id}", // URL with parameters new { controller = "Home", action = "Index", id = "" } // Parameter defaults); If you navigate to Home.aspx, for example, your site should be working fine. But Default.aspx and the default page address of http://[website]/ stop working correctly. So how is that fixed? Well, you need to define a second route. Unfortunately, using Default.aspx as the route does not work properly: routes.MapRoute( "Default2", // Route name "Default.aspx", // URL with parameters new { controller = "Home", action = "Index", id = "" } // Parameter defaults); So how do you get this to work? Well, this is where you need the original routing code: routes.MapRoute( "Default2", // Route name "{controller}/{action}/{id}", // URL with parameters new { controller = "Home", action = "Index", id = "" } // Parameter defaults); When you do this, Default.aspx and http://[website]/ both start working again, I think because they become successfully mapped back to the Home controller. So the complete solution is: public class MvcApplication : System.Web.HttpApplication{ public static void RegisterRoutes(RouteCollection routes) { routes.IgnoreRoute("{resource}.axd/{*pathInfo}"); routes.MapRoute( "Default", // Route name "{controller}.aspx/{action}/{id}", // URL with parameters new { controller = "Home", action = "Index", id = "" } // Parameter defaults ); routes.MapRoute( "Default2", // Route name "{controller}/{action}/{id}", // URL with parameters new { controller = "Home", action = "Index", id = "" } // Parameter defaults ); } protected void Application_Start() { RegisterRoutes(RouteTable.Routes); }} And your site should start working just fine under IIS 6. (At least it does on my PC.) And as a bonus, if you are using Html.ActionLink() in your pages, you should not have to change any other line of code throughout the entire site. This method takes care of properly tagging on the .aspx extension to the controller. | {
"score": 5,
"source": [
"https://Stackoverflow.com/questions/34194",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2429/"
]
} |
34,249 | What's the best (halting) algorithm for determining if a linked list has a cycle in it? [Edit] Analysis of asymptotic complexity for both time and space would be sweet so answers can be compared better. [Edit] Original question was not addressing nodes with outdegree > 1, but there's some talk about it. That question is more along the lines of "Best algorithm to detect cycles in a directed graph". | Have two pointers iterating through the list; make one iterate through at twice the speed of the other, and compare their positions at each step. Off the top of my head, something like: node* tortoise(begin), * hare(begin);while(hare = hare->next){ if(hare == tortoise) { throw std::logic_error("There's a cycle"); } hare = hare->next; if(hare == tortoise) { throw std::logic_error("There's a cycle"); } tortoise = tortoise->next;} O(n), which is as good as you can get. | {
"score": 7,
"source": [
"https://Stackoverflow.com/questions/34249",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3594/"
]
} |
34,284 | I get the following error when building my Windows Forms solution: "LC.exe" exited with code -1 I use two commercial Windows Forms Libraries: Infragistics and the Gantt-Control from plexityhide.com, that's why I have licenses.licx files in my WinForms Projects. We also use Visual Sourcesafe as our Source Control. When the licenses.licx files are in the Projects I cannot build without the above error. However, when I exclude them from my projects the build works fine. But I need the licenses.licx files when I want to work with the commercial controls in the designer. This is a brand new developer machine with Windows XP SP3 (German) and Visual Studio 2005 Team Edition for Software Developers (German) with SP1. It's Windows XP 32-Bit by the way. Any suggestions? | Problem mainly arises due to license file. Exclude the file licenses.licx from your project | {
"score": 5,
"source": [
"https://Stackoverflow.com/questions/34284",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3353/"
]
} |
34,312 | I was wondering if anyone that has experience in both this stuff can shed some light on the significant difference between the two if any? Any specific strength of each that makes it suitable for any specific case? | This question is quite dated but as it is still getting traffic and answers I though I state my point here again even so I already did it on some other (newer) questions. I'm really really baffled that SimpleTest still is considered an alternative to phpunit. Maybe i'm just misinformed but as far as I've seen: PHPUnit is the standard; most frameworks use it (like Zend Framework (1&2), Cake, Agavi, even Symfony is dropping their own Framework in Symfony 2 for phpunit). PHPUnit is integrated in every PHP IDE (Eclipse, Netbeans, Zend Stuide, PHPStorm) and works nicely. Simpletest has an eclipse extension for PHP 5.1 (a.k.a. old) and nothing else. PHPUnit works fine with every continuous integration server since it outputs all standard log files for code coverage and test reports. Simpletest does not. While this is not a big problem to start with it will bite you big time once you stop "just testing" and start developing software (Yes that statement is provocative :) Don't take it too seriously). PHPUnit is actively maintained, stable and works great for every codebase, every scenario and every way you want to write your tests. (Subjective) PHPUnit provides much nicer code coverage reports than Simpletest With PHPUnit you also get these reports inside your IDE ( Netbeans , Eclipse, ...) Also there are a couple of suggestings for a web interface to phpunit tests . I've yet to see any argument in favor of SimpleTest. It's not even simpler to install since PHPUnit is available via pear: pear channel-discover pear.phpunit.depear install phpunit/PHPUnit and the "first test" looks pretty much the same. As of PHPUnit 3.7 it's even easier to install it by just using the PHAR Archive wget http://pear.phpunit.de/get/phpunit.pharchmod +x phpunit-3.7.6.phar or for windows just downloading the phar and running: php phpunit-.phar or when using the supported composer install ways like "require-dev": { "phpunit/phpunit": "3.7.*"} to your composer.json. For everything you want to test PHPUnit will have a solution and you will be able to find help pretty much anywhere (SO, #phpunit irc channel on freenode, pretty much every php developer ;) ) Please correct me if I've stated something wrong or forgot something :) Overview of PHP Testing tools Video: http://conference.phpnw.org.uk/phpnw11/schedule/sebastian-bergmann/ Slides: http://www.slideshare.net/sebastian_bergmann/the-php-testers-toolbox-osi-days-2011 It mentions stuff like Atoum which calls its self: "A simple, modern and intuitive unit testing framework for PHP!" Full disclosure I've originally written this answer Jan. 2011 where I had no affiliation with any PHP Testing project. Since then I became a contributor to PHPUnit. | {
"score": 8,
"source": [
"https://Stackoverflow.com/questions/34312",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2976/"
]
} |
34,314 | I want to implement search functionality for a website (assume it is similar to SO). I don't want to use Google search of stuff like that. My question is: How do I implement this? There are two methods I am aware of: Search all the databases in the application when the user gives his query. Index all the data I have and store it somewhere else and query from there (like what Google does). Can anyone tell me which way to go? What are the pros and cons? Better, are there any better ways to do this? | Use lucene, http://lucene.apache.org/java/docs/ Apache Lucene is a high-performance, full-featured text search engine library written entirely in Java. It is a technology suitable for nearly any application that requires full-text search, especially cross-platform. It is available in java and .net. It is also in available in php in the form of a zend framework module. Lucene does what you wanted(indexing of the searched items), you have to keep track of a lucene index but it is much better than doing a database search in terms of performance. BTW, SO search is powered by lucene. :D | {
"score": 6,
"source": [
"https://Stackoverflow.com/questions/34314",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/184/"
]
} |
34,390 | Since there are no header sections for user controls in asp.net, user controls have no way of knowing about stylesheet files. So css classes in the user controls are not recognized by visual studio and produces warnings. How can I make a user control know that it will relate to a css class, so if it is warning me about a non-existing css class, it means that the class really do not exist? Edit: Or should I go for a different design like exposing css classes as properties like "HeaderStyle-CssClass" of GridView? | Here's what I did: <link rel="Stylesheet" type="text/css" href="Stylesheet.css" id="style" runat="server" visible="false" /> It fools Visual Studio into thinking you've added a stylesheet to the page but it doesn't get rendered. Here's an even more concise way to do this with multiple references; <% if (false) { %> <link rel="Stylesheet" type="text/css" href="Stylesheet.css" /> <script type="text/javascript" src="js/jquery-1.2.6.js" /><% } %> As seen in this blog post from Phil Haack. | {
"score": 7,
"source": [
"https://Stackoverflow.com/questions/34390",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/31505/"
]
} |
34,394 | How would you programmacially abbreviate XHTML to an arbitrary number of words without leaving unclosed or corrupted tags? i.e. <p> Proin tristique dapibus neque. Nam eget purus sit amet leo tincidunt accumsan.</p><p> Proin semper, orci at mattis blandit, augue justo blandit nulla. <span>Quisque ante congue justo</span>, ultrices aliquet, mattis eget, hendrerit, <em>justo</em>.</p> Abbreviated to 25 words would be: <p> Proin tristique dapibus neque. Nam eget purus sit amet leo tincidunt accumsan.</p><p> Proin semper, orci at mattis blandit, augue justo blandit nulla. <span>Quisque ante congue...</span></p> | Here's what I did: <link rel="Stylesheet" type="text/css" href="Stylesheet.css" id="style" runat="server" visible="false" /> It fools Visual Studio into thinking you've added a stylesheet to the page but it doesn't get rendered. Here's an even more concise way to do this with multiple references; <% if (false) { %> <link rel="Stylesheet" type="text/css" href="Stylesheet.css" /> <script type="text/javascript" src="js/jquery-1.2.6.js" /><% } %> As seen in this blog post from Phil Haack. | {
"score": 7,
"source": [
"https://Stackoverflow.com/questions/34394",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3187/"
]
} |
34,399 | I have an html file with an unordered list. I want to show the list items horizontally but still keep the bullets. No matter what I try, whenever I set the style to inline to meet the horizontal requirement I can't get the bullets to display. | The best option I saw in other answers was to use float:left; . Unfortunately, it doesn't work in IE7 which is a requirement here * — you still lose the bullet. I'm not really keen on using a background image either. What I'm gonna do instead (that no one else suggested, hence the self-answer) is go with manually adding • to the my html, rather than styling this. It's less than ideal, but it's the most compatible option I found. edit : * Current readers take note of the original post date. IE7 is unlikely to be a concern anymore. | {
"score": 6,
"source": [
"https://Stackoverflow.com/questions/34399",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3043/"
]
} |
34,401 | Is anyone using Elmah to send exceptions via email? I've got Elmah logging set up via SQL Server, and can view the errors page via the Elmah.axd page, but I am unable to get the email component working. The idea here is to get the email notification so we can react more quickly to exceptions. Here is my web.config (unnecessary sectionss omitted), with all the sensitive data replaced by * * *. Even though I am specifying a server to connect to, does the SMTP service need to be running on the local machine? <?xml version="1.0"?><configuration> <configSections> <sectionGroup name="elmah"> <section name="errorLog" requirePermission="false" type="Elmah.ErrorLogSectionHandler, Elmah"/> <section name="errorMail" requirePermission="false" type="Elmah.ErrorMailSectionHandler, Elmah"/> <section name="errorFilter" requirePermission="false" type="Elmah.ErrorFilterSectionHandler, Elmah"/> </sectionGroup> </configSections> <appSettings/> <connectionStrings> <add name="elmah-sql" connectionString="Data Source=***;Initial Catalog=***;Persist Security Info=True;User ID=***;Password=***" /> </connectionStrings> <elmah> <errorLog type="Elmah.SqlErrorLog, Elmah" connectionStringName="elmah-sql" > </errorLog> <errorMail from="[email protected]" to="[email protected]" subject="Application Exception" async="false" smtpPort="25" smtpServer="***" userName="***" password="***"> </errorMail> </elmah> <system.web> <customErrors mode="RemoteOnly" defaultRedirect="CustomError.aspx"> <error statusCode="403" redirect="NotAuthorized.aspx" /> <!--<error statusCode="404" redirect="FileNotFound.htm" />--> </customErrors> <httpHandlers> <remove verb="*" path="*.asmx"/> <add verb="*" path="*.asmx" validate="false" type="System.Web.Script.Services.ScriptHandlerFactory, System.Web.Extensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35"/> <add verb="*" path="*_AppService.axd" validate="false" type="System.Web.Script.Services.ScriptHandlerFactory, System.Web.Extensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35"/> <add verb="GET,HEAD" path="ScriptResource.axd" type="System.Web.Handlers.ScriptResourceHandler, System.Web.Extensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" validate="false"/> <add verb="POST,GET,HEAD" path="elmah.axd" type="Elmah.ErrorLogPageFactory, Elmah" /> </httpHandlers> <httpModules> <add name="ScriptModule" type="System.Web.Handlers.ScriptModule, System.Web.Extensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35"/> <add name="ErrorLog" type="Elmah.ErrorLogModule, Elmah"/> </httpModules> </system.web></configuration> | You need the ErrorMail httpModule. add this line inside the <httpModules> section <add name="ErrorMail" type="Elmah.ErrorMailModule, Elmah" /> If you're using a remote SMTP server (which it looks like you are) you don't need SMTP on the server. | {
"score": 7,
"source": [
"https://Stackoverflow.com/questions/34401",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1284/"
]
} |
34,413 | I am getting a NoClassDefFoundError when I run my Java application. What is typically the cause of this? | While it's possible that this is due to a classpath mismatch between compile-time and run-time, it's not necessarily true. It is important to keep two or three different exceptions straight in our head in this case: java.lang.ClassNotFoundException This exception indicates that the class was not found on the classpath. This indicates that we were trying to load the class definition, and the class did not exist on the classpath. java.lang.NoClassDefFoundError This exception indicates that the JVM looked in its internal class definition data structure for the definition of a class and did not find it. This is different than saying that it could not be loaded from the classpath. Usually this indicates that we previously attempted to load a class from the classpath, but it failed for some reason - now we're trying to use the class again (and thus need to load it, since it failed last time), but we're not even going to try to load it, because we failed loading it earlier (and reasonably suspect that we would fail again). The earlier failure could be a ClassNotFoundException or an ExceptionInInitializerError (indicating a failure in the static initialization block) or any number of other problems. The point is, a NoClassDefFoundError is not necessarily a classpath problem. | {
"score": 10,
"source": [
"https://Stackoverflow.com/questions/34413",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3535/"
]
} |
34,439 | Given a Python object of any kind, is there an easy way to get the list of all methods that this object has? Or, if this is not possible, is there at least an easy way to check if it has a particular method other than simply checking if an error occurs when the method is called? | For many objects , you can use this code, replacing 'object' with the object you're interested in: object_methods = [method_name for method_name in dir(object) if callable(getattr(object, method_name))] I discovered it at diveintopython.net (now archived), that should provide some further details! If you get an AttributeError , you can use this instead : getattr() is intolerant of pandas style Python 3.6 abstract virtual sub-classes. This code does the same as above and ignores exceptions. import pandas as pddf = pd.DataFrame([[10, 20, 30], [100, 200, 300]], columns=['foo', 'bar', 'baz'])def get_methods(object, spacing=20): methodList = [] for method_name in dir(object): try: if callable(getattr(object, method_name)): methodList.append(str(method_name)) except Exception: methodList.append(str(method_name)) processFunc = (lambda s: ' '.join(s.split())) or (lambda s: s) for method in methodList: try: print(str(method.ljust(spacing)) + ' ' + processFunc(str(getattr(object, method).__doc__)[0:90])) except Exception: print(method.ljust(spacing) + ' ' + ' getattr() failed')get_methods(df['foo']) | {
"score": 10,
"source": [
"https://Stackoverflow.com/questions/34439",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3587/"
]
} |
34,486 | I have a small JS function that does Ajax for me and another like it that adds in POST data to the request. With Ajax being such a big topic with so many libraries about it, what am I missing from my function, is it insecure or something else worrying? function loadPage(pagePath, displayElement){ var xmlHttp; try { // Firefox, Opera 8.0+, Safari xmlHttp=new XMLHttpRequest(); } catch (e) { // Internet Explorer try { xmlHttp=new ActiveXObject("Msxml2.XMLHTTP"); } catch (e) { try { xmlHttp=new ActiveXObject("Microsoft.XMLHTTP"); } catch (e) { alert("Your browser does not support AJAX!"); return false; } } } xmlHttp.onreadystatechange=function() { if(xmlHttp.readyState==4) { document.getElementById(displayElement).innerHTML = xmlHttp.responseText; } } xmlHttp.open("GET", pagePath, true); xmlHttp.send(null);} | I strongly recommend you not roll your own Ajax code. Instead, use a framework such as Prototype, Dojo, or any of the others. They've taken care of handling all the ReadyStates you're not handling (2 means it's been sent, 3 means it's in process, etc.), and they should escape the reponse you're getting so you don't insert potentially insecure javascript or something into your page. Another thing a more robust framework will give you is the ability to do more than just use innerHTML to replace items in the DOM. Your function here can only be used to replace one element with the response from the ajax call. There's a lot more you can do with Ajax. | {
"score": 5,
"source": [
"https://Stackoverflow.com/questions/34486",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1384652/"
]
} |
34,488 | Will limiting a query to one result record, improve performance in a large(ish) MySQL table if the table only has one matching result? for example select * from people where name = "Re0sless" limit 1 if there is only one record with that name? and what about if name was the primary key/ set to unique? and is it worth updating the query or will the gain be minimal? | If the column has a unique index: no, it's no faster a non-unique index: maybe, because it will prevent sending any additional rows beyond the first matched, if any exist no index: sometimes if 1 or more rows match the query, yes , because the full table scan will be halted after the first row is matched. if no rows match the query, no , because it will need to complete a full table scan | {
"score": 6,
"source": [
"https://Stackoverflow.com/questions/34488",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2098/"
]
} |
34,490 | SHA Hash functions | require 'digest/sha1'Digest::SHA1.hexdigest 'foo' | {
"score": 10,
"source": [
"https://Stackoverflow.com/questions/34490",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3624/"
]
} |
34,505 | The MSDN documentation on Object.GetHashCode() describes 3 contradicting rules for how the method should work. If two objects of the same type represent the same value, the hash function must return the same constant value for either object. For the best performance, a hash function must generate a random distribution for all input. The hash function must return exactly the same value regardless of any changes that are made to the object. Rules 1 & 3 are contradictory to me. Does Object.GetHashCode() return a unique number based on the value of an object, or the reference to the object. If I override the method I can choose what to use, but I'd like to know what is used internally if anyone knows. | Rules 1 & 3 are contradictory to me. To a certain extent, they are. The reason is simple: if an object is stored in a hash table and, by changing its value, you change its hash then the hash table has lost the value and you can't find it again by querying the hash table. It is important that while objects are stored in a hash table, they retain their hash value. To realize this it is often simplest to make hashable objects immutable, thus evading the whole problem. It is however sufficient to make only those fields immutable that determine the hash value. Consider the following example: struct Person { public readonly string FirstName; public readonly string Name; public readonly DateTime Birthday; public int ShoeSize;} People rarely change their birthday and most people never change their name (except when marrying). However, their shoe size may grow arbitrarily, or even shrink. It is therefore reasonable to identify people using their birthday and name but not their shoe size. The hash value should reflect this: public int GetHashCode() { return FirstName.GetHashCode() ^ Name.GetHashCode() ^ Birthday.GetHashCode();} | {
"score": 6,
"source": [
"https://Stackoverflow.com/questions/34505",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/392/"
]
} |
34,509 | We have a large database on which we have DB side pagination. This is quick, returning a page of 50 rows from millions of records in a small fraction of a second. Users can define their own sort, basically choosing what column to sort by. Columns are dynamic - some have numeric values, some dates and some text. While most sort as expected text sorts in a dumb way. Well, I say dumb, it makes sense to computers, but frustrates users. For instance, sorting by a string record id gives something like: rec1rec10rec14rec2rec20rec3rec4 ...and so on. I want this to take account of the number, so: rec1rec2rec3rec4rec10rec14rec20 I can't control the input (otherwise I'd just format in leading 000s) and I can't rely on a single format - some are things like "{alpha code}-{dept code}-{rec id}". I know a few ways to do this in C#, but can't pull down all the records to sort them, as that would be to slow. Does anyone know a way to quickly apply a natural sort in Sql server? We're using: ROW_NUMBER() over (order by {field name} asc) And then we're paging by that. We can add triggers, although we wouldn't. All their input is parametrised and the like, but I can't change the format - if they put in "rec2" and "rec10" they expect them to be returned just like that, and in natural order. We have valid user input that follows different formats for different clients. One might go rec1, rec2, rec3, ... rec100, rec101 While another might go: grp1rec1, grp1rec2, ... grp20rec300, grp20rec301 When I say we can't control the input I mean that we can't force users to change these standards - they have a value like grp1rec1 and I can't reformat it as grp01rec001, as that would be changing something used for lookups and linking to external systems. These formats vary a lot, but are often mixtures of letters and numbers. Sorting these in C# is easy - just break it up into { "grp", 20, "rec", 301 } and then compare sequence values in turn. However there may be millions of records and the data is paged, I need the sort to be done on the SQL server. SQL server sorts by value, not comparison - in C# I can split the values out to compare, but in SQL I need some logic that (very quickly) gets a single value that consistently sorts. @moebius - your answer might work, but it does feel like an ugly compromise to add a sort-key for all these text values. | Most of the SQL-based solutions I have seen break when the data gets complex enough (e.g. more than one or two numbers in it). Initially I tried implementing a NaturalSort function in T-SQL that met my requirements (among other things, handles an arbitrary number of numbers within the string), but the performance was way too slow. Ultimately, I wrote a scalar CLR function in C# to allow for a natural sort, and even with unoptimized code the performance calling it from SQL Server is blindingly fast. It has the following characteristics: will sort the first 1,000 characters or so correctly (easily modified in code or made into a parameter) properly sorts decimals, so 123.333 comes before 123.45 because of above, will likely NOT sort things like IP addresses correctly; if you wish different behaviour, modify the code supports sorting a string with an arbitrary number of numbers within it will correctly sort numbers up to 25 digits long (easily modified in code or made into a parameter) The code is here: using System;using System.Data.SqlTypes;using System.Text;using Microsoft.SqlServer.Server;public class UDF{ [SqlFunction(DataAccess = DataAccessKind.None, IsDeterministic=true)] public static SqlString Naturalize(string val) { if (String.IsNullOrEmpty(val)) return val; while(val.Contains(" ")) val = val.Replace(" ", " "); const int maxLength = 1000; const int padLength = 25; bool inNumber = false; bool isDecimal = false; int numStart = 0; int numLength = 0; int length = val.Length < maxLength ? val.Length : maxLength; //TODO: optimize this so that we exit for loop once sb.ToString() >= maxLength var sb = new StringBuilder(); for (var i = 0; i < length; i++) { int charCode = (int)val[i]; if (charCode >= 48 && charCode <= 57) { if (!inNumber) { numStart = i; numLength = 1; inNumber = true; continue; } numLength++; continue; } if (inNumber) { sb.Append(PadNumber(val.Substring(numStart, numLength), isDecimal, padLength)); inNumber = false; } isDecimal = (charCode == 46); sb.Append(val[i]); } if (inNumber) sb.Append(PadNumber(val.Substring(numStart, numLength), isDecimal, padLength)); var ret = sb.ToString(); if (ret.Length > maxLength) return ret.Substring(0, maxLength); return ret; } static string PadNumber(string num, bool isDecimal, int padLength) { return isDecimal ? num.PadRight(padLength, '0') : num.PadLeft(padLength, '0'); }} To register this so that you can call it from SQL Server, run the following commands in Query Analyzer: CREATE ASSEMBLY SqlServerClr FROM 'SqlServerClr.dll' --put the full path to DLL heregoCREATE FUNCTION Naturalize(@val as nvarchar(max)) RETURNS nvarchar(1000) EXTERNAL NAME SqlServerClr.UDF.Naturalizego Then, you can use it like so: select *from MyTableorder by dbo.Naturalize(MyTextField) Note : If you get an error in SQL Server along the lines of Execution of user code in the .NET Framework is disabled. Enable "clr enabled" configuration option. , follow the instructions here to enable it. Make sure you consider the security implications before doing so. If you are not the db admin, make sure you discuss this with your admin before making any changes to the server configuration. Note2 : This code does not properly support internationalization (e.g., assumes the decimal marker is ".", is not optimized for speed, etc. Suggestions on improving it are welcome! Edit: Renamed the function to Naturalize instead of NaturalSort , since it does not do any actual sorting. | {
"score": 6,
"source": [
"https://Stackoverflow.com/questions/34509",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/905/"
]
} |
34,510 | When writing multithreaded applications, one of the most common problems experienced is race conditions. My questions to the community are: What is the race condition? How do you detect them? How do you handle them? Finally, how do you prevent them from occurring? | A race condition occurs when two or more threads can access shared data and they try to change it at the same time. Because the thread scheduling algorithm can swap between threads at any time, you don't know the order in which the threads will attempt to access the shared data. Therefore, the result of the change in data is dependent on the thread scheduling algorithm, i.e. both threads are "racing" to access/change the data. Problems often occur when one thread does a "check-then-act" (e.g. "check" if the value is X, then "act" to do something that depends on the value being X) and another thread does something to the value in between the "check" and the "act". E.g: if (x == 5) // The "Check"{ y = x * 2; // The "Act" // If another thread changed x in between "if (x == 5)" and "y = x * 2" above, // y will not be equal to 10.} The point being, y could be 10, or it could be anything, depending on whether another thread changed x in between the check and act. You have no real way of knowing. In order to prevent race conditions from occurring, you would typically put a lock around the shared data to ensure only one thread can access the data at a time. This would mean something like this: // Obtain lock for xif (x == 5){ y = x * 2; // Now, nothing can change x until the lock is released. // Therefore y = 10}// release lock for x | {
"score": 12,
"source": [
"https://Stackoverflow.com/questions/34510",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1931/"
]
} |
34,512 | When writing multi-threaded applications, one of the most common problems experienced are deadlocks. My questions to the community are: What is a deadlock? How do you detect them? Do you handle them? And finally, how do you prevent them from occurring? | A lock occurs when multiple processes try to access the same resource at the same time. One process loses out and must wait for the other to finish. A deadlock occurs when the waiting process is still holding on to another resource that the first needs before it can finish. So, an example: Resource A and resource B are used by process X and process Y X starts to use A. X and Y try to start using B Y 'wins' and gets B first now Y needs to use A A is locked by X, which is waiting for Y The best way to avoid deadlocks is to avoid having processes cross over in this way. Reduce the need to lock anything as much as you can. In databases avoid making lots of changes to different tables in a single transaction, avoid triggers and switch to optimistic/dirty/nolock reads as much as possible. | {
"score": 9,
"source": [
"https://Stackoverflow.com/questions/34512",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1931/"
]
} |
34,516 | Is there a standard convention (like phpdoc or python's docstring) for commenting C# code so that class documentation can be automatically generated from the source code? | You can use XML style comments, and use tools to pull those comments out into API documentation. Here is an example of the comment style: /// <summary>/// Authenticates a user based on a username and password./// </summary>/// <param name="username">The username.</param>/// <param name="password">The password.</param>/// <returns>/// True, if authentication is successful, otherwise False./// </returns>/// <remarks>/// For use with local systems/// </remarks>public override bool Authenticate(string username, string password) Some items to facilitate this are: GhostDoc , which give a single shortcut key to automatically generate comments for a class or method. Sandcastle , which generates MSDN style documentation from XML comments. | {
"score": 6,
"source": [
"https://Stackoverflow.com/questions/34516",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/305/"
]
} |
34,519 | A semaphore is a programming concept that is frequently used to solve multi-threading problems. My question to the community: What is a semaphore and how do you use it? | Think of semaphores as bouncers at a nightclub. There are a dedicated number of people that are allowed in the club at once. If the club is full no one is allowed to enter, but as soon as one person leaves another person might enter. It's simply a way to limit the number of consumers for a specific resource. For example, to limit the number of simultaneous calls to a database in an application. Here is a very pedagogic example in C# :-) using System;using System.Collections.Generic;using System.Text;using System.Threading;namespace TheNightclub{ public class Program { public static Semaphore Bouncer { get; set; } public static void Main(string[] args) { // Create the semaphore with 3 slots, where 3 are available. Bouncer = new Semaphore(3, 3); // Open the nightclub. OpenNightclub(); } public static void OpenNightclub() { for (int i = 1; i <= 50; i++) { // Let each guest enter on an own thread. Thread thread = new Thread(new ParameterizedThreadStart(Guest)); thread.Start(i); } } public static void Guest(object args) { // Wait to enter the nightclub (a semaphore to be released). Console.WriteLine("Guest {0} is waiting to entering nightclub.", args); Bouncer.WaitOne(); // Do some dancing. Console.WriteLine("Guest {0} is doing some dancing.", args); Thread.Sleep(500); // Let one guest out (release one semaphore). Console.WriteLine("Guest {0} is leaving the nightclub.", args); Bouncer.Release(1); } }} | {
"score": 9,
"source": [
"https://Stackoverflow.com/questions/34519",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1931/"
]
} |
34,524 | A mutex is a programming concept that is frequently used to solve multi-threading problems. My question to the community: What is a mutex and how do you use it? | When I am having a big heated discussion at work, I use a rubber chicken which I keep in my desk for just such occasions. The person holding the chicken is the only person who is allowed to talk. If you don't hold the chicken you cannot speak. You can only indicate that you want the chicken and wait until you get it before you speak. Once you have finished speaking, you can hand the chicken back to the moderator who will hand it to the next person to speak. This ensures that people do not speak over each other, and also have their own space to talk. Replace Chicken with Mutex and person with thread and you basically have the concept of a mutex. Of course, there is no such thing as a rubber mutex. Only rubber chicken. My cats once had a rubber mouse, but they ate it. Of course, before you use the rubber chicken, you need to ask yourself whether you actually need 5 people in one room and would it not just be easier with one person in the room on their own doing all the work. Actually, this is just extending the analogy, but you get the idea. | {
"score": 11,
"source": [
"https://Stackoverflow.com/questions/34524",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1931/"
]
} |
34,536 | This most be the second most simple rollover effect, still I don't find any simple solution. Wanted: I have a list of items and a corresponding list of slides (DIVs). After loading, the first list item should be selected (bold) and the first slide should be visible. When the user hovers over another list item, that list item should be selected instead and the corresponding slide be shown. The following code works, but is awful . How can I get this behaviour in an elegant way? jquery has dozens of animated and complicated rollover effects, but I didn't come up with a clean way for this effect. <script type="text/javascript">function switchTo(id) { document.getElementById('slide1').style.display=(id==1)?'block':'none'; document.getElementById('slide2').style.display=(id==2)?'block':'none'; document.getElementById('slide3').style.display=(id==3)?'block':'none'; document.getElementById('slide4').style.display=(id==4)?'block':'none'; document.getElementById('switch1').style.fontWeight=(id==1)?'bold':'normal'; document.getElementById('switch2').style.fontWeight=(id==2)?'bold':'normal'; document.getElementById('switch3').style.fontWeight=(id==3)?'bold':'normal'; document.getElementById('switch4').style.fontWeight=(id==4)?'bold':'normal';}</script><ul id="switches"> <li id="switch1" onmouseover="switchTo(1);" style="font-weight:bold;">First slide</li> <li id="switch2" onmouseover="switchTo(2);">Second slide</li> <li id="switch3" onmouseover="switchTo(3);">Third slide</li> <li id="switch4" onmouseover="switchTo(4);">Fourth slide</li></ul><div id="slides"> <div id="slide1">Well well.</div> <div id="slide2" style="display:none;">Oh no!</div> <div id="slide3" style="display:none;">You again?</div> <div id="slide4" style="display:none;">I'm gone!</div></div> | Rather than displaying all slides when JS is off (which would likely break the page layout) I would place inside the switch LIs real A links to server-side code which returns the page with the "active" class pre-set on the proper switch/slide. $(document).ready(function() { switches = $('#switches > li'); slides = $('#slides > div'); switches.each(function(idx) { $(this).data('slide', slides.eq(idx)); }).hover( function() { switches.removeClass('active'); slides.removeClass('active'); $(this).addClass('active'); $(this).data('slide').addClass('active'); });}); #switches .active { font-weight: bold;}#slides div { display: none;}#slides div.active { display: block;} <html><head> <title>test</title> <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <script type="text/javascript" src="switch.js"></script></head><body> <ul id="switches"> <li class="active">First slide</li> <li>Second slide</li> <li>Third slide</li> <li>Fourth slide</li> </ul> <div id="slides"> <div class="active">Well well.</div> <div>Oh no!</div> <div>You again?</div> <div>I'm gone!</div> </div></body></html> | {
"score": 5,
"source": [
"https://Stackoverflow.com/questions/34536",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3377/"
]
} |
34,565 | Additionally, how can I format it as a string padded with zeros? | To generate the number call rand with the result of the expression "10 to the power of 10" rand(10 ** 10) To pad the number with zeros you can use the string format operator '%010d' % rand(10 ** 10) or the rjust method of string rand(10 ** 10).to_s.rjust(10,'0') | {
"score": 7,
"source": [
"https://Stackoverflow.com/questions/34565",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3624/"
]
} |
34,571 | How do I use JUnit to test a class that has internal private methods, fields or nested classes? It seems bad to change the access modifier for a method just to be able to run a test. | If you have somewhat of a legacy Java application, and you're not allowed to change the visibility of your methods, the best way to test private methods is to use reflection . Internally we're using helpers to get/set private and private static variables as well as invoke private and private static methods. The following patterns will let you do pretty much anything related to the private methods and fields. Of course, you can't change private static final variables through reflection. Method method = TargetClass.getDeclaredMethod(methodName, argClasses);method.setAccessible(true);return method.invoke(targetObject, argObjects); And for fields: Field field = TargetClass.getDeclaredField(fieldName);field.setAccessible(true);field.set(object, value); Notes: TargetClass.getDeclaredMethod(methodName, argClasses) lets you look into private methods. The same thing applies for getDeclaredField . The setAccessible(true) is required to play around with privates. | {
"score": 12,
"source": [
"https://Stackoverflow.com/questions/34571",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3098/"
]
} |
34,588 | When running my application I sometimes get an error about too many files open . Running ulimit -a reports that the limit is 1024. How do I increase the limit above 1024? Edit ulimit -n 2048 results in a permission error. | You could always try doing a ulimit -n 2048 . This will only reset the limit for your current shell and the number you specify must not exceed the hard limit Each operating system has a different hard limit setup in a configuration file. For instance, the hard open file limit on Solaris can be set on boot from /etc/system. set rlim_fd_max = 166384set rlim_fd_cur = 8192 On OS X, this same data must be set in /etc/sysctl.conf. kern.maxfilesperproc=166384kern.maxfiles=8192 Under Linux, these settings are often in /etc/security/limits.conf. There are two kinds of limits: soft limits are simply the currently enforced limits hard limits mark the maximum value which cannot be exceeded by setting a soft limit Soft limits could be set by any user while hard limits are changeable only by root.Limits are a property of a process. They are inherited when a child process is created so system-wide limits should be set during the system initialization in init scripts and user limits should be set during user login for example by using pam_limits. There are often defaults set when the machine boots. So, even though you may reset your ulimit in an individual shell, you may find that it resets back to the previous value on reboot. You may want to grep your boot scripts for the existence ulimit commands if you want to change the default. | {
"score": 8,
"source": [
"https://Stackoverflow.com/questions/34588",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3535/"
]
} |
34,595 | What is a good Hash function? I saw a lot of hash function and applications in my data structures courses in college, but I mostly got that it's pretty hard to make a good hash function. As a rule of thumb to avoid collisions my professor said that: function Hash(key) return key mod PrimeNumberend (mod is the % operator in C and similar languages) with the prime number to be the size of the hash table. I get that is a somewhat good function to avoid collisions and a fast one, but how can I make a better one? Is there better hash functions for string keys against numeric keys? | There's no such thing as a “good hash function” for universal hashes (ed. yes, I know there's such a thing as “universal hashing” but that's not what I meant). Depending on the context different criteria determine the quality of a hash. Two people already mentioned SHA. This is a cryptographic hash and it isn't at all good for hash tables which you probably mean. Hash tables have very different requirements. But still, finding a good hash function universally is hard because different data types expose different information that can be hashed. As a rule of thumb it is good to consider all information a type holds equally. This is not always easy or even possible. For reasons of statistics (and hence collision), it is also important to generate a good spread over the problem space, i.e. all possible objects. This means that when hashing numbers between 100 and 1050 it's no good to let the most significant digit play a big part in the hash because for ~ 90% of the objects, this digit will be 0. It's far more important to let the last three digits determine the hash. Similarly, when hashing strings it's important to consider all characters – except when it's known in advance that the first three characters of all strings will be the same; considering these then is a waste. This is actually one of the cases where I advise to read what Knuth has to say in The Art of Computer Programming , vol. 3. Another good read is Julienne Walker's The Art of Hashing . | {
"score": 6,
"source": [
"https://Stackoverflow.com/questions/34595",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3485/"
]
} |
34,611 | What are some toolkits for developing 2D games in Python? An option that I have heard of is Pygame, but is there anything that has more range to do more things? What are the good and bad parts about the modules? | I use pygame myself and it is very good. It has good documentation and tutorials, and is quite well designed. I've also heard wonderful reviews of pyglet . | {
"score": 5,
"source": [
"https://Stackoverflow.com/questions/34611",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1447/"
]
} |
34,655 | I would like to have an iframe take as much vertical space as it needs to display its content and not display a scrollbar. Is it at all possible ? Are there any workarounds? | This should set the IFRAME height to its content's height: <script type="text/javascript">the_height = document.getElementById('the_iframe').contentWindow.document.body.scrollHeight;document.getElementById('the_iframe').height = the_height;</script> You may want to add scrolling="no" to your IFRAME to turn off the scrollbars. edit: Oops, forgot to declare the_height . | {
"score": 5,
"source": [
"https://Stackoverflow.com/questions/34655",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1983/"
]
} |
34,664 | Has anyone found a useful solution to the DesignMode problem when developing controls? The issue is that if you nest controls then DesignMode only works for the first level. The second and lower levels DesignMode will always return FALSE. The standard hack has been to look at the name of the process that is running and if it is "DevEnv.EXE" then it must be studio thus DesignMode is really TRUE. The problem with that is looking for the ProcessName works its way around through the registry and other strange parts with the end result that the user might not have the required rights to see the process name. In addition this strange route is very slow. So we have had to pile additional hacks to use a singleton and if an error is thrown when asking for the process name then assume that DesignMode is FALSE. A nice clean way to determine DesignMode is in order. Acually getting Microsoft to fix it internally to the framework would be even better! | Revisiting this question, I have now 'discovered' 5 different ways of doing this, which are as follows: System.ComponentModel.DesignMode propertySystem.ComponentModel.LicenseManager.UsageMode propertyprivate string ServiceString(){ if (GetService(typeof(System.ComponentModel.Design.IDesignerHost)) != null) return "Present"; else return "Not present";}public bool IsDesignerHosted{ get { Control ctrl = this; while(ctrl != null) { if((ctrl.Site != null) && ctrl.Site.DesignMode) return true; ctrl = ctrl.Parent; } return false; }}public static bool IsInDesignMode(){ return System.Reflection.Assembly.GetExecutingAssembly() .Location.Contains("VisualStudio"))} To try and get a hang on the three solutions proposed, I created a little test solution - with three projects: TestApp (winforms application), SubControl (dll) SubSubControl (dll) I then embedded the SubSubControl in the SubControl, then one of each in the TestApp.Form. This screenshot shows the result when running. This screenshot shows the result with the form open in Visual Studio: Conclusion: It would appear that without reflection the only one that is reliable within the constructor is LicenseUsage, and the only one which is reliable outside the constructor is 'IsDesignedHosted' (by BlueRaja below) PS: See ToolmakerSteve's comment below (which I haven't tested): "Note that IsDesignerHosted answer has been updated to include LicenseUsage..., so now the test can simply be if (IsDesignerHosted). An alternative approach is test LicenseManager in constructor and cache the result ." | {
"score": 7,
"source": [
"https://Stackoverflow.com/questions/34664",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2862/"
]
} |
34,674 | You can use a standard dot notation or a method call in Objective-C to access a property of an object in Objective-C. myObject.property = YES; or [myObject setProperty:YES]; Is there a difference in performance (in terms of accessing the property)? Is it just a matter of preference in terms of coding style? | Dot notation for property access in Objective-C is a message send, just as bracket notation. That is, given this: @interface Foo : NSObject@property BOOL bar;@endFoo *foo = [[Foo alloc] init];foo.bar = YES;[foo setBar:YES]; The last two lines will compile exactly the same. The only thing that changes this is if a property has a getter and/or setter attribute specified; however, all it does is change what message gets sent, not whether a message is sent: @interface MyView : NSView@property(getter=isEmpty) BOOL empty;@endif ([someView isEmpty]) { /* ... */ }if (someView.empty) { /* ... */ } Both of the last two lines will compile identically. | {
"score": 5,
"source": [
"https://Stackoverflow.com/questions/34674",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1987/"
]
} |
34,687 | When I try to do any svn command and supply the --username and/or --password options, it prompts me for my password anyways, and always will attempt to use my current user instead of the one specified by --username . Neither --no-auth-cache nor --non-interactive have any effect on this. This is a problem because I'm trying to call svn commands from a script, and I can't have it show the prompt. For example, logged in as user1: # $ svn update --username 'user2' --password 'password'# [email protected]'s password: Other options work correctly: # $ svn --version --quiet# 1.3.2 Why does it prompt me? And why is it asking for user1's password instead of user2's? I'm 99% sure all of my permissions are set correctly. Is there some config option for svn that switches off command-line passwords? Or is it something else entirely? I'm running svn 1.3.2 (r19776) on Fedora Core 5 (Bordeaux). Here's a list of my environment variables (with sensitive information X'ed out). None of them seem to apply to SVN: # HOSTNAME=XXXXXX# TERM=xterm# SHELL=/bin/sh# HISTSIZE=1000# KDE_NO_IPV6=1# SSH_CLIENT=XXX.XXX.XXX.XXX XXXXX XX# QTDIR=/usr/lib/qt-3.3# QTINC=/usr/lib/qt-3.3/include# SSH_TTY=/dev/pts/2# USER=XXXXXX# LS_COLORS=no=00:fi=00:di=00;34:ln=00;36:pi=40;33:so=00;35:bd=40;33;01:cd=40;33;01:or=01;05;37;41:mi=01;05;37;41:ex=00;32:*.cmd=00;32:*.exe=00;32:*.com=00;32:*.btm=00;32:*.bat=00;32:*.sh=00;32:*.csh=00;32:*.tar=00;31:*.tgz=00;31:*.arj=00;31:*.taz=00;31:*.lzh=00;31:*.zip=00;31:*.z=00;31:*.Z=00;31:*.gz=00;31:*.bz2=00;31:*.bz=00;31:*.tz=00;31:*.rpm=00;31:*.cpio=00;31:*.jpg=00;35:*.gif=00;35:*.bmp=00;35:*.xbm=00;35:*.xpm=00;35:*.png=00;35:*.tif=00;35:# KDEDIR=/usr# MAIL=/var/spool/mail/XXXXXX# PATH=/usr/lib/qt-3.3/bin:/usr/kerberos/bin:/usr/local/bin:/bin:/usr/bin# INPUTRC=/etc/inputrc# PWD=/home/users/XXXXXX/my_repository# KDE_IS_PRELINKED=1# LANG=en_US.UTF-8# SSH_ASKPASS=/usr/libexec/openssh/gnome-ssh-askpass# SHLVL=1# HOME=/home/users/XXXXXX# LOGNAME=XXXXXX# QTLIB=/usr/lib/qt-3.3/lib# CVS_RSH=ssh# SSH_CONNECTION=69.202.73.122 60998 216.7.19.47 22# LESSOPEN=|/usr/bin/lesspipe.sh %s# G_BROKEN_FILENAMES=1# _=/bin/env# OLDPWD=/home/users/XXXXXX | Do you actually have the single quotes in your command? I don't think they are necessary. Plus, I think you also need --no-auth-cache and --non-interactive Here is what I use (no single quotes) --non-interactive --no-auth-cache --username XXXX --password YYYY See the Client Credentials Caching documentation in the svnbook for more information. | {
"score": 6,
"source": [
"https://Stackoverflow.com/questions/34687",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3625/"
]
} |
34,728 | I am particularly interested in Document Libraries, but in terms of general SharePoint lists, can anyone answer the following...? What is the maximum number of items that a SharePoint list can contain? What is the maximum number of lists that a single SharePoint server can host? When the number of items in the list approaches the maximum, does filtering slow down, and if so, what can be done to improve it? | In SharePoint v.2: Max # list items : 2000 (per folder level) Max lists per site : 2000 is a "reasonable" number Effect when we reach the limit : Exponential degradation of performance. More info: http://technet.microsoft.com/en-us/library/cc287743.aspx In SharePoint v.3: Max # list items : 2000 (per view, you can have million items as long as you don't display in a single view more than 2000 items) Max lists per site : 2000 is a "reasonable" number Effect when we reach the limit : Exponential degradation of performance when we enumerate more than 2000 items using the OM. An alternative is to use Search API or CAML queries. More info: http://technet.microsoft.com/en-us/library/cc287790.aspx | {
"score": 5,
"source": [
"https://Stackoverflow.com/questions/34728",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3362/"
]
} |
34,732 | How do I list the symbols being exported from a .so file? If possible, I'd also like to know their source (e.g. if they are pulled in from a static library). I'm using gcc 4.0.2, if that makes a difference. | The standard tool for listing symbols is nm , you can use it simply like this: nm -gD yourLib.so If you want to see symbols of a C++ library, add the "-C" option which demangle the symbols (it's far more readable demangled). nm -gDC yourLib.so If your .so file is in elf format, you have two options: Either objdump ( -C is also useful for demangling C++): $ objdump -TC libz.solibz.so: file format elf64-x86-64DYNAMIC SYMBOL TABLE:0000000000002010 l d .init 0000000000000000 .init0000000000000000 DF *UND* 0000000000000000 GLIBC_2.2.5 free0000000000000000 DF *UND* 0000000000000000 GLIBC_2.2.5 __errno_location0000000000000000 w D *UND* 0000000000000000 _ITM_deregisterTMCloneTable Or use readelf : $ readelf -Ws libz.soSymbol table '.dynsym' contains 112 entries: Num: Value Size Type Bind Vis Ndx Name 0: 0000000000000000 0 NOTYPE LOCAL DEFAULT UND 1: 0000000000002010 0 SECTION LOCAL DEFAULT 10 2: 0000000000000000 0 FUNC GLOBAL DEFAULT UND free@GLIBC_2.2.5 (14) 3: 0000000000000000 0 FUNC GLOBAL DEFAULT UND __errno_location@GLIBC_2.2.5 (14) 4: 0000000000000000 0 NOTYPE WEAK DEFAULT UND _ITM_deregisterTMCloneTable | {
"score": 10,
"source": [
"https://Stackoverflow.com/questions/34732",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3051/"
]
} |
34,784 | What is a good setup for .hgignore file when working with Visual Studio 2008? I mostly develop on my own, only occasionly I clone the repository for somebody else to work on it. I'm thinking about obj folders, .suo, .sln, .user files etc.. Can they just be included or are there file I shouldn't include? Thanks! p.s.: at the moment I do the following : ignore all .pdb files and all obj folders. # regexp syntax.syntax: glob*.pdbsyntax: regexp/obj/ | Here's my standard .hgignore file for use with VS2008 that was originally modified from a Git ignore file: # Ignore file for Visual Studio 2008# use glob syntaxsyntax: glob# Ignore Visual Studio 2008 files*.obj*.exe*.pdb*.user*.aps*.pch*.vspscc*_i.c*_p.c*.ncb*.suo*.tlb*.tlh*.bak*.cache*.ilk*.log*.lib*.sbr*.scc[Bb]in[Dd]ebug*/obj/[Rr]elease*/_ReSharper*/[Tt]est[Rr]esult*[Bb]uild[Ll]og.**.[Pp]ublish.xml | {
"score": 9,
"source": [
"https://Stackoverflow.com/questions/34784",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/925/"
]
} |
34,852 | I have an NHibernate session. In this session, I am performing exactly 1 operation, which is to run this code to get a list: public IList<Customer> GetCustomerByFirstName(string customerFirstName){return _session.CreateCriteria(typeof(Customer)) .Add(new NHibernate.Expression.EqExpression("FirstName", customerFirstName)) .List<Customer>();} I am calling Session.Flush() at the end of the HttpRequest , and I get a HibernateAdoException . NHibernate is passing an update statement to the db, and causing a foreign key violation. If I don't run the flush , the request completes with no problem. The issue here is that I need the flush in place in case there is a change that occurs within other sessions, since this code is reused in other areas. Is there another configuration setting I might be missing? Here's the code from the exception: [SQL: UPDATE CUSTOMER SET first_name = ?, last_name = ?, strategy_code_1 = ?, strategy_code_2 = ?, strategy_code_3 = ?, dts_import = ?, account_cycle_code = ?, bucket = ?, collector_code = ?, days_delinquent_count = ?, external_status_code = ?, principal_balance_amount = ?, total_min_pay_due = ?, current_balance = ?, amount_delinquent = ?, current_min_pay_due = ?, bucket_1 = ?, bucket_2 = ?, bucket_3 = ?, bucket_4 = ?, bucket_5 = ?, bucket_6 = ?, bucket_7 = ? WHERE customer_account_id = ?] No parameters are showing as being passed. | Always be careful with NULLable fields whenever you deal with NHibernate. If your field is NULLable in DB, make sure corresponding .NET class uses Nullable type too. Otherwise, all kinds of weird things will happen. The symptom is usually will be that NHibernate will try to update the record in DB, even though you have not changed any fields since you read the entity from the database. The following sequence explains why this happens: NHibernate retrieves raw entity's data from DB using ADO.NET NHibernate constructs the entity and sets its properties If DB field contained NULL the property will be set to the defaul value for its type: properties of reference types will be set to null properties of integer and floating point types will be set to 0 properties of boolean type will be set to false properties of DateTime type will be set to DateTime.MinValue etc. Now, when transaction is committed, NHibernate compares the value of the property to the original field value it read form DB, and since the field contained NULL but the property contains a non-null value, NHibernate considers the property dirty, and forces an update of the enity. Not only this hurts performance (you get extra round-trip to DB and extra update every time you retrieve the entity) but it also may cause hard to troubleshoot errors with DateTime columns. Indeed, when DateTime property is initialized to its default value it's set to 1/1/0001. When this value is saved to DB, ADO.NET's SqlClient can't convert it to a valid SqlDateTime value since the smallest possible SqlDateTime is 1/1/1753!!! The easiest fix is to make the class property use Nullable type, in this case "DateTime?". Alternatively, you could implement a custom type mapper by implementing IUserType with its Equals method properly comparing DbNull.Value with whatever default value of your value type. In our case Equals would need to return true when comparing 1/1/0001 with DbNull.Value. Implementing a full-functional IUserType is not really that hard but it does require knowledge of NHibernate trivia so prepare to do some substantial googling if you choose to go that way. | {
"score": 6,
"source": [
"https://Stackoverflow.com/questions/34852",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1284/"
]
} |
34,858 | I'd like to know the standard way to benchmark a SQL Sever Query, preferably I'd like to know about the tools that come with SQL Server rather than 3rd Party tools. | set showplan_text on will show you the execution plan (to see it graphically use CTRL + K (sql 2000) or CTRL + M (sql 2005 +) set statistics IO onwill show you the reads set statistics time onwill show you the elapsed time | {
"score": 5,
"source": [
"https://Stackoverflow.com/questions/34858",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1736/"
]
} |
34,868 | In the PHP manual, to show the syntax for functions with optional parameters, they use brackets around each set of dependent optional parameter. For example, for the date() function, the manual reads: string date ( string $format [, int $timestamp = time() ] ) Where $timestamp is an optional parameter, and when left blank it defaults to the time() function's return value. How do you go about creating optional parameters like this when defining a custom function in PHP? | Much like the manual, use an equals ( = ) sign in your definition of the parameters: function dosomething($var1, $var2, $var3 = 'somevalue'){ // Rest of function here...} | {
"score": 9,
"source": [
"https://Stackoverflow.com/questions/34868",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2687/"
]
} |
34,879 | I need debug some old code that uses a Hashtable to store response from various threads. I need a way to go through the entire Hashtable and print out both keys and the data in the Hastable. How can this be done? | foreach(string key in hashTable.Keys){ Console.WriteLine(String.Format("{0}: {1}", key, hashTable[key]));} | {
"score": 6,
"source": [
"https://Stackoverflow.com/questions/34879",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2469/"
]
} |
34,896 | User equals untrustworthy. Never trust untrustworthy user's input. I get that. However, I am wondering when the best time to sanitize input is. For example, do you blindly store user input and then sanitize it whenever it is accessed/used, or do you sanitize the input immediately and then store this "cleaned" version? Maybe there are also some other approaches I haven't though of in addition to these. I am leaning more towards the first method, because any data that came from user input must still be approached cautiously, where the "cleaned" data might still unknowingly or accidentally be dangerous. Either way, what method do people think is best, and for what reasons? | Unfortunately, almost no one of the participants ever clearly understands what are they talking about. Literally. Only Kibbee managed to make it straight. This topic is all about sanitization. But the truth is, such a thing like wide-termed "general purpose sanitization" everyone is so eager to talk about is just doesn't exist. There are a zillion different mediums , each require it's own, distinct data formatting. Moreover - even single certain medium require different formatting for it's parts . Say, HTML formatting is useless for javascript embedded in HTML page. Or, string formatting is useless for the numbers in SQL query. As a matter of fact, such a "sanitization as early as possible", as suggested in most upvoted answers, is just impossible . As one just cannot tell in which certain medium or medium part the data will be used. Say, we are preparing to defend from "sql-injection", escaping everything that moves. But whoops! - some required fields weren't filled and we have to fill out data back into form instead of database... with all the slashes added. On the other hand, we diligently escaped all the "user input"... but in the sql query we have no quotes around it, as it is a number or identifier. And no "sanitization" ever helped us. On the third hand - okay, we did our best in sanitizing the terrible, untrustworthy and disdained "user input"... but in some inner process we used this very data without any formatting (as we did our best already!) - and whoops! have got second order injection in all its glory. So, from the real life usage point of view, the only proper way would be formatting, not whatever "sanitization" right before use according to the certain medium rules and even following sub-rules required for this medium's different parts. | {
"score": 6,
"source": [
"https://Stackoverflow.com/questions/34896",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2628/"
]
} |
34,913 | I'm experimenting with Linq and am having trouble figuring out grouping. I've gone through several tutorials but for some reason can't figure this out. As an example, say I have a table (SiteStats) with multiple website IDs that stores a count of how many visitors by type have accessed each site in total and for the past 30 days. ╔════════╦═════════════╦════════╦══════╗║ SiteId ║ VisitorType ║ Last30 ║ Total║╠════════╬═════════════╬════════╬══════╣║ 1 ║ 1 ║ 10 ║ 100 ║║ 1 ║ 2 ║ 40 ║ 140 ║║ 2 ║ 1 ║ 20 ║ 180 ║╚════════╩═════════════╩════════╩══════╝ In SQL, I can easily get the counts for SiteID 1 with the following: SELECT SiteId, SUM(Last30) AS Last30Sum FROM Sites WHERE SiteId = 1 GROUP BY SiteId and should get a row like... ╔════════╦════════════╗║ SiteId ║ Last30Total║╠════════╬════════════╣║ 1 ║ 50 ║╚════════╩════════════╝ However I'm not sure how to get this result using Linq. I've tried: var statsRecord = from ss in db.SiteStats where ss.SiteId == siteId group ss by ss.SiteId into ss select ss; but I'm not able to get back the total with something like statsRecord.Last30 Can someone please let me know where I'm going wrong? Any help is appreciated. | Actually, although Thomas' code will work, it is more succint to use a lambda expression: var totals =from s in sitesgroup s by s.SiteID into groupedselect new{ SiteID = grouped.Key, Last30Sum = grouped.Sum( s => s.Last30 )}; which uses the Sum extension method without the need for a nested LINQ operation. as per the LINQ 101 examples - http://msdn.microsoft.com/en-us/vcsharp/aa336747.aspx#sumGrouped | {
"score": 6,
"source": [
"https://Stackoverflow.com/questions/34913",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2034/"
]
} |
34,920 | What is the best way to create a lock on a file in Perl? Is it best to flock on the file or to create a lock file to place a lock on and check for a lock on the lock file? | If you end up using flock, here's some code to do it: use Fcntl ':flock'; # Import LOCK_* constants# We will use this file path in error messages and function calls.# Don't type it out more than once in your code. Use a variable.my $file = '/path/to/some/file';# Open the file for appending. Note the file path is quoted# in the error message. This helps debug situations where you# have a stray space at the start or end of the path.open(my $fh, '>>', $file) or die "Could not open '$file' - $!";# Get exclusive lock (will block until it does)flock($fh, LOCK_EX) or die "Could not lock '$file' - $!";# Do something with the file here...# Do NOT use flock() to unlock the file if you wrote to the# file in the "do something" section above. This could create# a race condition. The close() call below will unlock the# file for you, but only after writing any buffered data.# In a world of buffered i/o, some or all of your data may not # be written until close() completes. Always, always, ALWAYS # check the return value of close() if you wrote to the file!close($fh) or die "Could not write '$file' - $!"; Some useful links: PerlMonks file locking tutorial (somewhat old) flock() documentation In response to your added question, I'd say either place the lock on the file or create a file that you call 'lock' whenever the file is locked and delete it when it is no longer locked (and then make sure your programs obey those semantics). | {
"score": 6,
"source": [
"https://Stackoverflow.com/questions/34920",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1539/"
]
} |
34,926 | my SSRS DataSet returns a field with HTML, e.g. <b>blah blah </b><i> blah </i>. how do i strip all the HTML tags? has to be done with inline VB.NET Changing the data in the table is not an option. Solution found ... = System.Text.RegularExpressions.Regex.Replace(StringWithHTMLtoStrip, "<[^>]+>","") | Thanx to Daniel, but I needed it to be done inline ... here's the solution: = System.Text.RegularExpressions.Regex.Replace(StringWithHTMLtoStrip, "<[^>]+>","") Here are the links: http://weblogs.asp.net/rosherove/archive/2003/05/13/6963.aspx http://msdn.microsoft.com/en-us/library/ms157328.aspx | {
"score": 5,
"source": [
"https://Stackoverflow.com/questions/34926",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3661/"
]
} |
34,955 | When building projects in C++, I've found debugging linking errors to be tricky, especially when picking up other people's code. What strategies do people use for debugging and fixing linking errors? | Not sure what your level of expertise is, but here are the basics. Below is a linker error from VS 2005 - yes, it's a giant mess if you're not familiar with it. ByteComparator.obj : error LNK2019: unresolved external symbol "int __cdecl does_not_exist(void)" (?does_not_exist@@YAHXZ) referenced in function "void __cdecl TextScan(struct FileTextStats &,char const *,char const *,bool,bool,__int64)" (?TextScan@@YAXAAUFileTextStats@@PBD1_N2_J@Z) There are a couple of points to focus on: "ByteComparator.obj" - Look for a ByteComparator.cpp file, this is the source of the linker problem "int __cdecl does_not_exist(void)" - This is the symbol it couldn't find, in this case a function named does_not_exist() At this point, in many cases the fastest way to resolution is to search the code base for this function and find where the implementation is. Once you know where the function is implemented you just have to make sure the two places get linked together. If you're using VS2005, you would use the "Project Dependencies..." right-click menu. If you're using gcc, you would look in your makefiles for the executable generation step (gcc called with a bunch of .o files) and add the missing .o file. In a second scenario, you may be missing an "external" dependency, which you don't have code for. The Win32 libraries are often times implemented in static libraries that you have to link to. In this case, go to MSDN or "Microsoft Google" and search for the API. At the bottom of the API description the library name is given. Add this to your project properties "Configuration Properties->Linker->Input->Additional Dependencies" list. For example, the function timeGetTime()'s page on MSDN tells you to use Winmm.lib at the bottom of the page. | {
"score": 6,
"source": [
"https://Stackoverflow.com/questions/34955",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3575/"
]
} |
34,975 | The company I work for is starting to have issues with their current branching model and I was wondering what different kinds of branching strategies the community has been exposed to? Are there any good ones for different situations? What does your company use? What are the advantages and disadvantages of them?? | Here is the method I've used in the past with good success: /trunk - bleeding edge. Next major release of the code. May or may not work at any given time. /branches/1.0, 1.1, etc. Stable maintenance branches of the code. Used to fix bugs, stabilize new releases. If a maintenance branch, it should compile (if applicable) and be ready for QA/shipping at any given time. If a stabilization branch, it should compile and be feature complete. No new features should be added, no refactoring, and no code cleanups. You can add a pre- prefix to indicate stabilization branches vs maintenance branches. /branches/cool_feature. Used for highly experimental or destructive work that may or may not make it into trunk (or a maintenance branch). No guarantees about code compiling, working, or otherwise behaving sanely. Should last the minimum time as possible before merging into the mainline branch. /tags/1.0.1, 1.0.2, 1.1.3a, etc. Used for tagging a packaged & shipped release. Never EVER changes. Make as many tags as you want, but they're immutable. | {
"score": 6,
"source": [
"https://Stackoverflow.com/questions/34975",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2328/"
]
} |
34,981 | I'm the second dev and a recent hire here at a PHP/MySQL shop. I was hired mostly due to my experience in wrangling some sort of process out of a chaotic mess. At least, that's what I did at my last company. ;) Since I've been here (a few months now), I've brought on board my boss, my product manager and several other key figures (But mostly chickens, if you pardon the Scrum-based stereotyping). I've also helped bring in some visibility to the development cycle of a major product that has been lagging for over a year. People are loving it! However, my coworker (the only other dev here for now) is not into it. She prefers to close her door and focus on her work and be left alone. Me? I'm into the whole Agile approach of collaboration, cooperation and openness. Without her input, I started the Scrum practices (daily scrums, burndown charts and other things I've found that worked for me and my previous teams (ala H. Kniberg's cool wall chart). During our daily stand up she slinks by and ignores us as if we actually weren't standing right outside her door (we are actually). It's pretty amazing. I've never seen such resistance. Question... how do I get her onboard? Peer pressure is not working. Thanks from fellow Scrum-borg, beaudetious | While Scrum other agile methodologies like it embody a lot of good practices, sometimes giving it a name and making it (as many bloggers have commented on) a "religion" that must be adopted in the workplace is rather offputting to a lot of people, including myself. It depends on what your options and commitments are, but I know I'd be a lot more keen on accepting ideas because they are good ideas, not because they are a bandwagon. Try implementing/drawing her in to the practices one at a time, by showing her how they can improve her life and workflow as well. Programmers love cool things that help them get stuff done. They hate being preached at or being asked to board what they see as a bandwagon. Present it as the former rather than the latter. (It goes without saying, make sure it actually IS the former) Edit: another question I've never actually worked for a place that used a specific agile methodology, though I'm pretty happy where I'm at now in that we incorporate a lot of agile practices without the hype and the dogma (best of both worlds, IMHO). But I was just reading about Scrum and, is a system like that even beneficial for a 2 person team? Scrum does add a certain amount of overhead to a project, it seems, and that might outweigh the benefits when you have a very small team where communication and planning is already easy. | {
"score": 5,
"source": [
"https://Stackoverflow.com/questions/34981",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3622/"
]
} |
34,987 | I am trying to iterate over all the elements of a static array of strings in the best possible way. I want to be able to declare it on one line and easily add/remove elements from it without having to keep track of the number. Sounds really simple, doesn't it? Possible non-solutions: vector<string> v;v.push_back("abc");b.push_back("xyz");for(int i = 0; i < v.size(); i++) cout << v[i] << endl; Problems - no way to create the vector on one line with a list of strings Possible non-solution 2: string list[] = {"abc", "xyz"}; Problems - no way to get the number of strings automatically (that I know of). There must be an easy way of doing this. | C++ 11 added initialization lists to allow the following syntax: std::vector<std::string> v = {"Hello", "World"}; Support for this C++ 11 feature was added in at least GCC 4.4 and only in Visual Studio 2013 . | {
"score": 7,
"source": [
"https://Stackoverflow.com/questions/34987",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/779/"
]
} |
35,002 | Is there anything built into the core C# libraries that can give me an immutable Dictionary? Something along the lines of Java's : Collections.unmodifiableMap(myMap); And just to clarify, I am not looking to stop the keys / values themselves from being changed, just the structure of the Dictionary. I want something that fails fast and loud if any of IDictionary's mutator methods are called ( Add, Remove, Clear ). | No, but a wrapper is rather trivial: public class ReadOnlyDictionary<TKey, TValue> : IDictionary<TKey, TValue>{ IDictionary<TKey, TValue> _dict; public ReadOnlyDictionary(IDictionary<TKey, TValue> backingDict) { _dict = backingDict; } public void Add(TKey key, TValue value) { throw new InvalidOperationException(); } public bool ContainsKey(TKey key) { return _dict.ContainsKey(key); } public ICollection<TKey> Keys { get { return _dict.Keys; } } public bool Remove(TKey key) { throw new InvalidOperationException(); } public bool TryGetValue(TKey key, out TValue value) { return _dict.TryGetValue(key, out value); } public ICollection<TValue> Values { get { return _dict.Values; } } public TValue this[TKey key] { get { return _dict[key]; } set { throw new InvalidOperationException(); } } public void Add(KeyValuePair<TKey, TValue> item) { throw new InvalidOperationException(); } public void Clear() { throw new InvalidOperationException(); } public bool Contains(KeyValuePair<TKey, TValue> item) { return _dict.Contains(item); } public void CopyTo(KeyValuePair<TKey, TValue>[] array, int arrayIndex) { _dict.CopyTo(array, arrayIndex); } public int Count { get { return _dict.Count; } } public bool IsReadOnly { get { return true; } } public bool Remove(KeyValuePair<TKey, TValue> item) { throw new InvalidOperationException(); } public IEnumerator<KeyValuePair<TKey, TValue>> GetEnumerator() { return _dict.GetEnumerator(); } System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator() { return ((System.Collections.IEnumerable)_dict).GetEnumerator(); }} Obviously, you can change the this[] setter above if you want to allow modifying values. | {
"score": 7,
"source": [
"https://Stackoverflow.com/questions/35002",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1853/"
]
} |
35,007 | Every time I create an object that has a collection property I go back and forth on the best way to do it? public property with a getter thatreturns a reference to private variable explicit get_ObjList and set_ObjListmethods that return and create new or clonedobjects every time explicit get_ObjList that returns anIEnumerator and a set_ObjList thattakes IEnumerator Does it make a difference if the collection is an array (i.e., objList.Clone()) versus a List? If returning the actual collection as a reference is so bad because it creates dependencies, then why return any property as a reference? Anytime you expose an child object as a reference the internals of that child can be changed without the parent "knowing" unless the child has a property changed event. Is there a risk for memory leaks? And, don't options 2 and 3 break serialization? Is this a catch 22 or do you have to implement custom serialization anytime you have a collection property? The generic ReadOnlyCollection seems like a nice compromise for general use. It wraps an IList and restricts access to it. Maybe this helps with memory leaks and serialization. However it still has enumeration concerns Maybe it just depends. If you don't care that the collection is modified, then just expose it as a public accessor over a private variable per #1. If you don't want other programs to modify the collection then #2 and/or #3 is better. Implicit in the question is why should one method be used over another and what are the ramifications on security, memory, serialization, etc.? | How you expose a collection depends entirely on how users are intended to interact with it. 1) If users will be adding and removing items from an object's collection, then a simple get-only collection property is best (option #1 from the original question): private readonly Collection<T> myCollection_ = new ...;public Collection<T> MyCollection { get { return this.myCollection_; }} This strategy is used for the Items collections on the WindowsForms and WPF ItemsControl controls, where users add and remove items they want the control to display. These controls publish the actual collection and use callbacks or event listeners to keep track of items. WPF also exposes some settable collections to allow users to display a collection of items they control, such as the ItemsSource property on ItemsControl (option #3 from the original question). However, this is not a common use case. 2) If users will only be reading data maintained by the object, then you can use a readonly collection, as Quibblesome suggested: private readonly List<T> myPrivateCollection_ = new ...;private ReadOnlyCollection<T> myPrivateCollectionView_;public ReadOnlyCollection<T> MyCollection { get { if( this.myPrivateCollectionView_ == null ) { /* lazily initialize view */ } return this.myPrivateCollectionView_; }} Note that ReadOnlyCollection<T> provides a live view of the underlying collection, so you only need to create the view once. If the internal collection does not implement IList<T> , or if you want to restrict access to more advanced users, you can instead wrap access to the collection through an enumerator: public IEnumerable<T> MyCollection { get { foreach( T item in this.myPrivateCollection_ ) yield return item; }} This approach is simple to implement and also provides access to all the members without exposing the internal collection. However, it does require that the collection remain unmodfied, as the BCL collection classes will throw an exception if you try to enumerate a collection after it has been modified. If the underlying collection is likely to change, you can either create a light wrapper that will enumerate the collection safely, or return a copy of the collection. 3) Finally, if you need to expose arrays rather than higher-level collections, then you should return a copy of the array to prevent users from modifying it (option #2 from the orginal question): private T[] myArray_;public T[] GetMyArray( ) { T[] copy = new T[this.myArray_.Length]; this.myArray_.CopyTo( copy, 0 ); return copy; // Note: if you are using LINQ, calling the 'ToArray( )' // extension method will create a copy for you.} You should not expose the underlying array through a property, as you will not be able to tell when users modify it. To allow modifying the array, you can either add a corresponding SetMyArray( T[] array ) method, or use a custom indexer: public T this[int index] { get { return this.myArray_[index]; } set { // TODO: validate new value; raise change event; etc. this.myArray_[index] = value; }} (of course, by implementing a custom indexer, you will be duplicating the work of the BCL classes :) | {
"score": 7,
"source": [
"https://Stackoverflow.com/questions/35007",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2582/"
]
} |
35,011 | I've got a whole directory of dll's I need to register to the GAC. I'd like to avoid registering each file explicitly- but it appears that gacutil has no "register directory" option. Anyone have a fast/simple solution? | GACUTIL doesn't register DLLs -- not in the "COM" sense. Unlike in COM, GACUTIL copies the file to an opaque directory under %SYSTEMROOT%\assembly and that's where they run from. It wouldn't make sense to ask GACUTIL "register a folder" (not that you can do that with RegSvr32 either). You can use a batch FOR command such as: FOR %a IN (C:\MyFolderWithAssemblies\*.dll) DO GACUTIL /i %a If you place that in a batch file, you must replace %a with %%a | {
"score": 6,
"source": [
"https://Stackoverflow.com/questions/35011",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/667/"
]
} |
35,026 | I need to convert a named instance of SQL server 2005, to a default instance. Is there a way to do this without a reinstall? The problem is, 2 out of 6 of the developers, installed with a named instance. So its becoming a pain changing connection strings for the other 4 of us. I am looking for the path of least resistance to getting these 2 back on to our teams standard setup. Each has expressed that this is going to be, too much trouble and that it will take away from their development time. I assumed that it would take some time to resolve, in the best interest of all involved, I tried combing through configuration apps installed and didn't see anything, so I figured someone with more knowledge of the inner workings would be here. | I also wanted to convert a named instance to default - my reason was to access it with just the machine name from various applications. If you want to access a named instance from any connection string without using the instance name , and using only the server name and/or IP address, then you can do the following: Open SQL Server Configuration Manager Click SQL Server Network Configuration Click Protocols for INSTANCENAME you want to make available (i.e. SQLExpress) Right-click TCP/IP and click Enabled Right-click TCP/IP and go to Properties Go to the IP Addresses tab Scroll down to the IPAll section Clear the field TCP Dynamic Ports (i.e. empty/blank ) Set TCP Port to 1433 Click Ok Go to SQL Server Services Right-click your SQL Server (INSTANCENAME) and click Restart This will make the named instance listen on the default port. Note : You can have only one instance configured like this - no two instances can have same port on the IP All section unless the instance is a failover cluster. | {
"score": 9,
"source": [
"https://Stackoverflow.com/questions/35026",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1220/"
]
} |
35,103 | I'd like to bind a configuration file to my executable. I'd like to do this by storing an MD5 hash of the file inside the executable. This should keep anyone but the executable from modifying the file. Essentially if someone modifies this file outside of the program the program should fail to load it again. EDIT: The program processes credit card information so being able to change the configuration in any way could be a potential security risk. This software will be distributed to a large number of clients. Ideally client should have a configuration that is tied directly to the executable. This will hopefully keep a hacker from being able to get a fake configuration into place. The configuration still needs to be editable though so compiling an individual copy for each customer is not an option. It's important that this be dynamic. So that I can tie the hash to the configuration file as the configuration changes. | A better solution is to store the MD5 in the configuration file. But instead of the MD5 being just of the configuration file, also include some secret "key" value, like a fixed guid, in the MD5. write(MD5(SecretKey + ConfigFileText)); Then you simply remove that MD5 and rehash the file (including your secret key). If the MD5's are the same, then no-one modified it. This prevents someone from modifying it and re-applying the MD5 since they don't know your secret key. Keep in mind this is a fairly weak solution (as is the one you are suggesting) as they could easily track into your program to find the key or where the MD5 is stored. A better solution would be to use a public key system and sign the configuration file. Again that is weak since that would require the private key to be stored on their local machine. Pretty much anything that is contained on their local PC can be bypassed with enough effort. If you REALLY want to store the information in your executable (which I would discourage) then you can just try appending it at the end of the EXE. That is usually safe. Modifying executable programs is virus like behavior and most operating system security will try to stop you too. If your program is in the Program Files directory, and your configuration file is in the Application Data directory, and the user is logged in as a non-administrator (in XP or Vista), then you will be unable to update the EXE. Update: I don't care if you are using Asymmetric encryption, RSA or Quantum cryptography, if you are storing your keys on the user's computer (which you must do unless you route it all through a web service) then the user can find your keys, even if it means inspecting the registers on the CPU at run time! You are only buying yourself a moderate level of security, so stick with something that is simple. To prevent modification the solution I suggested is the best. To prevent reading then encrypt it, and if you are storing your key locally then use AES Rijndael. Update: The FixedGUID / SecretKey could alternatively be generated at install time and stored somewhere "secret" in the registry. Or you could generate it every time you use it from hardware configuration. Then you are getting more complicated. How you want to do this to allow for moderate levels of hardware changes would be to take 6 different signatures, and hash your configuration file 6 times - once with each. Combine each one with a 2nd secret value, like the GUID mentioned above (either global or generated at install). Then when you check you verify each hash separately. As long as they have 3 out of 6 (or whatever your tolerance is) then you accept it. Next time you write it you hash it with the new hardware configuration. This allows them to slowly swap out hardware over time and get a whole new system. . . Maybe that is a weakness. It all comes down to your tolerance. There are variations based on tighter tolerances. UPDATE: For a Credit Card system you might want to consider some real security. You should retain the services of a security and cryptography consultant . More information needs to be exchanged. They need to analyze your specific needs and risks. Also, if you want security with .NET you need to first start with a really good .NET obfuscator ( just Google it ). A .NET assembly is way to easy to disassemble and get at the source code and read all your secrets. Not to sound a like a broken record, but anything that depends on the security of your user's system is fundamentally flawed from the beginning. | {
"score": 5,
"source": [
"https://Stackoverflow.com/questions/35103",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2191/"
]
} |
35,106 | I've found ScriptingJsonSerializationSection but I'm not sure how to use it. I could write a function to convert the object to a JSON string manually, but since .Net can do it on the fly with the <System.Web.Services.WebMethod()> and <System.Web.Script.Services.ScriptMethod()> attributes so there must be a built-in way that I'm missing. PS: using Asp.Net 2.0 and VB.Net - I put this in the tags but I think people missed it. | This should do the trick Dim jsonSerialiser As New System.Web.Script.Serialization.JavaScriptSerializerDim jsonString as String = jsonSerialiser.Serialize(yourObject) | {
"score": 5,
"source": [
"https://Stackoverflow.com/questions/35106",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1414/"
]
} |
35,123 | What did I do wrong? Here is an excerpt from my code: public void createPartControl(Composite parent) { parent.setLayout(new FillLayout()); ScrolledComposite scrollBox = new ScrolledComposite(parent, SWT.V_SCROLL); scrollBox.setExpandHorizontal(true); mParent = new Composite(scrollBox, SWT.NONE); scrollBox.setContent(mParent); FormLayout layout = new FormLayout(); mParent.setLayout(layout); // Adds a bunch of controls here mParent.layout(); mParent.setSize(mParent.computeSize(SWT.DEFAULT, SWT.DEFAULT, true));} ...but it clips the last button: bigbrother82: That didn't work. SCdF: I tried your suggestion, and now the scrollbars are gone. I need to work some more on that. | This is a common hurdle when using ScrolledComposite . When it gets so small that the scroll bar must be shown, the client control has to shrink horizontally to make room for the scroll bar. This has the side effect of making some labels wrap lines, which moved the following controls farther down, which increased the minimum height needed by the content composite. You need to listen for width changes on the content composite ( mParent ), compute the minimum height again given the new content width, and call setMinHeight() on the scrolled composite with new height. public void createPartControl(Composite parent) { parent.setLayout(new FillLayout()); ScrolledComposite scrollBox = new ScrolledComposite(parent, SWT.V_SCROLL); scrollBox.setExpandHorizontal(true); scrollBox.setExpandVertical(true); // Using 0 here ensures the horizontal scroll bar will never appear. If // you want the horizontal bar to appear at some threshold (say 100 // pixels) then send that value instead. scrollBox.setMinWidth(0); mParent = new Composite(scrollBox, SWT.NONE); FormLayout layout = new FormLayout(); mParent.setLayout(layout); // Adds a bunch of controls here mParent.addListener(SWT.Resize, new Listener() { int width = -1; public void handleEvent(Event e) { int newWidth = mParent.getSize().x; if (newWidth != width) { scrollBox.setMinHeight(mParent.computeSize(newWidth, SWT.DEFAULT).y); width = newWidth; } } } // Wait until here to set content pane. This way the resize listener will // fire when the scrolled composite first resizes mParent, which in turn // computes the minimum height and calls setMinHeight() scrollBox.setContent(mParent);} In listening for size changes, note that we ignore any resize events where the width stays the same. This is because changes in the height of the content do not affect the minimum height of the content, as long as the width is the same. | {
"score": 5,
"source": [
"https://Stackoverflow.com/questions/35123",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3657/"
]
} |
35,167 | I know that the following is true int i = 17; //binary 10001int j = i << 1; //decimal 34, binary 100010 But, if you shift too far, the bits fall off the end. Where this happens is a matter of the size of integer you are working with. Is there a way to perform a shift so that the bits rotate around to the other side? I'm looking for a single operation, not a for loop. | If you know the size of type, you could do something like: uint i = 17;uint j = i << 1 | i >> 31; ... which would perform a circular shift of a 32 bit value. As a generalization to circular shift left n bits, on a b bit variable: /*some unsigned numeric type*/ input = 17;var result = input << n | input >> (b - n); @The comment, it appears that C# does treat the high bit of signed values differently. I found some info on this here . I also changed the example to use a uint. | {
"score": 7,
"source": [
"https://Stackoverflow.com/questions/35167",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2470/"
]
} |
35,170 | What does it mean if a task is declared with the automatic keyword in Verilog? task automatic do_things; input [31:0] number_of_things; reg [31:0] tmp_thing; begin // ... endendtask; Note: This question is mostly because I'm curious if there are any hardware programmers on the site. :) | It means that the task is re-entrant - items declared within the task are dynamically allocated rather than shared between different invocations of the task. You see - some of us do Verilog... (ugh) | {
"score": 5,
"source": [
"https://Stackoverflow.com/questions/35170",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3594/"
]
} |
35,185 | What would be the best algorithm for finding a number that occurs only once in a list which has all other numbers occurring exactly twice. So, in the list of integers (lets take it as an array) each integer repeats exactly twice, except one. To find that one, what is the best algorithm. | The fastest (O(n)) and most memory efficient (O(1)) way is with the XOR operation. In C: int arr[] = {3, 2, 5, 2, 1, 5, 3};int num = 0, i;for (i=0; i < 7; i++) num ^= arr[i];printf("%i\n", num); This prints "1", which is the only one that occurs once. This works because the first time you hit a number it marks the num variable with itself, and the second time it unmarks num with itself (more or less). The only one that remains unmarked is your non-duplicate. | {
"score": 8,
"source": [
"https://Stackoverflow.com/questions/35185",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/380/"
]
} |
35,186 | I'm getting a NoSuchMethodError error when running my Java program. What's wrong and how do I fix it? | Without any more information it is difficult to pinpoint the problem, but the root cause is that you most likely have compiled a class against a different version of the class that is missing a method, than the one you are using when running it. Look at the stack trace ... If the exception appears when calling a method on an object in a library, you are most likely using separate versions of the library when compiling and running. Make sure you have the right version both places. If the exception appears when calling a method on objects instantiated by classes you made, then your build process seems to be faulty. Make sure the class files that you are actually running are updated when you compile. | {
"score": 9,
"source": [
"https://Stackoverflow.com/questions/35186",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3535/"
]
} |
35,194 | Have you guys had any experiences (positive or negative) by placing your source code/solution on a network drive for Visual Studio 2005 or 2008? Please note I am not referring to placing your actual source control system on that drive, but rather your working folder. Thanks | Without any more information it is difficult to pinpoint the problem, but the root cause is that you most likely have compiled a class against a different version of the class that is missing a method, than the one you are using when running it. Look at the stack trace ... If the exception appears when calling a method on an object in a library, you are most likely using separate versions of the library when compiling and running. Make sure you have the right version both places. If the exception appears when calling a method on objects instantiated by classes you made, then your build process seems to be faulty. Make sure the class files that you are actually running are updated when you compile. | {
"score": 9,
"source": [
"https://Stackoverflow.com/questions/35194",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2343/"
]
} |
35,224 | I have a Flex ComboBox that gets populated by a dataprovider all is well... I would now like to add a default " -- select a item --" option at the 0 index, how can I do this and still use a dataprovider ? I have not seen any examples of such, but I can't imagine this being hard... | If you don't need the default item to be selectable you can use the prompt property of ComboBox and set the selectedIndex to -1. That will show the string you set propmt to as the selected value until the user chooses another. It will not appear in the list of options, however. | {
"score": 6,
"source": [
"https://Stackoverflow.com/questions/35224",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1638/"
]
} |
35,301 | I have always used || (two pipes) in OR expressions, both in C# and PHP. Occasionally I see a single pipe used: | . What is the difference between those two usages? Are there any caveats when using one over the other or are they interchangeable? | Just like the & and && operator, the double Operator is a "short-circuit" operator. For example: if(condition1 || condition2 || condition3) If condition1 is true, condition 2 and 3 will NOT be checked. if(condition1 | condition2 | condition3) This will check conditions 2 and 3, even if 1 is already true. As your conditions can be quite expensive functions, you can get a good performance boost by using them. There is one big caveat, NullReferences or similar problems. For example: if(class != null && class.someVar < 20) If class is null, the if-statement will stop after class != null is false. If you only use &, it will try to check class.someVar and you get a nice NullReferenceException . With the Or-Operator that may not be that much of a trap as it's unlikely that you trigger something bad, but it's something to keep in mind. No one ever uses the single & or | operators though, unless you have a design where each condition is a function that HAS to be executed. Sounds like a design smell, but sometimes (rarely) it's a clean way to do stuff. The & operator does "run these 3 functions, and if one of them returns false, execute the else block", while the | does "only run the else block if none return false" - can be useful, but as said, often it's a design smell. There is a Second use of the | and & operator though: Bitwise Operations . | {
"score": 10,
"source": [
"https://Stackoverflow.com/questions/35301",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3238/"
]
} |
35,366 | I'm working on a database for a small web app at my school using SQL Server 2005 . I see a couple of schools of thought on the issue of varchar vs nvarchar : Use varchar unless you deal with a lot of internationalized data, then use nvarchar . Just use nvarchar for everything. I'm beginning to see the merits of view 2. I know that nvarchar does take up twice as much space, but that isn't necessarily a huge deal since this is only going to store data for a few hundred students. To me it seems like it would be easiest not to worry about it and just allow everything to use nvarchar. Or is there something I'm missing? | Always use nvarchar. You may never need the double-byte characters for most applications. However, if you need to support double-byte languages and you only have single-byte support in your database schema it's really expensive to go back and modify throughout your application. The cost of migrating one application from varchar to nvarchar will be much more than the little bit of extra disk space you'll use in most applications. | {
"score": 8,
"source": [
"https://Stackoverflow.com/questions/35366",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2147/"
]
} |
35,373 | I have a solution consisting of five projects, each of which compile to separate assemblies. Right now I'm code-signing them, but I'm pretty sure I'm doing it wrong. What's the best practice here? Sign each with a different key; make sure the passwords are different Sign each with a different key; use the same password if you want Sign each with the same key Something else entirely Basically I'm not quite sure what "signing" does to them, or what the best practices are here, so a more generally discussion would be good. All I really know is that FxCop yelled at me, and it was easy to fix by clicking the "Sign this assembly" checkbox and generating a .pfx file using Visual Studio (2008). | If your only objective is to stop FxCop from yelling at you, then you have found the best practice. The best practice for signing your assemblies is something that is completely dependent on your objectives and needs. We would need more information like your intended deployment: For personal use For use on corporate network PC's as a client application Running on a web server Running in SQL Server Downloaded over the internet Sold on a CD in shrink wrap Uploaded straight into a cybernetic brain Etc. Generally you use code signing to verify that the Assemblies came from a specific trusted source and have not been modified. So each with the same key is fine. Now how that trust and identity is determined is another story. UPDATE: How this benefits your end users when you are deploying over the web is if you have obtained a software signing certificate from a certificate authority . Then when they download your assemblies they can verify they came from Domenic's Software Emporium , and they haven't been modified or corrupted along the way. You will also want to sign the installer when it is downloaded. This prevents the warning that some browsers display that it has been obtained from an unknown source. Note, you will pay for a software signing certificate. What you get is the certificate authority become the trusted 3rd party who verifies you are who you say you are. This works because of a web of trust that traces its way back to a root certificate that is installed in their operating system. There are a few certificate authorities to choose from, but you will want to make sure they are supported by the root certificates on the target operating system. | {
"score": 6,
"source": [
"https://Stackoverflow.com/questions/35373",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3191/"
]
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.