Prompt
stringlengths
10
31k
Chosen
stringlengths
3
29.4k
Rejected
stringlengths
3
51.1k
Title
stringlengths
9
150
Tags
listlengths
3
7
I have inherited a client site which crashes every 3 or 4 days. It is built using the zend-framework with which I have no knowledge. The following code: ``` <?php // Make sure classes are in the include path. ini_set('include_path', ini_get('include_path') . PATH_SEPARATOR . 'lib' . PATH_SEPARATOR . 'app' . DI...
for a start I think your include path should maybe have a trailing slash. Here is an example of mine : ``` set_include_path('../library/ZendFramework-1.5.2/library/:../application/classes/:../application/classes/excpetions/:../application/forms/'); ``` You bootstrap file will be included by another file (probably...
The fact that it only happens sporadically makes me think this is less of a programming issue, and more of a sysadmin issue - if it were a defect in the implementation, you'd expect it to fail consistently considering the error is "No such file or directory". Two guesses * There are multiple front-end web servers, and...
Failed to load Zend/Loader.php. Trying to work out why?
[ "", "php", "zend-framework", "" ]
I am using [Hibernate](http://www.hibernate.org/) in a Java application to access my Database and it works pretty well with MS-SQL and MySQL. But some of the data I have to show on some forms has to come from Text files, and by Text files I mean Human-Readable files, they can be CSV, Tab-Delimited, or even a key, value...
Hibernate is written against the JDBC API. So, you need a JDBC driver that works with the file format you are interested in. Obviously, even for read-only access, this isn't going to perform well, but it might still be useful if that's not a high priority. On a Windows system, you can set up ODBC datasources for delimi...
A quick google came up with * [JDBC driver for csv files](http://sourceforge.net/projects/csvjdbc) * [JDBC driver for XML files](http://www.csv-jdbc.com/stels_xml_jdbc.htm) Hope this might provide some inspiration?
Using Hibernate to work with Text Files
[ "", "java", "database", "hibernate", "text-files", "" ]
I know I must be missing something, but in a `while` statement how does the variable hold the data, when it finishes the first pass and goes into the second pass? --- { ``` int num1 = 0 ; int num2 = 0; int num3 = 0; while (num1 < 10) {cout << "enter your first number: "; cin >> num1; cout << "Enter your secon...
Is num1 the variable you're having trouble with? This line: ``` cin >> num1; ``` is setting num1 to the value input by the user. So the value calculated for it in the previous run through the loop is being overwritten each time by the new input.
I'm not clear exactly what you're asking, but variables will maintain their value for each iteration of a loop, as long as they're declared outside of the loop itself. For example: ``` int a = 0; while(a < 10) { int b = 0; cout << "a: " << a << " b: " << b << "\n"; a++; b++; } ``` In the above, the...
Variable Holding data in a while statement
[ "", "c++", "" ]
Is it possible for gcc to link against a library that was created with Visual C++? If so, are there any conflicts/problems that might arise from doing so?
Some of the comments in the answers here are slightly too generalistic. Whilst no, in the specific case mentioned gcc binaries won't link with a VC++ library (AFAIK). The actual means of interlinking code/libraries is a question of the ABI standard being used. An increasingly common standard in the embedded world is ...
I would guess not. Usually c++ compilers have quite different methods of name-mangling which means that the linkers will fail to find the correct symbols. This is a good thing by the way, because C++ compilers are allowed by the standard to have much greater levels of incompatibility than just this that will cause your...
Mixing C/C++ Libraries
[ "", "c++", "visual-studio", "gcc", "linker", "" ]
There are two popular closure styles in javascript. The first I call *anonymous constructor*: ``` new function() { var code... } ``` and the *inline executed function*: ``` (function() { var code... })(); ``` are there differences in behaviour between those two? Is one "better" over the other?
Both cases will execute the function, the only real difference is what the return value of the expression may be, and what the value of "this" will be inside the function. Basically behaviour of ``` new expression ``` Is effectively equivalent to ``` var tempObject = {}; var result = expression.call(tempObject); if...
@Lance: the first one is also executing. Compare it with a named constructor: ``` function Blah() { alert('blah'); } new Bla(); ``` this is actually also executing code. The same goes for the anonymous constructor... But that was not the question ;-)
What's the difference in closure style
[ "", "javascript", "" ]
I have a ASP.NET page with an asp:button that is not visible. I can't turn it visible with JavaScript because it is not rendered to the page. What can I do to resolve this?
If you need to manipulate it on the client side, you can't use the Visible property on the server side. Instead, set its CSS display style to "none". For example: ``` <asp:Label runat="server" id="Label1" style="display: none;" /> ``` Then, you could make it visible on the client side with: ``` document.getElementBy...
Try this. ``` <asp:Button id="myButton" runat="server" style="display:none" Text="Click Me" /> <script type="text/javascript"> function ShowButton() { var buttonID = '<%= myButton.ClientID %>'; var button = document.getElementById(buttonID); if(button) { button.style.display = 'inherit'; }...
Change visibility of ASP.NET label with JavaScript
[ "", "asp.net", "javascript", "" ]
Will limiting a query to one result record, improve performance in a large(ish) MySQL table if the table only has one matching result? for example ``` select * from people where name = "Re0sless" limit 1 ``` if there is only one record with that name? and what about if `name` was the primary key/ set to unique? and...
If the column has **a unique index: no,** it's no faster **a non-unique index: maybe,** because it will prevent sending any additional rows beyond the first matched, if any exist **no index: sometimes** * if 1 or more rows match the query, **yes**, because the full table scan will be halted after the first row is m...
If you have a slightly more complicated query, with one or more joins, the LIMIT clause gives the optimizer extra information. If it expects to match two tables and return all rows, a [hash join](http://en.wikipedia.org/wiki/Hash_join "hash join") is typically optimal. A hash join is a type of join optimized for large ...
Does limiting a query to one record improve performance
[ "", "sql", "mysql", "database", "" ]
I have read through several reviews on Amazon and some books seem outdated. I am currently using MyEclipse 6.5 which is using Eclipse 3.3. I'm interested in hearing from people that have experience learning RCP and what reference material they used to get started.
I've been doing Eclipse RCP development for almost 2 years now. When I first started, I wanted a book for help and many people told me, with Eclipse you're better off using the [Eclipsepedia](http://wiki.eclipse.org/index.php/Rich_Client_Platform) and Google. However, I started with "[The Java Developer's Guide to Ecl...
I agree with Thomas Owens on "[Eclipse Rich Client Platform: Designing, Coding, and Packaging Java(TM) Applications](https://rads.stackoverflow.com/amzn/click/com/0321334612)" and would also add "[Eclipse: Building Commercial-Quality Plug-ins](https://rads.stackoverflow.com/amzn/click/com/032142672X)" to the list of ra...
I would like a recommendation for a book on Eclipse's Rich Client Platform (RCP)
[ "", "java", "eclipse", "rcp", "myeclipse", "" ]
There are a couple of things that I am having a difficult time understanding with regards to developing custom components in JSF. For the purposes of these questions, you can assume that all of the custom controls are using valuebindings/expressions (not literal bindings), but I'm interested in explanations on them as ...
There is a pretty good diagram in the [JSF specification](http://java.sun.com/javaee/javaserverfaces/download.html) that shows the request lifecycle - essential for understanding this stuff. The steps are: * **Restore View**. The UIComponent tree is rebuilt. * **Apply Request Values**. Editable components should impl...
Action listeners, such as for a *CommandButton*, are called during the *Invoke Application* phase, which is the last phase before the final *Render Response* phase. This is shown in [The JSF Lifecycle - figure 1](http://www.ibm.com/developerworks/library/j-jsf2/#figure1).
JSF Lifecycle and Custom components
[ "", "java", "jsf", "jakarta-ee", "custom-component", "" ]
The MSDN documentation on [Object.GetHashCode()](http://msdn.microsoft.com/en-us/library/system.object.gethashcode.aspx) describes 3 contradicting rules for how the method should work. 1. If two objects of the same type represent the same value, the hash function must return the same constant value for either object. ...
> Rules 1 & 3 are contradictory to me. To a certain extent, they are. The reason is: if an object is stored in a hash table and, by changing its value, you change its hash then the hash table has lost the value and you can't find it again by querying the hash table. — It is therefore important that while objects are s...
Not sure what MSDN documentation you are referring to. Looking at the current documentation on Object.GetHashCode (<http://msdn.microsoft.com/en-us/library/system.object.gethashcode.aspx>) provides the following "rules": * If two objects compare as equal, the GetHashCode method for each object must return the same val...
Is Object.GetHashCode() unique to a reference or a value?
[ "", "c#", ".net", "" ]
Is there anyway to have a sort of virtual static member in C++? For example: ``` class BaseClass { public: BaseClass(const string& name) : _name(name) {} string GetName() const { return _name; } virtual void UseClass() = 0; private: const string _name; }; class DerivedClass :...
Here is one solution: ``` struct BaseData { const string my_word; const int my_number; }; class Base { public: Base(const BaseData* apBaseData) { mpBaseData = apBaseData; } const string getMyWord() { return mpBaseData->my_word; } int getMyNumber() { return m...
It seems like the answer is in the question - the method you suggested seems to be the right direction to go, except that if you have a big number of those shared members you might want to gather them into a struct or class and past that as the argument to the constructor of the base class. If you insist on having the...
Simulating a virtual static member of a class in c++?
[ "", "c++", "virtual-functions", "" ]
I've learned in College that you always have to free your unused Objects but not how you actually do it. For example structuring your code right and so on. Are there any general rules on how to handle pointers in C++? I'm currently not allowed to use boost. I have to stick to pure c++ because the framework I'm using f...
I have worked with the embedded Symbian OS, which had an excellent system in place for this, based entirely on developer conventions. 1. Only one object will ever own a pointer. By default this is the creator. 2. Ownership can be passed on. To indicate passing of ownership, the object is passed as a pointer in the met...
Rules: 1. Wherever possible, use a [smart pointer](http://en.wikipedia.org/wiki/Smart_pointer). Boost has some [good ones](http://www.boost.org/doc/libs/1_35_0/libs/smart_ptr/sp_techniques.html). 2. If you can't use a smart pointer, [null out your pointer after deleting it](http://csis.pace.edu/~bergin/pap...
C++ Memory management
[ "", "c++", "memory", "pointers", "" ]
How do I check if an object property in JavaScript is undefined?
The usual way to check if the value of a property is the special value `undefined`, is: ``` if(o.myProperty === undefined) { alert("myProperty value is the special value `undefined`"); } ``` To check if an object does not actually have such a property, and will therefore return `undefined` by default when you try t...
I believe there are a number of incorrect answers to this topic. Contrary to common belief, "undefined" is **not** a keyword in JavaScript and can in fact have a value assigned to it. # Correct Code The most robust way to perform this test is: ``` if (typeof myVar === "undefined") ``` This will always return the co...
Detecting an undefined object property
[ "", "javascript", "object", "undefined", "object-property", "" ]
What are the best methods for tracking and/or automating DB schema changes? Our team uses Subversion for version control and we've been able to automate some of our tasks this way (pushing builds up to a staging server, deploying tested code to a production server) but we're still doing database updates manually. I wou...
In the Rails world, there's the concept of migrations, scripts in which changes to the database are made in Ruby rather than a database-specific flavour of SQL. Your Ruby migration code ends up being converted into the DDL specific to your current database; this makes switching database platforms very easy. For every ...
We use something similar to bcwoord to keep our database schemata synchronized across 5 different installations (production, staging and a few development installations), and backed up in version control, and it works pretty well. I'll elaborate a bit: --- To synchronize the database structure, we have a single scrip...
Mechanisms for tracking DB schema changes
[ "", "php", "mysql", "database", "svn", "migration", "" ]
I am running a Tomcat application, and I need to display some time values. Unfortunately, the time is coming up an hour off. I looked into it and discovered that my default TimeZone is being set to: ``` sun.util.calendar.ZoneInfo[id="GMT-08:00", offset=-28800000, d...
It's a "quirk" in the way the JVM looks up the zoneinfo file. See [Bug ID 6456628](https://bugs.java.com/bugdatabase/view_bug?bug_id=6456628). The easiest workaround is to make /etc/localtime a symlink to the correct zoneinfo file. For Pacific time, the following commands should work: ``` # sudo cp /etc/localtime /et...
On Ubuntu, it's not enough to just change the /etc/localtime file. It seems to read /etc/timezone file, too. It's better follow the [instruction](https://help.ubuntu.com/community/UbuntuTime) to set the time zone properly. In particular, do the following: ``` $ sudo cp /etc/timezone /etc/timezone.dist $ echo "Australi...
Java Time Zone is messed up
[ "", "java", "linux", "timezone", "" ]
Given 2 rgb colors and a rectangular area, I'd like to generate a basic linear gradient between the colors. I've done a quick search and the only thing I've been able to find is [this blog entry](http://jtauber.com/blog/2008/05/18/creating_gradients_programmatically_in_python/), but the example code seems to be missing...
you want an interpolation between the first and the second colour. Interpolating colours is easy by calculating the same interpolation for each of its components (R, G, B). There are many ways to interpolate. The easiest is to use linear interpolation: just take percentage *p* of the first colour and percentage 1 - *p*...
You can use the built in [GradientPaint](https://docs.oracle.com/javase/7/docs/api/java/awt/GradientPaint.html) class. ``` void Paint(Graphics2D g, Regtangle r, Color c1, Color c2) { GradientPaint gp = new GradientPaint(0,0,c1,r.getWidth(),r.getHeight(),c2); g.setPaint(gp); g.fill(rect); } ```
Generating gradients programmatically?
[ "", "java", "colors", "rgb", "gradient", "" ]
I am using LINQ to query a generic dictionary and then use the result as the datasource for my ListView (WebForms). Simplified code: ``` Dictionary<Guid, Record> dict = GetAllRecords(); myListView.DataSource = dict.Values.Where(rec => rec.Name == "foo"); myListView.DataBind(); ``` I thought that would work but in fa...
Try this: ``` var matches = dict.Values.Where(rec => rec.Name == "foo").ToList(); ``` Be aware that that will essentially be creating a new list from the original Values collection, and so any changes to your dictionary won't automatically be reflected in your bound control.
I tend to prefer using the new Linq syntax: ``` myListView.DataSource = ( from rec in GetAllRecords().Values where rec.Name == "foo" select rec ).ToList(); myListView.DataBind(); ``` Why are you getting a dictionary when you don't use the key? You're paying for that overhead.
How can I convert IEnumerable<T> to List<T> in C#?
[ "", "c#", "linq", "generics", "listview", "" ]
I've been having a hard time trying to understand PyPy's translation. It looks like something absolutely revolutionary from simply reading the description, however I'm hard-pressed to find good documentation on actually translating a real world piece of code to something such as LLVM. Does such a thing exist? The offic...
This document seems to go into quite a bit of detail (and I think a complete description is out of scope for a stackoverflow answer): * <http://codespeak.net/pypy/dist/pypy/doc/translation.html> The general idea of translating from one language to another isn't particularly revolutionary, but it has only recently bee...
If you want some hand-on examples, [PyPy's Getting Started](http://codespeak.net/pypy/dist/pypy/doc/getting-started.html) document has a section titled "Trying out the translator".
Where can I learn more about PyPy's translation function?
[ "", "python", "translation", "pypy", "" ]
I'm having issues with my SQL Reporting Services reports. I'm using a custom font for report headers, and when deployed to the server it does not render correctly when I print or export to PDF/TIFF. I have installed the font on the server. Is there anything else I need to do in order to use custom fonts? When viewing ...
The PDF files served up from SSRS, like many PDF files, have embedded postscript fonts. So, the local fonts used in the report are converted to a best matching postscript font when the conversion takes place so the PDF is totally portable without relying on locally installed fonts. You can see the official MS guidelin...
Note: I have found that when you install the fonts on the Reporting Services server box, you may need to: = Actually open the font from the Fonts control panel, so you can see the preview AND = Reboot the server box. And yes, I agree you should not need to do this - but I have seen it work.
Custom font in SQL Server 2005 Reporting Services
[ "", "sql", "reporting-services", "" ]
I'm currently trying to read in an XML file, make some minor changes (alter the value of some attributes), and write it back out again. I have intended to use a StAX parser (`javax.xml.stream.XMLStreamReader`) to read in each event, see if it was one I wanted to change, and then pass it straight on to the StAX writer ...
StAX works pretty well and is very fast. I used it in a project to parse XML files which are up to 20MB. I don't have a thorough analysis, but it was definitely faster than SAX. As for your question: The difference between streaming and event-handling, AFAIK is control. With the streaming API you can walk through your...
After a bit of mucking around, the answer seems to be to use the Event reader/writer versions rather than the Stream versions. (i.e. javax.xml.stream.XMLEventReader and javax.xml.stream.XMLEventWriter) See also <http://www.devx.com/tips/Tip/37795>, which is what finally got me moving.
Small modification to an XML document using StAX
[ "", "java", "xml", "stax", "" ]
I'm interested in seeing a good diff algorithm, possibly in Javascript, for rendering a side-by-side diff of two HTML pages. The idea would be that the diff would show the differences of the *rendered* HTML. To clarify, I want to be able to see the side-by-side diffs *as* rendered output. So if I delete a paragraph, t...
There's another nice trick you can use to significantly improve the look of a rendered HTML diff. Although this doesn't fully solve the initial problem, it will make a significant difference in the appearance of your rendered HTML diffs. Side-by-side rendered HTML will make it very difficult for your diff to line up v...
Over the weekend I posted a new project on codeplex that implements an HTML diff algorithm in C#. The original algorithm was written in Ruby. I understand you were looking for a JavaScript implementation, perhaps having one available in C# with source code could assist you to port the algorithm. Here is the link if you...
Anyone have a diff algorithm for rendered HTML?
[ "", "javascript", "html", "diff", "" ]
I am looking for the best method to run a Java Application as a \*NIX daemon or a Windows Service. I've looked in to the [Java Service Wrapper](http://wrapper.tanukisoftware.org/), the [Apache Commons project 'jsvc'](http://commons.apache.org/daemon/jsvc.html), and the [Apache Commons project 'procrun'](http://commons....
I've had great success with Java Service Wrapper myself. I haven't looked at the others, but the major strengths of ServiceWrapper are: * Great x-platform support - I've used it on Windows and Linux, and found it easy on both * Solid Documentation - The docs are clear and to the point, with great examples * Deep per-p...
Another option is [WinRun4J](http://winrun4j.sourceforge.net/ "WinRun4J"). This is windows only but has some useful features: * 32 bit and 64 bit support * API to access the event log and registry * Can register service to be dependent on other services (i.e serviceA and serviceB must startup before serviceC) Its als...
Best Method to run a Java Application as a *nix Daemon or Windows Service?
[ "", "java", "unix", "windows-services", "daemon", "" ]
What would be the Master Pages equivalent in the Java web development world? I've heard of Tiles, Tapestry and Velocity but don't know anything about them. Are they as easy to use as Master Pages? I want something as easy as set up one template and subsequent pages derive from the template and override content regions...
First, the equivalent of ASP.Net in Java is going to be a web framework, such as the ones you mention (Tiles, Tapestry and Velocity). Master pages give the ability to define pages in terms of content slotted into a master template. Master pages are a feature of ASP.Net (the .Net web framework), so you are looking for...
You should also check out [Facelets](https://facelets.java.net/); there is a [good introductory article](http://www.ibm.com/developerworks/java/library/j-facelets/) on DeveloperWorks. The Facelets `<ui:insert/>` tag is comparable to the ASP.NET `<asp:ContentPlaceHolder/>` tag used in master pages; it lets you provide ...
ASP.NET Master Pages equivalent in Java
[ "", "java", "model-view-controller", "master-pages", "" ]
Is there a way to find the number of files of a specific type without having to loop through all results inn a Directory.GetFiles() or similar method? I am looking for something like this: ``` int ComponentCount = MagicFindFileCount(@"c:\windows\system32", "*.dll"); ``` I know that I can make a recursive function to ...
You should use the [Directory.GetFiles(path, searchPattern, SearchOption)](http://msdn.microsoft.com/en-us/library/ms143316.aspx) overload of Directory.GetFiles(). Path specifies the path, searchPattern specifies your wildcards (e.g., \*, \*.format) and SearchOption provides the option to include subdirectories. The ...
The slickest method woud be to use linq: ``` var fileCount = (from file in Directory.EnumerateFiles(@"H:\iPod_Control\Music", "*.mp3", SearchOption.AllDirectories) select file).Count(); ```
Find number of files with a specific extension, in all subdirectories
[ "", "c#", "file", "recursion", "" ]
We've been using the 32bit linux version of the [JavaServiceWrapper](http://wrapper.tanukisoftware.org/) for quite a while now and it's working perfectly. We are now considering also using it on 64bit linux systems. There are downloads for 64bit binaries on the website, but looking into Makefile for the 64bit version I...
I've had it running in production on 64-bit red hat without any trouble for the last year or so.
From <http://wrapper.tanukisoftware.org/doc/english/introduction.html> : > Binary distributions are provided for > the following list of platforms and > are available on the download page. > Only OS versions which are known to > work have been listed. > > (snip...) > > * linux - Linux kernels; 2.2.x 2.4.x, 2.6.x. Know...
JavaServiceWrapper on 64bit linux, any problems?
[ "", "java", "daemon", "" ]
In Java (or any other language with checked exceptions), when creating your own exception class, how do you decide whether it should be checked or unchecked? My instinct is to say that a checked exception would be called for in cases where the caller might be able to recover in some productive way, where as an uncheck...
Checked Exceptions are great, so long as you understand when they should be used. The Java core API fails to follow these rules for SQLException (and sometimes for IOException) which is why they are so terrible. **Checked Exceptions** should be used for **predictable**, but **unpreventable** errors that are **reasonab...
From [A Java Learner](http://lankireddy.blogspot.com/2007/10/checked-vs-unchecked-exceptions.html): > When an exception occurs, you have to > either catch and handle the exception, > or tell compiler that you can't handle > it by declaring that your method > throws that exception, then the code > that uses your method...
When to choose checked and unchecked exceptions
[ "", "java", "exception", "checked-exceptions", "" ]
What issues / pitfalls must be considered when overriding `equals` and `hashCode`?
### The theory (for the language lawyers and the mathematically inclined): `equals()` ([javadoc](http://docs.oracle.com/javase/7/docs/api/java/lang/Object.html#equals(java.lang.Object))) must define an equivalence relation (it must be *reflexive*, *symmetric*, and *transitive*). In addition, it must be *consistent* (i...
There are some issues worth noticing if you're dealing with classes that are persisted using an Object-Relationship Mapper (ORM) like Hibernate, if you didn't think this was unreasonably complicated already! **Lazy loaded objects are subclasses** If your objects are persisted using an ORM, in many cases you will be d...
What issues should be considered when overriding equals and hashCode in Java?
[ "", "java", "overriding", "equals", "hashcode", "" ]
I'm trying to extend some "base" classes in Python: ``` class xlist (list): def len(self): return len(self) def add(self, *args): self.extend(args) return None class xint (int): def add(self, value): self += value return self x = xlist([1,2,3]) print x.len() #...
`int` is a value type, so each time you do an assignment, (e.g. both instances of `+=` above), it doesn't modify the object you have on the heap, but replaces the reference with one of the result of the right hand side of the assignment (i.e. an `int`) `list` isn't a value type, so it isn't bound by the same rules. t...
Your two `xint` examples don't work for two different reasons. The first doesn't work because `self += value` is equivalent to `self = self + value` which just reassigns the local variable `self` to a different object (an integer) but doesn't change the original object. You can't really get this ``` >>> x = xint(10) ...
Extending base classes in Python
[ "", "python", "" ]
I have an images folder with a png in it. I would like to set a MenuItem's icon to that png. How do I write this in procedural code?
``` menutItem.Icon = new System.Windows.Controls.Image { Source = new BitmapImage(new Uri("images/sample.png", UriKind.Relative)) }; ```
``` <MenuItem> <MenuItem.Icon> <Image> <Image.Source> <BitmapImage UriSource="/your_assembly;component/your_path_here/Image.png" /> </Image.Source> </Image> </MenuItem.Icon> </MenuItem> ``` Just make sure your image in also included in the project file and marked as resource, and you ar...
WPF setting a MenuItem.Icon in code
[ "", "c#", "wpf", "icons", "menuitem", "" ]
Is it possible to access an element on a Master page from the page loaded within the `ContentPlaceHolder` for the master? I have a ListView that lists people's names in a navigation area on the Master page. I would like to update the ListView after a person has been added to the table that the ListView is data bound t...
I believe you *could* do this by using this.Master.FindControl or something similar, but you probably shouldn't - it requires the content page to know too much about the structure of the master page. I would suggest another method, such as firing an event in the content area that the master could listen for and re-bin...
Assuming the control is called "PeopleListView" on the master page ``` ListView peopleListView = (ListView)this.Master.FindControl("PeopleListView"); peopleListView.DataSource = [whatever]; peopleListView.DataBind(); ``` But @[palmsey](https://stackoverflow.com/users/521/palmsey) is more correct, especially if your p...
How to access .Net element on Master page from a Content page?
[ "", "c#", ".net", "" ]
In a C# (feel free to answer for other languages) loop, what's the difference between `break` and `continue` as a means to leave the structure of the loop, and go to the next iteration? Example: ``` foreach (DataRow row in myTable.Rows) { if (someConditionEvalsToTrue) { break; //what's the difference ...
`break` will exit the loop completely, `continue` will just **skip** the current iteration. For example: ``` for (int i = 0; i < 10; i++) { if (i == 0) { break; } DoSomeThingWith(i); } ``` The `break` will cause the loop to exit on the first iteration —`DoSomeThingWith` will never be executed. ...
A really easy way to understand this is to place the word "loop" after each of the keywords. The terms now make sense if they are just read like everyday phrases. **`break`** loop - looping is broken and stops. **`continue`** loop - loop continues to execute with the next iteration.
C# loop — break vs. continue
[ "", "c#", "loops", "break", "enumeration", "continue", "" ]
I've deployed some Managed Beans on WebSphere 6.1 and I've managed to invoke them through a standalone client, but when I try to use the application "jconsole" distributed with the standard JDK can can't make it works. Has anyone achieved to connect the jconsole with WAS 6.1? IBM WebSphere 6.1 it's supossed to suppor...
WebSphere's support for JMX is crap. Particularly, if you need to connect to any secured JMX beans. Here's an interesting tidbit, their own implementation of jConsole will not connect to their own JVM. I have had a PMR open with IBM for over a year to fix this issue, and have gotten nothing but the runaround. They clea...
IT WORKS ! <http://issues.apache.org/jira/browse/GERONIMO-4534;jsessionid=FB20DD5973F01DD2D470FB9A1B45D209?page=com.atlassian.jira.plugin.system.issuetabpanels%3Aall-tabpanel> ``` 1) Change the config.xml and start the server. ``` -see here how to change config.xml: <http://publib.boulder.ibm.com/wasce/V2.1.0/en/w...
How can I make "jconsole" work with Websphere 6.1?
[ "", "java", "websphere", "jmx", "mbeans", "" ]
(**Updated a little**) I'm not very experienced with internationalization using PHP, it must be said, and a deal of searching didn't really provide the answers I was looking for. I'm in need of working out a reliable way to convert only 'relevant' text to Unicode to send in an SMS message, using PHP (just temporarily...
To deal with it conceptually before getting into mechanisms, and apologies if any of this is obvious, a string can be defined as a sequence of Unicode characters, Unicode being a database that gives an id number known as a code point to every character you might need to work with. GSM-338 contains a subset of the Unico...
Although this is an old thread I recently had to solve a very similar problem and wanted to post my answer. The PHP code is somewhat simple. It starts with a painstakingly large array of GSM valid character codes in an array, then simply checks if the current character is in that array using the [ord($string) function]...
'Reliable' SMS Unicode & GSM Encoding in PHP
[ "", "php", "unicode", "sms", "gsm", "" ]
How can I calculate the value of PI using C#? I was thinking it would be through a recursive function, if so, what would it look like and are there any math equations to back it up? I'm not too fussy about performance, mainly how to go about it from a learning point of view.
If you want recursion: ``` PI = 2 * (1 + 1/3 * (1 + 2/5 * (1 + 3/7 * (...)))) ``` This would become, after some rewriting: ``` PI = 2 * F(1); ``` with F(i): ``` double F (int i) { return 1 + i / (2.0 * i + 1) * F(i + 1); } ``` Isaac Newton (you may have heard of him before ;) ) came up with this trick. Note t...
How about using: ``` double pi = Math.PI; ``` If you want better precision than that, you will need to use an algorithmic system and the Decimal type.
How do I calculate PI in C#?
[ "", "c#", "pi", "" ]
I have just received and bypassed a problem with LightWindow and IE7 where, on page load, it throws a JavaScript error on line 444 of `lightwindow.js`, claiming that the `object does not support this property or method`. Despite finding various postings on various forums, no Google result I could find had a solution, s...
I fixed this by changing line 444 to: ``` var gallery = this._getGalleryInfo(link.rel) ``` Then changing the subsequent comparison statement to: ``` if(gallery.length > 0) { // Rest of code here... ``` ...which seems to have sorted it in IE6+ and kept it working in Firefox etc. I didn't change line 1157 at all...
Instead of the try..catch maybe you could try using ``` if( this && this._getGalleryInfo ) { //use the function } ``` you could also check in the same way **this.element.rel** ( `if(this && this.element && this.element.rel)` ... ) before using it. It looks like there's a case that the `_getGalleryInfo` or `this...
LightWindow & IE7, "Line 444 - object does not support this property or method"
[ "", "javascript", "debugging", "internet-explorer-7", "lightwindow", "" ]
What's the best Python idiom for this C construct? ``` while ((x = next()) != END) { .... } ``` I don't have the ability to recode next(). update: and the answer from seems to be: ``` for x in iter(next, END): .... ```
Short answer: there's no way to do inline variable assignment in a while loop in Python. Meaning that I **cannot** say: ``` while x=next(): // do something here! ``` Since that's not possible, there are a number of "idiomatically correct" ways of doing this: ``` while 1: x = next() if x != END: /...
@Mark Harrison's answer: ``` for x in iter(next_, END): .... ``` Here's an excerpt from [Python's documentation](http://docs.python.org/library/functions.html): ``` iter(o[, sentinel]) ``` > Return an iterator object. > *...(snip)...* If the second argument, `sentinel`, is given, then `o` must be > a callable o...
Most Pythonic way equivalent for: while ((x = next()) != END)
[ "", "c", "python", "" ]
I'm trying to serialize a Type object in the following way: ``` Type myType = typeof (StringBuilder); var serializer = new XmlSerializer(typeof(Type)); TextWriter writer = new StringWriter(); serializer.Serialize(writer, myType); ``` When I do this, the call to Serialize throws the following exception: > "The type S...
I wasn't aware that a Type object could be created with only a string containing the fully-qualified name. To get the fully qualified name, you can use the following: ``` string typeName = typeof (StringBuilder).FullName; ``` You can then persist this string however needed, then reconstruct the type like this: ``` T...
I had the same problem, and my solution was to create a SerializableType class. It freely converts to and from System.Type, but it serializes as a string. All you have to do is declare the variable as a SerializableType, and from then on you can refer to it as System.Type. Here is the class: ``` // a version of Syste...
Can I serialize a C# Type object?
[ "", "c#", "serialization", "" ]
I'm looking to the equivalent of Windows [`_wfopen()`](http://msdn.microsoft.com/fr-fr/library/yeby3zcb.aspx) under Mac OS X. Any idea? I need this in order to port a Windows library that uses `wchar*` for its File interface. As this is intended to be a cross-platform library, I am unable to rely on how the client app...
POSIX API in Mac OS X are usable with UTF-8 strings. In order to convert a wchar\_t string to UTF-8, it is possible to use the CoreFoundation framework from Mac OS X. Here is a class that will wrap an UTF-8 generated string from a wchar\_t string. ``` class Utf8 { public: Utf8(const wchar_t* wsz): m_utf8(NULL) ...
You just want to open a file handle using a path that may contain Unicode characters, right? Just pass the path in *filesystem representation* to `fopen`. * If the path came from the stock Mac OS X frameworks (for example, an Open panel whether Carbon or Cocoa), you won't need to do any conversion on it and will be ab...
_wfopen equivalent under Mac OS X
[ "", "c++", "winapi", "macos", "porting", "fopen", "" ]
I am looking for a more technical explanation than the OS calls the function. Is there a website or book?
The .exe file (or equivalent on other platforms) contains an 'entry point' address. To a first approximation, the OS loads the relevant sections of the .EXE file into RAM, and then jumps to the entry point. As others have said, this entry point will not be 'main', but will instead be a part of the runtime library - it...
`main()` is part of the C library and is not a system function. I don't know for OS X or Linux, but Windows usually starts a program with `WinMainCRTStartup()`. This symbol init your process, extract command line arguments and environment (`argc, argv, end`) and calls `main()`. It is also responsible of calling any cod...
In a C/C++ program, how does the system (Windows, Linux, and Mac OS X) call the main() function?
[ "", "c++", "c", "program-entry-point", "" ]
I'm running PHP 5.2.3 on Windows 2000 Server with IIS 5. I'm trying to get cURL working, so in my **php.ini** file, I have this line: > extension\_dir ="F:\PHP\ext" And later, I have: > extension=php\_curl.dll The file **F:\PHP\ext\php\_curl.dll** exists, but when I try to run any PHP script, I get this in the erro...
Problem solved! Although the error message said **The specified module could not be found**, this is a little misleading -- it's not that it couldn't find `php_curl.dll`, but rather it couldn't find a module that `php_curl.dll` required. The 2 DLLs it requires are `libeay32.dll` and `SSLeay32.dll`. So, you have to pu...
`libeay32.dll` and `ssleay32.dll` have to be path-accessible for `php_curl.dll` to work correctly. In **Control Panel** -> **Search** -> **Advanced System Settings** and use the button **Environment Variables**. Under **System Variables** find **Path** add the `c:/php` folder (or whatever path) and restart Apache.
PHP / cURL on Windows install: "The specified module could not be found."
[ "", "php", "windows", "curl", "" ]
I've written a stored proc that will do an update if a record exists, otherwise it will do an insert. It looks something like this: ``` update myTable set Col1=@col1, Col2=@col2 where ID=@ID if @@rowcount = 0 insert into myTable (Col1, Col2) values (@col1, @col2) ``` My logic behind writing it in this way is that the...
Your assumption is right, this is the optimal way to do it and it's called [upsert/merge](http://en.wikipedia.org/wiki/Upsert). [Importance of UPSERT - from sqlservercentral.com](http://www.sqlservercentral.com/articles/T-SQL/61773/): > For every update in the case mentioned above we are removing one > additional rea...
Please read the [post on my blog](http://samsaffron.com/blog/archive/2007/04/04/14.aspx) for a good, safe pattern you can use. There are a lot of considerations, and the accepted answer on this question is far from safe. For a quick answer try the following pattern. It will work fine on SQL 2000 and above. SQL 2005 gi...
Insert Update stored proc on SQL Server
[ "", "sql", "sql-server", "stored-procedures", "upsert", "" ]
I'm having trouble figuring out how to get the testing framework set up and usable in **Visual Studio 2008** for C++ presumably with the built-in unit testing suite. Any links or tutorials would be appreciated.
[This page](http://gamesfromwithin.com/exploring-the-c-unit-testing-framework-jungle) may help, it reviews quite a few C++ unit test frameworks: * CppUnit * Boost.Test * CppUnitLite * NanoCppUnit * Unit++ * CxxTest Check out ***[CPPUnitLite](http://www.objectmentor.com/resources/downloads.html)*** or ***[CPPUnitLite2...
**There is a way to test unmanaged C++ using the built in testing framework within Visual Studio 2008**. If you create a C++ Test Project, using C++/CLI, you can then make calls to an unmanaged DLL. You will have to switch the Common Language Runtime support to /clr from /clr:safe if you want to test code that was writ...
How to set up unit testing for Visual Studio C++
[ "", "c++", "unit-testing", "testing", "visual-studio-2008", "frameworks", "" ]
I need to store products for an e-commerce solution in a database. Each product should have descriptive information, such as name, description etc. I need any product to be localized to x number of languages. What I've done so far, is to make any column that should be localized and `nvarchar(MAX)` and then i store an...
You should store the current language somewhere (in a [singleton](http://www.yoda.arachsys.com/csharp/singleton.html), for instance) and in the product.Name property use the language setting to get the correct string. This way you only have to write the language specific code once for each field rather than thinking ab...
Rob Conery's MVC Storefront webcast series has [a video on this issue](http://blog.wekeroad.com/mvc-storefront/mvcstore-part-5/) (he gets to the database around 5:30). He stores a list of cultures, and then has a Product table for non-localized data and a ProductCultureDetail table for localized text.
Globalization architecture
[ "", "c#", "architecture", "localization", "globalization", "" ]
What is the **complete** and correct syntax for the SQL Case expression?
The **complete** syntax depends on the database engine you're working with: For SQL Server: ``` CASE case-expression WHEN when-expression-1 THEN value-1 [ WHEN when-expression-n THEN value-n ... ] [ ELSE else-value ] END ``` or: ``` CASE WHEN boolean-when-expression-1 THEN value-1 [ WHEN boolean-when-...
Considering you tagged multiple products, I'd say the *full* correct syntax would be the one found in the ISO/ANSI SQL-92 standard: ``` <case expression> ::= <case abbreviation> | <case specification> <case abbreviation> ::= NULLIF <left paren> <value expression> <comma> <value expres...
SQL Case Expression Syntax?
[ "", "sql", "" ]
In Visual C++ a DWORD is just an unsigned long that is machine, platform, and SDK dependent. However, since DWORD is a double word (that is 2 \* 16), is a DWORD still 32-bit on 64-bit architectures?
Actually, on 32-bit computers a word is 32-bit, but the DWORD type is a leftover from the good old days of 16-bit. In order to make it easier to port programs to the newer system, Microsoft has decided all the old types will not change size. You can find the official list here: <http://msdn.microsoft.com/en-us/librar...
It is defined as: ``` typedef unsigned long DWORD; ``` However, according to the MSDN: > On 32-bit platforms, long is > synonymous with int. Therefore, DWORD is 32bit on a 32bit operating system. There is a separate define for a 64bit DWORD: ``` typdef unsigned _int64 DWORD64; ``` Hope that helps.
How large is a DWORD with 32- and 64-bit code?
[ "", "c++", "winapi", "64-bit", "dword", "" ]
I have developed some classes with similar behavior, they all implement the same interface. I implemented a factory that creates the appropriate object and returns the interface. I am writing a unit test for the factory. All you get back is an interface to the object. What is the best way to test that the factory has w...
Since I don't know how your factory method looks like, all I can advise right now is to 1. Check to see the object is the correct concrete implementation you were looking for: ``` IMyInterface fromFactory = factory.create(...); Assert.assertTrue(fromFactory instanceof MyInterfaceImpl1); ``` 2. You can c...
# What you are trying to do is not Unit Testing If you test whether or not the returned objects are instances of specific concrete classes, you aren't unit testing. You are integration testing. While integration testing is important, it is not the same thing. In unit testing, you only need to test the object itself. ...
Checking the results of a Factory in a unit test
[ "", "java", "unit-testing", "tdd", "" ]
I'm working on a windows forms application (C#) where a user is entering data in a form. At any point while editing the data in the form the user can click one of the buttons on the form to perform certain actions. By default the focus goes to the clicked button so the user has to click back on to the control they want...
For a bit of 'simplicity' maybe try. ``` public Form1() { InitializeComponent(); foreach (Control ctrl in Controls) { if (ctrl is TextBox) { ctrl.Enter += delegate(object sender, EventArgs e) { ...
You could do the following Change the button to a label and make it look like a button. The label will never get focus and you don't have to do all the extra coding.
How do you return the focus to the last used control after clicking a button in a winform app?
[ "", "c#", ".net", "winforms", "" ]
I have multiple selects: ``` <select id="one"> <option value="1">one</option> <option value="2">two</option> <option value="3">three</option> </select> <select id="two"> <option value="1">one</option> <option value="2">two</option> <option value="3">three</option> </select> ``` What I want is to select "o...
I am not (currently) a user of jQuery, but I can tell you that you need to temporarily disconnect your event handler while you repopulate the items or, at the least, set a flag that you then test for and based on its value, handle the change.
Here's the final code that I ended up using, the flag (`changeOnce`) worked great, thanks @Jason. ``` $(function () { var $one = $("#one"); var $two = $("#two"); var selectOptions = []; $("select").each(function (index) { selectOptions[index] = []; for (var i = 0; i < this.options.leng...
Is there any way to repopulate an Html Select's Options without firing the Change event (using jQuery)?
[ "", "javascript", "jquery", "dom", "html-select", "" ]
When writing a switch statement, there appears to be two limitations on what you can switch on in case statements. For example (and yes, I know, if you're doing this sort of thing it probably means your [object-oriented](https://en.wikipedia.org/wiki/Object-oriented_programming) (OO) architecture is iffy - this is jus...
This is my original post, which sparked some debate... **because it is wrong**: > The switch statement is not the same > thing as a big if-else statement. > Each case must be unique and evaluated > statically. The switch statement does > a constant time branch regardless of > how many cases you have. The if-else > sta...
It's important not to confuse the C# switch statement with the CIL switch instruction. The CIL switch is a jump table, that requires an index into a set of jump addresses. This is only useful if the C# switch's cases are adjacent: ``` case 3: blah; break; case 4: blah; break; case 5: blah; break; ``` But of little ...
C# switch statement limitations - why?
[ "", "c#", "switch-statement", "" ]
I was just looking through some information about Google's [protocol buffers](http://code.google.com/apis/protocolbuffers/) data interchange format. Has anyone played around with the code or even created a project around it? I'm currently using XML in a Python project for structured content created by hand in a text e...
If you are looking for user facing interaction, stick with xml. It has more support, understanding, and general acceptance currently. If it's internal, I would say that protocol buffers are a great idea. Maybe in a few years as more tools come out to support protocol buffers, then start looking towards that for a publ...
Protocol buffers are intended to optimize communications between machines. They are really not intended for human interaction. Also, the format is binary, so it could not replace XML in that use case. I would also recommend [JSON](http://en.wikipedia.org/wiki/JSON) as being the most compact text-based format.
Any experiences with Protocol Buffers?
[ "", "python", "xml", "database", "protocol-buffers", "" ]
I am trying to grab the capital letters of a couple of words and wrap them in span tags. I am using [preg\_replace](http://php.net/manual/en/function.preg-replace.php) for extract and wrapping purposes, but it's not outputting anything. ``` preg_replace("/[A-Z]/", "<span class=\"initial\">$1</span>", $str) ```
You need to put the pattern in parentheses `/([A-Z])/`, like this: ``` preg_replace("/([A-Z])/", "<span class=\"initial\">$1</span>", $str) ```
`\0` will also match the entire matched expression without doing an explicit capture using parenthesis. ``` preg_replace("/[A-Z]/", "<span class=\"initial\">\\0</span>", $str) ``` As always, you can go to [php.net/preg\_replace](http://php.net/preg_replace) or php.net/<whatever search term> to search the documentatio...
How can I get at the matches when using preg_replace in PHP?
[ "", "php", "regex", "html-parsing", "preg-replace", "" ]
I am getting back into a bit more .NET after a few-years of not using it full-time and am wondering what the good unit testing packages are these days. I'm familiar with NUnit (a few years ago) and have played briefly around with [IronRuby](https://en.wikipedia.org/wiki/IronRuby), with the goal of getting something li...
There are so many it's crazy. Crazy good, I guess. * For the conservative types (me), [**NUnit**](http://www.nunit.org/) is still available and still more than capable. * For the Microsoft-types, [**MSTest**](http://msdn.microsoft.com/en-us/vstudio/default.aspx) is adequate, but it is slow and clunky compared to NUnit...
Stick to NUnit. Don't go anywhere near MSTest. NUnit + ReSharper is an absolute joy to work with.
.NET unit testing packages
[ "", "c#", ".net", "unit-testing", "testing", "" ]
If I have a variable in C# that needs to be checked to determine if it is equal to one of a set of variables, what is the best way to do this? I'm not looking for a solution that stores the set in an array. I'm more curious to see if there is a solution that uses boolean logic in some way to get the answer. I know I ...
``` bool b = new int[] { 3,7,12,5 }.Contains(5); ```
You can do something similar with .NET 2.0, by taking advantage of the fact that an array of T implements IList<T>, and IList<T> has a Contains method. Therefore the following is equivalent to Corey's .NET 3.5 solution, though obviously less clear: ``` bool b = ((IList<int>)new int[] { 3, 7, 12, 5 }).Contains(5); ``` ...
Most succinct way to determine if a variable equals a value from a 'list' of values
[ "", "c#", "logic", "boolean-logic", "" ]
When I am writing code in Python, I often need to remove items from a list or other sequence type based on some criteria. I haven't found a solution that is elegant and efficient, as removing items from a list you are currently iterating through is bad. For example, you can't do this: ``` for name in names: if nam...
Two easy ways to accomplish just the filtering are: 1. Using `filter`: `names = filter(lambda name: name[-5:] != "Smith", names)` 2. Using list comprehensions: `names = [name for name in names if name[-5:] != "Smith"]` Note that both cases keep the values for which the predicate function evaluates to `True`, ...
You can also iterate backwards over the list: ``` for name in reversed(names): if name[-5:] == 'Smith': names.remove(name) ``` This has the advantage that it does not create a new list (like `filter` or a list comprehension) and uses an iterator instead of a list copy (like `[:]`). Note that although rem...
Elegant way to remove items from sequence in Python?
[ "", "python", "optimization", "set", "series", "" ]
Does the Java language have delegate features, similar to how C# has support for delegates?
Not really, no. You may be able to achieve the same effect by using reflection to get Method objects you can then invoke, and the other way is to create an interface with a single 'invoke' or 'execute' method, and then instantiate them to call the method your interested in (i.e. using an anonymous inner class). You m...
Depending precisely what you mean, you can achieve a similar effect (passing around a method) using the Strategy Pattern. Instead of a line like this declaring a named method signature: ``` // C# public delegate void SomeFunction(); ``` declare an interface: ``` // Java public interface ISomeBehaviour { void Som...
Java Delegates?
[ "", "java", "delegates", "" ]
We currently maintain a suit of MFC applications that are fairly well designed, however the user interface is beginning to look tired and a lot of the code is in need quite a bit of refactoring to tidy up some duplication and/or performance problems. We make use of quite a few custom controls that handle all their own ...
In my company, we are currently using Qt and are very happy with it. I personnally never had to move a MFC-app into using the Qt framework, but here is something which might be of some interest for you : [Qt/MFC Migration Framework](http://www.qtsoftware.com/products/appdev/add-on-products/catalog/3/Windows/qtwinmigr...
(This doesn't really answer your specific questions but...) I haven't personally used Qt, but it's not free for commercial Windows development. Have you looked at [wxWindows](http://wxwindows.org/) which is free? Nice article [here](http://www.linuxjournal.com/article/6778). Just as an aside, if you wanted a single co...
Integrating Qt into legacy MFC applications
[ "", "c++", "qt", "mfc", "" ]
Is there any efficiency difference in an explicit vs implicit inner join? For example: ``` SELECT * FROM table a INNER JOIN table b ON a.id = b.id; ``` vs. ``` SELECT a.*, b.* FROM table a, table b WHERE a.id = b.id; ```
Performance-wise, they are exactly the same (at least in SQL Server). PS: Be aware that the "implicit `OUTER JOIN`" syntax--using `*=` or `=*` in a `WHERE` after using comma--is deprecated since SQL Server 2005. (The "implicit (`CROSS`) `JOIN`" syntax using comma as used in the question is still supported.) [Deprecat...
Personally I prefer the join syntax as its makes it clearer that the tables are joined and how they are joined. Try compare larger SQL queries where you selecting from 8 different tables and you have lots of filtering in the where. By using join syntax you separate out the parts where the tables are joined, to the part...
Explicit vs implicit SQL joins
[ "", "sql", "join", "" ]
I am trying to set a flag to show or hide a page element, but it always displays even when the expression is false. ``` $canMerge = ($condition1 && $condition2) ? 'true' : 'false'; ... <?php if ($canMerge) { ?>Stuff<?php } ?> ``` What's up?
This is broken because 'false' as a string will evaluate to true as a boolean. However, this is an unneeded ternary expression, because the resulting values are simple true and false. This would be equivalent: ``` $canMerge = ($condition1 && $condition2); ```
The value of 'false' is true. You need to remove the quotes: ``` $canMerge = ($condition1 && $condition2) ? true : false; ```
Why is my ternary expression not working?
[ "", "php", "ternary-operator", "" ]
Can you cast a `List<int>` to `List<string>` somehow? I know I could loop through and .ToString() the thing, but a cast would be awesome. I'm in C# 2.0 (so no [LINQ](http://en.wikipedia.org/wiki/Language_Integrated_Query)).
.NET 2.0 has the `ConvertAll` method where you can pass in a converter function: ``` List<int> l1 = new List<int>(new int[] { 1, 2, 3 } ); List<string> l2 = l1.ConvertAll<string>(delegate(int i) { return i.ToString(); }); ```
Updated for 2010 ``` List<int> l1 = new List<int>(new int[] { 1,2,3 } ); List<string> l2 = l1.ConvertAll<string>(x => x.ToString()); ```
Cast List<int> to List<string> in .NET 2.0
[ "", "c#", "generics", "casting", "" ]
I have a class property exposing an internal IList<> through ``` System.Collections.ObjectModel.ReadOnlyCollection<> ``` How can I pass a part of this `ReadOnlyCollection<>` without copying elements into a new array (I need a live view, and the target device is short on memory)? I'm targetting Compact Framework 2.0.
Try a method that returns an enumeration using yield: ``` IEnumerable<T> FilterCollection<T>( ReadOnlyCollection<T> input ) { foreach ( T item in input ) if ( /* criterion is met */ ) yield return item; } ```
These foreach samples are fine, though you can make them much more terse if you're using .NET 3.5 and LINQ: ``` return FullList.Where(i => IsItemInPartialList(i)).ToList(); ```
How can I expose only a fragment of IList<>?
[ "", "c#", "windows-mobile", "compact-framework", ".net-2.0", "" ]
I have a form in C# that has a button that, when clicked, I want the background image to cycle through a set of images (which I have as resources to the project). The images are named '\_1', '\_2', etc. and each time I click the button I want its background image to increment to the next one and go back to "\_1" when i...
Why don't you just put the images in an array?
You could subclass Button and override the BackgroundImage property so you can better keep track of the current resource that represents the image. You might also override the onclick method to internally handle cycling to the next image, though that might be a little weird if the resources are handled outside of your ...
Cycle Button Background Images in C#
[ "", "c#", ".net", "winforms", "" ]
I'm working on a C#/ASP.NET project that has all the javascript files in a /Javascript folder. If I refer to the JS file using this syntax: src="/Javascript/jsfile.js" then the file is correctly picked up if the project is deployed to the root of the URL. However, if this "web site" is deployed to a sub-folder of the ...
If you reference the JS-file in a section that is "runat=server" you could write src="~/Javascript/jsfile.js" and it will always work. You could also do this in your Page\_Load (In your masterpage): ``` Page.ClientScript.RegisterClientScriptInclude("myJsFile", Page.ResolveClientUrl("~/Javascript/jsfile.js")) ```
Try something like this in the Master Page: ``` <script type="text/javascript" src="<%= Response.ApplyAppPathModifier("~/javascript/globaljs.aspx") %>"></script> ``` For whatever reason, I've found the browsers to be quite finicky about the final tag, so just ending the tag with /> doesn't seem to work.
How do I reference a javascript file?
[ "", "asp.net", "javascript", "" ]
I'm currently building a Java app that could end up being run on many different platforms, but primarily variants of Solaris, Linux and Windows. Has anyone been able to successfully extract information such as the current disk space used, CPU utilisation and memory used in the underlying OS? What about just what the J...
You can get some limited memory information from the Runtime class. It really isn't exactly what you are looking for, but I thought I would provide it for the sake of completeness. Here is a small example. Edit: You can also get disk usage information from the java.io.File class. The disk space usage stuff requires Jav...
The [java.lang.management](http://java.sun.com/javase/6/docs/api/java/lang/management/package-summary.html) package does give you a whole lot more info than Runtime - for example it will give you heap memory (`ManagementFactory.getMemoryMXBean().getHeapMemoryUsage()`) separate from non-heap memory (`ManagementFactory.g...
Get OS-level system information
[ "", "java", "memory", "resources", "system", "" ]
I've got a Windows DLL that I wrote, written in C/C++ (all exported functions are 'C'). The DLL works fine for me in VC++. I've given the DLL to another company who do all their development in VB. They seem to be having a problem linking to the functions. I haven't used VB in ten years and I don't even have it installe...
By using `__declspec` for export, the function name will get exported *mangled*, i.e. contain type information to help the C++ compiler resolve overloads. VB6 cannot handle mangled names. As a workaround, you have to de-mangle the names. The easiest solution is to link the DLL file using an [export definition](http://...
Try adding \_\_stdcall at the end ``` #define MYDCC_API __declspec(dllexport) __stdcall ``` We have some C++ dlls that interact with our old VB6 apps and they all have that at the end.
Calling DLL functions from VB6
[ "", "c++", "c", "vb6", "" ]
With the increased power of JavaScript frameworks like YUI, JQuery, and Prototype, and debugging tools like Firebug, doing an application entirely in browser-side JavaScript looks like a great way to make simple applications like puzzle games and specialized calculators. Is there any downside to this other than exposi...
I've written several application in JS including a spreadsheet. Upside: * great language * short code-run-review cycle * DOM manipulation is great for UI design * clients on every computer (and phone) Downside: * differences between browsers (especially IE) * code base scalability (with no intrinsic support for nam...
Another option for developing simple desktop like applications or games in JavaScript is [Adobe AIR](http://www.adobe.com/devnet/air/). You can build your app code in either HTML + JavaScript or using Flash/Flex or a combination of both. It has the advantage of being cross-platform (actually cross-platform, Linux, OS X...
Building Standalone Applications in JavaScript
[ "", "javascript", "deployment", "web-applications", "browser", "" ]
Is there a standard convention (like phpdoc or python's docstring) for commenting C# code so that class documentation can be automatically generated from the source code?
You can use XML style comments, and use tools to pull those comments out into API documentation. Here is an example of the comment style: ``` /// <summary> /// Authenticates a user based on a username and password. /// </summary> /// <param name="username">The username.</param> /// <param name="password">The password...
``` /// <summary> /// /// </summary> /// <param name="strFilePath"></param> ``` <http://msdn.microsoft.com/en-us/magazine/cc302121.aspx>
Is there a standard (like phpdoc or python's docstring) for commenting C# code?
[ "", "c#", "comments", "" ]
Does anyone know how to get IntelliSense to work reliably when working in C/C++ projects? It seems to work for about 1 in 10 files. Visual Studio 2005 seems to be a lot better than 2008. Edit: Whilst not necessarily a solution, the work-around provided here: [How to get IntelliSense to reliably work in Visual Studio ...
I've also realized than Intellisense is sometime 'lost', on some big project. Why? No idea. This is why we have bought [Visual Assist](http://www.wholetomato.com/) (from [Tomato software](http://www.wholetomato.com/)) and disabled Intellisense by deleting the dll feacp.dll in the Visual studio subdirectory (C:\Program...
Native C++ intellisense does not work reliably in any version of Visual Studio. I find there are two common problems: 1) Header file paths are not set-up correctly. When you find a type where intellisense is not working, use the IDE to click through each header file to find the one containing the type. (Right click on...
How to get IntelliSense to reliably work in Visual Studio 2008
[ "", "c++", "c", "visual-studio-2008", "intellisense", "" ]
In the [How Can I Expose Only a Fragment of IList<>](https://stackoverflow.com/questions/39447/how-can-i-expose-only-a-fragment-of-ilist) question one of the answers had the following code snippet: ``` IEnumerable<object> FilteredList() { foreach(object item in FullList) { if(IsItemInPartialList(item))...
The `yield` contextual keyword actually does quite a lot here. The function returns an object that implements the `IEnumerable<object>` interface. If a calling function starts `foreach`ing over this object, the function is called again until it "yields". This is syntactic sugar introduced in **C# 2.0**. In earlier ver...
Iteration. It creates a state machine "under the covers" that remembers where you were on each additional cycle of the function and picks up from there.
What is the yield keyword used for in C#?
[ "", "c#", "yield", "" ]
I can do an `eval("something()");` to execute the code dynamically in JavaScript. Is there a way for me to do the same thing in C#? An example of what I am trying to do is: I have an integer variable (say `i`) and I have multiple properties by the names: "Property1", "Property2", "Property3", etc. Now, I want to perfo...
**DISCLAIMER:** This answer was written back in 2008. The landscape has changed drastically since then. Look at the other answers on this page, especially the one detailing `Microsoft.CodeAnalysis.CSharp.Scripting`. Rest of answer will be left as it was originally posted but is no longer accurate. --- Unfortunately...
Using the Roslyn scripting API. More samples [in the Rolsyn wiki](https://github.com/dotnet/roslyn/blob/main/docs/wiki/Scripting-API-Samples.md). ``` // add NuGet package 'Microsoft.CodeAnalysis.Scripting' using Microsoft.CodeAnalysis.CSharp.Scripting; await CSharpScript.EvaluateAsync("System.Math.Pow(2, 4)") // retu...
How can I evaluate C# code dynamically?
[ "", "c#", "reflection", "properties", "c#-2.0", "" ]
Example: I have two shared objects (same should apply to .dlls). The first shared object is from a third-party library, we'll call it libA.so. I have wrapped some of this with JNI and created my own library, libB.so. Now libB depends on libA. When webstarting, both libraries are places in some webstart working area. M...
Static compilation proved to be the only way to webstart multiple dependent native libraries.
I'm not sure if this would be handled exactly the same way for webstart, but we ran into this situation in a desktop application when dealing with a set of native libraries (dlls in our case). Loading libA before libB should work, unless one of those libraries has a dependency that is unaccounted for and not in the pa...
How can I Java webstart multiple, dependent, native libraries?
[ "", "java", "java-native-interface", "java-web-start", "" ]
I have to develop an application which parses a log file and sends specific data to a server. It has to run on both Linux and Windows. The problem appears when I want to test the log rolling system (which appends .1 to the name of the creates a new one with the same name). On Windows (haven't tested yet on Linux) I ca...
> Is there a way to open file in a non-exclusive way, Yes, using Win32, passing the various FILE\_SHARE\_Xxxx flags to CreateFile. > is it cross platform? No, it requires platform-specific code. Due to annoying backwards compatibility concerns (DOS applications, being single-tasking, assume that nothing can delete ...
It's not the reading operation that's requiring the exclusive mode, it's the rename, because this is essentially the same as moving the file to a new location. I'm not sure but I don't think this can be done. Try copying the file instead, and later delete/replace the old file when it is no longer read.
C++ : Opening a file in non exclusive mode
[ "", "c++", "windows", "linux", "filesystems", "" ]
This most be the second most simple rollover effect, still I don't find any simple solution. **Wanted:** I have a list of items and a corresponding list of slides (DIVs). After loading, the first list item should be selected (bold) and the first slide should be visible. When the user hovers over another list item, tha...
Rather than displaying all slides when JS is off (which would likely break the page layout) I would place inside the switch LIs real A links to server-side code which returns the page with the "active" class pre-set on the proper switch/slide. ``` $(document).ready(function() { switches = $('#switches > li'); sl...
Here's my light-markup jQuery version: ``` <script type="text/javascript" src="jquery.js"></script> <script type="text/javascript"> function switchTo(i) { $('#switches li').css('font-weight','normal').eq(i).css('font-weight','bold'); $('#slides div').css('display','none').eq(i).css('display','block'); } $(document...
How do you swap DIVs on mouseover (jQuery)?
[ "", "javascript", "jquery", "html", "css", "" ]
I've been using PostgreSQL a little bit lately, and one of the things that I think is cool is that you can use languages other than SQL for scripting functions and whatnot. But when is this actually useful? For example, the documentation says that the main use for PL/Perl is that it's pretty good at text manipulation....
"isn't that [text manipulation] more of something that should be programmed into the application?" Usually, yes. The generally accepted "[three-tier](http://en.wikipedia.org/wiki/Multitier_architecture)" application design for databases says that your logic should be in the middle tier, between the client and the data...
@Mike: this kind of thinking makes me nervous. I've heard to many times "this should be infinitely portable", but when the question is asked: do you actually foresee that there will be any porting? the answer is: no. Sticking to the lowest common denominator can really hurt performance, as can the introduction of abst...
Languages other than SQL in postgres
[ "", "sql", "database", "postgresql", "trusted-vs-untrusted", "" ]
I'm looking for a simple way to encrypt my soap communication in my C# Web-Service. I was looking into [WSE 3.0](http://www.google.com/url?sa=t&ct=res&cd=1&url=http%3A%2F%2Fwww.microsoft.com%2Fdownloads%2Fdetails.aspx%3Ffamilyid%3D018a09fd-3a74-43c5-8ec1-8d789091255d&ei=x1isSPTUO4bS0QXsjIzWAw&usg=AFQjCNHn7aOkIXoysM1wo...
I think this can help; last year we used this to compress the webservices and it performed very well, I believe it could be enhanced with encryption classes; [Creating Custom SOAP Extensions - Compression Extension](http://www.mastercsharp.com/article.aspx?ArticleID=86&&TopicID=7)
Anything you do to provide "encryption" that isn't using SSL/TLS is likely to be vulnerable. Now you have to ask yourself, is it worth burning dev hours you could be spending on features on a rubber-chicken security measure? Maybe it is. .NET APIs like DPAPI and the Win32 crypt32 API make it easy to encrypt blobs of d...
Encryption in C# Web-Services
[ "", "c#", "web-services", "security", "encryption", "" ]
For those of us who use standard shared hosting packages, such as GoDaddy or Network Solutions, how do you handle datetime conversions when your hosting server (PHP) and MySQL server are in different time zones? Also, does anybody have some best practice advice for determining what time zone a visitor to your site is ...
As of PHP 5.1.0 you can use [*date\_default\_timezone\_set()*](http://www.php.net/manual/en/function.date-default-timezone-set.php) function to set the default timezone used by all date/time functions in a script. For MySql (quoted from [MySQL Server Time Zone Support](http://dev.mysql.com/doc/refman/4.1/en/time-zone-...
Store everything as UTC. You can do conversions at the client level, or on the server side using client settings. [php - date](http://us.php.net/date) [mysql - utc-timestamp](http://dev.mysql.com/doc/refman/5.0/en/date-and-time-functions.html#function_utc-timestamp)
Dealing with PHP server and MySQL server in different time zones
[ "", "php", "mysql", "datetime", "date", "timezone", "" ]
I have a fairly small MySQL database (a Textpattern install) on a server that I do not have SSH access to (I have FTP access only). I need to regularly download the live database to my local dev server on demand; i.e., I would like to either run a script and/or have a cron job running. What are some good ways of doing ...
Since you can access your database remotely, you can use mysqldump from your windows machine to fetch the remote database. From commandline: ``` cd "into mysql directory" mysqldump -u USERNAME -p -h YOUR_HOST_IP DATABASE_TO_MIRROR >c:\backup\database.sql ``` The program will ask you for the database password and then...
Here's what I use. This dumps the database from the live server while uploads it to the local server. `mysqldump -hlive_server_addresss -ulive_server_user -plive_server_password --opt --compress live_server_db | mysql -ulocal_server_user -plocal_server_password local_server_db` You can run this from a **bat** file. Yo...
How to download a live MySQL db into a local test db on demand, without SSH?
[ "", "php", "ruby", "database", "mysql", "" ]
I completely understand the concept of expression trees, but I am having a hard time trying to find situations in which they are useful. Is there a specific instance in which expression trees can be applied? Or is it only useful as a transport mechanism for code? I feel like I am missing something here. Thanks!
> Or is it only useful as a transport mechanism for code? It's useful as an *execution mechanism* for code. Using the [interpreter pattern](http://en.wikipedia.org/wiki/Interpreter_pattern), expression trees can directly be interpreted. This is useful because it's very easy and fast to implement. Such interpreters are...
Some unit test mocking frameworks make use of expression trees in order to set up strongly typed expectations/verifications. Ie: ``` myMock.Verify(m => m.SomeMethod(someObject)); // tells moq to verify that the method // SomeMethod was called with ...
What are some instances in which expression trees are useful?
[ "", "c#", "expression", "" ]
I need to find out how to format numbers as strings. My code is here: ``` return str(hours)+":"+str(minutes)+":"+str(seconds)+" "+ampm ``` Hours and minutes are integers, and seconds is a float. the str() function will convert all of these numbers to the tenths (0.1) place. So instead of my string outputting "5:30:59...
Starting with Python 3.6, formatting in Python can be done using [formatted string literals](https://docs.python.org/3/whatsnew/3.6.html#whatsnew36-pep498) or *f-strings*: ``` hours, minutes, seconds = 6, 56, 33 f'{hours:02}:{minutes:02}:{seconds:02} {"pm" if hours > 12 else "am"}' ``` or the [`str.format`](https://d...
The OP & accepted answer focus on formatting time, but the OP *question* itself discusses formatting numbers to strings in Python. In many cases, the output requires additional data fields be included along with timestamps, all of which include formatting numbers as strings. Below are a variety of *non time-based* exa...
Format numbers to strings in Python
[ "", "python", "string-formatting", "" ]
What are the best practices to consider when catching exceptions and re-throwing them? I want to make sure that the `Exception` object's `InnerException` and stack trace are preserved. Is there a difference between the following code blocks in the way they handle this? ``` try { //some code } catch (Exception ex) ...
The way to preserve the stack trace is through the use of the `throw;` This is valid as well ``` try { // something that bombs here } catch (Exception ex) { throw; } ``` `throw ex;` is basically like throwing an exception from that point, so the stack trace would only go to where you are issuing the `throw ex;`...
If you throw a new exception with the initial exception you will preserve the initial stack trace too.. ``` try{ } catch(Exception ex){ throw new MoreDescriptiveException("here is what was happening", ex); } ```
Best practices for catching and re-throwing .NET exceptions
[ "", "c#", ".net", "exception", "rethrow", "" ]
Google is not being my friend - it's been a long time since my stats class in college...I need to calculate the start and end points for a trendline on a graph - is there an easy way to do this? (working in C# but whatever language works for you)
Given that the trendline is straight, find the slope by choosing any two points and calculating: (A) slope = (y1-y2)/(x1-x2) Then you need to find the offset for the line. The line is specified by the equation: (B) y = offset + slope\*x So you need to solve for offset. Pick any point on the line, and solve for offs...
Thanks to all for your help - I was off this issue for a couple of days and just came back to it - was able to cobble this together - not the most elegant code, but it works for my purposes - thought I'd share if anyone else encounters this issue: ``` public class Statistics { public Trendline CalculateLinearRegre...
How do I calculate a trendline for a graph?
[ "", "c#", "math", "graph", "" ]
I am storing a PNG as an embedded resource in an assembly. From within the same assembly I have some code like this: ``` Bitmap image = new Bitmap(typeof(MyClass), "Resources.file.png"); ``` The file, named "file.png" is stored in the "Resources" folder (within Visual Studio), and is marked as an embedded resource. ...
This will get you a string array of all the resources: ``` System.Reflection.Assembly.GetExecutingAssembly().GetManifestResourceNames(); ```
I find myself forgetting how to do this every time as well so I just wrap the two one-liners that I need in a little class: ``` public class Utility { /// <summary> /// Takes the full name of a resource and loads it in to a stream. /// </summary> /// <param name="resourceName">Assuming an embedded reso...
How can I discover the "path" of an embedded resource?
[ "", "c#", ".net", "resources", "" ]
How do I use JUnit to test a class that has internal private methods, fields or nested classes? It seems bad to change the access modifier for a method just to be able to run a test.
If you have somewhat of a legacy **Java** application, and you're not allowed to change the visibility of your methods, the best way to test private methods is to use [reflection](http://en.wikipedia.org/wiki/Reflection_%28computer_programming%29). Internally we're using helpers to get/set `private` and `private stati...
The best way to test a private method is via another public method. If this cannot be done, then one of the following conditions is true: 1. The private method is dead code 2. There is a design smell near the class that you are testing 3. The method that you are trying to test should not be private
How do I test a class that has private methods, fields or inner classes?
[ "", "java", "unit-testing", "junit", "tdd", "" ]
I'm looking for a good way to perform multi-row inserts into an Oracle 9 database. The following works in MySQL but doesn't seem to be supported in Oracle. ``` INSERT INTO TMP_DIM_EXCH_RT (EXCH_WH_KEY, EXCH_NAT_KEY, EXCH_DATE, EXCH_RATE, FROM_CURCY_CD, TO_CURCY_CD, EXCH_EFF_DATE, EXCH_EFF_END_DATE, EXCH...
This works in Oracle: ``` insert into pager (PAG_ID,PAG_PARENT,PAG_NAME,PAG_ACTIVE) select 8000,0,'Multi 8000',1 from dual union all select 8001,0,'Multi 8001',1 from dual ``` The thing to remember here is to use the `from dual` statement.
In Oracle, to insert multiple rows into table t with columns col1, col2 and col3 you can use the following syntax: ``` INSERT ALL INTO t (col1, col2, col3) VALUES ('val1_1', 'val1_2', 'val1_3') INTO t (col1, col2, col3) VALUES ('val2_1', 'val2_2', 'val2_3') INTO t (col1, col2, col3) VALUES ('val3_1', 'val3_2'...
Best way to do multi-row insert in Oracle?
[ "", "sql", "oracle", "sql-insert", "oracle9i", "" ]
The following code works great in IE, but not in FF or Safari. I can't for the life of me work out why. The code is *supposed* to disable radio buttons if you select the "Disable 2 radio buttons" option. It should enable the radio buttons if you select the "Enable both radio buttons" option. These both work... However...
To get FF to mimic IE's behavior when using the keyboard, you can use the keyup event on the select box. In your example (I am not a fan of attaching event handlers this way, but that's another topic), it would be like this: ``` <select name="user" id="selUser" onchange="javascript:SetLocationOptions()" onkeyup="javas...
Well, IE has a somewhat non-standard object model; what you're doing shouldn't work but you're getting away with it because IE is being nice to you. In Firefox and Safari, document.frm in your code evaluates to undefined. You need to be using id values on your form elements and use `document.getElementById('whatever')...
How can I enable disabled radio buttons?
[ "", "javascript", "html", "radio-button", "" ]
I'm using JBoss Seam Framework, but it's seems to me isn't very popular among java developers. I want to know how many java programmers here are using it, and in what kind of projects. Is as good as django, or RoR?
In our [JBoss Seam in Action presentation](http://www.lunatech-research.com/archives/2007/12/14/javapolis-2007-seam) at the Javapolis conference last year, my colleague and I said that 'Seam is the next Struts'. This needed some explanation, which I later wrote-up as [Seam is the new Struts](http://www.lunatech-researc...
I have used JBoss Seam now for about a year and like it very much over Spring. Unfortunately, I don't use this at work, more for side projects and personal projects. For me, it saves me a lot of time developing new projects for clients. And, one big reason I use it primarily is, the tight integration with each layer an...
How Popular is the Seam Framework
[ "", "java", "frameworks", "seam", "" ]
Which C#/.NET Dependency Injection frameworks are worth looking into? And what can you say about their complexity and speed.
**edit** (not by the author): There is a comprehensive list of IoC frameworks available at <https://github.com/quozd/awesome-dotnet/blob/master/README.md#ioc>: * [Castle Windsor](https://github.com/castleproject/Windsor) - Castle Windsor is best of breed, mature Inversion of Control container available for .NET and Si...
It depends on what you are looking for, as they each have their pros and cons. 1. **`Spring.NET`** is the most mature as it comes out of Spring from the Java world. Spring has a very rich set of framework libraries that extend it to support Web, Windows, etc. 2. **`Castle Windsor`** is one of the most widely used in t...
Which .NET Dependency Injection frameworks are worth looking into?
[ "", "c#", ".net", "dependency-injection", "inversion-of-control", "" ]
I'm trying to learn C. As a C# developer, my IDE is Visual Studio. I've heard this is a good environment for C/C++ development. However, it seems no matter what little thing I try to do, intuition fails me. Can someone give good resources for how to either: * learn the ins and out of C in Visual Studio * recommend a b...
Answering the purely subject question "recommend me a better C IDE and compiler" I find [Ming32w and Code::blocks (now with combined installer)](http://www.codeblocks.org/) very useful on windows but YMMV as you are obviously used to the MS IDE and are just struggling with C. May I suggest you concentrate on console a...
well you can use visual studio just fine take a look at here man <http://www.daniweb.com/forums/thread16256.html> Go to View Menu select Solution Explorer or CTRL+ ALT +L Then Select The project that your are developing and right click on that. Then select the Properties from the submenu. Then select the Configurat...
C on Visual Studio
[ "", "c++", "c", "ide", "compiler-construction", "" ]
I am about to reenter the MFC world after years away for a new job. What resources to people recommend for refreshing the memory? I have been doing mainly C# recently. Also any MFC centric websites or blogs that people recommend?
* For blogs: Your best bet would be the [Visual C++ Team Blog](http://blogs.msdn.com/vcblog/default.aspx). * For books: [Programming Windows with MFC](https://rads.stackoverflow.com/amzn/click/com/1572316950) is one of the best book on the subject. * For tutorials: Simply [search google for various tutorials on MFC](ht...
The best: [The Code Project](http://www.codeproject.com/)
MFC resources / links
[ "", "c++", "c", "mfc", "" ]
How do you find a memory leak in Java (using, for example, JHat)? I have tried to load the heap dump up in JHat to take a basic look. However, I do not understand how I am supposed to be able to find the root reference ([ref](https://stackoverflow.com/questions/104/anatomy-of-a-memory-leak)) or whatever it is called. B...
I use following approach to finding memory leaks in Java. I've used jProfiler with great success, but I believe that any specialized tool with graphing capabilities (diffs are easier to analyze in graphical form) will work. 1. Start the application and wait until it get to "stable" state, when all the initialization i...
Questioner here, I have got to say getting a tool that does not take 5 minutes to answer any click makes it a lot easier to find potential memory leaks. Since people are suggesting several tools ( I only tried visual wm since I got that in the JDK and JProbe trial ) I though I should suggest a free / open source tool ...
How to find a Java Memory Leak
[ "", "java", "memory", "memory-leaks", "jhat", "" ]
What is the best way of creating an alphabetically sorted list in Python?
Basic answer: ``` mylist = ["b", "C", "A"] mylist.sort() ``` This modifies your original list (i.e. sorts in-place). To get a sorted copy of the list, without changing the original, use the [`sorted()`](http://docs.python.org/library/functions.html#sorted) function: ``` for x in sorted(mylist): print x ``` Howe...
It is also worth noting the [`sorted()`](https://docs.python.org/3/library/functions.html#sorted "sorted") function: ``` for x in sorted(list): print x ``` This returns a new, sorted version of a list without changing the original list.
How to sort a list of strings?
[ "", "python", "string", "sorting", "" ]
I need a C# profiler. Although I'm not averse to paying for one, something which is free or at least with a trial version would be ideal since it takes time to raise a purchase order. Any recommendations?
You can try the following: * [nprof](http://nprof.sourceforge.net/Site/Description.html) (free but kinda old) * [ProfileSharp](http://sourceforge.net/projects/profilesharp/) (open source) * [.Net Memory Profiler](http://memprofiler.com/) (really good for memory leaks, there's a trial version) --- Edit: Nprof has bee...
I used [Ants profiler](http://www.red-gate.com/products/dotnet-development/ants-performance-profiler/) on a large c# project a year and a half ago. It really performed very nicely for what it cost, and even outperformed a few of the more expensive competitors. It calculates cost on with almost a line by line resolutio...
Any decent C# profilers out there?
[ "", "c#", ".net", "profiling", "profiler", "" ]
My project is based on spring framework 2.5.4. And I try to add aspects for some controllers (I use aspectj 1.5.3). I've enabled auto-proxy in application-servlet.xml, just pasted these lines to the end of the xml file: ``` <aop:aspectj-autoproxy /> <bean id="auditLogProcessor" class="com.example.bg.web.utils.AuditLo...
Your breakpoints aren't being hit because you are using Spring's AOP Proxies. See [understanding-aop-proxies](http://static.springframework.org/spring/docs/2.5.x/reference/aop.html#aop-understanding-aop-proxies) for a description of how AOP Proxies are special. Basically, the MVC framework is going to call the `handle...
AspectJ doesn't work well with classes in the Spring Web MVC framework. [Read the bottom of the "Open for extension..." box on the right side of the page](http://static.springframework.org/spring/docs/2.0.x/reference/mvc.html) Instead, take a look at the [HandlerInterceptor](http://static.springframework.org/spring/do...
Aspectj doesn't catch all events in spring framework?
[ "", "java", "spring", "spring-aop", "" ]
I'm creating an application which lets you define events with a time frame. I want to automatically fill in the end date when the user selects or changes the start date. I can't quite figure out, however, how to get the difference between the two times, and then how to create a new end Date using that difference.
In JavaScript, dates can be transformed to the number of milliseconds since the epoc by calling the `getTime()` method **or** just using the date in a numeric expression. So to get the difference, just subtract the two dates. To create a new date based on the difference, just pass the number of milliseconds in the co...
JavaScript perfectly supports date difference out of the box <https://jsfiddle.net/b9chris/v5twbe3h/> ``` var msMinute = 60*1000, msDay = 60*60*24*1000, a = new Date(2012, 2, 12, 23, 59, 59), b = new Date("2013 march 12"); console.log(Math.floor((b - a) / msDay) + ' full days between'); // 364 console....
How do I get the difference between two Dates in JavaScript?
[ "", "javascript", "date", "" ]
We’ve found that the unit tests we’ve written for our C#/C++ code have really paid off. But we still have thousands of lines of business logic in stored procedures, which only really get tested in anger when our product is rolled out to a large number of users. What makes this worse is that some of these stored proced...
I ran into this same issue a while back and found that if I created a simple abstract base class for data access that allowed me to inject a connection and transaction, I could unit test my sprocs to see if they did the work in SQL that I asked them to do and then rollback so none of the test data is left in the db. T...
Have you tried [DBUnit](http://dbunit.sourceforge.net/)? It's designed to unit test your database, and just your database, without needing to go through your C# code.
Has anyone had any success in unit testing SQL stored procedures?
[ "", "sql", "unit-testing", "linq-to-sql", "" ]
Is there a tag in HTML that will only display its content if JavaScript is enabled? I know `<noscript>` works the opposite way around, displaying its HTML content when JavaScript is turned off. But I would like to only display a form on a site if JavaScript is available, telling them why they can't use the form if they...
You could have an invisible div that gets shown via JavaScript when the page loads.
Easiest way I can think of: ``` <html> <head> <noscript><style> .jsonly { display: none } </style></noscript> </head> <body> <p class="jsonly">You are a JavaScript User!</p> </body> </html> ``` No document.write, no scripts, pure CSS.
Is there a HTML opposite to <noscript>?
[ "", "javascript", "html", "noscript", "" ]
How can one determine, in code, how long the machine is locked? Other ideas outside of C# are also welcome. --- I like the windows service idea (and have accepted it) for simplicity and cleanliness, but unfortunately I don't think it will work for me in this particular case. I wanted to run this on my workstation at...
I hadn't found this before, but from any application you can hookup a SessionSwitchEventHandler. Obviously your application will need to be running, but so long as it is: ``` Microsoft.Win32.SystemEvents.SessionSwitch += new Microsoft.Win32.SessionSwitchEventHandler(SystemEvents_SessionSwitch); void SystemEvents_Sess...
I would create a Windows Service (a visual studio 2005 project type) that handles the OnSessionChange event as shown below: ``` protected override void OnSessionChange(SessionChangeDescription changeDescription) { if (changeDescription.Reason == SessionChangeReason.SessionLock) { //I left my desk ...
Programmatically Determine a Duration of a Locked Workstation?
[ "", "c#", "windows", "" ]
I've got a menu in Python. That part was easy. I'm using `raw_input()` to get the selection from the user. The problem is that `raw_input` (and input) require the user to press `Enter` after they make a selection. Is there any way to make the program act immediately upon a keystroke? Here's what I've got so far: ``` ...
**On Windows:** ``` import msvcrt answer=msvcrt.getch() ```
**On Linux:** * set raw mode * select and read the keystroke * restore normal settings ``` import sys import select import termios import tty def getkey(): old_settings = termios.tcgetattr(sys.stdin) tty.setraw(sys.stdin.fileno()) select.select([sys.stdin], [], [], 0) answer = sys.stdin.read(1) t...
How do I make a menu that does not require the user to press [enter] to make a selection?
[ "", "python", "" ]
In .net frameworks 1.1, I use ``` System.Configuration.ConfigurationSettings.AppSettings["name"]; ``` for application settings. But in .Net 2.0, it says ConfigurationSettings is obsolete and to use ConfigurationManager instead. So I swapped it out with this: ``` System.Configuration.ConfigurationManager.AppSettings[...
You have to reference the System.configuration assembly (note the lowercase) I don't know why this assembly is not added by default to new projects on Visual Studio, but I find myself having the same problem every time I start a new project. I always forget to add the reference.
If you're just trying to get a value from the app.config file, you might want to use: ``` ConfigurationSettings.AppSettings["name"]; ``` That works for me, anyways. /Jonas
Help accessing application settings using ConfigurationManager
[ "", "c#", ".net", ".net-2.0", "" ]
How do you OCR an tiff file using Tesseract's interface in c#? Currently I only know how to do it using the executable.
The source code seemed to be geared for an executable, you might need to rewire stuffs a bit so it would build as a DLL instead. I don't have much experience with Visual C++ but I think it shouldn't be too hard with some research. My guess is that someone might have had made a library version already, you should try Go...
Take a look at [tessnet](http://www.pixel-technology.com/freeware/tessnet2/)
OCR with the Tesseract interface
[ "", "c#", "ocr", "tesseract", "" ]
In your applications, what's a "long time" to keep a transaction open before committing or rolling back? Minutes? Seconds? Hours? and on which database?
@lomaxx, @ChanChan: to the best of my knowledge cursors are only a problem on SQL Server and Sybase (T-SQL variants). If your database of choice is Oracle, then cursors are your friend. I've seen a number of cases where the use of cursors has actually improved performance. Cursors are an incredibly useful mechanism and...
I'm probably going to get flamed for this, but you really should try and avoid using cursors as they incur a serious performance hit. If you must use it, you should keep it open the absolute minimum amount of time possible so that you free up the resources being blocked by the cursor ASAP.
What is a "reasonable" length of time to keep a SQL cursor open?
[ "", "sql", "cursors", "" ]