Prompt
stringlengths
10
31k
Chosen
stringlengths
3
29.4k
Rejected
stringlengths
3
51.1k
Title
stringlengths
9
150
Tags
listlengths
3
7
I have a JavaScript snippet that runs very well on Firefox and Safari, but refuses to run on IE: ``` var drop= function(id) { if(document.getElementById("select1").value == "Ficha de pediatria"){ top.location.href = "print.jsp?id="+id+"&type=2"; } else if(document.getElementById("select1").value == "Ficha...
[EDIT] Sorry. I introduced an error with my first post by not carefully looking at how you are constructing your url. I shouldn't have removed the `id` parameter. I've updated the code and it should work now. Try this instead: ``` function drop(ctl,id) { var value = ctl.options[ctl.selectedIndex].value; if(val...
IE doesn't like the way you're grabbing the value of the select ``` document.getElementById("select1").value ``` This is saying "give me the text that's in the value attribute of the selected option in the select element with the id *select1*. Your options don't have any values. When Firefox and Safari encounter this...
Javascript not running on IE
[ "", "javascript", "internet-explorer", "" ]
Can someone explain how exactly prepared connection pooling using dbcp can be used? (with some example code if possible). I've figured out how to turn it on - passing a KeyedObjectPoolFactory to the PoolableConnectionFactory. But how should the specific prepared statements be defined after that? Right now I'm only usin...
Well talking about getting connection from the pool vs getting "not-pooled" connection, do you have any change in your code :)? I bet you do not. Same way with prepared statements. Your code should not change. So, there is no useful code example to this. You should read docs for your JDBC Datasource implementation and...
Here's basic code I use. ``` GenericObjectPool connectionPool = new GenericObjectPool(null); connectionPool.setMinEvictableIdleTimeMillis(1000 * 60 * 30); connectionPool.setTimeBetweenEvictionRunsMillis(1000 * 60 * 30); connectionPool.setNumTestsPerEvictionRun(3); connectionPool.setTestOnBorrow(tru...
Using PreparedStatement pooling in dbcp
[ "", "java", "prepared-statement", "connection-pooling", "apache-commons-dbcp", "" ]
Say for example I have the following string: var testString = "Hello, world"; And I want to call the following methods: var newString = testString.Replace("Hello", "").Replace("world", ""); Is there some code construct that simplifies this, so that I only have to specify the Replace method once, and can specify a b...
Create a function to which you pass the `String` and a `Dictionary(String, String)`. Iterate over each item in the Dictionary and `InputString.Replace(DictionaryEntry.Key, DictionaryEntry.Value)`. Return the string with the replaced values. But I'd just do `.Replace.Replace` if it's only 2 times...
Another option to make this more readable is to add new lines and proper indentation (which would be the better option to me): ``` var newString = testString.Replace("Hello", "") .Replace("world", "") .Replace("and", "") .Replace("something"...
Is there a sweet, efficient way to call the same method twice with two different arguments?
[ "", "c#", "arrays", "parameters", "methods", "call", "" ]
I'm trying to reorder/group a set of results using SQL. I have a few fields (which for the example have been renamed to something a bit less specific), and each logical group of records has a field which remains constant - the address field. There are also fields which are present for each address, these are the same f...
Assuming that the column headings "john", "lucy" etc are fixed, you can group by the address field and use if() functions combined with aggregate operators to get your results: ``` select max(if(forename='john',surname,null)) as john, max(if(forename='lucy',surname,null)) as lucy, max(if(forename='jenny'...
I'm not certain, but I think what you're trying to do is GROUP BY. ``` SELECT Address,Name FROM Table GROUP BY Name ``` if you want to select more columns, make sure they're included in the GROUP BY clause. Also, you can now do aggregate functions, like MAX() or COUNT().
Remapping/Concatenating in SQL
[ "", "sql", "mysql", "concatenation", "" ]
It's a simple case of a javascript that continuously asks "are there yet?" Like a four year old on a car drive.. But, much like parents, if you do this too often or, with too many kids at once, the server will buckle under pressure.. How do you solve the issue of having a webpage that looks for new content in the orde...
stackoverflow does it some way, don't know how though. The more standard way would indeed be the javascript that looks for new content every few seconds. A more advanced way would use a [push-like](http://en.wikipedia.org/wiki/Push_technology) technique, by using [Comet](http://en.wikipedia.org/wiki/Comet_(programmin...
In Java I used Ajax library (DWR) using Comet technology - I think you should search for library in PHP using it. The idea is that server is sending one very long Http response and when it has something to send to the client it ends it and send new response with updated data. Using it client doens't have to ping server...
Ajax "Is there new content? If so, update page" - How to do this without breaking the server?
[ "", "javascript", "mysql", "ajax", "comet", "" ]
I'm working on a Spring MVC project, and I have unit tests for all of the various components in the source tree. For example, if I have a controller `HomeController`, which needs to have a `LoginService` injected into it, then in my unit test `HomeControllerTest` I simply instantiate the object as normal (outside of S...
I can't speak to being a best practice, but here's what I've done in the past. **Unit tests:** * Create unit tests for non-trivial beans (ie, most of your Spring related beans) * Use Mocks for injected services where practical (ie, most if not all the time). * Use a standard naming convention for these tests in the p...
A few isolated points: Yes, it's a common approach to Spring testing - seperate unit tests and integration tests where the former doesn't load any Spring context. For your unit tests, maybe consider mocking to ensure that your tests are focussed on one isolated module. If you're tests are wiring in a ton of dependen...
Unit tests vs integration tests with Spring
[ "", "java", "tdd", "junit", "spring-mvc", "integration-testing", "" ]
I'm writing a C++ program that doesn't work (I get a segmentation fault) when I compile it with optimizations (options -O1, -O2, -O3, etc.), but it works just fine when I compile it without optimizations. Is there any chance that the error is in my code? or should I assume that this is a bug in GCC? My GCC version is...
Now that you posted the code fragment and a working workaround was found (@Windows programmer's answer), I can say that perhaps what you are looking for is `-ffloat-store`. > -ffloat-store > > Do not store floating point variables in registers, and inhibit other options that might change whether a floating point value...
I would assume your code is wrong first. Though it is hard to tell. Does your code compile with 0 warnings? ``` g++ -Wall -Wextra -pedantic -ansi ```
GCC: program doesn't work with compilation option -O3
[ "", "c++", "gcc", "compilation", "" ]
I use *lazy connection* to connect to my DB within my DB object. This basically means that it doesn't call mysql\_connect() until the first query is handed to it, and it subsequently skips reconnecting from then on after. Now I have a method in my DB class called `disconnectFromDB()` which pretty much calls `mysql_clo...
As far as I know, unless you are using persistent connections, your MySQL connection will be closed at the end of the page execution. Therefore, you calling disconnect will add nothing and because you do the lazy connection, may cause a second connection to be created if you or another developer makes a mistake and di...
I just read this comment on PHP website regarding persistent connection and it might be interesting to know: > Here's a recap of important reasons > NOT to use persistent connections: > > * When you lock a table, normally it is unlocked when the connection > closes, but since persistent > connections do not close,...
PHP mySQL - When is the best time to disconnect from the database?
[ "", "php", "mysql", "" ]
What is the accepted practice for indenting SQL statements? How should this example be indented? ``` SELECT column1, column2 FROM table1 WHERE column3 IN ( SELECT TOP(1) column4 FROM table2 INNER JOIN table3 ON table2.column1 = table3.column1 ) ```
``` SELECT column1 , column2 FROM table1 WHERE column3 IN ( SELECT TOP(1) column4 FROM table2 INNER JOIN table3 ON table2.column1 = table3.column1 ) ``` I like to have all **"," in front**, this way I never search them when an error at line X from the SQL editor. --- ### This is an example for t...
``` SELECT column1, column2 FROM table WHERE column3 IN ( SELECT TOP(1) column4 FROM table2 INNER JOIN table3 ON table2.column1 = table3.column1 ) ``` This is pretty short and easy to read. I'd make adjustments if there were more columns selected or more join conditions.
SQL Statement indentation good practice
[ "", "sql", "coding-style", "indentation", "" ]
What's the best way to output the public contents of an object to a human-readable file? I'm looking for a way to do this that would not require me to know of all the members of the class, but rather use the compiler to tell me what members exist, and what their names are. There have to be macros or something like that...
Take a look at [this library](http://s11n.net) .
What you're looking for is "[reflection](<http://en.wikipedia.org/wiki/Reflection_(computer_science)#C.2B.2B)>". I found two promising links with a Google search for "C++ reflection": <http://www.garret.ru/cppreflection/docs/reflect.html> <http://seal-reflex.web.cern.ch/seal-reflex/index.html>
Best way to take a snapshot of an object to a file
[ "", "c++", "visual-studio-2005", "file-io", "" ]
I am looking for the highest key value (a defined by the comparison operator) of a std::map. Is this guaranteed to be ``` map.rbegin()->first ``` ? (I am a bit shaky on reverse iterators, and how much freedom there is in the implementation of std::map) If not, please advise. I cannot change the data structure.
Yes. Map is a sorted container, the reverse iterator must return the elements in reverse (i.e. decreasing) order of their keys. [Edit: as Charles Bailey points out in his answer, your code gives the greatest key **if it exists** - i.e. if the map is non-empty]
Yes, but remember to check that `map.rbegin() != map.rend()`.
Last key in a std::map
[ "", "c++", "iterator", "stdmap", "" ]
How do I extract a tar (or tar.gz, or tar.bz2) file in Java?
*Note:* This functionality was later published through a separate project, Apache Commons Compress, as [described in another answer.](https://stackoverflow.com/a/7556307/3474) This answer is out of date. --- I haven't used a tar API directly, but tar and bzip2 are implemented in Ant; you could borrow their implementa...
You can do this with the Apache Commons Compress library. You can download the 1.2 version from <http://mvnrepository.com/artifact/org.apache.commons/commons-compress/1.2>. Here are two methods: one that unzips a file and another one that untars it. So, for a file <fileName>tar.gz, you need to first unzip it and after...
How do I extract a tar file in Java?
[ "", "java", "archive", "tar", "" ]
I have an app that writes messages to the event log. The source I'm passing in to EventLog.WriteEntry does not exist, so the Framework tries to create the source by adding it to the registry. It works fine if the user is an Admin by I get the following whe the user is not an admin: "System.Security.SecurityException :...
For your update I have found something that might help you : ``` Run regedt32 Navigate to the following key: HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Services\Eventlog\Security Right click on this entry and select Permissions Add the ASPNET user Give it Read permission 2. Change settings in machine.config file Ru...
The "non-programming way" is to grant the user that user your web application/web service with access to registry (Event Log are written in the event log).
Event Log SecurityException for Web Application?
[ "", "c#", "events", ".net-2.0", "c#-2.0", "" ]
I am reading log files but not all lines want to be processed straight away. I am using a queue / buffer to store the lines while they wait to be processed. This queue is regularly scanned for particular lines - when they are found, they are removed from the queue (they can be anywhere in it). When there isn't a parti...
LinkedHashSet might be of interest. It is effectively a HashSet but it also maintains a LinkedList to allow a predictable iteration order - and therefore can also be used as a FIFO queue, with the nice added benefit that it can't contain duplicate entries. Because it is a HashSet too, searches (as opposed to scans) ca...
A LinkedList would probably be most appropriate. It has all the requested properties, and allows links to be removed from the middle in constant time, rather than the linear time required for an ArrayList. If you have some specific strategy for finding the next element to remove, a PriorityQueue or even a sorted set m...
Best Collection To Use?
[ "", "java", "performance", "collections", "queue", "buffer", "" ]
During navigation of the `java.lang.reflect.Method` class I came across the method `isBridge`. Its Javadoc says that it returns true only if the Java spec declares the method as true. Please help me understand what this is used for! Can a custom class declare its method as a bridge if required?
A bridge method may be created by the compiler when extending a parameterized type whose methods have parameterized arguments. You can find in this class [BridgeMethodResolver](https://fisheye.springsource.org/browse/spring-framework/spring-core/src/main/java/org/springframework/core/BridgeMethodResolver.java?r=02a447...
The example shown there (quoted from the JLS) makes it sound like bridge methods are only used in situations where raw types are used. Since this is not the case, I thought I'd pipe in with an example where bridge methods are used for totally type-correct generic code. Consider the following interface and function: `...
What Method.isBridge used for?
[ "", "java", "api", "reflection", "" ]
``` import sys words = { 1 : 'one', 2 : 'two', 3 : 'three', 4 : 'four', 5 : 'five', 6 : 'six', 7 : 'seven', 8 : 'eight', 9 : 'nine', 10 : 'ten', 11 : 'eleven', 12 : 'twelve', 13 : 'thirteen', 14 : 'fourteen', 15 : 'fifteen', 16 : 'sixteen', 17 : 'seve...
You can't group digits into "segments" going from left-to-right. The `range(0,len(),3)` is not going to work out well. You'll have to write the same algorithm for inserting digit separators. You start from the right, picking off segments of digits. What's left over (on the left, get it?) will be 1, 2 or 3 digits. You'...
Two improvements come to mind: * 40 is spelled "forty", not "fourty" * your program needs unit tests Have a look at the Python [doctest](http://python.org/doc/2.5/lib/module-doctest.html) and [unittest](http://python.org/doc/2.5/lib/module-unittest.html) modules.
How can I improve this number2words script
[ "", "python", "" ]
Our coding standards ask that we minimise the use of C# var (suggests limiting it's use to being in conjunction with Linq). However there are times when using generics where it's reasonably convenient e.g. ``` Dictionary<DateTime, Dictionary<string, float>> allValues = ... // ... foreach (var dateEntry in allValue) ``...
I've got ReSharper 4.1, and it does offer this option (in either direction). Actually, I'd recommend challenging the standard... the former is far more readable than the latter (especially if you call the variable `pair` or something similar). I would't use "var" for `var i = 0`, but it is ideally suited to the above....
This is possible in Visual Studio 2017. Tools > Options > Text Editor > C# > Code Style > General – Find 'var' preferences > When variable type is apparent. For Preference select "Prefer explicit type," and for Severity select "Suggestion." [![enter image description here](https://i.stack.imgur.com/wdxwh.png)](https...
Tool to refactor C# var to explicit type
[ "", "c#", "refactoring", "" ]
I'm currently working on some logging code that supposed to - among other things - print information about the calling function. This should be relatively easy, standard C++ has a `type_info` class. This contains the name of the typeid'd class/function/etc. but it's mangled. It's not very useful. I.e. `typeid(std::vect...
Given the attention this question / answer receives, and the valuable feedback from [GManNickG](https://stackoverflow.com/questions/281818/unmangling-the-result-of-stdtype-infoname/4541470#comment26629807_4541470), I have cleaned up the code a little bit. Two versions are given: one with C++11 features and another one ...
Boost core contains a demangler. Checkout [core/demangle.hpp](http://www.boost.org/doc/libs/master/libs/core/doc/html/core/demangle.html#core.demangle.header_boost_core_demangle_hpp): ``` #include <boost/core/demangle.hpp> #include <typeinfo> #include <iostream> template<class T> struct X { }; int main() { char ...
Unmangling the result of std::type_info::name
[ "", "c++", "gcc", "name-mangling", "" ]
During development I have to "clear cache" in Firefox all the time in order to make it use the latest version of JavaScript files. Is there some kind of setting (about:config) to turn off caching completely for JavaScript files? Or, if not, for all files?
Enter "about:config" into the Firefox address bar and set: ``` browser.cache.disk.enable = false browser.cache.memory.enable = false ``` If developing locally, or using HTML5's new manifest attribute you may have to also set the following in about:config - ``` browser.cache.offline.enable = false ```
The [Web Developer Toolbar](https://addons.mozilla.org/en-US/firefox/addon/60) has an option to disable caching which makes it very easy to turn it on and off when you need it.
How to turn off caching on Firefox?
[ "", "javascript", "firefox", "caching", "" ]
I am porting an MFC application to .NET WinForms. In the MFC application, you can right click on a menu or on a context menu item and we show another context menu with diagnostic and configuration items. I am trying to port this functionality to .NET, but I am having trouble. I have been able to capture the right clic...
Edit, due to a comment: In: ``` protected override void OnClick(EventArgs e) { if (SecondaryContextMenu == null || MouseButtons != MouseButtons.Right) { base.OnClick(e); } } ``` this part ``` MouseButtons != MouseButtons.Right ``` should and does compile as it is a call to Control.MouseButtons...
You'll probably have to p/invoke the method. ``` [DllImport("user32.dll")] static extern bool TrackPopupMenuEx(IntPtr hmenu, uint fuFlags, int x, int y, IntPtr hwnd, IntPtr lptpm); const int TPM_RECURSE = 0x0001; ```
How to show a Context Menu when you right click a Menu Item
[ "", "c#", ".net", "winforms", "contextmenu", "" ]
I'm having some trouble with a generic method I'm writing. It has the following signature; ``` public static ThingCollection<T> GetThings<T>(...) where T : Thing ``` There are several classes; ThingA, ThingB and ThingC that inherit from Thing; and I want to be able to have code something like this in the method. ```...
I don't get what you are trying to do with that code. If you want to create a Collection of Things where you could add any type of class derived from Thing, ThingCollection should not have a Typename: it's supposed to be a collection for concrete types. E.g, implementing A ThingCollection this way: ``` public class ...
Primarly I think, this code snippet has bad design. If you add "ThingD" class, you need change in another part of code, for clear behaviour. You should use something like: ``` public static ThingCollection<T> GetThings<T>(...) where T : Thing, new() ... ... T item = new T(); item.Something = Whatever(); ``` Or you ca...
Casting problem in C# generic method
[ "", "c#", "generics", "collections", "casting", "methods", "" ]
In the past I've always gone and called my namespace for a particular project the same as the project (and principle class) e.g.: ``` namespace KeepAlive { public partial class KeepAlive : ServiceBase {... ``` Then from other projects whenever i've called that class its always been: ``` KeepAlive.KeepAlive()...
We have this simple scheme: ``` CompanyName.ProductName ``` Then the application layer, e.g. ``` CompanyName.ProductName.Data CompanyName.ProductName.Web ``` etc. And inside divided per module and/or functionality, which normally correspond to folders ``` CompanyName.ProductName.Web.Shop CompanyName.Pro...
Having the name of a class being the same as the namespace is a bad idea - it makes it quite tricky to refer to the right thing in some cases, in my opinion. I usually call the project (and namespace) an appropriate name and then have "EntryPoint" or "Program" for the entry point where appropriate. In your example, I'...
What is best thing to call your namespace in .Net
[ "", "c#", ".net", "namespaces", "package", "" ]
I am working on a project where I need to create a boundary around a group of rectangles. Let's use this picture as an example of what I want to accomplish. EDIT: Couldn't get the image tag to work properly, so here is the full link: <http://www.flickr.com/photos/21093416@N04/3029621742/> We have rectangles A and C ...
Using the example, where rectangles are perpendicular to each other and can therefore be presented by four values (two x coordinates and two y coordinates): ``` 1 2 3 4 5 6 1 +---+---+ | | 2 + A +---+---+ | | B | 3 + + +---+---+ | | | | | 4 +---+---...
The generalized solution to this problem is to implement boolean operations in terms of a scanline. You can find a brief discussion [here](http://boolean.klaasholwerda.nl/algdoc/top.html) to get you started. From the text: "The basis of the boolean algorithms is scanlines. For the basic principles the book: [Computati...
Calculating a boundary around several linked rectangles
[ "", "c++", "graphics", "geometry", "" ]
``` abstract class Foo { private List<Object> container; private bool update; Foo Foo() { container = new List<object>(); update = false; } public abstract Bar CreateBar(); public void BeginUpdate() { if (!update) { Thread update_thread = ne...
Your code does not do what you think it does. This method ``` public List<Object> Objects { get { lock (container) { return this.container; } } } ``` Does not hold the lock after it has returned the value. So your loop is not locked. You cannot return the container ins...
Several problems with this code: 1. You do not start the thread 2. You can have a race-condition (might not be applicable to your program) where multiple threads call BeginUpdate, both sees that update is false, and both start a thread, now you have two threads running, possibly interfering with each other, since you ...
How will locking behave in .net?
[ "", "c#", ".net", "multithreading", "locking", "" ]
I added the columns in the select list to the order by list, but it is still giving me the error: ORDER BY items must appear in the select list if SELECT DISTINCT is specified. Here is the stored proc: ``` CREATE PROCEDURE [dbo].[GetRadioServiceCodesINGroup] @RadioServiceGroup nvarchar(1000) = NULL AS BEGIN SET NOC...
Try this: ``` ORDER BY 1, 2 ``` OR ``` ORDER BY rsc.RadioServiceCodeId, rsc.RadioServiceCode + ' - ' + rsc.RadioService ```
While they are not the same thing, in one sense `DISTINCT` implies a `GROUP BY`, because every `DISTINCT` could be re-written using `GROUP BY` instead. With that in mind, it doesn't make sense to order by something that's not in the aggregate group. For example, if you have a table like this: ``` col1 col2 ---- ---...
ORDER BY items must appear in the select list if SELECT DISTINCT is specified
[ "", "sql", "sql-server", "t-sql", "" ]
How do I clear the cin buffer in C++?
Possibly: ``` std::cin.ignore(INT_MAX); ``` This would read in and ignore everything until `EOF`. (you can also supply a second argument which is the character to read until (ex: `'\n'` to ignore a single line). Also: You probably want to do a: `std::cin.clear();` before this too to reset the stream state.
I would prefer the C++ size constraints over the C versions: ``` // Ignore to the end of Stream std::cin.ignore(std::numeric_limits<std::streamsize>::max()) // Ignore to the end of line std::cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n') ```
How do I flush the cin buffer?
[ "", "c++", "cin", "io-buffering", "" ]
If I have a for loop which is nested within another, how can I efficiently come out of both loops (inner and outer) in the quickest possible way? I don't want to have to use a boolean and then have to say go to another method, but rather just to execute the first line of code after the outer loop. What is a quick and...
Well, `goto`, but that is ugly, and not always possible. You can also place the loops into a method (or an anon-method) and use `return` to exit back to the main code. ``` // goto for (int i = 0; i < 100; i++) { for (int j = 0; j < 100; j++) { goto Foo; // yeuck! } }...
C# adaptation of approach often used in C - set value of outer loop's variable outside of loop conditions (i.e. for loop using int variable `INT_MAX -1` is often good choice): ``` for (int i = 0; i < 100; i++) { for (int j = 0; j < 100; j++) { if (exit_condition) { // cause the oute...
Breaking out of a nested loop
[ "", "c#", "for-loop", "nested-loops", "" ]
What is the best way to convert an Int value to the corresponding Char in Utf16, given that the Int is in the range of valid values?
``` (char)myint; ``` for example: ``` Console.WriteLine("(char)122 is {0}", (char)122); ``` yields: > (char)122 is z
``` int i = 65; char c = Convert.ToChar(i); ```
Int to Char in C#
[ "", "c#", "casting", "" ]
I have been banging my head on this one all day. The C++ project I am currently working on has a requirement to display an editable value. The currently selected digit displays the incremented value above and decremented value below for said digit. It is useful to be able to reference the editable value as both a numbe...
Internal representation of the float point numbers aren't like was you see. You can only cast to a stirng. To cast, do this: ``` char string[99]; sprintf(string,"%f",floatValue); ``` Or see this : <http://www.parashift.com/c++-faq-lite/misc-technical-issues.html#faq-39.1> The wikipedia article can explain more on t...
[Oh, there are many ways to convert to a string.](https://stackoverflow.com/questions/303562/c-format-macro-inline-ostringstream#306053) (Though I do prefer s**n**printf() myself.) Or you could convert to an int and pull the digits out with modulus and integer-division. You can count the number of digits with log{base...
Extracting individual digits from a float
[ "", "c++", "floating-point", "extract", "digits", "" ]
I have an arraylist that contains items called Room. Each Room has a roomtype such as kitchen, reception etc. I want to check the arraylist to see if any rooms of that type exist before adding it to the list. Can anyone recommend a neat way of doing this without the need for multiple foreach loops? (.NET 2.0) --- I ...
I would not use `ArrayList` here; since you have .NET 2.0, use `List<T>` and all becomes simple: ``` List<Room> rooms = ... string roomType = "lounge"; bool exists = rooms.Exists(delegate(Room room) { return room.Type == roomType; }); ``` Or with C# 3.0 (still targetting .NET 2.0) ``` bool exists = rooms.Exists(room...
From your question it's not 100% clear to me if you want to enforce the rule that there may be only one room of a given type, or if you simply want to know. If you have the invariant that no collection of `Room`s may have more than one of the same `Room` type, you might try using a `Dictionary<Type, Room>`. This has ...
check for duplicates in arraylist
[ "", "c#", ".net", "asp.net", "" ]
I've written a program that counts lines, words, and characters in a text: it does this with threads. It works great sometimes, but not so great other times. What ends up happening is the variables pointing to the number of words and characters counted sometimes come up short and sometimes don't. It seems to me that t...
A different threaded design would make it easier to find and fix this kind of problem, and be more efficient into the bargain. This is a longish response, but the summary is "if you're doing threads in Java, check out [java.util.concurrent](http://java.sun.com/j2se/1.5.0/docs/api/java/util/concurrent/package-summary.ht...
As Chris Kimpton already pointed out correctly you have a problem with the updating of `chars` and `words` in different threads. Synchronizing on `this` won't work either because `this` is a reference to the current thread which means different threads will synchronize on different objects. You could use an extra "lock...
when does a thread go out of scope?
[ "", "java", "multithreading", "scope", "" ]
In OOP languages like C# or VB.NET, if I make the properties or methods in a super class `protected` I can't access them in my Form - they can only be accessed in my class that inherits from that super class. To access those properties or methods I need to make them `public`, which defeats encapsulation, or re-write t...
"need to make them public which defeats encapsulation" Don't conflate good design with the icky visibility rules. The visibility rules are confusing. There are really two orthogonal kinds of visibility -- subclass and client. It's not perfectly clear why we'd ever conceal anything from our subclasses. But we can, with...
If you have code which needs to ask an Class to perform a specific operation but the class does not present your code with a means to do that then the Class doesn't fulfill you codes requirements. Its bit like saying I've got a Car (Automobile) that has a protected steering wheel so I can't access it. The car is no us...
Encapsulation VS Inheritance - How to use a protected function?
[ "", "c#", "vb.net", "oop", "inheritance", "encapsulation", "" ]
I run all my integers through a `(int)Integer` to make them safe to use in my query strings. I also run my strings through this function code:- ``` if(!get_magic_quotes_gpc()) { $string = mysql_real_escape_string($string); } $pattern = array("\\'", "\\\"", "\\\\", "\\0"); $replace = array("", "", ...
yeah I think you've got things going a bit strangely there. First of all, I'd check for magic quotes and *remove* the slashes if it's turned on. That way you've got a string which actually represents the information you want (and not one that has been treated with slashes). If you particularly want to remove the % wi...
Okay I have several comments: * The magic quoting feature is [deprecated](http://php.net/manual/en/security.magicquotes.php), your PHP environment should never enable magic quotes. So checking for it should be unnecessary, unless you're designing code that may be be deployed into other customers' environments who have...
MySQL/PHP - escaping characters that may slow my database down (or make it perform unexpectedly)
[ "", "php", "mysql", "security", "sql-injection", "" ]
The assembly it's trying to find isn't the root assembly - it's a referenced one, but it's in the same folder, and Directory.GetCurrentDirectory() is the folder with all of the files in. I'm stuck - any suggestions?
You can either: 1. Create a new `AppDomain` to load the assembly (and set the `AppDomain`'s base directory to the directory containing all the assemblies). 2. Attach a handler for `AppDomain.AssemblyResolve` to help the CLR find the assembly's dependencies. 3. You might be able to add the directory in question to the ...
You could try using something like this ``` string myDll = string.Empty; string location = Assembly.GetExecutingAssembly().Location; if (location != null) { myDll = string.Format(@"{0}\my.assembly.name.dll", location.Substring(0, location.LastIndexOf(@"\"))); } ``` This should get physical directory in which the ...
Trying to load an app through reflection and get error "Could not load file or assembly...The system cannot find the file specified."
[ "", "c#", "reflection", "" ]
I need a method for adding "business days" in PHP. For example, Friday 12/5 + 3 business days = Wednesday 12/10. At a minimum I need the code to understand weekends, but ideally it should account for US federal holidays as well. I'm sure I could come up with a solution by brute force if necessary, but I'm hoping there...
Here's a function from the [user comments](http://www.php.net/manual/en/function.date.php#79911) on the date() function page in the PHP manual. It's an improvement of an earlier function in the comments that adds support for leap years. Enter the starting and ending dates, along with an array of any holidays that migh...
Get the number of **working days without holidays** between two dates : ### Use example: ``` echo number_of_working_days('2013-12-23', '2013-12-29'); ``` ### Output: ``` 3 ``` ### Function: ``` function number_of_working_days($from, $to) { $workingDays = [1, 2, 3, 4, 5]; # date format = N (1 = Monday, ...) ...
Calculate business days
[ "", "php", "calendar", "date", "" ]
I always hear that using "lastInsertId" (or mysql\_insert\_id() if you're not using PDO) is evil. In case of triggers it obviously is, because it could return something that's totally not the last ID that your INSERT created. ``` $DB->exec("INSERT INTO example (column1) VALUES ('test')"); // Usually returns your newly...
If you go the route of ADOdb (<http://adodb.sourceforge.net/>), then you can create the insert ID *before hand* and explicitly specific the ID when inserting. This can be implemented portably (ADOdb supports a ton of different databases...) and guarantees you're using the correct insert ID. The PostgreSQL SERIAL data ...
IMHO it's only considered "evil" because hardly any other SQL database (if any) has it. Personally I find it incredibly useful, and wish that I didn't have to resort to other more complicated methods on other systems.
Alternative to "PDO::lastInsertId" / "mysql_insert_id"
[ "", "php", "mysql", "auto-increment", "lastinsertid", "mysql-insert-id", "" ]
I have a need to populate a Word 2007 document from code, including repeating table sections - currently I use an XML transform on the document.xml portion of the docx, but this is extremely time consuming to setup (each time you edit the template document, you have to recreate the transform.xsl file, which can take up...
I tried myself to write some code for that purpose, but gave up. Now I use a 3rd party product: [**Aspose Words**](http://www.aspose.com/categories/file-format-components/aspose.words-for-.net-and-java/default.aspx) and am quite happy with that component. It doesn't need Microsoft Word on the machine. *"Aspose.Words ...
Since a DOCX file is simply a ZIP file containing a folder structure with images and XML files, you should be able to manipulate those XML files using our favorite XML manipulation API. The specification of the format is known as **WordprocessingML**, part of the [Office Open XML standard](http://en.wikipedia.org/wiki/...
What is the best way to populate a Word 2007 template in C#?
[ "", "c#", "ms-word", "openxml", "docx", "word-2007", "" ]
Are all the additions to C# for version 4 (dynamic, code contracts etc) expected to run on the current .NET CLR, or is there a planned .NET upgrade as well?
C# 4 will require the .NET 4.0 CLR.
Well, .NET 4.0 will require CLR 4.0; however, it is a little harder to answer what parts of C# 4.0 will work on .NET 2.0/3.x. We can hope that VS2010 will still be multi-targeting(I don't have the CTP "on me" so to speak, so I can't check...). But some of the language features don't *seem* hugely tied to the runtime (n...
C# 4 and CLR Compatibility
[ "", "c#", ".net", "clr", "" ]
I have an application where I would like to have mixed Java and Scala source (actually its migrating a java app to scala - but a bit at a time). I can make this work in IDEs just fine, very nice. But I am not sure how to do this with maven - scalac can compile java and scala intertwined, but how to I set up maven for ...
Using the maven scala plugin, a config like the one below will work for a project that mixes java and scala source (scala source of course goes in the /scala directory, as mentioned by someone else). You can run run mvn compile, test etc... and it will all work as normal. Very nice (it will run scalac first automatica...
Yeah, the scala part has to be in a separate module and in `src/main/scala` directory. Maven regards mixed source like this as heresy. You enable scala compilation by importing the [scala maven plugin](http://scala-tools.org/mvnsites/maven-scala-plugin/). The ["usage"](http://scala-tools.org/mvnsites/maven-scala-plugi...
Building a scala app with maven (that has java source mixed in)
[ "", "java", "maven-2", "scala", "" ]
First, I know there are methods off of the generic `List<>` class already in the framework do iterate over the `List<>`. But as an example, what is the correct syntax to write a ForEach method to iterate over each object of a `List<>`, and do a `Console.WriteLine(object.ToString())` on each object. Something that take...
``` public void Each<T>(IEnumerable<T> items, Action<T> action) { foreach (var item in items) action(item); } ``` ... and call it thusly: ``` Each(myList, i => Console.WriteLine(i)); ```
Is this what you're asking for? ``` int[] numbers = { 1, 2, 3 }; numbers.ToList().ForEach(n => Console.WriteLine(n)); ```
C# Syntax - Example of a Lambda Expression - ForEach() over Generic List
[ "", "c#", ".net", "syntax", "lambda", "" ]
I'm in the process of setting up a php project, but am not very familiar with how to properly use php's include/require commands. My layout currently looks like this: ``` /public --apache points into this directory /public/index.php /public/blah/page.php /utils/util1.php -- useful classes/code are stored...
Usually, the standard conventions are thus: like @grepsedawk said, you'll want to define a constant that contains the root of your project folder and if you can the root of your includes folder: ``` define('APP_ROOT', dirname(__FILE__)); define('INCLUDE_ROOT', APP_ROOT . "/includes"); ``` Note: the constant name need...
Have a configuration script that sets the "INSTALL ROOT" of your project and then use absolute paths. Relative path with multiple includes is a headache in php. DEFINE("INSTALL\_ROOT", "/path/to/www/project") require\_once(INSTALL\_ROOT . '/util1.php')
PHP include file strategy needed
[ "", "php", "" ]
What is the best way to deal with XML documents, XSD etc in C# 2.0? Which classes to use etc. What are the best practices of parsing and making XML documents etc. EDIT: .Net 3.5 suggestions are also welcome.
The primary means of reading and writing in C# 2.0 is done through the **XmlDocument** class. You can load most of your settings directly into the XmlDocument through the XmlReader it accepts. ### Loading XML Directly ``` XmlDocument document = new XmlDocument(); document.LoadXml("<People><Person Name='Nick' /><Perso...
It depends on the size; for small to mid size xml, a DOM such as [XmlDocument](http://msdn.microsoft.com/en-us/library/system.xml.xmldocument.aspx) (any C#/.NET versions) or [XDocument](http://msdn.microsoft.com/en-us/library/system.xml.linq.xdocument.aspx) (.NET 3.5/C# 3.0) is the obvious winner. For using xsd, You ca...
How to deal with XML in C#
[ "", "c#", ".net", "xml", "" ]
I have recently written a dynamic querying tool using expression trees and as I went the power of expression trees began to dawn on me. My querying tool could also form the basis of a reporting tool, a dynamic decision engine and maybe other cases where you need to work with dynamic objects in abstract ways. The proce...
[Generic operators](http://www.pobox.com/~skeet/csharp/miscutil/usage/genericoperators.html) (in [MiscUtil](http://www.pobox.com/~skeet/csharp/miscutil/)) is a pretty well utilised bit of code based on expression trees; very simple, but very versatile. Some other ideas: * [cloning objects](http://groups.google.com/gro...
Have you looked at the DLR? I don't know much about it in detail, but my understanding is that the expression-tree mechanism which is behind the scenes in Linq-to-SQL has effectively been published in the DLR.
Expression trees in .NET - Libraries?
[ "", "c#", ".net", "expression-trees", "" ]
I would like to create a simple program (in Java) which edits text files - particularly one which performs inserting arbitrary pieces of text at random positions in a text file. This feature is part of a larger program I am currently writing. Reading the description about java.util.RandomAccessFile, it appears that an...
Okay, this question is pretty old, but FileChannels exist since Java 1.4 and I don't know why they aren't mentioned anywhere when dealing with the problem of replacing or inserting content in files. [FileChannels](http://docs.oracle.com/javase/6/docs/api/java/nio/channels/FileChannel.html) are fast, use them. Here's a...
Well, no, I don't believe there is a way to avoid overwriting existing content with a single, standard Java IO API call. If the files are not too large, just read the entire file into an ArrayList (an entry per line) and either rewrite entries or insert new entries for new lines. Then overwrite the existing file with...
Inserting text into an existing file via Java
[ "", "java", "file", "file-io", "filesystems", "" ]
I've been told that the java class TreeMap uses an implementation of a RB tree. If this is the case, how does one do an inorder, preorder and postorder tree-walk on a TreeMap? Or is this not possible?
You wouldn't be able to do this with the TreeMap implemented in the Collections library. Here's an implementation of a [Red-Black Tree](https://www.java-tips.org/java-se-tips-100019/24-java-lang/1904-red-black-tree-implementation-in-java.html) in Java that you can look at though. Check out the `printTree()` methods to ...
You can at least do the inorder walk using the iterator and a for each loop: ``` void inOrderWalk(TreeMap<K,V> treeMap) { //this will loop through the values in the map in sorted order (inorder traversal) for (Map.Entry<K,V> entry : treeMap.entrySet() { V value = entry.getValue(); K key = entry.g...
Java TreeMap sorting options?
[ "", "java", "binary-tree", "red-black-tree", "" ]
I've got mssql 2005 running on my personal computer with a database I'd like to run some python scripts on. I'm looking for a way to do some really simple access on the data. I'd like to run some select statements, process the data and maybe have python save a text file with the results. Unfortunately, even though I k...
I use [SQL Alchemy](http://www.sqlalchemy.org/) with cPython (I don't know if it'll work with IronPython though). It'll be pretty familiar to you if you've used Hibernate/nHibernate. If that's a bit too verbose for you, you can use [Elixir](http://elixir.ematia.de/trac/wiki), which is a thin layer on top of SQL Alchemy...
Everyone else seems to have the cPython -> SQL Server side covered. If you want to use IronPython, you can use the standard ADO.NET API to talk to the database: ``` import clr clr.AddReference('System.Data') from System.Data.SqlClient import SqlConnection, SqlParameter conn_string = 'data source=<machine>; initial ca...
What's the simplest way to access mssql with python or ironpython?
[ "", "python", "sql-server", "ironpython", "" ]
Given the following class: ``` class TestClass { public void SetValue(int value) { Value = value; } public int Value { get; set; } } ``` I can do ``` TestClass tc = new TestClass(); Action<int> setAction = tc.SetValue; setAction.Invoke(12); ``` which is all good. Is it possible to do the same thing using the pr...
You could create the delegate using reflection : ``` Action<int> valueSetter = (Action<int>)Delegate.CreateDelegate(typeof(Action<int>), tc, tc.GetType().GetProperty("Value").GetSetMethod()); ``` or create a delegate to an anonymous method which sets the property; ``` Action<int> valueSetter = v => tc.Value = v; ```...
There are three ways of doing this; the first is to use GetGetMethod()/GetSetMethod() and create a delegate with Delegate.CreateDelegate. The second is a lambda (not much use for reflection!) [i.e. x=>x.Foo]. The third is via Expression (.NET 3.5). The lambda is the easiest ;-p ``` class TestClass { p...
Is there a delegate available for properties in C#?
[ "", "c#", ".net", "" ]
I distribute my application using a VS2008 install package, which normally works great. When I create new versions of the app, I go in and increment the `Version` property on the install package and verify the `RemovePreviousVersions` property is set to True. This works just fine most of the time - I just run the inst...
Not a direct answer, but the key difference between an upgrade and an uninstall+ a reinstall is that any custom uninstall steps are not called in 2k8 but are in 2k5. This is referenced in [Visual Studio 2005 -> 2008/10 Service Installer Project Upgrade issue](https://stackoverflow.com/questions/370940/visual-studio-20...
second is By using orca Orca is utility to modify msi files. You can download 'Orca' from following links. <http://www.softpedia.com/get/Authoring-tools/Setup-creators/Orca.shtml> Steps: ``` a. Install orca into your computer. b. Open orca c. Drag and drop your msi into orca UI d. Into left panel it will list t...
.NET Install Package Sometimes Not Completely Removing Previous Versions
[ "", "c#", ".net", "visual-studio", "" ]
If I have something like a loop or a set of if/else statements, and I want to return a value from within the nest (see below), is the best way of doing this to assign the value to a field or property and return that? See below: ``` bool b; public bool ifelse(int i) { if(i == 5) { b = true; } else { b = false; } ret...
Yes, that is good style. The alternative (which would be **bad**) would be to do this: ``` public bool ifelse(int i) { if(i == 5) { return true; } else { return false; } } ``` The reason multiple return points are regarded as bad style is that especially for larger met...
what about ``` return i == 5; ```
Quick question about returning from a nested statement
[ "", "c#", "coding-style", "function-exit", "nested-statement", "" ]
I have a Repeater control on ASPX-page defined like this: ``` <asp:Repeater ID="answerVariantRepeater" runat="server" onitemdatabound="answerVariantRepeater_ItemDataBound"> <ItemTemplate> <asp:RadioButton ID="answerVariantRadioButton" runat="server" GroupName="answerVariants" T...
Since You are using javascript already to handle the radio button click event on the client, you could update a hidden field with the selected value at the same time. Your server code would then just access the selected value from the hidden field.
You could always use [`Request.Form`](http://msdn.microsoft.com/en-us/library/system.web.httprequest.form.aspx) to get the submitted radio button: ``` var value = Request.Form["answerVariants"]; ``` I think the submitted value defaults to the id of the `<asp:RadioButton />` that was selected, but you can always add a...
How to find checked RadioButton inside Repeater Item?
[ "", "asp.net", "javascript", "repeater", "radio-button", "" ]
I've got a bunch of legacy code that I need to write unit tests for. It uses pre-compiled headers everywhere so almost all .cpp files have a dependecy on stdafx.h which is making it difficult to break dependencies in order to write tests. My first instinct is to remove all these stdafx.h files which, for the most part...
Yes, there is a better way. The problem, IMHO, with the 'wizard style' of precompiled headers is that they encourage unrequired coupling and make reusing code harder than it should be. Also, code that's been written with the 'just stick everything in stdafx.h' style is prone to be a pain to maintain as changing anythi...
When you normally use precompiled headers, "stdafx.h" serves 2 purposes. It defines a set of stable, common include files. Also in each .cpp file, it serves as a marker as where the precompiled headers end. Sounds like what you want to do is: * Leave precompiled header turned on. * Leave the "stdafx.h" include in eac...
Is there a way to use pre-compiled headers in VC++ without requiring stdafx.h?
[ "", "c++", "unit-testing", "dependencies", "precompiled-headers", "stdafx.h", "" ]
Does anyone know in .Net 2.0 - .Net 3.5 how to load a jpeg into a System.Windows.Forms.WebControl as a byte-array and with the right mimetypes set so it will show? Something like: ``` webBrowser1.DocumentStream = new MemoryStream(File.ReadAllBytes("mypic.jpg")); webBrowser1.DocumentType = "application/jpeg"; ``` The...
You have to implement an async pluggable protocol, e.g. IClassFactory, IInternetProtocol... Then you use CoInternetGetSession to register your protocol. When IE calls your implementation, you can serve your image data from memory/provide mime type. It's a bit tedious, but doable. Look at IInternetProtocol and pluggabl...
You cannot do it. You cannot stuff images into Microsoft's web-browser control. The limitation comes from the IWebBrowser control itself, which .NET wraps up.
How do I get a C# WebBrowser control to show jpeg files (raw)?
[ "", "c#", ".net", "webbrowser-control", "" ]
In C++, is the return type considered part of the function signature? and no overloading is allowed with just return type modified.
Normal functions do not include the return type in their signature. (*note*: i've rewritten this answer, and the comments below don't apply to this revision - see the edit-history for details). ### Introduction However, the matter about functions and function declarations in the Standard is complicated. There are tw...
It depends if the function is a *function template* or not. In **C++ Templates -- the complete guides**, Jusuttis provides a different definition of that given in the C++ standard, but with equivalent consequences: We define the signature of a function as the the following information: 1. The *unqualified name* of t...
Is the return type part of the function signature?
[ "", "c++", "function", "" ]
Sorry for the bad title, but I couldn't think of a better one. I'm having a class A and a class B which is kind of a sub class of A, like so: (Is there actually a correct name for it? Isn't "sub class" reserved for inheritance?) ``` class A { int i = 0; class B { int j = 1; } } class Test { ...
There doesn't seem to be a way to access the outer class from outside. But you can do it like this: ``` class A { int i = 0; class B { final A outer = A.this; int j = 1; } } class Test { public static void main() { A a = new A(); A.B b = a.new B(); A c = b.outer...
You can access it with the `ParentClass.this` syntax from within the inner class. e.g. ``` public class Outter { class Inner { public Outter getOutter() { return Outter.this; } } public Inner getInner(){ return new Inner(); } } class Runner{ public sta...
Two questions on inner classes in Java (class A { class B { } })
[ "", "java", "class", "" ]
Simple case: i put a DataTable in Cache ``` DataTable table = SomeClass.GetTable(); Cache["test"] = table; then in later calls i use DataTable table = (DataTable)Cache["test"]; ``` now the question is: should i call table.dispose() on each call, though its stored in the Cache? Means the object is always the same? O...
All you are doing is storing a pointer in cache... The actual "table" is still on the heap, where all .Net reference types are stored... You are not making a copy of it... The variable in cache just acts to stop the garbage collector from erasing the object on the heap... and no, you don't want to call dispose until t...
i believe that you should only call Dispose once when you are completely done with the datatable; calling Dispose changes the state of the object. note that 'cached' does not always mean 'copied'!
Do I have to call dispose after each use though datatable is stored in cache?
[ "", "c#", "asp.net", "caching", "datatable", "dispose", "" ]
I have a simple WPF application with a menu. I need to add menu items dynamically at runtime. When I simply create a new menu item, and add it onto its parent MenuItem, it does not display in the menu, regardless of if UpdateLayout is called. What must happen to allow a menu to have additional items dynamically added ...
``` //Add to main menu MenuItem newMenuItem1 = new MenuItem(); newMenuItem1.Header = "Test 123"; this.MainMenu.Items.Add(newMenuItem1); //Add to a sub item MenuItem newMenuItem2 = new MenuItem(); MenuItem newExistMenuItem = (MenuItem)this.MainMenu.Items[0]; newMenuItem2.Header = "Test 456"; newExistMenuItem.Items.Add(...
I have successfully added menu items to a pre-defined menu item. In the following code, the LanguageMenu is defined in design view in th xaml, and then added the sub items in C#. XAML: ``` <MenuItem Name="LanguageMenu" Header="_Language"> <MenuItem Header="English" IsCheckable="True" Click="File_Language_Click"/> <...
WPF: How can you add a new menuitem to a menu at runtime?
[ "", "c#", "wpf", "" ]
When I call a static method like: ``` Something.action(); ``` Since a instance isn't created how long will the Class of the static method be held in memory? If I call the same method will the Class be reloaded for each call since no instance exists? And are only individual static methods loaded when called or are a...
Unless you have configured garbage collection of permgenspace, the class stays in memory until the vm exits. The full class is loaded with all static methods.
The class stays in memory till the classloader that loaded that class stays in memory. So, if the class is loaded from the system class loader, the class never gets unloaded as far as I know. If you want to unload a class, you need to: 1. Load the class and all the classes that refer to that class using a custom clas...
Java: `static` Methods
[ "", "java", "static", "methods", "" ]
In other words, can `fn()` know that it is being used as `$var = fn();` rather than as `fn();`? A use case would be to `echo` the return value in the latter case but to `return` it in the former. Can this be done without passing a parameter to the function to declare which way it is being used?
Many PHP functions do this by passing a boolean value called $return which returns the value if $return is true, or prints the value if $return is false. A couple of examples are [print\_r()](http://php.net/print_r) and [highlight\_file()](http://php.net/highlight_file). So your function would look like this: ``` fun...
No, and it shouldn't. It's a pretty basic premise of the language that functions are unaware of the context in which they are used. This allows you to decompose your application, because each part (function) is completely isolated from its surroundings. That said, what you can do about this particular use-case, is to ...
PHP: Can a function know if it's being assigned as a value?
[ "", "php", "function", "" ]
Does anyone know if there's a way to automatically expand a list in Python, separated by commas? I'm writing some Python code that uses the MySQLdb library, and I'm trying to dynamically update a list of rows in a MySQL database with certain key values. For instance, in the code below, I'd like to have the numeric val...
try: ``` ",".join( map(str, record_ids) ) ``` `",".join( list_of_strings )` joins a list of string by separating them with commas if you have a list of numbers, `map( str, list )` will convert it to a list of strings
I do stuff like this (to ensure I'm using bindings): ``` sqlStmt=("UPDATE apps.sometable SET lastmod=SYSDATE() where rec_id in (%s)" % ', '.join(['?' for n in record_ids])) mysql_cursor.execute(sqlStmt, record_ids) mysql.commit() ``` This works for all dynamic lists you want to bind without leaving you susceptib...
Automagically expanding a Python list with formatted output
[ "", "python", "list", "mysql", "" ]
I know that I am supposed to use `delete []` after I use `new []`, so using `auto_ptr` with `new []` is not such a bright idea. However, while debugging `delete []` (using Visual Studio 2005), I noticed that the call went into a function that looked like this: ``` void operator delete[]( void * p ) { RTCCALLBACK(...
Consider this code: ``` class DeleteMe { public: ~DeleteMe() { std::cout << "Thanks mate, I'm gone!\n"; } }; int main() { DeleteMe *arr = new DeleteMe[5]; delete arr; return 0; } ``` If you run that in VS2005 it will print: ``` Thanks mate, I'm gone! ``` If you change `main()` to correctly adhere t...
I guess it's just an implementation detail. Their heap allocator works the same way when freeing arrays and pointers. But since the standard allows implementations to have different algorithms for the two cases, you really shouldn't assume that `delete` and `delete[]` do the same thing. The behaviour might even change...
delete and delete [] the same in Visual C++?
[ "", "c++", "visual-c++", "" ]
For what I can read, it is used to dispatch a new thread in a swing app to perform some "background" work, but what's the benefit from using this rather than a "normal" thread? Is not the same using a new Thread and when it finish invoke some GUI method using SwingUtilities.invokeLater?... What am I missing here? <h...
Yes, you can accomplish what a SwingWorker does with vanilla threads + invokeLater. SwingWorker provides a predictable, integrated way to accomplish tasks on a background thread and report result on the EDT. SwingWorker additionally adds support for intermediate results. Again, you can do all of this yourself but somet...
A code example: ``` import org.jdesktop.swingx.util.SwingWorker; // This one is from swingx // another one is built in // since JDK 1.6 AFAIK? public class SwingWorkerTest { public static void main( String[] args ) { /*...
What is the rationale of SwingWorker?
[ "", "java", "multithreading", "swing", "swingworker", "" ]
I just came over this syntax in some of the questions in this forum, but Google and any other searchengine tends to block out anything but letters and number in the search so it is impossible to search out "=>". So can anyone tell me what it is and how it is used?
It's the lambda operator. From C# 3 to C# 5, this was only used for [lambda expressions](http://msdn.microsoft.com/en-us/library/bb397687.aspx). These are basically a shorter form of the [anonymous methods](http://msdn.microsoft.com/en-us/library/0yw3tz5k.aspx) introduced in C# 2, but can also be converted into [expre...
It's a much more concise form of method notation. The following are roughly equivalent: ``` // explicit method int MyFunc(int x) { return x; } // anonymous (name-less) method // note that the method is "wrapped" up in a hidden object (Delegate) this way // so there is a very tiny bit of overhead compared to an exp...
What does the '=>' syntax in C# mean?
[ "", "c#", "syntax", "" ]
Is there a way to change the connection string of a DataBase object in Enterprise Library at runtime? I've found [this](http://blog.benday.com/archive/2005/05/05/357.aspx) link but its a little bit outdated (2005) I've also found [this](https://stackoverflow.com/questions/63546/vs2005-c-programmatically-change-connect...
If you take a look at "[Enterprise Library Docs - Adding Application Code](http://msdn.microsoft.com/en-us/library/dd139953.aspx)" it says this: > "If you know the connection string for > the database you want to create, you > can bypass the application's > configuration information and use a > constructor to directly...
look at this:[Open Microsoft.practices.EnterpriseLibrary database with just a connection string](https://stackoverflow.com/questions/401339/open-microsoft-practices-enterpriselibrary-database-with-just-a-connection-string) just use this follow code, you can programming create database at runtime ``` database mydb = n...
Changing connection string at runtime in Enterprise Library
[ "", "c#", ".net", "database", "configuration", "enterprise-library", "" ]
I am attempting to write a component in C# to be consumed by classic ASP that allows me to access the indexer of the component (aka default property). For example: C# component: ``` public class MyCollection { public string this[string key] { get { /* return the value associated with key */ } } ...
Try setting the DispId attribute of the property to be 0, as described here in the [MSDN documentation](http://msdn.microsoft.com/en-us/library/system.runtime.interopservices.dispidattribute(VS.71).aspx).
Thanks to Rob Walker's tip, I got it working by adding the following method and attribute to MyCollection: ``` [DispId(0)] public string Item(string key) { return this[key]; } ``` Edit: See [this better solution](https://stackoverflow.com/a/311946/3195477) which uses an indexer.
Exposing the indexer / default property via COM Interop
[ "", "c#", "collections", "asp-classic", "vbscript", "com-interop", "" ]
I have been looking at improving my ASP.NET page performance. Is it worth changing `autoeventwireup` from `true` to `false` and adding event handlers, or is the performance penalty very small? This is an ASP.NET 2.0 project.
The wireup isn't done at compile-time. It's done at runtime. As described in this article: <http://odetocode.com/Blogs/scott/archive/2006/02/16/2914.aspx> There IS a performance penalty because of the calls to CreateDelegate which must be made every time a page has been created. The performance hit is probably neglig...
From MSDN article. [Performance Tips and Tricks in .NET Applications](http://msdn.microsoft.com/en-us/library/ms973839.aspx) **Avoid the Autoeventwireup Feature** Instead of relying on autoeventwireup, override the events from Page. For example, instead of writing a Page\_Load() method, try overloading the public vo...
What is the performance cost of autoeventwireup?
[ "", "c#", "asp.net", "performance", "" ]
I am a PHP developer who is kind of in a pickle. I'm trying to locate and/or build an API capable of speaking to Hotmail, Yahoo and GMAIL in order to retrieve contact lists (with the user's consent, of course). The one I'm having the most trouble finding is a Hotmail API. Where would I start to look as far as finding ...
Some pointers: * Gmail: [Google Contacts Data API](http://code.google.com/apis/contacts/) * Yahoo: + [Address Book API](http://developer.yahoo.com/addressbook/) **(deprecated)** + [Contacts API](http://developer.yahoo.com/social/rest_api_guide/contact_api.html) * Hotmail: [Windows Live Contacts API](http://msdn.mi...
Plaxo has an [API widget](http://www.plaxo.com/api/widget) to import contacts from Gmail, Yahoo, AOL and Hotmail. You can view a demo of it in action [here](http://www.plaxo.com/api/widget_demo). It previously had a small issue with IE7 (last checked half a year ago), but if its resolved it might suite your needs.
PHP APIs for Hotmail, Gmail and Yahoo?
[ "", "php", "api", "gmail", "yahoo", "hotmail", "" ]
Is there a way to prematurely abort a transaction? Say, I have sent a command to the database which runs five minutes and after four, I want to abort it. Does JDBC define a way to send a "stop whatever you are doing on this connection" signal to the DB?
As mentioned by james, [Statement.cancel()](https://docs.oracle.com/javase/7/docs/api/java/sql/Statement.html#cancel()) will cancel the execution of a running Statement (select, update, etc). The JDBC docs specifically say that Statement.cancel() is safe to run from another thread and even suggests the usage of calling...
I am guessing what you want to do is prevent your application blocking on long running queries / transactions. To this end, JDBC supports the concept of a query time out. You can set the query timeout using this: ``` java.sql.Statement.setQueryTimeout(seconds) ``` And handle the `SQLException` thrown by the `execute(...
How can I abort a running JDBC transaction?
[ "", "java", "jdbc", "" ]
I need to write a tool in C++ to determine the changed bits in a file compared against another file for replication. What would be the best method of accomplishing this? I don't have a specific OS or library in mind, I'm open to suggestions. My primary goal is reducing the amount of network traffic involved in replica...
Look at rsync - it splits the file into blocks, calculates a checksum for each block, and transmits only the checksum to determine if there are any changesto the destination before transmitting the block data only if necessary.
If you can't use rsync as is, check [librsync](http://librsync.sourceforge.net/). It's old, but the code is easy to read and improve.
Best method to determine changed data in C++
[ "", "c++", "file", "compare", "replication", "librsync", "" ]
I've been using the idiom below for some time now. And it seems to be the most wide-spread, at least on the sites I've visited. Is there a better/different way to read a file into a string in Java? ``` private String readFile(String file) throws IOException { BufferedReader reader = new BufferedReader(new FileRea...
## Read all text from a file Java 11 added the [readString()](https://docs.oracle.com/en/java/javase/11/docs/api/java.base/java/nio/file/Files.html#readString(java.nio.file.Path,java.nio.charset.Charset)) method to read small files as a `String`, preserving line terminators: ``` String content = Files.readString(path...
If you're willing to use an external library, check out [Apache Commons IO](https://commons.apache.org/proper/commons-io/) (200KB JAR). It contains an [`org.apache.commons.io.FileUtils.readFileToString()`](https://commons.apache.org/proper/commons-io/javadocs/api-release/org/apache/commons/io/FileUtils.html#readFileToS...
How do I create a Java string from the contents of a file?
[ "", "java", "string", "file", "file-io", "io", "" ]
I am using the .NET 3.5 SP1 framework and I've implemented URL routing in my application. I was getting javascript errors: `Error: ASP.NET Ajax client-side framework failed to load. Resource interpreted as script but transferred with MIME type text/html. ReferenceError: Can't find variable: Sys` Which I believe i...
You don't need to reference ASP.NET MVC. You can use the [StopRoutingHandler](http://msdn.microsoft.com/en-us/library/system.web.routing.stoproutinghandler.aspx) which implements IRouteHandler like so: ``` routes.Add(new Route("{resource}.axd/{*pathInfo}", new StopRoutingHandler())); ``` This is part of .NET 3.5 SP1 ...
An old question but in case it still helps anyone, this worked for me: ``` routes.Ignore("{resource}.axd/{*pathInfo}"); ``` The "Ignore" method exists, whereas in standard ASP.NET the "IgnoreRoute" method appears not to (i.e., not using MVC). This will achieve the same result as Haacked's code, but is slightly cleane...
How to ignore route in asp.net forms url routing
[ "", "c#", "asp.net", "url-routing", "axd", "ignoreroute", "" ]
Some of you may recognize this as Project Euler's problem number 11. The one with the grid. I'm trying to replicate the grid in a large multidimensional array, But it's giving me a syntax error and i'm not sure why ``` grid = [ [ 08, 02, 22, 97, 38, 15, 00, 40, 00, 75, 04, 05, 07, 78, 52, 12, 50, 77, 91, 08 ], [ 49,...
I think when you start a literal number with a 0, it interprets it as an octal number and you can't have an '8' in an octal number.
Note that the "^" symbol in the error points exactly to the erroneous column. Together with the line number it points exactly on the digit 8. This can help lead you to what Jeremy suggested.
Python: Invalid Token
[ "", "python", "octal", "" ]
The [build instructions of V8 JavaScript Engine](http://code.google.com/p/v8/wiki/BuildingOnWindows) mention only Visual Studio 2005 and 2008. Has anybody been successful with [MinGW](http://mingw.org/) on Windows XP/Vista?
You just need to change Scons a bit. Take a look at C:\YourPythonFolder\Lib\site-packages\scons-YourSconsVersion\SCons\Script\_\_ init\_\_.py and go to line 560. Change the linker to gnulink, the c compiler to mingw and the c++ compiler to g++. Eventually it should look like this: ``` linkers = ['gnulink', 'msli...
There is a patch for MinGW support: <http://codereview.chromium.org/18309> See also: <http://code.google.com/p/v8/issues/detail?id=64>
V8 JavaScript Engine on Windows (MinGW)
[ "", "javascript", "windows", "mingw", "v8", "" ]
I'm trying to make a calculator that will take inputs from users and estimate for them how much money they'll save if they use various different VoIP services. I've set it up like this: ``` <form method="get" action="voip_calculator.php"> How much is your monthly phone bill? <input name="monthlybill" type="tex...
You need to get the value from the QueryString and put it into a PHP variable. Like this: ``` $monthlyBill = $_GET['monthlybill']; ``` Now the variable $monthlyBill contains the value from the QueryString. To display it: ``` echo "Your monthly bill is: $monthlyBill"; ```
One thing i do is this ``` echo "<pre>"; print_r($_GET); echo "</pre>"; ``` Put this somewhere in your receiving end and you'll get an understanding of whats happening.
basic php form help
[ "", "php", "forms", "calculator", "" ]
I am performing two validations on the client side on the samve event. I have defined my validations as shown below ``` btnSearch.Attributes["OnClick"] = "javascript:return prepareSave(); return prepareSearch();" ``` Pseudo code for ``` prepareSave(): { if (bPendingchanges) { return confirm('Need to save ...
Your second `return` statement will never be reached. Execution stops after `javascript:return prepareSave()`. Looks like you want to return true if both functions return true - therefore, do: ``` btnSearch.Attributes["OnClick"] = javascript: return prepareSave() && prepareSearch(); ```
`return`, as the name implies, returns control back to whatever called the code in question. Therefore, anything that's after a return statement ``` return prepareSave(); return prepareSearch(); // ^^^^^^^^^^^^^^^^^^^^^^^ e.g. this part ``` never executes. Try `return (prepareSave() && prepareSearc...
Javascript - multiple client-side validations on same event
[ "", "javascript", "html", "validation", "" ]
As Scott Myers wrote, you can take advantage of a relaxation in C++'s type-system to declare clone() to return a pointer to the actual type being declared: ``` class Base { virtual Base* clone() const = 0; }; class Derived : public Base { virtual Derived* clone() const }; ``` The compiler detects that clone(...
It depends on your use case. If you ever think you will need to call `clone` on a derived object whose dynamic type you know (remember, the whole point of `clone` is to allow copying *without* knowing the dynamic type), then you should probably return a dumb pointer and load that into a smart pointer in the calling cod...
Use the Public non-virtual / Private virtual pattern : ``` class Base { public: std::auto_ptr<Base> clone () { return doClone(); } private: virtual Base* doClone() { return new (*this); } }; class Derived : public Base { public: std::auto_ptr<Derived> clone () { return doClone(); } private:...
What's the best signature for clone() in C++?
[ "", "c++", "clone", "smart-pointers", "covariant-return-types", "" ]
What is the best way to scale a 2D image array? For instance, suppose I have an image of 1024 x 2048 bytes, with each byte being a pixel. Each pixel is a grayscale level from 0 to 255. I would like to be able to scale this image by an arbitrary factor and get a new image. So, if I scale the image by a factor of 0.68, I...
There is no simple way of accomplishing this. Neither [scaling](http://en.wikipedia.org/wiki/Image_scaling) nor rotating are trivial processes. It is therefore advisable to use a 2d imaging library. [Magick++](http://www.imagemagick.org/Magick++/) can be an idea as divideandconquer.se point out, but there are others.
There are many ways to scale and rotate images. The simplest way to scale is: ``` dest[dx,dy] = src[dx*src_width/dest_width,dy*src_height/dest_height] ``` but this produces blocky effects when increasing the size and loss of detail when reducing the size. There are ways to produce better looking results, for example,...
Image scaling and rotating in C/C++
[ "", "c++", "c", "image", "image-scaling", "" ]
In most programming languages, dictionaries are preferred over hashtables. What are the reasons behind that?
For what it's worth, a Dictionary **is** (conceptually) a hash table. If you meant "why do we use the `Dictionary<TKey, TValue>` class instead of the `Hashtable` class?", then it's an easy answer: `Dictionary<TKey, TValue>` is a generic type, `Hashtable` is not. That means you get type safety with `Dictionary<TKey, TV...
## Differences | `Dictionary` | `Hashtable` | | --- | --- | | **Generic** | **Non-Generic** | | Needs **own thread synchronization** | Offers **thread safe** version through **`Synchronized()`** method | | Enumerated item: **`KeyValuePair`** | Enumerated item: **`DictionaryEntry`** | | Newer (> **.NET 2.0**) | Older (...
Why is Dictionary preferred over Hashtable in C#?
[ "", "c#", ".net", "vb.net", "data-structures", "" ]
In a PHP application I am writing, I would like to have users enter in text a mix of HTML and text with pointed-brackets, but when I display this text, I want to let the HTML tags be rendered by the non-HTML tags be shown literary, e.g. a user should be able to enter: ``` <b> 5 > 3 = true</b> ``` when displayed, the ...
I'd recommend having the users enter BBcode style markup which you then replace with the html tags: ``` [b]This is bold[/b] [i]this is italic with a > 'greater than' sign there[/i] ``` This gives you more control over how you parse user's input into html, though I admit it looks like an unnecessary burden.
If you're allowing user input HTML, you've got to solve a far bigger problem than a few unescaped angled brackets; HTML is really tough to validate and filter properly, and if you don't do it right you open yourself up to XSS attacks. I've written a library that does this; someone else already posted a link to it here ...
Best way to handle mixed HTML and in user input?
[ "", "php", "parsing", "" ]
Often you need to show a list of database items and certain aggregate numbers about each item. For instance, when you type the title text on Stack Overflow, the Related Questions list appears. The list shows the titles of related entries and the single aggregated number of quantity of responses for each title. I have ...
Here's a trick: calculating a `SUM()` of values that are known to be either 1 or 0 is equivalent to a `COUNT()` of the rows where the value is 1. And you know that a boolean comparison returns 1 or 0 (or NULL). ``` SELECT c.catname, COUNT(m.catid) AS item_count, SUM(i.ownerid = @ownerid) AS owner_item_count FROM cat...
You can sneak a CASE statement inside your SUM(): ``` SELECT categories.catName, COUNT(map.itemId) AS item_count, SUM(CASE WHEN owner= @ownerid THEN 1 ELSE 0 END) AS owner_item_count FROM categories LEFT JOIN map ON categories.catId = map.catId LEFT JOIN items ON items.itemId = map.itemId GROUP BY categorie...
Query: count multiple aggregates per item
[ "", "mysql", "sql", "grouping", "mysql-error-1054", "" ]
So, I've been looking at [Hadoop](http://hadoop.apache.org/) with keen interest, and to be honest I'm fascinated, things don't get much cooler. My only minor issue is I'm a C# developer and it's in Java. It's not that I don't understand the Java as much as I'm looking for the Hadoop.net or NHadoop or the .NET project...
Have you looked at using [Hadoop's streaming?](http://wiki.apache.org/hadoop/HadoopStreaming) I use it in python all the time :-). I'm starting to see that the heterogeneous approach is often the best and it looks like other folks are doing the same. If you look at projects like protocol-buffers or facebook's thrift...
Recently, MySpace released their .NET MapReduce framework, [Qizmt](http://code.google.com/p/qizmt/), as Open Source, so this is also a potential contender in this space.
Is there a .NET equivalent to Apache Hadoop?
[ "", "c#", ".net", "hadoop", "mapreduce", "" ]
Should I use textbox.text.Trim() function every time when I insert any data from web page to database. I just have a habit of using the trim function? Does it effect the performance any way? Should I use everytime or just when needed?
I've seen many problems with spaces which had been added at the end to a text field by accident (for instance logins which mysteriously didn't work). So it's not a bad idea at all to trim() most textfield input as a standard practice. I think the performance hit of a trim() is absolutely neglible, except maybe for sit...
You should trim data as it comes into your application (from a submitted form), rather than just before you put it into the database. It's a validation step to get data into a controlled format, rather than an escaping step to store in a database safely. (\*) You should also be doing removal of control characters and ...
Should I use Trim function everytime when I insert data from webpage to database?
[ "", "c#", "asp.net", "" ]
This question is simple. What function would I use in a PHP script to load data from a URL into a string?
CURL is usually a good solution: <http://www.php.net/curl> ``` // create a new cURL resource $ch = curl_init(); // set URL and other appropriate options curl_setopt($ch, CURLOPT_URL, "http://www.example.com/"); curl_setopt($ch, CURLOPT_HEADER, 0); curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); // grab URL and pass ...
I think you are looking for ``` $url_data = file_get_contents("http://example.com/examplefile.txt"); ```
How do I load arbitrary data from a url PHP?
[ "", "php", "url", "scripting", "load", "" ]
Should my program support IA64, or should it only support x64? I haven't been able to easily find IA64 computers myself. Is IA64 dead? MS seems to have a wide support for IA64, but it took me a long time to be able to find an IA64, and I had to end up getting it on eBay.
What kind of software do you develop? If it's not a data center type of application or a high-end number crunching app, I'd be surprised if there were any demand for an ia64 version. And even then, I'd think it would be a situation where if you have to ask if you should support it, you probably don't need to. A couple...
If you have access to an IA64, then it is absolutely worth it to make your code run on it. Porting your code to another CPU architecture will reveal all sorts of hidden problems. You might have a string overflow by 1 that doesn't show itself on Linux/Windows/x86 but crashes the program because of different stack layou...
Should my C++ program support IA64 or only x64?
[ "", "c++", "c", "64-bit", "itanium", "" ]
In Ruby I have often written a number of small classes, and had a main class organize the little guys to get work done. I do this by writing ``` require "converter.rb" require "screenFixer.rb" . . . ``` at the top of the main class. How do I do this in Java? Is it "import?" Also, could someone please come up with a ...
If you mean that you are going to write some code that will be using another class. Yes you will need to import those classes using an import statement. i.e. ``` package com.boo; import com.foo.Bar; public class StackOverflow { private Bar myBar; } ```
You don't import you own \*.java files in java. Instead you do like this. ``` javac file1.java file2.java file3.java java file1 ```
How do I "require" a neighbour class in Java?
[ "", "java", "" ]
I was looking into GWT. It seems nice, but our software have the must work without JS requirement. Is it possible?
No, it isn't. GWT provides a windowing toolkit that is specifically designed to run on the client, not on the server. Degraded (e.g. non-javascript) code would need to deliver complete HTML to the browser, which GWT simply does not do. It compiles your java code to a javascript file that is delivered to the client and ...
You could degrade gracefully by creating an html structure that is just 'good enough' (with form posts, linked menus, etc) and then have GWT attach to each part of that structure, augmenting its behavior. For example, make an HTML drop down dynamic, replace a link to another page with a component that opens a lightbox,...
GWT without JavaScript?
[ "", "javascript", "web-applications", "gwt", "graceful-degradation", "noscript", "" ]
Kind of a basic question but I'm having troubles thinking of a solution so I need a push in the right direction. I have an input file that I'm pulling in, and I have to put it into one string variable. The problem is I need to split this string up into different things. There will be 3 strings and 1 int. They are sepa...
With C-style strings you can use [strtok()](http://linux.die.net/man/3/strtok) to do this. You could also use [sscanf()](http://linux.die.net/man/3/sscanf) But since you're dealing with C++, you probably want to stick with built in std::string functions. As such you can use find(). Find has a form which takes a second...
I usually use something like this: ``` void split(const std::string &s, char delim, std::vector<std::string> &elems) { std::stringstream ss(s); std::string item; while(std::getline(ss, item, delim)) { elems.push_back(item); } } ``` you can use it like this: ``` std::vector<std::string> tokens...
C++ Strings Modifying and Extracting based on Separators
[ "", "c++", "string", "" ]
I have a web application that uses Ext-JS 2.2. In a certain component, we have an empty toolbar that we are trying to add a button to using ``` myPanel.getTopToolbar().insertButton(0, [...array of buttons...]); ``` However, in IE6/7 this fails because of lines 20241-20242 in ext-all-debug.js: ``` var td = document.c...
I didn't think there was a CSS-only solution. For the record, I ended up injecting javascript into the page that overrides the Ext.Toolbar prototype for the insertButton() function to check for the existance of "this.tr.childNodes([0])" and default to addButton() if it didn't exist.
What I've had to do in the past was include an empty toolbar in my element config: tbar:[] Then (and only after the element has completely rendered) use the .add() method for injecting buttons. Order of events will get you every time. It takes a while to get a handle on it.
Needing an ExtJS bug workaround
[ "", "javascript", "css", "extjs", "" ]
I have this method in my db class ``` public function query($queryString) { if (!$this->_connected) $this->_connectToDb(); //connect to database $results = mysql_query($queryString, $this->_dbLink) or trigger_error(mysql_error()); return mysql_num_rows($results) > 0 ? mysql_fetch_assoc($result...
``` public function query($queryString) { if (!$this->_connected) $this->_connectToDb(); //connect to database $results = mysql_query($queryString, $this->_dbLink) or trigger_error(mysql_error()); $data = array(); while($row = mysql_fetch_assoc($results)) { ...
You might also want to look at the [PDO](http://www.php.net/manual/en/book.pdo.php) extension. You can load the entire result set into an array or you can loop using foreach. ``` <?php $db = new PDO($connection_string, $username, $password); $result = $db->query($queryString); foreach($result as $row) { // do some...
PHP mySQL - Can you return an associated array with a number index?
[ "", "php", "mysql", "" ]
I'm trying to validate that a submitted URL doesn't already exist in the database. The relevant parts of the Form class look like this: ``` from django.contrib.sites.models import Site class SignUpForm(forms.Form): # ... Other fields ... url = forms.URLField(label='URL for new site, eg: example.com') def...
django channel in IRC saved me here. The problem was that the URLField.clean() does two things I wasn't expecting: 1. If no URL scheme is present (eg, http://) the method prepends 'http://' to the url 2. the method also appends a trailing slash. The results are returned and stored in the form's cleaned\_data. So I wa...
I do it this way. It's slightly simpler. ``` try: a = Site.objects.get(domain=url) raise forms.ValidationError("That URL is already in the database. Please submit a unique URL.") except Site.DoesNotExist: pass return url ```
Problems raising a ValidationError on a Django Form
[ "", "python", "django", "django-forms", "cleaned-data", "" ]
EDIT: I've tagged this C in a hope to get more response. It's more the theory I'm interested in than a specific language implementation. So if you're a C coder please treat the following PHP as pseudo-code and feel free to respond with an answer written in C. I am trying to speed up a PHP CLI script by having it execu...
There is no syscall to get a list of child pids, but `ps` can do it for you. `--ppid` switch will list all children for you process so you just need to count number of lines outputted by `ps`. Alternatively you can maintain your own counter that you will increment on `fork()` and decrement on `SIGCHLD` signal, assumi...
The best thing I can come up with is to add all the tasks to a queue, launch the maximum number of threads you want, and then have each thread requesting a task from the queue, execute the task and requesting the next one. Don't forget to have the threads terminate when there are no more tasks to do.
How can I enforce a maximum amount of forked children?
[ "", "php", "c", "fork", "process-management", "" ]
For the moment the best way that I have found to be able to manipulate DOM from a string that contain HTML is: ``` WebBrowser webControl = new WebBrowser(); webControl.DocumentText = html; HtmlDocument doc = webControl.Document; ``` There are two problems: 1. Requires the `WebBrowser` object! 2. This can't be used w...
I did a search to GooglePlex for HTML and I found [Html Agility Pack](https://html-agility-pack.net/) I do not know if it's for that or not, I am downloading it right now to give a try.
Depending on what you are trying to do (maybe you can give us more details?) and depending on whether or not the HTML is well-formed, you *could* convert this to an `XmlDocument`: ``` System.Xml.XmlDocument x = new System.Xml.XmlDocument(); x.LoadXml(html); // as long as html is well-formed, i.e. XHTML ``` Then you c...
How can I manipulate the DOM from a string of HTML in C#?
[ "", "c#", ".net", "html", "dom", ".net-2.0", "" ]
I'm building a python application from some source code I've found [Here](http://code.google.com/p/enso) I've managed to compile and fix some problems by searching the web, but I'm stuck at this point: When running the application this message appears. [alt text http://img511.imageshack.us/img511/4481/loadfr0.png](h...
I've been able to compile and run Enso by using /LD as a compiler flag. This links dynamically to the MS Visual C++ runtime, and seems to allow you to get away without a manifest. If you're using SCons, see the diff file here: <http://paste2.org/p/69732>
Looking at your update, it looks like you need to install [Pycairo](http://www.cairographics.org/pycairo/) since you're missing the \_cairo module installed as part of Pycairo. See the [Pycairo downloads page](http://www.cairographics.org/download/) for instructions on how to obtain/install binaries for Windows.
load dll from python
[ "", "python", "swig", "scons", "dynamic-linking", "" ]
I created 26 `JButton` in an anonymous `actionListener` labeled as each letter of the alphabet. ``` for (int i = 65; i < 91; i++){ final char c = (char)i; final JButton button = new JButton("" + c); alphabetPanel.add(button); button.addActionListener( new ActionListener () { public ...
Could you not simply declare an array of 26 JButton objects at class level, so that both listeners can access them? I believe anonymous inner classes can access class variables as well as final variables.
I don't know if you want to disable the button or do you want to remove it? In you code you're calling remove and in your answer you're talking about disabling. You could achieve this by adding a KeyListener to the alphabetPanel. So you could add this just before starting the for-loop: ``` InputMap iMap = alphabetPane...
Accessing a "nameless" Jbutton in an anonymous class from another anonymous class?
[ "", "java", "swing", "actionlistener", "keylistener", "" ]
How can I start writing a plugin for [Eclipse](http://en.wikipedia.org/wiki/Eclipse_%28software%29)? I've looked for documentation, but unfortunately there is very little or it's poor, so what articles can recommended?
There are some pretty good resources and tutorials on the main Eclipse and IBM's site. One of the best ways is to pick an open source plug-in that has some similar features to what you want to do and start to dissect it. * *[PDE Does Plug-ins](http://www.eclipse.org/articles/Article-PDE-does-plugins/PDE-intro.html)* *...
Eclipse has a pretty good "[Your First Plug-in](http://www.eclipse.org/articles/Article-Your%20First%20Plug-in/YourFirstPlugin.html)" tutorial. If it is confusing, I'm sure they would greatly appreciate your feedback. Keep in mind that Eclipse is essentially Java, so if you don't have a good grasp of Java go for genera...
How to write a plugin for Eclipse?
[ "", "java", "eclipse", "plugins", "" ]
I'm playing around with CodeIgniter; hoping to convert some of my old, ugly PHP into a more maintainable framework. However, I've come across a rather frustrating roadblock - I can't seem to define methods in my views. Any time I try I get a completely blank page, and when I look in the debug log the processing seemed ...
Define your functions in a [helper](http://codeigniter.com/user_guide/general/helpers.html) and load them from the controller. That way you can reuse the functions in other views, as well.
I'm not familiar with CodeIgnitor, but it could be including your templates multiple times. Try wrapping your function in a check: ``` if (!function_exists('myfunc')) { function myfunc() {} } ``` CodeIgnitor is probably swallowing errors, so you could also try flushing buffers immediately before your function: `...
CodeIgniter doesn't like methods in views?
[ "", "php", "codeigniter", "" ]
I keep it in single line, if it's short. Lately I've been using this style for longer or nested ternary operator expressions. A contrived example: ``` $value = ( $a == $b ) ? 'true value # 1' : ( $a == $c ) ? 'true value # 2' : 'false value'; ``` Personally whi...
The ternary operator is generally to be avoided, but this form can be quite readable: ``` result = (foo == bar) ? result1 : (foo == baz) ? result2 : (foo == qux) ? result3 : (foo == quux) ? result4 : fail_result; ``` This way, the condition and the res...
I try not to use a ternary operator to write nested conditions. It defies readability and provides no extra value over using a conditional. Only if it can fit on a single line, and it's crystal-clear what it means, I use it: ``` $value = ($a < 0) ? 'minus' : 'plus'; ```
Which coding style you use for ternary operator?
[ "", "php", "language-agnostic", "coding-style", "ternary-operator", "" ]
As a beginning programmer, I'm trying to settle on a standard naming convention for myself. I realize that it's personal preference, but I was trying to get some ideas from some of you (well a LOT of you) who are much smarter than myself. I'm not talking about camel notation but rather how do you name your variables, ...
Some [basic rules can be found here](http://msdn.microsoft.com/en-us/library/ms229045.aspx). And [much more extended rules can be found here](http://msdn.microsoft.com/en-us/library/ms229002.aspx). These are the official guidelines from the Microsoft framework designers. As for your example, the variable should should...
In this case, I think you'd be better off naming it as primaryAddressLine or firstAddressLine. Here's why - rtxt as a prefix uselessly tells you the type. Intellisense will help you with the type and is immune to changes made to the actual object type. Calling it firstAddressLine keeps it away from the (poor) conventio...
What naming conventions do you use in C#?
[ "", "c#", "naming-conventions", "" ]
I've been exploring the details of Django for about a week now and like what I see. However I've come upon some.. negativity in relation to fine-grained control of permissions to the CRUD interface. What I'm writing is an Intranet client management web-app. The organisation is about 6 tiers, and I need to restrict acc...
If I read your updated requirements correctly, I don't think Django's existing auth system will be sufficient. It sounds like you need a full-on ACL system. This subject has come up a number of times. Try googling on django+acl. Random samplings ... There was a Summer of Code project a couple of years ago, but I'm n...
The Django permission system totally rules. Each model has a default set of permissions. You can add new permissions to your models, also. Each User has a set of permissions as well as group memberships. Individual users can have individual permissions. And they inherit permissions from their group membership. Your v...
Will Django be a good choice for a permissions based web-app?
[ "", "python", "django", "permissions", "" ]
I have an interface called Dictionary which has a method `insert()`. This interface is implemented by class `BSTree`, but I also have a class `AVLTree` which is a child class of `BSTree`. `AVLTree` redefines the `insert()` so it suits it's needs. Now if I type the following code: ``` Dictionary data=new AVLTree(); dat...
In java, (I'm talking relatively to C++), polymorphism should "always" work. It's hard to see what's wrong without looking at the code.. maybe you could post interesting part? Such as the method's signature, class declaration, etc.. My guess is that you haven't used the same signature for both methods.
When you say AVLTree "redefines" the insert, what exactly do you mean? It has to override the method, which means having exactly the same signature (modulo variance). Could you post the signatures of insert() in both BSTree and AVLTree? If you apply the @Override annotation in AVLTree (assuming a suitably recent JDK)...
Polymorphism not working correctly
[ "", "java", "" ]
Does anyone know if its possible to create a new property on an existing Entity Type which is based on 2 other properties concatenated together? E.g. My Person Entity Type has these fields "ID", "Forename", "Surname", "DOB" I want to create a new field called "Fullname" which is ``` Forenames + " " + Surname ``` So...
Not yet, but maybe soon. First, note that your suggested query will not work at all in LINQ to Entities, with or without the property, because, at present, it doesn't support Contains. The new version of the Entity Framework in .NET 4.0, however, is supposed to support custom methods in LINQ to Entities queries. You ca...
For anyone happening in to read this so many years after the question has been answered: There is a more up to date and more DRY compliant answer here: [Using a partial class property inside LINQ statement](https://stackoverflow.com/questions/6879529/using-a-partial-class-property-inside-linq-statement)
Linq to Entities and concatenated properties
[ "", "c#", "linq", "c#-3.0", "linq-to-entities", "" ]