q: What are metaclasses? What are they used for?

[A]
Note, this answer is for Python 2.x as it was written in 2008, metaclasses are slightly different in 3.x.
Metaclasses are the secret sauce that make 'class' work. The default metaclass for a new style object is called 'type'.
```
```
class type(object)
  |  type(object) -> the object's type
  |  type(name, bases, dict) -> a new type
```
```
Metaclasses take 3 args. '
name
', '
bases
' and '
dict
'
Here is where the secret starts. Look for where name, bases and the dict come from in this example class definition.
```
```
class ThisIsTheName(Bases, Are, Here):
    All_the_code_here
    def doesIs(create, a):
        dict
```
```
Lets define a metaclass that will demonstrate how '
class:
' calls it.
```
```
def test_metaclass(name, bases, dict):
    print 'The Class Name is', name
    print 'The Class Bases are', bases
    print 'The dict has', len(dict), 'elems, the keys are', dict.keys()

    return "yellow"

class TestName(object, None, int, 1):
    __metaclass__ = test_metaclass
    foo = 1
    def baz(self, arr):
        pass

print 'TestName = ', repr(TestName)

# output =>
The Class Name is TestName
The Class Bases are (<type 'object'>, None, <type 'int'>, 1)
The dict has 4 elems, the keys are ['baz', '__module__', 'foo', '__metaclass__']
TestName =  'yellow'
```
```
And now, an example that actually means something, this will automatically make the variables in the list "attributes" set on the class, and set to None.
```
```
def init_attributes(name, bases, dict):
    if 'attributes' in dict:
        for attr in dict['attributes']:
            dict[attr] = None

    return type(name, bases, dict)

class Initialised(object):
    __metaclass__ = init_attributes
    attributes = ['foo', 'bar', 'baz']

print 'foo =>', Initialised.foo
# output=>
foo => None
```
```
Note that the magic behaviour that
```
Initialised
```
gains by having the metaclass
```
init_attributes
```
is not passed onto a subclass of
```
Initialised
```
.
Here is an even more concrete example, showing how you can subclass 'type' to make a metaclass that performs an action when the class is created. This is quite tricky:
```
```
class MetaSingleton(type):
    instance = None
    def __call__(cls, *args, **kw):
        if cls.instance is None:
            cls.instance = super(MetaSingleton, cls).__call__(*args, **kw)
        return cls.instance

class Foo(object):
    __metaclass__ = MetaSingleton

a = Foo()
b = Foo()
assert a is b
```
```


q:
When logging with Log4Net it's very easy to put class that called the log into the log file.  I've found in the past that this makes it very easy to trace through the code and see the flow through the classes.  In Log4Net I use the %logger property in the conversion pattern like so:

<conversionPattern value="%date [%thread] %-5level %logger [%property{NDC}] - %message%newline" />

And this gives me the output I want:

2008-09-19 15:40:26,906 [3132] ERROR <b>Log4NetTechDemo.Tester</b> [(null)] - Failed method

You can see from the output that the class that has called the log is Log4NetTechDemo.Tester, so I can trace the error back to that class quite easily.

In the Logging Applicaton Block I cannot figure out how to do this with a simple log call.  Does anyone know how it can be done?  If so, an example or steps to do so would be very helpful.

[A]
We havn't found an easy way without hitting the StackTrace.  If it's an exception, we just grab from that:
```
```
StackTrace trace = new StackTrace(ex, true);
 StackFrame frame = trace.GetFrame(0);
```
```
For chatty items, we just write the string.  We have a snippet that's able to grab the class name on insertion.  We also declare the const string with the class name.
Not pretty, but it's the best we've found.  I hope someone else has a bettwe answer in this thread  :)

s: huggingface

c: devops

d: intermediate


q:
I'd like to know if there's an easier way to insert a record if it doesn't already exist in a table. I'm still trying to build my LINQ to SQL skills.

Here's what I've got, but it seems like there should be an easier way.

public static TEntity InsertIfNotExists<TEntity>
(
    DataContext db,
    Table<TEntity> table,
    Func<TEntity,bool> where,
    TEntity record
)
    where TEntity : class
{
    TEntity existing = table.SingleOrDefault<TEntity>(where);

    if (existing != null)
    {
        return existing;
    }
    else
    {
        table.InsertOnSubmit(record);

        // Can't use table.Context.SubmitChanges()
        // 'cause it's read-only

        db.SubmitChanges();
    }

    return record;
}

[A]
```
```
public static void InsertIfNotExists<TEntity>
                    (this Table<TEntity> table,
                     TEntity entity,
                     Expression<Func<TEntity,bool>> predicate)
    where TEntity : class
{
    if (!table.Any(predicate))
    {
        table.InsertOnSubmit(record);
        table.Context.SubmitChanges();
    }
 }

table.InsertIfNotExists(entity, e=>e.BooleanProperty);
```
```


q:
Which CMS are you using in Java and what is your experience with it (in terms of extensibility, usage comfort, framework API, memory usage, performance etc.). I am looking for suggestions.

Specifically any one that supports a search engine(probably lucene or similar).

[A]
We are using
opencms
.
I haven't tried to extend it beyond changing page templates (writing JSPs) but where usage is concerned it gets the job done, albeit the feeling you get is that you fight the system all the way through.
Memory consumption on the JVM running opencms is right now 161 Mb, the JVM running since January 2008. This is on a low traffic site serving around 6000 hits per month with an average traffic of 1800 Mb per month.


