source_id
int64 1
74.7M
| question
stringlengths 0
40.2k
| response
stringlengths 0
111k
| metadata
dict |
---|---|---|---|
46,324 | I'm going to guess that the answer is "no" based on the below error message (and this Google result ), but is there anyway to perform a cross-database query using PostgreSQL? databaseA=# select * from databaseB.public.someTableName;ERROR: cross-database references are not implemented: "databaseB.public.someTableName" I'm working with some data that is partitioned across two databases although data is really shared between the two (userid columns in one database come from the users table in the other database). I have no idea why these are two separate databases instead of schema, but c'est la vie... | Note: As the original asker implied, if you are setting up two databases on the same machine you probably want to make two schemas instead - in that case you don't need anything special to query across them. postgres_fdw Use postgres_fdw (foreign data wrapper) to connect to tables in any Postgres database - local or remote. Note that there are foreign data wrappers for other popular data sources . At this time, only postgres_fdw and file_fdw are part of the official Postgres distribution. For Postgres versions before 9.3 Versions this old are no longer supported, but if you need to do this in a pre-2013 Postgres installation, there is a function called dblink . I've never used it, but it is maintained and distributed with the rest of PostgreSQL. If you're using the version of PostgreSQL that came with your Linux distro, you might need to install a package called postgresql-contrib. | {
"score": 8,
"source": [
"https://Stackoverflow.com/questions/46324",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4249/"
]
} |
46,338 | I am writing a webapp using CodeIgniter that requires authentication. I created a model which handles all my authentication. However, I can't find a way to access this authentication model from inside another model. Is there a way to access a model from inside another mode, or a better way to handle authentication inside CodeIgniter? | In general, you don't want to create objects inside an object. That's a bad habit, instead, write a clear API and inject a model into your model. <?php// in your controller$model1 = new Model1();$model2 = new Model2();$model2->setWhatever($model1);?> | {
"score": 5,
"source": [
"https://Stackoverflow.com/questions/46338",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/889/"
]
} |
46,347 | Is there a clean way to redirect all attempts to going to an HTTP:// version of a site to its HTTPS:// equivalent? | I think the cleanest way is as described here on IIS-aid.com . It's web.config only and so if you change server you don't have to remember all the steps you went through with the 403.4 custom error page or other special permissions, it just works. <configuration> <system.webServer> <rewrite> <rules> <rule name="HTTP to HTTPS redirect" stopProcessing="true"> <match url="(.*)" /> <conditions> <add input="{HTTPS}" pattern="off" ignoreCase="true" /> </conditions> <action type="Redirect" redirectType="Permanent" url="https://{HTTP_HOST}/{R:1}" /> </rule> </rules> </rewrite> </system.webServer></configuration> | {
"score": 8,
"source": [
"https://Stackoverflow.com/questions/46347",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2312/"
]
} |
46,354 | I'm trying to perform a SQL query through a linked SSAS server. The initial query works fine: SELECT "Ugly OLAP name" as "Value" FROM OpenQuery( OLAP, 'OLAP Query') But if I try to add: WHERE "Value" > 0 I get an error Invalid column name 'Value' Any ideas what I might be doing wrong? So the problem was that the order in which elements of the query are processed are different that the order they are written. According to this source: http://blogs.x2line.com/al/archive/2007/06/30/3187.aspx The order of evaluation in MSSQL is: FROM ON JOIN WHERE GROUP BY HAVING SELECT ORDER BY So the alias wasn't processed until after the WHERE and HAVING clauses. | This should work: SELECT A.ValueFROM (SELECT "Ugly OLAP name" as "Value" FROM OpenQuery( OLAP, 'OLAP Query')) AS aWHERE a.Value > 0 It's not that Value is a reserved word, the problem is that it's a column alias, not the column name. By making it an inline view, "Value" becomes the column name and can then be used in a where clause. | {
"score": 5,
"source": [
"https://Stackoverflow.com/questions/46354",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1807/"
]
} |
46,376 | (This is a followup to my previous question about measuring .NET remoting traffic.) When I am testing our Windows service / service controller GUI combination, it is often most convenient to run both pieces on my development box. With this setup, the remoting traffic between the two is via loopback, not through the Ethernet card. Are there any software packet sniffers that can capture loopback traffic on a WinXP machine? Wireshark is a great package, but it can only capture external traffic on a Windows machine, not loopback. | What you should do is to run RawCap, which is a sniffer that can capture traffic to/from the loopback interface in Windows. Just start it with "RawCap.exe 127.0.0.1 loopback.pcap". You can then open up loopback.pcap in Wireshark or NetworkMiner to look at the network traffic. You can find RawCap here: http://www.netresec.com/?page=RawCap Good Luck! | {
"score": 5,
"source": [
"https://Stackoverflow.com/questions/46376",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3776/"
]
} |
46,377 | What is the syntax for placing constraints on multiple types? The basic example: class Animal<SpeciesType> where SpeciesType : Species I would like to place constraints on both types in the following definition such that SpeciesType must inherit from Species and OrderType must inherit from Order : class Animal<SpeciesType, OrderType> | public class Animal<SpeciesType,OrderType> where SpeciesType : Species where OrderType : Order{} | {
"score": 7,
"source": [
"https://Stackoverflow.com/questions/46377",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/327/"
]
} |
46,380 | If you've used Oracle, you've probably gotten the helpful message "ORA-00942: Table or view does not exist". Is there a legitimate technical reason the message doesn't include the name of the missing object? Arguments about this being due to security sound like they were crafted by the TSA. If I'm an attacker, I'd know what table I just attempted to exploit, and be able to interpret this unhelpful message easily. If I'm a developer working with a complex join through several layers of application code, it's often very difficult to tell. My guess is that when this error was originally implemented, someone neglected to add the object name, and now, people are afraid it will break compatibility to fix it. (Code doing silly things like parsing the error message will be confused if it changes.) Is there a developer-friendly (as opposed to recruiting your DBA) way to determine the name of the missing table? Although I've accepted an answer which is relevant to the topic, it doesn't really answer my question: Why isn't the name part of the error message? If anyone can come up with the real answer, I'll be happy to change my vote. | You can set an EVENT in your parameter file (plain text or spfile) to force Oracle to dump a detailed trace file in the user_dump_dest, the object name might be in there, if not the SQL should be. EVENT="942 trace name errorstack level 12" If you are using a plain text file you need to keep all your EVENT settings on consecutive lines. Not sure how that applied to spfile. | {
"score": 5,
"source": [
"https://Stackoverflow.com/questions/46380",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3474/"
]
} |
46,385 | What's the best way to delete all rows from a table in sql but to keep n number of rows on the top? | DELETE FROM Table WHERE ID NOT IN (SELECT TOP 10 ID FROM Table) Edit: Chris brings up a good performance hit since the TOP 10 query would be run for each row. If this is a one time thing, then it may not be as big of a deal, but if it is a common thing, then I did look closer at it. | {
"score": 7,
"source": [
"https://Stackoverflow.com/questions/46385",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/298/"
]
} |
46,483 | What are the differences between htmlspecialchars() and htmlentities() . When should I use one or the other? | From the PHP documentation for htmlentities : This function is identical to htmlspecialchars() in all ways, except with htmlentities() , all characters which have HTML character entity equivalents are translated into these entities. From the PHP documentation for htmlspecialchars : Certain characters have special significance in HTML, and should be represented by HTML entities if they are to preserve their meanings. This function returns a string with some of these conversions made; the translations made are those most useful for everyday web programming. If you require all HTML character entities to be translated, use htmlentities() instead. The difference is what gets encoded. The choices are everything (entities) or "special" characters, like ampersand, double and single quotes, less than, and greater than (specialchars). I prefer to use htmlspecialchars whenever possible. For example: echo htmlentities('<Il était une fois un être>.'); // Output: <Il était une fois un être>. // ^^^^^^^^ ^^^^^^^ echo htmlspecialchars('<Il était une fois un être>.'); // Output: <Il était une fois un être>. // ^ ^ | {
"score": 10,
"source": [
"https://Stackoverflow.com/questions/46483",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4137/"
]
} |
46,496 | Today I had a coworker suggest I refactor my code to use a label statement to control flow through 2 nested for loops I had created. I've never used them before because personally I think they decrease the readability of a program. I am willing to change my mind about using them if the argument is solid enough however. What are people's opinions on label statements? | Many algorithms are expressed more easily if you can jump across two loops (or a loop containing a switch statement). Don't feel bad about it. On the other hand, it may indicate an overly complex solution. So stand back and look at the problem. Some people prefer a "single entry, single exit" approach to all loops. That is to say avoiding break (and continue) and early return for loops altogether. This may result in some duplicate code. What I would strongly avoid doing is introducing auxilary variables. Hiding control-flow within state adds to confusion. Splitting labeled loops into two methods may well be difficult. Exceptions are probably too heavyweight. Try a single entry, single exit approach. | {
"score": 7,
"source": [
"https://Stackoverflow.com/questions/46496",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2628/"
]
} |
46,512 | In the build log I'd like to the start and end time of each project's compilation. Is there any way to get VS to do this? | For VC++ builds you can enable build timing. Go to Tools->Options->Projects and Solutions->VC++ Project settings and choose the option for 'Build Timing' | {
"score": 5,
"source": [
"https://Stackoverflow.com/questions/46512",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4790/"
]
} |
46,541 | Name the design considerations in deciding between use of a singleton versus a static class. In doing this, you're kind of forced to contrast the two, so whatever contrasts you can come up with are also useful in showing your thought process! Also, every interviewer likes to see illustrative examples. :) | Singletons can implement interfaces and inherit from other classes. Singletons can be lazy loaded. Only when it is actually needed. That's very handy if the initialisation includes expensive resource loading or database connections. Singletons offer an actual object. Singletons can be extended into a factory. The object management behind the scenes is abstract so it's better maintainable and results in better code. | {
"score": 7,
"source": [
"https://Stackoverflow.com/questions/46541",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3594/"
]
} |
46,545 | How do I do backups in MySQL? I'm hoping there'll be something better than just running mysqldump every "x" hours. Is there anything like SQL Server has, where you can take a full backup each day, and then incrementals every hour, so if your DB dies you can restore up to the latest backup? Something like the DB log, where as long as the log doesn't die, you can restore up to the exact point where the DB died? Also, how do these things affect locking?I'd expect the online transactions to be locked for a while if I do a mysqldump. | You might want to look at incremental backups . | {
"score": 5,
"source": [
"https://Stackoverflow.com/questions/46545",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3314/"
]
} |
46,571 | I have been tasked with going through a number of ColdFusion sites that have recently been the subject of a rather nasty SQL Injection attack. Basically my work involves adding <cfqueryparam > tags to all of the inline sql. For the most part I've got it down, but can anybody tell me how to use cfqueryparam with the LIKE operator? If my query looks like this: select * from Foo where name like '%Bob%' what should my <cfqueryparam > tag look like? | @Joel, I have to disagree. select a,b,cfrom Foowhere name like <cfqueryparam cfsqltype="columnType" value="%#variables.someName#%" /> Never suggest to someone that they should "select star." Bad form! Even for an example! (Even copied from the question!) The query is pre-compiled and you should include the wild card character(s) as part of the parameter being passed to the query. This format is more readable and will run more efficiently. When doing string concatenation, use the ampersand operator (&), not the plus sign. Technically, in most cases, plus will work just fine... until you throw a NumberFormat() in the middle of the string and start wondering why you're being told that you're not passing a valid number when you've checked and you are. | {
"score": 7,
"source": [
"https://Stackoverflow.com/questions/46571",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3271/"
]
} |
46,582 | We have the requirement to take a form submission and save some data, then redirect the user to a page offsite, but in redirecting, we need to "submit" a form with POST, not GET. I was hoping there was an easy way to accomplish this, but I'm starting to think there isn't. I think I must now create a simple other page, with just the form that I want, redirect to it, populate the form variables, then do a body.onload call to a script that merely calls document.forms[0].submit(); Can anyone tell me if there is an alternative? We might need to tweak this later in the project, and it might get sort of complicated, so if there was an easy we could do this all non-other page dependent that would be fantastic. Anyway, thanks for any and all responses. | Doing this requires understanding how HTTP redirects work. When you use Response.Redirect() , you send a response (to the browser that made the request) with HTTP Status Code 302 , which tells the browser where to go next. By definition, the browser will make that via a GET request, even if the original request was a POST . Another option is to use HTTP Status Code 307 , which specifies that the browser should make the redirect request in the same way as the original request, but to prompt the user with a security warning. To do that, you would write something like this: public void PageLoad(object sender, EventArgs e){ // Process the post on your side Response.Status = "307 Temporary Redirect"; Response.AddHeader("Location", "http://example.com/page/to/post.to");} Unfortunately, this won't always work. Different browsers implement this differently , since it is not a common status code. Alas, unlike the Opera and FireFox developers, the IE developers have never read the spec, and even the latest, most secure IE7 will redirect the POST request from domain A to domain B without any warnings or confirmation dialogs! Safari also acts in an interesting manner, while it does not raise a confirmation dialog and performs the redirect, it throws away the POST data, effectively changing 307 redirect into the more common 302. So, as far as I know, the only way to implement something like this would be to use Javascript. There are two options I can think of off the top of my head: Create the form and have its action attribute point to the third-party server. Then, add a click event to the submit button that first executes an AJAX request to your server with the data, and then allows the form to be submitted to the third-party server. Create the form to post to your server. When the form is submitted, show the user a page that has a form in it with all of the data you want to pass on, all in hidden inputs. Just show a message like "Redirecting...". Then, add a javascript event to the page that submits the form to the third-party server. Of the two, I would choose the second, for two reasons. First, it is more reliable than the first because Javascript is not required for it to work; for those who don't have it enabled, you can always make the submit button for the hidden form visible, and instruct them to press it if it takes more than 5 seconds. Second, you can decide what data gets transmitted to the third-party server; if you use just process the form as it goes by, you will be passing along all of the post data, which is not always what you want. Same for the 307 solution, assuming it worked for all of your users. Hope this helps! | {
"score": 9,
"source": [
"https://Stackoverflow.com/questions/46582",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/232/"
]
} |
46,585 | From what I can gather, there are three categories: Never use GET and use POST Never use POST and use GET It doesn't matter which one you use. Am I correct in assuming those three cases? If so, what are some examples from each case? | Use POST for destructive actions such as creation (I'm aware of the irony), editing, and deletion, because you can't hit a POST action in the address bar of your browser. Use GET when it's safe to allow a person to call an action. So a URL like: http://myblog.org/admin/posts/delete/357 Should bring you to a confirmation page, rather than simply deleting the item. It's far easier to avoid accidents this way. POST is also more secure than GET , because you aren't sticking information into a URL. And so using GET as the method for an HTML form that collects a password or other sensitive information is not the best idea. One final note: POST can transmit a larger amount of information than GET . 'POST' has no size restrictions for transmitted data, whilst 'GET' is limited to 2048 characters. | {
"score": 10,
"source": [
"https://Stackoverflow.com/questions/46585",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/572/"
]
} |
46,586 | Everyone is aware of Dijkstra's Letters to the editor: go to statement considered harmful (also here .html transcript and here .pdf) and there has been a formidable push since that time to eschew the goto statement whenever possible. While it's possible to use goto to produce unmaintainable, sprawling code, it nevertheless remains in modern programming languages . Even the advanced continuation control structure in Scheme can be described as a sophisticated goto. What circumstances warrant the use of goto? When is it best to avoid? As a follow-up question: C provides a pair of functions, setjmp() and longjmp(), that provide the ability to goto not just within the current stack frame but within any of the calling frames. Should these be considered as dangerous as goto? More dangerous? Dijkstra himself regretted that title, for which he was not responsible. At the end of EWD1308 (also here .pdf) he wrote: Finally a short story for the record.In 1968, the Communications of the ACMpublished a text of mine under thetitle " The goto statement consideredharmful ", which in later years wouldbe most frequently referenced,regrettably, however, often by authorswho had seen no more of it than itstitle, which became a cornerstone ofmy fame by becoming a template: wewould see all sorts of articles underthe title "X considered harmful" foralmost any X, including one titled"Dijkstra considered harmful". Butwhat had happened? I had submitted apaper under the title " A case againstthe goto statement ", which, in orderto speed up its publication, theeditor had changed into a "letter tothe Editor", and in the process he hadgiven it a new title of his owninvention! The editor was NiklausWirth. A well thought out classic paper about this topic, to be matched to that of Dijkstra, is Structured Programming with go to Statements , by Donald E. Knuth. Reading both helps to reestablish context and a non-dogmatic understanding of the subject. In this paper, Dijkstra's opinion on this case is reported and is even more strong: Donald E. Knuth: I believe that by presenting such aview I am not in fact disagreeingsharply with Dijkstra's ideas, sincehe recently wrote the following:"Please don't fall into the trap ofbelieving that I am terriblydogmatical about [the go tostatement]. I have the uncomfortablefeeling that others are making areligion out of it, as if theconceptual problems of programmingcould be solved by a single trick, bya simple form of coding discipline! " | The following statements are generalizations; while it is always possible to plead exception, it usually (in my experience and humble opinion) isn't worth the risks. Unconstrained use of memory addresses (either GOTO or raw pointers) provides too many opportunities to make easily avoidable mistakes. The more ways there are to arrive at a particular "location" in the code, the less confident one can be about what the state of the system is at that point. (See below.) Structured programming IMHO is less about "avoiding GOTOs" and more about making the structure of the code match the structure of the data. For example, a repeating data structure (e.g. array, sequential file, etc.) is naturally processed by a repeated unit of code. Having built-in structures (e.g. while, for, until, for-each, etc.) allows the programmer to avoid the tedium of repeating the same cliched code patterns. Even if GOTO is low-level implementation detail (not always the case!) it's below the level that the programmer should be thinking. How many programmers balance their personal checkbooks in raw binary? How many programmers worry about which sector on the disk contains a particular record, instead of just providing a key to a database engine (and how many ways could things go wrong if we really wrote all of our programs in terms of physical disk sectors)? Footnotes to the above: Regarding point 2, consider the following code: a = b + 1 /* do something with a */ At the "do something" point in the code, we can state with high confidence that a is greater than b . (Yes, I'm ignoring the possibility of untrapped integer overflow. Let's not bog down a simple example.) On the other hand, if the code had read this way: ... goto 10 ... a = b + 1 10: /* do something with a */ ... goto 10 ... The multiplicity of ways to get to label 10 means that we have to work much harder to be confident about the relationships between a and b at that point. (In fact, in the general case it's undecideable!) Regarding point 4, the whole notion of "going someplace" in the code is just a metaphor. Nothing is really "going" anywhere inside the CPU except electrons and photons (for the waste heat). Sometimes we give up a metaphor for another, more useful, one. I recall encountering (a few decades ago!) a language where if (some condition) { action-1 } else { action-2 } was implemented on a virtual machine by compiling action-1 and action-2 as out-of-line parameterless routines, then using a single two-argument VM opcode which used the boolean value of the condition to invoke one or the other. The concept was simply "choose what to invoke now" rather than "go here or go there". Again, just a change of metaphor. | {
"score": 9,
"source": [
"https://Stackoverflow.com/questions/46586",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/658/"
]
} |
46,636 | What's the best way to copy a file from a network share to the local file system using a Windows batch file? Normally, I would use "net use *" but using this approach how can I get the drive letter? | Can you just use the full UNC path to the file? copy \\myserver\myshare\myfolder\myfile.txt c:\myfiles | {
"score": 5,
"source": [
"https://Stackoverflow.com/questions/46636",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4778/"
]
} |
46,663 | Is it possible to send an email from my Java application using a GMail account? I have configured my company mail server with Java app to send email, but that's not going to cut it when I distribute the application. Answers with any of using Hotmail, Yahoo or GMail are acceptable. | First download the JavaMail API and make sure the relevant jar files are in your classpath. Here's a full working example using GMail. import java.util.*;import javax.mail.*;import javax.mail.internet.*;public class Main { private static String USER_NAME = "*****"; // GMail user name (just the part before "@gmail.com") private static String PASSWORD = "********"; // GMail password private static String RECIPIENT = "[email protected]"; public static void main(String[] args) { String from = USER_NAME; String pass = PASSWORD; String[] to = { RECIPIENT }; // list of recipient email addresses String subject = "Java send mail example"; String body = "Welcome to JavaMail!"; sendFromGMail(from, pass, to, subject, body); } private static void sendFromGMail(String from, String pass, String[] to, String subject, String body) { Properties props = System.getProperties(); String host = "smtp.gmail.com"; props.put("mail.smtp.starttls.enable", "true"); props.put("mail.smtp.host", host); props.put("mail.smtp.user", from); props.put("mail.smtp.password", pass); props.put("mail.smtp.port", "587"); props.put("mail.smtp.auth", "true"); Session session = Session.getDefaultInstance(props); MimeMessage message = new MimeMessage(session); try { message.setFrom(new InternetAddress(from)); InternetAddress[] toAddress = new InternetAddress[to.length]; // To get the array of addresses for( int i = 0; i < to.length; i++ ) { toAddress[i] = new InternetAddress(to[i]); } for( int i = 0; i < toAddress.length; i++) { message.addRecipient(Message.RecipientType.TO, toAddress[i]); } message.setSubject(subject); message.setText(body); Transport transport = session.getTransport("smtp"); transport.connect(host, from, pass); transport.sendMessage(message, message.getAllRecipients()); transport.close(); } catch (AddressException ae) { ae.printStackTrace(); } catch (MessagingException me) { me.printStackTrace(); } }} Naturally, you'll want to do more in the catch blocks than print the stack trace as I did in the example code above. (Remove the catch blocks to see which method calls from the JavaMail API throw exceptions so you can better see how to properly handle them.) Thanks to @jodonnel and everyone else who answered. I'm giving him a bounty because his answer led me about 95% of the way to a complete answer. | {
"score": 9,
"source": [
"https://Stackoverflow.com/questions/46663",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1288/"
]
} |
46,704 | For the following HTML: <form name="myForm"> <label>One<input name="area" type="radio" value="S" /></label> <label>Two<input name="area" type="radio" value="R" /></label> <label>Three<input name="area" type="radio" value="O" /></label> <label>Four<input name="area" type="radio" value="U" /></label></form> Changing from the following JavaScript code: $(function() { var myForm = document.myForm; var radios = myForm.area; // Loop through radio buttons for (var i=0; i<radios.length; i++) { if (radios[i].value == "S") { radios[i].checked = true; // Selected when form displays radioClicks(); // Execute the function, initial setup } radios[i].onclick = radioClicks; // Assign to run when clicked } }); Thanks EDIT: The response I selected answers the question I asked, however I like the answer that uses bind() because it also shows how to distinguish the group of radio buttons | $( function() { $("input:radio") .click(radioClicks) .filter("[value='S']") .attr("checked", "checked");}); | {
"score": 5,
"source": [
"https://Stackoverflow.com/questions/46704",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2755/"
]
} |
46,718 | I'm just curious how most people make their ASP.NET pages printer-friendly? Do you create a separate printer-friendly version of the ASPX page, use CSS or something else? How do you handle situations like page breaks and wide tables? Is there one elegant solution that works for the majority of the cases? | You basically make another CSS file that hide things or gives simpler "printer-friendly" style to things then add that with a media="print" so that it only applies to print media (when it is printed) <link rel="stylesheet" type="text/css" media="print" href="print.css" /> | {
"score": 5,
"source": [
"https://Stackoverflow.com/questions/46718",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3329/"
]
} |
46,788 | Is there a way to bind a MemoryStream to asp:image control? | Best bet is to create an HttpHandler that would return the image. Then bind the ImageUrl property on the asp:Image to the url of the HttpHandler. Here is some code. First create the HttpHandler: <%@ WebHandler Language="C#" Class="ImageHandler" %>using System.Drawing;using System.Drawing.Imaging;using System.IO;using System.Web;public class ImageHandler : IHttpHandler{ public void ProcessRequest (HttpContext context) { context.Response.Clear(); if (!String.IsNullOrEmpty(context.Request.QueryString["id"])) { int id = Int32.Parse(context.Request.QueryString["id"]); // Now you have the id, do what you want with it, to get the right image // More than likely, just pass it to the method, that builds the image Image image = GetImage(id); // Of course set this to whatever your format is of the image context.Response.ContentType = "image/jpeg"; // Save the image to the OutputStream image.Save(context.Response.OutputStream, ImageFormat.Jpeg); } else { context.Response.ContentType = "text/html"; context.Response.Write("<p>Need a valid id</p>"); } } public bool IsReusable { get { return false; } } private Image GetImage(int id) { // Not sure how you are building your MemoryStream // Once you have it, you just use the Image class to // create the image from the stream. MemoryStream stream = new MemoryStream(); return Image.FromStream(stream); }} Next, just call it inside your aspx page where you are using the asp:Image. <%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="_Default" %><!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"><html xmlns="http://www.w3.org/1999/xhtml"><head runat="server"> <title></title></head><body> <form id="form1" runat="server"> <div> <asp:Image ID="myImage" ImageUrl="~/ImageHandler.ashx?id=1" runat="server" /> </div> </form></body></html> And that is it. | {
"score": 5,
"source": [
"https://Stackoverflow.com/questions/46788",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4215/"
]
} |
46,805 | I want to use an image or icon as a custom cursor in WPF app. How can I do that? | You have two basic options: When the mouse cursor is over your control, hide the system cursor by setting this.Cursor = Cursors.None; and draw your own cursor using whatever technique you like. Then, update the position and appearance of your cursor by responding to mouse events. Here are two examples: http://www.xamlog.com/2006/07/17/creating-a-custom-cursor/ http://www.hanselman.com/blog/DeveloperDesigner.aspx Additional examples can be found here: WPF Tutorial - How To Use Custom Cursors Setting the Cursor to Render Some Text While Dragging Getting fancy and using the Visual we are dragging for feedback [instead of a cursor] How can I drag and drop items between data bound ItemsControls? Create a new Cursor object by loading an image from a .cur or .ani file. You can create and edit these kinds of files in Visual Studio. There are also some free utilites floating around for dealing with them. Basically they're images (or animated images) which specify a "hot spot" indicating what point in the image the cursor is positioned at. If you choose to load from a file, note that you need an absolute file-system path to use the Cursor(string fileName) constructor. Lamely, a relative path or Pack URI will not work. If you need to load the cursor from a relative path or from a resource packed with your assembly, you will need to get a stream from the file and pass it in to the Cursor(Stream cursorStream) constructor. Annoying but true. On the other hand, specifying a cursor as a relative path when loading it using a XAML attribute does work, a fact you could use to get your cursor loaded onto a hidden control and then copy the reference to use on another control. I haven't tried it, but it should work. | {
"score": 6,
"source": [
"https://Stackoverflow.com/questions/46805",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1133/"
]
} |
46,827 | Visual Studio 2005 doesn't provide an interface for creating relationships between tables in a SQL Server CE database (I'm using version 3.0) and you can't open a Compact Edition DB using Management Studio as far as I know. Any ideas? | Unfortunately there is currently no designer support (unlike for SQL Server 2005) for building relationships between tables in SQL Server CE. To build relationships you need to use SQL commands such as: ALTER TABLE OrdersADD CONSTRAINT FK_Customer_OrderFOREIGN KEY (CustomerId) REFERENCES Customers(CustomerId) If you are doing CE development, i would recomend this FAQ: EDIT : In Visual Studio 2008 this is now possible to do in the GUI by right-clicking on your table. | {
"score": 7,
"source": [
"https://Stackoverflow.com/questions/46827",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1943/"
]
} |
46,898 | If I have an object implementing the Map interface in Java and I wish to iterate over every pair contained within it, what is the most efficient way of going through the map? Will the ordering of elements depend on the specific map implementation that I have for the interface? | Map<String, String> map = ...for (Map.Entry<String, String> entry : map.entrySet()) { System.out.println(entry.getKey() + "/" + entry.getValue());} On Java 10+: for (var entry : map.entrySet()) { System.out.println(entry.getKey() + "/" + entry.getValue());} | {
"score": 13,
"source": [
"https://Stackoverflow.com/questions/46898",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4807/"
]
} |
46,909 | I have a situation where I might have multiple instances of a program running at once, and it's important that just one specific function not be executing in more than one of these instances at once. Is this the proper way to use a mutex to prevent this from happening? lock (this.GetType()) { _log.Info("Doing Sync"); DoSync(); _log.Info("Sync Completed");} | You said multiple instances of one application, so we're talking about two program.exe's running, right? The lock statement won't lock across multiple programs, just within the program. If you want a true Mutex, look at the System.Threading.Mutex object. Here is a usage example: bool createdNew;using (Mutex mtx = new Mutex(false, "MyAwesomeMutex", out createdNew)){ try { mtx.WaitOne(); MessageBox.Show("Click OK to release the mutex."); } finally { mtx.ReleaseMutex(); }} The createdNew variable will let you know whether or not it was created the first time. It only tells you if it has been created, though. If you want to acquire the lock, you need to call WaitOne and then call ReleaseMutex to release it. If you just want to see if you created a Mutex, just constructing it is fine. | {
"score": 5,
"source": [
"https://Stackoverflow.com/questions/46909",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1512/"
]
} |
46,918 | What is the proper way to minimize a WinForms app to the system tray? Note: minimize to system tray ; on the right side of the taskbar by the clock. I'm not asking about minimizing to taskbar, which is what happens when you hit the "minus" button on the window. I've seen hackish solutions like, "minimize, set ShowInTaskbar = false, then show your NotifyIcon." Solutions like that are hackish because the app doesn't appear to minimize to the tray like other apps, the code has to detect when to set ShowInTaskbar = true, among other issues. What's the proper way to do this? | There is actually no managed way to do that form of animation to the tray in native winforms, however you can P/Invoke shell32.dll to do it: Some good info here (In the comments not the post): http://blogs.msdn.com/jfoscoding/archive/2005/10/20/483300.aspx And here it is in C++: http://www.codeproject.com/KB/shell/minimizetotray.aspx You can use that to figure out what stuff to Pinvoke for your C# version. | {
"score": 5,
"source": [
"https://Stackoverflow.com/questions/46918",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/536/"
]
} |
46,933 | I'm having some inheritance issues as I've got a group of inter-related abstract classes that need to all be overridden together to create a client implementation. Ideally I would like to do something like the following: abstract class Animal{ public Leg GetLeg() {...}}abstract class Leg { }class Dog : Animal{ public override DogLeg Leg() {...}}class DogLeg : Leg { } This would allow anyone using the Dog class to automatically get DogLegs and anyone using the Animal class to get Legs. The problem is that the overridden function has to have the same type as the base class so this will not compile. I don't see why it shouldn't though, since DogLeg is implicitly castable to Leg. I know there are plenty of ways around this, but I'm more curious why this isn't possible/implemented in C#. EDIT : I modified this somewhat, since I'm actually using properties instead of functions in my code. EDIT : I changed it back to functions, because the answer only applies to that situation (covariance on the value parameter of a property's set function shouldn't work). Sorry for the fluctuations! I realize it makes a lot of the answers seem irrelevant. | The short answer is that GetLeg is invariant in its return type. The long answer can be found here: Covariance and contravariance I'd like to add that while inheritance is usually the first abstraction tool that most developers pull out of their toolbox, it is almost always possible to use composition instead. Composition is slightly more work for the API developer, but makes the API more useful for its consumers. | {
"score": 5,
"source": [
"https://Stackoverflow.com/questions/46933",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/327/"
]
} |
46,982 | I am trying to improve the performance of a web application. I have metrics that I can use to optimize the time taken to return the main HTML page, but I'm concerned about the external CSS and JavaScript files that are included from these HTML pages. These are served statically, with HTTP Expires headers, but are shared between all the pages of the application. I'm concerned that the browser has to parse these CSS and JavaScript files for each page that is displayed and so having all the CSS and JavaScript for the site shared into common files will negatively affect performance. Should I be trying to split out these files so I link from each page to only the CSS and JavaScript needed for that page, or would I get little return for my efforts? Are there any tools that could help me generate metrics for this? | Context: While it's true that HTTP overhead is more significant than parsing JS and CSS, ignoring the impact of parsing on browser performance (even if you have less than a meg of JS) is a good way to get yourself in trouble. YSlow, Fiddler, and Firebug are not the best tools to monitor parsing speed. Unless they've been updated very recently, they don't separate the amount of time required to fetch JS over HTTP or load from cache versus the amount of time spent parsing the actual JS payload. Parse speed is slightly difficult to measure, but we've chased this metric a number of times on projects I've worked on and the impact on pageloads were significant even with ~500k of JS. Obviously the older browsers suffer the most...hopefully Chrome, TraceMonkey and the like help resolve this situation. Suggestion: Depending on the type of traffic you have at your site, it may be well worth your while to split up your JS payload so some large chunks of JS that will never be used on a the most popular pages are never sent down to the client. Of course, this means that when a new client hits a page where this JS is needed, you'll have to send it over the wire. However, it may well be the case that, say, 50% of your JS is never needed by 80% of your users due to your traffic patterns. If this is so, you should definitely user smaller, packaged JS payloads only on pages where the JS is necessary. Otherwise 80% of your users will suffer unnecessary JS parsing penalties on every single pageload . Bottom Line: It's difficult to find the proper balance of JS caching and smaller, packaged payloads, but depending on your traffic pattern it's definitely well worth considering a technique other than smashing all of your JS into every single pageload. | {
"score": 5,
"source": [
"https://Stackoverflow.com/questions/46982",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2649/"
]
} |
47,003 | I'm looking at working on a project which uses C#.NET (sitting on a windows box) as the primary language and PostgreSQL as the backend database (backend is sitting on a linux box). I've heard that ODBC.NET allows for easy integration of these two components. Has anyone had experience actually setting C# and PostgreSQL up to work together? If so, do you have any suggestions about how to go about it, issues you've found, etc.? | I'm working with C# and Postgres using Npgsql2 component, and they work fast, I recommend you. You can download from https://github.com/npgsql/Npgsql/releases Note: If you want an application that works with any database you can use the DbProviderFactory class and make your queries using IDbConnection , IDbCommand , IDataReader and/or IDbTransaction interfaces. | {
"score": 7,
"source": [
"https://Stackoverflow.com/questions/47003",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/145/"
]
} |
47,007 | A question that occasionally arises is what is the best way to determine the changelist that you last synced to in Perforce. This is often needed for things like injecting the changelist number into the revision info by the automatic build system. | I recommend the opposite for automatic build systems: you should first get the latest changelist from the server using: p4 changes -s submitted -m1 then sync to that change and record it in the revision info. The reason is as follows. Although Perforce recommends the following to determine the changelist to which the workspace is synced: p4 changes -m1 @clientname they note a few gotchas: This only works if you have not submitted anything from the workspace in question. It is also possible that a client workspace is not synced to any specific changelist. and there's an additional gotcha they don't mention: If the highest changelist to which the sync occured strictly deleted files from the workspace, the next-highest changelist will be reported (unless it, too, strictly deleted files). If you must sync first and record later, Perforce recommends running the following command to determine if you've been bit by the above gotchas; it should indicate nothing was synced or removed: p4 sync -n @changelist_number | {
"score": 8,
"source": [
"https://Stackoverflow.com/questions/47007",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2102/"
]
} |
47,022 | I've somehow managed to get an SVN repository into a bad state. I've moved a directory and now I can't commit it in its new location. As far as svn status is concerned, the directory is unknown (the name of the directory is type ). $ svn status? type When I try to add the directory, the server says it already exists. $ svn add typesvn: warning: 'type' is already under version control If I try to update the directory, it's gone again. $ svn update typesvn: '.' is not under version control If I try to commit it, the server complains that it's old parent directory no longer exists. $ svn commit type -m "Moving type"svn: Commit failed (details follow):svn: '/prior/trunk/src/nyu/prior/cvc3/theorem_prover/expression' path not found To add to the mystery, the contents of the directory are marked as modified. $ svn status typeA + typeM + type/IntegerType.javaM + type/BooleanType.javaM + type/Type.javaM + type/RationalRangeType.javaM + type/RationalType.javaM + type/IntegerRangeType.java If I try to update from within the directory, I get this. $ cd type$ svn updatesvn: Two top-level reports with no target Committing from within the directory gives the same path not found error as above. What's going on and how do I fix it? EDIT: @Rob Oxspring caught me out: I got too aggressive moving things around in Eclipse. UPDATE: I'm accepting @Rob Oxspring's answer of "don't do that/just start over" and taking his advice. I'd still be interested if anybody could tell me: (a) what the above error messages mean precisely and (b) how to actually fix the problem. | It looks to me like type was created by some Subversion-aware copy command, then moved into the current directory using a Subversion-unaware copy. In my experience, this sort of thing typically occurs when package refactoring operations have been chained together in Eclipse without commits in between. Typically, Subversion doesn't handle it well when you copy/move a locally copied/moved file or folder, although I think version 1.5 may handle it better. To avoid this in the future, commit between such steps. If you'd like to hide the intervening commits then I'd recommend doing the multi-step refactoring on a branch and then merging the changes back into the mainline in that single commit you were after. If it's not too much work, then I'd recommend getting back to a clean working copy and redoing your changes, committing after each step. If you're happy to lose the history, i.e. allowing the new IntegerType.java to not be linked at all to the old IntegerType.java , then you could take the approach suggested by BCS: Move your changed files into some temporary location, stripping out any .svn directories Update your working copy into a clean working state Copy your changes back to where you want them to be Commit the resulting working copy | {
"score": 5,
"source": [
"https://Stackoverflow.com/questions/47022",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1412/"
]
} |
47,045 | Printf got added to Java with the 1.5 release but I can't seem to find how to send the output to a string rather than a file (which is what sprintf does in C). Does anyone know how to do this? | // Store the formatted string in 'result'String result = String.format("%4d", i * j);// Write the result to standard outputSystem.out.println( result ); See format and its syntax | {
"score": 10,
"source": [
"https://Stackoverflow.com/questions/47045",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4498/"
]
} |
47,066 | I am writing a C program in Linux. Commands like execv() require a path in the form of a C string. Is there a command that will return the current path in the form of a C-style string? | getcwd() : SYNOPSIS #include <unistd.h>char *getcwd(char *buf, size_t size); DESCRIPTION The getcwd() function shall place an absolute pathname of the current working directory in the array pointed to by buf, and return buf . The pathname copied to the array shall contain no components that are symbolic links. The size argument is the size in bytes of the character array pointed to by the buf argument. If buf is a null pointer, the behavior of getcwd() is unspecified. RETURN VALUE Upon successful completion, getcwd() shall return the buf argument. Otherwise, getcwd() shall return a null pointer and set errno to indicate the error. The contents of the array pointed to by buf are then undefined.... | {
"score": 5,
"source": [
"https://Stackoverflow.com/questions/47066",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/159/"
]
} |
47,089 | About 6 months ago I rolled out a site where every request needed to be over https. The only way at the time I could find to ensure that every request to a page was over https was to check it in the page load event. If the request was not over http I would response.redirect(" https://example.com ") Is there a better way -- ideally some setting in the web.config? | Please use HSTS (HTTP Strict Transport Security) from http://www.hanselman.com/blog/HowToEnableHTTPStrictTransportSecurityHSTSInIIS7.aspx <?xml version="1.0" encoding="UTF-8"?><configuration> <system.webServer> <rewrite> <rules> <rule name="HTTP to HTTPS redirect" stopProcessing="true"> <match url="(.*)" /> <conditions> <add input="{HTTPS}" pattern="off" ignoreCase="true" /> </conditions> <action type="Redirect" url="https://{HTTP_HOST}/{R:1}" redirectType="Permanent" /> </rule> </rules> <outboundRules> <rule name="Add Strict-Transport-Security when HTTPS" enabled="true"> <match serverVariable="RESPONSE_Strict_Transport_Security" pattern=".*" /> <conditions> <add input="{HTTPS}" pattern="on" ignoreCase="true" /> </conditions> <action type="Rewrite" value="max-age=31536000" /> </rule> </outboundRules> </rewrite> </system.webServer></configuration> Original Answer (replaced with the above on 4 December 2015) basically protected void Application_BeginRequest(Object sender, EventArgs e){ if (HttpContext.Current.Request.IsSecureConnection.Equals(false) && HttpContext.Current.Request.IsLocal.Equals(false)) { Response.Redirect("https://" + Request.ServerVariables["HTTP_HOST"]+ HttpContext.Current.Request.RawUrl); }} that would go in the global.asax.cs (or global.asax.vb) i dont know of a way to specify it in the web.config | {
"score": 9,
"source": [
"https://Stackoverflow.com/questions/47089",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4846/"
]
} |
47,107 | Is there a way to disallow publishing of debug builds with ClickOnce? I only want to allow release builds through, but right now human error causes a debug build to slip through once in a while. We're publishing the build from within Visual Studio. | I have started to modify the .csproj files to include the following code to throw an error for debug deploys, effectively preventing the deploy from happening: <!-- The following makes sure we don’t try to publish a configuration that defines the DEBUG constant --><Target Name="BeforePublish"> <Error Condition="'$(DebugSymbols)' == 'true'" Text="You attempted to publish a configuration that defines the DEBUG constant!" /></Target> Just place it at the end of the file, right before the </Project> tag. (original source: http://www.nathanpjones.com/wp/2010/05/preventing-clickonce-publishing-a-debug-configuration/comment-page-1/#comment-625 ) | {
"score": 7,
"source": [
"https://Stackoverflow.com/questions/47107",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3641/"
]
} |
47,177 | I would like to monitor the following system information in Java: Current CPU usage** (percent) Available memory* (free/total) Available disk space (free/total) *Note that I mean overall memory available to the whole system, not just the JVM. I'm looking for a cross-platform solution (Linux, Mac, and Windows) that doesn't rely on my own code calling external programs or using JNI. Although these are viable options, I would prefer not to maintain OS-specific code myself if someone already has a better solution. If there's a free library out there that does this in a reliable, cross-platform manner, that would be great (even if it makes external calls or uses native code itself). Any suggestions are much appreciated. To clarify, I would like to get the current CPU usage for the whole system, not just the Java process(es). The SIGAR API provides all the functionality I'm looking for in one package, so it's the best answer to my question so far. However, due it being licensed under the GPL, I cannot use it for my original purpose (a closed source, commercial product). It's possible that Hyperic may license SIGAR for commercial use, but I haven't looked into it. For my GPL projects, I will definitely consider SIGAR in the future. For my current needs, I'm leaning towards the following: For CPU usage, OperatingSystemMXBean.getSystemLoadAverage() / OperatingSystemMXBean.getAvailableProcessors() (load average per cpu) For memory, OperatingSystemMXBean.getTotalPhysicalMemorySize() and OperatingSystemMXBean.getFreePhysicalMemorySize() For disk space, File.getTotalSpace() and File.getUsableSpace() Limitations: The getSystemLoadAverage() and disk space querying methods are only available under Java 6. Also, some JMX functionality may not be available to all platforms (i.e. it's been reported that getSystemLoadAverage() returns -1 on Windows). Although originally licensed under GPL, it has been changed to Apache 2.0 , which can generally be used for closed source, commercial products. | Along the lines of what I mentioned in this post . I recommend you use the SIGAR API . I use the SIGAR API in one of my own applications and it is great. You'll find it is stable, well supported, and full of useful examples. It is open-source with a GPL 2 Apache 2.0 license. Check it out. I have a feeling it will meet your needs. Using Java and the Sigar API you can get Memory, CPU, Disk, Load-Average, Network Interface info and metrics, Process Table information, Route info, etc. | {
"score": 7,
"source": [
"https://Stackoverflow.com/questions/47177",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2783/"
]
} |
47,203 | When should I choose one or the other? What are the implications regarding space and (full-text) indexing? BTW: I'm currently using SQL Server 2005 planing to upgrade to 2008 in the following months. Thanks | The new (max) fields make it a lot easier to deal with the data from .NET code. With varbinary(max) , you simply set the value of a SqlParameter to a byte array and you are done. WIth the image field, you need to write a few hundred lines of code to stream the data into and out of the field. Also, the image/text fields are deprecated in favor of varbinary(max) and varchar(max) , and future versions of Sql Server will discontinue support for them. | {
"score": 5,
"source": [
"https://Stackoverflow.com/questions/47203",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2148/"
]
} |
47,207 | Can i print out a url /admin/manage/products/add of a certain view in a template? Here is the rule i want to create a link for (r'^manage/products/add/$', create_object, {'model': Product, 'post_save_redirect': ''}), I would like to have /manage/products/add in a template without hardcoding it. How can i do this? Edit: I am not using the default admin (well, i am but it is at another url), this is my own | You can use get_absolute_url , but that will only work for a particular object. Since your object hasn't been created yet, it won't work in this case. You want to use named URL patterns . Here's a quick intro: Change the line in your urls.py to: (r'^manage/products/add/$', create_object, {'model': Product, 'post_save_redirect': ''}, "create-product"), Then, in your template you use this to display the URL: {% url create-product %} If you're using Django 1.5 or higher you need this: {% url 'create-product' %} You can do some more powerful things with named URL patterns, they're very handy. Note that they are only in the development version (and also 1.0). | {
"score": 5,
"source": [
"https://Stackoverflow.com/questions/47207",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2592/"
]
} |
47,217 | I've got a DataSet in VisualStudio 2005. I need to change the datatype of a column in one of the datatables from System.Int32 to System.Decimal . When I try to change the datatype in the DataSet Designer I receive the following error: Property value is not valid. Cannot change DataType of a column once it has data. From my understanding, this should be changing the datatype in the schema for the DataSet. I don't see how there can be any data to cause this error. Does any one have any ideas? | I get the same error but only for columns with its DefaultValue set to any value (except the default <DBNull> ). So the way I got around this issue was: Column DefaultValue : Type in <DBNull> Save and reopen the dataset | {
"score": 6,
"source": [
"https://Stackoverflow.com/questions/47217",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3123/"
]
} |
47,239 | Does anyone know a way to auto-generate database tables for a given class? I'm not looking for an entire persistence layer - I already have a data access solution I'm using, but I suddenly have to store a lot of information from a large number of classes and I really don't want to have to create all these tables by hand. For example, given the following class: class Foo{ private string property1; public string Property1 { get { return property1; } set { property1 = value; } } private int property2; public int Property2 { get { return property2; } set { property2 = value; } }} I'd expect the following SQL: CREATE TABLE Foo( Property1 VARCHAR(500), Property2 INT) I'm also wondering how you could handle complex types. For example, in the previously cited class, if we changed that to be : class Foo{ private string property1; public string Property1 { get { return property1; } set { property1 = value; } } private System.Management.ManagementObject property2; public System.Management.ManagementObject Property2 { get { return property2; } set { property2 = value; } }} How could I handle this? I've looked at trying to auto-generate the database scripts by myself using reflection to enumerate through each class' properties, but it's clunky and the complex data types have me stumped. | It's really late, and I only spent about 10 minutes on this, so its extremely sloppy, however it does work and will give you a good jumping off point: using System;using System.Collections.Generic;using System.Text;using System.Reflection;namespace TableGenerator{ class Program { static void Main(string[] args) { List<TableClass> tables = new List<TableClass>(); // Pass assembly name via argument Assembly a = Assembly.LoadFile(args[0]); Type[] types = a.GetTypes(); // Get Types in the assembly. foreach (Type t in types) { TableClass tc = new TableClass(t); tables.Add(tc); } // Create SQL for each table foreach (TableClass table in tables) { Console.WriteLine(table.CreateTableScript()); Console.WriteLine(); } // Total Hacked way to find FK relationships! Too lazy to fix right now foreach (TableClass table in tables) { foreach (KeyValuePair<String, Type> field in table.Fields) { foreach (TableClass t2 in tables) { if (field.Value.Name == t2.ClassName) { // We have a FK Relationship! Console.WriteLine("GO"); Console.WriteLine("ALTER TABLE " + table.ClassName + " WITH NOCHECK"); Console.WriteLine("ADD CONSTRAINT FK_" + field.Key + " FOREIGN KEY (" + field.Key + ") REFERENCES " + t2.ClassName + "(ID)"); Console.WriteLine("GO"); } } } } } } public class TableClass { private List<KeyValuePair<String, Type>> _fieldInfo = new List<KeyValuePair<String, Type>>(); private string _className = String.Empty; private Dictionary<Type, String> dataMapper { get { // Add the rest of your CLR Types to SQL Types mapping here Dictionary<Type, String> dataMapper = new Dictionary<Type, string>(); dataMapper.Add(typeof(int), "BIGINT"); dataMapper.Add(typeof(string), "NVARCHAR(500)"); dataMapper.Add(typeof(bool), "BIT"); dataMapper.Add(typeof(DateTime), "DATETIME"); dataMapper.Add(typeof(float), "FLOAT"); dataMapper.Add(typeof(decimal), "DECIMAL(18,0)"); dataMapper.Add(typeof(Guid), "UNIQUEIDENTIFIER"); return dataMapper; } } public List<KeyValuePair<String, Type>> Fields { get { return this._fieldInfo; } set { this._fieldInfo = value; } } public string ClassName { get { return this._className; } set { this._className = value; } } public TableClass(Type t) { this._className = t.Name; foreach (PropertyInfo p in t.GetProperties()) { KeyValuePair<String, Type> field = new KeyValuePair<String, Type>(p.Name, p.PropertyType); this.Fields.Add(field); } } public string CreateTableScript() { System.Text.StringBuilder script = new StringBuilder(); script.AppendLine("CREATE TABLE " + this.ClassName); script.AppendLine("("); script.AppendLine("\t ID BIGINT,"); for (int i = 0; i < this.Fields.Count; i++) { KeyValuePair<String, Type> field = this.Fields[i]; if (dataMapper.ContainsKey(field.Value)) { script.Append("\t " + field.Key + " " + dataMapper[field.Value]); } else { // Complex Type? script.Append("\t " + field.Key + " BIGINT"); } if (i != this.Fields.Count - 1) { script.Append(","); } script.Append(Environment.NewLine); } script.AppendLine(")"); return script.ToString(); } }} I put these classes in an assembly to test it: public class FakeDataClass{ public int AnInt { get; set; } public string AString { get; set; } public float AFloat { get; set; } public FKClass AFKReference { get; set; }}public class FKClass { public int AFKInt { get; set; } } And it generated the following SQL: CREATE TABLE FakeDataClass( ID BIGINT, AnInt BIGINT, AString NVARCHAR(255), AFloat FLOAT, AFKReference BIGINT)CREATE TABLE FKClass( ID BIGINT, AFKInt BIGINT)GOALTER TABLE FakeDataClass WITH NOCHECKADD CONSTRAINT FK_AFKReference FOREIGN KEY (AFKReference) REFERENCES FKClass(ID)GO Some further thoughts...I'd consider adding an attribute such as [SqlTable] to your classes, that way it only generates tables for the classes you want. Also, this can be cleaned up a ton, bugs fixed, optimized (the FK Checker is a joke) etc etc...Just to get you started. | {
"score": 8,
"source": [
"https://Stackoverflow.com/questions/47239",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4550/"
]
} |
47,253 | I work in a Windows environment and would prefer to deploy code to IIS. At the same time I would like to code in Python. Having read that IIS can run fastCGI application, I went to the IIS site where it describes in detail how to get PHP up and running but not much about anything else. Does anyone have experience getting a Python framework running under IIS using something other that plain old CGI? If so can you explain to direct me to some instructions on setting this up? | There shouldn't be any need to use FastCGI. There exists a ISAPI extension for WSGI . | {
"score": 6,
"source": [
"https://Stackoverflow.com/questions/47253",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4491/"
]
} |
47,363 | What is the command to list all triggers in a MySQL database? | The command for listing all triggers is: show triggers; or you can access the INFORMATION_SCHEMA table directly by: select trigger_schema, trigger_name, action_statementfrom information_schema.triggers You can do this from version 5.0.10 onwards. More information about the TRIGGERS table is here . | {
"score": 9,
"source": [
"https://Stackoverflow.com/questions/47363",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4704/"
]
} |
47,366 | We're a .NET team which uses the Oracle DB for a lot of reasons that I won't get into. But deployment has been a bitch. We are manually keeping track of all the changes to the schema in each version, by keeping a record of all the scripts that we run during development. Now, if a developer forgets to check-in his script to the source control after he ran it - which is not that rare - at the end of the iteration we get a great big headache. I hear that SQL Compare by Red-Gate might solve these kind of issues, but it only has SQL Server support. Anybody knows of a similar tool for Oracle? I've been unable to find one. | Red Gate Schema Compare for Oracle has now been released! http://www.red-gate.com/products/schema_compare_for_oracle/index.htm There is a 28-day fully functional free trial. Please give it a go and let us know your feedback! | {
"score": 5,
"source": [
"https://Stackoverflow.com/questions/47366",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3389/"
]
} |
47,376 | In a project of mine the SQL statements that are executed against a SQL Server are failing for some unknown reason. Some of the code is already used in production so debugging it is not an easy task. Therefore I need a way to see in the database itself what SQL statements are used, as the statements are generated at runtime by the project and could be flawed when certain conditions are met. I therefore considered the possibility to monitor the incoming statements and check myself if I see any flaws. The database is running on a SQL Server 2005, and I use SQL server management studio express as primary tool to manipulate the database. So my question is, what is the best way to do this? | Seeing how you use the Management Studio Express, I will assume you don't have access to the MSSQL 2005 client tools. If you do, install those, because it includes the SQL profiler which does exactly what you want (and more!). For more info about that one, see msdn . I found this a while ago, because I was thinking about the exact same thing. I have access to the client tools myself, so I don't really need to yet, but that access is not unlimited (it's through my current job). If you try it out, let me know if it works ;-) | {
"score": 6,
"source": [
"https://Stackoverflow.com/questions/47376",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/46/"
]
} |
47,387 | I've been hearing about triggers, and I have a few questions. What are triggers? How do I set them up? Are there any precautions, aside from typical SQL stuff, that should be taken? | Triggers allow you to perform a function in the database as certain events happen (eg, an insert into a table). I can't comment on mysql specifically. Precaution: Triggers can be very alluring, when you first start using them they seem like a magic bullet to all kinds of problems. But, they make "magic" stuff happen, if you don't know the database inside out, it can seem like really strange things happen (such as inserts into other tables, input data changing, etc). Before implementing things as a trigger I'd seriously consider instead enforcing the use of an API around the schema (preferably in the database, but outside if you can't). Some things I'd still use triggers for Keeping track of "date_created" and "date_last_edited" fields Inserting "ID"'s (in oracle, where there is no auto id field) Keeping change history Things you wouldn't want to use triggers for business rules/logic anything which connects outside of the database (eg a webservice call) Access control Anything which isn't transactional ( anything you do in the trigger MUST be able to rollback with the transaction ) | {
"score": 5,
"source": [
"https://Stackoverflow.com/questions/47387",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/115/"
]
} |
47,400 | With the code, forms and data inside the same database I am wondering what are the best practices to design a suite of tests for a Microsoft Access application (say for Access 2007). One of the main issues with testing forms is that only a few controls have a hwnd handle and other controls only get one they have focus, which makes automation quite opaque since you cant get a list of controls on a form to act on. Any experience to share? | 1. Write Testable Code First, stop writing business logic into your Form's code behind. That's not the place for it. It can't be properly tested there. In fact, you really shouldn't have to test your form itself at all. It should be a dead dumb simple view that responds to User Interaction and then delegates responsibility for responding to those actions to another class that is testable. How do you do that? Familiarizing yourself with the Model-View-Controller pattern is a good start. It can't be done perfectly in VBA due to the fact that we get either events or interfaces, never both, but you can get pretty close. Consider this simple form that has a text box and a button. In the form's code behind, we'll wrap the TextBox's value in a public property and re-raise any events we're interested in. Public Event OnSayHello()Public Event AfterTextUpdate()Public Property Let Text(value As String) Me.TextBox1.value = valueEnd PropertyPublic Property Get Text() As String Text = Me.TextBox1.valueEnd PropertyPrivate Sub SayHello_Click() RaiseEvent OnSayHelloEnd SubPrivate Sub TextBox1_AfterUpdate() RaiseEvent AfterTextUpdateEnd Sub Now we need a model to work with. Here I've created a new class module named MyModel . Here lies the code we'll put under test. Note that it naturally shares a similar structure as our view. Private mText As StringPublic Property Let Text(value As String) mText = valueEnd PropertyPublic Property Get Text() As String Text = mTextEnd PropertyPublic Function Reversed() As String Dim result As String Dim length As Long length = Len(mText) Dim i As Long For i = 0 To length - 1 result = result + Mid(mText, (length - i), 1) Next i Reversed = resultEnd FunctionPublic Sub SayHello() MsgBox Reversed()End Sub Finally, our controller wires it all together. The controller listens for form events and communicates changes to the model and triggers the model's routines. Private WithEvents view As Form_Form1Private model As MyModelPublic Sub Run() Set model = New MyModel Set view = New Form_Form1 view.Visible = TrueEnd SubPrivate Sub view_AfterTextUpdate() model.Text = view.TextEnd SubPrivate Sub view_OnSayHello() model.SayHello view.Text = model.Reversed()End Sub Now this code can be run from any other module. For the purposes of this example, I've used a standard module. I highly encourage you to build this yourself using the code I've provided and see it function. Private controller As FormControllerPublic Sub Run() Set controller = New FormController controller.RunEnd Sub So, that's great and all but what does it have to do with testing?! Friend, it has everything to do with testing. What we've done is make our code testable . In the example I've provided, there is no reason what-so-ever to even try to test the GUI. The only thing we really need to test is the model . That's where all of the real logic is. So, on to step two. 2. Choose a Unit Testing Framework There aren't a lot of options here. Most frameworks require installing COM Add-ins, lots of boiler plate, weird syntax, writing tests as comments, etc. That's why I got involved in building one myself , so this part of my answer isn't impartial, but I'll try to give a fair summary of what's available. AccUnit Works only in Access. Requires you to write tests as a strange hybrid of comments and code. (no intellisense for the comment part. There is a graphical interface to help you write those strange looking tests though. The project has not seen any updates since 2013. VB Lite Unit I can't say I've personally used it. It's out there, but hasn't seen an update since 2005. xlUnit xlUnit isn't awful, but it's not good either. It's clunky and there's lots of boiler plate code. It's the best of the worst, but it doesn't work in Access. So, that's out. Build your own framework I've been there and done that . It's probably more than most people want to get into, but it is completely possible to build a Unit Testing framework in Native VBA code. Rubberduck VBE Add-In's Unit Testing Framework Disclaimer: I'm one of the co-devs . I'm biased, but this is by far my favorite of the bunch. Little to no boiler plate code. Intellisense is available. The project is active. More documentation than most of these projects. It works in most of the major office applications, not just Access. It is, unfortunately, a COM Add-In, so it has to be installed onto your machine. 3. Start writing tests So, back to our code from section 1. The only code that we really needed to test was the MyModel.Reversed() function. So, let's take a look at what that test could look like. (Example given uses Rubberduck, but it's a simple test and could translate into the framework of your choice.) '@TestModulePrivate Assert As New Rubberduck.AssertClass'@TestMethodPublic Sub ReversedReversesCorrectly()Arrange: Dim model As New MyModel Const original As String = "Hello" Const expected As String = "olleH" Dim actual As String model.Text = originalAct: actual = model.ReversedAssert: Assert.AreEqual expected, actualEnd Sub Guidelines for Writing Good Tests Only test one thing at a time. Good tests only fail when there is a bug introduced into the system or the requirements have changed. Don't include external dependencies such as databases and file systems. These external dependencies can make tests fail for reasons outside of your control. Secondly, they slow your tests down. If your tests are slow, you won't run them. Use test names that describe what the test is testing. Don't worry if it gets long. It's most important that it is descriptive. I know that answer was a little long, and late, but hopefully it helps some people get started in writing unit tests for their VBA code. | {
"score": 6,
"source": [
"https://Stackoverflow.com/questions/47400",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3811/"
]
} |
47,402 | Given an array of characters which forms a sentence of words, give an efficient algorithm to reverse the order of the words (not characters) in it. Example input and output: >>> reverse_words("this is a string")'string a is this' It should be O(N) time and O(1) space ( split() and pushing on / popping off the stack are not allowed). The puzzle is taken from here . | A solution in C/C++: void swap(char* str, int i, int j){ char t = str[i]; str[i] = str[j]; str[j] = t;}void reverse_string(char* str, int length){ for(int i=0; i<length/2; i++){ swap(str, i, length-i-1); }}void reverse_words(char* str){ int l = strlen(str); //Reverse string reverse_string(str,strlen(str)); int p=0; //Find word boundaries and reverse word by word for(int i=0; i<l; i++){ if(str[i] == ' '){ reverse_string(&str[p], i-p); p=i+1; } } //Finally reverse the last word. reverse_string(&str[p], l-p);} This should be O(n) in time and O(1) in space. Edit: Cleaned it up a bit. The first pass over the string is obviously O(n/2) = O(n). The second pass is O(n + combined length of all words / 2) = O(n + n/2) = O(n), which makes this an O(n) algorithm. | {
"score": 6,
"source": [
"https://Stackoverflow.com/questions/47402",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4279/"
]
} |
47,427 | Many websites, including this one, add what are apparently called slugs - descriptive but as far as I can tell useless bits of text - to the end of URLs. For example, the URL the site gives for this question is: https://stackoverflow.com/questions/47427/why-do-some-websites-add-slugs-to-the-end-of-urls But the following URL works just as well: https://stackoverflow.com/questions/47427/ Is the point of this text just to somehow make the URL more user friendly or are there some other benefits? | The slugs make the URL more user-friendly and you know what to expect when you click a link. Search engines such as Google, rank the pages higher if the searchword is in the URL. | {
"score": 8,
"source": [
"https://Stackoverflow.com/questions/47427",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3171/"
]
} |
47,432 | This free collection library comes from IT University of Copenhagen. http://www.itu.dk/research/c5/ There is a video with one of the authors on Channel 9. I am trying to learn how to use these collections and I was wondering whether anyone has more experiences or what are your thoughts on this specific collection library for .NET. Do you like the way they are designed, do you like their performance and what were your major problems with them ? | I've used it in the past and there are a couple of notes I must make: The library is very good, very fast and very useful. It has lots of very nice data structures, some of which I did not know before starting to use this library. It's Open-Source! This is a huge benefit. Sometimes you don't have exactly what you want. As far as my experience showed, the library's authors decided to go with a very fault-intolerant attitude, throwing exceptions about everything. This caused me to add a few fault-tolerant methods. All in all, a very nice library with some advanced data structures. Unfortunately, support for it is very lacking, as you can see from the fact that new releases (bugfixes, et al) range somewhere from 6 months to a year. Note: Starting with Mono 2.0, C5 is bundled as a 3rd party API , which I believe to be a wonderful show of faith in the product from the Mono team. | {
"score": 5,
"source": [
"https://Stackoverflow.com/questions/47432",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4694/"
]
} |
47,433 | Consider the following 2 queries: select tblA.a,tblA.b,tblA.c,tblA.dfrom tblAwhere tblA.a not in (select tblB.a from tblB)select tblA.a,tblA.b,tblA.c,tblA.dfrom tblA left outer join tblBon tblA.a = tblB.a where tblB.a is null Which will perform better? My assumption is that in general the join will be better except in cases where the subselect returns a very small result set. | RDBMSs "rewrite" queries to optimize them, so it depends on system you're using, and I would guess they end up giving the same performance on most "good" databases. I suggest picking the one that is clearer and easier to maintain, for my money, that's the first one. It's much easier to debug the subquery as it can be run independently to check for sanity. | {
"score": 5,
"source": [
"https://Stackoverflow.com/questions/47433",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/292/"
]
} |
47,436 | What is the shortcut key for Run to cursor in Visual Studio 2008? | The shortcut key is CTRL + F10 . | {
"score": 7,
"source": [
"https://Stackoverflow.com/questions/47436",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3854/"
]
} |
47,475 | If unit-test names can become outdated over time and if you consider that the test itself is the most important thing, then is it important to choose wise test names? ie [Test]public void ShouldValidateUserNameIsLessThan100Characters() {} verse [Test]public void UserNameTestValidation1() {} | The name of any method should make it clear what it does. IMO, your first suggestion is a bit long and the second one isn't informative enough. Also it's probably a bad idea to put "100" in the name, as that's very likely to change. What about: public void validateUserNameLength() If the test changes, the name should be updated accordingly. | {
"score": 5,
"source": [
"https://Stackoverflow.com/questions/47475",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4642/"
]
} |
47,487 | Possible Duplicate: Avoiding repeated constants in CSS We have some "theme colors" that are reused in our CSS sheet. Is there a way to set a variable and then reuse it? E.g. .cssOurColor: BlueH1 { color:OurColor;} | There's no requirement that all styles for a selector reside in a single rule, and a single rule can apply to multiple selectors... so flip it around : /* Theme color: text */H1, P, TABLE, UL{ color: blue; }/* Theme color: emphasis */B, I, STRONG, EM{ color: #00006F; }/* ... *//* Theme font: header */H1, H2, H3, H4, H5, H6{ font-family: Comic Sans MS; }/* ... *//* H1-specific styles */H1{ font-size: 2em; margin-bottom: 1em;} This way, you avoid repeating styles that are conceptually the same, while also making it clear which parts of the document they affect. Note the emphasis on "conceptually" in that last sentence... This just came up in the comments, so I'm gonna expand on it a bit, since I've seen people making this same mistake over and over again for years - predating even the existence of CSS: two attributes sharing the same value does not necessarily mean they represent the same concept . The sky may appear red in the evening, and so do tomatoes - but the sky and the tomato are not red for the same reason, and their colors will vary over time independently. By the same token, just because you happen to have two elements in your stylesheet that are given the same color, or size or positioning does not mean they will always share these values. A naive designer who uses grouping (as described here) or a variable processor such as SASS or LESS to avoid value repetition risks making future changes to styling incredibly error-prone; always focus on the contextual meaning of styles when looking to reduce repetition, ignoring their current values . | {
"score": 8,
"source": [
"https://Stackoverflow.com/questions/47487",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4906/"
]
} |
47,521 | Here is a sample code to retrieve data from a database using the yield keyword that I found in a few place while googling around : public IEnumerable<object> ExecuteSelect(string commandText){ using (IDbConnection connection = CreateConnection()) { using (IDbCommand cmd = CreateCommand(commandText, connection)) { connection.Open(); using (IDbDataReader reader = cmd.ExecuteReader()) { while(reader.Read()) { yield return reader["SomeField"]; } } connection.Close(); } }} Am I correct in thinking that in this sample code, the connection would not be closed if we do not iterate over the whole datareader ? Here is an example that would not close the connection, if I understand yield correctly.. foreach(object obj in ExecuteSelect(commandText)){ break;} For a db connection that might not be catastrophic, I suppose the GC would clean it up eventually, but what if instead of a connection it was a more critical resource? | The Iterator that the compiler synthesises implements IDisposable , which foreach calls when the foreach loop is exited. The Iterator's Dispose() method will clean up the using statements on early exit. As long as you use the iterator in a foreach loop, using() block, or call the Dispose() method in some other way, the cleanup of the Iterator will happen. | {
"score": 5,
"source": [
"https://Stackoverflow.com/questions/47521",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4789/"
]
} |
47,537 | Does anyone know if there is a c# Console app, similar to the Python or Ruby console? I know the whole "Compiled versus Interpreted" difference, but with C#'s reflection power I think it could be done. UPDATE Well, it only took about 200 lines, but I wrote a simple one...It works a lot like osql. You enter commands and then run them with go. SharpConsole http://www.gfilter.net/junk/sharpconsole.jpg If anyone wants it, let me know. | Given your mention of "C#'s reflection power", I am unsure whether you're looking for an interactive C# console for small code snippets of your own (à la Ruby's irb ), or a means of interacting with an existing, compiled application currently running as a process. In the former case: Windows PowerShell might be your friend Another candidate would be the C# shell Finally, CSI , a Simple C# Interpreter | {
"score": 5,
"source": [
"https://Stackoverflow.com/questions/47537",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1965/"
]
} |
47,589 | I'm dealing with a MySQL table that defines the JobName column as UNIQUE. If somebody tries to save a new Job to the database using a JobName that is already in the database, MySQL throws a warning. I would like to be able to detect this warning, just like an error, in my PHP script and deal with it appropriately. Ideally I would like to know what kind of warning MySQL has thrown so that I can branch the code to handle it. Is this possible? If not, is it because MySQL doesn't have this ability, PHP doesn't have this ability, or both? | For warnings to be "flagged" to PHP natively would require changes to the mysql/mysqli driver, which is obviously beyond the scope of this question. Instead you're going to have to basically check every query you make on the database for warnings: $warningCountResult = mysql_query("SELECT @@warning_count");if ($warningCountResult) { $warningCount = mysql_fetch_row($warningCountResult ); if ($warningCount[0] > 0) { //Have warnings $warningDetailResult = mysql_query("SHOW WARNINGS"); if ($warningDetailResult ) { while ($warning = mysql_fetch_assoc($warningDetailResult) { //Process it } } }//Else no warnings} Obviously this is going to be hideously expensive to apply en-mass, so you might need to carefully think about when and how warnings may arise (which may lead you to refactor to eliminate them). For reference, MySQL SHOW WARNINGS Of course, you could dispense with the initial query for the SELECT @@warning_count , which would save you a query per execution, but I included it for pedantic completeness. | {
"score": 5,
"source": [
"https://Stackoverflow.com/questions/47589",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2056/"
]
} |
47,605 | Assuming String a and b: a += ba = a.concat(b) Under the hood, are they the same thing? Here is concat decompiled as reference. I'd like to be able to decompile the + operator as well to see what that does. public String concat(String s) { int i = s.length(); if (i == 0) { return this; } else { char ac[] = new char[count + i]; getChars(0, count, ac, 0); s.getChars(0, i, ac, count); return new String(0, count + i, ac); }} | No, not quite. Firstly, there's a slight difference in semantics. If a is null , then a.concat(b) throws a NullPointerException but a+=b will treat the original value of a as if it were null . Furthermore, the concat() method only accepts String values while the + operator will silently convert the argument to a String (using the toString() method for objects). So the concat() method is more strict in what it accepts. To look under the hood, write a simple class with a += b; public class Concat { String cat(String a, String b) { a += b; return a; }} Now disassemble with javap -c (included in the Sun JDK). You should see a listing including: java.lang.String cat(java.lang.String, java.lang.String); Code: 0: new #2; //class java/lang/StringBuilder 3: dup 4: invokespecial #3; //Method java/lang/StringBuilder."<init>":()V 7: aload_1 8: invokevirtual #4; //Method java/lang/StringBuilder.append:(Ljava/lang/String;)Ljava/lang/StringBuilder; 11: aload_2 12: invokevirtual #4; //Method java/lang/StringBuilder.append:(Ljava/lang/String;)Ljava/lang/StringBuilder; 15: invokevirtual #5; //Method java/lang/StringBuilder.toString:()Ljava/lang/ String; 18: astore_1 19: aload_1 20: areturn So, a += b is the equivalent of a = new StringBuilder() .append(a) .append(b) .toString(); The concat method should be faster. However, with more strings the StringBuilder method wins, at least in terms of performance. The source code of String and StringBuilder (and its package-private base class) is available in src.zip of the Sun JDK. You can see that you are building up a char array (resizing as necessary) and then throwing it away when you create the final String . In practice memory allocation is surprisingly fast. Update: As Pawel Adamski notes, performance has changed in more recent HotSpot. javac still produces exactly the same code, but the bytecode compiler cheats. Simple testing entirely fails because the entire body of code is thrown away. Summing System.identityHashCode (not String.hashCode ) shows the StringBuffer code has a slight advantage. Subject to change when the next update is released, or if you use a different JVM. From @lukaseder , a list of HotSpot JVM intrinsics . | {
"score": 10,
"source": [
"https://Stackoverflow.com/questions/47605",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/292/"
]
} |
47,639 | I just noticed that Chromium was installed in AppData in both Vista and XP. If Google does that and if other applications does this, than is that becuase there is some form of protection? Should we write installers that does the same thing as Google? | Windows still lacks a convention for per-user installation. When an installer asks whether to install for the current user or all users, it really only refers to shortcut placement (Start Menu; Desktop). The actual application files still go in the system-wide %PROGRAMFILES% . Microsoft's own ClickOnce works around this by creating a completely non-standard %USERPROFILE%\Local Settings\Apps ( %USERPROFILE%\AppData\Roaming on Vista / Server 2008) directory, with both program files and configuration data in there. (I'm at a loss why Microsoft couldn't add a per-user Program Files directory in Vista. For example, in OS X, you can create a ~/Applications , and the Finder will give it an appropriate icon. Apps like CrossOver and Adobe AIR automatically use that, defaulting to per-user apps. Thus, no permissions issues.) What you probably should do: if the user is not an admin, install in the user directory; if they do, give them both options. | {
"score": 5,
"source": [
"https://Stackoverflow.com/questions/47639",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/370899/"
]
} |
47,656 | I would like to do full-text searching of data in my Ruby on Rails application. What options exist? | There are several options available and each have different strengths and weaknesses. If you would like to add full-text searching, it would be prudent to investigate each a little bit and try them out to see how well it works for you in your environment. MySQL has built-in support for full-text searching. It has online support meaning that when new records are added to the database, they are automatically indexed and will be available in the search results. The documentation has more details. acts_as_tsearch offers a wrapper for similar built-in functionality for recent versions of PostgreSQL For other databases you will have to use other software. Lucene is a popular search provider written in Java. You can use Lucene through its search server Solr with Rails using acts_as_solr . If you don't want to use Java, there is a port of Lucene to Ruby called Ferret . Support for Rails is added using the acts_as_ferret plugin. Xapian is another good option and is supported in Rails using the acts_as_xapian plugin. Finally, my preferred choice is Sphinx using the Ultrasphinx plugin. It is extremely fast and has many options on how to index and search your databases, but is no longer being actively maintained. Another plugin for Sphinx is Thinking Sphinx which has a lot of positive feedback . It is a little easier to get started using Thinking Sphinx than Ultrasphinx. I would suggest investigating both plugins to determine which fits better with your project. | {
"score": 5,
"source": [
"https://Stackoverflow.com/questions/47656",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4028/"
]
} |
47,676 | The Weblogic servers we are using have been configured to allow JNDI datasource names like "appds". For development (localhost), we might be running Tomcat and when declared in the <context> section of server.xml, Tomcat will hang JNDI datasources on "java:comp/env/jdbc/*" in the JNDI tree. Problem: in Weblogic, the JNDI lookup is "appds" whilst in Tomcat, it seems that that I must provide the formal "java:comp/env/jdbc/appds". I'm afraid the Tomcat version is an implicit standard but unfortunately, I can't change Weblogic's config ... so that means we end up with two different spring config files (we're using spring 2.5) to facilitate the different environments. Is there an elegant way to address this. Can I look JNDI names up directly in Tomcat? Can Spring take a name and look in both places? Google searches or suggestions would be great. | JndiLocatorSupport has a property resourceRef . When setting this true, "java:comp/env/" prefix will be prepended automatically. So I believe it would be correct to differentiate this parameter when moving from Tomcat to Weblogic. | {
"score": 5,
"source": [
"https://Stackoverflow.com/questions/47676",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4910/"
]
} |
47,692 | I keep reading about people who are "test infected", meaning that they don't just "get" TDD but also can't live without it. They've "had the makeover" as it were. The question is, how do I get like that? | Part of the point of being "test infected" is that you've used TDD enough and seen the successes enough that you don't want to code without it . Once you've gone through a cycle of writing tests first, then coding and refactoring and seeing your bug counts go down and your code get better as a result, not only does it become second nature like Zxaos said, you have a hard time going back to Code First. This is being test infected. | {
"score": 5,
"source": [
"https://Stackoverflow.com/questions/47692",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2455/"
]
} |
47,701 | I'm trying to debug a deadlock in a multi-threaded Python application after it has locked up. Is there a way to attach a debugger to inspect the state of the process? Edit: I'm attempting this on Linux, but it would be great if there were a cross-platform solution. It's Python after all :) | Yeah, gdb is good for lower level debugging. You can change threads with the thread command. e.g (gdb) thr 2[Switching to thread 2 (process 6159 thread 0x3f1b)](gdb) backtrace.... You could also check out Python specific debuggers like Winpdb , or pydb . Both platform independent. | {
"score": 5,
"source": [
"https://Stackoverflow.com/questions/47701",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4883/"
]
} |
47,703 | Is here any performance benefit to using multiple threads on a computer with a single CPU that does not having hyperthreading? | In terms of speed of computation, No. In fact things will slow down due to the overhead of managing the threads. In terms of responsiveness, yes. You can for example have one thread wait on an IO operation and have another run a GUI at the same time. | {
"score": 6,
"source": [
"https://Stackoverflow.com/questions/47703",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4883/"
]
} |
47,709 | When you print from Google Docs (using the "print" link, not File/Print) you end up printing a nicely formated PDF file instead of relying on the print engine of the browser. Same is true for some of the reports in Google Analytics . . . the printed reports as PDF's are beautiful. How do they do that? I can't imagine they use something like Adobe Acrobat to facilitate it but maybe they do. I've seen some expensive HTML to PDF converters online from time to time but have never tired it. Any thoughts? | If you are specifically looking at how Google does it. If you look at the PDF Properties page, they use Prince 6.0 (see princexml.com ) There are lots of other PDF generators out there. I've had great success with PDFlib for tricky jobs. | {
"score": 5,
"source": [
"https://Stackoverflow.com/questions/47709",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4835/"
]
} |
47,711 | When creating a database structure, what are good guidelines to follow or good ways to determine how far a database should be normalized? Should you create an un-normalized database and split it apart as the project progresses? Should you create it fully normalized and combine tables as needed for performance? | You want to start designing a normalized database up to 3rd normal form. As you develop the business logic layer you may decide you have to denormalize a bit but never, never go below the 3rd form. Always, keep 1st and 2nd form compliant. You want to denormalize for simplicity of code, not for performance. Use indexes and stored procedures for that :) The reason not "normalize as you go" is that you would have to modify the code you already have written most every time you modify the database design. There are a couple of good articles: http://www.agiledata.org/essays/dataNormalization.html | {
"score": 5,
"source": [
"https://Stackoverflow.com/questions/47711",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4924/"
]
} |
47,749 | A while ago I read the Mocks Aren't Stubs article by Martin Fowler and I must admit I'm a bit scared of external dependencies with regards to added complexity so I would like to ask: What is the best method to use when unit testing? Is it better to always use a mock framework to automatically mock the dependencies of the method being tested, or would you prefer to use simpler mechanisms like for instance test stubs? | As the mantra goes 'Go with the simplest thing that can possibly work.' If fake classes can get the job done, go with them. If you need an interface with multiple methods to be mocked, go with a mock framework. Avoid using mocks always because they make tests brittle. Your tests now have intricate knowledge of the methods called by the implementation, if the mocked interface or your implementation changes... your tests break. This is bad coz you'll spend additional time getting your tests to run instead of just getting your SUT to run. Tests should not be inappropriately intimate with the implementation. So use your best judgment.. I prefer mocks when it'll help save me writing-updating a fake class with n>>3 methods. Update Epilogue/Deliberation: (Thanks to Toran Billups for example of a mockist test. See below) Hi Doug, Well I think we've transcended into another holy war - Classic TDDers vs Mockist TDDers. I think I'm belong to the former. If I am on test#101 Test_ExportProductList and I find I need to add a new param to IProductService.GetProducts(). I do that get this test green. I use a refactoring tool to update all other references. Now I find all the mockist tests calling this member now blow up. Then I have to go back and update all these tests - a waste of time. Why did ShouldPopulateProductsListOnViewLoadWhenPostBackIsFalse fail? Was it because the code is broken? Rather the tests are broken. I favor the one test failure = 1 place to fix . Mocking freq goes against that. Would stubs be better? If it I had a fake_class.GetProducts().. sure One place to change instead of shotgun surgery over multiple Expect calls. In the end it's a matter of style.. if you had a common utility method MockHelper.SetupExpectForGetProducts() - that'd also suffice.. but you'll see that this is uncommon. If you place a white strip on the test name, the test is hard to read. Lot of plumbing code for the mock framework hides the actual test being performed. requires you to learn this particular flavor of a mocking framework | {
"score": 5,
"source": [
"https://Stackoverflow.com/questions/47749",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1324220/"
]
} |
47,752 | Anyone have a quick method for de-duplicating a generic List in C#? | If you're using .Net 3+, you can use Linq. List<T> withDupes = LoadSomeData();List<T> noDupes = withDupes.Distinct().ToList(); | {
"score": 10,
"source": [
"https://Stackoverflow.com/questions/47752",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4541/"
]
} |
47,786 | Simple one really. In SQL, if I want to search a text field for a couple of characters, I can do: SELECT blah FROM blah WHERE blah LIKE '%text%' The documentation for App Engine makes no mention of how to achieve this, but surely it's a common enough problem? | BigTable, which is the database back end for App Engine, will scale to millions of records. Due to this, App Engine will not allow you to do any query that will result in a table scan, as performance would be dreadful for a well populated table. In other words, every query must use an index. This is why you can only do = , > and < queries. (In fact you can also do != but the API does this using a a combination of > and < queries.) This is also why the development environment monitors all the queries you do and automatically adds any missing indexes to your index.yaml file. There is no way to index for a LIKE query so it's simply not available. Have a watch of this Google IO session for a much better and more detailed explanation of this. | {
"score": 7,
"source": [
"https://Stackoverflow.com/questions/47786",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/366/"
]
} |
47,789 | When should you use generator expressions and when should you use list comprehensions in Python? # Generator expression(x*2 for x in range(256))# List comprehension[x*2 for x in range(256)] | John's answer is good (that list comprehensions are better when you want to iterate over something multiple times). However, it's also worth noting that you should use a list if you want to use any of the list methods. For example, the following code won't work: def gen(): return (something for something in get_some_stuff())print gen()[:2] # generators don't support indexing or slicingprint [5,6] + gen() # generators can't be added to lists Basically, use a generator expression if all you're doing is iterating once. If you want to store and use the generated results, then you're probably better off with a list comprehension. Since performance is the most common reason to choose one over the other, my advice is to not worry about it and just pick one; if you find that your program is running too slowly, then and only then should you go back and worry about tuning your code. | {
"score": 9,
"source": [
"https://Stackoverflow.com/questions/47789",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4883/"
]
} |
47,817 | Html Textarea elements only wrap when they reach a space or tab character. This is fine, until the user types a looooooooooooooooooooooong enough word. I'm looking for a way to strictly enforce line breaks (eg.: even if it results in "loooooooooooo \n ooooooooooong"). The best I've found is to add a zero-width unicode space after every letter, but this breaks copy and paste operations. Anyone know of a better way? Note: I'm referring to the "textarea" element here (i.e.: the one that behaves similarly to a text input) - not just a plain old block of text. | The CSS settings word-wrap:break-word and text-wrap:unrestricted appear to be CSS 3 features. Good luck finding a way to do this on current implementations. | {
"score": 5,
"source": [
"https://Stackoverflow.com/questions/47817",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4939/"
]
} |
47,824 | Using core jQuery, how do you remove all the options of a select box, then add one option and select it? My select box is the following. <Select id="mySelect" size="9"> </Select> EDIT: The following code was helpful with chaining. However, (in Internet Explorer) .val('whatever') did not select the option that was added. (I did use the same 'value' in both .append and .val .) $('#mySelect').find('option').remove().end().append('<option value="whatever">text</option>').val('whatever'); EDIT: Trying to get it to mimic this code, I use the following code whenever the page/form is reset. This select box is populated by a set of radio buttons. .focus() was closer, but the option did not appear selected like it does with .selected= "true" . Nothing is wrong with my existing code - I am just trying to learn jQuery. var mySelect = document.getElementById('mySelect');mySelect.options.length = 0;mySelect.options[0] = new Option ("Foo (only choice)", "Foo");mySelect.options[0].selected="true"; EDIT: selected answer was close to what I needed. This worked for me: $('#mySelect').children().remove().end().append('<option selected value="whatever">text</option>') ; But both answers led me to my final solution.. | $('#mySelect') .find('option') .remove() .end() .append('<option value="whatever">text</option>') .val('whatever'); | {
"score": 12,
"source": [
"https://Stackoverflow.com/questions/47824",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2755/"
]
} |
47,833 | I know you can look at the row.count or tables.count, but are there other ways to tell if a dataset is empty? | I would suggest something like:- bool nonEmptyDataSet = dataSet != null && (from DataTable t in dataSet.Tables where t.Rows.Count > 0 select t).Any(); Edits: I have significantly cleaned up the code after due consideration, I think this is much cleaner. Many thanks to Keith for the inspiration regarding the use of .Any(). In line with Keith's suggestion, here is an extension method version of this approach:- public static class ExtensionMethods { public static bool IsEmpty(this DataSet dataSet) { return dataSet == null || !(from DataTable t in dataSet.Tables where t.Rows.Count > 0 select t).Any(); } } Note, as Keith rightly corrected me on in the comments of his post, this method will work even when the data set is null. | {
"score": 5,
"source": [
"https://Stackoverflow.com/questions/47833",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/445815/"
]
} |
47,837 | I'm struggling to find the right terminology here, but if you have jQuery object... $('#MyObject') ...is it possible to extract the base element? Meaning, the equivalent of this: document.getElementById('MyObject') | Yes, use .get(index) . According to the documentation : The .get() method grants access to the DOM nodes underlying each jQuery object. | {
"score": 7,
"source": [
"https://Stackoverflow.com/questions/47837",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1923/"
]
} |
47,845 | I've heard that creating a new process on a Windows box is more expensive than on Linux. Is this true? Can somebody explain the technical reasons for why it's more expensive and provide any historical reasons for the design decisions behind those reasons? | mweerden: NT has been designed for multi-user from day one, so this is not really a reason. However, you are right about that process creation plays a less important role on NT than on Unix as NT, in contrast to Unix, favors multithreading over multiprocessing. Rob, it is true that fork is relatively cheap when COW is used, but as a matter of fact, fork is mostly followed by an exec. And an exec has to load all images as well. Discussing the performance of fork therefore is only part of the truth. When discussing the speed of process creation, it is probably a good idea to distinguish between NT and Windows/Win32. As far as NT (i.e. the kernel itself) goes, I do not think process creation (NtCreateProcess) and thread creation (NtCreateThread) is significantly slower as on the average Unix. There might be a little bit more going on, but I do not see the primary reason for the performance difference here. If you look at Win32, however, you'll notice that it adds quite a bit of overhead to process creation. For one, it requires the CSRSS to be notified about process creation, which involves LPC. It requires at least kernel32 to be loaded additionally, and it has to perform a number of additional bookkeeping work items to be done before the process is considered to be a full-fledged Win32 process. And let's not forget about all the additional overhead imposed by parsing manifests, checking if the image requires a compatbility shim, checking whether software restriction policies apply, yada yada. That said, I see the overall slowdown in the sum of all those little things that have to be done in addition to the raw creation of a process, VA space, and initial thread. But as said in the beginning -- due to the favoring of multithreading over multitasking, the only software that is seriously affected by this additional expense is poorly ported Unix software. Although this sitatuion changes when software like Chrome and IE8 suddenly rediscover the benefits of multiprocessing and begin to frequently start up and teardown processes... | {
"score": 6,
"source": [
"https://Stackoverflow.com/questions/47845",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4883/"
]
} |
47,854 | On linux, it's possible to create a tun interface using a tun driver which provides a "network interface psuedo-device" that can be treated as a regular network interface. Is there a way to do this programmatically on windows? Is there a way to do this without writing my own driver? | You can do this on XP with the Microsoft Loopback Adapter which is a driver for a virtual network card. On newer Windows version: Installing the Microsoft Loopback Adapter in Windows 8 and Windows Server 2012 | {
"score": 5,
"source": [
"https://Stackoverflow.com/questions/47854",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4883/"
]
} |
47,882 | What is a magic number? Why should it be avoided? Are there cases where it's appropriate? | A magic number is a direct usage of a number in the code. For example, if you have (in Java): public class Foo { public void setPassword(String password) { // don't do this if (password.length() > 7) { throw new InvalidArgumentException("password"); } }} This should be refactored to: public class Foo { public static final int MAX_PASSWORD_SIZE = 7; public void setPassword(String password) { if (password.length() > MAX_PASSWORD_SIZE) { throw new InvalidArgumentException("password"); } }} It improves readability of the code and it's easier to maintain. Imagine the case where I set the size of the password field in the GUI. If I use a magic number, whenever the max size changes, I have to change in two code locations. If I forget one, this will lead to inconsistencies. The JDK is full of examples like in Integer , Character and Math classes. PS: Static analysis tools like FindBugs and PMD detects the use of magic numbers in your code and suggests the refactoring. | {
"score": 10,
"source": [
"https://Stackoverflow.com/questions/47882",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2915/"
]
} |
47,886 | We have an SEO team at my office, and one of their dictums is that having lots of <script> blocks inline with the HTML is apocalypticly bad. As a developer that makes no sense to me at all. Surely the Google search engineers, who are the smartest people on the planet, know how to skip over such blocks? My gut instinct is that minimizing script blocks is a superstition that comes from the early ages of search engine optimizations, and that in today's world it means nothing. Does anyone have any insight on this? per our SEO guru, script blocks (especially those that are in-line, or occur before actual content) are very, very bad, and make the google bots give up before processing your actual content. Seems like bull to me, but I'd like to see what others say. | It's been ages since I've played the reading google's tea leafs game, but there are a few reasons your SEO expert might be saying this Three or four years back there was a bit of conventional wisdom floating around that the search engine algorithms would give more weight to search terms that happened sooner in the page. If all other things were equal on Pages A and B, if Page A mentions widgets earlier in the HTML file than Page B, Page A "wins". It's not that Google's engineers and PhD employees couldn't skip over the blocks, it's that they found a valuable metric in their presence. Taking that into account, it's easy to see how unless something "needs" (see #2 below) to be in the head of a document, an SEO obsessed person would want it out. The SEO people who aren't offering a quick fix tend to be proponents of well-crafted, validating/conforming HTML/XHTML structure. Inline Javascript, particularly the kind web ignorant software engineers tend to favor makes these people (I'm one) seethe. The bias against script tags themselves could also stem from some of the work Yahoo and others have done in optimizing Ajax applications (don't make the browser parse Javascript until is has to). Not necessarily directly related to SEO, but a best practice a white hat SEO type will have picked up. It's also possible you're misunderstanding each other. Content that's generated by Javascript is considered controversial in the SEO world. It's not that Google can't "see" this content, it's that people are unsure how its presence will rank the page, as a lot of black hat SEO games revolve around hiding and showing content with Javascript. SEO is at best Kremlinology and at worse a field that the black hats won over a long time ago. My free unsolicited advice is to stay out of the SEO game, present your managers with estimates as so how long it will take to implement their SEO related changes, and leave it at that. | {
"score": 5,
"source": [
"https://Stackoverflow.com/questions/47886",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2757/"
]
} |
47,901 | Is it possible for UDP data to come to you corrupted? I know it is possible for it to be lost. | UDP packets use a 16 bit checksum. It is not impossible for UDP packets to have corruption, but it's pretty unlikely. In any case it is not more susceptible to corruption than TCP. | {
"score": 6,
"source": [
"https://Stackoverflow.com/questions/47901",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4946/"
]
} |
47,903 | For general protocol message exchange, which can tolerate some packet loss. How much more efficient is UDP over TCP? | UDP is faster than TCP, and the simple reason is because its non-existent acknowledge packet (ACK) that permits a continuous packet stream, instead of TCP that acknowledges a set of packets, calculated by using the TCP window size and round-trip time (RTT). For more information, I recommend the simple, but very comprehensible Skullbox explanation (TCP vs. UDP) | {
"score": 8,
"source": [
"https://Stackoverflow.com/questions/47903",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4946/"
]
} |
47,919 | I'm used to doing all my coding in one C file. However, I'm working on a project large enough that it becomes impractical to do so. I've been #including them together but I've run into cases where I'm #including some files multiple times, etc. I've heard of .h files, but I'm not sure what their function is (or why having 2 files is better than 1). What strategies should I use for organizing my code? Is it possible to separate "public" functions from "private" ones for a particular file? This question precipitated my inquiry. The tea.h file makes no reference to the tea.c file. Does the compiler "know" that every .h file has a corresponding .c file? | You should regard .h files as interface files of your .c file. Every .c file represents a module with a certain amount of functionality. If functions in a .c file are used by other modules (i.e. other .c files) put the function prototype in the .h interface file. By including the interface file in your original modules .c file and every other .c file you need the function in, you make this function available to other modules. If you only need a function in a certain .c file (not in any other module), declare its scope static. This means it can only be called from within the c file it is defined in. Same goes for variables that are used across multiple modules. They should go in the header file and there they have to marked with the keyword 'extern'. Note: For functions the keyword 'extern' is optional. Functions are always considered 'extern'. The inclusion guards in header files help to not include the same header file multiple times. For example: Module1.c: #include "Module1.h" static void MyLocalFunction(void); static unsigned int MyLocalVariable; unsigned int MyExternVariable; void MyExternFunction(void) { MyLocalVariable = 1u; /* Do something */ MyLocalFunction(); } static void MyLocalFunction(void) { /* Do something */ MyExternVariable = 2u; } Module1.h: #ifndef __MODULE1.H #define __MODULE1.H extern unsigned int MyExternVariable; void MyExternFunction(void); #endif Module2.c #include "Module.1.h" static void MyLocalFunction(void); static void MyLocalFunction(void) { MyExternVariable = 1u; MyExternFunction(); } | {
"score": 6,
"source": [
"https://Stackoverflow.com/questions/47919",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/658/"
]
} |
47,937 | Either I had a bad dream recently or I am just too stupid to google, but I remember that someone somewhere wrote that ASP.net has a Function which allows "merging" multiple JavaScript files automatically and only delivering one file to the client, thus reducing the number of HTTP Requests. Server Side, you still kept all the individual .js files, but the Runtime itself then creates one big JavaScript file which is then included in the script-tag instead and can be properly cached etc. In case that this function really exists and is not just a product of my imagination, can someone point me in the right direction please? | It's called Script Combining . There is a video example from asp.net explaining it here . | {
"score": 5,
"source": [
"https://Stackoverflow.com/questions/47937",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/91/"
]
} |
47,941 | I'm trying to upload an application to the iPhone App Store, but I get this error message from iTunes Connect: The binary you uploaded was invalid. The signature was invalid, or it was not signed with an Apple submission certificate. Note: The details of original question have been removed, as this page has turned into a repository for all information about possible causes of that particular error message. For general information on submitting iPhone applications to the App Store, see Steps to upload an iPhone application to the AppStore . | It's been my experience that Xcode occasionally gets confused about which signing certificate to use. I got into the habit of quitting and restarting Xcode after any change to the code signing settings (and doing a clean build) to work around this problem. | {
"score": 6,
"source": [
"https://Stackoverflow.com/questions/47941",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1175/"
]
} |
47,953 | I've read some about .egg files and I've noticed them in my lib directory but what are the advantages/disadvantages of using then as a developer? | From the Python Enterprise Application Kit community : "Eggs are to Pythons as Jars are to Java..." Python eggs are a way of bundling additional information with a Python project, that allows the project's dependencies to be checked and satisfied at runtime, as well as allowing projects to provide plugins for other projects. There are several binary formats that embody eggs, but the most common is '.egg' zipfile format, because it's a convenient one for distributing projects. All of the formats support including package-specific data, project-wide metadata, C extensions, and Python code. The primary benefits of Python Eggs are: They enable tools like the "Easy Install" Python package manager .egg files are a "zero installation" format for a Python package; no build or install step is required, just put them on PYTHONPATH or sys.path and use them (may require the runtime installed if C extensions or data files are used) They can include package metadata, such as the other eggs they depend on They allow "namespace packages" (packages that just contain other packages) to be split into separate distributions (e.g. zope. , twisted. , peak.* packages can be distributed as separate eggs, unlike normal packages which must always be placed under the same parent directory. This allows what are now huge monolithic packages to be distributed as separate components.) They allow applications or libraries to specify the needed version of a library, so that you can e.g. require("Twisted-Internet>=2.0") before doing an import twisted.internet. They're a great format for distributing extensions or plugins to extensible applications and frameworks (such as Trac, which uses eggs for plugins as of 0.9b1), because the egg runtime provides simple APIs to locate eggs and find their advertised entry points (similar to Eclipse's "extension point" concept). There are also other benefits that may come from having a standardized format, similar to the benefits of Java's "jar" format. -Adam | {
"score": 6,
"source": [
"https://Stackoverflow.com/questions/47953",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4491/"
]
} |
47,972 | I'm researching and experimenting more with Groovy and I'm trying to wrap my mind around the pros and cons of implementing things in Groovy that I can't/don't do in Java. Dynamic programming is still just a concept to me since I've been deeply steeped static and strongly typed languages. Groovy gives me the ability to duck-type , but I can't really see the value. How is duck-typing more productive than static typing? What kind of things can I do in my code practice to help me grasp the benefits of it? I ask this question with Groovy in mind but I understand it isn't necessarily a Groovy question so I welcome answers from every code camp. | A lot of the comments for duck typing don't really substantiate the claims. Not "having to worry" about a type is not sustainable for maintenance or making an application extendable. I've really had a good opportunity to see Grails in action over my last contract and its quite funny to watch really. Everyone is happy about the gains in being able to "create-app" and get going - sadly it all catches up to you on the back end. Groovy seems the same way to me. Sure you can write very succinct code and definitely there is some nice sugar in how we get to work with properties, collections, etc... But the cost of not knowing what the heck is being passed back and forth just gets worse and worse. At some point your scratching your head wondering why the project has become 80% testing and 20% work. The lesson here is that "smaller" does not make for "more readable" code. Sorry folks, its simple logic - the more you have to know intuitively then the more complex the process of understanding that code becomes. It's why GUI's have backed off becoming overly iconic over the years - sure looks pretty but WTH is going on is not always obvious. People on that project seemed to have troubles "nailing down" the lessons learned, but when you have methods returning either a single element of type T, an array of T, an ErrorResult or a null ... it becomes rather apparent. One thing working with Groovy has done for me however - awesome billable hours woot! | {
"score": 5,
"source": [
"https://Stackoverflow.com/questions/47972",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3030/"
]
} |
47,980 | I'm really beginning to understand what people mean when they say that C++'s error messages are pretty terrible in regards to templates. I've seen horrendously long errors for things as simple as a function not matching its prototype. Are there any tricks to deciphering these errors? EDIT: I'm using both gcc and MSVC. They both seem to be pretty terrible. | You can try the following tool to make things more sane: http://www.bdsoft.com/tools/stlfilt.html | {
"score": 5,
"source": [
"https://Stackoverflow.com/questions/47980",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2147/"
]
} |
47,981 | How do I set, clear, and toggle a bit? | Setting a bit Use the bitwise OR operator ( | ) to set a bit. number |= 1UL << n; That will set the n th bit of number . n should be zero, if you want to set the 1 st bit and so on upto n-1 , if you want to set the n th bit. Use 1ULL if number is wider than unsigned long ; promotion of 1UL << n doesn't happen until after evaluating 1UL << n where it's undefined behaviour to shift by more than the width of a long . The same applies to all the rest of the examples. Clearing a bit Use the bitwise AND operator ( & ) to clear a bit. number &= ~(1UL << n); That will clear the n th bit of number . You must invert the bit string with the bitwise NOT operator ( ~ ), then AND it. Toggling a bit The XOR operator ( ^ ) can be used to toggle a bit. number ^= 1UL << n; That will toggle the n th bit of number . Checking a bit You didn't ask for this, but I might as well add it. To check a bit, shift the number n to the right, then bitwise AND it: bit = (number >> n) & 1U; That will put the value of the n th bit of number into the variable bit . Changing the n th bit to x Setting the n th bit to either 1 or 0 can be achieved with the following on a 2's complement C++ implementation: number ^= (-x ^ number) & (1UL << n); Bit n will be set if x is 1 , and cleared if x is 0 . If x has some other value, you get garbage. x = !!x will booleanize it to 0 or 1. To make this independent of 2's complement negation behaviour (where -1 has all bits set, unlike on a 1's complement or sign/magnitude C++ implementation), use unsigned negation. number ^= (-(unsigned long)x ^ number) & (1UL << n); or unsigned long newbit = !!x; // Also booleanize to force 0 or 1number ^= (-newbit ^ number) & (1UL << n); It's generally a good idea to use unsigned types for portable bit manipulation. or number = (number & ~(1UL << n)) | (x << n); (number & ~(1UL << n)) will clear the n th bit and (x << n) will set the n th bit to x . It's also generally a good idea to not to copy/paste code in general and so many people use preprocessor macros (like the community wiki answer further down ) or some sort of encapsulation. | {
"score": 13,
"source": [
"https://Stackoverflow.com/questions/47981",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/445087/"
]
} |
47,989 | Is there a risk of legal trouble if you include GPL or LGPL licensed icons in a closed source software? Would it force it to become open source just to include the icon? Does it matter if the icon is compiled as a resource? Are the creative common licensed icons safe to use if you follow the attribution rules specified by the license? | For GPL, yes. Any GPL Code/Content that's compiled into your Application or the Package will make it GPL. (Edit: What could be safe is if the Icon is a separate file and is used. That could be a grey area, as you are not using GPL Code to access it. But any attempt to embed it will force your program to GPL, it's one of the most restrictive licenses out there) LGPL is fine: Any modification to LGPL Content has to be released under LGPL, but using the Code/Content is safe. Addition: Like LGPL, CreativeCommons usually only affects the Content you're using. So if you're using a CC Icon and modify it, you will have to give out the modified item under CreativeCommons, but your Application is not affected. Just mind the "Non-Commercial" Clause if it exists. | {
"score": 6,
"source": [
"https://Stackoverflow.com/questions/47989",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4789/"
]
} |
48,006 | Right up front: I do not want to start a religious war. I've used vi for as long as I can remember, and the few times I've tried to pick up Emacs I've been so lost that I've quickly given up. Lots of people find Emacs very powerful, however. Its programmability is somewhat legendary. I'm primarily doing Solaris+Java development, and I'd like to ask a simple question: will my productivity increase if I invest time in getting my head around Emacs? Is the functionality that it offers over Vim going to be paid back in productivity increases in a reasonable timeframe? Repeat: I don't want a "my editor is better than yours" answer. I just want a yes or no answer as to whether it's worth investing the time or not. Will my productivity really increase? | I prefer emacs to vi, but I'm comfortable in both. There are some things that you can do in emacs that make it more powerful than vi, but not all of them are even programming-related. (Can you send email or read news from within vi? No, but who cares?) If you're comfortable with lisp (I'm not), you might be able to write add-ons and modes and stuff to make your life easier, but that's just likely to be syntax colouring and brace matching and eye candy like that. I will stop rambling now. Will your productivity increase using emacs? No. Update : See my comment below. Since I posted this, I have come across ways that using emacs has made me more productive than using vi. | {
"score": 6,
"source": [
"https://Stackoverflow.com/questions/48006",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/826/"
]
} |
48,017 | Can someone explain the mechanics of a jump table and why is would be needed in embedded systems? | A jump table can be either an array of pointers to functions or an array of machine code jump instructions. If you have a relatively static set of functions (such as system calls or virtual functions for a class) then you can create this table once and call the functions using a simple index into the array. This would mean retrieving the pointer and calling a function or jumping to the machine code depending on the type of table used. The benefits of doing this in embedded programming are: Indexes are more memory efficient than machine code or pointers, so there is a potential for memory savings in constrained environments. For any particular function the index will remain stable and changing the function merely requires swapping out the function pointer. If does cost you a tiny bit of performance for accessing the table, but this is no worse than any other virtual function call. | {
"score": 7,
"source": [
"https://Stackoverflow.com/questions/48017",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/445087/"
]
} |
48,041 | I'm working on a project with a friend that will utilize Hbase to store it's data. Are there any good query examples? I seem to be writing a ton of Java code to iterate through lists of RowResult's when, in SQL land, I could write a simple query. Am I missing something? Or is Hbase missing something? | I think you, like many of us, are making the mistake of treating bigtable and HBase like just another RDBMS when it's actually a column-oriented storage model meant for efficiently storing and retrieving large sets of sparse data. This means storing, ideally, many-to-one relationships within a single row, for example. Your queries should return very few rows but contain (potentially) many datapoints. Perhaps if you told us more about what you were trying to store, we could help you design your schema to match the bigtable/HBase way of doing things. For a good rundown of what HBase does differently than a "traditional" RDBMS, check out this awesome article: Matching Impedance: When to use HBase by Bryan Duxbury. | {
"score": 5,
"source": [
"https://Stackoverflow.com/questions/48041",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4962/"
]
} |
48,053 | I read somewhere once that the modulus operator is inefficient on small embedded devices like 8 bit micro-controllers that do not have integer division instruction. Perhaps someone can confirm this but I thought the difference is 5-10 time slower than with an integer division operation. Is there another way to do this other than keeping a counter variable and manually overflowing to 0 at the mod point? const int FIZZ = 6;for(int x = 0; x < MAXCOUNT; x++){ if(!(x % FIZZ)) print("Fizz\n"); // slow on some systems} vs: The way I am currently doing it: const int FIZZ = 6;int fizzcount = 1;for(int x = 1; x < MAXCOUNT; x++){ if(fizzcount >= FIZZ) { print("Fizz\n"); fizzcount = 0; }} | Ah, the joys of bitwise arithmetic. A side effect of many division routines is the modulus - so in few cases should division actually be faster than modulus. I'm interested to see the source you got this information from. Processors with multipliers have interesting division routines using the multiplier, but you can get from division result to modulus with just another two steps (multiply and subtract) so it's still comparable. If the processor has a built in division routine you'll likely see it also provides the remainder. Still, there is a small branch of number theory devoted to Modular Arithmetic which requires study if you really want to understand how to optimize a modulus operation. Modular arithmatic, for instance, is very handy for generating magic squares . So, in that vein, here's a very low level look at the math of modulus for an example of x, which should show you how simple it can be compared to division: Maybe a better way to think about the problem is in terms of numberbases and modulo arithmetic. For example, your goal is to compute DOWmod 7 where DOW is the 16-bit representation of the day of theweek. You can write this as: DOW = DOW_HI*256 + DOW_LO DOW%7 = (DOW_HI*256 + DOW_LO) % 7 = ((DOW_HI*256)%7 + (DOW_LO % 7)) %7 = ((DOW_HI%7 * 256%7) + (DOW_LO%7)) %7 = ((DOW_HI%7 * 4) + (DOW_LO%7)) %7 Expressed in this manner, you can separately compute the modulo 7result for the high and low bytes. Multiply the result for the high by4 and add it to the low and then finally compute result modulo 7. Computing the mod 7 result of an 8-bit number can be performed in asimilar fashion. You can write an 8-bit number in octal like so: X = a*64 + b*8 + c Where a, b, and c are 3-bit numbers. X%7 = ((a%7)*(64%7) + (b%7)*(8%7) + c%7) % 7 = (a%7 + b%7 + c%7) % 7 = (a + b + c) % 7 since 64%7 = 8%7 = 1 Of course, a, b, and c are c = X & 7 b = (X>>3) & 7 a = (X>>6) & 7 // (actually, a is only 2-bits). The largest possible value for a+b+c is 7+7+3 = 17 . So, you'll needone more octal step. The complete (untested) C version could bewritten like: unsigned char Mod7Byte(unsigned char X){ X = (X&7) + ((X>>3)&7) + (X>>6); X = (X&7) + (X>>3); return X==7 ? 0 : X;} I spent a few moments writing a PIC version. The actual implementationis slightly different than described above Mod7Byte: movwf temp1 ; andlw 7 ;W=c movwf temp2 ;temp2=c rlncf temp1,F ; swapf temp1,W ;W= a*8+b andlw 0x1F addwf temp2,W ;W= a*8+b+c movwf temp2 ;temp2 is now a 6-bit number andlw 0x38 ;get the high 3 bits == a' xorwf temp2,F ;temp2 now has the 3 low bits == b' rlncf WREG,F ;shift the high bits right 4 swapf WREG,F ; addwf temp2,W ;W = a' + b' ; at this point, W is between 0 and 10 addlw -7 bc Mod7Byte_L2Mod7Byte_L1: addlw 7Mod7Byte_L2: return Here's a liitle routine to test the algorithm clrf x clrf countTestLoop: movf x,W RCALL Mod7Byte cpfseq count bra fail incf count,W xorlw 7 skpz xorlw 7 movwf count incfsz x,F bra TestLooppassed: Finally, for the 16-bit result (which I have not tested), you couldwrite: uint16 Mod7Word(uint16 X){ return Mod7Byte(Mod7Byte(X & 0xff) + Mod7Byte(X>>8)*4);} Scott | {
"score": 7,
"source": [
"https://Stackoverflow.com/questions/48053",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/445087/"
]
} |
48,087 | I need a quick algorithm to select 5 random elements from a generic list. For example, I'd like to get 5 random elements from a List<string> . | Iterate through and for each element make the probability of selection = (number needed)/(number left) So if you had 40 items, the first would have a 5/40 chance of being selected. If it is, the next has a 4/39 chance, otherwise it has a 5/39 chance. By the time you get to the end you will have your 5 items, and often you'll have all of them before that. This technique is called selection sampling , a special case of Reservoir Sampling . It's similar in performance to shuffling the input, but of course allows the sample to be generated without modifying the original data. | {
"score": 8,
"source": [
"https://Stackoverflow.com/questions/48087",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4541/"
]
} |
48,088 | I was surprised recently to find that it's possible to have a return statement in a finally block in Java. It seems like lots of people think it's a bad thing to do as described in ' Don't return in a finally clause '. Scratching a little deeper, I also found ' Java's return doesn't always ' which shows some pretty horrible examples of other types of flow control in finally blocks. So, my question is, can anyone give me an example where a return statement (or other flow control) in a finally block produces better / more readable code? | The examples you provided are reason enough to not use flow-control from finally. Even if there's a contrived example where it's "better," consider the developer who has to maintain your code later and who might not be aware of the subtleties. That poor developer might even be you.... | {
"score": 8,
"source": [
"https://Stackoverflow.com/questions/48088",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/797/"
]
} |
48,094 | So I have a pointer to an array of pointers. If I delete it like this: delete [] PointerToPointers; Will that delete all the pointed to pointers as well? If not, do I have to loop over all of the pointers and delete them as well, or is there an easier way to do it? My google-fu doesn't seem to give me any good answers to this question. (And yeah, I know I need to use a vector. This is one of those "catch up on C++" type assignments in school.) | Yes you have to loop over the pointers, deleting individually. Reason: What if other code had pointers to the objects in your array? The C++ compiler doesn't know if that's true or not, so you have to be explicit. For an "easier way," two suggestions: (1) Make a subroutine for this purpose so at least you won't have to write the code more than once. (2) Use the "smart pointer" design paradigm where you hold an array of objects with reference-counters, then the objects are deleted when the objects are no longer referenced by any code. | {
"score": 6,
"source": [
"https://Stackoverflow.com/questions/48094",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2147/"
]
} |
48,123 | I've been learning python for a while now with some success. I even managed to create one or two (simple) programs using PyGtk + Glade. The thing is: I am not sure if the best way to use GTK with python is by building the interfaces using Glade. I was wondering if the more experienced ones among us (remember, I'm just a beginner) could point out the benefits and caveats of using Glade as opposed to creating everything in the code itself (assuming that learning the correct gtk bindings wouldn't exactly be a problem). | I would say that it depends: if you find that using Glade you can build the apps you want or need to make than that's absolutely fine. If however you actually want to learn how GTK works or you have some non-standard UI requirements you will have to dig into GTK internals (which are not that complicated). Personally I'm usually about 5 minutes into a rich client when I need some feature or customization that is simply impossible through a designer such as Glade or Stetic . Perhaps it's just me. Nevertheless it is still useful for me to bootstrap window design using a graphical tool. My recommendation: if making rich clients using GTK is going to be a significant part of your job/hobby then learn GTK as well since you will need to write that code someday. P.S. I personally find Stetic to be superior to Glade for design work, if a little bit more unstable. | {
"score": 5,
"source": [
"https://Stackoverflow.com/questions/48123",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/802/"
]
} |
48,124 | How can I generate a (pseudo)random alpha-numeric string, something like: 'd79jd8c' in PHP? | First make a string with all your possible characters: $characters = 'abcdefghijklmnopqrstuvwxyz0123456789'; You could also use range() to do this more quickly. Then, in a loop, choose a random number and use it as the index to the $characters string to get a random character, and append it to your string: $string = ''; $max = strlen($characters) - 1; for ($i = 0; $i < $random_string_length; $i++) { $string .= $characters[mt_rand(0, $max)]; } $random_string_length is the length of the random string. | {
"score": 8,
"source": [
"https://Stackoverflow.com/questions/48124",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/115/"
]
} |
48,126 | Documentation is severely lacking on anything to do with stored procedures in mysql with PHP. I currently have a stored procedure that I call via PHP, how can I get the value of an out parameter? | it looks like it's answered in this post: http://forums.mysql.com/read.php?52,198596,198717#msg-198717 With mysqli PHP API: Assume sproc myproc( IN i int, OUT j int ): $mysqli = new mysqli( "HOST", "USR", "PWD", "DBNAME" );$ivalue=1;$res = $mysqli->multi_query( "CALL myproc($ivalue,@x);SELECT @x" );if( $res ) { $results = 0; do { if ($result = $mysqli->store_result()) { printf( "<b>Result #%u</b>:<br/>", ++$results ); while( $row = $result->fetch_row() ) { foreach( $row as $cell ) echo $cell, " "; } $result->close(); if( $mysqli->more_results() ) echo "<br/>"; } } while( $mysqli->next_result() );}$mysqli->close(); | {
"score": 5,
"source": [
"https://Stackoverflow.com/questions/48126",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1638/"
]
} |
48,144 | It seems like anything you can do with bytecode you can do just as easily and much faster in native code. In theory, you could even retain platform and language independence by distributing programs and libraries in bytecode then compiling to native code at installation, rather than JITing it. So in general, when would you want to execute bytecode instead of native? | Hank Shiffman from SGI said (a long time ago, but it's till true): There are three advantages of Java using byte code instead of going to the native code of the system: Portability : Each kind of computer has its unique instruction set. While some processors include the instructions for their predecessors, it's generally true that a program that runs on one kind of computer won't run on any other. Add in the services provided by the operating system, which each system describes in its own unique way, and you have a compatibility problem. In general, you can't write and compile a program for one kind of system and run it on any other without a lot of work. Java gets around this limitation by inserting its virtual machine between the application and the real environment (computer + operating system). If an application is compiled to Java byte code and that byte code is interpreted the same way in every environment then you can write a single program which will work on all the different platforms where Java is supported. (That's the theory, anyway. In practice there are always small incompatibilities lying in wait for the programmer.) Security : One of Java's virtues is its integration into the Web. Load a web page that uses Java into your browser and the Java code is automatically downloaded and executed. But what if the code destroys files, whether through malice or sloppiness on the programmer's part? Java prevents downloaded applets from doing anything destructive by disallowing potentially dangerous operations. Before it allows the code to run it examines it for attempts to bypass security. It verifies that data is used consistently: code that manipulates a data item as an integer at one stage and then tries to use it as a pointer later will be caught and prevented from executing. (The Java language doesn't allow pointer arithmetic, so you can't write Java code to do what we just described. However, there is nothing to prevent someone from writing destructive byte code themselves using a hexadecimal editor or even building a Java byte code assembler.) It generally isn't possible to analyze a program's machine code before execution and determine whether it does anything bad. Tricks like writing self-modifying code mean that the evil operations may not even exist until later. But Java byte code was designed for this kind of validation: it doesn't have the instructions a malicious programmer would use to hide their assault. Size : In the microprocessor world RISC is generally preferable over CISC. It's better to have a small instruction set and use many fast instructions to do a job than to have many complex operations implemented as single instructions. RISC designs require fewer gates on the chip to implement their instructions, allowing for more room for pipelines and other techniques to make each instruction faster. In an interpreter, however, none of this matters. If you want to implement a single instruction for the switch statement with a variable length depending on the number of case clauses, there's no reason not to do so. In fact, a complex instruction set is an advantage for a web-based language: it means that the same program will be smaller (fewer instructions of greater complexity), which means less time to transfer across our speed-limited network. So when considering byte code vs native, consider which trade-offs you want to make between portability, security, size, and execution speed. If speed is the only important factor, go native. If any of the others are more important, go with bytecode. I'll also add that maintaining a series of OS and architecture-targeted compilations of the same code base for every release can become very tedious. It's a huge win to use the same Java bytecode on multiple platforms and have it "just work." | {
"score": 6,
"source": [
"https://Stackoverflow.com/questions/48144",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1891/"
]
} |
48,198 | How do I find out which process is listening on a TCP or UDP port on Windows? | PowerShell TCP Get-Process -Id (Get-NetTCPConnection -LocalPort YourPortNumberHere).OwningProcess UDP Get-Process -Id (Get-NetUDPEndpoint -LocalPort YourPortNumberHere).OwningProcess cmd netstat -a -b (Add -n to stop it trying to resolve hostnames, which will make it a lot faster.) Note Dane's recommendation for TCPView . It looks very useful! -a Displays all connections and listening ports. -b Displays the executable involved in creating each connection or listening port. In some cases well-known executables host multiple independent components, and in these cases the sequence of components involved in creating the connection or listening port is displayed. In this case the executable name is in [] at the bottom, on top is the component it called, and so forth until TCP/IP was reached. Note that this option can be time-consuming and will fail unless you have sufficient permissions. -n Displays addresses and port numbers in numerical form. -o Displays the owning process ID associated with each connection. | {
"score": 13,
"source": [
"https://Stackoverflow.com/questions/48198",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4883/"
]
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.