Prompt
stringlengths
10
31k
Chosen
stringlengths
3
29.4k
Rejected
stringlengths
3
51.1k
Title
stringlengths
9
150
Tags
listlengths
3
7
A query that is used to loop through **17 millions records to remove duplicates** has been running now for about **16 hours** and I wanted to know if the query is stopped right now if it will finalize the delete statements or if it has been deleting while running this query? Indeed, if I do stop it, does it finalize th...
no, sql server will not roll back the deletes it has already performed if you stop query execution. oracle requires an explicit committal of action queries or the data gets rolled back, but not mssql. with sql server it will not roll back unless you are specifically running in the context of a transaction and you roll...
Your query is not wrapped in a transaction, so it won't rollback the changes already made by the individual delete statements. I specifically tested this myself on my own SQL Server using the following query, and the ApplicationLog table was empty even though I cancelled the query: ``` declare @count int select @coun...
If I stop a long running query, does it rollback?
[ "", "sql", "sql-server", "duplicate-data", "" ]
I'm aware I can add maven repositories for fetching dependencies in ~/.m2/settings.xml. But is it possible to add a repository using command line, something like: ``` mvn install -Dmaven.repository=http://example.com/maven2 ``` The reason I want to do this is because I'm using a continuous integration tool where I ha...
You can do this but you're probably better off doing it in the POM as others have said. On the command line you can specify a property for the local repository, and another repository for the remote repositories. The remote repository will have all default settings though The example below specifies two remote reposi...
One of the goals for Maven't Project Object Model (POM) is to capture all information needed to reliably reproduce an artifact, thus passing settings impacting the artifact creation is strongly discouraged. To achieve your goal, you can check in your user-level settings.xml file with each project and use the -s (or --...
Can I add maven repositories in the command line?
[ "", "java", "maven-2", "build-process", "" ]
Ok, so I just ran into the following problem that raised an eyebrow. For various reasons I have a testing setup where Testing classes in a TestingAssembly.dll depend on the TestingBase class in a BaseTestingAssembly.dll. One of the things the TestBase does in the meantime is look for a certain embedded resource in its...
The static constructor is called by the runtime and not directly by user code. You can see this by setting a breakpoint in the constructor and then running in the debugger. The function immediately above it in the call chain is native code. **Edit:** There are a lot of ways in which static initializers run in a differ...
I think the answer is here in the discussion of [C# static constructors](http://msdn.microsoft.com/en-us/library/k9x6w0hc(VS.80).aspx). My best guess is that the static constructor is getting called from an unexpected context because: > The user has no control on when the > static constructor is executed in the > prog...
Assembly.GetCallingAssembly() and static constructors?
[ "", "c#", "reflection", "static-constructor", "" ]
I'm looking for some programming guides to C# GUI design. I come from the Java camp (where I can happily hand-code Swing/AWT GUIs) and thus don't have a clue where to start :( Also, what difference (if any) is there between the Windows Presentation Foundation and WinForms?
Chris Sells seems to be 'dah man' with regard to Windows Forms and WPF: > [http://www.sellsbrothers.com/writing/](https://web.archive.org/web/20120415062302/http://www.sellsbrothers.com/writing/) > [http://www.sellsbrothers.com/writing/wfbook](https://web.archive.org/web/20120507182223/http://www.sellsbrothers.com/w...
**Windows Presentation Foundation** is a vector-based system that is part of .NET 3.0. It allows you to define your UI in XAML, and can do all sorts of animation, 3D, etc. very easily. It's much newer and still being evalulated by a lot of folks. **Windows Forms** is a wrapper over older windows UI classes (Win32/MFC ...
C# .NET 3.5 GUI design
[ "", "c#", ".net", "wpf", "winforms", "user-interface", "" ]
Is there a way to lock a row in the SQL 2005-2008 database without starting a transaction, so other processes cannot update the row until it is unlocked?
You can use [RowLock or other hints](http://blog.sqlauthority.com/2007/04/27/sql-server-2005-locking-hints-and-examples/) but you should be [careful](http://www.sqlteam.com/article/row-locking).. The HOLDLOCK hint will instruct SQL Server to hold the lock until you commit the transaction. The ROWLOCK hint will lock on...
Everything you execute in the server happens in a transaction, either implicit or explicit. You can not simply lock a row with no transaction (make the row read only). You can make the database read only, but not just one row. Explain your purpose and it might be a better solution. Isolation levels and lock hints and...
Locking Row in SQL 2005-2008
[ "", "sql", "sql-server", "locking", "" ]
Is there a way in Firebug to start a new script file to apply to page? Basically I want to do work like I'd normally do on the Firebug console but be able to to paste in multi-line functions, etc. It doesn't seem like the console is amenable to that.
Down in the lower-right corner of the FireBug UI you should see a red square icon with an up arrow. Use that and stretch it to a size you like. --- [![Screenshot](https://i.stack.imgur.com/SE7Ai.gif)](https://i.stack.imgur.com/SE7Ai.gif) [![Screenshot](https://i.stack.imgur.com/eG63w.gif)](https://i.stack.imgur.com/...
maybe not within firebug, but you could try some techniques similar to the jQuery bookmarklet. [bookmarklet link](http://erikandcolleen.com/erik/projects/jquery/bookmarklet/)
Firebug - how can I run multiline scripts or create a new JavaScript file?
[ "", "javascript", "firefox", "firebug", "" ]
According to the documentation, they're pretty much interchangeable. Is there a stylistic reason to use one over the other?
I like to use double quotes around strings that are used for interpolation or that are natural language messages, and single quotes for small symbol-like strings, but will break the rules if the strings contain quotes, or if I forget. I use triple double quotes for docstrings and raw string literals for regular express...
Quoting the official docs at <https://docs.python.org/2.0/ref/strings.html>: > In plain English: String literals can be enclosed in matching single quotes (') or double quotes ("). So there is no difference. Instead, people will tell you to choose whichever style that matches the context, *and to be consistent*. And ...
Single quotes vs. double quotes in Python
[ "", "python", "coding-style", "" ]
I wrote a Java program to add and retrieve data from an MS Access. At present it goes sequentially through ~200K insert queries in ~3 minutes, which I think is slow. I plan to rewrite it using threads with 3-4 threads handling different parts of the hundred thousands records. I have a compound question: * Will this he...
First, don't use Access. Move your data anywhere else -- SQL/Server -- MySQL -- anything. The DB engine inside access (called Jet) is pitifully slow. It's not a real database; it's for personal projects that involve small amounts of data. It doesn't scale at all. Second, threads rarely help. The JDBC-to-Database conn...
1. Don't know. Without knowing more about what the bottle neck is I can't comment if it will make it faster. If the database is the limiter then chances are more threads will slow it down. 2. I would dump the access database to a flat file and then bulk load that file. Bulk loading allows for optimzations which are far...
Will it be faster to use several threads to update the same database?
[ "", "sql", "database", "multithreading", "" ]
What is the difference between this: ``` this.btnOk.Click += new System.EventHandler(this.btnOK_Click); ``` and this? ``` this.btnOk.Click += this.btnOK_Click; ``` They both work. The former is what Visual Studio defaults to when you use the snippets. But it seems like it only ads extra verbiage, or am I missing so...
No difference. Omitting the delegate instantiation is just syntax candy; the C# compiler will generate the delegate instantiation for you under the hood.
In C# 3.0 and later this is no difference. Before C# 3.0 EventHandlers were required due to compiler limitations, but with the advent of C# 3.0, the second form is preferred unless you want to be very explicit.
What is the difference between Events with Delegate Handlers and those without?
[ "", "c#", "events", "" ]
I'm taking a look at how the model system in django works and I noticed something that I don't understand. I know that you create an empty `__init__.py` file to specify that the current directory is a package. And that you can set some variable in `__init__.py` so that import \* works properly. But django adds a bunc...
All imports in `__init__.py` are made available when you import the package (directory) that contains it. Example: `./dir/__init__.py`: ``` import something ``` `./test.py`: ``` import dir # can now use dir.something ``` EDIT: forgot to mention, the code in `__init__.py` runs the first time you import any module ...
It's just personal preference really, and has to do with the layout of your python modules. Let's say you have a module called `erikutils`. There are two ways that it can be a module, either you have a file called *erikutils.py* on your `sys.path` or you have a directory called *erikutils* on your `sys.path` with an e...
Adding code to __init__.py
[ "", "python", "initialization", "package", "" ]
Ever since I started using .NET, I've just been creating Helper classes or Partial classes to keep code located and contained in their own little containers, etc. What I'm looking to know is the best practices for making ones code as clean and polished as it possibly could be. Obviously clean code is subjective, but ...
A real eye-opener to me was [Refactoring: Improving the Design of Existing Code](https://rads.stackoverflow.com/amzn/click/com/0201485672): > With proper training a skilled system > designer can take a bad design and > rework it into well-designed, robust > code. In this book, Martin Fowler > shows you where opportuni...
Jeff Atwood made a [nice blog post on refactoring and code smells](http://blog.codinghorror.com/code-smells/), you might want to check that out. Refactoring code in .NET takes some time to grok. You need to know some object-oriented [design principles](http://books.google.se/books?id=LjJcCnNf92kC) (or [design techniqu...
Refactoring Code: When to do what?
[ "", "c#", "vb.net", "refactoring", "coding-style", "" ]
I'm reading data from a table( from a MySQL Database) with Hibernate SQL Query. The thing is, the table contains a colum that is mapped to a char in Hibernate Model, and sometimes this column is empty. And I suppose this is where my exception comes from. How can I map a colum of char to my hibernate model without getti...
I am assuming from your question that you're mapping this to a primitive character. Next time, please post the stacktrace that you receive (you may leave out where you call it, you could only include the hibernate stuff if your project is too sensitive). If you do map to a primitive character, and it is null, you will...
Search your JBoss (server) whether `mysql.jar` (mysql-connector-java-5.1.7-bin) is present in lib files or not. Even I faced the same problem, after adding the `mysql.jar` file it is working fine.
could not read column value from result set ; String index out of range: 0
[ "", "java", "hibernate", "" ]
I have some decimal data that I am pushing into a SharePoint list where it is to be viewed. I'd like to restrict the number of significant figures displayed in the result data based on my knowledge of the specific calculation. Sometimes it'll be 3, so 12345 will become 12300 and 0.012345 will become 0.0123. Occasionall...
See: [RoundToSignificantFigures](https://stackoverflow.com/questions/374316/round-a-double-to-x-significant-figures-after-decimal-point/374470#374470) by "P Daddy". I've combined his method with another one I liked. Rounding to significant figures is a lot easier in TSQL where the rounding method is based on roundin...
This might do the trick: ``` double Input1 = 1234567; string Result1 = Convert.ToDouble(String.Format("{0:G3}",Input1)).ToString("R0"); double Input2 = 0.012345; string Result2 = Convert.ToDouble(String.Format("{0:G3}", Input2)).ToString("R6"); ``` Changing the G3 to G4 produces the oddest result though. It appears ...
Formatting numbers with significant figures in C#
[ "", "c#", "significant-digits", "" ]
I've been reading through a lot of the rookie Java questions on `finalize()` and find it kind of bewildering that no one has really made it plain that finalize() is an unreliable way to clean up resources. I saw someone comment that they use it to clean up Connections, which is really scary since the only way to come a...
You could use it as a backstop for an object holding an external resource (socket, file, etc). Implement a `close()` method and document that it needs to be called. Implement `finalize()` to do the `close()` processing if you detect it hasn't been done. Maybe with something dumped to `stderr` to point out that you're ...
`finalize()` is a hint to the JVM that it might be nice to execute your code at an unspecified time. This is good when you want code to mysteriously fail to run. Doing anything significant in finalizers (basically anything except logging) is also good in three situations: * you want to gamble that other finalized obj...
Why would you ever implement finalize()?
[ "", "java", "jvm", "finalize", "" ]
example: ``` public static void DoSomething<K,V>(IDictionary<K,V> items) { items.Keys.Each(key => { if (items[key] **is IEnumerable<?>**) { /* do something */ } else { /* do something else */ } } ``` Can this be done without using reflection? How do I say IEnumerable in C#? Should I just use IEnumerabl...
[The previously accepted answer](https://stackoverflow.com/a/74648/1968) is nice but it is wrong. Thankfully, the error is a small one. Checking for `IEnumerable` is not enough if you really want to know about the generic version of the interface; there are a lot of classes that implement only the nongeneric interface....
Thanks very much for this post. I wanted to provide a version of Konrad Rudolph's solution that has worked better for me. I had minor issues with that version, notably when testing if a Type is a nullable value type: ``` public static bool IsAssignableToGenericType(Type givenType, Type genericType) { var interface...
How To Detect If Type is Another Generic Type
[ "", "c#", "" ]
Can't understand why the following takes place: ``` String date = "06-04-2007 07:05"; SimpleDateFormat fmt = new SimpleDateFormat("MM-dd-yyyy HH:mm"); Date myDate = fmt.parse(date); System.out.println(myDate); //Mon Jun 04 07:05:00 EDT 2007 long timestamp = myDate.getTime(); System.out.println(timestamp); //1180955...
What milliseconds? You are providing only minutes information in the first example, whereas your second example grabs current date from the system with milliseconds, what is it you're looking for? ``` String date = "06-04-2007 07:05:00.999"; SimpleDateFormat fmt = new SimpleDateFormat("MM-dd-yyyy HH:mm:ss.S"); Date my...
Instead of using the Sun JDK Time/Date libraries (which leave much to be desired) I recommend taking a look at <http://joda-time.sourceforge.net>. This is a very mature and active sourceforge project and has a very elegant API.
Date.getTime() not including time?
[ "", "java", "date", "timestamp", "gettime", "" ]
[This page](http://www.techonthenet.com/oracle/functions/trunc_date.php]) mentions how to trunc a timestamp to minutes/hours/etc. in Oracle. How would you trunc a timestamp to seconds in the same manner?
Since the precision of `DATE` is to the second (and no fractions of seconds), there is no need to `TRUNC` at all. The data type `TIMESTAMP` allows for fractions of seconds. If you convert it to a `DATE` the fractional seconds will be removed - e.g. ``` select cast(systimestamp as date) from dual; ```
I am sorry, but all my predecessors seem to be wrong. ``` select cast(systimestamp as date) from dual ``` ..does not truncate, but rounds to the next second instead. I use a function: ``` CREATE OR REPLACE FUNCTION TRUNC_TS(TS IN TIMESTAMP) RETURN DATE AS BEGIN RETURN TS; END; ``` For example: ``` SELECT sy...
How to trunc a date to seconds in Oracle
[ "", "sql", "oracle", "" ]
We use [Hudson](http://hudson-ci.org/) as a continuous integration system to execute automated builds (nightly and based on CVS polling) of a lot of our projects. Some projects poll CVS every 15 minutes, some others poll every 5 minutes and some poll every hour. Every few weeks we'll get a build that fails with the f...
This is Hudson issue 715 (~~<http://issues.hudson-ci.org/browse/HUDSON-715>~~). The current recommendation is to set the 'maximum number of simultaneous polling threads' to keep the polling activity down.
See <https://wiki.jenkins-ci.org/display/JENKINS/I%27m+getting+too+many+open+files+error> for what we need from you to fix this kind of problem.
How do you fix "Too many open files" problem in Hudson?
[ "", "java", "exception", "continuous-integration", "build-automation", "hudson", "" ]
I currently am tasked with updating an XML file (persistance.xml) within a jar at a customers site. I can of course unjar the file, update the xml, then rejar the file for redeployment. I would like to kind these command line operations in a Swing App so that the person doing it does not have to drop to the command lin...
The Java API has [classes](http://java.sun.com/javase/6/docs/api/java/util/jar/package-summary.html) for manipulating JAR files.
Sure: ``` File tmp = new File ("tmp"); tmp.mkdirs(); Process unjar = new ProcessBuilder ("jar", "-xf", "myjar.jar", tmp.getName ()).start(); unjar.waitFor(); // TODO read and update persistence.xml Process jar = new ProcessBuilder ("jar", "-cf", "myjar.jar", tmp.getName()).start(); jar.waitFor(); ```
Modify an xml files in a jar file with Java
[ "", "java", "jakarta-ee", "jboss", "jar", "" ]
I have a C# application that includes the following code: ``` string file = "relativePath.txt"; //Time elapses... string contents = File.ReadAllText(file); ``` This works fine, most of the time. The file is read relative to the directory that the app was started from. However, in testing, it has been found that if ...
If the file is always in a path relative to the executable assembly, then yes, use Assembly.Location. I mostly use Assembly.GetExecutingAssembly if applicable though instead of Assembly.GetEntryAssembly. This means that if you're accessing the file from a DLL, the path will be relative to the DLL path.
One spooky place that can change your path is the OpenFileDialog. As a user navigates between folders it's changing your application directory to the one currently being looked at. If the user closes the dialog in a different directory then you will be stuck in that directory. It has a property called [RestoreDirector...
What would cause the current directory of an executing app to change?
[ "", "c#", ".net", "filesystems", "working-directory", "" ]
What I want to do is to remove all accents and umlauts from a string, turning "lärm" into "larm" or "andré" into "andre". What I tried to do was to utf8\_decode the string and then use strtr on it, but since my source file is saved as UTF-8 file, I can't enter the ISO-8859-15 characters for all umlauts - the editor ins...
``` iconv("utf-8","ascii//TRANSLIT",$input); ``` Extended [example](http://php.net/manual/en/function.iconv.php#83238)
A little trick that doesn't require setting locales or having huge translation tables: ``` function Unaccent($string) { if (strpos($string = htmlentities($string, ENT_QUOTES, 'UTF-8'), '&') !== false) { $string = html_entity_decode(preg_replace('~&([a-z]{1,2})(?:acute|cedil|circ|grave|lig|orn|ring|slas...
PHP: Replace umlauts with closest 7-bit ASCII equivalent in an UTF-8 string
[ "", "php", "utf-8", "diacritics", "strtr", "" ]
I'm firing off a Java application from inside of a C# [.NET](http://en.wikipedia.org/wiki/.NET_Framework) console application. It works fine for the case where the Java application doesn't care what the "default" directory is, but fails for a Java application that only searches the current directory for support files. ...
Yes! ProcessStartInfo Has a property called *WorkingDirectory*, just use: ``` ... using System.Diagnostics; ... var startInfo = new ProcessStartInfo(); startInfo.WorkingDirectory = // working directory // set additional properties Process proc = Process.Start(startInfo); ```
Use the [*ProcessStartInfo.WorkingDirectory*](http://msdn.microsoft.com/en-us/library/system.diagnostics.processstartinfo.workingdirectory.aspx "Link to MSDN documentation on ProcessStartInfo.WorkingDirectory") property to set it prior to starting the process. If the property is not set, the default working directory i...
.NET Process.Start default directory?
[ "", "c#", "" ]
I'm looking for a good ASP.NET RichTextBox component that integrates fairly easily with .NET Framework 3.5 Ajax, specifically one that can easily provide its values from inside an UpdatePanel. I got burned by RicherComponents RichTextBox which still does not reference the Framework 3.5. thanks!
Look at FCKEditor for a free solution. I'm unsure if it's usable inside an update panel, but it's free and opensource. <http://www.fckeditor.net/>
If you would consider going with an HTML editor instead of a Rich Text format editor, I recommend the Telerik web editor. It is very flexible and integrates quite solidly with Ajax.
What is the best free, Ajax.NET (System.Web.Extensions 3.5) compatible Rich Text Box control?
[ "", "c#", "asp.net", ".net-3.5", "richtext", "ajax.net", "" ]
What is the best way (in C++) to set up a container allowing for double-indexing? Specifically, I have a list of objects, each indexed by a key (possibly multiple per key). This implies a multimap. The problem with this, however, is that it means a possibly worse-than-linear lookup to find the location of an object. I'...
I'm making several assumptions based on your writeup: * Keys are cheap to copy and compare * There should be only one copy of the object in the system * The same key may refer to many objects, but only one object corresponds to a given key (one-to-many) * You want to be able to efficiently look up which objects corres...
One option would be to use two std::maps that referenced shared\_ptrs. Something like this may get you going: ``` template<typename T, typename K1, typename K2> class MyBiMap { public: typedef boost::shared_ptr<T> ptr_type; void insert(const ptr_type& value, const K1& key1, const K2& key2) { _map1...
Best container for double-indexing
[ "", "c++", "stl", "containers", "" ]
I have a web application where there are number of Ajax components which refresh themselves every so often inside a page (it's a dashboard of sorts). Now, I want to add functionality to the page so that when there is no Internet connectivity, the current content of the page doesn't change and a message appears on the ...
One way to handle this might be to extend the XmlHTTPRequest object with an explicit timeout method, then use that to determine if you're working in offline mode (that is, for browsers that don't support navigator.onLine). Here's how I implemented Ajax timeouts on one site (a site that uses the [Prototype](http://proto...
``` navigator.onLine ``` That should do what you're asking. You probably want to check that in whatever code you have that updates the page. Eg: ``` if (navigator.onLine) { updatePage(); } else { displayOfflineWarning(); } ```
What is the best method to detect offline mode in the browser?
[ "", "javascript", "ajax", "offline-mode", "" ]
Ok I have two modules, each containing a class, the problem is their classes reference each other. Lets say for example I had a room module and a person module containing CRoom and CPerson. The CRoom class contains infomation about the room, and a CPerson list of every one in the room. The CPerson class however some...
**No need to import CRoom** You don't use `CRoom` in `person.py`, so don't import it. Due to dynamic binding, Python doesn't need to "see all class definitions at compile time". If you actually *do* use `CRoom` in `person.py`, then change `from room import CRoom` to `import room` and use module-qualified form `room.C...
Do you actually need to reference the classes at class definition time? ie. ``` class CRoom(object): person = CPerson("a person") ``` Or (more likely), do you just need to use CPerson in the methods of your class (and vice versa). eg: ``` class CRoom(object): def getPerson(self): return CPerson("someone") ...
Python module dependency
[ "", "python", "module", "circular-dependency", "" ]
If you have two jars in your classpath that contain different versions of the same class, the classpath order becomes critical. I am looking for a tool that can detect and flag such potential conflicts in a given classpath or set of folders. Certainly a script that starts: ``` classes=`mktemp` for i in `find . -name...
The [Tattletale](http://www.jboss.org/tattletale) tool from JBoss is another candidate: "Spot if a class/package is located in multiple JAR files"
Looks like [jarfish](http://code.google.com/p/jarfish/wiki/Intro) will do what you want with its "dupes" command.
Is there a tool to discover if the same class exists in multiple jars in the classpath?
[ "", "java", "jar", "classpath", "" ]
I've seen both done in some code I'm maintaining, but don't know the difference. Is there one? let me add that myCustomer is an instance of Customer
The result of both are exactly the same in your case. It will be your custom type that derives from `System.Type`. The only real difference here is that when you want to obtain the type from an instance of your class, you use `GetType`. If you don't have an instance, but you know the type name (and just need the actual...
GetType() is used to find the *actual* type of a object reference at run-time. This can be different from the type of the variable that references the object, because of inheritance. typeof() creates a Type literal that is of the exact type specified and is determined at compile-time.
What is the difference between myCustomer.GetType() and typeof(Customer) in C#?
[ "", "c#", ".net", "" ]
Which is your favorite way to go with strings in C++? A C-style array of `char`s? Or `wchar_t`? `CString`, `std::basic_string`, `std::string`, `BSTR` or `CComBSTR`? Certainly each of these has its own area of application, but anyway, which is your favorite and why?
std::string or std::wstring, depending on your needs. Why? * They're standard * They're portable * They can handle I18N * They have performance guarantees (as per the standard) * Protected against buffer overflows and similar attacks * Are easily converted to other types as needed * Are nicely templated, giving you a ...
**std::string** !! There's a reason why they call it a "Standard". basic\_string is an implementation detail and should be ignored. BSTR & CComBSTR only for interOp with COM, and only for the moment of interop.
How do you handle strings in C++?
[ "", "c++", "string", "" ]
I have a C++ program that when run, by default, displays the X in the upper right corner. Clicking X, minimizes the program. I've added code using the SHInitDialog function to change the X to OK, so that clicking OK exits the program. My question: Is there a better method that applies to the window, since SHInitDialog...
With Windows Mobile 5.0 and higher, using the CreateWindowEx function passing it WS\_EX\_CAPTIONOKBTN for the extended style works. @ctacke SHDoneButton may have also worked but I wanted to change the main window without handling it like a dialogbox, which is basically what SHInitDialog is doing.
Take a look at [SHDoneButton](http://msdn.microsoft.com/en-us/library/aa453682.aspx) API.
On Windows Mobile device, what is the best way to display an OK button instead of the X button?
[ "", "c++", "windows-mobile", "" ]
I'm doing a tech review and looking at AMF integration with various backends (Rails, Python, Grails etc). Lots of options are out there, question is, what do the Adobe products do (BlazeDS etc) that something like RubyAMF / pyAMF don't?
Other than NIO (RTMP) channels, LCDS include also the "data management" features. Using this feature, you basically implement, in an ActionScript class, a CRUD-like interface defined by LCDS, and you get: * automatic progressive list loading (large lists/datagrids loads while scrolling) * automatic crud management (y...
The data management features for LCDS described here are certainly valid, however I believe they do not let you actually develop a solution faster. A developer still has to write ALL the data access code, query execution, extracting data from datareaders into value objects. ALL of this has been solved a dozen of times ...
What does BlazeDS Livecycle Data Services do, that something like PyAMF or RubyAMF not do?
[ "", "python", "ruby-on-rails", "ruby", "apache-flex", "blazeds", "" ]
I have a large 2d array that I serialize and base64\_encode and throw into a database. On a different page I pull the array out and when I `base64_decode` the serialized array I can echo it out and it definitely looks valid. However, if I try to `unserialize(base64_decode($serializedArray))` it just throws the same er...
Are you sure you're just serializing an array, and not an object (e.g. DOMNode?) Like resources, not all classes are going to be happy with being unserialized. As an example with the DOM (which your error suggests to me you're working with), every node has a reference to the parentNode, and if the parentNode doesn't ex...
Make sure that the database field is large enough to hold the serialized array. Serialized data is **very** space-inefficient in PHP, and many DBs (like MySQL) will silently truncate field values that are too long.
PHP unserialize keeps throwing same error over 100 times
[ "", "php", "mysql", "serialization", "" ]
I've updated **php.ini** and moved **php\_mysql.dll** as explained in [steps 6 and 8 here.](https://stackoverflow.com/questions/11919/how-do-i-get-php-and-mysql-working-on-iis-70#94341) I get this error… ``` Fatal error: Call to undefined function mysql_connect() in C:\inetpub... ``` MySQL doesn't show up in my **ph...
As the others say these two values in php.ini are crucial. I have the following in my php.ini: note the trailing slash - not sure if it is needed - but it does work. ``` extension_dir = "H:\apps\php\ext\" extension=php_mysql.dll ``` Also it is worth ensuring that you only have one copy of php.ini on your machine - I...
In the php.ini file, check if the extention path configuration is valid.
How do I install MySQL modules within PHP?
[ "", "php", "mysql", "windows", "" ]
I have an object of the type System.Drawing.Image and want to make every pixel which has some specific color, for example black, transparent (that is, set alpha to 0 for this pixel). What is the best way to do this?
One good approach is to use the **ImageAttributes** class to setup a list of colors to remap when drawing takes place. The advantage of this is good performance as well as allowing you to alter the remapping colors very easily. Try something like this code... ``` ImageAttributes attribs = new ImageAttributes(); List<C...
Construct a Bitmap from the Image, and then call MakeTransparent() on that Bitmap. It allows you to specify a colour that should be rendered as transparent.
Making every pixel of an image having a specific color transparent
[ "", "c#", ".net", "image", "transparency", "" ]
I would like display something more meaningful that animated gif while users upload file to my web application. What possibilities do I have? *Edit: I am using .Net but I don't mind if somebody shows me platform agnostic version.*
Here are a couple of versions of what you're looking for for some common JavaScript toolkits. * Mootools - <http://digitarald.de/project/fancyupload/> * Extjs - <http://extjs.com/learn/Extension:UploadForm>
If you are interested how all this generally works client-site, this is it: All the solutions hook up the form via javascript and change the forms target to a newly created, invisible IFRAME. Then they are free to use AJAX to request some status about the file from the server. The IFRAME trick is needed because all t...
How to implement file upload progress bar on web?
[ "", ".net", "javascript", "ajax", "" ]
I need to replace all WinAPI calls of the * CreateFile, * ReadFile, * SetFilePointer, * CloseHandle with my own implementation (which use low-level file reading via Bluetooth). The code, where functions will be replaced, is Video File Player and it already works with the regular hdd files. It is also needed, that Vid...
I suggest that you follow these steps: 1. Write a set of wrapper functions, e.g MyCreateFile, MyReadFile, etc, that initially just call the corresponding API and pass the same arguments along, unmodified. 2. Use your text editor to search for all calls to the original APIs, and replace these with calls to your new wra...
You could just write your new functions in a custom namespace. e.g. ``` namespace Bluetooth { void CreateFile(/*params*/); void etc... } ``` Then in your code, the only thing you would have to change is: ``` if (::CreateFile(...)) { } ``` to ``` if (Bluetooth::CreateFile(...)) { } ``` Easy! :)
How to replace WinAPI functions calls in the MS VC++ project with my own implementation (name and parameters set are the same)?
[ "", "c++", "winapi", "visual-c++", "" ]
Greetings, I need a way (either via C# or in a .bat file) to get a list of all the computers on a given network. Normally, I use "net view", but this tends to work (from my understanding) only within your domain. I need the names (or at least the IP Addresses) of all computers available on my network. Being able to g...
[Nmap](http://nmap.org/) is good for this - use the -O option for OS fingerprinting and -oX "filename.xml" for [output](http://nmap.org/book/man-output.html) as xml that you can then parse from c#. A suitable commandline would be (where 192.168.0.0/24 is the subnet to scan): ``` nmap -O -oX "filename.xml" 192.168.0.0...
To expand on what Unkwntech has said - You can also do a "broadcast" ping to avoid having to ping each IP address individually. Immediately after than you can use "arp" to examine the ARP cache and get a list of which IP addresses are on which MAC address.
Get a list of all computers on a network w/o DNS
[ "", "c#", ".net", "networking", "batch-file", "" ]
Here's the situation. I have a webservice (C# 2.0), which consists of (mainly) a class inheriting from System.Web.Services.WebService. It contains a few methods, which all need to call a method that checks if they're authorized or not. Basically something like this (pardon the architecture, this is purely as an exampl...
Here is what you need to do to get this to work correctly. It is possible to create your own custom SoapHeader: ``` public class ServiceAuthHeader : SoapHeader { public string SiteKey; public string Password; public ServiceAuthHeader() {} } ``` Then you need a SoapExtensionAttribute: ``` public class A...
You can implement the so-called SOAP extension by deriving from [SoapExtension base](http://msdn.microsoft.com/en-us/library/system.web.services.protocols.soapextension.aspx) class. That way you will be able to inspect an incoming SOAP message and perform validate logic before a particular web method is called.
Call a certain method before each webservice call
[ "", "c#", ".net", "web-services", "" ]
I am using Apache Axis to connect my Java app to a web server. I used wsdl2java to create the stubs for me, but when I try to use the stubs, I get the following exception: ``` org.apache.axis.ConfigurationException: No service named `<web service name>` is available ``` What is happening?
Just a guess, but it looks like that error message is reporting that you've left the service name blank. I imagine the code that generates that error message looks like this: ``` throw new ConfigurationException("No service named" + serviceName + " is available"); ```
According to the [documentation](http://wiki.apache.org/ws/FrontPage/Axis/DealingWithCommonExceptions) linked to by @arnonym, this exception is somewhat misleading. In the first attempt to find the service a ConfigurationException is thrown and caught. It is logged at DEBUG level by the ConfigurationException class. Th...
Apache Axis ConfigurationException
[ "", "java", "apache", "apache-axis", "" ]
Im trying to put an html embed code for a flash video into the `rss feed`, which will then be parser by a parser `(magpie)` on my other site. How should I encode the embed code on one side, and then decode it on the other so I can insert clean html into the `DB` on the receiving server?
Since RSS is XML, you might want to check out CDATA, which I believe is valid in the various RSS specs. <summary><![CDATA[Data Here]]> Here's the w3schools entry on it: <http://www.w3schools.com/XML/xml_cdata.asp>
htmlencode/htmldecode should do the trick.
Whats the best way to pass html embed code via rss feed to a rss parser in php?
[ "", "php", "html", "xml", "validation", "rss", "" ]
How do I cause the page to make the user jump to a new web page after X seconds. If possible I'd like to use HTML but a niggly feeling tells me it'll have to be Javascript. So far I have the following but it has no time delay ``` <body onload="document.location='newPage.html'"> ```
A meta refresh is ugly but will work. The following will go to the new url after 5 seconds: ``` <meta http-equiv="refresh" content="5;url=http://example.com/"/> ``` <http://en.wikipedia.org/wiki/Meta_refresh>
If you are going the JS route just use ``` setTimeout("window.location.href = 'newPage.html';", 5000); ```
Delayed jump to a new web page
[ "", "javascript", "html", "" ]
For all major browsers (except IE), the JavaScript `onload` event doesn’t fire when the page loads as a result of a back button operation — it only fires when the page is first loaded. Can someone point me at some sample cross-browser code (Firefox, Opera, Safari, IE, …) that solves this problem? I’m familiar with Fir...
Guys, I found that JQuery has only one effect: the page is reloaded when the back button is pressed. This has nothing to do with "**ready**". How does this work? Well, JQuery adds an **onunload** event listener. ``` // http://code.jquery.com/jquery-latest.js jQuery(window).bind("unload", function() { // ... ``` By d...
Some modern browsers (Firefox, Safari, and Opera, but not Chrome) support the special "back/forward" cache (I'll call it bfcache, which is a term invented by Mozilla), involved when the user navigates Back. Unlike the regular (HTTP) cache, it captures the complete state of the page (including the state of JS, DOM). Thi...
Is there a cross-browser onload event when clicking the back button?
[ "", "javascript", "pageload", "" ]
I was wondering how to use `cin` so that if the user does not enter in any value and just pushes `ENTER` that `cin` will recognize this as valid input.
You will probably want to try `std::getline`: ``` #include <iostream> #include <string> std::string line; std::getline( std::cin, line ); if( line.empty() ) ... ```
I find that for user input `std::getline` works very well. You can use it to read a line and just discard what it reads. The problem with doing things like this, ``` // Read a number: std::cout << "Enter a number:"; std::cin >> my_double; std::count << "Hit enter to continue:"; std::cin >> throwaway_char; // Hmmmm,...
C++ having cin read a return character
[ "", "c++", "input", "return", "iostream", "cin", "" ]
What's the difference between `TRUNCATE` and `DELETE` in SQL? If your answer is platform specific, please indicate that.
Here's a list of differences. I've highlighted Oracle-specific features, and hopefully the community can add in other vendors' specific difference also. Differences that are common to most vendors can go directly below the headings, with differences highlighted below. --- # General Overview If you want to quickly de...
The difference between truncate and delete is listed below: ``` +----------------------------------------+----------------------------------------------+ | Truncate | Delete | +----------------------------------------+---------------------------------...
What's the difference between TRUNCATE and DELETE in SQL
[ "", "sql", "database", "truncate", "" ]
I need to remove temp files on Tomcat startup, the pass to a folder which contains temp files is in applicationContext.xml. Is there a way to run a method/class only on Tomcat startup?
You could write a `ServletContextListener` which calls your method from the `contextInitialized()` method. You attach the listener to your webapp in web.xml, e.g. ``` <listener> <listener-class>my.Listener</listener-class> </listener> ``` and ``` package my; public class Listener implements javax.servlet.Servlet...
You can also use (starting Servlet v3) an annotated aproach (no need to add anything to web.xml): ``` @WebListener public class InitializeListner implements ServletContextListener { @Override public final void contextInitialized(final ServletContextEvent sce) { } @Override ...
Is there a way to run a method/class only on Tomcat/Wildfly/Glassfish startup?
[ "", "java", "tomcat", "jakarta-ee", "web-applications", "startup", "" ]
I'm trying to run the following SQL statement in Oracle, and it takes ages to run: ``` SELECT orderID FROM tasks WHERE orderID NOT IN (SELECT DISTINCT orderID FROM tasks WHERE engineer1 IS NOT NULL AND engineer2 IS NOT NULL) ``` If I run just the sub-part that is in the IN clause, that runs very quickly in Oracle, ...
Often this type of problem goes away if you analyze the tables involved (so Oracle has a better idea of the distribution of the data) ``` ANALYZE TABLE tasks COMPUTE STATISTICS; ```
The "IN" - clause is known in Oracle to be pretty slow. In fact, the internal query optimizer in Oracle cannot handle statements with "IN" pretty good. try using "EXISTS": ``` SELECT orderID FROM tasks WHERE orderID NOT EXISTS (SELECT DISTINCT orderID FROM tasks WHERE engineer1 IS NOT NULL AND engineer2 ...
Optimising a SELECT query that runs slow on Oracle which runs quickly on SQL Server
[ "", "sql", "sql-server", "oracle", "optimization", "" ]
I'm writing a photo gallery webapp for a friend's wedding and they want a photo gallery for guests to submit the digital photos they take on the day. After evaluating all the options, I've decided the easiest thing for users would be to let them use a familiar interface (their email) and just have them send in the pic...
What MTA are you using? If you use postfix + maildrop you can create a filtering rule that pipes certain messages through a PHP script that then handles the incoming mails. (google for maildrop and `xfilter`).
I used to do a lot of this before, but I can't find the code, here's a scaled down version I found. It should put you on the correct path. I used to run this type of script from a cronjob. Sorry I can't find the final version. ;( ``` // Open pop mailbox if (!$mbox = imap_open ("{localhost:110/pop3/notls}INBOX", "user"...
How to get email and their attachments from PHP
[ "", "php", "email", "" ]
I need to know, from within Powershell, if the current drive is a mapped drive or not. Unfortunately, Get-PSDrive is not working "as expected": ``` PS:24 H:\temp >get-psdrive h Name Provider Root CurrentLocation ---- -------- ---- --------------- H FileSystem H:\ ...
Use the .NET framework: ``` PS H:\> $x = new-object system.io.driveinfo("h:\") PS H:\> $x.drivetype Network ```
A slightly more compact variation on the accepted answer: ``` [System.IO.DriveInfo]("C") ```
In PowerShell, how can I determine if the current drive is a networked drive or not?
[ "", "c#", "powershell", "networking", "mapped-drive", "" ]
I've got a request from a customer to automatically detect the type of mobile device (not the browser, the type. ex: Moto Q, Blackjack II, etc.) and automatically select the device from a drop down with a list of supported devices. So far I've found that the HTTP Headers (submitted by mobile IE) contain information su...
What exactly does the customer mean by "supported". Surely it means that the phone in question supports the web application and it's inner functionality - wouldn't it be better then to forget device detection and simply focus on detecting those capabilities required for the app to function properly? For example, if my ...
You may want to have a look at WURFL, here: <http://wurfl.sourceforge.net/>. From the site: > So... What is WURFL? > The WURFL is an XML configuration file which contains information about capabilities and features of many mobile devices. > > The main scope of the file is to collect as much information as we can abou...
Possible to detect the *type of mobile device* via javascript or HTTP Headers?
[ "", "javascript", "http", "windows-mobile", "http-headers", "" ]
There seem to many ways to skin this particular cat - but which is the best and easiest to implement. It would seem that the ASP.net Membership Provider is the one that will save more time, so my questions are: 1. What are the pros/cons of Membership? 2. How do you integrate the auto generated user db with your own cu...
Membership is lightweight and easy to set up. You can also use the various providers to use Active Directory or some other member location. You shouldn't need to integrate the databases, you can use one to authenticate users and then as long as they are valid, go query another database for the data. This is a good way...
Overall I give it a thumbs up, but there are several minor cons I can think of: * Roles are just strings, there's no way to attach additional information to them without rolling your own code. * Some of the Login controls don't set their default button properly, so hitting the "enter" key while in an input field does ...
New site creation and security/authentication,- should I use ASP.net Membership Provider?
[ "", "c#", "asp.net", "security", "authentication", "asp.net-membership", "" ]
I want to clear the Firebug console of the JavaScript already sent. Does something like `console.clear()` exist and work?
`console.clear();` works for me
If you want to see all the available methods under console: ``` for(var i in console) { console.log(i); } ```
Clear the JavaScript sent to Firebug console
[ "", "javascript", "firebug", "" ]
As part of some error handling in our product, we'd like to dump some stack trace information. However, we experience that many users will simply take a screenshot of the error message dialog instead of sending us a copy of the full report available from the program, and thus I'd like to make some minimal stack trace i...
You should be able to get a StackTrace object instead of a string by saying ``` var trace = new System.Diagnostics.StackTrace(exception); ``` You can then look at the frames yourself without relying on the framework's formatting. See also: [StackTrace reference](http://msdn.microsoft.com/en-us/library/system.diagnos...
Here is the code I use to do this without an exception ``` public static void LogStack() { var trace = new System.Diagnostics.StackTrace(); foreach (var frame in trace.GetFrames()) { var method = frame.GetMethod(); if (method.Name.Equals("LogStack")) continue; Log.Debug(string.Format("{0}::{1}", ...
Print stack trace information from C#
[ "", "c#", "parsing", "error-handling", "stack-trace", "" ]
I've got two arrays of the same size. I'd like to merge the two so the values of one are the key indexes of the new array, and the values of the new array are the values of the other. Right now I'm just looping through the arrays and creating the new array manually, but I have a feeling there is a much more elegant wa...
See [`array_combine()`](http://php.net/array_combine) on PHP.net.
(from the docs for easy reading) array\_combine — Creates an array by using one array for keys and another for its values **Description** `array array_combine ( array $keys , array $values )` Creates an array by using the values from the keys array as keys and the values from the values array as the corresponding v...
Merge two arrays as key value pairs in PHP
[ "", "php", "arrays", "" ]
I want to compress some files (into the [ZIP](http://en.wikipedia.org/wiki/ZIP_%28file_format%29) format) and encrypt them if possible using C#. Is there some way to do this? Can encryption be done as a part of the compression itself?
For compression, look at the [`System.IO.Compression`](http://msdn.microsoft.com/en-us/library/system.io.compression.aspx) namespace and for encryption look at [`System.Security.Cryptography`](http://msdn.microsoft.com/en-us/library/system.security.cryptography.aspx).
For Zip Compression, have you seen <http://www.icsharpcode.net/OpenSource/SharpZipLib/>
Are there any compression and encryption libraries in C#?
[ "", "c#", "encryption", "compression", "" ]
If I use mod\_rewrite to control all my 301 redirects, does this happen before my page is served? so if I also have a bunch of redirect rules in a php script that runs on my page, will the .htaccess kick in first?
When a request is made to the URI affected by the .htaccess file, then Apache will handle any rewrite rules before any of your PHP code executes.
The .htaccess will kick in first. If you look at the Apache request cycle: ![Apache Request Cycle](https://i.stack.imgur.com/3PwIg.gif) PHP is a response handler. mod\_rewrite runs at URI translation, except for rewrite rules in .htaccess and <Directory> or <Location> blocks which run in the fixup phase. This is beca...
What happens first? .htaccess or php code?
[ "", "php", "apache", ".htaccess", "mod-rewrite", "" ]
I was wondering if it is possible to not attach Excel sheet if it is empty, and maybe write a different comment in the email if empty. When I go to report delivery options, there's no such configuration. **Edit**: I'm running SQL Server Reporting Services 2005. Some possible workarounds as mentioned below: [MSDN: R...
I believe the answer is no, at least not out of the box. It shouldn't be difficult to write your own delivery extension given the printing delivery extension sample included in RS.
Yeah, I don't think that is possible. You could use the "NoRows" property of your table to display a message when no data is returned, but that wouldn't prevent the report from being attached. But at least when they opened the excel file it could print out your custom message instead of an empty document.
SQL Server Reporting Services 2005 - How to Handle Empty Reports
[ "", "sql", "reporting-services", "reporting", "report", "" ]
I have a large number of Enums that implement this interface: ``` /** * Interface for an enumeration, each element of which can be uniquely identified by its code */ public interface CodableEnum { /** * Get the element with a particular code * @param code * @return */ public CodableEnum ...
You could factor the duplicated code into a `CodeableEnumHelper` class: ``` public class CodeableEnumHelper { public static CodeableEnum getByCode(String code, CodeableEnum[] values) { for (CodeableEnum e : values) { if (e.getCode().equalsIgnoreCase(code)) { return e; ...
Abstract enums are potentially very useful (and currently not allowed). But a proposal and prototype exists if you'd like to lobby someone in Sun to add it: <http://freddy33.blogspot.com/2007/11/abstract-enum-ricky-carlson-way.html> Sun RFE: <https://bugs.java.com/bugdatabase/view_bug?bug_id=6570766>
How can I eliminate duplicated Enum code?
[ "", "java", "enums", "enumeration", "" ]
I am working with Reporting Services and Sharepoint, I have an application that leverages reporting services however a client would like our application integrated into sharepoint. Currently we are tightly coupled to the ReportService.asmx webservice which exposes various methods for performing operations. Reporting Se...
The most robust solution is to create a CatalogItem interface and create wrappers for each of your web services and hide the whole thing behind a factory. The factory will contain the logic for calling the "correct" web service and the client code will have to be changed to use the interface but it is a change for the ...
I think you are headed in the right direction for this situation, It's just going to take a fair amount more of work to drive it home. I would create some proxy classes that can wrap both versions of the classes using reflection or dynamic methods. I've also seen people use the proxy classes from the remoting namespace...
.NET Architectural issue: 2 Web Services, how do I change which one is used at run time?
[ "", "c#", ".net", "sharepoint", "architecture", "reporting-services", "" ]
What are the most common memory optimizations in csharp, dotnet 2.0. Wanted to see if there common things that people may not be doing by default in winform app
* use structs for small wrapper objects to avoid heap fragmentation * think carefully about object lifetimes, especially for large objects so they do not end up on the LOH unless you intend them to * think about allocations inside of a loop * make sure dynamically sized array will be of reasonable size, otherwise parti...
Use StringBuilder instead of directly modifying a string if you're performing many modifications to the same string.
Common memory optimization
[ "", "c#", "optimization", "memory-management", "" ]
Is global memory initialized in C++? And if so, how? (Second) clarification: When a program starts up, what is in the memory space which will become global memory, prior to primitives being initialized? I'm trying to understand if it is zeroed out, or garbage for example. The situation is: can a singleton reference ...
Yes global primitives are initialized to NULL. Example: ``` int x; int main(int argc, char**argv) { assert(x == 0); int y; //assert(y == 0); <-- wrong can't assume this. } ``` You cannot make any assumptions about classes, structs, arrays, blocks of memory on the heap... It's safest just to always initialize...
From the standard: > Objects with static storage duration (3.7.1) shall be zero-initialized (8.5) before any other initialization takes place. Zero-initialization and initialization with a constant expression are collectively called *static initialization*; all other initialization is *dynamic initialization*. Objects...
Is global memory initialized in C++?
[ "", "c++", "memory", "memory-management", "" ]
I'm trying to install a service using InstallUtil.exe but invoked through `Process.Start`. Here's the code: ``` ProcessStartInfo startInfo = new ProcessStartInfo (m_strInstallUtil, strExePath); System.Diagnostics.Process.Start (startInfo); ``` where `m_strInstallUtil` is the fully qualified path and exe to "InstallUt...
You can indicate the new process should be started with elevated permissions by setting the Verb property of your startInfo object to 'runas', as follows: ``` startInfo.UseShellExecute = true; startInfo.Verb = "runas"; ``` This will cause Windows to behave as if the process has been started from Explorer with the "Ru...
This code puts the above all together and restarts the current wpf app with admin privs: ``` if (IsAdministrator() == false) { // Restart program and run as admin var exeName = System.Diagnostics.Process.GetCurrentProcess().MainModule.FileName; ProcessStartInfo startInfo = new ProcessStartInfo(exeName); ...
Elevating process privilege programmatically?
[ "", "c#", ".net", "windows", "windows-services", "process-elevation", "" ]
I have a website where we use Javascript to submit the login form. On Firefox it prompts the user to remember their password, when they login, but on IE7 it doesn't. After doing some research it looks like the user is only prompted in IE7 when the form is submitted via a Submit control. I've created some sample html t...
Why not try hooking the form submission this way? ``` <html> <head> <title>test autocomplete</title> <script type="text/javascript"> function submitForm() { return true; } </script> </head> <body> <form method="GET" act...
Did you try putting in url in the href and attaching a click event handler to submit the form and returning false from the click handler so that the url does not get navigates to. Alternatively hidden submit button triggered via javascript?
IE7 form not prompted for remember password when submitted through javascript
[ "", "javascript", "html", "internet-explorer-7", "" ]
I've done some research into server push with javascript and have found the general consensus to be that what I'm looking for lies in the "Comet" design pattern. Are there any good implementations of this pattern built on top of jQuery? If not, are there any good implementations of this pattern at all? And regardless o...
I wrote the plugin mentioned by Till. The plugin is an implementation of the [Bayeux](http://cometdproject.dojotoolkit.org/documentation/bayeux) protocol and currently supports long-polling (local server via AJAX) and callback-polling (remote server via XSS). There is a [Bayeux](http://cometdproject.dojotoolkit.org/doc...
Someone built [a client for Comet using jQuery](http://plugins.jquery.com/project/Comet). I don't know if it's any good though. I've read about Comet and heard about all the good it can do, but I have never gotten around to using it. Just had no time and no use case on any of my current projects. I totally forgot to a...
Comet and jQuery
[ "", "javascript", "jquery", "design-patterns", "comet", "server-push", "" ]
When a user on our site loses his password and heads off to the Lost Password page we need to give him a new temporary password. I don't really mind how random this is, or if it matches all the "needed" strong password rules, all I want to do is give them a password that they can change later. The application is a Web...
There's always [`System.Web.Security.Membership.GeneratePassword(int length, int numberOfNonAlphanumericCharacters`)](http://msdn.microsoft.com/en-us/library/system.web.security.membership.generatepassword.aspx).
``` public string CreatePassword(int length) { const string valid = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890"; StringBuilder res = new StringBuilder(); Random rnd = new Random(); while (0 < length--) { res.Append(valid[rnd.Next(valid.Length)]); ...
Generating Random Passwords
[ "", "c#", "passwords", "random", "" ]
I'm having some internationalisation woes: My UTF-8 string fields are being rendered in the browser as ???? after being returned from the database. After retrieval from the database using Hibernate, the String fields are presented correctly on inspection using the eclipse debugger. However Struts2/Tiles is rendering...
You could try something like this. It's taken from sun's page on [Character Sets and Encodings](http://java.sun.com/j2ee/1.4/docs/tutorial/doc/WebI18N5.html). I think this has to be the very first line in your jsp. ``` <%@ page contentType="text/html; charset=UTF-8" %> ```
OMG - it turns out that the cause was a total WTF? all our tile responses were being served by a homegrown servlet that was ignoring the `<%@ page contentType="text/html; charset=UTF-8" %>` directive (and who know what else). `TilesDispatchExtensionServlet` : bloody architecture astronauts, i shake my fist at ye.
Stuts2 Tiles Tomcat suspected of changing UTF-8 to?
[ "", "java", "utf-8", "internationalization", "struts2", "tiles", "" ]
We have the usual **web.xml** for our web application which includes some jsp and jsp tag files. I want to switch to using pre-compiled jsp's. I have the pre-compilation happening in the build ok, and it generates the web.xml fragment and now I want to merge the fragment into the main web.xml. Is there an **include** ...
I use the [Tomcat jasper ANT tasks](http://tomcat.apache.org/tomcat-6.0-doc/jasper-howto.html) in my project, which precompile the JSPs into servlets and add the new servlet mappings to the original web.xml. In the DEV builds, just skip this step and deploy the JSPs without pre-compile and modification of the web.xml. ...
Doh - there is an option on the jasper2 task to auto-merge the fragment into the main web.xml - **addWebXmlMappings** ``` <jasper2 validateXml="false" uriroot="${web.dir}" addWebXmlMappings="true" webXmlFragment="${web.dir}/WEB-INF/classes/jasper_generated_web.xml" outp...
How to merge jsp pre-compiled web.xml fragment with main web.xml using Ant
[ "", "java", "jsp", "tomcat", "ant", "web.xml", "" ]
Can you do a better code? I need to check/uncheck all childs according to parent and when an child is checked, check parent, when all childs are unchecked uncheck parent. ``` $(".parent").children("input").click(function() { $(this).parent().siblings("input").attr("checked", this.checked); }); $(".parent").si...
``` $(".parent").children("input").click(function() { $(this).parent().siblings("input").attr("checked", this.checked); }); $(".parent").siblings("input").click(function() { $(this).siblings("div").children("input").attr("checked", this.checked || $(this).siblings("input[checked]").length>0 ); }); ...
woah, i'm mega confused. it looks as though you have inputs with other inputs inside of them? ...which doesn't make sense. Here's what I *think* your structure looks like, so here I go. ``` <div class="parent"> <input type="checkbox" /> <div> <input type="checkbox" /> <input type="checkbox" /> ...
Check/uncheck parents and children
[ "", "javascript", "jquery", "" ]
I'm creating a networked server for a boggle-clone I wrote in python, which accepts users, solves the boards, and scores the player input. The dictionary file I'm using is 1.8MB (the ENABLE2K dictionary), and I need it to be available to several game solver classes. Right now, I have it so that each class iterates thro...
If you create a dictionary.py module, containing code which reads the file and builds a dictionary, this code will only be executed the first time it is imported. Further imports will return a reference to the existing module instance. As such, your classes can: ``` import dictionary dictionary.words[whatever] ``` w...
Even though it is essentially a singleton at this point, the usual arguments against globals apply. For a pythonic singleton-substitute, look up the "borg" object. That's really the only difference. Once the dictionary object is created, you are only binding new references as you pass it along unless if you explicitly...
Best way to store and use a large text-file in python
[ "", "python", "boggle", "" ]
1. New class is a subclass of the original object 2. It needs to be php4 compatible
You could have your classes instantiated empty and then loaded by any number of methods. One of these methods could accept an instance of the parent class as an argument, and then copy its data from there ``` class childClass extends parentClass { function childClass() { //do nothing } functio...
You can do it with some black magic, although I would seriously question **why** you have this requirement in the first place. It suggests that there is something severely wrong with your design. Nonetheless: ``` function change_class($object, $new_class) { preg_match('~^O:[0-9]+:"[^"]+":(.+)$~', serialize($object)...
How do you copy a PHP object into a different object type
[ "", "php", "oop", "" ]
Jquery has a great language construct that looks like this: ``` $(document).ready(function() { $("a").click(function() { alert("Hello world!"); }); }); ``` As you might guess this, once the document has loaded, binds a custom function to the onClick event of all ***a*** tags. The question is, how can...
Prototype 1.6 provides the [`dom:loaded`](http://prototypejs.org/api/document/observe) event on document: ``` document.observe("dom:loaded", function() { $$('a').each(function(elem) { elem.observe("click", function() { alert("Hello World"); }); }); }); ``` I also use the [`each`](http://prototypejs.or...
``` $(document).observe('dom:loaded', function() { $$('a').invoke('observe', 'click', function() { alert('Hello world!'); }); }); ```
Binding custom functions to DOM events in prototype?
[ "", "javascript", "dom", "prototypejs", "" ]
I am developing a Joomla component and one of the views needs to render itself as PDF. In the view, I have tried setting the content-type with the following line, but when I see the response, it is text/html anyways. ``` header('Content-type: application/pdf'); ``` If I do this in a regular php page, everything works...
Since version 1.5 Joomla has the JDocument object. Use [JDocument::setMimeEncoding()](http://api.joomla.org/Joomla-Framework/Document/JDocument.html#setMimeEncoding) to set the content type. ``` $doc =& JFactory::getDocument(); $doc->setMimeEncoding('application/pdf'); ``` In your special case, a look at [JDocumentPD...
For those of you thinking that the above is a very old answer, I confirm that the JDocument::setMimeEncoding() still works, even on the 1.6 version (haven't tried it on 1.7 yet).
How do I set the Content-type in Joomla?
[ "", "php", "http", "joomla", "content-type", "" ]
What java GUI layout manager does everyone use? Lately, I have been using [MigLayout](http://www.miglayout.com/), which has some powerful component controls. Just wanted to see what other developers are using other than the standard JDK ones.
[MiGLayout](http://www.miglayout.com/) is the GUI layout manager which is widely used by Java Developers.
[GridBagLayout](http://java.sun.com/javase/6/docs/api/java/awt/GridBagLayout.html) is usable. Once you get used to using it, it works great. I think the standard JDK layout managers are pretty powerful on their own. Plus, you get to minimize dependency on 3rd party libraries.
Which Layout Manager do you use?
[ "", "java", "swing", "layout", "" ]
What guidelines do you follow to improve the general quality of your code? Many people have rules about how to write C++ code that (supposedly) make it harder to make mistakes. I've seen people *insist* that every `if` statement is followed by a brace block (`{...}`). I'm interested in what guidelines other people fol...
A few of my personal favorites: Strive to write code that is [const correct](http://www.parashift.com/c++-faq-lite/const-correctness.html). You will enlist the compiler to help weed out easy to fix but sometimes painful bugs. Your code will also tell a story of what you had in mind at the time you wrote it -- valuable...
1. Delete unnecessary code. That is all.
Guidelines to improve your code
[ "", "c++", "coding-style", "" ]
I have normally hand written xml like this: ``` <tag><?= $value ?></tag> ``` Having found tools such as simpleXML, should I be using those instead? What's the advantage of doing it using a tool like that?
Good XML tools will ensure that the resulting XML file properly validates against the DTD you are using. Good XML tools also save a bunch of repetitive typing of tags.
If you're dealing with a small bit of XML, there's little harm in doing it by hand (as long as you can avoid typos). However, with larger documents you're frequently better off using an editor, which can validate your doc against the schema and protect against typos.
When writing XML, is it better to hand write it, or to use a generator such as simpleXML in PHP?
[ "", "php", "xml", "language-agnostic", "" ]
I have a need to convert Pixels to Points in C#. I've seen some complicated explanations about the topic, but can't seem to locate a simple formula. Let's assume a standard 96dpi, how do I calulate this conversion?
There are [72 points per inch](http://en.wikipedia.org/wiki/Point_%28typography%29); if it is sufficient to assume 96 pixels per inch, the formula is rather simple: points = pixels \* 72 / 96 There is a way to get the configured pixels per inch of your display in Windows using [`GetDeviceCaps`](https://msdn.microsoft...
Try this if your code lies in a form: ``` Graphics g = this.CreateGraphics(); points = pixels * 72 / g.DpiX; g.Dispose(); ```
Convert Pixels to Points
[ "", "c#", ".net", "pixel", "point", "" ]
I have always made a point of writing nice code comments for classes and methods with the C# xml syntax. I always expected to easily be able to export them later on. Today I actually have to do so, but am having trouble finding out how. Is there something I'm missing? I want to go *Menu->Build->Build Code Documentatio...
Actually it's in the project properties. Build tab, Output section, XML documentation file, and enter the filename. It will be built on every build of the project. After that you can build the actual help with [Sandcastle](http://www.microsoft.com/downloads/details.aspx?FamilyId=E82EA71D-DA89-42EE-A715-696E3A4873B2&di...
You could try [NDOC](http://ndoc.sourceforge.net/) or [SandCastle](http://www.codeplex.com/Sandcastle) if you dont mind using 3rd party tools.
How do I export the code documentation in C# / VisualStudio 2008?
[ "", "c#", ".net", "visual-studio-2008", "xml-documentation", "" ]
Just how much slower are events? I have written a streaming XML parser (that can handle open-ended and incomplete documents) and by tearing out the events and using an interface instead I got a significant speed boost. Does any one else have any war stories? (Let's not open the GC can of worms here, we all know it's ...
Events firing are delegate invocations, which are a [a bit slower than virtual calls](http://msdn.microsoft.com/en-us/magazine/cc163759.aspx) [![alt text](https://i.stack.imgur.com/xExdh.gif)](https://i.stack.imgur.com/xExdh.gif) (source: [microsoft.com](http://i.msdn.microsoft.com/cc163759.fig02(en-us).gif)) But d...
Events are really just delegates. From what I recall, they were made much faster in the 2.0 CLR. I'm surprised that replacing events with an interface made your code significantly faster - in my experience they're pretty fast, and if you're dealing with XML, I wouldn't have expected the event calls to be the bottleneck...
Events in C#
[ "", "c#", ".net", "performance", "events", "" ]
How do I truncate a java `String` so that I know it will fit in a given number of bytes storage once it is UTF-8 encoded?
Here is a simple loop that counts how big the UTF-8 representation is going to be, and truncates when it is exceeded: ``` public static String truncateWhenUTF8(String s, int maxBytes) { int b = 0; for (int i = 0; i < s.length(); i++) { char c = s.charAt(i); // ranges from http://en.wikipedia.o...
You should use [CharsetEncoder](https://docs.oracle.com/javase/8/docs/api/java/nio/charset/CharsetEncoder.html#encode-java.nio.CharBuffer-java.nio.ByteBuffer-boolean-), the simple `getBytes()` + copy as many as you can can cut UTF-8 charcters in half. Something like this: ``` public static int truncateUtf8(String inp...
How do I truncate a java string to fit in a given number of bytes, once UTF-8 encoded?
[ "", "java", "string", "unicode", "utf-8", "truncate", "" ]
Is there a way to test if an object is a dictionary? In a method I'm trying to get a value from a selected item in a list box. In some circumstances, the list box might be bound to a dictionary, but this isn't known at compile time. I would like to do something similar to this: ``` if (listBox.ItemsSource is Diction...
It should be something like the following. I wrote this in the answer box so the syntax may not be exactly right, but I've made it Wiki editable so anybody can fix up. ``` if (listBox.ItemsSource.IsGenericType && typeof(IDictionary<,>).IsAssignableFrom(listBox.ItemsSource.GetGenericTypeDefinition())) { var me...
Check to see if it implements IDictionary. See the definition of System.Collections.IDictionary to see what that gives you. ``` if (listBox.ItemsSource is IDictionary) { DictionaryEntry pair = (DictionaryEntry)listBox.SelectedItem; object value = pair.Value; } ``` **EDIT:** Alternative when I realized KeyVal...
Testing if an Object is a Dictionary in C#
[ "", "c#", "reflection", "collections", "dictionary", "" ]
Currently I use .Net `WebBrowser.Document.Images()` to do this. It requires the `Webrowser` to load the document. It's messy and takes up resources. According to [this question](https://stackoverflow.com/questions/138313/how-to-extract-img-src-title-and-alt-from-html-using-php) XPath is better than a regex at this. A...
If your input string is valid XHTML you can treat is as xml, load it into an xmldocument, and do XPath magic :) But it's not always the case. Otherwise you can try this function, that will return all image links from HtmlSource : ``` public List<Uri> FetchLinksFromSource(string htmlSource) { List<Uri> links = new...
The big issue with any HTML parsing is the "well formed" part. You've seen the crap HTML out there - how much of it is really well formed? I needed to do something similar - parse out all links in a document (and in my case) update them with a rewritten link. I found the [Html Agility Pack](http://www.codeplex.com/html...
How do you parse an HTML string for image tags to get at the SRC information?
[ "", "c#", ".net", "html", "regex", "xpath", "" ]
How can we connect a `PHP` script to `MS Access (.mdb)` file? I tried by including following `PHP` code: ``` $db_path = $_SERVER['DOCUMENT_ROOT'] . '\WebUpdate\\' . $file_name . '.mdb'; $cfg_dsn = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" . $db_path; $odbcconnect = odbc_connect($cfg_dsn, '', ''); ``` But it fa...
Here's a sample for a connect and a simple select... ``` <?php $db_conn = new COM("ADODB.Connection"); $connstr = "DRIVER={Microsoft Access Driver (*.mdb)}; DBQ=". realpath("./Northwind.mdb").";"; $db_conn->open($connstr); $rS = $db_conn->execute("SELECT * FROM Employees"); $f1 = $rS->Fields(0); $f2 = $rS->Fields(1)...
In the filename, I'm looking at '\WebUpdate\' - it looks like you have one backslash at the beginning at two at the end. Are you maybe missing a backslash at the beginning?
PHP and MS Access
[ "", "php", "ms-access", "" ]
I have a temporary file with data that's returned as part of a SOAP response via a MTOM binary attachment. I would like to trash it as soon as the method call "ends" (i.e., finishes transferring). What's the best way for me to do this? The best way I can figure out how to do this is to delete them when the session is d...
I ran into this same problem. The issue is that the JAX-WS stack manages the file. It is not possible to determine in your code when JAX-WS is done with the file so you do not know when to delete it. In my case, I am using a DataHandler on my object model rather than a file. MyFileResult would have the following field...
Are you using standard java temp files? If so, you can do this: ``` File script = File.createTempFile("temp", ".tmp", new File("./")); ... use the file ... script.delete(); // delete when done. ```
Tomcat 6: how to delete temporary files after a web method call has ended?
[ "", "java", "web-services", "tomcat", "jax-ws", "" ]
I am trying to add a timed delay in a C++ program, and was wondering if anyone has any suggestions on what I can try or information I can look at? I wish I had more details on how I am implementing this timed delay, but until I have more information on how to add a timed delay I am not sure on how I should even attemp...
[In Win32](https://msdn.microsoft.com/en-us/library/windows/desktop/ms686298(v=vs.85).aspx): ``` #include<windows.h> Sleep(milliseconds); ``` [In Unix](http://linux.die.net/man/3/usleep): ``` #include<unistd.h> unsigned int microsecond = 1000000; usleep(3 * microsecond);//sleeps for 3 second ``` `sleep()` only take...
An updated answer for C++11: Use the `sleep_for` and `sleep_until` functions: ``` #include <chrono> #include <thread> int main() { using namespace std::this_thread; // sleep_for, sleep_until using namespace std::chrono; // nanoseconds, system_clock, seconds sleep_for(nanoseconds(10)); sleep_until(sy...
How do you add a timed delay to a C++ program?
[ "", "c++", "time", "" ]
I have a generic method defined like this: ``` public void MyMethod<T>(T myArgument) ``` The first thing I want to do is check if the value of myArgument is the default value for that type, something like this: ``` if (myArgument == default(T)) ``` But this doesn't compile because I haven't guaranteed that T will i...
To avoid boxing, the best way to compare generics for equality is with `EqualityComparer<T>.Default`. This respects `IEquatable<T>` (without boxing) as well as `object.Equals`, and handles all the `Nullable<T>` "lifted" nuances. Hence: ``` if(EqualityComparer<T>.Default.Equals(obj, default(T))) { return obj; } ```...
How about this: ``` if (object.Equals(myArgument, default(T))) { //... } ``` Using the `static object.Equals()` method avoids the need for you to do the `null` check yourself. Explicitly qualifying the call with `object.` probably isn't necessary depending on your context, but I normally prefix `static` calls wit...
Null or default comparison of generic argument in C#
[ "", "c#", "generics", "" ]
I have a function in a native DLL defined as follows: ``` #include <string> void SetPath(string path); ``` I tried to put this in Microsoft's P/Invoke Interop Assistant, but it chokes on the "string" class (which I think is from MFC?). I have tried marshaling it as a variety of different types (C# String, char[], by...
Looks like you're trying to use the C++ standard library string class. I doubt that will be easy to Marshal. Better to stick with a char \* and Marshal as StringBuilder. That's what I usually do. You'll have to add a wrapper that generates the C++ string for you.
The PInvoke interop assistant only supports C not C++. Unfortunately the MFC String class (CString I believe?) is C++ and won't work through the assistant. Instead try using the following ``` void SetPath(__in const WCHAR* path); ```
Marshal C++ "string" class in C# P/Invoke
[ "", ".net", "c++", "string", "interop", "marshalling", "" ]
Which is better to do client side or server side validation? In our situation we are using * jQuery and MVC. * JSON data to pass between our View and Controller. A lot of the validation I do is validating data as users enter it. For example I use the the `keypress` event to prevent letters in a text box, set a max n...
As others have said, you should do both. Here's why: ## Client Side You want to validate input on the client side first because you can give **better feedback to the average user**. For example, if they enter an invalid email address and move to the next field, you can show an error message immediately. That way the ...
Yes, client side validation can be totally bypassed, always. You need to do both, client side to provide a better user experience, and server side to be sure that the input you get is actually validated and not just supposedly validated by the client.
JavaScript: client-side vs. server-side validation
[ "", "javascript", "security", "validation", "" ]
Is it possible to do a cast within a LINQ query (for the compiler's sake)? The following code isn't terrible, but it would be nice to make it into one query: ``` Content content = dataStore.RootControl as Controls.Content; List<TabSection> tabList = (from t in content.ChildControls select...
Try this: ``` from TabSection t in content.ChildControls ``` Also, even if this were not available (or for a different, future scenario you may encounter), you wouldn't be restricted to converting everything to Lists. Converting to a List causes query evaluation on the spot. But if you removing the ToList call, you c...
Depending on what you are trying to do, one of these might do the trick: ``` List<Line> parentLineList1 = (from t in content.ChildControls.OfType<TabSection>() from p in t.ChildControls.OfType<Paragraph>() from pl in p.ChildControls.OfType<Line>() select pl).ToList(); List<Line> parentLineList2 = (from T...
Doing a Cast Within a LINQ Query
[ "", "c#", ".net", "linq", ".net-3.5", "" ]
I'm writing a small web server in Python, using BaseHTTPServer and a custom subclass of BaseHTTPServer.BaseHTTPRequestHandler. Is it possible to make this listen on more than one port? What I'm doing now: ``` class MyRequestHandler(BaseHTTPServer.BaseHTTPRequestHandler): def doGET [...] class ThreadingHTTPServer...
Sure; just start two different servers on two different ports in two different threads that each use the same handler. Here's a complete, working example that I just wrote and tested. If you run this code then you'll be able to get a Hello World webpage at both <http://localhost:1111/> and <http://localhost:2222/> ```...
I would say that threading for something this simple is overkill. You're better off using some form of asynchronous programming. Here is an example using [Twisted](http://twistedmatrix.com/): ``` from twisted.internet import reactor from twisted.web import resource, server class MyResource(resource.Resource): is...
How do I write a python HTTP server to listen on multiple ports?
[ "", "python", "webserver", "" ]
Can you have a multicolumn listview control where one of the columns is a checkbox? Example code or links would be greatly appreciated. I am using visual studio 2005
Allan Anderson created a custom control to let you do this. You can find it here: <http://www.codeproject.com/KB/list/aa_listview.aspx> Here's some example code for that control: ``` GlacialList mylist = new GlacialList(); mylist.Columns.Add( "Column1", 100 ); // this can also be added // through the ...
Better use grid view control, but if you want **only** one column with checkboxes and that column is the **first** one you can just write: ``` this.listView1.CheckBoxes = true; ```
Checkbox in listview control
[ "", "c#", "user-interface", "visual-studio-2005", "checkbox", "" ]
I despise the PHP language, and I'm quite certain that I'm not alone. But the great thing about PHP is the way that mod\_php takes and hides the gory details of integrating with the apache runtime, and achieves CGI-like request isolation and decent performance. What's the shortest-distance approach to getting the same...
Look at [Catalyst](http://www.catalystframework.org/) this MVC (model, view, controller) framework works stand-a-lone or with apache\_perl and hides a lot of the messy bits. There is a slightly odd learning curve (quick start, slower middle, then it really clicks for advanced stuff). Catalyst allows you to use [Templa...
I just saw [Dancer](http://search.cpan.org/dist/Dancer/lib/Dancer.pm). Looks like this might be a good option.
How can I get PHP's (deployment) simplicity but Perl's power?
[ "", "php", "perl", "" ]
It is discouraged to simply catch `System.Exception`. Instead, only the "known" exceptions should be caught. Now, this sometimes leads to unnecessary repetitive code, for example: ``` try { WebId = new Guid(queryString["web"]); } catch (FormatException) { WebId = Guid.Empty; } catch (OverflowException) { ...
Catch `System.Exception` and switch on the types ``` catch (Exception ex) { if (ex is FormatException || ex is OverflowException) { WebId = Guid.Empty; } else throw; } ```
**EDIT:** I do concur with others who are saying that, as of C# 6.0, exception filters are now a perfectly fine way to go: `catch (Exception ex) when (ex is ... || ex is ... )` Except that I still kind of hate the one-long-line layout and would personally lay the code out like the following. I think this is as functio...
Catch multiple exceptions at once?
[ "", "c#", ".net", "exception", "" ]
I have three (C++) classes: Player, Hand, and Card. Player has a member, hand, that holds a Hand. It also has a method, getHand(), that returns the contents of hand. ``` Hand Player::getHand() { return hand; } ``` Hand has a method, addCard(Card c), that adds a card to the hand. I want to do this: player1.getH...
If getHand() is not returning a reference you will be in trouble.
If getHand() returns by-value you're modifying a copy of the hand and not the original.
How to use one object's method to update another object's attribute?
[ "", "c++", "oop", "methods", "" ]
``` SELECT GETDATE() ``` Returns: `2008-09-22 15:24:13.790` I want that date part without the time part: `2008-09-22 00:00:00.000` How can I get that?
*NOTE: This answer returns the original `DATETIME` or `DATETIME2` type. For an expression that returns a true `DATE` type (SQL Server 2008 and later), see [BenR's answer](https://stackoverflow.com/a/126984/1501497) below.* ``` SELECT DATEADD(dd, 0, DATEDIFF(dd, 0, @your_date)) ``` for example ``` SELECT DATEADD(dd, ...
SQLServer 2008 now has a 'date' data type which contains only a date with no time component. Anyone using SQLServer 2008 and beyond can do the following: ``` SELECT CONVERT(date, GETDATE()) ```
How to return only the Date from a SQL Server DateTime datatype
[ "", "sql", "date", "t-sql", "datetime", "sql-server-2008", "" ]
`fopen` is failing when I try to read in a very moderately sized file in `PHP`. `A 6 meg file` makes it choke, though smaller files around `100k` are just fine. i've read that it is sometimes necessary to recompile `PHP` with the `-D_FILE_OFFSET_BITS=64` flag in order to read files over 20 gigs or something ridiculous,...
Are you sure that it's `fopen` that's failing and not your script's timeout setting? The default is usually around 30 seconds or so, and if your file is taking longer than that to read in, it may be tripping that up. Another thing to consider may be the memory limit on your script - reading the file into an array may ...
Did 2 tests with a 1.3GB file and a 9.5GB File. **1.3 GB** **Using `fopen()`** This process used 15555 ms for its computations. It spent 169 ms in system calls. **Using `file()`** This process used 6983 ms for its computations. It spent 4469 ms in system calls. **9.5 GB** **Using `fopen()`** This process used...
Reading very large files in PHP
[ "", "php", "file", "large-files", "" ]
Can I persuade `operator>>` in C++ to read both a `hex` value AND and a `decimal` value? The following program demonstrates how reading hex goes wrong. I'd like the same `istringstream` to be able to read both `hex` and `decimal`. ``` #include <iostream> #include <sstream> int main(int argc, char** argv) { int re...
Use [`std::setbase(0)`](http://en.cppreference.com/w/cpp/io/manip/setbase) which enables prefix dependent parsing. It will be able to parse `10` (dec) as 10 decimal, `0x10` (hex) as 16 decimal and `010` (octal) as 8 decimal. ``` #include <iomanip> is >> std::setbase(0) >> result; ```
You need to tell C++ what your base is going to be. Want to parse a hex number? Change your "is >> result" line to: ``` is >> std::hex >> result; ``` Putting a std::dec indicates decimal numbers, std::oct indicates octal.
Can operator>> read an int hex AND decimal?
[ "", "c++", "hex", "istringstream", "" ]
I want to delete all directories and subdirectories under a root directory that are contain "tmp" in their names. This should include any .svn files too. My first guess is to use ``` <delete> <dirset dir="${root}"> <include name="**/*tmp*" /> </dirset> </delete> ``` This does not seem to work as you...
Here's the answer that worked for me: ``` <delete includeemptydirs="true"> <fileset dir="${root}" defaultexcludes="false"> <include name="**/*tmp*/**" /> </fileset> </delete> ``` I had an added complication I needed to remove `.svn` directories too. With `defaultexcludes`, `.*` files were being exclude...
try: ``` <delete includeemptydirs="true"> <fileset dir="${root}"> <include name="**/*tmp*/*" /> </fileset> </delete> ``` --- ThankYou flicken !
How do I delete a dirset of directories with Ant?
[ "", "java", "ant", "build", "" ]
In Oracle, the number of rows returned in an arbitrary query can be limited by filtering on the "virtual" `rownum` column. Consider the following example, which will return, at most, 10 rows. ``` SELECT * FROM all_tables WHERE rownum <= 10 ``` Is there a simple, generic way to do something similar in Ingres?
Blatantly changing my answer. "Limit 10" works for MySql and others, Ingres uses ``` Select First 10 * from myTable ``` [Ref](http://docs.ingres.com/sqlref/Selectinteractive)
select \* from myTable limit 10 does not work. Have discovered one possible solution: ``` TIDs are "tuple identifiers" or row addresses. The TID contains the page number and the index of the offset to the row relative to the page boundary. TIDs are presently implemented as 4-byte integers. The TID u...
How to limit result set size for arbitrary query in Ingres?
[ "", "sql", "oracle", "ingres", "" ]
What is the simplest way to determine the length (in seconds) of a given mp3 file, **without using outside libraries**? (python source highly appreciated)
You can use [pymad](http://spacepants.org/src/pymad/). It's an external library, but don't fall for the Not Invented Here trap. Any particular reason you don't want any external libraries? ``` import mad mf = mad.MadFile("foo.mp3") track_length_in_milliseconds = mf.total_time() ``` Spotted [here](http://simonwilliso...
For google followers' sake, here are a few more external libs: * mpg321 -t * ffmpeg -i * midentify (mplayer basically) see [Using mplayer to determine length of audio/video file](https://stackoverflow.com/questions/497681/using-mplayer-to-determine-length-of-audio-video-file) * mencoder (pass it invalid params, it wil...
time length of an mp3 file
[ "", "python", "mp3", "media", "duration", "" ]
What is the best way to generate a current datestamp in Java? YYYY-MM-DD:hh-mm-ss
Using the standard JDK, you will want to use java.text.SimpleDateFormat ``` Date myDate = new Date(); SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd:HH-mm-ss"); String myDateString = sdf.format(myDate); ``` However, if you have the option to use the Apache Commons Lang package, you can use org.apache.commons...
``` Date d = new Date(); String formatted = new SimpleDateFormat ("yyyy-MM-dd:HH-mm-ss").format (d); System.out.println (formatted); ```
Generate a current datestamp in Java
[ "", "java", "datestamp", "" ]
I'd like to check if the current browser supports the onbeforeunload event. The common javascript way to do this does not seem to work: ``` if (window.onbeforeunload) { alert('yes'); } else { alert('no'); } ``` Actually, it only checks whether some handler has been attached to the event. Is there a way to det...
I wrote about a more-or-less [reliable inference for detecting event support](http://perfectionkills.com/detecting-event-support-without-browser-sniffing/) in modern browsers some time ago. You can see on a demo page that "beforeunload" is supported in at least Safari 4+, FF3.x+ and IE. **Edit**: This technique is now...
Unfortunately [kangax's answer](https://stackoverflow.com/a/1262811/345716) doesn't work for [Safari on iOS](https://stackoverflow.com/questions/3239834/window-onbeforeunload-not-working-on-the-ipad). In my testing `beforeunload` was supported in every browser I tried exactly except Safari on IOS :-( Instead I suggest...
onbeforeunload support detection
[ "", "javascript", "" ]