[A]
It takes two arrayrefs and returns a new arrayref with the contents of the second array rearranged such that the second part comes before the first part, split at a point based on the memory location of the first array. When the second array is empty or contains one item, just returns a copy of the second array. Equivalent to the following:
```
```
sub foo {
    my ($list1, $list2) = @_;
    my @output;
    if (@$list2 > 0) {
        my $split = $list1 % @$list2;
        @output = @$list2[$split .. $#$list2, 0 .. ($split - 1)];
    } else {
        @output = @$list2;
    }
    return \@output;
}
```
```
```
$list1 % @$list2
```
essentially picks a random place to split the array, based on
```
$list
```
which evaluates to the memory address of $list when evaluated in a numeric context.
The original mostly uses a lot of tautologies involving punctuation variables to obfuscate. e.g.
```
!$| | $|
```
is always 1
```
@- - @+
```
is always 0
Updated to note that
```
perltidy
```
was very helpful deciphering here, but it choked on
```
!!$^^^!$^^
```
, which it reformats to
```
!!$^ ^ ^ !$^ ^
```
, which is invalid Perl; it should be
```
!!$^^ ^ !$^^
```
. This might be the cause of RWendi's compile error.


q:
I was happily using Eclipse 3.2 (or as happy as one can be using Eclipse) when for a forgotten reason I decided to upgrade to 3.4. I'm primarily using PyDev, Aptana, and Subclipse, very little Java development.

I've noticed 3.4 tends to really give my laptop a hernia compared to 3.2 (vista, core2duo, 2G). Is memory usage on 3.4 actually higher than on 3.2, and if so is there a way to reduce it?

EDIT: I tried disabling plugins (I didn't have much enabled anyway) and used the jvm monitor; the latter was interesting but I couldn't figure out how to use the info in any practical way. I'm still not able to reduce its memory footprint. I've also noticed every once in a while Eclipse just hangs for ~30 seconds, then magically comes back.

[A]
Yes memory usage can get real high and you might run into problems with your JVM, as the default setting is a bit to low.
Consider using this startup parameters when running eclipse:
```
```
-vmargs -XX:MaxPermSize=1024M -Xms256M -Xmx1024M
```
```


q:
I have a folder on my server to which I had a number of symbolic links pointing. I've since created a new folder and I want to change all those symbolic links to point to the new folder. I'd considered replacing the original folder with a symlink to the new folder, but it seems that if I continued with that practice it could get very messy very fast.

What I've been doing is manually changing the symlinks to point to the new folder, but I may have missed a couple.

Is there a way to check if there are any symlinks pointing to a particular folder?

[A]
I'd use the find command.
```
```
find . -lname /particular/folder
```
```
That will recursively search the current directory for symlinks to
```
/particular/folder
```
. Note that it will only find absolute symlinks. A similar command can be used to search for all symlinks pointing at objects called "folder":
```
```
find . -lname '*folder'
```
```
From there you would need to weed out any false positives.


q:
I just installed Glassfish V2 on my local machine just to play around with it.

I was wondering if there is a way to retrieve a param passed in by the GET HTTP method.

For instance,

http://localhost:8080/HelloWorld/resources/helloWorld?name=ABC

How do I retrieve the "name" param in my Java code?

[A]
Like this:
```
```
@Path("/helloWorld")
@Consumes({"application/xml", "application/json"})
@Produces({"application/xml", "application/json"})
@Singleton
public class MyService {
    @GET
    public String getRequest(@QueryParam("name") String name) {
            return "Name was " + name;
    }
}
```
```


q: Whilst refactoring some old code I realised that a particular header file was full of function declarations for functions long since removed from the .cpp file.  Does anyone know of a tool that could find (and strip) these automatically?

[A]
If you index to code with Doxygen you can see from where is each function referenced. However, you would have to browse through each class (1 HTML page per class) and scan for those that don't have anything pointing to them.
Alternatively, you could use ctags to generate list of all functions in the code, and then use objdump or some similar tool to get list of all function in .o files - and then compare those lists. However, this can be problematic due to name mangling.


q:
I'm using C# in .Net 2.0, and I want to read in a PNG image file and check for the first row and first column that has non-transparent pixels.

What assembly and/or class should I use?

[A]
Of course I googled already and found the PngBitmapDecoder class, but it doesn't seem to be available in .Net 2.0?
http://msdn.microsoft.com/en-us/library/system.windows.media.imaging.pngbitmapdecoder.aspx
The above link mentions it's in the PresentationCore assembly which I don't seem to have included with .Net 2.0


q:
AFAIK one of the objectives of Stack Overflow is to make sure anyone can come here and find good answers to her Perl related questions. Certainly beginners would ask what is the best online source to learn Perl but others might just want to ask a question.

Probably the friendliest place is the Monastery of Perl Monks. It is a web site with a rating system similar to but more simple than Stack Overflow. You can find lots of good answers there and if you don't find an answer you can always ask.

The other big resource would be the mailing list of your local Perl Mongers group.

Where do you go when you are looking for an answer to a Perl related question?

[A]
It's worth noting that
http://perlmonks.org
, in addition to the fora, has the Chatterbox, where simple questions can be answered immediately in conversation with other users.
It requires
setting up an account
and
logging in
before
using the Chatterbox
, though.


q: Has any one done this before? It would seem to me that there should be a webservice but i can't find one.  I am writing an application for personal use that would just show basic info from IMDB.

[A]
There is no webservice available.
But there are enough html scrapers written in every language to suit your needs!
I've used the
.NET 3.5 Imdb Services opensource project
in a few personal projects.
1 minute google results:
Perl:
IMDB-Film
Ruby:
libimdb-ruby
Python:
IMDbPY


q:
I'm using the .NET TWAIN code from http://www.codeproject.com/KB/dotnet/twaindotnet.aspx?msg=1007385#xx1007385xx in my application.
When I try to scan an image when the scanner is not plugged in, the application freezes.

How can I check if the device is plugged in, using the TWAIN driver?

[A]
I started of with the same source code that you downloaded from CodeProject, but moved most of the code in MainFrame.cs that initiates the scanning to a Scanner class.  In order to check for scan errors I call the following method in stead of calling Twain.Acquire directly:
```
```
enum AcquireResult
{
    OK = 0,
    InitFailed = 1,
    DeviceIDFailed = 2,
    CapabilityFailed = 3,
    UserInterfaceError = 4
}
private void StartScan()
{
    if (!_msgFilter)
    {
        _parent.Enabled = false;
        _msgFilter = true;
        Application.AddMessageFilter(this);
    }
    AcquireResult ar = _twain.Acquire();
    if (ar != AcquireResult.OK)
    {
        EndingScan();
        switch (ar)
        {
            case AcquireResult.CapabilityFailed:
                throw new Exception("Scanner capability setup failed");
            case AcquireResult.DeviceIDFailed:
                throw new Exception("Unable to determine device identity");
            case AcquireResult.InitFailed:
                throw new Exception("Scanner initialisation failed");
            case AcquireResult.UserInterfaceError:
                throw new Exception("Error with the Twain user interface");
            default:
                throw new Exception("Document scanning failed");
        }
    }
}
```
```
I usually initiate the scan event on a seperate thread in order for the app not to freeze while scanning is in progress.


q:
Can somebody in SO please provide me with a list of resources about Enterprise Mashups and technologies related to SharePoint platform?

Update (as per suggestion of @Spoon16 in the comments):-
The mashup application may typically retrieve a list of contacts from a SharePoint site and display the address of a selected contact person on a map (again maybe Google maps).

[A]
There are a number of different ways to pull external information into SharePoint.
For mashing up SharePoint data in external applications:
Web Services
; great web services coverage for the underlying API will allow you to build external mashups (like the one you mention in your question comment).  Specifically take a look at the
Lists Service
.
For mashing up external data sources inside of SharePoint:
Business Data Catalog
; when you have the enterprise version of Microsoft Office SharePoint Portal server you can use the Business Data Catalog to interact with a very wide variety of external datasources in a read/write fashion.  Works with relational databases and web services.
Enterprise Search
; the indexing capabilities provided by SharePoint's Enterprise search technology are extensive
RSS Web Part
; allows you to consume and apply XSLT transform to any RSS feed and output the result on any SharePoint page
Page Viewer Web Part
; allows an iframe to be embedded on any page, provides an easy mechanism of integrating external applications into the SharePoint environment
SharePoint has an
extensive development framework
that enables you to leverage the full capabilities of the .NET framework to make your wildest mashup dreams come true.  You can use even add additional services to SharePoint that expose the underlying data in custom ways (not covered by the Out of the Box web services) if you like.


q:
Imagine I have an function which goes through one million/billion strings and checks smth in them.

f.ex:

foreach (String item in ListOfStrings)
{
    result.add(CalculateSmth(item));
}

it consumes lot's of time, because CalculateSmth is very time consuming function.

I want to ask: how to integrate multithreading in this kinda process?

f.ex: I want to fire-up 5 threads and each of them returns some results, and thats goes-on till the list has items.

Maybe anyone can show some examples or articles..

Forgot to mention I need it in .NET 2.0

[A]
You could try the
Parallel extensions
(part of .NET 4.0)
These allow you to write something like:
```
```
Parallel.Foreach (ListOfStrings, (item) =>
    result.add(CalculateSmth(item));
);
```
```
Of course result.add would need to be thread safe.


q:
I have a large source repository split across multiple projects. I would like to produce a report about the health of the source code, identifying problem areas that need to be addressed.

Specifically, I'd like to call out routines with a high cyclomatic complexity, identify repetition, and perhaps run some lint-like static analysis to spot suspicious (and thus likely erroneous) constructs.

How might I go about constructing such a report?

[A]
For static analysis there is
pylint
and
pychecker
. Personally I use pylint as it seems to be more comprehensive than pychecker.
For cyclomatic complexity you can try
this perl program
, or this
article
which introduces a python program to do the same


q:
I'm facing a problem on the Win32 API. I have a program that, when it handles WM_PAINT messages, it calls BeginPaint to clip the region and validate the update region, but the BeginPaint function is always generating a WM_NCPAINT message with the same update region, even if the touched part that needs repainting is only inside the client region.

Do anyone has any clue why this is happening? It's on child windows with the WS_CHILD style.

[A]
I guess the
```
WM_NCPAINT
```
message is always sent with the assumption that the border needs to be repainted as well!


q:
I have two webapplication, one is a simple authenticationsite which can authenticate the logged in user and redirects him then to another site.

Therefore I have to pass ther userId (GUID) to the second application. Currently this is done via the URL but i would like to hide this id.

Has anybody an idea how to do this properly?

[EDIT]: I can't use the Session because of the ApplicationBoundaries (2 different Servers)

[A]
Pass the GUID through a
session
, best way.
http://www.w3schools.com/ASP/asp_sessions.asp
OR, since it's 2 different servers, pass the information by POST method:
http://www.w3schools.com/aspnet/aspnet_forms.asp
The other possibility is to store the session state in a database on the local server, and remotely access that database from the other server to see if the user has successfully logged in and within session timelimit.
With that in mind, you can do the entire authentication remotely as well.  Remotely connect to the local database from the remote server and check the login credentials from there...that way you will be able to store the session and/or cookie on the remote server.
I would recommend AGAINST the hidden field proposition
, as it completely counteracts what you are trying to do!  You are trying to hide the GUID in the URL but posting the same information in your HTML code!  This is not the way to do it.
Best choice is the database option, or if not possible, then use HTTP POST.


q:
In SQL Server 2000/2005,

Is it possible to force the default value to be written to already existing rows when adding a new column to a table without using NOT NULL on the new column?

[A]
I doubt it.
http://msdn.microsoft.com/en-us/library/ms190273(SQL.90).aspx
The approach recommended by Microsoft is as follows (taken from the url above)
```
```
UPDATE MyTable SET NullCol = N'some_value' WHERE NullCol IS NULL
ALTER TABLE MyTable ALTER COLUMN NullCOl NVARCHAR(20) NOT NULL
```
```


q:
I'm using a ASP.NET menu control. I'd like the menu to look like this, where link 1 through 10 are in one sitemap file and link 11 through 20 in another.

root
--link 1
(...)
--link 10
--link 11
(...)
--link 20

However, sitemap file MUST have a root  which I cannot seem to suppress.

Any thoughts?

-Edoode

[A]
Is there any reason that you can't add a dummy root node and then subclass the ASP.NET menu control to ignore your dummy "root" node?
You should be able to tell your SiteMapProvider to use different site maps for the menu.
The other question I have is what's the purpose of having multiple sitemap files?  I'm sure you have a valid reason for this, but knowing what's going on would make it easier to understand and come up with a better solution.
That being said, I would come up with a homegrown menu system.  You could use jQuery and the superfish plugin on the front end and use C# to read your site map files on the back end to build the menuing structure.


q: I would like to know what's the best technique to do single sign-on in web sites. It means that if you enter in more than one website, you will be authenticated in a "transparent" way. I'm using php + curl to set the cookies for the different sites, but i really would like to know if does exist a standard way to do it.

[A]
The best way is to use Image tags which pull an image stream from your external sites.
So if you're at www.some-site.com and you want to also be signed into www.some-partner-site.com you have this displayed after logging in:
Because you're using an Image it forces the browser to "pull in" the contents of that URL.
I've recently built a solution which does it with ASP.NET but we also have a php-based partner site.
What image displayed is irrelivant, really you should not display any image at all (hence the 1x1 size)


q: Say I have a table called myTable.  What is the SQL command to return all of the field names of this table?  If the answer is database specific then I need SQL Server right now but would be interested in seeing the solution for other database systems as well.

[A]
MySQL 3 and 4 (and 5):
```
```
desc tablename
```
```
which is an alias for
```
```
show fields from tablename
```
```
SQL Server (from 2000) and MySQL 5:
```
```
select COLUMN_NAME from INFORMATION_SCHEMA.COLUMNS
where TABLE_NAME = 'tablename'
```
```
Completing the answer: like people below have said, in SQL Server you can also use the stored procedure
```
sp_help
```
```
```
exec sp_help 'tablename'
```
```


q:
Is it possible to do like this:

interface IDBBase {
     DataTable getDataTableSql(DataTable curTable,IDbCommand cmd);
     ...
}

class DBBase : IDBBase {
     public DataTable getDataTableSql(DataTable curTable, SqlCommand cmd) {
         ...
     }
}

I want to use the interface to implement to d/t providers (MS-SQL,Oracle...); in it there are some signatures to be implemented in the corresponding classes that implement it. I also tried like this:

genClass<typeOj>
{
    typeOj instOj;

    public  genClass(typeOj o)
    {      instOj=o;    }

    public typeOj getType()
    {        return instOj;    }

...

interface IDBBase
{
    DataTable getDataTableSql(DataTable curTable,genClass<idcommand> cmd);
    ...
}

class DBBase : IDBBase
{
    public DataTable getDataTableSql(DataTable curTable, genClass<SqlCommand> cmd)
    {
        ...
    }
}

[A]
No it's not possible. Method should have same signature that one declared in the interface.
However you can use type parameter constraints:
```
```
interface IDBClass<T> where T:IDbCommand
{
    void Test(T cmd);
}

class DBClass:IDBClass<SqlCommand>
{
    public void Test(SqlCommand cmd)
    {
    }
}
```
```


q:
I realize you can script Microsoft Office apps, but I'm looking for something more general that I can apply to other apps, such as Adobe Acrobat, web browsers and other apps with no scripting ability.

I've used AutoIt but it's a bit clunky, especially when trying to debug why a script fails or stalls. Also, getting the timing of actions, such as clicking a button, or selecting a menu item correctly can be a pain.

Are there build tools that could be used for this purpose?

[A]
I recommend
AutoHotKey
. Its syntax is not pretty, but most of the times you don't have to concoct your own scripts, because its community is so large and well organized. Even if you do, the documentation is extensive and good and the forums will answer your questions quickly. The developer is active and responsive, which means that bugs get fixed quickly, and new features are being considered and added.
Since I began using AHK I don't imagine doing without it - it allows to make life on Windows simpler in so many ways.
You can also employ the COM interface from Python and other scripting languages. It is more complex, but you get to use a more powerful language.


q:
How to wait for multiple child processes in Python on Windows, without active wait (polling)? Something like this almost works for me:

proc1 = subprocess.Popen(['python','mytest.py'])
proc2 = subprocess.Popen(['python','mytest.py'])
proc1.wait()
print "1 finished"
proc2.wait()
print "2 finished"

The problem is that when proc2 finishes before proc1, the parent process will still wait for proc1. On Unix one would use waitpid(0) in a loop to get the child processes' return codes as they finish - how to achieve something like this in Python on Windows?

[A]
It might seem overkill, but, here it goes:
```
```
import Queue, thread, subprocess

results= Queue.Queue()
def process_waiter(popen, description, que):
    try: popen.wait()
    finally: que.put( (description, popen.returncode) )
process_count= 0

proc1= subprocess.Popen( ['python', 'mytest.py'] )
thread.start_new_thread(process_waiter,
    (proc1, "1 finished", results))
process_count+= 1

proc2= subprocess.Popen( ['python', 'mytest.py'] )
thread.start_new_thread(process_waiter,
    (proc2, "2 finished", results))
process_count+= 1

# etc

while process_count > 0:
    description, rc= results.get()
    print "job", description, "ended with rc =", rc
    process_count-= 1
```
```


q:
Are there any tools available for calculating Cyclomatic Complexity in Javascript?

I've found it a very helpful metric in the past while working on server side code, and would like to be able to use it for the client side Javascript I write.

[A]
Since cyclomatic complexity is evaluated counting the number of keyword
"if, switch, while for break" etc.. every tools that works with C will do the job, like
sourcemonitor:
http://www.campwoodsw.com/sourcemonitor.html
Actually, on javascript the more you try to modulize your code, the more you will slow it down, so take it with a grain of salt ;)
EDIT:
I
Really
can't understand what's going on on this answer, I get another downvote, when in my answer I tell a good tool for calculating cyclomatic complexity in javascript,
and this in particular works very well.
For the second assertion, mine is a comment that comes from experience, I never tell
don't modulize your js code
, I only tell to
make attention in doing it
, because often there is a tradeoff with speed, and when I talk of speed I mean that 2 different slowdown can happen: at
download time
and at
execution time
(and in slow device like pda/smartphone this is important).
Since tools like this often drive developer into writing more code trying to chase the smaller index possible,
but in js more code unfortunately means that slowdowns can happen, and the
overuse
of these tools is bad.
Surelly these tools can give you hints of
where
your code can be improved, but you've to master how to use the tool and not blindy rely on it.
So if you downvote me again, please write a comment in which you explain why you do so, the discussion can only benefit from this, thank you and sorry for the vent.


q:
Are there any tools available for calculating the average number of lines of code per method?

I want to know the average size of each method, not just the total number of lines in the project. The per method count will allow me to measure how simple each method is.

This will be calculated as part of the build process, and displayed on a dashboard. The idea being that we can see if the average size of each method is increasing. And this will flag the possibility that code complexity is increasing and we may need to think about refactoring.

[A]
I am not sure if it does that, but searching, after your previous post, what is cyclomatic complexity, I went to the related Wikipedia page which pointed to
Code Analyzer
.
There they say:
When counting for HTML or JSP files, it will count LoC correctly for
  javascript and vbscript code embedded within the <script> tag.
I don't know if this count is dispatched per method, but it might be worth taking a look (it is a free tool).


q: I have a problem that confuses my users, being that although an item is highlighted (by the hover style) when the user mouses over it, they have to mouse over the actual item text, sometimes quite small compared to the item.  Is there a way to make the whole item clickable?

[A]
Add some padding to the A element? Or if it's in a menu contained within a block-level element, make the A display as block too:
```
```
a {
  display: block;
  width: 100%;
}
```
```


q:
I'm wondering, how expensive it is to have many threads in waiting state in java 1.6 x64.

To be more specific, I'm writing application which runs across many computers and sends/receives data from one to another. I feel more comfortable to have separate thread for each connected machine and task, like 1) sending data, 2) receiving data, 3) reestablishing connection when it is dropped. So, given that there are N nodes in cluster, each machine is going to have 3 threads for each of N-1 neighbours. Typically there will be 12 machines, which comes to 33 communication threads.

Most of those threads will be sleeping most of the time, so for optimization purposes I could reduce number of threads and give more job to each of them. Like, for example. reestablishing connection is responsibility of receiving thread. Or sending to all connected machines is done by single thread.

So is there any significant perfomance impact on having many sleeping threads?

[A]
For most cases, the resources consumed by a sleeping thread will be its stack space. Using a 2-threads-per-connection-model, which I think is similar to what you're describing, is known to cause great scalability issues for this very reason when the number of connections grow large.
I've been in this situation myself, and when the number of connections grew above 500 connections (about a thousand threads), you tend to get into lots of cases where you get OutOfMemoryError, since the threads stack space usage exceeds the maximum amount of memory for a single process. At least in our case, which was in a Java on 32 bit Windows world. You can tune things and get a bit further, I guess, but in the end it's just not very scalable since you waste lots of memory.
If you need a large number of connections, Java NIO (new IO or whatever) is the way to go, making it possible to handle lots of connections in the same thread.
Having said that, you shouldn't encounter much of a problem with under a 100 threads on a reasonably modern server, even if it's probably still a waste of resources.


q:
I've seen several examples of code like this:

if not someobj:
    #do something

But I'm wondering why not doing:

if someobj == None:
    #do something

Is there any difference? Does one have an advantage over the other?

[A]
In the first test, Python try to convert the object to a
```
bool
```
value if it is not already one. Roughly,
we are asking the object : are you meaningful or not ?
This is done using the following algorithm :
If the object has a
```
__nonzero__
```
special method (as do numeric built-ins,
```
int
```
and
```
float
```
), it calls this method. It must either return a
```
bool
```
value which is then directly used, or an
```
int
```
value that is considered
```
False
```
if equal to zero.
Otherwise, if the object has a
```
__len__
```
special method (as do container built-ins,
```
list
```
,
```
dict
```
,
```
set
```
,
```
tuple
```
, ...), it calls this method, considering a container
```
False
```
if it is empty (length is zero).
Otherwise, the object is considered
```
True
```
unless it is
```
None
```
in which case, it is considered
```
False
```
.
In the second test, the object is compared for equality to
```
None
```
. Here,
we are asking the object, "Are you equal to this other value?"
This is done using the following algorithm :
If the object has a
```
__eq__
```
method, it is called, and the return value is then converted to a
```
bool
```
value and used to determine the outcome of the
```
if
```
.
Otherwise, if the object has a
```
__cmp__
```
method, it is called. This function must return an
```
int
```
indicating the order of the two object (
```
-1
```
if
```
self < other
```
,
```
0
```
if
```
self == other
```
,
```
+1
```
if
```
self > other
```
).
Otherwise, the object are compared for identity (ie. they are reference to the same object, as can be tested by the
```
is
```
operator).
There is another test possible using the
```
is
```
operator.
We would be asking the object, "Are you this particular object?"
Generally, I would recommend to use the first test with non-numerical values, to use the test for equality when you want to compare objects of the same nature (two strings, two numbers, ...) and to check for identity only when using sentinel values (
```
None
```
meaning not initialized for a member field for exemple, or when using the
```
getattr
```
or the
```
__getitem__
```
methods).
To summarize, we have :
```
```
>>> class A(object):
...    def __repr__(self):
...        return 'A()'
...    def __nonzero__(self):
...        return False

>>> class B(object):
...    def __repr__(self):
...        return 'B()'
...    def __len__(self):
...        return 0

>>> class C(object):
...    def __repr__(self):
...        return 'C()'
...    def __cmp__(self, other):
...        return 0

>>> class D(object):
...    def __repr__(self):
...        return 'D()'
...    def __eq__(self, other):
...        return True

>>> for obj in ['', (), [], {}, 0, 0., A(), B(), C(), D(), None]:
...     print '%4s: bool(obj) -> %5s, obj == None -> %5s, obj is None -> %5s' % \
...         (repr(obj), bool(obj), obj == None, obj is None)
  '': bool(obj) -> False, obj == None -> False, obj is None -> False
  (): bool(obj) -> False, obj == None -> False, obj is None -> False
  []: bool(obj) -> False, obj == None -> False, obj is None -> False
  {}: bool(obj) -> False, obj == None -> False, obj is None -> False
   0: bool(obj) -> False, obj == None -> False, obj is None -> False
 0.0: bool(obj) -> False, obj == None -> False, obj is None -> False
 A(): bool(obj) -> False, obj == None -> False, obj is None -> False
 B(): bool(obj) -> False, obj == None -> False, obj is None -> False
 C(): bool(obj) ->  True, obj == None ->  True, obj is None -> False
 D(): bool(obj) ->  True, obj == None ->  True, obj is None -> False
None: bool(obj) -> False, obj == None ->  True, obj is None ->  True
```
```


q:
I'm looking for a good way to represent organic growth - especially trees and flowers - using code.

I've found Lindenmayer Systems as a reasonable way to portray this, but need a good place to start programming this.

Any good suggestions?

[A]
I am not sure how much you already know on the topic, but I believe Wikipedia's article on
L-system
should be a good start.
"using code" is a bit fuzzy, so I can hardly answer. You might find some freeware to experiment with L-systems, you can play with some graphical language like Processing, do that in GDI or Java2D (or 3D), etc.
There are other methods too, my own
Ferns - Static view
was made with Processing, drawing short lines, using a hierarchical class system to represent trunk, branches and leaves.


q: Hi were can I find training videos for MySQL ?

[A]
In youtube you find somethings like
mysql install:
http://www.youtube.com/watch?v=KQcFP3GcQ0s
mysql trainning:
http://www.youtube.com/watch?v=BHq-bORKncA
Google presentation about mysql tunning (hot)
http://www.youtube.com/watch?v=u70mkgDnDdU
You have anothers google presentations about mysql, just search in youtube and googlevideos :-)


q: While editing an aspx file I found both these opening tags used for seemingly the same thing. Is there a difference and if yes, what is it?

[A]
The difference is that the # symbol specifies a data binding directive, that is resolved at data binding time (for example, when you call Page.DataBind ) and the = sign specifies an evaluation expression just evaluates and prints to the HTML output when that line is processed.
Edit: Just adding that only inside <%# %> you have acces to databinding functions like Eval.


q:
I have C++ project (VS2005) which includes header file with version number in #define directive. Now I need to include exactly the same number in twin C# project. What is the best way to do it?

I'm thinking about including this file as a resource, then parse it at a runtime with regex to recover version number, but maybe there's a better way, what do you think?

I cannot move version outside .h file, also build system depends on it and the C# project is one which should be adapted.

[A]
MSDN tells us:
The #define directive cannot be used
  to declare constant values as is
  typically done in C and C++. Constants
  in C# are best defined as static
  members of a class or struct. If you
  have several such constants, consider
  creating a separate "Constants" class
  to hold them.
You can create library using managed C++ that includes class - wrapper around your constants. Then you can reference this class from C# project. Just don't forget to use
readonly < type >
instead of
const < type >
for your constants declaration :)


