Prompt
stringlengths
10
31k
Chosen
stringlengths
3
29.4k
Rejected
stringlengths
3
51.1k
Title
stringlengths
9
150
Tags
listlengths
3
7
**The original question is below, but I changed the title because I think it will be easier to find others with the same doubt. In the end, a XHTML document is a XML document.** It's a beginner question, but I would like to know which do you think is the best library for parsing XHTML documents in PHP5? I have genera...
Just to clear up the confusion here. PHP has a number of XML libraries, because php4 didn't have very good options in that direction. From PHP5, you have the choice between [SimpleXml](http://docs.php.net/manual/en/book.simplexml.php), [DOM](http://docs.php.net/manual/en/book.dom.php) and the [sax-based expat parser](h...
You could use [SimpleXML](https://www.php.net/simplexml), which is included in a default PHP install. This extensions offers easy object-oriented access to XML-structures. There's also [DOM XML](http://nl2.php.net/domxml). A "downside" to this extension is that it is a bit harder to use and that it is not included by ...
What's the difference between the different XML parsing libraries in PHP5?
[ "", "php", "xml", "parsing", "xhtml", "" ]
Is there a way to get Visual Studio 2008 to do matching brace highlighting for Javascript? If there is no way to do it in Studio, can it be done using ReSharper? Thanks!!
Note that Visual Studio will still find a matching brace in JavaScript via Ctrl + ].
Here is an extension for VS2010 that will do just what you desire. And it's free! <http://visualstudiogallery.msdn.microsoft.com/872d27ee-38c7-4a97-98dc-0d8a431cc2ed>
Brace highlighting in Visual Studio for Javascript?
[ "", "javascript", "visual-studio-2008", "ide", "resharper", "" ]
I need to pad the output of an integer to a given length. For example, with a length of 4 digits, the output of the integer 4 is "0004" instead of "4". How can I do this in C# 2.0?
Use the string.Format command. ``` output = String.Format("{0:0000}", intVariable); ``` More details: <http://msdn.microsoft.com/en-us/library/fht0f5be.aspx>
i think it was: intVal.ToString( "####" ); but there is some [useful documentation here](http://msdn.microsoft.com/en-us/library/8wch342y.aspx)
Integer formatting, padding to a given length
[ "", "c#", "string", "integer", "format", "" ]
I need to tweak some variables (only in a development setting) without having to restart IIS or anything (so I assume Web.Config is the wrong place to put them). Where is the easiest place to put about 500 config settings that have to be read for every request and written to, like I said, while IIS is running? **EDIT*...
In a database?
500 Config Settings to be read for every request? I'd put them in a database so they can be indexed and cached. A separate XML or data file would also most likely be cached in memory by the web server, but still wouldn't provide the performance an indexed database table could. But it depends on how you are accessing th...
Best way to have a live readable config file in Asp.Net
[ "", "c#", "asp.net", "configuration-files", "" ]
I am trying to upload files using the FileReference class. Files >2MB all work correctly but files <2MB cause this error: > "java.io.IOException: Corrupt form data: premature ending" On the server I am using the com.oreilly.servlet package to handle the request. I have used this package many times to successfully ha...
It seems that there is a bug that exists when using com.orielly.servlet.MultipartRequest class and the org.apache.struts2.dispatcher.ActionContextCleanUp filter together. This is what was causing small file uploads to fail.
<http://www.servlets.com/cos/faq.html> ***Why when using com.oreilly.servlet.MultipartRequest or MultipartParser do large uploads fail?*** The classes themselves were specifically designed to have no maximum upload size limit (unlike most other file upload utilities), but for your server's protection the constructor a...
Corrupt form data: premature ending
[ "", "java", "actionscript-3", "apache-flex", "" ]
I'm using the javax.mail system, and having problems with "Invalid Address" exceptions. Here's the basics of the code: ``` // Get system properties Properties props = System.getProperties(); // Setup mail server props.put("mail.smtp.host", m_sending_host); // Get session Session session = Ses...
--Update: problem with authentication. Ok, here's what I've discovered was going on. When receiving e-mail, the code above correctly sets up authentication and the Authenticator.getPasswordAuthentication() callback is actually invoked. Not so when sending e-mail. You have to do a bit more. Add this: ``` // Setup mai...
I would change the call to InternetAddress to use the "strict" interpretation and see if you get further errors on the addresses you are having trouble with. ``` message.addRecipient(Message.RecipientType.TO, new InternetAddress(vcea.get(i).emailaddr, true )); // ...
Getting Invalid Address with javax.mail when the addresses are fine
[ "", "java", "email", "" ]
Is there anything out there freeware or commercial that can facilitate analysis of memory usage by a PHP application? I know xdebug can produce trace files that shows memory usage by function call but without a graphical tool the data is hard to interpret. Ideally I would like to be able to view not only total memory ...
As you probably know, Xdebug dropped the memory profiling support since the 2.\* version. Please search for the "removed functions" string here: <http://www.xdebug.org/updates.php> > **Removed functions** > > Removed support for Memory profiling as that didn't work properly. So I've tried another tool and it worked w...
I came across the same issue recently, couldn't find any specific tools unfortunately. But something that helped was to output the xdebug trace in human readable format with mem deltas enabled (an INI setting, xdebug.show\_mem\_deltas or something I think?). Then run sort (if you are on \*nix) on the output: ``` sort...
Tools to visually analyze memory usage of a PHP app
[ "", "php", "memory-management", "profiling", "" ]
How can I launch an application using C#? Requirements: Must work on [Windows XP](http://en.wikipedia.org/wiki/Windows_XP) and [Windows Vista](http://en.wikipedia.org/wiki/Windows_Vista). I have seen a sample from DinnerNow.net sampler that only works in Windows Vista.
Use [`System.Diagnostics.Process.Start()`](http://msdn.microsoft.com/en-us/library/system.diagnostics.process.start.aspx) method. Check out [this article](http://www.codeproject.com/KB/cs/start_an_external_app.aspx) on how to use it. ``` Process.Start("notepad", "readme.txt"); string winpath = Environment.GetEnviron...
Here's a snippet of helpful code: ``` using System.Diagnostics; // Prepare the process to run ProcessStartInfo start = new ProcessStartInfo(); // Enter in the command line arguments, everything you would enter after the executable name itself start.Arguments = arguments; // Enter the executable to run, including the...
Launching an application (.EXE) from C#?
[ "", "c#", ".net", "windows-vista", "windows-xp", "" ]
Returning to WinForms in VS2008 after a long time.. Tinkering with a OOD problem in VS2008 Express Edition. I need some controls to be "display only" widgets. The user should not be able to change the value of these controls... the widgets are updated by a periodic update tick event. I vaguely remember there being a R...
For some typical winforms controls: <http://jquiz.wordpress.com/2007/05/29/c-winforms-readonly-controls/> This is also a good tip to preserve the appearance: ``` Color clr = textBox1.BackColor; textBox1.ReadOnly = true; textBox1.BackColor = clr; ```
To make the forms control Readonly instantly on one click do use the following peice of Code : ``` public void LockControlValues(System.Windows.Forms.Control Container) { try { foreach (Control ctrl in Container.Controls) { if (ctrl.GetType() == typeof(Te...
How do I make a Windows Forms control readonly?
[ "", "c#", ".net", "winforms", "" ]
OK, so I've read through various posts about teaching beginner's to program, and there were some helpful things I will look at more closely. But what I want to know is whether there are any effective tools out there to teach a kid *Java* specifically? I want to teach him Java specifically because (a) with my strong ba...
Just make the learning fun and all the rest will follow ! Amazingly Scala might be the easiest language if you try [Kojo](http://www.kogics.net/sf:kojo) (Scala is better Java, you have access to all Java libraries of course)
You may find some inspiration in this project: [Teaching Kids Programming: Even Younger Kids Can Learn Java](http://java.sys-con.com/node/44575) > Java Programming for Kids, Parents and Grandparents. You can find here at the [faratasystems web site](http://www.faratasystems.com/?page_id=69) (direct link [here](http:...
What's a good way to teach my son to program Java
[ "", "java", "" ]
Programming is learned by writing programs. But code reading is said to be another good way of learning. I would like to improve my unit-testing skills by reading, examining real-world code. Could you recommend any open source projects where the source is extensively tested with unit tests? I'm interested in code writ...
AFAIK C++ Boost libraries - <http://boost.org/> - have broadly covered code base, and a policy that every new piece of code must have unit tests with it. Might be worth checking.
The [Chromium](http://code.google.com/chromium/) project.
Could you recommend any open source projects where the source is extensively tested with unit tests?
[ "", "c++", "unit-testing", "open-source", "" ]
I have written a script that goes through a bunch of files and snips out a portion of the files for further processing. The script creates a new directory and creates new files for each snip that is taken out. I have to now evaluate each of the files that were created to see if it is what I needed. The script also crea...
Well I finally found an answer that achieved what I wanted-I did not want to learn a new language-Python is hard enough given my lack or experience ``` def OnDelete(self, event): assert self.current, "invalid delete operation" try: os.remove(os.path.join(self.cwd, self.current)) ```
You could make this even simpler by making it all happen in one main page. Instead of having a list of hyperlinks, just have the main page have one frame that loads one of the autocreated pages in it. Put a couple of buttons at the bottom - a "Keep this page" and a "Delete this page." When you click either button, the ...
Can I Use Python to Make a Delete Button in a 'web page'
[ "", "python", "web-applications", "browser", "" ]
I created a list of lists: ``` >>> xs = [[1] * 4] * 3 >>> print(xs) [[1, 1, 1, 1], [1, 1, 1, 1], [1, 1, 1, 1]] ``` Then, I changed one of the innermost values: ``` >>> xs[0][0] = 5 >>> print(xs) [[5, 1, 1, 1], [5, 1, 1, 1], [5, 1, 1, 1]] ``` Why did every first element of each sublist change to `5`? --- See also:...
When you write `[x]*3` you get, essentially, the list `[x, x, x]`. That is, a list with 3 references to the same `x`. When you then modify this single `x` it is visible via all three references to it: ``` x = [1] * 4 xs = [x] * 3 print(f"id(x): {id(x)}") # id(x): 140560897920048 print( f"id(xs[0]): {id(xs[0])}\n" ...
``` size = 3 matrix_surprise = [[0] * size] * size matrix = [[0]*size for _ in range(size)] ``` [Live visualization](http://pythontutor.com/visualize.html#code=size%20%3D%203%0Amatrix_surprise%20%3D%20%5B%5B0%5D%20*%20size%5D%20*%20size%0Amatrix%20%3D%20%5B%5B0%5D*size%20for%20_%20in%20range%28size%29%5D&cumulative=fa...
List of lists changes reflected across sublists unexpectedly
[ "", "python", "list", "nested-lists", "mutable", "" ]
Is std::string size() a O(1) operation? The implementation of STL I'm using is the one built into VC++
If you're asking if MSVC's implementation of string::size() has constant complexity, then the answer is yes. But [Don Wakefield](https://stackoverflow.com/questions/256033/is-stdstring-size-a-o1-operation#256081) mentioned Table 65 in 23.1 of the C++ Standard where it says that the complexity of `size()` should follow ...
Yes, std::string::size() is O(1).
Is std::string size() a O(1) operation?
[ "", "c++", "visual-c++", "stl", "stdstring", "" ]
I have a base class with an optional virtual function ``` class Base { virtual void OnlyImplementThisSometimes(int x) {} }; ``` When I compile this I get a warning about the unused param x. Is there some other way I should have implemented the virtual function? I have re-written it like this: ``` class Base { ...
Ignoring the design issues you can get around the compiler warning about an unused variable by omitting the variable name, for example: ``` virtual void OnlyImplementThisSometimes(int ) { } ``` Mistakenly implementing the wrong method signature when trying to override the virtual function is just something you need t...
We define a macro `_unused` as: ``` #define _unused(x) ((void)x) ``` Then define the function as: ``` virtual void OnlyImplementThisSometimes(int x) { _unused( x );} ``` This not only keeps the compiler from complaining, but makes it obvious to anyone maintaining the code that you haven't forgotten about x -- you a...
Are non-pure virtual functions with parameters bad practice?
[ "", "c++", "polymorphism", "" ]
What are you using for binding XML to Java? JAXB, Castor, and XMLBeans are some of the available choices. The comparisons that I've seen are all three or four years old. I'm open to other suggestions. Marshalling / unmarshalling performance and ease of use are of particular interest. Clarification: I'd like to see not...
[JiBX](http://www.jibx.org). Previously I used [Castor XML](http://www.castor.org/xml-framework.html), but JiBX proved to be significantly better, particularly in terms of performance (a straight port of some application code from Castor XML to JiBX made it 9x faster). I also found the mapping format for JiBX to be mor...
If you want to make an informed decision you need to be clear why you are translating between XML and java objects. The reason being that the different technologies in this space try to solve different problems. The different tools fall into two categories: 1. XML data binding - refers to the process of representing t...
Java XML Binding
[ "", "java", "xml", "jaxb", "castor", "xmlbeans", "" ]
I'm using a `std::map` (VC++ implementation) and it's a little slow for lookups via the map's find method. The key type is `std::string`. Can I increase the performance of this `std::map` lookup via a custom key compare override for the map? For example, maybe `std::string` < compare doesn't take into consideration a...
First, turn off all the profiling and DEBUG switches. These can slow down STL immensely. If that's not it, part of the problem may be that your strings are identical for the first 80-90% of the string. This isn't bad for map, necessarily, but it is for string comparisons. If this is the case, your search can take much...
As [Even](https://stackoverflow.com/questions/256038/how-can-i-increase-the-performance-in-a-map-lookup-with-key-type-stdstring#256052) said the operator used in a `set` is `<` not `==`. If you don't care about the order of the strings in your `set` you can pass the `set` a custom comparator that performs better than ...
How can I increase the performance in a map lookup with key type std::string?
[ "", "c++", "dictionary", "optimization", "visual-c++", "stdmap", "" ]
Is it generally better to run functions on the webserver, or in the database? Example: ``` INSERT INTO example (hash) VALUE (MD5('hello')) ``` or ``` INSERT INTO example (hash) VALUE ('5d41402abc4b2a76b9719d911017c592') ``` Ok so that's a really trivial example, but for scalability when a site grows to multiple we...
I try to think of the database as the place to persist stuff only, and put all abstraction code elsewhere. Database expressions are complex enough already without adding functions to them. Also, the query optimizer will trip over any expressions with functions if you should ever end up wanting to do something like "SE...
I try to use functions in my scripting language whenever calculations like that are required. I keep my SQL function useage down to a minimum, for a number of reasons. The primary reason is that my one SQL database is responsible for hosting multiple websites. If the SQL server were to get bogged down with requests fr...
Functions in MySQL or PHP
[ "", "php", "mysql", "performance", "" ]
I'm writing a lightweight XML editor, and in cases where the user's input is not well formed, I would like to indicate to the user where the problem is, or at least where the first problem is. Does anyone know of an existing algorithm for this? If looking at code helps, if I could fill in the FindIndexOfInvalidXml meth...
I'd probably just cheat. :) This will get you a line number and position: ``` string s = "<?xml version=\"1.0\"?><tag1><tag2>Some text.</taagg2></tag1>"; System.Xml.XmlDocument doc = new System.Xml.XmlDocument(); try { doc.LoadXml(s); } catch(System.Xml.XmlException ex) { MessageBox.Show(ex.LineNumber.ToStrin...
Unless this is an academic exercise, I think that writing your own XML parser is probably not the best way to go about this. I would probably check out the [XmlDocument class](http://msdn.microsoft.com/en-us/library/system.xml.xmldocument.aspx) within the System.Xml namespace and try/catch [exceptions](http://msdn.micr...
How can I find the position where a string is malformed XML (in C#)?
[ "", "c#", "xml", "algorithm", "" ]
How can i generate bytecode (Byte[]) from a String at runtime, without using a "javac" process or something of this sort? is there a simple way of calling the compiler like that? later addition: I chose to [accept the solution that actually best fits **my** situation](https://stackoverflow.com/questions/200833/when-s...
You might find something like rhino or groovy more useful in practice.
JDK6 has a [Java compiler API](http://www.java2s.com/Code/Java/JDK-6/CompilingfromMemory.htm). However, it's not necessarily very easy to use. A quick google pulled up [this example usage](http://www.java2s.com/Code/Java/JDK-6/CompilingfromMemory.htm).
java in-memory compilation
[ "", "java", "runtime", "compilation", "" ]
I'm trying to create Excel 2007 Documents programmatically. Now, there are two ways I've found: * Manually creating the XML, as outlined in [this post](https://stackoverflow.com/questions/150339/generating-an-excel-file-in-aspnet#150368) * Using a Third Party Library like [ExcelPackage](http://www.codeplex.com/ExcelPa...
You could try using the [Office Open XML SDK](http://www.microsoft.com/downloads/details.aspx?FamilyID=c6e744e5-36e9-45f5-8d8c-331df206e0d0&DisplayLang=en). This will allow you to create Excel files in memory using say a `MemoryStream` and much more easily than generating all the XML by hand. As Brian Kim pointed out,...
I'm just generating HTML table, which can be opened by Excel: ``` <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd"> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> <title>Wnioski</title> <style type="text/css"> <!-- br { mso-data-placement: same-cel...
Programmatically creating Excel 2007 Sheets
[ "", "c#", ".net", "excel", "" ]
I have noticed that my particular instance of Trac is not running quickly and has big lags. This is at the very onset of a project, so not much is in Trac (except for plugins and code loaded into SVN). **Setup Info:** This is via a SELinux system hosted by WebFaction. It is behind Apache, and connections are over SSL....
It's hard to say without knowing more about your setup, but one easy win is to make sure that Trac is running in something like `mod_python`, which keeps the Python runtime in memory. Otherwise, every HTTP request will cause Python to run, import all the modules, and then finally handle the request. Using `mod_python` ...
We've had the best luck with FastCGI. Another critical factor was to only use `https` for authentication but use `http` for all other traffic -- I was really surprised how much that made a difference.
How to improve Trac's performance
[ "", "python", "performance", "trac", "" ]
I have a HTML file that has code similar to the following. ``` <table> <tr> <td id="MyCell">Hello World</td> </tr> </table> ``` I am using javascript like the following to get the value ``` document.getElementById(cell2.Element.id).innerText ``` This returns the text "Hello World" with only 1 space bet...
HTML is white space insensititive which means your DOM is too. Would wrapping your "Hello World" in **pre** block work at all?
In HTML,any spaces >1 are ignored, both in displaying text and in retrieving it via the DOM. The only guaranteed way to maintain spaces it to use a non-breaking space `&nbsp;`.
Javascript Removing Whitespace When It Shouldn't?
[ "", "javascript", "dom", "whitespace", "innerhtml", "" ]
I noticed that writing to a file, closing it and moving it to destination place randomly fails on Vista. Specifically, MoveFileEx() would return `ERROR_ACCESS_DENIED` for no apparent reason. This happens on Vista SP1 at least (32 bit). Does not happen on XP SP3. Found [this thread](http://groups.google.com/group/micro...
I suggest you use [Process Monitor](http://technet.microsoft.com/en-us/sysinternals/bb896645.aspx) *(edit: the artist formerly known as FileMon)* to watch and see which application exactly is getting in the way. It can show you the entire trace of file system calls made on your machine. *(edit: thanks to @moocha for t...
I'd say it's either your anti-virus or Windows Indexing messing with the file at the same moment. Can you run the same test without an anti-virus. Then run it again making sure the temp file is created somewhere not indexed by Windows Search?
Random MoveFileEx failures on Vista
[ "", "c++", "windows", "winapi", "windows-vista", "" ]
In C and C++ you can tell the compiler that a number is a 'long' by putting an 'l' at the end of the number. e.g long x = 0l; How can I tell the C# compiler that a number is a byte?
According to the [C# language specification](http://msdn.microsoft.com/en-us/library/aa664674(VS.71).aspx) there is no way to specify a byte literal. You'll have to cast down to byte in order to get a byte. Your best bet is probably to specify in hex and cast down, like this: ``` byte b = (byte) 0x10; ```
``` byte b = (byte) 123; ``` even though ``` byte b = 123; ``` does the same thing. If you have a variable: ``` int a = 42; byte b = (byte) a; ```
How to cast a number to a byte?
[ "", "c#", "casting", "" ]
How can one programmatically sort a union query when pulling data from two tables? For example, ``` SELECT table1.field1 FROM table1 ORDER BY table1.field1 UNION SELECT table2.field1 FROM table2 ORDER BY table2.field1 ``` Throws an exception Note: this is being attempted on MS Access Jet database engine
Sometimes you need to have the `ORDER BY` in each of the sections that need to be combined with `UNION`. In this case ``` SELECT * FROM ( SELECT table1.field1 FROM table1 ORDER BY table1.field1 ) DUMMY_ALIAS1 UNION ALL SELECT * FROM ( SELECT table2.field1 FROM table2 ORDER BY table2.field1 ) DUMMY_ALIAS2 ```
``` SELECT field1 FROM table1 UNION SELECT field1 FROM table2 ORDER BY field1 ```
SQL Query - Using Order By in UNION
[ "", "sql", "ms-access", "sorting", "sql-order-by", "union", "" ]
The [.NET coding standards PDF from SubMain](http://submain.com/landing/codeit.right/?utm_campaign=codeit.right&utm_medium=textad&utm_source=stackoverflow) that have started showing up in the "Sponsored By" area seems to indicate that properties are only appropriate for logical data members (see pages 34-35 of the docu...
They seem sound, and basically in line with MSDN member design guidelines: <http://msdn.microsoft.com/en-us/library/ms229059.aspx> One point that people sometimes seem to forget (\*) is that callers should be able to set properties in any order. Particularly important for classes that support designers, as you can't ...
Those are interesting guidelines, and I agree with them. It's interesting in that they are setting the rules based on "everything is a property except the following". That said, they are good guidelines for avoiding problems by defining something as a property that can cause issues later. At the end of the day a prope...
What guidelines are appropriate for determining when to implement a class member as a property versus a method?
[ "", "c#", ".net", "" ]
I'd like to make sure that a thread is moved to a specific CPU core and can never be moved from it by the scheduler. There's a `SetThreadAffinityMask()` call but there's no `GetThreadAffinityMask()`. The reason I need this is because high resolution timers will get messed up if the scheduler moves that thread to anot...
You should probably just use SetThreadAffinityMask and trust that it is working. [MSDN](http://msdn.microsoft.com/en-us/library/ms684251.aspx)
If you could call a function that returns a number indicating what CPU the thread is running on, without using affinity, the answer would often be wrong as soon as the function returned. So checking the mask returned by `SetThreadAffinityMask()` is as close as you're going to get, outside of kernel code running at elev...
On Win32 how do you move a thread to another CPU core?
[ "", "c++", "c", "multithreading", "winapi", "multicore", "" ]
I went to school for programming years ago and when I got out I found a job in system administration and that is the direction my career took. I'd like to get back into development of some sort and have been 'playing' with C# and ASP.NET, but I've been hearing lots of buzz for other 'new' languages (by new I mean that ...
You should learn at least 1 compiled language (like C# or Java) and 1 Script Language (Python, Ruby, etc). This is usually enough to help most developers succeed at what they do, regardless of the age of the language. As for new vs old, I'd stick with C# for now as it's pretty popular. Learning a new language wouldn't...
C. Seriously, learn C. If you don't run screaming for the hills pulling your hair out then you're cut out to be a developer. Note that I'm not saying that people who don't know C aren't developers (Jeff, the founder of this site, doesn't know C and he's doing just fine) but C will introduce you to a lot of the [less...
What to learn first?
[ "", "c#", "asp.net", "ruby", "f#", "" ]
I'm writing a CESetup.dll for a Windows Mobile app. It must be unmanaged, which I have little experience with. So I'm unsure of whether I should free the memory I allocate and how I do it. Here's the function I've written: ``` Uninstall_Init( HWND hwndParent, LPCTSTR pszInstallDir ) { LPTST...
I think you want to use this: ``` delete [] folderPath; ``` It looks like you're allocating an array of TCHARs, which makes sense since it's a string. When you allocate an array, you must delete using the array delete operator (which you get by including the brackets in the delete statement). I'm pretty sure you'll g...
There is a common misperception I have seen with people who are unused to C/C++ programming - when they see a function with a pointer parameter, they think the variable must be allocated with *new*. That is not the case, a local variable is suitable and preferred, since you don't have to worry about its lifetime. You ...
Freeing memory on the heap. Should I and how?
[ "", "c++", "winapi", "memory-management", "windows-ce", "" ]
I have a question at [SO](https://stackoverflow.com/questions/150038/how-to-wire-a-middle-tier-of-objects-to-a-data-tier-consisting-of-a-dataset#151255) asking how to wire a middle tier to a DataSet. I put up an answer showing what I had come up with, but I am not happy with the tight coupling. I have just started to ...
IMO; DataSets are evil. They are, and should only be used as, offline databases. Nothing more, IMO. However, what you do in your Data Access Layer (DAL) should not really impact your Business layer (BL). I'd just use objects (use interfaces) between them (IList) and then use an interface to define your DAL (IRepository...
You need IOC (inversion of control) and mock objects. I encourage you to watch [dnrTV episode 126](http://www.dnrtv.com/default.aspx?showNum=126) with James Kovacs. He demonstrates exactly what you are looking for.
How to decouple a middle tier and a dataset to allow for unit testing?
[ "", "c#", ".net", "integration-testing", "" ]
For my C# RichTextBox, I want to programmatically do the same thing as clicking the up arrow at the top of a vertical scroll bar, which moves the RichTextBox display up by one line. What is the code for this? Thanks!
Here's what I do: ``` using System.Runtime.InteropServices; [DllImport("user32.dll")] static extern int SendMessage(IntPtr hWnd, uint wMsg, UIntPtr wParam, IntPtr lParam); ``` then call: ``` SendMessage(myRichTextBox.Handle, (uint)0x00B6, (UIntPtr)0, (IntPtr)(-1)); ``` Seems to work...
For future reference the EM\_LINESCROLL message is what you send to any multi-line edit control to set the scroll position. You can scroll vertically or horizontally. See [MSDN](http://msdn.microsoft.com/en-us/library/bb761615(VS.85).aspx) for details. You can also use the Rich Edit Selection method, where you set the...
How to move scroll bar up by one line? (In C# RichTextBox)
[ "", "c#", "richtextbox", "scrollbar", "" ]
I have a database with DateTime fields that are currently stored in local time. An upcoming project will require all these dates to be converted to universal time. Rather than writing a c# app to convert these times to universal time, I'd rather use available sqlserver/sql features to accurately convert these dates to ...
A User Defined Function would allow you to write an SQL query that looks like this: ``` SELECT toUTC([MyDateColumn], [MyTimeZoneColumn]) FROM [MyTable] ``` Then you get universal times back from the server without a lot of ugly syntax in the query itself. Now you could build the UDF for this with regular SQL similar ...
SQL Doesn't have anything built in for this. Two ways would be the `C# application` (you mentioned you don't want) or writing a really complicated update statement with something like: ``` UtcDate = DATEADD(hour, CASE WHEN OriginalDate BETWEEN x AND y THEN 4 WHEN OriginalDate BETWEEN x2 AND y2 THEN 5 ... END, Origin...
How to convert a SqlServer DateTime to universal time using SQL
[ "", "sql", "sql-server", "database", "" ]
I have several `std::vector`, all of the same length. I want to sort one of these vectors, and apply the same transformation to all of the other vectors. Is there a neat way of doing this? (preferably using the STL or Boost)? Some of the vectors hold `int`s and some of them `std::string`s. Pseudo code: ``` std::vecto...
friol's approach is good when coupled with yours. First, build a vector consisting of the numbers 1…*n*, along with the elements from the vector dictating the sorting order: ``` typedef vector<int>::const_iterator myiter; vector<pair<size_t, myiter> > order(Index.size()); size_t n = 0; for (myiter it = Index.begin()...
``` typedef std::vector<int> int_vec_t; typedef std::vector<std::string> str_vec_t; typedef std::vector<size_t> index_vec_t; class SequenceGen { public: SequenceGen (int start = 0) : current(start) { } int operator() () { return current++; } private: int current; }; class Comp{ int_vec_t& _v; pu...
How do I sort a std::vector by the values of a different std::vector?
[ "", "c++", "stl", "boost", "vector", "sorting", "" ]
This code always works, even in different browsers: ``` function fooCheck() { alert(internalFoo()); // We are using internalFoo() here... return internalFoo(); // And here, even though it has not been defined... function internalFoo() { return true; } //...until here! } fooCheck(); ``` I could not find a sin...
The `function` declaration is magic and causes its identifier to be bound before anything in its code-block\* is executed. This differs from an assignment with a `function` expression, which is evaluated in normal top-down order. If you changed the example to say: ``` var internalFoo = function() { return true; }; `...
It is called HOISTING - Invoking (calling) a function before it has been defined. Two different types of function that I want to write about are: Expression Functions & Declaration Functions 1. Expression Functions: Function expressions can be stored in a variable so they do not need function names. They will al...
Why can I use a function before it's defined in JavaScript?
[ "", "javascript", "function", "" ]
In class, we are all 'studying' databases, and everyone is using Access. Bored with this, I am trying to do what the rest of the class is doing, but with raw SQL commands with MySQL instead of using Access. I have managed to create databases and tables, but now how do I make a relationship between two tables? If I ha...
If the tables are innodb you can create it like this: ``` CREATE TABLE accounts( account_id INT NOT NULL AUTO_INCREMENT, customer_id INT( 4 ) NOT NULL , account_type ENUM( 'savings', 'credit' ) NOT NULL, balance FLOAT( 9 ) NOT NULL, PRIMARY KEY ( account_id ), FOREIGN KEY (customer_id) REFEREN...
as ehogue said, put this in your CREATE TABLE ``` FOREIGN KEY (customer_id) REFERENCES customers(customer_id) ``` alternatively, if you already have the table created, use an ALTER TABLE command: ``` ALTER TABLE `accounts` ADD CONSTRAINT `FK_myKey` FOREIGN KEY (`customer_id`) REFERENCES `customers` (`customer_id`)...
How to create relationships in MySQL
[ "", "mysql", "sql", "foreign-keys", "relational-database", "" ]
I'd like to set up a large linear programming model to solve an interesting problem. I would be most comfortable in Java. What tools/libraries are available?
I used [lp\_solve](http://lpsolve.sourceforge.net/5.5/) with success. It looks like there is a native Java API, but I've only used the text file interface. It supports the semi-standard MPS and LP file formats, which I found more convenient for trying out different solvers (such as [glpsol](http://www.gnu.org/software/...
There were several suggestions from an [earlier question that I posted](https://stackoverflow.com/questions/143020/mathematical-optimization-library-for-java-free-or-open-source-recommendations): * [CPLEX](http://www.ilog.com/products/cplex) * [Dash](http://www.dashoptimization.com/home/cgi-bin/example.pl#bcl_java) * ...
Linear Programming Tool/Libraries for Java
[ "", "java", "linear-programming", "" ]
I am getting the following error when I try to call a stored procedure that contains a SELECT Statement: > The operation is not valid for the state of the transaction Here is the structure of my calls: ``` public void MyAddUpdateMethod() { using (TransactionScope Scope = new TransactionScope(TransactionScopeOpt...
After doing some research, it seems I cannot have two connections opened to the same database with the TransactionScope block. I needed to modify my code to look like this: ``` public void MyAddUpdateMethod() { using (TransactionScope Scope = new TransactionScope(TransactionScopeOption.RequiresNew)) { ...
When I encountered this exception, there was an InnerException "Transaction Timeout". Since this was during a debug session, when I halted my code for some time inside the TransactionScope, I chose to ignore this issue. When this specific exception with a timeout appears in deployed code, I think that the following se...
"The operation is not valid for the state of the transaction" error and transaction scope
[ "", "c#", ".net", "sql-server", "transactions", "transactionscope", "" ]
SQL Server (2005/2008) Each of the below statements have the same result. Does anyone know if one outperforms the other? ``` insert into SOMETABLE values ('FieldOneValue','FieldTwoValue',3,4.55,'10/10/2008 16:42:00.000') insert into SOMETABLE select 'FieldOneValue','FieldTwoValue',3,4.55,'10/10/2008 16:42:00.0...
I just tested this. 5 million iterations of both approaches on two sets of hardware, one a server with 16GB RAM, one a notebook with 1GB. Result: They appear to be the same. The query plans for these are the same, and the performance differential is statistically insignificant.
i think, based on this question, you are to the point of [premature optimization](http://en.wikipedia.org/wiki/Code_optimization#When_to_optimize). i'd stick to the standard insert () values () if you are just inserting 1 record and let the Sql Server team make it the most performant.
Insert Into: Is one syntax more optimal or is it preference?
[ "", "sql", "performance", "optimization", "insert", "" ]
Imagine that you want to develop a non-trivial end-user desktop (not web) application in Python. What is the best way to structure the project's folder hierarchy? Desirable features are ease of maintenance, IDE-friendliness, suitability for source control branching/merging, and easy generation of install packages. In...
Doesn't too much matter. Whatever makes you happy will work. There aren't a lot of silly rules because Python projects can be simple. * `/scripts` or `/bin` for that kind of command-line interface stuff * `/tests` for your tests * `/lib` for your C-language libraries * `/doc` for most documentation * `/apidoc` for the...
According to Jean-Paul Calderone's [Filesystem structure of a Python project](http://as.ynchrono.us/2007/12/filesystem-structure-of-python-project_21.html): ``` Project/ |-- bin/ | |-- project | |-- project/ | |-- test/ | | |-- __init__.py | | |-- test_main.py | | | |-- __init__.py | |-- main.py |...
What is the best project structure for a Python application?
[ "", "python", "directory-structure", "organization", "project-structure", "" ]
I am developing a piece of software in Python that will be distributed to my employer's customers. My employer wants to limit the usage of the software with a time-restricted license file. If we distribute the `.py` files or even `.pyc` files it will be easy to (decompile and) remove the code that checks the license f...
Python, being a byte-code-compiled interpreted language, is very difficult to lock down. Even if you use a exe-packager like [py2exe](http://py2exe.org), the layout of the executable is well-known, and the Python byte-codes are well understood. Usually in cases like this, you have to make a tradeoff. How important is ...
"Is there a good way to handle this problem?" No. Nothing can be protected against reverse engineering. Even the firmware on DVD machines has been reverse engineered and the [AACS Encryption key](http://en.wikipedia.org/wiki/AACS_encryption_key_controversy) exposed. And that's in spite of the DMCA making that a crimina...
How do I protect Python code from being read by users?
[ "", "python", "licensing", "obfuscation", "copy-protection", "" ]
I'm developing an application which has a lot of text and also different modules which can be included or not in every build. For each saved project we generate automatically a report with all the details (i.e. description of algorithms used in that project and so on). Currently we embed all text as strings in the sou...
I think all text which may change between different versions of the code should be kept in separate property files. You can build a mechanism which maps message ids to the proper string from a property file, say map id 15 to "search" or to "busca" in the English and Spanish property files respectively. So a property fi...
If I have lots of text to display, I typically store it in XML outside the application and read it as needed. This would work well for documentation, as well, I think. You could simply have a separate stylesheet to produce documentation from it. Localizing your application would then become a matter of maintaining the ...
What's the best way to manage a lot of text in code (and also support translations)?
[ "", "c++", "documentation", "internationalization", "" ]
I have a list of tuples like this: ``` [ ('a', 1), ('a', 2), ('a', 3), ('b', 1), ('b', 2), ('c', 1), ] ``` I want to iterate through this keying by the first item, so, for example, I could print something like this: ``` a 1 2 3 b 1 2 c 1 ``` How would I go about doing this without keeping an item to track whether t...
``` l = [ ('a', 1), ('a', 2), ('a', 3), ('b', 1), ('b', 2), ('c', 1), ] d = {} for x, y in l: d.setdefault(x, []).append(y) print d ``` produces: ``` {'a': [1, 2, 3], 'c': [1], 'b': [1, 2]} ```
Slightly simpler... ``` from collections import defaultdict fq = defaultdict(list) for n, v in myList: fq[n].append(v) print(fq) # defaultdict(<type 'list'>, {'a': [1, 2, 3], 'c': [1], 'b': [1, 2]}) ```
Converting a list of tuples into a dict
[ "", "python", "list", "dictionary", "tuples", "iteration", "" ]
I was recently working with a `DateTime` object, and wrote something like this: ``` DateTime dt = DateTime.Now; dt.AddDays(1); return dt; // still today's date! WTF? ``` The intellisense documentation for `AddDays()` says it adds a day to the date, which it doesn't - it actually *returns* a date with a day added to i...
``` private int myVar; public int MyVar { get { return MyVar; } } ``` Blammo. Your app crashes with no stack trace. Happens all the time. (Notice capital `MyVar` instead of lowercase `myVar` in the getter.)
**Type.GetType** The one which I've seen bite lots of people is [`Type.GetType(string)`](http://msdn.microsoft.com/en-us/library/w3f99sx1.aspx). They wonder why it works for types in their own assembly, and some types like `System.String`, but not `System.Windows.Forms.Form`. The answer is that it only looks in the cu...
What is the worst gotcha in C# or .NET?
[ "", "c#", ".net", "" ]
I have a `TreeView` windows forms control with an `ImageList`, and I want some of the nodes to display images, but the others to not have images. I *don't* want a blank space where the image should be. I *don't* want an image that looks like the lines that the TreeView would draw if it didn't have an ImageList. How do...
I tried this once and I don't think it is possible. If you try to set both `ImageKey` and `ImageIndex` to "not set" values the control just defaults `ImageIndex` to 0. The following code: ``` treeView.ImageKey = "Value"; Debug.WriteLine(treeView.ImageIndex); treeView.ImageKey = null; Debug.WriteLine(treeView.ImageInd...
You need to set `ImageIndex` and `SelectedImageIndex` to a number that is higher than the number of values in your `ImageList`. For example, if you create this node and add it to your `TreeView`: ``` TreeNode node1 = new TreeNode(string.Empty, 12, 12); // imageList1.Count = 5 ``` you will have an invisible `TreeNode`...
How do I set an image for some but not all nodes in a TreeView?
[ "", "c#", ".net", "winforms", "treeview", "" ]
Is it possible to define an implicit conversion of enums in c#? something that could achieve this? ``` public enum MyEnum { one = 1, two = 2 } MyEnum number = MyEnum.one; long i = number; ``` If not, why not?
There is a solution. Consider the following: ``` public sealed class AccountStatus { public static readonly AccountStatus Open = new AccountStatus(1); public static readonly AccountStatus Closed = new AccountStatus(2); public static readonly SortedList<byte, AccountStatus> Values = new SortedList<byte, Ac...
You can't do implict conversions (except for zero), and you can't write your own instance methods - however, you can probably write your own extension methods: ``` public enum MyEnum { A, B, C } public static class MyEnumExt { public static int Value(this MyEnum foo) { return (int)foo; } static void Main() ...
Can we define implicit conversions of enums in c#?
[ "", "c#", "enums", "implicit-conversion", "implicit", "" ]
I'm running my C++ program in gdb. I'm not real experienced with gdb, but I'm getting messages like: ``` warning: HEAP[test.exe]: warning: Heap block at 064EA560 modified at 064EA569 past requested size of 1 ``` How can I track down where this is happening at? Viewing the memory doesn't give me any clues. Thanks!
So you're busting your heap. Here's a nice [GDB tutorial](http://www.cs.princeton.edu/courses/archive/spring99/cs126/help/gdbtut.html) to keep in mind. My normal practice is to set a break in known good part of the code. Once it gets there step through until you error out. Normally you can determine the problem that w...
You can probably use a feature called a "watch point". This is like a break point but the debugger stops when the memory is modified. I gave a rough idea on how to use this in an [answer](https://stackoverflow.com/questions/7525/of-memory-management-heap-corruption-and-c#71983) to a different question.
Debugging a memory error with GDB and C++
[ "", "c++", "memory", "gdb", "" ]
What is the difference between `new`/`delete` and `malloc`/`free`? Related (duplicate?): [In what cases do I use malloc vs new?](https://stackoverflow.com/questions/184537/in-what-cases-do-i-use-malloc-vs-new)
## `new` / `delete` * Allocate / release memory 1. Memory allocated from 'Free Store'. 2. Returns a fully typed pointer. 3. `new` (standard version) never returns a `NULL` (will throw on failure). 4. Are called with Type-ID (compiler calculates the size). 5. Has a version explicitly to handle arrays. 6. Re...
The most relevant difference is that the `new` operator allocates memory then calls the constructor, and `delete` calls the destructor then deallocates the memory.
What is the difference between new/delete and malloc/free?
[ "", "c++", "memory-management", "" ]
I'm writing a password encryption routine. I've written the below app to illustrate my problem. About 20% of the time, this code works as expected. The rest of the time, the decryption throws a cryptographic exception - "The data is invalid". I believe the problem is in the encryption portion, because the decryption p...
On the advice of a colleague, I opted for Convert.ToBase64String. Works well. Corrected program below. ``` using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Text; using System.Windows.Forms; using System.Security.Cryptography; namespace ...
You should never use any of the `System.Text.Encoding` classes for cipher text. You *will* experience intermittent errors. You should use Base64 encoding and the `System.Convert` class methods. 1. To obtain an encrypted `string` from an encrypted `byte[]`, you should use: ``` Convert.ToBase64String(byte[] bytes...
ProtectedData.Protect intermittent failure
[ "", "c#", ".net", "security", "encoding", "cryptography", "" ]
I've been doing "plain old java objects" programming for 10 years now, with Swing and JDBC, and I consider myself pretty good at it. But I start a new job in two weeks where they use JBoss, and I'd like to get a heads up and start learning all this stuff before I start. What are good resources? On-line tutorials, books...
For quick getting up to speed, you really need to master EJBs and JSP/Servlets. Those are the fundamentals of Java EE technology. The Head First series on EJBs and JSP/Servlets is a good start for what has usually been a mind-numbingly complex framework. Beware that recent Head First editions have switched to teaching ...
A couple of answers come to mind: * if "plain old java" is what you're used to, you'll probably need a grounding of plain old j2EE more than JBOSS specific stuff. I'd start with [the sun tutorials](http://java.sun.com/javaee/5/docs/tutorial/doc/), but being familiar with the general structure of servlets, the servlet ...
Learning Java EE, jboss, etc
[ "", "java", "jakarta-ee", "jboss", "" ]
We have similar code to the following in one of our projects. Can anyone explain (in simple English) why the fixed statement is needed here? ``` class TestClass { int iMyVariable; static void Main() { TestClass oTestClass = new TestClass(); unsafe { fixed (int* p = &oTes...
It fixes the pointer in memory. Garbage collected languages have the freedom to move objects around memory for efficiency. This is all transparent to the programmer because they don't really use pointers in "normal" CLR code. However, when you do require pointers, then you need to fix it in memory if you want to work w...
The [fixed statement](http://msdn.microsoft.com/en-us/library/f58wzh21(VS.80).aspx) will "pin" the variable in memory so that the garbage collector doesn't move it around when collecting. If it did move the variable, the pointer would become useless and when you used it you'd be trying to access or modify something tha...
Fixed Statement in C#
[ "", "c#", ".net", "memory-management", "garbage-collection", "unsafe", "" ]
I have to concatenate a bunch of Strings in Javascript and am searching for the fastest way to do so. Let's assume that the Javascript has to create a large XML-"file" that, naturally, consists of many small Strings. So I came up with: ``` var sbuffer = []; for (var idx=0; idx<10000; idx=idx+1) { sbuff...
Changing the line: `sbuffer.push(‘Data comes here... bla... ’);` to `sbuffer[sbuffer.length] = ‘Data comes here... bla... ’;` will give you 5-50% speed gain (depending on browser, in IE - gain will be highest) Regards.
The question [JavaScript string concatenation](https://stackoverflow.com/questions/112158/javascript-string-concatenation) has an accepted answer that links to a [very good comparison of JavaScript string concatenation performance](http://www.sitepen.com/blog/2008/05/09/string-performance-an-analysis/). **Edit:** I wo...
Javascript String concatenation faster than this example?
[ "", "javascript", "performance", "join", "" ]
What is their use if when you call the method, it might not exist? Does that mean that you would be able to dynamically create a method on a dynamic object? What are the practical use of this?
You won't really be able to dynamically create the method - but you can get an implementation of `IDynamicMetaObject` (often by extending `DynamicObject`) to respond *as if the method existed*. Uses: * Programming against COM objects with a weak API (e.g. office) * Calling into dynamic languages such as Ruby/Python *...
First of all, you can't use it now. It's part of C#4, which will be released sometime in the future. Basically, it's for an object, whose properties won't be known until runtime. Perhaps it comes from a COM object. Perhaps it's a "define on the fly object" as you describe (although I don't think there's a facility to ...
What is the practical use of "dynamic" variable in C# 4.0?
[ "", "c#", ".net", "c#-4.0", "" ]
I have a main window (#1) on my webpage from which I open a new browser window (#2) from which I open a new window (#3). Now if my user closes window#2 before window#3, I have the problem that window#3 no longer can call function in its window.opener since it has gone away. What I would like to do is to set window#3....
In the third wndow you put in: ``` <script type="text/javascript"> var grandMother = null; window.onload = function(){ grandMother = window.opener.opener; } </script> ``` Thus you have the handle to the grandmother-window, and you can then use it for anything directly: ``` if(grandMother) grandMother...
`window.opener` probably is read-only. I'd setup your own property to refer to the grandparent when grandchild is loaded. ``` function onLoad() { window.grandparent = window.opener.opener; } ```
Handling of child and grandchild windows in Javascript
[ "", "javascript", "jquery", "window", "" ]
I would like create my own collection that has all the attributes of python list and also knows how to save/load itself into/from a database. Also I want to make the load implicit and lazy, as in it doesn't happen at the point of creation of the list, but waits until its first used. Is there a single`__xxx__`method I ...
No, there isn't.
Not a *single*, but 5 is enough: ``` from collections import MutableSequence class Monitored(MutableSequence):     def __init__(self):         super(Monitored, self).__init__()         self._list = []     def __len__(self):         r = len(self._list)         print "len: {0:d}".format(r)         return r     def __...
Python lazy list
[ "", "python", "" ]
Java process control is notoriously bad - primarily due to inadequate support by the Java VM/JDK classes (e.g. java.lang.Process). I am wondering, are there any good open source libraries out there that are reliable. The requirements would be: 1. OSS 2. Start/Stop processes 3. Manage STDIN and STDOUT 4. cross platfo...
[Java Service Wrapper](http://wrapper.tanukisoftware.org/doc/english/download.jsp) might be what you're looking for. It's cross-platform, can be used to start things as a Windows service, capture IO, and generally completely manage any java app. It's very light weight and well designed. Atlassian uses it to wrap their ...
How about [Apache Commons Exec](http://commons.apache.org/exec/download_exec.cgi)?
Good Java Process Control Library
[ "", "java", "open-source", "process", "" ]
``` struct elem { int i; char k; }; elem user; // compile error! struct elem user; // this is correct ``` In the above piece of code we are getting an error for the first declaration. But this error doesn't occur with a C++ compiler. In C++ we don't need to use the keyword struct again and again. So why doesn't any...
Because it takes years for a new Standard to evolve. They are working on a new C++ Standard ([C++0x](http://en.wikipedia.org/wiki/C%2B%2B0x)), and also on a new C standard (C1x), but if you remember that it usually takes between 5 and 10 years for each iteration, i don't expect to see it before 2010 or so. Also, just ...
``` typedef struct { int i; char k; } elem; elem user; ``` will work nicely. as other said, it's about standard -- when you implement this in VS2008, you can't use it in GCC and when you implement this even in GCC, you certainly not compile in something else. Method above will work everywhere. On the other side --...
Why doesn't anyone upgrade their C compiler with advanced features?
[ "", "c++", "c", "visual-studio", "compiler-construction", "" ]
Markdown is a great tool for formatting plain text into pretty html, but it doesn't turn plain-text links into URLs automatically. Like this one: <http://www.google.com/> How do I get markdown to add tags to URLs when I format a block of text?
I couldn't get superjoe30's regular expression to compile, so I adapted his solution to convert plain URLs (within Markdown text) to be Markdown compatible. The modified filter: ``` urlfinder = re.compile('^(http:\/\/\S+)') urlfinder2 = re.compile('\s(http:\/\/\S+)') @register.filter('urlify_markdown') def urlify_mar...
You could write an extension to markdown. Save this code as mdx\_autolink.py ``` import markdown from markdown.inlinepatterns import Pattern EXTRA_AUTOLINK_RE = r'(?<!"|>)((https?://|www)[-\w./#?%=&]+)' class AutoLinkPattern(Pattern): def handleMatch(self, m): el = markdown.etree.Element('a') if...
How do I get python-markdown to additionally "urlify" links when formatting plain text?
[ "", "python", "django", "markdown", "" ]
I was looking at the Java code for `LinkedList` and noticed that it made use of a static nested class, `Entry`. ``` public class LinkedList<E> ... { ... private static class Entry<E> { ... } } ``` What is the reason for using a static nested class, rather than an normal inner class? The only reason I could think ...
The Sun page you link to has some key differences between the two: > A nested class is a member of its enclosing class. Non-static nested classes (inner classes) have access to other members of the enclosing class, even if they are declared private. Static nested classes do not have access to other members of the encl...
To my mind, the question ought to be the other way round whenever you see an inner class - does it *really* need to be an inner class, with the extra complexity and the implicit (rather than explicit and clearer, IMO) reference to an instance of the containing class? Mind you, I'm biased as a C# fan - C# doesn't have ...
Static nested class in Java, why?
[ "", "java", "class", "static", "member", "" ]
i want to be a good developer citizen, [pay my taxes](http://blogs.msdn.com/oldnewthing/archive/2005/08/22/454487.aspx), and disable things if we're running over Remote Desktop, or running on battery. If we're running over remote desktop (or equivalently in a Terminal server session), we must disable animations and do...
I believe you can check [SystemInformation.PowerStatus](http://msdn.microsoft.com/en-us/library/system.windows.forms.systeminformation.powerstatus(VS.80).aspx) to see if it's on battery or not. ``` Boolean isRunningOnBattery = (System.Windows.Forms.SystemInformation.PowerStatus.PowerLineStatus == PowerLi...
R. Bemrose found the managed call. Here's some sample code: ``` /// <summary> /// Indicates if we're running on battery power. /// If we are, then disable CPU wasting things like animations, background operations, network, I/O, etc /// </summary> public static Boolean IsRunningOnBattery { get { PowerLineSt...
C# .NET: How to check if we're running on battery?
[ "", "c#", "performance", "optimization", "" ]
I want to display an image within a scroll area. The view port of the scroll area shall have a defined initial size. That means, if the image's size is bigger than the initial size of the view port, scroll bars will be visible, otherwise not. ``` // create label for displaying an image QImage image( ":/test.png" ); QL...
I think that you are looking at the problem the wrong way. The QScrollArea is just a widget that you put in a frame or QMainWindow. The size of the widget is controlled by the layout of the widget that contains it. Take a look at this example from Trolltech: [Image Viewer Example](http://doc.qt.io/qt-5/qtwidgets-widge...
You can try: ``` class MyScrollArea : public QScrollArea { virtual QSize sizeHint() const { return QSize( 300, 300 ); } }; // create label for displaying an image QImage image( ":/test.png" ); Label *label = new QLabel; label->setPixmap( image.toPixmap() ); // put label into scroll area QScollArea *area = new My...
How to set an initial size of a QScrollArea?
[ "", "c++", "qt", "qscrollarea", "" ]
I have the following code which works just fine when the method is "POST", but changing to "GET" doesn't work: ``` HttpWebRequest request = null; request = HttpWebRequest.Create(uri) as HttpWebRequest; request.ContentType = "application/x-www-form-urlencoded; charset=UTF-8"; request.Method = "POST"; // Doesn't work wi...
This is [specified in the documentation](http://msdn.microsoft.com/en-us/library/system.net.httpwebrequest.begingetrequeststream.aspx). Basically GET requests aren't meant to contain bodies, so there's no sensible reason to call `BeginGetRequestStream`.
Does it make sense for a GET request to send a Content-Type? Did you try removing the third line?
How do I use HttpWebRequest with GET method
[ "", "c#", ".net", "silverlight", "web-services", "http", "" ]
``` template <class T> bool BST<T>::search(const T& x, int& len) const { return search(BT<T>::root, x); } template <class T> bool BST<T>::search(struct Node<T>*& root, const T& x) { if (root == NULL) return false; else { if (root->data == x) return true; else if(r...
Okay, `bool BST<T>::search(struct Node<T>*& root, const T& x)` should probably have const after it like so: `bool BST<T>::search(struct Node<T>*& root, const T& x) const`. Basically, you've called a non-const function from a const function and this is a no-no. BTW, this looks suspect to me "`struct Node<T>*&`"... I'd ...
There are multiple problems in your search code: * The sort order is backwards, if the node data is less than what you search, you should search in the right branch, not the left branch. * You should return the result of the recursive call * It is also unclear why you pass `root` by reference. it should instead be pas...
C++ Binary Search Tree Recursive search function
[ "", "c++", "binary-search-tree", "" ]
I've recently started using code coverage tools (particularily Emma and EclEmma), and I really like the view that it gives me as to the completeness of my unit tests - and the ability to see what areas of the code my unit tests aren't hitting at all. I currently work in an organization that doesn't do a lot of unit tes...
I use code coverage to give me hints on places where I may have an incomplete set of tests. For example, I may write a test for some given functionality, then go develop the code that satisfies that functionality, but in doing so actually write code that does more than it is supposed to -- say it might catch an excepti...
I think it is worthwhile to use a library where you can choose to ignore certain kinds of statements. For example, if you have a lot of: ``` if(logger.isDebugEnabled()) { logger.debug("something"); } ``` It is useful if you can turn off coverage calculations for those sorts of lines. It can also be (arguably) val...
How far do you take code coverage?
[ "", "java", "tdd", "code-coverage", "emma", "" ]
Ok, I am reading in dat files into a byte array. For some reason, the people who generate these files put about a half meg's worth of useless null bytes at the end of the file. Anybody know a quick way to trim these off the end? First thought was to start at the end of the array and iterate backwards until I found som...
Given the extra questions now answered, it sounds like you're fundamentally doing the right thing. In particular, you have to touch every byte of the file from the last 0 onwards, to check that it only has 0s. Now, whether you have to copy everything or not depends on what you're then doing with the data. * You could...
I agree with Jon. The critical bit is that you must "touch" every byte from the last one until the first non-zero byte. Something like this: ``` byte[] foo; // populate foo int i = foo.Length - 1; while(foo[i] == 0) --i; // now foo[i] is the last non-zero byte byte[] bar = new byte[i+1]; Array.Copy(foo, bar, i+1);...
Removing trailing nulls from byte array in C#
[ "", "c#", "arrays", "" ]
I'm hitting this error and I'm not really sure why. I have a minified version of excanvas.js and something is breaking in IE, specifically on: `var b=a.createStyleSheet();` I'm not sure why. Does anyone have any insight? I can provide more information, I'm just not sure what information will help.
This is a slightly old thread, but I thought it would be useful to post. There seems to be a limitation on how much style information a page can contain, which causes this error in IE6. I am able to produce an invalid argument error using this simple test page: ``` <html> <head> <title></title> <script> for(var i=0;i<...
The newest version of excanvas.js did not fix this issue for me in IE8 so I updated line 111 of excanvas.js to the code below and I no longer get the exception. The code for this solution is from <http://dean.edwards.name/weblog/2010/02/bug85/>. ``` var ss = null; var cssText = 'canvas{display:inline-block;overflo...
What does the error "htmlfile: invalid argument" mean? I'm getting this in excanvas.js
[ "", "javascript", "" ]
I have a requirement to get the contents of every method in a cs file into a string. What I am looking for is when you have an input of a cs file, a dictionary is returned with the method name as the key and the method body as the value. I have tried Regex and reflection with no success, can anyone help? Thanks
I don't know if it's any use to you but Visual Studio Addins include a EnvDTE object, that gives you full access to the VB and C# language parsers. See [Discovering Code with the code Model](http://msdn.microsoft.com/en-us/library/ms228763(VS.80).aspx) I touched on it tangentially years ago, I don't know how difficult...
**Assuming that the file is valid** (i.e. compiles), you can start by reading the whole file into a string. I gather from your question that you are only interested in method names, not in class names. Then you need a regex that gives you all instances of *public|protected|private*, optional keywords virtual/override ...
Get a method's contents from a cs file
[ "", "c#", "regex", "methods", "" ]
How would I achieve the pseudo-code below in JavaScript? I want to include the date check in the second code excerpt, where txtDate is for the BilledDate. ``` If ABS(billeddate – getdate) > 31 then yesno “The date you have entered is more than a month from today, Are you sure the date is correct,”. if (txtDate && ...
Generally speaking you work with Date-objects in javascript, and these should be constructed with the following syntax: ``` var myDate = new Date(yearno, monthno-1, dayno); //you could put hour, minute, second and milliseconds in this too ``` Beware, the month-part is an index, so january is 0, february is 1 ...
To get the date difference in days in plain JavaScript, you can do it like this: ``` var billeddate = Date.parse("2008/10/27"); var getdate = Date.parse("2008/09/25"); var differenceInDays = (billeddate - getdate)/(1000*60*60*24) ``` However if you want to get more control in your date manipulation I suggest you to ...
Date Parsing and Validation in JavaScript
[ "", "javascript", "" ]
I'd like something like a generic, re-usable `getPosition()` method that will tell me the number of bytes read from the starting point of the stream. Ideally, I would prefer this to work with all InputStreams, so that I don't have to wrap each and every one of them as I get them from disparate sources. Does such a bea...
Take a look at [CountingInputStream](http://commons.apache.org/io/apidocs/org/apache/commons/io/input/CountingInputStream.html) in the Commons IO package. They have a pretty good collection of other useful InputStream variants as well.
You'll need to follow the Decorator pattern established in `java.io` to implement this. Let's give it a try here: ``` import java.io.FilterInputStream; import java.io.IOException; import java.io.InputStream; public final class PositionInputStream extends FilterInputStream { private long pos = 0; private long...
Given a Java InputStream, how can I determine the current offset in the stream?
[ "", "java", "io", "inputstream", "" ]
I have just installed Eclipse 3.4 and found out that there is not a plugin to create Swing applications yet. I also have found that there is a Matisse implementation in MyEclipse IDE, but I'd like to now whether there is such a Matisse plugin for free.
Instatiations Swing Designer is the best in my opinion. We settled on it after trying may different Eclipse plugins.
there isnt one for free. myeclipse is the only way to run matisse inside eclipse.
Matisse in Eclipse
[ "", "java", "eclipse", "swing", "eclipse-3.4", "matisse", "" ]
I'd like to receive error logs via email. For example, if a `Warning-level` error message should occur, I'd like to get an email about it. How can I get that working in CodeIgniter?
You could extend the Exception core class to do it. Might have to adjust the reference to CI's email class, not sure if you can instantiate it from a library like this. I don't use CI's email class myself, I've been using the Swift Mailer library. But this should get you on the right path. Make a file MY\_Exceptions....
One thing that is left out of the solution is that you have to grab CodeIgniters super object to load and use the email library (or any of CodeIgniters other libraries and native functions). ``` $CI =& get_instance(); ``` After you have done that you use `$CI` instead of `$this` to load the email library and set all ...
In CodeIgniter, How Can I Have PHP Error Messages Emailed to Me?
[ "", "php", "email", "codeigniter", "error-logging", "" ]
When running PHP in CLI mode, *most* of the time (not always), the script will hang at the end of execution for about 5 seconds and then output this: > `Error in my_thread_global_end(): 1 threads didn't exit` It doesn't seem to actually have any effect on the script itself. Some web searches turned up blogs which su...
This is a known bug with some of the PHP 5.2.X version in the windows fast-cgi implementation <http://bugs.php.net/bug.php?id=41350&edit=1> I have encountered this bug before and downgrading my PHP install to 5.2.0 solved the problem.
There is no need to downgrade the entire PHP version, just replace the **libmysql.dll** from the **PHP 5.2.1 release** & things should be rolling :) Refer [**this link**](http://www.eukhost.com/forums/f15/fix-error-my_thread_global_end-1-thread-didnt-exit-5612/) for more info.
PHP: Error in my_thread_global_end(): 1 threads didn't exit
[ "", "php", "mysql", "" ]
I have a one-dimensional array of strings in JavaScript that I'd like to turn into a comma-separated list. Is there a simple way in garden-variety JavaScript (or jQuery) to turn that into a comma-separated list? (I know how to iterate through the array and build the string myself by concatenation if that's the only way...
The [Array.prototype.join()](https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/Array/join) method: ``` var arr = ["Zero", "One", "Two"]; document.write(arr.join(", ")); ```
Actually, the `toString()` implementation does a join with commas by default: ``` var arr = [ 42, 55 ]; var str1 = arr.toString(); // Gives you "42,55" var str2 = String(arr); // Ditto ``` I don't know if this is mandated by the JS spec but this is what ~~most~~ pretty much all browsers seem to be doing.
Easy way to turn JavaScript array into comma-separated list?
[ "", "javascript", "" ]
Is there a PHP class/library that would allow me to query an XHTML document with CSS selectors? I need to scrape some pages for data that is very easily accessible if I could somehow use CSS selectors (jQuery has spoiled me!). Any ideas?
After Googling further (initial results weren't very helpful), it seems there is actually a Zend Framework library for this, along with some others: * [DOM-Query](https://github.com/PHPPowertools/DOM-Query) * [phpQuery](http://code.google.com/p/phpquery/) * [pQuery](https://github.com/tburry/pquery) * [QueryPath](http...
XPath is a fairly standard way to access XML (and XHTML) nodes, and provides much more precision than CSS.
PHP CSS Selector Library?
[ "", "php", "screen-scraping", "css-selectors", "" ]
i am planning to use 2 dedicated root servers rented at a hosting provider. those machines will run tomcat 6 in a cluster. if i will add additional machines later on - it is unlikely that they will be accessible with multicast, because they will be located in different subnets. is it possible to run tomcat without mul...
With no control over the distance between both servers (they might be in two different datacenters) and no dedicated inter-server-communication line, I'd rather run them via round-robin DNS or a loadbalancer that redirects clients to either www1.yourdomain.xxx or www2.yourdomain.xxx and handle server-communication care...
Seeing the comment to the question after having given my other answer I'm puzzled about what your question is... Is it about session replication? Cluster communication? It might be better to state your problem instead of your planned solution that has problems itself. I'll state some possible problems together with qu...
tomcat session replication without multicast
[ "", "java", "tomcat", "multicast", "failovercluster", "" ]
In this thread, we look at examples of good uses of `goto` in C or C++. It's inspired by [an answer](https://stackoverflow.com/questions/244445/best-refactoring-for-the-dreaded-while-true-loop#244644) which people voted up because they thought I was joking. Summary (label changed from original to make intent even clea...
Heres one trick I've heard of people using. I've never seen it in the wild though. And it only applies to C because C++ has RAII to do this more idiomatically. ``` void foo() { if (!doA()) goto exit; if (!doB()) goto cleanupA; if (!doC()) goto cleanupB; /* everything has succee...
The classic need for GOTO in C is as follows ``` for ... for ... if(breakout_condition) goto final; final: ``` There is no straightforward way to break out of nested loops without a goto.
Examples of good gotos in C or C++
[ "", "c++", "c", "goto", "" ]
Can an abstract class have a constructor? If so, how can it be used and for what purposes?
Yes, an abstract class can have a constructor. Consider this: ``` abstract class Product { int multiplyBy; public Product( int multiplyBy ) { this.multiplyBy = multiplyBy; } public int mutiply(int val) { return multiplyBy * val; } } class TimesTwo extends Product { public Time...
You would define a constructor in an abstract class if you are in one of these situations: * you want to perform some initialization (to fields of the abstract class) before the instantiation of a subclass actually takes place * you have defined final fields in the abstract class but you did not initialize...
Can an abstract class have a constructor?
[ "", "java", "constructor", "abstract-class", "" ]
If I have a table like: ``` CREATE TABLE FRED ( recordId number(18) primary key, firstName varchar2(50) ); ``` Is there an easy way to clone it's structure (not it's data) into another table of a given name. Basically I want to create table with exactly the same structure, but a different name, so that I can perform ...
If you're looking a way to find the exact DDL to recreate the table, including the storage clause, you can use ``` select dbms_metadata.get_ddl('TABLE', 'TABLE_NAME', 'SCHEMA_NAME') from dual ``` as described [here](http://www.troygeek.com/articles/ExtractingOracleDDLCommandLine/).
CREATE TABLE tablename AS SELECT \* FROM orginaltable WHERE 1=2; Edit: The WHERE clause prohibits any rows from qualifying.
Is there an easy way to clone the structure of a table in Oracle?
[ "", "java", "database", "oracle", "" ]
What does Mozilla Firefox's XPCSafeJSObject wrapper actually do? [MDC](https://developer.mozilla.org/en/XPConnect_wrappers#XPCSafeJSObjectWrapper)'s documentation is as follows: > This wrapper was created to address some problems with XPCNativeWrapper. In particular, some extensions want to be able to safely access n...
The purpose of the wrappers in general is to protect Privileged code when interacting with unprivileged code. The author of the unprivileged code might redefine a JavaScript object to do something malicious, like redefine the getter of a property to execute something bad as a side effect. When the privileged code tries...
Actually XPCSafeJSObjectWrapper is used for all content objects, including windows and documents (which is in fact where it's most usually needed.) I believe it was invented mainly to stop XSS attacks automatically turning into privilege escalation attacks (by doing XSS against the browser itself). At least now if an X...
What does XPCSafeJSObjectWrapper do?
[ "", "javascript", "firefox", "firefox-addon", "gecko", "" ]
I've been given some code with commenting unlike anything I've come across before: ``` //{{{ Imports import imports; //}}} ``` It is the same for each method block, ``` //{{{ above the code block //}}} below the code block ``` Also see: <http://en.wikipedia.org/wiki/Folding_editor>
A quick search for *"triple curly" comment* suggests it's "[Emacs folding mode](http://www.emacswiki.org/cgi-bin/wiki/FoldingMode)". Or some other code folding marker in any case.
[jEdit](http://www.jedit.org) uses {{{ and }}} to mark "explicit" folds.
Java: Triple Curly Bracing
[ "", "java", "coding-style", "folding", "" ]
I am debugging some code and have encountered the following SQL query (simplified version): ``` SELECT ads.*, location.county FROM ads LEFT JOIN location ON location.county = ads.county_id WHERE ads.published = 1 AND ads.type = 13 AND ads.county_id = 2 OR ads.county_id = 5 OR ads.county_id = 7 OR ads.county_id = 9 `...
Put parentheses around the "OR"s: ``` SELECT ads.*, location.county FROM ads LEFT JOIN location ON location.county = ads.county_id WHERE ads.published = 1 AND ads.type = 13 AND ( ads.county_id = 2 OR ads.county_id = 5 OR ads.county_id = 7 OR ads.county_id = 9 ) ``` Or even better, use IN: ``` SELEC...
You can try using parentheses around the OR expressions to make sure your query is interpreted correctly, or more concisely, use IN: ``` SELECT ads.*, location.county FROM ads LEFT JOIN location ON location.county = ads.county_id WHERE ads.published = 1 AND ads.type = 13 AND ads.county_id IN (2,5,7,9) ```
How to do select from where x is equal to multiple values?
[ "", "sql", "mysql", "" ]
i have a server - client application that runs on java 1.3; i want to change to java 1.6 step by step, meaning first few clients, than rest of the clients and finally server... i was wondering could you direct me to some common problems that can come along and what should i look after?
Sun tries to keep a high level of backward-compatibility, so you possibly simply can install the new JVM and restart your application with it. A document describing the backward-incompatibilities from Java 1.6 with earlier version is [here](http://java.sun.com/javase/6/webnotes/compatibility.html). This document links...
Off the top of my head, look for the names `enum` and `assert` in fields and local variables... These words have become keywords in java 1.4 and 5. The java 6 compiler will mark them as compilation errors if it sees them. Yuval =8-)
Changing java version
[ "", "java", "jvm", "version", "compatibility", "versions", "" ]
I quite often see JavaScript with variables that start with a dollar sign. When/why would you choose to prefix a variable in this way? (I'm not asking about `$('p.foo')` syntax that you see in jQuery and others, but normal variables like `$name` and `$order`)
Very common use in **jQuery** is to distinguish **jQuery** objects stored in variables from other variables. For example, I would define: ``` var $email = $("#email"); // refers to the jQuery object representation of the dom object var email_field = $("#email").get(0); // refers to the dom object itself ``` I find t...
In the 1st, 2nd, and [3rd Edition of ECMAScript](http://www.ecma-international.org/publications/files/ECMA-ST-ARCH/ECMA-262,%203rd%20edition,%20December%201999.pdf), using $-prefixed variable names was explicitly discouraged by the spec except in the context of autogenerated code: > The dollar sign (`$`) and the under...
Why would a JavaScript variable start with a dollar sign?
[ "", "javascript", "naming-conventions", "" ]
I have roughly the following code. Could this be made nicer or more efficient? Perhaps using `std::remove_if`? Can you remove items from the map while traversing it? Can we avoid using the temporary map? ``` typedef std::map<Action, What> Actions; static Actions _actions; bool expired(const Actions::value_type &actio...
You could use erase(), but I don't know how BOOST\_FOREACH will handle the invalidated iterator. The [documentation for map::erase](http://en.cppreference.com/w/cpp/container/map/erase) states that only the erased iterator will be invalidated, the others should be OK. Here's how I would restructure the inner loop: ```...
A variation of Mark Ransom algorithm but without the need for a temporary. ``` for(Actions::iterator it = _actions.begin();it != _actions.end();) { if (expired(*it)) { bar(*it); _actions.erase(it++); // Note the post increment here. // This increments 'it' and re...
How to filter items from a std::map?
[ "", "c++", "boost", "stl", "" ]
In our application we enable users to print pages. We do this by supplying a button which when click calls the window.print() function. Some of the pages would look better if they were printed in landscape mode rather than portrait. Is there a way to control the page layout from JavaScript? Update: Following the adv...
You should use a print stylesheet. ``` <link rel="stylesheet" href="print.css" type="text/css" media="print" /> ``` More info... [How to print only parts of a page?](https://stackoverflow.com/questions/224078/how-to-print-only-parts-of-a-page) Edit: to coerce landscape orientation, apparently the standard is `size:...
Do it with CSS by including a print stylesheet thusly: ``` <style type="text/css" media="print">@import url("/inc/web.print.css");</style> ```
Can I change page layout when using window.print()?
[ "", "javascript", "" ]
Ant has a nice way to select groups of files, most handily using \*\* to indicate a directory tree. E.g. ``` **/CVS/* # All files immediately under a CVS directory. mydir/mysubdir/** # All files recursively under mysubdir ``` More examples can be seen here: <http://ant.apache.org/manual/dirtasks.html> ...
As soon as you come across a `**`, you're going to have to recurse through the whole directory structure, so I think at that point, the easiest method is to iterate through the directory with os.walk, construct a path, and then check if it matches the pattern. You can probably convert to a regex by something like: ```...
Sorry, this is quite a long time after your OP. I have just released a Python package which does exactly this - it's called Formic and it's available at the [PyPI Cheeseshop](http://pypi.python.org/pypi/formic). With Formic, your problem is solved with: ``` import formic fileset = formic.FileSet(include="**/CVS/*", de...
How would you implement ant-style patternsets in python to select groups of files?
[ "", "python", "file", "ant", "" ]
Are the two events the same or are there differences that we should take note when coding the keyboard presses?
My answer here is just based on experimenting with different applications, not programming per se. Handle the keydown. Let that be the trigger for your logic. That's what the user would expect based on interacting with other applications. For example, try a key down in Notepad, and you'll see that the DOWN triggers t...
It doesn't matter if it's .Net or not, it matters what the user expects. Keydown is a good time to respond to the four arrow keys. Character input is a good time to respond to input of visible characters. Keyup is usually a good time to respond to any action that is going to have an effect on a document, but keydown wo...
In .Net, what's the better choice to code key presses in keyboard, key-up or keydown?
[ "", "c#", ".net", "vb.net", "winapi", "" ]
I'm trying to use stl algorithm for\_each without proliferating templates throughout my code. std::for\_each wants to instantiate MyFunctor class by value, but it can't since its abstract. I've created a functor adapter class which passes a pointer around and then derefernces it when appropriate. My Question: Does th...
tr1::ref may help you here --- it's meant to be a reference wrapper so that you can pass normal objects by reference to bind or function objects (even abstract ones) by reference to standard algorithms. ``` // requires TR1 support from your compiler / standard library implementation #include <functional> void applyTo...
You could use the function adapters (and their shims) from `functional`. ``` #include <functional> using namespace std; for_each( vec.begin(), vec.end(), :mem_fun_ptr( &MyClass::f ) ); ``` If your container contains pointers-to-objects, use `mem_fun_ptr`, else use `mem_fun`. Next to these, there are wrappers for mem...
Polymorphic functors in std::for_each
[ "", "c++", "stl", "polymorphism", "" ]
Each of my clients can have many todo items and every todo item has a due date. What would be the query for discovering the next undone todo item by due date for each file? In the event that a client has more than one todo, the one with the lowest id is the correct one. Assuming the following minimal schema: ``` cli...
I haven't tested this yet, so you may have to tweak it: ``` SELECT TD1.client_id, TD1.id, TD1.description, TD1.timestamp_due FROM Todos TD1 LEFT OUTER JOIN Todos TD2 ON TD2.client_id = TD1.client_id AND TD2.timestamp_completed IS NULL AND ( TD2.timestamp_due < TD1.timestamp_due ...
This question is the classic ***pick-a-winner for each group***. It gets posted about twice a day. ``` SELECT * FROM todos t WHERE t.timestamp_completed is null and ( SELECT top 1 t2.id FROM todos t2 WHERE t.client_id = t2.client_id and t2.timestamp_completed is null --there is no earlier record a...
"Simple" SQL Query
[ "", "sql", "sql-server", "" ]
I have the following SQL-statement: ``` SELECT DISTINCT name FROM log WHERE NOT name = '' AND name LIKE '%.EDIT%'; ``` It works fine on Postgres (returns all different names from log, which aren't empty and contain the string '.EDIT'). But on Oracle this statement doesn't work. Any idea why?
``` SELECT DISTINCT name FROM log WHERE NOT name = '' AND name LIKE '%.EDIT%'; ``` 1) Oracle treats '' as NULL, which means the comparison "NOT name = ''" is never true or false; use "IS NOT NULL" instead. But... 2) The second condition "name LIKE '%.EDIT%' will not match an empty string anyway, making the first cond...
The empty string in Oracle is equivalent to NULL, causing the comparison to fail. Change that part of the query to NAME IS NOT NULL
Why won't this SQL statement work?
[ "", "sql", "oracle", "" ]
``` $doba = explode("/", $dob); $date = date("Y-m-d", mktime(0,0,0, $doba[0], $doba[1], $doba[2])); ``` The above code turns any date i pass through into 1999-11-30 and i know it was working yesterday. Date is correct when I echo $doba. Anyone have any ideas? Cheers
What is the format of `$doba`? Remember `mktime`'s syntax goes hour, minute, second, **month, day year** which can be confusing. Here's some examples: ``` $doba = explode('/', '1991/08/03'); echo(date('Y-m-d', mktime(0,0,0, $doba[1], $doba[2], $doba[0]); $doba = explode('/', '03/08/1991'); echo(date('Y-m-d', mktime(...
or even easier: `$date = date('Y-m-d', strtotime($dob))`
PHP mangles my dates
[ "", "php", "date", "" ]
What is the upper limit for an autoincrement primary key in SQL Server? What happens when an SQL Server autoincrement primary key reaches its upper limit?
Joel's answer is correct, it is the upper limit of whatever datatype you use. Here's an example of two of them: * int: 2^31-1 (2,147,483,647) * bigint: 2^63-1 (9,223,372,036,854,775,807) I have actually hit the limit at a job I worked at. The actual error is: ``` Msg 8115, Level 16, State 1, Line 1 Arithmet...
It depends on the datatype. If you use bigint, you're unlikely to ever overflow. Even a normal int gives you a couple billion rows. I've never overflowed, so I can't tell you what happens if you do.
Upper limit for autoincrement primary key in SQL Server
[ "", "sql", "sql-server", "auto-increment", "" ]
How can I play audio (it would be like a 1 second sound) from a Python script? It would be best if it was platform independent, but firstly it needs to work on a Mac. I know I could just execute the `afplay file.mp3` command from within Python, but is it possible to do it in raw Python? I would also be better if it d...
You can find information about Python audio here: <http://wiki.python.org/moin/Audio/> It doesn't look like it can play .mp3 files without external libraries. You could either convert your .mp3 file to a .wav or other format, or use a library like [PyMedia](http://pymedia.org/).
Try [playsound](https://github.com/TaylorSMarks/playsound) which is a Pure Python, cross platform, single function module with no dependencies for playing sounds. Install via pip: ``` $ pip install playsound ``` Once you've installed, you can use it like this: ``` from playsound import playsound playsound('/path/to...
Play audio with Python
[ "", "python", "audio", "" ]
An abstract class can only be used as a base class which is extended by some other class, right? The constructor(s) of an abstract class can have the usual access modifiers (public, protected, and private (for internal use)). Which of `protected` and `public` is the correct access modifier to use, since the abstract ty...
An abstract class's constructor can only be called from the implementation's constructor, so there is no difference between it being public or protected. E.g.: ``` public class Scratch { public static abstract class A { public A( int i ) {} } public static class B extends A { p...
If this behavior is true, and I'm not sure it is, you should always use the most restricted scope available for your application to function. So in that case, I would recommend using protected.
Abstract class constructor access modifier
[ "", "java", "" ]
I have a menu with an animation going on, but I want to disable the click while the animation is happening. ``` <div></div> <div></div> <div></div> $("div").click(function() { $(this).animate({height: "200px"}, 2000); return false; }); ``` However, I want to disable all the buttons while the event is happening...
``` $("div").click(function() { if (!$(this).parent().children().is(':animated')) { $(this).animate({height: "200px"}, 2000); } return false; }); ```
You could do something like this... ``` $(function() { $("div").click(function() { //check to see if any of the divs are animating if ($("div").is(":animated")) { alert("busy"); return; } //whatever your animation is ...
Using jQuery, how do I disable the click effect on the current tab?
[ "", "javascript", "jquery", "" ]
I want to increment a cookie value every time a page is referenced even if the page is loaded from cache. What is the "best" or most concise way to implement this?
Stolen from <http://www.quirksmode.org/js/cookies.html#script> ``` function createCookie(name,value,days) { if (days) { var date = new Date(); date.setTime(date.getTime()+(days*24*60*60*1000)); var expires = "; expires="+date.toUTCString(); } else var expires = ""; document.cook...
Most of the old cookie handling functions I've seen use simple string manipulations for storing an retrieving values, like [this](http://www.w3schools.com/JS/js_cookies.asp) example, you can use other libraries, like [cookie-js](http://code.google.com/p/cookie-js/), a small *(< 100 lines)* utility for cookie access. I...
What is the "best" way to get and set a single cookie value using JavaScript
[ "", "javascript", "cookies", "" ]
What I want to do is scroll down the window when I expand elements in my page. The effect I am trying to achieve is like the Stack Overflow comments. If it expands beyond the page, it scrolls down to fit all the comments in the window. What is the best way of doing this? Edit: I am using JQuery.
This jQuery plugin worked well for me: <http://demos.flesler.com/jquery/scrollTo/>
You can do it nicely with [Scriptaculous](http://script.aculo.us/) (built on top of [Prototype](http://prototypejs.org)): ``` new Effect.ScrollTo('someDiv',{...some parameters...}) ``` It gives you finer control than Prototype alone (delay before start, duration and callback events (such as afterFinish) that allow yo...
What is the best way of scrolling the browser window for expanding elements?
[ "", "javascript", "window", "scroll", "" ]
I've got a little problem that's slightly frustrating. Is it possible to set a default value when deserializing xml in C# (.NET 3.5)? Basically I'm trying to deserialize some xml that is not under my control and one element looks like this: ``` <assignee-id type="integer">38628</assignee-id> ``` it can also look like...
It looks like your source XML is using xsi:type and xsi:nil, but not prefixing them with a namespace. What you could do is process these with XSLT to turn this: ``` <assignees> <assignee> <assignee-id type="integer">123456</assignee-id> </assignee> <assignee> <assignee-id type="integer" nil="true"></ass...
You might want to take a look at the [OnDeserializedAttribute](http://msdn.microsoft.com/en-us/library/system.runtime.serialization.ondeserializedattribute.aspx),[OnSerializingAttribute](http://msdn.microsoft.com/en-us/library/system.runtime.serialization.onserializingattribute.aspx), [OnSerializedAttribute](http://msd...
Is it possible to set a default value when deserializing xml in C# (.NET 3.5)?
[ "", "c#", "xml", "serialization", "" ]
Currently using System.Web.UI.WebControls.FileUpload wrapped in our own control. We have licenses for Telerik. I wanted to know if anyone had experience with that or could suggest a better one? Some criteria to be measured by * validation * peformance * multiple files * localisation ([browse](https://stackoverflow.c...
Personally, if you have the Telerik controls I would give them a shot. I've found that they are very helpful, and the user experience is good. Their upload control is quite nice.
I just posted about this [in another question](https://stackoverflow.com/questions/254419/aspnet-image-uploading-with-resizing#254812), but if you use this ActiveX control you will be able to process images quickly and efficiently. The component will actually resize the images on the client machine before sending them....
Can you recommend alternative FileUpload control for asp.net-mvc?
[ "", "c#", "asp.net-mvc", "file-upload", "web-controls", "" ]
I need to integrate a email client in my current python web app. Anything available? L.E.: I'm building my app on top of CherryPy
Looking up [webmail](http://pypi.python.org/pypi?%3Aaction=search&term=webmail&submit=search) on [pypi](http://pypi.python.org/pypi) gives [Posterity](http://pypi.python.org/pypi/Posterity/). There is very probably some way to build a webmail with very little work using [Zope3](http://www.zope.org/Products/Zope3) comp...
For others who might find this thread, check out [Mailpile](http://www.mailpile.is/). I haven't used it yet, it is a python-based mail client, and I am sure it could be modified to work as a webmail app as well.
Are there any web based email clients written in python?
[ "", "python", "email", "" ]