source_id
int64 1
74.7M
| question
stringlengths 0
40.2k
| response
stringlengths 0
111k
| metadata
dict |
---|---|---|---|
154,853 | I have a folder, c:\websites\test , and it contains folders and files that were checked out from a repository that no longer exists. How do I get Subversion to stop tracking that folder and any of the subfolders and files? I know I could simply delete the .svn folder, but there are a lot of sub-folders in many layers. | Also, if you are using TortoiseSVN, just export to the current working copy location and it will remove the .svn folders and files. http://tortoisesvn.net/docs/release/TortoiseSVN_en/tsvn-dug-export.html#tsvn-dug-export-unversion Updated Answer for Subversion 1.7: In Subversion 1.7 the working copy has been revised extensively. There is only one .svn folder, located in the base of the working copy. If you are using 1.7, then just deleting the .svn folder and its contents is an easy solution (regardless of using TortoiseSVN or command line tools). | {
"score": 9,
"source": [
"https://Stackoverflow.com/questions/154853",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3747/"
]
} |
154,862 | How can I convert a JavaScript string value to be in all lower case letters? Example: "Your Name" to "your name" | var lowerCaseName = "Your Name".toLowerCase(); | {
"score": 12,
"source": [
"https://Stackoverflow.com/questions/154862",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5440/"
]
} |
154,897 | Did you ever had a bug in your code, you could not resolve? I hope I'm not the only one out there, who made this experience ... There exist some classes of bugs, that are very hard to track down: timing-related bugs (that occur during inter-process-communication for example) memory-related bugs (most of you know appropriate examples, I guess !!!) event-related bugs (hard to debug, because every break point you run into makes your IDE the target for mouse release/focus events ...) OS-dependent bugs hardware dependent bugs (occurs onrelease machine, but not ondeveloper machine) ... To be honest, from time to time I fail to fix such a bug on my own ... After debugging for hours (or sometimes even days) I feel very demoralized. What do you do in this situation (apart from asking others for help which is not always possible)? Do you use pencil and paper instead of a debugger face for another thing and return tothis bug later ... Please let me know! | Some things that help: 1) Take a break, approach the bug from a different angle. 2) Get more aggressive with tracing and logging. 3) Have another pair of eyes look at it. 4) A usual last resort is to figure out a way to make the bug irrelevant by changing the fundamental conditions in which it occurs 5) Smash and break things. (Stress relief only!) | {
"score": 6,
"source": [
"https://Stackoverflow.com/questions/154897",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2012356/"
]
} |
154,900 | I was wrestling with some Perl that uses hash references. In the end it turned out that my problem was the line: $myhash{$key} |= {}; That is, "assign $myhash{$key} a reference to an empty hash, unless it already has a value". Dereferencing this and trying to use it as a hash reference, however, resulted in interpreter errors about using a string as a hash reference. Changing it to: if( ! exists $myhash{$key}) { $myhash{$key} = {};} ... made things work. So I don't have a problem . But I'm curious about what was going on. Can anyone explain? | The reason you're seeing an error about using a string as a hash reference is because you're using the wrong operator. |= means "bitwise-or-assign." In other words, $foo |= $bar; is the same as $foo = $foo | $bar What's happening in your example is that your new anonymous hash reference is getting stringified, then bitwise-ORed with the value of $myhash{$key} . To confuse matters further, if $myhash{$key} is undefined at the time, the value is the simple stringification of the hash reference, which looks like HASH(0x80fc284) . So if you do a cursory inspection of the structure, it may look like a hash reference, but it's not. Here's some useful output via Data::Dumper : perl -MData::Dumper -le '$hash{foo} |= { }; print Dumper \%hash' $VAR1 = { 'foo' => 'HASH(0x80fc284)' }; And here's what you get when you use the correct operator: perl -MData::Dumper -le '$hash{foo} ||= { }; print Dumper \%hash' $VAR1 = { 'foo' => {} }; | {
"score": 5,
"source": [
"https://Stackoverflow.com/questions/154900",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7512/"
]
} |
154,964 | I have a question regarding the two additional columns (timeCreated, timeLastUpdated) for each record that we see in many solutions. My question: Is there a better alternative? Scenario: You have a huge DB (in terms of tables, not records), and then the customer comes and asks you to add "timestamping" to 80% of your tables. I believe this can be accomplished by using a separate table (TIMESTAMPS). This table would have, in addition to the obvious timestamp column, the table name and the primary key for the table being updated. (I'm assuming here that you use an int as primary key for most of your tables, but the table name would most likely have to be a string). To picture this suppose this basic scenario. We would have two tables: PAYMENT :- (your usual records) TIMESTAMP :- {current timestamp} + { TABLE_UPDATED , id_of_entry_updated , timestamp_type } Note that in this design you don't need those two "extra" columns in your native payment object (which, by the way, might make it thru your ORM solution) because you are now indexing by TABLE_UPDATED and id_of_entry_updated . In addition, timestamp_type will tell you if the entry is for insertion (e.g "1"), update (e.g "2"), and anything else you may want to add, like "deletion". I would like to know what do you think about this design. I'm most interested in best practices, what works and scales over time. References, links, blog entries are more than welcome. I know of at least one patent (pending) that tries to address this problem, but it seems details are not public at this time. Cheers,Eduardo | While you're at it, also record the user who made the change. The flaw with the separate-table design (in addition to the join performance highlighted by others) is that it makes the assumption that every table has an identity column for the key. That's not always true. If you use SQL Server, the new 2008 version supports something they call Change Data Capture that should take away a lot of the pain you're talking about. I think Oracle may have something similar as well. Update: Apparently Oracle calls it the same thing as SQL Server. Or rather, SQL Server calls it the same thing as Oracle, since Oracle's implementation came first ;) http://www.oracle.com/technology/oramag/oracle/03-nov/o63tech_bi.html | {
"score": 5,
"source": [
"https://Stackoverflow.com/questions/154964",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/23920/"
]
} |
155,054 | Is it possible to define a timestamp column in a MySQL table that will automatically be updated every time a field in the same row is modified? Ideally this column should initially be set to the time a row was inserted. Cheers,Don | That is the default functionality of the timestamp column type. However, note that the format of this type is yyyymmddhhmmss (all digits, no colons or other separation). EDIT: The above comment about the format is only true for versions of MySQL < 4.1... Later versions format it like a DateTime | {
"score": 6,
"source": [
"https://Stackoverflow.com/questions/155054",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2648/"
]
} |
155,069 | Procedural generation has been brought into the spotlight recently (by Spore, MMOs, etc), and it seems like an interesting/powerful programming technique. My questions are these: Do you know of any mid-sized projects that utilize procedural generation techniques? What language/class of languages is best for procedural generation? Can you use procedural generation for "serious" code? (i.e., not a game) | You should probably start with a little theory and simple examples such as the midpoint displacement algorithm . You should also learn a little about Perlin Noise if you are interested in generating graphics. I used this to get me started with my final year project on procedural generation. Fractals are closely related to procedural generation. Terragen and SpeedTree will show you some amazing possibilities of procedural generation. Procedural generation is a technique that can be used in any language (it is definitely not restricted to procedural languages such as C, as it can be used in OO languages such as Java, and Logic languages such as Prolog). A good understanding of recursion in any language will strengthen your grasp of Procedural Generation. As for 'serious' or non-game code, procedural generation techniques have been used to: simulate the growth of cities in order to plan for traffic management to simulate the growth of blood vessels SpeedTree is used in movies and architectural presentations | {
"score": 8,
"source": [
"https://Stackoverflow.com/questions/155069",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/10601/"
]
} |
155,071 | Do you have a simple debounce routine handy to deal with a single switch input? This is a simple bare metal system without any OS. I would like to avoid a looping construct with a specific count, as the processor speed might fluctuate. | I think you could learn a lot about this here: http://www.ganssle.com/debouncing.pdf Your best bet is always to do this in hardware if possible, but there are some thoughts on software in there as well. Simple example code from TFA: #define CHECK_MSEC 5 // Read hardware every 5 msec#define PRESS_MSEC 10 // Stable time before registering pressed#define RELEASE_MSEC 100 // Stable time before registering released// This function reads the key state from the hardware.extern bool_t RawKeyPressed();// This holds the debounced state of the key.bool_t DebouncedKeyPress = false;// Service routine called every CHECK_MSEC to// debounce both edgesvoid DebounceSwitch1(bool_t *Key_changed, bool_t *Key_pressed){ static uint8_t Count = RELEASE_MSEC / CHECK_MSEC; bool_t RawState; *Key_changed = false; *Key_pressed = DebouncedKeyPress; RawState = RawKeyPressed(); if (RawState == DebouncedKeyPress) { // Set the timer which allows a change from current state. if (DebouncedKeyPress) Count = RELEASE_MSEC / CHECK_MSEC; else Count = PRESS_MSEC / CHECK_MSEC; } else { // Key has changed - wait for new state to become stable. if (--Count == 0) { // Timer expired - accept the change. DebouncedKeyPress = RawState; *Key_changed=true; *Key_pressed=DebouncedKeyPress; // And reset the timer. if (DebouncedKeyPress) Count = RELEASE_MSEC / CHECK_MSEC; else Count = PRESS_MSEC / CHECK_MSEC; } } } | {
"score": 5,
"source": [
"https://Stackoverflow.com/questions/155071",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/10703/"
]
} |
155,074 | I'm a newbie when it comes to SQL. When creating a stored procedure with parameters as such: @executed bit,@failure bit,@success bit,@testID int, @time float = 0,@name varchar(200) = '',@description varchar(200) = '',@executionDateTime nvarchar(max) = '',@message nvarchar(max) = '' This is the correct form for default values in T-SQL? I have tried to use NULL instead of ''. When I attempted to execute this procedure through C# I get an error referring to the fact that description is expected but not provided. When calling it like this: cmd.Parameters["@description"].Value = result.Description; result.Description is null. Should this not default to NULL (well '' in my case right now) in SQL? Here's the calling command: cmd.CommandText = "EXEC [dbo].insert_test_result @executed, @failure, @success, @testID, @time, @name, @description, @executionDateTime, @message;"; ... cmd.Parameters.Add("@description", SqlDbType.VarChar); cmd.Parameters.Add("@executionDateTime", SqlDbType.VarChar); cmd.Parameters.Add("@message", SqlDbType.VarChar); cmd.Parameters["@name"].Value = result.Name; cmd.Parameters["@description"].Value = result.Description; ... try { connection.Open(); cmd.ExecuteNonQuery(); } ... finally { connection.Close(); } | A better approach would be to change the CommandText to just the name of the SP, and the CommandType to StoredProcedure - then the parameters will work much more cleanly: cmd.CommandText = "insert_test_result";cmd.CommandType = CommandType.StoredProcedure; This also allows simpler passing by name, rather than position. In general, ADO.NET wants DBNull.Value, not null. I just use a handy method that loops over my args and replaces any nulls with DBNull.Value - as simple as (wrapped): foreach (IDataParameter param in command.Parameters) { if (param.Value == null) param.Value = DBNull.Value; } However! Specifying a value with null is different to letting it assume the default value. If you want it to use the default, don't include the parameter in the command. | {
"score": 5,
"source": [
"https://Stackoverflow.com/questions/155074",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/13688/"
]
} |
155,087 | Before you start firing at me, I'm NOT looking to do this, but someone in another post said it was possible. How is it possible? I've never heard of inheriting from anything using reflection. But I've seen some strange things... | Without virtual functions to override, there's not much point in subclassing a sealed class. If you try write a sealed class with a virtual function in it, you get the following compiler error: // error CS0549: 'Seal.GetName()' is a new virtual member in sealed class 'Seal' However, you can get virtual functions into sealed classes by declaring them in a base class (like this), public abstract class Animal{ private readonly string m_name; public virtual string GetName() { return m_name; } public Animal( string name ) { m_name = name; }}public sealed class Seal : Animal{ public Seal( string name ) : base(name) {}} The problem still remains though, I can't see how you could sneak past the compiler to let you declare a subclass. I tried using IronRuby (ruby is the hackiest of all the hackety languages) but even it wouldn't let me. The 'sealed' part is embedded into the MSIL, so I'd guess that the CLR itself actually enforces this. You'd have to load the code, dissassemble it, remove the 'sealed' bit, then reassemble it, and load the new version. | {
"score": 5,
"source": [
"https://Stackoverflow.com/questions/155087",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5469/"
]
} |
155,097 | I am programmatically exporting data (using PHP 5.2) into a .csv test file. Example data: Numéro 1 (note the accented e).The data is utf-8 (no prepended BOM). When I open this file in MS Excel is displays as Numéro 1 . I am able to open this in a text editor (UltraEdit) which displays it correctly. UE reports the character is decimal 233 . How can I export text data in a .csv file so that MS Excel will correctly render it, preferably without forcing the use of the import wizard, or non-default wizard settings? | A correctly formatted UTF8 file can have a Byte Order Mark as its first three octets. These are the hex values 0xEF, 0xBB, 0xBF. These octets serve to mark the file as UTF8 (since they are not relevant as "byte order" information). 1 If this BOM does not exist, the consumer/reader is left to infer the encoding type of the text. Readers that are not UTF8 capable will read the bytes as some other encoding such as Windows-1252 and display the characters  at the start of the file. There is a known bug where Excel, upon opening UTF8 CSV files via file association, assumes that they are in a single-byte encoding, disregarding the presence of the UTF8 BOM. This can not be fixed by any system default codepage or language setting. The BOM will not clue in Excel - it just won't work. (A minority report claims that the BOM sometimes triggers the "Import Text" wizard.) This bug appears to exist in Excel 2003 and earlier. Most reports (amidst the answers here) say that this is fixed in Excel 2007 and newer. Note that you can always* correctly open UTF8 CSV files in Excel using the "Import Text" wizard, which allows you to specify the encoding of the file you're opening. Of course this is much less convenient. Readers of this answer are most likely in a situation where they don't particularly support Excel < 2007, but are sending raw UTF8 text to Excel, which is misinterpreting it and sprinkling your text with à and other similar Windows-1252 characters. Adding the UTF8 BOM is probably your best and quickest fix. If you are stuck with users on older Excels, and Excel is the only consumer of your CSVs, you can work around this by exporting UTF16 instead of UTF8. Excel 2000 and 2003 will double-click-open these correctly. (Some other text editors can have issues with UTF16, so you may have to weigh your options carefully.) * Except when you can't, (at least) Excel 2011 for Mac's Import Wizard does not actually always work with all encodings, regardless of what you tell it. </anecdotal-evidence> :) | {
"score": 9,
"source": [
"https://Stackoverflow.com/questions/155097",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/23598/"
]
} |
155,101 | When I parse my xml file (variable f) in this method, I get an error C:\Documents and Settings\joe\Desktop\aicpcudev\OnlineModule\map.dtd (The system cannot find the path specified) I know I do not have the dtd, nor do I need it. How can I parse this File object into a Document object while ignoring DTD reference errors? private static Document getDoc(File f, String docId) throws Exception{ DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance(); DocumentBuilder db = dbf.newDocumentBuilder(); Document doc = db.parse(f); return doc;} | A similar approach to the one suggested by @anjanb builder.setEntityResolver(new EntityResolver() { @Override public InputSource resolveEntity(String publicId, String systemId) throws SAXException, IOException { if (systemId.contains("foo.dtd")) { return new InputSource(new StringReader("")); } else { return null; } } }); I found that simply returning an empty InputSource worked just as well? | {
"score": 7,
"source": [
"https://Stackoverflow.com/questions/155101",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5653/"
]
} |
155,105 | I am getting the following error when I put class files in subfolders of my App_Code folder: errorCS0246: The type or namespace name 'MyClassName' could not be found (are you missing a using directive or an assembly reference?) This class is not in a namespace at all. Any ideas? | You need to add codeSubDirectories to your compilation element in web.config <configuration> <system.web> <compilation> <codeSubDirectories> <add directoryName="View"/> </codeSubDirectories> </compilation> </system.web></configuration> | {
"score": 5,
"source": [
"https://Stackoverflow.com/questions/155105",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/18926/"
]
} |
155,109 | What book or website would you recommend to learn about QEMU? I'd like to see some usage examples as well as how to use the APIs. | Best Resources: Main QEMU Usage Documentation Qemu Man Page - Invaluable resource when working with qemu. Quick Start Guide - Slightly ubuntu/debian specific. Covers KVM. Qemu Networking Guide - Great resource, super useful. Have fun qemu's a great tool. | {
"score": 5,
"source": [
"https://Stackoverflow.com/questions/155109",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11157/"
]
} |
155,188 | I have one text input and one button (see below). How can I use JavaScript to trigger the button's click event when the Enter key is pressed inside the text box? There is already a different submit button on my current page, so I can't simply make the button a submit button. And, I only want the Enter key to click this specific button if it is pressed from within this one text box, nothing else. <input type="text" id="txtSearch" /><input type="button" id="btnSearch" value="Search" onclick="doSomething();" /> | In jQuery, the following would work: $("#id_of_textbox").keyup(function(event) { if (event.keyCode === 13) { $("#id_of_button").click(); }}); $("#pw").keyup(function(event) { if (event.keyCode === 13) { $("#myButton").click(); }});$("#myButton").click(function() { alert("Button code executed.");}); <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>Username:<input id="username" type="text"><br>Password: <input id="pw" type="password"><br><button id="myButton">Submit</button> Or in plain JavaScript, the following would work: document.getElementById("id_of_textbox") .addEventListener("keyup", function(event) { event.preventDefault(); if (event.keyCode === 13) { document.getElementById("id_of_button").click(); }}); document.getElementById("pw") .addEventListener("keyup", function(event) { event.preventDefault(); if (event.keyCode === 13) { document.getElementById("myButton").click(); }});function buttonCode(){ alert("Button code executed.");} <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>Username:<input id="username" type="text"><br>Password: <input id="pw" type="password"><br><button id="myButton" onclick="buttonCode()">Submit</button> | {
"score": 12,
"source": [
"https://Stackoverflow.com/questions/155188",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/23947/"
]
} |
155,243 | As a follow up to a recent question , I wonder why it is impossible in Java, without attempting reading/writing on a TCP socket, to detect that the socket has been gracefully closed by the peer? This seems to be the case regardless of whether one uses the pre-NIO Socket or the NIO SocketChannel . When a peer gracefully closes a TCP connection, the TCP stacks on both sides of the connection know about the fact. The server-side (the one that initiates the shutdown) ends up in state FIN_WAIT2 , whereas the client-side (the one that does not explicitly respond to the shutdown) ends up in state CLOSE_WAIT . Why isn't there a method in Socket or SocketChannel that can query the TCP stack to see whether the underlying TCP connection has been terminated? Is it that the TCP stack doesn't provide such status information? Or is it a design decision to avoid a costly call into the kernel? With the help of the users who have already posted some answers to this question, I think I see where the issue might be coming from. The side that doesn't explicitly close the connection ends up in TCP state CLOSE_WAIT meaning that the connection is in the process of shutting down and waits for the side to issue its own CLOSE operation. I suppose it's fair enough that isConnected returns true and isClosed returns false , but why isn't there something like isClosing ? Below are the test classes that use pre-NIO sockets. But identical results are obtained using NIO. import java.net.ServerSocket;import java.net.Socket;public class MyServer { public static void main(String[] args) throws Exception { final ServerSocket ss = new ServerSocket(12345); final Socket cs = ss.accept(); System.out.println("Accepted connection"); Thread.sleep(5000); cs.close(); System.out.println("Closed connection"); ss.close(); Thread.sleep(100000); }}import java.net.Socket;public class MyClient { public static void main(String[] args) throws Exception { final Socket s = new Socket("localhost", 12345); for (int i = 0; i < 10; i++) { System.out.println("connected: " + s.isConnected() + ", closed: " + s.isClosed()); Thread.sleep(1000); } Thread.sleep(100000); }} When the test client connects to the test server the output remains unchanged even after the server initiates the shutdown of the connection: connected: true, closed: falseconnected: true, closed: false... | I have been using Sockets often, mostly with Selectors, and though not a Network OSI expert, from my understanding, calling shutdownOutput() on a Socket actually sends something on the network (FIN) that wakes up my Selector on the other side (same behaviour in C language). Here you have detection : actually detecting a read operation that will fail when you try it. In the code you give, closing the socket will shutdown both input and output streams, without possibilities of reading the data that might be available, therefore loosing them. The Java Socket.close() method performs a "graceful" disconnection (opposite as what I initially thought) in that the data left in the output stream will be sent followed by a FIN to signal its close. The FIN will be ACK'd by the other side, as any regular packet would 1 . If you need to wait for the other side to close its socket, you need to wait for its FIN. And to achieve that, you have to detect Socket.getInputStream().read() < 0 , which means you should not close your socket, as it would close its InputStream . From what I did in C, and now in Java, achieving such a synchronized close should be done like this: Shutdown socket output (sends FIN on the other end, this is the last thing that will ever be sent by this socket). Input is still open so you can read() and detect the remote close() Read the socket InputStream until we receive the reply-FIN from the other end (as it will detect the FIN, it will go through the same graceful diconnection process). This is important on some OS as they don't actually close the socket as long as one of its buffer still contains data. They're called "ghost" socket and use up descriptor numbers in the OS (that might not be an issue anymore with modern OS) Close the socket (by either calling Socket.close() or closing its InputStream or OutputStream ) As shown in the following Java snippet: public void synchronizedClose(Socket sok) { InputStream is = sok.getInputStream(); sok.shutdownOutput(); // Sends the 'FIN' on the network while (is.read() > 0) ; // "read()" returns '-1' when the 'FIN' is reached sok.close(); // or is.close(); Now we can close the Socket} Of course both sides have to use the same way of closing, or the sending part might always be sending enough data to keep the while loop busy (e.g. if the sending part is only sending data and never reading to detect connection termination. Which is clumsy, but you might not have control on that). As @WarrenDew pointed out in his comment, discarding the data in the program (application layer) induces a non-graceful disconnection at application layer: though all data were received at TCP layer (the while loop), they are discarded. 1 : From " Fundamental Networking in Java ": see fig. 3.3 p.45, and the whole §3.7, pp 43-48 | {
"score": 5,
"source": [
"https://Stackoverflow.com/questions/155243",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/16724/"
]
} |
155,246 | I have a test environment for a database that I want to reload with new data at the start of a testing cycle. I am not interested in rebuilding the entire database- just simply "re-setting" the data. What is the best way to remove all the data from all the tables using TSQL? Are there system stored procedures, views, etc. that can be used? I do not want to manually create and maintain truncate table statements for each table- I would prefer it to be dynamic. | For SQL 2005, EXEC sp_MSForEachTable 'TRUNCATE TABLE ?' Couple more links for 2000 and 2005/2008 .. | {
"score": 9,
"source": [
"https://Stackoverflow.com/questions/155246",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4872/"
]
} |
155,250 | Apparently we use the Scrum development methodology. Here's generally how it goes: Developers thrash around trying to accomplish their tasks. Generally the tasks take most of the sprint to complete. QA pesters Dev to release something they can test, Dev finally throws some buggy code out to QA a day or two before the sprint ends and spends the rest of the time fixing bugs that QA is finding. QA can never complete the tasks on time, sprints are rarely releasable on time, and Dev and QA have a miserable few days at the end of the sprint. How is scrum supposed to work when releasable Dev tasks take up most of the sprint? Thank you everyone for your part in the discussion. As it's a pretty open-ended question, it doesn't seem like there is one "answer" - there are many good suggestions below. I'll attempt to summarize some of my "take home" points and make some clarifications. (BTW - Is this the best place to put this or should I have put it in an 'answer'?) Points to ponder / act on: Need to ensure that developer tasks are as small (granular) as possible. Sprint length should be appropriately based on average task length (e.g. sprint with 1 week tasks should be at least 4 weeks long) Team (including QA) needs to work on becoming more accurate at estimating. Consider doing a separate QA sprint in parallel but off-set if that works best for the team Unit testing! | My opinion is that you have an estimation problem. It seems that the time to test each feature is missing, and only the building part is being considered when planning the sprint. I'm not saying it is an easy problem to solve, because it is more common than anything. But things that could help are: Consider QA as members of the dev team, and include them in the sprint planning and estimating more closely. 'Releasable Dev tasks' should not take up most of the sprint. Complete working features should. Try to gather metrics about dev time vs QA time for each kind of task and use those metrics when estimating future sprints. You might need to review your backlog to see if you have very coarse grained features. Try to divide them in smaller tasks that could be easily estimated and tested. In summary, it seems that your team hasn't found what its real velocity is because there are tasks that are not being considered when doing the estimation and planning for the sprint. But in the end, estimation inaccuracy is a tough project management issue that you find in agile-based or waterfall-based projects. Good luck. | {
"score": 6,
"source": [
"https://Stackoverflow.com/questions/155250",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/620435/"
]
} |
155,260 | I have been learning about the basics of C# but haven't come across a good explanation of what this is: var l = new List<string>(); I don't know what the <string> is doing or if it's the List that is doing the magic. I have also seen objects been thrown within the < > tags. Can someone explain this to me with examples, please? | That is the generic syntax for C#. The basic concept is that it allows you to use a Type placeholder and substitute the actual real type in at compile time. For example, the old way: ArrayList foos = new Arraylist();foos.Add("Test"); worked by making ArrayList store a list of System.Objects (The base type for all things .NET). So, when adding or retrieving an object from the list, The CLR would have to cast it to object, basically what really happens is this: foos.Add("Test" as System.Object);string s = foos[1] as String. This causes a performance penalty from the casting, and its also unsafe because I can do this: ArrayList listOfStrings = new ArrayList();listOfStrings.Add(1);listOfStrings.Add("Test"); This will compile just fine, even though I put an integer in listOfStrings. Generics changed all of this, now using Generics I can declare what Type my collection expects: List<int> listOfIntegers = new List<int>();List<String> listOfStrings = new List<String>();listOfIntegers.add(1);// Compile time error.listOfIntegers.add("test"); This provides compile-time type safety, as well as avoids expensive casting operations. The way you leverage this is pretty simple, though there are some advanced edge cases. The basic concept is to make your class type agnostic by using a type placeholder, for example, if I wanted to create a generic "Add Two Things" class. public class Adder<T>{ public T AddTwoThings(T t1, T t2) { return t1 + t2; }}Adder<String> stringAdder = new Adder<String>();Console.Writeline(stringAdder.AddTwoThings("Test,"123"));Adder<int> intAdder = new Adder<int>();Console.Writeline(intAdder.AddTwoThings(2,2)); For a much more detailed explanation of generics, I can't recommend enough the book CLR via C#. | {
"score": 6,
"source": [
"https://Stackoverflow.com/questions/155260",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/22459/"
]
} |
155,271 | Is there a way to hide the text limit line in netbeans 6.5? | In NetBeans 6.9, setting Right Margin to 0 effectively hides the text limit line. Set the value in Preferences > Editor > Formatting > All Languages > Right Margin. (Mac OS X 10.6.4, NetBeans 6.9) | {
"score": 5,
"source": [
"https://Stackoverflow.com/questions/155271",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3740/"
]
} |
155,291 | I thought they could be, but as I'm not putting my money where my mouth was (so to speak) setting the readonly attribute doesn't actually seem to do anything. I'd rather not use Disabled, since I want the checked check boxes to be submitted with the rest of the form, I just don't want the client to be able to change them under certain circumstances. | READONLY doesn't work on checkboxes as it prevents you from editing a field's value , but with a checkbox you're actually editing the field's state (on || off) From faqs.org : It's important to understand that READONLY merely prevents the user from changing the value of the field, not from interacting with the field. In checkboxes, for example, you can check them on or off (thus setting the CHECKED state) but you don't change the value of the field. If you don't want to use disabled but still want to submit the value, how about submitting the value as a hidden field and just printing its contents to the user when they don't meet the edit criteria? e.g. // user allowed changeif($user_allowed_edit){ echo '<input type="checkbox" name="my_check"> Check value';}else{ // Not allowed change - submit value.. echo '<input type="hidden" name="my_check" value="1" />'; // .. and show user the value being submitted echo '<input type="checkbox" disabled readonly> Check value';} | {
"score": 9,
"source": [
"https://Stackoverflow.com/questions/155291",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/19074/"
]
} |
155,303 | How do I go from this string: "ThisIsMyCapsDelimitedString" ...to this string: "This Is My Caps Delimited String" Fewest lines of code in VB.net is preferred but C# is also welcome. Cheers! | I made this a while ago. It matches each component of a CamelCase name. /([A-Z]+(?=$|[A-Z][a-z])|[A-Z]?[a-z]+)/g For example: "SimpleHTTPServer" => ["Simple", "HTTP", "Server"]"camelCase" => ["camel", "Case"] To convert that to just insert spaces between the words: Regex.Replace(s, "([a-z](?=[A-Z])|[A-Z](?=[A-Z][a-z]))", "$1 ") If you need to handle digits: /([A-Z]+(?=$|[A-Z][a-z]|[0-9])|[A-Z]?[a-z]+|[0-9]+)/gRegex.Replace(s,"([a-z](?=[A-Z]|[0-9])|[A-Z](?=[A-Z][a-z]|[0-9])|[0-9](?=[^0-9]))","$1 ") | {
"score": 9,
"source": [
"https://Stackoverflow.com/questions/155303",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/17235/"
]
} |
155,306 | I have a textarea with many lines of input, and a JavaScript event fires that necessitates I scroll the textarea to line 345. scrollTop sort of does what I want, except as far as I can tell it's pixel level, and I want something that operates on a line level. What also complicates things is that, afaik once again, it's not possible to make textareas not line-wrap. | You can stop wrapping with the wrap attribute. It is not part of HTML 4, but most browsers support it. You can compute the height of a line by dividing the height of the area by its number of rows. <script type="text/javascript" language="JavaScript">function Jump(line){ var ta = document.getElementById("TextArea"); var lineHeight = ta.clientHeight / ta.rows; var jump = (line - 1) * lineHeight; ta.scrollTop = jump;}</script><textarea name="TextArea" id="TextArea" rows="40" cols="80" title="Paste text here" wrap="off"></textarea><input type="button" onclick="Jump(98)" title="Go!" value="Jump"/> Tested OK in FF3 and IE6. | {
"score": 5,
"source": [
"https://Stackoverflow.com/questions/155306",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/23845/"
]
} |
155,321 | I'm trying to build a mapping table to associate the IDs of new rows in a table with those that they're copied from. The OUTPUT INTO clause seems perfect for that, but it doesn't seem to behave according to the documentation. My code: DECLARE @Missing TABLE (SrcContentID INT PRIMARY KEY )INSERT INTO @Missing ( SrcContentID ) SELECT cshadow.ContentID FROM Private.Content AS cshadow LEFT JOIN Private.Content AS cglobal ON cshadow.Tag = cglobal.Tag WHERE cglobal.ContentID IS NULL PRINT 'Adding new content headers'DECLARE @Inserted TABLE (SrcContentID INT PRIMARY KEY, TgtContentID INT )INSERT INTO Private.Content ( Tag, Description, ContentDate, DateActivate, DateDeactivate, SortOrder, CreatedOn, IsDeleted, ContentClassCode, ContentGroupID, OrgUnitID ) OUTPUT cglobal.ContentID, INSERTED.ContentID INTO @Inserted (SrcContentID, TgtContentID)SELECT Tag, Description, ContentDate, DateActivate, DateDeactivate, SortOrder, CreatedOn, IsDeleted, ContentClassCode, ContentGroupID, NULL FROM Private.Content AS cglobal INNER JOIN @Missing AS m ON cglobal.ContentID = m.SrcContentID Results in the error message: Msg 207, Level 16, State 1, Line 34Invalid column name 'SrcContentID'. (line 34 being the one with the OUTPUT INTO) Experimentation suggests that only rows that are actually present in the target of the INSERT can be selected in the OUTPUT INTO. But this contradicts the docs in the books online. The article on OUTPUT Clause has example E that describes a similar usage: The OUTPUT INTO clause returns values from the table being updated (WorkOrder) and also from the Product table. The Product table is used in the FROM clause to specify the rows to update. Has anyone worked with this feature? (In the meantime I've rewritten my code to do the job using a cursor loop, but that's ugly and I'm still curious) | I've verified that the problem is that you can only use INSERTED columns. The documentation seems to indicate that you can use from_table_name , but I can't seem to get it to work (The multi-part identifier "m.ContentID" could not be bound.): TRUNCATE TABLE mainSELECT *FROM incomingSELECT *FROM mainDECLARE @Missing TABLE (ContentID INT PRIMARY KEY)INSERT INTO @Missing(ContentID) SELECT incoming.ContentIDFROM incomingLEFT JOIN main ON main.ContentID = incoming.ContentIDWHERE main.ContentID IS NULLSELECT *FROM @MissingDECLARE @Inserted TABLE (ContentID INT PRIMARY KEY, [Content] varchar(50))INSERT INTO main(ContentID, [Content]) OUTPUT INSERTED.ContentID /* incoming doesn't work, m doesn't work */, INSERTED.[Content] INTO @Inserted (ContentID, [Content])SELECT incoming.ContentID, incoming.[Content] FROM incomingINNER JOIN @Missing AS m ON m.ContentID = incoming.ContentIDSELECT *FROM @InsertedSELECT *FROM incomingSELECT *FROM main Apparently the from_table_name prefix is only allowed on DELETE or UPDATE (or MERGE in 2008) - I'm not sure why: from_table_name Is a column prefix that specifies a table included in the FROM clause of a DELETE or UPDATE statement that is used to specify the rows to update or delete. If the table being modified is also specified in the FROM clause, any reference to columns in that table must be qualified with the INSERTED or DELETED prefix. | {
"score": 5,
"source": [
"https://Stackoverflow.com/questions/155321",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/10082/"
]
} |
155,371 | I want to use XMLHttpRequest in JavaScript to POST a form that includes a file type input element so that I can avoid page refresh and get useful XML back. I can submit the form without page refresh, using JavaScript to set the target attribute on the form to an iframe for MSIE or an object for Mozilla, but this has two problems. The minor problem is that target is not W3C compliant (which is why I set it in JavaScript, not in XHTML). The major problem is that the onload event doesn't fire, at least not on Mozilla on OS X Leopard. Besides, XMLHttpRequest would make for prettier response code because the returned data could be XML, not confined to XHTML as is the case with iframe. Submitting the form results in HTTP that looks like: Content-Type: multipart/form-data;boundary=<boundary string>Content-Length: <length>--<boundary string>Content-Disposition: form-data, name="<input element name>"<input element value>--<boundary string>Content-Disposition: form-data, name=<input element name>"; filename="<input element value>"Content-Type: application/octet-stream<element body> How do I get the XMLHttpRequest object's send method to duplicate the above HTTP stream? | You can construct the 'multipart/form-data' request yourself (read more about it at http://www.faqs.org/rfcs/rfc2388.html ) and then use the send method (ie. xhr.send(your-multipart-form-data)). Similarly, but easier, in Firefox 4+ (also in Chrome 5+ and Safari 5+) you can use the FormData interface that helps to construct such requests. The send method is good for text content but if you want to send binary data such as images, you can do it with the help of the sendAsBinary method that has been around starting with Firefox 3.0. For details on how to send files via XMLHttpRequest , please refer to http://blog.igstan.ro/2009/01/pure-javascript-file-upload.html . | {
"score": 6,
"source": [
"https://Stackoverflow.com/questions/155371",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/14405/"
]
} |
155,378 | I have a double value f and would like a way to nudge it very slightly larger (or smaller) to get a new value that will be as close as possible to the original but still strictly greater than (or less than) the original. It doesn't have to be close down to the last bit—it's more important that whatever change I make is guaranteed to produce a different value and not round back to the original. | Check your math.h file. If you're lucky you have the nextafter and nextafterf functions defined. They do exactly what you want in a portable and platform independent way and are part of the C99 standard. Another way to do it (could be a fallback solution) is to decompose your float into the mantissa and exponent part. Incrementing is easy: Just add one to the mantissa. If you get an overflow you have to handle this by incrementing your exponent. Decrementing works the same way. EDIT : As pointed out in the comments it is sufficient to just increment the float in it's binary representation. The mantissa-overflow will increment the exponent, and that's exactly what we want. That's in a nutshell the same thing that nextafter does. This won't be completely portable though. You would have to deal with endianess and the fact that not all machines do have IEEE floats (ok - the last reason is more academic). Also handling NAN's and infinites can be a bit tricky. You cannot simply increment them as they are by definition not numbers. | {
"score": 7,
"source": [
"https://Stackoverflow.com/questions/155378",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4790/"
]
} |
155,391 | What is the difference between a BitmapFrame and BitmapImage in WPF? Where would you use each (ie. why would you use a BitmapFrame rather than a BitmapImage?) | You should stick to using the abstract class BitmapSource if you need to get at the bits, or even ImageSource if you just want to draw it. The implementation BitmapFrame is just the object oriented nature of the implementation showing through. You shouldn't really have any need to distinguish between the implementations. BitmapFrames may contain a little extra information (metadata), but usually nothing but an imaging app would care about. You'll notice these other classes that inherit from BitmapSource: BitmapFrame BitmapImage CachedBitmap ColorConvertedBitmap CroppedBitmap FormatConvertedBitmap RenderTargetBitmap TransformedBitmap WriteableBitmap You can get a BitmapSource from a URI by constructing a BitmapImage object: Uri uri = ...;BitmapSource bmp = new BitmapImage(uri);Console.WriteLine("{0}x{1}", bmp.PixelWIdth, bmp.PixelHeight); The BitmapSource could also come from a decoder. In this case you are indirectly using BitmapFrames. Uri uri = ...;BitmapDecoder dec = BitmapDecoder.Create(uri, BitmapCreateOptions.None, BitmapCacheOption.Default);BitmapSource bmp = dec.Frames[0];Console.WriteLine("{0}x{1}", bmp.PixelWIdth, bmp.PixelHeight); | {
"score": 5,
"source": [
"https://Stackoverflow.com/questions/155391",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3798/"
]
} |
155,393 | Is there any one website which contains many good C# screencasts? | I like the channel 9 screencasts tagged C#.. | {
"score": 5,
"source": [
"https://Stackoverflow.com/questions/155393",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/13227/"
]
} |
155,436 | What are the best practices for naming unit test classes and test methods? This was discussed on SO before, at What are some popular naming conventions for Unit Tests? I don't know if this is a very good approach, but currently in my testing projects, I have one-to-one mappings between each production class and a test class, e.g. Product and ProductTest . In my test classes I then have methods with the names of the methods I am testing, an underscore, and then the situation and what I expect to happen, e.g. Save_ShouldThrowExceptionWithNullName() . | Update (Jul 2021) It's been quite a while since my original answer (almost 12 years) and best practices have been changing a lot during this time. So I feel inclined to update my own answer and offer different naming strategies to the readers. Many comments and answers point out that the naming strategy I propose in my original answer is not resistant to refactorings and ends up with difficult to understand names, and I fully agree. In the last years, I ended up using a more human readable naming schema where the test name describes what we want to test, in the line described by Vladimir Khorikov . Some examples would be: Add_credit_updates_customer_balance Purchase_without_funds_is_not_possible Add_affiliate_discount But as you can see it's quite a flexible schema but the most important thing is that reading the name you know what the test is about without including technical details that may change over time. To name the projects and test classes I still adhere to the original answer schema. Original answer (Oct 2009) I like Roy Osherove's naming strategy . It's the following: [UnitOfWork_StateUnderTest_ExpectedBehavior] It has every information needed on the method name and in a structured manner. The unit of work can be as small as a single method, a class, or as large as multiple classes. It should represent all the things that are to be tested in this test case and are under control. For assemblies, I use the typical .Tests ending, which I think is quite widespread and the same for classes (ending with Tests ): [NameOfTheClassUnderTestTests] Previously, I used Fixture as suffix instead of Tests, but I think the latter is more common, then I changed the naming strategy. | {
"score": 10,
"source": [
"https://Stackoverflow.com/questions/155436",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11829/"
]
} |
155,449 | Right now I have the following in my .vimrc : au BufWritePost *.c,*.cpp,*.h !ctags -R There are a few problems with this: It's slow -- regenerates tags for files that haven't changed since the last tag generation. I have to push the enter button again after writing the file because of an inevitable "press Enter or type command to continue". When you combine these two issues I end up pushing the additional enter too soon (before ctags -R has finished), then see the annoying error message, and have to push enter again. I know it doesn't sound like a big deal, but with the amount of file writes I do on a given day it tends to get really annoying. There's gotta be a better way to do it! | au BufWritePost *.c,*.cpp,*.h silent! !ctags -R & The downside is that you won't have a useful tags file until it completes. As long as you're on a *nix system it should be ok to do multiple writes before the previous ctags has completed, but you should test that. On a Windows system it won't put it in the background and it'll complain that the file is locked until the first ctags finishes (which shouldn't cause problems in vim, but you'll end up with a slightly outdated tags file). Note, you could use the --append option as tonylo suggests, but then you'll have to disable tagbsearch which could mean that tag searches take a lot longer, depending on the size of your tag file. | {
"score": 7,
"source": [
"https://Stackoverflow.com/questions/155449",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3594/"
]
} |
155,458 | I need to do a comparaison between an object and NULL. When the object is not NULL I fill it with some data. Here is the code : if (region != null) { .... } This is working but when looping and looping sometime the region object is NOT null (I can see data inside it in debug mode). In step-by-step when debugging, it doesn't go inside the IF statement... When I do a Quick Watch with these following expression : I see the (region == null) return false, AND (region != null) return false too... why and how? Update Someone point out that the object was == and != overloaded: public static bool operator ==(Region r1, Region r2) { if (object.ReferenceEquals(r1, null)) { return false; } if (object.ReferenceEquals(r2, null)) { return false; } return (r1.Cmr.CompareTo(r2.Cmr) == 0 && r1.Id == r2.Id); } public static bool operator !=(Region r1, Region r2) { if (object.ReferenceEquals(r1, null)) { return false; } if (object.ReferenceEquals(r2, null)) { return false; } return (r1.Cmr.CompareTo(r2.Cmr) != 0 || r1.Id != r2.Id); } | Is the == and/or != operator overloaded for the region object's class? Now that you've posted the code for the overloads: The overloads should probably look like the following (code taken from postings made by Jon Skeet and Philip Rieck ): public static bool operator ==(Region r1, Region r2){ if (object.ReferenceEquals( r1, r2)) { // handles if both are null as well as object identity return true; } if ((object)r1 == null || (object)r2 == null) { return false; } return (r1.Cmr.CompareTo(r2.Cmr) == 0 && r1.Id == r2.Id);}public static bool operator !=(Region r1, Region r2){ return !(r1 == r2);} | {
"score": 6,
"source": [
"https://Stackoverflow.com/questions/155458",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/13913/"
]
} |
155,462 | In Ruby: for i in A do # some codeend is the same as: A.each do |i| # some codeend for is not a kernel method: What exactly is " for " in ruby Is there a way to use other keywords to do similar things? Something like: total = sum i in I {x[i]} mapping to: total = I.sum {|i] x[i]} | It's almost syntax sugar. One difference is that, while for would use the scope of the code around it, each creates a separate scope within its block. Compare the following: for i in (1..3) x = iendp x # => 3 versus (1..3).each do |i| x = iendp x # => undefined local variable or method `x' for main:Object | {
"score": 7,
"source": [
"https://Stackoverflow.com/questions/155462",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/14167/"
]
} |
155,504 | I had a look in the reference doc, and Spring seems to have pretty good support for sending mail. However, I need to login to a mail account, read the messages, and download any attachments. Is downloading mail attachments supported by the Spring mail API? I know you can do this with the Java Mail API, but in the past I've found that very verbose and unpleasant to work with. EDIT : I've received several replies pointing towards tutorials that describe how to send mail with attachments, but what I'm asking about is how to read attachments from received mail. Cheers,Don | Here's the class that I use for downloading e-mails (with attachment handling). You'll have to glance by some of the stuff it's doing (like ignore the logging classes and database writes). I've also re-named some of the packages for ease of reading. The general idea is that all attachments are saved as individual files in the filesystem, and each e-mail is saved as a record in the database with a set of child records that point to all of the attachment file paths. Focus on the doEMailDownload method. /** * Copyright (c) 2008 Steven M. Cherry * All rights reserved. */package utils.scheduled;import java.io.BufferedOutputStream;import java.io.File;import java.io.FileOutputStream;import java.io.InputStream;import java.sql.Timestamp;import java.util.Properties;import java.util.Vector;import javax.mail.Address;import javax.mail.Flags;import javax.mail.Folder;import javax.mail.Message;import javax.mail.Multipart;import javax.mail.Part;import javax.mail.Session;import javax.mail.Store;import javax.mail.internet.MimeBodyPart;import glob.ActionLogicImplementation;import glob.IOConn;import glob.log.Log;import logic.utils.sql.Settings;import logic.utils.sqldo.EMail;import logic.utils.sqldo.EMailAttach;/** * This will connect to our incoming e-mail server and download any e-mails * that are found on the server. The e-mails will be stored for further processing * in our internal database. Attachments will be written out to separate files * and then referred to by the database entries. This is intended to be run by * the scheduler every minute or so. * * @author Steven M. Cherry */public class DownloadEMail implements ActionLogicImplementation { protected String receiving_host; protected String receiving_user; protected String receiving_pass; protected String receiving_protocol; protected boolean receiving_secure; protected String receiving_attachments; /** This will run our logic */ public void ExecuteRequest(IOConn ioc) throws Exception { Log.Trace("Enter"); Log.Debug("Executing DownloadEMail"); ioc.initializeResponseDocument("DownloadEMail"); // pick up our configuration from the server: receiving_host = Settings.getValue(ioc, "server.email.receiving.host"); receiving_user = Settings.getValue(ioc, "server.email.receiving.username"); receiving_pass = Settings.getValue(ioc, "server.email.receiving.password"); receiving_protocol = Settings.getValue(ioc, "server.email.receiving.protocol"); String tmp_secure = Settings.getValue(ioc, "server.email.receiving.secure"); receiving_attachments = Settings.getValue(ioc, "server.email.receiving.attachments"); // sanity check on the parameters: if(receiving_host == null || receiving_host.length() == 0){ ioc.SendReturn(); ioc.Close(); Log.Trace("Exit"); return; // no host defined. } if(receiving_user == null || receiving_user.length() == 0){ ioc.SendReturn(); ioc.Close(); Log.Trace("Exit"); return; // no user defined. } if(receiving_pass == null || receiving_pass.length() == 0){ ioc.SendReturn(); ioc.Close(); Log.Trace("Exit"); return; // no pass defined. } if(receiving_protocol == null || receiving_protocol.length() == 0){ Log.Debug("EMail receiving protocol not defined, defaulting to POP"); receiving_protocol = "POP"; } if(tmp_secure == null || tmp_secure.length() == 0 || tmp_secure.compareToIgnoreCase("false") == 0 || tmp_secure.compareToIgnoreCase("no") == 0 ){ receiving_secure = false; } else { receiving_secure = true; } if(receiving_attachments == null || receiving_attachments.length() == 0){ Log.Debug("EMail receiving attachments not defined, defaulting to ./email/attachments/"); receiving_attachments = "./email/attachments/"; } // now do the real work. doEMailDownload(ioc); ioc.SendReturn(); ioc.Close(); Log.Trace("Exit"); } protected void doEMailDownload(IOConn ioc) throws Exception { // Create empty properties Properties props = new Properties(); // Get the session Session session = Session.getInstance(props, null); // Get the store Store store = session.getStore(receiving_protocol); store.connect(receiving_host, receiving_user, receiving_pass); // Get folder Folder folder = store.getFolder("INBOX"); folder.open(Folder.READ_WRITE); try { // Get directory listing Message messages[] = folder.getMessages(); for (int i=0; i < messages.length; i++) { // get the details of the message: EMail email = new EMail(); email.fromaddr = messages[i].getFrom()[0].toString(); Address[] to = messages[i].getRecipients(Message.RecipientType.TO); email.toaddr = ""; for(int j = 0; j < to.length; j++){ email.toaddr += to[j].toString() + "; "; } Address[] cc; try { cc = messages[i].getRecipients(Message.RecipientType.CC); } catch (Exception e){ Log.Warn("Exception retrieving CC addrs: %s", e.getLocalizedMessage()); cc = null; } email.cc = ""; if(cc != null){ for(int j = 0; j < cc.length; j++){ email.cc += cc[j].toString() + "; "; } } email.subject = messages[i].getSubject(); if(messages[i].getReceivedDate() != null){ email.received_when = new Timestamp(messages[i].getReceivedDate().getTime()); } else { email.received_when = new Timestamp( (new java.util.Date()).getTime()); } email.body = ""; Vector<EMailAttach> vema = new Vector<EMailAttach>(); Object content = messages[i].getContent(); if(content instanceof java.lang.String){ email.body = (String)content; } else if(content instanceof Multipart){ Multipart mp = (Multipart)content; for (int j=0; j < mp.getCount(); j++) { Part part = mp.getBodyPart(j); String disposition = part.getDisposition(); if (disposition == null) { // Check if plain MimeBodyPart mbp = (MimeBodyPart)part; if (mbp.isMimeType("text/plain")) { Log.Debug("Mime type is plain"); email.body += (String)mbp.getContent(); } else { Log.Debug("Mime type is not plain"); // Special non-attachment cases here of // image/gif, text/html, ... EMailAttach ema = new EMailAttach(); ema.name = decodeName(part.getFileName()); File savedir = new File(receiving_attachments); savedir.mkdirs(); File savefile = File.createTempFile("emailattach", ".atch", savedir ); ema.path = savefile.getAbsolutePath(); ema.size = part.getSize(); vema.add(ema); ema.size = saveFile(savefile, part); } } else if ((disposition != null) && (disposition.equals(Part.ATTACHMENT) || disposition.equals(Part.INLINE) ) ){ // Check if plain MimeBodyPart mbp = (MimeBodyPart)part; if (mbp.isMimeType("text/plain")) { Log.Debug("Mime type is plain"); email.body += (String)mbp.getContent(); } else { Log.Debug("Save file (%s)", part.getFileName() ); EMailAttach ema = new EMailAttach(); ema.name = decodeName(part.getFileName()); File savedir = new File(receiving_attachments); savedir.mkdirs(); File savefile = File.createTempFile("emailattach", ".atch", savedir ); ema.path = savefile.getAbsolutePath(); ema.size = part.getSize(); vema.add(ema); ema.size = saveFile( savefile, part); } } } } // Insert everything into the database: logic.utils.sql.EMail.insertEMail(ioc, email); for(int j = 0; j < vema.size(); j++){ vema.get(j).emailid = email.id; logic.utils.sql.EMail.insertEMailAttach(ioc, vema.get(j) ); } // commit this message and all of it's attachments ioc.getDBConnection().commit(); // Finally delete the message from the server. messages[i].setFlag(Flags.Flag.DELETED, true); } // Close connection folder.close(true); // true tells the mail server to expunge deleted messages. store.close(); } catch (Exception e){ folder.close(true); // true tells the mail server to expunge deleted messages. store.close(); throw e; } } protected int saveFile(File saveFile, Part part) throws Exception { BufferedOutputStream bos = new BufferedOutputStream( new FileOutputStream(saveFile) ); byte[] buff = new byte[2048]; InputStream is = part.getInputStream(); int ret = 0, count = 0; while( (ret = is.read(buff)) > 0 ){ bos.write(buff, 0, ret); count += ret; } bos.close(); is.close(); return count; } protected String decodeName( String name ) throws Exception { if(name == null || name.length() == 0){ return "unknown"; } String ret = java.net.URLDecoder.decode( name, "UTF-8" ); // also check for a few other things in the string: ret = ret.replaceAll("=\\?utf-8\\?q\\?", ""); ret = ret.replaceAll("\\?=", ""); ret = ret.replaceAll("=20", " "); return ret; }} | {
"score": 5,
"source": [
"https://Stackoverflow.com/questions/155504",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2648/"
]
} |
155,507 | How exactly can I create a new directory using Emacs? What commands do I use? (If possible, please provide an example) | to create the directory dir/to/create , type: M-x make-directory RET dir/to/create RET to create directories dir/parent1/node and dir/parent2/node , type: M-! mkdir -p dir/parent{1,2}/node RET It assumes that Emacs's inferior shell is bash / zsh or other compatible shell. or in a Dired mode + It doesn't create nonexistent parent directories. Example: C-x d *.py RET ; shows python source files in the CWD in `Dired` mode+ test RET ; create `test` directory in the CWD CWD stands for Current Working Directory. or just create a new file with non-existing parent directories using C-x C-f and type: M-x make-directory RET RET Emacs asks to create the parent directories automatically while saving a new file in recent Emacs versions. For older version, see How to make Emacs create intermediate dirs - when saving a file? | {
"score": 9,
"source": [
"https://Stackoverflow.com/questions/155507",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4872/"
]
} |
155,517 | Is it possible to cancel out of a long running process in VB6.0 without using DoEvents? For example: for i = 1 to someVeryHighNumber ' Do some work here ' ... if cancel then exit for end ifnextSub btnCancel_Click() cancel = trueEnd Sub I assume I need a "DoEvents" before the "if cancel then..." is there a better way? It's been awhile... | Nope, you got it right, you definitely want DoEvents in your loop. If you put the DoEvents in your main loop and find that slows down processing too much, try calling the Windows API function GetQueueStatus (which is much faster than DoEvents) to quickly determine if it's even necessary to call DoEvents. GetQueueStatus tells you if there are any events to process. ' at the top:Declare Function GetQueueStatus Lib "user32" (ByVal qsFlags As Long) As Long' then call this instead of DoEvents:Sub DoEventsIfNecessary() If GetQueueStatus(255) <> 0 Then DoEventsEnd Sub | {
"score": 6,
"source": [
"https://Stackoverflow.com/questions/155517",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5019/"
]
} |
155,532 | Are there any good methods for getting ASP.NET 2.0 to validate under the XHTML 1.0 Strict (or Transitional) DTD? I'm interested to hear some ideas before I hack up the core of the HTTP response. One major problem is the form tag itself, this is the output I got from W3C when I tried to validate: Line 13, Column 11: there is no attribute "name".<form name="aspnetForm" method="post" action="Default.aspx" onsubmit="javascript That tag is very fundamental to ASP.NET, as you all know. Hmmmm. | ASP.NET 2.0 and above can indeed output Strict (or Transitional) XHTML. This will resolve your 'there is no attribute "name"' validation error, amongst other things. To set this up, update your Web.config file with something like: <system.web> ... other configuration goes here ... <xhtmlConformance mode="Strict" /></system.web> For Transitional XHTML, use mode="Transitional" instead. See How to: Configure XHTML Rendering in ASP.NET Web Sites on MSDN. | {
"score": 5,
"source": [
"https://Stackoverflow.com/questions/155532",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/12252/"
]
} |
155,560 | I want a function like GetCurrentThread which returns a TThread object of the current executing thread. I know there is a Win32 API call GetCurrentThread, but it returns the thread Id. If there is a possibility to get TThread object from that ID that's also fine. | The latest version of Delphi, Delphi 2009, has a CurrentThread class property on the TThread class. This will return the proper Delphi thread object if it's a native thread. If the thread is an "alien" thread, i.e. created using some other mechanism or on a callback from a third party thread, then it will create a wrapper thread around the thread handle. | {
"score": 6,
"source": [
"https://Stackoverflow.com/questions/155560",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
]
} |
155,584 | I need a way to allow each letter of a word to rotate through 3 different colors. I know of some not so clean ways I can do this with asp.NET, but I'm wondering if there might be a cleaner CSS/JavaScript solution that is more search engine friendly. The designer is including a file like this for each page. I'd rather not have to manually generate an image for every page as that makes it hard for the non-technical site editors to add pages and change page names. | Here is some JavaScript. var message = "The quick brown fox.";var colors = new Array("#ff0000","#00ff00","#0000ff"); // red, green, bluefor (var i = 0; i < message.length; i++){ document.write("<span style=\"color:" + colors[(i % colors.length)] + ";\">" + message[i] + "</span>");} | {
"score": 5,
"source": [
"https://Stackoverflow.com/questions/155584",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4318/"
]
} |
155,586 | We use the DesignSurface and all that good IDesignerHost goodness in our own designer. The designed forms are then persisted in our own bespoke format and all that works great. WE also want to export the forms to a text-based format (which we've done as it isn't that difficult). However, we also want to import that text back into a document for the designer which involves getting the designer code back into a CodeCompileUnit. Unfortunately, the Parse method is not implemented (for, no doubt, good reasons). Is there an alternative? We don't want to use anything that wouldn't exist on a standard .NET installation (like .NET libraries installed with Visual Studio). My current idea is to compile the imported text and then instantiate the form and copy its properties and controls over to the design surface object, and just capture the new CodeCompileUnit, but I was hoping there was a better way. Thanks. UPDATE: I though some might be interested in our progress. So far, not so good. A brief overview of what I've discovered is that the Parse method was not implemented because it was deemed too difficult, open source parsers exist that do the work but they're not complete and therefore aren't guaranteed to work in all cases (NRefactory is one of those from the SharpDevelop project, I believe), and the copying of controls across from an instance to the designer isn't working as yet. I believe this is because although the controls are getting added to the form instance that the designer surface wraps, the designer surface is not aware of their inclusion. Our next attempt is to mimic cut/paste to see if that solves it. Obviously, this is a huge nasty workaround, but we need it working so we'll take the hit and keep an eye out for alternatives. | Here is some JavaScript. var message = "The quick brown fox.";var colors = new Array("#ff0000","#00ff00","#0000ff"); // red, green, bluefor (var i = 0; i < message.length; i++){ document.write("<span style=\"color:" + colors[(i % colors.length)] + ";\">" + message[i] + "</span>");} | {
"score": 5,
"source": [
"https://Stackoverflow.com/questions/155586",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/23234/"
]
} |
155,593 | Is there a way to determine the number of users that have active sessions in an ASP.NET application? I have an admin/tools page in a particular application, and I would like to display info regarding all open sessions, such as the number of sessions, and perhaps the requesting machines' addresses, or other credential information for each user. | ASP.NET Performance Counters like State Server Sessions Active (The number of active user sessions) should help you out. Then you can just read and display the performance counters from your admin page.. | {
"score": 5,
"source": [
"https://Stackoverflow.com/questions/155593",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/23886/"
]
} |
155,601 | What references offer a good summary/tutorial for using RDF/OWL? There seem to be enough tools (Protege, Topbraid, Jena, etc.) that knowing the syntax of the markup languages is not necessary, but knowing the concepts is, of course, still critical. I'm working through the w3c documents (particularly the RDF Primer ) but I'd like to find other resources/techniques to use as well. | A very good introduction to the semantic web in comparison to object-oriented languages is this document from W3C: A Semantic Web Primer for Object-Oriented Software Developers . It helped me clarify a lot of things from the beginning. | {
"score": 6,
"source": [
"https://Stackoverflow.com/questions/155601",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3446/"
]
} |
155,603 | Our network admins have disabled IMAP and POP for our exchange server, but do have RDP over HTTP enabled. Does Mac Mail only use IMAP to communicate with exchange servers, or does it also know how to use RDP over HTTP? | A very good introduction to the semantic web in comparison to object-oriented languages is this document from W3C: A Semantic Web Primer for Object-Oriented Software Developers . It helped me clarify a lot of things from the beginning. | {
"score": 6,
"source": [
"https://Stackoverflow.com/questions/155603",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/12497/"
]
} |
155,609 | Can someone provide a simple explanation of methods vs. functions in OOP context? | A function is a piece of code that is called by name. It can be passed data to operate on (i.e. the parameters) and can optionally return data (the return value). All data that is passed to a function is explicitly passed. A method is a piece of code that is called by a name that is associated with an object. In most respects it is identical to a function except for two key differences: A method is implicitly passed the object on which it was called. A method is able to operate on data that is contained within the class (remembering that an object is an instance of a class - the class is the definition, the object is an instance of that data). (this is a simplified explanation, ignoring issues of scope etc.) | {
"score": 12,
"source": [
"https://Stackoverflow.com/questions/155609",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/23973/"
]
} |
155,610 | I have a trivial console application in .NET. It's just a test part of a larger application. I'd like to specify the "exit code" of my console application. How do I do this? | Three options: You can return it from Main if you declare your Main method to return int . You can call Environment.Exit(code) . You can set the exit code using properties: Environment.ExitCode = -1; . This will be used if nothing else sets the return code or uses one of the other options above). Depending on your application (console, service, web application, etc.), different methods can be used. | {
"score": 10,
"source": [
"https://Stackoverflow.com/questions/155610",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/22471/"
]
} |
155,615 | I understand that server-side validation is an absolute must to prevent malicious users (or simply users who choose to disable javascript) from bypassing client-side validation. But that's mainly to protect your application, not to provide value for those who are running browsers with javascript disabled. Is it reasonable to assume visitors have javascript enabled and simply have an unusable site for those who don't? | I browse with NoScript in Firefox, and it always annoys me when I get pages that don't work. That said - know your audience. If you're trying to cater to paranoid computer security professionals - assume they might not have JavaScript enabled. If you're going for a general audience, JavaScript is probably on. | {
"score": 6,
"source": [
"https://Stackoverflow.com/questions/155615",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1574/"
]
} |
155,649 | What's the best way to add the coordinates of a circle to an array in JavaScript? So far I've only been able to do a half circle, but I need a formula that returns the whole circle to two different arrays: xValues and yValues . (I'm trying to get the coordinates so I can animate an object along a path.) Here's what I have so far: circle: function(radius, steps, centerX, centerY){ var xValues = [centerX]; var yValues = [centerY]; for (var i = 1; i < steps; i++) { xValues[i] = (centerX + radius * Math.cos(Math.PI * i / steps-Math.PI/2)); yValues[i] = (centerY + radius * Math.sin(Math.PI * i / steps-Math.PI/2)); }} | Your loop should be set up like this instead: for (var i = 0; i < steps; i++) { xValues[i] = (centerX + radius * Math.cos(2 * Math.PI * i / steps)); yValues[i] = (centerY + radius * Math.sin(2 * Math.PI * i / steps));} Start your loop at 0 Step through the entire 2 * PI range, not just PI. You shouldn't have the var xValues = [centerX]; var yValues = [centerY]; -- the center of the circle is not a part of it. | {
"score": 6,
"source": [
"https://Stackoverflow.com/questions/155649",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/13281/"
]
} |
155,681 | I have saved input from a textarea element to a TEXT column in MySQL. I'm using PHP to pull that data out of the database and want to display it in a p element while still showing the whitespace that the user entered (e.g. multiple spaces and newlines). I've tried a pre tag but it doesn't obey the width set in the containing div element. Other than creating a PHP function to convert spaces to   and new lines to br tags, what are my options? I'd prefer a clean HTML/CSS solution, but any input is welcome! Thanks! | You can cause the text inside the pre to wrap by using the following CSS pre { white-space: pre-wrap; /* css-3 */ white-space: -moz-pre-wrap; /* Mozilla, since 1999 */ white-space: -pre-wrap; /* Opera 4-6 */ white-space: -o-pre-wrap; /* Opera 7 */ word-wrap: break-word; /* Internet Explorer 5.5+ */} Taken from this site It's currently defined in CSS3 (which is not yet a finished standard) but most browsers seem to support it as per the comments. | {
"score": 5,
"source": [
"https://Stackoverflow.com/questions/155681",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/23976/"
]
} |
155,719 | Internationalizing web apps always seems to be a chore. No matter how much you plan ahead for pluggable languages, there's always issues with encoding, funky phrasing that doesn't fit your templates, and other problems. I think it would be useful to get the SO community's input for a set of things that programmers should look out for when deciding to internationalize their web apps. | Internationalization is hard, here's a few things I've learned from working with 2 websites that were in over 20 different languages: Use UTF-8 everywhere. No exceptions. HTML, server-side language (watch out for PHP especially), database, etc. No text in images unless you want a ton of work. Use CSS to put text over images if necessary. Separate configuration from localization. That way localizers can translate the text and you can deal with different configurations per locale (features, layout, etc). You don't want localizers to have the ability to mess with your app. Make sure your layouts can deal with text that is 2-3 times longer than English. And also 50% less than English (Japanese and Chinese are often shorter). Some languages need larger font sizes (Japanese, Chinese) Colors are locale-specific also. Red and green don't mean the same thing everywhere! Add a classname that is the locale name to the body tag of your documents. That way you can specify a specific locale's layout in your CSS file easily. Watch out for variable substitution. Don't split your strings. Leave them whole like this: "You have X new messages" and replace the 'X' with the #. Different languages have different pluralization. 0, 1, 2-4, 5-7, 7-infinity. Hard to deal with. Context is difficult. Sometimes localizers need to know where/how a string is used to make sure it's translated correctly. Resources: http://interglacial.com/~sburke/tpj/as_html/tpj13.html http://www.ryandoherty.net/2008/05/26/quick-tips-for-localizing-web-apps/ http://ed.agadak.net/2007/12/one-potato-two-potato-three-potato-four | {
"score": 6,
"source": [
"https://Stackoverflow.com/questions/155719",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/14032/"
]
} |
155,721 | Please post a working source code example (or link) of how to search string in another process memory and getting offset of match if found. The similar way its done in game cheating utils which search for values in game memory using ReadProcessMemory. | Internationalization is hard, here's a few things I've learned from working with 2 websites that were in over 20 different languages: Use UTF-8 everywhere. No exceptions. HTML, server-side language (watch out for PHP especially), database, etc. No text in images unless you want a ton of work. Use CSS to put text over images if necessary. Separate configuration from localization. That way localizers can translate the text and you can deal with different configurations per locale (features, layout, etc). You don't want localizers to have the ability to mess with your app. Make sure your layouts can deal with text that is 2-3 times longer than English. And also 50% less than English (Japanese and Chinese are often shorter). Some languages need larger font sizes (Japanese, Chinese) Colors are locale-specific also. Red and green don't mean the same thing everywhere! Add a classname that is the locale name to the body tag of your documents. That way you can specify a specific locale's layout in your CSS file easily. Watch out for variable substitution. Don't split your strings. Leave them whole like this: "You have X new messages" and replace the 'X' with the #. Different languages have different pluralization. 0, 1, 2-4, 5-7, 7-infinity. Hard to deal with. Context is difficult. Sometimes localizers need to know where/how a string is used to make sure it's translated correctly. Resources: http://interglacial.com/~sburke/tpj/as_html/tpj13.html http://www.ryandoherty.net/2008/05/26/quick-tips-for-localizing-web-apps/ http://ed.agadak.net/2007/12/one-potato-two-potato-three-potato-four | {
"score": 6,
"source": [
"https://Stackoverflow.com/questions/155721",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/21582/"
]
} |
155,733 | I've used all three of these when making local programmatic connections to databases. Is there any real difference between them? | The final result is the same. The difference is: 'localhost' resolves at the TCP/IP level and is equivalent to the IP address 127.0.0.1 Depending on the application "(local)" could be just an alias for 'localhost'. In SQLServer, '(local)' and '.' mean that the connection will be made using the named pipes (shared memory) protocol within the same machine (doesn't need to go through the TCP/IP stack). That's the theory. In practice, I don't think there is substantial difference in performance or features if you use either one of them. | {
"score": 6,
"source": [
"https://Stackoverflow.com/questions/155733",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3289/"
]
} |
155,739 | I have a requirement to implement an "Unsaved Changes" prompt in an ASP .Net application. If a user modifies controls on a web form, and attempts to navigate away before saving, a prompt should appear warning them that they have unsaved changes, and give them the option to cancel and stay on the current page. The prompt should not display if the user hasn't touched any of the controls. Ideally I'd like to implement this in JavaScript, but before I go down the path of rolling my own code, are there any existing frameworks or recommended design patterns for achieving this? Ideally I'd like something that can easily be reused across multiple pages with minimal changes. | Using jQuery: var _isDirty = false;$("input[type='text']").change(function(){ _isDirty = true;});// replicate for other input types and selects Combine with onunload / onbeforeunload methods as required. From the comments, the following references all input fields, without duplicating code: $(':input').change(function () { Using $(":input") refers to all input, textarea, select, and button elements. | {
"score": 8,
"source": [
"https://Stackoverflow.com/questions/155739",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/637/"
]
} |
155,780 | What is SafeHandle? how does it differ from IntPtr? When should I use one? What are its advantages? | I think MSDN is pretty clear in definition: The SafeHandle class provides critical finalization of handle resources, preventing handles from being reclaimed prematurely by garbage collection and from being recycled by Windows to reference unintended unmanaged objects. Before the .NET Framework version 2.0, all operating system handles could only be encapsulated in the IntPtr managed wrapper object. The SafeHandle class contains a finalizer that ensures that the handle is closed and is guaranteed to run, even during unexpected AppDomain unloads when a host may not trust the consistency of the state of the AppDomain. For more information about the benefits of using a SafeHandle, see Safe Handles and Critical Finalization. This class is abstract because you cannot create a generic handle. To implement SafeHandle, you must create a derived class. To create SafeHandle derived classes, you must know how to create and free an operating system handle. This process is different for different handle types because some use CloseHandle, while others use more specific methods such as UnmapViewOfFile or FindClose. For this reason, you must create a derived class of SafeHandle for each operating system handle type; such as MySafeRegistryHandle, MySafeFileHandle, and MySpecialSafeFileHandle. Some of these derived classes are prewritten and provided for you in the Microsoft.Win32.SafeHandles namespace. | {
"score": 5,
"source": [
"https://Stackoverflow.com/questions/155780",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7418/"
]
} |
155,797 | ADO.NET has the notorious DataRow class which you cannot instantiate using new. This is a problem now that I find a need to mock it using Rhino Mocks. Does anyone have any ideas how I could get around this problem? | I'm curious as to why you need to mock the DataRow. Sometimes you can get caught up doing mocking and forget that it can be just as prudent to use the real thing. If you are passing around data rows then you can simply instantiate one with a helper method and use that as a return value on your mock. SetupResult.For(someMockClass.GetDataRow(input)).Return(GetReturnRow());public DataRow GetReturnRow(){ DataTable table = new DataTable("FakeTable"); DataRow row = table.NewRow(); row.value1 = "someValue"; row.value2 = 234; return row;} If this is not the situation you are in then I am going to need some example code to be able to figure out what you are trying to do. | {
"score": 5,
"source": [
"https://Stackoverflow.com/questions/155797",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5056/"
]
} |
155,810 | When you double click on a class (in 'solution explorer')... if that class happens to be an .asmx.cs webservice... then you get this... To add components to your class, drag them from the Toolbox and use the Properties window to set their properties. To create methods and events for your class, click here to switch to code view. ...it's a 'visual design surface' for webservices. (Who actually uses that surface to write webservices?) So what I want to know, how do I configure visual studio to never show me that design view? Or at least, to show me the code view by default? | You can set the default editor for any given file type (.cs, .xml, .xsd, etc). To change the default editor for a given type: Right-click a file of that type inyour project, and select "OpenWith..." Select your preferred editor. Youmay want "CSharp Editor". Click "Set as Default". I don't see the behavior you see with web services, but this should work with all file types in Visual Studio. | {
"score": 6,
"source": [
"https://Stackoverflow.com/questions/155810",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/49/"
]
} |
155,848 | I need to create an access (mdb) database without using the ADOX interop assembly. How can this be done? | Before I throw away this code, it might as well live on stackoverflow Something along these lines seems to do the trick: if (!File.Exists(DB_FILENAME)){ var cnnStr = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + DB_FILENAME; // Use a late bound COM object to create a new catalog. This is so we avoid an interop assembly. var catType = Type.GetTypeFromProgID("ADOX.Catalog"); object o = Activator.CreateInstance(catType); catType.InvokeMember("Create", BindingFlags.InvokeMethod, null, o, new object[] {cnnStr}); OleDbConnection cnn = new OleDbConnection(cnnStr); cnn.Open(); var cmd = cnn.CreateCommand(); cmd.CommandText = "CREATE TABLE VideoPosition (filename TEXT , pos LONG)"; cmd.ExecuteNonQuery();} This code illustrates that you can access the database using OleDbConnection once its created with the ADOX.Catalog COM component. | {
"score": 5,
"source": [
"https://Stackoverflow.com/questions/155848",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/17174/"
]
} |
155,864 | I have a controller with an action method as follows: public class InventoryController : Controller{ public ActionResult ViewStockNext(int firstItem) { // Do some stuff }} And when I run it I get an error stating: The parameters dictionary does not contain a valid value of type 'System.Int32' for parameter 'firstItem'. To make a parameter optional its type should either be a reference type or a Nullable type. I had it working at one point and I decided to try the function without parameters. Finding out that the controller was not persistant I put the parameter back in, now it refuses to recognise the parameter when I call the method. I'm using this url syntax to call the action: http://localhost:2316/Inventory/ViewStockNext/11 Any ideas why I would get this error and what I need to do to fix it? I've tried adding another method that takes an integer to the class it it also fails with the same reason. I've tried adding one that takes a string, and the string is set to null. I've tried adding one without parameters and that works fine, but of course it won't suit my needs. | Your routing needs to be set up along the lines of {controller}/{action}/{firstItem} . If you left the routing as the default {controller}/{action}/{id} in your global.asax.cs file, then you will need to pass in id . routes.MapRoute( "Inventory", "Inventory/{action}/{firstItem}", new { controller = "Inventory", action = "ListAll", firstItem = "" }); ... or something close to that. | {
"score": 8,
"source": [
"https://Stackoverflow.com/questions/155864",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11908/"
]
} |
155,920 | I have one of those "I swear I didn't touch the server" situations. I honestly didn't touch any of the php scripts. The problem I am having is that php data is not being saved across different pages or page refreshes. I know a new session is being created correctly because I can set a session variable (e.g. $_SESSION['foo'] = "foo" and print it back out on the same page just fine. But when I try to use that same variable on another page it is not set! Is there any php functions or information I can use on my hosts server to see what is going on? Here is an example script that does not work on my hosts' server as of right now: <?phpsession_start();if(isset($_SESSION['views'])) $_SESSION['views'] = $_SESSION['views']+ 1;else $_SESSION['views'] = 1;echo "views = ". $_SESSION['views'];echo '<p><a href="page1.php">Refresh</a></p>';?> The 'views' variable never gets incremented after doing a page refresh. I'm thinking this is a problem on their side, but I wanted to make sure I'm not a complete idiot first. Here is the phpinfo() for my hosts' server (PHP Version 4.4.7): | Thanks for all the helpful info. It turns out that my host changed servers and started using a different session save path other than /var/php_sessions which didn't exist anymore. A solution would have been to declare ini_set(' session.save_path','SOME WRITABLE PATH'); in all my script files but that would have been a pain. I talked with the host and they explicitly set the session path to a real path that did exist. Hope this helps anyone having session path troubles. | {
"score": 6,
"source": [
"https://Stackoverflow.com/questions/155920",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/13556/"
]
} |
155,932 | I would like to know how to loop through each line in a text file using a Windows batch file and process each line of text in succession. | I needed to process the entire line as a whole. Here is what I found to work. for /F "tokens=*" %%A in (myfile.txt) do [process] %%A The tokens keyword with an asterisk (*) will pull all text for the entire line. If you don't put in the asterisk it will only pull the first word on the line. I assume it has to do with spaces. For Command on TechNet If there are spaces in your file path, you need to use usebackq . For example. for /F "usebackq tokens=*" %%A in ("my file.txt") do [process] %%A | {
"score": 9,
"source": [
"https://Stackoverflow.com/questions/155932",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5132/"
]
} |
155,934 | What GNU/Linux command-line tool would I use for performing a search and replace on a file? Can the search text, and replacement, be specified in a regex format? | sed 's/a.*b/xyz/g;' old_file > new_file GNU sed (which you probably have) is even more versatile: sed -r --in-place 's/a(.*)b/x\1y/g;' your_file Here is a brief explanation of those options: -i[SUFFIX], --in-place[=SUFFIX] edit files in place (makes backup if extension supplied) -r, --regexp-extended use extended regular expressions in the script. The FreeBSD , NetBSD and OpenBSD versions also supports these options. If you want to learn more about sed, Cori has suggested this tutorial . | {
"score": 7,
"source": [
"https://Stackoverflow.com/questions/155934",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2045/"
]
} |
155,964 | I know about the HIG (which is quite handy!), but what programming practices do you use when writing Objective-C, and more specifically when using Cocoa (or CocoaTouch). | There are a few things I have started to do that I do not think are standard: 1) With the advent of properties, I no longer use "_" to prefix "private" class variables. After all, if a variable can be accessed by other classes shouldn't there be a property for it? I always disliked the "_" prefix for making code uglier, and now I can leave it out. 2) Speaking of private things, I prefer to place private method definitions within the .m file in a class extension like so: #import "MyClass.h"@interface MyClass ()- (void) someMethod;- (void) someOtherMethod;@end@implementation MyClass Why clutter up the .h file with things outsiders should not care about? The empty () works for private categories in the .m file, and issues compile warnings if you do not implement the methods declared. 3) I have taken to putting dealloc at the top of the .m file, just below the @synthesize directives. Shouldn't what you dealloc be at the top of the list of things you want to think about in a class? That is especially true in an environment like the iPhone. 3.5) In table cells, make every element (including the cell itself) opaque for performance. That means setting the appropriate background color in everything. 3.6) When using an NSURLConnection, as a rule you may well want to implement the delegate method: - (NSCachedURLResponse *)connection:(NSURLConnection *)connection willCacheResponse:(NSCachedURLResponse *)cachedResponse{ return nil;} I find most web calls are very singular and it's more the exception than the rule you'll be wanting responses cached, especially for web service calls. Implementing the method as shown disables caching of responses. Also of interest, are some good iPhone specific tips from Joseph Mattiello (received in an iPhone mailing list). There are more, but these were the most generally useful I thought (note that a few bits have now been slightly edited from the original to include details offered in responses): 4) Only use double precision if you have to, such as when working with CoreLocation. Make sure you end your constants in 'f' to make gcc store them as floats. float val = someFloat * 2.2f; This is mostly important when someFloat may actually be a double, you don't need the mixed-mode math, since you're losing precision in 'val' on storage. While floating-point numbers are supported in hardware on iPhones, it may still take more time to do double-precision arithmetic as opposed to single precision. References: Double vs float on the iPhone iPhone/iPad double precision math On the older phones supposedly calculations operate at the same speed but you can have more single precision components in registers than doubles, so for many calculations single precision will end up being faster. 5) Set your properties as nonatomic . They're atomic by default and upon synthesis, semaphore code will be created to prevent multi-threading problems. 99% of you probably don't need to worry about this and the code is much less bloated and more memory-efficient when set to nonatomic. 6) SQLite can be a very, very fast way to cache large data sets. A map application for instance can cache its tiles into SQLite files. The most expensive part is disk I/O. Avoid many small writes by sending BEGIN; and COMMIT; between large blocks. We use a 2 second timer for instance that resets on each new submit. When it expires, we send COMMIT; , which causes all your writes to go in one large chunk. SQLite stores transaction data to disk and doing this Begin/End wrapping avoids creation of many transaction files, grouping all of the transactions into one file. Also, SQL will block your GUI if it's on your main thread. If you have a very long query, It's a good idea to store your queries as static objects, and run your SQL on a separate thread. Make sure to wrap anything that modifies the database for query strings in @synchronize() {} blocks. For short queries just leave things on the main thread for easier convenience. More SQLite optimization tips are here, though the document appears out of date many of the points are probably still good; http://web.utk.edu/~jplyon/sqlite/SQLite_optimization_FAQ.html | {
"score": 10,
"source": [
"https://Stackoverflow.com/questions/155964",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/21804/"
]
} |
155,977 | I have the following markup, and I want to make the All radio button checked. <ul> <li><input type="radio" value="All" name="Foo"/>All</li> <li><input type="radio" value="New" name="Foo"/>New</li> <li><input type="radio" value="Removed" name="Foo"/>Removed</li> <li><input type="radio" value="Updated" name="Foo"/>Updated</li></ul> I'd like to match via attribute, but I need to match on 2 attributes, @name='Foo' and @value='All' . Something like this: $("input[@name='Foo' @value='all']").attr('checked','checked'); Can someone show how this can be done? | The following HTML file shows how you can do this: <html> <head> <script type="text/javascript" src="jquery-1.2.6.pack.js"></script> <script type="text/javascript"> $(document).ready(function(){ $("a").click(function(event){ $("input[name='Foo'][value='All']").attr('checked','checked'); event.preventDefault(); }); }); </script> </head> <body> <ul> <li><input type="radio" value="All" name="Foo" />All</li> <li><input type="radio" value="New" name="Foo" />New</li> <li><input type="radio" value="Removed" name="Foo" />Removed</li> <li><input type="radio" value="Updated" name="Foo" />Updated</li> </ul> <a href="" >Click here</a> </body></html> When you click on the link, the desired radio button is selected. The important line is the one setting the checked attribute. | {
"score": 7,
"source": [
"https://Stackoverflow.com/questions/155977",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/410357/"
]
} |
156,013 | I can't quite figure out this syntax problem with a case expression in a do block. What is the correct syntax? If you could correct my example and explain it that would be the best. module Main where main = do putStrLn "This is a test" s <- foo putStrLn s foo = do args <- getArgs return case args of [] -> "No Args" [s]-> "Some Args" A little update. My source file was a mix of spaces and tabs and it was causing all kinds of problems.Just a tip for any one else starting in Haskell. If you are having problems check for tabs and spaces in your source code. | return is an (overloaded) function, and it's not expecting its first argument to be a keyword. You can either parenthesize: module Main where import System(getArgs)main = do putStrLn "This is a test" s <- foo putStrLn s foo = do args <- getArgs return (case args of [] -> "No Args" [s]-> "Some Args") or use the handy application operator ($): foo = do args <- getArgs return $ case args of [] -> "No Args" [s]-> "Some Args" Stylewise, I'd break it out into another function: foo = do args <- getArgs return (has_args args)has_args [] = "No Args"has_args _ = "Some Args" but you still need to parenthesize or use ($), because return takes one argument, and function application is the highest precedence. | {
"score": 6,
"source": [
"https://Stackoverflow.com/questions/156013",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/8965/"
]
} |
156,046 | I'm using a Form to show notifications (it appears at the bottom right of the screen), but when I show this form it steals the focus from the main Form. Is there a way to show this "notification" form without stealing focus? | Hmmm, isn't simply overriding Form.ShowWithoutActivation enough? protected override bool ShowWithoutActivation{ get { return true; }} And if you don't want the user to click this notification window either, you can override CreateParams: protected override CreateParams CreateParams{ get { CreateParams baseParams = base.CreateParams; const int WS_EX_NOACTIVATE = 0x08000000; const int WS_EX_TOOLWINDOW = 0x00000080; baseParams.ExStyle |= ( int )( WS_EX_NOACTIVATE | WS_EX_TOOLWINDOW ); return baseParams; }} | {
"score": 8,
"source": [
"https://Stackoverflow.com/questions/156046",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4386/"
]
} |
156,083 | I hear people writing these programs all the time and I know what they do, but how do they actually do it? I'm looking for general concepts. | Technically, screenscraping is any program that grabs the display data of another program and ingests it for it's own use. Quite often, screenscaping refers to a web client that parses the HTML pages of targeted website to extract formatted data. This is done when a website does not offer an RSS feed or a REST API for accessing the data in a programmatic way. One example of a library used for this purpose is Hpricot for Ruby, which is one of the better-architected HTML parsers used for screen scraping. | {
"score": 6,
"source": [
"https://Stackoverflow.com/questions/156083",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/17744/"
]
} |
156,114 | When paging through data that comes from a DB, you need to know how many pages there will be to render the page jump controls. Currently I do that by running the query twice, once wrapped in a count() to determine the total results, and a second time with a limit applied to get back just the results I need for the current page. This seems inefficient. Is there a better way to determine how many results would have been returned before LIMIT was applied? I am using PHP and Postgres. | Pure SQL Things have changed since 2008. You can use a window function to get the full count and the limited result in one query. Introduced with PostgreSQL 8.4 in 2009 . SELECT foo , count(*) OVER() AS full_count FROM barWHERE <some condition>ORDER BY <some col>LIMIT <pagesize>OFFSET <offset>; Note that this can be considerably more expensive than without the total count . All rows have to be counted, and a possible shortcut taking just the top rows from a matching index may not be helpful any more. Doesn't matter much with small tables or full_count <= OFFSET + LIMIT . Matters for a substantially bigger full_count . Corner case : when OFFSET is at least as great as the number of rows from the base query, no row is returned. So you also get no full_count . Possible alternative: Run a query with a LIMIT/OFFSET and also get the total number of rows Sequence of events in a SELECT query ( 0. CTEs are evaluated and materialized separately. In Postgres 12 or later the planner may inline those like subqueries before going to work.) Not here. WHERE clause (and JOIN conditions, though none in your example) filter qualifying rows from the base table(s). The rest is based on the filtered subset. ( 2. GROUP BY and aggregate functions would go here.) Not here. ( 3. Other SELECT list expressions are evaluated, based on grouped / aggregated columns.) Not here. Window functions are applied depending on the OVER clause and the frame specification of the function. The simple count(*) OVER() is based on all qualifying rows. ORDER BY ( 6. DISTINCT or DISTINCT ON would go here.) Not here. LIMIT / OFFSET are applied based on the established order to select rows to return. LIMIT / OFFSET becomes increasingly inefficient with a growing number of rows in the table. Consider alternative approaches if you need better performance: Optimize query with OFFSET on large table Alternatives to get final count There are completely different approaches to get the count of affected rows ( not the full count before OFFSET & LIMIT were applied). Postgres has internal bookkeeping how many rows where affected by the last SQL command. Some clients can access that information or count rows themselves (like psql). For instance, you can retrieve the number of affected rows in plpgsql immediately after executing an SQL command with: GET DIAGNOSTICS integer_var = ROW_COUNT; Details in the manual. Or you can use pg_num_rows in PHP . Or similar functions in other clients. Related: Calculate number of rows affected by batch query in PostgreSQL | {
"score": 8,
"source": [
"https://Stackoverflow.com/questions/156114",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20851/"
]
} |
156,230 | Is there a framework equivalent to Guice ( http://code.google.com/p/google-guice ) for Python? | I haven't used it, but the Spring Python framework is based on Spring and implements Inversion of Control . There also appears to be a Guice in Python project: snake-guice | {
"score": 5,
"source": [
"https://Stackoverflow.com/questions/156230",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9940/"
]
} |
156,243 | What is the difference between the following 2 ways to allocate and init an object? AController *tempAController = [[AController alloc] init];self.aController = tempAController;[tempAController release]; and self.aController= [[AController alloc] init]; Most of the apple example use the first method. Why would you allocate, init and object and then release immediately? | Every object has a reference count. When it goes to 0, the object is deallocated. Assuming the property was declared as @property (retain) : Your first example, line by line: The object is created by alloc , it has a reference count of 1. The object is handed over to self 's setAController: method, which sends it a retain message (because the method doesn't know where the object is coming from), incrementing its reference count to 2. The calling code no longer needs the object itself, so it calls release , decrementing the reference count to 1. Your second example basically does steps 1 and 2 but not 3, so at the end the object's reference count is 2. The rule is that if you create an object, you are responsible for releasing it when you're done with it. In your example, the code is done with tempAController after it sets the property. It is the setter method's responsibility to call retain if it needs that object to stick around. It's important to remember that self.property = foo; in Objective-C is really just shorthand for [self setProperty:foo]; and that the setProperty: method is going to be retaining or copying objects as needed. If the property was declared @property (copy) , then the object would have been copied instead of retained. In the first example, the original object would be released right away; in the second example, the original object's reference count would be 1 even though it should be 0. So you would still want to write your code the same way. If the property was declared @property (assign) , then self isn't claiming ownership of the object, and somebody else needs to retain it. In this case, the first example would be incorrect. These sorts of properties are rare, usually only used for object delegates. | {
"score": 7,
"source": [
"https://Stackoverflow.com/questions/156243",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1987/"
]
} |
156,257 | In an AI application I am writing in C++, there is not much numerical computation there are lot of structures for which run-time polymorphism is needed very often, several polymorphic structures interact during computation In such a situation, are there any optimization techniques? While I won't care to optimize the application just now, one aspect of selecting C++ over Java for the project was to enable more leverage to optimize and to be able to use non-object oriented methods (templates, procedures, overloading). In particular, what are the optimization techniques related to virtual functions? Virtual functions are implemented through virtual tables in memory. Is there some way to pre-fetch these virtual tables onto L2 cache (the cost of fetching from memory/L2 cache is increasing)? Apart from this, are there good references for data locality techniques in C++? These techniques would reduce the wait time for data fetch into L2 cache needed for computation. Update : Also see the following related forums: Performance Penalty for Interface , Several Levels of Base Classes | Virtual functions are very efficient. Assuming 32 bit pointers the memory layout is approximately: classptr -> [vtable:4][classdata:x]vtable -> [first:4][second:4][third:4][fourth:4][...]first -> [code:x]second -> [code:x]... The classptr points to memory that is typically on the heap, occasionally on the stack, and starts with a four byte pointer to the vtable for that class. But the important thing to remember is the vtable itself is not allocated memory. It's a static resource and all objects of the same class type will point to the exactly the same memory location for their vtable array. Calling on different instances won't pull different memory locations into L2 cache. This example from msdn shows the vtable for class A with virtual func1, func2, and func3. Nothing more than 12 bytes. There is a good chance the vtables of different classes will also be physically adjacent in the compiled library (you'll want to verify this is you're especially concerned) which could increase cache efficiency microscopically. CONST SEGMENT??_7A@@6B@ DD FLAT:?func1@A@@UAEXXZ DD FLAT:?func2@A@@UAEXXZ DD FLAT:?func3@A@@UAEXXZCONST ENDS The other performance concern would be instruction overhead of calling through a vtable function. This is also very efficient. Nearly identical to calling a non-virtual function. Again from the example from msdn : ; A* pa;; pa->func3();mov eax, DWORD PTR _pa$[ebp]mov edx, DWORD PTR [eax]mov ecx, DWORD PTR _pa$[ebp]call DWORD PTR [edx+8] In this example ebp, the stack frame base pointer, has the variable A* pa at zero offset. The register eax is loaded with the value at location [ebp], so it has the A*, and edx is loaded with the value at location [eax], so it has class A vtable. Then ecx is loaded with [ebp], because ecx represents "this" it now holds the A*, and finally the call is made to the value at location [edx+8] which is the third function address in the vtable. If this function call was not virtual the mov eax and mov edx would not be needed, but the difference in performance would be immeasurably small. | {
"score": 6,
"source": [
"https://Stackoverflow.com/questions/156257",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/19501/"
]
} |
156,275 | Is there a good reason why there is no Pair<L,R> in Java? What would be the equivalent of this C++ construct? I would rather avoid reimplementing my own. It seems that 1.6 is providing something similar ( AbstractMap.SimpleEntry<K,V> ), but this looks quite convoluted. | In a thread on comp.lang.java.help , Hunter Gratzner gives some arguments against the presence of a Pair construct in Java. The main argument is that a class Pair doesn't convey any semantics about the relationship between the two values (how do you know what "first" and "second" mean ?). A better practice is to write a very simple class, like the one Mike proposed, for each application you would have made of the Pair class. Map.Entry is an example of a pair that carry its meaning in its name. To sum up, in my opinion it is better to have a class Position(x,y) , a class Range(begin,end) and a class Entry(key,value) rather than a generic Pair(first,second) that doesn't tell me anything about what it's supposed to do. | {
"score": 10,
"source": [
"https://Stackoverflow.com/questions/156275",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/13673/"
]
} |
156,279 | The title is self explanatory. Is there a way of directly doing such kind of importing? | The .BAK files from SQL server are in Microsoft Tape Format (MTF) ref: http://www.fpns.net/willy/msbackup.htm The bak file will probably contain the LDF and MDF files that SQL server uses to store the database. You will need to use SQL server to extract these. SQL Server Express is free and will do the job. So, install SQL Server Express edition, and open the SQL Server Powershell. There execute sqlcmd -S <COMPUTERNAME>\SQLExpress (whilst logged in as administrator) then issue the following command. restore filelistonly from disk='c:\temp\mydbName-2009-09-29-v10.bak';GO This will list the contents of the backup - what you need is the first fields that tell you the logical names - one will be the actual database and the other the log file. RESTORE DATABASE mydbName FROM disk='c:\temp\mydbName-2009-09-29-v10.bak'WITH MOVE 'mydbName' TO 'c:\temp\mydbName_data.mdf', MOVE 'mydbName_log' TO 'c:\temp\mydbName_data.ldf';GO At this point you have extracted the database - then install Microsoft's "Sql Web Data Administrator". together with this export tool and you will have an SQL script that contains the database. | {
"score": 7,
"source": [
"https://Stackoverflow.com/questions/156279",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/131/"
]
} |
156,322 | fossil http://www.fossil-scm.org I found this recently and have started using it for my home projects. I want to hear what other people think of this VCS. What is missing in my mind, is IDE support. Hopefully it will come, but I use the command line just fine. My favorite things about fossil: single executable with built in web server wiki and bug tracking. The repository is just one SQLite ( http://www.sqlite.org ) database file, easy to do backups on. I also like that I can run fossil from and keep the repository on my thumb drive. This means my software development has become completely portable. Tell me what you think.... | Mr. Millikin, if you will take a few moments to review some of the documentation on fossil, I think your objections are addressed there. Storing a repository in an sQLite database is arguably safer than any other approach. See link text for some of the advantages of using a transactional database to store a repository. As for bloat: The entire thing is in a single self-contained executable which seems to disprove that concern. Full disclosure: I am the author of fossil. Note that I wrote fossil because no other DVCS met my needs. On the other hand, my needs are not your needs and so only you can judge whether or not fossil is right for you. But I do encourage you to at least have a look at the documentation and try to understand the problem that fossil is trying to solve before you dismiss it. | {
"score": 8,
"source": [
"https://Stackoverflow.com/questions/156322",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3576/"
]
} |
156,329 | I need to pad numbers with leading zeros (total 8 digits) for display. I'm using oracle. select to_char(1011,'00000000') OPE_NO from dual;select length(to_char(1011,'00000000')) OPE_NO from dual; Instead of '00001011' I get ' 00001011'.Why do I get an extra leading blank space? What is the correct number formatting string to accomplish this? P.S. I realise I can just use trim() , but I want to understand number formatting better. @Eddie: I already read the documentation. And yet I still don't understand how to get rid of the leading whitespace. @David: So does that mean there's no way but to use trim() ? | Use FM (Fill Mode), e.g. select to_char(1011,'FM00000000') OPE_NO from dual; | {
"score": 6,
"source": [
"https://Stackoverflow.com/questions/156329",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3751/"
]
} |
156,330 | I'm just trying to time a piece of code. The pseudocode looks like: start = get_ticks()do_long_code()print "It took " + (get_ticks() - start) + " seconds." How does this look in Python? More specifically, how do I get the number of ticks since midnight (or however Python organizes that timing)? | In the time module, there are two timing functions: time and clock . time gives you "wall" time, if this is what you care about. However, the python docs say that clock should be used for benchmarking. Note that clock behaves different in separate systems: on MS Windows, it uses the Win32 function QueryPerformanceCounter(), with "resolution typically better than a microsecond". It has no special meaning, it's just a number (it starts counting the first time you call clock in your process). # ms windows t0= time.clock() do_something() t= time.clock() - t0 # t is wall seconds elapsed (floating point) on *nix, clock reports CPU time. Now, this is different, and most probably the value you want, since your program hardly ever is the only process requesting CPU time (even if you have no other processes, the kernel uses CPU time now and then). So, this number, which typically is smaller¹ than the wall time (i.e. time.time() - t0), is more meaningful when benchmarking code: # linux t0= time.clock() do_something() t= time.clock() - t0 # t is CPU seconds elapsed (floating point) Apart from all that, the timeit module has the Timer class that is supposed to use what's best for benchmarking from the available functionality. ¹ unless threading gets in the way… ² Python ≥3.3: there are time.perf_counter() and time.process_time() . perf_counter is being used by the timeit module. | {
"score": 6,
"source": [
"https://Stackoverflow.com/questions/156330",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/432/"
]
} |
156,331 | I was inserting data into a MS Access database using JDBC-ODBC driver. The blank mdb file was 2KB. After populating this database, the size grew to 155MB. Then I was deleting the data. But I found the size of mdb remains the same as 155MB. I don't get any errors. But is it normal this way? I would expect the file size reduces. If it is designed in this way, what is the idea behind it? Thanks | MS Access doesn't reclaim the space for records until you have compacted the database. This is something you should do to an access database as part of your regularly maintenance otherwise you will end up with some pretty painful problems. You can compact a database either through the MS Access UI (Tools -> Database Utilities -> Compact and Repair Database) of you can use the command prompt using: msaccess.exe "target database.accdb" /compact N.B. the /Compact switch must be after the target database | {
"score": 5,
"source": [
"https://Stackoverflow.com/questions/156331",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/24020/"
]
} |
156,362 | Just getting my head around Ruby metaprogramming. The mixin/modules always manage to confuse me. include : mixes in specified module methods as instance methods in the target class extend : mixes in specified module methods as class methods in the target class So is the major difference just this or is a bigger dragon lurking? e.g. module ReusableModule def module_method puts "Module Method: Hi there!" endendclass ClassThatIncludes include ReusableModuleendclass ClassThatExtends extend ReusableModuleendputs "Include"ClassThatIncludes.new.module_method # "Module Method: Hi there!"puts "Extend"ClassThatExtends.module_method # "Module Method: Hi there!" | What you have said is correct. However, there is more to it than that. If you have a class Klazz and module Mod , including Mod in Klazz gives instances of Klazz access to Mod 's methods. Or you can extend Klazz with Mod giving the class Klazz access to Mod 's methods. But you can also extend an arbitrary object with o.extend Mod . In this case the individual object gets Mod 's methods even though all other objects with the same class as o do not. | {
"score": 9,
"source": [
"https://Stackoverflow.com/questions/156362",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1695/"
]
} |
156,373 | I'm storing an object ( TTF_Font ) in a shared_ptr that is provided to me from a third-party API. I cannot use new or delete on the object, so the shared_ptr is also provided a "freeing" functor. // Functorstruct CloseFont{ void operator()(TTF_Font* font) const { if(font != NULL) { TTF_CloseFont(font); } }};boost::shared_ptr<TTF_Font> screenFont;screenFont = boost::shared_ptr<TTF_Font>( TTF_OpenFont("slkscr.ttf", 8), CloseFont() ); If, later, I need to explicitly free this object is it correct to do this: screenFont.reset(); And then let screenFont (the actual shared_ptr object) be destroyed naturally? | shared_ptr<>::reset() will drop the refcount by one. If that results in the count dropping to zero, the resource pointed to by the shared_ptr<> will be freed. So I think the answer for you is, yes that will work. Or you can simply let the screenFont variable be destructed due to dropping out of scope or whatever, if that's what's about to happen. To be clear, the normal usage of shared_ptr<> is that you let it be destructed naturally, and it will deal with the refcount and freeing the resource when it drops to zero naturally. reset() is only required if you need to release that particular instance of the shared resource before the shared_ptr<> would be naturally destructed. | {
"score": 5,
"source": [
"https://Stackoverflow.com/questions/156373",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/18265/"
]
} |
156,394 | How is it that Ruby allows a class access methods outside of the class implicitly? Example: class Candy def land homer endenddef homer puts "Hello"endCandy.new.land #Outputs Hello | The definition of the "homer" method is adding the method to the Object class. It is not defining a free function. Class Candy implicitly inherits from Object, and so has access to the methods in Object. When you call "homer" in the "land" method, the method resolution can't find a definition in the current class, goes to the super class, finds the method you have added to Object, and calls it. | {
"score": 6,
"source": [
"https://Stackoverflow.com/questions/156394",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
]
} |
156,395 | As a Java developer who is reading Apple's Objective-C 2.0 documentation: I wonder what " sending a message to nil " means - let alone how it is actually useful. Taking an excerpt from the documentation: There are several patterns in Cocoa that take advantage of this fact. The value returned from a message to nil may also be valid: If the method returns an object, any pointer type, any integer scalar of size less than or equal to sizeof(void*), a float, a double, a long double, or a long long, then a message sent to nil returns 0. If the method returns a struct, as defined by the Mac OS X ABI Function Call Guide to be returned in registers, then a message sent to nil returns 0.0 for every field in the data structure. Other struct data types will not be filled with zeros. If the method returns anything other than the aforementioned value types the return value of a message sent to nil is undefined. Has Java rendered my brain incapable of grokking the explanation above? Or is there something that I am missing that would make this as clear as glass? I do get the idea of messages/receivers in Objective-C, I am simply confused about a receiver that happens to be nil . | Well, I think it can be described using a very contrived example. Let's say you have a method in Java which prints out all of the elements in an ArrayList: void foo(ArrayList list){ for(int i = 0; i < list.size(); ++i){ System.out.println(list.get(i).toString()); }} Now, if you call that method like so: someObject.foo(NULL); you're going to probably get a NullPointerException when it tries to access list, in this case in the call to list.size(); Now, you'd probably never call someObject.foo(NULL) with the NULL value like that. However, you may have gotten your ArrayList from a method which returns NULL if it runs into some error generating the ArrayList like someObject.foo(otherObject.getArrayList()); Of course, you'll also have problems if you do something like this: ArrayList list = NULL;list.size(); Now, in Objective-C, we have the equivalent method: - (void)foo:(NSArray*)anArray{ int i; for(i = 0; i < [anArray count]; ++i){ NSLog(@"%@", [[anArray objectAtIndex:i] stringValue]; }} Now, if we have the following code: [someObject foo:nil]; we have the same situation in which Java will produce a NullPointerException. The nil object will be accessed first at [anArray count] However, instead of throwing a NullPointerException, Objective-C will simply return 0 in accordance with the rules above, so the loop will not run. However, if we set the loop to run a set number of times, then we're first sending a message to anArray at [anArray objectAtIndex:i]; This will also return 0, but since objectAtIndex: returns a pointer, and a pointer to 0 is nil/NULL, NSLog will be passed nil each time through the loop. (Although NSLog is a function and not a method, it prints out (null) if passed a nil NSString. In some cases it's nicer to have a NullPointerException, since you can tell right away that something is wrong with the program, but unless you catch the exception, the program will crash. (In C, trying to dereference NULL in this way causes the program to crash.) In Objective-C, it instead just causes possibly incorrect run-time behavior. However, if you have a method that doesn't break if it returns 0/nil/NULL/a zeroed struct, then this saves you from having to check to make sure the object or parameters are nil. | {
"score": 8,
"source": [
"https://Stackoverflow.com/questions/156395",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9931/"
]
} |
156,430 | I recently read somewhere that writing a regexp to match an email address, taking into account all the variations and possibilities of the standard is extremely hard and is significantly more complicated than what one would initially assume. Why is that? Are there any known and proven regexps that actually do this fully? What are some good alternatives to using regexps for matching email addresses? | For the formal e-mail spec, yes, it is technically impossible via Regex due to the recursion of things like comments (especially if you don't remove comments to whitespace first), and the various different formats (an e-mail address isn't always [email protected]). You can get close (with some massive and incomprehensible Regex patterns), but a far better way of checking an e-mail is to do the very familiar handshake: they tell you their e-mail you e-mail them a confimation link with a Guid when they click on the link you know that: the e-mail is correct it exists they own it Far better than blindly accepting an e-mail address. | {
"score": 7,
"source": [
"https://Stackoverflow.com/questions/156430",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9611/"
]
} |
156,436 | It's quite a simple question - how do I sort a collection? I've got a CSV file with rows in a random order. I'd like to sort the rows according to the date in one column. Do I add the rows to a recordset? Can I sort with a Scripting.Dictionary? I've clearly been spoilt with .NET and Linq, and now I find myself back in the land of classic asp, realising I must have known this 7 years ago, and missing generics immensely. I feel like a complete n00b. | In this case I would get help from big brother .net. It's possible to use System.Collections.Sortedlist within your ASP app and get your key value pairs sorted. set list = server.createObject("System.Collections.Sortedlist")with list .add "something", "YY" .add "something else", "XX"end withfor i = 0 to list.count - 1 response.write(list.getKey(i) & " = " & list.getByIndex(i))next Btw if the following .net classes are available too: System.Collections.Queue System.Collections.Stack System.Collections.ArrayList System.Collections.SortedList System.Collections.Hashtable System.IO.StringWriter System.IO.MemoryStream; Also see: Marvels of COM .NET interop | {
"score": 5,
"source": [
"https://Stackoverflow.com/questions/156436",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5744/"
]
} |
156,438 | See title: what does it mean for a C++ function to be inline? | The function is placed in the code, rather than being called, similar to using macros (conceptually). This can improve speed (no function call), but causes code bloat (if the function is used 100 times, you now have 100 copies). You should note this does not force the compiler to make the function inline, and it will ignore you if it thinks its a bad idea. Similarly the compiler may decide to make normal functions inline for you. This also allows you to place the entire function in a header file, rather than implementing it in a cpp file (which you can't anyways, since then you get an unresolved external if it was declared inline, unless of course only that cpp file used it). | {
"score": 6,
"source": [
"https://Stackoverflow.com/questions/156438",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7545/"
]
} |
156,467 | I've been looking at F# recently, and while I'm not likely to leap the fence any time soon, it definitely highlights some areas where C# (or library support) could make life easier. In particular, I'm thinking about the pattern matching capability of F#, which allows a very rich syntax - much more expressive than the current switch/conditional C# equivalents. I won't try to give a direct example (my F# isn't up to it), but in short it allows: match by type (with full-coverage checking for discriminated unions) [note this also infers the type for the bound variable, giving member access etc] match by predicate combinations of the above (and possibly some other scenarios I'm not aware of) While it would be lovely for C# to eventually borrow [ahem] some of this richness, in the interim I've been looking at what can be done at runtime - for example, it is fairly easy to knock together some objects to allow: var getRentPrice = new Switch<Vehicle, int>() .Case<Motorcycle>(bike => 100 + bike.Cylinders * 10) // "bike" here is typed as Motorcycle .Case<Bicycle>(30) // returns a constant .Case<Car>(car => car.EngineType == EngineType.Diesel, car => 220 + car.Doors * 20) .Case<Car>(car => car.EngineType == EngineType.Gasoline, car => 200 + car.Doors * 20) .ElseThrow(); // or could use a Default(...) terminator where getRentPrice is a Func<Vehicle,int>. [note - maybe Switch/Case here is the wrong terms... but it shows the idea] To me, this is a lot clearer than the equivalent using repeated if/else, or a composite ternary conditional (which gets very messy for non-trivial expressions - brackets galore). It also avoids a lot of casting, and allows for simple extension (either directly or via extension methods) to more-specific matches, for example an InRange(...) match comparable to the VB Select...Case "x To y" usage. I'm just trying to gauge if people think there is much benefit from constructs like the above (in the absence of language support)? Note additionally that I've been playing with 3 variants of the above: a Func<TSource,TValue> version for evaluation - comparable to composite ternary conditional statements an Action<TSource> version - comparable to if/else if/else if/else if/else an Expression<Func<TSource,TValue>> version - as the first, but usable by arbitrary LINQ providers Additionally, using the Expression-based version enables Expression-tree re-writing, essentially inlining all the branches into a single composite conditional Expression, rather than using repeated invocation. I haven't checked recently, but in some early Entity Framework builds I seem to recall this being necessary, as it didn't like InvocationExpression very much. It also allows more efficient usage with LINQ-to-Objects, since it avoids repeated delegate invocations - tests show a match like the above (using the Expression form) performing at the same speed [marginally quicker, in fact] compared to the equivalent C# composite conditional statement. For completeness, the Func<...> based-version took 4 times as long as the C# conditional statement, but is still very quick and is unlikely to be a major bottleneck in most use-cases. I welcome any thoughts / input / critique / etc on the above (or on the possibilities of richer C# language support... here's hoping ;-p). | In C# 7, you can do: switch(shape){ case Circle c: WriteLine($"circle with radius {c.Radius}"); break; case Rectangle s when (s.Length == s.Height): WriteLine($"{s.Length} x {s.Height} square"); break; case Rectangle r: WriteLine($"{r.Length} x {r.Height} rectangle"); break; default: WriteLine("<unknown shape>"); break; case null: throw new ArgumentNullException(nameof(shape));} | {
"score": 6,
"source": [
"https://Stackoverflow.com/questions/156467",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/23354/"
]
} |
156,503 | How can I use JUnit idiomatically to test that some code throws an exception? While I can certainly do something like this: @Testpublic void testFooThrowsIndexOutOfBoundsException() { boolean thrown = false; try { foo.doStuff(); } catch (IndexOutOfBoundsException e) { thrown = true; } assertTrue(thrown);} I recall that there is an annotation or an Assert.xyz or something that is far less kludgy and far more in-the-spirit of JUnit for these sorts of situations. | It depends on the JUnit version and what assert libraries you use. For JUnit5 and 4.13 see answer If you use AssertJ or google-truth, see answer The original answer for JUnit <= 4.12 was: @Test(expected = IndexOutOfBoundsException.class) public void testIndexOutOfBoundsException() { ArrayList emptyList = new ArrayList(); Object o = emptyList.get(0); } Though answer has more options for JUnit <= 4.12. Reference: JUnit Test-FAQ | {
"score": 12,
"source": [
"https://Stackoverflow.com/questions/156503",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1666/"
]
} |
156,508 | Alright, I have been doing the following (variable names have been changed): FileInputStream fis = null;try{ fis = new FileInputStream(file); ... process ...}catch (IOException e){ ... handle error ...}finally{ if (fis != null) fis.close();} Recently, I started using FindBugs, which suggests that I am not properly closing streams. I decide to see if there's anything that can be done with a finally{} block, and then I see, oh yeah, close() can throw IOException. What are people supposed to do here? The Java libraries throw too many checked exceptions. | For Java 7 and above try-with-resources should be used: try (InputStream in = new FileInputStream(file)) { // TODO: work} catch (IOException e) { // TODO: handle error} If you're stuck on Java 6 or below... This pattern avoids mucking around with null : try { InputStream in = new FileInputStream(file); try { // TODO: work } finally { in.close(); } } catch (IOException e) { // TODO: error handling } For a more detail on how to effectively deal with close , read this blog post: Java: how not to make a mess of stream handling . It has more sample code, more depth and covers the pitfalls of wrapping close in a catch block. | {
"score": 7,
"source": [
"https://Stackoverflow.com/questions/156508",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/18049/"
]
} |
156,510 | Is there a way to increase the stack size of a Windows application at compile/link time with GCC? | IIRC, In GCC you can provide the --stack,[bytes] parameter to ld. E.g. gcc -Wl,--stack,16777216 -o file.exe file.c To have a stack of 16MiB, I think that the default size is 8MiB. | {
"score": 5,
"source": [
"https://Stackoverflow.com/questions/156510",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1597/"
]
} |
156,529 | What modes are the best? And any tips or tricks that make developing java in emacs a bit better. | For anything else than casual Java editing, many people recommend the Java Development Environment for Emacs. | {
"score": 5,
"source": [
"https://Stackoverflow.com/questions/156529",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/609/"
]
} |
156,575 | I'm looking for a good TraceListener for .Net that supports rolling over the log file based on size limits. Constraints Uses .Net built in Trace logging Independent class or binary that's not part of some gigantic library Allows rolling over a log file based on size | You could use Microsoft.VisualBasic.Logging.FileLogTraceListener , which comes built-in with the .NET Framework. Don't let the VisualBasic in the namespace scare you, you'll just have to reference the microsoft.visualbasic.dll assembly and it should work fine with C#. | {
"score": 5,
"source": [
"https://Stackoverflow.com/questions/156575",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/17222/"
]
} |
156,582 | I started using Sandcastle some time ago to generate a Documentation Website for one of our projects. It's working quite well but we've always only written documentation for classes, methods, properties (...) in our project and had completely separate documentation for the overall project and project parts/modules/namespaces. It would be nice if I could merge that documentation together and add respective documentation to the generated helper files but I can't figure out how to do it. Just adding comments to the namespace declaration doesn't seem to work (C#): /// <summary>/// My short namespace description/// </summary>namespace MyNamespace { ... } Does anyone know how to do this? I know it's possible somehow and it would be really nice to have... :) | Sandcastle also supports the ndoc-style namespace documentation, which allows you to stick the documentation in the source files: Simply create a non-public class called NamespaceDoc in the namespace you want to document, and the xml doc comment for that class will be used for the namespace. Adorn it with a [CompilerGenerated] attribute to prevent the class itself from showing up in the documentation. Example: namespace Some.Test{ /// <summary> /// The <see cref="Some.Test"/> namespace contains classes for .... /// </summary> [System.Runtime.CompilerServices.CompilerGenerated] class NamespaceDoc { }} The work item in SandCastle is located here. | {
"score": 7,
"source": [
"https://Stackoverflow.com/questions/156582",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5005/"
]
} |
156,641 | I have a table of users which has a username column consisting of a six digit number e.g 675381, I need to prepend a zero to each of these usernames e.g. 0675381 would be the final output of the previous example, is there a query that could handle this? | UPDATE Tablename SET Username = Concat('0', Username); | {
"score": 6,
"source": [
"https://Stackoverflow.com/questions/156641",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/13658/"
]
} |
156,650 | When reviewing, I sometimes encounter this kind of loop: i = beginwhile ( i != end ) { // ... do stuff if ( i == end-1 (the one-but-last element) ) { ... do other stuff } increment i} Then I ask the question: would you write this? i = beginmid = ( end - begin ) / 2 // (the middle element)while ( i != end ) { // ... do stuff if ( i > mid ) { ... do other stuff } increment i} In my opinion, this beats the intention of writing a loop: you loop because there is something common to be done for each of the elements. Using this construct, for some of the elements you do something different. So, I conclude, you need a separate loop for those elements: i = beginmid = ( end - begin ) / 2 //(the middle element)while ( i != mid ) { // ... do stuff increment i}while ( i != end ) { // ... do stuff // ... do other stuff increment i} Now I even saw a question on SO on how to write the if -clause in a nice way... And I got sad: something isn't right here. Am I wrong? If so, what's so good about cluttering the loop body with special cases, which you are aware of upfront, at coding time? | I don't think this question should be answered by a principle (e.g. "in a loop, treat every element equally"). Instead, you can look at two factors to evaluate if an implementation is good or bad: Runtime effectivity - does the compiled code run fast, or would it be faster doing it differently? Code maintainability - Is it easy (for another developer) to understand what is happening here? If it is faster and the code is more readable by doing everything in one loop, do it that way. If it is slower and less readable, do it another way. If it is faster and less readably, or slower but more readable, find out which of the factors matters more in your specific case, and then decide how to loop (or not to loop). | {
"score": 5,
"source": [
"https://Stackoverflow.com/questions/156650",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6610/"
]
} |
156,683 | I would like to know what of the many XSLT engines out there works well with Perl. I will use Apache (2.0) and Perl, and I want to obtain PDFs and XHTMLs. I'm new to this kind of projects so any comment or suggestion will be welcome. Thanks. Doing a simple search on Google I found a lot and I suppose that there are to many more. http://www.mod-xslt2.com/ http://xml.apache.org/xalan-j/ http://saxon.sourceforge.net/ http://www.dopscripts.com/xslt_parser.html Any comment on your experiences will be welcome. | First mistake - search on CPAN , not Google :) This throws up a bunch of results, but does rather highlight the problem of CPAN, that there's more than one solution, and it's not always clear which ones work, have been abandoned, are broken, slow or whatever. And disturbingly, the best answer (or at least, one of the best) comes up on page four of the results :( As other folks have suggested, XML::LibXSLT is robust and does the job: use XML::LibXSLT; use XML::LibXML; my $parser = XML::LibXML->new(); my $xslt = XML::LibXSLT->new(); my $source = $parser->parse_file('foo.xml'); my $style_doc = $parser->parse_file('bar.xsl'); my $stylesheet = $xslt->parse_stylesheet($style_doc); my $results = $stylesheet->transform($source); print $stylesheet->output_string($results); If you want to output results to a file then add this #create output fileopen(my $output_xml_file_name, '>', 'test.xml');print $output_xml_file_name "$results"; If you don't want to do anything fancy, though, there's XML::LibXSLT::Easy , which essentially just wraps the above in one method call (and does a bunch of clever stuff behind the scenes using Moose . Check the source for an education!). use XML::LibXSLT::Easy; my $p = XML::LibXSLT::Easy->new; my $output = $p->process( xml => "foo.xml", xsl => "foo.xsl" ); | {
"score": 6,
"source": [
"https://Stackoverflow.com/questions/156683",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/19689/"
]
} |
156,686 | How do I initialize an automatic download of a file in Internet Explorer? For example, in the download page, I want the download link to appear and a message: "If you download doesn't start automatically .... etc". The download should begin shortly after the page loads. In Firefox this is easy, you just need to include a meta tag in the header, <meta http-equiv="Refresh" content="n;url"> where n is the number of seconds and url is the download URL. This does not work in Internet Explorer. How do I make this work in Internet Explorer browsers? | SourceForge uses an <iframe> element with the src="" attribute pointing to the file to download. <iframe width="1" height="1" frameborder="0" src="[File location]"></iframe> (Side effect: no redirect, no JavaScript, original URL remains unchanged.) | {
"score": 8,
"source": [
"https://Stackoverflow.com/questions/156686",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4685/"
]
} |
156,688 | I have an error occuring frequently from our community server installation whenever the googlesitemap.ashx is traversed on a specific sectionID. I suspect that a username has been amended but the posts havn't recached to reflect this. Is there a way a can check the data integruity by performing a select statement on the database, alternatively is there a way to force the database to recache? | SourceForge uses an <iframe> element with the src="" attribute pointing to the file to download. <iframe width="1" height="1" frameborder="0" src="[File location]"></iframe> (Side effect: no redirect, no JavaScript, original URL remains unchanged.) | {
"score": 8,
"source": [
"https://Stackoverflow.com/questions/156688",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5055/"
]
} |
156,696 | Which browsers other than Firefox support Array.forEach()? Mozilla say it's an extension to the standard and I realise it's trivial to add to the array prototype, I'm just wondering what other browsers support it? | The JavaScript article of Wikipedia lists the JS versions by browser. forEach is part of JavaScript 1.6 . So it is supported indeed by most browsers, except Opera 9.02 (which I just tested). Opera 9.5 (which I just installed!) supports it, along with indexOf for Array. Surprisingly, it is not official. I don't see its support in the page ECMAScript support in Opera 9.5 . Perhaps it is an overlook or perhaps only a partial support they don't want to advertise. | {
"score": 5,
"source": [
"https://Stackoverflow.com/questions/156696",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/21030/"
]
} |
156,707 | In Eclipse 3.3.2, I would like to replace a character (say ',') by a new line in a file.What should I write in the "Replace with" box in order to do so ? EDIT : Many answers seems to be for Eclipse 3.4. Is there a solution for Eclipse 3.3.X ? | Check box 'Regular Expressions' and use '\R' in the 'Replace with' box It's a new feature introduced with Eclipse 3.4, See What's New in 3.4 | {
"score": 8,
"source": [
"https://Stackoverflow.com/questions/156707",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3122/"
]
} |
156,712 | If I hit a page which calls session_start() , how long would I have to wait before I get a new session ID when I refresh the page? | Check out php.ini the value set for session.gc_maxlifetime is the ID lifetime in seconds. I believe the default is 1440 seconds (24 mins) http://www.php.net/manual/en/session.configuration.php Edit: As some comments point out, the above is not entirely accurate. A wonderful explanation of why, and how to implement session lifetimes is available here: How do I expire a PHP session after 30 minutes? | {
"score": 7,
"source": [
"https://Stackoverflow.com/questions/156712",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1741868/"
]
} |
156,745 | I am using Eclipse for quite some time and I still haven't found how to configure the Problems View to display only the Errors and Warnings of interest. Is there an easy way to filter out warnings from a specific resource or from a specific path? For example, when I generate javadoc I get tons of irrelevant html warnings. Also, is there a way to change the maximum number of appearing warnings/errors? I am aware of the filters concept, but I am looking for some real life examples. What kind of filters or practices do other people use? Edit: I found the advice to filter on "On selected element and its children" to be the best one. I have one other issue however. If I have "a lot" of warnings or errors, only the first 100 appear. In the rare case I want to see all of them, how do I do it? | I feel that filtering "On selected element and its children" is the best mode of Problems view filter, because it allows you to very quickly narrow down the scope of reported problems: click on Working Set (in Package Explorer), and it shows all problems in all projects in the set; click on a project - and only problems in the selected project appear. Click on individual class (or package) - only problems in the selected class (or package) are shown. So you don't get distracted with problems unrelated to your task at hand. | {
"score": 7,
"source": [
"https://Stackoverflow.com/questions/156745",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/24054/"
]
} |
156,748 | How do I go about using HTTPS for some of the pages in my ASP.NET MVC based site? Steve Sanderson has a pretty good tutorial on how to do this in a DRY way on Preview 4 at: http://blog.codeville.net/2008/08/05/adding-httpsssl-support-to-aspnet-mvc-routing/ Is there a better / updated way with Preview 5?, | If you are using ASP.NET MVC 2 Preview 2 or higher , you can now simply use: [RequireHttps]public ActionResult Login(){ return View();} Though, the order parameter is worth noting, as mentioned here . | {
"score": 8,
"source": [
"https://Stackoverflow.com/questions/156748",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/13238/"
]
} |
156,767 | When verbally talking about methods, I'm never sure whether to use the word argument or parameter or something else. Either way the other people know what I mean, but what's correct, and what's the history of the terms? I'm a C# programmer, but I also wonder whether people use different terms in different languages. For the record I'm self-taught without a background in Computer Science. (Please don't tell me to read Code Complete because I'm asking this for the benefit of other people who don't already have a copy of Steve McConnell 's marvellous book.) Summary The general consensus seems to be that it's OK to use these terms interchangeably in a team environment. Except perhaps when you're defining the precise terminology; then you can also use " formal argument/parameter" and " actual argument/parameter" to disambiguate. | A parameter is a variable in a method definition. When a method is called, the arguments are the data you pass into the method's parameters. public void MyMethod(string myParam) { }...string myArg1 = "this is my argument";myClass.MyMethod(myArg1); | {
"score": 11,
"source": [
"https://Stackoverflow.com/questions/156767",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5351/"
]
} |
156,779 | I've written a simple SessionItem management class to handle all those pesky null checks and insert a default value if none exists. Here is my GetItem method: public static T GetItem<T>(string key, Func<T> defaultValue){ if (HttpContext.Current.Session[key] == null) { HttpContext.Current.Session[key] = defaultValue.Invoke(); } return (T)HttpContext.Current.Session[key];} Now, how do I actually use this, passing in the Func<T> as an inline method parameter? | Since that is a func, a lambda would be the simplest way: Foo foo = GetItem<Foo>("abc", () => new Foo("blah")); Where [new Foo("blah")] is the func that is invoked as a default. You could also simplify to: return ((T)HttpContext.Current.Session[key]) ?? defaultValue(); Where ?? is the null-coalescing operator - if the first arg is non-null, it is returned; otherwise the right hand is evaluated and returned (so defaultValue() isn't invoked unless the item is null). Finally, if you just want to use the default constructor, then you could add a "new()" constraint: public static T GetItem<T>(string key) where T : new(){ return ((T)HttpContext.Current.Session[key]) ?? new T();} This is still lazy - the new() is only used if the item was null. | {
"score": 5,
"source": [
"https://Stackoverflow.com/questions/156779",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/192/"
]
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.