q:
As most of you would know, if I drop a file named app_offline.htm in the root of an asp.net application, it takes the application offline as detailed here.

You would also know, that while this is great, IIS actually returns a 404 code when this is in process and Microsoft is not going to do anything about it as mentioned here.

Now, since Asp.Net in general is so extensible, I am thinking that shouldn't there be a way to over ride this status code to return a 503 instead? The problem is, I don't know where to start looking to make this change.

HELP!

[A]
You can try turning it off in the web.config.
```
```
<httpRuntime enable = "False"/>
```
```


q:
What's the best / simplest / most accurate way to detect the browser of a user?

Ease of extendability and implementation is a plus.

The less technologies used, the better.

The solution can be server side, client side, or both. The results should eventually end up at the server, though.

The solution can be framework agnostic.

The solution will only be used for reporting purposes.

[A]
The
JQuery Browser Plugin
will do it client-side for you.
What is the jQuery Browser Plugin?
The jQuery Browser Plugin is an addon for jQuery that makes it easy to uniquely identify your visitors' browsers.
What does it do?
It gives you an object in javascript that contains all of the information about the browser being used. It also adds CSS browser selectors, which means you can style elements or write functions for specific browsers, browser versions, layouts, layout versions, and even operating systems. Image of the jQuery Browser Plugin in action.
The plug-in makes
```
$.browser
```
available, which you can re-submit to your server via an AJAX call, if you really need it server-side.
```
```
alert($.browser.name);  // Alerts Firefox for me
```
```
The plug-in will only be as effective as the browsers it's been tested against, however. The plugin listed above has a list of
browsers recognised in it's tests
, but there's always the risk that a new browser will come sneaking out (
Google Chrome..
) that will require a re-write of the recognition rules. That said, this plug-in seems to be regularly updated.


