Prompt
stringlengths
10
31k
Chosen
stringlengths
3
29.4k
Rejected
stringlengths
3
51.1k
Title
stringlengths
9
150
Tags
listlengths
3
7
I'm writing a Firefox extension that needs to know what the username of the currently logged in user is in Windows, Mac, or Linux. So if I'm logged into my machine as "brh", it'll return "brh". Any idea how to do that from extension JavaScript?
Firefox extensions play by different rules to normal JavaScript running in the page: finding the current user is absolutely possible. Open your Error Console (in Tools) and enter this: ``` Components.classes["@mozilla.org/process/environment;1"].getService(Components.interfaces.nsIEnvironment).get('USER') ``` The en...
The flagged correct answer works fine. I use this in our extension on Firefox 38. I also use events so that the page can communicate with the extension and retrieve windows properties from the extension. getWindowsProperty: function(prop){ return Components.classes["@mozilla.org/process/environment;1"].getService(Comp...
Finding the currently logged in user from a Firefox extension
[ "", "javascript", "firefox", "xul", "" ]
I'm using Django to write a blog app, and I'm trying to implement a hierarchical category structure. Each category has a "parent" ForeignKey pointing back to the same Category model. I want to allow admins to add categories, and I want the interface to allow them to select a category's parent category. However, I want ...
If I understand your predicament correctly, the problem itself lies with the way you're dealing with which categories can be parents and which ones can't. One option to avoid these problems is to actually limit the level of categories which can become parents. For example, let's say you have the following categories: ...
Take a look at the [django-treebeard](http://code.google.com/p/django-treebeard/) app.
ForeignKey form restrictions in Django
[ "", "python", "django", "django-forms", "" ]
If I'm using a `Hashtable`, I can write code like this: ``` object item = hashtable[key] ?? default_value; ``` That works whether or not `key` appears in the `Hashtable`. I can't do that with a `Dictionary<TKey. TValue>`. If the key's not present in the dictionary, that will throw a `KeyNotFoundException`. So I have...
The difference between a `Dictionary<T>` and a `Hashtable` is that a `Dictionary<T>` is a generic type that can specialize to store value types along reference types. The hashtable can only store reference types (a `Object` passed by reference) and only value types that are boxed (also passed by reference). When a di...
There is one misconception in your post. Dictionary is not a wrapper around Hashtable. It's a completely different implementation. The reason why this change was made is mainly justified by one assertion: Null is a valid value for a hashtable. Without this change it's not possible to distinguish between a non-exsisten...
Why doesn't a Dictionary access nonexistent keys like a Hashtable does?
[ "", "c#", ".net", "dictionary", "hashtable", "" ]
``` $pee = preg_replace( '|<p>|', "$1<p>", $pee ); ``` This regular expression is from the Wordpress source code (formatting.php, wpautop function); I'm not sure what it does, can anyone help? Actually I'm trying to port this function to Python...if anyone knows of an existing port already, that would be much better ...
wordpress really calls a variable "pee" ? I'm not sure what the $1 stands for (there are no braces in the first parameter?), so I don't think it actually does anything, but i could be wrong.
The preg\_replace() function - somewhat confusingly - allows you to use other delimiters besides the standard "/" for regular expressions, so ``` "|<p>|" ``` Would be a regular expression just matching ``` "<p>" ``` in the text. However, I'm not clear on what the replacement parameter of ``` "$1<p>" ``` would be ...
What does this Regular Expression do
[ "", "php", "regex", "wordpress", "" ]
I've been working with jQuery for a pair of weeks and I've noticed it works fine with objects that are in the original HTML document, but when I generate a new element using jQuery the library doesn't get any of its events. Let's say I try to run something like this: ``` $('.whatever').click(function() { alert("ALE...
Thats because the : (corrected) ``` $('.whatever').click(function() { alert("ALERT!"); }); ``` Means, in literal terms: ``` Find all elements currently on the page that have the class ".whatever" Foreach element in that result set, bind this function to its click event ``` so naturally, adding a new DOM element w...
If you have jQuery 1.3 or later, try using [live](http://docs.jquery.com/Events/live) for adding events to dynamically generated elements: ``` $('.whatever').live("click", function() { alert("ALERT!"); }); ```
jQuery with elements generated dynamically
[ "", "javascript", "jquery", "" ]
I've got a C++ program that's likely to generate a HUGE amount of data -- billions of binary records of varying sizes, most probably less than 256 bytes but a few stretching to several K. Most of the records will seldom be looked at by the program after they're created, but some will be accessed and modified regularly....
I doubt you will find a library that meets your requirements exactly, so you'll have to decide on what 'features' are really important to you and then decide if an existing DB solution comes close enough. Billions of records is a large dataset by any stretch. What rate are records generated at? How long do they persis...
Take a look at [STXXL](http://stxxl.sourceforge.net/). `stxxl::map<>` looks like it does exactly what you need.
Store huge std::map, mostly on disk
[ "", "c++", "data-structures", "" ]
My product opens a web browser and points it at an HTML file containing a local Flash application. How do I detect programmatically whether this file loaded successfully and if not what exception was thrown? Is there a way to do this using Javascript? Checking externally whether the file exists on disk is not enough b...
Answering my own question: <https://sourceforge.net/forum/message.php?msg_id=5929756> 1. Define a Javascript function that should be invoked if Flash loaded. 2. Invoke this method from the top of your Flash file. 3. Use a timer to detect if the callback is never invoked. 4. Prefer invoking Javascript functions from Fl...
In cases where you cannot modify the swf and adding an ExternalInterface is not an option, you can still use Javascript to get the status of the swf. For example, you can call document.getElementById(swf\_id).PercentLoaded() from Javascript, and wait for it to be 100. That won't tell you what exception was thrown if t...
Detect if Flash application loaded correctly using Javascript?
[ "", "javascript", "flash", "" ]
I was trying to check out a project from SVN using Eclipse. I tried using "Checkout As" to make it into a "Java project from existing Ant script", but the project wizard requires the file to have already been downloaded. Is there a way to checkout the project into Eclipse as a Java project, without having to download i...
If it wasn't checked in as a Java Project, you can add the java nature as shown [here](http://enarion.net/programming/tools/eclipse/changing-general-project-to-java-project/).
Here are the steps: * Install the subclipse plugin (provides svn connectivity in eclipse) and connect to the repository. Instructions here: <http://subclipse.tigris.org/install.html> * Go to File->New->Other->Under the SVN category, select Checkout Projects from SVN. * Select your project's root folder and select ch...
How do I check out an SVN project into Eclipse as a Java project?
[ "", "java", "eclipse", "svn", "ant", "subversive", "" ]
Has anyone seen anything in Tix work under python 3.0? I've tried to work through the examples but when creating anything it states that cnf is unsubscriptable. I also noticed that none of the Dir Select stuff (DirList DirTree) works under 2.6.1. Why doesn't Python either dump Tix or support it? Its got a lot of good...
Likely what happened is that no one noticed the bug. (It's very hard to automatically test GUI libraries like Tix and Tkinter.) You should report bugs as you find them to <http://bugs.python.org>.
Generally speaking, if you're using third-party modules, you're better off avoiding Python 3.0 for now. If you're working on a third-party module yourself, porting forward to Python 3.0 is a good idea, but for the time being general development in it is just going to be a recipe for pain.
Tix and Python 3.0
[ "", "python", "python-3.x", "tix", "" ]
I'm doing a bookmarking system and looking for the fastest (easiest) way to retrieve a page's title with PHP. It would be nice to have something like `$title = page_title($url)`
``` <?php function page_title($url) { $fp = file_get_contents($url); if (!$fp) return null; $res = preg_match("/<title>(.*)<\/title>/siU", $fp, $title_matches); if (!$res) return null; // Clean up title: remove EOL's and excessive whitespace. ...
You can get it without reg expressions: ``` $title = ''; $dom = new DOMDocument(); if($dom->loadHTMLFile($urlpage)) { $list = $dom->getElementsByTagName("title"); if ($list->length > 0) { $title = $list->item(0)->textContent; } } ```
Fastest way to retrieve a <title> in PHP
[ "", "php", "html", "parsing", "" ]
Why does the parameterless Guid constructor generate an empty GUID rather than default to a generated one as with Guid.NewGuid()? Is there a particular use for an empty Guid?
> Why does the parameterless Guid constructor generate an empty GUID rather than default to a generated one as with Guid.NewGuid()? Short answer: Because the language/runtime didn't let the designer of the Guid type define a default constructor. It's not only conventional that the value of a "default-constructed" str...
This behavior is consistent with the rest of the value types in the .Net framework. When "newing up" a value type, a default value is used. This just happens to be the default for Guid similar to Int32's default value of 0.
Why does the parameterless Guid constructor generate an empty GUID?
[ "", "c#", ".net", "guid", "default-constructor", "" ]
I'm working on a Python library that interfaces with a web service API. Like many web services I've encountered, this one requests limiting the rate of requests. I would like to provide an optional parameter, `limit`, to the class instantiation that, if provided, will hold outgoing requests until the number of seconds ...
This works out better with a queue and a dispatcher. You split your processing into two sides: **source** and **dispatch**. These can be separate threads (or separate processes if that's easier). The **Source** side creates and enqueues requests at whatever rate makes them happy. The **Dispatch** side does this. 1....
Don't reinvent the wheel, unless it's called for. Check the awesome library [ratelimit](https://pypi.org/project/ratelimit/). Perfect if you just want to rate limit your calls to an rest api for whatever reason and get on with your life. ``` from datetime import timedelta from ratelimit import limits, sleep_and_retry ...
How to limit rate of requests to web services in Python?
[ "", "python", "web-services", "rate-limiting", "" ]
I'm working on a small GreaseMonkey script where I would like to embed a jQuery plugin (Markitup) so that the script is fully self contained (images + js) except for jQuery which is served from google. I found the site <http://www.greywyvern.com/code/php/binary2base64> which says that you can embed javascript with the...
maybe just a thought but maybe the "href" should be "src" instead.
If you'd check script tag syntax you'd get ``` <script src="..." ^^^ src NOT href ``` Using data URIs here doesn't work in IE 6 btw.
Embed javascript as base64
[ "", "javascript", "embed", "base64", "" ]
I'm considering using Annotations to define my Hibernate mappings but have run into a problem: I want to use a base entity class to define common fields (including the ID field) but I want different tables to have different ID generation strategies: ``` @MappedSuperclass public abstract class Base implements Serializa...
In the code above, it looks like you're mixing annotations on fields (superclass) and methods (subclass). The Hibernate [reference documentation](http://www.hibernate.org/hib_docs/annotations/reference/en/html_single/#entity-mapping-entity) recommends avoiding this, and I suspect it might be causing the problem. In my ...
On the method in the child dont add the second @Id tag. ``` @Override // So that we can set Generated strategy @GeneratedValue(strategy = AUTO) public Integer getId() { return super.getId(); } ```
How do I override the GenerationType strategy using Hibernate/JPA annotations?
[ "", "java", "hibernate", "jpa", "annotations", "" ]
Why are static indexers disallowed in C#? I see no reason why they should not be allowed and furthermore they could be very useful. For example: ``` public static class ConfigurationManager { public object this[string name] { get => ConfigurationManager.getProperty(name); set ...
Indexer notation requires a reference to `this`. Since static methods don't have a reference to any particular instance of the class, you can't use `this` with them, and consequently you can't use indexer notation on static methods. The solution to your problem is using a singleton pattern as follows: ``` public clas...
I believe it was considered not to be terribly useful. I think it's a shame too - an example I tend to use is Encoding, where `Encoding.GetEncoding("foo")` could be `Encoding["Foo"]`. I don't think it would come up *very* often, but aside from anything else it just feels a little inconsistent not to be available. I wo...
Static Indexers?
[ "", "c#", ".net", "static", "indexer", "static-indexers", "" ]
What's the best way to handle data entered through dynamically generated controls in ASP.NET? Currently, I have a group of controls that are generated in the Page\_Load stage, and I need to access the data from them. It seems like it might be possible to just use a hidden field that's read and parsed on postback, but ...
The key is recreating the controls on postback. [Old but good article](https://web.archive.org/web/20211031102347/https://aspnet.4guysfromrolla.com/articles/092904-1.aspx) to explain how and why. You can also use the request.form collection to grab the posted values.
[redsquare](https://stackoverflow.com/users/6440/redsquare) is right. If you can just remember that ASP.Net is a lie wrapped around Http then you will be ok. The browser doesn't really care that MS neatly abstracts the Http Request/Response away from you in the form of Web Controls. It only knows that it needs to wrap ...
Handling dynamically generated controls in asp.net
[ "", "c#", "asp.net", "" ]
When trying to compile my class I get an error: > The constant `'NamespaceName.ClassName.CONST_NAME'` cannot be marked static. at the line: ``` public static const string CONST_NAME = "blah"; ``` I could do this all of the time in Java. What am I doing wrong? And why doesn't it let me do this?
A `const` object is always `static`.
From the [C# language specification](http://www.ecma-international.org/publications/standards/Ecma-334.htm) *(PDF page 287 - or 300th page of the PDF):* > Even though constants are considered > static members, a constant > declaration neither requires nor > allows a static modifier.
Why can't I have "public static const string S = "stuff"; in my Class?
[ "", "c#", "constants", "" ]
I am trying to generate some code at runtime using the DynamicMethod class in the Reflection.Emit namespace but for some reason its throwing a "VerificationException". Here is the IL code I am trying to use... ``` ldarg.1 ldarg.0 ldfld, System.String FirstName callvirt, Void Write(System.String) ldarg.1 ldarg.0 ldfld,...
I have found some more help here... [DebuggerVisualizer for DynamicMethod (Show me the IL)](http://blogs.msdn.com/haibo_luo/archive/2005/10/25/484861.aspx) It's is a debugger visualizer using which you will be able to see the generated IL at runtime! And even better is [Debugging LCG](http://blogs.msdn.com/yirutang/...
Try using the [peverify](http://msdn.microsoft.com/en-us/library/62bwd2yd(VS.80).aspx) tool to check the IL. From MSDN: > peverify.exe performs comprehensive > MSIL verification checks based on > dataflow analysis plus a list of > several hundred rules on valid > metadata. For detailed information on > the checks Peve...
How do I debug IL code generated at runtime using Reflection.Emit
[ "", "c#", ".net", "vb.net", "" ]
Is it possible to create a stored procedure as ``` CREATE PROCEDURE Dummy @ID INT NOT NULL AS BEGIN END ``` Why is it not possible to do something like this?
Parameter validation is not currently a feature of procedural logic in SQL Server, and NOT NULL is only one possible type of data validation. The CHAR datatype in a table has a length specification. Should that be implemented as well? And how do you handle exceptions? There is an extensive, highly developed and somewha...
You could check for its NULL-ness in the sproc and `RAISERROR` to report the state back to the calling location. ``` CREATE proc dbo.CheckForNull @i int as begin if @i is null raiserror('The value for @i should not be null', 15, 1) -- with log end GO ``` Then call: ``` exec dbo.CheckForNull @i = 1 ``` o...
How to restrict NULL as parameter to stored procedure SQL Server?
[ "", "sql", "sql-server", "stored-procedures", "" ]
On my page I have a drop-down select box, with a default value of (empty). When the user selects an entry, the appropriate form for that entry type is displayed. Couple of problems.. 1. The code is not DRY and seems more verbose than it needs to be, so not easily maintainable / extensible. 2. When a user selects some...
Instead of the multiple IF clauses, you can iterate over an array of values. But in this case, if there are no other requirements then simply: ``` $(document).ready(function(){ var select = $('#select_type'); $('#' + select.val()).toggle(); // Toggle the preset value select.change(function () { ...
``` $(document).ready(function() { $("#select_type").change(function () { $("fieldset").css("display", "none"); $("#" + $(this).val()).toggle(); }).change(); }); ```
How to make this jQuery function more elegant?
[ "", "javascript", "jquery", "html", "forms", "html-select", "" ]
I have a form that is dynamically generated, and has dynamically generated id's (and potentially classes). The forms are the same but they have the related id tacked on to the end. How can I select each set of inputs and apply code to each one? I was experimenting with $('input[id^=@id\_airline\_for\_]') but could no...
``` $("input[id^='id_airline_for_']").each(function() { var id = parseInt(this.id.replace("id_airline_for_", ""), 10); var airline = $("#id_airline_for_" + id); var flightNumber = $("#id_flight_number_for_" + id); // do stuff with airline and flightNumber <input>s }); ```
You can use `$("input#id_airline_for" + id)` (where `id` is your number, e.g., 8), but it will be faster if you drop the tag name and just use: ``` $("#id_airline_for" + id); ```
jQuery selection with dynamic id's
[ "", "javascript", "jquery", "" ]
I have a hibernate mapping as follows: ``` <hibernate-mapping> <class name="kochman.elie.data.types.InvoiceTVO" table="INVOICE"> <id name="id" column="ID"> <generator class="increment"/> </id> <property name="date" column="INVOICE_DATE"/> <property name="customerId" colu...
I would use an integer type (int, long). Never any funny issues with those as long you can avoid overflows.
Using float or double for money is absolutely inacceptable and may even be illegal (as in, breaking laws or at least regulations). That needs to be fixed, then the error will disappear. float has limited precision and cannot accurately represent most decimal fractions at all. [For money, always, ALWAYS use BigDecimal....
Hibernate and currency precision
[ "", "java", "hibernate", "types", "" ]
Ok, I have one JavaScript that creates rows in a table like this: ``` function AddRow(text,rowID) { var tbl = document.getElementById('tblNotePanel'); var row = tbl.insertRow(tbl.rows.length); var cell = row.insertCell(); var textNode = document.createTextNode(text); cell.id = rowID; cell.st...
Try this: ``` cell.onclick = function() { clickTest(rowID); }; ``` The idea is that you are binding the onclick handler to the anonymous function. The anonymous function calls clickTest with rowID as the parameter.
In the clickTest function you should have access to a the `this` variable. Try this inside of `clickTest` function: ``` alert(this.id); ``` This will refer to the DOM element that fired the event. Basically, there isn't really a way to pass parameters to an event handler function. The reason for that is that the bro...
How to pass a parameter to a dynamically set JavaScript function?
[ "", "javascript", "" ]
In Django, I've got loggers all over the place, currently with hard-coded names. For module-level logging (i.e., in a module of view functions) I have the urge to do this. ``` log = logging.getLogger(__name__) ``` For class-level logging (i.e., in a class `__init__` method) I have the urge to do this. ``` self.log ...
I typically don't use or find a need for class-level loggers, but I keep my modules at a few classes at most. A simple: ``` import logging LOG = logging.getLogger(__name__) ``` At the top of the module and subsequent: ``` LOG.info('Spam and eggs are tasty!') ``` from anywhere in the file typically gets me to where ...
For class level logging, as an alternative to a pseudo-class decorator, you could use a metaclass to make the logger for you at class creation time... ``` import logging class Foo(object): class __metaclass__(type): def __init__(cls, name, bases, attrs): type.__init__(name, bases, attrs) ...
Naming Python loggers
[ "", "python", "django", "logging", "python-logging", "" ]
Below is the command I tried executing, without success: ``` exec('ln -s ' . PLUGIN_DIR . '/.htaccess ' . ABSPATH . '/.htaccess'); ``` When you add a die() at the end, it catches that there's an error: ``` exec('ln -s ' . PLUGIN_DIR . '/.htaccess ' . ABSPATH . '/.htaccess') or die('what?!'); ``` For the above exec(...
You can receive the output result of the [exec function](http://www.php.net/function.exec) by passing an optional second parameter: ``` exec('ln -s ' . PLUGIN_DIR . '/.htaccess ' . ABSPATH . '/.htaccess',$output); var_dump($output); ```
The following code will capture both the normal output (from StdOut) and the error output (from SdtErr). ``` exec('ln -s ' . PLUGIN_DIR . '/.htaccess ' . ABSPATH . '/.htaccess 2>&1',$output); var_dump($output); ```
How to retrieve PHP exec() error responses?
[ "", "php", "shell", "exec", "" ]
Is there a way to use verbatim String literals in managed C++? Similar to C#'s ``` String Docs = @"c:\documents and settings\" ```
in C++11, there is raw string literal: ``` cout<<R"((\"ddd\aa)\n)"<<endl; cout<<R"delimiter((\"ddd\aa)\n)delimiter"<<endl; ``` output is: ``` (\"ddd\aa)\n (\"ddd\aa)\n ```
This is not currently possible. Managed C++ string literals have almost the exact same rules as normal C++ strings. The managed C++ spec is in fact just an augmentation of the ANSI C++ standard. Currently there is no support for C# style literal syntax in C++ (managed or not). You must manually escape every character....
Verbatim Literals in Managed C++? (like C#'s @"blah")
[ "", ".net", "c++", ".net-2.0", "string", "managed-c++", "" ]
I have a national customer who are currently recruiting dealers by selling each dealer an area for a set fee. They want a 'find a dealer' feature on their website which should point customers to the dealer who has purchased the area the visitor enters. At first we were going to list major cities with the hope that the ...
1. Create your polygons in Google Maps using KML or whatever format you have them in. 2. Use Google Maps to geocode the location that the user enters (in other words, transform postal code and city to lat/long). 3. Use the contains or containsLatLng methods of the GLatLngBounds object in each polygon to determine wheth...
It sounds like you will need polygon regions that represent the dealer's specific area. You can make polygons with the Google Maps API and then you should be able to let user click or mouse over those...
Finding a dealer area via google maps API
[ "", "php", "api", "google-maps", "geocoding", "" ]
I've got some code that looks like this: ``` using (DBDataContext dc = new DBDataContext(ConnectionString)) { Main main = new Main { ClientTime = clientTime }; dc.Mains.InsertOnSubmit(main); dc.SubmitChanges(); return main.ID; } ``` If I return from inside a "using", will the using sti...
Yes, and that's one of the big advantages of `using` it.
Yes. It really is just the equivalent of a `try/finally` statement - and `finally` blocks get executed however the `try` block exits, whether through an exception, a return statement, or just getting to the end of the block.
Returning from inside the scope of a 'using' statement?
[ "", "c#", ".net", "" ]
I am adding items to a `ListBox` like so: ``` myListBox.Items.addRange(myObjectArray); ``` and I also want to select some of the items I add by the following: ``` foreach(MyObject m in otherListOfMyObjects) { int index = myListBox.Items.IndexOf(m); myListBox.SelectedIndices.Add(index); } ``` however `index...
You should make sure that `MyObject` overrides `Equals()`, `GetHashCode()` and `ToString()` so that the `IndexOf()` method can find the object properly. Technically, `ToString()` doesn't need to be overridden for equality testing, but it is useful for debugging.
You can use some kind of a key for values in the listbox, like GUIDs. Then you can easily use `myListBox.Items.FindByValue(value)` to find the right item.
How Can I Get the Index of An Item in a ListBox?
[ "", "c#", "listbox", "" ]
Is there any way to access the `<compilation />` tag in a web.config file? I want to check if the "*debug*" attribute is set to "*true*" in the file, but I can't seem to figure out how to do it. I've tried using the `WebConfigurationManager`, but that doesn't seem to allow me to get to the `<compilation />` section. ...
Use: ``` using System.Configuration; using System.Web.Configuration; ``` ... ``` CompilationSection configSection = (CompilationSection) ConfigurationManager.GetSection( "system.web/compilation" ); ``` You can then check the `configSection.Debug` property. **TIP:** if you need to know how to get a valu...
The easy way to check if you're running in debug mode is to use the [HttpContext.IsDebuggingEnabled](http://msdn.microsoft.com/en-us/library/system.web.httpcontext.isdebuggingenabled.aspx) property. It gets its answer from the compilation element's debug attribute which is the same thing you're trying to do.
Programmatically access the <compilation /> section of a web.config?
[ "", "c#", ".net", "asp.net", "configuration", "" ]
I am using the pimpl idiom and want to reference one of the methods of the forward declared class. Below isn't exactly what I'm doing but uses the same concepts. ``` template< typename Class, void (Class::*Method)(void) > struct Call { Call( Class* c ) : m_c(c) { } void operator()( void ) { (m_c...
You cannot forward declare a member function. I think the reason is that, when you call the function on a pointer to B, the compiler has to pass the this pointer to that method. But it doesn't know the precise class hierarchy of B yet. So possible adjustments of that pointer (due to the method being virtual, for exampl...
It can't compile B::bar() because class B is undefined. But I think you are leaving too much out of the question. At this point: ``` void do_bar( B* b ) { Call<B,&B::bar> c(b); c(); } ``` why can't you just say? ``` void do_Bar(B* b) { b->bar(); } ``` Perhaps if you included that explanation it would be e...
Forward declare method pointer
[ "", "c++", "templates", "" ]
I have the following use case , lot of code which was tightly coupled on a concrete type (say Concrete1). Later figured out the concrete type needs to be changed, so defined an interface . E.g ``` Class ABC { virtual int foo() = 0; virtual int getType() = 0; } class Concrete1 : public ABC { int foo() { ....
the entire point of using interfaces is so that you can use polymorphism which means you should never have to check what type an instance is. doing so is a very big code smell (see Fowlers Refacotring). move the conditional logic to the concrete classes and add te function that will handle it to the interface EDIT (Ad...
Put the `...` inside the implementation of yet another virtual method: ``` if (abc.getType() == 1) { ... // A } else if (abc.getType() == 2) { ... // B } ``` Put A and B like this: ``` class ABC { virtual int foo() = 0; virtual void doIt() = 0; // choose a proper name }; class Concrete1 : public ABC { ...
Concrete type or Interface?
[ "", "c++", "" ]
When a user clicks on an image on a web page, I'd like to trigger the browser's Save Image dialog and to let the user save the image on their hard drive. Is there a cross-browser way to do this with jQuery/Javascript?
Not precisely, but you can do it by hyperlinking to the img file and setting the content-type and content-disposition headers in the server response. Try, e.g., application/x-download, [plus the other headers specified here](http://www.onjava.com/pub/a/onjava/excerpt/jebp_3/index3.html).
The only thing that comes to my mind is the document.execCommand("SaveAs") of Internet Explorer, you can open a window or use a hidden iframe with the url of your image, and then call it... Check (with IE of course) [this example](http://dl.getdropbox.com/u/35146/ieSaveAs.html) I've done.
Open the Save Image dialog using jQuery/Javascript?
[ "", "javascript", "jquery", "" ]
I want to convince the architecture manager to include the [Joda-Time](http://www.joda.org/joda-time/) jar in our product. Do you know any disadvantages in using it? I think Joda-Time needs to be constantly updated because of the files that it includes. And that is a disadvantage. Maybe I am wrong. Could you provide...
I've had almost entirely positive experiences with Joda Time. My one problem was when trying to construct my own time zone (for legitimate reasons, I assure you :) I got some very weird exceptions, and the documentation wasn't very good for that particular use case. However, for the most part it's been a joy to use - ...
In my opinion, the most important drawback in Joda-Time is about precision: many databases store timestamps with [microsecond](https://en.wikipedia.org/wiki/Microsecond) (or even [nanosecond](https://en.wikipedia.org/wiki/Nanosecond)) precision. Joda-time goes only to [milliseconds](https://en.wikipedia.org/wiki/Millis...
Are there any cons to using Joda-Time?
[ "", "java", "jodatime", "" ]
How can I grab something like ^MM (CTRL + M + M) in .NET, using C#?
Here's a way to do it: ``` bool mSeenCtrlM; protected override bool ProcessCmdKey(ref Message msg, Keys keyData) { if (keyData == (Keys.Control | Keys.M)) { mSeenCtrlM = !mSeenCtrlM; if (!mSeenCtrlM) { MessageBox.Show("yada"); } return true; } mSeenCtrlM = false; return base.ProcessCmdKe...
This is just a guess, you could store the key and key modifiers on each key stroke and then next time through check the last keys pressed for a matching sequence. You could probably implement this in either the ProcessCmdKey or OnKeyPress.
How can I grab a double key stroke in .NET
[ "", "c#", ".net", "key", "" ]
I'm building a C++ application and need to use PDCurses on Windows. I'm compiling with VC++ from MS VS 2005 and I'm getting a link error. > ``` > error LNK2019: unresolved external > symbol __imp__GetKeyState@4 referenced > in function __get_key_count > ``` There are 11 errors all with the same error code and diff...
GetKeyState() is a Windows function in "user32.dll", so you need to be sure you're linking against "user32.lib". You may also need to make sure it comes after the PDCurses library in the list of linker libraries, too.
Did you build PDCurses on your machine - with MS VC++? If so, I'm not sure what's up. If not, then there's a decent chance that what you are using is not compatible with MS VC++. Mixing code from different C++ compilers is fraught. It also depends a bit on what you mean by 'several other errors'. If that's a grotesque ...
How do I link PDCurses to a C++ application on Windows?
[ "", "c++", "windows", "linker", "ncurses", "pdcurses", "" ]
What is a synthetic class in Java? Why should it be used? How can I use it?
For example, When you have a switch statement, java creates a variable that starts with a $. If you want to see an example of this, peek into the java reflection of a class that has a switch statement in it. You will see these variables when you have at least one switch statement anywhere in the class. To answer your ...
Java has the ability to create classes at runtime. These classes are known as Synthetic Classes or Dynamic Proxies. See <http://java.sun.com/j2se/1.5.0/docs/guide/reflection/proxy.html> for more information. Other open-source libraries, such as [CGLIB](http://cglib.sourceforge.net/) and [ASM](http://asm.objectweb.org...
Synthetic Class in Java
[ "", "java", "class", "synthetic", "" ]
I have a Visual Studio 2005 C++ program that runs differently in Release mode than it does in Debug mode. In release mode, there's an (apparent) intermittent crash occurring. In debug mode, it doesn't crash. What are some reasons that a Release build would work differently than a Debug build? It's also worth mentionin...
[**Surviving the Release Version**](https://www.codeproject.com/Articles/548/Surviving-the-Release-Version) gives a good overview. Things I have encountered - most are already mentioned **Variable initialization** by far the most common. In Visual Studio, debug builds explicitly initialize allocated memory to given v...
In debug version often assertions and/or debug symbols are enabled. This can lead to different memory layout. In case of a bad pointer, overflow of an array or similar memory access you access in one case critical bad memory (e.g. function pointer) and in other case maybe just some non-critical memory (e.g. just a doc ...
What are some reasons a Release build would run differently than a Debug build
[ "", "c++", "visual-studio", "visual-studio-2005", "" ]
I'm trying to find out if it's possible to develop a key capturing application to analyse writing styles when using the SMS composer for the n73 using S60 2nd Edition, Feature Pack 3 SDK in Java? Originally, I thought that all Java applications would be sand-boxed making it difficult to call the native key capture func...
Note: This answer comes from my friend who knows a lot more about these things. --- As this [J2ME FAQ](http://www.j2meforums.com/wiki/index.php/FAQ#Can_I_access_the_phone.27s_j2me.3F_.28memory.2C_phone_book.2C_inbox.2C_pictures....29_.3F) states, > **Can I access the phone's j2me?** > **(memory, phone book, inbox,**...
I'll be talking as a user: Opera Mini (a java-based application) is able to read and write user data (phone memory and memory card). And I've also seen java-based applications that access hardware such as the phone's camera, and seen apps that call system APIs such as vibration or sound notifications. However, I don'...
Developing apps for the nokia n73 in Java?
[ "", "java", "symbian", "nokia", "n73", "" ]
I have a common code of serializing a class object in my 3-4 methods ,So I am thinking to create a common function for that code and call function in all the methods I am doingn this from the following code ``` DataContractJsonSerializer ser = new DataContractJsonSerializer(this.GetType()); MemoryStream ms = new Memo...
You are confusing a "class" with an "object". You serialize an object, which is an instance of a particular class (aka "Type"). You can create a method taking a parameter of the .NET base type for all objects, "object", like this: ``` public static string GenerateJsonString(object o) { DataContractJsonSerializer...
Type the parameter as "object". You can't pass a class as a parameter, only an instance of a class - which in OOP is referred to as an "object" ``` public string GenerateJsonString(object obj) ```
How to build DataContractJsonSerialize convenience function
[ "", "c#", "json", "" ]
I seem to have a problem with this SQL query: ``` SELECT * FROM appts WHERE timeStart >='$timeStart' AND timeEnd <='$timeEnd' AND dayappt='$boatdate' ``` The time is formatted as military time. The logistics is that a boat rental can be reserved at 7am til 1pm or 9am til 1pm or 9am til 5pm. If there is an appt wit...
The correct check would look like this: ``` SELECT * FROM appts WHERE timeStart <='$timeEnd' AND timeEnd >='$timeStart' AND dayappt='$boatdate' ``` Other good explanations have been given but I'll go ahead and update it with an alternative explanation of how I visualize this myself. Most people are looking for eac...
Shahkalpesh answered the question with: > I think you need an OR. > > ``` > SELECT * FROM appts > WHERE (timeStart >='$timeStart' > OR timeEnd <='$timeEnd') > AND dayappt='$boatdate' > ``` I posted a comment that I consider this to be wrong, giving a pair of counter-examples: > This is plain wrong - @ShaneD is cor...
How do I compare overlapping values within a row?
[ "", "sql", "mysql", "overlap", "" ]
What are the main differences among them? And in which typical scenarios is it better to use each language?
In order of appearance, the languages are `sed`, `awk`, `perl`, `python`. The `sed` program is a stream editor and is designed to apply the actions from a script to each line (or, more generally, to specified ranges of lines) of the input file or files. Its language is based on `ed`, the Unix editor, and although it h...
After mastering a few dozen languages, one gets tired of absolute recommendations against tools, like in [this answer](https://stackoverflow.com/a/367082/2057969) regarding `sed` and `awk`. Sed is the best tool for extremely simple command-line pipelines. In the hands of a sed master, it's suitable for one-offs of arb...
What are the differences between Perl, Python, AWK and sed?
[ "", "python", "perl", "sed", "awk", "language-comparisons", "" ]
I've been using ReSharper for the past months and, advertising aside, I can't see myself coding without it. Since I love living on the bleeding "What the hell just went wrong" edge, I decided to try my luck w/ the latest ReSharper 4.5 nightly builds. It's all nice. However, I've noticed that the using directives group...
As Scott proceeds to discover in his post, there is **no runtime difference** between these two cases. Therefore, it does **not** serve the purpose of lazy loading references. If you read the comments in Scott's blog all the way to the end, you will also see that the developer who passed this rumor to Scott (Mike Brow...
Well, the usual is subjective. :) But for me, the usual is the "old" way.
Organizing using directives
[ "", "c#", "coding-style", "using-directives", "" ]
I can't figure out how to get the SCOPE\_IDENTITY() back to my variables from an SQL2005 Store Procedure. My sSQL String: ``` sSQL = "EXEC [sp_NewClaim] " & Chr(34) & ClaimNumber & Chr(34) & ", " & Request.Cookies("UserID") & ", " & Request.Cookies("MasterID") & ", " & Chr(34) & strRestaurante & Chr(34) & ", " & Chr(...
For your stored procedure, do this: ``` CREATE PROCEDURE sp_NewClaim ( @ClaimNumber nvarchar(50), @blah............ ................. ) AS BEGIN SET NOCOUNT ON; INSERT INTO Accidente (ClaimNumber,........., RecordNumber) VALUES (@ClaimNumber,....., @RecordNumber) SELECT SCOPE_IDENTIT...
I agree with Joel Coehoorn's response, but I wanted to note that you are sending your SCOPE\_IDENTITY() variable back as an output parameter, but not retrieving it that way in your ado call. You cannot retrieve an output parameter using the method you are to call the stored procedure. If you are curious there are some...
Classic ASP getting SCOPE_IDENTITY() Value from SQL2005
[ "", "sql", "asp-classic", "identity", "" ]
I tried to make the title as clear as possible... here is my scenario: I have 2 tables (let's call them table A and table B) that have a similar schema. I would like write a stored procedure that would select specific columns of data out of table A, and insert this data as a new record in table B. Can someone point m...
``` INSERT INTO B (Col1, Col2) SELECT Col1, Col2 FROM A ``` Is this what you mean?
You can do this as a single query from C# like this: ``` Insert into tableB (col1, col2, col3) select col1, col2, col3 from tableA where ... ``` The trick is that column names need to be in the same order and compatible types.
Need SQL help - How can I select rows to perform an insert?
[ "", "sql", "sql-server", "t-sql", "" ]
Hullo all, Wondering if there are any Java hackers who can clue me in at to why the following doesn't work: ``` public class Parent { public Parent copy() { Parent aCopy = new Parent(); ... return aCopy; } } public class ChildN extends Parent { ... } public class Driver { publi...
(Can't add code in a comment, so I'll add here) Regarding Cloneable: if you're implementing Cloneable, implement it as follows; much cleaner to call... ``` public class Foo implements Cloneable { public Foo clone() { try { return (Foo) super.clone(); } catch (CloneNotSupportedException...
Is like trying to do this: ``` public Object copy(){ return new Object(); } ``` And then attempt to: ``` String s = ( String ) copy(); ``` Your *Parent* class and *ChildN* class have the same relationship as *Object* and *String* To make it work you would need to do the following: ``` public class Ch...
"Dynamic" Casting in Java
[ "", "java", "inheritance", "casting", "" ]
I am trying to implement the python logging handler `TimedRotatingFileHandler`. When it rolls over to midnight it appends the current day in the form `YYYY-MM-DD`. ``` LOGGING_MSG_FORMAT = '%(name)-14s > [%(levelname)s] [%(asctime)s] : %(message)s' LOGGING_DATE_FORMAT = '%Y-%m-%d %H:%M:%S' logging.basicConfig( ...
"How can i change how it alters the filename?" Since it isn't documented, I elected to read the source. This is what I concluded from reading the source of `logging/handlers.py` ``` handler = logging.handlers.TimedRotatingFileHandler("C:\\isis_ops\\logs\\Rotate_Test",'midnight',1) handler.suffix = "%Y-%m-%d" # or any...
You can do this by changing the log suffix as suggested above but you will also need to change the extMatch variable to match the suffix for it to find rotated files: ``` handler.suffix = "%Y%m%d" handler.extMatch = re.compile(r"^\d{8}$") ```
TimedRotatingFileHandler Changing File Name?
[ "", "python", "logging", "" ]
I'm trying to set a WPF image's source in code. The image is embedded as a resource in the project. By looking at examples I've come up with the below code. For some reason it doesn't work - the image does not show up. By debugging I can see that the stream contains the image data. So what's wrong? ``` Assembly asm =...
After having the same problem as you and doing some reading, I discovered the solution - [Pack URIs](http://msdn.microsoft.com/en-us/library/aa970069.aspx). I did the following in code: ``` Image finalImage = new Image(); finalImage.Width = 80; ... BitmapImage logo = new BitmapImage(); logo.BeginInit(); logo.UriSourc...
``` var uriSource = new Uri(@"/WpfApplication1;component/Images/Untitled.png", UriKind.Relative); foo.Source = new BitmapImage(uriSource); ``` This will load a image called "Untitled.png" in a folder called "Images" with its "Build Action" set to "Resource" in an assembly called "WpfApplication1".
Setting WPF image source in code
[ "", "c#", ".net", "wpf", "image", "" ]
If I am assigning an event handler at runtime and it is in a spot that can be called multiple times, what is the recommended practice to prevent multiple assignments of the same handler to the same event. ``` object.Event += MyFunction ``` Adding this in a spot that will be called more than once will execute the hand...
Baget is right about using an explicitly implemented event (although there's a mixture there of explicit interface implementation and the full event syntax). You can probably get away with this: ``` private EventHandler foo; public event EventHandler Foo { add { // First try to remove the handler, the...
I tend to add an event handler in a path that's executed once, for example in a constructor.
Preventing same Event handler assignment multiple times
[ "", "c#", "events", "" ]
I'm teaching myself some basic scraping and I've found that sometimes the URL's that I feed into my code return 404, which gums up all the rest of my code. So I need a test at the top of the code to check if the URL returns 404 or not. This would seem like a pretty straightfoward task, but Google's not giving me any ...
If you are using PHP's [`curl` bindings](https://www.php.net/manual/en/ref.curl.php), you can check the error code using [`curl_getinfo`](https://www.php.net/manual/en/function.curl-getinfo.php) as such: ``` $handle = curl_init($url); curl_setopt($handle, CURLOPT_RETURNTRANSFER, TRUE); /* Get the HTML or whatever is...
If your running php5 you can use: ``` $url = 'http://www.example.com'; print_r(get_headers($url, 1)); ``` Alternatively with php4 a user has contributed the following: ``` /** This is a modified version of code from "stuart at sixletterwords dot com", at 14-Sep-2005 04:52. This version tries to emulate get_headers()...
Easy way to test a URL for 404 in PHP?
[ "", "php", "http", "validation", "http-headers", "http-status-code-404", "" ]
How does `const` (pointers, references and member functions) help with thread safety in C++?
The main problem with multiple threads is mutability. const restricts this, but since you can cast away the const-ness, it's not foolproof.
Any immutable (that is, unchangable) data is inherently thread safe - there's no risk for multiple threads concurrently reading the same read-only data because it's never going to change! Marking a variable as const in C++ makes it read-only and thus thread safe.
Thread safety and `const`
[ "", "c++", "multithreading", "" ]
The code below is checking performance of three different ways to do same solution. ``` public static void Main(string[] args) { // for loop { Stopwatch sw = Stopwatch.StartNew(); int accumulator = 0; for (int i = 1; i <= 100000000; ++i) { ...
Why should `Enumerable.Range` be any slower than your self-made `GetIntRange`? In fact, if `Enumerable.Range` were defined as ``` public static class Enumerable { public static IEnumerable<int> Range(int start, int count) { var end = start + count; for(var current = start; current < end; ++current)...
My guess is that you're running in a debugger. Here are my results, having built from the command line with "/o+ /debug-" ``` time = 142; result = 987459712 time = 1590; result = 987459712 time = 1792; result = 987459712 ``` There's still a slight difference, but it's not as pronounced. Iterator block implementations...
Why is Enumerable.Range faster than a direct yield loop?
[ "", "c#", "performance", "ienumerable", "range", "enumerable", "" ]
I am trying to test that a particular method throws an expected exception from a method. As per JUnit4 documentation and [this answer](https://stackoverflow.com/questions/156503/how-to-assert-that-a-certain-exception-is-thrown-in-junit45-tests) I wrote the test as: ``` @Test(expected=CannotUndoException.class) publi...
I have found the problem. The TestRunner I was using was the correct one (JUnit 4), however, I declared my test class as: ``` public class CommandTest extends TestCase ``` Which I assume is causing the test runner to treat it as a JUnit 3 test. I removed `extends TestCase` and received the expected results.
Your test code looks ok to me. Check that you're running with a junit 4 testrunner, not a junit 3.8 testrunner - this could very well be the culprit here (try launching from the command line or just visually inspect the command line when running your test). *The classpath of your testrunner may not be the same as your...
Cause of an unexpected behaviour using JUnit 4's expected exception mechanism?
[ "", "java", "unit-testing", "exception", "junit4", "" ]
I decided to change a utility I'm working on to use a tabpage. When I tried to drag various controls from the form to a tab page on top of the form, it made copies of the control, giving it a different name. It's easy enough to just remake the form on top of the tab or just edit the source code in the designer to have ...
Have you tried cut and paste. That usually works for me.
The correct tool for this is the Document Outline (CTRL+W, U). Simply drag your set of controls in the outline so that they are under the tab page. Voila. The document outline dramatically simplifies these types of operations, especially when you are dealing with complex layouts.
C#: Move Controls From Form to tabPage in VS Form Designer
[ "", "c#", "winforms", "visual-studio-2005", "windows-forms-designer", "" ]
I've seen several of answers about using [Handle](http://technet.microsoft.com/en-us/sysinternals/bb896655.aspx) or [Process Monitor](http://technet.microsoft.com/en-us/sysinternals/bb896645.aspx), but I would like to be able to find out in my own code (C#) which process is locking a file. I have a nasty feeling that ...
One of the good things about `handle.exe` is that you can run it as a subprocess and parse the output. We do this in our deployment script - works like a charm.
Long ago it was impossible to reliably get the list of processes locking a file because Windows simply did not track that information. To support the [Restart Manager API](http://msdn.microsoft.com/en-us/library/windows/desktop/aa373656%28v=vs.85%29.aspx), that information is now tracked. I put together code that take...
How do I find out which process is locking a file using .NET?
[ "", "c#", "file-locking", "" ]
Should Java Objects be reused as often as it can be reused ? Or should we reuse it only when they are "heavyweight", ie have OS resources associated with it ? All old articles on the internet talk about object reuse and object pooling as much as possible, but I have read recent articles that say `new Object()` is high...
I let the garbage collector do that kind of deciding for me, the only time I've hit heap limit with freshly allocated objects was after running a buggy recursive algorithm for a couple of seconds which generated 3 \* 27 \* 27... new objects as fast as it could. Do what's best for readability and encapsulation. Sometim...
If you use them very **intensively** and the construction is **costly**, you should try to reuse them as much as you can. If your objects are very small, and cheap to create ( like Object ) you should create new ones. For instance connections database are pooled because the cost of creating a new one is higher than t...
Java Object Reuse
[ "", "java", "" ]
I recently asked this question: [Expose XML or Objects](https://stackoverflow.com/questions/368521/api-design-expose-xml-or-objects "Expose XML or Objects") - thanks all for the responses. One point to clarify. * The API will always be accessed remotely (i.e. as a service), most probably via webservices or WCF. I ag...
* Objects can perform better (thinking binary serialization here). * Objects can have stronger simple type validations. * Objects allow you to put the validation and business rules closer to the data structure definition. * Objects by their nature allow you to write simpler business rules and validation, since much of ...
If you're looking for an argument in favour of XML (not that I am particularly in favour of XML) are: * Exposing the XML and providing an XSD is self explanatory when it comes to data. You can pass off all the data in that form, it's self documenting and can be validated reasonably simply. * I can write a bunch of saf...
API Design: Expose XML or Objects #2
[ "", "c#", "web-services", "architecture", "n-tier-architecture", "" ]
I would like to use `ON DUPLICATE KEY UPDATE` in Zend Framework 1.5, is this possible? Example ``` INSERT INTO sometable (...) VALUES (...) ON DUPLICATE KEY UPDATE ... ```
I worked for Zend and specifically worked on Zend\_Db quite a bit. No, there is no API support for the `ON DUPLICATE KEY UPDATE` syntax. For this case, you must simply use `query()` and form the complete SQL statement yourself. I do not recommend interpolating values into the SQL as harvejs shows. Use query parameter...
As a sidebar, you can simplify the `ON DUPLICATE KEY UPDATE` clause and reduce the amount of processing your script needs to do by using `VALUES()`: ``` $sql = 'INSERT INTO ... ON DUPLICATE KEY UPDATE id = VALUES(id), col2 = VALUES(col2), col3 = VALUES(col3)'; ``` See <http://dev.mysql.com/doc/refman/5.1/en/insert-on...
Is there a way to do an "INSERT...ON DUPLICATE KEY UPDATE" in Zend Framework 1.5?
[ "", "php", "mysql", "zend-framework", "insert-update", "" ]
I am a bit of a newbie to Reg Ex and don't fully understand the difference between the different flavors. However, I have a basic Reg Ex that works when I try it via the UNIX system (vi and grep) but not when I try to to use it in PHP's ereg functions. I suspect there is something different about the PHP ereg function ...
PHP's ereg functions use a very limited regex flavor called [POSIX ERE](http://www.regular-expressions.info/posix.html). My [flavor comparison](http://www.regular-expressions.info/refflavors.html) indicates all that this flavor lacks compared with modern flavors. In your case, the word boundary \b is not supported. A ...
You may need to escape the backslash: ``` $string = ereg_replace("<em\\b[^>]*>(.*?)</em>","\\1",$string); ``` This is because `\b` in a PHP string means something different from a `\b` in a regular expression. Using `\\` in the PHP string passes through a single backslash to `ereg_replace()`. This is the same reason ...
Why won't this standard Reg Ex work in PHP's ereg function
[ "", "php", "html", "regex", "" ]
I want to do something like this: page A has a link to page B page B gets content from a database and processes it the result from page B is displayed on a div in page A Please notice that I don't want to leave page A while page B processes the information of the database. What I'm really trying to do is avoid u...
You want AJAX! AJAX will do that, but the steps will be a little different from what you describe * page A has a link that calls a javascript function * the javascript function makes an AJAX call to page B which gets content from a database and processes it * the result from page B is returned to the javascript funct...
What you are looking for is JavaScript and AJAX.
Is it possible to change an HTML element property using its ID with PHP?
[ "", "php", "html", "" ]
Helvetica is available in one form or another on Windows, Mac OS X, and Linux. Under Windows, I can see it from Microsoft Word. On the two UNIX platforms, I can find it with xlsfonts | grep -i helvetica; the name seems to be adobe-helvetica. But the JDK can't find it! It's not listed from GraphicsEnvironment.getAllFon...
I realize that this isn't actually answering the question, but... On Windows, Helvetica isn't always installed. My machine at work (the one I'm using now) doesn't, despite having Microsoft Office XP.
``` Font f = new Font("Helvetica", Font.PLAIN, 10); // make a new font object ObjectName.setFont(f); // set the objects font using setFont(); ``` where "Helvetica" is the font, Font.PLAIN defines the style, and 10 defines the size. Of course it must be installed to work, and you can bundle it using CreateFont(). Tr...
How do I use Helvetica in Java?
[ "", "java", "fonts", "" ]
I'm loading an XML document in my C# application with the following: ``` XDocument xd1 = new XDocument(); xd1 = XDocument.Load(myfile); ``` but before that, I do test to make sure the file exists with: ``` File.Exists(myfile); ``` But... is there an (easy) way to test the file before the XDocument.Load() to make su...
It's probably just worth catching the specific exception if you want to show a message to the user: ``` try { XDocument xd1 = new XDocument(); xd1 = XDocument.Load(myfile); } catch (XmlException exception) { ShowMessage("Your XML was probably bad..."); } ```
**This question confuses "[well-formed](http://www.w3.org/TR/REC-xml/#sec-well-formed)" with "[valid](http://en.wikipedia.org/wiki/Valid_XML_document)" XML document**. A valid xml document is by definition a well formed document. **Additionally**, it must satisfy a [**DTD**](http://www.w3.org/TR/REC-xml/#dt-doctype) o...
How does one test a file to see if it's a valid XML file before loading it with XDocument.Load()?
[ "", "c#", "xml", "linq-to-xml", "" ]
I'm working with a code base where lists need to be frequently searched for a single element. Is it faster to use a Predicate and Find() than to manually do an enumeration on the List? for example: ``` string needle = "example"; FooObj result = _list.Find(delegate(FooObj foo) { return foo.Name == needle; }); ```...
They are not equivalent in performance. The Find() method requires a method (in this case delegate) invocation for every item in the list. Method invocation is not free and is **relatively** expensive as compared to an inline comparison. The foreach version requires no extra method invocation per object. That being sa...
If searching your list is too slow as-is, you can probably do better than a linear search. If you can keep the list sorted, you can use a binary search to find the element in O(lg n) time. If you're searching a *whole* lot, consider replacing that list with a Dictionary to index your objects by name.
Find() vs. enumeration on lists
[ "", "c#", "performance", "search", "list", "" ]
What's the best way to animate a background image sliding to the left, and looping it? Say I've got a progress bar with a background I want to animate when it's active (like in Gnome or OS X). I've been playing with the `$(...).animate()` function and trying to modify the relevant CSS property, but I keep hitting a br...
As soon as I posted this I figured it out. In case it helps anyone else, here's the function I came up with: ``` function animateBar(self) { // Setup var bar = self.element.find('.ui-progress-bar'); bar.css('background-position', '0px 0px'); bar.animate({ backgroundPosition: '-20px 0px' }...
Just a suggestion, but rather than using a standard function and passing in the element as an argument, it would be better to use fn.extend. ``` $.fn.extend({ animateBar: function(){ $(this).find('.ui-progress-bar').css('background-position', '0px 0px'); $(this).find('.ui-progress-bar').animate({ ...
Easiest way to animate background image sliding left?
[ "", "javascript", "jquery", "css", "jquery-animate", "" ]
I have test database and a production database. When developing I of course work against that test database then when deploying I have to semi-manually update the production database (by running a batch-sql-script). This usually works fine but there's a chance for mistakes where the deployed database isn't the same as ...
I use a similar approach during development and I can ensure that the synchronization between the development and production databases can easily become a daunting task if you modify too many tables at once. I realized that the best approach would be to forget about doing this synchronization manually, it's simply too...
As far as I can tell, there's no way to automatically test before doing a submit. You can however infer it and programmatically check it. I have a controller for each Linq object that I use to marshal the Linq object, and that controller has an IsValid method that goes through and checks the db rules using a technique ...
Linq2Sql Testing
[ "", "c#", ".net", "unit-testing", "linq-to-sql", "" ]
I have a variable of type Hashmap`<String,Integer`>. In this, the Integer value might have to go some manipulation depending upon the value of a flag variable. I did it like this... ``` Hashmapvariable.put( somestring, if (flag_variable) { //manipulation code goes here new Integer(manipulated value); ...
You cannot place a statement in the method call. However, one option could be to make an method that returns a `Integer` such as: ``` private Integer getIntegerDependingOnFlag(boolean flag) { if (flag) return new Integer(MANIPULATED_VALUE); else return new Integer(NON-MANIPULATED_VALUE); } ```...
``` new Integer(flag_variable ? manipulated value : non-manipulated value) ``` Does the trick Edit: On Java 5, I suppose you can also write ``` hashmap.put(someString, flag_variable ? manipulated value : non-manipulated value) ``` due to auto-boxing.
If construct in hashmap.put call
[ "", "java", "hashmap", "" ]
``` Image.FromFile(@"path\filename.tif") ``` or ``` Image.FromStream(memoryStream) ``` both produce image objects with only one frame even though the source is a multi-frame TIFF file. **How do you load an image file that retains these frames?** The tiffs are saved using the Image.SaveAdd methods frame by frame. The...
Here's what I use: ``` private List<Image> GetAllPages(string file) { List<Image> images = new List<Image>(); Bitmap bitmap = (Bitmap)Image.FromFile(file); int count = bitmap.GetFrameCount(FrameDimension.Page); for (int idx = 0; idx < count; idx++) { // save each frame to a bytestream ...
I was able to handle the multi-frame tiff by using the below method. ``` Image multiImage = Image.FromFile(sourceFile); multiImage.Save(destinationFile, tiff, prams); int pageCount = multiImage.GetFrameCount(FrameDimension.Page); for (int page = 1; page < pageCount; page++ ) { multiImage.SelectActiveFrame(Frame...
How to open a multi-frame TIFF imageformat image in .NET 2.0?
[ "", "c#", "tiff", "system.drawing", "" ]
Explanation: Say package A is always built first and then package B. I need to configure my eclipse workspace such that it mimics the build environment and shows compilation errors when sources in package A refer package B. Is this possible? If yes, how?
Take a look to: [Arquitecture Rules](http://architecturerules.googlecode.com/svn/docs/downloads.html) or [Macker](http://innig.net/macker/) These tools are able to warn you when some rule is broken. They both support the rule "some package should not invoke some other package". I do not know if there is an eclipse pl...
You'd need to build them as separate projects, with project B referring to project A but not the other way round.
How do I enforce a package-level build order in eclipse
[ "", "java", "eclipse", "ide", "" ]
I have following situation. A main table and many other tables linked together with foreign keys. Now when I would like to delete a row in the main table a ConstraintsViolation will occur, which is intended and good. Now I want to be able to check if the ConstraintsViolation will occur before I trigger the delete row ...
``` If Exists ( Select * From OtherTable Where OtherTableFKColumn = MainTablePrimaryKey) Begin Rollback Transaction RaisError('Violating FK Constraint in Table [OtherTable]', 16, 1) End ```
This is a question that on the surface looks good, but has implications. First of all, you'd need to ensure that after you've read the status of those relations, nobody could change those, so obviously you need to use a transaction and lock the rows in question. Then you need a way to figure out what relations to che...
Can I check for constraints before a delete in SQL Server?
[ "", "sql", "database", "sql-server-2005", "constraints", "" ]
I would like to compare two dates in javascript. I have been doing some research, but all I can find is how to return the current date. I want to compare 2 separate dates, not related to today. How do I do that. ``` var startDate = Date(document.form1.Textbox2); ```
``` if (date1.getTime() > date2.getTime()) { alert("The first date is after the second date!"); } ``` [Reference to Date object](https://developer.mozilla.org/en/Core_JavaScript_1.5_Reference/Global_Objects/Date)
``` new Date('1945/05/09').valueOf() < new Date('2011/05/09').valueOf() ```
How do I do a Date comparison in Javascript?
[ "", "javascript", "datetime", "" ]
Can anyone link me to a decent c++ tutorial that's actually currently in date? Almost everything I find applies to 2005 and the code examples are riddled with errors which won't run in my 2008 version of the visual compiler.
The book *Accelerated C++* is a good start to learn C++.
Here is a Visual C++ 2008 Express Edition Introdution: [Introduction to Visual C++ 2008 Express (Video)](http://msdn.microsoft.com/en-us/beginner/bb964629.aspx). You will find a good book-list about Standard C++ here: <http://jcatki.no-ip.org:8080/fncpp/Resources#books> (that's the website of the ##c++ irc channel on i...
Is there a tutorial on C++ programming in Visual Studio 2008?
[ "", "c++", "windows", "visual-studio-2008", "" ]
It seems that ``` if (x=y) { .... } ``` instead of ``` if (x==y) { ... } ``` is a root of many evils. Why don't *all* compilers *mark it as error* instead of a configurable warning? I'm interested in finding out cases where the construct `if (x=y)` is useful.
Most of the time, compilers try very hard to remain backward compatible. Changing their behavior in this matter to throw errors will break existing legitimate code, and even starting to throw warnings about it will cause problems with automatic systems that keep track of code by automatically compiling it and checking...
One useful construct is for example: ``` char *pBuffer; if (pBuffer = malloc(100)) { // Continue to work here } ``` As mentioned before, and downvoted several times now, I might add this is not specially good style, but I have seen it often enough to say it's useful. I've also seen this with `new`, but it makes m...
Inadvertent use of = instead of ==
[ "", "c++", "c", "compiler-construction", "programming-languages", "" ]
I am working on an in-browser editor within a `textarea`. I have started looking for some information on dealing with `textarea` selection and found [this jQuery plugin, fieldSelection](https://github.com/localhost/jquery-fieldselection) that does some simple manipulation. However, it doesn't explain what's going on. ...
Start with PPK's [introduction to ranges](http://www.quirksmode.org/dom/range_intro.html). Mozilla developer connection has info on [W3C selections](https://developer.mozilla.org/en/DOM/window.getSelection). Microsoft have their system [documented on MSDN](http://msdn.microsoft.com/en-us/library/ms535869(VS.85).aspx). ...
``` function get_selection(the_id) { var e = document.getElementById(the_id); //Mozilla and DOM 3.0 if('selectionStart' in e) { var l = e.selectionEnd - e.selectionStart; return { start: e.selectionStart, end: e.selectionEnd, length: l, text: e.value.substr(e.selectionStart, l) }; }...
Understanding what goes on with textarea selection with JavaScript
[ "", "javascript", "textarea", "selection", "" ]
``` string str1 = "12345ABC...\\...ABC100000"; // Hypothetically huge string of 100000 + Unicode Chars str1 = str1.Replace("1", string.Empty); str1 = str1.Replace("22", string.Empty); str1 = str1.Replace("656", string.Empty); str1 = str1.Replace("77ABC", string.Empty); // ... this replace anti-pattern might h...
*All* characters in a .NET string are "unicode chars". Do you mean they're non-ascii? That shouldn't make any odds - unless you run into composition issues, e.g. an "e + acute accent" not being replaced when you try to replace an "e acute". You could try using a regular expression with [`Regex.Replace`](http://msdn.mi...
If you want to be really fast, and I mean really fast you'll have to look beyond the StringBuilder and just write well optimized code. One thing your computer doesn't like to do is branching, if you can write a replace method which operates on a fixed array (char \*) and doesn't branch you have great performance. Wha...
Memory Efficiency and Performance of String.Replace .NET Framework
[ "", "c#", ".net", "string", "" ]
JTextField has a keyTyped event but it seems that at the time it fires the contents of the cell have not yet changed. Because of that .length() is always wrong if read here. There must be a simple way of getting the length as it appears to the user after a key stroke?
This is probably not the optimal way (and it's been a while), but in the past, I have added a DocumentListener to the JTextField and on any of the events (insert, update, remove) I: ``` evt.getDocument().getLength() ``` Which returns the total length of text field's contents.
This may be related to this ["bug" (or rather "feature")](https://bugs.java.com/bugdatabase/view_bug?bug_id=4140413) > The listeners are notified of the key events prior to processing them to > allow the listeners to "steal" the events by consuming them. This gives > compatibility with the older awt notion of consumin...
How can I get the length of a JTextField's contents as the user types?
[ "", "java", "swing", "events", "jtextfield", "" ]
Is there any way that I can find the container pointed to by an iterator? Specifically, I want to be able to find the `std::vector` pointed to by a particular `std::vector::iterator` so that I can check the range, without having to actually pass references to that vector around. If (as I suspect) the answer is no, why...
I don't believe so. If iterators had to keep a reference/pointer to their owning container, then it would be impossible for them to be optimized down to a lightweight pointer (which can be done with containers guaranteeing contiguous storage like vectors and such).
There is no way to make that work. The reason is simple: Adding a way to the iterators to get the container to which they are pointing is * Pointless. Iterators iterate over a collection. As other said, only that, nothing more. * Not compatible with the iterator requirements. Remember a pointer is a random access iter...
Finding the owner of an STL iterator
[ "", "c++", "stl", "iterator", "" ]
I'm trying to parse an array of JSON objects into an array of strings in C#. I can extract the array from the JSON object, but I can't split the array string into an array of individual objects. What I have is this test string: ``` string json = "{items:[{id:0,name:\"Lorem Ipsum\"},{id:1,name" + ":\"Lore...
Balanced parentheses are literally a textbook example of a language that cannot be processed with regular expressions. JSON is essentially balanced parentheses plus a bunch of other stuff, with the braces replaced by parens. In the [hierarchy of formal languages](http://en.wikipedia.org/wiki/Chomsky_hierarchy), JSON is...
> Balanced parentheses are literally a textbook example of a language that cannot be processed with regular expressions bla bla bla ... check this out: ``` arrayParser = "(?<Key>[\w]+)":"?(?<Value>([\s\w\d\.\\\-/:_]+(,[,\s\w\d\.\\\-/:_]+)?)+)"? ``` this works for me if you want to match empty values change last '+'...
Regular expression to parse an array of JSON objects?
[ "", "c#", ".net", "regex", "json", "" ]
I have to call domain A.com (which sets the cookies with http) from domain B.com. All I do on domain B.com is (javascript): ``` var head = document.getElementsByTagName("head")[0]; var script = document.createElement("script"); script.src = "A.com/setCookie?cache=1231213123"; head.appendChild(script); ``` This sets t...
From the [`Safari Developer FAQ`](http://developer.apple.com/internet/safari/faq.html#anchor6): > Safari ships with a conservative cookie policy which limits cookie writes to only the pages chosen ("navigated to") by the user. This default conservative policy may confuse frame based sites that attempt to write cookies...
Here is a solution which works: <http://anantgarg.com/2010/02/18/cross-domain-cookies-in-safari/>
Setting cross-domain cookies in Safari
[ "", "javascript", "safari", "cookies", "cross-domain", "cross-site", "" ]
I have a solution that is missing a lot of code coverage. I need to refactor this code to decouple to begin to create unit tests. What is the best strategy? I am first thinking that I should push to decouple business logic from data access from businessobjects to first get some organization and then drill down from the...
Check out [Working Effectively with Legacy Code](https://rads.stackoverflow.com/amzn/click/com/0131177052).
One of the most important things to do and best ways to approach in legacy code is defects. It is a process that you will continue to do with any code base that you introduce unit testing to, as well. Whenever a defect is reported, write a unit test that will expose the defect. You will quickly find that code that woul...
Best strategy to get coding prepared for unit testing
[ "", "c#", "unit-testing", "refactoring", "code-coverage", "" ]
I need to keep a couple of [Jena](http://jena.sf.net) Models (OntModels, specifically) synchronized across a socket, and I'd like to do this one change at a time (for various reasons -- one being that each Statement added or removed from the OntModels is also adapting a JESS rule base.). I am able to listen to the add/...
I would serialize the changes out in N-TRIPLES format. Jena has built-in N-TRIPLES serializer and parser, but the N-TRIPLES syntax is (deliberately) very simple so it would be easy to generate manually in your code. However, it might be even easier to keep a plain mem model around to hold the changes, have the event h...
Not an area I've looked at in great depth, but I recalled Talis were doing some research and was able to [follow breadcrumbs](http://n2.talis.com/wiki/Changeset_Protocol) to the relevant vocabulary called "Changeset". <http://vocab.org/changeset/schema> I'm surprised you had issues serialising individual statements u...
Serializing JENA OntModel Changes
[ "", "java", "serialization", "jena", "ontology", "" ]
I've got the following Generic usercontrol declared: ``` public partial class MessageBase<T> : UserControl { protected T myEntry; public MessageBase() { InitializeComponent(); } public MessageBase(T newEntry) { InitializeComponent(); ...
Try this ``` public partial class MessageControl : MessageControlBase { public MessageControl() { InitializeComponent(); } } public class MessageControlBase : MessageBase<Post> {} ``` The key to getting the designer to work is that the base class of the class you are editing must not ...
Yes. its possible. See Below link to get an idea. <https://web.archive.org/web/20130603104810/http://www.hackersbasement.com/csharp/post/2009/08/29/Generic-Control-Builder-in-ASPNet.aspx>
Is it Possible to Make a Generic Control in .Net 3.5?
[ "", "c#", ".net", "winforms", "generics", "user-controls", "" ]
Is there a good way in C++ to implement (or fake) a type for a generic vector of vectors? Ignore the issue of when a vector of vectors is a good idea (unless there's something equivalent which is always better). Assume that it does accurately model the problem, and that a matrix does not accurately model the problem. ...
You want to have template-typedefs. That is *not* yet supported in the current C++. A workaround is to do ``` template<typename T> struct vecvec { typedef std::vector< std::vector<T> > type; }; int main() { vecvec<int>::type intSequences; vecvec<std::string>::type stringSequences; } ``` In the next C++ ...
I use [Boost.MultiArray](http://www.boost.org/doc/libs/release/libs/multi_array/doc/user.html) which is implemented in the boost library. HTH
Generic vector of vectors in C++
[ "", "c++", "stl", "" ]
I have a function that expects real numbers (either integers or floats) as its input, and I'm trying to validate this input before doing mathematical operations on it. My first instinct is to cast inputs as floats from within a try-except block. ``` try: myinput = float(input) except: raise ValueError("input is...
To quote myself from [How much input validation should I be doing on my python functions/methods?](https://stackoverflow.com/questions/367560/how-much-input-validation-should-i-be-doing-on-my-python-functionsmethods#368072): > For calculations like sum, factorial etc, pythons built-in type checks will do fine. The cal...
In Python 2.6 and 3.0, a type hierarchy of numeric abstract data types has been [added](http://www.python.org/dev/peps/pep-3141/), so you could perform your check as: ``` >>> import numbers >>> isValid = isinstance(myinput , numbers.Real) ``` numbers.Real will match integral or float type, but not non-numeric types, ...
What's the most pythonic way of testing that inputs are well-formed numbers
[ "", "python", "idioms", "" ]
I use cvs to maintain all my python snippets, notes, c, c++ code. As the hosting provider provides a public web- server also, I was thinking that I should convert the cvs automatically to a programming snippets website. 1. [cvsweb](http://www.freebsd.org/projects/cvsweb.html) is not what I mean. 2. [doxygen](http://ww...
I finally settled for [rest2web](http://www.voidspace.org.uk/python/rest2web/). I had to do the following. 1. Use a separate python script to recursively copy the files in the CVS to a separate directory. 2. Added extra files index.txt and template.txt to all the directories which I wanted to be in the webpage. 3. The...
Run [Trac](http://trac.edgewall.org/) on the server linked to the (svn) repository. The Trac wiki can conveniently refer to files and changesets. You get TODO tickets, too.
Convert CVS/SVN to a Programming Snippets Site
[ "", "python", "svn", "web-applications", "rest", "cvs", "" ]
I have a list box control: ``` <asp:ListBox runat="server" id="lbox" autoPostBack="true" /> ``` The code behind resembles: ``` private void Page_Load(object sender, System.EventArgs e) { lbox.SelectedIndexChanged+=new EventHandler(lbox_SelectedIndexChanged); if(!Page.IsPostBack) { LoadData(); ...
What's the output of the foo() function call? Populating manually the list box you can set indexes to whatever you want (all 0 for example) - so the same thing can happen setting a given dataSource under certain circumstances (one that specifies indexes I suppose). If all the item indexes are 0 the result is that the ...
The **real** issue here is order of events. When you databind in page\_load you overwrite the posted data, thats why the selection is not set in the listbox. You can easily overcome this by moving the binding logic to Page\_Init.
selectedIndex is lost during postbacks - ASP.NET
[ "", "c#", ".net", "asp.net", "viewstate", "" ]
``` typeof(int).Name ``` Will return System.Int32 does anyone know of a way to return "int"
There aren't many types that are C# keywords (int, double, string) ... so perhaps you can write your own mapping function, from the System type name to the corresonding C# keyword.
Yeah, you could write a mapping function. That is just an alias anyway. Here is a list: <http://msdn.microsoft.com/en-us/library/86792hfa(VS.71).aspx>
C# type name instead of CLR type name
[ "", "c#", "system.type", "" ]
When the Java compiler autoboxes a primitive to the wrapper class, what code does it generate behind the scenes? I imagine it calls: * The valueOf() method on the wrapper * The wrapper's constructor * Some other magic?
You can use the `javap` tool to see for yourself. Compile the following code: ``` public class AutoboxingTest { public static void main(String []args) { Integer a = 3; int b = a; } } ``` To compile and disassemble: ``` javac AutoboxingTest.java javap -c AutoboxingTest ``` The output is: ...
I came up with a unit test that proves that Integer.valueOf() is called instead of the wrapper's constructor. ``` import static org.junit.Assert.assertNotSame; import static org.junit.Assert.assertSame; import org.junit.Test; public class Boxing { @Test public void boxing() { assertSame(5, 5); ...
What code does the compiler generate for autoboxing?
[ "", "java", "autoboxing", "" ]
I've searched, but I've not understood very well these three concepts. When do I have to use dynamic allocation (in the heap) and what's its real advantage? What are the problems of static and stack? Could I write an entire application without allocating variables in the heap? I heard that others languages incorporate...
[A similar question](https://stackoverflow.com/questions/79923/what-and-where-are-the-stack-and-heap) was asked, but it didn't ask about statics. ## Summary of what static, heap, and stack memory are: * A static variable is basically a global variable, even if you cannot access it globally. Usually there is an addres...
The following is of course all not quite precise. Take it with a grain of salt when you read it :) Well, the three things you refer to are **automatic, static and dynamic storage duration**, which has something to do with how long objects live and when they begin life. --- ### Automatic storage duration You use aut...
Stack, Static, and Heap in C++
[ "", "c++", "static", "garbage-collection", "stack", "heap-memory", "" ]
I want to use php in console mode and create an environment to test my functions. I do not want to be forced to use a web browser and create a new file each time I want to test a function. I want to access the function in the console and then it return the result. How do I do this? **Update:** Perhaps I have expla...
I have used [phpsh](http://www.phpsh.org/) in the past and found it very useful. Once you start it you will need to `chdir()` to where your files are and then obviously `require()` any files containing functions you need to test. You can then just test your function calls by typing them into the shell e.g. `var_dump(so...
I guess you've to be more specific what kind of functions exactly. Wordpress does not provide something like that out of the box, most PHP apps won't. I also think you're calling for trouble here when such apps aren't developed in mind for such environments. Here's an example trying to call "current\_time()" from fun...
Creating a testing environment with php cli
[ "", "php", "shell", "environment", "command-line-interface", "" ]
I am learning Java for a test (tomorrow) and am wondering about a question that will probably never come up but has got me curious. Is it possible to create a new collection class such as a list or something that can hold only a specific type and not its sub-types? Would I use generics to achieve this goal?
Not really, or at least not practically. Subtypes should operate like sets in mathematical set theory. If B is a subset of A, any item in B is also an item in A. In the same way, if B is a subtype of A, any item in B is also an item of A. Thus, any collection of A must be able to maintain items of B. That being said...
The question is: why would you want that. If you have a list containing animals, why would you want to fill that list only with the "base animal", but prevent dogs or cats being added to the list. One of the basic concepts of OO is that you use an instance of a subclass everywhere where you need in instance of the base...
Java: How to create a collection of a specific parent type and not its subtypes?
[ "", "java", "generics", "" ]
I need assistance finding a delivery method that best fulfills the following requirements: * We wish to deliver a single file to my clients. * Clients should be able to launch this file from the operating system shell - much like running an '.exe' on Windows. * After being launched, the program/script should be able t...
> *..but internet explorer warns users when local content is launched..* I don't get it, what's the problem with IE saying "Hey this app is trying to run *your* files!" I don't mean you don't have a good reason for this, it is just, I don't get it. IE will only warn the user if the app has not been downloaded and tr...
"internet explorer warns users when local content is launched" There's a reason for this. How can they distinguish your excellent, well-behaved, polite application from a virus? Since the line between your app and a virus is very, very blurry, go with any of Silverlight XAP file, an adobe Flex file or a Java JAR. Th...
Cross-platform executable/runtime delivery method
[ "", "java", "flash", "silverlight", "cross-platform", "" ]
Suppose I have some per-class data: (AandB.h) ``` class A { public: static Persister* getPersister(); } class B { public: static Persister* getPersister(); } ``` ... and lots and lots more classes. And I want to do something like: ``` persistenceSystem::registerPersistableType( A::getPersister() ); persistenc...
You can execute something before main once if a instantiation of a template is made. The trick is to put a static data member into a class template, and reference that from outside. The side effect that static data member triggers can be used to call the register function: ``` template<typename D> struct automatic_reg...
Register each template at run-time in the constructor. Use a static variable per template to check if the type has already been registered. The following is a quickly hacked together example: ``` #include <iostream> #include <vector> using namespace std; class Registerable { static vector<Registerable *> registr...
Best way to for C++ types to self register in a list?
[ "", "c++", "" ]
I need to make an AJAX request from a website to a REST web service hosted in another domain. Although this is works just fine in Internet Explorer, other browsers such as Mozilla and Google Chrome impose far stricter security restrictions, which prohibit cross-site AJAX requests. The problem is that I have no contro...
maybe [JSONP](http://en.wikipedia.org/wiki/JSONP) can help. NB youll have to change your messages to use json instead of xml Edit Major sites such as flickr and [twitter](http://apiwiki.twitter.com/Search+API+Documentation) support jsonp with callbacks etc
The post marked as the answer is erroneous: the iframes document is NOT able to access the parent. The same origin policy works both ways. The fact is that it is not possible in any way to consume a rest based webservice using xmlhttprequest. The only way to load data from a different domain (without any framework) is...
Cross-site AJAX requests
[ "", "javascript", "ajax", "security", "xss", "" ]
How do I get my netbeans drag and drop widget to know whether it is rendering inside the netbeans design view window or the running application? I'm trying to do some custom rendering. I think it has to do with the root container.
Try [java.beans.Beans.isDesignTime()](http://java.sun.com/javase/6/docs/api/java/beans/Beans.html#isDesignTime()).
This is another method: ``` Component c = javax.swing.SwingUtilities.getRoot(this); String className = c.getClass().getCanonicalName(); if (!"org.netbeans.core.windows.view.ui.MainWindow" .equalsIgnoreCase(className)) { ``` Although I think the ``` Beans.isDesignTime() ``` method is better
How do I get my netbeans drag and drop widget to know whether it is rendering inside the netbeans design view window or the running application?
[ "", "java", "swing", "netbeans", "javabeans", "designview", "" ]
In the following code, g++ gives this error : 1.cpp: In member function `void W::test()': 1.cpp:6: error:`int F::glob' is private 1.cpp:19: error: within this context But, shouldn't the globally declared variable 'glob' be used here, instead of the "private" "glob"? ``` #include <iostream.h> int glob; cla...
Variables and functions are accessed using scoping rules, not visbility rules. Because `F::glob` is the `glob` in the scope of `W::test()`, it is used. However, `W::test()` does not have access to `F::glob`, and an error results. The compiler does *not* check for `::glob` because something else preceeds it in scope "pr...
private glob shadows the global glob,so the error is correct use ::glob to access the global variable if u intent to use global variable
C++ variable with same name, context : global and private,
[ "", "c++", "private", "global", "" ]
I just started reading Effective C++ today and got to the point where the author talks about the operator new. The book explains very well how you can catch (with various degrees of elegance) the std::bad\_alloc exception that the operator new can raise if you run out of memory. My question is: How often do you check...
I catch exceptions when I can answer this question: > What will you do with the exception once you've caught it? Most of the time, my answer is, "I have no idea. Maybe my caller knows." So I don't catch the exception. Let it bubble up to someone who knows better. When you catch an exception and let your function pro...
The problem is that when you run out of memory there is generally not much you can do except write to a crash dump and exit the program. It's therefore useless to check every new in your program. One exception to this is when you allocate memory for e.g. loading a file, in which case you just need to inform the user t...
How often do you check for an exception in a C++ new instruction?
[ "", "c++", "exception", "" ]
A little background: * [PEP 8](http://www.python.org/dev/peps/pep-0008/) is the *Style Guide for Python Code*. It contains the conventions all python programmers should follow. * [pep8.py](http://pypi.python.org/pypi/pep8) is a (very useful) script that checks the code formating of a given python script, according to ...
As of PyDev 2.3.0, `pep8` is integrated in PyDev by default, even shipping with a default version of it. Open Window > Preferences It must be enabled in PyDev > Editor > Code Analysis > pep8.py Errors/Warnings should be shown as markers (as other things in the regular code analysis). In the event a file is not anal...
I don't know how to integrate it for whole project, but I have used it as an external tool to analyze an individual file. Note that the [`pycodestyle`](https://pypi.python.org/pypi/pycodestyle/) package is the official replacement for and is the newer version of the [`pep8`](https://pypi.python.org/pypi/pep8/) package...
How to integrate pep8.py in Eclipse?
[ "", "python", "eclipse", "pydev", "pep8", "" ]
I'd like to hide a div when user click anywhere on the page outside of that div. How can I do that using raw javascript or jQuery?
Attach a click event to the document to hide the div: ``` $(document).click(function(e) { $('#somediv').hide(); }); ``` Attach a click event to the div to stop clicks on it from propagating to the document: ``` $('#somediv').click(function(e) { e.stopPropagation(); }); ```
First idea, in raw javascript (from [this post](http://www.webdeveloper.com/forum/showpost.php?p=465274&postcount=4)): ``` <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <html> <head> <title>Untitled Document</title> <meta http-equiv="Content-Type" con...
Event on a click everywhere on the page outside of the specific div
[ "", "javascript", "jquery", "" ]
My question pertains to multi-threading in Java. I'm translating an app I wrote in Visual Basic 2008 into Java. There is a class in VB called [BackgroundWorker](http://msdn.microsoft.com/en-us/library/system.componentmodel.backgroundworker_members.aspx), which allows the coder to perform a task on another thread, a lot...
The solely intention of the following code is to show how does it looks like when the SwingUtilities.invokeLater method is used. The effect is the task is executed in the AWT-Event thread ( the one responsible for component painting ) . The rest ( creating a new thread , creating a gui etc. ) is just scaffold code. ...
What was the mainline again? Let me see if I get this right. The background thread fires an event the GUI can intercept to know the data is ready. Is that correct? You may use SwingUtilities.invokeLater( Runnable r ); It inserts that runnable instance in the AWT event dispatch thread ( that I guess is the same as ...
Firing a mainline event from a background thread in Java
[ "", "java", "multithreading", "events", "" ]
I have a type which I consider use it as struct. * It represents single value * It is immutable But the problem is, it has 6 fields of int. So which solution I should use for this type? 1. keep using struct? 2. change to class? 3. or pack 6 integers into an array of int, so it has only one field **EDIT** Size of ...
It depends how you are going to use it? 1. Are you going to allocate a lot of it vs. pass it around a lot? 2. Is it going to be consumed by 3rd party code? In this case, classes typically give you more flexibility. 3. Do you want struct vs. class semantics? For example, non-nullable? 4. Would you benefit from having a...
Be careful of boxing. If your struct is going to be consumed by a method which expects an Object, it will be coerced into an object and you'll have a potential performance hit. Here's a [reference](http://www.c-sharpcorner.com/UploadFile/stuart_fujitani/BoxNUnbox11192005055746AM/BoxNUnbox.aspx) that explains it in mor...
Optimal solution for struct with more than 16 bytes
[ "", "c#", "optimization", "class", "struct", "" ]