Prompt
stringlengths
10
31k
Chosen
stringlengths
3
29.4k
Rejected
stringlengths
3
51.1k
Title
stringlengths
9
150
Tags
listlengths
3
7
I read the following in a review of Knuth's "The Art of Computer Programming": "The very 'practicality' means that the would-be CS major has to learn Kernighan's mistakes in designing C, notably the infamous fact that a for loop evaluates the for condition repeatedly, which duplicates while and fails to match the beha...
Consider this: ``` for i:=0 to 100 do { ... } ``` In this case, we could replace the final value, 100, by a function call: ``` for i:=0 to final_value() do { ... } ``` ... and the `final_value`-function would be called only once. In C, however: ``` for (int i=0; i<final_value(); ++i) // ... ``` ... the `final_va...
If all you want is a simple counting loop, then ``` for (i=0; i<100; i++) dostuff(); ``` will be fine, and the compiler can optimize it. If you use a function in the continue part of the for statement, like ``` for (i=0; i<strlen(s); i++) dostuff(); ``` then the function will be evaluated every time and this is us...
C for loop implemented differently than other languages?
[ "", "c++", "c", "knuth", "" ]
I'd like to create a basic "Hello World" style application for the IPhone using Java - can anyone tell me how?
You can't code in Java for iPhone. The iPhone only supports C/C++/Objective-C - Cocoa. However, under the current license you can use translation tools that generate such code. There are several solutions that do exactly that: [Codename One](http://www.codenameone.com/) - focuses on building applications using Java w...
Might want to check [Alchemo for iphone](http://www.innaworks.com/alcheMo-for-iPhone.html) never used it myself yet. It convert your CLDC 1.1 MIPD 2.0 code into native iPhone code. It even take care of the memory management.
How do I create a "Hello World" application in java for an iphone?
[ "", "java", "iphone", "" ]
We are looking for a open source J2EE Application server for log budget deployments. We are considering JBoss and Glassfish. Which is the best open source application server? Any comparative study available?
JBoss has been used in production environment for over 6 years now. Glassfish's codebase is over 10 years BUT most of the code is recent. Glassfish v3 (still in beta) has a microkernel (so is Jboss 5) architecture. Glassfish has command line tools and a nice console. Since Glassfish is from sun, usually it will work w...
After using JBoss from the very beginning and then switching to Glassfish in the last 6 months, I can honestly say that Glassfish is fast, reliable and full-featured. I would never consider going back. Im not talking "PetStore" here, my experience with these servers is in the high-transaction online stock-trading arena...
Which is the best Open source application server?
[ "", "java", "" ]
First, two examples: ``` // This works int foo = 43; long lFoo = foo; // This doesn't object foo = (int)43; long? nullFoo = foo as long?; // returns null long lFoo = (long)foo; // throws InvalidCastException if (foo.GetType() == typeof(int)) Console.WriteLine("But foo is an int..."); // This gets written out ``` ...
``` object foo = (int) 43; long lFoo = ((IConvertible) foo).ToInt64(null); ```
When you're casting to a value type you're really forcing an unbox IL operation, which requires that the type you're casting to matches *exactly* the boxed value; there are no conversions, implicit, or explicit that can happen at the same time. This usually means that you either need to do a switch using the typecode ...
C# boxing question
[ "", "c#", "icomparable", "unboxing", "" ]
The other day I set up an Ubuntu installation in a VM and went to gather the tools and libraries I figured I would need for programming mostly in C++. I had a problem though, where to put things such as 3rd party source libraries, etc. From what I can gather, a lot of source distributions assume that a lot of their de...
Short answer: don't do a "heaps of code in local dir" thing. Long answer: don't do a "heaps of code in local dir" thing, because it will be nightmare to keep up-to-date, and if you decide to distribute your code, it will be nightmare to package it for any decent distribution. Whenever possible, stick to the libraries...
For libraries/includes... ``` /usr/local/lib /usr/local/include ```
Linux programming environment configuration
[ "", "c++", "linux", "development-environment", "" ]
There's a common way to store multiple values in one variable, by using a bitmask. For example, if a user has read, write and execute privileges on an item, that can be converted to a single number by saying `read = 4 (2^2), write = 2 (2^1), execute = 1 (2^0)` and then add them together to get 7. I use this technique ...
Off the top of my head, I'd write a `set_bit` and `get_bit` function that could take an array of bytes and a bit offset in the array, and use some bit-twiddling to set/get the appropriate bit in the array. Something like this (in C, but hopefully you get the idea): ``` // sets the n-th bit in |bytes|. num_bytes is the...
I've used bit masks in filesystem code where the bit mask is many times bigger than a machine word. think of it like an "array of booleans"; (journalling masks in flash memory if you want to know) many compilers know how to do this *for you*. Adda bit of OO code to have types that operate senibly and then your code s...
Is there a practical limit to the size of bit masks?
[ "", "sql", "bit-manipulation", "bitmask", "" ]
Is there a catchall function somewhere that works well for sanitizing user input for SQL injection and XSS attacks, while still allowing certain types of HTML tags?
It's a common misconception that user input can be filtered. PHP even had a (now defunct) "feature", called [magic-quotes](https://en.wikipedia.org/wiki/Magic_quotes), that builds on this idea. It's nonsense. Forget about filtering (or cleaning, or whatever people call it). What you should do, to avoid problems, is qu...
Do not try to prevent SQL injection by sanitizing input data. Instead, **do not allow data to be used in creating your SQL code**. Use Prepared Statements (i.e. using parameters in a template query) that uses bound variables. It is the only way to be guaranteed against SQL injection. Please see my website <http://bob...
How can I sanitize user input with PHP?
[ "", "php", "security", "xss", "sql-injection", "user-input", "" ]
I've seen [this question](https://stackoverflow.com/questions/49156/importing-javascript-in-jsp-tags) regading the importing of js-files related to the tag content itself. I have a similar problem, here I have a jsp tag that generates some HTML and has a generic js-implementation that handles the behavior of this HTML....
You should strive for javascript in its own files. This is usually done with [Progressive Enhancement](http://accessites.org/site/2007/02/graceful-degradation-progressive-enhancement/). But some times you don't have a choice, for instance when the same JSP renders pages in different languages. Here's a real-life exampl...
I'm not entirely sure what you asking here, but I don't there's anything wrong with including `<script>` tags in the JSP to instantiate javascript code. I often follow this model, writing the library code in external javascript files, and then calling the constructors to my objects from the `<script>` tags. This makes...
Using JavaScript within a JSP tag
[ "", "javascript", "jsp", "jsp-tags", "" ]
I have a console application that require to use some code that need administrator level. I have read that I need to add a Manifest file myprogram.exe.manifest that look like that : ``` <?xml version="1.0" encoding="UTF-8" standalone="yes"?> <assembly xmlns="urn:schemas-microsoft-com:asm.v1" manifestVersion="1.0"> <...
You need to embed the UAC manifest as an embedded Win32 resource. See [Adding a UAC Manifest to Managed Code](http://blogs.msdn.com/shawnfa/archive/2006/04/06/568563.aspx). In short, you use a Windows SDK command line tool to embed it into your executable. You can automate this as a post-build step by placing the fol...
For anyone using Visual Studio, it's super easy. I was about to go set up the Windows SDK and do mt.exe post-build steps and all that before realizing it's built into VS. I figured I'd record it for posterity. 1. Project | Add New Item -> Visual C# Items -> Application Manifest File 2. Open app.manifest, change reques...
UAC need for console application
[ "", "c#", ".net", ".net-2.0", "uac", "manifest", "" ]
I am making a Python gui project that needs to duplicate the look of a Windows gui environment (ie Explorer). I have my own custom icons to draw but they should be selectable by the same methods as usual; click, ctrl-click, drag box etc. Are any of the gui toolkits going to help with this or will I have to implement it...
Python has extensions for accessing the Win32 API, but good luck trying to re-write explorer in *that* by yourself. Your best bet is to use a toolkit like [Qt](http://doc.trolltech.com/4.4/gallery-windowsxp.html), but you'll still have to write the vast majority of the application from scratch. Is there any way you ca...
In wxPython there's a plethora of ready-made list and tree controls (CustomTreeCtrl, TreeListCtrl, and others), a mixture of which you can use to create a simple explorer in minutes. The wxPython demo even has a few relevant examples (see the demo of MVCTree).
Something like Explorer's icon grid view in a Python GUI
[ "", "python", "user-interface", "" ]
I'm relatively new to Python and am having problems programming with Scapy, the Python network manipulation tool. However, I can't tell if it's as much a Scapy problem as it is a being-a-Python-newbie problem. On the [scapy site](http://www.secdev.org/projects/scapy/build_your_own_tools.html), they give a sample progra...
With the caveat from Federico Ramponi "You should use scapy as an interpreter by its own, not as a library", I want to answer the non-scapy-specific parts of the question. **Q:** when installing Python libraries, do I need to change my path or anything similar? **A:** I think you are talking about changing `PYTHONPAT...
I had the same problem, in the scapy v2.x use ``` from scapy.all import * ``` instead the v1.x ``` from scapy import * ``` as written [here](http://www.secdev.org/projects/scapy/doc/installation.html) Enjoy it =)
Python - Library Problems
[ "", "python", "networking", "scapy", "" ]
I would like to implement an interactive evolutionary algorithm for generating music (probably just simple melodies to start with). I'd like to use [JFugue](http://www.jfugue.org) for this. Its website claims that it is well-suited to evolutionary music, but I can't find any evolutionary examples. I already have [a f...
So far I've found only [this](http://graphics.stanford.edu/~bjohanso/gp-music/gp_music-old.html), which is a genetic programming example in C. **Update (January 2010):** And [this online system](http://darwintunes.org/), which doesn't have source code but is an example of what can be achieved. I also found [Grammidity...
You probably want to look into *Markov Chains* - They're probably of more use to you than an evolutionary algorithm to start with, as judging the quality of the output in order to breed the best is going to be a nightmare (subjective and time-consuming), and they're ideal for combining with evolutionary programming. T...
Looking for evolutionary music example code
[ "", "java", "genetic-algorithm", "evolutionary-algorithm", "jfugue", "" ]
I'm currently adding some new extended classes to this code: ``` foreach (BaseType b in CollectionOfExtendedTypes) { if (b is ExtendedType1) { ((ExtendedType1) b).foo = this; } else if (b is ExtendedType2) { ((ExtenedType2) b).foo = this; } else { b.foo = this; } } ``` and was curious if t...
This really looks like a situation for a good polymorphic implementation. If you override the appropriate methods in the derived classes, you may not need the checks in the loop at all.
The latest version of C# (7) now includes this functionality [Type pattern](https://learn.microsoft.com/en-us/dotnet/csharp/language-reference/keywords/switch#type-pattern) The type pattern enables concise type evaluation and conversion. When used with the switch statement to perform pattern matching, it tests whethe...
using the 'is' keyword in a switch in c#
[ "", "c#", "switch-statement", "" ]
I have a grid that is binded to a collection. For some reason that I do not know, now when I do some action in the grid, the grid doesn't update. Situation : When I click a button in the grid, it increase a value that is in the same line. When I click, I can debug and see the value increment but the value doesn't chan...
In order for the binding to be bidirectional, from control to datasource and from datasource to control the datasource must implement property changing notification events, in one of the 2 possible ways: * Implement the [INotifyPropertyChanged](https://learn.microsoft.com/en-us/dotnet/api/system.componentmodel.inotify...
It sounds like you need to call DataBind in your update code.
C# grid binding not update
[ "", "c#", "data-binding", "datagridview", "" ]
A strict equality operator will tell you if two object **types** are equal. However, is there a way to tell if two objects are equal, **much like the hash code** value in Java? Stack Overflow question *[Is there any kind of hashCode function in JavaScript?](https://stackoverflow.com/questions/194846)* is similar to th...
**The short answer** The simple answer is: No, there is no generic means to determine that an object is equal to another in the sense you mean. The exception is when you are strictly thinking of an object being typeless. **The long answer** The concept is that of an Equals method that compares two different instance...
Why reinvent the wheel? Give [Lodash](http://lodash.com/docs#isEqual) a try. It has a number of must-have functions such as [isEqual()](http://lodash.com/docs#isEqual). ``` _.isEqual(object, other); ``` It will brute force check each key value - just like the other examples on this page - using [ECMAScript 5](http://...
How can I determine equality for two JavaScript objects?
[ "", "javascript", "object", "equals", "hashcode", "" ]
Is it possible to reference system environment variables (as opposed to Java system properties) in a log4j xml configuration file? I'd like to be able to do something like: ``` <level value="${env.LOG_LEVEL}" /> ``` and have it get that from the system environment variables, so I can avoid having to pass in so many ...
This syntax is documented only in log4j 2.X so make sure you are using the correct version. It does not work on the 1.X versions. ``` <Appenders> <File name="file" fileName="${env:LOG_PATH}"> <PatternLayout> <Pattern>%d %p %c{1.} [%t] %m %ex%n</Pattern> </PatternLayout> </File> ...
I tried to do that recently and couldn't get it to work. What I ended up doing is sending a variable at startup. So say you have an environment variable called $LOG\_LEVEL: ``` <level value="${log_level}" /> ``` and at startup... ``` java -Dlog_level=$LOG_LEVEL your_app ```
Using system environment variables in log4j xml configuration
[ "", "java", "xml", "configuration", "log4j", "environment-variables", "" ]
I need to convert a Word document into HTML file(s) in Java. The function will take input an word document and the output will be html file(s) based on the number of pages the word document has i.e. if the word document has 3 pages then there will be 3 html files generated having the required page break. I searched fo...
We use tm-extractors (<http://mvnrepository.com/artifact/org.textmining/tm-extractors>), and fall back to the commercial Aspose (<http://www.aspose.com/>). Both have native Java APIs.
I recommend the [JODConverter](http://www.artofsolving.com/opensource/jodconverter), It leverages OpenOffice.org, which provides arguably the best import/export filters for OpenDocument and Microsoft Office formats available today. JODConverter has a lot of documents, scripts, and tutorials to help you out.
Convert Word doc to HTML programmatically in Java
[ "", "java", "html", "ms-word", "" ]
In Java, suppose I have a String variable S, and I want to search for it inside of another String T, like so: ``` if (T.matches(S)) ... ``` (note: the above line was T.contains() until a few posts pointed out that that method does not use regexes. My bad.) But now suppose S may have unsavory characters in it. For...
[`String.contains`](https://docs.oracle.com/en/java/javase/17/docs/api/java.base/java/lang/String.html#contains(java.lang.CharSequence)) does not use regex, so there isn't a problem in this case. Where a regex is required, rather rejecting strings with regex special characters, use [`java.util.regex.Pattern.quote`](ht...
As [Tom Hawtin](https://stackoverflow.com/questions/168639/escaping-a-string-from-getting-regex-parsed-in-java#168652) said, you need to quote the pattern. You can do this in two ways (edit: actually three ways, as pointed out by @[diastrophism](https://stackoverflow.com/questions/168639/escaping-a-string-from-getting-...
Escaping a String from getting regex parsed in Java
[ "", "java", "regex", "string", "escaping", "" ]
What is the best way to save enums into a database? I know Java provides `name()` and `valueOf()` methods to convert enum values into a String and back. But are there any other (flexible) options to store these values? Is there a smart way to make enums into unique numbers (`ordinal()` is not safe to use)? #### Upda...
We *never* store enumerations as numerical ordinal values anymore; it makes debugging and support way too difficult. We store the actual enumeration value converted to string: ``` public enum Suit { Spade, Heart, Diamond, Club } Suit theSuit = Suit.Heart; szQuery = "INSERT INTO Customers (Name, Suit) " + "...
Unless you have specific performance reasons to avoid it, I would recommend using a separate table for the enumeration. Use foreign key integrity unless the extra lookup really kills you. ### Suits table: ``` suit_id suit_name 1 Clubs 2 Hearts 3 Spades 4 Diamonds ``` ### Players table ``` pl...
Ways to save enums in database
[ "", "java", "database", "enums", "" ]
I need to serialize a huge amount of data (around 2gigs) of small objects into a single file in order to be processed later by another Java process. Performance is kind of important. Can anyone suggest a good method to achieve this?
Have you taken a look at google's [protocol buffers](http://code.google.com/p/protobuf/)? Sounds like a use case for it.
I don't know why Java Serialization got voted down, it's a perfectly viable mechanism. It's not clear from the original post, but is all 2G of data in the heap at the same time? Or are you dumping something else? Out of the box, Serialization isn't the "perfect" solution, but if you implement Externalizable on your o...
Java: Serializing a huge amount of data to a single file
[ "", "java", "serialization", "" ]
I am building Java web applications, and I hate the traditional "code-compile-deploy-test" cycle. I want to type in one tiny change, then see the result INSTANTLY, without having to compile and deploy. Fortunately, [Jetty](http://www.mortbay.org/jetty/) is great for this. It is a pure-java web server. It comes with a ...
Jetty uses memory-mapped files to buffer static content, which causes the file-locking in Windows. Try setting `useFileMappedBuffer` for `DefaultServlet` to `false`. [Troubleshooting Locked files on Windows (from the Jetty wiki)](http://www.eclipse.org/jetty/documentation/current/troubleshooting-locked-files-on-window...
While one of the answers above is exactly right for configuring jetty by xml, if you want to configure this option in code (for an embedded server) the answer is different and not found on that page. You'll find a number of suggestions online including context.getInitParams().put("useFileMappedBuffer", "false"); Or ...
How to make Jetty dynamically load "static" pages
[ "", "java", "spring", "jetty", "" ]
I have a regexp I'm using with sed, but now I need to make it work in PHP also. I can't use system calls as they are disabled. ``` $ cat uglynumber.txt: Ticket number : 303905694, FOO:BAR:BAR: Some text Case ID:123,456,789:Foobar - Some other text 303867970;[FOOBAR] Some text goes here Case Ref: 303658850 - Some rando...
Your specific SED example is obviously 2 regular expressions, 1 being replacing the commas, and one being technically grabbing the 9 digit continuous numbers. The first half of your SED string is best fit with the `preg_replace()` function. ``` //`sed s/regex/replace_value/flags` preg_replace('/regex/flags', 'replac...
Try using [`preg_replace()`](https://www.php.net/preg_replace) instead of `preg_match()`. `grep` is to `sed` what `preg_match` is to `preg_replace`.
Converting a sed string to PHP
[ "", "php", "regex", "" ]
I am trying to prevent data races in a multihreaded server. My problem is the following: there is a `List<RServer>`, the type `RServer` is a class with several fields. Now, the server has several threads all running at the same time and they can modify both the `List` (adding more items) and the individual `RServer` in...
If you have a contended lock, the second thread has to wait until the first releases the lock. Your plan sounds *nearly* okay - but you need to lock when *reading* data as well, to make sure you get the most recent values, and consistent ones. Otherwise you could be half way through writing some values in one thread, ...
Looks like you have a prime candidate for a ReaderWriterLock. The best class to use (if your runtime supports it, I think 3.0+) is ReaderWriterLockSlim as the original ReaderWriterLock has performance issues. One of the MSDN magazine authors also came across a problem with the RWLS class, I won't go into the specifics...
c# locking
[ "", "c#", "multithreading", "locking", "" ]
Given an `InputStream` called `in` which contains audio data in a compressed format (such as MP3 or OGG), I wish to create a `byte` array containing a WAV conversion of the input data. Unfortunately, if you try to do this, JavaSound hands you the following error: ``` java.io.IOException: stream length not specified ``...
The problem is that the most AudioFileWriters need to know the file size in advance if writing to an OutputStream. Because you can't provide this, it always fails. Unfortunatly, the default Java sound API implementation doesn't have any alternatives. But you can try using the AudioOutputStream architecture from the Tr...
I notice this one was asked very long time ago. In case any new person (using Java 7 and above) found this thread, note there is a better new way doing it via Files.readAllBytes API. See: [How to convert .wav file into byte array?](https://stackoverflow.com/questions/13802441/how-to-convert-wav-file-into-byte-array)
Convert audio stream to WAV byte array in Java without temp file
[ "", "java", "audio", "wav", "javasound", "" ]
I have heard mixed opinions over the amount of memory that a byte takes up in a java program. I am aware you can store no more than +127 in a java byte, and the [documentation](http://java.sun.com/docs/books/tutorial/java/nutsandbolts/datatypes.html) says that a byte is only 8 bits but [here](http://www.jguru.com/faq/...
Okay, there's been a lot of discussion and not a lot of code :) Here's a quick benchmark. It's got the normal caveats when it comes to this kind of thing - testing memory has oddities due to JITting etc, but with suitably large numbers it's useful anyway. It has two types, each with 80 members - LotsOfBytes has 80 byt...
Yes, a byte variable in Java is in fact 4 bytes in memory. However this doesn't hold true for arrays. The storage of a byte array of 20 bytes is in fact only 20 bytes in memory. That is because the Java Bytecode Language only knows two integer number types: ints and longs. So it must handle all numbers internally as e...
Size of a byte in memory - Java
[ "", "java", "performance", "memory", "" ]
I have a class that I need to binary serialize. The class contains one field as below: ``` private T[,] m_data; ``` These multi-dimensional arrays can be fairly large (hundreds of thousands of elements) and of any primitive type. When I tried standard .net serialization on an object the file written to disk was large...
Here's what I came up with. The code below makes an int[1000][10000] and writes it out using the BinaryFormatter to 2 files - one zipped and one not. The zipped file is 1.19 MB (1,255,339 bytes) Unzipped is 38.2 MB (40,150,034 bytes) ``` int width = 1000; int height = 10000; List<int[]> list =...
The best code length/output size ratio would be to encode your array using BitConverter, converting all elements into their compact binary format. It's manual, I know, but will save 80-90% space compared to .NET binary serialization.
Optimising binary serialization for multi-dimensional generic arrays
[ "", "c#", ".net", "serialization", "binary", "" ]
As a followup to my [question about the java.awt.Component.getName() property](https://stackoverflow.com/questions/227143/java-what-is-javaawtcomponentgetname-and-setname-used-for), I'm wondering if there is a way of squirreling an arbitrary object somewhere in a Component, similar to the [tag property in .NET](http://...
I generally create a hash and put (component, cookie) whenever I add a component to the screen. When you need your cookie object back (in an event perhaps), the event always gets a copy of the component, and then you are just a get(component) away from your cookie. In some extreme conditions, I've subclassed the contr...
`JComponent` has `putClientProperty` and `getClientProperty`.
Java: Any way of squirreling an object about a Component somewhere in the Component?
[ "", "java", "awt", "" ]
We are using a WCF service layer to return images from a repository. Some of the images are color, multi-page, nearly all are TIFF format. We experience slowness - one of many issues. 1.) What experiences have you had with returning images via WCF 2.) Do you have any suggestions tips for returning large images? 3.) Al...
Okay Just to second the responses by ZombieSheep and Seba Gomez, you should definitely look at streaming your data. By doing so you could seamlessly integrate the GZipStream into the process. On the client side you can reverse the compression process and convert the stream back to your desired image. By using streamin...
If you are using another .Net assembly as your client, you can use two methodologies for returning large chunks of data, streaming or MTOM. Streaming will allow you to pass a TIFF image as if it were a normal file stream on the local filesystem. See [here](http://msdn.microsoft.com/en-us/library/aa751889.aspx) for mor...
WCF - returning large images - your experience and tips on doing so
[ "", "c#", ".net", "wcf", "" ]
I have a .NET web-service client that has been autogenerated from a wsdl-file using the wsdl.exe tool. When I first instantiate the generated class, it begins to request a bunch of documents from w3.org and others. The first one being <http://www.w3.org/2001/XMLSchema.dtd> Besides not wanting to cause unnecessary tra...
I needed the XmlResolver, so [tamberg's solution](https://stackoverflow.com/questions/217841/net-autogenerated-web-service-client-how-do-i-avoid-requesting-schemas-from-w3o#218105) did not quite work. I solved it by implementing my own XmlResolver that read the necessary schemas from embedded resources instead of downl...
if you have access to the XmlReader (or XmlTextReader) you can do the following: ``` XmlReader r = ... r.XmlResolver = null; // prevent xsd or dtd parsing ``` Regards, tamberg
.NET autogenerated web-service client: How do I avoid requesting schemas from w3.org?
[ "", "c#", ".net", "web-services", "wsdl", "offline", "" ]
I am trying to link to a file that has the '#' character in via a window.open() call. The file does exist and can be linked to just fine using a normal anchor tag. I have tried escaping the '#' character with '%23' but when the window.open(myurl) gets processed, the '%23' becomes '%2523'. This tells me that my url str...
You seek the dark magicks of [encodeURI](http://www.w3schools.com/jsref/jsref_encodeURI.asp): ``` window.open("http://your-url.com/" + encodeURIComponent("foo#123.jpg")); ```
Did you try using the standard text escape char "\"? ``` \# ```
javascript window.open() and # symbol
[ "", "javascript", "url-rewriting", "" ]
In few months I start a project in PHP and I am hesitating to do like usual : develop on my Windows Vista 64bits machine. Since I know few things on Linux, I think it can be a good way to learn by working on a Linux distribution. **Do you think it's a good idea or not?** I would run a [VirtualBox](http://www.virtualbo...
You should really develop on the same platform where you are going to deploy. I'm not saying it is bad to do differently, but it can save you some pain in the long run. OTOH, you might learn faster about platform differences that way. So, the main question is: do you want to have a production system running ASAP withou...
PHP **should** be the same on any platform - so *where* you develop shouldn't matter. However, in my experience and observation,more sites running PHP are running on Linux than Windows. Getting Apache and PHP setup on something like Ubuntu or Fedora is a cinch, and testing everything is pretty simple, too. Also, whe...
PHP website, should I develop into a Linux distribution instead of Windows?
[ "", "php", "linux", "xampp", "virtualbox", "" ]
As a new Eclipse user, I am constantly annoyed by how long it takes compiler error messages to display. This is mostly only a problem for long errors that don't fit in the status bar or the "Problems" tab. But I get enough long errors in Java—especially with generics—that this is a nagging issue. (Note: The correct ans...
Well, you can press F2 to display the popup that normally shows javadoc. If there's an error, it will display the error message with available quick fixes. So you can do Ctrl+., F2 repeatedly to achieve what you want.
> "After a noticeable lag, the error message > appears as a "tool tip", along with > any associated "Quick Fixes." Dont know if this will help you but you can reduce the lag in the pop up by changing the value of auto activation delay in the in the menu located at: ``` Window>Preferences>Java>>Editor>ContentAssist ``...
Fast compiler error messages in Eclipse
[ "", "java", "eclipse", "ide", "" ]
I have an array I've created in JavaScript. The end result comes out to element1,element2,,,element5,element6,,,element9.... etc Once passed to ColdFusion, it removes the null elements, I end up with element1,element2,element5,element6,element9 I need to maintain these spaces, any ideas? My problem may begin before t...
Are you deserializing the jS array into a list? CF ignores empty list fields using its built-in functions. This can be worked around by processing the text directly. Someone has already done this for you, fortunately. There are several functions at cflib.org, like: * [ListFix](http://cflib.org/udf/ListFix) * [ListLenI...
In exchanging data between javascript and coldfusion have a look at using JSON. <http://www.json.org> <http://www.epiphantastic.com/cfjson/>
JavaScript array to ColdFusion
[ "", "javascript", "jquery", "forms", "coldfusion", "" ]
I've been writing a little application that will let people upload & download files to me. I've added a web service to this applciation to provide the upload/download functionality that way but I'm not too sure on how well my implementation is going to cope with large files. At the moment the definitions of the upload...
[Stephen Denne](https://stackoverflow.com/q/132618/16800) has a Metro implementation that satisfies your requirement. My answer is provided below after a short explination as to why that is the case. Most Web Service implementations that are built using HTTP as the message protocol are REST compliant, in that they onl...
Yes, it is possible with Metro. See the [Large Attachments](https://metro.java.net/guide/ch06.html#large-attachments) example, which looks like it does what you want. > JAX-WS RI provides support for sending and receiving large attachments in a streaming fashion. > > * Use MTOM and DataHandler in the programming model...
Can a web service return a stream?
[ "", "java", "web-services", "cxf", "" ]
We have a number of projects that use the same and/or similar package names. Many or these projects will build jar files that are used by other projects. We have found a number of foo.util foo.db and foo.exceptions where the same class names are being used leading to name space conflicts. Does anyone know of a tool th...
It's simpler to fix your names in each individual project. Really. You don't need to **know** all the conflicts. Your package names should be unique in the first place. If they aren't unique, you need to rethink how you're assigning your package names. If they're "flat" (`foo.this` and `foo.that`) you need to make th...
If you can load the projects into Eclipse, the Problems view will give you the conflicts and ambiguous imports. There is also a organize imports wizard that will help with any unnecessary imports.
Tool for finding package namespace conflicts in java code
[ "", "java", "refactoring", "" ]
I'm trying to select a random 10% sampling from a small table. I thought I'd just use the RAND() function and select those rows where the random number is less than 0.10: ``` SELECT * FROM SomeTable WHERE SomeColumn='SomeCondition' AND RAND() < 0.10 ``` But I soon discovered that RAND() always returns the same ...
This type of approach (shown by ΤΖΩΤΖΙΟΥ) will not guarantee a 10% sampling. It will only give you all rows where Rand() is evaluated to < .10 which will not be consistent. Something like ``` select top 10 percent * from MyTable order by NEWID() ``` will do the trick. **edit:** there is not really a good way to mak...
If your table has a column (perhaps even the **rowid** column) that is numeric in the general sense, like integer, floating point or SQL numeric, please try the following: ``` SELECT * FROM SomeTable WHERE SomeColumn='SomeCondition' AND 0*rowid+RAND() < 0.10 ``` In order to evaluate `RAND()` once for *every row*, not...
What am I doing wrong when using RAND() in MS SQL Server 2005?
[ "", "sql", "sql-server", "random", "" ]
I have the following code: ``` MemoryStream foo(){ MemoryStream ms = new MemoryStream(); // write stuff to ms return ms; } void bar(){ MemoryStream ms2 = foo(); // do stuff with ms2 return; } ``` Is there any chance that the MemoryStream that I've allocated will somehow fail to be disposed of...
If something is Disposable, you should always Dispose it. You should be using a `using` statement in your `bar()` method to make sure `ms2` gets Disposed. It will eventually get cleaned up by the garbage collector, but it is always good practice to call Dispose. If you run FxCop on your code, it would flag it as a war...
You won't leak anything - at least in the current implementation. Calling Dispose won't clean up the memory used by MemoryStream any faster. It *will* stop your stream from being viable for Read/Write calls after the call, which may or may not be useful to you. If you're absolutely sure that you *never* want to move ...
Is a memory leak created if a MemoryStream in .NET is not closed?
[ "", "c#", ".net", "memory-leaks", "memorystream", "" ]
I have a 2D character array: `char nm[MAX1][MAX2] = { "john", "bob", "david" };` I want to swap two of these elements (without `std::swap`) by simply writing `swapPointers(nm[0], nm[1]);` where `swapPointers` looks like this ``` void swapPointers(char *&a, char *&b) { char *temp = a; a = b; ...
Zan is close, but his problem is that his 'swap' function can take any pointer to characters. This can cause problems if misused. Here is a safer version: ``` void swap(char (&x)[MAX2], char (&y)[MAX2]) { char temp[MAX2]; memcpy(temp, x, MAX2); memcpy(x, y, MAX2); memcpy(y, temp, MAX2); } ``` There i...
You cannot swap those pointers by reassigning the pointers, because those pointers point into a 2-D character array. nm[a] and nm[b] are very strongly `const` because nm is a truly `const` object. If it wasn't, you could move C variables around in RAM by reassigning their names. Just think of the havoc! So you can't ...
Transparently swapping pointers to character arrays in C++
[ "", "c++", "pointers", "" ]
I'm writing a routine that validates data before inserting it into a database, and one of the steps is to see if numeric values fit the precision and scale of a Numeric(x,y) SQL-Server type. I have the precision and scale from SQL-Server already, but what's the most efficient way in C# to get the precision and scale o...
``` System.Data.SqlTypes.SqlDecimal.ConvertToPrecScale( new SqlDecimal (1234.56789), 8, 2) ``` gives 1234.57. it will truncate extra digits after the decimal place, and will throw an error rather than try to truncate digits before the decimal place (i.e. ConvertToPrecScale(12344234, 5,2)
Without triggering an exception, you could use the following method to determine if the value fits the precision and scale constraints. ``` private static bool IsValid(decimal value, byte precision, byte scale) { var sqlDecimal = new SqlDecimal(value); var actualDigitsToLeftOfDecimal = sqlDecimal.Precision - ...
What is an efficient way to check the precision and scale of a numeric value?
[ "", "c#", "sql-server", ".net-3.5", "" ]
How do you fix a names mismatch problem, if the client-side names are keywords or reserved words in the server-side language you are using? The DOJO JavaScript toolkit has a QueryReadStore class that you can subclass to submit REST patterned queries to the server. I'm using this in conjunction w/ the FilteringSelect D...
While it feels like the wrong thing to do, because I'm hacking at a well tested, nicely written JavaScript toolkit, this is how I fixed the problem: I went into the DOJOX QueryReadStore.js and **replaced** the "start" and "count" references with acceptable (to the server-side language) parameter names. I would have l...
As opposed to removing it from the API, as you mentioned, you can actually create a subclass with your own fetch, and remove start/count parameters (theoretically). Have a look at this URL for guidance: <http://www.sitepen.com/blog/2008/06/25/web-service-data-store/> Start and count are actually very useful because t...
How Do You Fix A Parameter Names Mismatch - DOJO and PL/SQL
[ "", "javascript", "web-applications", "plsql", "dojo", "" ]
How do I pass a parameter from a page's useBean in JSP to a servlet in Java? I have some data in a form that gets passed no problem with a submit button, but no way to send anything else. Please help? Here is my code: ``` <input name = "deleteGameButton" type = "submit" value = "Delete" onclick = "submitToServlet('De...
You kind of mess things here. onclick() is Javascript and executed on client side. It has no (direct) way to update session-scoped bean. That bean is left on server-side, and was used when the HTML page was **generated**. To pass parameters back to servlet you need to use good old form fields, and submit the form. Ad...
It depends exactly what you are trying to do. The `<jsp:useBean id = "userBean" scope = "session" class = "org.project.User" />` tag will allow you to use the userBean attribute of the session in your jsp. If there is not a userBean attribute in the session, it will create a new one (using the default constructor for...
How to pass parameter to servlet
[ "", "java", "html", "forms", "jsp", "parameters", "" ]
I want to start working with TDD but I don't know really where to start. We coding with .NET (C#/ASP.NET).
See the questions [Why should I practice Test Driven Development and how should I start?](https://stackoverflow.com/questions/4303/why-should-i-practice-test-driven-development-and-how-should-i-start), [Moving existing code to Test Driven Development](https://stackoverflow.com/questions/167079/moving-existing-code-to-t...
There's a good book called [Test Driven Development in Microsoft .NET](http://www.microsoft.com/MSPress/books/6778.aspx) that you might check out. It is essentially the same as the classic [Test Driven Development by Example](https://rads.stackoverflow.com/amzn/click/com/0321146530), but with the Microsoft platform in ...
What are the best steps to start programming with TDD with C#?
[ "", "c#", ".net", "tdd", "" ]
I'm actually developing a Web Service in Java using Axis 2. I designed my service as a POJO (Plain Old Java Object) with public method throwing exceptions : ``` public class MyService { public Object myMethod() throws MyException { [...] } } ``` I then generated the WSDL using Axis2 ant task. With the W...
I don't really think there is a problem. Your Client calls a method on the server. That method results in an exception. Axis transforms this exception to something which can be send to the client to indicate the error. All exceptions, as far as I know, are wrapped into an AxisFault which is then transmitted to the cli...
Have you tried using Axis2 with Lady4j, it solved this issue for us.
Web Service throwing exception using Axis2 Java
[ "", "java", "web-services", "exception", "axis", "" ]
I have a collection of data stored in XDocuments and DataTables, and I'd like to address both as a single unified data space with XPath queries. So, for example, "/Root/Tables/Orders/FirstName" would fetch the value of the Firstname column in every row of the DataTable named "Orders". Is there a way to do this without...
I eventually figured out the answer to this myself. I discovered a class in System.Xml.LINQ called XStreamingElement that can create an XML structure on-the-fly from a LINQ expression. Here's an example of casting a DataTable into an XML-space. ``` Dictionary<string,DataTable> Tables = new Dictionary<string,DataTable>...
.NETs XPath stuff operates on the IXPathNavigable interface. Every IXPathNavigable has a CreateNavigator() method that returns an IXPathNavigator. In order to expose all of your data sources as one large document you would need to create a class implementing IXPathNavigable, containing all the xpath data sources. The ...
Abstracting storage data structures within XPath
[ "", "c#", "xml", ".net-3.5", "datatable", "" ]
I run a browser based game at www.darknovagames.com. Recently, I've been working on reformatting the site with CSS, trying to get all of its pages to verify according to the HTML standard. I've been toying with this idea of having the navigation menu on the left AJAX the pages in (rather than taking the user to a sepa...
If you're going to enable AJAX, don't do it at the expense of having accessible URLs to every significant page on your site. This is the backbone of a navigable site that people can use. When you shovel all your functionality into AJAX calls and callbacks, you're basically forcing your users into a single path to acce...
Use ajax for portions of the page that needs to update, not the entire thing. For that you should use templates. When you want to still preserve the back button for your various state changes on the page, combine them with # achors to alter the url (without forcing the browser to issue another GET). For example, gmai...
AJAX and the Browser Back Button
[ "", "javascript", "html", "ajax", "navigation", "" ]
In many symbolic math systems, such as Matlab or Mathematica, you can use a variable like `Ans` or `%` to retrieve the last computed value. Is there a similar facility in the Python shell?
Underscore. ``` >>> 5+5 10 >>> _ 10 >>> _ + 5 15 >>> _ 15 ```
Just for the record, ipython takes this one step further and you can access every result with \_ and its numeric value ``` In [1]: 10 Out[1]: 10 In [2]: 32 Out[2]: 32 In [3]: _ Out[3]: 32 In [4]: _1 Out[4]: 10 In [5]: _2 Out[5]: 32 In [6]: _1 + _2 Out[6]: 42 In [7]: _6 Out[7]: 42 ``` And it is possible to edit ...
Get last result in interactive Python shell
[ "", "python", "" ]
I have a string containing a date, and another string containing the date format of the first string. Is there a function that I can call to convert that date into something like a SYSTEMTIME structure? Basically, I'd like the opposite of [GetDateFormat()](http://msdn.microsoft.com/en-us/library/ms776293(VS.85).aspx).
No, but you can write a function that will convert the date format string into a `sscanf` format string and series of variables. Then copy the data from the variables to the `SYSTEMTIME` structure and you're all set. It's not trivial, but it is probably the most flexible arrangement if you must support many different ...
It doesn't do quite what you've described, but I'd start by using `COleDateTime::ParseDateTime`. It works with localized date-time formats.
Parse a Date from a String in Win32
[ "", "c++", "windows", "winapi", "" ]
I have a sorted collection of objects (it can be either SortedList or SortedDictionary, I will use it mainly for reading so add performance is not that important). How can I get the i-th value? So e.g. when I have numbers 1, 2, 3, 4, 5 in the collection and I want the median (so 3 in this example), how can I do it?
Try something like this: list.Values[list.Count / 2]; Note that a true median would average the two numbers in the middle if Count is even.
You can use code like ``` list.Values[index] ``` for a sorted list. The easiest way with a SortedDictonary would be to use the ElementAt() method: ``` dict.ElementAt(index).Value ``` However, this is slower than in the list case. In either case, you need to check your count. If it is odd, take index = (list.lengt...
Getting i-th value from a SortedList or SortedDictionary
[ "", "c#", ".net", "collections", "" ]
My application deals with e-mails coming from different sources, e.g. Outlook and IMAP mailboxes. Before parsing them, I write them to the temporary directory (keeping them in memory is not an option). While parsing, I might be writing attachments to the temp directory (for example, if they are too large to keep in mem...
Write your files with encryption. I would think you wouldn't need anything too tricky or involved. Also encrypt or mangle the filenames as the virus scanner might be triggered by that as well.
If changing Virus scanner configuration is not the ideal option for you. Could you keep the file open from it's creation up to the end of your process? If you got an handle on the file, it will not be available for the Virus scanner.
Virus scanners locking and deleting temporary files - best way to cope with them?
[ "", "c#", "locking", "temporary-files", "antivirus", "" ]
Is there a way to make a python module load a dll in my application directory rather than the version that came with the python installation, without making changes to the python installation (which would then require I made an installer, and be careful I didn't break other apps for people by overwrting python modules ...
Ok it turns out python always loads the dll in the same directory as the pyd file, regardless of what the python and os paths are set to. So I needed to copy the \_sqlite3.pyd from python/v2.5/DLLS to my apps directory where the new sqlite3.dll is, making it load my new dll, rather than the one that comes with python ...
If you're talking about Python module DLLs, then simply modifying `sys.path` should be fine. However, if you're talking about DLLs *linked* against those DLLs; i.e. a `libfoo.dll` which a `foo.pyd` depends on, then you need to modify your PATH environment variable. I wrote about [doing this for PyGTK a while ago](http:...
python module dlls
[ "", "python", "module", "" ]
I have a "settings file" in my Winforms application called Settings.settings with a partial class for custom methods, etc. Is there a way to load / save dynamic settings based on arbitrary keys? For example, I have some ListViews in my application in which I want to save / load the column widths; Instead of creating a...
Store your column width settings in an Xml Serializable object. Ie, something that implements [IXmlSerializable](http://msdn.microsoft.com/en-us/library/system.xml.serialization.ixmlserializable.aspx) then create a single setting entry of that type in Settings.settings. A good option would probably be an Xml Serializa...
I think the error > The settings property > 'key' was not found. occurs because the 'key' value does not exist in your settings file (fairly self-explanatory). As far as I am aware, you can't add settings values programmatically, you might need to investigate adding all of the settings you need to the file after all...
Winforms - Dynamic Load / Save Settings
[ "", "c#", "winforms", "dynamic", "settings", "" ]
I need to import all ad groups in a few OUs into a table in SQL Server 2008. Once I have those I need to import all the members of those groups to a different table. I can use c# to do the work and pass the data to SQL server or do it directly in SQL server. Suggestions on the best way to approach this?
Arry, I don't know exactly, but found some links that may help you. I think the hottest track is this expression: ``` "(&(objectCategory=Person)(memberOf=DN=GroupName, OU=Org, DC=domain, DC=com))" ``` I found it in [LDAP Query for group members](http://www.houseoffusion.com/groups/cf-talk/thread.cfm/threadid:55298) ...
Add a Linked Server to your SQL Server and query the Active Directory via LDAP queries. This here described this quite well: [Create a SQL Server View of your AD Users, Brendan Tompkins (MVP)](http://codebetter.com/blogs/brendan.tompkins/archive/2003/12/19/4746.aspx)
Importing Active Directory Users and Groups into SQL Server (possibly via c#)
[ "", "c#", "sql-server", "active-directory", "" ]
I'm trying to write a web application using SpringMVC. Normally I'd just map some made-up file extension to Spring's front controller and live happily, but this time I'm going for REST-like URLs, with no file-name extensions. Mapping everything under my context path to the front controller (let's call it "**app**") me...
I think I may know what is going on. In your working web.xml you have set your servlet to be the default servlet (/ by itself is the default servlet called if there are no other matches), it will answer any request that doesn't match another mapping. In Failed 1 your /\* mapping does appear to be a valid path mapping...
For reference, the "failed attempt #2" is perfectly correct in version of Tomcat >= to 6.0.29. It was the result of a Tomcat bug that get fixed in version 6.0.29: <https://issues.apache.org/bugzilla/show_bug.cgi?id=50026> ``` <!-- Correct for Tomcat >= 6.0.29 or other Servlet containers --> <servlet-mapping> <serv...
Can anyone explain servlet mapping?
[ "", "java", "jakarta-ee", "servlets", "spring-mvc", "web.xml", "" ]
I am interested in making a Google Talk client using Python and would like to use the Twisted libraries Words module. I have looked at the examples, but they don't work with the current implementation of Google Talk. Has anybody had any luck with this? Would you mind documenting a brief tutorial? As a simple task, I'...
wokkel is the future of twisted words. [metajack](http://metajack.im/) wrote a really nice [blog post](http://metajack.im/2008/09/25/an-xmpp-echo-bot-with-twisted-and-wokkel/) on getting started. If you want a nice, functional sample project to start with, check out my [whatsup](http://github.com/dustin/whatsup) bot.
I have written a simple Jabber bot (and thus Google talk bot) using the `xmpppy` library, which works well. The examples on [xmpppy](http://xmpppy.sourceforge.net/) should get you started (specifically [`bot.py`](http://xmpppy.sourceforge.net/examples/bot.py)) As for something actually implemented in twisted.Words: [...
How do you create a simple Google Talk Client using the Twisted Words Python library?
[ "", "python", "twisted", "xmpp", "google-talk", "" ]
**Note: Mathematical expression evaluation is not the focus of this question. I want to compile and execute new code at runtime in .NET.** That being said... I would like to allow the user to enter any equation, like the following, into a text box: ``` x = x / 2 * 0.07914 x = x^2 / 5 ``` And have that equation appli...
Yes! Using methods found in the [Microsoft.CSharp](http://msdn.microsoft.com/en-us/library/microsoft.csharp.aspx), [System.CodeDom.Compiler](http://msdn.microsoft.com/en-us/library/system.codedom.compiler.aspx), and [System.Reflection](http://msdn.microsoft.com/en-us/library/system.reflection.aspx) name spaces. Here is...
You might try this: [Calculator.Net](http://weblogs.asp.net/pwelter34/archive/2007/05/05/calculator-net-calculator-that-evaluates-math-expressions.aspx) It will evaluate a math expression. From the posting it will support the following: ``` MathEvaluator eval = new MathEvaluator(); //basic math double result = eval....
Is it possible to compile and execute new code at runtime in .NET?
[ "", "c#", ".net", "compilation", "runtime", "" ]
How do you create an application shortcut (.lnk file) in C# or using the .NET framework? The result would be a .lnk file to the specified application or URL.
It's not as simple as I'd have liked, but there is a great class call [ShellLink.cs](http://www.vbaccelerator.com/home/NET/Code/Libraries/Shell_Projects/Creating_and_Modifying_Shortcuts/ShellLink_Code.html) at [vbAccelerator](http://www.vbaccelerator.com/home/index.html) This code uses interop, but does not rely on WS...
Nice and clean. (**.NET 4.0**) ``` Type t = Type.GetTypeFromCLSID(new Guid("72C24DD5-D70A-438B-8A42-98424B88AFB8")); //Windows Script Host Shell Object dynamic shell = Activator.CreateInstance(t); try{ var lnk = shell.CreateShortcut("sc.lnk"); try{ lnk.TargetPath = @"C:\something"; lnk.IconLoca...
Creating application shortcut in a directory
[ "", "c#", ".net", "file-io", "shortcut", "" ]
I have some linq entities that inherit something like this: ``` public abstract class EntityBase { public int Identifier { get; } } public interface IDeviceEntity { int DeviceId { get; set; } } public abstract class DeviceEntityBase : EntityBase, IDeviceEntity { public abstract int DeviceId { get; set; } } public...
LINQ-to-SQL has *some* support for inheritance via a discriminator ([here](http://www.davidhayden.com/blog/dave/archive/2007/10/28/LINQToSQLEnumSupportExampleDiscriminatorColumnInheritanceMapping.aspx), [here](http://weblogs.asp.net/zeeshanhirani/archive/2008/06/25/inheritance-in-linq-to-sql.aspx)), but you can only qu...
Wow, looks like for once I may be able to one-up @MarcGravell! I had the same problem, then I discovered [this answer](https://stackoverflow.com/questions/1021274/linq-to-sql-mapping-exception-when-using-abstract-base-classes/1068499#1068499), which solved the problem for me! In your case, you would say: ``` return ...
LinqToSql and abstract base classes
[ "", "c#", "linq-to-sql", "" ]
How do you prepare your SQL deltas? do you manually save each schema-changing SQL to a delta folder, or do you have some kind of an automated diffing process? I am interested in conventions for versioning database schema along with the source code. Perhaps a pre-commit hook that diffs the schema? Also, what options f...
See [Is there a version control system for database structure changes?](https://stackoverflow.com/questions/308/is-there-a-version-control-system-for-database-structure-changes) [How do I version my MS SQL database in SVN?](https://stackoverflow.com/questions/173/how-do-i-version-my-ms-sql-database-in-svn) and Jeff'...
You might take a look at another, similar thread: [How do I version my MS SQL database in SVN?](https://stackoverflow.com/questions/173/how-do-i-version-my-ms-sql-database-in-svn).
How do you version your database schema?
[ "", "sql", "mysql", "schema", "versioning", "" ]
I know how to find a method in java using a fixed string, ``` someClass.getMethod("foobar", argTypes); ``` but is there a way to use a regular expression rather than a fixed string to find a method on a given class? An example of the usage might be if I wanted to find a method that was called either "foobar" or "foo...
You should apply your regexp on [getDeclaredMethods](http://java.sun.com/j2se/1.4.2/docs/api/java/lang/Class.html#getDeclaredMethods())() reflection method (or GetMethods() if you want only the public ones). [Warning: both methods will throw a SecurityException if there is a security manager.] You apply it on each na...
Not directly. You could loop over all the methods and check each. ``` Pattern p = Pattern.compile("foo[Bb]ar"); for(Method m : someClass.getMethods()) { if(p.matcher(m.getName()).matches()) { return m; } } ```
Can I use regular expressions to find a method on a class in java?
[ "", "java", "reflection", "" ]
[YUI Compressor](http://developer.yahoo.com/yui/compressor/) does not accept wildcard parameters, so I cannot run it like this: ``` C:>java -jar yuicompressor.jar *.js ``` But I have over 500 files and would rather not have to create a batch file like this: ``` C:>java -jar yuicompressor.jar file1.js -o deploy\file1...
I might go for a makefile (I think it would probably be more maintainable long term), but if you want a quick-n-dirty Windows batch command something like the following should work: ``` for %%a in (*.js) do @java -jar yuicompressor.jar "%%a" -o "deploy\%%a" ```
If you are geared towards Java, you can also use Ant for conversion. I've found a [blog entry](http://blog.gomilko.com/2007/11/29/yui-compression-tool-as-ant-task/) about an [Ant Taks for the YUI Compressor](http://www.ubik-ingenierie.com/ubikwiki/index.php?title=Minifying_JS/CSS). Disclaimer: Never tried it - sorry
How to automate JavaScript files compression with YUI Compressor?
[ "", "javascript", "batch-file", "yui", "" ]
> **Possible Duplicate:** > [Reference: Comparing PHP's print and echo](https://stackoverflow.com/questions/7094118/reference-comparing-phps-print-and-echo) Is there any major and fundamental difference between these two functions in PHP?
From: <http://web.archive.org/web/20090221144611/http://faqts.com/knowledge_base/view.phtml/aid/1/fid/40> 1. Speed. There is a difference between the two, but speed-wise it should be irrelevant which one you use. echo is marginally faster since it doesn't set a return value if you really want to get down to the ...
They are: * print only takes one parameter, while echo can have multiple parameters. * print returns a value (1), so can be used as an expression. * echo is slightly faster.
How are echo and print different in PHP?
[ "", "php", "echo", "" ]
I'm trying to come up with a Java regex that will match a filename only if it has a valid extension. For example it should match "foo.bar" and "foo.b", but neither "foo." nor "foo". I've written the following test program ``` public static void main(String[] args) { Pattern fileExtensionPattern = Pattern.compile("\...
The [Matcher.matches()](http://java.sun.com/javase/6/docs/api/java/util/regex/Matcher.html#matches()) function tries to match the pattern against the entire input. Thus, you have to add `.*` to the beginning of your regex (and the `\\Z` at the end is superfluous, too), or use the [find()](http://java.sun.com/javase/6/d...
``` public boolean isFilename(String filename) { int i=filename.lastInstanceOf("."); return(i != -1 && i != filename.length - 1) } ``` Would be significantly faster and regardless of what you do, putting it in a method would be more readable.
Java file extension regex
[ "", "java", "regex", "" ]
Currently we are using prototype and jQuery as our js frameworks. Right now, jQuery is set to $j() to prevent conflicts from prototype. In the past, we've used a lot of prototype's Element.down(), Element.next(), and Element.previous() to traverse the DOM. However, I need a simple way to retrieve the last child elemen...
Guys, note that the selector functions return arrays of elements (not single elements), so you must adddress the element in the result array by index: [0]. Code in prototype ``` //if you only have the id of the parent var lastChild = $$("#parent :last-child")[0]; //or //if you have the actual DOM element var lastChi...
Try this it has always worked for me in jQuery ``` var lastChild = $("#parent :last-child"); ``` <http://docs.jquery.com/Selectors/lastChild>
Best way to implement .lastChild using Prototype or jQuery
[ "", "javascript", "jquery", "prototypejs", "" ]
When overriding the MembershipProvider and calling it directly, is there a way to fill the NameValueCollection config parameter of the Initialize method without manually looking through the config file for the settings? Obviously this Initialize is being called by asp.net and the config is being filled somewhere. I ha...
tvanfosson- Thanks for the help. (if I had the 15 points necessary I would vote you up) From your link I was able to figure it out. It turns out the second parameter to the Initialize proceedure was the list of parameters from the provider and could be reached in the following way: ``` string configPath = "~/web.conf...
Not sure why you want to create a new one, but if you create it yourself, you'll need to read the web config and get the values yourself to pass to Initialize() as this is done outside the class. I'm sure, though, that there is already a section handler for this section so it should be just a matter of doing: ``` Memb...
Custom MembershipProvider Initialize method
[ "", "c#", ".net", "membership-provider", "" ]
I have a DataSet consisting of XML data, I can easily output this to a file: ``` DataSet ds = new DataSet(); DataTable dt = new DataTable(); ds.Tables.Add(dt); ds.Load(reader, LoadOption.PreserveChanges, ds.Tables[0]); ds.WriteXml("C:\\test.xml"); ``` However what I want to do is compress the XML into a ZIP or other ...
I've managed to compress a DataSet's XML stream using .NET 2.0's gzip compression. Here's the blog post I made a few years ago about it: [Saving DataSets Locally With Compression](http://www.madprops.org/blog/saving-datasets-locally-with-compression) ... and here's the code I added to my DataSet's partial class to w...
This works with streams or files, has a good license and source: <http://www.codeplex.com/DotNetZip> Here's the code to do exactly what the original poster asked: write a DataSet into a zip that is split into 1mb chunks: ``` // get connection to the database var c1= new System.Data.SqlClient.SqlConnection(connstring1...
.NET - Stream DataSet (of XML data) to ZIP file?
[ "", "c#", "compression", "zip", "" ]
I have an app that has impersonation used throughout. But when a user is logged in as an admin, a few operation require them to write to the server itself. Now if these users do not have rights on the actual server (some don't) it will not let them write. What I want to do is turn off impersonation for just a couple c...
Make sure the Application Pool do have the proper rights that you need. Then, when you want to revert to the application pool identity... run the following: ``` private WindowsImpersonationContext context = null; public void RevertToAppPool() { try { if (!WindowsIdentity.GetCurrent().IsSystem) ...
I am not sure if this is the preferred approach but when I wanted to do this I new'd up an instance of a [WindowsIdentity](http://msdn.microsoft.com/en-us/library/system.security.principal.windowsidentity.aspx) and called the [Impersonate](http://msdn.microsoft.com/en-us/library/system.security.principal.windowsidentit...
Can I turn off impersonation just in a couple instances
[ "", "c#", "asp.net", "impersonation", "" ]
I want to write a C# application where it connects to a telnet server and communicates to the server. I was wondering how a telnet server sends information to the client. I have looked (skimmed) over the [Telnet RFC](http://www.faqs.org/rfcs/rfc854.html) and looked at the incoming packets coming in from the server and ...
Moving the cursor and changing the color isn't done by the telnet protocol. Your telnet client is emulating a [terminal](http://en.wikipedia.org/wiki/Computer_terminal), most probably a VT-100 variant. To move the cursor and change the color, the server sends escape sequences especific to the type of terminal being em...
A [simple Google search](http://www.google.com/search?q=c%23+telnet+client&ie=utf-8&oe=utf-8&aq=t&rls=org.mozilla:en-US:official&client=firefox-a) reveals many open source Telnet (and other network protocol) clients written in C#. You could just download the source code to one and see how they implement connection nego...
How does Telnet server communicate to the client?
[ "", "c#", "terminal", "client-server", "telnet", "vt100", "" ]
Any gotchas I should be aware of? Can I store it in a text field, or do I need to use a blob? (I'm not overly familiar with either pickle or sqlite, so I wanted to make sure I'm barking up the right tree with some of my high-level design ideas.)
If you want to store a pickled object, you'll need to use a blob, since it is binary data. However, you can, say, base64 encode the pickled object to get a string that can be stored in a text field. Generally, though, doing this sort of thing is indicative of bad design, since you're storing opaque data you lose the a...
I needed to achieve the same thing too. I turns out it caused me quite a headache before I finally figured out, [thanks to this post](http://coding.derkeiler.com/Archive/Python/comp.lang.python/2008-12/msg00352.html), how to actually make it work in a binary format. ### To insert/update: ``` pdata = cPickle.dumps(da...
Can I pickle a python dictionary into a sqlite3 text field?
[ "", "python", "sqlite", "pickle", "" ]
1. How do I get a method's execution time? 2. Is there a `Timer` utility class for things like timing how long a task takes, etc? Most of the searches on Google return results for timers that schedule threads and tasks, which is not what I want.
There is always the old-fashioned way: ``` long startTime = System.nanoTime(); methodToTime(); long endTime = System.nanoTime(); long duration = (endTime - startTime); //divide by 1000000 to get milliseconds. ```
I go with the simple answer. Works for me. ``` long startTime = System.currentTimeMillis(); doReallyLongThing(); long endTime = System.currentTimeMillis(); System.out.println("That took " + (endTime - startTime) + " milliseconds"); ``` It works quite well. The resolution is obviously only to the millisecond, you c...
How do I time a method's execution in Java?
[ "", "java", "timing", "execution-time", "" ]
What is the most efficient way to convert a MySQL query to CSV in PHP please? It would be best to avoid temp files as this reduces portability (dir paths and setting file-system permissions required). The CSV should also include one top line of field names.
``` SELECT * INTO OUTFILE "c:/mydata.csv" FIELDS TERMINATED BY ',' OPTIONALLY ENCLOSED BY '"' LINES TERMINATED BY "\n" FROM my_table; ``` (*the documentation for this is here: <http://dev.mysql.com/doc/refman/5.0/en/select.html>*) or: ``` $select = "SELECT * FROM table_name"; $export = mysql_query ( $select ) or di...
Check out this [question / answer](https://stackoverflow.com/questions/81934/easy-way-to-export-a-sql-table-without-access-to-the-server-or-phpmyadmin#81951). It's more concise than @Geoff's, and also uses the builtin fputcsv function. ``` $result = $db_con->query('SELECT * FROM `some_table`'); if (!$result) die('Coul...
PHP code to convert a MySQL query to CSV
[ "", "php", "mysql", "csv", "" ]
If I create classes, that are used at the moment only in a single thread, should I make them thread-safe, even if I don't need that at the moment? It could be happen, that I later use this class in multiple threads, and at that time I could get race conditions and may have a hard time to find them if I didn't made the ...
Start from the data. Decide which data is explicitly shared and protect it. If at all possible, encapsulate the locking with the data. Use pre-existing thread-safe concurrent collections. Whenever possible, use immutable objects. Make attributes final, set their values in the constructors. If you need to "change" the ...
I used to try to make everything thread-safe - then I realised that the very meaning of "thread-safe" depends on the usage. You often just can't predict that usage, and the caller will *have* to take action anyway to use it in a thread-safe way. These days I write almost everything assuming single threading, and put t...
Should I always make my java-code thread-safe, or for performance-reasons do it only when needed?
[ "", "java", "multithreading", "performance", "concurrency", "thread-safety", "" ]
What's the easiest way of me converting the simpler regex format that most users are used to into the correct re python regex string? As an example, I need to convert this: ``` string = "*abc+de?" ``` to this: ``` string = ".*abc.+de.?" ``` Of course I could loop through the string and build up another string char...
Those don't look like regexps you're trying to translate, they look more like unix shell globs. Python has a [module](http://www.python.org/doc/2.5.2/lib/module-fnmatch.html) for doing this already. It doesn't know about the "+" syntax you used, but neither does my shell, and I think the syntax is nonstandard. ``` >>>...
.replacing() each of the wildcards is the quick way, but what if the wildcarded string contains other regex special characters? eg. someone searching for 'my.thing\*' probably doesn't mean that '.' to match any character. And in the worst case things like match-group-creating parentheses are likely to break your final ...
String Simple Substitution
[ "", "python", "string", "" ]
Is there any good way to use a windows application written in C# to display/control a powerpoint slideshow? Ultimately I would like to show thumbnails in a form and clicking these thumbnails would advance the slides shown on a second monitor (similar to using Powerpoint itself to show a slideshow on a second monitor). ...
This kb lays out the basics for working with the powerpoint presentation viewer object model. I'd suggest you include the viewer when you distribute your application. <http://support.microsoft.com/kb/265385> Once you get a reference to the viewer (top level) object it is basically the same as working with the powerpo...
One of our softwares here at work does that. Initially we used MS Office but recently we switched to use [OpenOffice.org Uno](http://udk.openoffice.org/) since it offers better control than MS Office and is easier to work with. It has [.NET CLI-bindings](http://wiki.services.openoffice.org/wiki/Uno/CLI). To answer you...
Using C# to display powerpoint
[ "", "c#", ".net", "powerpoint", "" ]
I'm new to Windows programming and after reading the Petzold book I wonder: is it still good practice to use the `TCHAR` type and the `_T()` function to declare strings or should I just use the `wchar_t` and `L""` strings in new code? I will target only modern Windows (as of this writing versions 10 and 11) and my cod...
I would still use the TCHAR syntax if I was doing a new project today. There's not much practical difference between using it and the WCHAR syntax, and I prefer code which is explicit in what the character type is. Since most API functions and helper objects take/use TCHAR types (e.g.: CString), it just makes sense to ...
The short answer: **NO**. Like all the others already wrote, a lot of programmers still use TCHARs and the corresponding functions. In my humble opinion **the whole concept was a bad idea**. [UTF-16](http://en.wikipedia.org/wiki/UTF-16/UCS-2) string processing is a lot different than simple ASCII/MBCS string processin...
Is TCHAR still relevant?
[ "", "c++", "c", "windows", "unicode", "wchar-t", "" ]
How do you pass options to an executable? Is there an easier way than making the options boolean arguments? EDIT: The last two answers have suggested using arguments. I know I can code a workable solution like that, but I'd rather have them be options. EDIT2: Per requests for clarification, I'll use this simple examp...
You seem to think that there is some fundamental difference between "options" that start with "`--`" and "arguments" that don't. The only difference is in how you parse them. It might be worth your time to look at GNU's `getopt()`/`getopt_long()` option parser. It supports passing arguments with options such as `--num...
Command-line arguments is the way to go. You may want to consider using Boost.ProgramOptions to simplify this task.
C++ Passing Options To Executable
[ "", "c++", "arguments", "" ]
Suppose I have a hash\_map and a code like ``` // i is an iterator i = hash_map.erase(i) ``` But GCC's STL doesn't return iterator in erase, but a void. Now is a code like ``` hash_map.erase(i++) ``` safe (i.e. does not invalidate the iterator or does any other unexpected or unpleasant things)? Please note this is ...
Yes, this is safe, because the value of `i` will have been set to the next value, before the current value is erased. According to the [SGI documentation about hashed containers](http://www.sgi.com/tech/stl/HashedAssociativeContainer.html) invalidation does not occur for non-erased elements, nor even for resizing (the...
You can encapsulate erasing to provide the same interface for all containers you use: ``` namespace detail { template<typename Container, typename R> struct SelectErase { // by default, assume the next iterator is returned template<typename Iterator> Iterator erase(Container& c, Iterator where) { return c.er...
What is a safe equivalent of non-void STL erase?
[ "", "c++", "stl", "iterator", "hashmap", "" ]
I'm trying to make a simple blackjack program. Sadly, I'm having problems right off the bat with generating a deck of cards. ``` #include <iostream> #include <vector> using namespace std; int main() { vector<char> deck; char suit[] = {'h','d','c','s'}; char card[] = {'2','3','4','5','6','7','8','9','10',...
Try to create class of Card with suit and card as a member and set it as a type of vector. Like ``` public class Card { public: Card(char suit, char card); char suit, card; }; int main() { vector<Card> deck; char suit[] = {'h','d','c','s'}; char card[] = {'2','3','4','5','6','7','8','9','T','J','Q','...
I think what you are looking to use is an enumeration. It will make your code clearer and resolve your problem. ``` enum SUIT { HEART, CLUB, DIAMOND, SPADE }; enum VALUE { ONE, TWO, THREE, ..., TEN, JACK, QUEEN, KING}; ```
Generating a Deck of Cards
[ "", "c++", "" ]
Ok, so it's *almost* as easy as pie already. But it really should be as easier than it is. I think I should be able to connect to another database just by putting a JDBC connection string into TNSNAMES. Every database vendor has a type-4 JDBC driver and there's usually a good, free alternative. With Oracle being such...
It's a real question - perhaps slightly jokey but certainly not rhetorical. It is entirely in Oracle's interest to make it really easy to access other people's data. At the moment there's lots of ways to do it but none sufficiently straightforward. There's a JVM in the database and JDBC drivers to every other database ...
The answer is the same as for the following questions: 1. Why doesn't Oracle provide an efficient way of unloading data into a non-proprietary format (e.g. comma-delimited or XML) 2. Why do most Oracle non-DB products only work with the Oracle RDBMS? (without having to use Oracle Database Gateways) You've ever heard ...
Why isn't querying a JDBC-compliant database from Oracle as easy as pie?
[ "", "java", "oracle", "jdbc", "" ]
I'm looking for recommendations on books about MVC on the desktop. If they use Java, that is a bonus. Some background: I'm writing a desktop application in Java. It's an audio application that has a number of views and a central model called a Library with playlists, effects lists and a folder structure to organize th...
I've had the same problem: it really takes a lot of discipline to write a (non trivial) swing app, because all the listeners and events and asynchronous processing make up really fast for a big pile of unmaintainable code. I found that classic MVC isn't enough, you have to look into more specific patterns like [Presen...
In C# rather then Java, but Jeremy Miller has a [bunch of posts](http://codebetter.com/blogs/jeremy.miller/archive/tags/Build+your+own+CAB/default.aspx) regarding desktop apps and MVP/MVC (and a whole bunch of other related stuff).
Recommended books on Desktop Application development using MVC
[ "", "java", "model-view-controller", "desktop", "" ]
Is there any class in the .NET framework that can read/write standard .ini files: ``` [Section] <keyname>=<value> ... ``` Delphi has the `TIniFile` component and I want to know if there is anything similar for C#?
The creators of the .NET framework want you to use XML-based config files, rather than INI files. So no, there is no built-in mechanism for reading them. There are third party solutions available, though. * INI handlers can be obtained as [NuGet packages](https://www.nuget.org/packages?q=ini), such as [INI Parser](ht...
## Preface Firstly, read this MSDN blog post on [the limitations of INI files](https://devblogs.microsoft.com/oldnewthing/20071126-00/?p=24383). If it suits your needs, read on. This is a concise implementation I wrote, utilising the original Windows P/Invoke, so it is supported by all versions of Windows with .NET i...
Reading/writing an INI file
[ "", "c#", ".net", "ini", "" ]
*Note: I found this ["Creating a Word Doc in C#.NET"](https://stackoverflow.com/questions/10412/creating-a-word-doc-in-cnet), but that is not what I want.* Do you know how to create a **.odt** to create file from C# .NET? Is there a .NET component or wrapper for an OpenOffice.org library to do this?
Have a look at AODL (see <http://odftoolkit.org/projects/odftoolkit/pages/AODL>). * fully managed .NET 1.1 (so it runs on MS.Net and Mono) * support for text and spreadsheet documents * create, read, edit, save documents * ... EDIT by kame: New link [AODL-Wiki](https://wiki.openoffice.org/wiki/AODL)
You can check out the [OASIS Standards site](http://www.oasis-open.org/specs/index.php#opendocument) for information on the ODT standard. From what I've seen, they're using an XML based standard and have an XSD available for the the document standard, so you could use that in conjunction with your own code to build a d...
How to create .odt files with C#.NET?
[ "", "c#", "document", "openoffice.org", "" ]
Alright, I'm trying to read a comma delimited file and then put that into a ListView (or any grid, really). I have the delimiting part of the job taken care of, with the fields of the file being put into a multidimensional string array. The problem is trying to get it into the ListView. It appears that there isn't a r...
Just loop through each of the arrays in that you've created and create a new ListViewItem object (there is a constructor that takes an array of strings, I believe). The pass the ListViewItem to the ListView.Items.Add() method.
You can [load a csv file with ado.net](http://www.dotnetspider.com/resources/646-Handling-CSV-Files-ADO.aspx) and bind it to a datagrids data source. Or you could use [linq for xml](http://weblogs.asp.net/pleloup/archive/2008/04/12/linq-to-csv-library.aspx) to parse the file and bind those results to a datagrid's data ...
Reading Comma Delimited File and Putting Data in ListView - C#
[ "", "c#", "listview", "user-interface", "" ]
In a previous question, I asked about various ORM libraries. It turns out Kohana looks very clean yet functional for the purposes of ORM. I already have an MVC framework that I am working in though. If I don't want to run it as a framework, what is the right fileset to include to just give me the DB and ORM base class ...
Why not just have a ``` class ORM extends ORM_Core {} ``` somewhere in your code? This removes the need to use any of the loader code. You'll also need Kohana\_Exception, the Database library (and appropraite driver), Kohana::config(), Kohana::auto\_load(), Kohana::log() methods (search Database.php for those). Koh...
It turns out that Kohana uses magic class loading so that if a defined class with an \_Core extention doesn't exist as a class i.e. ORM\_Core exists, but ORM doesn't, so Kohana will magically define an ORM class Since the package uses 100% magic class loading. In case anyone is interested, I'm documenting my finds he...
Is it possible to install Kohana libraries for ORM in PHP without using the entire framework?
[ "", "php", "orm", "kohana", "" ]
I am planning a PHP application that needs to store date/times in an MSSQL database. (For the curious, it is a calendar application.) What is the preferred format to store this information? MSSQL has its own datetime data type, which works well in the database itself and is very readable. However, there aren't any MSS...
I would store the dates in the MS-SQL format to assist in using the date manipulation functions in T-SQL to their fullest. It's easier to write and read ``` SELECT * FROM Foo WHERE DateDiff(d,field1,now()) < 1 ``` Than to try and perform the equivalent operation by manipulating integers To convert a MsSQL date into ...
I'd recommend the same as i do for all dates in any db engine, the db native type. (DATETIME) Just use "YYYY-MM-DD HH:MM:SS" for inserting in php: `date('Y-m-d H:i:s', $myTimeStampInSeconds);` -edit in response to comments below here - 1. for selected columns you can use `$timestamp = strtotime( $yourColumnValue );`...
What is the preferred format to store date/times in a SQL Server database when PHP is your primary language?
[ "", "php", "sql-server", "datetime", "time", "" ]
Is there a way to merge two primary keys into one and then cascade update all affected relationships? Here's the scenario: Customers (idCustomer int PK, Company varchar(50), etc) CustomerContacts (idCustomerContact int PK, idCustomer int FK, Name varchar(50), etc) CustomerNotes (idCustomerNote int PK, idCustomer int...
There's no automatic way to do it, but you have a couple options, you can manually write the procedures, or you can either code generate the merge on a regular basis or dynamically generate it at run-time. To do this, you can use the `INFORMATION_SCHEMA.REFERENTIAL_CONSTRAINTS` and `INFORMATION_SCHEMA.KEY_COLUMN_USAGE`...
Any more recent solution to this? I have kind of the same problem and at the moment building the procedures dynamically seems too complicated. Here's how it could work in theory, but I guess it doesn't? In one transaction: 1) Temporarily disable primary key constraint on Customers 2) Update Primary ID of Cingular to ...
Merge Primary Keys - Cascade Update
[ "", "sql", "sql-server", "cascade", "" ]
My MFC application using the "ESRI MapObjects LT2" ActiveX plugin throws an ASSERT at me when closing it. The error occurs in `cmdtarg.cpp`: ``` CCmdTarget::~CCmdTarget() { #ifndef _AFX_NO_OLE_SUPPORT if (m_xDispatch.m_vtbl != 0) ((COleDispatchImpl*)&m_xDispatch)->Disconnect(); ASSERT(m_dwRef <= 1); //...
The following solved it for me: In the window that contains the control, add an OnDestroy() handler: ``` void CMyWnd::OnDestroy() { // Apparently we have to disconnect the (ActiveX) Map control manually // with this undocumented method. COleControlSite* pSite = GetOleControlSite(MY_DIALOG_CONTROL_ID); ...
That looks like a reference count. Could this "target" be referenced by something else, something that's not releasing it?
ActiveX plugin causes ASSERT to fail on application exit in VS2008
[ "", "c++", "activex", "visual-c++-6", "visual-c++-2008", "" ]
I am a big fan of letting the compiler do as much work for you as possible. When writing a simple class the compiler can give you the following for 'free': * A default (empty) constructor * A copy and move constructor * A destructor * Assignment operators (`operator=`) But it cannot seem to give you any comparison op...
The compiler wouldn't know whether you wanted a pointer comparison or a deep (internal) comparison. It's safer to just not implement it and let the programmer do that themselves. Then they can make all the assumptions they like.
The argument that if the compiler can provide a default copy constructor, it should be able to provide a similar default `operator==()` makes a certain amount of sense. I think that the reason for the decision not to provide a compiler-generated default for this operator can be guessed by what Stroustrup said about the...
Why don't C++ compilers define operator== and operator!=?
[ "", "c++", "operators", "language-design", "comparison-operators", "default-comparisons", "" ]
I recently stumbled across [this entry in the google testing blog](http://googletesting.blogspot.com/2008/08/by-miko-hevery-so-you-decided-to.html) about guidelines for writing more testable code. I was in agreement with the author until this point: > Favor polymorphism over conditionals: If you see a switch statement...
Actually this makes testing and code easier to write. If you have one switch statement based on an internal field you probably have the same switch in multiple places doing slightly different things. This causes problems when you add a new case as you have to update all the switch statements (if you can find them). B...
## Do not fear... I guess your problem lies with familiarity, not technology. Familiarize yourself with C++ OOP. ## C++ is an OOP language Among its multiple paradigms, it has OOP features and is more than able to support comparison with most pure OO language. Don't let the "C part inside C++" make you believe C++ ...
Do polymorphism or conditionals promote better design?
[ "", "c++", "oop", "tdd", "polymorphism", "" ]
I have a collection of elements that I need to operate over, calling member functions on the collection: ``` std::vector<MyType> v; ... // vector is populated ``` For calling functions with no arguments it's pretty straight-forward: ``` std::for_each(v.begin(), v.end(), std::mem_fun(&MyType::myfunc)); ``` A similar...
Boost Lambda makes this easy. ``` #include <boost/lambda/lambda.hpp> #include <boost/lambda/bind.hpp> #include <boost/lambda/if.hpp> std::for_each( v.begin(), v.end(), if_( MyPred() )[ std::mem_fun(&MyType::myfunc) ] ); ``` You could even do away with defining MyPred(), if it is simple....
I wrote a `for_each_if()` and a `for_each_equal()` which do what I think you're looking for. `for_each_if()` takes a predicate functor to evaluate equality, and `for_each_equal()` takes a value of any type and does a direct comparison using `operator ==`. In both cases, the function you pass in is called on each eleme...
using STL to find all elements in a vector
[ "", "c++", "stl", "" ]
I need to [serialize](https://en.wikipedia.org/wiki/Serialization) an object to [JSON](https://www.json.org/). I'm using [jQuery](https://api.jquery.com/). Is there a "standard" way to do this? My specific situation: I have an array defined as shown below: ``` var countries = new Array(); countries[0] = 'ga'; countri...
[JSON-js](https://github.com/douglascrockford/JSON-js) - JSON in JavaScript. To convert an object to a string, use `JSON.stringify`: ``` var json_text = JSON.stringify(your_object, null, 2); ``` To convert a JSON string to object, use `JSON.parse`: ``` var your_object = JSON.parse(json_text); ``` It was recently r...
I've been using [jquery-json](https://code.google.com/p/jquery-json/) for 6 months and it works great. It's very simple to use: ``` var myObj = {foo: "bar", "baz": "wockaflockafliz"}; $.toJSON(myObj); // Result: {"foo":"bar","baz":"wockaflockafliz"} ```
Serializing to JSON in jQuery
[ "", "javascript", "jquery", "ajax", "json", "serialization", "" ]
I want to be able to do the following: ``` $normal_array = array(); $array_of_arrayrefs = array(&$normal_array); // Here I want to access the $normal_array reference **as a reference**, // but that doesn't work obviously. How to do it? end($array_of_arrayrefs)["one"] = 1; // choking on this one print $normal_a...
`end()` doesn't return a reference of the last value, but rather the last value itself. Here is a workaround: ``` $normal_array = array(); $array_of_arrayrefs = array( &$normal_array ); $refArray = &end_byref( $array_of_arrayrefs ); $refArray["one"] = 1; print $normal_array["one"]; // should output 1 function...
Here are a couple of approaches, neither of which I find particularly satisfying. I'm sure there's a better way.. ``` <?php $normal_array = array(); $array_of_arrayrefs = array( "blah", &$normal_array ); foreach ($array_of_arrayrefs as &$v); $v["one"] = 1; echo $normal_array["one"]; //prints 1 ?> <?php $nor...
Set element on last reference in an array of references
[ "", "php", "arrays", "reference", "pass-by-reference", "" ]
I'm looking into some possible options for unit testing C++ classes. So, short and to the point, what are you using?
I'm using [cppunit](http://sourceforge.net/projects/cppunit). It is a pretty good port of the iconic JUnit to c++.
[UnitTest++](http://unittest-cpp.sourceforge.net/). In the past I used Boost Test, which is also pretty good, but I ran across a problem where boost test wanted an operator<< defined and it wouldn't accept my overloaded operator<<. UnitTest++ didn't flinch a bit.
What are you using to unit test your C++ code?
[ "", "c++", "unit-testing", "" ]
I have an XML file loaded into a DOM document, I wish to iterate through all 'foo' tags, getting values from every tag below it. I know I can get values via ``` $element = $dom->getElementsByTagName('foo')->item(0); foreach($element->childNodes as $node){ $data[$node->nodeName] = $node->nodeValue; } ``` However, ...
Not tested, but what about: ``` $elements = $dom->getElementsByTagName('foo'); $data = array(); foreach($elements as $node){ foreach($node->childNodes as $child) { $data[] = array($child->nodeName => $child->nodeValue); } } ```
It's generally much better to use XPath to query a document than it is to write code that depends on knowledge of the document's structure. There are two reasons. First, there's a lot less code to test and debug. Second, if the document's structure changes it's a lot easier to change an XPath query than it is to change...
How do I iterate through DOM elements in PHP?
[ "", "php", "xml", "dom", "" ]
I need to be able to take a string like: ``` '''foo, bar, "one, two", three four''' ``` into: ``` ['foo', 'bar', 'one, two', 'three four'] ``` I have an feeling (with hints from #python) that the solution is going to involve the shlex module.
The shlex module solution allows escaped quotes, one quote escape another, and all fancy stuff shell supports. ``` >>> import shlex >>> my_splitter = shlex.shlex('''foo, bar, "one, two", three four''', posix=True) >>> my_splitter.whitespace += ',' >>> my_splitter.whitespace_split = True >>> print list(my_splitter) ['f...
It depends how complicated you want to get... do you want to allow more than one type of quoting. How about escaped quotes? Your syntax looks very much like the common CSV file format, which is supported by the Python standard library: ``` import csv reader = csv.reader(['''foo, bar, "one, two", three four'''], skipi...
How can i parse a comma delimited string into a list (caveat)?
[ "", "python", "split", "escaping", "quotes", "" ]
If I were to use more than one, what order should I use modifier keywords such as: `public`, `private`, `protected`, `virtual`, `abstract`, `override`, `new`, `static`, `internal`, `sealed`, and any others I'm forgetting.
I had a look at Microsoft's [Framework Design Guidelines](https://msdn.microsoft.com/en-us/library/ms229042%28v=vs.100%29) and couldn't find any references to what order modifiers should be put on members. Likewise, a look at the [C# 5.0 language specification](https://www.microsoft.com/en-gb/download/details.aspx?id=7...
[StyleCop](https://stylecop.codeplex.com) is available as a [Visual Studio extension](https://marketplace.visualstudio.com/items?itemName=ChrisDahlberg.StyleCop) or a [NuGet package](https://www.nuget.org/packages/StyleCop.MSBuild) and can validate your source code against the rules some teams in Microsoft use. StyleCo...
Is there a convention to the order of modifiers in C#?
[ "", "c#", "" ]
Is it possible to define a class in C# such that ``` class GenericCollection<T> : SomeBaseCollection<T> where T : Delegate ``` I couldn't for the life of me accomplish this last night in .NET 3.5. I tried using `delegate, Delegate, Action<T> and Func<T, T>` It seems to me that this should be allowable in some way. ...
A number of classes are unavailable as generic contraints - Enum being another. For delegates, the closest you can get is ": class", perhaps using reflection to check (for example, in the static constructor) that the T *is* a delegate: ``` static GenericCollection() { if (!typeof(T).IsSubclassOf(typeof(Delegate))...
Yes it's possible in C# 7.3, Constraints family increased to include `Enum`, `Delegate` and `unmanaged` types. You can write this code without a problem: ``` void M<D, E, T>(D d, E e, T* t) where D : Delegate where E : Enum where T : unmanaged { } ``` [From Docs](https://learn.microsoft.com/en-us/dotnet/csha...
C# Generics won't allow Delegate Type Constraints
[ "", "c#", "generics", "events", "delegates", "constraints", "" ]
What is the correct way to do this? For example, how would I change a stored procedure with this signature: ``` CREATE PROCEDURE dbo.MyProcedure @Param BIT = NULL AS SELECT * FROM dbo.SomeTable T WHERE T.SomeColumn = @Param ``` So that giving @Param with a value of 1 or 0 performs the filter, but not specifyi...
Assuming that NULL means "don't care" then use ``` CREATE PROCEDURE dbo.MyProcedure @Param BIT = NULL AS SELECT * FROM dbo.SomeTable T WHERE T.SomeColumn = @Param OR @Param IS NULL ```
There's more than one way. Here's one: ``` SELECT * FROM dbo.SomeTable T WHERE T.SomeColumn = COALESCE(@Param, T.SomeColumn) ``` but this will not include rows for which T.SomeColumn is NULL. The following alternative will include those rows: ``` SELECT * FROM dbo.SomeTable T WHERE T.SomeColumn = @Param OR ...
Using a tristate parameter in a stored procedure
[ "", "sql", "stored-procedures", "" ]
The SQL implementation of relational databases has been around in their current form for something like 25 years (since System R and Ingres). Even the main (loosely adhered to) standard is ANSI-92 (although there were later updates) is a good 15 years old. What innovations can you think of with SQL based databases in ...
* Hash joins * Cost-based optimizers (pretty much turned query-writing on its head) * Partitioning (enables much better VLDB management) * Parallel (multi-threaded) query processing * Clustering (not just availability but scalability too) * More flexibility in SQL as well as easier integration of SQL with 3GL languages...
Analytic functions like RANK
What relational database innovations have there been in the last 10 years
[ "", "sql", "database", "relational", "" ]
Should I create two `CFile` objects and copy one into the other character by character? Or is there something in the library that will do this for me?
I would just use the [`CopyFile`](https://learn.microsoft.com/en-us/windows/win32/api/winbase/nf-winbase-copyfile) Win32 API function, but the example code in the [`CFile::Open`](https://learn.microsoft.com/en-us/cpp/mfc/reference/cfile-class?view=msvc-160#open) documentation shows how to copy files with `CFile` (using...
It depends on what you want to do. There are a number of ways to copy files: * `CopyFile()` * `CopyFileEx()` * `SHFileOperation()` * `IFileOperation` (replaces `SHFileOperation()` in Vista)
In an MFC application, what's the easiest way to copy a file from one directory to another?
[ "", "c++", "windows", "mfc", "file", "" ]
In Eclipse (Ganymede) I'm debugging some code that uses Apache Commons HttpClient and would like to step into the HttpClient code. I've downloaded the source code and tried to attach it in the normal fashion (CTRL-click on the method name and use the Attach Source button). I've tried to attach both as external file and...
Try pointing it at a directory containing the top level package directly, "D:/Data/Download/commons-httpclient-3.1/src/java" for you. What worked for me was creating a new src zip file containing the "org" folder and everything beneath it. Here's my .classpath entry, (which works for me) in case it helps: ``` <classp...
I've found that sometimes, you point to the directory you'd assume was correct, and then it still states that it can't find the file in the attached source blah blah. These times, I've realized that the last path element was "src". Just removing this path element (thus indeed pointing one level above the actual path w...
Attach Source Issue in Eclipse
[ "", "java", "eclipse", "eclipse-3.4", "ganymede", "" ]