q:
Per man pages, snprintf is returning number of bytes written from glibc version 2.2 onwards. But on lower versions of libc2.2 and HP-UX, it returns a positive integer, which could lead to a buffer overflow.

How can one overcome this and write portable code?

Edit : For want of more clarity

This code is working perfectly in lib 2.3

    if ( snprintf( cmd, cmdLen + 1, ". %s%s", myVar1, myVar2 )  != cmdLen )
    {
        fprintf( stderr, "\nError: Unable to  copy bmake command!!!");
        returnCode = ERR_COPY_FILENAME_FAILED;
    }

It returns the length of the string (10) on Linux. But the same code is returning a positive number that is greater than the number of characters printed on HP-UX machine. Hope this explanation is fine.

[A]
I have found one portable way to predict and/or limit the number of characters returned by sprintf and related functions, but it's inefficient and many consider it inelegant.
What you do is create a temporary file with tmpfile(), fprintf() to that (which reliably returns the number of bytes written), then rewind and read all or part of the text into a buffer.
Example:
```
```
int my_snprintf(char *buf, size_t n, const char *fmt, ...)
{
    va_list va;
    int nchars;
    FILE *tf = tmpfile();

    va_start(va, n);
    nchars = vfprintf(tf, fmt, va);
    if (nchars >= (int) n)
        nchars = (int) n - 1;
    va_end(va);
    memset(buf, 0, 1 + (size_t) nchars);

    if (nchars > 0)
    {
        rewind(tf);
        fread(buf, 1, (size_t) nchars, tf);
    }

    fclose(tf);

    return nchars;
}
```
```


q: I'm trying to read data from a Delphi DBIV database, every time I access the database it creates a Paradox.lck and a Pdoxusrs.lck file.  I'm using only a TQuery Object to do this (nothing else). can I access a  Delphi DBIV database without it creating these lock files?


q:
Can someone explain to me the advantages of using an IOC container over simply hardcoding the default implementation into a default constructor?

In other words, what is wrong about this code?

public class MyClass
{
    private IMyInterface _myInterface;

    public MyClass()
    {
        _myInterface = new DefaultMyInterface();
    }

    public MyClass(IMyInterface myInterface)
    {
        _myInterface = myInterface;
    }
}

As far as I can tell, this class supports constructor injection enough so unit testing and mocking is easily done.  In addition to which, the default constructor removes the computational overhead of the IOC container (not to mention the whole process is a lot more transparent).

The only benefits i can see to using an IOC container is if you need to switch out the implementation of your interfaces frequently.  Am I missing something?

[A]
The idea of IoC is to delegate part of your component's functionality to another part of the system. In IoC world, you have components that don't know about each other. Your example violates this, as you're creating tight coupling between MyClass and some implementation of IMyInterface.
The main idea
is that your component
has no knowledge
about how it will be used. In your example, your component
makes some assumptions
about its use.
Actually this approach can work, but mixing IoC and explicit object initialization is not a good practice IMO.
IoC gives you loose coupling by performing late binding for the price of code clarity. When you add additional behavior to this process, it makes things even more complicated and can lead to bugs when some components can potentially receive object with unwanted or unpredicted behavior.


q: I installed MySQL via MacPorts. What is the command I need to stop the server (I need to test how my application behave when MySQL is dead)?

[A]
Apparently you want:
```
```
sudo /Library/StartupItems/MySQLCOM/MySQLCOM stop
```
```
Have a further read in
Jeez People, Stop Fretting Over Installing RMagic
.


q:
We have a graphics intensive application that seems to be experiencing problems on AMD 64 bit Dual Core platforms that are not apparent on Intel platforms.

Running the application causes the CPU to run at 100%, in particular when using code for shadows and lighting (Open GL).

Does anyone know of specific issues with AMD processors that could cause this or know where to track down the problem, and/or ways to optimize the code base to avoid these issues?

note, the application generally works well on mid range hardware, my dev machine has an nvidia gtx260 card in, so lack of power should not be an issue

[A]
I would invest in profiling software to trace down the actual cause of the problem.
On linux, Valgrind ( which contains Cachegrind &  Callgrind ) + KCacheGrind can make working out where all the heavy function calls are going on.
Also, compile with full debug symbols and it can even show the assembley code at the slow function calls.
If you're using an Intel Specific compiler, this may be part of your problem ( not definate tho ), and try the GCC family.
Also, you may want to dive into OpenMP and Threads if you haven't already.


q:
I'm new to both Web Services and RMI and I wonder which is the better way to do remoting between different web applications, when these applications are all written in Java, that is when different programming languages don't matter (which would be the advantage of WS).

While on the one hand I would guess that there's a performance overhead when using web services (does anyone have some numbers to prove that?), on the other hand it seems to me that web services are much more loosely coupled and can be used to implement a more service-oriented architecture (SOA) (which isn't possible with RMI, right?).

Although this is quite a general question, what's your opinion?

Thanks

[A]
My experience with RMI and Web Services mirrors your guesses above.  In general, RMI's performance exceeds web services, if the communication requirement is for complex objects. The JEE interface specification needs to be explicitly specified for Web Services.
Note that Web Services are interoperable whereas RMI is not (in terms of the technologies of Client and Server).  I tend to use Web Services when I had one or more external partners who were implementing the interface, but RMI if I was in control of both ends of the connection.


q:
So I got this question from one of the developers in my team: What is domain driven design? I could of course point to the book from Evans but is that actually an answer?

How would you explain DDD in a few sentences to junior software engineers in your team?

[A] I would say this practice promotes concentrating your efforts on the 'problem space' rather than the 'solution space'. Driving an emergent solution (the design) by studying and really getting to know and understand the domain. One of the practices (taken from XP) would be the writing of stories that occur in the problem domain. From these you can identify your use cases and objects for your design. They 'emerge' and tell you what needs to be in the solution, and how they will need to interact with each other.


q:
Our rails app is designed as a single code base linking to multiple client databases. Based on the subdomain the app determines which db to connect to.

We use liquid templates to customise the presentation for each client. We are unable to customise the generic 'We're Sorry, somethign went wrong..' message for each client.

Can anyone recommend an approach that would allow us to do this.

Thanks

DOm

[A]
For catching exceptions in Rails 2,
```
rescue_from
```
controller method is a great way to specify actions which handle various cases.
```
```
class ApplicationController < ActionController::Base
  rescue_from MyAppError, :with => :show_errors

  def show_errors
    render :action => "..."
  end
end
```
```
This way you can make dynamic error pages to replace the static "public/500.html" page.


q: I want to create a stored procedure with one argument which will return different sets of records depending on the argument. What is the way to do this? Can I call it from plain SQL?

[A]
I think you want to return a REFCURSOR:
```
```
create function test_cursor
            return sys_refcursor
            is
                    c_result sys_refcursor;
            begin
                    open c_result for
                    select * from dual;
                    return c_result;
            end;
```
```
Update
: If you need to call this from SQL, use a table function like @Tony Andrews suggested.


q:
I have a Win32 TreeCtrl where the user can rename the tree labels. I process the TVN_ENDLABELEDIT message to do this.

In certain cases I need to change the text that the user entered. Basically the user can enter a short name during edit and I want to replace it with a longer text.

To do this I change the pszText member of the TVITEM struct I received during TVN_ENDLABELEDIT. I do a pointer replace here, as the original memory may be too small to do a simple strcpy like operation.

However I do not know how to deallocate the original pszText member. Basically because it's unknown if that was created with malloc() or new ... therefore I cannot call the appropriate deallocator. Obviously Win32 won't call the deallocator for the old pszText because the pointer has been replaced. So if I don't deallocate, there will be a memory leak.

Any idea how Win32 allocate these structs and what is the proper way to handle the above situation?

[A]
Unless you're using
```
LPSTR_TEXTCALLBACK
```
, the tree-view control is responsible for allocating the memory, not your code, so you shouldn't change the value of the
```
pszText
```
pointer.
To change the item's text in your
```
TVN_ENDLABELEDIT
```
handler, you can use
```
TreeView_SetItem
```
, then return 0 from the handler.


