source_id
int64 1
74.7M
| question
stringlengths 0
40.2k
| response
stringlengths 0
111k
| metadata
dict |
---|---|---|---|
44,153 | Like the title says: Can reflection give you the name of the currently executing method. I'm inclined to guess not, because of the Heisenberg problem. How do you call a method that will tell you the current method without changing what the current method is? But I'm hoping someone can prove me wrong there. Update: Part 2: Could this be used to look inside code for a property as well? Part 3: What would the performance be like? Final Result I learned about MethodBase.GetCurrentMethod(). I also learned that not only can I create a stack trace, I can create only the exact frame I need if I want. To use this inside a property, just take a .Substring(4) to remove the 'set_' or 'get_'. | For non- async methods one can use System.Reflection.MethodBase.GetCurrentMethod().Name; https://learn.microsoft.com/en-us/dotnet/api/system.reflection.methodbase.getcurrentmethod Please remember that for async methods it will return "MoveNext". | {
"score": 8,
"source": [
"https://Stackoverflow.com/questions/44153",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3043/"
]
} |
44,176 | Is there a way to perform a full text search of a subversion repository, including all the history? For example, I've written a feature that I used somewhere, but then it wasn't needed, so I svn rm'd the files, but now I need to find it again to use it for something else. The svn log probably says something like "removed unused stuff", and there's loads of checkins like that. Edit 2016-04-15: Please note that what is asked here by the term "full text search", is to search the actual diffs of the commit history, and not filenames and/or commit messages . I'm pointing this out because the author's phrasing above does not reflect that very well - since in his example he might as well be only looking for a filename and/or commit message. Hence a lot of the svn log answers and comments. | git svn clone <svn url> git log -G<some regex> | {
"score": 7,
"source": [
"https://Stackoverflow.com/questions/44176",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3408/"
]
} |
44,181 | I have a database with two tables ( Table1 and Table2 ). They both have a common column [ColumnA] which is an nvarchar . How can I select this column from both tables and return it as a single column in my result set? So I'm looking for something like: ColumnA in Table1:abcColumnA in Table2:defResult set should be:abcdef | SELECT ColumnA FROM Table1 UNION Select ColumnB FROM Table2 ORDER BY 1 Also, if you know the contents of Table1 and Table2 will NEVER overlap, you can use UNION ALL in place of UNION instead. Saves a little bit of resources that way. -- Kevin Fairchild | {
"score": 5,
"source": [
"https://Stackoverflow.com/questions/44181",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1980/"
]
} |
44,194 | This is what I've got. It works. But, is there a simpler or better way? One an ASPX page, I've got the download link... <asp:HyperLink ID="HyperLinkDownload" runat="server" NavigateUrl="~/Download.aspx">Download as CSV file</asp:HyperLink> And then I've got the Download.aspx.vb Code Behind... Public Partial Class Download Inherits System.Web.UI.Page Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load 'set header Response.Clear() Response.ContentType = "text/csv" Dim FileName As String = "books.csv" Response.AppendHeader("Content-Disposition", "attachment;filename=" + FileName) 'generate file content Dim db As New bookDevelopmentDataContext Dim Allbooks = From b In db.books _ Order By b.Added _ Select b Dim CsvFile As New StringBuilder CsvFile.AppendLine(CsvHeader()) For Each b As Book In Allbooks CsvFile.AppendLine(bookString(b)) Next 'write the file Response.Write(CsvFile.ToString) Response.End() End Sub Function CsvHeader() As String Dim CsvLine As New StringBuilder CsvLine.Append("Published,") CsvLine.Append("Title,") CsvLine.Append("Author,") CsvLine.Append("Price") Return CsvLine.ToString End Function Function bookString(ByVal b As Book) As String Dim CsvLine As New StringBuilder CsvLine.Append(b.Published.ToShortDateString + ",") CsvLine.Append(b.Title.Replace(",", "") + ",") CsvLine.Append(b.Author.Replace(",", "") + ",") CsvLine.Append(Format(b.Price, "c").Replace(",", "")) Return CsvLine.ToString End FunctionEnd Class | CSV formatting has some gotchas. Have you asked yourself these questions: Does any of my data have embedded commas? Does any of my data have embedded double-quotes? Does any of my data have have newlines? Do I need to support Unicode strings? I see several problems in your code above. The comma thing first of all... you are stripping commas: CsvLine.Append(Format(b.Price, "c").Replace(",", "")) Why? In CSV, you should be surrounding anything which has commas with quotes: CsvLine.Append(String.Format("\"{0:c}\"", b.Price)) (or something like that... my VB is not very good). If you're not sure if there are commas, but put quotes around it. If there are quotes in the string, you need to escape them by doubling them. " becomes "" . b.Title.Replace("\"", "\"\"") Then surround this by quotes if you want. If there are newlines in your string, you need to surround the string with quotes... yes, literal newlines are allowed in CSV files. It looks weird to humans, but it's all good. A good CSV writer requires some thought. A good CSV reader (parser) is just plain hard (and no, regex not good enough for parsing CSV... it will only get you about 95% of the way there). And then there is Unicode... or more generally I18N (Internationalization) issues. For example, you are stripping commas out of a formatted price. But that's assuming the price is formatted as you expect it in the US. In France, the number formatting is reversed (periods used instead of commas, and vice versa ). Bottom line, use culture-agnostic formatting wherever possible. While the issue here is generating CSV, inevitably you will need to parse CSV. In .NET, the best parser I have found (for free) is Fast CSV Reader on CodeProject . I've actually used it in production code and it is really really fast, and very easy to use! | {
"score": 6,
"source": [
"https://Stackoverflow.com/questions/44194",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/83/"
]
} |
44,288 | Comparing string in C# is pretty simple. In fact there are several ways to do it. I have listed some in the block below. What I am curious about are the differences between them and when one should be used over the others? Should one be avoided at all costs? Are there more I haven't listed? string testString = "Test";string anotherString = "Another";if (testString.CompareTo(anotherString) == 0) {}if (testString.Equals(anotherString)) {}if (testString == anotherString) {} (Note: I am looking for equality in this example, not less than or greater than but feel free to comment on that as well) | Here are the rules for how these functions work: stringValue.CompareTo(otherStringValue) null comes before a string it uses CultureInfo.CurrentCulture.CompareInfo.Compare , which means it will use a culture-dependent comparison. This might mean that ß will compare equal to SS in Germany, or similar stringValue.Equals(otherStringValue) null is not considered equal to anything unless you specify a StringComparison option, it will use what looks like a direct ordinal equality check, i.e. ß is not the same as SS , in any language or culture stringValue == otherStringValue Is not the same as stringValue.Equals() . The == operator calls the static Equals(string a, string b) method (which in turn goes to an internal EqualsHelper to do the comparison. Calling .Equals() on a null string gets null reference exception, while on == does not. Object.ReferenceEquals(stringValue, otherStringValue) Just checks that references are the same, i.e. it isn't just two strings with the same contents, you're comparing a string object with itself. Note that with the options above that use method calls, there are overloads with more options to specify how to compare. My advice if you just want to check for equality is to make up your mind whether you want to use a culture-dependent comparison or not, and then use .CompareTo or .Equals , depending on the choice. | {
"score": 9,
"source": [
"https://Stackoverflow.com/questions/44288",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2894/"
]
} |
44,352 | In Python, given a module X and a class Y, how can I iterate or generate a list of all subclasses of Y that exist in module X? | Here's one way to do it: import inspectdef get_subclasses(mod, cls): """Yield the classes in module ``mod`` that inherit from ``cls``""" for name, obj in inspect.getmembers(mod): if hasattr(obj, "__bases__") and cls in obj.__bases__: yield obj | {
"score": 5,
"source": [
"https://Stackoverflow.com/questions/44352",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
]
} |
44,359 | I have built a basic data entry application allowing users to browse external content in iframe and enter data quickly from the same page. One of the data variables is the URL.Ideally I would like to be able to load the iframes current url into a textbox with javascript. I realize now that this is not going to happen due to security issues. Has anyone done anything on the server side? or know of any .Net browser in browser controls. The ultimate goal is to just give the user an easy method of extracting the url of the page they are viewing in the iframe It doesn't necessarily HAVE to be an iframe, a browser in the browser would be ideal. Thanks,Adam | I did some tests in Firefox 3 comparing the value of .src and .documentWindow.location.href in an iframe . (Note: The documentWindow is called contentDocument in Chrome, so instead of .documentWindow.location.href in Chrome it will be .contentDocument.location.href .) src is always the last URL that was loaded in the iframe without user interaction. I.e., it contains the first value for the URL, or the last value you set up with Javascript from the containing window doing: document.getElementById("myiframe").src = 'http://www.google.com/'; If the user navigates inside the iframe, you can't anymore access the value of the URL using src. In the previous example, if the user goes away from www.google.com and you do: alert(document.getElementById("myiframe").src); You will still get " http://www.google.com ". documentWindow.location.href is only available if the iframe contains a page in the same domain as the containing window, but if it's available it always contains the right value for the URL, even if the user navigates in the iframe. If you try to access documentWindow.location.href (or anything under documentWindow ) and the iframe is in a page that doesn't belong to the domain of the containing window, it will raise an exception: document.getElementById("myiframe").src = 'http://www.google.com/';alert(document.getElementById("myiframe").documentWindow.location.href);Error: Permission denied to get property Location.href I have not tested any other browser. Hope it helps! | {
"score": 6,
"source": [
"https://Stackoverflow.com/questions/44359",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4568/"
]
} |
44,364 | So, I was reading the Google testing blog, and it says that global state is bad and makes it hard to write tests. I believe it--my code is difficult to test right now. So how do I avoid global state? The biggest things I use global state (as I understand it) for is managing key pieces of information between our development, acceptance, and production environments. For example, I have a static class named "Globals" with a static member called "DBConnectionString." When the application loads, it determines which connection string to load, and populates Globals.DBConnectionString. I load file paths, server names, and other information in the Globals class. Some of my functions rely on the global variables. So, when I test my functions, I have to remember to set certain globals first or else the tests will fail. I'd like to avoid this. Is there a good way to manage state information? (Or am I understanding global state incorrectly?) | Dependency injection is what you're looking for. Rather than have those functions go out and look for their dependencies, inject the dependencies into the functions. That is, when you call the functions pass the data they want to them. That way it's easy to put a testing framework around a class because you can simply inject mock objects where appropriate. It's hard to avoid some global state, but the best way to do this is to use factory classes at the highest level of your application, and everything below that very top level is based on dependency injection. Two main benefits: one, testing is a heck of a lot easier, and two, your application is much more loosely coupled. You rely on being able to program against the interface of a class rather than its implementation. | {
"score": 5,
"source": [
"https://Stackoverflow.com/questions/44364",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/681/"
]
} |
44,376 | How do you shade alternating rows in a SQL Server Reporting Services report? Edit: There are a bunch of good answers listed below--from quick and simple to complex and comprehensive . Alas, I can choose only one... | Go to the table row's BackgroundColor property and choose "Expression..." Use this expression: = IIf(RowNumber(Nothing) Mod 2 = 0, "Silver", "Transparent") This trick can be applied to many areas of the report. And in .NET 3.5+ You could use: = If(RowNumber(Nothing) Mod 2 = 0, "Silver", "Transparent") Not looking for rep--I just researched this question myself and thought I'd share. | {
"score": 9,
"source": [
"https://Stackoverflow.com/questions/44376",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/29/"
]
} |
44,383 | I am looking for a method of reading emails using Pop3 in C# 2.0. Currently, I am using code found in CodeProject . However, this solution is less than ideal. The biggest problem is that it doesn't support emails written in unicode. | I've successfully used OpenPop.NET to access emails via POP3. | {
"score": 7,
"source": [
"https://Stackoverflow.com/questions/44383",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/889/"
]
} |
44,391 | This is related to another question I asked . In summary, I have a special case of a URL where, when a form is POSTed to it, I can't rely on cookies for authentication or to maintain the user's session, but I somehow need to know who they are, and I need to know they're logged in! I think I came up with a solution to my problem, but it needs fleshing out. Here's what I'm thinking. I create a hidden form field called "username", and place within it the user's username, encrypted. Then, when the form POSTs, even though I don't receive any cookies from the browser, I know they're logged in because I can decrypt the hidden form field and get the username. The major security flaw I can see is replay attacks. How do I prevent someone from getting ahold of that encrypted string, and POSTing as that user? I know I can use SSL to make it harder to steal that string, and maybe I can rotate the encryption key on a regular basis to limit the amount of time that the string is good for, but I'd really like to find a bulletproof solution. Anybody have any ideas? Does the ASP.Net ViewState prevent replay? If so, how do they do it? Edit : I'm hoping for a solution that doesn't require anything stored in a database. Application state would be okay, except that it won't survive an IIS restart or work at all in a web farm or garden scenario. I'm accepting Chris's answer, for now, because I'm not convinced it's even possible to secure this without a database. But if someone comes up with an answer that does not involve the database, I'll accept it! | If you hash in a time-stamp along with the user name and password, you can close the window for replay attacks to within a couple of seconds. I don't know if this meets your needs, but it is at least a partial solution. | {
"score": 5,
"source": [
"https://Stackoverflow.com/questions/44391",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2527/"
]
} |
44,396 | I use Eclipse, Maven, and Java in my development. I use Maven to download dependencies (jar files and javadoc when available) and Maven's eclipse plug-in to generate the .project and .classpath files for Eclipse. When the dependency downloaded does not have attached javadoc I manually add a link for the javadoc in the .classpath file so that I can see the javadoc for the dependency in Eclipse. Then when I run Maven's eclipse plugin to regenerate the .classpath file it of course wipes out that change. Is there a way to configure Maven's eclipse plug-in to automatically add classpath attributes for javadoc when running Maven's eclipse plug-in? I'm only interested in answers where the javadoc and/or sources are not provided for the dependency in the maven repository, which is the case most often for me. Using downloadSources and/or downloadJavadocs properties won't help this problem. | From the Maven Eclipse Plugin FAQ The following example shows how to do this in the command-line: mvn eclipse:eclipse -DdownloadSources=true -DdownloadJavadocs=true or in your pom.xml: <project> [...] <build> [...] <plugins> [...] <plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-eclipse-plugin</artifactId> <configuration> <downloadSources>true</downloadSources> <downloadJavadocs>true</downloadJavadocs> </configuration> </plugin> [...] </plugins> [...] </build> [...]</project> | {
"score": 5,
"source": [
"https://Stackoverflow.com/questions/44396",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4476/"
]
} |
44,408 | I would like to generate a random floating point number between 2 values. What is the best way to do this in C#? | The only thing I'd add to Eric 's response is an explanation; I feel that knowledge of why code works is better than knowing what code works. The explanation is this: let's say you want a number between 2.5 and 4.5. The range is 2.0 (4.5 - 2.5). NextDouble only returns a number between 0 and 1.0, but if you multiply this by the range you will get a number between 0 and range . So, this would give us random doubles between 0.0 and 2.0: rng.NextDouble() * 2.0 But, we want them between 2.5 and 4.5! How do we do this? Add the smallest number, 2.5: 2.5 + rng.NextDouble() * 2.0 Now, we get a number between 0.0 and 2.0; if you add 2.5 to each of these values we see that the range is now between 2.5 and 4.5. At first I thought that it mattered if b > a or a > b, but if you work it out both ways you'll find it works out identically so long as you don't mess up the order of the variables used. I like to express it with longer variable names so I don't get mixed up: double NextDouble(Random rng, double min, double max){ return min + (rng.NextDouble() * (max - min));} | {
"score": 7,
"source": [
"https://Stackoverflow.com/questions/44408",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2064/"
]
} |
44,470 | Every time I publish the application in ClickOnce I get get it to update the revision number by one. Is there a way to get this change automatically to change the version number in AssemblyInfo.cs file (all our error reporting looks at the Assembly Version)? | We use Team Foundation Server Team Build and have added a block to the TFSBuild.proj's AfterCompile target to trigger the ClickOnce publish with our preferred version number: <MSBuild Projects="$(SolutionRoot)\MyProject\Myproject.csproj" Properties="PublishDir=$(OutDir)\myProjectPublish\; ApplicationVersion=$(PublishApplicationVersion); Configuration=$(Configuration);Platform=$(Platform)" Targets="Publish" /> The PublishApplicationVersion variable is generated by a custom MSBuild task to use the TFS Changeset number, but you could use your own custom task or an existing solution to get the version number from the AssemblyInfo file. This could theoretically be done in your project file (which is just an MSBuild script anyway), but I'd recommend against deploying from a developer machine. I'm sure other continuous integration (CI) solutions can handle this similarly. Edit: Sorry, got your question backwards. Going from the ClickOnce version number to the AssemblyInfo file should be doable. I'm sure the MSBuild Community Tasks (link above) have a task for updating the AssemblyInfo file, so you'd just need a custom task to pull the version number from the ClickOnce configuration XML. However, you may also consider changing your error reporting to include the ClickOnce publish version too: if (System.Deployment.Application.ApplicationDeployment.IsNetworkDeployed){ Debug.WriteLine(System.Deployment.Application.ApplicationDeployment. CurrentDeployment.CurrentVersion);} | {
"score": 6,
"source": [
"https://Stackoverflow.com/questions/44470",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3798/"
]
} |
44,509 | Our company has multiple domains set up with one website hosted on each of the domains. At this time, each domain has its own authentication which is done via cookies. When someone logged on to one domain needs to access anything from the other, the user needs to log in again using different credentials on the other website, located on the other domain. I was thinking of moving towards single sign on (SSO), so that this hassle can be eliminated. I would appreciate any ideas on how this could be achieved, as I do not have any experience in this regard. Thanks. Edit: The websites are mix of internet (external) and intranet (internal-used within the company) sites. | The SSO solution that I've implemented here works as follows: There is a master domain, login.mydomain.example with the script master_login.php that manages the logins. Each client domain has the script client_login.php All the domains have a shared user session database. When the client domain requires the user to be logged in, it redirects to the master domain ( login.mydomain.example/master_login.php ). If the user has not signed in to the master it requests authentication from the user (ie. display login page). After the user is authenticated it creates a session in a database. If the user is already authenticated it looks up their session id in the database. The master domain returns to the client domain ( client.mydomain.example/client_login.php ) passing the session id. The client domain creates a cookie storing the session id from the master. The client can find out the logged in user by querying the shared database using the session id. Notes: The session id is a unique global identifier generated with algorithm from RFC 4122 The master_login.php will only redirect to domains in its whitelist The master and clients can be in different top level domains. Eg. client1.abc.example , client2.xyz.example , login.mydomain.example | {
"score": 7,
"source": [
"https://Stackoverflow.com/questions/44509",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1311/"
]
} |
44,542 | Can someome provide code or pseudo-code for how the paging links on StackOverflow are generated? I keep racking my brain but can't think of a decent way to build the dynamic links that always show the 2 pages around the current, plus the first and last. Example: 1 ... 5 6 7 ... 593 | There are several other answers already, but I'd like to show you the approach I took to solve it:First, let's check out how Stack Overflow handles normal cases and edge cases. Each of my pages displays 10 results, so to find out what it does for 1 page, find a tag that has less than 11 entries: usability works today. We can see nothing is displayed, which makes sense. How about 2 pages? Find a tag that has between 11 and 20 entries ( emacs works today). We see: " 1 2 Next" or "Prev 1 2 ", depending on which page we're on. 3 pages? " 1 2 3 ... 3 Next", "Prev 1 2 3 Next", and "Prev 1 ... 2 3 ". Interestingly, we can see that Stack Overflow itself doesn't handle this edge case very well: it should display " 1 2 ... 3 Next" 4 pages? " 1 2 3 ... 4 Next", "Prev 1 2 3 ... 4 Next", "Prev 1 ... 2 3 4 Next" and "Prev 1 ... 3 4 " Finally let's look at the general case, N pages: " 1 2 3 ... N Next", "Prev 1 2 3 ... N Next", "Prev 1 ... 2 3 4 ... N Next", "Prev 1 ... 3 4 5 ... N Next", etc. Let's generalize based on what we've seen: The algorithm seems to have these traits in common: If we're not on the first page, display link to Prev Always display the first page number Always display the current page number Always display the page before this page, and the page after this page. Always display the last page number If we're not on the last page, display link to Next Let's ignore the edge case of a single page and make a good first attempt at the algorithm: (As has been mentioned, the code to actually print out the links would be more complicated. Imagine each place we place a page number, Prev or Next as a function call that will return the correct URL.) function printPageLinksFirstTry(num totalPages, num currentPage) if ( currentPage > 1 ) print "Prev" print "1" print "..." print currentPage - 1 print currentPage print currentPage + 1 print "..." print totalPages if ( currentPage < totalPages ) print "Next"endFunction This function works ok, but it doesn't take into account whether we're near the first or last page. Looking at the above examples, we only want to display the ... if the current page is two or more away. function printPageLinksHandleCloseToEnds(num totalPages, num currentPage) if ( currentPage > 1 ) print "Prev" print "1" if ( currentPage > 2 ) print "..." if ( currentPage > 2 ) print currentPage - 1 print currentPage if ( currentPage < totalPages - 1 ) print currentPage + 1 if ( currentPage < totalPages - 1 ) print "..." print totalPages if ( currentPage < totalPages ) print "Next"endFunction As you can see, we have some duplication here. We can go ahead and clean that up for readibility: function printPageLinksCleanedUp(num totalPages, num currentPage) if ( currentPage > 1 ) print "Prev" print "1" if ( currentPage > 2 ) print "..." print currentPage - 1 print currentPage if ( currentPage < totalPages - 1 ) print currentPage + 1 print "..." print totalPages if ( currentPage < totalPages ) print "Next"endFunction There are only two problems left. First, we don't print out correctly for one page, and secondly, we'll print out "1" twice if we're on the first or last page. Let's clean those both up in one go: function printPageLinksFinal(num totalPages, num currentPage) if ( totalPages == 1 ) return if ( currentPage > 1 ) print "Prev" print "1" if ( currentPage > 2 ) print "..." print currentPage - 1 if ( currentPage != 1 and currentPage != totalPages ) print currentPage if ( currentPage < totalPages - 1 ) print currentPage + 1 print "..." print totalPages if ( currentPage < totalPages ) print "Next"endFunction Actually, I lied: We have one remaining issue. When you have at least 4 pages and are on the first or last page, you get an extra page in your display. Instead of " 1 2 ... 10 Next" you get " 1 2 3 ... 10 Next". To match what's going on at Stack Overflow exactly, you'll have to check for this situation: function printPageLinksFinalReally(num totalPages, num currentPage) if ( totalPages == 1 ) return if ( currentPage > 1 ) print "Prev" print "1" if ( currentPage > 2 ) print "..." if ( currentPage == totalPages and totalPages > 3 ) print currentPage - 2 print currentPage - 1 if ( currentPage != 1 and currentPage != totalPages ) print currentPage if ( currentPage < totalPages - 1 ) print currentPage + 1 if ( currentPage == 1 and totalPages > 3 ) print currentPage + 2 print "..." print totalPages if ( currentPage < totalPages ) print "Next"endFunction I hope this helps! | {
"score": 7,
"source": [
"https://Stackoverflow.com/questions/44542",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1097/"
]
} |
44,554 | As Jeff Atwood asked : "What’s your logging philosophy? Should all code be littered with .logthis() and .logthat() calls? Or do you inject logging after the fact somehow?" | My logging philosophy is pretty easily summarized in four parts: Auditing, or business logic logging Log those things that are required to be logged. This comes from the application requirements, and may include logging every change made to any database (as in many financial applications) or logging accesses to data (as may be required in the health industry to meet industry regulations) As this is part of the program requirements many do not include it in their general discussions of logging, however there is overlap in these areas, and for some applications it is useful to consider all logging activities together. Program logging Messages which will help developers test and debug the application, and more easily follow the data flow and program logic to understand where implementation, integration, and other errors may exist. In general this logging is turned on and off as needed for debugging sessions. Performance logging Add later logging as needed to find and resolve performance bottlenecks and other program issues which aren't causing the program to fail, but will lead to better operation. Overlaps with Program logging in the case of memory leaks and some non-critical errors. Security logging Logging user actions and interactions with external systems where security is a concern. Useful for determining how an attacker broke a system after an attack, but may also tie into an intrusion detection system to detect new or ongoing attacks. | {
"score": 5,
"source": [
"https://Stackoverflow.com/questions/44554",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/672/"
]
} |
44,569 | I have never used octal numbers in my code nor come across any code that used it (hexadecimal and bit twiddling notwithstanding). I started programming in C/C++ about 1994 so maybe I'm too young for this? Does older code use octal? C includes support for these by prepending a 0, but where is the code that uses these base 8 number literals? | I recently had to write network protocol code that accesses 3-bit fields. Octal comes in handy when you want to debug that. Just for effect, can you tell me what the 3-bit fields of this are? 0x492492 On the other hand, this same number in octal: 022222222 Now, finally, in binary (in groups of 3): 010 010 010 010 010 010 010 010 | {
"score": 7,
"source": [
"https://Stackoverflow.com/questions/44569",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2543/"
]
} |
44,588 | My current place of employment is currently in a transition, new ownership has taken over, things are finally getting standardized and proper guidelines are being enforced. But we are still using VSS, there really isn't any reason for using it other then that's what whats initially setup. We don't use Visual Studio, or any tool really that specifically requires it. What would be the absolute best argument I can bring up to help convince them that going to something like Subversion would be a much better solution, in the long run. | VSS totally relies on the clients to manage the database. If a client drops connection in the middle of a write over the network at just the wrong time, your file is trashed on the server. Not just the tip, but all the history. Hope you have a good backup. I've been through it. It's bad news. VSS usage over VPN or other remote connections is abysmal. It's using SMB to transfer the data, and you have to retrieve the file and all of its deltas just to get the tip. Nasty. I've seen VSS start to act up at 1GB of data. Database errors, etc. MS (somewhere in a FAQ or KB) says that 2GB is really the max safe limit. There are no good management tools (the clients run the asylum), so you don't really get any warning about this. Anything with a server process to provide some level of transactions and integrity control is a superior solution. | {
"score": 5,
"source": [
"https://Stackoverflow.com/questions/44588",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/567/"
]
} |
44,601 | I have just got a MacBook Pro and have been using it (+Fusion) to develop on for about a month now. The purpose of this question is similar to Hidden Features of C# ; to become a how-to of tips and trick for windows development on a mac. I should clarify that I am aware of boot camp but do not use it (nor do I have any interest to), hence my use of steady state to make sure nothing happens to my OS partition without my knowledge. However; as Sara pointed out, Apple makes great hardware and I absolutely LOVE the form factor of my MBP so for someone who is looking for a windows only laptop a mac with boot camp should not be overlooked as the hardware is amazing. My environment is as follows * MacBook Pro 15" 2.4Ghz 2GB RAM (Going to upgrade to 4GB soon) * VMWare Fusion 2.0 Beta * Windows XP Pro SP3 (Slipstreamed BEFORE install) Tips: * Use Windows Steady State to keep OS consistent * Use svn+ssh to connect to the mac for small repositories then use time machine to backup. * Use spaces. | @Andrew - I'm exactly in your situation. I use a MBP while my company work is purely Microsoft based: i.e., .NET, COM etc. While nothing can beat running Vista natively in Boot Camp (I've never seen Vista run so fast), the niceties of having your Mac OS be the "main" OS, for internet, mail etc. has gotten me to the following configuration. Works like a charm: Hardware Load up your MBP with the max possible - 4GB. It's really worth every $. Upgrade your hard drive (if not already) to 7200RPM. Major performance boost here. Software Parallels Desktop for Mac for virtualization. You can either have multiple VM, or use a boot camp partition. The latter is supposed to be faster, but I haven't really measured it (I use it for having the option to boot natively if I really need speed). The former allows you to have multiple OS. I gave my VM 1GB memory. I can do more if you want it more snappy. Micorsoft Visual Studio 2005/8 for .NET and C++. I have yet to see any IDE for .NET which beats this one. The intellisense is really amazing. Code Gear (yes we have some Delphi) For non development occasional need I also keep Microsoft Office 2007 installed. They do have MAC ports, but those don't always cut it. | {
"score": 5,
"source": [
"https://Stackoverflow.com/questions/44601",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3683/"
]
} |
44,637 | I recently downloaded ndepend and ran an analysis on an open source project I participate in. I did not now where to look next - a bit of visual and information overload and it turned out I don't even know where to start. Can anyone suggest starting points? What information should I look for first? What points out problems in the code (in a BIG way)? What would the low hanging fruit that can immediately seen? | Scott Hanselman / Stuart Celarier / Patrick Cauldwell's poster with ndepend metrics has some useful information on it. Rather than trying to break down all the heuristics being used I'd focus on only a few at a time starting with "zone of pain / zone of uselessness" and cyclomatic complexity. There is also a podcast which covers some of the basics of the tool. Between that and running nDepend on a few different projects you may be able to start gathering useful data that you can make into insights. | {
"score": 5,
"source": [
"https://Stackoverflow.com/questions/44637",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1583/"
]
} |
44,713 | How can I create an empty one-dimensional string array? | Dim strEmpty(-1) As String | {
"score": 6,
"source": [
"https://Stackoverflow.com/questions/44713",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3821/"
]
} |
44,715 | Ruby setters—whether created by (c)attr_accessor or manually—seem to be the only methods that need self. qualification when accessed within the class itself. This seems to put Ruby alone the world of languages: All methods need self / this (like Perl, and I think Javascript) No methods require self / this is (C#, Java) Only setters need self / this (Ruby?) The best comparison is C# vs Ruby, because both languages support accessor methods which work syntactically just like class instance variables: foo.x = y , y = foo.x . C# calls them properties. Here's a simple example; the same program in Ruby then C#: class A def qwerty; @q; end # manual getter def qwerty=(value); @q = value; end # manual setter, but attr_accessor is same def asdf; self.qwerty = 4; end # "self." is necessary in ruby? def xxx; asdf; end # we can invoke nonsetters w/o "self." def dump; puts "qwerty = #{qwerty}"; endenda = A.newa.xxxa.dump take away the self.qwerty =() and it fails (Ruby 1.8.6 on Linux & OS X). Now C#: using System;public class A { public A() {} int q; public int qwerty { get { return q; } set { q = value; } } public void asdf() { qwerty = 4; } // C# setters work w/o "this." public void xxx() { asdf(); } // are just like other methods public void dump() { Console.WriteLine("qwerty = {0}", qwerty); }}public class Test { public static void Main() { A a = new A(); a.xxx(); a.dump(); }} Question: Is this true? Are there other occasions besides setters where self is necessary? I.e., are there other occasions where a Ruby method cannot be invoked without self? There are certainly lots of cases where self becomes necessary. This is not unique to Ruby, just to be clear: using System;public class A { public A() {} public int test { get { return 4; }} public int useVariable() { int test = 5; return test; } public int useMethod() { int test = 5; return this.test; }}public class Test { public static void Main() { A a = new A(); Console.WriteLine("{0}", a.useVariable()); // prints 5 Console.WriteLine("{0}", a.useMethod()); // prints 4 }} Same ambiguity is resolved in same way. But while subtle I'm asking about the case where A method has been defined, and No local variable has been defined, and we encounter qwerty = 4 which is ambiguous—is this a method invocation or an new local variable assignment? @Mike Stone Hi! I understand and appreciate the points you've made and your example was great. Believe me when I say, if I had enough reputation,I'd vote up your response. Yet we still disagree: on a matter of semantics, and on a central point of fact First I claim, not without irony, we're having a semantic debate about the meaning of 'ambiguity'. When it comes to parsing and programming language semantics (the subject of this question), surely you would admit a broad spectrum of the notion 'ambiguity'. Let's just adopt some random notation: ambiguous: lexical ambiguity (lex must 'look ahead') Ambiguous: grammatical ambiguity (yacc must defer to parse-tree analysis) AMBIGUOUS: ambiguity knowing everything at the moment of execution (and there's junk between 2-3 too). All these categories are resolved by gathering more contextual info, looking more and more globally. So when you say, "qwerty = 4" is UNAMBIGUOUS in C# when there is no variable defined... I couldn't agree more. But by the same token, I'm saying "qwerty = 4" is un-Ambiguous in ruby (as it now exists) "qwerty = 4" is Ambiguous in C# And we're not yet contradicting each other. Finally, here's where we really disagree: Either ruby could or could not be implemented without any further language constructs such that, For "qwerty = 4," ruby UNAMBIGUOUSLY invokes an existing setter if there is no local variable defined You say no. I say yes; another ruby could exist which behaves exactly like the current in every respect, except "qwerty = 4" defines a new variable when no setter and no local exists, it invokes the setter if one exists, and it assigns to the local if one exists. I fully accept that I could be wrong. In fact, a reason why I might be wrong would be interesting. Let me explain. Imagine you are writing a new OO language with accessor methods lookinglike instances vars (like ruby & C#). You'd probably start with conceptual grammars something like: var = expr // assignment method = expr // setter method invocation But the parser-compiler (not even the runtime) will puke, because even afterall the input is grokked there's no way to know which grammar is pertinent.You're faced which a classic choice. I can't be sure of the details, butbasically ruby does this: var = expr // assignment (new or existing) // method = expr, disallow setter method invocation without . that is why it's un-Ambiguous, while and C# does this: symbol = expr // push 'symbol=' onto parse tree and decide later // if local variable is def'd somewhere in scope: assignment // else if a setter is def'd in scope: invocation For C#, 'later' is still at compile time. I'm sure ruby could do the same, but 'later' would have to be at runtime, because as ben points out you don't know until the statement is executed which case applies. My question was never intended to mean "do I really need the 'self.'?" or "what potential ambiguity is being avoided?" Rather I wanted to know why was thisparticular choice made? Maybe it's not performance. Maybe it just got the jobdone, or it was considered best to always allow a 1-liner local to override a method (a pretty rare case requirement) ... But I'm sort of suggesting that the most dynamical language might be the one whichpostpones this decision the longest, and chooses semantics based on the most contextual info: so if you have no local and you defined a setter, it would use the setter. Isn't this why we like ruby, smalltalk, objc, because method invocation is decided at runtime,offering maximum expressiveness? | Well, I think the reason this is the case is because qwerty = 4 is ambiguous—are you defining a new variable called qwerty or calling the setter? Ruby resolves this ambiguity by saying it will create a new variable, thus the self. is required. Here is another case where you need self. : class A def test 4 end def use_variable test = 5 test end def use_method test = 5 self.test endenda = A.newa.use_variable # returns 5a.use_method # returns 4 As you can see, the access to test is ambiguous, so the self. is required. Also, this is why the C# example is actually not a good comparison, because you define variables in a way that is unambiguous from using the setter. If you had defined a variable in C# that was the same name as the accessor, you would need to qualify calls to the accessor with this. , just like the Ruby case. | {
"score": 6,
"source": [
"https://Stackoverflow.com/questions/44715",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4615/"
]
} |
44,721 | I have downloaded a font that looks less than desirable if it is not anti-aliased. I can not figure out how to enable anti-aliasing in VS, I have changed the 'Smooth Edges of Screen Fonts' in the system performance options but that does not seem to help. VS2008 on XP SP3. What am I missing? | Try using ClearType, not Standard font smoothing. It's in Display properties, Appearance, Effects. | {
"score": 6,
"source": [
"https://Stackoverflow.com/questions/44721",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3683/"
]
} |
44,737 | Is there a plugin for targetting .NET 1.1 with VS 2008? | Try using ClearType, not Standard font smoothing. It's in Display properties, Appearance, Effects. | {
"score": 6,
"source": [
"https://Stackoverflow.com/questions/44737",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1782/"
]
} |
44,760 | What actually happens to the file system when you do a Subclipse Share Project on an Eclipse project that was externally checked out from Subversion? All the .svn folders are already in place. I get an error when I try to Share Project the right way, and I'd rather not delete and re-checkout the projects from the SVN Repository browser. | Dunno exactly what happens within eclipse, I presume it does some funky stuff in the .metadata directory of the workspace. That said, I would recommend the following to get eclipse to learn about the svn settings of the project: Delete the project from the workspace (keep "Delete project contents on disk" unchecked) File > Import... > General > Existing Projects into Workspace Browse to the folder containing the original project(s) of interest Import the projects into your workspace This seems to have the side effect of subclipse noticing the subversion settings when importing the "new" projects into your workspace. | {
"score": 5,
"source": [
"https://Stackoverflow.com/questions/44760",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4223/"
]
} |
44,777 | I'm sending mail from my C# Application, using the SmtpClient. Works great, but I have to decide if I want to send the mail as Plain Text or HTML. I wonder, is there a way to send both? I think that's called multipart. I googled a bit, but most examples essentially did not use SmtpClient but composed the whole SMTP-Body themselves, which is a bit "scary", so I wonder if something is built in the .net Framework 3.0? If not, is there any really well used/robust Third Party Library for sending e-Mails? | What you want to do is use the AlternateViews property on the MailMessage http://msdn.microsoft.com/en-us/library/system.net.mail.mailmessage.alternateviews.aspx | {
"score": 7,
"source": [
"https://Stackoverflow.com/questions/44777",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/91/"
]
} |
44,778 | What would be your preferred way to concatenate strings from a sequence such that between every two consecutive pairs a comma is added. That is, how do you map, for instance, ['a', 'b', 'c'] to 'a,b,c' ? (The cases ['s'] and [] should be mapped to 's' and '' , respectively.) I usually end up using something like ''.join(map(lambda x: x+',',l))[:-1] , but also feeling somewhat unsatisfied. | my_list = ['a', 'b', 'c', 'd']my_string = ','.join(my_list) 'a,b,c,d' This won't work if the list contains integers And if the list contains non-string types (such as integers, floats, bools, None) then do: my_string = ','.join(map(str, my_list)) | {
"score": 11,
"source": [
"https://Stackoverflow.com/questions/44778",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4285/"
]
} |
44,834 | I see __all__ in __init__.py files. What does it do? | It's a list of public objects of that module, as interpreted by import * . It overrides the default of hiding everything that begins with an underscore. | {
"score": 11,
"source": [
"https://Stackoverflow.com/questions/44834",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1794/"
]
} |
44,853 | I'm using ant to generate javadocs, but get this exception over and over - why? I'm using JDK version 1.6.0_06 . [javadoc] java.lang.ClassCastException: com.sun.tools.javadoc.ClassDocImpl cannot be cast to com.sun.javadoc.AnnotationTypeDoc [javadoc] at com.sun.tools.javadoc.AnnotationDescImpl.annotationType(AnnotationDescImpl.java:46) [javadoc] at com.sun.tools.doclets.formats.html.HtmlDocletWriter.getAnnotations(HtmlDocletWriter.java:1739) [javadoc] at com.sun.tools.doclets.formats.html.HtmlDocletWriter.writeAnnotationInfo(HtmlDocletWriter.java:1713) [javadoc] at com.sun.tools.doclets.formats.html.HtmlDocletWriter.writeAnnotationInfo(HtmlDocletWriter.java:1702) [javadoc] at com.sun.tools.doclets.formats.html.HtmlDocletWriter.writeAnnotationInfo(HtmlDocletWriter.java:1681) [javadoc] at com.sun.tools.doclets.formats.html.FieldWriterImpl.writeSignature(FieldWriterImpl.java:130) [javadoc] at com.sun.tools.doclets.internal.toolkit.builders.FieldBuilder.buildSignature(FieldBuilder.java:184) [javadoc] at sun.reflect.GeneratedMethodAccessor8.invoke(Unknown Source) [javadoc] at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25) [javadoc] at java.lang.reflect.Method.invoke(Method.java:597) [javadoc] at com.sun.tools.doclets.internal.toolkit.builders.FieldBuilder.invokeMethod(FieldBuilder.java:114) [javadoc] at com.sun.tools.doclets.internal.toolkit.builders.AbstractBuilder.build(AbstractBuilder.java:90) [javadoc] at com.sun.tools.doclets.internal.toolkit.builders.AbstractMemberBuilder.build(AbstractMemberBuilder.java:56) [javadoc] at com.sun.tools.doclets.internal.toolkit.builders.FieldBuilder.buildFieldDoc(FieldBuilder.java:158) [javadoc] at sun.reflect.GeneratedMethodAccessor51.invoke(Unknown Source) [javadoc] at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25) [javadoc] at java.lang.reflect.Method.invoke(Method.java:597) [javadoc] at com.sun.tools.doclets.internal.toolkit.builders.FieldBuilder.invokeMethod(FieldBuilder.java:114) [javadoc] at com.sun.tools.doclets.internal.toolkit.builders.AbstractBuilder.build(AbstractBuilder.java:90) [javadoc] at com.sun.tools.doclets.internal.toolkit.builders.AbstractMemberBuilder.build(AbstractMemberBuilder.java:56) [javadoc] at com.sun.tools.doclets.internal.toolkit.builders.ClassBuilder.buildFieldDetails(ClassBuilder.java:301) [javadoc] at sun.reflect.GeneratedMethodAccessor43.invoke(Unknown Source) [javadoc] at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25) [javadoc] at java.lang.reflect.Method.invoke(Method.java:597) [javadoc] at com.sun.tools.doclets.internal.toolkit.builders.ClassBuilder.invokeMethod(ClassBuilder.java:101) [javadoc] at com.sun.tools.doclets.internal.toolkit.builders.AbstractBuilder.build(AbstractBuilder.java:90) [javadoc] at com.sun.tools.doclets.internal.toolkit.builders.ClassBuilder.buildClassDoc(ClassBuilder.java:124) [javadoc] at sun.reflect.GeneratedMethodAccessor19.invoke(Unknown Source) [javadoc] at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25) [javadoc] at java.lang.reflect.Method.invoke(Method.java:597) [javadoc] at com.sun.tools.doclets.internal.toolkit.builders.ClassBuilder.invokeMethod(ClassBuilder.java:101) [javadoc] at com.sun.tools.doclets.internal.toolkit.builders.AbstractBuilder.build(AbstractBuilder.java:90) [javadoc] at com.sun.tools.doclets.internal.toolkit.builders.ClassBuilder.build(ClassBuilder.java:108) [javadoc] at com.sun.tools.doclets.formats.html.HtmlDoclet.generateClassFiles(HtmlDoclet.java:155) [javadoc] at com.sun.tools.doclets.internal.toolkit.AbstractDoclet.generateClassFiles(AbstractDoclet.java:164) [javadoc] at com.sun.tools.doclets.internal.toolkit.AbstractDoclet.startGeneration(AbstractDoclet.java:106) [javadoc] at com.sun.tools.doclets.internal.toolkit.AbstractDoclet.start(AbstractDoclet.java:64) [javadoc] at com.sun.tools.doclets.formats.html.HtmlDoclet.start(HtmlDoclet.java:42) [javadoc] at com.sun.tools.doclets.standard.Standard.start(Standard.java:23) [javadoc] at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) [javadoc] at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39) [javadoc] at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25) [javadoc] at java.lang.reflect.Method.invoke(Method.java:597) [javadoc] at com.sun.tools.javadoc.DocletInvoker.invoke(DocletInvoker.java:215) [javadoc] at com.sun.tools.javadoc.DocletInvoker.start(DocletInvoker.java:91) [javadoc] at com.sun.tools.javadoc.Start.parseAndExecute(Start.java:340) [javadoc] at com.sun.tools.javadoc.Start.begin(Start.java:128) [javadoc] at com.sun.tools.javadoc.Main.execute(Main.java:41) [javadoc] at com.sun.tools.javadoc.Main.main(Main.java:31) | It looks like this has been reported as a Java bug . It appears to be caused by using annotations from a 3rd party library (like JUnit) and not including the jar with that annotation in the javadoc invocation. If that is the case, just use the -classpath option on javadoc and include the extra jar files. | {
"score": 7,
"source": [
"https://Stackoverflow.com/questions/44853",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1310/"
]
} |
44,905 | When writing a switch statement, there appears to be two limitations on what you can switch on in case statements. For example (and yes, I know, if you're doing this sort of thing it probably means your object-oriented (OO) architecture is iffy - this is just a contrived example!), Type t = typeof(int); switch (t) { case typeof(int): Console.WriteLine("int!"); break; case typeof(string): Console.WriteLine("string!"); break; default: Console.WriteLine("unknown!"); break; } Here the switch() statement fails with 'A value of an integral type expected' and the case statements fail with 'A constant value is expected'. Why are these restrictions in place, and what is the underlying justification? I don't see any reason why the switch statement has to succumb to static analysis only, and why the value being switched on has to be integral (that is, primitive). What is the justification? | This is my original post, which sparked some debate... because it is wrong : The switch statement is not the same thing as a big if-else statement. Each case must be unique and evaluated statically. The switch statement does a constant time branch regardless of how many cases you have. The if-else statement evaluates each condition until it finds one that is true. In fact, the C# switch statement is not always a constant time branch. In some cases the compiler will use a CIL switch statement which is indeed a constant time branch using a jump table. However, in sparse cases as pointed out by Ivan Hamilton the compiler may generate something else entirely. This is actually quite easy to verify by writing various C# switch statements, some sparse, some dense, and looking at the resulting CIL with the ildasm.exe tool. | {
"score": 8,
"source": [
"https://Stackoverflow.com/questions/44905",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3394/"
]
} |
44,912 | Does the Java language have delegate features, similar to how C# has support for delegates? | Not really, no. You may be able to achieve the same effect by using reflection to get Method objects you can then invoke, and the other way is to create an interface with a single 'invoke' or 'execute' method, and then instantiate them to call the method your interested in (i.e. using an anonymous inner class). You might also find this article interesting / useful : A Java Programmer Looks at C# Delegates (@blueskyprojects.com) | {
"score": 8,
"source": [
"https://Stackoverflow.com/questions/44912",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3498/"
]
} |
44,917 | Is there any efficiency difference in an explicit vs implicit inner join?For example: SELECT * FROMtable a INNER JOIN table bON a.id = b.id; vs. SELECT a.*, b.*FROM table a, table bWHERE a.id = b.id; | Performance wise, they are exactly the same (at least in SQL Server). PS: Be aware that the IMPLICIT OUTER JOIN syntax is deprecated since SQL Server 2005. (The IMPLICIT INNER JOIN syntax as used in the question is still supported) Deprecation of "Old Style" JOIN Syntax: Only A Partial Thing | {
"score": 8,
"source": [
"https://Stackoverflow.com/questions/44917",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4316/"
]
} |
44,937 | I want to make an etag that matches what Apache produces. How does apache create it's etags? | Apache uses the standard format of inode-filesize-mtime. The only caveat to this is that the mtime must be epoch time and padded with zeros so it is 16 digits. Here is how to do it in PHP: $fs = stat($file);header("Etag: ".sprintf('"%x-%x-%s"', $fs['ino'], $fs['size'],base_convert(str_pad($fs['mtime'],16,"0"),10,16))); | {
"score": 5,
"source": [
"https://Stackoverflow.com/questions/44937",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/497/"
]
} |
44,940 | Does anybody know any good resources for learning how to program CIL with in-depth descriptions of commands, etc.? I have looked around but not found anything particularly good. | The only CIL book on my shelf is Expert .NET 2.0 IL Assembler by Serge Lidin. In terms of what the individual opcodes do or mean, the Microsoft documentation on System.Reflection.Emit has some pretty good information. And it's always useful to look at existing IL with Reflector . Edit: CIL (and indeed the CLR in general) has not changed at all between .NET 2.0 and .NET 3.5 -- the underlying runtime is basically the same, modulo fixes and performance improvements. So there's nothing newer available on a CIL level than what would be in a book on 2.0 | {
"score": 5,
"source": [
"https://Stackoverflow.com/questions/44940",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3394/"
]
} |
44,942 | Can you cast a List<int> to List<string> somehow? I know I could loop through and .ToString() the thing, but a cast would be awesome. I'm in C# 2.0 (so no LINQ ). | .NET 2.0 has the ConvertAll method where you can pass in a converter function: List<int> l1 = new List<int>(new int[] { 1, 2, 3 } );List<string> l2 = l1.ConvertAll<string>(delegate(int i) { return i.ToString(); }); | {
"score": 8,
"source": [
"https://Stackoverflow.com/questions/44942",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/493/"
]
} |
44,961 | I've searched on the Internet for comparisons between F# and Haskell but haven't found anything really definitive. What are the primary differences and why would I want to choose one over the other? | Haskell is a "pure" functional language, where as F# has aspects of both imperative/OO and functional languages. Haskell also has lazy evaluation, which is fairly rare amongst functional languages. What do these things mean? A pure functional language, means there are no side effects (or changes in shared state, when a function is called) which means that you are guaranteed that if you call f(x), nothing else happens besides returning a value from the function, such as console output, database output, changes to global or static variables.. and although Haskell can have non pure functions (through monads), it must be 'explicitly' implied through declaration. Pure functional languages and 'No side effect' programming has gained popularity recently as it lends itself well to multi core concurrency, as it is much harder to get wrong with no shared state, rather than myriad locks & semaphores. Lazy evaluation is where a function is NOT evaluated until it is absolutely necessary required. meaning that many operation can be avoided when not necessary. Think of this in a basic C# if clause such as this: if(IsSomethingTrue() && AnotherThingTrue()){ do something;} If IsSomethingTrue() is false then AnotherThingTrue() method is never evaluated. While Haskell is an amazing language, the major benefit of F# (for the time being), is that it sits on top of the CLR. This lends it self to polyglot programming. One day, you may write your web UI in ASP.net MVC, your business logic in C#, your core algorithms in F# and your unit tests in Ironruby.... All amongst the the .Net framework. Listen to the Software Engineering radio with Simon Peyton Jones for more info on Haskell: Episode 108: Simon Peyton Jones on Functional Programming and Haskell | {
"score": 8,
"source": [
"https://Stackoverflow.com/questions/44961",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3394/"
]
} |
44,965 | Having briefly looked at Haskell recently, what would be a brief, succinct, practical explanation as to what a monad essentially is? I have found most explanations I've come across to be fairly inaccessible and lacking in practical detail. | First: The term monad is a bit vacuous if you are not a mathematician. An alternative term is computation builder which is a bit more descriptive of what they are actually useful for. They are a pattern for chaining operations. It looks a bit like method chaining in object-oriented languages, but the mechanism is slightly different. The pattern is mostly used in functional languages (especially Haskell which uses monads pervasively) but can be used in any language which support higher-order functions (that is, functions which can take other functions as arguments). Arrays in JavaScript support the pattern, so let’s use that as the first example. The gist of the pattern is we have a type ( Array in this case) which has a method which takes a function as argument. The operation supplied must return an instance of the same type (i.e. return an Array ). First an example of method chaining which does not use the monad pattern: [1,2,3].map(x => x + 1) The result is [2,3,4] . The code does not conform to the monad pattern, since the function we are supplying as an argument returns a number, not an Array. The same logic in monad form would be: [1,2,3].flatMap(x => [x + 1]) Here we supply an operation which returns an Array , so now it conforms to the pattern. The flatMap method executes the provided function for every element in the array. It expects an array as result for each invocation (rather than single values), but merges the resulting set of arrays into a single array. So the end result is the same, the array [2,3,4] . (The function argument provided to a method like map or flatMap is often called a "callback" in JavaScript. I will call it the "operation" since it is more general.) If we chain multiple operations (in the traditional way): [1,2,3].map(a => a + 1).filter(b => b != 3) Results in the array [2,4] The same chaining in monad form: [1,2,3].flatMap(a => [a + 1]).flatMap(b => b != 3 ? [b] : []) Yields the same result, the array [2,4] . You will immediately notice that the monad form is quite a bit uglier than the non-monad! This just goes to show that monads are not necessarily “good”. They are a pattern which is sometimes beneficial and sometimes not. Do note that the monad pattern can be combined in a different way: [1,2,3].flatMap(a => [a + 1].flatMap(b => b != 3 ? [b] : [])) Here the binding is nested rather than chained, but the result is the same. This is an important property of monads as we will see later. It means two operations combined can be treated the same as a single operation. The operation is allowed to return an array with different element types, for example transforming an array of numbers into an array of strings or something else; as long as it still an Array. This can be described a bit more formally using Typescript notation. An array has the type Array<T> , where T is the type of the elements in the array. The method flatMap() takes a function argument of the type T => Array<U> and returns an Array<U> . Generalized, a monad is any type Foo<Bar> which has a "bind" method which takes a function argument of type Bar => Foo<Baz> and returns a Foo<Baz> . This answers what monads are. The rest of this answer will try to explain through examples why monads can be a useful pattern in a language like Haskell which has good support for them. Haskell and Do-notation To translate the map/filter example directly to Haskell, we replace flatMap with the >>= operator: [1,2,3] >>= \a -> [a+1] >>= \b -> if b == 3 then [] else [b] The >>= operator is the bind function in Haskell. It does the same as flatMap in JavaScript when the operand is a list, but it is overloaded with different meaning for other types. But Haskell also has a dedicated syntax for monad expressions, the do -block, which hides the bind operator altogether: do a <- [1,2,3] b <- [a+1] if b == 3 then [] else [b] This hides the "plumbing" and lets you focus on the actual operations applied at each step. In a do -block, each line is an operation. The constraint still holds that all operations in the block must return the same type. Since the first expression is a list, the other operations must also return a list. The back-arrow <- looks deceptively like an assignment, but note that this is the parameter passed in the bind. So, when the expression on the right side is a List of Integers, the variable on the left side will be a single Integer – but will be executed for each integer in the list. Example: Safe navigation (the Maybe type) Enough about lists, lets see how the monad pattern can be useful for other types. Some functions may not always return a valid value. In Haskell this is represented by the Maybe -type, which is an option that is either Just value or Nothing . Chaining operations which always return a valid value is of course straightforward: streetName = getStreetName (getAddress (getUser 17)) But what if any of the functions could return Nothing ? We need to check each result individually and only pass the value to the next function if it is not Nothing : case getUser 17 of Nothing -> Nothing Just user -> case getAddress user of Nothing -> Nothing Just address -> getStreetName address Quite a lot of repetitive checks! Imagine if the chain was longer. Haskell solves this with the monad pattern for Maybe : do user <- getUser 17 addr <- getAddress user getStreetName addr This do -block invokes the bind-function for the Maybe type (since the result of the first expression is a Maybe ). The bind-function only executes the following operation if the value is Just value , otherwise it just passes the Nothing along. Here the monad-pattern is used to avoid repetitive code. This is similar to how some other languages use macros to simplify syntax, although macros achieve the same goal in a very different way. Note that it is the combination of the monad pattern and the monad-friendly syntax in Haskell which result in the cleaner code. In a language like JavaScript without any special syntax support for monads, I doubt the monad pattern would be able to simplify the code in this case. Mutable state Haskell does not support mutable state. All variables are constants and all values immutable. But the State type can be used to emulate programming with mutable state: add2 :: State Integer Integeradd2 = do -- add 1 to state x <- get put (x + 1) -- increment in another way modify (+1) -- return state getevalState add2 7=> 9 The add2 function builds a monad chain which is then evaluated with 7 as the initial state. Obviously this is something which only makes sense in Haskell. Other languages support mutable state out of the box. Haskell is generally "opt-in" on language features - you enable mutable state when you need it, and the type system ensures the effect is explicit. IO is another example of this. IO The IO type is used for chaining and executing “impure” functions. Like any other practical language, Haskell has a bunch of built-in functions which interface with the outside world: putStrLine , readLine and so on. These functions are called “impure” because they either cause side effects or have non-deterministic results. Even something simple like getting the time is considered impure because the result is non-deterministic – calling it twice with the same arguments may return different values. A pure function is deterministic – its result depends purely on the arguments passed and it has no side effects on the environment beside returning a value. Haskell heavily encourages the use of pure functions – this is a major selling point of the language. Unfortunately for purists, you need some impure functions to do anything useful. The Haskell compromise is to cleanly separate pure and impure, and guarantee that there is no way that pure functions can execute impure functions, directly or indirect. This is guaranteed by giving all impure functions the IO type. The entry point in Haskell program is the main function which have the IO type, so we can execute impure functions at the top level. But how does the language prevent pure functions from executing impure functions? This is due to the lazy nature of Haskell. A function is only executed if its output is consumed by some other function. But there is no way to consume an IO value except to assign it to main . So if a function wants to execute an impure function, it has to be connected to main and have the IO type. Using monad chaining for IO operations also ensures that they are executed in a linear and predictable order, just like statements in an imperative language. This brings us to the first program most people will write in Haskell: main :: IO ()main = do putStrLn ”Hello World” The do keyword is superfluous when there is only a single operation and therefore nothing to bind, but I keep it anyway for consistency. The () type means “void”. This special return type is only useful for IO functions called for their side effect. A longer example: main = do putStrLn "What is your name?" name <- getLine putStrLn "hello" ++ name This builds a chain of IO operations, and since they are assigned to the main function, they get executed. Comparing IO with Maybe shows the versatility of the monad pattern. For Maybe , the pattern is used to avoid repetitive code by moving conditional logic to the binding function. For IO , the pattern is used to ensure that all operations of the IO type are sequenced and that IO operations cannot "leak" to pure functions. Summing up In my subjective opinion, the monad pattern is only really worthwhile in a language which has some built-in support for the pattern. Otherwise it just leads to overly convoluted code. But Haskell (and some other languages) have some built-in support which hides the tedious parts, and then the pattern can be used for a variety of useful things. Like: Avoiding repetitive code ( Maybe ) Adding language features like mutable state or exceptions for delimited areas of the program. Isolating icky stuff from nice stuff ( IO ) Embedded domain-specific languages ( Parser ) Adding GOTO to the language. | {
"score": 10,
"source": [
"https://Stackoverflow.com/questions/44965",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3394/"
]
} |
44,980 | How can one determine, in code, how long the machine is locked? Other ideas outside of C# are also welcome. I like the windows service idea (and have accepted it) for simplicity and cleanliness, but unfortunately I don't think it will work for me in this particular case. I wanted to run this on my workstation at work rather than home (or in addition to home, I suppose), but it's locked down pretty hard courtesy of the DoD. That's part of the reason I'm rolling my own, actually. I'll write it up anyway and see if it works. Thanks everyone! | I hadn't found this before, but from any application you can hookup a SessionSwitchEventHandler. Obviously your application will need to be running, but so long as it is: Microsoft.Win32.SystemEvents.SessionSwitch += new Microsoft.Win32.SessionSwitchEventHandler(SystemEvents_SessionSwitch);void SystemEvents_SessionSwitch(object sender, Microsoft.Win32.SessionSwitchEventArgs e){ if (e.Reason == SessionSwitchReason.SessionLock) { //I left my desk } else if (e.Reason == SessionSwitchReason.SessionUnlock) { //I returned to my desk }} | {
"score": 8,
"source": [
"https://Stackoverflow.com/questions/44980",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1588/"
]
} |
44,989 | I'm trying to get the following bit of code to work in LINQPad but am unable to index into a var. Anybody know how to index into a var in LINQ? string[] sa = {"one", "two", "three"};sa[1].Dump();var va = sa.Select( (a,i) => new {Line = a, Index = i});va[1].Dump();// Cannot apply indexing with [] to an expression of type 'System.Collections.Generic.IEnumerable<AnonymousType#1>' | As the comment says, you cannot apply indexing with [] to an expression of type System.Collections.Generic.IEnumerable<T> . The IEnumerable interface only supports the method GetEnumerator() . However with LINQ you can call the extension method ElementAt(int) . | {
"score": 5,
"source": [
"https://Stackoverflow.com/questions/44989",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1463/"
]
} |
45,004 | Is there a way to select a parent element based on the class of a child element in the class? The example that is relevant to me relating to HTML output by a nice menu plugin for http://drupal.org . The output renders like this: <ul class="menu"> <li> <a class="active">Active Page</a> </li> <li> <a>Some Other Page</a> </li> </ul> My question is whether or not it is possible to apply a style to the list item that contains the anchor with the active class on it. Obviously, I'd prefer that the list item be marked as active, but I don't have control of the code that gets produced. I could perform this sort of thing using javascript (JQuery springs to mind), but I was wondering if there is a way to do this using CSS selectors. Just to be clear, I want to apply a style to the list item, not the anchor. | Unfortunately, there's no way to do that with CSS. It's not very difficult with JavaScript though: // JavaScript code:document.getElementsByClassName("active")[0].parentNode;// jQuery code:$('.active').parent().get(0); // This would be the <a>'s parent <li>. | {
"score": 8,
"source": [
"https://Stackoverflow.com/questions/45004",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4640/"
]
} |
45,015 | Given a string of JSON data, how can I safely turn that string into a JavaScript object? Obviously I can do this unsafely with something like: var obj = eval("(" + json + ')'); but that leaves me vulnerable to the JSON string containing other code, which it seems very dangerous to simply eval. | JSON.parse(jsonString) is a pure JavaScript approach so long as you can guarantee a reasonably modern browser. | {
"score": 12,
"source": [
"https://Stackoverflow.com/questions/45015",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/797/"
]
} |
45,030 | I'm wanting to parse a string into a nullable int in C#. ie. I want to get back either the int value of the string or null if it can't be parsed. I was kind of hoping that this would work int? val = stringVal as int?; But that won't work, so the way I'm doing it now is I've written this extension method public static int? ParseNullableInt(this string value){ if (value == null || value.Trim() == string.Empty) { return null; } else { try { return int.Parse(value); } catch { return null; } }} Is there a better way of doing this? EDIT: Thanks for the TryParse suggestions, I did know about that, but it worked out about the same. I'm more interested in knowing if there is a built-in framework method that will parse directly into a nullable int? | int.TryParse is probably a tad easier: public static int? ToNullableInt(this string s){ int i; if (int.TryParse(s, out i)) return i; return null;} Edit @Glenn int.TryParse is "built into the framework". It and int.Parse are the way to parse strings to ints. | {
"score": 10,
"source": [
"https://Stackoverflow.com/questions/45030",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2975/"
]
} |
45,036 | The .NET IDisposable Pattern implies that if you write a finalizer, and implement IDisposable, that your finalizer needs to explicitly call Dispose.This is logical, and is what I've always done in the rare situations where a finalizer is warranted. However, what happens if I just do this: class Foo : IDisposable{ public void Dispose(){ CloseSomeHandle(); }} and don't implement a finalizer, or anything. Will the framework call the Dispose method for me? Yes I realise this sounds dumb, and all logic implies that it won't, but I've always had 2 things at the back of my head which have made me unsure. Someone a few years ago once told me that it would in fact do this, and that person had a very solid track record of "knowing their stuff." The compiler/framework does other 'magic' things depending on what interfaces you implement (eg: foreach, extension methods, serialization based on attributes, etc), so it makes sense that this might be 'magic' too. While I've read a lot of stuff about it, and there's been lots of things implied, I've never been able to find a definitive Yes or No answer to this question. | The .Net Garbage Collector calls the Object.Finalize method of an object on garbage collection. By default this does nothing and must be overidden if you want to free additional resources. Dispose is NOT automatically called and must be explicity called if resources are to be released, such as within a 'using' or 'try finally' block see http://msdn.microsoft.com/en-us/library/system.object.finalize.aspx for more information | {
"score": 8,
"source": [
"https://Stackoverflow.com/questions/45036",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/234/"
]
} |
45,045 | When executing SubmitChanges to the DataContext after updating a couple properties with a LINQ to SQL connection (against SQL Server Compact Edition) I get a "Row not found or changed." ChangeConflictException. var ctx = new Data.MobileServerDataDataContext(Common.DatabasePath);var deviceSessionRecord = ctx.Sessions.First(sess => sess.SessionRecId == args.DeviceSessionId);deviceSessionRecord.IsActive = false;deviceSessionRecord.Disconnected = DateTime.Now;ctx.SubmitChanges(); The query generates the following SQL: UPDATE [Sessions]SET [Is_Active] = @p0, [Disconnected] = @p1WHERE 0 = 1-- @p0: Input Boolean (Size = 0; Prec = 0; Scale = 0) [False]-- @p1: Input DateTime (Size = 0; Prec = 0; Scale = 0) [9/4/2008 5:12:02 PM]-- Context: SqlProvider(SqlCE) Model: AttributedMetaModel Build: 3.5.21022.8 The obvious problem is the WHERE 0=1 , After the record was loaded, I've confirmed that all the properties in the "deviceSessionRecord" are correct to include the primary key. Also when catching the "ChangeConflictException" there is no additional information about why this failed. I've also confirmed that this exception get's thrown with exactly one record in the database (the record I'm attempting to update) What's strange is that I have a very similar update statement in a different section of code and it generates the following SQL and does indeed update my SQL Server Compact Edition database. UPDATE [Sessions]SET [Is_Active] = @p4, [Disconnected] = @p5WHERE ([Session_RecId] = @p0) AND ([App_RecId] = @p1) AND ([Is_Active] = 1) AND ([Established] = @p2) AND ([Disconnected] IS NULL) AND ([Member_Id] IS NULL) AND ([Company_Id] IS NULL) AND ([Site] IS NULL) AND (NOT ([Is_Device] = 1)) AND ([Machine_Name] = @p3)-- @p0: Input Guid (Size = 0; Prec = 0; Scale = 0) [0fbbee53-cf4c-4643-9045-e0a284ad131b]-- @p1: Input Guid (Size = 0; Prec = 0; Scale = 0) [7a174954-dd18-406e-833d-8da650207d3d]-- @p2: Input DateTime (Size = 0; Prec = 0; Scale = 0) [9/4/2008 5:20:50 PM]-- @p3: Input String (Size = 0; Prec = 0; Scale = 0) [CWMOBILEDEV]-- @p4: Input Boolean (Size = 0; Prec = 0; Scale = 0) [False]-- @p5: Input DateTime (Size = 0; Prec = 0; Scale = 0) [9/4/2008 5:20:52 PM]-- Context: SqlProvider(SqlCE) Model: AttributedMetaModel Build: 3.5.21022.8 I have confirmed that the proper primary fields values have been identified in both the Database Schema and the DBML that generates the LINQ classes. I guess this is almost a two part question: Why is the exception being thrown? After reviewing the second set of generated SQL, it seems like for detecting conflicts it would be nice to check all the fields, but I imagine this would be fairly inefficient. Is this the way this always works? Is there a setting to just check the primary key? I've been fighting with this for the past two hours so any help would be appreciated. | Thats nasty, but simple: Check if the data types for all fields in the O/R-Designer match the data types in your SQL table. Double check for nullable! A column should be either nullable in both the O/R-Designer and SQL, or not nullable in both. For example, a NVARCHAR column "title" is marked as NULLable in your database, and contains the value NULL. Even though the column is marked as NOT NULLable in your O/R-Mapping, LINQ will load it successfully and set the column-String to null. Now you change something and callSubmitChanges(). LINQ will generate a SQL querycontaining "WHERE [title] IS NULL", to make sure the title has not been changed by someone else. LINQ looks up the properties of[title] in the mapping. LINQ will find [title] NOT NULLable. Since [title] is NOT NULLable, bylogic it never could be NULL! So, optimizing the query, LINQreplaces it with "where 0 = 1", theSQL equivalent of "never". The same symptom will appear when the data types of a field does not match the data type in SQL, or if fields are missing, since LINQ will not be able to make sure the SQL data has not changed since reading the data. | {
"score": 9,
"source": [
"https://Stackoverflow.com/questions/45045",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2723/"
]
} |
45,093 | Is there a Regular Expression that can detect SQL in a string? Does anyone have a sample of something that they have used before to share? | Don't do it. You're practically guaranteed to fail. Use PreparedStatement (or its equivalent) instead. | {
"score": 6,
"source": [
"https://Stackoverflow.com/questions/45093",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4541/"
]
} |
45,135 | Why does the order in which libraries are linked sometimes cause errors in GCC? | (See the history on this answer to get the more elaborate text, but I now think it's easier for the reader to see real command lines). Common files shared by all below commands // a depends on b, b depends on d$ cat a.cppextern int a;int main() { return a;}$ cat b.cppextern int b;int a = b;$ cat d.cppint b; Linking to static libraries $ g++ -c b.cpp -o b.o$ ar cr libb.a b.o$ g++ -c d.cpp -o d.o$ ar cr libd.a d.o$ g++ -L. -ld -lb a.cpp # wrong order$ g++ -L. -lb -ld a.cpp # wrong order$ g++ a.cpp -L. -ld -lb # wrong order$ g++ a.cpp -L. -lb -ld # right order The linker searches from left to right, and notes unresolved symbols as it goes. If a library resolves the symbol, it takes the object files of that library to resolve the symbol (b.o out of libb.a in this case). Dependencies of static libraries against each other work the same - the library that needs symbols must be first, then the library that resolves the symbol. If a static library depends on another library, but the other library again depends on the former library, there is a cycle. You can resolve this by enclosing the cyclically dependent libraries by -( and -) , such as -( -la -lb -) (you may need to escape the parens, such as -\( and -\) ). The linker then searches those enclosed lib multiple times to ensure cycling dependencies are resolved. Alternatively, you can specify the libraries multiple times, so each is before one another: -la -lb -la . Linking to dynamic libraries $ export LD_LIBRARY_PATH=. # not needed if libs go to /usr/lib etc$ g++ -fpic -shared d.cpp -o libd.so$ g++ -fpic -shared b.cpp -L. -ld -o libb.so # specifies its dependency!$ g++ -L. -lb a.cpp # wrong order (works on some distributions)$ g++ -Wl,--as-needed -L. -lb a.cpp # wrong order$ g++ -Wl,--as-needed a.cpp -L. -lb # right order It's the same here - the libraries must follow the object files of the program. The difference here compared with static libraries is that you need not care about the dependencies of the libraries against each other, because dynamic libraries sort out their dependencies themselves . Some recent distributions apparently default to using the --as-needed linker flag, which enforces that the program's object files come before the dynamic libraries. If that flag is passed, the linker will not link to libraries that are not actually needed by the executable (and it detects this from left to right). My recent archlinux distribution doesn't use this flag by default, so it didn't give an error for not following the correct order. It is not correct to omit the dependency of b.so against d.so when creating the former. You will be required to specify the library when linking a then, but a doesn't really need the integer b itself, so it should not be made to care about b 's own dependencies. Here is an example of the implications if you miss specifying the dependencies for libb.so $ export LD_LIBRARY_PATH=. # not needed if libs go to /usr/lib etc$ g++ -fpic -shared d.cpp -o libd.so$ g++ -fpic -shared b.cpp -o libb.so # wrong (but links)$ g++ -L. -lb a.cpp # wrong, as above$ g++ -Wl,--as-needed -L. -lb a.cpp # wrong, as above$ g++ a.cpp -L. -lb # wrong, missing libd.so$ g++ a.cpp -L. -ld -lb # wrong order (works on some distributions)$ g++ -Wl,--as-needed a.cpp -L. -ld -lb # wrong order (like static libs)$ g++ -Wl,--as-needed a.cpp -L. -lb -ld # "right" If you now look into what dependencies the binary has, you note the binary itself depends also on libd , not just libb as it should. The binary will need to be relinked if libb later depends on another library, if you do it this way. And if someone else loads libb using dlopen at runtime (think of loading plugins dynamically), the call will fail as well. So the "right" really should be a wrong as well. | {
"score": 9,
"source": [
"https://Stackoverflow.com/questions/45135",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1597/"
]
} |
45,179 | Having worked with Classic ASP for about 2 years now by creating a few 100 simple web forms I can't see a good reason for switching to .net; however, I'm not that versed in .net so I'm sure I could be missing a few things. Some points that I often hear around work can be found here: http://www.packtpub.com/article/Classic-ASP (not that I share all of these thoughts, but it's a good jumping off point) I'm very interested to hear what others have to say on this matter. | You're missing more than a few things! ASP.NET is orders of magnitudes more productive, robust, and maintainable than old-school ASP ever thought about being. Server side controls, third-party controls, master pages, forms authentication, forms validation, an OO model than encourages appropriate application partitioning, easy deployment, built-in debugging and tracing, state management. You even have the choice of WebForms or MVC. It's not an understatement to say that you are simply out of your mind if you don't thoroughly investigate what you're missing. | {
"score": 7,
"source": [
"https://Stackoverflow.com/questions/45179",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3349/"
]
} |
45,207 | Is there a way to always have LF line endings in Visual Studio? I can never seem to find it! | There'a an add-in for Visual Studio 2008 that converts the end of line format when a file is saved. You can download it here: http://grebulon.com/software/stripem.php | {
"score": 6,
"source": [
"https://Stackoverflow.com/questions/45207",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4121/"
]
} |
45,227 | I have been searching everywhere for the following functionality in Lisp, and have gotten nowhere: find the index of something in a list. example: (index-of item InThisList) replace something at a specific spot in a list. example: (replace item InThisList AtThisIndex) ;i think this can be done with 'setf'? return an item at a specific index. example: (return InThisList ItemAtThisIndex) Up until this point, I've been faking it with my own functions. I'm wondering if I'm just creating more work for myself. This is how I've been faking number 1: (defun my-index (findMe mylist) (let ((counter 0) (found 1)) (dolist (item mylist) (cond ((eq item findMe) ;this works because 'eq' checks place in memory, ;and as long as 'findMe' was from the original list, this will work. (setq found nil) (found (incf counter)))) counter)) | You can use setf and nth to replace and retrieve values by index. (let ((myList '(1 2 3 4 5 6))) (setf (nth 4 myList) 101); <---- myList)(1 2 3 4 101 6) To find by index you can use the position function . (let ((myList '(1 2 3 4 5 6))) (setf (nth 4 myList) 101) (list myList (position 101 myList)))((1 2 3 4 101 6) 4) I found these all in this index of functions . | {
"score": 6,
"source": [
"https://Stackoverflow.com/questions/45227",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/50/"
]
} |
45,228 | I've been unable to find a source for this information, short of looking through the Python source code myself to determine how the objects work. Does anyone know where I could find this online? | Checkout the TimeComplexity page on the py dot org wiki. It covers set/dicts/lists/etc at least as far as time complexity goes. | {
"score": 5,
"source": [
"https://Stackoverflow.com/questions/45228",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1114/"
]
} |
45,230 | I have a small local network. Only one of the machines is available to the outside world (this is not easily changeable). I'd like to be able to set it up such that ssh requests that don't come in on the standard port go to another machine. Is this possible? If so, how? Oh and all of these machines are running either Ubuntu or OS X. | Another way to go would be to use ssh tunneling (which happens on the client side). You'd do an ssh command like this: ssh -L 8022:myinsideserver:22 paul@myoutsideserver That connects you to the machine that's accessible from the outside (myoutsideserver) and creates a tunnel through that ssh connection to port 22 (the standard ssh port) on the server that's only accessible from the inside. Then you'd do another ssh command like this (leaving the first one still connected): ssh -p 8022 paul@localhost That connection to port 8022 on your localhost will then get tunneled through the first ssh connection taking you over myinsideserver. There may be something you have to do on myoutsideserver to allow forwarding of the ssh port. I'm double-checking that now. Edit Hmmm. The ssh manpage says this: **Only the superuser can forward privileged ports. ** That sort of implies to me that the first ssh connection has to be as root. Maybe somebody else can clarify that. It looks like superuser privileges aren't required as long as the forwarded port (in this case, 8022) isn't a privileged port (like 22). Thanks for the clarification Mike Stone . | {
"score": 5,
"source": [
"https://Stackoverflow.com/questions/45230",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/85/"
]
} |
45,239 | Short version: What is the cleanest and most maintainable technique for consistant presentation and AJAX function across all browsers used by both web developers and web developers' end-users? IE 6, 7, 8 Firefox 2, 3 Safari Google Chrome Opera Long version: I wrote a web app aimed at other web developers . I want my app to support the major web browsers (plus Google Chrome) in both presentation and AJAX behavior. I began on Firefox/Firebug, then added conditional comments for a consistent styling under IE 6 and 7. Next, to my amazement, I discovered that jQuery does not behave identically in IE; so I changed my Javascript to be portable on FF and IE using conditionals and less pure jQuery. Today, I started testing on Webkit and Google Chrome and discovered that, not only are the styles inconsistant with both FF and IE, but Javascript is not executing at all, probably due to a syntax or parse error. I expected some CSS work, but now I have more Javascript debugging to do! At this point, I want to step back and think before writing piles of special cases for all situations. I am not looking for a silver bullet, just best practices to keep things as understandable and maintainable as possible. I prefer if this works with no server-side intelligence; however if there is a advantage to, for example, check the user-agent and then return different files to different browsers, that is fine if the total comprehensibility and maintainability of the web app is lower. Thank you all very much! | I am in a similar situation, working on a web app that is targeted at IT professionals, and required to support the same set of browsers, minus Opera. Some general things I've learned so far: Test often, in as many of your target browsers as you can. Make sure you have time for this in your development schedule. Toolkits can get you part of the way to cross-browser support, but will eventually miss something on some browser. Plan some time for debugging and researching fixes for specific browsers. If you need something that's not in a toolkit and can't find a free code snippet, invest some time to write utility functions that encapsulate the browser-dependent behavior. Educate yourself about known browser bugs, so that you can steer your implementation around them. A few more-specific things I've learned: Use conditional code based on the user-agent only as a last resort, because different generations of the "same" browser may have different features. Instead, test for standards-compliant behavior first — e.g., if(node.addEventListener)... , then common non-standard functions — e.g., if(window.attachEvent)... , and then, if you must, look at the user-agent for a specific browser type & version number. Knowing when the DOM is 'ready' for script access is different in just about every browser. A good toolkit will abstract this for you. Event handlers are different in just about every browser. A good toolkit will abstract this for you. Creating DOM elements, particularly form controls or elements with attributes, can be tricky with document.createElement and element.setAttribute. While not standard (and kinda yucky), using node.innerHTML with strings that contain bits of HTML seems to be more reliable across browser types. I have yet to find a toolkit that will let you use element.setAttribute to add a 'name' to a form element in IE. CSS differences (and bugs) are just as important as JS differences. The 'core' Javascript features (String, Date, RegExp, Array functions) seem to be pretty reliable and consistent across browsers, especially relative to the DOM/CSS/Window functions. There's some small joy in the fact that the language isn't entirely different on every platform. :-) I haven't really run into any Chrome-specific JS bugs, but it's always one of the first browsers I test. HTH | {
"score": 5,
"source": [
"https://Stackoverflow.com/questions/45239",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2938/"
]
} |
45,264 | Does anyone know of any existing packages or libraries that can be used to build a calendar in a django app? | A quick google search reveals django-gencal , which looks like exactly what you need. It would also be worth looking at the snippets under the calendar tag on Django Snippets at http://www.djangosnippets.org/tags/calendar/ . | {
"score": 5,
"source": [
"https://Stackoverflow.com/questions/45264",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1934/"
]
} |
45,325 | Sometimes when I'm editing page or control the .designer files stop being updated with the new controls I'm putting on the page. I'm not sure what's causing this to happen, but I'm wondering if there's any way of forcing Visual Studio to regenerate the .designer file. I'm using Visual Studio 2008 EDIT: Sorry I should have noted I've already tried: Closing & re-opening all the files & Visual Studio Making a change to a runat="server" control on the page Deleting & re-adding the page directive | If you open the .aspx file and switch between design view and html view and back it will prompt VS to check the controls and add any that are missing to the designer file. In VS2013-15 there is a Convert to Web Application command under the Project menu. Prior to VS2013 this option was available in the right-click context menu for as(c/p)x files. When this is done you should see that you now have a *.Designer.cs file available and your controls within the Design HTML will be available for your control. PS: This should not be done in debug mode, as not everything is "recompiled" when debugging. Some people have also reported success by (making a backup copy of your .designer.cs file and then) deleting the .designer.cs file. Re-create an empty file with the same name. There are many comments to this answer that add tips on how best to re-create the designer.cs file. | {
"score": 10,
"source": [
"https://Stackoverflow.com/questions/45325",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2975/"
]
} |
45,340 | Python frameworks always provide ways to handle URLs that convey the data of the request in an elegant way, like for example http://somewhere.overtherainbow.com/userid/123424/ I want you to notice the ending path /userid/123424/ How do you do this in ASP.NET? | This example uses ASP.NET Routing to implement friendly URLs. Examples of the mappings that the application handles are: http://samplesite/userid/1234 - http://samplesite/users.aspx?userid=1234 http://samplesite/userid/1235 - http://samplesite/users.aspx?userid=1235 This example uses querystrings and avoids any requirement to modify the code on the aspx page. Step 1 - add the necessary entries to web.config <system.web><compilation debug="true"> <assemblies> … <add assembly="System.Web.Routing, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35"/> </assemblies> </compilation>… <httpModules> … <add name="UrlRoutingModule" type="System.Web.Routing.UrlRoutingModule, System.Web.Routing, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" /> </httpModules></system.web><system.webServer> … <modules> … <add name="UrlRoutingModule" type="System.Web.Routing.UrlRoutingModule, System.Web.Routing, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35"/> </modules> <handlers… <add name="UrlRoutingHandler" preCondition="integratedMode" verb="*" path="UrlRouting.axd" type="System.Web.HttpForbiddenHandler, System.Web, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a"/> </handlers></system.webServer> Step 2 - add a routing table in global.asax Define the mapping from the friendly URL to the aspx page, saving the requested userid for later use. void Application_Start(object sender, EventArgs e){ RegisterRoutes(RouteTable.Routes);}public static void RegisterRoutes(RouteCollection routes){ routes.Add("UseridRoute", new Route ( "userid/{userid}", new CustomRouteHandler("~/users.aspx") ));} Step 3 - implement the route handler Add the querystring to the current context before the routing takes place. using System.Web.Compilation;using System.Web.UI;using System.Web;using System.Web.Routing;public class CustomRouteHandler : IRouteHandler{ public CustomRouteHandler(string virtualPath) { this.VirtualPath = virtualPath; } public string VirtualPath { get; private set; } public IHttpHandler GetHttpHandler(RequestContext requestContext) { // Add the querystring to the URL in the current context string queryString = "?userid=" + requestContext.RouteData.Values["userid"]; HttpContext.Current.RewritePath( string.Concat( VirtualPath, queryString)); var page = BuildManager.CreateInstanceFromVirtualPath (VirtualPath, typeof(Page)) as IHttpHandler; return page; }} Code from users.aspx The code on the aspx page for reference. protected void Page_Load(object sender, EventArgs e){ string id = Page.Request.QueryString["userid"]; switch (id) { case "1234": lblUserId.Text = id; lblUserName.Text = "Bill"; break; case "1235": lblUserId.Text = id; lblUserName.Text = "Claire"; break; case "1236": lblUserId.Text = id; lblUserName.Text = "David"; break; default: lblUserId.Text = "0000"; lblUserName.Text = "Unknown"; break;} | {
"score": 5,
"source": [
"https://Stackoverflow.com/questions/45340",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4491/"
]
} |
45,399 | I've worked on a number of database systems in the past where moving entries between databases would have been made a lot easier if all the database keys had been GUID / UUID values. I've considered going down this path a few times, but there's always a bit of uncertainty, especially around performance and un-read-out-over-the-phone-able URLs. Has anyone worked extensively with GUIDs in a database? What advantages would I get by going that way, and what are the likely pitfalls? | Advantages: Can generate them offline. Makes replication trivial (as opposed to int's, which makes it REALLY hard) ORM's usually like them Unique across applications. So We can use the PK's from our CMS (guid) in our app (also guid) and know we are NEVER going to get a clash. Disadvantages: Larger space use, but space is cheap(er) Can't order by ID to get the insert order. Can look ugly in a URL, but really, WTF are you doing putting a REAL DB key in a URL!? (This point disputed in comments below) Harder to do manual debugging, but not that hard. Personally, I use them for most PK's in any system of a decent size, but I got "trained" on a system which was replicated all over the place, so we HAD to have them. YMMV. I think the duplicate data thing is rubbish - you can get duplicate data however you do it. Surrogate keys are usually frowned upon where ever I've been working. We DO use the WordPress-like system though: unique ID for the row (GUID/whatever). Never visible to the user. public ID is generated ONCE from some field (e.g. the title - make it the-title-of-the-article) UPDATE: So this one gets +1'ed a lot, and I thought I should point out a big downside of GUID PK's: Clustered Indexes. If you have a lot of records, and a clustered index on a GUID, your insert performance will SUCK, as you get inserts in random places in the list of items (that's the point), not at the end (which is quick). So if you need insert performance, maybe use a auto-inc INT, and generate a GUID if you want to share it with someone else (e.g., showing it to a user in a URL). | {
"score": 9,
"source": [
"https://Stackoverflow.com/questions/45399",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/797/"
]
} |
45,400 | What's the recommended source control system for a very small team (one developer)? Price does not matter. Customer would pay :-) I'm working on Vista32 with VS 2008 in C++ and later in C# and with WPF. Setting up an extra (physical) server for this seems overkill to me. Any opinions? | I would use Subversion (in fact I use it) [ update : Jul 2014 -- I use Git -- see end of the answer].SVN is: free, good enough (see disadvantages below), simple, works fine on Windows (and Linux too), a lot of people use it so it's easy to get help, can integrate with most of IDEs i.e. Visual Studio (i.e. ankhsvn or VisualSVN -- more info ) or Eclipse (i.e. Subclipse -- here someone asked about that). I would strongly recommended separate machine to source control server. At best somewhere on the cloud . Advantages: You don't lost your source control repositories if your development box dies. You don't have to worry about maintenance of one more box. There are companies which host SVN repositories . Here are links to SVN (client and server) packages for various operating systems. Disadvantages of SVN I am using SVN on Windows machine for about 5 years and found that SVN has a few disadvantages :). It is slow on large repositories SVN (or its client -- TortoiseSVN) has one big disadvantage -- it terrible slow (while updating or committing) on large (thousands of files) repositories unless you have SSD drive. Merging can be difficult Many people complain about how hard merging is with SVN. I do merging for about 4 years (including about 2 years in CVS -- that was terrible, but doable) and about 2 years with SVN. And personally I don't find it hard -- on the other hand -- any merge is easy after merging branches in CVS :). I do merge of large repository (two repositories in fact) once a week and rarely I have conflicts which are hard to solve (most of conflicts are solved automatically with diff software which I use). However in case of project of a few developers merging should not be problem at all if you keep a few simple rules: merge changes often, avoid active development in various branches simultaneously. Added in July 2011 Many devs recommended Distributed Version Control like Git or Mercurial . From single developer perspective there are only a few important advantages of DVCS over SVN: DVCS can be faster. You can commit to local repository without access to central one. DVCS is hot thing and fancy to use/learn (if someone pay for your learning). And I don't think merging is a problem in case of single developer. Joel Spolsky wrote tutorial about Mercurial which is definitively worth to read. So, despite of many advantages of DVCS I would stay with SVN if merging or speed is not a problem. Or try Mercurial, which according to this and this SO questions, is better supported (in July 2011) on Windows. Added in July 2014 For about a year I use Git (Git Bash mainly) for my pet-projects (i.e. solving Euler problems) and local branches for each Euler problem are really nice feature -- exactly as it is described as advantage of DVCS. Today Git tooling on Windows is much, much better then 2 or more years ago.You can use remote repo (like GitHub or ProjectLocker and many others) to keep copy of your project away from your workstation with no extra effort/money. However I use GUI client only to looks at diffs (and sometimes to choose files to commit),so it's better to not afraid of command line -- it's really nice. So as of today I would go with Git. | {
"score": 7,
"source": [
"https://Stackoverflow.com/questions/45400",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3714/"
]
} |
45,407 | What are the main differences (if any) between the box models of IE8 and Firefox3? Are they the same now? What are the other main differences between these two browsers? Can a web developer assume that these two browsers as the same since they (seem to) support the latest web standards? | The Internet Explorer box model has been "fixed" since Internet Explorer 6 so long as your pages are in standard compliants mode. See: Quirks mode and Internet Explorer box model bug . Until I learnt about doctype declerations getting IE to work properly was a real PAIN, because IE runs in "quirks mode" by default. So having a standards mode doctype will eliminate a whole bunch of the most painful CSS problems. | {
"score": 5,
"source": [
"https://Stackoverflow.com/questions/45407",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/184/"
]
} |
45,453 | I'm generating ICalendar (.ics) files. Using the UID and SEQUENCE fields I can update existing events in Google Calendar and in Windows Calendar BUT NOT in MS Outlook 2007 - it just creates a second event How do I get them to work for Outlook ? Thanks Tom | I've continued to do some testing and have now managed to get Outlook to update and cancel events based on the .cs file. Outlook in fact seems to respond to the rules defined in RFC 2446 In summary you have to specify METHOD:REQUEST and ORGANIZER:xxxxxxxx in addition to UID : and SEQUENCE: For a cancellation you have to specify METHOD:CANCEL Request/Update Example BEGIN:VCALENDARVERSION:2.0PRODID:-//SYFADIS//PORTAIL FORMATION//FRMETHOD:REQUESTBEGIN:VEVENTUID:[email protected]:5DTSTAMP:20081106T154911ZORGANIZER:[email protected]:20081113T164907DTEND:20081115T170000SUMMARY:TestTrainingSTATUS:CONFIRMEDEND:VEVENTEND:VCALENDAR Cancel Example; BEGIN:VCALENDARVERSION:2.0PRODID:-//SYFADIS//PORTAIL FORMATION//FRMETHOD:CANCELBEGIN:VEVENTUID:[email protected]:7DTSTAMP:20081106T154916ZORGANIZER:[email protected]:20081113T164907SUMMARY:TestTrainingSTATUS:CANCELLEDEND:VEVENTEND:VCALENDAR | {
"score": 6,
"source": [
"https://Stackoverflow.com/questions/45453",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2839/"
]
} |
45,470 | Can you suggest some good MVC framework for perl -- one I am aware of is catalyst The need is to be able to expose services on the perl infrastructure which can be called by Java/.Net applications seamlessly. | I'll tell you right now that Catalyst has by far the best reputation amongst Perl developers in terms of a rapid application development MVC framework. In terms of "pure" MVC I'm not sure there are even that many "mature" or at least production-ready alternatives. If Catalyst doesn't seem right to you, then you could build upon the lightweight framework CGI::Application to suit your needs or take a look at some of the lesser known MVC frameworks like PageKit and Maypole . | {
"score": 5,
"source": [
"https://Stackoverflow.com/questions/45470",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4406/"
]
} |
45,494 | I have a table story_category in my database with corrupt entries. The next query returns the corrupt entries: SELECT * FROM story_category WHERE category_id NOT IN ( SELECT DISTINCT category.id FROM category INNER JOIN story_category ON category_id=category.id); I tried to delete them executing: DELETE FROM story_category WHERE category_id NOT IN ( SELECT DISTINCT category.id FROM category INNER JOIN story_category ON category_id=category.id); But I get the next error: #1093 - You can't specify target table 'story_category' for update in FROM clause How can I overcome this? | Update: This answer covers the general error classification. For a more specific answer about how to best handle the OP's exact query, please see other answers to this question In MySQL, you can't modify the same table which you use in the SELECT part. This behaviour is documented at: http://dev.mysql.com/doc/refman/5.6/en/update.html Maybe you can just join the table to itself If the logic is simple enough to re-shape the query, lose the subquery and join the table to itself, employing appropriate selection criteria. This will cause MySQL to see the table as two different things, allowing destructive changes to go ahead. UPDATE tbl AS aINNER JOIN tbl AS b ON ....SET a.col = b.col Alternatively, try nesting the subquery deeper into a from clause ... If you absolutely need the subquery, there's a workaround, but it'sugly for several reasons, including performance: UPDATE tbl SET col = ( SELECT ... FROM (SELECT.... FROM) AS x); The nested subquery in the FROM clause creates an implicit temporarytable , so it doesn't count as the same table you're updating. ... but watch out for the query optimiser However, beware that from MySQL 5.7.6 and onward, the optimiser may optimise out the subquery, and still give you the error. Luckily, the optimizer_switch variable can be used to switch off this behaviour; although I couldn't recommend doing this as anything more than a short term fix, or for small one-off tasks. SET optimizer_switch = 'derived_merge=off'; Thanks to Peter V. Mørch for this advice in the comments. Example technique was from Baron Schwartz, originally published at Nabble , paraphrased and extended here. | {
"score": 11,
"source": [
"https://Stackoverflow.com/questions/45494",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2138/"
]
} |
45,507 | I'm looking to create favicon.ico files programatically from Python, but PIL only has support for reading ico files. | You can use Pillow : from PIL import Imagefilename = r'logo.png'img = Image.open(filename)img.save('logo.ico') Optionally, you may specify the icon sizes you want: icon_sizes = [(16,16), (32, 32), (48, 48), (64,64)]img.save('logo.ico', sizes=icon_sizes) The Pillow docs say that by default it will generate sizes [(16, 16), (24, 24), (32, 32), (48, 48), (64, 64), (128, 128), (255, 255)] and any size bigger than the original size or 255 will be ignored. Yes, it is in the Read-only section of the docs, but it works to some extent. | {
"score": 6,
"source": [
"https://Stackoverflow.com/questions/45507",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4203/"
]
} |
45,535 | I need the month+year from the datetime in SQL Server like 'Jan 2008'. I'm grouping the query by month, year. I've searched and found functions like datepart, convert, etc., but none of them seem useful for this. Am I missing something here? Is there a function for this? | If you mean you want them back as a string, in that format; SELECT CONVERT(CHAR(4), date_of_birth, 100) + CONVERT(CHAR(4), date_of_birth, 120) FROM customers Here are the other format options | {
"score": 7,
"source": [
"https://Stackoverflow.com/questions/45535",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1688440/"
]
} |
45,546 | I want my controller to return the right HTTP response code when the user lacks permission to view a particular page. | Create an Exception annotated with @ResponseStatus e.g. like this: @ResponseStatus(HttpStatus.FORBIDDEN)public class ForbiddenException extends RuntimeException {} Now just throw that Exception in your handler method and the response will have status 403. | {
"score": 6,
"source": [
"https://Stackoverflow.com/questions/45546",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4702/"
]
} |
45,604 | C# doesn't require you to specify a generic type parameter if the compiler can infer it, for instance: List<int> myInts = new List<int> {0,1,1, 2,3,5,8,13,21,34,55,89,144,233,377, 610,987,1597,2584,4181,6765};//this statement is clunkyList<string> myStrings = myInts. Select<int,string>( i => i.ToString() ). ToList<string>();//the type is inferred from the lambda expression//the compiler knows that it's taking an int and //returning a stringList<string> myStrings = myInts. Select( i => i.ToString() ). ToList(); This is needed for anonymous types where you don't know what the type parameter would be (in intellisense it shows up as 'a ) because it's added by the compiler. Class-level type parameters don't let you do this: //sample generic classpublic class GenericDemo<T> { public GenericDemo ( T value ) { GenericTypedProperty = value; } public T GenericTypedProperty {get; set;}}//why can't I do:int anIntValue = 4181;var item = new GenericDemo( anIntValue ); //type inference fails//however I can create a wrapper like this:public static GenericDemo<T> Create<T> ( T value ){ return new GenericDemo<T> ( value );}//then this works - type inference on the method compilesvar item = Create( anIntValue ); Why doesn't C# support this class level generic type inference? | Actually, your question isn't bad. I've been toying with a generic programming language for last few years and although I've never come around to actually develop it (and probably never will), I've thought a lot about generic type inference and one of my top priorities has always been to allow the construction of classes without having to specify the generic type. C# simply lacks the set of rules to make this possible. I think the developers never saw the neccesity to include this. Actually, the following code would be very near to your proposition and solve the problem. All C# needs is an added syntax support. class Foo<T> { public Foo(T x) { … }}// Notice: non-generic class overload. Possible in C#!class Foo { public static Foo<T> ctor<T>(T x) { return new Foo<T>(x); }}var x = Foo.ctor(42); Since this code actually works, we've shown that the problem is not one of semantics but simply one of lacking support. I guess I have to take back my previous posting. ;-) | {
"score": 6,
"source": [
"https://Stackoverflow.com/questions/45604",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/905/"
]
} |
45,613 | What could be the problem with reversing the array of DOM objects as in the following code: var imagesArr = new Array();imagesArr = document.getElementById("myDivHolderId").getElementsByTagName("img");imagesArr.reverse(); In Firefox 3, when I call the reverse() method the script stops executing and shows the following error in the console of the Web Developer Toolbar: imagesArr.reverse is not a function The imagesArr variable can be iterated through with a for loop and elements like imagesArr[i] can be accessed, so why is it not seen as an array when calling the reverse() method? | Because getElementsByTag name actually returns a NodeList structure. It has similar array like indexing properties for syntactic convenience, but it is not an array. For example, the set of entries is actually constantly being dynamically updated - if you add a new img tag under myDivHolderId, it will automatically appear in imagesArr. See http://www.w3.org/TR/DOM-Level-2-Core/core.html#ID-536297177 for more. | {
"score": 5,
"source": [
"https://Stackoverflow.com/questions/45613",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4723/"
]
} |
45,621 | Example I have Person , SpecialPerson , and User . Person and SpecialPerson are just people - they don't have a user name or password on a site, but they are stored in a database for record keeping. User has all of the same data as Person and potentially SpecialPerson , along with a user name and password as they are registered with the site. How would you address this problem? Would you have a Person table which stores all data common to a person and use a key to look up their data in SpecialPerson (if they are a special person) and User (if they are a user) and vice-versa? | There are generally three ways of mapping object inheritance to database tables. You can make one big table with all the fields from all the objects with a special field for the type. This is fast but wastes space, although modern databases save space by not storing empty fields. And if you're only looking for all users in the table, with every type of person in it things can get slow. Not all or-mappers support this. You can make different tables for all the different child classes with all of the tables containing the base-class fields. This is ok from a performance perspective. But not from a maintenance perspective. Every time your base-class changes all the tables change. You can also make a table per class like you suggested. This way you need joins to get all the data. So it's less performant. I think it's the cleanest solution. What you want to use depends of course on your situation. None of the solutions is perfect so you have to weigh the pros and cons. | {
"score": 7,
"source": [
"https://Stackoverflow.com/questions/45621",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/572/"
]
} |
45,623 | In Java, what would the best way be to have a constantly listening port open, and still send upon receipt of a packet. I am not particularly savvy with network programming at the moment, so the tutorials I have found on the net aren't particularly helpful. Would it make sense to have the listening socket as a serversocket and run it in a separate thread to the socket I'm using to send data to the server? In a loosely related question. Does anyone know if programming simply for java, in netbeans then exporting it for use on a blackberry (using a plugin) the sockets would still work ? | If you can afford the threading, try this (keep in mind I've left out some details like exception handling and playing nice with threads). You may want to look into SocketChannels and/or NIO async sockets / selectors. This should get you started. boolean finished = false;int port = 10000;ServerSocket server = new ServerSocket(port);while (!finished) { // This will block until a connection is made Socket s = server.accept(); // Spawn off some thread (or use a thread pool) to handle this socket // Server will continue to listen} | {
"score": 5,
"source": [
"https://Stackoverflow.com/questions/45623",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4739/"
]
} |
45,624 | I use TortoiseSVN to access file based local repo. In all my commits an author is my Windows login name. Is it possible to use different name? I know how to change author after commit but how to change before? Installing apache/svnserver is not an option. | Yes, it's possible. TortoiseSVN and the svn command line client share the same settings location in your profile folder. So you may simply checkout one version using svn.exe : $ svn co --username different_user_name file:///C:/path/to/your/repo ... and Subversion will happily replace the associated username for that repository. New commits from TortoiseSVN will then always use that username, no matter with what program you make the new checkouts. The procedure should work with TortoiseSVN 1.5.5. If it doesn't, try emptying svn's authentication cache ( %APPDATA%\Subversion\auth\svn.username ) first. | {
"score": 5,
"source": [
"https://Stackoverflow.com/questions/45624",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/501/"
]
} |
45,627 | In unmanaged C/C++ code, what are the best practices to detect memory leaks? And coding guidelines to avoid? (As if it's that simple ;) We have used a bit of a silly way in the past: having a counter increment for every memory allocation call and decrement while freeing. At the end of the program, the counter value should be zero. I know this is not a great way and there are a few catches. (For instance, if you are freeing memory which was allocated by a platform API call, your allocation count will not exactly match your freeing count. Of course, then we incremented the counter when calling API calls that allocated memory.) I am expecting your experiences, suggestions and maybe some references to tools which simplify this. | If your C/C++ code is portable to *nix, few things are better than Valgrind . | {
"score": 6,
"source": [
"https://Stackoverflow.com/questions/45627",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/123/"
]
} |
45,650 | Many times I have seen Visual Studio solutions which have multiple projects that share source files. These common source files are usually out in a common directory and in the solution explorer their icon shows up with a link arrow in the bottom left. However, any time I try to add a source file to the project that is outside of that project's main directory, it just automatically copies it into the directory so that I no longer have a shared copy. I found that I can get around this by manually opening the project file in a text editor and modifying the path to something like "../../../Common/Source.cs" but this is more of a hack then I would like. Is there a setting or something I can change that will allow me to do this from within the IDE? | Right click on a project, select Add->Existing Item->Add as link (press on small arrow on Add button) | {
"score": 6,
"source": [
"https://Stackoverflow.com/questions/45650",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/194/"
]
} |
45,651 | I inserted some values into a table. There is a column whose value is auto-generated. In the next statement of my code, I want to retrieve this value. Can you tell me how to do it the right way? | @@IDENTITY is not scope safe and will get you back the id from another table if you have an insert trigger on the original table, always use SCOPE_IDENTITY() | {
"score": 7,
"source": [
"https://Stackoverflow.com/questions/45651",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/184/"
]
} |
45,702 | Let's say I want to run a .NET application on a machine where the .NET framework is not available; Is there any way to compile the application to native code? | Microsoft has an article describing how you can Compile MSIL to Native Code You can use Ngen . The Native Image Generator (Ngen.exe) is a tool that improves the performance of managed applications. Ngen.exe creates native images, which are files containing compiled processor-specific machine code, and installs them into the native image cache on the local computer. The runtime can use native images from the cache instead using the just-in-time (JIT) compiler to compile the original assembly. Unfortunately, you still need the libraries from the framework in order to run your program. There's no feature that I know of with the MS .Net framework SDK that allows you to compile all the required files into a single executable | {
"score": 7,
"source": [
"https://Stackoverflow.com/questions/45702",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/184/"
]
} |
45,779 | How would you dynamically subscribe to a C# event so that given a Object instance and a String name containing the name of the event, you subscribe to that event and do something (write to the console for example) when that event has been fired? It would seem using Reflection this isn't possible and I would like to avoid having to use Reflection.Emit if possible, as this currently (to me) seems like the only way of doing it. /EDIT: I do not know the signature of the delegate needed for the event, this is the core of the problem /EDIT 2: Although delegate contravariance seems like a good plan, I can not make the assumption necessary to use this solution | You can compile expression trees to use void methods without any arguments as event handlers for events of any type. To accommodate other event handler types, you have to map the event handler's parameters to the events somehow. using System; using System.Linq; using System.Linq.Expressions; using System.Reflection; class ExampleEventArgs : EventArgs { public int IntArg {get; set;} } class EventRaiser { public event EventHandler SomethingHappened; public event EventHandler<ExampleEventArgs> SomethingHappenedWithArg; public void RaiseEvents() { if (SomethingHappened!=null) SomethingHappened(this, EventArgs.Empty); if (SomethingHappenedWithArg!=null) { SomethingHappenedWithArg(this, new ExampleEventArgs{IntArg = 5}); } } } class Handler { public void HandleEvent() { Console.WriteLine("Handler.HandleEvent() called.");} public void HandleEventWithArg(int arg) { Console.WriteLine("Arg: {0}",arg); } } static class EventProxy { //void delegates with no parameters static public Delegate Create(EventInfo evt, Action d) { var handlerType = evt.EventHandlerType; var eventParams = handlerType.GetMethod("Invoke").GetParameters(); //lambda: (object x0, EventArgs x1) => d() var parameters = eventParams.Select(p=>Expression.Parameter(p.ParameterType,"x")); var body = Expression.Call(Expression.Constant(d),d.GetType().GetMethod("Invoke")); var lambda = Expression.Lambda(body,parameters.ToArray()); return Delegate.CreateDelegate(handlerType, lambda.Compile(), "Invoke", false); } //void delegate with one parameter static public Delegate Create<T>(EventInfo evt, Action<T> d) { var handlerType = evt.EventHandlerType; var eventParams = handlerType.GetMethod("Invoke").GetParameters(); //lambda: (object x0, ExampleEventArgs x1) => d(x1.IntArg) var parameters = eventParams.Select(p=>Expression.Parameter(p.ParameterType,"x")).ToArray(); var arg = getArgExpression(parameters[1], typeof(T)); var body = Expression.Call(Expression.Constant(d),d.GetType().GetMethod("Invoke"), arg); var lambda = Expression.Lambda(body,parameters); return Delegate.CreateDelegate(handlerType, lambda.Compile(), "Invoke", false); } //returns an expression that represents an argument to be passed to the delegate static Expression getArgExpression(ParameterExpression eventArgs, Type handlerArgType) { if (eventArgs.Type==typeof(ExampleEventArgs) && handlerArgType==typeof(int)) { //"x1.IntArg" var memberInfo = eventArgs.Type.GetMember("IntArg")[0]; return Expression.MakeMemberAccess(eventArgs,memberInfo); } throw new NotSupportedException(eventArgs+"->"+handlerArgType); } } static class Test { public static void Main() { var raiser = new EventRaiser(); var handler = new Handler(); //void delegate with no parameters string eventName = "SomethingHappened"; var eventinfo = raiser.GetType().GetEvent(eventName); eventinfo.AddEventHandler(raiser,EventProxy.Create(eventinfo,handler.HandleEvent)); //void delegate with one parameter string eventName2 = "SomethingHappenedWithArg"; var eventInfo2 = raiser.GetType().GetEvent(eventName2); eventInfo2.AddEventHandler(raiser,EventProxy.Create<int>(eventInfo2,handler.HandleEventWithArg)); //or even just: eventinfo.AddEventHandler(raiser,EventProxy.Create(eventinfo,()=>Console.WriteLine("!"))); eventInfo2.AddEventHandler(raiser,EventProxy.Create<int>(eventInfo2,i=>Console.WriteLine(i+"!"))); raiser.RaiseEvents(); } } | {
"score": 6,
"source": [
"https://Stackoverflow.com/questions/45779",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1111/"
]
} |
45,783 | My team is currently trying to automate the deployment of our .Net and PHP web applications. We want to streamline deployments, and to avoid the hassle and many of the headaches caused by doing it manually. We require a solution that will enable us to: - Compile the application - Version the application with the SVN version number - Backup the existing site - Deploy to a web farm All our apps are source controlled using SVN and our .Net apps use CruiseControl.We have been trying to use MSBuild and NAnt deployment scripts with limited success. We have also used Capistrano in the past, but wish to avoid using Ruby if possible. Are there any other deployment tools out there that would help us? | Thank you all for your kind suggestions. We checked them all out, but after careful consideration we decided to roll our own with a combination of CruiseControl, NAnt, MSBuild and MSDeploy. This article has some great information: Integrating MSBuild with CruiseControl.NET Here's roughly how our solution works: Developers build the 'debug' version of the app and run unit tests, then check in to SVN. CruiseControl sees the updates and calls our build script... Runs any new migrations on the build database Replaces the config files with the build server config Builds the 'debug' configuration of the app Runs all unit and integration tests Builds the 'deploy' configuration of the app Versions the DLLs with the current major/minor version and SVN revision, e.g. 1.2.0.423 Moves this new build to a 'release' folder on our build server Removes unneeded files Updates IIS on the build server if required Then when we have verified everything is ready to go up to live/staging we run another script to: Run migrations on live/staging server MSDeploy: archive current live/staging site MSDeploy: sync site from build to live/staging It wasn't pretty getting to this stage, but it's mostly working like a charm now :D I'm going to try and keep this answer updated as we make changes to our process, as there seem to be several similar questions on SA now. | {
"score": 6,
"source": [
"https://Stackoverflow.com/questions/45783",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4734/"
]
} |
45,813 | Is there a way with WPF to get an array of elements under the mouse on a MouseMove event? | You can also try using the Mouse.DirectlyOver property to get the top-most element that is under the mouse. | {
"score": 6,
"source": [
"https://Stackoverflow.com/questions/45813",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3291/"
]
} |
45,827 | How do you automatically set the focus to a textbox when a web page loads? Is there an HTML tag to do it or does it have to be done via Javascript? | If you're using jquery: $(function() { $("#Box1").focus();}); or prototype: Event.observe(window, 'load', function() { $("Box1").focus();}); or plain javascript: window.onload = function() { document.getElementById("Box1").focus();}; though keep in mind that this will replace other on load handlers, so look up addLoadEvent() in google for a safe way to append onload handlers rather than replacing. | {
"score": 9,
"source": [
"https://Stackoverflow.com/questions/45827",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/305/"
]
} |
45,861 | I am using js2-mode to edit Javascript in Emacs, but I can't seem to get it to stop using tabs instead of spaces for indentation. My other modes work fine, just having issues w/ js2. | Do you have (setq-default indent-tabs-mode nil) in your .emacs? It works fine for me in emacs 23.0.60.1 when I do that. js2-mode uses the standard emacs function indent-to, which respects indent-tabs-mode, to do its indenting. | {
"score": 6,
"source": [
"https://Stackoverflow.com/questions/45861",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4748/"
]
} |
45,865 | I'm writing a wizard for an Eclipse RCP application. After doing some processing on a file and taking some user input, I don't want to let the user go back to make changes. At this point they must either accept or reject the changes they are about to make to the system. What I can't seem to find is a method call that lets me override the buttons that display or the user's ability to hit the back button. I'd prefer that it not be there or at least be disabled. Has anyone found a way to do this using the JFace Wizard and WizardPage ? Usability-wise, am I breaking wizard conventions? Should I consider a different approach to the problem? | You can return null from the getPreviousPage() method in your wizard page implementation. | {
"score": 5,
"source": [
"https://Stackoverflow.com/questions/45865",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4513/"
]
} |
45,879 | We have an InnoDB database that is about 70 GB and we expect it to grow to several hundred GB in the next 2 to 3 years. About 60 % of the data belong to a single table. Currently the database is working quite well as we have a server with 64 GB of RAM, so almost the whole database fits into memory, but we’re concerned about the future when the amount of data will be considerably larger. Right now we’re considering some way of splitting up the tables (especially the one that accounts for the biggest part of the data) and I’m now wondering, what would be the best way to do it. The options I’m currently aware of are Using MySQL Partitioning that comes with version 5.1 Using some kind of third party library that encapsulates the partitioning of the data (like hibernate shards) Implementing it ourselves inside our application Our application is built on J2EE and EJB 2.1 (hopefully we’re switching to EJB 3 some day). What would you suggest? EDIT (2011-02-11): Just an update: Currently the size of the database is 380 GB, the data size of our "big" table is 220 GB and the size of its index is 36 GB. So while the whole table does not fit in memory any more, the index does. The system is still performing fine (still on the same hardware) and we're still thinking about partitioning the data. EDIT (2014-06-04):One more update: The size of the whole database is 1.5 TB, the size of our "big" table is 1.1 TB. We upgraded our server to a 4 processor machine (Intel Xeon E7450) with 128 GB RAM.The system is still performing fine.What we're planning to do next is putting our big table on a separate database server (we've already done the necessary changes in our software) while simultaneously upgrading to new hardware with 256 GB RAM. This setup is supposed to last for two years. Then we will either have to finally start implementing a sharding solution or just buy servers with 1 TB of RAM which should keep us going for some time. EDIT (2016-01-18): We have since put our big table in it's own database on a separate server. Currently the size ot this database is about 1.9 TB, the size of the other database (with all tables except for the "big" one) is 1.1 TB. Current Hardware setup: HP ProLiant DL 580 4 x Intel(R) Xeon(R) CPU E7- 4830 256 GB RAM Performance is fine with this setup. | You will definitely start to run into issues on that 42 GB table once it no longer fits in memory. In fact, as soon as it does not fit in memory anymore, performance will degrade extremely quickly. One way to test is to put that table on another machine with less RAM and see how poor it performs. First of all, it doesn't matter as much splitting out tables unless you also move some of the tables to a separate physical volume. This is incorrect. Partioning (either through the feature in MySQL 5.1, or the same thing using MERGE tables) can provide significant performance benefits even if the tables are on the same drive. As an example, let's say that you are running SELECT queries on your big table using a date range. If the table is whole, the query will be forced to scan through the entire table (and at that size, even using indexes can be slow). The advantage of partitioning is that your queries will only run on the partitions where it is absolutely necessary. If each partition is 1 GB in size and your query only needs to access 5 partitions in order to fulfill itself, the combined 5 GB table is a lot easier for MySQL to deal with than a monster 42 GB version. One thing you need to ask yourself is how you are querying the data. If there is a chance that your queries will only need to access certain chunks of data (i.e. a date range or ID range), partitioning of some kind will prove beneficial. I've heard that there is still some buggyness with MySQL 5.1 partitioning, particularly related to MySQL choosing the correct key. MERGE tables can provide the same functionality, although they require slightly more overhead. Hope that helps...good luck! | {
"score": 5,
"source": [
"https://Stackoverflow.com/questions/45879",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4497/"
]
} |
45,888 | I have jQuery but I'm not sure if it has any built-in sorting helpers. I could make a 2d array of each item's text , value , and selected properties, but I don't think that javascript's built in Array.sort() would work correctly. | Extract options into a temporary array, sort, then rebuild the list: var my_options = $("#my_select option");var selected = $("#my_select").val();my_options.sort(function(a,b) { if (a.text > b.text) return 1; if (a.text < b.text) return -1; return 0})$("#my_select").empty().append( my_options );$("#my_select").val(selected); Mozilla's sort documentation (specifically the compareFunction) and Wikipedia's Sorting Algorithm page are relevant. If you want to make the sort case insensitive, replace text with text.toLowerCase() The sort function shown above illustrates how to sort. Sorting non-english languages accurately can be complex (see the unicode collation algorithm ). Using localeCompare in the sort function is a good solution, eg: my_options.sort(function(a,b) { return a.text.localeCompare(b.text);}); | {
"score": 8,
"source": [
"https://Stackoverflow.com/questions/45888",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1414/"
]
} |
45,904 | Situation: I have a simple XML document that contains image information. I need to transform it into HTML . However, I can't see where the open tag is and when I use the XSL code below, it shows the following error message: "Cannot write an attribute node when no element start tag is open." XML content: <root> <HeaderText> <HeaderText>Dan Testing</HeaderText> </HeaderText> <Image> <img width="100" height="100" alt="FPO lady" src="/uploadedImages/temp_photo_small.jpg"/> </Image> <BodyText> <p>This is a test of the body text<br /></p> </BodyText> <ShowLinkArrow>false</ShowLinkArrow></root> XSL code: <xsl:stylesheet version="1.0" extension-element-prefixes="msxsl" exclude-result-prefixes="msxsl js dl" xmlns:xsl="http://www.w3.org/1999/XSL/Transform" xmlns:js="urn:custom-javascript" xmlns:msxsl="urn:schemas-microsoft-com:xslt" xmlns:dl="urn:datalist"> <xsl:output method="xml" version="1.0" omit-xml-declaration="yes" indent="yes" encoding="utf-8"/> <xsl:template match="/" xml:space="preserve"> <img> <xsl:attribute name="width"> 100 </xsl:attribute> <xsl:attribute name="height"> 100 </xsl:attribute> <xsl:attribute name="class"> CalloutRightPhoto </xsl:attribute> <xsl:attribute name="src"> <xsl:copy-of select="/root/Image/node()"/> </xsl:attribute> </img> </xsl:template></xsl:stylesheet> | Just to clarify the problem here - the error is in the following bit of code: <xsl:attribute name="src"> <xsl:copy-of select="/root/Image/node()"/></xsl:attribute> The instruction xsl:copy-of takes a node or node-set and makes a copy of it - outputting a node or node-set. However an attribute cannot contain a node, only a textual value, so xsl:value-of would be a possible solution (as this returns the textual value of a node or nodeset). A MUCH shorter solution (and perhaps more elegant) would be the following: <img width="100" height="100" src="{/root/Image/node()}" class="CalloutRightPhoto"/> The use of the {} in the attribute is called an Attribute Value Template, and can contain any XPATH expression. Note, the same XPath can be used here as you have used in the xsl_copy-of as it knows to take the textual value when used in a Attribute Value Template. | {
"score": 6,
"source": [
"https://Stackoverflow.com/questions/45904",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2757/"
]
} |
45,953 | I need to execute a directory copy upon a user action, but the directories are quite large, so I would like to be able to perform such an action without the user being aware of the time it takes for the copy to complete. Any suggestions would be much appreciated. | Assuming this is running on a Linux machine, I've always handled it like this: exec(sprintf("%s > %s 2>&1 & echo $! >> %s", $cmd, $outputfile, $pidfile)); This launches the command $cmd , redirects the command output to $outputfile , and writes the process id to $pidfile . That lets you easily monitor what the process is doing and if it's still running. function isRunning($pid){ try{ $result = shell_exec(sprintf("ps %d", $pid)); if( count(preg_split("/\n/", $result)) > 2){ return true; } }catch(Exception $e){} return false;} | {
"score": 10,
"source": [
"https://Stackoverflow.com/questions/45953",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1071/"
]
} |
45,964 | How do I multiply 10 to an Integer object and get back the Integer object? I am looking for the neatest way of doing this. I would probably do it this way:Get int from Integer object, multiply it with the other int and create another Integer object with this int value. Code will be something like ... integerObj = new Integer(integerObj.intValue() * 10); But, I saw a code where the author is doing it this way: Get the String from the Integer object, concatenate "0" at the end and then get Integer object back by using Integer.parseInt The code is something like this: String s = integerObj + "0";integerObj = Integer.parseInt(s); Is there any merit in doing it either way? And what would be the most efficient/neatest way in general and in this case? | With Java 5's autoboxing , you can simply do: Integer a = new Integer(2); // or even just Integer a = 2;a *= 10;System.out.println(a); | {
"score": 6,
"source": [
"https://Stackoverflow.com/questions/45964",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4406/"
]
} |
45,972 | I'm working on a program that will be processing files that could potentially be 100GB or more in size. The files contain sets of variable length records. I've got a first implementation up and running and am now looking towards improving performance, particularly at doing I/O more efficiently since the input file gets scanned many times. Is there a rule of thumb for using mmap() versus reading in blocks via C++'s fstream library? What I'd like to do is read large blocks from disk into a buffer, process complete records from the buffer, and then read more. The mmap() code could potentially get very messy since mmap 'd blocks need to lie on page sized boundaries (my understanding) and records could potentially lie across page boundaries. With fstream s, I can just seek to the start of a record and begin reading again, since we're not limited to reading blocks that lie on page sized boundaries. How can I decide between these two options without actually writing up a complete implementation first? Any rules of thumb (e.g., mmap() is 2x faster) or simple tests? | I was trying to find the final word on mmap / read performance on Linux and I came across a nice post ( link ) on the Linux kernel mailing list. It's from 2000, so there have been many improvements to IO and virtual memory in the kernel since then, but it nicely explains the reason why mmap or read might be faster or slower. A call to mmap has more overhead than read (just like epoll has more overhead than poll , which has more overhead than read ). Changing virtual memory mappings is a quite expensive operation on some processors for the same reasons that switching between different processes is expensive. The IO system can already use the disk cache, so if you read a file, you'll hit the cache or miss it no matter what method you use. However, Memory maps are generally faster for random access, especially if your access patterns are sparse and unpredictable. Memory maps allow you to keep using pages from the cache until you are done. This means that if you use a file heavily for a long period of time, then close it and reopen it, the pages will still be cached. With read , your file may have been flushed from the cache ages ago. This does not apply if you use a file and immediately discard it. (If you try to mlock pages just to keep them in cache, you are trying to outsmart the disk cache and this kind of foolery rarely helps system performance). Reading a file directly is very simple and fast. The discussion of mmap/read reminds me of two other performance discussions: Some Java programmers were shocked to discover that nonblocking I/O is often slower than blocking I/O, which made perfect sense if you know that nonblocking I/O requires making more syscalls. Some other network programmers were shocked to learn that epoll is often slower than poll , which makes perfect sense if you know that managing epoll requires making more syscalls. Conclusion: Use memory maps if you access data randomly, keep it around for a long time, or if you know you can share it with other processes ( MAP_SHARED isn't very interesting if there is no actual sharing). Read files normally if you access data sequentially or discard it after reading. And if either method makes your program less complex, do that . For many real world cases there's no sure way to show one is faster without testing your actual application and NOT a benchmark. (Sorry for necro'ing this question, but I was looking for an answer and this question kept coming up at the top of Google results.) | {
"score": 9,
"source": [
"https://Stackoverflow.com/questions/45972",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2353001/"
]
} |
45,988 | In a C# .NET 3.5 app (a mix of WinForms and WPF) I want to let the user select a folder to import a load of data from. At the moment, it's using System.Windows.Forms.FolderBrowserDialog but that's a bit lame. Mainly because you can't type the path into it (so you need to map a network drive, instead of typing a UNC path). I'd like something more like the System.Windows.Forms.OpenFileDialog , but for folders instead of files. What can I use instead? A WinForms or WPF solution is fine, but I'd prefer not to PInvoke into the Windows API if I can avoid it. | Don't create it yourself! It's been done. You can use FolderBrowserDialogEx - a re-usable derivative of the built-in FolderBrowserDialog. This one allows you to type in a path, even a UNC path. You can also browse for computers or printers with it. Works just like the built-in FBD, but ... better. Full Source code. Free. MS-Public license. Code to use it: var dlg1 = new Ionic.Utils.FolderBrowserDialogEx();dlg1.Description = "Select a folder to extract to:";dlg1.ShowNewFolderButton = true;dlg1.ShowEditBox = true;//dlg1.NewStyle = false;dlg1.SelectedPath = txtExtractDirectory.Text;dlg1.ShowFullPathInEditBox = true;dlg1.RootFolder = System.Environment.SpecialFolder.MyComputer;// Show the FolderBrowserDialog.DialogResult result = dlg1.ShowDialog();if (result == DialogResult.OK){ txtExtractDirectory.Text = dlg1.SelectedPath;} | {
"score": 6,
"source": [
"https://Stackoverflow.com/questions/45988",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1367/"
]
} |
46,029 | If I have a collection of database tables (in an Access file, for example) and need to validate each table in this collection against a rule set that has both common rules across all tables as well as individual rules specific to one or a subset of tables, can someone recommend a good design pattern to look into? Specifically, I would like to avoid code similar to: void Main(){ ValidateTable1(); ValidateTable2(); ValidateTable3();}private void ValidateTable1(){ //Table1 validation code goes here}private void ValidateTable2(){ //Table2 validation code goes here}private void ValidateTable3(){ //Table3 validation code goes here} Also, I've decided to use log4net to log all of the errors and warnings, so that each method can be declared void and doesn't need to return anything. Is this a good idea or would it be better to create some sort of ValidationException that catches all exceptions and stores them in a List<ValidationException> before printing them all out at the end? I did find this , which looks like it may work, but I'm hoping to actually find some code samples to work off of. Any suggestions? Has anyone done something similar in the past? For some background, the program will be written in either C# or VB.NET and the tables will more than likely be stored in either Access or SQL Server CE. | Just an update on this: I decided to go with the Decorator pattern . That is, I have one 'generic' table class that implements an IValidateableTable interface (which contains validate() method). Then, I created several validation decorators (that also implement IValidateableTable ) which I can wrap around each table that I'm trying to validate. So, the code ends up looking like this: IValidateableTable table1 = new GenericTable(myDataSet);table1 = new NonNullNonEmptyColumnValidator(table1, "ColumnA");table1 = new ColumnValueValidator(table1, "ColumnB", "ExpectedValue"); Then, all I need to do is call table1.Validate() which unwinds through the decorators calling all of the needed validations. So far, it seems to work really well, though I am still open to suggestions. | {
"score": 5,
"source": [
"https://Stackoverflow.com/questions/46029",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1108/"
]
} |
46,030 | So, I did search google and SO prior to asking this question. Basically I have a DLL that has a form compiled into it. The form will be used to display information to the screen. Eventually it will be asynchronous and expose a lot of customization in the dll. For now I just want it to display properly. The problem that I am having is that I use the dll by loading it in a Powershell session. So when I try to display the form and get it to come to the top and have focus, It has no problem with displaying over all the other apps, but I can't for the life of me get it to display over the Powershell window. Here is the code that I am currently using to try and get it to display. I am sure that the majority of it won't be required once I figure it out, this just represents all the things that I found via google. CLass Blah{ [DllImport("user32.dll", EntryPoint = "SystemParametersInfo")] public static extern bool SystemParametersInfo(uint uiAction, uint uiParam, uint pvParam, uint fWinIni); [DllImport("user32.dll", EntryPoint = "SetForegroundWindow")] public static extern bool SetForegroundWindow(IntPtr hWnd); [DllImport("User32.dll", EntryPoint = "ShowWindowAsync")] private static extern bool ShowWindowAsync(IntPtr hWnd, int cmdShow); private const int WS_SHOWNORMAL = 1; public void ShowMessage(string msg) { MessageForm msgFrm = new MessageForm(); msgFrm.lblMessage.Text = "FOO"; msgFrm.ShowDialog(); msgFrm.BringToFront(); msgFrm.TopMost = true; msgFrm.Activate(); SystemParametersInfo((uint)0x2001, 0, 0, 0x0002 | 0x0001); ShowWindowAsync(msgFrm.Handle, WS_SHOWNORMAL); SetForegroundWindow(msgFrm.Handle); SystemParametersInfo((uint)0x2001, 200000, 200000, 0x0002 | 0x0001); }} As I say I'm sure that most of that is either not needed or even flat out wrong, I just wanted to show the things that I had tried. Also, as I mentioned, I plan to have this be asynchronously displayed at some point which I suspect will wind up requiring a separate thread. Would splitting the form out into it's own thread make it easier to cause it to get focus over the Powershell session? @Joel, thanks for the info. Here is what I tried based on your suggestion: msgFrm.ShowDialog();msgFrm.BringToFront();msgFrm.Focus();Application.DoEvents(); The form still comes up under the Powershell session. I'll proceed with working out the threading. I've spawned threads before but never where the parent thread needed to talk to the child thread, so we'll see how it goes. Thnks for all the ideas so far folks. Ok, threading it took care of the problem. @Quarrelsome, I did try both of those. Neither (nor both together) worked. I am curious as to what is evil about using threading? I am not using Application.Run and I have yet to have a problem. I am using a mediator class that both the parent thread and the child thread have access to. In that object I am using a ReaderWriterLock to lock one property that represents the message that I want displayed on the form that the child thread creates. The parent locks the property then writes what should be displayed. The child thread locks the property and reads what it should change the label on the form to. The child has to do this on a polling interval (I default it to 500ms) which I'm not real happy about, but I could not find an event driven way to let the child thread know that the proerty had changed, so I'm stuck with polling. | I also had trouble activating and bringing a window to the foreground. Here is the code that eventually worked for me. I'm not sure if it will solve your problem. Basically, call ShowWindow() then SetForegroundWindow(). using System.Diagnostics;using System.Runtime.InteropServices;// Sets the window to be foreground[DllImport("User32")]private static extern int SetForegroundWindow(IntPtr hwnd);// Activate or minimize a window[DllImportAttribute("User32.DLL")]private static extern bool ShowWindow(IntPtr hWnd, int nCmdShow);private const int SW_SHOW = 5;private const int SW_MINIMIZE = 6;private const int SW_RESTORE = 9;private void ActivateApplication(string briefAppName){ Process[] procList = Process.GetProcessesByName(briefAppName); if (procList.Length > 0) { ShowWindow(procList[0].MainWindowHandle, SW_RESTORE); SetForegroundWindow(procList[0].MainWindowHandle); }} | {
"score": 5,
"source": [
"https://Stackoverflow.com/questions/46030",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1358/"
]
} |
46,079 | Details: Only disable after user clicks the submit button, but before the posting back to the server ASP.NET Webforms (.NET 1.1) Prefer jQuery (if any library at all) Must be enabled if form reloads (i.e. credit card failed) This isn't a necessity that I do this, but if there is a simple way to do it without having to change too much, I'll do it. (i.e. if there isn't a simple solution, I probably won't do it, so don't worry about digging too deep) | For all submit buttons, via JQuery, it'd be: $('input[type=submit]').click(function() { this.disabled = true; }); Or it might be more useful to do so on form submission: $('form').submit(function() { $('input[type=submit]', this).attr("disabled","disabled");}); But I think we could give a better answer to your question if we knew a bit more about the context. If this is an ajax request, then you'll need to make sure you enable submit buttons again on either success or failure. If this is a standard HTTP form submission (aside from disabling the button with javascript) and you're doing this to safe guard from multiple submissions of the same form, then you ought to have some sort of control in the code that deals with the submitted data, because disabling a button with javascript might not prevent multiple submissions. | {
"score": 5,
"source": [
"https://Stackoverflow.com/questions/46079",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1446/"
]
} |
46,080 | I'm using TortoiseSVN against the SourceForge SVN repository. I'd like to move a file from one folder to another in order to maintain its revision history. Is this possible? If so, how do you do it? (My current strategy has been to copy the file into the new folder and check it in and then delete the file from the current folder.) | Subversion has native support for moving files. svn move SOURCE DESTINATION See the online help (svn help move) for more information. | {
"score": 8,
"source": [
"https://Stackoverflow.com/questions/46080",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1463/"
]
} |
46,124 | I've seen people doing things like this in their HTML: <!--[if IE]> <link rel="stylesheet" href="ie.css" type="text/css" /><![endif]--> Does this work across all modern browsers and is there a list of browser types that will work with that kind of if statement? Edit Thanks Ross . Interesting to find out about gt, lt, gte, & lte . | This works across all browsers because anything except IE sees <!--IGNORED COMMENT--> . Only IE reads the comment if it contains a conditional clause. Have a look at this article You can also specify which version of IE. For example: <!--[if IE 8]><link rel="stylesheet type="text/css" href="ie8.css" /><![endif]--> | {
"score": 5,
"source": [
"https://Stackoverflow.com/questions/46124",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/305/"
]
} |
46,125 | I want to do this: //*fu which returns all nodes whose name ends in fu , such as <tarfu /> and <snafu /> , but not <fubar /> | Do something like: //*[ends-with(name(), 'fu')] For a good XPath reference, check out W3Schools . | {
"score": 6,
"source": [
"https://Stackoverflow.com/questions/46125",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
]
} |
46,155 | I'd like to check if the user input is an email address in JavaScript, before sending it to a server or attempting to send an email to it, to prevent the most basic mistyping. How could I achieve this? | Using regular expressions is probably the best way. You can see a bunch of tests here (taken from chromium ) const validateEmail = (email) => { return String(email) .toLowerCase() .match( /^(([^<>()[\]\\.,;:\s@"]+(\.[^<>()[\]\\.,;:\s@"]+)*)|(".+"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/ );}; Here's the example of a regular expression that accepts unicode: const re = /^(([^<>()[\]\.,;:\s@\"]+(\.[^<>()[\]\.,;:\s@\"]+)*)|(\".+\"))@(([^<>()[\]\.,;:\s@\"]+\.)+[^<>()[\]\.,;:\s@\"]{2,})$/i; But keep in mind that one should not rely only upon JavaScript validation. JavaScript can easily be disabled. This should be validated on the server side as well. Here's an example of the above in action: const validateEmail = (email) => { return email.match( /^(([^<>()[\]\\.,;:\s@\"]+(\.[^<>()[\]\\.,;:\s@\"]+)*)|(\".+\"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/ );};const validate = () => { const $result = $('#result'); const email = $('#email').val(); $result.text(''); if (validateEmail(email)) { $result.text(email + ' is valid :)'); $result.css('color', 'green'); } else { $result.text(email + ' is not valid :('); $result.css('color', 'red'); } return false;}$('#email').on('input', validate); <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script><label for="email">Enter an email address: </label><input id="email" /><h2 id="result"></h2> | {
"score": 14,
"source": [
"https://Stackoverflow.com/questions/46155",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/72/"
]
} |
46,214 | I'm looking for any way that I can improve the selector performance of a jQuery call. Specifically things like this: Is $("div.myclass") faster than $(".myclass") I would think it might be, but I don't know if jQuery is smart enough to limit the search by tag name first, etc. Anyone have any ideas for how to formulate a jQuery selector string for best performance? | There is no doubt that filtering by tag name first is much faster than filtering by classname. This will be the case until all browsers implement getElementsByClassName natively, as is the case with getElementsByTagName. | {
"score": 6,
"source": [
"https://Stackoverflow.com/questions/46214",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4541/"
]
} |
46,219 | If I have a <input id="uploadFile" type="file" /> tag, and a submit button, how do I determine, in IE6 (and above) if a file has been selected by the user. In FF, I just do: var selected = document.getElementById("uploadBox").files.length > 0; But that doesn't work in IE. | This works in IE (and FF, I believe): if(document.getElementById("uploadBox").value != "") { // you have a file} | {
"score": 8,
"source": [
"https://Stackoverflow.com/questions/46219",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/698/"
]
} |
46,220 | I'm writing my first iPhone app, so I haven't gotten around to figuring out much in the way of debugging.Essentially my app displays an image and when touched plays a short sound.When compiling and building the project in XCode, everything builds successfully, but when the app is run in the iPhone simulator, it crashes. I get the following error: Application Specific Information:iPhone Simulator 1.0 (70), iPhone OS 2.0 (5A331)*** Terminating app due to uncaught exception 'NSUnknownKeyException', reason: '[<UIView 0x34efd0> setValue:forUndefinedKey:]: this class is not key value coding-compliant for the key kramerImage.' kramerImage here is the image I'm using for the background. I'm not sure what NSUnknownKeyException means or why the class is not key value coding-compliant for the key. | (This isn't really iPhone specific - the same thing will happen in regular Cocoa). NSUnknownKeyException is a common error when using Key-Value Coding to access a key that the object doesn't have. The properties of most Cocoa objects can be accessing directly: [@"hello world" length] // Objective-C 1.0@"hello world".length // Objective-C 2.0 Or via Key-Value Coding: [@"hello world" valueForKey:@"length"] I would get an NSUnknownKeyException if I used the following line: [@"hello world" valueForKey:@"purpleMonkeyDishwasher"] because NSString does not have a property (key) called 'purpleMonkeyDishwasher'. Something in your code is trying to set a value for the key 'kramerImage' on an UIView, which (apparently) doesn't support that key. If you're using Interface Builder, it might be something in your nib. Find where 'kramerImage' is being used, and try to track it down from there. | {
"score": 6,
"source": [
"https://Stackoverflow.com/questions/46220",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2293/"
]
} |
46,231 | I'm working on an application where users have to make a call and type a verification number with the keypad of their phone. I would like to be able to detect if the number they type is correct or not. The phone system does not have access to a list of valid numbers, but instead, it will validate the number against an algorithm (like a credit card number). Here are some of the requirements : It must be difficult to type a valid random code It must be difficult to have a valid code if I make a typo (transposition of digits, wrong digit) I must have a reasonable number of possible combinations (let's say 1M) The code must be as short as possible, to avoid errors from the user Given these requirements, how would you generate such a number? EDIT : @Haaked: The code has to be numerical because the user types it with its phone. @matt b: On the first step, the code is displayed on a Web page, the second step is to call and type in the code. I don't know the user's phone number. Followup : I've found several algorithms to check the validity of numbers (See this interesting Google Code project : checkDigits ). | After some research, I think I'll go with the ISO 7064 Mod 97,10 formula. It seems pretty solid as it is used to validate IBAN (International Bank Account Number). The formula is very simple: Take a number : 123456 Apply the following formula to obtain the 2 digits checksum : mod(98 - mod(number * 100, 97), 97) => 76 Concat number and checksum to obtain the code => 12345676 To validate a code, verify that mod(code, 97) == 1 Test : mod(12345676, 97) = 1 => GOOD mod(21345676, 97) = 50 => BAD ! mod(12345678, 97) = 10 => BAD ! Apparently, this algorithm catches most of the errors. Another interesting option was the Verhoeff algorithm . It has only one verification digit and is more difficult to implement (compared to the simple formula above). | {
"score": 6,
"source": [
"https://Stackoverflow.com/questions/46231",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1130/"
]
} |
46,276 | I am a web-developer working in PHP. I have some limited experience with using Test Driven Development in C# desktop applications. In that case we used nUnit for the unit testing framework. I would like to start using TDD in new projects but I'm really not sure where to begin. What recommendations do you have for a PHP-based unit testing framework and what are some good resources for someone who is pretty new to the TDD concept? | I've used both PHPUnit & SimpleTest and I found SimpleTest to be easier to use. As far as TDD goes, I haven't had much luck with it in the purest sense. I think that's mainly a time/discipline issue on my part though. Adding tests after the fact has been somewhat useful but my favorite things to do is use write SimpleTest tests that test for specific bugs that I have to fix. That makes it very easy to verify that things are actually fixed and stay fixed. | {
"score": 6,
"source": [
"https://Stackoverflow.com/questions/46276",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3238/"
]
} |
46,282 | I am using a class library which represents some of its configuration in .xml. The configuration is read in using the XmlSerializer . Fortunately, the classes which represent the .xml use the XmlAnyElement attribute at which allows me to extend the configuration data for my own purposes without modifying the original class library. <?xml version="1.0" encoding="utf-8"?><Config> <data>This is some data</data> <MyConfig> <data>This is my data</data> </MyConfig></Config> This works well for deserialization. I am able to allow the class library to deserialize the .xml as normal and the I can use my own XmlSerializer instances with a XmlNodeReader against the internal XmlNode . public class Config{ [XmlElement] public string data; [XmlAnyElement] public XmlNode element;}public class MyConfig{ [XmlElement] public string data;}class Program{ static void Main(string[] args) { using (Stream fs = new FileStream(@"c:\temp\xmltest.xml", FileMode.Open)) { XmlSerializer xser1 = new XmlSerializer(typeof(Config)); Config config = (Config)xser1.Deserialize(fs); if (config.element != null) { XmlSerializer xser2 = new XmlSerializer(typeof(MyConfig)); MyConfig myConfig = (MyConfig)xser2.Deserialize(new XmlNodeReader(config.element)); } } } I need to create a utility which will allow the user to generate a new configuration file that includes both the class library configuration as well my own configuration, so new objects will be created which were not read from the .xml file. The question is how can I serialize the data back into .xml? I realize that I have to initially call XmlSerializer.Serialize on my data before calling the same method on the class library configuration. However, this requires that my data is represented by an XmlNode after calling Serialize . What is the best way to serialize an object into an XmlNode using the XmlSerializer ? Thanks, -kevin btw-- It looks like an XmlNodeWriter class written by Chris Lovett was available at one time from Microsoft, but the links are now broken. Does anyone know of an alternative location to get this class? | So you need to have your class contain custom configuration information, then serialize that class to XML, then make that serialized XML into an XML node: is that right? Could you just take the string created by the XMLSerializer and wrap that in it's own XML tags? XmlSerializer xs = new XmlSerializer(typeof(MyConfig));StringWriter xout = new StringWriter();xs.Serialize(xout, myConfig);XmlDocument x = new XmlDocument();x.LoadXml("<myConfig>" + xout.ToString() + "</myConfig>"); Now x is an XmlDocument containing one element, "<myconfig>", which has your serialized custom configuration in it. Is that at all what you're looking for? | {
"score": 5,
"source": [
"https://Stackoverflow.com/questions/46282",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4599/"
]
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.