Prompt
stringlengths
10
31k
Chosen
stringlengths
3
29.4k
Rejected
stringlengths
3
51.1k
Title
stringlengths
9
150
Tags
listlengths
3
7
I want my controller to return the right HTTP response code when the user lacks permission to view a particular page.
**Quickie** If you are using plain JSP views (as is most common), then simply add ``` <% response.setStatus( 403 ); %> ``` somewhere in your view file. At the top is a nice place. **Detail** In MVC, i would always set this in the view, and in most cases with Spring-MVC, use the `SimpleMappingExceptionResolver` to ...
You can also just throw ``` org.springframework.security.access.AccessDeniedException("403 returned"); ``` This returns a 403 in the response header.
How do I return a 403 Forbidden in Spring MVC?
[ "", "java", "spring", "http-status-code-403", "httpforbiddenhandler", "" ]
I'm trying to alpha blend sprites and backgrounds with [devkitPro](http://www.devkitpro.org/) (including libnds, libarm, etc). Does anyone know how to do this?
As a generic reference, i once wrote [a small blog entry](http://sylvainhb.blogspot.com/2006/09/alpha-blending.html) about that issue. Basically, you first have to define which layer is alpha-blended against which other layer(s). Afaik, * the source layer(s) must be over destination layer(s) to have some blending disp...
Sprites on the DS can be alpha blended using the [blend control registers](http://www.coranac.com/tonc/text/gfx.htm#sec-blend). TONC gives the necessary information for getting blending working on the main screen because the register locations are the same. Alpha blending on the subscreen uses the same process with dif...
Alpha blending sprites in Nintendo DS Homebrew
[ "", "c++", "c", "nintendo-ds", "" ]
Is there a way to tell MS SQL that a query is not too important and that it can (and should) take its time? Likewise is there a way to tell MS SQL that it should give higher priority to a query?
Not in versions below SQL 2008. In SQL Server 2008 there's the resource governor. Using that you can assign logins to groups based on properties of the login (login name, application name, etc). The groups can then be assigned to resource pools and limitations or restrictions i.t.o. resources can be applied to those re...
SQL Server does not have any form of resource governor yet. There is a SET option called QUERY\_GOVERNOR\_COST\_LIMIT but it's not quite what you're looking for. And it prevents queries from executing based on the cost rather than controlling resources.
Priority of a query in MS SQL
[ "", "sql", "sql-server", "database", "" ]
Can anyone recommend a good binary XML format? It's for a JavaME application, so it needs to be a) Easy to implement on the server, and b) Easy to write a low-footprint parser for on a low-end JavaME client device. And it goes without saying that it needs to be smaller than XML, and faster to parse. --- The data wou...
You might want to take a look at [wbxml](http://en.wikipedia.org/wiki/WBXML) (Wireless Binary XML) it is optimized for size, and often used on mobile phones, but it is not optimized for parsing speed.
[Hessian](http://en.wikipedia.org/wiki/Hessian_(protocol)) might be an alternative worth looking at. It is a small protocol, well-suited for Java ME applications. "Hessian is a binary web service protocol that makes web services usable without requiring a large framework, and without learning a new set of protocols. B...
Best binary XML format for JavaME
[ "", "java", "xml", "java-me", "mobile", "" ]
I am developing a web page code, which fetches dynamically the content from the server and then places this content to container nodes using something like ``` container.innerHTML = content; ``` Sometimes I have to overwrite some previous content in this node. This works fine, until it happens that previous content o...
The easiest solution that I have found would be to place an anchor tag `<a>` at the top of the `div` you are editing: ``` <a name="ajax-div"></a> ``` Then when you change the content of the `div`, you can do this to have the browser jump to your anchor tag: ``` location.hash = 'ajax-div'; ``` Use this to make sure ...
It sounds like the webkit rendering engine of Safari is not at first recognizing the content change, at least not fully enough to remove the previous html content. Minimizing and then restoring the windows initiates a redraw event in the browser's rendering engine. I think I would explore 2 avenues: first could I use ...
innerHTML manipulation in JavaScript
[ "", "javascript", "html", "dom", "" ]
I want to implement in Java a class for handling graph data structures. I have a Node class and an Edge class. The Graph class maintains two list: a list of nodes and a list of edges. Each node must have an unique name. How do I guard against a situation like this: ``` Graph g = new Graph(); Node n1 = new Node("#1");...
I work with graph structures in Java a lot, and my advice would be to make any data member of the Node and Edge class that the Graph depends on for maintaining its structure final, with no setters. In fact, if you can, I would make Node and Edge completely immutable, which has [many benefits](http://www.javapractices.c...
It isn't clear to me why you are adding the additional indirection of the String names for the nodes. Wouldn't it make more sense for your Edge constructor's signature to be something like `public Edge(String, Node, Node)` instead of `public Edge (String, String, String)`? I don't know where clone would help you here....
Should I use clone when adding a new element? When should clone be used?
[ "", "java", "memory", "class", "" ]
Certainly there's the difference in general syntax, but what other critical distinctions exist? There are *some* differences, right?
The linked comparisons are very thorough, but as far as the main differences I would note the following: * C# has anonymous methodsVB has these now, too * C# has the yield keyword (iterator blocks)VB11 added this * VB supports [implicit late binding](http://smartypeeps.blogspot.com/2006/06/late-binding-in-c-and-vbnet....
This topic has had a lot of face time since .Net 2.0 was released. See this [Wikipedia](http://en.wikipedia.org/wiki/Comparison_of_C_sharp_and_Visual_Basic_.NET) article for a readable summary.
What are the most important functional differences between C# and VB.NET?
[ "", "c#", "vb.net", "comparison", "" ]
What is the best way of doing case-insensitive string comparison in C++ without transforming a string to all uppercase or all lowercase? Please indicate whether the methods are Unicode-friendly and how portable they are.
Boost includes a handy algorithm for this: ``` #include <boost/algorithm/string.hpp> // Or, for fewer header dependencies: //#include <boost/algorithm/string/predicate.hpp> std::string str1 = "hello, world!"; std::string str2 = "HELLO, WORLD!"; if (boost::iequals(str1, str2)) { // Strings are identical } ```
The trouble with boost is that you have to link with and depend on boost. Not easy in some cases (e.g. android). And using char\_traits means *all* your comparisons are case insensitive, which isn't usually what you want. This should suffice. It should be reasonably efficient. Doesn't handle unicode or anything thoug...
Case-insensitive string comparison in C++
[ "", "c++", "string", "" ]
We've been trying to alter a lot of columns from nullable to not nullable, which involves dropping all the associated objects, making the change, and recreating the associated objects. We've been using SQL Compare to generate the scripts, but I noticed that SQL Compare doesn't script statistic objects. Does this mean ...
It is considered best practice to auto create and auto update statistics. Sql Server will create them if it needs them. You will often see the tuning wizard generate lots of these, and you will also see people advise that you update statistics as a part of your maintenance plan, but this is not necessary and might actu...
If you have update stats and auto create stats on then it should works as before You can also run `sp_updatestats` or `UPDATE STATISTICS WITH FULLSCAN` after you make the changes
Is it OK to drop sql statistics?
[ "", "sql", "sql-server", "scripting", "statistics", "" ]
For example, <http://developer.apple.com/cocoa/pyobjc.html> is still for OS X 10.4 Tiger, not 10.5 Leopard.. And that's the official Apple documentation for it.. The official PyObjC page is equally bad, <http://pyobjc.sourceforge.net/> It's so bad it's baffling.. I'm considering learning Ruby primarily because the Ru...
I agree that that tutorial is flawed, throwing random, unexplained code right in front of your eyes. It introduces concepts such as the autorelease pool and user defaults without explaining why you would want them ("Autorelease pool for memory management" is hardly an explanation). That said… > basically all I want t...
The main reason for the lack of documentation for PyObjC is that there is one developer (me), and as most developers I don't particularly like writing documentation. Because PyObjC is a side project for me I tend to focus on working on features and bugfixes, because that's more interesting for me. The best way to impr...
Why is the PyObjC documentation so bad?
[ "", "python", "macos", "cocoa", "pyobjc", "" ]
I am starting to work on a hobby project with a **Python** codebase and I would like to set up some form of continuous integration (i.e. running a battery of test-cases each time a check-in is made and sending nag e-mails to responsible persons when the tests fail) similar to **CruiseControl** or **TeamCity**. I reali...
We run [Buildbot - Trac](http://buildbot.net/trac) at work. I haven't used it too much since my codebase isn't part of the release cycle yet. But we run the tests on different environments (OSX/Linux/Win) and it sends emails — and it's written in Python.
One possibility is Hudson. It's written in Java, but there's integration with Python projects: > [Hudson embraces Python](http://redsolo.blogspot.com/2007/11/hudson-embraces-python.html) I've never tried it myself, however. (**Update**, Sept. 2011: After a trademark dispute Hudson has been renamed to [Jenkins](http:...
Continuous Integration System for a Python Codebase
[ "", "python", "continuous-integration", "extreme-programming", "" ]
I have a directory with PDF files that I need to create an index for. It is a PHP page with a list of links: ``` <A HREF="path to file">filename</A> ``` The filenames can be complicated: ``` LVD 2-1133 - Ändring av dumpningslina (1984-11-20).pdf ``` What is the correct way to link to this file on a Linux/Apache ser...
You can use [rawurlencode()](http://php.net/manual/en/function.rawurlencode.php) to convert a string according to the RFC 1738 spec. This function replaces all non-alphanumeric characters by their associated code. The difference with [urlencode()](http://php.net/manual/en/function.urlencode.php) is that spaces are enc...
The urlencode() function will convert spaces into plus signs (+), so it won't work. The rawurlencode does the trick. Thanks. Be sure to convert each part of the path separately, otherwise path/file will be converted into path%2Ffile. (which was what I missed)
How to convert complex filename into HTML link?
[ "", "php", "html", "" ]
After the suggestion to use a library for [my ajax needs](https://stackoverflow.com/questions/34486/what-more-is-needed-for-ajax-than-this-function) I am going to use one, the problem is that there are so many and I've no idea how to even begin telling them apart. Thus, can anybody A) Give a rundown of the differen...
To answer B: [**Comparison of JavaScript frameworks**](http://en.wikipedia.org/wiki/Comparison_of_JavaScript_frameworks) --- **EDIT:** Although everyone and their mom is apparently riding the [**jQuery**](http://jquery.com/) bandwagon (I use [**MochiKit**](http://www.mochikit.com)), there are many libraries which pr...
jQuery, easy to learn, easy to use, small footprint, active plugin developer community. Can't go wrong with jQuery.
Comparison of Javascript libraries
[ "", "javascript", "comparison", "" ]
I have a Java application that launches another java application. The launcher has a watchdog timer and receives periodic notifications from the second VM. However, if no notifications are received then the second virtual machine should be killed and the launcher will perform some additional clean-up activities. The q...
I may be missing something but can't you call the [`destroy()`](http://java.sun.com/j2se/1.5.0/docs/api/java/lang/Process.html#destroy()) method on the [`Process`](http://java.sun.com/j2se/1.5.0/docs/api/java/lang/Process.html) object returned by [`Runtime.exec()`](http://java.sun.com/j2se/1.5.0/docs/api/java/lang/Runt...
You can use [java.lang.Process](http://java.sun.com/javase/6/docs/api/java/lang/Process.html) to do what you want. Once you have created the nested process and have a reference to the Process instance, you can get references to its standard out and err streams. You can periodically monitor those, and call .destroy() if...
Is it possible to kill a Java Virtual Machine from another Virtual Machine?
[ "", "java", "process-management", "" ]
Let's say I had a program in C# that did something computationally expensive, like encoding a list of WAV files into MP3s. Ordinarily I would encode the files one at a time, but let's say I wanted the program to figure out how many CPU cores I had and spin up an encoding thread on each core. So, when I run the program ...
Don't bother doing that. Instead use the [Thread Pool](http://msdn.microsoft.com/en-us/library/system.threading.threadpool.aspx). The thread pool is a mechanism (actually a class) of the framework that you can query for a new thread. When you ask for a new thread it will either give you a new one or enqueue the work ...
It is not necessarily as simple as using the thread pool. By default, the thread pool allocates multiple threads for each CPU. Since every thread which gets involved in the work you are doing has a cost (task switching overhead, use of the CPU's very limited L1, L2 and maybe L3 cache, etc...), the optimal number of th...
How do I spawn threads on different CPU cores?
[ "", "c#", ".net", "windows", "multithreading", "" ]
I'm just wondering if it exists better solution for this. ``` BitConverter.ToInt32(sample_guid.ToByteArray(), 0) ```
I don't think there's a better solution than this.
I don't know if it's better, but it is easier to read: Int32.Parse(sample\_guid.ToString().SubString(0,1)); I'm a junior developer, admittedly, but the above reads easier to me than a byte conversion, and on a modern computer it would run indistinguishably quickly.
What is the best method of getting Int32 from first four bytes of GUID?
[ "", "c#", ".net", "guid", "" ]
I'm trying to use Groovy to create an interactive scripting / macro mode for my application. The application is OSGi and much of the information the scripts may need is not know up front. I figured I could use GroovyShell and call eval() multiple times continually appending to the namespace as OSGi bundles are loaded. ...
Ended up injecting code before each script compilation. End goal is that the user written script has a domain-specific-language available for use.
I am not sure about what you mean about declared classes not existing between evals, the following two scripts work as expected when evaled one after another: ``` class C {{println 'hi'}} new C() ``` ... ``` new C() ``` However methods become bound to the class that declared them, and GroovyShell creates a new clas...
How can I convince GroovyShell to maintain state over eval() calls?
[ "", "java", "groovy", "scripting", "groovyshell", "" ]
How do you create a database from an Entity Data Model. So I created a database using the EDM Designer in VisualStudio 2008, and now I want to generate the SQL Server Schema to create storage in SQL Server.
From what I understand you are not just supposed to use EDM as a "pretty" database designer, in fact EDM does not depend on a specific storage layer. It tries to abstract that part for the developer. There are design schemas (CSDL) and storage schemas (SSDL). Anyway, don't mean to lecture you. ;) There is [EDM Generat...
The Feature "Generate Database Schema from Model" is scheduled for a future release of Entity Framework. V1 does'nt support schema generatiorn based on EF models.
How do you create a database from an EDM?
[ "", "sql", "entity-framework", "ado.net", "" ]
Sometimes I have to work on code that moves the computer clock forward. In this case some .cpp or .h files get their latest modification date set to the future time. Later on, when my clock is fixed, and I compile my sources, system rebuilds most of the project because some of the latest modification dates are in the ...
If this was my problem, I'd look for ways to avoid mucking with the system time. Isolating the code under unit tests, or a virtual machine, or something. However, because I love [PowerShell](https://stackoverflow.com/questions/52487/the-most-amazing-pieces-of-software-in-the-world#53414): ``` Get-ChildItem -r . | ...
I would recommend using a virtual machine where you can mess with the clock to your heart's content and it won't affect your development machine. Two free ones are [Virtual PC](http://www.microsoft.com/Windows/products/winfamily/virtualpc/default.mspx) from Microsoft and [VirtualBox](http://www.virtualbox.org/) from Su...
Resetting detection of source file changes
[ "", "c++", "visual-studio", "svn", "time", "timezone", "" ]
I want to move various parts of my app into simple scripts, to allow people that do not have a strong knowledge of c++ to be able to edit and implement various features. Because it's a real time app, I need to have some kind of multitasking for these scripts. Ideally I want it so that the c++ app calls a script functi...
You can use either Lua or Python. Lua is more "lightweight" than python. It's got a smaller memory footprint than python does and in our experience was easier to integrate (people's mileage on this point might vary). It can support a bunch of scripts running simultaneously. Lua, at least, supports stopping/starting thr...
I can highly recommend that you take a look at [Luabind](http://sourceforge.net/projects/luabind/). It makes it very simple to integrate Lua in your C++ code and vice versa. It is also possible to expose whole C++ classes to be used in Lua.
Implementing scripts in c++ app
[ "", "c++", "scripting", "" ]
My understanding of Hibernate is that as objects are loaded from the DB they are added to the Session. At various points, depending on your configuration, the session is flushed. At this point, modified objects are written to the database. How does Hibernate decide which objects are 'dirty' and need to be written? Do...
Hibernate does/can use bytecode generation (CGLIB) so that it knows a field is dirty as soon as you call the setter (or even assign to the field afaict). This immediately marks that field/object as dirty, but doesn't reduce the number of objects that need to be dirty-checked during flush. All it does is impact the imp...
Hibernate takes a snapshot of the state of each object that gets loaded into the Session. On flush, each object in the Session is compared with its corresponding snapshot to determine which ones are dirty. SQL statements are issued as required, and the snapshots are updated to reflect the state of the (now clean) Sessi...
When Hibernate flushes a Session, how does it decide which objects in the session are dirty?
[ "", "java", "hibernate", "session", "orm", "flush", "" ]
Why is the following C# code not allowed: ``` public abstract class BaseClass { public abstract int Bar { get;} } public class ConcreteClass : BaseClass { public override int Bar { get { return 0; } set {} } } ``` > CS0546 'ConcreteClass.Bar.set': cannot override because 'BaseClass.Ba...
Because the writer of Baseclass has explicitly declared that Bar has to be a read-only property. It doesn't make sense for derivations to break this contract and make it read-write. I'm with Microsoft on this one. Let's say I'm a new programmer who has been told to code against the Baseclass derivation. i write some...
I think the main reason is simply that the syntax is too explicit for this to work any other way. This code: ``` public override int MyProperty { get { ... } set { ... } } ``` is quite explicit that both the `get` and the `set` are overrides. There is no `set` in the base class, so the compiler complains. Just like y...
Why is it impossible to override a getter-only property and add a setter?
[ "", "c#", ".net", "properties", "getter-setter", "" ]
Inspired by the MVC storefront the latest project I'm working on is using extension methods on IQueryable to filter results. I have this interface; ``` IPrimaryKey { int ID { get; } } ``` and I have this extension method ``` public static IPrimaryKey GetByID(this IQueryable<IPrimaryKey> source, int id) { retu...
It works, when done right. cfeduke's solution works. However, you don't have to make the `IPrimaryKey` interface generic, in fact, you don't have to change your original definition at all: ``` public static IPrimaryKey GetByID<T>(this IQueryable<T> source, int id) where T : IPrimaryKey { return source(obj => obj.I...
Edit: [Konrad](https://stackoverflow.com/questions/82442/extension-methods-not-working-for-an-interface#85503)'s solution is better because its far simpler. The below solution works but is only required in situations similar to ObjectDataSource where a method of a class is retrieved through reflection without walking u...
Extension Methods not working for an interface
[ "", "c#", ".net", "extension-methods", "" ]
I am writing an immutable DOM tree in Java, to simplify access from multiple threads.\* However, it does need to support inserts and updates as fast as possible. And since it is immutable, if I make a change to a node on the N'th level of the tree, I need to allocate at least N new nodes in order to return the new tre...
These days, object creation is pretty dang fast, and the concept of object pooling is kind of obsolete (at least in general; connection pooling is of course still valid). Avoid premature optimization. Create your nodes when you need them when doing your copies, and then see if that becomes prohibitively slow. If so, t...
I hate to give a non-answer, but I think the only definitive way to answer a performance question like this might be for you to code both approaches, benchmark the two, and compare the results.
Java object allocation overhead
[ "", "java", "xml", "dom", "concurrency", "" ]
The [demos](http://dev.jquery.com/view/trunk/ui/demos/functional/#ui.dialog) for the jquery ui dialog all use the "flora" theme. I wanted a customized theme, so I used the themeroller to generate a css file. When I used it, everything seemed to be working fine, but later I found that I can't control any input element c...
I think it is because you have the classes different. `<div id="SERVICE03_DLG" class="flora">` (flora) `<div id="SERVICE03_DLG" class="ui-dialog">` (custom) Even with the flora theme, you would still use the ui-dialog class to define it as a dialog. I've done modals before and I've never even defined a class in t...
After playing with this in Firebug, if you add a z-index attribute greater than 1004 to your default div, id of "SERVICE03\_DLG", then it will work. I'd give it something extremely high, like 5000, just to be sure. I'm not sure what it is in the themeroller CSS that causes this. They've probably changed or neglected t...
A issue with the jquery dialog when using the themeroller css
[ "", "javascript", "jquery", "user-interface", "dialog", "" ]
C# doesn't require you to specify a generic type parameter if the compiler can infer it, for instance: ``` List<int> myInts = new List<int> {0,1,1, 2,3,5,8,13,21,34,55,89,144,233,377, 610,987,1597,2584,4181,6765}; //this statement is clunky List<string> myStrings = myInts. Select<int,string>( i => i.ToStr...
Actually, your question isn't bad. I've been toying with a generic programming language for last few years and although I've never come around to actually develop it (and probably never will), I've thought a lot about generic type inference and one of my top priorities has always been to allow the construction of class...
> Why doesn't C# support this class level generic type inference? Because they're generally ambiguous. By contrast, type inference is trivial for function calls (if all types appear in arguments). But in the case of constructor calls (glorified functions, for the sake of discussion), the compiler has to resolve multip...
Why doesn't C# support implied generic types on class constructors?
[ "", "c#", ".net", "generics", "" ]
I'm writing a CMS application in PHP and one of the requirements is that it must be able to interface with the customer's Exchange server. I've written up this functionality a few times before and have always used [WebDAV](http://en.wikipedia.org/wiki/WebDAV) to do it, but now I'm leaning away from that. I will be run...
**Update as of 2020:** Over a decade since this question and things have moved on. Microsft now has a [Rest API](https://learn.microsoft.com/en-us/exchange/client-developer/exchange-web-services/office-365-rest-apis-for-mail-calendars-and-contacts) that will allow you to easily access this data. --- **Original Answ...
Is your customer using Exchange 2007? If so, I'd have a look at [Exchange Web Services](http://msdn.microsoft.com/en-us/library/bb204119(EXCHG.80).aspx). If not, as hairy as it can be, I think WebDAV is your best bet. Personally I don't like using the Outlook.Application COM object route, as its security prompts ("An ...
Best way to access Exchange using PHP?
[ "", "php", "windows", "exchange-server", "webdav", "mapi", "" ]
> **Possible Duplicate:** > [.NET - What’s the best way to implement a “catch all exceptions handler”](https://stackoverflow.com/questions/219594/net-whats-the-best-way-to-implement-a-catch-all-exceptions-handler) I have a .NET console app app that is crashing and displaying a message to the user. All of my code is ...
Contrary to what some others have posted, there's nothing wrong catching all exceptions. The important thing is to handle them all appropriately. If you have a stack overflow or out of memory condition, the app should shut down for them. Also, keep in mind that OOM conditions can prevent your exception handler from run...
You can add an event handler to AppDomain.UnhandledException event, and it'll be called when a exception is thrown and not caught.
How to catch ALL exceptions/crashes in a .NET app
[ "", "c#", ".net", "exception", "" ]
I'm needing to access Excel workbooks from .Net. I know all about the different ways of doing it (I've written them up in a [blog post](http://blog.functionalfun.net/2008/06/reading-and-writing-excel-files-with.html "Reading and Writing Excel files in .Net")), and I know that using a native .Net component is going to b...
I haven't done any proper benchmarks, but I tried out several other components,and found that [SpreadsheetGear](http://spreadsheetgear.com/) was considerably faster than XlsIO which I was using before. I've written up some of my findings in this [post](http://blog.functionalfun.net/2008/08/which-net-excel-io-component-...
Can't help you with your original question, but are you aware that you can access Excel files using an OleDbConnection, and therefore treat it as a database? You can then read worksheets into a DataTable, perform all the changes you need to the data in your application, and then save it all back to the file using an Ol...
Does anyone have .Net Excel IO component benchmarks?
[ "", "c#", "excel", "components", "" ]
What could be the problem with reversing the array of DOM objects as in the following code: ``` var imagesArr = new Array(); imagesArr = document.getElementById("myDivHolderId").getElementsByTagName("img"); imagesArr.reverse(); ``` In Firefox 3, when I call the `reverse()` method the script stops executing and shows ...
Because getElementsByTag name actually returns a NodeList structure. It has similar array like indexing properties for syntactic convenience, but it is *not* an array. For example, the set of entries is actually constantly being dynamically updated - if you add a new img tag under myDivHolderId, it will automatically a...
`getElementsByTag()` returns a NodeList instead of an Array. You can convert a NodeList to an Array but note that the array will be another object, so reversing it will not affect the DOM nodes position. ``` var listNodes = document.getElementById("myDivHolderId").getElementsByTagName("img"); var arrayNodes = Array.sl...
Javascript collection of DOM objects - why can't I reverse with Array.reverse()?
[ "", "javascript", "arrays", "" ]
In Java, what would the best way be to have a constantly listening port open, and still send upon receipt of a packet. I am not particularly savvy with network programming at the moment, so the tutorials I have found on the net aren't particularly helpful. Would it make sense to have the listening socket as a serverso...
If you can afford the threading, try this (keep in mind I've left out some details like exception handling and playing nice with threads). You may want to look into `SocketChannels` and/or NIO async sockets / selectors. This should get you started. ``` boolean finished = false; int port = 10000; ServerSocket server = ...
As for connecting to a Blackberry, this is problematic since in most cases the Blackberry won't have a public IP address and will instead be behind a WAP gateway or wireless provider access point server. RIM provides the Mobile Data Server (MDS) to get around this and provide "Push" data which uses ServerSocket semanti...
Sockets and Processes in Java
[ "", "java", "networking", "sockets", "blackberry", "" ]
[Interfaces](http://php.net/Interfaces) allow you to create code that defines the methods of classes that implement it. You cannot however add any code to those methods. [Abstract classes](http://php.net/Abstract) allow you to do the same thing, along with adding code to the method. Now if you can achieve the same go...
The entire point of interfaces is to give you the flexibility to have your class be forced to implement multiple interfaces, but still not allow multiple inheritance. The issues with inheriting from multiple classes are many and varied and the [wikipedia](http://en.wikipedia.org/wiki/Multiple_inheritance) page on it su...
The concept is useful all around in object oriented programming. To me I think of an interface as a contract. So long my class and your class agree on this method signature contract we can "interface". As for abstract classes those I see as more of base classes that stub out some methods and I need to fill in the detai...
What is the point of interfaces in PHP?
[ "", "php", "oop", "interface", "theory", "" ]
I'm developing an Excel 2007 add-in using Visual Studio Tools for Office (2008). I have one sheet with several ListObjects on it, which are being bound to datatables on startup. When they are bound, they autosize correctly. The problem comes when they are re-bound. I have a custom button on the ribbon bar which goes b...
If anyone else is having this problem, I have found the cause of this exception. ListObjects will automatically re-size on binding, as long as they do not affect any other objects on the sheet. Keep in mind that ListObjects can only affect the Ranges which they wrap around. In my case, the list object which was above ...
I've got a similar issue with refreshign multiple listobjects. We are setting each listObject.DataSource = null, then rebinding starting at the bottom listobject and working our way up instead of the top down.
.NET - Excel ListObject autosizing on databind
[ "", "c#", ".net", "excel", "data-binding", "vsto", "" ]
Are there any automatic methods for trimming a path string in .NET? For example: ``` C:\Documents and Settings\nick\My Documents\Tests\demo data\demo data.emx ``` becomes ``` C:\Documents...\demo data.emx ``` It would be particularly cool if this were built into the Label class, and I seem to recall it is--can't f...
Use **TextRenderer.DrawText** with **TextFormatFlags.PathEllipsis** flag ``` void label_Paint(object sender, PaintEventArgs e) { Label label = (Label)sender; TextRenderer.DrawText(e.Graphics, label.Text, label.Font, label.ClientRectangle, label.ForeColor, TextFormatFlags.PathEllipsis); } ``` > Your code is 95% th...
@ [lubos hasko](https://stackoverflow.com/questions/20467?sort=votes#20495) Your code is 95% there. The only problem is that the trimmed text is drawn on top of the text which is already on the label. This is easily solved: ``` Label label = (Label)sender; using (SolidBrush b = new SolidBrush(label.BackColor))...
Path Display in Label
[ "", "c#", ".net", "winforms", "path", "" ]
I'm working with a SQL Server 2000 database that likely has a few dozen tables that are no longer accessed. I'd like to clear out the data that we no longer need to be maintaining, but I'm not sure how to identify which tables to remove. The database is shared by several different applications, so I can't be 100% conf...
MSSQL2000 won't give you that kind of information. But a way you can identify what tables ARE used (and then deduce which ones are not) is to use the SQL Profiler, to save all the queries that go to a certain database. Configure the profiler to record the results to a new table, and then check the queries saved there t...
Another suggestion for tracking tables that have been written to is to use [Red Gate SQL Log Rescue](http://www.red-gate.com/products/SQL_Log_Rescue/index.htm) (free). This tool dives into the log of the database and will show you all inserts, updates and deletes. The list is fully searchable, too. It doesn't meet you...
Strategy for identifying unused tables in SQL Server 2000?
[ "", "sql", "database", "sql-server-2000", "" ]
Can/Should I use a LIKE criteria as part of an INNER JOIN when building a stored procedure/query? I'm not sure I'm asking the right thing, so let me explain. I'm creating a procedure that is going to take a list of keywords to be searched for in a column that contains text. If I was sitting at the console, I'd execute...
Your first query will work but will require a full table scan because any index on that column will be ignored. You will also have to do some dynamic SQL to generate all your LIKE clauses. Try a full text search if your using SQL Server or check out one of the [Lucene](http://lucene.apache.org/java/docs/index.html) im...
Try this ``` select * from Table_1 a left join Table_2 b on b.type LIKE '%' + a.type + '%' ``` This practice is not ideal. Use with caution.
Use a LIKE clause in part of an INNER JOIN
[ "", "sql", "sql-server", "design-patterns", "" ]
I have a class that I want to use to store "properties" for another class. These properties simply have a name and a value. Ideally, what I would like is to be able to add *typed* properties, so that the "value" returned is always of the type that I want it to be. The type should always be a primitive. This class subc...
I am not sure whether I understood your intentions correctly, but let's see if this one helps. ``` public class TypedProperty<T> : Property where T : IConvertible { public T TypedValue { get { return (T)Convert.ChangeType(base.Value, typeof(T)); } set { base.Value = value.ToString();} } } `...
lubos hasko's method fails for nullables. The method below will work for nullables. I didn't come up with it, though. I found it via Google: <http://web.archive.org/web/20101214042641/http://dogaoztuzun.com/post/C-Generic-Type-Conversion.aspx> Credit to "Tuna Toksoz" Usage first: ``` TConverter.ChangeType<T>(StringVa...
Generic type conversion FROM string
[ "", "c#", "generics", "primitive", "type-safety", "" ]
I have a flex application that needs the ability to generate and execute JavaScript. When I say this, I mean I need to execute raw JavaScript that I create in my Flex application (not just an existing JavaScript method) I am currently doing this by exposing the following JavaScript method: ``` function doScript(js){ ...
There's no need for the JavaScript function, the first argument to `ExternalInterface` can be any JavaScript code, it doesn't have to be a function name (the documentation says so, but it is wrong). Try this: ``` ExternalInterface.call("alert('hello')"); ```
This isn't inherently dangerous, but the moment you pass any user-provided data into the function, it's ripe for a code injection exploit. That's worrisome, and something I'd avoid. I think a better approach would be to only expose the functionality you *need*, and nothing more.
Executing JavaScript from Flex: Is this javascript function dangerous?
[ "", "javascript", "apache-flex", "exploit", "" ]
I have a structure which I need to populate and write to disk (several actually). An example is: ``` byte-6 bit0 - original_or_copy bit1 - copyright bit2 - data_alignment_indicator bit3 - PES_priority bit4-bit5 - PES_scrambling control. bit6-bit7 - reserved ``` In C I might do something like the follow...
I'd probably knock together something using attributes, then a conversion class to convert suitably attributed structures to the bitfield primitives. Something like... ``` using System; namespace BitfieldTest { [global::System.AttributeUsage(AttributeTargets.Field, AllowMultiple = false)] sealed class Bitfiel...
By using an enum you can do this, but will look awkward. ``` [Flags] public enum PESHeaderFlags { IsCopy = 1, // implied that if not present, then it is an original IsCopyrighted = 2, IsDataAligned = 4, Priority = 8, ScramblingControlType1 = 0, ScramblingControlType2 = 16, ScramblingControl...
Bit fields in C#
[ "", "c#", "bit-fields", "" ]
I needed some simple string encryption, so I wrote the following code (with a great deal of "inspiration" from [here](http://www.codeproject.com/KB/security/DotNetCrypto.aspx)): ``` // create and initialize a crypto algorithm private static SymmetricAlgorithm getAlgorithm(string password) { SymmetricAl...
Although this have been already answered I think it would be a good idea to explain **why** it is to be expected. A padding scheme is usually applied because most cryptographic filters are not semantically secure and to prevent some forms of cryptoatacks. For example, usually in RSA the [OAEP](http://en.wikipedia.org/...
I experienced a similar "Padding is invalid and cannot be removed." exception, but in my case the key IV and padding were correct. It turned out that flushing the crypto stream is all that was missing. Like this: ``` MemoryStream msr3 = new MemoryStream(); CryptoStream encStream = new CryptoS...
Why does a bad password cause "Padding is invalid and cannot be removed"?
[ "", "c#", ".net", "exception", "encryption", "" ]
How can I present a control to the user that allows him/her to select a directory? There doesn't seem to be any native .net controls which do this?
The [FolderBrowserDialog class](http://msdn.microsoft.com/en-us/library/system.windows.forms.folderbrowserdialog.aspx) is the best option.
``` string folderPath = ""; FolderBrowserDialog folderBrowserDialog1 = new FolderBrowserDialog(); if (folderBrowserDialog1.ShowDialog() == DialogResult.OK) { folderPath = folderBrowserDialog1.SelectedPath ; } ```
Browse for a directory in C#
[ "", "c#", ".net", "directory", "" ]
I was checking out Intel's "whatif" site and their Transactional Memory compiler (each thread has to make atomic commits or rollback the system's memory, like a Database would). It seems like a promising way to replace locks and mutexes but I can't find many testimonials. Does anyone here have any input?
I have not used Intel's compiler, however, Herb Sutter had some interesting comments on it... From [Sutter Speaks: The Future of Concurrency](http://www.devx.com/go-parallel/Article/37839) **Do you see a lot of interest in and usage of transactional memory, or is the concept too difficult for most developers to grasp...
Dr. Dobb's had an article on the concept last year: Transactional Programming by Calum Grant -- <http://www.ddj.com/cpp/202802978> It includes some examples, comparisons, and conclusions using his example library.
Has anyone tried transactional memory for C++?
[ "", "c++", "multithreading", "locking", "intel", "transactional-memory", "" ]
Let's say I want a web page that contains a Flash applet and I'd like to drag and drop some objects from or to the rest of the web page, is this at all possible? Bonus if you know a website somewhere that does that!
This one intrigued me. I know jessegavin posted some code while I went to figure this out, but this one is tested. I have a super-simple working example that lets you drag to and from flash. It's pretty messy as I threw it together during my lunch break. Here's the [demo](http://enobrev.github.io/DragSWF/) And the [s...
**DISCLAIMER** I haven't tested this code at all, but the idea should work. Also, this only handles the dragging ***to*** a flash movie. Here's some Actionscript 3.0 code which makes use of the [ExternalInterface](http://livedocs.adobe.com/flash/9.0/ActionScriptLangRefV3/flash/external/ExternalInterface.html) class. ...
Is it possible to drag and drop from/to outside a Flash applet with JavaScript?
[ "", "javascript", "flash", "drag-and-drop", "" ]
I have some classes layed out like this ``` class A { public virtual void Render() { } } class B : A { public override void Render() { // Prepare the object for rendering SpecialRender(); // Do some cleanup } protected virtual void SpecialRender() { } } clas...
You can seal individual methods to prevent them from being overridable: ``` public sealed override void Render() { // Prepare the object for rendering SpecialRender(); // Do some cleanup } ```
Yes, you can use the sealed keyword in the B class's implementation of Render: ``` class B : A { public sealed override void Render() { // Prepare the object for rendering SpecialRender(); // Do some cleanup } protected virtual void SpecialRender() { } } ```
Can I prevent an inherited virtual method from being overridden in subclasses?
[ "", "c#", "polymorphism", "" ]
I believe the application has some parts that target .NET, and some that don't. I'm particularly interested in looking at the resource files, if there are any.
To add to aku's excellent answer, for English speakers, IDA Pro is available at <http://www.hex-rays.com/>.
If you want to disassemble native x86/64 app use [IDA](http://www.idapro.ru), .NET exe/dll can be disassembled using Reflector. There are [tons](http://www.google.ru/search?complete=1&hl=en&newwindow=1&client=firefox-a&rls=org.mozilla%3Aen-US%3Aofficial&hs=v1M&q=extract+resource+from+exe+file&btnG=%D0%9F%D0%BE%D0%B8%D1...
How do I disassemble a VC++ application?
[ "", "c++", "resources", "reverse-engineering", "" ]
I'd like to bind a configuration file to my executable. I'd like to do this by storing an MD5 hash of the file inside the executable. This should keep anyone but the executable from modifying the file. Essentially if someone modifies this file outside of the program the program should fail to load it again. EDIT: The...
A better solution is to store the MD5 in the configuration file. But instead of the MD5 being just of the configuration file, also include some secret "key" value, like a fixed guid, in the MD5. ``` write(MD5(SecretKey + ConfigFileText)); ``` Then you simply remove that MD5 and rehash the file (including your secret ...
Out of pure curiosity, what's your reasoning for never wanting to load the file if it's been changed? Why not just keep all of the configuration information compiled in the executable? Why bother with an external file at all? ***Edit*** I just read your edit about this being a credit card info program. That poses a ...
How do I store information in my executable in .Net
[ "", "c#", ".net", "" ]
Does anyone use [Phing](http://phing.info/trac/) to deploy PHP applications, and if so how do you use it? We currently have a hand-written "setup" script that we run whenever we deploy a new instance of our project. We just check out from SVN and run it. It sets some basic configuration variables, installs or reloads t...
From Federico Cargnelutti's [blog post](http://phpimpact.wordpress.com/2007/06/30/phing-php-project-build-system-based-on-apache-ant/): > Features include file transformations (e.g. token > replacement, XSLT transformation, > Smarty template transformations), file > system operations, interactive build > support, SQL ...
The compelling answer for me is that phing understands PHP classpaths. Ant doesn't. I don't want to have an ant build.xml full of exec commands. I happen to be primarily a java programmer and still use phing. It's the best tool for the job.
Do you use Phing?
[ "", "php", "deployment", "build-process", "build-automation", "phing", "" ]
What I want to do is something like this: I have enums with combined flagged values. ``` public static class EnumExtension { public static bool IsSet<T>( this T input, T matchTo ) where T:enum //the constraint I want that doesn't exist in C#3 { return (input & matchTo) != 0; } } ``` S...
**EDIT: This is now live in version 0.0.0.2 of UnconstrainedMelody.** (As requested on my [blog post about enum constraints](http://codeblog.jonskeet.uk/2009/09/10/generic-constraints-for-enums-and-delegates/). I've included the basic facts below for the sake of a standalone answer.) The best solution is to wait for ...
As of C# 7.3, there is now a built-in way to add enum constraints: ``` public class UsingEnum<T> where T : System.Enum { } ``` source: <https://learn.microsoft.com/en-us/dotnet/csharp/language-reference/keywords/where-generic-type-constraint>
Anyone know a good workaround for the lack of an enum generic constraint?
[ "", "c#", ".net", "enums", "flags", "" ]
I am developing a J2ME application that has a large amount of data to store on the device (in the region of 1MB but variable). I can't rely on the file system so I'm stuck the Record Management System (RMS), which allows multiple record stores but each have a limited size. My initial target platform, Blackberry, limits...
For anything past a few kilobytes you need to use either JSR 75 or a remote server. RMS records are extremely limited in size and speed, even in some higher end handsets. If you need to juggle 1MB of data in J2ME the only reliable, portable way is to store it on the network. The HttpConnection class and the GET and POS...
RMS performance and implementation varies wildly between devices, so if platform portability is a problem, you may find that your code works well on some devices and not others. RMS is designed to store small amounts of data (High score tables, or whatever) not large amounts. You might find that some platforms are fas...
Best practice for storing large amounts of data with J2ME
[ "", "java", "java-me", "rms", "" ]
I have a database table and one of the fields (not the primary key) is having a unique index on it. Now I want to swap values under this column for two rows. How could this be done? Two hacks I know are: 1. Delete both rows and re-insert them. 2. Update rows with some other value and swap and then update to actual ...
I think you should go for solution 2. There is no 'swap' function in any SQL variant I know of. If you need to do this regularly, I suggest solution 1, depending on how other parts of the software are using this data. You can have locking issues if you're not careful. But in short: there is no other solution than the...
The magic word is **DEFERRABLE** here: ``` DROP TABLE ztable CASCADE; CREATE TABLE ztable ( id integer NOT NULL PRIMARY KEY , payload varchar ); INSERT INTO ztable(id,payload) VALUES (1,'one' ), (2,'two' ), (3,'three' ); SELECT * FROM ztable; -- This works, because there is no constraint UPDATE ztabl...
Swap unique indexed column values in database
[ "", "sql", "database", "" ]
I would like the version property of my application to be incremented for each build but I'm not sure on how to enable this functionality in Visual Studio (2005/2008). I have tried to specify the AssemblyVersion as 1.0.\* but it doesn't get me exactly what I want. I'm also using a settings file and in earlier attempts...
With the "Built in" stuff, you can't, as using 1.0.\* or 1.0.0.\* will replace the revision and build numbers with a coded date/timestamp, which is usually also a good way. For more info, see the [Assembly Linker](http://msdn2.microsoft.com/en-us/library/c405shex(vs.80).aspx) Documentation in the /v tag. As for autom...
VS.NET defaults the Assembly version to 1.0.\* and uses the following logic when auto-incrementing: it sets the build part to the number of days since January 1st, 2000, and sets the revision part to the number of seconds since midnight, local time, divided by two. See this [MSDN article](http://msdn.microsoft.com/en-u...
Automatically update version number
[ "", "c#", "visual-studio", "versioning", "" ]
What did I do wrong? Here is an excerpt from my code: ``` public void createPartControl(Composite parent) { parent.setLayout(new FillLayout()); ScrolledComposite scrollBox = new ScrolledComposite(parent, SWT.V_SCROLL); scrollBox.setExpandHorizontal(true); mParent = new Composite(scrollBox, SWT.NONE); scroll...
This is a common hurdle when using `ScrolledComposite`. When it gets so small that the scroll bar must be shown, the client control has to shrink horizontally to make room for the scroll bar. This has the side effect of making some labels wrap lines, which moved the following controls farther down, which increased the ...
If I am not mistaken you need to swap the ``` mParent.layout(); ``` and ``` mParent.setSize(mParent.computeSize(SWT.DEFAULT, SWT.DEFAULT, true)); ``` so that you have: ``` public void createPartControl(Composite parent) { parent.setLayout(new FillLayout()); ScrolledComposite scrollBox = new ScrolledComposite(p...
Prevent SWT ScrolledComposite from eating part of it's children
[ "", "java", "eclipse", "swt", "rcp", "" ]
I have a List of Foo. Foo has a string property named Bar. I'd like to use **LINQ** to get a string[] of **distinct** values for Foo.Bar in List of Foo. How can I do this?
I'd go lambdas... wayyy nicer ``` var bars = Foos.Select(f => f.Bar).Distinct().ToArray(); ``` works the same as what @lassevk posted. I'd also add that you might want to keep from converting to an array until the last minute. LINQ does some optimizations behind the scenes, queries stay in its query form until expl...
This should work if you want to use the fluent pattern: ``` string[] arrayStrings = fooList.Select(a => a.Bar).Distinct().ToArray(); ```
How to get an array of distinct property values from in memory lists?
[ "", "c#", ".net", "performance", "linq", "filtering", "" ]
What is the fastest, yet secure way to encrypt passwords (in PHP preferably), and for whichever method you choose, is it portable? In other words, if I later migrate my website to a different server, will my passwords continue to work? The method I am using now, as I was told, is dependent on the exact versions of th...
If you are choosing an encryption method for your login system then speed is not your friend, Jeff had a to-and-frow with Thomas Ptacek about passwords and the [conclusion](http://chargen.matasano.com/chargen/2007/9/7/enough-with-the-rainbow-tables-what-you-need-to-know-about-s.html) was that you should use the slowest...
I'm with Peter. Developer don't seem to understand passwords. We all pick (and I'm guilty of this too) MD5 or SHA1 because they are fast. Thinking about it ('cuz someone recently pointed it out to me) that doesn't make any sense. We should be picking a hashing algorithm that's stupid slow. I mean, on the scale of thing...
Encrypting Passwords
[ "", "php", "encryption", "passwords", "" ]
What is the best method to parse multiple, discrete, custom XML documents with Java?
I would use [Stax](http://jcp.org/en/jsr/detail?id=173) to parse XML, it's fast and easy to use. I've been using it on my last project to parse XML files up to 24MB. There's a nice introduction on [java.net](http://today.java.net/pub/a/today/2006/07/20/introduction-to-stax.html), which tells you everything you need to ...
Basically, you have two main XML parsing methods in Java : * [SAX](http://en.wikipedia.org/wiki/Simple_API_for_XML), where you use an [handler](http://download.oracle.com/javase/6/docs/api/org/xml/sax/helpers/DefaultHandler.html) to only grab what you want in your XML and ditch the rest * [DOM](http://en.wikipedia.org...
Best method to parse various custom XML documents in Java
[ "", "java", "xml", "" ]
I have a template class that I serialize (call it C), for which I want to specify a version for boost serialization. As BOOST\_CLASS\_VERSION does not work for template classes. I tried this: ``` namespace boost { namespace serialization { template< typename T, typename U > struct version< C<T,U> > { ...
``` #include <boost/serialization/version.hpp> ``` :-)
I was able to properly use the macro BOOST\_CLASS\_VERSION until I encapsulated it inside a namespace. Compilation errors returned were: ``` error C2988: unrecognizable template declaration/definition error C2143: syntax error: missing ';' before '<' error C2913: explicit specialization; 'Romer::RDS::Settings::boost::...
Boost serialization: specifying a template class version
[ "", "c++", "boost-serialization", "" ]
I'm part of a team that develops a pretty big Swing Java Applet. Most of our code are legacy and there are tons of singleton references. We've bunched all of them to a single "Application Context" singleton. What we now need is to create some way to separate the shared context (shared across all applets currently showi...
Singletons are evil, what do you expect? ;) Perhaps the most comprehensive approach would be to load the bulk of the applet in a different class loader (use java.net.URLClassLoader.newInstance). Then use a WeakHashMap to associate class loader with an applet. If you could split most of the code into a common class loa...
If I understand you correctly, the idea is to get a different "singleton" object for each caller object or "context". One thing you can do is to create a thread-local global variable where you write the ID of the current context. (This can be done with AOP.) Then in the singleton getter, the context ID is fetched from ...
How can I identify in which Java Applet context running without passing an ID?
[ "", "java", "swing", "applet", "" ]
I am looking for a very fast way to filter down a collection in C#. I am currently using generic `List<object>` collections, but am open to using other structures if they perform better. Currently, I am just creating a new `List<object>` and looping thru the original list. If the filtering criteria matches, I put a co...
If you're using C# 3.0 you can use linq, which is way better and way more elegant: ``` List<int> myList = GetListOfIntsFromSomewhere(); // This will filter ints that are not > 7 out of the list; Where returns an // IEnumerable<T>, so call ToList to convert back to a List<T>. List<int> filteredList = myList.Where(x =>...
Here is a code block / example of some list filtering using three different methods that I put together to show Lambdas and LINQ based list filtering. ``` #region List Filtering static void Main(string[] args) { ListFiltering(); Console.ReadLine(); } private static void ListFiltering() { var PersonList =...
Filtering collections in C#
[ "", "c#", "collections", "filtering", "" ]
I'm fairly new to ASP.NET and trying to learn how things are done. I come from a C# background so the code-behind portion is easy, but thinking like a web developer is unfamiliar. I have an aspx page that contains a grid of checkboxes. I have a button that is coded via a Button\_Click event to collect a list of which ...
All a usercontrol(.ascx) file is is a set of controls that you have grouped together to provide some reusable functionality. The controls defined in it are still added to the page's control collection (.aspx) durring the page lifecylce. The ModalPopupExtender uses javascript and dhtml to show and hide the controls in t...
After some research following DancesWithBamboo's answer, I figured out how to make it work. An example reference to my ascx page within my aspx page: ``` <uc1:ChildPage ID="MyModalPage" runat="server" /> ``` The aspx code-behind to grab and open the ModalPopupExtender (named modalPopup) would look like this: ``` A...
How can I pass data from an aspx page to an ascx modal popup?
[ "", "c#", "asp.net", "asp.net-ajax", "" ]
I've been trying to use SQLite with the PDO wrapper in PHP with mixed success. I can read from the database fine, but none of my updates are being committed to the database when I view the page in the browser. Curiously, running the script from my shell does update the database. I suspected file permissions as the culp...
Kyle, in order for PDO/Sqlite to work you need write permission to directory where your database resides. Also, I see you perform multiple selects in loop. This may be ok if you are building something small and not heavy loaded. Otherwise I'd suggest building single query that returns multiple rows and process them in...
I found the answer on the [PHP manual](http://www.php.net/manual/en/ref.pdo-sqlite.php#57356) "The folder that houses the database file must be writeable."
SQLite/PHP read-only?
[ "", "php", "sqlite", "permissions", "pdo", "" ]
I am working with both [amq.js](http://activemq.apache.org/ajax.html) (ActiveMQ) and [Google Maps](http://code.google.com/apis/maps/documentation/reference.html). I load my scripts in this order ``` <head> <meta http-equiv="content-type" content="text/html;charset=UTF-8" /> <title>AMQ & Maps Demo</title> ...
> **Is there a way to make sure both scripts load before I use them in my application.js?** JavaScript files should load sequentially *and block* so unless the scripts you are depending on are doing something unusual all you should need to do is load application.js after the other files. [Non-blocking JavaScript Down...
cross-domain scripts are loaded after scripts of site itself, this is why you get errors. interestingly, nobody knows this here.
JavaScript Load Order
[ "", "javascript", "google-maps", "" ]
I need advice on how to have my C# console application display text to the user through the standard output while still being able access it later on. The actual feature I would like to implement is to dump the entire output buffer to a text file at the end of program execution. The workaround I use while I don't find...
The perfect solution for this is to use [log4net](http://logging.apache.org/log4net/) with a console appender and a file appender. There are many other appenders available as well. It also allows you to turn the different appenders off and on at runtime.
I don't think there's anything wrong with your approach. If you wanted reusable code, consider implementing a class called `MultiWriter` or somesuch that takes as input two (or N?) `TextWriter` streams and distributes all writs, flushes, etc. to those streams. Then you can do this file/console thing, but just as easil...
How to save the output of a console application
[ "", "c#", ".net", "console", "stdout", "" ]
I'm working on a web service at the moment and there is the potential that the returned results could be quite large ( > 5mb). It's perfectly valid for this set of data to be this large and the web service can be called either sync or async, but I'm wondering what people's thoughts are on the following: 1. If the con...
I have seen all three approaches, **paged**, **store and retrieve**, and **massive push**. I think the solution to your problem depends to some extent on why your result set is so large and how it is generated. Do your results grow over time, are they calculated all at once and then pushed, do you want to stream them ...
There's no hard law against 5 Mb as a result set size. Over 400 Mb can be [hard to send](http://msdn.microsoft.com/en-us/library/aa528822.aspx). You'll automatically get async handlers (since you're using .net) > implement some sort of "paging" where > the resultset is generated and stored > on the server and the cli...
Returning Large Results Via a Webservice
[ "", "c#", ".net", "web-services", "" ]
I've been raised to believe that if multiple threads can access a variable, then all reads from and writes to that variable must be protected by synchronization code, such as a "lock" statement, because the processor might switch to another thread halfway through a write. However, I was looking through System.Web.Secu...
For the definitive answer go to the spec. :) Partition I, Section 12.6.6 of the CLI spec states: "A conforming CLI shall guarantee that read and write access to properly aligned memory locations no larger than the native word size is atomic when all the write accesses to a location are the same size." So that confirm...
This is a (bad) form of the double check locking pattern which is **not** thread safe in C#! There is one big problem in this code: s\_Initialized is not volatile. That means that writes in the initialization code can move after s\_Initialized is set to true and other threads can see uninitialized code even if s\_Ini...
Is accessing a variable in C# an atomic operation?
[ "", "c#", "multithreading", "" ]
I have been working with a `string[]` array in C# that gets returned from a function call. I could possibly cast to a `Generic` collection, but I was wondering if there was a better way to do it, possibly by using a temp array. **What is the best way to remove duplicates from a C# array?**
You could possibly use a LINQ query to do this: ``` int[] s = { 1, 2, 3, 3, 4}; int[] q = s.Distinct().ToArray(); ```
Here is the [HashSet<string>](http://msdn.microsoft.com/en-us/library/bb359438.aspx) approach: ``` public static string[] RemoveDuplicates(string[] s) { HashSet<string> set = new HashSet<string>(s); string[] result = new string[set.Count]; set.CopyTo(result); return result; } ``` Unfortunately this so...
How do I remove duplicates from a C# array?
[ "", "c#", "arrays", "duplicates", "" ]
In C#, (and feel free to answer for other languages), what order does the runtime evaluate a logic statement? Example: ``` DataTable myDt = new DataTable(); if (myDt != null && myDt.Rows.Count > 0) { //do some stuff with myDt } ``` Which statement does the runtime evaluate first - ``` myDt != null ``` or: ```...
C# : Left to right, and processing stops if a non-match (evaluates to false) is found.
"C# : Left to right, and processing stops if a match (evaluates to true) is found." Zombie sheep is wrong. The question is about the && operator, not the || operator. In the case of && evaluation will stop if a FALSE is found. In the case of || evaluation stops if a TRUE is found.
C# logic order and compiler behavior
[ "", "c#", "language-agnostic", "compiler-construction", "logic", "" ]
I'm having trouble reading a "chunked" response when using a StreamReader to read the stream returned by GetResponseStream() of a HttpWebResponse: ``` // response is an HttpWebResponse StreamReader reader = new StreamReader(response.GetResponseStream()); string output = reader.ReadToEnd(); // throws exception... ``` ...
Haven't tried it this with a "chunked" response but would something like this work? ``` StringBuilder sb = new StringBuilder(); Byte[] buf = new byte[8192]; Stream resStream = response.GetResponseStream(); string tmpString = null; int count = 0; do { count = resStream.Read(buf, 0, buf.Length); if(count != 0)...
I am working on a similar problem. The .net HttpWebRequest and HttpWebRequest handle cookies and redirects automatically but they do not handle chunked content on the response body automatically. This is perhaps because chunked content may contain more than simple data (i.e.: chunk names, trailing headers). Simply re...
Reading "chunked" response with HttpWebResponse
[ "", "c#", "http", ".net-3.5", ".net-2.0", "" ]
Can someone show me how to implement a recursive lambda expression to traverse a tree structure in C#.
Ok, I found some free time finally. Here we go: ``` class TreeNode { public string Value { get; set;} public List<TreeNode> Nodes { get; set;} public TreeNode() { Nodes = new List<TreeNode>(); } } Action<TreeNode> traverse = null; traverse = (n) => { Console.WriteLine(n.Value); n.Node...
A proper solution, and indeed the idiomatic solution in many functional programming languages, would be the use of a [fixed-point combinator](https://en.wikipedia.org/wiki/Fixed-point_combinator). In a nutshell: a fixed-point combinator answers the question “how do I define an anonymous function to be recursive?”. But ...
Recursive lambda expression to traverse a tree in C#
[ "", "c#", "recursion", "lambda", "" ]
Does anyone know of a good method for editing PDFs in PHP? Preferably open-source/zero-license cost methods. :) I am thinking along the lines of opening a PDF file, replacing text in the PDF and then writing out the modified version of the PDF? On the front-end
If you are taking a 'fill in the blank' approach, you can precisely position text anywhere you want on the page. So it's relatively easy (if not a bit tedious) to add the missing text to the document. For example with Zend Framework: ``` <?php require_once 'Zend/Pdf.php'; $pdf = Zend_Pdf::load('blank.pdf'); $page = $...
There is a free and easy to use PDF class to create PDF documents. It's called [FPDF](http://www.fpdf.org/). In combination with FPDI (<http://www.setasign.de/products/pdf-php-solutions/fpdi>) it is even possible to edit PDF documents. The following code shows how to use FPDF and FPDI to fill an existing gift coupon wi...
Edit PDF in PHP?
[ "", "php", "pdf", "" ]
[This answer says](https://stackoverflow.com/questions/71955/when-choosing-an-orm-is-linq-to-sql-or-linq-to-entities-better-than-nhibernate#71974) that Linq is targeted at a slightly different group of developers than NHibernate, Castle, etc. Being rather new to C#, nevermind all the DB stuff surrounding it: * Are th...
When you say Castle I assume you mean Castle Active Record? The difference is NHibernate is an OR/M and is aimed at developers who want to focus on the domain rather than the database. With linq to sql, your database is pre-existing and you're relationships and some of programming will be driven by how your database i...
LINQ is just a set of new C# features: extension methods, lambda expressions, object initializers, anonymous types, etc. "LINQ to SQL" on the other hand is something you can compare other SQL wrappers.
Differences between NHibernate, Castle, Linq - Who are they aimed at?
[ "", "c#", "database", "linq", "nhibernate", "" ]
Does Python have a unit testing framework compatible with the standard xUnit style of test framework? If so, what is it, where is it, and is it any good?
Python has several testing frameworks, including `unittest`, `doctest`, and `nose`. The most xUnit-like is `unittest`, which is documented on Python.org. * [`unittest` documentation](https://docs.python.org/3/library/unittest.html) * [`doctest` documentation](https://docs.python.org/3/library/doctest.html)
I recommend [nose](https://nose.readthedocs.org/en/latest/). It is the most Pythonic of the unit test frameworks. The test runner runs both doctests and unittests, so you are free to use whatever style of test you like.
Unit tests in Python
[ "", "python", "unit-testing", "" ]
I'm parsing text from a file and storing it in a string. The problem is that some of the text in the original files contains `ASCII art` and whatnot that I would like to preserve. When I print out the string on the `HTML page`, even if it does have the same formatting and everything since it is in `HTML`, the spacing a...
use the <pre> tag (pre formatted), that will use a mono spaced font (for your art) and keep all the white space ``` <pre> text goes here and here and here and here Some out here ▄ ▄█▄ █▄ ▄ ▄█▀█▓ ▄▓▀▀█▀ ▀▀▀█▓▀▀ ▀▀ ▄█▀█▓▀▀▀▀▀▓▄▀██▀▀ ██ ██ ▀██▄▄ ▄█ ▀ ░▒ ░▒ ██ ██ ▄█...
the `<pre>` and `</pre>` might not be ideal in textarea etc.. When wanting to preserve new line - `\n` and `\n\r` use [nl2br](http://php.net/manual/en/function.nl2br.php) as mentioned by UnkwnTech and Brad Mace. When wanting to preserve spaces use [str\_replace](http://www.php.net/str_replace): `str_replace(' ', '&n...
How do I keep whitespace formatting using PHP/HTML?
[ "", "php", "html", "ascii", "" ]
By default tomcat will create a session cookie for the current domain. If you are on www.example.com, your cookie will be created for www.example.com (will only work on www.example.com). Whereas for example.com it will be created for .example.com (desired behaviour, will work on any subdomain of example.com as well as...
This is apparently supported via a configuration setting in 6.0.27 and onwards: > Configuration is done by editing > META-INF/context.xml > > <Context > sessionCookiePath="/something" > sessionCookieDomain=".domain.tld" /> <https://issues.apache.org/bugzilla/show_bug.cgi?id=48379>
I have just gone through all of this looking for a simple solution. I started looking at it from the tomcat perspective first. Tomcat does not give direct access to configuring the domain cookie for the session, and I definitely did not want to custom patch tomcat to fix that problem as shown in some other posts. Val...
Best way for allowing subdomain session cookies using Tomcat
[ "", "java", "tomcat", "session", "cookies", "subdomain", "" ]
Is there any list of blog engines, written in Django?
EDIT: Original link went dead so here's an updated link with extracts of the list sorted with the most recently updated source at the top. [Eleven Django blog engines you should know](http://blog.montylounge.com/2010/02/10/eleven-django-blog-engines-you-should-know/) by Monty Lounge Industries > * [Biblion](http://g...
James Bennett has an [interesting take](http://www.b-list.org/weblog/2007/nov/29/django-blog) on this question: > “where can I find a good Django-powered blogging application” is probably at the top of the frequently-asked questions list both on django-users and in the IRC; part of this is simply that, right now, ther...
Is there any list of blog engines, written in Django?
[ "", "python", "django", "" ]
I have an application that reads a CSV file with piles of data rows. I give the user a summary of the number of rows based on types of data, but I want to make sure that I don't read in too many rows of data and cause `OutOfMemoryError`s. Each row translates into an object. Is there a way to find out the size of that o...
You can use the [`java.lang.instrument` package](http://docs.oracle.com/javase/8/docs/api/java/lang/instrument/Instrumentation.html). Compile and put this class in a JAR: ``` import java.lang.instrument.Instrumentation; public class ObjectSizeFetcher { private static Instrumentation instrumentation; public ...
You should use [jol](http://openjdk.java.net/projects/code-tools/jol/), a tool developed as part of the OpenJDK project. > JOL (Java Object Layout) is the tiny toolbox to analyze object layout schemes in JVMs. These tools are using Unsafe, JVMTI, and Serviceability Agent (SA) heavily to decoder the actual object layou...
How to determine the size of an object in Java
[ "", "java", "memory", "" ]
I've been wondering, what is the point of clog? As near as I can tell, clog is the same as cerr but with buffering so it is more efficient. Usually stderr is the same as stdout, so clog is the same as cout. This seems pretty lame to me, so I figure I must be misunderstanding it. If I have log messages going out to the ...
> Is it possible to redirect clog, cerr, cout, stdin, stdout, and/or stderr? Yes. You want the [`rdbuf`](http://www.cplusplus.com/reference/iostream/ios/rdbuf.html) function. ``` ofstream ofs("logfile"); cout.rdbuf(ofs.rdbuf()); cout << "Goes to file." << endl; ``` > Is the only difference between clog and cerr the ...
If you're in a posix shell environment (I'm really thinking of bash), you can redirect any file descriptor to any other file descriptor, so to redirect, you can just: ``` $ myprogram 2>&5 ``` to redirect stderr to the file represented by fd=5. Edit: on second thought, I like @Konrad Rudolph's answer about redirectio...
What is the point of clog?
[ "", "c++", "logging", "log4cpp", "" ]
My motto for Java is "just because Java has static blocks, it doesn't mean that you should be using them." Jokes aside, there are a lot of tricks in Java that make testing a nightmare. Two of the most I hate are Anonymous Classes and Static Blocks. We have a lot of legacy code that make use of Static Blocks and these a...
When I run into this problem, I usually do the same thing you describe, except I make the static method protected so I can invoke it manually. On top of this, I make sure that the method can be invoked multiple times without problems (otherwise it is no better than the static initializer as far as the tests go). This ...
[PowerMock](http://powermock.org) is another mock framework that extends EasyMock and Mockito. With PowerMock you can easily [remove unwanted behavior](http://code.google.com/p/powermock/wiki/SuppressUnwantedBehavior) from a class, for example a static initializer. In your example you simply add the following annotatio...
Mocking Static Blocks in Java
[ "", "java", "unit-testing", "mocking", "jmockit", "static-block", "" ]
I'm trying to run powershell commands through a web interface (ASP.NET/C#) in order to create mailboxes/etc on Exchange 2007. When I run the page using Visual Studio (Cassini), the page loads up correctly. However, when I run it on IIS (v5.1), I get the error "unknown user name or bad password". The biggest problem tha...
Exchange 2007 doesn't allow you to impersonate a user for security reasons. This means that it is impossible (at the moment) to create mailboxes by impersonating a user. In order to get around this problem, I created a web service which runs under AD user which has permissions to create email acounts, etc. You can then...
Here is a class that I use to impersonate a user. ``` using System; using System.Data; using System.Configuration; using System.Web; using System.Web.Security; using System.Web.UI; using System.Web.UI.WebControls; using System.Web.UI.WebControls.WebParts; using System.Web.UI.HtmlControls; namespace orr.Tools { #...
How do you impersonate an Active Directory user in Powershell?
[ "", "c#", "asp.net", "powershell", "active-directory", "" ]
I'm trying to reduce the form spam on our website. (It's actually pretty recent). I seem to remember reading somewhere that the spammers aren't executing the Javascript on the site. Is that true? And if so, then could you simply check for javascript being disabled and then figure it's *likely* that it's spam?
There are still a large number of people that run with Javascript turned off. Alternatively, I have had decent success with stopping form spam using CSS. Basically, include an input field and label that is hidden using CSS (`display: none;`) and once submitted, check if anything has been entered in the field. I gener...
check <http://kahi.cz/wordpress/ravens-antispam-plugin/> for a nice answer if puts in ``` <noscript><p><label for="websiteurl99f">Please type "e73053": </label><input type="text" name="websiteurl99f" id="websiteurl99f" /></p></noscript> <script type="text/javascript">/* <![CDATA[ */ document.write('<div><inpu...
Simple & basic form spam reduction: checking for Javascript?
[ "", "javascript", "user-input", "" ]
So, in Java, the first line of your constructor HAS to be a call to super... be it implicitly calling super(), or explicitly calling another constructor. What I want to know is, why can't I put a try block around that? My specific case is that I have a mock class for a test. There is no default constructor, but I want...
Unfortunately, compilers can't work on theoretical principles, and even though you may know that it is safe in your case, if they allowed it, it would have to be safe for all cases. In other words, the compiler isn't stopping just you, it's stopping everyone, including all those that don't know that it is unsafe and n...
It's done to prevent someone from creating a new `SecurityManager` object from untrusted code. ``` public class Evil : SecurityManager { Evil() { try { super(); } catch { Throwable t } { } } } ```
Why can't I use a try block around my super() call?
[ "", "java", "exception", "mocking", "try-catch", "" ]
How do you specify that a foreign key constraint should be a 1:1 relationship in transact sql? Is declaring the column UNIQUE enough? Below is my existing code.! ``` CREATE TABLE [dbo].MyTable( [MyTablekey] INT IDENTITY(1,1) NOT FOR REPLICATION NOT NULL, [OtherTableKey] INT NOT NULL UNIQUE CONSTRAINT [...
A foreign key column with the UNIQUE and NOT NULL constraints that references a UNIQUE, NOT NULL column in another table creates a 1:(0|1) relationship, which is probably what you want. If there was a true 1:1 relationship, every record in the first table would have a corresponding record in the second table and vice-...
You could declare the column to be both the primary key and a foreign key. This is a good strategy for "extension" tables that are used to avoid putting nullable columns into the main table.
1:1 Foreign Key Constraints
[ "", "sql", "sql-server", "" ]
I don't remember whether I was dreaming or not but I seem to recall there being a function which allowed something like, ``` foo in iter_attr(array of python objects, attribute name) ``` I've looked over the docs but this kind of thing doesn't fall under any obvious listed headers
Using a list comprehension would build a temporary list, which could eat all your memory if the sequence being searched is large. Even if the sequence is not large, building the list means iterating over the whole of the sequence before `in` could start its search. The temporary list can be avoiding by using a generat...
Are you looking to get a list of objects that have a certain attribute? If so, a [list comprehension](http://docs.python.org/tut/node7.html#SECTION007140000000000000000) is the right way to do this. ``` result = [obj for obj in listOfObjs if hasattr(obj, 'attributeName')] ```
Using 'in' to match an attribute of Python objects in an array
[ "", "python", "arrays", "iteration", "" ]
I have a java back-end that needs to expose services to clients running in the following environments : * J2ME * Windows Mobile * iPhone I am looking for the best tool for each platform. I do not search a technology that works everywhere. I need something "light" adapted to low speed internet access. Right now I...
Hessian. <http://hessian.caucho.com>. Implementations in multiple languages (including ObjC), super light weight, and doesn't require reliance on dom/xml parsers for translation from wire to object models. Once we found Hessian, we forgot we ever knew XML.
[JSON](http://www.json.org/) is fairly compact, and supported by most frameworks. You can transfer data over HTTP using standard [REST](http://en.wikipedia.org/wiki/Representational_State_Transfer) techniques. There are JSON libraries for [Java](http://www.json.org/java/), [Objective C](http://code.brautaset.org/JSON/...
What are the best remoting technologies for mobile applications?
[ "", "java", "iphone", "windows-mobile", "java-me", "mobile", "" ]
I've just started skimming 'Debugging MS .Net 2.0 Applications' by John Robbins, and have become confused by his evangelism for Debug.Assert(...). He points out that well-implemented Asserts store the state, somewhat, of an error condition, e.g.: ``` Debug.Assert(i > 3, "i > 3", "This means I got a bad parameter"); `...
Assertions are not for parameter checking. Parameter checking should always be done (and precisely according to what pre-conditions are specified in your documentation and/or specification), and the `ArgumentOutOfRangeException` thrown as necessary. Assertions are for testing for "impossible" situations, i.e., things ...
There is a communication aspect to asserts vs exception throwing. Let's say we have a User class with a Name property and a ToString method. If ToString is implemented like this: ``` public string ToString() { Debug.Assert(Name != null); return Name; } ``` It says that Name should never null and there is ...
Debug.Assert vs. Specific Thrown Exceptions
[ "", "c#", "exception", "assert", "" ]
I've got an upcoming project wherein I will need to connect our website (`PHP5/Apache 1.3/OpenBSD 4.1`) to our back-end system running on an iSeries with OS400 V5R3 so that I can access some tables stored there. I've done some checking around but am running into some roadblocks. From what I've seen the DB2 extensions ...
Have you looked at connecting to the server using [unixODBC](http://www.unixodbc.org/)? If I remember correctly it has support for IBM DB2 and compiles on OpenBSD. Check out <http://www.php.net/odbc> for more information regarding the PHP side. If you can't get that to work, the option to setup a web service on a Linu...
Rather than setup a 2nd box, why don't you look into the PHP Connector for iSeries? My mainframe guys said it was very easy to setup on our iSeries here. We wrote a simple server in PHP that loads data models from DB2 data, serializes them, and returns them to the caller. This approach means that only another PHP app ...
Connect PHP to IBM i (AS/400)
[ "", "php", "database", "odbc", "db2", "ibm-midrange", "" ]
How do you rewrite this in Linq? ``` SELECT Id, Name FROM TableA WHERE TableA.Id IN (SELECT xx from TableB INNER JOIN Table C....) ``` So in plain english, I want to select Id and Name from TableA where TableA's Id is in a result set from a second query.
``` from a in TableA where (from b in TableB join c in TableC on b.id equals c.id where .. select b.id) .Contains(a.Id) select new { a.Id, a.Name } ```
LINQ supports IN in the form of contains. Think "collection.Contains(id)" instead of "id IN (collection)". ``` from a in TableA where ( from b in TableB join c in TableC on b.id equals c.id select b.id ).Contains(TableA.Id) select new { a.Id, a.Name } ``` See also this blog [post](http://blog.weke...
How do I write SELECT FROM myTable WHERE id IN (SELECT...) in Linq?
[ "", "sql", "linq", "linq-to-sql", "" ]
The subject says it all - normally easy and cross platform way is to poll, intelligently. But every OS has some means to notify without polling. Is it possible in a reasonably cross platform way? (I only really care about Windows and Linux, but I use mac, so I thought posix may help?)
Linux users can use [inotify](http://en.wikipedia.org/wiki/Inotify) > inotify is a Linux kernel subsystem > that provides file system event > notification. Some goodies for Windows fellows: * [File Change Notification](http://msdn.microsoft.com/en-us/library/bb158663.aspx) on MSDN * "[When Folders Change](http://www...
The Qt library has a [QFileSystemWatcher](http://doc.qt.io/qt-5/qfilesystemwatcher.html) class which provides cross platform notifications when a file changes. Even if you are not using Qt, because the source is available you could have a look at it as a sample for your own implementation. Qt has separate implementatio...
How to be notified of file/directory change in C/C++, ideally using POSIX
[ "", "c++", "c", "posix", "" ]
I know that the following is true ``` int i = 17; //binary 10001 int j = i << 1; //decimal 34, binary 100010 ``` But, if you shift too far, the bits fall off the end. Where this happens is a matter of the size of integer you are working with. Is there a way to perform a shift so that the bits rotate around to the ot...
If you know the size of type, you could do something like: ``` uint i = 17; uint j = i << 1 | i >> 31; ``` ... which would perform a circular shift of a 32 bit value. As a generalization to circular shift left n bits, on a b bit variable: ``` /*some unsigned numeric type*/ input = 17; var result = input << n | inp...
One year ago I've to implement MD4 for my undergraduate thesis. Here it is my implementation of circular bit shift using a UInt32. ``` private UInt32 RotateLeft(UInt32 x, Byte n) { return UInt32((x << n) | (x >> (32 - n))); } ```
Is there a way to perform a circular bit shift in C#?
[ "", "c#", "bit-manipulation", "" ]
I'm looking to introduce a unit testing framework into the mix at my job. We're using Visual Studio 2005 (though we may be moving to 2008 within the next six months) and work primarily in C#. If the framework has some kind of IDE integration that would be best, but I'm open to frameworks that don't have integration but...
I think [NUnit](https://en.wikipedia.org/wiki/NUnit) **is** your best bet. With [TestDriven.NET](https://testdriven.net/), you get great integration within Visual Studio. (ReSharper also has a unit test runner if you're using it). NUnit is simple to use and follows an established paradigm. You'll also find plenty of pr...
Scott Hanselman had a good *podcast* about this, entitled: > "The Past, Present and Future of .NET Unit Testing Frameworks" : [Hanselminutes #112](http://www.hanselminutes.com/default.aspx?showID=130)
.NET testing framework advice
[ "", "c#", ".net", "visual-studio", "unit-testing", "nunit", "" ]
What method do you use when you want to get performance data about specific code paths?
This method has several limitations, but I still find it very useful. I'll list the limitations (I know of) up front and let whoever wants to use it do so at their own risk. 1. The original version I posted over-reported time spent in recursive calls (as pointed out in the comments to the answer). 2. It's not thread s...
I do my profiles by creating two classes: `cProfile` and `cProfileManager`. `cProfileManager` will hold all the data that resulted from `cProfile`. `cProfile` with have the following requirements: * `cProfile` has a constructor which initializes the current time. * `cProfile` has a deconstructor which sends the tota...
Quick and dirty way to profile your code
[ "", "c++", "performance", "profiling", "code-snippets", "" ]
I'm getting a `NoSuchMethodError` error when running my Java program. What's wrong and how do I fix it?
Without any more information it is difficult to pinpoint the problem, but the root cause is that you most likely have compiled a class against a different version of the class that is missing a method, than the one you are using when running it. Look at the stack trace ... If the exception appears when calling a metho...
I was having your problem, and this is how I fixed it. The following steps are a working way to add a library. I had done the first two steps right, but I hadn't done the last one by dragging the ".jar" file direct from the file system into the "lib" folder on my eclipse project. Additionally, I had to remove the previ...
How do I fix a NoSuchMethodError?
[ "", "java", "nosuchmethoderror", "" ]
I have an issue that is driving me a bit nuts: Using a UserProfileManager as an non-authorized user. The problem: The user does not have "Manage User Profiles" rights, but I still want to use the UserProfileManager. The idea of using SPSecurity.RunWithElevatedPrivileges does not seem to work, as the UserProfileManager...
The permission that needs set is actually found in the Shared Service Provider. 1. Navigate to Central Admin 2. Navigate to the Shared Service Provider 3. Under **User Profiles and My Sites** navigate to Personalization services permissions . 4. If the account doesn't already exist, add the account for which your site...
Thanks for the Answers. One Caveat: if you run the Application Pool as "Network Service" instead of a Domain Account, you're screwed. But then again, it's recommended to use a domain account anyway (On a test server I used network service, but after changing it to a domain account it worked).
Sharepoint UserProfileManager without Manage User Profiles right
[ "", "c#", "sharepoint", "" ]
This is something that I think would be very useful. Basically, I'd like there to be a way to edit Python source programmatically without requiring human intervention. There are a couple of things I would like to do with this: 1. Edit the configuration of Python apps that use source modules for configuration. 2. Set u...
Python's standard library provides pretty good facilities for working with Python source; note the [tokenize](https://docs.python.org/2/library/tokenize.html) and [parser](https://docs.python.org/2/library/parser.html) modules.
I had the same issue and I simply opened the file and did some replace: then reload the file in the Python interpreter. This works fine and is easy to do. Otherwise AFAIK you have to use some conf objects.
Programmatically editing Python source
[ "", "python", "file-io", "" ]
The following code is causing an intermittent crash on a Vista machine. ``` using (SoundPlayer myPlayer = new SoundPlayer(Properties.Resources.BEEPPURE)) myPlayer.Play(); ``` I highly suspect it is this code because the program crashes mid-beep or just before the beep is played every time. I have top-level traps...
Actually, the above code (that is, new SoundPlayer(BEEPPURE)).Play(); was crashing for me. This article explains why, and provides an alternative to SoundPlayer that works flawlessly: <http://www.codeproject.com/KB/audio-video/soundplayerbug.aspx?msg=2862832#xx2862832xx>
You can use WinDBG and trap all first-chance exceptions. I'm sure you'll see something interesting. If so, you can use SOS to clean up the stack and post it here to help us along. Or you can use Visual Studio by enabling the trap of all exceptions. Go to "Debug" and then "Exceptions" and make sure you trap everything....
SoundPlayer crash on Vista
[ "", "c#", "winforms", "windows-vista", "audio", "" ]
In a project our team is using object lists to perform mass operations on sets of data that should all be processed in a similar way. In particular, different objects would ideally act the same, which would be very easily achieved with polymorphism. The problem I have with it is that inheritance implies the *is a* rela...
This can be accomplished using multiple inheritance. In your specific case (C++), you can use pure virtual classes as interfaces. This allows you to have multiple inheritance without creating scope/ambiguity problems. Example: ``` class Damage { virtual void addDamage(int d) = 0; virtual int getDamage() = 0; }...
I think you should be implementing interfaces to be able to enforce your *has a* relationships (am doing this in C#): ``` public interface IDamageable { void AddDamage(int i); int DamageCount {get;} } ``` You could implement this in your objects: ``` public class Person : IDamageable public class House : ID...
Inheritance and Polymorphism - Ease of use vs Purity
[ "", "c++", "inheritance", "oop", "polymorphism", "" ]
What are the differences between a [`HashMap`](https://docs.oracle.com/en/java/javase/11/docs/api/java.base/java/util/HashMap.html) and a [`Hashtable`](https://docs.oracle.com/en/java/javase/11/docs/api/java.base/java/util/Hashtable.html) in Java? Which is more efficient for non-threaded applications?
There are several differences between [`HashMap`](https://docs.oracle.com/en/java/javase/17/docs/api/java.base/java/util/HashMap.html) and [`Hashtable`](https://docs.oracle.com/en/java/javase/17/docs/api/java.base/java/util/Hashtable.html) in Java: 1. `Hashtable` is [synchronized](https://stackoverflow.com/questions/1...
Note, that a lot of the answers state that Hashtable is synchronized. **In practice this buys you very little.** The synchronization is on the accessor/mutator methods will stop two threads adding or removing from the map concurrently, but in the real world, you will often need additional synchronization. A very commo...
What are the differences between a HashMap and a Hashtable in Java?
[ "", "java", "collections", "hashmap", "hashtable", "" ]
[Django](http://www.djangoproject.com/) view points to a function, which can be a problem if you want to change only a bit of functionality. Yes, I could have million keyword arguments and even more if statements in the function, but I was thinking more of an object oriented approach. For example, I have a page that d...
I've created and used my own generic view classes, defining **`__call__`** so an instance of the class is callable. I really like it; while Django's generic views allow some customization through keyword arguments, OO generic views (if their behavior is split into a number of separate methods) can have much more fine-g...
I needed to use class based views, but I wanted to be able to use the full name of the class in my URLconf without always having to instantiate the view class before using it. What helped me was a surprisingly simple metaclass: ``` class CallableViewClass(type): def __call__(cls, *args, **kwargs): if args ...
Class views in Django
[ "", "python", "django", "view", "oop", "" ]
I'm interested in doing comparisons between the date string and the MySQL timestamp. However, I'm not seeing an easy conversion. Am I overlooking something obvious?
Converting from timestamp to format: ``` date('Y-m-d', $timestamp); ``` Converting from formatted to timestamp: ``` mktime(0, 0, 0, $month, $day, $year, $is_dst); ``` See [date](http://www.php.net/manual/en/function.date.php) and [mktime](http://www.php.net/manual/en/function.mktime.php) for further documentation. ...
You can avoid having to use `strtotime()` or `getdate()` in **PHP** by using MySQL's `UNIX_TIMESTAMP()` function. ``` SELECT UNIX_TIMESTAMP(timestamp) FROM sometable ``` The resulting data will be a standard integer Unix timestamp, so you can do a direct comparison to `time()`.
If I have a PHP string in the format YYYY-DD-MM and a timestamp in MySQL, is there a good way to convert between them?
[ "", "php", "mysql", "time", "timestamp", "date", "" ]
I would like to retrieve the ethernet address of the network interface that is used to access a particular website. How can this be done in Java? **Solution** Note that the accepted solution of `getHardwareAddress` is only available in Java 6. There does not seem to be a solution for Java 5 aside from executing i(f|p...
[java.net.NetworkInterface.getHardwareAddress](http://java.sun.com/javase/6/docs/api/java/net/NetworkInterface.html#getHardwareAddress%28%29) (method added in Java 6) It has to be called on the machine you are interested in - the MAC is not transferred across network boundaries (i.e. LAN and WAN). If you want to make ...
You can get the address that connects to your ServerSocket using <http://java.sun.com/javase/6/docs/api/java/net/NetworkInterface.html#getInetAddresses()> However if your client is connecting via a NAT, then you will get the address of the router and NOT the Ethernet address. If it is on your local network (via a hub/...
How do you get the ethernet address using Java?
[ "", "java", "networking", "ethernet", "" ]
One may not always know the `Type` of an object at compile-time, but may need to create an instance of the `Type`. How do you get a new object instance from a `Type`?
The `Activator` class within the root `System` namespace is pretty powerful. There are a lot of overloads for passing parameters to the constructor and such. Check out the documentation at: > <http://msdn.microsoft.com/en-us/library/system.activator.createinstance.aspx> or (new path) > <https://learn.microsoft.com/...
The answer was already given: > ``` > ObjectType instance = (ObjectType)Activator.CreateInstance(objectType); > ``` However, the `Activator` class has a [generic variant for the parameterless constructor](https://learn.microsoft.com/en-us/dotnet/api/system.activator.createinstance?view=net-7.0#system-activator-create...
How to create a new object instance from a Type
[ "", "c#", ".net", "performance", "reflection", "types", "" ]