q:
I cannot understand the Oracle documentation. :-(

Does anybody know how to fetch multiple rows of simple data from Oracle via OCI?

I currently use OCIDefineByPos to define single variables (I only need to do this for simple integers -- SQLT_INT/4-byte ints) and then fetch a single row at a time with OCIStmtExecute/OCIStmtFetch2.

This is OK for small amounts of data but it takes around .5ms per row, so when reading a few ten thousand rows this is too slow.

I just don't understand the documentation for OCIBindArrayOfStruct. How can I fetch a few thousand rows at a time?


q:
If you are writing a simple little loop, what should you name the counter?

Provide example loops!

[A]
My experience is that most people use single letters, e.g.:
```
i
```
,
```
j
```
,
```
k
```
,
...
or
```
x
```
,
```
y
```
,
or
```
r
```
,
```
c
```
(for row/column)
or
```
w
```
,
```
h
```
(for width/height)
, etc.
But I learned a great alternative a long time ago, and have used it ever since: double letter variables.
```
```
// recommended style              ●    // "typical" single-letter style
                                  ●
for (ii=0; ii<10; ++ii) {         ●    for (i=0; i<10; ++i) {
    for (jj=0; jj<10; ++jj) {     ●        for (j=0; j<10; ++j) {
        mm[ii][jj] = ii * jj;     ●             m[i][j] = i * j;
    }                             ●        }
}                                 ●    }
```
```
In case the benefit isn't immediately obvious: searching through code for any single letter will find many things that
aren't
what you're looking for.  The letter
```
i
```
occurs quite often in code where it isn't the variable you're looking for.


q: Was this an oversight?  Or is it to do with the JVM?

[A] I guess it has to do with the fact that the JVM is coded in C++. Apart from that, pointers and references are nearly similar. You could say that the reference mechanism in Java is implemented using C++ pointers and the name 'NullPointerException' allows that implementation detail to shine through.


q:
I have an Exchange mailbox linked as a table in an MS Access app. This is primarily used for reading, but I would also like to be able to "move" messages to another folder.

Unfortunately this is not as simple as writing in a second linked mailbox, because   apparently I can not edit some fields. Some critical fields like the To: field are unavailable, as I get the following error

"Field 'To' is based on an expression and cannot be edited".

Using CreateObject("Outlook.Application") instead is not an option here, because as far as I know, this gives a security dialog when called from Access.

Any solutions?*

[A]
Is this two problems? Mail can be moved using the Move method. Here is a snippet:
```
```
Set oApp = CreateObject("Outlook.Application")

Set oNS = oApp.GetNamespace("MAPI")

Set oMailItems = oNS.GetDefaultFolder(olFolderInbox)
Set itm = oMailItems.Items(6)
itm.Move oNS.GetDefaultFolder(olFolderDeletedItems)
```
```
However, Recipients (To) is read only, even, I believe, with Outlook Redemtion.


q: Is there a way to check if the user has a different version of the CSS cached by their browser and if so force their browser to pull the new version?

[A]
You should possibly just share a common ancestor class, then you can flick it with a single js command if need be.
```
```
<body class="style2">

<body class="style1">
```
```
etc.


q: How do I read text from the (windows) clipboard with python?

[A]
Try win32clipboard from the win32all package (that's probably installed if you're on ActiveState Python).
See sample here:
http://code.activestate.com/recipes/474121/


q: How can someone validate that a specific element exists in an XML file? Say I have an ever changing XML file and I need to verify every element exists before reading/parsing it.

[A]
```
```
if(doc.SelectSingleNode("//mynode")==null)....
```
```
Should do it (where doc is your XmlDocument object, obviously)
Alternatively you could use an XSD and validate against that


q:
I need to count and check how much of some images is placed in folder od web server.
Example- images get names from user_id, and on example I have user_id 27, and my images are:

27_1.jpg, 27_2.jpg, 27_3.jpg, ...

How to check and write to database this thing?

Thanks

[A]
Once you know your path you can use IO.Directory.GetFiles() method.
```
```
IO.Directory.GetFiles("\translated\path","27_*.jpg").Count()
```
```
will give you what you're looking for.


q: How do you return a serialized JSON object to the client side using ASP.NET MVC via an AJAX call?

[A]
From the controller you can just return a JsonResult:
```
```
public ActionResult MyAction()
{
    ... // Populate myObject
    return new JsonResult{ Data = myObject };
}
```
```
The form of the Ajax call will depend on which library you're using, of course. Using jQuery it would be something like:
```
```
$.getJSON("/controllerName/MyAction", callbackFunction);
```
```
where the
```
callbackFunction
```
takes a parameter which is the data from the XHR request.


q:
In Python there is a really neat function called zip which can be used to iterate through two lists at the same time:

list1 = [1, 2, 3]
list2 = ["a", "b", "c"]
for v1, v2 in zip(list1, list2):
    print v1 + " " + v2

The above code should produce the following:

1 a
2 b
3 c

I wonder if there is a method like it available in .Net? I'm thinking about writing it myself, but there is no point if it's already available.

[A]
Nope, there is no such function in .NET. You have roll out your own. Note that C# doesn't support tuples, so python-like syntax sugar is missing too.
You can use something like this:
```
```
class Pair<T1, T2>
{
    public T1 First { get; set;}
    public T2 Second { get; set;}
}

static IEnumerable<Pair<T1, T2>> Zip<T1, T2>(IEnumerable<T1> first, IEnumerable<T2> second)
{
    if (first.Count() != second.Count())
        throw new ArgumentException("Blah blah");

    using (IEnumerator<T1> e1 = first.GetEnumerator())
    using (IEnumerator<T2> e2 = second.GetEnumerator())
    {
        while (e1.MoveNext() && e2.MoveNext())
        {
            yield return new Pair<T1, T2>() {First = e1.Current, Second = e2.Current};
        }
    }
}

...

var ints = new int[] {1, 2, 3};
var strings = new string[] {"A", "B", "C"};

foreach (var pair in Zip(ints, strings))
{
    Console.WriteLine(pair.First + ":" + pair.Second);
}
```
```


q: I'm building an installer for an application. The user gets to select a datasource they have configured and nominate what type of database it is.  I want to confirm that the database type is indeed Oracle, and if possible, what version of Oracle they are running by sending a SQL statement to the datasource.

[A]
Run this SQL:
```
```
select * from v$version;
```
```
And you'll get a result like:
```
```
BANNER
----------------------------------------------------------------
Oracle Database 10g Release 10.2.0.3.0 - 64bit Production
PL/SQL Release 10.2.0.3.0 - Production
CORE    10.2.0.3.0      Production
TNS for Solaris: Version 10.2.0.3.0 - Production
NLSRTL Version 10.2.0.3.0 - Production
```
```


q:
I'm playing with the wonderful FindBugs plugin for Hudson. Ideally, I'd like to have the build fail if FindBugs finds any problems. Is this possible?

Please, don't try and tell me that "0 warnings" is unrealistic with FindBugs. We've been using FindBugs from Ant for a while and we usually do maintain 0 warnings. We achieve this through the use of general exclude filters and specific/targeted annotations.

[A]
You can not rely on find bugs so much , it is just an expert system that tells you that something
may
be wrong with your program during runtime. Personally I have seen a lot of warning generated by findbugs because it was not able to figure out the correctness of code (in fact).
One example when you open a stream or jdbc connection in one method and close it in other, in this case findbugs expecting to see close() call in same method which sometimes is impossible to do.


q: I'm building an installer for an application. The user gets to select a datasource they have configured and nominate what type of database it is.  I want to confirm that the database type is indeed Postgres, and if possible, what version of Postgres they are running by sending a SQL statement to the datasource.


q: Net::HTTP can be rather cumbersome for the standard use case!

[A]
This is what I use:
http://rubyforge.org/projects/restful-rails/
.


q:
I have a pivot table on an olap cube. I can go into a page field and manually deselect multiple items. How can I do this in VBA based on a list of items I need excluded? (n.b. I do not have a corrresponding list of items I need included)

I know how to exclude these items in other ways, by altering the underlying query for example. I specifically want to replicate the user action of deselecting items in the pivot.

[A]
I apologize for this example being in C#, but I really don't know enough VBA to translate it (perhaps someone can edit this entry and add it below).
Are you refering to something like this?
```
```
((MOE.PivotField)pivotTableObject.PivotFields("[NAME]")).Delete();
```
```
Where MOE is the Microsoft.Office.Interop.Excel namespace and [NAME] is the name of the field you want to remove


[A]
```
/sbin/chkconfig
```
— The
```
/sbin/chkconfig
```
utility is a simple command line tool for maintaining the
```
/etc/rc.d/init.d/
```
directory hierarchy.


q:
I want to search for $maximumTotalAllowedAfterFinish and replace it with $minimumTotalAllowedAfterFinish. Instead of typing the long text:

:%s/$maximumTotalAllowedAfterFinish/$minimumTotalAllowedAfterFinish/g

Is there a way to COPY these long variable names down into the search line, since, on the command line I can't type "p" to paste?

[A]
Type
```
q:
```
to get into history editing mode in a new buffer. Then edit the last line of the buffer and press
```
Enter
```
to execute it.


q: As the title says: What is the difference between a non-secure random number generator and a secure random number generator?

[A]
No computationally feasible algorithm should:
recover the seed, or
predict the "next bit"
for a secure random number generator.
Example: a linear feedback shift register produces lots of random numbers out there, but given enough output, the seed can be discovered and all subsequent numbers predicted.


q: Our application is written in ActionScript2 and has about 50.000+ lines of code. We want to port it to ActionScript3 and we're trying to find out what our options are. Do we have to do it manually or can we use a converter, and what problems can we expect?

[A]
I don't think you can ever use an automatic converter for this task.
A converter may be able to save you some steps or point out places where change must take place, but you'll have to go over the code manually.
For example, referring to a _level0.variableName in AS2 can point to a movieClip on the _root level, to a FlashVar sent from the HTML container or to an object created by the code itself. There's no real way of knowing. (You can't look for the varname in the code since that too can be calculated or read externally.
You need to have a very good reason to do such conversion. If AS2 is not suitable anymore for some reason, maybe you should try to solve the problem instead of converting to AS3 just because it has a nice little function that you need.


q:
I was wondering are there any security concerns with adding crossdomain.xml to the root of an application server? Can it be added to any other parts of the server and are you aware of any work arounds that dont require the server to have this file in place?

Thanks
Damien

[A]
By adding the crossdomain.xml, the main security concern is that flash applications can now connect to your server.  So if someone logs into your site, and then browses over to another website with a malicious flash app, that flash app can connect back to your site.  Since it's in a browser, cookies are shared to the flash app.  This allows the flash app to hijack the user's session to do whatever it is your website does without the user knowing about it.
If your flex app is served from the same server, you don't need a crossdomain.xml
You can put it in a sub directory of your site and use System.security.loadSecurityPolicy()
http://livedocs.adobe.com/flex/2/langref/flash/system/Security.html
Applications would then be limited to that tree of your directory structure.


q:
What is the most efficient way given to raise an integer to the power of another integer in C?

// 2^3
pow(2,3) == 8

// 5^5
pow(5,5) == 3125

[A]
An extremely specialized case is, when you need say 2^(-x to the y), where x, is of course is negative and y is too large to do shifting on an int. You can still do 2^x in constant time by screwing with a float.
```
```
struct IeeeFloat
{

    unsigned int base : 23;
    unsigned int exponent : 8;
    unsigned int signBit : 1;
};

union IeeeFloatUnion
{
    IeeeFloat brokenOut;
    float f;
};

inline float twoToThe(char exponent)
{
    // notice how the range checking is already done on the exponent var
    static IeeeFloatUnion u;
    u.f = 2.0;
    // Change the exponent part of the float
    u.brokenOut.exponent += (exponent - 1);
    return (u.f);
}
```
```
You can get more powers of 2 by using a double as the base type.
(Thanks a lot to commenters for helping to square this post away).
There's also the possibility that learning more about
IEEE floats
, other special cases of exponentiation might present themselves.


q:
I'm guessing I need to implement an NVelocityViewEngine and NVelocityView - but before I do I wanted to check to see if anyone has already done this.

I can't see anything in the trunk for MVCContrib.

I've already seen the post below - I'm looking specifically for something which works with Preview 5:

Testing ScottGu: Alternate View Engines with ASP.NET MVC (NVelocity)

Otherwise I'll start writing one :)


q:
Most languages (Ruby included) allow number literals to be written in at least three bases: decimal, octal and hexadecimal. Numbers in decimal base is the usual thing and are written as (most) people naturally write numbers, 96 is written as 96. Numbers prefixed by a zero are usually interpreted as octal based: 96 would be written as 0140. Hexadecimal based numbers are usually prefixed by 0x: 96 would be written as 0x60.

The question is: can I write numbers as binary literals in Ruby? How?

[A]
From
this manual
```
```
0b01011
```
```
binary integer


q:
I know how to change the schema of a table in SQL server 2005:

ALTER SCHEMA NewSchama TRANSFER dbo.Table1

But how can i check and/or alter stored procedures that use the old schema name?

Sorry: I mean:
There are stored procedures that have the old schema name of the table in the sql of the stored procedure... How can i edit all the stored procedures that have the dbo.Table1 in the body of the procedure...

[A]
Get a list of dependent objects by right-clicking on the table before you change the schema and then look at what is dependent on the table, make a list and then change those. There is, however, always a possibility that you'll miss something because it is possible to break the dependencies SQL server tracks.
But the best way would be to script the database out into a file and then do a search for the table name, make a list of all of the sprocs where it needs to be changed and then add those to the script to change the schema of the table.


q:
Does anybody know if there is a feasible way on Windows XP to programmatically create and configure a user account so that after logging in from the console (no terminal services) a specific app is launched and the user is "locked" to that app ?

The user should be prevented from doing anything else with the system (e.g.: no ctrl+alt+canc, no ctrl+shift+esc, no win+e, no nothing).

As an added optional bonus the user should be logged off when the launched app is closed and/or crashes.

Any existing free tool, language or any mixture of them that gets the job done would be fine (batch, VB-script, C, C++, whatever)

[A]
I guess you're building a windows kiosk?
Here's some background in replacing the windows login shell -
http://blogs.msdn.com/embedded/archive/2005/03/30/403999.aspx
The above link talks about using IE as the replacement, but any program can be used.
Also check out Windows Steady State -
http://www.microsoft.com/windows/products/winfamily/sharedaccess/default.mspx


q:
I have some code which collects points (consed integers) from a loop which looks something like this:

(loop
    for x from 1   to     100
    for y from 100 downto 1
        collect `(,x . ,y))

My question is, is it correct to use `(,x . ,y) in this situation?

Edit: This sample is not about generating a table of 100x100 items, the code here just illustrate the use of two loop variables and the consing of their values. I have edited the loop to make this clear. The actual loop I use depends on several other functions (and is part of one itself) so it made more sense to replace the calls with literal integers and to pull the loop out of the function.

[A]
Why not just
```
```
(cons x y)
```
```
By the way, I tried to run your code in CLISP and it didn't work as expected. Since I'm not a big fan of the loop macro here's how you might accomplish the same thing recursively:
```
```
(defun genint (stop)
  (if (= stop 1) '(1)
      (append (genint (- stop 1)) (list stop))))

(defun genpairs (x y)
  (let ((row (mapcar #'(lambda (y)
                        (cons x y))
                        (genint y))))
    (if (= x 0) row
        (append (genpairs (- x 1) y)
                row))))

(genpairs 100 100)
```
```


q: I have Flex Builder 3 installed on two Windows machines and the same project on both of them. On one computer, the CSS styles I defined are shown in design view; on the other computer they are not applied. Is there any reason why it might not work on one?


q:
When I run a Flex application in the debug flash player I get an exception pop up as soon as something unexpected happened. However when a customer uses the application he does not use the debug flash player. In this case he does not get an exception pop up, but he UI is not working.

So for supportability reasons, I would like to catch any exception that can happen anywhere in the Flex UI and present an error message in a Flex internal popup. By using Java I would just encapsulate the whole UI code in a try/catch block, but with MXML applications in Flex I do not know, where I could perform such a general try/catch.

[A]
There is no way to be notified on uncaught exceptions in Flex 3. Adobe are aware of the problem but I don't know if they plan on creating a workaround.
The only solution as it stands is to put try/catch in logical places and make sure you are listening to the ERROR (or FAULT for webservices) event for anything that dispatches them.
Edit:
Furthermore, it's actually impossible to catch an error thrown from an event handler. I have logged a
bug
on the Adobe Bug System.
Update 2010-01-12:
Global error handling is now supported in
Flash 10.1
and
AIR 2.0
(both in beta), and is achieved by subscribing the
UNCAUGHT_ERROR
event of
LoaderInfo.uncaughtErrorEvents
. The following code is taken from the
code sample on livedocs
:
```
```
public class UncaughtErrorEventExample extends Sprite
{
    public function UncaughtErrorEventExample()
    {
        loaderInfo.uncaughtErrorEvents.addEventListener(
            UncaughtErrorEvent.UNCAUGHT_ERROR, uncaughtErrorHandler);
    }

    private function uncaughtErrorHandler(event:UncaughtErrorEvent):void
    {
        if (event.error is Error)
        {
            var error:Error = event.error as Error;
            // do something with the error
        }
        else if (event.error is ErrorEvent)
        {
            var errorEvent:ErrorEvent = event.error as ErrorEvent;
            // do something with the error
        }
        else
        {
            // a non-Error, non-ErrorEvent type was thrown and uncaught
        }
    }
```
```


q:
The above error message comes up just before SQL Server marks the database as "Suspect" and refuses to open it. Does anyone know what the message means and how to fix it? I think it's a matter of grabbing the backup, but would be nice if it was possible to recover the data.

I've had a look at the kb article but there are no transactions to resolve.

[A]
It appears that it means your distributed transaction coordinator failed to start correctly when bringing the SQL Server online.
please refer to this
ASP.NET forum post
and
knowledge base article
Depending on the level of logging, you should be able to take the last known backup and slowly recover the logs using point in time recovery techniques to slowly bring the database up to the point right before failure began.


q: How do I get an element or element list by it's tag name. Take for example that I want all elements from <h1></h1>.

[A]
document.getElementsByTagName('a') returns an array. Look here for more information:
http://web.archive.org/web/20120511135043/https://developer.mozilla.org/en/DOM/element.getElementsByTagName
Amendment: If you want a real array, you should use something like
```
Array.from(document.getElementsByTagName('a'))
```
, or these days you'd probably want
```
Array.from(document.querySelectorAll('a'))
```
. Maybe polyfill
```
Array.from()
```
if your browser does not support it yet. I can recommend
https://polyfill.io/v2/docs/
very much (not affiliated in any way)


q:
I've got an application that uses a hibernate(annotations)/mysql combination for ORM. In that application, I got an entity with a Date field. I'm looking for a way to select on that date within a time range (so hh:mm:ss without the date part).

In MySQL there's a function TIME(expression) that can extract the time part and use that in the where clause, but that does not seem to be available in Hibernate without switching to native queries. Is there an option in hibernate to do this, or should I loop through the results in java and do the comparison there? Would this be much slower as the MySQL solution, since that would not use indexes anyway?

[A]
The following functions are available in HQL, maybe you could use them:
```
second(...), minute(...), hour(...), day(...), month(...), year(...)
```


q: I need to write a module to detect similar documents. I have read many papers of fingerprints of documents techniques and others, but I do not know how to write code or implement such a solution. The algorithm should work for Chinese, Japanese, English and German language or be language independent. How can I accomplish this?

[A]
You can use or at last study
difflib
from Python's stdlib to write your code.
It is very flexible, and has algorithms to find differences between lists of strings, and to point these differences. Then you can use the
```
get_close_matches()
```
to find similar words:
```
```
>>> get_close_matches('appel', ['ape', 'apple', 'peach', 'puppy'])
['apple', 'ape']
```
```
It is not the solution but maybe it is a start.


q: Is there a setting in ReSharper 4 (or even Visual Studio itself...) that forces a warning if I forget to wrap code in a using block, or omit the proper Dispose call in a finally block?

[A]
Correct automatic Dispose analysis requires DFA (Data Flow Analysis) in a global way. It is unlikely that you create an IDisposable object and doesn't call any method on it and do not pass it around as an argument. If disposable object is passed to other methods (including calling its members, when "this" is implicitly passed), the tool should analyse if Dispose is not called within, or that object is not stored somewhere for later disposal.
That said, naive implementation of checking if disposable object is in fact disposed with "using" construct or in any other way would yield too much false positives, and render analysis useless.


q:
Let's say I have this code:

if (md5($_POST[$foo['bar']]) == $somemd5) {
  doSomethingWith(md5($_POST[$foo['bar']]);
}

I could shorten that down by doing:

$value = md5($_POST[$foo['bar']];
if ($value == $somemd5) {
  doSomethingWith($value);
}

But is there any pre-set variable that contains the first or second condition of the current if? Like for instance:

if (md5($_POST[$foo['bar']]) == $somemd5) {
  doSomethingWith($if1);
}

May be a unnecessary way of doing it, but I'm just wondering.

[A]
No, but since the assignment itself is an expression, you can use the assignment as the conditional expression for the if statement.
```
if (($value = md5(..)) == $somemd5) { ... }
```
In general, though, you'll want to avoid embedding assignments into conditional expressions:
The code is denser and therefore harder to read, with more nested parentheses.
Mixing = and == in the same expression is just asking for them to get mixed up.


q: What are the best continuous integration frameworks/projects for Perl and why?

[A]
The only one I've seen in action is
Smolder
(it is used for
parrot
). It is TAP based and therefore integrates well with standard perl testing structures. See also this
presentation
.


q:
When I run indent with various options I want against my source, it does what I want but also messes with the placement of *s in pointer types:

  -int send_pkt(tpkt_t* pkt, void* opt_data);
  -void dump(tpkt_t* bp);
  +int send_pkt(tpkt_t * pkt, void *opt_data);
  +void dump(tpkt * bp);

I know my placement of *s next to the type not the variable is unconventional but how can I get indent to just leave them alone? Or is there another tool that will do what I want?  I've looked in the man page, the info page, and visited a half a dozen pages that Google suggested and I can't find an option to do this.

I tried Artistic Style (a.k.a. AStyle) but can't seem to figure out how to make it indent in multiples of 4 but make every 8 a tab.  That is:

if ( ... ) {
<4spaces>if ( ... ) {
<tab>...some code here...
<4spaces>}
}

[A]
Uncrustify
Uncrustify has several options on how to indent your files.
From the config file:
```
indent_with_tabs
  How to use tabs when indenting code
  0=spaces only
  1=indent with tabs, align with spaces
  2=indent and align with tabs
```
You can find it
here
.
BCPP
From the website:
"bcpp indents C/C++ source programs, replacing tabs with spaces or the reverse. Unlike indent, it does (by design) not attempt to wrap long statements."
Find it
here
.
UniversalIndentGUI
It's a tool which supports several beautifiers / formatters. It could lead you to even more alternatives.
Find it
here
.
Artistic Style
You could try
Artistic Style aka AStyle
instead (even though it doesn't do what you need it to do, I'll leave it here in case someone else finds it useful).


q:
Take this code:

<?php
if (isset($_POST['action']) && !empty($_POST['action'])) {
    $action = $_POST['action'];
}

if ($action) {
    echo $action;
}
else {
    echo 'No variable';
}
?>

And then access the file with ?action=test
Is there any way of preventing $action from automatically being declared by the GET? Other than of course adding

&& !isset($_GET['action'])

Why would I want the variable to be declared for me?

[A]
Check your php.ini for the
```
register_globals
```
setting. It is probably on, you want it off.
Why would I want the variable to be declared for me?
You don't.
It's a horrible security risk. It makes the Environment, GET, POST, Cookie and Server variables global
(PHP manual)
. These are a handful of
reserved variables
in PHP.


q: Is there any easy to install/use (on unix) database migration tools like Rails Migrations? I really like the idea, but installing ruby/rails purely to manage my database migrations seems overkill.

[A]
I haven't personally done it, but it should be possible to use ActiveRecord::Migration without any of the other Rails stuff.  Setting up the load path correctly would be the hard part, but really all you need is the
```
rake
```
tasks and the
```
db/migrate
```
directory plus whatever Rails gems they depend on, probably
```
activerecord
```
,
```
actviesupport
```
and maybe a couple others like
```
railties
```
.  I'd try it and just see what classes are missing and add those in.
At a previous company we built a tool that did essentially what ActiveRecord::Migration does, except it was written in Java as a Maven plugin.  All it did was assemble text blobs of SQL scripts.  It just needs to be smart about the filenames going in order and know how to update a versioning table.


q: How can I add Page transitions effects like IE in Safari for web pages?

[A]
You could check out this example:
http://sachiniscool.blogspot.com/2006/01/implementing-page-transitions-in.html
. It describes how to emulate page transitions in Firefox using AJAX and CSS. The same method works for Safari as well. The code below is taken from that page and slightly formatted:
```
```
var xmlhttp;
var timerId = 0;
var op = 1;

function getPageFx() {
  url = "/transpage2.html";
  if (window.XMLHttpRequest) {
    xmlhttp = new XMLHttpRequest()
    xmlhttp.onreadystatechange=xmlhttpChange
    xmlhttp.open("GET",url,true)
    xmlhttp.send(null)
  } else getPageIE();
}

function xmlhttpChange() {
// if xmlhttp shows "loaded"
  if (xmlhttp.readyState == 4) {
  // if "OK"
    if (xmlhttp.status == 200) {
      if (timerId != 0)
        window.clearTimeout(timerId);
        timerId = window.setTimeout("trans();",100);
    } else {
       alert(xmlhttp.status)
    }
  }
}

function trans() {
  op -= .1;
  document.body.style.opacity = op;
  if(op < .4) {
    window.clearTimeout(timerId);
    timerId = 0; document.body.style.opacity = 1;
    document.open();
    document.write(xmlhttp.responseText);
    document.close();
    return;
  }
  timerId = window.setTimeout("trans();",100);
}

function getPageIE() {
  window.location.href = "transpage2.html";
}
```
```


q:
I've just created my first Preview 5 error and it doesn't seem to place nice with Resharper.  All the C# in the Views are coming up with errors, things like <%= Html.Password("currentPassword") %> has the "currentPassword" highlighted with the following error: Argument type "System.String" is not assignable parameter type "string".

IList errors = ViewData["errors"] as IList; has the IList highlighted as "Can not resole symbol 'string'"

Has anyone seen this?

[A]
Did you try
latest nightly build
of ReSharper 4.1? In some cases the bug in 4.1 manifests itself with numerous ambiguity errors, and it has been fixed within the follow up build.


q:
What tools are there for me to build a real, honest to goodness external DSL. And no, I'm not talking about abusing Ruby, Boo, XML or another existing language or syntax, I mean a REAL external DSL -- my own language for my own purposes.

I know that there are a few language workbenches being developed and I've heard about things like "Irony" for .NET.  And, of course, there's ANTLR, Lex/Yaac, etc but I'm afraid those are too complicated for what I'm trying to do.

Please talk about a DSL builder tool you may have used or heard about and your impressions on how it helps and what its downsides are.

[A]
You should really check out
Ragel
. It's a framework to embed state machines in your regular source code. Ragel supports C, C++, Objective-C, D, Java and Ruby.
Ragel's great for writing file and protocol parsers as well as stepping through external DSL stuff. Chiefly because it allows you to execute any kind of code on state transitions and such.
A couple of notable projects that use Ragel are,
Mongrel
, a great ruby web server. And
Hpricot
, a ruby based html-parser, sort of inspired by jQuery.
Another great feature of Ragel is how it can generate
graphviz
-based charts that visualize your state machines. Below is an example taken from
Zed Shaw's
article on ragel state charts
.


q: Is there a way (without installing any libraries) of validating XML using a custom DTD in PHP?

[A]
Take a look at
PHP's DOM
, especially
DOMDocument::schemaValidate
and
DOMDocument::validate
.
The example for DOMDocument::validate is fairly simple:
```
```
<?php
$dom = new DOMDocument;
$dom->Load('book.xml');
if ($dom->validate()) {
    echo "This document is valid!\n";
}
?>
```
```


q:
I am trying to develop a .NET Web Project using NHibernate and Spring.NET, but I'm stuck. Spring.NET seems to depend on different versions of the NHibernate assemblies (maybe it needs 1.2.1.4000 and my NHibernate version is 1.2.0.4000).

I had originally solved similar problems using the "bindingRedirect" tag, but now even that stopped working.

Is there any simple solution to resolve these inter-library relations?

[A]
I too ran into this, frustrated I just grabbed the Spring source and compiled it against the latest NHibernate to make it go away forever.  Not sure if that's an option for you but the 10 minutes that took seems to have saved me a lot of time overall.
Here's the SourceForge link for the Spring Source for all versions:
Spring Source


q:
The default 64 MB max heap memory can be small for a large Java application. Are there any applet parameter to increment this for a signed applet?

For a Java program this is a simple command line parameter but how this work for an applet in the browser.

[A]
Not that I know for certain, it's been a long time since I wrote applets, but I don't think you can set this from the applet.
Apparently, you can set the JVM's heap size for the browser's JVM from the Java plug-in control panel, but that's something the user has to do before starting your applet.
You can always check
http://forums.sun.com/thread.jspa?threadID=523105&messageID=3033288
for more discussion on the topic.


q: In C++, when is it best to use the stack? When is it best to use the heap?

[A]
Use the heap for only allocating space for objects at runtime. If you know the size at compile time, use the stack. Instead of returning heap-allocated objects from a function, pass a buffer into the function for it to write to. That way the buffer can be allocated where the function is called as an array or other stack-based structure.
The fewer malloc() statements you have, the fewer chances for memory leaks.


q:
With previous versions of flash, entering the full screen mode increased the height and width of the stage to the dimensions of the screen.  Now that hardware scaling has arrived, the height and width are set to the dimensions of the video (plus borders if the aspect ratio is different).

That's fine, unless you have controls placed over the video.  Before, you could control their size; but now they're blown up by the same scale as the video, and pixellated horribly.  Controls are ugly and subtitles are unreadable.

It's possible for the user to turn off hardware scaling, but all that achieves is to turn off anti-aliasing.  The controls are still blown up to ugliness.

Is there a way to get the old scaling behaviour back?

[A]
```
```
stage.align     = StageAlign.TOP_LEFT;
stage.scaleMode = StageScaleMode.NO_SCALE;
stage.addEventListener(Event.RESIZE, onStageResize);

function onStageResize(event:Event):void {
    //do whatever you want to re-position your controls and scale the video
    // here's an example
    myFLVPlayback.width = stage.stageWidth;
    myFLVPlayback.height = stage.stageHeight - controls.height;
    controls.y = stage.stageHeight - controls.height;
}
```
```
Or, and I'm not entirely sure about this, you might try to do some 9 slice scaling on the FLVPlayback, but I don't know if that'll work.
9-slice scaling tutorial:
http://www.sephiroth.it/tutorials/flashPHP/scale9/


q: Is there a tutotial or help file, suitable for a beginner c# programmer to use.

[A]
Andy Beaulieu has beein doing a lot of work to make Farseer easier to use in Silverlight, you can read about it here:
http://www.andybeaulieu.com/Home/tabid/67/EntryID/115/Default.aspx


q: How to add child rows in datagrid c#.net windows forms?

[A]
I'm not sure if this is what you're asking, but if you want to append rows you're easiest way is to append them to whatever DataSource you're using before you DataBind()
If this wasn't what you're after, please provide more detail.


q: Sorry, I'm new to SVN and I looked around a little for this. How do you mark a major version in SVN, kind of like set up a restore point. Right now I just setup my server and added all my files- I've been intermittently committing different changes. When I have something in a stable state is there a way to mark this so I can easily revert back to it if necessary?

[A]
Sounds like you're looking for tags.
Tags in the Subversion book
"A tag is just a “snapshot” of a project in time"


q:
I'm looking for a method that computes the line number of a given text position in a JTextPane with wrapping enabled.

Example:

This a very very very very very very very very very very very very very very very very very very very very very very long line.

  This is another very very very very very very very very very very very very very very very very very very very very very very long line.|

The cursor is on line number four, not two.

Can someone provide me with the implementation of the method:

int getLineNumber(JTextPane pane, int pos)
{
     return ???
}

[A]
Try this
```
```
/**
   * Return an int containing the wrapped line index at the given position
   * @param component JTextPane
   * @param int pos
   * @return int
   */
  public int getLineNumber(JTextPane component, int pos)
  {
    int posLine;
    int y = 0;

    try
    {
      Rectangle caretCoords = component.modelToView(pos);
      y = (int) caretCoords.getY();
    }
    catch (BadLocationException ex)
    {
    }

    int lineHeight = component.getFontMetrics(component.getFont()).getHeight();
    posLine = (y / lineHeight) + 1;
    return posLine;
  }
```
```


q:
Is there a way to "align" columns in a data repeater control?

I.E currently it looks like this:

user1 - colA colB colC colD colE
user2 - colD colE

I want it to look like:

  user1
   -colA
   -colB
   -colC
   -colD
   -colE

   user1

   -colD
   -colE

I need to columns for each record to align properly when additional
records might not have data for a given column.

The requirements call for a repeater and not a grid control.

Any ideas?

[A]
If you have access to how many columns are mising in the repeat, then just the following as the table tag.  I you don't have access to this, can you post the source for your data repeater and what DataSource you're going against?
```
```
<td colspan='<%# MissingCount(Contatiner.DataItem) %>'>
```
```


q: Can I determine from an ASP.NET application the transfer rate, i.e. how many KB per second are transferd?

[A]
There are a number of debugging tools you can use to check this at the browser.  It will of course vary by page, cache settings, server load, network connection speed, etc.
Check out
http://www.fiddlertool.com/fiddler/
Or if you are using Firefox, the FireBug add-in
http://addons.mozilla.org/en-US/firefox/addon/1843


q:
What is the best way to add "Expires" in http header for static content? eg. images, css, js

The web server is IIS 6.0; the language is classical ASP

[A]
I don't know if this is what you are looking for, but it does keep my pages from being cached.
```
```
<META HTTP-EQUIV="Pragma" CONTENT="no-cache">
<META HTTP-EQUIV="Cache-Control" CONTENT="no-store">
<META HTTP-EQUIV="Cache-Control" CONTENT="no-cache">
<META HTTP-EQUIV="Expires" CONTENT="0">
<META HTTP-EQUIV="Cache-Control" CONTENT="max-age=0">
```
```
I got these from an article on line that I no longer have a reference for.


q:
I'd like to add a drop-down list to a Windows application.  It will have two choices, neither of which are editable.  What's the best control to use?  Is it a combo box with the editing property set to No?

I'm using Visual Studio 2008.

[A]
```
yourComboBox.DropDownStyle = ComboBoxStyle.DropDownList
```


q:
I have a strange problem on a PeopleSoft application.   It appears that integration broker messages are being processed out of order.   There is another possibility, and that is that the commit is being fired asynchronously, allowing the transactions to complete out of order.

There are many inserts of detail records, followed by a trailer record which performs an update on the rows just inserted.   Some of the rows are not receiving the update.  This problem is sporadic, about once every 6 months, but it causes statistically significant financial reporting errors.

I am hoping that someone has had enough dealings with the internals of PeopleTools to know what it is up to, so that perhaps I can find a work around to the problem.

[A]
You don't mentioned whether you've set this or not, but you have a choice with Integration Broker.  All messages flow through message channels, and a channel can either be ordered or unordered.  If a channel is ordered then - if a message errors - all subsequent messages queue up behind it and will not be processed until it succeeds.
Whether a channel is ordered or not depends upon the checkbox on the message channel properties in Application Designer.  From memory channels are ordered by default, but you can uncheck the box to increase throughput.
Hope this helps.
PS. As of Tools 8.49 the setup changed slightly, Channels became Queues, Messages Service Operations etc.


q:
Does full trust mean the same as Run As Administrator?  I have read things stating that "for this to work, the application must be a full-trust application."  Is that the same as you must have administrator privileges to run the application?  If not, what's the difference?  How can you tell if an app is "full-trust"?

I am told that "Administrator or not, .Net apps won't do certain things if they aren't running from a 'trusted' location."  What is a "trusted location"?  If you run an app from a "trusted location", can you do things that "require full-trust" without being an administrator?

[A]
No.  As of version 2.0, the .Net framework has it's own little filesystem setup for security.  Administrator or not, .Net apps won't do certain things if they aren't running from a 'trusted' location.
Just about anything on your local hard drive is trusted, but (and supposedly they fixed this for 3.5sp1) even the local intranet is
not
trusted, so most .Net desktop apps will fail to even start if they're sitting on a network drive or share.
You can change the configuration on a machine so it will allow apps from that zone, but it has to be done for
every
machine that's going to run the application, which breaks a common corporate deployment scenario.
From an ASP.Net standpoint, it also means that certain activities require more 'trust' than others.  Sending e-mail, for example, can cause exceptions if not set up correctly.


q: What would be the best WPF control in C# (VS 2008) that you can place on a form that would allow you to do drawing similar to the "Paint" function for the CWnd class in C++?  Also, that could display bitmaps, have a scroll bar, and the ability to accept user inputs (ie. MouseMove, Button Clicks, etc...).  Basically all the functionality of a CWnd in a control on a WPF form?


q:
I have two tables Organisation and Employee having one to many relation i.e one organisation can have multiple employees. Now I want to select all information of a particular organisation plus first name of all employees for this organisation. What’s the best way to do it? Can I get all of this in single record set or I will have to get multiple rows based on no. of employees? Here is a bit graphical demonstration of what I want:

Org_ID      Org_Address    Org_OtherDetails    Employess

1           132A B Road    List of details     Emp1, Emp2, Emp3.....

[A]
If you use Oracle you can create a PL/SQL function you can use in your query that accepts an organization_id as input, and returns the first name of all employees belonging to that org as a string. For example:-
```
```
select
   o.org_id,
   o.org_address,
   o.org_otherdetails,
   org_employees( o.org_id ) as org_employees
from
   organization o
```
```


q:
I have a need to open a popup detail window from a gridview (VS 2005 / 2008).  What I am trying to do is in the markup for my TemplateColumn have an asp:Button control, sort of like this:

<asp:Button ID="btnShowDetails" runat="server" CausesValidation="false"
   CommandName="Details" Text="Order Details"
   onClientClick="window.open('PubsOrderDetails.aspx?OrderId=<%# Eval("order_id") %>',
   '','scrollbars=yes,resizable=yes, width=350, height=550');"

Of course, what isn't working is the appending of the <%# Eval...%> section to set the query string variable.

Any suggestions?  Or is there a far better way of achieving the same result?

[A]
I believe the way to do it is
```
```
onClientClick=<%# string.Format("window.open('PubsOrderDetails.aspx?OrderId={0}',scrollbars=yes,resizable=yes, width=350, height=550);", Eval("order_id")) %>
```
```


q:
I'm building an install using VS 2003. The install has an Excel workbook and two Access databases. I need to force the Access files to load regardless of the create/mod date of the existing databases on the user's computer. I currently use ORCA to force in a Version number on the two files, but would like to find a simpler, more elegant solution (hand editing a .msi file is not something I see as "best practice".

Is there a way to add a version number to the databases using Access that would then be used in the install?

Is there a better way for me to do this?

[A]
Since it sounds like you don't have properly versioned resources, have you tried changing the REINSTALLMODE property?
IIRC, in the default value of 'omus', it's the 'o' flag that's only allowing you to install if you have an older version.  You may try changing this from 'o' to 'e'.  Be warned that this will overwrite missing, older AND equally versioned files.
Manually adding in versions was the wrong way to start, but this should ensure that you don't have to manually bump up the version numbers to get them to install.


q:
I have just installed a build server with a 64 bit windows server 2008 for continuous integration.

The reason I choose a 64 bit server was to have more than ~3Gb of RAM. I had hopes that this machine would provide blazing fast builds.

Unfortunately, the result are lacking greatly to say the least. My desktop provides faster builds than this server equipped with a Xeon quad core, 15k RPM SAS and 8 Gigs of RAM.

We use Visual C++ 2005 to compile our 32 bit application with Cygwin.

Could the WOW64 emulator be the bottleneck that is slowing down the build process?

Any pointers, comments would be greatly appreciated.

Regards,


q: I am trying to sort a dict based on its key and return an iterator to the values from within an overridden iter method in a class. Is there a nicer and more efficient way of doing this than creating a new list, inserting into the list as I sort through the keys?

[A]
By far the easiest approach, and almost certainly the fastest, is something along the lines of:
```
```
def sorted_dict(d):
    keys = d.keys()
    keys.sort()
    for key in keys:
        yield d[key]
```
```
You can't sort without fetching all keys. Fetching all keys into a list and then sorting that list is the most efficient way to do that; list sorting is very fast, and fetching the keys list like that is as fast as it can be. You can then either create a new list of values or yield the values as the example does. Keep in mind that you can't modify the dict if you are iterating over it (the next iteration would fail) so if you want to modify the dict before you're done with the result of sorted_dict(), make it return a list.


q:
I am looking for a .NET implementation of a priority queue or heap data structure

Priority queues are data structures that provide more flexibility than simple sorting, because they allow new elements to enter a system at arbitrary intervals. It is much more cost-effective to insert a new job into a priority queue than to re-sort everything on each such arrival.

The basic priority queue supports three primary operations:

Insert(Q,x). Given an item x with key k, insert it into the priority queue Q.

Find-Minimum(Q). Return a pointer to the item
  whose key value is smaller than any other key in the priority queue
  Q.

Delete-Minimum(Q). Remove the item from the priority queue Q whose key is minimum

Unless I am looking in the wrong place, there isn't one in the framework. Is anyone aware of a good one, or should I roll my own?

[A]
I like using the
```
OrderedBag
```
and
```
OrderedSet
```
classes in
PowerCollections
as priority queues.


q:
Given an existing valid SVG document, what's the best way to create "informational popups", so that when you hover or click on certain elements (let's say ) you popup a box with an arbitrary amount (i.e. not just a single line tooltip) of extra information?

This should display correctly at least in Firefox and be invisible if the image was rasterized to a bitmap format.

[A]
```
```
<svg>
  <text id="thingyouhoverover" x="50" y="35" font-size="14">Mouse over me!</text>
  <text id="thepopup" x="250" y="100" font-size="30" fill="black" visibility="hidden">Change me
    <set attributeName="visibility" from="hidden" to="visible" begin="thingyouhoverover.mouseover" end="thingyouhoverover.mouseout"/>
  </text>
</svg>
```
```
Further explanation can be found
here
.