Prompt
stringlengths
10
31k
Chosen
stringlengths
3
29.4k
Rejected
stringlengths
3
51.1k
Title
stringlengths
9
150
Tags
listlengths
3
7
I looking for a way, specifically in PHP that I will be guaranteed to always get a unique key. I have done the following: ``` strtolower(substr(crypt(time()), 0, 7)); ``` But I have found that once in a while I end up with a duplicate key (rarely, but often enough). I have also thought of doing: ``` strtolower(sub...
There are only 3 ways to generate unique values, rather they be passwords, user IDs, etc.: 1. Use an effective GUID generator - these are long and cannot be shrunk. If you only use part **you FAIL**. 2. At least part of the number is sequentially generated off of a single sequence. You can add fluff or encoding to mak...
**Any algorithm will result in duplicates**. Therefore, might I suggest that you use your existing algorithm\* and simply check for duplicates? \*Slight addition: If `uniqid()` can be non-unique based on time, also include a global counter that you increment after every invocation. That way something is different eve...
Unique key generation
[ "", "php", "web-services", "security", "passwords", "" ]
Consider these two function definitions: ``` void foo() { } void foo(void) { } ``` Is there any difference between these two? If not, why is the `void` argument there? Aesthetic reasons?
**Historical note:** this answer applies to C17 and older editions. C23 and later editions treat `void foo()` differently. --- In **C**: * `void foo()` means "a function `foo` taking an unspecified number of arguments of unspecified type" * `void foo(void)` means "a function `foo` taking no arguments" In **C++**: ...
I realize your question pertains to C++, but when it comes to C the answer can be found in [K&R](https://en.wikipedia.org/wiki/The_C_Programming_Language), pages 72-73: > Furthermore, if a function declaration does not include arguments, as > in > > ``` > double atof(); > ``` > > that too is taken to mean that nothing...
Is there a difference between foo(void) and foo() in C++ or C?
[ "", "c++", "c", "arguments", "function-declaration", "" ]
When compiling my C++ .Net application I get 104 warnings of the type: ``` Warning C4341 - 'XX': signed value is out of range for enum constant ``` Where XX can be * WCHAR * LONG * BIT * BINARY * GUID * ... I can't seem to remove these warnings whatever I do. When I double click on them it takes me to a part of my ...
This is a [compiler bug](http://forums.msdn.microsoft.com/en-US/vclanguage/thread/7bc77d72-c223-4d5e-b9f7-4c639c68b624/). Here's [another post](http://forums.microsoft.com/MSDN/ShowPost.aspx?PostID=159519&SiteID=1) confirming it's a known issue. I've got the same issue in one of my projects and there's no way to preven...
In Visual Studio you can always disable specific warnings by going to: > Project settings -> C/C++ -> Advanced -> Disable Specific warnings: 4341
Warning C4341 - 'XX': signed value is out of range for enum constant
[ "", ".net", "c++", "visual-c++", "" ]
What is the best way of implementing a cache for a PHP site? Obviously, there are some things that shouldn't be cached (for example search queries), but I want to find a good solution that will make sure that I avoid the 'digg effect'. I know there is WP-Cache for WordPress, but I'm writing a custom solution that isn'...
If a proxy cache is out of the question, and you're serving complete HTML files, you'll get the best performance by bypassing PHP altogether. Study how [WP Super Cache](http://ocaoimh.ie/wp-super-cache/) works. Uncached pages are copied to a cache folder with similar URL structure as your site. On later requests, mod\...
You can use [output buffering](https://www.php.net/manual/en/function.ob-get-contents.php) to selectively save parts of your output (those you want to cache) and display them to the next user if it hasn't been long enough. This way you're still rendering other parts of the page on-the-fly (e.g., customizable boxes, per...
How do I implement a HTML cache for a PHP site?
[ "", "php", "html", "caching", "" ]
Is there a way using Python's standard library to easily determine (i.e. one function call) the last day of a given month? If the standard library doesn't support that, does the dateutil package support this?
[`calendar.monthrange`](https://docs.python.org/library/calendar.html#calendar.monthrange) provides this information: > calendar.**monthrange**(year, month) >     Returns weekday of first day of the month and number of days in month, for the specified *year* and *month*. ``` >>> import calendar >>> calendar.monthra...
If you don't want to import the `calendar` module, a simple two-step function can also be: ``` import datetime def last_day_of_month(any_day): # The day 28 exists in every month. 4 days later, it's always next month next_month = any_day.replace(day=28) + datetime.timedelta(days=4) # subtracting the number...
Get the last day of the month
[ "", "python", "date", "" ]
Anyone who writes client-side JavaScript is familiar with the DOM - the tree structure that your browser references in memory, generated from the HTML it got from the server. JavaScript can add, remove and modify nodes on the DOM tree to make changes to the page. I find it very nice to work with (browser bugs aside), a...
You're describing [Rhino on Rails](http://www.youtube.com/watch?v=1QD9XQm_Jd4), which is not out but will be soon. Similarly, [Aptana Jaxer](http://www.aptana.com/jaxer/), however RnR will include an actual framework (Rails) whereas Jaxer is just the server technology.
Aptana's Jaxer AJAX server might be something for you to check out, as it uses JS server-side, as well. That being said, I would argue that you're better off not generating your markup with print statements or echos, but rather template and hook in your dynamic content.
Tree-Based (vs. HTML-Based) Web Framework?
[ "", "javascript", "html", "dom", "" ]
I have a bunch of legacy documents that are HTML-like. As in, they look like HTML, but have additional made up tags that aren't a part of HTML ``` <strong>This is an example of a <pseud-template>fake tag</pseud-template></strong> ``` I need to parse these files. PHP is the only only tool available. The documents don'...
You can suppress warnings with [`libxml_use_internal_errors`](http://www.php.net/manual/en/function.libxml-use-internal-errors.php), while loading the document. Eg.: ``` libxml_use_internal_errors(true); $doc = new DomDocument(); $doc->loadHTML("<strong>This is an example of a <pseud-template>fake tag</pseud-template>...
I wonder if passing the "bad" HTML through [HTML Tidy](http://www.w3.org/People/Raggett/tidy/) might help as a first pass? Might be worth a look, if you can get the document to be well formed, maybe you could load it as a regular XML file with DomDocument.
Error Tolerant HTML/XML/SGML parsing in PHP
[ "", "php", "html", "xml", "parsing", "" ]
I've created a python object, but I want to send signals on it. I made it inherit from gobject.GObject, but there doesn't seem to be any way to create a new signal on my object.
You can also define signals inside the class definition: ``` class MyGObjectClass(gobject.GObject): __gsignals__ = { "some-signal": (gobject.SIGNAL_RUN_FIRST, gobject.TYPE_NONE, (object, )), } ``` The contents of the tuple are the the same as the three last arguments to `gobject.signal_new`.
Here is how: ``` import gobject class MyGObjectClass(gobject.GObject): ... gobject.signal_new("signal-name", MyGObjectClass, gobject.SIGNAL_RUN_FIRST, None, (str, int)) ``` Where the second to last argument is the return type and the last argument is a tuple of argument types.
How do I create a new signal in pygtk
[ "", "python", "gtk", "pygtk", "gobject", "" ]
I'm a pretty new C# and .NET developer. I recently created an MMC snapin using C# and was gratified by how easy it was to do, especially after hearing a lot of horror stories by some other developers in my organisation about how hard it is to do in C++. I pretty much went through the whole project at some point and ma...
I believe in blackboxes where possible. As a programmer, I want a well defined blackbox which I can easily drop into my systems, and have it work. I give it values, call the appropriate methods, and then get my results back out of it. To that end, give me only the functionality that the class needs to expose to work. ...
What you did is exactly what you should do; give your classes the most minimal visibility you can. Heck, if you want to really go whole hog, you can make *everything* `internal` (at most) and use the [`InternalsVisibleTo` attribute](https://learn.microsoft.com/en-us/dotnet/api/system.runtime.compilerservices.internalsv...
Should I use internal or public visibility by default?
[ "", "c#", ".net", "public", "internals", "" ]
I've been trying to figure out a regex to allow me to search for a particular string while automatically skipping comments. Anyone have an RE like this or know of one? It doesn't even need to be sophisticated enough to skip `#if 0` blocks; I just want it to skip over `//` and `/*` blocks. The converse, that is only sea...
This is a harder problem than it might at first appear, since you need to consider comment tokens inside strings, comment tokens that are themselves commented out etc. I wrote a string and comment parser for C#, let me see if I can dig out something that will help... I'll update if I find anything. EDIT: ... ok, so I...
Be especially careful with strings. Strings often have escape sequences which you also have to respect while you're finding the end of them. So e.g. `"This is \"a test\""`. You cannot blindly look for a double-quote to terminate. Also beware of ``"This is \"`, which shows that you cannot just say "unless double-quote ...
Regex's For Developers
[ "", "c++", "regex", "visual-c++", "utilities", "" ]
So I have an object which has some fields, doesn't really matter what. I have a generic list of these objects. ``` List<MyObject> myObjects = new List<MyObject>(); myObjects.Add(myObject1); myObjects.Add(myObject2); myObjects.Add(myObject3); ``` So I want to remove objects from my list based on some criteria. For ins...
There's two options, an explicit delegate or a delegate disguised as a lamba construct: explicit delegate ``` myObjects.RemoveAll(delegate (MyObject m) { return m.X >= 10; }); ``` lambda ``` myObjects.RemoveAll(m => m.X >= 10); ``` --- Performance wise both are equal. As a matter of fact, both language constructs...
The lambda C# 3.0 way: ``` myObjects.RemoveAll(m => m.x >= 10); ``` The anonymous delegate C# 2.0 way: ``` myObjects.RemoveAll(delegate (MyObject m) { return m.x >= 10; }); ``` And, for the VB guys, the VB 9.0 lambda way: ``` myObjects.RemoveAll(Function(m) m.x >= 10) ``` Unfortunately, VB doesn't support an a...
How do you declare a Predicate Delegate inline?
[ "", "c#", "delegates", "" ]
What would be the best way to develop a text box that remembers the last x number of entries that were put into it. This is a standalone app written with C#.
[@Ethan](https://stackoverflow.com/questions/42966/google-suggestish-text-box#45014) I forgot about the fact that you would want to save that so it wasn't a per session only thing :P But yes, you are completely correct. This is easily done, especially since it's just basic strings, just write out the contents of Auto...
This is actually fairly easy, especially in terms of showing the "AutoComplete" part of it. In terms of remembering the last x number of entries, you are just going to have to decide on a particular event (or events) that you consider as an entry being completed and write that entry off to a list... an AutoCompleteStri...
Google Suggestish text box (autocomplete)
[ "", "c#", "winforms", "autocomplete", "" ]
Can you please tell me how much is `(-2) % 5`? According to my Python interpreter is 3, but do you have a wise explanation for this? I've read that in some languages the result can be machine-dependent, but I'm not sure though.
By the way: most programming languages would disagree with Python and give the result `-2`. Depending on the interpretation of modulus this is correct. However, the most agreed-upon mathematical definition states that the modulus of *a* and *b* is the (strictly positive) rest *r* of the division of *a* / *b*. More prec...
Your Python interpreter is correct. One (stupid) way of calculating a modulus is to subtract or add the modulus until the resulting value is between 0 and (modulus − 1). e.g.: 13 mod 5 = (13 − 5) mod 5 = (13 − 10) mod 5 = 3 or in your case: −2 mod 5 = (−2 + 5) mod 5 = 3
Modulus operation with negatives values - weird thing?
[ "", "python", "math", "modulo", "" ]
I have a class: ``` class MyClass: def __init__(self, foo): if foo != 1: raise Error("foo is not equal to 1!") ``` and a unit test that is supposed to make sure the incorrect arg passed to the constructor properly raises an error: ``` def testInsufficientArgs(self): foo = 0 self.assertRaises((Err...
'Error' in this example could be any exception object. I think perhaps you have read a code example that used it as a metasyntatic placeholder to mean, "The Appropriate Exception Class". The baseclass of all exceptions is called 'Exception', and most of its subclasses are descriptive names of the type of error involve...
How about this: ``` class MyClass: def __init__(self, foo): if foo != 1: raise Exception("foo is not equal to 1!") import unittest class Tests(unittest.TestCase): def testSufficientArgs(self): foo = 1 MyClass(foo) def testInsufficientArgs(self): foo = 2 ...
How do I unit test an __init__() method of a python class with assertRaises()?
[ "", "python", "unit-testing", "exception", "" ]
Any recommendations for a javascript form validation library. I could try and roll my own (but I'm not very good at javascript). Needs to support checking for required fields, and preferably regexp validation of fields.
I've used [this library](http://tetlaw.id.au/view/javascript/really-easy-field-validation) for a couple of personal projects. It's pretty good, though I have had to make my own modifications to it a couple of times - nothing major, though, and it's easy enough to do so. I'm sure you already do this, but also validate ...
I am about to start implementing javascript validation in my forms using [jQuery Validation](http://bassistance.de/jquery-plugins/jquery-plugin-validation/). I think that StackOverflow users this jQuery plugin as well. It seems to be a very mature validation library, however it does build on top of jQuery, so it might ...
Recommendation for javascript form validation library
[ "", "javascript", "forms", "validation", "" ]
I have a web report that uses a Django form (new forms) for fields that control the query used to generate the report (start date, end date, ...). The issue I'm having is that the page should work using the form's initial values (unbound), but I can't access the cleaned\_data field unless I call `is_valid()`. But `is_v...
If you add this method to your form class: ``` def get_cleaned_or_initial(self, fieldname): if hasattr(self, 'cleaned_data'): return self.cleaned_data.get(fieldname) else: return self[fieldname].field.initial ``` you could then re-write your code as: ``` if request.method == '...
*Unbound* means there is no data associated with form (either initial or provided later), so the validation may fail. As mentioned in other answers (and in your own conclusion), you have to provide initial values and check for both bound data and initial values. The use case for forms is form processing **and** valida...
How to use form values from an unbound form
[ "", "python", "django", "" ]
I have an Java desktop application which connects directly with the DB (an Oracle). The application has multiple user accounts. What is the correct method to send the user's password (not DB password) over the network? I don't want to send it in plain text.
You could connect over a secure socket connection, or hash the password locally before sending it to the database (or better, both) - Ideally, the only time the password should exist in plain text form is prior to hashing. If you can do all of that on the client side, more the better.
You can use SSL connection between Oracle client and Oracle database. To configure SSL between oracle client and server using JDBC: At server side: 1) First of all, the listener must be configured to use the TCPS protocol: ``` LISTENER = (ADDRESS_LIST= (ADDRESS=(PROTOCOL=tcps)(HOST=servername)(PORT=2484))) WALLET_L...
In a client-server application: How to send to the DB the user's application password?
[ "", "java", "oracle", "security", "passwords", "" ]
I am writing picture editing windows forms application using vb.net/c#. i have a client requirement to capture the photo from digital still camera attached to computer. how can i capture a photo from USB connected digital still camera device in my windows application ?
If you use the Windows Image Acquisition Library, you'll see events there for capturing camera new picture events. I had a similar requirement and wrote a test rig; we went down to the local camera store and tried every camera they had. The only cameras we could find that supported this functionality were the Nikon D-s...
I assume you want to activate the action of taking a picture from the computer which the camera is attached to. If that is the case then the first thing I would do is search for an API for that particular camera model. I don't believe there is a standard protocol/framework for interacting with digital cameras besides a...
how do i take picture from a digital camera attached to my computer throught USB cable using vb.net or asp.net or C#?
[ "", "c#", "vb.net", "image-capture", "" ]
Let's say I write a DLL in C++, and declare a global object of a class with a non-trivial destructor. Will the destructor be called when the DLL is unloaded?
In a Windows C++ DLL, all global objects (including static members of classes) will be constructed just before the calling of the DllMain with DLL\_PROCESS\_ATTACH, and they will be destroyed just after the call of the DllMain with DLL\_PROCESS\_DETACH. Now, you must consider three problems: 0 - Of course, global non...
This page from Microsoft goes into the details of DLL initialization and destruction of globals: <http://msdn.microsoft.com/en-us/library/988ye33t.aspx>
What happens to global variables declared in a DLL?
[ "", "c++", "windows", "dll", "" ]
Here is a quick test program: ``` public static void main( String[] args ) { Date date = Calendar.getInstance().getTime(); System.out.println("Months:"); printDate( "MMMM", "en", date ); printDate( "MMMM", "es", date ); printDate( "MMMM", "fr", date ); printDate( "MMMM", "de", date ); ...
Not all languages share english capitalization rules. I guess you'd need to alter the data used by the API, but your non-english clients might not appreciate it... [about.com on french capitalization](http://french.about.com/library/writing/bl-capitalization.htm)
Capitalisation rules are different for different languages. In French, month names [should not be capitalised](http://french.about.com/library/writing/bl-capitalization.htm).
How to control the capitalization of month and day names returned by DateFormat?
[ "", "java", "date", "internationalization", "" ]
I want to point a file dialog at a particular folder in the current user's Local Settings folder on Windows. What is the shortcut to get this path?
How about this, for example: ``` String appData = Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData); ``` I don't see an enum for just the Local Settings folder. <http://web.archive.org/web/20080303235606/http://dotnetjunkies.com/WebLog/nenoloje/archive/2007/07/07/259223.aspx> has a list ...
``` string localPath = Directory.GetParent(Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData)).FullName; ``` is the simple answer.
How do I get the current user's Local Settings folder path in C#?
[ "", "c#", ".net", "windows", "" ]
I'm having a little trouble figuring out exactly how const applies in a specific case. Here's the code I have: ``` struct Widget { Widget():x(0), y(0), z(0){} int x, y, z; }; struct WidgetHolder //Just a simple struct to hold four Widgets. { WidgetHolder(Widget a, Widget b, Widget c, Widget d): A(a), B(b...
This compiles because although the WidgetHolder is a const object, this const-ness does not automatically apply to objects pointed to (referenced by) the WidgetHolder. Think of it at a machine level - if the WidgetHolder object itself were held in read-only memory, you could still write to things that were pointed to b...
You need to create a new type specifically for holding const Widget& objects. Ie: ``` struct ConstWidgetHolder { ConstWidgetHolder(const Widget &a, const Widget &b, const Widget &c, const Widget &d): A(a), B(b), C(c), D(d){} const Widget& A; const Widget& B; const Widget& C; const Widget& D; }; c...
Const Struct&
[ "", "c++", "constants", "" ]
When using the php include function the include is succesfully executed, but it is also outputting a char before the output of the include is outputted, the char is of hex value 3F and I have no idea where it is coming from, although it seems to happen with every include. At first I thbought it was file encoding, but ...
What you are seeing is a UTF-8 Byte Order Mark: > The UTF-8 representation of the BOM is the byte sequence EF BB BF, which appears as the ISO-8859-1 characters  in most text editors and web browsers not prepared to handle UTF-8. > > [Byte Order Mark on Wikipedia](http://en.wikipedia.org/wiki/Byte_Order_Mark) PHP d...
Your web server (or your text editor) apparently includes a [BOM](http://en.wikipedia.org/wiki/Byte_order_mark) into the document. I don't see the rogue character in my browser except when I set the site's encoding explicitly to Latin-1. Then, I see two (!) UTF-8 BOMs. /EDIT: From the fact that there are *two* BOMs I ...
PHP Include function outputting unknown char
[ "", "php", "encoding", "byte-order-mark", "" ]
I have a members table in MySQL ``` CREATE TABLE `members` ( `id` int(10) unsigned NOT NULL auto_increment, `name` varchar(65) collate utf8_unicode_ci NOT NULL, `order` tinyint(3) unsigned NOT NULL default '0', PRIMARY KEY (`id`) ) ENGINE=InnoDB; ``` And I would like to let users order the members how they ...
You can do the SELECT as part of the INSERT, such as: ``` INSERT INTO members SELECT 0, "new member", max(`order`)+1 FROM members; ``` Keep in mind that you are going to want to have an index on the `order` column to make the SELECT part optimized. In addition, you might want to reconsider the tinyint for order, unl...
Since you already automatically increment the id for each new member, you can order by id.
How to determine order for new item?
[ "", "php", "mysql", "" ]
For example which is better: ``` select * from t1, t2 where t1.country='US' and t2.country=t1.country and t1.id=t2.id ``` or ``` select * from t1, t2 where t1.country'US' and t2.country='US' and t1.id=t2.id ``` better as in less work for the database, faster results. **Note:** Sybase, and there's an index on both ...
I had a situation similar to this and this was the solution I resorted to: Select \* FROM t1 INNER JOIN t2 ON t1.id = t2.id AND t1.country = t2.country AND t1.country = 'US' I noticed that my query ran faster in this scenario. I made the assumption that joining on the constant saved the engine time because the WHERE ...
I don't think there is a global answer to your question. It depends on the specific query. You would have to compare the execution plans for the two queries to see if there are significant differences. I personally prefer the first form: select \* from t1, t2 where t1.country='US' and t2.country=t1.country and t1.id=...
Is it better to join two fields together, or to compare them each to the same constant?
[ "", "sql", "join", "" ]
Is anyone using the Obout controls in C# .Net? How would you rate these controls, especially the Grid Control?
I was thoroughly impressed with them. Of all the other control sets out there (infragistics, telerik) this is the only (more than) respectable one I've worked with that was 1) free! and 2) lightweight!. The only caveat to Obout is I had trouble with merging some of these controls and some of the stock AJAX components. ...
I like obout for their lightweight'ness. Their licensing policy is very fair (pay once free updates for life) and they also give (free) educational licenses. However, I had to use Developer Express on one of my projects and never looked back since. Very powerful and not as bloated as Infragistics. Basically, if you d...
Obout controls in C# .Net
[ "", "c#", ".net", "obout", "" ]
I am calling, through reflection, a method which may cause an exception. How can I pass the exception to my caller without the wrapper reflection puts around it? I am rethrowing the InnerException, but this destroys the stack trace. Example code: ``` public void test1() { // Throw an exception for testing purp...
In **.NET 4.5** there is now the [`ExceptionDispatchInfo`](https://learn.microsoft.com/en-us/dotnet/api/system.runtime.exceptionservices.exceptiondispatchinfo) class. This lets you capture an exception and re-throw it without changing the stack-trace: ``` using ExceptionDispatchInfo = System.Runtime.ExceptionSer...
It **is** possible to preserve the stack trace before rethrowing without reflection: ``` static void PreserveStackTrace (Exception e) { var ctx = new StreamingContext (StreamingContextStates.CrossAppDomain) ; var mgr = new ObjectManager (null, ctx) ; var si = new SerializationInfo (e.GetType (), new ...
How to rethrow InnerException without losing stack trace in C#?
[ "", "c#", ".net", "exception", "" ]
I have never "hand-coded" object creation code for SQL Server and foreign key decleration is seemingly different between SQL Server and Postgres. Here is my sql so far: ``` drop table exams; drop table question_bank; drop table anwser_bank; create table exams ( exam_id uniqueidentifier primary key, exam_name ...
``` create table question_bank ( question_id uniqueidentifier primary key, question_exam_id uniqueidentifier not null, question_text varchar(1024) not null, question_point_value decimal, constraint fk_questionbank_exams foreign key (question_exam_id) references exams (exam_id) ); ```
And if you just want to create the constraint on its own, you can use ALTER TABLE ``` alter table MyTable add constraint MyTable_MyColumn_FK FOREIGN KEY ( MyColumn ) references MyOtherTable(PKColumn) ``` I wouldn't recommend the syntax mentioned by Sara Chipps for inline creation, just because I would rather name my ...
How do I create a foreign key in SQL Server?
[ "", "sql", "sql-server", "t-sql", "" ]
I've created a custom exception for a very specific problem that can go wrong. I receive data from another system, and I raise the exception if it bombs while trying to parse that data. In my custom exception, I added a field called "ResponseData", so I can track exactly what my code couldn't handle. In custom excepti...
You shouldn't fill `.Message` with debug information, but rather with a concise, helpful piece of text. <http://msdn.microsoft.com/en-us/library/system.exception.message.aspx> > **The text of Message should completely describe the error and should, when possible, explain how to correct it.** The value of the Message ...
> In custom exceptions such as this one, > should that extra response data go > into the exception "message"? No, as [Sören already pointed out](https://stackoverflow.com/questions/48773/adding-extra-information-to-a-custom-exception#48792). However, your exception type could override `ToString` and sensibly add the r...
Adding extra information to a custom exception
[ "", "c#", ".net", "exception", "elmah", "" ]
Are there any prebuilt modules for this? Is there an event thats called everytime a page is loaded? I'm just trying to secure one of my more important admin sections.
As blowdart said, simple IP Address logging is handled by IIS already. Simply right-click on the Website in Internet Information Services (IIS) Manager tool, go to the Web Site tab, and check the Enable Logging box. You can customize what information is logged also. If you want to restrict the site or even a folder of...
A little more information please; do you want to log IPs or lock access via IP? Both those functions are built into IIS rather than ASP.NET; so are you looking for how to limit access via IP programatically?
Asp.net c# and logging ip access on every page and frequency
[ "", "c#", "logging", "ip-address", "" ]
Do you know any open source/free software C++ libraries to manipulate images in these formats: .jpg .gif .png .bmp ? The more formats it supports, the better. I am implementing a free program in C++ which hides a text file into one or more images, using [steganography](http://en.wikipedia.org/wiki/Steganography). I am...
[ImageMagick](http://www.imagemagick.org/) can manipulate about anything and has interfaces for a [dozen of languages](https://imagemagick.org/script/develop.php), including the [Magick++](http://www.imagemagick.org/Magick++/) API for C++.
@lurks: I assume that you are looking for LSB shifting? I did some stego work a couple of years ago, and that's how it appeared most apps worked. It appears that ImageMagick (suggested by others) allows you to identify and manipulate the LSBs.
C++ libraries to manipulate images
[ "", "c++", "image", "steganography", "" ]
Is there any way in the Servlet API to access properties specified in web.xml (such as initialization parameters) from within a Bean or Factory class that is not associated at all with the web container? For example, I'm writing a Factory class, and I'd like to include some logic within the Factory to check a hierarch...
One way you could do this is: ``` public class FactoryInitialisingServletContextListener implements ServletContextListener { public void contextDestroyed(ServletContextEvent event) { } public void contextInitialized(ServletContextEvent event) { Properties properties = new Properties(); Se...
Have you considered using the Spring framework for this? That way, your beans don't get any extra cruft, and spring handles the configuration setup for you.
Is there a way to access web.xml properties from a Java Bean?
[ "", "java", "servlets", "" ]
Using reflection, I need to investigate a user DLL and create an object of a class in it. What is the simple way of doing it?
Try [Activator.CreateInstance](http://msdn.microsoft.com/en-us/library/system.activator.createinstance.aspx).
`System.Reflection.Assembly` is the class you will want to use. It contains many method for iterating over the types contained with a user DLL. You can iterate through each class, perhaps see if it inherits from a particular interface etc. <http://msdn.microsoft.com/en-us/library/system.reflection.assembly_members.asp...
Creating an object without knowing the class name at design time
[ "", "c#", "reflection", "" ]
This might be a bit on the silly side of things but I need to send the contents of a DataTable (unknown columns, unknown contents) via a text e-mail. Basic idea is to loop over rows and columns and output all cell contents into a StringBuilder using .ToString(). Formatting is a big issue though. Any tips/ideas on how ...
Would converting the datatable to a HTML-table and sending HTML-mail be an alternative? That would make it much nicer on the receiving end if their client supports it.
This will sound like a really horrible solution, but it just might work: Render the DataTable contents into a DataGrid/GridView (assuming ASP.NET) and then screen scrape that. I told you it would be messy.
DataTable to readable text string
[ "", "c#", "formatting", "datatable", "" ]
``` EmployeeNumber = string.IsNullOrEmpty(employeeNumberTextBox.Text) ? null : Convert.ToInt32(employeeNumberTextBox.Text), ``` I often find myself wanting to do things like this (`EmployeeNumber` is a `Nullable<int>` as it's a property on a LINQ-to-SQL dbml object where the column allows NULL values). Unfortu...
The problem occurs because the conditional operator doesn't look at how the value is used (assigned in this case) to determine the type of the expression -- just the true/false values. In this case, you have a `null` and an `Int32`, and the type can not be determined (there are real reasons it can't just assume `Nullab...
I think a utility method could help make this cleaner. ``` public static class Convert { public static T? To<T>(string value, Converter<string, T> converter) where T: struct { return string.IsNullOrEmpty(value) ? null : (T?)converter(value); } } ``` then ``` EmployeeNumber = Convert.To<int>(emplo...
Conditional operator assignment with Nullable<value> types?
[ "", "c#", "conditional-operator", "nullable", "" ]
Is there any way to convert a bmp image to jpg/png without losing the quality in C#? Using Image class we can convert bmp to jpg but the quality of output image is very poor. Can we gain the quality level as good as an image converted to jpg using photoshop with highest quality?
``` var qualityEncoder = Encoder.Quality; var quality = (long)<desired quality>; var ratio = new EncoderParameter(qualityEncoder, quality ); var codecParams = new EncoderParameters(1); codecParams.Param[0] = ratio; var jpegCodecInfo = <one of the codec infos from ImageCodecInfo.GetImageEncoders() with mime type = "imag...
``` public static class BitmapExtensions { public static void SaveJPG100(this Bitmap bmp, string filename) { EncoderParameters encoderParameters = new EncoderParameters(1); encoderParameters.Param[0] = new EncoderParameter(System.Drawing.Imaging.Encoder.Quality, 100L); bmp.Sa...
Bmp to jpg/png in C#
[ "", "c#", "image-manipulation", "" ]
For many questions the answer seems to be found in "the standard". However, where do we find that? Preferably online. Googling can sometimes feel futile, again especially for the C standards, since they are drowned in the flood of discussions on programming forums. To get this started, since these are the ones I am s...
## PDF versions of the standard As of 1st September 2014 March 2022, the best locations by price for the official C and C++ standards documents in PDF seem to be: * C++20 – ISO/IEC 14882:2020: [212 CAD (about $165 US) from csagroup.org](https://www.csagroup.org/store/product/CSA%20ISO%25100IEC%2014882%3A21/?format=PD...
Online versions of the standard can be found: ### Working Draft, Standard for Programming Language C++ ***The following all draft versions of the standard***: All the following are freely downloadable 2023-12-18: [N4971](https://www.open-std.org/jtc1/sc22/wg21/docs/papers/2023/n4971.pdf) 2023-10-15: [N4964](http...
Where do I find the current C or C++ standard documents?
[ "", "c++", "c", "standards", "c++-faq", "" ]
I assumed that the C# margin property had a meaning like in CSS - the spacing around the outside of the control. But Margin values seem to be ignored to matter what values I enter. Then I read on the SDK: > Setting the Margin property on a > docked control has no effect on the > distance of the control from the the >...
The margin property is used by whatever layout engine your control host (Panel, for example) is using, in whatever way that layout engine sees fit. However, it is best used for spacing just as you assume. Just read the documentation for that specific layout engine. It can be very handy when using a FlowLayoutPanel or ...
Like Philip Rieck said, the margin property is only respected by container controls that perform layout. Here's an example that makes it fairly clear how the `TableLayoutPanel` respects the Margin property: ``` using System.Drawing; using System.Windows.Forms; namespace WindowsFormsApplication1 { public partial c...
What is the .NET Control.Margin property for?
[ "", "c#", "controls", "margin", "" ]
While searching the interweb for a solution for my VB.net problems I often find helpful articles on a specific topic, but the code is C#. That is no big problem but it cost some time to convert it to VB manually. There are some sites that offer code converters from C# to VB and vice versa, but to fix all the flaws afte...
If you cannot find a good converter, you could always compile the c# code and use the dissasembler in [Reflector](http://www.red-gate.com/products/reflector/) to see Visual Basic code. Some of the variable names will change.
Telerik has [a good converter](http://converter.telerik.com/) that is based on SharpDevelop that has worked pretty well over the years, though it has not been updated in years (due to it being based on SharpDevelop). I've recently come across a [roslyn based converter as well](http://web.archive.org/web/20180312203225...
What is the best C# to VB.net converter?
[ "", "c#", "vb.net", "converters", "" ]
I am curious if anyone have used UnderC, Cint, Cling, Ch, or any other C++ interpreter and could share their experience.
There is **[cling](http://cern.ch/cling) Cern's project** of C++ interpreter based on [clang](http://clang.llvm.org/) - it's *new approach* based on 20 years of experience in *ROOT cint* and it's quite stable and recommended by Cern guys. Here is nice [Google Talk: Introducing cling, a C++ Interpreter Based on clang/L...
**NOTE:** what follows is rather CINT specific, but given that its probably the most [widely used](http://www.google.com/search?hl=en&q=c%2b%2b%20interpreter) C++ interpreter it may be valid for them all. As a graduate student in particle physics who's used CINT extensively, I should warn you away. While it does "work...
Have you used any of the C++ interpreters (not compilers)?
[ "", "c++", "interpreter", "read-eval-print-loop", "" ]
Is there any complete guidance on doing AppBar docking (such as locking to the screen edge) in WPF? I understand there are InterOp calls that need to be made, but I'm looking for either a proof of concept based on a simple WPF form, or a componentized version that can be consumed. Related resources: * <http://www.cod...
**Please Note:** This question gathered a good amount of feedback, and some people below have made great points or fixes. Therefore, while I'll keep the code here (and possibly update it), I've also **created a [WpfAppBar project on github](https://github.com/PhilipRieck/WpfAppBar)**. Feel free to send pull requests. ...
There is an excellent MSDN article from 1996 which is entertainingly up to date: [Extend the Windows 95 Shell with Application Desktop Toolbars](http://web.archive.org/web/20170704171718/https://www.microsoft.com/msj/archive/S274.aspx). Following its guidance produces an WPF based appbar which handles a number of scena...
How do you do AppBar docking (to screen edge, like WinAmp) in WPF?
[ "", "c#", "wpf", "dock", "docking", "appbar", "" ]
Is there a way of getting the process id of my C++ application? I am using the Carbon framework, but not Cocoa…
can you use the getpid() function found in unistd.h ? [osx reference](https://developer.apple.com/library/archive/documentation/System/Conceptual/ManPages_iPhoneOS/man2/getpid.2.html)
Note that you don't actually need to call GetCurrentProcess, you can use the constant kCurrentProcess. (But getpid is a lot less work if you're not trying to access another process's PID, anyway.)
Is there a way of getting the process id of my C++ application?
[ "", "c++", "macos", "macos-carbon", "" ]
I've got some Java code using a servlet and Apache Commons FileUpload to upload a file to a set directory. It's working fine for character data (e.g. text files) but image files are coming out garbled. I can open them but the image doesn't look like it should. Here's my code: Servlet ``` protected void doPost(HttpSer...
One thing I don't like is here in this block from StreamUtils.getBytes(): ``` 1 while (true) { 2 int nBytesRead = src.read(buff); 3 if (nBytesRead < 0) { 4 break; 5 } 6 byteStream.write(buff); 7 } ``` At line 6, it writes the entire buffer, no matter how many bytes are read in. I am not convinced t...
I'd just use [commons io](http://commons.apache.org/io/) Then you could just do an IOUtils.copy(InputStream, OutputStream); It's got lots of other useful utility methods.
Why is my image coming out garbled?
[ "", "java", "file-io", "apache-commons-fileupload", "" ]
I'm wondering if there's such a thing as Django-like ease of web app development combined with good deployment, debugging and other tools? Django is a very productive framework for building content-heavy sites; the best I've tried and a breath of fresh air compared to some of the Java monstrosities out there. However ...
You asked for someone who used both Grails and Django. I've done work on both for big projects. Here's my Thoughts: **IDE's:** Django works really well in Eclipse, Grails works really well in IntelliJ Idea. **Debugging:** Practically the same (assuming you use IntelliJ for Grails, and Eclipse for Python). Step debugg...
> However it's written in Python which > means there's little real support in > the way of deployment/packaging, > debugging, profilers and other tools > that make building and maintaining > applications much easier. Python has: 1. a [great interactive debugger](http://docs.python.org/lib/module-pdb.html), which make...
Django -vs- Grails -vs-?
[ "", "python", "django", "frameworks", "" ]
Is there a built in function in .NET 2.0 that will take two arrays and merge them into one array? The arrays are both of the same type. I'm getting these arrays from a widely used function within my code base and can't modify the function to return the data in a different format. I'm looking to avoid writing my own f...
If you can manipulate one of the arrays, you can resize it before performing the copy: ``` T[] array1 = getOneArray(); T[] array2 = getAnotherArray(); int array1OriginalLength = array1.Length; Array.Resize<T>(ref array1, array1OriginalLength + array2.Length); Array.Copy(array2, 0, array1, array1OriginalLength, array2....
In C# 3.0 you can use LINQ's [Concat](https://msdn.microsoft.com/en-us/library/vstudio/bb302894%28v=vs.100%29.aspx) method to accomplish this easily: ``` int[] front = { 1, 2, 3, 4 }; int[] back = { 5, 6, 7, 8 }; int[] combined = front.Concat(back).ToArray(); ``` In C# 2.0 you don't have such a direct way, but Array....
Merging two arrays in .NET
[ "", "c#", ".net", "arrays", "" ]
I would like to display an RTF document in an SWT (actually Eclipse RCP) application. I know there is a Swing widget for displaying and editing RTF text, but it is Swing and quite alien in look and feel when used in the otherwise platform (not to mention that to the last of my knowledge it did not display images and h...
Actuall, I've just found another widget that is quite promising atm: <http://onpositive.com/richtext>
You may use swt.custom.StyledText. That has many features to change the look of the text. But I don't think it can load or save RTF right now. I once wrote an HTML editor with it, but it is quite difficult, since the StyledText model to add styles to a part of the text is so alien compared to the way HTML/RTF works. ...
Is there an RTF display widget in SWT
[ "", "java", "eclipse", "swt", "rtf", "" ]
I am looking for an easy way to check if an object in C# is serializable. As we know you make an object serializable by either implementing the *ISerializable* interface or by placing the *[Serializable]* at the top of the class. What I am looking for is a quick way to check this without having to reflect the class t...
You have a lovely property on the `Type` class called `IsSerializable`.
You're going to have to check all types in the graph of objects being serialized for the serializable attribute. The easiest way is to try to serialize the object and catch the exception. (But that's not the cleanest solution). Type.IsSerializable and checking for the serializalbe attribute don't take the graph into ac...
How to check if an object is serializable in C#
[ "", "c#", "serialization", "" ]
Is there a setting in ReSharper 4 (or even Visual Studio itself...) that forces a warning if I forget to wrap code in a `using` block, or omit the proper Dispose call in a `finally` block?
Correct automatic Dispose analysis requires DFA (Data Flow Analysis) in a global way. It is unlikely that you create an IDisposable object and doesn't call any method on it and do not pass it around as an argument. If disposable object is passed to other methods (including calling its members, when "this" is implicitly...
Discontent with current methods, I created my own: [EyeDisposable](https://github.com/kizzx2/EyeDisposable). It's an IL instrumenter so it should catch many leaks not caught by static analysis. It's still in its early stage, inputs are welcome.
Can ReSharper be set to warn if IDisposable not handled correctly?
[ "", "c#", ".net", "resharper", "static-analysis", "" ]
What's the simplest SQL statement that will return the duplicate values for a given column and the count of their occurrences in an Oracle database table? For example: I have a `JOBS` table with the column `JOB_NUMBER`. How can I find out if I have any duplicate `JOB_NUMBER`s, and how many times they're duplicated?
Aggregate the column by COUNT, then use a HAVING clause to find values that appear more than once. ``` SELECT column_name, COUNT(column_name) FROM table_name GROUP BY column_name HAVING COUNT(column_name) > 1; ```
Another way: ``` SELECT * FROM TABLE A WHERE EXISTS ( SELECT 1 FROM TABLE WHERE COLUMN_NAME = A.COLUMN_NAME AND ROWID < A.ROWID ) ``` Works fine (quick enough) when there is index on `column_name`. And it's better way to delete or update duplicate rows.
How do I find duplicate values in a table in Oracle?
[ "", "sql", "oracle", "duplicate-data", "" ]
Are there any good solutions to represent a parameterized enum in `C# 3.0`? I am looking for something like [OCaml](http://www.ocaml.org) or [Haxe](http://www.haxe.org) has. I can only think of class hierarchy with a simple enum field for easy switching for now, maybe there are better ideas? See Ocaml example below in...
Not being familiar with OCaml or Haxe, and not being clever enough to understand the other explanations, I went and looked up the [Haxe enum documentation](https://haxe.org/manual/types-enum-instance.html) - the 'Enum Type Parameters' bit at the bottom seems to be the relevant part. My understanding based on that is a...
Use a **class** that with static properties to represent the enumeration values. You can, optionally, use a private constructor to force all references to the class to go through a static property. Take a look at the `System.Drawing.Color` class. It uses this approach.
Best way to represent a parameterized enum in C#?
[ "", "c#", "enums", "ocaml", "haxe", "" ]
I'm having an issue with a query that currently uses ``` LEFT JOIN weblog_data AS pwd ON (pwd.field_id_41 != '' AND pwd.field_id_41 LIKE CONCAT('%', ewd.field_id_32, '%')) ``` However I'm discovering that I need it to only use that if there is no exact match first. What's happening is that the query is double d...
It sounds like you want to join the tables aliased as pwd and ewd in your snippet based first on an exact match, and if that fails, then on the like comparison you have now. Try this: ``` LEFT JOIN weblog_data AS pwd1 ON (pwd.field_id_41 != '' AND pwd.field_id_41 = ewd.field_id_32) LEFT JOIN weblog_data AS pwd2 ON (p...
you're talking about short circuit evaluation. Take a look at this article it might help you: <http://beingmarkcohen.com/?p=62>
SQL Query - Use Like only if no exact match exists?
[ "", "sql", "left-join", "" ]
I have a simple type that explicitly implemets an Interface. ``` public interface IMessageHeader { string FromAddress { get; set; } string ToAddress { get; set; } } [Serializable] public class MessageHeader:IMessageHeader { private string from; private string to; [XmlAttribute("From")] string IMess...
You cannot serialize IMessageHeader because you can't do Activator.CreateInstance(typeof(IMessageHeader)) which is what serialization is going to do under the covers. You need a concrete type. You can do typeof(MessageHeader) or you could say, have an instance of MessageHeader and do ``` XmlSerializer serializer = ne...
No, because the serializer needs a concrete class that it can instantiate. Given the following code: ``` XmlSerializer ser = new XmlSerializer(typeof(IMessageHeader)); IMessageHeader header = (IMessageHeader)ser.Deserialize(data); ``` What class does the serializer create to return from Deserialize()? In theory it...
XMLSerialization in C#
[ "", "c#", ".net", "serialization", "interface", "" ]
When I do a clean build my C# project, the produced dll is different then the previously built one (which I saved separately). No code changes were made, just clean and rebuild. Diff shows some bytes in the DLL have changes -- few near the beginning and few near the end, but I can't figure out what these represent. Do...
My best guess would be the changed bytes you're seeing are the internally-used metadata columns that are automatically generated at build-time. Some of the Ecma-335 Partition II (CLI Specification Metadata Definition) columns that can change per-build, even if the source code doesn't change at all: * Module.Mvid: A b...
I think that would be the TimeDateStamp field in the IMAGE\_FILE\_HEADER header of the [PE32 specifications](http://msdn.microsoft.com/en-us/library/ms809762.aspx).
Why is a different dll produced after a clean build, with no code changes?
[ "", "c#", ".net", "visual-studio", "build-process", "" ]
To complete some testing I need to load the 64 bit version of an assembly even though I am running a 32 bit version of Windows. Is this possible?
I'm not sure why you would want to do this, but I suppose you could. If you don't do anything to tell it otherwise, the CLR will load the version of the assembly that is specific to the CPU you are using. That's usually what you want. But I have had an occasion where I needed to load the neutral IL version of an assemb...
From CLR Via C# (Jeff Richter): "If your assembly files contain only type-safe managed code, you are writing code that should work on both 32-bit and 64-bit versions of Windows. No source code changes are required for your code to run on either version of Windows. In fact, the resulting EXE/DLL file produced by the c...
How to load a specific version of an assembly
[ "", "c#", ".net", "assemblies", "64-bit", "" ]
After reading [this description](http://www.colder.ch/news/08-24-2007/28/late-static-bindings-expl.html) of late static binding (LSB) I see pretty clearly what is going on. Now, under which sorts of circumstances might that be most useful or needed?
I needed LSB this for the following scenario: * Imagine you're building a "mail processor" daemon that downloads the message from an email server, classifies it, parses it, saves it, and then does something, depending on the type of the message. * Class hierarchy: you have a base Message class, with children "BouncedM...
One primary need I have for late static binding is for a set of static instance-creation methods. This [DateAndTime class](http://harmoni.sourceforge.net/harmoniDoc/phpdoc/harmoni/primitives.chronology/DateAndTime.html) is part of a chronology library that I ported to PHP from Smalltalk/Squeak. Using static instance-c...
When would you need to use late static binding?
[ "", "php", "oop", "" ]
I have a method in my Python code that returns a tuple - a row from a SQL query. Let's say it has three fields: (jobId, label, username) For ease of passing it around between functions, I've been passing the entire tuple as a variable called 'job'. Eventually, however, I want to get at the bits, so I've been using cod...
I'd say that a dictionary is definitely the best way to do it. It's easily extensible, allows you to give each value a sensible name, and Python has a lot of built-in language features for using and manipulating dictionaries. If you need to add more fields later, all you need to change is the code that converts the tup...
@Staale There is a better way: ``` job = dict(zip(keys, values)) ```
Splitting tuples in Python - best practice?
[ "", "python", "tuples", "" ]
I'm trying to build a better username/password field for my workplace and would like to be able to complain when they have their caps lock on. Is this possible? And if so I'd like to have it detected before the client types their first letter. Is there a non-platform specific way to do this?
Try this, from java.awt.Toolkit, returns a boolean: ``` Toolkit.getDefaultToolkit().getLockingKeyState(KeyEvent.VK_CAPS_LOCK) ```
here is some info on the class <http://java.sun.com/j2se/1.5.0/docs/api/java/awt/Toolkit.html#getLockingKeyState(int)>
How can I detect if caps lock is toggled in Swing?
[ "", "java", "swing", "" ]
Can you specialize a template method within a template class without specializing the class template parameter? Please note that the specialization is on the *value* of the template parameter, not its type. This seems to compile under Visual Studio 2008 SP1 complier, but not GCC 4.2.4. ``` #include <iostream> using ...
Here is another workaround, also useful when you need to partialy specialize a function (which is not allowed). Create a template functor class (ie. class whose sole purpose is to execute a single member function, usually named operator() ), specialize it and then call from within your template function. I think I lea...
It is not supported in the standard (and it is apparently a known bug with Visual Studio that you *can* do it). The standard doesn't allow an inner template (member function *or* class) to be specialized without the outer template being specialized as well. One of the reasons for this is that you can normally just ove...
C++ method expansion
[ "", "c++", "templates", "" ]
In C++, can member function pointers be used to point to derived (or even base) class members? EDIT: Perhaps an example will help. Suppose we have a hierarchy of three classes `X`, `Y`, `Z` in order of inheritance. `Y` therefore has a base class `X` and a derived class `Z`. Now we can define a member function pointer...
C++03 std, [§4.11 2 Pointer to member conversions](http://www.open-std.org/jtc1/sc22/WG21/docs/wp/html/nov97-2/conv.html#conv.mem): > An rvalue of type “pointer to member of B of type *cv* T,” where B is a class type, can be converted to an rvalue of type “pointer to member of D of type *cv* T,” where D is a derived c...
I'm not 100% sure what you are asking, but here is an example that works with virtual functions: ``` #include <iostream> using namespace std; class A { public: virtual void foo() { cout << "A::foo\n"; } }; class B : public A { public: virtual void foo() { cout << "B::foo\n"; } }; int main() { void (A::*...
C++ inheritance and member function pointers
[ "", "c++", "inheritance", "oop", "pointer-to-member", "" ]
No, this is not a question about generics. I have a Factory pattern with several classes with internal constructors (I don't want them being instantiated if not through the factory). My problem is that `CreateInstance` fails with a "No parameterless constructor defined for this object" error unless I pass "true" on t...
To get around this, couldnt you just alter your usage as such: ``` public class GenericFactory<T> where T : MyAbstractType { public static T GetInstance() { return Activator.CreateInstance(typeof(T), true); } } ``` Your factory method will still be generic, but the call to the activator will not u...
If you absolutely require that the constructor be private you can try something like this: ``` public abstract class GenericFactory<T> where T : MyAbstractType { public static T GetInstance() { return (T)Activator.CreateInstance(typeof(T), true); } } ``` Otherwise you're best off adding the new co...
Activator.CreateInstance(string) and Activator.CreateInstance<T>() difference
[ "", "c#", "generics", "design-patterns", "" ]
Which compiles to faster code: "ans = n \* 3" or "ans = n+(n\*2)"? Assuming that n is either an int or a long, and it is is running on a modern Win32 Intel box. Would this be different if there was some dereferencing involved, that is, which of these would be faster? ``` long a; long *pn; long ans; ... *p...
IMO such micro-optimization is not necessary unless you work with some exotic compiler. I would put readability on the first place.
It doesn't matter. Modern processors can execute an integer MUL instruction in one clock cycle or less, unlike older processers which needed to perform a series of shifts and adds internally in order to perform the MUL, thereby using multiple cycles. I would bet that ``` MUL EAX,3 ``` executes faster than ``` MOV EB...
Which compiles to faster code: "n * 3" or "n+(n*2)"?
[ "", "c++", "c", "optimization", "compiler-construction", "performance", "" ]
Are **CDATA** tags ever necessary in script tags and if so when? In other words, when and where is this: ``` <script type="text/javascript"> //<![CDATA[ ...code... //]]> </script> ``` preferable to this: ``` <script type="text/javascript"> ...code... </script> ```
A CDATA section is required if you need your document to parse as XML (e.g. when an XHTML page is interpreted as XML) *and you want to be able to write literal `i<10` and `a && b` instead of `i&lt;10` and `a &amp;&amp; b`*, as XHTML will parse the JavaScript code as parsed character data as opposed to character data by...
When browsers treat the markup as XML: ``` <script> <![CDATA[ ...code... ]]> </script> ``` When browsers treat the markup as HTML: ``` <script> ...code... </script> ``` When browsers treat the markup as HTML and you want your XHTML 1.0 markup (for example) to validate. ``` <script> //<![CDATA[ ...code....
When is a CDATA section necessary within a script tag?
[ "", "javascript", "html", "xhtml", "cdata", "" ]
I understand the overall meaning of pointers and references(or at least I think i do), I also understand that when I use **new** I am dynamically allocating memory. My question is the following: If i were to use `cout << &p`, it would display the "virtual memory location" of `p`. Is there a way in which I could manip...
Sure, you can manipulate the pointer to access the different elements in the array, but you will need to manipulate the content of the pointer (i.e. the address of what p is pointing to), rather than the address of the pointer itself. ``` int *p = new int[3]; p[0] = 13; p[1] = 54; p[2] = 42; cout << *p << ' ' << *(p+...
Not quite. `&p` is the address *of the pointer `p`*. `&p+1` will refer to an address which is one `int*` further along. What you want to do is ``` p=p+1; /* or ++p or p++ */ ``` Now when you do ``` cout << *p; ``` You will get 54. The difference is, `p` contains the *address of the start of the array of ints*, whil...
Change pointer to an array to get a specific array element
[ "", "c++", "pointers", "" ]
I have a `String` representation of a date that I need to create a `Date` or `Calendar` object from. I've looked through `Date` and `Calendar` APIs but haven't found anything that can do this other than creating my own ugly parse method. I know there must be a way, does anyone know of a solution?
In brief: ``` DateFormat formatter = new SimpleDateFormat("MM/dd/yy"); try { Date date = formatter.parse("01/29/02"); } catch (ParseException e) { e.printStackTrace(); } ``` See [`SimpleDateFormat` javadoc](http://docs.oracle.com/javase/7/docs/api/java/text/SimpleDateFormat.html) for more. And to turn it into a ...
# tl;dr ``` LocalDate.parse( "2015-01-02" ) ``` # java.time Java 8 and later has a new [java.time](http://docs.oracle.com/javase/8/docs/api/java/time/package-summary.html) framework that makes these other answers outmoded. This framework is inspired by [Joda-Time](http://www.joda.org/joda-time/), defined by [JSR 310...
How to convert a date String to a Date or Calendar object?
[ "", "java", "date", "calendar", "" ]
Suppose I have two applications written in C#. The first is a third party application that raises an event called "OnEmailSent". The second is a custom app that I've written that I would like to somehow subscribe to the "OnEmailSent" even of the first application. Is there any way that I could somehow attach the seco...
In order for two applications (separate processes) to exchange events, they must agree on how these events are communicated. There are many different ways of doing this, and exactly which method to use may depend on architecture and context. The general term for this kind of information exchange between processes is [I...
You can try [Managed Spy](http://msdn.microsoft.com/en-us/magazine/cc163617.aspx) and for programmatic access **ManagedSpyLib** > ManagedSpyLib introduces a class > called ControlProxy. A ControlProxy is > a representation of a > System.Windows.Forms.Control in > another process. ControlProxy allows > you to get or se...
Listen for events in another application
[ "", "c#", "events", "delegates", "" ]
In VB.net I'm using the TcpClient to retrieve a string of data. I'm constantly checking the .Connected property to verify if the client is connected but even if the client disconnects this still returns true. What can I use as a workaround for this? This is a stripped down version of my current code: ``` Dim client a...
When NetworkStream.Read returns 0, then the connection has been closed. [Reference](http://msdn.microsoft.com/en-us/library/system.net.sockets.networkstream.read(VS.71).aspx): > If no data is available for reading, the NetworkStream.Read method will block until data is available. To avoid blocking, you can use the Dat...
Better answer: ``` if (client.Client.Poll(0, SelectMode.SelectRead)) { byte[] checkConn = new byte[1]; if (client.Client.Receive(checkConn, SocketFlags.Peek) == 0) throw new IOException(); } ```
TcpClient.Connected returns true yet client is not connected, what can I use instead?
[ "", "c#", ".net", "vb.net", "sockets", "" ]
I have two unrelated processes that use .NET assemblies as plugins. However, either process can be started/stopped at any time. I can't rely on a particular process being the server. In fact, there may be multiple copies running of one of the processes, but only one of the other. I initially implemented a solution bas...
Using shared memory is tougher because you'll have to manage the size of the shared memory buffer (or just pre-allocate enough). You'll also have to manually manage the data structures that you put in there. Once you have it tested and working though, it will be easier to use and test because of its simplicity. If you...
Why not host the server and the client on both sides, and whoever comes up first gets to be the server? And if the server drops out, the client that is still active switches roles.
.NET IPC without having a service mediator
[ "", "c#", ".net", "windows", "remoting", "ipc", "" ]
I need to send MMS thought a C# application. I have already found 2 interesting components: <http://www.winwap.com> <http://www.nowsms.com> Does anyone have experience with other third party components? Could someone explain what kind of server I need to send those MMS? Is it a classic SMTP Server?
Typically I have always done this using a 3rd party aggregator. The messages are compiled into SMIL, which is the description language for the MMS messages. These are then sent on to the aggregator who will then send them through the MMS gateway of the Network Operator. They are typically charged on a per message basis...
You could do it yourself. Some MMS companies just have a SOAP API that you can call. All you need to do is construct the XML and send it off via a URL. I have done this once before, but can't remember the name of the company I used.
How to send MMS with C#
[ "", "c#", "mms", "" ]
I'd like to use a different icon for the demo version of my game, and I'm building the demo with a different build config than I do for the full verison, using a preprocessor define to lockout some content, use different graphics, etc. Is there a way that I can make Visual Studio use a different icon for the app Icon i...
According to [this page](http://msdn.microsoft.com/en-us/library/aa381033(VS.85).aspx) you may use preprocessor directives in your \*.rc file. You should write something like this ``` #ifdef _DEMO_VERSION_ IDR_MAINFRAME ICON "demo.ico" #else IDR_MAINFRAME ICON "full.ico" #endif ```
What I would do is setup a pre-build event (Project properties -> Configuration Properties -> Build Events -> Pre-Build Event). The pre-build event is a command line. I would use this to copy the appropriate icon file to the build icon. For example, let's say your build icon is 'app.ico'. I would make my fullicon 'app...
Change app icon in Visual Studio 2005?
[ "", "c++", "visual-studio-2005", "icons", "visual-c++-2005", "" ]
Why isn't [Collection.remove(Object o)](http://java.sun.com/javase/6/docs/api/java/util/Collection.html#remove(java.lang.Object)) generic? Seems like `Collection<E>` could have `boolean remove(E o);` Then, when you accidentally try to remove (for example) `Set<String>` instead of each individual String from a `Collec...
Josh Bloch and Bill Pugh refer to this issue in [*Java Puzzlers IV: The Phantom Reference Menace, Attack of the Clone, and Revenge of The Shift*](https://www.youtube.com/watch?v=wDN_EYUvUq0). Josh Bloch says (6:41) that they attempted to generify the get method of Map, remove method and some other, but "it simply didn...
`remove()` (in `Map` as well as in `Collection`) is not generic because you should be able to pass in any type of object to `remove()`. The object removed does not have to be the same type as the object that you pass in to `remove()`; it only requires that they be equal. From the specification of `remove()`, `remove(o)...
Why aren't Java Collections remove methods generic?
[ "", "java", "generics", "collections", "" ]
Right now I'm developing mostly in C/C++, but I wrote some small utilities in Python to automatize some tasks and I really love it as language (especially the productivity). Except for the performances (a problem that could be sometimes solved thanks to the ease of interfacing Python with C modules), do you think it i...
We've used IronPython to build our flagship spreadsheet application (40kloc production code - and it's Python, which IMO means loc per feature is low) at [Resolver Systems](http://www.resolversystems.com/), so I'd definitely say it's ready for production use of complex apps. There are two ways in which this might not ...
You'll find mostly two answers to that – the religous one (Yes! Of course! It's the best language ever!) and the other religious one (you gotta be kidding me! Python? No... it's not mature enough). I will maybe skip the last religion (Python?! Use Ruby!). The truth, as always, is far from obvious. **Pros**: it's easy,...
Is Python good for big software projects (not web based)?
[ "", "python", "ide", "" ]
This is a follow up question to [This Question](https://stackoverflow.com/questions/85815/how-to-tell-if-a-javascript-function-is-defined). I like (and understand) the solution there. However, in the code I am working in, another way to solve the same problem is used: ``` function exist(sFN) { if(self[sFN]) retur...
Your condition is checking the existence of the "sFN" property in the "self" object. Anything that isn't null, undefined, 0, and "" will evaluate to true. As others have said, you can use typeof, or instanceof to see if it's actually a function. Looking at your linked example, you should read up on the difference bet...
Try this: ``` function exist(sFN) { return (typeof sFN == 'function'); } ```
Tell if a Javascript function is defined by looking at self[name] - is this a good way?
[ "", "javascript", "" ]
Is there a difference between just saying `throw;` and `throw ex;` assuming `ex` is the exception you're catching?
`throw ex;` will erase your stacktrace. Don't do this unless you mean to clear the stacktrace. Just use `throw;`
Here is a simple code snippet that will help illustrate the difference. The difference being that throw ex will reset the stack trace as if the line "`throw ex;`" were the source of the exception. Code: ``` using System; namespace StackOverflowMess { class Program { static void TestMethod() {...
Throwing exceptions in ASP.NET C#
[ "", "c#", ".net", "exception", "" ]
We have a case where clients seem to be eternally caching versions of applets. We're making use of the `<param name="cache_version">` tag correctly within our `<object>` tag, or so we think. We went from a version string of `7.1.0.40` to `7.1.0.42` and this triggered a download for only about half of our clients. It d...
Unfortunately, different versions of the Java Plug-In have different caching behaviors. Setting your Cache-Control and Last-Modified HTTP headers is the ideal solution, but it only works under [the most recent versions](http://java.sun.com/javase/6/docs/technotes/guides/deployment/enhancements.html) of the JRE. The on...
You can remove applet from Java cache using `Java Control Panel`. For example, on Win XP ``` Start -> Control Panel -> Java -> Temporary Internet Files[View] ```
Java applet cached forever, not downloading new version?
[ "", "java", "caching", "applet", "" ]
At home we have a proxy server. At work we don't. Firefox irritates in this regard: whenever I launch it, it defaults to the proxy server. If I do Tools>Options>Settings and select "No proxy", no problem. However, if I shutdown Firefox and restart it, I have to do the Tools>Options>Settings thing all over again because...
Use [FoxyProxy](http://foxyproxy.mozdev.org/), much more flexible to configure
The problem was a recent windows-only regression in Firefox. It was hard to track down, basically I got lucky... Here's the meta bug: <https://bugzilla.mozilla.org/show_bug.cgi?id=448634> Here's where the fix was put in. <https://bugzilla.mozilla.org/show_bug.cgi?id=446536> I haven't had time to verify it, my win...
Proxy settings in Firefox don't "stick"
[ "", "javascript", "firefox", "proxy", "" ]
I'm using the following method to send mail from Python using SMTP. Is it the right method to use or are there gotchas I'm missing ? ``` from smtplib import SMTP import datetime debuglevel = 0 smtp = SMTP() smtp.set_debuglevel(debuglevel) smtp.connect('YOUR.MAIL.SERVER', 26) smtp.login('USERNAME@DOMAIN', 'PASSWORD')...
The script I use is quite similar; I post it here as an example of how to use the email.\* modules to generate MIME messages; so this script can be easily modified to attach pictures, etc. I rely on my ISP to add the date time header. My ISP requires me to use a secure smtp connection to send mail, I rely on the smtp...
The method I commonly use...not much different but a little bit ``` import smtplib from email.MIMEMultipart import MIMEMultipart from email.MIMEText import MIMEText msg = MIMEMultipart() msg['From'] = 'me@gmail.com' msg['To'] = 'you@gmail.com' msg['Subject'] = 'simple email in python' message = 'here is the email' ms...
Sending mail from Python using SMTP
[ "", "python", "smtp", "" ]
Consider the Oracle `emp` table. I'd like to get the employees with the top salary with `department = 20` and `job = clerk`. Also assume that there is no "empno" column, and that the primary key involves a number of columns. You can do this with: ``` select * from scott.emp where deptno = 20 and job = 'CLERK' and sal ...
The following is slightly over-engineered, but is a good SQL pattern for "top x" queries. ``` SELECT * FROM scott.emp WHERE (deptno,job,sal) IN (SELECT deptno, job, max(sal) FROM scott.emp WHERE deptno = 20 and job = 'CLERK' GROUP BY deptno, job ) ``` Also note that this ...
If I was certain of the targeted database I'd go with Mark Nold's solution, but if you ever want some dialect agnostic SQL\*, try ``` SELECT * FROM scott.emp e WHERE e.deptno = 20 AND e.job = 'CLERK' AND e.sal = ( SELECT MAX(e2.sal) FROM scott.emp e2 WHERE e.deptno = e2.deptno AND e.job = e2.job ) ``` \*I...
SQL: aggregate function and group by
[ "", "sql", "oracle", "aggregate", "" ]
I have a large GUI project that I'd like to port to Linux. What is the most recommended framework to utilize for GUI programming in Linux? Are Frameworks such as KDE / Gnome usable for this objective Or is better to use something more generic other than X? I feel like if I chose one of Gnome or KDE, I'm closing the ma...
Your best bet may be to port it to a cross-platform widget library such as [wxWidgets](http://en.wikipedia.org/wiki/WxWidgets), which would give you portability to any platform wxWidgets supports. It's also important to make the distinction between Gnome libraries and GTK, and likewise KDE libraries and Qt. If you wri...
I recommend [wxWidgets](http://www.wxwidgets.org/) or [Qt](http://www.trolltech.no/). They are both mature, well-structured and cross-platform, with decent documentation and sample source code.
Linux GUI development
[ "", "c++", "linux", "user-interface", "gnome", "kde-plasma", "" ]
I am wondering if it is possible to extract the index position in a given string where a Regex failed when trying to match it? For example, if my regex was "abc" and I tried to match that with "abd" the match would fail at index 2. Edit for clarification. The reason I need this is to allow me to simplify the parsing ...
I agree with Colin Younger, I don't think it is possible with the existing Regex class. However, I think it is doable if you are willing to sweat a little: 1. Get the Regex class source code (e.g. <http://www.codeplex.com/NetMassDownloader> to download the .Net source). 2. Change the code to have a readonly ...
I guess such an index would only have meaning in some simple case, like in your example. If you'll take a regex like "ab\*c\*z" (where by \* I mean any character) and a string "abbbcbbcdd", what should be the index, you are talking about? It will depend on the algorithm used for mathcing... Could fail on "abbbc..." or...
Regex index in matching string where the match failed
[ "", "c#", "regex", "" ]
What I'm trying to do here is get the headers of a given URL so I can determine the MIME type. I want to be able to see if `http://somedomain/foo/` will return an HTML document or a JPEG image for example. Thus, I need to figure out how to send a HEAD request so that I can read the MIME type without having to download ...
**edit**: This answer works, but nowadays you should just use the [requests](http://docs.python-requests.org/en/latest/index.html) library as mentioned by other answers below. --- Use [httplib](https://docs.python.org/2/library/httplib.html). ``` >>> import httplib >>> conn = httplib.HTTPConnection("www.google.com")...
[urllib2](https://docs.python.org/2/library/urllib2.html) can be used to perform a HEAD request. This is a little nicer than using httplib since urllib2 parses the URL for you instead of requiring you to split the URL into host name and path. ``` >>> import urllib2 >>> class HeadRequest(urllib2.Request): ... def g...
How do you send a HEAD HTTP request in Python 2?
[ "", "python", "python-2.7", "http", "http-headers", "content-type", "" ]
I have the concept of `NodeType`s and `Node`s. A `NodeType` is a bunch of meta-data which you can create `Node` instances from (a lot like the whole Class / Object relationship). I have various `NodeType` implementations and various Node implementations. In my AbstractNodeType (top level for NodeTypes) I have ab abst...
You can just replace `<T extends AbstractNode> T` with `AbstractNode` thanks to the magic of [covariant returns](http://en.wikipedia.org/wiki/Covariant_return_type). `Java 5` added support, but it didn't receive the pub it deserved.
Two ways: (a) Don't use generics. It's probably not necessary in this case. (Although that depends on the code you havn't shown.) (b) Generify AbstractNodeType as follows: ``` public abstract class AbstractNodeType<T extends AbstractNode> { public abstract T createInstance(); } public class ThingType<Thing> { pu...
Generic Method Type Safety
[ "", "java", "generics", "" ]
There have been some questions about whether or not JavaScript is an object-oriented language. Even a statement, "just because a language has objects doesn't make it OO." Is JavaScript an object-oriented language?
IMO (and it is only an opinion) **the** key characteristic of an object orientated language would be that it would support [*polymorphism*](http://en.wikipedia.org/wiki/Polymorphism_in_object-oriented_programming). Pretty much all dynamic languages do that. The next characteristic would be [*encapsulation*](http://en....
The short answer is Yes. For more information: From [Wikipedia](http://en.wikipedia.org/wiki/Javascript): > JavaScript is heavily object-based. > Objects are associative arrays, > augmented with prototypes (see below). > Object property names are associative > array keys: obj.x = 10 and obj["x"] = > 10 are equivalent...
Is JavaScript object-oriented?
[ "", "javascript", "oop", "" ]
In a custom module for drupal 4.7 I hacked together a node object and passed it to node\_save($node) to create nodes. This hack appears to no longer work in drupal 6. While I'm sure this hack could be fixed I'm curious if there is a standard solution to create nodes without a form. In this case the data is pulled in fr...
I don't know of a standard API for creating a node pragmatically. But this is what I've gleaned from building a module that does what you're trying to do. 1. Make sure the important fields are set: uid, name, type, language, title, body, filter (see `node_add()` and `node_form()`) 2. Pass the node through `node_object...
The best practices method of making this happen is to utilize drupal\_execute. drupal\_execute will run standard validation and basic node operations so that things behave the way the system expects. drupal\_execute has its quirks and is slightly less intuitive than simply a node\_save, but, in Drupal 6, you can utiliz...
How do I create a node from a cron job in drupal?
[ "", "php", "drupal", "drupal-6", "" ]
I have been asked to lend a hand on a hobby project that a couple friends are working on, they are using SharpDevelop 3.0 (Beta 2 I think, but it might be Beta 1) is there any hassle for me to install and use this IDE given that I have Visual Studio 2008 installed?
I've had no problems at all, in fact some of the tools in sharpdevelop (like the vb.net -> c# converter) are very nice to have. In addition, there are some good libraries included with sharpdevelop that are also handy (like sharpziplib for zip files) I actually have VS2005, VS2008, SharpDevelop and VisualStudio 6 ins...
They behave very well together, I have had SharpDevelop installed with 2003, 2005 and 2008. No issues at all.
Any problems running SharpDevelop 3.0 and Visual Studio 2008 side by side?
[ "", "c#", "visual-studio", "sharpdevelop", "" ]
In C++, you can specify that a function may or may not throw an exception by using an exception specifier. For example: ``` void foo() throw(); // guaranteed not to throw an exception void bar() throw(int); // may throw an exception of type int void baz() throw(...); // may throw an exception of some unspecified type ...
No. Here are several examples why: 1. Template code is impossible to write with exception specifications, ``` template<class T> void f( T k ) { T x( k ); x.x(); } ``` The copies might throw, the parameter passing might throw, and `x()` might throw some unknown exception. 2. Exce...
Avoid exception specifications in C++. The reasons you give in your question are a pretty good start for why. See Herb Sutter's ["A Pragmatic Look at Exception Specifications"](http://www.gotw.ca/publications/mill22.htm).
Should I use an exception specifier in C++?
[ "", "c++", "function", "exception", "throw", "specifier", "" ]
I have a Google App Engine app - <http://mylovelyapp.appspot.com/> It has a page - mylovelypage For the moment, the page just does `self.response.out.write('OK')` If I run the following Python at my computer: ``` import urllib2 f = urllib2.urlopen("http://mylovelyapp.appspot.com/mylovelypage") s = f.read() print s f...
appcfg.py, the tool that uploads data to App Engine has to do exactly this to authenticate itself with the App Engine server. The relevant functionality is abstracted into appengine\_rpc.py. In a nutshell, the solution is: 1. Use the [Google ClientLogin API](http://code.google.com/apis/accounts/docs/AuthForInstalledAp...
thanks to Arachnid for the answer - it worked as suggested here is a simplified copy of the code, in case it is helpful to the next person to try! ``` import os import urllib import urllib2 import cookielib users_email_address = "billy.bob@gmail.com" users_password = "billybobspassword" target_authenticated_go...
How do you access an authenticated Google App Engine service from a (non-web) python client?
[ "", "python", "web-services", "google-app-engine", "authentication", "" ]
Can you provide a good example of rule definition language written in C#. Java guys have [JESS](http://herzberg.ca.sandia.gov/), is there anything good for C#?
This page shows some examples of open-source rules engines in C#: <http://csharp-source.net/open-source/rule-engines>
You can use the forward chaining inference engine that is part of Windows Workflow Foundation (.NET 3.5 and higher) The best part is that this has a free runtime licensing. You can use the [Rule Manager](http://www.acumenbusiness.com/products.htm) from Acumen Business and install the Windows Workflow Foundation adapte...
Example of c# based rule language?
[ "", "c#", "rule-engine", "" ]
I have a distributed Java application running on 5 application servers. The servers all use the same Oracle 9i database running on a 6th machine. The application need to prefetch a batch of 100 IDs from a sequence. It's relatively easy to do in a single-threaded, non-distributed environment, you can just issue these q...
Why not just have the sequence as increment by 100 all the time? each "nextval" gives you 100 sequence numbers to work with ``` SQL> create sequence so_test start with 100 increment by 100 nocache; Sequence created. SQL> select so_test.nextval - 99 as first_seq, so_test.currval as last_seq from dual; FIRST_SEQ L...
Why do you need to fetch the sequence IDs in the first place? In most cases you would insert into a table and return the ID. ``` insert into t (my_pk, my_data) values (mysequence.nextval, :the_data) returning my_pk into :the_pk; ``` It sounds like you are trying to pre-optimize the processing. If you REALLY need to ...
How to prefetch Oracle sequence ID-s in a distributed environment
[ "", "java", "oracle", "" ]
What is the best way to disable `Alt` + `F4` in a c# win form to prevent the user from closing the form? I am using a form as a popup dialog to display a progress bar and I do not want the user to be able to close it.
This does the job: ``` private void Form1_FormClosing(object sender, FormClosingEventArgs e) { e.Cancel = true; } ``` Edit: In response to pix0rs concern - yes you are correct that you will not be able to programatically close the app. However, you can simply remove the event handler for the form\_closing event b...
If you look at the [value](https://learn.microsoft.com/en-us/dotnet/api/system.windows.forms.closereason?view=netframework-4.7.2) of `FormClosingEventArgs e.CloseReason`, it will tell you why the form is being closed. You can then decide what to do, the possible values are: **Member name** - Description --- **None**...
How to Disable Alt + F4 closing form?
[ "", "c#", ".net", "winforms", "" ]
I'm trying to do a basic "OR" on three fields using a hibernate criteria query. Example ``` class Whatever{ string name; string address; string phoneNumber; } ``` I'd like to build a criteria query where my search string could match "name" or "address" or "phoneNumber".
You want to use `Restrictions.disjuntion()`. Like so ``` session.createCriteria(Whatever.class) .add(Restrictions.disjunction() .add(Restrictions.eq("name", queryString)) .add(Restrictions.eq("address", queryString)) .add(Restrictions.eq("phoneNumber", queryString)) ); ``` See the Hibe...
Assuming you have a hibernate session to hand then something like the following should work: ``` Criteria c = session.createCriteria(Whatever.class); Disjunction or = Restrictions.disjunction(); or.add(Restrictions.eq("name",searchString)); or.add(Restrictions.eq("address",searchString)); or.add(Restrictions.eq("phone...
How do you "OR" criteria together when using a criteria query with hibernate?
[ "", "java", "hibernate", "" ]
I would like to create an XML-based website. I want to use XML files as datasources since it is a kind of online directory site. Can someone please give me a starting point? Are there any good online resources that I can refer to? I am pretty comfortable with ASP and JavaScript.
If you cannot or don't wish to store your data in XHTML format, then XSLT is definitely the way you want to go. By its very definition, it is a transformation language designed to transform data from one format to another. Because this is it's focus, it provides power, speed and flexibility you won't find in many other...
Hey, here's an idea - xhtml is xml, after all, so if you can define the format of the xml files, just create browser-friendly xhtml to begin with. Otherwise I'm sure there are XML parsing libraries for ASP and you can look into XSLT (which is cool to learn, but a bit more of a challenge).
XML based website - how to create?
[ "", "javascript", "xml", "asp-classic", "" ]
This is probably a really simple jQuery question, but I couldn't answer it after 10 minutes in the documentation so... I have a list of checkboxes, and I can get them with the selector `'input[type=checkbox]'`. I want the user to be able to shift-click and select a range of checkboxes. To accomplish this, I need to ge...
The following selector should also work in jQuery: `input:checkbox`. You can then string the `:gt(index)` and `:lt(index)` filters together, so if you want the 5th to 7th checkboxes, you'd use `input:checkbox:gt(4):lt(2)`. To get the index of the currently clicked checkbox, just use `$("input:checkbox").index($(this)...
This is a quick solution, but I would give each checkbox a unique ID, perhaps with an index hint, like so: ``` <input id="checkbox-0" type="checkbox" /> <input id="checkbox-1" type="checkbox" /> <input id="checkbox-2" type="checkbox" /> <input id="checkbox-3" type="checkbox" /> <input id="checkbox-4" type="checkbox" /...
jQuery slicing and click events
[ "", "javascript", "jquery", "" ]
I have a winforms application that normally is at about 2-4% CPU. We are seeing some spikes up to 27% of CPU for limited number of times. What is the best profiling tool to determine what is actually causing this spike. We use dottrace but i dont see how to map that to exactly the CPU spikes? Appreciate the help
I've used 2 profiling tools before - RedGate's ANTS profiler, and the built in profiler found in Visual Studio Team System. It's been some time since I used RedGate's (<http://www.red-gate.com/products/ants_profiler/index.htm>) profiler, though I used the built in in Visual Studio 2008 fairly recently. That being sai...
I’ve found DevPartner from Compuware <http://www.compuware.com/> to be an excellent profiling tool. Unfortunately it looks like at the present time they don’t support VS 2008.
Winform application profiling CPU usage / spikes .
[ "", "c#", "winforms", "performance", "optimization", "cpu", "" ]
I need to implement auto-capitalization inside of a Telerik RadEditor control on an ASPX page as a user types. This can be an IE specific solution (IE6+). I currently capture every keystroke (down/up) as the user types to support a separate feature called "macros" that are essentially short keywords that expand into ...
I'm not sure if this is what you're trying to do, but here is a function ([reference](http://individed.com/code/to-title-case/js/to-title-case.js)) to convert a given string to title case: ``` function toTitleCase(str) { return str.replace(/([\w&`'‘’"“.@:\/\{\(\[<>_]+-? *)/g, function(match, p1, index, title...
Have you tried to apply the [text-transform](http://www.w3.org/TR/CSS2/text.html#caps-prop) CSS style to your controls?
How would you implement auto-capitalization in JavaScript/HTML
[ "", "javascript", "formatting", "text-editor", "" ]
When we compile a dll using \_\_stdcall inside visual studio 2008 the compiled function names inside the dll are. FunctionName Though when we compile the same dll using GCC using wx-dev-cpp GCC appends the number of paramers the function has, so the name of the function using Dependency walker looks like. FunctionNa...
\_\_stdcall decorates the function name by adding an underscore to the start, and the number of bytes of parameters to the end (separated by @). So, a function: ``` void __stdcall Foo(int a, int b); ``` ...would become \_Foo@8. If you list the function name (undecorated) in the EXPORTS section of your .DEF file, it...
Just use `-Wl,--kill-at` on the gcc command line, which will pass `--kill-at` to the linker. References: * <http://sourceware.org/binutils/docs/ld/Options.html#Options> * <http://www.geocities.com/yongweiwu/stdcall.htm>
GCC compiling a dll with __stdcall
[ "", "c++", "gcc", "name-decoration", "" ]
My professor did an informal benchmark on a little program and the Java times were: 1.7 seconds for the first run, and 0.8 seconds for the runs thereafter. * Is this due entirely to the loading of the runtime environment into the operating environment ? OR * Is it influenced by Java's optimizing the code and storin...
I agree that the performance difference seen by the poster is most likely caused by disk latency bringing the JRE into memory. The Just In Time compiler (JIT) would not have an impact on performance of a little application. Java 1.6u10 (<http://download.java.net/jdk6/>) touches the runtime JARs in a background process...
Okay, I found where I read that. This is all from "Learning Java" (O'Reilly 2005): > The problem with a traditional JIT compilation is that optimizing code takes time. So a JIT compiler can produce decent results but may suffer a significant latency when the application starts up. This is generally not a problem for l...
Does Java save its runtime optimizations?
[ "", "java", "optimization", "caching", "" ]
I want a splash screen to show while the application is loading. I have a form with a system tray control tied to it. I want the splash screen to display while this form loads, which takes a bit of time since it's accessing a web service API to populate some drop-downs. I also want to do some basic testing for dependen...
Well, for a ClickOnce app that I deployed in the past, we used the `Microsoft.VisualBasic` namespace to handle the splash screen threading. You can reference and use the `Microsoft.VisualBasic` assembly from C# in .NET 2.0 and it provides a lot of nice services. 1. Have the main form inherit from `Microsoft.VisualBasi...
The trick is to to create separate thread responsible for splash screen showing. When you run you app .net creates main thread and loads specified (main) form. To conceal hard work you can hide main form until loading is done. Assuming that Form1 - is your main form and SplashForm is top level, borderles nice splash...
Multi-threaded splash screen in C#?
[ "", "c#", ".net", "winforms", "multithreading", "splash-screen", "" ]
Is there a way to mock object construction using JMock in Java? For example, if I have a method as such: ``` public Object createObject(String objectType) { if(objectType.equals("Integer") { return new Integer(); } else if (objectType.equals("String") { return new String(); } } ``` ...is ...
The only thing I can think of is to have the create method on at factory object, which you would than mock. But in terms of mocking a constructor call, no. Mock objects presuppose the existence of the object, whereas a constructor presuppose that the object doesn't exist. At least in java where allocation and initiali...
jmockit can do this. See my answer in <https://stackoverflow.com/questions/22697#93675>
How to mock object construction?
[ "", "java", "tdd", "junit", "mocking", "" ]
This is probably a silly question, but curiosity has gotten the better of me. I've been seeing code lately that seems to "reverse" the order of expressions for relational operators e.g.: ``` if (0 == someVariable) ``` As opposed to what I normally see/write: ``` if (someVariable == 0) ``` To me, the second method s...
I understand that this is personal preference. Although by putting the variable second you can ensure that you don't accidentally assign the constant to the variable which used to concearn c developers. This is probably why you are seeing it in c# as developers switch language.
Order does not matter, however, the former implies that it s the zero you're checking. Convention dictates the use of hte latter.
relational operator expression order
[ "", "c#", "operators", "logical-operators", "" ]
How do you unit test a large MFC UI application? We have a few large MFC applications that have been in development for many years, we use some standard automated QA tools to run basic scripts to check fundamentals, file open etc. These are run by the QA group post the daily build. But we would like to introduce proc...
It depends on how the App is structured. If logic and GUI code is separated (MVC) then testing the logic is easy. Take a look at Michael Feathers ["Humble Dialog Box"](https://web.archive.org/web/20080509080327/http://www.objectmentor.com/resources/articles/TheHumbleDialogBox.pdf "Humble Dialog Box") (PDF). EDIT: If y...
Since you mentioned MFC, I assumed you have an application that would be hard to get under an automated test harness. You'll observe best benefits of unit testing frameworks when you build tests as you write the code.. But trying to add a new feature in a test-driven manner to an application which is not designed to be...
Unit testing MFC UI applications?
[ "", "c++", "unit-testing", "user-interface", "mfc", "tdd", "" ]